diff --git a/packages/core/src/tool/plugin/websearch.ts b/packages/core/src/tool/plugin/websearch.ts index 5c28858d1cf9..45a1dfbf53ef 100644 --- a/packages/core/src/tool/plugin/websearch.ts +++ b/packages/core/src/tool/plugin/websearch.ts @@ -3,7 +3,8 @@ export * as WebSearchTool from "./websearch.js" import type { Context } from "@opencode/plugin/effect/plugin" import type { SessionHooks } from "@opencode/plugin/effect/session" import { ToolFailure } from "@opencode/ai/effect" -import { Effect, Schema, Semaphore } from "effect" +import { isRecord } from "@opencode/util/record" +import { Effect, Option, Schema, Semaphore, type JsonSchema } from "effect" import { HttpClientError } from "effect/http" import { Config } from "../../config.js" import { ConfigEntryObserver } from "../../config/plugin/entry-observer.js" @@ -22,10 +23,15 @@ const httpErrors = new Map([ export const description = `Search the web using the user's selected search integration. Use this for current information beyond knowledge cutoff. +Pass \`providerID\` to pick the search provider for this call; the accepted values are listed in that parameter. Omit it to use the user's saved or random provider, and put the provider there rather than in the query text. + The current year is ${new Date().getFullYear()}. Use this year when searching for recent information or current events.` export const Input = Schema.Struct({ query: Schema.String.annotate({ description: "Websearch query" }), + providerID: Schema.optionalKey(WebSearch.ID).annotate({ + description: "Search provider for this call. Omit to use the user's saved or random provider.", + }), }) const Output = Schema.Array( @@ -56,13 +62,43 @@ export const Plugin = { output: Output, execute: (input, context) => Effect.gen(function* () { - yield* permission.assert({ + const requested = input.providerID + const approval = { action: name, resources: [input.query], save: ["*"], metadata: input, ...Permission.invocation(context), - }) + } + let needsConsent = false + if (requested !== undefined) { + const providers = (yield* ctx.websearch.providers()).data + // A bad ID fails before the approval prompt so it cannot record a saved permission, but a policy + // deny still outranks it: `assertNotDenied` evaluates the rules without asking the user. + if (!providers.some((provider) => provider.id === requested)) { + yield* permission.assertNotDenied(approval) + return yield* new ToolFailure({ + message: `Unknown web search provider "${requested}". Available: ${providers.map((provider) => provider.id).join(", ") || "none"}.`, + }) + } + // A saved "disabled" choice outranks a per-call provider; no saved choice still needs consent. + const saved = yield* websearch.default().pipe(Effect.option) + if (Option.isNone(saved)) { + yield* permission.assertNotDenied(approval) + return yield* new WebSearch.DisabledError() + } + needsConsent = saved.value === undefined + // A provider the user saved outranks a per-call request: only `random` (or no choice yet) leaves the + // routing to the model. Otherwise the request has to agree with the user's choice. + const pinned = yield* websearch.selection() + if (pinned !== undefined && pinned !== false && pinned !== "random" && pinned !== requested) { + yield* permission.assertNotDenied(approval) + return yield* new ToolFailure({ + message: `Web search is pinned to "${pinned}" by the user. Omit providerID or pass "${pinned}".`, + }) + } + } + yield* permission.assert(approval) const search = (providerID?: WebSearch.ID) => websearch.query( { ...input, providerID }, @@ -71,7 +107,11 @@ export const Plugin = { onProvider: (provider) => context.progress({ provider: provider.id }), }, ) - const result = yield* search().pipe( + // A pinned provider is used as-is: no failover, and consent never overrides it. + const attempt: Effect.Effect = needsConsent + ? Effect.fail(new WebSearch.ProviderRequiredError()) + : search(requested) + const result = yield* attempt.pipe( Effect.catchTag("WebSearch.ProviderRequired", () => { return providerSelectionLock .withPermit( @@ -150,7 +190,8 @@ export const Plugin = { duration: "1 minute", orElse: () => Effect.fail(new Error("Web search cancelled")), }), - Effect.flatMap(search), + // Consent never overrides the provider the model pinned for this call. + Effect.flatMap((providerID) => search(requested ?? providerID)), ) }), ) @@ -174,6 +215,8 @@ export const Plugin = { return { output, content, metadata: { provider: result.providerID } } }).pipe( Effect.mapError((error) => { + // The tool already produced a precise, model-facing message. + if (error instanceof ToolFailure) return error const fallback = `Unable to search the web for ${input.query}` if (!Schema.is(WebSearch.RequestError)(error)) return new ToolFailure({ message: fallback, error }) const status = HttpClientError.isHttpClientError(error.cause) ? error.cause.response?.status : undefined @@ -197,8 +240,27 @@ export const Plugin = { Effect.as(false), Effect.catchTag("WebSearch.Disabled", () => Effect.succeed(true)), ) + if (disabled) return delete event.tools[name] + const providers = yield* websearch.providers() // Policy can remove every provider, and the model shouldn't be offered a tool that can't search. - if (disabled || (yield* websearch.providers()).length === 0) delete event.tools[name] + if (providers.length === 0) return delete event.tools[name] + // The accepted ids are published here because a tool definition converts its schema once at registration. + // With `full_codemode` enabled this tool moves to the Code Mode catalog, which renders and caches its own + // schema from the registry, so the enum only reaches the model for a direct tool call; an unknown id still + // fails with the list of available ones below. + const tool = event.tools[name] + const properties = tool?.input.properties + if (!tool || !isRecord(properties)) return + tool.input = { + ...tool.input, + properties: { + ...properties, + providerID: { + type: "string", + enum: Array.from(new Set(providers.map((provider) => provider.id))).toSorted(), + }, + } satisfies JsonSchema.JsonSchema, + } }) yield* ctx.session.hook("context", hook) yield* ctx.session.hook("compaction", hook) diff --git a/packages/core/src/websearch.ts b/packages/core/src/websearch.ts index eeb593730507..0aff00d7094f 100644 --- a/packages/core/src/websearch.ts +++ b/packages/core/src/websearch.ts @@ -57,6 +57,8 @@ export type Error = ProviderRequiredError | ProviderNotFoundError | DisabledErro export interface Interface extends State.Transformable { readonly providers: () => Effect.Effect readonly default: () => Effect.Effect + /** The saved choice: a provider id, `"random"`, `false` when disabled, or `undefined` before consent. */ + readonly selection: () => Effect.Effect readonly select: (selection: Selection) => Effect.Effect readonly query: ( input: Input, @@ -178,11 +180,18 @@ const layer = Layer.effect( const provider = yield* defaultProvider(yield* selection()) return provider && { id: provider.id, name: provider.name } }), + selection: Effect.fn("WebSearch.selectionValue")(function* () { + return yield* selection() + }), select: Effect.fn("WebSearch.select")(function* (selection) { yield* kv.set(ProviderKey, selection) }), query: Effect.fn("WebSearch.query")(function* (input, options) { - const choice = input.providerID ? undefined : yield* selection() + // The saved "disabled" choice outranks a per-call provider. An unset choice stays allowed, because + // asking for consent is the tool's job. + const saved = yield* selection() + if (saved === false) return yield* new DisabledError() + const choice = input.providerID ? undefined : saved let provider = input.providerID ? yield* requireProvider(state.get().providers, input.providerID) : yield* defaultProvider(choice) diff --git a/packages/core/test/fixture/policy.ts b/packages/core/test/fixture/policy.ts index 09c6387a756c..e2fc1ec40a82 100644 --- a/packages/core/test/fixture/policy.ts +++ b/packages/core/test/fixture/policy.ts @@ -87,6 +87,7 @@ export const registerIntegrationPolicy = Effect.fn(function* (input: { WebSearch.Service.of({ providers: () => Effect.die("unused WebSearch.providers"), default: () => Effect.die("unused WebSearch.default"), + selection: () => Effect.die("unused WebSearch.selection"), select: () => Effect.die("unused WebSearch.select"), query: () => Effect.die("unused WebSearch.query"), transform: () => Effect.succeed({ dispose: Effect.void }), diff --git a/packages/core/test/tool-websearch.test.ts b/packages/core/test/tool-websearch.test.ts index c9043eba6ffb..04d06d2e4c8e 100644 --- a/packages/core/test/tool-websearch.test.ts +++ b/packages/core/test/tool-websearch.test.ts @@ -89,6 +89,7 @@ const setup = Effect.gen(function* () { fixture.events.push("permission") fixture.assertions.push(input) }), + assertNotDenied: () => Effect.void, }), ), WebSearch.node.replace(Layer.succeed(WebSearch.Service, websearch)), @@ -192,6 +193,106 @@ describe("WebSearchTool registration", () => { }), ) + it.effect("uses the provider the model picks when the saved choice is random", () => + Effect.gen(function* () { + const fixture = yield* setup + yield* fixture.websearch.select("random") + + expect( + yield* executeTool(fixture.registry, { + sessionID, + ...toolIdentity, + call: { + type: "tool-call", + id: "call-provider", + name: "websearch", + input: { query: "effect", providerID: "parallel" }, + }, + }), + ).toMatchObject({ status: "completed", metadata: { provider: "parallel" } }) + expect(fixture.formRequests).toEqual([]) + expect(fixture.websearch.queries).toEqual([{ query: "effect", providerID: WebSearch.ID.make("parallel") }]) + expect(yield* fixture.kv.get(WebSearch.ProviderKey)).toBe("random") + }), + ) + + it.effect("keeps a provider the user pinned instead of the one the model asks for", () => + Effect.gen(function* () { + const fixture = yield* setup + yield* fixture.websearch.select(WebSearch.ID.make("exa")) + + expect( + yield* executeTool(fixture.registry, { + sessionID, + ...toolIdentity, + call: { + type: "tool-call", + id: "call-pinned", + name: "websearch", + input: { query: "effect", providerID: "parallel" }, + }, + }), + ).toEqual({ + status: "error", + error: { + type: "tool.execution", + message: 'Web search is pinned to "exa" by the user. Omit providerID or pass "exa".', + }, + }) + expect(fixture.websearch.queries).toEqual([]) + expect(yield* fixture.kv.get(WebSearch.ProviderKey)).toBe(WebSearch.ID.make("exa")) + }), + ) + + it.effect("rejects a provider that is not available before searching", () => + Effect.gen(function* () { + const fixture = yield* setup + + expect( + yield* executeTool(fixture.registry, { + sessionID, + ...toolIdentity, + call: { + type: "tool-call", + id: "call-missing", + name: "websearch", + input: { query: "effect", providerID: "missing" }, + }, + }), + ).toEqual({ + status: "error", + error: { + type: "tool.execution", + message: 'Unknown web search provider "missing". Available: exa, parallel.', + }, + }) + expect(fixture.events).toEqual([]) + expect(fixture.formRequests).toEqual([]) + }), + ) + + it.effect("asks for consent before the first search with a provider the model picks", () => + Effect.gen(function* () { + const fixture = yield* setup + fixture.formResponse = { status: "answered", answer: { choice: "allow" } } + + expect( + yield* executeTool(fixture.registry, { + sessionID, + ...toolIdentity, + call: { + type: "tool-call", + id: "call-provider-consent", + name: "websearch", + input: { query: "effect", providerID: "parallel" }, + }, + }), + ).toMatchObject({ status: "completed", metadata: { provider: "parallel" } }) + expect(fixture.formRequests).toHaveLength(1) + expect(fixture.websearch.queries).toEqual([{ query: "effect", providerID: WebSearch.ID.make("parallel") }]) + }), + ) + it.effect("uses the concise no-results fallback", () => Effect.gen(function* () { const fixture = yield* setup @@ -358,6 +459,35 @@ describe("WebSearchTool registration", () => { }), ) + it.effect("lists the live provider ids in the schema the model sees", () => + Effect.gen(function* () { + contextHooks.length = 0 + const fixture = yield* setup + const definition = (yield* toolDefinitions(fixture.registry)).find((tool) => tool.name === "websearch") + const schema = () => + Effect.gen(function* () { + const event = { + tools: { + [WebSearchTool.name]: { + description: definition?.description ?? "", + input: structuredClone(definition?.inputSchema ?? {}), + }, + }, + } + yield* Effect.forEach(contextHooks, (hook) => hook(event as unknown as SessionContext)) + return event.tools[WebSearchTool.name]?.input as { + required?: ReadonlyArray + properties: Record }> + } + }) + + expect((yield* schema()).properties.providerID?.enum).toEqual(["exa", "parallel"]) + expect((yield* schema()).required).toEqual(["query"]) + // An unchanged provider set emits the same schema, so the prompt prefix stays stable. + expect(JSON.stringify(yield* schema())).toBe(JSON.stringify(yield* schema())) + }), + ) + it.effect("offers the tool to the model only while a provider remains", () => Effect.gen(function* () { contextHooks.length = 0 diff --git a/packages/core/test/websearch.test.ts b/packages/core/test/websearch.test.ts index 59f0c32d1055..6387d2d44e26 100644 --- a/packages/core/test/websearch.test.ts +++ b/packages/core/test/websearch.test.ts @@ -586,6 +586,19 @@ describe("WebSearch", () => { ) }) + it.effect("keeps an explicit provider disabled when web search is turned off", () => + Effect.gen(function* () { + const exa = yield* register("exa") + const websearch = yield* WebSearch.Service + yield* websearch.select(false) + + expect(yield* websearch.query({ query: "effect", providerID: exa.providerID }).pipe(Effect.flip)).toBeInstanceOf( + WebSearch.DisabledError, + ) + expect(exa.calls).toEqual([]) + }), + ) + it.effect("fails when web search is explicitly disabled", () => Effect.gen(function* () { yield* register("exa") diff --git a/services/site/src/docs/content/tools.mdx b/services/site/src/docs/content/tools.mdx index 6f7dac76f35b..7f7df7780493 100644 --- a/services/site/src/docs/content/tools.mdx +++ b/services/site/src/docs/content/tools.mdx @@ -148,7 +148,8 @@ URL as its resource. ### Websearch `websearch` searches the selected integration for current information. Its -input is a search `query`. +input is a search `query` and an optional `providerID`; the accepted ids are +listed in that parameter's schema. ```text Search the web for the latest Bun release notes. diff --git a/services/site/src/docs/content/websearch.mdx b/services/site/src/docs/content/websearch.mdx index c03848e33654..d81602274ed4 100644 --- a/services/site/src/docs/content/websearch.mdx +++ b/services/site/src/docs/content/websearch.mdx @@ -32,6 +32,15 @@ $ TAVILY_API_KEY=your-key opencode Set a provider in `opencode.jsonc` to skip the selection prompt. +The model can also pick the provider for a single search by passing `providerID`; +the ids available in the current session are listed in that parameter's schema. +A pinned search uses only that provider, does not fall back to another one when +rate limited, and never changes your default. + +If you saved a specific provider, that choice wins: `providerID` must match it, +and a different id is refused so a search never leaves the provider you chose. +With `"random"` (or before you have chosen) the model is free to pick. + ```jsonc title="opencode.jsonc" { "$schema": "https://opencode.ai/config.json",