@prplkane/roundtable 0.6.6 → 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.
@@ -3,12 +3,18 @@
3
3
  import { spawn } from 'node:child_process';
4
4
  import { mkdirSync, existsSync } from 'node:fs';
5
5
  import path from 'node:path';
6
- import { cleanEnv, resolveBinary, registerCall, killTree } from './spawn.js';
6
+ import os from 'node:os';
7
+ import { mkdtemp, rm } from 'node:fs/promises';
8
+ import { cleanEnv, resolveBinary, registerCall, killTree, runProcess } from './spawn.js';
7
9
  import { agentLinkProfile } from '../seats.js';
8
10
  import { VERSION } from '../version.js';
9
11
 
10
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']);
11
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 });
12
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 });
13
19
  const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
14
20
 
@@ -24,6 +30,25 @@ export function agentLinkBinary(env = process.env) {
24
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'); }
25
31
  }
26
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
+
27
52
  // Optional ACP end-turn usage is still experimental. Fresh sessions avoid the
28
53
  // deployed turn-vs-session ambiguity. Context-window `used` is never spending.
29
54
  // Accept inclusive or additive cache counts only when the reported total agrees.
@@ -40,11 +65,20 @@ export function promptUsage(value, cost, ms) {
40
65
  return { input: uncached, output, cacheRead, cacheWrite, thinking, cost, ms, usageVersion: 3 };
41
66
  }
42
67
 
43
- function connect(bin, profile, { cwd, env, signal, onUpdate }) {
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 }) {
44
77
  const child = spawn(bin.file, [...bin.prefix, 'acp', profile], {
45
78
  cwd, env, windowsHide: true, detached: process.platform !== 'win32', stdio: ['pipe', 'pipe', 'pipe'],
46
79
  });
47
80
  let next = 0, pendingText = '', bytes = 0, failure, closed = false, closing = false, sessionId;
81
+ let capabilities = {}, strategy, history, openingId, finishOpening;
48
82
  const pending = new Map();
49
83
  const send = (message) => { if (!closed && child.stdin.writable) child.stdin.write(JSON.stringify({ jsonrpc: '2.0', ...message }) + '\n'); };
50
84
  const cancel = () => { if (sessionId) send({ method: 'session/cancel', params: { sessionId } }); };
@@ -58,8 +92,11 @@ function connect(bin, profile, { cwd, env, signal, onUpdate }) {
58
92
  const aborted = () => fail(signal.reason || fault('ACP call cancelled.', 'KILLED', 'killed'));
59
93
  const exit = new Promise((resolve) => child.once('close', () => {
60
94
  closed = true;
95
+ finishOpening?.(false);
61
96
  if (pendingText.trim()) fail(fault('ACP stdout ended with an incomplete JSON-RPC frame.'));
62
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();
63
100
  resolve();
64
101
  }));
65
102
  child.on('error', (e) => fail(fault(`Could not launch AgentLink (${e.code || 'spawn error'}).`, e.code || 'CLI_EXIT', 'missing')));
@@ -67,6 +104,7 @@ function connect(bin, profile, { cwd, env, signal, onUpdate }) {
67
104
  function receive(message) {
68
105
  if (!record(message) || message.jsonrpc !== '2.0') throw fault('Invalid ACP JSON-RPC envelope.');
69
106
  if (Object.hasOwn(message, 'method')) {
107
+ if (failure) return;
70
108
  if (typeof message.method !== 'string') throw fault('Invalid ACP method.');
71
109
  if (Object.hasOwn(message, 'id')) {
72
110
  if (message.method === 'session/request_permission') {
@@ -85,117 +123,259 @@ function connect(bin, profile, { cwd, env, signal, onUpdate }) {
85
123
  return;
86
124
  }
87
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
+ }
88
137
  const p = pending.get(message.id);
138
+ if (failure && !p?.optional) return;
89
139
  if (!p) throw fault('ACP response has an unknown request ID.');
90
140
  pending.delete(message.id);
91
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
+ }
92
147
  const auth = message.error.code === -32000;
93
148
  p.reject(fault(auth ? 'ACP authentication is required. Sign in using the agent vendor login flow, then check the AgentLink profile.'
94
149
  : `ACP request failed: ${String(message.error.message || 'unknown error').slice(0, 500)}`, 'CLI_FAILURE', auth ? 'auth' : 'other'));
95
150
  } else if (!record(message.result)) p.reject(fault('ACP response result must be an object.'));
96
151
  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;
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
+ }
100
158
  p.resolve(message.result);
101
159
  }
102
160
  }
103
161
  const accountBytes = (d) => {
104
162
  bytes += Buffer.byteLength(d);
105
163
  if (bytes > LIMIT) { fail(fault('ACP output exceeded the local size limit.', 'OUTPUT_LIMIT')); return false; }
106
- return !failure;
164
+ return true;
107
165
  };
108
166
  child.stderr.on('data', accountBytes); // diagnostics are bounded, never copied into review records
109
167
  child.stdout.setEncoding('utf8').on('data', (d) => {
110
168
  if (!accountBytes(d)) return;
111
169
  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); }
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
+ }
120
177
  });
