mirror of
https://github.com/morluto/rea.git
synced 2026-11-18 20:53:00 +00:00
fix(cli): reuse decoded inline JSON during admission (#11790)
This commit is contained in:
4 files changed
+121
-23
No files matched your search
@@ -714,9 +714,9 @@ export interface ContractCliDescription {
|
||||
/** The command adds `--detail` and `--evidence_output`. */
|
||||
readonly evidenceDelivery: boolean;
|
||||
/**
|
||||
* Decode run-time JSON, then map parsed values to the contract input and
|
||||
* the selected delivery. An input or delivery that is not admitted is
|
||||
* refused before any target is opened.
|
||||
* Map values decoded by `admitDeliveryOptions` and the JSON input reader
|
||||
* to the contract input and selected delivery. An input or delivery that
|
||||
* is not admitted is refused before any target is opened.
|
||||
*/
|
||||
readonly admit: (
|
||||
values: Readonly<Record<string, unknown>>,
|
||||
@@ -724,11 +724,12 @@ export interface ContractCliDescription {
|
||||
/**
|
||||
* Refuse inline JSON options and a delivery the options cannot select,
|
||||
* before any JSON input is read, so an invalid invocation never waits on a
|
||||
* file or stdin. `admit` still checks the admitted view with the input.
|
||||
* file or stdin. Return the decoded options for the input reader and `admit`;
|
||||
* `admit` still checks the admitted view with the input.
|
||||
*/
|
||||
readonly admitDeliveryOptions: (
|
||||
values: Readonly<Record<string, unknown>>,
|
||||
) => Result<void, AnalysisInputError>;
|
||||
) => Result<Record<string, unknown>, AnalysisInputError>;
|
||||
}
|
||||
|
||||
/** One contract from a contract group, keeping its exact schema types. */
|
||||
@@ -2506,7 +2507,7 @@ export const describeContractCommand = <
|
||||
admitDeliveryOptions: (values) => {
|
||||
const decoded = decodeInlineJson(contract.name, parameters, values);
|
||||
if (!decoded.ok) return decoded;
|
||||
if (!evidenceDelivery) return ok(undefined);
|
||||
if (!evidenceDelivery) return decoded;
|
||||
const view =
|
||||
viewDelivery === undefined
|
||||
? undefined
|
||||
@@ -2537,7 +2538,7 @@ export const describeContractCommand = <
|
||||
evidenceOutput: decoded.value.evidence_output as string | undefined,
|
||||
view,
|
||||
});
|
||||
return refused === undefined ? ok(undefined) : err(refused);
|
||||
return refused === undefined ? decoded : err(refused);
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -2653,8 +2654,8 @@ const selectSpelledSelector = (
|
||||
};
|
||||
|
||||
/**
|
||||
* Decode run-time JSON, then map the values to the contract input and the
|
||||
* selected delivery. When the projection decodes JSON at run time, the
|
||||
* Map decoded values to the contract input and selected delivery.
|
||||
* When the projection decodes JSON at run time, the
|
||||
* decoded input, delivery and view are admitted together by the contract
|
||||
* input schema, so the contract's own rules and messages apply. When argv
|
||||
* supplies the whole contract input, it is parsed once the same way and the
|
||||
@@ -2690,9 +2691,7 @@ const admitInvocation = (
|
||||
wholeInput,
|
||||
checkedFields,
|
||||
} = command;
|
||||
const inline = decodeInlineJson(contract.name, parameters, values);
|
||||
if (!inline.ok) return inline;
|
||||
const decoded = inline.value;
|
||||
const decoded = values;
|
||||
const input = toContractInput(decoded);
|
||||
const detail = evidenceDelivery
|
||||
? (decoded[rename("detail")] as "complete" | "summary" | undefined)
|
||||
|
||||
@@ -663,7 +663,7 @@ export const registerContractCommand = <
|
||||
logCliCommand(logger, description.command, async () => {
|
||||
const options = selected.admitDeliveryOptions(values);
|
||||
if (!options.ok) return projectAnalysisError(options.error);
|
||||
const read = await readJsonInputs(selected, values, signal);
|
||||
const read = await readJsonInputs(selected, options.value, signal);
|
||||
if (!read.ok) return read.error;
|
||||
const admitted = selected.admit(read.value);
|
||||
// Admission and handler issues alike name renamed fields by CLI key.
|
||||
@@ -981,7 +981,7 @@ export const registerRoutedCommand = (
|
||||
if (!options.ok) return projectAnalysisError(options.error);
|
||||
const read = await readJsonInputs(
|
||||
description,
|
||||
shared.value,
|
||||
options.value,
|
||||
signal,
|
||||
ownJsonInputs(description, sharedJson),
|
||||
);
|
||||
|
||||
@@ -27,6 +27,14 @@ import {
|
||||
} from "../../../src/contracts/toolContracts.js";
|
||||
import { registeredContractDescriptions } from "../../support/cli/commandCli.js";
|
||||
|
||||
/** Apply the same inline-option admission stage as registered commands. */
|
||||
const admitOptions = (
|
||||
description: ContractCliDescription,
|
||||
values: Readonly<Record<string, unknown>>,
|
||||
): ReturnType<ContractCliDescription["admit"]> => {
|
||||
const options = description.admitDeliveryOptions(values);
|
||||
return options.ok ? description.admit(options.value) : options;
|
||||
};
|
||||
const DECIMAL_TOKEN = /^[0-9]+$/u;
|
||||
|
||||
const cli = createCli({});
|
||||
@@ -789,7 +797,8 @@ describe("JSON decoded when contract commands run", () => {
|
||||
// there; the CLI tests cover that refusal.
|
||||
if (parameter.runtimeJson === undefined || parameter.jsonInput)
|
||||
continue;
|
||||
const malformed = description.admit(
|
||||
const malformed = admitOptions(
|
||||
description,
|
||||
argvValues(description, {
|
||||
detail: "summary",
|
||||
evidence_output: "out.json",
|
||||
@@ -852,7 +861,7 @@ describe("JSON decoded when contract commands run", () => {
|
||||
...(detail === undefined ? {} : { detail }),
|
||||
...supplied,
|
||||
}).success;
|
||||
const admitted = description.admit(values).ok;
|
||||
const admitted = admitOptions(description, values).ok;
|
||||
// A checked JSON input is admitted by its check, which the
|
||||
// command runs as soon as the input is read, and may be
|
||||
// stricter than the contract; the contract admits the rest.
|
||||
@@ -1328,7 +1337,8 @@ describe("Evidence delivery of contract commands", () => {
|
||||
...ARGV_SATISFYING_RULES[command],
|
||||
...SUMMARY_SELECTIONS[command],
|
||||
};
|
||||
const refused = description.admit(
|
||||
const refused = admitOptions(
|
||||
description,
|
||||
argvValues(description, { ...satisfying, detail: "summary" }),
|
||||
);
|
||||
expect(refused.ok).toBe(false);
|
||||
@@ -1337,7 +1347,8 @@ describe("Evidence delivery of contract commands", () => {
|
||||
["evidence_output"],
|
||||
]);
|
||||
expect(
|
||||
description.admit(
|
||||
admitOptions(
|
||||
description,
|
||||
argvValues(description, {
|
||||
...satisfying,
|
||||
detail: "summary",
|
||||
@@ -1733,7 +1744,7 @@ describe("Positional selectors with a named option", () => {
|
||||
);
|
||||
const { required } = option;
|
||||
const admit = (values: Record<string, unknown>) =>
|
||||
description.admit({
|
||||
admitOptions(description, {
|
||||
[description.sessionTarget?.key ?? "path"]: "rel/app",
|
||||
...values,
|
||||
});
|
||||
@@ -1782,7 +1793,7 @@ describe("Positional selectors with a named option", () => {
|
||||
(_command, description, parameter, alternative) => {
|
||||
const option = parameter.selectorOption!;
|
||||
const admit = (values: Record<string, unknown>) =>
|
||||
description.admit({
|
||||
admitOptions(description, {
|
||||
[description.sessionTarget?.key ?? "path"]: "rel/app",
|
||||
...values,
|
||||
});
|
||||
@@ -1940,7 +1951,7 @@ describe("Contract command field groups", () => {
|
||||
"path",
|
||||
"query",
|
||||
]);
|
||||
const admitted = description.admit({
|
||||
const admitted = admitOptions(description, {
|
||||
path: "/x",
|
||||
query: '{"name":"a","tags":["b"]}',
|
||||
});
|
||||
@@ -1949,7 +1960,7 @@ describe("Contract command field groups", () => {
|
||||
name: "a",
|
||||
tags: ["b"],
|
||||
});
|
||||
expect(description.admit({ path: "/x" }).ok).toBe(true);
|
||||
expect(admitOptions(description, { path: "/x" }).ok).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
@@ -1957,7 +1968,7 @@ describe("Contract command field groups", () => {
|
||||
['{"path":"/y"}', ["query", "path"], undefined],
|
||||
['{"name":1}', ["name"], undefined],
|
||||
])("refuses the group %s", (text, path, reason) => {
|
||||
const admitted = grouped(["name", "tags"]).admit({
|
||||
const admitted = admitOptions(grouped(["name", "tags"]), {
|
||||
path: "/x",
|
||||
query: text,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import pino from "pino";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
commandRoute,
|
||||
registerContractCommand,
|
||||
registerRoutedCommand,
|
||||
} from "../../../src/cli/contractCommand.js";
|
||||
import { cliCommand } from "../../../src/cli/commandRegistry.js";
|
||||
import type { CliInstance } from "../../../src/cli/types.js";
|
||||
import { createCommandCli } from "../../support/cli/commandCli.js";
|
||||
|
||||
describe.each(["direct", "routed"])("%s inline JSON admission", (kind) => {
|
||||
it.each([
|
||||
['{"items":[1,2,3]}', { items: [1, 2, 3] }],
|
||||
['"a JSON string"', "a JSON string"],
|
||||
["null", null],
|
||||
])(
|
||||
"decodes the inline option %s once per invocation",
|
||||
async (text, expected) => {
|
||||
const cli = createCommandCli();
|
||||
const received: unknown[] = [];
|
||||
const contract = {
|
||||
name: "inline_probe",
|
||||
inputSchema: z.object({ query: z.unknown() }),
|
||||
};
|
||||
const projection = {
|
||||
command: "inline-probe",
|
||||
description: "Inline JSON probe",
|
||||
runtimeJson: { query: "query must be JSON" },
|
||||
};
|
||||
const handle = async (input: unknown) => {
|
||||
received.push(input);
|
||||
return {};
|
||||
};
|
||||
if (kind === "direct")
|
||||
registerContractCommand(
|
||||
cli as unknown as CliInstance,
|
||||
pino({ enabled: false }),
|
||||
contract,
|
||||
projection,
|
||||
handle,
|
||||
);
|
||||
else
|
||||
registerRoutedCommand(
|
||||
cli as unknown as CliInstance,
|
||||
pino({ enabled: false }),
|
||||
projection,
|
||||
[
|
||||
commandRoute(contract, projection, handle, {
|
||||
requirement: "inline JSON",
|
||||
}),
|
||||
],
|
||||
);
|
||||
const registered = cliCommand(cli, "inline-probe")?.definition;
|
||||
if (registered === undefined) throw new Error("inline-probe is missing");
|
||||
const parse = (value: unknown) =>
|
||||
(
|
||||
Reflect.get(registered, "options") as { parse(v: unknown): unknown }
|
||||
).parse(value);
|
||||
const run = Reflect.get(registered, "run") as (
|
||||
value: unknown,
|
||||
) => Promise<unknown>;
|
||||
const exitCode = process.exitCode;
|
||||
const parseJson = vi.spyOn(JSON, "parse");
|
||||
try {
|
||||
for (let invocation = 0; invocation < 2; invocation += 1) {
|
||||
parseJson.mockClear();
|
||||
await run({ args: {}, options: parse({ query: text }) });
|
||||
expect(received.at(-1)).toEqual({ query: expected });
|
||||
expect(
|
||||
parseJson.mock.calls.filter(([value]) => value === text),
|
||||
).toHaveLength(1);
|
||||
}
|
||||
await expect(
|
||||
run({ args: {}, options: parse({ query: "{" }) }),
|
||||
).resolves.toMatchObject({
|
||||
code: "invalid_request",
|
||||
});
|
||||
expect(received).toHaveLength(2);
|
||||
} finally {
|
||||
parseJson.mockRestore();
|
||||
process.exitCode = exitCode;
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
Reference in new issue
Block a user