Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
feat(search): synchronize public adapters and query contracts
wyt7a46df4c7331
diff --git a/src/main/features/search_auth.ts b/src/main/features/search_auth.tsindex 1531b2ec..b926991a 100644--- a/src/main/features/search_auth.ts+++ b/src/main/features/search_auth.ts@@ -7,6 +7,7 @@** Supported search providers (one-shot adapters in `model/core-agent/search-tools.ts`):* - tavily (https://tavily.com)+ * - deepseek (https://api-docs.deepseek.com/guides/search/)* - serper (https://serper.dev)* - brave-search (https://brave.com/search/api/)* - baidu-ai-search (https://cloud.baidu.com/doc/qianfan-api/s/em82g4tlk)diff --git a/src/main/model/core-agent/search-adapters.ts b/src/main/model/core-agent/search-adapters.tsindex fd75abf3..bd6876e2 100644--- a/src/main/model/core-agent/search-adapters.ts+++ b/src/main/model/core-agent/search-adapters.ts@@ -12,9 +12,11 @@* `features/search_auth.ts::addSearchProfile`.*/+import { randomUUID } from 'node:crypto';import type { SearchProfile } from '../../features/auth';import { createLogger } from '../../logger';-import { fetchAndReadWithTimeout } from '../../util/abort';+import { composeAbortSignal, fetchAndReadWithTimeout } from '../../util/abort';+import { getSearchQueryMaxChars, validateSearchQuery } from '../../util/search-contract';import {ORKAS_API_BASE_URL,ORKAS_API_KEYS_URL,@@ -36,16 +38,31 @@ export interface SearchAdapterResult {results: NormalisedSearchResult[];}-/** Account-level search failure that should not be retried immediately. */-export class SearchAccountError extends Error {- constructor(message: string) {- super(message);- this.name = 'SearchAccountError';+const REQUEST_TIMEOUT_MS = 30_000;+const MAX_RESPONSE_BYTES = 2_000_000;+class SearchBodyTooLargeError extends Error {}++async function readSearchBody(response: Response): Promise<string> {+ if (!response.body) return '';+ const reader = response.body.getReader();+ const decoder = new TextDecoder();+ let size = 0;+ let text = '';+ try {+ while (true) {+ const { value, done } = await reader.read();+ if (done) break;+ size += value.byteLength;+ if (size > MAX_RESPONSE_BYTES) throw new SearchBodyTooLargeError('Search response is too large');+ text += decoder.decode(value, { stream: true });+ }+ return text + decoder.decode();+ } finally {+ await reader.cancel().catch(() => undefined);+ reader.releaseLock();}}-const REQUEST_TIMEOUT_MS = 30_000;-async function fetchTextWithTimeout(url: string,init: RequestInit,@@ -57,7 +74,7 @@ async function fetchTextWithTimeout(timeoutMs,null,`Search request timed out after ${timeoutMs}ms`,- (resp) => resp.text(),+ readSearchBody,);return { response, text: body };}@@ -70,6 +87,41 @@ function clamp(n: number, min: number, max: number): number {return Math.max(min, Math.min(max, n));}+function normaliseResults(text: string, provider: 'deepseek' | 'tavily', count: number): NormalisedSearchResult[] {+ let data: any;+ try { data = JSON.parse(text); } catch { throw new Error(`${SEARCH_PROVIDER_LABEL[provider]} search returned an invalid response`); }+ if (!data || !Array.isArray(data.results) || data.results.length > 100) {+ throw new Error(`${SEARCH_PROVIDER_LABEL[provider]} search returned an invalid response`);+ }+ const results: NormalisedSearchResult[] = [];+ for (const item of data.results) {+ if (!item || typeof item.url !== 'string' || item.url.length > 4096) continue;+ const url = item.url.trim();+ try {+ const parsed = new URL(url);+ if (!['http:', 'https:'].includes(parsed.protocol) || !parsed.hostname || parsed.username || parsed.password) continue;+ } catch { continue; }+ const snippet = provider === 'deepseek' ? item.summary || item.snippet || ''+ : item.content || '';+ if (typeof snippet !== 'string' || (item.title != null && typeof item.title !== 'string')) continue;+ results.push({ title: (item.title || '').slice(0, 512), url, snippet: snippet.slice(0, 10000) });+ if (results.length >= count) break;+ }+ return results;+}++/**+ * Account-level search failure (credits exhausted / auth), not "no results".+ * Keep the HTTP status so callers can distinguish a balance that payment can+ * restore from rejected credentials. Both fall back without an inline retry.+ */+export class SearchAccountError extends Error {+ constructor(message: string, readonly statusCode?: number) {+ super(message);+ this.name = 'SearchAccountError';+ }+}+// ── Orkas public search API ─────────────────────────────────────────────async function orkasApiSearch(@@ -107,28 +159,95 @@ async function orkasApiSearch(async function tavilySearch(profile: SearchProfile, query: string, count: number): Promise<SearchAdapterResult> {const body = JSON.stringify({- api_key: profile.apiKey,query,max_results: clamp(count, 1, 20),search_depth: 'basic',});const { response: resp, text } = await fetchTextWithTimeout('https://api.tavily.com/search', {method: 'POST',- headers: { 'Content-Type': 'application/json' },+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${profile.apiKey}` },body,});if (!resp.ok) {- throw new Error(`Tavily ${resp.status}: ${text.slice(0, 300)}`);+ // Never expose provider error bodies: they may echo the key or query.+ const message = `Tavily search ${resp.status}: request failed`;+ if ([401, 402, 403].includes(resp.status)) throw new SearchAccountError(message, resp.status);+ throw new Error(message);}- const data = parseJson(text) as { results?: Array<{ title?: string; url?: string; content?: string }> };- return {- provider: 'tavily',- results: (data.results || []).map((r) => ({- title: String(r.title || ''),- url: String(r.url || ''),- snippet: String(r.content || ''),- })).filter((r) => r.url),+ return { provider: 'tavily', results: normaliseResults(text, 'tavily', count) };+}++// ── DeepSeek ────────────────────────────────────────────────────────────++function searchTransportReason(error: unknown): string {+ // Node/Undici preserve structured causes. Never infer a cause from prose.+ let cause: any = error;+ const known: Record<string, string> = {+ ENOTFOUND: 'dns_error', EAI_AGAIN: 'dns_error', ECONNREFUSED: 'connect_error',+ ECONNRESET: 'connection_reset', ETIMEDOUT: 'transport_timeout',+ UND_ERR_CONNECT_TIMEOUT: 'connect_timeout', UND_ERR_HEADERS_TIMEOUT: 'headers_timeout',+ UND_ERR_BODY_TIMEOUT: 'read_timeout', CERT_HAS_EXPIRED: 'tls_error',+ ERR_TLS_CERT_ALTNAME_INVALID: 'tls_error', UNABLE_TO_VERIFY_LEAF_SIGNATURE: 'tls_error',+ SELF_SIGNED_CERT_IN_CHAIN: 'tls_error',};+ try {+ for (let i = 0; cause && i < 4; i++) {+ if (typeof cause.code === 'string' && Object.hasOwn(known, cause.code)) return known[cause.code];+ cause = cause.cause;+ }+ } catch { /* A nonstandard error accessor must not replace the failure. */ }+ return 'transport_error';+}++async function deepseekSearch(profile: SearchProfile, query: string, count: number): Promise<SearchAdapterResult> {+ const started = performance.now();+ const searchRef = randomUUID();+ const timeoutMessage = 'Search request timed out after 60000ms';+ const composed = composeAbortSignal(null, 60_000, timeoutMessage);+ let phase = 'before_response';+ let status = 0;+ let result = 'failure';+ let reason = 'transport_error';+ try {+ const resp = await fetch('https://api.deepseek.com/v1/tools/search', {+ method: 'POST', signal: composed.signal,+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${profile.apiKey}` },+ body: JSON.stringify({ query, count: clamp(Math.trunc(count) || 1, 1, 20), need_content: false }),+ });+ status = resp.status;+ phase = 'after_response';+ const text = await readSearchBody(resp);+ if (!resp.ok) {+ reason = 'http_error';+ const message = `DeepSeek search ${resp.status}: request failed`;+ if ([401, 402, 403].includes(resp.status)) throw new SearchAccountError(message, resp.status);+ throw new Error(message);+ }+ phase = 'response_validation';+ reason = 'invalid_response';+ const results = normaliseResults(text, 'deepseek', count);+ result = results.length ? 'success' : 'empty';+ reason = results.length ? 'none' : 'empty_results';+ return { provider: 'deepseek', results };+ } catch (error) {+ if (composed.signal.aborted) {+ reason = 'deadline_timeout';+ throw new Error(timeoutMessage);+ }+ if (error instanceof SearchBodyTooLargeError) reason = 'response_too_large';+ else if (phase !== 'response_validation' && reason !== 'http_error') reason = searchTransportReason(error);+ throw error;+ } finally {+ composed.cleanup();+ // One constant-size local observation, including the actual header status+ // on body failures. No account/profile id, query, URL or exception text.+ try {+ const data = { provider: 'deepseek', search_ref: searchRef, result, reason, phase,+ status_code: status, duration_ms: Math.min(1_000_000, Math.max(0, Math.round(performance.now() - started))) };+ if (result === 'failure') log.warn('search provider result', data);+ else log.debug('search provider result', data);+ } catch { /* Diagnostics cannot trigger fallback or change the result. */ }+ }}// ── Serper ──────────────────────────────────────────────────────────────@@ -146,9 +265,9 @@ async function serperSearch(profile: SearchProfile, query: string, count: numberif (!resp.ok) {throw new Error(`Serper ${resp.status}: ${text.slice(0, 300)}`);}- const data = parseJson(text) as {+ const data = parseJson<{organic?: Array<{ title?: string; link?: string; snippet?: string }>;- };+ }>(text);return {provider: 'serper',results: (data.organic || []).map((r) => ({@@ -176,9 +295,9 @@ async function braveApiSearch(profile: SearchProfile, query: string, count: numbif (!resp.ok) {throw new Error(`Brave Search ${resp.status}: ${text.slice(0, 300)}`);}- const data = parseJson(text) as {+ const data = parseJson<{web?: { results?: Array<{ title?: string; url?: string; description?: string }> };- };+ }>(text);return {provider: 'brave-search',results: (data.web?.results || []).map((r) => ({@@ -218,9 +337,9 @@ async function baiduAiSearch(profile: SearchProfile, query: string, count: numbeif (!resp.ok) {throw new Error(`Baidu AI Search ${resp.status}: ${text.slice(0, 300)}`);}- const data = parseJson(text) as {+ const data = parseJson<{references?: Array<{ title?: string; url?: string; web_anchor?: string; snippet?: string; content?: string }>;- };+ }>(text);return {provider: 'baidu-ai-search',results: (data.references || []).map((r) => ({@@ -235,11 +354,11 @@ async function baiduAiSearch(profile: SearchProfile, query: string, count: numbe/*** Metaso AI Search:- * Endpoint: POST https://api.metaso.cn/search+ * Endpoint: POST https://metaso.cn/api/v1/search* Auth: Authorization: Bearer <api-key>- * Docs / console: https://metaso.cn/+ * Docs / console: https://metaso.cn/search-api/playground*- * Request body core fields (verified 2026-04):+ * Request body core fields (official playground + MCP catalog):* - q (string, required)* - scope: 'webpage' | 'document' | 'scholar' | 'podcast' | 'video' | 'image'* (default 'webpage')@@ -258,7 +377,7 @@ async function metasoSearch(profile: SearchProfile, query: string, count: numbersize: clamp(count, 1, 20),includeSummary: false,});- const { response: resp, text } = await fetchTextWithTimeout('https://api.metaso.cn/search', {+ const { response: resp, text } = await fetchTextWithTimeout('https://metaso.cn/api/v1/search', {method: 'POST',headers: {'Content-Type': 'application/json',@@ -269,7 +388,7 @@ async function metasoSearch(profile: SearchProfile, query: string, count: numberif (!resp.ok) {throw new Error(`Metaso ${resp.status}: ${text.slice(0, 300)}`);}- const data = parseJson(text) as Record<string, unknown>;+ const data = parseJson<Record<string, unknown>>(text);const list: any[] = Array.isArray((data as any).references) ? (data as any).references: Array.isArray((data as any).results) ? (data as any).results: Array.isArray((data as any).data) ? (data as any).data@@ -297,6 +416,7 @@ export type SearchAdapter = (export const searchAdaptersByProvider: Record<string, SearchAdapter> = {[ORKAS_API_PROVIDER]: orkasApiSearch,tavily: tavilySearch,+ deepseek: deepseekSearch,serper: serperSearch,'brave-search': braveApiSearch,'baidu-ai-search': baiduAiSearch,@@ -308,6 +428,7 @@ export const searchAdaptersByProvider: Record<string, SearchAdapter> = {export const SEARCH_PROVIDER_LABEL: Record<string, string> = {[ORKAS_API_PROVIDER]: 'Orkas · Search',tavily: 'Tavily',+ deepseek: 'DeepSeek',serper: 'Serper','brave-search': 'Brave','baidu-ai-search': 'Baidu',@@ -318,6 +439,7 @@ export const SEARCH_PROVIDER_LABEL: Record<string, string> = {export const SEARCH_PROVIDER_DOCS: Record<string, string> = {[ORKAS_API_PROVIDER]: ORKAS_API_KEYS_URL,tavily: 'https://tavily.com/',+ deepseek: 'https://api-docs.deepseek.com/guides/search/',serper: 'https://serper.dev/','brave-search': 'https://brave.com/search/api/','baidu-ai-search': 'https://cloud.baidu.com/doc/qianfan-api/s/em82g4tlk',@@ -330,6 +452,9 @@ export async function runSearchAdapter(count: number,context?: OrkasApiUsageContext,): Promise<SearchAdapterResult> {+ query = query.trim();+ validateSearchQuery(query, getSearchQueryMaxChars(profile.provider));+ count = clamp(Math.trunc(count) || 1, 1, 20);const adapter = searchAdaptersByProvider[profile.provider];if (!adapter) throw new Error(`no search adapter registered for provider "${profile.provider}"`);log.debug('runSearchAdapter', { provider: profile.provider, count });diff --git a/src/main/model/core-agent/search-tools.ts b/src/main/model/core-agent/search-tools.tsindex a3be3f99..d7db1ab8 100644--- a/src/main/model/core-agent/search-tools.ts+++ b/src/main/model/core-agent/search-tools.ts@@ -30,6 +30,7 @@ import { listSearchProfiles } from '../../features/search_auth';import { runSearchAdapter, SEARCH_PROVIDER_LABEL, SearchAccountError } from './search-adapters';import { createLogger } from '../../logger';import { logErrorSummary } from '../../util/log-redact';+import { getSearchQueryMaxChars, validateSearchQuery } from '../../util/search-contract';// core-agent is ESM; main is CJS. Static import would yank pi-ai into the// CJS load graph and crash with `ERR_PACKAGE_PATH_NOT_EXPORTED`. Same@@ -97,6 +98,9 @@ function formatPaidResults(query: string, providerLabel: string, results: { titlexport async function createWebSearchOverrideTool(context?: SearchExecutionContext): Promise<AgentTool> {const mod = await ca();+ const firstProfile = listSearchProfiles()[0];+ // Keyless search retains its existing unrestricted query contract.+ const maxQueryChars = firstProfile ? getSearchQueryMaxChars(firstProfile.provider) : undefined;const runKeylessFallback = async (query: string,count: number,@@ -140,7 +144,7 @@ export async function createWebSearchOverrideTool(context?: SearchExecutionConteinputSchema: {type: 'object',properties: {- query: { type: 'string', description: 'The search query.' },+ query: { type: 'string', ...(maxQueryChars !== undefined ? { maxLength: maxQueryChars } : {}), description: 'The search query; length is measured in Unicode characters.' },count: { type: 'number', description: `Number of results to return (default: ${DEFAULT_COUNT}, max: ${MAX_COUNT}).` },},required: ['query'],@@ -152,6 +156,13 @@ export async function createWebSearchOverrideTool(context?: SearchExecutionConteif (!query) return { content: 'Error: query is required', isError: true };const profiles = listSearchProfiles();+ // A changed setting can tighten this run's advertised bound. A wider+ // schema takes effect when the next runner constructs its tools.+ const currentMax = profiles[0] ? getSearchQueryMaxChars(profiles[0].provider) : undefined;+ const applicableMax = Math.min(maxQueryChars ?? Infinity, currentMax ?? Infinity);+ try { if (Number.isFinite(applicableMax)) validateSearchQuery(query, applicableMax); } catch (error) {+ return { content: (error as Error).message, isError: true };+ }if (profiles.length) {const userId = getActiveUserId();const candidates = profiles.map(profile => ({ profile, key: searchCooldownKey(userId, profile) }));@@ -165,6 +176,10 @@ export async function createWebSearchOverrideTool(context?: SearchExecutionContecontinue;}paidSearchCooldowns.delete(key);+ // Input incompatibility must not advance the fallback chain or dispatch a request.+ try { validateSearchQuery(query, getSearchQueryMaxChars(profile.provider)); } catch (error) {+ return { content: (error as Error).message, isError: true };+ }log.info('web_search via paid API', { provider: profile.provider, query_len: query.length, count });try {const res = await runSearchAdapter(profile, query, count, context);diff --git a/src/main/util/search-contract.ts b/src/main/util/search-contract.tsnew file mode 100644index 00000000..daa50296--- /dev/null+++ b/src/main/util/search-contract.ts@@ -0,0 +1,17 @@+/** Default configured-service query bound, measured in Unicode characters. */+const DEFAULT_SEARCH_QUERY_CHARS = 128;++export function getSearchQueryMaxChars(provider?: string): number {+ // Tavily permits longer queries. The keyless route does not use this bound.+ return provider === 'tavily' ? 400 : DEFAULT_SEARCH_QUERY_CHARS;+}++export function validateSearchQuery(query: string, maxChars = DEFAULT_SEARCH_QUERY_CHARS): void {+ if (!query.trim()) throw new Error('A search query is required');+ let length = 0;+ for (const _character of query) {+ if (++length > maxChars) {+ throw new Error(`This search service supports at most ${maxChars} Unicode characters. Shorten the query and try again.`);+ }+ }+}diff --git a/test/main/features/search_auth.test.ts b/test/main/features/search_auth.test.tsindex 239af3aa..36d90fdb 100644--- a/test/main/features/search_auth.test.ts+++ b/test/main/features/search_auth.test.ts@@ -12,11 +12,8 @@ vi.mock('../../../src/main/features/auth', () => ({mocks.profiles = profiles.map((profile) => ({ ...profile }));},}));-vi.mock('../../../src/main/model/core-agent/search-adapters', () => ({- searchAdaptersByProvider: {- tavily: vi.fn(),- serper: vi.fn(),- },+vi.mock('../../../src/main/model/core-agent/search-adapters', async importOriginal => ({+ ...await importOriginal(),runSearchAdapter: mocks.runSearchAdapter,}));vi.mock('../../../src/main/logger', () => ({@@ -34,6 +31,15 @@ beforeEach(() => {});describe('search credential profiles', () => {+ it('accepts and probes a user-owned DeepSeek key without a managed session',async()=>{+ const auth=await import('../../../src/main/features/search_auth');+ const added=auth.addSearchProfile({provider:'deepseek',apiKey:'fixture-key'});+ expect(added.ok).toBe(true);if(!added.ok)throw new Error('profile rejected');+ mocks.runSearchAdapter.mockResolvedValue({provider:'deepseek',results:[]});+ expect(await auth.testSearchProfile(added.id)).toMatchObject({ok:true});+ expect(auth.listSearchProfiles()).toHaveLength(1);+ expect(mocks.runSearchAdapter).toHaveBeenCalledWith(expect.objectContaining({provider:'deepseek',apiKey:'fixture-key'}),'Orkas connectivity probe',1);+ });it('does not create duplicate fallback rows for the same provider and key', async () => {const searchAuth = await import('../../../src/main/features/search_auth');diff --git a/test/main/model/core-agent/search-adapters.test.ts b/test/main/model/core-agent/search-adapters.test.tsindex 14b7274d..87b361b8 100644--- a/test/main/model/core-agent/search-adapters.test.ts+++ b/test/main/model/core-agent/search-adapters.test.ts@@ -1,18 +1,25 @@-import { afterEach, describe, expect, it, vi } from 'vitest';-const h = vi.hoisted(() => ({ warn: vi.fn(), error: vi.fn() }));+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+const h = vi.hoisted(() => ({ warn: vi.fn(), error: vi.fn(), candidates: [] as any[], builtin: vi.fn() }));vi.mock('../../../../src/main/logger', () => ({createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: h.warn, error: h.error }),}));+vi.mock('../../../../src/main/features/users', () => ({getActiveUserId:()=> 'synthetic-search-user'}));+vi.mock('../../../../src/main/features/search_auth', () => ({listSearchProfiles:()=>h.candidates}));+vi.mock('#core-agent',()=>({defineTool:(tool:any)=>tool,runBuiltinWebSearch:(...args:any[])=>h.builtin(...args)}));+import {runSearchAdapter,+ SearchAccountError,SEARCH_PROVIDER_LABEL,searchAdaptersByProvider,} from '../../../../src/main/model/core-agent/search-adapters';+beforeEach(() => { vi.resetModules(); h.warn.mockReset(); h.error.mockReset(); h.candidates=[]; h.builtin.mockReset().mockResolvedValue({content:'Independent fallback evidence'}); });afterEach(() => {vi.unstubAllGlobals();+ expect(h.error).not.toHaveBeenCalled();});describe('open-source BYO search adapters', () => {@@ -122,6 +129,7 @@ describe('open-source BYO search adapters', () => {expect(Object.keys(searchAdaptersByProvider).sort()).toEqual(['baidu-ai-search','brave-search',+ 'deepseek','metaso','orkas-api','serper',@@ -131,23 +139,263 @@ describe('open-source BYO search adapters', () => {});describe('search transfer deadlines', () => {- it.each(['orkas-api', 'tavily', 'serper', 'brave-search', 'baidu-ai-search', 'metaso'])('keeps the %s deadline active while reading the response body', async (provider) => {+ it.each(['orkas-api', 'tavily', 'serper', 'brave-search', 'baidu-ai-search', 'metaso', 'deepseek'])('keeps the %s deadline active while reading the response body', async (provider) => {vi.useFakeTimers();try {let responseSignal: AbortSignal | undefined;- const readBody = () => new Promise<string>((_resolve, reject) => {- responseSignal!.addEventListener('abort', () => reject(new Error('body aborted')), { once: true });- });vi.stubGlobal('fetch', vi.fn(async (_url, init) => {responseSignal = init.signal;- return { ok: true, status: 200, text: readBody, json: readBody };+ return new Response(new ReadableStream({ start(controller) {+ responseSignal!.addEventListener('abort', () => controller.error(new Error('body aborted')), { once: true });+ } }));}));const pending = runSearchAdapter({ id: 'test', provider, apiKey: 'fixture', label: '', createdAt: 0 } as any, 'query', 1);const outcome = pending.then(() => 'success', () => 'failed');- await vi.advanceTimersByTimeAsync(30_001);+ await vi.advanceTimersByTimeAsync(provider === 'deepseek' ? 60_001 : 30_001);expect(responseSignal?.aborted).toBe(true);expect(await outcome).toBe('failed');} finally { vi.useRealTimers(); }});});++describe('configured DeepSeek search', () => {+ afterEach(() => { vi.unstubAllGlobals(); vi.useRealTimers(); });++ // Independent protocol oracle: https://api-docs.deepseek.com/api/search/.+ it('returns model-readable overseas evidence using one standalone authenticated search', async () => {+ const fetch = vi.fn(async () => new Response(JSON.stringify({ results: [+ { title: 'NASA mission', url: 'https://www.nasa.gov/mission/', snippet: 'Short display text', summary: 'Detailed source evidence for the model.', content: '' },+ { title: 'European source', url: 'https://www.esa.int/', snippet: 'Available short evidence', summary: '' },+ ] })));+ vi.stubGlobal('fetch', fetch);+ const { runSearchAdapter } = await import('../../../../src/main/model/core-agent/search-adapters');+ const result = await runSearchAdapter({ provider: 'deepseek', apiKey: 'fixture-key' } as any,+ 'space missions lang:en', 8);+ expect(result).toEqual({ provider: 'deepseek', results: [+ { title: 'NASA mission', url: 'https://www.nasa.gov/mission/', snippet: 'Detailed source evidence for the model.' },+ { title: 'European source', url: 'https://www.esa.int/', snippet: 'Available short evidence' },+ ] });+ expect(fetch).toHaveBeenCalledOnce();+ const [url, init] = fetch.mock.calls[0] as any;+ expect(url).toBe('https://api.deepseek.com/v1/tools/search');+ expect(init.headers).toEqual({ 'Content-Type': 'application/json', Authorization: 'Bearer fixture-key' });+ expect(JSON.parse(init.body)).toEqual({ query: 'space missions lang:en', count: 8, need_content: false });+ });++ it.each([127, 128, 129])('preserves Unicode query semantics at the %s-character boundary', async length => {+ const fetch = vi.fn(async () => new Response(JSON.stringify({ results: [] })));+ vi.stubGlobal('fetch', fetch);+ const { runSearchAdapter } = await import('../../../../src/main/model/core-agent/search-adapters');+ const query = '🌏'.repeat(length);+ const operation = runSearchAdapter({ provider: 'deepseek', apiKey: 'fixture-key' } as any, query, 5);+ if (length <= 128) {+ await expect(operation).resolves.toEqual({ provider: 'deepseek', results: [] });+ expect(JSON.parse((fetch.mock.calls[0] as any)[1].body).query).toBe(query);+ } else {+ await expect(operation).rejects.toThrow('128');+ expect(fetch).not.toHaveBeenCalled();+ }+ });++ it.each([401, 402, 403, 429, 500])('preserves HTTP %s failure without replay or exposing upstream content', async status => {+ const fetch = vi.fn(async () => new Response('private-query fixture-key', { status }));+ vi.stubGlobal('fetch', fetch);+ const { runSearchAdapter, SearchAccountError } = await import('../../../../src/main/model/core-agent/search-adapters');+ const error = await runSearchAdapter({ provider: 'deepseek', apiKey: 'fixture-key' } as any, 'public query', 8).catch(e => e);+ expect(error).toBeInstanceOf(Error);+ expect(error.message).toContain(String(status));+ expect(error.message).not.toMatch(/private-query|fixture-key/);+ expect(error instanceof SearchAccountError).toBe([401, 402, 403].includes(status));+ expect(fetch).toHaveBeenCalledOnce();+ });++ it.each(['{}', '{"results":{}}', 'not JSON'])('does not report a malformed upstream response as no matches (%s)', async body => {+ vi.stubGlobal('fetch', vi.fn(async () => new Response(body)));+ const { runSearchAdapter } = await import('../../../../src/main/model/core-agent/search-adapters');+ await expect(runSearchAdapter({ provider: 'deepseek', apiKey: 'fixture-key' } as any, 'public query', 8))+ .rejects.toThrow('invalid response');+ });++ it('bounds the network wait and does not retry a timeout', async () => {+ vi.useFakeTimers();+ const fetch = vi.fn((_url, init) => new Promise<Response>((_resolve, reject) => {+ init.signal.addEventListener('abort', () => reject(init.signal.reason));+ }));+ vi.stubGlobal('fetch', fetch);+ const { runSearchAdapter } = await import('../../../../src/main/model/core-agent/search-adapters');+ const operation = runSearchAdapter({ provider: 'deepseek', apiKey: 'fixture-key' } as any, 'public query', 8).catch(error => error);+ await vi.advanceTimersByTimeAsync(60_000);+ expect(await operation).toMatchObject({ message: expect.stringContaining('timed out') });+ expect(fetch).toHaveBeenCalledOnce();+ });+});++describe('configured Metaso request contract', () => {+ afterEach(() => { vi.unstubAllGlobals(); });++ // Endpoint/body oracle: the official playground's generated request source+ // https://metaso.cn/search-api/playground. Its official MCP listing also+ // declares size as an integer. Legacy response mappings remain compatible.+ it.each([[0, 1], [50, 20]])('uses the official endpoint with bounded count %s', async (count, expected) => {+ const fetch = vi.fn(async () => new Response(JSON.stringify({ results: [{ title: 'Source', link: 'https://example.test/source', snippet: 'Evidence' }] })));+ vi.stubGlobal('fetch', fetch);+ const { runSearchAdapter } = await import('../../../../src/main/model/core-agent/search-adapters');+ expect(await runSearchAdapter({ provider: 'metaso', apiKey: 'fixture-key' } as any, 'research', count))+ .toEqual({ provider: 'metaso', results: [{ title: 'Source', url: 'https://example.test/source', snippet: 'Evidence' }] });+ expect(fetch).toHaveBeenCalledOnce();+ const [url, init] = fetch.mock.calls[0] as any;+ expect(url).toBe('https://metaso.cn/api/v1/search');+ expect(init.headers.Authorization).toBe('Bearer fixture-key');+ expect(JSON.parse(init.body)).toEqual({ q: 'research', scope: 'webpage', size: expected, includeSummary: false });+ });++ it('does not report an authentication failure as an empty search or replay it', async () => {+ const fetch = vi.fn(async () => new Response('unauthorized', { status: 401 })); vi.stubGlobal('fetch', fetch);+ const { runSearchAdapter } = await import('../../../../src/main/model/core-agent/search-adapters');+ await expect(runSearchAdapter({ provider: 'metaso', apiKey: 'fixture-key' } as any, 'research', 5)).rejects.toThrow('Metaso 401');+ expect(fetch).toHaveBeenCalledOnce();+ });+});+++describe('configured DeepSeek failure diagnostics', () => {+ beforeEach(() => { h.warn.mockReset(); });+ afterEach(() => { vi.unstubAllGlobals(); vi.useRealTimers(); });+ it.each([401,429,502])('records HTTP %s without query, key or provider prose', async status => {+ const fetch = vi.fn(async()=>new Response('PRIVATE_ERROR PRIVATE_KEY PRIVATE_QUERY',{status}));+ vi.stubGlobal('fetch',fetch);+ const {runSearchAdapter}=await import('../../../../src/main/model/core-agent/search-adapters');+ await expect(runSearchAdapter({provider:'deepseek',apiKey:'PRIVATE_KEY'} as any,'PRIVATE_QUERY',8)).rejects.toThrow(String(status));+ expect(fetch).toHaveBeenCalledOnce();+ const [message,data]=h.warn.mock.calls.at(-1)!;+ expect(message).toBe('search provider result');+ expect(data).toMatchObject({provider:'deepseek',result:'failure',reason:'http_error',phase:'after_response',status_code:status});+ expect(data.duration_ms).toBeGreaterThanOrEqual(0);+ expect(typeof data.search_ref).toBe('string');+ expect(JSON.stringify(h.warn.mock.calls)).not.toMatch(/PRIVATE_/);+ });+ it('distinguishes a DNS failure before headers using only structured causes',async()=>{+ vi.stubGlobal('fetch',vi.fn(async()=>{throw new Error('PRIVATE_ERROR /private/path',{cause:{code:'ENOTFOUND'}});}));+ const {runSearchAdapter}=await import('../../../../src/main/model/core-agent/search-adapters');+ await expect(runSearchAdapter({provider:'deepseek',apiKey:'fixture'} as any,'query',8)).rejects.toThrow();+ expect(h.warn.mock.calls.at(-1)?.[1]).toMatchObject({reason:'dns_error',phase:'before_response',status_code:0});+ expect(JSON.stringify(h.warn.mock.calls)).not.toMatch(/PRIVATE_ERROR|private\/path/);+ });+ it('keeps HTTP 200 and the body phase when the full-body deadline expires',async()=>{+ vi.useFakeTimers();+ vi.stubGlobal('fetch',vi.fn(async(_url,init)=>new Response(new ReadableStream({start(controller){+ init.signal.addEventListener('abort',()=>controller.error(init.signal.reason));+ }}))));+ const {runSearchAdapter}=await import('../../../../src/main/model/core-agent/search-adapters');+ const operation=runSearchAdapter({provider:'deepseek',apiKey:'fixture'} as any,'query',8).catch(e=>e);+ await vi.advanceTimersByTimeAsync(60_000);+ expect(await operation).toBeInstanceOf(Error);+ expect(h.warn.mock.calls.at(-1)?.[1]).toMatchObject({reason:'deadline_timeout',phase:'after_response',status_code:200});+ });+ it('keeps the original failure when an error accessor or diagnostic sink throws',async()=>{+ const original=new Error('fixture transport failure');+ Object.defineProperty(original,'code',{get(){throw new Error('PRIVATE_ERROR');}});+ const fetch=vi.fn(async()=>{throw original;}); vi.stubGlobal('fetch',fetch);+ h.warn.mockImplementationOnce(()=>{throw new Error('PRIVATE_ERROR');});+ const {runSearchAdapter}=await import('../../../../src/main/model/core-agent/search-adapters');+ await expect(runSearchAdapter({provider:'deepseek',apiKey:'fixture'} as any,'query',8)).rejects.toBe(original);+ expect(fetch).toHaveBeenCalledOnce();+ expect(h.warn.mock.calls.at(-1)?.[1]).toMatchObject({reason:'transport_error',status_code:0});+ });+ it('records validation failure rather than transport failure for malformed data',async()=>{+ vi.stubGlobal('fetch',vi.fn(async()=>new Response('PRIVATE_ERROR')));+ const {runSearchAdapter}=await import('../../../../src/main/model/core-agent/search-adapters');+ await expect(runSearchAdapter({provider:'deepseek',apiKey:'fixture'} as any,'query',8)).rejects.toThrow('invalid response');+ expect(h.warn.mock.calls.at(-1)?.[1]).toMatchObject({reason:'invalid_response',phase:'response_validation',status_code:200});+ expect(JSON.stringify(h.warn.mock.calls)).not.toContain('PRIVATE_ERROR');+ });+});+++describe('public search query and response bounds', () => {+ it.each(['orkas-api', 'deepseek', 'serper', 'brave-search', 'baidu-ai-search', 'metaso', 'tavily'])('rejects over-limit Unicode input before %s dispatch', async provider => {+ const fetch = vi.fn(); vi.stubGlobal('fetch', fetch);+ await expect(runSearchAdapter({provider, apiKey:'fixture'} as any, '🌏'.repeat(provider === 'tavily' ? 401 : 129), 8)).rejects.toThrow(String(provider === 'tavily' ? 400 : 128));+ expect(fetch).not.toHaveBeenCalled();+ });+ it.each([['deepseek',128], ['tavily',400]] as const)('sends the complete trimmed %s Unicode query', async(provider,length)=>{+ const fetch=vi.fn(async()=>new Response(JSON.stringify({results:[]}))); vi.stubGlobal('fetch',fetch);+ const query='🌏'.repeat(length);+ await runSearchAdapter({provider,apiKey:'fixture'} as any,' '+query+' ',3);+ expect(JSON.parse((fetch.mock.calls[0] as any)[1].body).query).toBe(query);+ });+ it.each(['deepseek','tavily'])('rejects unsafe result URLs and bounds %s evidence',async provider=>{+ vi.stubGlobal('fetch',vi.fn(async()=>new Response(JSON.stringify({results:[+ {url:'javascript:alert(1)',summary:'unsafe',content:'unsafe'},+ {url:'https://user:[email protected]',summary:'secret',content:'secret'},+ {title:'Valid',url:'https://example.org/a',summary:'DS evidence',snippet:'Short',content:'TV evidence'},+ {title:'Extra',url:'https://example.org/b',summary:'extra',content:'extra'}+ ]}))));+ expect((await runSearchAdapter({provider,apiKey:'fixture'} as any,'query',1)).results).toEqual([+ {title:'Valid',url:'https://example.org/a',snippet:provider==='deepseek'?'DS evidence':'TV evidence'}+ ]);+ });+ it.each(['orkas-api','deepseek','tavily','serper','brave-search','baidu-ai-search','metaso'])('caps the %s body before parsing',async provider=>{+ const cancelled=vi.fn(); let sent=false;+ vi.stubGlobal('fetch',vi.fn(async()=>new Response(new ReadableStream({pull(controller){if(!sent){sent=true;controller.enqueue(new Uint8Array(2_000_001));}},cancel:cancelled}))));+ await expect(runSearchAdapter({provider,apiKey:'fixture'} as any,'query',8)).rejects.toThrow('too large');+ expect(cancelled).toHaveBeenCalledOnce();+ });+ it.each([401,402,403,429,500])('Tavily HTTP %s is safe, typed and not retried',async status=>{+ const fetch=vi.fn(async()=>new Response('PRIVATE_KEY PRIVATE_QUERY',{status})); vi.stubGlobal('fetch',fetch);+ const error=await runSearchAdapter({provider:'tavily',apiKey:'PRIVATE_KEY'} as any,'query',8).catch(error=>error);+ expect(error).toBeInstanceOf(Error); expect(error.message).toContain(String(status));+ expect(error.message).not.toContain('PRIVATE_');+ expect(error instanceof SearchAccountError).toBe([401,402,403].includes(status));+ expect(fetch).toHaveBeenCalledOnce();+ });+ it('uses only the Tavily Authorization header for the user key',async()=>{+ const fetch=vi.fn(async()=>new Response(JSON.stringify({results:[]})));vi.stubGlobal('fetch',fetch);+ await runSearchAdapter({provider:'tavily',apiKey:'fixture-key'} as any,'query',8);+ const [,init]=fetch.mock.calls[0] as any;+ expect(init.headers.Authorization).toBe('Bearer fixture-key');+ expect(JSON.parse(init.body)).toEqual({query:'query',max_results:8,search_depth:'basic'});+ });+ it.each(['{}','{"results":{}}','not JSON'])('does not turn malformed Tavily data into empty matches (%s)',async body=>{+ vi.stubGlobal('fetch',vi.fn(async()=>new Response(body)));+ await expect(runSearchAdapter({provider:'tavily',apiKey:'fixture'} as any,'query',8)).rejects.toThrow('invalid response');+ });+});+++describe('configured public search through the real adapter and tool',()=>{+ it('uses the existing credential cooldown after rejected DeepSeek credentials, retaining free fallback',async()=>{+ h.candidates=[{id:'deepseek',provider:'deepseek',apiKey:'fixture-key'}];+ const fetch=vi.fn(async()=>new Response('PRIVATE_UPSTREAM',{status:401}));vi.stubGlobal('fetch',fetch);+ const {createWebSearchOverrideTool}=await import('../../../../src/main/model/core-agent/search-tools');+ const tool=await createWebSearchOverrideTool();+ for(const query of ['first public query','second public query']){+ const result=await tool.execute({query},{} as any);+ expect(result.isError).not.toBe(true);expect(result.content).toContain('Independent fallback evidence');+ expect(result.content).not.toContain('PRIVATE_UPSTREAM');+ }+ expect(fetch).toHaveBeenCalledOnce();expect(h.builtin).toHaveBeenCalledTimes(2);+ expect(h.warn.mock.calls.filter(([message])=>message==='search provider result')).toHaveLength(1);+ expect(h.warn.mock.calls.filter(([message])=>message==='paid search failed; trying next provider')).toHaveLength(1);+ });+ it('preserves a short Unicode query when Tavily fails and DeepSeek succeeds',async()=>{+ h.candidates=[{id:'tavily',provider:'tavily',apiKey:'first'},{id:'deepseek',provider:'deepseek',apiKey:'second'}];+ const fetch=vi.fn(async(url)=>String(url).includes('tavily')?new Response('unavailable',{status:503}):new Response(JSON.stringify({results:[{url:'https://example.org',summary:'Recovered source'}]})));+ vi.stubGlobal('fetch',fetch);+ const {createWebSearchOverrideTool}=await import('../../../../src/main/model/core-agent/search-tools');+ const query='🌏'.repeat(128);const result=await(await createWebSearchOverrideTool()).execute({query},{} as any);+ expect(result.isError).not.toBe(true);expect(result.content).toContain('Recovered source');+ expect(fetch).toHaveBeenCalledTimes(2);expect(h.builtin).not.toHaveBeenCalled();+ for(const [,init] of fetch.mock.calls as any)expect(JSON.parse(init.body).query).toBe(query);+ });+ it('stops before an incompatible second configured provider without rewriting a valid first-provider query',async()=>{+ h.candidates=[{id:'tavily',provider:'tavily',apiKey:'first'},{id:'deepseek',provider:'deepseek',apiKey:'second'}];+ const fetch=vi.fn(async()=>new Response('unavailable',{status:503}));vi.stubGlobal('fetch',fetch);+ const {createWebSearchOverrideTool}=await import('../../../../src/main/model/core-agent/search-tools');+ const query='🌏'.repeat(200);const result=await(await createWebSearchOverrideTool()).execute({query},{} as any);+ expect(result.isError).toBe(true);expect(result.content).toContain('128');+ expect(fetch).toHaveBeenCalledOnce();expect(h.builtin).not.toHaveBeenCalled();+ expect(JSON.parse((fetch.mock.calls[0] as any)[1].body).query).toBe(query);+ });+});diff --git a/test/main/model/core-agent/search-tools.test.ts b/test/main/model/core-agent/search-tools.test.tsindex d58ab67b..d607ae6d 100644--- a/test/main/model/core-agent/search-tools.test.ts+++ b/test/main/model/core-agent/search-tools.test.ts@@ -311,4 +311,56 @@ describe('web_search override tool', () => {await tool.execute({ query: 'evicted' }, { state: {} } as any);expect(h.runSearchAdapter).toHaveBeenCalledTimes(130);});++ it.each([['deepseek',128], ['orkas-api',128], ['tavily',400]] as const)('advertises and enforces the first provider Unicode bound (%s)', async(provider,limit)=>{+ h.candidates=provider?[{provider,apiKey:'fixture'}]:[];+ const tool=await createTool();+ expect((tool.inputSchema as any).properties.query.maxLength).toBe(limit);+ const result=await tool.execute({query:'🌏'.repeat(limit+1)},{} as any);+ expect(result.isError).toBe(true);expect(result.content).toContain(String(limit));+ expect(h.runSearchAdapter).not.toHaveBeenCalled();expect(h.runBuiltinWebSearch).not.toHaveBeenCalled();+ });+ it('lets a changed first provider tighten but never widen an existing run schema',async()=>{+ h.candidates=[{provider:'tavily',apiKey:'fixture'}]; const wide=await createTool();+ h.candidates=[{provider:'deepseek',apiKey:'fixture'}];+ expect((await wide.execute({query:'🌏'.repeat(129)},{} as any)).isError).toBe(true);+ const narrow=await createTool();h.candidates=[{provider:'tavily',apiKey:'fixture'}];+ expect((await narrow.execute({query:'🌏'.repeat(129)},{} as any)).isError).toBe(true);+ expect(h.runSearchAdapter).not.toHaveBeenCalled();expect(h.runBuiltinWebSearch).not.toHaveBeenCalled();+ });+ it.each(['deepseek','orkas-api'])('stops an incompatible fallback without dispatching it (%s)',async backup=>{+ h.candidates=[{provider:'tavily',apiKey:'fixture'},...(backup?[{provider:backup,apiKey:'fixture'}]:[])];+ h.runSearchAdapter.mockRejectedValueOnce(new Error('Tavily 503: request failed'));+ const result=await(await createTool()).execute({query:'🌏'.repeat(200)},{} as any);+ expect(result.isError).toBe(true);expect(result.content).toContain('128');+ expect(h.runSearchAdapter).toHaveBeenCalledTimes(1);expect(h.runBuiltinWebSearch).not.toHaveBeenCalled();+ expect(h.runSearchAdapter.mock.calls[0][1]).toBe('🌏'.repeat(200));+ });+ it('keeps the existing tool guidance and does not append paid-search reminders',async()=>{+ h.candidates=[{provider:'tavily',apiKey:'fixture'}];+ h.runSearchAdapter.mockResolvedValue({results:[{title:'Source',url:'https://example.org',snippet:'Evidence'}]});+ const tool=await createTool();+ expect(tool.description).toBe('Search the web for information. Returns a list of search results with titles, URLs, and snippets. Use this when you need to find current information, news, documentation, or any web content. After searching, use web_fetch to read the full content of relevant result URLs.');+ for(let i=0;i<15;i++){+ const result=await tool.execute({query:'public query'},{} as any);+ expect(result.content).toContain('Evidence');expect(result.content).not.toMatch(/This turn:|paid web searches|Prioritize completing/);+ }+ expect(h.runSearchAdapter).toHaveBeenCalledTimes(15);+ });++ it('preserves the existing unbounded keyless query without advertising a configured-service limit',async()=>{+ const tool=await createTool();const query='🌏'.repeat(1024);+ expect((tool.inputSchema as any).properties.query).not.toHaveProperty('maxLength');+ expect((await tool.execute({query},{} as any)).isError).not.toBe(true);+ expect(h.runBuiltinWebSearch).toHaveBeenCalledExactlyOnceWith(query,8);expect(h.runSearchAdapter).not.toHaveBeenCalled();+ });+ it('preserves keyless recovery after a valid long Tavily query fails',async()=>{+ h.candidates=[{provider:'tavily',apiKey:'fixture'}];+ h.runSearchAdapter.mockRejectedValueOnce(new Error('Tavily 503: request failed'));+ const query='🌏'.repeat(400);const result=await(await createTool()).execute({query},{} as any);+ expect(result.isError).not.toBe(true);expect(result.content).toContain('free results');+ expect(h.runBuiltinWebSearch).toHaveBeenCalledExactlyOnceWith(query,8);+ expect(h.runSearchAdapter).toHaveBeenCalledTimes(1);+ });+});