feat(signals): discover installed decoders and option help (#2487)
* feat(signals): discover installed decoders and selected option help * fix(signals): bound retained discovery data and preserve resource failures * fix(signals): complete CLI help and portable decoder patterns * test(signals): verify case-insensitive decoder help queries * fix(signals): retain discovery operation across cleanup retries
This commit is contained in:
@@ -405,7 +405,7 @@ const workflowAvailabilityFor = ({
|
||||
remediation:
|
||||
"On Linux, supply TShark 4.x via absolute REA_TSHARK_COMMAND and util-linux prlimit (REA_TSHARK_PRLIMIT_COMMAND, default /usr/bin/prlimit). No active binary target or hardware is required; the tool is checked at execution.",
|
||||
};
|
||||
if (name === "decode_signal_recording")
|
||||
if (name === "decode_signal_recording" || name === "inspect_signal_decoders")
|
||||
return policy.signalRecordingEnabled === true
|
||||
? { reason: "available", remediation: null }
|
||||
: {
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
import {
|
||||
inspectSignalDecodersInputSchema,
|
||||
signalDecodersSchema,
|
||||
type InspectSignalDecodersInput,
|
||||
} from "../../domain/signals/signalDecoders.js";
|
||||
import type { JsonValue } from "../../domain/jsonValue.js";
|
||||
import { isAbsolute } from "node:path";
|
||||
import type {
|
||||
AnalysisExecution,
|
||||
@@ -24,6 +30,10 @@ export interface SignalRecordingPort {
|
||||
input: DecodeSignalRecordingInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>>;
|
||||
inspectDecoders(
|
||||
input: InspectSignalDecodersInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -74,14 +84,58 @@ export class SignalRecordingService {
|
||||
"Decoder returned malformed data or changed the selected recording identity/options.",
|
||||
),
|
||||
);
|
||||
const evidence = createEvidence(execution.subject, execution.provider, {
|
||||
operation,
|
||||
parameters: input.data,
|
||||
result: report.data,
|
||||
confidence: "observed",
|
||||
locations: execution.locations,
|
||||
limitations: execution.limitations,
|
||||
});
|
||||
return this.#evidence(operation, input.data, execution, options);
|
||||
}
|
||||
async inspectDecoders(
|
||||
raw: unknown,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
const operation = "inspect_signal_decoders";
|
||||
if (options?.signal?.aborted)
|
||||
return err(new AnalysisCancelledError(operation));
|
||||
const input = inspectSignalDecodersInputSchema.safeParse(raw);
|
||||
if (!input.success)
|
||||
return err(
|
||||
analysisInputErrorFromIssues(operation, input.error.issues, raw, {
|
||||
cause: input.error,
|
||||
}),
|
||||
);
|
||||
const decoded = await this.provider.inspectDecoders(input.data, options);
|
||||
if (!decoded.ok) return decoded;
|
||||
const execution = decoded.value;
|
||||
const report = signalDecodersSchema.safeParse(execution.result);
|
||||
if (
|
||||
!report.success ||
|
||||
JSON.stringify(report.data.selection) !== JSON.stringify(input.data) ||
|
||||
execution.subject?.path !== report.data.tool.path ||
|
||||
execution.subject.sha256 !== report.data.tool.sha256
|
||||
)
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
operation,
|
||||
"Decoder discovery returned malformed data or changed the selected installation/options.",
|
||||
),
|
||||
);
|
||||
return this.#evidence(operation, input.data, execution, options);
|
||||
}
|
||||
#evidence(
|
||||
operation: string,
|
||||
parameters: Readonly<Record<string, JsonValue>>,
|
||||
execution: AnalysisExecution,
|
||||
options?: ExecutionOptions,
|
||||
): Result<Evidence, AnalysisError> {
|
||||
const evidence = createEvidence(
|
||||
execution.subject ?? undefined,
|
||||
execution.provider,
|
||||
{
|
||||
operation,
|
||||
parameters,
|
||||
result: execution.result,
|
||||
confidence: "observed",
|
||||
locations: execution.locations,
|
||||
limitations: execution.limitations,
|
||||
},
|
||||
);
|
||||
return options?.signal?.aborted
|
||||
? err(
|
||||
new AnalysisCancelledError(operation, {
|
||||
|
||||
+69
-26
@@ -1,3 +1,4 @@
|
||||
import { inspectSignalDecodersInputSchema } from "../domain/signals/signalDecoders.js";
|
||||
import { z } from "incur";
|
||||
import type { SignalRecordingService } from "../application/signals/SignalRecordingService.js";
|
||||
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
@@ -22,9 +23,75 @@ export const registerSignalCommands = (
|
||||
environment: Readonly<NodeJS.ProcessEnv>,
|
||||
service: Pick<
|
||||
SignalRecordingService,
|
||||
"decode" | "close"
|
||||
"decode" | "inspectDecoders" | "close"
|
||||
> = createSignalRecordingService(environment),
|
||||
): void => {
|
||||
const finish = async (
|
||||
result: Awaited<ReturnType<SignalRecordingService["decode"]>>,
|
||||
operation: string,
|
||||
) => {
|
||||
// A one-shot command must retry retained cleanup before discarding its owner.
|
||||
try {
|
||||
await service.close();
|
||||
} catch (cause) {
|
||||
const cleanup =
|
||||
cause instanceof AnalysisError
|
||||
? cause
|
||||
: new ProviderCleanupError(
|
||||
"sigrok-recording",
|
||||
[],
|
||||
{ reason: String(cause) },
|
||||
{ cause, operation: operation },
|
||||
);
|
||||
if (result.ok) cleanup.retainPartialObservation(result.value);
|
||||
return projectAnalysisError(
|
||||
result.ok
|
||||
? cleanup
|
||||
: analysisErrorWithCleanupFailure(result.error, cleanup, operation),
|
||||
);
|
||||
}
|
||||
return result.ok ? result.value : projectAnalysisError(result.error);
|
||||
};
|
||||
cli.command(CLI_COMMANDS.inspectSignalDecoders, {
|
||||
description: "Search installed sigrok decoders or selected decoder help",
|
||||
options: z
|
||||
.object({
|
||||
...inspectSignalDecodersInputSchema.shape,
|
||||
limit: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.max(Number.MAX_SAFE_INTEGER)
|
||||
.optional()
|
||||
.describe(
|
||||
"Maximum matching decoders or help lines to return; defaults to 50",
|
||||
),
|
||||
all: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.describe("Return all remaining matches"),
|
||||
})
|
||||
.superRefine((options, context) => {
|
||||
if (options.all && options.limit !== undefined)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["all"],
|
||||
message: "all and limit are mutually exclusive",
|
||||
});
|
||||
}),
|
||||
run: ({ options: { all, ...options } }) =>
|
||||
withCommandCancellation((signal) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.inspectSignalDecoders, async () =>
|
||||
finish(
|
||||
await service.inspectDecoders(
|
||||
{ ...options, ...(all ? { limit: null } : {}) },
|
||||
{ signal },
|
||||
),
|
||||
"inspect_signal_decoders",
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
cli.command(CLI_COMMANDS.decodeSignalRecording, {
|
||||
description:
|
||||
"Decode an existing signal recording with caller-supplied sigrok",
|
||||
@@ -68,31 +135,7 @@ export const registerSignalCommands = (
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
// A one-shot command must retry retained cleanup before discarding its owner.
|
||||
try {
|
||||
await service.close();
|
||||
} catch (cause) {
|
||||
const cleanup =
|
||||
cause instanceof AnalysisError
|
||||
? cause
|
||||
: new ProviderCleanupError(
|
||||
"sigrok-recording",
|
||||
[],
|
||||
{ reason: String(cause) },
|
||||
{ cause, operation: "decode_signal_recording" },
|
||||
);
|
||||
if (result.ok) cleanup.retainPartialObservation(result.value);
|
||||
return projectAnalysisError(
|
||||
result.ok
|
||||
? cleanup
|
||||
: analysisErrorWithCleanupFailure(
|
||||
result.error,
|
||||
cleanup,
|
||||
"decode_signal_recording",
|
||||
),
|
||||
);
|
||||
}
|
||||
return result.ok ? result.value : projectAnalysisError(result.error);
|
||||
return finish(result, "decode_signal_recording");
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
export const CLI_COMMANDS = Object.freeze({
|
||||
inspectPacketFields: "inspect-packet-fields",
|
||||
inspectPacketCapture: "inspect-packet-capture",
|
||||
inspectSignalDecoders: "inspect-signal-decoders",
|
||||
decodeSignalRecording: "decode-signal-recording",
|
||||
inspectWasmArtifact: "inspect-wasm-artifact",
|
||||
inspectSqliteDatabase: "inspect-sqlite-database",
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import {
|
||||
inspectSignalDecodersInputSchema,
|
||||
signalDecodersSchema,
|
||||
} from "../../domain/signals/signalDecoders.js";
|
||||
import {
|
||||
decodeSignalRecordingInputSchema,
|
||||
signalRecordingSchema,
|
||||
@@ -6,6 +10,22 @@ import type { ToolContract } from "../toolContractTypes.js";
|
||||
import { toolContractMetadata } from "../toolEffects.js";
|
||||
import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js";
|
||||
export const SIGNAL_TOOL_CONTRACTS = [
|
||||
{
|
||||
name: "inspect_signal_decoders",
|
||||
...toolContractMetadata("inspect_signal_decoders"),
|
||||
kind: "artifact-provider",
|
||||
description:
|
||||
"Discover installed sigrok protocol decoders or inspect one decoder's channel/option help on Linux. Omit decoder to list ID/name pairs; supply its exact ID for literal help lines with source line numbers. query is a case-insensitive literal substring. Page matches with offset/limit (default 50; null returns all remaining). Reports tool identity, version, diagnostics and examined/matching coverage. Uses configured REA_SIGROK_COMMAND and prlimit; no recording, binary target, hardware scan or acquisition. Each call probes again; decoder modules are trusted, not fully fingerprinted. Use returned IDs/options with decode_signal_recording.",
|
||||
inputSchema: inspectSignalDecodersInputSchema,
|
||||
outputSchema: evidenceResultOf(signalDecodersSchema),
|
||||
examples: [
|
||||
{ title: "Find installed UART decoders", input: { query: "uart" } },
|
||||
{
|
||||
title: "Read the installed UART baud-rate option",
|
||||
input: { decoder: "uart", query: "baud" },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "decode_signal_recording",
|
||||
...toolContractMetadata("decode_signal_recording"),
|
||||
|
||||
@@ -69,6 +69,11 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
launchesProcess: true,
|
||||
writesFilesystem: true,
|
||||
}),
|
||||
inspect_signal_decoders: effects({
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
writesFilesystem: true,
|
||||
}),
|
||||
decode_signal_recording: effects({
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { z } from "zod";
|
||||
import { signalRecordingSchema } from "./signalRecording.js";
|
||||
|
||||
export const inspectSignalDecodersInputSchema = z.strictObject({
|
||||
decoder: z
|
||||
.string()
|
||||
.regex(/^[a-zA-Z0-9_+\x2d]+$/u)
|
||||
.max(256)
|
||||
.nullable()
|
||||
.default(null)
|
||||
.describe(
|
||||
"Exact installed decoder ID for help; null searches the decoder catalog",
|
||||
),
|
||||
query: z
|
||||
.string()
|
||||
.max(8192)
|
||||
.default("")
|
||||
.describe(
|
||||
"Case-insensitive literal substring in decoder ID/name or help lines; empty selects all",
|
||||
),
|
||||
offset: z
|
||||
.number()
|
||||
.int()
|
||||
.nonnegative()
|
||||
.max(Number.MAX_SAFE_INTEGER)
|
||||
.default(0)
|
||||
.describe(
|
||||
"Number of matching decoders or help lines to skip; defaults to 0",
|
||||
),
|
||||
limit: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.max(Number.MAX_SAFE_INTEGER)
|
||||
.nullable()
|
||||
.default(50)
|
||||
.describe(
|
||||
"Maximum matching decoders or help lines returned; null requests all remaining",
|
||||
),
|
||||
});
|
||||
export type InspectSignalDecodersInput = z.infer<
|
||||
typeof inspectSignalDecodersInputSchema
|
||||
>;
|
||||
export const signalDecodersSchema = z
|
||||
.strictObject({
|
||||
selection: inspectSignalDecodersInputSchema,
|
||||
decoders: z.array(z.strictObject({ id: z.string(), name: z.string() })),
|
||||
help_lines: z.array(
|
||||
z.strictObject({
|
||||
line_number: z.number().int().positive(),
|
||||
text: z.string(),
|
||||
}),
|
||||
),
|
||||
output_window: z.strictObject({
|
||||
unit: z.enum(["decoders", "help-lines"]),
|
||||
examined: z.number().int().nonnegative(),
|
||||
matching: z.number().int().nonnegative(),
|
||||
returned: z.number().int().nonnegative(),
|
||||
has_more: z.boolean(),
|
||||
}),
|
||||
diagnostics: z.string(),
|
||||
tool: signalRecordingSchema.shape.tool,
|
||||
resource_limiter: signalRecordingSchema.shape.resource_limiter,
|
||||
limits: signalRecordingSchema.shape.limits,
|
||||
hardware_acquisition: z.literal("not-performed"),
|
||||
})
|
||||
.superRefine((report, context) => {
|
||||
const w = report.output_window;
|
||||
const catalog = report.selection.decoder === null;
|
||||
const remaining = Math.max(0, w.matching - report.selection.offset);
|
||||
const expected = Math.min(remaining, report.selection.limit ?? remaining);
|
||||
if (
|
||||
w.unit !== (catalog ? "decoders" : "help-lines") ||
|
||||
w.matching > w.examined ||
|
||||
w.returned !== expected ||
|
||||
(catalog ? report.decoders : report.help_lines).length !== expected ||
|
||||
(catalog ? report.help_lines : report.decoders).length !== 0 ||
|
||||
w.has_more !== remaining > expected
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["output_window"],
|
||||
message:
|
||||
"Discovery coverage must match the selected page and result kind",
|
||||
});
|
||||
});
|
||||
@@ -28,4 +28,17 @@ export const registerSignalTools = (
|
||||
toolRegistrationOptions(contract),
|
||||
handler(contract),
|
||||
);
|
||||
const discovery = toolContract("inspect_signal_decoders");
|
||||
const discover = createEvidenceToolHandler(
|
||||
server,
|
||||
(input, options) => service.inspectDecoders(input, options),
|
||||
logger,
|
||||
recordEvidence,
|
||||
withAdmittedAnalysis,
|
||||
);
|
||||
server.registerTool(
|
||||
discovery.name,
|
||||
toolRegistrationOptions(discovery),
|
||||
discover(discovery),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,3 +1,11 @@
|
||||
import {
|
||||
type InspectSignalDecodersInput,
|
||||
signalDecodersSchema,
|
||||
} from "../domain/signals/signalDecoders.js";
|
||||
import {
|
||||
DecoderDiscoveryBudgetError,
|
||||
parseDecoderDiscovery,
|
||||
} from "./parseDecoderDiscovery.js";
|
||||
import {
|
||||
readLinuxResourceLimits,
|
||||
type LinuxResourceLimits,
|
||||
@@ -81,7 +89,7 @@ export class SigrokRecordingProvider implements SignalRecordingPort {
|
||||
readLimits,
|
||||
{
|
||||
message:
|
||||
"A signal decoding operation is already active; retry after it completes.",
|
||||
"A sigrok operation is already active; retry after it completes.",
|
||||
details: { max_concurrent_decodes: 1 },
|
||||
},
|
||||
);
|
||||
@@ -91,17 +99,28 @@ export class SigrokRecordingProvider implements SignalRecordingPort {
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>> {
|
||||
return this.#resources.run(
|
||||
() => this.#decode(input, options),
|
||||
() => this.#executeRequest(input, options),
|
||||
options?.signal,
|
||||
);
|
||||
}
|
||||
inspectDecoders(
|
||||
input: InspectSignalDecodersInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>> {
|
||||
return this.#resources.run(
|
||||
() => this.#executeRequest(input, options),
|
||||
options?.signal,
|
||||
"inspect_signal_decoders",
|
||||
);
|
||||
}
|
||||
close(): Promise<void> {
|
||||
return this.#resources.close();
|
||||
}
|
||||
async #decode(
|
||||
input: DecodeSignalRecordingInput,
|
||||
async #executeRequest(
|
||||
input: DecodeSignalRecordingInput | InspectSignalDecodersInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>> {
|
||||
const operation = "path" in input ? OPERATION : "inspect_signal_decoders";
|
||||
let phase:
|
||||
| "configuration"
|
||||
| "artifact"
|
||||
@@ -109,12 +128,12 @@ export class SigrokRecordingProvider implements SignalRecordingPort {
|
||||
| "producer"
|
||||
| "integrity" = "configuration";
|
||||
let capturedOutput: AnalysisCapturedOutput | undefined;
|
||||
let resourcePath = input.path;
|
||||
let resourcePath = "path" in input ? input.path : "sigrok decoder catalog";
|
||||
let effectiveLimits: LinuxResourceLimits | undefined;
|
||||
let root: ArtifactAnalysisRuntime | undefined;
|
||||
let result: Result<AnalysisExecution, AnalysisError>;
|
||||
try {
|
||||
if (options?.signal?.aborted) throw new AnalysisCancelledError(OPERATION);
|
||||
if (options?.signal?.aborted) throw new AnalysisCancelledError(operation);
|
||||
await this.#resources.release();
|
||||
if (this.platform !== "linux")
|
||||
throw new Error(
|
||||
@@ -154,7 +173,7 @@ export class SigrokRecordingProvider implements SignalRecordingPort {
|
||||
];
|
||||
phase = "workspace";
|
||||
root = await this.createRuntime();
|
||||
this.#resources.retain(root, undefined);
|
||||
this.#resources.retain(root, undefined, operation);
|
||||
const snapshotPath = join(root.path, "recording");
|
||||
const execute = async (args: readonly string[]) => {
|
||||
const output = await runOwnedCommand(
|
||||
@@ -197,24 +216,24 @@ export class SigrokRecordingProvider implements SignalRecordingPort {
|
||||
);
|
||||
if (currentLimiter.sha256 !== limiterIdentity.sha256)
|
||||
throw new AnalysisArtifactChangedError(
|
||||
OPERATION,
|
||||
operation,
|
||||
limiter,
|
||||
"Configured resource limiter changed during analysis.",
|
||||
{ capturedOutput },
|
||||
);
|
||||
if (current.sha256 !== tool.sha256)
|
||||
throw new AnalysisArtifactChangedError(
|
||||
OPERATION,
|
||||
operation,
|
||||
command,
|
||||
"Configured decoder executable changed during analysis.",
|
||||
{ capturedOutput },
|
||||
);
|
||||
phase = previousPhase;
|
||||
resourcePath = input.path;
|
||||
resourcePath = "path" in input ? input.path : command;
|
||||
if (output.exitCode !== 0)
|
||||
throw new ProviderAdapterError(
|
||||
SIGROK_PROVIDER_IDENTITY.id,
|
||||
OPERATION,
|
||||
operation,
|
||||
{
|
||||
diagnostics: {
|
||||
exit_code: output.exitCode ?? null,
|
||||
@@ -234,65 +253,15 @@ export class SigrokRecordingProvider implements SignalRecordingPort {
|
||||
throw new Error(
|
||||
"Expected sigrok-cli 0.7.2 with libsigrokdecode; inspect the selected installation.",
|
||||
);
|
||||
phase = "artifact";
|
||||
const selected = await this.#resources.read(
|
||||
input.path,
|
||||
LIMITS.input_bytes,
|
||||
options?.signal,
|
||||
);
|
||||
phase = "workspace";
|
||||
await writeFile(snapshotPath, selected.bytes, {
|
||||
flag: "wx",
|
||||
mode: 0o400,
|
||||
});
|
||||
phase = "producer";
|
||||
const args = [
|
||||
"--dont-scan",
|
||||
"--input-file=recording",
|
||||
`--protocol-decoders=${input.decoders}`,
|
||||
"--protocol-decoder-samplenum",
|
||||
...(input.input_format === null
|
||||
? []
|
||||
: [`--input-format=${input.input_format}`]),
|
||||
...(input.annotations === null
|
||||
? []
|
||||
: [`--protocol-decoder-annotations=${input.annotations}`]),
|
||||
];
|
||||
const output = await execute(args);
|
||||
phase = "integrity";
|
||||
resourcePath = snapshotPath;
|
||||
if (
|
||||
(await this.#resources.read(snapshotPath, LIMITS.input_bytes))
|
||||
.sha256 !== selected.sha256
|
||||
)
|
||||
throw new AnalysisArtifactChangedError(
|
||||
OPERATION,
|
||||
snapshotPath,
|
||||
"Decoder changed the private recording copy.",
|
||||
capturedOutput === undefined ? {} : { capturedOutput },
|
||||
);
|
||||
phase = "producer";
|
||||
resourcePath = input.path;
|
||||
const report = signalRecordingSchema.parse({
|
||||
artifact: {
|
||||
path: input.path,
|
||||
sha256: selected.sha256,
|
||||
bytes: selected.bytes.length,
|
||||
},
|
||||
selection: input,
|
||||
...windowAnnotationText(
|
||||
output.stdout.text,
|
||||
input.line_offset,
|
||||
input.line_limit,
|
||||
),
|
||||
diagnostics: output.stderr.text,
|
||||
const metadata = (args: readonly string[], diagnostics: string) => ({
|
||||
diagnostics,
|
||||
tool: {
|
||||
configured_path: configured,
|
||||
path: command,
|
||||
sha256: tool.sha256,
|
||||
version_banner: version.stdout.text,
|
||||
version_diagnostics: version.stderr.text,
|
||||
arguments: args,
|
||||
arguments: [...args],
|
||||
},
|
||||
resource_limiter: {
|
||||
configured_path: configuredLimiter,
|
||||
@@ -301,31 +270,108 @@ export class SigrokRecordingProvider implements SignalRecordingPort {
|
||||
arguments: limitArguments,
|
||||
},
|
||||
limits: { ...LIMITS, ...effectiveLimits },
|
||||
hardware_acquisition: "not-performed",
|
||||
hardware_acquisition: "not-performed" as const,
|
||||
});
|
||||
result = ok(
|
||||
createAnalysisExecution(report, SIGROK_PROVIDER_IDENTITY, {
|
||||
subject: {
|
||||
if (!("path" in input)) {
|
||||
phase = "producer";
|
||||
const args =
|
||||
input.decoder === null
|
||||
? ["--dont-scan", "--list-supported"]
|
||||
: ["--dont-scan", `--protocol-decoders=${input.decoder}`, "--show"];
|
||||
const output = await execute(args);
|
||||
const report = signalDecodersSchema.parse({
|
||||
selection: input,
|
||||
...parseDecoderDiscovery(output.stdout.text, input),
|
||||
...metadata(args, output.stderr.text),
|
||||
});
|
||||
result = ok(
|
||||
createAnalysisExecution(report, SIGROK_PROVIDER_IDENTITY, {
|
||||
subject: { path: command, sha256: tool.sha256, format: "file" },
|
||||
limitations: [
|
||||
"Catalog and help are observed from the selected sigrok installation. Help lines preserve producer descriptions, not a separately validated parameter schema.",
|
||||
"Each request probes the installation again; pages do not share a frozen catalog. Decoder modules and libraries are trusted and not fully fingerprinted.",
|
||||
"Hardware discovery, recording reads and acquisition are not requested. Linux per-process limits and bounded output apply; this is not an OS sandbox.",
|
||||
],
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
phase = "artifact";
|
||||
const selected = await this.#resources.read(
|
||||
input.path,
|
||||
LIMITS.input_bytes,
|
||||
options?.signal,
|
||||
);
|
||||
phase = "workspace";
|
||||
await writeFile(snapshotPath, selected.bytes, {
|
||||
flag: "wx",
|
||||
mode: 0o400,
|
||||
});
|
||||
phase = "producer";
|
||||
const args = [
|
||||
"--dont-scan",
|
||||
"--input-file=recording",
|
||||
`--protocol-decoders=${input.decoders}`,
|
||||
"--protocol-decoder-samplenum",
|
||||
...(input.input_format === null
|
||||
? []
|
||||
: [`--input-format=${input.input_format}`]),
|
||||
...(input.annotations === null
|
||||
? []
|
||||
: [`--protocol-decoder-annotations=${input.annotations}`]),
|
||||
];
|
||||
const output = await execute(args);
|
||||
phase = "integrity";
|
||||
resourcePath = snapshotPath;
|
||||
if (
|
||||
(await this.#resources.read(snapshotPath, LIMITS.input_bytes))
|
||||
.sha256 !== selected.sha256
|
||||
)
|
||||
throw new AnalysisArtifactChangedError(
|
||||
operation,
|
||||
snapshotPath,
|
||||
"Decoder changed the private recording copy.",
|
||||
capturedOutput === undefined ? {} : { capturedOutput },
|
||||
);
|
||||
phase = "producer";
|
||||
resourcePath = "path" in input ? input.path : command;
|
||||
const report = signalRecordingSchema.parse({
|
||||
artifact: {
|
||||
path: input.path,
|
||||
sha256: selected.sha256,
|
||||
format: "file",
|
||||
bytes: selected.bytes.length,
|
||||
},
|
||||
locations: [{ kind: "artifact-path", path: input.path }],
|
||||
limitations: [
|
||||
"Annotations are the selected decoder's interpretation of the recorded samples and caller-selected settings, not independently verified protocol semantics. Empty output does not establish absence of traffic.",
|
||||
"Sample-number ranges and display text are preserved verbatim, not converted to timestamps or parsed as a lossless byte stream. All producer stderr is retained, including warnings on exit zero.",
|
||||
"Only a private copy of the selected file is decoded. Hardware discovery/acquisition and target execution are not requested. Caller-supplied tools, plugins and decoder modules are trusted; this is not an OS sandbox.",
|
||||
"Linux prlimit enforces soft and hard ceilings before execution, preserving stricter inherited limits: at most 1 GiB address space per process, 64 MiB per file, 30 CPU seconds and no core dumps. Effective limits are reported. Resident input is capped at 32 MiB, each command at 30 wall-clock seconds and combined output at 4 MiB. Output overflow fails. These are per-process/per-file limits, not aggregate memory or filesystem quotas; caller-supplied tools and the limiter are trusted.",
|
||||
],
|
||||
}),
|
||||
);
|
||||
selection: input,
|
||||
...windowAnnotationText(
|
||||
output.stdout.text,
|
||||
input.line_offset,
|
||||
input.line_limit,
|
||||
),
|
||||
...metadata(args, output.stderr.text),
|
||||
});
|
||||
result = ok(
|
||||
createAnalysisExecution(report, SIGROK_PROVIDER_IDENTITY, {
|
||||
subject: {
|
||||
path: input.path,
|
||||
sha256: selected.sha256,
|
||||
format: "file",
|
||||
},
|
||||
locations: [{ kind: "artifact-path", path: input.path }],
|
||||
limitations: [
|
||||
"Annotations are the selected decoder's interpretation of the recorded samples and caller-selected settings, not independently verified protocol semantics. Empty output does not establish absence of traffic.",
|
||||
"Sample-number ranges and display text are preserved verbatim, not converted to timestamps or parsed as a lossless byte stream. All producer stderr is retained, including warnings on exit zero.",
|
||||
"Only a private copy of the selected file is decoded. Hardware discovery/acquisition and target execution are not requested. Caller-supplied tools, plugins and decoder modules are trusted; this is not an OS sandbox.",
|
||||
"Linux prlimit enforces soft and hard ceilings before execution, preserving stricter inherited limits: at most 1 GiB address space per process, 64 MiB per file, 30 CPU seconds and no core dumps. Effective limits are reported. Resident input is capped at 32 MiB, each command at 30 wall-clock seconds and combined output at 4 MiB. Output overflow fails. These are per-process/per-file limits, not aggregate memory or filesystem quotas; caller-supplied tools and the limiter are trusted.",
|
||||
],
|
||||
}),
|
||||
);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (
|
||||
root !== undefined &&
|
||||
cause instanceof OwnedCommandFailure &&
|
||||
cause.cleanupOwner !== undefined
|
||||
)
|
||||
this.#resources.retain(root, cause.cleanupOwner);
|
||||
this.#resources.retain(root, cause.cleanupOwner, operation);
|
||||
result = err(
|
||||
this.#failure(
|
||||
cause,
|
||||
@@ -334,18 +380,22 @@ export class SigrokRecordingProvider implements SignalRecordingPort {
|
||||
root?.path ?? null,
|
||||
effectiveLimits,
|
||||
capturedOutput,
|
||||
operation,
|
||||
),
|
||||
);
|
||||
}
|
||||
return this.#resources.finish(result, (execution) =>
|
||||
createEvidence(execution.subject ?? undefined, execution.provider, {
|
||||
operation: OPERATION,
|
||||
parameters: input,
|
||||
result: execution.result,
|
||||
confidence: "observed",
|
||||
locations: execution.locations,
|
||||
limitations: execution.limitations,
|
||||
}),
|
||||
return this.#resources.finish(
|
||||
result,
|
||||
(execution) =>
|
||||
createEvidence(execution.subject ?? undefined, execution.provider, {
|
||||
operation,
|
||||
parameters: input,
|
||||
result: execution.result,
|
||||
confidence: "observed",
|
||||
locations: execution.locations,
|
||||
limitations: execution.limitations,
|
||||
}),
|
||||
operation,
|
||||
);
|
||||
}
|
||||
#failure(
|
||||
@@ -360,6 +410,7 @@ export class SigrokRecordingProvider implements SignalRecordingPort {
|
||||
workspacePath: string | null,
|
||||
effectiveLimits: LinuxResourceLimits | undefined,
|
||||
observedOutput: AnalysisCapturedOutput | undefined,
|
||||
operation = OPERATION,
|
||||
): AnalysisError {
|
||||
if (cause instanceof AnalysisError) return cause;
|
||||
if (cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined)
|
||||
@@ -367,15 +418,34 @@ export class SigrokRecordingProvider implements SignalRecordingPort {
|
||||
cause.cleanup,
|
||||
cause,
|
||||
observedOutput,
|
||||
operation,
|
||||
);
|
||||
if (
|
||||
(cause instanceof Error && cause.name === "AbortError") ||
|
||||
(cause instanceof ArtifactReaderFailure && cause.reason === "cancelled")
|
||||
)
|
||||
return new AnalysisCancelledError(OPERATION, { cause });
|
||||
return new AnalysisCancelledError(operation, { cause });
|
||||
if (cause instanceof DecoderDiscoveryBudgetError)
|
||||
return new AnalysisResourceConstraintError(
|
||||
operation,
|
||||
"memory",
|
||||
cause.message,
|
||||
{ line_budget: 65536 },
|
||||
{
|
||||
cause,
|
||||
...(observedOutput === undefined
|
||||
? {}
|
||||
: { capturedOutput: observedOutput }),
|
||||
},
|
||||
);
|
||||
const reason = cause instanceof Error ? cause.message : String(cause);
|
||||
if (cause instanceof OwnedCommandFailure)
|
||||
return this.#resources.commandFailure(cause, LIMITS, effectiveLimits);
|
||||
return this.#resources.commandFailure(
|
||||
cause,
|
||||
LIMITS,
|
||||
effectiveLimits,
|
||||
operation,
|
||||
);
|
||||
if (phase === "workspace") {
|
||||
const code =
|
||||
cause instanceof Error &&
|
||||
@@ -385,13 +455,13 @@ export class SigrokRecordingProvider implements SignalRecordingPort {
|
||||
: null;
|
||||
if (code === "ENOSPC" || code === "EDQUOT" || code === "EFBIG")
|
||||
return new AnalysisResourceConstraintError(
|
||||
OPERATION,
|
||||
operation,
|
||||
"file-size",
|
||||
`Private analysis workspace failed (${code}): ${reason}`,
|
||||
{ workspace_path: workspacePath, system_code: code },
|
||||
{ cause },
|
||||
);
|
||||
return new ProviderAdapterError(SIGROK_PROVIDER_IDENTITY.id, OPERATION, {
|
||||
return new ProviderAdapterError(SIGROK_PROVIDER_IDENTITY.id, operation, {
|
||||
cause,
|
||||
userMessage: `Cannot prepare the private analysis workspace: ${reason}`,
|
||||
diagnostics: {
|
||||
@@ -414,12 +484,12 @@ export class SigrokRecordingProvider implements SignalRecordingPort {
|
||||
["limit", "integrity", "path"].includes(cause.reason)
|
||||
)
|
||||
return new AnalysisArtifactChangedError(
|
||||
OPERATION,
|
||||
operation,
|
||||
path,
|
||||
`Post-run identity verification failed for ${path}: ${reason}`,
|
||||
detail,
|
||||
);
|
||||
return new ProviderAdapterError(SIGROK_PROVIDER_IDENTITY.id, OPERATION, {
|
||||
return new ProviderAdapterError(SIGROK_PROVIDER_IDENTITY.id, operation, {
|
||||
...detail,
|
||||
diagnostics: { stage: "integrity", resource_path: path, reason },
|
||||
});
|
||||
@@ -427,10 +497,13 @@ export class SigrokRecordingProvider implements SignalRecordingPort {
|
||||
if (phase === "configuration")
|
||||
return new AnalysisCapabilityUnavailableError(
|
||||
SIGROK_PROVIDER_IDENTITY.id,
|
||||
OPERATION,
|
||||
operation,
|
||||
reason,
|
||||
{
|
||||
cause,
|
||||
...(observedOutput === undefined
|
||||
? {}
|
||||
: { capturedOutput: observedOutput }),
|
||||
userMessage: `${reason} On Linux, configure sigrok-cli 0.7.2 through REA_SIGROK_COMMAND and util-linux prlimit through REA_SIGROK_PRLIMIT_COMMAND (default /usr/bin/prlimit).`,
|
||||
},
|
||||
);
|
||||
@@ -440,14 +513,14 @@ export class SigrokRecordingProvider implements SignalRecordingPort {
|
||||
cause.reason === "limit"
|
||||
)
|
||||
return new AnalysisResourceConstraintError(
|
||||
OPERATION,
|
||||
operation,
|
||||
"file-size",
|
||||
reason,
|
||||
{ input_bytes: LIMITS.input_bytes },
|
||||
{ cause },
|
||||
);
|
||||
if (cause instanceof ArtifactReaderFailure && cause.reason === "integrity")
|
||||
return new AnalysisArtifactChangedError(OPERATION, path, reason, {
|
||||
return new AnalysisArtifactChangedError(operation, path, reason, {
|
||||
cause,
|
||||
});
|
||||
if (
|
||||
@@ -456,13 +529,18 @@ export class SigrokRecordingProvider implements SignalRecordingPort {
|
||||
"code" in cause &&
|
||||
(cause.code === "EACCES" || cause.code === "EPERM")
|
||||
)
|
||||
return new AnalysisAccessDeniedError(OPERATION, path, cause.code, {
|
||||
return new AnalysisAccessDeniedError(operation, path, cause.code, {
|
||||
cause,
|
||||
});
|
||||
if (phase === "artifact")
|
||||
return new AnalysisInputError(OPERATION, { cause }, [
|
||||
return new AnalysisInputError(operation, { cause }, [
|
||||
{ path: ["path"], reason: "invalid_value", message: reason },
|
||||
]);
|
||||
return new AnalysisOutputError(OPERATION, reason, { cause });
|
||||
return new AnalysisOutputError(operation, reason, {
|
||||
cause,
|
||||
...(observedOutput === undefined
|
||||
? {}
|
||||
: { capturedOutput: observedOutput }),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import type { InspectSignalDecodersInput } from "../domain/signals/signalDecoders.js";
|
||||
|
||||
export class DecoderDiscoveryBudgetError extends Error {}
|
||||
|
||||
const copyText = (value: string): string =>
|
||||
Buffer.from(value, "utf16le").toString("utf16le");
|
||||
|
||||
/** Parse only the 0.7.2 catalog grammar; help remains literal producer text. */
|
||||
export const parseDecoderDiscovery = (
|
||||
text: string,
|
||||
input: InspectSignalDecodersInput,
|
||||
) => {
|
||||
// Bound record-object expansion before splitting the already byte-bounded output.
|
||||
// 65,536 records leaves an 8 MiB budget at 128 bytes of bookkeeping per record.
|
||||
let separators = 0;
|
||||
for (const character of text)
|
||||
if (character === "\n" && ++separators >= 65536)
|
||||
throw new DecoderDiscoveryBudgetError(
|
||||
"Decoder discovery exceeds the 65,536-line representation budget",
|
||||
);
|
||||
const lines = text.split(/\r?\n/u);
|
||||
if (lines.at(-1) === "") lines.pop();
|
||||
const query = input.query.toLowerCase();
|
||||
const decoders: { id: string; name: string }[] = [];
|
||||
const help: { line_number: number; text: string }[] = [];
|
||||
if (input.decoder === null) {
|
||||
const start = lines.indexOf("Supported protocol decoders:");
|
||||
if (start < 0) throw new Error("sigrok decoder catalog heading is missing");
|
||||
const seen = new Set<string>();
|
||||
for (const line of lines.slice(start + 1)) {
|
||||
if (line === "") continue;
|
||||
const match = /^ {2}([a-zA-Z0-9_+-]+) +(.+)$/u.exec(line);
|
||||
if (
|
||||
match?.[1] === undefined ||
|
||||
match[2] === undefined ||
|
||||
seen.has(match[1])
|
||||
)
|
||||
throw new Error("Malformed or duplicate sigrok decoder catalog record");
|
||||
seen.add(match[1]);
|
||||
decoders.push({ id: match[1], name: match[2] });
|
||||
}
|
||||
if (decoders.length === 0)
|
||||
throw new Error("sigrok returned an empty decoder catalog");
|
||||
} else {
|
||||
if (lines[0] !== `ID: ${input.decoder}`)
|
||||
throw new Error("Decoder help does not identify the selected decoder");
|
||||
lines.forEach((line, i) => help.push({ line_number: i + 1, text: line }));
|
||||
}
|
||||
const catalog = input.decoder === null;
|
||||
const matching = catalog
|
||||
? decoders.filter(({ id, name }) =>
|
||||
`${id} ${name}`.toLowerCase().includes(query),
|
||||
)
|
||||
: help.filter(({ text: line }) => line.toLowerCase().includes(query));
|
||||
const start = Math.min(input.offset, matching.length);
|
||||
const count = Math.min(
|
||||
input.limit ?? matching.length,
|
||||
matching.length - start,
|
||||
);
|
||||
// Keep retained pages independent of the complete producer-output allocation.
|
||||
const page = matching
|
||||
.slice(start, start + count)
|
||||
.map((record) =>
|
||||
"id" in record
|
||||
? { id: copyText(record.id), name: copyText(record.name) }
|
||||
: { line_number: record.line_number, text: copyText(record.text) },
|
||||
);
|
||||
return {
|
||||
decoders: catalog ? page : [],
|
||||
help_lines: catalog ? [] : page,
|
||||
output_window: {
|
||||
unit: catalog ? "decoders" : "help-lines",
|
||||
examined: catalog ? decoders.length : help.length,
|
||||
matching: matching.length,
|
||||
returned: page.length,
|
||||
has_more: start + count < matching.length,
|
||||
},
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user