perf(cli/server/dotnet): single-pass --token-count JSON, indexed CLI command lookup, single status parse, and direct loops (#13631)

* perf(cli/server/dotnet): single-pass --token-count JSON, indexed CLI command lookup, single status parse, and direct loops

* fix(cli): admit JSON token counting before retaining output
This commit is contained in:
morluto authored and GitHub committed 2026-11-22 22:13:50 +00:00
1 parent c0c080176d
commit 2532adda84
6 files changed
+109 -46

No files matched your search

+3 -1
View File
@@ -76,7 +76,9 @@ export const resolveXrefsName = async (
}
if (signal?.aborted) return err(cancelledBy(operation, signal));
const addresses = new Set<string>();
for (const [index, row] of inventory.value.fact.entries()) {
const rows = inventory.value.fact;
for (let index = 0; index < rows.length; index += 1) {
const row = rows[index]!;
// An empty address cannot be passed back to xrefs.
if (row.address.length === 0)
return err(
+7 -14
View File
@@ -576,20 +576,13 @@ export const createCliResultOutput = (
// require a complete formatted string.
const tokenValue = document;
let characters = 0;
if (
tokenValue !== undefined &&
tokenValue !== null &&
typeof tokenValue !== "function" &&
typeof tokenValue !== "symbol"
) {
if (format === "json") {
for (const part of jsonOutputParts(
tokenValue,
format,
isTerminalOutput(destination),
))
characters += part.length;
}
if (format === "json") {
for (const part of jsonOutputParts(
tokenValue,
format,
isTerminalOutput(destination),
))
characters += part.length;
}
if (characters <= constants.MAX_STRING_LENGTH) {
let formatted: string;
+58 -20
View File
@@ -123,6 +123,7 @@ export const registerCliCommand = <
source: registration.source ?? { kind: "host" },
};
registry.entries.push(entry);
operationCommandIndexes.delete(registry.entries);
registry.byName.set(name, entry);
};
@@ -211,6 +212,56 @@ export const commandOwnOperations = (
return operations;
};
interface OperationCommandIndex {
readonly canonical: ReadonlyMap<string, string>;
readonly contractPrimary: ReadonlyMap<string, string>;
readonly contractSecondary: ReadonlyMap<string, string>;
readonly otherMatch: ReadonlyMap<string, string>;
}
const operationCommandIndexes = new WeakMap<
readonly CliCommandEntry[],
OperationCommandIndex
>();
const getOperationCommandIndex = (
entries: readonly CliCommandEntry[],
): OperationCommandIndex => {
let cached = operationCommandIndexes.get(entries);
if (cached !== undefined) return cached;
const canonical = new Map<string, string>();
const contractPrimary = new Map<string, string>();
const contractSecondary = new Map<string, string>();
const otherMatch = new Map<string, string>();
for (const entry of entries) {
const own = commandOwnOperations(entry);
const primaryName = own[0]?.name;
for (let index = 0; index < own.length; index += 1) {
const matched = own[index]!;
const opName = matched.name;
const command =
matched.selector === undefined
? entry.name
: `${entry.name} ${matched.selector}`;
if (entry.name === cliCommandFor(opName) && !canonical.has(opName))
canonical.set(opName, command);
if (entry.source.kind === "contract") {
if (primaryName === opName) {
if (!contractPrimary.has(opName))
contractPrimary.set(opName, command);
} else if (!contractSecondary.has(opName)) {
contractSecondary.set(opName, command);
}
} else if (!otherMatch.has(opName)) {
otherMatch.set(opName, command);
}
}
}
cached = { canonical, contractPrimary, contractSecondary, otherMatch };
operationCommandIndexes.set(entries, cached);
return cached;
};
/**
* The CLI command spelling (`rea <command>`) that runs a contract operation,
* or undefined when no CLI command answers it. Prefers the canonical
@@ -224,31 +275,18 @@ export const cliCommandForOperation = (
cliName: string,
recordedCommands?: Readonly<Record<string, string>>,
): string | undefined => {
const index = getOperationCommandIndex(entries);
const direct = index.canonical.get(operation);
if (direct !== undefined) return `${cliName} ${direct}`;
const canonical = cliCommandFor(operation);
let contractPrimary: string | undefined;
let contractSecondary: string | undefined;
let otherMatch: string | undefined;
for (const entry of entries) {
const own = commandOwnOperations(entry);
const matched = own.find(({ name }) => name === operation);
if (matched === undefined) continue;
const command =
matched.selector === undefined
? entry.name
: `${entry.name} ${matched.selector}`;
if (entry.name === canonical) return `${cliName} ${command}`;
if (entry.source.kind === "contract") {
if (own[0]?.name === operation) contractPrimary ??= command;
else contractSecondary ??= command;
} else {
otherMatch ??= command;
}
}
if (
recordedCommands !== undefined &&
Object.hasOwn(recordedCommands, canonical)
)
return `${cliName} ${canonical}`;
const selected = contractPrimary ?? contractSecondary ?? otherMatch;
const selected =
index.contractPrimary.get(operation) ??
index.contractSecondary.get(operation) ??
index.otherMatch.get(operation);
return selected === undefined ? undefined : `${cliName} ${selected}`;
};
+10 -8
View File
@@ -326,6 +326,15 @@ export const inspectManagedMembersBytes = (
declarationTypeName,
});
appendManagedParseIssues(issues, memberRefs.issues);
const memberRefKinds = new Map<string, "field" | "method">();
for (let index = 0; index < memberRefs.refs.length; index += 1) {
const memberRef = memberRefs.refs[index]!;
if (
memberRef.signature.kind === "field" ||
memberRef.signature.kind === "method"
)
memberRefKinds.set(memberRef.token, memberRef.signature.kind);
}
const methods = parseMethods({
bytes,
layout,
@@ -334,14 +343,7 @@ export const inspectManagedMembersBytes = (
signatureTypeName,
displayTypeName,
declarationTypeName,
memberRefKinds: new Map(
memberRefs.refs.flatMap((memberRef) =>
memberRef.signature.kind === "field" ||
memberRef.signature.kind === "method"
? [[memberRef.token, memberRef.signature.kind] as const]
: [],
),
),
memberRefKinds,
memberLists,
selected,
methodOffset,
+3 -1
View File
@@ -130,7 +130,9 @@ export const readSessionStatus = async (
if (!(cause instanceof AnalysisError)) throw cause;
return err(cause);
}
const statusObject = ownedJsonObjectSchema.parse(status);
const statusObject = status as unknown as Readonly<
Record<string, import("../domain/jsonValue.js").JsonValue>
>;
// Availability is derived from the complete provider facts: an
// advertised composed tool still depends on direct operations the
// registration hides. Advertisement narrows only the public report.
+28 -2
View File
@@ -1,4 +1,8 @@
import { registerCliCommand } from "../../../src/cli/commandRegistry.js";
import {
cliCommandForOperation,
cliCommands,
registerCliCommand,
} from "../../../src/cli/commandRegistry.js";
import { createCommandCli } from "../../support/cli/commandCli.js";
import { constants } from "node:buffer";
import { createHash } from "node:crypto";
@@ -521,6 +525,7 @@ describe("full-output token counts", () => {
[],
["--full-output"],
["--filter-output", "missing"],
["--filter-output", "raw_result"],
["--format", "jsonl"],
]) {
const argv = ["fixture", "--json", ...flags];
@@ -541,7 +546,10 @@ describe("full-output token counts", () => {
destination,
);
if (output === undefined) throw new Error("Missing output surface");
await output.write({ rows: ["hello", "雪😀"] }, metadata);
await output.write(
{ rows: ["hello", "雪😀"], raw_result: null },
metadata,
);
return Buffer.concat(chunks).toString("utf8");
};
const document = await render(false);
@@ -785,3 +793,21 @@ describe("streamed CLI filtered selections", () => {
},
);
});
it("refreshes the operation lookup after registering another command", () => {
const cli = createCommandCli();
registerCliCommand(cli, "existing", { run: () => undefined });
const commands = cliCommands(cli);
const lookup = () =>
cliCommandForOperation("fixture_late_operation", commands, "rea");
expect(lookup()).toBeUndefined();
registerCliCommand(
cli,
"fixture-late-operation",
{ run: () => undefined },
{
operations: [{ name: "fixture_late_operation", flags: {} }],
},
);
expect(lookup()).toBe("rea fixture-late-operation");
});