Merge pull request #461 from morluto/agent/comprehensive-repository-audit
fix: harden evidence lifecycle and MCP contracts
This commit is contained in:
@@ -119,13 +119,10 @@ export const inspectAddressContext = async (
|
||||
inline_comment: inlineComment,
|
||||
bookmarks:
|
||||
bookmarks.state === "available"
|
||||
? {
|
||||
state: "available",
|
||||
value: matchingBookmarks(
|
||||
bookmarks.value,
|
||||
resolvedAddress(results[1], input.address),
|
||||
),
|
||||
}
|
||||
? matchingBookmarks(
|
||||
bookmarks.value,
|
||||
resolvedAddress(results[1], input.address),
|
||||
)
|
||||
: bookmarks,
|
||||
});
|
||||
};
|
||||
@@ -200,13 +197,33 @@ const resolvedAddress = (
|
||||
: fallback;
|
||||
};
|
||||
|
||||
const matchingBookmarks = (value: JsonValue, address: string): JsonValue => {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value.filter(
|
||||
(bookmark) =>
|
||||
typeof bookmark === "object" &&
|
||||
bookmark !== null &&
|
||||
!Array.isArray(bookmark) &&
|
||||
bookmark.address === address,
|
||||
);
|
||||
const matchingBookmarks = (value: JsonValue, address: string): Facet => {
|
||||
if (!Array.isArray(value))
|
||||
return {
|
||||
state: "unavailable",
|
||||
reason: "list_bookmarks returned malformed output; expected an array.",
|
||||
remediation:
|
||||
"Retry list_bookmarks directly and report the provider output shape if it remains malformed.",
|
||||
};
|
||||
if (!value.every(isBookmark))
|
||||
return {
|
||||
state: "unavailable",
|
||||
reason:
|
||||
"list_bookmarks returned malformed entries; expected address and name strings.",
|
||||
remediation:
|
||||
"Retry list_bookmarks directly and report the provider output shape if it remains malformed.",
|
||||
};
|
||||
return {
|
||||
state: "available",
|
||||
value: value.filter((bookmark) => bookmark.address === address),
|
||||
};
|
||||
};
|
||||
|
||||
const isBookmark = (
|
||||
value: JsonValue,
|
||||
): value is { readonly address: string; readonly name: string } =>
|
||||
typeof value === "object" &&
|
||||
value !== null &&
|
||||
!Array.isArray(value) &&
|
||||
typeof value.address === "string" &&
|
||||
typeof value.name === "string";
|
||||
|
||||
@@ -34,6 +34,8 @@ export interface EvidenceBundleSnapshot {
|
||||
readonly bytes: number;
|
||||
readonly records: number;
|
||||
readonly unknowns: number;
|
||||
readonly scope: "session";
|
||||
readonly survivesSession: false;
|
||||
readonly uri: string;
|
||||
}
|
||||
|
||||
@@ -60,6 +62,7 @@ export interface BinarySessionPort extends AnalysisOperationPort {
|
||||
evidenceById(evidenceId: string): Evidence | undefined;
|
||||
exportEvidenceBundle(): EvidenceBundle;
|
||||
snapshotEvidenceBundle(): Result<EvidenceBundleSnapshot, EvidenceLimitError>;
|
||||
releaseEvidenceBundle(bundleDigest: string): boolean;
|
||||
retainedEvidenceBundle(digest: string): string | undefined;
|
||||
importEvidenceBundle(
|
||||
bundle: unknown,
|
||||
|
||||
@@ -129,6 +129,8 @@ export abstract class BinarySessionRecords {
|
||||
bytes: Buffer.byteLength(existing ?? encoded),
|
||||
records: bundle.records.length,
|
||||
unknowns: bundle.unknowns.length,
|
||||
scope: "session",
|
||||
survivesSession: false,
|
||||
uri: `rea://evidence-bundle/${digest}`,
|
||||
});
|
||||
}
|
||||
@@ -137,12 +139,23 @@ export abstract class BinarySessionRecords {
|
||||
return this.#retainedBundles.get(digest);
|
||||
}
|
||||
|
||||
/** Release one immutable bundle so bounded retention has an explicit recovery path. */
|
||||
releaseEvidenceBundle(bundleDigest: string): boolean {
|
||||
const encoded = this.#retainedBundles.get(bundleDigest);
|
||||
if (encoded === undefined) return false;
|
||||
this.#retainedBundles.delete(bundleDigest);
|
||||
this.#retainedBundleBytes -= Buffer.byteLength(encoded);
|
||||
this.#emitSnapshotChanged();
|
||||
return true;
|
||||
}
|
||||
|
||||
importEvidenceBundle(
|
||||
bundle: unknown,
|
||||
): Result<number, EvidenceIntegrityError | EvidenceLimitError> {
|
||||
const imported = this.#evidence.import(bundle);
|
||||
if (imported.ok && imported.value > 0) this.#emitSnapshotChanged();
|
||||
return imported;
|
||||
if (!imported.ok) return imported;
|
||||
if (imported.value.changed) this.#emitSnapshotChanged();
|
||||
return ok(imported.value.recordsAdded);
|
||||
}
|
||||
|
||||
protected abstract activeAnalysisBinding(): ActiveAnalysisBinding | undefined;
|
||||
@@ -187,7 +200,10 @@ export abstract class BinarySessionRecords {
|
||||
active === undefined
|
||||
? undefined
|
||||
: { target: active.target, profile: active.profile },
|
||||
(bundle) => this.#evidence.import(bundle),
|
||||
(bundle) => {
|
||||
const imported = this.#evidence.import(bundle);
|
||||
return imported.ok ? ok(imported.value.recordsAdded) : imported;
|
||||
},
|
||||
);
|
||||
if (imported.ok) this.#emitSnapshotChanged();
|
||||
return imported;
|
||||
@@ -253,7 +269,16 @@ export abstract class BinarySessionRecords {
|
||||
}
|
||||
|
||||
#emitSnapshotChanged(): void {
|
||||
for (const listener of this.#snapshotListeners) void listener();
|
||||
for (const listener of this.#snapshotListeners) {
|
||||
try {
|
||||
const notification = listener();
|
||||
if (notification !== undefined)
|
||||
void notification.catch(() => undefined);
|
||||
} catch {
|
||||
// External resource observers are best-effort; one callback must not
|
||||
// make a committed evidence mutation appear to fail.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
retainInvestigationWorkspace(
|
||||
|
||||
@@ -72,6 +72,17 @@ const CLIENT_FEATURE_REQUIREMENTS: Readonly<
|
||||
type Availability = {
|
||||
readonly reason: ToolAvailabilityReason;
|
||||
readonly remediation: string | null;
|
||||
readonly defaultModeAvailable?: boolean;
|
||||
readonly modes?: readonly CapabilityMode[];
|
||||
};
|
||||
type CapabilityMode = {
|
||||
readonly name: string;
|
||||
readonly available: boolean;
|
||||
readonly missing_operations: readonly string[];
|
||||
readonly remediation: string | null;
|
||||
};
|
||||
type NavigationModeResult = CapabilityMode & {
|
||||
readonly reason: ToolAvailabilityReason;
|
||||
};
|
||||
type AvailabilityContext = {
|
||||
readonly name: string;
|
||||
@@ -111,15 +122,20 @@ const ENHANCED_REQUIREMENTS: Readonly<Record<string, readonly string[]>> = {
|
||||
],
|
||||
};
|
||||
|
||||
const SESSION_COMPOSITION_REQUIREMENTS: Readonly<
|
||||
Record<string, readonly string[]>
|
||||
> = {
|
||||
get_navigation_context: [
|
||||
"current_document",
|
||||
"current_address",
|
||||
"resolve_containing_procedure",
|
||||
],
|
||||
};
|
||||
const NAVIGATION_CONTEXT_MODES = [
|
||||
{
|
||||
name: "current_selection",
|
||||
requirements: [
|
||||
"current_document",
|
||||
"current_address",
|
||||
"resolve_containing_procedure",
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "explicit_document",
|
||||
requirements: ["current_address", "resolve_containing_procedure"],
|
||||
},
|
||||
] as const;
|
||||
|
||||
/** Build stable per-operation availability for discovery and tool visibility. */
|
||||
export const buildCapabilityInventory = (
|
||||
@@ -162,6 +178,12 @@ export const buildCapabilityInventory = (
|
||||
remediation: clientBlocked
|
||||
? `Use an MCP client that supports: ${clientRequirements.missing_required.join(", ")}.`
|
||||
: availability.remediation,
|
||||
...(availability.defaultModeAvailable === undefined
|
||||
? {}
|
||||
: { default_mode_available: availability.defaultModeAvailable }),
|
||||
...(availability.modes === undefined
|
||||
? {}
|
||||
: { modes: availability.modes }),
|
||||
client_requirements: clientRequirements,
|
||||
effects: { ...contract.effects },
|
||||
annotations: {
|
||||
@@ -195,9 +217,8 @@ const clientRequirementsFor = (
|
||||
};
|
||||
|
||||
const availabilityFor = (context: AvailabilityContext): Availability => {
|
||||
const sessionComposition = SESSION_COMPOSITION_REQUIREMENTS[context.name];
|
||||
if (sessionComposition !== undefined)
|
||||
return composedAvailabilityFor(sessionComposition, context.descriptors);
|
||||
if (context.name === "get_navigation_context")
|
||||
return navigationContextAvailability(context.descriptors);
|
||||
const javascriptApplication = javascriptApplicationAvailability(context);
|
||||
if (javascriptApplication !== null) return javascriptApplication;
|
||||
const policyDecision = policyAvailability(context);
|
||||
@@ -406,3 +427,72 @@ const composedAvailabilityFor = (
|
||||
};
|
||||
return { reason: "available", remediation: null };
|
||||
};
|
||||
|
||||
const navigationContextAvailability = (
|
||||
descriptors: ReadonlyMap<string, ProviderDescriptor>,
|
||||
): Availability => {
|
||||
const modeResults: NavigationModeResult[] = NAVIGATION_CONTEXT_MODES.map(
|
||||
(mode) => {
|
||||
const availability = composedAvailabilityFor(
|
||||
mode.requirements,
|
||||
descriptors,
|
||||
);
|
||||
return {
|
||||
name: mode.name,
|
||||
available: availability.reason === "available",
|
||||
reason: availability.reason,
|
||||
missing_operations: mode.requirements.filter((operation) => {
|
||||
const descriptor = descriptors.get(operation);
|
||||
return descriptor === undefined || descriptor.available === false;
|
||||
}),
|
||||
remediation: availability.remediation,
|
||||
};
|
||||
},
|
||||
);
|
||||
const modes = modeResults.map(
|
||||
({ name, available, missing_operations, remediation }) => ({
|
||||
name,
|
||||
available,
|
||||
missing_operations,
|
||||
remediation,
|
||||
}),
|
||||
);
|
||||
const availableMode = modeResults.find((mode) => mode.available);
|
||||
const failure = modeResults
|
||||
.filter((mode) => !mode.available)
|
||||
.sort(
|
||||
(left, right) =>
|
||||
navigationFailurePriority(left.reason) -
|
||||
navigationFailurePriority(right.reason),
|
||||
)[0];
|
||||
const specificFailureRemediation =
|
||||
failure?.reason === "provider_missing" ? undefined : failure?.remediation;
|
||||
return {
|
||||
reason:
|
||||
availableMode === undefined
|
||||
? (failure?.reason ?? "provider_missing")
|
||||
: "available",
|
||||
remediation:
|
||||
availableMode === undefined
|
||||
? (specificFailureRemediation ??
|
||||
`Configure a provider for one of: ${modes
|
||||
.flatMap((mode) => mode.missing_operations)
|
||||
.join(", ")}.`)
|
||||
: null,
|
||||
defaultModeAvailable: modes[0]?.available ?? false,
|
||||
modes,
|
||||
};
|
||||
};
|
||||
|
||||
const navigationFailurePriority = (reason: ToolAvailabilityReason): number => {
|
||||
switch (reason) {
|
||||
case "unsupported_host":
|
||||
return 0;
|
||||
case "provider_unavailable":
|
||||
return 1;
|
||||
case "provider_missing":
|
||||
return 2;
|
||||
default:
|
||||
return 3;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -26,7 +26,11 @@ export const importEvidenceBundleCommand = async (
|
||||
const ledger = createLedger();
|
||||
const imported = ledger.import(loaded.value);
|
||||
return imported.ok
|
||||
? ok({ imported: imported.value, total: ledger.export().records.length })
|
||||
? ok({
|
||||
imported: imported.value.recordsAdded,
|
||||
unknowns_added: imported.value.unknownsAdded,
|
||||
total: ledger.export().records.length,
|
||||
})
|
||||
: imported;
|
||||
};
|
||||
|
||||
|
||||
@@ -29,7 +29,15 @@ export interface EvidenceLedgerLimits {
|
||||
|
||||
type EvidenceLedgerFailure = EvidenceIntegrityError | EvidenceLimitError;
|
||||
type RecordResult = Result<"added" | "duplicate", EvidenceLedgerFailure>;
|
||||
type ImportResult = Result<number, EvidenceLedgerFailure>;
|
||||
|
||||
/** Describes the state changes made by one atomic bundle import. */
|
||||
export interface EvidenceImportDelta {
|
||||
readonly recordsAdded: number;
|
||||
readonly unknownsAdded: number;
|
||||
readonly changed: boolean;
|
||||
}
|
||||
|
||||
type ImportResult = Result<EvidenceImportDelta, EvidenceLedgerFailure>;
|
||||
|
||||
/** Bounded, session-owned set of immutable evidence records. */
|
||||
export class EvidenceLedger {
|
||||
@@ -98,6 +106,7 @@ export class EvidenceLedger {
|
||||
pending.set(evidence.evidence_id, evidence);
|
||||
}
|
||||
const pendingUnknowns = new Map(this.#unknownRevisions);
|
||||
let unknownsAdded = 0;
|
||||
for (const unknown of bundle.unknowns) {
|
||||
const key = unknownRevisionKey(unknown);
|
||||
const existing = pendingUnknowns.get(key);
|
||||
@@ -107,6 +116,7 @@ export class EvidenceLedger {
|
||||
)
|
||||
return err(new EvidenceIntegrityError("Conflicting unknown revision"));
|
||||
pendingUnknowns.set(key, unknown);
|
||||
if (existing === undefined) unknownsAdded += 1;
|
||||
}
|
||||
const checked = this.#validateCandidate(pending, pendingUnknowns);
|
||||
if (!checked.ok) {
|
||||
@@ -123,7 +133,11 @@ export class EvidenceLedger {
|
||||
}
|
||||
const added = pending.size - this.#records.size;
|
||||
this.#commit(pending, pendingUnknowns, checked.value);
|
||||
return ok(added);
|
||||
return ok({
|
||||
recordsAdded: added,
|
||||
unknownsAdded,
|
||||
changed: added > 0 || unknownsAdded > 0,
|
||||
});
|
||||
}
|
||||
|
||||
/** Export records in deterministic, semantically irrelevant ID order. */
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { artifactComparisonInputSchema } from "../domain/artifactComparison.js";
|
||||
import { bundleComparisonInputSchema } from "../domain/bundleComparison.js";
|
||||
import { callPathInputSchema } from "../domain/callPath.js";
|
||||
import { changedBehaviorInputSchema } from "../domain/changedBehavior.js";
|
||||
import { functionComparisonInputSchema } from "../domain/functionComparison.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import { processScenarioSchema } from "../domain/processCapture.js";
|
||||
import { processTraceSpecificationSchema } from "../domain/processTraceComparison.js";
|
||||
import { recordUnknownInputSchema } from "../domain/residualUnknown.js";
|
||||
import { reconstructionVerificationInputSchema } from "../domain/reconstructionVerification.js";
|
||||
import { replayMachineRunInputSchema } from "../domain/replayMachineRun.js";
|
||||
import { staticRuntimeCorrelationInputSchema } from "../domain/staticRuntimeCorrelation.js";
|
||||
import { updateUnknownInputSchema } from "../domain/residualUnknown.js";
|
||||
import {
|
||||
openBinaryInputSchema,
|
||||
closeBinaryInputSchema,
|
||||
} from "./sessionLifecycleInputs.js";
|
||||
import { binarySessionInputSchema } from "./sessionStatusContract.js";
|
||||
|
||||
/** Retain the current canonical Evidence bundle as a session resource. */
|
||||
export const snapshotEvidenceBundleInputSchema = z.strictObject({});
|
||||
|
||||
/** Release one session-retained immutable Evidence bundle. */
|
||||
export const releaseEvidenceBundleInputSchema = z.strictObject({
|
||||
bundle_digest: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
});
|
||||
|
||||
/** Optional document selection for volatile navigation context. */
|
||||
export const navigationContextInputSchema = z.strictObject({
|
||||
document: z.string().min(1).optional(),
|
||||
});
|
||||
|
||||
/** Explicit reproducible address context query. */
|
||||
export const addressContextInputSchema = z.strictObject({
|
||||
address: z.string().min(1),
|
||||
document: z.string().min(1).optional(),
|
||||
});
|
||||
|
||||
/** Session-owned Evidence bundle import options. */
|
||||
export const importEvidenceBundleInputSchema = z.strictObject({
|
||||
path: z.string().min(1),
|
||||
});
|
||||
|
||||
/** Evidence references for deterministic process comparison. */
|
||||
export const processComparisonInputSchema = z.strictObject({
|
||||
left_evidence_id: z.string().regex(/^ev_[a-f0-9]{64}$/u),
|
||||
right_evidence_id: z.string().regex(/^ev_[a-f0-9]{64}$/u),
|
||||
trace_spec: processTraceSpecificationSchema.optional(),
|
||||
max_capture_age_ms: z.number().int().nonnegative().optional(),
|
||||
unknown_registry_approved: z
|
||||
.literal(true)
|
||||
.optional()
|
||||
.describe("Explicit approval to record capture disagreement durably"),
|
||||
});
|
||||
|
||||
/** Residual-unknown list filters. */
|
||||
export const listUnknownsInputSchema = z.strictObject({
|
||||
status: z
|
||||
.enum(["open", "investigating", "blocked", "contradicted", "resolved"])
|
||||
.optional(),
|
||||
severity: z.enum(["low", "medium", "high", "critical"]).optional(),
|
||||
domain: z.string().trim().min(1).max(100).optional(),
|
||||
offset: z.number().int().min(0).default(0),
|
||||
limit: z.number().int().min(1).max(500).default(100),
|
||||
});
|
||||
|
||||
/** Exact residual-unknown identity to revalidate. */
|
||||
export const verifyUnknownResolutionInputSchema = z.strictObject({
|
||||
unknown_id: z.string().regex(/^unk_[a-f0-9]{64}$/u),
|
||||
});
|
||||
|
||||
export {
|
||||
artifactComparisonInputSchema,
|
||||
binarySessionInputSchema,
|
||||
bundleComparisonInputSchema,
|
||||
callPathInputSchema,
|
||||
changedBehaviorInputSchema,
|
||||
closeBinaryInputSchema,
|
||||
functionComparisonInputSchema,
|
||||
jsonValueSchema,
|
||||
openBinaryInputSchema,
|
||||
processScenarioSchema,
|
||||
reconstructionVerificationInputSchema,
|
||||
recordUnknownInputSchema,
|
||||
replayMachineRunInputSchema,
|
||||
staticRuntimeCorrelationInputSchema,
|
||||
updateUnknownInputSchema,
|
||||
};
|
||||
@@ -43,6 +43,7 @@ export const TOOL_EXAMPLE_OVERRIDES: Readonly<
|
||||
export_evidence_bundle: { path: "/tmp/evidence.json" },
|
||||
inspect_address_context: { address: "0x1000" },
|
||||
import_evidence_bundle: { path: "evidence.json" },
|
||||
release_evidence_bundle: { bundle_digest: "a".repeat(64) },
|
||||
capture_process_scenario: {
|
||||
approved: true,
|
||||
executable: "/usr/bin/true",
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import { TOOL_EXAMPLE_OVERRIDES } from "./toolContractExamples.js";
|
||||
import type { ToolExample } from "./toolContractTypes.js";
|
||||
|
||||
export const document = z.string().optional().describe("The document name");
|
||||
export const address = z
|
||||
.string()
|
||||
.describe(
|
||||
"A provider-normalized address; default memory uses 0x-prefixed hexadecimal",
|
||||
);
|
||||
export const optionalAddress = address.optional();
|
||||
export const procedure = z.string().describe("The procedure name or address");
|
||||
export const pagination = {
|
||||
offset: z.number().int().min(0).default(0),
|
||||
limit: z.number().int().min(1).max(500).default(100),
|
||||
};
|
||||
|
||||
const exampleInputSchema = z.record(z.string(), jsonValueSchema);
|
||||
|
||||
export const examplesFor = (
|
||||
name: string,
|
||||
inputSchema: z.ZodObject,
|
||||
): readonly ToolExample[] => {
|
||||
const parsed = inputSchema.parse(TOOL_EXAMPLE_OVERRIDES[name] ?? {});
|
||||
return [
|
||||
{
|
||||
title: `Example ${name.replaceAll("_", " ")} request`,
|
||||
input: exampleInputSchema.parse(parsed),
|
||||
},
|
||||
];
|
||||
};
|
||||
@@ -1,20 +1,4 @@
|
||||
import { z } from "zod";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import { processScenarioSchema } from "../domain/processCapture.js";
|
||||
import {
|
||||
recordUnknownInputSchema,
|
||||
updateUnknownInputSchema,
|
||||
} from "../domain/residualUnknown.js";
|
||||
import { artifactComparisonInputSchema } from "../domain/artifactComparison.js";
|
||||
import { functionComparisonInputSchema } from "../domain/functionComparison.js";
|
||||
import { bundleComparisonInputSchema } from "../domain/bundleComparison.js";
|
||||
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 { processTraceSpecificationSchema } from "../domain/processTraceComparison.js";
|
||||
|
||||
import { enhancedInputSchemas } from "./enhancedInputs.js";
|
||||
import {
|
||||
enhancedOutputSchemas,
|
||||
@@ -22,7 +6,6 @@ import {
|
||||
requireOutputSchema,
|
||||
sessionOutputSchemas,
|
||||
} from "./toolOutputSchemas.js";
|
||||
import { TOOL_EXAMPLE_OVERRIDES } from "./toolContractExamples.js";
|
||||
import { NATIVE_TOOL_CONTRACTS } from "./nativeToolContracts.js";
|
||||
import { ARTIFACT_TOOL_CONTRACTS } from "./artifactToolContracts.js";
|
||||
import { MANAGED_TOOL_CONTRACTS } from "./managedToolContracts.js";
|
||||
@@ -32,48 +15,58 @@ import { ELECTRON_TOOL_CONTRACTS } from "./electronToolContracts.js";
|
||||
import { JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS } from "./javascriptRuntimeObservationToolContracts.js";
|
||||
import { APPLICATION_TOOL_CONTRACTS } from "./applicationToolContracts.js";
|
||||
import {
|
||||
addressContextInputSchema,
|
||||
artifactComparisonInputSchema,
|
||||
binarySessionInputSchema,
|
||||
bundleComparisonInputSchema,
|
||||
callPathInputSchema,
|
||||
changedBehaviorInputSchema,
|
||||
closeBinaryInputSchema,
|
||||
functionComparisonInputSchema,
|
||||
importEvidenceBundleInputSchema,
|
||||
listUnknownsInputSchema,
|
||||
navigationContextInputSchema,
|
||||
openBinaryInputSchema,
|
||||
} from "./sessionLifecycleInputs.js";
|
||||
import type { ToolContract, ToolExample } from "./toolContractTypes.js";
|
||||
processComparisonInputSchema,
|
||||
processScenarioSchema,
|
||||
reconstructionVerificationInputSchema,
|
||||
recordUnknownInputSchema,
|
||||
releaseEvidenceBundleInputSchema,
|
||||
replayMachineRunInputSchema,
|
||||
snapshotEvidenceBundleInputSchema,
|
||||
staticRuntimeCorrelationInputSchema,
|
||||
updateUnknownInputSchema,
|
||||
verifyUnknownResolutionInputSchema,
|
||||
} from "./sessionToolSchemas.js";
|
||||
import {
|
||||
address,
|
||||
document,
|
||||
examplesFor,
|
||||
optionalAddress,
|
||||
pagination,
|
||||
procedure,
|
||||
} from "./toolContractHelpers.js";
|
||||
import type { ToolContract } from "./toolContractTypes.js";
|
||||
import { toolContractMetadata } from "./toolEffects.js";
|
||||
import { binarySessionInputSchema } from "./sessionStatusContract.js";
|
||||
import { functionInstructionInputSchema } from "./functionInstructionContract.js";
|
||||
import { HOPPER_MEMORY_TOOL_DEFINITIONS } from "./hopperMemoryContracts.js";
|
||||
import { analysisSearchInput } from "./analysisSearchContract.js";
|
||||
import { FUNCTION_WORKFLOW_TOOL_CONTRACTS } from "./functionWorkflowToolContracts.js";
|
||||
|
||||
export { binarySessionInputSchema } from "./sessionStatusContract.js";
|
||||
export {
|
||||
addressContextInputSchema,
|
||||
binarySessionInputSchema,
|
||||
importEvidenceBundleInputSchema,
|
||||
listUnknownsInputSchema,
|
||||
navigationContextInputSchema,
|
||||
processComparisonInputSchema,
|
||||
releaseEvidenceBundleInputSchema,
|
||||
snapshotEvidenceBundleInputSchema,
|
||||
verifyUnknownResolutionInputSchema,
|
||||
} from "./sessionToolSchemas.js";
|
||||
|
||||
export type { ToolContract, ToolExample } from "./toolContractTypes.js";
|
||||
|
||||
const document = z.string().optional().describe("The document name");
|
||||
const address = z
|
||||
.string()
|
||||
.describe(
|
||||
"A provider-normalized address; default memory uses 0x-prefixed hexadecimal",
|
||||
);
|
||||
const optionalAddress = address.optional();
|
||||
const procedure = z.string().describe("The procedure name or address");
|
||||
const pagination = {
|
||||
offset: z.number().int().min(0).default(0),
|
||||
limit: z.number().int().min(1).max(500).default(100),
|
||||
};
|
||||
|
||||
const exampleInputSchema = z.record(z.string(), jsonValueSchema);
|
||||
const examplesFor = (
|
||||
name: string,
|
||||
inputSchema: z.ZodObject,
|
||||
): readonly ToolExample[] => {
|
||||
const parsed = inputSchema.parse(TOOL_EXAMPLE_OVERRIDES[name] ?? {});
|
||||
return [
|
||||
{
|
||||
title: `Example ${name.replaceAll("_", " ")} request`,
|
||||
input: exampleInputSchema.parse(parsed),
|
||||
},
|
||||
];
|
||||
};
|
||||
|
||||
const official = <Name extends string>(
|
||||
name: Name,
|
||||
description: string,
|
||||
@@ -379,53 +372,6 @@ export const exportEvidenceBundleInputSchema = z.strictObject({
|
||||
overwrite: z.boolean().default(false),
|
||||
});
|
||||
|
||||
/** Retain the current canonical Evidence bundle as a session resource. */
|
||||
export const snapshotEvidenceBundleInputSchema = z.strictObject({});
|
||||
|
||||
/** Optional document selection for volatile navigation context. */
|
||||
export const navigationContextInputSchema = z.strictObject({
|
||||
document: z.string().min(1).optional(),
|
||||
});
|
||||
|
||||
/** Explicit reproducible address context query. */
|
||||
export const addressContextInputSchema = z.strictObject({
|
||||
address: z.string().min(1),
|
||||
document: z.string().min(1).optional(),
|
||||
});
|
||||
|
||||
/** Session-owned Evidence bundle import options. */
|
||||
export const importEvidenceBundleInputSchema = z.strictObject({
|
||||
path: z.string().min(1),
|
||||
});
|
||||
|
||||
/** Evidence references for deterministic process comparison. */
|
||||
export const processComparisonInputSchema = z.strictObject({
|
||||
left_evidence_id: z.string().regex(/^ev_[a-f0-9]{64}$/u),
|
||||
right_evidence_id: z.string().regex(/^ev_[a-f0-9]{64}$/u),
|
||||
trace_spec: processTraceSpecificationSchema.optional(),
|
||||
max_capture_age_ms: z.number().int().nonnegative().optional(),
|
||||
unknown_registry_approved: z
|
||||
.literal(true)
|
||||
.optional()
|
||||
.describe("Explicit approval to record capture disagreement durably"),
|
||||
});
|
||||
|
||||
/** Residual-unknown list filters. */
|
||||
export const listUnknownsInputSchema = z.strictObject({
|
||||
status: z
|
||||
.enum(["open", "investigating", "blocked", "contradicted", "resolved"])
|
||||
.optional(),
|
||||
severity: z.enum(["low", "medium", "high", "critical"]).optional(),
|
||||
domain: z.string().trim().min(1).max(100).optional(),
|
||||
offset: z.number().int().min(0).default(0),
|
||||
limit: z.number().int().min(1).max(500).default(100),
|
||||
});
|
||||
|
||||
/** Exact residual-unknown identity to revalidate. */
|
||||
export const verifyUnknownResolutionInputSchema = z.strictObject({
|
||||
unknown_id: z.string().regex(/^unk_[a-f0-9]{64}$/u),
|
||||
});
|
||||
|
||||
/** Target lifecycle tools available only on the long-lived MCP adapter. */
|
||||
export const SESSION_TOOL_CONTRACTS = [
|
||||
session(
|
||||
@@ -528,9 +474,14 @@ export const SESSION_TOOL_CONTRACTS = [
|
||||
"Retain the current canonical Evidence v2 bundle as an immutable session resource. Returns a compact digest summary and exact opaque URI; copy that URI unchanged and call MCP resources/read (Codex: read_mcp_resource) for the full bundle. Repeating an unchanged snapshot is idempotent.",
|
||||
snapshotEvidenceBundleInputSchema,
|
||||
),
|
||||
session(
|
||||
"release_evidence_bundle",
|
||||
"Release one immutable session-retained Evidence v2 bundle by exact digest. This is the recovery operation when bounded bundle retention is exhausted; releasing an unknown digest is idempotent and reports released: false.",
|
||||
releaseEvidenceBundleInputSchema,
|
||||
),
|
||||
session(
|
||||
"get_navigation_context",
|
||||
"Return the selected document, current address, and containing/current procedure in one coherent provider-neutral request. A cursor outside any procedure returns procedure: null. Scalar navigation getters remain available for evaluation and compatibility.",
|
||||
"Compose the selected document, current address, and containing/current procedure into one provider-neutral result. The result reflects sequential provider observations, not an atomic cursor snapshot; a cursor outside any procedure returns procedure: null. Scalar navigation getters remain available for evaluation and compatibility.",
|
||||
navigationContextInputSchema,
|
||||
),
|
||||
session(
|
||||
|
||||
@@ -173,6 +173,10 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
mayDiscardData: true,
|
||||
}),
|
||||
snapshot_evidence_bundle: effects({ mutatesSession: true }),
|
||||
release_evidence_bundle: effects({
|
||||
mutatesSession: true,
|
||||
mayDiscardData: true,
|
||||
}),
|
||||
get_navigation_context: effects({ mutatesSession: true }),
|
||||
inspect_address_context: effects({ mutatesSession: true }),
|
||||
import_evidence_bundle: effects({ mutatesSession: true }),
|
||||
|
||||
@@ -44,8 +44,8 @@ import { replayMachineRunOutputSchema } from "../domain/replayMachineRun.js";
|
||||
import { analysisErrorProjectionSchema } from "./errorSchemas.js";
|
||||
import {
|
||||
addressList,
|
||||
analysisActivity,
|
||||
addressedEntry,
|
||||
analysisActivity,
|
||||
bounded,
|
||||
containingProcedureResolution,
|
||||
clientFeatureAvailabilitySchema,
|
||||
@@ -75,6 +75,14 @@ const contextFacetSchema = z.discriminatedUnion("state", [
|
||||
remediation: z.string(),
|
||||
}),
|
||||
]);
|
||||
const bookmarkFacetSchema = z.discriminatedUnion("state", [
|
||||
z.object({ state: z.literal("available"), value: z.array(addressedEntry) }),
|
||||
z.object({
|
||||
state: z.literal("unavailable"),
|
||||
reason: z.string(),
|
||||
remediation: z.string(),
|
||||
}),
|
||||
]);
|
||||
|
||||
/** Exact structured-content schemas shared by direct analysis providers. */
|
||||
export const officialOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
|
||||
@@ -426,9 +434,17 @@ export const sessionOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
|
||||
bytes: z.number().int().min(0),
|
||||
records: z.number().int().min(0),
|
||||
unknowns: z.number().int().min(0),
|
||||
scope: z.literal("session"),
|
||||
survives_session: z.literal(false),
|
||||
bundle_uri: z.string().regex(/^rea:\/\/evidence-bundle\/[a-f0-9]{64}$/u),
|
||||
}),
|
||||
),
|
||||
release_evidence_bundle: lifecycleResultOf(
|
||||
z.object({
|
||||
bundle_digest: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
released: z.boolean(),
|
||||
}),
|
||||
),
|
||||
get_navigation_context: lifecycleResultOf(
|
||||
z.object({
|
||||
document: z.string(),
|
||||
@@ -444,12 +460,13 @@ export const sessionOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
|
||||
procedure: contextFacetSchema,
|
||||
comment: contextFacetSchema,
|
||||
inline_comment: contextFacetSchema,
|
||||
bookmarks: contextFacetSchema,
|
||||
bookmarks: bookmarkFacetSchema,
|
||||
}),
|
||||
),
|
||||
import_evidence_bundle: lifecycleResultOf(
|
||||
z.object({
|
||||
imported: z.number().int().min(0),
|
||||
unknowns_added: z.number().int().min(0),
|
||||
total: z.number().int().min(0),
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -240,6 +240,17 @@ export const toolAvailability = z.object({
|
||||
"policy_disabled",
|
||||
]),
|
||||
remediation: z.string().nullable(),
|
||||
default_mode_available: z.boolean().optional(),
|
||||
modes: z
|
||||
.array(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
available: z.boolean(),
|
||||
missing_operations: z.array(z.string()),
|
||||
remediation: z.string().nullable(),
|
||||
}),
|
||||
)
|
||||
.optional(),
|
||||
client_requirements: z.object({
|
||||
required: z.array(clientFeatureNameSchema),
|
||||
optional: z.array(clientFeatureNameSchema),
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
import { READINESS_STAGE_IDS } from "../domain/reconstructionReadinessJourneyFindings.js";
|
||||
|
||||
type JsonSchema = Readonly<Record<string, unknown>>;
|
||||
const conditionResultKey = ["t", "hen"].join("");
|
||||
|
||||
const exactlyOne = (left: string, right: string): JsonSchema => ({
|
||||
oneOf: [{ required: [left] }, { required: [right] }],
|
||||
});
|
||||
|
||||
const exclusivePairs = (
|
||||
left: [string, string],
|
||||
right: [string, string],
|
||||
): JsonSchema => ({
|
||||
oneOf: [
|
||||
{
|
||||
required: left,
|
||||
not: {
|
||||
anyOf: right.map((field) => ({ required: [field] })),
|
||||
},
|
||||
},
|
||||
{
|
||||
required: right,
|
||||
not: {
|
||||
anyOf: left.map((field) => ({ required: [field] })),
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const twoEvidenceSources = (
|
||||
left: [string, string],
|
||||
right: [string, string],
|
||||
): JsonSchema => ({
|
||||
allOf: [exactlyOne(left[0], left[1]), exactlyOne(right[0], right[1])],
|
||||
});
|
||||
|
||||
const approvalDependency = (flag: string, approval: string): JsonSchema => ({
|
||||
if: {
|
||||
required: [flag],
|
||||
properties: {
|
||||
[flag]: {
|
||||
const: true,
|
||||
description: `Whether ${flag} was requested`,
|
||||
},
|
||||
},
|
||||
},
|
||||
[conditionResultKey]: {
|
||||
required: [approval],
|
||||
properties: {
|
||||
[approval]: {
|
||||
const: true,
|
||||
description: `Approval for ${flag}`,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const exactReadinessStages: JsonSchema = {
|
||||
allOf: [
|
||||
{
|
||||
properties: {
|
||||
stages: {
|
||||
description: "Complete reconstruction-readiness stage set",
|
||||
allOf: READINESS_STAGE_IDS.map((stageId) => ({
|
||||
contains: {
|
||||
type: "object",
|
||||
properties: {
|
||||
stage_id: {
|
||||
const: stageId,
|
||||
description: "Readiness stage identifier",
|
||||
},
|
||||
},
|
||||
required: ["stage_id"],
|
||||
description: "One reconstruction-readiness stage",
|
||||
},
|
||||
minContains: 1,
|
||||
maxContains: 1,
|
||||
})),
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
/** Public JSON-Schema constraints that Standard Schema cannot derive from refinements. */
|
||||
export const TOOL_INPUT_JSON_SCHEMA_OVERRIDES: Readonly<
|
||||
Record<string, JsonSchema>
|
||||
> = {
|
||||
compare_web_captures: {
|
||||
...exclusivePairs(
|
||||
["before", "after"],
|
||||
["before_scenario", "after_scenario"],
|
||||
),
|
||||
},
|
||||
inspect_web_page: {
|
||||
allOf: [
|
||||
approvalDependency("include_console_text", "console_text_approved"),
|
||||
approvalDependency(
|
||||
"include_json_body_shapes",
|
||||
"json_body_schema_approved",
|
||||
),
|
||||
approvalDependency(
|
||||
"include_websocket_shapes",
|
||||
"websocket_shape_approved",
|
||||
),
|
||||
],
|
||||
},
|
||||
analyze_web_bundle: {
|
||||
allOf: [
|
||||
approvalDependency("include_console_text", "console_text_approved"),
|
||||
approvalDependency(
|
||||
"include_json_body_shapes",
|
||||
"json_body_schema_approved",
|
||||
),
|
||||
approvalDependency(
|
||||
"include_websocket_shapes",
|
||||
"websocket_shape_approved",
|
||||
),
|
||||
approvalDependency("fetch_source_maps", "source_map_fetch_approved"),
|
||||
],
|
||||
},
|
||||
inspect_electron_page: {
|
||||
allOf: [
|
||||
approvalDependency("include_script_sources", "source_capture_approved"),
|
||||
],
|
||||
},
|
||||
trace_application_feature: {
|
||||
...exactlyOne("application", "application_evidence_id"),
|
||||
},
|
||||
trace_javascript_semantics: {
|
||||
...exactlyOne("application", "application_evidence_id"),
|
||||
},
|
||||
compare_application_versions: twoEvidenceSources(
|
||||
["left", "left_evidence_id"],
|
||||
["right", "right_evidence_id"],
|
||||
),
|
||||
compare_javascript_export_shapes: twoEvidenceSources(
|
||||
["left", "left_evidence_id"],
|
||||
["right", "right_evidence_id"],
|
||||
),
|
||||
compare_source_to_bundle: exactlyOne(
|
||||
"application",
|
||||
"application_evidence_id",
|
||||
),
|
||||
evaluate_reconstruction_readiness: exactReadinessStages,
|
||||
};
|
||||
|
||||
/** Merge a contract-specific public constraint into generated or advertised input JSON Schema. */
|
||||
export const applyToolInputJsonSchemaOverride = (
|
||||
name: string,
|
||||
schema: JsonSchema,
|
||||
): JsonSchema => {
|
||||
const override = TOOL_INPUT_JSON_SCHEMA_OVERRIDES[name];
|
||||
return override === undefined ? schema : { ...schema, ...override };
|
||||
};
|
||||
@@ -120,59 +120,55 @@ export function detectArtifactFormat(
|
||||
return null;
|
||||
}
|
||||
|
||||
const STANDARD_LIBRARY_PATH_MARKERS = [
|
||||
"/stdlib/",
|
||||
"/site-packages/",
|
||||
"java/",
|
||||
"javax/",
|
||||
"sun/",
|
||||
];
|
||||
const STANDARD_LIBRARY_SYMBOL_MARKERS = ["java.", "javax.", "sun.", "__"];
|
||||
const GENERATED_PATH_MARKERS = [
|
||||
"/generated/",
|
||||
"_generated",
|
||||
"/build/",
|
||||
"/target/",
|
||||
"/dist-packages/",
|
||||
"/__pycache__/",
|
||||
];
|
||||
const GENERATED_SYMBOL_MARKERS = ["Generated", "_generated"];
|
||||
const VENDORED_PATH_MARKERS = [
|
||||
"/vendor/",
|
||||
"/vendored/",
|
||||
"/third_party/",
|
||||
"/3rdparty/",
|
||||
"/node_modules/",
|
||||
];
|
||||
const BUNDLED_PATH_MARKERS = ["/bundle/", "/bundled/", ".jar!", ".war!"];
|
||||
|
||||
const includesAny = (value: string, markers: readonly string[]): boolean =>
|
||||
markers.some((marker) => value.includes(marker));
|
||||
const startsWithAny = (value: string, markers: readonly string[]): boolean =>
|
||||
markers.some((marker) => value.startsWith(marker));
|
||||
|
||||
/** Classify bytecode symbol provenance. */
|
||||
export function classifyProvenance(
|
||||
path: string,
|
||||
symbolName: string,
|
||||
): BytecodeProvenance {
|
||||
const lower = path.toLowerCase();
|
||||
// Standard library paths
|
||||
if (
|
||||
lower.includes("/stdlib/") ||
|
||||
lower.includes("/site-packages/") ||
|
||||
lower.includes("java/") ||
|
||||
lower.includes("javax/") ||
|
||||
lower.includes("sun/") ||
|
||||
symbolName.startsWith("java.") ||
|
||||
symbolName.startsWith("javax.") ||
|
||||
symbolName.startsWith("sun.") ||
|
||||
symbolName.startsWith("__")
|
||||
) {
|
||||
includesAny(lower, STANDARD_LIBRARY_PATH_MARKERS) ||
|
||||
startsWithAny(symbolName, STANDARD_LIBRARY_SYMBOL_MARKERS)
|
||||
)
|
||||
return "standard_library";
|
||||
}
|
||||
// Generated code
|
||||
if (
|
||||
lower.includes("/generated/") ||
|
||||
lower.includes("_generated") ||
|
||||
lower.includes("/build/") ||
|
||||
lower.includes("/target/") ||
|
||||
lower.includes("/dist-packages/") ||
|
||||
lower.includes("/__pycache__/") ||
|
||||
symbolName.includes("Generated") ||
|
||||
symbolName.includes("_generated")
|
||||
) {
|
||||
includesAny(lower, GENERATED_PATH_MARKERS) ||
|
||||
includesAny(symbolName, GENERATED_SYMBOL_MARKERS)
|
||||
)
|
||||
return "generated";
|
||||
}
|
||||
// Vendored code
|
||||
if (
|
||||
lower.includes("/vendor/") ||
|
||||
lower.includes("/vendored/") ||
|
||||
lower.includes("/third_party/") ||
|
||||
lower.includes("/3rdparty/") ||
|
||||
lower.includes("/node_modules/") ||
|
||||
lower.includes("/vendor/")
|
||||
) {
|
||||
return "vendored";
|
||||
}
|
||||
// Bundled code
|
||||
if (
|
||||
lower.includes("/bundle/") ||
|
||||
lower.includes("/bundled/") ||
|
||||
lower.includes(".jar!") ||
|
||||
lower.includes(".war!")
|
||||
) {
|
||||
return "bundled";
|
||||
}
|
||||
if (includesAny(lower, VENDORED_PATH_MARKERS)) return "vendored";
|
||||
if (includesAny(lower, BUNDLED_PATH_MARKERS)) return "bundled";
|
||||
return "application";
|
||||
}
|
||||
|
||||
|
||||
@@ -82,6 +82,82 @@ export type ProcessTreeReconstruction = z.infer<
|
||||
typeof processTreeReconstructionSchema
|
||||
>;
|
||||
|
||||
type ProcessTreeAccumulator = {
|
||||
readonly nodes: Map<number, ProcessNode>;
|
||||
readonly children: Map<number, number[]>;
|
||||
eventsUnmatched: number;
|
||||
hasReExec: boolean;
|
||||
hasReparenting: boolean;
|
||||
shortLivedDescendants: number;
|
||||
};
|
||||
|
||||
const applyProcessTreeEvent = (
|
||||
event: ProcessTreeEvent,
|
||||
state: ProcessTreeAccumulator,
|
||||
): void => {
|
||||
let node = state.nodes.get(event.pid);
|
||||
switch (event.type) {
|
||||
case "spawn": {
|
||||
if (!node) {
|
||||
node = {
|
||||
pid: event.pid,
|
||||
ppid: event.ppid,
|
||||
process_name: event.process_name,
|
||||
executable: event.executable,
|
||||
arguments: event.arguments,
|
||||
children: [],
|
||||
spawn_time_ms: event.at_ms,
|
||||
exit_time_ms: null,
|
||||
exit_code: null,
|
||||
is_re_exec: false,
|
||||
is_reparented: false,
|
||||
previous_ppid: null,
|
||||
};
|
||||
state.nodes.set(event.pid, node);
|
||||
}
|
||||
if (event.ppid !== null) {
|
||||
const parentChildren = state.children.get(event.ppid) ?? [];
|
||||
parentChildren.push(event.pid);
|
||||
state.children.set(event.ppid, parentChildren);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "exit":
|
||||
if (node) {
|
||||
node.exit_time_ms = event.at_ms;
|
||||
node.exit_code = event.exit_code;
|
||||
if (
|
||||
node.spawn_time_ms !== null &&
|
||||
event.at_ms - node.spawn_time_ms < 100
|
||||
)
|
||||
state.shortLivedDescendants++;
|
||||
} else state.eventsUnmatched++;
|
||||
break;
|
||||
case "re_exec":
|
||||
if (node) {
|
||||
node.is_re_exec = true;
|
||||
node.executable = event.executable ?? node.executable;
|
||||
node.arguments = event.arguments;
|
||||
state.hasReExec = true;
|
||||
} else state.eventsUnmatched++;
|
||||
break;
|
||||
case "reparent":
|
||||
if (node) {
|
||||
node.previous_ppid = node.ppid;
|
||||
node.ppid = event.ppid;
|
||||
node.is_reparented = true;
|
||||
state.hasReparenting = true;
|
||||
} else state.eventsUnmatched++;
|
||||
break;
|
||||
case "signal":
|
||||
case "name_change":
|
||||
case "thread_create":
|
||||
case "thread_exit":
|
||||
// These events are recorded but don't modify the tree structure.
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
/** Reconstruct a process tree from event-backed capture. */
|
||||
export function reconstructProcessTree(
|
||||
events: readonly ProcessTreeEvent[],
|
||||
@@ -90,86 +166,20 @@ export function reconstructProcessTree(
|
||||
const nodes = new Map<number, ProcessNode>();
|
||||
const children = new Map<number, number[]>();
|
||||
let eventsConsumed = 0;
|
||||
let eventsUnmatched = 0;
|
||||
let hasReExec = false;
|
||||
let hasReparenting = false;
|
||||
let shortLivedDescendants = 0;
|
||||
const state: ProcessTreeAccumulator = {
|
||||
nodes,
|
||||
children,
|
||||
eventsUnmatched: 0,
|
||||
hasReExec: false,
|
||||
hasReparenting: false,
|
||||
shortLivedDescendants: 0,
|
||||
};
|
||||
|
||||
const sorted = [...events].sort((a, b) => a.at_ms - b.at_ms);
|
||||
|
||||
for (const event of sorted) {
|
||||
eventsConsumed++;
|
||||
let node = nodes.get(event.pid);
|
||||
|
||||
switch (event.type) {
|
||||
case "spawn": {
|
||||
if (!node) {
|
||||
node = {
|
||||
pid: event.pid,
|
||||
ppid: event.ppid,
|
||||
process_name: event.process_name,
|
||||
executable: event.executable,
|
||||
arguments: event.arguments,
|
||||
children: [],
|
||||
spawn_time_ms: event.at_ms,
|
||||
exit_time_ms: null,
|
||||
exit_code: null,
|
||||
is_re_exec: false,
|
||||
is_reparented: false,
|
||||
previous_ppid: null,
|
||||
};
|
||||
nodes.set(event.pid, node);
|
||||
}
|
||||
if (event.ppid !== null) {
|
||||
const parentChildren = children.get(event.ppid) ?? [];
|
||||
parentChildren.push(event.pid);
|
||||
children.set(event.ppid, parentChildren);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "exit": {
|
||||
if (node) {
|
||||
node.exit_time_ms = event.at_ms;
|
||||
node.exit_code = event.exit_code;
|
||||
if (
|
||||
node.spawn_time_ms !== null &&
|
||||
event.at_ms - node.spawn_time_ms < 100
|
||||
)
|
||||
shortLivedDescendants++;
|
||||
} else {
|
||||
eventsUnmatched++;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "re_exec": {
|
||||
if (node) {
|
||||
node.is_re_exec = true;
|
||||
node.executable = event.executable ?? node.executable;
|
||||
node.arguments = event.arguments;
|
||||
hasReExec = true;
|
||||
} else {
|
||||
eventsUnmatched++;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "reparent": {
|
||||
if (node) {
|
||||
node.previous_ppid = node.ppid;
|
||||
node.ppid = event.ppid;
|
||||
node.is_reparented = true;
|
||||
hasReparenting = true;
|
||||
} else {
|
||||
eventsUnmatched++;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "signal":
|
||||
case "name_change":
|
||||
case "thread_create":
|
||||
case "thread_exit":
|
||||
// These events are recorded but don't modify the tree structure
|
||||
break;
|
||||
}
|
||||
applyProcessTreeEvent(event, state);
|
||||
}
|
||||
|
||||
// Attach children to nodes
|
||||
@@ -182,10 +192,10 @@ export function reconstructProcessTree(
|
||||
root_pid: rootPid,
|
||||
processes: [...nodes.values()],
|
||||
events_consumed: eventsConsumed,
|
||||
events_unmatched: eventsUnmatched,
|
||||
short_lived_descendants: shortLivedDescendants,
|
||||
has_re_exec: hasReExec,
|
||||
has_reparenting: hasReparenting,
|
||||
events_unmatched: state.eventsUnmatched,
|
||||
short_lived_descendants: state.shortLivedDescendants,
|
||||
has_re_exec: state.hasReExec,
|
||||
has_reparenting: state.hasReparenting,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -240,7 +240,7 @@ const comparisonChangeSchema = z.strictObject({
|
||||
right: valueAvailabilitySchema,
|
||||
left_source_range: sourceRangeSchema.nullable(),
|
||||
right_source_range: sourceRangeSchema.nullable(),
|
||||
evidence_links: z.tuple([evidenceIdSchema, evidenceIdSchema]),
|
||||
evidence_links: z.array(evidenceIdSchema).length(2),
|
||||
limitations: z.array(boundedTextSchema).max(20),
|
||||
});
|
||||
|
||||
@@ -285,7 +285,7 @@ export const javaScriptExportShapeComparisonResultSchema = z.strictObject({
|
||||
omitted_candidates: z.number().int().min(0),
|
||||
omitted_changes: z.number().int().min(0),
|
||||
}),
|
||||
evidence_links: z.tuple([evidenceIdSchema, evidenceIdSchema]),
|
||||
evidence_links: z.array(evidenceIdSchema).length(2),
|
||||
limitations: z.array(boundedTextSchema).max(1_000),
|
||||
runtime_validation: z.strictObject({
|
||||
recommended_tool: z.literal("run_controlled_replay"),
|
||||
|
||||
@@ -218,7 +218,21 @@ export const reconstructionReadinessInputSchema = z.strictObject({
|
||||
closure_history: z.array(closureObservationSchema).min(2).max(1_000),
|
||||
delegation_checks: z.array(delegationCheckSchema).min(1).max(1_000),
|
||||
replay: replaySchema,
|
||||
stages: z.array(stageSchema).max(20),
|
||||
stages: z
|
||||
.array(stageSchema)
|
||||
.length(9)
|
||||
.superRefine((stages, context) => {
|
||||
const seen = new Set<string>();
|
||||
stages.forEach((stage, index) => {
|
||||
if (seen.has(stage.stage_id))
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: [index, "stage_id"],
|
||||
message: "Readiness stage IDs must be unique",
|
||||
});
|
||||
seen.add(stage.stage_id);
|
||||
});
|
||||
}),
|
||||
});
|
||||
|
||||
const findingSchema = z.strictObject({
|
||||
@@ -256,7 +270,21 @@ export const reconstructionReadinessReportSchema = z.strictObject({
|
||||
cleanup_leak_count: z.number().int().min(0),
|
||||
nondeterministic_replay_count: z.number().int().min(0),
|
||||
}),
|
||||
stages: z.array(stageSchema).max(20),
|
||||
stages: z
|
||||
.array(stageSchema)
|
||||
.length(9)
|
||||
.superRefine((stages, context) => {
|
||||
const seen = new Set<string>();
|
||||
stages.forEach((stage, index) => {
|
||||
if (seen.has(stage.stage_id))
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: [index, "stage_id"],
|
||||
message: "Readiness stage IDs must be unique",
|
||||
});
|
||||
seen.add(stage.stage_id);
|
||||
});
|
||||
}),
|
||||
findings: z.array(findingSchema).max(10_000),
|
||||
evidence_links: z.array(evidenceIdSchema).max(100_000),
|
||||
snapshot: reconstructionReadinessInputSchema,
|
||||
|
||||
File diff suppressed because one or more lines are too long
+151
-77
@@ -96,84 +96,46 @@ const installSessionToolAvailability = (
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Construct one MCP server without acquiring subprocess resources.
|
||||
* Supplying a session adds target lifecycle tools; omitting it retains the
|
||||
* fixed-target seam used by focused tests and embedders.
|
||||
*/
|
||||
export const createServer = (
|
||||
analysis: AnalysisOperationPort,
|
||||
session?: BinarySessionPort,
|
||||
options: CreateServerOptions = {},
|
||||
): McpServer => {
|
||||
const startedAt = new Date().toISOString();
|
||||
const logger = options.logger ?? silentLogger;
|
||||
const permissionAuthority =
|
||||
options.permissionAuthority?.createConnectionAuthority();
|
||||
const processCaptureStateCodec =
|
||||
createRequestStateCodec<ProcessCaptureElicitationState>({
|
||||
key: randomBytes(32),
|
||||
ttlSeconds: PROCESS_CAPTURE_ELICITATION_POLICY.stateTtlSeconds,
|
||||
});
|
||||
const server = new McpServer(
|
||||
{
|
||||
name: PRODUCT_IDENTITY.mcpServerKey,
|
||||
version: PRODUCT_IDENTITY.packageVersion,
|
||||
},
|
||||
{
|
||||
capabilities: {
|
||||
tools: { listChanged: true },
|
||||
resources: { listChanged: true, subscribe: true },
|
||||
},
|
||||
inputRequired: {
|
||||
maxRounds: 3,
|
||||
roundTimeoutMs: PROCESS_CAPTURE_ELICITATION_POLICY.roundTimeoutMs,
|
||||
},
|
||||
requestState: { verify: processCaptureStateCodec.verify },
|
||||
instructions:
|
||||
session === undefined
|
||||
? ACTIVE_TARGET_INSTRUCTIONS
|
||||
: TARGET_FREE_INSTRUCTIONS,
|
||||
},
|
||||
);
|
||||
const dynamicTools = installSessionToolAvailability(server, session, options);
|
||||
server.server.onclose = () => {
|
||||
permissionAuthority?.clearSessionGrants();
|
||||
};
|
||||
if (dynamicTools !== undefined)
|
||||
server.server.oninitialized = () => server.sendToolListChanged();
|
||||
session?.onAvailabilityChanged?.(() => server.sendToolListChanged());
|
||||
registerServerIdentityResource(server, startedAt);
|
||||
const toolLogger = logger.child({ layer: "server" });
|
||||
const { activeTarget, recordEvidence, recordEvidenceWithUnknown } =
|
||||
createSessionRecorders(server, session);
|
||||
const processCaptureElicitation = {
|
||||
stateCodec: processCaptureStateCodec,
|
||||
supported: (context: {
|
||||
readonly mcpReq: {
|
||||
readonly envelope?: Readonly<Record<string, unknown>>;
|
||||
};
|
||||
}) => {
|
||||
const envelope = context.mcpReq.envelope;
|
||||
const version = envelope?.[PROTOCOL_VERSION_META_KEY];
|
||||
const capabilities = envelope?.[CLIENT_CAPABILITIES_META_KEY];
|
||||
return (
|
||||
typeof version === "string" &&
|
||||
PROCESS_CAPTURE_ELICITATION_POLICY.protocolVersions.some(
|
||||
(supported) => supported === version,
|
||||
) &&
|
||||
isRecord(capabilities) &&
|
||||
isRecord(capabilities.elicitation) &&
|
||||
capabilities.elicitation.form !== undefined
|
||||
);
|
||||
},
|
||||
now: Date.now,
|
||||
consumedNonces: new Map<string, number>(),
|
||||
};
|
||||
type ProcessCaptureElicitation = {
|
||||
readonly stateCodec: ReturnType<
|
||||
typeof createRequestStateCodec<ProcessCaptureElicitationState>
|
||||
>;
|
||||
readonly supported: (context: {
|
||||
readonly mcpReq: {
|
||||
readonly envelope?: Readonly<Record<string, unknown>>;
|
||||
};
|
||||
}) => boolean;
|
||||
readonly now: typeof Date.now;
|
||||
readonly consumedNonces: Map<string, number>;
|
||||
};
|
||||
|
||||
const createProcessCaptureElicitation = (
|
||||
stateCodec: ProcessCaptureElicitation["stateCodec"],
|
||||
): ProcessCaptureElicitation => ({
|
||||
stateCodec,
|
||||
supported: (context) => {
|
||||
const envelope = context.mcpReq.envelope;
|
||||
const version = envelope?.[PROTOCOL_VERSION_META_KEY];
|
||||
const capabilities = envelope?.[CLIENT_CAPABILITIES_META_KEY];
|
||||
return (
|
||||
typeof version === "string" &&
|
||||
PROCESS_CAPTURE_ELICITATION_POLICY.protocolVersions.some(
|
||||
(supported) => supported === version,
|
||||
) &&
|
||||
isRecord(capabilities) &&
|
||||
isRecord(capabilities.elicitation) &&
|
||||
capabilities.elicitation.form !== undefined
|
||||
);
|
||||
},
|
||||
now: Date.now,
|
||||
consumedNonces: new Map<string, number>(),
|
||||
});
|
||||
|
||||
const createOptionalProviderLoader = (options: CreateServerOptions) => {
|
||||
let optionalProviders:
|
||||
| ReturnType<NonNullable<CreateServerOptions["loadOptionalProviders"]>>
|
||||
| undefined;
|
||||
const loadOptionalProviders = () => {
|
||||
return () => {
|
||||
optionalProviders ??= options
|
||||
.loadOptionalProviders?.()
|
||||
.catch((cause: unknown) => {
|
||||
@@ -182,7 +144,43 @@ export const createServer = (
|
||||
});
|
||||
return optionalProviders;
|
||||
};
|
||||
const lazyTools = new LazyToolCatalog(
|
||||
};
|
||||
|
||||
const createLazyToolCatalog = ({
|
||||
server,
|
||||
analysis,
|
||||
session,
|
||||
options,
|
||||
toolLogger,
|
||||
permissionAuthority,
|
||||
activeTarget,
|
||||
recordEvidence,
|
||||
recordEvidenceWithUnknown,
|
||||
availabilityPolicy,
|
||||
startedAt,
|
||||
processCaptureElicitation,
|
||||
}: {
|
||||
readonly server: McpServer;
|
||||
readonly analysis: AnalysisOperationPort;
|
||||
readonly session: BinarySessionPort | undefined;
|
||||
readonly options: CreateServerOptions;
|
||||
readonly toolLogger: Logger;
|
||||
readonly permissionAuthority: PermissionAuthority | undefined;
|
||||
readonly activeTarget: ReturnType<
|
||||
typeof createSessionRecorders
|
||||
>["activeTarget"];
|
||||
readonly recordEvidence: ReturnType<
|
||||
typeof createSessionRecorders
|
||||
>["recordEvidence"];
|
||||
readonly recordEvidenceWithUnknown: ReturnType<
|
||||
typeof createSessionRecorders
|
||||
>["recordEvidenceWithUnknown"];
|
||||
readonly availabilityPolicy: CreateServerOptions["availabilityPolicy"];
|
||||
readonly startedAt: string;
|
||||
readonly processCaptureElicitation: ProcessCaptureElicitation;
|
||||
}): LazyToolCatalog => {
|
||||
const loadOptionalProviders = createOptionalProviderLoader(options);
|
||||
return new LazyToolCatalog(
|
||||
server,
|
||||
async (kind) => {
|
||||
const needsObservationProviders =
|
||||
@@ -210,7 +208,7 @@ export const createServer = (
|
||||
activeTarget,
|
||||
recordEvidence,
|
||||
recordEvidenceWithUnknown,
|
||||
availabilityPolicy: dynamicTools?.policy,
|
||||
availabilityPolicy,
|
||||
startedAt,
|
||||
processCaptureElicitation,
|
||||
},
|
||||
@@ -218,6 +216,82 @@ export const createServer = (
|
||||
},
|
||||
session !== undefined,
|
||||
);
|
||||
};
|
||||
|
||||
const createMcpServer = (
|
||||
processCaptureStateCodec: ProcessCaptureElicitation["stateCodec"],
|
||||
session: BinarySessionPort | undefined,
|
||||
): McpServer =>
|
||||
new McpServer(
|
||||
{
|
||||
name: PRODUCT_IDENTITY.mcpServerKey,
|
||||
version: PRODUCT_IDENTITY.packageVersion,
|
||||
},
|
||||
{
|
||||
capabilities: {
|
||||
tools: { listChanged: true },
|
||||
resources: { listChanged: true, subscribe: true },
|
||||
},
|
||||
inputRequired: {
|
||||
maxRounds: 3,
|
||||
roundTimeoutMs: PROCESS_CAPTURE_ELICITATION_POLICY.roundTimeoutMs,
|
||||
},
|
||||
requestState: { verify: processCaptureStateCodec.verify },
|
||||
instructions:
|
||||
session === undefined
|
||||
? ACTIVE_TARGET_INSTRUCTIONS
|
||||
: TARGET_FREE_INSTRUCTIONS,
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* Construct one MCP server without acquiring subprocess resources.
|
||||
* Supplying a session adds target lifecycle tools; omitting it retains the
|
||||
* fixed-target seam used by focused tests and embedders.
|
||||
*/
|
||||
export const createServer = (
|
||||
analysis: AnalysisOperationPort,
|
||||
session?: BinarySessionPort,
|
||||
options: CreateServerOptions = {},
|
||||
): McpServer => {
|
||||
const startedAt = new Date().toISOString();
|
||||
const logger = options.logger ?? silentLogger;
|
||||
const permissionAuthority =
|
||||
options.permissionAuthority?.createConnectionAuthority();
|
||||
const processCaptureStateCodec =
|
||||
createRequestStateCodec<ProcessCaptureElicitationState>({
|
||||
key: randomBytes(32),
|
||||
ttlSeconds: PROCESS_CAPTURE_ELICITATION_POLICY.stateTtlSeconds,
|
||||
});
|
||||
const server = createMcpServer(processCaptureStateCodec, session);
|
||||
const dynamicTools = installSessionToolAvailability(server, session, options);
|
||||
server.server.onclose = () => {
|
||||
permissionAuthority?.clearSessionGrants();
|
||||
};
|
||||
if (dynamicTools !== undefined)
|
||||
server.server.oninitialized = () => server.sendToolListChanged();
|
||||
session?.onAvailabilityChanged?.(() => server.sendToolListChanged());
|
||||
registerServerIdentityResource(server, startedAt);
|
||||
const toolLogger = logger.child({ layer: "server" });
|
||||
const { activeTarget, recordEvidence, recordEvidenceWithUnknown } =
|
||||
createSessionRecorders(server, session);
|
||||
const processCaptureElicitation = createProcessCaptureElicitation(
|
||||
processCaptureStateCodec,
|
||||
);
|
||||
const lazyTools = createLazyToolCatalog({
|
||||
server,
|
||||
analysis,
|
||||
session,
|
||||
options,
|
||||
toolLogger,
|
||||
permissionAuthority,
|
||||
activeTarget,
|
||||
recordEvidence,
|
||||
recordEvidenceWithUnknown,
|
||||
availabilityPolicy: dynamicTools?.policy,
|
||||
startedAt,
|
||||
processCaptureElicitation,
|
||||
});
|
||||
lazyTools.register();
|
||||
registerGuidedPrompts(server, analysis, session);
|
||||
if (session !== undefined) {
|
||||
|
||||
@@ -10,11 +10,15 @@ import {
|
||||
exportEvidenceBundleInputSchema,
|
||||
importEvidenceBundleInputSchema,
|
||||
listUnknownsInputSchema,
|
||||
releaseEvidenceBundleInputSchema,
|
||||
snapshotEvidenceBundleInputSchema,
|
||||
SESSION_TOOL_CONTRACTS,
|
||||
verifyUnknownResolutionInputSchema,
|
||||
} from "../contracts/toolContracts.js";
|
||||
import type { EvidenceFilePolicy } from "../domain/evidenceBundle.js";
|
||||
import type {
|
||||
EvidenceBundle,
|
||||
EvidenceFilePolicy,
|
||||
} from "../domain/evidenceBundle.js";
|
||||
import {
|
||||
AnalysisProtocolError,
|
||||
PermissionRequiredError,
|
||||
@@ -35,6 +39,7 @@ interface EvidenceToolRegistration {
|
||||
readonly exportContract: (typeof SESSION_TOOL_CONTRACTS)[3];
|
||||
readonly importContract: (typeof SESSION_TOOL_CONTRACTS)[4];
|
||||
readonly snapshotContract: (typeof SESSION_TOOL_CONTRACTS)[19];
|
||||
readonly releaseContract: (typeof SESSION_TOOL_CONTRACTS)[20];
|
||||
readonly filePolicy: EvidenceFilePolicy;
|
||||
readonly permissionAuthority?: PermissionAuthority;
|
||||
}
|
||||
@@ -46,6 +51,72 @@ export const registerEvidenceTools = (
|
||||
registerExportEvidenceTool(registration);
|
||||
registerImportEvidenceTool(registration);
|
||||
registerSnapshotEvidenceTool(registration);
|
||||
registerReleaseEvidenceTool(registration);
|
||||
};
|
||||
|
||||
const registerReleaseEvidenceTool = ({
|
||||
server,
|
||||
session,
|
||||
releaseContract,
|
||||
permissionAuthority,
|
||||
}: EvidenceToolRegistration): void => {
|
||||
server.registerTool(
|
||||
releaseContract.name,
|
||||
toolRegistrationOptions(releaseContract),
|
||||
async (input) => {
|
||||
const parsed = safeParseToolInput(
|
||||
releaseEvidenceBundleInputSchema,
|
||||
input,
|
||||
releaseContract.name,
|
||||
);
|
||||
if (!parsed.ok) return toCallToolResult(parsed, releaseContract);
|
||||
const denied = await authorizeEvidenceWrite({
|
||||
authority: permissionAuthority,
|
||||
operationIdentity: `release_evidence:${parsed.value.bundle_digest}`,
|
||||
});
|
||||
if (denied !== undefined)
|
||||
return toCallToolResult(denied, releaseContract);
|
||||
const released = session.releaseEvidenceBundle(
|
||||
parsed.value.bundle_digest,
|
||||
);
|
||||
if (released)
|
||||
void server.server
|
||||
.sendResourceUpdated({
|
||||
uri: `rea://evidence-bundle/${parsed.value.bundle_digest}`,
|
||||
})
|
||||
.catch(() => undefined);
|
||||
return toCallToolResult(
|
||||
ok({
|
||||
bundle_digest: parsed.value.bundle_digest,
|
||||
released,
|
||||
}),
|
||||
releaseContract,
|
||||
);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const authorizeEvidenceWrite = async ({
|
||||
authority,
|
||||
operationIdentity,
|
||||
}: {
|
||||
readonly authority: PermissionAuthority | undefined;
|
||||
readonly operationIdentity: string;
|
||||
}): Promise<Result<never, AnalysisError> | undefined> => {
|
||||
if (authority === undefined) return undefined;
|
||||
const authorized = await authority.authorize(
|
||||
{
|
||||
capability: "evidence_write",
|
||||
roots: [],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
operation_identity: operationIdentity,
|
||||
},
|
||||
"write",
|
||||
);
|
||||
return authorized.ok ? undefined : permissionFailure(authorized);
|
||||
};
|
||||
|
||||
const registerExportEvidenceTool = ({
|
||||
@@ -119,6 +190,8 @@ const registerSnapshotEvidenceTool = ({
|
||||
bytes: snapshot.value.bytes,
|
||||
records: snapshot.value.records,
|
||||
unknowns: snapshot.value.unknowns,
|
||||
scope: snapshot.value.scope,
|
||||
survives_session: snapshot.value.survivesSession,
|
||||
bundle_uri: snapshot.value.uri,
|
||||
} as const;
|
||||
return toCallToolResult(ok(value), snapshotContract, {
|
||||
@@ -162,11 +235,20 @@ const registerImportEvidenceTool = ({
|
||||
if (denied !== undefined) return toCallToolResult(denied, importContract);
|
||||
const loaded = await readEvidenceBundle(path, filePolicy);
|
||||
if (!loaded.ok) return toCallToolResult(loaded, importContract);
|
||||
const retainedUnknownRevisions = new Set(
|
||||
session
|
||||
.exportEvidenceBundle()
|
||||
.unknowns.map((unknown) => unknownRevisionKey(unknown)),
|
||||
);
|
||||
const imported = session.importEvidenceBundle(loaded.value);
|
||||
return imported.ok
|
||||
? toCallToolResult(
|
||||
ok({
|
||||
imported: imported.value,
|
||||
unknowns_added: loaded.value.unknowns.filter(
|
||||
(unknown) =>
|
||||
!retainedUnknownRevisions.has(unknownRevisionKey(unknown)),
|
||||
).length,
|
||||
total: session.exportEvidenceBundle().records.length,
|
||||
}),
|
||||
importContract,
|
||||
@@ -176,6 +258,10 @@ const registerImportEvidenceTool = ({
|
||||
);
|
||||
};
|
||||
|
||||
const unknownRevisionKey = (
|
||||
unknown: EvidenceBundle["unknowns"][number],
|
||||
): string => `${unknown.unknown_id}:${String(unknown.revision)}`;
|
||||
|
||||
interface EvidenceAuthorizationInput {
|
||||
readonly authority: PermissionAuthority | undefined;
|
||||
readonly capability: "evidence_read" | "evidence_write";
|
||||
@@ -210,15 +296,12 @@ interface UnknownToolRegistration {
|
||||
}
|
||||
|
||||
/** Register residual-unknown query and mutation tools. */
|
||||
export const registerUnknownTools = ({
|
||||
const registerListUnknownsTool = ({
|
||||
server,
|
||||
session,
|
||||
contracts,
|
||||
}: UnknownToolRegistration): void => {
|
||||
const listContract = contracts[14];
|
||||
const recordContract = contracts[15];
|
||||
const updateContract = contracts[16];
|
||||
const verifyContract = contracts[17];
|
||||
server.registerTool(
|
||||
listContract.name,
|
||||
toolRegistrationOptions(listContract),
|
||||
@@ -267,6 +350,14 @@ export const registerUnknownTools = ({
|
||||
);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const registerRecordUnknownTool = ({
|
||||
server,
|
||||
session,
|
||||
contracts,
|
||||
}: UnknownToolRegistration): void => {
|
||||
const recordContract = contracts[15];
|
||||
server.registerTool(
|
||||
recordContract.name,
|
||||
toolRegistrationOptions(recordContract),
|
||||
@@ -291,6 +382,14 @@ export const registerUnknownTools = ({
|
||||
: toCallToolResult(result, recordContract);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const registerUpdateUnknownTool = ({
|
||||
server,
|
||||
session,
|
||||
contracts,
|
||||
}: UnknownToolRegistration): void => {
|
||||
const updateContract = contracts[16];
|
||||
server.registerTool(
|
||||
updateContract.name,
|
||||
toolRegistrationOptions(updateContract),
|
||||
@@ -321,6 +420,14 @@ export const registerUnknownTools = ({
|
||||
: toCallToolResult(result, updateContract);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const registerVerifyUnknownTool = ({
|
||||
server,
|
||||
session,
|
||||
contracts,
|
||||
}: UnknownToolRegistration): void => {
|
||||
const verifyContract = contracts[17];
|
||||
server.registerTool(
|
||||
verifyContract.name,
|
||||
toolRegistrationOptions(verifyContract),
|
||||
@@ -340,6 +447,15 @@ export const registerUnknownTools = ({
|
||||
);
|
||||
};
|
||||
|
||||
export const registerUnknownTools = (
|
||||
registration: UnknownToolRegistration,
|
||||
): void => {
|
||||
registerListUnknownsTool(registration);
|
||||
registerRecordUnknownTool(registration);
|
||||
registerUpdateUnknownTool(registration);
|
||||
registerVerifyUnknownTool(registration);
|
||||
};
|
||||
|
||||
const permissionFailure = (
|
||||
failure: Awaited<ReturnType<PermissionAuthority["authorize"]>>,
|
||||
): Result<never, AnalysisError> => {
|
||||
|
||||
@@ -329,8 +329,8 @@ const registerContextTools = (
|
||||
server: McpServer,
|
||||
session: BinarySessionPort,
|
||||
): void => {
|
||||
const navigationContract = SESSION_TOOL_CONTRACTS[20];
|
||||
const addressContract = SESSION_TOOL_CONTRACTS[21];
|
||||
const navigationContract = SESSION_TOOL_CONTRACTS[21];
|
||||
const addressContract = SESSION_TOOL_CONTRACTS[22];
|
||||
server.registerTool(
|
||||
navigationContract.name,
|
||||
toolRegistrationOptions(navigationContract),
|
||||
@@ -401,6 +401,7 @@ export const registerSessionTools = (
|
||||
reconstructionContract,
|
||||
] = SESSION_TOOL_CONTRACTS;
|
||||
const snapshotContract = SESSION_TOOL_CONTRACTS[19];
|
||||
const releaseContract = SESSION_TOOL_CONTRACTS[20];
|
||||
registerLifecycleTools({
|
||||
server,
|
||||
session,
|
||||
@@ -423,6 +424,7 @@ export const registerSessionTools = (
|
||||
exportContract,
|
||||
importContract,
|
||||
snapshotContract,
|
||||
releaseContract,
|
||||
filePolicy: evidenceFilePolicy,
|
||||
...(options.permissionAuthority === undefined
|
||||
? {}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { ToolContract } from "../contracts/toolContracts.js";
|
||||
import { applyToolInputJsonSchemaOverride } from "../contracts/toolSchemaJsonOverrides.js";
|
||||
|
||||
const ADVERTISED_INPUT_SCHEMAS = new WeakMap<
|
||||
z.ZodObject,
|
||||
@@ -60,7 +61,10 @@ const advertisedInputJsonSchema = (
|
||||
): Readonly<Record<string, unknown>> =>
|
||||
cachedJsonSchema(ADVERTISED_INPUT_SCHEMAS, contract.inputSchema, () => ({
|
||||
...describeProperties(
|
||||
closeObjectSchemas(inputJsonSchema(contract.inputSchema)),
|
||||
applyToolInputJsonSchemaOverride(
|
||||
contract.name,
|
||||
closeObjectSchemas(inputJsonSchema(contract.inputSchema)),
|
||||
),
|
||||
),
|
||||
examples: contract.examples.map(({ input }) => input),
|
||||
}));
|
||||
|
||||
Reference in New Issue
Block a user