From ccfc0343e999c0d8f31b73fcdf336e54d6da7869 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 8 Sep 2026 12:48:46 -0700 Subject: [PATCH 01/10] refactor(onboard): route provider consumers through adapter Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../rebuild-local-provider-recreate.test.ts | 5 +- src/lib/onboard.ts | 22 +- src/lib/onboard/bedrock-runtime.ts | 6 +- src/lib/onboard/build-credential-reuse.ts | 8 +- .../onboard/compatible-endpoint-smoke.test.ts | 211 +++++++------ src/lib/onboard/compatible-endpoint-smoke.ts | 59 ++-- .../created-sandbox-finalization.test.ts | 22 +- .../onboard/created-sandbox-finalization.ts | 8 +- .../credential-provider-registration.test.ts | 37 +-- .../credential-provider-registration.ts | 46 +-- ...rovider-reconciliation-diagnostics.test.ts | 38 +-- ...tra-provider-reconciliation-probes.test.ts | 22 +- ...a-provider-reconciliation.test-fixtures.ts | 6 +- .../extra-provider-reconciliation.test.ts | 16 +- .../onboard/extra-provider-reconciliation.ts | 99 +++--- src/lib/onboard/hermes-auth.ts | 30 +- .../compatible-endpoint-gateway-route.test.ts | 37 ++- .../compatible-endpoint-gateway-route.ts | 36 ++- .../inference-providers/hermes.test.ts | 1 + src/lib/onboard/inference-providers/hermes.ts | 4 +- .../inference-providers/ollama-local.ts | 4 +- src/lib/onboard/inference-providers/remote.ts | 6 +- src/lib/onboard/inference-providers/routed.ts | 2 +- src/lib/onboard/inference-providers/types.ts | 12 +- .../onboard/inference-providers/vllm-local.ts | 2 +- src/lib/onboard/machine/handlers/policies.ts | 12 +- .../machine/handlers/provider-inference.ts | 17 +- .../handlers/sandbox-messaging.test.ts | 109 ++++--- .../machine/handlers/sandbox-messaging.ts | 87 +++--- src/lib/onboard/machine/handlers/sandbox.ts | 137 ++++++--- .../onboard/machine/resume-provider-shim.ts | 2 +- src/lib/onboard/messaging-credentials.ts | 6 +- src/lib/onboard/messaging-prep.test.ts | 88 +++--- src/lib/onboard/messaging-prep.ts | 30 +- src/lib/onboard/messaging-reuse.test.ts | 33 +- src/lib/onboard/messaging-reuse.ts | 21 +- src/lib/onboard/openrouter-runtime.ts | 6 +- src/lib/onboard/providers.test.ts | 282 ++++++++---------- src/lib/onboard/providers.ts | 139 +++++---- src/lib/onboard/resume-provider-recovery.ts | 4 +- src/lib/onboard/routed-inference.test.ts | 30 +- src/lib/onboard/routed-inference.ts | 8 +- .../sandbox-create-intent-resolution.ts | 24 +- .../onboard/sandbox-create/orchestration.ts | 15 +- .../onboard/sandbox-messaging-preflight.ts | 46 +-- .../setup-inference-gateway-scope.test.ts | 10 +- src/lib/onboard/setup-inference.ts | 4 +- src/lib/verify-deployment.ts | 13 +- .../hermes-discord-credential-binding.test.ts | 14 +- 49 files changed, 1011 insertions(+), 865 deletions(-) diff --git a/src/lib/actions/sandbox/rebuild-local-provider-recreate.test.ts b/src/lib/actions/sandbox/rebuild-local-provider-recreate.test.ts index 745429448d0..e040513e0cd 100644 --- a/src/lib/actions/sandbox/rebuild-local-provider-recreate.test.ts +++ b/src/lib/actions/sandbox/rebuild-local-provider-recreate.test.ts @@ -174,7 +174,10 @@ describe("rebuild local-provider recreation", () => { : { status: args[0] === "provider" && args[1] === "get" ? 1 : 0, stdout: "", - stderr: "", + stderr: + args[0] === "provider" && args[1] === "get" + ? `provider '${provider}' not found` + : "", }; }); const liveSource = "Name: alpha\nId: sbx-alpha-source\nPhase: Ready\n"; diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index e07c1338632..4847464d0fb 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -2038,15 +2038,15 @@ async function handleRemoteProviderSelection( providerKeyBridge.stageBuildProviderKeyBridge(); let apiKeyNavigation: unknown = null; if (isNonInteractive()) { - const reuseGatewayCredential = buildCredentialReuse.resolveNonInteractiveBuildCredential({ - provider: state.provider, - helpUrl: REMOTE_PROVIDER_CONFIG.build.helpUrl, - recoveredFromSandbox, - providerExistsInGateway: (name) => - providerExistsInGateway(name, args.gatewayName ?? GATEWAY_NAME), - }); - state.skipHostInferenceSmoke = reuseGatewayCredential; - state.reuseGatewayCredentialWithoutLocalKey = reuseGatewayCredential; + state.skipHostInferenceSmoke = + await buildCredentialReuse.resolveNonInteractiveBuildCredential({ + provider: state.provider, + helpUrl: REMOTE_PROVIDER_CONFIG.build.helpUrl, + recoveredFromSandbox, + providerExistsInGateway: (name) => + providerExistsInGateway(name, args.gatewayName ?? GATEWAY_NAME), + }); + state.reuseGatewayCredentialWithoutLocalKey = state.skipHostInferenceSmoke; } else { assertSelectionMutationAuthority(state, "register the NVIDIA provider credential"); apiKeyNavigation = await ensureApiKey(); @@ -2469,11 +2469,11 @@ const stageSandboxCredentialProviders = ( sandboxCreateIntentResolver.prepareCredentialProviders, ); -function getRecordedMessagingChannelsForResume( +async function getRecordedMessagingChannelsForResume( resume: boolean, session: Session | null, sandboxName: string | null, -): string[] | null { +): Promise { return getRecordedMessagingChannelsForResumeFromState({ resume, sessionMessagingChannels: getChannelsFromPlan(session?.messagingPlan), diff --git a/src/lib/onboard/bedrock-runtime.ts b/src/lib/onboard/bedrock-runtime.ts index 5dd45e50580..6d45fdbfdd2 100644 --- a/src/lib/onboard/bedrock-runtime.ts +++ b/src/lib/onboard/bedrock-runtime.ts @@ -26,7 +26,9 @@ type UpsertProvider = ( credentialEnv: string, baseUrl: string | null, env?: NodeJS.ProcessEnv, -) => { ok: boolean; message?: string; status?: number }; +) => + | { ok: boolean; message?: string; status?: number } + | Promise<{ ok: boolean; message?: string; status?: number }>; type SetupInferenceResult = { ok: true; retry?: undefined } | { retry: "selection" }; @@ -178,7 +180,7 @@ export async function setupBedrockRuntimeInference( return { handled: true, result: { retry: "selection" } }; } - const providerResult = options.upsertProvider( + const providerResult = await options.upsertProvider( options.provider, "openai", adapter.credentialEnv, diff --git a/src/lib/onboard/build-credential-reuse.ts b/src/lib/onboard/build-credential-reuse.ts index 29f47c75941..0bdd07507af 100644 --- a/src/lib/onboard/build-credential-reuse.ts +++ b/src/lib/onboard/build-credential-reuse.ts @@ -22,12 +22,12 @@ import { logMissingNvidiaApiKeyHelp } from "./missing-credential-hints"; * * Exits the process when the credential is missing/invalid and unrecoverable. */ -export function resolveNonInteractiveBuildCredential(opts: { +export async function resolveNonInteractiveBuildCredential(opts: { provider: string; helpUrl: string | null | undefined; recoveredFromSandbox: boolean; - providerExistsInGateway: (name: string) => boolean; -}): boolean { + providerExistsInGateway: (name: string) => boolean | Promise; +}): Promise { const { provider, helpUrl, recoveredFromSandbox, providerExistsInGateway } = opts; const resolvedNvidiaKey = resolveProviderCredential("NVIDIA_INFERENCE_API_KEY"); if (resolvedNvidiaKey) { @@ -39,7 +39,7 @@ export function resolveNonInteractiveBuildCredential(opts: { } return false; } - if (!recoveredFromSandbox || !providerExistsInGateway(provider)) { + if (!recoveredFromSandbox || !(await providerExistsInGateway(provider))) { logMissingNvidiaApiKeyHelp(helpUrl); process.exit(1); } diff --git a/src/lib/onboard/compatible-endpoint-smoke.test.ts b/src/lib/onboard/compatible-endpoint-smoke.test.ts index 87139f9fe4e..ca5de7d6c12 100644 --- a/src/lib/onboard/compatible-endpoint-smoke.test.ts +++ b/src/lib/onboard/compatible-endpoint-smoke.test.ts @@ -254,13 +254,23 @@ time.sleep = lambda seconds: sleep_delays.append(seconds) } describe("compatible endpoint sandbox smoke helpers", () => { + const providerMetadata = (name: string): string => + [ + `Id: provider-${name}`, + `Name: ${name}`, + "Type: openai", + "Resource version: 1", + "Credential keys: COMPATIBLE_API_KEY", + "Config keys: OPENAI_BASE_URL", + ].join("\n"); + it.each([ { agent: { name: "hermes" as const }, provider: "compatible-endpoint" }, { agent: { name: "openclaw" as const }, provider: "nvidia-prod" }, - ])("skips sandbox smoke for $agent.name with $provider", ({ agent, provider }) => { + ])("skips sandbox smoke for $agent.name with $provider", async ({ agent, provider }) => { const runOpenshell = vi.fn(); - verifyCompatibleEndpointSandboxSmoke({ + await verifyCompatibleEndpointSandboxSmoke({ sandboxName: "smoke-sandbox", provider, model: "nvidia/nemotron-3-ultra", @@ -272,23 +282,26 @@ describe("compatible endpoint sandbox smoke helpers", () => { expect(runOpenshell).not.toHaveBeenCalled(); }); - it("normalizes spawn output values to strings", () => { + it("normalizes spawn output values to strings", async () => { expect(spawnOutputToString("already string")).toBe("already string"); expect(spawnOutputToString(Buffer.from("buffered"))).toBe("buffered"); expect(spawnOutputToString(null)).toBe(""); expect(spawnOutputToString(42)).toBe("42"); }); - it("budgets the host command timeout for every retry attempt", () => { + it("budgets the host command timeout for every retry attempt", async () => { const runOpenshell = vi .fn() - .mockReturnValueOnce({ status: 0, stdout: "provider ready" }) + .mockImplementationOnce((args: string[]) => ({ + status: 0, + stdout: providerMetadata(args.at(-1) ?? ""), + })) .mockReturnValueOnce({ status: 0, stdout: "OPENCLAW_CONFIG_OK\nINFERENCE_SMOKE_OK PONG", }); - verifyCompatibleEndpointSandboxSmoke({ + await verifyCompatibleEndpointSandboxSmoke({ sandboxName: "smoke-sandbox", provider: "compatible-endpoint", model: "nvidia/nemotron-3-ultra", @@ -304,14 +317,17 @@ describe("compatible endpoint sandbox smoke helpers", () => { ); }); - it("withholds sandbox-route success output when sandbox identity changes during proof (#9833)", () => { + it("withholds sandbox-route success output when sandbox identity changes during proof (#9833)", async () => { const runOpenshell = vi .fn() - .mockReturnValueOnce({ status: 0, stdout: "provider ready" }) + .mockImplementationOnce((args: string[]) => ({ + status: 0, + stdout: providerMetadata(args.at(-1) ?? ""), + })) .mockReturnValueOnce({ status: 0, stdout: "INFERENCE_SMOKE_OK PONG" }); const log = vi.spyOn(console, "log").mockImplementation(() => undefined); - expect(() => + await expect( verifyCompatibleEndpointSandboxSmoke({ sandboxName: "smoke-sandbox", provider: "compatible-endpoint", @@ -323,7 +339,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { throw new Error("sandbox identity changed"); }, }), - ).toThrow("sandbox identity changed"); + ).rejects.toThrow("sandbox identity changed"); expect(runOpenshell).toHaveBeenCalledTimes(2); expect(log.mock.calls.flat().join("\n")).not.toContain( @@ -332,13 +348,16 @@ describe("compatible endpoint sandbox smoke helpers", () => { log.mockRestore(); }); - it("budgets the canonical outer timeout for reasoning retry, tool proof, and direct denial", () => { + it("budgets the canonical outer timeout for reasoning retry, tool proof, and direct denial", async () => { const runOpenshell = vi .fn() - .mockReturnValueOnce({ status: 0, stdout: "provider ready" }) + .mockImplementationOnce((args: string[]) => ({ + status: 0, + stdout: providerMetadata(args.at(-1) ?? ""), + })) .mockReturnValueOnce({ status: 0, stdout: "INFERENCE_SMOKE_OK PONG" }); - verifyCompatibleEndpointSandboxSmoke({ + await verifyCompatibleEndpointSandboxSmoke({ sandboxName: "managed-inference-sandbox", provider: "vllm-local", model: "qwen3.5-9b", @@ -385,7 +404,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { expected: ["Compatible endpoint provider", "inference.local route cannot reach"], unexpected: "Telegram", }, - ])("reports mode-accurate $label provider lookup failures", (testCase) => { + ])("reports mode-accurate $label provider lookup failures", async (testCase) => { const errors: string[] = []; const error = vi.spyOn(console, "error").mockImplementation((message) => { errors.push(String(message)); @@ -395,7 +414,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { }); try { - expect(() => + await expect( verifyCompatibleEndpointSandboxSmoke({ sandboxName: "provider-lookup-failure-sandbox", provider: testCase.provider, @@ -405,13 +424,13 @@ describe("compatible endpoint sandbox smoke helpers", () => { messagingChannels: testCase.messagingChannels, forceCanonicalRoute: testCase.forceCanonicalRoute, }), - ).toThrow("process.exit(1)"); + ).rejects.toThrow("process.exit(1)"); const diagnostics = errors.join("\n"); expect(diagnostics).toContain(testCase.expected[0]); expect(diagnostics).toContain(testCase.expected[1]); expect(diagnostics).not.toContain(testCase.unexpected); - expect(diagnostics).toContain("provider query failed"); + expect(diagnostics).toContain("OpenShell could not inspect the provider"); expect(exit).toHaveBeenCalledWith(1); } finally { exit.mockRestore(); @@ -424,55 +443,61 @@ describe("compatible endpoint sandbox smoke helpers", () => { { label: "Telegram", messagingChannels: ["telegram"] }, ])( "reports a channel-agnostic sandbox smoke failure for $label messaging (#10405)", - ({ messagingChannels }) => { - const errors: string[] = []; - const error = vi.spyOn(console, "error").mockImplementation((message) => { - errors.push(String(message)); - }); - const exit = vi.spyOn(process, "exit").mockImplementation((code) => { - throw new Error(`process.exit(${code})`); - }); - const runOpenshell = vi - .fn() - .mockReturnValueOnce({ status: 0, stdout: "provider ready" }) - .mockReturnValueOnce({ status: 1, stderr: "curl exit 7" }); - - try { - expect(() => - verifyCompatibleEndpointSandboxSmoke({ - sandboxName: "no-messaging-sandbox", - provider: "compatible-endpoint", - model: "issue-10405-model", - runOpenshell, - redact: (value) => value, - messagingChannels, - }), - ).toThrow("process.exit(1)"); - - expect(runOpenshell).toHaveBeenCalledTimes(2); - const diagnostics = errors.join("\n"); - expect(diagnostics).toContain("Compatible endpoint sandbox smoke check failed"); - expect(diagnostics).toContain( - "Messaging setup is not the root cause; the sandbox inference.local route failed.", - ); - expect(diagnostics).toContain("curl exit 7"); - expect(diagnostics).not.toContain("Telegram"); - } finally { - exit.mockRestore(); - error.mockRestore(); - } + async ({ messagingChannels }) => { + const errors: string[] = []; + const error = vi.spyOn(console, "error").mockImplementation((message) => { + errors.push(String(message)); + }); + const exit = vi.spyOn(process, "exit").mockImplementation((code) => { + throw new Error(`process.exit(${code})`); + }); + const runOpenshell = vi + .fn() + .mockImplementationOnce((args: string[]) => ({ + status: 0, + stdout: providerMetadata(args.at(-1) ?? ""), + })) + .mockReturnValueOnce({ status: 1, stderr: "curl exit 7" }); + + try { + await expect( + verifyCompatibleEndpointSandboxSmoke({ + sandboxName: "no-messaging-sandbox", + provider: "compatible-endpoint", + model: "issue-10405-model", + runOpenshell, + redact: (value) => value, + messagingChannels, + }), + ).rejects.toThrow("process.exit(1)"); + + expect(runOpenshell).toHaveBeenCalledTimes(2); + const diagnostics = errors.join("\n"); + expect(diagnostics).toContain("Compatible endpoint sandbox smoke check failed"); + expect(diagnostics).toContain( + "Messaging setup is not the root cause; the sandbox inference.local route failed.", + ); + expect(diagnostics).toContain("curl exit 7"); + expect(diagnostics).not.toContain("Telegram"); + } finally { + exit.mockRestore(); + error.mockRestore(); + } }, ); it.each(providerNeutralCases)( "runs a real provider-neutral $service request inside the $agentName sandbox", - ({ agentName, service, provider, port, directHealthPath }) => { + async ({ agentName, service, provider, port, directHealthPath }) => { const runOpenshell = vi .fn() - .mockReturnValueOnce({ status: 0, stdout: "provider ready" }) + .mockImplementationOnce((args: string[]) => ({ + status: 0, + stdout: providerMetadata(args.at(-1) ?? ""), + })) .mockReturnValueOnce({ status: 0, stdout: "INFERENCE_SMOKE_OK PONG" }); - verifyCompatibleEndpointSandboxSmoke({ + await verifyCompatibleEndpointSandboxSmoke({ sandboxName: `${agentName}-sandbox`, provider, model: "qwen3.5-9b", @@ -522,16 +547,19 @@ describe("compatible endpoint sandbox smoke helpers", () => { }, ); - it("fails closed when the provider-neutral sandbox request or direct-host deny proof fails", () => { + it("fails closed when the provider-neutral sandbox request or direct-host deny proof fails", async () => { const exit = vi.spyOn(process, "exit").mockImplementation((code) => { throw new Error(`process.exit(${code})`); }); const runOpenshell = vi .fn() - .mockReturnValueOnce({ status: 0, stdout: "provider ready" }) + .mockImplementationOnce((args: string[]) => ({ + status: 0, + stdout: providerMetadata(args.at(-1) ?? ""), + })) .mockReturnValueOnce({ status: 1, stderr: "direct host inference deny could not be proven" }); - expect(() => + await expect( verifyCompatibleEndpointSandboxSmoke({ sandboxName: "hermes-sandbox", provider: "ollama-local", @@ -547,13 +575,13 @@ describe("compatible endpoint sandbox smoke helpers", () => { toolCallingRequired: true, }, }), - ).toThrow("process.exit(1)"); + ).rejects.toThrow("process.exit(1)"); expect(exit).toHaveBeenCalledWith(1); exit.mockRestore(); }); - it("builds a sandbox script that checks managed provider routing", () => { + it("builds a sandbox script that checks managed provider routing", async () => { const script = buildCompatibleEndpointSandboxSmokeScript("provider/model'"); expect(script).toContain("OPENCLAW_CONFIG_OK"); @@ -569,7 +597,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { expect(script).not.toContain("VALIDATE_OPENCLAW_CONFIG"); }); - it("builds a Python-only provider-neutral route allow and direct-host deny proof", () => { + it("builds a Python-only provider-neutral route allow and direct-host deny proof", async () => { const script = buildProviderNeutralInferenceSandboxSmokeScript("qwen3.5-9b", { service: "nim", directHostPort: 8001, @@ -607,7 +635,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { }, ); - it("retries reasoning-only content through the public sandbox verification path", () => { + it("retries reasoning-only content through the public sandbox verification path", async () => { const authority = allAgentProofAuthorities[0].authority; const model = "qwen3-vl:4b"; const responses = [ @@ -626,7 +654,10 @@ describe("compatible endpoint sandbox smoke helpers", () => { let result: ReturnType | undefined; const runOpenshell = vi .fn() - .mockReturnValueOnce({ status: 0, stdout: "provider ready" }) + .mockImplementationOnce((args: string[]) => ({ + status: 0, + stdout: providerMetadata(args.at(-1) ?? ""), + })) .mockImplementationOnce((args: string[]) => { result = runProviderNeutralScript({ authority, @@ -639,7 +670,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { const log = vi.spyOn(console, "log").mockImplementation(() => undefined); try { - verifyCompatibleEndpointSandboxSmoke({ + await verifyCompatibleEndpointSandboxSmoke({ sandboxName: "managed-inference-sandbox", provider: "ollama-local", model, @@ -661,7 +692,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { } }); - it("routes managed inference through the runtime proxy and bypasses it for direct denial (#10423)", () => { + it("routes managed inference through the runtime proxy and bypasses it for direct denial (#10423)", async () => { const authority = allAgentProofAuthorities[0].authority; const result = runProviderNeutralScript({ authority, @@ -678,7 +709,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { expect(result.stdout).toContain("DIRECT_REQUEST_COUNT=1"); }); - it("does not fall back to direct DNS when the managed runtime proxy is unavailable (#10423)", () => { + it("does not fall back to direct DNS when the managed runtime proxy is unavailable (#10423)", async () => { const result = runProviderNeutralScript({ authority: allAgentProofAuthorities[0].authority, managedProxyResponses: [], @@ -694,7 +725,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { expect(result.stdout).toContain("SLEEP_DELAYS=5,10"); }); - it("executes the provider-neutral proof for receipt-owned llama.cpp authority (#10423)", () => { + it("executes the provider-neutral proof for receipt-owned llama.cpp authority (#10423)", async () => { const result = runProviderNeutralScript({ authority: { service: "llama-cpp", @@ -713,7 +744,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { ); }); - it("fails after one larger-budget attempt when output remains reasoning-only", () => { + it("fails after one larger-budget attempt when output remains reasoning-only", async () => { const reasoningOnly = { model: "qwen3.5-9b", choices: [ @@ -870,7 +901,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { }, ); - it("accepts a content-only proof when durable authority marks tool calling optional", () => { + it("accepts a content-only proof when durable authority marks tool calling optional", async () => { const authority = { ...allAgentProofAuthorities[0].authority, toolCallingRequired: false, @@ -884,7 +915,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { expect(result.stdout).toContain("INFERENCE_SMOKE_OK PONG"); }); - it("rejects service-specific direct-host authority drift before sandbox execution", () => { + it("rejects service-specific direct-host authority drift before sandbox execution", async () => { expect(() => buildProviderNeutralInferenceSandboxSmokeScript("qwen3.5-9b", { service: "nim", @@ -895,7 +926,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { ).toThrow("exact provider health authority"); }); - it("rejects an oversized provider-neutral inference response before JSON parsing", () => { + it("rejects an oversized provider-neutral inference response before JSON parsing", async () => { const result = runProviderNeutralScript({ authority: allAgentProofAuthorities[0].authority, responses: [{ __oversized__: true }], @@ -905,7 +936,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { expect(result.stderr).toContain("response exceeded byte limit"); }); - it("does not mistake a reachable provider's own HTTP 403 for policy denial", () => { + it("does not mistake a reachable provider's own HTTP 403 for policy denial", async () => { const authority = allAgentProofAuthorities[2].authority; const result = runProviderNeutralScript({ authority, @@ -916,7 +947,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { expect(result.stderr).toContain("was not an OpenShell policy denial"); }); - it("accepts an exact OpenShell denial with guidance beyond the old 4096-byte window", () => { + it("accepts an exact OpenShell denial with guidance beyond the old 4096-byte window", async () => { const authority = allAgentProofAuthorities[2].authority; const directAuthority = `host.openshell.internal:${String(authority.directHostPort)}`; const result = runProviderNeutralScript({ @@ -932,7 +963,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { expect(result.stdout).toContain("INFERENCE_SMOKE_OK PONG"); }); - it("rejects an oversized OpenShell policy-denial body before parsing", () => { + it("rejects an oversized OpenShell policy-denial body before parsing", async () => { const result = runProviderNeutralScript({ authority: allAgentProofAuthorities[2].authority, denialOversized: true, @@ -942,7 +973,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { expect(result.stderr).toContain("policy-denial response exceeded byte limit"); }); - it("reports malformed OpenShell policy-denial JSON separately", () => { + it("reports malformed OpenShell policy-denial JSON separately", async () => { const result = runProviderNeutralScript({ authority: allAgentProofAuthorities[2].authority, denialBytes: Array.from(Buffer.from('{"error":', "utf8")), @@ -952,7 +983,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { expect(result.stderr).toContain("policy-denial response was not valid JSON"); }); - it("reports invalid UTF-8 in an OpenShell policy-denial body separately", () => { + it("reports invalid UTF-8 in an OpenShell policy-denial body separately", async () => { const result = runProviderNeutralScript({ authority: allAgentProofAuthorities[2].authority, denialBytes: [0xff], @@ -962,7 +993,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { expect(result.stderr).toContain("policy-denial response was not valid UTF-8"); }); - it("reports OpenShell policy-denial contract format drift separately", () => { + it("reports OpenShell policy-denial contract format drift separately", async () => { const authority = allAgentProofAuthorities[2].authority; const result = runProviderNeutralScript({ authority, @@ -977,7 +1008,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { expect(result.stderr).not.toContain("was not an OpenShell policy denial"); }); - it("shell-quotes hostile model text through the generated smoke script", () => { + it("shell-quotes hostile model text through the generated smoke script", async () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-compat-smoke-quoting-")); const sentinel = path.join(tmpDir, "model-command-ran"); const model = "foo'bar`baz$(touch " + sentinel + ")"; @@ -996,7 +1027,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { expect(fs.existsSync(sentinel)).toBe(false); }); - it("retries a reasoning-only length response before failing the sandbox smoke", () => { + it("retries a reasoning-only length response before failing the sandbox smoke", async () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-compat-smoke-reasoning-")); const model = "provider/reasoning-model"; const configPath = writeSmokeConfig(tmpDir, model); @@ -1031,7 +1062,7 @@ fi expect(fs.readFileSync(callFile, "utf-8")).toBe("2"); }); - it("retries a transient non-JSON gateway response", () => { + it("retries a transient non-JSON gateway response", async () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-compat-smoke-transient-")); const model = "nvidia/nemotron-3-ultra"; const configPath = writeSmokeConfig(tmpDir, model); @@ -1060,7 +1091,7 @@ fi expect(fs.readFileSync(callFile, "utf-8")).toBe("2"); }); - it("retries a parseable JSON HTTP 500 response", () => { + it("retries a parseable JSON HTTP 500 response", async () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-compat-smoke-json-500-")); const model = "nvidia/nemotron-3-ultra"; const configPath = writeSmokeConfig(tmpDir, model); @@ -1090,7 +1121,7 @@ fi expect(fs.readFileSync(callFile, "utf-8")).toBe("2"); }); - it("backs off for 5s then 10s between three attempts", () => { + it("backs off for 5s then 10s between three attempts", async () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-compat-smoke-backoff-")); const model = "nvidia/nemotron-3-ultra"; const configPath = writeSmokeConfig(tmpDir, model); @@ -1118,7 +1149,7 @@ fi expect(fs.readFileSync(sleepFile, "utf-8")).toBe("5\n10\n"); }); - it("does not retry a parseable JSON HTTP 429 response", () => { + it("does not retry a parseable JSON HTTP 429 response", async () => { // Fail closed: a blind replay cannot honor Retry-After and amplifies overload. const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-compat-smoke-json-429-")); const model = "nvidia/nemotron-3-ultra"; @@ -1176,7 +1207,7 @@ printf '%s\n' '{"choices":[{"message":{"content":"PONG"},"finish_reason":"stop"} }, ); - it("does not retry a permanent curl exit", () => { + it("does not retry a permanent curl exit", async () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-compat-smoke-curl-terminal-")); const model = "nvidia/nemotron-3-ultra"; const configPath = writeSmokeConfig(tmpDir, model); @@ -1195,7 +1226,7 @@ printf '%s\n' '{"choices":[{"message":{"content":"PONG"},"finish_reason":"stop"} expect(fs.readFileSync(callFile, "utf-8")).toBe("1"); }); - it("does not retry a permanent JSON response validation failure", () => { + it("does not retry a permanent JSON response validation failure", async () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-compat-smoke-permanent-")); const model = "nvidia/nemotron-3-ultra"; const configPath = writeSmokeConfig(tmpDir, model); @@ -1217,7 +1248,7 @@ printf '%s\n' '{"choices":[{"message":{"content":"PONG"},"finish_reason":"stop"} expect(fs.readFileSync(callFile, "utf-8")).toBe("1"); }); - it("fails after the bounded transient retry budget", () => { + it("fails after the bounded transient retry budget", async () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-compat-smoke-exhausted-")); const model = "nvidia/nemotron-3-ultra"; const configPath = writeSmokeConfig(tmpDir, model); @@ -1242,7 +1273,7 @@ printf '%s\n' '{"choices":[{"message":{"content":"PONG"},"finish_reason":"stop"} expect(fs.readFileSync(callFile, "utf-8")).toBe("3"); }); - it("reports a model-output budget problem when the retry also has no assistant content", () => { + it("reports a model-output budget problem when the retry also has no assistant content", async () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-compat-smoke-no-content-")); const model = "provider/reasoning-model"; const configPath = writeSmokeConfig(tmpDir, model); @@ -1270,7 +1301,7 @@ JSON expect(fs.readFileSync(callFile, "utf-8")).toBe("2"); }); - it("passes the native multiline script through the OpenShell command argument", () => { + it("passes the native multiline script through the OpenShell command argument", async () => { const command = buildCompatibleEndpointSandboxSmokeCommand("nvidia/model"); expect(command).toBe(buildCompatibleEndpointSandboxSmokeScript("nvidia/model")); diff --git a/src/lib/onboard/compatible-endpoint-smoke.ts b/src/lib/onboard/compatible-endpoint-smoke.ts index ca7693fdf89..84cb9b6a05e 100644 --- a/src/lib/onboard/compatible-endpoint-smoke.ts +++ b/src/lib/onboard/compatible-endpoint-smoke.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import type { StdioOptions } from "node:child_process"; +import { createCliOpenShellProviderAdapter } from "../adapters/openshell/provider-adapter-cli"; import { shellQuote } from "../core/shell-quote"; import { compactText } from "../core/url-utils"; import { INFERENCE_ROUTE_URL, MANAGED_PROVIDER_ID } from "../inference/config"; @@ -98,7 +99,7 @@ export function spawnOutputToString(value: unknown): string { return String(value); } -export function verifyCompatibleEndpointSandboxSmoke(options: { +export async function verifyCompatibleEndpointSandboxSmoke(options: { sandboxName: string; provider: string; model: string; @@ -113,7 +114,7 @@ export function verifyCompatibleEndpointSandboxSmoke(options: { hostLocalInferenceProofAuthority?: HostLocalInferenceSandboxProofAuthority; /** Recheck sandbox identity after the sandbox proof and before success output. */ beforeSuccess?: () => void; -}): void { +}): Promise { const agentName = options.agent?.name || "openclaw"; if ( options.forceCanonicalRoute !== true && @@ -128,48 +129,40 @@ export function verifyCompatibleEndpointSandboxSmoke(options: { : " Verifying compatible endpoint through the sandbox runtime...", ); - const providerResult = options.runOpenshell(["provider", "get", options.provider], { - ignoreError: true, - suppressOutput: true, - stdio: ["ignore", "pipe", "pipe"], + const adapter = createCliOpenShellProviderAdapter({ + run: (command, runOptions) => { + const result = options.runOpenshell(command, runOptions); + return { + status: result.status, + stdout: + typeof result.stdout === "string" || Buffer.isBuffer(result.stdout) + ? result.stdout + : null, + stderr: + typeof result.stderr === "string" || Buffer.isBuffer(result.stderr) + ? result.stderr + : null, + }; + }, + }); + const providerResult = await adapter.getProvider({ + target: { kind: "selected" }, + providerName: options.provider, }); - const providerDetails = [ - spawnOutputToString(providerResult.stdout), - spawnOutputToString(providerResult.stderr), - ] - .join("\n") - .trim(); - if (providerResult.status !== 0) { + if (!providerResult.ok) { console.error( options.forceCanonicalRoute ? ` Provider-neutral inference provider '${options.provider}' is missing or unreachable in the OpenShell gateway.` : ` Compatible endpoint provider '${options.provider}' is missing from the OpenShell gateway.`, ); console.error(" The sandbox inference.local route cannot reach the selected model provider."); - if (providerDetails) { - console.error(` ${compactText(options.redact(providerDetails)).slice(0, 800)}`); - } - process.exit(providerResult.status || 1); - } - - if ( - options.forceCanonicalRoute !== true && - options.endpointUrl && - providerDetails && - /OPENAI_BASE_URL|baseUrl|base URL|endpoint/i.test(providerDetails) && - !providerDetails.includes(options.endpointUrl) - ) { - console.warn( - ` \u26a0 Gateway provider '${options.provider}' did not report the selected endpoint URL.`, - ); - console.warn(" Continuing to the sandbox-side inference.local smoke check."); + console.error(` ${compactText(options.redact(providerResult.error.message)).slice(0, 800)}`); + process.exit(1); } if ( options.credentialEnv && - providerDetails && - /credential|api key|secret/i.test(providerDetails) && - !providerDetails.includes(options.credentialEnv) + !providerResult.value.credentialKeys.includes(options.credentialEnv) ) { console.warn( ` \u26a0 Gateway provider '${options.provider}' did not report the selected credential binding.`, diff --git a/src/lib/onboard/created-sandbox-finalization.test.ts b/src/lib/onboard/created-sandbox-finalization.test.ts index a682f60b084..592de113fe5 100644 --- a/src/lib/onboard/created-sandbox-finalization.test.ts +++ b/src/lib/onboard/created-sandbox-finalization.test.ts @@ -72,13 +72,13 @@ describe("created sandbox registration authority", () => { }); describe("new sandbox cancellation recovery", () => { - it("preserves recovery guidance when the durable identity is unavailable (#9833)", () => { + it("preserves recovery guidance when the durable identity is unavailable (#9833)", async () => { const error = vi.spyOn(console, "error").mockImplementation(() => undefined); const runFile = vi.fn(); const armCancelRollback = vi.fn(); const markCancellationRecovery = vi.fn(); - expect(() => + await expect( completeOrdinaryOnboardSandboxCreation( { sandboxName: "new-sandbox", @@ -102,7 +102,7 @@ describe("new sandbox cancellation recovery", () => { applyVmDnsMonkeypatch: vi.fn(), }, ), - ).toThrow("Sandbox 'new-sandbox' has no exact identity for cancel recovery."); + ).rejects.toThrow("Sandbox 'new-sandbox' has no exact identity for cancel recovery."); const guidance = error.mock.calls.flat().join("\n"); expect(guidance).toContain("Sandbox 'new-sandbox' was created on gateway 'nemoclaw'"); @@ -650,7 +650,9 @@ describe("created DCode sandbox finalization", () => { expect(register).not.toHaveBeenCalled(); expect(error).toHaveBeenCalledWith(expect.stringContaining("sandbox still exists")); expect(error).toHaveBeenCalledWith(expect.stringContaining("rebuild is unsafe")); - expect(error).toHaveBeenCalledWith(expect.stringContaining("Recovery remains blocked while this sandbox exists")); + expect(error).toHaveBeenCalledWith( + expect.stringContaining("Recovery remains blocked while this sandbox exists"), + ); expect(error.mock.calls.flat().join("\n")).not.toContain("openshell sandbox delete"); expect(error).toHaveBeenCalledWith(expect.stringContaining("nemoclaw onboard")); }); @@ -1055,7 +1057,9 @@ describe("created OpenClaw sandbox finalization", () => { expect(error).toHaveBeenCalledWith( " State was not restored and registry metadata was not updated.", ); - expect(error).toHaveBeenCalledWith(expect.stringContaining("Recovery remains blocked while this sandbox exists")); + expect(error).toHaveBeenCalledWith( + expect.stringContaining("Recovery remains blocked while this sandbox exists"), + ); expect(error.mock.calls.flat().join("\n")).not.toContain("openshell sandbox delete"); expect(error).toHaveBeenCalledWith(" Manual recovery: /tmp/managed-openclaw-backup"); }); @@ -1102,7 +1106,9 @@ describe("created OpenClaw sandbox finalization", () => { expect(error).toHaveBeenCalledWith( " State was not restored and registry metadata was not updated.", ); - expect(error).toHaveBeenCalledWith(expect.stringContaining("Recovery remains blocked while this sandbox exists")); + expect(error).toHaveBeenCalledWith( + expect.stringContaining("Recovery remains blocked while this sandbox exists"), + ); expect(error.mock.calls.flat().join("\n")).not.toContain("openshell sandbox delete"); expect(error).toHaveBeenCalledWith( " Then rerun the original `nemoclaw onboard --from ` command.", @@ -1158,7 +1164,9 @@ describe("created OpenClaw sandbox finalization", () => { expect(error).toHaveBeenCalledWith( expect.stringContaining(sandboxState.OPENCLAW_IMAGE_PLUGIN_PROVENANCE_RESTORE_ERROR), ); - expect(error).toHaveBeenCalledWith(expect.stringContaining("Recovery remains blocked while this sandbox exists")); + expect(error).toHaveBeenCalledWith( + expect.stringContaining("Recovery remains blocked while this sandbox exists"), + ); expect(error.mock.calls.flat().join("\n")).not.toContain("openshell sandbox delete"); expect(error).toHaveBeenCalledWith( " Then rerun the original `nemoclaw onboard --from ` command.", diff --git a/src/lib/onboard/created-sandbox-finalization.ts b/src/lib/onboard/created-sandbox-finalization.ts index de81ac8c984..24eaa874b8c 100644 --- a/src/lib/onboard/created-sandbox-finalization.ts +++ b/src/lib/onboard/created-sandbox-finalization.ts @@ -242,7 +242,7 @@ export function createOnboardCreatedSandboxRegistration(input: { } /** Finish ordinary post-registration actions after portable onboarding has returned. */ -export function completeOrdinaryOnboardSandboxCreation( +export async function completeOrdinaryOnboardSandboxCreation( input: { readonly sandboxName: string; readonly sandboxWasLiveDefault: boolean; @@ -257,7 +257,7 @@ export function completeOrdinaryOnboardSandboxCreation( readonly runFile: (command: string, args: string[], options: { ignoreError: true }) => unknown; readonly scriptsDir: string; readonly gatewayName: string; - readonly providerExistsInGateway: (providerName: string) => boolean; + readonly providerExistsInGateway: (providerName: string) => boolean | Promise; readonly armCancelRollback: (sandboxName: string, sandboxIdentityFingerprint: string) => void; readonly markCancellationRecovery: (sandboxName: string) => unknown; readonly dockerInfoFormat: Parameters[0]["dockerInfoFormat"]; @@ -265,7 +265,7 @@ export function completeOrdinaryOnboardSandboxCreation( readonly revalidateSandboxIdentity: (operation: string) => void; readonly applyVmDnsMonkeypatch?: typeof applyOnboardVmDnsMonkeypatch; }, -): string { +): Promise { deps.revalidateSandboxIdentity(`completing sandbox '${input.sandboxName}'`); restoreDefaultAfterRecreate(deps.setDefault, input.sandboxName, input.sandboxWasLiveDefault); deps.revalidateSandboxIdentity(`starting DNS setup for sandbox '${input.sandboxName}'`); @@ -284,7 +284,7 @@ export function completeOrdinaryOnboardSandboxCreation( { revalidateSandboxIdentity: deps.revalidateSandboxIdentity }, ); for (const provider of input.messagingProviders) { - if (!deps.providerExistsInGateway(provider)) printMessagingProviderMissing(provider); + if (!(await deps.providerExistsInGateway(provider))) printMessagingProviderMissing(provider); } deps.revalidateSandboxIdentity(`reporting sandbox '${input.sandboxName}' creation success`); console.log(` ✓ Sandbox '${input.sandboxName}' created`); diff --git a/src/lib/onboard/credential-provider-registration.test.ts b/src/lib/onboard/credential-provider-registration.test.ts index d4a46babc45..ba45f148100 100644 --- a/src/lib/onboard/credential-provider-registration.test.ts +++ b/src/lib/onboard/credential-provider-registration.test.ts @@ -215,7 +215,7 @@ describe("credential provider registration", () => { }, ])( "reuses a tokenless Hermes Discord provider only when its static profile $condition", - ({ endpoints, expected }) => { + async ({ endpoints, expected }) => { const session = { stagedCredentialProviders: [] } as unknown as Session; const runOpenshell = vi.fn((args: string[]) => args.includes("profile") && args.includes("export") @@ -235,7 +235,7 @@ describe("credential provider registration", () => { const registration = createCredentialProviderRegistration(deps); expect( - registration.providerMatchesGatewayCredential( + await registration.providerMatchesGatewayCredential( "alpha-discord-bridge", "discord-hermes-static-v1", "DISCORD_BOT_TOKEN", @@ -262,7 +262,7 @@ describe("credential provider registration", () => { }, ); - it("uses one selected gateway for static profile and provider identity", () => { + it("uses one selected gateway for static profile and provider identity", async () => { const session = { stagedCredentialProviders: [] } as unknown as Session; const commandResults = new Map([ [ @@ -290,7 +290,7 @@ describe("credential provider registration", () => { const registration = createCredentialProviderRegistration(deps); expect( - registration.providerMatchesGatewayCredential( + await registration.providerMatchesGatewayCredential( "alpha-discord-bridge", "discord-hermes-static-v1", "DISCORD_BOT_TOKEN", @@ -325,7 +325,7 @@ describe("credential provider registration", () => { { condition: "malformed provider metadata", result: () => ({ status: 0, stdout: "unexpected output" }), - expected: { kind: "collision" as const }, + expected: { kind: "indeterminate" as const }, }, { condition: "a thrown gateway command", @@ -334,14 +334,14 @@ describe("credential provider registration", () => { }, expected: { kind: "indeterminate" as const }, }, - ])("preserves $condition when inspecting a credential binding", ({ result, expected }) => { + ])("preserves $condition when inspecting a credential binding", async ({ result, expected }) => { const session = { stagedCredentialProviders: [] } as unknown as Session; const registration = createCredentialProviderRegistration( registrationDeps(vi.fn(result), session), ); expect( - registration.inspectGatewayCredential( + await registration.inspectGatewayCredential( "alpha-telegram-bridge", "nemoclaw-mcp-v1", "TELEGRAM_BOT_TOKEN", @@ -349,7 +349,7 @@ describe("credential provider registration", () => { ).toEqual(expected); }); - it("treats a failed static profile inspection as indeterminate", () => { + it("treats a failed static profile inspection as indeterminate", async () => { const session = { stagedCredentialProviders: [] } as unknown as Session; const runOpenshell = vi.fn((args: string[]) => args.includes("profile") @@ -361,7 +361,7 @@ describe("credential provider registration", () => { const registration = createCredentialProviderRegistration(deps); expect( - registration.inspectGatewayCredential( + await registration.inspectGatewayCredential( "alpha-discord-bridge", "discord-hermes-static-v1", "DISCORD_BOT_TOKEN", @@ -432,16 +432,20 @@ describe("credential provider registration", () => { }, ])( "records migration according to the value sent when $condition", - ({ env, ambientValue, expectedMigrated }) => { + async ({ env, ambientValue, expectedMigrated }) => { const session = { stagedCredentialProviders: [] } as unknown as Session; - const runOpenshell = vi.fn(() => ({ status: 0, stdout: "", stderr: "" })); + const runOpenshell = vi.fn((args: string[]) => + args[1] === "get" + ? providerMetadata("compatible-endpoint", "openai", "COMPATIBLE_API_KEY") + : { status: 0, stdout: "", stderr: "" }, + ); const deps = registrationDeps(runOpenshell, session); deps.getCredential = vi.fn(() => ambientValue); deps.stagedLegacyValues = new Map([["COMPATIBLE_API_KEY", "legacy-key"]]); deps.migratedLegacyKeys.add("COMPATIBLE_API_KEY"); const registration = createCredentialProviderRegistration(deps); - const result = registration.upsertProvider( + const result = await registration.upsertProvider( "compatible-endpoint", "openai", "COMPATIBLE_API_KEY", @@ -460,7 +464,7 @@ describe("credential provider registration", () => { }, ); - it("does not record migration when provider registration fails", () => { + it("does not record migration when provider registration fails", async () => { const session = { stagedCredentialProviders: [] } as unknown as Session; const runOpenshell = vi.fn((args: string[]) => ({ status: args[1] === "get" ? 1 : 9, @@ -471,7 +475,7 @@ describe("credential provider registration", () => { deps.stagedLegacyValues = new Map([["COMPATIBLE_API_KEY", "legacy-key"]]); const registration = createCredentialProviderRegistration(deps); - const result = registration.upsertProvider( + const result = await registration.upsertProvider( "compatible-endpoint", "openai", "COMPATIBLE_API_KEY", @@ -920,10 +924,7 @@ describe("credential provider registration", () => { sandboxCreateProviderArgs: ["--provider", providerName], }); const cleanup = vi.spyOn(MessagingSetupApplier, "cleanupProvidersAtOpenShell"); - const deps = registrationDeps( - vi.fn(), - { stagedCredentialProviders: [] } as unknown as Session, - ); + const deps = registrationDeps(vi.fn(), { stagedCredentialProviders: [] } as unknown as Session); deps.stagedLegacyValues = new Map([["DISCORD_BOT_TOKEN", DISCORD_SECRET]]); deps.persistMigratedLegacyKeys = vi.fn(() => { throw new Error("receipt persistence failed"); diff --git a/src/lib/onboard/credential-provider-registration.ts b/src/lib/onboard/credential-provider-registration.ts index 04bcf7a2607..0d6b0786af1 100644 --- a/src/lib/onboard/credential-provider-registration.ts +++ b/src/lib/onboard/credential-provider-registration.ts @@ -234,7 +234,7 @@ function validatePlannedCredentialProviderBindings( export function createCredentialProviderRegistration(deps: CredentialProviderRegistrationDeps) { const gatewayRunner = (gatewayName = deps.getGatewayName()) => createGatewayScopedOpenshellRunner(deps.runOpenshell, gatewayName); - function upsertProvider( + async function upsertProvider( name: string, type: string, credentialEnv: string, @@ -243,7 +243,7 @@ export function createCredentialProviderRegistration(deps: CredentialProviderReg gatewayName = deps.getGatewayName(), options: MessagingProviderRegistrationOptions = {}, ) { - const result = providers.upsertProvider( + const result = await providers.upsertProvider( name, type, credentialEnv, @@ -332,45 +332,53 @@ export function createCredentialProviderRegistration(deps: CredentialProviderReg } } - function credentialBindingMatchesGateway( + async function credentialBindingMatchesGateway( binding: CheckpointProviderBinding, runOpenshell: OpenshellCliHelpers["runOpenshell"], - ): boolean { - return inspectGatewayCredentialBinding(binding, runOpenshell).kind === "exact"; + ): Promise { + return (await inspectGatewayCredentialBinding(binding, runOpenshell)).kind === "exact"; } - function inspectGatewayCredentialBinding( + async function inspectGatewayCredentialBinding( binding: CheckpointProviderBinding, runOpenshell: OpenshellCliHelpers["runOpenshell"], - ): gatewayProviderMetadata.GatewayCredentialOnlyProviderInspection { + ): Promise { const profileMatches = messagingBridgeProvider.matchesRegisteredMessagingBridgeProfile( binding.type, { root: deps.root, runOpenshell }, ); if (profileMatches === false) return { kind: "indeterminate" }; - return gatewayProviderMetadata.inspectGatewayCredentialFamilyProviderBinding( - { - name: binding.name, - type: binding.type, - credentialKey: binding.credentialEnv, - }, - runOpenshell, - ); + const observed = await createCliOpenShellProviderAdapter({ run: runOpenshell }).getProvider({ + target: { kind: "selected" }, + providerName: binding.name, + }); + if (!observed.ok) { + return observed.error.kind === "command" && observed.error.reason === "not_found" + ? { kind: "missing" } + : { kind: "indeterminate" }; + } + return gatewayProviderMetadata.matchesGatewayCredentialFamilyProviderBinding(observed.value, { + name: binding.name, + type: binding.type, + credentialKey: binding.credentialEnv, + }) + ? { kind: "exact" } + : { kind: "collision" }; } - function inspectGatewayCredential( + async function inspectGatewayCredential( name: string, type: string, credentialEnv: string, - ): gatewayProviderMetadata.GatewayCredentialOnlyProviderInspection { + ): Promise { return inspectGatewayCredentialBinding({ name, type, credentialEnv }, gatewayRunner()); } - function providerMatchesGatewayCredential( + async function providerMatchesGatewayCredential( name: string, type: string, credentialEnv: string, - ): boolean { + ): Promise { return credentialBindingMatchesGateway({ name, type, credentialEnv }, gatewayRunner()); } diff --git a/src/lib/onboard/extra-provider-reconciliation-diagnostics.test.ts b/src/lib/onboard/extra-provider-reconciliation-diagnostics.test.ts index 79ed8677d69..2952112051a 100644 --- a/src/lib/onboard/extra-provider-reconciliation-diagnostics.test.ts +++ b/src/lib/onboard/extra-provider-reconciliation-diagnostics.test.ts @@ -97,8 +97,8 @@ describe("reconcileRegisteredExtraProviders diagnostics", () => { provider: "my-gateway-provider", stderr: "Error: provider 'my-gateway-provider' not found", }, - ])("accepts exact $label not-found diagnostics (#6501)", ({ provider, stderr }) => { - expect(reconcile([provider], { [provider]: { status: 1, stderr } })).toEqual([]); + ])("accepts exact $label not-found diagnostics (#6501)", async ({ provider, stderr }) => { + expect(await reconcile([provider], { [provider]: { status: 1, stderr } })).toEqual([]); }); it.each([ @@ -128,19 +128,19 @@ describe("reconcileRegisteredExtraProviders diagnostics", () => { "conflicting structured status", "Error: status: Unavailable, message: \"provider 'stale-provider' not found\"", ], - ])("preserves providers for ambiguous diagnostics: %s (#6501)", (_label, stderr) => { + ])("preserves providers for ambiguous diagnostics: %s (#6501)", async (_label, stderr) => { expect( - reconcile(["stale-provider"], { + await reconcile(["stale-provider"], { "stale-provider": { status: 1, stderr }, }), ).toEqual(["stale-provider"]); }); - it("uses composite output only when stderr and stdout are empty (#6501)", () => { + it("uses composite output only when stderr and stdout are empty (#6501)", async () => { const diagnostic = Buffer.from("Error: provider 'stale-provider' not found"); expect( - reconcile(["stale-provider"], { + await reconcile(["stale-provider"], { "stale-provider": { status: 1, output: [null, Buffer.alloc(0), diagnostic], @@ -151,12 +151,12 @@ describe("reconcileRegisteredExtraProviders diagnostics", () => { ).toEqual([]); }); - it("bounds diagnostics before parsing and warns without leaking provider names (#6501)", () => { + it("bounds diagnostics before parsing and warns without leaking provider names (#6501)", async () => { const warn = vi.fn(); const recorded = ["at-limit-provider", "ambiguous-provider"]; expect( - reconcile( + await reconcile( recorded, { "at-limit-provider": { @@ -170,20 +170,20 @@ describe("reconcileRegisteredExtraProviders diagnostics", () => { }, { warn }, ), - ).toEqual(recorded); + ).toEqual(["ambiguous-provider"]); expect(warn).toHaveBeenCalledWith( " Warning: extra-provider reconciliation preserved indeterminate attachments " + - "(providerCount=2; reasonClasses=ambiguous-diagnostic,diagnostic-capture-limit).", + "(providerCount=1; reasonClasses=ambiguous-diagnostic).", ); expect(warn.mock.calls[0]?.[0]).not.toContain("at-limit-provider"); expect(warn.mock.calls[0]?.[0]).not.toContain("ambiguous-provider"); }); - it("redacts exact diagnostic provider names from warnings (#6501)", () => { + it("redacts exact diagnostic provider names from warnings (#6501)", async () => { const warn = vi.fn(); expect( - reconcile( + await reconcile( ["exact-provider", "named-ambiguous-provider"], { "exact-provider": { @@ -207,9 +207,9 @@ describe("reconcileRegisteredExtraProviders diagnostics", () => { expect(warn.mock.calls[0]?.[0]).not.toContain("named-ambiguous-provider"); }); - it("keeps branch priority deterministic for conflicting diagnostics (#6501)", () => { + it("keeps branch priority deterministic for conflicting diagnostics (#6501)", async () => { expect( - reconcile(["stale-provider"], { + await reconcile(["stale-provider"], { "stale-provider": { status: 1, stderr: [ @@ -220,7 +220,7 @@ describe("reconcileRegisteredExtraProviders diagnostics", () => { }), ).toEqual(["stale-provider"]); expect( - reconcile(["stale-provider"], { + await reconcile(["stale-provider"], { "stale-provider": { status: 1, stderr: [ @@ -232,9 +232,9 @@ describe("reconcileRegisteredExtraProviders diagnostics", () => { ).toEqual(["stale-provider"]); }); - it("preserves providers when the not-found diagnostic uses different casing (#6501)", () => { + it("preserves providers when the not-found diagnostic uses different casing (#6501)", async () => { expect( - reconcile(["tavily-search"], { + await reconcile(["tavily-search"], { "tavily-search": { status: 1, stderr: "Error: provider 'Tavily-Search' not found", @@ -243,7 +243,7 @@ describe("reconcileRegisteredExtraProviders diagnostics", () => { ).toEqual(["tavily-search"]); }); - it("parses adversarial diagnostics within a bounded budget (#6501)", () => { + it("parses adversarial diagnostics within a bounded budget (#6501)", async () => { const adversarial = [ `${"error: ".repeat(2_000)}provider 'redos-provider' not found`, `Error: provider '${"a".repeat(8_000)}`, @@ -253,7 +253,7 @@ describe("reconcileRegisteredExtraProviders diagnostics", () => { const started = performance.now(); expect( - reconcile(["redos-provider"], { + await reconcile(["redos-provider"], { "redos-provider": { status: 1, stderr: adversarial }, }), ).toEqual(["redos-provider"]); diff --git a/src/lib/onboard/extra-provider-reconciliation-probes.test.ts b/src/lib/onboard/extra-provider-reconciliation-probes.test.ts index 07a2d087d13..e58d4239290 100644 --- a/src/lib/onboard/extra-provider-reconciliation-probes.test.ts +++ b/src/lib/onboard/extra-provider-reconciliation-probes.test.ts @@ -15,7 +15,7 @@ afterEach(() => { }); describe("reconcileRegisteredExtraProviders probe outcomes", () => { - it("preserves providers for thrown, timed-out, process-error, and nonstandard probes (#6501)", () => { + it("preserves providers for thrown, timed-out, process-error, and nonstandard probes (#6501)", async () => { const warn = vi.fn(); const recorded = [ "thrown-provider", @@ -25,7 +25,7 @@ describe("reconcileRegisteredExtraProviders probe outcomes", () => { ]; expect( - reconcile( + await reconcile( recorded, { "thrown-provider": () => { @@ -50,11 +50,11 @@ describe("reconcileRegisteredExtraProviders probe outcomes", () => { ).toEqual(recorded); expect(warn).toHaveBeenCalledWith( " Warning: extra-provider reconciliation preserved indeterminate attachments " + - "(providerCount=4; reasonClasses=probe-process-error,probe-threw,timeout-or-signal,unexpected-exit).", + "(providerCount=4; reasonClasses=ambiguous-diagnostic).", ); }); - it("bounds aggregate probe latency and preserves names left after the deadline (#6501)", () => { + it("bounds aggregate probe latency and preserves names left after the deadline (#6501)", async () => { let now = 0; const timeouts: number[] = []; const warn = vi.fn(); @@ -67,7 +67,7 @@ describe("reconcileRegisteredExtraProviders probe outcomes", () => { const recorded = ["provider-1", "provider-2", "provider-3", "provider-4", "provider-5"]; expect( - reconcileRegisteredExtraProviders("nemoclaw", { + await reconcileRegisteredExtraProviders("nemoclaw", { listExtraProviders: () => [...recorded], nowMs: () => now, removeExtraProvider: () => true, @@ -79,29 +79,29 @@ describe("reconcileRegisteredExtraProviders probe outcomes", () => { expect(timeouts).toEqual([5_000, 5_000, 5_000]); expect(warn).toHaveBeenCalledWith( " Warning: extra-provider reconciliation preserved indeterminate attachments " + - "(providerCount=5; reasonClasses=aggregate-time-budget,timeout-or-signal).", + "(providerCount=5; reasonClasses=aggregate-time-budget,ambiguous-diagnostic).", ); }); - it("enforces gateway containment and requires a gateway name before probing (#6501)", () => { + it("enforces gateway containment and requires a gateway name before probing (#6501)", async () => { const runOpenshell = vi.fn((): ProbeResult => ok()); vi.stubEnv("OPENSHELL_GATEWAY_ENDPOINT", "https://other.example.test"); - expect(() => + await expect( reconcileRegisteredExtraProviders("nemoclaw", { listExtraProviders: () => ["custom-provider"], removeExtraProvider: () => true, runOpenshell, }), - ).toThrow(/OPENSHELL_GATEWAY_ENDPOINT is set/); + ).rejects.toThrow(/OPENSHELL_GATEWAY_ENDPOINT is set/); vi.unstubAllEnvs(); - expect(() => + await expect( reconcileRegisteredExtraProviders("", { listExtraProviders: () => ["custom-provider"], removeExtraProvider: () => true, runOpenshell, }), - ).toThrow("OpenShell gateway name is required."); + ).rejects.toThrow("OpenShell gateway name is required."); expect(runOpenshell).not.toHaveBeenCalled(); }); }); diff --git a/src/lib/onboard/extra-provider-reconciliation.test-fixtures.ts b/src/lib/onboard/extra-provider-reconciliation.test-fixtures.ts index d16e2194846..1fb245db1f3 100644 --- a/src/lib/onboard/extra-provider-reconciliation.test-fixtures.ts +++ b/src/lib/onboard/extra-provider-reconciliation.test-fixtures.ts @@ -8,8 +8,8 @@ export type ProbeResult = { status: number | null; error?: Error; output?: unknown; - stdout?: unknown; - stderr?: unknown; + stdout?: string | Buffer | null; + stderr?: string | Buffer | null; }; export const LIMIT = 64 * 1024; @@ -25,7 +25,7 @@ export function reconcile( recorded: string[], responses: Record ProbeResult)> = {}, extra: Partial[1]> = {}, -): string[] { +): Promise { return reconcileRegisteredExtraProviders("nemoclaw", { listExtraProviders: () => [...recorded], removeExtraProvider: () => true, diff --git a/src/lib/onboard/extra-provider-reconciliation.test.ts b/src/lib/onboard/extra-provider-reconciliation.test.ts index 528b87bf4d0..81542988d88 100644 --- a/src/lib/onboard/extra-provider-reconciliation.test.ts +++ b/src/lib/onboard/extra-provider-reconciliation.test.ts @@ -20,11 +20,11 @@ afterEach(() => { }); describe("reconcileRegisteredExtraProviders", () => { - it("skips gateway probes when no extra provider is recorded (#6501)", () => { + it("skips gateway probes when no extra provider is recorded (#6501)", async () => { const runOpenshell = vi.fn((): ProbeResult => ok()); expect( - reconcileRegisteredExtraProviders("nemoclaw", { + await reconcileRegisteredExtraProviders("nemoclaw", { listExtraProviders: () => [], runOpenshell, }), @@ -32,7 +32,7 @@ describe("reconcileRegisteredExtraProviders", () => { expect(runOpenshell).not.toHaveBeenCalled(); }); - it("probes every recorded provider exactly and never trusts provider-list snapshots (#6501)", () => { + it("probes every recorded provider exactly and never trusts provider-list snapshots (#6501)", async () => { const recorded = Array.from({ length: 128 }, (_value, index) => `custom-provider-${index}`); const calls: Array<{ args: string[]; @@ -45,7 +45,7 @@ describe("reconcileRegisteredExtraProviders", () => { }); expect( - reconcileRegisteredExtraProviders("nemoclaw", { + await reconcileRegisteredExtraProviders("nemoclaw", { listExtraProviders: () => [...recorded], removeExtraProvider, runOpenshell, @@ -66,9 +66,9 @@ describe("reconcileRegisteredExtraProviders", () => { }); }); - it("keeps healthy providers and omits only exact provider-specific not-found diagnostics (#6501)", () => { + it("keeps healthy providers and omits only exact provider-specific not-found diagnostics (#6501)", async () => { expect( - reconcile(["healthy-provider", "stale-provider", "indeterminate-provider"], { + await reconcile(["healthy-provider", "stale-provider", "indeterminate-provider"], { "stale-provider": { status: 1, stderr: Buffer.from("Error: provider 'stale-provider' not found\n"), @@ -78,9 +78,9 @@ describe("reconcileRegisteredExtraProviders", () => { ).toEqual(["healthy-provider", "indeterminate-provider"]); }); - it("plans stale-provider cleanup without mutation until apply (#6226)", () => { + it("plans stale-provider cleanup without mutation until apply (#6226)", async () => { const removeExtraProvider = vi.fn(() => true); - const plan = planRegisteredExtraProviders("nemoclaw", { + const plan = await planRegisteredExtraProviders("nemoclaw", { listExtraProviders: () => ["healthy-provider", "stale-provider"], removeExtraProvider, runOpenshell: (args) => (args.at(-1) === "stale-provider" ? missing("stale-provider") : ok()), diff --git a/src/lib/onboard/extra-provider-reconciliation.ts b/src/lib/onboard/extra-provider-reconciliation.ts index d6e9f26f7fd..5abfe1c5e05 100644 --- a/src/lib/onboard/extra-provider-reconciliation.ts +++ b/src/lib/onboard/extra-provider-reconciliation.ts @@ -1,8 +1,9 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { assertNoOpenShellGatewayEndpointOverride } from "../openshell-gateway-endpoint-guard"; -import { reportsExactProviderNotFound } from "../adapters/openshell/provider-diagnostic-cli"; +import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; +import { createCliOpenShellProviderAdapter } from "../adapters/openshell/provider-adapter-cli"; +import { namedOpenShellGateway } from "../adapters/openshell/sandbox-observer"; type ExtraProviderRunOpenshell = ( args: string[], @@ -11,12 +12,13 @@ type ExtraProviderRunOpenshell = ( status: number | null; error?: Error; output?: unknown; - stdout?: unknown; - stderr?: unknown; + stdout?: string | Buffer | null; + stderr?: string | Buffer | null; }; export type ReconcileExtraProvidersDeps = { runOpenshell?: ExtraProviderRunOpenshell; + providerAdapter?: OpenShellProviderAdapter; listExtraProviders?: () => string[]; removeExtraProvider?: (name: string) => boolean; nowMs?: () => number; @@ -31,11 +33,8 @@ export type ExtraProviderReconciliationPlan = { type IndeterminateProbeReason = | "aggregate-time-budget" | "ambiguous-diagnostic" - | "diagnostic-capture-limit" | "probe-process-error" - | "probe-threw" - | "timeout-or-signal" - | "unexpected-exit"; + | "timeout-or-signal"; function defaultRunOpenshell( args: string[], @@ -67,15 +66,7 @@ function defaultRemoveExtraProvider(name: string): boolean { return removeExtraProvider(name); } -function outputText(value: unknown): string { - if (typeof value === "string") return value; - if (Buffer.isBuffer(value)) return value.toString(); - if (Array.isArray(value)) return value.map(outputText).filter(Boolean).join("\n"); - return value === null || value === undefined ? "" : String(value); -} - const PROVIDER_PROBE_TIMEOUT_MS = 5_000; -const PROVIDER_PROBE_DIAGNOSTIC_LIMIT = 64 * 1024; const PROVIDER_RECONCILIATION_BUDGET_MS = 15_000; function monotonicNowMs(): number { @@ -90,53 +81,35 @@ type ProviderProbeOutcome = { type ProviderProbeContext = { gatewayName: string; name: string; - runOpenshell: ExtraProviderRunOpenshell; + providerAdapter: OpenShellProviderAdapter; nowMs: () => number; deadlineMs: number; }; -function diagnosticPartsFromProbeResult(result: ReturnType): string[] { - const primaryDiagnosticParts = [result.stderr, result.stdout].map(outputText).filter(Boolean); - return primaryDiagnosticParts.length > 0 - ? primaryDiagnosticParts - : [outputText(result.output)].filter(Boolean); -} - -function probeExtraProvider(context: ProviderProbeContext): ProviderProbeOutcome { +async function probeExtraProvider(context: ProviderProbeContext): Promise { const remainingMs = context.deadlineMs - context.nowMs(); if (remainingMs <= 0) return { keep: true, reason: "aggregate-time-budget" }; - let result: ReturnType; - try { - result = context.runOpenshell(["provider", "get", "-g", context.gatewayName, context.name], { - ignoreError: true, - maxBuffer: PROVIDER_PROBE_DIAGNOSTIC_LIMIT, - stdio: ["ignore", "pipe", "pipe"], - suppressOutput: true, - timeout: Math.max(1, Math.min(PROVIDER_PROBE_TIMEOUT_MS, Math.floor(remainingMs))), - }); - } catch { - return { keep: true, reason: "probe-threw" }; + const result = await context.providerAdapter.getProvider({ + target: namedOpenShellGateway(context.gatewayName), + providerName: context.name, + timeoutMs: Math.max(1, Math.min(PROVIDER_PROBE_TIMEOUT_MS, Math.floor(remainingMs))), + }); + if (result.ok) return { keep: true }; + if ( + result.error.kind === "validation" || + (result.error.kind === "transport" && result.error.reason === "identity_mismatch") + ) { + throw new Error(result.error.message); + } + if (result.error.kind === "command" && result.error.reason === "not_found") { + return { keep: false }; } - if (result.error) return { keep: true, reason: "probe-process-error" }; - if (result.status === 0) return { keep: true }; - // OpenShell CLI command errors use exit 1. A null status means timeout or - // signal termination, while any other exit is outside this diagnostic - // contract; both are indeterminate and must preserve the provider. - if (result.status === null) return { keep: true, reason: "timeout-or-signal" }; - if (result.status !== 1) return { keep: true, reason: "unexpected-exit" }; - - const diagnosticParts = diagnosticPartsFromProbeResult(result); - if (diagnosticParts.some((part) => Buffer.byteLength(part) >= PROVIDER_PROBE_DIAGNOSTIC_LIMIT)) { - return { keep: true, reason: "diagnostic-capture-limit" }; + if (result.error.kind === "timeout") return { keep: true, reason: "timeout-or-signal" }; + if (result.error.kind === "transport" && result.error.reason === "process_start") { + return { keep: true, reason: "probe-process-error" }; } - return reportsExactProviderNotFound( - diagnosticParts.join("\n"), - context.name, - PROVIDER_PROBE_DIAGNOSTIC_LIMIT, - ) - ? { keep: false } - : { keep: true, reason: "ambiguous-diagnostic" }; + return { keep: true, reason: "ambiguous-diagnostic" }; } /** @@ -157,18 +130,18 @@ function probeExtraProvider(context: ProviderProbeContext): ProviderProbeOutcome * Removal condition: delete this defensive prune once OpenShell/NemoClaw gateway * reset owns extra-provider lifecycle cleanup before sandbox creation (#6501). */ -export function planRegisteredExtraProviders( +export async function planRegisteredExtraProviders( gatewayName: string, deps: ReconcileExtraProvidersDeps = {}, -): ExtraProviderReconciliationPlan { +): Promise { const recorded = (deps.listExtraProviders ?? defaultListExtraProviders)(); if (recorded.length === 0) { return { extraProviders: [], staleExtraProviders: [] }; } if (!gatewayName) throw new Error("OpenShell gateway name is required."); - assertNoOpenShellGatewayEndpointOverride(); - const runOpenshell = deps.runOpenshell ?? defaultRunOpenshell; + const providerAdapter = + deps.providerAdapter ?? createCliOpenShellProviderAdapter({ run: runOpenshell }); const nowMs = deps.nowMs ?? monotonicNowMs; const warn = deps.warn ?? ((message: string) => console.warn(message)); const deadlineMs = nowMs() + PROVIDER_RECONCILIATION_BUDGET_MS; @@ -183,10 +156,10 @@ export function planRegisteredExtraProviders( const reconciled: string[] = []; const staleExtraProviders: string[] = []; for (const name of recorded) { - const outcome = probeExtraProvider({ + const outcome = await probeExtraProvider({ gatewayName, name, - runOpenshell, + providerAdapter, nowMs, deadlineMs, }); @@ -217,12 +190,12 @@ export function applyExtraProviderReconciliation( for (const name of plan.staleExtraProviders) removeExtraProvider(name); } -export function reconcileRegisteredExtraProviders( +export async function reconcileRegisteredExtraProviders( gatewayName: string, deps: ReconcileExtraProvidersDeps = {}, -): string[] { +): Promise { // Compatibility wrapper for focused #6501 tests; remove with that defensive prune. - const plan = planRegisteredExtraProviders(gatewayName, deps); + const plan = await planRegisteredExtraProviders(gatewayName, deps); applyExtraProviderReconciliation(plan, deps); return [...plan.extraProviders]; } diff --git a/src/lib/onboard/hermes-auth.ts b/src/lib/onboard/hermes-auth.ts index c804c73b731..953c7b8b0f4 100644 --- a/src/lib/onboard/hermes-auth.ts +++ b/src/lib/onboard/hermes-auth.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { normalizeCredentialValue } from "../credentials/store"; +import { createCliOpenShellProviderAdapter } from "../adapters/openshell/provider-adapter-cli"; import type { HermesAuthMethod } from "../hermes-provider-auth"; import * as hermesProviderAuth from "../hermes-provider-auth"; @@ -93,7 +94,7 @@ export interface HermesAuthHelpers { }): string; checkHermesProviderStoreReachable( runOpenshellImpl?: HermesAuthFlowDeps["runOpenshell"], - ): { ok: true } | { ok: false; message: string }; + ): Promise<{ ok: true } | { ok: false; message: string }>; } export function createHermesAuthHelpers(deps: HermesAuthFlowDeps): HermesAuthHelpers { @@ -182,20 +183,27 @@ export function createHermesAuthHelpers(deps: HermesAuthFlowDeps): HermesAuthHel return deps.compactText(deps.redact(`${result.stderr || ""} ${result.stdout || ""}`)); } - function checkHermesProviderStoreReachable( + async function checkHermesProviderStoreReachable( runOpenshellImpl: HermesAuthFlowDeps["runOpenshell"] = deps.runOpenshell, - ): { ok: true } | { ok: false; message: string } { - const result = runOpenshellImpl(["provider", "list"], { - ignoreError: true, - stdio: ["ignore", "pipe", "pipe"], - timeout: 10_000, + ): Promise<{ ok: true } | { ok: false; message: string }> { + const adapter = createCliOpenShellProviderAdapter({ + run: (args, options) => { + const result = runOpenshellImpl(args, options); + return { + status: result.status ?? null, + stdout: result.stdout, + stderr: result.stderr, + }; + }, + }); + const result = await adapter.listProviders({ + target: { kind: "selected" }, + timeoutMs: 10_000, }); - if (result.status === 0) return { ok: true }; + if (result.ok) return { ok: true }; return { ok: false, - message: - openshellResultMessage(result) || - "OpenShell provider storage is unreachable; the gateway may be stopped or refusing connections.", + message: result.error.message, }; } diff --git a/src/lib/onboard/inference-providers/compatible-endpoint-gateway-route.test.ts b/src/lib/onboard/inference-providers/compatible-endpoint-gateway-route.test.ts index cff07e4ace6..d8d2dc06454 100644 --- a/src/lib/onboard/inference-providers/compatible-endpoint-gateway-route.test.ts +++ b/src/lib/onboard/inference-providers/compatible-endpoint-gateway-route.test.ts @@ -31,13 +31,13 @@ describe("compatible endpoint gateway routing", () => { }, ); - it("leaves a generic compatible-endpoint loopback URL unchanged on port 8081 (#8161)", () => { + it("leaves a generic compatible-endpoint loopback URL unchanged on port 8081 (#8161)", async () => { expect( gatewayReachableCompatibleEndpointUrl("compatible-endpoint", "http://127.0.0.1:8081/v1"), ).toBe("http://127.0.0.1:8081/v1"); }); - it("rewrites only fixed loopback port 8081 for llama.cpp attachment (#8161)", () => { + it("rewrites only fixed loopback port 8081 for llama.cpp attachment (#8161)", async () => { expect( gatewayReachableCompatibleEndpointUrl("llama-cpp-local", "http://127.0.0.1:8081/v1"), ).toBe("http://host.openshell.internal:8081/v1"); @@ -46,7 +46,7 @@ describe("compatible endpoint gateway routing", () => { ).toBe("http://127.0.0.1:8000/v1"); }); - it("preserves query strings and fragments for root and non-root routes (#5744)", () => { + it("preserves query strings and fragments for root and non-root routes (#5744)", async () => { expect( gatewayReachableCompatibleEndpointUrl( "compatible-endpoint", @@ -61,7 +61,7 @@ describe("compatible endpoint gateway routing", () => { ).toBe("http://host.openshell.internal:8000/v1?tenant=local#models"); }); - it("leaves default, privileged, unsupported, and adjacent URL shapes unchanged (#5744)", () => { + it("leaves default, privileged, unsupported, and adjacent URL shapes unchanged (#5744)", async () => { const unchanged = [ "http://localhost/v1", "http://localhost:80/v1", @@ -115,7 +115,18 @@ describe("recovered provider reuse and the openai provider profile (#9895)", () commands.push(args.join(" ")); return args[1] === "profile" ? (profileResults.shift() ?? { status: 1, stderr: "unexpected profile call" }) - : { status: 0, stdout: "", stderr: "" }; + : { + status: 0, + stdout: [ + "Id: provider-compatible-endpoint", + "Name: compatible-endpoint", + "Type: openai", + "Resource version: 1", + "Credential keys: COMPATIBLE_API_KEY", + "Config keys: OPENAI_BASE_URL", + ].join("\n"), + stderr: "", + }; }); return { commands, runOpenshell }; } @@ -128,14 +139,18 @@ describe("recovered provider reuse and the openai provider profile (#9895)", () gatewayEndpointUrl: REGISTERED_URL, }; - it("declares the openai profile for an unchanged gateway route that performs no upsert", () => { + it("declares the openai profile for an unchanged gateway route that performs no upsert", async () => { const { commands, runOpenshell } = createRunOpenshell([ { status: 0, stdout: OPENAI_ENDPOINTLESS_PROFILE }, ]); const upsertProvider = vi.fn(() => ({ ok: true })); expect( - reuseRegisteredProviderWithGatewayEndpoint({ ...reuseArgs, runOpenshell, upsertProvider }), + await reuseRegisteredProviderWithGatewayEndpoint({ + ...reuseArgs, + runOpenshell, + upsertProvider, + }), ).toEqual({ ok: true }); expect(upsertProvider).not.toHaveBeenCalled(); @@ -145,14 +160,14 @@ describe("recovered provider reuse and the openai provider profile (#9895)", () ]); }); - it("reports a failed profile import instead of reusing the recovered provider", () => { + it("reports a failed profile import instead of reusing the recovered provider", async () => { const { runOpenshell } = createRunOpenshell([ { status: 1, stderr: "provider profile not found" }, { status: 1, stderr: "import refused" }, ]); const upsertProvider = vi.fn(() => ({ ok: true })); - const result = reuseRegisteredProviderWithGatewayEndpoint({ + const result = await reuseRegisteredProviderWithGatewayEndpoint({ ...reuseArgs, runOpenshell, upsertProvider, @@ -167,12 +182,12 @@ describe("recovered provider reuse and the openai provider profile (#9895)", () expect(upsertProvider).not.toHaveBeenCalled(); }); - it("leaves a non-openai recovered provider untouched", () => { + it("leaves a non-openai recovered provider untouched", async () => { const { commands, runOpenshell } = createRunOpenshell([]); const upsertProvider = vi.fn(() => ({ ok: true })); expect( - reuseRegisteredProviderWithGatewayEndpoint({ + await reuseRegisteredProviderWithGatewayEndpoint({ ...reuseArgs, providerType: "anthropic", runOpenshell, diff --git a/src/lib/onboard/inference-providers/compatible-endpoint-gateway-route.ts b/src/lib/onboard/inference-providers/compatible-endpoint-gateway-route.ts index 02bccfcb226..8fd2e9528ca 100644 --- a/src/lib/onboard/inference-providers/compatible-endpoint-gateway-route.ts +++ b/src/lib/onboard/inference-providers/compatible-endpoint-gateway-route.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { VLLM_PORT } from "../../core/vllm-port"; +import { createCliOpenShellProviderAdapter } from "../../adapters/openshell/provider-adapter-cli"; import { checkOpenAiInferenceProviderProfile, OPENAI_GATEWAY_PROVIDER_TYPE, @@ -71,7 +72,7 @@ export function gatewayReachableCompatibleEndpointUrl( : `${parsed.origin}${parsed.pathname}${routeSuffix}`; } -export function reuseRegisteredProviderWithGatewayEndpoint(args: { +export async function reuseRegisteredProviderWithGatewayEndpoint(args: { provider: string; providerType: string; credentialEnv: string | null | undefined; @@ -79,7 +80,7 @@ export function reuseRegisteredProviderWithGatewayEndpoint(args: { gatewayEndpointUrl: string | null | undefined; runOpenshell: RunOpenshell; upsertProvider: UpsertProvider; -}): UpsertProviderResult { +}): Promise { const { provider, providerType, @@ -91,15 +92,34 @@ export function reuseRegisteredProviderWithGatewayEndpoint(args: { } = args; // The caller has already authorized the recovered provider's non-secret // credential/config identity through assessRecoveredProviderCredentialReuse. - const existing = runOpenshell(["provider", "get", provider], { - ignoreError: true, - suppressOutput: true, + const adapter = createCliOpenShellProviderAdapter({ + run: (command, options) => { + const result = runOpenshell(command, options); + return { + status: result.status, + stdout: + typeof result.stdout === "string" || Buffer.isBuffer(result.stdout) + ? result.stdout + : null, + stderr: + typeof result.stderr === "string" || Buffer.isBuffer(result.stderr) + ? result.stderr + : null, + }; + }, }); - if (existing.status !== 0) { + const existing = await adapter.getProvider({ + target: { kind: "selected" }, + providerName: provider, + }); + if (!existing.ok) { return { ok: false, - status: existing.status || 1, - message: `Recovered provider '${provider}' is no longer registered in OpenShell.`, + status: 1, + message: + existing.error.kind === "command" && existing.error.reason === "not_found" + ? `Recovered provider '${provider}' is no longer registered in OpenShell.` + : existing.error.message, }; } if (gatewayEndpointUrl === endpointUrl) { diff --git a/src/lib/onboard/inference-providers/hermes.test.ts b/src/lib/onboard/inference-providers/hermes.test.ts index 32bcbd311ef..214918ed1c2 100644 --- a/src/lib/onboard/inference-providers/hermes.test.ts +++ b/src/lib/onboard/inference-providers/hermes.test.ts @@ -76,6 +76,7 @@ describe("setupHermesProviderInference smoke verification", () => { }); const setup = setupHermesProviderInference(makeArgs(null), deps as never); + await Promise.resolve(); expect(deps.verifyOnboardInferenceSmoke).toHaveBeenCalledOnce(); expect(deps.registry.updateSandbox).not.toHaveBeenCalled(); diff --git a/src/lib/onboard/inference-providers/hermes.ts b/src/lib/onboard/inference-providers/hermes.ts index c4edd8fad07..1e4bce5f2c6 100644 --- a/src/lib/onboard/inference-providers/hermes.ts +++ b/src/lib/onboard/inference-providers/hermes.ts @@ -103,7 +103,7 @@ export async function setupHermesProviderInference( (credentialEnv === HERMES_NOUS_API_KEY_CREDENTIAL_ENV ? HERMES_AUTH_METHOD_API_KEY : HERMES_AUTH_METHOD_OAUTH); - const providerStore = checkHermesProviderStoreReachable(runOpenshell); + const providerStore = await checkHermesProviderStoreReachable(runOpenshell); if (!providerStore.ok) { error(" ✗ OpenShell provider storage is unreachable."); error(` ${providerStore.message}`); @@ -115,7 +115,7 @@ export async function setupHermesProviderInference( const toolGatewayProviderRegistered = hermesToolGateways.length === 0 ? true - : providerExistsInGateway( + : await providerExistsInGateway( getHermesToolGatewayBroker().getHermesToolGatewayProviderName(targetSandbox), ); const hasFreshNousApiKey = diff --git a/src/lib/onboard/inference-providers/ollama-local.ts b/src/lib/onboard/inference-providers/ollama-local.ts index 2a476332194..805d2ccf4db 100644 --- a/src/lib/onboard/inference-providers/ollama-local.ts +++ b/src/lib/onboard/inference-providers/ollama-local.ts @@ -122,9 +122,9 @@ export async function setupOllamaLocalInference( // so the gateway never reads the user's host OPENAI_API_KEY for local // Ollama. GH #2519: a stale host OPENAI_API_KEY was leaking into the // inference path and producing 401s. - let providerResult: ReturnType; + let providerResult: Awaited>; try { - providerResult = upsertProvider( + providerResult = await upsertProvider( "ollama-local", "openai", OLLAMA_PROXY_CREDENTIAL_ENV, diff --git a/src/lib/onboard/inference-providers/remote.ts b/src/lib/onboard/inference-providers/remote.ts index a5c539daadf..87065367dac 100644 --- a/src/lib/onboard/inference-providers/remote.ts +++ b/src/lib/onboard/inference-providers/remote.ts @@ -271,7 +271,7 @@ export async function setupRemoteProviderInference( proxy?.baseUrl ?? gatewayReachableCompatibleEndpointUrl(provider, resolvedEndpointUrl); let providerResult; if (reuseGatewayCredentialWithoutLocalKey) { - providerResult = reuseRegisteredProviderWithGatewayEndpoint({ + providerResult = await reuseRegisteredProviderWithGatewayEndpoint({ provider, providerType: config.providerType, credentialEnv: resolvedCredentialEnv, @@ -336,7 +336,7 @@ export async function setupRemoteProviderInference( compactText, }); providerResult = replaced.ok - ? upsertProvider( + ? await upsertProvider( provider, "openai", resolvedCredentialEnv, @@ -350,7 +350,7 @@ export async function setupRemoteProviderInference( }; } } else { - providerResult = upsertProvider( + providerResult = await upsertProvider( provider, config.providerType, resolvedCredentialEnv, diff --git a/src/lib/onboard/inference-providers/routed.ts b/src/lib/onboard/inference-providers/routed.ts index dd863c41f1b..637fda541aa 100644 --- a/src/lib/onboard/inference-providers/routed.ts +++ b/src/lib/onboard/inference-providers/routed.ts @@ -36,7 +36,7 @@ export async function setupRoutedInference( error(` ✗ Failed to start model router: ${err instanceof Error ? err.message : String(err)}`); return exitProcess(1); } - const routed = routedInference.upsertRoutedProvider(provider, endpointUrl, credentialEnv, { + const routed = await routedInference.upsertRoutedProvider(provider, endpointUrl, credentialEnv, { upsertProvider, hydrateCredentialEnv, }); diff --git a/src/lib/onboard/inference-providers/types.ts b/src/lib/onboard/inference-providers/types.ts index 40d56416959..93cc48f3e6a 100644 --- a/src/lib/onboard/inference-providers/types.ts +++ b/src/lib/onboard/inference-providers/types.ts @@ -45,7 +45,7 @@ export type UpsertProvider = ( credentialEnv: any, baseUrl: any, env?: NodeJS.ProcessEnv, -) => UpsertProviderResult; +) => UpsertProviderResult | Promise; export type RemoteProviderConfigEntry = { label: string; @@ -194,10 +194,12 @@ export type HermesDeps = CommonDeps & { getHermesToolGatewayBroker: () => { getHermesToolGatewayProviderName(sandboxName: string): string; }; - providerExistsInGateway: (name: string) => boolean; + providerExistsInGateway: (name: string) => boolean | Promise; normalizeHermesAuthMethod: (m: HermesAuthMethod | string | null) => HermesAuthMethod | null; resolveHermesNousApiKey: () => any; - checkHermesProviderStoreReachable: (runOpenshell: any) => { ok: boolean; message?: string }; + checkHermesProviderStoreReachable: ( + runOpenshell: any, + ) => { ok: boolean; message?: string } | Promise<{ ok: boolean; message?: string }>; hermesAuthMethodLabel: (m: HermesAuthMethod) => string; hermesConstants: { HERMES_NOUS_API_KEY_CREDENTIAL_ENV: string; @@ -284,7 +286,9 @@ export type RoutedDeps = CommonDeps & { upsertProvider: UpsertProvider; hydrateCredentialEnv: (envName: any, resolveCredential?: any) => any; }, - ): { ok: boolean; result: { message?: string; status?: number } }; + ): + | { ok: boolean; result: { message?: string; status?: number } } + | Promise<{ ok: boolean; result: { message?: string; status?: number } }>; }; hydrateCredentialEnv: (envName: any, resolveCredential?: any) => any; redact: (input: string) => string; diff --git a/src/lib/onboard/inference-providers/vllm-local.ts b/src/lib/onboard/inference-providers/vllm-local.ts index cb1c7d1fccd..dc0a89fee16 100644 --- a/src/lib/onboard/inference-providers/vllm-local.ts +++ b/src/lib/onboard/inference-providers/vllm-local.ts @@ -64,7 +64,7 @@ export async function setupVllmLocalInference( // the bearer for legacy single-host installs; managed dual-Station vLLM // uses the private persisted key. The dedicated env name prevents // accidental hijacking by a host OPENAI_API_KEY. See GH #2519. - const providerResult = upsertProvider( + const providerResult = await upsertProvider( "vllm-local", "openai", VLLM_LOCAL_CREDENTIAL_ENV, diff --git a/src/lib/onboard/machine/handlers/policies.ts b/src/lib/onboard/machine/handlers/policies.ts index 5939937cea5..a0d5d1d6182 100644 --- a/src/lib/onboard/machine/handlers/policies.ts +++ b/src/lib/onboard/machine/handlers/policies.ts @@ -68,7 +68,7 @@ export interface PoliciesStateOptions { forceCanonicalRoute?: boolean; hostLocalInferenceProofAuthority?: HostLocalInferenceSandboxProofAuthority; beforeSuccess?: () => void; - }): void; + }): void | Promise; preparePolicyPresetResumeSelection( sandboxName: string, options: { @@ -169,7 +169,7 @@ export async function handlePoliciesState({ activeMessagingChannels, disabledChannels, ); - const verifySandboxInferenceRoute = () => + const verifySandboxInferenceRoute = async () => deps.verifyCompatibleEndpointSandboxSmoke({ sandboxName, provider, @@ -184,7 +184,7 @@ export async function handlePoliciesState({ : {}), }); if (preserveRebuildLivePolicy) { - verifySandboxInferenceRoute(); + await verifySandboxInferenceRoute(); deps.skippedStepMessage("policies", "live OpenShell rebuild policy"); await deps.recordStateSkipped("policies", { reason: "rebuild-live-policy", @@ -207,7 +207,7 @@ export async function handlePoliciesState({ }), }; } - if (!hostLocalInferenceRouteOnly) verifySandboxInferenceRoute(); + if (!hostLocalInferenceRouteOnly) await verifySandboxInferenceRoute(); const policyResumeSelection = deps.preparePolicyPresetResumeSelection(sandboxName, { disabledChannels, @@ -234,7 +234,7 @@ export async function handlePoliciesState({ let appliedPolicyPresets = livePolicyPresetsForSupport; let session: Session | null; if (resumePolicies) { - if (hostLocalInferenceRouteOnly) verifySandboxInferenceRoute(); + if (hostLocalInferenceRouteOnly) await verifySandboxInferenceRoute(); deps.skippedStepMessage("policies", livePolicyPresetsForSupport.join(", ")); await deps.recordStateSkipped("policies", { reason: "resume", @@ -271,7 +271,7 @@ export async function handlePoliciesState({ hermesToolGateways, onSelection: () => undefined, }); - if (hostLocalInferenceRouteOnly) verifySandboxInferenceRoute(); + if (hostLocalInferenceRouteOnly) await verifySandboxInferenceRoute(); session = await deps.recordStepComplete( "policies", deps.toSessionUpdates({ diff --git a/src/lib/onboard/machine/handlers/provider-inference.ts b/src/lib/onboard/machine/handlers/provider-inference.ts index 7b3926b01ef..45716f5b014 100644 --- a/src/lib/onboard/machine/handlers/provider-inference.ts +++ b/src/lib/onboard/machine/handlers/provider-inference.ts @@ -183,10 +183,7 @@ export interface ProviderInferenceStateOptions { ) => GatewayRouteDiscoveryConstraints, canProbeRoute?: (provider: string) => boolean, recoverySessionId?: string | null, - revalidateSandboxIdentity?: ( - route: ProviderInferenceProbeRoute, - operation: string, - ) => void, + revalidateSandboxIdentity?: (route: ProviderInferenceProbeRoute, operation: string) => void, ): Promise; setupInference( sandboxName: string | null, @@ -261,7 +258,9 @@ export interface ProviderInferenceStateOptions { provider: string, endpointUrl: string | null, credentialEnv: string | null, - ): { ok: boolean; endpointUrl: string; message?: string; status?: number }; + ): + | { ok: boolean; endpointUrl: string; message?: string; status?: number } + | Promise<{ ok: boolean; endpointUrl: string; message?: string; status?: number }>; reserveSandboxInferenceRoute( sandboxName: string, route: { @@ -1339,11 +1338,7 @@ export async function handleProviderInferenceState({ sandboxName, deps.ensureManagedLlamaCppResumeReady, ); - const recovery = await deps.ensureResumeProviderReady( - gatewayName, - provider, - credentialEnv, - ); + const recovery = await deps.ensureResumeProviderReady(gatewayName, provider, credentialEnv); forceInferenceSetup ||= recovery.forceInferenceSetup; credentialEnv = recovery.credentialEnv; // Rebuild may be resuming a legacy session whose step marker was never @@ -1743,7 +1738,7 @@ export async function handleProviderInferenceState({ ); deps.exitProcess(1); } - const reupserted = deps.reupsertRoutedProvider( + const reupserted = await deps.reupsertRoutedProvider( gatewayName, selectedProvider, endpointUrl, diff --git a/src/lib/onboard/machine/handlers/sandbox-messaging.test.ts b/src/lib/onboard/machine/handlers/sandbox-messaging.test.ts index 54e5efb34aa..f07e1d53909 100644 --- a/src/lib/onboard/machine/handlers/sandbox-messaging.test.ts +++ b/src/lib/onboard/machine/handlers/sandbox-messaging.test.ts @@ -1,8 +1,6 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 - import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; - import type { AgentDefinition } from "../../../agent/defs"; import { MessagingSetupApplier } from "../../../messaging/applier/setup-applier"; import { MESSAGING_SETUP_APPLIER_ENV_KEY } from "../../../messaging/applier/types"; @@ -28,13 +26,10 @@ import { reconcileReusedSandboxMessaging, reconcileSandboxMessaging, } from "./sandbox-messaging"; - const mixedChannelIds: MessagingChannelId[] = ["telegram", "unsupported"]; - function channelIdsFrom(entries: readonly T[]): string[] { return entries.map(({ channelId }) => channelId); } - const credentialSpecs = { telegram: ["telegram", "botToken", "botToken", "alpha-telegram-bridge", "TELEGRAM_BOT_TOKEN"], discord: ["discord", "discordBotToken", "botToken", "alpha-discord-bridge", "DISCORD_BOT_TOKEN"], @@ -267,7 +262,7 @@ describe("hasMessagingCredentialDrift", () => { const oldToken = "123456:old-telegram-token"; const plan = telegramPlan(hashCredential(oldToken) ?? ""); - it("detects only an explicitly supplied replacement credential", () => { + it("detects only an explicitly supplied replacement credential", async () => { expect(hasMessagingCredentialDrift(plan, {})).toBe(false); expect(hasMessagingCredentialDrift(plan, { TELEGRAM_BOT_TOKEN: oldToken })).toBe(false); expect( @@ -277,7 +272,7 @@ describe("hasMessagingCredentialDrift", () => { ).toBe(true); }); - it("ignores replacement credentials for disabled channels", () => { + it("ignores replacement credentials for disabled channels", async () => { const disabledPlan = mixedChannelPlan(); expect( hasMessagingCredentialDrift(disabledPlan, { @@ -297,12 +292,12 @@ afterEach(() => { }); describe("reconcileReusedSandboxMessaging", () => { - it("does not clear an equal recorded plan from a different authority", () => { + it("does not clear an equal recorded plan from a different authority", async () => { const plan = telegramPlan(hashCredential("123456:registry-token") ?? ""); const clearPlanEnv = vi.fn(); vi.stubEnv("TELEGRAM_BOT_TOKEN", "123456:registry-token"); - const result = reconcileReusedSandboxMessaging( + const result = await reconcileReusedSandboxMessaging( structuredClone(plan), { name: "openclaw" }, { @@ -318,7 +313,7 @@ describe("reconcileReusedSandboxMessaging", () => { expect(clearPlanEnv).not.toHaveBeenCalled(); }); - it("rejects a retired channel without changing a Ready sandbox plan (#9283)", () => { + it("rejects a retired channel without changing a Ready sandbox plan (#9283)", async () => { const plan = discordPlan(hashCredential("previous-discord-token") ?? ""); const deps = { clearPlanEnv: vi.fn(), @@ -328,20 +323,20 @@ describe("reconcileReusedSandboxMessaging", () => { }; vi.stubEnv("DISCORD_BOT_TOKEN", ""); - expect(() => + await expect( reconcileReusedSandboxMessaging(structuredClone(plan), { name: "openclaw" }, deps, plan), - ).toThrow( + ).rejects.toThrow( /Ready sandbox 'alpha'.*running sandbox and durable messaging plan were not changed/u, ); expect(deps.writePlanToEnv).not.toHaveBeenCalled(); expect(deps.clearPlanEnv).not.toHaveBeenCalled(); }); - it("keeps a still-configured channel in a reused sandbox selection (#9283)", () => { + it("keeps a still-configured channel in a reused sandbox selection (#9283)", async () => { const plan = discordPlan(hashCredential("previous-discord-token") ?? ""); vi.stubEnv("DISCORD_BOT_TOKEN", "123456:live-discord-token"); - const result = reconcileReusedSandboxMessaging( + const result = await reconcileReusedSandboxMessaging( structuredClone(plan), { name: "openclaw" }, { @@ -356,13 +351,13 @@ describe("reconcileReusedSandboxMessaging", () => { expect(result.selectedChannels).toEqual(["discord"]); }); - it("keeps a bridge channel whose gateway credential outlived the onboarding process (#10660)", () => { + it("keeps a bridge channel whose gateway credential outlived the onboarding process (#10660)", async () => { const plan = googlechatPlan(); vi.stubEnv("GOOGLECHAT_SERVICE_ACCOUNT", ""); const inspectGatewayCredential = vi.fn(() => ({ kind: "exact" as const })); const note = vi.fn(); - const result = reconcileReusedSandboxMessaging( + const result = await reconcileReusedSandboxMessaging( structuredClone(plan), { name: "openclaw" }, { clearPlanEnv: vi.fn(), inspectGatewayCredential, note, writePlanToEnv: vi.fn() }, @@ -378,13 +373,13 @@ describe("reconcileReusedSandboxMessaging", () => { ); }); - it("rejects Ready sandbox reuse when a bridge credential is missing (#10660)", () => { + it("rejects Ready sandbox reuse when a bridge credential is missing (#10660)", async () => { const plan = googlechatPlan(); vi.stubEnv("GOOGLECHAT_SERVICE_ACCOUNT", ""); const note = vi.fn(); const writePlanToEnv = vi.fn(); - expect(() => + await expect( reconcileReusedSandboxMessaging( structuredClone(plan), { name: "openclaw" }, @@ -396,19 +391,19 @@ describe("reconcileReusedSandboxMessaging", () => { }, plan, ), - ).toThrow( + ).rejects.toThrow( /Ready sandbox 'alpha'.*running sandbox and durable messaging plan were not changed/u, ); expect(writePlanToEnv).not.toHaveBeenCalled(); expect(note).not.toHaveBeenCalledWith(expect.stringContaining("disabling the channel")); }); - it("keeps a token channel whose provider still matches at the gateway (#10660)", () => { + it("keeps a token channel whose provider still matches at the gateway (#10660)", async () => { const plan = discordPlan(hashCredential("previous-discord-token") ?? ""); vi.stubEnv("DISCORD_BOT_TOKEN", ""); const inspectGatewayCredential = vi.fn(() => ({ kind: "exact" as const })); - const result = reconcileReusedSandboxMessaging( + const result = await reconcileReusedSandboxMessaging( structuredClone(plan), { name: "openclaw" }, { @@ -431,41 +426,45 @@ describe("reconcileReusedSandboxMessaging", () => { it.each([ ["app-token", "SLACK_APP_TOKEN"], ["bot-token", "SLACK_BOT_TOKEN"], - ] as const)("rejects Ready sandbox reuse when its Slack %s is missing (#10660)", (_, missing) => { - const plan = slackPlan( - hashCredential("previous-slack-bot-token") ?? "", - hashCredential("previous-slack-app-token") ?? "", - ); - vi.stubEnv("SLACK_BOT_TOKEN", ""); - vi.stubEnv("SLACK_APP_TOKEN", ""); - const writePlanToEnv = vi.fn(); - const inspectGatewayCredential = vi.fn((_name: string, _type: string, credentialEnv: string) => - credentialEnv === missing ? ({ kind: "missing" } as const) : ({ kind: "exact" } as const), - ); + ] as const)( + "rejects Ready sandbox reuse when its Slack %s is missing (#10660)", + async (_, missing) => { + const plan = slackPlan( + hashCredential("previous-slack-bot-token") ?? "", + hashCredential("previous-slack-app-token") ?? "", + ); + vi.stubEnv("SLACK_BOT_TOKEN", ""); + vi.stubEnv("SLACK_APP_TOKEN", ""); + const writePlanToEnv = vi.fn(); + const inspectGatewayCredential = vi.fn( + (_name: string, _type: string, credentialEnv: string) => + credentialEnv === missing ? ({ kind: "missing" } as const) : ({ kind: "exact" } as const), + ); - expect(() => - reconcileReusedSandboxMessaging( - structuredClone(plan), - { name: "openclaw" }, - { clearPlanEnv: vi.fn(), inspectGatewayCredential, note: vi.fn(), writePlanToEnv }, - plan, - ), - ).toThrow( - /Ready sandbox 'alpha'.*running sandbox and durable messaging plan were not changed/u, - ); - expect(writePlanToEnv).not.toHaveBeenCalled(); - expect(inspectGatewayCredential).toHaveBeenCalledTimes(2); - }); + await expect( + reconcileReusedSandboxMessaging( + structuredClone(plan), + { name: "openclaw" }, + { clearPlanEnv: vi.fn(), inspectGatewayCredential, note: vi.fn(), writePlanToEnv }, + plan, + ), + ).rejects.toThrow( + /Ready sandbox 'alpha'.*running sandbox and durable messaging plan were not changed/u, + ); + expect(writePlanToEnv).not.toHaveBeenCalled(); + expect(inspectGatewayCredential).toHaveBeenCalledTimes(2); + }, + ); it.each(["collision", "indeterminate"] as const)( "preserves the channel plan when gateway credential inspection is %s (#10660)", - (kind) => { + async (kind) => { const plan = googlechatPlan(); vi.stubEnv("GOOGLECHAT_SERVICE_ACCOUNT", ""); const clearPlanEnv = vi.fn(); const writePlanToEnv = vi.fn(); - expect(() => + await expect( reconcileReusedSandboxMessaging( structuredClone(plan), { name: "openclaw" }, @@ -477,7 +476,7 @@ describe("reconcileReusedSandboxMessaging", () => { }, plan, ), - ).toThrow( + ).rejects.toThrow( /provider 'alpha-googlechat-bridge'.*sandbox 'alpha'.*No messaging state was changed/u, ); expect(clearPlanEnv).not.toHaveBeenCalled(); @@ -485,7 +484,7 @@ describe("reconcileReusedSandboxMessaging", () => { }, ); - it("preserves Slack when a missing binding accompanies an indeterminate inspection (#10660)", () => { + it("preserves Slack when a missing binding accompanies an indeterminate inspection (#10660)", async () => { const plan = slackPlan( hashCredential("previous-slack-bot-token") ?? "", hashCredential("previous-slack-app-token") ?? "", @@ -500,25 +499,25 @@ describe("reconcileReusedSandboxMessaging", () => { : ({ kind: "indeterminate" } as const), ); - expect(() => + await expect( reconcileReusedSandboxMessaging( structuredClone(plan), { name: "openclaw" }, { clearPlanEnv, inspectGatewayCredential, note: vi.fn(), writePlanToEnv }, plan, ), - ).toThrow(/Could not inspect messaging provider/u); + ).rejects.toThrow(/Could not inspect messaging provider/u); expect(inspectGatewayCredential).toHaveBeenCalledTimes(2); expect(clearPlanEnv).not.toHaveBeenCalled(); expect(writePlanToEnv).not.toHaveBeenCalled(); }); - it("keeps an in-sandbox QR channel in a reused sandbox selection (#9283)", () => { + it("keeps an in-sandbox QR channel in a reused sandbox selection (#9283)", async () => { const plan = whatsappPlan(); vi.stubEnv("WHATSAPP_MODE", ""); vi.stubEnv("WHATSAPP_ALLOWED_IDS", ""); - const result = reconcileReusedSandboxMessaging( + const result = await reconcileReusedSandboxMessaging( structuredClone(plan), { name: "openclaw" }, { @@ -534,9 +533,9 @@ describe("reconcileReusedSandboxMessaging", () => { expect(result.selectedChannels).toEqual(["whatsapp"]); }); - it("removes every unsupported channel artifact from a reused plan", () => { + it("removes every unsupported channel artifact from a reused plan", async () => { vi.stubEnv("TELEGRAM_BOT_TOKEN", "123456:registry-token"); - const result = reconcileReusedSandboxMessaging( + const result = await reconcileReusedSandboxMessaging( mixedChannelPlan(), { name: "openclaw" }, { diff --git a/src/lib/onboard/machine/handlers/sandbox-messaging.ts b/src/lib/onboard/machine/handlers/sandbox-messaging.ts index 45730f48c1d..80101a49c9d 100644 --- a/src/lib/onboard/machine/handlers/sandbox-messaging.ts +++ b/src/lib/onboard/machine/handlers/sandbox-messaging.ts @@ -55,7 +55,7 @@ export interface SandboxMessagingDeps { resume: boolean, session: Session | null, sandboxName: string | null, - ): string[] | null; + ): string[] | null | Promise; setupMessagingChannels( agent: Agent, existingChannels: string[] | null, @@ -70,8 +70,12 @@ export interface SandboxMessagingDeps { name: string, type: string, credentialEnv: string, - ): GatewayCredentialOnlyProviderInspection; - providerMatchesGatewayCredential(name: string, type: string, credentialEnv: string): boolean; + ): GatewayCredentialOnlyProviderInspection | Promise; + providerMatchesGatewayCredential( + name: string, + type: string, + credentialEnv: string, + ): boolean | Promise; } export interface SandboxMessagingSelection { @@ -261,21 +265,27 @@ function selectionFromReusablePlan( * - Durable record: `channels remove` deletes the provider, a rebuild does not. * - Same match the create intent uses to reuse a provider without its secret. */ -function channelCredentialLivesAtGateway( +async function channelCredentialLivesAtGateway( plan: SandboxMessagingPlan, channelId: string, deps: Pick, "inspectGatewayCredential">, -): boolean { +): Promise { const providerBindings = requiredMessagingProviderBindings( plan.sandboxName, plan, new Set([channelId]), ); if (providerBindings.length === 0) return false; - const inspections = providerBindings.map((binding) => ({ - binding, - inspection: deps.inspectGatewayCredential(binding.name, binding.type, binding.credentialEnv), - })); + const inspections = await Promise.all( + providerBindings.map(async (binding) => ({ + binding, + inspection: await deps.inspectGatewayCredential( + binding.name, + binding.type, + binding.credentialEnv, + ), + })), + ); const unresolved = inspections.find( ({ inspection }) => inspection.kind === "collision" || inspection.kind === "indeterminate", ); @@ -293,13 +303,13 @@ function channelCredentialLivesAtGateway( return inspections.every(({ inspection }) => inspection.kind === "exact"); } -function reconcileGatewayCredentialChannels( +async function reconcileGatewayCredentialChannels( plan: SandboxMessagingPlan, channelIds: readonly string[], missingChannels: Set, deps: Pick, "inspectGatewayCredential">, addMissingChannels: boolean, -): void { +): Promise { for (const channelId of channelIds) { const providerBindings = requiredMessagingProviderBindings( plan.sandboxName, @@ -307,7 +317,7 @@ function reconcileGatewayCredentialChannels( new Set([channelId]), ); if (providerBindings.length === 0) continue; - if (channelCredentialLivesAtGateway(plan, channelId, deps)) { + if (await channelCredentialLivesAtGateway(plan, channelId, deps)) { missingChannels.delete(channelId); } else if (addMissingChannels) { missingChannels.add(channelId); @@ -323,7 +333,7 @@ function persistMessagingPlan( else deps.clearPlanEnv(); } -function filterUnconfiguredHostChannelsFromSelection( +async function filterUnconfiguredHostChannelsFromSelection( selection: SandboxMessagingSelection, agent: Agent, deps: Pick< @@ -332,7 +342,7 @@ function filterUnconfiguredHostChannelsFromSelection( >, persist = true, missingAction: "disable" | "reject-ready-reuse" = "disable", -): SandboxMessagingSelection { +): Promise { // A registry plan records the previous selection, not the current host // input. Rebuild the host-backed selection so policy reconciliation can // disable a removed channel. The detector keeps in-sandbox QR-paired @@ -353,7 +363,7 @@ function filterUnconfiguredHostChannelsFromSelection( const channelsToInspect = inspectAllActiveCredentialChannels ? selection.selectedChannels : [...unconfiguredChannels]; - reconcileGatewayCredentialChannels( + await reconcileGatewayCredentialChannels( planForGatewayCheck, channelsToInspect, unconfiguredChannels, @@ -502,7 +512,7 @@ async function selectionFromMessagingSetup( } /** Probe gateway state before persisting a reusable plan. */ -function selectionFromReconciledReusablePlan( +async function selectionFromReconciledReusablePlan( plan: SandboxMessagingPlan, agent: Agent, writeToEnv: boolean, @@ -511,10 +521,15 @@ function selectionFromReconciledReusablePlan( SandboxMessagingDeps, "clearPlanEnv" | "inspectGatewayCredential" | "note" | "writePlanToEnv" >, -): SandboxMessagingSelection { +): Promise { const prepared = prepareReusablePlan(plan, agent, env); const reusable = { plan: prepared.plan, selectedChannels: prepared.selectedChannels }; - const reconciled = filterUnconfiguredHostChannelsFromSelection(reusable, agent, deps, false); + const reconciled = await filterUnconfiguredHostChannelsFromSelection( + reusable, + agent, + deps, + false, + ); if (writeToEnv || prepared.changed || reconciled.plan !== prepared.plan) { persistMessagingPlan(reconciled.plan, deps); } @@ -522,18 +537,18 @@ function selectionFromReconciledReusablePlan( } /** Reconcile checkpoint channels against current host inputs before reuse. */ -function selectionFromRecordedChannels( +async function selectionFromRecordedChannels( recordedChannels: string[], envPlan: SandboxMessagingPlan | null, registryPlan: SandboxMessagingPlan | null, options: ReconcileSandboxMessagingOptions, -): SandboxMessagingSelection { +): Promise { let selection: SandboxMessagingSelection = { plan: null, selectedChannels: filterChannelNamesForCurrentAgent(recordedChannels, options.agent), }; if (registryPlan && !envPlan) { - selection = selectionFromReconciledReusablePlan( + selection = await selectionFromReconciledReusablePlan( registryPlan, options.agent, true, @@ -542,7 +557,7 @@ function selectionFromRecordedChannels( ); } else { if (envPlan) { - selection = selectionFromReconciledReusablePlan( + selection = await selectionFromReconciledReusablePlan( envPlan, options.agent, false, @@ -550,7 +565,7 @@ function selectionFromRecordedChannels( options.deps, ); } else { - selection = filterUnconfiguredHostChannelsFromSelection( + selection = await filterUnconfiguredHostChannelsFromSelection( selection, options.agent, options.deps, @@ -618,7 +633,7 @@ async function selectionFromRegistryPlan( ); } -export function reconcileReusedSandboxMessaging( +export async function reconcileReusedSandboxMessaging( plan: SandboxMessagingPlan | null, agent: Agent, deps: Pick< @@ -626,9 +641,9 @@ export function reconcileReusedSandboxMessaging( "clearPlanEnv" | "inspectGatewayCredential" | "note" | "writePlanToEnv" >, recordedPlan: SandboxMessagingPlan | null = plan, -): SandboxMessagingSelection & { readonly changed: boolean } { +): Promise { const filtered = plan ? filterMessagingPlanForCurrentAgent(plan, agent) : null; - const selection = filterUnconfiguredHostChannelsFromSelection( + const selection = await filterUnconfiguredHostChannelsFromSelection( { plan: filtered, selectedChannels: getActiveChannelsFromPlan(filtered) }, agent, deps, @@ -673,15 +688,15 @@ async function selectionFromDivergedMessagingCheckpoint( return selectionFromMessagingSetup([...checkpointedChannels], options, true); } -function missingCredentialNeedsValidation( +async function missingCredentialNeedsValidation( binding: SandboxMessagingPlan["credentialBindings"][number], agent: SandboxMessagingPlan["agent"], validateMissingCredentials: boolean, stagedProviderNames: ReadonlySet, deps: Pick, "providerMatchesGatewayCredential">, -): boolean { +): Promise { if (validateMissingCredentials && !stagedProviderNames.has(binding.providerName)) return true; - const providerMatches = deps.providerMatchesGatewayCredential( + const providerMatches = await deps.providerMatchesGatewayCredential( binding.providerName, staticMessagingProviderTypeForChannel(binding.channelId, agent) ?? MESSAGING_CREDENTIAL_PROVIDER_TYPE, @@ -690,13 +705,13 @@ function missingCredentialNeedsValidation( return validateMissingCredentials && !providerMatches; } -function channelsNeedingCredentialValidation( +async function channelsNeedingCredentialValidation( plan: SandboxMessagingPlan, selectedChannels: readonly string[], validateMissingCredentials: boolean, stagedProviderNames: ReadonlySet, deps: Pick, "providerMatchesGatewayCredential">, -): string[] { +): Promise { const activeChannels = new Set(selectedChannels); const channels = new Set(); for (const binding of plan.credentialBindings) { @@ -708,13 +723,13 @@ function channelsNeedingCredentialValidation( } if ( !credentialHash && - missingCredentialNeedsValidation( + (await missingCredentialNeedsValidation( binding, plan.agent, validateMissingCredentials, stagedProviderNames, deps, - ) + )) ) { channels.add(binding.channelId); } @@ -772,7 +787,7 @@ async function selectionFromCompletedMessagingCheckpoint( return selection; } - const credentialValidationChannels = channelsNeedingCredentialValidation( + const credentialValidationChannels = await channelsNeedingCredentialValidation( filteredPlan, selectedChannels, validateMissingCredentials, @@ -811,7 +826,7 @@ async function selectionFromCompletedRegistryCheckpoint( const filteredPlan = registryPlan ? filterMessagingPlanForCurrentAgent(registryPlan, options.agent) : null; - const reconciled = filterUnconfiguredHostChannelsFromSelection( + const reconciled = await filterUnconfiguredHostChannelsFromSelection( { plan: filteredPlan, selectedChannels: getActiveChannelsFromPlan(filteredPlan) }, options.agent, options.deps, @@ -958,7 +973,7 @@ export async function reconcileSandboxMessaging( resolvedOptions, ); if (completedSelection) return completedSelection; - const recordedChannels = resolvedOptions.deps.getRecordedMessagingChannelsForResume( + const recordedChannels = await resolvedOptions.deps.getRecordedMessagingChannelsForResume( resolvedOptions.resume, resolvedOptions.session, resolvedOptions.sandboxName, diff --git a/src/lib/onboard/machine/handlers/sandbox.ts b/src/lib/onboard/machine/handlers/sandbox.ts index cb5bb700655..e920ebde768 100644 --- a/src/lib/onboard/machine/handlers/sandbox.ts +++ b/src/lib/onboard/machine/handlers/sandbox.ts @@ -297,7 +297,7 @@ export interface SandboxStateOptions< resume: boolean, session: Session | null, sandboxName: string | null, - ): string[] | null; + ): string[] | null | Promise; showMessagingStage?(): void; setupMessagingChannels( agent: Agent, @@ -315,8 +315,14 @@ export interface SandboxStateOptions< name: string, type: string, credentialEnv: string, - ): import("../../gateway-provider-metadata").GatewayCredentialOnlyProviderInspection; - providerMatchesGatewayCredential(name: string, type: string, credentialEnv: string): boolean; + ): + | import("../../gateway-provider-metadata").GatewayCredentialOnlyProviderInspection + | Promise; + providerMatchesGatewayCredential( + name: string, + type: string, + credentialEnv: string, + ): boolean | Promise; stageSandboxCredentialProviders(input: { sandboxName: string; enabledChannels: readonly string[]; @@ -331,7 +337,9 @@ export interface SandboxStateOptions< listRegistrySandboxes(): { sandboxes: unknown[] }; planRegisteredExtraProviders( gatewayName: string, - ): import("../../extra-provider-reconciliation").ExtraProviderReconciliationPlan; + ): + | import("../../extra-provider-reconciliation").ExtraProviderReconciliationPlan + | Promise; resolveSandboxCreateIntent(input: { sandboxName: string; inferenceProvider?: string | null; @@ -727,7 +735,9 @@ class SandboxStateFlow< return this.checkpointSandboxName(state, explicitName); } - private resolveResumeDecision(state: SandboxStepState): SandboxResumeDecision { + private async resolveResumeDecision( + state: SandboxStepState, + ): Promise { const storedMessagingConfig = this.deps.getStoredMessagingChannelConfig( state.sandboxName, state.session, @@ -832,11 +842,11 @@ class SandboxStateFlow< return this.resolveCheckpointCrashRecovery(managedDcodeDecision, state, sandboxReuseState); } - private resolveCheckpointCrashRecovery( + private async resolveCheckpointCrashRecovery( decision: SandboxResumeDecision, state: SandboxStepState, sandboxReuseState: string, - ): SandboxResumeDecision { + ): Promise { if (this.options.recreateSandbox(false)) return decision; return this.applyCheckpointCrashRecovery(decision, state, sandboxReuseState); } @@ -847,11 +857,11 @@ class SandboxStateFlow< // durable checkpoint proves that (recorded identity + a sandbox_create // effect receipt), disambiguate using live state instead of blindly // recreating under the same name (#5961, #6228). - private applyCheckpointCrashRecovery( + private async applyCheckpointCrashRecovery( decision: SandboxResumeDecision, state: SandboxStepState, sandboxReuseState: string, - ): SandboxResumeDecision { + ): Promise { if (!shouldApplyCheckpointCrashRecovery(decision, this.options.recreateSandbox(false))) { return decision; } @@ -873,7 +883,7 @@ class SandboxStateFlow< const bindingCheck = revalidateCheckpointBindings( checkpoint, - this.checkpointBindingAvailabilityBeforeProviderReplay(checkpoint), + await this.checkpointBindingAvailabilityBeforeProviderReplay(checkpoint), ); if (bindingCheck.status === "stale") return this.rejectStaleCheckpointBindings(bindingCheck); @@ -945,13 +955,13 @@ class SandboxStateFlow< return this.deps.exitProcess(1); } - private checkpointBindingAvailability( + private async checkpointBindingAvailability( checkpoint: OnboardCheckpoint, provisionallyAvailableBindings: readonly CheckpointProviderBinding[] = [], - ): { + ): Promise<{ availableCredentialEnvs: ReadonlySet; liveRegisteredProviders: ReadonlySet; - } { + }> { const provisionallyAvailableBindingKeys = new Set( provisionallyAvailableBindings.map(checkpointProviderBindingKey), ); @@ -959,17 +969,24 @@ class SandboxStateFlow< for (const binding of checkpoint.bindings.registeredProviders) { bindingNameCounts.set(binding.name, (bindingNameCounts.get(binding.name) ?? 0) + 1); } - const liveRegisteredBindings = checkpoint.bindings.registeredProviders.filter( - (binding) => - bindingNameCounts.get(binding.name) === 1 && - isCanonicalCheckpointProviderBinding(binding) && - (provisionallyAvailableBindingKeys.has(checkpointProviderBindingKey(binding)) || - this.deps.providerMatchesGatewayCredential( - binding.name, - binding.type, - binding.credentialEnv, - )), - ); + const liveRegisteredBindings = ( + await Promise.all( + checkpoint.bindings.registeredProviders.map(async (binding) => ({ + binding, + live: + bindingNameCounts.get(binding.name) === 1 && + isCanonicalCheckpointProviderBinding(binding) && + (provisionallyAvailableBindingKeys.has(checkpointProviderBindingKey(binding)) || + (await this.deps.providerMatchesGatewayCredential( + binding.name, + binding.type, + binding.credentialEnv, + ))), + })), + ) + ) + .filter(({ live }) => live) + .map(({ binding }) => binding); return { availableCredentialEnvs: new Set( [ @@ -986,10 +1003,12 @@ class SandboxStateFlow< }; } - private checkpointBindingAvailabilityBeforeProviderReplay(checkpoint: OnboardCheckpoint): { + private async checkpointBindingAvailabilityBeforeProviderReplay( + checkpoint: OnboardCheckpoint, + ): Promise<{ availableCredentialEnvs: ReadonlySet; liveRegisteredProviders: ReadonlySet; - } { + }> { const replayableBindings = this.replayableCheckpointProviderBindings(checkpoint); return this.checkpointBindingAvailability(checkpoint, replayableBindings); } @@ -1044,12 +1063,14 @@ class SandboxStateFlow< return this.deps.exitProcess(1); } - private assertCheckpointBindingsStillLive(state: SandboxStepState): void { + private async assertCheckpointBindingsStillLive( + state: SandboxStepState, + ): Promise { const checkpoint = state.session?.checkpoint; if (!checkpoint) return; const bindingCheck = revalidateCheckpointBindings( checkpoint, - this.checkpointBindingAvailability(checkpoint), + await this.checkpointBindingAvailability(checkpoint), ); if (bindingCheck.status === "stale") this.rejectStaleCheckpointBindings(bindingCheck); } @@ -1191,7 +1212,7 @@ class SandboxStateFlow< state: SandboxStepState, ): Promise> { return this.deps.withGatewayRouteMutationLock(this.options.gatewayName, async () => { - this.assertCheckpointBindingsStillLive(state); + await this.assertCheckpointBindingsStillLive(state); this.assertGatewayRouteCompatible(state.sandboxName); if (state.webSearchConfig) { const provider = webSearchProviderForConfig( @@ -1205,7 +1226,7 @@ class SandboxStateFlow< state.sandboxName, state.session, ); - const messaging = reconcileReusedSandboxMessaging( + const messaging = await reconcileReusedSandboxMessaging( messagingAuthority.plan, this.options.agent, this.deps, @@ -1357,11 +1378,11 @@ class SandboxStateFlow< state.sandboxName && !localCredential && this.ownsGatewayWebSearchProvider(state, `${state.sandboxName}-${provider}-search`) && - this.deps.providerMatchesGatewayCredential( + (await this.deps.providerMatchesGatewayCredential( `${state.sandboxName}-${provider}-search`, provider, credentialEnv, - ) + )) ) { this.deps.note(` [resume] Reusing ${label} credential registered with OpenShell.`); return state.webSearchConfig; @@ -1514,6 +1535,21 @@ class SandboxStateFlow< replaceExisting = false, verifiedIdentityRevalidation?: (operation: string) => void, ): Promise { + const observedBindings = new Map( + await Promise.all( + requiredBindings.map( + async (binding) => + [ + checkpointProviderBindingKey(binding), + await this.deps.providerMatchesGatewayCredential( + binding.name, + binding.type, + binding.credentialEnv, + ), + ] as const, + ), + ), + ); if ( !this.resumesSandboxPrompts || (!webSearchConfig && enabledChannels.length === 0 && requiredBindings.length === 0) @@ -1536,12 +1572,11 @@ class SandboxStateFlow< planEffectGroupReplay( checkpoint, group, - observeProviderEffectFingerprint(checkpoint, group, requiredBindings, (binding) => - this.deps.providerMatchesGatewayCredential( - binding.name, - binding.type, - binding.credentialEnv, - ), + observeProviderEffectFingerprint( + checkpoint, + group, + requiredBindings, + (binding) => observedBindings.get(checkpointProviderBindingKey(binding)) === true, ), ).action === "skip" ) { @@ -1578,13 +1613,17 @@ class SandboxStateFlow< } stagedProviderNames.add(binding.name); } - const allRequiredBindingsLive = requiredBindings.every((binding) => - this.deps.providerMatchesGatewayCredential( - binding.name, - binding.type, - binding.credentialEnv, - ), - ); + const allRequiredBindingsLive = ( + await Promise.all( + requiredBindings.map((binding) => + this.deps.providerMatchesGatewayCredential( + binding.name, + binding.type, + binding.credentialEnv, + ), + ), + ) + ).every(Boolean); if (!allRequiredBindingsLive) { this.deps.error(" OpenShell did not retain the selected credential bindings."); this.deps.error(" Re-run onboarding with the required credentials available."); @@ -2096,7 +2135,9 @@ class SandboxStateFlow< state.webSearchConfig as unknown as SharedWebSearchConfig | null, this.options.hermesToolGateways, ); - const extraProviderPlan = this.deps.planRegisteredExtraProviders(this.options.gatewayName); + const extraProviderPlan = await this.deps.planRegisteredExtraProviders( + this.options.gatewayName, + ); const createAndRecord = async (): Promise> => { this.assertRegistryMessagingPlanUnchanged( requestedSandboxName, @@ -2131,7 +2172,7 @@ class SandboxStateFlow< this.options.provider.trim().length === 0 && this.options.model.trim().length === 0; this.assertGatewayRouteCompatible(requestedSandboxName); - this.assertCheckpointBindingsStillLive(state); + await this.assertCheckpointBindingsStillLive(state); this.assertCheckpointCreateInputsStillMatch( state, requestedSandboxName, @@ -2514,7 +2555,7 @@ class SandboxStateFlow< const initialState = this.checkpointChangedExplicitSandboxName( this.applyObservabilityRequest(this.prepareWebSearchSupport()), ); - const decision = this.resolveResumeDecision(initialState); + const decision = await this.resolveResumeDecision(initialState); const completedState = decision.kind === "reuse" ? await this.reuseSandbox(initialState) diff --git a/src/lib/onboard/machine/resume-provider-shim.ts b/src/lib/onboard/machine/resume-provider-shim.ts index cbf6e4cdbec..5380eecc80e 100644 --- a/src/lib/onboard/machine/resume-provider-shim.ts +++ b/src/lib/onboard/machine/resume-provider-shim.ts @@ -23,7 +23,7 @@ const onboardProviders = require("../providers") as { export type ResumeProviderShimDeps = { isNonInteractive: ResumeProviderRecoveryDeps["isNonInteractive"]; - providerExistsInGateway(name: string, gatewayName: string): boolean; + providerExistsInGateway(name: string, gatewayName: string): boolean | Promise; isRoutedInferenceProvider: ResumeProviderRecoveryDeps["isRoutedInferenceProvider"]; replaceNamedCredential: ResumeProviderRecoveryDeps["replaceNamedCredential"]; /** Recover an exact gateway-scoped managed runtime; false means no managed owner state exists. */ diff --git a/src/lib/onboard/messaging-credentials.ts b/src/lib/onboard/messaging-credentials.ts index 315c601c955..cd550e94a86 100644 --- a/src/lib/onboard/messaging-credentials.ts +++ b/src/lib/onboard/messaging-credentials.ts @@ -19,11 +19,11 @@ export interface RecordedMessagingChannelsOptions { sandboxName: string | null; channels: unknown[]; getCredential(envKey: string): string | null | undefined; - providerExistsInGateway(name: string): boolean; + providerExistsInGateway(name: string): boolean | Promise; isNonInteractive(): boolean; } -export function getRecordedMessagingChannelsForResume({ +export async function getRecordedMessagingChannelsForResume({ resume, sessionMessagingChannels, sandboxName, @@ -31,7 +31,7 @@ export function getRecordedMessagingChannelsForResume({ getCredential, providerExistsInGateway, isNonInteractive, -}: RecordedMessagingChannelsOptions): string[] | null { +}: RecordedMessagingChannelsOptions): Promise { return require("./messaging-reuse").getNonInteractiveStoredMessagingChannels( resume, sessionMessagingChannels, diff --git a/src/lib/onboard/messaging-prep.test.ts b/src/lib/onboard/messaging-prep.test.ts index b2d7dbb2d3f..0d3a6069b12 100644 --- a/src/lib/onboard/messaging-prep.test.ts +++ b/src/lib/onboard/messaging-prep.test.ts @@ -43,10 +43,10 @@ function createInput( } describe("prepareCreateSandboxMessaging", () => { - it("does not read messaging credentials when no channel is enabled (#9833)", () => { + it("does not read messaging credentials when no channel is enabled (#9833)", async () => { const getValidatedMessagingTokenByEnvKey = vi.fn(() => "secret-value"); - const result = prepareCreateSandboxMessaging( + const result = await prepareCreateSandboxMessaging( createInput({ enabledChannels: [], getValidatedMessagingTokenByEnvKey, @@ -57,7 +57,7 @@ describe("prepareCreateSandboxMessaging", () => { expect(result.messagingTokenDefs).toEqual([]); }); - it("filters token definitions and reuses missing-token providers with matching bindings", () => { + it("filters token definitions and reuses missing-token providers with matching bindings", async () => { const registerExtraPlaceholderProviders = vi.fn(() => ["SLACK_BOT_TOKEN_AGENT_A"]); const providerMatchesGatewayCredential = vi.fn( (name: string, type: string, credentialKey: string) => @@ -66,7 +66,7 @@ describe("prepareCreateSandboxMessaging", () => { credentialKey === "SLACK_BOT_TOKEN", ); - const result = prepareCreateSandboxMessaging( + const result = await prepareCreateSandboxMessaging( createInput({ enabledChannels: ["slack", "telegram"], disabledChannels: ["telegram"], @@ -93,7 +93,7 @@ describe("prepareCreateSandboxMessaging", () => { ); }); - it("reattaches an exact durable provider when rebuild resumes without channel prompts", () => { + it("reattaches an exact durable provider when rebuild resumes without channel prompts", async () => { const providerMatchesGatewayCredential = vi.fn( (name: string, type: string, credentialKey: string) => name === "demo-discord-bridge" && @@ -101,7 +101,7 @@ describe("prepareCreateSandboxMessaging", () => { credentialKey === "DISCORD_BOT_TOKEN", ); - const result = prepareCreateSandboxMessaging( + const result = await prepareCreateSandboxMessaging( createInput({ enabledChannels: null, requireExactProviderBinding: true, @@ -118,7 +118,7 @@ describe("prepareCreateSandboxMessaging", () => { ); }); - it("reuses an existing gateway bridge provider when the bridge secret is not resolvable", () => { + it("reuses an existing gateway bridge provider when the bridge secret is not resolvable", async () => { // Deferred rebuild in a fresh process: the pasted secret is env-only and // gone, so no bridge token def exists — but the gateway still durably // holds the refresh material, so the provider only needs re-attaching. @@ -130,7 +130,7 @@ describe("prepareCreateSandboxMessaging", () => { credentialKey === "GOOGLE_CHAT_ACCESS_TOKEN", ); - const result = prepareCreateSandboxMessaging( + const result = await prepareCreateSandboxMessaging( createInput({ enabledChannels: ["googlechat"], providerMatchesGatewayCredential, @@ -149,13 +149,13 @@ describe("prepareCreateSandboxMessaging", () => { ); }); - it("refuses and reports a bridge the gateway holds for a different agent", () => { + it("refuses and reports a bridge the gateway holds for a different agent", async () => { // onboard recreates a sandbox name under a new agent (`Delete and recreate // '' as ?`), and the provider name carries no agent. Reusing the // stale binding would mint the previous agent's token — for Hermes that means // an OpenClaw profile whose scopes omit pubsub, so `:pull` fails with 403. // Refusing it also has to surface, or the channel silently leaves the intent. - const result = prepareCreateSandboxMessaging( + const result = await prepareCreateSandboxMessaging( createInput({ agentName: "hermes", enabledChannels: ["googlechat"], @@ -169,8 +169,8 @@ describe("prepareCreateSandboxMessaging", () => { expect(result.missingBridgeChannels).toEqual(["googlechat"]); }); - it("reuses a bridge the gateway holds for the agent being onboarded", () => { - const result = prepareCreateSandboxMessaging( + it("reuses a bridge the gateway holds for the agent being onboarded", async () => { + const result = await prepareCreateSandboxMessaging( createInput({ agentName: "hermes", enabledChannels: ["googlechat"], @@ -184,12 +184,12 @@ describe("prepareCreateSandboxMessaging", () => { expect(result.missingBridgeChannels).toEqual([]); }); - it("does not reuse a Hermes bridge when onboarding OpenClaw", () => { + it("does not reuse a Hermes bridge when onboarding OpenClaw", async () => { const gatewayHoldsHermesBinding = vi.fn( (_name: string, type: string) => type === "google-chat-hermes-bridge", ); - const result = prepareCreateSandboxMessaging( + const result = await prepareCreateSandboxMessaging( createInput({ enabledChannels: ["googlechat"], providerMatchesGatewayCredential: gatewayHoldsHermesBinding, @@ -200,10 +200,10 @@ describe("prepareCreateSandboxMessaging", () => { expect(result.reusableMessagingChannels).not.toContain("googlechat"); }); - it("routes the bridge through upsert instead of reuse when the secret is resolvable", () => { + it("routes the bridge through upsert instead of reuse when the secret is resolvable", async () => { const providerMatchesGatewayCredential = vi.fn(() => true); - const result = prepareCreateSandboxMessaging( + const result = await prepareCreateSandboxMessaging( createInput({ enabledChannels: ["googlechat"], env: { @@ -225,10 +225,10 @@ describe("prepareCreateSandboxMessaging", () => { expect(providerMatchesGatewayCredential).not.toHaveBeenCalled(); }); - it("configures no bridge for an agent no channel manifest supports", () => { + it("configures no bridge for an agent no channel manifest supports", async () => { // Defaulting an unknown agent to OpenClaw would hand a sandbox with no // messaging support the OpenClaw Google Chat bridge and its credential. - const result = prepareCreateSandboxMessaging( + const result = await prepareCreateSandboxMessaging( createInput({ agentName: "deepagents", enabledChannels: ["googlechat"], @@ -250,8 +250,8 @@ describe("prepareCreateSandboxMessaging", () => { expect(result.reusableMessagingChannels).not.toContain("googlechat"); }); - it("does not reuse a bridge provider without an exact gateway binding", () => { - const result = prepareCreateSandboxMessaging( + it("does not reuse a bridge provider without an exact gateway binding", async () => { + const result = await prepareCreateSandboxMessaging( createInput({ enabledChannels: ["googlechat"], providerMatchesGatewayCredential: () => false, @@ -263,12 +263,12 @@ describe("prepareCreateSandboxMessaging", () => { expect(result.missingBridgeChannels).toEqual(["googlechat"]); }); - it("does not reuse the bridge provider of a disabled channel", () => { + it("does not reuse the bridge provider of a disabled channel", async () => { // The matcher would accept this provider, so only the disabled guard can // keep it out — and a disabled channel is not a missing one either. const providerMatchesGatewayCredential = vi.fn(() => true); - const result = prepareCreateSandboxMessaging( + const result = await prepareCreateSandboxMessaging( createInput({ enabledChannels: ["googlechat"], disabledChannels: ["googlechat"], @@ -281,10 +281,10 @@ describe("prepareCreateSandboxMessaging", () => { expect(providerMatchesGatewayCredential).not.toHaveBeenCalled(); }); - it("reports missing Brave API keys before registering extra placeholder providers", () => { + it("reports missing Brave API keys before registering extra placeholder providers", async () => { const registerExtraPlaceholderProviders = vi.fn(() => ["BRAVE_API_KEY_AGENT_A"]); - const result = prepareCreateSandboxMessaging( + const result = await prepareCreateSandboxMessaging( createInput({ webSearchConfig: { fetchEnabled: true }, env: { [BRAVE_API_KEY_ENV]: " " }, @@ -300,13 +300,13 @@ describe("prepareCreateSandboxMessaging", () => { expect(registerExtraPlaceholderProviders).not.toHaveBeenCalled(); }); - it("reuses an exact Brave gateway provider when the raw key is unavailable (#6743)", () => { + it("reuses an exact Brave gateway provider when the raw key is unavailable (#6743)", async () => { const providerMatchesGatewayCredential = vi.fn( (name: string, type: string, credentialEnv: string) => name === "demo-brave-search" && type === "brave" && credentialEnv === BRAVE_API_KEY_ENV, ); - const result = prepareCreateSandboxMessaging( + const result = await prepareCreateSandboxMessaging( createInput({ webSearchConfig: { fetchEnabled: true }, requireExactProviderBinding: true, @@ -324,8 +324,8 @@ describe("prepareCreateSandboxMessaging", () => { expect(result.reusableMessagingProviders).toEqual(["demo-brave-search"]); }); - it("reports a missing Tavily key using the selected provider credential", () => { - const result = prepareCreateSandboxMessaging( + it("reports a missing Tavily key using the selected provider credential", async () => { + const result = await prepareCreateSandboxMessaging( createInput({ webSearchConfig: { fetchEnabled: true, provider: "tavily" }, env: { [BRAVE_API_KEY_ENV]: "brv-does-not-satisfy-tavily" }, @@ -338,10 +338,10 @@ describe("prepareCreateSandboxMessaging", () => { ); }); - it("adds the Brave provider token from the credential store before host env fallback", () => { + it("adds the Brave provider token from the credential store before host env fallback", async () => { const registerExtraPlaceholderProviders = vi.fn(() => []); - const result = prepareCreateSandboxMessaging( + const result = await prepareCreateSandboxMessaging( createInput({ webSearchConfig: { fetchEnabled: true }, env: { [BRAVE_API_KEY_ENV]: "brv-host" }, @@ -360,8 +360,8 @@ describe("prepareCreateSandboxMessaging", () => { }); }); - it("adds a per-sandbox Tavily provider with credential-store precedence", () => { - const result = prepareCreateSandboxMessaging( + it("adds a per-sandbox Tavily provider with credential-store precedence", async () => { + const result = await prepareCreateSandboxMessaging( createInput({ webSearchConfig: { fetchEnabled: true, provider: "tavily" }, env: { [TAVILY_API_KEY_ENV]: "tvly-host" }, @@ -378,8 +378,8 @@ describe("prepareCreateSandboxMessaging", () => { }); }); - it("uses the versioned Hermes Tavily profile for Hermes sandboxes", () => { - const result = prepareCreateSandboxMessaging( + it("uses the versioned Hermes Tavily profile for Hermes sandboxes", async () => { + const result = await prepareCreateSandboxMessaging( createInput({ agentName: "hermes", webSearchConfig: { fetchEnabled: true, provider: "tavily" }, @@ -395,8 +395,8 @@ describe("prepareCreateSandboxMessaging", () => { }); }); - it("removes both Slack bot and app token definitions when Slack is disabled", () => { - const result = prepareCreateSandboxMessaging( + it("removes both Slack bot and app token definitions when Slack is disabled", async () => { + const result = await prepareCreateSandboxMessaging( createInput({ disabledChannels: ["slack"], getValidatedMessagingTokenByEnvKey: (_channels, envKey) => @@ -409,10 +409,10 @@ describe("prepareCreateSandboxMessaging", () => { expect(result.messagingTokenDefs.map(({ envKey }) => envKey)).not.toContain("SLACK_APP_TOKEN"); }); - it("includes all static token-backed channels by default without probing reusable providers", () => { + it("includes all static token-backed channels by default without probing reusable providers", async () => { const providerMatchesGatewayCredential = vi.fn(() => true); - const result = prepareCreateSandboxMessaging( + const result = await prepareCreateSandboxMessaging( createInput({ enabledChannels: null, providerMatchesGatewayCredential, @@ -432,8 +432,8 @@ describe("prepareCreateSandboxMessaging", () => { expect(providerMatchesGatewayCredential).not.toHaveBeenCalled(); }); - it("binds static messaging credentials to the endpointless provider profile (#9875)", () => { - const result = prepareCreateSandboxMessaging( + it("binds static messaging credentials to the endpointless provider profile (#9875)", async () => { + const result = await prepareCreateSandboxMessaging( createInput({ enabledChannels: ["discord", "slack"], getValidatedMessagingTokenByEnvKey: (_channels, envKey) => `${envKey}-value`, @@ -459,8 +459,8 @@ describe("prepareCreateSandboxMessaging", () => { ]); }); - it("uses BRAVE_API_KEY from host env when the credential store has no value", () => { - const result = prepareCreateSandboxMessaging( + it("uses BRAVE_API_KEY from host env when the credential store has no value", async () => { + const result = await prepareCreateSandboxMessaging( createInput({ webSearchConfig: { fetchEnabled: true }, env: { [BRAVE_API_KEY_ENV]: " brv-host " }, @@ -475,8 +475,8 @@ describe("prepareCreateSandboxMessaging", () => { }); }); - it("does not create static token definitions for tokenless QR channels", () => { - const result = prepareCreateSandboxMessaging( + it("does not create static token definitions for tokenless QR channels", async () => { + const result = await prepareCreateSandboxMessaging( createInput({ enabledChannels: ["whatsapp"], }), diff --git a/src/lib/onboard/messaging-prep.ts b/src/lib/onboard/messaging-prep.ts index 8db823574a0..ceb43290ea2 100644 --- a/src/lib/onboard/messaging-prep.ts +++ b/src/lib/onboard/messaging-prep.ts @@ -58,8 +58,12 @@ export interface CreateSandboxMessagingPrepInput { sources?: ExtraPlaceholderCredentialSources, ): string[]; getMessagingChannelForEnvKey(envKey: string): string | null; - providerExistsInGateway(name: string): boolean; - providerMatchesGatewayCredential(name: string, type: string, credentialEnv: string): boolean; + providerExistsInGateway(name: string): boolean | Promise; + providerMatchesGatewayCredential( + name: string, + type: string, + credentialEnv: string, + ): boolean | Promise; } export interface CreateSandboxMessagingPrepResult { @@ -74,9 +78,9 @@ export interface CreateSandboxMessagingPrepResult { missingWebSearchCredentialEnv: string | null; } -export function prepareCreateSandboxMessaging( +export async function prepareCreateSandboxMessaging( input: CreateSandboxMessagingPrepInput, -): CreateSandboxMessagingPrepResult { +): Promise { const requiresExactOpenClawProviderBinding = input.requireExactProviderBinding === true && (!input.agentName || input.agentName.trim().toLowerCase() === "openclaw"); @@ -142,11 +146,11 @@ export function prepareCreateSandboxMessaging( requiresExactOpenClawProviderBinding && webSearchEnabled && !webSearchApiKey && - input.providerMatchesGatewayCredential( + (await input.providerMatchesGatewayCredential( webSearchProviderName, webSearchProviderType, webSearchCredentialEnv, - ); + )); const missingWebSearchCredentialEnv = webSearchEnabled && !webSearchApiKey && !reusableWebSearchProvider ? webSearchCredentialEnv @@ -235,10 +239,10 @@ export function prepareCreateSandboxMessaging( // provider already holding that authority. if (token && !channelDisabled) continue; const providerReusable = providerType - ? input.providerMatchesGatewayCredential(name, providerType, envKey) + ? await input.providerMatchesGatewayCredential(name, providerType, envKey) : requiresExactOpenClawProviderBinding - ? input.providerMatchesGatewayCredential(name, "generic", envKey) - : input.providerExistsInGateway(name); + ? await input.providerMatchesGatewayCredential(name, "generic", envKey) + : await input.providerExistsInGateway(name); if (!providerReusable) continue; reusableMessagingProviders.push(name); if (!channelDisabled && !reusableMessagingChannels.includes(channel)) { @@ -261,7 +265,13 @@ export function prepareCreateSandboxMessaging( for (const name of bridgeProviderNamesForChannel(input.sandboxName, channel, [profile])) { if (messagingTokenDefs.some((def) => def.name === name && def.token)) continue; if (reusableMessagingProviders.includes(name)) continue; - if (!input.providerMatchesGatewayCredential(name, profile.profileId, profile.credentialKey)) + if ( + !(await input.providerMatchesGatewayCredential( + name, + profile.profileId, + profile.credentialKey, + )) + ) continue; reusableMessagingProviders.push(name); if (!reusableMessagingChannels.includes(channel)) { diff --git a/src/lib/onboard/messaging-reuse.test.ts b/src/lib/onboard/messaging-reuse.test.ts index 839518bb90e..a4da6b08f66 100644 --- a/src/lib/onboard/messaging-reuse.test.ts +++ b/src/lib/onboard/messaging-reuse.test.ts @@ -49,7 +49,7 @@ function authoritativeRegistry( } describe("onboard messaging reuse", () => { - it("maps one bridge provider for single-token messaging channels", () => { + it("maps one bridge provider for single-token messaging channels", async () => { expect(getMessagingProviderNamesForChannel("assistant", "discord")).toEqual([ "assistant-discord-bridge", ]); @@ -61,13 +61,13 @@ describe("onboard messaging reuse", () => { ]); }); - it("requires both Slack providers before reusing a stored Slack channel", () => { + it("requires both Slack providers before reusing a stored Slack channel", async () => { expect(getMessagingProviderNamesForChannel("assistant", "slack")).toEqual([ "assistant-slack-bridge", "assistant-slack-app", ]); - const reusedChannels = getNonInteractiveStoredMessagingChannels( + const reusedChannels = await getNonInteractiveStoredMessagingChannels( false, null, "assistant", @@ -81,8 +81,8 @@ describe("onboard messaging reuse", () => { expect(reusedChannels).toBeNull(); }); - it("reuses stored Slack channels when both Slack providers exist", () => { - const reusedChannels = getNonInteractiveStoredMessagingChannels( + it("reuses stored Slack channels when both Slack providers exist", async () => { + const reusedChannels = await getNonInteractiveStoredMessagingChannels( false, null, "assistant", @@ -96,8 +96,8 @@ describe("onboard messaging reuse", () => { expect(reusedChannels).toEqual(["slack"]); }); - it("reuses a stored WeChat channel when its bridge provider exists", () => { - const reusedChannels = getNonInteractiveStoredMessagingChannels( + it("reuses a stored WeChat channel when its bridge provider exists", async () => { + const reusedChannels = await getNonInteractiveStoredMessagingChannels( false, null, "assistant", @@ -111,8 +111,8 @@ describe("onboard messaging reuse", () => { expect(reusedChannels).toEqual(["wechat"]); }); - it("honors an explicit empty resume messaging channel set", () => { - const reusedChannels = getNonInteractiveStoredMessagingChannels( + it("honors an explicit empty resume messaging channel set", async () => { + const reusedChannels = await getNonInteractiveStoredMessagingChannels( true, ["unknown"], "assistant", @@ -126,8 +126,8 @@ describe("onboard messaging reuse", () => { expect(reusedChannels).toEqual([]); }); - it("does not rediscover token-backed channels when resume recorded none", () => { - const reusedChannels = getNonInteractiveStoredMessagingChannels( + it("does not rediscover token-backed channels when resume recorded none", async () => { + const reusedChannels = await getNonInteractiveStoredMessagingChannels( true, [], "assistant", @@ -141,13 +141,14 @@ describe("onboard messaging reuse", () => { expect(reusedChannels).toEqual([]); }); - it("does not reuse messaging channels from a pending route reservation without a host token", () => { - const getRegistryMessagingAuthority = vi.fn( - (): RegistryMessagingAuthority => ({ authoritative: false, plan: null }), - ); + it("does not reuse messaging channels from a pending route reservation without a host token", async () => { + const getRegistryMessagingAuthority = vi.fn((): RegistryMessagingAuthority => ({ + authoritative: false, + plan: null, + })); const providerExists = vi.fn(() => true); - const reusedChannels = getNonInteractiveStoredMessagingChannels( + const reusedChannels = await getNonInteractiveStoredMessagingChannels( false, null, "assistant", diff --git a/src/lib/onboard/messaging-reuse.ts b/src/lib/onboard/messaging-reuse.ts index f772b2e7162..2ee5b26a52a 100644 --- a/src/lib/onboard/messaging-reuse.ts +++ b/src/lib/onboard/messaging-reuse.ts @@ -23,16 +23,16 @@ function getKnownMessagingChannels( return [...new Set(channels.filter((channel) => known.has(channel)))]; } -export function getNonInteractiveStoredMessagingChannels( +export async function getNonInteractiveStoredMessagingChannels( resume: boolean, sessionChannels: string[] | null | undefined, sandboxName: string | null, messagingChannels: readonly MessagingChannel[], hasMessagingToken: (envKey: string) => boolean, getRegistryMessagingAuthority: (sandboxName: string) => RegistryMessagingAuthority, - providerExists: (providerName: string) => boolean, + providerExists: (providerName: string) => boolean | Promise, nonInteractive: boolean, -): string[] | null { +): Promise { if (!nonInteractive) return null; if (resume && Array.isArray(sessionChannels)) { const knownSessionChannels = getKnownMessagingChannels(sessionChannels, messagingChannels); @@ -53,10 +53,15 @@ export function getNonInteractiveStoredMessagingChannels( messagingChannels, ); const disabledChannels = new Set(getDisabledChannelsFromPlan(registryAuthority.plan)); - const reusableChannels = configuredChannels.filter((channel) => { - if (disabledChannels.has(channel)) return false; - const providers = getMessagingProviderNamesForChannel(sandboxName, channel); - return providers.length > 0 && providers.every((provider) => providerExists(provider)); - }); + const reusableChannels = ( + await Promise.all( + configuredChannels.map(async (channel) => { + if (disabledChannels.has(channel)) return null; + const providers = getMessagingProviderNamesForChannel(sandboxName, channel); + const exists = await Promise.all(providers.map((provider) => providerExists(provider))); + return providers.length > 0 && exists.every(Boolean) ? channel : null; + }), + ) + ).filter((channel): channel is string => channel !== null); return reusableChannels.length > 0 ? reusableChannels : null; } diff --git a/src/lib/onboard/openrouter-runtime.ts b/src/lib/onboard/openrouter-runtime.ts index 3ca8dcc89c3..52f928889a2 100644 --- a/src/lib/onboard/openrouter-runtime.ts +++ b/src/lib/onboard/openrouter-runtime.ts @@ -19,7 +19,9 @@ type UpsertProvider = ( credentialEnv: string, baseUrl: string | null, env?: NodeJS.ProcessEnv, -) => { ok: boolean; message?: string; status?: number }; +) => + | { ok: boolean; message?: string; status?: number } + | Promise<{ ok: boolean; message?: string; status?: number }>; type SetupInferenceResult = { ok: true; retry?: undefined } | { retry: "selection" }; @@ -83,7 +85,7 @@ export async function setupOpenRouterRuntimeInference( } const env = options.credentialValue ? { [credentialEnv]: options.credentialValue } : {}; - const providerResult = options.upsertProvider( + const providerResult = await options.upsertProvider( options.provider, "openai", credentialEnv, diff --git a/src/lib/onboard/providers.test.ts b/src/lib/onboard/providers.test.ts index 04dd28c0581..5c9509a8b92 100644 --- a/src/lib/onboard/providers.test.ts +++ b/src/lib/onboard/providers.test.ts @@ -21,13 +21,27 @@ type RunOptions = { }; type RunOpenshell = (command: string[], opts?: RunOptions) => RunResult; +function providerMetadata(name: string, type: string, credentialKey: string): RunResult { + return { + status: 0, + stdout: [ + `Id: provider-${name}`, + `Name: ${name}`, + `Type: ${type}`, + "Resource version: 1", + `Credential keys: ${credentialKey}`, + "Config keys: ", + ].join("\n"), + stderr: "", + }; +} + const { HOSTED_INFERENCE_ENDPOINT_URL, HOSTED_INFERENCE_MODEL, NON_INTERACTIVE_PROVIDER_ALIASES, NON_INTERACTIVE_PROVIDER_KEYS, REMOTE_PROVIDER_CONFIG, - buildProviderArgs, getNonInteractiveProvider, getNonInteractiveModel, getRequestedModelHint, @@ -50,13 +64,6 @@ const { defaultModel: string; } >; - buildProviderArgs: ( - action: "create" | "update", - name: string, - type: string, - credentialEnv: string, - baseUrl: string | null, - ) => string[]; getNonInteractiveProvider: (allowHostedInferenceStaging?: boolean) => string | null; getNonInteractiveModel: ( providerKey: string, @@ -132,18 +139,18 @@ function withProviderEnv(next: Record, testBody: () } describe("onboard provider helpers", () => { - it("uses Gemini 3.6 Flash as the onboarding default (#9298)", () => { + it("uses Gemini 3.6 Flash as the onboarding default (#9298)", async () => { expect(REMOTE_PROVIDER_CONFIG.gemini.defaultModel).toBe("gemini-3.6-flash"); }); - it("keeps managed llama.cpp as a public non-interactive provider selector (#8433)", () => { + it("keeps managed llama.cpp as a public non-interactive provider selector (#8433)", async () => { expect(NON_INTERACTIVE_PROVIDER_KEYS.has("install-llama-cpp")).toBe(true); withProviderEnv({ NEMOCLAW_PROVIDER: "install-llama-cpp" }, () => { expect(getNonInteractiveProvider(false)).toBe("install-llama-cpp"); }); }); - it("registers OpenRouter with an OpenAI-compatible provider profile and aliases (#5826)", () => { + it("registers OpenRouter with an OpenAI-compatible provider profile and aliases (#5826)", async () => { const provider = REMOTE_PROVIDER_CONFIG.openrouter; expect(provider).toMatchObject({ @@ -154,18 +161,9 @@ describe("onboard provider helpers", () => { expect(NON_INTERACTIVE_PROVIDER_KEYS.has("openrouter")).toBe(true); expect(NON_INTERACTIVE_PROVIDER_ALIASES["open-router"]).toBe("openrouter"); expect(NON_INTERACTIVE_PROVIDER_ALIASES.openrouterai).toBe("openrouter"); - expect( - buildProviderArgs( - "create", - provider.providerName, - provider.providerType, - provider.credentialEnv, - "https://openrouter.ai/api/v1", - ), - ).toContain("OPENAI_BASE_URL=https://openrouter.ai/api/v1"); }); - it("keeps the discovery profile Anthropic before agent-specific surface selection (#6289)", () => { + it("keeps the discovery profile Anthropic before agent-specific surface selection (#6289)", async () => { const provider = REMOTE_PROVIDER_CONFIG.anthropicCompatible; // Remote provider setup can replace this registration with type=openai @@ -175,97 +173,34 @@ describe("onboard provider helpers", () => { providerType: "anthropic", credentialEnv: "COMPATIBLE_ANTHROPIC_API_KEY", }); - expect( - buildProviderArgs( - "create", - provider.providerName, - provider.providerType, - provider.credentialEnv, - "https://inference-api.nvidia.com", - ), - ).toContain("ANTHROPIC_BASE_URL=https://inference-api.nvidia.com"); - }); - - it("builds create arguments for generic providers", () => { - const args = buildProviderArgs( - "create", - "discord-bridge", - "generic", - "DISCORD_BOT_TOKEN", - null, - ); - expect(args).toEqual([ - "provider", - "create", - "--name", - "discord-bridge", - "--type", - "generic", - "--credential", - "DISCORD_BOT_TOKEN", - ]); }); - it("builds update arguments", () => { - const args = buildProviderArgs( - "update", - "inference", - "openai", - "NVIDIA_INFERENCE_API_KEY", - null, - ); - expect(args).toEqual([ - "provider", - "update", - "inference", - "--credential", - "NVIDIA_INFERENCE_API_KEY", - ]); - }); - - it("appends OPENAI_BASE_URL config for openai providers with a base URL", () => { - const args = buildProviderArgs( - "create", - "inference", - "openai", - "NVIDIA_INFERENCE_API_KEY", - "https://api.example.com/v1", - ); - expect(args).toContain("--config"); - expect(args).toContain("OPENAI_BASE_URL=https://api.example.com/v1"); - }); - - it("appends ANTHROPIC_BASE_URL config for anthropic providers with a base URL", () => { - const args = buildProviderArgs( - "create", - "inference", - "anthropic", - "ANTHROPIC_API_KEY", - "https://api.anthropic.example.com", - ); - expect(args).toContain("--config"); - expect(args).toContain("ANTHROPIC_BASE_URL=https://api.anthropic.example.com"); - }); - - it("ignores base URL for generic providers", () => { - const args = buildProviderArgs( - "create", - "slack-bridge", - "generic", - "SLACK_BOT_TOKEN", - "https://ignored.example.com", - ); - expect(args).not.toContain("--config"); + it("checks whether providers exist in the gateway", async () => { + expect( + await providerExistsInGateway("discord-bridge", () => + providerMetadata("discord-bridge", "generic", "DISCORD_BOT_TOKEN"), + ), + ).toBe(true); + expect( + await providerExistsInGateway("missing-bridge", () => ({ + status: 1, + stderr: "provider 'missing-bridge' not found", + })), + ).toBe(false); }); - it("checks whether providers exist in the gateway", () => { - expect(providerExistsInGateway("discord-bridge", () => ({ status: 0 }))).toBe(true); - expect(providerExistsInGateway("missing-bridge", () => ({ status: 1 }))).toBe(false); + it("fails closed when provider metadata is malformed", async () => { + await expect( + providerExistsInGateway("discord-bridge", () => ({ + status: 0, + stdout: "unexpected output", + })), + ).rejects.toThrow("OpenShell returned invalid provider metadata"); }); - it("creates a new provider and returns ok on success", () => { + it("creates a new provider and returns ok on success", async () => { const commands: string[] = []; - const result = upsertProvider( + const result = await upsertProvider( "discord-bridge", "generic", "DISCORD_BOT_TOKEN", @@ -274,7 +209,9 @@ describe("onboard provider helpers", () => { (command) => { const normalized = command.join(" "); commands.push(normalized); - if (normalized.includes("provider get")) return { status: 1, stdout: "", stderr: "" }; + if (normalized.includes("provider get")) { + return { status: 1, stdout: "", stderr: "provider 'discord-bridge' not found" }; + } return { status: 0, stdout: "", stderr: "" }; }, ); @@ -286,16 +223,18 @@ describe("onboard provider helpers", () => { expect(commands[1]).toMatch(/--credential DISCORD_BOT_TOKEN/); }); - it("does not add its own log line on top of runner output (#1506)", () => { + it("does not add its own log line on top of runner output (#1506)", async () => { let stdoutWrites = 0; - const result = upsertProvider( + const result = await upsertProvider( "test-bridge", "generic", "TEST_TOKEN", null, { TEST_TOKEN: "tok" }, (command) => { - if (command.includes("get")) return { status: 1, stdout: "", stderr: "" }; + if (command.includes("get")) { + return { status: 1, stdout: "", stderr: "provider 'test-bridge' not found" }; + } stdoutWrites += 1; return { status: 0, stdout: "✓ Created provider test-bridge", stderr: "" }; }, @@ -305,9 +244,9 @@ describe("onboard provider helpers", () => { expect(stdoutWrites).toBe(1); }); - it("updates existing providers instead of creating (#1155)", () => { + it("updates existing providers instead of creating (#1155)", async () => { const commands: string[] = []; - const result = upsertProvider( + const result = await upsertProvider( "inference", "openai", "NVIDIA_INFERENCE_API_KEY", @@ -315,7 +254,9 @@ describe("onboard provider helpers", () => { {}, (command) => { commands.push(command.join(" ")); - return { status: 0, stdout: "", stderr: "" }; + return command.includes("get") + ? providerMetadata("inference", "openai", "NVIDIA_INFERENCE_API_KEY") + : { status: 0, stdout: "", stderr: "" }; }, ); @@ -328,9 +269,9 @@ describe("onboard provider helpers", () => { ); }); - it("omits --credential from the update args when the env value is empty", () => { + it("omits --credential from the update args when the env value is empty", async () => { const commands: string[] = []; - const result = upsertProvider( + const result = await upsertProvider( "nvidia-prod", "openai", "NVIDIA_INFERENCE_API_KEY", @@ -338,7 +279,9 @@ describe("onboard provider helpers", () => { {}, (command) => { commands.push(command.join(" ")); - return { status: 0, stdout: "", stderr: "" }; + return command.includes("get") + ? providerMetadata("nvidia-prod", "openai", "NVIDIA_INFERENCE_API_KEY") + : { status: 0, stdout: "", stderr: "" }; }, ); @@ -352,24 +295,34 @@ describe("onboard provider helpers", () => { expect(commands[1]).toMatch(/OPENAI_BASE_URL=https:\/\/integrate\.api\.nvidia\.com\/v1/); }); - it("keeps --credential on the create path even when env is empty", () => { - // create cannot omit credentials — OpenShell rejects empty credential - // maps on creation. The caller is responsible for staging a value. + it("fails before create when the credential value is empty", async () => { const commands: string[] = []; - upsertProvider("fresh-provider", "generic", "FRESH_TOKEN", null, {}, (command) => { - commands.push(command.join(" ")); - if (command.includes("get")) return { status: 1, stdout: "", stderr: "" }; - return { status: 0, stdout: "", stderr: "" }; - }); + const result = await upsertProvider( + "fresh-provider", + "generic", + "FRESH_TOKEN", + null, + {}, + (command) => { + commands.push(command.join(" ")); + if (command.includes("get")) { + return { status: 1, stdout: "", stderr: "provider 'fresh-provider' not found" }; + } + return { status: 0, stdout: "", stderr: "" }; + }, + ); - expect(commands).toHaveLength(2); - expect(commands[1]).toMatch(/^provider create --name fresh-provider /); - expect(commands[1]).toMatch(/--credential FRESH_TOKEN/); + expect(result).toEqual({ + ok: false, + status: 1, + message: "Provider credential input is missing or conflicts with imported credentials.", + }); + expect(commands).toEqual(["provider get fresh-provider"]); }); - it("keeps --credential on the update path when a value is staged in env", () => { + it("keeps --credential on the update path when a value is staged in env", async () => { const commands: string[] = []; - upsertProvider( + await upsertProvider( "nvidia-prod", "openai", "NVIDIA_INFERENCE_API_KEY", @@ -377,7 +330,9 @@ describe("onboard provider helpers", () => { { NVIDIA_INFERENCE_API_KEY: "nvapi-staged" }, (command) => { commands.push(command.join(" ")); - return { status: 0, stdout: "", stderr: "" }; + return command.includes("get") + ? providerMetadata("nvidia-prod", "openai", "NVIDIA_INFERENCE_API_KEY") + : { status: 0, stdout: "", stderr: "" }; }, ); @@ -386,7 +341,7 @@ describe("onboard provider helpers", () => { expect(commands[1]).toMatch(/--credential NVIDIA_INFERENCE_API_KEY/); }); - it("stages non-nvapi NVIDIA_INFERENCE_API_KEY as hosted custom inference", () => { + it("stages non-nvapi NVIDIA_INFERENCE_API_KEY as hosted custom inference", async () => { withProviderEnv( { NVIDIA_INFERENCE_API_KEY: " repo-hosted-key ", @@ -405,7 +360,7 @@ describe("onboard provider helpers", () => { ); }); - it("does not synthesize hosted selection when authoritative resume disables staging", () => { + it("does not synthesize hosted selection when authoritative resume disables staging", async () => { withProviderEnv( { NVIDIA_INFERENCE_API_KEY: "repo-hosted-key", @@ -420,7 +375,7 @@ describe("onboard provider helpers", () => { ); }); - it("supports the NVIDIA QA non-interactive provider-model contract (#6869)", () => { + it("supports the NVIDIA QA non-interactive provider-model contract (#6869)", async () => { withProviderEnv( { NEMOCLAW_PROVIDER: "ollama", @@ -432,7 +387,7 @@ describe("onboard provider helpers", () => { ); }); - it("keeps NEMOCLAW_MODEL ahead of NEMOCLAW_PROVIDER_MODEL", () => { + it("keeps NEMOCLAW_MODEL ahead of NEMOCLAW_PROVIDER_MODEL", async () => { withProviderEnv( { NEMOCLAW_PROVIDER: "ollama", @@ -445,7 +400,7 @@ describe("onboard provider helpers", () => { ); }); - it("preserves NEMOCLAW_MODEL when the provider-model fallback is disabled", () => { + it("preserves NEMOCLAW_MODEL when the provider-model fallback is disabled", async () => { withProviderEnv( { NEMOCLAW_MODEL: "nvidia/nemotron-3-super-120b-a12b", @@ -459,13 +414,13 @@ describe("onboard provider helpers", () => { ); }); - it("omits NEMOCLAW_PROVIDER_MODEL when the provider-model fallback is disabled", () => { + it("omits NEMOCLAW_PROVIDER_MODEL when the provider-model fallback is disabled", async () => { withProviderEnv({ NEMOCLAW_PROVIDER_MODEL: "fallback-model" }, () => { expect(getNonInteractiveModel("openai", { allowProviderModelFallback: false })).toBeNull(); }); }); - it("stages Deep Agents NEMOCLAW_PROVIDER_KEY as hosted custom inference", () => { + it("stages Deep Agents NEMOCLAW_PROVIDER_KEY as hosted custom inference", async () => { withProviderEnv( { NEMOCLAW_AGENT: "langchain-deepagents-code", @@ -483,7 +438,7 @@ describe("onboard provider helpers", () => { ); }); - it("does not stage route-like Deep Agents NEMOCLAW_PROVIDER_KEY values as credentials", () => { + it("does not stage route-like Deep Agents NEMOCLAW_PROVIDER_KEY values as credentials", async () => { withProviderEnv( { NEMOCLAW_AGENT: "langchain-deepagents-code", @@ -553,7 +508,7 @@ describe("onboard provider helpers", () => { }, ); - it("keeps generic NEMOCLAW_PROVIDER_KEY from implying hosted custom inference", () => { + it("keeps generic NEMOCLAW_PROVIDER_KEY from implying hosted custom inference", async () => { withProviderEnv( { NEMOCLAW_PROVIDER_KEY: "repo-hosted-key", @@ -566,7 +521,7 @@ describe("onboard provider helpers", () => { ); }); - it("does not override an explicit hosted inference API preference", () => { + it("does not override an explicit hosted inference API preference", async () => { withProviderEnv( { NVIDIA_INFERENCE_API_KEY: "repo-hosted-key", @@ -580,7 +535,7 @@ describe("onboard provider helpers", () => { ); }); - it("keeps explicit cloud provider selection on the Build provider path", () => { + it("keeps explicit cloud provider selection on the Build provider path", async () => { withProviderEnv( { NVIDIA_INFERENCE_API_KEY: "repo-hosted-key", @@ -595,7 +550,7 @@ describe("onboard provider helpers", () => { ); }); - it("preserves explicit custom provider credentials when NVIDIA_INFERENCE_API_KEY is unrelated", () => { + it("preserves explicit custom provider credentials when NVIDIA_INFERENCE_API_KEY is unrelated", async () => { withProviderEnv( { COMPATIBLE_API_KEY: "custom-endpoint-key", @@ -611,16 +566,25 @@ describe("onboard provider helpers", () => { ); }); - it("returns redacted error details when create or update fails", () => { - const result = upsertProvider("bad-provider", "generic", "SOME_KEY", null, {}, (command) => { - if (command.includes("get")) return { status: 1, stdout: "", stderr: "" }; - return { status: 1, stdout: "", stderr: "gateway unreachable" }; - }); + it("returns redacted error details when create or update fails", async () => { + const result = await upsertProvider( + "bad-provider", + "generic", + "SOME_KEY", + null, + { SOME_KEY: "fake" }, + (command) => { + if (command.includes("get")) { + return { status: 1, stdout: "", stderr: "provider 'bad-provider' not found" }; + } + return { status: 1, stdout: "", stderr: "gateway unreachable" }; + }, + ); expect(result).toEqual({ ok: false, status: 1, message: "gateway unreachable" }); }); - it("rechecks sandbox identity after a provider probe and before its mutation (#9833)", () => { + it("rechecks sandbox identity after a provider probe and before its mutation (#9833)", async () => { const commands: string[] = []; const revalidationSteps = [ () => undefined, @@ -629,7 +593,7 @@ describe("onboard provider helpers", () => { }, ]; - expect(() => + await expect( upsertProvider( "alpha-discord-bridge", "generic", @@ -638,17 +602,21 @@ describe("onboard provider helpers", () => { { DISCORD_BOT_TOKEN: "secret" }, (command) => { commands.push(command.join(" ")); - return { status: 1, stdout: "", stderr: "not found" }; + return { + status: 1, + stdout: "", + stderr: "provider 'alpha-discord-bridge' not found", + }; }, { revalidateSandboxIdentity: () => revalidationSteps.shift()?.() }, ), - ).toThrow(/sandbox identity changed after provider probe/u); + ).rejects.toThrow(/sandbox identity changed after provider probe/u); expect(commands).toEqual(["provider get alpha-discord-bridge"]); }); - it("rejects an existing generic provider when an exact credential binding is required", () => { + it("rejects an existing generic provider when an exact credential binding is required", async () => { const commands: string[] = []; - const result = upsertProvider( + const result = await upsertProvider( "alpha-discord-bridge", "discord-hermes-static-v1", "DISCORD_BOT_TOKEN", @@ -677,15 +645,12 @@ describe("onboard provider helpers", () => { message: "Existing provider 'alpha-discord-bridge' does not match the required 'discord-hermes-static-v1' credential binding.", }); - expect(commands).toEqual([ - "provider get alpha-discord-bridge", - "provider get alpha-discord-bridge", - ]); + expect(commands).toEqual(["provider get alpha-discord-bridge"]); }); - it("updates an existing provider when its exact credential binding matches", () => { + it("updates an existing provider when its exact credential binding matches", async () => { const commands: string[] = []; - const result = upsertProvider( + const result = await upsertProvider( "alpha-discord-bridge", "discord-hermes-static-v1", "DISCORD_BOT_TOKEN", @@ -709,7 +674,6 @@ describe("onboard provider helpers", () => { expect(result).toEqual({ ok: true }); expect(commands).toEqual([ - "provider get alpha-discord-bridge", "provider get alpha-discord-bridge", "provider update alpha-discord-bridge --credential DISCORD_BOT_TOKEN", ]); diff --git a/src/lib/onboard/providers.ts b/src/lib/onboard/providers.ts index 14aed04e187..12400167482 100644 --- a/src/lib/onboard/providers.ts +++ b/src/lib/onboard/providers.ts @@ -16,6 +16,7 @@ const { const openrouter = require("../inference/openrouter"); const { isSafeModelId } = require("../validation"); const { compactText } = require("../core/url-utils"); +const { createCliOpenShellProviderAdapter } = require("../adapters/openshell/provider-adapter-cli"); const { LLAMA_CPP_CREDENTIAL_ENV, LLAMA_CPP_HOST_OPENAI_BASE_URL, @@ -359,40 +360,6 @@ function getRequestedModelHint(nonInteractive, allowHostedInferenceStaging = tru // Functions that call runOpenshell accept it as the last parameter // to avoid a circular dependency with onboard.ts. -/** - * Build the argument array for an `openshell provider create` or `update` command. - * @param {"create"|"update"} action - Whether to create or update. - * @param {string} name - Provider name. - * @param {string} type - Provider type (for example, "openai" or "nemoclaw-mcp-v1"). - * @param {string} credentialEnv - Credential environment variable name. - * @param {string|null} baseUrl - Optional base URL for API-compatible endpoints. - * @param {{ includeCredential?: boolean, credentialEnvs?: string[] }} [opts] - When `includeCredential` is - * false, the `--credential` flag is omitted from the args. Used on the - * `provider update` path when the host env does not carry the credential and - * the gateway already holds it (no rotation needed). OpenShell's CLI rejects - * `--credential KEY` when the local env var is empty, so passing the flag - * would fail before reaching the gateway. - * @returns {string[]} Argument array for runOpenshell(). - */ -function buildProviderArgs(action, name, type, credentialEnv, baseUrl, opts = {}) { - const { includeCredential = true, credentialEnvs } = opts; - const args = - action === "create" - ? ["provider", "create", "--name", name, "--type", type] - : ["provider", "update", name]; - if (includeCredential) { - for (const envKey of credentialEnvs ?? [credentialEnv]) { - args.push("--credential", envKey); - } - } - if (baseUrl && type === "openai") { - args.push("--config", `OPENAI_BASE_URL=${baseUrl}`); - } else if (baseUrl && type === "anthropic") { - args.push("--config", `ANTHROPIC_BASE_URL=${baseUrl}`); - } - return args; -} - /** * Check whether an OpenShell provider exists in the gateway. * @@ -403,12 +370,15 @@ function buildProviderArgs(action, name, type, credentialEnv, baseUrl, opts = {} * @param {Function} _runOpenshell - Injected runOpenshell from onboard.ts. * @returns {boolean} True if the provider exists in the gateway. */ -function providerExistsInGateway(name, _runOpenshell) { - const result = _runOpenshell(["provider", "get", name], { - ignoreError: true, - stdio: ["ignore", "ignore", "ignore"], +async function providerExistsInGateway(name, runOpenshell) { + const adapter = createCliOpenShellProviderAdapter({ run: runOpenshell }); + const result = await adapter.getProvider({ + target: { kind: "selected" }, + providerName: name, }); - return result.status === 0; + if (result.ok) return true; + if (result.error.kind === "command" && result.error.reason === "not_found") return false; + throw new Error(result.error.message); } /** @@ -448,13 +418,40 @@ function identityCheckedRunner(runOpenshell, revalidateSandboxIdentity, operatio * @param {{replaceExisting?: boolean, knownExists?: boolean, allowedSandboxes?: readonly string[], requireExactBinding?: boolean, allowExtendedCredentialKeys?: boolean, credentialEnvs?: string[], revalidateSandboxIdentity?: (operation: string) => void}} options - Optional replacement controls. * @returns {{ ok: boolean, status?: number, message?: string, reason?: string }} */ -function upsertProvider(name, type, credentialEnv, baseUrl, env, _runOpenshell, options = {}) { - const runOpenshell = identityCheckedRunner( - _runOpenshell, - options.revalidateSandboxIdentity, - `inspect or change provider ${JSON.stringify(name)}`, - ); - const exists = options.knownExists ?? providerExistsInGateway(name, runOpenshell); +async function upsertProvider( + name, + type, + credentialEnv, + baseUrl, + env, + _runOpenshell, + options = {}, +) { + const operation = `inspect or change provider ${JSON.stringify(name)}`; + const revalidate = () => options.revalidateSandboxIdentity?.(operation); + const adapter = createCliOpenShellProviderAdapter({ run: _runOpenshell }); + let observed = null; + if (options.knownExists === undefined || options.requireExactBinding) { + revalidate(); + observed = await adapter.getProvider({ + target: { kind: "selected" }, + providerName: name, + }); + } + const exists = + options.knownExists ?? + (observed?.ok === true + ? true + : observed?.error?.kind === "command" && observed.error.reason === "not_found" + ? false + : null); + if (exists === null) { + return { + ok: false, + status: 1, + message: observed?.error?.message || `Could not inspect provider '${name}'.`, + }; + } const credentialEnvs = options.credentialEnvs ?? [credentialEnv]; const bindingMatches = (metadata) => options.allowExtendedCredentialKeys @@ -472,7 +469,7 @@ function upsertProvider(name, type, credentialEnv, baseUrl, env, _runOpenshell, exists && options.requireExactBinding && !options.replaceExisting && - !bindingMatches(readGatewayProviderMetadata(name, runOpenshell)) + !bindingMatches(observed?.ok ? observed.value : null) ) { return { ok: false, @@ -483,6 +480,11 @@ function upsertProvider(name, type, credentialEnv, baseUrl, env, _runOpenshell, } if (exists && options.replaceExisting) { const { deleteProviderWithRecovery } = require("./sandbox-provider-cleanup"); + const runOpenshell = identityCheckedRunner( + _runOpenshell, + options.revalidateSandboxIdentity, + operation, + ); const r = deleteProviderWithRecovery(name, { runOpenshell, allowedSandboxes: options.allowedSandboxes, @@ -520,19 +522,37 @@ function upsertProvider(name, type, credentialEnv, baseUrl, env, _runOpenshell, }; } const submittedCredentialEnvs = action === "create" ? credentialEnvs : availableCredentialEnvs; - const includeCredential = submittedCredentialEnvs.length > 0; - const args = buildProviderArgs(action, name, type, credentialEnv, baseUrl, { - includeCredential, - credentialEnvs: submittedCredentialEnvs, + const credentials = submittedCredentialEnvs.flatMap((envKey) => { + const value = env[envKey]; + return typeof value === "string" && value.length > 0 ? [{ name: envKey, value }] : []; }); - const runOpts = { ignoreError: true, env, stdio: ["ignore", "pipe", "pipe"] }; - const result = runOpenshell(args, runOpts); - if (result.status !== 0) { - const output = - compactText(redact(`${result.stderr || ""}`)) || - compactText(redact(`${result.stdout || ""}`)) || - `Failed to ${action} provider '${name}'.`; - return { ok: false, status: result.status || 1, message: output }; + const config = baseUrl + ? [ + { + key: type === "anthropic" ? "ANTHROPIC_BASE_URL" : "OPENAI_BASE_URL", + value: baseUrl, + }, + ] + : []; + revalidate(); + const result = + action === "create" + ? await adapter.createProvider({ + target: { kind: "selected" }, + name, + type, + credentials, + config, + fromExisting: false, + }) + : await adapter.updateProvider({ + target: { kind: "selected" }, + providerName: name, + credentials, + config, + }); + if (!result.ok) { + return { ok: false, status: 1, message: result.error.message }; } return { ok: true }; } @@ -563,7 +583,6 @@ module.exports = { getRequestedProviderHint, getRequestedModelHint, isProviderKeyCredentialCandidate, - buildProviderArgs, upsertProvider, providerExistsInGateway, readGatewayProviderMetadata, diff --git a/src/lib/onboard/resume-provider-recovery.ts b/src/lib/onboard/resume-provider-recovery.ts index 10cb336407b..50e6f63e142 100644 --- a/src/lib/onboard/resume-provider-recovery.ts +++ b/src/lib/onboard/resume-provider-recovery.ts @@ -25,7 +25,7 @@ export type ResumeProviderRecoveryDeps = { remoteProviderConfig: Record; defaultRouteCredentialEnv: string; isRoutedInferenceProvider: (provider: string) => boolean; - providerExistsInGateway: (name: string) => boolean; + providerExistsInGateway: (name: string) => boolean | Promise; hydrateCredentialEnv: (envName: string) => string | null; getProviderLabel: (key: string) => string; isNonInteractive: () => boolean; @@ -96,7 +96,7 @@ export async function ensureResumeProviderReady( if (!provider || (!config && !deps.isRoutedInferenceProvider(provider))) { return { forceInferenceSetup: false, credentialEnv: credentialEnv ?? null }; } - if (deps.providerExistsInGateway(provider)) { + if (await deps.providerExistsInGateway(provider)) { return { forceInferenceSetup: false, credentialEnv: credentialEnv ?? null }; } diff --git a/src/lib/onboard/routed-inference.test.ts b/src/lib/onboard/routed-inference.test.ts index 63353540b4d..7ed0ae0f5d3 100644 --- a/src/lib/onboard/routed-inference.test.ts +++ b/src/lib/onboard/routed-inference.test.ts @@ -23,31 +23,31 @@ import { } from "./routed-inference"; describe("normalizeRoutedEndpointUrl (#4564)", () => { - it("rewrites localhost to the sandbox-facing host alias", () => { + it("rewrites localhost to the sandbox-facing host alias", async () => { expect(normalizeRoutedEndpointUrl("http://localhost:4000/v1")).toBe( "http://host.openshell.internal:4000/v1", ); }); - it("rewrites 127.0.0.1 to the host alias", () => { + it("rewrites 127.0.0.1 to the host alias", async () => { expect(normalizeRoutedEndpointUrl("http://127.0.0.1:4000/v1")).toBe( "http://host.openshell.internal:4000/v1", ); }); - it("omits the colon when the endpoint has no explicit port and preserves query/hash", () => { + it("omits the colon when the endpoint has no explicit port and preserves query/hash", async () => { expect(normalizeRoutedEndpointUrl("http://localhost/v1?x=1#frag")).toBe( "http://host.openshell.internal/v1?x=1#frag", ); }); - it("leaves an already-aliased endpoint untouched", () => { + it("leaves an already-aliased endpoint untouched", async () => { expect(normalizeRoutedEndpointUrl("http://host.openshell.internal:4000/v1")).toBe( "http://host.openshell.internal:4000/v1", ); }); - it("falls back to the blueprint endpoint when none is recorded, then normalizes it", () => { + it("falls back to the blueprint endpoint when none is recorded, then normalizes it", async () => { // The mocked loadBlueprintProfile returns http://localhost:4000/v1. expect(normalizeRoutedEndpointUrl(null)).toBe("http://host.openshell.internal:4000/v1"); expect(normalizeRoutedEndpointUrl("")).toBe("http://host.openshell.internal:4000/v1"); @@ -55,12 +55,12 @@ describe("normalizeRoutedEndpointUrl (#4564)", () => { }); describe("resolveRoutedCredentialEnv (#4564)", () => { - it("prefers an explicitly recorded credential env", () => { + it("prefers an explicitly recorded credential env", async () => { const loadProfile = vi.fn(() => ({ credential_env: "CUSTOM_KEY" })) as never; expect(resolveRoutedCredentialEnv("SESSION_KEY", loadProfile)).toBe("SESSION_KEY"); }); - it("falls back to the routed profile credential env before the NVIDIA default", () => { + it("falls back to the routed profile credential env before the NVIDIA default", async () => { const loadProfile = vi.fn(() => ({ credential_env: "CUSTOM_KEY", router: { credential_env: "ROUTER_KEY" }, @@ -69,23 +69,23 @@ describe("resolveRoutedCredentialEnv (#4564)", () => { expect(resolveRoutedCredentialEnv(null, loadProfile)).toBe("ROUTER_KEY"); }); - it("falls back to the profile-level credential env when the router has none", () => { + it("falls back to the profile-level credential env when the router has none", async () => { const loadProfile = vi.fn(() => ({ credential_env: "CUSTOM_KEY" })) as never; expect(resolveRoutedCredentialEnv(null, loadProfile)).toBe("CUSTOM_KEY"); }); - it("uses the NVIDIA default when no profile credential env is set", () => { + it("uses the NVIDIA default when no profile credential env is set", async () => { const loadProfile = vi.fn(() => ({ endpoint: "http://localhost:4000/v1" })) as never; expect(resolveRoutedCredentialEnv(null, loadProfile)).toBe("NVIDIA_INFERENCE_API_KEY"); }); }); describe("upsertRoutedProvider (#4564)", () => { - it("upserts the provider with the normalized host alias base URL", () => { + it("upserts the provider with the normalized host alias base URL", async () => { const upsertProvider = vi.fn(() => ({ ok: true })); const hydrateCredentialEnv = vi.fn(() => "nvapi-secret"); - const result = upsertRoutedProvider( + const result = await upsertRoutedProvider( "nvidia-router", "http://localhost:4000/v1", "NVIDIA_INFERENCE_API_KEY", @@ -107,11 +107,11 @@ describe("upsertRoutedProvider (#4564)", () => { ); }); - it("defaults the credential env and omits an empty credential from the env block", () => { + it("defaults the credential env and omits an empty credential from the env block", async () => { const upsertProvider = vi.fn(() => ({ ok: true })); const hydrateCredentialEnv = vi.fn(() => undefined); - const result = upsertRoutedProvider("nvidia-router", "http://localhost:4000/v1", null, { + const result = await upsertRoutedProvider("nvidia-router", "http://localhost:4000/v1", null, { upsertProvider, hydrateCredentialEnv, }); @@ -126,11 +126,11 @@ describe("upsertRoutedProvider (#4564)", () => { ); }); - it("propagates a failed upsert result", () => { + it("propagates a failed upsert result", async () => { const upsertProvider = vi.fn(() => ({ ok: false, message: "boom", status: 3 })); const hydrateCredentialEnv = vi.fn(() => "nvapi-secret"); - const result = upsertRoutedProvider( + const result = await upsertRoutedProvider( "nvidia-router", "http://localhost:4000/v1", "NVIDIA_INFERENCE_API_KEY", diff --git a/src/lib/onboard/routed-inference.ts b/src/lib/onboard/routed-inference.ts index c9e866234ad..38272922b69 100644 --- a/src/lib/onboard/routed-inference.ts +++ b/src/lib/onboard/routed-inference.ts @@ -30,7 +30,7 @@ export type RoutedProviderDeps = { credentialEnv: string, baseUrl: string | null, env: NodeJS.ProcessEnv, - ) => UpsertProviderResult; + ) => UpsertProviderResult | Promise; hydrateCredentialEnv: (credentialEnv: string) => string | null | undefined; }; @@ -99,17 +99,17 @@ export function resolveRoutedCredentialEnv( * Upsert the routed provider into the gateway with a normalized, sandbox-facing * base URL. Used by both fresh routed setup and resume repair. */ -export function upsertRoutedProvider( +export async function upsertRoutedProvider( provider: string, endpointUrl: string | null, credentialEnv: string | null, deps: RoutedProviderDeps, -): RoutedProviderUpsert { +): Promise { const resolvedCredentialEnv = resolveRoutedCredentialEnv(credentialEnv); const normalizedEndpoint = normalizeRoutedEndpointUrl(endpointUrl); const credentialValue = deps.hydrateCredentialEnv(resolvedCredentialEnv); const env = credentialValue ? { [resolvedCredentialEnv]: credentialValue } : {}; - const result = deps.upsertProvider( + const result = await deps.upsertProvider( provider, "openai", resolvedCredentialEnv, diff --git a/src/lib/onboard/sandbox-create-intent-resolution.ts b/src/lib/onboard/sandbox-create-intent-resolution.ts index f08f3f4f8a3..3a4c2580986 100644 --- a/src/lib/onboard/sandbox-create-intent-resolution.ts +++ b/src/lib/onboard/sandbox-create-intent-resolution.ts @@ -179,16 +179,30 @@ export function createSandboxCreateIntentResolver< readonly hermesPortable: boolean; readonly requestedExtraProviders?: readonly string[]; readonly resolvedIntent?: SandboxCreateIntent; - readonly planOrdinaryExtraProviders: () => { - readonly extraProviders: readonly string[]; - readonly staleExtraProviders: readonly string[]; - }; + readonly planOrdinaryExtraProviders: () => + | { + readonly extraProviders: readonly string[]; + readonly staleExtraProviders: readonly string[]; + } + | Promise<{ + readonly extraProviders: readonly string[]; + readonly staleExtraProviders: readonly string[]; + }>; }, ) { + const ordinaryExtraProviderPlan = + !options.hermesPortable && !options.requestedExtraProviders + ? await options.planOrdinaryExtraProviders() + : null; const extraProviderPlan = selectHermesPortableExtraProviderPlan( options.hermesPortable, options.requestedExtraProviders, - options.planOrdinaryExtraProviders, + () => { + if (!ordinaryExtraProviderPlan) { + throw new Error("Ordinary extra-provider plan is unavailable."); + } + return ordinaryExtraProviderPlan; + }, ); const intent = options.resolvedIntent ?? diff --git a/src/lib/onboard/sandbox-create/orchestration.ts b/src/lib/onboard/sandbox-create/orchestration.ts index 22cd04e9c62..152cb520f78 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -1822,9 +1822,14 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche // Check whether messaging providers are missing from the gateway. Only // force recreation when at least one required provider doesn't exist yet — // this avoids destroying sandboxes already created with provider attachments. + const providerExistence = await Promise.all( + messagingTokenDefs.map(async ({ name, token }) => ({ + token, + exists: token ? await providerExistsInGateway(name) : true, + })), + ); const needsProviderMigration = - hasMessagingTokens && - messagingTokenDefs.some(({ name, token }) => token && !providerExistsInGateway(name)); + hasMessagingTokens && providerExistence.some(({ token, exists }) => token && !exists); const selectionDrift = isManagedDcodeAgent ? readManagedDcodeCreateSelectionDrift( { sandboxName, provider, model, preferredInferenceApi, createIntent }, @@ -2990,12 +2995,12 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche cleanupInitialCreateSource(); } } - return runWithPostCreateRecovery( - () => { + return runAsyncWithPostCreateRecovery( + async () => { managedStateVolumeLifecycle.commit(); if ("complete" in recreateRuntime) recreateRuntime.complete(); if (agentCreateInput.hermesPortableLifecycle) return sandboxName; - return completeOrdinaryOnboardSandboxCreation( + return await completeOrdinaryOnboardSandboxCreation( { sandboxName, sandboxWasLiveDefault, diff --git a/src/lib/onboard/sandbox-messaging-preflight.ts b/src/lib/onboard/sandbox-messaging-preflight.ts index 3dc60d7dde2..46178da4a91 100644 --- a/src/lib/onboard/sandbox-messaging-preflight.ts +++ b/src/lib/onboard/sandbox-messaging-preflight.ts @@ -30,8 +30,12 @@ export interface SandboxMessagingPreflightDeps { resolveDisabledChannels(sandboxName: string): string[]; gatewayName(): string; registry: MessagingConflictGuardDeps["registry"]; - providerExistsInGateway(name: string): boolean; - providerMatchesGatewayCredential(name: string, type: string, credentialEnv: string): boolean; + providerExistsInGateway(name: string): boolean | Promise; + providerMatchesGatewayCredential( + name: string, + type: string, + credentialEnv: string, + ): boolean | Promise; isNonInteractive(): boolean; promptYesNoOrDefault( message: string, @@ -54,7 +58,7 @@ export interface SandboxMessagingPreflightDeps { getMessagingChannelForEnvKey(envKey: string): string | null; prepareCreateSandboxMessaging?: ( input: CreateSandboxMessagingPrepInput, - ) => CreateSandboxMessagingPrepResult; + ) => CreateSandboxMessagingPrepResult | Promise; enforceMessagingChannelConflicts?: (deps: MessagingConflictGuardDeps) => Promise; } @@ -69,23 +73,25 @@ export async function prepareSandboxMessagingPreflight( const disabledChannels = deps.resolveDisabledChannels(input.sandboxName); await checkMessagingPlanConflicts(input.sandboxName, disabledChannels, deps); - const result = (deps.prepareCreateSandboxMessaging ?? defaultPrepareCreateSandboxMessaging)({ - sandboxName: input.sandboxName, - agentName: input.agentName, - requireExactProviderBinding: input.requireExactProviderBinding, - channels: input.channels, - enabledChannels: input.enabledChannels, - disabledChannels, - webSearchConfig: input.webSearchConfig, - env: input.env, - getValidatedMessagingTokenByEnvKey: deps.getValidatedMessagingTokenByEnvKey, - getCredential: deps.getCredential, - normalizeCredentialValue: deps.normalizeCredentialValue, - registerExtraPlaceholderProviders: deps.registerExtraPlaceholderProviders, - getMessagingChannelForEnvKey: deps.getMessagingChannelForEnvKey, - providerExistsInGateway: deps.providerExistsInGateway, - providerMatchesGatewayCredential: deps.providerMatchesGatewayCredential, - }); + const result = await (deps.prepareCreateSandboxMessaging ?? defaultPrepareCreateSandboxMessaging)( + { + sandboxName: input.sandboxName, + agentName: input.agentName, + requireExactProviderBinding: input.requireExactProviderBinding, + channels: input.channels, + enabledChannels: input.enabledChannels, + disabledChannels, + webSearchConfig: input.webSearchConfig, + env: input.env, + getValidatedMessagingTokenByEnvKey: deps.getValidatedMessagingTokenByEnvKey, + getCredential: deps.getCredential, + normalizeCredentialValue: deps.normalizeCredentialValue, + registerExtraPlaceholderProviders: deps.registerExtraPlaceholderProviders, + getMessagingChannelForEnvKey: deps.getMessagingChannelForEnvKey, + providerExistsInGateway: deps.providerExistsInGateway, + providerMatchesGatewayCredential: deps.providerMatchesGatewayCredential, + }, + ); // Fail before the caller can act on this intent: onboard may delete and // recreate the sandbox, and a selected channel that resolved to nothing would diff --git a/src/lib/onboard/setup-inference-gateway-scope.test.ts b/src/lib/onboard/setup-inference-gateway-scope.test.ts index 25908ab6d8d..d4c12862024 100644 --- a/src/lib/onboard/setup-inference-gateway-scope.test.ts +++ b/src/lib/onboard/setup-inference-gateway-scope.test.ts @@ -137,7 +137,7 @@ describe("gateway-scoped onboarding OpenShell commands", () => { ); }); - it("registers the OpenAI profile before a routed resume provider mutation (#10155)", () => { + it("registers the OpenAI profile before a routed resume provider mutation (#10155)", async () => { const events: string[] = []; const results = [ { @@ -177,7 +177,7 @@ describe("gateway-scoped onboarding OpenShell commands", () => { }); expect( - reupsertRoutedProvider( + await reupsertRoutedProvider( GATEWAY, "nvidia-router", "http://host.openshell.internal:4000/v1", @@ -206,7 +206,7 @@ describe("gateway-scoped onboarding OpenShell commands", () => { ); }); - it("blocks a routed resume provider mutation when OpenAI profile import fails (#10155)", () => { + it("blocks a routed resume provider mutation when OpenAI profile import fails (#10155)", async () => { const sensitiveDiagnostic = "unauthorized nvapi-TEST-NOT-A-REAL-VALUE"; const results = [ { @@ -229,14 +229,14 @@ describe("gateway-scoped onboarding OpenShell commands", () => { }, }); - expect(() => + await expect( reupsertRoutedProvider( GATEWAY, "nvidia-router", "http://host.openshell.internal:4000/v1", "NVIDIA_INFERENCE_API_KEY", ), - ).toThrow("exit 1"); + ).rejects.toThrow("exit 1"); expect(upsert).not.toHaveBeenCalled(); expect(run).toHaveBeenCalledTimes(2); diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index 3a846842771..cb1449369ee 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -295,13 +295,13 @@ export function createRoutedResumeProviderUpsert(deps: { error?: CommonDeps["error"]; exitProcess?: CommonDeps["exitProcess"]; }) { - return ( + return async ( gatewayName: string, provider: string, endpointUrl: string | null, credentialEnv: string | null, ) => { - const result = upsertRoutedInferenceProvider(provider, endpointUrl, credentialEnv, { + const result = await upsertRoutedInferenceProvider(provider, endpointUrl, credentialEnv, { upsertProvider: bindOpenAiProviderProfile( bindGatewayUpsertProvider(deps.upsertProvider, gatewayName), deps.runGatewayOpenshell, diff --git a/src/lib/verify-deployment.ts b/src/lib/verify-deployment.ts index 25466474950..c9e7c537e8a 100644 --- a/src/lib/verify-deployment.ts +++ b/src/lib/verify-deployment.ts @@ -102,7 +102,7 @@ export interface VerifyDeploymentDeps { getMessagingChannels: (name: string) => string[]; /** Check if a messaging bridge is polling (provider exists in gateway). */ - providerExistsInGateway: (providerName: string) => boolean; + providerExistsInGateway: (providerName: string) => boolean | Promise; /** * Probe the in-sandbox agent config to learn which channels the runtime @@ -402,10 +402,10 @@ export interface MessagingBridgeStatus { * the channel?) so the "No channels found" dashboard symptom from #4156 * surfaces here as a warning. */ -function verifyMessagingBridges( +async function verifyMessagingBridges( sandboxName: string, deps: VerifyDeploymentDeps, -): MessagingBridgeStatus { +): Promise { const channels = deps.getMessagingChannels(sandboxName); if (channels.length === 0) { return { @@ -424,7 +424,10 @@ function verifyMessagingBridges( continue; } const expectedProviders = providerNames.length > 0 ? providerNames : [channel]; - if (!expectedProviders.every((providerName) => deps.providerExistsInGateway(providerName))) { + const providersExist = await Promise.all( + expectedProviders.map((providerName) => deps.providerExistsInGateway(providerName)), + ); + if (!providersExist.every(Boolean)) { missingProviders.push(channel); } } @@ -643,7 +646,7 @@ export async function verifyDeployment( // 5. Messaging bridges (providers attached AND runtime config exposes // each configured channel — #4156). - const messaging = verifyMessagingBridges(sandboxName, deps); + const messaging = await verifyMessagingBridges(sandboxName, deps); if (!messaging.healthy) { diagnostics.push({ link: "messaging", diff --git a/test/agents/hermes/hermes-discord-credential-binding.test.ts b/test/agents/hermes/hermes-discord-credential-binding.test.ts index c081ea9c91a..6b4ac6ea323 100644 --- a/test/agents/hermes/hermes-discord-credential-binding.test.ts +++ b/test/agents/hermes/hermes-discord-credential-binding.test.ts @@ -15,7 +15,7 @@ const SANDBOX_NAME = "hermes-discord"; const PROVIDER_NAME = `${SANDBOX_NAME}-discord-bridge`; const PROVIDER_TYPE = "discord-hermes-static-v1"; -function prepareDiscord( +async function prepareDiscord( token: string | null, providerMatchesGatewayCredential: () => boolean = () => false, disabled = false, @@ -41,8 +41,8 @@ function prepareDiscord( } describe("Hermes Discord credential endpoint binding", () => { - it("creates the Discord provider from an endpointless profile", () => { - const result = prepareDiscord("test-discord-token"); + it("creates the Discord provider from an endpointless profile", async () => { + const result = await prepareDiscord("test-discord-token"); expect(result.messagingTokenDefs).toEqual([ { @@ -69,9 +69,9 @@ describe("Hermes Discord credential endpoint binding", () => { it.each([ { state: "active", disabled: false }, { state: "stopped", disabled: true }, - ])("does not reuse an untyped provider for a $state channel", ({ disabled }) => { + ])("does not reuse an untyped provider for a $state channel", async ({ disabled }) => { const providerMatches = vi.fn(() => false); - const result = prepareDiscord(null, providerMatches, disabled); + const result = await prepareDiscord(null, providerMatches, disabled); expect(result.reusableMessagingProviders).toEqual([]); expect(result.reusableMessagingChannels).toEqual([]); @@ -80,9 +80,9 @@ describe("Hermes Discord credential endpoint binding", () => { it.each([null, "test-discord-token"])( "retains the exact Discord provider for a stopped channel with source token %s (#9773)", - (token) => { + async (token) => { const providerMatches = vi.fn(() => true); - const result = prepareDiscord(token, providerMatches, true); + const result = await prepareDiscord(token, providerMatches, true); expect(result.messagingTokenDefs).toEqual([]); expect(result.reusableMessagingProviders).toEqual([PROVIDER_NAME]); From 701c9213ca9ccbdf02ac2fad6de7d1e249eb4960 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 8 Sep 2026 14:39:48 -0700 Subject: [PATCH 02/10] fix: complete async onboarding provider consumers Signed-off-by: Rebecca Sliter <571084+rsliter@users.noreply.github.com> --- .../sandbox/rebuild-credential-preflight.ts | 22 +++---- .../sandbox/rebuild-dcode-orchestrator.ts | 2 +- .../rebuild-local-provider-recreate.test.ts | 6 +- .../actions/sandbox/rebuild-target-runtime.ts | 4 +- src/lib/hermes-provider-auth.test.ts | 49 ++++++++++------ src/lib/hermes-provider-auth.ts | 49 ++++++++-------- src/lib/hermes-tool-gateway-broker.ts | 4 +- src/lib/onboard/bedrock-runtime.test.ts | 2 +- src/lib/onboard/bedrock-runtime.ts | 11 +--- ...tra-provider-reconciliation-probes.test.ts | 2 +- .../compatible-endpoint-gateway-route.test.ts | 6 +- .../inference-providers/hermes.test.ts | 8 +-- src/lib/onboard/inference-providers/hermes.ts | 2 +- .../inference-providers/ollama-local.test.ts | 11 ++-- .../remote-openai-surface.test.ts | 6 +- src/lib/onboard/inference-providers/types.ts | 6 +- .../inference-providers/vllm-local.test.ts | 8 +-- src/lib/onboard/openrouter-runtime.ts | 11 +--- src/lib/onboard/providers.test.ts | 33 ++++++++++- src/lib/onboard/providers.ts | 4 +- src/lib/onboard/routed-inference.test.ts | 31 +++++++++- .../setup-inference-gateway-scope.test.ts | 15 +++-- .../setup-inference-route-containment.test.ts | 10 ++-- src/lib/onboard/setup-inference.test.ts | 26 ++++----- src/lib/onboard/setup-inference.ts | 6 +- test/credentials/credential-exposure.test.ts | 47 ++++++++------- ...rd-build-recreate-credential-reuse.test.ts | 12 ++++ ...board-host-local-inference-routing.test.ts | 2 +- .../onboard-inference-failure-paths.test.ts | 32 +++++------ .../onboard-inference-gateway-scope.test.ts | 2 +- .../onboard-inference-smoke.test.ts | 8 ++- .../onboard-openrouter-inference.test.ts | 2 +- test/onboarding/onboard-selection.test.ts | 6 +- test/support/setup-inference-test-harness.ts | 57 +++++++++++++++++-- 34 files changed, 312 insertions(+), 190 deletions(-) diff --git a/src/lib/actions/sandbox/rebuild-credential-preflight.ts b/src/lib/actions/sandbox/rebuild-credential-preflight.ts index 0f96ca1a3b7..d3dcf3371cb 100644 --- a/src/lib/actions/sandbox/rebuild-credential-preflight.ts +++ b/src/lib/actions/sandbox/rebuild-credential-preflight.ts @@ -16,16 +16,16 @@ const hermesProviderAuth = require("../../hermes-provider-auth") as { HERMES_PROVIDER_NAME: string; HERMES_INFERENCE_CREDENTIAL_ENV: string; HERMES_NOUS_API_KEY_CREDENTIAL_ENV: string; - inspectHermesProviderBinding: (runOpenshellFn: typeof runOpenshell) => { + inspectHermesProviderBinding: (runOpenshellFn: typeof runOpenshell) => Promise<{ exists: boolean; credentialKeys: string[] | null; - }; + }>; registerHermesInferenceProvider: ( apiKey: string, runOpenshellFn: typeof runOpenshell, credentialEnv?: string, baseUrl?: string, - ) => void; + ) => Promise; }; export type RebuildBail = (message: string, code?: number) => never; @@ -62,11 +62,11 @@ function nonEmptyString(value: unknown): string | null { return normalized || null; } -function preflightHermesProviderCredentials( +async function preflightHermesProviderCredentials( persistedAuthMethod: unknown, credentialEnv: string | null, log: RebuildLog, -): boolean { +): Promise { const authMethod = normalizeHermesRebuildAuthMethod(persistedAuthMethod) || (credentialEnv === hermesProviderAuth.HERMES_NOUS_API_KEY_CREDENTIAL_ENV ? "api_key" : null); @@ -74,7 +74,7 @@ function preflightHermesProviderCredentials( authMethod === "api_key" ? hermesProviderAuth.HERMES_NOUS_API_KEY_CREDENTIAL_ENV : hermesProviderAuth.HERMES_INFERENCE_CREDENTIAL_ENV; - const binding = hermesProviderAuth.inspectHermesProviderBinding(runOpenshell); + const binding = await hermesProviderAuth.inspectHermesProviderBinding(runOpenshell); if (binding.exists) { const matches = @@ -107,12 +107,12 @@ function preflightHermesProviderCredentials( console.log( " Hermes Provider is not registered in OpenShell; registering it from the configured exported API-key environment variable before rebuild.", ); - hermesProviderAuth.registerHermesInferenceProvider( + await hermesProviderAuth.registerHermesInferenceProvider( envKey, runOpenshell, hermesProviderAuth.HERMES_NOUS_API_KEY_CREDENTIAL_ENV, ); - const registered = hermesProviderAuth.inspectHermesProviderBinding(runOpenshell); + const registered = await hermesProviderAuth.inspectHermesProviderBinding(runOpenshell); return ( registered.credentialKeys?.length === 1 && registered.credentialKeys[0] === hermesProviderAuth.HERMES_NOUS_API_KEY_CREDENTIAL_ENV @@ -146,17 +146,17 @@ function preflightHermesProviderCredentials( return false; } -export function preflightRebuildCredentials( +export async function preflightRebuildCredentials( sb: RebuildSandboxEntry, log: RebuildLog, bail: RebuildBail, options: RebuildCredentialPreflightOptions = {}, -): boolean { +): Promise { const rebuildCredentialEnv = getRebuildCredentialEnvFromRegistry(sb.provider, sb.credentialEnv); const rebuildProvider = sb.provider; if (rebuildProvider === hermesProviderAuth.HERMES_PROVIDER_NAME) { - if (!preflightHermesProviderCredentials(sb.hermesAuthMethod, rebuildCredentialEnv, log)) { + if (!(await preflightHermesProviderCredentials(sb.hermesAuthMethod, rebuildCredentialEnv, log))) { bail("Missing Hermes Provider credentials"); return false; } diff --git a/src/lib/actions/sandbox/rebuild-dcode-orchestrator.ts b/src/lib/actions/sandbox/rebuild-dcode-orchestrator.ts index 6dbc3398991..2756096aaa4 100644 --- a/src/lib/actions/sandbox/rebuild-dcode-orchestrator.ts +++ b/src/lib/actions/sandbox/rebuild-dcode-orchestrator.ts @@ -30,7 +30,7 @@ type DcodeRebuildOrchestratorDeps = { entry: RebuildSandboxEntry, log: (message: string) => void, bail: DcodeRebuildPreflightBail, - ): boolean; + ): boolean | Promise; ensureAgentBaseImage( agentName: string | null, bail: DcodeRebuildPreflightBail, diff --git a/src/lib/actions/sandbox/rebuild-local-provider-recreate.test.ts b/src/lib/actions/sandbox/rebuild-local-provider-recreate.test.ts index e040513e0cd..c93a5fb9186 100644 --- a/src/lib/actions/sandbox/rebuild-local-provider-recreate.test.ts +++ b/src/lib/actions/sandbox/rebuild-local-provider-recreate.test.ts @@ -34,19 +34,19 @@ const onboardProviders = requireDist("../../onboard/providers.js") as { baseUrl: string | null, env: NodeJS.ProcessEnv, runOpenshell: typeof openshellRuntime.runOpenshell, - ): { ok: boolean; status?: number; message?: string }; + ): Promise<{ ok: boolean; status?: number; message?: string }>; }; type SetupResult = { done: true; result: unknown } | { done: false }; -function upsertLocalProvider( +async function upsertLocalProvider( name: string, type: string, credentialEnv: string, baseUrl: string | null, env: NodeJS.ProcessEnv = {}, ) { - return onboardProviders.upsertProvider( + return await onboardProviders.upsertProvider( name, type, credentialEnv, diff --git a/src/lib/actions/sandbox/rebuild-target-runtime.ts b/src/lib/actions/sandbox/rebuild-target-runtime.ts index 1e706a55ec1..0bbbf94d334 100644 --- a/src/lib/actions/sandbox/rebuild-target-runtime.ts +++ b/src/lib/actions/sandbox/rebuild-target-runtime.ts @@ -251,7 +251,7 @@ export async function preflightRebuildTargetRuntime( // rows may recover provider/model from their own matching onboard session; // checking the raw row first would miss that remote credential requirement. if ( - !preflightRebuildCredentials( + !(await preflightRebuildCredentials( { ...sb, provider: target.resumeConfig.provider, @@ -268,7 +268,7 @@ export async function preflightRebuildTargetRuntime( requiresGatewayProviderReconfigure = true; }, }, - ) + )) ) { return { ok: false }; } diff --git a/src/lib/hermes-provider-auth.test.ts b/src/lib/hermes-provider-auth.test.ts index 9e4dc122b77..c882320412d 100644 --- a/src/lib/hermes-provider-auth.test.ts +++ b/src/lib/hermes-provider-auth.test.ts @@ -46,34 +46,39 @@ afterEach(() => { }); describe("Hermes provider OpenShell credential handoff", () => { - it("inspects exact OpenShell credential key bindings without exposing values", () => { + it("inspects exact OpenShell credential key bindings without exposing values", async () => { const auth = loadAuth(); - const binding = auth.inspectHermesProviderBinding(() => ({ + const binding = await auth.inspectHermesProviderBinding(() => ({ status: 0, - stdout: "Provider:\n\n Name: hermes-provider\n Credential keys: NOUS_API_KEY\n", + stdout: + "Name: hermes-provider\nType: openai\nCredential keys: NOUS_API_KEY\nConfig keys: OPENAI_BASE_URL\n", stderr: "", })); expect(binding).toEqual({ exists: true, credentialKeys: ["NOUS_API_KEY"] }); }); - it("fails closed when OpenShell provider details omit credential metadata", () => { + it("fails closed when OpenShell provider details omit credential metadata", async () => { const auth = loadAuth(); - expect( + await expect( auth.inspectHermesProviderBinding(() => ({ status: 0, stdout: "Provider: exists" })), - ).toEqual({ exists: true, credentialKeys: null }); + ).resolves.toEqual({ exists: true, credentialKeys: null }); }); - it("imports the OpenAI profile before Hermes credential registration (#10155)", () => { + it("imports the OpenAI profile before Hermes credential registration (#10155)", async () => { const auth = loadAuth(); const runOpenshell = vi .fn() .mockReturnValueOnce({ status: 1, stdout: "", stderr: "provider profile not found" }) .mockReturnValueOnce({ status: 0, stdout: "Imported", stderr: "" }) .mockReturnValueOnce({ status: 0, stdout: EXACT_OPENAI_PROFILE, stderr: "" }) - .mockReturnValueOnce({ status: 1, stdout: "", stderr: "provider not found" }) + .mockReturnValueOnce({ + status: 1, + stdout: "", + stderr: "provider 'hermes-provider' not found", + }) .mockReturnValueOnce({ status: 0, stdout: "", stderr: "" }); - auth.registerHermesInferenceProvider("nous-key", runOpenshell); + await auth.registerHermesInferenceProvider("nous-key", runOpenshell); expect(runOpenshell.mock.calls.map(([args]) => args)).toEqual([ ["provider", "profile", "export", "openai", "--output", "json"], @@ -96,7 +101,7 @@ describe("Hermes provider OpenShell credential handoff", () => { }); }); - it("rejects an incompatible OpenAI profile before Hermes credential mutation (#10155)", () => { + it("rejects an incompatible OpenAI profile before Hermes credential mutation (#10155)", async () => { const auth = loadAuth(); const secret = "nous-incompatible-secret"; const runOpenshell = vi.fn().mockReturnValueOnce({ @@ -113,7 +118,7 @@ describe("Hermes provider OpenShell credential handoff", () => { let thrown: unknown; try { - auth.registerHermesInferenceProvider(secret, runOpenshell); + await auth.registerHermesInferenceProvider(secret, runOpenshell); } catch (error) { thrown = error; } @@ -123,7 +128,7 @@ describe("Hermes provider OpenShell credential handoff", () => { expect(runOpenshell).toHaveBeenCalledOnce(); }); - it("suppresses failed OpenAI profile import output before Hermes credential mutation (#10155)", () => { + it("suppresses failed OpenAI profile import output before Hermes credential mutation (#10155)", async () => { const auth = loadAuth(); const secret = "profile-import-secret"; const runOpenshell = vi @@ -133,7 +138,7 @@ describe("Hermes provider OpenShell credential handoff", () => { let thrown: unknown; try { - auth.registerHermesInferenceProvider("nous-key", runOpenshell); + await auth.registerHermesInferenceProvider("nous-key", runOpenshell); } catch (error) { thrown = error; } @@ -158,7 +163,11 @@ describe("Hermes provider OpenShell credential handoff", () => { return args[1] === "profile" ? { status: 0, stdout: EXACT_OPENAI_PROFILE, stderr: "" } : args[1] === "get" - ? { status: 1, stdout: "", stderr: "" } + ? { + status: 1, + stdout: "", + stderr: "provider 'hermes-provider' not found", + } : { status: 0, stdout: "", stderr: "" }; }, }); @@ -233,7 +242,11 @@ describe("Hermes provider OpenShell credential handoff", () => { return args[1] === "profile" ? { status: 0, stdout: EXACT_OPENAI_PROFILE, stderr: "" } : args[1] === "get" - ? { status: 1, stdout: "", stderr: "" } + ? { + status: 1, + stdout: "", + stderr: "provider 'hermes-provider' not found", + } : { status: 0, stdout: "", stderr: "" }; }, }); @@ -317,7 +330,11 @@ describe("Hermes provider OpenShell credential handoff", () => { return args[1] === "profile" ? { status: 0, stdout: EXACT_OPENAI_PROFILE, stderr: "" } : args[1] === "get" - ? { status: 1, stdout: "", stderr: "" } + ? { + status: 1, + stdout: "", + stderr: "provider 'hermes-provider' not found", + } : { status: 0, stdout: "", stderr: "" }; }, toolGatewayPresets: ["nous-web", "nous-audio"], diff --git a/src/lib/hermes-provider-auth.ts b/src/lib/hermes-provider-auth.ts index 624857d268f..b6b84ec7855 100644 --- a/src/lib/hermes-provider-auth.ts +++ b/src/lib/hermes-provider-auth.ts @@ -11,6 +11,7 @@ import type { StdioOptions } from "node:child_process"; +import { createCliOpenShellProviderAdapter } from "./adapters/openshell/provider-adapter-cli"; import { checkOpenAiInferenceProviderProfile } from "./adapters/openshell/provider-profile-registration"; import { HERMES_PROVIDER_NAME } from "./onboard/inference-providers/hermes-provider-identity"; import * as oauth from "./oauth-device-code"; @@ -18,7 +19,7 @@ import * as oauth from "./oauth-device-code"; export { HERMES_PROVIDER_NAME }; const onboardProviders = require("./onboard/providers") as { - providerExistsInGateway: (name: string, runOpenshell: RunOpenshell) => boolean; + providerExistsInGateway: (name: string, runOpenshell: RunOpenshell) => Promise; upsertProvider: ( name: string, type: string, @@ -26,7 +27,7 @@ const onboardProviders = require("./onboard/providers") as { baseUrl: string | null, env: NodeJS.ProcessEnv, runOpenshell: RunOpenshell, - ) => { ok: boolean; status?: number; message?: string }; + ) => Promise<{ ok: boolean; status?: number; message?: string }>; }; type HermesToolGatewayBroker = { @@ -34,7 +35,7 @@ type HermesToolGatewayBroker = { sandboxName: string, refreshToken: string, runOpenshell: RunOpenshell, - ) => { providerName: string; brokerToken: string }; + ) => Promise<{ providerName: string; brokerToken: string }>; ensureHermesToolGatewayBroker: (options?: { refreshToken?: string }) => boolean; }; @@ -49,7 +50,7 @@ export const AGENT_KEY_MIN_TTL_SECONDS = 1800; export type HermesAuthMethod = "oauth" | "api_key"; type RunOpenshellResult = { - status?: number | null; + status: number | null; output?: string | Buffer | null; stdout?: string | Buffer | null; stderr?: string | Buffer | null; @@ -87,7 +88,7 @@ function agentKeyExpiresAt(minted: oauth.AgentKeyResponse): string | null { return null; } -export function isHermesProviderRegistered(runOpenshell: RunOpenshell): boolean { +export function isHermesProviderRegistered(runOpenshell: RunOpenshell): Promise { return onboardProviders.providerExistsInGateway(HERMES_PROVIDER_NAME, runOpenshell); } @@ -96,32 +97,30 @@ export type HermesProviderBinding = { credentialKeys: string[] | null; }; -export function inspectHermesProviderBinding(runOpenshell: RunOpenshell): HermesProviderBinding { - const result = runOpenshell(["provider", "get", HERMES_PROVIDER_NAME], { - ignoreError: true, - stdio: ["ignore", "pipe", "pipe"], +export async function inspectHermesProviderBinding( + runOpenshell: RunOpenshell, +): Promise { + const result = await createCliOpenShellProviderAdapter({ run: runOpenshell }).getProvider({ + target: { kind: "selected" }, + providerName: HERMES_PROVIDER_NAME, }); - if (result.status !== 0) return { exists: false, credentialKeys: null }; - const output = `${result.stdout ?? ""}\n${result.stderr ?? ""}\n${result.output ?? ""}`; - const rawKeys = output.match(/Credential keys:\s*([^\r\n]+)/i)?.[1]?.trim(); - if (!rawKeys) return { exists: true, credentialKeys: null }; - if (rawKeys === "") return { exists: true, credentialKeys: [] }; + if (!result.ok) { + return result.error.kind === "command" && result.error.reason === "not_found" + ? { exists: false, credentialKeys: null } + : { exists: true, credentialKeys: null }; + } return { exists: true, - credentialKeys: rawKeys - .split(",") - .map((value) => value.trim()) - .filter(Boolean) - .sort(), + credentialKeys: [...result.value.credentialKeys].sort(), }; } -export function registerHermesInferenceProvider( +export async function registerHermesInferenceProvider( apiKey: string, runOpenshell: RunOpenshell, credentialEnv = HERMES_INFERENCE_CREDENTIAL_ENV, baseUrl = oauth.DEFAULT_INFERENCE_BASE_URL, -): void { +): Promise { const normalizedApiKey = nonEmptyString(apiKey); if (!normalizedApiKey) { throw new Error("Hermes Provider credential is empty"); @@ -130,7 +129,7 @@ export function registerHermesInferenceProvider( if (!profile.ok) { throw new Error(profile.messages.join("\n")); } - const result = onboardProviders.upsertProvider( + const result = await onboardProviders.upsertProvider( HERMES_PROVIDER_NAME, "openai", credentialEnv, @@ -176,7 +175,7 @@ export async function ensureHermesProviderOAuthCredentials( minTtlSeconds: AGENT_KEY_MIN_TTL_SECONDS, }); const inferenceBaseUrl = minted.inference_base_url || baseUrl; - registerHermesInferenceProvider( + await registerHermesInferenceProvider( minted.api_key, runOpenshell, HERMES_INFERENCE_CREDENTIAL_ENV, @@ -184,7 +183,7 @@ export async function ensureHermesProviderOAuthCredentials( ); if (Array.isArray(toolGatewayPresets) && toolGatewayPresets.length > 0) { const hermesToolGateway = getHermesToolGatewayBroker(); - hermesToolGateway.registerHermesToolGatewayRefreshProvider( + await hermesToolGateway.registerHermesToolGatewayRefreshProvider( _sandboxName, tokens.refresh_token, runOpenshell, @@ -220,7 +219,7 @@ export async function ensureHermesProviderApiKeyCredentials( const normalizedApiKey = nonEmptyString(apiKey); if (!normalizedApiKey) return null; - registerHermesInferenceProvider( + await registerHermesInferenceProvider( normalizedApiKey, runOpenshell, HERMES_NOUS_API_KEY_CREDENTIAL_ENV, diff --git a/src/lib/hermes-tool-gateway-broker.ts b/src/lib/hermes-tool-gateway-broker.ts index 5d4c196f8bd..9d960929d32 100644 --- a/src/lib/hermes-tool-gateway-broker.ts +++ b/src/lib/hermes-tool-gateway-broker.ts @@ -334,14 +334,14 @@ function brokerRuntimeFileHash(file) { } } -function registerHermesToolGatewayRefreshProvider(sandboxName, refreshToken, runOpenshell) { +async function registerHermesToolGatewayRefreshProvider(sandboxName, refreshToken, runOpenshell) { const normalized = String(refreshToken || "").trim(); if (!normalized) { throw new Error("Hermes tool gateway refresh credential is empty"); } const state = persistHermesToolGatewayProviderState(sandboxName, normalized); const providerName = getHermesToolGatewayProviderName(sandboxName); - const result = onboardProviders.upsertProvider( + const result = await onboardProviders.upsertProvider( providerName, "generic", HERMES_TOOL_GATEWAY_REFRESH_CREDENTIAL_ENV, diff --git a/src/lib/onboard/bedrock-runtime.test.ts b/src/lib/onboard/bedrock-runtime.test.ts index cad6c202701..9bc9d007fde 100644 --- a/src/lib/onboard/bedrock-runtime.test.ts +++ b/src/lib/onboard/bedrock-runtime.test.ts @@ -62,7 +62,7 @@ function createBedrockSetupHarness( credentialEnv: "COMPATIBLE_ANTHROPIC_API_KEY", isNonInteractive: () => false, runOpenshell: vi.fn(() => ({ status: 0, stdout: "", stderr: "" })), - upsertProvider: vi.fn(() => ({ ok: true })), + upsertProvider: vi.fn(async () => ({ ok: true })), verifyInferenceRoute: vi.fn(), verifyOnboardInferenceSmoke, ensureAdapter: vi.fn(async () => ({ diff --git a/src/lib/onboard/bedrock-runtime.ts b/src/lib/onboard/bedrock-runtime.ts index 6d45fdbfdd2..7aade38678f 100644 --- a/src/lib/onboard/bedrock-runtime.ts +++ b/src/lib/onboard/bedrock-runtime.ts @@ -14,22 +14,13 @@ import type { BackToSelection } from "../navigation"; import { redact } from "../runner"; import * as registry from "../state/registry"; import { LOCAL_INFERENCE_TIMEOUT_SECS } from "./env"; +import type { UpsertProvider } from "./inference-providers/types"; type RunOpenshell = ( args: string[], options?: { ignoreError?: boolean; suppressOutput?: boolean; timeout?: number }, ) => { status: number | null; stdout?: unknown; stderr?: unknown }; -type UpsertProvider = ( - name: string, - type: string, - credentialEnv: string, - baseUrl: string | null, - env?: NodeJS.ProcessEnv, -) => - | { ok: boolean; message?: string; status?: number } - | Promise<{ ok: boolean; message?: string; status?: number }>; - type SetupInferenceResult = { ok: true; retry?: undefined } | { retry: "selection" }; type BedrockRuntimeDependencies = { diff --git a/src/lib/onboard/extra-provider-reconciliation-probes.test.ts b/src/lib/onboard/extra-provider-reconciliation-probes.test.ts index e58d4239290..cc83a512bf1 100644 --- a/src/lib/onboard/extra-provider-reconciliation-probes.test.ts +++ b/src/lib/onboard/extra-provider-reconciliation-probes.test.ts @@ -15,7 +15,7 @@ afterEach(() => { }); describe("reconcileRegisteredExtraProviders probe outcomes", () => { - it("preserves providers for thrown, timed-out, process-error, and nonstandard probes (#6501)", async () => { + it("preserves providers when raw probe failures lack classifiable adapter diagnostics (#6501)", async () => { const warn = vi.fn(); const recorded = [ "thrown-provider", diff --git a/src/lib/onboard/inference-providers/compatible-endpoint-gateway-route.test.ts b/src/lib/onboard/inference-providers/compatible-endpoint-gateway-route.test.ts index d8d2dc06454..ed18f74b0b9 100644 --- a/src/lib/onboard/inference-providers/compatible-endpoint-gateway-route.test.ts +++ b/src/lib/onboard/inference-providers/compatible-endpoint-gateway-route.test.ts @@ -143,7 +143,7 @@ describe("recovered provider reuse and the openai provider profile (#9895)", () const { commands, runOpenshell } = createRunOpenshell([ { status: 0, stdout: OPENAI_ENDPOINTLESS_PROFILE }, ]); - const upsertProvider = vi.fn(() => ({ ok: true })); + const upsertProvider = vi.fn(async () => ({ ok: true })); expect( await reuseRegisteredProviderWithGatewayEndpoint({ @@ -165,7 +165,7 @@ describe("recovered provider reuse and the openai provider profile (#9895)", () { status: 1, stderr: "provider profile not found" }, { status: 1, stderr: "import refused" }, ]); - const upsertProvider = vi.fn(() => ({ ok: true })); + const upsertProvider = vi.fn(async () => ({ ok: true })); const result = await reuseRegisteredProviderWithGatewayEndpoint({ ...reuseArgs, @@ -184,7 +184,7 @@ describe("recovered provider reuse and the openai provider profile (#9895)", () it("leaves a non-openai recovered provider untouched", async () => { const { commands, runOpenshell } = createRunOpenshell([]); - const upsertProvider = vi.fn(() => ({ ok: true })); + const upsertProvider = vi.fn(async () => ({ ok: true })); expect( await reuseRegisteredProviderWithGatewayEndpoint({ diff --git a/src/lib/onboard/inference-providers/hermes.test.ts b/src/lib/onboard/inference-providers/hermes.test.ts index 214918ed1c2..7f19fe0115d 100644 --- a/src/lib/onboard/inference-providers/hermes.test.ts +++ b/src/lib/onboard/inference-providers/hermes.test.ts @@ -19,14 +19,14 @@ function makeDeps(overrides: Record = {}) { error: vi.fn(), log: vi.fn(), hermesProviderAuth: { - isHermesProviderRegistered: vi.fn(() => true), + isHermesProviderRegistered: vi.fn(async () => true), ensureHermesProviderApiKeyCredentials: vi.fn(() => ({})), ensureHermesProviderOAuthCredentials: vi.fn(() => ({})), }, getHermesToolGatewayBroker: vi.fn(() => ({ getHermesToolGatewayProviderName: vi.fn(() => "hermes-tool-gateway"), })), - providerExistsInGateway: vi.fn(() => true), + providerExistsInGateway: vi.fn(async () => true), normalizeHermesAuthMethod: vi.fn(() => "api-key"), resolveHermesNousApiKey: vi.fn(() => null), checkHermesProviderStoreReachable: vi.fn(() => ({ ok: true })), @@ -76,9 +76,7 @@ describe("setupHermesProviderInference smoke verification", () => { }); const setup = setupHermesProviderInference(makeArgs(null), deps as never); - await Promise.resolve(); - - expect(deps.verifyOnboardInferenceSmoke).toHaveBeenCalledOnce(); + await vi.waitFor(() => expect(deps.verifyOnboardInferenceSmoke).toHaveBeenCalledOnce()); expect(deps.registry.updateSandbox).not.toHaveBeenCalled(); expect(deps.log).not.toHaveBeenCalled(); diff --git a/src/lib/onboard/inference-providers/hermes.ts b/src/lib/onboard/inference-providers/hermes.ts index 1e4bce5f2c6..8bf9c34bcc3 100644 --- a/src/lib/onboard/inference-providers/hermes.ts +++ b/src/lib/onboard/inference-providers/hermes.ts @@ -111,7 +111,7 @@ export async function setupHermesProviderInference( if (isNonInteractive()) return exitProcess(1); return { retry: "selection" }; } - const providerRegistered = hermesProviderAuth.isHermesProviderRegistered(runOpenshell); + const providerRegistered = await hermesProviderAuth.isHermesProviderRegistered(runOpenshell); const toolGatewayProviderRegistered = hermesToolGateways.length === 0 ? true diff --git a/src/lib/onboard/inference-providers/ollama-local.test.ts b/src/lib/onboard/inference-providers/ollama-local.test.ts index 5ade5ab3edb..eb35a07a399 100644 --- a/src/lib/onboard/inference-providers/ollama-local.test.ts +++ b/src/lib/onboard/inference-providers/ollama-local.test.ts @@ -42,6 +42,7 @@ const CREDENTIAL_ENV = "NEMOCLAW_OLLAMA_PROXY_TOKEN"; beforeEach(() => { vi.stubEnv("DOCKER_CONTEXT", "default"); + vi.stubEnv("DOCKER_HOST", ""); }); afterEach(() => { @@ -63,7 +64,7 @@ function deps(overrides: OllamaDepsOverrides = {}): OllamaDeps { const { localInference, ...rest } = overrides; return { runOpenshell: vi.fn(() => ({ status: 0 })), - upsertProvider: vi.fn(() => ({ ok: true })), + upsertProvider: vi.fn(async () => ({ ok: true })), verifyInferenceRoute: vi.fn(), verifyOnboardInferenceSmoke: vi.fn(), isNonInteractive: () => true, @@ -96,7 +97,7 @@ function deps(overrides: OllamaDepsOverrides = {}): OllamaDeps { describe("Ollama local provider sandbox-facing model gate", () => { it("refuses to record a route the sandbox endpoint cannot serve (#9454)", async () => { - const upsertProvider = vi.fn(() => ({ ok: true })); + const upsertProvider = vi.fn(async () => ({ ok: true })); const error = vi.fn(); const validateSandboxFacingOllamaModel = vi.fn(() => ({ ok: false, @@ -148,7 +149,7 @@ describe("Ollama local provider sandbox-facing model gate", () => { }); it("records the route when the sandbox endpoint serves the model", async () => { - const upsertProvider = vi.fn(() => ({ ok: true })); + const upsertProvider = vi.fn(async () => ({ ok: true })); const stateRoot = mkdtempSync(join(tmpdir(), "nemoclaw-ollama-provider-route-")); setResolvedOllamaHost(OLLAMA_HOST_DOCKER_INTERNAL); try { @@ -234,7 +235,7 @@ describe("Ollama local provider sandbox-facing model gate", () => { }); it("fails before provider registration when the cleanup route cannot be staged", async () => { - const upsertProvider = vi.fn(() => ({ ok: true })); + const upsertProvider = vi.fn(async () => ({ ok: true })); const error = vi.fn(); await expect( @@ -266,7 +267,7 @@ describe("Ollama local provider sandbox-facing model gate", () => { setupOllamaLocalInference( { model: "llama3.2:1b", provider: "ollama-local", allowToolsIncompatible: false }, deps({ - upsertProvider: () => ({ ok: false, status: 1, message: "provider rejected" }), + upsertProvider: async () => ({ ok: false, status: 1, message: "provider rejected" }), localInference: { validateOllamaModelWithToolsOverride: () => ({ ok: true }), validateSandboxFacingOllamaModel: () => ({ ok: true }), diff --git a/src/lib/onboard/inference-providers/remote-openai-surface.test.ts b/src/lib/onboard/inference-providers/remote-openai-surface.test.ts index 749d0b607bf..f032ae8ea1a 100644 --- a/src/lib/onboard/inference-providers/remote-openai-surface.test.ts +++ b/src/lib/onboard/inference-providers/remote-openai-surface.test.ts @@ -37,7 +37,7 @@ function makeArgs(sandboxName: string | null) { function createHarness() { const runOpenshell = vi.fn(() => SUCCESS); - const upsertProvider = vi.fn(() => ({ ok: true })); + const upsertProvider = vi.fn(async () => ({ ok: true })); const probeOpenAiLikeEndpoint = vi.fn(() => ({ ok: true })); const readGatewayProviderMetadata = vi.fn(() => ({ name: PROVIDER, @@ -350,7 +350,7 @@ describe("OpenAI-compatible no-auth provider registration", () => { restore, }); harness.deps.hydrateCredentialEnv.mockReturnValue("proxy-token"); - harness.upsertProvider.mockReturnValue({ ok: false }); + harness.upsertProvider.mockResolvedValue({ ok: false }); await expect(setupRemoteProviderInference(args, harness.deps)).rejects.toThrow("EXIT_CALLED:1"); expect(persist).not.toHaveBeenCalled(); @@ -394,7 +394,7 @@ describe("OpenAI-compatible no-auth provider registration", () => { restore, }); harness.deps.hydrateCredentialEnv.mockReturnValue("proxy-token"); - harness.upsertProvider.mockReturnValue({ ok: false }); + harness.upsertProvider.mockResolvedValue({ ok: false }); harness.deps.isNonInteractive.mockReturnValue(false); harness.deps.promptValidationRecovery.mockResolvedValue("selection"); diff --git a/src/lib/onboard/inference-providers/types.ts b/src/lib/onboard/inference-providers/types.ts index 93cc48f3e6a..3bcb65845e6 100644 --- a/src/lib/onboard/inference-providers/types.ts +++ b/src/lib/onboard/inference-providers/types.ts @@ -45,7 +45,7 @@ export type UpsertProvider = ( credentialEnv: any, baseUrl: any, env?: NodeJS.ProcessEnv, -) => UpsertProviderResult | Promise; +) => Promise; export type RemoteProviderConfigEntry = { label: string; @@ -176,7 +176,7 @@ export type HermesDeps = CommonDeps & { lookup?: LookupFn; hermesProviderAuth: { HERMES_PROVIDER_NAME: string; - isHermesProviderRegistered(runOpenshell: any): boolean; + isHermesProviderRegistered(runOpenshell: any): Promise; ensureHermesProviderApiKeyCredentials( sandboxName: string, opts: { apiKey: unknown; runOpenshell: any; baseUrl?: string | undefined }, @@ -194,7 +194,7 @@ export type HermesDeps = CommonDeps & { getHermesToolGatewayBroker: () => { getHermesToolGatewayProviderName(sandboxName: string): string; }; - providerExistsInGateway: (name: string) => boolean | Promise; + providerExistsInGateway: (name: string) => Promise; normalizeHermesAuthMethod: (m: HermesAuthMethod | string | null) => HermesAuthMethod | null; resolveHermesNousApiKey: () => any; checkHermesProviderStoreReachable: ( diff --git a/src/lib/onboard/inference-providers/vllm-local.test.ts b/src/lib/onboard/inference-providers/vllm-local.test.ts index ab87a6d7b3f..43eb1501c7c 100644 --- a/src/lib/onboard/inference-providers/vllm-local.test.ts +++ b/src/lib/onboard/inference-providers/vllm-local.test.ts @@ -10,7 +10,7 @@ const CREDENTIAL_ENV = "NEMOCLAW_VLLM_LOCAL_TOKEN"; function deps(overrides: Partial = {}): VllmDeps { return { runOpenshell: vi.fn(() => ({ status: 0 })), - upsertProvider: vi.fn(() => ({ ok: true })), + upsertProvider: vi.fn(async () => ({ ok: true })), verifyInferenceRoute: vi.fn(), verifyOnboardInferenceSmoke: vi.fn(), isNonInteractive: () => true, @@ -33,7 +33,7 @@ function deps(overrides: Partial = {}): VllmDeps { describe("vLLM local provider credential", () => { it("preserves the literal dummy credential for legacy single-host vLLM", async () => { - const upsertProvider = vi.fn(() => ({ ok: true })); + const upsertProvider = vi.fn(async () => ({ ok: true })); await expect( setupVllmLocalInference( @@ -53,7 +53,7 @@ describe("vLLM local provider credential", () => { it("registers the persisted managed key through provider env, never as an argv field", async () => { const apiKey = "c".repeat(64); - const upsertProvider = vi.fn(() => ({ ok: true })); + const upsertProvider = vi.fn(async () => ({ ok: true })); await expect( setupVllmLocalInference( @@ -80,7 +80,7 @@ describe("vLLM local provider credential", () => { it("fails closed without rendering credential-loader details", async () => { const leaked = "d".repeat(64); const error = vi.fn(); - const upsertProvider = vi.fn(() => ({ ok: true })); + const upsertProvider = vi.fn(async () => ({ ok: true })); await expect( setupVllmLocalInference( diff --git a/src/lib/onboard/openrouter-runtime.ts b/src/lib/onboard/openrouter-runtime.ts index 52f928889a2..f7441eb882c 100644 --- a/src/lib/onboard/openrouter-runtime.ts +++ b/src/lib/onboard/openrouter-runtime.ts @@ -7,22 +7,13 @@ import { ensureOpenRouterRuntimeAdapter } from "../inference/openrouter-runtime- import { redact } from "../runner"; import * as registry from "../state/registry"; import { LOCAL_INFERENCE_TIMEOUT_SECS } from "./env"; +import type { UpsertProvider } from "./inference-providers/types"; type RunOpenshell = ( args: string[], options?: { ignoreError?: boolean; suppressOutput?: boolean; timeout?: number }, ) => { status: number | null; stdout?: unknown; stderr?: unknown }; -type UpsertProvider = ( - name: string, - type: string, - credentialEnv: string, - baseUrl: string | null, - env?: NodeJS.ProcessEnv, -) => - | { ok: boolean; message?: string; status?: number } - | Promise<{ ok: boolean; message?: string; status?: number }>; - type SetupInferenceResult = { ok: true; retry?: undefined } | { retry: "selection" }; type OpenRouterRuntimeDependencies = { diff --git a/src/lib/onboard/providers.test.ts b/src/lib/onboard/providers.test.ts index 5c9509a8b92..9b70bfacff5 100644 --- a/src/lib/onboard/providers.test.ts +++ b/src/lib/onboard/providers.test.ts @@ -78,7 +78,7 @@ const { allowHostedInferenceStaging?: boolean, ) => string | null; isProviderKeyCredentialCandidate: (value: string | null | undefined) => boolean; - providerExistsInGateway: (name: string, runOpenshell: RunOpenshell) => boolean; + providerExistsInGateway: (name: string, runOpenshell: RunOpenshell) => Promise; stageHostedInferenceSourceSecretEnv: () => boolean; upsertProvider: ( name: string, @@ -94,7 +94,7 @@ const { requireExactBinding?: boolean; revalidateSandboxIdentity?(operation: string): void; }, - ) => { ok: boolean; status?: number; message?: string; reason?: string }; + ) => Promise<{ ok: boolean; status?: number; message?: string; reason?: string }>; }; function withProviderEnv(next: Record, testBody: () => void): void { @@ -198,6 +198,15 @@ describe("onboard provider helpers", () => { ).rejects.toThrow("OpenShell returned invalid provider metadata"); }); + it("treats an operational provider inspection failure as unavailable", async () => { + await expect( + providerExistsInGateway("discord-bridge", () => ({ + status: 1, + stderr: "gateway temporarily unavailable", + })), + ).resolves.toBe(false); + }); + it("creates a new provider and returns ok on success", async () => { const commands: string[] = []; const result = await upsertProvider( @@ -295,6 +304,26 @@ describe("onboard provider helpers", () => { expect(commands[1]).toMatch(/OPENAI_BASE_URL=https:\/\/integrate\.api\.nvidia\.com\/v1/); }); + it("does not apply an OpenAI base URL config to native NVIDIA providers", async () => { + const commands: string[] = []; + const result = await upsertProvider( + "nvidia", + "nvidia", + "NVIDIA_INFERENCE_API_KEY", + "https://integrate.api.nvidia.com/v1", + { NVIDIA_INFERENCE_API_KEY: "nvapi-staged" }, + (command) => { + commands.push(command.join(" ")); + return command.includes("get") + ? providerMetadata("nvidia", "nvidia", "NVIDIA_INFERENCE_API_KEY") + : { status: 0, stdout: "", stderr: "" }; + }, + ); + + expect(result).toEqual({ ok: true }); + expect(commands[1]).not.toContain("--config"); + }); + it("fails before create when the credential value is empty", async () => { const commands: string[] = []; const result = await upsertProvider( diff --git a/src/lib/onboard/providers.ts b/src/lib/onboard/providers.ts index 12400167482..fe41d9709e0 100644 --- a/src/lib/onboard/providers.ts +++ b/src/lib/onboard/providers.ts @@ -377,7 +377,7 @@ async function providerExistsInGateway(name, runOpenshell) { providerName: name, }); if (result.ok) return true; - if (result.error.kind === "command" && result.error.reason === "not_found") return false; + if (result.error.kind !== "schema" && result.error.kind !== "validation") return false; throw new Error(result.error.message); } @@ -526,7 +526,7 @@ async function upsertProvider( const value = env[envKey]; return typeof value === "string" && value.length > 0 ? [{ name: envKey, value }] : []; }); - const config = baseUrl + const config = baseUrl && (type === "openai" || type === "anthropic") ? [ { key: type === "anthropic" ? "ANTHROPIC_BASE_URL" : "OPENAI_BASE_URL", diff --git a/src/lib/onboard/routed-inference.test.ts b/src/lib/onboard/routed-inference.test.ts index 7ed0ae0f5d3..dfe694401ff 100644 --- a/src/lib/onboard/routed-inference.test.ts +++ b/src/lib/onboard/routed-inference.test.ts @@ -82,7 +82,7 @@ describe("resolveRoutedCredentialEnv (#4564)", () => { describe("upsertRoutedProvider (#4564)", () => { it("upserts the provider with the normalized host alias base URL", async () => { - const upsertProvider = vi.fn(() => ({ ok: true })); + const upsertProvider = vi.fn(async () => ({ ok: true })); const hydrateCredentialEnv = vi.fn(() => "nvapi-secret"); const result = await upsertRoutedProvider( @@ -108,7 +108,7 @@ describe("upsertRoutedProvider (#4564)", () => { }); it("defaults the credential env and omits an empty credential from the env block", async () => { - const upsertProvider = vi.fn(() => ({ ok: true })); + const upsertProvider = vi.fn(async () => ({ ok: true })); const hydrateCredentialEnv = vi.fn(() => undefined); const result = await upsertRoutedProvider("nvidia-router", "http://localhost:4000/v1", null, { @@ -127,7 +127,7 @@ describe("upsertRoutedProvider (#4564)", () => { }); it("propagates a failed upsert result", async () => { - const upsertProvider = vi.fn(() => ({ ok: false, message: "boom", status: 3 })); + const upsertProvider = vi.fn(async () => ({ ok: false, message: "boom", status: 3 })); const hydrateCredentialEnv = vi.fn(() => "nvapi-secret"); const result = await upsertRoutedProvider( @@ -144,4 +144,29 @@ describe("upsertRoutedProvider (#4564)", () => { expect(result.result.message).toBe("boom"); expect(result.result.status).toBe(3); }); + + it("waits for provider registration before resolving", async () => { + let release: ((value: { ok: true }) => void) | undefined; + const upsertProvider = vi.fn( + () => + new Promise<{ ok: true }>((resolve) => { + release = resolve; + }), + ); + let settled = false; + const resultPromise = upsertRoutedProvider( + "nvidia-router", + "http://localhost:4000/v1", + "NVIDIA_INFERENCE_API_KEY", + { upsertProvider, hydrateCredentialEnv: () => "nvapi-secret" }, + ).then((result) => { + settled = true; + return result; + }); + + await Promise.resolve(); + expect(settled).toBe(false); + release?.({ ok: true }); + await expect(resultPromise).resolves.toMatchObject({ ok: true }); + }); }); diff --git a/src/lib/onboard/setup-inference-gateway-scope.test.ts b/src/lib/onboard/setup-inference-gateway-scope.test.ts index d4c12862024..381d5a99e6b 100644 --- a/src/lib/onboard/setup-inference-gateway-scope.test.ts +++ b/src/lib/onboard/setup-inference-gateway-scope.test.ts @@ -124,9 +124,14 @@ describe("gateway-scoped onboarding OpenShell commands", () => { expect(run).not.toHaveBeenCalled(); }); - it("keeps an omitted provider env separate from the bound gateway", () => { - const upsert = vi.fn(() => ({ ok: true })); - bindGatewayUpsertProvider(upsert, GATEWAY)("openai-api", "openai", "OPENAI_API_KEY", null); + it("keeps an omitted provider env separate from the bound gateway", async () => { + const upsert = vi.fn(async () => ({ ok: true })); + await bindGatewayUpsertProvider(upsert, GATEWAY)( + "openai-api", + "openai", + "OPENAI_API_KEY", + null, + ); expect(upsert).toHaveBeenCalledWith( "openai-api", "openai", @@ -162,7 +167,7 @@ describe("gateway-scoped onboarding OpenShell commands", () => { events.push(args.join(" ")); return results.shift()!; }); - const upsert = vi.fn(() => { + const upsert = vi.fn(async () => { events.push("provider mutation"); return { ok: true }; }); @@ -217,7 +222,7 @@ describe("gateway-scoped onboarding OpenShell commands", () => { { status: 13, stdout: "", stderr: sensitiveDiagnostic }, ]; const run = vi.fn(() => results.shift()!); - const upsert = vi.fn(() => ({ ok: true })); + const upsert = vi.fn(async () => ({ ok: true })); const error = vi.fn(); const reupsertRoutedProvider = createRoutedResumeProviderUpsert({ upsertProvider: upsert, diff --git a/src/lib/onboard/setup-inference-route-containment.test.ts b/src/lib/onboard/setup-inference-route-containment.test.ts index 1454e30bb5c..0ce7253da44 100644 --- a/src/lib/onboard/setup-inference-route-containment.test.ts +++ b/src/lib/onboard/setup-inference-route-containment.test.ts @@ -71,7 +71,7 @@ describe("onboard shared gateway route containment", () => { stderr: "", })), updateSandbox: vi.fn(() => true), - upsertProvider: vi.fn(() => ({ ok: true })), + upsertProvider: vi.fn(async () => ({ ok: true })), verifyInferenceRoute: vi.fn(), verifyOnboardInferenceSmoke, resolveEndpointHost, @@ -144,7 +144,7 @@ describe("onboard shared gateway route containment", () => { events.push("registry-published"); return true; }); - const upsertProvider = vi.fn(() => ({ ok: true })); + const upsertProvider = vi.fn(async () => ({ ok: true })); const verifyInferenceRoute = vi.fn(); const verifyOnboardInferenceSmoke = vi.fn(); const getGatewayName = vi.fn(() => "nemoclaw-9090"); @@ -256,7 +256,7 @@ describe("onboard shared gateway route containment", () => { it("fails before provider mutation when endpoint or credential identity differs (#6315)", async () => { const runOpenshell = vi.fn(() => ({ status: 0 })); const updateSandbox = vi.fn(() => true); - const upsertProvider = vi.fn(() => ({ ok: true })); + const upsertProvider = vi.fn(async () => ({ ok: true })); const error = vi.fn(); const exitProcess = vi.fn((code: number): never => { throw new Error(`exit ${code}`); @@ -412,7 +412,7 @@ describe("onboard shared gateway route containment", () => { getGatewayName: () => "nemoclaw", runOpenshell, updateSandbox, - upsertProvider: vi.fn(() => ({ ok: true })), + upsertProvider: vi.fn(async () => ({ ok: true })), verifyInferenceRoute: vi.fn(), verifyOnboardInferenceSmoke, isNonInteractive: () => true, @@ -524,7 +524,7 @@ describe("onboard shared gateway route containment", () => { getGatewayName: () => "nemoclaw", runOpenshell: vi.fn(() => ({ status: 0 })), updateSandbox, - upsertProvider: vi.fn(() => ({ ok: true })), + upsertProvider: vi.fn(async () => ({ ok: true })), verifyInferenceRoute: vi.fn(), verifyOnboardInferenceSmoke: vi.fn(), isNonInteractive: () => true, diff --git a/src/lib/onboard/setup-inference.test.ts b/src/lib/onboard/setup-inference.test.ts index ecffb3ad17e..5549a8d67a0 100644 --- a/src/lib/onboard/setup-inference.test.ts +++ b/src/lib/onboard/setup-inference.test.ts @@ -7,7 +7,7 @@ import { setupOllamaLocalInference } from "./inference-providers/ollama-local"; import { bindOpenAiProviderProfile, createProviderReviewDeps } from "./setup-inference"; describe("bindOpenAiProviderProfile", () => { - it("imports the profile immediately before an OpenAI provider upsert", () => { + it("imports the profile immediately before an OpenAI provider upsert", async () => { const events: string[] = []; const profileEvents = ["profile-export", "profile-import", "profile-reexport"]; const profileResults = [ @@ -30,7 +30,7 @@ describe("bindOpenAiProviderProfile", () => { events.push(profileEvents[profileIndex]!); return profileResults[profileIndex++]!; }); - const upsertProvider = vi.fn(() => { + const upsertProvider = vi.fn(async () => { events.push("upsert"); return { ok: true }; }); @@ -43,7 +43,7 @@ describe("bindOpenAiProviderProfile", () => { }, ); - expect( + await expect( profiledUpsert( "compatible-endpoint", "openai", @@ -51,7 +51,7 @@ describe("bindOpenAiProviderProfile", () => { "https://inference.example/v1", { COMPATIBLE_API_KEY: "test-secret" }, ), - ).toEqual({ ok: true }); + ).resolves.toEqual({ ok: true }); expect(events).toEqual(["profile-export", "profile-import", "profile-reexport", "upsert"]); expect(runOpenshell).toHaveBeenNthCalledWith( @@ -86,9 +86,9 @@ describe("bindOpenAiProviderProfile", () => { ); }); - it("does not import the OpenAI profile for another provider type", () => { + it("does not import the OpenAI profile for another provider type", async () => { const runOpenshell = vi.fn(() => ({ status: 0, stdout: "", stderr: "" })); - const upsertProvider = vi.fn(() => ({ ok: true })); + const upsertProvider = vi.fn(async () => ({ ok: true })); const profiledUpsert = bindOpenAiProviderProfile( upsertProvider, runOpenshell, @@ -98,7 +98,7 @@ describe("bindOpenAiProviderProfile", () => { }, ); - expect( + await expect( profiledUpsert( "anthropic-prod", "anthropic", @@ -106,7 +106,7 @@ describe("bindOpenAiProviderProfile", () => { "https://api.anthropic.com", {}, ), - ).toEqual({ ok: true }); + ).resolves.toEqual({ ok: true }); expect(runOpenshell).not.toHaveBeenCalled(); }); @@ -144,10 +144,10 @@ describe("bindOpenAiProviderProfile", () => { expected: "does not match NemoClaw's endpointless inference contract", guidance: "Remove the conflicting profile", }, - ])("fails closed with fixed guidance for $reason", ({ results, expected, guidance }) => { + ])("fails closed with fixed guidance for $reason", async ({ results, expected, guidance }) => { let resultIndex = 0; const runOpenshell = vi.fn(() => results[resultIndex++]!); - const upsertProvider = vi.fn(() => ({ ok: true })); + const upsertProvider = vi.fn(async () => ({ ok: true })); const error = vi.fn(); const profiledUpsert = bindOpenAiProviderProfile( upsertProvider, @@ -158,7 +158,7 @@ describe("bindOpenAiProviderProfile", () => { }, ); - expect(() => + await expect(async () => profiledUpsert( "compatible-endpoint", "openai", @@ -166,7 +166,7 @@ describe("bindOpenAiProviderProfile", () => { "https://inference.example/v1", {}, ), - ).toThrow("exit 1"); + ).rejects.toThrow("exit 1"); expect(upsertProvider).not.toHaveBeenCalled(); const output = error.mock.calls.flat().join("\n"); @@ -311,7 +311,7 @@ describe("createProviderReviewDeps", () => { }, { runOpenshell: () => ({ status: 0 }), - upsertProvider: () => ({ ok: true }), + upsertProvider: async () => ({ ok: true }), verifyInferenceRoute: vi.fn(), verifyOnboardInferenceSmoke: vi.fn(), isNonInteractive: () => true, diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index cb1449369ee..6e6a2240dbd 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -218,7 +218,7 @@ export type SetupInferenceDeps = ProviderBranchDeps & { options?: { revalidateSandboxIdentity?(operation: string): void }, ) => ReturnType; verifyInferenceRoute: (gatewayName: string, provider: string, model: string) => void; - providerExistsInGateway: (name: string, gatewayName: string) => boolean; + providerExistsInGateway: (name: string, gatewayName: string) => Promise; run: typeof import("../runner").run; updateSandbox: typeof import("../state/registry").reserveSandboxInferenceRoute; // #9110 optional GPU-release seams; omitted by test literals that build deps @@ -805,11 +805,11 @@ export function createSetupInference( } : deps.error; const profiledUpsertProvider = bindOpenAiProviderProfile( - (...args) => { + async (...args) => { revalidateSandboxIdentity?.("register the inference provider"); const selectedUpsertProvider = hostLocalGatewayMutation?.upsertProvider ?? defaultUpsertProvider; - return selectedUpsertProvider(...args); + return await selectedUpsertProvider(...args); }, runGatewayOpenshell, providerError, diff --git a/test/credentials/credential-exposure.test.ts b/test/credentials/credential-exposure.test.ts index 647766d5db2..c832d9b9bf1 100644 --- a/test/credentials/credential-exposure.test.ts +++ b/test/credentials/credential-exposure.test.ts @@ -7,8 +7,8 @@ // there is no reason to pass the secret itself on the command line where it // would be visible in `ps aux` output. -import { createRequire } from "node:module"; import { describe, expect, it } from "vitest"; +import { createCliOpenShellProviderAdapter } from "../../src/lib/adapters/openshell/provider-adapter-cli"; import { buildSubprocessEnv as buildPluginSubprocessEnv, withLocalNoProxy as withPluginLocalNoProxy, @@ -18,31 +18,34 @@ import { withLocalNoProxy as withCliLocalNoProxy, } from "../../src/lib/subprocess-env"; -const require = createRequire(import.meta.url); -const { buildProviderArgs } = require("../../src/lib/onboard/providers.js") as { - buildProviderArgs: ( - action: "create" | "update", - name: string, - type: string, - credentialEnv: string, - baseUrl: string | null, - ) => string[]; -}; - describe("credential exposure in process arguments", () => { - it("onboard.js --credential flags pass env var names only", () => { - const args = buildProviderArgs( - "create", - "inference", - "openai", - "NVIDIA_INFERENCE_API_KEY", - "https://api.example.test/v1", - ); - + it("provider adapter --credential flags pass env var names only", async () => { + const secret = "nvapi-test-secret"; + const calls: Array<{ args: string[]; env?: Record }> = []; + const adapter = createCliOpenShellProviderAdapter({ + run: (args, options) => { + calls.push({ args, env: options.env }); + return { status: 0, stdout: "", stderr: "" }; + }, + }); + + await expect( + adapter.createProvider({ + target: { kind: "selected" }, + name: "inference", + type: "openai", + credentials: [{ name: "NVIDIA_INFERENCE_API_KEY", value: secret }], + config: [{ key: "OPENAI_BASE_URL", value: "https://api.example.test/v1" }], + fromExisting: false, + }), + ).resolves.toEqual({ ok: true }); + + const [{ args, env }] = calls; expect(args).toContain("--credential"); expect(args).toContain("NVIDIA_INFERENCE_API_KEY"); expect(args.join(" ")).not.toContain("NVIDIA_INFERENCE_API_KEY="); - expect(args.join(" ")).not.toContain("nvapi-"); + expect(args.join(" ")).not.toContain(secret); + expect(env).toEqual({ NVIDIA_INFERENCE_API_KEY: secret }); }); it("subprocess-env TLS allowlist includes git, curl, and python CA vars (#2270)", () => { diff --git a/test/onboarding/onboard-build-recreate-credential-reuse.test.ts b/test/onboarding/onboard-build-recreate-credential-reuse.test.ts index c130ce0f633..f3cb36b5b0a 100644 --- a/test/onboarding/onboard-build-recreate-credential-reuse.test.ts +++ b/test/onboarding/onboard-build-recreate-credential-reuse.test.ts @@ -52,6 +52,12 @@ EOF exit 0 fi if [ "$1" = "provider" ] && [ "$2" = "get" ]; then + cat <<'EOF' +Name: nvidia-prod +Type: nvidia +Credential keys: NVIDIA_INFERENCE_API_KEY +Config keys: +EOF exit 0 fi exit 0 @@ -195,6 +201,12 @@ const { setupNim, setupInference } = require(${onboardPath}); path.join(fakeBin, "openshell"), `#!/usr/bin/env bash if [ "$1" = "provider" ] && [ "$2" = "get" ]; then + cat <<'EOF' +Name: nvidia-prod +Type: nvidia +Credential keys: NVIDIA_INFERENCE_API_KEY +Config keys: +EOF exit 0 fi exit 0 diff --git a/test/onboarding/onboard-host-local-inference-routing.test.ts b/test/onboarding/onboard-host-local-inference-routing.test.ts index 5e8f1a7ea0b..8e8a77a6717 100644 --- a/test/onboarding/onboard-host-local-inference-routing.test.ts +++ b/test/onboarding/onboard-host-local-inference-routing.test.ts @@ -586,7 +586,7 @@ describe("onboard host-local inference routing", () => { it("uses a transaction-owned provider create instead of the generic gateway upsert", async () => { const exactProviderCreate = vi.fn(() => ({ ok: true })); - const genericUpsertProvider = vi.fn(() => ({ ok: true })); + const genericUpsertProvider = vi.fn(async () => ({ ok: true })); const route = fixture("hermes", "ollama", { gatewayUpsertProvider: exactProviderCreate, }); diff --git a/test/onboarding/onboard-inference-failure-paths.test.ts b/test/onboarding/onboard-inference-failure-paths.test.ts index 8887df8cb77..bb3f2a5d3b1 100644 --- a/test/onboarding/onboard-inference-failure-paths.test.ts +++ b/test/onboarding/onboard-inference-failure-paths.test.ts @@ -132,7 +132,7 @@ describe("setupInference dependency failures", () => { it("fails through the injected exit boundary when a remote credential is missing", async () => { const exitProcess = createInjectedExit(); const hydrateCredentialEnv = vi.fn(() => null); - const upsertProvider = vi.fn(() => ({ ok: true })); + const upsertProvider = vi.fn(async () => ({ ok: true })); const promptValidationRecovery = vi.fn(async () => "selection" as const); const setupBedrockRuntimeInference = vi.fn(async () => ({ handled: false as const })); const harness = createDirectSetupInferenceHarness({ @@ -165,7 +165,7 @@ describe("setupInference dependency failures", () => { it("preserves a remote provider upsert status through the injected exit boundary", async () => { const exitProcess = createInjectedExit(); const hydrateCredentialEnv = vi.fn(() => "openai-secret"); - const upsertProvider = vi.fn(() => ({ + const upsertProvider = vi.fn(async () => ({ ok: false, status: 23, message: "remote provider registration rejected", @@ -209,7 +209,7 @@ describe("setupInference dependency failures", () => { it("redacts a remote inference-set failure and preserves its status at the exit boundary", async () => { const exitProcess = createInjectedExit(); const hydrateCredentialEnv = vi.fn(() => "openai-secret"); - const upsertProvider = vi.fn(() => ({ ok: true })); + const upsertProvider = vi.fn(async () => ({ ok: true })); const promptValidationRecovery = vi.fn(async () => "selection" as const); const setupBedrockRuntimeInference = vi.fn(async () => ({ handled: false as const })); const commandRouter = createDirectCommandRouter([ @@ -410,7 +410,7 @@ describe("setupInference dependency failures", () => { it("exits through injected Hermes boundaries when provider storage is unavailable", async () => { const exitProcess = createInjectedExit(); const isHermesProviderRegistered = vi.fn( - (_runOpenshell: SetupInferenceDeps["runOpenshell"]) => true, + async (_runOpenshell: SetupInferenceDeps["runOpenshell"]) => true, ); const ensureHermesProviderApiKeyCredentials = vi.fn(async () => ({})); const ensureHermesProviderOAuthCredentials = vi.fn(async () => ({})); @@ -456,13 +456,13 @@ describe("setupInference dependency failures", () => { it("exits through injected boundaries when Hermes API-key preparation throws", async () => { const exitProcess = createInjectedExit(); const isHermesProviderRegistered = vi.fn( - (_runOpenshell: SetupInferenceDeps["runOpenshell"]) => false, + async (_runOpenshell: SetupInferenceDeps["runOpenshell"]) => false, ); const ensureHermesProviderApiKeyCredentials = vi.fn(async () => { throw new Error("API-key preparation failed"); }); const ensureHermesProviderOAuthCredentials = vi.fn(async () => ({})); - const providerExistsInGateway = vi.fn(() => true); + const providerExistsInGateway = vi.fn(async () => true); const resolveHermesNousApiKey = vi.fn(() => "nous-secret"); const checkHermesProviderStoreReachable = vi.fn( (_runOpenshell: SetupInferenceDeps["runOpenshell"]) => ({ ok: true }), @@ -517,13 +517,13 @@ describe("setupInference dependency failures", () => { it("exits through injected boundaries when Hermes OAuth preparation throws", async () => { const exitProcess = createInjectedExit(); const isHermesProviderRegistered = vi.fn( - (_runOpenshell: SetupInferenceDeps["runOpenshell"]) => false, + async (_runOpenshell: SetupInferenceDeps["runOpenshell"]) => false, ); const ensureHermesProviderApiKeyCredentials = vi.fn(async () => ({})); const ensureHermesProviderOAuthCredentials = vi.fn(async () => { throw new Error("OAuth preparation failed"); }); - const providerExistsInGateway = vi.fn(() => true); + const providerExistsInGateway = vi.fn(async () => true); const resolveHermesNousApiKey = vi.fn(() => "unused-key"); const checkHermesProviderStoreReachable = vi.fn( (_runOpenshell: SetupInferenceDeps["runOpenshell"]) => ({ ok: true }), @@ -605,7 +605,7 @@ describe("setupInference dependency failures", () => { stubMissingBedrockAuth(); const exitProcess = createInjectedExit(); const ensureAdapter = vi.fn(async () => successfulBedrockAdapter()); - const upsertProvider = vi.fn(() => ({ ok: true })); + const upsertProvider = vi.fn(async () => ({ ok: true })); const harness = createDirectSetupInferenceHarness({ overrides: { isNonInteractive: () => true, @@ -642,7 +642,7 @@ describe("setupInference dependency failures", () => { const ensureAdapter = vi.fn(async () => { throw new Error("adapter unavailable"); }); - const upsertProvider = vi.fn(() => ({ ok: true })); + const upsertProvider = vi.fn(async () => ({ ok: true })); const harness = createDirectSetupInferenceHarness({ overrides: { exitProcess, @@ -677,7 +677,7 @@ describe("setupInference dependency failures", () => { const ensureAdapter = vi.fn(async () => { throw new Error("adapter unavailable"); }); - const upsertProvider = vi.fn(() => ({ ok: true })); + const upsertProvider = vi.fn(async () => ({ ok: true })); const harness = createDirectSetupInferenceHarness({ overrides: { isNonInteractive: () => true, @@ -712,7 +712,7 @@ describe("setupInference dependency failures", () => { vi.stubEnv(BEDROCK_CREDENTIAL_ENV, "bedrock-bearer"); const exitProcess = createInjectedExit(); const ensureAdapter = vi.fn(async () => successfulBedrockAdapter()); - const upsertProvider = vi.fn(() => ({ + const upsertProvider = vi.fn(async () => ({ ok: false, status: 23, message: "Bedrock provider registration failed", @@ -749,7 +749,7 @@ describe("setupInference dependency failures", () => { vi.stubEnv(BEDROCK_CREDENTIAL_ENV, "bedrock-bearer"); const exitProcess = createInjectedExit(); const ensureAdapter = vi.fn(async () => successfulBedrockAdapter()); - const upsertProvider = vi.fn(() => ({ + const upsertProvider = vi.fn(async () => ({ ok: false, status: 0, message: "Bedrock provider registration failed without status", @@ -786,7 +786,7 @@ describe("setupInference dependency failures", () => { vi.stubEnv(BEDROCK_CREDENTIAL_ENV, "bedrock-bearer"); const exitProcess = createInjectedExit(); const ensureAdapter = vi.fn(async () => successfulBedrockAdapter()); - const upsertProvider = vi.fn(() => ({ ok: true })); + const upsertProvider = vi.fn(async () => ({ ok: true })); const harness = createDirectSetupInferenceHarness({ runOpenshell: (args) => args.slice(0, 2).join(" ") === "inference set" @@ -831,7 +831,7 @@ describe("setupInference dependency failures", () => { vi.stubEnv(BEDROCK_CREDENTIAL_ENV, "bedrock-bearer"); const exitProcess = createInjectedExit(); const ensureAdapter = vi.fn(async () => successfulBedrockAdapter()); - const upsertProvider = vi.fn(() => ({ ok: true })); + const upsertProvider = vi.fn(async () => ({ ok: true })); const harness = createDirectSetupInferenceHarness({ runOpenshell: (args) => args.slice(0, 2).join(" ") === "inference set" @@ -931,7 +931,7 @@ describe("setupInference dependency failures", () => { it("preserves a routed-provider upsert status through the injected exit boundary", async () => { const exitProcess = createInjectedExit(); const reconcileModelRouter = vi.fn(async () => {}); - const upsertProvider = vi.fn(() => ({ ok: true })); + const upsertProvider = vi.fn(async () => ({ ok: true })); const hydrateCredentialEnv = vi.fn(() => "unused-secret"); const upsertRoutedProvider = vi.fn< SetupInferenceDeps["routedInference"]["upsertRoutedProvider"] diff --git a/test/onboarding/onboard-inference-gateway-scope.test.ts b/test/onboarding/onboard-inference-gateway-scope.test.ts index d3911bf3fc8..a1a6e207ced 100644 --- a/test/onboarding/onboard-inference-gateway-scope.test.ts +++ b/test/onboarding/onboard-inference-gateway-scope.test.ts @@ -148,7 +148,7 @@ describe("onboarding inference gateway scope", () => { const providerUpdate = harness.commands.find(({ command }) => command.startsWith("provider update "), ); - expect(providerUpdate?.env).toEqual({}); + expect(providerUpdate?.env).toBeUndefined(); expect(harness.commands.every(({ env }) => env?.COMPATIBLE_API_KEY === undefined)).toBe(true); expect(harness.verifyOnboardInferenceSmoke).not.toHaveBeenCalled(); expect(harness.verifyInferenceRoute).toHaveBeenCalledWith( diff --git a/test/onboarding/onboard-inference-smoke.test.ts b/test/onboarding/onboard-inference-smoke.test.ts index d17a580f540..b8326a66875 100644 --- a/test/onboarding/onboard-inference-smoke.test.ts +++ b/test/onboarding/onboard-inference-smoke.test.ts @@ -72,8 +72,12 @@ runner.run = (command) => { calls.push(["run", text]); const profileResult = require(${onboardScriptMocksPath}).mockManagedEndpointlessProviderProfileRun(command); if (profileResult !== null) return profileResult; - if (text.includes("provider") && text.includes("upsert")) { - return { status: 0, stdout: "Created provider compatible-endpoint\n", stderr: "" }; + if (text.includes("provider get") && text.includes("compatible-endpoint")) { + return { + status: 1, + stdout: "", + stderr: "provider 'compatible-endpoint' not found", + }; } if (text.includes("inference") && text.includes("set")) { return { status: 0, stdout: "Inference configured\n", stderr: "" }; diff --git a/test/onboarding/onboard-openrouter-inference.test.ts b/test/onboarding/onboard-openrouter-inference.test.ts index bc409de7f9c..06689101026 100644 --- a/test/onboarding/onboard-openrouter-inference.test.ts +++ b/test/onboarding/onboard-openrouter-inference.test.ts @@ -97,7 +97,7 @@ describe("OpenRouter onboarding inference setup", () => { credentialValue: "sk-or-test", isNonInteractive: () => true, runOpenshell: () => ({ status: 0 }), - upsertProvider: () => ({ ok: true }), + upsertProvider: async () => ({ ok: true }), verifyInferenceRoute: vi.fn(), verifyOnboardInferenceSmoke: vi.fn(() => smokePending), ensureAdapter: vi.fn(async () => ({ diff --git a/test/onboarding/onboard-selection.test.ts b/test/onboarding/onboard-selection.test.ts index dde543b0dbb..d9aced1ba93 100644 --- a/test/onboarding/onboard-selection.test.ts +++ b/test/onboarding/onboard-selection.test.ts @@ -3012,7 +3012,7 @@ reportChildScenario(async () => { try { const { result, lines } = await captureConsoleOutput(async () => { try { - resolveNonInteractiveBuildCredential({ + await resolveNonInteractiveBuildCredential({ provider: "nvidia-prod", helpUrl: "https://build.nvidia.com/settings/api-keys", recoveredFromSandbox: false, @@ -3059,7 +3059,7 @@ reportChildScenario(async () => { try { const { result, lines } = await captureConsoleOutput(async () => { try { - resolveNonInteractiveBuildCredential({ + await resolveNonInteractiveBuildCredential({ provider: "nvidia-prod", helpUrl: "https://build.nvidia.com/settings/api-keys", recoveredFromSandbox: false, @@ -4082,7 +4082,7 @@ if (args[0] === "inference" && args[1] === "set") { process.exit(0); } if (args[0] === "provider" && args[1] === "profile" && args.includes("export")) { process.stdout.write(JSON.stringify({ id: "openai", credentials: [], endpoints: [], binaries: [], inference_capable: true })); process.exit(0); } -if (args[0] === "provider" && args[1] === "get") { process.exit(1); } // Force provider creation. +if (args[0] === "provider" && args[1] === "get") { process.stderr.write("provider 'compatible-endpoint' not found"); process.exit(1); } // Force provider creation. process.exit(0); `, { mode: 0o755 }, diff --git a/test/support/setup-inference-test-harness.ts b/test/support/setup-inference-test-harness.ts index 3f65eb4f778..564ad9f96b7 100644 --- a/test/support/setup-inference-test-harness.ts +++ b/test/support/setup-inference-test-harness.ts @@ -20,8 +20,8 @@ const onboardProviderHelpers = require("../../src/lib/onboard/providers") as { baseUrl: string | null, env: Record, runOpenshell: DirectRunOpenshell, - ) => { ok: boolean; status?: number; message?: string }; - providerExistsInGateway: (name: string, runOpenshell: DirectRunOpenshell) => boolean; + ) => Promise<{ ok: boolean; status?: number; message?: string }>; + providerExistsInGateway: (name: string, runOpenshell: DirectRunOpenshell) => Promise; }; const localInferenceModule = require("../../src/lib/inference/local") as typeof import("../../src/lib/inference/local.js"); @@ -119,6 +119,17 @@ if (argv[0] === "inference" && argv[1] === "get") { `Gateway inference:\n Provider: ${options.provider}\n Model: ${options.model}\n`, )}); } +if (argv[0] === "provider" && argv[1] === "get") { + process.stdout.write(${JSON.stringify( + [ + `Name: ${options.provider}`, + `Type: ${options.provider === "nvidia-prod" ? "nvidia" : "openai"}`, + `Credential keys: ${options.credentialEnv}`, + `Config keys: ${options.provider === "nvidia-prod" ? "" : "OPENAI_BASE_URL"}`, + "", + ].join("\n"), + )}); +} process.exit(0); `, { mode: 0o755 }, @@ -289,7 +300,30 @@ export function createDirectSetupInferenceHarnessFactory( ignoreError: runOptions.ignoreError, }); const routed = options.runOpenshell?.(args, runOptions, commands); - if (routed !== undefined) return directRunResult(routed); + if (routed !== undefined) { + if (args[0] === "provider" && args[1] === "get") { + const providerName = args.at(-1) ?? "provider"; + if (routed.status === 1 && !routed.stdout && !routed.stderr) { + return directRunResult({ + ...routed, + stderr: `provider '${providerName}' not found`, + }); + } + if (routed.status === 0 && !routed.stdout && !routed.stderr) { + return directRunResult({ + ...routed, + stdout: [ + `Name: ${providerName}`, + "Type: openai", + "Credential keys: COMPATIBLE_API_KEY", + "Config keys: OPENAI_BASE_URL", + "", + ].join("\n"), + }); + } + } + return directRunResult(routed); + } if ( args[0] === "provider" && args[1] === "profile" && @@ -298,6 +332,19 @@ export function createDirectSetupInferenceHarnessFactory( ) { return directRunResult({ status: 0, stdout: OPENAI_ENDPOINTLESS_PROFILE }); } + if (args[0] === "provider" && args[1] === "get") { + const providerName = args.at(-1) ?? "provider"; + return directRunResult({ + status: 0, + stdout: [ + `Name: ${providerName}`, + "Type: openai", + "Credential keys: COMPATIBLE_API_KEY", + "Config keys: OPENAI_BASE_URL", + "", + ].join("\n"), + }); + } return directRunResult(); }; const setupInferenceWithoutPolicyAuthority = createSetupInference({ @@ -311,7 +358,7 @@ export function createDirectSetupInferenceHarnessFactory( step: () => {}, getGatewayName: () => "nemoclaw", runOpenshell, - upsertProvider: ( + upsertProvider: async ( name: string, type: string, credentialEnv: string, @@ -319,7 +366,7 @@ export function createDirectSetupInferenceHarnessFactory( env: Record | undefined, gatewayName: string, ) => - onboardProviderHelpers.upsertProvider( + await onboardProviderHelpers.upsertProvider( name, type, credentialEnv, From dd262eff8bd1ae5ff3e994933317e28244bfa8d3 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 8 Sep 2026 15:10:44 -0700 Subject: [PATCH 03/10] test: use typed provider metadata in reconciliation --- .../onboard-inference-reconciliation.test.ts | 23 +++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/test/onboarding/onboard-inference-reconciliation.test.ts b/test/onboarding/onboard-inference-reconciliation.test.ts index 8adc8f63837..02fc27e1535 100644 --- a/test/onboarding/onboard-inference-reconciliation.test.ts +++ b/test/onboarding/onboard-inference-reconciliation.test.ts @@ -28,6 +28,22 @@ import { withProcessEnv, } from "../support/setup-inference-test-harness.js"; +const HERMES_OAUTH_PROVIDER_METADATA = [ + "Name: hermes-provider", + "Type: openai", + "Credential keys: OPENAI_API_KEY", + "Config keys: OPENAI_BASE_URL", + "", +].join("\n"); + +const HERMES_API_KEY_PROVIDER_METADATA = [ + "Name: hermes-provider", + "Type: openai", + "Credential keys: NOUS_API_KEY", + "Config keys: OPENAI_BASE_URL", + "", +].join("\n"); + describe("onboard helpers", () => { it("reuses a registered Hermes Provider without re-collecting host credentials", async () => { await withProcessEnv( @@ -39,7 +55,7 @@ describe("onboard helpers", () => { const harness = createDirectSetupInferenceHarness({ runOpenshell: (args) => args.join(" ") === "provider get -g nemoclaw hermes-provider" - ? { status: 0, stdout: "Provider: hermes-provider", stderr: "" } + ? { status: 0, stdout: HERMES_OAUTH_PROVIDER_METADATA, stderr: "" } : undefined, overrides: { isNonInteractive: () => true }, }); @@ -305,6 +321,9 @@ try { runner.run = (command, opts = {}) => { const normalized = _n(command); commands.push({ command: normalized, env: opts.env || null }); + if (normalized.includes("provider get") && normalized.includes("hermes-provider")) { + return { status: 0, stdout: ${JSON.stringify(HERMES_API_KEY_PROVIDER_METADATA)}, stderr: "" }; + } return { status: 0, stdout: "", stderr: "" }; }; runner.runCapture = (command) => { @@ -517,7 +536,7 @@ const { onboard } = require(${onboardPath}); const harness = createDirectSetupInferenceHarness({ runOpenshell: (args) => args.join(" ") === "provider get -g nemoclaw hermes-provider" - ? { status: 0, stdout: "Provider: hermes-provider", stderr: "" } + ? { status: 0, stdout: HERMES_OAUTH_PROVIDER_METADATA, stderr: "" } : undefined, overrides: { isNonInteractive: () => true }, }); From c2f188da59edbe414a105246232ff64341f6e8be Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 8 Sep 2026 15:37:27 -0700 Subject: [PATCH 04/10] test: tighten provider lifecycle fixtures --- ...rd-build-recreate-credential-reuse.test.ts | 12 ++++++++-- .../onboard-inference-gateway-scope.test.ts | 8 ++++++- .../onboard-inference-reconciliation.test.ts | 17 +++++++++++--- .../onboard-inference-smoke.test.ts | 19 ++++++++++++++++ .../onboard-openrouter-inference.test.ts | 10 +++++++++ test/onboarding/onboard.test.ts | 14 ++++++++++-- test/support/setup-inference-test-harness.ts | 22 ++----------------- 7 files changed, 74 insertions(+), 28 deletions(-) diff --git a/test/onboarding/onboard-build-recreate-credential-reuse.test.ts b/test/onboarding/onboard-build-recreate-credential-reuse.test.ts index f3cb36b5b0a..8b4e209289e 100644 --- a/test/onboarding/onboard-build-recreate-credential-reuse.test.ts +++ b/test/onboarding/onboard-build-recreate-credential-reuse.test.ts @@ -51,7 +51,7 @@ Gateway inference: EOF exit 0 fi -if [ "$1" = "provider" ] && [ "$2" = "get" ]; then +if [ "$1" = "provider" ] && [ "$2" = "get" ] && [ "$5" = "nvidia-prod" ]; then cat <<'EOF' Name: nvidia-prod Type: nvidia @@ -60,6 +60,10 @@ Config keys: EOF exit 0 fi +if [ "$1" = "provider" ] && [ "$2" = "get" ]; then + printf "provider '%s' not found\n" "$5" >&2 + exit 1 +fi exit 0 `, { mode: 0o755 }, @@ -200,7 +204,7 @@ const { setupNim, setupInference } = require(${onboardPath}); fs.writeFileSync( path.join(fakeBin, "openshell"), `#!/usr/bin/env bash -if [ "$1" = "provider" ] && [ "$2" = "get" ]; then +if [ "$1" = "provider" ] && [ "$2" = "get" ] && [ "$5" = "nvidia-prod" ]; then cat <<'EOF' Name: nvidia-prod Type: nvidia @@ -209,6 +213,10 @@ Config keys: EOF exit 0 fi +if [ "$1" = "provider" ] && [ "$2" = "get" ]; then + printf "provider '%s' not found\n" "$5" >&2 + exit 1 +fi exit 0 `, { mode: 0o755 }, diff --git a/test/onboarding/onboard-inference-gateway-scope.test.ts b/test/onboarding/onboard-inference-gateway-scope.test.ts index a1a6e207ced..45081891b8d 100644 --- a/test/onboarding/onboard-inference-gateway-scope.test.ts +++ b/test/onboarding/onboard-inference-gateway-scope.test.ts @@ -117,7 +117,13 @@ describe("onboarding inference gateway scope", () => { await withProcessEnv({ COMPATIBLE_API_KEY: undefined }, async () => { const harness = createHarness({ runOpenshell: (args) => - args.slice(0, 2).join(" ") === "provider get" ? { status: 0 } : undefined, + args.slice(0, 2).join(" ") === "provider get" + ? { + status: 0, + stdout: + "Name: compatible-endpoint\nType: openai\nCredential keys: COMPATIBLE_API_KEY\nConfig keys: OPENAI_BASE_URL\n", + } + : undefined, }); const model = "deepseek-ai/DeepSeek-V4-Flash"; diff --git a/test/onboarding/onboard-inference-reconciliation.test.ts b/test/onboarding/onboard-inference-reconciliation.test.ts index 02fc27e1535..3c5f1cca513 100644 --- a/test/onboarding/onboard-inference-reconciliation.test.ts +++ b/test/onboarding/onboard-inference-reconciliation.test.ts @@ -44,6 +44,14 @@ const HERMES_API_KEY_PROVIDER_METADATA = [ "", ].join("\n"); +const OPENAI_API_PROVIDER_METADATA = [ + "Name: openai-api", + "Type: openai", + "Credential keys: OPENAI_API_KEY", + "Config keys: OPENAI_BASE_URL", + "", +].join("\n"); + describe("onboard helpers", () => { it("reuses a registered Hermes Provider without re-collecting host credentials", async () => { await withProcessEnv( @@ -927,7 +935,7 @@ console.log(JSON.stringify({ const harness = createDirectSetupInferenceHarness({ runOpenshell: (args) => args.slice(0, 2).join(" ") === "provider get" - ? { status: 0, stdout: "", stderr: "" } + ? { status: 0, stdout: OPENAI_API_PROVIDER_METADATA, stderr: "" } : undefined, }); @@ -954,7 +962,10 @@ console.log(JSON.stringify({ { name: "provider-get", matches: (command) => command.startsWith("provider get"), - results: [{ status: 0, stdout: "", stderr: "" }], + results: [ + { status: 0, stdout: OPENAI_API_PROVIDER_METADATA, stderr: "" }, + { status: 0, stdout: OPENAI_API_PROVIDER_METADATA, stderr: "" }, + ], }, { name: "inference-set", @@ -999,7 +1010,7 @@ console.log(JSON.stringify({ { name: "provider-get", matches: (command) => command.startsWith("provider get"), - results: [{ status: 0, stdout: "", stderr: "" }], + results: [{ status: 0, stdout: OPENAI_API_PROVIDER_METADATA, stderr: "" }], }, { name: "inference-set", diff --git a/test/onboarding/onboard-inference-smoke.test.ts b/test/onboarding/onboard-inference-smoke.test.ts index b8326a66875..8bcec16adec 100644 --- a/test/onboarding/onboard-inference-smoke.test.ts +++ b/test/onboarding/onboard-inference-smoke.test.ts @@ -25,6 +25,7 @@ describe("onboard inference smoke guard (#3253)", () => { const fakeBin = path.join(tmpDir, "bin"); const scriptPath = path.join(tmpDir, "setup-inference-smoke-check.cjs"); const curlLogPath = path.join(tmpDir, "curl-probes.log"); + const commandLogPath = path.join(tmpDir, "openshell-commands.log"); const onboardPath = JSON.stringify(path.join(REPO_ROOT, "src", "lib", "onboard.ts")); const runnerPath = JSON.stringify(path.join(REPO_ROOT, "src", "lib", "runner.ts")); const registryPath = JSON.stringify( @@ -70,6 +71,7 @@ const normalize = (command) => (Array.isArray(command) ? command.join(" ") : Str runner.run = (command) => { const text = normalize(command); calls.push(["run", text]); + require("node:fs").appendFileSync(process.env.NEMOCLAW_FAKE_COMMAND_LOG, text + "\n"); const profileResult = require(${onboardScriptMocksPath}).mockManagedEndpointlessProviderProfileRun(command); if (profileResult !== null) return profileResult; if (text.includes("provider get") && text.includes("compatible-endpoint")) { @@ -153,6 +155,7 @@ const setupInference = createSetupInference({ VITEST: "false", NEMOCLAW_TEST_NO_SLEEP: "1", NEMOCLAW_FAKE_CURL_LOG: curlLogPath, + NEMOCLAW_FAKE_COMMAND_LOG: commandLogPath, BROKEN_API_KEY: "test-key", }, timeout: 80_000, @@ -165,6 +168,22 @@ const setupInference = createSetupInference({ `setupInference accepted a configured route without proving chat/completions; output:\n${output}`, ); + const commands = fs.readFileSync(commandLogPath, "utf8").trim().split("\n"); + const providerCreateIndex = commands.findIndex( + (command) => + command.includes("provider create -g nemoclaw") && + command.includes("--name compatible-endpoint"), + ); + const inferenceSetIndex = commands.findIndex((command) => + command.includes("inference set -g nemoclaw"), + ); + assert.ok(providerCreateIndex >= 0, "setupInference did not create compatible-endpoint"); + assert.ok(inferenceSetIndex >= 0, "setupInference did not configure inference"); + assert.ok( + providerCreateIndex < inferenceSetIndex, + "setupInference configured inference before creating compatible-endpoint", + ); + const expectedDiagnostics = [ /compatible-endpoint/i, /broken-model/i, diff --git a/test/onboarding/onboard-openrouter-inference.test.ts b/test/onboarding/onboard-openrouter-inference.test.ts index 06689101026..a8ff9753563 100644 --- a/test/onboarding/onboard-openrouter-inference.test.ts +++ b/test/onboarding/onboard-openrouter-inference.test.ts @@ -18,6 +18,8 @@ const openrouterRuntimeOnboard = const createDirectSetupInferenceHarness = createDirectSetupInferenceHarnessFactory( onboard.createSetupInference, ); +const OPENROUTER_PROVIDER_METADATA = + "Name: openrouter-api\nType: openai\nCredential keys: OPENROUTER_API_KEY\nConfig keys: OPENAI_BASE_URL\n"; describe("OpenRouter onboarding inference setup", () => { it("configures OpenRouter through the runtime header adapter (#5826)", async () => { @@ -31,6 +33,10 @@ describe("OpenRouter onboarding inference setup", () => { const setupOpenRouterRuntimeInference = openrouterRuntimeOnboard.setupOpenRouterRuntimeInference; const harness = createDirectSetupInferenceHarness({ + runOpenshell: (args) => + args.slice(0, 2).join(" ") === "provider get" + ? { status: 0, stdout: OPENROUTER_PROVIDER_METADATA } + : undefined, overrides: { isNonInteractive: () => true, openrouterRuntimeOnboard: { @@ -131,6 +137,10 @@ describe("OpenRouter onboarding inference setup", () => { const setupOpenRouterRuntimeInference = openrouterRuntimeOnboard.setupOpenRouterRuntimeInference; const harness = createDirectSetupInferenceHarness({ + runOpenshell: (args) => + args.slice(0, 2).join(" ") === "provider get" + ? { status: 0, stdout: OPENROUTER_PROVIDER_METADATA } + : undefined, overrides: { isNonInteractive: () => true, openrouterRuntimeOnboard: { diff --git a/test/onboarding/onboard.test.ts b/test/onboarding/onboard.test.ts index 4c25917b398..1457f3b4473 100644 --- a/test/onboarding/onboard.test.ts +++ b/test/onboarding/onboard.test.ts @@ -789,7 +789,12 @@ const { createSandbox } = require(${onboardPath}); const harness = createDirectSetupInferenceHarness({ runOpenshell: (args) => args.slice(0, 2).join(" ") === "provider get" - ? { status: 0, stdout: "", stderr: "" } + ? { + status: 0, + stdout: + "Name: openai-api\nType: openai\nCredential keys: OPENAI_API_KEY\nConfig keys: OPENAI_BASE_URL\n", + stderr: "", + } : undefined, overrides: { verifyInferenceRoute: route.verifyInferenceRoute }, }); @@ -828,7 +833,12 @@ const { createSandbox } = require(${onboardPath}); const harness = createDirectSetupInferenceHarness({ runOpenshell: (args) => args.slice(0, 2).join(" ") === "provider get" - ? { status: 0, stdout: "", stderr: "" } + ? { + status: 0, + stdout: + "Name: openai-api\nType: openai\nCredential keys: OPENAI_API_KEY\nConfig keys: OPENAI_BASE_URL\n", + stderr: "", + } : undefined, overrides: { verifyInferenceRoute: route.verifyInferenceRoute }, }); diff --git a/test/support/setup-inference-test-harness.ts b/test/support/setup-inference-test-harness.ts index 564ad9f96b7..0632bbf9236 100644 --- a/test/support/setup-inference-test-harness.ts +++ b/test/support/setup-inference-test-harness.ts @@ -309,18 +309,6 @@ export function createDirectSetupInferenceHarnessFactory( stderr: `provider '${providerName}' not found`, }); } - if (routed.status === 0 && !routed.stdout && !routed.stderr) { - return directRunResult({ - ...routed, - stdout: [ - `Name: ${providerName}`, - "Type: openai", - "Credential keys: COMPATIBLE_API_KEY", - "Config keys: OPENAI_BASE_URL", - "", - ].join("\n"), - }); - } } return directRunResult(routed); } @@ -335,14 +323,8 @@ export function createDirectSetupInferenceHarnessFactory( if (args[0] === "provider" && args[1] === "get") { const providerName = args.at(-1) ?? "provider"; return directRunResult({ - status: 0, - stdout: [ - `Name: ${providerName}`, - "Type: openai", - "Credential keys: COMPATIBLE_API_KEY", - "Config keys: OPENAI_BASE_URL", - "", - ].join("\n"), + status: 1, + stderr: `provider '${providerName}' not found`, }); } return directRunResult(); From 70e8eeaef4196b2ba912dcf911ed0c2f77f33acf Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 8 Sep 2026 15:51:06 -0700 Subject: [PATCH 05/10] test: match exact Hermes provider lookup --- test/onboarding/onboard-inference-reconciliation.test.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/test/onboarding/onboard-inference-reconciliation.test.ts b/test/onboarding/onboard-inference-reconciliation.test.ts index 3c5f1cca513..e91bc9884d3 100644 --- a/test/onboarding/onboard-inference-reconciliation.test.ts +++ b/test/onboarding/onboard-inference-reconciliation.test.ts @@ -306,6 +306,7 @@ const prompts = []; const registryUpdates = []; const done = new Error("INFERENCE_STEP_DONE"); let inferenceSessionSnapshot = null; +const hermesApiKeyProviderMetadata = ${JSON.stringify(HERMES_API_KEY_PROVIDER_METADATA)}; delete process.env.NEMOCLAW_NON_INTERACTIVE; delete process.env.NEMOCLAW_SANDBOX_NAME; @@ -329,8 +330,9 @@ try { runner.run = (command, opts = {}) => { const normalized = _n(command); commands.push({ command: normalized, env: opts.env || null }); - if (normalized.includes("provider get") && normalized.includes("hermes-provider")) { - return { status: 0, stdout: ${JSON.stringify(HERMES_API_KEY_PROVIDER_METADATA)}, stderr: "" }; + const providerGet = "provider get -g nemoclaw hermes-provider"; + if (normalized === providerGet || normalized.endsWith(" " + providerGet)) { + return { status: 0, stdout: hermesApiKeyProviderMetadata, stderr: "" }; } return { status: 0, stdout: "", stderr: "" }; }; From 6e43b1112673d48846bcd1f02884ea244e6f3e2b Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 8 Sep 2026 16:01:37 -0700 Subject: [PATCH 06/10] test: match provider commands by token --- .../onboard-inference-smoke.test.ts | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/test/onboarding/onboard-inference-smoke.test.ts b/test/onboarding/onboard-inference-smoke.test.ts index 8bcec16adec..a6dad85250c 100644 --- a/test/onboarding/onboard-inference-smoke.test.ts +++ b/test/onboarding/onboard-inference-smoke.test.ts @@ -16,6 +16,13 @@ import { testTimeoutOptions } from "../helpers/timeouts"; // bash or the scenario framework. Refs #5098, #4349. const REPO_ROOT = path.join(import.meta.dirname, "../.."); +function hasTokenSequence(command: string, sequence: readonly string[]): boolean { + const tokens = command.trim().split(/\s+/); + return tokens.some((_, index) => + sequence.every((expected, offset) => tokens[index + offset] === expected), + ); +} + describe("onboard inference smoke guard (#3253)", () => { it( "rejects a configured OpenAI-compatible route when chat/completions returns 503", @@ -171,11 +178,15 @@ const setupInference = createSetupInference({ const commands = fs.readFileSync(commandLogPath, "utf8").trim().split("\n"); const providerCreateIndex = commands.findIndex( (command) => - command.includes("provider create -g nemoclaw") && - command.includes("--name compatible-endpoint"), + hasTokenSequence(command, ["provider", "create"]) && + hasTokenSequence(command, ["-g", "nemoclaw"]) && + hasTokenSequence(command, ["--name", "compatible-endpoint"]), ); - const inferenceSetIndex = commands.findIndex((command) => - command.includes("inference set -g nemoclaw"), + const inferenceSetIndex = commands.findIndex( + (command) => + hasTokenSequence(command, ["inference", "set"]) && + hasTokenSequence(command, ["-g", "nemoclaw"]) && + hasTokenSequence(command, ["--provider", "compatible-endpoint"]), ); assert.ok(providerCreateIndex >= 0, "setupInference did not create compatible-endpoint"); assert.ok(inferenceSetIndex >= 0, "setupInference did not configure inference"); From 0c9c06345e337a69cfe4243afafc08677d9f56db Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 8 Sep 2026 16:39:38 -0700 Subject: [PATCH 07/10] fix: complete provider adapter migration --- src/lib/onboard.ts | 4 ---- src/lib/onboard/hermes-auth.test.ts | 35 +++++++++++++++++++++++++++++ test/onboarding/onboard.test.ts | 4 ++++ 3 files changed, 39 insertions(+), 4 deletions(-) diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 4847464d0fb..56b99d058da 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -812,9 +812,6 @@ const { promptValidationRecovery } = createValidationRecoveryPromptHelpers({ exitOnboardFromPrompt, }); -// Provider CRUD — thin wrappers that inject runOpenshell to avoid circular deps. -const { buildProviderArgs } = onboardProviders; - // Snapshot of legacy {env-key → value} pairs that stageLegacyCredentialsToEnv() // imported from ~/.nemoclaw/credentials.json at the start of this run. // Captured by the onboard() entry point; consulted by the upsertProvider / @@ -3388,7 +3385,6 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { module.exports = { buildOrphanedSandboxRollbackMessage, - buildProviderArgs, buildGatewayBootstrapSecretsScript, buildCompatibleEndpointSandboxSmokeCommand, buildCompatibleEndpointSandboxSmokeScript, diff --git a/src/lib/onboard/hermes-auth.test.ts b/src/lib/onboard/hermes-auth.test.ts index 2676923446f..9b6fc89f0a2 100644 --- a/src/lib/onboard/hermes-auth.test.ts +++ b/src/lib/onboard/hermes-auth.test.ts @@ -90,6 +90,41 @@ describe("Hermes authentication exit boundaries", () => { }); }); +describe("Hermes provider store availability", () => { + it("lists providers through the selected gateway", async () => { + const runOpenshell = vi.fn(() => ({ + status: 0, + stdout: "hermes-provider\n", + stderr: "", + })); + const helpers = createHermesAuthHelpers(createDeps({ runOpenshell })); + + await expect(helpers.checkHermesProviderStoreReachable()).resolves.toEqual({ ok: true }); + expect(runOpenshell).toHaveBeenCalledWith(["provider", "list", "--names"], { + ignoreError: true, + maxBuffer: 64 * 1024, + stdio: ["ignore", "pipe", "pipe"], + timeout: 10_000, + }); + }); + + it("reports malformed provider inventory as unavailable", async () => { + const runOpenshell = vi.fn(() => ({ status: 0, stdout: "bad/name\n", stderr: "" })); + const helpers = createHermesAuthHelpers(createDeps({ runOpenshell })); + + await expect(helpers.checkHermesProviderStoreReachable()).resolves.toEqual({ + ok: false, + message: "OpenShell returned an invalid provider inventory.", + }); + expect(runOpenshell).toHaveBeenCalledWith(["provider", "list", "--names"], { + ignoreError: true, + maxBuffer: 64 * 1024, + stdio: ["ignore", "pipe", "pipe"], + timeout: 10_000, + }); + }); +}); + describe("Hermes authentication selection", () => { it("selects API key authentication non-interactively when a key already exists", async () => { clearHermesAuthEnvironment(); diff --git a/test/onboarding/onboard.test.ts b/test/onboarding/onboard.test.ts index 1457f3b4473..ad4de0293dd 100644 --- a/test/onboarding/onboard.test.ts +++ b/test/onboarding/onboard.test.ts @@ -101,6 +101,10 @@ const createDirectSetupInferenceHarness = createDirectSetupInferenceHarnessFactory(createSetupInference); describe("onboard helpers", () => { + it("does not expose the removed provider argument builder", () => { + expect(loadedOnboardInternals).not.toHaveProperty("buildProviderArgs"); + }); + it("does not treat an empty policy preset selection as already applied (#6042)", () => { expect(arePolicyPresetsApplied("unused", [])).toBe(false); }); From 6d6f3216704f45cfdbebff7521a722a0e392ae35 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 8 Sep 2026 16:57:15 -0700 Subject: [PATCH 08/10] test: focus Hermes provider store contract --- src/lib/onboard/hermes-auth.test.ts | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/src/lib/onboard/hermes-auth.test.ts b/src/lib/onboard/hermes-auth.test.ts index 9b6fc89f0a2..01f643c632b 100644 --- a/src/lib/onboard/hermes-auth.test.ts +++ b/src/lib/onboard/hermes-auth.test.ts @@ -100,12 +100,10 @@ describe("Hermes provider store availability", () => { const helpers = createHermesAuthHelpers(createDeps({ runOpenshell })); await expect(helpers.checkHermesProviderStoreReachable()).resolves.toEqual({ ok: true }); - expect(runOpenshell).toHaveBeenCalledWith(["provider", "list", "--names"], { - ignoreError: true, - maxBuffer: 64 * 1024, - stdio: ["ignore", "pipe", "pipe"], - timeout: 10_000, - }); + expect(runOpenshell).toHaveBeenCalledWith( + ["provider", "list", "--names"], + expect.objectContaining({ timeout: 10_000 }), + ); }); it("reports malformed provider inventory as unavailable", async () => { @@ -116,12 +114,10 @@ describe("Hermes provider store availability", () => { ok: false, message: "OpenShell returned an invalid provider inventory.", }); - expect(runOpenshell).toHaveBeenCalledWith(["provider", "list", "--names"], { - ignoreError: true, - maxBuffer: 64 * 1024, - stdio: ["ignore", "pipe", "pipe"], - timeout: 10_000, - }); + expect(runOpenshell).toHaveBeenCalledWith( + ["provider", "list", "--names"], + expect.objectContaining({ timeout: 10_000 }), + ); }); }); From 0f1dfbeef1df21fd598af185f1c7bb40c2b8fdb1 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 8 Sep 2026 18:02:11 -0700 Subject: [PATCH 09/10] refactor: remove eager provider reconciliation wrapper --- ...rovider-reconciliation-diagnostics.test.ts | 2 +- ...tra-provider-reconciliation-probes.test.ts | 25 +++++++++---------- ...a-provider-reconciliation.test-fixtures.ts | 9 +++---- .../extra-provider-reconciliation.test.ts | 25 +++++++++++-------- .../onboard/extra-provider-reconciliation.ts | 10 -------- src/lib/onboard/sandbox-provider-cleanup.ts | 5 +--- 6 files changed, 32 insertions(+), 44 deletions(-) diff --git a/src/lib/onboard/extra-provider-reconciliation-diagnostics.test.ts b/src/lib/onboard/extra-provider-reconciliation-diagnostics.test.ts index 2952112051a..4efe2045d1e 100644 --- a/src/lib/onboard/extra-provider-reconciliation-diagnostics.test.ts +++ b/src/lib/onboard/extra-provider-reconciliation-diagnostics.test.ts @@ -10,7 +10,7 @@ const exactWrappedDiagnostic = [ " │ --name stale-provider`", ].join("\n"); -describe("reconcileRegisteredExtraProviders diagnostics", () => { +describe("planRegisteredExtraProviders diagnostics", () => { it.each([ { label: "single-quoted CLI", diff --git a/src/lib/onboard/extra-provider-reconciliation-probes.test.ts b/src/lib/onboard/extra-provider-reconciliation-probes.test.ts index cc83a512bf1..f1b0f09f248 100644 --- a/src/lib/onboard/extra-provider-reconciliation-probes.test.ts +++ b/src/lib/onboard/extra-provider-reconciliation-probes.test.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { afterEach, describe, expect, it, vi } from "vitest"; -import { reconcileRegisteredExtraProviders } from "./extra-provider-reconciliation"; +import { planRegisteredExtraProviders } from "./extra-provider-reconciliation"; import { missing, ok, @@ -14,7 +14,7 @@ afterEach(() => { vi.unstubAllEnvs(); }); -describe("reconcileRegisteredExtraProviders probe outcomes", () => { +describe("planRegisteredExtraProviders probe outcomes", () => { it("preserves providers when raw probe failures lack classifiable adapter diagnostics (#6501)", async () => { const warn = vi.fn(); const recorded = [ @@ -67,13 +67,14 @@ describe("reconcileRegisteredExtraProviders probe outcomes", () => { const recorded = ["provider-1", "provider-2", "provider-3", "provider-4", "provider-5"]; expect( - await reconcileRegisteredExtraProviders("nemoclaw", { - listExtraProviders: () => [...recorded], - nowMs: () => now, - removeExtraProvider: () => true, - runOpenshell, - warn, - }), + ( + await planRegisteredExtraProviders("nemoclaw", { + listExtraProviders: () => [...recorded], + nowMs: () => now, + runOpenshell, + warn, + }) + ).extraProviders, ).toEqual(recorded); expect(runOpenshell).toHaveBeenCalledTimes(3); expect(timeouts).toEqual([5_000, 5_000, 5_000]); @@ -88,17 +89,15 @@ describe("reconcileRegisteredExtraProviders probe outcomes", () => { vi.stubEnv("OPENSHELL_GATEWAY_ENDPOINT", "https://other.example.test"); await expect( - reconcileRegisteredExtraProviders("nemoclaw", { + planRegisteredExtraProviders("nemoclaw", { listExtraProviders: () => ["custom-provider"], - removeExtraProvider: () => true, runOpenshell, }), ).rejects.toThrow(/OPENSHELL_GATEWAY_ENDPOINT is set/); vi.unstubAllEnvs(); await expect( - reconcileRegisteredExtraProviders("", { + planRegisteredExtraProviders("", { listExtraProviders: () => ["custom-provider"], - removeExtraProvider: () => true, runOpenshell, }), ).rejects.toThrow("OpenShell gateway name is required."); diff --git a/src/lib/onboard/extra-provider-reconciliation.test-fixtures.ts b/src/lib/onboard/extra-provider-reconciliation.test-fixtures.ts index 1fb245db1f3..bc290df9012 100644 --- a/src/lib/onboard/extra-provider-reconciliation.test-fixtures.ts +++ b/src/lib/onboard/extra-provider-reconciliation.test-fixtures.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { vi } from "vitest"; -import { reconcileRegisteredExtraProviders } from "./extra-provider-reconciliation"; +import { planRegisteredExtraProviders } from "./extra-provider-reconciliation"; export type ProbeResult = { status: number | null; @@ -24,16 +24,15 @@ export const missing = (name: string): ProbeResult => ({ export function reconcile( recorded: string[], responses: Record ProbeResult)> = {}, - extra: Partial[1]> = {}, + extra: Partial[1]> = {}, ): Promise { - return reconcileRegisteredExtraProviders("nemoclaw", { + return planRegisteredExtraProviders("nemoclaw", { listExtraProviders: () => [...recorded], - removeExtraProvider: () => true, runOpenshell: vi.fn((args: string[]): ProbeResult => { const response = responses[args.at(-1) ?? ""]; return typeof response === "function" ? response() : (response ?? ok()); }), warn: () => undefined, ...extra, - }); + }).then((plan) => [...plan.extraProviders]); } diff --git a/src/lib/onboard/extra-provider-reconciliation.test.ts b/src/lib/onboard/extra-provider-reconciliation.test.ts index 81542988d88..b926f21034a 100644 --- a/src/lib/onboard/extra-provider-reconciliation.test.ts +++ b/src/lib/onboard/extra-provider-reconciliation.test.ts @@ -5,7 +5,6 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { applyExtraProviderReconciliation, planRegisteredExtraProviders, - reconcileRegisteredExtraProviders, } from "./extra-provider-reconciliation"; import { LIMIT, @@ -19,16 +18,16 @@ afterEach(() => { vi.unstubAllEnvs(); }); -describe("reconcileRegisteredExtraProviders", () => { +describe("planRegisteredExtraProviders", () => { it("skips gateway probes when no extra provider is recorded (#6501)", async () => { const runOpenshell = vi.fn((): ProbeResult => ok()); expect( - await reconcileRegisteredExtraProviders("nemoclaw", { + await planRegisteredExtraProviders("nemoclaw", { listExtraProviders: () => [], runOpenshell, }), - ).toEqual([]); + ).toEqual({ extraProviders: [], staleExtraProviders: [] }); expect(runOpenshell).not.toHaveBeenCalled(); }); @@ -44,13 +43,17 @@ describe("reconcileRegisteredExtraProviders", () => { return args.at(-1) === "custom-provider-127" ? missing("custom-provider-127") : ok(); }); - expect( - await reconcileRegisteredExtraProviders("nemoclaw", { - listExtraProviders: () => [...recorded], - removeExtraProvider, - runOpenshell, - }), - ).toEqual(recorded.slice(0, -1)); + const plan = await planRegisteredExtraProviders("nemoclaw", { + listExtraProviders: () => [...recorded], + removeExtraProvider, + runOpenshell, + }); + expect(plan).toEqual({ + extraProviders: recorded.slice(0, -1), + staleExtraProviders: ["custom-provider-127"], + }); + expect(removeExtraProvider).not.toHaveBeenCalled(); + applyExtraProviderReconciliation(plan, { removeExtraProvider }); expect(removeExtraProvider).toHaveBeenCalledWith("custom-provider-127"); expect(calls).toHaveLength(recorded.length); expect(calls.some(({ args }) => args.includes("list") || args.includes("--names"))).toBe(false); diff --git a/src/lib/onboard/extra-provider-reconciliation.ts b/src/lib/onboard/extra-provider-reconciliation.ts index 5abfe1c5e05..09532ac9a4d 100644 --- a/src/lib/onboard/extra-provider-reconciliation.ts +++ b/src/lib/onboard/extra-provider-reconciliation.ts @@ -189,13 +189,3 @@ export function applyExtraProviderReconciliation( const removeExtraProvider = deps.removeExtraProvider ?? defaultRemoveExtraProvider; for (const name of plan.staleExtraProviders) removeExtraProvider(name); } - -export async function reconcileRegisteredExtraProviders( - gatewayName: string, - deps: ReconcileExtraProvidersDeps = {}, -): Promise { - // Compatibility wrapper for focused #6501 tests; remove with that defensive prune. - const plan = await planRegisteredExtraProviders(gatewayName, deps); - applyExtraProviderReconciliation(plan, deps); - return [...plan.extraProviders]; -} diff --git a/src/lib/onboard/sandbox-provider-cleanup.ts b/src/lib/onboard/sandbox-provider-cleanup.ts index 407630ec44b..de129f16b87 100644 --- a/src/lib/onboard/sandbox-provider-cleanup.ts +++ b/src/lib/onboard/sandbox-provider-cleanup.ts @@ -10,7 +10,6 @@ export { type ExtraProviderReconciliationPlan, planRegisteredExtraProviders, type ReconcileExtraProvidersDeps, - reconcileRegisteredExtraProviders, } from "./extra-provider-reconciliation"; export function removeManagedHermesStateVolume( context: import("./managed-workload/hermes-state-volume").ManagedHermesStateVolumeContext, @@ -161,9 +160,7 @@ export function detachSandboxProviders( // OpenShell resolves provider detach by mutable sandbox name. These checks detect // replacement and stop later detaches; they do not make this command an atomic, // identity-bound mutation. Operators must not mutate the sandbox concurrently. - deps.revalidateSandboxIdentity?.( - `detaching provider '${name}' from sandbox '${sandboxName}'`, - ); + deps.revalidateSandboxIdentity?.(`detaching provider '${name}' from sandbox '${sandboxName}'`); const result = runOpenshell(["sandbox", "provider", "detach", sandboxName, name], { ignoreError: true, stdio: ["ignore", "pipe", "pipe"], From 370fd71e588cb92e4466662d56c930f8e82cebb5 Mon Sep 17 00:00:00 2001 From: Rebecca Sliter <571084+rsliter@users.noreply.github.com> Date: Tue, 8 Sep 2026 18:43:22 -0700 Subject: [PATCH 10/10] fix: reconcile providers inside creation lock --- .../sandbox-route-mutation-lock.test.ts | 39 ++++++++++++++++--- src/lib/onboard/machine/handlers/sandbox.ts | 6 +-- 2 files changed, 37 insertions(+), 8 deletions(-) diff --git a/src/lib/onboard/machine/handlers/sandbox-route-mutation-lock.test.ts b/src/lib/onboard/machine/handlers/sandbox-route-mutation-lock.test.ts index 6b6c76e5884..61ad50c99b2 100644 --- a/src/lib/onboard/machine/handlers/sandbox-route-mutation-lock.test.ts +++ b/src/lib/onboard/machine/handlers/sandbox-route-mutation-lock.test.ts @@ -51,6 +51,18 @@ describe("sandbox registration route transaction", () => { it("stages credentials, then holds sandbox, host dashboard, and gateway locks through creation", async () => { const events: string[] = []; + let releaseProviderPlan!: () => void; + const providerPlanReleased = new Promise((resolve) => { + releaseProviderPlan = resolve; + }); + let reportProviderPlanEntered!: () => void; + const providerPlanEntered = new Promise((resolve) => { + reportProviderPlanEntered = resolve; + }); + const createSandbox = vi.fn(async () => { + events.push("create"); + return "my-assistant"; + }); const { deps } = createDeps({ configureWebSearch: vi.fn(async () => ({ fetchEnabled: true as const, @@ -72,14 +84,17 @@ describe("sandbox registration route transaction", () => { events.push("gateway-lock"); return await operation(); }, + planRegisteredExtraProviders: async () => { + events.push("provider-plan"); + reportProviderPlanEntered(); + await providerPlanReleased; + return { extraProviders: [], staleExtraProviders: [] }; + }, stageSandboxCredentialProviders: async () => { events.push("stage"); return []; }, - createSandbox: async () => { - events.push("create"); - return "my-assistant"; - }, + createSandbox, finalizeSandboxRouteReservation: () => { events.push("publish"); return true; @@ -89,7 +104,20 @@ describe("sandbox registration route transaction", () => { }, }); - await expect(handleSandboxState(baseOptions(deps))).resolves.toMatchObject({ + const onboard = handleSandboxState(baseOptions(deps)); + await providerPlanEntered; + expect(events).toEqual([ + "gateway-lock", + "stage", + "sandbox-lock", + "dashboard-lock", + "gateway-lock", + "provider-plan", + ]); + expect(createSandbox).not.toHaveBeenCalled(); + releaseProviderPlan(); + + await expect(onboard).resolves.toMatchObject({ sandboxName: "my-assistant", }); expect(events).toEqual([ @@ -98,6 +126,7 @@ describe("sandbox registration route transaction", () => { "sandbox-lock", "dashboard-lock", "gateway-lock", + "provider-plan", "guard", "create", "registry", diff --git a/src/lib/onboard/machine/handlers/sandbox.ts b/src/lib/onboard/machine/handlers/sandbox.ts index e920ebde768..98a68a72b79 100644 --- a/src/lib/onboard/machine/handlers/sandbox.ts +++ b/src/lib/onboard/machine/handlers/sandbox.ts @@ -2135,14 +2135,14 @@ class SandboxStateFlow< state.webSearchConfig as unknown as SharedWebSearchConfig | null, this.options.hermesToolGateways, ); - const extraProviderPlan = await this.deps.planRegisteredExtraProviders( - this.options.gatewayName, - ); const createAndRecord = async (): Promise> => { this.assertRegistryMessagingPlanUnchanged( requestedSandboxName, registryMessagingAuthoritySnapshot, ); + const extraProviderPlan = await this.deps.planRegisteredExtraProviders( + this.options.gatewayName, + ); if ( this.options.apfInterceptorRequested === true && (extraProviderPlan.extraProviders.length > 0 ||