diff --git a/apps/host/server/agent/README.md b/apps/host/server/agent/README.md index 81857ded..22fed672 100644 --- a/apps/host/server/agent/README.md +++ b/apps/host/server/agent/README.md @@ -68,7 +68,7 @@ The chat's Mode menu is real Harness behaviour. Each turn the page sends the cha What the person chose is saved by `tools-settings.mjs` (inside the host's settings file) and shown by `src/components/SettingsTools.tsx` (`GET/PUT /api/agent/tools`, `POST/PATCH/DELETE /api/agent/tools/custom[/id]`). A change reaches the agent from the next message: the profile carries a `toolsSignature`, and the bridge restarts the Harness (after the running turns end) when it differs. - Tool groups (`tools-catalog.mjs`): each is one switch in plain words and is one or more preset plugins (`withoutDisabled`); `fetch` and `search` are the two halves of the Harness's `tool-web` (both off drops it). Goals off: `/goal` answers that goals are turned off. -- Web search needs no account. The default is DuckDuckGo's HTML result page (`../web-search-ddg.mjs`): a browser User-Agent, one request at a time at least 1.5 s apart, at most 20 a minute, a 10 minute cache per query, a 15 s limit, the lite page as a fallback, and a plain message when DuckDuckGo asks for a human check ("limiting searches from this computer"). **The results come from DuckDuckGo**; they are not ranked or filtered here. The person may switch to Exa, Perplexity or DeepSeek with their own key (`../web-search-keyed.mjs`; DeepSeek uses the Harness's own provider): the key is saved in the settings file, reaches the agent only as the environment variable `STRATA_SEARCH_KEY`, never the profile file and never the screen (it only learns `keySet`). A keyed service without its key falls back to DuckDuckGo. The profile pins `web.searchProvider` to the chosen id so two usable backends cannot make the choice ambiguous. +- Web search needs no account. The default is DuckDuckGo's HTML result page (`../web-search-ddg.mjs`), with Bing's plain result page (`../web-search-bing.mjs`) as the second source. Manners, because DuckDuckGo refuses a program that asks fast (a real box: two searches in 1.2 s answered, the third got HTTP 202 and every DuckDuckGo page refused for many minutes): a browser User-Agent and the page's own request shape (Referer, Origin, Sec-Fetch-*), one request at a time per source, 2.5 to 4 s apart (random), at most 8 a minute, a 30 minute session cache per question, a cooldown after a refusal that doubles (1, 2, 4 ... 10 minutes, `Retry-After` honoured) during which that source gets no request, no lite-page follow-up after a refusal, one retry for a timeout or a 5xx, a 15 s limit. When every source refuses, the tool answers one plain sentence (`LIMITED_SENTENCE`: "Web search is limited right now. Try again in a minute, or add a search key (Exa, Perplexity or DeepSeek) in Settings -> Tools -> Web search.") plus an instruction to the model not to retry; the turn guard in `agent-bridge.mjs` (see Turn guard) stops a model that retries anyway. **The results come from DuckDuckGo or Bing**; they are not ranked or filtered here. The person may switch to Exa, Perplexity or DeepSeek with their own key (`../web-search-keyed.mjs`; DeepSeek uses the Harness's own provider): the key is saved in the settings file, reaches the agent only as the environment variable `STRATA_SEARCH_KEY`, never the profile file and never the screen (it only learns `keySet`). A keyed service without its key falls back to DuckDuckGo. The profile pins `web.searchProvider` to the chosen id so two usable backends cannot make the choice ambiguous. - The browser: Playwright's MCP server (`@playwright/mcp`, staged next to the Harness by `apps/desktop/scripts/stage-harness.mjs`) on the person's own Chrome, Edge or Chromium (`browser-probe.mjs`), `--isolated` so it never sees their profile. Tools appear as `mcp__browser__browser_*`. In Manual, opening a page, clicking, typing, uploading, running a script in the page and closing tabs ask (plain reasons: "Open the web page ...", "Click on the page: ..."); looking (snapshot, screenshot, console, network, waiting, listing tabs) does not. Plan refuses every connected tool. The screen says plainly when no browser, or no tool server, is found. - The person's own tools: `instructions` (the tool returns their text; look-only, never asks), `command` (runs their command with the assistant's text in the `STRATA_INPUT` environment variable, never spliced into the command line; asks in Manual, refused in Plan) and `server` (a web address or a program, added as `mcp__custom-__*`; asks in Manual). Instruction and command tools are served by `custom-tools-mcp.mjs` (stdio MCP) from a JSON file the settings module rewrites on every change, so a switch in Settings is seen without a restart. - `strata-gate.mjs` implements the Manual/Plan rules above (`planDecision`, `browserDecision`, the look-only instruction server). @@ -121,3 +121,13 @@ A model on OpenRouter whose model list names `reasoning` in `supported_parameter ## Pictures Pictures are on by default for every model that can read them: an API model reads them unless the person switched it off (Settings > Models > "Read pictures with this model") or its server says it cannot; a local model reads them when it was loaded with Read pictures (on by default). `src/lib/pictures.ts` is the one answer used by the composer and by Send; the agent route declares image input from the same flag. + +## Turn guard (`turn-guard.mjs`) + +A turn that keeps failing the same way is stopped by the app, never left to the model. Seen on a search-heavy `/plan`: every web search was refused, the model searched again and rewrote its plan after each one until the context reached 100%, then the turn ended with no answer and no message. + +- **Counted, from what the turn shows:** web searches that failed in a row (3), searches in one turn (10 in a plan turn, 25 otherwise), a plan turn that starts its numbered list from `1.` again (4 times), and a context of 93% or more (the Harness's own compaction did not keep up). +- **Stopped the way Stop stops** (`session/cancel`, helpers first) but ended as a normal turn (`done`, not cancelled, no error card), so the plan the model had written is still proposed. The plan card carries the reason (`plan.caution`); any other turn ends with one `delta` frame that has `own: true` and `key` (the English sentence, translated by the page; `GUARD_NOTES` are in the interface catalog in all eight languages). Each sentence says what happened and gives one next step. +- **Compaction:** after a guard stop (and after a turn the model server refused because the context was full) the bridge asks the Harness for `/compact` on that session, so the next message has room. Best effort and logged. +- **Never silent:** a turn that ends (`completed` or `max-tokens`) with no answer text gets "I ran out of room in this chat..." when the last request used 85% of the window or more, otherwise "I stopped without writing an answer..." (not when tool cards were shown, not after Stop, not after an error, which says why by itself). Goal runs have their own ending lines and are not guarded. +- Tests: `tests/agent-turn-guard.test.mjs` (counting, always; end to end with the real Harness, the scripted model's `searchloop` and `bloat` scripts and `searchMock: 'limited'` on the bridge, which runs the real search code on a pretend web that refuses, no network). diff --git a/apps/host/server/agent/agent-bridge.mjs b/apps/host/server/agent/agent-bridge.mjs index 0a9ce77d..647b00b2 100644 --- a/apps/host/server/agent/agent-bridge.mjs +++ b/apps/host/server/agent/agent-bridge.mjs @@ -28,6 +28,7 @@ import { ChildProjector } from './children.mjs'; import { nearestBudget } from './llm-shape.mjs'; import { DeliverableTracker, ActivityGroups } from './deliverables.mjs'; import { SkillsUsed, skillInfoFrom } from './skills-used.mjs'; +import { TurnGuard, guardNote, GUARD_NOTES } from './turn-guard.mjs'; import { PlanStore, planPrompt, parsePlan, parsePoints, stepObjective, stepLine, firstSentence, stepSummary, planAsPrompt, editedSteps, planView, researchPrompt, researchWritePrompt, RESEARCH_NUDGE, parseSources } from './plan.mjs'; /** @@ -90,7 +91,7 @@ const deferred = () => { let resolve; const promise = new Promise(r => { resolve * @param {string} [options.nodePath] the Node runtime that runs the Harness * @param {(line:string)=>void} [options.log] */ -export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = null, gate = true, localInstances, connections, tools = () => undefined, skillsDir = () => null, onGoal = () => {}, onPlan = () => {}, onQueue = () => {}, proxyBase = null, expertSampling = () => null, stallMs = 4 * 60_000, stallToolMs = 20 * 60_000, env = process.env, nodePath = process.execPath, log = () => {}, startTimeoutMs = 120_000 }) { +export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = null, gate = true, localInstances, connections, tools = () => undefined, skillsDir = () => null, onGoal = () => {}, onPlan = () => {}, onQueue = () => {}, proxyBase = null, searchMock = null, expertSampling = () => null, stallMs = 4 * 60_000, stallToolMs = 20 * 60_000, env = process.env, nodePath = process.execPath, log = () => {}, startTimeoutMs = 120_000 }) { const root = join(dataDir, 'agent'); const home = join(root, 'home'); const sessionsFile = join(root, 'sessions.json'); @@ -146,7 +147,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = /** The agent's profile now, plus where its shaped routes really lead (read by the forwarding endpoint). */ let shapeTargets = {}; function buildProfileNow() { - const profile = buildProfile({ local: localInstances(), connections: connections(), gate, tools: tools(), skillsDir: skillsDir(), proxyBase }); + const profile = buildProfile({ local: localInstances(), connections: connections(), gate, tools: tools(), skillsDir: skillsDir(), proxyBase, searchMock }); shapeTargets = profile.shapeTargets ?? {}; return profile; } @@ -311,6 +312,8 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = signal?.addEventListener('abort', () => { send = () => {}; attached = false; }, { once: true }); // What the assistant itself wrote in this run (not our own step lines): a plan turn reads its plan from it, a step reads its summary. const written = { all: '', step: '' }; + // The turn guard (turn-guard.mjs): counts failing searches, searches, plan rewrites and a nearly full context. Set up once the route is known. + let guard = null; const raw = frame => { try { send(frame); } catch { send = () => {}; attached = false; } }; // What the turn made (files) and compact activity lines (notes-split-agent8.md): derived from the cards the turn already sends. const tracker = new DeliverableTracker(workspacePath, trackerFolders()); @@ -319,7 +322,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = const groups = new ActivityGroups({ emit: raw }); const skills = new SkillsUsed({ emit: raw, info: skillInfoFrom(skillsDir()) }); const emit = frame => { - if (frame.type === 'delta' && !frame.own) { written.all += frame.text; written.step += frame.text; if (hideDeltas) return; } + if (frame.type === 'delta' && !frame.own) { written.all += frame.text; written.step += frame.text; if (guard) trip(guard.text(frame.text)); if (hideDeltas) return; } if (frame.own) { const { own, ...rest } = frame; frame = rest; } if (frame.type === 'delta' && frame.text) groups.text(); if (frame.type === 'agent-tool' && frame.tool) { @@ -328,6 +331,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = if (frame.tool.state === 'done' && (frame.tool.name === 'write' || frame.tool.name === 'edit')) { try { made = tracker.check(frame.tool.args?.file_path ?? frame.tool.args?.path); } catch { made = null; } } raw(frame); if (made) raw(made); + if (guard) trip(guard.card(frame.tool)); groups.card(frame.tool, made); skills.card(frame.tool); return; @@ -370,6 +374,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = await applyMode(runtime, sessionId, appliedMode); const projector = new TurnProjector({ policy: MODE_PRESETS[appliedMode].approval }); + if (!goal) guard = new TurnGuard({ plan: !!planTask, contextMax: route.kind === 'local' ? route.contextWindow : 0 }); // a saved connection's window is often only assumed: never judged by a guess projector.onStatus = update => { if (!turn?.parentOpen && turn?.children.size && [...turn.children.values()].some(h => !h.done) && update.phase === 'waiting') return; reporter.set(update); }; const turn = { sessionId, projector, route, requestId, live: false, lastSeq: -1, @@ -406,13 +411,19 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = clearInterval(turn.watchdog); turn.follow?.close(); for (const child of turn.children.values()) child.follow?.close(); - if (turn.stopping && !failure) projector.ended = { kind: 'aborted', reason: { kind: 'user' } }; + if (turn.stopping && !failure) projector.ended = turn.guard ? { kind: 'completed' } : { kind: 'aborted', reason: { kind: 'user' } }; reporter.clear(); const extra = []; try { if (toolsRan) for (const d of tracker.sweep()) { emit(d); groups.addFile(d); } } catch { /* never blocks the end of a turn */ } groups.end(); if (researchTopic && !failure && !turn.stopping) { const sources = parseSources(written.all); if (sources.length) extra.push({ type: 'research', topic: researchTopic, sources }); } try { extra.push(...settlePlan(failure)); } catch { /* a plan frame must never break the end of a turn */ } + // The turn guard: a turn the app stopped, or one that ended with no words, always ends with one plain message (a plan card carries it itself). + let noteReason = turn.guard ?? null; + if (!noteReason && guard && !failure && !turn.stopping && !turn.goalRun) { + noteReason = guard.silent({ ended: projector.ended, wrote: projector.emittedAny === true, acted: projector.tools.size > 0, contextTokens: projector.contextTokens }); + } + if (noteReason && !extra.some(f => f.type === 'plan' && f.event === 'proposed')) { const note = guardNote(noteReason); if (note) extra.push(note); } for (const f of extra) emit(f); const frames = failure ? [{ type: 'error', message: plainAgentFailure(failure), details: failure, code: 'AGENT_STOPPED' }] : projector.finish({ model: route.name, contextMax: route.contextWindow }); for (const f of frames.slice(0, -1)) emit(f); @@ -425,6 +436,8 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = c.turn = null; turn.ended.resolve({ reason: projector.ended, failure: failure ?? null }); notifyIdle(); + // A turn that filled the context, or that the guard stopped, leaves a long history behind: summarise the older part now so the next message has room. + if (noteReason === 'context' || noteReason === 'searches' || noteReason === 'searches-failed' || noteReason === 'rewrites' || /context window|too long|exceeds/i.test(String(projector.ended?.error?.message ?? ''))) void compactSession(runtime, sessionId); } emit({ type: 'start', model: route.name, contextMax: route.contextWindow, demo: false, remoteModel: route.kind === 'api', agent: true, mode: appliedMode, sessionId, requestId, skills: [], ...(planTask ? { planning: true } : {}) }); @@ -442,6 +455,14 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = onError: e => finishTurn(`The agent lost the session stream: ${e.message}`), }); + /** The guard says stop: end the turn the way Stop does, but as a normal end with a plain message (finishTurn). */ + function trip(reason) { + if (!reason || turn.guard || turn.finished || turn.stopping) return; + turn.guard = reason; + log(`agent · turn guard: ${reason} (searches ${guard?.searches ?? 0}, failed in a row ${guard?.failedInARow ?? 0}, plan rewrites ${guard?.rewrites ?? 0})`); + void stop(chatId).catch(() => {}); + } + function handle(item) { if (turn.finished) return; turn.lastActivity = Date.now(); @@ -457,6 +478,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = } } else if (!turn.live) return; for (const f of projector.consume(item)) emit(f); + if (guard && projector.contextTokens != null) trip(guard.context(projector.contextTokens)); if (item.type === 'event') watchParent(item.event); } @@ -566,10 +588,10 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = /** What the end of the turn means for the plan: a plan turn makes one; a step run records where it stopped. */ function settlePlan(failure) { if (planTask) { - if (failure || turn.stopping) return []; + if (failure || (turn.stopping && !turn.guard)) return []; const parsed = parsePlan(written.all, planTask); if (!parsed) return []; - const plan = plans.create(chatId, { title: parsed.title, steps: parsed.steps, request: planTask }); + const plan = plans.create(chatId, { title: parsed.title, steps: parsed.steps, request: planTask, ...(turn.guard ? { caution: GUARD_NOTES[turn.guard] } : {}) }); return [publishPlan('proposed', plan)]; } const run = turn.plan; @@ -1094,6 +1116,14 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = * Stop one chat's turn. Resolves only once the turn has ended (or the wait times out), because the * Harness acknowledges a cancel as admitted, not as done. */ + /** Summarise the older part of a session with the Harness's own /compact. Best effort: the next message compacts again by itself when it must. */ + async function compactSession(runtime, sessionId) { + try { + const r = await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: '/compact', submittedAttachments: [] }); + log(`agent · compact after a stopped turn: ${r?.result?.kind ?? 'done'} ${String(r?.result?.text ?? '').slice(0, 120)}`); + } catch (e) { log(`agent · compact after a stopped turn failed: ${e.message}`); } + } + async function stop(chatId, { waitMs = 20_000 } = {}) { const c = chats.get(chatId); const turn = c?.turn; diff --git a/apps/host/server/agent/plan.mjs b/apps/host/server/agent/plan.mjs index 06639107..2c7e372f 100644 --- a/apps/host/server/agent/plan.mjs +++ b/apps/host/server/agent/plan.mjs @@ -193,9 +193,9 @@ export class PlanStore { } catch { /* the plan still lives in memory */ } } get(chatId) { return this.plans.get(chatId) ?? null; } - create(chatId, { title, steps, request = '', source = 'plan', state = 'proposed' }) { + create(chatId, { title, steps, request = '', source = 'plan', state = 'proposed', caution = null }) { const now = new Date().toISOString(); - const plan = { id: randomUUID(), chatId, title, request, source, state, steps, createdAt: now, updatedAt: now, goalStarted: false }; + const plan = { id: randomUUID(), chatId, title, request, source, state, steps, createdAt: now, updatedAt: now, goalStarted: false, ...(caution ? { caution } : {}) }; this.plans.set(chatId, plan); this.#save(); return plan; } diff --git a/apps/host/server/agent/plugins/strata-search.mjs b/apps/host/server/agent/plugins/strata-search.mjs index 57d63334..cf5bda68 100644 --- a/apps/host/server/agent/plugins/strata-search.mjs +++ b/apps/host/server/agent/plugins/strata-search.mjs @@ -15,7 +15,10 @@ export const inject = ['web']; export function apply(ctx, config = {}) { const keyOf = () => (config.keyEnv ? process.env[config.keyEnv] ?? '' : ''); - const provider = config.provider === 'exa' ? createExaSearch({ key: keyOf }) + // Tests only (the bridge option `searchMock`): the same search code on a pretend web, so nothing leaves the machine. + const pretend = config.mock === 'limited' ? { fetch: async url => new Response('please verify you are human: captcha', { status: /duckduckgo/.test(String(url)) ? 202 : 429 }) } : null; + const provider = pretend ? createDuckDuckGoSearch(pretend) + : config.provider === 'exa' ? createExaSearch({ key: keyOf }) : config.provider === 'perplexity' ? createPerplexitySearch({ key: keyOf }) : createDuckDuckGoSearch(); ctx.web.registerSearchProvider(provider); diff --git a/apps/host/server/agent/profile.mjs b/apps/host/server/agent/profile.mjs index b82be830..99d5a5ce 100644 --- a/apps/host/server/agent/profile.mjs +++ b/apps/host/server/agent/profile.mjs @@ -163,7 +163,7 @@ export function outputBudget(context, maxOutput = null) { /** What a local model, or an OpenAI-style server on this network, takes for the thinking level (see the comment where a local route is built). */ const THINKING_COMPAT = { supportsStore: false, thinkingFormat: 'chat-template', chatTemplateKwargs: { enable_thinking: { $var: 'thinking.enabled' }, reasoning_effort: { $var: 'thinking.effort', omitWhenOff: true } } }; -export function buildProfile({ local = [], connections = [], gate = true, tools = NO_TOOLS_SETTINGS, skillsDir = null, proxyBase = null }) { +export function buildProfile({ local = [], connections = [], gate = true, tools = NO_TOOLS_SETTINGS, skillsDir = null, proxyBase = null, searchMock = null }) { const providers = {}; const env = {}; const routes = []; @@ -271,7 +271,7 @@ export function buildProfile({ local = [], connections = [], gate = true, tools const webRows = !searchOn ? [] : keyed === 'deepseek' ? [{ id: 'web', config: { searchProvider: 'deepseek-official', fetchProvider: 'http' } }, { id: 'web-search-deepseek', config: { apiKeyEnv: 'STRATA_SEARCH_KEY' } }] : [{ id: 'web', config: { searchProvider: keyed ?? DDG_PROVIDER_ID, fetchProvider: 'http' } }, { id: 'web-search-deepseek', disabled: true }, - { insert: [{ id: 'strata-web-search', name: SEARCH_PLUGIN, config: { provider: keyed ?? 'duckduckgo', keyEnv: 'STRATA_SEARCH_KEY' } }] }]; + { insert: [{ id: 'strata-web-search', name: SEARCH_PLUGIN, config: { provider: keyed ?? 'duckduckgo', keyEnv: 'STRATA_SEARCH_KEY', ...(searchMock ? { mock: searchMock } : {}) } }] }]; /** The models a helper agent may be started on: the table the model-choice plugin and the Harness's allow-list are written from. */ const subagentRoutes = routes.map(r => ({ provider: r.route, model: r.modelId, name: r.name, connection: r.connectionName, local: r.kind === 'local' })); const entries = [ diff --git a/apps/host/server/agent/turn-guard.mjs b/apps/host/server/agent/turn-guard.mjs new file mode 100644 index 00000000..f28ce3f4 --- /dev/null +++ b/apps/host/server/agent/turn-guard.mjs @@ -0,0 +1,105 @@ +/** + * The turn guard: a turn that keeps failing the same way, or keeps rewriting the same thing, is stopped by the app and ends with a plain message. + * Pure (no I/O); the bridge feeds it what the turn shows and acts on what it answers. + * + * Why: a search-heavy /plan on a small model searched again after every refusal and rewrote its plan after every search until the context + * reached 100%, then the turn ended with no answer and no message. Nothing here relies on the model behaving: the app counts. + * + * searches-failed this many web searches in a row failed (web search was limited, or could not be reached) + * searches this many searches in one turn (a plan or an ordinary answer needs a handful, not dozens) + * rewrites a plan turn wrote its numbered plan from "1." again this many times + * context the context is nearly full: the Harness compaction did not keep up + * + * What the person is told is `guardNote`: fixed English sentences that are also in the interface catalog in all eight languages (the page + * translates a `delta` frame that carries `key`). Each says what happened and gives one next step. + */ + +export const GUARD_LIMITS = Object.freeze({ + failedSearches: 3, + searchesPlan: 10, + searchesTurn: 25, + planRewrites: 4, + contextFraction: 0.93, + /** A turn that ends with no words at all and a context this full is "out of room", not "nothing to say". */ + contextEmptyFraction: 0.85, +}); + +const SEARCH_TOOLS = new Set(['web_search']); +const SEARCH_FAILED = /web search is limited|search could not reach|could not reach the internet|WEB_RATE_LIMITED|WEB_PROVIDER_ERROR|did not accept the key|too many searches/i; + +/** The plain sentences, keyed by reason. `values` are the slots the page fills in. */ +const NOTES = { + 'searches-failed': 'Web search is limited right now, so I stopped searching and went on with what I have. Try again in a minute, or add a search key in Settings → Tools → Web search.', + searches: 'I searched a lot and stopped so this chat does not fill up. This is what I have so far. Tell me what to look into next.', + rewrites: 'I kept rewriting the plan, so I stopped here with the latest version. Tell me what to change, or approve it.', + context: 'I ran out of room in this chat, so I stopped. Strata is summarising the older messages to make space. Say “continue” to go on, or start a new chat.', + empty: 'I stopped without writing an answer. Send your message again, or say “continue”.', +}; +export const GUARD_NOTES = Object.freeze({ ...NOTES }); + +/** A `delta` frame the page shows as ordinary assistant text and translates (`key` is the English sentence). */ +export function guardNote(reason) { + const text = NOTES[reason]; + return text ? { type: 'delta', own: true, text: `\n\n${text}`, key: text, noteReason: reason } : null; +} + +export class TurnGuard { + /** + * @param {{plan?: boolean, contextMax?: number, limits?: Partial}} [options] + */ + constructor({ plan = false, contextMax = 0, limits = {} } = {}) { + this.plan = plan; this.contextMax = Number(contextMax) || 0; + this.limits = { ...GUARD_LIMITS, ...limits }; + this.seen = new Set(); + this.searches = 0; this.failedInARow = 0; this.failedTotal = 0; + this.rewrites = 0; this.written = ''; + this.reason = null; + } + + #fire(reason) { this.reason ??= reason; return this.reason; } + + /** A tool card frame (`agent-tool`). Counts a search once, when it has finished. Returns the reason to stop, or null. */ + card(tool) { + if (this.reason || !tool || !SEARCH_TOOLS.has(tool.name)) return this.reason; + const done = tool.state === 'done' || tool.state === 'error' || tool.state === 'denied'; + if (!done || this.seen.has(tool.id)) return this.reason; + this.seen.add(tool.id); + this.searches += 1; + const failed = tool.state === 'error' || SEARCH_FAILED.test(String(tool.result ?? '')); + if (failed) { this.failedInARow += 1; this.failedTotal += 1; } else this.failedInARow = 0; + if (this.failedInARow >= this.limits.failedSearches) return this.#fire('searches-failed'); + if (this.searches >= (this.plan ? this.limits.searchesPlan : this.limits.searchesTurn)) return this.#fire(this.failedTotal >= this.searches / 2 ? 'searches-failed' : 'searches'); + return this.reason; + } + + /** Text the assistant wrote (not our own lines). A plan turn that starts its numbered list again and again is rewriting. */ + text(delta) { + if (this.reason || !this.plan || !delta) return this.reason; + this.written += delta; + if (this.written.length > 200_000) this.written = this.written.slice(-100_000); + if (!delta.includes('\n') && !/\d[.)]\s/.test(delta)) return this.reason; + this.rewrites = (this.written.match(/(?:^|\n)[ \t]{0,3}1[.)][ \t]+\S/g) ?? []).length; + if (this.rewrites >= this.limits.planRewrites) return this.#fire('rewrites'); + return this.reason; + } + + /** What the context holds now (tokens of the last request). */ + context(tokens) { + if (this.reason || !this.contextMax || !Number.isFinite(tokens)) return this.reason; + if (tokens / this.contextMax >= this.limits.contextFraction) return this.#fire('context'); + return this.reason; + } + + /** + * The turn is over. If the person has seen no words from it, which sentence do they get? `ended` is the Harness's turn end reason, + * `wrote` whether any answer text was shown, `acted` whether tool cards were shown, `contextTokens` the last request's size. Returns a reason or null. + */ + silent({ ended, wrote, contextTokens, acted = false, stoppedByPerson = false }) { + if (this.reason) return this.reason; + if (stoppedByPerson || wrote) return null; + const kind = ended?.kind; + if (kind !== 'completed' && kind !== 'max-tokens') return null; // an error says why by itself; Stop is the person's own + if (this.contextMax && Number(contextTokens) / this.contextMax >= this.limits.contextEmptyFraction) return 'context'; + return acted ? null : 'empty'; // cards of work done are an answer of a kind; no cards and no words is not + } +} diff --git a/apps/host/server/api-paths.mjs b/apps/host/server/api-paths.mjs new file mode 100644 index 00000000..77d4d49e --- /dev/null +++ b/apps/host/server/api-paths.mjs @@ -0,0 +1,12 @@ +/** + * Anthropic clients add `/v1/messages` to the base URL themselves, so the base URL they are given is the server root (no `/v1`). + * A base URL copied from an OpenAI-style setup ends in `/v1`, and the client then posts `/v1/v1/messages`. That one path means the + * same as the real one; nothing else is aliased (an OpenAI client never adds `/v1` on its own). + */ +const ALIASES = new Map([['/v1/v1/messages', '/v1/messages'], ['/v1/v1/messages/count_tokens', '/v1/messages/count_tokens']]); + +export function apiPath(path) { + const clean = path.length > 1 ? path.replace(/\/+$/, '') : path; + return ALIASES.get(clean) ?? path; +} + diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs index ef9c80c1..f9c7b48c 100644 --- a/apps/host/server/index.mjs +++ b/apps/host/server/index.mjs @@ -68,6 +68,7 @@ import { forbidden as acquisitionForbidden } from './acquisition.mjs'; import { randomBytes, timingSafeEqual } from 'node:crypto'; import { nativeGateway } from './native-gateway.mjs'; import { proxyCompletion } from './inference.mjs'; +import { apiPath } from './api-paths.mjs'; import { validateChatImages } from './chat-images.mjs'; import { createTimeSkip, measureFolder, timeskipRevisionMessage, imageTypeOf } from './timeskip.mjs'; @@ -925,7 +926,7 @@ const server = http.createServer(async (req, res) => { } if (path.startsWith('/v1/')) { if (storageChanging && method !== 'GET') return error(res, 409, 'Wait for the model folder check to finish.'); - return await openai(req, res, path, method); + return await openai(req, res, apiPath(path), method); } return await staticFile(req, res, path); } catch (err) { diff --git a/apps/host/server/local-share.mjs b/apps/host/server/local-share.mjs index 34cc5a35..788932f9 100644 --- a/apps/host/server/local-share.mjs +++ b/apps/host/server/local-share.mjs @@ -1,6 +1,7 @@ /** A separate, key-protected listener for inference only. Never serves the UI or host APIs. */ import http from 'node:http'; import os from 'node:os'; +import { apiPath } from './api-paths.mjs'; export function createLocalShare({ handle, hasKey, changed = () => {}, host = '0.0.0.0', port = 8792 }) { let listener = null, active = false; const address = () => Object.values(os.networkInterfaces()).flat().find(n => n?.family === 'IPv4' && !n.internal)?.address ?? '127.0.0.1'; @@ -10,7 +11,7 @@ export function createLocalShare({ handle, hasKey, changed = () => {}, host = '0 if (listener) throw new Error('Sharing is already starting.'); if (!hasKey()) throw new Error('Set an API key before sharing with other devices.'); listener = http.createServer(async (req, res) => { - const path = new URL(req.url ?? '/', 'http://localhost').pathname; + const path = apiPath(new URL(req.url ?? '/', 'http://localhost').pathname); if (!['/v1/models','/v1/chat/completions','/v1/messages'].includes(path)) { res.writeHead(404); res.end('Not found'); return; } try { await handle(req, res, path, req.method ?? 'GET'); } catch { if (!res.headersSent) res.writeHead(500); res.end('Request failed'); } diff --git a/apps/host/server/web-search-bing.mjs b/apps/host/server/web-search-bing.mjs new file mode 100644 index 00000000..e7d3575e --- /dev/null +++ b/apps/host/server/web-search-bing.mjs @@ -0,0 +1,68 @@ +/** + * The second keyless source for the agent's web search: Bing's plain result page, used only when DuckDuckGo refuses. + * + * It is read the way a browser reads it (an ordinary User-Agent, the page's own request shape, nothing hidden) and is held to the same + * manners as DuckDuckGo (see web-search-ddg.mjs): one request at a time, spaced out, a cooldown after a refusal. Results are not ranked or + * filtered here. Pure parsing lives in this file so it can be tested on saved pages. + */ + +const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ', '#39': "'", '#x27': "'", '#x2F': '/', '#183': '·' }; +const decode = text => String(text).replace(/&(#x?[0-9a-f]+|[a-z]+);/gi, (whole, key) => { + if (key[0] === '#') { + const code = key[1].toLowerCase() === 'x' ? parseInt(key.slice(2), 16) : parseInt(key.slice(1), 10); + return Number.isFinite(code) && code > 0 && code < 0x110000 ? String.fromCodePoint(code) : whole; + } + return ENTITIES[key.toLowerCase()] ?? whole; +}); +const plain = html => decode(String(html).replace(/<[^>]*>/g, '')).replace(/\s+/g, ' ').trim(); + +export const BING_URL = 'https://www.bing.com/search'; + +/** Bing wraps every result link in its own redirect (`/ck/a?...&u=a1`). */ +export function bingTarget(href) { + const value = decode(href).trim(); + try { + const url = new URL(value, 'https://www.bing.com/'); + if (/(^|\.)bing\.com$/i.test(url.hostname)) { + const u = url.searchParams.get('u'); + if (u && /^a1/.test(u)) { + const target = Buffer.from(u.slice(2).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); + const real = new URL(target); + return /^https?:$/.test(real.protocol) ? real.href : null; + } + return null; // Bing's own page (images, maps, "more results") + } + return /^https?:$/.test(url.protocol) ? url.href : null; + } catch { return null; } +} + +/** The result list of the page. Tolerant: a result needs a link and a title; the snippet is optional. */ +export function parseBingResults(html) { + const out = []; + const seen = new Set(); + const blocks = String(html).split(/]*\bclass="[^"]*\bb_algo\b[^"]*"/i).slice(1); + for (const block of blocks) { + const end = block.search(/]*\bclass="[^"]*\bb_(?:algo|ans|ad|pag)\b/i); + const body = end > 0 ? block.slice(0, end) : block; + const h2 = /]*>\s*]*)>([\s\S]*?)<\/a>/i.exec(body); + if (!h2) continue; + const href = /\bhref="([^"]*)"/i.exec(h2[1])?.[1]; + const url = href ? bingTarget(href) : null; + const title = plain(h2[2]); + if (!url || !title || seen.has(url)) continue; + const snippetMatch = /]*class="[^"]*\bb_lineclamp\d*\b[^"]*"[^>]*>([\s\S]*?)<\/p>/i.exec(body) + ?? /]*class="[^"]*\bb_caption\b[^"]*"[^>]*>[\s\S]*?]*>([\s\S]*?)<\/p>/i.exec(body); + const snippet = snippetMatch ? plain(snippetMatch[1]) : ''; + seen.add(url); + out.push({ url, title, ...(snippet ? { snippet } : {}) }); + } + return out; +} + +/** Bing serves a challenge page, or a refusal, instead of results. A page with results is never "blocked". */ +export function bingLooksBlocked(status, html) { + if (status === 403 || status === 429 || status === 503) return true; + const text = String(html).slice(0, 80000); + if (/\bclass="[^"]*\bb_algo\b/.test(text)) return false; + return /captcha|unusual traffic|are you a robot|verify you are (?:a )?human|\bcf-chl|challenge-platform/i.test(text); +} diff --git a/apps/host/server/web-search-ddg.mjs b/apps/host/server/web-search-ddg.mjs index e2f02df1..cfe73e4b 100644 --- a/apps/host/server/web-search-ddg.mjs +++ b/apps/host/server/web-search-ddg.mjs @@ -1,28 +1,39 @@ /** - * Web search with no account and no key: DuckDuckGo's own web-page search results. + * Web search with no account and no key: DuckDuckGo's own web-page search results, with Bing's plain result page as the second source. * * The Harness has three search backends and all of them need a paid service key. This is the fourth: it asks DuckDuckGo's plain * HTML search page the way a browser does and reads the result list out of the page. It is the default for the agent's * `web_search` tool; the person can switch to a keyed service in Settings -> Tools. * - * Being polite is part of the design: - * - an ordinary browser User-Agent and the page's own request shape (nothing hidden, nothing faked beyond the User-Agent); - * - at most one request every 1.5 s and 20 a minute from this program, with the same query answered from a 10 minute cache; - * - a 15 s time limit, no retries in a loop; when DuckDuckGo asks for a human check or refuses, the answer says so in plain - * words and the model is told to carry on without search. - * Results come from DuckDuckGo; they are not ranked or filtered here. + * Being polite is part of the design, because DuckDuckGo refuses a program that asks too fast (2026-10-18, a Linux box: two searches in + * 1.2 s were answered, the third got HTTP 202 "anomaly" and every DuckDuckGo page then refused for minutes): + * - an ordinary browser User-Agent and the page's own request shape (Referer, Origin, Sec-Fetch-*; nothing hidden); + * - one request at a time per source, 2.5 to 4 s apart (random, so it does not look like a clock), at most 8 a minute; + * - the same question is answered from a session cache (30 minutes), so a model that repeats itself costs nothing; + * - when a source refuses (HTTP 202/403/429 or a challenge page) it is left alone for a cooldown that doubles every time it refuses + * again (1, 2, 4 ... up to 10 minutes; a Retry-After header is honoured) instead of being asked again, which only extends a block; + * - a refused DuckDuckGo page is not followed by the lite page (same refusal, one more strike): the next source is tried instead; + * - a timeout or a server error gets one retry after a short pause, then the next source; + * - when every source refuses the answer is one plain sentence that also tells the model not to retry (see LIMITED_MESSAGE). + * Results come from DuckDuckGo or Bing; they are not ranked or filtered here. * * Nothing in this file touches the Harness, so it can be tested alone. `strata-search.mjs` is the plugin that registers it. */ +import { BING_URL, bingLooksBlocked, parseBingResults } from './web-search-bing.mjs'; export const DDG_PROVIDER_ID = 'strata-duckduckgo'; const HTML_URL = 'https://html.duckduckgo.com/html/'; const LITE_URL = 'https://lite.duckduckgo.com/lite/'; -const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36'; -const CACHE_MS = 10 * 60 * 1000; -const MIN_GAP_MS = 1500; -const PER_MINUTE = 20; +const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'; +const CACHE_MS = 30 * 60 * 1000; +const CACHE_SIZE = 120; +const GAP_MS = 2500; +const JITTER_MS = 1500; +const PER_MINUTE = 8; +const COOLDOWN_MS = 60_000; +const COOLDOWN_MAX_MS = 10 * 60_000; +const RETRY_PAUSE_MS = 1500; const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ', '#39': "'", '#x27': "'", '#x2F': '/' }; const decode = text => String(text).replace(/&(#x?[0-9a-f]+|[a-z]+);/gi, (whole, key) => { @@ -106,83 +117,148 @@ export function looksBlocked(status, html) { && !/class="[^"]*\bresult__a\b/.test(html); } + export class SearchUnavailable extends Error { constructor(message, code = 'WEB_PROVIDER_ERROR', options) { super(message, options); this.name = 'WebError'; this.code = code; } } -export const BLOCKED_MESSAGE = 'DuckDuckGo is limiting searches from this computer right now. Try again in a few minutes, or add a search key in Settings, Tools.'; +/** The one plain sentence for the person. The words "Settings → Tools → Web search" are where the key goes in the app. */ +export const LIMITED_SENTENCE = 'Web search is limited right now. Try again in a minute, or add a search key (Exa, Perplexity or DeepSeek) in Settings → Tools → Web search.'; +/** What the tool answers: the sentence, then what the model should do (it must not keep searching). */ +export const BLOCKED_MESSAGE = `${LIMITED_SENTENCE} Do not retry this search: go on with what you know and tell the person, in one plain sentence, that web search was limited.`; +export const UNREACHABLE_MESSAGE = 'The search could not reach the internet. Check the connection and try again. Do not retry this search now: go on with what you know and say that search was unavailable.'; -/** - * @param {{fetch?: typeof fetch, now?: () => number, sleep?: (ms: number) => Promise}} [deps] - */ -export function createDuckDuckGoSearch({ fetch: fetchImpl = globalThis.fetch, now = Date.now, sleep = ms => new Promise(r => setTimeout(r, ms)) } = {}) { - const cache = new Map(); - const starts = []; - let last = 0; - let chain = Promise.resolve(); - - /** One request at a time, spaced out, and at most PER_MINUTE a minute. */ - function turn(signal) { - const run = chain.then(async () => { +/** One request at a time, spaced out with a little randomness, and at most PER_MINUTE a minute. */ +class Pacer { + constructor({ now, sleep, random, gap = GAP_MS, jitter = JITTER_MS, perMinute = PER_MINUTE }) { + Object.assign(this, { now, sleep, random, gap, jitter, perMinute }); + this.starts = []; this.last = 0; this.chain = Promise.resolve(); + } + turn(signal) { + const run = this.chain.then(async () => { + const spacing = this.gap + Math.floor(this.random() * this.jitter); for (;;) { - signal?.throwIfAborted(); - const t = now(); - while (starts.length && t - starts[0] > 60_000) starts.shift(); - const wait = Math.max(MIN_GAP_MS - (t - last), starts.length >= PER_MINUTE ? 60_000 - (t - starts[0]) : 0); + if (signal?.aborted) throw new SearchUnavailable('The search was cancelled.', 'WEB_ABORTED'); + const t = this.now(); + while (this.starts.length && t - this.starts[0] > 60_000) this.starts.shift(); + const wait = this.last ? Math.max(spacing - (t - this.last), this.starts.length >= this.perMinute ? 60_000 - (t - this.starts[0]) : 0) : 0; if (wait <= 0) break; - if (wait > 30_000) throw new SearchUnavailable('Too many searches in a short time. Try again in a minute.', 'WEB_RATE_LIMITED'); - await sleep(wait); + if (wait > 30_000) throw new SearchUnavailable(LIMITED_SENTENCE, 'WEB_RATE_LIMITED'); + await this.sleep(wait); } - last = now(); - starts.push(last); + this.last = this.now(); + this.starts.push(this.last); }); - chain = run.catch(() => {}); + this.chain = run.catch(() => {}); return run; } +} - async function ask(url, query, signal) { +const REFUSED = Symbol('refused'); +const retryAfterMs = res => { + const v = Number(res?.headers?.get?.('retry-after')); + return Number.isFinite(v) && v > 0 ? Math.min(v * 1000, COOLDOWN_MAX_MS) : 0; +}; +const serverError = status => status >= 500 && status < 600; +const queryKey = query => query.toLowerCase().replace(/\s+/g, ' ').trim(); + +/** + * @param {{fetch?: typeof fetch, now?: () => number, sleep?: (ms: number) => Promise, random?: () => number}} [deps] + */ +export function createDuckDuckGoSearch({ fetch: fetchImpl = globalThis.fetch, now = Date.now, sleep = ms => new Promise(r => setTimeout(r, ms)), random = Math.random } = {}) { + const cache = new Map(); + + /** A source: its pacing, and what to do after it refuses. */ + const source = (id, name) => ({ id, name, pacer: new Pacer({ now, sleep, random }), blockedUntil: 0, strikes: 0, refusals: 0 }); + const ddg = source('duckduckgo', 'DuckDuckGo'); + const bing = source('bing', 'Bing'); + const refuse = (s, res) => { + s.strikes += 1; s.refusals += 1; + s.blockedUntil = now() + Math.max(retryAfterMs(res), Math.min(COOLDOWN_MS * 2 ** (s.strikes - 1), COOLDOWN_MAX_MS)); + }; + const accepted = s => { s.strikes = 0; s.blockedUntil = 0; }; + + const headers = (origin, extra = {}) => ({ + 'user-agent': USER_AGENT, accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'accept-language': 'en-US,en;q=0.9', + 'upgrade-insecure-requests': '1', 'sec-fetch-dest': 'document', 'sec-fetch-mode': 'navigate', 'sec-fetch-site': 'same-origin', 'sec-fetch-user': '?1', + ...(origin ? { referer: `${origin}/`, origin } : {}), ...extra, + }); + + async function get(url, init, signal) { const timeout = AbortSignal.timeout(15_000); - const res = await fetchImpl(url, { - method: 'POST', redirect: 'follow', - headers: { 'user-agent': USER_AGENT, 'content-type': 'application/x-www-form-urlencoded', accept: 'text/html,application/xhtml+xml', 'accept-language': 'en-US,en;q=0.8' }, - body: new URLSearchParams({ q: query, b: '' }).toString(), - signal: signal ? AbortSignal.any([signal, timeout]) : timeout, - }); - const html = await res.text(); - return { status: res.status, html }; + const res = await fetchImpl(url, { redirect: 'follow', ...init, signal: signal ? AbortSignal.any([signal, timeout]) : timeout }); + return { res, status: res.status, html: await res.text() }; + } + + /** One page request with one retry after a pause for a timeout, a network error or a server error. Throws SearchUnavailable only for cancel. */ + async function ask(s, makeRequest, signal) { + let failure; + for (let attempt = 0; attempt < 2; attempt++) { + await s.pacer.turn(signal); + try { + const page = await get(...makeRequest(), signal); + if (!serverError(page.status)) return page; + failure = new Error(`HTTP ${page.status}`); + } catch (error) { + if (signal?.aborted) throw new SearchUnavailable('The search was cancelled.', 'WEB_ABORTED', { cause: error }); + failure = error; + } + if (attempt === 0) await sleep(RETRY_PAUSE_MS + Math.floor(random() * 1000)); + } + return { failure }; + } + + async function searchDuckDuckGo(query, signal) { + const form = new URLSearchParams({ q: query, b: '', kl: 'wt-wt', df: '' }).toString(); + const post = (url, origin) => () => [url, { method: 'POST', headers: headers(origin, { 'content-type': 'application/x-www-form-urlencoded' }), body: form }]; + let reachedOnce = false; + for (const [url, origin, parse] of [[HTML_URL, 'https://html.duckduckgo.com', parseHtmlResults], [LITE_URL, 'https://lite.duckduckgo.com', parseLiteResults]]) { + const page = await ask(ddg, post(url, origin), signal); + if (page.failure) return { failure: page.failure }; + reachedOnce = true; + // A refusal on the first page is a refusal for the whole address: the lite page would only add one more strike. + if (looksBlocked(page.status, page.html)) { refuse(ddg, page.res); return { refused: true }; } + const sources = parse(page.html); + if (sources.length) { accepted(ddg); return { sources }; } + } + if (reachedOnce) accepted(ddg); + return { sources: [] }; + } + + async function searchBing(query, signal) { + const url = `${BING_URL}?${new URLSearchParams({ q: query, setlang: 'en' })}`; + const page = await ask(bing, () => [url, { method: 'GET', headers: headers(null) }], signal); + if (page.failure) return { failure: page.failure }; + if (bingLooksBlocked(page.status, page.html)) { refuse(bing, page.res); return { refused: true }; } + accepted(bing); + return { sources: parseBingResults(page.html) }; } return { id: DDG_PROVIDER_ID, available: () => typeof fetchImpl === 'function', + /** What happened so far, for tests and for the status line in the app's log. */ + status: () => ({ duckduckgo: { strikes: ddg.strikes, refusals: ddg.refusals, blockedForMs: Math.max(0, ddg.blockedUntil - now()) }, bing: { strikes: bing.strikes, refusals: bing.refusals, blockedForMs: Math.max(0, bing.blockedUntil - now()) }, cached: cache.size }), async search(request, signal) { const query = String(request.query ?? '').trim().slice(0, 400); if (!query) throw new SearchUnavailable('Type what to search for.', 'WEB_PROVIDER_ERROR'); - const key = query.toLowerCase(); + const key = queryKey(query); + const want = request.maxResults ?? 10; const hit = cache.get(key); - if (hit && now() - hit.at < CACHE_MS) return { sources: hit.sources.slice(0, request.maxResults ?? 10), truncated: false }; - let sources = []; - let blocked = false; - for (const [url, parse] of [[HTML_URL, parseHtmlResults], [LITE_URL, parseLiteResults]]) { - await turn(signal); - let page; - try { page = await ask(url, query, signal); } - catch (error) { - if (signal?.aborted) throw new SearchUnavailable('The search was cancelled.', 'WEB_ABORTED', { cause: error }); - if (error?.name === 'TimeoutError') throw new SearchUnavailable('The search took too long. Try again.', 'WEB_TIMEOUT', { cause: error }); - throw new SearchUnavailable('The search could not reach DuckDuckGo. Check the internet connection and try again.', 'WEB_PROVIDER_ERROR', { cause: error }); - } - if (looksBlocked(page.status, page.html)) { blocked = true; continue; } - sources = parse(page.html); - if (sources.length) { blocked = false; break; } + if (hit && now() - hit.at < CACHE_MS) return { sources: hit.sources.slice(0, want), truncated: false }; + let limited = false, unreachable = false; + for (const [s, run] of [[ddg, searchDuckDuckGo], [bing, searchBing]]) { + if (s.blockedUntil > now()) { limited = true; continue; } // asked again too soon: that only extends a block + const result = await run(query, signal); + if (result.refused) { limited = true; continue; } + if (result.failure) { unreachable = true; continue; } + if (!result.sources.length) return { sources: [], truncated: false }; // a real search with no results is an answer, not an error + cache.set(key, { at: now(), sources: result.sources }); + if (cache.size > CACHE_SIZE) cache.delete(cache.keys().next().value); + return { sources: result.sources.slice(0, want), truncated: false }; } - if (!sources.length) { - if (blocked) throw new SearchUnavailable(BLOCKED_MESSAGE, 'WEB_RATE_LIMITED'); - return { sources: [], truncated: false }; // a real search with no results is an answer, not an error - } - cache.set(key, { at: now(), sources }); - if (cache.size > 60) cache.delete(cache.keys().next().value); - return { sources: sources.slice(0, request.maxResults ?? 10), truncated: false }; + if (limited) throw new SearchUnavailable(BLOCKED_MESSAGE, 'WEB_RATE_LIMITED'); + throw new SearchUnavailable(unreachable ? UNREACHABLE_MESSAGE : BLOCKED_MESSAGE, unreachable ? 'WEB_PROVIDER_ERROR' : 'WEB_RATE_LIMITED'); }, }; } diff --git a/apps/host/src/components/PlanCard.tsx b/apps/host/src/components/PlanCard.tsx index acaa1618..920bb1d3 100644 --- a/apps/host/src/components/PlanCard.tsx +++ b/apps/host/src/components/PlanCard.tsx @@ -59,6 +59,7 @@ export function PlanCard({ chatId, planId }: { chatId: string | null | undefined return
{tr("Plan")}{planCount(plan)}
+ {plan.caution ?

{tr(plan.caution)}

: null} {proposed ?

{tr("Nothing runs until you approve.")}

: null} {proposed ?
void run(() => approvePlan(chatId, plan.id))}>{tr("Approve")} diff --git a/apps/host/src/components/SettingsTools.tsx b/apps/host/src/components/SettingsTools.tsx index 480a124a..b6ace950 100644 --- a/apps/host/src/components/SettingsTools.tsx +++ b/apps/host/src/components/SettingsTools.tsx @@ -130,7 +130,7 @@ export function SettingsTools({ preview }: { preview?: ToolsState }) {

{tr('Web search')}

- + : null)}
  1. {tr("In your client, choose a compatible provider.")}
  2. {tr("Set its base URL to ")}{serving.baseUrl}.
  3. {tr("Use model ID ")}{loaded?.apiModelId ?? 'from the Models screen after loading'}.
  4. {tr(serving.access.apiKeySet ? 'Enter your existing API key in the client.' : 'This local API has no key configured.')}
{tr(protocol === 'responses' && (!native?.instances.some(i => i.status === 'ready') || native.capabilities.responses === false) ?

{tr("Responses requires a running native model and a Strata version that supports this API. Update the native installation in Settings \u2192 About if needed.")}

: null)}
{tr("curl")} void navigator.clipboard.writeText(code)}/>
{code}

{tr("Model list: ")}{tr(serving.baseUrl)}{tr(serving.endpoints.models)}{tr(". Network access depends on the host\u2019s listen address and your firewall.")}

+
setGuide(false)} headerActions={
} sheet>
{tr(multipleModels ?