fix(cli): preserve failure semantics across full-output formats
This commit is contained in:
+1
-1
@@ -44,7 +44,7 @@ import type { CliInstance } from "./cli/types.js";
|
||||
import {
|
||||
streamCliCommandResults,
|
||||
type CliResultOutput,
|
||||
} from "./cli/streamedJsonOutput.js";
|
||||
} from "./cli/cliResultOutput.js";
|
||||
|
||||
/** Describe CLI settings that are invalid before any command runs, as MCP does. */
|
||||
export const cliConfigurationError = (
|
||||
|
||||
@@ -1,15 +1,24 @@
|
||||
import { constants } from "node:buffer";
|
||||
import type { Writable } from "node:stream";
|
||||
|
||||
import { Cli, Filter } from "incur";
|
||||
import { Cli, Filter, Formatter } from "incur";
|
||||
import { estimateTokenCount, sliceByTokens } from "tokenx";
|
||||
|
||||
import { parseCliOutputArguments } from "../cliOutput.js";
|
||||
import {
|
||||
parseCliOutputArguments,
|
||||
validateCliOutputArguments,
|
||||
} from "../cliOutput.js";
|
||||
import { cliOperationFailurePayload } from "../cliLogging.js";
|
||||
import { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js";
|
||||
import {
|
||||
projectAnalysisError,
|
||||
type AnalysisErrorProjection,
|
||||
} from "../domain/analysisErrorProjection.js";
|
||||
import { jsonOutputParts, writeJsonOutput } from "./jsonOutput.js";
|
||||
import {
|
||||
jsonOutputParts,
|
||||
writeJsonOutput,
|
||||
writeOutputText,
|
||||
} from "./jsonOutput.js";
|
||||
import type { CliInstance } from "./types.js";
|
||||
|
||||
/** Result metadata supplied by the command that actually ran. */
|
||||
@@ -100,19 +109,15 @@ const wrapCommand = (
|
||||
};
|
||||
};
|
||||
|
||||
/** Preserve Incur's JSON controls while streaming the complete result. */
|
||||
export const createStreamedCliJsonOutput = (
|
||||
/** Preserve Incur output controls and stream JSON while framing failures. */
|
||||
export const createCliResultOutput = (
|
||||
arguments_: readonly string[],
|
||||
destination: Writable,
|
||||
): CliResultOutput | undefined => {
|
||||
const options = parseCliOutputArguments(arguments_);
|
||||
if (
|
||||
options.parseError ||
|
||||
options.tokenWindow ||
|
||||
(options.format !== "json" && options.format !== "jsonl")
|
||||
)
|
||||
if (options.parseError || !validateCliOutputArguments(arguments_).ok)
|
||||
return undefined;
|
||||
const format = options.format;
|
||||
const format = options.format as "json" | "jsonl" | "yaml" | "toon" | "md";
|
||||
let handled = false;
|
||||
let failed = false;
|
||||
let error: AnalysisErrorProjection | undefined;
|
||||
@@ -128,27 +133,53 @@ export const createStreamedCliJsonOutput = (
|
||||
},
|
||||
async write(value, metadata) {
|
||||
if (metadata.format !== format) return false;
|
||||
const failure = options.fullOutput
|
||||
? cliOperationFailurePayload(value)
|
||||
: undefined;
|
||||
const filtered: unknown = options.filterOutput
|
||||
? Filter.apply(value, Filter.parse(options.filterOutput))
|
||||
: value;
|
||||
const meta = {
|
||||
command: metadata.command,
|
||||
duration: metadata.duration,
|
||||
};
|
||||
// Leave successful YAML and bare YAML rendering to Incur. The custom
|
||||
// boundary is needed only for a full failure envelope, whose error
|
||||
// sentinel otherwise drops category, remediation, and details.
|
||||
if (format !== "json" && format !== "jsonl" && failure === undefined)
|
||||
return false;
|
||||
if (options.tokenCount) {
|
||||
// Incur/tokenx materialize the formatted value. Measure its UTF-16
|
||||
// expansion before allowing that allocation, independently of UTF-8 bytes.
|
||||
// Incur/tokenx materialize JSON. Measure its UTF-16 expansion before
|
||||
// allowing that allocation, independently of UTF-8 bytes. Other formats
|
||||
// retain Incur's materializing behavior.
|
||||
const tokenValue = failure ?? filtered;
|
||||
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;
|
||||
tokenValue !== undefined &&
|
||||
tokenValue !== null &&
|
||||
typeof tokenValue !== "function" &&
|
||||
typeof tokenValue !== "symbol"
|
||||
) {
|
||||
if (format === "json" || format === "jsonl") {
|
||||
for (const part of jsonOutputParts(
|
||||
tokenValue,
|
||||
format,
|
||||
format === "json",
|
||||
))
|
||||
characters += part.length;
|
||||
characters = Math.max(0, characters - 1);
|
||||
}
|
||||
}
|
||||
if (characters <= constants.MAX_STRING_LENGTH) {
|
||||
if (failure === undefined) return false;
|
||||
handled = true;
|
||||
try {
|
||||
await writeOutputText(
|
||||
destination,
|
||||
`${estimateTokenCount(Formatter.format(failure, format))}\n`,
|
||||
);
|
||||
return true;
|
||||
} catch (cause: unknown) {
|
||||
failed = true;
|
||||
throw cause;
|
||||
}
|
||||
}
|
||||
error = projectAnalysisError(
|
||||
new AnalysisResourceConstraintError(
|
||||
metadata.command,
|
||||
@@ -165,10 +196,26 @@ export const createStreamedCliJsonOutput = (
|
||||
),
|
||||
);
|
||||
}
|
||||
const meta = {
|
||||
command: metadata.command,
|
||||
duration: metadata.duration,
|
||||
};
|
||||
const errorDocument =
|
||||
options.fullOutput && failure !== undefined
|
||||
? fullFailureEnvelope(
|
||||
failure,
|
||||
meta,
|
||||
format,
|
||||
options.tokenLimit,
|
||||
options.tokenOffset,
|
||||
)
|
||||
: undefined;
|
||||
const document = options.fullOutput
|
||||
? filtered === undefined
|
||||
? { ok: true, meta }
|
||||
: { ok: true, data: filtered, meta }
|
||||
? failure !== undefined
|
||||
? errorDocument
|
||||
: filtered === undefined
|
||||
? { ok: true, meta }
|
||||
: { ok: true, data: filtered, meta }
|
||||
: filtered === undefined ||
|
||||
filtered === null ||
|
||||
typeof filtered === "function" ||
|
||||
@@ -179,15 +226,24 @@ export const createStreamedCliJsonOutput = (
|
||||
// document from Incur's error formatter.
|
||||
handled = true;
|
||||
try {
|
||||
await writeJsonOutput(
|
||||
error === undefined
|
||||
? document
|
||||
: options.fullOutput
|
||||
? { ok: false, error, meta }
|
||||
: error,
|
||||
destination,
|
||||
format,
|
||||
);
|
||||
if (failure !== undefined && format !== "json" && format !== "jsonl") {
|
||||
// Incur's error sentinel only carries code/message/retryable. Render
|
||||
// the full caller-visible failure at this output boundary.
|
||||
await writeOutputText(
|
||||
destination,
|
||||
`${Formatter.format(document, format)}\n`,
|
||||
);
|
||||
} else {
|
||||
await writeJsonOutput(
|
||||
error === undefined
|
||||
? document
|
||||
: options.fullOutput
|
||||
? { ok: false, error, meta }
|
||||
: error,
|
||||
destination,
|
||||
format as "json" | "jsonl",
|
||||
);
|
||||
}
|
||||
} catch (cause: unknown) {
|
||||
failed = true;
|
||||
throw cause;
|
||||
@@ -196,3 +252,26 @@ export const createStreamedCliJsonOutput = (
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const fullFailureEnvelope = (
|
||||
failure: unknown,
|
||||
meta: Readonly<Record<string, unknown>>,
|
||||
format: "json" | "jsonl" | "yaml" | "toon" | "md",
|
||||
tokenLimit: number | undefined,
|
||||
tokenOffset: number | undefined,
|
||||
): Readonly<Record<string, unknown>> => {
|
||||
if (tokenLimit === undefined && tokenOffset === undefined)
|
||||
return { ok: false, error: failure, meta };
|
||||
const formatted = Formatter.format(failure, format);
|
||||
const total = estimateTokenCount(formatted);
|
||||
const offset = tokenOffset ?? 0;
|
||||
const end = tokenLimit === undefined ? total : offset + tokenLimit;
|
||||
if (offset === 0 && end >= total) return { ok: false, error: failure, meta };
|
||||
const actualEnd = Math.min(end, total);
|
||||
const nextOffset = actualEnd < total ? actualEnd : undefined;
|
||||
return {
|
||||
ok: false,
|
||||
error: `${sliceByTokens(formatted, offset, end)}\n[truncated: showing tokens ${offset}–${actualEnd} of ${total}]`,
|
||||
meta: { ...meta, ...(nextOffset === undefined ? {} : { nextOffset }) },
|
||||
};
|
||||
};
|
||||
@@ -19,13 +19,16 @@ export const writeJsonOutput = async (
|
||||
for (const part of bufferedJsonParts(
|
||||
jsonOutputParts(value, format, isTerminal(destination)),
|
||||
))
|
||||
await writePart(destination, part);
|
||||
await writeOutputText(destination, part);
|
||||
};
|
||||
|
||||
const isTerminal = (destination: Writable): boolean =>
|
||||
"isTTY" in destination && destination.isTTY === true;
|
||||
|
||||
const writePart = (destination: Writable, part: string): Promise<void> =>
|
||||
export const writeOutputText = (
|
||||
destination: Writable,
|
||||
part: string,
|
||||
): Promise<void> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const onError = (cause: unknown): void => reject(cause);
|
||||
destination.once("error", onError);
|
||||
|
||||
+63
-13
@@ -12,20 +12,64 @@ import type { Logger } from "pino";
|
||||
const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
/** Identify caller-visible CLI outcomes that mean the requested operation failed. */
|
||||
export const isCliOperationFailure = (value: unknown): boolean => {
|
||||
if (!isRecord(value)) return false;
|
||||
if (
|
||||
isRecord(value.error) &&
|
||||
analysisErrorProjectionSchema.safeParse(value.error).success
|
||||
)
|
||||
return true;
|
||||
if (analysisCliErrorEnvelopeSchema.safeParse(value).success) return true;
|
||||
if (analysisErrorProjectionSchema.safeParse(value).success) return true;
|
||||
if (value.healthy === false) return true;
|
||||
return false;
|
||||
const loggedFailures = new WeakMap<object, unknown>();
|
||||
|
||||
/** Return the canonical failure projection owned by the CLI result boundary. */
|
||||
const projectCliOperationFailure = (
|
||||
value: unknown,
|
||||
): AnalysisErrorProjection | undefined => {
|
||||
if (!isRecord(value)) return undefined;
|
||||
const direct = analysisErrorProjectionSchema.safeParse(value);
|
||||
if (direct.success) return value as AnalysisErrorProjection;
|
||||
const envelope = analysisCliErrorEnvelopeSchema.safeParse(value);
|
||||
if (envelope.success) {
|
||||
const {
|
||||
error: _label,
|
||||
input_path: inputPath,
|
||||
input_reason: inputReason,
|
||||
...projection
|
||||
} = value;
|
||||
const parsed = projection as AnalysisErrorProjection;
|
||||
if (typeof inputPath !== "string" && typeof inputReason !== "string")
|
||||
return parsed;
|
||||
return {
|
||||
...parsed,
|
||||
details: {
|
||||
...parsed.details,
|
||||
...(typeof inputPath === "string" ? { input_path: inputPath } : {}),
|
||||
...(typeof inputReason === "string"
|
||||
? { input_reason: inputReason }
|
||||
: {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
if (isRecord(value.error)) {
|
||||
const nested = analysisErrorProjectionSchema.safeParse(value.error);
|
||||
if (nested.success) return value.error as AnalysisErrorProjection;
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
/** Return the canonical projection or original record classified as failed. */
|
||||
const inferCliOperationFailure = (value: unknown): unknown | undefined => {
|
||||
const projection = projectCliOperationFailure(value);
|
||||
if (projection !== undefined) return projection;
|
||||
if (isRecord(value) && value.healthy === false) return value;
|
||||
return undefined;
|
||||
};
|
||||
|
||||
export const cliOperationFailurePayload = (
|
||||
value: unknown,
|
||||
): unknown | undefined => {
|
||||
if (isRecord(value) && loggedFailures.has(value))
|
||||
return loggedFailures.get(value);
|
||||
return inferCliOperationFailure(value);
|
||||
};
|
||||
|
||||
/** Identify caller-visible CLI outcomes that mean the requested operation failed. */
|
||||
export const isCliOperationFailure = (value: unknown): boolean =>
|
||||
cliOperationFailurePayload(value) !== undefined;
|
||||
|
||||
/** Log one CLI command with duration and a stable success or failure status. */
|
||||
export const logCliCommand = async <Value>(
|
||||
logger: Logger,
|
||||
@@ -36,7 +80,13 @@ export const logCliCommand = async <Value>(
|
||||
const startedAt = performance.now();
|
||||
try {
|
||||
const value = await execute();
|
||||
const failed = isCommandFailure?.(value) ?? isCliOperationFailure(value);
|
||||
const inferredFailure = inferCliOperationFailure(value);
|
||||
const failed = isCommandFailure?.(value) ?? inferredFailure !== undefined;
|
||||
if (isRecord(value))
|
||||
loggedFailures.set(
|
||||
value,
|
||||
failed ? (inferredFailure ?? value) : undefined,
|
||||
);
|
||||
logger[failed ? "error" : "info"](
|
||||
{
|
||||
command,
|
||||
|
||||
+10
-3
@@ -20,6 +20,8 @@ interface ParsedCliOutputArguments {
|
||||
readonly parseError: boolean;
|
||||
readonly tokenCount: boolean;
|
||||
readonly tokenWindow: boolean;
|
||||
readonly tokenLimit: number | undefined;
|
||||
readonly tokenOffset: number | undefined;
|
||||
}
|
||||
|
||||
/** Read effective Incur output controls at the executable boundary. */
|
||||
@@ -30,14 +32,18 @@ export const parseCliOutputArguments = (
|
||||
let filterOutput: string | undefined;
|
||||
let fullOutput = false;
|
||||
let tokenCount = false;
|
||||
let tokenWindow = false;
|
||||
let tokenLimit: number | undefined;
|
||||
let tokenOffset: number | undefined;
|
||||
const parsed = (parseError: boolean): ParsedCliOutputArguments => ({
|
||||
filterOutput,
|
||||
format,
|
||||
fullOutput,
|
||||
parseError,
|
||||
tokenCount,
|
||||
tokenWindow: parseError ? false : tokenWindow,
|
||||
tokenWindow:
|
||||
!parseError && (tokenLimit !== undefined || tokenOffset !== undefined),
|
||||
tokenLimit: parseError ? undefined : tokenLimit,
|
||||
tokenOffset: parseError ? undefined : tokenOffset,
|
||||
});
|
||||
for (let index = 0; index < arguments_.length; index += 1) {
|
||||
const argument = arguments_[index];
|
||||
@@ -71,7 +77,8 @@ export const parseCliOutputArguments = (
|
||||
const numericValue = Number(value);
|
||||
if (!Number.isFinite(numericValue) || value.trim() === "")
|
||||
return parsed(true);
|
||||
tokenWindow = true;
|
||||
if (argument === "--token-limit") tokenLimit = numericValue;
|
||||
else tokenOffset = numericValue;
|
||||
index += 1;
|
||||
}
|
||||
continue;
|
||||
|
||||
Reference in New Issue
Block a user