mirror of
https://github.com/morluto/rea.git
synced 2026-11-18 12:42:20 +00:00
feat(signals): decode recordings with bounded sigrok output (#2339)
Decode caller-selected protocols from existing recordings through shared CLI/MCP Evidence. Page literal output lines after complete decoding; preserve explicit full output, source identity and failed cleanup ownership. Verified real sigrok-cli 0.7.2 workflows, published UART/SPI/I2C recordings, independent UART values, selector limits, SDK schemas and cleanup regressions. Co-authored-by: Olorinm <59321404+Olorinm@users.noreply.github.com> Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing)
This commit is contained in:
1 parent
5f79c852af
commit
91b8f587cd
50 files changed
+2715
-252
No files matched your search
@@ -44,6 +44,7 @@ type ToolAvailabilityReason = "available" | ToolUnavailabilityReason;
|
||||
type ProviderDescriptor = ProviderCapability;
|
||||
export type AvailabilityPolicy = {
|
||||
readonly packetCaptureEnabled?: boolean;
|
||||
readonly signalRecordingEnabled?: boolean;
|
||||
readonly wasmArtifactEnabled?: boolean;
|
||||
readonly evmInterfaceEnabled?: boolean;
|
||||
readonly processCaptureEnabled: boolean;
|
||||
@@ -404,6 +405,14 @@ 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")
|
||||
return policy.signalRecordingEnabled === true
|
||||
? { reason: "available", remediation: null }
|
||||
: {
|
||||
reason: "provider_missing",
|
||||
remediation:
|
||||
"On Linux, supply sigrok-cli 0.7.2 via absolute REA_SIGROK_COMMAND and util-linux prlimit (REA_SIGROK_PRLIMIT_COMMAND, default /usr/bin/prlimit). No active binary target or hardware is required; the tool is checked at execution.",
|
||||
};
|
||||
if (name === "inspect_wasm_artifact")
|
||||
return policy.wasmArtifactEnabled === true
|
||||
? { reason: "available", remediation: null }
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { isAbsolute } from "node:path";
|
||||
import type {
|
||||
AnalysisExecution,
|
||||
ExecutionOptions,
|
||||
} from "../AnalysisProvider.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import { createEvidence, type Evidence } from "../../domain/evidence.js";
|
||||
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
|
||||
import {
|
||||
decodeSignalRecordingInputSchema,
|
||||
signalRecordingSchema,
|
||||
type DecodeSignalRecordingInput,
|
||||
} from "../../domain/signals/signalRecording.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
|
||||
export interface SignalRecordingPort {
|
||||
/** Release per-call resources before returning, or retain failed cleanup for close/retry. */
|
||||
decode(
|
||||
input: DecodeSignalRecordingInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
/** One shared validation and Evidence owner for CLI and MCP. */
|
||||
export class SignalRecordingService {
|
||||
constructor(readonly provider: SignalRecordingPort) {}
|
||||
close(): Promise<void> {
|
||||
return this.provider.close();
|
||||
}
|
||||
async decode(
|
||||
raw: unknown,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
const operation = "decode_signal_recording";
|
||||
if (options?.signal?.aborted)
|
||||
return err(new AnalysisCancelledError(operation));
|
||||
const input = decodeSignalRecordingInputSchema.safeParse(raw);
|
||||
if (!input.success)
|
||||
return err(
|
||||
analysisInputErrorFromIssues(operation, input.error.issues, raw, {
|
||||
cause: input.error,
|
||||
}),
|
||||
);
|
||||
if (!isAbsolute(input.data.path))
|
||||
return err(
|
||||
new AnalysisInputError(operation, undefined, [
|
||||
{
|
||||
path: ["path"],
|
||||
reason: "invalid_format",
|
||||
message: "Expected an absolute local path.",
|
||||
},
|
||||
]),
|
||||
);
|
||||
const decoded = await this.provider.decode(input.data, options);
|
||||
if (!decoded.ok) return decoded;
|
||||
const execution = decoded.value;
|
||||
const report = signalRecordingSchema.safeParse(execution.result);
|
||||
if (
|
||||
!report.success ||
|
||||
report.data.artifact.path !== input.data.path ||
|
||||
execution.subject?.path !== input.data.path ||
|
||||
execution.subject.sha256 !== report.data.artifact.sha256 ||
|
||||
JSON.stringify(report.data.selection) !== JSON.stringify(input.data)
|
||||
)
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
operation,
|
||||
"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 options?.signal?.aborted
|
||||
? err(
|
||||
new AnalysisCancelledError(operation, {
|
||||
partialObservation: evidence,
|
||||
}),
|
||||
)
|
||||
: ok(evidence);
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,10 @@ import {
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import type { PacketCapturePort } from "../application/captures/PacketCaptureService.js";
|
||||
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
|
||||
import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
|
||||
import {
|
||||
ArtifactAnalysisResources,
|
||||
type ArtifactAnalysisRuntime,
|
||||
} from "../process/ArtifactAnalysisResources.js";
|
||||
import { readStableArtifact } from "../artifacts/readStableArtifact.js";
|
||||
import {
|
||||
AnalysisError,
|
||||
@@ -28,13 +31,9 @@ import {
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
AnalysisResourceConstraintError,
|
||||
AnalysisTimeoutError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
|
||||
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
|
||||
import {
|
||||
type InspectPacketCaptureInput,
|
||||
packetCaptureSchema,
|
||||
@@ -45,7 +44,6 @@ import {
|
||||
OwnedCommandFailure,
|
||||
} from "../process/OwnedCommand.js";
|
||||
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
|
||||
import type { ProviderProcessSupervisor } from "../process/ProviderProcess.js";
|
||||
|
||||
const OPERATION = "inspect_packet_capture";
|
||||
export const TSHARK_PROVIDER_IDENTITY = {
|
||||
@@ -62,129 +60,43 @@ const LIMITS = {
|
||||
file_bytes: 64 * 1024 * 1024,
|
||||
cpu_seconds: 30,
|
||||
} as const;
|
||||
type Runtime = Pick<PrivateRuntimeRoot, "path" | "close">;
|
||||
type Launcher = NonNullable<Parameters<typeof runOwnedCommand>[2]>["launcher"];
|
||||
|
||||
/** Inspect selected capture files only, retaining cleanup ownership across failures. */
|
||||
export class TsharkCaptureProvider implements PacketCapturePort {
|
||||
readonly #artifactResources = new ArtifactResourceScope();
|
||||
readonly #pending = new Map<Runtime, ProviderProcessSupervisor | undefined>();
|
||||
#tail: Promise<void> = Promise.resolve();
|
||||
#busy = false;
|
||||
#closed = false;
|
||||
readonly #resources: ArtifactAnalysisResources;
|
||||
constructor(
|
||||
readonly environment: Readonly<NodeJS.ProcessEnv> = process.env,
|
||||
readonly launcher?: Launcher,
|
||||
readonly createRuntime: () => Promise<Runtime> = () =>
|
||||
readonly createRuntime: () => Promise<ArtifactAnalysisRuntime> = () =>
|
||||
PrivateRuntimeRoot.create({ prefix: "rea-tshark-" }),
|
||||
readonly platform: NodeJS.Platform = process.platform,
|
||||
readonly readArtifact: typeof readStableArtifact = readStableArtifact,
|
||||
readonly readLimits: typeof readLinuxResourceLimits = readLinuxResourceLimits,
|
||||
) {}
|
||||
) {
|
||||
this.#resources = new ArtifactAnalysisResources(
|
||||
TSHARK_PROVIDER_IDENTITY.id,
|
||||
OPERATION,
|
||||
readArtifact,
|
||||
readLimits,
|
||||
{
|
||||
message:
|
||||
"A packet inspection is already active; retry after it completes.",
|
||||
details: { max_concurrent_inspections: 1 },
|
||||
},
|
||||
);
|
||||
}
|
||||
inspect(
|
||||
input: InspectPacketCaptureInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>> {
|
||||
if (this.#closed || options?.signal?.aborted)
|
||||
return Promise.resolve(err(new AnalysisCancelledError(OPERATION)));
|
||||
if (this.#busy)
|
||||
return Promise.resolve(
|
||||
err(
|
||||
new AnalysisResourceConstraintError(
|
||||
OPERATION,
|
||||
"capacity",
|
||||
"A packet inspection is already active; retry after it completes.",
|
||||
{ max_concurrent_inspections: 1 },
|
||||
),
|
||||
),
|
||||
);
|
||||
this.#busy = true;
|
||||
const work = this.#tail
|
||||
.then(() =>
|
||||
this.#artifactResources.run(() => this.#inspect(input, options)),
|
||||
)
|
||||
.catch((cause: unknown) =>
|
||||
err(
|
||||
this.#failure(
|
||||
cause,
|
||||
"artifact",
|
||||
input.path,
|
||||
null,
|
||||
undefined,
|
||||
undefined,
|
||||
),
|
||||
),
|
||||
)
|
||||
.finally(() => {
|
||||
this.#busy = false;
|
||||
});
|
||||
this.#tail = work.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
return this.#resources.run(
|
||||
() => this.#inspect(input, options),
|
||||
options?.signal,
|
||||
);
|
||||
return work;
|
||||
}
|
||||
close(): Promise<void> {
|
||||
this.#closed = true;
|
||||
const work = this.#tail.then(() => this.#closeResources());
|
||||
this.#tail = work.catch(() => undefined);
|
||||
return work;
|
||||
}
|
||||
async #closeResources(): Promise<void> {
|
||||
let descriptorFailure: AnalysisError | undefined;
|
||||
try {
|
||||
await this.#artifactResources.close();
|
||||
} catch (cause: unknown) {
|
||||
descriptorFailure = this.#failure(
|
||||
cause,
|
||||
"artifact",
|
||||
"TShark artifact descriptors",
|
||||
null,
|
||||
undefined,
|
||||
undefined,
|
||||
);
|
||||
}
|
||||
try {
|
||||
await this.#release();
|
||||
} catch (cause: unknown) {
|
||||
if (descriptorFailure !== undefined && cause instanceof AnalysisError)
|
||||
throw analysisErrorWithCleanupFailure(
|
||||
descriptorFailure,
|
||||
cause,
|
||||
OPERATION,
|
||||
);
|
||||
throw cause;
|
||||
}
|
||||
if (descriptorFailure !== undefined) throw descriptorFailure;
|
||||
}
|
||||
#read(path: string, maximumBytes: number, signal?: AbortSignal) {
|
||||
return this.readArtifact(
|
||||
path,
|
||||
maximumBytes,
|
||||
signal,
|
||||
undefined,
|
||||
this.#artifactResources,
|
||||
);
|
||||
}
|
||||
async #release(): Promise<void> {
|
||||
for (const [root, owner] of this.#pending) {
|
||||
try {
|
||||
if (owner !== undefined) {
|
||||
const stopped = await owner.stop();
|
||||
if (stopped.status === "incomplete") throw new Error(stopped.reason);
|
||||
this.#pending.set(root, undefined);
|
||||
}
|
||||
await root.close();
|
||||
this.#pending.delete(root);
|
||||
} catch (cause) {
|
||||
throw new ProviderCleanupError(
|
||||
TSHARK_PROVIDER_IDENTITY.id,
|
||||
[root.path],
|
||||
{ reason: String(cause) },
|
||||
{ operation: OPERATION, cause },
|
||||
);
|
||||
}
|
||||
}
|
||||
return this.#resources.close();
|
||||
}
|
||||
async #inspect(
|
||||
input: InspectPacketCaptureInput,
|
||||
@@ -199,11 +111,11 @@ export class TsharkCaptureProvider implements PacketCapturePort {
|
||||
let capturedOutput: AnalysisCapturedOutput | undefined;
|
||||
let resourcePath = input.path;
|
||||
let effectiveLimits: LinuxResourceLimits | undefined;
|
||||
let root: Runtime | undefined;
|
||||
let root: ArtifactAnalysisRuntime | undefined;
|
||||
let result: Result<AnalysisExecution, AnalysisError>;
|
||||
try {
|
||||
if (options?.signal?.aborted) throw new AnalysisCancelledError(OPERATION);
|
||||
await this.#release();
|
||||
await this.#resources.release();
|
||||
if (this.platform !== "linux")
|
||||
throw new Error(
|
||||
"Packet inspection requires Linux with util-linux prlimit and REA_TSHARK_COMMAND so expanded captures are processed under an enforced address-space limit.",
|
||||
@@ -213,19 +125,23 @@ export class TsharkCaptureProvider implements PacketCapturePort {
|
||||
throw new Error("Supply absolute REA_TSHARK_COMMAND for TShark 4.x.");
|
||||
const command = await realpath(configured);
|
||||
await access(command, constants.X_OK);
|
||||
const tool = await this.#read(command, 64 * 1024 * 1024, options?.signal);
|
||||
const tool = await this.#resources.read(
|
||||
command,
|
||||
64 * 1024 * 1024,
|
||||
options?.signal,
|
||||
);
|
||||
const configuredLimiter =
|
||||
this.environment.REA_TSHARK_PRLIMIT_COMMAND ?? "/usr/bin/prlimit";
|
||||
if (!isAbsolute(configuredLimiter))
|
||||
throw new Error("REA_TSHARK_PRLIMIT_COMMAND must be absolute.");
|
||||
const limiter = await realpath(configuredLimiter);
|
||||
await access(limiter, constants.X_OK);
|
||||
const limiterIdentity = await this.#read(
|
||||
const limiterIdentity = await this.#resources.read(
|
||||
limiter,
|
||||
64 * 1024 * 1024,
|
||||
options?.signal,
|
||||
);
|
||||
effectiveLimits = await this.readLimits(LIMITS, this.#artifactResources);
|
||||
effectiveLimits = await this.#resources.readLimits(LIMITS);
|
||||
const limitArguments = [
|
||||
`--as=${effectiveLimits.address_space_bytes}:${effectiveLimits.address_space_bytes}`,
|
||||
`--fsize=${effectiveLimits.file_bytes}:${effectiveLimits.file_bytes}`,
|
||||
@@ -236,7 +152,7 @@ export class TsharkCaptureProvider implements PacketCapturePort {
|
||||
];
|
||||
phase = "workspace";
|
||||
root = await this.createRuntime();
|
||||
this.#pending.set(root, undefined);
|
||||
this.#resources.retain(root, undefined);
|
||||
const snapshotPath = join(root.path, "capture");
|
||||
const configurationPath = join(root.path, "configuration");
|
||||
await mkdir(configurationPath, { mode: 0o700 });
|
||||
@@ -276,9 +192,12 @@ export class TsharkCaptureProvider implements PacketCapturePort {
|
||||
const previousPhase = phase;
|
||||
phase = "integrity";
|
||||
resourcePath = command;
|
||||
const current = await this.#read(command, 64 * 1024 * 1024);
|
||||
const current = await this.#resources.read(command, 64 * 1024 * 1024);
|
||||
resourcePath = limiter;
|
||||
const currentLimiter = await this.#read(limiter, 64 * 1024 * 1024);
|
||||
const currentLimiter = await this.#resources.read(
|
||||
limiter,
|
||||
64 * 1024 * 1024,
|
||||
);
|
||||
if (currentLimiter.sha256 !== limiterIdentity.sha256)
|
||||
throw new AnalysisArtifactChangedError(
|
||||
OPERATION,
|
||||
@@ -320,7 +239,7 @@ export class TsharkCaptureProvider implements PacketCapturePort {
|
||||
"Expected TShark 4.x; inspect the selected installation.",
|
||||
);
|
||||
phase = "artifact";
|
||||
const selected = await this.#read(
|
||||
const selected = await this.#resources.read(
|
||||
input.path,
|
||||
LIMITS.input_bytes,
|
||||
options?.signal,
|
||||
@@ -354,8 +273,8 @@ export class TsharkCaptureProvider implements PacketCapturePort {
|
||||
phase = "integrity";
|
||||
resourcePath = snapshotPath;
|
||||
if (
|
||||
(await this.#read(snapshotPath, LIMITS.input_bytes)).sha256 !==
|
||||
selected.sha256
|
||||
(await this.#resources.read(snapshotPath, LIMITS.input_bytes))
|
||||
.sha256 !== selected.sha256
|
||||
)
|
||||
throw new AnalysisArtifactChangedError(
|
||||
OPERATION,
|
||||
@@ -432,7 +351,7 @@ export class TsharkCaptureProvider implements PacketCapturePort {
|
||||
cause instanceof OwnedCommandFailure &&
|
||||
cause.cleanupOwner !== undefined
|
||||
)
|
||||
this.#pending.set(root, cause.cleanupOwner);
|
||||
this.#resources.retain(root, cause.cleanupOwner);
|
||||
result = err(
|
||||
this.#failure(
|
||||
cause,
|
||||
@@ -444,42 +363,16 @@ export class TsharkCaptureProvider implements PacketCapturePort {
|
||||
),
|
||||
);
|
||||
}
|
||||
try {
|
||||
await this.#release();
|
||||
} catch (cause) {
|
||||
const partialObservation = result.ok
|
||||
? createEvidence(
|
||||
result.value.subject ?? undefined,
|
||||
result.value.provider,
|
||||
{
|
||||
operation: OPERATION,
|
||||
parameters: input,
|
||||
result: result.value.result,
|
||||
confidence: "observed",
|
||||
locations: result.value.locations,
|
||||
limitations: result.value.limitations,
|
||||
},
|
||||
)
|
||||
: result.error.partialObservation;
|
||||
return err(
|
||||
new ProviderCleanupError(
|
||||
TSHARK_PROVIDER_IDENTITY.id,
|
||||
[...this.#pending.keys()].map((item) => item.path),
|
||||
{
|
||||
reason: String(cause),
|
||||
previous_error: result.ok
|
||||
? null
|
||||
: projectAnalysisError(result.error),
|
||||
},
|
||||
{
|
||||
operation: OPERATION,
|
||||
cause,
|
||||
...(partialObservation === undefined ? {} : { partialObservation }),
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
return result;
|
||||
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,
|
||||
}),
|
||||
);
|
||||
}
|
||||
#failure(
|
||||
cause: unknown,
|
||||
@@ -496,16 +389,10 @@ export class TsharkCaptureProvider implements PacketCapturePort {
|
||||
): AnalysisError {
|
||||
if (cause instanceof AnalysisError) return cause;
|
||||
if (cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined)
|
||||
return new ProviderCleanupError(
|
||||
TSHARK_PROVIDER_IDENTITY.id,
|
||||
cause.cleanup.resources,
|
||||
{
|
||||
reason: cause.cleanup.reason,
|
||||
...(observedOutput === undefined
|
||||
? {}
|
||||
: { captured_output: { ...observedOutput } }),
|
||||
},
|
||||
{ operation: OPERATION, cause },
|
||||
return this.#resources.cleanupFailure(
|
||||
cause.cleanup,
|
||||
cause,
|
||||
observedOutput,
|
||||
);
|
||||
if (
|
||||
(cause instanceof Error && cause.name === "AbortError") ||
|
||||
@@ -513,51 +400,8 @@ export class TsharkCaptureProvider implements PacketCapturePort {
|
||||
)
|
||||
return new AnalysisCancelledError(OPERATION, { cause });
|
||||
const reason = cause instanceof Error ? cause.message : String(cause);
|
||||
if (cause instanceof OwnedCommandFailure) {
|
||||
const capturedOutput =
|
||||
cause.snapshot === null
|
||||
? undefined
|
||||
: {
|
||||
stdout: cause.snapshot.stdout.text,
|
||||
stderr: cause.snapshot.stderr.text,
|
||||
truncated: cause.snapshot.diagnosticTruncated ?? false,
|
||||
exit_code: cause.snapshot.exitCode ?? null,
|
||||
signal: cause.snapshot.signal ?? null,
|
||||
};
|
||||
const detail = {
|
||||
cause,
|
||||
...(capturedOutput === undefined ? {} : { capturedOutput }),
|
||||
};
|
||||
if (cause.reason === "cancelled")
|
||||
return new AnalysisCancelledError(OPERATION, detail);
|
||||
if (cause.reason === "timeout")
|
||||
return new AnalysisTimeoutError(
|
||||
OPERATION,
|
||||
LIMITS.command_timeout_ms,
|
||||
detail,
|
||||
);
|
||||
if (cause.reason === "output-limit")
|
||||
return new AnalysisResourceConstraintError(
|
||||
OPERATION,
|
||||
"memory",
|
||||
reason,
|
||||
{ output_bytes: LIMITS.output_bytes },
|
||||
detail,
|
||||
);
|
||||
if (
|
||||
cause.reason === "process" &&
|
||||
(cause.snapshot?.signal === "SIGXFSZ" ||
|
||||
cause.snapshot?.signal === "SIGXCPU")
|
||||
)
|
||||
return new AnalysisResourceConstraintError(
|
||||
OPERATION,
|
||||
cause.snapshot.signal === "SIGXFSZ" ? "file-size" : "cpu",
|
||||
`Producer terminated with ${cause.snapshot.signal}; the signal's exact cause is not independently established.`,
|
||||
effectiveLimits === undefined ? null : { ...effectiveLimits },
|
||||
detail,
|
||||
);
|
||||
return new AnalysisOutputError(OPERATION, reason, detail);
|
||||
}
|
||||
if (cause instanceof OwnedCommandFailure)
|
||||
return this.#resources.commandFailure(cause, LIMITS, effectiveLimits);
|
||||
if (phase === "workspace") {
|
||||
const code =
|
||||
cause instanceof Error &&
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { registerCaptureCommands } from "./cli/captureCommands.js";
|
||||
import { registerSignalCommands } from "./cli/signalCommands.js";
|
||||
import { registerWasmCommands } from "./cli/wasmCommands.js";
|
||||
import { snapshotEnvironment } from "./process/snapshotEnvironment.js";
|
||||
import { createDirectAnalysis } from "./composition/directAnalysis.js";
|
||||
@@ -96,6 +97,7 @@ export const createCli = (
|
||||
registerUtilityCommands(cli, logger, environment, analysis);
|
||||
registerWasmCommands(cli, logger, environment);
|
||||
registerCaptureCommands(cli, logger, environment);
|
||||
registerSignalCommands(cli, logger, environment);
|
||||
registerEvmCommands(cli, logger, environment);
|
||||
registerGoCommands(cli, logger);
|
||||
registerSqliteCommands(cli, logger, environment);
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { z } from "incur";
|
||||
import type { SignalRecordingService } from "../application/signals/SignalRecordingService.js";
|
||||
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
|
||||
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
||||
import { resolve } from "node:path";
|
||||
import { createSignalRecordingService } from "../composition/signals.js";
|
||||
import {
|
||||
signalRecordingOptionsSchema,
|
||||
signalRecordingSelectorBudgetIssue,
|
||||
withinSignalRecordingSelectorBudget,
|
||||
} from "../domain/signals/signalRecording.js";
|
||||
import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
import { logCliCommand } from "../cliLogging.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import type { Logger } from "pino";
|
||||
import type { CliInstance } from "./types.js";
|
||||
import { withCommandCancellation } from "./commandCancellation.js";
|
||||
export const registerSignalCommands = (
|
||||
cli: CliInstance,
|
||||
logger: Logger,
|
||||
environment: Readonly<NodeJS.ProcessEnv>,
|
||||
service: Pick<
|
||||
SignalRecordingService,
|
||||
"decode" | "close"
|
||||
> = createSignalRecordingService(environment),
|
||||
): void => {
|
||||
cli.command(CLI_COMMANDS.decodeSignalRecording, {
|
||||
description:
|
||||
"Decode an existing signal recording with caller-supplied sigrok",
|
||||
args: z.object({ path: z.string().describe("Local signal recording") }),
|
||||
options: z
|
||||
.object({
|
||||
...signalRecordingOptionsSchema.shape,
|
||||
line_limit: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.optional()
|
||||
.describe("Returned output lines per page; default 50"),
|
||||
all_lines: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.describe(
|
||||
"Return all remaining output lines instead of a bounded page",
|
||||
),
|
||||
})
|
||||
.superRefine((options, context) => {
|
||||
if (options.all_lines && options.line_limit !== undefined)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["all_lines"],
|
||||
message: "all_lines and line_limit are mutually exclusive",
|
||||
});
|
||||
})
|
||||
.refine(
|
||||
withinSignalRecordingSelectorBudget,
|
||||
signalRecordingSelectorBudgetIssue,
|
||||
),
|
||||
run: ({ args, options: { all_lines, ...options } }) =>
|
||||
withCommandCancellation((signal) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.decodeSignalRecording, async () => {
|
||||
const result = await service.decode(
|
||||
{
|
||||
...options,
|
||||
...(all_lines ? { line_limit: null } : {}),
|
||||
path: resolve(args.path),
|
||||
},
|
||||
{ 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);
|
||||
}),
|
||||
),
|
||||
});
|
||||
};
|
||||
@@ -1,6 +1,7 @@
|
||||
/** Canonical names used by every one-shot CLI command registration. */
|
||||
export const CLI_COMMANDS = Object.freeze({
|
||||
inspectPacketCapture: "inspect-packet-capture",
|
||||
decodeSignalRecording: "decode-signal-recording",
|
||||
inspectWasmArtifact: "inspect-wasm-artifact",
|
||||
inspectSqliteDatabase: "inspect-sqlite-database",
|
||||
inspectEvmInterface: "inspect-evm-interface",
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import { SignalRecordingService } from "../application/signals/SignalRecordingService.js";
|
||||
import { SigrokRecordingProvider } from "../signals/SigrokRecordingProvider.js";
|
||||
export const createSignalRecordingService = (
|
||||
environment: Readonly<NodeJS.ProcessEnv> = process.env,
|
||||
): SignalRecordingService =>
|
||||
new SignalRecordingService(new SigrokRecordingProvider(environment));
|
||||
@@ -0,0 +1,29 @@
|
||||
import {
|
||||
decodeSignalRecordingInputSchema,
|
||||
signalRecordingSchema,
|
||||
} from "../../domain/signals/signalRecording.js";
|
||||
import type { ToolContract } from "../toolContractTypes.js";
|
||||
import { toolContractMetadata } from "../toolEffects.js";
|
||||
import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js";
|
||||
export const SIGNAL_TOOL_CONTRACTS = [
|
||||
{
|
||||
name: "decode_signal_recording",
|
||||
...toolContractMetadata("decode_signal_recording"),
|
||||
kind: "artifact-provider",
|
||||
description:
|
||||
"Decode an existing local logic/signal recording on Linux with sigrok-cli 0.7.2 and util-linux prlimit. Supply decoder stack, channels and options explicitly; optionally select input format and annotation classes. Return 50 literal output lines by default, with line_offset/line_limit paging; line_limit:null requests all remaining lines. Output windows count display lines, not annotations or samples, and do not shorten decoding. Preserve selected text, sample ranges, stderr, source/tool identity and coverage inline. Configure absolute REA_SIGROK_COMMAND. File-only analysis; no hardware acquisition or device communication. Empty output does not prove absence of traffic.",
|
||||
inputSchema: decodeSignalRecordingInputSchema,
|
||||
outputSchema: evidenceResultOf(signalRecordingSchema),
|
||||
examples: [
|
||||
{
|
||||
title: "Decode recorded UART RX bytes",
|
||||
input: {
|
||||
path: "/artifacts/uart.vcd",
|
||||
input_format: "vcd",
|
||||
decoders: "uart:rx=RX:baudrate=9600",
|
||||
annotations: "uart=rx-data",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
] as const satisfies readonly ToolContract[];
|
||||
@@ -1,4 +1,5 @@
|
||||
import { CAPTURE_TOOL_CONTRACTS } from "./captures/captureToolContracts.js";
|
||||
import { SIGNAL_TOOL_CONTRACTS } from "./signals/signalToolContracts.js";
|
||||
import { WASM_TOOL_CONTRACTS } from "./wasm/wasmToolContracts.js";
|
||||
import { EVM_TOOL_CONTRACTS } from "./evm/evmToolContracts.js";
|
||||
import { GO_TOOL_CONTRACTS } from "./go/goToolContracts.js";
|
||||
@@ -41,6 +42,7 @@ export const TOOL_CONTRACTS = [
|
||||
...WASM_TOOL_CONTRACTS,
|
||||
...SQLITE_TOOL_CONTRACTS,
|
||||
...CAPTURE_TOOL_CONTRACTS,
|
||||
...SIGNAL_TOOL_CONTRACTS,
|
||||
...MANAGED_TOOL_CONTRACTS,
|
||||
...ANDROID_TOOL_CONTRACTS,
|
||||
...APKTOOL_TOOL_CONTRACTS,
|
||||
|
||||
@@ -64,6 +64,11 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
launchesProcess: true,
|
||||
writesFilesystem: true,
|
||||
}),
|
||||
decode_signal_recording: effects({
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
writesFilesystem: true,
|
||||
}),
|
||||
inspect_wasm_artifact: effects({
|
||||
mutatesSession: true,
|
||||
writesFilesystem: true,
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { windowAnnotationText } from "./annotationTextWindow.js";
|
||||
|
||||
it("preserves line terminators, blank lines and literal display text", () => {
|
||||
const text = "1-2 uart-1: 界\r\n\ntext without a sample range\nlast";
|
||||
expect(windowAnnotationText(text, 1, 2)).toEqual({
|
||||
annotations_text: "\ntext without a sample range\n",
|
||||
output_window: { total_lines: 4, returned_lines: 2, has_more: true },
|
||||
});
|
||||
expect(windowAnnotationText(text, 0, null).annotations_text).toBe(text);
|
||||
expect(windowAnnotationText(text, 3, 2)).toEqual({
|
||||
annotations_text: "last",
|
||||
output_window: { total_lines: 4, returned_lines: 1, has_more: false },
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["", "\n", "line\n", "line"])(
|
||||
"does not invent a trailing line or normalize %j",
|
||||
(text) => {
|
||||
expect(windowAnnotationText(text, 0, null)).toEqual({
|
||||
annotations_text: text,
|
||||
output_window: {
|
||||
total_lines: text === "" ? 0 : 1,
|
||||
returned_lines: text === "" ? 0 : 1,
|
||||
has_more: false,
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("returns an empty covered window beyond the last line without unsafe arithmetic", () => {
|
||||
expect(
|
||||
windowAnnotationText(
|
||||
"one\ntwo",
|
||||
Number.MAX_SAFE_INTEGER,
|
||||
Number.MAX_SAFE_INTEGER,
|
||||
),
|
||||
).toEqual({
|
||||
annotations_text: "",
|
||||
output_window: { total_lines: 2, returned_lines: 0, has_more: false },
|
||||
});
|
||||
});
|
||||
|
||||
it("does not replace source UTF-16 code units when copying a partial window", () => {
|
||||
expect(
|
||||
windowAnnotationText("first\n\ud800\nlast", 1, 1).annotations_text,
|
||||
).toBe("\ud800\n");
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
/** Page literal LF-separated display lines without interpreting annotation semantics. */
|
||||
export const windowAnnotationText = (
|
||||
text: string,
|
||||
offset: number,
|
||||
limit: number | null,
|
||||
) => {
|
||||
let total = 0;
|
||||
let returned = 0;
|
||||
let start = text.length;
|
||||
let end = text.length;
|
||||
for (let from = 0; from < text.length;) {
|
||||
const newline = text.indexOf("\n", from);
|
||||
const next = newline < 0 ? text.length : newline + 1;
|
||||
if (total === offset) start = from;
|
||||
if (total >= offset && (limit === null || returned < limit)) {
|
||||
end = next;
|
||||
returned++;
|
||||
}
|
||||
total++;
|
||||
from = next;
|
||||
}
|
||||
return {
|
||||
// Copy partial windows so retained Evidence does not retain the full producer
|
||||
// string. UTF-16 preserves every source code unit, including lone surrogates.
|
||||
annotations_text:
|
||||
start === 0 && end === text.length
|
||||
? text
|
||||
: Buffer.from(text.slice(start, end), "utf16le").toString("utf16le"),
|
||||
output_window: {
|
||||
total_lines: total,
|
||||
returned_lines: returned,
|
||||
has_more: Math.min(offset, total) + returned < total,
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,148 @@
|
||||
import { z } from "zod";
|
||||
import { localPathStringSchema } from "../localPath.js";
|
||||
import { windowAnnotationText } from "./annotationTextWindow.js";
|
||||
|
||||
// These strings are single sigrok arguments, never shell fragments.
|
||||
const selection = z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(8192)
|
||||
.refine((value) => !value.includes("\0"), "NUL is not an argument character");
|
||||
const signalInputShape = z.strictObject({
|
||||
path: localPathStringSchema.describe("Absolute local recording path"),
|
||||
decoders: selection.describe(
|
||||
"sigrok decoder stack, options and channel assignments, e.g. uart:rx=RX:baudrate=9600",
|
||||
),
|
||||
input_format: selection
|
||||
.nullable()
|
||||
.default(null)
|
||||
.describe(
|
||||
"Explicit sigrok input format and options; omitted means autodetection",
|
||||
),
|
||||
annotations: selection
|
||||
.nullable()
|
||||
.default(null)
|
||||
.describe("Optional annotation selection, e.g. uart=rx-data"),
|
||||
line_offset: z
|
||||
.number()
|
||||
.int()
|
||||
.nonnegative()
|
||||
.default(0)
|
||||
.describe("Skip this many literal LF-separated output lines; default 0"),
|
||||
line_limit: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.nullable()
|
||||
.default(50)
|
||||
.describe(
|
||||
"Return at most this many output lines; default 50. Null explicitly returns all remaining lines within producer limits. Lines are not annotation counts.",
|
||||
),
|
||||
});
|
||||
export const withinSignalRecordingSelectorBudget = (input: {
|
||||
decoders: string;
|
||||
input_format: string | null;
|
||||
annotations: string | null;
|
||||
}): boolean => {
|
||||
let bytes = 0;
|
||||
for (const [value, prefix] of [
|
||||
[input.decoders, "--protocol-decoders="],
|
||||
[input.input_format, "--input-format="],
|
||||
[input.annotations, "--protocol-decoder-annotations="],
|
||||
] as const)
|
||||
if (value !== null)
|
||||
bytes +=
|
||||
Buffer.byteLength(prefix, "utf8") +
|
||||
Buffer.byteLength(value, "utf8") +
|
||||
9;
|
||||
return bytes <= 32768;
|
||||
};
|
||||
export const signalRecordingSelectorBudgetIssue = {
|
||||
message:
|
||||
"Signal selectors exceed the 32 KiB encoded argument budget; reduce decoder, format or annotation selections.",
|
||||
};
|
||||
export const decodeSignalRecordingInputSchema = signalInputShape.refine(
|
||||
withinSignalRecordingSelectorBudget,
|
||||
signalRecordingSelectorBudgetIssue,
|
||||
);
|
||||
export const signalRecordingOptionsSchema = signalInputShape
|
||||
.omit({ path: true })
|
||||
.refine(
|
||||
withinSignalRecordingSelectorBudget,
|
||||
signalRecordingSelectorBudgetIssue,
|
||||
);
|
||||
export type DecodeSignalRecordingInput = z.infer<
|
||||
typeof decodeSignalRecordingInputSchema
|
||||
>;
|
||||
|
||||
export const signalRecordingSchema = z
|
||||
.strictObject({
|
||||
artifact: z.strictObject({
|
||||
path: z.string(),
|
||||
sha256: z.string().regex(/^[a-f0-9]{64}$/),
|
||||
bytes: z.number().int().nonnegative(),
|
||||
}),
|
||||
selection: decodeSignalRecordingInputSchema,
|
||||
annotations_text: z
|
||||
.string()
|
||||
.describe(
|
||||
"Selected literal lines of sigrok display output with unchanged sample ranges and line endings; not a lossless binary protocol representation",
|
||||
),
|
||||
output_window: z.strictObject({
|
||||
total_lines: z
|
||||
.number()
|
||||
.int()
|
||||
.nonnegative()
|
||||
.describe(
|
||||
"Literal LF-separated lines in completed producer output, not annotation or sample counts",
|
||||
),
|
||||
returned_lines: z.number().int().nonnegative(),
|
||||
has_more: z.boolean(),
|
||||
}),
|
||||
diagnostics: z.string(),
|
||||
tool: z.strictObject({
|
||||
configured_path: z.string(),
|
||||
path: z.string(),
|
||||
sha256: z.string().regex(/^[a-f0-9]{64}$/),
|
||||
version_banner: z.string(),
|
||||
version_diagnostics: z.string(),
|
||||
arguments: z.array(z.string()),
|
||||
}),
|
||||
resource_limiter: z.strictObject({
|
||||
configured_path: z.string(),
|
||||
path: z.string(),
|
||||
sha256: z.string().regex(/^[a-f0-9]{64}$/),
|
||||
arguments: z.array(z.string()),
|
||||
}),
|
||||
limits: z.strictObject({
|
||||
input_bytes: z.number().int().positive(),
|
||||
output_bytes: z.number().int().positive(),
|
||||
command_timeout_ms: z.number().int().positive(),
|
||||
address_space_bytes: z.number().int().nonnegative(),
|
||||
file_bytes: z.number().int().nonnegative(),
|
||||
cpu_seconds: z.number().int().nonnegative(),
|
||||
}),
|
||||
hardware_acquisition: z.literal("not-performed"),
|
||||
})
|
||||
.superRefine((report, context) => {
|
||||
const remaining = Math.max(
|
||||
report.output_window.total_lines - report.selection.line_offset,
|
||||
0,
|
||||
);
|
||||
const expected =
|
||||
report.selection.line_limit === null
|
||||
? remaining
|
||||
: Math.min(remaining, report.selection.line_limit);
|
||||
if (
|
||||
report.output_window.returned_lines !== expected ||
|
||||
windowAnnotationText(report.annotations_text, 0, null).output_window
|
||||
.total_lines !== expected ||
|
||||
report.output_window.has_more !== remaining > expected
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["output_window"],
|
||||
message:
|
||||
"Output text and window must agree with examined lines and selected offset/limit",
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,272 @@
|
||||
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
|
||||
import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
|
||||
import { readStableArtifact } from "../artifacts/readStableArtifact.js";
|
||||
import {
|
||||
AnalysisError,
|
||||
type AnalysisCapturedOutput,
|
||||
type AnalysisPartialObservation,
|
||||
} from "../domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisResourceConstraintError,
|
||||
AnalysisOutputError,
|
||||
AnalysisTimeoutError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
|
||||
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { err, type Result } from "../domain/result.js";
|
||||
import {
|
||||
readLinuxResourceLimits,
|
||||
type LinuxResourceLimits,
|
||||
} from "./LinuxResourceLimits.js";
|
||||
import type { PrivateRuntimeRoot } from "./PrivateRuntimeRoot.js";
|
||||
import type { ProviderProcessSupervisor } from "./ProviderProcess.js";
|
||||
import { OwnedCommandFailure } from "./OwnedCommand.js";
|
||||
|
||||
export type ArtifactAnalysisRuntime = Pick<
|
||||
PrivateRuntimeRoot,
|
||||
"path" | "close"
|
||||
>;
|
||||
|
||||
/** Own admission, artifact descriptors, producer cleanup and private workspaces together. */
|
||||
export class ArtifactAnalysisResources {
|
||||
readonly #artifacts = new ArtifactResourceScope();
|
||||
readonly #pending = new Map<
|
||||
ArtifactAnalysisRuntime,
|
||||
ProviderProcessSupervisor | undefined
|
||||
>();
|
||||
#tail: Promise<void> = Promise.resolve();
|
||||
#busy = false;
|
||||
#closed = false;
|
||||
|
||||
constructor(
|
||||
readonly providerId: string,
|
||||
readonly operation: string,
|
||||
readonly readArtifact: typeof readStableArtifact,
|
||||
readonly readKernelLimits: typeof readLinuxResourceLimits,
|
||||
readonly capacity: {
|
||||
readonly message: string;
|
||||
readonly details: Readonly<Record<string, JsonValue>>;
|
||||
},
|
||||
) {}
|
||||
|
||||
run<T>(
|
||||
work: () => Promise<Result<T, AnalysisError>>,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Result<T, AnalysisError>> {
|
||||
if (this.#closed || signal?.aborted)
|
||||
return Promise.resolve(err(new AnalysisCancelledError(this.operation)));
|
||||
if (this.#busy)
|
||||
return Promise.resolve(
|
||||
err(
|
||||
new AnalysisResourceConstraintError(
|
||||
this.operation,
|
||||
"capacity",
|
||||
this.capacity.message,
|
||||
this.capacity.details,
|
||||
),
|
||||
),
|
||||
);
|
||||
this.#busy = true;
|
||||
const running = this.#tail
|
||||
.then(() => this.#artifacts.run(work))
|
||||
.catch((cause: unknown) => err(this.#artifactFailure(cause)))
|
||||
.finally(() => {
|
||||
this.#busy = false;
|
||||
});
|
||||
this.#tail = running.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
return running;
|
||||
}
|
||||
|
||||
read(path: string, maximumBytes: number, signal?: AbortSignal) {
|
||||
return this.readArtifact(
|
||||
path,
|
||||
maximumBytes,
|
||||
signal,
|
||||
undefined,
|
||||
this.#artifacts,
|
||||
);
|
||||
}
|
||||
|
||||
readLimits(limits: LinuxResourceLimits): Promise<LinuxResourceLimits> {
|
||||
return this.readKernelLimits(limits, this.#artifacts);
|
||||
}
|
||||
|
||||
retain(
|
||||
root: ArtifactAnalysisRuntime,
|
||||
owner?: ProviderProcessSupervisor,
|
||||
): void {
|
||||
this.#pending.set(root, owner);
|
||||
}
|
||||
|
||||
get pendingPaths(): readonly string[] {
|
||||
return [...this.#pending.keys()].map((root) => root.path);
|
||||
}
|
||||
|
||||
async release(): Promise<void> {
|
||||
for (const [root, owner] of this.#pending) {
|
||||
try {
|
||||
if (owner !== undefined) {
|
||||
const stopped = await owner.stop();
|
||||
if (stopped.status === "incomplete") throw new Error(stopped.reason);
|
||||
this.#pending.set(root, undefined);
|
||||
}
|
||||
await root.close();
|
||||
this.#pending.delete(root);
|
||||
} catch (cause: unknown) {
|
||||
throw new ProviderCleanupError(
|
||||
this.providerId,
|
||||
[root.path],
|
||||
{ reason: String(cause) },
|
||||
{ operation: this.operation, cause },
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cleanupFailure(
|
||||
observation: NonNullable<ArtifactReaderFailure["cleanup"]>,
|
||||
cause: unknown,
|
||||
capturedOutput?: AnalysisCapturedOutput,
|
||||
): ProviderCleanupError {
|
||||
return new ProviderCleanupError(
|
||||
this.providerId,
|
||||
observation.resources,
|
||||
{
|
||||
reason: observation.reason,
|
||||
...(capturedOutput === undefined
|
||||
? {}
|
||||
: { captured_output: { ...capturedOutput } }),
|
||||
},
|
||||
{ operation: this.operation, cause },
|
||||
);
|
||||
}
|
||||
|
||||
commandFailure(
|
||||
cause: OwnedCommandFailure,
|
||||
limits: {
|
||||
readonly command_timeout_ms: number;
|
||||
readonly output_bytes: number;
|
||||
},
|
||||
effectiveLimits: LinuxResourceLimits | undefined,
|
||||
): AnalysisError {
|
||||
const capturedOutput =
|
||||
cause.snapshot === null
|
||||
? undefined
|
||||
: {
|
||||
stdout: cause.snapshot.stdout.text,
|
||||
stderr: cause.snapshot.stderr.text,
|
||||
truncated: cause.snapshot.diagnosticTruncated ?? false,
|
||||
exit_code: cause.snapshot.exitCode ?? null,
|
||||
signal: cause.snapshot.signal ?? null,
|
||||
};
|
||||
const detail = {
|
||||
cause,
|
||||
...(capturedOutput === undefined ? {} : { capturedOutput }),
|
||||
};
|
||||
if (cause.reason === "cancelled")
|
||||
return new AnalysisCancelledError(this.operation, detail);
|
||||
if (cause.reason === "timeout")
|
||||
return new AnalysisTimeoutError(
|
||||
this.operation,
|
||||
limits.command_timeout_ms,
|
||||
detail,
|
||||
);
|
||||
if (cause.reason === "output-limit")
|
||||
return new AnalysisResourceConstraintError(
|
||||
this.operation,
|
||||
"memory",
|
||||
cause.message,
|
||||
{ output_bytes: limits.output_bytes },
|
||||
detail,
|
||||
);
|
||||
if (
|
||||
cause.reason === "process" &&
|
||||
(cause.snapshot?.signal === "SIGXFSZ" ||
|
||||
cause.snapshot?.signal === "SIGXCPU")
|
||||
)
|
||||
return new AnalysisResourceConstraintError(
|
||||
this.operation,
|
||||
cause.snapshot.signal === "SIGXFSZ" ? "file-size" : "cpu",
|
||||
`Producer terminated with ${cause.snapshot.signal}; the signal's exact cause is not independently established.`,
|
||||
effectiveLimits === undefined ? null : { ...effectiveLimits },
|
||||
detail,
|
||||
);
|
||||
return new AnalysisOutputError(this.operation, cause.message, detail);
|
||||
}
|
||||
|
||||
async finish<T>(
|
||||
result: Result<T, AnalysisError>,
|
||||
observation: (value: T) => AnalysisPartialObservation,
|
||||
): Promise<Result<T, AnalysisError>> {
|
||||
try {
|
||||
await this.release();
|
||||
return result;
|
||||
} catch (cause: unknown) {
|
||||
const partialObservation = result.ok
|
||||
? observation(result.value)
|
||||
: result.error.partialObservation;
|
||||
return err(
|
||||
new ProviderCleanupError(
|
||||
this.providerId,
|
||||
this.pendingPaths,
|
||||
{
|
||||
reason: String(cause),
|
||||
previous_error: result.ok
|
||||
? null
|
||||
: projectAnalysisError(result.error),
|
||||
},
|
||||
{
|
||||
operation: this.operation,
|
||||
cause,
|
||||
...(partialObservation === undefined ? {} : { partialObservation }),
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
close(): Promise<void> {
|
||||
this.#closed = true;
|
||||
const work = this.#tail.then(() => this.#closeResources());
|
||||
this.#tail = work.catch(() => undefined);
|
||||
return work;
|
||||
}
|
||||
|
||||
async #closeResources(): Promise<void> {
|
||||
let descriptorFailure: AnalysisError | undefined;
|
||||
try {
|
||||
await this.#artifacts.close();
|
||||
} catch (cause: unknown) {
|
||||
descriptorFailure = this.#artifactFailure(cause);
|
||||
}
|
||||
try {
|
||||
await this.release();
|
||||
} catch (cause: unknown) {
|
||||
if (descriptorFailure !== undefined && cause instanceof AnalysisError)
|
||||
throw analysisErrorWithCleanupFailure(
|
||||
descriptorFailure,
|
||||
cause,
|
||||
this.operation,
|
||||
);
|
||||
throw cause;
|
||||
}
|
||||
if (descriptorFailure !== undefined) throw descriptorFailure;
|
||||
}
|
||||
|
||||
#artifactFailure(cause: unknown): AnalysisError {
|
||||
if (cause instanceof AnalysisError) return cause;
|
||||
if (cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined)
|
||||
return this.cleanupFailure(cause.cleanup, cause);
|
||||
return new ProviderAdapterError(this.providerId, this.operation, {
|
||||
cause,
|
||||
diagnostics: { stage: "artifact-resources", reason: String(cause) },
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
import type { PacketCaptureService } from "../application/captures/PacketCaptureService.js";
|
||||
import { createPacketCaptureService } from "../composition/captures.js";
|
||||
import { registerCaptureTools } from "./registerCaptureTools.js";
|
||||
import type { SignalRecordingService } from "../application/signals/SignalRecordingService.js";
|
||||
import { createSignalRecordingService } from "../composition/signals.js";
|
||||
import { registerSignalTools } from "./registerSignalTools.js";
|
||||
import type { WasmArtifactService } from "../application/wasm/WasmArtifactService.js";
|
||||
import { wasmArtifactModule } from "../composition/wasm.js";
|
||||
import { registerWasmTools } from "./registerWasmTools.js";
|
||||
@@ -123,6 +126,7 @@ export interface CreateServerOptions {
|
||||
readonly environment?: Readonly<NodeJS.ProcessEnv>;
|
||||
readonly delivery?: ToolResultDelivery;
|
||||
readonly packetCapture?: PacketCaptureService;
|
||||
readonly signalRecording?: SignalRecordingService;
|
||||
readonly wasmArtifact?: WasmArtifactService;
|
||||
readonly evmInterface?: EvmInterfaceService;
|
||||
readonly sqliteDatabase?: SqliteDatabaseService;
|
||||
@@ -168,6 +172,9 @@ const installSessionToolAvailability = (
|
||||
packetCaptureEnabled:
|
||||
options.packetCapture !== undefined ||
|
||||
(linux && isAbsolute(environment.REA_TSHARK_COMMAND ?? "")),
|
||||
signalRecordingEnabled:
|
||||
options.signalRecording !== undefined ||
|
||||
(linux && isAbsolute(environment.REA_SIGROK_COMMAND ?? "")),
|
||||
wasmArtifactEnabled:
|
||||
options.wasmArtifact !== undefined ||
|
||||
isAbsolute(environment.REA_WABT_BIN_DIRECTORY ?? ""),
|
||||
@@ -301,6 +308,8 @@ export const createServer = (
|
||||
);
|
||||
const packetCapture =
|
||||
options.packetCapture ?? createPacketCaptureService(environment);
|
||||
const signalRecording =
|
||||
options.signalRecording ?? createSignalRecordingService(environment);
|
||||
const apktool =
|
||||
options.apktoolAnalysis ??
|
||||
createApktoolResourceAnalysisProvider(environment);
|
||||
@@ -314,6 +323,7 @@ export const createServer = (
|
||||
fridaInstrumentation.closeAll(),
|
||||
wasmArtifact.close(),
|
||||
packetCapture.close(),
|
||||
signalRecording.close(),
|
||||
apktool.close(),
|
||||
jeb.close(),
|
||||
adbDevice.close(),
|
||||
@@ -401,6 +411,13 @@ export const createServer = (
|
||||
recordEvidence,
|
||||
analysisAdmission,
|
||||
);
|
||||
registerSignalTools(
|
||||
server,
|
||||
signalRecording,
|
||||
toolLogger,
|
||||
recordEvidence,
|
||||
analysisAdmission,
|
||||
);
|
||||
registerConfiguredAnalysisTools(
|
||||
toolContext,
|
||||
android,
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
|
||||
import type { SignalRecordingService } from "../application/signals/SignalRecordingService.js";
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import { toolContract } from "../contracts/toolContracts.js";
|
||||
import type { Logger } from "pino";
|
||||
import type { WithAdmittedAnalysis } from "./analysisAdmission.js";
|
||||
import { createEvidenceToolHandler } from "./contractToolHandler.js";
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
|
||||
/** Bind the named signal contract through shared admission and retained Evidence delivery. */
|
||||
export const registerSignalTools = (
|
||||
server: EvidenceMcpServer,
|
||||
service: SignalRecordingService,
|
||||
logger: Logger,
|
||||
recordEvidence?: EvidenceWriter["recordEvidence"],
|
||||
withAdmittedAnalysis?: WithAdmittedAnalysis,
|
||||
): void => {
|
||||
const contract = toolContract("decode_signal_recording");
|
||||
const handler = createEvidenceToolHandler(
|
||||
server,
|
||||
(input, options) => service.decode(input, options),
|
||||
logger,
|
||||
recordEvidence,
|
||||
withAdmittedAnalysis,
|
||||
);
|
||||
server.registerTool(
|
||||
contract.name,
|
||||
toolRegistrationOptions(contract),
|
||||
handler(contract),
|
||||
);
|
||||
};
|
||||
@@ -9,6 +9,7 @@ export interface SessionAvailabilityDefaults {
|
||||
readonly optionalFeatures?: Pick<
|
||||
AvailabilityPolicy,
|
||||
| "packetCaptureEnabled"
|
||||
| "signalRecordingEnabled"
|
||||
| "wasmArtifactEnabled"
|
||||
| "evmInterfaceEnabled"
|
||||
| "browserObservationEnabled"
|
||||
@@ -35,6 +36,8 @@ export const sessionAvailabilityPolicy = (
|
||||
(() => ({
|
||||
packetCaptureEnabled:
|
||||
defaults.optionalFeatures?.packetCaptureEnabled ?? false,
|
||||
signalRecordingEnabled:
|
||||
defaults.optionalFeatures?.signalRecordingEnabled ?? false,
|
||||
wasmArtifactEnabled:
|
||||
defaults.optionalFeatures?.wasmArtifactEnabled ?? false,
|
||||
evmInterfaceEnabled:
|
||||
|
||||
@@ -0,0 +1,468 @@
|
||||
import {
|
||||
readLinuxResourceLimits,
|
||||
type LinuxResourceLimits,
|
||||
} from "../process/LinuxResourceLimits.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { constants } from "node:fs";
|
||||
import { access, realpath, writeFile } from "node:fs/promises";
|
||||
import { isAbsolute, join } from "node:path";
|
||||
import {
|
||||
createAnalysisExecution,
|
||||
type AnalysisExecution,
|
||||
type ExecutionOptions,
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import type { SignalRecordingPort } from "../application/signals/SignalRecordingService.js";
|
||||
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
|
||||
import {
|
||||
ArtifactAnalysisResources,
|
||||
type ArtifactAnalysisRuntime,
|
||||
} from "../process/ArtifactAnalysisResources.js";
|
||||
import { readStableArtifact } from "../artifacts/readStableArtifact.js";
|
||||
import {
|
||||
AnalysisError,
|
||||
type AnalysisCapturedOutput,
|
||||
} from "../domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisAccessDeniedError,
|
||||
AnalysisArtifactChangedError,
|
||||
AnalysisCancelledError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
AnalysisResourceConstraintError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
|
||||
import { windowAnnotationText } from "../domain/signals/annotationTextWindow.js";
|
||||
import {
|
||||
type DecodeSignalRecordingInput,
|
||||
signalRecordingSchema,
|
||||
} from "../domain/signals/signalRecording.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
runOwnedCommand,
|
||||
OwnedCommandFailure,
|
||||
} from "../process/OwnedCommand.js";
|
||||
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
|
||||
|
||||
const OPERATION = "decode_signal_recording";
|
||||
export const SIGROK_PROVIDER_IDENTITY = {
|
||||
id: "sigrok-recording",
|
||||
name: "REA sigrok recording adapter",
|
||||
version: "sigrok-cli@0.7.2",
|
||||
} as const;
|
||||
// Bound the resident input copy and retained text before allocation/collection.
|
||||
const LIMITS = {
|
||||
input_bytes: 32 * 1024 * 1024,
|
||||
output_bytes: 4 * 1024 * 1024,
|
||||
command_timeout_ms: 30_000,
|
||||
address_space_bytes: 1024 * 1024 * 1024,
|
||||
file_bytes: 64 * 1024 * 1024,
|
||||
cpu_seconds: 30,
|
||||
} as const;
|
||||
type Launcher = NonNullable<Parameters<typeof runOwnedCommand>[2]>["launcher"];
|
||||
|
||||
/** Decode selected recordings only, retaining cleanup ownership across failures. */
|
||||
export class SigrokRecordingProvider implements SignalRecordingPort {
|
||||
readonly #resources: ArtifactAnalysisResources;
|
||||
constructor(
|
||||
readonly environment: Readonly<NodeJS.ProcessEnv> = process.env,
|
||||
readonly launcher?: Launcher,
|
||||
readonly createRuntime: () => Promise<ArtifactAnalysisRuntime> = () =>
|
||||
PrivateRuntimeRoot.create({ prefix: "rea-sigrok-" }),
|
||||
readonly platform: NodeJS.Platform = process.platform,
|
||||
readonly readArtifact: typeof readStableArtifact = readStableArtifact,
|
||||
readonly readLimits: typeof readLinuxResourceLimits = readLinuxResourceLimits,
|
||||
) {
|
||||
this.#resources = new ArtifactAnalysisResources(
|
||||
SIGROK_PROVIDER_IDENTITY.id,
|
||||
OPERATION,
|
||||
readArtifact,
|
||||
readLimits,
|
||||
{
|
||||
message:
|
||||
"A signal decoding operation is already active; retry after it completes.",
|
||||
details: { max_concurrent_decodes: 1 },
|
||||
},
|
||||
);
|
||||
}
|
||||
decode(
|
||||
input: DecodeSignalRecordingInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>> {
|
||||
return this.#resources.run(
|
||||
() => this.#decode(input, options),
|
||||
options?.signal,
|
||||
);
|
||||
}
|
||||
close(): Promise<void> {
|
||||
return this.#resources.close();
|
||||
}
|
||||
async #decode(
|
||||
input: DecodeSignalRecordingInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>> {
|
||||
let phase:
|
||||
| "configuration"
|
||||
| "artifact"
|
||||
| "workspace"
|
||||
| "producer"
|
||||
| "integrity" = "configuration";
|
||||
let capturedOutput: AnalysisCapturedOutput | undefined;
|
||||
let resourcePath = input.path;
|
||||
let effectiveLimits: LinuxResourceLimits | undefined;
|
||||
let root: ArtifactAnalysisRuntime | undefined;
|
||||
let result: Result<AnalysisExecution, AnalysisError>;
|
||||
try {
|
||||
if (options?.signal?.aborted) throw new AnalysisCancelledError(OPERATION);
|
||||
await this.#resources.release();
|
||||
if (this.platform !== "linux")
|
||||
throw new Error(
|
||||
"Signal decoding requires Linux with util-linux prlimit and REA_SIGROK_COMMAND so expanded recordings are processed under an enforced address-space limit.",
|
||||
);
|
||||
const configured = this.environment.REA_SIGROK_COMMAND ?? "";
|
||||
if (!isAbsolute(configured))
|
||||
throw new Error(
|
||||
"Supply absolute REA_SIGROK_COMMAND for sigrok-cli 0.7.2 with libsigrokdecode.",
|
||||
);
|
||||
const command = await realpath(configured);
|
||||
await access(command, constants.X_OK);
|
||||
const tool = await this.#resources.read(
|
||||
command,
|
||||
64 * 1024 * 1024,
|
||||
options?.signal,
|
||||
);
|
||||
const configuredLimiter =
|
||||
this.environment.REA_SIGROK_PRLIMIT_COMMAND ?? "/usr/bin/prlimit";
|
||||
if (!isAbsolute(configuredLimiter))
|
||||
throw new Error("REA_SIGROK_PRLIMIT_COMMAND must be absolute.");
|
||||
const limiter = await realpath(configuredLimiter);
|
||||
await access(limiter, constants.X_OK);
|
||||
const limiterIdentity = await this.#resources.read(
|
||||
limiter,
|
||||
64 * 1024 * 1024,
|
||||
options?.signal,
|
||||
);
|
||||
effectiveLimits = await this.#resources.readLimits(LIMITS);
|
||||
const limitArguments = [
|
||||
`--as=${effectiveLimits.address_space_bytes}:${effectiveLimits.address_space_bytes}`,
|
||||
`--fsize=${effectiveLimits.file_bytes}:${effectiveLimits.file_bytes}`,
|
||||
`--cpu=${effectiveLimits.cpu_seconds}:${effectiveLimits.cpu_seconds}`,
|
||||
"--core=0:0",
|
||||
"--",
|
||||
command,
|
||||
];
|
||||
phase = "workspace";
|
||||
root = await this.createRuntime();
|
||||
this.#resources.retain(root, undefined);
|
||||
const snapshotPath = join(root.path, "recording");
|
||||
const execute = async (args: readonly string[]) => {
|
||||
const output = await runOwnedCommand(
|
||||
{
|
||||
command: limiter,
|
||||
arguments: [...limitArguments, ...args],
|
||||
...(root === undefined ? {} : { cwd: root.path }),
|
||||
expectedCommand: null,
|
||||
runId: `rea-sigrok-${randomUUID()}`,
|
||||
hostEnvironment: this.environment,
|
||||
},
|
||||
{
|
||||
timeoutMs: LIMITS.command_timeout_ms,
|
||||
diagnosticBytes: LIMITS.output_bytes,
|
||||
acceptNonZeroExit: true,
|
||||
},
|
||||
{
|
||||
...(options?.signal === undefined
|
||||
? {}
|
||||
: { signal: options.signal }),
|
||||
...(this.launcher === undefined ? {} : { launcher: this.launcher }),
|
||||
},
|
||||
);
|
||||
capturedOutput = {
|
||||
stdout: output.stdout.text,
|
||||
stderr: output.stderr.text,
|
||||
truncated: output.diagnosticTruncated ?? false,
|
||||
exit_code: output.exitCode ?? null,
|
||||
signal: output.signal ?? null,
|
||||
};
|
||||
// Finish bounded integrity checks after output; service handles late cancellation with Evidence.
|
||||
const previousPhase = phase;
|
||||
phase = "integrity";
|
||||
resourcePath = command;
|
||||
const current = await this.#resources.read(command, 64 * 1024 * 1024);
|
||||
resourcePath = limiter;
|
||||
const currentLimiter = await this.#resources.read(
|
||||
limiter,
|
||||
64 * 1024 * 1024,
|
||||
);
|
||||
if (currentLimiter.sha256 !== limiterIdentity.sha256)
|
||||
throw new AnalysisArtifactChangedError(
|
||||
OPERATION,
|
||||
limiter,
|
||||
"Configured resource limiter changed during analysis.",
|
||||
{ capturedOutput },
|
||||
);
|
||||
if (current.sha256 !== tool.sha256)
|
||||
throw new AnalysisArtifactChangedError(
|
||||
OPERATION,
|
||||
command,
|
||||
"Configured decoder executable changed during analysis.",
|
||||
{ capturedOutput },
|
||||
);
|
||||
phase = previousPhase;
|
||||
resourcePath = input.path;
|
||||
if (output.exitCode !== 0)
|
||||
throw new ProviderAdapterError(
|
||||
SIGROK_PROVIDER_IDENTITY.id,
|
||||
OPERATION,
|
||||
{
|
||||
diagnostics: {
|
||||
exit_code: output.exitCode ?? null,
|
||||
stdout: output.stdout.text,
|
||||
stderr: output.stderr.text,
|
||||
},
|
||||
},
|
||||
);
|
||||
return output;
|
||||
};
|
||||
phase = "configuration";
|
||||
const version = await execute(["--version"]);
|
||||
if (
|
||||
!/^sigrok-cli 0\.7\.2(?:\r?\n|$)/u.test(version.stdout.text) ||
|
||||
!version.stdout.text.includes("libsigrokdecode")
|
||||
)
|
||||
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,
|
||||
tool: {
|
||||
configured_path: configured,
|
||||
path: command,
|
||||
sha256: tool.sha256,
|
||||
version_banner: version.stdout.text,
|
||||
version_diagnostics: version.stderr.text,
|
||||
arguments: args,
|
||||
},
|
||||
resource_limiter: {
|
||||
configured_path: configuredLimiter,
|
||||
path: limiter,
|
||||
sha256: limiterIdentity.sha256,
|
||||
arguments: limitArguments,
|
||||
},
|
||||
limits: { ...LIMITS, ...effectiveLimits },
|
||||
hardware_acquisition: "not-performed",
|
||||
});
|
||||
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);
|
||||
result = err(
|
||||
this.#failure(
|
||||
cause,
|
||||
phase,
|
||||
resourcePath,
|
||||
root?.path ?? null,
|
||||
effectiveLimits,
|
||||
capturedOutput,
|
||||
),
|
||||
);
|
||||
}
|
||||
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,
|
||||
}),
|
||||
);
|
||||
}
|
||||
#failure(
|
||||
cause: unknown,
|
||||
phase:
|
||||
| "configuration"
|
||||
| "artifact"
|
||||
| "workspace"
|
||||
| "producer"
|
||||
| "integrity",
|
||||
path: string,
|
||||
workspacePath: string | null,
|
||||
effectiveLimits: LinuxResourceLimits | undefined,
|
||||
observedOutput: AnalysisCapturedOutput | undefined,
|
||||
): AnalysisError {
|
||||
if (cause instanceof AnalysisError) return cause;
|
||||
if (cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined)
|
||||
return this.#resources.cleanupFailure(
|
||||
cause.cleanup,
|
||||
cause,
|
||||
observedOutput,
|
||||
);
|
||||
if (
|
||||
(cause instanceof Error && cause.name === "AbortError") ||
|
||||
(cause instanceof ArtifactReaderFailure && cause.reason === "cancelled")
|
||||
)
|
||||
return new AnalysisCancelledError(OPERATION, { cause });
|
||||
const reason = cause instanceof Error ? cause.message : String(cause);
|
||||
if (cause instanceof OwnedCommandFailure)
|
||||
return this.#resources.commandFailure(cause, LIMITS, effectiveLimits);
|
||||
if (phase === "workspace") {
|
||||
const code =
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
typeof cause.code === "string"
|
||||
? cause.code
|
||||
: null;
|
||||
if (code === "ENOSPC" || code === "EDQUOT" || code === "EFBIG")
|
||||
return new AnalysisResourceConstraintError(
|
||||
OPERATION,
|
||||
"file-size",
|
||||
`Private analysis workspace failed (${code}): ${reason}`,
|
||||
{ workspace_path: workspacePath, system_code: code },
|
||||
{ cause },
|
||||
);
|
||||
return new ProviderAdapterError(SIGROK_PROVIDER_IDENTITY.id, OPERATION, {
|
||||
cause,
|
||||
userMessage: `Cannot prepare the private analysis workspace: ${reason}`,
|
||||
diagnostics: {
|
||||
stage: "workspace",
|
||||
workspace_path: workspacePath,
|
||||
system_code: code,
|
||||
reason,
|
||||
},
|
||||
});
|
||||
}
|
||||
if (phase === "integrity") {
|
||||
const detail = {
|
||||
cause,
|
||||
...(observedOutput === undefined
|
||||
? {}
|
||||
: { capturedOutput: observedOutput }),
|
||||
};
|
||||
if (
|
||||
cause instanceof ArtifactReaderFailure &&
|
||||
["limit", "integrity", "path"].includes(cause.reason)
|
||||
)
|
||||
return new AnalysisArtifactChangedError(
|
||||
OPERATION,
|
||||
path,
|
||||
`Post-run identity verification failed for ${path}: ${reason}`,
|
||||
detail,
|
||||
);
|
||||
return new ProviderAdapterError(SIGROK_PROVIDER_IDENTITY.id, OPERATION, {
|
||||
...detail,
|
||||
diagnostics: { stage: "integrity", resource_path: path, reason },
|
||||
});
|
||||
}
|
||||
if (phase === "configuration")
|
||||
return new AnalysisCapabilityUnavailableError(
|
||||
SIGROK_PROVIDER_IDENTITY.id,
|
||||
OPERATION,
|
||||
reason,
|
||||
{
|
||||
cause,
|
||||
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).`,
|
||||
},
|
||||
);
|
||||
if (
|
||||
phase === "artifact" &&
|
||||
cause instanceof ArtifactReaderFailure &&
|
||||
cause.reason === "limit"
|
||||
)
|
||||
return new AnalysisResourceConstraintError(
|
||||
OPERATION,
|
||||
"file-size",
|
||||
reason,
|
||||
{ input_bytes: LIMITS.input_bytes },
|
||||
{ cause },
|
||||
);
|
||||
if (cause instanceof ArtifactReaderFailure && cause.reason === "integrity")
|
||||
return new AnalysisArtifactChangedError(OPERATION, path, reason, {
|
||||
cause,
|
||||
});
|
||||
if (
|
||||
phase === "artifact" &&
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
(cause.code === "EACCES" || cause.code === "EPERM")
|
||||
)
|
||||
return new AnalysisAccessDeniedError(OPERATION, path, cause.code, {
|
||||
cause,
|
||||
});
|
||||
if (phase === "artifact")
|
||||
return new AnalysisInputError(OPERATION, { cause }, [
|
||||
{ path: ["path"], reason: "invalid_value", message: reason },
|
||||
]);
|
||||
return new AnalysisOutputError(OPERATION, reason, { cause });
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user