Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): add Cindy AI web search (#1928)
klc896b8548cb4
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.tsindex 74efc6aab0..98956e290a 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.ts@@ -28,6 +28,7 @@ function fakeGhost(media?: string[];text?: string[];embed?: string[];+ search?: string[];} | null;} = {},): InstalledGhost {@@ -74,6 +75,9 @@ function makeSlot(overrides: Partial<CindySlotDeps> = {}): {depositMedia: ReturnType<typeof vi.fn>;depositUsageBytes: ReturnType<typeof vi.fn>;releaseDeposit: ReturnType<typeof vi.fn>;+ searchWeb: ReturnType<typeof vi.fn>;+ claimPipeCall: ReturnType<typeof vi.fn>;+ settlePipeCallClaim: ReturnType<typeof vi.fn>;} {const generateImage = vi.fn(async () => ({buffer: new Uint8Array([1, 2, 3]),@@ -143,6 +147,19 @@ function makeSlot(overrides: Partial<CindySlotDeps> = {}): {);const depositUsageBytes = vi.fn(async () => 0);const releaseDeposit = vi.fn(async () => true);+ const searchWeb = vi.fn(async () => ({+ ok: true as const,+ results: [+ {+ title: 'Cindy',+ url: 'https://example.test/cindy',+ snippet: 'Search result',+ },+ ],+ requestId: 'search-call-1',+ }));+ const claimPipeCall = vi.fn(() => true);+ const settlePipeCallClaim = vi.fn(() => true);const slot = new GhostCindySlot({getGhost: () => fakeGhost(),getOwnerScopeKey: () => 'cloud:test-owner:1',@@ -162,6 +179,9 @@ function makeSlot(overrides: Partial<CindySlotDeps> = {}): {depositMedia,depositUsageBytes,releaseDeposit,+ searchWeb,+ claimPipeCall,+ settlePipeCallClaim,...overrides,} as CindySlotDeps);return {@@ -180,6 +200,9 @@ function makeSlot(overrides: Partial<CindySlotDeps> = {}): {depositMedia,depositUsageBytes,releaseDeposit,+ searchWeb,+ claimPipeCall,+ settlePipeCallClaim,};}@@ -288,6 +311,194 @@ describe('载荷校验', () => {});});+describe('Cindy Web Search', () => {+ const SEARCH_REQ = {+ type: 'cindy-request',+ kind: 'search_web',+ query: ' Cindy Web Search ',+ provider: 'cindy',+ callId: 'call-search-1',+ callerTool: 'research',+ };++ const searchGhost = () => fakeGhost({ model: { search: ['web'] } });++ it('按能力声明放行,trim query、补默认结果数并保持逻辑 Provider 为 cindy', async () => {+ const searchWeb = vi.fn(async () => ({+ ok: true as const,+ results: [+ {+ title: 'Result',+ url: 'https://example.test/result',+ snippet: 'Summary',+ },+ ],+ requestId: 'litellm-call-1',+ }));+ const { slot, claimPipeCall, settlePipeCallClaim } = makeSlot({+ getGhost: searchGhost,+ searchWeb,+ });++ const result = await slot.handleModelRequest('art', SEARCH_REQ);++ expect(searchWeb).toHaveBeenCalledWith({ query: 'Cindy Web Search', limit: 5 });+ expect(claimPipeCall).toHaveBeenCalledWith(+ 'art',+ 'call-search-1',+ 'research',+ 'cindy.search.web',+ expect.stringMatching(/^[a-f0-9]{64}$/),+ );+ expect(settlePipeCallClaim).toHaveBeenCalledWith(+ 'art',+ 'call-search-1',+ 'research',+ 'cindy.search.web',+ expect.stringMatching(/^[a-f0-9]{64}$/),+ false,+ );+ expect(result).toEqual({+ ok: true,+ provider: 'cindy',+ results: [+ {+ title: 'Result',+ url: 'https://example.test/result',+ snippet: 'Summary',+ },+ ],+ });+ });++ it('权限不足返回 PERMISSION_DENIED;非法参数返回 INVALID_PARAMS,且不出网', async () => {+ const searchWeb = vi.fn();+ for (const getGhost of [+ () => fakeGhost({ enabled: false, model: { search: ['web'] } }),+ () => fakeGhost({ slots: ['tool'], model: { search: ['web'] } }),+ () => fakeGhost(),+ ]) {+ const denied = makeSlot({ getGhost, searchWeb });+ expect(await denied.slot.handleModelRequest('art', SEARCH_REQ)).toMatchObject({+ ok: false,+ errorCode: 'PERMISSION_DENIED',+ });+ }++ const unbound = makeSlot({+ getGhost: searchGhost,+ searchWeb,+ claimPipeCall: vi.fn(() => false),+ });+ expect(await unbound.slot.handleModelRequest('art', SEARCH_REQ)).toMatchObject({+ ok: false,+ errorCode: 'PERMISSION_DENIED',+ });++ const { slot } = makeSlot({ getGhost: searchGhost, searchWeb });+ for (const request of [+ { ...SEARCH_REQ, provider: 'tavily' },+ { ...SEARCH_REQ, query: ' ' },+ { ...SEARCH_REQ, query: 'x'.repeat(2001) },+ { ...SEARCH_REQ, limit: 0 },+ { ...SEARCH_REQ, limit: 1.5 },+ { ...SEARCH_REQ, limit: 11 },+ { ...SEARCH_REQ, callId: '' },+ { ...SEARCH_REQ, callerTool: '' },+ ]) {+ expect(await slot.handleModelRequest('art', request)).toMatchObject({+ ok: false,+ errorCode: 'INVALID_PARAMS',+ });+ }+ expect(searchWeb).not.toHaveBeenCalled();+ });++ it('能力未接线、并发受限和账号切换等前置失败不消费 binding', async () => {+ const notConfigured = makeSlot({+ getGhost: searchGhost,+ searchWeb: undefined,+ });+ expect(await notConfigured.slot.handleModelRequest('art', SEARCH_REQ)).toMatchObject({+ ok: false,+ errorCode: 'NOT_CONFIGURED',+ });+ expect(notConfigured.claimPipeCall).not.toHaveBeenCalled();+ expect(notConfigured.settlePipeCallClaim).not.toHaveBeenCalled();++ const rateLimited = makeSlot({+ getGhost: searchGhost,+ getInflightLimit: () => 0,+ });+ expect(await rateLimited.slot.handleModelRequest('art', SEARCH_REQ)).toMatchObject({+ ok: false,+ errorCode: 'RATE_LIMITED',+ });+ expect(rateLimited.claimPipeCall).not.toHaveBeenCalled();+ expect(rateLimited.settlePipeCallClaim).not.toHaveBeenCalled();++ const switching = makeSlot({+ getGhost: searchGhost,+ isOwnerBoundaryPending: () => true,+ });+ expect(await switching.slot.handleModelRequest('art', SEARCH_REQ)).toMatchObject({+ ok: false,+ errorCode: 'UPSTREAM_UNAVAILABLE',+ });+ expect(switching.claimPipeCall).not.toHaveBeenCalled();+ expect(switching.settlePipeCallClaim).not.toHaveBeenCalled();+ });++ it('仅明确未出网的失败允许重试;已出网错误保留错误码并消费 binding', async () => {+ const notStartedSearch = vi.fn(async () => ({+ ok: false as const,+ errorCode: 'NOT_CONFIGURED' as const,+ message: '搜索尚未配置',+ requestStarted: false,+ }));+ const notStarted = makeSlot({ getGhost: searchGhost, searchWeb: notStartedSearch });+ expect(await notStarted.slot.handleModelRequest('art', SEARCH_REQ)).toEqual({+ ok: false,+ errorCode: 'NOT_CONFIGURED',+ message: '搜索尚未配置',+ });+ expect(notStarted.settlePipeCallClaim).toHaveBeenCalledWith(+ 'art',+ 'call-search-1',+ 'research',+ 'cindy.search.web',+ expect.stringMatching(/^[a-f0-9]{64}$/),+ true,+ );++ const searchWeb = vi.fn(async () => ({+ ok: false as const,+ errorCode: 'QUOTA_EXHAUSTED' as const,+ message: 'Cindy AI 搜索额度不足',+ requestStarted: true,+ status: 402,+ requestId: 'litellm-call-2',+ }));+ const quota = makeSlot({ getGhost: searchGhost, searchWeb });+ expect(await quota.slot.handleModelRequest('art', SEARCH_REQ)).toEqual({+ ok: false,+ errorCode: 'QUOTA_EXHAUSTED',+ message: 'Cindy AI 搜索额度不足',+ });++ expect(quota.claimPipeCall).toHaveBeenCalledTimes(1);+ expect(quota.settlePipeCallClaim).toHaveBeenCalledWith(+ 'art',+ 'call-search-1',+ 'research',+ 'cindy.search.web',+ expect.stringMatching(/^[a-f0-9]{64}$/),+ false,+ );+ expect(searchWeb).toHaveBeenCalledTimes(1);+ });+});+describe('视频画面参数', () => {const VIDEO_REQ = { type: 'cindy-request', kind: 'gen_video', prompt: '一只猫奔跑' };const EDIT_VIDEO_REQ = {diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.tsindex 3d34f0a2d7..f03037078b 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.ts@@ -297,6 +297,151 @@ describe('配对交卷', () => {});});+describe('tool-call 宿主能力绑定', () => {+ it('按 ghostId + callId + callerTool 验身,同请求只允许一次暂态重试', async () => {+ const h = makeHarness();+ const pending = h.dispatcher.callGhostTool(CALL);+ await vi.waitFor(() => expect(h.sent).toHaveLength(1));+ const callId = h.sent[0].callId;++ expect(+ h.dispatcher.claimPendingCall(+ 'evil-ghost',+ callId,+ 'gen_image',+ 'cindy.search.web',+ 'request-a',+ ),+ ).toBe(false);+ expect(+ h.dispatcher.claimPendingCall(+ 'art',+ callId,+ 'other_tool',+ 'cindy.search.web',+ 'request-a',+ ),+ ).toBe(false);+ expect(+ h.dispatcher.claimPendingCall(+ 'art',+ callId,+ 'gen_image',+ 'cindy.search.web',+ 'request-a',+ ),+ ).toBe(true);+ expect(+ h.dispatcher.claimPendingCall(+ 'art',+ callId,+ 'gen_image',+ 'cindy.search.web',+ 'request-a',+ ),+ ).toBe(false);+ expect(+ h.dispatcher.settlePendingCallClaim(+ 'art',+ callId,+ 'gen_image',+ 'cindy.search.web',+ 'request-a',+ true,+ ),+ ).toBe(true);+ expect(+ h.dispatcher.claimPendingCall(+ 'art',+ callId,+ 'gen_image',+ 'cindy.search.web',+ 'request-b',+ ),+ ).toBe(false);+ expect(+ h.dispatcher.claimPendingCall(+ 'art',+ callId,+ 'gen_image',+ 'cindy.search.web',+ 'request-a',+ ),+ ).toBe(true);+ expect(+ h.dispatcher.settlePendingCallClaim(+ 'art',+ callId,+ 'gen_image',+ 'cindy.search.web',+ 'request-a',+ true,+ ),+ ).toBe(true);+ expect(+ h.dispatcher.claimPendingCall(+ 'art',+ callId,+ 'gen_image',+ 'cindy.search.web',+ 'request-a',+ ),+ ).toBe(false);++ h.dispatcher.handleToolResult('art', {+ type: 'tool-result',+ callId,+ ok: true,+ result: 'done',+ });+ await expect(pending).resolves.toMatchObject({ ok: true });+ });++ it('成功或不可重试结果会永久消费 binding', async () => {+ const h = makeHarness();+ const pending = h.dispatcher.callGhostTool(CALL);+ await vi.waitFor(() => expect(h.sent).toHaveLength(1));+ const callId = h.sent[0].callId;++ expect(+ h.dispatcher.claimPendingCall(+ 'art',+ callId,+ 'gen_image',+ 'cindy.search.web',+ 'request-a',+ ),+ ).toBe(true);+ expect(+ h.dispatcher.settlePendingCallClaim(+ 'art',+ callId,+ 'gen_image',+ 'cindy.search.web',+ 'request-a',+ false,+ ),+ ).toBe(true);+ expect(+ h.dispatcher.claimPendingCall(+ 'art',+ callId,+ 'gen_image',+ 'cindy.search.web',+ 'request-a',+ ),+ ).toBe(false);++ h.dispatcher.handleToolResult('art', {+ type: 'tool-result',+ callId,+ ok: true,+ result: 'done',+ });+ await expect(pending).resolves.toMatchObject({ ok: true });+ });+});+describe('超时与收卷', () => {beforeEach(() => vi.useFakeTimers());afterEach(() => vi.useRealTimers());diff --git a/apps/desktop/src/main/cindy-brain/cindySlot.ts b/apps/desktop/src/main/cindy-brain/cindySlot.tsindex 58d97d3717..acd35eb645 100644--- a/apps/desktop/src/main/cindy-brain/cindySlot.ts+++ b/apps/desktop/src/main/cindy-brain/cindySlot.ts@@ -38,7 +38,7 @@* 依赖注入(规则 14):生成/落盘/记账/归属解析全部经 deps,单测直测。*/-import { randomUUID } from 'node:crypto';+import { createHash, randomUUID } from 'node:crypto';import {GHOST_CINDY_DEPOSIT_BURST,@@ -52,6 +52,9 @@ import {GHOST_CINDY_EMBED_TIMEOUT_MS,GHOST_CINDY_JOB_TTL_MS,GHOST_CINDY_MAX_ASYNC_JOBS,+ GHOST_CINDY_SEARCH_DEFAULT_RESULTS,+ GHOST_CINDY_SEARCH_MAX_QUERY_CHARS,+ GHOST_CINDY_SEARCH_MAX_RESULTS,GHOST_IMAGE_ASPECT_RATIOS,GHOST_MODEL_TIERS,GHOST_ONESHOT_TEXT_DEFAULT_MAX_TOKENS,@@ -75,6 +78,7 @@ import {type GhostVideoResultParams,type InstalledGhost,} from '../../shared/ghost.js';+import type { CindyProxySearchService } from '../mcp-integrations/cindyProxySearch.js';import { probeImageSize } from './imageProbe.js';/**@@ -269,6 +273,13 @@ export interface CindySlotDeps {depositUsageBytes?(ghostId: string): Promise<number>;/** 撤回该意识对某指纹的寄存引用;返回是否真的删掉了行(false = 本就没有)。 */releaseDeposit?(params: { ghostId: string; hash: string }): Promise<boolean>;+ /**+ * Cindy 托管 Web Search。实现固定读取主机 XD endpoint + XD user key,+ * 并通过固定模型别名调用 Anthropic Messages 原生网页搜索;插件不能注入+ * 上游地址、凭证、模型名或工具定义。+ * 可选依赖:未接线的宿主/测试环境 fail closed。+ */+ searchWeb?: CindyProxySearchService['search'];/*** 快问快答(text.oneshot,2026-07-31):把 prompt 交给主机的轻量任务* 模型链直答一次。注入实现包装 utility-model/oneShotCandidates 的@@ -295,6 +306,23 @@ export interface CindySlotDeps {*/holdPipeCall?(ghostId: string, callId: string, budgetMs: number): void;releasePipeCall?(ghostId: string, callId: string): void;+ /** 绑定真实在途 tool-call;同请求只允许一次受控重试。 */+ claimPipeCall?(+ ghostId: string,+ callId: string,+ callerTool: string,+ binding: string,+ requestKey: string,+ ): boolean;+ /** 收束能力尝试;allowRetry 只对首次明确暂态失败生效。 */+ settlePipeCallClaim?(+ ghostId: string,+ callId: string,+ callerTool: string,+ binding: string,+ requestKey: string,+ allowRetry: boolean,+ ): boolean;/*** 视频型号预期耗时(秒;video registry 登记值)。hold 预算与异步受理* 返回的 expectedSeconds 共用。未注入/查无该型号 → null(用缺省)。@@ -562,6 +590,10 @@ export class GhostCindySlot {data?: unknown;label?: unknown;hash?: unknown;+ query?: unknown;+ limit?: unknown;+ provider?: unknown;+ callerTool?: unknown;};if (p?.kind === 'query_job') {return this.handleQueryJob(ghostId, p);@@ -627,13 +659,28 @@ export class GhostCindySlot {return { ok: false, message: `文本转向量失败:${message}`, errorCode };}}+ if (p?.kind === 'search_web') {+ try {+ return await this.handleSearchWeb(ghostId, payload);+ } catch (err) {+ this.deps.log?.warn('ghost cindy-request search_web unexpected failure', {+ ghostId,+ error: err instanceof Error ? err.message : String(err),+ });+ return {+ ok: false,+ message: 'Cindy AI 搜索失败,请稍后再试',+ errorCode: 'INTERNAL',+ };+ }+ }const info = typeof p?.kind === 'string' ? KIND_INFO[p.kind] : undefined;if (!info) {return {ok: false,message:`未知的代办类型(当前支持 ${Object.keys(KIND_INFO).join(' / ')} / ` +- 'deposit_media / release_media / oneshot_text / embed_text / query_job)',+ 'deposit_media / release_media / oneshot_text / embed_text / search_web / query_job)',};}const kind = p.kind as string;@@ -1141,6 +1188,218 @@ export class GhostCindySlot {return null;}+ /**+ * search_web:Cindy 托管公网搜索。它与插件 network 槽里的 BYO Provider+ * 完全分账,主机只接受 provider:'cindy',失败不做任何跨 Provider fallback。+ * 查询文本不进日志;日志只留归因号、状态、耗时、结果数和上游 request id。+ */+ private async handleSearchWeb(+ ghostId: string,+ payload: unknown,+ ): Promise<GhostPipeModelResult> {+ const ghost = this.deps.getGhost(ghostId);+ if (!ghost || !ghost.enabled) {+ return {+ ok: false,+ message: '意识不在可用状态',+ errorCode: 'PERMISSION_DENIED',+ };+ }+ if (!ghost.manifest.slots?.includes('cindy')) {+ return {+ ok: false,+ message: '本意识未声明 cindy 卡槽,无权请 Cindy 搜索',+ errorCode: 'PERMISSION_DENIED',+ };+ }+ const declared: readonly string[] = ghost.manifest.cindy?.search ?? [];+ if (!declared.includes('web')) {+ return {+ ok: false,+ message:+ '本意识未声明搜索「网页搜索」能力(身份卡 cindy.search 缺 "web"),请意识作者更新声明',+ errorCode: 'PERMISSION_DENIED',+ };+ }++ const p = payload as {+ query?: unknown;+ limit?: unknown;+ provider?: unknown;+ callId?: unknown;+ callerTool?: unknown;+ };+ if (p.provider !== 'cindy') {+ return {+ ok: false,+ message: 'search_web 的 provider 必须固定为 cindy',+ errorCode: 'INVALID_PARAMS',+ };+ }+ if (typeof p.query !== 'string' || p.query.trim().length === 0) {+ return { ok: false, message: 'query 不能为空', errorCode: 'INVALID_PARAMS' };+ }+ const query = p.query.trim();+ if (query.length > GHOST_CINDY_SEARCH_MAX_QUERY_CHARS) {+ return {+ ok: false,+ message: `query 过长(上限 ${GHOST_CINDY_SEARCH_MAX_QUERY_CHARS} 字符)`,+ errorCode: 'INVALID_PARAMS',+ };+ }+ if (+ p.limit !== undefined &&+ (typeof p.limit !== 'number' ||+ !Number.isInteger(p.limit) ||+ p.limit < 1 ||+ p.limit > GHOST_CINDY_SEARCH_MAX_RESULTS)+ ) {+ return {+ ok: false,+ message: `limit 不合法(1–${GHOST_CINDY_SEARCH_MAX_RESULTS} 的整数,或不传)`,+ errorCode: 'INVALID_PARAMS',+ };+ }+ if (+ typeof p.callId !== 'string' ||+ p.callId.length === 0 ||+ p.callId.length > MAX_CALL_ID_LEN+ ) {+ return {+ ok: false,+ message: 'callId 不合法(搜索必须透传 1–128 字符的 tool-call 归因号)',+ errorCode: 'INVALID_PARAMS',+ };+ }+ const callId = p.callId;+ if (+ typeof p.callerTool !== 'string' ||+ !/^[a-z][a-z0-9_-]{0,63}$/.test(p.callerTool)+ ) {+ return {+ ok: false,+ message: 'callerTool 不合法(必须透传本次 tool-call 的 msg.tool)',+ errorCode: 'INVALID_PARAMS',+ };+ }+ const callerTool = p.callerTool;+ const searchWeb = this.deps.searchWeb;+ if (!searchWeb) {+ return {+ ok: false,+ message: '主机当前不支持 Cindy AI 搜索(能力未接线)',+ errorCode: 'NOT_CONFIGURED',+ };+ }++ const inflight = this.inflight.get(ghostId) ?? 0;+ const inflightLimit = this.deps.getInflightLimit?.(ghostId) ?? null;+ if (inflightLimit !== null && inflight >= inflightLimit) {+ return {+ ok: false,+ message: `同时进行的代办已达上限(${inflightLimit} 单),请稍后再试`,+ errorCode: 'RATE_LIMITED',+ };+ }++ this.inflight.set(ghostId, inflight + 1);+ try {+ if (this.deps.isOwnerBoundaryPending()) {+ return {+ ok: false,+ message: '账号正在切换,请稍后再试',+ errorCode: 'UPSTREAM_UNAVAILABLE',+ };+ }+ const limit =+ (p.limit as number | undefined) ?? GHOST_CINDY_SEARCH_DEFAULT_RESULTS;+ const requestKey = createHash('sha256')+ .update(query)+ .update('\0')+ .update(String(limit))+ .digest('hex');+ if (+ !this.deps.claimPipeCall?.(+ ghostId,+ callId,+ callerTool,+ 'cindy.search.web',+ requestKey,+ )+ ) {+ return {+ ok: false,+ message: 'Cindy AI 搜索只允许由当前插件真实在途的工具调用触发',+ errorCode: 'PERMISSION_DENIED',+ };+ }+ const ownerScopeKey = this.deps.getOwnerScopeKey();+ this.deps.log?.info('ghost cindy-request search_web start', {+ ghostId,+ callId,+ logicalProvider: 'cindy',+ });+ let allowRetry = false;+ try {+ const outcome = await searchWeb({ query, limit });+ if (+ this.deps.isOwnerBoundaryPending() ||+ this.deps.getOwnerScopeKey() !== ownerScopeKey+ ) {+ allowRetry = false;+ return {+ ok: false,+ message: '搜索期间账号已切换,本次结果已丢弃',+ errorCode: 'UPSTREAM_UNAVAILABLE',+ };+ }+ if (!outcome.ok) {+ allowRetry = outcome.requestStarted === false;+ this.deps.log?.warn('ghost cindy-request search_web failed', {+ ghostId,+ callId,+ logicalProvider: 'cindy',+ errorCode: outcome.errorCode,+ ...(outcome.status !== undefined ? { status: outcome.status } : {}),+ ...(outcome.requestId ? { requestId: outcome.requestId } : {}),+ });+ return {+ ok: false,+ message: outcome.message,+ errorCode: outcome.errorCode,+ };+ }+ allowRetry = false;+ this.deps.log?.info('ghost cindy-request search_web done', {+ ghostId,+ callId,+ logicalProvider: 'cindy',+ resultCount: outcome.results.length,+ ...(outcome.webSearchRequests !== undefined+ ? { webSearchRequests: outcome.webSearchRequests }+ : {}),+ ...(outcome.requestId ? { requestId: outcome.requestId } : {}),+ });+ return {+ ok: true,+ provider: 'cindy',+ results: outcome.results,+ };+ } finally {+ this.deps.settlePipeCallClaim?.(+ ghostId,+ callId,+ callerTool,+ 'cindy.search.web',+ requestKey,+ allowRetry,+ );+ }+ } finally {+ this.releaseInflight(ghostId);+ }+ }+/*** oneshot_text:快问快答(2026-07-31 开闸)。轻量任务模型链直答一次,* 文字随本次 invoke 递回;不选型(链由用户在主机侧配置)、不产媒体、diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex 98b9f7657a..55721f3770 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -1074,9 +1074,10 @@ my-ghost/// 否则请始终声明一个 command。"tools": [ /* 见 §3 */ ],"cindy": { "image": ["generate", "edit"] }, // 声明了 cindy 槽时必写:能力详单,见下- // 三个类目:image / video 的动作是 "generate" | "edit";media 的动作只有- // "deposit"(把你手里的媒体字节寄存进总仓换指纹,见 §4.0.1)。按需申请,- // 每条都会在装入确认框里单独列给用户看。+ // 类目按需申请:image / video 的动作是 "generate" | "edit";media 只有+ // "deposit"(把你手里的媒体字节寄存进总仓换指纹,见 §4.0.1);+ // text 只有 "oneshot";search 只有 "web"(Cindy 托管公网搜索)。每条都会+ // 在装入确认框里单独列给用户看。"panel": { "title": "面板标题", "html": "panel.html", "position": "left","minWidth": 240, "defaultFraction": 0.24,"systemButtons": { "maximize": false } },@@ -1239,9 +1240,11 @@ node 详单**不接受** \`command\` / \`args\` / \`shell\` / \`env\` 或其它文生视频 / \`edit\`=图生视频,参考图怎么用由 \`refMode\` 决定:首尾帧 1–2 张,或多张参考图,详见 §4 的 cindy-request 视频段)、\`media\`(\`deposit\`=把手里的媒体字节存进媒体库,§4.0.1)、\`text\`(\`oneshot\`=快问快答,§4.0.2)、-\`embed\`(\`text\`=文本转向量,§4.0.3)。+\`embed\`(\`text\`=文本转向量,§4.0.3)、\`search\`(\`web\`=Cindy 托管+公网搜索,见 §4 的 \`search_web\` 段)。详单里没申请的动作,运行时点单直接被拒;声明了 cindy 槽却漏写详单 = 零能力,-别漏。(旧名 model 槽/字段仍兼容,但新意识一律用 cindy。)+别漏。\`search.web\` 只能由真实 tool-call 触发,还必须同时声明 \`tool\` 槽和+至少一个工具。(旧名 model 槽/字段仍兼容,但新意识一律用 cindy。)**network 详单**(声明了 network 槽时必写,详见 §4.7):@@ -1471,10 +1474,25 @@ const r = await cindy.send({ type: 'cindy-request', kind: 'gen_image', prompt: '// 聊天卡片时用它按比例精确声明卡高(见 §4.5),别拿去写进交卷文案。// 图像可选画幅 aspectRatio:'1:1' 方图 / '3:2' 横图 / '2:3' 竖图,不传 = 后端自定:// { kind: 'gen_image', prompt: '一只猫', aspectRatio: '3:2' }+// 比例是意图声明(同 tier 哲学),主机翻译成该模型支持的具体尺寸,真实像素// 以返回的 width/height 为准。**图像类专用**(gen_image 与 edit_image 都收;// 改图不传 = 跟随源图画幅);视频画幅是另一个参数 ratio,值域不同,带错会被拒。// 用户没提横竖要求时别自作主张,不传让后端自定。+//+// Cindy 托管 Web Search(需声明 cindy.search:["web"]):+// provider 固定为 cindy,主机固定 Anthropic Messages 搜索模型与上游凭证;+// 不接受 api_base/header/key/model/tool。+const search = await cindy.send({+ type: 'cindy-request',+ kind: 'search_web',+ query: 'Cindy 最新版本',+ limit: 5, // 可选,1–10,缺省 5+ provider: 'cindy',+ callId: msg.callId, // 搜索只由 tool-call 触发,必须透传+ callerTool: msg.tool, // 与 callId 配对验身,必须逐字透传+});+// search = { ok:true, provider:'cindy', results:[{ title, url, snippet }] }// 改图(需详单含 "edit";源图必须是本意识名下的,1–4 张——含用户过户给你的// args.attachments 指纹):// { kind: 'edit_image', prompt, hashes: ['<指纹>'] }diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 0f35048bb8..8bb53d6390 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -265,6 +265,7 @@ import {} from './ghostRecentUsageStore.js';import { createXaiImageChannel } from './xaiImageClient.js';import { getCindyProxyMediaService } from '../mcp-integrations/cindyProxyMedia.js';+import { getCindyProxySearchService } from '../mcp-integrations/cindyProxySearch.js';import { ImageChannelRegistry, decodeImageResponse } from './imageChannelRegistry.js';import { createGeminiImageChannel } from './geminiImageClient.js';import { createCodexImageChannel } from './codexImageClient.js';@@ -2795,6 +2796,10 @@ export function getGhostCindySlot(): GhostCindySlot {// 在途并发上限:用户级隐藏配置(ghost-cindy-prefs.json 的 inflightLimits),// 缺省 null = 不限并发;每单现读,改配置即生效。getInflightLimit: (ghostId) => readGhostCindyInflightLimit(ghostId),+ // Web Search:固定走主机托管的 LiteLLM /v1/messages。endpoint/key 与+ // model-access 下发值同源,模型别名和 Claude 原生 Web Search 工具定义+ // 留在主机侧,意识只拿规范化结果。+ searchWeb: (params) => getCindyProxySearchService().search(params),// 快问快答(text.oneshot):走轻量任务模型链(与会话起标题/任务摘要// 同一条,用户在设置里配置)。动态 import:utility-model 的传递依赖在// 模块顶层读 electron app 路径,静态引入会把这条链拽进所有 import 本@@ -2834,6 +2839,30 @@ export function getGhostCindySlot(): GhostCindySlot {// ghostId 由派发器配对验身:冒用他人在途 callId 不能续命/收短别人的卷。holdPipeCall: (ghostId, callId, budgetMs) => getGhostPipeDispatcher().holdCall(ghostId, callId, budgetMs),releasePipeCall: (ghostId, callId) => getGhostPipeDispatcher().releaseCall(ghostId, callId),+ claimPipeCall: (ghostId, callId, callerTool, binding, requestKey) =>+ getGhostPipeDispatcher().claimPendingCall(+ ghostId,+ callId,+ callerTool,+ binding,+ requestKey,+ ),+ settlePipeCallClaim: (+ ghostId,+ callId,+ callerTool,+ binding,+ requestKey,+ allowRetry,+ ) =>+ getGhostPipeDispatcher().settlePendingCallClaim(+ ghostId,+ callId,+ callerTool,+ binding,+ requestKey,+ allowRetry,+ ),// 视频型号预期耗时(registry 登记值;hold 预算与异步受理返回共用)。// registry 缺席/型号查无 → null,cindySlot 用自己的缺省。videoExpectedSeconds: (model) => {diff --git a/apps/desktop/src/main/cindy-brain/pipeDispatcher.ts b/apps/desktop/src/main/cindy-brain/pipeDispatcher.tsindex fd65abb1b1..bb1c7ad30c 100644--- a/apps/desktop/src/main/cindy-brain/pipeDispatcher.ts+++ b/apps/desktop/src/main/cindy-brain/pipeDispatcher.ts@@ -48,9 +48,19 @@ export interface PipeDispatcherDeps {};}+interface PendingBindingClaim {+ callerTool: string;+ requestKey: string;+ attempts: number;+ active: boolean;+ consumed: boolean;+}+interface PendingCall {ghostId: string;tool: string;+ /** 宿主能力按用途绑定,允许同请求一次受控重试,禁止换参或无限消费。 */+ claimedBindings: Map<string, PendingBindingClaim>;resolve: (result: GhostToolCallResult) => void;timer: ReturnType<typeof setTimeout> | undefined;/** 派发时刻(续命天花板从这里起算)。 */@@ -167,6 +177,7 @@ export class GhostPipeDispatcher {const entry: PendingCall = {ghostId,tool,+ claimedBindings: new Map(),resolve,timer: undefined,startedAt,@@ -185,6 +196,73 @@ export class GhostPipeDispatcher {});}+ /**+ * 认领真实在途 tool-call 的宿主能力绑定。+ *+ * callerTool 必须与派发器事实表逐字匹配;同一 binding 只允许同 requestKey+ * 在暂态失败后重试一次,禁止换查询借用同一 callId 或无限消费付费通道。+ */+ claimPendingCall(+ ghostId: string,+ callId: string,+ callerTool: string,+ binding: string,+ requestKey: string,+ ): boolean {+ const entry = this.pending.get(callId);+ if (!entry || entry.ghostId !== ghostId || entry.tool !== callerTool) return false;+ const existing = entry.claimedBindings.get(binding);+ if (!existing) {+ entry.claimedBindings.set(binding, {+ callerTool,+ requestKey,+ attempts: 1,+ active: true,+ consumed: false,+ });+ return true;+ }+ if (+ existing.callerTool !== callerTool ||+ existing.requestKey !== requestKey ||+ existing.active ||+ existing.consumed ||+ existing.attempts >= 2+ ) {+ return false;+ }+ existing.attempts += 1;+ existing.active = true;+ return true;+ }++ /** 收束一次能力尝试;仅首次暂态失败可重新认领同一请求。 */+ settlePendingCallClaim(+ ghostId: string,+ callId: string,+ callerTool: string,+ binding: string,+ requestKey: string,+ allowRetry: boolean,+ ): boolean {+ const entry = this.pending.get(callId);+ const claim = entry?.claimedBindings.get(binding);+ if (+ !entry ||+ entry.ghostId !== ghostId ||+ entry.tool !== callerTool ||+ !claim ||+ claim.callerTool !== callerTool ||+ claim.requestKey !== requestKey ||+ !claim.active+ ) {+ return false;+ }+ claim.active = false;+ if (!allowRetry || claim.attempts >= 2) claim.consumed = true;+ return true;+ }+/** 基础超时档(注入值钳到天花板内,保证初始 deadline 不越过绝对上限)。 */private baseTimeoutMs(override?: number): number {const requested = Number.isFinite(override)diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/cindyProxySearch.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/cindyProxySearch.test.tsnew file mode 100644index 0000000000..23c59a4747--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/__tests__/cindyProxySearch.test.ts@@ -0,0 +1,335 @@+import { describe, expect, it, vi } from 'vitest';++import {+ buildCindySearchUrl,+ CINDY_SEARCH_MODEL_NAME,+ createCindyProxySearchService,+} from '../cindyProxySearch';++function response(body: unknown, init: ResponseInit = {}): Response {+ return new Response(JSON.stringify(body), {+ status: 200,+ headers: { 'Content-Type': 'application/json' },+ ...init,+ });+}++describe('cindyProxySearch', () => {+ it('supports LiteLLM hosts stored with or without the /v1 suffix', () => {+ expect(buildCindySearchUrl('https://gateway.example.test')).toBe(+ 'https://gateway.example.test/v1/messages',+ );+ expect(buildCindySearchUrl('https://gateway.example.test/v1/')).toBe(+ 'https://gateway.example.test/v1/messages',+ );+ expect(buildCindySearchUrl('https://gateway.example.test/v1/messages')).toBe(+ 'https://gateway.example.test/v1/messages',+ );+ expect(buildCindySearchUrl('https://gateway.example.test/V1/')).toBe(+ 'https://gateway.example.test/V1/messages',+ );+ expect(buildCindySearchUrl('https://gateway.example.test/V1/Messages')).toBe(+ 'https://gateway.example.test/V1/Messages',+ );+ expect(+ buildCindySearchUrl('https://gateway.example.test/api/v1?tenant=alpha&mode=fast#local'),+ ).toBe('https://gateway.example.test/api/v1/messages?tenant=alpha&mode=fast');+ });++ it('固定调用 cindy/web-search 的 Messages Web Search,并解析工具结果与 citations', async () => {+ const fetchImpl = vi.fn(async () =>+ response(+ {+ id: 'msg-search-123',+ usage: { server_tool_use: { web_search_requests: 2 } },+ content: [+ {+ type: 'web_search_tool_result',+ content: [+ {+ type: 'web_search_result',+ title: 'Cindy',+ url: 'https://example.test/cindy',+ },+ {+ type: 'web_search_result',+ title: '',+ url: 'https://example.test/second',+ },+ ],+ },+ {+ type: 'text',+ text: '搜索结果已整理。',+ citations: [+ {+ type: 'web_search_result_location',+ title: 'Cindy',+ url: 'https://example.test/cindy',+ cited_text: 'Cindy search result',+ },+ {+ type: 'web_search_result_location',+ title: 'Second',+ url: 'https://example.test/second',+ cited_text: 'Second search result',+ },+ {+ type: 'web_search_result_location',+ title: 'Citation only',+ url: 'https://example.test/citation-only',+ cited_text: 'Citation-only result',+ },+ ],+ },+ ],+ },+ { headers: { 'x-litellm-call-id': 'call-123' } },+ ),+ ) as unknown as typeof fetch;+ const service = createCindyProxySearchService({+ getBaseUrl: () => 'https://gateway.example.test/',+ getApiKey: () => 'test-key',+ fetchImpl,+ });++ const result = await service.search({ query: 'Cindy', limit: 3 });++ expect(fetchImpl).toHaveBeenCalledTimes(1);+ const [url, init] = (fetchImpl as unknown as ReturnType<typeof vi.fn>).mock.calls[0];+ expect(url).toBe('https://gateway.example.test/v1/messages');+ expect(init).toMatchObject({+ method: 'POST',+ headers: {+ Authorization: 'Bearer test-key',+ 'x-api-key': 'test-key',+ 'Content-Type': 'application/json',+ 'anthropic-version': '2023-06-01',+ },+ });+ expect(JSON.parse(String(init.body))).toEqual({+ model: CINDY_SEARCH_MODEL_NAME,+ max_tokens: 2048,+ messages: [{ role: 'user', content: 'Cindy' }],+ tools: [+ {+ type: 'web_search_20250305',+ name: 'web_search',+ max_uses: 1,+ },+ ],+ });+ expect(result).toEqual({+ ok: true,+ requestId: 'call-123',+ webSearchRequests: 2,+ results: [+ {+ title: 'Cindy',+ url: 'https://example.test/cindy',+ snippet: 'Cindy search result',+ },+ {+ title: 'Second',+ url: 'https://example.test/second',+ snippet: 'Second search result',+ },+ {+ title: 'Citation only',+ url: 'https://example.test/citation-only',+ snippet: 'Citation-only result',+ },+ ],+ });+ });++ it('未配置 endpoint/key 时 fail closed,且不发请求', async () => {+ const fetchImpl = vi.fn() as unknown as typeof fetch;+ for (const [baseUrl, apiKey] of [+ ['', 'test-key'],+ ['https://gateway.example.test', null],+ ] as const) {+ const service = createCindyProxySearchService({+ getBaseUrl: () => baseUrl,+ getApiKey: () => apiKey,+ fetchImpl,+ });+ await expect(service.search({ query: 'Cindy', limit: 5 })).resolves.toMatchObject({+ ok: false,+ errorCode: 'NOT_CONFIGURED',+ requestStarted: false,+ });+ }+ expect(fetchImpl).not.toHaveBeenCalled();+ });++ it('归一化鉴权、额度、限流、服务不可用和非法响应错误', async () => {+ const cases = [+ { status: 401, body: { error: 'insufficient scope' }, code: 'AUTH_REJECTED' },+ { status: 403, body: { error: 'insufficient permissions' }, code: 'AUTH_REJECTED' },+ { status: 402, body: { error: 'insufficient balance' }, code: 'QUOTA_EXHAUSTED' },+ { status: 429, body: { error: 'rate limit' }, code: 'RATE_LIMITED' },+ { status: 503, body: { error: 'unavailable' }, code: 'UPSTREAM_UNAVAILABLE' },+ ] as const;++ for (const testCase of cases) {+ const service = createCindyProxySearchService({+ getBaseUrl: () => 'https://gateway.example.test',+ getApiKey: () => 'test-key',+ fetchImpl: vi.fn(async () =>+ response(testCase.body, { status: testCase.status }),+ ) as unknown as typeof fetch,+ });+ await expect(service.search({ query: 'Cindy', limit: 5 })).resolves.toMatchObject({+ ok: false,+ errorCode: testCase.code,+ requestStarted: true,+ status: testCase.status,+ });+ }++ const malformed = createCindyProxySearchService({+ getBaseUrl: () => 'https://gateway.example.test',+ getApiKey: () => 'test-key',+ fetchImpl: vi.fn(async () =>+ response({+ content: [+ {+ type: 'web_search_tool_result',+ content: [{ type: 'web_search_result', title: 'missing url' }],+ },+ ],+ }),+ ) as unknown as typeof fetch,+ });+ await expect(malformed.search({ query: 'Cindy', limit: 5 })).resolves.toMatchObject({+ ok: false,+ errorCode: 'RESPONSE_INVALID',+ });+ });++ it('将无匹配结果和未触发搜索工具视为有效空结果', async () => {+ for (const body of [+ {+ content: [{ type: 'web_search_tool_result', content: [] }],+ },+ {+ content: [{ type: 'text', text: 'No web search was needed.' }],+ },+ ]) {+ const service = createCindyProxySearchService({+ getBaseUrl: () => 'https://gateway.example.test',+ getApiKey: () => 'test-key',+ fetchImpl: vi.fn(async () => response(body)) as unknown as typeof fetch,+ });++ await expect(service.search({ query: 'Cindy', limit: 5 })).resolves.toMatchObject({+ ok: true,+ results: [],+ });+ }+ });++ it('归一化 Messages Web Search 的 HTTP 200 工具级错误', async () => {+ const cases = [+ { upstream: 'too_many_requests', code: 'RATE_LIMITED' },+ { upstream: 'max_uses_exceeded', code: 'RATE_LIMITED' },+ { upstream: 'invalid_tool_input', code: 'INVALID_PARAMS' },+ { upstream: 'query_too_long', code: 'INVALID_PARAMS' },+ { upstream: 'unavailable', code: 'UPSTREAM_UNAVAILABLE' },+ ] as const;++ for (const testCase of cases) {+ const service = createCindyProxySearchService({+ getBaseUrl: () => 'https://gateway.example.test',+ getApiKey: () => 'test-key',+ fetchImpl: vi.fn(async () =>+ response({+ content: [+ {+ type: 'web_search_tool_result',+ content: {+ type: 'web_search_tool_result_error',+ error_code: testCase.upstream,+ },+ },+ ],+ }),+ ) as unknown as typeof fetch,+ });++ await expect(service.search({ query: 'Cindy', limit: 5 })).resolves.toMatchObject({+ ok: false,+ errorCode: testCase.code,+ status: 200,+ });+ }+ });++ it('响应体读取中断时返回可重试的上游错误并保留诊断元数据', async () => {+ const warn = vi.fn();+ const service = createCindyProxySearchService({+ getBaseUrl: () => 'https://gateway.example.test',+ getApiKey: () => 'test-key',+ fetchImpl: vi.fn(async () =>+ ({+ ok: true,+ status: 200,+ headers: new Headers({ 'x-request-id': 'request-body-failed' }),+ text: vi.fn(async () => {+ throw new Error('stream interrupted');+ }),+ }) as unknown as Response,+ ) as unknown as typeof fetch,+ log: { info: vi.fn(), warn },+ });++ await expect(service.search({ query: 'Cindy', limit: 5 })).resolves.toMatchObject({+ ok: false,+ errorCode: 'UPSTREAM_UNAVAILABLE',+ requestStarted: true,+ status: 200,+ requestId: 'request-body-failed',+ });+ expect(warn).toHaveBeenCalledWith(+ 'cindy search response body failed',+ expect.objectContaining({+ status: 200,+ requestId: 'request-body-failed',+ error: 'body read failure',+ }),+ );+ });++ it('日志只包含状态元数据,不包含 query 或 Authorization', async () => {+ const info = vi.fn();+ const warn = vi.fn();+ const service = createCindyProxySearchService({+ getBaseUrl: () => 'https://gateway.example.test',+ getApiKey: () => 'super-secret-test-key',+ fetchImpl: vi.fn(async () =>+ response({+ content: [+ {+ type: 'web_search_tool_result',+ content: [+ {+ type: 'web_search_result',+ title: 'Result',+ url: 'https://example.test/result',+ },+ ],+ },+ ],+ }),+ ) as unknown as typeof fetch,+ log: { info, warn },+ });++ await service.search({ query: 'sensitive user query', limit: 5 });++ const logged = JSON.stringify([info.mock.calls, warn.mock.calls]);+ expect(logged).not.toContain('sensitive user query');+ expect(logged).not.toContain('super-secret-test-key');+ });+});diff --git a/apps/desktop/src/main/mcp-integrations/cindyProxySearch.ts b/apps/desktop/src/main/mcp-integrations/cindyProxySearch.tsnew file mode 100644index 0000000000..3da37d70c2--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/cindyProxySearch.ts@@ -0,0 +1,477 @@+import { getAppCapabilities } from '../appCapabilities.js';+import { createLogger } from '../logger.js';+import { effectiveXdGatewayBaseUrl } from '../model-access/effectiveEndpoint.js';+import { getProviderSecretStore } from '../secrets/providerSecretStore.js';+import { outboundFetch } from '../maker-host/outbound-fetch.js';++export const CINDY_SEARCH_MODEL_NAME = 'cindy/web-search';+const CINDY_SEARCH_WEB_TOOL_TYPE = 'web_search_20250305';+const CINDY_SEARCH_MAX_TOKENS = 2_048;+const CINDY_SEARCH_TIMEOUT_MS = 30_000;++/**+ * Join the Anthropic-compatible Messages endpoint for either a gateway root or+ * a `/v1` base returned by the logged-in Cindy gateway configuration.+ */+export function buildCindySearchUrl(baseUrl: string): string {+ const normalizedBaseUrl = baseUrl.replace(/\/+$/, '');+ try {+ const url = new URL(normalizedBaseUrl);+ const pathname = url.pathname.replace(/\/+$/, '');+ const lowerPathname = pathname.toLowerCase();+ if (lowerPathname === '/v1/messages' || lowerPathname.endsWith('/v1/messages')) {+ url.pathname = pathname || '/v1/messages';+ } else {+ const suffix =+ lowerPathname === '/v1' || lowerPathname.endsWith('/v1') ? '/messages' : '/v1/messages';+ url.pathname = `${pathname}${suffix}` || '/v1/messages';+ }+ url.hash = '';+ return url.toString();+ } catch {+ // The caller validates configured URLs; retaining the old path makes this+ // helper harmless for injected unit-test values as well.+ }+ const suffix = normalizedBaseUrl.endsWith('/v1') ? '/messages' : '/v1/messages';+ return `${normalizedBaseUrl}${suffix}`;+}++export type CindyProxySearchErrorCode =+ | 'NOT_CONFIGURED'+ | 'QUOTA_EXHAUSTED'+ | 'AUTH_REJECTED'+ | 'RATE_LIMITED'+ | 'UPSTREAM_UNAVAILABLE'+ | 'INVALID_PARAMS'+ | 'RESPONSE_INVALID'+ | 'INTERNAL';++export interface CindyProxySearchItem {+ title: string;+ url: string;+ snippet: string;+}++export type CindyProxySearchOutcome =+ | {+ ok: true;+ results: CindyProxySearchItem[];+ requestId?: string;+ webSearchRequests?: number;+ }+ | {+ ok: false;+ errorCode: CindyProxySearchErrorCode;+ message: string;+ /** true 表示已进入 fetch,不能证明本次请求未消耗上游配额。 */+ requestStarted: boolean;+ status?: number;+ requestId?: string;+ };++export interface CindyProxySearchService {+ search(params: { query: string; limit: number }): Promise<CindyProxySearchOutcome>;+}++export interface CindyProxySearchDeps {+ getBaseUrl(): string;+ getApiKey(): string | null;+ fetchImpl: typeof fetch;+ timeoutMs?: number;+ log?: {+ info(message: string, meta?: Record<string, unknown>): void;+ warn(message: string, meta?: Record<string, unknown>): void;+ };+}++function requestIdOf(response: Response): string | undefined {+ return (+ response.headers.get('x-litellm-call-id') ?? response.headers.get('x-request-id') ?? undefined+ );+}++function classifyHttpFailure(+ status: number,+ body: string,+): { errorCode: CindyProxySearchErrorCode; message: string } {+ const normalized = body.slice(0, 1024).toLowerCase();+ if (status === 401 || status === 403) {+ return {+ errorCode: 'AUTH_REJECTED',+ message: 'Cindy AI 搜索鉴权失败,请重新登录或稍后再试',+ };+ }+ const looksLikeQuota =+ status === 402 ||+ /(?:quota|credit|balance|insufficient|exhausted|spend limit)/.test(normalized);+ if (looksLikeQuota) {+ return {+ errorCode: 'QUOTA_EXHAUSTED',+ message: 'Cindy AI 搜索额度不足,请稍后再试或在插件设置中改用自己的搜索渠道',+ };+ }+ if (status === 404) {+ return {+ errorCode: 'NOT_CONFIGURED',+ message: 'Cindy AI 搜索服务尚未配置,请稍后再试',+ };+ }+ if (+ (status === 400 || status === 422) &&+ /(?:invalid|unknown|not found|does not exist).{0,80}model|model.{0,80}(?:invalid|unknown|not found|does not exist)/.test(+ normalized,+ )+ ) {+ return {+ errorCode: 'NOT_CONFIGURED',+ message: 'Cindy AI 搜索模型尚未配置,请稍后再试',+ };+ }+ if (status === 429) {+ return {+ errorCode: 'RATE_LIMITED',+ message: 'Cindy AI 搜索请求过于频繁,请稍后再试',+ };+ }+ if (status >= 500) {+ return {+ errorCode: 'UPSTREAM_UNAVAILABLE',+ message: 'Cindy AI 搜索服务暂时不可用,请稍后再试',+ };+ }+ if (status === 400 || status === 422) {+ return {+ errorCode: 'INVALID_PARAMS',+ message: 'Cindy AI 搜索请求参数未被服务接受',+ };+ }+ return {+ errorCode: 'INTERNAL',+ message: 'Cindy AI 搜索失败,请稍后再试',+ };+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null;+}++function normalizedHttpUrl(value: unknown): string | null {+ if (typeof value !== 'string' || value.trim().length === 0) return null;+ try {+ const url = new URL(value.trim());+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;+ return url.toString();+ } catch {+ return null;+ }+}++function fallbackTitle(url: string): string {+ try {+ return new URL(url).hostname;+ } catch {+ return url;+ }+}++interface SearchSource {+ url: string;+ title: string;+ snippet: string;+}++type ParsedSearchResponse =+ | {+ ok: true;+ results: CindyProxySearchItem[];+ }+ | {+ ok: false;+ errorCode: CindyProxySearchErrorCode;+ message: string;+ };++function sourceFromRecord(value: Record<string, unknown>): SearchSource | null {+ const url = normalizedHttpUrl(value.url);+ if (!url) return null;+ const title =+ typeof value.title === 'string' && value.title.trim().length > 0+ ? value.title.trim()+ : fallbackTitle(url);+ const snippet =+ typeof value.cited_text === 'string'+ ? value.cited_text.trim()+ : typeof value.snippet === 'string'+ ? value.snippet.trim()+ : '';+ return { url, title, snippet };+}++function invalidSearchResponse(): ParsedSearchResponse {+ return {+ ok: false,+ errorCode: 'RESPONSE_INVALID',+ message: 'Cindy AI 搜索返回了无法识别的结果,请稍后再试',+ };+}++function searchToolFailure(errorCode: unknown): ParsedSearchResponse {+ if (errorCode === 'too_many_requests') {+ return {+ ok: false,+ errorCode: 'RATE_LIMITED',+ message: 'Cindy AI 搜索请求过于频繁,请稍后再试',+ };+ }+ if (errorCode === 'max_uses_exceeded') {+ return {+ ok: false,+ errorCode: 'RATE_LIMITED',+ message: 'Cindy AI 搜索已达到本次调用上限,请稍后再试',+ };+ }+ if (errorCode === 'invalid_tool_input' || errorCode === 'query_too_long') {+ return {+ ok: false,+ errorCode: 'INVALID_PARAMS',+ message: 'Cindy AI 搜索请求参数未被服务接受',+ };+ }+ if (errorCode === 'unavailable') {+ return {+ ok: false,+ errorCode: 'UPSTREAM_UNAVAILABLE',+ message: 'Cindy AI 搜索服务暂时不可用,请稍后再试',+ };+ }+ return invalidSearchResponse();+}++function parseSearchResponse(raw: unknown, limit: number): ParsedSearchResponse {+ if (!isRecord(raw) || !Array.isArray(raw.content)) {+ return invalidSearchResponse();+ }++ const sources = new Map<string, SearchSource>();+ let sawCandidate = false;+ const mergeSource = (source: SearchSource) => {+ const existing = sources.get(source.url);+ if (!existing) {+ sources.set(source.url, source);+ return;+ }+ if (existing.title === fallbackTitle(existing.url) && source.title !== existing.title) {+ existing.title = source.title;+ }+ if (!existing.snippet && source.snippet) existing.snippet = source.snippet;+ };++ for (const block of raw.content) {+ if (!isRecord(block)) continue;++ if (block.type === 'web_search_tool_result') {+ if (Array.isArray(block.content)) {+ if (block.content.length > 0) sawCandidate = true;+ for (const item of block.content) {+ if (!isRecord(item) || item.type !== 'web_search_result') continue;+ const source = sourceFromRecord(item);+ if (source) mergeSource(source);+ }+ } else if (isRecord(block.content) && block.content.type === 'web_search_tool_result_error') {+ return searchToolFailure(block.content.error_code);+ } else {+ return invalidSearchResponse();+ }+ }++ if (block.type === 'text' && Array.isArray(block.citations)) {+ if (block.citations.length > 0) sawCandidate = true;+ for (const citation of block.citations) {+ if (!isRecord(citation)) continue;+ const source = sourceFromRecord(citation);+ if (source) mergeSource(source);+ }+ }+ }++ if (sawCandidate && sources.size === 0) return invalidSearchResponse();+ return {+ ok: true,+ results: Array.from(sources.values()).slice(0, limit),+ };+}++function webSearchRequestsOf(raw: unknown): number | undefined {+ if (!isRecord(raw) || !isRecord(raw.usage) || !isRecord(raw.usage.server_tool_use)) {+ return undefined;+ }+ const value = raw.usage.server_tool_use.web_search_requests;+ return typeof value === 'number' && Number.isInteger(value) && value >= 0 ? value : undefined;+}++export function createCindyProxySearchService(deps: CindyProxySearchDeps): CindyProxySearchService {+ return {+ async search({ query, limit }): Promise<CindyProxySearchOutcome> {+ const baseUrl = deps.getBaseUrl().trim().replace(/\/+$/, '');+ const apiKey = deps.getApiKey();+ if (!baseUrl || !apiKey) {+ return {+ ok: false,+ errorCode: 'NOT_CONFIGURED',+ message: 'Cindy AI 搜索尚未就绪,请重新登录或在插件设置中改用自己的搜索渠道',+ requestStarted: false,+ };+ }++ const startedAt = Date.now();+ let response: Response;+ try {+ response = await deps.fetchImpl(buildCindySearchUrl(baseUrl), {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${apiKey}`,+ 'x-api-key': apiKey,+ 'Content-Type': 'application/json',+ 'anthropic-version': '2023-06-01',+ },+ body: JSON.stringify({+ model: CINDY_SEARCH_MODEL_NAME,+ max_tokens: CINDY_SEARCH_MAX_TOKENS,+ messages: [{ role: 'user', content: query }],+ tools: [+ {+ type: CINDY_SEARCH_WEB_TOOL_TYPE,+ name: 'web_search',+ max_uses: 1,+ },+ ],+ }),+ signal: AbortSignal.timeout(deps.timeoutMs ?? CINDY_SEARCH_TIMEOUT_MS),+ });+ } catch (error) {+ const latencyMs = Date.now() - startedAt;+ deps.log?.warn('cindy search request failed before response', {+ logicalProvider: 'cindy',+ upstreamProtocol: 'anthropic-messages',+ modelAlias: CINDY_SEARCH_MODEL_NAME,+ latencyMs,+ error:+ error instanceof DOMException && error.name === 'TimeoutError'+ ? 'timeout'+ : 'network failure',+ });+ return {+ ok: false,+ errorCode: 'UPSTREAM_UNAVAILABLE',+ message: 'Cindy AI 搜索服务连接失败,请稍后再试',+ requestStarted: true,+ };+ }++ const requestId = requestIdOf(response);+ let body: string;+ try {+ body = await response.text();+ } catch {+ const latencyMs = Date.now() - startedAt;+ deps.log?.warn('cindy search response body failed', {+ logicalProvider: 'cindy',+ upstreamProtocol: 'anthropic-messages',+ modelAlias: CINDY_SEARCH_MODEL_NAME,+ status: response.status,+ latencyMs,+ ...(requestId ? { requestId } : {}),+ error: 'body read failure',+ });+ return {+ ok: false,+ errorCode: 'UPSTREAM_UNAVAILABLE',+ message: 'Cindy AI 搜索响应传输中断,请稍后再试',+ requestStarted: true,+ status: response.status,+ ...(requestId ? { requestId } : {}),+ };+ }+ const latencyMs = Date.now() - startedAt;+ if (!response.ok) {+ const failure = classifyHttpFailure(response.status, body);+ deps.log?.warn('cindy search request rejected', {+ logicalProvider: 'cindy',+ upstreamProtocol: 'anthropic-messages',+ modelAlias: CINDY_SEARCH_MODEL_NAME,+ status: response.status,+ latencyMs,+ ...(requestId ? { requestId } : {}),+ errorCode: failure.errorCode,+ });+ return {+ ok: false,+ ...failure,+ requestStarted: true,+ status: response.status,+ ...(requestId ? { requestId } : {}),+ };+ }++ let decoded: unknown;+ try {+ decoded = JSON.parse(body);+ } catch {+ decoded = null;+ }+ const parsed = parseSearchResponse(decoded, limit);+ const webSearchRequests = webSearchRequestsOf(decoded);+ if (!parsed.ok) {+ deps.log?.warn('cindy search response rejected', {+ logicalProvider: 'cindy',+ upstreamProtocol: 'anthropic-messages',+ modelAlias: CINDY_SEARCH_MODEL_NAME,+ status: response.status,+ latencyMs,+ ...(requestId ? { requestId } : {}),+ errorCode: parsed.errorCode,+ });+ return {+ ok: false,+ errorCode: parsed.errorCode,+ message: parsed.message,+ requestStarted: true,+ status: response.status,+ ...(requestId ? { requestId } : {}),+ };+ }+ const results = parsed.results;++ deps.log?.info('cindy search request completed', {+ logicalProvider: 'cindy',+ upstreamProtocol: 'anthropic-messages',+ modelAlias: CINDY_SEARCH_MODEL_NAME,+ status: response.status,+ latencyMs,+ resultCount: results.length,+ ...(webSearchRequests !== undefined ? { webSearchRequests } : {}),+ ...(requestId ? { requestId } : {}),+ });+ return {+ ok: true,+ results,+ ...(webSearchRequests !== undefined ? { webSearchRequests } : {}),+ ...(requestId ? { requestId } : {}),+ };+ },+ };+}++const log = createLogger('search');+let service: CindyProxySearchService | null = null;++export function getCindyProxySearchService(): CindyProxySearchService {+ service ??= createCindyProxySearchService({+ getBaseUrl: () => effectiveXdGatewayBaseUrl(),+ getApiKey: () =>+ getAppCapabilities().canUseCindyGateway ? getProviderSecretStore().get('xd') : null,+ fetchImpl: outboundFetch,+ log,+ });+ return service;+}diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPermissionList.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPermissionList.test.tsxindex 7ca1165802..a5452186ff 100644--- a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPermissionList.test.tsx+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPermissionList.test.tsx@@ -121,6 +121,16 @@ describe('GhostPermissionList(装入全量清单)', () => {expect(screen.queryByText('settings.ghosts.perm.codeDetail')).toBeNull();});+ it('Cindy Web Search 能力在安装权限清单中单独披露', () => {+ const search: GhostManifest = {+ ...chip(),+ cindy: { search: ['web'] },+ };+ render(<GhostPermissionList items={ghostPermissionItems(search)} />);+ expect(screen.getByText('settings.ghosts.perm.cindySearchWeb')).toBeTruthy();+ expect(screen.getByText('settings.ghosts.perm.cindySearchWebDetail')).toBeTruthy();+ });+it('Node 持久凭证单独披露明文注入范围', () => {const node: GhostManifest = {...chip(),diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex ad3041fc68..09d50b7377 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -3425,6 +3425,8 @@"cindyTextOneshotDetail": "Uses the system's lightweight utility model chain (the same lane as auto titles). No Agent involved and no file access. Model charges may apply.","cindyEmbedText": "Can send text to be turned into vectors (for semantic search)","cindyEmbedTextDetail": "Text is sent to the system embedding model and turned into numbers, up to {{max}} items per call. Model charges may apply. The vectors go only to the plugin — nothing is written to your own library.",+ "cindySearchWeb": "Can search the public web with Cindy AI",+ "cindySearchWebDetail": "Search requests access the public web and may consume Cindy AI quota.","agentUserAction": "Can start a new Agent turn after you click a plugin card","agentUserActionDetail": "Each click permits one turn only, and only in the session that owns the card.","agentBackground": "Can automatically start new Agent turns in the background",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 95bd58df25..5ced64a974 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -3424,6 +3424,8 @@"cindyTextOneshotDetail": "システムの軽量タスクモデルチェーン(自動タイトルと同じ経路)を使用します。Agent は使わず、ファイルにもアクセスしません。モデル料金が発生する場合があります。","cindyEmbedText": "テキストをベクトルに変換できます(意味検索用)","cindyEmbedTextDetail": "テキストはシステムのベクトルモデルに送られて数値列に変換されます。1 回あたり最大 {{max}} 件で、モデル料金が発生する場合があります。生成されたベクトルはプラグインだけが保持し、あなたのライブラリには書き込まれません。",+ "cindySearchWeb": "Cindy AI で公開ウェブを検索できます",+ "cindySearchWebDetail": "検索では公開ウェブにアクセスし、Cindy AI の利用枠を消費する場合があります。","agentUserAction": "プラグインカードをクリックした後、Agent の新しいターンを開始できます","agentUserActionDetail": "1 回のクリックにつき 1 回だけ開始でき、そのカードが属するセッションでのみ使用できます。","agentBackground": "バックグラウンドで Agent の新しいターンを自動的に開始できます",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex b6a2f66761..cda12b556d 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -3424,6 +3424,8 @@"cindyTextOneshotDetail": "시스템의 경량 작업 모델 체인(자동 제목과 같은 경로)을 사용합니다. Agent를 사용하지 않고 파일에도 접근하지 않습니다. 모델 비용이 발생할 수 있습니다.","cindyEmbedText": "텍스트를 벡터로 변환할 수 있습니다(의미 검색용)","cindyEmbedTextDetail": "텍스트가 시스템 벡터 모델로 전송되어 숫자 배열로 변환됩니다. 한 번에 최대 {{max}}개이며 모델 요금이 발생할 수 있습니다. 생성된 벡터는 플러그인만 보관하며 사용자 라이브러리에는 기록되지 않습니다.",+ "cindySearchWeb": "Cindy AI로 공개 웹을 검색할 수 있음",+ "cindySearchWebDetail": "검색 요청은 공개 웹에 접근하며 Cindy AI 사용량을 소모할 수 있습니다.","agentUserAction": "플러그인 카드를 클릭한 뒤 Agent의 새 작업을 시작할 수 있음","agentUserActionDetail": "클릭 한 번마다 한 번만 시작할 수 있으며, 해당 카드가 속한 세션에서만 사용할 수 있습니다.","agentBackground": "백그라운드에서 Agent의 새 작업을 자동으로 시작할 수 있음",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 6dc7b90a50..1351cb1b51 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -3424,6 +3424,8 @@"cindyTextOneshotDetail": "走系统的轻量任务模型链(与自动起标题同一条通道),不动用 Agent、碰不到你的文件,可能产生模型费用。","cindyEmbedText": "可把文字送去算成向量(用于语义检索)","cindyEmbedTextDetail": "文字会送到系统的向量模型算成一串数字,单次最多 {{max}} 条,可能产生模型费用。算出的向量只交给插件自己保管,不写入你的资料库。",+ "cindySearchWeb": "可使用 Cindy AI 搜索公网",+ "cindySearchWebDetail": "查询会访问公网,并可能消耗 Cindy AI 配额。","agentUserAction": "用户点击插件卡片后,可让 Agent 开始新一轮工作","agentUserActionDetail": "每次点击只允许启动一次,并且只能使用这张卡所属的任务。","agentBackground": "可在后台自动让 Agent 开始新一轮工作",diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.tsindex 2340ecf496..4434e665aa 100644--- a/apps/desktop/src/shared/__tests__/ghost.test.ts+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts@@ -1393,6 +1393,8 @@ describe('ghost · cindy 能力详单校验(字段旧名 model 别名兼容)', ('image',{ media: ['upload'] }, // media 类目只有 deposit{ media: [] },+ { search: ['deep'] },+ { search: [] },]) {const v = validateGhostManifest(chipWithModel(bad));expect(v.ok, JSON.stringify(bad)).toBe(false);@@ -1490,6 +1492,32 @@ describe('ghost · cindy 能力详单校验(字段旧名 model 别名兼容)', (embed: ['text'],});});++ it('search 类目落进 cindy.search,并生成独立的 Web Search 权限行', () => {+ const manifest = chipWithModel({ search: ['web'] });+ manifest.slots = ['panel', 'cindy', 'tool'];+ manifest.tools = [{ name: 'research', description: '查询资料' }];+ const v = validateGhostManifest(manifest);+ expect(v.ok, JSON.stringify(v)).toBe(true);+ if (!v.ok) return;+ expect(v.manifest.cindy).toEqual({ search: ['web'] });+ expect(ghostPermissionItems(v.manifest)).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ key: 'cindy:search.web',+ kind: 'cindy',+ labelKey: 'cindySearchWeb',+ detailKey: 'cindySearchWebDetail',+ }),+ ]),+ );+ });++ it('search.web 缺少 tool 槽或工具声明时拒装', () => {+ const withoutTool = validateGhostManifest(chipWithModel({ search: ['web'] }));+ expect(withoutTool.ok).toBe(false);+ expect(!withoutTool.ok && withoutTool.reason).toContain('tool');+ });});describe('ghost · model → cindy 旧名兼容(2026-07-11 更名)', () => {diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex aa0360dd90..a93a7ff03c 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -466,6 +466,17 @@ export type GhostCindyTextAction = (typeof GHOST_CINDY_TEXT_ACTIONS)[number];export const GHOST_CINDY_EMBED_ACTIONS = ['text'] as const;export type GhostCindyEmbedAction = (typeof GHOST_CINDY_EMBED_ACTIONS)[number];+/**+ * cindy 槽·搜索类可申请的动作。+ *+ * `web` = Cindy 托管的公网搜索:意识只递查询词与结果数,主机固定走当前+ * model-access 下发的 XD endpoint + XD user key,通过固定模型别名调用+ * Anthropic Messages 原生网页搜索,不把网关 key、模型名或工具定义暴露给+ * 意识。它与 network 槽里的 BYO Brave/Tavily 是两条独立凭证与计费路径。+ */+export const GHOST_CINDY_SEARCH_ACTIONS = ['web'] as const;+export type GhostCindySearchAction = (typeof GHOST_CINDY_SEARCH_ACTIONS)[number];+/*** cindy 槽能力详单(卡槽⑤配套,原名模型槽,2026-07-11 设计定案):声明"这个意识被允许* 向主机点哪几类代办"——只有类目与动作,**不含任何具体模型/供应商信息**@@ -483,6 +494,8 @@ export interface GhostCindyNeeds {text?: GhostCindyTextAction[];/** 向量类:text=文本转向量(只生成不存储,向量原样递回意识自己保管)。 */embed?: GhostCindyEmbedAction[];+ /** 搜索类:web=Cindy 托管的公网搜索(主机固定路由,意识不经手网关凭证)。 */+ search?: GhostCindySearchAction[];}/**@@ -1552,6 +1565,7 @@ const GHOST_CINDY_PERM_LABEL: Record<string, string> = {'media.deposit': 'cindyMediaDeposit','text.oneshot': 'cindyTextOneshot','embed.text': 'cindyEmbedText',+ 'search.web': 'cindySearchWeb',};/**@@ -1565,6 +1579,7 @@ const GHOST_CINDY_PERM_DETAIL: Record<string, string> = {// 向量:用户要知道的是"文字会被送去算向量"(计费面)与"结果不落主机"// (向量归意识自己保管)。单次条数上限一并插值,同 deposit 的口径。'embed.text': 'cindyEmbedTextDetail',+ 'search.web': 'cindySearchWebDetail',};/**@@ -3009,6 +3024,7 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {media: GHOST_CINDY_MEDIA_ACTIONS,text: GHOST_CINDY_TEXT_ACTIONS,embed: GHOST_CINDY_EMBED_ACTIONS,+ search: GHOST_CINDY_SEARCH_ACTIONS,};for (const [category, actionsRaw] of Object.entries(cindyRaw)) {const allowed = actionTable[category];@@ -3041,6 +3057,7 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {else if (category === 'media') cindy.media = actions as GhostCindyMediaAction[];else if (category === 'text') cindy.text = actions as GhostCindyTextAction[];else if (category === 'embed') cindy.embed = actions as GhostCindyEmbedAction[];+ else if (category === 'search') cindy.search = actions as GhostCindySearchAction[];else return { ok: false, reason: `cindy 能力类目 ${JSON.stringify(category)} 尚未接线(主机缺陷)` };}if (@@ -3048,10 +3065,17 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {cindy.video === undefined &&cindy.media === undefined &&cindy.text === undefined &&- cindy.embed === undefined+ cindy.embed === undefined &&+ cindy.search === undefined) {return { ok: false, reason: 'cindy 能力详单不能是空对象' };}+ if (cindy.search?.includes('web') && (!slots.includes('tool') || tools === undefined)) {+ return {+ ok: false,+ reason: 'cindy.search.web 只允许由真实 tool-call 触发,必须同时声明 "tool" 槽和 tools',+ };+ }}// agent 槽详单:有槽无详单 = 仅允许真实用户点击触发;background 是@@ -5434,6 +5458,11 @@ export const GHOST_ONESHOT_TEXT_DEFAULT_MAX_TOKENS = 1024;/** 单次快问快答的等待上限(毫秒;超时按结构化失败收单,不吊管子)。 */export const GHOST_ONESHOT_TEXT_TIMEOUT_MS = 60_000;+/** Cindy 托管 Web Search 的请求边界。 */+export const GHOST_CINDY_SEARCH_MAX_QUERY_CHARS = 2000;+export const GHOST_CINDY_SEARCH_DEFAULT_RESULTS = 5;+export const GHOST_CINDY_SEARCH_MAX_RESULTS = 10;+/*** ── embed_text 政策参数(2026-08-04 开闸)──────────────────────────────* 上限不是抄上游 API 的(Voyage / OpenAI 都收到 1000 条一批),而是被**回传体积**@@ -5580,6 +5609,29 @@ export type GhostPipeCindyRequest =/** 异步模式(同 gen_video 分支)。 */mode?: 'submit';}+ | {+ /**+ * Cindy 托管 Web Search:主机固定使用当前 XD endpoint、XD user key+ * 与内置 Anthropic Messages 搜索模型,不接受意识传入+ * api_base/header/key/model/tool。+ * `provider` 固定为 cindy,用于与插件 network 槽的 BYO Brave/Tavily+ * 明确分账。+ *+ * 须声明 'cindy' 卡槽 + `cindy.search: ["web"]`。+ */+ type: 'cindy-request';+ kind: 'search_web';+ /** 用户原话查询,trim 后 1–2000 字符。 */+ query: string;+ /** 结果条数,1–10,缺省 5。 */+ limit?: number;+ /** 固定为 cindy;其它值明拒。 */+ provider: 'cindy';+ /** 搜索只由 tool-call 触发,必须透传本次 callId 用于账单与日志归因。 */+ callId: string;+ /** 必须透传本次 tool-call 的 msg.tool,供宿主与 callId 事实表配对验身。 */+ callerTool: string;+ }| {type: 'cindy-request';kind: 'query_job';@@ -5887,6 +5939,16 @@ export type GhostPipeModelResult =/** 与请求 documents 同形:文档 → chunk → 维度。 */documentEmbeddings: number[][][];} & GhostCindyEmbedResultMeta)+ | {+ /** search_web 成功;逻辑 Provider 恒为 cindy,不暴露内部模型路由。 */+ ok: true;+ provider: 'cindy';+ results: Array<{+ title: string;+ url: string;+ snippet: string;+ }>;+ }| {ok: false;message: string;@@ -5896,7 +5958,9 @@ export type GhostPipeModelResult =* 'NO_CANDIDATE'(快速通道无可用模型/凭证;embed_text 复用它表示* 目录里没有可用的向量型号)、* 'BAD_MODEL_OUTPUT'(expectJson 下输出不可解析)、'RATE_LIMITED'、- * 'TIMEOUT'、'PERMISSION_DENIED'、'INVALID_PARAMS'、'INTERNAL'。+ * 'TIMEOUT'、'PERMISSION_DENIED'、'INVALID_PARAMS'、'INTERNAL';+ * search_web 在这些通用值之外另使用 'NOT_CONFIGURED'、'QUOTA_EXHAUSTED'、+ * 'AUTH_REJECTED'、'UPSTREAM_UNAVAILABLE'、'RESPONSE_INVALID'。*/errorCode?: string;};