@prplkane/roundtable 0.6.4 → 0.7.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.
@@ -0,0 +1,318 @@
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,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;
@@ -102,7 +102,7 @@ export function buildArgs(cfg, { prompt, sessionId = null, model = null, effort
102
102
  if (model && cfg.model) extra.push(...cfg.model(model));
103
103
  if (instructionsFile) extra.push('-c', `model_instructions_file=${JSON.stringify(instructionsFile)}`);
104
104
  // 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));
105
+ if (effort && cfg.effort && !(model && cfg.effortInModel && (cfg.effortInModel.test(model) || model.endsWith(`-${effort}`)))) extra.push(...cfg.effort(effort));
106
106
  if (extra.length) {
107
107
  const at = args[args.length - 1] === '-' ? args.length - 1 : args.length;
108
108
  args.splice(at, 0, ...extra);
@@ -1,3 +1,4 @@
1
+ import { effortSuffix } from './models.js';
1
2
  // One row per vendor. Everything the adapters need to know about a vendor lives here.
2
3
  //
3
4
  // kind 'cli': the vendor's own CLI on the user's subscription (the normal seat);
@@ -187,9 +188,9 @@ export const ADAPTERS = {
187
188
  model: (m) => ['--model', m],
188
189
  effort: (e) => ['--effort', e],
189
190
  effortLevels: ['low', 'medium', 'high'], // `claude --help`: "--effort <level>"
190
- // Request no extended-thinking budget for hidden-mood seats, which select Haiku 4.5.
191
+ // Request no extended-thinking budget for hidden-mood seats, which select Haiku.
191
192
  minimalEnv: { MAX_THINKING_TOKENS: '0' },
192
- modelHints: ['opus', 'sonnet', 'claude-haiku-4-5'], // use the explicit Haiku model id
193
+ modelHints: [], // direct CLI fallback in models.js
193
194
  pool: 'Anthropic subscription',
194
195
  promptVia: 'stdin',
195
196
  output: 'jsonl',
@@ -275,7 +276,7 @@ export const ADAPTERS = {
275
276
  // CLI effort vocabulary; availability depends on the selected model and installed CLI.
276
277
  // ~/.codex/config.toml is not a source: --ignore-user-config keeps it from the seat.
277
278
  effortLevels: ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'],
278
- modelHints: [], // curated capability and plan hints in models.js; no catalogue refresh at startup
279
+ modelHints: [], // catalogue.js reads the CLI listing and falls back to models.js
279
280
  pool: 'ChatGPT subscription',
280
281
  promptVia: 'stdin',
281
282
  output: 'jsonl',
@@ -350,11 +351,9 @@ export const ADAPTERS = {
350
351
  resume: (id, base) => [...base, '--conversation', id],
351
352
  model: (m) => ['--model', m],
352
353
  effort: (e) => ['--effort', e],
353
- // `agy --help` (1.4.12) lists low|medium|high|xhigh|max, but a model takes only its own levels
354
- // and every model `agy models` lists refuses xhigh and max before any turn ("gemini-4-argon
355
- // has no "xhigh" effort (available: low, medium, high)"). A family's levels come from its ids.
356
- effortLevels: ['low', 'medium', 'high'],
357
- effortInModel: /-(low|medium|high)$/, // `agy models` ids end in the level: gemini-4-argon-high
354
+ // Listed variants carry their own level. Discovery adds any new advertised levels.
355
+ effortLevels: ['low', 'medium', 'high', 'xhigh', 'max'],
356
+ effortInModel: effortSuffix,
358
357
  modelHints: [], // filled from `agy models` (catalogue.js)
359
358
  // `/usage`: limits per model group (Gemini; Claude and GPT; Gemini 4 Argon on some plans),
360
359
  // each with a weekly and usually a 5-hour window; AI credits, when enabled, take over after.
@@ -422,11 +421,21 @@ export const ADAPTERS = {
422
421
  colour: 'steel',
423
422
  readOnly: 'no tools in the request',
424
423
  },
424
+ acp: {
425
+ kind: 'acp', label: 'AgentLink (ACP)', binary: 'agentlink',
426
+ npmBin: ['@prplkane/agentlink', 'src/cli.mjs'],
427
+ args: [], resume: null, model: null, effort: null, home: null,
428
+ effortLevels: [], modelHints: [], paths: { cost: null, quota: null },
429
+ quota: null, usageUrl: null, colour: 'dusk', limitedIsolation: true,
430
+ pool: 'Selected AgentLink profile; billing and quota belong to its agent',
431
+ isolation: 'fresh ACP sessions in separate working directories; profile-owned tools and customization are not sandboxed',
432
+ readOnly: 'client tools denied; reported tool activity stops the seat; configure the profile agent to disable its own tools',
433
+ },
425
434
  };
426
435
 
427
436
  // A vendor whose seats draw on separate pools per account: a CLI with a state directory
428
437
  // (named login profiles), or an endpoint vendor (one pool per host). Pool keys (seats.poolKey)
429
438
  // carry the account only for these.
430
- export const poolsByAccount = (a) => !!a?.home || a?.kind === 'api';
439
+ export const poolsByAccount = (a) => !!a?.home || a?.kind === 'api' || a?.kind === 'acp';
431
440
 
432
441
  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 };
@@ -9,16 +9,15 @@
9
9
 
10
10
  export const MODELS = {
11
11
  claude: [
12
- { id: 'fable', label: 'Fable 5.1' },
12
+ { id: 'claude-fable-5-2', label: 'Fable 5.2' },
13
13
  { id: 'opus', label: 'Opus 5.5', note: 'default' },
14
14
  { id: 'sonnet', label: 'Sonnet 5.5' },
15
15
  // Pin the intended Haiku version instead of relying on the CLI alias.
16
- { id: 'claude-haiku-4-5', label: 'Haiku 4.5', note: 'lightest' },
16
+ { id: 'claude-haiku-5-5', label: 'Haiku 5.5', note: 'lightest' },
17
17
  ],
18
18
  codex: [
19
- { id: 'gpt-6-astra', label: 'GPT-6 Astra' },
20
- { id: 'gpt-6.1-sol', label: 'GPT-6.1 Sol' },
21
- { id: 'gpt-6-sol', label: 'GPT-6 Sol' },
19
+ { id: 'gpt-6.2-astra', label: 'GPT-6.2 Astra' },
20
+ { id: 'gpt-6.2-sol', label: 'GPT-6.2 Sol' },
22
21
  { id: 'gpt-6.1-terra', label: 'GPT-6.1 Terra' },
23
22
  // efforts: only where a model takes fewer levels than its vendor offers (`codex debug models`
24
23
  // supported_reasoning_levels: the Luna models stop at max)
@@ -41,16 +40,16 @@ export function modelsByCapability(models = []) {
41
40
 
42
41
  // The effort levels a model takes: its vendor's levels, narrowed where the table names fewer.
43
42
  // A model the table does not know (a typed id, the CLI default) keeps the vendor's levels.
44
- export function modelEfforts(vendor, model, levels = []) {
45
- const known = (MODELS[vendor] || []).find((m) => m.id === String(model || '').trim());
46
- return known?.efforts ? levels.filter((l) => known.efforts.includes(l)) : levels;
43
+ export function modelEfforts(vendor, model, levels = [], models = MODELS[vendor] || []) {
44
+ const known = models.find((m) => m.id === String(model || '').trim());
45
+ return known?.efforts || levels;
47
46
  }
48
47
 
49
48
  // Retired for ChatGPT sign-in: a call with one of these fails. id -> [date, replacement].
50
49
  export const RETIRED = {
51
50
  codex: {
52
- 'gpt-5.5': ['2026-10-14', 'gpt-6.1-sol'], 'gpt-5.4': ['2026-08-31', 'gpt-6-sol'], 'gpt-5.4-mini': ['2026-08-31', 'gpt-6-luna'],
53
- 'gpt-5.3-codex-spark': ['2026-09-14', 'gpt-6.1-sol'], 'gpt-5.3-codex': ['deprecated', 'gpt-6.1-sol'], 'gpt-5.2': ['deprecated', 'gpt-6.1-sol'],
51
+ 'gpt-5.5': ['2026-10-14', 'gpt-6.2-sol'], 'gpt-5.4': ['2026-08-31', 'gpt-6.2-sol'], 'gpt-5.4-mini': ['2026-08-31', 'gpt-6-luna'],
52
+ 'gpt-5.3-codex-spark': ['2026-09-14', 'gpt-6.2-sol'], 'gpt-5.3-codex': ['deprecated', 'gpt-6.2-sol'], 'gpt-5.2': ['deprecated', 'gpt-6.2-sol'],
54
53
  },
55
54
  };
56
55
 
@@ -60,17 +59,31 @@ export function retired(vendor, id) {
60
59
  }
61
60
 
62
61
  // agy ids carry the effort level ("gemini-4-argon-high"): one entry per model, the levels it has.
62
+ const levelOrder = ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'];
63
+ export const effortSuffix = /-(low|medium|high|xhigh|max|ultra)$/;
63
64
  export function agyFamilies(models = []) {
64
- const fam = new Map();
65
- for (const m of models) {
66
- const hit = /^(.*)-(low|medium|high)$/.exec(m.id);
67
- const id = hit ? hit[1] : m.id;
68
- const label = String(m.label || id).replace(/\s*\((low|medium|high)\)\s*$/i, '');
69
- if (!fam.has(id)) fam.set(id, { id, label, levels: [] });
70
- if (hit) fam.get(id).levels.push(hit[2]);
65
+ const families = new Map();
66
+ for (const { id, label = id } of models) {
67
+ // A future level can identify itself in the vendor label, e.g. "Neon (Deep)" / neon-deep.
68
+ const named = /\s*\(([a-z0-9_-]+)\)\s*$/i.exec(label);
69
+ const suffix = named?.[1].toLowerCase();
70
+ const level = suffix && id.endsWith(`-${suffix}`) ? suffix : effortSuffix.exec(id)?.[1];
71
+ const base = level ? id.slice(0, -level.length - 1) : id;
72
+ if (!families.has(base)) families.set(base, { id: base, label: level && named ? label.slice(0, named.index) : label, levels: [] });
73
+ const levels = families.get(base).levels;
74
+ if (level && !levels.includes(level)) levels.push(level);
71
75
  }
72
- const order = ['low', 'medium', 'high'];
73
- return [...fam.values()].map((f) => ({ ...f, levels: f.levels.sort((a, b) => order.indexOf(a) - order.indexOf(b)) }));
76
+ const rank = (level) => levelOrder.includes(level) ? levelOrder.indexOf(level) : levelOrder.length;
77
+ for (const family of families.values()) family.levels.sort((a, b) => rank(a) - rank(b));
78
+ return [...families.values()];
79
+ }
80
+ export function agyFamily(families, model) {
81
+ return families.find((f) => f.id === model) || families.find((f) => f.levels.some((level) => model === `${f.id}-${level}`));
82
+ }
83
+ export function agySelection(family, picked, effort) {
84
+ const levels = family?.levels || [];
85
+ const level = levels.includes(effort) ? effort : levels.includes('medium') ? 'medium' : levels[0];
86
+ return { model: level ? `${family.id}-${level}` : picked, effort: level || '' };
74
87
  }
75
88
 
76
89
  // agy's quota comes in groups, each with its own windows (quota.js agyQuota). Which group a model
@@ -11,7 +11,9 @@ const WIN = process.platform === 'win32';
11
11
  // without one, and a shell would mangle quoted prompt text).
12
12
  export function resolveBinary(name, npmBin, { platform = process.platform, env = process.env, exists = existsSync } = {}) {
13
13
  const P = platform === 'win32' ? path.win32 : path.posix;
14
- const dirs = (env.PATH || '').split(P.delimiter).filter(Boolean);
14
+ // Match Node's Windows environment handling, including duplicate-key ordering.
15
+ const pathKey = platform === 'win32' ? Object.keys(env).sort().find(key => key.toUpperCase() === 'PATH') || 'PATH' : 'PATH';
16
+ const dirs = (env[pathKey] || '').split(P.delimiter).filter(Boolean);
15
17
  const exts = platform === 'win32' ? ['.exe'] : [''];
16
18
  for (const dir of dirs) {
17
19
  for (const ext of exts) {