@prplkane/roundtable 0.7.0 → 0.8.0

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.
@@ -1,318 +1,381 @@
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 os from 'node:os';
7
- import { mkdtemp, rm } from 'node:fs/promises';
8
- import { cleanEnv, resolveBinary, registerCall, killTree, runProcess } from './spawn.js';
9
- import { agentLinkProfile } from '../seats.js';
10
- import { VERSION } from '../version.js';
11
-
12
- const LIMIT = 8 * 1024 * 1024;
13
- const fault = (message, code = 'PROVIDER_PROTOCOL', kind = 'other') => Object.assign(new Error(message), { code, kind });
14
- 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 });
15
- const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
16
-
17
- // This local launch override is read only from the server's environment, never a
18
- // review request. It supports source checkouts and avoids Windows .cmd execution.
19
- export function agentLinkBinary(env = process.env) {
20
- const script = env.ROUNDTABLE_AGENTLINK_CLI;
21
- if (script) {
22
- if (!path.isAbsolute(script) || !existsSync(script)) throw fault('ROUNDTABLE_AGENTLINK_CLI must name an existing absolute AgentLink CLI script.', 'ENOENT', 'missing');
23
- return { file: process.execPath, prefix: [script] };
24
- }
25
- try { return resolveBinary('agentlink', ['@prplkane/agentlink', 'src/cli.mjs'], { env }); }
26
- 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'); }
27
- }
28
-
29
- // Publish only picker metadata. AgentLink's raw inventory can contain launch arguments and environment settings.
30
- const optionId = (id) => typeof id === 'string' && id.length > 0 && id.length <= 200 && !/[\u0000-\u001f\u007f]/.test(id);
31
- function savedDefaults(row) {
32
- return Object.fromEntries(['model', 'effort'].filter((key) => optionId(row?.[key])).map((key) => [key, row[key]]));
33
- }
34
- export async function listProfiles(launch = {}) {
35
- const env = cleanEnv(null, { source: launch.env || process.env });
36
- const bin = launch.bin || agentLinkBinary(env);
37
- const result = await runProcess(bin, ['list', '--json'], { env, timeoutMs: 5000, maxOutputBytes: 2 * 1024 * 1024 });
38
- if (result.code !== 0) throw new Error('Could not list saved AgentLink profiles. Run agentlink list.');
39
- const rows = JSON.parse(result.stdout);
40
- if (!Array.isArray(rows)) throw new Error('AgentLink returned an unreadable profile list.');
41
- return rows.filter((p) => p && !p.error).map((p) => {
42
- const defaults = savedDefaults(p.defaults);
43
- return { name: agentLinkProfile(p.name), provider: typeof p.provider === 'string' ? p.provider : null,
44
- ...(Object.keys(defaults).length ? { defaults } : {}) };
45
- });
46
- }
47
-
48
- // Optional ACP end-turn usage is still experimental. Fresh sessions avoid the
49
- // deployed turn-vs-session ambiguity. Context-window `used` is never spending.
50
- // Accept inclusive or additive cache counts only when the reported total agrees.
51
- export function promptUsage(value, cost, ms) {
52
- if (!record(value)) return null;
53
- const count = (n) => Number.isSafeInteger(n) && n >= 0;
54
- const { inputTokens: input, outputTokens: output, totalTokens: total } = value;
55
- const cacheRead = value.cachedReadTokens ?? 0, cacheWrite = value.cachedWriteTokens ?? 0, thinking = value.thoughtTokens ?? 0;
56
- if (![input, output, total, cacheRead, cacheWrite, thinking].every(count)) return null;
57
- let uncached;
58
- if (total === input + output && input >= cacheRead + cacheWrite) uncached = input - cacheRead - cacheWrite;
59
- else if (total === input + output + cacheRead + cacheWrite) uncached = input;
60
- else return null;
61
- return { input: uncached, output, cacheRead, cacheWrite, thinking, cost, ms, usageVersion: 3 };
62
- }
63
-
64
- function connect(bin, profile, { cwd, env, signal, onUpdate }) {
65
- const child = spawn(bin.file, [...bin.prefix, 'acp', profile], {
66
- cwd, env, windowsHide: true, detached: process.platform !== 'win32', stdio: ['pipe', 'pipe', 'pipe'],
67
- });
68
- let next = 0, pendingText = '', bytes = 0, failure, closed = false, closing = false, sessionId;
69
- const pending = new Map();
70
- const send = (message) => { if (!closed && child.stdin.writable) child.stdin.write(JSON.stringify({ jsonrpc: '2.0', ...message }) + '\n'); };
71
- const cancel = () => { if (sessionId) send({ method: 'session/cancel', params: { sessionId } }); };
72
- const fail = (error) => {
73
- if (failure) return;
74
- failure = error;
75
- cancel();
76
- for (const p of pending.values()) p.reject(error);
77
- pending.clear();
78
- };
79
- const aborted = () => fail(signal.reason || fault('ACP call cancelled.', 'KILLED', 'killed'));
80
- const exit = new Promise((resolve) => child.once('close', () => {
81
- closed = true;
82
- if (pendingText.trim()) fail(fault('ACP stdout ended with an incomplete JSON-RPC frame.'));
83
- if (!closing) fail(fault('ACP process exited before the call completed. Run agentlink check for this profile.', 'CLI_EXIT'));
84
- resolve();
85
- }));
86
- child.on('error', (e) => fail(fault(`Could not launch AgentLink (${e.code || 'spawn error'}).`, e.code || 'CLI_EXIT', 'missing')));
87
- child.stdin.on('error', () => { if (!closing) fail(fault('ACP input closed before the call completed.', 'CLI_EXIT')); });
88
- function receive(message) {
89
- if (!record(message) || message.jsonrpc !== '2.0') throw fault('Invalid ACP JSON-RPC envelope.');
90
- if (Object.hasOwn(message, 'method')) {
91
- if (typeof message.method !== 'string') throw fault('Invalid ACP method.');
92
- if (Object.hasOwn(message, 'id')) {
93
- if (message.method === 'session/request_permission') {
94
- send({ id: message.id, result: { outcome: { outcome: 'cancelled' } } });
95
- throw policy();
96
- }
97
- send({ id: message.id, error: { code: -32601, message: 'Roundtable does not provide client tools.' } });
98
- if (/^(fs\/|terminal\/)/.test(message.method)) throw policy();
99
- } else if (message.method === 'session/update') {
100
- const { params } = message;
101
- if (!record(params) || !record(params.update) || typeof params.sessionId !== 'string') throw fault('Invalid ACP session update.');
102
- if (['tool_call', 'tool_call_update'].includes(params.update.sessionUpdate)) throw policy();
103
- if (sessionId && params.sessionId !== sessionId) throw fault('ACP update belongs to another session.');
104
- if (sessionId) onUpdate(params.update);
105
- }
106
- return;
107
- }
108
- if (!Object.hasOwn(message, 'id') || Object.hasOwn(message, 'result') === Object.hasOwn(message, 'error')) throw fault('Invalid ACP response.');
109
- const p = pending.get(message.id);
110
- if (!p) throw fault('ACP response has an unknown request ID.');
111
- pending.delete(message.id);
112
- if (message.error) {
113
- if (p.method === 'session/new' && ['OPTION_UNAVAILABLE', 'OPTION_UNCONFIRMED'].includes(message.error.data?.code)) {
114
- p.reject(fault(`AgentLink could not apply a saved default for ${profile}. Inspect choices with agentlink models ${profile} and update them with agentlink defaults ${profile}.`, 'ACP_UNSUPPORTED'));
115
- return;
116
- }
117
- const auth = message.error.code === -32000;
118
- p.reject(fault(auth ? 'ACP authentication is required. Sign in using the agent vendor login flow, then check the AgentLink profile.'
119
- : `ACP request failed: ${String(message.error.message || 'unknown error').slice(0, 500)}`, 'CLI_FAILURE', auth ? 'auth' : 'other'));
120
- } else if (!record(message.result)) p.reject(fault('ACP response result must be an object.'));
121
- else {
122
- // Bind at the receive boundary: the next frame can be in this same chunk,
123
- // before the awaiting session/new caller gets a chance to resume.
124
- if (p.method === 'session/new' && typeof message.result.sessionId === 'string') sessionId = message.result.sessionId;
125
- p.resolve(message.result);
126
- }
127
- }
128
- const accountBytes = (d) => {
129
- bytes += Buffer.byteLength(d);
130
- if (bytes > LIMIT) { fail(fault('ACP output exceeded the local size limit.', 'OUTPUT_LIMIT')); return false; }
131
- return !failure;
132
- };
133
- child.stderr.on('data', accountBytes); // diagnostics are bounded, never copied into review records
134
- child.stdout.setEncoding('utf8').on('data', (d) => {
135
- if (!accountBytes(d)) return;
136
- pendingText += d;
137
- try {
138
- let i;
139
- while ((i = pendingText.indexOf('\n')) >= 0) {
140
- const line = pendingText.slice(0, i); pendingText = pendingText.slice(i + 1);
141
- if (line.trim()) receive(JSON.parse(line));
142
- if (failure) break;
143
- }
144
- } catch (e) { fail(e instanceof SyntaxError ? fault('ACP stdout contained invalid JSON.') : e); }
145
- });
146
- signal.addEventListener('abort', aborted, { once: true });
147
- if (signal.aborted) aborted();
148
- return {
149
- setSession(id) { sessionId = id; },
150
- check() { if (failure) throw failure; },
151
- request(method, params) {
152
- if (failure) return Promise.reject(failure);
153
- const id = ++next;
154
- return new Promise((resolve, reject) => { pending.set(id, { resolve, reject, method }); send({ id, method, params }); });
155
- },
156
- async close() {
157
- closing = true;
158
- signal.removeEventListener('abort', aborted);
159
- if (!closed) {
160
- child.stdin.end();
161
- // Leave time for AgentLink's own bridge cleanup and lease release.
162
- const timer = setTimeout(() => killTree(child), 2000);
163
- try { await exit; } finally { clearTimeout(timer); }
164
- }
165
- },
166
- };
167
- }
168
-
169
- // A session's select-type config option by ACP category, or by id for an agent that labels
170
- // none, and the values it offers (flat, or grouped). Roundtable never invents a value: a model or
171
- // reasoning level is sent only when the agent advertised it for this session.
172
- function configOption(session, category, ids) {
173
- const selects = (Array.isArray(session.configOptions) ? session.configOptions : [])
174
- .filter((o) => o?.type === 'select' && typeof (o.configId ?? o.id) === 'string');
175
- return selects.find((o) => o.category === category) || selects.find((o) => !o.category && ids.includes(o.configId ?? o.id));
176
- }
177
- const optionValues = (option) => Array.isArray(option?.options) ? option.options.flatMap((o) => Array.isArray(o?.options) ? o.options : [o]).filter(record) : [];
178
- const MODEL = { category: 'model', ids: ['model'], what: 'model' };
179
- const EFFORT = { category: 'thought_level', ids: ['thought_level', 'effort', 'reasoning_effort', 'reasoning'], what: 'reasoning level' };
180
- const advertised = (session, option) => optionValues(configOption(session, option.category, option.ids));
181
- async function selectOption(connection, session, value, { category, ids, what }) {
182
- const option = configOption(session, category, ids);
183
- if (!option || !optionValues(option).some((o) => o.value === value)) throw fault(`The ACP agent did not advertise this ${what}. Use its default or an advertised ${what} ID.`, 'ACP_UNSUPPORTED');
184
- if (option.currentValue === value) return;
185
- const result = await connection.request('session/set_config_option', { sessionId: session.sessionId, configId: option.configId ?? option.id, value });
186
- session.configOptions = result.configOptions;
187
- if (configOption(session, category, ids)?.currentValue !== value) throw fault(`The ACP agent did not confirm the selected ${what}.`, 'ACP_UNSUPPORTED');
188
- }
189
-
190
- async function withProfile(prompt, previousSession, opts, { bin, env: suppliedEnv }, inspect) {
191
- const profile = agentLinkProfile(opts.account);
192
- if (!opts.allowLimitedIsolation) throw fault('ACP profiles control their own permissions and customization. Accept limited isolation before using this profile.', 'ISOLATION_REQUIRED', 'policy');
193
- if (previousSession || opts.keepSession) throw fault('ACP seats currently require stateless memory; no previous session was loaded.', 'ACP_STATELESS_REQUIRED');
194
- if (opts.research) throw fault('ACP seats do not support Roundtable web research.', 'ACP_UNSUPPORTED');
195
- const cwd = opts.cwd;
196
- if (!cwd || !path.isAbsolute(cwd)) throw fault('ACP seats need an absolute, isolated working directory.');
197
- mkdirSync(cwd, { recursive: true });
198
- const env = cleanEnv(null, { source: suppliedEnv || process.env });
199
- const launch = bin || agentLinkBinary(env);
200
- const call = registerCall(opts.tag);
201
- const timeout = new AbortController();
202
- const timer = setTimeout(() => timeout.abort(fault('ACP call timed out.', 'TIMEOUT', 'timeout')), opts.timeoutMs ?? 300_000);
203
- const signal = AbortSignal.any([call.signal, timeout.signal, ...(opts.signal ? [opts.signal] : [])]);
204
- const started = Date.now();
205
- let text = '', cost = null, activePrompt = false;
206
- let connection;
207
- try {
208
- if (signal.aborted) throw signal.reason;
209
- connection = connect(launch, profile, { cwd, env, signal, onUpdate: (update) => {
210
- if (!activePrompt) return;
211
- if (update.sessionUpdate === 'agent_message_chunk') {
212
- if (update.content?.type !== 'text' || typeof update.content.text !== 'string') throw fault('ACP review replies must contain text.');
213
- text += update.content.text;
214
- } else if (update.sessionUpdate === 'usage_update' && update.cost?.currency === 'USD' && Number.isFinite(update.cost.amount) && update.cost.amount >= 0) cost = update.cost.amount;
215
- } });
216
- const init = await connection.request('initialize', { protocolVersion: 1, clientCapabilities: {}, clientInfo: { name: 'roundtable', version: VERSION } });
217
- if (init.protocolVersion !== 1) throw fault('This Roundtable client requires ACP v1; the agent negotiated an incompatible protocol.', 'ACP_UNSUPPORTED');
218
- const session = await connection.request('session/new', { cwd, mcpServers: [] });
219
- if (typeof session.sessionId !== 'string' || !session.sessionId) throw fault('ACP agent did not return a session ID.');
220
- connection.setSession(session.sessionId);
221
- const hasModel = advertised(session, MODEL).some((o) => o.value === opts.model);
222
- if (opts.model && (!inspect || hasModel)) await selectOption(connection, session, opts.model, MODEL);
223
- if (inspect) {
224
- const models = advertised(session, MODEL).filter((o) => typeof o.value === 'string' && o.value.length <= 200)
225
- .map((o) => ({ id: o.value, label: typeof o.name === 'string' ? o.name : o.value }));
226
- const effortChoices = advertised(session, EFFORT).filter((o) => optionId(o.value))
227
- .map((o) => ({ id: o.value, label: typeof o.name === 'string' ? o.name : o.value }));
228
- await connection.close();
229
- connection.check();
230
- return { models, efforts: effortChoices.map((e) => e.id), effortChoices, effortModel: hasModel ? opts.model : '' };
231
- }
232
- if (opts.effort) await selectOption(connection, session, opts.effort, EFFORT);
233
- if (opts.model && configOption(session, MODEL.category, MODEL.ids)?.currentValue !== opts.model) {
234
- throw fault('The ACP agent changed the selected model while applying the reasoning level.', 'ACP_UNSUPPORTED');
235
- }
236
- activePrompt = true;
237
- const result = await connection.request('session/prompt', { sessionId: session.sessionId, prompt: [{ type: 'text', text: prompt }] });
238
- connection.check();
239
- 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');
240
- if (!text.trim()) throw fault('ACP agent completed without a text answer.');
241
- await connection.close();
242
- connection.check();
243
- const ms = Date.now() - started;
244
- return { text, usage: promptUsage(result.usage, cost, ms), cost, ms, sessionId: session.sessionId, usedTools: false };
245
- } catch (e) {
246
- throw Object.assign(e, { usage: null, cost, ms: Date.now() - started });
247
- } finally {
248
- clearTimeout(timer);
249
- try { await connection?.close(); } finally { call.release(); }
250
- }
251
- }
252
-
253
- export function makeAcpAdapter(launch = {}) {
254
- return (prompt, previousSession = null, opts = {}) => withProfile(prompt, previousSession, opts, launch, false);
255
- }
256
-
257
- // Explicit local setup action. The profile receives an empty workspace and no prompt.
258
- export async function inspectProfileSession(account, model = '', launch = {}) {
259
- agentLinkProfile(account);
260
- if (typeof model !== 'string' || model.length > 200) throw new Error('Model ID must be at most 200 characters.');
261
- const cwd = await mkdtemp(path.join(os.tmpdir(), 'roundtable-profile-'));
262
- try {
263
- return await withProfile(null, null, { account, model, cwd, timeoutMs: 20_000, allowLimitedIsolation: true }, launch, true);
264
- } finally {
265
- await rm(cwd, { recursive: true, force: true });
266
- }
267
- }
268
-
269
- // Unlike session/new, beta.3 management inspection ignores saved pins. A retired
270
- // central default must not prevent the picker from showing its replacements.
271
- async function modelReport(bin, env, account, model) {
272
- const args = ['models', account, '--json'];
273
- if (model) args.push('--model', model);
274
- const result = await runProcess(bin, args, { env, timeoutMs: 20_000 });
275
- if (result.code !== 0) {
276
- if (!model && /^INVALID_ARGUMENT: Unknown command\. Run agentlink --help\.\s*$/.test(result.stderr)) return null; // beta.2
277
- throw fault(`AgentLink could not inspect profile ${account}. Run agentlink models ${account} to check its connection.`, 'CLI_FAILURE');
278
- }
279
- let report;
280
- try { report = JSON.parse(result.stdout); } catch {}
281
- if (report?.name !== account || !['model', 'effort'].every((k) => report[k] === null || Array.isArray(report[k]?.choices))) {
282
- throw fault('AgentLink returned an unreadable model report.');
283
- }
284
- return report;
285
- }
286
-
287
- function namedChoices(selector) {
288
- return (selector?.choices || []).filter((o) => optionId(o?.id))
289
- .map(({ id, name }) => ({ id, label: typeof name === 'string' && name ? name : id }));
290
- }
291
-
292
- export async function discoverProfile(account, model = '', launch = {}) {
293
- account = agentLinkProfile(account);
294
- if (model !== '' && !optionId(model)) throw new Error('Choose a model ID of at most 200 characters.');
295
- const env = cleanEnv(null, { source: launch.env || process.env });
296
- const bin = launch.bin || agentLinkBinary(env);
297
- const base = await modelReport(bin, env, account);
298
- if (!base) return inspectProfileSession(account, model, launch);
299
- const defaults = savedDefaults(base.defaults);
300
- const models = namedChoices(base.model);
301
- const offers = (id) => models.some((m) => m.id === id);
302
- const profileModel = defaults.model || (optionId(base.model?.current) ? base.model.current : '');
303
- const effortModel = offers(model) ? model : '';
304
- const selected = effortModel || (offers(profileModel) ? profileModel : '');
305
- const detail = selected && selected !== base.model?.current ? await modelReport(bin, env, account, selected) : base;
306
- const effortChoices = namedChoices(detail.effort);
307
- const efforts = effortChoices.map((e) => e.id);
308
- const inheritsModel = !effortModel || effortModel === profileModel;
309
- const stale = defaults.model && !offers(defaults.model) || inheritsModel && defaults.effort && !efforts.includes(defaults.effort);
310
- // The inspector bypasses saved pins. After a seat overrides a centrally configured
311
- // model, only its actual session knows whether the provider retained or reset effort.
312
- const observedEffort = optionId(detail.effort?.current) ? detail.effort.current : '';
313
- const defaultEffort = inheritsModel ? defaults.effort || observedEffort : Object.keys(defaults).length ? '' : observedEffort;
314
- return { models, efforts, effortChoices, effortModel, defaults, profileModel, defaultEffort,
315
- ...(stale ? { warning: `A saved AgentLink default is unavailable. Choose a replacement with agentlink defaults ${account} before starting a review.` } : {}) };
316
- }
317
-
318
- export const run = makeAcpAdapter();
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 os from 'node:os';
7
+ import { mkdtemp, rm } from 'node:fs/promises';
8
+ import { cleanEnv, resolveBinary, registerCall, killTree, runProcess } from './spawn.js';
9
+ import { agentLinkProfile } from '../seats.js';
10
+ import { VERSION } from '../version.js';
11
+
12
+ const LIMIT = 8 * 1024 * 1024;
13
+ const SESSION_ACTION_MS = 1500;
14
+ const HISTORY_KEY = 'agentlink.dev/session-history';
15
+ const HISTORY_STRATEGIES = new Set(['ephemeral', 'archive-on-close', 'provider-managed']);
16
+ const fault = (message, code = 'PROVIDER_PROTOCOL', kind = 'other') => Object.assign(new Error(message), { code, kind });
17
+ const unsupportedHistory = (profile) => Object.assign(fault(`AgentLink profile ${profile} cannot confirm a non-saving session. Choose a compatible profile or change the provider chat history setting.`, 'ACP_UNSUPPORTED'), { status: 400 });
18
+ 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 });
19
+ const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
20
+
21
+ // This local launch override is read only from the server's environment, never a
22
+ // review request. It supports source checkouts and avoids Windows .cmd execution.
23
+ export function agentLinkBinary(env = process.env) {
24
+ const script = env.ROUNDTABLE_AGENTLINK_CLI;
25
+ if (script) {
26
+ if (!path.isAbsolute(script) || !existsSync(script)) throw fault('ROUNDTABLE_AGENTLINK_CLI must name an existing absolute AgentLink CLI script.', 'ENOENT', 'missing');
27
+ return { file: process.execPath, prefix: [script] };
28
+ }
29
+ try { return resolveBinary('agentlink', ['@prplkane/agentlink', 'src/cli.mjs'], { env }); }
30
+ 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'); }
31
+ }
32
+
33
+ // Publish only picker metadata. AgentLink's raw inventory can contain launch arguments and environment settings.
34
+ const optionId = (id) => typeof id === 'string' && id.length > 0 && id.length <= 200 && !/[\u0000-\u001f\u007f]/.test(id);
35
+ function savedDefaults(row) {
36
+ return Object.fromEntries(['model', 'effort'].filter((key) => optionId(row?.[key])).map((key) => [key, row[key]]));
37
+ }
38
+ export async function listProfiles(launch = {}) {
39
+ const env = cleanEnv(null, { source: launch.env || process.env });
40
+ const bin = launch.bin || agentLinkBinary(env);
41
+ const result = await runProcess(bin, ['list', '--json'], { env, timeoutMs: 5000, maxOutputBytes: 2 * 1024 * 1024 });
42
+ if (result.code !== 0) throw new Error('Could not list saved AgentLink profiles. Run agentlink list.');
43
+ const rows = JSON.parse(result.stdout);
44
+ if (!Array.isArray(rows)) throw new Error('AgentLink returned an unreadable profile list.');
45
+ return rows.filter((p) => p && !p.error).map((p) => {
46
+ const defaults = savedDefaults(p.defaults);
47
+ return { name: agentLinkProfile(p.name), provider: typeof p.provider === 'string' ? p.provider : null,
48
+ ...(Object.keys(defaults).length ? { defaults } : {}) };
49
+ });
50
+ }
51
+
52
+ // Optional ACP end-turn usage is still experimental. Fresh sessions avoid the
53
+ // deployed turn-vs-session ambiguity. Context-window `used` is never spending.
54
+ // Accept inclusive or additive cache counts only when the reported total agrees.
55
+ export function promptUsage(value, cost, ms) {
56
+ if (!record(value)) return null;
57
+ const count = (n) => Number.isSafeInteger(n) && n >= 0;
58
+ const { inputTokens: input, outputTokens: output, totalTokens: total } = value;
59
+ const cacheRead = value.cachedReadTokens ?? 0, cacheWrite = value.cachedWriteTokens ?? 0, thinking = value.thoughtTokens ?? 0;
60
+ if (![input, output, total, cacheRead, cacheWrite, thinking].every(count)) return null;
61
+ let uncached;
62
+ if (total === input + output && input >= cacheRead + cacheWrite) uncached = input - cacheRead - cacheWrite;
63
+ else if (total === input + output + cacheRead + cacheWrite) uncached = input;
64
+ else return null;
65
+ return { input: uncached, output, cacheRead, cacheWrite, thinking, cost, ms, usageVersion: 3 };
66
+ }
67
+
68
+ // Metadata may outlive the turn. A timeout never starts another model call.
69
+ function boundedAction(start) {
70
+ return new Promise(resolve => {
71
+ const timer = setTimeout(() => resolve(false), SESSION_ACTION_MS);
72
+ start(ok => { clearTimeout(timer); resolve(ok); });
73
+ });
74
+ }
75
+
76
+ function connect(bin, profile, { cwd, env, signal, providerHistory, onUpdate }) {
77
+ const child = spawn(bin.file, [...bin.prefix, 'acp', profile], {
78
+ cwd, env, windowsHide: true, detached: process.platform !== 'win32', stdio: ['pipe', 'pipe', 'pipe'],
79
+ });
80
+ let next = 0, pendingText = '', bytes = 0, failure, closed = false, closing = false, sessionId;
81
+ let capabilities = {}, strategy, history, openingId, finishOpening;
82
+ const pending = new Map();
83
+ const send = (message) => { if (!closed && child.stdin.writable) child.stdin.write(JSON.stringify({ jsonrpc: '2.0', ...message }) + '\n'); };
84
+ const cancel = () => { if (sessionId) send({ method: 'session/cancel', params: { sessionId } }); };
85
+ const fail = (error) => {
86
+ if (failure) return;
87
+ failure = error;
88
+ cancel();
89
+ for (const p of pending.values()) p.reject(error);
90
+ pending.clear();
91
+ };
92
+ const aborted = () => fail(signal.reason || fault('ACP call cancelled.', 'KILLED', 'killed'));
93
+ const exit = new Promise((resolve) => child.once('close', () => {
94
+ closed = true;
95
+ finishOpening?.(false);
96
+ if (pendingText.trim()) fail(fault('ACP stdout ended with an incomplete JSON-RPC frame.'));
97
+ if (!closing) fail(fault('ACP process exited before the call completed. Run agentlink check for this profile.', 'CLI_EXIT'));
98
+ for (const p of pending.values()) if (p.optional) p.reject();
99
+ pending.clear();
100
+ resolve();
101
+ }));
102
+ child.on('error', (e) => fail(fault(`Could not launch AgentLink (${e.code || 'spawn error'}).`, e.code || 'CLI_EXIT', 'missing')));
103
+ child.stdin.on('error', () => { if (!closing) fail(fault('ACP input closed before the call completed.', 'CLI_EXIT')); });
104
+ function receive(message) {
105
+ if (!record(message) || message.jsonrpc !== '2.0') throw fault('Invalid ACP JSON-RPC envelope.');
106
+ if (Object.hasOwn(message, 'method')) {
107
+ if (failure) return;
108
+ if (typeof message.method !== 'string') throw fault('Invalid ACP method.');
109
+ if (Object.hasOwn(message, 'id')) {
110
+ if (message.method === 'session/request_permission') {
111
+ send({ id: message.id, result: { outcome: { outcome: 'cancelled' } } });
112
+ throw policy();
113
+ }
114
+ send({ id: message.id, error: { code: -32601, message: 'Roundtable does not provide client tools.' } });
115
+ if (/^(fs\/|terminal\/)/.test(message.method)) throw policy();
116
+ } else if (message.method === 'session/update') {
117
+ const { params } = message;
118
+ if (!record(params) || !record(params.update) || typeof params.sessionId !== 'string') throw fault('Invalid ACP session update.');
119
+ if (['tool_call', 'tool_call_update'].includes(params.update.sessionUpdate)) throw policy();
120
+ if (sessionId && params.sessionId !== sessionId) throw fault('ACP update belongs to another session.');
121
+ if (sessionId) onUpdate(params.update);
122
+ }
123
+ return;
124
+ }
125
+ if (!Object.hasOwn(message, 'id') || Object.hasOwn(message, 'result') === Object.hasOwn(message, 'error')) throw fault('Invalid ACP response.');
126
+ // A successful session/new owns this ID even when cancellation raced the response.
127
+ // Bind it before reading updates coalesced in the same stdout chunk.
128
+ if (openingId !== undefined && message.id === openingId) {
129
+ openingId = undefined;
130
+ if (typeof message.result?.sessionId === 'string' && message.result.sessionId) {
131
+ sessionId = message.result.sessionId;
132
+ const status = message.result._meta?.[HISTORY_KEY]?.status;
133
+ history = strategy ? (status === strategy ? status : 'unconfirmed') : 'provider-managed';
134
+ }
135
+ finishOpening?.(true);
136
+ }
137
+ const p = pending.get(message.id);
138
+ if (failure && !p?.optional) return;
139
+ if (!p) throw fault('ACP response has an unknown request ID.');
140
+ pending.delete(message.id);
141
+ if (message.error) {
142
+ if (p.method === 'session/new' && ['SESSION_HISTORY_UNSUPPORTED', 'SESSION_HISTORY_UNCONFIRMED'].includes(message.error.data?.code)) return p.reject(unsupportedHistory(profile));
143
+ if (p.method === 'session/new' && ['OPTION_UNAVAILABLE', 'OPTION_UNCONFIRMED'].includes(message.error.data?.code)) {
144
+ p.reject(fault(`AgentLink could not apply a saved default for ${profile}. Inspect choices with agentlink models ${profile} and update them with agentlink defaults ${profile}.`, 'ACP_UNSUPPORTED'));
145
+ return;
146
+ }
147
+ const auth = message.error.code === -32000;
148
+ p.reject(fault(auth ? 'ACP authentication is required. Sign in using the agent vendor login flow, then check the AgentLink profile.'
149
+ : `ACP request failed: ${String(message.error.message || 'unknown error').slice(0, 500)}`, 'CLI_FAILURE', auth ? 'auth' : 'other'));
150
+ } else if (!record(message.result)) p.reject(fault('ACP response result must be an object.'));
151
+ else {
152
+ if (p.method === 'initialize') {
153
+ const agent = message.result.agentCapabilities;
154
+ capabilities = agent?.sessionCapabilities ?? {};
155
+ const extension = agent?._meta?.[HISTORY_KEY];
156
+ if (providerHistory !== 'provider-default' && extension?.version === 1 && HISTORY_STRATEGIES.has(extension.strategy)) strategy = extension.strategy;
157
+ }
158
+ p.resolve(message.result);
159
+ }
160
+ }
161
+ const accountBytes = (d) => {
162
+ bytes += Buffer.byteLength(d);
163
+ if (bytes > LIMIT) { fail(fault('ACP output exceeded the local size limit.', 'OUTPUT_LIMIT')); return false; }
164
+ return true;
165
+ };
166
+ child.stderr.on('data', accountBytes); // diagnostics are bounded, never copied into review records
167
+ child.stdout.setEncoding('utf8').on('data', (d) => {
168
+ if (!accountBytes(d)) return;
169
+ pendingText += d;
170
+ let i;
171
+ while ((i = pendingText.indexOf('\n')) >= 0) {
172
+ const line = pendingText.slice(0, i); pendingText = pendingText.slice(i + 1);
173
+ if (!line.trim()) continue;
174
+ try { receive(JSON.parse(line)); }
175
+ catch (e) { fail(e instanceof SyntaxError ? fault('ACP stdout contained invalid JSON.') : e); }
176
+ }
177
+ });
178
+ signal.addEventListener('abort', aborted, { once: true });
179
+ if (signal.aborted) aborted();
180
+ // These metadata requests only address the id returned to this connection by session/new.
181
+ // A late acknowledgement still has a matching id. A slow or unavailable history operation
182
+ // must not discard a paid reply or trigger a second model call.
183
+ function closeSession() {
184
+ if (!sessionId || closed || !child.stdin.writable) return Promise.resolve(false);
185
+ const id = ++next;
186
+ return boundedAction(done => {
187
+ pending.set(id, { method: 'session/close', optional: true, resolve: done, reject: () => done(false) });
188
+ send({ id, method: 'session/close', params: { sessionId } });
189
+ });
190
+ }
191
+ return {
192
+ async newSession() {
193
+ if (providerHistory === 'require-ephemeral' && strategy !== 'ephemeral') throw unsupportedHistory(profile);
194
+ const session = await this.request('session/new', { cwd, mcpServers: [],
195
+ ...(strategy ? { _meta: { [HISTORY_KEY]: { mode: providerHistory } } } : {}) });
196
+ if (typeof session.sessionId !== 'string' || !session.sessionId) throw fault('ACP agent did not return a session ID.');
197
+ if (providerHistory === 'require-ephemeral' && history !== 'ephemeral') throw unsupportedHistory(profile);
198
+ return session;
199
+ },
200
+ check() { if (failure) throw failure; },
201
+ request(method, params) {
202
+ if (failure) return Promise.reject(failure);
203
+ const id = ++next;
204
+ if (method === 'session/new') openingId = id;
205
+ return new Promise((resolve, reject) => { pending.set(id, { resolve, reject, method }); send({ id, method, params }); });
206
+ },
207
+ async close() {
208
+ if (closing) { await exit; return history; }
209
+ closing = true;
210
+ signal.removeEventListener('abort', aborted);
211
+ if (openingId !== undefined && !closed) await boundedAction(done => { finishOpening = done; });
212
+ if (openingId !== undefined) history = 'unconfirmed';
213
+ if (sessionId) {
214
+ const result = record(capabilities.close) || strategy === 'archive-on-close' ? await closeSession() : null;
215
+ if (history === 'archive-on-close') history = result?._meta?.[HISTORY_KEY]?.status === 'archived' ? 'archived' : 'unconfirmed';
216
+ }
217
+ if (!closed) {
218
+ child.stdin.end();
219
+ // Leave time for AgentLink's own bridge cleanup and lease release.
220
+ const timer = setTimeout(() => killTree(child), 2000);
221
+ try { await exit; } finally { clearTimeout(timer); }
222
+ }
223
+ return history;
224
+ },
225
+ };
226
+ }
227
+
228
+ // A session's select-type config option by ACP category, or by id for an agent that labels
229
+ // none, and the values it offers (flat, or grouped). Roundtable never invents a value: a model or
230
+ // reasoning level is sent only when the agent advertised it for this session.
231
+ function configOption(session, category, ids) {
232
+ const selects = (Array.isArray(session.configOptions) ? session.configOptions : [])
233
+ .filter((o) => o?.type === 'select' && typeof (o.configId ?? o.id) === 'string');
234
+ return selects.find((o) => o.category === category) || selects.find((o) => !o.category && ids.includes(o.configId ?? o.id));
235
+ }
236
+ const optionValues = (option) => Array.isArray(option?.options) ? option.options.flatMap((o) => Array.isArray(o?.options) ? o.options : [o]).filter(record) : [];
237
+ const MODEL = { category: 'model', ids: ['model'], what: 'model' };
238
+ const EFFORT = { category: 'thought_level', ids: ['thought_level', 'effort', 'reasoning_effort', 'reasoning'], what: 'reasoning level' };
239
+ const advertised = (session, option) => optionValues(configOption(session, option.category, option.ids));
240
+ async function selectOption(connection, session, value, { category, ids, what }) {
241
+ const option = configOption(session, category, ids);
242
+ if (!option || !optionValues(option).some((o) => o.value === value)) throw fault(`The ACP agent did not advertise this ${what}. Use its default or an advertised ${what} ID.`, 'ACP_UNSUPPORTED');
243
+ if (option.currentValue === value) return;
244
+ const result = await connection.request('session/set_config_option', { sessionId: session.sessionId, configId: option.configId ?? option.id, value });
245
+ session.configOptions = result.configOptions;
246
+ if (configOption(session, category, ids)?.currentValue !== value) throw fault(`The ACP agent did not confirm the selected ${what}.`, 'ACP_UNSUPPORTED');
247
+ }
248
+
249
+ async function withProfile(prompt, previousSession, opts, { bin, env: suppliedEnv }, inspect) {
250
+ const profile = agentLinkProfile(opts.account);
251
+ const providerHistory = opts.providerHistory ?? 'prefer-ephemeral';
252
+ if (!opts.allowLimitedIsolation) throw fault('ACP profiles control their own permissions and customization. Accept limited isolation before using this profile.', 'ISOLATION_REQUIRED', 'policy');
253
+ if (previousSession || opts.keepSession) throw fault('ACP seats currently require stateless memory; no previous session was loaded.', 'ACP_STATELESS_REQUIRED');
254
+ if (opts.research) throw fault('ACP seats do not support Roundtable web research.', 'ACP_UNSUPPORTED');
255
+ const cwd = opts.cwd;
256
+ if (!cwd || !path.isAbsolute(cwd)) throw fault('ACP seats need an absolute, isolated working directory.');
257
+ mkdirSync(cwd, { recursive: true });
258
+ const env = cleanEnv(null, { source: suppliedEnv || process.env });
259
+ const launch = bin || agentLinkBinary(env);
260
+ const call = registerCall(opts.tag);
261
+ const timeout = new AbortController();
262
+ const timer = setTimeout(() => timeout.abort(fault('ACP call timed out.', 'TIMEOUT', 'timeout')), opts.timeoutMs ?? 300_000);
263
+ const signal = AbortSignal.any([call.signal, timeout.signal, ...(opts.signal ? [opts.signal] : [])]);
264
+ const started = Date.now();
265
+ let text = '', cost = null, endUsage, activePrompt = false;
266
+ let connection;
267
+ try {
268
+ if (signal.aborted) throw signal.reason;
269
+ connection = connect(launch, profile, { cwd, env, signal, providerHistory, onUpdate: (update) => {
270
+ if (!activePrompt) return;
271
+ if (update.sessionUpdate === 'agent_message_chunk') {
272
+ if (update.content?.type !== 'text' || typeof update.content.text !== 'string') throw fault('ACP review replies must contain text.');
273
+ text += update.content.text;
274
+ } else if (update.sessionUpdate === 'usage_update' && update.cost?.currency === 'USD' && Number.isFinite(update.cost.amount) && update.cost.amount >= 0) cost = update.cost.amount;
275
+ } });
276
+ const init = await connection.request('initialize', { protocolVersion: 1,
277
+ clientCapabilities: providerHistory === 'provider-default' ? {} : { _meta: { [HISTORY_KEY]: { version: 1 } } }, clientInfo: { name: 'roundtable', version: VERSION } });
278
+ if (init.protocolVersion !== 1) throw fault('This Roundtable client requires ACP v1; the agent negotiated an incompatible protocol.', 'ACP_UNSUPPORTED');
279
+ const session = await connection.newSession();
280
+ const hasModel = advertised(session, MODEL).some((o) => o.value === opts.model);
281
+ if (opts.model && (!inspect || hasModel)) await selectOption(connection, session, opts.model, MODEL);
282
+ if (inspect) {
283
+ const models = advertised(session, MODEL).filter((o) => typeof o.value === 'string' && o.value.length <= 200)
284
+ .map((o) => ({ id: o.value, label: typeof o.name === 'string' ? o.name : o.value }));
285
+ const effortChoices = advertised(session, EFFORT).filter((o) => optionId(o.value))
286
+ .map((o) => ({ id: o.value, label: typeof o.name === 'string' ? o.name : o.value }));
287
+ await connection.close();
288
+ connection.check();
289
+ return { models, efforts: effortChoices.map((e) => e.id), effortChoices, effortModel: hasModel ? opts.model : '' };
290
+ }
291
+ if (opts.effort) await selectOption(connection, session, opts.effort, EFFORT);
292
+ if (opts.model && configOption(session, MODEL.category, MODEL.ids)?.currentValue !== opts.model) {
293
+ throw fault('The ACP agent changed the selected model while applying the reasoning level.', 'ACP_UNSUPPORTED');
294
+ }
295
+ activePrompt = true;
296
+ const result = await connection.request('session/prompt', { sessionId: session.sessionId, prompt: [{ type: 'text', text: prompt }] });
297
+ endUsage = result.usage;
298
+ connection.check();
299
+ 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');
300
+ if (!text.trim()) throw fault('ACP agent completed without a text answer.');
301
+ activePrompt = false;
302
+ const historyOutcome = await connection.close();
303
+ connection.check();
304
+ const ms = Date.now() - started;
305
+ return { text, usage: promptUsage(endUsage, cost, ms), cost, ms, sessionId: session.sessionId, usedTools: false, progress: { providerHistory: historyOutcome } };
306
+ } catch (e) {
307
+ const providerHistory = await connection?.close();
308
+ const ms = Date.now() - started;
309
+ throw Object.assign(e, { usage: promptUsage(endUsage, cost, ms), cost, ms, ...(providerHistory ? { progress: { providerHistory } } : {}) });
310
+ } finally {
311
+ clearTimeout(timer);
312
+ try { await connection?.close(); } finally { call.release(); }
313
+ }
314
+ }
315
+
316
+ export function makeAcpAdapter(launch = {}) {
317
+ return (prompt, previousSession = null, opts = {}) => withProfile(prompt, previousSession, opts, launch, false);
318
+ }
319
+
320
+ // Explicit local setup action. The profile receives an empty workspace and no prompt.
321
+ export async function inspectProfileSession(account, model = '', launch = {}, providerHistory = 'prefer-ephemeral') {
322
+ agentLinkProfile(account);
323
+ if (typeof model !== 'string' || model.length > 200) throw new Error('Model ID must be at most 200 characters.');
324
+ const cwd = await mkdtemp(path.join(os.tmpdir(), 'roundtable-profile-'));
325
+ try {
326
+ return await withProfile(null, null, { account, model, cwd, providerHistory, timeoutMs: 20_000, allowLimitedIsolation: true }, launch, true);
327
+ } finally {
328
+ await rm(cwd, { recursive: true, force: true });
329
+ }
330
+ }
331
+
332
+ // Unlike session/new, beta.3 management inspection ignores saved pins. A retired
333
+ // central default must not prevent the picker from showing its replacements.
334
+ async function modelReport(bin, env, account, model) {
335
+ const args = ['models', account, '--json'];
336
+ if (model) args.push('--model', model);
337
+ const result = await runProcess(bin, args, { env, timeoutMs: 20_000 });
338
+ if (result.code !== 0) {
339
+ if (!model && /^INVALID_ARGUMENT: Unknown command\. Run agentlink --help\.\s*$/.test(result.stderr)) return null; // beta.2
340
+ throw fault(`AgentLink could not inspect profile ${account}. Run agentlink models ${account} to check its connection.`, 'CLI_FAILURE');
341
+ }
342
+ let report;
343
+ try { report = JSON.parse(result.stdout); } catch {}
344
+ if (report?.name !== account || !['model', 'effort'].every((k) => report[k] === null || Array.isArray(report[k]?.choices))) {
345
+ throw fault('AgentLink returned an unreadable model report.');
346
+ }
347
+ return report;
348
+ }
349
+
350
+ function namedChoices(selector) {
351
+ return (selector?.choices || []).filter((o) => optionId(o?.id))
352
+ .map(({ id, name }) => ({ id, label: typeof name === 'string' && name ? name : id }));
353
+ }
354
+
355
+ export async function discoverProfile(account, model = '', launch = {}) {
356
+ account = agentLinkProfile(account);
357
+ if (model !== '' && !optionId(model)) throw new Error('Choose a model ID of at most 200 characters.');
358
+ const env = cleanEnv(null, { source: launch.env || process.env });
359
+ const bin = launch.bin || agentLinkBinary(env);
360
+ const base = await modelReport(bin, env, account);
361
+ if (!base) return inspectProfileSession(account, model, launch);
362
+ const defaults = savedDefaults(base.defaults);
363
+ const models = namedChoices(base.model);
364
+ const offers = (id) => models.some((m) => m.id === id);
365
+ const profileModel = defaults.model || (optionId(base.model?.current) ? base.model.current : '');
366
+ const effortModel = offers(model) ? model : '';
367
+ const selected = effortModel || (offers(profileModel) ? profileModel : '');
368
+ const detail = selected && selected !== base.model?.current ? await modelReport(bin, env, account, selected) : base;
369
+ const effortChoices = namedChoices(detail.effort);
370
+ const efforts = effortChoices.map((e) => e.id);
371
+ const inheritsModel = !effortModel || effortModel === profileModel;
372
+ const stale = defaults.model && !offers(defaults.model) || inheritsModel && defaults.effort && !efforts.includes(defaults.effort);
373
+ // The inspector bypasses saved pins. After a seat overrides a centrally configured
374
+ // model, only its actual session knows whether the provider retained or reset effort.
375
+ const observedEffort = optionId(detail.effort?.current) ? detail.effort.current : '';
376
+ const defaultEffort = inheritsModel ? defaults.effort || observedEffort : Object.keys(defaults).length ? '' : observedEffort;
377
+ return { models, efforts, effortChoices, effortModel, defaults, profileModel, defaultEffort,
378
+ ...(stale ? { warning: `A saved AgentLink default is unavailable. Choose a replacement with agentlink defaults ${account} before starting a review.` } : {}) };
379
+ }
380
+
381
+ export const run = makeAcpAdapter();