Files
reverse-engineering-anything/src/jeb/JebMcpConnectionOwner.ts
T
morluto 5f718ce30e refactor(kernel): give error-message, byte-hex and SHA-256 hex helpers one owner in a new src/kernel layer (#11542)
* refactor(kernel): give error-to-message text one owner in a new src/kernel layer

* fix(kernel): keep the regex worker's own error text inside its isolated source

* refactor(kernel): exclude copies that run in another realm from the error-message guard by name

The regex worker's source string and the page.evaluate fetch in PlaywrightScenarioRequest cannot import errorMessage. The guard now names them, so the counted baseline does not invite a later slice to rewrite them.

* refactor(kernel): migrate the long tail of inline error-message copies to errorMessage (#11552)

Every provider and adapter folder with six or fewer copies now calls errorMessage from src/kernel. Local helpers whose whole body was the copy (failureMessage, gdbErrorMessage, message, describe, reasonOf, recoveryFailureMessage and four local errorMessage definitions) are removed and their call sites call the owner.

Refs #11548

* refactor(kernel): give byte-to-hex formatting one owner in src/kernel (#11560)

byteToHex returns the two lowercase hexadecimal digits of one byte. All eight inline copies (native, contracts, domain firmware and desktop, pcap) call it, keeping their own 0x, % or \x notation, and a counted guard with an empty baseline keeps new copies out.

Refs #11548

* refactor(kernel): give one-shot SHA-256 hex digests one owner in src/kernel (#11562)

sha256Hex digests one in-memory value. A counted guard records the one-shot createHash("sha256").update(x).digest("hex") chains (115 in 101 files) and the first slice migrates domain, contracts and process (35 copies), removing local wrappers (sha256, sha256Text, hash) and the exported sha256Text. Incremental and streamed hashing is not counted.

Refs #11548

* refactor(kernel): migrate the application layer's inline error-message copies to errorMessage (#11563)

All 69 copies in src/application call errorMessage from src/kernel. Local helpers whose whole body was the copy (errorDetail, causeReason and five local errorMessage definitions) are removed and their call sites call the owner.

Refs #11548

* refactor(kernel): migrate the native provider's inline error-message copies to errorMessage (#11567)

All 49 copies in src/native call errorMessage from src/kernel. The local errorReason helpers in LldbCallTracer and LldbRetainedObservations, whose whole body was the copy, are removed and their call sites call the owner.

Refs #11548

* refactor(kernel): migrate the remaining inline error-message copies to errorMessage (#11569)
2026-11-16 07:05:30 +08:00

174 lines
5.2 KiB
TypeScript

import { StructuredContentMcpClient } from "../providers/StructuredContentMcpClient.js";
import {
SdkError,
SdkErrorCode,
StreamableHTTPClientTransport,
} from "@modelcontextprotocol/client";
import { AnalysisCleanupLease } from "../resources/index.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { SharedStartupAttempt } from "../process/SharedStartupAttempt.js";
import type { Result } from "../domain/result.js";
import {
McpHttpUtf8Error,
validateMcpHttpResponse,
} from "../providers/Utf8McpResponse.js";
import { errorMessage } from "../kernel/errorMessage.js";
/** Physical SDK failure captured before any subsequent resource cleanup. */
export class JebMcpPhysicalFailure extends Error {
constructor(
readonly phase: "catalog" | "tool",
override readonly cause: unknown,
) {
super(`JEB MCP ${phase} failed`, { cause });
this.name = "JebMcpPhysicalFailure";
}
}
/** An operation failed while its exact connection still has pending cleanup. */
export class JebMcpCleanupFailure extends ProviderCleanupError {
constructor(
readonly primaryFailure: unknown,
readonly cleanupFailure: ProviderCleanupError,
operation: string,
) {
super(
"jeb",
cleanupFailure.cleanupResources,
{
reason: "JEB MCP operation and cleanup failed",
},
{
operation,
cause: new AggregateError(
[primaryFailure, cleanupFailure],
"JEB MCP operation and cleanup failed",
{ cause: primaryFailure },
),
},
);
this.bindCleanupDependencies([cleanupFailure]).bindCleanupResourceOwner(
cleanupFailure,
);
}
}
/** One SDK client owns its attached transport; failed cleanup retains both identities. */
export class JebMcpConnectionOwner {
readonly client = new StructuredContentMcpClient({
name: "rea-jeb",
version: "0.0.0",
});
readonly transport: StreamableHTTPClientTransport;
readonly signal = new AbortController();
tools: readonly string[] | undefined;
acquisition:
| SharedStartupAttempt<Result<readonly string[], unknown>>
| undefined;
acquisitionFailure: { readonly cause: unknown } | undefined;
invalidation:
| { readonly failure: Promise<unknown>; settled: boolean }
| undefined;
readonly #clientResource: string;
readonly #transportResource: string;
readonly #lease: AnalysisCleanupLease;
#clientClosed = false;
#transportClosed = false;
#disposal: Promise<void> | undefined;
#httpUtf8Failure: McpHttpUtf8Error | undefined;
constructor(endpoint: URL) {
this.transport = new StreamableHTTPClientTransport(endpoint, {
requestInit: { redirect: "error" },
fetch: async (input, init) =>
validateMcpHttpResponse(await fetch(input, init), (failure) => {
this.#httpUtf8Failure ??= failure;
this.tools = undefined;
void this.transport.close().catch(() => undefined);
}),
});
this.#clientResource = `${endpoint} (JEB MCP client)`;
this.#transportResource = `${endpoint} (JEB MCP transport)`;
this.#lease = new AnalysisCleanupLease(
() => this.#dispose(),
[this.#clientResource, this.#transportResource],
);
}
get disposing(): boolean {
return this.#disposal !== undefined;
}
/** Attribute only the actual transport close caused by malformed response bytes. */
responseFailure(cause: unknown): unknown {
return this.#httpUtf8Failure !== undefined &&
cause instanceof SdkError &&
cause.code === SdkErrorCode.ConnectionClosed
? this.#httpUtf8Failure
: cause;
}
get cleanupResources(): readonly string[] {
return [
...(this.#clientClosed ? [] : [this.#clientResource]),
...(this.#transportClosed ? [] : [this.#transportResource]),
];
}
close(): Promise<void> {
return this.#lease.release();
}
async #dispose(): Promise<void> {
if (this.#disposal !== undefined) return this.#disposal;
const disposal = this.#closeResources();
this.#disposal = disposal;
try {
await disposal;
} catch (cause: unknown) {
this.#disposal = undefined;
throw cause;
}
}
async #closeResources(): Promise<void> {
const failures: unknown[] = [];
if (!this.#clientClosed) {
const attached = this.client.transport === this.transport;
try {
await this.client.close();
this.#clientClosed = true;
// SDK 2.3.1 awaits its attached transport's close before resolving.
if (attached) this.#transportClosed = true;
} catch (cause: unknown) {
failures.push(cause);
}
}
if (!this.#transportClosed) {
try {
await this.transport.close();
this.#transportClosed = true;
} catch (cause: unknown) {
failures.push(cause);
}
}
if (failures.length === 0) return;
const failure = new ProviderCleanupError(
"jeb",
this.cleanupResources,
{
reason: failures.map((cause) => errorMessage(cause)).join("; "),
},
{
operation: "close_jeb_connection",
cause: new AggregateError(
failures,
"JEB MCP connection cleanup failed",
),
},
).bindCleanupResourceOwner(this);
this.#lease.bindCleanupError(failure);
throw failure;
}
}