ostia 0.6.1 → 0.7.1

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/README.md CHANGED
@@ -24,8 +24,8 @@ group("ids", () => {
24
24
  ```
25
25
 
26
26
  <picture>
27
- <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/metonym/ostia/master/.github/assets/bench-dark.png">
28
- <img alt="ostia bench suite.ts: 2 tasks, fastest dedupe 2,000 at 21.6 µs, sort 2,000 at 123 µs, each with its noise and instructions per call" src="https://raw.githubusercontent.com/metonym/ostia/master/.github/assets/bench-light.png">
27
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/metonym/ostia/master/.github/assets/bench-dark.svg">
28
+ <img alt="ostia bench suite.ts as it runs: a progress bar at task 1 of 2, dedupe 2,000, then at 2 of 2, sort 2,000, then the result: fastest dedupe 2,000 at 18.4 µs, sort 2,000 at 97.9 µs, 5.31 times as long, each with its noise and instructions per call" src="https://raw.githubusercontent.com/metonym/ostia/master/.github/assets/bench-light.svg">
29
29
  </picture>
30
30
 
31
31
  **It tells you when a change made something slower.**
@@ -38,13 +38,6 @@ alternating batches in one process:
38
38
  <img alt="ostia ab suite.ts after dedupe moved from a Set to indexOf: fail, dedupe 2,000 regressed +207%, confirmed by repeats in fresh processes, sort 2,000 unchanged, ending with the command to profile it" src="https://raw.githubusercontent.com/metonym/ostia/master/.github/assets/ab-light.png">
39
39
  </picture>
40
40
 
41
- While it runs, one line says where it is:
42
-
43
- <picture>
44
- <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/metonym/ostia/master/.github/assets/progress-dark.png">
45
- <img alt="ostia ab's progress line: a bar at task 2 of 2, ids/sort 2,000" src="https://raw.githubusercontent.com/metonym/ostia/master/.github/assets/progress-light.png">
46
- </picture>
47
-
48
41
  Exit 1 on a regression, so CI can gate on it.
49
42
  `ostia time` does the same for whole commands:
50
43
 
@@ -146,7 +146,7 @@ Never emitted for `time`, `bench` or `report`.
146
146
  | `baseline` | `ci` only: `{ name, path }`. |
147
147
  | `git` | `{ base?, cand? }`, each `{ sha, branch, dirty }`, when available. |
148
148
  | `exportedTo` | The `--export-json` path, when given. |
149
- | `verdict` | `"pass"` when `exitCode` is 0, `"fail"` when it is 1 (a regression), `"error"` otherwise: exit 2 (harness error) or 130 (cancelled), where no verdict was reached. |
149
+ | `verdict` | `"pass"` when `exitCode` is 0, `"fail"` when it is 1 (a regression), `"error"` otherwise: exit 2 (harness error), 130 or 143 (cancelled), where no verdict was reached. |
150
150
  | `exitCode` | The process's exit code. |
151
151
 
152
152
  Example (`ostia ci --format events` after a regression):
@@ -166,9 +166,10 @@ The same across commands:
166
166
  | `1` | At least one workload failed its comparison (`compare`, `ci`), or a confirmed regression, a task that threw on the candidate side only, or the geomean over its threshold (`ab`). `time` and `bench` never return 1. |
167
167
  | `2` | Harness error: the numbers couldn't be produced or compared. |
168
168
  | `130` | Cancelled with Ctrl-C (`time`, `bench`, `ab`, `ci`). |
169
+ | `143` | Stopped by `SIGTERM`, as Ctrl-C stops it. |
169
170
 
170
- `--help` exits 0; a missing required argument prints the help
171
- and exits 2.
171
+ `--help` exits 0; a missing required argument is a usage error
172
+ (`invalid-flag`), exit 2.
172
173
 
173
174
  ## Errors
174
175
 
@@ -185,6 +186,20 @@ line of stderr:
185
186
  `data` is included when there is structured detail.
186
187
  stdout stays pure JSON for the machine formats.
187
188
 
189
+ With `--format json` (or `--json`), stdout gets the error too,
190
+ as its one document, so `JSON.parse(stdout)` succeeds
191
+ unless `--quiet` left it empty:
192
+
193
+ ```json
194
+ {"schemaVersion":2,"ok":false,"error":{"kind":"invalid-flag","message":"ostia time needs a command to time. Run \"ostia time --help\"."}}
195
+ ```
196
+
197
+ `error.kind` is the `code` below, and `message`
198
+ and `data` are the error line's.
199
+ A run that printed its document before it failed
200
+ (`time` with a failing command) adds no second one;
201
+ the line on stderr still says why.
202
+
188
203
  | `code` | Cause |
189
204
  |---|---|
190
205
  | `invalid-flag` | Unknown flag or subcommand, bad flag value, bad `--time-source` regex, wrong number of `--prepare` hooks, invalid baseline name, a surplus positional or a flag with nothing to act on (`--time-unit` without `--time-source`, `report --out-dir` with a non-visualization format), a `suites` glob in `ci` that matches no files, `ab` outside a git repository or with a `--base` that isn't a commit. |
package/docs/cli.md CHANGED
@@ -15,7 +15,10 @@ the version.
15
15
  A flag's value can follow it (`--format events`)
16
16
  or be attached (`--format=events`); `--ignore-failure[=CODES]` only
17
17
  takes the attached form.
18
- A flag that needs a value and is given none is a usage error (exit 2).
18
+ A flag that needs a value and is given none is a usage error (exit 2),
19
+ as is a missing argument: one line naming it, and where the help is.
20
+ An unknown flag or command names the nearest real
21
+ one: `Unknown flag "--jsno" for "ostia time" (did you mean --json?).`
19
22
  Exit codes and the machine-readable error line are described
20
23
  in [agent-protocol.md](agent-protocol.md).
21
24
 
@@ -137,6 +140,8 @@ a command with some timed-out trials and some samples still passes
137
140
  Ctrl-C cancels cleanly: in-flight children are killed,
138
141
  the document holds whatever finished (with an `aborted` warning),
139
142
  `--export-json` still writes it, and the exit code is 130.
143
+ `SIGTERM` does the same and exits 143; a second Ctrl-C,
144
+ for a run slow to stop, exits at once.
140
145
 
141
146
  ### `--prepare`
142
147
 
@@ -262,6 +267,9 @@ a suite failed to import or run, a task threw, a subprocess timed out,
262
267
  or a bad flag; `130` Ctrl-C.
263
268
  A failing suite stops the run: queued suites are skipped
264
269
  and in-flight ones killed.
270
+ Ctrl-C stops it as it stops `time`, and keeps every task that finished,
271
+ in a suite stopped mid-run too; the report counts them against the tasks
272
+ the started suites planned: `✗ Cancelled · 2 of 6 tasks measured`.
265
273
 
266
274
  ### Sampling
267
275
 
@@ -204,7 +204,7 @@ table; `--format events` includes `code` and `data`.
204
204
  | `jit-cold` | `--cpu` capture | More than 20% of samples in the llint/baseline tiers. |
205
205
  | `empty-profile` | CPU capture | The profile recorded no samples (`--cpu` or `profile()`). |
206
206
  | `artifact-missing` | CPU/heap capture | The expected `.cpuprofile`/`.heapsnapshot` file wasn't written. |
207
- | `aborted` | last measurement | The run was cancelled; the document is partial. |
207
+ | `aborted` | last measurement | The run was cancelled; the document is partial. From `bench`, `data.tasks` is how many tasks the suites that started had planned. |
208
208
  | `thin-comparison` | comparison | Fewer than 5 samples on a side; point-estimate verdict. |
209
209
  | `skipped` | comparison | The candidate task was skipped; treated as unchanged. |
210
210
  | `environment-mismatch` | comparison | The documents came from different platforms, Bun versions, or CPUs. |
package/index.d.ts CHANGED
@@ -847,8 +847,9 @@ export interface BenchOptions {
847
847
  /**
848
848
  * Aborting kills in-flight subprocesses, starts no new ones, and resolves
849
849
  * (never rejects) with whatever suites/tasks had finished, plus an
850
- * `aborted` warning on the last measurement. A suite killed mid-run is
851
- * dropped entirely: it only writes its result once, at the end. */
850
+ * `aborted` warning on the last measurement, whose `data.tasks` counts
851
+ * the tasks the started suites planned. A suite killed mid-run keeps the
852
+ * tasks it finished; an isolated task killed mid-run is dropped. */
852
853
  signal?: AbortSignal;
853
854
  /** Called before each task is measured, for a progress line. */
854
855
  onProgress?: (progress: BenchProgress) => void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ostia",
3
- "version": "0.6.1",
3
+ "version": "0.7.1",
4
4
  "description": "Fast profiling and benchmarking for Bun.",
5
5
  "license": "MIT",
6
6
  "author": "Eric Liu (https://github.com/metonym)",
@@ -15,7 +15,7 @@ import { stampDrift } from "../measure/environment.ts";
15
15
  import type { PeakMemResult } from "../measure/peak.ts";
16
16
  import { assertSamplingOptions } from "../measure/timing.ts";
17
17
  import { type SuiteLaunch, suiteLauncher } from "./projects.ts";
18
- import type { TaskProgress } from "./run-tasks.ts";
18
+ import { type MeasuredTask, partPath, type TaskProgress } from "./run-tasks.ts";
19
19
  import type { RunnerOpts } from "./runner.ts";
20
20
  import {
21
21
  absolutePath,
@@ -104,8 +104,9 @@ export interface BenchOptions {
104
104
  /**
105
105
  * Aborting kills in-flight subprocesses, starts no new ones, and resolves
106
106
  * (never rejects) with whatever suites/tasks had finished, plus an
107
- * `aborted` warning on the last measurement. A suite killed mid-run is
108
- * dropped entirely: it only writes its result once, at the end. */
107
+ * `aborted` warning on the last measurement, whose `data.tasks` counts
108
+ * the tasks the started suites planned. A suite killed mid-run keeps the
109
+ * tasks it finished; an isolated task killed mid-run is dropped. */
109
110
  signal?: AbortSignal;
110
111
  /** Called before each task is measured, for a progress line. */
111
112
  onProgress?: (progress: BenchProgress) => void;
@@ -263,6 +264,32 @@ function isPlan(value: unknown): value is { tasks: PlannedTask[] } {
263
264
  );
264
265
  }
265
266
 
267
+ // A stopped runner's finished tasks, in the order they ran: each file
268
+ // was renamed into place whole, so the first missing one ends them.
269
+ async function finishedTasks(outputPath: string): Promise<MeasuredTask[]> {
270
+ const tasks: MeasuredTask[] = [];
271
+ for (let n = 0; ; n++) {
272
+ const file = Bun.file(partPath(outputPath, n));
273
+ if (!(await file.exists())) return tasks;
274
+ const task: unknown = await file.json();
275
+ if (!isMeasuredTask(task)) {
276
+ throw new Error(`bench: unreadable finished task: ${file.name}`);
277
+ }
278
+ tasks.push(task);
279
+ }
280
+ }
281
+
282
+ // The runner wrote it, from the same types; only its shape is checked.
283
+ function isMeasuredTask(value: unknown): value is MeasuredTask {
284
+ return (
285
+ typeof value === "object" &&
286
+ value !== null &&
287
+ "workload" in value &&
288
+ "measurements" in value &&
289
+ Array.isArray(value.measurements)
290
+ );
291
+ }
292
+
266
293
  function isPeakMemResult(value: unknown): value is PeakMemResult {
267
294
  return (
268
295
  typeof value === "object" &&
@@ -318,6 +345,9 @@ export async function bench(opts: BenchOptions): Promise<ProfileDocument> {
318
345
  const filter = opts.filter !== undefined && { filter: opts.filter };
319
346
  const onProgress = opts.onProgress;
320
347
  const progress = onProgress !== undefined && { progress: true };
348
+ // A run that can be stopped keeps each task as it finishes, since a
349
+ // suite stopped mid-run never writes its document.
350
+ const partial = opts.signal !== undefined && { partial: true };
321
351
 
322
352
  const outPath = (tag: string, suite: Suite, ...rest: unknown[]) =>
323
353
  `${tmpDir}/${fp(tag, suite.path, ...rest)}.json`;
@@ -398,6 +428,7 @@ export async function bench(opts: BenchOptions): Promise<ProfileDocument> {
398
428
  ...filter,
399
429
  ...(opts.isolate !== undefined && { isolate: opts.isolate }),
400
430
  ...progress,
431
+ ...partial,
401
432
  preload: p.suite.preload,
402
433
  planPath: p.planPath,
403
434
  },
@@ -416,12 +447,27 @@ export async function bench(opts: BenchOptions): Promise<ProfileDocument> {
416
447
  }),
417
448
  );
418
449
  const primaryDocs = await Promise.all(
419
- primaries.map((p) => loadIfExists(p.outPath)),
450
+ primaries.map(async (p) => {
451
+ const doc = await loadIfExists(p.outPath);
452
+ if (doc) return { doc, whole: true };
453
+ // A suite stopped mid-run wrote no document, so its finished tasks
454
+ // stand in, a prefix of its plan.
455
+ const tasks = await finishedTasks(p.outPath);
456
+ if (tasks.length === 0) return undefined;
457
+ return {
458
+ doc: createDocument(
459
+ tasks.map((t) => t.workload),
460
+ tasks.flatMap((t) => t.measurements),
461
+ ),
462
+ whole: false,
463
+ };
464
+ }),
420
465
  );
421
466
  const plans = primaries.map((p, i) => ({
422
467
  suite: p.suite,
423
468
  tasks: planTasks[i] ?? [],
424
- doc: primaryDocs[i],
469
+ doc: primaryDocs[i]?.doc,
470
+ whole: primaryDocs[i]?.whole ?? false,
425
471
  }));
426
472
 
427
473
  // Phase 2: each isolated task in its own subprocess, so its JIT state
@@ -507,7 +553,7 @@ export async function bench(opts: BenchOptions): Promise<ProfileDocument> {
507
553
  // no measurement.
508
554
  const workloads: Workload[] = [];
509
555
  const measurements: Measurement[] = [];
510
- for (const { suite, tasks, doc: sharedDoc } of plans) {
556
+ for (const { suite, tasks, doc: sharedDoc, whole } of plans) {
511
557
  // A cancelled suite wrote nothing and is absent, not empty.
512
558
  if (!sharedDoc) continue;
513
559
  const sharedByWorkload = Map.groupBy(
@@ -522,6 +568,8 @@ export async function bench(opts: BenchOptions): Promise<ProfileDocument> {
522
568
  const workload = task.isolate
523
569
  ? doc.workloads[0]
524
570
  : sharedWorkloads.next().value;
571
+ // A stopped suite's tasks end where it stopped.
572
+ if (workload === undefined && !whole && !task.isolate) continue;
525
573
  if (workload === undefined) {
526
574
  throw new Error(
527
575
  `bench: ${suite.given} wrote fewer workloads than its plan`,
@@ -538,12 +586,15 @@ export async function bench(opts: BenchOptions): Promise<ProfileDocument> {
538
586
  }
539
587
  }
540
588
 
589
+ // The tasks it never ran aren't in the document, so the warning
590
+ // counts what the started suites planned.
541
591
  stampRunWarnings(
542
592
  measurements,
543
593
  noiseWarning,
544
594
  opts.signal?.aborted
545
595
  ? "Run was cancelled before it finished; this document holds whatever suites/tasks had already completed."
546
596
  : undefined,
597
+ { tasks: plans.reduce((sum, plan) => sum + plan.tasks.length, 0) },
547
598
  );
548
599
  stampDrift(environment);
549
600
  return createDocument(workloads, measurements, environment);
@@ -86,6 +86,17 @@ export interface TaskProgress {
86
86
  label: string;
87
87
  }
88
88
 
89
+ // One file a task, from 0, since a runner killed mid-write must leave the
90
+ // tasks before it whole.
91
+ export const partPath = (outputPath: string, n: number): string =>
92
+ `${outputPath}.${n}.part`;
93
+
94
+ /** A task that finished, measured or skipped, and what it measured. */
95
+ export interface MeasuredTask {
96
+ workload: Workload;
97
+ measurements: Measurement[];
98
+ }
99
+
89
100
  // The caller has already selected `tasks` and handled isolation, so
90
101
  // neither happens here.
91
102
  export async function measureTasks(
@@ -93,6 +104,7 @@ export async function measureTasks(
93
104
  tasks: readonly RegisteredTask[],
94
105
  opts: MeasureTasksOpts,
95
106
  onTask?: (progress: TaskProgress) => void,
107
+ onMeasured?: (task: MeasuredTask) => void,
96
108
  ): Promise<ProfileDocument> {
97
109
  const willMeasure = tasks.some((t) => !t.skipped);
98
110
  const { environment, noiseWarning } = captureRunEnvironment(
@@ -107,8 +119,12 @@ export async function measureTasks(
107
119
  for (const [idx, t] of tasks.entries()) {
108
120
  const workload = taskWorkload(suiteFile, t, opts.markIsolated);
109
121
  workloads.push(workload);
122
+ const firstOwn = measurements.length;
110
123
 
111
- if (t.skipped) continue;
124
+ if (t.skipped) {
125
+ onMeasured?.({ workload, measurements: [] });
126
+ continue;
127
+ }
112
128
  started++;
113
129
  onTask?.({ task: started, tasks: measuredCount, label: taskIdOf(t) });
114
130
 
@@ -186,6 +202,7 @@ export async function measureTasks(
186
202
 
187
203
  if (t.opts?.after) await t.opts.after();
188
204
  await runGroupHooks(t, "after", leave);
205
+ onMeasured?.({ workload, measurements: measurements.slice(firstOwn) });
189
206
  }
190
207
 
191
208
  stampDrift(environment);
@@ -1,5 +1,7 @@
1
1
  #!/usr/bin/env bun
2
2
 
3
+ import { renameSync, writeFileSync } from "node:fs";
4
+
3
5
  import { errorMessage } from "../errors.ts";
4
6
  import { saveDocument } from "../ir/document.ts";
5
7
  import {
@@ -20,8 +22,10 @@ import {
20
22
  taskPeakMem,
21
23
  } from "./registry.ts";
22
24
  import {
25
+ type MeasuredTask,
23
26
  measureTasks,
24
27
  type MeasureTasksOpts,
28
+ partPath,
25
29
  taskWorkload,
26
30
  } from "./run-tasks.ts";
27
31
 
@@ -57,6 +61,22 @@ export interface RunnerOpts extends MeasureTasksOpts {
57
61
  preload?: string[];
58
62
  /** Send a `TaskProgress` message over IPC before each task. */
59
63
  progress?: boolean;
64
+ /**
65
+ * Write each task as it finishes to `partPath(outputPath, n)`, so a run
66
+ * stopped mid-suite keeps what finished. */
67
+ partial?: boolean;
68
+ }
69
+
70
+ // Written whole, then renamed, so a runner killed mid-write leaves no
71
+ // half a file; synchronously, since a task's measuring holds the event
72
+ // loop, and an IPC message waits behind it until the suite ends.
73
+ function partWriter(outputPath: string): (task: MeasuredTask) => void {
74
+ let n = 0;
75
+ return (task) => {
76
+ const path = partPath(outputPath, n++);
77
+ writeFileSync(`${path}.tmp`, JSON.stringify(task));
78
+ renameSync(`${path}.tmp`, path);
79
+ };
60
80
  }
61
81
 
62
82
  // The parent serializes a `RunnerOpts`; only that it's an object
@@ -161,6 +181,7 @@ async function main(): Promise<number> {
161
181
  toRun,
162
182
  opts,
163
183
  opts.progress ? (progress) => process.send?.(progress) : undefined,
184
+ opts.partial ? partWriter(outputPath) : undefined,
164
185
  );
165
186
  await saveDocument(doc, outputPath);
166
187
  return 0;
@@ -95,13 +95,18 @@ export function stampRunWarnings(
95
95
  measurements: Measurement[],
96
96
  noiseWarning: Warning | undefined,
97
97
  abortedMessage: string | undefined,
98
+ abortedData?: Record<string, unknown>,
98
99
  ): void {
99
100
  const first = measurements[0];
100
101
  const last = measurements[measurements.length - 1];
101
102
  if (!first || !last) return;
102
103
  if (noiseWarning) first.warnings.push(noiseWarning);
103
104
  if (abortedMessage) {
104
- last.warnings.push({ code: "aborted", message: abortedMessage });
105
+ last.warnings.push({
106
+ code: "aborted",
107
+ message: abortedMessage,
108
+ ...(abortedData && { data: abortedData }),
109
+ });
105
110
  }
106
111
  }
107
112
 
package/src/cli/agent.ts CHANGED
@@ -1,28 +1,8 @@
1
1
  import { processEnv } from "../config/env.ts";
2
-
3
- // The variables a coding agent sets, as svelte-typecheck and svelte-lint
4
- // read them, after `bun check`: `AGENT` and `CLAUDECODE`, `AI_AGENT`, the
5
- // shared name, and Codex's `CODEX_CI` and `CODEX_THREAD_ID`. Kept the same
6
- // so the three tools agree on what an agent is (metonym/ostia#53).
7
- const AGENT_ENV = [
8
- "AGENT",
9
- "AI_AGENT",
10
- "CLAUDECODE",
11
- "CODEX_CI",
12
- "CODEX_THREAD_ID",
13
- ] as const;
2
+ import { agentVariableOf } from "../terminal.ts";
14
3
 
15
4
  type Env = Readonly<Record<string, string | undefined>>;
16
5
 
17
- // The first agent variable set to anything but empty or `0`, which a
18
- // person sets to say "not an agent" without unsetting it.
19
- export function agentVariable(env: Env = processEnv()): string | undefined {
20
- return AGENT_ENV.find((name) => {
21
- const value = env[name];
22
- return value !== undefined && value !== "" && value !== "0";
23
- });
24
- }
25
-
26
6
  function asksForFormat(argv: readonly string[]): boolean {
27
7
  return argv.some(
28
8
  (arg) =>
@@ -45,7 +25,7 @@ export function withDefaultFormat(
45
25
  if (chosen !== undefined && chosen !== "") {
46
26
  return { argv: [...argv, "--format", chosen] };
47
27
  }
48
- const agent = agentVariable(env);
28
+ const agent = agentVariableOf(env);
49
29
  if (agent === undefined) return { argv: [...argv] };
50
30
  return {
51
31
  argv: [...argv, "--format", "concise"],
package/src/cli/flags.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { availableJobs } from "../bench/index.ts";
2
2
  import type { FormatName } from "../renderers/index.ts";
3
3
  import { splitCommand } from "../spawn/index.ts";
4
+ import { nearest } from "../terminal.ts";
4
5
 
5
6
  /**
6
7
  * Thrown for a malformed flag; the dispatcher prints it with a `--help`
@@ -218,6 +219,13 @@ interface ParseSpec<T> {
218
219
  rest?: (rest: string[], args: T) => void;
219
220
  }
220
221
 
222
+ // ` (did you mean --json?)`, or nothing when no known word is near, so a
223
+ // message reads the same either way.
224
+ export function didYouMean(given: string, known: readonly string[]): string {
225
+ const near = nearest(given, known);
226
+ return near === undefined ? "" : ` (did you mean ${near}?)`;
227
+ }
228
+
221
229
  // Throws only `CliUsageError`, so the dispatcher can print a `--help`
222
230
  // pointer for any parse failure. `--flag=value` equals `--flag value`.
223
231
  export function parseFlags<T extends object>(
@@ -237,7 +245,7 @@ export function parseFlags<T extends object>(
237
245
  if (!flagDef) {
238
246
  if (arg.startsWith("-") || !positional) {
239
247
  throw new CliUsageError(
240
- `Unknown flag "${arg}" for "ostia ${command}".`,
248
+ `Unknown flag "${arg}" for "ostia ${command}"${didYouMean(name, Object.keys(flags))}.`,
241
249
  );
242
250
  }
243
251
  positional(arg, args);
package/src/cli/help.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { processEnv } from "../config/env.ts";
2
2
  import {
3
3
  createPaint,
4
+ fitTerminal,
5
+ isAgent,
4
6
  MEASURE,
5
7
  type Paint,
6
8
  PLAIN,
@@ -8,7 +10,6 @@ import {
8
10
  wantsColor,
9
11
  } from "../terminal.ts";
10
12
  import { TOOL_VERSION } from "../version.ts";
11
- import { agentVariable } from "./agent.ts";
12
13
 
13
14
  // A status line, Usage, Commands, Options, Examples, then the agent
14
15
  // section, within 80 columns. Section heads are bold and defaults gray,
@@ -656,15 +657,26 @@ export async function paintFor(
656
657
  // invocation about 4 ms (median of 150 runs, before and after).
657
658
  const { isatty } = await import("node:tty");
658
659
  const env = processEnv();
659
- return wantsColor(forced, isatty(fd), env, agentVariable(env) !== undefined)
660
+ return wantsColor(forced, isatty(fd), env, isAgent(env))
660
661
  ? createPaint()
661
662
  : PLAIN;
662
663
  }
663
664
 
665
+ // Help asked for is the output, so it goes to stdout; help shown because
666
+ // an argument is missing goes to stderr, with the error's exit code.
664
667
  export async function showHelp(
665
668
  topic: HelpTopic,
666
669
  requested: boolean,
667
670
  ): Promise<0 | 2> {
668
- await Bun.write(Bun.stdout, helpText(topic, await paintFor(1)));
671
+ const { isatty } = await import("node:tty");
672
+ const fd = requested ? 1 : 2;
673
+ await Bun.write(
674
+ requested ? Bun.stdout : Bun.stderr,
675
+ fitTerminal(
676
+ helpText(topic, await paintFor(fd)),
677
+ isatty(fd),
678
+ (requested ? process.stdout : process.stderr).columns,
679
+ ),
680
+ );
669
681
  return requested ? 0 : 2;
670
682
  }
package/src/cli/output.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { processEnv } from "../config/env.ts";
1
2
  import { errorMessage, OstiaUsageError } from "../errors.ts";
2
3
  import {
3
4
  saveDocument,
@@ -46,14 +47,19 @@ export class CliError extends Error {
46
47
  readonly code: CliErrorCode;
47
48
  // Structured detail for the `error` event's `data`.
48
49
  readonly data?: Record<string, unknown> | undefined;
50
+ // Thrown after the command printed its report, so `--json`'s stdout
51
+ // has its one document already.
52
+ readonly reported: boolean;
49
53
  constructor(
50
54
  code: CliErrorCode,
51
55
  message: string,
52
56
  data?: Record<string, unknown>,
57
+ options: { reported?: boolean } = {},
53
58
  ) {
54
59
  super(message);
55
60
  this.code = code;
56
61
  this.data = data;
62
+ this.reported = options.reported ?? false;
57
63
  }
58
64
  }
59
65
 
@@ -76,42 +82,74 @@ export async function orFail<T>(
76
82
  // `minimal` too, since this reads argv before the alias resolves.
77
83
  const MACHINE_FORMATS = new Set(["events", "minimal", "json", "jsonl"]);
78
84
 
85
+ // ostia's own arguments: those before `--`, since what follows is a
86
+ // command's own argv.
87
+ function ownArgs(): string[] {
88
+ const argv = process.argv.slice(2);
89
+ const end = argv.indexOf("--");
90
+ return end === -1 ? argv : argv.slice(0, end);
91
+ }
92
+
93
+ // Read from argv, since an error can come before the flags are parsed;
94
+ // the last flag wins, as in parseFlags, and `OSTIA_FORMAT` when argv
95
+ // names none, as `withDefaultFormat` adds it.
96
+ function askedFormat(): string | undefined {
97
+ const own = ownArgs();
98
+ let asked = false;
99
+ let format: string | undefined;
100
+ for (const [i, arg] of own.entries()) {
101
+ if (arg === "--json" || arg === "--json=true") format = "json";
102
+ else if (arg === "--format") format = own[i + 1];
103
+ else if (arg.startsWith("--format=")) {
104
+ format = arg.slice("--format=".length);
105
+ } else if (!arg.startsWith("--json=")) continue;
106
+ asked = true;
107
+ }
108
+ return asked ? format : processEnv().OSTIA_FORMAT;
109
+ }
110
+
79
111
  // Machine errors are for scripts and agents: stderr isn't a terminal, or a
80
112
  // machine `--format` was asked for.
81
113
  async function wantsMachineErrors(): Promise<boolean> {
82
114
  // perf: imported lazily, since loading node:tty up front costs every
83
115
  // invocation ~15ms.
84
116
  const { isatty } = await import("node:tty");
85
- if (!isatty(2)) return true;
86
- const argv = process.argv.slice(2);
87
- return argv.some(
88
- (arg, i) =>
89
- arg === "--json" ||
90
- arg === "--json=true" ||
91
- (arg === "--format" && MACHINE_FORMATS.has(argv[i + 1] ?? "")) ||
92
- (arg.startsWith("--format=") &&
93
- MACHINE_FORMATS.has(arg.slice("--format=".length))),
94
- );
117
+ return !isatty(2) || MACHINE_FORMATS.has(askedFormat() ?? "");
95
118
  }
96
119
 
97
120
  // Writes `message` to stderr, then for a machine reader one JSON `error`
98
- // line (first line of `message` only). Never touches stdout.
121
+ // line (first line of `message` only). With `--json`, stdout gets the
122
+ // error as its one document too, unless the report is there already
123
+ // (`reported`), so a program that parses stdout learns why instead of
124
+ // failing to parse.
99
125
  export async function writeCliError(
100
126
  code: CliErrorCode,
101
127
  message: string,
102
128
  data?: Record<string, unknown>,
129
+ options: { reported?: boolean } = {},
103
130
  ): Promise<void> {
104
131
  await errOut(message.endsWith("\n") ? message : `${message}\n`);
105
132
  if (!(await wantsMachineErrors())) return;
133
+ const first = message.split("\n")[0] ?? "";
106
134
  await errOut(
107
135
  `${JSON.stringify({
108
136
  event: "error",
109
137
  protocolVersion: MINIMAL_PROTOCOL_VERSION,
110
138
  code,
111
- message: message.split("\n")[0],
139
+ message: first,
112
140
  ...(data && { data }),
113
141
  })}\n`,
114
142
  );
143
+ const quiet = ownArgs().includes("--quiet");
144
+ if (askedFormat() !== "json" || options.reported === true || quiet) return;
145
+ const schemaVersion: ProfileDocument["schemaVersion"] = 2;
146
+ await out(
147
+ `${JSON.stringify({
148
+ schemaVersion,
149
+ ok: false,
150
+ error: { kind: code, message: first, ...(data && { data }) },
151
+ })}\n`,
152
+ );
115
153
  }
116
154
 
117
155
  export async function writeRenderResult(