@prplkane/roundtable 0.6.4 → 0.6.6

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/CHANGELOG.md CHANGED
@@ -1,5 +1,41 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.6
4
+
5
+ - Keep MCP wait deadlines and caller cancellation connected on Node 22 when
6
+ garbage collection runs while an idle event stream is open.
7
+
8
+ - Use the public `@prplkane/agentlink` package for optional ACP seats, including
9
+ shell-free Windows npm launch resolution. Document the qualified beta version.
10
+
11
+ - Bind ACP session IDs while receiving `session/new` so a foreign-session update
12
+ coalesced with that reply is rejected before prompting. Update the offline peer
13
+ to return the correct v2 initialization fields when probed by AgentLink.
14
+
15
+ - Add AgentLink (ACP) seats and chairman profiles through standard ACP v1 stdio,
16
+ without runtime dependencies. Keep bridge management in AgentLink and existing
17
+ direct CLI adapters available. Each call uses a fresh isolated seat session.
18
+ - Deny ACP client tools, stop reported tool activity, preserve missing usage,
19
+ and propagate cancellation with process cleanup. Refuse unsupported session
20
+ resume, effort and model overrides instead of inventing compatibility.
21
+ - Test complete reviews, profile selection, chairman fallback, malformed output,
22
+ authentication failure, tool denial and cancellation with offline fake agents.
23
+
24
+ ## 0.6.5
25
+
26
+ ### Agent API
27
+
28
+ - Say who wrote each answer: every answer to `roundtable_answer` or `agent answer` takes
29
+ `from: "user"` or `from: "assistant"`, and a missing `from` counts as `assistant`. A submission made
30
+ only of the user's own answers reaches the board as "You said, via your assistant", and the
31
+ seats and the exported record as the human's answer relayed by the assistant; anything else
32
+ stays an agent note whose answer lines say whose words they are. The declaration is the
33
+ assistant's and is shown, not verified.
34
+ - Deadlines readable without arithmetic: `deadlineAt` and `gate.autoContinueAt` (epoch
35
+ milliseconds) now come with `deadlineAtIso`, `secondsUntilDeadline`, `autoContinueAtIso`
36
+ and `secondsUntilAutoContinue`; `roundtable_hold` returns the same pair for the renewed
37
+ window.
38
+
3
39
  ## 0.6.4
4
40
 
5
41
  ### Terminal
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 prplkane
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 prplkane
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -12,6 +12,12 @@ supports the same workflow for agents and scripts.
12
12
  Usage statistics describe your own agents' calls in Roundtable and stay on your machine.
13
13
  Roundtable has no telemetry or analytics service and sends no usage data to its developers.
14
14
 