121
178
  signal.addEventListener('abort', aborted, { once: true });
122
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
+ }
123
191
  return {
124
- setSession(id) { sessionId = id; },
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
+ },
125
200
  check() { if (failure) throw failure; },
126
201
  request(method, params) {
127
202
  if (failure) return Promise.reject(failure);
128
203
  const id = ++next;
204
+ if (method === 'session/new') openingId = id;
129
205
  return new Promise((resolve, reject) => { pending.set(id, { resolve, reject, method }); send({ id, method, params }); });
130
206
  },
131
207
  async close() {
208
+ if (closing) { await exit; return history; }
132
209
  closing = true;
133
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
+ }
134
217
  if (!closed) {
135
218
  child.stdin.end();
136
219
  // Leave time for AgentLink's own bridge cleanup and lease release.
137
220
  const timer = setTimeout(() => killTree(child), 2000);
138
221
  try { await exit; } finally { clearTimeout(timer); }
139
222
  }
223
+ return history;
140
224
  },
141
225
  };
142
226
  }
143
227
 
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.');
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 }));
188
287
  await connection.close();
189
288
  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(); }
289
+ return { models, efforts: effortChoices.map((e) => e.id), effortChoices, effortModel: hasModel ? opts.model : '' };
197
290
  }
198
- };
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.` } : {}) };
199
379
  }
200
380
 
201
381
  export const run = makeAcpAdapter();
@@ -1,11 +1,6 @@
1
- // What each vendor can be asked for: model ids and effort levels, from the sources that exist.
2
- //
3
- // claude no list command headless; the aliases in config.js are the hints
4
- // codex the model table in models.js and the levels in config.js. Not ~/.codex/config.toml: the
5
- // seat runs with --ignore-user-config, so that file cannot describe its defaults
6
- // agy `agy models` prints "<id>\t<label>" lines (slow: a network call), cached after one read
1
+ // Direct CLI choices for the setup screen. ACP profiles advertise their own session options.
7
2
  import { ADAPTERS } from './config.js';
8
- import { resolveBinary, runProcess } from './spawn.js';
3
+ import { resolveBinary, runProcess, cleanEnv } from './spawn.js';
9
4
  import { MODELS, agyFamilies } from './models.js';
10
5
 
11
6
  // "gemini-4-argon-high\tGemini 4 Argon (High)" lines; anything else (the "Fetching..." line) is skipped.
@@ -15,22 +10,36 @@ export function parseAgyModels(text) {
15
10
  .map(([id, label]) => ({ id: id.trim(), label: label.trim() }));
16
11
  }
17
12
 
18
- let agyCache = null;
19
13
  export async function readAgyModels({ timeoutMs = 30_000 } = {}) {
20
- if (agyCache) return agyCache;
21
14
  try {
22
- const bin = resolveBinary('agy');
23
- const res = await runProcess(bin, ['models'], { timeoutMs });
24
- const models = parseAgyModels(res.stdout);
25
- if (models.length) agyCache = models;
26
- return models;
15
+ const res = await runProcess(resolveBinary('agy'), ['models'], { timeoutMs });
16
+ return res.code === 0 ? parseAgyModels(res.stdout) : [];
17
+ } catch { return []; }
18
+ }
19
+
20
+ export function parseCodexModels(text) {
21
+ const rows = JSON.parse(text).models;
22
+ if (!Array.isArray(rows)) return [];
23
+ return rows.filter((m) => m?.visibility === 'list' && typeof m.slug === 'string' && m.slug.length > 0)
24
+ .map((m) => {
25
+ const hint = MODELS.codex.find((h) => h.id === m.slug);
26
+ const efforts = Array.isArray(m.supported_reasoning_levels) ? m.supported_reasoning_levels.map((l) => l?.effort).filter((l) => typeof l === 'string') : null;
27
+ return { id: m.slug, label: hint?.label || m.display_name || m.slug, ...(hint?.note ? { note: hint.note } : {}), ...(efforts ? { efforts } : {}) };
28
+ });
29
+ }
30
+
31
+ export async function readCodexModels() {
32
+ try {
33
+ const bin = resolveBinary('codex', ADAPTERS.codex.npmBin);
34
+ const res = await runProcess(bin, ['debug', 'models'], { timeoutMs: 10_000, env: cleanEnv() });
35
+ return res.code === 0 ? parseCodexModels(res.stdout) : [];
27
36
  } catch { return []; }
28
37
  }
29
38
 
30
39
  // One object for the setup screen, per vendor: models, efforts, defaults, and the pool the
31
40
  // vendor's quota is drawn against. `agyModels` is injectable so tests never spawn the CLI.
32
- export async function vendorCatalogue({ agyModels = readAgyModels } = {}) {
33
- const agy = await agyModels();
41
+ export async function vendorCatalogue({ agyModels = readAgyModels, codexModels = readCodexModels } = {}) {
42
+ const [agy, codex] = await Promise.all([agyModels(), codexModels()]);
34
43
  const out = {};
35
44
  for (const [vendor, a] of Object.entries(ADAPTERS)) {
36
45
  const entry = {
@@ -41,8 +50,18 @@ export async function vendorCatalogue({ agyModels = readAgyModels } = {}) {
41
50
  if (MODELS[vendor]) entry.models = MODELS[vendor].slice();
42
51
  if (vendor === 'claude') entry.defaultLabel = 'Opus 5.5';
43
52
  // The installed CLI chooses its default; a static model table cannot establish it.
44
- if (vendor === 'codex') entry.defaultLabel = 'CLI default';
45
- if (vendor === 'agy' && agy.length) { entry.models = agy; entry.families = agyFamilies(agy); }
53
+ if (vendor === 'codex') {
54
+ entry.defaultLabel = 'CLI default';
55
+ if (codex.length) {
56
+ entry.models = codex;
57
+ entry.efforts = [...new Set([...entry.efforts, ...codex.flatMap((m) => m.efforts || [])])];
58
+ }
59
+ }
60
+ if (vendor === 'agy' && agy.length) {
61
+ entry.models = agy;
62
+ entry.families = agyFamilies(agy);
63
+ entry.efforts = [...new Set([...entry.efforts, ...entry.families.flatMap((f) => f.levels)])];
64
+ }
46
65
  out[vendor] = entry;
47
66
  }
48
67
  return out;
@@ -29,17 +29,40 @@ const reportedCost = (v) => Number.isFinite(v) && v >= 0 ? v : null;
29
29
  // Pull the normalised fields out of one JSON object using the config's dot paths.
30
30
  export function pickJson(obj, paths) {
31
31
  const n = (p) => dig(obj, p);
32
+ const usage = usageCounters({ input: n(paths.input), cacheRead: n(paths.cacheRead), cacheWrite: n(paths.cacheWrite),
33
+ output: n(paths.output), thinking: n(paths.thinking) });
34
+ const total = n(paths.total);
35
+ if (usage && Number.isSafeInteger(total) && total >= 0) usage.providerTotal = total;
32
36
  return {
33
37
  text: String(dig(obj, paths.text) ?? ''),
34
38
  sessionId: dig(obj, paths.sessionId) ?? null,
35
- usage: usageCounters({ input: n(paths.input), cacheRead: n(paths.cacheRead), cacheWrite: n(paths.cacheWrite),
36
- output: n(paths.output), thinking: n(paths.thinking) }),
39
+ usage,
37
40
  cost: reportedCost(dig(obj, paths.cost)),
38
41
  quota: paths.quota ? (dig(obj, paths.quota) ?? null) : null,
39
42
  isError: paths.isError ? dig(obj, paths.isError) === true : false,
40
43
  };
41
44
  }
42
45
 
46
+ // Completed Antigravity model steps are incremental. Repeated updates for an index describe one step.
47
+ function completedStepUsage(events, paths) {
48
+ const steps = new Map();
49
+ for (const event of events) {
50
+ const s = event.step_update;
51
+ if (s?.step_type !== 'agent_response' || s.state !== 'DONE' || !Number.isSafeInteger(s.step_index) || s.step_index < 0) continue;
52
+ const u = pickJson(s, paths).usage;
53
+ if (u) steps.set(s.step_index, u);
54
+ }
55
+ if (!steps.size) return null;
56
+ const sum = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, thinking: 0 };
57
+ let providerTotal;
58
+ for (const u of steps.values()) {
59
+ for (const k of Object.keys(sum)) sum[k] += u[k];
60
+ if (u.providerTotal != null) providerTotal = (providerTotal ?? 0) + u.providerTotal;
61
+ }
62
+ return usageCounters(sum) && { ...sum, modelSteps: steps.size, tokenCoverage: { reported: 0, of: 1 },
63
+ ...(Number.isSafeInteger(providerTotal) ? { providerTotal } : {}) };
64
+ }
65
+
43
66
  // Same for a JSONL stream: each path names the event type that carries the value.
44
67
  export function pickJsonl(text, paths) {
45
68
  const events = parseLines(text);
@@ -90,7 +113,7 @@ export function normaliseUsage(cfg, u, rawCost = null) {
90
113
  // keepSession: the call's session will be resumed (resume memory), so the CLI must save it. Any
91
114
  // other fresh call adds the CLI's `ephemeral` argv when it has one; a resumed call never does,
92
115
  // since its session goes on.
93
- export function buildArgs(cfg, { prompt, sessionId = null, model = null, effort = null, instructionsFile = null, timeoutMs = 300_000, keepSession = false }) {
116
+ export function buildArgs(cfg, { prompt, sessionId = null, model = null, effort = null, instructionsFile = null, timeoutMs = 300_000, keepSession = false, providerHistory = 'prefer-ephemeral' }) {
94
117
  const useStdin = cfg.promptVia === 'stdin' ||
95
118
  (cfg.promptVia === 'argv-or-stdin' && prompt.length > ARGV_LIMIT);
96
119
  const streamMode = useStdin && !!cfg.stdinArgs;
@@ -98,11 +121,13 @@ export function buildArgs(cfg, { prompt, sessionId = null, model = null, effort
98
121
  const args = sessionId ? cfg.resume(sessionId, base) : [...base];
99
122
  const extra = [];
100
123
  if (cfg.stream) extra.push(...cfg.stream(timeoutMs, effort)); // the stream's idle limit fits inside the call limit
101
- if (!keepSession && !sessionId && cfg.ephemeral) extra.push(...cfg.ephemeral);
124
+ const canRunEphemeral = !keepSession && !sessionId && cfg.ephemeral;
125
+ if (providerHistory === 'require-ephemeral' && !canRunEphemeral) throw new Error(`${cfg.label} cannot confirm a non-saving session.`);
126
+ if (providerHistory !== 'provider-default' && canRunEphemeral) extra.push(...cfg.ephemeral);
102
127
  if (model && cfg.model) extra.push(...cfg.model(model));
103
128
  if (instructionsFile) extra.push('-c', `model_instructions_file=${JSON.stringify(instructionsFile)}`);
104
129
  // Skip the effort flag when the model id already names the level (agy), so nothing is said twice.
105
- if (effort && cfg.effort && !(model && cfg.effortInModel && cfg.effortInModel.test(model))) extra.push(...cfg.effort(effort));
130
+ if (effort && cfg.effort && !(model && cfg.effortInModel && (cfg.effortInModel.test(model) || model.endsWith(`-${effort}`)))) extra.push(...cfg.effort(effort));
106
131
  if (extra.length) {
107
132
  const at = args[args.length - 1] === '-' ? args.length - 1 : args.length;
108
133
  args.splice(at, 0, ...extra);
@@ -113,6 +138,17 @@ export function buildArgs(cfg, { prompt, sessionId = null, model = null, effort
113
138
  return { args, stdin, streamMode };
114
139
  }
115
140
 
141
+ // Strict reviews also check the installed CLI. Reading help never opens a session.
142
+ export async function checkEphemeralCli(cfg, bin) {
143
+ let help;
144
+ try {
145
+ const command = bin ?? resolveBinary(cfg.binary, cfg.npmBin);
146
+ help = await runProcess(command, cfg.ephemeralHelp, { env: cleanEnv(), timeoutMs: 5000, maxOutputBytes: 384 * 1024 });
147
+ } catch { /* A missing or unresponsive CLI cannot confirm support. */ }
148
+ const words = help?.code === 0 ? (help.stdout + '\n' + help.stderr).split(/[\s,=]+/) : [];
149
+ if (!cfg.ephemeral.every(flag => words.includes(flag))) throw new Error(`${cfg.label} could not confirm ${cfg.ephemeral.join(' ')} in its CLI help. Check the installation or choose another provider.`);
150
+ }
151
+
116
152
  // Build a run(prompt, sessionId, opts) for one config row. All three adapters are this
117
153
  // function with a different row; the per-CLI files exist so a vendor quirk has a home.
118
154
  export function makeAdapter(name, overrides = {}) {
@@ -150,10 +186,10 @@ export function makeAdapter(name, overrides = {}) {
150
186
  const guard = searching ? searching.foreignTool : cfg.usedTools; // search allowed, every other tool still stops the call
151
187
  if (cfg.limitedIsolation && !opts.allowLimitedIsolation) throw Object.assign(new Error('Explicit consent to limited isolation is required.'), { code: 'ISOLATION_REQUIRED' });
152
188
  if (cfg.terms && opts.acknowledgeTermsRisk !== true) throw Object.assign(new Error(`The person has not acknowledged ${cfg.label}'s terms notice.`), { code: 'TERMS_ACK_REQUIRED' });
