@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.
@@ -1,7 +1,7 @@
1
- // Antigravity CLI: `agy --output-format json -p=<prompt>`, `--conversation <id>` to resume.
2
- // Quirks: `-p` needs its value attached (`-p=...`) and stdin is ignored in that mode; for long
3
- // prompts common.js switches to --input-format stream-json, where each stdin line is
4
- // {"event":"user","message":{"role":"user","content":...}} and the last stdout line is
5
- // {"event":"result","result":{...same shape as --output-format json...}}. No cost reported.
6
- import { makeAdapter } from './common.js';
7
- export const run = makeAdapter('agy');
1
+ // Antigravity CLI: `agy --output-format json -p=<prompt>`, `--conversation <id>` to resume.
2
+ // Quirks: `-p` needs its value attached (`-p=...`) and stdin is ignored in that mode; for long
3
+ // prompts common.js switches to --input-format stream-json, where each stdin line is
4
+ // {"event":"user","message":{"role":"user","content":...}} and the last stdout line is
5
+ // {"event":"result","result":{...same shape as --output-format json...}}. No cost reported.
6
+ import { makeAdapter } from './common.js';
7
+ export const run = makeAdapter('agy');
@@ -1,6 +1,6 @@
1
- // Claude Code: `claude -p --output-format stream-json --verbose`, prompt on stdin, `--resume <id>`.
2
- // Quirks: total_cost_usd is cumulative for the session on resume; common.js takes the delta.
3
- // stream-json is used only so the rate_limit_event line (remaining quota) comes with each reply.
4
- import { makeAdapter } from './common.js';
5
- import { claudeQuota } from './quota.js';
6
- export const run = makeAdapter('claude', { normaliseQuota: claudeQuota });
1
+ // Claude Code: `claude -p --output-format stream-json --verbose`, prompt on stdin, `--resume <id>`.
2
+ // Quirks: total_cost_usd is cumulative for the session on resume; common.js takes the delta.
3
+ // stream-json is used only so the rate_limit_event line (remaining quota) comes with each reply.
4
+ import { makeAdapter } from './common.js';
5
+ import { claudeQuota } from './quota.js';
6
+ export const run = makeAdapter('claude', { normaliseQuota: claudeQuota });
@@ -1,6 +1,6 @@
1
- // Codex: `codex exec --json`, prompt on stdin (`-`), `exec resume <id>`.
2
- // Quirks: usage comes in the turn.completed event, no cost; `resume` rejects --sandbox so the
3
- // policy is passed with -c sandbox_mode; the PATH entry is an npm .cmd shim, so spawn.js runs
4
- // bin/codex.js through node instead.
5
- import { makeAdapter } from './common.js';
6
- export const run = makeAdapter('codex');
1
+ // Codex: `codex exec --json`, prompt on stdin (`-`), `exec resume <id>`.
2
+ // Quirks: usage comes in the turn.completed event, no cost; `resume` rejects --sandbox so the
3
+ // policy is passed with -c sandbox_mode; the PATH entry is an npm .cmd shim, so spawn.js runs
4
+ // bin/codex.js through node instead.
5
+ import { makeAdapter } from './common.js';
6
+ export const run = makeAdapter('codex');
@@ -29,17 +29,40 @@ const reportedCost = (v) => Number.isFinite(v) && v >= 0 ? v : null;
29
29
  // Pull the normalised fields out of one JSON object using the config's dot paths.
30
30
  export function pickJson(obj, paths) {
31
31
  const n = (p) => dig(obj, p);
32
+ const usage = usageCounters({ input: n(paths.input), cacheRead: n(paths.cacheRead), cacheWrite: n(paths.cacheWrite),
33
+ output: n(paths.output), thinking: n(paths.thinking) });
34
+ const total = n(paths.total);
35
+ if (usage && Number.isSafeInteger(total) && total >= 0) usage.providerTotal = total;
32
36
  return {
33
37
  text: String(dig(obj, paths.text) ?? ''),
34
38
  sessionId: dig(obj, paths.sessionId) ?? null,
35
- usage: usageCounters({ input: n(paths.input), cacheRead: n(paths.cacheRead), cacheWrite: n(paths.cacheWrite),
36
- output: n(paths.output), thinking: n(paths.thinking) }),
39
+ usage,
37
40
  cost: reportedCost(dig(obj, paths.cost)),
38
41
  quota: paths.quota ? (dig(obj, paths.quota) ?? null) : null,
39
42
  isError: paths.isError ? dig(obj, paths.isError) === true : false,
40
43
  };
41
44
  }
