feat(process): add direct replay machine runner
This commit is contained in:
@@ -51,6 +51,7 @@ export const CLI_COMMANDS = Object.freeze({
|
||||
traceApplicationFeature: "trace-application-feature",
|
||||
compareApplicationVersions: "compare-application-versions",
|
||||
compareJavaScriptExportShapes: "compare-javascript-export-shapes",
|
||||
runReplayMachine: "run-replay-machine",
|
||||
runControlledReplay: "run-controlled-replay",
|
||||
prepareNodeCharacterization: "prepare-node-characterization",
|
||||
executeNodeCharacterization: "execute-node-characterization",
|
||||
|
||||
@@ -7,12 +7,20 @@ import {
|
||||
import { logCliCommand } from "./cliLogging.js";
|
||||
import type { Logger } from "./logger.js";
|
||||
import { CLI_COMMANDS } from "./cliCommandNames.js";
|
||||
import { parseCliJsonInput } from "./cliJsonInput.js";
|
||||
import {
|
||||
replayMachineRunInputSchema,
|
||||
runReplayMachine,
|
||||
} from "./domain/replayMachineRun.js";
|
||||
import { AnalysisInputError, projectAnalysisError } from "./domain/errors.js";
|
||||
import { projectInputIssues } from "./domain/inputIssueProjection.js";
|
||||
|
||||
/** Register Process Capture v4 one-shot commands through shared application services. */
|
||||
export const registerProcessCommands = (
|
||||
cli: ReturnType<typeof Cli.create>,
|
||||
logger: Logger,
|
||||
): void => {
|
||||
registerReplayMachineCommand(cli, logger);
|
||||
cli.command(CLI_COMMANDS.captureProcess, {
|
||||
description: "Capture one approved Process Capture v4 JSON scenario",
|
||||
args: z.object({ scenario: z.string().describe("Scenario JSON path") }),
|
||||
@@ -33,3 +41,39 @@ export const registerProcessCommands = (
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
const registerReplayMachineCommand = (
|
||||
cli: ReturnType<typeof Cli.create>,
|
||||
logger: Logger,
|
||||
): void => {
|
||||
cli.command(CLI_COMMANDS.runReplayMachine, {
|
||||
description:
|
||||
"Run ordered protocol events directly through a finite replay machine",
|
||||
args: z.object({
|
||||
inputJson: z.string().describe("Inline replay JSON or JSON file path"),
|
||||
}),
|
||||
run: ({ args }) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.runReplayMachine, async () => {
|
||||
const input = await parseCliJsonInput(
|
||||
args.inputJson,
|
||||
CLI_COMMANDS.runReplayMachine,
|
||||
);
|
||||
if (!input.ok) return input.error;
|
||||
const parsed = replayMachineRunInputSchema.safeParse(input.value);
|
||||
return parsed.success
|
||||
? runReplayMachine(parsed.data)
|
||||
: {
|
||||
error: "Process command failed",
|
||||
...projectAnalysisError(
|
||||
new AnalysisInputError(
|
||||
CLI_COMMANDS.runReplayMachine,
|
||||
{
|
||||
cause: parsed.error,
|
||||
},
|
||||
projectInputIssues(parsed.error.issues, input.value),
|
||||
),
|
||||
),
|
||||
};
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { jsonObjectSchema } from "../domain/jsonValue.js";
|
||||
|
||||
/** Minimal login callback accepted by the direct replay-machine contract. */
|
||||
export const REPLAY_MACHINE_RUN_EXAMPLE = jsonObjectSchema.parse({
|
||||
machine: {
|
||||
initial_state: "waiting",
|
||||
states: [{ name: "waiting" }, { name: "complete", terminal: true }],
|
||||
transitions: [
|
||||
{
|
||||
id: "accept_callback",
|
||||
from: "waiting",
|
||||
to: "complete",
|
||||
trigger: { protocol: "http", method: "POST", path: "/callback" },
|
||||
captures: [
|
||||
{
|
||||
variable: "token",
|
||||
value: { source: "request_json", path: ["token"] },
|
||||
sensitive: true,
|
||||
},
|
||||
],
|
||||
actions: [{ type: "http_response", status: 204, body: "" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 1,
|
||||
},
|
||||
events: [
|
||||
{
|
||||
protocol: "http",
|
||||
connection: "not_applicable",
|
||||
at_ms: 0,
|
||||
method: "POST",
|
||||
path: "/callback",
|
||||
headers: {},
|
||||
body: '{"token":"opaque"}',
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import { UNKNOWN_CONTRACT_EXAMPLES } from "./unknownContractExamples.js";
|
||||
import { ARTIFACT_COMPARISON_EXAMPLE } from "./artifactComparisonExample.js";
|
||||
import { FUNCTION_COMPARISON_EXAMPLE } from "./functionComparisonExample.js";
|
||||
import { INVESTIGATION_EXAMPLES } from "./investigationExamples.js";
|
||||
import { REPLAY_MACHINE_RUN_EXAMPLE } from "./replayMachineExample.js";
|
||||
|
||||
/** Canonical examples for contracts whose required inputs have no defaults. */
|
||||
export const TOOL_EXAMPLE_OVERRIDES: Readonly<
|
||||
@@ -39,6 +40,7 @@ export const TOOL_EXAMPLE_OVERRIDES: Readonly<
|
||||
executable: "/usr/bin/true",
|
||||
working_directory: "/tmp",
|
||||
},
|
||||
run_replay_machine: REPLAY_MACHINE_RUN_EXAMPLE,
|
||||
compare_process_captures: {
|
||||
left_evidence_id: `ev_${"0".repeat(64)}`,
|
||||
right_evidence_id: `ev_${"1".repeat(64)}`,
|
||||
|
||||
@@ -12,6 +12,7 @@ import { changedBehaviorInputSchema } from "../domain/changedBehavior.js";
|
||||
import { callPathInputSchema } from "../domain/callPath.js";
|
||||
import { staticRuntimeCorrelationInputSchema } from "../domain/staticRuntimeCorrelation.js";
|
||||
import { reconstructionVerificationInputSchema } from "../domain/reconstructionVerification.js";
|
||||
import { replayMachineRunInputSchema } from "../domain/replayMachineRun.js";
|
||||
|
||||
import { enhancedInputSchemas } from "./enhancedInputs.js";
|
||||
import {
|
||||
@@ -497,6 +498,11 @@ export const SESSION_TOOL_CONTRACTS = [
|
||||
"Revalidate the current residual-unknown head against live bundled evidence, exact authority/confidence/environment requirements, and revision integrity. Withdrawn and out-of-scope dispositions are not truth claims.",
|
||||
verifyUnknownResolutionInputSchema,
|
||||
),
|
||||
session(
|
||||
"run_replay_machine",
|
||||
"Evaluate ordered HTTP and WebSocket events directly against one validated finite replay machine without opening sockets or launching a target. Returns every decision, a capture-value-free transition journal, one redacted action table entry per used transition, captured aliases, final state, and exact configured and consumed limits.",
|
||||
replayMachineRunInputSchema,
|
||||
),
|
||||
] as const satisfies readonly ToolContract[];
|
||||
|
||||
/** Complete ordered public inventory used by registration and verification. */
|
||||
|
||||
@@ -117,6 +117,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
trace_application_feature: evidence,
|
||||
compare_application_versions: evidence,
|
||||
compare_javascript_export_shapes: evidence,
|
||||
run_replay_machine: effects(),
|
||||
run_controlled_replay: effects({
|
||||
mutatesSession: true,
|
||||
writesFilesystem: true,
|
||||
|
||||
@@ -35,6 +35,7 @@ import { changedBehaviorResultSchema } from "../domain/changedBehavior.js";
|
||||
import { callPathResultSchema } from "../domain/callPath.js";
|
||||
import { staticRuntimeCorrelationResultSchema } from "../domain/staticRuntimeCorrelation.js";
|
||||
import { reconstructionVerificationResultSchema } from "../domain/reconstructionVerification.js";
|
||||
import { replayMachineRunOutputSchema } from "../domain/replayMachineRun.js";
|
||||
import { analysisErrorProjectionSchema } from "./errorSchemas.js";
|
||||
import {
|
||||
addressList,
|
||||
@@ -365,4 +366,5 @@ export const sessionOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
|
||||
unknown: residualUnknownSchema,
|
||||
}),
|
||||
),
|
||||
run_replay_machine: lifecycleResultOf(replayMachineRunOutputSchema),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { replayMachineSchema, type ReplayMachine } from "./replayMachine.js";
|
||||
import {
|
||||
replayMachineEventSchema,
|
||||
ReplayMachineRuntime,
|
||||
} from "./replayMachineRuntime.js";
|
||||
|
||||
const refusalOutcomeSchema = z.enum([
|
||||
"unmatched",
|
||||
"invalid_state",
|
||||
"guard_failed",
|
||||
"transition_exhausted",
|
||||
"invalid_capture",
|
||||
"unexpected_reconnect",
|
||||
"limit_exhausted",
|
||||
]);
|
||||
|
||||
const MAX_DIRECT_REPLAY_EVENTS = 10_000;
|
||||
const MAX_DIRECT_REPLAY_ACTION_BYTES = 4 * 1_024 * 1_024;
|
||||
const MAX_DIRECT_REPLAY_ACTION_FIELDS = 1_024;
|
||||
const MAX_DIRECT_REPLAY_SENSITIVE_CAPTURES = 1_024;
|
||||
|
||||
const actionFieldCount = (machine: ReplayMachine): number =>
|
||||
machine.transitions.reduce(
|
||||
(total, transition) =>
|
||||
total +
|
||||
transition.actions.reduce(
|
||||
(fields, action) =>
|
||||
fields +
|
||||
(action.type === "http_response"
|
||||
? Object.keys(action.headers).length + 1
|
||||
: action.type === "websocket_send"
|
||||
? 1
|
||||
: 0),
|
||||
0,
|
||||
),
|
||||
0,
|
||||
);
|
||||
|
||||
const maximumSensitiveCapturesPerEvent = (machine: ReplayMachine): number =>
|
||||
Math.max(
|
||||
0,
|
||||
...machine.transitions.map(
|
||||
({ captures }) => captures.filter(({ sensitive }) => sensitive).length,
|
||||
),
|
||||
);
|
||||
|
||||
/** Complete declarative input for one direct replay-machine run. */
|
||||
export const replayMachineRunInputSchema = z
|
||||
.strictObject({
|
||||
machine: replayMachineSchema,
|
||||
events: z.array(replayMachineEventSchema).max(MAX_DIRECT_REPLAY_EVENTS),
|
||||
})
|
||||
.superRefine(({ machine, events }, context) => {
|
||||
const actionBytes = Buffer.byteLength(
|
||||
JSON.stringify(
|
||||
machine.transitions.map(({ id, actions }) => ({ id, actions })),
|
||||
),
|
||||
);
|
||||
if (actionBytes > MAX_DIRECT_REPLAY_ACTION_BYTES)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["machine", "transitions"],
|
||||
message: "direct replay actions exceed the 4 MiB output boundary",
|
||||
input: machine.transitions,
|
||||
});
|
||||
if (actionFieldCount(machine) > MAX_DIRECT_REPLAY_ACTION_FIELDS)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["machine", "transitions"],
|
||||
message: "direct replay actions exceed the 1,024-field output boundary",
|
||||
input: machine.transitions,
|
||||
});
|
||||
if (
|
||||
maximumSensitiveCapturesPerEvent(machine) * events.length >
|
||||
MAX_DIRECT_REPLAY_SENSITIVE_CAPTURES
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["events"],
|
||||
message:
|
||||
"direct replay events exceed the 1,024 sensitive-capture operation boundary",
|
||||
input: events,
|
||||
});
|
||||
});
|
||||
|
||||
const replayMachineRunDecisionSchema = z.strictObject({
|
||||
event_sequence: z.number().int().nonnegative(),
|
||||
outcome: z.union([z.literal("matched"), refusalOutcomeSchema]),
|
||||
transition_sequence: z.number().int().nonnegative().nullable(),
|
||||
});
|
||||
|
||||
const replayRunActionSchema = z.discriminatedUnion("type", [
|
||||
z.strictObject({
|
||||
type: z.literal("http_response"),
|
||||
status: z.number().int().min(100).max(599),
|
||||
headers: z.record(
|
||||
z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(256)
|
||||
.regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u),
|
||||
z.string().max(8_192),
|
||||
),
|
||||
body: z.string().max(1_000_000),
|
||||
}),
|
||||
z.strictObject({
|
||||
type: z.literal("websocket_send"),
|
||||
data: z.string().max(1_000_000),
|
||||
}),
|
||||
z.strictObject({ type: z.literal("disconnect") }),
|
||||
z.strictObject({
|
||||
type: z.literal("delay"),
|
||||
duration_ms: z.number().int().nonnegative().max(30_000),
|
||||
}),
|
||||
]);
|
||||
|
||||
const replayRunIdentifierSchema = z
|
||||
.string()
|
||||
.regex(/^[A-Za-z][A-Za-z0-9_-]{0,63}$/u);
|
||||
|
||||
const replayMachineRunJournalEntrySchema = z.strictObject({
|
||||
sequence: z.number().int().nonnegative(),
|
||||
at_ms: z.number().int().nonnegative(),
|
||||
transition_id: replayRunIdentifierSchema,
|
||||
state_before: replayRunIdentifierSchema,
|
||||
state_after: replayRunIdentifierSchema,
|
||||
captured_aliases: z
|
||||
.array(
|
||||
z.strictObject({
|
||||
name: replayRunIdentifierSchema,
|
||||
sensitive: z.boolean(),
|
||||
}),
|
||||
)
|
||||
.max(32),
|
||||
});
|
||||
|
||||
/** Capture-value-free result of directly evaluating a finite replay machine. */
|
||||
export const replayMachineRunOutputSchema = z.strictObject({
|
||||
schema_version: z.literal(1),
|
||||
initial_state: replayRunIdentifierSchema,
|
||||
final_state: replayRunIdentifierSchema,
|
||||
terminal: z.boolean(),
|
||||
decisions: z
|
||||
.array(replayMachineRunDecisionSchema)
|
||||
.max(MAX_DIRECT_REPLAY_EVENTS),
|
||||
transition_journal: z
|
||||
.array(replayMachineRunJournalEntrySchema)
|
||||
.max(MAX_DIRECT_REPLAY_EVENTS),
|
||||
transition_actions: z
|
||||
.array(
|
||||
z.strictObject({
|
||||
transition_id: replayRunIdentifierSchema,
|
||||
actions: z.array(replayRunActionSchema).max(32),
|
||||
}),
|
||||
)
|
||||
.max(2_000),
|
||||
limits: z.strictObject({
|
||||
configured: z.strictObject({
|
||||
transitions: z.number().int().positive(),
|
||||
connections: z.number().int().positive(),
|
||||
messages: z.number().int().positive(),
|
||||
bytes: z.number().int().positive(),
|
||||
duration_ms: z.number().int().positive(),
|
||||
}),
|
||||
usage: z.strictObject({
|
||||
offered_events: z.number().int().nonnegative(),
|
||||
admitted_events: z.number().int().nonnegative(),
|
||||
transitions: z.number().int().nonnegative(),
|
||||
connections: z.number().int().nonnegative(),
|
||||
messages: z.number().int().nonnegative(),
|
||||
bytes: z.number().int().nonnegative(),
|
||||
last_at_ms: z.number().int().nonnegative(),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
|
||||
export type ReplayMachineRunInput = z.infer<typeof replayMachineRunInputSchema>;
|
||||
export type ReplayMachineRunOutput = z.infer<
|
||||
typeof replayMachineRunOutputSchema
|
||||
>;
|
||||
|
||||
type ReplayAction = ReplayMachine["transitions"][number]["actions"][number];
|
||||
|
||||
const redactAction = (
|
||||
runtime: ReplayMachineRuntime,
|
||||
action: ReplayAction,
|
||||
): ReplayAction => {
|
||||
switch (action.type) {
|
||||
case "http_response":
|
||||
return {
|
||||
...action,
|
||||
headers: Object.fromEntries(
|
||||
Object.entries(action.headers).map(([name, value]) => [
|
||||
name,
|
||||
runtime.redactField(value),
|
||||
]),
|
||||
),
|
||||
body: runtime.redactField(action.body),
|
||||
};
|
||||
case "websocket_send":
|
||||
return { ...action, data: runtime.redactField(action.data) };
|
||||
case "delay":
|
||||
case "disconnect":
|
||||
return action;
|
||||
}
|
||||
};
|
||||
|
||||
/** Evaluate every supplied event in order without opening sockets or processes. */
|
||||
export const runReplayMachine = (
|
||||
input: ReplayMachineRunInput,
|
||||
): ReplayMachineRunOutput => {
|
||||
const runtime = new ReplayMachineRuntime(input.machine);
|
||||
const decisions: ReplayMachineRunOutput["decisions"] = [];
|
||||
const transitionJournal: ReplayMachineRunOutput["transition_journal"] = [];
|
||||
const usedTransitionIds = new Set<string>();
|
||||
|
||||
for (const [eventSequence, event] of input.events.entries()) {
|
||||
const decision = runtime.dispatch(event);
|
||||
decisions.push({
|
||||
event_sequence: eventSequence,
|
||||
outcome: decision.outcome,
|
||||
transition_sequence: decision.transition?.sequence ?? null,
|
||||
});
|
||||
if (decision.outcome !== "matched") continue;
|
||||
usedTransitionIds.add(decision.transition.transition_id);
|
||||
const definition = input.machine.transitions.find(
|
||||
({ id }) => id === decision.transition.transition_id,
|
||||
);
|
||||
if (definition === undefined)
|
||||
throw new TypeError("Replay runtime selected an unknown transition");
|
||||
transitionJournal.push({
|
||||
sequence: decision.transition.sequence,
|
||||
at_ms: decision.transition.at_ms,
|
||||
transition_id: decision.transition.transition_id,
|
||||
state_before: decision.transition.state_before,
|
||||
state_after: decision.transition.state_after,
|
||||
captured_aliases: definition.captures.map(({ variable, sensitive }) => ({
|
||||
name: variable,
|
||||
sensitive,
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
const usage = runtime.usage;
|
||||
const transitionActions = input.machine.transitions
|
||||
.filter(({ id }) => usedTransitionIds.has(id))
|
||||
.map(({ id, actions }) => ({
|
||||
transition_id: id,
|
||||
actions: actions.map((action) => redactAction(runtime, action)),
|
||||
}));
|
||||
return replayMachineRunOutputSchema.parse({
|
||||
schema_version: 1,
|
||||
initial_state: input.machine.initial_state,
|
||||
final_state: runtime.state,
|
||||
terminal:
|
||||
input.machine.states.find(({ name }) => name === runtime.state)
|
||||
?.terminal ?? false,
|
||||
decisions,
|
||||
transition_journal: transitionJournal,
|
||||
transition_actions: transitionActions,
|
||||
limits: {
|
||||
configured: {
|
||||
transitions: input.machine.max_transitions,
|
||||
...input.machine.limits,
|
||||
},
|
||||
usage: {
|
||||
offered_events: input.events.length,
|
||||
admitted_events: usage.events,
|
||||
transitions: usage.transitions,
|
||||
connections: usage.connections,
|
||||
messages: usage.messages,
|
||||
bytes: usage.bytes,
|
||||
last_at_ms: usage.last_at_ms,
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -1,4 +1,5 @@
|
||||
import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
|
||||
import type { ReplayMachine } from "./replayMachine.js";
|
||||
|
||||
@@ -15,6 +16,61 @@ interface TransitionRecordOptions {
|
||||
}[];
|
||||
}
|
||||
|
||||
/** One bounded inbound protocol event offered to a replay machine. */
|
||||
const replayEventHeadersSchema = z
|
||||
.record(
|
||||
z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(256)
|
||||
.regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u),
|
||||
z
|
||||
.string()
|
||||
.max(8_192)
|
||||
.regex(/^[\t\x20-\x7e\x80-\xff]*$/u),
|
||||
)
|
||||
.superRefine((headers, context) => {
|
||||
const normalized = Object.keys(headers).map((name) => name.toLowerCase());
|
||||
if (new Set(normalized).size !== normalized.length)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "replay event headers must be unique ignoring case",
|
||||
input: headers,
|
||||
});
|
||||
});
|
||||
|
||||
const replayEventFields = {
|
||||
at_ms: z.number().int().nonnegative().safe(),
|
||||
path: z.string().startsWith("/").max(8_192),
|
||||
headers: replayEventHeadersSchema,
|
||||
body: z.string().max(1_000_000),
|
||||
};
|
||||
|
||||
export const replayMachineEventSchema = z.discriminatedUnion("protocol", [
|
||||
z.strictObject({
|
||||
protocol: z.literal("http"),
|
||||
connection: z.literal("not_applicable"),
|
||||
method: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(16)
|
||||
.transform((method) => method.toUpperCase()),
|
||||
...replayEventFields,
|
||||
}),
|
||||
z.strictObject({
|
||||
protocol: z.literal("websocket_connect"),
|
||||
connection: z.enum(["initial", "reconnect"]),
|
||||
method: z.null(),
|
||||
...replayEventFields,
|
||||
}),
|
||||
z.strictObject({
|
||||
protocol: z.literal("websocket_message"),
|
||||
connection: z.enum(["initial", "reconnect"]),
|
||||
method: z.null(),
|
||||
...replayEventFields,
|
||||
}),
|
||||
]);
|
||||
|
||||
/** One bounded inbound protocol event offered to a replay machine. */
|
||||
export interface ReplayMachineEvent {
|
||||
readonly protocol: "http" | "websocket_connect" | "websocket_message";
|
||||
@@ -27,6 +83,16 @@ export interface ReplayMachineEvent {
|
||||
readonly body: string;
|
||||
}
|
||||
|
||||
/** Runtime counters committed only for events admitted by all machine limits. */
|
||||
export interface ReplayMachineUsage {
|
||||
readonly events: number;
|
||||
readonly transitions: number;
|
||||
readonly connections: number;
|
||||
readonly messages: number;
|
||||
readonly bytes: number;
|
||||
readonly last_at_ms: number;
|
||||
}
|
||||
|
||||
/** Persistable transition journal entry containing aliases, never secrets. */
|
||||
export interface ReplayTransitionRecord {
|
||||
readonly sequence: number;
|
||||
@@ -183,6 +249,7 @@ export class ReplayMachineRuntime {
|
||||
#messages = 0;
|
||||
#bytes = 0;
|
||||
#lastAtMs = 0;
|
||||
#events = 0;
|
||||
|
||||
constructor(readonly machine: ReplayMachine) {
|
||||
this.#state = machine.initial_state;
|
||||
@@ -199,6 +266,18 @@ export class ReplayMachineRuntime {
|
||||
return this.#timeline;
|
||||
}
|
||||
|
||||
/** Current committed use of the machine's declared limits. */
|
||||
get usage(): ReplayMachineUsage {
|
||||
return {
|
||||
events: this.#events,
|
||||
transitions: this.#timeline.length,
|
||||
connections: this.#connections,
|
||||
messages: this.#messages,
|
||||
bytes: this.#bytes,
|
||||
last_at_ms: this.#lastAtMs,
|
||||
};
|
||||
}
|
||||
|
||||
/** Replace captured secret values with stable aliases before persistence. */
|
||||
redact(value: string): string {
|
||||
let redacted = value;
|
||||
@@ -216,6 +295,17 @@ export class ReplayMachineRuntime {
|
||||
return redacted;
|
||||
}
|
||||
|
||||
/** Replace a field containing captured secrets with one stable alias only. */
|
||||
redactField(value: string): string {
|
||||
const alias = [...this.#sensitiveValues]
|
||||
.filter(([, values]) =>
|
||||
[...values].some((secret) => value.includes(secret)),
|
||||
)
|
||||
.map(([variable]) => variable)
|
||||
.sort()[0];
|
||||
return alias === undefined ? value : `<secret:${alias}>`;
|
||||
}
|
||||
|
||||
/** Evaluate and, when admitted, commit one protocol event. */
|
||||
dispatch(event: ReplayMachineEvent): ReplayMachineDecision {
|
||||
const normalizedEvent = {
|
||||
@@ -334,6 +424,7 @@ export class ReplayMachineRuntime {
|
||||
this.#messages = messages;
|
||||
this.#bytes = bytes;
|
||||
this.#lastAtMs = event.at_ms;
|
||||
this.#events += 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import { SESSION_TOOL_CONTRACTS } from "../contracts/toolContracts.js";
|
||||
import {
|
||||
replayMachineRunInputSchema,
|
||||
runReplayMachine,
|
||||
} from "../domain/replayMachineRun.js";
|
||||
import { ok } from "../domain/result.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { safeParseToolInput } from "./toolInputValidation.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
import { toCallToolResult } from "./toolResult.js";
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
|
||||
const contract = SESSION_TOOL_CONTRACTS.find(
|
||||
({ name }) => name === "run_replay_machine",
|
||||
);
|
||||
if (contract === undefined)
|
||||
throw new TypeError("Missing run_replay_machine tool contract");
|
||||
|
||||
/** Register direct execution-free finite replay-machine evaluation. */
|
||||
export const registerReplayMachineTool = (
|
||||
server: McpServer,
|
||||
logger: Logger,
|
||||
): void => {
|
||||
server.registerTool(
|
||||
contract.name,
|
||||
toolRegistrationOptions(contract),
|
||||
async (input) => {
|
||||
const parsed = safeParseToolInput(
|
||||
replayMachineRunInputSchema,
|
||||
input,
|
||||
contract.name,
|
||||
);
|
||||
if (!parsed.ok) return toCallToolResult(parsed, contract);
|
||||
const result = await logToolExecution(logger, contract.name, () =>
|
||||
Promise.resolve(ok(runReplayMachine(parsed.value))),
|
||||
);
|
||||
return toCallToolResult(result, contract);
|
||||
},
|
||||
);
|
||||
};
|
||||
@@ -56,6 +56,7 @@ import {
|
||||
registerEvidenceTools,
|
||||
registerUnknownTools,
|
||||
} from "./registerSessionRecordTools.js";
|
||||
import { registerReplayMachineTool } from "./registerReplayMachineTool.js";
|
||||
import {
|
||||
sessionAvailabilityPolicy,
|
||||
type SessionAvailability,
|
||||
@@ -395,6 +396,19 @@ export interface SessionToolOptions {
|
||||
readonly availabilityPolicy?: () => SessionAvailability;
|
||||
}
|
||||
|
||||
const registerRecordAndReplayTools = (
|
||||
server: McpServer,
|
||||
session: BinarySessionPort,
|
||||
logger: Logger,
|
||||
): void => {
|
||||
registerUnknownTools({
|
||||
server,
|
||||
session,
|
||||
contracts: SESSION_TOOL_CONTRACTS,
|
||||
});
|
||||
registerReplayMachineTool(server, logger);
|
||||
};
|
||||
|
||||
export const registerSessionTools = (
|
||||
server: McpServer,
|
||||
session: BinarySessionPort,
|
||||
@@ -489,9 +503,5 @@ export const registerSessionTools = (
|
||||
? {}
|
||||
: { permissionAuthority: options.permissionAuthority }),
|
||||
});
|
||||
registerUnknownTools({
|
||||
server,
|
||||
session,
|
||||
contracts: SESSION_TOOL_CONTRACTS,
|
||||
});
|
||||
registerRecordAndReplayTools(server, session, logger);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user