From 429ed0fa40b5b7d6b8e47249afbc4ba9709fa747 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 15 Jul 2026 17:42:46 +0700 Subject: [PATCH 1/5] fix(onboard): skip completed prompts on resume --- docs/reference/commands.mdx | 6 +- docs/reference/troubleshooting.mdx | 4 +- src/lib/onboard.ts | 21 +- src/lib/onboard/agent-resume-state.ts | 6 + src/lib/onboard/lifecycle-contracts.md | 22 +- .../machine/handlers/provider-inference.ts | 7 + .../sandbox-create-intent-boundary.test.ts | 314 +++++++++++++++++- .../handlers/sandbox-messaging.test.ts | 182 +++++++++- .../machine/handlers/sandbox-messaging.ts | 75 ++++- .../machine/handlers/sandbox-test-fixtures.ts | 2 + .../onboard/machine/handlers/sandbox.test.ts | 9 + src/lib/onboard/machine/handlers/sandbox.ts | 165 +++++++-- .../onboard/messaging-channel-setup.test.ts | 104 ++++++ src/lib/onboard/messaging-channel-setup.ts | 83 ++++- src/lib/onboard/sandbox-agent.test.ts | 23 ++ src/lib/onboard/sandbox-agent.ts | 2 + src/lib/onboard/session-bootstrap.test.ts | 28 ++ src/lib/onboard/session-bootstrap.ts | 4 +- .../onboard-session-sandbox-prompts.test.ts | 183 ++++++++++ src/lib/state/onboard-session.ts | 78 +++++ test/onboard-inference-reconciliation.test.ts | 45 ++- test/onboard.test.ts | 20 ++ 22 files changed, 1319 insertions(+), 64 deletions(-) create mode 100644 src/lib/onboard/sandbox-agent.test.ts create mode 100644 src/lib/state/onboard-session-sandbox-prompts.test.ts diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index f77b64a90ea..61da3ab4615 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -227,7 +227,11 @@ For example, `nemohermes` resolves to `hermes`, while `dcode`, `deepagents`, `de #### `--resume` and `--fresh` 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. +Use `--resume` to continue a resumable onboarding session with the provider, model, sandbox name, agent, observability choice, web search selection, messaging selection and non-secret settings, resource profile, and custom Dockerfile path recorded by the original run. +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, so interactive resume can request a missing credential again while preserving the completed non-secret choices. +If a completed messaging choice lacks its credential during non-interactive resume, NemoClaw preserves the choice and exits; export the missing messaging credential environment variables, then run `$$nemoclaw onboard --resume` again. 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..4d5c297c5bb 100644 --- a/docs/reference/troubleshooting.mdx +++ b/docs/reference/troubleshooting.mdx @@ -774,7 +774,9 @@ 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 without repeating completed non-secret choices. + Interactive resume can request a web search or messaging credential again when it was available only to the interrupted process because raw credentials are not stored in the onboarding session. + Non-interactive resume cannot prompt for a missing messaging credential: it preserves the completed channel choice, exits, and asks you to export the missing messaging credential environment variables before running `$$nemoclaw onboard --resume` again. 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 diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index df6934a4fdb..7ca2ede3891 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -448,6 +448,13 @@ const promptValidatedSandboxName = sandboxAgent.createPromptValidatedSandboxName promptOrDefault, cliDisplayName, isNonInteractive, + checkpointSandboxName: (sandboxName) => { + onboardSession.updateSession((current: Session) => { + current.sandboxName = sandboxName; + current.sandboxPromptProgress.sandboxName = true; + return current; + }); + }, exit: process.exit, }); const modelRouter: typeof import("./onboard/model-router") = require("./onboard/model-router"); @@ -3782,12 +3789,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 +4226,11 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { const recordedSandboxName = session?.steps?.sandbox?.status === "complete" ? session?.sandboxName || null : null; - const gatewaySandboxName = resume ? (recordedSandboxName ?? requestedSandboxName) : null; + const checkpointedSandboxName = + resume && session?.sandboxPromptProgress?.sandboxName === true ? session.sandboxName : null; + 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 +4256,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, @@ -4352,7 +4365,8 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { // 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; + 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,6 +4495,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { configureWebSearch, startRecordedStep, getRecordedMessagingChannelsForResume, + showMessagingStage: () => step(5, 8, "Messaging channels"), setupMessagingChannels, readMessagingPlanFromEnv, writePlanToEnv, 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/lifecycle-contracts.md b/src/lib/onboard/lifecycle-contracts.md index 4d2542ae680..dc16c38791a 100644 --- a/src/lib/onboard/lifecycle-contracts.md +++ b/src/lib/onboard/lifecycle-contracts.md @@ -48,7 +48,7 @@ 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. 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. It still cannot resume inside gateway startup, credential upserts, sandbox creation, policy application, or another handler-owned effect group. ## Effect-order flows @@ -57,7 +57,7 @@ The FSM checkpoint is step-granular. It cannot resume inside gateway startup, cr ```text fresh onboard resolve entry options -> save session/machine* -> host preflight - -> gateway/provider effects -> resolve complete sandbox-create intent + -> gateway/provider effects -> checkpoint completed sandbox prompts* -> resolve complete sandbox-create intent -> materialize create plan -> create -> ready -> live validation -> register* -> finalize session* @@ -94,14 +94,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. 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, with narrow checkpoints after each completed secret-free sandbox prompt group; 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`, `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. Completed sandbox name, web search, messaging, and resource choices have explicit progress markers, including explicit `null` choices, while the complete create intent stays process-local and is not persisted or emitted. Raw credential values are rebound or requested again when missing; non-interactive messaging recovery preserves the checkpoint and fails with environment-variable guidance instead of prompting. 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 +113,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` | Step-mutation helpers and `OnboardRuntime` own whole-step progress; the sandbox handler owns prompt-group completion markers. 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 +149,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 +157,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/handlers/provider-inference.ts b/src/lib/onboard/machine/handlers/provider-inference.ts index 99f58434223..58b7ee55ebc 100644 --- a/src/lib/onboard/machine/handlers/provider-inference.ts +++ b/src/lib/onboard/machine/handlers/provider-inference.ts @@ -439,6 +439,13 @@ export async function handleProviderInferenceState({ deps.log(" [resume] Refreshing compatible-endpoint inference route for messaging."); } deps.skippedStepMessage("provider_selection", `${provider} / ${model}`); + if ( + 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..72c82199463 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,305 @@ 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("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"], ["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 () => []); + const readMessagingPlanFromEnv = vi + .fn<() => typeof messagingPlan | null>() + .mockReturnValueOnce(null) + .mockReturnValueOnce(messagingPlan) + .mockReturnValue(null); + const { deps, calls } = createDeps({ + updateSession, + recordStepComplete, + configureWebSearch, + setupMessagingChannels, + 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, + resourceProfile: null, + sandboxPromptProgress: { + sandboxName: true, + webSearch: true, + messaging: true, + resourceProfile: false, + }, + }); + expect(calls.resolveCreateIntent).not.toHaveBeenCalled(); + expect(calls.createSandbox).not.toHaveBeenCalled(); + + calls.selectResourceProfile.mockResolvedValueOnce({ cpu: "75%", memory: "75%" }); + await handleSandboxState({ + ...baseOptions(deps, durableSession), + resume: true, + sandboxName: durableSession.sandboxName, + webSearchConfig: durableSession.webSearchConfig, + env: credentialEnv, + }); + + expect(configureWebSearch).toHaveBeenCalledTimes(1); + expect(setupMessagingChannels).toHaveBeenCalledTimes(1); + 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..f2f9584c9c6 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,81 @@ 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) { + const session = createSession(); + session.sandboxName = plan.sandboxName; + session.messagingPlan = plan; + 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), + }; +} + +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 +217,104 @@ 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).not.toHaveBeenCalled(); + 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).not.toHaveBeenCalled(); + expect(persistedPlan.credentialBindings[0]?.credentialHash).toBe(hashCredential(previousToken)); + }); + + it("runs existing setup validation when the checkpointed credential is missing", async () => { + const persistedPlan = telegramPlan(hashCredential("123456:previous-token") ?? ""); + const deps = reconcileDeps([persistedPlan]); + 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 }, + ); + }); +}); diff --git a/src/lib/onboard/machine/handlers/sandbox-messaging.ts b/src/lib/onboard/machine/handlers/sandbox-messaging.ts index 0979ef46b89..ba82e1a44e7 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,6 +29,7 @@ export interface SandboxMessagingDeps { agent: Agent, existingChannels: string[] | null, sandboxName: string, + options?: { readonly selectionCompleted?: boolean }, ): Promise; readMessagingPlanFromEnv(): SandboxMessagingPlan | null; writePlanToEnv(plan: SandboxMessagingPlan): void; @@ -157,12 +160,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 +262,64 @@ 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) => + activeChannels.has(binding.channelId) && + hashCredential(getCredential(binding.providerEnvKey)) !== binding.credentialHash, + ); + if (credentialNeedsValidation) { + 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 +329,9 @@ export async function reconcileSandboxMessaging( options.sandboxName, ); const envPlan = options.deps.readMessagingPlanFromEnv(); + if (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-test-fixtures.ts b/src/lib/onboard/machine/handlers/sandbox-test-fixtures.ts index 2497879fc05..ce5efcdaa42 100644 --- a/src/lib/onboard/machine/handlers/sandbox-test-fixtures.ts +++ b/src/lib/onboard/machine/handlers/sandbox-test-fixtures.ts @@ -111,6 +111,7 @@ 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[]), promptName: vi.fn(async () => "my-assistant"), selectResourceProfile: vi.fn(async () => null as ResourceProfile | null), @@ -217,6 +218,7 @@ export function createDeps( configureWebSearch: calls.configureWebSearch, startRecordedStep: calls.startStep, getRecordedMessagingChannelsForResume: calls.getRecordedChannels, + showMessagingStage: calls.showMessagingStage, setupMessagingChannels: calls.setupMessaging, readMessagingPlanFromEnv: () => null, writePlanToEnv: () => undefined, diff --git a/src/lib/onboard/machine/handlers/sandbox.test.ts b/src/lib/onboard/machine/handlers/sandbox.test.ts index 3b45d20b427..5f44c1a1311 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(); }); diff --git a/src/lib/onboard/machine/handlers/sandbox.ts b/src/lib/onboard/machine/handlers/sandbox.ts index c7a3d6253d7..57790f71b71 100644 --- a/src/lib/onboard/machine/handlers/sandbox.ts +++ b/src/lib/onboard/machine/handlers/sandbox.ts @@ -16,7 +16,12 @@ import { 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,10 +161,12 @@ 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; @@ -295,6 +302,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; @@ -626,14 +637,7 @@ 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, ); @@ -645,6 +649,105 @@ 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.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 { + 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 { + 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 { + const session = this.deps.updateSession((current) => { + current.messagingPlan = messaging.plan; + current.sandboxPromptProgress.messaging = true; + return current; + }); + return { + ...state, + session, + selectedMessagingChannels: messaging.selectedChannels, + }; + } + + private async resolveResourceProfile(state: SandboxStepState): Promise<{ + state: SandboxStepState; + resourceProfile: ResourceProfile | null; + }> { + if ( + 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(); + 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, @@ -689,18 +792,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 +914,38 @@ 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 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, ); + nextState = this.checkpointWebSearch( + { + ...nextState, + webSearchConfig, + webSearchConfigChanged, + }, + webSearchConfig, + ); const requestedSandboxName = - state.sandboxName ?? (await this.deps.promptValidatedSandboxName(this.options.agent)); + nextState.sandboxName ?? (await this.deps.promptValidatedSandboxName(this.options.agent)); + if (!nextState.sandboxName) { + nextState = this.checkpointSandboxName(nextState, requestedSandboxName); + } 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, - }, - requestedSandboxName, - messaging.plan, - decision, - ); + nextState = this.checkpointMessaging(nextState, messaging); + 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/sandbox-agent.test.ts b/src/lib/onboard/sandbox-agent.test.ts new file mode 100644 index 00000000000..85a3f6e35b8 --- /dev/null +++ b/src/lib/onboard/sandbox-agent.test.ts @@ -0,0 +1,23 @@ +// 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"); + }); +}); diff --git a/src/lib/onboard/sandbox-agent.ts b/src/lib/onboard/sandbox-agent.ts index 50c8a44449b..c9e01023f63 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): void; exit(code: number): never; } @@ -174,6 +175,7 @@ export function createPromptValidatedSandboxName(deps: PromptSandboxNameDeps) { } continue; } + deps.checkpointSandboxName(validatedSandboxName); return validatedSandboxName; } catch (error) { const errorMessage = error instanceof Error ? error.message : String(error); 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..6c8ec4387cf 100644 --- a/src/lib/onboard/session-bootstrap.ts +++ b/src/lib/onboard/session-bootstrap.ts @@ -125,8 +125,10 @@ function assertRecoverableResumeSandboxName( deps: OnboardSessionBootstrapDeps, ): void { const sandboxStepCompleted = session?.steps?.sandbox?.status === "complete"; + const sandboxNameCheckpointed = 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/state/onboard-session-sandbox-prompts.test.ts b/src/lib/state/onboard-session-sandbox-prompts.test.ts new file mode 100644 index 00000000000..cad853cb912 --- /dev/null +++ b/src/lib/state/onboard-session-sandbox-prompts.test.ts @@ -0,0 +1,183 @@ +// 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"; + +const originalHome = process.env.HOME; +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(); + if (!loaded) throw new Error("Expected onboard session to be present"); + return loaded; +} + +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-")); + process.env.HOME = tmpDir; + vi.resetModules(); + session = await import("./onboard-session"); + session.clearSession(); +}); + +afterEach(() => { + session.clearSession(); + fs.rmSync(tmpDir, { recursive: true, force: true }); + if (originalHome === undefined) delete process.env.HOME; + else process.env.HOME = originalHome; +}); + +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, + }); + 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, + }); + 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); + }); + + 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(); + }); + + 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); + }); +}); diff --git a/src/lib/state/onboard-session.ts b/src/lib/state/onboard-session.ts index 91005a70813..460d46ba568 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. */ @@ -345,6 +362,60 @@ 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): boolean { + return value === null || parseSandboxMessagingPlan(value) !== 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), + 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,6 +633,11 @@ 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, @@ -608,6 +684,8 @@ 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, diff --git a/test/onboard-inference-reconciliation.test.ts b/test/onboard-inference-reconciliation.test.ts index ce26d31d189..324e28c0849 100644 --- a/test/onboard-inference-reconciliation.test.ts +++ b/test/onboard-inference-reconciliation.test.ts @@ -153,7 +153,7 @@ describe("onboard helpers", () => { expect(updateSandbox).toHaveBeenCalledWith("test-box", { model: "anthropic.claude-3-5-sonnet-20240620-v1:0", provider: "compatible-anthropic-endpoint", endpointUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", credentialEnv: "COMPATIBLE_ANTHROPIC_API_KEY", preferredInferenceApi: null, gatewayName: "nemoclaw" }); }); }); - it("resolves a sandbox name before reconciling Hermes Provider on resume", { + it("resolves a missing name but reuses a completed name before resume inference (#6743)", { timeout: 60_000, }, () => { const repoRoot = path.join(import.meta.dirname, ".."); @@ -204,6 +204,7 @@ const prompts = []; const registryUpdates = []; const done = new Error("INFERENCE_STEP_DONE"); let inferenceSessionSnapshot = null; +const useCheckpointedName = process.argv[2] === "checkpointed"; delete process.env.NEMOCLAW_NON_INTERACTIVE; delete process.env.NEMOCLAW_SANDBOX_NAME; @@ -287,7 +288,7 @@ onboardSession.saveSession( onboardSession.createSession({ mode: "interactive", agent: "hermes", - sandboxName: null, + sandboxName: useCheckpointedName ? "hermes-resume" : null, provider: "hermes-provider", model: "moonshotai/kimi-k2.6", endpointUrl: "https://8.8.8.8/v1", @@ -295,6 +296,12 @@ onboardSession.saveSession( hermesAuthMethod: "api_key", hermesToolGateways: [], policyPresets: ["nous-web"], + sandboxPromptProgress: { + sandboxName: useCheckpointedName, + webSearch: false, + messaging: false, + resourceProfile: false, + }, metadata: { gatewayName: "nemoclaw", fromDockerfile: null }, steps: { preflight: complete(), @@ -347,11 +354,14 @@ const { onboard } = require(${onboardPath}); delete env.NEMOCLAW_SANDBOX_NAME; delete env.NOUS_API_KEY; - const result = spawnSync(process.execPath, [scriptPath], { - cwd: repoRoot, - encoding: "utf-8", - env, - }); + const runScenario = (scenario: "missing" | "checkpointed") => + spawnSync(process.execPath, [scriptPath, scenario], { + cwd: repoRoot, + encoding: "utf-8", + env, + }); + + const result = runScenario("missing"); assert.equal(result.status, 0, result.stderr); assert.doesNotMatch( @@ -378,8 +388,8 @@ const { onboard } = require(${onboardPath}); assert.ok(!payload.commands.some((entry) => /provider (create|update)/.test(entry.command))); assert.equal( payload.inferenceSessionSandboxName, - null, - "resume inference must not persist sandboxName before sandbox creation", + "hermes-resume", + "resume inference should checkpoint the validated sandbox name before reconciliation", ); assert.ok( payload.registryUpdates.some( @@ -390,6 +400,23 @@ const { onboard } = require(${onboardPath}); ), "Hermes setup should reconcile inference against the resolved sandbox name", ); + + const checkpointedResult = runScenario("checkpointed"); + assert.equal(checkpointedResult.status, 0, checkpointedResult.stderr); + assert.match( + checkpointedResult.stdout, + /\[resume\] Reusing sandbox name: hermes-resume\./, + "resume should report the completed sandbox-name choice under inference configuration", + ); + const checkpointedPayload = parseStdoutJson<{ + prompts: string[]; + inferenceSessionSandboxName: string | null; + }>(checkpointedResult.stdout); + assert.ok( + !checkpointedPayload.prompts.some((question) => question.includes("Sandbox name")), + "resume must not repeat a completed sandbox-name prompt", + ); + assert.equal(checkpointedPayload.inferenceSessionSandboxName, "hermes-resume"); }); it("reconciles a registered Hermes Provider when a fresh shell Nous key is selected", async () => { 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"); From 1d4bb7574f7a95bc2d8f9941d2abec43638e94e2 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 15 Jul 2026 18:28:30 +0700 Subject: [PATCH 2/5] fix(onboard): reuse staged credentials on resume Signed-off-by: San Dang --- docs/reference/commands.mdx | 5 +- docs/reference/troubleshooting.mdx | 17 +- docs/security/credential-storage.mdx | 6 + src/lib/onboard.ts | 59 +++++- .../onboard/gateway-provider-metadata.test.ts | 45 +++++ src/lib/onboard/gateway-provider-metadata.ts | 21 +++ src/lib/onboard/lifecycle-contracts.md | 12 +- .../onboard/machine/core-flow-phases.test.ts | 2 + .../sandbox-create-intent-boundary.test.ts | 30 +++- .../handlers/sandbox-messaging.test.ts | 33 +++- .../machine/handlers/sandbox-messaging.ts | 17 +- .../sandbox-route-mutation-lock.test.ts | 8 +- .../machine/handlers/sandbox-test-fixtures.ts | 3 + src/lib/onboard/machine/handlers/sandbox.ts | 45 +++++ src/lib/onboard/messaging-prep.test.ts | 41 ++++- src/lib/onboard/messaging-prep.ts | 36 ++-- src/lib/onboard/providers.test.ts | 168 +++++++++++++++++- src/lib/onboard/providers.ts | 125 ++++++++++++- .../sandbox-create-intent-resolution.ts | 24 ++- .../sandbox-messaging-preflight.test.ts | 2 +- .../onboard/sandbox-messaging-preflight.ts | 4 +- .../onboard-session-sandbox-prompts.test.ts | 4 + src/lib/state/onboard-session.ts | 4 + test/onboard-messaging.test.ts | 8 +- 24 files changed, 651 insertions(+), 68 deletions(-) diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 61da3ab4615..7c562744351 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -230,8 +230,9 @@ 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, web search selection, messaging selection and non-secret settings, resource profile, and custom Dockerfile path recorded by the original run. 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, so interactive resume can request a missing credential again while preserving the completed non-secret choices. -If a completed messaging choice lacks its credential during non-interactive resume, NemoClaw preserves the choice and exits; export the missing messaging credential environment variables, then run `$$nemoclaw onboard --resume` again. +Raw web search and messaging credentials are never written to the onboarding session. +Resume skips their secret prompts when the same session recorded the provider creation and OpenShell still reports the exact expected name, type, and credential keys. +If the session lacks that creation receipt, the provider is missing, or its binding does not match, interactive resume requests the credential again; non-interactive resume preserves the completed choice and exits so you can export the required environment variable 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 4d5c297c5bb..e6ff2182bf8 100644 --- a/docs/reference/troubleshooting.mdx +++ b/docs/reference/troubleshooting.mdx @@ -775,8 +775,8 @@ Silent retry would loop on the same failure if your original choice, such as an ``` Retry the same session without repeating completed non-secret choices. - Interactive resume can request a web search or messaging credential again when it was available only to the interrupted process because raw credentials are not stored in the onboarding session. - Non-interactive resume cannot prompt for a missing messaging credential: it preserves the completed channel choice, exits, and asks you to export the missing messaging credential environment variables before running `$$nemoclaw onboard --resume` again. + Resume also reuses registered web search and messaging credentials when the same onboarding session recorded their creation and OpenShell still reports the exact expected name, type, and credential keys. + If the session lacks that creation receipt, the provider is missing, or its binding does not match, interactive resume requests the credential again; non-interactive resume preserves the completed choice, exits, and asks you to export the required environment variable before running `$$nemoclaw onboard --resume` again. 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 @@ -2727,17 +2727,4 @@ TAVILY_API_KEY= \ NemoClaw writes `web.backend: tavily`, applies the `tavily` policy preset, and configures request-body credential rewriting for Hermes. If the same onboarding run selected the Nous-managed web gateway, Tavily replaces `nous-web` while selected Nous image, audio, browser, and code tools remain enabled. -### Re-onboarding asks every messaging prompt again - -`nemohermes onboard --resume` against a Hermes sandbox that was originally onboarded with Telegram, Discord, and Slack credentials re-prompts for each channel's bot token and per-channel settings rather than reusing the stored values. -This is tracked in [#3581](https://github.com/NVIDIA/NemoClaw/issues/3581). -For unattended re-onboards, export the messaging env vars first so the wizard skips the prompts: - -```bash -export TELEGRAM_BOT_TOKEN=... -export DISCORD_BOT_TOKEN=... -export SLACK_BOT_TOKEN=... -nemohermes onboard --resume --non-interactive -``` - diff --git a/docs/security/credential-storage.mdx b/docs/security/credential-storage.mdx index d54b5910dd8..e1b0da97c3d 100644 --- a/docs/security/credential-storage.mdx +++ b/docs/security/credential-storage.mdx @@ -120,6 +120,12 @@ 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 messaging choices are checkpointed and before resource selection, NemoClaw creates any missing sandbox-named OpenShell providers for validated web search and messaging credentials. +An existing provider is left unchanged at this early checkpoint; a replacement value is applied later during sandbox materialization. +If onboarding is interrupted afterward, `--resume` reuses a provider only when the same session recorded its creation and its name, type, and credential keys still match 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 7ca2ede3891..30f72d69c06 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 gatewayProviderMetadata: typeof import("./onboard/gateway-provider-metadata") = require("./onboard/gateway-provider-metadata"); const inferenceProviders: typeof import("./onboard/inference-providers") = require("./onboard/inference-providers"); const setupInferenceFactory: typeof import("./onboard/setup-inference") = require("./onboard/setup-inference"); @@ -989,9 +990,18 @@ function upsertMessagingProviders( // Mirror upsertProvider's withdrawal logic so a later messaging upsert // that replaces the legacy value with something else cannot leave the // mark stuck on. + recordMigratedLegacyMessagingCredentials(tokenDefs, upserted); + return upserted; +} + +function recordMigratedLegacyMessagingCredentials( + tokenDefs: MessagingTokenDef[], + registeredProviderNames: readonly string[], +): void { + const registeredProviders = new Set(registeredProviderNames); let mutated = false; for (const def of tokenDefs) { - if (!def.token || !def.envKey) continue; + if (!registeredProviders.has(def.name) || !def.token || !def.envKey) continue; const stagedValue = stagedLegacyValues.get(def.envKey); if (stagedValue === undefined) continue; if (def.token === stagedValue) { @@ -1003,10 +1013,21 @@ function upsertMessagingProviders( } } if (mutated) persistMigratedLegacyKeys(); - return upserted; +} + +function setStagedCredentialProviderReceipt(name: string, staged: boolean): void { + onboardSession.updateSession((current: Session) => { + const providers = new Set(current.stagedCredentialProviders); + if (staged) providers.add(name); + else providers.delete(name); + current.stagedCredentialProviders = [...providers]; + return current; + }); } // 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)); +// biome-ignore format: keep src/lib/onboard.ts net-neutral for growth guardrail. +const providerMatchesGatewayCredential = (name: string, type: string, credentialEnv: string, gatewayName: string = GATEWAY_NAME) => gatewayProviderMetadata.matchesGatewayCredentialOnlyProviderBinding(onboardProviders.readGatewayProviderMetadata(name, runOpenshell, gatewayName), { name, type, credentialKey: credentialEnv }); // biome-ignore format: keep src/lib/onboard.ts net-neutral for growth guardrail. const { verifyInferenceRoute, isInferenceRouteReady, checkGatewayRouteCompatibility, preflightGatewayRouteDiscovery } = inferenceRouteHelpers.createInferenceRouteHelpers(runCaptureOpenshell); @@ -3752,7 +3773,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, 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), @@ -3769,6 +3790,36 @@ const sandboxCreateIntentResolver = sandboxCreateIntentResolution.createSandboxC }), }); +async function stageSandboxCredentialProviders(input: { + sandboxName: string; + enabledChannels: readonly string[]; + webSearchConfig: import("./inference/web-search").WebSearchConfig | null; + agent: AgentDefinition | null; +}): Promise { + const messaging = await sandboxCreateIntentResolver.prepareCredentialProviders(input); + for (const tokenDef of messaging.messagingTokenDefs) { + if (normalizeCredentialValue(tokenDef.token)) { + setStagedCredentialProviderReceipt(tokenDef.name, false); + } + } + // biome-ignore format: keep src/lib/onboard.ts net-neutral for growth guardrail. + braveProviderProfile.ensureWebSearchProviderProfiles(messaging.messagingTokenDefs, { root: ROOT, runOpenshell, redact }); + const created: string[] = []; + for (const tokenDef of messaging.messagingTokenDefs) { + if (!normalizeCredentialValue(tokenDef.token)) continue; + const staged = onboardProviders.stageMessagingProvidersCreateMissingOnly( + [tokenDef], + runOpenshell, + { gatewayName: GATEWAY_NAME }, + ); + if (staged.created.length === 0) continue; + setStagedCredentialProviderReceipt(tokenDef.name, true); + recordMigratedLegacyMessagingCredentials([tokenDef], staged.created); + created.push(...staged.created); + } + return created; +} + function getRecordedMessagingChannelsForResume( resume: boolean, session: Session | null, @@ -4501,6 +4552,8 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { writePlanToEnv, clearPlanEnv, getRegistrySandboxMessagingPlan, + providerMatchesGatewayCredential, + stageSandboxCredentialProviders, promptValidatedSandboxName, selectResourceProfileForSandbox: () => selectResourceProfileForSandbox({ isNonInteractive, note, prompt, promptOrDefault }), diff --git a/src/lib/onboard/gateway-provider-metadata.test.ts b/src/lib/onboard/gateway-provider-metadata.test.ts index d0032203659..c73e15ade74 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,50 @@ 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: ["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 dc16c38791a..2cbf88ac144 100644 --- a/src/lib/onboard/lifecycle-contracts.md +++ b/src/lib/onboard/lifecycle-contracts.md @@ -48,7 +48,7 @@ Every nonterminal state has one production owner or an explicit internal designa | `finalizing`, `post_verify` | `machine/handlers/finalization.ts` | | `complete`, `failed` | Terminal; no handler | -FSM transitions remain step-granular. 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. It still cannot resume inside gateway startup, credential upserts, sandbox creation, policy application, or another handler-owned effect group. +FSM transitions remain step-granular. 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 messaging is checkpointed, validated credentials may be registered in OpenShell with secret-free provider-name receipts before the resource prompt. 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 @@ -57,7 +57,9 @@ FSM transitions remain step-granular. The sandbox handler additionally checkpoin ```text fresh onboard resolve entry options -> save session/machine* -> host preflight - -> gateway/provider effects -> checkpoint completed sandbox prompts* -> resolve complete sandbox-create intent + -> gateway/inference-provider effects -> checkpoint name/web/messaging prompts* + -> create missing credential providers + save name receipts* -> checkpoint resource prompt* + -> resolve complete sandbox-create intent -> materialize create plan -> create -> ready -> live validation -> register* -> finalize session* @@ -94,9 +96,9 @@ 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, with narrow checkpoints after each completed secret-free sandbox prompt group; 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`, `sandbox-create-intent-boundary.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. Validated web-search and messaging providers can be created after their prompt 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, with 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 created 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. Completed sandbox name, web search, messaging, and resource choices have explicit progress markers, including explicit `null` choices, while the complete create intent stays process-local and is not persisted or emitted. Raw credential values are rebound or requested again when missing; non-interactive messaging recovery preserves the checkpoint and fails with environment-variable guidance instead of prompting. 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). | +| **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. Completed sandbox name, web search, messaging, and resource choices have 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 session recorded creating 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. | @@ -118,7 +120,7 @@ The schema and sanitation authority is `Session` plus `normalizeSession`/`filter | 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`, `sandboxPromptProgress` | Step-mutation helpers and `OnboardRuntime` own whole-step progress; the sandbox handler owns prompt-group completion markers. A marker is trusted only when its matching persisted value is present and valid, including an explicit `null` where supported. | +| Progress and recovery | `lastStepStarted`, `lastCompletedStep`, `failure`, `steps`, `machine`, `sandboxPromptProgress`, `stagedCredentialProviders` | Step-mutation helpers and `OnboardRuntime` own whole-step progress; the sandbox handler owns prompt-group completion markers. `stagedCredentialProviders` contains only names created before sandbox setup so 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. | 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/sandbox-create-intent-boundary.test.ts b/src/lib/onboard/machine/handlers/sandbox-create-intent-boundary.test.ts index 72c82199463..718f695ac24 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 @@ -198,6 +198,17 @@ describe("sandbox create intent machine boundary", () => { }); const configureWebSearch = vi.fn(async () => braveConfig); const setupMessagingChannels = vi.fn(async () => []); + const providerMatchesGatewayCredential = vi.fn( + (name: string, type: string, credentialEnvName: string) => + name === "tm-brave-search" && type === "brave" && credentialEnvName === "BRAVE_API_KEY", + ); + const stageSandboxCredentialProviders = vi + .fn<() => Promise>() + .mockImplementationOnce(async () => { + durableSession.stagedCredentialProviders = ["tm-brave-search"]; + return ["tm-brave-search"]; + }) + .mockResolvedValue([]); const readMessagingPlanFromEnv = vi .fn<() => typeof messagingPlan | null>() .mockReturnValueOnce(null) @@ -208,6 +219,8 @@ describe("sandbox create intent machine boundary", () => { recordStepComplete, configureWebSearch, setupMessagingChannels, + providerMatchesGatewayCredential, + stageSandboxCredentialProviders, readMessagingPlanFromEnv, }); calls.selectResourceProfile.mockRejectedValueOnce(new Error("resource prompt interrupted")); @@ -234,6 +247,15 @@ describe("sandbox create intent machine boundary", () => { }); 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( + calls.selectResourceProfile.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY, + ); calls.selectResourceProfile.mockResolvedValueOnce({ cpu: "75%", memory: "75%" }); await handleSandboxState({ @@ -241,11 +263,17 @@ describe("sandbox create intent machine boundary", () => { resume: true, sandboxName: durableSession.sandboxName, webSearchConfig: durableSession.webSearchConfig, - env: credentialEnv, + 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(calls.promptName).not.toHaveBeenCalled(); expect(calls.selectResourceProfile).toHaveBeenCalledTimes(2); expect(calls.resolveCreateIntent).toHaveBeenCalledTimes(1); diff --git a/src/lib/onboard/machine/handlers/sandbox-messaging.test.ts b/src/lib/onboard/machine/handlers/sandbox-messaging.test.ts index f2f9584c9c6..b7d4046c3c6 100644 --- a/src/lib/onboard/machine/handlers/sandbox-messaging.test.ts +++ b/src/lib/onboard/machine/handlers/sandbox-messaging.test.ts @@ -141,10 +141,14 @@ function telegramPlan(credentialHash: string): SandboxMessagingPlan { }; } -function completedCheckpointSession(plan: SandboxMessagingPlan) { +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; @@ -163,6 +167,7 @@ function reconcileDeps(plans: readonly (SandboxMessagingPlan | null)[]) { writePlanToEnv: vi.fn(), clearPlanEnv: vi.fn(), getRegistrySandboxMessagingPlan: vi.fn(() => null), + providerMatchesGatewayCredential: vi.fn(() => false), }; } @@ -295,9 +300,10 @@ describe("reconcileSandboxMessaging completed checkpoint credentials", () => { expect(persistedPlan.credentialBindings[0]?.credentialHash).toBe(hashCredential(previousToken)); }); - it("runs existing setup validation when the checkpointed credential is missing", async () => { + 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( @@ -316,5 +322,28 @@ describe("reconcileSandboxMessaging completed checkpoint credentials", () => { "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 ba82e1a44e7..17c2b8bcff1 100644 --- a/src/lib/onboard/machine/handlers/sandbox-messaging.ts +++ b/src/lib/onboard/machine/handlers/sandbox-messaging.ts @@ -35,6 +35,7 @@ export interface SandboxMessagingDeps { writePlanToEnv(plan: SandboxMessagingPlan): void; clearPlanEnv(): void; getRegistrySandboxMessagingPlan(sandboxName: string): SandboxMessagingPlan | null; + providerMatchesGatewayCredential(name: string, type: string, credentialEnv: string): boolean; } export interface SandboxMessagingSelection { @@ -298,11 +299,17 @@ async function selectionFromCompletedMessagingCheckpoint( } const activeChannels = new Set(selectedChannels); - const credentialNeedsValidation = filteredPlan.credentialBindings.some( - (binding) => - activeChannels.has(binding.channelId) && - hashCredential(getCredential(binding.providerEnvKey)) !== binding.credentialHash, - ); + 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) { return selectionFromMessagingSetup(selectedChannels, options, true); } 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..69db593911a 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,7 +49,7 @@ 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({ checkGatewayRouteCompatibility: () => { @@ -68,6 +68,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 +85,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 ce5efcdaa42..b8a9795fb18 100644 --- a/src/lib/onboard/machine/handlers/sandbox-test-fixtures.ts +++ b/src/lib/onboard/machine/handlers/sandbox-test-fixtures.ts @@ -113,6 +113,7 @@ export function createDeps( 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(), @@ -224,6 +225,8 @@ export function createDeps( 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.ts b/src/lib/onboard/machine/handlers/sandbox.ts index 57790f71b71..a0a32d83b1c 100644 --- a/src/lib/onboard/machine/handlers/sandbox.ts +++ b/src/lib/onboard/machine/handlers/sandbox.ts @@ -12,6 +12,7 @@ import { type WebSearchConfig as SharedWebSearchConfig, WEB_SEARCH_PROVIDER_ENV, webSearchConfigsEqual, + webSearchEnvFor, webSearchLabelFor, webSearchProviderForConfig, } from "../../../inference/web-search"; @@ -25,6 +26,7 @@ import type { import type { SandboxEntry } from "../../../state/registry"; import { getSandboxEntryInference } from "../../../state/registry-entry-view"; import { toolDisclosureOrDefault } from "../../../tool-disclosure"; +import { HERMES_TAVILY_PROVIDER_PROFILE_ID } from "../../brave-provider-profile"; import { withDashboardPortReservationLock as withHostDashboardPortReservationLock } from "../../dashboard-port"; import { type DashboardRuntimeAgent, shouldManageDashboardForAgent } from "../../dashboard-runtime"; import { @@ -172,6 +174,13 @@ export interface SandboxStateOptions< 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; @@ -642,6 +651,29 @@ class SandboxStateFlow< state.webSearchConfig as unknown as SharedWebSearchConfig, ); const label = webSearchLabelFor(provider); + const credentialEnv = webSearchEnvFor(provider); + const localCredential = this.options.env[credentialEnv]?.trim(); + const providerType = + provider === "tavily" && + (this.options.agent as { name?: string } | null)?.name?.trim().toLowerCase() === "hermes" + ? HERMES_TAVILY_PROVIDER_PROFILE_ID + : provider; + if ( + this.options.resume && + state.sandboxName && + !localCredential && + state.session?.stagedCredentialProviders.includes( + `${state.sandboxName}-${provider}-search`, + ) && + this.deps.providerMatchesGatewayCredential( + `${state.sandboxName}-${provider}-search`, + providerType, + 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; @@ -945,6 +977,19 @@ class SandboxStateFlow< deps: this.deps, }); nextState = this.checkpointMessaging(nextState, messaging); + const stagedProviders = await this.deps.withGatewayRouteMutationLock( + this.options.gatewayName, + () => + this.deps.stageSandboxCredentialProviders({ + sandboxName: requestedSandboxName, + enabledChannels: nextState.selectedMessagingChannels, + webSearchConfig: nextState.webSearchConfig, + agent: this.options.agent, + }), + ); + if (stagedProviders.length > 0) { + this.deps.note(" ✓ Registered selected credentials with OpenShell for resume."); + } return this.createAndRecordSandbox(nextState, requestedSandboxName, messaging.plan, decision); } diff --git a/src/lib/onboard/messaging-prep.test.ts b/src/lib/onboard/messaging-prep.test.ts index 886d3489961..4c97c37c95b 100644 --- a/src/lib/onboard/messaging-prep.test.ts +++ b/src/lib/onboard/messaging-prep.test.ts @@ -36,7 +36,7 @@ function createInput( if (envKey === "WECHAT_BOT_TOKEN") return "wechat"; return null; }, - providerExistsInGateway: () => false, + providerMatchesGatewayCredential: () => false, ...overrides, }; } @@ -44,7 +44,7 @@ function createInput( describe("prepareCreateSandboxMessaging", () => { it("filters token definitions by selected and disabled channels and reuses attached missing-token providers", () => { const registerExtraPlaceholderProviders = vi.fn(() => ["SLACK_BOT_TOKEN_AGENT_A"]); - const providerExistsInGateway = vi.fn((name: string) => name === "demo-slack-bridge"); + const providerMatchesGatewayCredential = vi.fn((name: string) => name === "demo-slack-bridge"); const result = prepareCreateSandboxMessaging( createInput({ @@ -53,7 +53,7 @@ describe("prepareCreateSandboxMessaging", () => { getValidatedMessagingTokenByEnvKey: (_channels, envKey) => envKey === "SLACK_APP_TOKEN" ? "xapp-valid" : null, registerExtraPlaceholderProviders, - providerExistsInGateway, + providerMatchesGatewayCredential, }), ); @@ -66,7 +66,11 @@ describe("prepareCreateSandboxMessaging", () => { expect(result.hasMessagingTokens).toBe(true); expect(result.reusableMessagingProviders).toEqual(["demo-slack-bridge"]); expect(result.reusableMessagingChannels).toEqual(["slack"]); - expect(providerExistsInGateway).toHaveBeenCalledWith("demo-slack-bridge"); + expect(providerMatchesGatewayCredential).toHaveBeenCalledWith( + "demo-slack-bridge", + "generic", + "SLACK_BOT_TOKEN", + ); expect(registerExtraPlaceholderProviders).toHaveBeenCalledWith( "demo", result.messagingTokenDefs, @@ -92,6 +96,29 @@ 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 }, + 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 +209,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 +228,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..86d446bcaa7 100644 --- a/src/lib/onboard/messaging-prep.ts +++ b/src/lib/onboard/messaging-prep.ts @@ -35,7 +35,7 @@ export interface CreateSandboxMessagingPrepInput { messagingTokenDefs: MessagingTokenDef[], ): string[]; getMessagingChannelForEnvKey(envKey: string): string | null; - providerExistsInGateway(name: string): boolean; + providerMatchesGatewayCredential(name: string, type: string, credentialEnv: string): boolean; } export interface CreateSandboxMessagingPrepResult { @@ -79,12 +79,28 @@ 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 = + webSearchEnabled && + !webSearchApiKey && + input.providerMatchesGatewayCredential( + webSearchProviderName, + webSearchProviderType, + webSearchCredentialEnv, + ); const missingWebSearchCredentialEnv = - webSearchEnabled && !webSearchApiKey ? webSearchCredentialEnv : null; + webSearchEnabled && !webSearchApiKey && !reusableWebSearchProvider + ? webSearchCredentialEnv + : null; if (missingWebSearchCredentialEnv) { return { disabledChannelNames, @@ -98,15 +114,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 +127,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 +137,7 @@ export function prepareCreateSandboxMessaging( if (token) continue; const channel = input.getMessagingChannelForEnvKey(envKey); if (!channel || !input.enabledChannels.includes(channel)) continue; - if (!input.providerExistsInGateway(name)) continue; + if (!input.providerMatchesGatewayCredential(name, "generic", envKey)) continue; reusableMessagingProviders.push(name); if (!reusableMessagingChannels.includes(channel)) { reusableMessagingChannels.push(channel); diff --git a/src/lib/onboard/providers.test.ts b/src/lib/onboard/providers.test.ts index acf689cfd13..de463df5590 100644 --- a/src/lib/onboard/providers.test.ts +++ b/src/lib/onboard/providers.test.ts @@ -4,7 +4,7 @@ import { describe, expect, it } from "vitest"; type RunResult = { status: number; stdout?: string; stderr?: string }; -type RunOptions = { env?: Record }; +type RunOptions = { env?: Record; suppressOutput?: boolean }; type RunOpenshell = (command: string[], opts?: RunOptions) => RunResult; const { @@ -18,6 +18,7 @@ const { getRequestedProviderHint, isProviderKeyCredentialCandidate, providerExistsInGateway, + stageMessagingProvidersCreateMissingOnly, stageHostedInferenceSourceSecretEnv, upsertProvider, upsertMessagingProviders, @@ -51,6 +52,16 @@ const { ) => string | null; isProviderKeyCredentialCandidate: (value: string | null | undefined) => boolean; providerExistsInGateway: (name: string, runOpenshell: RunOpenshell) => boolean; + stageMessagingProvidersCreateMissingOnly: ( + tokenDefs: Array<{ + name: string; + envKey: string; + token: string | null; + providerType?: string; + }>, + runOpenshell: RunOpenshell, + options?: { gatewayName?: string | null }, + ) => { created: string[]; reused: string[]; skipped: string[] }; stageHostedInferenceSourceSecretEnv: () => boolean; upsertProvider: ( name: string, @@ -235,6 +246,161 @@ describe("onboard provider helpers", () => { expect(providerExistsInGateway("missing-bridge", () => ({ status: 1 }))).toBe(false); }); + it("reuses an exact credential-only provider without mutating it", () => { + const commands: string[] = []; + const result = stageMessagingProvidersCreateMissingOnly( + [ + { + name: "tm-telegram-bridge", + envKey: "TELEGRAM_BOT_TOKEN", + token: "123456:test-token", + }, + ], + (command) => { + commands.push(command.join(" ")); + return { + status: 0, + stdout: + "Name: tm-telegram-bridge\nType: generic\nCredential keys: TELEGRAM_BOT_TOKEN\nConfig keys: \n", + }; + }, + { gatewayName: "nemoclaw" }, + ); + + expect(result).toEqual({ + created: [], + reused: ["tm-telegram-bridge"], + skipped: [], + }); + expect(commands).toEqual(["provider get -g nemoclaw tm-telegram-bridge"]); + }); + + it.each([ + ["the provider type differs", "brave", "TELEGRAM_BOT_TOKEN", ""], + ["the credential key differs", "generic", "OTHER_TOKEN", ""], + ["the provider has configuration", "generic", "TELEGRAM_BOT_TOKEN", "BASE_URL"], + ])("skips an existing provider when %s", (_label, type, credentialKey, configKey) => { + const commands: string[] = []; + const result = stageMessagingProvidersCreateMissingOnly( + [ + { + name: "tm-telegram-bridge", + envKey: "TELEGRAM_BOT_TOKEN", + token: "123456:test-token", + }, + ], + (command) => { + commands.push(command.join(" ")); + return { + status: 0, + stdout: `Name: tm-telegram-bridge\nType: ${type}\nCredential keys: ${credentialKey}\nConfig keys: ${configKey}\n`, + }; + }, + { gatewayName: "nemoclaw" }, + ); + + expect(result).toEqual({ + created: [], + reused: [], + skipped: ["tm-telegram-bridge"], + }); + expect(commands).toEqual(["provider get -g nemoclaw tm-telegram-bridge"]); + }); + + it("creates an exactly absent provider with its secret only in the command environment", () => { + const calls: Array<{ command: string[]; options?: RunOptions }> = []; + const token = "123456:staged-secret-token"; + const result = stageMessagingProvidersCreateMissingOnly( + [ + { + name: "tm-telegram-bridge", + envKey: "TELEGRAM_BOT_TOKEN", + token, + }, + ], + (command, options) => { + calls.push({ command, options }); + if (command[1] === "get") { + return { + status: 1, + stderr: "Error: provider 'tm-telegram-bridge' not found", + }; + } + return { status: 0 }; + }, + { gatewayName: "nemoclaw" }, + ); + + expect(result).toEqual({ + created: ["tm-telegram-bridge"], + reused: [], + skipped: [], + }); + expect(calls.map(({ command }) => command.join(" "))).toEqual([ + "provider get -g nemoclaw tm-telegram-bridge", + "provider create -g nemoclaw --name tm-telegram-bridge --type generic --credential TELEGRAM_BOT_TOKEN", + ]); + expect(calls[1]?.command).not.toContain(token); + expect(calls[1]?.options?.env).toEqual({ TELEGRAM_BOT_TOKEN: token }); + expect(calls[1]?.options?.suppressOutput).toBe(true); + }); + + it("skips an indeterminate absence probe instead of attempting a create", () => { + const commands: string[] = []; + const result = stageMessagingProvidersCreateMissingOnly( + [ + { + name: "tm-telegram-bridge", + envKey: "TELEGRAM_BOT_TOKEN", + token: "123456:test-token", + }, + ], + (command) => { + commands.push(command.join(" ")); + return { status: 1, stderr: "gateway unavailable" }; + }, + { gatewayName: "nemoclaw" }, + ); + + expect(result).toEqual({ + created: [], + reused: [], + skipped: ["tm-telegram-bridge"], + }); + expect(commands).toEqual(["provider get -g nemoclaw tm-telegram-bridge"]); + }); + + it("throws on create failure without attempting update, delete, or secret-bearing arguments", () => { + const commands: string[] = []; + const token = "123456:staged-secret-token"; + + expect(() => + stageMessagingProvidersCreateMissingOnly( + [ + { + name: "tm-telegram-bridge", + envKey: "TELEGRAM_BOT_TOKEN", + token, + }, + ], + (command) => { + commands.push(command.join(" ")); + if (command[1] === "get") { + return { + status: 1, + stderr: "Error: provider 'tm-telegram-bridge' not found", + }; + } + return { status: 1, stderr: `gateway rejected ${token}` }; + }, + { gatewayName: "nemoclaw" }, + ), + ).toThrow("Failed to stage messaging provider 'tm-telegram-bridge': gateway rejected"); + + expect(commands.every((command) => !command.includes(token))).toBe(true); + expect(commands.some((command) => /provider (update|delete)/.test(command))).toBe(false); + }); + it("creates a new provider and returns ok on success", () => { const commands: string[] = []; const result = upsertProvider( diff --git a/src/lib/onboard/providers.ts b/src/lib/onboard/providers.ts index d33aac3d9e2..fc5d01b9ee3 100644 --- a/src/lib/onboard/providers.ts +++ b/src/lib/onboard/providers.ts @@ -16,7 +16,12 @@ const { const openrouter = require("../inference/openrouter"); const { isSafeModelId } = require("../validation"); const { compactText } = require("../core/url-utils"); -const { readGatewayProviderMetadata } = require("./gateway-provider-metadata"); +const { + matchesGatewayCredentialOnlyProviderBinding, + parseGatewayProviderMetadata, + readGatewayProviderMetadata, +} = require("./gateway-provider-metadata"); +const { reportsExactProviderNotFound } = require("./extra-provider-diagnostic-parser"); // ── Constants ──────────────────────────────────────────────────── @@ -511,6 +516,123 @@ function upsertMessagingProviders(tokenDefs, _runOpenshell, options = {}) { return upserted; } +const STAGED_PROVIDER_DIAGNOSTIC_LIMIT = 16 * 1024; +const SAFE_STAGED_PROVIDER_NAME = /^[A-Za-z0-9._:-]{1,128}$/; +const SAFE_STAGED_PROVIDER_TYPE = /^[A-Za-z0-9._:-]{1,64}$/; +const SAFE_STAGED_CREDENTIAL_KEY = /^[A-Z_][A-Z0-9_]{0,127}$/; + +function providerCommandOutput(result) { + const text = (value) => { + if (Buffer.isBuffer(value)) return value.toString("utf8"); + return typeof value === "string" ? value : ""; + }; + const streams = [text(result.stderr), text(result.stdout)].filter(Boolean); + return streams.length > 0 ? streams.join("\n") : text(result.output); +} + +function inspectStagedProvider(name, gatewayName, _runOpenshell) { + const args = ["provider", "get"]; + if (gatewayName) args.push("-g", gatewayName); + args.push(name); + const result = _runOpenshell(args, { + ignoreError: true, + maxBuffer: STAGED_PROVIDER_DIAGNOSTIC_LIMIT, + suppressOutput: true, + stdio: ["ignore", "pipe", "pipe"], + }); + const output = providerCommandOutput(result); + if (result.status === 0) { + const metadata = parseGatewayProviderMetadata(output); + return { kind: "existing", metadata: metadata?.name === name ? metadata : null }; + } + if ( + result.status === 1 && + Buffer.byteLength(output) < STAGED_PROVIDER_DIAGNOSTIC_LIMIT && + reportsExactProviderNotFound(output, name, STAGED_PROVIDER_DIAGNOSTIC_LIMIT) + ) { + return { kind: "absent", metadata: null }; + } + return { kind: "indeterminate", metadata: null }; +} + +function stagedProviderCreateArgs(name, type, envKey, gatewayName) { + const args = buildProviderArgs("create", name, type, envKey, null); + if (gatewayName) args.splice(2, 0, "-g", gatewayName); + return args; +} + +/** + * Stage validated messaging credentials without mutating an existing provider. + * + * Existing providers are reported as reusable only when their complete + * non-secret binding matches. This does not prove that an existing provider + * contains the supplied token; callers must retain separate ownership proof + * before trusting one for credential-free resume. Mismatched, malformed, and + * indeterminate probes are left untouched. + * An absent provider is created with its secret available only in the command + * environment; this path never issues provider update/delete/replace commands. + * + * @param {Array<{name: string, envKey: string, token: string|null, providerType?: string}>} tokenDefs + * @param {Function} _runOpenshell - Injected runOpenshell from onboard.ts. + * @param {{gatewayName?: string|null}} options - Exact gateway scope when available. + * @returns {{created: string[], reused: string[], skipped: string[]}} + */ +function stageMessagingProvidersCreateMissingOnly(tokenDefs, _runOpenshell, options = {}) { + const created = []; + const reused = []; + const skipped = []; + const gatewayName = options.gatewayName || null; + + for (const { name, envKey, token, providerType } of tokenDefs) { + const credential = normalizeCredentialValue(token); + if (!credential) continue; + const type = providerType || "generic"; + if ( + !SAFE_STAGED_PROVIDER_NAME.test(name) || + !SAFE_STAGED_PROVIDER_TYPE.test(type) || + !SAFE_STAGED_CREDENTIAL_KEY.test(envKey) + ) { + skipped.push(name); + continue; + } + + const inspection = inspectStagedProvider(name, gatewayName, _runOpenshell); + if (inspection.kind === "existing") { + if ( + matchesGatewayCredentialOnlyProviderBinding(inspection.metadata, { + name, + type, + credentialKey: envKey, + }) + ) { + reused.push(name); + } else { + skipped.push(name); + } + continue; + } + if (inspection.kind !== "absent") { + skipped.push(name); + continue; + } + + const result = _runOpenshell(stagedProviderCreateArgs(name, type, envKey, gatewayName), { + ignoreError: true, + env: { [envKey]: credential }, + suppressOutput: true, + stdio: ["ignore", "pipe", "pipe"], + }); + if (result.status !== 0) { + const rawOutput = providerCommandOutput(result).replaceAll(credential, "[REDACTED]"); + const output = compactText(redact(rawOutput)) || `Provider create exited unsuccessfully.`; + throw new Error(`Failed to stage messaging provider '${name}': ${output}`); + } + created.push(name); + } + + return { created, reused, skipped }; +} + module.exports = { BUILD_ENDPOINT_URL, OPENAI_ENDPOINT_URL, @@ -540,6 +662,7 @@ module.exports = { upsertProvider, providerExistsInGateway, readGatewayProviderMetadata, + stageMessagingProvidersCreateMissingOnly, upsertMessagingProviders, getSandboxInferenceConfig, }; diff --git a/src/lib/onboard/sandbox-create-intent-resolution.ts b/src/lib/onboard/sandbox-create-intent-resolution.ts index f9151eaf390..d298da465ea 100644 --- a/src/lib/onboard/sandbox-create-intent-resolution.ts +++ b/src/lib/onboard/sandbox-create-intent-resolution.ts @@ -58,7 +58,17 @@ export function createSandboxCreateIntentResolver< "sandboxName" | "enabledChannels" | "webSearchConfig" | "agent" >, expectedIntent?: SandboxCreateIntent, + skipPlanConflictCheck = false, ) { + const preflightDeps = expectedIntent + ? { + ...deps.messagingPreflightDeps, + readMessagingPlanFromEnv: () => null, + resolveDisabledChannels: () => [...expectedIntent.disabledChannelNames], + } + : skipPlanConflictCheck + ? { ...deps.messagingPreflightDeps, readMessagingPlanFromEnv: () => null } + : deps.messagingPreflightDeps; const result = await prepareSandboxMessagingPreflight( { channels: deps.channels, @@ -68,13 +78,7 @@ export function createSandboxCreateIntentResolver< 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 +135,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..b14876d26c8 100644 --- a/src/lib/onboard/sandbox-messaging-preflight.test.ts +++ b/src/lib/onboard/sandbox-messaging-preflight.test.ts @@ -110,7 +110,7 @@ function createDeps( registry: { 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..524413a4bfd 100644 --- a/src/lib/onboard/sandbox-messaging-preflight.ts +++ b/src/lib/onboard/sandbox-messaging-preflight.ts @@ -28,7 +28,7 @@ export interface SandboxMessagingPreflightDeps { resolveDisabledChannels(sandboxName: string): string[]; gatewayName(): string; registry: MessagingConflictGuardDeps["registry"]; - providerExistsInGateway(name: string): boolean; + providerMatchesGatewayCredential(name: string, type: string, credentialEnv: string): boolean; isNonInteractive(): boolean; promptYesNoOrDefault( message: string, @@ -80,7 +80,7 @@ export async function prepareSandboxMessagingPreflight( normalizeCredentialValue: deps.normalizeCredentialValue, registerExtraPlaceholderProviders: deps.registerExtraPlaceholderProviders, getMessagingChannelForEnvKey: deps.getMessagingChannelForEnvKey, - providerExistsInGateway: deps.providerExistsInGateway, + providerMatchesGatewayCredential: deps.providerMatchesGatewayCredential, }); if (result.missingWebSearchCredentialEnv) { diff --git a/src/lib/state/onboard-session-sandbox-prompts.test.ts b/src/lib/state/onboard-session-sandbox-prompts.test.ts index cad853cb912..bd84e019ac7 100644 --- a/src/lib/state/onboard-session-sandbox-prompts.test.ts +++ b/src/lib/state/onboard-session-sandbox-prompts.test.ts @@ -81,6 +81,7 @@ describe("onboard session sandbox prompt checkpoints", () => { resourceProfile: true, }, resourceProfile, + stagedCredentialProviders: ["tm-brave-search", "tm-telegram-bridge"], }); Object.assign(created as unknown as Record, { BRAVE_API_KEY: braveCredential, @@ -101,6 +102,7 @@ describe("onboard session sandbox prompt checkpoints", () => { resourceProfile: true, }, resourceProfile, + stagedCredentialProviders: ["tm-brave-search", "tm-telegram-bridge"], }); const serialized = JSON.stringify(raw); expect(serialized).not.toContain(braveCredential); @@ -117,6 +119,7 @@ describe("onboard session sandbox prompt checkpoints", () => { 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)", () => { @@ -129,6 +132,7 @@ describe("onboard session sandbox prompt checkpoints", () => { resourceProfile: false, }); expect(fresh.resourceProfile).toBeNull(); + expect(fresh.stagedCredentialProviders).toEqual([]); }); it("keeps explicit null choices complete but clears malformed or missing values (#6743)", () => { diff --git a/src/lib/state/onboard-session.ts b/src/lib/state/onboard-session.ts index 460d46ba568..904895b03ef 100644 --- a/src/lib/state/onboard-session.ts +++ b/src/lib/state/onboard-session.ts @@ -173,6 +173,8 @@ export interface Session { hermesToolGateways: string[] | null; policyPresets: string[] | null; messagingPlan: SandboxMessagingPlan | null; + /** Non-secret names of credential providers created 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 @@ -644,6 +646,7 @@ export function createSession(overrides: Partial = {}): Session { hermesToolGateways: readStringArray(overrides.hermesToolGateways), policyPresets: readStringArray(overrides.policyPresets), messagingPlan: parseSandboxMessagingPlan(overrides.messagingPlan), + stagedCredentialProviders: readStringArray(overrides.stagedCredentialProviders) ?? [], migratedLegacyValueHashes: overrides.migratedLegacyValueHashes ? readStringRecord(overrides.migratedLegacyValueHashes) : null, @@ -692,6 +695,7 @@ export function normalizeSession(data: Session | SessionJsonValue | undefined): 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 }; }; From 4fa97d41a25160697ccd6e310547326d92fdbc37 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 15 Jul 2026 19:07:35 +0700 Subject: [PATCH 3/5] fix(onboard): register resume credentials early Signed-off-by: San Dang --- docs/reference/commands.mdx | 13 +- docs/reference/troubleshooting.mdx | 26 ++- docs/security/credential-storage.mdx | 13 +- src/lib/onboard.ts | 121 +++------- .../credential-provider-registration.test.ts | 220 ++++++++++++++++++ .../credential-provider-registration.ts | 162 +++++++++++++ .../onboard/gateway-provider-metadata.test.ts | 3 + src/lib/onboard/lifecycle-contracts.md | 16 +- .../machine/handlers/provider-inference.ts | 2 + .../sandbox-create-intent-boundary.test.ts | 3 + .../handlers/sandbox-messaging.test.ts | 4 +- .../machine/handlers/sandbox-messaging.ts | 8 +- .../sandbox-route-mutation-lock.test.ts | 4 + .../handlers/sandbox-tool-disclosure.test.ts | 1 + .../onboard/machine/handlers/sandbox.test.ts | 2 + src/lib/onboard/machine/handlers/sandbox.ts | 71 ++++-- src/lib/onboard/messaging-prep.test.ts | 12 +- src/lib/onboard/messaging-prep.ts | 11 +- src/lib/onboard/providers.test.ts | 168 +------------ src/lib/onboard/providers.ts | 125 +--------- src/lib/onboard/sandbox-agent.test.ts | 21 +- src/lib/onboard/sandbox-agent.ts | 61 ++--- .../sandbox-create-intent-resolution.ts | 16 +- .../sandbox-messaging-preflight.test.ts | 1 + .../onboard/sandbox-messaging-preflight.ts | 4 + src/lib/onboard/session-bootstrap.ts | 26 ++- src/lib/onboard/types.ts | 2 + .../onboard-session-sandbox-prompts.test.ts | 25 +- src/lib/state/onboard-session.ts | 11 +- test/onboard-inference-reconciliation.test.ts | 45 +--- 30 files changed, 683 insertions(+), 514 deletions(-) create mode 100644 src/lib/onboard/credential-provider-registration.test.ts create mode 100644 src/lib/onboard/credential-provider-registration.ts diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 7c562744351..652ff1b3d8e 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -227,12 +227,19 @@ For example, `nemohermes` resolves to `hermes`, while `dcode`, `deepagents`, `de #### `--resume` and `--fresh` 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, web search selection, messaging selection and non-secret settings, resource profile, and custom Dockerfile path recorded by the original run. +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 the provider creation and OpenShell still reports the exact expected name, type, and credential keys. -If the session lacks that creation receipt, the provider is missing, or its binding does not match, interactive resume requests the credential again; non-interactive resume preserves the completed choice and exits so you can export the required environment variable before retrying. +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 e6ff2182bf8..33ed0d7b9eb 100644 --- a/docs/reference/troubleshooting.mdx +++ b/docs/reference/troubleshooting.mdx @@ -774,15 +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 repeating completed non-secret choices. - Resume also reuses registered web search and messaging credentials when the same onboarding session recorded their creation and OpenShell still reports the exact expected name, type, and credential keys. - If the session lacks that creation receipt, the provider is missing, or its binding does not match, interactive resume requests the credential again; non-interactive resume preserves the completed choice, exits, and asks you to export the required environment variable before running `$$nemoclaw onboard --resume` again. + 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 @@ -2727,4 +2734,17 @@ TAVILY_API_KEY= \ NemoClaw writes `web.backend: tavily`, applies the `tavily` policy preset, and configures request-body credential rewriting for Hermes. If the same onboarding run selected the Nous-managed web gateway, Tavily replaces `nous-web` while selected Nous image, audio, browser, and code tools remain enabled. +### Re-onboarding asks every messaging prompt again + +`nemohermes onboard --resume` against a Hermes sandbox that was originally onboarded with Telegram, Discord, and Slack credentials re-prompts for each channel's bot token and per-channel settings rather than reusing the stored values. +This is tracked in [#3581](https://github.com/NVIDIA/NemoClaw/issues/3581). +For unattended re-onboards, export the messaging env vars first so the wizard skips the prompts: + +```bash +export TELEGRAM_BOT_TOKEN=... +export DISCORD_BOT_TOKEN=... +export SLACK_BOT_TOKEN=... +nemohermes onboard --resume --non-interactive +``` + diff --git a/docs/security/credential-storage.mdx b/docs/security/credential-storage.mdx index e1b0da97c3d..1cf51df669d 100644 --- a/docs/security/credential-storage.mdx +++ b/docs/security/credential-storage.mdx @@ -120,12 +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 messaging choices are checkpointed and before resource selection, NemoClaw creates any missing sandbox-named OpenShell providers for validated web search and messaging credentials. -An existing provider is left unchanged at this early checkpoint; a replacement value is applied later during sandbox materialization. -If onboarding is interrupted afterward, `--resume` reuses a provider only when the same session recorded its creation and its name, type, and credential keys still match the saved choice. + + + +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 30f72d69c06..7b0c7de17a1 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -253,7 +253,7 @@ const inferenceConfig: typeof import("./inference/config") = require("./inferenc const { DEFAULT_CLOUD_MODEL, getProviderSelectionConfig, parseGatewayInference } = inferenceConfig; const onboardProviders = require("./onboard/providers"); -const gatewayProviderMetadata: typeof import("./onboard/gateway-provider-metadata") = require("./onboard/gateway-provider-metadata"); +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"); @@ -449,13 +449,8 @@ const promptValidatedSandboxName = sandboxAgent.createPromptValidatedSandboxName promptOrDefault, cliDisplayName, isNonInteractive, - checkpointSandboxName: (sandboxName) => { - onboardSession.updateSession((current: Session) => { - current.sandboxName = sandboxName; - current.sandboxPromptProgress.sandboxName = true; - return current; - }); - }, + checkpointSandboxName: (sandboxName, agent) => + onboardSessionBootstrap.checkpointSandboxName(sandboxName, agent, onboardSession.updateSession), exit: process.exit, }); const modelRouter: typeof import("./onboard/model-router") = require("./onboard/model-router"); @@ -975,59 +970,22 @@ 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. - recordMigratedLegacyMessagingCredentials(tokenDefs, upserted); - return upserted; -} - -function recordMigratedLegacyMessagingCredentials( - tokenDefs: MessagingTokenDef[], - registeredProviderNames: readonly string[], -): 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 = 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(); -} - -function setStagedCredentialProviderReceipt(name: string, staged: boolean): void { - onboardSession.updateSession((current: Session) => { - const providers = new Set(current.stagedCredentialProviders); - if (staged) providers.add(name); - else providers.delete(name); - current.stagedCredentialProviders = [...providers]; - return current; +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)); -// biome-ignore format: keep src/lib/onboard.ts net-neutral for growth guardrail. -const providerMatchesGatewayCredential = (name: string, type: string, credentialEnv: string, gatewayName: string = GATEWAY_NAME) => gatewayProviderMetadata.matchesGatewayCredentialOnlyProviderBinding(onboardProviders.readGatewayProviderMetadata(name, runOpenshell, gatewayName), { name, type, credentialKey: credentialEnv }); // biome-ignore format: keep src/lib/onboard.ts net-neutral for growth guardrail. const { verifyInferenceRoute, isInferenceRouteReady, checkGatewayRouteCompatibility, preflightGatewayRouteDiscovery } = inferenceRouteHelpers.createInferenceRouteHelpers(runCaptureOpenshell); @@ -2337,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( @@ -2345,6 +2304,7 @@ async function createSandboxWithBaseImageResolution( enabledChannels, webSearchConfig, agent, + ...(createIntent?.reuseRegisteredCredentials ? { reuseRegisteredCredentials: true } : {}), }, resolvedCreateIntent, ); @@ -2735,6 +2695,7 @@ async function createSandboxWithBaseImageResolution( enabledChannels, webSearchConfig, agent, + ...(createIntent?.reuseRegisteredCredentials ? { reuseRegisteredCredentials: true } : {}), }, resolvedCreateIntent, ); @@ -3773,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, 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 }, + 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), @@ -3790,35 +3751,8 @@ const sandboxCreateIntentResolver = sandboxCreateIntentResolution.createSandboxC }), }); -async function stageSandboxCredentialProviders(input: { - sandboxName: string; - enabledChannels: readonly string[]; - webSearchConfig: import("./inference/web-search").WebSearchConfig | null; - agent: AgentDefinition | null; -}): Promise { - const messaging = await sandboxCreateIntentResolver.prepareCredentialProviders(input); - for (const tokenDef of messaging.messagingTokenDefs) { - if (normalizeCredentialValue(tokenDef.token)) { - setStagedCredentialProviderReceipt(tokenDef.name, false); - } - } - // biome-ignore format: keep src/lib/onboard.ts net-neutral for growth guardrail. - braveProviderProfile.ensureWebSearchProviderProfiles(messaging.messagingTokenDefs, { root: ROOT, runOpenshell, redact }); - const created: string[] = []; - for (const tokenDef of messaging.messagingTokenDefs) { - if (!normalizeCredentialValue(tokenDef.token)) continue; - const staged = onboardProviders.stageMessagingProvidersCreateMissingOnly( - [tokenDef], - runOpenshell, - { gatewayName: GATEWAY_NAME }, - ); - if (staged.created.length === 0) continue; - setStagedCredentialProviderReceipt(tokenDef.name, true); - recordMigratedLegacyMessagingCredentials([tokenDef], staged.created); - created.push(...staged.created); - } - return created; -} +// 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, @@ -4277,8 +4211,8 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { const recordedSandboxName = session?.steps?.sandbox?.status === "complete" ? session?.sandboxName || null : null; - const checkpointedSandboxName = - resume && session?.sandboxPromptProgress?.sandboxName === true ? session.sandboxName : 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; @@ -4411,11 +4345,8 @@ 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. + // #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)) { 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 c73e15ade74..211b8a773d4 100644 --- a/src/lib/onboard/gateway-provider-metadata.test.ts +++ b/src/lib/onboard/gateway-provider-metadata.test.ts @@ -74,6 +74,9 @@ describe("gateway provider metadata", () => { expected, ), ).toBe(false); + expect( + matchesGatewayCredentialOnlyProviderBinding({ ...metadata, credentialKeys: [] }, expected), + ).toBe(false); expect( matchesGatewayCredentialOnlyProviderBinding( { ...metadata, credentialKeys: ["TELEGRAM_BOT_TOKEN", "OTHER_TOKEN"] }, diff --git a/src/lib/onboard/lifecycle-contracts.md b/src/lib/onboard/lifecycle-contracts.md index 2cbf88ac144..5af832d553c 100644 --- a/src/lib/onboard/lifecycle-contracts.md +++ b/src/lib/onboard/lifecycle-contracts.md @@ -48,17 +48,19 @@ Every nonterminal state has one production owner or an explicit internal designa | `finalizing`, `post_verify` | `machine/handlers/finalization.ts` | | `complete`, `failed` | Terminal; no handler | -FSM transitions remain step-granular. 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 messaging is checkpointed, validated credentials may be registered in OpenShell with secret-free provider-name receipts before the resource prompt. The machine still cannot resume inside gateway startup, an individual credential upsert, 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/inference-provider effects -> checkpoint name/web/messaging prompts* - -> create missing credential providers + save name receipts* -> checkpoint resource prompt* + -> 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* @@ -96,9 +98,9 @@ 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. Validated web-search and messaging providers can be created after their prompt 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, with 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 created 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. | +| **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. Completed sandbox name, web search, messaging, and resource choices have 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 session recorded creating 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). | +| **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. | @@ -120,7 +122,7 @@ The schema and sanitation authority is `Session` plus `normalizeSession`/`filter | 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`, `sandboxPromptProgress`, `stagedCredentialProviders` | Step-mutation helpers and `OnboardRuntime` own whole-step progress; the sandbox handler owns prompt-group completion markers. `stagedCredentialProviders` contains only names created before sandbox setup so 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. | +| 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. | diff --git a/src/lib/onboard/machine/handlers/provider-inference.ts b/src/lib/onboard/machine/handlers/provider-inference.ts index 58b7ee55ebc..44a0491368c 100644 --- a/src/lib/onboard/machine/handlers/provider-inference.ts +++ b/src/lib/onboard/machine/handlers/provider-inference.ts @@ -439,7 +439,9 @@ 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 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 718f695ac24..7bb29c4376c 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 @@ -253,6 +253,9 @@ describe("sandbox create intent machine boundary", () => { 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, ); diff --git a/src/lib/onboard/machine/handlers/sandbox-messaging.test.ts b/src/lib/onboard/machine/handlers/sandbox-messaging.test.ts index b7d4046c3c6..4ed783da655 100644 --- a/src/lib/onboard/machine/handlers/sandbox-messaging.test.ts +++ b/src/lib/onboard/machine/handlers/sandbox-messaging.test.ts @@ -266,7 +266,7 @@ describe("reconcileSandboxMessaging completed checkpoint credentials", () => { "alpha", { selectionCompleted: true }, ); - expect(deps.writePlanToEnv).not.toHaveBeenCalled(); + expect(deps.writePlanToEnv).toHaveBeenCalledWith(persistedPlan); expect(result).toEqual({ plan: validatedPlan, selectedChannels: ["telegram"] }); }); @@ -296,7 +296,7 @@ describe("reconcileSandboxMessaging completed checkpoint credentials", () => { "alpha", { selectionCompleted: true }, ); - expect(deps.writePlanToEnv).not.toHaveBeenCalled(); + expect(deps.writePlanToEnv).toHaveBeenCalledWith(persistedPlan); expect(persistedPlan.credentialBindings[0]?.credentialHash).toBe(hashCredential(previousToken)); }); diff --git a/src/lib/onboard/machine/handlers/sandbox-messaging.ts b/src/lib/onboard/machine/handlers/sandbox-messaging.ts index 17c2b8bcff1..e973e9c5b6a 100644 --- a/src/lib/onboard/machine/handlers/sandbox-messaging.ts +++ b/src/lib/onboard/machine/handlers/sandbox-messaging.ts @@ -311,6 +311,7 @@ async function selectionFromCompletedMessagingCheckpoint( ); }); if (credentialNeedsValidation) { + options.deps.writePlanToEnv(durablePlan); return selectionFromMessagingSetup(selectedChannels, options, true); } @@ -336,7 +337,12 @@ export async function reconcileSandboxMessaging( options.sandboxName, ); const envPlan = options.deps.readMessagingPlanFromEnv(); - if (options.resume && options.session?.sandboxPromptProgress?.messaging === true) { + 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); 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 69db593911a..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 @@ -52,6 +52,10 @@ describe("sandbox registration route transaction", () => { 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 }; 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 5f44c1a1311..d74d038dcd7 100644 --- a/src/lib/onboard/machine/handlers/sandbox.test.ts +++ b/src/lib/onboard/machine/handlers/sandbox.test.ts @@ -783,6 +783,7 @@ describe("handleSandboxState", () => { toolDisclosure: "progressive", observabilityEnabled: false, extraProviders: [], + reuseRegisteredCredentials: true, }, ); expect(result.webSearchConfigChanged).toBe(true); @@ -903,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 a0a32d83b1c..65f0e5da7a4 100644 --- a/src/lib/onboard/machine/handlers/sandbox.ts +++ b/src/lib/onboard/machine/handlers/sandbox.ts @@ -26,7 +26,6 @@ import type { import type { SandboxEntry } from "../../../state/registry"; import { getSandboxEntryInference } from "../../../state/registry-entry-view"; import { toolDisclosureOrDefault } from "../../../tool-disclosure"; -import { HERMES_TAVILY_PROVIDER_PROFILE_ID } from "../../brave-provider-profile"; import { withDashboardPortReservationLock as withHostDashboardPortReservationLock } from "../../dashboard-port"; import { type DashboardRuntimeAgent, shouldManageDashboardForAgent } from "../../dashboard-runtime"; import { @@ -199,6 +198,7 @@ export interface SandboxStateOptions< extraProviders: readonly string[]; staleExtraProviders: readonly string[]; policyTier?: string | null; + reuseRegisteredCredentials?: boolean; }): Promise; createSandbox( gpu: Gpu, @@ -364,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) @@ -653,12 +658,8 @@ class SandboxStateFlow< const label = webSearchLabelFor(provider); const credentialEnv = webSearchEnvFor(provider); const localCredential = this.options.env[credentialEnv]?.trim(); - const providerType = - provider === "tavily" && - (this.options.agent as { name?: string } | null)?.name?.trim().toLowerCase() === "hermes" - ? HERMES_TAVILY_PROVIDER_PROFILE_ID - : provider; if ( + this.resumesSandboxPrompts && this.options.resume && state.sandboxName && !localCredential && @@ -667,7 +668,7 @@ class SandboxStateFlow< ) && this.deps.providerMatchesGatewayCredential( `${state.sandboxName}-${provider}-search`, - providerType, + provider, credentialEnv, ) ) { @@ -688,7 +689,9 @@ class SandboxStateFlow< this.options.env[WEB_SEARCH_PROVIDER_ENV], ).specified; const completedSelection = - this.options.resume && state.session?.sandboxPromptProgress?.webSearch === true; + this.resumesSandboxPrompts && + this.options.resume && + state.session?.sandboxPromptProgress?.webSearch === true; if (!this.options.authoritativeResumeConfig && !explicitlyConfigured && !completedSelection) { return this.deps.configureWebSearch( null, @@ -706,6 +709,7 @@ class SandboxStateFlow< 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; @@ -718,6 +722,7 @@ class SandboxStateFlow< state: SandboxStepState, sandboxName: string, ): SandboxStepState { + if (!this.resumesSandboxPrompts) return { ...state, sandboxName }; let messagingInvalidated = false; const session = this.deps.updateSession((current) => { const recordedNameChanged = @@ -741,6 +746,9 @@ class SandboxStateFlow< 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; @@ -753,11 +761,33 @@ class SandboxStateFlow< }; } + 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) @@ -772,6 +802,7 @@ class SandboxStateFlow< } 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; @@ -789,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, @@ -799,6 +831,7 @@ class SandboxStateFlow< hermesToolGateways, extraProviders, staleExtraProviders, + ...(reuseRegisteredCredentials ? { reuseRegisteredCredentials: true } : {}), ...(this.options.authoritativePolicyTier !== undefined ? { policyTier: this.options.authoritativePolicyTier } : {}), @@ -808,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 } @@ -969,6 +1003,11 @@ class SandboxStateFlow< if (!nextState.sandboxName) { nextState = this.checkpointSandboxName(nextState, requestedSandboxName); } + await this.registerCompletedCredentialProviders( + requestedSandboxName, + [], + nextState.webSearchConfig, + ); const messaging = await reconcileSandboxMessaging({ resume: this.options.resume, session: nextState.session, @@ -977,19 +1016,11 @@ class SandboxStateFlow< deps: this.deps, }); nextState = this.checkpointMessaging(nextState, messaging); - const stagedProviders = await this.deps.withGatewayRouteMutationLock( - this.options.gatewayName, - () => - this.deps.stageSandboxCredentialProviders({ - sandboxName: requestedSandboxName, - enabledChannels: nextState.selectedMessagingChannels, - webSearchConfig: nextState.webSearchConfig, - agent: this.options.agent, - }), + await this.registerCompletedCredentialProviders( + requestedSandboxName, + nextState.selectedMessagingChannels, + null, ); - if (stagedProviders.length > 0) { - this.deps.note(" ✓ Registered selected credentials with OpenShell for resume."); - } return this.createAndRecordSandbox(nextState, requestedSandboxName, messaging.plan, decision); } diff --git a/src/lib/onboard/messaging-prep.test.ts b/src/lib/onboard/messaging-prep.test.ts index 4c97c37c95b..968f7291e84 100644 --- a/src/lib/onboard/messaging-prep.test.ts +++ b/src/lib/onboard/messaging-prep.test.ts @@ -36,6 +36,7 @@ function createInput( if (envKey === "WECHAT_BOT_TOKEN") return "wechat"; return null; }, + providerExistsInGateway: () => false, providerMatchesGatewayCredential: () => false, ...overrides, }; @@ -44,7 +45,7 @@ function createInput( describe("prepareCreateSandboxMessaging", () => { it("filters token definitions by selected and disabled channels and reuses attached missing-token providers", () => { const registerExtraPlaceholderProviders = vi.fn(() => ["SLACK_BOT_TOKEN_AGENT_A"]); - const providerMatchesGatewayCredential = vi.fn((name: string) => name === "demo-slack-bridge"); + const providerExistsInGateway = vi.fn((name: string) => name === "demo-slack-bridge"); const result = prepareCreateSandboxMessaging( createInput({ @@ -53,7 +54,7 @@ describe("prepareCreateSandboxMessaging", () => { getValidatedMessagingTokenByEnvKey: (_channels, envKey) => envKey === "SLACK_APP_TOKEN" ? "xapp-valid" : null, registerExtraPlaceholderProviders, - providerMatchesGatewayCredential, + providerExistsInGateway, }), ); @@ -66,11 +67,7 @@ describe("prepareCreateSandboxMessaging", () => { expect(result.hasMessagingTokens).toBe(true); expect(result.reusableMessagingProviders).toEqual(["demo-slack-bridge"]); expect(result.reusableMessagingChannels).toEqual(["slack"]); - expect(providerMatchesGatewayCredential).toHaveBeenCalledWith( - "demo-slack-bridge", - "generic", - "SLACK_BOT_TOKEN", - ); + expect(providerExistsInGateway).toHaveBeenCalledWith("demo-slack-bridge"); expect(registerExtraPlaceholderProviders).toHaveBeenCalledWith( "demo", result.messagingTokenDefs, @@ -105,6 +102,7 @@ describe("prepareCreateSandboxMessaging", () => { const result = prepareCreateSandboxMessaging( createInput({ webSearchConfig: { fetchEnabled: true }, + requireExactProviderBinding: true, providerMatchesGatewayCredential, }), ); diff --git a/src/lib/onboard/messaging-prep.ts b/src/lib/onboard/messaging-prep.ts index 86d446bcaa7..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[]; @@ -35,6 +36,7 @@ export interface CreateSandboxMessagingPrepInput { messagingTokenDefs: MessagingTokenDef[], ): string[]; getMessagingChannelForEnvKey(envKey: string): string | null; + providerExistsInGateway(name: string): boolean; providerMatchesGatewayCredential(name: string, type: string, credentialEnv: string): boolean; } @@ -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( @@ -90,6 +95,7 @@ export function prepareCreateSandboxMessaging( null : null; const reusableWebSearchProvider = + requiresExactOpenClawProviderBinding && webSearchEnabled && !webSearchApiKey && input.providerMatchesGatewayCredential( @@ -137,7 +143,10 @@ export function prepareCreateSandboxMessaging( if (token) continue; const channel = input.getMessagingChannelForEnvKey(envKey); if (!channel || !input.enabledChannels.includes(channel)) continue; - if (!input.providerMatchesGatewayCredential(name, "generic", envKey)) 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/providers.test.ts b/src/lib/onboard/providers.test.ts index de463df5590..acf689cfd13 100644 --- a/src/lib/onboard/providers.test.ts +++ b/src/lib/onboard/providers.test.ts @@ -4,7 +4,7 @@ import { describe, expect, it } from "vitest"; type RunResult = { status: number; stdout?: string; stderr?: string }; -type RunOptions = { env?: Record; suppressOutput?: boolean }; +type RunOptions = { env?: Record }; type RunOpenshell = (command: string[], opts?: RunOptions) => RunResult; const { @@ -18,7 +18,6 @@ const { getRequestedProviderHint, isProviderKeyCredentialCandidate, providerExistsInGateway, - stageMessagingProvidersCreateMissingOnly, stageHostedInferenceSourceSecretEnv, upsertProvider, upsertMessagingProviders, @@ -52,16 +51,6 @@ const { ) => string | null; isProviderKeyCredentialCandidate: (value: string | null | undefined) => boolean; providerExistsInGateway: (name: string, runOpenshell: RunOpenshell) => boolean; - stageMessagingProvidersCreateMissingOnly: ( - tokenDefs: Array<{ - name: string; - envKey: string; - token: string | null; - providerType?: string; - }>, - runOpenshell: RunOpenshell, - options?: { gatewayName?: string | null }, - ) => { created: string[]; reused: string[]; skipped: string[] }; stageHostedInferenceSourceSecretEnv: () => boolean; upsertProvider: ( name: string, @@ -246,161 +235,6 @@ describe("onboard provider helpers", () => { expect(providerExistsInGateway("missing-bridge", () => ({ status: 1 }))).toBe(false); }); - it("reuses an exact credential-only provider without mutating it", () => { - const commands: string[] = []; - const result = stageMessagingProvidersCreateMissingOnly( - [ - { - name: "tm-telegram-bridge", - envKey: "TELEGRAM_BOT_TOKEN", - token: "123456:test-token", - }, - ], - (command) => { - commands.push(command.join(" ")); - return { - status: 0, - stdout: - "Name: tm-telegram-bridge\nType: generic\nCredential keys: TELEGRAM_BOT_TOKEN\nConfig keys: \n", - }; - }, - { gatewayName: "nemoclaw" }, - ); - - expect(result).toEqual({ - created: [], - reused: ["tm-telegram-bridge"], - skipped: [], - }); - expect(commands).toEqual(["provider get -g nemoclaw tm-telegram-bridge"]); - }); - - it.each([ - ["the provider type differs", "brave", "TELEGRAM_BOT_TOKEN", ""], - ["the credential key differs", "generic", "OTHER_TOKEN", ""], - ["the provider has configuration", "generic", "TELEGRAM_BOT_TOKEN", "BASE_URL"], - ])("skips an existing provider when %s", (_label, type, credentialKey, configKey) => { - const commands: string[] = []; - const result = stageMessagingProvidersCreateMissingOnly( - [ - { - name: "tm-telegram-bridge", - envKey: "TELEGRAM_BOT_TOKEN", - token: "123456:test-token", - }, - ], - (command) => { - commands.push(command.join(" ")); - return { - status: 0, - stdout: `Name: tm-telegram-bridge\nType: ${type}\nCredential keys: ${credentialKey}\nConfig keys: ${configKey}\n`, - }; - }, - { gatewayName: "nemoclaw" }, - ); - - expect(result).toEqual({ - created: [], - reused: [], - skipped: ["tm-telegram-bridge"], - }); - expect(commands).toEqual(["provider get -g nemoclaw tm-telegram-bridge"]); - }); - - it("creates an exactly absent provider with its secret only in the command environment", () => { - const calls: Array<{ command: string[]; options?: RunOptions }> = []; - const token = "123456:staged-secret-token"; - const result = stageMessagingProvidersCreateMissingOnly( - [ - { - name: "tm-telegram-bridge", - envKey: "TELEGRAM_BOT_TOKEN", - token, - }, - ], - (command, options) => { - calls.push({ command, options }); - if (command[1] === "get") { - return { - status: 1, - stderr: "Error: provider 'tm-telegram-bridge' not found", - }; - } - return { status: 0 }; - }, - { gatewayName: "nemoclaw" }, - ); - - expect(result).toEqual({ - created: ["tm-telegram-bridge"], - reused: [], - skipped: [], - }); - expect(calls.map(({ command }) => command.join(" "))).toEqual([ - "provider get -g nemoclaw tm-telegram-bridge", - "provider create -g nemoclaw --name tm-telegram-bridge --type generic --credential TELEGRAM_BOT_TOKEN", - ]); - expect(calls[1]?.command).not.toContain(token); - expect(calls[1]?.options?.env).toEqual({ TELEGRAM_BOT_TOKEN: token }); - expect(calls[1]?.options?.suppressOutput).toBe(true); - }); - - it("skips an indeterminate absence probe instead of attempting a create", () => { - const commands: string[] = []; - const result = stageMessagingProvidersCreateMissingOnly( - [ - { - name: "tm-telegram-bridge", - envKey: "TELEGRAM_BOT_TOKEN", - token: "123456:test-token", - }, - ], - (command) => { - commands.push(command.join(" ")); - return { status: 1, stderr: "gateway unavailable" }; - }, - { gatewayName: "nemoclaw" }, - ); - - expect(result).toEqual({ - created: [], - reused: [], - skipped: ["tm-telegram-bridge"], - }); - expect(commands).toEqual(["provider get -g nemoclaw tm-telegram-bridge"]); - }); - - it("throws on create failure without attempting update, delete, or secret-bearing arguments", () => { - const commands: string[] = []; - const token = "123456:staged-secret-token"; - - expect(() => - stageMessagingProvidersCreateMissingOnly( - [ - { - name: "tm-telegram-bridge", - envKey: "TELEGRAM_BOT_TOKEN", - token, - }, - ], - (command) => { - commands.push(command.join(" ")); - if (command[1] === "get") { - return { - status: 1, - stderr: "Error: provider 'tm-telegram-bridge' not found", - }; - } - return { status: 1, stderr: `gateway rejected ${token}` }; - }, - { gatewayName: "nemoclaw" }, - ), - ).toThrow("Failed to stage messaging provider 'tm-telegram-bridge': gateway rejected"); - - expect(commands.every((command) => !command.includes(token))).toBe(true); - expect(commands.some((command) => /provider (update|delete)/.test(command))).toBe(false); - }); - it("creates a new provider and returns ok on success", () => { const commands: string[] = []; const result = upsertProvider( diff --git a/src/lib/onboard/providers.ts b/src/lib/onboard/providers.ts index fc5d01b9ee3..d33aac3d9e2 100644 --- a/src/lib/onboard/providers.ts +++ b/src/lib/onboard/providers.ts @@ -16,12 +16,7 @@ const { const openrouter = require("../inference/openrouter"); const { isSafeModelId } = require("../validation"); const { compactText } = require("../core/url-utils"); -const { - matchesGatewayCredentialOnlyProviderBinding, - parseGatewayProviderMetadata, - readGatewayProviderMetadata, -} = require("./gateway-provider-metadata"); -const { reportsExactProviderNotFound } = require("./extra-provider-diagnostic-parser"); +const { readGatewayProviderMetadata } = require("./gateway-provider-metadata"); // ── Constants ──────────────────────────────────────────────────── @@ -516,123 +511,6 @@ function upsertMessagingProviders(tokenDefs, _runOpenshell, options = {}) { return upserted; } -const STAGED_PROVIDER_DIAGNOSTIC_LIMIT = 16 * 1024; -const SAFE_STAGED_PROVIDER_NAME = /^[A-Za-z0-9._:-]{1,128}$/; -const SAFE_STAGED_PROVIDER_TYPE = /^[A-Za-z0-9._:-]{1,64}$/; -const SAFE_STAGED_CREDENTIAL_KEY = /^[A-Z_][A-Z0-9_]{0,127}$/; - -function providerCommandOutput(result) { - const text = (value) => { - if (Buffer.isBuffer(value)) return value.toString("utf8"); - return typeof value === "string" ? value : ""; - }; - const streams = [text(result.stderr), text(result.stdout)].filter(Boolean); - return streams.length > 0 ? streams.join("\n") : text(result.output); -} - -function inspectStagedProvider(name, gatewayName, _runOpenshell) { - const args = ["provider", "get"]; - if (gatewayName) args.push("-g", gatewayName); - args.push(name); - const result = _runOpenshell(args, { - ignoreError: true, - maxBuffer: STAGED_PROVIDER_DIAGNOSTIC_LIMIT, - suppressOutput: true, - stdio: ["ignore", "pipe", "pipe"], - }); - const output = providerCommandOutput(result); - if (result.status === 0) { - const metadata = parseGatewayProviderMetadata(output); - return { kind: "existing", metadata: metadata?.name === name ? metadata : null }; - } - if ( - result.status === 1 && - Buffer.byteLength(output) < STAGED_PROVIDER_DIAGNOSTIC_LIMIT && - reportsExactProviderNotFound(output, name, STAGED_PROVIDER_DIAGNOSTIC_LIMIT) - ) { - return { kind: "absent", metadata: null }; - } - return { kind: "indeterminate", metadata: null }; -} - -function stagedProviderCreateArgs(name, type, envKey, gatewayName) { - const args = buildProviderArgs("create", name, type, envKey, null); - if (gatewayName) args.splice(2, 0, "-g", gatewayName); - return args; -} - -/** - * Stage validated messaging credentials without mutating an existing provider. - * - * Existing providers are reported as reusable only when their complete - * non-secret binding matches. This does not prove that an existing provider - * contains the supplied token; callers must retain separate ownership proof - * before trusting one for credential-free resume. Mismatched, malformed, and - * indeterminate probes are left untouched. - * An absent provider is created with its secret available only in the command - * environment; this path never issues provider update/delete/replace commands. - * - * @param {Array<{name: string, envKey: string, token: string|null, providerType?: string}>} tokenDefs - * @param {Function} _runOpenshell - Injected runOpenshell from onboard.ts. - * @param {{gatewayName?: string|null}} options - Exact gateway scope when available. - * @returns {{created: string[], reused: string[], skipped: string[]}} - */ -function stageMessagingProvidersCreateMissingOnly(tokenDefs, _runOpenshell, options = {}) { - const created = []; - const reused = []; - const skipped = []; - const gatewayName = options.gatewayName || null; - - for (const { name, envKey, token, providerType } of tokenDefs) { - const credential = normalizeCredentialValue(token); - if (!credential) continue; - const type = providerType || "generic"; - if ( - !SAFE_STAGED_PROVIDER_NAME.test(name) || - !SAFE_STAGED_PROVIDER_TYPE.test(type) || - !SAFE_STAGED_CREDENTIAL_KEY.test(envKey) - ) { - skipped.push(name); - continue; - } - - const inspection = inspectStagedProvider(name, gatewayName, _runOpenshell); - if (inspection.kind === "existing") { - if ( - matchesGatewayCredentialOnlyProviderBinding(inspection.metadata, { - name, - type, - credentialKey: envKey, - }) - ) { - reused.push(name); - } else { - skipped.push(name); - } - continue; - } - if (inspection.kind !== "absent") { - skipped.push(name); - continue; - } - - const result = _runOpenshell(stagedProviderCreateArgs(name, type, envKey, gatewayName), { - ignoreError: true, - env: { [envKey]: credential }, - suppressOutput: true, - stdio: ["ignore", "pipe", "pipe"], - }); - if (result.status !== 0) { - const rawOutput = providerCommandOutput(result).replaceAll(credential, "[REDACTED]"); - const output = compactText(redact(rawOutput)) || `Provider create exited unsuccessfully.`; - throw new Error(`Failed to stage messaging provider '${name}': ${output}`); - } - created.push(name); - } - - return { created, reused, skipped }; -} - module.exports = { BUILD_ENDPOINT_URL, OPENAI_ENDPOINT_URL, @@ -662,7 +540,6 @@ module.exports = { upsertProvider, providerExistsInGateway, readGatewayProviderMetadata, - stageMessagingProvidersCreateMissingOnly, upsertMessagingProviders, getSandboxInferenceConfig, }; diff --git a/src/lib/onboard/sandbox-agent.test.ts b/src/lib/onboard/sandbox-agent.test.ts index 85a3f6e35b8..211e57538bd 100644 --- a/src/lib/onboard/sandbox-agent.test.ts +++ b/src/lib/onboard/sandbox-agent.test.ts @@ -18,6 +18,25 @@ describe("sandbox name prompt", () => { }); await expect(promptValidatedSandboxName()).resolves.toBe("tm"); - expect(checkpointSandboxName).toHaveBeenCalledWith("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 c9e01023f63..98f6e50011b 100644 --- a/src/lib/onboard/sandbox-agent.ts +++ b/src/lib/onboard/sandbox-agent.ts @@ -144,7 +144,7 @@ export interface PromptSandboxNameDeps { promptOrDefault(question: string, envVar: string, defaultValue: string): Promise; cliDisplayName(): string; isNonInteractive(): boolean; - checkpointSandboxName(sandboxName: string): void; + checkpointSandboxName(sandboxName: string, agent: AgentDefinition | null): void; exit(code: number): never; } @@ -160,43 +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; - } - deps.checkpointSandboxName(validatedSandboxName); - 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 d298da465ea..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,10 +57,10 @@ export function createSandboxCreateIntentResolver< async function prepareMessagingCapabilities( input: Pick< CompleteSandboxCreateIntentInput, - "sandboxName" | "enabledChannels" | "webSearchConfig" | "agent" + "sandboxName" | "enabledChannels" | "webSearchConfig" | "agent" | "reuseRegisteredCredentials" >, expectedIntent?: SandboxCreateIntent, - skipPlanConflictCheck = false, + credentialRegistration = false, ) { const preflightDeps = expectedIntent ? { @@ -66,8 +68,12 @@ export function createSandboxCreateIntentResolver< readMessagingPlanFromEnv: () => null, resolveDisabledChannels: () => [...expectedIntent.disabledChannelNames], } - : skipPlanConflictCheck - ? { ...deps.messagingPreflightDeps, readMessagingPlanFromEnv: () => null } + : credentialRegistration + ? { + ...deps.messagingPreflightDeps, + readMessagingPlanFromEnv: () => null, + registerExtraPlaceholderProviders: () => [], + } : deps.messagingPreflightDeps; const result = await prepareSandboxMessagingPreflight( { @@ -75,6 +81,8 @@ export function createSandboxCreateIntentResolver< 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, }, diff --git a/src/lib/onboard/sandbox-messaging-preflight.test.ts b/src/lib/onboard/sandbox-messaging-preflight.test.ts index b14876d26c8..71a6fcaa141 100644 --- a/src/lib/onboard/sandbox-messaging-preflight.test.ts +++ b/src/lib/onboard/sandbox-messaging-preflight.test.ts @@ -110,6 +110,7 @@ function createDeps( registry: { listSandboxes: vi.fn(() => ({ sandboxes: [] })), }, + providerExistsInGateway: vi.fn(() => false), providerMatchesGatewayCredential: vi.fn(() => false), isNonInteractive: vi.fn(() => false), promptYesNoOrDefault: vi.fn(async () => true), diff --git a/src/lib/onboard/sandbox-messaging-preflight.ts b/src/lib/onboard/sandbox-messaging-preflight.ts index 524413a4bfd..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; @@ -28,6 +29,7 @@ export interface SandboxMessagingPreflightDeps { resolveDisabledChannels(sandboxName: string): string[]; gatewayName(): string; registry: MessagingConflictGuardDeps["registry"]; + providerExistsInGateway(name: string): boolean; providerMatchesGatewayCredential(name: string, type: string, credentialEnv: string): boolean; isNonInteractive(): boolean; promptYesNoOrDefault( @@ -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, @@ -80,6 +83,7 @@ export async function prepareSandboxMessagingPreflight( normalizeCredentialValue: deps.normalizeCredentialValue, registerExtraPlaceholderProviders: deps.registerExtraPlaceholderProviders, getMessagingChannelForEnvKey: deps.getMessagingChannelForEnvKey, + providerExistsInGateway: deps.providerExistsInGateway, providerMatchesGatewayCredential: deps.providerMatchesGatewayCredential, }); diff --git a/src/lib/onboard/session-bootstrap.ts b/src/lib/onboard/session-bootstrap.ts index 6c8ec4387cf..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,7 +147,9 @@ function assertRecoverableResumeSandboxName( deps: OnboardSessionBootstrapDeps, ): void { const sandboxStepCompleted = session?.steps?.sandbox?.status === "complete"; - const sandboxNameCheckpointed = session?.sandboxPromptProgress?.sandboxName === true; + const sandboxNameCheckpointed = + (!session?.agent || session.agent === "openclaw") && + session?.sandboxPromptProgress?.sandboxName === true; const recoveredSandboxName = input.requestedSandboxName || (sandboxStepCompleted || sandboxNameCheckpointed ? session?.sandboxName || null : null); 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 index bd84e019ac7..51acdd0f191 100644 --- a/src/lib/state/onboard-session-sandbox-prompts.test.ts +++ b/src/lib/state/onboard-session-sandbox-prompts.test.ts @@ -6,7 +6,6 @@ import os from "node:os"; import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -const originalHome = process.env.HOME; type OnboardSessionModule = typeof import("./onboard-session"); type LoadedSession = NonNullable>; type MessagingPlan = NonNullable; @@ -15,8 +14,7 @@ let tmpDir: string; function requireLoadedSession(loaded: LoadedSession | null): LoadedSession { expect(loaded).not.toBeNull(); - if (!loaded) throw new Error("Expected onboard session to be present"); - return loaded; + return loaded as LoadedSession; } function makeTelegramPlan(sandboxName: string): MessagingPlan { @@ -50,7 +48,7 @@ function makeTelegramPlan(sandboxName: string): MessagingPlan { beforeEach(async () => { tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-prompt-session-")); - process.env.HOME = tmpDir; + vi.stubEnv("HOME", tmpDir); vi.resetModules(); session = await import("./onboard-session"); session.clearSession(); @@ -59,8 +57,7 @@ beforeEach(async () => { afterEach(() => { session.clearSession(); fs.rmSync(tmpDir, { recursive: true, force: true }); - if (originalHome === undefined) delete process.env.HOME; - else process.env.HOME = originalHome; + vi.unstubAllEnvs(); }); describe("onboard session sandbox prompt checkpoints", () => { @@ -184,4 +181,20 @@ describe("onboard session sandbox prompt checkpoints", () => { 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 904895b03ef..aded1da0065 100644 --- a/src/lib/state/onboard-session.ts +++ b/src/lib/state/onboard-session.ts @@ -173,7 +173,7 @@ export interface Session { hermesToolGateways: string[] | null; policyPresets: string[] | null; messagingPlan: SandboxMessagingPlan | null; - /** Non-secret names of credential providers created before sandbox setup completed. */ + /** 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 @@ -378,8 +378,11 @@ function isValidNullableWebSearchChoice(value: unknown): boolean { return value === null || parseWebSearchConfig(value as SessionJsonValue | undefined) !== null; } -function isValidNullableMessagingChoice(value: unknown): boolean { - return value === null || parseSandboxMessagingPlan(value) !== null; +function isValidNullableMessagingChoice(value: unknown, sandboxName: unknown): boolean { + return ( + value === null || + (typeof sandboxName === "string" && parseSandboxMessagingPlan(value, { sandboxName }) !== null) + ); } function isValidNullableResourceChoice(value: unknown): boolean { @@ -403,7 +406,7 @@ function parseSandboxPromptProgress( messaging: progress.messaging === true && hasOwn(choices, "messagingPlan") && - isValidNullableMessagingChoice(choices.messagingPlan), + isValidNullableMessagingChoice(choices.messagingPlan, choices.sandboxName), resourceProfile: progress.resourceProfile === true && hasOwn(choices, "resourceProfile") && diff --git a/test/onboard-inference-reconciliation.test.ts b/test/onboard-inference-reconciliation.test.ts index 324e28c0849..ce26d31d189 100644 --- a/test/onboard-inference-reconciliation.test.ts +++ b/test/onboard-inference-reconciliation.test.ts @@ -153,7 +153,7 @@ describe("onboard helpers", () => { expect(updateSandbox).toHaveBeenCalledWith("test-box", { model: "anthropic.claude-3-5-sonnet-20240620-v1:0", provider: "compatible-anthropic-endpoint", endpointUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", credentialEnv: "COMPATIBLE_ANTHROPIC_API_KEY", preferredInferenceApi: null, gatewayName: "nemoclaw" }); }); }); - it("resolves a missing name but reuses a completed name before resume inference (#6743)", { + it("resolves a sandbox name before reconciling Hermes Provider on resume", { timeout: 60_000, }, () => { const repoRoot = path.join(import.meta.dirname, ".."); @@ -204,7 +204,6 @@ const prompts = []; const registryUpdates = []; const done = new Error("INFERENCE_STEP_DONE"); let inferenceSessionSnapshot = null; -const useCheckpointedName = process.argv[2] === "checkpointed"; delete process.env.NEMOCLAW_NON_INTERACTIVE; delete process.env.NEMOCLAW_SANDBOX_NAME; @@ -288,7 +287,7 @@ onboardSession.saveSession( onboardSession.createSession({ mode: "interactive", agent: "hermes", - sandboxName: useCheckpointedName ? "hermes-resume" : null, + sandboxName: null, provider: "hermes-provider", model: "moonshotai/kimi-k2.6", endpointUrl: "https://8.8.8.8/v1", @@ -296,12 +295,6 @@ onboardSession.saveSession( hermesAuthMethod: "api_key", hermesToolGateways: [], policyPresets: ["nous-web"], - sandboxPromptProgress: { - sandboxName: useCheckpointedName, - webSearch: false, - messaging: false, - resourceProfile: false, - }, metadata: { gatewayName: "nemoclaw", fromDockerfile: null }, steps: { preflight: complete(), @@ -354,14 +347,11 @@ const { onboard } = require(${onboardPath}); delete env.NEMOCLAW_SANDBOX_NAME; delete env.NOUS_API_KEY; - const runScenario = (scenario: "missing" | "checkpointed") => - spawnSync(process.execPath, [scriptPath, scenario], { - cwd: repoRoot, - encoding: "utf-8", - env, - }); - - const result = runScenario("missing"); + const result = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + encoding: "utf-8", + env, + }); assert.equal(result.status, 0, result.stderr); assert.doesNotMatch( @@ -388,8 +378,8 @@ const { onboard } = require(${onboardPath}); assert.ok(!payload.commands.some((entry) => /provider (create|update)/.test(entry.command))); assert.equal( payload.inferenceSessionSandboxName, - "hermes-resume", - "resume inference should checkpoint the validated sandbox name before reconciliation", + null, + "resume inference must not persist sandboxName before sandbox creation", ); assert.ok( payload.registryUpdates.some( @@ -400,23 +390,6 @@ const { onboard } = require(${onboardPath}); ), "Hermes setup should reconcile inference against the resolved sandbox name", ); - - const checkpointedResult = runScenario("checkpointed"); - assert.equal(checkpointedResult.status, 0, checkpointedResult.stderr); - assert.match( - checkpointedResult.stdout, - /\[resume\] Reusing sandbox name: hermes-resume\./, - "resume should report the completed sandbox-name choice under inference configuration", - ); - const checkpointedPayload = parseStdoutJson<{ - prompts: string[]; - inferenceSessionSandboxName: string | null; - }>(checkpointedResult.stdout); - assert.ok( - !checkpointedPayload.prompts.some((question) => question.includes("Sandbox name")), - "resume must not repeat a completed sandbox-name prompt", - ); - assert.equal(checkpointedPayload.inferenceSessionSandboxName, "hermes-resume"); }); it("reconciles a registered Hermes Provider when a fresh shell Nous key is selected", async () => { From deddbe193f806d69807cfbaf5effd2129ffc4926 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 15 Jul 2026 19:18:37 +0700 Subject: [PATCH 4/5] test(onboard): cover messaging credential staging Signed-off-by: San Dang --- .../sandbox-create-intent-boundary.test.ts | 31 +++++++++++++++++-- 1 file changed, 28 insertions(+), 3 deletions(-) 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 7bb29c4376c..8f0ee2748cd 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 @@ -180,7 +180,7 @@ describe("sandbox create intent machine boundary", () => { const braveCredential = "brave-secret-value"; const telegramCredential = "telegram-secret-value"; const messagingPlan = withTelegramCredentialHash( - makeMinimalPlan("tm", "openclaw", ["telegram"], ["telegram"]), + makeMinimalPlan("tm", "openclaw", ["telegram"]), "a".repeat(64), ); const credentialEnv = { @@ -197,10 +197,13 @@ describe("sandbox create intent machine boundary", () => { return durableSession; }); const configureWebSearch = vi.fn(async () => braveConfig); - const setupMessagingChannels = vi.fn(async () => []); + 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-brave-search" && type === "brave" && credentialEnvName === "BRAVE_API_KEY") || + (name === "tm-telegram-bridge" && + type === "generic" && + credentialEnvName === "TELEGRAM_BOT_TOKEN"), ); const stageSandboxCredentialProviders = vi .fn<() => Promise>() @@ -208,6 +211,10 @@ describe("sandbox create intent machine boundary", () => { 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>() @@ -237,6 +244,7 @@ describe("sandbox create intent machine boundary", () => { sandboxName: "tm", webSearchConfig: braveConfig, messagingPlan, + stagedCredentialProviders: ["tm-brave-search", "tm-telegram-bridge"], resourceProfile: null, sandboxPromptProgress: { sandboxName: true, @@ -259,6 +267,18 @@ describe("sandbox create intent machine boundary", () => { 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({ @@ -277,6 +297,11 @@ describe("sandbox create intent machine boundary", () => { "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); From f23c8d8b752390cacf75cd39723507312a448801 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Wed, 15 Jul 2026 09:09:36 -0700 Subject: [PATCH 5/5] fix(onboard): checkpoint sandbox name before web search --- .../sandbox-create-intent-boundary.test.ts | 33 +++++++++++++++++++ src/lib/onboard/machine/handlers/sandbox.ts | 10 +++--- 2 files changed, 38 insertions(+), 5 deletions(-) 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 8f0ee2748cd..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 @@ -141,6 +141,39 @@ describe("sandbox create intent machine boundary", () => { 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", diff --git a/src/lib/onboard/machine/handlers/sandbox.ts b/src/lib/onboard/machine/handlers/sandbox.ts index 65f0e5da7a4..9f49313e08f 100644 --- a/src/lib/onboard/machine/handlers/sandbox.ts +++ b/src/lib/onboard/machine/handlers/sandbox.ts @@ -983,6 +983,11 @@ class SandboxStateFlow< 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 = nextState.webSearchConfigChanged || @@ -998,11 +1003,6 @@ class SandboxStateFlow< }, webSearchConfig, ); - const requestedSandboxName = - nextState.sandboxName ?? (await this.deps.promptValidatedSandboxName(this.options.agent)); - if (!nextState.sandboxName) { - nextState = this.checkpointSandboxName(nextState, requestedSandboxName); - } await this.registerCompletedCredentialProviders( requestedSandboxName, [],