fix(cli): stream JSON results at the shared command boundary

Route ordinary CLI results through the bounded JSON writer after command registration, including managed member inspection. Remove JavaScript-specific output plumbing while preserving filters, envelopes, cancellation, and failure exits.

Measure formatted UTF-16 expansion before Incur token counting and return resource_constraint above the runtime string limit, with recovery guidance.

Validate output above the real V8 string limit by SHA-256 and exercise the compiled managed provider. Clean-worktree validation: npm run check; 76 focused tests passed, with 2 optional-provider skips; test discovery passed.

Fixes #1371.
This commit is contained in:
morluto
2026-10-10 06:23:26 +08:00
parent ecc67cab2d
commit 810107a2ad
9 changed files with 314 additions and 65 deletions
+7 -8
View File
@@ -31,7 +31,10 @@ import { registerJavaScriptRuntimeObservationCommands } from "./cliJavaScriptRun
import { registerApplicationCommands } from "./cli/applicationCommands.js";
import { presentOmittableDefaults } from "./cli/omittableDefaults.js";
import type { CliInstance } from "./cli/types.js";
import type { CliResultOutput } from "./cli/streamedJsonOutput.js";
import {
streamCliCommandResults,
type CliResultOutput,
} from "./cli/streamedJsonOutput.js";
/**
* Build the one-shot Incur CLI without starting Hopper at import time.
@@ -64,12 +67,7 @@ export const createCli = (
});
registerSetupCommands(cli, logger, environment);
registerCoreAnalysisCommands(
cli,
logger,
analysis.runDirectAnalysis,
resultOutput,
);
registerCoreAnalysisCommands(cli, logger, analysis.runDirectAnalysis);
registerUtilityCommands(cli, logger, environment, analysis);
registerEvmCommands(cli, logger, environment);
registerArtifactCommands(cli, logger, analysis.runProviderAnalysis);
@@ -89,9 +87,10 @@ export const createCli = (
registerJavaScriptRecoveryCommands(cli, logger, environment);
registerAdvancedBrowserCommands(cli, logger);
registerBrowserScenarioCommands(cli, logger, environment);
registerElectronCommands(cli, logger, environment, resultOutput);
registerElectronCommands(cli, logger, environment);
registerJavaScriptRuntimeObservationCommands(cli, logger);
registerApplicationCommands(cli, logger);
presentOmittableDefaults(cli);
if (resultOutput !== undefined) streamCliCommandResults(cli, resultOutput);
return cli;
};
+1 -3
View File
@@ -3,15 +3,13 @@ import type { Logger } from "pino";
import { registerCoreBinaryCommands } from "./coreBinaryCommands.js";
import { registerCoreNativeCommands } from "./coreNativeCommands.js";
import type { CliInstance } from "./types.js";
import type { CliResultOutput } from "./streamedJsonOutput.js";
/** Register core binary and native deep-analysis CLI commands. */
export const registerCoreAnalysisCommands = (
cli: CliInstance,
logger: Logger,
runDirectAnalysis: DirectAnalysis["runDirectAnalysis"],
resultOutput?: CliResultOutput,
): void => {
registerCoreBinaryCommands(cli, logger, runDirectAnalysis, resultOutput);
registerCoreBinaryCommands(cli, logger, runDirectAnalysis);
registerCoreNativeCommands(cli, logger, runDirectAnalysis);
};
+2 -10
View File
@@ -15,7 +15,6 @@ import {
import type { CliInstance } from "./types.js";
import { runCliJavaScriptApplicationAnalysis } from "./javascriptApplicationAnalysis.js";
import { withCommandCancellation } from "./commandCancellation.js";
import type { CliResultOutput } from "./streamedJsonOutput.js";
import { javascriptApplicationOptions } from "../cliObservationOptions.js";
/** Register provider-neutral binary overview and procedure CLI commands. */
@@ -23,9 +22,8 @@ export const registerCoreBinaryCommands = (
cli: CliInstance,
logger: Logger,
runDirectAnalysis: DirectAnalysis["runDirectAnalysis"],
resultOutput?: CliResultOutput,
): void => {
registerOverviewCommands(cli, logger, runDirectAnalysis, resultOutput);
registerOverviewCommands(cli, logger, runDirectAnalysis);
registerDecompileCommand(cli, logger, runDirectAnalysis);
registerFunctionCommand(cli, logger, runDirectAnalysis);
registerInstructionsCommand(cli, logger, runDirectAnalysis);
@@ -38,7 +36,6 @@ const registerOverviewCommands = (
cli: CliInstance,
logger: Logger,
runDirectAnalysis: DirectAnalysis["runDirectAnalysis"],
resultOutput?: CliResultOutput,
): void => {
const overviewOptions = z.object({
snapshot: z
@@ -58,11 +55,7 @@ const registerOverviewCommands = (
integrityPolicy: javascriptApplicationOptions.shape.integrityPolicy,
}),
alias: { integrityPolicy: "integrity-policy" },
run: async ({ args, options, format }) => {
const output =
resultOutput === undefined
? undefined
: { output: resultOutput, command: CLI_COMMANDS.analyze, format };
run: async ({ args, options }) => {
// Route JavaScript targets exactly like analyze-javascript-application,
// including typed cancellation; cancellation wraps logging so its exit
// code is not replaced by the logged failure status.
@@ -74,7 +67,6 @@ const registerOverviewCommands = (
input_path: resolve(args.path),
integrity_policy: options.integrityPolicy,
},
output,
signal,
),
),
+2 -12
View File
@@ -24,7 +24,6 @@ import {
javascriptApplicationOptions,
} from "../cliObservationOptions.js";
import { runCliJavaScriptApplicationAnalysis } from "./javascriptApplicationAnalysis.js";
import type { CliResultOutput } from "./streamedJsonOutput.js";
import { withCommandCancellation } from "./commandCancellation.js";
/** Register CLI equivalents of the Electron MCP tools. */
@@ -32,11 +31,10 @@ export const registerElectronCommands = (
cli: ReturnType<typeof Cli.create>,
logger: Logger,
environment: Readonly<Record<string, string | undefined>>,
resultOutput?: CliResultOutput,
): void => {
registerElectronObservationCommands(cli, logger);
registerElectronActiveCommand(cli, logger, environment);
registerJavaScriptApplicationCommand(cli, logger, resultOutput);
registerJavaScriptApplicationCommand(cli, logger);
registerJavaScriptRuntimeReconciliationCommand(cli, logger);
};
@@ -184,7 +182,6 @@ const registerElectronPageInspection = (
const registerJavaScriptApplicationCommand = (
cli: ReturnType<typeof Cli.create>,
logger: Logger,
resultOutput?: CliResultOutput,
): void => {
cli.command(CLI_COMMANDS.analyzeJavaScriptApplication, {
description:
@@ -194,7 +191,7 @@ const registerJavaScriptApplicationCommand = (
}),
options: javascriptApplicationOptions,
alias: { integrityPolicy: "integrity-policy" },
run: ({ args, options, format }) =>
run: ({ args, options }) =>
withCommandCancellation((signal) =>
logCliCommand(logger, CLI_COMMANDS.analyzeJavaScriptApplication, () =>
runCliJavaScriptApplicationAnalysis(
@@ -203,13 +200,6 @@ const registerJavaScriptApplicationCommand = (
format: options.artifactFormat,
integrity_policy: options.integrityPolicy,
},
resultOutput === undefined
? undefined
: {
output: resultOutput,
command: CLI_COMMANDS.analyzeJavaScriptApplication,
format,
},
signal,
),
),
+2 -16
View File
@@ -2,15 +2,12 @@ import { analyzeJavaScriptApplication } from "../application/javascript/JavaScri
import { createProgressReporter } from "../application/ProgressReporter.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { CliCommandOutput } from "./streamedJsonOutput.js";
/** Execute the shared one-shot CLI boundary for static JavaScript analysis. */
export const runCliJavaScriptApplicationAnalysis = async (
input: unknown,
output?: CliCommandOutput,
signal?: AbortSignal,
): Promise<JsonValue | undefined> => {
const started = performance.now();
): Promise<JsonValue> => {
const progress = createProgressReporter(
async (update) => {
process.stderr.write(`${JSON.stringify({ rea_progress: update })}\n`);
@@ -21,18 +18,7 @@ export const runCliJavaScriptApplicationAnalysis = async (
progress,
...(signal === undefined ? {} : { signal }),
});
const value = result.ok ? result.value : cliError(result.error);
if (
output !== undefined &&
(await output.output.write(value, {
command: output.command,
format: output.format,
duration: `${Math.round(performance.now() - started)}ms`,
}))
)
// Keep failures visible to command logging after the stream has handled stdout.
return result.ok ? undefined : value;
return value;
return result.ok ? result.value : cliError(result.error);
};
const cliError = (
+3 -2
View File
@@ -10,7 +10,7 @@ export const writeJsonOutput = async (
destination: Writable,
format: JsonOutputFormat = "json",
): Promise<void> => {
for (const part of bufferedJsonParts(documentParts(value, format)))
for (const part of bufferedJsonParts(jsonOutputParts(value, format)))
await writePart(destination, part);
};
@@ -35,7 +35,8 @@ const writePart = (destination: Writable, part: string): Promise<void> =>
}
});
function* documentParts(
/** The exact formatted document, including its final newline. */
export function* jsonOutputParts(
value: unknown,
format: JsonOutputFormat,
): Generator<string> {
+126 -12
View File
@@ -1,10 +1,16 @@
import { constants } from "node:buffer";
import { type Writable } from "node:stream";
import { Filter } from "incur";
import { Cli, Filter } from "incur";
import { parseCliOutputArguments } from "../cliOutput.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { writeJsonOutput } from "./jsonOutput.js";
import { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js";
import {
projectAnalysisError,
type AnalysisErrorProjection,
} from "../domain/analysisErrorProjection.js";
import { jsonOutputParts, writeJsonOutput } from "./jsonOutput.js";
import type { CliInstance } from "./types.js";
/** Result metadata supplied by the command that actually ran. */
export interface CliResultOutputMetadata {
@@ -17,15 +23,82 @@ export interface CliResultOutputMetadata {
export interface CliResultOutput {
readonly handled: boolean;
readonly failed: boolean;
write(value: JsonValue, metadata: CliResultOutputMetadata): Promise<boolean>;
readonly error: AnalysisErrorProjection | undefined;
write(value: unknown, metadata: CliResultOutputMetadata): Promise<boolean>;
}
/** Selected command output context, independent of application workflows. */
export interface CliCommandOutput {
readonly output: CliResultOutput;
readonly command: string;
readonly format: string;
}
type CommandMap = NonNullable<ReturnType<typeof Cli.toCommands.get>>;
type CommandDefinition = Extract<
CommandMap extends Map<string, infer Entry> ? Entry : never,
{ run: unknown }
>;
const registeredCommands: WeakMap<object, CommandMap> = Cli.toCommands;
/** Install formatting once, after registration, for every ordinary CLI result. */
export const streamCliCommandResults = (
cli: CliInstance,
output: CliResultOutput,
): void => {
const commands = registeredCommands.get(cli);
if (commands !== undefined) wrapCommands(commands, [], output);
};
const wrapCommands = (
commands: CommandMap,
parents: readonly string[],
output: CliResultOutput,
): void => {
for (const [name, entry] of commands) {
const path = [...parents, name];
if ("_group" in entry) {
wrapCommands(entry.commands, path, output);
if (entry.root !== undefined)
wrapCommand(entry.root, path.join(" "), output);
} else if (!("_alias" in entry) && !("_fetch" in entry))
wrapCommand(entry, path.join(" "), output);
}
};
const wrapCommand = (
command: Pick<CommandDefinition, "run">,
name: string,
output: CliResultOutput,
): void => {
const run = command.run;
command.run = (context) => {
const started = performance.now();
const result: unknown = run(context);
// Generator results and Incur's sentinel responses retain their own protocol.
if (
typeof result === "object" &&
result !== null &&
Symbol.asyncIterator in result
)
return result;
return Promise.resolve(result).then(async (value: unknown) => {
if (
typeof value === "object" &&
value !== null &&
Symbol.for("incur.sentinel") in value
)
return value;
if (
!(await output.write(value, {
command: name,
format: context.format,
duration: `${Math.round(performance.now() - started)}ms`,
}))
)
return value;
if (output.error !== undefined)
return context.error({
code: output.error.code,
message: output.error.message,
});
return undefined;
});
};
};
/** Preserve Incur's JSON controls while streaming the complete result. */
export const createStreamedCliJsonOutput = (
@@ -35,7 +108,6 @@ export const createStreamedCliJsonOutput = (
const options = parseCliOutputArguments(arguments_);
if (
options.parseError ||
options.tokenCount ||
options.tokenWindow ||
(options.format !== "json" && options.format !== "jsonl")
)
@@ -43,6 +115,7 @@ export const createStreamedCliJsonOutput = (
const format = options.format;
let handled = false;
let failed = false;
let error: AnalysisErrorProjection | undefined;
return {
get handled() {
return handled;
@@ -50,6 +123,9 @@ export const createStreamedCliJsonOutput = (
get failed() {
return failed;
},
get error() {
return error;
},
async write(value, metadata) {
if (metadata.format !== format) return false;
const filtered: unknown = options.filterOutput
@@ -59,6 +135,36 @@ export const createStreamedCliJsonOutput = (
command: metadata.command,
duration: metadata.duration,
};
if (options.tokenCount) {
// Incur/tokenx materialize the formatted value. Measure its UTF-16
// expansion before allowing that allocation, independently of UTF-8 bytes.
let characters = 0;
if (
filtered !== undefined &&
filtered !== null &&
typeof filtered !== "function" &&
typeof filtered !== "symbol"
)
for (const part of jsonOutputParts(filtered, format))
characters += part.length;
characters = Math.max(0, characters - 1);
if (characters <= constants.MAX_STRING_LENGTH) return false;
error = projectAnalysisError(
new AnalysisResourceConstraintError(
metadata.command,
"memory",
"Token counting requires a formatted string larger than the runtime permits.",
{
formatted_characters: characters,
max_string_characters: constants.MAX_STRING_LENGTH,
},
{
remediationAction:
"Remove --token-count to stream the complete JSON result, or narrow it with --filter-output.",
},
),
);
}
const document = options.fullOutput
? filtered === undefined
? { ok: true, meta }
@@ -73,7 +179,15 @@ export const createStreamedCliJsonOutput = (
// document from Incur's error formatter.
handled = true;
try {
await writeJsonOutput(document, destination, format);
await writeJsonOutput(
error === undefined
? document
: options.fullOutput
? { ok: false, error, meta }
: error,
destination,
format,
);
} catch (cause: unknown) {
failed = true;
throw cause;