153
- bin ??= cfg.bin || resolveBinary(cfg.binary, cfg.npmBin); // cfg.bin: a test's fake CLI
154
189
  // One time limit for the process and for the argv derived from it (cfg.stream).
155
190
  const timeoutMs = research ? Math.min(research.timeoutMs, opts.timeoutMs ?? research.timeoutMs) : opts.timeoutMs ?? 300_000;
156
- const built = buildArgs(cfg, { prompt, sessionId, model: opts.model, effort: opts.effort, instructionsFile, timeoutMs, keepSession: opts.keepSession === true });
191
+ const built = buildArgs(cfg, { prompt, sessionId, model: opts.model, effort: opts.effort, instructionsFile, timeoutMs, keepSession: opts.keepSession === true, providerHistory: opts.providerHistory });
192
+ bin ??= cfg.bin || resolveBinary(cfg.binary, cfg.npmBin); // cfg.bin: a test's fake CLI
157
193
  const { stdin, streamMode } = built;
158
194
  const args = searching ? searching.args(built.args) : built.args;
159
195
 
@@ -231,6 +267,11 @@ export function makeAdapter(name, overrides = {}) {
231
267
  completed = !!last;
232
268
  const obj = last ? last.result : {};
233
269
  picked = pickJson(obj, cfg.paths);
270
+ if (name === 'agy') {
271
+ const lower = completedStepUsage(events, cfg.paths);
272
+ if (lower && picked.usage) picked.usage.modelSteps = lower.modelSteps;
273
+ else if (lower) picked.usage = lower;
274
+ }
234
275
  usedTools = !!guard?.(obj, events);
235
276
  } else if (cfg.output === 'jsonl') {
236
277
  const events = parseLines(res.stdout);
@@ -288,6 +329,7 @@ export function makeAdapter(name, overrides = {}) {
288
329
  // An error result is not a reply; what the call cost still counts.
289
330
  if (picked.isError) throw Object.assign(new Error(`${cfg.label}: ${picked.text.trim().slice(0, 300)}`), { raw, ...accounting, sessionId: picked.sessionId });
290
331
  const quota = cfg.normaliseQuota && picked.quota ? cfg.normaliseQuota(picked.quota) : null;
332
+ progress.providerHistory = opts.providerHistory !== 'provider-default' && !sessionId && !opts.keepSession && cfg.ephemeral ? 'ephemeral' : 'provider-managed';
291
333
  return { text: picked.text.trim(), ...accounting, sessionId: picked.sessionId, quota, usedTools, raw };
292
334
  }
293
335
  }