@staix/agent-research 0.3.1 → 0.5.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/cli.ts CHANGED
@@ -1,6 +1,10 @@
1
+ import { GpuLeaseError } from "./exp/executor.ts";
2
+ import { paperDocument } from "./paper/document.ts";
1
3
  import { version } from "../package.json";
2
- import { findCommand, help, type CommandSpec } from "./commands-table.ts";
4
+ import { findCommand, helpUsage, type CommandSpec } from "./commands-table.ts";
5
+ import { fillMessage, colorFor, outputAscii, renderError, renderHelp, renderResult, streamWidth, usageHint, type OutputContext, type OutputOptions } from "./cli-output.ts";
3
6
  import * as ops from "./commands.ts";
7
+ import { validateCalibrationOptions, type CalibrationOptions } from "./exp/calibrate.ts";
4
8
  import { createHttp, type Http } from "./http.ts";
5
9
  import { PLAYBOOK } from "./playbook.ts";
6
10
  import { validateExecutionReference } from "./provenance.ts";
@@ -9,32 +13,57 @@ import { detectActor, openStudy, readTextBounded, releaseStudyLocksForExit } fro
9
13
  const INPUT_BYTES = 65_536;
10
14
  export interface Io extends ops.ExperimentRuntime { readStdin?: () => Promise<string>; http?: Http; signal?: AbortSignal }
11
15
 
12
- function parse(spec: CommandSpec, args: string[]): { flags: Record<string, string | true>; positional: string[] } {
16
+ class UsageError extends Error {}
17
+
18
+ interface CliOutput {
19
+ options: OutputOptions;
20
+ context?: OutputContext;
21
+ spec?: CommandSpec;
22
+ tty?: boolean;
23
+ columns?: number;
24
+ }
25
+
26
+ export function parse(spec: CommandSpec, args: string[], output: OutputOptions = {}): { flags: Record<string, string | true>; positional: string[] } {
13
27
  const flags: Record<string, string | true> = {}, positional: string[] = [];
14
28
  for (let i = 0; i < args.length; i++) {
15
- const word = args[i]!;
29
+ const arg = args[i]!;
30
+ const word = arg.startsWith("--color=") ? "--color" : arg;
31
+ if (word === "--ascii" || word === "--color") {
32
+ if (word in flags) throw new UsageError(`${spec.name}: repeated option ${word}`);
33
+ if (word === "--ascii") {
34
+ flags[word] = output.ascii = true;
35
+ } else {
36
+ const value = arg === word ? args[++i] : arg.slice("--color=".length);
37
+ if (value === undefined || value.startsWith("--")) throw new UsageError("--color: expected auto, always or never");
38
+ flags[word] = output.color = value;
39
+ }
40
+ continue;
41
+ }
16
42
  if (word === "-" || !word.startsWith("-")) { positional.push(word); continue; }
17
43
  const kind = spec.options[word];
18
- if (!kind || word in flags) throw new Error(`${spec.name}: unknown or repeated option ${word}; use ares --help and pass each supported option once`);
44
+ if (!kind || word in flags) throw new UsageError(`${spec.name}: unknown or repeated option ${word}; use ares --help and pass each supported option once`);
19
45
  if (kind === "value") {
20
46
  const value = args[++i];
21
- if (value === undefined || (value.startsWith("--") && value !== "-")) throw new Error(`${spec.name}: ${word} needs a value; use ares --help for its accepted values`);
47
+ if (value === undefined || (value.startsWith("--") && value !== "-")) throw new UsageError(`${spec.name}: ${word} needs a value; use ares --help for its accepted values`);
22
48
  flags[word] = value;
23
- } else flags[word] = true;
49
+ } else {
50
+ flags[word] = true;
51
+ if (word === "--json") output.json = true;
52
+ }
24
53
  }
25
54
  return { flags, positional };
26
55
  }
27
56
  function count(spec: CommandSpec, positional: string[], min: number, max = min): void {
28
- if (positional.length < min || positional.length > max) throw new Error(`usage: ares ${spec.usage}`);
57
+ if (positional.length < min || positional.length > max) throw new UsageError(`usage: ares ${spec.usage}`);
29
58
  }
30
59
  function integer(value: string | true | undefined, what: string): number | undefined {
31
60
  if (value === undefined) return undefined;
32
- if (typeof value !== "string" || !/^\d{1,7}$/.test(value)) throw new Error(`${what}: integer required; pass a nonnegative decimal integer`);
61
+ if (typeof value !== "string" || !/^\d{1,7}$/.test(value)) throw new UsageError(`${what}: integer required; pass a nonnegative decimal integer`);
33
62
  return Number(value);
34
63
  }
35
64
  function seed(value: string | undefined): number | undefined {
36
65
  if (value === undefined) return undefined;
37
- if (!/^-?\d{1,10}$/.test(value) || !Number.isSafeInteger(Number(value)) || Number(value) < -2_147_483_648 || Number(value) > 2_147_483_647) throw new Error("--seed: invalid integer; use a declared protocol seed in -2147483648..2147483647");
66
+ if (!/^-?\d{1,10}$/.test(value) || !Number.isSafeInteger(Number(value)) || Number(value) < -2_147_483_648 || Number(value) > 2_147_483_647) throw new UsageError("--seed: invalid integer; use a declared protocol seed in -2147483648..2147483647");
38
67
  return Number(value);
39
68
  }
