diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index f77b64a90ea..652ff1b3d8e 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -228,6 +228,18 @@ For example, `nemohermes` resolves to `hermes`, while `dcode`, `deepagents`, `de NemoClaw records onboarding progress so interrupted runs can continue. Use `--resume` to continue a resumable onboarding session with the provider, model, sandbox name, agent, observability choice, and custom Dockerfile path recorded by the original run. + + + +OpenClaw sessions also record the web search selection, messaging selection and non-secret settings, and resource profile. +When the saved session includes prompt checkpoints, resume skips each completed group and continues at the first incomplete choice. +Legacy sessions without those checkpoints may repeat choices whose completion cannot be proven. +Raw web search and messaging credentials are never written to the onboarding session. +Resume skips their secret prompts when the same session recorded a successful OpenShell provider registration and OpenShell still reports the exact expected name, type, and credential keys. +If the session lacks that registration receipt, the provider is missing, or its binding does not match, interactive resume requests the credential again; non-interactive resume preserves the completed choice, reports the required environment variable, and exits so you can export it before retrying. + + + Completed onboarding sessions are not resumable. Use `--resume` only for interrupted `in_progress` sessions, not to change provider, model, agent, or sandbox recreation settings after onboarding has completed. During resume, NemoClaw reruns preflight, gateway, provider, and sandbox repair checks even when the saved session has already reached a later nonterminal onboarding phase. diff --git a/docs/reference/troubleshooting.mdx b/docs/reference/troubleshooting.mdx index 9c7387d47ca..33ed0d7b9eb 100644 --- a/docs/reference/troubleshooting.mdx +++ b/docs/reference/troubleshooting.mdx @@ -774,13 +774,22 @@ Silent retry would loop on the same failure if your original choice, such as an curl -fsSL https://www.nvidia.com/nemoclaw.sh | NEMOCLAW_FRESH=1 bash ``` - Retry the same session without re-prompting. + Retry the same session. + This is only useful if the original failure was transient, for example a network blip or a stopped Docker daemon, and not a wrong provider choice: ```bash $$nemoclaw onboard --resume ``` + + +OpenClaw resume does not repeat completed non-secret sandbox, web search, messaging, or resource choices. +Resume also reuses registered web search and messaging credentials when the same onboarding session recorded their successful OpenShell registration and OpenShell still reports the exact expected name, type, and credential keys. +If the session lacks that registration receipt, the provider is missing, or its binding does not match, interactive resume requests the credential again; non-interactive resume preserves the completed choice, reports the required environment variable, and exits so you can export it before retrying `$$nemoclaw onboard --resume`. + + + As a last resort, you can also delete the session file directly and re-run the installer: ```bash diff --git a/docs/security/credential-storage.mdx b/docs/security/credential-storage.mdx index d54b5910dd8..1cf51df669d 100644 --- a/docs/security/credential-storage.mdx +++ b/docs/security/credential-storage.mdx @@ -120,6 +120,19 @@ For any other missing-provider case, rerun `$$nemoclaw onboard` or re-register t ## Onboarding Reads Credentials from Environment `$$nemoclaw onboard` reads credentials from the host environment, registers them with the OpenShell gateway, and creates the sandbox. + + + +After the sandbox name and web search choices are checkpointed, NemoClaw registers a selected, validated web search credential before messaging setup. +After messaging choices are checkpointed, it registers selected, validated messaging credentials before resource selection. +It creates providers with the expected name, type, and credential key, and updates an existing provider only when that binding matches exactly. +If onboarding is interrupted afterward, `--resume` reuses a provider only when the same session recorded that successful registration and the live binding still matches the saved choice. +The session stores only those non-secret provider names; raw values never enter `~/.nemoclaw/onboard-session.json`. +Because registration precedes sandbox creation, an abandoned run can leave a provider behind. +Retry onboarding with the same sandbox name to reconcile that provider. + + + A typical onboarding invocation looks like: ```bash diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index df6934a4fdb..7b0c7de17a1 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -253,6 +253,7 @@ const inferenceConfig: typeof import("./inference/config") = require("./inferenc const { DEFAULT_CLOUD_MODEL, getProviderSelectionConfig, parseGatewayInference } = inferenceConfig; const onboardProviders = require("./onboard/providers"); +const credentialProviderRegistration: typeof import("./onboard/credential-provider-registration") = require("./onboard/credential-provider-registration"); const inferenceProviders: typeof import("./onboard/inference-providers") = require("./onboard/inference-providers"); const setupInferenceFactory: typeof import("./onboard/setup-inference") = require("./onboard/setup-inference"); @@ -448,6 +449,8 @@ const promptValidatedSandboxName = sandboxAgent.createPromptValidatedSandboxName promptOrDefault, cliDisplayName, isNonInteractive, + checkpointSandboxName: (sandboxName, agent) => + onboardSessionBootstrap.checkpointSandboxName(sandboxName, agent, onboardSession.updateSession), exit: process.exit, }); const modelRouter: typeof import("./onboard/model-router") = require("./onboard/model-router"); @@ -967,37 +970,20 @@ const verifyDirectSandboxGpu = sandboxGpuPreflight.createDirectSandboxGpuVerifie redact, }); -function upsertMessagingProviders( - tokenDefs: MessagingTokenDef[], - options: { replaceExisting?: boolean } = {}, -) { - // biome-ignore format: keep src/lib/onboard.ts net-neutral for growth guardrail. - braveProviderProfile.ensureWebSearchProviderProfiles(tokenDefs, { root: ROOT, runOpenshell, redact }); - const upserted = onboardProviders.upsertMessagingProviders(tokenDefs, runOpenshell, options); - // upsertMessagingProviders process.exits on failure, so reaching this - // point means every entry in tokenDefs that had a token was registered. - // Mark migrated only when the registered token equals the staged legacy - // value — a token rotated since staging (or a fresh prompt) is not a - // legacy migration even if it happens to use the same env-key name. - // Mirror upsertProvider's withdrawal logic so a later messaging upsert - // that replaces the legacy value with something else cannot leave the - // mark stuck on. - let mutated = false; - for (const def of tokenDefs) { - if (!def.token || !def.envKey) continue; - const stagedValue = stagedLegacyValues.get(def.envKey); - if (stagedValue === undefined) continue; - if (def.token === stagedValue) { - migratedLegacyKeys.add(def.envKey); - mutated = true; - } else { - migratedLegacyKeys.delete(def.envKey); - mutated = true; - } - } - if (mutated) persistMigratedLegacyKeys(); - return upserted; -} +const registeredCredentialProviders = + credentialProviderRegistration.createCredentialProviderRegistration({ + root: ROOT, + runOpenshell, + redact, + getGatewayName: () => GATEWAY_NAME, + normalizeCredentialValue, + updateSession: onboardSession.updateSession, + stagedLegacyValues, + migratedLegacyKeys, + persistMigratedLegacyKeys, + }); +const { upsertMessagingProviders, providerMatchesGatewayCredential } = + registeredCredentialProviders; // biome-ignore format: keep src/lib/onboard.ts net-neutral for growth guardrail. const providerExistsInGateway = (name: string, gatewayName: string = GATEWAY_NAME) => onboardProviders.providerExistsInGateway(name, setupInferenceFactory.createGatewayScopedOpenshellRunner(runOpenshell, gatewayName)); @@ -2309,6 +2295,7 @@ async function createSandboxWithBaseImageResolution( hermesToolGateways, extraProviders: extraProviderPlan.extraProviders, staleExtraProviders: extraProviderPlan.staleExtraProviders, + ...(createIntent?.reuseRegisteredCredentials ? { reuseRegisteredCredentials: true } : {}), ...(createIntent?.policyTier !== undefined ? { policyTier: createIntent.policyTier } : {}), })); const messagingCapabilities = await sandboxCreateIntentResolver.rebind( @@ -2317,6 +2304,7 @@ async function createSandboxWithBaseImageResolution( enabledChannels, webSearchConfig, agent, + ...(createIntent?.reuseRegisteredCredentials ? { reuseRegisteredCredentials: true } : {}), }, resolvedCreateIntent, ); @@ -2707,6 +2695,7 @@ async function createSandboxWithBaseImageResolution( enabledChannels, webSearchConfig, agent, + ...(createIntent?.reuseRegisteredCredentials ? { reuseRegisteredCredentials: true } : {}), }, resolvedCreateIntent, ); @@ -3745,7 +3734,7 @@ const sandboxCreateIntentResolver = sandboxCreateIntentResolution.createSandboxC >({ channels: MESSAGING_CHANNELS, // biome-ignore format: keep src/lib/onboard.ts net-neutral for growth guardrail. - messagingPreflightDeps: { readMessagingPlanFromEnv, resolveDisabledChannels: channelState.resolveDisabledChannels, gatewayName: () => GATEWAY_NAME, registry, providerExistsInGateway, isNonInteractive, promptYesNoOrDefault, cliName, log: (message) => console.log(message), error: (message) => console.error(message), exitProcess: (code) => process.exit(code), getValidatedMessagingTokenByEnvKey, getCredential, normalizeCredentialValue, registerExtraPlaceholderProviders: extraPlaceholderKeysModule.registerExtraPlaceholderProviders, getMessagingChannelForEnvKey }, + messagingPreflightDeps: { readMessagingPlanFromEnv, resolveDisabledChannels: channelState.resolveDisabledChannels, gatewayName: () => GATEWAY_NAME, registry, providerExistsInGateway, providerMatchesGatewayCredential, isNonInteractive, promptYesNoOrDefault, cliName, log: (message) => console.log(message), error: (message) => console.error(message), exitProcess: (code) => process.exit(code), getValidatedMessagingTokenByEnvKey, getCredential, normalizeCredentialValue, registerExtraPlaceholderProviders: extraPlaceholderKeysModule.registerExtraPlaceholderProviders, getMessagingChannelForEnvKey }, filterEnabledChannelsByAgent, defaultPolicyPath: path.join(ROOT, "nemoclaw-blueprint", "policies", "openclaw-sandbox.yaml"), getAgentPolicyPath: (agent) => (agent ? agentOnboard.getAgentPolicyPath(agent) : null), @@ -3762,6 +3751,9 @@ const sandboxCreateIntentResolver = sandboxCreateIntentResolution.createSandboxC }), }); +// biome-ignore format: keep src/lib/onboard.ts net-neutral for growth guardrail. +const stageSandboxCredentialProviders = (input: import("./onboard/credential-provider-registration").StageSandboxCredentialProvidersInput) => registeredCredentialProviders.stageSandboxCredentialProviders(input, sandboxCreateIntentResolver.prepareCredentialProviders); + function getRecordedMessagingChannelsForResume( resume: boolean, session: Session | null, @@ -3782,12 +3774,14 @@ async function setupMessagingChannels( agent: AgentDefinition | null = null, existingChannels: string[] | null = null, sandboxName: string | null = null, + options: { readonly selectionCompleted?: boolean } = {}, ): Promise { return setupMessagingChannelsImpl(agent, existingChannels, { step, note, isNonInteractive, sandboxName, + selectionCompleted: options.selectionCompleted, }); } @@ -4217,7 +4211,11 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { const recordedSandboxName = session?.steps?.sandbox?.status === "complete" ? session?.sandboxName || null : null; - const gatewaySandboxName = resume ? (recordedSandboxName ?? requestedSandboxName) : null; + // biome-ignore format: keep src/lib/onboard.ts net-neutral for growth guardrail. + const checkpointedSandboxName = onboardSessionBootstrap.getCheckpointedSandboxName(resume, agent, session); + const gatewaySandboxName = resume + ? (recordedSandboxName ?? requestedSandboxName ?? checkpointedSandboxName) + : null; // biome-ignore format: keep src/lib/onboard.ts net-neutral for growth guardrail. const onboardGateway = gatewayBinding.resolveCoreOnboardGatewayBinding({ authoritativeGateway, currentGateway: { name: GATEWAY_NAME, port: GATEWAY_PORT }, resume, sandbox: gatewaySandboxName ? registry.getSandbox(gatewaySandboxName) : null }); // biome-ignore format: keep src/lib/onboard.ts net-neutral for growth guardrail. @@ -4243,7 +4241,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { agent, recordedSandboxName, requestedSandboxName, - sandboxName: recordedSandboxName || requestedSandboxName || null, + sandboxName: recordedSandboxName || requestedSandboxName || checkpointedSandboxName || null, fromDockerfile, model: session?.model || null, provider: session?.provider || null, @@ -4347,12 +4345,10 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { const { gpuPassthrough } = initialContext; const gpu = initialContext.gpu ?? null; - // #2753: prefer requestedSandboxName over an unconfirmed session name. - // A pre-fix session may carry sandboxName even though sandbox creation - // never completed; users supplying `--name` / NEMOCLAW_SANDBOX_NAME on - // the resume run must win, otherwise the stale name silently overrides - // their explicit recovery input. - let sandboxName = recordedSandboxName || requestedSandboxName || null; + // #2753: for an unfinished sandbox, an explicit requested name precedes + // the checkpointed name from the interrupted session. + let sandboxName = + recordedSandboxName || requestedSandboxName || checkpointedSandboxName || null; if (sandboxName && RESERVED_SANDBOX_NAMES.has(sandboxName)) { console.error( ` Reserved name in resumed session: '${sandboxName}' is a ${cliDisplayName()} CLI command.`, @@ -4481,11 +4477,14 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { configureWebSearch, startRecordedStep, getRecordedMessagingChannelsForResume, + showMessagingStage: () => step(5, 8, "Messaging channels"), setupMessagingChannels, readMessagingPlanFromEnv, writePlanToEnv, clearPlanEnv, getRegistrySandboxMessagingPlan, + providerMatchesGatewayCredential, + stageSandboxCredentialProviders, promptValidatedSandboxName, selectResourceProfileForSandbox: () => selectResourceProfileForSandbox({ isNonInteractive, note, prompt, promptOrDefault }), diff --git a/src/lib/onboard/agent-resume-state.ts b/src/lib/onboard/agent-resume-state.ts index b655e448730..7634ad255b4 100644 --- a/src/lib/onboard/agent-resume-state.ts +++ b/src/lib/onboard/agent-resume-state.ts @@ -30,6 +30,12 @@ export function clearAgentScopedResumeState(session: Session, selectedAgentName: session.nimContainer = null; session.routerPid = null; session.routerCredentialHash = null; + session.webSearchConfig = null; + session.messagingPlan = null; + if (session.sandboxPromptProgress) { + session.sandboxPromptProgress.webSearch = false; + session.sandboxPromptProgress.messaging = false; + } session.policyPresets = null; const resetSteps = [ diff --git a/src/lib/onboard/credential-provider-registration.test.ts b/src/lib/onboard/credential-provider-registration.test.ts new file mode 100644 index 00000000000..11adfd474c8 --- /dev/null +++ b/src/lib/onboard/credential-provider-registration.test.ts @@ -0,0 +1,220 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it, vi } from "vitest"; + +import type { Session } from "../state/onboard-session"; +import { + type CredentialProviderRegistrationDeps, + createCredentialProviderRegistration, +} from "./credential-provider-registration"; +import type { MessagingTokenDef } from "./messaging-prep"; + +const BRAVE_SECRET = "brv-resume-secret"; +const DISCORD_SECRET = "discord-resume-secret"; + +function providerMetadata( + name: string, + type: string, + credentialKey: string, +): { status: number; stdout: string; stderr: string } { + return { + status: 0, + stdout: [ + `Name: ${name}`, + `Type: ${type}`, + `Credential keys: ${credentialKey}`, + "Config keys: ", + ].join("\n"), + stderr: "", + }; +} + +function registrationDeps( + runOpenshellMock: ReturnType, + session: Session, +): CredentialProviderRegistrationDeps { + const updateSession = vi.fn( + (mutator: (current: Session) => Session | void): Session => mutator(session) ?? session, + ); + return { + root: "/repo", + runOpenshell: runOpenshellMock as unknown as CredentialProviderRegistrationDeps["runOpenshell"], + redact: (input) => input, + getGatewayName: () => "test-gateway", + normalizeCredentialValue: (value) => (typeof value === "string" ? value.trim() : ""), + updateSession, + stagedLegacyValues: new Map(), + migratedLegacyKeys: new Set(), + persistMigratedLegacyKeys: vi.fn(), + }; +} + +function sandboxInput() { + return { + sandboxName: "alpha", + enabledChannels: ["discord"], + webSearchConfig: null, + agent: {}, + }; +} + +describe("credential provider registration", () => { + it("updates exact Brave and messaging providers and records secret-free receipts (#6743)", async () => { + const session = { stagedCredentialProviders: [] } as unknown as Session; + const commandResults = new Map([ + [ + "provider get -g test-gateway alpha-brave-search", + providerMetadata("alpha-brave-search", "brave", "BRAVE_API_KEY"), + ], + [ + "provider get -g test-gateway alpha-discord-bridge", + providerMetadata("alpha-discord-bridge", "generic", "DISCORD_BOT_TOKEN"), + ], + ]); + const defaultResult = { status: 0, stdout: "", stderr: "" }; + const runOpenshell = vi.fn( + (args: string[]) => commandResults.get(args.join(" ")) ?? defaultResult, + ); + const registration = createCredentialProviderRegistration( + registrationDeps(runOpenshell, session), + ); + const tokenDefs: MessagingTokenDef[] = [ + { + name: "alpha-brave-search", + envKey: "BRAVE_API_KEY", + token: BRAVE_SECRET, + providerType: "brave", + }, + { + name: "alpha-discord-bridge", + envKey: "DISCORD_BOT_TOKEN", + token: DISCORD_SECRET, + }, + ]; + + const registered = await registration.stageSandboxCredentialProviders( + sandboxInput(), + async () => ({ messagingTokenDefs: tokenDefs }), + ); + + expect(registered).toEqual(["alpha-brave-search", "alpha-discord-bridge"]); + expect(session.stagedCredentialProviders).toEqual([ + "alpha-brave-search", + "alpha-discord-bridge", + ]); + expect(runOpenshell).toHaveBeenCalledWith( + [ + "provider", + "update", + "-g", + "test-gateway", + "alpha-brave-search", + "--credential", + "BRAVE_API_KEY", + ], + expect.objectContaining({ env: { BRAVE_API_KEY: BRAVE_SECRET } }), + ); + expect(runOpenshell).toHaveBeenCalledWith( + [ + "provider", + "update", + "-g", + "test-gateway", + "alpha-discord-bridge", + "--credential", + "DISCORD_BOT_TOKEN", + ], + expect.objectContaining({ env: { DISCORD_BOT_TOKEN: DISCORD_SECRET } }), + ); + + const argv = runOpenshell.mock.calls.flatMap(([args]) => args); + const commandOutput = runOpenshell.mock.results + .flatMap(({ value }) => [value.stdout, value.stderr]) + .join("\n"); + expect(argv).not.toContain(BRAVE_SECRET); + expect(argv).not.toContain(DISCORD_SECRET); + expect(commandOutput).not.toContain(BRAVE_SECRET); + expect(commandOutput).not.toContain(DISCORD_SECRET); + }); + + it("creates a missing messaging provider and records its receipt (#6743)", async () => { + const session = { stagedCredentialProviders: [] } as unknown as Session; + const missing = { status: 1, stdout: "", stderr: "not found" }; + const success = { status: 0, stdout: "", stderr: "" }; + const runOpenshell = vi.fn((args: string[]) => + args[0] === "provider" && args[1] === "get" ? missing : success, + ); + const registration = createCredentialProviderRegistration( + registrationDeps(runOpenshell, session), + ); + + const registered = await registration.stageSandboxCredentialProviders( + sandboxInput(), + async () => ({ + messagingTokenDefs: [ + { + name: "alpha-discord-bridge", + envKey: "DISCORD_BOT_TOKEN", + token: DISCORD_SECRET, + }, + ], + }), + ); + + expect(registered).toEqual(["alpha-discord-bridge"]); + expect(session.stagedCredentialProviders).toEqual(["alpha-discord-bridge"]); + expect(runOpenshell).toHaveBeenCalledWith( + [ + "provider", + "create", + "-g", + "test-gateway", + "--name", + "alpha-discord-bridge", + "--type", + "generic", + "--credential", + "DISCORD_BOT_TOKEN", + ], + expect.objectContaining({ env: { DISCORD_BOT_TOKEN: DISCORD_SECRET } }), + ); + }); + + it("does not update or receipt a mismatched existing provider (#6743)", async () => { + const session = { + stagedCredentialProviders: ["alpha-brave-search"], + } as unknown as Session; + const mismatchedMetadata = providerMetadata("alpha-brave-search", "generic", "BRAVE_API_KEY"); + const commandResults = new Map([ + ["provider get -g test-gateway alpha-brave-search", mismatchedMetadata], + ]); + const defaultResult = { status: 0, stdout: "", stderr: "" }; + const runOpenshell = vi.fn( + (args: string[]) => commandResults.get(args.join(" ")) ?? defaultResult, + ); + const registration = createCredentialProviderRegistration( + registrationDeps(runOpenshell, session), + ); + + const registered = await registration.stageSandboxCredentialProviders( + sandboxInput(), + async () => ({ + messagingTokenDefs: [ + { + name: "alpha-brave-search", + envKey: "BRAVE_API_KEY", + token: BRAVE_SECRET, + providerType: "brave", + }, + ], + }), + ); + + expect(registered).toEqual([]); + expect(session.stagedCredentialProviders).toEqual([]); + expect(runOpenshell.mock.calls.map(([args]) => args.join(" "))).not.toContain( + "provider update -g test-gateway alpha-brave-search --credential BRAVE_API_KEY", + ); + }); +}); diff --git a/src/lib/onboard/credential-provider-registration.ts b/src/lib/onboard/credential-provider-registration.ts new file mode 100644 index 00000000000..2318e1deeda --- /dev/null +++ b/src/lib/onboard/credential-provider-registration.ts @@ -0,0 +1,162 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { WebSearchConfig } from "../inference/web-search"; +import type { Session } from "../state/onboard-session"; +import * as braveProviderProfile from "./brave-provider-profile"; +import * as gatewayProviderMetadata from "./gateway-provider-metadata"; +import type { MessagingTokenDef } from "./messaging-prep"; +import type { OpenshellCliHelpers } from "./openshell-cli"; +import { createGatewayScopedOpenshellRunner } from "./setup-inference"; + +const providers = require("./providers"); + +export interface StageSandboxCredentialProvidersInput { + sandboxName: string; + enabledChannels: readonly string[]; + webSearchConfig: WebSearchConfig | null; + agent: Agent; +} + +type PreparedCredentialProviders = { + messagingTokenDefs: MessagingTokenDef[]; +}; + +type PrepareCredentialProviders = ( + input: StageSandboxCredentialProvidersInput, +) => Promise; + +export interface CredentialProviderRegistrationDeps { + root: string; + runOpenshell: OpenshellCliHelpers["runOpenshell"]; + redact(input: string): string; + getGatewayName(): string; + normalizeCredentialValue(value: unknown): string; + updateSession(mutator: (session: Session) => Session | void): Session; + stagedLegacyValues: ReadonlyMap; + migratedLegacyKeys: Set; + persistMigratedLegacyKeys(): void; +} + +function recordMigratedLegacyMessagingCredentials( + tokenDefs: readonly MessagingTokenDef[], + registeredProviderNames: readonly string[], + deps: CredentialProviderRegistrationDeps, +): void { + const registeredProviders = new Set(registeredProviderNames); + let mutated = false; + for (const def of tokenDefs) { + if (!registeredProviders.has(def.name) || !def.token || !def.envKey) continue; + const stagedValue = deps.stagedLegacyValues.get(def.envKey); + if (stagedValue === undefined) continue; + if (def.token === stagedValue) { + deps.migratedLegacyKeys.add(def.envKey); + } else { + deps.migratedLegacyKeys.delete(def.envKey); + } + mutated = true; + } + if (mutated) deps.persistMigratedLegacyKeys(); +} + +function setStagedCredentialProviderReceipts( + names: readonly string[], + staged: boolean, + deps: CredentialProviderRegistrationDeps, +): void { + if (names.length === 0) return; + deps.updateSession((current) => { + const providerNames = new Set(current.stagedCredentialProviders); + for (const name of names) { + if (staged) providerNames.add(name); + else providerNames.delete(name); + } + current.stagedCredentialProviders = [...providerNames]; + return current; + }); +} + +export function createCredentialProviderRegistration(deps: CredentialProviderRegistrationDeps) { + const gatewayRunner = () => + createGatewayScopedOpenshellRunner(deps.runOpenshell, deps.getGatewayName()); + const ensureWebSearchProviderProfiles = ( + tokenDefs: readonly MessagingTokenDef[], + runOpenshell: OpenshellCliHelpers["runOpenshell"] = deps.runOpenshell, + ) => + braveProviderProfile.ensureWebSearchProviderProfiles(tokenDefs, { + root: deps.root, + runOpenshell, + redact: deps.redact, + }); + + function upsertMessagingProviders( + tokenDefs: MessagingTokenDef[], + options: { replaceExisting?: boolean } = {}, + runOpenshell: OpenshellCliHelpers["runOpenshell"] = deps.runOpenshell, + ): string[] { + ensureWebSearchProviderProfiles(tokenDefs, runOpenshell); + const upserted = providers.upsertMessagingProviders( + tokenDefs, + runOpenshell, + options, + ) as string[]; + recordMigratedLegacyMessagingCredentials(tokenDefs, upserted, deps); + return upserted; + } + + function providerMatchesGatewayCredential( + name: string, + type: string, + credentialEnv: string, + ): boolean { + const runOpenshell = gatewayRunner(); + return gatewayProviderMetadata.matchesGatewayCredentialOnlyProviderBinding( + providers.readGatewayProviderMetadata(name, runOpenshell, deps.getGatewayName()), + { name, type, credentialKey: credentialEnv }, + ); + } + + function canRegisterCredential( + tokenDef: MessagingTokenDef, + runOpenshell: OpenshellCliHelpers["runOpenshell"], + ): boolean { + if (!providers.providerExistsInGateway(tokenDef.name, runOpenshell)) return true; + return gatewayProviderMetadata.matchesGatewayCredentialOnlyProviderBinding( + providers.readGatewayProviderMetadata(tokenDef.name, runOpenshell, deps.getGatewayName()), + { + name: tokenDef.name, + type: tokenDef.providerType || "generic", + credentialKey: tokenDef.envKey, + }, + ); + } + + async function stageSandboxCredentialProviders( + input: StageSandboxCredentialProvidersInput, + prepareCredentialProviders: PrepareCredentialProviders, + ): Promise { + const messaging = await prepareCredentialProviders(input); + const tokenDefs = messaging.messagingTokenDefs.filter((tokenDef) => + deps.normalizeCredentialValue(tokenDef.token), + ); + setStagedCredentialProviderReceipts( + tokenDefs.map((tokenDef) => tokenDef.name), + false, + deps, + ); + const runOpenshell = gatewayRunner(); + const registered = upsertMessagingProviders( + tokenDefs.filter((tokenDef) => canRegisterCredential(tokenDef, runOpenshell)), + {}, + runOpenshell, + ); + setStagedCredentialProviderReceipts(registered, true, deps); + return registered; + } + + return { + providerMatchesGatewayCredential, + stageSandboxCredentialProviders, + upsertMessagingProviders, + }; +} diff --git a/src/lib/onboard/gateway-provider-metadata.test.ts b/src/lib/onboard/gateway-provider-metadata.test.ts index d0032203659..211b8a773d4 100644 --- a/src/lib/onboard/gateway-provider-metadata.test.ts +++ b/src/lib/onboard/gateway-provider-metadata.test.ts @@ -4,6 +4,7 @@ import { describe, expect, it, vi } from "vitest"; import { + matchesGatewayCredentialOnlyProviderBinding, matchesGatewayProviderBinding, parseGatewayProviderMetadata, readGatewayProviderMetadata, @@ -43,6 +44,53 @@ describe("gateway provider metadata", () => { ).toBe(false); }); + it("matches only an exact credential-only provider binding", () => { + const metadata = { + name: "alpha-telegram-bridge", + type: "generic", + credentialKeys: ["TELEGRAM_BOT_TOKEN"], + configKeys: [], + }; + const expected = { + name: "alpha-telegram-bridge", + type: "generic", + credentialKey: "TELEGRAM_BOT_TOKEN", + }; + + expect(matchesGatewayCredentialOnlyProviderBinding(metadata, expected)).toBe(true); + expect(matchesGatewayCredentialOnlyProviderBinding(null, expected)).toBe(false); + expect( + matchesGatewayCredentialOnlyProviderBinding( + { ...metadata, name: "other-provider" }, + expected, + ), + ).toBe(false); + expect( + matchesGatewayCredentialOnlyProviderBinding({ ...metadata, type: "brave" }, expected), + ).toBe(false); + expect( + matchesGatewayCredentialOnlyProviderBinding( + { ...metadata, credentialKeys: ["OTHER_TOKEN"] }, + expected, + ), + ).toBe(false); + expect( + matchesGatewayCredentialOnlyProviderBinding({ ...metadata, credentialKeys: [] }, expected), + ).toBe(false); + expect( + matchesGatewayCredentialOnlyProviderBinding( + { ...metadata, credentialKeys: ["TELEGRAM_BOT_TOKEN", "OTHER_TOKEN"] }, + expected, + ), + ).toBe(false); + expect( + matchesGatewayCredentialOnlyProviderBinding( + { ...metadata, configKeys: ["EXTRA_CONFIG"] }, + expected, + ), + ).toBe(false); + }); + it("parses one complete ANSI-decorated provider identity", () => { expect(parseGatewayProviderMetadata(COMPLETE_OUTPUT)).toEqual({ name: "compatible-endpoint", diff --git a/src/lib/onboard/gateway-provider-metadata.ts b/src/lib/onboard/gateway-provider-metadata.ts index c78d0fe776b..8ab4072f468 100644 --- a/src/lib/onboard/gateway-provider-metadata.ts +++ b/src/lib/onboard/gateway-provider-metadata.ts @@ -27,6 +27,12 @@ export type GatewayProviderBinding = { configKey: string; }; +export type GatewayCredentialOnlyProviderBinding = { + name: string; + type: string; + credentialKey: string; +}; + /** Match the complete non-secret provider identity used for route decisions. */ export function matchesGatewayProviderBinding( metadata: GatewayProviderMetadata | null, @@ -43,6 +49,21 @@ export function matchesGatewayProviderBinding( ); } +/** Match a provider that exposes exactly one credential and no configuration. */ +export function matchesGatewayCredentialOnlyProviderBinding( + metadata: GatewayProviderMetadata | null, + expected: GatewayCredentialOnlyProviderBinding, +): boolean { + return Boolean( + metadata && + metadata.name === expected.name && + metadata.type === expected.type && + metadata.credentialKeys.length === 1 && + metadata.credentialKeys[0] === expected.credentialKey && + metadata.configKeys.length === 0, + ); +} + type GatewayProviderCommandResult = { status: number | null; stdout?: string | Buffer | null; diff --git a/src/lib/onboard/lifecycle-contracts.md b/src/lib/onboard/lifecycle-contracts.md index 4d2542ae680..5af832d553c 100644 --- a/src/lib/onboard/lifecycle-contracts.md +++ b/src/lib/onboard/lifecycle-contracts.md @@ -48,16 +48,20 @@ Every nonterminal state has one production owner or an explicit internal designa | `finalizing`, `post_verify` | `machine/handlers/finalization.ts` | | `complete`, `failed` | Terminal; no handler | -The FSM checkpoint is step-granular. It cannot resume inside gateway startup, credential upserts, sandbox creation, policy application, or another handler-owned effect group. +FSM transitions remain step-granular. For OpenClaw onboarding, the sandbox handler additionally checkpoints each completed secret-free prompt group: sandbox name, web search selection, messaging selection and non-secret configuration, and resource profile. After the sandbox name and web search are checkpointed, a validated web search credential may be registered in OpenShell before messaging. After messaging is checkpointed, validated messaging credentials may be registered before the resource prompt. Each successful registration saves a secret-free provider-name receipt. The machine still cannot resume inside gateway startup, an individual credential upsert, sandbox creation, policy application, or another handler-owned effect group. ## Effect-order flows `*` marks a durable checkpoint and `!` marks the sandbox-delete boundary. In-place destructive effects that occur earlier are called out in the matrix. ```text -fresh onboard +fresh OpenClaw onboard resolve entry options -> save session/machine* -> host preflight - -> gateway/provider effects -> resolve complete sandbox-create intent + -> gateway/inference-provider effects -> checkpoint name/web prompts* + -> create or update exact web-search provider + save name receipt* + -> checkpoint messaging prompts* -> create or update exact messaging providers + save name receipts* + -> checkpoint resource prompt* + -> resolve complete sandbox-create intent -> materialize create plan -> create -> ready -> live validation -> register* -> finalize session* @@ -94,14 +98,14 @@ runtime mutation | Journey and entry | Desired state, planning, and assembly | Visible and destructive boundaries | Checkpoint and secret boundary | Compensation, coverage, and gaps | |---|---|---|---|---| -| **New interactive or non-interactive onboard** — `onboard()` and `resolveOnboardEntryOptions` | Current flags, environment, and prompts. `MessagingWorkflowPlanner.buildPlan`, `prepareSandboxMessagingPreflight`, resource-profile selection, `resolveSandboxCreateIntent`, and `materializeSandboxCreatePlan` assemble policy, provider, package, resource, host-forward, and runtime-setup contributions. Non-interactive mode replaces prompts with defaults or hard aborts. | Consent/session/lock setup and preflight can persist local state, install OpenShell, or clean stale gateway artifacts before the gateway handler. Gateway reuse/recovery/start is the first provider-routing effect; inference-provider upserts follow. A name with no live sandbox has no sandbox-destructive boundary; an existing target enters the recreate contract below. | Whole-step session plus machine snapshot; registry registration is deferred until readiness and live validation. The session stores credential environment names, redacted endpoint metadata, and legacy-value digests; real values are rebound from the process at apply time. | A non-Docker-GPU readiness failure attempts to delete the failed sandbox; the Docker-GPU patch path preserves it and emits patch-specific recovery diagnostics. Temp build-context cleanup is attempted inline with an exit-handler fallback; cancel rollback applies only to a brand-new sandbox. Coverage: `transition-traces.test.ts` and `sandbox-create-plan.test.ts`. Gap: gateway upserts can outlive a failed/interrupted create. | +| **New interactive or non-interactive onboard** — `onboard()` and `resolveOnboardEntryOptions` | Current flags, environment, and prompts. `MessagingWorkflowPlanner.buildPlan`, `prepareSandboxMessagingPreflight`, resource-profile selection, `resolveSandboxCreateIntent`, and `materializeSandboxCreatePlan` assemble policy, provider, package, resource, host-forward, and runtime-setup contributions. Non-interactive mode replaces prompts with defaults or hard aborts. | Consent/session/lock setup and preflight can persist local state, install OpenShell, or clean stale gateway artifacts before the gateway handler. Gateway reuse/recovery/start is the first provider-routing effect; inference-provider upserts follow. For OpenClaw, a validated web-search provider can be created or updated after the name/web checkpoint and before messaging; validated messaging providers can be created or updated after the messaging checkpoint and before resource selection. A name with no live sandbox has no sandbox-destructive boundary; an existing target enters the recreate contract below. | Whole-step session plus machine snapshot. OpenClaw adds narrow checkpoints after each completed secret-free sandbox prompt group; sandbox registry registration is deferred until readiness and live validation. The session stores credential environment names, redacted endpoint metadata, legacy-value digests, and non-secret names of providers registered for resume; real values remain process- or gateway-bound. | A non-Docker-GPU readiness failure attempts to delete the failed sandbox; the Docker-GPU patch path preserves it and emits patch-specific recovery diagnostics. Temp build-context cleanup is attempted inline with an exit-handler fallback; cancel rollback applies only to a brand-new sandbox. Coverage: `transition-traces.test.ts`, `sandbox-create-intent-boundary.test.ts`, and `sandbox-create-plan.test.ts`. Gap: gateway upserts can outlive a failed/interrupted create. | | **`--fresh` onboard** — `resolveOnboardEntryOptions`, `prepareFreshSession`, `createBaseImageResolutionContext` | Current flags/environment/prompts replace resumable intent. `--fresh` disables auto-resume and forces base-image resolution; it does not prove that the selected sandbox name is unused. | The first destructive effect is local: the prior onboard session is cleared before a new session is saved. A matching live sandbox can later reuse or recreate through the normal sandbox decision; `--fresh` does not itself delete it. | The new session and machine snapshot replace the old resume checkpoint. Credential and effect boundaries then match new onboard or live recreate. | The discarded resume checkpoint is not restored on later failure. Covered by `entry-options.test.ts`, `session-bootstrap.test.ts`, and base-image resolution tests. | -| **Resume, re-onboard, or recreate** — `onboard()`, `prepareOnboardSession`, `decideSandboxResume`, live-sandbox handling in `createSandbox` | For `--resume`, the recorded session is authoritative and conflicting current name/provider/model/image/tool-disclosure hints are rejected. A new re-onboard run takes current flags, environment, and prompts as intent while registry/gateway state provides drift evidence. The machine resolves a complete secret-free create intent, including policy, messaging/provider, GPU, resource, disabled-channel, and agent inputs, before repair/removal or live recreation. | Ordinary live recreation conditionally backs up before provider cleanup, **delete**, image removal, and registry removal. A selected pre-upgrade backup suppresses a new one; an explicit override permits recreation without backup. Resume registry removal and `repair-and-recreate` now follow complete intent validation. Temporary policy/build artifacts remain materialization effects after the delete boundary. | Resume continues the recorded session/machine snapshot; non-resume re-onboard writes a new session first. The selected sandbox name is recorded when the sandbox step starts, while the complete intent stays process-local and is not persisted or emitted. Credential values are rebound and checked before mutation and again immediately before materialization. | Restore failures warn and can still publish the replacement; managed-DCode live-selection failure leaves a running, unregistered sandbox with manual-delete guidance. Cancel rollback is not armed and there is no rebuild-style receipt rollback. Coverage: transition traces, sandbox handler tests, create-intent characterization, and the real create boundary. Gaps: #5961/#5783, #6040, early backup asymmetry, and delete-to-register window (#6228). | +| **Resume, re-onboard, or recreate** — `onboard()`, `prepareOnboardSession`, `decideSandboxResume`, live-sandbox handling in `createSandbox` | For `--resume`, the recorded session is authoritative and conflicting current name/provider/model/image/tool-disclosure hints are rejected. A new re-onboard run takes current flags, environment, and prompts as intent while registry/gateway state provides drift evidence. The machine resolves a complete secret-free create intent, including policy, messaging/provider, GPU, resource, disabled-channel, and agent inputs, before repair/removal or live recreation. | Ordinary live recreation conditionally backs up before provider cleanup, **delete**, image removal, and registry removal. A selected pre-upgrade backup suppresses a new one; an explicit override permits recreation without backup. Resume registry removal and `repair-and-recreate` now follow complete intent validation. Temporary policy/build artifacts remain materialization effects after the delete boundary. | Resume continues the recorded session/machine snapshot; non-resume re-onboard writes a new session first. OpenClaw records completed sandbox name, web search, messaging, and resource choices with explicit progress markers, including explicit `null` choices, while the complete create intent stays process-local and is not persisted or emitted. Raw credential values remain outside the session. A missing process value can be rebound only when the same OpenClaw session recorded successfully registering that provider and its live name, type, and credential-key binding still match; otherwise interactive resume requests it again and non-interactive resume exits with environment-variable guidance. Credentials are checked before mutation and again immediately before materialization. | Restore failures warn and can still publish the replacement; managed-DCode live-selection failure leaves a running, unregistered sandbox with manual-delete guidance. Cancel rollback is not armed and there is no rebuild-style receipt rollback. Coverage: transition traces, sandbox handler tests, create-intent characterization, and the real create boundary. Gaps: #5961/#5783, #6040, early backup asymmetry, and delete-to-register window (#6228). | | **Rebuild or installer-driven upgrade** — `rebuildSandbox` in `rebuild-pipeline.ts`; `upgradeSandboxes` | Registry state is authoritative. A matching session may fill guarded legacy gaps only when its selection agrees; an unrelated/global session is never used. Ambient provider/model selection is quarantined by `isolateAmbientRecreateEnv`, apart from narrowly scoped legacy recovery. Preflight assembles target config, messaging/policy/runtime inputs, recovery inputs, and a retained replacement context. Generic agents use `preflightRebuildImage`; DCode uses its specialized managed-context preflight instead and proves the live route only for normal live rebuild. Resource profile is not part of preflight. | Consent persistence, target-gateway selection/recovery, and target-preflight registry updates can precede disposable image build/probes. Backup is the first durable recovery checkpoint when available. Shields unlock, MCP detach/scrub, and NIM stop are destructive in-place effects before the **sandbox delete** boundary. Prepared context and mutation-edge conditions are rechecked before delete, proving buildability/input identity but not replacement health or atomic swap. | Durable checkpoints are the backup/recovery manifest when one exists and the rewritten recreate session; stale recovery can reach deletion without a manifest, making that session its first new durable checkpoint. Rollback receipts/snapshots are process-local. Credential metadata comes from the target or guarded fallback; raw credentials/providers are checked against current process/gateway state, while prepared installer recovery may reconstruct a missing gateway provider from a validated host credential. | In-process rollback best-effort restores registry/MCP retry metadata, but process death after non-MCP delete can still lose it. The inner onboard selects resource profile after deletion from non-quarantined ambient input. Covered by rebuild, image-preflight, DCode, and messaging tests. Gaps: post-delete resource intent plus health-before-delete/atomic swap (#5801). | | **Channel add/remove/start/stop** — `addSandboxChannel`, `removeSandboxChannel`, `sandboxChannelsSetEnabled` in `policy-channel.ts` | Add compiles and merges a manifest-derived channel delta with `MessagingWorkflowPlanner`. Start, stop, and remove transform the registry plan and rehydrate executable render/build/runtime/forward details from current manifests. | Token-backed add can mutate gateway credentials before policy and plan persistence; QR/in-sandbox-auth add skips that credential upsert. Start persists the enabled plan before policy; stop persists the disabled plan before the rebuild prompt. Remove clears QR-backed durable state when applicable, detaches gateway/bridge state, removes policy, then persists the plan. A queued rebuild has a separate delete boundary. | The compact registry messaging plan is authoritative; render/build/runtime/state/health entries and nested host-forward details are rehydrated rather than persisted. Session policy-preset sync is best-effort, and channel mutations do not rewrite `Session.messagingPlan`. Raw tokens stay in process/gateway bindings. | `rollbackChannelAdd`, re-disable after failed start, and fail-closed QR-state cleanup provide partial compensation. Covered by `policy-channel*.test.ts`, `workflow-planner.test.ts`, and channel integration tests. Gaps: channel add has a separate `--force` conflict policy; add/remove effects can precede plan persistence, and persistence failures are not fully rolled back. | | **Provider, model, or credential-binding change** — `runInferenceSet` | CLI intent plus registry/session metadata. Target resolution and OpenShell preparation occur before locking. The target is re-resolved in the mutating phase under the sandbox lifecycle and timer-bound shields locks; that phase validates provider/model syntax, selected agent, shields state, and local reachability before the first write. | First mutation is the gateway route, then a minimal registry write, API-family/config resolution, registry refresh, best-effort config/hash sync, matching-session update, and audit. An OpenClaw API-family change can then restart the managed gateway after the shields lock is released but while the outer sandbox lock remains held. No sandbox deletion. | Registry and matching session store logical provider/model/credential-environment metadata. Audit records the action, sandbox, and reason rather than credentials; raw values remain gateway-bound. | Forward-only; no rollback. `rebuild` is the repair path for degraded state. Covered by `inference-set*.test.ts`. Gap: several stores can diverge after a mid-sequence failure. | | **Credential rotation** — `configRotateToken` in `src/lib/sandbox/config.ts` | A session with `credentialEnv` selects the provider and binding. A non-null different `sandboxName` is rejected, but a legacy/null session name is accepted for the requested sandbox. The new value comes from a named environment variable, stdin, or a secret prompt; it is trimmed, then rejected when empty or still containing internal whitespace. | `saveCredential` first stages the value in the current process. OpenShell provider update is the first external mutation, with provider create as a fallback; audit follows. No sandbox deletion. | The logical binding is unchanged, so session and registry are not rewritten. The raw value exists only in process memory/environment and the gateway provider; audit records action/sandbox/reason without the value. | No rollback after a successful provider update; an audit failure can report failure after the credential is already active. Covered by the rotate-token cases in `test/config-set-nested-ssrf.test.ts`. Gap: a null-name legacy session is not strongly bound to the requested sandbox. | -| **Config, policy, resource, port-forward, and runtime setup contributions** — `configSet`; `prepareInitialSandboxCreatePolicy`; `selectResourceProfileForSandbox`; manifest compiler/runtime appliers; dashboard and channel forward helpers | Config uses validated dotpaths and SSRF-safe URL rewriting. Create/rebuild contributions are assembled by `sandbox-create-plan.ts` and `MessagingWorkflowPlanner`: policy presets/keys, resource flags, package/build steps, `hostForward`, runtime node preloads, env aliases, and secret scans. | Config’s first effect is a compare-and-swap sandbox write. Build-time contributions inherit the enclosing create/recreate boundary. Forward helpers can stop an existing forward and start its replacement in place after readiness, without recreating the sandbox. | Durable owners are compact registry messaging/policy/inference metadata, current manifests used for plan rehydration, onboard session, sandbox config/hash, gateway provider state, and shields audit. Resource-profile selection is only a create-time argument, not durable state. Logical bindings are serializable; raw provider values are not. | CAS rejects stale config writes; OpenClaw/Hermes commit config and integrity hashes together, while other agents may refresh a path hash afterward. Audit and optional restart are post-commit and forward-only. Forward recovery can re-establish declared forwards. Gaps: no cross-contribution transaction/checkpoint, and resource choice is not persisted. | +| **Config, policy, resource, port-forward, and runtime setup contributions** — `configSet`; `prepareInitialSandboxCreatePolicy`; `selectResourceProfileForSandbox`; manifest compiler/runtime appliers; dashboard and channel forward helpers | Config uses validated dotpaths and SSRF-safe URL rewriting. Create/rebuild contributions are assembled by `sandbox-create-plan.ts` and `MessagingWorkflowPlanner`: policy presets/keys, resource flags, package/build steps, `hostForward`, runtime node preloads, env aliases, and secret scans. | Config’s first effect is a compare-and-swap sandbox write. Build-time contributions inherit the enclosing create/recreate boundary. Forward helpers can stop an existing forward and start its replacement in place after readiness, without recreating the sandbox. | Durable owners are compact registry messaging/policy/inference metadata, current manifests used for plan rehydration, onboard session, sandbox config/hash, gateway provider state, and shields audit. An interrupted onboarding session records the selected resource values or an explicit OpenShell-default choice; the resolved create intent remains process-local. Logical bindings are serializable; raw provider values are not. | CAS rejects stale config writes; OpenClaw/Hermes commit config and integrity hashes together, while other agents may refresh a path hash afterward. Audit and optional restart are post-commit and forward-only. Forward recovery can re-establish declared forwards. Gaps: no cross-contribution effect transaction/checkpoint. | ## Agent-specific differences @@ -113,16 +117,17 @@ runtime mutation ## Persisted field ownership -The schema and sanitation authority is `Session` plus `normalizeSession`/`filterSafeUpdates` in `src/lib/state/onboard-session.ts`. `undefined` in an update means “leave unchanged”; accepted `null` means “clear.” On disk, many nullable fields still collapse never selected, explicitly declined, and explicitly cleared into the same `null` representation. That ambiguity is a #6228 contract gap, not an endorsed target. +The schema and sanitation authority is `Session` plus `normalizeSession`/`filterSafeUpdates` in `src/lib/state/onboard-session.ts`. `undefined` in an update means “leave unchanged”; accepted `null` means “clear.” On disk, many nullable fields still collapse never selected, explicitly declined, and explicitly cleared into the same `null` representation. `sandboxPromptProgress` removes that ambiguity only for the checkpointed sandbox name, web search, messaging, and resource choices; the remaining ambiguity is a #6228 contract gap, not an endorsed target. | Field group | Fields | Writer/owner and state meaning | |---|---|---| | Session envelope | `version`, `sessionId`, `mode`, `startedAt`, `updatedAt`, `status`, `resumable` | `createSession`, save/update helpers, and completion/failure paths. Values are always known after creation. | -| Progress and recovery | `lastStepStarted`, `lastCompletedStep`, `failure`, `steps`, `machine` | Step-mutation helpers and `OnboardRuntime`; nullable progress fields mean no recorded value, not a separately modeled decline. | -| Target identity | `agent`, `sandboxName`, `metadata.gatewayName`, `metadata.fromDockerfile` | Onboard selection, sandbox handler/registration, and rebuild session preparation. Nullable identity currently conflates unset/cleared; a completed sandbox step is the trust gate for recorded name. | +| Progress and recovery | `lastStepStarted`, `lastCompletedStep`, `failure`, `steps`, `machine`, `sandboxPromptProgress`, `stagedCredentialProviders` | Step-mutation helpers and `OnboardRuntime` own whole-step progress; the OpenClaw sandbox handler owns prompt-group completion markers. `stagedCredentialProviders` contains only names registered before sandbox setup so OpenClaw resume can require both durable ownership and an exact live binding. A marker is trusted only when its matching persisted value is present and valid, including an explicit `null` where supported. | +| Target identity | `agent`, `sandboxName`, `metadata.gatewayName`, `metadata.fromDockerfile` | Onboard selection, sandbox handler/registration, and rebuild session preparation. A completed sandbox step or valid `sandboxPromptProgress.sandboxName` marker is the trust gate for a recorded name. | | Inference intent | `provider`, `model`, `endpointUrl`, `credentialEnv`, `preferredInferenceApi`, `compatibleEndpointReasoning`, `nimContainer`, `webSearchConfig` | Provider/inference handlers and `runInferenceSet`. Known credential state is an environment-variable name or presence metadata, never the value. `redactUrl` masks userinfo and fragments, redacts values under sensitive parameter names, and redacts canonical token-shaped values even under benign parameter names. | | Agent and policy intent | `hermesAuthMethod`, `toolDisclosure`, `hermesToolGateways`, `policyPresets` | Agent setup and policy handling. Channel commands update matching-session `policyPresets` only best-effort. Nullable fields conflate unset, declined, and cleared where the CLI makes those distinctions. | | Messaging intent | `messagingPlan`, `telegramConfig`, `wechatConfig` | Onboard/rebuild write the session plan; channel commands instead own the compact registry plan. `telegramConfig` and `wechatConfig` are legacy fallback/preserved fields, while current channel input comes from the plan/manifests. Tokens stay outside the session. | +| Resource choice | `resourceProfile` | The sandbox handler records concrete CPU/RAM values or `null` for an explicit OpenShell-default choice after the prompt completes. Environment overrides still take precedence on the recovery run. | | Runtime metadata | `routerPid`, `routerCredentialHash`, `gpuPassthrough` | Router and sandbox setup/recovery. PID is a live-process hint; credential hash is a digest; GPU is a concrete boolean. | | Legacy migration proof | `migratedLegacyValueHashes` | Onboard legacy migration writes SHA-256 digests keyed by environment name; session filtering guarantees string records but does not independently validate digest shape. | @@ -148,6 +153,7 @@ The registry is separately owned by `src/lib/state/registry.ts`; backup/recovery | #5954 | Rebuild conflict was discovered after delete | Fixed by #5955 | | #6099 | Late dashboard-forward failure could roll back a healthy sandbox | Open; #6116 | | #6195 | DCode rebuild deleted before replacement validation | Fixed by #6214 | +| #6743 | Resume repeated completed sandbox prompts | Fixed by secret-free sandbox prompt checkpoints | PR #6218 separated secret-free create intent from effectful materialization. PR #6214 added DCode-specific pre-delete replacement validation; generic rebuild now also retains and revalidates a prebuilt context. PR #5955 moved the rebuild messaging conflict check before destruction. The remaining ownership and recovery changes belong to the open child issues and should update this map and its focused traces when behavior intentionally changes. @@ -155,12 +161,12 @@ PR #6218 separated secret-free create intent from effectful materialization. PR | Contract | Executable evidence | Uncovered boundary | |---|---|---| -| Fresh, resumed, recreate, successful, and failed machine event order | `machine/transition-traces.test.ts` | Sub-step crash recovery and end-to-end delete-to-register effects | +| Fresh, resumed, recreate, successful, and failed machine event order | `machine/transition-traces.test.ts` | Effect-level crash recovery and end-to-end delete-to-register effects | | Detailed recreate decisions and repair branches | `machine/handlers/sandbox-resume.test.ts`, `machine/handlers/sandbox.test.ts` | Cross-handler effect transaction | | Legal edges, result kinds, runtime event shapes, runner sequencing | `machine/transitions.test.ts`, `machine/runtime.test.ts`, `machine/runner*.test.ts` | None at the unit boundary | | Create intent/provider ordering and fail-closed credential drift | `sandbox-create-plan.test.ts` | Cross-module pre-delete ordering has no behavioral seam | | Messaging conflict validation before recreate | `sandbox-messaging-preflight.test.ts`, rebuild preflight tests | One shared declarative policy across all callers | | Resume identity | `test/onboard.test.ts`, `handlers/sandbox-resume.test.ts` | Interrupted live-flow identity (#5961) | -| Session sanitation and no-secret persistence | `src/lib/state/onboard-session.test.ts` | Unset/declined/cleared modeling (#6228) | +| Session sanitation, sandbox prompt checkpoints, and no-secret persistence | `src/lib/state/onboard-session-sandbox-prompts.test.ts`, `machine/handlers/sandbox-create-intent-boundary.test.ts` | Unset/declined/cleared modeling outside the checkpointed sandbox choices (#6228) | When a child issue changes one of these contracts, update the map and the narrow owning test in that same PR. Do not add source-text scans or production scaffolding solely to preserve current orchestration order. diff --git a/src/lib/onboard/machine/core-flow-phases.test.ts b/src/lib/onboard/machine/core-flow-phases.test.ts index 2cf1f6bca96..52b0d150e4d 100644 --- a/src/lib/onboard/machine/core-flow-phases.test.ts +++ b/src/lib/onboard/machine/core-flow-phases.test.ts @@ -204,6 +204,8 @@ function createPhases( writePlanToEnv: vi.fn(), clearPlanEnv: vi.fn(), getRegistrySandboxMessagingPlan: () => null, + providerMatchesGatewayCredential: () => false, + stageSandboxCredentialProviders: vi.fn(async () => []), promptValidatedSandboxName: vi.fn(async () => "my-sandbox"), selectResourceProfileForSandbox: vi.fn(async () => null), stopStaleDashboardListenersForSandbox: vi.fn(), diff --git a/src/lib/onboard/machine/handlers/provider-inference.ts b/src/lib/onboard/machine/handlers/provider-inference.ts index 99f58434223..44a0491368c 100644 --- a/src/lib/onboard/machine/handlers/provider-inference.ts +++ b/src/lib/onboard/machine/handlers/provider-inference.ts @@ -439,6 +439,15 @@ export async function handleProviderInferenceState({ deps.log(" [resume] Refreshing compatible-endpoint inference route for messaging."); } deps.skippedStepMessage("provider_selection", `${provider} / ${model}`); + const agentName = (agent as { name?: string } | null)?.name; + if ( + (!agentName || agentName === "openclaw") && + sandboxName && + session?.sandboxPromptProgress?.sandboxName === true && + session.sandboxName === sandboxName + ) { + deps.log(` [resume] Reusing sandbox name: ${sandboxName}.`); + } await deps.recordStateSkipped("provider_selection", { reason: "resume", provider, diff --git a/src/lib/onboard/machine/handlers/sandbox-create-intent-boundary.test.ts b/src/lib/onboard/machine/handlers/sandbox-create-intent-boundary.test.ts index 714fd666629..8fc910432dc 100644 --- a/src/lib/onboard/machine/handlers/sandbox-create-intent-boundary.test.ts +++ b/src/lib/onboard/machine/handlers/sandbox-create-intent-boundary.test.ts @@ -5,12 +5,23 @@ import { describe, expect, it, vi } from "vitest"; import { createSession } from "../../../state/onboard-session"; import { handleSandboxState } from "./sandbox"; -import { baseOptions, createDeps } from "./sandbox-test-fixtures"; +import { + baseOptions, + createDeps, + makeMinimalPlan, + withTelegramCredentialHash, +} from "./sandbox-test-fixtures"; vi.mock("../../messaging-channel-setup", () => ({ detectMessagingChannelsFromEnv: vi.fn(() => []), })); +const braveConfig = { fetchEnabled: true as const, provider: "brave" as const }; +const resourceProfiles: [string, { cpu: string; memory: string } | null][] = [ + ["OpenShell defaults", null], + ["a selected profile", { cpu: "75%", memory: "75%" }], +]; + describe("sandbox create intent machine boundary", () => { it("rejects deterministic create conflicts before resume recreation mutates state (#6226)", async () => { const session = createSession({ sandboxName: "saved" }); @@ -103,4 +114,394 @@ describe("sandbox create intent machine boundary", () => { expect(resolvedIntents[1]).toEqual(resolvedIntents[0]); expect(resolvedIntents[2]).toEqual(resolvedIntents[0]); }); + + it("checkpoints a known sandbox name before an interrupted web-search prompt (#6743)", async () => { + const durableSession = createSession(); + const updateSession = vi.fn((mutator: (value: typeof durableSession) => void) => { + mutator(durableSession); + return durableSession; + }); + const configureWebSearch = vi.fn(async () => { + throw new Error("web-search prompt interrupted"); + }); + const { deps, calls } = createDeps({ updateSession, configureWebSearch }); + + await expect( + handleSandboxState({ ...baseOptions(deps, durableSession), sandboxName: "tm" }), + ).rejects.toThrow("web-search prompt interrupted"); + + expect(durableSession.sandboxName).toBe("tm"); + expect(durableSession.sandboxPromptProgress).toMatchObject({ + sandboxName: true, + webSearch: false, + messaging: false, + resourceProfile: false, + }); + expect(calls.setupMessaging).not.toHaveBeenCalled(); + expect(calls.selectResourceProfile).not.toHaveBeenCalled(); + }); + + it("prompts and checkpoints a missing sandbox name before web-search selection (#6743)", async () => { + const durableSession = createSession(); + const updateSession = vi.fn((mutator: (value: typeof durableSession) => void) => { + mutator(durableSession); + return durableSession; + }); + const events: string[] = []; + const configureWebSearch = vi.fn(async () => { + events.push("web-search"); + throw new Error("web-search prompt interrupted"); + }); + const { deps, calls } = createDeps({ updateSession, configureWebSearch }); + calls.promptName.mockImplementationOnce(async () => { + events.push("sandbox-name"); + return "tm"; + }); + + await expect(handleSandboxState(baseOptions(deps, durableSession))).rejects.toThrow( + "web-search prompt interrupted", + ); + + expect(events).toEqual(["sandbox-name", "web-search"]); + expect(durableSession.sandboxName).toBe("tm"); + expect(durableSession.sandboxPromptProgress).toMatchObject({ + sandboxName: true, + webSearch: false, + messaging: false, + resourceProfile: false, + }); + expect(calls.setupMessaging).not.toHaveBeenCalled(); + expect(calls.selectResourceProfile).not.toHaveBeenCalled(); + }); + + it("invalidates sandbox-bound messaging when an explicit resume name changes (#6743)", async () => { + const durableSession = createSession({ + sandboxName: "old-name", + webSearchConfig: null, + messagingPlan: makeMinimalPlan("old-name"), + resourceProfile: null, + sandboxPromptProgress: { + sandboxName: true, + webSearch: true, + messaging: true, + resourceProfile: false, + }, + }); + const updateSession = vi.fn((mutator: (value: typeof durableSession) => void) => { + mutator(durableSession); + return durableSession; + }); + const { deps, calls } = createDeps({ updateSession }); + calls.setupMessaging.mockRejectedValueOnce(new Error("messaging selection interrupted")); + + await expect( + handleSandboxState({ + ...baseOptions(deps, durableSession), + resume: true, + sandboxName: "new-name", + }), + ).rejects.toThrow("messaging selection interrupted"); + + expect(calls.clearPlanEnv).toHaveBeenCalledTimes(1); + expect(calls.setupMessaging).toHaveBeenCalledWith(null, null, "new-name"); + expect(durableSession.sandboxName).toBe("new-name"); + expect(durableSession.messagingPlan).toBeNull(); + expect(durableSession.sandboxPromptProgress.messaging).toBe(false); + }); + + it("resumes at the interrupted resource prompt after checkpointing earlier choices (#6743)", async () => { + const braveCredential = "brave-secret-value"; + const telegramCredential = "telegram-secret-value"; + const messagingPlan = withTelegramCredentialHash( + makeMinimalPlan("tm", "openclaw", ["telegram"]), + "a".repeat(64), + ); + const credentialEnv = { + BRAVE_API_KEY: braveCredential, + TELEGRAM_BOT_TOKEN: telegramCredential, + }; + const durableSession = createSession(); + const updateSession = vi.fn((mutator: (value: typeof durableSession) => void) => { + mutator(durableSession); + return durableSession; + }); + const recordStepComplete = vi.fn(async (_stepName: string, updates: object) => { + Object.assign(durableSession, updates); + return durableSession; + }); + const configureWebSearch = vi.fn(async () => braveConfig); + const setupMessagingChannels = vi.fn(async () => ["telegram"]); + const providerMatchesGatewayCredential = vi.fn( + (name: string, type: string, credentialEnvName: string) => + (name === "tm-brave-search" && type === "brave" && credentialEnvName === "BRAVE_API_KEY") || + (name === "tm-telegram-bridge" && + type === "generic" && + credentialEnvName === "TELEGRAM_BOT_TOKEN"), + ); + const stageSandboxCredentialProviders = vi + .fn<() => Promise>() + .mockImplementationOnce(async () => { + durableSession.stagedCredentialProviders = ["tm-brave-search"]; + return ["tm-brave-search"]; + }) + .mockImplementationOnce(async () => { + durableSession.stagedCredentialProviders.push("tm-telegram-bridge"); + return ["tm-telegram-bridge"]; + }) + .mockResolvedValue([]); + const readMessagingPlanFromEnv = vi + .fn<() => typeof messagingPlan | null>() + .mockReturnValueOnce(null) + .mockReturnValueOnce(messagingPlan) + .mockReturnValue(null); + const { deps, calls } = createDeps({ + updateSession, + recordStepComplete, + configureWebSearch, + setupMessagingChannels, + providerMatchesGatewayCredential, + stageSandboxCredentialProviders, + readMessagingPlanFromEnv, + }); + calls.selectResourceProfile.mockRejectedValueOnce(new Error("resource prompt interrupted")); + + await expect( + handleSandboxState({ + ...baseOptions(deps, durableSession), + sandboxName: "tm", + env: credentialEnv, + }), + ).rejects.toThrow("resource prompt interrupted"); + + expect(durableSession).toMatchObject({ + sandboxName: "tm", + webSearchConfig: braveConfig, + messagingPlan, + stagedCredentialProviders: ["tm-brave-search", "tm-telegram-bridge"], + resourceProfile: null, + sandboxPromptProgress: { + sandboxName: true, + webSearch: true, + messaging: true, + resourceProfile: false, + }, + }); + expect(calls.resolveCreateIntent).not.toHaveBeenCalled(); + expect(calls.createSandbox).not.toHaveBeenCalled(); + expect(stageSandboxCredentialProviders).toHaveBeenCalledWith({ + sandboxName: "tm", + enabledChannels: [], + webSearchConfig: braveConfig, + agent: null, + }); + expect(stageSandboxCredentialProviders.mock.invocationCallOrder[0]).toBeLessThan( + setupMessagingChannels.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY, + ); + expect(stageSandboxCredentialProviders.mock.invocationCallOrder[0]).toBeLessThan( + calls.selectResourceProfile.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY, + ); + expect(stageSandboxCredentialProviders).toHaveBeenNthCalledWith(2, { + sandboxName: "tm", + enabledChannels: ["telegram"], + webSearchConfig: null, + agent: null, + }); + expect(stageSandboxCredentialProviders.mock.invocationCallOrder[1]).toBeGreaterThan( + setupMessagingChannels.mock.invocationCallOrder[0] ?? Number.NEGATIVE_INFINITY, + ); + expect(stageSandboxCredentialProviders.mock.invocationCallOrder[1]).toBeLessThan( + calls.selectResourceProfile.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY, + ); + + calls.selectResourceProfile.mockResolvedValueOnce({ cpu: "75%", memory: "75%" }); + await handleSandboxState({ + ...baseOptions(deps, durableSession), + resume: true, + sandboxName: durableSession.sandboxName, + webSearchConfig: durableSession.webSearchConfig, + env: {}, + }); + + expect(configureWebSearch).toHaveBeenCalledTimes(1); + expect(setupMessagingChannels).toHaveBeenCalledTimes(1); + expect(calls.validateBrave).not.toHaveBeenCalled(); + expect(providerMatchesGatewayCredential).toHaveBeenCalledWith( + "tm-brave-search", + "brave", + "BRAVE_API_KEY", + ); + expect(providerMatchesGatewayCredential).toHaveBeenCalledWith( + "tm-telegram-bridge", + "generic", + "TELEGRAM_BOT_TOKEN", + ); + expect(calls.promptName).not.toHaveBeenCalled(); + expect(calls.selectResourceProfile).toHaveBeenCalledTimes(2); + expect(calls.resolveCreateIntent).toHaveBeenCalledTimes(1); + expect(calls.createSandbox).toHaveBeenCalledTimes(1); + expect(durableSession.sandboxPromptProgress.resourceProfile).toBe(true); + expect(durableSession.resourceProfile).toEqual({ cpu: "75%", memory: "75%" }); + + const serializedSession = JSON.stringify(durableSession); + expect(serializedSession).not.toContain(braveCredential); + expect(serializedSession).not.toContain(telegramCredential); + expect(serializedSession).not.toContain('"resolved"'); + expect(serializedSession).not.toContain('"resourceCreateArgs"'); + }); + + it("keeps an active channel choice but reacquires its missing credential after restart (#6743)", async () => { + const messagingPlan = withTelegramCredentialHash( + makeMinimalPlan("tm", "openclaw", ["telegram"]), + "a".repeat(64), + ); + const durableSession = createSession({ + sandboxName: "tm", + webSearchConfig: null, + messagingPlan, + resourceProfile: null, + sandboxPromptProgress: { + sandboxName: true, + webSearch: true, + messaging: true, + resourceProfile: true, + }, + }); + const updateSession = vi.fn((mutator: (value: typeof durableSession) => void) => { + mutator(durableSession); + return durableSession; + }); + const { deps, calls } = createDeps({ updateSession }); + calls.setupMessaging.mockRejectedValueOnce(new Error("telegram token prompt interrupted")); + + await expect( + handleSandboxState({ + ...baseOptions(deps, durableSession), + resume: true, + sandboxName: "tm", + }), + ).rejects.toThrow("telegram token prompt interrupted"); + + expect(calls.configureWebSearch).not.toHaveBeenCalled(); + expect(calls.promptName).not.toHaveBeenCalled(); + expect(calls.setupMessaging).toHaveBeenCalledWith(null, ["telegram"], "tm", { + selectionCompleted: true, + }); + expect(calls.selectResourceProfile).not.toHaveBeenCalled(); + expect(calls.resolveCreateIntent).not.toHaveBeenCalled(); + expect(calls.createSandbox).not.toHaveBeenCalled(); + expect(durableSession.messagingPlan).toEqual(messagingPlan); + expect(durableSession.sandboxPromptProgress.messaging).toBe(true); + }); + + it("keeps a completed disabled channel choice without reacquiring credentials (#6743)", async () => { + const messagingPlan = withTelegramCredentialHash( + makeMinimalPlan("tm", "openclaw", ["telegram"], ["telegram"]), + "a".repeat(64), + ); + const durableSession = createSession({ + sandboxName: "tm", + webSearchConfig: null, + messagingPlan, + resourceProfile: null, + sandboxPromptProgress: { + sandboxName: true, + webSearch: true, + messaging: true, + resourceProfile: true, + }, + }); + const updateSession = vi.fn((mutator: (value: typeof durableSession) => void) => { + mutator(durableSession); + return durableSession; + }); + const recordStepComplete = vi.fn(async (_stepName: string, updates: object) => { + Object.assign(durableSession, updates); + return durableSession; + }); + const { deps, calls } = createDeps({ updateSession, recordStepComplete }); + + const result = await handleSandboxState({ + ...baseOptions(deps, durableSession), + resume: true, + sandboxName: "tm", + }); + + expect(calls.configureWebSearch).not.toHaveBeenCalled(); + expect(calls.promptName).not.toHaveBeenCalled(); + expect(calls.setupMessaging).not.toHaveBeenCalled(); + expect(calls.showMessagingStage).toHaveBeenCalledOnce(); + expect(calls.selectResourceProfile).not.toHaveBeenCalled(); + expect(calls.note).toHaveBeenCalledWith(" [resume] Reusing web search selection: disabled."); + expect(calls.note).toHaveBeenCalledWith( + " [resume] Reusing messaging selection: no active channels.", + ); + expect(calls.note).toHaveBeenCalledWith(" [resume] Reusing OpenShell default resources."); + expect(calls.resolveCreateIntent).toHaveBeenCalledWith( + expect.objectContaining({ enabledChannels: [] }), + ); + expect((calls.createSandbox.mock.calls[0] as unknown[])[6]).toEqual([]); + expect(result.selectedMessagingChannels).toEqual([]); + }); + + it.each( + resourceProfiles, + )("reuses %s after intent resolution is interrupted and recomputes the intent (#6743)", async (_label, selectedResourceProfile) => { + const messagingPlan = makeMinimalPlan("tm"); + const durableSession = createSession({ + sandboxName: "tm", + webSearchConfig: braveConfig, + messagingPlan, + resourceProfile: null, + sandboxPromptProgress: { + sandboxName: true, + webSearch: true, + messaging: true, + resourceProfile: false, + }, + }); + const updateSession = vi.fn((mutator: (value: typeof durableSession) => void) => { + mutator(durableSession); + return durableSession; + }); + const recordStepComplete = vi.fn(async (_stepName: string, updates: object) => { + Object.assign(durableSession, updates); + return durableSession; + }); + const { deps, calls } = createDeps({ updateSession, recordStepComplete }); + calls.selectResourceProfile.mockResolvedValue(selectedResourceProfile); + calls.resolveCreateIntent.mockRejectedValueOnce(new Error("intent resolution interrupted")); + + const options = () => ({ + ...baseOptions(deps, durableSession), + resume: true, + sandboxName: durableSession.sandboxName, + webSearchConfig: durableSession.webSearchConfig, + }); + await expect(handleSandboxState(options())).rejects.toThrow("intent resolution interrupted"); + + expect(durableSession.sandboxPromptProgress.resourceProfile).toBe(true); + expect(durableSession.resourceProfile).toEqual(selectedResourceProfile); + expect(calls.startStep).not.toHaveBeenCalled(); + expect(calls.createSandbox).not.toHaveBeenCalled(); + + await handleSandboxState(options()); + + expect(calls.configureWebSearch).not.toHaveBeenCalled(); + expect(calls.setupMessaging).not.toHaveBeenCalled(); + expect(calls.promptName).not.toHaveBeenCalled(); + expect(calls.selectResourceProfile).toHaveBeenCalledTimes(1); + expect(calls.resolveCreateIntent).toHaveBeenCalledTimes(2); + expect(calls.resolveCreateIntent.mock.calls[1]?.[0]).toEqual( + calls.resolveCreateIntent.mock.calls[0]?.[0], + ); + expect(calls.resolveCreateIntent).toHaveBeenLastCalledWith( + expect.objectContaining({ resourceProfile: selectedResourceProfile }), + ); + expect(calls.createSandbox).toHaveBeenCalledTimes(1); + expect((calls.createSandbox.mock.calls[0] as unknown[])[11]).toEqual(selectedResourceProfile); + + const serializedSession = JSON.stringify(durableSession); + expect(serializedSession).not.toContain('"resolved"'); + expect(serializedSession).not.toContain('"resourceCreateArgs"'); + }); }); diff --git a/src/lib/onboard/machine/handlers/sandbox-messaging.test.ts b/src/lib/onboard/machine/handlers/sandbox-messaging.test.ts index f6590b00bda..4ed783da655 100644 --- a/src/lib/onboard/machine/handlers/sandbox-messaging.test.ts +++ b/src/lib/onboard/machine/handlers/sandbox-messaging.test.ts @@ -1,10 +1,12 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { describe, expect, it } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { SandboxMessagingPlan } from "../../../messaging/manifest"; -import { reconcileReusedSandboxMessaging } from "./sandbox-messaging"; +import { hashCredential } from "../../../security/credential-hash"; +import { createSession } from "../../../state/onboard-session"; +import { reconcileReusedSandboxMessaging, reconcileSandboxMessaging } from "./sandbox-messaging"; const channelIds = ["telegram", "unsupported"]; @@ -99,6 +101,86 @@ function channelIdsFrom(entries: reado return entries.map((entry) => entry.channelId); } +function telegramPlan(credentialHash: string): SandboxMessagingPlan { + return { + schemaVersion: 1, + sandboxName: "alpha", + agent: "openclaw", + workflow: "onboard", + channels: [ + { + channelId: "telegram", + displayName: "Telegram", + authMode: "token-paste", + active: true, + selected: true, + configured: true, + disabled: false, + inputs: [], + hooks: [], + }, + ], + disabledChannels: [], + credentialBindings: [ + { + channelId: "telegram", + credentialId: "botToken", + sourceInput: "botToken", + providerName: "alpha-telegram-bridge", + providerEnvKey: "TELEGRAM_BOT_TOKEN", + placeholder: "openshell:resolve:env:TELEGRAM_BOT_TOKEN", + credentialAvailable: true, + credentialHash, + }, + ], + networkPolicy: { presets: [], entries: [] }, + agentRender: [], + buildSteps: [], + stateUpdates: [], + healthChecks: [], + }; +} + +function completedCheckpointSession( + plan: SandboxMessagingPlan, + stagedCredentialProviders: string[] = [], +) { + const session = createSession(); + session.sandboxName = plan.sandboxName; + session.messagingPlan = plan; + session.stagedCredentialProviders = stagedCredentialProviders; + session.sandboxPromptProgress.sandboxName = true; + session.sandboxPromptProgress.messaging = true; + return session; +} + +function reconcileDeps(plans: readonly (SandboxMessagingPlan | null)[]) { + return { + note: vi.fn(), + showMessagingStage: vi.fn(), + getRecordedMessagingChannelsForResume: vi.fn(() => null), + setupMessagingChannels: vi.fn(async () => ["telegram"]), + readMessagingPlanFromEnv: vi + .fn() + .mockReturnValueOnce(plans[0] ?? null) + .mockReturnValue(plans[1] ?? plans[0] ?? null), + writePlanToEnv: vi.fn(), + clearPlanEnv: vi.fn(), + getRegistrySandboxMessagingPlan: vi.fn(() => null), + providerMatchesGatewayCredential: vi.fn(() => false), + }; +} + +beforeEach(() => { + vi.unstubAllEnvs(); + vi.restoreAllMocks(); +}); + +afterEach(() => { + vi.unstubAllEnvs(); + vi.restoreAllMocks(); +}); + describe("reconcileReusedSandboxMessaging", () => { it("removes every unsupported channel artifact from a reused plan", () => { const result = reconcileReusedSandboxMessaging( @@ -140,3 +222,128 @@ describe("reconcileReusedSandboxMessaging", () => { }); }); }); + +describe("reconcileSandboxMessaging completed checkpoint credentials", () => { + it("reuses an active channel only when the process credential matches the persisted hash", async () => { + const token = "123456:accepted-telegram-token"; + const plan = telegramPlan(hashCredential(token) ?? ""); + const deps = reconcileDeps([null]); + vi.stubEnv("TELEGRAM_BOT_TOKEN", token); + + const result = await reconcileSandboxMessaging({ + resume: true, + session: completedCheckpointSession(plan), + sandboxName: "alpha", + agent: { name: "openclaw" }, + deps, + }); + + expect(deps.setupMessagingChannels).not.toHaveBeenCalled(); + expect(deps.writePlanToEnv).toHaveBeenCalledWith(plan); + expect(deps.showMessagingStage).toHaveBeenCalledOnce(); + expect(result).toEqual({ plan, selectedChannels: ["telegram"] }); + }); + + it("runs existing setup validation before accepting a changed Telegram token", async () => { + const previousToken = "123456:previous-telegram-token"; + const changedToken = "123456:changed-telegram-token"; + const persistedPlan = telegramPlan(hashCredential(previousToken) ?? ""); + const validatedPlan = telegramPlan(hashCredential(changedToken) ?? ""); + const deps = reconcileDeps([persistedPlan, validatedPlan]); + vi.stubEnv("TELEGRAM_BOT_TOKEN", changedToken); + + const result = await reconcileSandboxMessaging({ + resume: true, + session: completedCheckpointSession(persistedPlan), + sandboxName: "alpha", + agent: { name: "openclaw" }, + deps, + }); + + expect(deps.setupMessagingChannels).toHaveBeenCalledWith( + { name: "openclaw" }, + ["telegram"], + "alpha", + { selectionCompleted: true }, + ); + expect(deps.writePlanToEnv).toHaveBeenCalledWith(persistedPlan); + expect(result).toEqual({ plan: validatedPlan, selectedChannels: ["telegram"] }); + }); + + it("propagates Telegram rejection instead of refreshing the persisted hash", async () => { + const previousToken = "123456:previous-telegram-token"; + const rejectedToken = "123456:rejected-telegram-token"; + const persistedPlan = telegramPlan(hashCredential(previousToken) ?? ""); + const deps = reconcileDeps([persistedPlan]); + deps.setupMessagingChannels.mockRejectedValueOnce( + new Error("Bot token was rejected by Telegram"), + ); + vi.stubEnv("TELEGRAM_BOT_TOKEN", rejectedToken); + + await expect( + reconcileSandboxMessaging({ + resume: true, + session: completedCheckpointSession(persistedPlan), + sandboxName: "alpha", + agent: { name: "openclaw" }, + deps, + }), + ).rejects.toThrow("Bot token was rejected by Telegram"); + + expect(deps.setupMessagingChannels).toHaveBeenCalledWith( + { name: "openclaw" }, + ["telegram"], + "alpha", + { selectionCompleted: true }, + ); + expect(deps.writePlanToEnv).toHaveBeenCalledWith(persistedPlan); + expect(persistedPlan.credentialBindings[0]?.credentialHash).toBe(hashCredential(previousToken)); + }); + + it("runs existing setup validation when the checkpointed credential lacks a staging receipt", async () => { + const persistedPlan = telegramPlan(hashCredential("123456:previous-token") ?? ""); + const deps = reconcileDeps([persistedPlan]); + deps.providerMatchesGatewayCredential.mockReturnValueOnce(true); + deps.setupMessagingChannels.mockRejectedValueOnce(new Error("Telegram token is required")); + + await expect( + reconcileSandboxMessaging({ + resume: true, + session: completedCheckpointSession(persistedPlan), + sandboxName: "alpha", + agent: { name: "openclaw" }, + deps, + }), + ).rejects.toThrow("Telegram token is required"); + + expect(deps.setupMessagingChannels).toHaveBeenCalledWith( + { name: "openclaw" }, + ["telegram"], + "alpha", + { selectionCompleted: true }, + ); + expect(deps.providerMatchesGatewayCredential).not.toHaveBeenCalled(); + }); + + it("reuses an exact OpenShell provider when the raw credential is unavailable (#6743)", async () => { + const persistedPlan = telegramPlan(hashCredential("123456:previous-token") ?? ""); + const deps = reconcileDeps([null]); + deps.providerMatchesGatewayCredential.mockReturnValueOnce(true); + + const result = await reconcileSandboxMessaging({ + resume: true, + session: completedCheckpointSession(persistedPlan, ["alpha-telegram-bridge"]), + sandboxName: "alpha", + agent: { name: "openclaw" }, + deps, + }); + + expect(deps.providerMatchesGatewayCredential).toHaveBeenCalledWith( + "alpha-telegram-bridge", + "generic", + "TELEGRAM_BOT_TOKEN", + ); + expect(deps.setupMessagingChannels).not.toHaveBeenCalled(); + expect(result).toEqual({ plan: persistedPlan, selectedChannels: ["telegram"] }); + }); +}); diff --git a/src/lib/onboard/machine/handlers/sandbox-messaging.ts b/src/lib/onboard/machine/handlers/sandbox-messaging.ts index 0979ef46b89..e973e9c5b6a 100644 --- a/src/lib/onboard/machine/handlers/sandbox-messaging.ts +++ b/src/lib/onboard/machine/handlers/sandbox-messaging.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { getCredential } from "../../../credentials/store"; import { createBuiltInChannelManifestRegistry, listSupportedMessagingChannelIdsForAgent, @@ -18,6 +19,7 @@ type MessagingAgentLike = { export interface SandboxMessagingDeps { note(message: string): void; + showMessagingStage?(): void; getRecordedMessagingChannelsForResume( resume: boolean, session: Session | null, @@ -27,11 +29,13 @@ export interface SandboxMessagingDeps { agent: Agent, existingChannels: string[] | null, sandboxName: string, + options?: { readonly selectionCompleted?: boolean }, ): Promise; readMessagingPlanFromEnv(): SandboxMessagingPlan | null; writePlanToEnv(plan: SandboxMessagingPlan): void; clearPlanEnv(): void; getRegistrySandboxMessagingPlan(sandboxName: string): SandboxMessagingPlan | null; + providerMatchesGatewayCredential(name: string, type: string, credentialEnv: string): boolean; } export interface SandboxMessagingSelection { @@ -157,12 +161,21 @@ function selectionFromReusablePlan( async function selectionFromMessagingSetup( existingChannels: string[] | null, options: ReconcileSandboxMessagingOptions, + selectionCompleted = false, ): Promise { const existing = existingChannels ? filterChannelNamesForCurrentAgent(existingChannels, options.agent) : existingChannels; + const setupOptions = selectionCompleted ? { selectionCompleted: true } : undefined; const selected = filterChannelNamesForCurrentAgent( - await options.deps.setupMessagingChannels(options.agent, existing, options.sandboxName), + setupOptions + ? await options.deps.setupMessagingChannels( + options.agent, + existing, + options.sandboxName, + setupOptions, + ) + : await options.deps.setupMessagingChannels(options.agent, existing, options.sandboxName), options.agent, ); const plan = options.deps.readMessagingPlanFromEnv(); @@ -250,6 +263,71 @@ export function reconcileReusedSandboxMessaging( }; } +async function selectionFromCompletedMessagingCheckpoint( + envPlan: SandboxMessagingPlan | null, + options: ReconcileSandboxMessagingOptions, +): Promise { + // A completed checkpoint makes the session copy authoritative. The process + // plan may already have refreshed hashes, so it cannot prove that a newly + // exported credential passed the channel's validation hooks. + const durablePlan = options.session?.messagingPlan ?? null; + if (!durablePlan) { + options.deps.clearPlanEnv(); + options.deps.showMessagingStage?.(); + options.deps.note(" [resume] Reusing messaging selection: no channels."); + return { plan: null, selectedChannels: [] }; + } + + const filteredPlan = filterMessagingPlanForCurrentAgent(durablePlan, options.agent); + if (!filteredPlan) { + options.deps.clearPlanEnv(); + options.deps.showMessagingStage?.(); + options.deps.note(" [resume] Reusing messaging selection: no active channels."); + return { plan: null, selectedChannels: [] }; + } + const selectedChannels = getActiveChannelsFromPlan(filteredPlan); + if (selectedChannels.length === 0) { + const selection = selectionFromReusablePlan( + durablePlan, + options.agent, + envPlan !== durablePlan, + options.deps, + ); + options.deps.showMessagingStage?.(); + options.deps.note(" [resume] Reusing messaging selection: no active channels."); + return selection; + } + + const activeChannels = new Set(selectedChannels); + const credentialNeedsValidation = filteredPlan.credentialBindings.some((binding) => { + if (!activeChannels.has(binding.channelId)) return false; + const credentialHash = hashCredential(getCredential(binding.providerEnvKey)); + if (credentialHash) return credentialHash !== binding.credentialHash; + if (!options.session?.stagedCredentialProviders.includes(binding.providerName)) return true; + return !options.deps.providerMatchesGatewayCredential( + binding.providerName, + "generic", + binding.providerEnvKey, + ); + }); + if (credentialNeedsValidation) { + options.deps.writePlanToEnv(durablePlan); + return selectionFromMessagingSetup(selectedChannels, options, true); + } + + const selection = selectionFromReusablePlan( + durablePlan, + options.agent, + envPlan !== durablePlan, + options.deps, + ); + options.deps.showMessagingStage?.(); + options.deps.note( + ` [resume] Reusing messaging channels: ${selection.selectedChannels.join(", ")}.`, + ); + return selection; +} + export async function reconcileSandboxMessaging( options: ReconcileSandboxMessagingOptions, ): Promise { @@ -259,6 +337,14 @@ export async function reconcileSandboxMessaging( options.sandboxName, ); const envPlan = options.deps.readMessagingPlanFromEnv(); + const agentName = (options.agent as MessagingAgentLike | null)?.name; + if ( + (!agentName || agentName === "openclaw") && + options.resume && + options.session?.sandboxPromptProgress?.messaging === true + ) { + return selectionFromCompletedMessagingCheckpoint(envPlan, options); + } const registryPlan = options.deps.getRegistrySandboxMessagingPlan(options.sandboxName); if (recordedChannels) { return selectionFromRecordedChannels(recordedChannels, envPlan, registryPlan, options); 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 f565dbefc88..a31fa521ed6 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 @@ -49,9 +49,13 @@ describe("sandbox registration route transaction", () => { expect(calls.error).not.toHaveBeenCalled(); }); - it("holds sandbox, host dashboard, then gateway locks through creation and registration", async () => { + it("stages credentials, then holds sandbox, host dashboard, and gateway locks through creation", async () => { const events: string[] = []; const { deps } = createDeps({ + configureWebSearch: vi.fn(async () => ({ + fetchEnabled: true as const, + provider: "brave" as const, + })), checkGatewayRouteCompatibility: () => { events.push("guard"); return { ok: true }; @@ -68,6 +72,10 @@ describe("sandbox registration route transaction", () => { events.push("gateway-lock"); return await operation(); }, + stageSandboxCredentialProviders: async () => { + events.push("stage"); + return []; + }, createSandbox: async () => { events.push("create"); return "my-assistant"; @@ -81,6 +89,8 @@ describe("sandbox registration route transaction", () => { sandboxName: "my-assistant", }); expect(events).toEqual([ + "gateway-lock", + "stage", "sandbox-lock", "dashboard-lock", "gateway-lock", diff --git a/src/lib/onboard/machine/handlers/sandbox-test-fixtures.ts b/src/lib/onboard/machine/handlers/sandbox-test-fixtures.ts index 2497879fc05..b8a9795fb18 100644 --- a/src/lib/onboard/machine/handlers/sandbox-test-fixtures.ts +++ b/src/lib/onboard/machine/handlers/sandbox-test-fixtures.ts @@ -111,7 +111,9 @@ export function createDeps( configureWebSearch: vi.fn(async () => null as WebSearchConfig | null), startStep: vi.fn(async () => undefined), getRecordedChannels: vi.fn(() => null), + showMessagingStage: vi.fn(), setupMessaging: vi.fn(async () => [] as string[]), + stageCredentialProviders: vi.fn(async () => [] as string[]), promptName: vi.fn(async () => "my-assistant"), selectResourceProfile: vi.fn(async () => null as ResourceProfile | null), stopStale: vi.fn(), @@ -217,11 +219,14 @@ export function createDeps( configureWebSearch: calls.configureWebSearch, startRecordedStep: calls.startStep, getRecordedMessagingChannelsForResume: calls.getRecordedChannels, + showMessagingStage: calls.showMessagingStage, setupMessagingChannels: calls.setupMessaging, readMessagingPlanFromEnv: () => null, writePlanToEnv: () => undefined, clearPlanEnv: calls.clearPlanEnv, getRegistrySandboxMessagingPlan: () => null, + providerMatchesGatewayCredential: () => false, + stageSandboxCredentialProviders: calls.stageCredentialProviders, promptValidatedSandboxName: calls.promptName, selectResourceProfileForSandbox: calls.selectResourceProfile, stopStaleDashboardListenersForSandbox: calls.stopStale, diff --git a/src/lib/onboard/machine/handlers/sandbox-tool-disclosure.test.ts b/src/lib/onboard/machine/handlers/sandbox-tool-disclosure.test.ts index 209a177645d..922d27e084b 100644 --- a/src/lib/onboard/machine/handlers/sandbox-tool-disclosure.test.ts +++ b/src/lib/onboard/machine/handlers/sandbox-tool-disclosure.test.ts @@ -126,6 +126,7 @@ describe("handleSandboxState tool disclosure", () => { toolDisclosure: requestedMode, observabilityEnabled: false, extraProviders: [], + reuseRegisteredCredentials: true, }, ); }); diff --git a/src/lib/onboard/machine/handlers/sandbox.test.ts b/src/lib/onboard/machine/handlers/sandbox.test.ts index 3b45d20b427..d74d038dcd7 100644 --- a/src/lib/onboard/machine/handlers/sandbox.test.ts +++ b/src/lib/onboard/machine/handlers/sandbox.test.ts @@ -699,6 +699,12 @@ describe("handleSandboxState", () => { const session = createSession({ sandboxName: "saved", webSearchConfig: { fetchEnabled: true }, + sandboxPromptProgress: { + sandboxName: true, + webSearch: true, + messaging: false, + resourceProfile: false, + }, }); session.steps.sandbox.status = "complete"; const { deps, calls } = createDeps({ @@ -722,6 +728,9 @@ describe("handleSandboxState", () => { expect(calls.note).toHaveBeenCalledWith( " [resume] Web Search configuration changed; recreating sandbox.", ); + expect(calls.note).not.toHaveBeenCalledWith( + " [resume] Reusing web search selection: disabled.", + ); expect(calls.removeSandbox).toHaveBeenCalledWith("saved"); expect(calls.createSandbox).toHaveBeenCalled(); }); @@ -774,6 +783,7 @@ describe("handleSandboxState", () => { toolDisclosure: "progressive", observabilityEnabled: false, extraProviders: [], + reuseRegisteredCredentials: true, }, ); expect(result.webSearchConfigChanged).toBe(true); @@ -894,6 +904,7 @@ describe("handleSandboxState", () => { toolDisclosure: "progressive", observabilityEnabled: false, extraProviders: [], + reuseRegisteredCredentials: true, }, ); expect(result.webSearchConfig).toBeNull(); diff --git a/src/lib/onboard/machine/handlers/sandbox.ts b/src/lib/onboard/machine/handlers/sandbox.ts index c7a3d6253d7..9f49313e08f 100644 --- a/src/lib/onboard/machine/handlers/sandbox.ts +++ b/src/lib/onboard/machine/handlers/sandbox.ts @@ -12,11 +12,17 @@ import { type WebSearchConfig as SharedWebSearchConfig, WEB_SEARCH_PROVIDER_ENV, webSearchConfigsEqual, + webSearchEnvFor, webSearchLabelFor, webSearchProviderForConfig, } from "../../../inference/web-search"; import type { SandboxMessagingPlan } from "../../../messaging/manifest"; -import type { HermesAuthMethod, Session, SessionUpdates } from "../../../state/onboard-session"; +import type { + HermesAuthMethod, + Session, + SessionResourceProfile, + SessionUpdates, +} from "../../../state/onboard-session"; import type { SandboxEntry } from "../../../state/registry"; import { getSandboxEntryInference } from "../../../state/registry-entry-view"; import { toolDisclosureOrDefault } from "../../../tool-disclosure"; @@ -156,15 +162,24 @@ export interface SandboxStateOptions< session: Session | null, sandboxName: string | null, ): string[] | null; + showMessagingStage?(): void; setupMessagingChannels( agent: Agent, existingChannels: string[] | null, sandboxName: string, + options?: { readonly selectionCompleted?: boolean }, ): Promise; readMessagingPlanFromEnv(): SandboxMessagingPlan | null; writePlanToEnv(plan: SandboxMessagingPlan): void; clearPlanEnv(): void; getRegistrySandboxMessagingPlan(sandboxName: string): SandboxMessagingPlan | null; + providerMatchesGatewayCredential(name: string, type: string, credentialEnv: string): boolean; + stageSandboxCredentialProviders(input: { + sandboxName: string; + enabledChannels: readonly string[]; + webSearchConfig: WebSearchConfig | null; + agent: Agent; + }): Promise; promptValidatedSandboxName(agent: Agent): Promise; selectResourceProfileForSandbox(): Promise; stopStaleDashboardListenersForSandbox(sandboxes: unknown[], sandboxName: string): void; @@ -183,6 +198,7 @@ export interface SandboxStateOptions< extraProviders: readonly string[]; staleExtraProviders: readonly string[]; policyTier?: string | null; + reuseRegisteredCredentials?: boolean; }): Promise; createSandbox( gpu: Gpu, @@ -295,6 +311,10 @@ function effectiveHermesToolGatewaysForWebSearch( : [...gateways]; } +function hasResourceProfileEnvOverride(env: NodeJS.ProcessEnv): boolean { + return Boolean(env.NEMOCLAW_RESOURCE_PROFILE || env.NEMOCLAW_CPU || env.NEMOCLAW_RAM); +} + type SandboxCreationDecision = Exclude; type CompleteSandboxCreateIntent = SandboxCreateIntent & { readonly resolved: ResolvedSandboxCreateIntent; @@ -344,6 +364,11 @@ class SandboxStateFlow< return this.options.deps; } + private get resumesSandboxPrompts(): boolean { + const agentName = (this.options.agent as { name?: string } | null)?.name; + return !agentName || agentName === "openclaw"; + } + private prepareWebSearchSupport(): SandboxStepState { const probePath = this.options.fromDockerfile ? this.deps.resolvePath(this.options.fromDockerfile) @@ -626,18 +651,30 @@ class SandboxStateFlow< private async resolveWebSearchForCreation( state: SandboxStepState, ): Promise { - if (!state.webSearchConfig) { - if (this.options.authoritativeResumeConfig) return null; - return this.deps.configureWebSearch( - null, - this.options.agent, - state.webSearchSupportProbePath, - ); - } + if (!state.webSearchConfig) return this.resolveAbsentWebSearchForCreation(state); const provider = webSearchProviderForConfig( state.webSearchConfig as unknown as SharedWebSearchConfig, ); const label = webSearchLabelFor(provider); + const credentialEnv = webSearchEnvFor(provider); + const localCredential = this.options.env[credentialEnv]?.trim(); + if ( + this.resumesSandboxPrompts && + this.options.resume && + state.sandboxName && + !localCredential && + state.session?.stagedCredentialProviders.includes( + `${state.sandboxName}-${provider}-search`, + ) && + this.deps.providerMatchesGatewayCredential( + `${state.sandboxName}-${provider}-search`, + provider, + credentialEnv, + ) + ) { + this.deps.note(` [resume] Reusing ${label} credential registered with OpenShell.`); + return state.webSearchConfig; + } this.deps.note(` [resume] Revalidating ${label} configuration for sandbox recreation.`); const credential = await this.deps.ensureValidatedWebSearchCredential(state.webSearchConfig); if (this.deps.isBackToSelection(credential) || !credential) return null; @@ -645,6 +682,135 @@ class SandboxStateFlow< return state.webSearchConfig; } + private resolveAbsentWebSearchForCreation( + state: SandboxStepState, + ): Promise | null { + const explicitlyConfigured = parseExplicitWebSearchProvider( + this.options.env[WEB_SEARCH_PROVIDER_ENV], + ).specified; + const completedSelection = + this.resumesSandboxPrompts && + this.options.resume && + state.session?.sandboxPromptProgress?.webSearch === true; + if (!this.options.authoritativeResumeConfig && !explicitlyConfigured && !completedSelection) { + return this.deps.configureWebSearch( + null, + this.options.agent, + state.webSearchSupportProbePath, + ); + } + if (completedSelection && !explicitlyConfigured && !state.webSearchSupportDropped) { + this.deps.note(" [resume] Reusing web search selection: disabled."); + } + return null; + } + + private checkpointWebSearch( + state: SandboxStepState, + webSearchConfig: WebSearchConfig | null, + ): SandboxStepState { + if (!this.resumesSandboxPrompts) return { ...state, webSearchConfig }; + const session = this.deps.updateSession((current) => { + current.webSearchConfig = webSearchConfig as unknown as Session["webSearchConfig"]; + current.sandboxPromptProgress.webSearch = true; + return current; + }); + return { ...state, session, webSearchConfig }; + } + + private checkpointSandboxName( + state: SandboxStepState, + sandboxName: string, + ): SandboxStepState { + if (!this.resumesSandboxPrompts) return { ...state, sandboxName }; + let messagingInvalidated = false; + const session = this.deps.updateSession((current) => { + const recordedNameChanged = + current.sandboxName !== null && current.sandboxName !== sandboxName; + const messagingPlanTargetsAnotherName = + current.messagingPlan !== null && current.messagingPlan.sandboxName !== sandboxName; + if (recordedNameChanged || messagingPlanTargetsAnotherName) { + current.messagingPlan = null; + current.sandboxPromptProgress.messaging = false; + messagingInvalidated = true; + } + current.sandboxName = sandboxName; + current.sandboxPromptProgress.sandboxName = true; + return current; + }); + if (messagingInvalidated) this.deps.clearPlanEnv(); + return { ...state, session, sandboxName }; + } + + private checkpointMessaging( + state: SandboxStepState, + messaging: { plan: SandboxMessagingPlan | null; selectedChannels: string[] }, + ): SandboxStepState { + if (!this.resumesSandboxPrompts) { + return { ...state, selectedMessagingChannels: messaging.selectedChannels }; + } + const session = this.deps.updateSession((current) => { + current.messagingPlan = messaging.plan; + current.sandboxPromptProgress.messaging = true; + return current; + }); + return { + ...state, + session, + selectedMessagingChannels: messaging.selectedChannels, + }; + } + + private async registerCompletedCredentialProviders( + sandboxName: string, + enabledChannels: readonly string[], + webSearchConfig: WebSearchConfig | null, + ): Promise { + if (!this.resumesSandboxPrompts || (!webSearchConfig && enabledChannels.length === 0)) return; + const registeredProviders = await this.deps.withGatewayRouteMutationLock( + this.options.gatewayName, + () => + this.deps.stageSandboxCredentialProviders({ + sandboxName, + enabledChannels, + webSearchConfig, + agent: this.options.agent, + }), + ); + if (registeredProviders.length > 0) { + this.deps.note(" ✓ Registered selected credentials with OpenShell for resume."); + } + } + + private async resolveResourceProfile(state: SandboxStepState): Promise<{ + state: SandboxStepState; + resourceProfile: ResourceProfile | null; + }> { + if ( + this.resumesSandboxPrompts && + this.options.resume && + state.session?.sandboxPromptProgress?.resourceProfile === true && + !hasResourceProfileEnvOverride(this.options.env) + ) { + const resourceProfile = state.session.resourceProfile as ResourceProfile | null; + this.deps.note( + resourceProfile + ? " [resume] Reusing resource profile selection." + : " [resume] Reusing OpenShell default resources.", + ); + return { state, resourceProfile }; + } + + const resourceProfile = await this.deps.selectResourceProfileForSandbox(); + if (!this.resumesSandboxPrompts) return { state, resourceProfile }; + const session = this.deps.updateSession((current) => { + current.resourceProfile = resourceProfile as SessionResourceProfile | null; + current.sandboxPromptProgress.resourceProfile = true; + return current; + }); + return { state: { ...state, session }, resourceProfile }; + } + private async buildSandboxCreateIntent( state: SandboxStepState, sandboxName: string, @@ -654,6 +820,7 @@ class SandboxStateFlow< resourceProfile: ResourceProfile | null, hermesToolGateways: readonly string[], ): Promise { + const reuseRegisteredCredentials = this.resumesSandboxPrompts && this.options.resume; const resolved = await this.deps.resolveSandboxCreateIntent({ sandboxName, enabledChannels: state.selectedMessagingChannels, @@ -664,6 +831,7 @@ class SandboxStateFlow< hermesToolGateways, extraProviders, staleExtraProviders, + ...(reuseRegisteredCredentials ? { reuseRegisteredCredentials: true } : {}), ...(this.options.authoritativePolicyTier !== undefined ? { policyTier: this.options.authoritativePolicyTier } : {}), @@ -673,6 +841,7 @@ class SandboxStateFlow< recreate: decision.kind !== "create", toolDisclosure: toolDisclosureOrDefault(state.session?.toolDisclosure), observabilityEnabled: state.session?.observabilityEnabled === true, + ...(reuseRegisteredCredentials ? { reuseRegisteredCredentials: true as const } : {}), ...(this.options.endpointUrl ? { endpointUrl: this.options.endpointUrl } : {}), ...(state.session?.observabilityRequestedExplicitly === true ? { observabilityRequestedExplicitly: true as const } @@ -689,18 +858,20 @@ class SandboxStateFlow< } private async createAndRecordSandbox( - state: SandboxStepState, + initialState: SandboxStepState, requestedSandboxName: string, messagingPlan: SandboxMessagingPlan | null, decision: SandboxCreationDecision, ): Promise> { + const resourceSelection = await this.resolveResourceProfile(initialState); + const state = resourceSelection.state; + const resourceProfile = resourceSelection.resourceProfile; const effectiveHermesToolGateways = effectiveHermesToolGatewaysForWebSearch( this.options.agent as { name?: string } | null, state.webSearchConfig as unknown as SharedWebSearchConfig | null, this.options.hermesToolGateways, ); const extraProviderPlan = this.deps.planRegisteredExtraProviders(this.options.gatewayName); - const resourceProfile = await this.deps.selectResourceProfileForSandbox(); const createIntent = await this.buildSandboxCreateIntent( state, requestedSandboxName, @@ -809,34 +980,48 @@ class SandboxStateFlow< this.deps.error(mcpBlockReason); return this.deps.exitProcess(1); } - const webSearchConfig = await this.resolveWebSearchForCreation(state); + let nextState = state.sandboxName + ? this.checkpointSandboxName(state, state.sandboxName) + : state; + const requestedSandboxName = + nextState.sandboxName ?? (await this.deps.promptValidatedSandboxName(this.options.agent)); + if (!nextState.sandboxName) { + nextState = this.checkpointSandboxName(nextState, requestedSandboxName); + } + const webSearchConfig = await this.resolveWebSearchForCreation(nextState); const webSearchConfigChanged = - state.webSearchConfigChanged || + nextState.webSearchConfigChanged || !webSearchConfigsEqual( - state.webSearchConfig as unknown as SharedWebSearchConfig | null, + nextState.webSearchConfig as unknown as SharedWebSearchConfig | null, webSearchConfig as unknown as SharedWebSearchConfig | null, ); - const requestedSandboxName = - state.sandboxName ?? (await this.deps.promptValidatedSandboxName(this.options.agent)); + nextState = this.checkpointWebSearch( + { + ...nextState, + webSearchConfig, + webSearchConfigChanged, + }, + webSearchConfig, + ); + await this.registerCompletedCredentialProviders( + requestedSandboxName, + [], + nextState.webSearchConfig, + ); const messaging = await reconcileSandboxMessaging({ resume: this.options.resume, - session: state.session, + session: nextState.session, sandboxName: requestedSandboxName, agent: this.options.agent, deps: this.deps, }); - return this.createAndRecordSandbox( - { - ...state, - sandboxName: requestedSandboxName, - webSearchConfig, - webSearchConfigChanged, - selectedMessagingChannels: messaging.selectedChannels, - }, + nextState = this.checkpointMessaging(nextState, messaging); + await this.registerCompletedCredentialProviders( requestedSandboxName, - messaging.plan, - decision, + nextState.selectedMessagingChannels, + null, ); + return this.createAndRecordSandbox(nextState, requestedSandboxName, messaging.plan, decision); } private complete(state: SandboxStepState): SandboxStateResult { diff --git a/src/lib/onboard/messaging-channel-setup.test.ts b/src/lib/onboard/messaging-channel-setup.test.ts index ed965683e13..ac9ba11945c 100644 --- a/src/lib/onboard/messaging-channel-setup.test.ts +++ b/src/lib/onboard/messaging-channel-setup.test.ts @@ -412,6 +412,110 @@ describe("setupMessagingChannels", () => { expect(prompt).not.toHaveBeenCalled(); }); + it("reuses a completed channel selection while reacquiring only its missing credential (#6743)", async () => { + delete process.env.TELEGRAM_BOT_TOKEN; + delete process.env.TELEGRAM_ALLOWED_IDS; + delete process.env.TELEGRAM_REQUIRE_MENTION; + delete process.env.TELEGRAM_GROUP_POLICY; + process.env.SLACK_BOT_TOKEN = "xoxb-ambient-slack-token"; + process.env.SLACK_APP_TOKEN = "xapp-ambient-slack-token"; + vi.mocked(prompt).mockResolvedValueOnce("123456:resumed-telegram-token"); + const step = vi.fn(); + const note = vi.fn(); + + const result = await setupMessagingChannels(null, ["telegram"], { + sandboxName: "tm", + selectionCompleted: true, + step, + note, + }); + + expect(result).toEqual(["telegram"]); + expect(step).toHaveBeenCalledWith(5, 8, "Messaging channels"); + expect(note).toHaveBeenCalledWith( + " [resume] Reusing messaging channel selection; requesting missing credentials only.", + ); + expect(prompt).toHaveBeenCalledOnce(); + expect(prompt).toHaveBeenCalledWith(" Telegram Bot Token: ", { secret: true }); + expect(saveCredential).toHaveBeenCalledWith( + "TELEGRAM_BOT_TOKEN", + "123456:resumed-telegram-token", + ); + expect(MessagingSetupApplier.requirePlanFromEnv()).toMatchObject({ + sandboxName: "tm", + channels: [ + { + channelId: "telegram", + active: true, + inputs: expect.arrayContaining([ + expect.objectContaining({ inputId: "requireMention", value: "1" }), + expect.objectContaining({ inputId: "groupPolicy", value: "open" }), + ]), + }, + ], + }); + }); + + it("preserves completed non-default config while reacquiring a missing credential (#6743)", async () => { + process.env.TELEGRAM_BOT_TOKEN = "123456:original-telegram-token"; + process.env.TELEGRAM_REQUIRE_MENTION = "0"; + process.env.TELEGRAM_GROUP_POLICY = "disabled"; + await setupSelectedMessagingChannels( + ["telegram"], + new Set(["telegram"]), + manifests("telegram"), + { sandboxName: "tm" }, + ); + + delete process.env.TELEGRAM_BOT_TOKEN; + delete process.env.TELEGRAM_REQUIRE_MENTION; + delete process.env.TELEGRAM_GROUP_POLICY; + vi.mocked(prompt).mockClear(); + vi.mocked(prompt).mockResolvedValueOnce("123456:resumed-telegram-token"); + + await setupMessagingChannels(null, ["telegram"], { + sandboxName: "tm", + selectionCompleted: true, + }); + + expect(prompt).toHaveBeenCalledOnce(); + expect(prompt).toHaveBeenCalledWith(" Telegram Bot Token: ", { secret: true }); + expect(MessagingSetupApplier.requirePlanFromEnv()).toMatchObject({ + channels: [ + { + channelId: "telegram", + inputs: expect.arrayContaining([ + expect.objectContaining({ inputId: "requireMention", value: "0" }), + expect.objectContaining({ inputId: "groupPolicy", value: "disabled" }), + ]), + }, + ], + }); + }); + + it("preserves a completed channel selection when non-interactive resume lacks its credential (#6743)", async () => { + delete process.env.TELEGRAM_BOT_TOKEN; + process.env[MESSAGING_SETUP_APPLIER_ENV_KEY] = "durable-plan"; + const note = vi.fn(); + + await expect( + setupMessagingChannels(null, ["telegram"], { + isNonInteractive: () => true, + note, + sandboxName: "tm", + selectionCompleted: true, + }), + ).rejects.toThrow( + "Export the missing messaging credential environment variables, then run nemoclaw onboard --resume again.", + ); + + expect(note).toHaveBeenCalledWith( + expect.stringContaining("completed messaging selection is missing required credentials"), + ); + expect(process.env[MESSAGING_SETUP_APPLIER_ENV_KEY]).toBe("durable-plan"); + expect(prompt).not.toHaveBeenCalled(); + }); + it("skips partially configured multi-secret channels in non-interactive mode", async () => { process.env.SLACK_BOT_TOKEN = "xoxb-test-slack-token"; const notes: string[] = []; diff --git a/src/lib/onboard/messaging-channel-setup.ts b/src/lib/onboard/messaging-channel-setup.ts index 83a8d55c79a..d0368625c1c 100644 --- a/src/lib/onboard/messaging-channel-setup.ts +++ b/src/lib/onboard/messaging-channel-setup.ts @@ -38,6 +38,8 @@ export interface SetupSelectedMessagingChannelsOptions { readonly agent?: { readonly name?: string } | null; readonly sandboxName?: string | null; readonly interactive?: boolean; + /** Reuse already-answered config fields while reacquiring process-only credentials. */ + readonly configurationCompleted?: boolean; } export interface SetupMessagingChannelsDeps { @@ -45,6 +47,8 @@ export interface SetupMessagingChannelsDeps { readonly note?: (message: string) => void; readonly isNonInteractive?: () => boolean; readonly sandboxName?: string | null; + /** The channel selection is durable; do not reopen the selector on resume. */ + readonly selectionCompleted?: boolean; } const getMessagingToken = (envKey: string): string | null => @@ -87,6 +91,10 @@ export async function setupMessagingChannels( deps: SetupMessagingChannelsDeps = {}, ): Promise { deps.step?.(5, 8, "Messaging channels"); + const note = deps.note ?? console.log; + const isNonInteractive = + deps.isNonInteractive ?? (() => process.env.NEMOCLAW_NON_INTERACTIVE === "1"); + const nonInteractive = isNonInteractive() || process.env.NEMOCLAW_NON_INTERACTIVE === "1"; const invalidConfigEnvValues = detectInvalidMessagingChannelConfigEnvValues(); for (const { key, rawValue, validValues } of invalidConfigEnvValues) { @@ -98,9 +106,16 @@ export async function setupMessagingChannels( } if (invalidConfigEnvValues.length > 0) process.exit(1); - const note = deps.note ?? console.log; - const isNonInteractive = - deps.isNonInteractive ?? (() => process.env.NEMOCLAW_NON_INTERACTIVE === "1"); + if (deps.selectionCompleted) { + if (nonInteractive) { + const message = + "A completed messaging selection is missing required credentials. Export the missing messaging credential environment variables, then run nemoclaw onboard --resume again."; + note(` [resume] ${message}`); + throw new Error(message); + } + note(" [resume] Reusing messaging channel selection; requesting missing credentials only."); + } + const manifestRegistry = createBuiltInChannelManifestRegistry(); const availabilityContext = getMessagingManifestAvailabilityContext( agent, @@ -114,7 +129,7 @@ export async function setupMessagingChannels( includeAllExisting, }); - if (isNonInteractive() || process.env.NEMOCLAW_NON_INTERACTIVE === "1") { + if (nonInteractive) { const enabled = new Set(seedFromState(false)); const found = Array.from(enabled); if (found.length > 0) { @@ -131,13 +146,19 @@ export async function setupMessagingChannels( return Array.from(enabled); } - const enabled = new Set(seedFromState(true)); + const enabled = new Set( + deps.selectionCompleted + ? (existingChannels ?? []).filter((channelId) => + availableChannels.some((manifest) => manifest.id === channelId), + ) + : seedFromState(true), + ); const input = process.stdin as MessagingSelectorInput; const output = process.stderr as MessagingSelectorOutput; const statusForChannel = (manifest: ChannelManifest): string => hasManifestConfiguredInputs(manifest) ? " (configured)" : ""; - if (availableChannels.length > 0) { + if (!deps.selectionCompleted && availableChannels.length > 0) { if (!input.isTTY || !output.isTTY || typeof input.setRawMode !== "function") { await promptMessagingChannelLineSelection(availableChannels, enabled, statusForChannel); } else { @@ -169,12 +190,46 @@ export async function setupMessagingChannels( await setupSelectedMessagingChannels(selected, enabled, availableChannels, { agent, sandboxName: deps.sandboxName, + configurationCompleted: deps.selectionCompleted, }); console.log(""); return Array.from(enabled); } +function completedConfigurationEnv( + sandboxName: string, + agent: ReturnType, + selectedChannels: readonly string[], +): NodeJS.ProcessEnv { + const env = { ...process.env }; + const persistedPlan = MessagingSetupApplier.readPlanFromEnv(); + if ( + !persistedPlan || + persistedPlan.sandboxName !== sandboxName || + persistedPlan.agent !== agent + ) { + return env; + } + + const selected = new Set(selectedChannels); + for (const channel of persistedPlan.channels) { + if (!selected.has(channel.channelId)) continue; + for (const input of channel.inputs) { + if ( + input.kind !== "config" || + !input.sourceEnv || + typeof input.value !== "string" || + resolveMessagingChannelConfigEnvValue(input.sourceEnv, process.env).value + ) { + continue; + } + env[input.sourceEnv] = input.value; + } + } + return env; +} + /** * Prompt for token + per-channel config for each selected messaging channel. * @@ -199,9 +254,23 @@ export async function setupSelectedMessagingChannels( const agent = toMessagingAgentId(options.agent, registry.list()); const sandboxName = resolveMessagingSetupSandboxName(options); + const hooks = options.configurationCompleted + ? createBuiltInMessagingHookRegistry({ + common: { + // Completed optional/default config prompts are represented by their + // persisted values or absence. Seed only non-secret values into an + // isolated hook environment so reacquiring a raw token neither asks + // those questions again nor resets a prior answer to its default. + configPrompt: { + env: completedConfigurationEnv(sandboxName, agent, selectedChannels), + prompt: async () => "", + }, + }, + }) + : createBuiltInMessagingHookRegistry(); const planner = new MessagingWorkflowPlanner( registry, - createBuiltInMessagingHookRegistry(), + hooks, createBuiltInRenderTemplateResolver(), ); diff --git a/src/lib/onboard/messaging-prep.test.ts b/src/lib/onboard/messaging-prep.test.ts index 886d3489961..968f7291e84 100644 --- a/src/lib/onboard/messaging-prep.test.ts +++ b/src/lib/onboard/messaging-prep.test.ts @@ -37,6 +37,7 @@ function createInput( return null; }, providerExistsInGateway: () => false, + providerMatchesGatewayCredential: () => false, ...overrides, }; } @@ -92,6 +93,30 @@ describe("prepareCreateSandboxMessaging", () => { expect(registerExtraPlaceholderProviders).not.toHaveBeenCalled(); }); + it("reuses an exact Brave gateway provider when the raw key is unavailable (#6743)", () => { + const providerMatchesGatewayCredential = vi.fn( + (name: string, type: string, credentialEnv: string) => + name === "demo-brave-search" && type === "brave" && credentialEnv === BRAVE_API_KEY_ENV, + ); + + const result = prepareCreateSandboxMessaging( + createInput({ + webSearchConfig: { fetchEnabled: true }, + requireExactProviderBinding: true, + providerMatchesGatewayCredential, + }), + ); + + expect(result.missingWebSearchCredentialEnv).toBeNull(); + expect(result.messagingTokenDefs).toContainEqual({ + name: "demo-brave-search", + envKey: BRAVE_API_KEY_ENV, + token: null, + providerType: "brave", + }); + expect(result.reusableMessagingProviders).toEqual(["demo-brave-search"]); + }); + it("reports a missing Tavily key using the selected provider credential", () => { const result = prepareCreateSandboxMessaging( createInput({ @@ -182,12 +207,12 @@ describe("prepareCreateSandboxMessaging", () => { }); it("includes all static token-backed channels by default without probing reusable providers", () => { - const providerExistsInGateway = vi.fn(() => true); + const providerMatchesGatewayCredential = vi.fn(() => true); const result = prepareCreateSandboxMessaging( createInput({ enabledChannels: null, - providerExistsInGateway, + providerMatchesGatewayCredential, }), ); @@ -201,7 +226,7 @@ describe("prepareCreateSandboxMessaging", () => { ]); expect(result.reusableMessagingProviders).toEqual([]); expect(result.reusableMessagingChannels).toEqual([]); - expect(providerExistsInGateway).not.toHaveBeenCalled(); + expect(providerMatchesGatewayCredential).not.toHaveBeenCalled(); }); it("uses BRAVE_API_KEY from host env when the credential store has no value", () => { diff --git a/src/lib/onboard/messaging-prep.ts b/src/lib/onboard/messaging-prep.ts index fa9079a9755..df9dbc7ce7c 100644 --- a/src/lib/onboard/messaging-prep.ts +++ b/src/lib/onboard/messaging-prep.ts @@ -19,6 +19,7 @@ export interface MessagingTokenDef { export interface CreateSandboxMessagingPrepInput { sandboxName: string; agentName?: string | null; + requireExactProviderBinding?: boolean; channels: readonly NamedMessagingChannel[]; enabledChannels: readonly string[] | null; disabledChannels: readonly string[]; @@ -36,6 +37,7 @@ export interface CreateSandboxMessagingPrepInput { ): string[]; getMessagingChannelForEnvKey(envKey: string): string | null; providerExistsInGateway(name: string): boolean; + providerMatchesGatewayCredential(name: string, type: string, credentialEnv: string): boolean; } export interface CreateSandboxMessagingPrepResult { @@ -51,6 +53,9 @@ export interface CreateSandboxMessagingPrepResult { export function prepareCreateSandboxMessaging( input: CreateSandboxMessagingPrepInput, ): CreateSandboxMessagingPrepResult { + const requiresExactOpenClawProviderBinding = + input.requireExactProviderBinding === true && + (!input.agentName || input.agentName.trim().toLowerCase() === "openclaw"); const enabledEnvKeys = input.enabledChannels != null ? new Set( @@ -79,12 +84,29 @@ export function prepareCreateSandboxMessaging( const webSearchEnabled = braveProviderProfile.shouldEnableWebSearch(input.webSearchConfig); const webSearchProvider = webSearch.webSearchProviderForConfig(input.webSearchConfig); const webSearchCredentialEnv = webSearch.webSearchEnvFor(webSearchProvider); + const webSearchProviderType = + webSearchProvider === "tavily" && input.agentName?.trim().toLowerCase() === "hermes" + ? braveProviderProfile.HERMES_TAVILY_PROVIDER_PROFILE_ID + : webSearchProvider; + const webSearchProviderName = `${input.sandboxName}-${webSearchProvider}-search`; const webSearchApiKey = webSearchEnabled ? input.getCredential(webSearchCredentialEnv) || - input.normalizeCredentialValue(input.env[webSearchCredentialEnv]) + input.normalizeCredentialValue(input.env[webSearchCredentialEnv]) || + null : null; + const reusableWebSearchProvider = + requiresExactOpenClawProviderBinding && + webSearchEnabled && + !webSearchApiKey && + input.providerMatchesGatewayCredential( + webSearchProviderName, + webSearchProviderType, + webSearchCredentialEnv, + ); const missingWebSearchCredentialEnv = - webSearchEnabled && !webSearchApiKey ? webSearchCredentialEnv : null; + webSearchEnabled && !webSearchApiKey && !reusableWebSearchProvider + ? webSearchCredentialEnv + : null; if (missingWebSearchCredentialEnv) { return { disabledChannelNames, @@ -98,15 +120,11 @@ export function prepareCreateSandboxMessaging( } if (webSearchEnabled) { - const providerType = - webSearchProvider === "tavily" && input.agentName?.trim().toLowerCase() === "hermes" - ? braveProviderProfile.HERMES_TAVILY_PROVIDER_PROFILE_ID - : webSearchProvider; messagingTokenDefs.push({ - name: `${input.sandboxName}-${webSearchProvider}-search`, + name: webSearchProviderName, envKey: webSearchCredentialEnv, token: webSearchApiKey, - providerType, + providerType: webSearchProviderType, }); } @@ -115,7 +133,9 @@ export function prepareCreateSandboxMessaging( messagingTokenDefs, ); const hasMessagingTokens = messagingTokenDefs.some(({ token }) => !!token); - const reusableMessagingProviders: string[] = []; + const reusableMessagingProviders: string[] = reusableWebSearchProvider + ? [webSearchProviderName] + : []; const reusableMessagingChannels: string[] = []; if (input.enabledChannels != null) { @@ -123,7 +143,10 @@ export function prepareCreateSandboxMessaging( if (token) continue; const channel = input.getMessagingChannelForEnvKey(envKey); if (!channel || !input.enabledChannels.includes(channel)) continue; - if (!input.providerExistsInGateway(name)) continue; + const providerReusable = requiresExactOpenClawProviderBinding + ? input.providerMatchesGatewayCredential(name, "generic", envKey) + : input.providerExistsInGateway(name); + if (!providerReusable) continue; reusableMessagingProviders.push(name); if (!reusableMessagingChannels.includes(channel)) { reusableMessagingChannels.push(channel); diff --git a/src/lib/onboard/sandbox-agent.test.ts b/src/lib/onboard/sandbox-agent.test.ts new file mode 100644 index 00000000000..211e57538bd --- /dev/null +++ b/src/lib/onboard/sandbox-agent.test.ts @@ -0,0 +1,42 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it, vi } from "vitest"; +import { createPromptValidatedSandboxName } from "./sandbox-agent"; + +describe("sandbox name prompt", () => { + it("checkpoints a validated name before returning it to onboarding (#6743)", async () => { + const checkpointSandboxName = vi.fn(); + const promptValidatedSandboxName = createPromptValidatedSandboxName({ + promptOrDefault: vi.fn(async () => "tm"), + cliDisplayName: () => "NemoClaw", + isNonInteractive: () => false, + checkpointSandboxName, + exit: (code) => { + throw new Error(`unexpected exit ${code}`); + }, + }); + + await expect(promptValidatedSandboxName()).resolves.toBe("tm"); + expect(checkpointSandboxName).toHaveBeenCalledWith("tm", null); + }); + + it("propagates a checkpoint failure without treating the name as invalid (#6743)", async () => { + const checkpointError = new Error("session write failed"); + const promptOrDefault = vi.fn(async () => "tm"); + const promptValidatedSandboxName = createPromptValidatedSandboxName({ + promptOrDefault, + cliDisplayName: () => "NemoClaw", + isNonInteractive: () => false, + checkpointSandboxName: () => { + throw checkpointError; + }, + exit: (code) => { + throw new Error(`unexpected exit ${code}`); + }, + }); + + await expect(promptValidatedSandboxName()).rejects.toBe(checkpointError); + expect(promptOrDefault).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/lib/onboard/sandbox-agent.ts b/src/lib/onboard/sandbox-agent.ts index 50c8a44449b..98f6e50011b 100644 --- a/src/lib/onboard/sandbox-agent.ts +++ b/src/lib/onboard/sandbox-agent.ts @@ -144,6 +144,7 @@ export interface PromptSandboxNameDeps { promptOrDefault(question: string, envVar: string, defaultValue: string): Promise; cliDisplayName(): string; isNonInteractive(): boolean; + checkpointSandboxName(sandboxName: string, agent: AgentDefinition | null): void; exit(code: number): never; } @@ -159,42 +160,46 @@ export function createPromptValidatedSandboxName(deps: PromptSandboxNameDeps) { ); const sandboxName = (nameAnswer || defaultSandboxName).trim(); + let validatedSandboxName: string; try { - const validatedSandboxName = validateName(sandboxName, "sandbox name"); - if (RESERVED_SANDBOX_NAMES.has(sandboxName)) { - console.error( - ` Reserved name: '${sandboxName}' is a ${deps.cliDisplayName()} CLI command.`, - ); - console.error(" Choose a different name to avoid routing conflicts."); - if (deps.isNonInteractive()) { - deps.exit(1); - } - if (attempt < MAX_ATTEMPTS - 1) { - console.error(" Please try again.\n"); - } - continue; - } - return validatedSandboxName; + validatedSandboxName = validateName(sandboxName, "sandbox name"); } catch (error) { const errorMessage = error instanceof Error ? error.message : String(error); console.error(` ${errorMessage}`); - } + for (const line of getNameValidationGuidance("sandbox name", sandboxName, { + includeAllowedFormat: false, + })) { + console.error(` ${line}`); + } - for (const line of getNameValidationGuidance("sandbox name", sandboxName, { - includeAllowedFormat: false, - })) { - console.error(` ${line}`); - } + // Non-interactive runs cannot re-prompt — abort so the caller can fix the + // NEMOCLAW_SANDBOX_NAME env var and retry. + if (deps.isNonInteractive()) { + deps.exit(1); + } - // Non-interactive runs cannot re-prompt — abort so the caller can fix the - // NEMOCLAW_SANDBOX_NAME env var and retry. - if (deps.isNonInteractive()) { - deps.exit(1); + if (attempt < MAX_ATTEMPTS - 1) { + console.error(" Please try again.\n"); + } + continue; } - if (attempt < MAX_ATTEMPTS - 1) { - console.error(" Please try again.\n"); + if (RESERVED_SANDBOX_NAMES.has(sandboxName)) { + console.error( + ` Reserved name: '${sandboxName}' is a ${deps.cliDisplayName()} CLI command.`, + ); + console.error(" Choose a different name to avoid routing conflicts."); + if (deps.isNonInteractive()) { + deps.exit(1); + } + if (attempt < MAX_ATTEMPTS - 1) { + console.error(" Please try again.\n"); + } + continue; } + + deps.checkpointSandboxName(validatedSandboxName, agent); + return validatedSandboxName; } console.error(" Too many invalid attempts."); diff --git a/src/lib/onboard/sandbox-create-intent-resolution.ts b/src/lib/onboard/sandbox-create-intent-resolution.ts index f9151eaf390..7f284c94a42 100644 --- a/src/lib/onboard/sandbox-create-intent-resolution.ts +++ b/src/lib/onboard/sandbox-create-intent-resolution.ts @@ -29,6 +29,8 @@ export type CompleteSandboxCreateIntentInput = { extraProviders: readonly string[]; staleExtraProviders: readonly string[]; policyTier?: string | null; + /** Internal OpenClaw resume authority for exact registered provider reuse. */ + reuseRegisteredCredentials?: boolean; }; export interface SandboxCreateIntentResolverDeps { @@ -55,26 +57,36 @@ export function createSandboxCreateIntentResolver< async function prepareMessagingCapabilities( input: Pick< CompleteSandboxCreateIntentInput, - "sandboxName" | "enabledChannels" | "webSearchConfig" | "agent" + "sandboxName" | "enabledChannels" | "webSearchConfig" | "agent" | "reuseRegisteredCredentials" >, expectedIntent?: SandboxCreateIntent, + credentialRegistration = false, ) { + const preflightDeps = expectedIntent + ? { + ...deps.messagingPreflightDeps, + readMessagingPlanFromEnv: () => null, + resolveDisabledChannels: () => [...expectedIntent.disabledChannelNames], + } + : credentialRegistration + ? { + ...deps.messagingPreflightDeps, + readMessagingPlanFromEnv: () => null, + registerExtraPlaceholderProviders: () => [], + } + : deps.messagingPreflightDeps; const result = await prepareSandboxMessagingPreflight( { channels: deps.channels, enabledChannels: filterEnabledChannels(input.enabledChannels, input.agent), sandboxName: input.sandboxName, agentName: input.agent?.name ?? "openclaw", + requireExactProviderBinding: + credentialRegistration || input.reuseRegisteredCredentials === true, webSearchConfig: input.webSearchConfig, env: process.env, }, - expectedIntent - ? { - ...deps.messagingPreflightDeps, - readMessagingPlanFromEnv: () => null, - resolveDisabledChannels: () => [...expectedIntent.disabledChannelNames], - } - : deps.messagingPreflightDeps, + preflightDeps, ); if (expectedIntent) { validateSandboxCreateIntentBindings(expectedIntent, result.messagingTokenDefs); @@ -131,5 +143,11 @@ export function createSandboxCreateIntentResolver< return { resolve, rebind: prepareMessagingCapabilities, + prepareCredentialProviders: ( + input: Pick< + CompleteSandboxCreateIntentInput, + "sandboxName" | "enabledChannels" | "webSearchConfig" | "agent" + >, + ) => prepareMessagingCapabilities(input, undefined, true), }; } diff --git a/src/lib/onboard/sandbox-messaging-preflight.test.ts b/src/lib/onboard/sandbox-messaging-preflight.test.ts index d3bddc57f29..71a6fcaa141 100644 --- a/src/lib/onboard/sandbox-messaging-preflight.test.ts +++ b/src/lib/onboard/sandbox-messaging-preflight.test.ts @@ -111,6 +111,7 @@ function createDeps( listSandboxes: vi.fn(() => ({ sandboxes: [] })), }, providerExistsInGateway: vi.fn(() => false), + providerMatchesGatewayCredential: vi.fn(() => false), isNonInteractive: vi.fn(() => false), promptYesNoOrDefault: vi.fn(async () => true), cliName: vi.fn(() => "nemoclaw"), diff --git a/src/lib/onboard/sandbox-messaging-preflight.ts b/src/lib/onboard/sandbox-messaging-preflight.ts index cdf06d99c5a..f37ce284c87 100644 --- a/src/lib/onboard/sandbox-messaging-preflight.ts +++ b/src/lib/onboard/sandbox-messaging-preflight.ts @@ -17,6 +17,7 @@ import { export interface SandboxMessagingPreflightInput { sandboxName: string; agentName?: string | null; + requireExactProviderBinding?: boolean; channels: readonly NamedMessagingChannel[]; enabledChannels: readonly string[] | null; webSearchConfig: WebSearchConfig | null; @@ -29,6 +30,7 @@ export interface SandboxMessagingPreflightDeps { gatewayName(): string; registry: MessagingConflictGuardDeps["registry"]; providerExistsInGateway(name: string): boolean; + providerMatchesGatewayCredential(name: string, type: string, credentialEnv: string): boolean; isNonInteractive(): boolean; promptYesNoOrDefault( message: string, @@ -70,6 +72,7 @@ export async function prepareSandboxMessagingPreflight( const result = (deps.prepareCreateSandboxMessaging ?? defaultPrepareCreateSandboxMessaging)({ sandboxName: input.sandboxName, agentName: input.agentName, + requireExactProviderBinding: input.requireExactProviderBinding, channels: input.channels, enabledChannels: input.enabledChannels, disabledChannels, @@ -81,6 +84,7 @@ export async function prepareSandboxMessagingPreflight( registerExtraPlaceholderProviders: deps.registerExtraPlaceholderProviders, getMessagingChannelForEnvKey: deps.getMessagingChannelForEnvKey, providerExistsInGateway: deps.providerExistsInGateway, + providerMatchesGatewayCredential: deps.providerMatchesGatewayCredential, }); if (result.missingWebSearchCredentialEnv) { diff --git a/src/lib/onboard/session-bootstrap.test.ts b/src/lib/onboard/session-bootstrap.test.ts index 616738cad6c..3b64d57f257 100644 --- a/src/lib/onboard/session-bootstrap.test.ts +++ b/src/lib/onboard/session-bootstrap.test.ts @@ -310,6 +310,34 @@ describe("prepareOnboardSession", () => { expect(deps.exitProcess).toHaveBeenCalledTimes(1); }); + it("allows non-interactive resume with a checkpointed sandbox name", async () => { + const session = createSession({ + sandboxName: "checkpointed-box", + sandboxPromptProgress: { + sandboxName: true, + webSearch: false, + messaging: false, + resourceProfile: false, + }, + }); + const { deps } = createDeps(session); + + const result = await prepareOnboardSession( + { + resume: true, + fresh: false, + requestedFromDockerfile: null, + requestedSandboxName: null, + cannotPrompt: true, + nonInteractive: true, + }, + deps, + ); + + expect(result.session?.sandboxName).toBe("checkpointed-box"); + expect(deps.exitProcess).not.toHaveBeenCalled(); + }); + it("allows interactive resume to prompt when no sandbox name was recorded", async () => { const { deps } = createDeps(createSession({ sandboxName: null })); diff --git a/src/lib/onboard/session-bootstrap.ts b/src/lib/onboard/session-bootstrap.ts index 899cb0d60e1..ca776f71810 100644 --- a/src/lib/onboard/session-bootstrap.ts +++ b/src/lib/onboard/session-bootstrap.ts @@ -51,6 +51,28 @@ export interface OnboardSessionBootstrapResult { fromDockerfile: string | null; } +export function checkpointSandboxName( + sandboxName: string, + agent: { name?: string } | null, + updateSession: OnboardSessionBootstrapDeps["updateSession"], +): void { + if (agent?.name && agent.name !== "openclaw") return; + updateSession((current) => { + current.sandboxName = sandboxName; + current.sandboxPromptProgress.sandboxName = true; + return current; + }); +} + +export function getCheckpointedSandboxName( + resume: boolean, + agent: { name?: string } | null, + session: Session | null, +): string | null { + if (!resume || (agent?.name && agent.name !== "openclaw")) return null; + return session?.sandboxPromptProgress?.sandboxName === true ? session.sandboxName : null; +} + function mode(nonInteractive: boolean): "non-interactive" | "interactive" { return nonInteractive ? "non-interactive" : "interactive"; } @@ -125,8 +147,12 @@ function assertRecoverableResumeSandboxName( deps: OnboardSessionBootstrapDeps, ): void { const sandboxStepCompleted = session?.steps?.sandbox?.status === "complete"; + const sandboxNameCheckpointed = + (!session?.agent || session.agent === "openclaw") && + session?.sandboxPromptProgress?.sandboxName === true; const recoveredSandboxName = - input.requestedSandboxName || (sandboxStepCompleted ? session?.sandboxName || null : null); + input.requestedSandboxName || + (sandboxStepCompleted || sandboxNameCheckpointed ? session?.sandboxName || null : null); if (input.cannotPrompt && !recoveredSandboxName) { deps.error( " Cannot resume non-interactive onboard: the previous run was interrupted before sandbox creation completed,", diff --git a/src/lib/onboard/types.ts b/src/lib/onboard/types.ts index 8247821fd55..b95e0c28494 100644 --- a/src/lib/onboard/types.ts +++ b/src/lib/onboard/types.ts @@ -68,6 +68,8 @@ export interface SandboxCreateIntent { readonly policyTier?: string | null; /** Gateway-level extra providers reconciled immediately before sandbox creation. */ readonly extraProviders?: readonly string[]; + /** Internal OpenClaw resume authority for exact registered provider reuse. */ + readonly reuseRegisteredCredentials?: true; } export type OnboardOptions = { diff --git a/src/lib/state/onboard-session-sandbox-prompts.test.ts b/src/lib/state/onboard-session-sandbox-prompts.test.ts new file mode 100644 index 00000000000..51acdd0f191 --- /dev/null +++ b/src/lib/state/onboard-session-sandbox-prompts.test.ts @@ -0,0 +1,200 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +type OnboardSessionModule = typeof import("./onboard-session"); +type LoadedSession = NonNullable>; +type MessagingPlan = NonNullable; +let session: OnboardSessionModule; +let tmpDir: string; + +function requireLoadedSession(loaded: LoadedSession | null): LoadedSession { + expect(loaded).not.toBeNull(); + return loaded as LoadedSession; +} + +function makeTelegramPlan(sandboxName: string): MessagingPlan { + return { + schemaVersion: 1, + sandboxName, + agent: "openclaw", + workflow: "onboard", + channels: [ + { + channelId: "telegram", + displayName: "telegram", + authMode: "token-paste", + active: true, + selected: true, + configured: true, + disabled: false, + inputs: [], + hooks: [], + }, + ], + disabledChannels: [], + credentialBindings: [], + networkPolicy: { presets: [], entries: [] }, + agentRender: [], + buildSteps: [], + stateUpdates: [], + healthChecks: [], + }; +} + +beforeEach(async () => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-prompt-session-")); + vi.stubEnv("HOME", tmpDir); + vi.resetModules(); + session = await import("./onboard-session"); + session.clearSession(); +}); + +afterEach(() => { + session.clearSession(); + fs.rmSync(tmpDir, { recursive: true, force: true }); + vi.unstubAllEnvs(); +}); + +describe("onboard session sandbox prompt checkpoints", () => { + it.each([ + ["OpenShell defaults", null], + ["a selected profile", { cpu: "75%", memory: "75%" }], + ] as const)("round-trips completed choices with %s without transient secrets or intent (#6743)", (_label, resourceProfile) => { + const braveCredential = "brave-secret-value"; + const telegramCredential = "telegram-secret-value"; + const created = session.createSession({ + sandboxName: "tm", + webSearchConfig: { fetchEnabled: true, provider: "brave" }, + messagingPlan: makeTelegramPlan("tm"), + sandboxPromptProgress: { + sandboxName: true, + webSearch: true, + messaging: true, + resourceProfile: true, + }, + resourceProfile, + stagedCredentialProviders: ["tm-brave-search", "tm-telegram-bridge"], + }); + Object.assign(created as unknown as Record, { + BRAVE_API_KEY: braveCredential, + TELEGRAM_BOT_TOKEN: telegramCredential, + sandboxCreateIntent: { resolved: { resourceCreateArgs: ["--cpu", "6"] } }, + }); + + session.saveSession(created); + + const raw = JSON.parse(fs.readFileSync(session.SESSION_FILE, "utf-8")); + expect(raw).toMatchObject({ + sandboxName: "tm", + webSearchConfig: { fetchEnabled: true, provider: "brave" }, + sandboxPromptProgress: { + sandboxName: true, + webSearch: true, + messaging: true, + resourceProfile: true, + }, + resourceProfile, + stagedCredentialProviders: ["tm-brave-search", "tm-telegram-bridge"], + }); + const serialized = JSON.stringify(raw); + expect(serialized).not.toContain(braveCredential); + expect(serialized).not.toContain(telegramCredential); + expect(serialized).not.toContain('"sandboxCreateIntent"'); + expect(serialized).not.toContain('"resolved"'); + expect(serialized).not.toContain('"resourceCreateArgs"'); + + const loaded = requireLoadedSession(session.loadSession()); + expect(loaded.sandboxPromptProgress).toEqual({ + sandboxName: true, + webSearch: true, + messaging: true, + resourceProfile: true, + }); + expect(loaded.resourceProfile).toEqual(resourceProfile); + expect(loaded.stagedCredentialProviders).toEqual(["tm-brave-search", "tm-telegram-bridge"]); + }); + + it("defaults unanswered progress and resources for fresh sessions (#6743)", () => { + const fresh = session.createSession(); + + expect(fresh.sandboxPromptProgress).toEqual({ + sandboxName: false, + webSearch: false, + messaging: false, + resourceProfile: false, + }); + expect(fresh.resourceProfile).toBeNull(); + expect(fresh.stagedCredentialProviders).toEqual([]); + }); + + it("keeps explicit null choices complete but clears malformed or missing values (#6743)", () => { + const explicitNone = session.createSession({ + sandboxName: "tm", + webSearchConfig: null, + messagingPlan: null, + resourceProfile: null, + sandboxPromptProgress: { + sandboxName: true, + webSearch: true, + messaging: true, + resourceProfile: true, + }, + }); + expect(explicitNone.sandboxPromptProgress).toEqual({ + sandboxName: true, + webSearch: true, + messaging: true, + resourceProfile: true, + }); + + const malformed = explicitNone as unknown as Record; + malformed.sandboxName = "Invalid Name"; + malformed.webSearchConfig = { fetchEnabled: false }; + delete malformed.messagingPlan; + malformed.resourceProfile = { cpu: 42, memory: "75%" }; + + const normalized = requireLoadedSession(session.normalizeSession(malformed as never)); + expect(normalized.sandboxPromptProgress).toEqual({ + sandboxName: false, + webSearch: false, + messaging: false, + resourceProfile: false, + }); + }); + + it("preserves one-sided resource overrides as completed (#6743)", () => { + const normalized = session.createSession({ + resourceProfile: { cpu: "", memory: "75%" }, + sandboxPromptProgress: { + sandboxName: false, + webSearch: false, + messaging: false, + resourceProfile: true, + }, + }); + + expect(normalized.resourceProfile).toEqual({ cpu: "", memory: "75%" }); + expect(normalized.sandboxPromptProgress.resourceProfile).toBe(true); + }); + + it("rejects completed messaging state for a different sandbox (#6743)", () => { + const normalized = session.createSession({ + sandboxName: "tm", + messagingPlan: makeTelegramPlan("other-sandbox"), + sandboxPromptProgress: { + sandboxName: true, + webSearch: false, + messaging: true, + resourceProfile: false, + }, + }); + + expect(normalized.messagingPlan?.sandboxName).toBe("other-sandbox"); + expect(normalized.sandboxPromptProgress.messaging).toBe(false); + }); +}); diff --git a/src/lib/state/onboard-session.ts b/src/lib/state/onboard-session.ts index 91005a70813..aded1da0065 100644 --- a/src/lib/state/onboard-session.ts +++ b/src/lib/state/onboard-session.ts @@ -17,6 +17,7 @@ import { normalizeWebSearchConfig, type WebSearchConfig } from "../inference/web import type { SandboxMessagingPlan } from "../messaging/manifest"; import { compactSandboxMessagingPlanForPersistence } from "../messaging/persistence"; import { parseSandboxMessagingPlan } from "../messaging/plan-validation"; +import { NAME_MAX_LENGTH, NAME_VALID_PATTERN } from "../name-validation"; import { createOnboardMachineEvent, emitOnboardMachineEvent, @@ -123,6 +124,18 @@ export interface OnboardMachineSnapshot { recoveryReceipt?: SessionRecoveryReceipt; } +export interface SandboxPromptProgress { + sandboxName: boolean; + webSearch: boolean; + messaging: boolean; + resourceProfile: boolean; +} + +export interface SessionResourceProfile { + cpu: string; + memory: string; +} + export interface Session { version: number; sessionId: string; @@ -147,6 +160,10 @@ export interface Session { routerPid: number | null; routerCredentialHash: string | null; webSearchConfig: WebSearchConfig | null; + /** Completed secret-free choices that can be reused by an interrupted sandbox setup. */ + sandboxPromptProgress: SandboxPromptProgress; + /** The selected sandbox resource values; null is an explicit OpenShell-default choice. */ + resourceProfile: SessionResourceProfile | null; /** Selected preference, retained even when a model-specific safeguard downgrades it. */ toolDisclosure: ToolDisclosure; /** Enables credential-free OTLP trace export to NemoClaw's fixed local collector boundary. */ @@ -156,6 +173,8 @@ export interface Session { hermesToolGateways: string[] | null; policyPresets: string[] | null; messagingPlan: SandboxMessagingPlan | null; + /** Non-secret names of credential providers registered before sandbox setup completed. */ + stagedCredentialProviders: string[]; // SHA-256 hex digest of every legacy credential value successfully // written to the OpenShell gateway during this onboard session, keyed by // env-name. Persisted across process restarts so a `--resume` run that @@ -345,6 +364,63 @@ function parseWebSearchConfig(value: SessionJsonValue | undefined): WebSearchCon return normalizeWebSearchConfig(value as Partial); } +function hasOwn(value: object, key: string): boolean { + return Object.prototype.hasOwnProperty.call(value, key); +} + +function isValidCheckpointedSandboxName(value: unknown): boolean { + return ( + typeof value === "string" && value.length <= NAME_MAX_LENGTH && NAME_VALID_PATTERN.test(value) + ); +} + +function isValidNullableWebSearchChoice(value: unknown): boolean { + return value === null || parseWebSearchConfig(value as SessionJsonValue | undefined) !== null; +} + +function isValidNullableMessagingChoice(value: unknown, sandboxName: unknown): boolean { + return ( + value === null || + (typeof sandboxName === "string" && parseSandboxMessagingPlan(value, { sandboxName }) !== null) + ); +} + +function isValidNullableResourceChoice(value: unknown): boolean { + return value === null || parseSessionResourceProfile(value) !== null; +} + +function parseSandboxPromptProgress( + value: unknown, + choices: Record, +): SandboxPromptProgress { + const progress = isObject(value) ? value : {}; + return { + sandboxName: + progress.sandboxName === true && + hasOwn(choices, "sandboxName") && + isValidCheckpointedSandboxName(choices.sandboxName), + webSearch: + progress.webSearch === true && + hasOwn(choices, "webSearchConfig") && + isValidNullableWebSearchChoice(choices.webSearchConfig), + messaging: + progress.messaging === true && + hasOwn(choices, "messagingPlan") && + isValidNullableMessagingChoice(choices.messagingPlan, choices.sandboxName), + resourceProfile: + progress.resourceProfile === true && + hasOwn(choices, "resourceProfile") && + isValidNullableResourceChoice(choices.resourceProfile), + }; +} + +function parseSessionResourceProfile(value: unknown): SessionResourceProfile | null { + if (!isObject(value)) return null; + const cpu = readString(value.cpu); + const memory = readString(value.memory); + return cpu !== null && memory !== null ? { cpu, memory } : null; +} + function parseTelegramConfig(value: unknown): TelegramConfig | null { if (!isObject(value)) return null; if (value.requireMention === true) return { requireMention: true }; @@ -562,12 +638,18 @@ export function createSession(overrides: Partial = {}): Session { routerPid: readPositiveInteger(overrides.routerPid), routerCredentialHash: overrides.routerCredentialHash ?? null, webSearchConfig: normalizeWebSearchConfig(overrides.webSearchConfig), + sandboxPromptProgress: parseSandboxPromptProgress( + overrides.sandboxPromptProgress, + overrides as Record, + ), + resourceProfile: parseSessionResourceProfile(overrides.resourceProfile), toolDisclosure: normalizeSessionToolDisclosure(overrides.toolDisclosure), observabilityEnabled: overrides.observabilityEnabled === true, observabilityRequestedExplicitly: overrides.observabilityRequestedExplicitly === true, hermesToolGateways: readStringArray(overrides.hermesToolGateways), policyPresets: readStringArray(overrides.policyPresets), messagingPlan: parseSandboxMessagingPlan(overrides.messagingPlan), + stagedCredentialProviders: readStringArray(overrides.stagedCredentialProviders) ?? [], migratedLegacyValueHashes: overrides.migratedLegacyValueHashes ? readStringRecord(overrides.migratedLegacyValueHashes) : null, @@ -608,12 +690,15 @@ export function normalizeSession(data: Session | SessionJsonValue | undefined): routerPid: readPositiveInteger(data.routerPid), routerCredentialHash: readString(data.routerCredentialHash), webSearchConfig: parseWebSearchConfig(data.webSearchConfig), + sandboxPromptProgress: parseSandboxPromptProgress(data.sandboxPromptProgress, data), + resourceProfile: parseSessionResourceProfile(data.resourceProfile), toolDisclosure: normalizeSessionToolDisclosure(data.toolDisclosure), observabilityEnabled: data.observabilityEnabled === true, observabilityRequestedExplicitly: data.observabilityRequestedExplicitly === true, hermesToolGateways: readStringArray(data.hermesToolGateways), policyPresets: readStringArray(data.policyPresets), messagingPlan: parseSandboxMessagingPlan(data.messagingPlan), + stagedCredentialProviders: readStringArray(data.stagedCredentialProviders) ?? [], migratedLegacyValueHashes: readStringRecord(data.migratedLegacyValueHashes), gpuPassthrough: data.gpuPassthrough === true, telegramConfig: parseTelegramConfig(data.telegramConfig), diff --git a/test/onboard-messaging.test.ts b/test/onboard-messaging.test.ts index dc86b68f612..cad264577f5 100644 --- a/test/onboard-messaging.test.ts +++ b/test/onboard-messaging.test.ts @@ -532,9 +532,9 @@ registry.registerSandbox({ runner.run = (command, opts = {}) => { const normalized = _n(command); commands.push({ command: normalized, env: opts.env || null }); - if (normalized.includes("provider get -g nemoclaw my-assistant-discord-bridge")) return { status: 0 }; - if (normalized.includes("provider get -g nemoclaw my-assistant-slack-bridge")) return { status: 0 }; - if (normalized.includes("provider get -g nemoclaw my-assistant-slack-app")) return { status: 0 }; + if (normalized.includes("provider get -g nemoclaw my-assistant-discord-bridge")) return { status: 0, stdout: "Name: my-assistant-discord-bridge\nType: generic\nCredential keys: DISCORD_BOT_TOKEN\nConfig keys: \n" }; + if (normalized.includes("provider get -g nemoclaw my-assistant-slack-bridge")) return { status: 0, stdout: "Name: my-assistant-slack-bridge\nType: generic\nCredential keys: SLACK_BOT_TOKEN\nConfig keys: \n" }; + if (normalized.includes("provider get -g nemoclaw my-assistant-slack-app")) return { status: 0, stdout: "Name: my-assistant-slack-app\nType: generic\nCredential keys: SLACK_APP_TOKEN\nConfig keys: \n" }; if (normalized.includes("provider get")) return { status: 1 }; return { status: 0 }; }; @@ -694,7 +694,7 @@ registry.registerSandbox({ runner.run = (command, opts = {}) => { const normalized = _n(command); commands.push({ command: normalized, env: opts.env || null }); - if (normalized.includes("provider get -g nemoclaw my-assistant-telegram-bridge")) return { status: 0 }; + if (normalized.includes("provider get -g nemoclaw my-assistant-telegram-bridge")) return { status: 0, stdout: "Name: my-assistant-telegram-bridge\nType: generic\nCredential keys: TELEGRAM_BOT_TOKEN\nConfig keys: \n" }; if (normalized.includes("provider get")) return { status: 1 }; return { status: 0 }; }; diff --git a/test/onboard.test.ts b/test/onboard.test.ts index 3c6adb498fc..1e2e24634c1 100644 --- a/test/onboard.test.ts +++ b/test/onboard.test.ts @@ -593,6 +593,16 @@ startGateway(null).catch(() => {}); nimContainer: "nim-hermes", routerPid: 123, routerCredentialHash: "hash", + sandboxName: "hermes-box", + webSearchConfig: { fetchEnabled: true, provider: "tavily" }, + messagingPlan: null, + resourceProfile: { cpu: "75%", memory: "75%" }, + sandboxPromptProgress: { + sandboxName: true, + webSearch: true, + messaging: true, + resourceProfile: true, + }, policyPresets: ["nous-web", "brave"], lastCompletedStep: "policies", lastStepStarted: "policies", @@ -621,6 +631,16 @@ startGateway(null).catch(() => {}); expect(cleared.nimContainer).toBeNull(); expect(cleared.routerPid).toBeNull(); expect(cleared.routerCredentialHash).toBeNull(); + expect(cleared.sandboxName).toBe("hermes-box"); + expect(cleared.webSearchConfig).toBeNull(); + expect(cleared.messagingPlan).toBeNull(); + expect(cleared.resourceProfile).toEqual({ cpu: "75%", memory: "75%" }); + expect(cleared.sandboxPromptProgress).toEqual({ + sandboxName: true, + webSearch: false, + messaging: false, + resourceProfile: true, + }); expect(cleared.policyPresets).toBeNull(); expect(cleared.steps.gateway.status).toBe("complete"); expect(cleared.steps.provider_selection.status).toBe("pending");