@prplkane/roundtable 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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,7 +330,7 @@ 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
  }
@@ -658,7 +671,8 @@ export function createDebate({ fieldNotes, seats, chairman, options = {}, runner
658
671
  state.fieldNotes = fieldNotes;
659
672
  return true;
660
673
  }
661
- let result;
674
+ let result, verification;
675
+ const researchDeadline = now() + opts.research.timeoutMs;
662
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' };
663
677
  else {
664
678
  state.status = 'researching';
@@ -667,22 +681,41 @@ export function createDebate({ fieldNotes, seats, chairman, options = {}, runner
667
681
  // the searcher: its own vendor, model, effort and login profile from the research settings
668
682
  const { vendor, model, effort, account } = opts.research;
669
683
  const seat = { id: 'research', index: -2, vendor, label: 'Searcher', lens: 'searcher', model, effort, account };
670
- result = await callSeat(seat, researchPrompt(opts.research), -1, 'research', chairmanCall(seat), { isChairman: true });
684
+ result = await callSeat(seat, null, -1, 'research', {}, { isChairman: true });
671
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;
672
689
  if (result.ok) {
673
690
  try {
674
- 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.');
675
692
  const gatheredAt = new Date(now()).toISOString();
676
- 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 };
677
706
  fieldNotes = { ...fieldNotes, research: state.research.sources }; state.fieldNotes = fieldNotes;
678
707
  record({ type: 'research', ...state.research });
679
708
  store?.writeFieldNotes?.(fieldNotes, state.seats);
680
709
  fire('research', state.research);
681
710
  state.status = 'running';
682
711
  return true;
683
- } 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
+ }
684
717
  }
685
- 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 };
686
719
  record({ type: 'research', ...state.research }); fire('research', state.research);
687
720
  state.stopReason = stopRequested ? 'human' : expired() ? 'wall-clock' : 'research-failed';
688
721
  return false;
@@ -847,8 +880,16 @@ export function addUsage(a, b) {
847
880
  const ca = cov(a), cb = cov(b);
848
881
  const tokens = (u) => u?.tokenCoverage || { reported: u ? 1 : 0, of: u ? 1 : 0 };
849
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);
850
889
  const usageVersion = a?.usageVersion ?? b?.usageVersion;
851
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 } } : {}),
852
893
  costCoverage: { reported: ca.reported + cb.reported, of: ca.of + cb.of },
853
894
  tokenCoverage: { reported: ta.reported + tb.reported, of: ta.of + tb.of }, ...(usageVersion ? { usageVersion } : {}) };
854
895
  }
