diff --git a/.github/workflows/nightly-e2e.yaml b/.github/workflows/nightly-e2e.yaml index 5badfde8d8b..6356f4c2346 100644 --- a/.github/workflows/nightly-e2e.yaml +++ b/.github/workflows/nightly-e2e.yaml @@ -123,6 +123,7 @@ on: overlayfs-autofix-e2e, device-auth-health-e2e, launchable-smoke-e2e, gpu-e2e, gpu-double-onboard-e2e, channels-add-remove-e2e, channels-stop-start-e2e, brave-search-e2e, + duckduckgo-search-e2e, sessions-agents-cli-e2e required: false type: string @@ -599,6 +600,21 @@ jobs: nvidia_api_key: true github_token: true secrets: *nightly-e2e-default-secrets + duckduckgo-search-e2e: + if: >- + github.repository == 'NVIDIA/NemoClaw' && (github.event_name != 'workflow_dispatch' || + inputs.jobs == '' || + contains(format(',{0},', inputs.jobs), ',duckduckgo-search-e2e,')) + uses: ./.github/workflows/e2e-script.yaml + with: + ref: ${{ inputs.target_ref || github.ref }} + script: test/e2e/test-duckduckgo-search-e2e.sh + artifact_name: "install-log-duckduckgo-search" + artifact_path: "/tmp/nemoclaw-e2e-duckduckgo-search-onboard.log" + env_json: '{"NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE":"1","NEMOCLAW_NON_INTERACTIVE":"1","NEMOCLAW_EXPERIMENTAL":"1","NEMOCLAW_WEB_SEARCH_PROVIDER":"duckduckgo","NEMOCLAW_SANDBOX_NAME":"e2e-duckduckgo-search"}' + nvidia_api_key: true + github_token: true + secrets: *nightly-e2e-default-secrets kimi-inference-compat-e2e: if: >- github.repository == 'NVIDIA/NemoClaw' && @@ -1912,6 +1928,7 @@ jobs: channels-add-remove-e2e, channels-stop-start-e2e, brave-search-e2e, + duckduckgo-search-e2e, kimi-inference-compat-e2e, bedrock-runtime-compatible-anthropic-e2e, token-rotation-e2e, @@ -2020,6 +2037,7 @@ jobs: channels-add-remove-e2e, channels-stop-start-e2e, brave-search-e2e, + duckduckgo-search-e2e, kimi-inference-compat-e2e, bedrock-runtime-compatible-anthropic-e2e, token-rotation-e2e, @@ -2185,6 +2203,7 @@ jobs: channels-add-remove-e2e, channels-stop-start-e2e, brave-search-e2e, + duckduckgo-search-e2e, kimi-inference-compat-e2e, bedrock-runtime-compatible-anthropic-e2e, token-rotation-e2e, diff --git a/Dockerfile b/Dockerfile index 34d01f20b8b..9aecaa890fc 100644 --- a/Dockerfile +++ b/Dockerfile @@ -505,6 +505,10 @@ ARG NEMOCLAW_PROXY_PORT=3128 # The actual API key is injected at runtime via openshell:resolve:env, never # baked into the image. ARG NEMOCLAW_WEB_SEARCH_ENABLED=0 +# Non-secret flag: name of the web search provider when web search is enabled. +# Defaults to "brave"; "duckduckgo" is gated behind NEMOCLAW_EXPERIMENTAL=1 +# during onboard and is keyless (no API key is baked or injected). +ARG NEMOCLAW_WEB_SEARCH_PROVIDER=brave ARG NEMOCLAW_OPENCLAW_OTEL=0 ARG NEMOCLAW_OPENCLAW_OTEL_ENDPOINT=http://host.openshell.internal:4318 ARG NEMOCLAW_OPENCLAW_OTEL_SERVICE_NAME=openclaw-gateway @@ -538,6 +542,7 @@ ENV NEMOCLAW_MODEL=${NEMOCLAW_MODEL} \ NEMOCLAW_PROXY_HOST=${NEMOCLAW_PROXY_HOST} \ NEMOCLAW_PROXY_PORT=${NEMOCLAW_PROXY_PORT} \ NEMOCLAW_WEB_SEARCH_ENABLED=${NEMOCLAW_WEB_SEARCH_ENABLED} \ + NEMOCLAW_WEB_SEARCH_PROVIDER=${NEMOCLAW_WEB_SEARCH_PROVIDER} \ NEMOCLAW_OPENCLAW_OTEL=${NEMOCLAW_OPENCLAW_OTEL} \ NEMOCLAW_OPENCLAW_OTEL_ENDPOINT=${NEMOCLAW_OPENCLAW_OTEL_ENDPOINT} \ NEMOCLAW_OPENCLAW_OTEL_SERVICE_NAME=${NEMOCLAW_OPENCLAW_OTEL_SERVICE_NAME} \ diff --git a/docs/get-started/quickstart.mdx b/docs/get-started/quickstart.mdx index 694d368a22a..c76f5861490 100644 --- a/docs/get-started/quickstart.mdx +++ b/docs/get-started/quickstart.mdx @@ -297,8 +297,9 @@ Non-interactive runs (`NEMOCLAW_NON_INTERACTIVE=1`) print the summary for log cl ### Configure Web Search and Messaging After you confirm the summary, NemoClaw registers the selected provider with the OpenShell gateway and sets the `inference.local` route. -The wizard then asks whether to enable Brave Web Search. -If you enable it, enter a Brave Search API key when prompted. +The wizard then asks whether to enable Web Search. +If you accept, the wizard selects Brave Search by default and prompts for a Brave Search API key. +When `NEMOCLAW_EXPERIMENTAL=1` is set, the wizard also offers an unofficial, keyless DuckDuckGo backend; set `NEMOCLAW_WEB_SEARCH_PROVIDER=duckduckgo` to pre-select it and skip the provider prompt in both interactive and non-interactive runs. The wizard also offers messaging channels such as Telegram, Discord, Slack, WeChat, and WhatsApp. Press a channel number to toggle it, then press Enter to continue. @@ -312,7 +313,7 @@ Review [Messaging Channels](../manage-sandboxes/messaging-channels) before enabl After the sandbox image builds and OpenClaw starts inside the sandbox, NemoClaw asks which network policy tier to apply. Web search and messaging selections happen before this point so the sandbox image and the policy suggestions stay aligned. -The default **Balanced** tier includes common development presets such as npm, PyPI, Hugging Face, Homebrew, and Brave Search when the selected agent supports web search. +The default **Balanced** tier includes common development presets such as npm, PyPI, Hugging Face, Homebrew, and either Brave Search or DuckDuckGo (depending on the provider you picked) when the selected agent supports web search. Use the arrow keys or `j` and `k` to move, Space to select, and Enter to confirm. The preset selector lets you include more destinations, such as GitHub, Jira, Slack, Telegram, or local inference. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 25afe04477f..1c4c3b07a0c 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -234,6 +234,18 @@ BRAVE_API_KEY=... \ If Brave Search key validation fails in non-interactive mode, onboarding prints a warning, skips web search setup, and continues with the rest of the sandbox setup. After fixing the key, re-enable web search with `nemoclaw config web-search`. +To enable the experimental DuckDuckGo Web Search backend in non-interactive mode, set the experimental flag, the provider, and accept the third-party software notice (or pass `--yes-i-accept-third-party-software`): + +```bash +NEMOCLAW_EXPERIMENTAL=1 NEMOCLAW_WEB_SEARCH_PROVIDER=duckduckgo \ + NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE=1 \ + nemoclaw onboard --non-interactive +``` + +`NEMOCLAW_WEB_SEARCH_PROVIDER=duckduckgo` selects the DuckDuckGo backend, which has no API key requirement. +The DuckDuckGo backend is unofficial and rate-limited; do not depend on it for production workloads. +In interactive mode, the wizard prompts for `[brave/duckduckgo]` only when `NEMOCLAW_EXPERIMENTAL=1` is set and `NEMOCLAW_WEB_SEARCH_PROVIDER` is unset; otherwise it defaults to Brave. Pre-setting `NEMOCLAW_WEB_SEARCH_PROVIDER=duckduckgo` (together with `NEMOCLAW_EXPERIMENTAL=1`) skips the provider prompt and selects DuckDuckGo directly in both interactive and non-interactive modes. + The wizard prompts for a sandbox name. Names must be 1 to 63 characters, lowercase, start with a letter, contain only letters, numbers, and internal hyphens, and end with a letter or number. The CLI rejects names that do not match these rules. diff --git a/docs/reference/network-policies.mdx b/docs/reference/network-policies.mdx index d5060f80785..f2cafcdeb9e 100644 --- a/docs/reference/network-policies.mdx +++ b/docs/reference/network-policies.mdx @@ -65,14 +65,16 @@ The baseline policy is always applied regardless of the selected tier. | Tier | Presets included | Description | |------|------------------|-------------| | Restricted | None | Base sandbox only. No third-party network access beyond inference and core agent tooling. | -| Balanced (default) | `npm`, `pypi`, `huggingface`, `brew`, `brave when supported` | Full dev tooling and web search for agents that support web search. No messaging platform access. | -| Open | `npm`, `pypi`, `huggingface`, `brew`, `brave when supported`, `slack`, `discord`, `telegram`, `wechat` (experimental), `whatsapp` (experimental), `jira`, `outlook` | Broad access across third-party services including messaging and productivity. | +| Balanced (default) | `npm`, `pypi`, `huggingface`, `brew`, web-search preset (when supported) | Full dev tooling and web search for agents that support web search. No messaging platform access. | +| Open | `npm`, `pypi`, `huggingface`, `brew`, web-search preset (when supported), `slack`, `discord`, `telegram`, `wechat` (experimental), `whatsapp` (experimental), `jira`, `outlook` | Broad access across third-party services including messaging and productivity. | After selecting a tier, a combined preset and access-mode screen lets you include or exclude individual presets and toggle each between read (GET only) and read-write (GET + POST/PUT/PATCH) access. Tier-default presets are pre-selected; additional presets can be added from the full list. -NemoClaw filters tier defaults by the active agent's supported integrations. -For example, Hermes onboarding omits the Brave Search preset because Hermes does not use NemoClaw's OpenClaw web-search configuration. -Claude Code direct egress is not included in any policy tier. +NemoClaw filters tier defaults by the active agent's supported integrations and the selected web-search provider. +The included web-search preset depends on the provider you picked during onboarding: `brave` for Brave Search (default) or `duckduckgo` for the experimental DuckDuckGo backend. +NemoClaw prunes the unused web-search preset from the tier defaults. +For example, Hermes onboarding omits the web-search preset because Hermes does not use NemoClaw's OpenClaw web-search configuration. +Claude Code direct egress is not included in any tier or `shields down` permissive policy. If you install and run the Claude Code CLI inside the sandbox with its own credentials, apply the `claude-code` preset explicitly. Normal NemoClaw Anthropic inference still routes through the OpenShell gateway. diff --git a/nemoclaw-blueprint/policies/presets/duckduckgo.yaml b/nemoclaw-blueprint/policies/presets/duckduckgo.yaml new file mode 100644 index 00000000000..3ef540e0860 --- /dev/null +++ b/nemoclaw-blueprint/policies/presets/duckduckgo.yaml @@ -0,0 +1,28 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +preset: + name: duckduckgo + description: "DuckDuckGo Search access (experimental, unofficial, keyless)" +network_policies: + duckduckgo: + name: duckduckgo + endpoints: + - host: duckduckgo.com + port: 443 + protocol: rest + enforcement: enforce + rules: + - allow: { method: GET, path: "/**" } + - allow: { method: POST, path: "/**" } + - host: lite.duckduckgo.com + port: 443 + protocol: rest + enforcement: enforce + rules: + - allow: { method: GET, path: "/**" } + - allow: { method: POST, path: "/**" } + binaries: + - { path: /usr/local/bin/node } + - { path: /usr/bin/node } + - { path: /usr/local/bin/curl } + - { path: /usr/bin/curl } diff --git a/nemoclaw-blueprint/provider-profiles/duckduckgo.yaml b/nemoclaw-blueprint/provider-profiles/duckduckgo.yaml new file mode 100644 index 00000000000..156bd05c6a3 --- /dev/null +++ b/nemoclaw-blueprint/provider-profiles/duckduckgo.yaml @@ -0,0 +1,23 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +id: duckduckgo +display_name: DuckDuckGo Search +description: DuckDuckGo Search access (experimental, unofficial, keyless) +category: agent +endpoints: + - host: duckduckgo.com + port: 443 + protocol: rest + access: read-write + enforcement: enforce + - host: lite.duckduckgo.com + port: 443 + protocol: rest + access: read-write + enforcement: enforce +binaries: + - /usr/local/bin/node + - /usr/bin/node + - /usr/local/bin/curl + - /usr/bin/curl +inference_capable: false diff --git a/scripts/generate-openclaw-config.mts b/scripts/generate-openclaw-config.mts index 167cd7992d8..ccf142a9b16 100755 --- a/scripts/generate-openclaw-config.mts +++ b/scripts/generate-openclaw-config.mts @@ -21,6 +21,7 @@ // NEMOCLAW_EXTRA_AGENTS_JSON_B64, // NEMOCLAW_PROXY_HOST, NEMOCLAW_PROXY_PORT, // NEMOCLAW_OPENCLAW_MANAGED_PROXY, NEMOCLAW_WEB_SEARCH_ENABLED, +// NEMOCLAW_WEB_SEARCH_PROVIDER, // NEMOCLAW_OPENCLAW_OTEL, NEMOCLAW_OPENCLAW_OTEL_ENDPOINT, // NEMOCLAW_OPENCLAW_OTEL_SERVICE_NAME, NEMOCLAW_OPENCLAW_OTEL_SAMPLE_RATE. @@ -1072,11 +1073,18 @@ export function buildConfig(env: Env = process.env): JsonObject { tools.web.fetch = { enabled: true, useTrustedEnvProxy: true }; if (env.NEMOCLAW_WEB_SEARCH_ENABLED === "1") { - tools.web.search = { - enabled: true, - provider: "brave", - apiKey: "openshell:resolve:env:BRAVE_API_KEY", - }; + if (env.NEMOCLAW_WEB_SEARCH_PROVIDER === "duckduckgo") { + tools.web.search = { + enabled: true, + provider: "duckduckgo", + }; + } else { + tools.web.search = { + enabled: true, + provider: "brave", + apiKey: "openshell:resolve:env:BRAVE_API_KEY", + }; + } } return config; diff --git a/src/lib/inference/web-search.test.ts b/src/lib/inference/web-search.test.ts index cf98d55d781..9b7e47e59ca 100644 --- a/src/lib/inference/web-search.test.ts +++ b/src/lib/inference/web-search.test.ts @@ -3,10 +3,67 @@ import { describe, expect, it } from "vitest"; -import { BRAVE_API_KEY_ENV } from "./web-search"; +import { + BRAVE_API_KEY_ENV, + isWebSearchEnabled, + isWebSearchProvider, + normalizeWebSearchProvider, +} from "./web-search"; describe("web-search module", () => { it("exports BRAVE_API_KEY_ENV constant", () => { expect(BRAVE_API_KEY_ENV).toBe("BRAVE_API_KEY"); }); }); + +describe("isWebSearchEnabled", () => { + it("returns false for null or undefined", () => { + expect(isWebSearchEnabled(null)).toBe(false); + expect(isWebSearchEnabled(undefined)).toBe(false); + }); + + it("returns false when fetchEnabled is not literally true", () => { + expect(isWebSearchEnabled({})).toBe(false); + expect(isWebSearchEnabled({ fetchEnabled: false })).toBe(false); + expect(isWebSearchEnabled({ fetchEnabled: null })).toBe(false); + }); + + it("returns true regardless of provider when fetchEnabled is true", () => { + expect(isWebSearchEnabled({ fetchEnabled: true })).toBe(true); + expect( + isWebSearchEnabled({ fetchEnabled: true, provider: "duckduckgo" } as { + fetchEnabled: boolean; + }), + ).toBe(true); + }); +}); + +describe("isWebSearchProvider", () => { + it("accepts the known allowlist values", () => { + expect(isWebSearchProvider("brave")).toBe(true); + expect(isWebSearchProvider("duckduckgo")).toBe(true); + }); + + it("rejects unknown values, including realistic typos and rogue inputs", () => { + expect(isWebSearchProvider("bing")).toBe(false); + expect(isWebSearchProvider("Brave")).toBe(false); + expect(isWebSearchProvider("")).toBe(false); + expect(isWebSearchProvider(null)).toBe(false); + expect(isWebSearchProvider(undefined)).toBe(false); + expect(isWebSearchProvider(42)).toBe(false); + }); +}); + +describe("normalizeWebSearchProvider", () => { + it("returns the value when valid", () => { + expect(normalizeWebSearchProvider("brave")).toBe("brave"); + expect(normalizeWebSearchProvider("duckduckgo")).toBe("duckduckgo"); + }); + + it("falls back to the default provider for invalid values", () => { + expect(normalizeWebSearchProvider("bing")).toBe("brave"); + expect(normalizeWebSearchProvider("")).toBe("brave"); + expect(normalizeWebSearchProvider(null)).toBe("brave"); + expect(normalizeWebSearchProvider(undefined)).toBe("brave"); + }); +}); diff --git a/src/lib/inference/web-search.ts b/src/lib/inference/web-search.ts index dd6d7682ac9..35ca6fe9fe2 100644 --- a/src/lib/inference/web-search.ts +++ b/src/lib/inference/web-search.ts @@ -1,8 +1,29 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +export type WebSearchProvider = "brave" | "duckduckgo"; + +export const WEB_SEARCH_PROVIDERS: readonly WebSearchProvider[] = ["brave", "duckduckgo"]; + +export const DEFAULT_WEB_SEARCH_PROVIDER: WebSearchProvider = "brave"; + +export function isWebSearchProvider(value: unknown): value is WebSearchProvider { + return WEB_SEARCH_PROVIDERS.includes(value as WebSearchProvider); +} + +export function normalizeWebSearchProvider(value: unknown): WebSearchProvider { + return isWebSearchProvider(value) ? value : DEFAULT_WEB_SEARCH_PROVIDER; +} + export interface WebSearchConfig { fetchEnabled: boolean; + provider?: WebSearchProvider; +} + +export function isWebSearchEnabled( + webSearchConfig: { fetchEnabled?: boolean | null } | null | undefined, +): boolean { + return webSearchConfig?.fetchEnabled === true; } export const BRAVE_API_KEY_ENV = "BRAVE_API_KEY"; diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index e61222b2f32..59413dd067a 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -7018,7 +7018,7 @@ async function onboard(opts: OnboardOptions = {}): Promise { hermesToolGateways, stagedLegacyKeys, migratedLegacyKeys, - webSearchEnabled: braveProviderProfile.shouldEnableBraveWebSearch(webSearchConfig), + webSearchEnabled: webSearch.isWebSearchEnabled(webSearchConfig), deps: { ensureAgentDashboardForward, setDefaultSandbox: registry.setDefault, diff --git a/src/lib/onboard/brave-provider-profile.ts b/src/lib/onboard/brave-provider-profile.ts index cd8575c0fdb..c69efe8ffdb 100644 --- a/src/lib/onboard/brave-provider-profile.ts +++ b/src/lib/onboard/brave-provider-profile.ts @@ -13,12 +13,19 @@ export const BRAVE_PROVIDER_PROFILE_ID = "brave"; * `createSandbox` to push a Brave provider/token and trip the BRAVE_API_KEY- * required abort even when the feature is off, while the downstream * finalization/verifier paths already gate on `fetchEnabled`. Keep every gate - * routed through this helper so they stay aligned. + * routed through this helper so they stay aligned. A web-search config that + * names a non-Brave provider (e.g. `duckduckgo`) does not enable Brave-specific + * setup paths, even when `fetchEnabled` is true. */ export function shouldEnableBraveWebSearch( - webSearchConfig: { fetchEnabled?: boolean | null } | null | undefined, + webSearchConfig: + | { fetchEnabled?: boolean | null; provider?: string | null } + | null + | undefined, ): boolean { - return Boolean(webSearchConfig?.fetchEnabled); + if (!webSearchConfig?.fetchEnabled) return false; + const provider = webSearchConfig.provider; + return !provider || provider === BRAVE_PROVIDER_PROFILE_ID; } export type BraveProviderProfileDeps = { diff --git a/src/lib/onboard/dockerfile-patch.test.ts b/src/lib/onboard/dockerfile-patch.test.ts index 4ab309892e8..8f4019483ae 100644 --- a/src/lib/onboard/dockerfile-patch.test.ts +++ b/src/lib/onboard/dockerfile-patch.test.ts @@ -1281,6 +1281,7 @@ describe("dockerfile patch helpers", () => { "ARG NEMOCLAW_INFERENCE_API=openai-completions", "ARG NEMOCLAW_INFERENCE_COMPAT_B64=e30=", "ARG NEMOCLAW_WEB_SEARCH_ENABLED=0", + "ARG NEMOCLAW_WEB_SEARCH_PROVIDER=brave", "ARG NEMOCLAW_BUILD_ID=default", ].join("\n"), ); @@ -1299,6 +1300,7 @@ describe("dockerfile patch helpers", () => { ); const patched = fs.readFileSync(dockerfilePath, "utf8"); assert.match(patched, /^ARG NEMOCLAW_WEB_SEARCH_ENABLED=1$/m); + assert.match(patched, /^ARG NEMOCLAW_WEB_SEARCH_PROVIDER=brave$/m); // Regression guard: the old secret-bearing build arg must not reappear. assert.doesNotMatch(patched, /NEMOCLAW_WEB_CONFIG_B64/); } finally { @@ -1311,4 +1313,42 @@ describe("dockerfile patch helpers", () => { } }); + it("patches the staged Dockerfile with DuckDuckGo provider when selected", () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-dockerfile-ddg-")); + const dockerfilePath = path.join(tmpDir, "Dockerfile"); + fs.writeFileSync( + dockerfilePath, + [ + "ARG NEMOCLAW_MODEL=nvidia/nemotron-3-super-120b-a12b", + "ARG NEMOCLAW_PROVIDER_KEY=nvidia", + "ARG NEMOCLAW_PRIMARY_MODEL_REF=nvidia/nemotron-3-super-120b-a12b", + "ARG CHAT_UI_URL=http://127.0.0.1:18789", + "ARG NEMOCLAW_INFERENCE_BASE_URL=https://inference.local/v1", + "ARG NEMOCLAW_INFERENCE_API=openai-completions", + "ARG NEMOCLAW_INFERENCE_COMPAT_B64=e30=", + "ARG NEMOCLAW_WEB_SEARCH_ENABLED=0", + "ARG NEMOCLAW_WEB_SEARCH_PROVIDER=brave", + "ARG NEMOCLAW_BUILD_ID=default", + ].join("\n"), + ); + + try { + patchStagedDockerfile( + dockerfilePath, + "gpt-5.4", + "http://127.0.0.1:18789", + "build-ddg", + "openai-api", + null, + { fetchEnabled: true, provider: "duckduckgo" }, + ); + const patched = fs.readFileSync(dockerfilePath, "utf8"); + assert.match(patched, /^ARG NEMOCLAW_WEB_SEARCH_ENABLED=1$/m); + assert.match(patched, /^ARG NEMOCLAW_WEB_SEARCH_PROVIDER=duckduckgo$/m); + assert.doesNotMatch(patched, /BRAVE_API_KEY/); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); + }); diff --git a/src/lib/onboard/dockerfile-patch.ts b/src/lib/onboard/dockerfile-patch.ts index 27f4fcb0e9a..799b310d6f2 100644 --- a/src/lib/onboard/dockerfile-patch.ts +++ b/src/lib/onboard/dockerfile-patch.ts @@ -198,6 +198,11 @@ export function patchStagedDockerfile( /^ARG NEMOCLAW_WEB_SEARCH_ENABLED=.*$/m, `ARG NEMOCLAW_WEB_SEARCH_ENABLED=${sanitizeDockerArg(webSearchConfig ? "1" : "0")}`, ); + const webSearchProvider = webSearchConfig?.provider ?? "brave"; + dockerfile = dockerfile.replace( + /^ARG NEMOCLAW_WEB_SEARCH_PROVIDER=.*$/m, + `ARG NEMOCLAW_WEB_SEARCH_PROVIDER=${sanitizeDockerArg(webSearchProvider)}`, + ); for (const envKey of [ "NEMOCLAW_OPENCLAW_OTEL", "NEMOCLAW_OPENCLAW_OTEL_ENDPOINT", diff --git a/src/lib/onboard/policy-presets.ts b/src/lib/onboard/policy-presets.ts index 23202d80097..d2f883f4ee3 100644 --- a/src/lib/onboard/policy-presets.ts +++ b/src/lib/onboard/policy-presets.ts @@ -62,7 +62,9 @@ export function getSuggestedPolicyPresets({ maybeSuggestMessagingPreset("wechat", "WECHAT_BOT_TOKEN"); maybeSuggestMessagingPreset("whatsapp", null); - if (webSearchConfig) suggestions.push("brave"); + if (webSearchConfig) { + suggestions.push(webSearchConfig.provider === "duckduckgo" ? "duckduckgo" : "brave"); + } return suggestions; } diff --git a/src/lib/onboard/policy-selection.ts b/src/lib/onboard/policy-selection.ts index 886104c9c60..91df49648b0 100644 --- a/src/lib/onboard/policy-selection.ts +++ b/src/lib/onboard/policy-selection.ts @@ -122,18 +122,22 @@ export function mergeRequiredSetupPolicyPresets( ); } -export function isStaleBuiltinBravePolicyPreset( +export function isStaleBuiltinWebSearchPolicyPreset( name: string, options: { webSearchConfig?: WebSearchConfig | null; customPresetNames?: ReadonlySet | null; } = {}, ): boolean { - return ( - name === "brave" && - !options.webSearchConfig && - !options.customPresetNames?.has(name) - ); + if (options.customPresetNames?.has(name)) return false; + const activeProvider = options.webSearchConfig?.provider ?? "brave"; + if (name === "brave") { + return !options.webSearchConfig || activeProvider !== "brave"; + } + if (name === "duckduckgo") { + return !options.webSearchConfig || activeProvider !== "duckduckgo"; + } + return false; } export function computeSetupPresetSuggestions( @@ -158,7 +162,7 @@ export function computeSetupPresetSuggestions( const suggestions = deps.tiers .resolveTierPresets(tierName) .map((preset) => preset.name) - .filter((name) => !isStaleBuiltinBravePolicyPreset(name, { webSearchConfig })) + .filter((name) => !isStaleBuiltinWebSearchPolicyPreset(name, { webSearchConfig })) .filter((name) => deps.policies.setupPolicyPresetSupported(name, supportOptions)) .filter((name) => !known || known.has(name)); const add = (name: string) => { @@ -167,7 +171,9 @@ export function computeSetupPresetSuggestions( if (known && !known.has(name)) return; suggestions.push(name); }; - if (webSearchConfig) add("brave"); + if (webSearchConfig) { + add(webSearchConfig.provider === "duckduckgo" ? "duckduckgo" : "brave"); + } if (provider && deps.localInferenceProviders.includes(provider)) add("local-inference"); if (isOpenclawAgent(agent)) { add("openclaw-pricing"); @@ -214,13 +220,13 @@ export function preparePolicyPresetResumeSelection( supportOptions, customPolicyPresetNames, ); - const isStaleBuiltinBrave = (name: string) => - isStaleBuiltinBravePolicyPreset(name, { + const isStaleBuiltinWebSearch = (name: string) => + isStaleBuiltinWebSearchPolicyPreset(name, { webSearchConfig: options.webSearchConfig, customPresetNames: customPolicyPresetNames, }); let policyPresets = pruneDisabledMessagingPolicyPresets( - clampedRecordedPolicyPresets.filter((name) => !isStaleBuiltinBrave(name)), + clampedRecordedPolicyPresets.filter((name) => !isStaleBuiltinWebSearch(name)), options.disabledChannels, ); const recordedPolicyPresetsNeedReconcile = @@ -233,7 +239,7 @@ export function preparePolicyPresetResumeSelection( supportOptions, customPolicyPresetNames, ) - .filter((name) => !isStaleBuiltinBrave(name)); + .filter((name) => !isStaleBuiltinWebSearch(name)); const disabledMessagingPolicyPresetApplied = hasDisabledMessagingPolicyPreset( appliedPolicyPresetsForSupport, options.disabledChannels, @@ -307,12 +313,12 @@ async function setupPoliciesWithSelectionInner( supportOptions, customPresetNames, ); - const isStaleBuiltinBrave = (name: string) => - isStaleBuiltinBravePolicyPreset(name, { webSearchConfig, customPresetNames }); + const isStaleBuiltinWebSearch = (name: string) => + isStaleBuiltinWebSearchPolicyPreset(name, { webSearchConfig, customPresetNames }); const appliedForPreservation = pruneDisabledMessagingPolicyPresets( applied, disabledChannels, - ).filter((name) => !isStaleBuiltinBrave(name)); + ).filter((name) => !isStaleBuiltinWebSearch(name)); const pruneDisabledPresets = (presetNames: string[]) => pruneDisabledMessagingPolicyPresets(presetNames, disabledChannels); const filterSupportedPresetNames = (presetNames: string[]) => @@ -423,7 +429,7 @@ async function setupPoliciesWithSelectionInner( const preserved: string[] = []; for (const name of appliedForPreservation) { if (chosenSet.has(name)) continue; - if (isStaleBuiltinBrave(name)) continue; + if (isStaleBuiltinWebSearch(name)) continue; chosen.push(name); chosenSet.add(name); preserved.push(name); diff --git a/src/lib/onboard/web-search-flow.ts b/src/lib/onboard/web-search-flow.ts index 3aaa002d5f8..ab530d0f6a4 100644 --- a/src/lib/onboard/web-search-flow.ts +++ b/src/lib/onboard/web-search-flow.ts @@ -5,8 +5,8 @@ import type { CurlProbeResult } from "../adapters/http/probe"; import { runCurlProbe } from "../adapters/http/probe"; import type { AgentDefinition } from "../agent/defs"; import { getCredential, normalizeCredentialValue, saveCredential } from "../credentials/store"; -import type { WebSearchConfig } from "../inference/web-search"; -import { BRAVE_API_KEY_ENV } from "../inference/web-search"; +import type { WebSearchConfig, WebSearchProvider } from "../inference/web-search"; +import { BRAVE_API_KEY_ENV, normalizeWebSearchProvider } from "../inference/web-search"; import { ROOT } from "../runner"; import { classifyValidationFailure } from "../validation"; import { getTransportRecoveryMessage } from "../validation-recovery"; @@ -164,6 +164,31 @@ export function createWebSearchFlowHelpers(deps: WebSearchFlowDeps): WebSearchFl } } + function isDuckDuckGoExperimentalEnabled(): boolean { + return process.env.NEMOCLAW_EXPERIMENTAL === "1"; + } + + function isDuckDuckGoExistingConfig(config: WebSearchConfig | null): boolean { + return config?.provider === "duckduckgo"; + } + + async function promptWebSearchProvider(): Promise { + if (!isDuckDuckGoExperimentalEnabled()) return "brave"; + while (true) { + const answer = ( + await deps.prompt(" Web search provider [brave/duckduckgo] (default brave): ") + ) + .trim() + .toLowerCase(); + if (answer === "" || answer === "brave") return "brave"; + if (answer === "duckduckgo" || answer === "ddg") return "duckduckgo"; + if (answer === "exit" || answer === "quit") { + exitOnboardFromPrompt(); + } + console.error(" Unsupported provider. Enter 'brave' or 'duckduckgo'."); + } + } + async function configureWebSearch( existingConfig: WebSearchConfig | null = null, agent: AgentDefinition | null = null, @@ -175,10 +200,23 @@ export function createWebSearchFlowHelpers(deps: WebSearchFlowDeps): WebSearchFl } if (existingConfig) { + if (isDuckDuckGoExistingConfig(existingConfig)) { + return { fetchEnabled: true, provider: "duckduckgo" }; + } return { fetchEnabled: true }; } + const duckDuckGoRequested = + isDuckDuckGoExperimentalEnabled() && + normalizeWebSearchProvider( + (process.env.NEMOCLAW_WEB_SEARCH_PROVIDER || "").toLowerCase(), + ) === "duckduckgo"; + if (deps.isNonInteractive()) { + if (duckDuckGoRequested) { + deps.note(" [experimental][non-interactive] DuckDuckGo Web Search requested."); + return { fetchEnabled: true, provider: "duckduckgo" }; + } const braveApiKey = getCredential(BRAVE_API_KEY_ENV) || normalizeCredentialValue(process.env[BRAVE_API_KEY_ENV]); if (!braveApiKey) { @@ -199,11 +237,21 @@ export function createWebSearchFlowHelpers(deps: WebSearchFlowDeps): WebSearchFl process.env[BRAVE_API_KEY_ENV] = braveApiKey; return { fetchEnabled: true }; } - const enableAnswer = await deps.prompt(" Enable Brave Web Search? [y/N]: "); + const enableAnswer = await deps.prompt(" Enable Web Search? [y/N]: "); if (!isAffirmativeAnswer(enableAnswer)) { return null; } + const provider: WebSearchProvider = duckDuckGoRequested + ? "duckduckgo" + : await promptWebSearchProvider(); + + if (provider === "duckduckgo") { + console.log(" ✓ Enabled DuckDuckGo Web Search (experimental, unofficial)"); + console.log(""); + return { fetchEnabled: true, provider: "duckduckgo" }; + } + const braveApiKey = await ensureValidatedBraveSearchCredential(); if (isBackToSelection(braveApiKey)) { return configureWebSearch(existingConfig, agent, dockerfilePathOverride); diff --git a/src/lib/onboard/web-search-verify.test.ts b/src/lib/onboard/web-search-verify.test.ts index 949dc1fa292..2e852308a0e 100644 --- a/src/lib/onboard/web-search-verify.test.ts +++ b/src/lib/onboard/web-search-verify.test.ts @@ -134,6 +134,24 @@ describe("verifyWebSearchInsideSandbox", () => { ); }); + it("reports DuckDuckGo config-only verification without running an egress probe", () => { + const d = deps( + JSON.stringify({ + tools: { web: { search: { enabled: true, provider: "duckduckgo" } } }, + }), + ); + + verifyWebSearchInsideSandbox("alpha", { name: "openclaw" }, d); + + // The verifier must not shell out to curl for DDG — the live-search + // path is covered by test/e2e/test-duckduckgo-search-e2e.sh. + expect(d.runCaptureOpenshell).toHaveBeenCalledTimes(1); + expect(d.log).toHaveBeenCalledWith( + " ✓ Web search is configured inside sandbox (DuckDuckGo, experimental)", + ); + expect(d.warn).not.toHaveBeenCalled(); + }); + it("warns for unknown agents and catches probe errors", () => { const unknown = deps(null); verifyWebSearchInsideSandbox("alpha", { name: "other" }, unknown); diff --git a/src/lib/onboard/web-search-verify.ts b/src/lib/onboard/web-search-verify.ts index bde766708f4..ca335c77c13 100644 --- a/src/lib/onboard/web-search-verify.ts +++ b/src/lib/onboard/web-search-verify.ts @@ -109,6 +109,14 @@ export function verifyWebSearchInsideSandbox( warn(" ⚠ Web search was configured but tools.web.search is not enabled in openclaw.json."); return; } + if (search.provider === "duckduckgo") { + // Config presence only — no runtime egress probe yet. The DDG E2E + // (test/e2e/test-duckduckgo-search-e2e.sh, phase D4) covers the + // live-search path; downgrade the message here to match what was + // actually verified. + log(" ✓ Web search is configured inside sandbox (DuckDuckGo, experimental)"); + return; + } if (search.provider !== "brave") { log(" ✓ Web search is active inside sandbox"); return; diff --git a/src/lib/policy/index.ts b/src/lib/policy/index.ts index 260644e393c..a2ff2da8eda 100644 --- a/src/lib/policy/index.ts +++ b/src/lib/policy/index.ts @@ -258,7 +258,8 @@ function setupPolicyPresetSupported( name: string, options: SetupPolicyPresetSupportOptions = {}, ): boolean { - return name !== "brave" || options.webSearchSupported !== false; + if (name !== "brave" && name !== "duckduckgo") return true; + return options.webSearchSupported !== false; } function filterSetupPolicyPresets( diff --git a/src/lib/state/onboard-session.test.ts b/src/lib/state/onboard-session.test.ts index be35e8f73d1..9f02d8f6a2a 100644 --- a/src/lib/state/onboard-session.test.ts +++ b/src/lib/state/onboard-session.test.ts @@ -723,6 +723,43 @@ describe("onboard session", () => { expect(loaded.webSearchConfig).toBeNull(); }); + it("preserves a duckduckgo web-search provider across save/load", () => { + session.saveSession(session.createSession()); + session.markStepComplete("provider_selection", { + webSearchConfig: { fetchEnabled: true, provider: "duckduckgo" }, + }); + + const loaded = requireLoadedSession(session.loadSession()); + expect(loaded.webSearchConfig).toEqual({ fetchEnabled: true, provider: "duckduckgo" }); + }); + + it("drops unknown provider values from persisted web-search config", () => { + session.saveSession(session.createSession()); + session.markStepComplete("provider_selection", { + webSearchConfig: { + fetchEnabled: true, + // The disk-state boundary may have been written by a future or + // tampered build. Anything that does not match the in-code + // allowlist must be discarded by the normalizer, leaving only + // fetchEnabled. + provider: "bing" as unknown as "brave", + }, + }); + + const loaded = requireLoadedSession(session.loadSession()); + expect(loaded.webSearchConfig).toEqual({ fetchEnabled: true }); + }); + + it("treats fetchEnabled !== true as no web-search config", () => { + session.saveSession(session.createSession()); + session.markStepComplete("provider_selection", { + webSearchConfig: { fetchEnabled: false as unknown as true, provider: "duckduckgo" }, + }); + + const loaded = requireLoadedSession(session.loadSession()); + expect(loaded.webSearchConfig).toBeNull(); + }); + it("does not clear existing metadata when updates omit whitelisted metadata fields", () => { session.saveSession( session.createSession({ metadata: { gatewayName: "nemoclaw", fromDockerfile: null } }), diff --git a/src/lib/state/onboard-session.ts b/src/lib/state/onboard-session.ts index 26cbf083539..a18c1d8be87 100644 --- a/src/lib/state/onboard-session.ts +++ b/src/lib/state/onboard-session.ts @@ -13,7 +13,7 @@ import path from "node:path"; import { isErrnoException } from "../core/errno"; import type { JsonObject, JsonValue } from "../core/json-types"; -import type { WebSearchConfig } from "../inference/web-search"; +import { isWebSearchProvider, type WebSearchConfig } from "../inference/web-search"; import { sanitizeMessagingChannelConfig, type MessagingChannelConfig, @@ -282,8 +282,35 @@ function readStepStatus(value: SessionJsonValue | undefined): StepStatus | null return isStepStatus(value) ? value : null; } +/** + * Normalize a web-search config read from the on-disk session JSON. + * + * Source boundary: the session file is untrusted persisted JSON. It may have + * been written by a prior NemoClaw release (with fewer provider values), by a + * future release (with values this binary doesn't know yet), or hand-edited. + * Treat anything that doesn't match the in-code allowlist as malformed and + * normalize it away rather than propagating an invalid shape into the + * onboarding state machine. + * + * Invariants enforced here: + * - A truthy result means `fetchEnabled === true`. Anything else collapses + * to `null` so downstream gates uniformly treat web search as off. + * - `provider` is only preserved when it passes `isWebSearchProvider`. An + * unknown provider falls back to the implicit Brave default rather than + * leaking into the runtime. + * + * This defensive parse can be removed only when the session schema gains a + * version check that hard-fails on unknown shapes; until then it is the only + * guard against multi-provider rollouts leaving an unrecognised value in the + * session file. + */ function parseWebSearchConfig(value: SessionJsonValue | undefined): WebSearchConfig | null { - return isObject(value) && value.fetchEnabled === true ? { fetchEnabled: true } : null; + if (!isObject(value) || value.fetchEnabled !== true) return null; + const config: WebSearchConfig = { fetchEnabled: true }; + if (isWebSearchProvider(value.provider)) { + config.provider = value.provider; + } + return config; } function parseTelegramConfig(value: unknown): TelegramConfig | null { @@ -476,8 +503,9 @@ export function createSession(overrides: Partial = {}): Session { nimContainer: overrides.nimContainer ?? null, routerPid: readPositiveInteger(overrides.routerPid), routerCredentialHash: overrides.routerCredentialHash ?? null, - webSearchConfig: - overrides.webSearchConfig?.fetchEnabled === true ? { fetchEnabled: true } : null, + webSearchConfig: parseWebSearchConfig( + overrides.webSearchConfig as SessionJsonValue | undefined, + ), hermesToolGateways: readStringArray(overrides.hermesToolGateways), policyPresets: readStringArray(overrides.policyPresets), messagingChannels: readStringArray(overrides.messagingChannels), @@ -932,7 +960,11 @@ export function filterSafeUpdates(updates: SessionUpdates): Partial { safe.routerCredentialHash = updates.routerCredentialHash; } if (isObject(updates.webSearchConfig) && updates.webSearchConfig.fetchEnabled === true) { - safe.webSearchConfig = { fetchEnabled: true }; + const sanitized: WebSearchConfig = { fetchEnabled: true }; + if (isWebSearchProvider(updates.webSearchConfig.provider)) { + sanitized.provider = updates.webSearchConfig.provider; + } + safe.webSearchConfig = sanitized; } else if (updates.webSearchConfig === null) { safe.webSearchConfig = null; } diff --git a/test/e2e/test-duckduckgo-search-e2e.sh b/test/e2e/test-duckduckgo-search-e2e.sh new file mode 100755 index 00000000000..febd940104f --- /dev/null +++ b/test/e2e/test-duckduckgo-search-e2e.sh @@ -0,0 +1,359 @@ +#!/bin/bash +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# DuckDuckGo Search E2E +# +# Verifies the DuckDuckGo Web Search backend end-to-end: +# D1 Non-interactive onboard with NEMOCLAW_EXPERIMENTAL=1 + +# NEMOCLAW_WEB_SEARCH_PROVIDER=duckduckgo succeeds +# D2a duckduckgo network policy preset is applied +# D2b openclaw web-search config selects duckduckgo (no apiKey field) +# D3 openclaw.json carries no apiKey/credentials for the DDG provider +# D4a Real DDG search via openclaw agent +# D4b Real DDG search via curl from inside the sandbox (lite endpoint) +# +# Required env (CI injects from secrets): +# NVIDIA_API_KEY drives the agent inference turn in D4a (optional; +# the agent step self-skips when unavailable) +# +# DuckDuckGo Search is keyless. No secrets are involved on the egress path; +# the script intentionally omits the secret-handling gates present in the +# Brave Search E2E. +# +# Usage: +# NEMOCLAW_NON_INTERACTIVE=1 NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE=1 \ +# NEMOCLAW_EXPERIMENTAL=1 NEMOCLAW_WEB_SEARCH_PROVIDER=duckduckgo \ +# NVIDIA_API_KEY=... \ +# bash test/e2e/test-duckduckgo-search-e2e.sh + +set -uo pipefail + +export NEMOCLAW_E2E_DEFAULT_TIMEOUT=1800 +SCRIPT_DIR_TIMEOUT="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)" +# shellcheck source=test/e2e/e2e-timeout.sh +. "${SCRIPT_DIR_TIMEOUT}/e2e-timeout.sh" +# shellcheck source=test/e2e/lib/openclaw-json.sh +. "${SCRIPT_DIR_TIMEOUT}/lib/openclaw-json.sh" + +PASS=0 +FAIL=0 +SKIP=0 +TOTAL=0 + +pass() { + ((PASS++)) + ((TOTAL++)) + printf '\033[32m PASS: %s\033[0m\n' "$1" +} +fail() { + ((FAIL++)) + ((TOTAL++)) + printf '\033[31m FAIL: %s\033[0m\n' "$1" +} +skip() { + ((SKIP++)) + ((TOTAL++)) + printf '\033[33m SKIP: %s\033[0m\n' "$1" +} +section() { + echo "" + printf '\033[1;36m=== %s ===\033[0m\n' "$1" +} +info() { printf '\033[1;34m [info]\033[0m %s\n' "$1"; } + +summary() { + echo "" + echo "============================================================" + echo " DuckDuckGo Search E2E Results" + echo "============================================================" + echo " PASS: $PASS" + echo " FAIL: $FAIL" + echo " SKIP: $SKIP" + echo " TOTAL: $TOTAL" + echo "============================================================" + if [ "$FAIL" -gt 0 ]; then exit 1; fi +} + +# ── Repo root ───────────────────────────────────────────────────── +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)" +if [ -d /workspace ] && [ -f /workspace/install.sh ]; then + REPO="/workspace" +elif [ -f "${SCRIPT_DIR}/../../install.sh" ]; then + REPO="$(cd "${SCRIPT_DIR}/../.." && pwd)" +elif [ -f "./install.sh" ]; then + REPO="$(pwd)" +else + echo "ERROR: Cannot find repo root." + exit 1 +fi + +SANDBOX_NAME="${NEMOCLAW_SANDBOX_NAME:-e2e-duckduckgo-search}" +ONBOARD_LOG="/tmp/nemoclaw-e2e-duckduckgo-search-onboard.log" + +quote_for_remote_sh() { + local value="${1:-}" + printf "'%s'" "$(printf '%s' "$value" | sed "s/'/'\\\\''/g")" +} + +sandbox_exec_sh_script() { + local script="$1" + shift + local encoded remote_cmd arg + encoded="$(printf '%s' "$script" | base64 | tr -d '\n')" + remote_cmd="tmp=\$(mktemp); trap 'rm -f \"\$tmp\"' EXIT; printf %s $(quote_for_remote_sh "$encoded") | base64 -d > \"\$tmp\"; sh \"\$tmp\"" + for arg in "$@"; do + remote_cmd+=" $(quote_for_remote_sh "$arg")" + done + openshell sandbox exec --name "$SANDBOX_NAME" -- sh -lc "$remote_cmd" +} + +load_shell_path() { + local local_bin + if [ -f "$HOME/.bashrc" ]; then + # shellcheck source=/dev/null + source "$HOME/.bashrc" 2>/dev/null || true + fi + export NVM_DIR="${NVM_DIR:-$HOME/.nvm}" + if [ -s "$NVM_DIR/nvm.sh" ]; then + # shellcheck source=/dev/null + . "$NVM_DIR/nvm.sh" + fi + local_bin="$HOME/.local/bin" + if [ -d "$local_bin" ]; then + PATH=":${PATH}:" + PATH="${PATH//:${local_bin}:/:}" + PATH="${PATH#:}" + PATH="${PATH%:}" + export PATH="$local_bin:$PATH" + fi +} + +cli_command_available_from_source() { + [ -f "$REPO/dist/nemoclaw.js" ] && command -v node >/dev/null 2>&1 && command -v openshell >/dev/null 2>&1 +} + +destroy_sandbox_best_effort() { + if [ "${NEMOCLAW_E2E_KEEP_SANDBOX:-}" = "1" ]; then + return 0 + fi + if cli_command_available_from_source; then + run_with_timeout 120 node "$REPO/bin/nemoclaw.js" "$SANDBOX_NAME" destroy --yes >/dev/null 2>&1 || true + elif command -v nemoclaw >/dev/null 2>&1; then + run_with_timeout 120 nemoclaw "$SANDBOX_NAME" destroy --yes >/dev/null 2>&1 || true + fi + if command -v openshell >/dev/null 2>&1; then + run_with_timeout 60 openshell sandbox delete "$SANDBOX_NAME" >/dev/null 2>&1 || true + fi +} + +# D1 — non-interactive onboard with DuckDuckGo provider gated by EXPERIMENTAL. +run_onboard_with_duckduckgo() { + local onboard_exit=0 onboard_cmd_desc + export NEMOCLAW_SANDBOX_NAME="$SANDBOX_NAME" + export NEMOCLAW_RECREATE_SANDBOX=1 + export NEMOCLAW_NON_INTERACTIVE=1 + export NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE=1 + export NEMOCLAW_EXPERIMENTAL=1 + export NEMOCLAW_WEB_SEARCH_PROVIDER=duckduckgo + + if cli_command_available_from_source; then + onboard_cmd_desc="source CLI onboard" + info "Using source-built CLI at $REPO/bin/nemoclaw.js" + destroy_sandbox_best_effort + run_with_timeout 1200 node "$REPO/bin/nemoclaw.js" onboard --fresh --non-interactive --yes-i-accept-third-party-software 2>&1 \ + | tee "$ONBOARD_LOG" + onboard_exit=${PIPESTATUS[0]} + else + onboard_cmd_desc="install.sh" + info "Source CLI is not built; running install.sh from this checkout." + bash "$REPO/install.sh" --non-interactive --yes-i-accept-third-party-software --fresh 2>&1 \ + | tee "$ONBOARD_LOG" + onboard_exit=${PIPESTATUS[0]} + load_shell_path + fi + + if [ "$onboard_exit" -eq 0 ]; then + pass "D1: ${onboard_cmd_desc} completed for DuckDuckGo-enabled onboard" + else + fail "D1: ${onboard_cmd_desc} failed (exit $onboard_exit)" + summary + fi +} + +# D2 — duckduckgo preset is applied. +check_duckduckgo_preset_applied() { + local policy_output rc=0 config_check config_rc=0 config_script + + policy_output=$(openshell policy get --full "$SANDBOX_NAME" 2>&1) || rc=$? + if [ "$rc" -ne 0 ]; then + fail "D2a: openshell policy get failed (exit $rc)" + elif printf '%s' "$policy_output" | grep -q "duckduckgo.com" \ + && printf '%s' "$policy_output" | grep -q "lite.duckduckgo.com"; then + pass "D2a: duckduckgo preset applied — duckduckgo.com and lite.duckduckgo.com are in the loaded gateway policy" + else + fail "D2a: duckduckgo preset NOT applied — duckduckgo hosts missing from the gateway policy" + fi + + config_script=$( + cat <<'SH' +python3 <<'PY' +import json +with open("/sandbox/.openclaw/openclaw.json") as f: + cfg = json.load(f) +s = cfg.get("tools", {}).get("web", {}).get("search", {}) +print(f"enabled={s.get('enabled')}") +print(f"provider={s.get('provider')}") +print(f"has_api_key={'apiKey' in s}") +PY +SH + ) + config_check=$(sandbox_exec_sh_script "$config_script" 2>&1) || config_rc=$? + + if [ "$config_rc" -ne 0 ]; then + fail "D2b: could not read openclaw web-search config (exit $config_rc)" + elif printf '%s' "$config_check" | grep -q "^enabled=True$" \ + && printf '%s' "$config_check" | grep -q "^provider=duckduckgo$"; then + pass "D2b: duckduckgo preset wired through to openclaw — tools.web.search.provider=duckduckgo and enabled=true" + else + fail "D2b: openclaw web-search config does not select duckduckgo (got: $(printf '%s' "$config_check" | tr '\n' ' '))" + fi +} + +# D3 — no API key field of any kind is emitted for DuckDuckGo. +check_no_api_key_emitted() { + local config_dump + + config_dump=$(openshell sandbox exec --name "$SANDBOX_NAME" -- sh -lc \ + 'cat /sandbox/.openclaw/openclaw.json 2>/dev/null || true' 2>&1) || true + + if printf '%s' "$config_dump" | python3 -c ' +import json, sys +try: + cfg = json.load(sys.stdin) +except Exception: + sys.exit(2) +search = (((cfg or {}).get("tools") or {}).get("web") or {}).get("search") or {} +if search.get("provider") != "duckduckgo": + sys.exit(3) +if "apiKey" in search or "api_key" in search: + sys.exit(4) +sys.exit(0) +' >/dev/null 2>&1; then + pass "D3: openclaw.json has provider=duckduckgo with no apiKey/api_key field" + else + fail "D3: openclaw.json either is unparseable, missing the duckduckgo provider, or carries an unexpected apiKey field" + fi +} + +# D4a — real DuckDuckGo search via openclaw agent. +check_real_ddg_search_via_agent() { + local session_id raw ssh_cfg reply rc=0 ssh_cmd + if [ -z "${NVIDIA_API_KEY:-}" ]; then + skip "D4a: NVIDIA_API_KEY not set — skipping agent web-search turn" + return + fi + session_id="e2e-ddg-agent-$(date +%s)-$$" + ssh_cfg="$(mktemp)" + + if ! openshell sandbox ssh-config "$SANDBOX_NAME" >"$ssh_cfg" 2>/dev/null; then + rm -f "$ssh_cfg" + fail "D4a: agent web-search turn — could not get SSH config" + return + fi + + ssh_cmd="openclaw agent --agent main --json --session-id '${session_id}' -m 'Use the web search tool to find one result for the query: NVIDIA. Reply with only the title of the top result.'" + raw=$(run_with_timeout 120 ssh -F "$ssh_cfg" \ + -o StrictHostKeyChecking=no \ + -o UserKnownHostsFile=/dev/null \ + -o ConnectTimeout=10 \ + -o LogLevel=ERROR \ + "openshell-${SANDBOX_NAME}" \ + "$ssh_cmd" \ + 2>/dev/null) || rc=$? + rm -f "$ssh_cfg" + + if printf '%s' "$raw" | grep -qiE "SsrFBlockedError|Blocked hostname|ECONNREFUSED|EAI_AGAIN|gateway unavailable|network connection error"; then + fail "D4a: agent web-search failed with provider/transport error (exit ${rc}): ${raw:0:300}" + return + fi + + reply=$(printf '%s' "$raw" | parse_openclaw_agent_text 2>/dev/null) || true + + if [ "$rc" -eq 0 ] && printf '%s' "$reply" | grep -qiE "nvidia|geforce|cuda|gpu"; then + pass "D4a: openclaw agent web-search returned a recognizable DuckDuckGo result" + else + fail "D4a: agent web-search did not return a recognizable DuckDuckGo result (exit ${rc}, reply='${reply:0:200}')" + fi +} + +# D4b — real DuckDuckGo search via curl from inside the sandbox. Uses the +# keyless lite endpoint; HTTP 200 with a non-empty body proves egress is +# permitted by the duckduckgo preset and that no auth header is required. +check_real_ddg_search_via_curl() { + local response status_code body rc=0 + response=$(openshell sandbox exec --name "$SANDBOX_NAME" -- sh -lc \ + "curl -sS --max-time 20 -A 'Mozilla/5.0 (NemoClaw E2E)' -G 'https://lite.duckduckgo.com/lite/' \ + --data-urlencode 'q=NVIDIA' \ + -w '\nHTTP_STATUS:%{http_code}\n'" \ + 2>&1) || rc=$? + + status_code=$(printf '%s' "$response" | grep -m1 -oE 'HTTP_STATUS:[0-9]+' | head -1 | cut -d: -f2) + body=$(printf '%s' "$response" | sed '/^HTTP_STATUS:/d') + + if [ "$status_code" = "200" ]; then + if printf '%s' "$body" | grep -qiE "nvidia|geforce|cuda|gpu"; then + pass "D4b: real DuckDuckGo search via curl returned HTTP 200 with NVIDIA-related content" + else + fail "D4b: HTTP 200 but body had no NVIDIA-related content (head: $(printf '%s' "${body:0:200}"))" + fi + elif [ "$status_code" = "000" ] || [ -z "$status_code" ]; then + fail "D4b: curl never completed an HTTP transaction — check curl is in duckduckgo.yaml binaries allowlist. ${response:0:300}" + else + fail "D4b: unexpected HTTP status '${status_code:-}' from DuckDuckGo (exit $rc)" + fi +} + +trap destroy_sandbox_best_effort EXIT + +echo "" +echo "============================================================" +echo " DuckDuckGo Search E2E" +echo " $(date)" +echo "============================================================" + +section "Phase 0: Prerequisites" +if ! docker info >/dev/null 2>&1; then + fail "Docker is not running" + summary +fi +pass "Docker is running" + +if ! command -v python3 >/dev/null 2>&1; then + fail "python3 not found" + summary +fi +pass "python3 is available" + +load_shell_path +info "Repo: $REPO" +info "Sandbox: $SANDBOX_NAME" + +section "Phase 1: Non-interactive onboard with DuckDuckGo (experimental)" +run_onboard_with_duckduckgo + +section "Phase 2: DuckDuckGo preset is applied to the sandbox" +check_duckduckgo_preset_applied + +section "Phase 3: No API key is emitted for DuckDuckGo" +check_no_api_key_emitted + +section "Phase 4a: Real DuckDuckGo search via openclaw agent" +check_real_ddg_search_via_agent + +section "Phase 4b: Real DuckDuckGo search via curl from inside the sandbox" +check_real_ddg_search_via_curl + +trap - EXIT +destroy_sandbox_best_effort +summary diff --git a/test/generate-openclaw-config.test.ts b/test/generate-openclaw-config.test.ts index 1c13adba21b..05a16136c0b 100644 --- a/test/generate-openclaw-config.test.ts +++ b/test/generate-openclaw-config.test.ts @@ -908,6 +908,36 @@ describe("generate-openclaw-config.mts: config generation", () => { }); }); + it("emits the DuckDuckGo provider with no apiKey when NEMOCLAW_WEB_SEARCH_PROVIDER=duckduckgo", () => { + const config = runConfigScript({ + NEMOCLAW_WEB_SEARCH_ENABLED: "1", + NEMOCLAW_WEB_SEARCH_PROVIDER: "duckduckgo", + }); + expect(config.tools?.web?.search).toEqual({ + enabled: true, + provider: "duckduckgo", + }); + expect((config.tools?.web?.search as { apiKey?: string })?.apiKey).toBeUndefined(); + }); + + it("falls back to Brave when NEMOCLAW_WEB_SEARCH_PROVIDER is unset or unknown", () => { + const unset = runConfigScript({ NEMOCLAW_WEB_SEARCH_ENABLED: "1" }); + expect(unset.tools?.web?.search).toEqual({ + enabled: true, + provider: "brave", + apiKey: "openshell:resolve:env:BRAVE_API_KEY", + }); + const unknown = runConfigScript({ + NEMOCLAW_WEB_SEARCH_ENABLED: "1", + NEMOCLAW_WEB_SEARCH_PROVIDER: "bing", + }); + expect(unknown.tools?.web?.search).toEqual({ + enabled: true, + provider: "brave", + apiKey: "openshell:resolve:env:BRAVE_API_KEY", + }); + }); + it("omits web search when env is not set", () => { const config = runConfigScript(); expect(config.tools?.toolSearch).toBe(true); diff --git a/test/onboard-brave-validation.test.ts b/test/onboard-brave-validation.test.ts index 054c532e644..f78c1b5bc53 100644 --- a/test/onboard-brave-validation.test.ts +++ b/test/onboard-brave-validation.test.ts @@ -407,6 +407,75 @@ const { configureWebSearch } = require(${onboardPath}); }); }); +describe("configureWebSearch (DuckDuckGo non-interactive)", () => { + function runDuckDuckGoConfigure(envOverride: NodeJS.ProcessEnv): { + exitCode: number; + payload: { result: { fetchEnabled: boolean; provider?: string } | null; logs: string[] }; + } { + const repoRoot = path.join(import.meta.dirname, ".."); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-ddg-")); + const scriptPath = path.join(tmpDir, "configure-web-search-ddg.js"); + const outputPath = path.join(tmpDir, "outcome.json"); + const onboardPath = JSON.stringify(path.join(repoRoot, "dist", "lib", "onboard.js")); + + fs.writeFileSync( + scriptPath, + ` +const fs = require("node:fs"); +const logs = []; +console.log = (...args) => logs.push(args.join(" ")); +const { configureWebSearch } = require(${onboardPath}); +(async () => { + const result = await configureWebSearch(null); + fs.writeFileSync(${JSON.stringify(outputPath)}, JSON.stringify({ result, logs })); +})().catch((error) => { + console.error(error); + process.exit(1); +}); +`, + ); + + try { + const result = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + encoding: "utf-8", + env: { + ...process.env, + HOME: tmpDir, + NEMOCLAW_NON_INTERACTIVE: "1", + ...envOverride, + }, + }); + const payload = JSON.parse(fs.readFileSync(outputPath, "utf-8")); + return { exitCode: typeof result.status === "number" ? result.status : -1, payload }; + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + } + + it("selects duckduckgo when NEMOCLAW_EXPERIMENTAL=1 and NEMOCLAW_WEB_SEARCH_PROVIDER=duckduckgo", () => { + const { exitCode, payload } = runDuckDuckGoConfigure({ + NEMOCLAW_EXPERIMENTAL: "1", + NEMOCLAW_WEB_SEARCH_PROVIDER: "duckduckgo", + BRAVE_API_KEY: "", + }); + + expect(exitCode).toBe(0); + expect(payload.result).toEqual({ fetchEnabled: true, provider: "duckduckgo" }); + }); + + it("ignores NEMOCLAW_WEB_SEARCH_PROVIDER=duckduckgo without the experimental flag", () => { + const { exitCode, payload } = runDuckDuckGoConfigure({ + NEMOCLAW_EXPERIMENTAL: "", + NEMOCLAW_WEB_SEARCH_PROVIDER: "duckduckgo", + BRAVE_API_KEY: "", + }); + + expect(exitCode).toBe(0); + expect(payload.result).toBeNull(); + }); +}); + describe("configureWebSearch (interactive)", () => { it("returns to the Brave Search enable prompt when backing out of the API key prompt", () => { const { exitCode, payload } = runInteractiveConfigureWebSearch({ @@ -420,7 +489,7 @@ describe("configureWebSearch (interactive)", () => { expect(payload.errors).toEqual([]); expect(payload.saved.every((entry) => entry.value !== "back")).toBe(true); expect( - payload.prompts.filter((entry) => /Enable Brave Web Search\?/.test(entry.message)), + payload.prompts.filter((entry) => /Enable Web Search\?/.test(entry.message)), ).toHaveLength(2); expect( payload.prompts.some( diff --git a/test/onboard-policy-suggestions.test.ts b/test/onboard-policy-suggestions.test.ts index 0b2808bb17c..a5fe94644fe 100644 --- a/test/onboard-policy-suggestions.test.ts +++ b/test/onboard-policy-suggestions.test.ts @@ -39,6 +39,7 @@ describe("onboard policy preset suggestions", () => { "huggingface", "brew", "brave", + "duckduckgo", "slack", "discord", "telegram", @@ -237,6 +238,28 @@ describe("onboard policy preset suggestions", () => { expect(suggestions).toEqual(["npm", "pypi", "huggingface", "brew", "brave"]); }); + it("adds DuckDuckGo to tier defaults and prunes Brave when provider is duckduckgo", () => { + const suggestions = computeSetupPresetSuggestions("balanced", { + enabledChannels: [], + knownPresetNames: known, + webSearchConfig: { fetchEnabled: true, provider: "duckduckgo" }, + webSearchSupported: true, + }); + expect(suggestions).toContain("duckduckgo"); + expect(suggestions).not.toContain("brave"); + }); + + it("prunes a stale DuckDuckGo preset when provider is brave", () => { + const suggestions = computeSetupPresetSuggestions("balanced", { + enabledChannels: [], + knownPresetNames: known, + webSearchConfig: { fetchEnabled: true, provider: "brave" }, + webSearchSupported: true, + }); + expect(suggestions).toContain("brave"); + expect(suggestions).not.toContain("duckduckgo"); + }); + it("filters tier defaults to known presets for agent-specific onboarding", () => { const suggestions = computeSetupPresetSuggestions("balanced", { enabledChannels: [], diff --git a/test/policies.test.ts b/test/policies.test.ts index 68ce70a6917..0cd4c6589c9 100644 --- a/test/policies.test.ts +++ b/test/policies.test.ts @@ -145,11 +145,21 @@ selectFromList(items, options) describe("policies", () => { describe("listPresets", () => { + it("returns all 23 presets", () => { + const presets = policies.listPresets(); + expect(presets.length).toBe(23); + }); + it("includes the OpenClaw OTEL diagnostics preset", () => { const presets = policies.listPresets(); expect(presets.map((preset) => preset.name)).toContain("openclaw-diagnostics-otel-local"); }); + it("includes the DuckDuckGo web-search preset", () => { + const presets = policies.listPresets(); + expect(presets.map((preset) => preset.name)).toContain("duckduckgo"); + }); + it("each preset has name and description", () => { for (const p of policies.listPresets()) { expect(p.name).toBeTruthy(); @@ -167,6 +177,7 @@ describe("policies", () => { "brew", "claude-code", "discord", + "duckduckgo", "github", "huggingface", "jira",