42
45
 
46
+ // Completed Antigravity model steps are incremental. Repeated updates for an index describe one step.
47
+ function completedStepUsage(events, paths) {
48
+ const steps = new Map();
49
+ for (const event of events) {
50
+ const s = event.step_update;
51
+ if (s?.step_type !== 'agent_response' || s.state !== 'DONE' || !Number.isSafeInteger(s.step_index) || s.step_index < 0) continue;
52
+ const u = pickJson(s, paths).usage;
53
+ if (u) steps.set(s.step_index, u);
54
+ }
55
+ if (!steps.size) return null;
56
+ const sum = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, thinking: 0 };
57
+ let providerTotal;
58
+ for (const u of steps.values()) {
59
+ for (const k of Object.keys(sum)) sum[k] += u[k];
60
+ if (u.providerTotal != null) providerTotal = (providerTotal ?? 0) + u.providerTotal;
61
+ }
62
+ return usageCounters(sum) && { ...sum, modelSteps: steps.size, tokenCoverage: { reported: 0, of: 1 },
63
+ ...(Number.isSafeInteger(providerTotal) ? { providerTotal } : {}) };
64
+ }
65
+
43
66
  // Same for a JSONL stream: each path names the event type that carries the value.
44
67
  export function pickJsonl(text, paths) {
45
68
  const events = parseLines(text);
@@ -90,7 +113,7 @@ export function normaliseUsage(cfg, u, rawCost = null) {
90
113
  // keepSession: the call's session will be resumed (resume memory), so the CLI must save it. Any
91
114
  // other fresh call adds the CLI's `ephemeral` argv when it has one; a resumed call never does,
92
115
  // since its session goes on.
93
- export function buildArgs(cfg, { prompt, sessionId = null, model = null, effort = null, instructionsFile = null, timeoutMs = 300_000, keepSession = false }) {
116
+ export function buildArgs(cfg, { prompt, sessionId = null, model = null, effort = null, instructionsFile = null, timeoutMs = 300_000, keepSession = false, providerHistory = 'prefer-ephemeral' }) {
94
117
  const useStdin = cfg.promptVia === 'stdin' ||
95
118
  (cfg.promptVia === 'argv-or-stdin' && prompt.length > ARGV_LIMIT);
96
119
  const streamMode = useStdin && !!cfg.stdinArgs;
@@ -98,7 +121,9 @@ export function buildArgs(cfg, { prompt, sessionId = null, model = null, effort
98
121
  const args = sessionId ? cfg.resume(sessionId, base) : [...base];
99
122
  const extra = [];
100
123
  if (cfg.stream) extra.push(...cfg.stream(timeoutMs, effort)); // the stream's idle limit fits inside the call limit
101
- if (!keepSession && !sessionId && cfg.ephemeral) extra.push(...cfg.ephemeral);
124
+ const canRunEphemeral = !keepSession && !sessionId && cfg.ephemeral;
125
+ if (providerHistory === 'require-ephemeral' && !canRunEphemeral) throw new Error(`${cfg.label} cannot confirm a non-saving session.`);
126
+ if (providerHistory !== 'provider-default' && canRunEphemeral) extra.push(...cfg.ephemeral);
102
127
  if (model && cfg.model) extra.push(...cfg.model(model));
103
128
  if (instructionsFile) extra.push('-c', `model_instructions_file=${JSON.stringify(instructionsFile)}`);
104
129
  // Skip the effort flag when the model id already names the level (agy), so nothing is said twice.
@@ -113,6 +138,17 @@ export function buildArgs(cfg, { prompt, sessionId = null, model = null, effort
113
138
  return { args, stdin, streamMode };
114
139
  }
115
140
 
141
+ // Strict reviews also check the installed CLI. Reading help never opens a session.
142
+ export async function checkEphemeralCli(cfg, bin) {
143
+ let help;
144
+ try {
145
+ const command = bin ?? resolveBinary(cfg.binary, cfg.npmBin);
146
+ help = await runProcess(command, cfg.ephemeralHelp, { env: cleanEnv(), timeoutMs: 5000, maxOutputBytes: 384 * 1024 });
147
+ } catch { /* A missing or unresponsive CLI cannot confirm support. */ }
148
+ const words = help?.code === 0 ? (help.stdout + '\n' + help.stderr).split(/[\s,=]+/) : [];
149
+ if (!cfg.ephemeral.every(flag => words.includes(flag))) throw new Error(`${cfg.label} could not confirm ${cfg.ephemeral.join(' ')} in its CLI help. Check the installation or choose another provider.`);
150
+ }
151
+
116
152
  // Build a run(prompt, sessionId, opts) for one config row. All three adapters are this
117
153
  // function with a different row; the per-CLI files exist so a vendor quirk has a home.
118
154
  export function makeAdapter(name, overrides = {}) {
@@ -150,10 +186,10 @@ export function makeAdapter(name, overrides = {}) {
150
186
  const guard = searching ? searching.foreignTool : cfg.usedTools; // search allowed, every other tool still stops the call
151
187
  if (cfg.limitedIsolation && !opts.allowLimitedIsolation) throw Object.assign(new Error('Explicit consent to limited isolation is required.'), { code: 'ISOLATION_REQUIRED' });
152
188
  if (cfg.terms && opts.acknowledgeTermsRisk !== true) throw Object.assign(new Error(`The person has not acknowledged ${cfg.label}'s terms notice.`), { code: 'TERMS_ACK_REQUIRED' });
153
- bin ??= cfg.bin || resolveBinary(cfg.binary, cfg.npmBin); // cfg.bin: a test's fake CLI
154
189
  // One time limit for the process and for the argv derived from it (cfg.stream).
155
190
  const timeoutMs = research ? Math.min(research.timeoutMs, opts.timeoutMs ?? research.timeoutMs) : opts.timeoutMs ?? 300_000;
156
- const built = buildArgs(cfg, { prompt, sessionId, model: opts.model, effort: opts.effort, instructionsFile, timeoutMs, keepSession: opts.keepSession === true });
191
+ const built = buildArgs(cfg, { prompt, sessionId, model: opts.model, effort: opts.effort, instructionsFile, timeoutMs, keepSession: opts.keepSession === true, providerHistory: opts.providerHistory });
192
+ bin ??= cfg.bin || resolveBinary(cfg.binary, cfg.npmBin); // cfg.bin: a test's fake CLI
157
193
  const { stdin, streamMode } = built;
158
194
  const args = searching ? searching.args(built.args) : built.args;
159
195
 
@@ -231,6 +267,11 @@ export function makeAdapter(name, overrides = {}) {
231
267
  completed = !!last;
232
268
  const obj = last ? last.result : {};
233
269
  picked = pickJson(obj, cfg.paths);
270
+ if (name === 'agy') {
271
+ const lower = completedStepUsage(events, cfg.paths);
272
+ if (lower && picked.usage) picked.usage.modelSteps = lower.modelSteps;
273
+ else if (lower) picked.usage = lower;
274
+ }
234
275
  usedTools = !!guard?.(obj, events);
235
276
  } else if (cfg.output === 'jsonl') {
236
277
  const events = parseLines(res.stdout);
@@ -288,6 +329,7 @@ export function makeAdapter(name, overrides = {}) {
288
329
  // An error result is not a reply; what the call cost still counts.
289
330
  if (picked.isError) throw Object.assign(new Error(`${cfg.label}: ${picked.text.trim().slice(0, 300)}`), { raw, ...accounting, sessionId: picked.sessionId });
290
331
  const quota = cfg.normaliseQuota && picked.quota ? cfg.normaliseQuota(picked.quota) : null;
332
+ progress.providerHistory = opts.providerHistory !== 'provider-default' && !sessionId && !opts.keepSession && cfg.ephemeral ? 'ephemeral' : 'provider-managed';
291
333
  return { text: picked.text.trim(), ...accounting, sessionId: picked.sessionId, quota, usedTools, raw };
292
334
  }
293
335
  }
@@ -185,6 +185,7 @@ export const ADAPTERS = {
185
185
  resume: (id, base) => [...base, '--resume', id],
186
186
  // without it every seat call left a session, prompts included, under ~/.claude/projects
187
187
  ephemeral: ['--no-session-persistence'],
188
+ ephemeralHelp: ['--help'],
188
189
  model: (m) => ['--model', m],
189
190
  effort: (e) => ['--effort', e],
190
191
  effortLevels: ['low', 'medium', 'high'], // `claude --help`: "--effort <level>"
@@ -256,6 +257,7 @@ export const ADAPTERS = {
256
257
  ...CODEX_ISOLATION, '-c', 'sandbox_mode="read-only"', '-c', 'project_doc_max_bytes=0', ...CODEX_NO_TOOLS, ...CODEX_NO_TELEMETRY, ...CODEX_RUNTIME, '-'],
257
258
  // without it every seat call left a session file, prompts included, under ~/.codex/sessions
258
259
  ephemeral: ['--ephemeral'],
260
+ ephemeralHelp: ['exec', '--help'],
259
261
  completionGraceMs: 1000,
260
262
  // Replace the coding-agent base prompt: these calls review decisions, not repositories.
261
263
  // The CLI tool restrictions and the wrapper's stream guard still apply independently.
@@ -371,6 +373,7 @@ export const ADAPTERS = {
371
373
  sessionId: 'conversation_id',
372
374
  input: 'usage.input_tokens',
373
375
  cacheRead: 'usage.cache_read_tokens',
376
+ total: 'usage.total_tokens',
374
377
  cacheWrite: null,
375
378
  output: 'usage.output_tokens',
376
379
  thinking: 'usage.thinking_tokens',
@@ -385,6 +388,8 @@ export const ADAPTERS = {
385
388
  // stays the seat's. A tool step's ACTIVE and DONE updates share its step_index.
386
389
  research: {
387
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.',
388
393
  searchIds: (e) => {
389
394
  const names = agyToolNames(e), i = e?.step_update?.step_index;
390
395
  return names.length === 1 && names[0] === AGY_SEARCH ? [Number.isSafeInteger(i) ? `step-${i}` : null] : [];
@@ -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
  }
@@ -1,131 +1,133 @@
1
- import { LIMITS } from './validate.js';
2
- import { PROFILE_PROVIDERS, providerProfile } from './seats.js';
3
- import { localClient } from './local-http.js';
4
-
5
- export const HELP = {
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]',
7
- commands: {
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.',
10
- check: 'Validate --input and estimate calls/tokens without creating a review.',
11
- start: 'Start the review in --input. Uses the selected providers. Returns its id immediately.',
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.',
13
- answer: 'Send --input {round, answers:[{id:"q1",text:"..."}], message:"optional note"}, labelled as an agent note. Read the current state first; never invent a missing answer.',
14
- hold: 'Send --input {round} to give the user another answer window. This is a bounded extension, not an indefinite pause. It makes no model call.',
15
- stop: 'Cancel all in-flight calls, including the chairman; keep completed replies. A verdict runs later only if explicitly requested.',
16
- finish: 'End discussion and write the verdict from collected replies. Available after one complete round has a usable reply; may make a chairman call.',
17
- resume: 'Resume an interrupted review. May make provider calls.',
18
- verdict: 'Request a missing or failed verdict from saved replies. May make a provider call.',
19
- },
20
- 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.',
21
- 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.',
22
- 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.',
23
- recipe: {
24
- questions: 'When nextAction.type is ask_user, present gate.questions with an available user-input tool; if unavailable, ask in normal chat. Tell the user when the answer window closes (gate.secondsUntilAutoContinue, or gate.autoContinueAtIso; autoContinueAt is epoch milliseconds) and that unknowns stay unknown. Send the user\'s own reply as answers with from "user"; anything you add yourself goes in message, or in an answer with from "assistant". Do not just print JSON or answer for the user. In an async host, use nextAction.waitCommand while the question is pending; await_user means it has already been shown, so do not ask again. Read status before sending the user reply; if the round has advanced, preserve the reply and report that it was not submitted. Use hold only when the person needs more time, never as an automatic keepalive.',
25
- size: 'Normally use two seats, critiqueRounds 1 (the engine default), memory stateless and an explicit budget per vendor: up to five calls before repairs. Use 0 only for a requested quick comparison and disclose that the seats did not respond to each other. Consider 2 for a requested deep review or a decision with several consequential trade-offs, within the user\'s time and budget. Consensus can end discussion early. Do not automatically start another review or exceed agreed limits because disagreement remains.',
26
- 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.',
27
- 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.',
28
- 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.',
29
- 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.',
30
- 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.',
31
- 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.',
32
- 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.',
33
- 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.',
34
- 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.',
35
- 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.',
36
- },
37
- };
38
-
39
- export async function runAgent(command, flags = {}, input, signal) {
40
- if (command === 'guide') return HELP;
41
- if (!Object.hasOwn(HELP.commands, command)) throw new Error('Unknown agent command. Use agent --help.');
42
- const port = Number(flags.port || process.env.PORT || 4747);
43
- if (!Number.isInteger(port) || port < LIMITS.port[0] || port > LIMITS.port[1]) throw new Error('Port must be a number from 1 to 65535.');
44
- if (flags.id && !/^[a-z0-9-]+$/.test(flags.id)) throw new Error('Invalid review id.');
45
- const { base, request } = localClient(port, signal);
46
- const route = flags.id ? `/api/debates/${flags.id}` : null;
47
- const board = (id) => `${base}/#${id}`; // where a person can watch this review in a browser
48
- let result;
49
- if (command === 'status' && !route) {
50
- const setup = await request('/api/seats?cached=1');
51
- const inventory = await request('/api/profiles', {});
52
- const pools = inventory.profiles.map((p) => 'acp@' + p.name);
53
- const readiness = !pools.length ? { pools: [] } : flags.refresh
54
- ? await request('/api/preflight', { pools, fresh: true })
55
- : await request('/api/preflight?pools=' + encodeURIComponent(pools.join(',')));
56
- result = { mode: setup.runtime.mode, cataloguePending: setup.runtime.cataloguePending === true, defaultTransport: 'agentlink', agentLink: inventory,
57
- providers: Object.keys(PROFILE_PROVIDERS).map((vendor) => {
58
- const profile = providerProfile(vendor, inventory.profiles);
59
- return { vendor, transport: 'agentlink', account: profile?.name || null, configured: !!profile, ...(profile?.defaults ? { defaults: profile.defaults } : {}) };
60
- }),
61
- directProviders: setup.vendors.filter((v) => v.kind !== 'acp').map((v) => ({ vendor: v.vendor, kind: v.kind, ...(v.kind === 'cli' ? { transport: 'cli' } : {}),
62
- models: (v.catalogue?.models || []).map((m) => typeof m === 'string' ? m : m.id), efforts: v.catalogue?.efforts || [],
63
- ...(v.terms ? { terms: { notice: v.terms.notice, url: v.terms.url, acknowledgedOnBoard: v.terms.acknowledgedAt != null } } : {}) })),
64
- readiness: readiness.pools, defaults: setup.defaults, next: 'Check a JSON review with agent check --input file. No model call has been made.' };
65
- } else if (command === 'models') result = await request('/api/profile-models', input || {}, 45_000);
66
- else if (command === 'check') result = await request('/api/preview', input, 40_000);
67
- 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}` }; }
68
- else {
69
- if (!route) throw new Error('This command needs --id from agent start or the board URL.');
70
- if (command === 'status') result = { ...(await request(`${route}/state`)), board: board(flags.id) };
71
- else if (command === 'wait') {
72
- const seconds = Number(flags.seconds || 25);
73
- if (!Number.isInteger(seconds) || seconds < LIMITS.waitSeconds[0] || seconds > LIMITS.waitSeconds[1]) throw new Error('Wait seconds must be a whole number from 1 to 30.');
74
- const afterRound = flags['after-round'] == null ? -1 : Number(flags['after-round']);
75
- if (!Number.isInteger(afterRound) || afterRound < -1 || afterRound > LIMITS.critiqueRounds[1] || flags['after-round'] != null && afterRound < 0) throw new Error('After round must be a whole number from 0 to 8.');
76
- result = await request(`${route}/state`);
77
- if (['researching', 'running', 'verdict'].includes(result.status) || result.status === 'waiting' && (result.gate?.round === afterRound || result.gate?.mode === 'countdown' && !result.gate.questions.length)) {
78
- const controller = new AbortController(), timer = setTimeout(() => controller.abort(), seconds * 1000);
79
- const waiting = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
80
- let reader;
81
- // Node 22 can lose fetch's abort link after collection while an SSE body
82
- // is idle. Cancel the held reader directly so its pending read settles.
83
- const cancelRead = () => { reader?.cancel().catch(() => {}); };
84
- waiting.addEventListener('abort', cancelRead, { once: true });
85
- try {
86
- const response = await fetch(`${base}${route}/events`, { redirect: 'error', signal: waiting, headers: { 'last-event-id': result.revision } });
87
- if (!response.ok) throw new Error('Could not wait for review events.');
88
- reader = response.body.getReader();
89
- waiting.throwIfAborted();
90
- const decoder = new TextDecoder(); let buffer = '', finished = false;
91
- while (!finished) {
92
- const next = await reader.read(); if (next.done) break;
93
- buffer += decoder.decode(next.value, { stream: true });
94
- let end;
95
- while ((end = buffer.indexOf('\n\n')) >= 0) {
96
- const event = buffer.slice(0, end).split('\n').find((line) => line.startsWith('data: ')); buffer = buffer.slice(end + 2);
97
- if (event) {
98
- const update = JSON.parse(event.slice(6));
99
- if (['done', 'error', 'interrupted'].includes(update.type) || update.type === 'gate' && update.round !== afterRound && (update.questions?.length || update.mode === 'blocking')) finished = true;
100
- }
101
- }
102
- }
103
- signal?.throwIfAborted();
104
- } catch (error) { signal?.throwIfAborted(); if (!controller.signal.aborted) throw error; }
105
- finally {
106
- clearTimeout(timer);
107
- waiting.removeEventListener('abort', cancelRead);
108
- if (reader) await reader.cancel().catch(() => {});
109
- }
110
- result = await request(`${route}/state`);
111
- }
112
- result = { ...result, board: board(flags.id) };
113
- if (result.nextAction?.type === 'ask_user' && result.gate.round === afterRound) {
114
- result.nextAction = { ...result.nextAction, type: 'await_user', instruction: 'These questions have already been presented. Keep the existing prompt pending; do not ask again or invent answers. Read status before submitting a reply. Use waitCommand to wait for another step without extending the response window.' };
115
- }
116
- } else {
117
- const body = structuredClone(input ?? {});
118
- if (!body || typeof body !== 'object' || Array.isArray(body)) throw new Error('Input must be a JSON object.');
119
- if (['answer', 'finish', 'stop', 'resume'].includes(command)) body.source = 'agent';
120
- 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.');
121
- result = await request(`${route}/${command === 'answer' ? 'continue' : command === 'verdict' ? 'synthesize' : command}`, body);
122
- result = { ...result, id: flags.id, board: board(flags.id), next: `agent wait --port ${port} --id ${flags.id}` };
123
- }
124
- }
125
- if (['ask_user', 'await_user'].includes(result.nextAction?.type)) {
126
- result.nextAction.command = `agent answer --port ${port} --id ${flags.id} --input -`;
127
- result.nextAction.waitCommand = `agent wait --port ${port} --id ${flags.id} --after-round ${result.gate.round}`;
128
- result.nextAction.extend = { command: `agent hold --port ${port} --id ${flags.id} --input -`, input: { round: result.gate.round } };
129
- }
130
- return { ok: true, ...result };
131
- }
1
+ import { LIMITS } from './validate.js';
2
+ import { PROFILE_PROVIDERS, providerProfile } from './seats.js';
3
+ import { localClient } from './local-http.js';
4
+
5
+ export const HELP = {
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]',
7
+ commands: {
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.',
10
+ check: 'Validate --input and estimate calls/tokens without creating a review.',
11
+ start: 'Start the review in --input. Uses the selected providers. Returns its id immediately.',
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.',
13
+ answer: 'Send --input {round, answers:[{id:"q1",text:"..."}], message:"optional note"}, labelled as an agent note. Read the current state first; never invent a missing answer.',
14
+ hold: 'Send --input {round} to give the user another answer window. This is a bounded extension, not an indefinite pause. It makes no model call.',
15
+ stop: 'Cancel all in-flight calls, including the chairman; keep completed replies. A verdict runs later only if explicitly requested.',
16
+ finish: 'End discussion and write the verdict from collected replies. Available after one complete round has a usable reply; may make a chairman call.',
17
+ resume: 'Resume an interrupted review. May make provider calls.',
18
+ verdict: 'Request a missing or failed verdict from saved replies. May make a provider call.',
19
+ },
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.',
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.',
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.',
24
+ recipe: {
25
+ questions: 'When nextAction.type is ask_user, present gate.questions with an available user-input tool; if unavailable, ask in normal chat. Tell the user when the answer window closes (gate.secondsUntilAutoContinue, or gate.autoContinueAtIso; autoContinueAt is epoch milliseconds) and that unknowns stay unknown. Send the user\'s own reply as answers with from "user"; anything you add yourself goes in message, or in an answer with from "assistant". Do not just print JSON or answer for the user. In an async host, use nextAction.waitCommand while the question is pending; await_user means it has already been shown, so do not ask again. Read status before sending the user reply; if the round has advanced, preserve the reply and report that it was not submitted. Use hold only when the person needs more time, never as an automatic keepalive.',
26
+ size: 'Normally use two seats, critiqueRounds 1 (the engine default), memory stateless and an explicit budget per vendor: up to five calls before repairs. Use 0 only for a requested quick comparison and disclose that the seats did not respond to each other. Consider 2 for a requested deep review or a decision with several consequential trade-offs, within the user\'s time and budget. Consensus can end discussion early. Do not automatically start another review or exceed agreed limits because disagreement remains.',
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.',
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.',
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.',
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.',
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.',
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.',
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.',
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.',
37
+ },
38
+ };
39
+
40
+ export async function runAgent(command, flags = {}, input, signal) {
41
+ if (command === 'guide') return HELP;
42
+ if (!Object.hasOwn(HELP.commands, command)) throw new Error('Unknown agent command. Use agent --help.');
43
+ const port = Number(flags.port || process.env.PORT || 4747);
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.');
45
+ if (flags.id && !/^[a-z0-9-]+$/.test(flags.id)) throw new Error('Invalid review id.');
46
+ const dispatchesReview = ['check', 'start', 'answer', 'finish', 'resume', 'verdict'].includes(command);
47
+ const { base, request } = localClient(port, signal, { requireCurrentVersion: dispatchesReview });
48
+ const route = flags.id ? `/api/debates/${flags.id}` : null;
49
+ const board = (id) => `${base}/#${id}`; // where a person can watch this review in a browser
50
+ let result;
51
+ if (command === 'status' && !route) {
52
+ const setup = await request('/api/seats?cached=1');
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' } : {}),
64
+ models: (v.catalogue?.models || []).map((m) => typeof m === 'string' ? m : m.id), efforts: v.catalogue?.efforts || [],
65
+ ...(v.terms ? { terms: { notice: v.terms.notice, url: v.terms.url, acknowledgedOnBoard: v.terms.acknowledgedAt != null } } : {}) })),
66
+ readiness: readiness.pools, defaults: setup.defaults, next: 'Check a JSON review with agent check --input file. No model call has been made.' };
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}` }; }
70
+ else {
71
+ if (!route) throw new Error('This command needs --id from agent start or the board URL.');
72
+ if (command === 'status') result = { ...(await request(`${route}/state`)), board: board(flags.id) };
73
+ else if (command === 'wait') {
74
+ const seconds = Number(flags.seconds || 25);
75
+ if (!Number.isInteger(seconds) || seconds < LIMITS.waitSeconds[0] || seconds > LIMITS.waitSeconds[1]) throw new Error('Wait seconds must be a whole number from 1 to 30.');
76
+ const afterRound = flags['after-round'] == null ? -1 : Number(flags['after-round']);
77
+ if (!Number.isInteger(afterRound) || afterRound < -1 || afterRound > LIMITS.critiqueRounds[1] || flags['after-round'] != null && afterRound < 0) throw new Error('After round must be a whole number from 0 to 8.');
78
+ result = await request(`${route}/state`);
79
+ if (['researching', 'running', 'verdict'].includes(result.status) || result.status === 'waiting' && (result.gate?.round === afterRound || result.gate?.mode === 'countdown' && !result.gate.questions.length)) {
80
+ const controller = new AbortController(), timer = setTimeout(() => controller.abort(), seconds * 1000);
81
+ const waiting = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
82
+ let reader;
83
+ // Node 22 can lose fetch's abort link after collection while an SSE body
84
+ // is idle. Cancel the held reader directly so its pending read settles.
85
+ const cancelRead = () => { reader?.cancel().catch(() => {}); };
86
+ waiting.addEventListener('abort', cancelRead, { once: true });
87
+ try {
88
+ const response = await fetch(`${base}${route}/events`, { redirect: 'error', signal: waiting, headers: { 'last-event-id': result.revision } });
89
+ if (!response.ok) throw new Error('Could not wait for review events.');
90
+ reader = response.body.getReader();
91
+ waiting.throwIfAborted();
92
+ const decoder = new TextDecoder(); let buffer = '', finished = false;
93
+ while (!finished) {
94
+ const next = await reader.read(); if (next.done) break;
95
+ buffer += decoder.decode(next.value, { stream: true });
96
+ let end;
97
+ while ((end = buffer.indexOf('\n\n')) >= 0) {
98
+ const event = buffer.slice(0, end).split('\n').find((line) => line.startsWith('data: ')); buffer = buffer.slice(end + 2);
99
+ if (event) {
100
+ const update = JSON.parse(event.slice(6));
101
+ if (['done', 'error', 'interrupted'].includes(update.type) || update.type === 'gate' && update.round !== afterRound && (update.questions?.length || update.mode === 'blocking')) finished = true;
102
+ }
103
+ }
104
+ }
105
+ signal?.throwIfAborted();
106
+ } catch (error) { signal?.throwIfAborted(); if (!controller.signal.aborted) throw error; }
107
+ finally {
108
+ clearTimeout(timer);
109
+ waiting.removeEventListener('abort', cancelRead);
110
+ if (reader) await reader.cancel().catch(() => {});
111
+ }
112
+ result = await request(`${route}/state`);
113
+ }
114
+ result = { ...result, board: board(flags.id) };
115
+ if (result.nextAction?.type === 'ask_user' && result.gate.round === afterRound) {
116
+ result.nextAction = { ...result.nextAction, type: 'await_user', instruction: 'These questions have already been presented. Keep the existing prompt pending; do not ask again or invent answers. Read status before submitting a reply. Use waitCommand to wait for another step without extending the response window.' };
117
+ }
118
+ } else {
119
+ const body = structuredClone(input ?? {});
120
+ if (!body || typeof body !== 'object' || Array.isArray(body)) throw new Error('Input must be a JSON object.');
121
+ if (['answer', 'finish', 'stop', 'resume'].includes(command)) body.source = 'agent';
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.');
123
+ result = await request(`${route}/${command === 'answer' ? 'continue' : command === 'verdict' ? 'synthesize' : command}`, body, ['resume', 'verdict'].includes(command) ? 40_000 : undefined);
124
+ result = { ...result, id: flags.id, board: board(flags.id), next: `agent wait --port ${port} --id ${flags.id}` };
125
+ }
126
+ }
127
+ if (['ask_user', 'await_user'].includes(result.nextAction?.type)) {
128
+ result.nextAction.command = `agent answer --port ${port} --id ${flags.id} --input -`;
129
+ result.nextAction.waitCommand = `agent wait --port ${port} --id ${flags.id} --after-round ${result.gate.round}`;
130
+ result.nextAction.extend = { command: `agent hold --port ${port} --id ${flags.id} --input -`, input: { round: result.gate.round } };
131
+ }
132
+ return { ok: true, ...result };
133
+ }