@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.
@@ -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);
@@ -184,12 +185,13 @@ export const ADAPTERS = {
184
185
  resume: (id, base) => [...base, '--resume', id],
185
186
  // without it every seat call left a session, prompts included, under ~/.claude/projects
186
187
  ephemeral: ['--no-session-persistence'],
188
+ ephemeralHelp: ['--help'],
187
189
  model: (m) => ['--model', m],
188
190
  effort: (e) => ['--effort', e],
189
191
  effortLevels: ['low', 'medium', 'high'], // `claude --help`: "--effort <level>"
190
- // Request no extended-thinking budget for hidden-mood seats, which select Haiku 4.5.
192
+ // Request no extended-thinking budget for hidden-mood seats, which select Haiku.
191
193
  minimalEnv: { MAX_THINKING_TOKENS: '0' },
192
- modelHints: ['opus', 'sonnet', 'claude-haiku-4-5'], // use the explicit Haiku model id
194
+ modelHints: [], // direct CLI fallback in models.js
193
195
  pool: 'Anthropic subscription',
194
196
  promptVia: 'stdin',
195
197
  output: 'jsonl',
@@ -255,6 +257,7 @@ export const ADAPTERS = {
255
257
  ...CODEX_ISOLATION, '-c', 'sandbox_mode="read-only"', '-c', 'project_doc_max_bytes=0', ...CODEX_NO_TOOLS, ...CODEX_NO_TELEMETRY, ...CODEX_RUNTIME, '-'],
256
258
  // without it every seat call left a session file, prompts included, under ~/.codex/sessions
257
259
  ephemeral: ['--ephemeral'],
260
+ ephemeralHelp: ['exec', '--help'],
258
261
  completionGraceMs: 1000,
259
262
  // Replace the coding-agent base prompt: these calls review decisions, not repositories.
260
263
  // The CLI tool restrictions and the wrapper's stream guard still apply independently.
@@ -275,7 +278,7 @@ export const ADAPTERS = {
275
278
  // CLI effort vocabulary; availability depends on the selected model and installed CLI.
276
279
  // ~/.codex/config.toml is not a source: --ignore-user-config keeps it from the seat.
277
280
  effortLevels: ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'],
278
- modelHints: [], // curated capability and plan hints in models.js; no catalogue refresh at startup
281
+ modelHints: [], // catalogue.js reads the CLI listing and falls back to models.js
279
282
  pool: 'ChatGPT subscription',
280
283
  promptVia: 'stdin',
281
284
  output: 'jsonl',
@@ -350,11 +353,9 @@ export const ADAPTERS = {
350
353
  resume: (id, base) => [...base, '--conversation', id],
351
354
  model: (m) => ['--model', m],
352
355
  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
356
+ // Listed variants carry their own level. Discovery adds any new advertised levels.
357
+ effortLevels: ['low', 'medium', 'high', 'xhigh', 'max'],
358
+ effortInModel: effortSuffix,
358
359
  modelHints: [], // filled from `agy models` (catalogue.js)
359
360
  // `/usage`: limits per model group (Gemini; Claude and GPT; Gemini 4 Argon on some plans),
360
361
  // each with a weekly and usually a 5-hour window; AI credits, when enabled, take over after.
@@ -372,6 +373,7 @@ export const ADAPTERS = {
372
373
  sessionId: 'conversation_id',
373
374
  input: 'usage.input_tokens',
374
375
  cacheRead: 'usage.cache_read_tokens',
376
+ total: 'usage.total_tokens',
375
377
  cacheWrite: null,
376
378
  output: 'usage.output_tokens',
377
379
  thinking: 'usage.thinking_tokens',
@@ -386,6 +388,8 @@ export const ADAPTERS = {
386
388
  // stays the seat's. A tool step's ACTIVE and DONE updates share its step_index.
387
389
  research: {
388
390
  args: (args) => args,
391
+ searchHint: ({ maxSearches }) => maxSearches === 1 ? 'Plan one focused search and answer from its results.'
392
+ : 'Plan independent queries first and request them together in one model response. Finish from that batch unless a material evidence gap requires a follow-up within the limit.',
389
393
  searchIds: (e) => {
390
394
  const names = agyToolNames(e), i = e?.step_update?.step_index;
391
395
  return names.length === 1 && names[0] === AGY_SEARCH ? [Number.isSafeInteger(i) ? `step-${i}` : null] : [];
@@ -424,7 +428,7 @@ export const ADAPTERS = {
424
428
  },
425
429
  acp: {
426
430
  kind: 'acp', label: 'AgentLink (ACP)', binary: 'agentlink',
427
- npmBin: ['@local/agentlink', 'src/cli.mjs'],
431
+ npmBin: ['@prplkane/agentlink', 'src/cli.mjs'],
428
432
  args: [], resume: null, model: null, effort: null, home: null,
429
433
  effortLevels: [], modelHints: [], paths: { cost: null, quota: null },
430
434
  quota: null, usageUrl: null, colour: 'dusk', limitedIsolation: true,
@@ -107,6 +107,7 @@ export function pickUsage(u) {
107
107
  }
108
108
 
109
109
  export async function run(prompt, sessionId = null, opts = {}) {
110
+ if (opts.providerHistory === 'require-ephemeral') throw new Error('This API endpoint cannot confirm a non-saving session.');
110
111
  const t0 = Date.now(), timeoutMs = opts.timeoutMs ?? 300_000;
111
112
  let firstOutputMs, lastOutputAt = t0, stdoutBytes = 0, stage = 'waiting';
112
113
  const progress = (outcome) => safeProgress({ elapsedMs: Date.now() - t0, timeoutMs, firstOutputMs,
@@ -174,5 +175,5 @@ export async function run(prompt, sessionId = null, opts = {}) {
174
175
  if (usedTools) throw fail('reported prohibited tool activity. This seat is stopped for the review.', { code: 'TOOL_POLICY', kind: 'policy', usedTools: true, usage });
175
176
  if (!reply && !usedTools) throw fail(`empty reply (finish_reason ${data?.choices?.[0]?.finish_reason || 'unknown'}).`, { raw, usage });
176
177
  stage = 'completed';
177
- return { text: reply, usage, sessionId: null, quota: null, usedTools, raw, progress: progress('exited') };
178
+ return { text: reply, usage, sessionId: null, quota: null, usedTools, raw, progress: { ...progress('exited'), providerHistory: 'provider-managed' } };
178
179
  }
@@ -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) {
@@ -1,10 +1,12 @@
1
1
  import { LIMITS } from './validate.js';
2
+ import { PROFILE_PROVIDERS, providerProfile } from './seats.js';
2
3
  import { localClient } from './local-http.js';
3
4
 
4
5
  export const HELP = {
5
- usage: 'roundtable agent <status|check|start|wait|answer|hold|finish|stop|resume|verdict> [--port 4747] [--id review-id] [--input file|-] [--seconds 25] [--after-round round] [--refresh]',
6
+ usage: 'roundtable agent <status|models|check|start|wait|answer|hold|finish|stop|resume|verdict> [--port 4747] [--id review-id] [--input file|-] [--seconds 25] [--after-round round] [--refresh]',
6
7
  commands: {
7
- status: 'Without --id: cached provider setup. With --id: current step, questions, latest positions and verdict. --refresh refreshes free CLI status checks.',
8
+ status: 'Without --id: cached provider setup. With --id: current step, questions, latest positions and verdict. --refresh checks saved AgentLink profile availability without opening sessions.',
9
+ models: 'Read advertised model and effort names, IDs and saved profile defaults without sending a prompt. Supply --input with account, allowLimitedIsolation: true and an optional model.',
8
10
  check: 'Validate --input and estimate calls/tokens without creating a review.',
9
11
  start: 'Start the review in --input. Uses the selected providers. Returns its id immediately.',
10
12
  wait: 'Wait up to --seconds (1–30) for a question or completion. After presenting questions, use --after-round N to wait for the next step without asking the same questions again. Returns one state object, not an event log.',
@@ -15,7 +17,8 @@ export const HELP = {
15
17
  resume: 'Resume an interrupted review. May make provider calls.',
16
18
  verdict: 'Request a missing or failed verdict from saved replies. May make a provider call.',
17
19
  },
18
- acp: 'To use a saved AgentLink profile, select vendor="acp" and account="profile-name" for each seat and the chairman. Requires stateless memory and allowLimitedIsolation=true after the person accepts profile-owned permissions, customization and billing. Roundtable denies client tools and stops reported tool activity. AgentLink must already be installed/configured. Missing token usage stays unknown and stops further calls for that seat under its cap; no live quota is inferred.',
20
+ providerHistory: 'options.providerHistory defaults to prefer-ephemeral. Choose require-ephemeral with stateless memory to verify every selected provider before sending any review prompt. Choose provider-default to let each provider retain chats normally. Usage details show the outcome.',
21
+ acp: 'Codex, Claude and Antigravity seats and chairmen default to AgentLink. Bare vendor codex, claude or agy selects its saved profile. For an exact profile, select vendor="acp" and account="profile-name" for each seat and the chairman. Requires stateless memory and allowLimitedIsolation=true after the person accepts profile-owned permissions, customization and billing. Roundtable denies client tools and stops reported tool activity. AgentLink must already be installed/configured. Set transport=cli explicitly for direct CLI seats. Missing token usage stays unknown and stops further calls for that seat under its cap; no live quota is inferred.',
19
22
  setup: 'Use roundtable server status to inspect the local board; roundtable server start launches it hidden if needed (add --fake for a free test). After an update, server restart refuses active reviews. This client reads its launch token locally; it never prints or stores the token.',
20
23
  input: 'check/start accept the same {fieldNotes,seats,chairman,options} JSON as the board. Check available providers first. Every result with an id carries board, a link where a person can watch the review in a browser; offer it, do not open it.',
21
24
  recipe: {
@@ -24,12 +27,12 @@ export const HELP = {
24
27
  completion: 'A start acknowledgement or seat positions are not a completed review. Keep waiting through status running and verdict until status done and verdict.status ready. If interrupted, failed, skipped or missing, report that limitation instead of supplying your own chairman result. Include the review id, board link and depth.completedCritiqueRounds in the final report.',
25
28
  lenses: 'Give every seat a different lens, taken from what the decision could get wrong: risk, cost, evidence, reversibility, long-term effects, user impact. Two seats with one lens mostly agree, which wastes a call.',
26
29
  moods: 'Pair one sceptical seat (grill) with one practical seat (builder). Use steelman when the user already leans one way, contrarian when the seats would otherwise agree too early.',
27
- effort: 'effort low and the lightest model in status for the seats of a small review. Give the chairman one effort step more than the seats (medium when they run low): it judges the arguments, and at low effort it dismisses the hardest objection in a word. Raise one seat, not all, when the decision is hard to reverse.',
30
+ effort: 'Leave model and effort blank to follow the profile defaults. To pin a model or reasoning level, show the names reported by roundtable_models and send the corresponding IDs. Shared defaults are managed with agentlink defaults PROFILE.',
28
31
  context: 'constraints, known, assumed, reversibility and deadline go into every prompt. Fill them only with facts the user stated; put guesses under assumed, never under known. Leave a field empty rather than invent it.',
29
32
  unattended: 'Use options.unattended true for a background job with nobody to answer: it skips all pauses and keeps missing facts as assumptions. Live chat or browser reviews leave it false: ordinary checkpoints last autoContinueMs (15 seconds by default), questions last questionWaitMs (2 minutes). No answer continues automatically, without accepting a recommendation. Both modes respect the review wall clock.',
30
- isolation: 'Live Antigravity requires options.allowLimitedIsolation=true. Set it only when the user has agreed to its limits: session rules deny documented tools, but the CLI cannot disable all shared customizations or MCP discovery. Choose another provider otherwise. Reported prohibited tool activity still stops the seat.',
31
- terms: 'Live Antigravity also requires options.acknowledgeTermsRisk=true, for every seat, chairman or searcher on agy. Google\'s Antigravity FAQ says wrapping agy in third-party applications is not supported under consumer plans and that third-party access can get the account suspended or terminated. Show the person providers[].terms.notice and its url from status, and set the option only when they have agreed for this review; an acknowledgment on the board does not answer for an agent request. Choose another provider otherwise.',
32
- research: 'Only when the user requests web research: options.research={query:"public search question",maxSearches:4,timeoutMs:120000}. Adds one fresh CLI call, the searcher, before discussion; only this query goes into research. Optional vendor ("codex", "claude" or "agy"; default "codex"; agy also needs allowLimitedIsolation and acknowledgeTermsRisk), model, effort and account set the searcher; without model and effort it runs that vendor\'s lightest model at low effort on the default login. All seats receive the same saved provider-supplied sources. Reported search operations are bounded, but an operation may start before its report arrives. Failed or interrupted research never reruns automatically.',
33
+ isolation: 'AgentLink seats and direct Antigravity require options.allowLimitedIsolation=true. Set it only when the user has agreed to its limits: session rules deny documented tools, but the CLI cannot disable all shared customizations or MCP discovery. Choose another provider otherwise. Reported prohibited tool activity still stops the seat.',
34
+ terms: 'Direct Antigravity also requires options.acknowledgeTermsRisk=true, for every seat, chairman or searcher on agy. Google\'s Antigravity FAQ says wrapping agy in third-party applications is not supported under consumer plans and that third-party access can get the account suspended or terminated. Show the person directProviders[].terms.notice and its url from status, and set the option only when they have agreed for this review; an acknowledgment on the board does not answer for an agent request. Choose another provider otherwise.',
35
+ research: 'Only when the user requests web research: options.research={query:"public search question",timeoutMs:120000}. Adds one fresh CLI call, the searcher, before discussion; the searcher receives the query and optional sourceScopes (up to eight HTTPS host or path prefixes). Optional vendor ("codex", "claude" or "agy"; default "codex"; agy also needs allowLimitedIsolation and acknowledgeTermsRisk), model, effort and account set the searcher; without model and effort it runs that vendor\'s lightest model at low effort on the default login. The maxSearches default is two for Antigravity and four for other CLIs. Roundtable checks public page text and scope before sharing the same saved excerpts with all seats. A token cap includes cache reads and writes. Reported search operations are bounded, but an operation may start before its report arrives. Failed or interrupted research never reruns automatically.',
33
36
  agreement: 'When gate.reopenCalls is present, every seat already agrees. Empty answers and no message go straight to the verdict. Any answer text or message runs one more round at reopenCalls calls. Send text only if it could change a seat\'s position; a fact that confirms what the seats already said is better left for the verdict.',
34
37
  },
35
38
  };
@@ -40,20 +43,30 @@ export async function runAgent(command, flags = {}, input, signal) {
40
43
  const port = Number(flags.port || process.env.PORT || 4747);
41
44
  if (!Number.isInteger(port) || port < LIMITS.port[0] || port > LIMITS.port[1]) throw new Error('Port must be a number from 1 to 65535.');
42
45
  if (flags.id && !/^[a-z0-9-]+$/.test(flags.id)) throw new Error('Invalid review id.');
43
- const { base, request } = localClient(port, signal);
46
+ const dispatchesReview = ['check', 'start', 'answer', 'finish', 'resume', 'verdict'].includes(command);
47
+ const { base, request } = localClient(port, signal, { requireCurrentVersion: dispatchesReview });
44
48
  const route = flags.id ? `/api/debates/${flags.id}` : null;
45
49
  const board = (id) => `${base}/#${id}`; // where a person can watch this review in a browser
46
50
  let result;
47
51
  if (command === 'status' && !route) {
48
52
  const setup = await request('/api/seats?cached=1');
49
- const pools = setup.vendors.filter((v) => v.kind !== 'api').map((v) => v.vendor);
50
- const readiness = flags.refresh ? await request('/api/preflight', { pools, fresh: true }) : await request('/api/preflight');
51
- result = { mode: setup.runtime.mode, cataloguePending: setup.runtime.cataloguePending === true, providers: setup.vendors.map((v) => ({ vendor: v.vendor, kind: v.kind,
53
+ const inventory = await request('/api/profiles', {});
54
+ const pools = inventory.profiles.map((p) => 'acp@' + p.name);
55
+ const readiness = !pools.length ? { pools: [] } : flags.refresh
56
+ ? await request('/api/preflight', { pools, fresh: true })
57
+ : await request('/api/preflight?pools=' + encodeURIComponent(pools.join(',')));
58
+ result = { mode: setup.runtime.mode, cataloguePending: setup.runtime.cataloguePending === true, defaultTransport: 'agentlink', agentLink: inventory,
59
+ providers: Object.keys(PROFILE_PROVIDERS).map((vendor) => {
60
+ const profile = providerProfile(vendor, inventory.profiles);
61
+ return { vendor, transport: 'agentlink', account: profile?.name || null, configured: !!profile, ...(profile?.defaults ? { defaults: profile.defaults } : {}) };
62
+ }),
63
+ directProviders: setup.vendors.filter((v) => v.kind !== 'acp').map((v) => ({ vendor: v.vendor, kind: v.kind, ...(v.kind === 'cli' ? { transport: 'cli' } : {}),
52
64
  models: (v.catalogue?.models || []).map((m) => typeof m === 'string' ? m : m.id), efforts: v.catalogue?.efforts || [],
53
65
  ...(v.terms ? { terms: { notice: v.terms.notice, url: v.terms.url, acknowledgedOnBoard: v.terms.acknowledgedAt != null } } : {}) })),
54
66
  readiness: readiness.pools, defaults: setup.defaults, next: 'Check a JSON review with agent check --input file. No model call has been made.' };
55
- } else if (command === 'check') result = await request('/api/preview', input);
56
- else if (command === 'start') { const started = await request('/api/debates', input); result = { id: started.slug, board: board(started.slug), next: `agent wait --port ${port} --id ${started.slug}` }; }
67
+ } else if (command === 'models') result = await request('/api/profile-models', input || {}, 45_000);
68
+ else if (command === 'check') result = await request('/api/preview', input, 40_000);
69
+ else if (command === 'start') { const started = await request('/api/debates', input, 40_000); result = { id: started.slug, board: board(started.slug), next: `agent wait --port ${port} --id ${started.slug}` }; }
57
70
  else {
58
71
  if (!route) throw new Error('This command needs --id from agent start or the board URL.');
59
72
  if (command === 'status') result = { ...(await request(`${route}/state`)), board: board(flags.id) };
@@ -107,7 +120,7 @@ export async function runAgent(command, flags = {}, input, signal) {
107
120
  if (!body || typeof body !== 'object' || Array.isArray(body)) throw new Error('Input must be a JSON object.');
108
121
  if (['answer', 'finish', 'stop', 'resume'].includes(command)) body.source = 'agent';
109
122
  if (['answer', 'hold'].includes(command) && !Number.isInteger(body.round)) throw new Error('An answer or time extension needs the round number from the current state.');
110
- result = await request(`${route}/${command === 'answer' ? 'continue' : command === 'verdict' ? 'synthesize' : command}`, body);
123
+ result = await request(`${route}/${command === 'answer' ? 'continue' : command === 'verdict' ? 'synthesize' : command}`, body, ['resume', 'verdict'].includes(command) ? 40_000 : undefined);
111
124
  result = { ...result, id: flags.id, board: board(flags.id), next: `agent wait --port ${port} --id ${flags.id}` };
112
125
  }
113
126
  }
package/src/cli.js CHANGED
@@ -7,11 +7,13 @@
7
7
  // roundtable doctor [--live] what this machine can seat
8
8
  // roundtable export <slug> <dir>
9
9
  // roundtable debate [...] one debate headless against a running server (see the script)
10
- // --port <n> --no-open for the two board commands
10
+ // --port <n> --no-open for the two board commands; any other option there is refused
11
+ // roundtable --version the installed version
11
12
  import { spawn } from 'node:child_process';
12
13
  import path from 'node:path';
13
14
  import { fileURLToPath } from 'node:url';
14
15
  import { terminalBanner } from './terminal.js';
16
+ import { VERSION } from './version.js';
15
17
 
16
18
  const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
17
19
  const SCRIPTS = {
@@ -28,11 +30,27 @@ const USAGE = ['roundtable [--port <n>] [--no-open] the board, opened in your
28
30
  'roundtable setup --client codex connect an assistant across projects (also claude, agy, all)',
29
31
  'roundtable setup --help inspect, update or remove that connection',
30
32
  'roundtable server --help check, start, stop or restart the hidden board',
31
- 'roundtable mcp MCP tools over stdio; starts the local server as needed'].join('\n');
33
+ 'roundtable mcp MCP tools over stdio; starts the local server as needed',
34
+ 'roundtable --version the installed version'].join('\n');
32
35
  // help first, wherever it is on the line: a bare `--help` must never start the real server
33
36
  if (!['agent', 'setup', 'mcp', 'server'].includes(args[0]) && args.some((a) => a === 'help' || a === '--help' || a === '-h')) { process.stdout.write(terminalBanner()); console.log(USAGE); process.exit(0); }
37
+ // the version and nothing else, asked for first on the line (a later -v belongs to a subcommand)
38
+ if (['--version', '-v', '-V', 'version'].includes(args[0])) { console.log(VERSION); process.exit(0); }
39
+ const refuse = (why) => { console.error(`${why}\n\n${USAGE}`); process.exit(2); };
34
40
  const cmd = args[0] && !args[0].startsWith('-') ? args.shift() : 'start';
35
- if (!SCRIPTS[cmd]) { console.error(`unknown command: ${cmd}\n\n${USAGE}`); process.exit(2); }
41
+ if (!SCRIPTS[cmd]) refuse(`unknown command: ${cmd}`);
42
+ // The board commands take these options and no others. An unrecognised one used to fall through
43
+ // and start the board (a mistyped --port opened the live server on the default port), so it is
44
+ // refused here, before anything starts. The other commands check their own arguments.
45
+ if (['start', 'fake'].includes(cmd)) {
46
+ for (let i = 0; i < args.length; i++) {
47
+ if (args[i] === '--port') {
48
+ const n = /^\d{1,5}$/.test(args[i + 1] ?? '') ? Number(args[i + 1]) : 0;
49
+ if (n < 1 || n > 65535) refuse('--port needs a number from 1 to 65535');
50
+ i++;
51
+ } else if (!['--no-open', '--fake', '--fake-consensus'].includes(args[i])) refuse(`unknown option: ${args[i]}`);
52
+ }
53
+ }
36
54
  const env = { ...process.env };
37
55
  const port = args.indexOf('--port');
38
56
  if (port >= 0 && ['start', 'fake'].includes(cmd)) { env.PORT = args[port + 1]; args.splice(port, 2); }
@@ -23,6 +23,7 @@ const integer = (n, max) => Number.isInteger(n) && n >= 0 && n <= max;
23
23
  export const diagnosticId = () => `RT-${randomBytes(8).toString('hex')}`;
24
24
 
25
25
  export function diagnosticAction(pathname) {
26
+ if (pathname === '/api/profile-models') return 'catalogue';
26
27
  if (pathname === '/api/seats') return 'setup';
27
28
  if (pathname === '/api/health') return 'health';
28
29
  if (pathname === '/api/shutdown') return 'shutdown';
package/src/engine.js CHANGED
@@ -14,7 +14,7 @@
14
14
  import { validateReply, validateVerdict } from './contract.js';
15
15
  import { filterReply } from './seats.js';
16
16
  import { round0Prompt, roundPrompt, recoveryPrompt, repromptText, chairmanPrompt, statelessPrefix, statelessRoundPrompt, statelessRepromptText, verdictRepromptText } from './prompts.js';
17
- import { projectRound, projectChairman, budgetCheck, unknownUsageMessage, researchInputTokens } from './estimate.js';
17
+ import { projectRound, projectChairman, budgetCheck, unknownUsageMessage, researchInputTokens, researchEstimate } from './estimate.js';
18
18
  import { noteRecord, storedNote } from './notes.js';
19
19
  import { safeProgress } from './progress.js';
20
20
  import { researchSettings, researchPrompt, researchSources } from './research.js';
@@ -42,6 +42,7 @@ export const DEFAULTS = {
42
42
  // last reply, the others', the note). This avoids resending the full conversation; token use
43
43
  // still varies. 'resume': the CLI session is resumed, so conversation context can grow.
44
44
  memory: 'stateless',
45
+ providerHistory: 'prefer-ephemeral',
45
46
  // Reported tools stop a seat for the review; callers cannot disable this guard.
46
47
  strictTools: true,
47
48
  // { [vendor]: { tokens?: number, usd?: number } }: admit each round and every call attempt,
@@ -63,7 +64,7 @@ const EMPTY_USAGE = { input: 0, cacheRead: 0, cacheWrite: 0, output: 0, thinking
63
64
  // synthesisOnly: with resume, skip the rounds and write the verdict (POST .../synthesize).
64
65
  // limitGroup(seat): for a login whose limits differ by model group (agy), the group the seat's
65
66
  // model draws on, from the server's quota read; null for one set of limits or an unknown group.
66
- export function createDebate({ fieldNotes, seats, chairman, options = {}, runner, gate, store, emit = () => {}, now = Date.now, resume = null, baselines = {}, provenance = {}, cancel = () => {}, synthesisOnly = false, limitGroup = () => null }) {
67
+ export function createDebate({ fieldNotes, seats, chairman, options = {}, runner, verifySources, gate, store, emit = () => {}, now = Date.now, resume = null, baselines = {}, provenance = {}, cancel = () => {}, synthesisOnly = false, limitGroup = () => null }) {
67
68
  const opts = { ...DEFAULTS, ...options, strictTools: true };
68
69
  if (opts.research) opts.research = researchSettings(opts.research);
69
70
  const maxRound = opts.critiqueRounds;
@@ -189,8 +190,9 @@ export function createDebate({ fieldNotes, seats, chairman, options = {}, runner
189
190
  async function callSeat(seat, prompt, round, kind, projection = {}, { isChairman = false } = {}) {
190
191
  if (policyBlocked(seat)) return { ok: false, text: '', usage: { ...EMPTY_USAGE }, reported: false, error: 'This seat is stopped after a provider-policy failure. Check its earlier failure details.', kind: 'policy', skipped: true, fresh: true, attemptId: null };
191
192
  let retrying = null; // what a second attempt is called: 'network retry', 'rate-limit retry' or 'search retry'
192
- // one time limit for the searcher, however many attempts it takes
193
- const searchEnds = kind === 'research' ? now() + opts.research.timeoutMs : null;
193
+ // Both attempts share the research deadline and operation allowance.
194
+ let research = kind === 'research' ? opts.research : null;
195
+ const searchEnds = research ? now() + research.timeoutMs : null;
194
196
  for (let attemptNo = 1; ; attemptNo++) {
195
197
  // checked before a retry too: another seat may have benched this login during the pause
196
198
  const down = downOf(seat);
@@ -205,7 +207,10 @@ export function createDebate({ fieldNotes, seats, chairman, options = {}, runner
205
207
  error: 'the wall clock ran out before the call', kind: 'killed', cancelReason: 'wall-clock', fresh: !resumes || seat.sessionId == null, attemptId: null };
206
208
  const action = retrying || (kind === 'reprompt' ? 're-prompt' : kind);
207
209
  const what = ['verdict', 'research', 'search retry'].includes(action) ? action : `${action} of ${isChairman ? 'the chairman' : seat.lens}`;
208
- if (!isChairman) projection = oneCall(seat, round);
210
+ if (research) {
211
+ const estimate = researchEstimate(research, baselines);
212
+ projection = profiled(seat, { [seat.vendor]: { tokens: estimate.input + estimate.output, cost: estimate.cost } });
213
+ } else if (!isChairman) projection = oneCall(seat, round);
209
214
  // Check and reserve synchronously at the dispatch boundary. A retry sees the failed
210
215
  // attempt's reported usage and every other call still in flight; seat calls also leave
211
216
  // room for the verdict. A refusal is not an attempt and must not invent a usage row.
@@ -228,10 +233,10 @@ export function createDebate({ fieldNotes, seats, chairman, options = {}, runner
228
233
  const attemptId = newId();
229
234
  reserved.set(attemptId, projection);
230
235
  record({ type: 'attempt-start', attemptId, round, kind, seat: pub(seat), fresh: !resumes || seat.sessionId == null });
231
- let res = await callOnce(seat, prompt, kind === 'research', searchEnds);
236
+ let res = await callOnce(seat, research ? researchPrompt(research) : prompt, research, searchEnds);
232
237
  const attempt = { type: 'attempt', attemptId, round, kind, seat: pub(seat), fresh: res.fresh, usage: res.reported ? res.usage : null,
233
238
  ...(res.progress ? { progress: res.progress } : {}), ...(res.systemCode ? { systemCode: res.systemCode } : {}),
234
- // each searcher attempt keeps its own count: a retried search has its own limit
239
+ // Each attempt keeps its own observed count for usage calibration.
235
240
  ...(kind === 'research' && Number.isInteger(res.searches) ? { searches: res.searches } : {}),
236
241
  ...(res.reported ? {} : { unknown: true, ms: res.usage.ms,
237
242
  ...(res.usage.cost != null ? { cost: res.usage.cost } : {}), ...(res.usage.raw?.cost != null ? { rawCost: res.usage.raw.cost } : {}) }),
@@ -245,7 +250,13 @@ export function createDebate({ fieldNotes, seats, chairman, options = {}, runner
245
250
  // a search that went silent is started once more, inside the searcher's one time limit: one
246
251
  // the watchdog stopped (STALL), or one whose CLI used up its reconnects on a silent stream
247
252
  const silent = res.systemCode === 'STALL' || res.systemCode === 'CLI_FAILURE' && res.kind === 'timeout';
248
- const stalled = kind === 'research' && !res.ok && silent && searchEnds - now() >= SEARCH_RETRY_MIN_MS;
253
+ const remaining = research && Number.isInteger(res.searches) ? research.maxSearches - res.searches : null;
254
+ const searchStall = research && !res.ok && silent;
255
+ const stalled = searchStall && remaining != null && remaining > 0 && searchEnds - now() >= SEARCH_RETRY_MIN_MS;
256
+ if (searchStall && (remaining == null || remaining <= 0)) {
257
+ const reason = remaining == null ? 'the provider did not report the search count' : 'the search allowance was exhausted';
258
+ res = { ...res, error: `${res.error} No search retry because ${reason}.` };
259
+ }
249
260
  const retry = !res.ok && attemptNo === 1 && !expired() && !stopRequested && !(finishRequested && !isChairman)
250
261
  && (stalled || kind !== 'research' && (res.kind === 'network' || throttled && res.resetsAt != null && res.resetsAt < deadlineAt));
251
262
  // the attempt row keeps `throttled`; everything after it sees the quota failure it became,
@@ -257,6 +268,7 @@ export function createDebate({ fieldNotes, seats, chairman, options = {}, runner
257
268
  }
258
269
  if (!res.ok && POOL_FATAL.has(res.kind)) markDown(seat, res);
259
270
  if (retry) {
271
+ if (stalled) research = { ...research, maxSearches: remaining };
260
272
  retrying = stalled ? 'search retry' : throttled ? 'rate-limit retry' : 'network retry';
261
273
  await pause(stalled ? 0 : throttled ? Math.max(0, res.resetsAt - now()) : opts.networkRetryMs);
262
274
  continue;
@@ -278,12 +290,12 @@ export function createDebate({ fieldNotes, seats, chairman, options = {}, runner
278
290
  }
279
291
 
280
292
  // searchEnds: when the searcher's time limit runs out, so a retried search gets only what is left
281
- async function callOnce(seat, prompt, researching = false, searchEnds = null) {
293
+ async function callOnce(seat, prompt, research, searchEnds) {
282
294
  const t0 = now();
283
295
  const cancellation = () => interruptRequested ? 'interrupted' : stopRequested ? 'human' : deadlineHit ? 'wall-clock' : finishRequested && seat.id !== 'chairman' ? 'finish' : null;
284
296
  const cancellationText = (reason) => reason === 'interrupted' ? 'interrupted by server shutdown' : reason === 'human' ? 'stopped by the user' : reason === 'finish' ? 'discussion ended for the verdict' : 'stopped: the wall clock ran out during the call';
285
297
  // Stateless: never hand the CLI a session to resume; the prompt is self-contained.
286
- const sessionId = resumes && !researching ? seat.sessionId : null;
298
+ const sessionId = resumes && !research ? seat.sessionId : null;
287
299
  const accounting = (res) => {
288
300
  if (res.sessionId) seat.sessionId = res.sessionId;
289
301
  const rawCost = res.usage?.raw?.cost ?? res.rawCost;
@@ -295,10 +307,11 @@ export function createDebate({ fieldNotes, seats, chairman, options = {}, runner
295
307
  try {
296
308
  // prevCost: the session's last cumulative cost reading, so a resumed call is charged only
297
309
  // its own part even after a server restart (adapters/common.js).
298
- const res = await runner(seat.vendor, prompt, sessionId, { timeoutMs: researching ? Math.max(1, searchEnds != null ? searchEnds - now() : opts.research.timeoutMs) : opts.callTimeoutMs,
299
- ...(researching ? { research: opts.research } : {}), signal: controller.signal, seat, model: seat.model, effort: seat.effort, allowLimitedIsolation: opts.allowLimitedIsolation === true, acknowledgeTermsRisk: opts.acknowledgeTermsRisk === true,
310
+ const res = await runner(seat.vendor, prompt, sessionId, { timeoutMs: research ? Math.max(1, searchEnds - now()) : opts.callTimeoutMs,
311
+ ...(research ? { research } : {}), signal: controller.signal, seat, model: seat.model, effort: seat.effort, allowLimitedIsolation: opts.allowLimitedIsolation === true, acknowledgeTermsRisk: opts.acknowledgeTermsRisk === true,
300
312
  // only a seat in resume memory needs its CLI to save the session for the next round
301
- keepSession: resumes && !researching && seat.id !== 'chairman',
313
+ providerHistory: opts.providerHistory,
314
+ keepSession: resumes && !research && seat.id !== 'chairman',
302
315
  prevCost: sessionId ? seat.lastRawCost : undefined, prevUsage: sessionId ? seat.lastRawUsage : undefined });
303
316
  const usage = accounting(res);
304
317
  if (res.usedTools) {
@@ -307,8 +320,8 @@ export function createDebate({ fieldNotes, seats, chairman, options = {}, runner
307
320
  }
308
321
  const cancelReason = cancellation();
309
322
  if (cancelReason) return { ok: false, text: '', usage, reported: !!res.usage, progress: safeProgress(res.progress), error: cancellationText(cancelReason), kind: 'killed', cancelReason, fresh: sessionId == null };
310
- return { ok: true, text: researching ? res.text || '' : filterReply(seat.mood, res.text || ''), usage, reported: !!res.usage, raw: res.raw,
311
- ...(researching ? { searches: res.research?.searches } : {}), progress: safeProgress(res.progress), fresh: sessionId == null, usedTools: !!res.usedTools };
323
+ return { ok: true, text: research ? res.text || '' : filterReply(seat.mood, res.text || ''), usage, reported: !!res.usage, raw: res.raw,
324
+ ...(research ? { searches: res.research?.searches } : {}), progress: safeProgress(res.progress), fresh: sessionId == null, usedTools: !!res.usedTools };
312
325
  } catch (e) {
313
326
  const cancelReason = cancellation();
314
327
  const error = cancelReason ? cancellationText(cancelReason) : e.message;
@@ -317,15 +330,18 @@ export function createDebate({ fieldNotes, seats, chairman, options = {}, runner
317
330
  const usage = accounting(e);
318
331
  if (e.usedTools || e.kind === 'policy') seat.sessionId = null;
319
332
  return { ok: false, text: '', usage, reported: !!e.usage, error, progress: safeProgress(e.progress),
320
- ...(researching && Number.isInteger(e.research?.searches) && e.research.searches >= 0 && e.research.searches <= 9 ? { searches: e.research.searches } : {}),
333
+ ...(research && Number.isInteger(e.research?.searches) && e.research.searches >= 0 && e.research.searches <= 9 ? { searches: e.research.searches } : {}),
321
334
  systemCode: ['TIMEOUT', 'STALL', 'KILLED', 'TOOL_POLICY', 'OUTPUT_LIMIT', 'PROVIDER_PROTOCOL', 'CLI_EXIT', 'CLI_FAILURE', 'ISOLATION_REQUIRED', 'TERMS_ACK_REQUIRED', 'RESEARCH_LIMIT', 'RESEARCH_INVALID', 'ENOENT', 'EACCES', 'EPERM'].includes(e.code) ? e.code : undefined,
322
335
  kind: e.usedTools ? 'policy' : kind, usedTools: !!e.usedTools, cancelReason, resetsAt: e.resetsAt || null, timedOut: !cancelReason && kind === 'timeout', fresh: sessionId == null };
323
336
  }
324
337
  }
325
338
 
326
- const oneCall = (seat, round) => projectRound({ seats: [seat], round, baselines,
327
- memory: resumes && seat.sessionId != null ? 'resume' : 'stateless', researchTokens: researchInputTokens(fieldNotes.research || []) });
328
- const chairmanCall = (chairman = state.chairman) => projectChairman({ chairman, baselines, researchTokens: researchInputTokens(fieldNotes.research || []) });
339
+ // A seat on a named account is also projected under `vendor@account`, so a budget on one
340
+ // AgentLink profile can be checked on its own; the bare vendor key still carries every seat.
341
+ const profiled = (seat, projection) => seat?.account && projection[seat.vendor] ? { ...projection, [`${seat.vendor}@${seat.account}`]: { ...projection[seat.vendor] } } : projection;
342
+ const oneCall = (seat, round) => profiled(seat, projectRound({ seats: [seat], round, baselines,
343
+ memory: resumes && seat.sessionId != null ? 'resume' : 'stateless', researchTokens: researchInputTokens(fieldNotes.research || []) }));
344
+ const chairmanCall = (chairman = state.chairman) => profiled(chairman, projectChairman({ chairman, baselines, researchTokens: researchInputTokens(fieldNotes.research || []) }));
329
345
 
330
346
  // A seat's connection state, as the board shows it: idle, thinking, replied, reprompted,
331
347
  // failed, timed-out. Emitted here so the UI only renders.
@@ -586,8 +602,9 @@ export function createDebate({ fieldNotes, seats, chairman, options = {}, runner
586
602
  function spentByVendor() {
587
603
  const out = {};
588
604
  const at = (vendor) => (out[vendor] ??= { tokens: 0, cost: 0, costUnknown: false, tokensUnknown: false });
589
- for (const e of ledger) {
590
- const v = at(e.seat.vendor);
605
+ // under the vendor, and under `vendor@account` for a seat on a named account (profile budgets)
606
+ for (const e of ledger) for (const key of e.seat.account ? [e.seat.vendor, `${e.seat.vendor}@${e.seat.account}`] : [e.seat.vendor]) {
607
+ const v = at(key);
591
608
  if (usageUnknown(e.usage)) v.tokensUnknown = true;
592
609
  if (e.usage) v.tokens += (e.usage.input || 0) + (e.usage.cacheRead || 0) + (e.usage.cacheWrite || 0) + (e.usage.output || 0);
593
610
  const cost = e.usage?.cost ?? e.cost;
@@ -654,7 +671,8 @@ export function createDebate({ fieldNotes, seats, chairman, options = {}, runner
654
671
  state.fieldNotes = fieldNotes;
655
672
  return true;
656
673
  }
657
- let result;
674
+ let result, verification;
675
+ const researchDeadline = now() + opts.research.timeoutMs;
658
676
  if (resume) result = { ok: false, error: 'Research was interrupted before a usable source bundle was saved. It was not rerun. Check provider usage before starting a new review.', kind: 'interrupted' };
659
677
  else {
660
678
  state.status = 'researching';
@@ -663,22 +681,41 @@ export function createDebate({ fieldNotes, seats, chairman, options = {}, runner
663
681
  // the searcher: its own vendor, model, effort and login profile from the research settings
664
682
  const { vendor, model, effort, account } = opts.research;
665
683
  const seat = { id: 'research', index: -2, vendor, label: 'Searcher', lens: 'searcher', model, effort, account };
666
- result = await callSeat(seat, researchPrompt(opts.research), -1, 'research', chairmanCall(seat), { isChairman: true });
684
+ result = await callSeat(seat, null, -1, 'research', {}, { isChairman: true });
667
685
  }
686
+ const attempts = ledger.filter(a => a.kind === 'research');
687
+ const searches = attempts.length && attempts.every(a => Number.isInteger(a.searches) && a.searches >= 0)
688
+ ? attempts.reduce((sum, a) => sum + a.searches, 0) : undefined;
668
689
  if (result.ok) {
669
690
  try {
670
- if (!Number.isInteger(result.searches) || result.searches < 1 || result.searches > opts.research.maxSearches) throw new Error('Research did not report a usable search-operation count.');
691
+ if (!(result.searches > 0) || searches == null || searches > opts.research.maxSearches) throw new Error('Research did not report a usable search-operation count.');
671
692
  const gatheredAt = new Date(now()).toISOString();
672
- state.research = { status: 'done', sources: researchSources(result.text, gatheredAt), gatheredAt, searches: result.searches, attemptId: result.attemptId };
693
+ let sources = researchSources(result.text, gatheredAt, { allowEmpty: !!verifySources && opts.research.sourceScopes?.some(scope => !new URL(scope).pathname.endsWith('/')) });
694
+ if (verifySources) {
695
+ const left = researchDeadline - now();
696
+ if (left <= 0) throw new DOMException('The research time limit expired before checking sources.', 'TimeoutError');
697
+ const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(left)]);
698
+ const checked = await verifySources(sources, opts.research, signal);
699
+ checkInterrupted();
700
+ signal.throwIfAborted();
701
+ sources = checked.sources.map(source => ({ ...source, gatheredAt }));
702
+ verification = checked.verification;
703
+ if (!sources.length) throw new Error('No cited page supplied usable evidence within the requested source scope.');
704
+ }
705
+ state.research = { status: 'done', sources, ...(verification ? { verification } : {}), gatheredAt, searches, attemptId: result.attemptId };
673
706
  fieldNotes = { ...fieldNotes, research: state.research.sources }; state.fieldNotes = fieldNotes;
674
707
  record({ type: 'research', ...state.research });
675
708
  store?.writeFieldNotes?.(fieldNotes, state.seats);
676
709
  fire('research', state.research);
677
710
  state.status = 'running';
678
711
  return true;
679
- } catch (e) { result = { ...result, ok: false, kind: 'format', error: e.message }; }
712
+ } catch (e) {
713
+ checkInterrupted();
714
+ const kind = controller.signal.aborted ? 'killed' : e.name === 'TimeoutError' ? 'timeout' : 'format';
715
+ result = { ...result, ok: false, kind, error: e.message };
716
+ }
680
717
  }
681
- state.research = { status: 'failed', error: result.error, errorKind: result.kind, attemptId: result.attemptId, progress: result.progress, searches: result.searches };
718
+ state.research = { status: 'failed', error: result.error, errorKind: result.kind, ...(verification ? { verification } : {}), attemptId: result.attemptId, progress: result.progress, searches };
682
719
  record({ type: 'research', ...state.research }); fire('research', state.research);
683
720
  state.stopReason = stopRequested ? 'human' : expired() ? 'wall-clock' : 'research-failed';
684
721
  return false;
@@ -843,8 +880,16 @@ export function addUsage(a, b) {
843
880
  const ca = cov(a), cb = cov(b);
844
881
  const tokens = (u) => u?.tokenCoverage || { reported: u ? 1 : 0, of: u ? 1 : 0 };
845
882
  const ta = tokens(a), tb = tokens(b);
883
+ const cliCoverage = u => {
884
+ if (u?.providerTotalCoverage) return u.providerTotalCoverage;
885
+ const coverage = tokens(u);
886
+ return u?.providerTotal != null ? coverage : { reported: 0, of: coverage.of };
887
+ };
888
+ const pa = cliCoverage(a), pb = cliCoverage(b);
846
889
  const usageVersion = a?.usageVersion ?? b?.usageVersion;
847
890
  return { input: sum('input'), cacheRead: sum('cacheRead'), cacheWrite: sum('cacheWrite'), output: sum('output'), thinking: sum('thinking'), cost, ms: sum('ms'),
891
+ ...(a?.providerTotal != null || b?.providerTotal != null ? { providerTotal: sum('providerTotal'),
892
+ providerTotalCoverage: { reported: pa.reported + pb.reported, of: pa.of + pb.of } } : {}),
848
893
  costCoverage: { reported: ca.reported + cb.reported, of: ca.of + cb.of },
849
894
  tokenCoverage: { reported: ta.reported + tb.reported, of: ta.of + tb.of }, ...(usageVersion ? { usageVersion } : {}) };
850
895
  }
@@ -889,7 +934,7 @@ export function rollup(rows) {
889
934
  let total = null; // not a zero row: costCoverage counts only real calls
890
935
  let unknownAttempts = 0;
891
936
  for (const r of ledgerEntries(rows)) {
892
- if (!r.usage) unknownAttempts++;
937
+ if (!r.usage || r.usage.tokenCoverage?.reported < r.usage.tokenCoverage?.of) unknownAttempts++;
893
938
  const usage = r.usage || { ...EMPTY_USAGE, cost: r.cost ?? null, ms: r.ms || 0, tokenCoverage: { reported: 0, of: 1 } };
894
939
  const key = r.seat ? (r.seat.id || `${r.seat.vendor}:${r.seat.lens}`) : 'other';
895
940
  bySeat[key] = { seat: r.seat || null, usage: addUsage(bySeat[key]?.usage, usage) };