diff --git a/docs/deployment/register-external-component.mdx b/docs/deployment/register-external-component.mdx index 23091270e9c..e17d16f53bd 100644 --- a/docs/deployment/register-external-component.mdx +++ b/docs/deployment/register-external-component.mdx @@ -30,12 +30,14 @@ The component owner must operate its service, sockets, credentials, resources, a Version 1 does not support these operations or configurations: - Resume, reuse, repair, rebuild, recreation, or migration. -- Providerless Agent Policy Framework (APF) interceptor onboarding. +- Providerless component onboarding with NemoClaw-supplied initial policy. - An externally supervised OpenShell gateway. - More than one registered component. - Generic shell commands, repository commands, vendor adapters, or a new OpenShell provider attachment API. Onboarding without the declaration uses the existing onboarding behavior. +Registration alone does not select providerless onboarding. +Ordinary onboarding with a registered component keeps NemoClaw's initial policy and provider setup. ## Create the Declaration @@ -129,6 +131,32 @@ The policy version must match the live sandbox observation. NemoClaw sends identity to the component only after these checks pass. + + +### Select Interceptor-Supplied Policy + +To use the registered component for fresh providerless onboarding, explicitly select `--apf-interceptor`: + +```bash +nemoclaw onboard --fresh --apf-interceptor --name component-sandbox +``` + +The component must supply sandbox policy through the existing OpenShell `CreateSandbox` interceptor contract. +A generic component can implement this contract; no specific policy framework is required. +The [providerless onboarding prerequisites](../reference/commands#--apf-interceptor) also apply. + +NemoClaw supplies no initial policy, creates no providers, and handles no component credentials in this flow. +Any providers required by the component's policy must resolve through existing OpenShell mechanisms before activation. +Missing, invalid, or unresolved policy or provider requirements stop onboarding before activation. +NemoClaw does not substitute its own policy or switch to ordinary onboarding. + +After OpenShell creates the sandbox, NemoClaw verifies its immutable identity and effective policy before invoking the same activation endpoint described below. +Completion requires successful bounded activation and post-response verification. +This flow skips ordinary agent configuration, policy selection, and inference setup. +Providerless onboarding without a registered component retains its existing behavior. + + + ## Implement the Activation Endpoint NemoClaw sends one HTTP/1.1 request over `activationSocketPath`. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index a831555ce31..9d9f567385b 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -449,7 +449,9 @@ Without the lock, it preserves the foreign reservation. #### `--apf-interceptor` -Use this option to request a policyless sandbox creation for an APF-interceptor flow. This option currently supports providerless sandbox creation only. APF onboarding with an inference provider and model is not yet supported. APF onboarding with an OpenShell provider for a Model Context Protocol (MCP) server is also not yet supported. OpenShell cannot bind provider attachment to the new sandbox's verified immutable ID. If the prepared plan contains any provider, NemoClaw exits before it: +Use this option to request sandbox creation without a NemoClaw-supplied policy. +This option supports providerless onboarding only; NemoClaw does not configure an inference provider, model, or credential provider in this mode. +If NemoClaw's prepared plan contains any provider, it exits before it: - Creates the sandbox. - Registers or changes credentials. @@ -465,6 +467,12 @@ The option requires these conditions: NemoClaw omits a caller policy from every sandbox creation attempt. After creation, NemoClaw binds the returned durable sandbox identity and verifies its effective policy. The policy must be sandbox-scoped and contain every policy entry required by the prepared configuration. NemoClaw stores no policy owner, receipt, or desired state; later policy commands read OpenShell directly. This verification does not establish that APF injected the policy. +With one [registered external component](../deployment/register-external-component#select-interceptor-supplied-policy), the component supplies policy through the existing OpenShell interceptor contract. +Required providers must resolve through existing OpenShell mechanisms before activation. +NemoClaw activates the component only after verifying immutable sandbox identity and effective policy, then verifies them again after the response. +Missing or invalid policy does not trigger a fallback to NemoClaw policy or ordinary onboarding. +Registration alone does not select this option. + ```bash $$nemoclaw onboard --fresh --apf-interceptor --name my-apf-sandbox ``` diff --git a/src/lib/onboard/external-component/onboarding.test.ts b/src/lib/onboard/external-component/onboarding.test.ts index b406d360418..8b25285a32c 100644 --- a/src/lib/onboard/external-component/onboarding.test.ts +++ b/src/lib/onboard/external-component/onboarding.test.ts @@ -218,18 +218,14 @@ describe("external component onboarding lifecycle", () => { } }); - it("rejects APF onboarding when a component is registered (#11340)", () => { - mocks.loadExternalComponentDeclaration.mockReturnValue({} as never); - - expect(() => - prepareExternalComponent({ - externalComponentActivation: null, - apfInterceptorRequested: true, - }), - ).toThrowError( - expect.objectContaining>({ - code: "lifecycle_unsupported", - }), - ); - }); + it.each([true, false])( + "preserves registration with providerless selection %s (#11486)", + (apfInterceptorRequested) => { + const component = {} as PreparedExternalComponent; + mocks.loadExternalComponentDeclaration.mockReturnValue(component); + expect(prepareExternalComponent({ apfInterceptorRequested })).toBe(component); + mocks.loadExternalComponentDeclaration.mockReturnValue(null); + expect(prepareExternalComponent({ apfInterceptorRequested })).toBeNull(); + }, + ); }); diff --git a/src/lib/onboard/external-component/onboarding.ts b/src/lib/onboard/external-component/onboarding.ts index 94e888f6345..924af38d786 100644 --- a/src/lib/onboard/external-component/onboarding.ts +++ b/src/lib/onboard/external-component/onboarding.ts @@ -20,11 +20,7 @@ export function prepareExternalComponent( } | null, ): PreparedExternalComponent | null { assertNoIncompleteExternalComponentActivation(session); - const externalComponent = loadExternalComponentDeclaration(); - if (externalComponent && session?.apfInterceptorRequested === true) { - throw new ExternalComponentContractError("lifecycle_unsupported"); - } - return externalComponent; + return loadExternalComponentDeclaration(); } export function assertNoIncompleteExternalComponentActivation( diff --git a/src/lib/onboard/external-component/proof.test.ts b/src/lib/onboard/external-component/proof.test.ts index 00d947e5dee..80db12420c4 100644 --- a/src/lib/onboard/external-component/proof.test.ts +++ b/src/lib/onboard/external-component/proof.test.ts @@ -52,24 +52,49 @@ function fixture() { } describe("external component activation proof", () => { - it("binds the durable OpenShell identity to the effective policy (#11340)", () => { - const { deps } = fixture(); + it.each([policyHash, policyHash.slice("sha256:".length)])( + "binds the durable OpenShell identity to policy digest %s (#11486)", + (hash) => { + const { deps, inspection } = fixture(); + inspection.policyIdentity.hash = hash; + + const proof = createExternalComponentActivationProof("assistant", "nemoclaw", deps); + + expect(proof).toMatchObject({ + gatewayName: "nemoclaw", + sandboxId, + sandboxIdentityFingerprint: `sha256:${fingerprintOpenShellSandboxId(sandboxId)}`, + lifecycleGeneration: "generation-1", + policySource: "sandbox", + policyHash, + policyActiveVersion: 3, + }); + expect(deps.inspectPolicy).toHaveBeenCalledWith( + "assistant", + "verify external component activation policy", + "nemoclaw", + ); + }, + ); + it("rejects a changed OpenShell digest after activation (#11486)", () => { + const { deps, inspection } = fixture(); + inspection.policyIdentity.hash = "a".repeat(64); const proof = createExternalComponentActivationProof("assistant", "nemoclaw", deps); + inspection.policyIdentity.hash = "b".repeat(64); + expect(() => proof.revalidate("after_activation")).toThrow(ExternalComponentProofError); + }); - expect(proof).toMatchObject({ - gatewayName: "nemoclaw", - sandboxId, - sandboxIdentityFingerprint: `sha256:${fingerprintOpenShellSandboxId(sandboxId)}`, - lifecycleGeneration: "generation-1", - policySource: "sandbox", - policyHash, - policyActiveVersion: 3, - }); - expect(deps.inspectPolicy).toHaveBeenCalledWith( - "assistant", - "verify external component activation policy", - "nemoclaw", + it.each([ + "a".repeat(63), + "a".repeat(65), + `sha256:sha256:${"a".repeat(64)}`, + `sha512:${"a".repeat(64)}`, + ])("rejects malformed policy digest %s (#11486)", (hash) => { + const { deps, inspection } = fixture(); + inspection.policyIdentity.hash = hash; + expect(() => createExternalComponentActivationProof("assistant", "nemoclaw", deps)).toThrow( + ExternalComponentProofError, ); }); diff --git a/src/lib/onboard/external-component/proof.ts b/src/lib/onboard/external-component/proof.ts index 4e9f8dad759..78f3f8b0a65 100644 --- a/src/lib/onboard/external-component/proof.ts +++ b/src/lib/onboard/external-component/proof.ts @@ -81,11 +81,12 @@ function captureProofSnapshotUnchecked( "verify external component activation policy", expectedGatewayName, ); + const policyDigest = policy.inspection.policyIdentity.hash.replace(/^sha256:/u, ""); if ( policy.gatewayName !== expectedGatewayName || policy.inspection.policySource !== "sandbox" || row.current_policy_version !== policy.inspection.policyIdentity.activeVersion || - !/^sha256:[0-9a-f]{64}$/u.test(policy.inspection.policyIdentity.hash) + !/^[0-9a-f]{64}$/u.test(policyDigest) ) { throw new ExternalComponentProofError(); } @@ -101,7 +102,7 @@ function captureProofSnapshotUnchecked( gatewayName: expectedGatewayName, lifecycleGeneration: entry.lifecycleGeneration, policyActiveVersion: policy.inspection.policyIdentity.activeVersion, - policyHash: policy.inspection.policyIdentity.hash, + policyHash: `sha256:${policyDigest}`, policySource: policy.inspection.policySource, sandboxId: row.id, sandboxIdentityFingerprint: `sha256:${fingerprint}`, diff --git a/src/lib/onboard/machine/core-flow-phases.test.ts b/src/lib/onboard/machine/core-flow-phases.test.ts index cf952760063..c39c9d9440c 100644 --- a/src/lib/onboard/machine/core-flow-phases.test.ts +++ b/src/lib/onboard/machine/core-flow-phases.test.ts @@ -833,112 +833,129 @@ describe("core onboard flow phases", () => { expect(reserveSandboxInferenceRoute).not.toHaveBeenCalled(); }); - it("completes providerless APF after the verified sandbox-create boundary", async () => { - const setupNim = vi.fn(); - const setupInference = vi.fn(async () => ({ ok: true as const })); - let providerlessReservation: { - name: string; - gatewayName: string; - pendingRouteReservation: true; - reservationSessionId?: string; - provider: string | null; - model: string | null; - endpointUrl: string | null; - endpointSource: InferenceEndpointSource | null; - credentialEnv: string | null; - preferredInferenceApi: string | null; - } | null = null; - const reserveRoute = vi.fn( - ( - name: string, - route: Parameters[1], - ) => { - providerlessReservation = { - name, - pendingRouteReservation: true, - ...route, - }; - return true; - }, - ); - const updateSandboxRegistry = vi.fn(); - const recordStepComplete = vi.fn(async (_stepName: string, updates: SessionUpdates = {}) => { - Object.assign(session, updates); - return session; - }); - const createSandbox = vi.fn(async (...args: unknown[]) => { - expect(args[1]).toBe(""); - expect(args[2]).toBe(""); - expect(args[15]).toMatchObject({ - apfInterceptorRequested: true, - deferSandboxEffectsUntilIdentityVerification: true, + it.each([false, true])( + "routes verified providerless creation with component %s (#11486)", + async (registered) => { + const setupNim = vi.fn(); + const setupInference = vi.fn(async () => ({ ok: true as const })); + let providerlessReservation: { + name: string; + gatewayName: string; + pendingRouteReservation: true; + reservationSessionId?: string; + provider: string | null; + model: string | null; + endpointUrl: string | null; + endpointSource: InferenceEndpointSource | null; + credentialEnv: string | null; + preferredInferenceApi: string | null; + } | null = null; + const reserveRoute = vi.fn( + ( + name: string, + route: Parameters[1], + ) => { + providerlessReservation = { + name, + pendingRouteReservation: true, + ...route, + }; + return true; + }, + ); + const updateSandboxRegistry = vi.fn(); + const recordStepComplete = vi.fn(async (_stepName: string, updates: SessionUpdates = {}) => { + Object.assign(session, updates); + return session; }); - return "created-sandbox"; - }); - const session = createSession({ apfInterceptorRequested: true }); - const { providerInference: providerPhase, sandbox: sandboxPhase } = createPhases({ - providerEnv: { NEMOCLAW_WEB_SEARCH_PROVIDER: "none" }, - providerDeps: { - reserveSandboxInferenceRoute: reserveRoute, - setupInference, - setupNim, - }, - sandboxOptions: { apfInterceptorRequested: true }, - sandboxDeps: { - createSandbox, - getSandboxRegistryEntry: () => providerlessReservation, - recordStepComplete, - setupMessagingChannels: vi.fn(async () => []), - updateSandboxRegistry, - }, - }); - const initial = context({ - fresh: true, - session, - model: null, - provider: null, - selectedMessagingChannels: [], - }); - - const providerResult = await providerPhase.run(initial); - expect(providerResult.result).toEqual([ - advanceTo("inference", { - metadata: { state: "provider_selection", providerlessApf: true }, - }), - advanceTo("sandbox", { - metadata: { state: "inference", providerlessApf: true }, - }), - ]); - expect(reserveRoute).toHaveBeenCalledWith( - "my-sandbox", - expect.objectContaining({ - provider: null, + const createSandbox = vi.fn(async (...args: unknown[]) => { + expect(args[1]).toBe(""); + expect(args[2]).toBe(""); + expect(args[15]).toMatchObject({ + apfInterceptorRequested: true, + deferSandboxEffectsUntilIdentityVerification: true, + }); + return "created-sandbox"; + }); + const session = createSession({ apfInterceptorRequested: true }); + const { providerInference: providerPhase, sandbox: sandboxPhase } = createPhases({ + providerEnv: { NEMOCLAW_WEB_SEARCH_PROVIDER: "none" }, + providerDeps: { + reserveSandboxInferenceRoute: reserveRoute, + setupInference, + setupNim, + }, + sandboxOptions: { apfInterceptorRequested: true }, + sandboxDeps: { + createSandbox, + getSandboxRegistryEntry: () => providerlessReservation, + recordStepComplete, + setupMessagingChannels: vi.fn(async () => []), + updateSandboxRegistry, + }, + }); + const initial = context({ + fresh: true, + session, model: null, - gatewayName: "nemoclaw", - reservationSessionId: session.sessionId, - }), - { requireAbsent: true }, - ); - const sandboxResult = await sandboxPhase.run(providerResult.context); + provider: null, + selectedMessagingChannels: [], + externalComponent: registered + ? { + declaration: { + schemaVersion: 1, + componentId: "policy-governance", + interceptorSocketPath: "/run/component/interceptor.sock", + activationSocketPath: "/run/component/activation.sock", + }, + revalidateBeforeGateway: vi.fn(), + revalidateBeforeActivation: vi.fn(), + } + : null, + }); - expect(sandboxResult.result).toMatchObject({ type: "complete" }); - expect( - isCoreFlowCompleteBeforeFinalization({ - context: sandboxResult.context, - session: { machine: { state: "complete" } }, - }), - ).toBe(true); - expect(setupNim).not.toHaveBeenCalled(); - expect(setupInference).not.toHaveBeenCalled(); - expect(createSandbox).toHaveBeenCalledOnce(); - expect(updateSandboxRegistry).toHaveBeenCalledWith( - "created-sandbox", - expect.not.objectContaining({ model: expect.anything(), provider: expect.anything() }), - ); - const sandboxCompletion = recordStepComplete.mock.calls.find(([step]) => step === "sandbox"); - expect(sandboxCompletion?.[1]).not.toHaveProperty("model"); - expect(sandboxCompletion?.[1]).not.toHaveProperty("provider"); - }); + const providerResult = await providerPhase.run(initial); + expect(providerResult.result).toEqual([ + advanceTo("inference", { + metadata: { state: "provider_selection", providerlessApf: true }, + }), + advanceTo("sandbox", { + metadata: { state: "inference", providerlessApf: true }, + }), + ]); + expect(reserveRoute).toHaveBeenCalledWith( + "my-sandbox", + expect.objectContaining({ + provider: null, + model: null, + gatewayName: "nemoclaw", + reservationSessionId: session.sessionId, + }), + { requireAbsent: true }, + ); + const sandboxResult = await sandboxPhase.run(providerResult.context); + + expect(sandboxResult.result).toMatchObject( + registered ? { type: "transition", next: "agent_setup" } : { type: "complete" }, + ); + expect( + isCoreFlowCompleteBeforeFinalization({ + context: sandboxResult.context, + session: { machine: { state: "complete" } }, + }), + ).toBe(!registered); + expect(setupNim).not.toHaveBeenCalled(); + expect(setupInference).not.toHaveBeenCalled(); + expect(createSandbox).toHaveBeenCalledOnce(); + expect(updateSandboxRegistry).toHaveBeenCalledWith( + "created-sandbox", + expect.not.objectContaining({ model: expect.anything(), provider: expect.anything() }), + ); + const sandboxCompletion = recordStepComplete.mock.calls.find(([step]) => step === "sandbox"); + expect(sandboxCompletion?.[1]).not.toHaveProperty("model"); + expect(sandboxCompletion?.[1]).not.toHaveProperty("provider"); + }, + ); it.each([ ["registered", true, false], diff --git a/src/lib/onboard/machine/core-flow-phases.ts b/src/lib/onboard/machine/core-flow-phases.ts index 37ee9503384..9e03e90df77 100644 --- a/src/lib/onboard/machine/core-flow-phases.ts +++ b/src/lib/onboard/machine/core-flow-phases.ts @@ -110,11 +110,15 @@ interface EndpointProvenance { } export function isCoreFlowCompleteBeforeFinalization(result: { - readonly context: Pick; + readonly context: Pick< + OnboardFlowContext, + "providerlessApf" | "sandboxName" | "externalComponent" + >; readonly session: { readonly machine: { readonly state: string } }; }): boolean { return ( result.context.providerlessApf === true && + !result.context.externalComponent && result.session.machine.state === "complete" && Boolean(result.context.sandboxName) ); diff --git a/src/lib/onboard/machine/final-flow-phases.test.ts b/src/lib/onboard/machine/final-flow-phases.test.ts index f08d5aceedc..10ff8bbf6ea 100644 --- a/src/lib/onboard/machine/final-flow-phases.test.ts +++ b/src/lib/onboard/machine/final-flow-phases.test.ts @@ -2,12 +2,97 @@ // SPDX-License-Identifier: Apache-2.0 import { describe, expect, it, vi } from "vitest"; -import { context, createPhases } from "../../../../test/helpers/onboard-final-flow-phases"; +import { + context, + createPhases, + createProviderlessComponentFlow, +} from "../../../../test/helpers/onboard-final-flow-phases"; import { createSession } from "../../state/onboard-session"; import { runFinalOnboardFlowSlice } from "./final-flow-phases"; import { advanceTo } from "./result"; describe("final onboard flow phases", () => { + it("completes providerless onboarding only after verified component activation (#11486)", async () => { + const flow = createProviderlessComponentFlow(); + const result = await flow.run(); + expect(result.session.machine.state).toBe("complete"); + expect(flow.transport).toHaveBeenCalledOnce(); + expect(flow.revalidate).toHaveBeenCalledTimes(2); + expect(flow.evidence).toHaveBeenLastCalledWith(null); + expect(flow.order).toEqual(["verify-proof", "activate"]); + await expect(createPhases("openclaw")[3].run(flow.initial)).rejects.toThrow( + "Providerless component activation has not completed in this onboarding run.", + ); + }); + + it("preserves failed providerless activation evidence after rejection (#11486)", async () => { + const flow = createProviderlessComponentFlow(); + flow.response.result = "rejected"; + const result = await flow.run(); + expect(result.session.machine.state).toBe("finalizing"); + expect(result.session.externalComponentActivation).toMatchObject({ + sandboxIdentityFingerprint: flow.proof.sandboxIdentityFingerprint, + lifecycleGeneration: flow.proof.lifecycleGeneration, + resultClass: "failed", + }); + expect(flow.transport).toHaveBeenCalledOnce(); + expect(flow.order).toEqual(["verify-proof", "activate"]); + }); + + it.each([ + { + outcome: "malformed response", + arrange: (flow: ReturnType) => + flow.transport.mockResolvedValue("{}"), + requests: 1, + order: ["verify-proof", "activate"], + }, + { + outcome: "changed endpoint", + arrange: (flow: ReturnType) => + flow.revalidateEndpoint.mockImplementation(() => { + throw new Error("changed endpoint"); + }), + requests: 0, + order: ["verify-proof"], + }, + { + outcome: "changed identity or policy proof", + arrange: (flow: ReturnType) => + flow.revalidate + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => { + throw new Error("drift"); + }), + requests: 1, + order: ["verify-proof", "activate"], + }, + ])( + "preserves ambiguous providerless activation evidence for $outcome (#11486)", + async ({ arrange, requests, order }) => { + const flow = createProviderlessComponentFlow(); + arrange(flow); + const result = await flow.run(); + expect(result.session.machine.state).toBe("finalizing"); + expect(result.session.externalComponentActivation).toMatchObject({ + sandboxIdentityFingerprint: flow.proof.sandboxIdentityFingerprint, + lifecycleGeneration: flow.proof.lifecycleGeneration, + resultClass: "ambiguous", + }); + expect(flow.transport).toHaveBeenCalledTimes(requests); + expect(flow.order).toEqual(order); + }, + ); + + it("refuses providerless activation when policy proof is unavailable (#11486)", async () => { + const flow = createProviderlessComponentFlow(); + flow.createProof.mockImplementation(() => { + throw new Error("policy unavailable"); + }); + await expect(flow.run()).rejects.toThrow("policy unavailable"); + expect(flow.transport).not.toHaveBeenCalled(); + }); + it("selects the requested branch setup state", () => { expect(createPhases("openclaw")[0].state).toBe("openclaw"); expect(createPhases("agent_setup")[0].state).toBe("agent_setup"); diff --git a/src/lib/onboard/machine/final-flow-phases.ts b/src/lib/onboard/machine/final-flow-phases.ts index d5c35c50e8e..b0d34fb7da5 100644 --- a/src/lib/onboard/machine/final-flow-phases.ts +++ b/src/lib/onboard/machine/final-flow-phases.ts @@ -2,7 +2,11 @@ // SPDX-License-Identifier: Apache-2.0 import type { WebSearchConfig, WebSearchProvider } from "../../inference/web-search"; -import { assertSandboxCreatedContext, type OnboardFlowContext } from "./flow-context"; +import { + assertSandboxCreatedContext, + isProviderlessComponentOnboarding, + type OnboardFlowContext, +} from "./flow-context"; import { createAgentSetupPhase, createFinalizationPhase, @@ -20,7 +24,7 @@ import { } from "./handlers/finalization"; import { handlePoliciesState, type PoliciesStateOptions } from "./handlers/policies"; import { createPhaseProgressReporter } from "./phase-progress"; -import type { OnboardStateResult } from "./result"; +import { advanceTo, completeOnboardMachine, type OnboardStateResult } from "./result"; import type { OnboardMachineRunnerRuntime, OnboardStateHandlerResult } from "./runner"; import type { OnboardSequencePhase } from "./sequence-runner"; import type { OnboardMachineEventType, OnboardMachineState } from "./types"; @@ -60,10 +64,14 @@ export function createFinalOnboardFlowPhases< OnboardSequencePhase, ] { const finalizationDeps = options.finalizationDeps; + let activatedProviderlessSandbox: string | null = null; const createBranchPhase = options.branchState === "agent_setup" ? createAgentSetupPhase : createOpenclawSetupPhase; const branchSetupPhase = createBranchPhase(async (context) => { assertSandboxCreatedContext(context, "agent setup"); + if (isProviderlessComponentOnboarding(context)) { + return { result: advanceTo("policies", { metadata: { state: options.branchState } }) }; + } const agentSetupResult = await handleAgentSetupState({ agent: context.agent, sandboxName: context.sandboxName, @@ -84,6 +92,10 @@ export function createFinalOnboardFlowPhases< const policiesPhase = createPoliciesPhase(async (context) => { assertSandboxCreatedContext(context, "policies"); + if (isProviderlessComponentOnboarding(context)) { + // OpenShell already verified the interceptor-supplied policy during creation. + return { result: advanceTo("finalizing", { metadata: { state: "policies" } }) }; + } const policiesResult = await handlePoliciesState({ resume: context.resume, preserveRebuildLivePolicy: options.preserveRebuildLivePolicy, @@ -133,13 +145,28 @@ export function createFinalOnboardFlowPhases< portableProfileSelected: context.session?.checkpoint?.profile.value === "portable", recreateJournalHandoff: context.recreateJournalHandoff, externalComponent: context.externalComponent, + providerless: isProviderlessComponentOnboarding(context), deps: finalizationDeps, }); + if ( + isProviderlessComponentOnboarding(context) && + finalizationResult.stateResult.type === "transition" + ) { + activatedProviderlessSandbox = context.sandboxName; + } return { result: finalizationResult.stateResult }; }); const postVerifyPhase = createPostVerifyPhase(async (context) => { assertSandboxCreatedContext(context, "post verification"); + if (isProviderlessComponentOnboarding(context)) { + if (activatedProviderlessSandbox !== context.sandboxName) { + throw new Error( + "Providerless component activation has not completed in this onboarding run.", + ); + } + return { result: completeOnboardMachine({}, { state: "post_verify" }) }; + } const webSearchEnabled = options.finalization.webSearchEnabled(context.webSearchConfig); const postVerifyResult = await handlePostVerifyState({ sandboxName: context.sandboxName, diff --git a/src/lib/onboard/machine/flow-context.ts b/src/lib/onboard/machine/flow-context.ts index c64fbdf43e3..0a6c004e9c4 100644 --- a/src/lib/onboard/machine/flow-context.ts +++ b/src/lib/onboard/machine/flow-context.ts @@ -124,11 +124,20 @@ export function assertProviderSelectedContext, +): boolean { + return context.providerlessApf === true && Boolean(context.externalComponent); +} + export function assertSandboxCreatedContext( context: Context, stepName: string, ): asserts context is SandboxCreatedOnboardFlowContext { - if (!context.sandboxName || !context.model || !context.provider) { + const inferenceReady = isProviderlessComponentOnboarding(context) + ? context.model === "" && context.provider === "" + : Boolean(context.model && context.provider); + if (!context.sandboxName || !inferenceReady) { throw new Error(`Onboarding state is incomplete before ${stepName}.`); } } diff --git a/src/lib/onboard/machine/flow-handoff.test.ts b/src/lib/onboard/machine/flow-handoff.test.ts index f1e777104bc..92b6038944e 100644 --- a/src/lib/onboard/machine/flow-handoff.test.ts +++ b/src/lib/onboard/machine/flow-handoff.test.ts @@ -5,6 +5,7 @@ import { describe, expect, it, vi } from "vitest"; import { createSession, MACHINE_SNAPSHOT_VERSION, type Session } from "../../state/onboard-session"; import type { OnboardFlowContext } from "./flow-context"; +import type { PreparedExternalComponent } from "../external-component"; import { prepareCoreOnboardFlowContext, prepareFinalOnboardFlowContext } from "./flow-handoff"; import type { OnboardMachineState } from "./types"; @@ -99,6 +100,70 @@ function context(): OnboardFlowContext & { } describe("onboard flow handoffs", () => { + const component = (): PreparedExternalComponent => ({ + declaration: { + schemaVersion: 1, + componentId: "policy-governance", + interceptorSocketPath: "/run/component/interceptor.sock", + activationSocketPath: "/run/component/activation.sock", + }, + revalidateBeforeGateway: vi.fn(), + revalidateBeforeActivation: vi.fn(), + }); + + it("accepts a providerless final handoff with explicit selection and registration (#11486)", () => { + expect( + prepareFinalOnboardFlowContext({ + context: { + ...context(), + sandboxName: "ready", + providerlessApf: true, + externalComponent: component(), + }, + session: createSession(), + }), + ).toMatchObject({ model: "", provider: "" }); + }); + + it.each([ + [false, false], + [false, true], + [true, false], + ])( + "rejects a providerless final handoff with selection=%s and registration=%s (#11486)", + (selected, registered) => { + expect(() => + prepareFinalOnboardFlowContext({ + context: { + ...context(), + sandboxName: "ready", + providerlessApf: selected ? true : undefined, + externalComponent: registered ? component() : null, + }, + session: createSession(), + }), + ).toThrow("incomplete after sandbox setup"); + }, + ); + + it.each(["provider", "model"])( + "rejects conflicting %s state in a providerless final handoff (#11486)", + (field) => { + expect(() => + prepareFinalOnboardFlowContext({ + context: { + ...context(), + sandboxName: "ready", + providerlessApf: true, + externalComponent: component(), + [field]: "unexpected", + }, + session: createSession(), + }), + ).toThrow("incomplete after sandbox setup"); + }, + ); + it("constructs core context from the initial result and requested name", () => { const initialContext = context(); const persisted = createSession(); diff --git a/src/lib/onboard/machine/flow-handoff.ts b/src/lib/onboard/machine/flow-handoff.ts index acd607cf48b..1c483a0eee2 100644 --- a/src/lib/onboard/machine/flow-handoff.ts +++ b/src/lib/onboard/machine/flow-handoff.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import type { OnboardFlowContext } from "./flow-context"; +import { isProviderlessComponentOnboarding, type OnboardFlowContext } from "./flow-context"; import type { OnboardMachineRunnerResult } from "./runner"; type InitialHandoffContext = OnboardFlowContext & { @@ -47,14 +47,18 @@ export function prepareFinalOnboardFlowContext, ): Context & { sandboxName: string; model: string; provider: string } { const context = core.context; - if (!context.sandboxName || !context.model || !context.provider) { + const providerless = isProviderlessComponentOnboarding(context); + if ( + !context.sandboxName || + (providerless ? context.model || context.provider : !context.model || !context.provider) + ) { throw new Error("Onboarding state is incomplete after sandbox setup."); } return { ...context, session: core.session, sandboxName: context.sandboxName, - model: context.model, - provider: context.provider, + model: context.model ?? "", + provider: context.provider ?? "", }; } diff --git a/src/lib/onboard/machine/handlers/finalization.test.ts b/src/lib/onboard/machine/handlers/finalization.test.ts index c7ebc95675e..f61807a428c 100644 --- a/src/lib/onboard/machine/handlers/finalization.test.ts +++ b/src/lib/onboard/machine/handlers/finalization.test.ts @@ -150,6 +150,26 @@ async function runFinalizationHandlers( } describe("finalization handlers", () => { + it("completes providerless component activation without ordinary setup (#11486)", async () => { + const { deps, calls } = createDeps(); + const result = await handleFinalizationPhase({ + ...baseOptions(deps), + externalComponent, + providerless: true, + provider: "", + model: "", + }); + expect(result.stateResult).toMatchObject({ type: "transition", next: "post_verify" }); + expect(calls.activateExternalComponent).toHaveBeenCalledOnce(); + expect(calls.setExternalComponentActivationEvidence).toHaveBeenLastCalledWith(null); + expect(calls.setDefaultSandbox).not.toHaveBeenCalled(); + expect(calls.removeLegacy).not.toHaveBeenCalled(); + expect(calls.cleanupHost).not.toHaveBeenCalled(); + expect(calls.recoverProcesses).not.toHaveBeenCalled(); + expect(calls.verify).not.toHaveBeenCalled(); + expect(calls.dashboard).not.toHaveBeenCalled(); + }); + it("activates the registered component before declaring the sandbox ready (#11340)", async () => { const { deps, calls } = createDeps(); @@ -182,11 +202,13 @@ describe("finalization handlers", () => { }); it.each([ - ["rejected", "failed"], - ["ambiguous", "ambiguous"], + ["rejected", "failed", false], + ["ambiguous", "ambiguous", false], + ["rejected", "failed", true], + ["ambiguous", "ambiguous", true], ] as const)( "preserves identity-bound incomplete state for %s activation (#11340)", - async (kind, resultClass) => { + async (kind, resultClass, providerless) => { const activationId = "4b5a8e18-f967-4e27-a3b2-f2cc315abe21"; const activate = vi.fn(async () => kind === "rejected" @@ -198,6 +220,7 @@ describe("finalization handlers", () => { const result = await handleFinalizationPhase({ ...baseOptions(deps), externalComponent, + providerless, }); expect(result.stateResult).toEqual({ diff --git a/src/lib/onboard/machine/handlers/finalization.ts b/src/lib/onboard/machine/handlers/finalization.ts index 8d47752b0a3..15dbcdd17bf 100644 --- a/src/lib/onboard/machine/handlers/finalization.ts +++ b/src/lib/onboard/machine/handlers/finalization.ts @@ -36,6 +36,7 @@ export interface FinalizationStateOptions): Promise { const manageDashboard = shouldManageDashboardForAgent(agent as DashboardRuntimeAgent); + if (providerless && !externalComponent) { + throw new Error("Providerless finalization requires a registered external component."); + } if (externalComponent) { if ( !deps.createExternalComponentActivationProof || @@ -245,6 +250,12 @@ export async function handleFinalizationState !migratedLegacyKeys.has(key)), + }; + } // Reaching finalization means the policy-preset step was confirmed, so it is // now safe to register this sandbox as the default (#4614). deps.setDefaultSandbox(sandboxName); diff --git a/src/lib/onboard/machine/handlers/sandbox-apf.test.ts b/src/lib/onboard/machine/handlers/sandbox-apf.test.ts index e4205115e93..f5886bd066c 100644 --- a/src/lib/onboard/machine/handlers/sandbox-apf.test.ts +++ b/src/lib/onboard/machine/handlers/sandbox-apf.test.ts @@ -21,58 +21,62 @@ describe("APF sandbox create selection", () => { expect(apfCreateFingerprintFields(true)).toEqual(["apf-interceptor"]); }); - it("defers providerless creation effects behind the verified APF callback (#9833)", async () => { - const session = createSession({ apfInterceptorRequested: true }); - const { deps, calls } = createDeps( - { - getSandboxRegistryEntry: (name) => ({ - name, - gatewayName: "nemoclaw", - pendingRouteReservation: true, - reservationSessionId: session.sessionId, - webSearchEnabled: false, - toolDisclosure: "progressive", - fromDockerfile: null, - hermesAuthMethod: null, - }), - getSandboxRecreateObservation: () => ({ - state: "missing" as const, - liveIdentityFingerprint: null, - }), - }, - session, - ); - - await handleSandboxState({ - ...baseOptions(deps, session), - fresh: true, - apfInterceptorRequested: true, - model: "", - provider: "", - preferredInferenceApi: null, - }); - - expect(calls.stageCredentialProviders).not.toHaveBeenCalled(); - expect(calls.configureWebSearch).not.toHaveBeenCalled(); - expect(calls.validateBrave).not.toHaveBeenCalled(); - expect(calls.setupMessaging).not.toHaveBeenCalled(); - expect(calls.createSandbox).toHaveBeenCalledOnce(); - const createCall = calls.createSandbox.mock.calls[0] ?? []; - expect(createCall.at(-2)).toMatchObject({ - apfInterceptorRequested: true, - deferSandboxEffectsUntilIdentityVerification: true, - }); - const activateVerifiedEffects = createCall.at(-1); - expect(activateVerifiedEffects).toEqual(expect.any(Function)); - - const sessionUpdatesBeforeVerifiedEffects = calls.updateSession.mock.calls.length; - await (activateVerifiedEffects as unknown as (context: unknown) => Promise)({ - revalidateSandboxIdentity: () => undefined, - }); - expect(calls.updateSession.mock.calls.length).toBeGreaterThan( - sessionUpdatesBeforeVerifiedEffects, - ); - }); + it.each([false, true])( + "defers providerless creation effects behind verification with registration=%s (#11486)", + async (externalComponentRegistered) => { + const session = createSession({ apfInterceptorRequested: true }); + const { deps, calls } = createDeps( + { + getSandboxRegistryEntry: (name) => ({ + name, + gatewayName: "nemoclaw", + pendingRouteReservation: true, + reservationSessionId: session.sessionId, + webSearchEnabled: false, + toolDisclosure: "progressive", + fromDockerfile: null, + hermesAuthMethod: null, + }), + getSandboxRecreateObservation: () => ({ + state: "missing" as const, + liveIdentityFingerprint: null, + }), + }, + session, + ); + + await handleSandboxState({ + ...baseOptions(deps, session), + fresh: true, + apfInterceptorRequested: true, + externalComponentRegistered, + model: "", + provider: "", + preferredInferenceApi: null, + }); + + expect(calls.stageCredentialProviders).not.toHaveBeenCalled(); + expect(calls.configureWebSearch).not.toHaveBeenCalled(); + expect(calls.validateBrave).not.toHaveBeenCalled(); + expect(calls.setupMessaging).not.toHaveBeenCalled(); + expect(calls.createSandbox).toHaveBeenCalledOnce(); + const createCall = calls.createSandbox.mock.calls[0] ?? []; + expect(createCall.at(-2)).toMatchObject({ + apfInterceptorRequested: true, + deferSandboxEffectsUntilIdentityVerification: true, + }); + const activateVerifiedEffects = createCall.at(-1); + expect(activateVerifiedEffects).toEqual(expect.any(Function)); + + const sessionUpdatesBeforeVerifiedEffects = calls.updateSession.mock.calls.length; + await (activateVerifiedEffects as unknown as (context: unknown) => Promise)({ + revalidateSandboxIdentity: () => undefined, + }); + expect(calls.updateSession.mock.calls.length).toBeGreaterThan( + sessionUpdatesBeforeVerifiedEffects, + ); + }, + ); it.each([ [ @@ -103,43 +107,47 @@ describe("APF sandbox create selection", () => { expect(calls.createSandbox).not.toHaveBeenCalled(); }); - it("rejects a resolved APF provider plan before sandbox or provider effects (#9833)", async () => { - const session = createSession({ apfInterceptorRequested: true }); - const { deps, calls } = createDeps( - { - getSandboxRegistryEntry: (name) => ({ - name, - gatewayName: "nemoclaw", - pendingRouteReservation: true, - reservationSessionId: session.sessionId, + it.each([false, true])( + "rejects a provider plan before effects with registration=%s (#11486)", + async (externalComponentRegistered) => { + const session = createSession({ apfInterceptorRequested: true }); + const { deps, calls } = createDeps( + { + getSandboxRegistryEntry: (name) => ({ + name, + gatewayName: "nemoclaw", + pendingRouteReservation: true, + reservationSessionId: session.sessionId, + }), + getSandboxRecreateObservation: () => ({ + state: "missing" as const, + liveIdentityFingerprint: null, + }), + planRegisteredExtraProviders: () => ({ + extraProviders: [], + staleExtraProviders: ["stale-provider"], + }), + }, + session, + ); + + await expect( + handleSandboxState({ + ...baseOptions(deps, session), + fresh: true, + apfInterceptorRequested: true, + externalComponentRegistered, + model: "", + provider: "", + preferredInferenceApi: null, }), - getSandboxRecreateObservation: () => ({ - state: "missing" as const, - liveIdentityFingerprint: null, - }), - planRegisteredExtraProviders: () => ({ - extraProviders: [], - staleExtraProviders: ["stale-provider"], - }), - }, - session, - ); - - await expect( - handleSandboxState({ - ...baseOptions(deps, session), - fresh: true, - apfInterceptorRequested: true, - model: "", - provider: "", - preferredInferenceApi: null, - }), - ).rejects.toThrow(/supports providerless sandbox creation only/u); + ).rejects.toThrow(/supports providerless sandbox creation only/u); - expect(calls.resolveCreateIntent).not.toHaveBeenCalled(); - expect(calls.stageCredentialProviders).not.toHaveBeenCalled(); - expect(calls.createSandbox).not.toHaveBeenCalled(); - }); + expect(calls.resolveCreateIntent).not.toHaveBeenCalled(); + expect(calls.stageCredentialProviders).not.toHaveBeenCalled(); + expect(calls.createSandbox).not.toHaveBeenCalled(); + }, + ); it("rejects registered sandbox adoption before credential staging (#9833)", async () => { const session = createSession({ apfInterceptorRequested: true }); diff --git a/src/lib/onboard/machine/handlers/sandbox.ts b/src/lib/onboard/machine/handlers/sandbox.ts index 2c743fddf76..2ef2fe86e8f 100644 --- a/src/lib/onboard/machine/handlers/sandbox.ts +++ b/src/lib/onboard/machine/handlers/sandbox.ts @@ -2538,7 +2538,7 @@ class SandboxStateFlow< webSearchSupported: state.webSearchSupported, session: state.session, stateResult: - this.options.apfInterceptorRequested === true + this.options.apfInterceptorRequested === true && !this.options.externalComponentRegistered ? completeOnboardMachine({}, metadata) : branchTo(this.options.agent ? "agent_setup" : "openclaw", { metadata }), }; diff --git a/test/helpers/onboard-final-flow-phases.ts b/test/helpers/onboard-final-flow-phases.ts index eb96b9aaf1c..6a93a86c69f 100644 --- a/test/helpers/onboard-final-flow-phases.ts +++ b/test/helpers/onboard-final-flow-phases.ts @@ -2,11 +2,21 @@ // SPDX-License-Identifier: Apache-2.0 import { vi } from "vitest"; +import type { PreparedExternalComponent } from "../../src/lib/onboard/external-component"; +import { + activateExternalComponent, + type ExternalComponentActivationProof, +} from "../../src/lib/onboard/external-component/activation"; +import { prepareFinalOnboardFlowContext } from "../../src/lib/onboard/machine/flow-handoff"; import type { DashboardDeliveryChain } from "../../src/lib/dashboard/contract"; import type { OnboardMachineEvent } from "../../src/lib/onboard/machine/events"; -import { createFinalOnboardFlowPhases } from "../../src/lib/onboard/machine/final-flow-phases"; +import { + createFinalOnboardFlowPhases, + runFinalOnboardFlowSlice, +} from "../../src/lib/onboard/machine/final-flow-phases"; import type { OnboardFlowContext } from "../../src/lib/onboard/machine/flow-context"; import type { PoliciesStateOptions } from "../../src/lib/onboard/machine/handlers/policies"; +import type { FinalizationStateOptions } from "../../src/lib/onboard/machine/handlers/finalization"; import { OnboardRuntime, type OnboardRuntimeDeps } from "../../src/lib/onboard/machine/runtime"; import type { OnboardMachineState } from "../../src/lib/onboard/machine/types"; import { OnboardRuntimeBoundary } from "../../src/lib/onboard/runtime-boundary"; @@ -24,6 +34,9 @@ export type Agent = { name: string }; type WebSearchConfig = NonNullable; export type RecorderOverrides = { + finalizationDeps?: Partial< + FinalizationStateOptions["deps"] + >; loadSession?: () => Session | null; updateSession?: (mutator: (session: Session) => Session | void) => Session; recordStepSkipped?: (stepName: string) => Promise; @@ -312,6 +325,93 @@ export function createPhases( printDashboard: recorders.printDashboard ?? vi.fn(), error: vi.fn(), log: vi.fn(), + ...recorders.finalizationDeps, }, }); } + +export function createProviderlessComponentFlow() { + const order: string[] = []; + const harness = createRuntimeHarness(sessionAt("openclaw")); + const revalidate = vi.fn(); + const revalidateEndpoint = vi.fn(); + const proof: ExternalComponentActivationProof = { + gatewayName: "nemoclaw", + sandboxId: "sandbox-123", + sandboxIdentityFingerprint: `sha256:${"b".repeat(64)}`, + lifecycleGeneration: "generation-1", + policySource: "sandbox", + policyHash: `sha256:${"a".repeat(64)}`, + policyActiveVersion: 1, + revalidate, + }; + const component: PreparedExternalComponent = { + declaration: { + schemaVersion: 1, + componentId: "policy-governance", + interceptorSocketPath: "/run/component/interceptor.sock", + activationSocketPath: "/run/component/activation.sock", + }, + revalidateBeforeGateway: vi.fn(), + revalidateBeforeActivation: revalidateEndpoint, + }; + const activationId = "4b5a8e18-f967-4e27-a3b2-f2cc315abe21"; + const response = { + schemaVersion: 1, + activationId, + componentId: component.declaration.componentId, + sandboxId: proof.sandboxId, + policyHash: proof.policyHash, + result: "activated", + }; + const transport = vi.fn(async (_socket: string, _body: string) => JSON.stringify(response)); + const evidence = vi.fn(); + const createProof = vi.fn(() => { + order.push("verify-proof"); + return proof; + }); + const phases = createPhases("openclaw", order, { + finalizationDeps: { + createExternalComponentActivationProof: createProof, + createExternalComponentActivationId: () => activationId, + activateExternalComponent: (registered, verified, id) => + activateExternalComponent( + registered, + verified, + (socket, body) => { + order.push("activate"); + return transport(socket, body); + }, + id, + ), + setExternalComponentActivationEvidence: evidence, + }, + }); + const initial = prepareFinalOnboardFlowContext({ + context: context({ + providerlessApf: true, + externalComponent: component, + model: null, + provider: null, + }), + session: harness.getSession(), + }); + return { + order, + proof, + response, + transport, + evidence, + createProof, + revalidate, + revalidateEndpoint, + initial, + run: () => + runFinalOnboardFlowSlice({ + context: initial, + runtime: harness.boundary.getRuntime(), + phases, + recordRepairEvent: vi.fn(), + }), + }; +} diff --git a/test/onboarding/onboard-fsm-live-slices.test.ts b/test/onboarding/onboard-fsm-live-slices.test.ts index 89cd2b20c42..fea32acd9c6 100644 --- a/test/onboarding/onboard-fsm-live-slices.test.ts +++ b/test/onboarding/onboard-fsm-live-slices.test.ts @@ -244,7 +244,11 @@ const staleAdmissionExit = new Error("stale recovery admission refused"); if (scenario.mode === "providerless-external-component") { require(${externalComponentPath}).loadExternalComponentDeclaration = () => { called.push("component-validated"); - return {}; + return { + declaration: { schemaVersion: 1, componentId: "policy-governance", interceptorSocketPath: "/run/component/interceptor.sock", activationSocketPath: "/run/component/activation.sock" }, + revalidateBeforeGateway() {}, + revalidateBeforeActivation() {}, + }; }; } @@ -387,6 +391,7 @@ preflightHandlers.handlePreflightState = async (options) => { gatewayHandlers.handleGatewayState = async (options) => { if (scenario.mode === "providerless-external-component") { called.push("gateway-effect"); + return { gatewayReuseState: "healthy", session: options.session, stateResult: advanceTo("provider_selection", { metadata: { state: "gateway" } }) }; } if (!scenario.mode.includes("core-gateway")) { throw new Error("unexpected gateway compatibility handler"); @@ -594,9 +599,7 @@ const { onboard } = require(${onboardPath}); (scenario.mode === "endpoint-override" && error?.name === "OpenShellGatewayEndpointOverrideError") || (scenario.mode === "providerless-staged-messaging" && - /supports providerless sandbox creation only/.test(String(error?.message))) || - (scenario.mode === "providerless-external-component" && - error?.code === "lifecycle_unsupported") + /supports providerless sandbox creation only/.test(String(error?.message))) ) { const payload = "__RESULT__" + JSON.stringify({ called }); if (scenario.mode === "dashboard-port-composition") { @@ -687,11 +690,16 @@ describe("live onboard FSM slice boundaries", () => { ); }); - it("rejects a registered component with providerless APF before effects (#11340)", () => { - assert.deepEqual(runSliceProbe({ slice: "initial", mode: "providerless-external-component" }), [ - "component-validated", - ]); - }); + it( + "validates the registered component before providerless onboarding effects (#11486)", + () => { + assert.deepEqual( + runSliceProbe({ slice: "initial", mode: "providerless-external-component" }), + ["component-validated", "preflight-effect", "gateway-effect", "sandbox-effect"], + ); + }, + probeTimeoutMs, + ); it("rechecks retained sandbox admission after acquiring the onboarding lock (#9833)", () => { assert.deepEqual(runSliceProbe({ slice: "initial", mode: "stale-recovery-admission" }), []);