From 82e16b4dda6a5e526845a26ad09251f8fa69807d Mon Sep 17 00:00:00 2001 From: mengzhe gan Date: Thu, 19 Nov 2026 03:31:34 +0800 Subject: [PATCH] fix(setup): write the recommended tool call timeout into dsh registrations (#4043) * fix(setup): write the recommended tool call timeout into dsh registrations rea setup --client dsh wrote registrations without toolCallTimeoutMs, so DeepSeek Harness applied its 60-second default while a native provider startup alone can exceed it. Setup now derives the deadline from the same provider allowance plus operation headroom used for Kimi and Codex, preserves a positive caller-selected value, and doctor reports a registration without a usable timeout as stale. ProviderRequestBudgetResolver declares an optional budgetSettings read set, so the fail-closed budget gate rejects unresolved Cordis expressions only for settings the derivation may read plus the timeout inputs; an unrelated expression such as GHIDRA_INSTALL_DIR still refreshes, and an expression in REA_IDA_MCP_CONFIG fails closed. * test(setup): record the dsh tool call deadline in the NUL repair fixture The NUL refusal scenario rewrites a valid dsh registration and expects doctor to report it healthy. That fixture omitted toolCallTimeoutMs, which doctor now reports stale, so the repaired registration records the deadline a current dsh registration carries. * test(setup): separate dsh timeout repair coverage --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> --- docs/getting-started/client-configuration.md | 12 + src/application/ClientRegistration.ts | 4 + .../ClientRegistrationEnvironment.ts | 24 +- src/application/ClientRegistrationStatus.ts | 30 +- src/application/Doctor.ts | 54 +++- src/application/DshCordisPatch.ts | 22 ++ src/application/SetupClientConfiguration.ts | 17 +- src/doctorRuntime.ts | 53 ++-- .../registrationRuntimeEnvironmentCli.test.ts | 3 + .../filesystem/dshClientConfiguration.test.ts | 290 +++++++++++++++++- 10 files changed, 454 insertions(+), 55 deletions(-) diff --git a/docs/getting-started/client-configuration.md b/docs/getting-started/client-configuration.md index 6bfc1f0fff..188f96e279 100644 --- a/docs/getting-started/client-configuration.md +++ b/docs/getting-started/client-configuration.md @@ -1009,8 +1009,20 @@ The written entry is: transport: stdio command: /absolute/path/to/node args: ["/absolute/path/to/rea/scripts/rea.mjs", mcp] + toolCallTimeoutMs: 450000 ``` +The `toolCallTimeoutMs` field is derived from REA's known provider allowance +plus 120 seconds of operation headroom, with the same derivation as the Kimi +Code tool timeout above. The default is 450000 ms, covering the default +330-second Ghidra startup; without the field, DeepSeek Harness applies its own +60000 ms tool-call default, which a native provider startup alone can exceed. +Setup preserves positive caller-selected `toolCallTimeoutMs` values and Cordis +expressions. It writes the recommended literal when the field is missing or +malformed. Doctor reports those registrations as stale. Its non-blocking +advisories identify a timeout whose effective value is unknown because it is an +expression, or a positive literal shorter than the known provider allowance. + Setup preserves caller-owned Cordis expressions and replaces launcher fields with literal values that doctor can verify. It refuses to edit an expression that produces the entire REA config, or a group-targeted REA insertion. Use a diff --git a/src/application/ClientRegistration.ts b/src/application/ClientRegistration.ts index 70a844e3e1..ff5670998c 100644 --- a/src/application/ClientRegistration.ts +++ b/src/application/ClientRegistration.ts @@ -31,6 +31,7 @@ import { type ClientRegistrationCommandIdentity, } from "./ClientRegistrationIdentity.js"; import { CURRENT_ENTRYPOINT_PATH } from "../process/CurrentEntrypointPath.js"; +import { dshToolCallTimeout } from "./DshCordisPatch.js"; const tomlTimeoutSchema = z.union([ z.number().positive(), @@ -194,6 +195,9 @@ export const parseClientRegistrationPolicy = ( if (client.format === "dsh") { const parsed = registrationSchema .pick({ command: true, args: true, serverName: true, transport: true }) + .extend({ + toolCallTimeoutMs: z.unknown().transform(dshToolCallTimeout).optional(), + }) .strip() .safeParse(value); return parsed.success diff --git a/src/application/ClientRegistrationEnvironment.ts b/src/application/ClientRegistrationEnvironment.ts index 174917c3fb..6a0a97e81b 100644 --- a/src/application/ClientRegistrationEnvironment.ts +++ b/src/application/ClientRegistrationEnvironment.ts @@ -32,10 +32,19 @@ import { dshDocument } from "./DshCordisPatch.js"; import type { McpToolTimeoutInputs } from "../config/mcpStartupPolicy.js"; import type { AnalysisProviderSelector } from "../domain/providerSelection.js"; -export type ProviderRequestBudgetResolver = ( - analysisProvider: AnalysisProviderSelector, - environment: Readonly>, -) => Promise>; +export interface ProviderRequestBudgetResolver { + ( + analysisProvider: AnalysisProviderSelector, + environment: Readonly>, + ): Promise>; + /** + * Environment settings this resolver may read. Unresolved expressions in + * these settings block budget derivation; expressions in other settings + * stay preserved. An omitted set keeps the fail-closed whole-environment + * gate: every unresolved expression blocks the budget. + */ + readonly budgetSettings?: ReadonlySet; +} export interface ClientRegistrationEnvironmentDetails { readonly values: Readonly>; @@ -274,9 +283,14 @@ export const clientRegistrationEnvironmentDetailsWithBudget = async ( validation, ); if (!details.ok) return details; + // The budget gate stays fail-closed: settings the resolver may read must be + // literals, and an undeclared read set keeps every unresolved expression + // blocking, because an unreadable budget cannot be treated as absent. + const budgetSettings = resolveProviderRequestBudget?.budgetSettings; const unresolved = [...details.value.unresolvedSettings].filter( (setting) => - resolveProviderRequestBudget !== undefined || + (resolveProviderRequestBudget !== undefined && + (budgetSettings === undefined || budgetSettings.has(setting))) || TIMEOUT_INPUT_SETTINGS.has(setting), ); if (details.value.timeoutInputs === undefined || unresolved.length > 0) diff --git a/src/application/ClientRegistrationStatus.ts b/src/application/ClientRegistrationStatus.ts index 5669044590..f769763b79 100644 --- a/src/application/ClientRegistrationStatus.ts +++ b/src/application/ClientRegistrationStatus.ts @@ -361,7 +361,8 @@ export const readClientRegistrationInspections = async ( const registrationEnvironment = client.name === "kimi" || client.name === "codex" || - client.name === "lm_studio" + client.name === "lm_studio" || + client.name === "dsh" ? await clientRegistrationEnvironmentDetailsWithBudget( parsed, client, @@ -561,6 +562,10 @@ const registrationAligned = ({ // Native transport is admitted separately; the Harness route must name REA. if (client.format === "dsh" && registration.serverName !== "rea") return "stale"; + // Setup repairs missing or malformed literals. Doctor reports the unknown + // value of a caller-owned expression as an advisory. + if (client.format === "dsh" && registration.toolCallTimeoutMs === undefined) + return "stale"; // Legacy package runners remain owned, but setup migrates them to the selected installation. if (commandFacts.package !== undefined) return "stale"; // Owning the script does not establish how its shebang interpreter resolves @@ -640,12 +645,16 @@ const timeoutAdvisory = ( ? registration.toolTimeoutMs : client.name === "codex" ? registration.tool_timeout_sec - : undefined; + : client.name === "dsh" + ? registration.toolCallTimeoutMs + : undefined; if (toolTimeout === undefined) return undefined; + if (client.name === "dsh" && toolTimeout === null) + return "The effective timeout is unknown because toolCallTimeoutMs is a caller-owned Cordis expression."; const providerAllowance = mcpProviderDeadlineAllowanceMs(timeoutInputs); - const isKimi = client.name === "kimi"; + const inMilliseconds = client.name === "kimi" || client.name === "dsh"; // A bigint is beyond the safe Number range, so rounding cannot cross the allowance. - const toolTimeoutMs = Number(toolTimeout) * (isKimi ? 1 : 1000); + const toolTimeoutMs = Number(toolTimeout) * (inMilliseconds ? 1 : 1000); const batchScope = timeoutInputs.ghidraDecompileTimeoutMs !== undefined && (timeoutInputs.analysisProvider === "ghidra" || @@ -653,14 +662,19 @@ const timeoutAdvisory = ( ? "The derived Ghidra deadline is a single-decompile estimate. For multi-function workflows such as batch_decompile, decompile_all or trace_native_values, allow startup plus every attempted function's limit and other work; split calls, reduce trace_native_values max_functions, or select a larger client deadline when needed. Explicit caller deadlines remain unchanged." : undefined; if (toolTimeoutMs >= providerAllowance) return batchScope; - const setting = isKimi ? "toolTimeoutMs" : "tool_timeout_sec"; - const currentValue = isKimi + const setting = + client.name === "kimi" + ? "toolTimeoutMs" + : client.name === "dsh" + ? "toolCallTimeoutMs" + : "tool_timeout_sec"; + const currentValue = inMilliseconds ? `${String(toolTimeout)} ms` : `${String(toolTimeout)} seconds`; - const recommendedValue = isKimi + const recommendedValue = inMilliseconds ? `${String(recommendedMcpToolTimeoutMs(timeoutInputs))} ms` : `${String(recommendedMcpToolTimeoutSeconds(timeoutInputs))} seconds`; - const headroom = isKimi + const headroom = inMilliseconds ? `${String(MCP_STARTUP_POLICY.toolOperationHeadroomMs)} ms` : `${String(MCP_STARTUP_POLICY.toolOperationHeadroomMs / 1000)} seconds`; const recommendation = `The configured ${setting} (${currentValue}) is shorter than REA's known provider allowance (${String(providerAllowance)} ms), so provider startup or an upstream request may exceed this client deadline. REA recommends ${setting} = ${recommendedValue} to cover that allowance plus ${headroom} of operation headroom; this additional headroom is a recommendation, not a guarantee for every analysis.`; diff --git a/src/application/Doctor.ts b/src/application/Doctor.ts index ad4fb6a1c8..2dd7ea7557 100644 --- a/src/application/Doctor.ts +++ b/src/application/Doctor.ts @@ -653,6 +653,22 @@ const launcherInstallation = async ( : posix.dirname(resolved); }; +/** + * A provider request budget resolver with its retained resource scope and + * cancellation signal, as an outer adapter supplies it. The declared read + * set travels with it into the 2-parameter registration derivation. + */ +export interface RetainedProviderRequestBudgetResolver { + ( + provider: Parameters[0], + environment: Parameters[1], + resources: RetainedResourceScope, + signal: AbortSignal, + ): ReturnType; + /** Environment settings this resolver may read; see the base contract. */ + readonly budgetSettings?: ReadonlySet; +} + /** Optional outer-adapter diagnostics composed without reversing dependencies. */ export interface SystemDoctorHostOptions { readonly signal?: AbortSignal; @@ -665,12 +681,7 @@ export interface SystemDoctorHostOptions { signal: AbortSignal, clients: readonly string[], ) => Promise; - readonly resolveProviderRequestBudget?: ( - provider: Parameters[0], - environment: Parameters[1], - resources: RetainedResourceScope, - signal: AbortSignal, - ) => ReturnType; + readonly resolveProviderRequestBudget?: RetainedProviderRequestBudgetResolver; readonly linuxDemoRuntimeCheck?: ( resourceScope: RetainedResourceScope, signal: AbortSignal, @@ -773,16 +784,27 @@ export const systemDoctorHost = ( const resolveProviderRequestBudget = options.resolveProviderRequestBudget === undefined ? undefined - : ( - provider: Parameters[0], - environment: Parameters[1], - ) => - options.resolveProviderRequestBudget!( - provider, - environment, - resourceScope, - inspectionSignal, - ); + : Object.assign( + ( + provider: Parameters[0], + environment: Parameters[1], + ) => + options.resolveProviderRequestBudget!( + provider, + environment, + resourceScope, + inspectionSignal, + ), + // Carry the declared read set through the 2-parameter adaptation, + // so the budget gate stays fail-closed only for settings this + // resolver may actually read. + options.resolveProviderRequestBudget.budgetSettings === undefined + ? {} + : { + budgetSettings: + options.resolveProviderRequestBudget.budgetSettings, + }, + ); const host: DoctorHost = { ...(options.signal === undefined ? {} : { signal: options.signal }), platform, diff --git a/src/application/DshCordisPatch.ts b/src/application/DshCordisPatch.ts index a987d965c2..fbb1f96ef0 100644 --- a/src/application/DshCordisPatch.ts +++ b/src/application/DshCordisPatch.ts @@ -262,6 +262,7 @@ export class DshCordisDocument { command: readonly string[], overrides: Readonly>, platform: NodeJS.Platform, + toolCallTimeoutMs?: number, ): Result, ConfigurationError> { if (this.#editabilityError !== undefined) return err(this.#editabilityError); @@ -275,6 +276,11 @@ export class DshCordisDocument { const desired = { ...this.config, ...dshClientRegistrationEntry(command) }; delete desired.env; if (Object.keys(env).length > 0) desired.env = env; + if ( + toolCallTimeoutMs !== undefined && + dshToolCallTimeout(this.config?.toolCallTimeoutMs) === undefined + ) + desired.toolCallTimeoutMs = toolCallTimeoutMs; return ok(desired); } @@ -381,6 +387,12 @@ export class DshCordisDocument { // Caller nodes keep their tags and spelling; only literal launcher values change. for (const key of LAUNCHER_KEYS) this.#yaml.setValue(config, key, desired[key]); + if (typeof desired.toolCallTimeoutMs === "number") + this.#yaml.setValue( + config, + "toolCallTimeoutMs", + desired.toolCallTimeoutMs, + ); const env = this.#map(this.#yaml.field(sourceConfig, "env")); const desiredEnv = desired.env; if (isPatchRecord(desiredEnv)) { @@ -462,6 +474,16 @@ export const serializeDshDocument = ( throw new ConfigurationError("Missing Cordis edit plan"); return document.cordis.source.serialize(document.cordis.registration); }; +/** Read a positive literal deadline or null for a caller-owned expression of unknown value. */ +export const dshToolCallTimeout = ( + value: unknown, +): number | null | undefined => { + if (value instanceof CordisExpression) return null; + return typeof value === "number" && Number.isFinite(value) && value > 0 + ? value + : undefined; +}; + export const dshClientRegistrationEntry = ( command: readonly string[], environment: Readonly> = {}, diff --git a/src/application/SetupClientConfiguration.ts b/src/application/SetupClientConfiguration.ts index 32c19c99fd..2d11f66705 100644 --- a/src/application/SetupClientConfiguration.ts +++ b/src/application/SetupClientConfiguration.ts @@ -59,6 +59,7 @@ import { clientRegistrationOwnershipRemediation, refreshClientRegistration, } from "./ClientRegistration.js"; +import { recommendedMcpToolTimeoutMs } from "../config/mcpStartupPolicy.js"; import { PRODUCT_IDENTITY } from "../identity.js"; import { currentClientRegistrationCommand } from "./ClientRegistrationIdentity.js"; @@ -1346,18 +1347,28 @@ const clientConfigurationDesired = async ( const launcher = command.length === 0 ? [PRODUCT_IDENTITY.cliBinary, "mcp"] : command; if (format === "dsh") { - const validated = clientRegistrationEnvironment( + // The budget resolver's declared read set keeps the gate fail-closed only + // for settings the derivation may actually read, so unrelated Cordis + // expressions stay preserved while the budget still resolves. + const validated = await clientRegistrationEnvironmentDetailsWithBudget( effective, client, - platform, providerEnvironment, + "effective", + resolveProviderRequestBudget, + platform, ); if (!validated.ok) throw validated.error; const desired = ( parsed === undefined ? new DshCordisDocument("") : dshDocument(parsed.document) - ).desired(launcher, providerEnvironment, platform); + ).desired( + launcher, + providerEnvironment, + platform, + recommendedMcpToolTimeoutMs(validated.value.timeoutInputs), + ); if (!desired.ok) throw desired.error; return desired.value; } diff --git a/src/doctorRuntime.ts b/src/doctorRuntime.ts index 9815c95f99..b61ffc174e 100644 --- a/src/doctorRuntime.ts +++ b/src/doctorRuntime.ts @@ -1,5 +1,9 @@ import { HOST_PLATFORM, type HostPlatform } from "./platform/HostPlatform.js"; -import { systemDoctorHost, type DoctorHost } from "./application/Doctor.js"; +import { + systemDoctorHost, + type DoctorHost, + type RetainedProviderRequestBudgetResolver, +} from "./application/Doctor.js"; import type { DoctorCheck, DoctorProviderInspection, @@ -359,27 +363,32 @@ export const createSystemDoctorHost = ( platform, architecture: host.architecture, ...(signal === undefined ? {} : { signal }), - resolveProviderRequestBudget: async ( - analysisProvider, - registrationEnvironment, - resourceScope, - inspectionSignal, - ) => { - if (analysisProvider !== "ida" && analysisProvider !== "auto") - return ok(undefined); - const path = registrationEnvironment.REA_IDA_MCP_CONFIG; - if (path === undefined) return ok(undefined); - const registration = await readRegistration( - path, - resourceScope, - inspectionSignal, - ); - if (registration.ok) return ok(registration.value.timeoutMs); - // An invalid IDA registration cannot be selected automatically. Keep it - // out of recommendations for another available provider, but surface the - // parser-owned error when IDA itself was explicitly selected. - return analysisProvider === "ida" ? registration : ok(undefined); - }, + resolveProviderRequestBudget: Object.assign( + async ( + analysisProvider: Parameters[0], + registrationEnvironment: Parameters[1], + resourceScope: Parameters[2], + inspectionSignal: Parameters[3], + ) => { + if (analysisProvider !== "ida" && analysisProvider !== "auto") + return ok(undefined); + const path = registrationEnvironment.REA_IDA_MCP_CONFIG; + if (path === undefined) return ok(undefined); + const registration = await readRegistration( + path, + resourceScope, + inspectionSignal, + ); + if (registration.ok) return ok(registration.value.timeoutMs); + // An invalid IDA registration cannot be selected automatically. Keep it + // out of recommendations for another available provider, but surface the + // parser-owned error when IDA itself was explicitly selected. + return analysisProvider === "ida" ? registration : ok(undefined); + }, + // The only environment setting this resolver reads; an unresolved + // expression for it blocks budget derivation. + { budgetSettings: new Set(["REA_IDA_MCP_CONFIG"]) }, + ), providerInspections: async ( resourceScope: RetainedResourceScope, inspectionSignal: AbortSignal, diff --git a/tests/acceptance/setup/registrationRuntimeEnvironmentCli.test.ts b/tests/acceptance/setup/registrationRuntimeEnvironmentCli.test.ts index 6ffcdc29fd..593536a53e 100644 --- a/tests/acceptance/setup/registrationRuntimeEnvironmentCli.test.ts +++ b/tests/acceptance/setup/registrationRuntimeEnvironmentCli.test.ts @@ -369,6 +369,9 @@ cliTest.for([ [process.execPath, resolve("scripts/rea.mjs"), "mcp"], env, ); + // A current dsh registration records its tool call deadline; without + // it doctor reports the registration stale rather than healthy. + if (scenario.format === "dsh") entry.toolCallTimeoutMs = 3_600_000; if (scenario.position === "expression name") entry.env = Object.fromEntries( Object.entries(env).map(([key, value]) => { diff --git a/tests/boundary/filesystem/dshClientConfiguration.test.ts b/tests/boundary/filesystem/dshClientConfiguration.test.ts index c402443887..bc4f94ee56 100644 --- a/tests/boundary/filesystem/dshClientConfiguration.test.ts +++ b/tests/boundary/filesystem/dshClientConfiguration.test.ts @@ -14,7 +14,7 @@ import { import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js"; import { DshCordisDocument } from "../../../src/application/DshCordisPatch.js"; - +import { ok } from "../../../src/domain/result.js"; import { configureClientConfiguration, inspectClientConfiguration, @@ -217,6 +217,7 @@ describe("DeepSeek Harness Cordis patch registration", () => { transport: "stdio", command: command[0], args: command.slice(1), + toolCallTimeoutMs: 450_000, }, }, ], @@ -502,6 +503,7 @@ describe("DeepSeek Harness registration identity", () => { transport: "stdio", command: command[0], args: command.slice(1), + toolCallTimeoutMs: 450_000, }, }, ], @@ -545,6 +547,7 @@ describe("DeepSeek Harness repair boundaries", () => { transport: "stdio", command: command[0], args: command.slice(1), + toolCallTimeoutMs: 450_000, }, }, ], @@ -818,6 +821,185 @@ describe("DeepSeek Harness registration state", () => { }); }); +describe("DeepSeek Harness tool call timeout", () => { + it("writes the recommended tool call timeout into a fresh registration", async () => { + const { client } = await harnessClient(); + expect( + (await configureClientConfiguration(client, {}, command)).status, + ).toBe("configured"); + expect( + cordisPatches(await readFile(client.configPath, "utf8"))[0]?.insert?.[0] + ?.config?.toolCallTimeoutMs, + ).toBe(450_000); + }); + + it("derives a deadline beyond Node's timer ceiling for an overridden provider startup", async () => { + const { client } = await harnessClient(); + expect( + ( + await configureClientConfiguration( + client, + { + REA_ANALYSIS_PROVIDER: "ida", + REA_GHIDRA_STARTUP_TIMEOUT_MS: "2147483647", + }, + command, + ) + ).status, + ).toBe("configured"); + expect( + cordisPatches(await readFile(client.configPath, "utf8"))[0]?.insert?.[0] + ?.config?.toolCallTimeoutMs, + ).toBe(2_147_603_647); + }); + + it("preserves a caller-selected positive timeout through a refresh", async () => { + const { home, client } = await harnessClient(); + const entry = canonicalEntry(); + await writeFile( + client.configPath, + stringifyYaml([ + { + insert: [ + { + ...entry, + config: { ...entry.config, toolCallTimeoutMs: 900_000 }, + }, + ], + }, + ]), + ); + expect( + (await configureClientConfiguration(client, {}, command)).status, + ).toBe("unchanged"); + expect( + cordisPatches(await readFile(client.configPath, "utf8"))[0]?.insert?.[0] + ?.config?.toolCallTimeoutMs, + ).toBe(900_000); + expect(await dshStatus(home)).toMatchObject({ state: "aligned" }); + }); + + it("advises when a configured timeout is shorter than the provider allowance", async () => { + const { home, client } = await harnessClient(); + const entry = canonicalEntry(); + await writeFile( + client.configPath, + stringifyYaml([ + { + insert: [ + { + ...entry, + config: { ...entry.config, toolCallTimeoutMs: 300_000 }, + }, + ], + }, + ]), + ); + expect( + (await configureClientConfiguration(client, {}, command)).status, + ).toBe("unchanged"); + expect(await dshStatus(home)).toMatchObject({ + state: "aligned", + advisory: expect.stringContaining("toolCallTimeoutMs = 450000 ms"), + }); + }); +}); + +describe("DeepSeek Harness tool call timeout repair", () => { + it("repairs a registration without a tool timeout", async () => { + const { home, client } = await harnessClient(); + await writeFile( + client.configPath, + `- insert: + - id: rea-mcp + name: "@deepseek-ai/dsh-mcp-client" + config: + serverName: rea + transport: stdio + command: ${command[0]} + args: [${command.slice(1).join(", ")}] +`, + ); + expect(await dshStatus(home)).toMatchObject({ state: "stale" }); + expect( + (await configureClientConfiguration(client, {}, command)).status, + ).toBe("configured"); + expect( + cordisPatches(await readFile(client.configPath, "utf8"))[0]?.insert?.[0] + ?.config?.toolCallTimeoutMs, + ).toBe(450_000); + expect(await dshStatus(home)).toMatchObject({ state: "aligned" }); + expect( + (await configureClientConfiguration(client, {}, command)).status, + ).toBe("unchanged"); + }); + + it("repairs a malformed literal timeout with the recommended deadline", async () => { + const { client } = await harnessClient(); + const entry = canonicalEntry(); + await writeFile( + client.configPath, + stringifyYaml([ + { + insert: [ + { + ...entry, + config: { ...entry.config, toolCallTimeoutMs: '"450000"' }, + }, + ], + }, + ]), + ); + expect( + (await configureClientConfiguration(client, {}, command)).status, + ).toBe("configured"); + expect( + cordisPatches(await readFile(client.configPath, "utf8"))[0]?.insert?.[0] + ?.config?.toolCallTimeoutMs, + ).toBe(450_000); + }); + + it("preserves an expression-backed timeout and reports its value unknown", async () => { + const { home, client } = await harnessClient(); + const document = parseDocument( + stringifyYaml([{ insert: [canonicalEntry()] }]), + ); + const expression = document.createNode("process.env.REA_TOOL_TIMEOUT"); + expression.tag = "tag:yaml.org,2002:js"; + expression.comment = " caller timeout"; + document.setIn([0, "insert", 0, "config", "toolCallTimeoutMs"], expression); + const original = document.toString(); + await writeFile(client.configPath, original); + + expect( + (await configureClientConfiguration(client, {}, command)).status, + ).toBe("unchanged"); + expect(await readFile(client.configPath, "utf8")).toBe(original); + expect(await dshStatus(home)).toMatchObject({ + state: "aligned", + advisory: expect.stringContaining("effective timeout is unknown"), + }); + + expect( + ( + await configureClientConfiguration( + client, + { REA_ANALYSIS_PROVIDER: "ghidra" }, + command, + ) + ).status, + ).toBe("configured"); + const refreshed = await readFile(client.configPath, "utf8"); + expect( + cordisPatches(refreshed)[0]?.insert?.[0]?.config?.toolCallTimeoutMs, + ).toEqual({ __jsExpr: "process.env.REA_TOOL_TIMEOUT" }); + expect(refreshed).toContain("# caller timeout"); + expect(cordisPatches(refreshed)[0]?.insert?.[0]?.config?.env).toMatchObject( + { REA_ANALYSIS_PROVIDER: "ghidra" }, + ); + }); +}); + describe("DeepSeek Harness canonical row repair", () => { it("normalizes two aligned insertions instead of reporting unchanged", async () => { const { home, client } = await harnessClient(); @@ -1182,6 +1364,111 @@ describe("DeepSeek Harness entry ownership", () => { }); }); +describe("DeepSeek Harness budget resolver expressions", () => { + const budgetResolver = (budgetMs: number) => + Object.assign(async () => ok(budgetMs), { + budgetSettings: new Set(["REA_IDA_MCP_CONFIG"]), + }); + + it("keeps an environment expression while a budget resolver is supplied", async () => { + const { home, client } = await harnessClient(); + await writeFile( + client.configPath, + `- insert: + - id: rea-mcp + name: "@deepseek-ai/dsh-mcp-client" + config: + serverName: rea + transport: stdio + command: stale-launcher + args: [mcp] + env: + GHIDRA_INSTALL_DIR: !!js process.env.GHIDRA_INSTALL_DIR +`, + ); + const resolver = budgetResolver(45_000); + // A declared read set keeps the budget gate fail-closed only for settings + // the resolver may read, so the unrelated expression stays preserved and + // the row is still classified instead of rejected. + expect( + await readClientRegistrationStatuses(home, undefined, { + platform: process.platform, + environment: {}, + resolveProviderRequestBudget: resolver, + }), + ).toMatchObject([ + expect.objectContaining({ client: "dsh", state: "stale" }), + ]); + expect( + (await configureClientConfiguration(client, {}, command, resolver)) + .status, + ).toBe("configured"); + const text = await readFile(client.configPath, "utf8"); + expect(text).toContain("!!js process.env.GHIDRA_INSTALL_DIR"); + expect(text).not.toContain("stale-launcher"); + }); + + it("derives the declared provider request budget into the written timeout", async () => { + const { home, client } = await harnessClient(); + await writeFile( + client.configPath, + `- insert: + - id: rea-mcp + name: "@deepseek-ai/dsh-mcp-client" + config: + serverName: rea + transport: stdio + command: stale-launcher + args: [mcp] +`, + ); + const resolver = budgetResolver(900_000); + expect( + (await configureClientConfiguration(client, {}, command, resolver)) + .status, + ).toBe("configured"); + // The 900000 ms upstream request budget joins the allowance instead of + // leaving the written deadline at the startup-only estimate. + expect( + cordisPatches(await readFile(client.configPath, "utf8"))[0]?.insert?.[0] + ?.config?.toolCallTimeoutMs, + ).toBe(1_020_000); + expect( + await readClientRegistrationStatuses(home, undefined, { + platform: process.platform, + environment: {}, + resolveProviderRequestBudget: resolver, + }), + ).toMatchObject([ + expect.objectContaining({ client: "dsh", state: "aligned" }), + ]); + }); + + it("fails closed when a budget-read setting stays an expression", async () => { + const { client } = await harnessClient(); + const initial = `- insert: + - id: rea-mcp + name: "@deepseek-ai/dsh-mcp-client" + config: + serverName: rea + transport: stdio + command: stale-launcher + args: [mcp] + env: + REA_IDA_MCP_CONFIG: !!js process.env.REA_IDA_MCP_CONFIG +`; + await writeFile(client.configPath, initial); + const resolver = budgetResolver(900_000); + // The resolver may read REA_IDA_MCP_CONFIG, so an unresolved expression + // there blocks budget derivation instead of treating it as absent. + expect( + (await configureClientConfiguration(client, {}, command, resolver)) + .status, + ).toBe("failed"); + expect(await readFile(client.configPath, "utf8")).toBe(initial); + }); +}); + describe("DeepSeek Harness alias collapse", () => { it("collapses an aliased insertion and keeps an unrelated alias", async () => { const { client } = await harnessClient(); @@ -1761,6 +2048,7 @@ const canonicalEntry = () => ({ transport: "stdio", command: command[0], args: command.slice(1), + toolCallTimeoutMs: 450_000, }, });