15
+ You can also choose **AgentLink (ACP)** for seats and the chairman, then enter a saved
16
+ AgentLink profile name. Roundtable speaks standard ACP to the centrally installed
17
+ launcher; AgentLink owns bridge installation and updates. This path uses stateless
18
+ memory and has the selected profile's permissions and billing. See
19
+ [AgentLink setup and limits](docs/workflow.md#7c-agentlink-acp-profiles-optional).
20
+
15
21
  **Requirements:** Node.js 22 or newer. No runtime dependencies. Live reviews use installed
16
22
  Claude, Codex or Antigravity CLIs, or an OpenAI-compatible endpoint for a local or hosted model.
17
23
 
@@ -117,7 +123,7 @@ page. Refreshing the browser alone does not load an updated server or model list
117
123
 
118
124
  | Control | Behavior |
119
125
  | --- | --- |
120
- | Answer questions | Add context before the discussion continues. Agent notes and your notes are labelled separately. |
126
+ | Answer questions | Add context before the discussion continues. Your notes, answers your assistant relayed for you, and the assistant's own notes are labelled separately. |
121
127
  | Finish with verdict | End the discussion and request a recommendation from the completed replies. Available after a usable round. |
122
128
  | Stop | Cancel the discussion and any active chairman call. Saved replies and reported usage remain. |
123
129
  | Delete / Clear | Remove finished and interrupted history while protecting running sessions. Exports and local usage statistics are retained. |
package/SECURITY.md CHANGED
@@ -1,10 +1,29 @@
1
1
  # Security
2
2
 
3
- Roundtable runs a loopback server on your machine. Live debates use the vendor CLIs you
4
- installed or API endpoints you explicitly configure; demo mode uses scripted replies.
3
+ Roundtable runs a loopback server on your machine. Live debates use the vendor CLIs,
4
+ AgentLink ACP profiles or API endpoints you explicitly configure; demo mode uses
5
+ scripted replies.
5
6
 
6
7
  ## Data and execution
7
8
 
9
+ - **ACP profiles are trusted local executables, not sandboxes.** Roundtable launches
10
+ the installed AgentLink with a validated saved profile name. Executable overrides
11
+ come only from the server's environment, never review JSON. Each turn creates a
12
+ fresh ACP v1 session in a separate seat directory, advertises no client tools and
13
+ supplies no MCP servers. Permission requests are denied; filesystem/terminal
14
+ callbacks and reported tool activity stop the seat. The client binds the session
15
+ ID while receiving `session/new`, before processing any following frame, and
16
+ rejects foreign-session updates. Agents can still have their own built-in tools,
17
+ permissions, customizations and billing configuration. Use a
18
+ profile with those tools disabled and explicitly accept limited isolation. This
19
+ does not acknowledge a vendor's terms or guarantee its sandbox. Inherited API keys
20
+ are filtered as for direct CLIs, but AgentLink profile settings can add them back.
21
+ ACP output, including stderr, is bounded to 8 MiB per call. Roundtable sends
22
+ `session/cancel` on interruption and closes the connection, with process-tree
23
+ termination after a bounded grace period. Already-orphaned Windows descendants
24
+ are not guaranteed to be contained. Tokens are unknown unless valid optional
25
+ end-turn counters are reported; existing seat/vendor budget rules still apply.
26
+
8
27
  - **No telemetry or analytics service.** Usage statistics describe your own agents' calls in
9
28
  Roundtable. They are calculated and stored on your machine; Roundtable sends no usage
10
29
  statistics, review text or diagnostic logs to its developers. Live reviews still send the
package/docs/workflow.md CHANGED
@@ -837,6 +837,94 @@ What is different from a CLI seat:
837
837
  The chairman can be an endpoint too; its card takes the same fields. The decision record
838
838
  names the endpoint on each seat's line (`API http://localhost:11434/v1`) and on the chairman's.
839
839
 
840
+ ## 7c. AgentLink ACP profiles (optional)
841
+
842
+ [AgentLink](https://github.com/prplkane/agentlink) manages existing agent CLI/ACP
843
+ bridges in one place. Configure profiles there once. In Roundtable, choose
844
+ **AgentLink (ACP)** on each seat and the chairman, and enter its saved profile name.
845
+ The project uses the profile name; it does not install or copy the vendor bridge.
846
+
847
+ Install the qualified public beta once:
848
+
849
+ ```sh
850
+ npm install -g @prplkane/agentlink@0.3.0-beta.1
851
+ ```
852
+
853
+ With AgentLink installed globally, Roundtable launches `agentlink acp PROFILE`.
854
+ On Windows it resolves the npm script through Node, without a shell. For source
855
+ checkouts, set the absolute path once in the shell that starts Roundtable:
856
+
857
+ ```powershell
858
+ $env:ROUNDTABLE_AGENTLINK_CLI = 'C:\code\agentlink\src\cli.mjs'
859
+ node src/server.js
860
+ ```
861
+
862
+ On Linux/macOS use `export ROUNDTABLE_AGENTLINK_CLI=/absolute/path/agentlink/src/cli.mjs`.
863
+ `AGENTLINK_HOME`, if set in that shell, selects the shared AgentLink store. Otherwise
864
+ AgentLink uses its normal user store. The launcher override is local configuration;
865
+ a review request cannot supply executable paths or arguments.
866
+
867
+ For the JSON client, `vendor: "acp"` selects this connection and `account` names the
868
+ AgentLink profile. For ACP this field is not a Roundtable login directory:
869
+
870
+ ```json
871
+ {
872
+ "fieldNotes": { "decision": "Which rollout should we choose?", "options": ["Small trial", "Wait"] },
873
+ "seats": [
874
+ { "vendor": "acp", "account": "codex", "lens": "risk" },
875
+ { "vendor": "acp", "account": "claude", "lens": "cost" }
876
+ ],
877
+ "chairman": { "vendor": "acp", "account": "codex" },
878
+ "options": { "memory": "stateless", "critiqueRounds": 1, "allowLimitedIsolation": true }
879
+ }
880
+ ```
881
+
882
+ Save this as your own review JSON, then use `node src/cli.js agent check --input FILE`
883
+ and `node src/cli.js agent start --input FILE`. Check validates the request; it does
884
+ not start an agent. Start can make model calls. Follow the normal wait/answer flow
885
+ through a ready chairman verdict.
886
+
887
+ The initial integration deliberately has these limits:
888
+
889
+ - **ACP v1 and text reviews.** Each turn gets a fresh process/session in its seat's
890
+ isolated working directory. The session is bound as its creation response arrives,
891
+ so even a following update in the same stdout chunk must belong to that session.
892
+ `memory: resume` is refused. No AgentLink library,
893
+ daemon, package installation or discovery is loaded into Roundtable.
894
+ - **Profile-owned permissions and billing.** Roundtable advertises no filesystem
895
+ or terminal capabilities, supplies no MCP servers, denies permission requests,
896
+ and stops a seat on reported tool calls. ACP is not a sandbox and cannot disable
897
+ tools or customizations inside the agent. Use a trusted profile configured with
898
+ its own tools disabled. The board shows this limit; JSON clients must explicitly
899
+ accept it with `allowLimitedIsolation`. Check the selected vendor's applicable
900
+ terms separately. The direct adapters' vendor-specific restrictions do not apply
901
+ to an arbitrary ACP profile. Profile environment settings can select API billing.
902
+ - **Agent defaults remain defaults.** Leave Model empty, or supply a model ID
903
+ advertised in the session's standard model configuration options. Unadvertised
904
+ model overrides fail before a prompt. Reasoning preferences stay with the profile;
905
+ Roundtable does not guess effort flags or a safe mode from their names.
906
+ - **Usage is optional.** Roundtable reads the existing experimental
907
+ [end-turn usage field](https://docs.rs/agent-client-protocol/latest/agent_client_protocol/schema/v1/struct.PromptResponse.html#structfield.usage)
908
+ only when its counters and total agree. Missing/invalid usage remains unknown,
909
+ and the existing seat cap blocks that seat's next call, including a repair or
910
+ critique. The chairman may still summarize usable replies. ACP context occupancy
911
+ is not spending. No live subscription quota is inferred; dollar caps are refused.
912
+ An explicit `acp` token budget covers all ACP profiles in the review.
913
+ - **Login stays with the agent.** Sign in through the vendor's own flow. Authentication
914
+ errors identify that step; Roundtable does not open a login terminal automatically.
915
+ The readiness lamp checks the launcher only. Use `agentlink check PROFILE` to
916
+ check initialization; a successful check does not prove task compatibility.
917
+ - **Updates are central.** An explicit `agentlink bridge update NAME` changes new
918
+ connections, including the next Roundtable turn. In-flight connections retain
919
+ their AgentLink lease. There is no automatic update during connection startup.
920
+
921
+ `npm test` exercises the ACP client with a local fake peer. With both source
922
+ checkouts, run `node scripts/test-roundtable.mjs /absolute/path/to/roundtable`
923
+ **from AgentLink** for the real gateway integration. It starts an isolated local
924
+ Roundtable server with vendor discovery disabled, creates temporary managed fake
925
+ bridges, completes a two-round review and chairman verdict, updates the bridge,
926
+ and tests cancellation and missing usage. It never uses a real vendor account.
927
+
840
928
  ## 8. Run a debate without the browser
841
929
 
842
930
  ### Optional searcher before discussion
@@ -980,8 +1068,10 @@ When `nextAction.type` is `ask_user`, the coordinator must actually ask `gate.qu
980
1068
  1. Use the host's available question/input tool. If there is no form, ask in normal chat.
981
1069
  Combine overlapping questions when useful, while retaining their IDs. A raw JSON dump
982
1070
  alone is not the question handoff.
983
- 2. Tell the person when `gate.autoContinueAt` expires and that the review will continue with
984
- unanswered facts still unknown. Use only supplied facts; do not fill missing answers yourself.
1071
+ 2. Tell the person when the answer window closes: `gate.secondsUntilAutoContinue` is the whole
1072
+ seconds left and `gate.autoContinueAtIso` the same moment as an ISO timestamp
1073
+ (`autoContinueAt` is epoch milliseconds). The review will continue with unanswered facts
1074
+ still unknown. Use only supplied facts; do not fill missing answers yourself.
985
1075
  3. If the person needs more time, send `agent hold --id <review-id> --input file` with
986
1076
  `{ "round": 0 }`. This renews the configured answer window, bounded by the wall clock.
987
1077
  Do not use it as a background keepalive. `nextAction.extend` provides the command and input.
@@ -995,10 +1085,15 @@ When `nextAction.type` is `ask_user`, the coordinator must actually ask `gate.qu
995
1085
 
996
1086
  `nextAction.answerTemplate` and `nextAction.command` give the answer shape and agent subcommand.
997
1087
  Prefix subcommands with `node src/cli.js` from a checkout, or `roundtable` when installed.
998
- Use the current question IDs and round number in an answer file:
1088
+ Use the current question IDs and round number in an answer file. Each answer says who wrote it:
1089
+ `from: "user"` for the person's own reply, `from: "assistant"` for one the agent supplied with the
1090
+ person's permission (the default when `from` is omitted). A submission made only of the person's
1091
+ own answers, with no `message`, reaches the board, the seats and the exported record as the
1092
+ human's answer relayed by the assistant; anything else is an agent note whose answer lines say
1093
+ whose words they are. The declaration is the agent's own and is shown, not verified:
999
1094
 
1000
1095
  ```json
1001
- { "round": 0, "answers": [{ "id": "q1", "text": "The deadline can move by a week." }], "message": "Keep the trial reversible." }
1096
+ { "round": 0, "answers": [{ "id": "q1", "text": "The deadline can move by a week.", "from": "user" }] }
1002
1097
  ```
1003
1098
 
1004
1099
  ```bash
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prplkane/roundtable",
3
- "version": "0.6.4",
3
+ "version": "0.6.6",
4
4
  "description": "Local decision reviews with coding-agent CLIs, human input, budget checks and Markdown records.",
5
5
  "keywords": [
6
6
  "claude",
package/scripts/mcp.mjs CHANGED
@@ -33,8 +33,10 @@ const descriptors = [
33
33
  ['check', 'Validate a proposed review and estimate its calls/tokens before starting. Makes no model call.', object({ review }, ['review']), true],
34
34
  ['start', 'Start the requested Roundtable review after check. Makes model calls within its limits. Returns an id, NOT a recommendation; keep calling wait through the chairman.', object({ review }, ['review']), false],
35
35
  ['wait', 'Wait up to 25 seconds for questions or completion. A wait timeout is progress, not completion. After showing questions, pass afterRound to await the next step without repeating them.', object({ id, seconds: integer(LIMITS.waitSeconds), afterRound: round }, ['id']), true],
36
- ['answer', 'Submit only the user\'s real answers to the current round; read status first. May resume model calls. Silence is handled by the timer, not blank answers.', object({ id, round,
37
- answers: { type: 'array', maxItems: LIMITS.answers, items: object({ id: text(LIMITS.questionId), text: text(LIMITS.answer) }, ['id', 'text']) }, message: text(LIMITS.message) }, ['id', 'round']), false],
36
+ ['answer', 'Submit the user\'s real answers to the current round; read status first. Each answer says who wrote it: from "user" for the user\'s own reply, from "assistant" when you supplied it with the user\'s permission (also what a missing from means). The board and the seats see that declaration. May resume model calls. Silence is handled by the timer, not blank answers.', object({ id, round,
37
+ answers: { type: 'array', maxItems: LIMITS.answers, items: object({ id: text(LIMITS.questionId), text: text(LIMITS.answer),
38
+ from: { type: 'string', enum: ['user', 'assistant'], description: 'user: the user\'s own words, relayed. assistant: your own answer, given with the user\'s permission. Omitted counts as assistant.' } }, ['id', 'text']) },
39
+ message: text(LIMITS.message) }, ['id', 'round']), false],
38
40
  ['hold', 'Give the user another bounded answer window when they need more time. No model call. Never use as an automatic keepalive.', object({ id, round }, ['id', 'round']), false],
39
41
  ['finish', 'On the user\'s request, end discussion and call the chairman with collected replies. Keep waiting for the verdict.', object({ id, message: text(LIMITS.message) }, ['id']), false],
40
42
  ['stop', 'Cancel this review, including an in-flight chairman, when the user asks to stop. Does not synthesize a recommendation.', object({ id, message: text(LIMITS.message) }, ['id']), false],
@@ -33,7 +33,9 @@ one-time `roundtable setup --client codex` (or `claude` / `agy`) step.
33
33
  job sets `options.unattended: true`; an attended chat or browser review leaves it false.
34
34
  4. Keep using `roundtable_wait` through discussion and chairman synthesis. At `ask_user`,
35
35
  present the supplied questions using the host's available input tool, or normal chat.
36
- Include the deadline and explain that silence continues with unanswered facts unknown.
36
+ Include when the window closes (`gate.secondsUntilAutoContinue`) and explain that silence
37
+ continues with unanswered facts unknown. Send the user's reply with `from: "user"` on each
38
+ answer; an answer you supply yourself, with the user's permission, carries `from: "assistant"`.
37
39
  Keep question IDs when combining questions. Never fabricate or submit blank answers to
38
40
  move the review along. The server owns auto-continue; reading does not extend it.
39
41
  5. After presenting a question, asynchronous hosts wait with `afterRound` set to that round.
@@ -0,0 +1,201 @@
1
+ // Standard ACP v1 over stdio. AgentLink owns profiles/installations; Roundtable owns
2
+ // the review, fresh seat sessions, deadlines and denial of client-side tools.
3
+ import { spawn } from 'node:child_process';
4
+ import { mkdirSync, existsSync } from 'node:fs';
5
+ import path from 'node:path';
6
+ import { cleanEnv, resolveBinary, registerCall, killTree } from './spawn.js';
7
+ import { agentLinkProfile } from '../seats.js';
8
+ import { VERSION } from '../version.js';
9
+
10
+ const LIMIT = 8 * 1024 * 1024;
11
+ const fault = (message, code = 'PROVIDER_PROTOCOL', kind = 'other') => Object.assign(new Error(message), { code, kind });
12
+ const policy = () => Object.assign(fault('ACP agent requested or reported prohibited tool activity. This seat is stopped for the review.', 'TOOL_POLICY', 'policy'), { usedTools: true });
13
+ const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
14
+
15
+ // This local launch override is read only from the server's environment, never a
16
+ // review request. It supports source checkouts and avoids Windows .cmd execution.
17
+ export function agentLinkBinary(env = process.env) {
18
+ const script = env.ROUNDTABLE_AGENTLINK_CLI;
19
+ if (script) {
20
+ if (!path.isAbsolute(script) || !existsSync(script)) throw fault('ROUNDTABLE_AGENTLINK_CLI must name an existing absolute AgentLink CLI script.', 'ENOENT', 'missing');
21
+ return { file: process.execPath, prefix: [script] };
22
+ }
23
+ try { return resolveBinary('agentlink', ['@prplkane/agentlink', 'src/cli.mjs'], { env }); }
24
+ catch { throw fault('AgentLink is not installed. Run npm install -g @prplkane/agentlink@beta, or set ROUNDTABLE_AGENTLINK_CLI to its absolute src/cli.mjs path.', 'ENOENT', 'missing'); }
25
+ }
26
+
27
+ // Optional ACP end-turn usage is still experimental. Fresh sessions avoid the
28
+ // deployed turn-vs-session ambiguity. Context-window `used` is never spending.
29
+ // Accept inclusive or additive cache counts only when the reported total agrees.
30
+ export function promptUsage(value, cost, ms) {
31
+ if (!record(value)) return null;
32
+ const count = (n) => Number.isSafeInteger(n) && n >= 0;
33
+ const { inputTokens: input, outputTokens: output, totalTokens: total } = value;
34
+ const cacheRead = value.cachedReadTokens ?? 0, cacheWrite = value.cachedWriteTokens ?? 0, thinking = value.thoughtTokens ?? 0;
35
+ if (![input, output, total, cacheRead, cacheWrite, thinking].every(count)) return null;
36
+ let uncached;
37
+ if (total === input + output && input >= cacheRead + cacheWrite) uncached = input - cacheRead - cacheWrite;
38
+ else if (total === input + output + cacheRead + cacheWrite) uncached = input;
39
+ else return null;
40
+ return { input: uncached, output, cacheRead, cacheWrite, thinking, cost, ms, usageVersion: 3 };
41
+ }
42
+
43
+ function connect(bin, profile, { cwd, env, signal, onUpdate }) {
44
+ const child = spawn(bin.file, [...bin.prefix, 'acp', profile], {
45
+ cwd, env, windowsHide: true, detached: process.platform !== 'win32', stdio: ['pipe', 'pipe', 'pipe'],
46
+ });
47
+ let next = 0, pendingText = '', bytes = 0, failure, closed = false, closing = false, sessionId;
48
+ const pending = new Map();
49
+ const send = (message) => { if (!closed && child.stdin.writable) child.stdin.write(JSON.stringify({ jsonrpc: '2.0', ...message }) + '\n'); };
50
+ const cancel = () => { if (sessionId) send({ method: 'session/cancel', params: { sessionId } }); };
51
+ const fail = (error) => {
52
+ if (failure) return;
53
+ failure = error;
54
+ cancel();
55
+ for (const p of pending.values()) p.reject(error);
56
+ pending.clear();
57
+ };
58
+ const aborted = () => fail(signal.reason || fault('ACP call cancelled.', 'KILLED', 'killed'));
59
+ const exit = new Promise((resolve) => child.once('close', () => {
60
+ closed = true;
61
+ if (pendingText.trim()) fail(fault('ACP stdout ended with an incomplete JSON-RPC frame.'));
62
+ if (!closing) fail(fault('ACP process exited before the call completed. Run agentlink check for this profile.', 'CLI_EXIT'));
63
+ resolve();
64
+ }));
65
+ child.on('error', (e) => fail(fault(`Could not launch AgentLink (${e.code || 'spawn error'}).`, e.code || 'CLI_EXIT', 'missing')));
66
+ child.stdin.on('error', () => { if (!closing) fail(fault('ACP input closed before the call completed.', 'CLI_EXIT')); });
67
+ function receive(message) {
68
+ if (!record(message) || message.jsonrpc !== '2.0') throw fault('Invalid ACP JSON-RPC envelope.');
69
+ if (Object.hasOwn(message, 'method')) {
70
+ if (typeof message.method !== 'string') throw fault('Invalid ACP method.');
71
+ if (Object.hasOwn(message, 'id')) {
72
+ if (message.method === 'session/request_permission') {
73
+ send({ id: message.id, result: { outcome: { outcome: 'cancelled' } } });
74
+ throw policy();
75
+ }
76
+ send({ id: message.id, error: { code: -32601, message: 'Roundtable does not provide client tools.' } });
77
+ if (/^(fs\/|terminal\/)/.test(message.method)) throw policy();
78
+ } else if (message.method === 'session/update') {
79
+ const { params } = message;
80
+ if (!record(params) || !record(params.update) || typeof params.sessionId !== 'string') throw fault('Invalid ACP session update.');
81
+ if (['tool_call', 'tool_call_update'].includes(params.update.sessionUpdate)) throw policy();
82
+ if (sessionId && params.sessionId !== sessionId) throw fault('ACP update belongs to another session.');
83
+ if (sessionId) onUpdate(params.update);
84
+ }
85
+ return;
86
+ }
87
+ if (!Object.hasOwn(message, 'id') || Object.hasOwn(message, 'result') === Object.hasOwn(message, 'error')) throw fault('Invalid ACP response.');
88
+ const p = pending.get(message.id);
89
+ if (!p) throw fault('ACP response has an unknown request ID.');
90
+ pending.delete(message.id);
91
+ if (message.error) {
92
+ const auth = message.error.code === -32000;
93
+ p.reject(fault(auth ? 'ACP authentication is required. Sign in using the agent vendor login flow, then check the AgentLink profile.'
94
+ : `ACP request failed: ${String(message.error.message || 'unknown error').slice(0, 500)}`, 'CLI_FAILURE', auth ? 'auth' : 'other'));
95
+ } else if (!record(message.result)) p.reject(fault('ACP response result must be an object.'));
96
+ else {
97
+ // Bind at the receive boundary: the next frame can be in this same chunk,
98
+ // before the awaiting session/new caller gets a chance to resume.
99
+ if (p.method === 'session/new' && typeof message.result.sessionId === 'string') sessionId = message.result.sessionId;
100
+ p.resolve(message.result);
101
+ }
102
+ }
103
+ const accountBytes = (d) => {
104
+ bytes += Buffer.byteLength(d);
105
+ if (bytes > LIMIT) { fail(fault('ACP output exceeded the local size limit.', 'OUTPUT_LIMIT')); return false; }
106
+ return !failure;
107
+ };
108
+ child.stderr.on('data', accountBytes); // diagnostics are bounded, never copied into review records
109
+ child.stdout.setEncoding('utf8').on('data', (d) => {
110
+ if (!accountBytes(d)) return;
111
+ pendingText += d;
112
+ try {
113
+ let i;
114
+ while ((i = pendingText.indexOf('\n')) >= 0) {
115
+ const line = pendingText.slice(0, i); pendingText = pendingText.slice(i + 1);
116
+ if (line.trim()) receive(JSON.parse(line));
117
+ if (failure) break;
118
+ }
119
+ } catch (e) { fail(e instanceof SyntaxError ? fault('ACP stdout contained invalid JSON.') : e); }
120
+ });
121
+ signal.addEventListener('abort', aborted, { once: true });
122
+ if (signal.aborted) aborted();
123
+ return {
124
+ setSession(id) { sessionId = id; },
125
+ check() { if (failure) throw failure; },
126
+ request(method, params) {
127
+ if (failure) return Promise.reject(failure);
128
+ const id = ++next;
129
+ return new Promise((resolve, reject) => { pending.set(id, { resolve, reject, method }); send({ id, method, params }); });
130
+ },
131
+ async close() {
132
+ closing = true;
133
+ signal.removeEventListener('abort', aborted);
134
+ if (!closed) {
135
+ child.stdin.end();
136
+ // Leave time for AgentLink's own bridge cleanup and lease release.
137
+ const timer = setTimeout(() => killTree(child), 2000);
138
+ try { await exit; } finally { clearTimeout(timer); }
139
+ }
140
+ },
141
+ };
142
+ }
143
+
144
+ export function makeAcpAdapter({ bin, env: suppliedEnv } = {}) {
145
+ return async (prompt, previousSession = null, opts = {}) => {
146
+ const profile = agentLinkProfile(opts.account);
147
+ if (!opts.allowLimitedIsolation) throw fault('ACP profiles control their own permissions and customization. Accept limited isolation before using this profile.', 'ISOLATION_REQUIRED', 'policy');
148
+ if (previousSession || opts.keepSession) throw fault('ACP seats currently require stateless memory; no previous session was loaded.', 'ACP_STATELESS_REQUIRED');
149
+ if (opts.research) throw fault('ACP seats do not support Roundtable web research.', 'ACP_UNSUPPORTED');
150
+ if (opts.effort) throw fault('Set reasoning preferences in the AgentLink profile; this ACP client does not override effort.', 'ACP_UNSUPPORTED');
151
+ const cwd = opts.cwd;
152
+ if (!cwd || !path.isAbsolute(cwd)) throw fault('ACP seats need an absolute, isolated working directory.');
153
+ mkdirSync(cwd, { recursive: true });
154
+ const env = cleanEnv(null, { source: suppliedEnv || process.env });
155
+ const launch = bin || agentLinkBinary(env);
156
+ const call = registerCall(opts.tag);
157
+ const timeout = new AbortController();
158
+ const timer = setTimeout(() => timeout.abort(fault('ACP call timed out.', 'TIMEOUT', 'timeout')), opts.timeoutMs ?? 300_000);
159
+ const signal = AbortSignal.any([call.signal, timeout.signal, ...(opts.signal ? [opts.signal] : [])]);
160
+ const started = Date.now();
161
+ let text = '', cost = null, activePrompt = false;
162
+ let connection;
163
+ try {
164
+ if (signal.aborted) throw signal.reason;
165
+ connection = connect(launch, profile, { cwd, env, signal, onUpdate: (update) => {
166
+ if (!activePrompt) return;
167
+ if (update.sessionUpdate === 'agent_message_chunk') {
168
+ if (update.content?.type !== 'text' || typeof update.content.text !== 'string') throw fault('ACP review replies must contain text.');
169
+ text += update.content.text;
170
+ } else if (update.sessionUpdate === 'usage_update' && update.cost?.currency === 'USD' && Number.isFinite(update.cost.amount) && update.cost.amount >= 0) cost = update.cost.amount;
171
+ } });
172
+ const init = await connection.request('initialize', { protocolVersion: 1, clientCapabilities: {}, clientInfo: { name: 'roundtable', version: VERSION } });
173
+ if (init.protocolVersion !== 1) throw fault('This Roundtable client requires ACP v1; the agent negotiated an incompatible protocol.', 'ACP_UNSUPPORTED');
174
+ const session = await connection.request('session/new', { cwd, mcpServers: [] });
175
+ if (typeof session.sessionId !== 'string' || !session.sessionId) throw fault('ACP agent did not return a session ID.');
176
+ connection.setSession(session.sessionId);
177
+ if (opts.model) {
178
+ const option = Array.isArray(session.configOptions) && session.configOptions.find((o) => o?.type === 'select' && (o.category === 'model' || (!o.category && o.id === 'model')));
179
+ const choices = Array.isArray(option?.options) ? option.options.flatMap((o) => Array.isArray(o?.options) ? o.options : [o]).filter(record) : [];
180
+ if (!option || !choices.some((o) => o.value === opts.model)) throw fault('The ACP agent did not advertise this model. Use its default or an advertised model ID.', 'ACP_UNSUPPORTED');
181
+ await connection.request('session/set_config_option', { sessionId: session.sessionId, configId: option.id, value: opts.model });
182
+ }
183
+ activePrompt = true;
184
+ const result = await connection.request('session/prompt', { sessionId: session.sessionId, prompt: [{ type: 'text', text: prompt }] });
185
+ connection.check();
186
+ if (result.stopReason !== 'end_turn') throw fault(`ACP turn did not complete (${String(result.stopReason || 'missing stop reason')}).`, result.stopReason === 'cancelled' ? 'KILLED' : 'CLI_FAILURE', result.stopReason === 'cancelled' ? 'killed' : 'other');
187
+ if (!text.trim()) throw fault('ACP agent completed without a text answer.');
188
+ await connection.close();
189
+ connection.check();
190
+ const ms = Date.now() - started;
191
+ return { text, usage: promptUsage(result.usage, cost, ms), cost, ms, sessionId: session.sessionId, usedTools: false };
192
+ } catch (e) {
193
+ throw Object.assign(e, { usage: null, cost, ms: Date.now() - started });
194
+ } finally {
195
+ clearTimeout(timer);
196
+ try { await connection?.close(); } finally { call.release(); }
197
+ }
198
+ };
199
+ }
200
+
201
+ export const run = makeAcpAdapter();
@@ -1,7 +1,7 @@
1
- // Antigravity CLI: `agy --output-format json -p=<prompt>`, `--conversation <id>` to resume.
2
- // Quirks: `-p` needs its value attached (`-p=...`) and stdin is ignored in that mode; for long
3
- // prompts common.js switches to --input-format stream-json, where each stdin line is
4
- // {"event":"user","message":{"role":"user","content":...}} and the last stdout line is
5
- // {"event":"result","result":{...same shape as --output-format json...}}. No cost reported.
6
- import { makeAdapter } from './common.js';
7
- export const run = makeAdapter('agy');
1
+ // Antigravity CLI: `agy --output-format json -p=<prompt>`, `--conversation <id>` to resume.
2
+ // Quirks: `-p` needs its value attached (`-p=...`) and stdin is ignored in that mode; for long
3
+ // prompts common.js switches to --input-format stream-json, where each stdin line is
4
+ // {"event":"user","message":{"role":"user","content":...}} and the last stdout line is
5
+ // {"event":"result","result":{...same shape as --output-format json...}}. No cost reported.
6
+ import { makeAdapter } from './common.js';
7
+ export const run = makeAdapter('agy');
@@ -1,6 +1,6 @@
1
- // Claude Code: `claude -p --output-format stream-json --verbose`, prompt on stdin, `--resume <id>`.
2
- // Quirks: total_cost_usd is cumulative for the session on resume; common.js takes the delta.
3
- // stream-json is used only so the rate_limit_event line (remaining quota) comes with each reply.
4
- import { makeAdapter } from './common.js';
5
- import { claudeQuota } from './quota.js';
6
- export const run = makeAdapter('claude', { normaliseQuota: claudeQuota });
1
+ // Claude Code: `claude -p --output-format stream-json --verbose`, prompt on stdin, `--resume <id>`.
2
+ // Quirks: total_cost_usd is cumulative for the session on resume; common.js takes the delta.
3
+ // stream-json is used only so the rate_limit_event line (remaining quota) comes with each reply.
4
+ import { makeAdapter } from './common.js';
5
+ import { claudeQuota } from './quota.js';
6
+ export const run = makeAdapter('claude', { normaliseQuota: claudeQuota });
@@ -1,6 +1,6 @@
1
- // Codex: `codex exec --json`, prompt on stdin (`-`), `exec resume <id>`.
2
- // Quirks: usage comes in the turn.completed event, no cost; `resume` rejects --sandbox so the
3
- // policy is passed with -c sandbox_mode; the PATH entry is an npm .cmd shim, so spawn.js runs
4
- // bin/codex.js through node instead.
5
- import { makeAdapter } from './common.js';
6
- export const run = makeAdapter('codex');
1
+ // Codex: `codex exec --json`, prompt on stdin (`-`), `exec resume <id>`.
2
+ // Quirks: usage comes in the turn.completed event, no cost; `resume` rejects --sandbox so the
3
+ // policy is passed with -c sandbox_mode; the PATH entry is an npm .cmd shim, so spawn.js runs
4
+ // bin/codex.js through node instead.
5
+ import { makeAdapter } from './common.js';
6
+ export const run = makeAdapter('codex');
@@ -422,11 +422,21 @@ export const ADAPTERS = {
422
422
  colour: 'steel',
423
423
  readOnly: 'no tools in the request',
424
424
  },
425
+ acp: {
426
+ kind: 'acp', label: 'AgentLink (ACP)', binary: 'agentlink',
427
+ npmBin: ['@local/agentlink', 'src/cli.mjs'],
428
+ args: [], resume: null, model: null, effort: null, home: null,
429
+ effortLevels: [], modelHints: [], paths: { cost: null, quota: null },
430
+ quota: null, usageUrl: null, colour: 'dusk', limitedIsolation: true,
431
+ pool: 'Selected AgentLink profile; billing and quota belong to its agent',
432
+ isolation: 'fresh ACP sessions in separate working directories; profile-owned tools and customization are not sandboxed',
433
+ readOnly: 'client tools denied; reported tool activity stops the seat; configure the profile agent to disable its own tools',
434
+ },
425
435
  };
426
436
 
427
437
  // A vendor whose seats draw on separate pools per account: a CLI with a state directory
428
438
  // (named login profiles), or an endpoint vendor (one pool per host). Pool keys (seats.poolKey)
429
439
  // carry the account only for these.
430
- export const poolsByAccount = (a) => !!a?.home || a?.kind === 'api';
440
+ export const poolsByAccount = (a) => !!a?.home || a?.kind === 'api' || a?.kind === 'acp';
431
441
 
432
442
  export const ARGV_LIMIT = 24000;
@@ -2,10 +2,11 @@ import { run as claude } from './claude.js';
2
2
  import { run as codex } from './codex.js';
3
3
  import { run as agy } from './agy.js';
4
4
  import { run as api } from './endpoint.js';
5
+ import { run as acp } from './acp.js';
5
6
  import { ADAPTERS, poolsByAccount } from './config.js';
6
7
  import { readCodexQuota, readAgyQuota, readClaudeQuota } from './quota.js';
7
8
 
8
- export const adapters = { claude, codex, agy, api };
9
+ export const adapters = { claude, codex, agy, api, acp };
9
10
  // Vendors whose quota needs a separate read (no model call). The others ride on replies or have none.
10
11
  export const quotaReaders = { claude: readClaudeQuota, codex: readCodexQuota, agy: readAgyQuota };
11
12
  export { ADAPTERS, poolsByAccount };