Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat: optional model web search

Samrat Talukdarf95d928da844
diff --git a/apps/server/src/omnirush-gateway-broker.ts b/apps/server/src/omnirush-gateway-broker.ts
index 79cf2371..fd1bd31c 100644
--- a/apps/server/src/omnirush-gateway-broker.ts
+++ b/apps/server/src/omnirush-gateway-broker.ts
@@ -1680,6 +1680,8 @@ export class OmniRushGatewayBroker {
...(isRecord(payload.auto_compact) && typeof payload.auto_compact.enabled === "boolean" && typeof payload.auto_compact.after_turns === "number"
? { auto_compact: { enabled: payload.auto_compact.enabled, after_turns: payload.auto_compact.after_turns, ...(typeof payload.auto_compact.min_context_tokens === "number" ? { min_context_tokens: payload.auto_compact.min_context_tokens } : {}) } }
: {}),
+ // The model's own web search (web-search.ts reads it; absent is off).
+ ...(isRecord(payload.web_search) ? { web_search: payload.web_search } : {}),
};
} catch {
return null;
diff --git a/apps/server/src/omnirush-model-catalog.ts b/apps/server/src/omnirush-model-catalog.ts
index e5134304..a8989df9 100644
--- a/apps/server/src/omnirush-model-catalog.ts
+++ b/apps/server/src/omnirush-model-catalog.ts
@@ -20,6 +20,7 @@ import { join } from "node:path";
import { runtimeStorageDir } from "./runtime-db.js";
import type { ServerConfig } from "./types.js";
import { writeFileAtomic } from "./atomic-write.js";
+import { modelHasWebSearch, type WebSearchSwitch } from "./web-search.js";
/** Every effort a catalog model may list, lowest first. */
export const OMNIRUSH_MODEL_EFFORTS = ["none", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
@@ -218,7 +219,7 @@ export async function clearOmniRushModelCatalog(config: ServerConfig): Promise<v
* marked disabled. `deprecated` is never passed on: the engine deletes
* deprecated models, which would strand the sessions pinned to one.
*/
-export function engineModelsFromCatalog(catalog: OmniRushModelCatalog): Record<string, Record<string, unknown>> {
+export function engineModelsFromCatalog(catalog: OmniRushModelCatalog, webSearch: WebSearchSwitch | null = null): Record<string, Record<string, unknown>> {
return Object.fromEntries(catalog.map((model) => [model.id, {
name: model.display_name,
reasoning: model.capabilities.reasoning,
@@ -242,6 +243,9 @@ export function engineModelsFromCatalog(catalog: OmniRushModelCatalog): Record<s
},
...(model.family && model.family !== PROVIDER_FAMILY ? { family: model.family } : {}),
...(model.status === "beta" ? { status: "beta" } : {}),
+ // The model's own web search (web-search.ts): the engine declares the
+ // provider's web_search tool for it. Off, no `options` key at all.
+ ...(modelHasWebSearch(model, webSearch) ? { options: { hostedWebSearch: { searchContextSize: webSearch!.searchContextSize } } } : {}),
}]));
}
diff --git a/apps/server/src/omnirush-runtime-config.ts b/apps/server/src/omnirush-runtime-config.ts
index 7e7acd97..55f316c2 100644
--- a/apps/server/src/omnirush-runtime-config.ts
+++ b/apps/server/src/omnirush-runtime-config.ts
@@ -55,6 +55,7 @@ import {
type OmniRushModelCatalog,
} from "./omnirush-model-catalog.js";
import { writeFileAtomic } from "./atomic-write.js";
+import { webSearchSetting, type WebSearchSwitch } from "./web-search.js";
import { boxServiceFor } from "./box/desktop.js";
import { engineConfig as withBoxEngineConfig } from "./box/launch.js";
import {
@@ -111,7 +112,7 @@ export function omnirushGatewayConfigured(config: ServerConfig | undefined): boo
return resolveConfiguredInternalGatewayRuntime(config) !== undefined;
}
-function internalGatewayProvider(runtime: InternalGatewayRuntime, catalog: OmniRushModelCatalog): Record<string, unknown> {
+function internalGatewayProvider(runtime: InternalGatewayRuntime, catalog: OmniRushModelCatalog, webSearch: WebSearchSwitch | null): Record<string, unknown> {
return {
// The native OpenAI provider uses the Responses API, which preserves
// reasoning summaries, tool calls, and delegated task events. The generic
@@ -123,7 +124,7 @@ function internalGatewayProvider(runtime: InternalGatewayRuntime, catalog: OmniR
options: { baseURL: runtime.baseUrl },
// Only models come from the account's catalog; the provider fields above
// never do, so a catalog cannot route the engine past the local broker.
- models: engineModelsFromCatalog(catalog),
+ models: engineModelsFromCatalog(catalog, webSearch),
};
}
@@ -144,6 +145,8 @@ export async function buildOmniRushRuntimeConfigObject(
internalGateway && config ? await readOmniRushModelCatalog(config) : undefined,
config ? omnirushRuntimeSkillsDir(config) : undefined,
config ? omnirushBestPracticesSkillsDir(config) : undefined,
+ // The model's own web search: the server's switch as last seen (web-search.ts).
+ config ? webSearchSetting({ env: process.env, stateDir: runtimeStorageDir(config) }) : null,
);
// The Linux sandbox (box/): the engine's shell is the box shell and the box plugin is
// loaded once any workspace may use a box; every other project's commands run natively
@@ -219,6 +222,7 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(
catalog: OmniRushModelCatalog = builtinOmniRushModelCatalog(),
skillsDir?: string,
bestPracticesDir?: string,
+ webSearch: WebSearchSwitch | null = null,
): Record<string, unknown> {
const disabledProviders = runtimeDisabledProviderList(runtimeConfig);
// OMNIRUSH_APPROVALS in the server environment wins over the persisted setting.
@@ -233,7 +237,7 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(
const provider = {
...runtimeProviderMap(runtimeConfig),
...(internalGateway
- ? { [INTERNAL_PROVIDER_ID]: internalGatewayProvider(internalGateway, catalog) }
+ ? { [INTERNAL_PROVIDER_ID]: internalGatewayProvider(internalGateway, catalog, webSearch) }
: {}),
};
const ownProviders = Object.keys(provider).filter((id) => /^(?:lpr_|omnirush$)/i.test(id));
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 79dbe444..f54e16b2 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -180,6 +180,7 @@ import { boxHome } from "./box/common.js";
import { buildathonProjectsFile, reproStateFromBody, writeReproState } from "./buildathon-repro.js";
import { prepareBoxInstallLog } from "./box/install-log.js";
import { rememberServerDefault, watchServerDefault } from "./box/launch.js";
+import { rememberWebSearchSwitch, watchWebSearchSwitch } from "./web-search.js";
import { normalizeBackend } from "./box/backends/index.js";
import { buildOmniRushRuntimeConfigObject, omnirushGatewayConfigured, omnirushRuntimeConfigFilePath, writeOmniRushRuntimeConfigFile } from "./omnirush-runtime-config.js";
import { assertMcpAllowed, mcpAllowed, mcpPolicyForConfig, MCP_DISABLED_MESSAGE } from "./mcp-policy.js";
@@ -1228,12 +1229,23 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {
// image starts downloading), and the server's default (local_box) is read for the engine config.
const boxes = boxServiceFor(config, (level, message, attributes) => logger.log(level, message, attributes));
let stopBoxDefaultWatch: () => void = () => {};
+ let stopWebSearchWatch: () => void = () => {};
if (gatewayBroker.enabled) {
// Read before the first plan and the engine's first config (at most 1.5 s, else the last answer is
// used until it comes): a switch flipped or rolled back on the server applies at this start.
const read = gatewayBroker.sessionUploadCapabilities().then((capabilities) => rememberServerDefault(runtimeStorageDir(config), capabilities)).catch(() => false);
- const inTime = await Promise.race([read.then(() => true), new Promise<false>((resolvePromise) => setTimeout(() => resolvePromise(false), 1_500).unref?.())]);
+ // The model's own web search (web-search.ts), from the same answer. Strict: a failed read keeps
+ // the last answer, while an answer without the block (an older server) turns it off.
+ const readWebSearch = gatewayBroker.sessionUploadCapabilities({ strict: true }).then((capabilities) => rememberWebSearchSwitch(runtimeStorageDir(config), capabilities)).catch(() => false);
+ const inTime = await Promise.race([Promise.all([read, readWebSearch]).then(() => true), new Promise<false>((resolvePromise) => setTimeout(() => resolvePromise(false), 1_500).unref?.())]);
if (!inTime) void read.then((changed) => (changed ? applyServerBoxDefault(config, boxes) : undefined)).catch(() => undefined);
+ if (!inTime) void readWebSearch.then((changed) => (changed ? applyBoxEngineConfig(config, "web_search") : undefined)).catch(() => undefined);
+ stopWebSearchWatch = watchWebSearchSwitch({
+ stateDir: runtimeStorageDir(config),
+ read: () => gatewayBroker.sessionUploadCapabilities({ strict: true }),
+ apply: () => applyBoxEngineConfig(config, "web_search"),
+ everyMs: BOX_DEFAULT_REFRESH_MS,
+ });
// Read again while the app stays open (from the capabilities cache: at most one request per its
// TTL), so a switch flipped on the server reaches an app started before it without a restart.
stopBoxDefaultWatch = watchServerDefault({
@@ -1606,6 +1618,7 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {
});
} catch (error) {
stopBoxDefaultWatch();
+ stopWebSearchWatch();
bestPracticesReloads.stop();
// First, and synchronously: archive part uploads in flight are aborted now, not after the other shutdown steps.
const captureStopped = capture.stop();
@@ -1696,6 +1709,7 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {
// Before them, each chat in a box gets its last checkpoint (bounded; only when chats ran in a
// box this run, and the account answers it is still stored within a second).
stopBoxDefaultWatch();
+ stopWebSearchWatch();
const archiveFinals = accountStillStored();
if (boxes.hasChats() && await Promise.race([archiveFinals.catch(() => false), new Promise<false>((resolvePromise) => setTimeout(() => resolvePromise(false), 1_000).unref?.())])) {
await boxes.finals({ budgetMs: 10_000 }).catch(() => []);
diff --git a/apps/server/src/session-uploader.ts b/apps/server/src/session-uploader.ts
index 1d5af9a0..c4941659 100644
--- a/apps/server/src/session-uploader.ts
+++ b/apps/server/src/session-uploader.ts
@@ -868,6 +868,8 @@ export type TraceCapabilities = {
local_box?: { default: string; max_turn_bytes?: number | null; backends?: string[] | null };
/** Automatic compaction (session-archive/auto-compact.ts): absent is off. */
auto_compact?: { enabled: boolean; after_turns: number; min_context_tokens?: number };
+ /** The model's own web search (web-search.ts): the block as the server sent it; absent is off. */
+ web_search?: Record<string, unknown>;
};
diff --git a/apps/server/src/web-search.test.ts b/apps/server/src/web-search.test.ts
new file mode 100644
index 00000000..15151994
--- /dev/null
+++ b/apps/server/src/web-search.test.ts
@@ -0,0 +1,131 @@
+// The model's own web search (web-search.ts): off unless the environment or
+// the server's switch turns it on; only models with the capability (and on
+// the server's list) get `options.hostedWebSearch`; off, the engine config is
+// byte for byte what it was before.
+import { afterEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { backendCatalogBody } from "./__fixtures__/omnirush-model-catalog.js";
+import { engineModelsFromCatalog, sanitizeOmniRushModelCatalog } from "./omnirush-model-catalog.js";
+import { buildOmniRushRuntimeConfigObjectFromSnapshot } from "./omnirush-runtime-config.js";
+import {
+ WEB_SEARCH_SERVER_FILE,
+ modelHasWebSearch,
+ rememberWebSearchSwitch,
+ watchWebSearchSwitch,
+ webSearchServerSwitch,
+ webSearchSetting,
+} from "./web-search.js";
+
+const dirs: string[] = [];
+function tmp(): string {
+ const dir = mkdtempSync(join(tmpdir(), "omnirush-web-search-"));
+ dirs.push(dir);
+ return dir;
+}
+afterEach(() => {
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
+const catalog = sanitizeOmniRushModelCatalog(backendCatalogBody())!;
+const gateway = { baseUrl: "http://127.0.0.1:48123/omnirush-gateway/v1" };
+const serverBlock = { search_context_size: "medium", models: ["gpt-6-astra", "gpt-6.1-sol", "gpt-6-sol"], clients: ["cli", "desktop"], rollout_percent: 100 };
+
+describe("server switch", () => {
+ test("only an explicit enabled:true block is on; clients and rollout are the server's", () => {
+ expect(webSearchServerSwitch({})).toEqual({ enabled: false, searchContextSize: "medium", models: null });
+ expect(webSearchServerSwitch(null)).toEqual({ enabled: false, searchContextSize: "medium", models: null });
+ expect(webSearchServerSwitch({ web_search: true }).enabled).toBe(false);
+ expect(webSearchServerSwitch({ web_search: { enabled: "true" } }).enabled).toBe(false);
+ expect(webSearchServerSwitch({ web_search: { enabled: true, search_context_size: "huge" } }).searchContextSize).toBe("medium");
+ expect(webSearchServerSwitch({ web_search: { ...serverBlock, enabled: true, models: ["gpt-6-astra", 3, "bad id"] } }).models).toEqual(["gpt-6-astra"]);
+ expect(webSearchServerSwitch({ web_search: { ...serverBlock, enabled: false } }).enabled).toBe(false);
+ expect(webSearchServerSwitch({ web_search: { ...serverBlock, enabled: true, rollout_percent: 0, clients: ["cli"] } }).enabled).toBe(true);
+ });
+
+ test("remembered from every answer (a missing block is off); whether it changed", () => {
+ const dir = tmp();
+ expect(webSearchSetting({ env: {}, stateDir: dir })).toEqual({ enabled: false, source: "default", searchContextSize: "medium", models: null });
+ // The first answer without the block changes nothing.
+ expect(rememberWebSearchSwitch(dir, { schema_versions: [1, 2, 3] })).toBe(false);
+ expect(rememberWebSearchSwitch(dir, { web_search: { ...serverBlock, enabled: true, search_context_size: "high" } })).toBe(true);
+ expect(rememberWebSearchSwitch(dir, { web_search: { ...serverBlock, enabled: true, search_context_size: "high" } })).toBe(false);
+ expect(webSearchSetting({ env: {}, stateDir: dir })).toEqual({ enabled: true, source: "server", searchContextSize: "high", models: serverBlock.models });
+ expect(statSync(join(dir, WEB_SEARCH_SERVER_FILE)).mode & 0o777).toBe(0o600);
+ // No answer at all keeps the last one.
+ expect(rememberWebSearchSwitch(dir, null)).toBe(false);
+ expect(webSearchSetting({ env: {}, stateDir: dir }).enabled).toBe(true);
+ // An older server (no block) turns it off.
+ expect(rememberWebSearchSwitch(dir, { schema_versions: [1, 2, 3] })).toBe(true);
+ expect(webSearchSetting({ env: {}, stateDir: dir }).enabled).toBe(false);
+ // A broken file is no answer.
+ writeFileSync(join(dir, WEB_SEARCH_SERVER_FILE), "{");
+ expect(webSearchSetting({ env: {}, stateDir: dir }).source).toBe("default");
+ });
+
+ test("OMNIRUSH_WEB_SEARCH decides over the server", () => {
+ const dir = tmp();
+ rememberWebSearchSwitch(dir, { web_search: { ...serverBlock, enabled: true } });
+ for (const off of ["0", "off", " OFF ", "false", "no"]) expect(webSearchSetting({ env: { OMNIRUSH_WEB_SEARCH: off }, stateDir: dir }).enabled).toBe(false);
+ rememberWebSearchSwitch(dir, { web_search: { ...serverBlock, enabled: false } });
+ expect(webSearchSetting({ env: { OMNIRUSH_WEB_SEARCH: "1" }, stateDir: dir })).toMatchObject({ enabled: true, source: "env" });
+ });
+
+ test("the watcher applies a change once and keeps the last answer when a read fails", async () => {
+ const dir = tmp();
+ const answers: Array<() => Promise<unknown>> = [
+ async () => ({ web_search: { ...serverBlock, enabled: true } }),
+ async () => { throw new Error("offline"); },
+ async () => ({ web_search: { ...serverBlock, enabled: true } }),
+ ];
+ let applied = 0;
+ const stop = watchWebSearchSwitch({ stateDir: dir, read: () => (answers.shift() ?? (async () => null))(), apply: async () => { applied += 1; }, everyMs: 5 });
+ await new Promise((resolve) => setTimeout(resolve, 80));
+ stop();
+ expect(applied).toBe(1);
+ expect(JSON.parse(readFileSync(join(dir, WEB_SEARCH_SERVER_FILE), "utf8")).enabled).toBe(true);
+ });
+});
+
+describe("engine config", () => {
+ test("models: the capability, then the server's list", () => {
+ const on = { enabled: true, searchContextSize: "medium" as const, models: null };
+ expect(modelHasWebSearch(catalog[0], on)).toBe(true);
+ expect(modelHasWebSearch({ id: "x", capabilities: { ...catalog[0]!.capabilities, web_search: false } }, on)).toBe(false);
+ expect(modelHasWebSearch(catalog[0], { ...on, enabled: false })).toBe(false);
+ expect(modelHasWebSearch(catalog[1], { ...on, models: ["gpt-6-astra"] })).toBe(false);
+ expect(modelHasWebSearch(catalog[0], null)).toBe(false);
+ expect(modelHasWebSearch(undefined, on)).toBe(false);
+ });
+
+ test("off (no switch, an off switch, an off override): byte for byte the config without web search", () => {
+ const before = JSON.stringify(buildOmniRushRuntimeConfigObjectFromSnapshot({}, gateway, {}, catalog));
+ const dir = tmp();
+ for (const setting of [
+ null,
+ webSearchSetting({ env: {}, stateDir: dir }),
+ { enabled: false, searchContextSize: "high" as const, models: null },
+ webSearchSetting({ env: { OMNIRUSH_WEB_SEARCH: "0" }, stateDir: dir }),
+ ]) {
+ expect(JSON.stringify(buildOmniRushRuntimeConfigObjectFromSnapshot({}, gateway, {}, catalog, undefined, undefined, setting))).toBe(before);
+ }
+ for (const model of Object.values(engineModelsFromCatalog(catalog))) expect(model.options).toBeUndefined();
+ });
+
+ test("on: hostedWebSearch only on the models the server lists; nothing else changes", () => {
+ const setting = { enabled: true, searchContextSize: "low" as const, models: serverBlock.models };
+ const off = buildOmniRushRuntimeConfigObjectFromSnapshot({}, gateway, {}, catalog) as { provider: { omnirush: { models: Record<string, Record<string, unknown>> } } };
+ const on = buildOmniRushRuntimeConfigObjectFromSnapshot({}, gateway, {}, catalog, undefined, undefined, setting) as typeof off;
+ const models = on.provider.omnirush.models;
+ for (const id of serverBlock.models) expect(models[id]!.options).toEqual({ hostedWebSearch: { searchContextSize: "low" } });
+ for (const id of ["meta-muse-spark", "muse-spark-1.1", "muse-spark-1.3"]) expect(models[id]!.options).toBeUndefined();
+ for (const [id, model] of Object.entries(models)) {
+ const { options: _options, ...rest } = model;
+ expect([id, rest]).toEqual([id, off.provider.omnirush.models[id]]);
+ }
+ const strip = (config: typeof off) => JSON.stringify({ ...config, provider: null });
+ expect(strip(on)).toBe(strip(off));
+ });
+});
diff --git a/apps/server/src/web-search.ts b/apps/server/src/web-search.ts
new file mode 100644
index 00000000..49a72b9b
--- /dev/null
+++ b/apps/server/src/web-search.ts
@@ -0,0 +1,125 @@
+/**
+ * The model's own web search (the OpenAI Responses `web_search` tool, run by
+ * the provider) for the bundled engine; the same rules as the CLI's
+ * src/web-search.js.
+ *
+ * Off unless something turns it on, in this order:
+ * 1. OMNIRUSH_WEB_SEARCH=1/on or 0/off in the server environment;
+ * 2. the server's switch: GET /collect/capabilities `web_search`
+ * ({ enabled, search_context_size, models, clients, rollout_percent }),
+ * as last seen (<runtimeStorageDir>/web-search-server.json). No block (an
+ * older server), or enabled false, is off. The server answers for this
+ * account and app: `clients` and `rollout_percent` are already applied
+ * to `enabled`, so the app reads `enabled` as it is and sends nothing extra.
+ * Only models whose catalog entry has capabilities.web_search get the tool;
+ * the server's `models` list (the models its gateway lets search), when it
+ * gives one, narrows that further.
+ *
+ * When it is on, the engine config gives those models
+ * `options.hostedWebSearch` ({ searchContextSize }), which the engine turns
+ * into the provider's web_search tool. Off, the engine config is exactly what
+ * it was before (no `options` key on any model).
+ */
+import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+
+import type { OmniRushCatalogModel } from "./omnirush-model-catalog.js";
+
+export const WEB_SEARCH_SERVER_FILE = "web-search-server.json";
+export const SEARCH_CONTEXT_SIZES = ["low", "medium", "high"] as const;
+export type SearchContextSize = (typeof SEARCH_CONTEXT_SIZES)[number];
+export const DEFAULT_SEARCH_CONTEXT_SIZE: SearchContextSize = "medium";
+const MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
+
+export type WebSearchSwitch = { enabled: boolean; searchContextSize: SearchContextSize; models: string[] | null };
+export type WebSearchSetting = WebSearchSwitch & { source: "env" | "server" | "default" };
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function contextSize(value: unknown): SearchContextSize {
+ return (SEARCH_CONTEXT_SIZES as readonly unknown[]).includes(value) ? (value as SearchContextSize) : DEFAULT_SEARCH_CONTEXT_SIZE;
+}
+
+/** The server's switch in a /collect/capabilities answer; a missing or malformed block is off. */
+export function webSearchServerSwitch(capabilities: unknown): WebSearchSwitch {
+ const block = isRecord(capabilities) ? capabilities.web_search : null;
+ if (!isRecord(block)) return { enabled: false, searchContextSize: DEFAULT_SEARCH_CONTEXT_SIZE, models: null };
+ const models = Array.isArray(block.models)
+ ? block.models.filter((id): id is string => typeof id === "string" && MODEL_ID.test(id)).slice(0, 64)
+ : null;
+ return { enabled: block.enabled === true, searchContextSize: contextSize(block.search_context_size), models };
+}
+
+function readJson(file: string): unknown {
+ try {
+ return JSON.parse(readFileSync(file, "utf8"));
+ } catch {
+ return null;
+ }
+}
+
+function rememberedSwitch(stateDir: string): WebSearchSwitch | null {
+ const saved = readJson(join(stateDir, WEB_SEARCH_SERVER_FILE));
+ return isRecord(saved) ? webSearchServerSwitch({ web_search: saved }) : null;
+}
+
+/**
+ * Remembers the switch of a /collect/capabilities answer (every answer: a
+ * missing block turns it off; null, no answer, keeps the last). Whether the
+ * remembered switch changed.
+ */
+export function rememberWebSearchSwitch(stateDir: string, capabilities: unknown): boolean {
+ if (!stateDir || !isRecord(capabilities)) return false;
+ const value = webSearchServerSwitch(capabilities);
+ const before = rememberedSwitch(stateDir);
+ try {
+ mkdirSync(stateDir, { recursive: true });
+ writeFileSync(
+ join(stateDir, WEB_SEARCH_SERVER_FILE),
+ JSON.stringify({ enabled: value.enabled, search_context_size: value.searchContextSize, models: value.models, at: Date.now() }),
+ { mode: 0o600 },
+ );
+ } catch {
+ /* best effort */
+ }
+ return JSON.stringify(before ?? webSearchServerSwitch(null)) !== JSON.stringify(value);
+}
+
+/** Web search for the engine config; `models` (null: every model with the capability) comes from the server. */
+export function webSearchSetting({ env = process.env, stateDir }: { env?: NodeJS.ProcessEnv; stateDir?: string } = {}): WebSearchSetting {
+ const server = stateDir ? rememberedSwitch(stateDir) : null;
+ const size = server?.searchContextSize ?? DEFAULT_SEARCH_CONTEXT_SIZE;
+ const asked = String(env.OMNIRUSH_WEB_SEARCH ?? "").trim().toLowerCase();
+ if (["0", "off", "false", "no"].includes(asked)) return { enabled: false, source: "env", searchContextSize: size, models: null };
+ if (["1", "on", "true", "yes"].includes(asked)) return { enabled: true, source: "env", searchContextSize: size, models: null };
+ if (server) return { ...server, source: "server" };
+ return { enabled: false, source: "default", searchContextSize: size, models: null };
+}
+
+/** Whether `model` (a sanitized catalog entry) gets the tool under `setting`. */
+export function modelHasWebSearch(model: Pick<OmniRushCatalogModel, "id" | "capabilities"> | undefined, setting: WebSearchSwitch | null | undefined): boolean {
+ if (!setting?.enabled || !model?.capabilities?.web_search) return false;
+ return !Array.isArray(setting.models) || setting.models.includes(model.id);
+}
+
+/**
+ * Reads the server's switch again every `everyMs` while the app runs (an app
+ * started before the switch was flipped, or kept open for days, follows it
+ * without a restart) and calls `apply` when it changed. One read at a time;
+ * a failed read (`read` throws) keeps the last answer. Returns the stop.
+ */
+export function watchWebSearchSwitch({ stateDir, read, apply, everyMs }: { stateDir: string; read: () => Promise<unknown>; apply: () => Promise<unknown>; everyMs: number }): () => void {
+ let busy = false;
+ const timer = setInterval(() => {
+ if (busy) return;
+ busy = true;
+ void read()
+ .then((capabilities) => (rememberWebSearchSwitch(stateDir, capabilities) ? apply() : undefined))
+ .catch(() => undefined)
+ .finally(() => { busy = false; });
+ }, everyMs);
+ timer.unref?.();
+ return () => clearInterval(timer);
+}