fix(hopper): add bounded analysis recovery
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { AnalysisError } from "../domain/errors.js";
|
||||
import type { AnalysisClient, ExecutionOptions } from "./AnalysisProvider.js";
|
||||
|
||||
/** Close one provider client and normalize unexpected adapter rejection. */
|
||||
export const closeAnalysisClient = async (
|
||||
client: AnalysisClient,
|
||||
providerId: string,
|
||||
options: Pick<ExecutionOptions, "progress"> = {},
|
||||
): Promise<Result<null, AnalysisError>> => {
|
||||
try {
|
||||
if (client.closeWithOutcome !== undefined)
|
||||
return await client.closeWithOutcome(options);
|
||||
await client.close();
|
||||
return ok(null);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new ProviderCleanupError(
|
||||
providerId,
|
||||
["provider-client"],
|
||||
{ reason: "provider client close rejected unexpectedly" },
|
||||
{ cause },
|
||||
),
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -81,10 +81,29 @@ export interface ProviderRuntimeLineageSnapshot {
|
||||
readonly observation: ProcessLineageObservation;
|
||||
}
|
||||
|
||||
/** One provider's current serial-request activity, including detached callers. */
|
||||
export interface ProviderRequestActivitySnapshot {
|
||||
readonly provider: ProviderIdentity;
|
||||
readonly active: {
|
||||
readonly requestId: number;
|
||||
readonly operation: string;
|
||||
readonly elapsedMs: number;
|
||||
readonly timeoutMs: number;
|
||||
readonly callerState: "waiting" | "timed_out" | "cancelled";
|
||||
} | null;
|
||||
readonly queuedRequests: number;
|
||||
}
|
||||
|
||||
/** Provider session bound to exactly one parsed artifact. */
|
||||
export interface AnalysisClient extends AnalysisOperationPort {
|
||||
/** Retained token-verified process snapshots for dynamic providers this client started. */
|
||||
runtimeLineageSnapshots?(): readonly ProviderRuntimeLineageSnapshot[];
|
||||
/** Current provider work that may outlive a timed-out or cancelled caller. */
|
||||
requestActivitySnapshots?(): readonly ProviderRequestActivitySnapshot[];
|
||||
/** Close with a typed result when the provider can verify cleanup. */
|
||||
closeWithOutcome?(
|
||||
options?: Pick<ExecutionOptions, "progress">,
|
||||
): Promise<Result<null, AnalysisError>>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import type {
|
||||
AnalysisClient,
|
||||
AnalysisExecution,
|
||||
AnalysisClientFactory,
|
||||
ExecutionOptions,
|
||||
AnalysisProfileResolution,
|
||||
AnalysisProfileResolutionOptions,
|
||||
AnalysisOperationPort,
|
||||
@@ -37,6 +38,7 @@ import {
|
||||
type BinarySessionOpenOptions,
|
||||
} from "./BinarySessionOpen.js";
|
||||
import { prepareSessionExecution } from "./BinarySessionExecution.js";
|
||||
import { closeAnalysisClient } from "./AnalysisClientCleanup.js";
|
||||
export type { BinarySessionPort } from "./BinarySessionPort.js";
|
||||
const OFFICIAL_OPERATIONS: ReadonlySet<string> = new Set(
|
||||
OFFICIAL_TOOL_CONTRACTS.map(({ name }) => name),
|
||||
@@ -186,7 +188,17 @@ export class BinarySession
|
||||
await this.#drainCalls();
|
||||
const previous = this.#active;
|
||||
this.#active = undefined;
|
||||
await previous?.client.close();
|
||||
if (previous !== undefined) {
|
||||
const closed = await closeAnalysisClient(
|
||||
previous.client,
|
||||
previous.route.identity.id,
|
||||
);
|
||||
if (!closed.ok) {
|
||||
this.clearSessionRecords();
|
||||
this.#clearRuntimeAvailability();
|
||||
return closed;
|
||||
}
|
||||
}
|
||||
const runId = randomUUID();
|
||||
const client = route.createClient(target, { runId });
|
||||
const started = await client.execute("health", {}, options);
|
||||
@@ -226,15 +238,24 @@ export class BinarySession
|
||||
}
|
||||
|
||||
/** Close the active target, if any. */
|
||||
close(): Promise<Result<null, AnalysisError>> {
|
||||
close(
|
||||
options: Pick<ExecutionOptions, "progress"> = {},
|
||||
): Promise<Result<null, AnalysisError>> {
|
||||
return this.#serialize(async () => {
|
||||
const previous = this.#active;
|
||||
this.#active = undefined;
|
||||
await this.#drainCalls();
|
||||
await previous?.client.close();
|
||||
const closed =
|
||||
previous === undefined
|
||||
? ok(null)
|
||||
: await closeAnalysisClient(
|
||||
previous.client,
|
||||
previous.route.identity.id,
|
||||
options,
|
||||
);
|
||||
this.clearSessionRecords();
|
||||
this.#clearRuntimeAvailability();
|
||||
return ok(null);
|
||||
return closed;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -248,6 +269,8 @@ export class BinarySession
|
||||
runId: this.#active?.runId,
|
||||
runtimeLineageSnapshots:
|
||||
this.#active?.client.runtimeLineageSnapshots?.() ?? [],
|
||||
requestActivitySnapshots:
|
||||
this.#active?.client.requestActivitySnapshots?.() ?? [],
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ import type { ReconstructionCoverageWorkspace } from "../domain/reconstructionCo
|
||||
import type {
|
||||
AnalysisOperation,
|
||||
AnalysisOperationPort,
|
||||
ExecutionOptions,
|
||||
ProviderIdentity,
|
||||
} from "./AnalysisProvider.js";
|
||||
|
||||
@@ -37,7 +38,9 @@ export interface BinarySessionPort extends AnalysisOperationPort {
|
||||
readonly providerId?: AnalysisProviderSelector;
|
||||
},
|
||||
): Promise<Result<BinaryTarget, AnalysisError>>;
|
||||
close(): Promise<Result<null, AnalysisError>>;
|
||||
close(
|
||||
options?: Pick<ExecutionOptions, "progress">,
|
||||
): Promise<Result<null, AnalysisError>>;
|
||||
status(): JsonValue;
|
||||
activeTarget(): BinaryTarget | undefined;
|
||||
recordEvidence(
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import type {
|
||||
CapabilityDescriptor,
|
||||
ProviderRequestActivitySnapshot,
|
||||
ProviderRuntimeLineageSnapshot,
|
||||
} from "./AnalysisProvider.js";
|
||||
import type {
|
||||
@@ -19,6 +20,7 @@ interface BinarySessionStatusInput {
|
||||
>;
|
||||
readonly runId: string | undefined;
|
||||
readonly runtimeLineageSnapshots: readonly ProviderRuntimeLineageSnapshot[];
|
||||
readonly requestActivitySnapshots: readonly ProviderRequestActivitySnapshot[];
|
||||
}
|
||||
|
||||
/** Project internal provider routing state into the caller-visible session status. */
|
||||
@@ -29,6 +31,7 @@ export const binarySessionStatus = ({
|
||||
runtimeAvailability,
|
||||
runId,
|
||||
runtimeLineageSnapshots,
|
||||
requestActivitySnapshots,
|
||||
}: BinarySessionStatusInput): JsonValue => {
|
||||
const configuredProvider = router.configuredIdentity();
|
||||
const provider = providerSummary(configuredProvider);
|
||||
@@ -73,6 +76,7 @@ export const binarySessionStatus = ({
|
||||
run_id: runId,
|
||||
process_lineage: processLineageStatus(runtimeLineageSnapshots),
|
||||
},
|
||||
analysis_activity: requestActivityStatus(requestActivitySnapshots),
|
||||
};
|
||||
return target === undefined
|
||||
? { open: false, ...common }
|
||||
@@ -87,6 +91,42 @@ export const binarySessionStatus = ({
|
||||
};
|
||||
};
|
||||
|
||||
const requestActivityStatus = (
|
||||
snapshots: readonly ProviderRequestActivitySnapshot[],
|
||||
) => {
|
||||
const providers = snapshots
|
||||
.slice()
|
||||
.sort((left, right) => left.provider.id.localeCompare(right.provider.id))
|
||||
.map(({ provider, active, queuedRequests }) => ({
|
||||
provider: providerSummary(provider),
|
||||
active:
|
||||
active === null
|
||||
? null
|
||||
: {
|
||||
request_id: active.requestId,
|
||||
operation: active.operation,
|
||||
elapsed_ms: active.elapsedMs,
|
||||
timeout_ms: active.timeoutMs,
|
||||
caller_state: active.callerState,
|
||||
},
|
||||
queued_requests: queuedRequests,
|
||||
}));
|
||||
const active = snapshots.flatMap((snapshot) =>
|
||||
snapshot.active === null ? [] : [snapshot.active],
|
||||
);
|
||||
return {
|
||||
status:
|
||||
snapshots.length === 0
|
||||
? "not_observed"
|
||||
: active.some(({ callerState }) => callerState === "timed_out")
|
||||
? "timed_out_busy"
|
||||
: active.length > 0
|
||||
? "busy"
|
||||
: "idle",
|
||||
providers,
|
||||
};
|
||||
};
|
||||
|
||||
const providerSummary = ({
|
||||
id,
|
||||
name,
|
||||
|
||||
@@ -10,6 +10,7 @@ import type {
|
||||
CapabilityDescriptor,
|
||||
ProviderIdentity,
|
||||
} from "./AnalysisProvider.js";
|
||||
import { closeAnalysisClient } from "./AnalysisClientCleanup.js";
|
||||
|
||||
/** Synthetic compatibility identity for a deterministic provider set. */
|
||||
export const compositeProviderIdentity = (
|
||||
@@ -103,6 +104,16 @@ export class CompositeProvider implements AnalysisProvider {
|
||||
clients.set(provider, created);
|
||||
return created;
|
||||
};
|
||||
const closeWithOutcome: NonNullable<
|
||||
AnalysisClient["closeWithOutcome"]
|
||||
> = async (options) => {
|
||||
const outcomes = await Promise.all(
|
||||
[...clients.entries()].map(([provider, client]) =>
|
||||
closeAnalysisClient(client, provider.identity().id, options),
|
||||
),
|
||||
);
|
||||
return outcomes.find((outcome) => !outcome.ok) ?? ok(null);
|
||||
};
|
||||
return {
|
||||
execute: (operation, parameters, options) => {
|
||||
if (operation === "health")
|
||||
@@ -135,10 +146,15 @@ export class CompositeProvider implements AnalysisProvider {
|
||||
.sort((left, right) =>
|
||||
left.provider.id.localeCompare(right.provider.id),
|
||||
),
|
||||
requestActivitySnapshots: () =>
|
||||
[...clients.values()]
|
||||
.flatMap((client) => client.requestActivitySnapshots?.() ?? [])
|
||||
.sort((left, right) =>
|
||||
left.provider.id.localeCompare(right.provider.id),
|
||||
),
|
||||
closeWithOutcome,
|
||||
close: async () => {
|
||||
await Promise.allSettled(
|
||||
[...clients.values()].map(async (client) => client.close()),
|
||||
);
|
||||
await closeWithOutcome();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -49,6 +49,7 @@ export {
|
||||
type DirectAnalysisTool =
|
||||
| "binary_overview"
|
||||
| "procedure_pseudo_code"
|
||||
| "read_function_instructions"
|
||||
| "analyze_function"
|
||||
| "search_strings"
|
||||
| "search_procedures"
|
||||
|
||||
@@ -309,22 +309,24 @@ export class EnhancedTools {
|
||||
input: { detail: "concise" | "detailed"; limit: number },
|
||||
signal?: AbortSignal,
|
||||
): EnhancedResult {
|
||||
const [segmentsResult, documentsResult, procedures, stringsResult] =
|
||||
const [segmentsResult, documentsResult, proceduresResult, stringsResult] =
|
||||
await Promise.all([
|
||||
this.#call("list_segments", {}, signal),
|
||||
this.#call("list_documents", {}, signal),
|
||||
this.#allAddressed("list_procedures", signal),
|
||||
this.#call("list_strings", {}, signal),
|
||||
this.#call("list_procedures", { offset: 0, limit: 1 }, signal),
|
||||
this.#call("list_strings", { offset: 0, limit: 1 }, signal),
|
||||
]);
|
||||
if (!segmentsResult.ok) return segmentsResult;
|
||||
if (!documentsResult.ok) return documentsResult;
|
||||
if (!procedures.ok) return procedures;
|
||||
if (!proceduresResult.ok) return proceduresResult;
|
||||
if (!stringsResult.ok) return stringsResult;
|
||||
|
||||
const segments = parseSegments(segmentsResult.value);
|
||||
if (!segments.ok) return segments;
|
||||
const documents = parseDocuments(documentsResult.value);
|
||||
if (!documents.ok) return documents;
|
||||
const procedureCount = parseListCount(proceduresResult.value, "procedures");
|
||||
if (!procedureCount.ok) return procedureCount;
|
||||
const stringCount = parseListCount(stringsResult.value, "strings");
|
||||
if (!stringCount.ok) return stringCount;
|
||||
|
||||
@@ -339,7 +341,7 @@ export class EnhancedTools {
|
||||
: { name, start, end },
|
||||
),
|
||||
segment_count: segments.value.length,
|
||||
procedure_count: procedures.value.length,
|
||||
procedure_count: procedureCount.value,
|
||||
string_count: stringCount.value,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ export const registerCoreAnalysisCommands = (
|
||||
): void => {
|
||||
registerCoreCommands(cli, logger);
|
||||
registerFunctionCommand(cli, logger);
|
||||
registerInstructionsCommand(cli, logger);
|
||||
registerSearchCommand(cli, logger);
|
||||
registerXrefsCommand(cli, logger);
|
||||
registerTraceCommand(cli, logger);
|
||||
@@ -285,6 +286,54 @@ const registerFunctionCommand = (cli: CliInstance, logger: Logger): void => {
|
||||
});
|
||||
};
|
||||
|
||||
const registerInstructionsCommand = (
|
||||
cli: CliInstance,
|
||||
logger: Logger,
|
||||
): void => {
|
||||
cli.command(CLI_COMMANDS.instructions, {
|
||||
description: "Read one bounded raw-instruction window without decompiling",
|
||||
args: z.object({
|
||||
path: z.string().describe("App or program path"),
|
||||
address: z.string().describe("Procedure name or address"),
|
||||
}),
|
||||
options: z.object({
|
||||
offset: z
|
||||
.number()
|
||||
.int()
|
||||
.min(0)
|
||||
.max(100_000)
|
||||
.default(0)
|
||||
.describe("Zero-based instruction offset"),
|
||||
limit: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(500)
|
||||
.default(64)
|
||||
.describe("Maximum raw instructions to return"),
|
||||
snapshot: z
|
||||
.string()
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Load and update a local analysis snapshot"),
|
||||
provider: providerSelectionOption,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.instructions, () =>
|
||||
runDirectAnalysis(
|
||||
args.path,
|
||||
"read_function_instructions",
|
||||
{
|
||||
procedure: args.address,
|
||||
offset: options.offset,
|
||||
limit: options.limit,
|
||||
},
|
||||
directAnalysisOptions(logger, options.snapshot, options.provider),
|
||||
),
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
const registerSearchCommand = (cli: CliInstance, logger: Logger): void => {
|
||||
cli.command(CLI_COMMANDS.search, {
|
||||
description: "Search bounded analyzed strings or procedure names",
|
||||
|
||||
@@ -12,6 +12,7 @@ export const CLI_COMMANDS = Object.freeze({
|
||||
capabilities: "capabilities",
|
||||
providers: "providers",
|
||||
function: "function",
|
||||
instructions: "instructions",
|
||||
search: "search",
|
||||
importReferenceSource: "import-reference-source",
|
||||
inventoryArtifact: "inventory-artifact",
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { z } from "zod";
|
||||
|
||||
/** Provider-neutral input for one bounded raw function-instruction window. */
|
||||
export const functionInstructionInputSchema = z.object({
|
||||
procedure: z.string().describe("The procedure name or address"),
|
||||
offset: z.number().int().min(0).max(100_000).default(0),
|
||||
limit: z.number().int().min(1).max(500).default(64),
|
||||
document: z.string().optional().describe("The document name"),
|
||||
});
|
||||
@@ -17,6 +17,7 @@ export const TOOL_EXAMPLE_OVERRIDES: Readonly<
|
||||
procedure_callees: { procedure: "main" },
|
||||
procedure_callers: { procedure: "main" },
|
||||
procedure_info: { procedure: "main" },
|
||||
read_function_instructions: { procedure: "main" },
|
||||
procedure_references: { procedure: "main" },
|
||||
procedure_pseudo_code: { procedure: "main" },
|
||||
resolve_containing_procedure: { address: "0x1000" },
|
||||
|
||||
@@ -37,6 +37,7 @@ import {
|
||||
import type { ToolContract, ToolExample } from "./toolContractTypes.js";
|
||||
import { toolContractMetadata } from "./toolEffects.js";
|
||||
import { binarySessionInputSchema } from "./sessionStatusContract.js";
|
||||
import { functionInstructionInputSchema } from "./functionInstructionContract.js";
|
||||
|
||||
export { binarySessionInputSchema } from "./sessionStatusContract.js";
|
||||
|
||||
@@ -240,6 +241,11 @@ export const OFFICIAL_TOOL_CONTRACTS = [
|
||||
"Return bounded metadata for one procedure identified by symbol or address: entrypoint, signature, locals, size, and block count. Follow with decompilation or assembly for behavior.",
|
||||
z.object({ procedure, document }),
|
||||
),
|
||||
official(
|
||||
"read_function_instructions",
|
||||
"Read one offset-paginated window of raw instructions for an analyzed procedure without decompilation, caller discovery, or whole-program string/name scans. Use this fast path for instruction-level orientation; follow next_offset when truncated.",
|
||||
functionInstructionInputSchema,
|
||||
),
|
||||
official(
|
||||
"procedure_references",
|
||||
"Return a bounded set of raw incoming or outgoing reference edges for one procedure. Endpoint procedures are resolved only from provider containment; Ghidra preserves observed reference kinds while providers without kind authority mark them unavailable.",
|
||||
|
||||
@@ -60,6 +60,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
procedure_callees: evidence,
|
||||
procedure_callers: evidence,
|
||||
procedure_info: evidence,
|
||||
read_function_instructions: evidence,
|
||||
procedure_references: evidence,
|
||||
procedure_pseudo_code: evidence,
|
||||
resolve_containing_procedure: evidence,
|
||||
|
||||
@@ -6,7 +6,10 @@ import {
|
||||
} from "../domain/processCapture.js";
|
||||
import { evidenceBundleSchema } from "../domain/evidenceBundle.js";
|
||||
import { residualUnknownSchema } from "../domain/residualUnknown.js";
|
||||
import { referenceKindSchema } from "../domain/hopperValues.js";
|
||||
import {
|
||||
functionInstructionWindowSchema,
|
||||
referenceKindSchema,
|
||||
} from "../domain/hopperValues.js";
|
||||
import {
|
||||
demangleSwiftSchema,
|
||||
inspectMachoSchema,
|
||||
@@ -39,6 +42,7 @@ import { replayMachineRunOutputSchema } from "../domain/replayMachineRun.js";
|
||||
import { analysisErrorProjectionSchema } from "./errorSchemas.js";
|
||||
import {
|
||||
addressList,
|
||||
analysisActivity,
|
||||
addressedEntry,
|
||||
bounded,
|
||||
containingProcedureResolution,
|
||||
@@ -82,6 +86,7 @@ export const officialOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
|
||||
procedure_callees: resultOf(addressList),
|
||||
procedure_callers: resultOf(addressList),
|
||||
procedure_info: procedureInfoOutput,
|
||||
read_function_instructions: resultOf(functionInstructionWindowSchema),
|
||||
procedure_references: resultOf(
|
||||
z.object({
|
||||
procedure: procedureIdentity,
|
||||
@@ -297,6 +302,7 @@ export const sessionOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
|
||||
reasons: z.array(z.string()),
|
||||
remediation: z.string().nullable(),
|
||||
}),
|
||||
analysis_activity: analysisActivity,
|
||||
recommended_actions: z.array(z.string()),
|
||||
}),
|
||||
z.object({
|
||||
|
||||
@@ -140,6 +140,25 @@ const analysisRun = z
|
||||
})
|
||||
.nullable();
|
||||
|
||||
export const analysisActivity = z.object({
|
||||
status: z.enum(["not_observed", "idle", "busy", "timed_out_busy"]),
|
||||
providers: z.array(
|
||||
z.object({
|
||||
provider: providerIdentity,
|
||||
active: z
|
||||
.object({
|
||||
request_id: z.number().int().min(1),
|
||||
operation: z.string().min(1),
|
||||
elapsed_ms: z.number().int().min(0),
|
||||
timeout_ms: z.number().int().min(0),
|
||||
caller_state: z.enum(["waiting", "timed_out", "cancelled"]),
|
||||
})
|
||||
.nullable(),
|
||||
queued_requests: z.number().int().min(0),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
const providerRejectionCode: z.ZodType<ProviderRejectionCode> = z.enum(
|
||||
PROVIDER_REJECTION_CODES,
|
||||
);
|
||||
@@ -225,6 +244,7 @@ export const sessionProvider = z.object({
|
||||
providers: z.array(providerIdentity),
|
||||
capabilities: z.array(providerCapability),
|
||||
analysis_run: analysisRun,
|
||||
analysis_activity: analysisActivity,
|
||||
analysis_provider_binding: z
|
||||
.object({
|
||||
provider: providerIdentity,
|
||||
|
||||
@@ -60,6 +60,7 @@ export const projectAnalysisError = (
|
||||
};
|
||||
|
||||
const errorCode = (error: AnalysisError): AnalysisErrorProjection["code"] => {
|
||||
if (error.cleanupIncomplete) return "cleanup_incomplete";
|
||||
if (error instanceof ReplayPlanStaleError) return "plan_stale";
|
||||
if (error instanceof PermissionRequiredError) return "permission_required";
|
||||
if (error instanceof ProviderSelectionError)
|
||||
@@ -295,6 +296,12 @@ const providerErrorDetails = (
|
||||
return {
|
||||
provider_id: error.providerId,
|
||||
operation: error.operation,
|
||||
...(error.cleanupIncomplete
|
||||
? {
|
||||
cleanup: "incomplete",
|
||||
resources: [...error.cleanupResources],
|
||||
}
|
||||
: {}),
|
||||
...(error.diagnostics === undefined
|
||||
? {}
|
||||
: { diagnostics: error.diagnostics }),
|
||||
|
||||
@@ -143,6 +143,18 @@ const boundedSchema = <T extends z.ZodType>(item: T) =>
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/** Provider-neutral bounded raw-instruction window for one analyzed function. */
|
||||
export const functionInstructionWindowSchema = z
|
||||
.object({
|
||||
procedure: procedureIdentitySchema,
|
||||
instructions: boundedSchema(z.string()),
|
||||
instructions_scanned: z.number().int().min(0),
|
||||
instruction_scan_truncated: z.boolean(),
|
||||
limitations: z.array(z.string()),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const availableReferenceKindSchema = z
|
||||
.object({
|
||||
available: z.literal(true),
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { ProviderAdapterError } from "./errors.js";
|
||||
import type { JsonValue } from "./jsonValue.js";
|
||||
|
||||
/** Provider resources could not be proven closed after bounded cleanup. */
|
||||
export class ProviderCleanupError extends ProviderAdapterError {
|
||||
override readonly cleanupIncomplete = true;
|
||||
override readonly cleanupResources: readonly string[];
|
||||
override readonly userMessage =
|
||||
"Provider cleanup could not be fully confirmed. Review the reported local resources before opening another target.";
|
||||
|
||||
constructor(
|
||||
providerId: string,
|
||||
resources: readonly string[],
|
||||
diagnostics: Readonly<Record<string, JsonValue>>,
|
||||
options?: ErrorOptions,
|
||||
) {
|
||||
super(providerId, "close_binary", { ...options, diagnostics });
|
||||
this.cleanupResources = [...resources];
|
||||
}
|
||||
}
|
||||
@@ -17,4 +17,4 @@ export const GHIDRA_MAX_QUEUED_REQUESTS = 32;
|
||||
/** Maximum encoded response line accepted from the Java bridge. */
|
||||
export const GHIDRA_MAX_LINE_BYTES = 1024 * 1024;
|
||||
/** Version of REA's Java bridge handshake and request protocol. */
|
||||
export const GHIDRA_BRIDGE_VERSION = 4;
|
||||
export const GHIDRA_BRIDGE_VERSION = 5;
|
||||
|
||||
@@ -2,6 +2,7 @@ import { z } from "zod";
|
||||
|
||||
import { AnalysisInputError, AnalysisOutputError } from "../domain/errors.js";
|
||||
import {
|
||||
functionInstructionWindowSchema,
|
||||
functionDossierSchema,
|
||||
type FunctionDossier,
|
||||
} from "../domain/hopperValues.js";
|
||||
@@ -24,6 +25,7 @@ export const GHIDRA_FUNCTION_OPERATIONS = [
|
||||
"procedure_callers",
|
||||
"procedure_info",
|
||||
"procedure_pseudo_code",
|
||||
"read_function_instructions",
|
||||
"procedure_references",
|
||||
"xrefs",
|
||||
] as const;
|
||||
@@ -88,6 +90,13 @@ const inputSchemas = {
|
||||
procedure_callers: z.object(directProcedure).strict(),
|
||||
procedure_info: z.object(directProcedure).strict(),
|
||||
procedure_pseudo_code: z.object(directProcedure).strict(),
|
||||
read_function_instructions: z
|
||||
.object({
|
||||
...directProcedure,
|
||||
offset: z.number().int().min(0).max(100_000).default(0),
|
||||
limit: z.number().int().min(1).max(500).default(64),
|
||||
})
|
||||
.strict(),
|
||||
procedure_references: z
|
||||
.object({
|
||||
...directProcedure,
|
||||
@@ -281,6 +290,9 @@ const ghidraFunctionDossier = functionDossierSchema.superRefine(
|
||||
});
|
||||
},
|
||||
);
|
||||
const ghidraFunctionInstructionWindow = functionInstructionWindowSchema
|
||||
.extend({ procedure: procedureIdentity })
|
||||
.strict();
|
||||
|
||||
const resultSchemas = {
|
||||
analyze_function: ghidraFunctionDossier,
|
||||
@@ -289,6 +301,7 @@ const resultSchemas = {
|
||||
procedure_callers: z.array(ghidraCanonicalAddressSchema),
|
||||
procedure_info: procedureInfo,
|
||||
procedure_pseudo_code: z.string().nullable(),
|
||||
read_function_instructions: ghidraFunctionInstructionWindow,
|
||||
procedure_references: procedureReferences,
|
||||
xrefs: z.array(ghidraCanonicalAddressSchema),
|
||||
} satisfies Readonly<Record<GhidraFunctionOperation, z.ZodType>>;
|
||||
|
||||
@@ -49,6 +49,7 @@ const PAGINATED_OPERATIONS: ReadonlySet<string> = new Set([
|
||||
"search_procedures",
|
||||
"search_strings",
|
||||
"procedure_references",
|
||||
"read_function_instructions",
|
||||
"analyze_function",
|
||||
]);
|
||||
const SEARCH_OPERATIONS: ReadonlySet<string> = new Set([
|
||||
@@ -119,6 +120,12 @@ export const limitationsFor = (operation: string): readonly string[] => {
|
||||
"Pseudocode is Ghidra decompiler output, not original source and not text-equivalent to Hopper output; each decompile has a 30-second native deadline.",
|
||||
"External functions and functions without an analyzable body return null; other decompiler failures remain explicit.",
|
||||
];
|
||||
case "read_function_instructions":
|
||||
return [
|
||||
...common,
|
||||
"This bounded fast path reads only the requested function instruction window and does not invoke the decompiler or whole-program string/name inventories.",
|
||||
"Instruction text is Ghidra-specific and does not claim textual equivalence with Hopper output.",
|
||||
];
|
||||
case "procedure_assembly":
|
||||
return [
|
||||
...common,
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
import type { Socket } from "node:net";
|
||||
|
||||
import type { ProgressReporter } from "../application/ProgressReporter.js";
|
||||
import type { AnalysisError, HopperError } from "../domain/errors.js";
|
||||
import { HopperProcessError } from "../domain/errors.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import type { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
|
||||
import type { ProcessCleanupResult } from "../process/ProcessOwnership.js";
|
||||
import type { ProviderProcessSupervisor } from "../process/ProviderProcess.js";
|
||||
import type { BridgeLaunch } from "./BridgeLauncher.js";
|
||||
import {
|
||||
createOwnedHopperShutdownDiagnostic,
|
||||
type HopperDiagnostic,
|
||||
providerCleanupFailure,
|
||||
} from "./HopperDiagnostics.js";
|
||||
import type { HopperRequestActivity } from "./HopperRequestQueue.js";
|
||||
import {
|
||||
isHopperCleanupRequired,
|
||||
isHopperShutdownAcknowledgement,
|
||||
} from "./HopperSessionValues.js";
|
||||
|
||||
interface CleanupIssue {
|
||||
readonly resource: string;
|
||||
readonly reason: string;
|
||||
}
|
||||
|
||||
interface CleanupState {
|
||||
readonly issues: CleanupIssue[];
|
||||
readonly resources: Set<string>;
|
||||
cleanupResult: ProcessCleanupResult | undefined;
|
||||
shutdownConfirmed: boolean;
|
||||
ownedProcessStopped: boolean;
|
||||
}
|
||||
|
||||
export interface HopperCleanupInput {
|
||||
readonly socket: Socket | undefined;
|
||||
readonly launch: BridgeLaunch | undefined;
|
||||
readonly processSupervisor: ProviderProcessSupervisor | undefined;
|
||||
readonly runtimeRoot: PrivateRuntimeRoot | undefined;
|
||||
readonly activeRequest: HopperRequestActivity | null;
|
||||
readonly progress: ProgressReporter | undefined;
|
||||
readonly logger: Logger;
|
||||
readonly onDiagnostic: ((event: HopperDiagnostic) => void) | undefined;
|
||||
request(
|
||||
method: "shutdown" | "shutdown_document",
|
||||
): Promise<Result<JsonValue, HopperError>>;
|
||||
releaseTransport(socket: Socket | undefined): void;
|
||||
}
|
||||
|
||||
/** Close Hopper phases and retain every resource whose cleanup is unverified. */
|
||||
export const cleanupHopperSession = async (
|
||||
input: HopperCleanupInput,
|
||||
): Promise<Result<null, AnalysisError>> => {
|
||||
const state: CleanupState = {
|
||||
issues: [],
|
||||
resources: new Set(),
|
||||
cleanupResult: undefined,
|
||||
shutdownConfirmed: false,
|
||||
ownedProcessStopped: false,
|
||||
};
|
||||
await report(input.progress, 0, "requesting Hopper document shutdown");
|
||||
await requestShutdown(input, state);
|
||||
await report(input.progress, 0.35, "releasing Hopper bridge transport");
|
||||
input.releaseTransport(input.socket);
|
||||
await stopProcess(input, state);
|
||||
recordUnconfirmedDocument(input, state);
|
||||
await report(input.progress, 0.75, "removing Hopper private runtime files");
|
||||
await closeRuntimeRoot(input.runtimeRoot, state);
|
||||
return cleanupOutcome(input, state);
|
||||
};
|
||||
|
||||
const requestShutdown = async (
|
||||
input: HopperCleanupInput,
|
||||
state: CleanupState,
|
||||
): Promise<void> => {
|
||||
if (
|
||||
input.socket === undefined ||
|
||||
input.socket.destroyed ||
|
||||
input.activeRequest !== null
|
||||
) {
|
||||
if (input.activeRequest !== null)
|
||||
input.logger.warn(
|
||||
{
|
||||
method: input.activeRequest.operation,
|
||||
callerState: input.activeRequest.callerState,
|
||||
},
|
||||
"Hopper shutdown skipped because a bridge operation remained active",
|
||||
);
|
||||
return;
|
||||
}
|
||||
const shutdown = await input
|
||||
.request("shutdown")
|
||||
.catch(() => err(new HopperProcessError(null)));
|
||||
if (
|
||||
shutdown.ok &&
|
||||
isHopperCleanupRequired(shutdown.value) &&
|
||||
input.launch?.shutdownByCleanup === true &&
|
||||
input.launch.cleanup !== undefined
|
||||
) {
|
||||
state.cleanupResult = await input.launch
|
||||
.cleanup()
|
||||
.catch(providerCleanupFailure);
|
||||
if (!state.cleanupResult.cleaned) {
|
||||
state.shutdownConfirmed = await fallbackDocumentShutdown(input);
|
||||
state.cleanupResult = await input.launch
|
||||
.cleanup()
|
||||
.catch(providerCleanupFailure);
|
||||
}
|
||||
} else if (shutdown.ok) {
|
||||
state.shutdownConfirmed = isHopperShutdownAcknowledgement(shutdown.value);
|
||||
}
|
||||
if (
|
||||
!shutdown.ok ||
|
||||
(!state.shutdownConfirmed && state.cleanupResult === undefined)
|
||||
)
|
||||
input.logger.warn(
|
||||
{ status: shutdown.ok ? "invalid-acknowledgement" : "failed" },
|
||||
"Hopper document shutdown was not confirmed",
|
||||
);
|
||||
};
|
||||
|
||||
const fallbackDocumentShutdown = async (
|
||||
input: HopperCleanupInput,
|
||||
): Promise<boolean> => {
|
||||
const fallback = await input
|
||||
.request("shutdown_document")
|
||||
.catch(() => err(new HopperProcessError(null)));
|
||||
const confirmed =
|
||||
fallback.ok && isHopperShutdownAcknowledgement(fallback.value);
|
||||
if (!confirmed)
|
||||
input.logger.warn(
|
||||
{ status: fallback.ok ? "invalid-acknowledgement" : "failed" },
|
||||
"Hopper document shutdown fallback was not confirmed",
|
||||
);
|
||||
return confirmed;
|
||||
};
|
||||
|
||||
const stopProcess = async (
|
||||
input: HopperCleanupInput,
|
||||
state: CleanupState,
|
||||
): Promise<void> => {
|
||||
const supervisor = input.processSupervisor;
|
||||
if (supervisor === undefined) return;
|
||||
const stopped = await supervisor.stop(
|
||||
state.cleanupResult === undefined
|
||||
? {}
|
||||
: { cleanupResult: state.cleanupResult },
|
||||
);
|
||||
const diagnostic = createOwnedHopperShutdownDiagnostic(
|
||||
supervisor.launch,
|
||||
stopped,
|
||||
state.cleanupResult,
|
||||
);
|
||||
try {
|
||||
input.onDiagnostic?.(diagnostic);
|
||||
} catch {
|
||||
// Diagnostic consumers cannot change the already-observed cleanup result.
|
||||
}
|
||||
input.logger.info(diagnostic, "Owned Hopper launcher shutdown completed");
|
||||
if (stopped.status !== "incomplete") {
|
||||
state.ownedProcessStopped = stopped.status !== "not-owned";
|
||||
return;
|
||||
}
|
||||
const processGroupId = supervisor.launch.ownership?.processGroupId;
|
||||
const resource =
|
||||
processGroupId === undefined
|
||||
? "hopper-process"
|
||||
: `process-group:${String(processGroupId)}`;
|
||||
state.resources.add(resource);
|
||||
state.issues.push({ resource, reason: stopped.reason });
|
||||
input.logger.warn(
|
||||
{ reason: stopped.reason },
|
||||
"Owned launcher cleanup failed closed",
|
||||
);
|
||||
};
|
||||
|
||||
const recordUnconfirmedDocument = (
|
||||
input: HopperCleanupInput,
|
||||
state: CleanupState,
|
||||
): void => {
|
||||
if (
|
||||
(input.socket === undefined && input.launch === undefined) ||
|
||||
state.shutdownConfirmed ||
|
||||
state.ownedProcessStopped
|
||||
)
|
||||
return;
|
||||
state.resources.add("hopper-document");
|
||||
state.issues.push({
|
||||
resource: "hopper-document",
|
||||
reason:
|
||||
input.activeRequest === null
|
||||
? "authenticated shutdown acknowledgement was not observed"
|
||||
: `bridge operation ${input.activeRequest.operation} remained active after caller ${input.activeRequest.callerState}`,
|
||||
});
|
||||
};
|
||||
|
||||
const closeRuntimeRoot = async (
|
||||
runtimeRoot: PrivateRuntimeRoot | undefined,
|
||||
state: CleanupState,
|
||||
): Promise<void> => {
|
||||
try {
|
||||
await runtimeRoot?.close();
|
||||
} catch (cause: unknown) {
|
||||
const resource = runtimeRoot?.path ?? "hopper-runtime-root";
|
||||
state.resources.add(resource);
|
||||
state.issues.push({
|
||||
resource,
|
||||
reason:
|
||||
cause instanceof Error
|
||||
? cause.message
|
||||
: "private runtime root cleanup failed",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const cleanupOutcome = (
|
||||
input: HopperCleanupInput,
|
||||
state: CleanupState,
|
||||
): Result<null, AnalysisError> => {
|
||||
if (state.issues.length === 0) return ok(null);
|
||||
return err(
|
||||
new ProviderCleanupError("hopper", [...state.resources], {
|
||||
issues: cleanupIssueDetails(state.issues),
|
||||
...(input.runtimeRoot === undefined
|
||||
? {}
|
||||
: { runtime_root: input.runtimeRoot.path }),
|
||||
...(input.activeRequest === null
|
||||
? {}
|
||||
: { active_request: activityDetails(input.activeRequest) }),
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const cleanupIssueDetails = (issues: readonly CleanupIssue[]): JsonValue =>
|
||||
issues.map((issue) => ({
|
||||
resource: issue.resource,
|
||||
reason: issue.reason,
|
||||
}));
|
||||
|
||||
const activityDetails = (activity: HopperRequestActivity): JsonValue => ({
|
||||
request_id: activity.requestId,
|
||||
operation: activity.operation,
|
||||
elapsed_ms: activity.elapsedMs,
|
||||
timeout_ms: activity.timeoutMs,
|
||||
caller_state: activity.callerState,
|
||||
queued_requests: activity.queuedRequests,
|
||||
});
|
||||
|
||||
const report = async (
|
||||
progress: ProgressReporter | undefined,
|
||||
completed: number,
|
||||
message: string,
|
||||
): Promise<void> => {
|
||||
await progress
|
||||
?.report({
|
||||
phase: "hopper_cleanup",
|
||||
completed,
|
||||
total: 1,
|
||||
message,
|
||||
})
|
||||
.catch(() => undefined);
|
||||
};
|
||||
+86
-140
@@ -6,6 +6,7 @@ import { join } from "node:path";
|
||||
|
||||
import {
|
||||
HopperCancelledError,
|
||||
type AnalysisError,
|
||||
type HopperError,
|
||||
HopperProcessError,
|
||||
HopperProtocolError,
|
||||
@@ -16,36 +17,35 @@ import {
|
||||
} from "../domain/errors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import type { ProgressReporter } from "../application/ProgressReporter.js";
|
||||
import { silentLogger, type Logger } from "../logger.js";
|
||||
import { PendingOperations } from "../process/PendingOperations.js";
|
||||
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
|
||||
import { ProviderStartupDeadline } from "../process/ProviderDeadline.js";
|
||||
import type { ProcessCleanupResult } from "../process/ProcessOwnership.js";
|
||||
import { ProviderRunLineage } from "../process/ProviderRunLineage.js";
|
||||
import {
|
||||
type ProviderProcessDiagnostic,
|
||||
ProviderProcessSupervisor,
|
||||
} from "../process/ProviderProcess.js";
|
||||
import type { BridgeLaunch, BridgeLauncher } from "./BridgeLauncher.js";
|
||||
import type { HopperDiagnostic } from "./HopperDiagnostics.js";
|
||||
import { cleanupHopperSession } from "./HopperCleanup.js";
|
||||
import {
|
||||
createOwnedHopperShutdownDiagnostic,
|
||||
type HopperDiagnostic,
|
||||
providerCleanupFailure,
|
||||
} from "./HopperDiagnostics.js";
|
||||
import {
|
||||
isHopperCleanupRequired,
|
||||
isHopperShutdownAcknowledgement,
|
||||
parseHopperServerInfo,
|
||||
type HopperServerInfo,
|
||||
} from "./HopperSessionValues.js";
|
||||
import { connectHopperSocketOnce } from "./HopperSocketConnection.js";
|
||||
import { hopperLauncherFailureDiagnostic } from "./HopperProcessDiagnostic.js";
|
||||
import { parseResponseLine, responseResult } from "./protocol.js";
|
||||
import {
|
||||
HopperRequestQueue,
|
||||
type HopperRequestActivity,
|
||||
} from "./HopperRequestQueue.js";
|
||||
import { HopperResponseStream } from "./HopperResponseStream.js";
|
||||
import { responseResult } from "./protocol.js";
|
||||
|
||||
export type { HopperServerInfo } from "./HopperSessionValues.js";
|
||||
|
||||
const MAX_LINE_BYTES = 10 * 1024 * 1024;
|
||||
const SHUTDOWN_TIMEOUT_MS = 30_000;
|
||||
const MAX_QUEUED_REQUESTS = 64;
|
||||
const SESSION_ROOT = process.platform === "darwin" ? "/tmp" : tmpdir();
|
||||
|
||||
/** Dependencies, deadlines, and redacted diagnostics for one bridge client. */
|
||||
@@ -72,10 +72,8 @@ export class HopperClient {
|
||||
Pick<HopperClientOptions, "requestTimeoutMs" | "startupTimeoutMs">
|
||||
> &
|
||||
HopperClientOptions;
|
||||
readonly #pending = new PendingOperations<
|
||||
number,
|
||||
Result<JsonValue, HopperError>
|
||||
>();
|
||||
readonly #requests: HopperRequestQueue;
|
||||
readonly #responses: HopperResponseStream;
|
||||
readonly #logger: Logger;
|
||||
#socket: Socket | undefined;
|
||||
#launch: BridgeLaunch | undefined;
|
||||
@@ -84,15 +82,14 @@ export class HopperClient {
|
||||
#token: string | undefined;
|
||||
readonly #lineage = new ProviderRunLineage();
|
||||
#nextId = 1;
|
||||
#buffer = "";
|
||||
#closing = false;
|
||||
#launcherExitCode: number | null | undefined;
|
||||
#launcherFailureDiagnostic: HopperStartupDiagnostic | undefined;
|
||||
#startupController: AbortController | undefined;
|
||||
#startPromise: Promise<Result<HopperServerInfo, HopperError>> | undefined;
|
||||
#closePromise: Promise<void> | undefined;
|
||||
#closePromise: Promise<Result<null, AnalysisError>> | undefined;
|
||||
readonly #onSocketData = (chunk: string): void => {
|
||||
this.#onData(chunk);
|
||||
this.#responses.push(chunk);
|
||||
};
|
||||
readonly #onSocketError = (): void => {
|
||||
this.#failAll(new HopperProcessError(null));
|
||||
@@ -108,6 +105,30 @@ export class HopperClient {
|
||||
requestTimeoutMs: options.requestTimeoutMs ?? 30_000,
|
||||
startupTimeoutMs: options.startupTimeoutMs ?? 120_000,
|
||||
};
|
||||
this.#requests = new HopperRequestQueue(
|
||||
MAX_QUEUED_REQUESTS,
|
||||
({ id, method, params }, failed) => {
|
||||
const socket = this.#socket;
|
||||
const token = this.#token;
|
||||
if (socket === undefined || socket.destroyed || token === undefined) {
|
||||
failed();
|
||||
return;
|
||||
}
|
||||
socket.write(
|
||||
`${JSON.stringify({ id, token, method, params })}\n`,
|
||||
(cause) => {
|
||||
if (cause !== undefined && cause !== null) failed();
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
this.#responses = new HopperResponseStream({
|
||||
accept: (response) =>
|
||||
this.#requests.accept(response.id, responseResult(response)),
|
||||
hasQueued: (id) => this.#requests.hasQueued(id),
|
||||
nextRequestId: () => this.#nextId,
|
||||
abort: (message, cause) => this.#abortProtocol(message, cause),
|
||||
});
|
||||
}
|
||||
|
||||
/** Latest token-verified launcher lineage for the active run. */
|
||||
@@ -115,6 +136,11 @@ export class HopperClient {
|
||||
return this.#lineage.snapshot();
|
||||
}
|
||||
|
||||
/** Observe a request that still occupies Hopper after caller timeout/cancel. */
|
||||
requestActivity(): HopperRequestActivity | null {
|
||||
return this.#requests.activity();
|
||||
}
|
||||
|
||||
/** Launch the bridge once and complete its authenticated health handshake. */
|
||||
start(signal?: AbortSignal): Promise<Result<HopperServerInfo, HopperError>> {
|
||||
if (this.#closePromise !== undefined) {
|
||||
@@ -251,6 +277,7 @@ export class HopperClient {
|
||||
options: {
|
||||
readonly signal?: AbortSignal;
|
||||
readonly timeoutMs?: number;
|
||||
readonly progress?: ProgressReporter;
|
||||
} = {},
|
||||
): Promise<Result<JsonValue, HopperError>> {
|
||||
const started = await this.start(options.signal);
|
||||
@@ -260,11 +287,18 @@ export class HopperClient {
|
||||
|
||||
/** Stop the bridge, settle outstanding requests, and remove session artifacts. */
|
||||
close(): Promise<void> {
|
||||
return this.closeWithOutcome().then(() => undefined);
|
||||
}
|
||||
|
||||
/** Stop the bridge and report whether every owned resource was verified clean. */
|
||||
closeWithOutcome(
|
||||
options: { readonly progress?: ProgressReporter } = {},
|
||||
): Promise<Result<null, AnalysisError>> {
|
||||
const starting = this.#startPromise;
|
||||
const controller = this.#startupController;
|
||||
controller?.abort();
|
||||
this.#closePromise ??= Promise.resolve().then(() =>
|
||||
this.#close(starting, controller),
|
||||
this.#close(starting, controller, options),
|
||||
);
|
||||
return this.#closePromise;
|
||||
}
|
||||
@@ -272,10 +306,11 @@ export class HopperClient {
|
||||
async #close(
|
||||
starting: Promise<Result<HopperServerInfo, HopperError>> | undefined,
|
||||
controller: AbortController | undefined,
|
||||
): Promise<void> {
|
||||
options: { readonly progress?: ProgressReporter },
|
||||
): Promise<Result<null, AnalysisError>> {
|
||||
try {
|
||||
await starting?.catch(() => undefined);
|
||||
await this.#cleanup();
|
||||
return await this.#cleanup(options);
|
||||
} finally {
|
||||
if (this.#startPromise === starting) this.#startPromise = undefined;
|
||||
if (this.#startupController === controller) {
|
||||
@@ -285,92 +320,41 @@ export class HopperClient {
|
||||
}
|
||||
}
|
||||
|
||||
async #cleanup(): Promise<void> {
|
||||
async #cleanup(
|
||||
options: { readonly progress?: ProgressReporter } = {},
|
||||
): Promise<Result<null, AnalysisError>> {
|
||||
this.#closing = true;
|
||||
try {
|
||||
const socket = this.#socket;
|
||||
let cleanupResult: ProcessCleanupResult | undefined;
|
||||
if (socket !== undefined && !socket.destroyed) {
|
||||
const shutdown = await this.#request(
|
||||
"shutdown",
|
||||
{},
|
||||
{ timeoutMs: SHUTDOWN_TIMEOUT_MS },
|
||||
).catch(() => err(new HopperProcessError(null)));
|
||||
if (
|
||||
shutdown.ok &&
|
||||
isHopperCleanupRequired(shutdown.value) &&
|
||||
this.#launch?.shutdownByCleanup === true &&
|
||||
this.#launch.cleanup !== undefined
|
||||
) {
|
||||
cleanupResult = await this.#launch
|
||||
.cleanup()
|
||||
.catch(providerCleanupFailure);
|
||||
if (!cleanupResult.cleaned) {
|
||||
await this.#fallbackDocumentShutdown();
|
||||
cleanupResult = await this.#launch
|
||||
.cleanup()
|
||||
.catch(providerCleanupFailure);
|
||||
}
|
||||
} else if (
|
||||
!shutdown.ok ||
|
||||
!isHopperShutdownAcknowledgement(shutdown.value)
|
||||
)
|
||||
this.#logger.warn(
|
||||
{ status: shutdown.ok ? "invalid-acknowledgement" : "failed" },
|
||||
"Hopper document shutdown was not confirmed",
|
||||
);
|
||||
}
|
||||
this.#failAll(new HopperProcessError(null));
|
||||
if (socket !== undefined) this.#detachSocket(socket);
|
||||
socket?.destroy();
|
||||
return await cleanupHopperSession({
|
||||
socket: this.#socket,
|
||||
launch: this.#launch,
|
||||
processSupervisor: this.#process,
|
||||
runtimeRoot: this.#runtimeRoot,
|
||||
activeRequest: this.#requests.activity(),
|
||||
progress: options.progress,
|
||||
logger: this.#logger,
|
||||
onDiagnostic: this.#options.onDiagnostic,
|
||||
request: (method) =>
|
||||
this.#request(method, {}, { timeoutMs: SHUTDOWN_TIMEOUT_MS }),
|
||||
releaseTransport: (socket) => {
|
||||
this.#failAll(new HopperProcessError(null));
|
||||
if (socket !== undefined) this.#detachSocket(socket);
|
||||
socket?.destroy();
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
this.#socket = undefined;
|
||||
if (this.#process !== undefined) {
|
||||
const stopped = await this.#process.stop(
|
||||
cleanupResult === undefined ? {} : { cleanupResult },
|
||||
);
|
||||
const diagnostic = createOwnedHopperShutdownDiagnostic(
|
||||
this.#process.launch,
|
||||
stopped,
|
||||
cleanupResult,
|
||||
);
|
||||
this.#options.onDiagnostic?.(diagnostic);
|
||||
this.#logger.info(
|
||||
diagnostic,
|
||||
"Owned Hopper launcher shutdown completed",
|
||||
);
|
||||
if (stopped.status === "incomplete")
|
||||
this.#logger.warn(
|
||||
{ reason: stopped.reason },
|
||||
"Owned launcher cleanup failed closed",
|
||||
);
|
||||
}
|
||||
this.#process = undefined;
|
||||
this.#launch = undefined;
|
||||
const runtimeRoot = this.#runtimeRoot;
|
||||
this.#runtimeRoot = undefined;
|
||||
await runtimeRoot?.close();
|
||||
this.#token = undefined;
|
||||
this.#buffer = "";
|
||||
this.#responses.reset();
|
||||
this.#launcherExitCode = undefined;
|
||||
this.#launcherFailureDiagnostic = undefined;
|
||||
} finally {
|
||||
this.#closing = false;
|
||||
}
|
||||
}
|
||||
|
||||
async #fallbackDocumentShutdown(): Promise<void> {
|
||||
const fallback = await this.#request(
|
||||
"shutdown_document",
|
||||
{},
|
||||
{ timeoutMs: SHUTDOWN_TIMEOUT_MS },
|
||||
).catch(() => err(new HopperProcessError(null)));
|
||||
if (!fallback.ok || !isHopperShutdownAcknowledgement(fallback.value))
|
||||
this.#logger.warn(
|
||||
{ status: fallback.ok ? "invalid-acknowledgement" : "failed" },
|
||||
"Hopper document shutdown fallback was not confirmed",
|
||||
);
|
||||
}
|
||||
|
||||
async #connect(
|
||||
socketPath: string,
|
||||
deadline: ProviderStartupDeadline,
|
||||
@@ -413,7 +397,11 @@ export class HopperClient {
|
||||
async #request(
|
||||
method: string,
|
||||
params: JsonValue,
|
||||
options: { readonly signal?: AbortSignal; readonly timeoutMs?: number },
|
||||
options: {
|
||||
readonly signal?: AbortSignal;
|
||||
readonly timeoutMs?: number;
|
||||
readonly progress?: ProgressReporter;
|
||||
},
|
||||
): Promise<Result<JsonValue, HopperError>> {
|
||||
const socket = this.#socket;
|
||||
const token = this.#token;
|
||||
@@ -425,20 +413,11 @@ export class HopperClient {
|
||||
const id = this.#nextId++;
|
||||
const startedAt = performance.now();
|
||||
const timeoutMs = options.timeoutMs ?? this.#options.requestTimeoutMs;
|
||||
const response = this.#pending.wait(id, {
|
||||
const result = await this.#requests.run(id, method, params, {
|
||||
timeoutMs,
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
timeoutValue: () => err(new HopperTimeoutError(timeoutMs)),
|
||||
cancelledValue: () => err(new HopperCancelledError()),
|
||||
...(options.progress !== undefined ? { progress: options.progress } : {}),
|
||||
});
|
||||
socket.write(
|
||||
`${JSON.stringify({ id, token, method, params })}\n`,
|
||||
(cause) => {
|
||||
if (cause !== undefined && cause !== null)
|
||||
this.#pending.settle(id, err(new HopperProcessError(null)));
|
||||
},
|
||||
);
|
||||
const result = await response;
|
||||
this.#logger[result.ok ? "debug" : "warn"](
|
||||
{
|
||||
method,
|
||||
@@ -501,46 +480,13 @@ export class HopperClient {
|
||||
);
|
||||
}
|
||||
|
||||
#onData(chunk: string): void {
|
||||
this.#buffer += chunk;
|
||||
let newline = this.#buffer.indexOf("\n");
|
||||
while (newline >= 0) {
|
||||
const line = this.#buffer.slice(0, newline).trim();
|
||||
this.#buffer = this.#buffer.slice(newline + 1);
|
||||
if (Buffer.byteLength(line) > MAX_LINE_BYTES) {
|
||||
this.#abortProtocol("Hopper response exceeded the maximum line size");
|
||||
return;
|
||||
}
|
||||
if (line.length > 0) this.#onLine(line);
|
||||
newline = this.#buffer.indexOf("\n");
|
||||
}
|
||||
if (Buffer.byteLength(this.#buffer) > MAX_LINE_BYTES) {
|
||||
this.#abortProtocol("Hopper response exceeded the maximum line size");
|
||||
}
|
||||
}
|
||||
|
||||
#onLine(line: string): void {
|
||||
const parsed = parseResponseLine(line);
|
||||
if (!parsed.ok) {
|
||||
this.#abortProtocol(parsed.error.message, parsed.error);
|
||||
return;
|
||||
}
|
||||
if (!this.#pending.has(parsed.value.id)) {
|
||||
if (parsed.value.id >= this.#nextId) {
|
||||
this.#abortProtocol("Hopper returned an unknown response id");
|
||||
}
|
||||
return;
|
||||
}
|
||||
this.#pending.settle(parsed.value.id, responseResult(parsed.value));
|
||||
}
|
||||
|
||||
#abortProtocol(message: string, cause?: Error): void {
|
||||
this.#failAll(new HopperProtocolError(message, { cause }));
|
||||
this.#socket?.destroy();
|
||||
}
|
||||
|
||||
#failAll(error: HopperError): void {
|
||||
this.#pending.failAll(() => err(error));
|
||||
this.#requests.failAll(error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -255,6 +255,26 @@ export class HopperProvider implements AnalysisProviderCandidate {
|
||||
? []
|
||||
: [{ provider: executionProvider, observation }];
|
||||
},
|
||||
requestActivitySnapshots: () => {
|
||||
const activity = client.requestActivity();
|
||||
return [
|
||||
{
|
||||
provider: executionProvider,
|
||||
active:
|
||||
activity === null
|
||||
? null
|
||||
: {
|
||||
requestId: activity.requestId,
|
||||
operation: activity.operation,
|
||||
elapsedMs: activity.elapsedMs,
|
||||
timeoutMs: activity.timeoutMs,
|
||||
callerState: activity.callerState,
|
||||
},
|
||||
queuedRequests: activity?.queuedRequests ?? 0,
|
||||
},
|
||||
];
|
||||
},
|
||||
closeWithOutcome: (options) => client.closeWithOutcome(options),
|
||||
close: () => client.close(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
import { performance } from "node:perf_hooks";
|
||||
|
||||
import type { ProgressReporter } from "../application/ProgressReporter.js";
|
||||
import {
|
||||
HopperCancelledError,
|
||||
type HopperError,
|
||||
HopperProcessError,
|
||||
HopperProtocolError,
|
||||
HopperTimeoutError,
|
||||
} from "../domain/errors.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { err, type Result } from "../domain/result.js";
|
||||
|
||||
export type HopperRequestResult = Result<JsonValue, HopperError>;
|
||||
|
||||
export interface HopperRequestQueueOptions {
|
||||
readonly signal?: AbortSignal;
|
||||
readonly timeoutMs: number;
|
||||
readonly progress?: ProgressReporter;
|
||||
}
|
||||
|
||||
export interface HopperRequestActivity {
|
||||
readonly requestId: number;
|
||||
readonly operation: string;
|
||||
readonly elapsedMs: number;
|
||||
readonly timeoutMs: number;
|
||||
readonly callerState: "waiting" | "timed_out" | "cancelled";
|
||||
readonly queuedRequests: number;
|
||||
}
|
||||
|
||||
type RequestSender = (
|
||||
request: {
|
||||
readonly id: number;
|
||||
readonly method: string;
|
||||
readonly params: JsonValue;
|
||||
},
|
||||
failed: () => void,
|
||||
) => void;
|
||||
|
||||
interface QueuedRequest {
|
||||
readonly id: number;
|
||||
readonly method: string;
|
||||
readonly params: JsonValue;
|
||||
readonly signal: AbortSignal | undefined;
|
||||
readonly timeoutMs: number;
|
||||
readonly deadline: number;
|
||||
readonly progress: ProgressReporter | undefined;
|
||||
readonly resolve: (result: HopperRequestResult) => void;
|
||||
readonly timer: NodeJS.Timeout;
|
||||
readonly onAbort: (() => void) | undefined;
|
||||
callerState: "waiting" | "timed_out" | "cancelled";
|
||||
callerSettled: boolean;
|
||||
startedAt: number | undefined;
|
||||
heartbeat: NodeJS.Timeout | undefined;
|
||||
}
|
||||
|
||||
/** Bounded FIFO that keeps the wire serialized until Hopper actually replies. */
|
||||
export class HopperRequestQueue {
|
||||
readonly #queue: QueuedRequest[] = [];
|
||||
#active: QueuedRequest | undefined;
|
||||
|
||||
constructor(
|
||||
private readonly maximum: number,
|
||||
private readonly send: RequestSender,
|
||||
) {}
|
||||
|
||||
/** Queue one request, counting queue wait against its caller deadline. */
|
||||
run(
|
||||
id: number,
|
||||
method: string,
|
||||
params: JsonValue,
|
||||
options: HopperRequestQueueOptions,
|
||||
): Promise<HopperRequestResult> {
|
||||
if (options.signal?.aborted === true)
|
||||
return Promise.resolve(err(new HopperCancelledError()));
|
||||
if (options.timeoutMs <= 0)
|
||||
return Promise.resolve(err(new HopperTimeoutError(options.timeoutMs)));
|
||||
if (this.#size() >= this.maximum)
|
||||
return Promise.resolve(
|
||||
err(
|
||||
new HopperProtocolError(
|
||||
`Hopper serial request queue reached its ${String(this.maximum)}-request limit`,
|
||||
),
|
||||
),
|
||||
);
|
||||
return new Promise((resolve) => {
|
||||
let entry: QueuedRequest;
|
||||
const onAbort =
|
||||
options.signal === undefined ? undefined : () => this.#cancel(entry);
|
||||
const timer = setTimeout(() => this.#timeout(entry), options.timeoutMs);
|
||||
entry = {
|
||||
id,
|
||||
method,
|
||||
params,
|
||||
signal: options.signal,
|
||||
timeoutMs: options.timeoutMs,
|
||||
deadline: performance.now() + options.timeoutMs,
|
||||
progress: options.progress,
|
||||
resolve,
|
||||
timer,
|
||||
onAbort,
|
||||
callerState: "waiting",
|
||||
callerSettled: false,
|
||||
startedAt: undefined,
|
||||
heartbeat: undefined,
|
||||
};
|
||||
this.#queue.push(entry);
|
||||
if (onAbort !== undefined)
|
||||
options.signal?.addEventListener("abort", onAbort, { once: true });
|
||||
if (this.#active !== undefined || this.#queue.length > 1)
|
||||
this.#report(
|
||||
entry,
|
||||
`${method} queued behind ${String(this.#size() - 1)} Hopper request(s)`,
|
||||
);
|
||||
this.#drain();
|
||||
});
|
||||
}
|
||||
|
||||
/** Settle the active wire request. False identifies an unexpected response id. */
|
||||
accept(id: number, result: HopperRequestResult): boolean {
|
||||
const entry = this.#active;
|
||||
if (entry === undefined || entry.id !== id) return false;
|
||||
this.#releaseWire(entry);
|
||||
if (!entry.callerSettled) this.#settleCaller(entry, result, "waiting");
|
||||
this.#active = undefined;
|
||||
this.#drain();
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Fail the active wire request and every request still waiting in the FIFO. */
|
||||
failAll(error: HopperError): void {
|
||||
const active = this.#active;
|
||||
this.#active = undefined;
|
||||
if (active !== undefined) {
|
||||
this.#releaseWire(active);
|
||||
if (!active.callerSettled)
|
||||
this.#settleCaller(active, err(error), "waiting");
|
||||
}
|
||||
for (const entry of this.#queue.splice(0))
|
||||
this.#settleCaller(entry, err(error), "waiting");
|
||||
}
|
||||
|
||||
/** Snapshot the one request still occupying Hopper's serial Python thread. */
|
||||
activity(): HopperRequestActivity | null {
|
||||
const active = this.#active;
|
||||
if (active === undefined || active.startedAt === undefined) return null;
|
||||
return {
|
||||
requestId: active.id,
|
||||
operation: active.method,
|
||||
elapsedMs: Math.max(0, Math.round(performance.now() - active.startedAt)),
|
||||
timeoutMs: active.timeoutMs,
|
||||
callerState: active.callerState,
|
||||
queuedRequests: this.#queue.length,
|
||||
};
|
||||
}
|
||||
|
||||
/** Return whether an id belongs to a request that has not crossed the wire. */
|
||||
hasQueued(id: number): boolean {
|
||||
return this.#queue.some((entry) => entry.id === id);
|
||||
}
|
||||
|
||||
/** Number of caller requests waiting behind the active bridge operation. */
|
||||
queuedCount(): number {
|
||||
return this.#queue.length;
|
||||
}
|
||||
|
||||
#size(): number {
|
||||
return this.#queue.length + (this.#active === undefined ? 0 : 1);
|
||||
}
|
||||
|
||||
#drain(): void {
|
||||
if (this.#active !== undefined) return;
|
||||
const entry = this.#queue.shift();
|
||||
if (entry === undefined) return;
|
||||
const remaining = entry.deadline - performance.now();
|
||||
if (entry.signal?.aborted === true || remaining <= 0) {
|
||||
this.#settleCaller(
|
||||
entry,
|
||||
entry.signal?.aborted === true
|
||||
? err(new HopperCancelledError())
|
||||
: err(new HopperTimeoutError(entry.timeoutMs)),
|
||||
entry.signal?.aborted === true ? "cancelled" : "timed_out",
|
||||
);
|
||||
this.#drain();
|
||||
return;
|
||||
}
|
||||
this.#active = entry;
|
||||
entry.startedAt = performance.now();
|
||||
this.#report(entry, `${entry.method} started on Hopper's serial bridge`);
|
||||
entry.heartbeat = setInterval(() => {
|
||||
if (entry.callerSettled || entry.startedAt === undefined) return;
|
||||
const elapsed = Math.round(performance.now() - entry.startedAt);
|
||||
this.#report(
|
||||
entry,
|
||||
`${entry.method} is still running in Hopper (${String(elapsed)} ms elapsed)`,
|
||||
);
|
||||
}, 1_000);
|
||||
try {
|
||||
this.send(
|
||||
{ id: entry.id, method: entry.method, params: entry.params },
|
||||
() => this.accept(entry.id, err(new HopperProcessError(null))),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
this.accept(
|
||||
entry.id,
|
||||
err(new HopperProtocolError("Hopper socket write failed", { cause })),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#timeout(entry: QueuedRequest): void {
|
||||
if (entry.callerSettled) return;
|
||||
if (this.#active === entry) {
|
||||
this.#settleCaller(
|
||||
entry,
|
||||
err(new HopperTimeoutError(entry.timeoutMs)),
|
||||
"timed_out",
|
||||
);
|
||||
return;
|
||||
}
|
||||
const index = this.#queue.indexOf(entry);
|
||||
if (index < 0) return;
|
||||
this.#queue.splice(index, 1);
|
||||
this.#settleCaller(
|
||||
entry,
|
||||
err(new HopperTimeoutError(entry.timeoutMs)),
|
||||
"timed_out",
|
||||
);
|
||||
}
|
||||
|
||||
#cancel(entry: QueuedRequest): void {
|
||||
if (entry.callerSettled) return;
|
||||
if (this.#active === entry) {
|
||||
this.#settleCaller(entry, err(new HopperCancelledError()), "cancelled");
|
||||
return;
|
||||
}
|
||||
const index = this.#queue.indexOf(entry);
|
||||
if (index < 0) return;
|
||||
this.#queue.splice(index, 1);
|
||||
this.#settleCaller(entry, err(new HopperCancelledError()), "cancelled");
|
||||
}
|
||||
|
||||
#settleCaller(
|
||||
entry: QueuedRequest,
|
||||
result: HopperRequestResult,
|
||||
callerState: QueuedRequest["callerState"],
|
||||
): void {
|
||||
if (entry.callerSettled) return;
|
||||
entry.callerSettled = true;
|
||||
entry.callerState = callerState;
|
||||
if (this.#active === entry && entry.heartbeat !== undefined) {
|
||||
clearInterval(entry.heartbeat);
|
||||
entry.heartbeat = undefined;
|
||||
}
|
||||
clearTimeout(entry.timer);
|
||||
if (entry.signal !== undefined && entry.onAbort !== undefined)
|
||||
entry.signal.removeEventListener("abort", entry.onAbort);
|
||||
entry.resolve(result);
|
||||
}
|
||||
|
||||
#releaseWire(entry: QueuedRequest): void {
|
||||
if (entry.heartbeat !== undefined) clearInterval(entry.heartbeat);
|
||||
entry.heartbeat = undefined;
|
||||
clearTimeout(entry.timer);
|
||||
if (entry.signal !== undefined && entry.onAbort !== undefined)
|
||||
entry.signal.removeEventListener("abort", entry.onAbort);
|
||||
}
|
||||
|
||||
#report(entry: QueuedRequest, message: string): void {
|
||||
void entry.progress
|
||||
?.report({
|
||||
phase: "hopper_request",
|
||||
completed: 0,
|
||||
total: 1,
|
||||
message,
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { parseResponseLine, type HopperResponse } from "./protocol.js";
|
||||
|
||||
const MAX_LINE_BYTES = 10 * 1024 * 1024;
|
||||
|
||||
export interface HopperResponseStreamOptions {
|
||||
readonly accept: (response: HopperResponse) => boolean;
|
||||
readonly hasQueued: (id: number) => boolean;
|
||||
readonly nextRequestId: () => number;
|
||||
readonly abort: (message: string, cause?: Error) => void;
|
||||
}
|
||||
|
||||
/** Incrementally validates bounded Hopper NDJSON response frames. */
|
||||
export class HopperResponseStream {
|
||||
#buffer = "";
|
||||
|
||||
constructor(readonly options: HopperResponseStreamOptions) {}
|
||||
|
||||
push(chunk: string): void {
|
||||
this.#buffer += chunk;
|
||||
let newline = this.#buffer.indexOf("\n");
|
||||
while (newline >= 0) {
|
||||
const line = this.#buffer.slice(0, newline).trim();
|
||||
this.#buffer = this.#buffer.slice(newline + 1);
|
||||
if (Buffer.byteLength(line) > MAX_LINE_BYTES) {
|
||||
this.options.abort("Hopper response exceeded the maximum line size");
|
||||
return;
|
||||
}
|
||||
if (line.length > 0 && !this.#acceptLine(line)) return;
|
||||
newline = this.#buffer.indexOf("\n");
|
||||
}
|
||||
if (Buffer.byteLength(this.#buffer) > MAX_LINE_BYTES) {
|
||||
this.options.abort("Hopper response exceeded the maximum line size");
|
||||
}
|
||||
}
|
||||
|
||||
reset(): void {
|
||||
this.#buffer = "";
|
||||
}
|
||||
|
||||
#acceptLine(line: string): boolean {
|
||||
const parsed = parseResponseLine(line);
|
||||
if (!parsed.ok) {
|
||||
this.options.abort(parsed.error.message, parsed.error);
|
||||
return false;
|
||||
}
|
||||
if (this.options.accept(parsed.value)) return true;
|
||||
if (
|
||||
parsed.value.id >= this.options.nextRequestId() ||
|
||||
this.options.hasQueued(parsed.value.id)
|
||||
) {
|
||||
this.options.abort("Hopper returned an unknown response id");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { ProgressReporter } from "../application/ProgressReporter.js";
|
||||
|
||||
/** Report one lifecycle operation start through the shared monotonic boundary. */
|
||||
export const reportLifecycleStart = (
|
||||
progress: ProgressReporter,
|
||||
phase: string,
|
||||
message = "started",
|
||||
): Promise<void> => progress.report({ phase, completed: 0, total: 1, message });
|
||||
|
||||
/** Report one lifecycle operation's terminal disposition. */
|
||||
export const reportLifecycleEnd = (
|
||||
progress: ProgressReporter,
|
||||
phase: string,
|
||||
succeeded: boolean,
|
||||
): Promise<void> =>
|
||||
progress.report({
|
||||
phase,
|
||||
completed: 1,
|
||||
total: 1,
|
||||
message: succeeded ? "completed" : "failed",
|
||||
terminal: true,
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { PermissionAuthority } from "../application/PermissionAuthority.js";
|
||||
import {
|
||||
AnalysisProtocolError,
|
||||
PermissionRequiredError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import { err, type Result } from "../domain/result.js";
|
||||
|
||||
/** Preserve a typed permission denial or contain an unexpected authority error. */
|
||||
export const permissionFailure = (
|
||||
failure: Awaited<ReturnType<PermissionAuthority["authorize"]>>,
|
||||
): Result<never, AnalysisError> => {
|
||||
if (failure.ok)
|
||||
return err(new AnalysisProtocolError("Expected a denied permission"));
|
||||
return err(
|
||||
failure.error instanceof PermissionRequiredError
|
||||
? failure.error
|
||||
: new AnalysisProtocolError(failure.error.message, {
|
||||
cause: failure.error,
|
||||
}),
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,93 @@
|
||||
import { writeAnalysisSnapshot } from "../application/AnalysisSnapshotFiles.js";
|
||||
import { closeBinaryInputSchema } from "../contracts/sessionLifecycleInputs.js";
|
||||
import { ok } from "../domain/result.js";
|
||||
import {
|
||||
reportLifecycleEnd,
|
||||
reportLifecycleStart,
|
||||
} from "./lifecycleProgress.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
import { toCallToolResult } from "./toolResult.js";
|
||||
import { mcpProgressReporter } from "./mcpProgress.js";
|
||||
import { permissionFailure } from "./permissionFailure.js";
|
||||
import type { LifecycleToolRegistration } from "./registerSessionTools.js";
|
||||
import { safeParseToolInput } from "./toolInputValidation.js";
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
|
||||
/** Register provider cleanup and optional pre-close snapshot persistence. */
|
||||
export const registerCloseLifecycleTool = ({
|
||||
server,
|
||||
session,
|
||||
logger,
|
||||
contracts: [, closeContract],
|
||||
snapshotFilePolicy,
|
||||
permissionAuthority,
|
||||
}: LifecycleToolRegistration): void => {
|
||||
server.registerTool(
|
||||
closeContract.name,
|
||||
toolRegistrationOptions(closeContract),
|
||||
async (input, context) => {
|
||||
const parsedInput = safeParseToolInput(
|
||||
closeBinaryInputSchema,
|
||||
input,
|
||||
closeContract.name,
|
||||
);
|
||||
if (!parsedInput.ok) return toCallToolResult(parsedInput, closeContract);
|
||||
const parsed = parsedInput.value;
|
||||
const progress = mcpProgressReporter(context);
|
||||
if (parsed.snapshot_path === undefined) {
|
||||
await reportLifecycleStart(progress, closeContract.name);
|
||||
const closed = await logToolExecution(logger, closeContract.name, () =>
|
||||
session.close({ progress }),
|
||||
);
|
||||
await reportLifecycleEnd(progress, closeContract.name, closed.ok);
|
||||
server.sendToolListChanged();
|
||||
return toCallToolResult(closed, closeContract);
|
||||
}
|
||||
if (permissionAuthority !== undefined) {
|
||||
const authorized = await permissionAuthority.authorize(
|
||||
{
|
||||
capability: "snapshot_write",
|
||||
roots: [parsed.snapshot_path],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
operation_identity: `close_binary:snapshot:${parsed.snapshot_path}`,
|
||||
},
|
||||
"write",
|
||||
);
|
||||
if (!authorized.ok)
|
||||
return toCallToolResult(permissionFailure(authorized), closeContract);
|
||||
}
|
||||
const snapshot = session.exportAnalysisSnapshot();
|
||||
if (!snapshot.ok) return toCallToolResult(snapshot, closeContract);
|
||||
const written = await writeAnalysisSnapshot(
|
||||
snapshot.value,
|
||||
parsed.snapshot_path,
|
||||
parsed.overwrite,
|
||||
snapshotFilePolicy,
|
||||
);
|
||||
if (!written.ok) return toCallToolResult(written, closeContract);
|
||||
await reportLifecycleStart(
|
||||
progress,
|
||||
closeContract.name,
|
||||
"snapshot written; closing provider",
|
||||
);
|
||||
const closed = await logToolExecution(logger, closeContract.name, () =>
|
||||
session.close({ progress }),
|
||||
);
|
||||
await reportLifecycleEnd(progress, closeContract.name, closed.ok);
|
||||
server.sendToolListChanged();
|
||||
return closed.ok
|
||||
? toCallToolResult(
|
||||
ok({
|
||||
path: written.value.path,
|
||||
bytes: written.value.bytes,
|
||||
entries: snapshot.value.entries.length,
|
||||
}),
|
||||
closeContract,
|
||||
)
|
||||
: toCallToolResult(closed, closeContract);
|
||||
},
|
||||
);
|
||||
};
|
||||
@@ -49,9 +49,8 @@ export const registerEnhancedTools = (
|
||||
analysis: AnalysisOperationPort,
|
||||
options: EnhancedToolRegistration,
|
||||
): void => {
|
||||
const services = new EnhancedTools(analysis);
|
||||
for (const contract of ENHANCED_TOOL_CONTRACTS) {
|
||||
registerEnhancedTool(server, services, contract, {
|
||||
registerEnhancedTool(server, analysis, contract, {
|
||||
logger: options.logger,
|
||||
activeTarget: options.activeTarget,
|
||||
analysisProfile: options.analysisProfile,
|
||||
@@ -63,7 +62,7 @@ export const registerEnhancedTools = (
|
||||
|
||||
const registerEnhancedTool = (
|
||||
server: McpServer,
|
||||
services: EnhancedTools,
|
||||
analysis: AnalysisOperationPort,
|
||||
contract: ToolContract,
|
||||
registration: {
|
||||
readonly logger: Logger;
|
||||
@@ -91,6 +90,13 @@ const registerEnhancedTool = (
|
||||
if (!validatedCall.ok) return toCallToolResult(validatedCall, contract);
|
||||
const parsedInput = validatedCall.value.input;
|
||||
const parameters = jsonParameters(parsedInput);
|
||||
const services = new EnhancedTools({
|
||||
execute: (operation, operationParameters, executionOptions) =>
|
||||
analysis.execute(operation, operationParameters, {
|
||||
...executionOptions,
|
||||
progress,
|
||||
}),
|
||||
});
|
||||
const result = await logToolExecution(registration.logger, name, () =>
|
||||
services.executeValidated(validatedCall.value, context.mcpReq.signal),
|
||||
);
|
||||
|
||||
@@ -148,6 +148,7 @@ const projectSessionStatus = (options: {
|
||||
active_provider: activeProvider,
|
||||
target: open ? targetFrom(options.status) : null,
|
||||
alignment: options.serverIdentity.alignment,
|
||||
analysis_activity: options.status.analysis_activity,
|
||||
recommended_actions: recommendedActions(
|
||||
open,
|
||||
options.serverIdentity.alignment.state,
|
||||
|
||||
@@ -6,7 +6,7 @@ import { SESSION_TOOL_CONTRACTS } from "../contracts/toolContracts.js";
|
||||
import { toCallToolResult } from "./toolResult.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { ok, type Result } from "../domain/result.js";
|
||||
import type {
|
||||
ProcessCapture,
|
||||
ProcessExecutionPolicy,
|
||||
@@ -18,16 +18,8 @@ import { processCapturePermissionRequest } from "../application/ProcessCapturePe
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
|
||||
import type { EvidenceFilePolicy } from "../domain/evidenceBundle.js";
|
||||
import {
|
||||
readAnalysisSnapshot,
|
||||
writeAnalysisSnapshot,
|
||||
} from "../application/AnalysisSnapshotFiles.js";
|
||||
import {
|
||||
AnalysisProtocolError,
|
||||
PermissionRequiredError,
|
||||
UnknownRegistryError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import { readAnalysisSnapshot } from "../application/AnalysisSnapshotFiles.js";
|
||||
import { UnknownRegistryError, type AnalysisError } from "../domain/errors.js";
|
||||
import {
|
||||
DENY_EVIDENCE_FILE_POLICY,
|
||||
DENY_PROCESS_POLICY,
|
||||
@@ -40,10 +32,7 @@ import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
import { safeParseToolInput } from "./toolInputValidation.js";
|
||||
import { registerBundleComparisonTool } from "./registerBundleComparisonTool.js";
|
||||
import { registerInvestigationTools } from "./registerInvestigationTools.js";
|
||||
import {
|
||||
closeBinaryInputSchema,
|
||||
openBinaryInputSchema,
|
||||
} from "../contracts/sessionLifecycleInputs.js";
|
||||
import { openBinaryInputSchema } from "../contracts/sessionLifecycleInputs.js";
|
||||
import { registerSessionStatusTool } from "./registerSessionStatusTool.js";
|
||||
import type { PermissionAuthority } from "../application/PermissionAuthority.js";
|
||||
import { mcpProgressReporter } from "./mcpProgress.js";
|
||||
@@ -61,20 +50,8 @@ import {
|
||||
sessionAvailabilityPolicy,
|
||||
type SessionAvailability,
|
||||
} from "./sessionAvailabilityPolicy.js";
|
||||
|
||||
const permissionFailure = (
|
||||
failure: Awaited<ReturnType<PermissionAuthority["authorize"]>>,
|
||||
): Result<never, AnalysisError> => {
|
||||
if (failure.ok)
|
||||
return err(new AnalysisProtocolError("Expected a denied permission"));
|
||||
return err(
|
||||
failure.error instanceof PermissionRequiredError
|
||||
? failure.error
|
||||
: new AnalysisProtocolError(failure.error.message, {
|
||||
cause: failure.error,
|
||||
}),
|
||||
);
|
||||
};
|
||||
import { permissionFailure } from "./permissionFailure.js";
|
||||
import { registerCloseLifecycleTool } from "./registerCloseLifecycleTool.js";
|
||||
|
||||
const recordProcessResidualUnknowns = (
|
||||
session: BinarySessionPort,
|
||||
@@ -204,7 +181,7 @@ const registerProcessTools = ({
|
||||
);
|
||||
};
|
||||
|
||||
interface LifecycleToolRegistration {
|
||||
export interface LifecycleToolRegistration {
|
||||
readonly server: McpServer;
|
||||
readonly session: BinarySessionPort;
|
||||
readonly logger: Logger;
|
||||
@@ -314,75 +291,6 @@ const registerOpenLifecycleTool = ({
|
||||
);
|
||||
};
|
||||
|
||||
const registerCloseLifecycleTool = ({
|
||||
server,
|
||||
session,
|
||||
logger,
|
||||
contracts: [, closeContract],
|
||||
snapshotFilePolicy,
|
||||
permissionAuthority,
|
||||
}: LifecycleToolRegistration): void => {
|
||||
server.registerTool(
|
||||
closeContract.name,
|
||||
toolRegistrationOptions(closeContract),
|
||||
async (input) => {
|
||||
const parsedInput = safeParseToolInput(
|
||||
closeBinaryInputSchema,
|
||||
input,
|
||||
closeContract.name,
|
||||
);
|
||||
if (!parsedInput.ok) return toCallToolResult(parsedInput, closeContract);
|
||||
const parsed = parsedInput.value;
|
||||
if (parsed.snapshot_path === undefined) {
|
||||
const closed = await logToolExecution(logger, closeContract.name, () =>
|
||||
session.close(),
|
||||
);
|
||||
if (closed.ok) server.sendToolListChanged();
|
||||
return toCallToolResult(closed, closeContract);
|
||||
}
|
||||
if (permissionAuthority !== undefined) {
|
||||
const authorized = await permissionAuthority.authorize(
|
||||
{
|
||||
capability: "snapshot_write",
|
||||
roots: [parsed.snapshot_path],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
operation_identity: `close_binary:snapshot:${parsed.snapshot_path}`,
|
||||
},
|
||||
"write",
|
||||
);
|
||||
if (!authorized.ok)
|
||||
return toCallToolResult(permissionFailure(authorized), closeContract);
|
||||
}
|
||||
const snapshot = session.exportAnalysisSnapshot();
|
||||
if (!snapshot.ok) return toCallToolResult(snapshot, closeContract);
|
||||
const written = await writeAnalysisSnapshot(
|
||||
snapshot.value,
|
||||
parsed.snapshot_path,
|
||||
parsed.overwrite,
|
||||
snapshotFilePolicy,
|
||||
);
|
||||
if (!written.ok) return toCallToolResult(written, closeContract);
|
||||
const closed = await logToolExecution(logger, closeContract.name, () =>
|
||||
session.close(),
|
||||
);
|
||||
if (closed.ok) server.sendToolListChanged();
|
||||
return closed.ok
|
||||
? toCallToolResult(
|
||||
ok({
|
||||
path: written.value.path,
|
||||
bytes: written.value.bytes,
|
||||
entries: snapshot.value.entries.length,
|
||||
}),
|
||||
closeContract,
|
||||
)
|
||||
: toCallToolResult(closed, closeContract);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
/** Register MCP-only target lifecycle operations on a long-lived session. */
|
||||
export interface SessionToolOptions {
|
||||
readonly processPolicy?: ProcessExecutionPolicy;
|
||||
|
||||
Reference in New Issue
Block a user