perf(cli): write compact JSON when output is not a terminal (#1413)
`--json` / `--format json` always indented its streamed result. Agents and scripts read REA through pipes and redirects, where indentation carries no information: on real application results it added 16-45% model tokens (o200k proxy) and 25-73% bytes. The skill's CLI fallback uses `--json`. Indent only when stdout is a TTY, as `gh --json` does; piped or redirected JSON is compact. The JSON value, `jsonl`, `--filter-output`, `--full-output` and the token-window paths are unchanged. `jq .` restores indentation for files. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
de8fc67195
commit
ca3131b36c
+15
-3
@@ -4,16 +4,27 @@ import { bufferedJsonParts, jsonParts } from "../domain/jsonSerialization.js";
|
||||
|
||||
type JsonOutputFormat = "json" | "jsonl";
|
||||
|
||||
/** Write ordinary JSON without constructing a document-sized string. */
|
||||
/**
|
||||
* Write ordinary JSON without constructing a document-sized string.
|
||||
*
|
||||
* `json` is indented for a terminal reader. Piped or redirected output, which
|
||||
* agents and scripts consume, is compact: indentation adds no information and
|
||||
* measured 16-45% more model tokens on real results. The value is identical.
|
||||
*/
|
||||
export const writeJsonOutput = async (
|
||||
value: unknown,
|
||||
destination: Writable,
|
||||
format: JsonOutputFormat = "json",
|
||||
): Promise<void> => {
|
||||
for (const part of bufferedJsonParts(jsonOutputParts(value, format)))
|
||||
for (const part of bufferedJsonParts(
|
||||
jsonOutputParts(value, format, isTerminal(destination)),
|
||||
))
|
||||
await writePart(destination, part);
|
||||
};
|
||||
|
||||
const isTerminal = (destination: Writable): boolean =>
|
||||
"isTTY" in destination && destination.isTTY === true;
|
||||
|
||||
const writePart = (destination: Writable, part: string): Promise<void> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const onError = (cause: unknown): void => reject(cause);
|
||||
@@ -39,6 +50,7 @@ const writePart = (destination: Writable, part: string): Promise<void> =>
|
||||
export function* jsonOutputParts(
|
||||
value: unknown,
|
||||
format: JsonOutputFormat,
|
||||
pretty = true,
|
||||
): Generator<string> {
|
||||
if (format === "jsonl" && Array.isArray(value)) {
|
||||
for (const item of value) {
|
||||
@@ -47,6 +59,6 @@ export function* jsonOutputParts(
|
||||
}
|
||||
return;
|
||||
}
|
||||
yield* jsonParts(value, format === "json");
|
||||
yield* jsonParts(value, pretty && format === "json");
|
||||
yield "\n";
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user