40
69
  async function readInput(path: string, io: Io): Promise<unknown> {
@@ -48,20 +77,61 @@ async function readInput(path: string, io: Io): Promise<unknown> {
48
77
  }
49
78
 
50
79
  export async function run(args: string[], env: NodeJS.ProcessEnv = process.env, io: Io = {}): Promise<{ text: string; code: number }> {
51
- if (!args.length || (args.length === 1 && ["--help", "-h", "help"].includes(args[0]!))) return { text: help(), code: 0 };
80
+ return execute(args, env, io, { options: {} });
81
+ }
82
+
83
+ async function execute(args: string[], env: NodeJS.ProcessEnv, io: Io, output: CliOutput): Promise<{ text: string; code: number }> {
84
+ const leadingHelp = args[0] === "help" || args[0] === "--help" || args[0] === "-h";
85
+ const helpArgs = leadingHelp ? args.slice(1) : args;
86
+ const helpCommand = args[0] === "help" || !leadingHelp ? findCommand(helpArgs) : undefined;
87
+ const trailingHelp = !leadingHelp && helpCommand?.rest[0] === "--help";
88
+ if (!args.length || leadingHelp || trailingHelp) {
89
+ const formatting = trailingHelp ? helpCommand.rest.slice(1) : helpCommand?.rest ?? helpArgs;
90
+ const spec = helpCommand?.spec;
91
+ if (spec) output.spec = spec;
92
+ const { positional } = parse({ name: spec?.name ?? "help", usage: "", mutates: false, options: {}, summary: "" }, formatting, output.options);
93
+ if (positional.length) {
94
+ throw new UsageError(spec ? `${spec.name}: unexpected help argument ${positional[0]}` : `unknown help command: ${positional.join(" ")}`);
95
+ }
96
+ const color = colorFor(output.options, output.tty ?? false, env);
97
+ if (color instanceof Error) throw new UsageError(color.message);
98
+ return { text: renderHelp(spec, color, outputAscii(output.options, env)), code: 0 };
99
+ }
52
100
  if (args.length === 1 && args[0] === "--version") return { text: version, code: 0 };
53
- const found = findCommand(args);
54
- if (!found) throw new Error(`unknown command: ${args.slice(0, 2).join(" ")}; use --help`);
55
- const { spec, rest } = found, { flags, positional } = parse(spec, rest);
56
- const ctx: ops.Ctx = { actor: detectActor(env), http: io.http ?? createHttp(env), ...(io.signal ? { signal: io.signal } : {}), ...(io.sleep ? { sleep: io.sleep } : {}), ...(io.runner ? { runner: io.runner } : {}), ...(io.now ? { now: io.now } : {}), ...(io.collectEvaluation ? { collectEvaluation: io.collectEvaluation } : {}), ...(io.collectStageEvidence ? { collectStageEvidence: io.collectStageEvidence } : {}) };
101
+ const found = helpCommand;
102
+ if (!found) throw new UsageError(`unknown command: ${args.slice(0, 2).join(" ")}; use --help`);
103
+ const { spec, rest } = found;
104
+ output.spec = spec;
105
+ const { flags, positional } = parse(spec, rest, output.options);
106
+ const values: Record<string, string> = {};
107
+ const declaration = helpUsage(spec).slice(spec.name.length).trim().split(/\s+(?=\[?--)/)[0] ?? "";
108
+ for (const [index, token] of declaration.split(/\s+/).entries()) {
109
+ const key = /<([a-z][a-z0-9-]*)>/.exec(token)?.[1];
110
+ if (key && positional[index] !== undefined) values[key] = positional[index]!;
111
+ }
112
+ const commandArgs = [...spec.name.split(" "), ...positional];
113
+ for (const [flag, value] of Object.entries(flags)) {
114
+ if (typeof value === "string") values[flag] = value;
115
+ if (["--json", "--ascii", "--color"].includes(flag)) continue;
116
+ commandArgs.push(flag);
117
+ if (typeof value === "string") commandArgs.push(value);
118
+ }
119
+ output.context = { args: commandArgs, values, now: io.now?.() ?? Date.now() };
120
+ const color = colorFor(output.options, output.tty ?? false, env);
121
+ if (color instanceof Error) throw new UsageError(color.message);
122
+ const ctx: ops.Ctx = { actor: detectActor(env), env, http: io.http ?? createHttp(env), ...(io.signal ? { signal: io.signal } : {}), ...(io.sleep ? { sleep: io.sleep } : {}), ...(io.runner ? { runner: io.runner } : {}), ...(io.now ? { now: io.now } : {}), ...(io.collectEvaluation ? { collectEvaluation: io.collectEvaluation } : {}), ...(io.collectStageEvidence ? { collectStageEvidence: io.collectStageEvidence } : {}) };
57
123
  const str = (flag: string) => (typeof flags[flag] === "string" ? flags[flag] as string : undefined);
124
+ const selectDocument = () => {
125
+ try { return paperDocument(str("--doc")); }
126
+ catch (error) { throw new UsageError(error instanceof Error ? error.message : "paper document: invalid --doc"); }
127
+ };
58
128
  let result: unknown, code = 0;
59
129
  switch (spec.name) {
60
130
  case "lineage show": {
61
131
  count(spec, positional, 1);
62
132
  const kind = str("--root"), id = str("--id"), revision = str("--revision"), hash = str("--sha256"), cursor = str("--cursor");
63
133
  const hasRoot = [kind, id, revision, hash].some(value => value !== undefined);
64
- if (hasRoot && (kind === undefined || id === undefined)) throw new Error("lineage show: partial root reference; pass --root KIND and --id ID together, with optional --revision/--sha256");
134
+ if (hasRoot && (kind === undefined || id === undefined)) throw new UsageError("lineage show: partial root reference; pass --root KIND and --id ID together, with optional --revision/--sha256");
65
135
  let root = hasRoot ? validateExecutionReference({ v: 1, tool: "ares", projectKey: "pending-study-identity", kind, id, ...(revision === undefined ? {} : { revision }), ...(hash === undefined ? {} : { sha256: hash }) }) : undefined;
66
136
  if (root) {
67
137
  let projectKey: string;
@@ -74,10 +144,10 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
74
144
  case "lineage compare": {
75
145
  count(spec, positional, 1);
76
146
  const attempts = str("--attempts"), candidates = str("--candidates");
77
- if (attempts !== undefined && candidates !== undefined) throw new Error("lineage compare: selection flags conflict; pass either --attempts ID,... or --candidates COMMIT,...");
147
+ if (attempts !== undefined && candidates !== undefined) throw new UsageError("lineage compare: selection flags conflict; pass either --attempts ID,... or --candidates COMMIT,...");
78
148
  const list = (value: string) => {
79
149
  const values = value.split(",");
80
- if (values.length < 1 || values.length > 8 || values.some(item => !item.trim())) throw new Error("lineage compare: selection needs 1..8 nonblank ids; pass a comma-separated --attempts or --candidates list");
150
+ if (values.length < 1 || values.length > 8 || values.some(item => !item.trim())) throw new UsageError("lineage compare: selection needs 1..8 nonblank ids; pass a comma-separated --attempts or --candidates list");
81
151
  return values;
82
152
  };
83
153
  result = ops.lineageCompare(positional[0]!, { ...(attempts === undefined ? {} : { attempts: list(attempts) }), ...(candidates === undefined ? {} : { candidates: list(candidates) }) }); break;
@@ -87,7 +157,7 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
87
157
  case "console list": count(spec, positional, 0); result = ops.consoleList(env); break;
88
158
  case "watch set": {
89
159
  count(spec, positional, 1); const file = str("--file");
90
- if (file === undefined) throw new Error("watch set: input missing; pass --file PATH or --file - for watch JSON");
160
+ if (file === undefined) throw new UsageError("watch set: input missing; pass --file PATH or --file - for watch JSON");
91
161
  result = await ops.watchSet(positional[0]!, await readInput(file, io), ctx); break;
92
162
  }
93
163
  case "watch run": {
@@ -97,7 +167,7 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
97
167
  case "watch show": count(spec, positional, 1); result = ops.watchShow(positional[0]!); break;
98
168
  case "setup": {
99
169
  count(spec, positional, 1);
100
- if (flags["--apply"] && flags["--undo"]) throw new Error("setup: --apply and --undo conflict; choose one or omit both for preview");
170
+ if (flags["--apply"] && flags["--undo"]) throw new UsageError("setup: --apply and --undo conflict; choose one or omit both for preview");
101
171
  const root = str("--root"); result = ops.setup(positional[0]!, flags["--apply"] ? "apply" : flags["--undo"] ? "undo" : "dry-run", env, { ...(root === undefined ? {} : { root }) });
102
172
  if ((result as ReturnType<typeof ops.setup>).actions.some(action => action.change === "refused")) code = 1;
103
173
  break;
@@ -107,19 +177,19 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
107
177
  case "lesson propose":
108
178
  case "lesson decide": {
109
179
  count(spec, positional, spec.name === "lesson propose" ? 1 : 2); const file = str("--file");
110
- if (file === undefined) throw new Error(`${spec.name}: input missing; pass --file PATH or --file - for bounded JSON`);
180
+ if (file === undefined) throw new UsageError(`${spec.name}: input missing; pass --file PATH or --file - for bounded JSON`);
111
181
  const raw = await readInput(file, io);
112
182
  result = spec.name === "lesson propose" ? await ops.lessonPropose(positional[0]!, raw, ctx, env) : await ops.lessonDecide(positional[0]!, positional[1]!, raw, ctx, env); break;
113
183
  }
114
184
  case "skill check": count(spec, positional, 2); result = await ops.skillCheck(positional[0]!, positional[1]!, ctx, env); break;
115
185
  case "skill propose": {
116
186
  count(spec, positional, 1); const file = str("--file");
117
- if (file === undefined) throw new Error("skill propose: input missing; pass --file PATH or --file - for proposal JSON");
187
+ if (file === undefined) throw new UsageError("skill propose: input missing; pass --file PATH or --file - for proposal JSON");
118
188
  result = await ops.skillPropose(positional[0]!, await readInput(file, io), ctx, env); break;
119
189
  }
120
190
  case "skill decide": {
121
191
  count(spec, positional, 3); const reason = str("--reason");
122
- if (reason === undefined) throw new Error("skill decide: reason missing; pass --reason TEXT and --pr URL for accept");
192
+ if (reason === undefined) throw new UsageError("skill decide: reason missing; pass --reason TEXT and --pr URL for accept");
123
193
  result = await ops.skillDecide(positional[0]!, positional[1]!, positional[2]!, reason, str("--pr"), ctx, undefined, env); break;
124
194
  }
125
195
  case "skill list": count(spec, positional, 1); result = ops.skillList(positional[0]!); break;
@@ -133,62 +203,72 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
133
203
  }
134
204
  case "run": {
135
205
  count(spec, positional, 1); const parallel = integer(flags["--parallel"], "--parallel");
136
- const completed = await ops.planRun(positional[0]!, { ...(parallel !== undefined ? { parallel } : {}) }, ctx);
206
+ const completed = await ops.planRun(positional[0]!, { ...(parallel !== undefined ? { parallel } : {}), env }, ctx);
137
207
  result = completed; if (completed.state === "failed") code = 1; break;
138
208
  }
139
209
  case "manifest": count(spec, positional, 0); result = ops.manifest(); break;
140
210
  case "playbook": count(spec, positional, 0); return { text: PLAYBOOK.trimEnd(), code: 0 };
141
- case "mcp": throw new Error("mcp: run `ares mcp` with no other arguments");
211
+ case "mcp": throw new UsageError("mcp: run `ares mcp` with no other arguments");
142
212
  case "autonomy show": count(spec, positional, 1); result = ops.autonomyShow(positional[0]!); break;
143
213
  case "autonomy set": count(spec, positional, 2); result = await ops.autonomySet(positional[0]!, positional[1]!, str("--phase"), ctx); break;
144
214
  case "init": {
145
215
  count(spec, positional, 1);
146
216
  const question = str("--question");
147
- if (question === undefined) throw new Error("init: --question is required");
217
+ if (question === undefined) throw new UsageError("init: --question is required");
148
218
  result = ops.init(positional[0]!, { question, ...(str("--mode") ? { mode: str("--mode")! } : {}), ...(str("--autonomy") ? { autonomy: str("--autonomy")! } : {}) }, ctx);
149
219
  break;
150
220
  }
151
221
  case "plan set": {
152
222
  count(spec, positional, 1);
153
223
  const file = str("--file");
154
- if (file === undefined) throw new Error("plan set: --file is required");
224
+ if (file === undefined) throw new UsageError("plan set: --file is required");
155
225
  result = await ops.planSet(positional[0]!, await readInput(file, io), ctx); break;
156
226
  }
157
227
  case "plan control": {
158
228
  count(spec, positional, 2, 3);
159
229
  const commandId = str("--command-id"), expectedRevision = integer(flags["--expected-revision"], "--expected-revision");
160
- if (!commandId || expectedRevision === undefined) throw new Error("plan control: command id and revision required; pass --command-id ID --expected-revision N from ares plan show");
230
+ if (!commandId || expectedRevision === undefined) throw new UsageError("plan control: command id and revision required; pass --command-id ID --expected-revision N from ares plan show");
161
231
  result = await ops.planControl(positional[0]!, { action: positional[1]! as Parameters<typeof ops.planControl>[1]["action"], ...(positional[2] !== undefined ? { node: positional[2] } : {}), commandId, expectedRevision }, ctx); break;
162
232
  }
163
233
  case "plan show": count(spec, positional, 1); result = ops.planShow(positional[0]!); break;
164
234
  case "status": count(spec, positional, 1); result = ops.status(positional[0]!); break;
165
235
  case "study export": {
166
236
  count(spec, positional, 1); const bundle = str("--bundle");
167
- if (bundle === undefined) throw new Error("study export: --bundle DIR is required; pass a new or empty output directory");
237
+ if (bundle === undefined) throw new UsageError("study export: --bundle DIR is required; pass a new or empty output directory");
168
238
  result = await ops.studyExport(positional[0]!, { bundle, ...(flags["--list"] ? { list: true } : {}) }); break;
169
239
  }
170
240
  case "scope": {
171
241
  count(spec, positional, 1);
172
242
  const file = str("--file");
173
- if (file === undefined) throw new Error("scope: --file is required");
243
+ if (file === undefined) throw new UsageError("scope: --file is required");
174
244
  result = await ops.scope(positional[0]!, await readInput(file, io), ctx);
175
245
  break;
176
246
  }
177
247
  case "idea add": {
178
248
  count(spec, positional, 1); const file = str("--file");
179
- if (file === undefined) throw new Error("idea add: input missing; pass --file PATH or --file - for JSON");
249
+ if (file === undefined) throw new UsageError("idea add: input missing; pass --file PATH or --file - for JSON");
180
250
  result = await ops.ideaAdd(positional[0]!, await readInput(file, io), ctx); break;
181
251
  }
182
252
  case "idea decide": {
183
253
  count(spec, positional, 3); const reason = str("--reason"), attempts = str("--attempts");
184
- if (reason === undefined) throw new Error("idea decide: reason missing; pass --reason TEXT and --commit SHA for refine, plus --attempts for an idea with commits");
254
+ if (reason === undefined) throw new UsageError("idea decide: reason missing; pass --reason TEXT and --commit SHA for refine, plus --attempts for an idea with commits");
185
255
  result = await ops.ideaDecide(positional[0]!, positional[1]!, { decision: positional[2], reason, ...(str("--cause") !== undefined ? { cause: str("--cause") } : {}), ...(str("--retry-when") !== undefined ? { retryWhen: str("--retry-when") } : {}), ...(attempts !== undefined ? { attempts: attempts.split(",") } : {}), ...(str("--commit") !== undefined ? { commit: str("--commit") } : {}) }, ctx); break;
186
256
  }
257
+ case "idea categories": {
258
+ count(spec, positional, 1); const file = str("--file");
259
+ if (file === undefined) throw new UsageError("idea categories: input missing; pass --file PATH or --file - for JSON");
260
+ result = await ops.ideaCategories(positional[0]!, await readInput(file, io), ctx); break;
261
+ }
262
+ case "idea report": {
263
+ count(spec, positional, 1); const window = integer(flags["--window"], "--window"), runArg = str("--run");
264
+ if (window !== undefined && (window < 1 || window > 1000)) throw new UsageError("--window: integer in 1..1000 required");
265
+ result = ops.ideaReport(positional[0]!, { ...(runArg !== undefined ? { run: runArg } : {}), ...(window !== undefined ? { window } : {}) }); break;
266
+ }
187
267
  case "investigate show": count(spec, positional, 1); result = ops.investigateShow(positional[0]!); break;
188
268
  case "investigate close": count(spec, positional, 1); result = await ops.investigateClose(positional[0]!, ctx); break;
189
269
  case "ablate add": {
190
270
  count(spec, positional, 1); const file = str("--file");
191
- if (file === undefined) throw new Error("ablate add: input missing; pass --file PATH or --file - for JSON");
271
+ if (file === undefined) throw new UsageError("ablate add: input missing; pass --file PATH or --file - for JSON");
192
272
  result = await ops.ablateAdd(positional[0]!, await readInput(file, io), ctx); break;
193
273
  }
194
274
  case "ablate show": count(spec, positional, 1); result = ops.ablateShow(positional[0]!); break;
@@ -197,75 +277,100 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
197
277
  case "final close": count(spec, positional, 1); result = await ops.finalClose(positional[0]!, ctx); break;
198
278
  case "final seeds": {
199
279
  count(spec, positional, 1); const file = str("--file");
200
- if (file === undefined) throw new Error("final seeds: input missing; pass --file PATH or --file - for JSON");
280
+ if (file === undefined) throw new UsageError("final seeds: input missing; pass --file PATH or --file - for JSON");
201
281
  result = await ops.finalSeeds(positional[0]!, await readInput(file, io), ctx); break;
202
282
  }
203
283
  case "selection": {
204
284
  count(spec, positional, 1);
205
285
  const file = str("--file");
206
- if (file === undefined) throw new Error("selection: input missing; pass --file PATH or --file - for a JSON rule");
286
+ if (file === undefined) throw new UsageError("selection: input missing; pass --file PATH or --file - for a JSON rule");
207
287
  result = await ops.selection(positional[0]!, await readInput(file, io), ctx); break;
208
288
  }
289
+ case "selection calibrate": {
290
+ count(spec, positional, 1);
291
+ const fromRun = str("--from-run"), nullCommit = str("--null"), z = str("--z");
292
+ if (!fromRun) throw new UsageError("selection calibrate: --from-run RUN is required");
293
+ let options: CalibrationOptions;
294
+ try {
295
+ options = validateCalibrationOptions({
296
+ fromRun, ...(nullCommit === undefined ? {} : { nullCommit }), ...(z === undefined ? {} : { z: Number(z) }),
297
+ });
298
+ } catch (error) {
299
+ throw new UsageError(error instanceof Error ? error.message : "selection calibrate: invalid options");
300
+ }
301
+ result = await ops.selectionCalibrate(positional[0]!, options, ctx);
302
+ break;
303
+ }
209
304
  case "retention inspect": {
210
305
  count(spec, positional, 1); const offset = str("--offset"), limit = integer(flags["--limit"], "--limit");
211
- if (offset !== undefined && !/^[0-9]{1,8}$/.test(offset)) throw new Error("retention inspect: offset must be in 0..16000000");
306
+ if (offset !== undefined && !/^[0-9]{1,8}$/.test(offset)) throw new UsageError("retention inspect: offset must be in 0..16000000");
212
307
  result = await ops.retentionInspect(positional[0]!, ctx, { ...(offset === undefined ? {} : { offset: Number(offset) }), ...(limit === undefined ? {} : { limit }) }); break;
213
308
  }
214
309
  case "retention prune": {
215
310
  count(spec, positional, 1); const file = str("--file"), fingerprint = str("--confirm");
216
- if (file === undefined) throw new Error("retention prune: --file PATH|- is required for explicit retained references");
311
+ if (file === undefined) throw new UsageError("retention prune: --file PATH|- is required for explicit retained references");
217
312
  const refs = await readInput(file, io);
313
+ if (!flags["--json"] && Array.isArray(refs)) output.context.previewCount = refs.length;
218
314
  result = await ops.retentionPrune(positional[0]!, { refs: refs as Parameters<typeof ops.retentionPrune>[1]["refs"], ...(fingerprint === undefined ? {} : { fingerprint }) }, ctx); break;
219
315
  }
220
316
  case "protocol": {
221
317
  count(spec, positional, 1);
222
318
  const file = str("--file");
223
- if (file === undefined) throw new Error("protocol: input file missing; use --file PATH or --file - for JSON standard input");
319
+ if (file === undefined) throw new UsageError("protocol: input file missing; use --file PATH or --file - for JSON standard input");
224
320
  result = await ops.protocol(positional[0]!, await readInput(file, io), ctx); break;
225
321
  }
226
322
  case "harness stream set": case "experience freeze": case "experience select": {
227
- count(spec, positional, 1); const file = str("--file"); if (!file) throw new Error(`usage: ares ${spec.usage}`);
323
+ count(spec, positional, 1); const file = str("--file"); if (!file) throw new UsageError(`usage: ares ${spec.usage}`);
228
324
  const raw = await readInput(file, io);
229
325
  result = spec.name === "harness stream set" ? await ops.harnessStreamSet(positional[0]!, raw, ctx) : spec.name === "experience freeze" ? await ops.experienceFreeze(positional[0]!, raw, ctx, env) : await ops.experienceSelect(positional[0]!, raw, ctx, env); break;
230
326
  }
231
327
  case "harness stream show": count(spec, positional, 1); result = ops.harnessStreamShow(positional[0]!); break;
232
328
  case "experience check": {
233
- count(spec, positional, 2); const model = str("--model"), runtime = str("--runtime"), toolsetSha256 = str("--toolset-sha256"); if (!model || !runtime) throw new Error(`usage: ares ${spec.usage}`);
329
+ count(spec, positional, 2); const model = str("--model"), runtime = str("--runtime"), toolsetSha256 = str("--toolset-sha256"); if (!model || !runtime) throw new UsageError(`usage: ares ${spec.usage}`);
234
330
  result = await ops.experienceCheck(positional[0]!, positional[1]!, {model, runtime, ...(toolsetSha256 !== undefined ? {toolsetSha256} : {})}, ctx, env); break;
235
331
  }
236
332
  case "harness contrast": case "harness compose": case "harness adopt": case "harness close": {
237
- count(spec, positional, 2); const file = str("--file"); if (!file) throw new Error(`usage: ares ${spec.usage}`);
333
+ count(spec, positional, 2); const file = str("--file"); if (!file) throw new UsageError(`usage: ares ${spec.usage}`);
238
334
  const form = await readInput(file, io);
239
335
  result = spec.name === "harness contrast" ? await ops.harnessContrast(positional[0]!, positional[1]!, form, ctx) : spec.name === "harness compose" ? await ops.harnessCompose(positional[0]!, positional[1]!, form, ctx) : spec.name === "harness close" ? await ops.harnessClose(positional[0]!, positional[1]!, form, str("--confirm"), ctx) : await ops.harnessAdopt(positional[0]!, positional[1]!, form, str("--confirm"), ctx); break;
240
336
  }
241
337
  case "harness set": {
242
- count(spec, positional, 1); const file = str("--file"); if (!file) throw new Error(`usage: ares ${spec.usage}`);
338
+ count(spec, positional, 1); const file = str("--file"); if (!file) throw new UsageError(`usage: ares ${spec.usage}`);
243
339
  result = await ops.harnessSet(positional[0]!, await readInput(file, io), ctx); break;
244
340
  }
245
341
  case "harness show": count(spec, positional, 1); result = ops.harnessShow(positional[0]!, str("--round")); break;
246
342
  case "harness import": {
247
- count(spec, positional, 2); const file = str("--file"); if (!file) throw new Error(`usage: ares ${spec.usage}`);
343
+ count(spec, positional, 2); const file = str("--file"); if (!file) throw new UsageError(`usage: ares ${spec.usage}`);
248
344
  result = await ops.harnessImport(positional[0]!, positional[1]!, await readInput(file, io), ctx); break;
249
345
  }
250
346
  case "executor set": {
251
347
  count(spec, positional, 1);
252
348
  const kind = str("--kind"), workdir = str("--workdir");
253
- if (!kind || !workdir) throw new Error("executor set: kind/workdir missing; use --kind local|ssh --workdir PATH and --host ALIAS for ssh");
349
+ if (!kind || !workdir) throw new UsageError("executor set: kind/workdir missing; use --kind local|ssh --workdir PATH and --host ALIAS for ssh");
254
350
  const gpuValues = [str("--gpu-devices"), str("--gpu-min-free-memory-mb"), str("--gpu-max-load-ratio")];
255
351
  const gpuRequested = gpuValues.some(value => value !== undefined);
256
- if (gpuRequested && gpuValues.some(value => value === undefined)) throw new Error("executor GPU: incomplete settings; pass --gpu-devices, --gpu-min-free-memory-mb and --gpu-max-load-ratio together");
352
+ if (gpuRequested && gpuValues.some(value => value === undefined)) throw new UsageError("executor GPU: incomplete settings; pass --gpu-devices, --gpu-min-free-memory-mb and --gpu-max-load-ratio together");
257
353
  const gpu = gpuRequested ? { devices: gpuValues[0]!.split(",").map(value => value.trim()), minFreeMemoryMb: Number(gpuValues[1]), maxLoadRatio: Number(gpuValues[2]) } : undefined;
258
- if (gpu && (!/^[0-9]{1,10}$/.test(gpuValues[1]!) || !/^(?:[0-9]+(?:\.[0-9]+)?|\.[0-9]+)$/.test(gpuValues[2]!))) throw new Error("executor GPU: invalid thresholds; use decimal memory MB and a positive decimal load ratio");
354
+ if (gpu && (!/^[0-9]{1,10}$/.test(gpuValues[1]!) || !/^(?:[0-9]+(?:\.[0-9]+)?|\.[0-9]+)$/.test(gpuValues[2]!))) throw new UsageError("executor GPU: invalid thresholds; use decimal memory MB and a positive decimal load ratio");
259
355
  const cap = str("--retention-cap-bytes");
260
- if (cap !== undefined && !/^[0-9]{1,13}$/.test(cap)) throw new Error("--retention-cap-bytes: expected an integer byte count in 1..1099511627776");
356
+ if (cap !== undefined && !/^[0-9]{1,13}$/.test(cap)) throw new UsageError("--retention-cap-bytes: expected an integer byte count in 1..1099511627776");
261
357
  result = await ops.executorSet(positional[0]!, { v: 1, kind, workdir, ...(cap !== undefined ? { retentionCapBytes: Number(cap) } : {}), ...(str("--host") !== undefined ? { host: str("--host") } : {}), ...(gpu ? { gpu } : {}) }, ctx); break;
262
358
  }
263
359
  case "executor inputs hash": count(spec, positional, 2); result = await ops.executorInputsHash(positional[0]!, positional[1]!, ctx); break;
264
- case "executor check": count(spec, positional, 1); result = await ops.executorCheck(positional[0]!, ctx); break;
360
+ case "executor check": {
361
+ count(spec, positional, 1);
362
+ if (flags["--json"]) result = await ops.executorCheck(positional[0]!, ctx);
363
+ else {
364
+ const report = await ops.executorCheckReport(positional[0]!, ctx);
365
+ result = report;
366
+ if (report.checks.some(row => row.state === "failed")) code = 1;
367
+ }
368
+ break;
369
+ }
265
370
  case "attempt run": {
266
371
  count(spec, positional, 1);
267
372
  const repo = str("--repo"), commit = str("--commit"), chosenSeed = seed(str("--seed"));
268
- if (!repo || !commit) throw new Error("attempt run: repo/commit missing; use --repo PATH --commit FULL_40_HEX_SHA");
373
+ if (!repo || !commit) throw new UsageError("attempt run: repo/commit missing; use --repo PATH --commit FULL_40_HEX_SHA");
269
374
  const attempt = await ops.attemptRun(positional[0]!, { repo, commit, ...(chosenSeed !== undefined ? { seed: chosenSeed } : {}), ...(str("--run") !== undefined ? { run: str("--run") } : {}), ...(str("--label") !== undefined ? { label: str("--label") } : {}), ...(str("--retry") !== undefined ? { retry: str("--retry") } : {}), ...(str("--reuse") !== undefined ? { reuse: str("--reuse") as "off" | "eligible" } : {}), ...(flags["--force-fresh"] ? { forceFresh: true } : {}), detach: !!flags["--detach"] }, ctx);
270
375
  if (attempt.status === "deferred") code = 75;
271
376
  else if (attempt.status !== "running" && attempt.status !== "succeeded") code = 1;
@@ -281,7 +386,6 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
281
386
  case "attempt logs": {
282
387
  count(spec, positional, 2); const tailBytes = integer(flags["--tail"], "--tail");
283
388
  const logs = await ops.attemptLogs(positional[0]!, positional[1]!, { ...(str("--stage") !== undefined ? { stage: str("--stage") } : {}), ...(str("--candidate-stage") !== undefined ? { candidateStage: str("--candidate-stage") } : {}), ...(str("--stream") !== undefined ? { stream: str("--stream") } : {}), ...(tailBytes !== undefined ? { tailBytes } : {}) }, ctx);
284
- if (!flags["--json"]) return { text: logs.logs.map(log => `[${log.candidateStage === undefined ? log.stage : `candidate:${log.candidateStage}`} ${log.stream}${log.truncated ? ", truncated copy" : ""}]\n${log.text}`).join("\n"), code: 0 };
285
389
  result = logs; break;
286
390
  }
287
391
  case "gate list": count(spec, positional, 1); result = ops.gateList(positional[0]!); break;
@@ -300,7 +404,7 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
300
404
  case "lit queries": count(spec, positional, 1); result = ops.queries(positional[0]!); break;
301
405
  case "lit flow": {
302
406
  count(spec, positional, 1);
303
- if (flags["--markdown"]) { if (flags["--json"]) throw new Error("lit flow: choose one of --markdown or --json"); return { text: ops.flowMarkdownView(positional[0]!).markdown.trimEnd(), code: 0 }; }
407
+ if (flags["--markdown"]) { if (flags["--json"]) throw new UsageError("lit flow: choose one of --markdown or --json"); return { text: ops.flowMarkdownView(positional[0]!).markdown.trimEnd(), code: 0 }; }
304
408
  result = ops.flow(positional[0]!); break;
305
409
  }
306
410
  case "lit list": {
@@ -310,15 +414,15 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
310
414
  break;
311
415
  }
312
416
  case "lit screen": {
313
- if (positional.length < 2) throw new Error(`usage: ares ${spec.usage}`);
314
- if (!!flags["--include"] === !!flags["--exclude"]) throw new Error("lit screen: exactly one of --include or --exclude");
417
+ if (positional.length < 2) throw new UsageError(`usage: ares ${spec.usage}`);
418
+ if (!!flags["--include"] === !!flags["--exclude"]) throw new UsageError("lit screen: exactly one of --include or --exclude");
315
419
  result = await ops.screen(positional[0]!, positional.slice(1), flags["--include"] ? "include" : "exclude", str("--reason"), ctx, undefined, str("--code"));
316
420
  break;
317
421
  }
318
422
  case "lit card export": case "lit card import": {
319
- if (positional.length < 2) throw new Error(`usage: ares ${spec.usage}`);
423
+ if (positional.length < 2) throw new UsageError(`usage: ares ${spec.usage}`);
320
424
  const vault = str("--vault");
321
- if (vault === undefined) throw new Error(`${spec.name}: --vault is required; pass the registered vault id (vmem vaults list)`);
425
+ if (vault === undefined) throw new UsageError(`${spec.name}: --vault is required; pass the registered vault id (vmem vaults list)`);
322
426
  const confirm = str("--confirm"), family = str("--model-family");
323
427
  result = spec.name === "lit card export"
324
428
  ? await ops.cardExport(positional[0]!, positional.slice(1), { vault, ...(confirm !== undefined ? { confirm } : {}), ...(family !== undefined ? { modelFamily: family } : {}) }, ctx, env)
@@ -329,28 +433,48 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
329
433
  case "lit card": {
330
434
  count(spec, positional, 2);
331
435
  const file = str("--file");
332
- if (file === undefined) throw new Error("lit card: --file is required");
436
+ if (file === undefined) throw new UsageError("lit card: --file is required");
333
437
  result = await ops.card(positional[0]!, positional[1]!, await readInput(file, io), ctx);
334
438
  break;
335
439
  }
336
- case "lit verify": if (!positional.length) throw new Error(`usage: ares ${spec.usage}`); result = await ops.verify(positional[0]!, positional.slice(1), ctx); break;
440
+ case "lit verify": if (!positional.length) throw new UsageError(`usage: ares ${spec.usage}`); result = await ops.verify(positional[0]!, positional.slice(1), ctx); break;
337
441
  case "lit bib": count(spec, positional, 1); result = await ops.bib(positional[0]!, ctx); break;
338
442
  case "review add": {
339
443
  count(spec, positional, 1); const file = str("--file");
340
- if (file === undefined) throw new Error("review add: --file is required; pass --file PATH|- with a current-build report");
444
+ if (file === undefined) throw new UsageError("review add: --file is required; pass --file PATH|- with a current-build report");
341
445
  result = await ops.reviewAdd(positional[0]!, await readInput(file, io), ctx); break;
342
446
  }
343
447
  case "review resolve": {
344
448
  count(spec, positional, 2); const reason = str("--reason");
345
- if (reason === undefined) throw new Error("review resolve: --reason is required; explain how the finding was resolved");
449
+ if (reason === undefined) throw new UsageError("review resolve: --reason is required; explain how the finding was resolved");
346
450
  result = await ops.reviewResolve(positional[0]!, positional[1]!, reason, ctx); break;
347
451
  }
348
452
  case "review show": count(spec, positional, 1); result = ops.reviewShow(positional[0]!); break;
349
453
  case "review checklist": count(spec, positional, 0); result = ops.reviewChecklistShow(); break;
350
- case "paper build": count(spec, positional, 1); result = await ops.paperBuild(positional[0]!, ctx); break;
454
+ case "paper build": count(spec, positional, 1); result = await ops.paperBuild(positional[0]!, ctx, selectDocument()); break;
455
+ case "paper render record": {
456
+ count(spec, positional, 1); const file = str("--file"), receipt = str("--receipt");
457
+ if (file === undefined || receipt === undefined) throw new UsageError("paper render record: --file and --receipt are required; pass the rendered document and the renderer's receipt JSON");
458
+ result = await ops.paperRenderRecord(positional[0]!, file, receipt, ctx, selectDocument()); break;
459
+ }
460
+ case "paper render show": count(spec, positional, 1); result = ops.paperRenderShow(positional[0]!, selectDocument()); break;
461
+ case "renderer set": {
462
+ count(spec, positional, 1); const command = str("--command"), timeout = str("--timeout-s");
463
+ if (command === undefined) throw new UsageError("renderer set: --command is required; pass the renderer argv as a JSON array using {study} and {out}");
464
+ let argv: unknown;
465
+ try { argv = JSON.parse(command); } catch { throw new UsageError("renderer set: --command must be a JSON array of strings"); }
466
+ if (timeout !== undefined && !/^[0-9]{1,6}$/.test(timeout)) throw new UsageError("--timeout-s: expected an integer number of seconds");
467
+ result = ops.rendererSet(positional[0]!, { command: argv, ...(timeout !== undefined ? { timeoutS: Number(timeout) } : {}) }, env); break;
468
+ }
469
+ case "renderer show": count(spec, positional, 1); result = ops.rendererShow(positional[0]!, env); break;
470
+ case "renderer check": {
471
+ count(spec, positional, 1); const report = ops.rendererCheck(positional[0]!, env);
472
+ if (!report.ok) code = 1;
473
+ result = report; break;
474
+ }
351
475
  case "paper plan set": {
352
476
  count(spec, positional, 1); const file = str("--file");
353
- if (file === undefined) throw new Error("paper plan set: input missing; pass --file PATH or --file - with a bounded version-1 paper-plan JSON");
477
+ if (file === undefined) throw new UsageError("paper plan set: input missing; pass --file PATH or --file - with a bounded version-1 paper-plan JSON");
354
478
  let plan: unknown;
355
479
  try { plan = await readInput(file, io); }
356
480
  catch { throw new Error("paper plan set: input is unreadable, non-regular, invalid UTF-8/JSON or larger than 64 KiB; restore a bounded JSON file or stdin, then retry ares paper plan set <dir> --file PATH|-"); }
@@ -358,20 +482,23 @@ export async function run(args: string[], env: NodeJS.ProcessEnv = process.env,
358
482
  }
359
483
  case "paper plan show": count(spec, positional, 1); result = ops.paperPlanShow(positional[0]!); break;
360
484
  case "paper check": {
361
- count(spec, positional, 1); const report = ops.paperCheck(positional[0]!);
485
+ count(spec, positional, 1); const report = ops.paperCheck(positional[0]!, selectDocument());
362
486
  if (!report.ok) code = 1;
363
487
  result = report; break;
364
488
  }
365
489
  case "cite check": {
366
490
  count(spec, positional, 2);
367
- const report = ops.cite(positional[0]!, positional[1]!);
491
+ const report = (flags["--json"] ? ops.cite : ops.citeHuman)(positional[0]!, positional[1]!);
368
492
  if (!report.ok) code = 1;
369
493
  result = report;
370
494
  break;
371
495
  }
372
- default: throw new Error(`unknown command: ${spec.name}`);
496
+ default: throw new UsageError(`unknown command: ${spec.name}`);
373
497
  }
374
- return { text: JSON.stringify(result, null, flags["--json"] ? undefined : 2), code };
498
+ const text = output.options.json
499
+ ? JSON.stringify(result)
500
+ : renderResult(spec.name, result, code, color, outputAscii(output.options, env), streamWidth(output.tty ?? false, output.columns, env), output.context);
501
+ return { text, code };
375
502
  }
376
503
 
377
504
  /** `ares mcp`: stdout carries protocol frames only. */
@@ -402,13 +529,29 @@ async function readStdinBounded(): Promise<string> {
402
529
  export async function main(args: string[]): Promise<number> {
403
530
  const stop = new AbortController(), interrupt = () => stop.abort();
404
531
  if (args[0] === "run") { process.on("SIGINT", interrupt); process.on("SIGTERM", interrupt); }
532
+ const env = process.env;
533
+ const cli: CliOutput = {
534
+ options: {},
535
+ tty: Boolean(process.stdout.isTTY),
536
+ ...(process.stdout.isTTY ? { columns: process.stdout.columns } : {}),
537
+ };
405
538
  try {
406
- const output = await run(args, process.env, { readStdin: readStdinBounded, signal: stop.signal });
539
+ const output = await execute(args, env, { readStdin: readStdinBounded, signal: stop.signal }, cli);
407
540
  console.log(output.text);
408
541
  return output.code;
409
542
  } catch (error) {
410
- console.error(`ares: ${error instanceof Error ? error.message : "operation failed"}`);
411
- return 1;
543
+ const tty = Boolean(process.stderr.isTTY);
544
+ const columns = streamWidth(tty, process.stderr.columns, env);
545
+ const color = colorFor(cli.options, tty, env) === true;
546
+ const usage = error instanceof UsageError || error instanceof GpuLeaseError;
547
+ let message = error instanceof Error ? error.message : "operation failed";
548
+ if (message.startsWith("usage: ares ")) message = `${cli.spec?.name ?? "command"}: missing or invalid arguments`;
549
+ const diagnostic = renderError(fillMessage(message, cli.context?.values ?? {}), tty, color, outputAscii(cli.options, env), Math.min(columns ?? 80, 80));
550
+ console.error(diagnostic);
551
+ if (usage) {
552
+ console.error(usageHint(cli.spec, columns));
553
+ }
554
+ return usage ? 2 : 1;
412
555
  } finally {
413
556
  if (args[0] === "run") { process.off("SIGINT", interrupt); process.off("SIGTERM", interrupt); }
414
557
  }