@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.
package/src/seats.js CHANGED
@@ -13,7 +13,7 @@ export const DEFAULT_MOOD = 'grill';
13
13
  // A custom mood matching a persona code uses its prompt, avatar and light model settings.
14
14
  // The server opts board requests into these shortcuts; ordinary API requests keep custom text.
15
15
  import { HIDDEN_MOODS } from './personas.js';
16
- import { modelEfforts } from './adapters/models.js';
16
+ import { modelEfforts, MODELS, effortSuffix } from './adapters/models.js';
17
17
  export { HIDDEN_MOODS } from './personas.js';
18
18
  export function hiddenMood(text) {
19
19
  const word = String(text || '').trim().toLowerCase();
@@ -41,14 +41,15 @@ export function filterReply(mood, text) {
41
41
  // The cheapest model each CLI offers (adapters/models.js marks claude's and codex's lightest).
42
42
  // agy: Flash-low over gpt-oss-120b-medium, measured on a hidden-mood prompt: the same input,
43
43
  // but gpt-oss wrote 1.7k-4k output tokens to Flash-low's ~190, and took two to four times longer.
44
- export const LIGHTEST = { claude: 'claude-haiku-4-5', codex: 'gpt-6-luna', agy: 'gemini-3.8-flash-low' };
44
+ export const LIGHTEST = { claude: MODELS.claude.find((m) => m.note === 'lightest').id, codex: MODELS.codex.find((m) => m.note === 'lightest').id, agy: 'gemini-3.8-flash-low' };
45
45
  // agy's list depends on the account (`agy models`): a Flash-Lite model, where offered, is lighter
46
46
  // than Flash, and a family's "-low" level is its lightest. LIGHTEST.agy when the list has neither.
47
47
  export function lightestModel(vendor, models = []) {
48
+ if (vendor === 'codex' && models.length) return models.find((m) => m.note === 'lightest')?.id;
48
49
  if (vendor !== 'agy') return LIGHTEST[vendor];
49
50
  const rank = (id) => (/flash-lite/.test(id) ? 0 : 3) + (/-low$/.test(id) ? 0 : /-medium$/.test(id) ? 1 : 2);
50
51
  const ids = models.map((m) => m?.id || m).filter((id) => /^gemini-.*flash/.test(String(id)));
51
- return ids.sort((a, b) => rank(a) - rank(b))[0] || LIGHTEST.agy;
52
+ return ids.sort((a, b) => rank(a) - rank(b))[0] || (models.length ? undefined : LIGHTEST.agy);
52
53
  }
53
54
 
54
55
  const STARTER_LENSES = ['risk and failure modes', 'cost and effort', 'evidence and assumptions',
@@ -90,15 +91,6 @@ export function seatSetupIssue(seats) {
90
91
  // Seat colours from the signature-design accent family, cycled when a table has more seats.
91
92
  export const COLOURS = ['rust', 'olive', 'teal', 'dusk', 'steel'];
92
93
 
93
- // First use starts small. Prefer ready default logins; one ready vendor can fill both seats.
94
- // With no ready result yet, show two editable CLI choices and their status lamps.
95
- export function initialSeatVendors(vendors, checks = []) {
96
- const cli = vendors.filter((v) => v.kind !== 'api' && v.kind !== 'acp').map((v) => v.vendor);
97
- const ready = cli.filter((v) => checks.some((p) => p.key === v && p.state === 'ok'));
98
- const choices = ready.length ? ready : cli;
99
- return choices.length ? [choices[0], choices[1] || choices[0]] : [];
100
- }
101
-
102
94
  // A profile name is a directory name under the roundtable data dir, so it is kept plain.
103
95
  // (Here rather than in adapters/spawn.js because this module also runs in the browser.)
104
96
  export const PROFILE_RE = /^[a-z0-9][a-z0-9_.-]{0,39}$/i;
@@ -131,6 +123,70 @@ export function agentLinkProfile(raw) {
131
123
  return name;
132
124
  }
133
125
 
126
+ // Provider shortcuts use AgentLink's conventional profile names. Custom profiles are always
127
+ // selectable by their exact name, including multiple accounts for the same provider.
128
+ export const PROFILE_PROVIDERS = { codex: 'codex', claude: 'claude', agy: 'antigravity' };
129
+ export function providerProfile(vendor, profiles) {
130
+ const matches = profiles.filter((p) => p.provider === PROFILE_PROVIDERS[vendor]);
131
+ return matches.find((p) => p.name === vendor) || (matches.length === 1 ? matches[0] : null);
132
+ }
133
+
134
+ // Conventional provider choices come first. A missing profile is offered for setup only
135
+ // if its name is free. A profile named "codex" can legitimately belong to another provider.
136
+ export function profileChoicesFor(profiles) {
137
+ const choices = [];
138
+ for (const vendor of Object.keys(PROFILE_PROVIDERS)) {
139
+ const selected = providerProfile(vendor, profiles);
140
+ if (selected) choices.push({ name: selected.name, vendor, configured: true });
141
+ else if (!profiles.some((p) => p.name === vendor || p.provider === PROFILE_PROVIDERS[vendor])) {
142
+ choices.push({ name: vendor, vendor, configured: false });
143
+ }
144
+ }
145
+ for (const p of profiles) {
146
+ if (!choices.some((c) => c.name === p.name)) choices.push({ name: p.name, configured: true });
147
+ }
148
+ return choices;
149
+ }
150
+
151
+ export function routeReviewProfiles(raw, profiles) {
152
+ if (!raw || typeof raw !== 'object') return raw;
153
+ const routed = new Map();
154
+ function card(seat) {
155
+ if (!seat || typeof seat !== 'object') return seat;
156
+ if (seat.transport != null && !['cli', 'agentlink'].includes(seat.transport)) throw new Error('Seat transport must be cli or agentlink.');
157
+ if (!Object.hasOwn(PROFILE_PROVIDERS, seat.vendor)) {
158
+ if (seat.transport != null) throw new Error('Set transport only on a named CLI provider.');
159
+ return seat;
160
+ }
161
+ if (seat.transport === 'cli') return seat;
162
+ const name = seat.account ? agentLinkProfile(seat.account) : providerProfile(seat.vendor, profiles)?.name;
163
+ if (!name || !profiles.some((p) => p.name === name && (!p.provider || p.provider === PROFILE_PROVIDERS[seat.vendor]))) {
164
+ throw new Error(`Choose a saved AgentLink profile for ${seat.vendor}, or create one with agentlink add ${seat.vendor} --provider ${PROFILE_PROVIDERS[seat.vendor]}. For a direct CLI seat set transport to "cli".`);
165
+ }
166
+ const names = routed.get(seat.vendor) || new Set();
167
+ names.add(name); routed.set(seat.vendor, names);
168
+ return { ...seat, vendor: 'acp', account: name };
169
+ }
170
+ const seats = Array.isArray(raw.seats) ? raw.seats.map(card) : raw.seats;
171
+ const chairman = card(raw.chairman);
172
+ const options = raw.options;
173
+ if (!options?.budget || typeof options.budget !== 'object' || Array.isArray(options.budget)) return { ...raw, seats, chairman };
174
+ const budget = { ...options.budget };
175
+ for (const [vendor, names] of routed) {
176
+ if (!Object.hasOwn(budget, vendor)) continue;
177
+ const direct = [...(Array.isArray(seats) ? seats : []), chairman].some((s) => s?.vendor === vendor)
178
+ || (options.research && (options.research.vendor || 'codex') === vendor);
179
+ if (direct && [...names].every((name) => Object.hasOwn(budget, 'acp@' + name))) continue;
180
+ if (direct || names.size !== 1) {
181
+ throw new Error(`Budget for ${vendor} covers different connections. Set separate caps using acp@PROFILE for each AgentLink profile.`);
182
+ }
183
+ const key = 'acp@' + [...names][0];
184
+ if (Object.hasOwn(budget, key)) throw new Error(`Duplicate budget for ${key}.`);
185
+ budget[key] = budget[vendor]; delete budget[vendor];
186
+ }
187
+ return { ...raw, seats, chairman, options: { ...options, budget } };
188
+ }
189
+
134
190
  // The one line a seat sees about how to approach the question. Custom text wins when given.
135
191
  export function moodLine(mood) {
136
192
  if (!mood) return MOODS[DEFAULT_MOOD];
@@ -233,6 +289,31 @@ function seatAccount(raw, row) {
233
289
  // vendors: { [vendor]: { label, effortLevels } } (the adapter table). efforts may widen a
234
290
  // vendor's levels from the catalogue (agy's come from its model ids); models is the
235
291
  // catalogue's model list per vendor, for the lightest model a hidden mood runs on.
292
+ // An ACP agent advertises its reasoning levels when a session opens, so the adapter checks a
293
+ // seat's effort against that list; here it is only a bounded identifier.
294
+
295
+ function checkEffort(raw, vendor, allowed, label) {
296
+ const effort = raw.effort ? String(raw.effort).trim() : null;
297
+ if (!effort) return null;
298
+ if (vendor.kind === 'acp') {
299
+ if (effort.length > 200 || /[\u0000-\u001f\u007f]/.test(effort)) throw new Error(`${label}: an ACP effort must be an advertised ID of at most 200 characters without control characters.`);
300
+ return effort;
301
+ }
302
+ if (!allowed.includes(effort)) throw new Error(`${label} does not accept effort "${effort}"${allowed.length ? ` (allowed: ${allowed.join(', ')})` : ''}.`);
303
+ return effort;
304
+ }
305
+
306
+ function validateAgyModel(vendor, model, models, label) {
307
+ if (vendor !== 'agy' || !model) return;
308
+ const id = String(model).trim();
309
+ const offered = models.agy || [];
310
+ if (offered.some((m) => (m.id || m) === id)) return;
311
+ const level = effortSuffix.exec(id);
312
+ if (offered.length || (level && effortSuffix.test(id.slice(0, level.index)))) {
313
+ throw new Error(`${label}: Antigravity model "${id}" is unavailable. Choose a model and one effort level from the picker.`);
314
+ }
315
+ }
316
+
236
317
  export function normaliseSeats(input, { vendors, efforts = {}, models = {}, hidden = false }) {
237
318
  const issue = seatSetupIssue((input || []).map((raw) => raw && vendors[raw.vendor] ? raw : null));
238
319
  if (issue) throw Object.assign(new Error(issue.message), issue, { status: 400 });
@@ -241,15 +322,15 @@ export function normaliseSeats(input, { vendors, efforts = {}, models = {}, hidd
241
322
  for (const raw of input || []) {
242
323
  if (!raw || !vendors[raw.vendor]) continue;
243
324
  const lens = String(raw.lens || '').trim();
244
- const allowed = modelEfforts(raw.vendor, raw.model, efforts[raw.vendor] || vendors[raw.vendor].effortLevels || []);
245
- const effort = raw.effort ? String(raw.effort).trim() : null;
246
- if (effort && !allowed.includes(effort)) throw new Error(`${vendors[raw.vendor].label}${raw.model ? ` ${String(raw.model).trim()}` : ''} does not accept effort "${effort}" (allowed: ${allowed.join(', ')}).`);
325
+ validateAgyModel(raw.vendor, raw.model, models, `Seat "${lens}"`);
326
+ const allowed = modelEfforts(raw.vendor, raw.model, efforts[raw.vendor] || vendors[raw.vendor].effortLevels || [], models[raw.vendor]);
327
+ const effort = checkEffort(raw, vendors[raw.vendor], allowed, `${vendors[raw.vendor].label}${raw.model ? ` ${String(raw.model).trim()}` : ''}`);
247
328
  perVendor[raw.vendor] = (perVendor[raw.vendor] || 0) + 1;
248
329
  // an endpoint seat: URL, model and key variable checked; its account is its host
249
330
  const ep = vendors[raw.vendor].kind === 'api' ? normaliseEndpoint(raw, `Seat "${lens}"`) : null;
250
331
  const mood = normaliseMood(raw.mood, { hidden });
251
332
  // a hidden mood always runs as cheaply as the seat's vendor allows
252
- const locked = mood.hidden ? { model: ep ? ep.model : lightestModel(raw.vendor, models[raw.vendor]) || (raw.model ? String(raw.model).trim() : undefined), effort: allowed[0] || undefined } : null;
333
+ const locked = mood.hidden ? { model: ep ? ep.model : vendors[raw.vendor].kind === 'acp' ? raw.model || undefined : lightestModel(raw.vendor, models[raw.vendor]), effort: allowed[0] || undefined } : null;
253
334
  seats.push({
254
335
  id: `seat-${seats.length}`,
255
336
  vendor: raw.vendor,
@@ -275,12 +356,12 @@ export function normaliseSeats(input, { vendors, efforts = {}, models = {}, hidd
275
356
  }
276
357
 
277
358
  // role: who the error names; the searcher's settings are checked here too
278
- export function normaliseChairman(raw, { vendors, efforts = {}, role = 'Chairman' }) {
359
+ export function normaliseChairman(raw, { vendors, efforts = {}, models = {}, role = 'Chairman' }) {
279
360
  const vendor = raw?.vendor && vendors[raw.vendor] ? raw.vendor : null;
280
361
  if (!vendor) return null;
281
- const allowed = modelEfforts(vendor, raw.model, efforts[vendor] || vendors[vendor].effortLevels || []);
282
- const effort = raw.effort ? String(raw.effort).trim() : null;
283
- if (effort && !allowed.includes(effort)) throw new Error(`${role}: ${vendors[vendor].label}${raw.model ? ` ${String(raw.model).trim()}` : ''} does not accept effort "${effort}".`);
362
+ validateAgyModel(vendor, raw.model, models, role);
363
+ const allowed = modelEfforts(vendor, raw.model, efforts[vendor] || vendors[vendor].effortLevels || [], models[vendor]);
364
+ const effort = checkEffort(raw, vendors[vendor], allowed, `${role}: ${vendors[vendor].label}${raw.model ? ` ${String(raw.model).trim()}` : ''}`);
284
365
  const ep = vendors[vendor].kind === 'api' ? normaliseEndpoint(raw, role) : null;
285
366
  return { vendor, colour: vendors[vendor].colour || undefined, model: ep ? ep.model : raw.model ? String(raw.model).trim() : undefined, effort: effort || undefined,
286
367
  account: ep ? ep.account : seatAccount(raw, vendors[vendor]), ...(ep ? { endpoint: ep.endpoint, keyEnv: ep.keyEnv } : {}) };
package/src/server.js CHANGED
@@ -7,13 +7,15 @@ import { readFile } from 'node:fs/promises';
7
7
  import path from 'node:path';
8
8
  import { fileURLToPath } from 'node:url';
9
9
  import { adapters, ADAPTERS, quotaReaders, poolsByAccount } from './adapters/index.js';
10
- import { agentLinkBinary } from './adapters/acp.js';
10
+ import { checkEphemeralCli } from './adapters/common.js';
11
+ import { agentLinkBinary, discoverProfile, inspectProfileSession, listProfiles } from './adapters/acp.js';
11
12
  import { profileHome, killAll, liveChildren, resolveBinary, runProcess, cleanEnv } from './adapters/spawn.js';
12
13
  import { checkPool, STATUS, endpointLamp, createPreflightCache } from './preflight.js';
13
14
  import { retired, quotaGroup } from './adapters/models.js';
14
15
  import { vendorCatalogue } from './adapters/catalogue.js';
15
16
  import { createDebate, DEFAULTS } from './engine.js';
16
- import { normaliseSeats, normaliseChairman, MOODS, COLOURS, poolKey, poolVendor, poolAccount, lightestModel } from './seats.js';
17
+ import { verifyResearchSources } from './source-check.js';
18
+ import { normaliseSeats, normaliseChairman, MOODS, COLOURS, poolKey, poolVendor, poolAccount, lightestModel, PROFILE_PROVIDERS, routeReviewProfiles } from './seats.js';
17
19
  import { slugFor, openDebateDir, rebuildDebate } from './store.js';
18
20
  import { exportDebate, validateTarget, decisionRecord } from './export.js';
19
21
  import { rollup, hasUsableRound } from './engine.js';
@@ -74,17 +76,43 @@ const termsRecord = createTermsRecord(TERMS_FILE, { adapters: ADAPTERS, onError:
74
76
  } });
75
77
  const termsHeld = (vendor, acknowledged = false) => !acknowledged && !termsRecord.acknowledged(vendor);
76
78
 
77
- // Model ids and effort levels per vendor. `agy models` is a network call, so it is read once in
78
- // the background at boot, or once Antigravity's terms notice is acknowledged; the setup screen
79
- // gets the static hints until it lands.
80
- let catalogue = null;
81
- const staticCatalogue = await vendorCatalogue({ agyModels: async () => [] });
82
- const readCatalogue = () => (FAKE || termsHeld('agy') ? vendorCatalogue({ agyModels: async () => [] }) : vendorCatalogue())
83
- .then((c) => { catalogue = c; return c; })
84
- .catch((e) => { diagnostics.write({ code: 'status-failed', action: 'catalogue' }, e); console.error('[catalogue]', e.message); return vendorCatalogue({ agyModels: async () => [] }).then((c) => (catalogue = c)); });
85
- let catalogueReady = readCatalogue();
86
- const effortsByVendor = () => Object.fromEntries(Object.entries(catalogue || staticCatalogue).map(([v, c]) => [v, c.efforts]));
87
- const modelsByVendor = () => Object.fromEntries(Object.entries(catalogue || staticCatalogue).map(([v, c]) => [v, c.models || []]));
79
+ // Direct catalogues are loaded only for a selected direct connection or searcher.
80
+ const emptyModels = async () => [];
81
+ const staticCatalogue = await vendorCatalogue({ agyModels: emptyModels, codexModels: emptyModels });
82
+ const catalogue = { ...staticCatalogue }, directReads = new Map();
83
+ async function directCatalogue(vendor) {
84
+ if (FAKE || !['agy', 'codex'].includes(vendor) || termsHeld(vendor)) return catalogue[vendor];
85
+ if (!directReads.has(vendor)) {
86
+ const read = vendorCatalogue(vendor === 'codex' ? { agyModels: emptyModels } : { codexModels: emptyModels })
87
+ .then((c) => { if (directReads.get(vendor) === read && !termsHeld(vendor)) catalogue[vendor] = c[vendor]; return catalogue[vendor]; })
88
+ .finally(() => { if (directReads.get(vendor) === read && !catalogue[vendor]?.models?.length) directReads.delete(vendor); });
89
+ directReads.set(vendor, read);
90
+ }
91
+ return directReads.get(vendor);
92
+ }
93
+ const effortsByVendor = () => Object.fromEntries(Object.entries(catalogue).map(([v, c]) => [v, c.efforts]));
94
+ const modelsByVendor = () => Object.fromEntries(Object.entries(catalogue).map(([v, c]) => [v, c.models || []]));
95
+
96
+ let listing;
97
+ function profileInventory() {
98
+ if (FAKE) return Promise.resolve({ profiles: Object.entries(PROFILE_PROVIDERS).map(([name, provider]) => ({ name, provider })) });
99
+ listing ??= listProfiles().then((profiles) => ({ profiles })).catch((e) => ({
100
+ profiles: [], error: e.code === 'ENOENT' ? 'Install AgentLink to use saved profiles.' : 'Could not read AgentLink profiles. Run agentlink list.',
101
+ })).finally(() => { listing = null; });
102
+ return listing;
103
+ }
104
+
105
+ async function reviewConnections(raw) {
106
+ const cards = [...(Array.isArray(raw?.seats) ? raw.seats : []), raw?.chairman];
107
+ const named = cards.some((s) => s && Object.hasOwn(PROFILE_PROVIDERS, s.vendor) && s.transport !== 'cli');
108
+ const inventory = named ? await profileInventory() : { profiles: [] };
109
+ if (inventory.error) throw new Error(inventory.error);
110
+ const routed = routeReviewProfiles(raw, inventory.profiles);
111
+ const direct = cards.filter((s) => s?.transport === 'cli').map((s) => s.vendor);
112
+ if (raw?.options?.research) direct.push(raw.options.research.vendor || 'codex');
113
+ await Promise.all([...new Set(direct)].map(directCatalogue));
114
+ return routed;
115
+ }
88
116
 
89
117
  // The quota picture. Baselines: tokens per call per vendor from every transcript on disk.
90
118
  // Calibration: how much of each vendor window one round took, measured between the quota
@@ -250,11 +278,16 @@ function loadDebate(slug) {
250
278
  // Continue an interrupted debate: the engine is recreated from the field-notes row (seats with
251
279
  // their recorded session ids, used when memory is 'resume') and runs from the first incomplete
252
280
  // round. A message belongs to the last complete round, or precedes round zero if none completed.
253
- function resumeDebate(d, body = {}) {
281
+ async function resumeDebate(d, body = {}) {
254
282
  recoverFailed(d);
255
283
  if (!d.interrupted) throw new Error(d.finished ? 'This debate is finished.' : 'This debate is running.');
256
- prepareTranscript(d);
257
284
  const rb = d.rebuilt;
285
+ if (!FAKE && rb.options?.providerHistory === 'require-ephemeral') {
286
+ // Recovery reuses saved evidence and never launches the searcher again.
287
+ await checkProviderSessions([...rb.seats, rb.chairman], rb.options.providerHistory);
288
+ if (!d.interrupted || debates.get(d.slug) !== d) throw new Error('This review changed while checking provider sessions. Refresh its status.');
289
+ }
290
+ prepareTranscript(d);
258
291
  const message = String(body.message || '').trim();
259
292
  if (message) {
260
293
  const round = rb.nextRound - 1;
@@ -296,18 +329,19 @@ const preflightCache = createPreflightCache({ check: (key) => {
296
329
  async function loginStatus(vendor, account) {
297
330
  if (FAKE) return true;
298
331
  const s = STATUS[vendor];
299
- if (!s) return (catalogue || await catalogueReady)?.[vendor]?.models?.length ? true : null; // agy: its model list answered
332
+ if (!s) return (await directCatalogue(vendor))?.models?.length ? true : null; // agy: its model list answered
300
333
  const home = account && ADAPTERS[vendor].home ? { env: ADAPTERS[vendor].home.env, dir: profileHome(vendor, account) } : null;
301
334
  try {
302
335
  const r = await runProcess(resolveBinary(ADAPTERS[vendor].binary, ADAPTERS[vendor].npmBin), s.args, { env: cleanEnv(home), timeoutMs: 20_000 });
303
- const out = `${r.stdout}\n${r.stderr}`;
304
- return s.plan ? { loggedIn: s.read(out), plan: s.plan(out) } : s.read(out);
336
+ const loggedIn = s.read(r.stdout, r.stderr);
337
+ return s.plan ? { loggedIn, plan: loggedIn ? s.plan(r.stdout) : null } : loggedIn;
305
338
  } catch (e) { diagnostics.write({ code: 'status-failed', action: 'preflight', vendor }, e); return null; }
306
339
  }
307
340
  // endpoints: { [key]: { url, keyEnv } } for API pools, from the board (POST only: it names a
308
341
  // variable of this process, so the launch token is required). No request leaves this server
309
342
  // for an endpoint pool (preflight.js endpointLamp).
310
343
  async function preflight(keys, { refresh = false, fresh = false, endpoints = {} } = {}) {
344
+ const inventory = refresh && !FAKE && keys.some((key) => poolVendor(key) === 'acp') ? await profileInventory() : null;
311
345
  return Promise.all(keys.map(async (key) => {
312
346
  const vendor = poolVendor(key), account = poolAccount(key);
313
347
  if (!Object.hasOwn(ADAPTERS, vendor)) return { key, state: 'danger', kind: 'missing', note: `unknown vendor ${vendor}` };
@@ -316,8 +350,12 @@ async function preflight(keys, { refresh = false, fresh = false, endpoints = {}
316
350
  if (FAKE) return { key, vendor, account, installed: null, loggedIn: null, quota: null, state: 'ok', kind: 'demo', note: 'Scripted demo; no AgentLink or vendor process is used' };
317
351
  try {
318
352
  agentLinkBinary();
353
+ if (inventory && account && !inventory.error && !inventory.profiles.some((p) => p.name === account)) {
354
+ const setup = Object.hasOwn(PROFILE_PROVIDERS, account) ? ` Run agentlink add ${account} --provider ${PROFILE_PROVIDERS[account]}.` : ' Choose a saved profile.';
355
+ return { key, vendor, account, installed: true, loggedIn: null, quota: null, state: 'danger', kind: 'missing', note: `AgentLink profile "${account}" is missing.${setup}` };
356
+ }
319
357
  return { key, vendor, account, installed: true, loggedIn: null, quota: null, state: 'warn', kind: 'unknown',
320
- note: account ? 'AgentLink found; profile, login and ACP support are checked on the first call' : 'Choose a saved AgentLink profile' };
358
+ note: !account ? 'Choose a saved AgentLink profile' : inventory?.error || (inventory ? 'Saved AgentLink profile. Sign-in and quota are unverified.' : 'Refresh status to check this AgentLink profile.') };
321
359
  } catch (e) { return { key, vendor, account, installed: false, loggedIn: null, quota: null, state: 'danger', kind: 'missing', note: e.message }; }
322
360
  }
323
361
  if (ADAPTERS[vendor].kind === 'api') {
@@ -346,7 +384,7 @@ async function listDebates() {
346
384
  if (row.state === 'corrupt') return row;
347
385
  const state = activeDebate(debates.get(row.slug)) ? 'running' : finished ? 'finished' : 'interrupted';
348
386
  return { ...row, state, status: state === 'finished' ? row.status : state,
349
- tokens: u.tokenCoverage?.reported === 0 ? null : u.input + u.cacheRead + u.cacheWrite + u.output,
387
+ tokens: u.tokenCoverage?.reported === 0 && !(u.input + u.cacheRead + u.cacheWrite + u.output) ? null : u.input + u.cacheRead + u.cacheWrite + u.output,
350
388
  tokensPartial: !!(u.tokenCoverage && u.tokenCoverage.reported < u.tokenCoverage.of),
351
389
  cost: u.cost, costPartial: !!(u.costCoverage && u.costCoverage.reported < u.costCoverage.of) };
352
390
  });
@@ -384,7 +422,7 @@ function deleteSessions(ids, finishedOnly = false) {
384
422
  // supersedes the old one.
385
423
  // body.chairman (optional): write it with another vendor, for example when the first chairman's
386
424
  // quota ran out. Checked like the setup screen's chairman.
387
- function synthesizeDebate(d, body = {}) {
425
+ async function synthesizeDebate(d, body = {}) {
388
426
  recoverFailed(d);
389
427
  if (!d.finished) throw new Error(d.interrupted ? 'This debate was interrupted; resume it first.' : 'This debate is still running.');
390
428
  if (d.synthesizing) throw new Error('The verdict is being written.');
@@ -394,9 +432,13 @@ function synthesizeDebate(d, body = {}) {
394
432
  let chairman = rb.chairman;
395
433
  if (body.chairman) {
396
434
  for (const k of ['vendor', 'model', 'effort', 'account', 'keyEnv', 'endpoint']) if (body.chairman[k] != null && (typeof body.chairman[k] !== 'string' || body.chairman[k].length > (k === 'endpoint' ? 500 : 200))) throw new Error(`chairman ${k}: text of at most ${k === 'endpoint' ? 500 : 200} characters`);
397
- chairman = normaliseChairman(body.chairman, { vendors: ADAPTERS, efforts: effortsByVendor() });
435
+ chairman = normaliseChairman(body.chairman, { vendors: ADAPTERS, efforts: effortsByVendor(), models: modelsByVendor() });
398
436
  if (!chairman) throw new Error('chairman vendor: one of ' + Object.keys(ADAPTERS).join(', '));
399
437
  }
438
+ if (!FAKE && rb.options?.providerHistory === 'require-ephemeral') {
439
+ await checkProviderSessions([chairman], rb.options.providerHistory);
440
+ if (!d.finished || d.synthesizing || debates.get(d.slug) !== d || rebuildDebate(d.store.readTranscript()).synthesis === 'done') throw new Error('This review changed while checking the chairman. Refresh its status.');
441
+ }
400
442
  prepareTranscript(d);
401
443
  d.synthesizing = true;
402
444
  d.finished = false;
@@ -476,7 +518,7 @@ function scheduleGate(d, duration, extended = false) {
476
518
  const cookie = (req, name) => (req.headers.cookie || '').split(/;\s*/).find((c) => c.startsWith(`${name}=`))?.slice(name.length + 1);
477
519
  let pickingFolder = false;
478
520
  const fromBoard = (req) => cookie(req, 'rt_board') === BOARD_COOKIE && ORIGINS.has(req.headers.origin || '') && req.headers['sec-fetch-site'] === 'same-origin';
479
- function prepareDebate(raw, { board = false } = {}) {
521
+ async function prepareDebate(raw, { board = false } = {}) {
480
522
  const body = validateDebateRequest(raw, { adapters: ADAPTERS });
481
523
  const fieldNotes = body.fieldNotes;
482
524
  if (fieldNotes.exportTo) fieldNotes.exportTo = validateTarget(fieldNotes.exportTo, { forbid: [DEBATES_DIR] }); // checked up front, not when the verdict lands
@@ -486,7 +528,7 @@ function prepareDebate(raw, { board = false } = {}) {
486
528
  const r = s?.model && retired(s.vendor, String(s.model).trim());
487
529
  if (r) throw new Error(`${ADAPTERS[s.vendor].label} retired ${s.model} (${r.date}); use ${r.instead}.`);
488
530
  }
489
- const chairman = normaliseChairman(body.chairman, { vendors: ADAPTERS, efforts: effortsByVendor() });
531
+ const chairman = normaliseChairman(body.chairman, { vendors: ADAPTERS, efforts: effortsByVendor(), models: modelsByVendor() });
490
532
  // the board sends acknowledgeTermsRisk once the person has acknowledged on a card; an agent must send it
491
533
  const unacknowledged = FAKE ? null : termsRefusal([...seats, chairman, body.options.research], body.options, ADAPTERS);
492
534
  if (unacknowledged) throw unacknowledged;
@@ -498,23 +540,49 @@ function prepareDebate(raw, { board = false } = {}) {
498
540
  // the board always names the searcher's settings, even "default"; an agent may leave them out
499
541
  const named = ['model', 'effort', 'account'].some((k) => raw?.options?.research && Object.hasOwn(raw.options.research, k));
500
542
  if (options.research) options.research = searcherSettings(options.research, named);
543
+ if (!FAKE) await checkProviderSessions([...seats, chairman, options.research], options.providerHistory);
501
544
  return { fieldNotes, seats, chairman, options };
502
545
  }
503
546
 
547
+ async function checkProviderSessions(participants, mode) {
548
+ const checks = new Map(), direct = new Set();
549
+ for (const s of participants.filter(Boolean)) {
550
+ if (s.vendor !== 'acp') {
551
+ if (mode === 'require-ephemeral') {
552
+ const adapter = ADAPTERS[s.vendor];
553
+ if (!adapter?.ephemeralHelp) throw new Error(`${adapter?.label || s.vendor} cannot confirm a non-saving session. Choose a compatible provider or change the provider chat history setting.`);
554
+ direct.add(adapter);
555
+ }
556
+ continue;
557
+ }
558
+ if (mode !== 'require-ephemeral' && !s.model && !s.effort) continue;
559
+ const key = JSON.stringify([s.account, s.model || '']);
560
+ if (!checks.has(key)) checks.set(key, { account: s.account, model: s.model || '', efforts: new Set() });
561
+ if (s.effort) checks.get(key).efforts.add(s.effort);
562
+ }
563
+ await Promise.all([...direct].map(adapter => checkEphemeralCli(adapter)));
564
+ await Promise.all([...checks.values()].map(async ({ account, model, efforts }) => {
565
+ const cat = await inspectProfileSession(account, model, {}, mode === 'require-ephemeral' ? mode : 'prefer-ephemeral');
566
+ if (model && !cat.models.some((m) => m.id === model)) throw new Error(`AgentLink profile ${account} no longer offers model ${model}. Refresh profile models or choose the profile default.`);
567
+ for (const effort of efforts) {
568
+ if (!cat.efforts.includes(effort)) throw new Error(`AgentLink profile ${account} does not offer effort ${effort} for ${model || 'its default model'}. Refresh profile models.`);
569
+ }
570
+ }));
571
+ }
572
+
504
573
  // The searcher runs on its own settings, checked like the chairman's. A request that names none
505
574
  // gets its vendor's lightest model at low effort: finding and quoting sources needs little reasoning.
506
575
  function searcherSettings(research, named) {
507
576
  const v = research.vendor;
508
577
  const efforts = effortsByVendor()[v] || ADAPTERS[v].effortLevels || [];
509
- const s = normaliseChairman({ vendor: v, model: named ? research.model : lightestModel(v, modelsByVendor()[v]), effort: named ? research.effort : efforts.includes('low') ? 'low' : undefined, account: research.account }, { vendors: ADAPTERS, efforts: effortsByVendor(), role: 'Searcher' });
578
+ const s = normaliseChairman({ vendor: v, model: named ? research.model : lightestModel(v, modelsByVendor()[v]), effort: named ? research.effort : efforts.includes('low') ? 'low' : undefined, account: research.account }, { vendors: ADAPTERS, efforts: effortsByVendor(), models: modelsByVendor(), role: 'Searcher' });
510
579
  const gone = s.model && retired(v, s.model);
511
580
  if (gone) throw Object.assign(new Error(`Searcher: ${ADAPTERS[v].label} retired ${s.model} (${gone.date}); use ${gone.instead}.`), { status: 400 });
512
581
  const { model, effort, account, ...rest } = research;
513
582
  return { ...rest, ...(s.model ? { model: s.model } : {}), ...(s.effort ? { effort: s.effort } : {}), ...(s.account ? { account: s.account } : {}) };
514
583
  }
515
584
 
516
- function startDebate(raw, opts) {
517
- const { fieldNotes, seats, chairman, options } = prepareDebate(raw, opts);
585
+ function startDebate({ fieldNotes, seats, chairman, options }) {
518
586
  const slug = slugFor(fieldNotes.decision, DEBATES_DIR);
519
587
  const store = openDebateDir(DEBATES_DIR, slug);
520
588
  const d = { slug, gen: Date.now(), events: [], clients: new Set(), pending: null, timer: null, store, qAtRound: {}, settled: new Set(), interrupted: false, finished: false };
@@ -572,6 +640,7 @@ function attachEngine(d, { fieldNotes, seats, chairman, options, resume = null,
572
640
  acknowledgeTermsRisk: opts.acknowledgeTermsRisk === true || termsRecord.acknowledged(vendor),
573
641
  research: opts.research,
574
642
  keepSession: opts.keepSession === true,
643
+ providerHistory: opts.providerHistory,
575
644
  minimal: !!opts.seat?.mood?.hidden, // a hidden mood runs as cheaply as its vendor allows
576
645
  });
577
646
  // After every reply the vendor's quota is read again (not awaited) where a free read exists, so
@@ -596,6 +665,7 @@ function attachEngine(d, { fieldNotes, seats, chairman, options, resume = null,
596
665
 
597
666
  d.debate = createDebate({
598
667
  fieldNotes, seats, chairman, options, runner, gate, store, resume, baselines, provenance: FAKE ? { fake: true } : {}, synthesisOnly,
668
+ verifySources: FAKE ? undefined : verifyResearchSources,
599
669
  // agy: the limit group a seat's model draws on, from the latest quota read, so a used-up
600
670
  // group benches only its own seats; null for a vendor with one set of limits
601
671
  limitGroup: (seat) => quotaGroup(quota[keyOf(seat.vendor, seat.account)]?.groups, seat.model),
@@ -724,7 +794,7 @@ const server = http.createServer(async (req, res) => {
724
794
  const html = (await readFile(path.join(UI, 'index.html'), 'utf8'))
725
795
  .replace('<meta name="roundtable-token" content="">', `<meta name="roundtable-token" content="${TOKEN}">`)
726
796
  .replace('<span class="end" id="st-version"></span>', `<span class="end" id="st-version">v${VERSION}</span>`);
727
- res.writeHead(200, { 'content-type': MIME['.html'], 'cache-control': 'no-store', 'set-cookie': `rt_board=${BOARD_COOKIE}; HttpOnly; SameSite=Strict; Path=/` });
797
+ res.writeHead(200, { 'content-type': MIME['.html'], 'cache-control': 'no-store', 'x-roundtable-version': VERSION, 'set-cookie': `rt_board=${BOARD_COOKIE}; HttpOnly; SameSite=Strict; Path=/` });
728
798
  return res.end(html);
729
799
  }
730
800
  if (req.method === 'GET' && p.startsWith('/ui/')) return serveFile(res, path.join(UI, path.normalize(p.slice(4))));
@@ -732,9 +802,9 @@ const server = http.createServer(async (req, res) => {
732
802
  if (req.method === 'GET' && p.startsWith('/src/') && p.endsWith('.js')) return serveFile(res, path.join(ROOT, path.normalize(p)));
733
803
 
734
804
  if (req.method === 'GET' && p === '/api/seats') {
735
- const cat = catalogue || (url.searchParams.get('cached') === '1' ? staticCatalogue : await catalogueReady);
805
+ const cat = catalogue;
736
806
  return json(res, 200, {
737
- runtime: { mode: FAKE ? 'demo' : 'live', dataDir: DEBATES_DIR, cataloguePending: !catalogue, ...(legacyDataDirs.length ? { legacyDataDirs } : {}), diagnostics: diagnostics.status() },
807
+ runtime: { mode: FAKE ? 'demo' : 'live', dataDir: DEBATES_DIR, cataloguePending: false, ...(legacyDataDirs.length ? { legacyDataDirs } : {}), diagnostics: diagnostics.status() },
738
808
  vendors: Object.entries(ADAPTERS).map(([vendor, a]) => ({
739
809
  vendor, kind: a.kind, label: a.label, colour: a.colour, usageUrl: a.usageUrl || null, quota: quota[vendor] || null, profiles: poolsByAccount(a), limitedIsolation: a.limitedIsolation === true, search: !!a.research,
740
810
  terms: termsRecord.status(vendor), pool: a.pool, catalogue: cat[vendor],
@@ -768,7 +838,9 @@ const server = http.createServer(async (req, res) => {
768
838
  if (typeof body?.acknowledged !== 'boolean') throw new Error('acknowledged must be true or false.');
769
839
  const terms = termsRecord.set(tm[1], body.acknowledged);
770
840
  console.log(`[terms] ${ADAPTERS[tm[1]].label} terms notice ${body.acknowledged ? 'acknowledged on the board' : 'acknowledgment withdrawn'}`);
771
- if (body.acknowledged) { catalogueReady = readCatalogue(); await catalogueReady; refreshQuota(tm[1]); }
841
+ directReads.delete(tm[1]);
842
+ catalogue[tm[1]] = staticCatalogue[tm[1]];
843
+ if (body.acknowledged) { await directCatalogue(tm[1]); refreshQuota(tm[1]); }
772
844
  return json(res, 200, { terms, catalogue: catalogue?.[tm[1]] || null });
773
845
  }
774
846
  if (req.method === 'GET' && p === '/api/debates') return json(res, 200, { debates: await listDebates(), usage: usageStore.summary(FAKE) });
@@ -788,11 +860,27 @@ const server = http.createServer(async (req, res) => {
788
860
  try { const chosen = await pickFolder(); return json(res, 200, chosen ? { path: chosen } : { cancelled: true }); }
789
861
  finally { pickingFolder = false; }
790
862
  }
863
+ if (req.method === 'POST' && p === '/api/profiles') {
864
+ await readBody(req);
865
+ return json(res, 200, await profileInventory());
866
+ }
867
+ if (req.method === 'POST' && p === '/api/direct-models') {
868
+ const { vendor } = await readBody(req);
869
+ if (!Object.hasOwn(PROFILE_PROVIDERS, vendor)) throw new Error('Choose a direct CLI provider.');
870
+ return json(res, 200, await directCatalogue(vendor));
871
+ }
872
+ if (req.method === 'POST' && p === '/api/profile-models') {
873
+ const body = await readBody(req);
874
+ if (FAKE) throw new Error('Profile discovery is available in live mode.');
875
+ if (body.allowLimitedIsolation !== true) throw new Error('Select a trusted AgentLink profile and accept limited isolation to read its models.');
876
+ return json(res, 200, await discoverProfile(body.account, body.model));
877
+ }
791
878
  if (req.method === 'POST' && p === '/api/preview') {
792
- const plan = prepareDebate(await readBody(req), { board: fromBoard(req) });
879
+ const body = await reviewConnections(await readBody(req));
880
+ const plan = await prepareDebate(body, { board: fromBoard(req) });
793
881
  return json(res, 200, { valid: true, mode: FAKE ? 'demo' : 'live',
794
882
  plannedCalls: plan.seats.length * (plan.options.critiqueRounds + 1) + 1 + (plan.options.research ? 1 : 0),
795
- projection: project({ seats: plan.seats, chairman: plan.chairman || { vendor: plan.seats[0].vendor }, critiqueRounds: plan.options.critiqueRounds, memory: plan.options.memory, research: plan.options.research, baselines }),
883
+ projection: project({ seats: plan.seats, chairman: plan.chairman || (plan.seats[0].vendor === 'acp' ? plan.seats[0] : { vendor: plan.seats[0].vendor }), critiqueRounds: plan.options.critiqueRounds, memory: plan.options.memory, research: plan.options.research, baselines }),
796
884
  note: 'Estimate before retries. Checking does not start a review or call a model.' });
797
885
  }
798
886
  if (p === '/api/preflight' && (req.method === 'GET' || req.method === 'POST')) {
@@ -807,8 +895,8 @@ const server = http.createServer(async (req, res) => {
807
895
  return json(res, 200, { pools: await preflight(keys, { refresh, fresh: body.fresh === true, endpoints }) });
808
896
  }
809
897
  if (req.method === 'POST' && p === '/api/debates') {
810
- const body = await readBody(req);
811
- return json(res, 200, { slug: startDebate(body, { board: fromBoard(req) }) });
898
+ const body = await reviewConnections(await readBody(req));
899
+ return json(res, 200, { slug: startDebate(await prepareDebate(body, { board: fromBoard(req) })) });
812
900
  }
813
901
  const m = p.match(/^\/api\/debates\/([^/]+)\/(events|state|continue|finish|stop|hold|resume|export|synthesize|accept)$/);
814
902
  if (m) {
@@ -859,8 +947,8 @@ const server = http.createServer(async (req, res) => {
859
947
  body.message = validateMessage({ message: answerMessage(d.pending.info.questions, body.answers, body.message, { attributed: body.source === 'agent' && !relayed }) }).message;
860
948
  if (relayed) body.source = 'relayed';
861
949
  }
862
- if (m[2] === 'resume') { resumeDebate(d, body); return json(res, 200, { ok: true }); }
863
- if (m[2] === 'synthesize') { synthesizeDebate(d, body); return json(res, 200, { ok: true }); }
950
+ if (m[2] === 'resume') { await resumeDebate(d, body); return json(res, 200, { ok: true }); }
951
+ if (m[2] === 'synthesize') { await synthesizeDebate(d, await reviewConnections(body)); return json(res, 200, { ok: true }); }
864
952
  if (m[2] === 'accept') return json(res, 200, acceptDecision(d, body));
865
953
  if (m[2] === 'export') {
866
954
  if (!d.finished) return requestError(res, 400, 'Export after the verdict; the record needs the whole debate.', 'export');
@@ -913,8 +1001,7 @@ server.listen(PORT, '127.0.0.1', () => {
913
1001
  process.stdout.write(terminalBanner());
914
1002
  console.log(`roundtable${FAKE ? ' (fake seats)' : ''}: ${url} token ${TOKEN}`);
915
1003
  console.log(`mode: ${FAKE ? 'demo (scripted replies and usage)' : 'live'}; data: ${DEBATES_DIR}`);
916
- const found = Object.entries(ADAPTERS).filter(([v, a]) => a.kind === 'cli' && installed(v)).map(([, a]) => paintVendor(a));
917
- if (!FAKE) console.log(found.length ? `providers: ${found.join(', ')} (CLIs on PATH; an API endpoint is seated on the board)` : 'providers: no Claude, Codex or Antigravity CLI on PATH; seat an API endpoint on the board, or install one and restart. roundtable doctor has details');
1004
+ if (!FAKE) console.log('providers: AgentLink profiles for seats and chairman. The board lists saved profiles and offers direct connections.');
918
1005
  console.log('diagnostics: _diagnostics in the data folder; use Save error log on the board. Nothing is uploaded.');
919
1006
  console.log(`${opened ? 'the board is open in your browser' : `open ${url} in your browser`}; Ctrl+C here stops the server and every CLI it started`);
920
1007
  });
@@ -942,4 +1029,4 @@ process.on('SIGINT', () => shutdown('SIGINT'));
942
1029
  process.on('SIGTERM', () => shutdown('SIGTERM'));
943
1030
  process.on('uncaughtException', (e) => { diagnostics.write({ code: 'server-crash', action: 'unknown' }, e); console.error('[server] uncaught:', e); shutdown('uncaught error', 1); });
944
1031
  process.on('unhandledRejection', (e) => { diagnostics.write({ code: 'server-crash', action: 'unknown' }, e); console.error('[server] unhandled rejection:', e); });
945
- for (const vendor of Object.keys(readers)) refreshQuota(vendor); // one read each at start: claude and agy -p /usage, the codex app-server; agy only once its terms notice is acknowledged
1032
+ if (FAKE) for (const vendor of Object.keys(readers)) refreshQuota(vendor);
package/src/snapshot.js CHANGED
@@ -2,7 +2,7 @@ import { rollup, hasUsableRound, DEFAULTS } from './engine.js';
2
2
  import { groupQuestions, stopExplanation, cancellationReason } from './review-view.js';
3
3
  import { optionLabel, verdictSections } from './contract.js';
4
4
  import { safeProgress } from './progress.js';
5
- import { researchSources } from './research.js';
5
+ import { researchSources, checkedCounts } from './research.js';
6
6
 
7
7
  const RESEARCH_FAILURES = {
8
8
  timeout: 'Research did not finish before its time limit.',
@@ -29,14 +29,14 @@ function researchSnapshot(research) {
29
29
  try {
30
30
  const gatheredAt = new Date(research.gatheredAt).toISOString();
31
31
  if (gatheredAt !== research.gatheredAt || !integerWithin(research.searches, 1, 8)) throw new Error('invalid metadata');
32
- return { status: 'done', gatheredAt, searches: research.searches,
32
+ return { status: 'done', gatheredAt, searches: research.searches, ...checkedCounts(research.verification),
33
33
  sources: researchSources(JSON.stringify({ sources: research.sources }), gatheredAt) };
34
34
  } catch { return { status: 'failed', errorKind: 'format', error: RESEARCH_FAILURES.format }; }
35
35
  }
36
36
  const errorKind = research.status === 'interrupted' ? 'interrupted'
37
37
  : Object.hasOwn(RESEARCH_FAILURES, research.errorKind) ? research.errorKind : 'other';
38
38
  return { status: research.status === 'interrupted' ? 'interrupted' : 'failed', errorKind,
39
- error: RESEARCH_FAILURES[errorKind], progress: safeProgress(research.progress),
39
+ error: research.verification && errorKind === 'format' ? 'No cited page passed the source checks.' : RESEARCH_FAILURES[errorKind], progress: safeProgress(research.progress), ...checkedCounts(research.verification),
40
40
  ...(integerWithin(research.searches, 0, 9) ? { searches: research.searches } : {}) };
41
41
  }
42
42
 
@@ -95,6 +95,7 @@ export function reviewSnapshot(d) {
95
95
  verdict: verdict ? { status: verdict.skipped ? 'skipped' : verdict.failed ? 'failed' : 'ready',
96
96
  ...(sections ? { sections: Object.fromEntries(Object.entries(sections).map(([key, lines]) => [key, lines.filter((x) => x.trim()).join('\n')])) } : { reason: verdict.reason || verdict.errorKind || 'format' }) } : null,
97
97
  usage: { input: usage.input, cacheRead: usage.cacheRead, cacheWrite: usage.cacheWrite, output: usage.output,
98
+ ...(usage.providerTotal != null ? { providerTotal: usage.providerTotal, providerTotalCoverage: usage.providerTotalCoverage } : {}),
98
99
  cost: usage.cost, tokenCoverage: usage.tokenCoverage, costCoverage: usage.costCoverage },
99
100
  };
100
101
  }