@@ -893,7 +934,7 @@ export function rollup(rows) {
893
934
  let total = null; // not a zero row: costCoverage counts only real calls
894
935
  let unknownAttempts = 0;
895
936
  for (const r of ledgerEntries(rows)) {
896
- if (!r.usage) unknownAttempts++;
937
+ if (!r.usage || r.usage.tokenCoverage?.reported < r.usage.tokenCoverage?.of) unknownAttempts++;
897
938
  const usage = r.usage || { ...EMPTY_USAGE, cost: r.cost ?? null, ms: r.ms || 0, tokenCoverage: { reported: 0, of: 1 } };
898
939
  const key = r.seat ? (r.seat.id || `${r.seat.vendor}:${r.seat.lens}`) : 'other';
899
940
  bySeat[key] = { seat: r.seat || null, usage: addUsage(bySeat[key]?.usage, usage) };
package/src/estimate.js CHANGED
@@ -4,6 +4,7 @@
4
4
  // Baselines come from this machine's own transcripts (tokens per call, fresh round-0 calls and
5
5
  // resumed later calls separately). Effort multipliers are guesses until measured deltas replace
6
6
  // them; they live here and nowhere else.
7
+ import { defaultSearchLimit } from './research.js';
7
8
  import { quotaGroup } from './adapters/models.js';
8
9
 
9
10
  export const EFFORT_MULTIPLIER = { low: 0.7, medium: 1, high: 1.4, xhigh: 1.8, ultra: 2.2, max: 2.6 };
@@ -66,14 +67,29 @@ function median(xs) {
66
67
  // Transcript rows (any number of debates) -> per-vendor medians per call.
67
68
  export function baselinesFrom(rows) {
68
69
  const acc = {};
70
+ const research = new Map();
69
71
  for (const r of rows || []) {
70
- if (r.kind === 'research') continue; // web evidence gathering has a different context size
71
72
  if (!r.usage || !r.seat?.vendor) continue;
73
+ if (r.usage.tokenCoverage && r.usage.tokenCoverage.reported < r.usage.tokenCoverage.of) continue;
72
74
  if (r.type !== 'reply' && r.type !== 'verdict' && r.type !== 'attempt') continue;
73
75
  // a call the server refused before the model ran (an endpoint's 429) reports zero tokens: known
74
76
  // spending for the caps, but no sample of what a call costs
75
77
  if (!((r.usage.input || 0) + (r.usage.cacheRead || 0) + (r.usage.cacheWrite || 0) + (r.usage.output || 0))) continue;
76
78
  if (typeof r.sessionId === 'string' && r.sessionId.startsWith('fake-')) continue; // a scripted seat
79
+ if (r.kind === 'research') {
80
+ if (!Number.isInteger(r.searches) || r.searches < 1 || r.searches > 8 || r.errorKind) continue;
81
+ const keys = [r.seat.vendor];
82
+ if (r.seat.model) keys.push(`${r.seat.vendor}:${r.seat.model}`);
83
+ for (const key of keys) {
84
+ if (!research.has(key)) research.set(key, {});
85
+ const group = research.get(key)[r.searches] ??= { input: [], output: [], steps: [], cost: [] };
86
+ group.input.push(r.usage.input + (r.usage.cacheRead || 0) + (r.usage.cacheWrite || 0));
87
+ group.output.push(r.usage.output);
88
+ if (r.usage.modelSteps > 0) group.steps.push(r.usage.modelSteps);
89
+ if (typeof r.usage.cost === 'number') group.cost.push(r.usage.cost);
90
+ }
91
+ continue;
92
+ }
77
93
  // Rows since 0.2.0 say whether the call resumed a session; older rows are fresh at round 0 only.
78
94
  const kind = r.type === 'verdict' || r.kind === 'verdict' || r.round === 0 || r.fresh === true ? 'fresh' : 'resumed';
79
95
  const v = (acc[r.seat.vendor] ??= { fresh: { input: [], output: [], cost: [] }, resumed: { input: [], output: [], cost: [] } });
@@ -94,9 +110,26 @@ export function baselinesFrom(rows) {
94
110
  out[vendor][kind] = { input: median(v[kind].input), output: median(v[kind].output), n: v[kind].input.length, cost: v[kind].cost.length ? median100(v[kind].cost) : null, nCost: v[kind].cost.length };
95
111
  }
96
112
  }
113
+ for (const [key, groups] of research) {
114
+ (out[key] ??= {}).research = Object.fromEntries(Object.entries(groups).map(([limit, g]) => [limit, {
115
+ input: median(g.input), output: median(g.output), samples: g.input.length,
116
+ modelSteps: g.steps.length ? median(g.steps) : null, cost: g.cost.length ? median100(g.cost) : null,
117
+ }]));
118
+ }
97
119
  return out;
98
120
  }
99
121
 
122
+ // A sample describes completed searches, not every prompt sent to the same CLI.
123
+ export function researchEstimate(settings, baselines = {}) {
124
+ const vendor = settings.vendor || 'codex', limit = settings.maxSearches ?? defaultSearchLimit(vendor);
125
+ const measured = baselines[`${vendor}:${settings.model}`]?.research?.[limit] || baselines[vendor]?.research?.[limit];
126
+ if (measured) return measured;
127
+ if (vendor === 'agy') return { input: 34_000 + (limit - 1) * 4_000, output: 1000, samples: 0, modelSteps: null, cost: null };
128
+ const b = baseFor(vendor, 'fresh', baselines), m = EFFORT_MULTIPLIER[settings.effort] ?? 1;
129
+ return { input: Math.round(b.input * CHAIRMAN_INPUT_FACTOR), output: Math.round(b.output * 1.5 * m),
130
+ cost: projectChairman({ chairman: { ...settings, vendor }, baselines })[vendor].cost, samples: 0, modelSteps: null };
131
+ }
132
+
100
133
  function baseFor(vendor, kind, baselines) {
101
134
  const b = baselines?.[vendor]?.[kind];
102
135
  if (b && b.n > 0 && b.input > 0) return b;
@@ -146,8 +179,10 @@ export function project({ seats, chairman, critiqueRounds = 3, baselines = {}, m
146
179
  if (research) {
147
180
  const selected = typeof research === 'object' ? research : {}; // the searcher's own vendor, model and effort
148
181
  const vendor = selected.vendor || 'codex';
149
- const fresh = baseFor(vendor, 'fresh', baselines), m = EFFORT_MULTIPLIER[selected.effort] ?? 1;
150
- add(vendor, 'research', [{ input: fresh.input * CHAIRMAN_INPUT_FACTOR, output: fresh.output * 1.5 * m }], selected.model);
182
+ const estimate = researchEstimate(selected, baselines);
183
+ add(vendor, 'research', [estimate], selected.model);
184
+ bySeat.research.samples = estimate.samples;
185
+ bySeat.research.modelSteps = estimate.modelSteps;
151
186
  }
152
187
  const total = Object.values(byVendor).reduce((a, v) => a + v.total, 0);
153
188
  return { bySeat, byVendor, total, critiqueRounds };
@@ -302,11 +337,11 @@ export function projectChairman({ chairman, baselines = {}, researchTokens = 0 }
302
337
  // ({vendor: {tokens?, usd?}})? Returns the first crossing, or null.
303
338
  export function budgetCheck(budget, spent, next) {
304
339
  for (const [vendor, cap] of Object.entries(budget || {})) {
305
- if (!cap) continue;
340
+ if (!cap || !next?.[vendor]) continue;
306
341
  // No new call to this vendor adds zero cost. An actual call whose projection is unknown
307
342
  // still carries cost: null and must be refused under a dollar cap.
308
- const s = spent?.[vendor] || { tokens: 0, cost: 0 }, n = next?.[vendor] || { tokens: 0, cost: 0 };
309
- if (cap.tokens > 0 && s.tokensUnknown && next?.[vendor]) return { vendor, kind: 'tokens-unknown', spent: s.tokens, projected: n.tokens, cap: cap.tokens };
343
+ const s = spent?.[vendor] || { tokens: 0, cost: 0 }, n = next[vendor];
344
+ if (cap.tokens > 0 && s.tokensUnknown) return { vendor, kind: 'tokens-unknown', spent: s.tokens, projected: n.tokens, cap: cap.tokens };
310
345
  if (cap.tokens > 0 && s.tokens + n.tokens > cap.tokens) return { vendor, kind: 'tokens', spent: s.tokens, projected: n.tokens, cap: cap.tokens };
311
346
  // A dollar cap cannot be checked against a cost nobody reported: that is a crossing of its
312
347
  // own kind, not a zero.