@klarkxy/dsh-zhihu 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/tools.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"tools.js","names":[],"sources":["../src/tool-definitions.ts","../src/tools.ts"],"sourcesContent":["import { defineTool } from '@deepseek-ai/dsh-tools'\nimport { reportExecuted, type ZhihuClientOptions } from './zhihu-client.ts'\nimport { ZHIHU_SEARCH_TOOL_NAME, ZHIHU_GLOBAL_SEARCH_TOOL_NAME, ZHIHU_HOT_LIST_TOOL_NAME, ZHIHU_ASK_TOOL_NAME, ZHIHU_KNOWLEDGE_SEARCH_TOOL_NAME } from './contracts.ts'\nimport { executeZhihuSearch, renderZhihuSearch, ZHIHU_SEARCH_DEFAULT_COUNT, ZHIHU_SEARCH_MAX_COUNT, type ZhihuSearchResult } from './search-api.ts'\nimport { ZHIHU_GLOBAL_SEARCH_VERSION, ZHIHU_GLOBAL_SEARCH_DEFAULT_COUNT, ZHIHU_GLOBAL_SEARCH_MAX_COUNT, ZHIHU_HOT_LIST_VERSION, ZHIHU_HOT_LIST_DEFAULT_LIMIT, ZHIHU_HOT_LIST_MAX_LIMIT, ZHIHU_ASK_VERSION, ZHIHU_ASK_TIMEOUT_MS, ZHIHU_KNOWLEDGE_SEARCH_VERSION, ZHIHU_KNOWLEDGE_SEARCH_DEFAULT_LIMIT, ZHIHU_KNOWLEDGE_SEARCH_MAX_LIMIT, ZHIHU_ASK_MODELS, ZhihuAskModel, ZHIHU_ASK_DEFAULT_MODEL, ZhihuToolOptions, ZhihuGlobalSearchDb, ZhihuGlobalSearchResult, executeZhihuGlobalSearch, renderZhihuGlobalSearch, ZhihuHotListItem, ZhihuHotListResult, executeZhihuHotList, renderZhihuHotList, ZhihuAskResult, executeZhihuAsk, renderZhihuAsk, ZhihuKnowledgeItem, ZhihuRecallScope, ZHIHU_RECALL_SCOPES, ZhihuKnowledgeSearchResult, normalizeRecallScopes, executeZhihuKnowledgeSearch, renderZhihuKnowledgeSearch } from './operations.ts'\nexport type CreateZhihuSearchToolOptions = ZhihuClientOptions & {\n /** Best-effort metering hook; invoked after every execution, failures included. */\n onExecuted?: (event: { ok: boolean; results: number }) => void\n}\n\nconst SEARCH_ITEM_SCHEMA = {\n type: 'object',\n additionalProperties: false,\n properties: {\n title: { type: 'string', required: true },\n type: { type: 'string', required: true },\n url: { type: 'string', required: true },\n summary: { type: 'string', required: true },\n votes: { type: 'integer', required: true },\n comments: { type: 'integer', required: true },\n author: { type: 'string', required: true },\n authority: { type: 'string', required: true },\n editTime: { type: 'string', required: true },\n },\n} as const\n\nexport function createZhihuSearchTool(options: CreateZhihuSearchToolOptions = {}) {\n const { onExecuted, ...client } = options\n return defineTool({\n name: ZHIHU_SEARCH_TOOL_NAME,\n description: '调用知乎开放平台站内搜索(GET /api/v1/content/zhihu_search)拉取社区证据;结果仅作社区/读者反馈参考,不构成 canon,也不直接写入项目文件。',\n parameters: {\n query: { type: 'string', required: true, description: '搜索词,2-100 字符。' },\n count: { type: 'integer', description: `返回条数,1-${ZHIHU_SEARCH_MAX_COUNT},默认 ${ZHIHU_SEARCH_DEFAULT_COUNT}。` },\n },\n output: {\n schema: {\n type: 'object',\n additionalProperties: false,\n properties: {\n version: { type: 'integer', required: true },\n query: { type: 'string', required: true },\n count: { type: 'integer', required: true },\n items: {\n type: 'array',\n required: true,\n items: SEARCH_ITEM_SCHEMA,\n },\n emptyReason: { type: 'string' },\n },\n },\n render(_args, value) {\n return [{ type: 'text' as const, text: renderZhihuSearch(value as ZhihuSearchResult) }]\n },\n },\n isConcurrencySafe() { return true },\n async execute(args, exec) {\n const typed = args as { query: string; count?: number }\n try {\n const result = await executeZhihuSearch(typed.query, typed.count ?? ZHIHU_SEARCH_DEFAULT_COUNT, {\n ...client,\n signal: exec.signal,\n })\n reportExecuted(onExecuted, { ok: true, results: result.items.length })\n return result\n } catch (error) {\n reportExecuted(onExecuted, { ok: false, results: 0 })\n throw error\n }\n },\n })\n}\n\nconst OTHER_SEARCH_ITEM_SCHEMA = {\n type: 'object',\n additionalProperties: false,\n properties: {\n title: { type: 'string', required: true },\n type: { type: 'string', required: true },\n url: { type: 'string', required: true },\n summary: { type: 'string', required: true },\n votes: { type: 'integer', required: true },\n comments: { type: 'integer', required: true },\n author: { type: 'string', required: true },\n authority: { type: 'string', required: true },\n editTime: { type: 'string', required: true },\n },\n} as const\n\n/** 包一层计量:成功报 results,失败报 ok:false 再原样抛出。 */\nasync function metered<T>(onExecuted: ZhihuToolOptions['onExecuted'], run: () => Promise<T>, results: (value: T) => number): Promise<T> {\n try {\n const value = await run()\n reportExecuted(onExecuted, { ok: true, results: results(value) })\n return value\n } catch (error) {\n reportExecuted(onExecuted, { ok: false, results: 0 })\n throw error\n }\n}\n\nexport function createZhihuGlobalSearchTool(options: ZhihuToolOptions = {}) {\n const { onExecuted, ...client } = options\n return defineTool({\n name: ZHIHU_GLOBAL_SEARCH_TOOL_NAME,\n description: '调用知乎开放平台全网搜索(GET /api/v1/content/global_search)检索站外公开网页资料;结果仅作参考,不构成 canon,也不直接写入项目文件。',\n parameters: {\n query: { type: 'string', required: true, description: '搜索词,2-100 字符。' },\n count: { type: 'integer', description: `返回条数,1-${ZHIHU_GLOBAL_SEARCH_MAX_COUNT},默认 ${ZHIHU_GLOBAL_SEARCH_DEFAULT_COUNT}。` },\n searchDb: { type: 'string', description: '检索库:all(默认)、realtime(实时)、static(静态)。' },\n },\n output: {\n schema: {\n type: 'object',\n additionalProperties: false,\n properties: {\n version: { type: 'integer', required: true },\n query: { type: 'string', required: true },\n count: { type: 'integer', required: true },\n searchDb: { type: 'string', required: true },\n items: { type: 'array', required: true, items: OTHER_SEARCH_ITEM_SCHEMA },\n emptyReason: { type: 'string' },\n },\n },\n render(_args, value) {\n return [{ type: 'text' as const, text: renderZhihuGlobalSearch(value as ZhihuGlobalSearchResult) }]\n },\n },\n isConcurrencySafe() { return true },\n async execute(args, exec) {\n const typed = args as { query: string; count?: number; searchDb?: string }\n const searchDb: ZhihuGlobalSearchDb = typed.searchDb === 'realtime' || typed.searchDb === 'static' ? typed.searchDb : 'all'\n return await metered(onExecuted, () => executeZhihuGlobalSearch(\n typed.query,\n typed.count ?? ZHIHU_GLOBAL_SEARCH_DEFAULT_COUNT,\n searchDb,\n { ...client, signal: exec.signal },\n ), (result) => result.items.length)\n },\n })\n}\n\nexport function createZhihuHotListTool(options: ZhihuToolOptions = {}) {\n const { onExecuted, ...client } = options\n return defineTool({\n name: ZHIHU_HOT_LIST_TOOL_NAME,\n description: '拉取知乎热榜(GET /api/v1/content/hot_list)了解当前社区热点;结果仅作题材与热点参考,不构成 canon,也不直接写入项目文件。',\n parameters: {\n limit: { type: 'integer', description: `返回条数,1-${ZHIHU_HOT_LIST_MAX_LIMIT},默认 ${ZHIHU_HOT_LIST_DEFAULT_LIMIT}。` },\n },\n output: {\n schema: {\n type: 'object',\n additionalProperties: false,\n properties: {\n version: { type: 'integer', required: true },\n limit: { type: 'integer', required: true },\n items: {\n type: 'array',\n required: true,\n items: {\n type: 'object',\n additionalProperties: false,\n properties: {\n title: { type: 'string', required: true },\n url: { type: 'string', required: true },\n summary: { type: 'string', required: true },\n },\n },\n },\n },\n },\n render(_args, value) {\n return [{ type: 'text' as const, text: renderZhihuHotList(value as ZhihuHotListResult) }]\n },\n },\n isConcurrencySafe() { return true },\n async execute(args, exec) {\n const typed = args as { limit?: number }\n return await metered(onExecuted, () => executeZhihuHotList(\n typed.limit ?? ZHIHU_HOT_LIST_DEFAULT_LIMIT,\n { ...client, signal: exec.signal },\n ), (result) => result.items.length)\n },\n })\n}\n\nexport function createZhihuAskTool(options: ZhihuToolOptions = {}) {\n const { onExecuted, ...client } = options\n return defineTool({\n name: ZHIHU_ASK_TOOL_NAME,\n description: '调用知乎直答(POST /v1/chat/completions,OpenAI 兼容)基于知乎社区内容生成综合回答;适合考据与背景调研。结果仅作参考,不构成 canon,也不直接写入项目文件。',\n parameters: {\n query: { type: 'string', required: true, description: '要问的问题。' },\n model: { type: 'string', description: 'zhida-thinking-1p5(默认,带思考过程)、zhida-fast-1p5(快,仅适合简单事实查询)或 zhida-agent(最慢最强,仅在明确要求时使用)。' },\n },\n output: {\n schema: {\n type: 'object',\n additionalProperties: false,\n properties: {\n version: { type: 'integer', required: true },\n query: { type: 'string', required: true },\n model: { type: 'string', required: true },\n content: { type: 'string', required: true },\n reasoning: { type: 'string', required: true },\n },\n },\n render(_args, value) {\n return [{ type: 'text' as const, text: renderZhihuAsk(value as ZhihuAskResult) }]\n },\n },\n isConcurrencySafe() { return true },\n async execute(args, exec) {\n const typed = args as { query: string; model?: string }\n const model: ZhihuAskModel = (ZHIHU_ASK_MODELS as readonly string[]).includes(typed.model ?? '')\n ? (typed.model as ZhihuAskModel)\n : ZHIHU_ASK_DEFAULT_MODEL\n return await metered(onExecuted, () => executeZhihuAsk(\n typed.query,\n model,\n { ...client, signal: exec.signal },\n ), (result) => (result.content ? 1 : 0))\n },\n })\n}\n\nexport function createZhihuKnowledgeSearchTool(options: ZhihuToolOptions = {}) {\n const { onExecuted, ...client } = options\n return defineTool({\n name: ZHIHU_KNOWLEDGE_SEARCH_TOOL_NAME,\n description: '检索知乎知识库(POST /api/v1/knowledge/search,RAG 片段),默认只查公开库;用户在知乎网页端上传过个人资料后可加 personal/subscription 召回。结果仅作背景参考,不构成 canon,也不直接写入项目文件。',\n parameters: {\n query: { type: 'string', required: true, description: '检索词。' },\n limit: { type: 'integer', description: `返回条数,1-${ZHIHU_KNOWLEDGE_SEARCH_MAX_LIMIT},默认 ${ZHIHU_KNOWLEDGE_SEARCH_DEFAULT_LIMIT}。` },\n recallScopes: {\n type: 'array',\n description: '召回范围:public(公开库,默认)、personal(个人库)、subscription(订阅库),可多选。',\n items: { type: 'string', enum: [...ZHIHU_RECALL_SCOPES] },\n },\n },\n output: {\n schema: {\n type: 'object',\n additionalProperties: false,\n properties: {\n version: { type: 'integer', required: true },\n query: { type: 'string', required: true },\n limit: { type: 'integer', required: true },\n recallScopes: { type: 'array', required: true, items: { type: 'string' } },\n items: {\n type: 'array',\n required: true,\n items: {\n type: 'object',\n additionalProperties: false,\n properties: {\n docName: { type: 'string', required: true },\n originUrl: { type: 'string', required: true },\n snippets: { type: 'array', required: true, items: { type: 'string' } },\n },\n },\n },\n },\n },\n render(_args, value) {\n return [{ type: 'text' as const, text: renderZhihuKnowledgeSearch(value as ZhihuKnowledgeSearchResult) }]\n },\n },\n isConcurrencySafe() { return true },\n async execute(args, exec) {\n const typed = args as { query: string; limit?: number; recallScopes?: unknown }\n return await metered(onExecuted, () => executeZhihuKnowledgeSearch(\n typed.query,\n typed.limit ?? ZHIHU_KNOWLEDGE_SEARCH_DEFAULT_LIMIT,\n normalizeRecallScopes(typed.recallScopes),\n { ...client, signal: exec.signal },\n ), (result) => result.items.length)\n },\n })\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport type { ZhihuService } from './index.ts'\nimport { createZhihuSearchTool, createZhihuGlobalSearchTool, createZhihuHotListTool, createZhihuAskTool, createZhihuKnowledgeSearchTool } from './tool-definitions.ts'\nexport const name = 'dsh-zhihu-tools'\nexport const inject = ['zhihu', 'tools'] as const\nexport function apply(ctx: Context): void {\n const host = ctx as Context & { zhihu: ZhihuService; tools: { register: (tool: unknown) => unknown } }\n const options = host.zhihu.toolOptions\n for (const create of [createZhihuSearchTool, createZhihuGlobalSearchTool, createZhihuHotListTool, createZhihuAskTool, createZhihuKnowledgeSearchTool]) {\n const tool = create(options)\n const execute = tool.execute as unknown as (args: unknown, exec: { signal: AbortSignal }) => Promise<unknown>\n host.tools.register({ ...tool, execute: (args: unknown, exec: { signal: AbortSignal }) =>\n host.zhihu.run(signal => execute(args, { ...exec, signal }), exec.signal) })\n }\n}\n"],"mappings":";;;;AAUA,MAAM,qBAAqB;CACzB,MAAM;CACN,sBAAsB;CACtB,YAAY;EACV,OAAO;GAAE,MAAM;GAAU,UAAU;EAAK;EACxC,MAAM;GA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AAS,CAAC,SAAS,OAAO;AACvC,SAAgB,MAAM,KAAoB;CACxC,MAAM,OAAO;CACb,MAAM,UAAU,KAAK,MAAM;CAC3B,KAAK,MAAM,UAAU;EAAC;EAAuB;EAA6B;EAAwB;EAAoB;CAA8B,GAAG;EACrJ,MAAM,OAAO,OAAO,OAAO;EAC3B,MAAM,UAAU,KAAK;EACrB,KAAK,MAAM,SAAS;GAAE,GAAG;GAAM,UAAU,MAAe,SACtD,KAAK,MAAM,KAAI,WAAU,QAAQ,MAAM;IAAE,GAAG;IAAM;GAAO,CAAC,GAAG,KAAK,MAAM;EAAE,CAAC;CAC/E;AACF"}
1
+ {"version":3,"file":"tools.js","names":[],"sources":["../src/tool-definitions.ts","../src/open-platform-render.ts","../src/open-platform-tools.ts","../src/tools.ts"],"sourcesContent":["import { defineTool } from '@deepseek-ai/dsh-tools'\nimport { reportExecuted, type ZhihuClientOptions } from './zhihu-client.ts'\nimport { ZHIHU_SEARCH_TOOL_NAME, ZHIHU_GLOBAL_SEARCH_TOOL_NAME, ZHIHU_HOT_LIST_TOOL_NAME, ZHIHU_ASK_TOOL_NAME, ZHIHU_KNOWLEDGE_SEARCH_TOOL_NAME } from './contracts.ts'\nimport { executeZhihuSearch, renderZhihuSearch, ZHIHU_SEARCH_DEFAULT_COUNT, ZHIHU_SEARCH_MAX_COUNT, type ZhihuSearchResult } from './search-api.ts'\nimport { ZHIHU_GLOBAL_SEARCH_VERSION, ZHIHU_GLOBAL_SEARCH_DEFAULT_COUNT, ZHIHU_GLOBAL_SEARCH_MAX_COUNT, ZHIHU_HOT_LIST_VERSION, ZHIHU_HOT_LIST_DEFAULT_LIMIT, ZHIHU_HOT_LIST_MAX_LIMIT, ZHIHU_ASK_VERSION, ZHIHU_ASK_TIMEOUT_MS, ZHIHU_KNOWLEDGE_SEARCH_VERSION, ZHIHU_KNOWLEDGE_SEARCH_DEFAULT_LIMIT, ZHIHU_KNOWLEDGE_SEARCH_MAX_LIMIT, ZHIHU_ASK_MODELS, ZhihuAskModel, ZHIHU_ASK_DEFAULT_MODEL, ZhihuToolOptions, ZhihuGlobalSearchDb, ZhihuGlobalSearchResult, executeZhihuGlobalSearch, renderZhihuGlobalSearch, ZhihuHotListItem, ZhihuHotListResult, executeZhihuHotList, renderZhihuHotList, ZhihuAskResult, executeZhihuAsk, renderZhihuAsk, ZhihuKnowledgeItem, ZhihuRecallScope, ZHIHU_RECALL_SCOPES, ZhihuKnowledgeSearchResult, normalizeRecallScopes, executeZhihuKnowledgeSearch, renderZhihuKnowledgeSearch } from './operations.ts'\nexport type CreateZhihuSearchToolOptions = ZhihuClientOptions & {\n /** Best-effort metering hook; invoked after every execution, failures included. */\n onExecuted?: (event: { ok: boolean; results: number }) => void\n}\n\nconst SEARCH_ITEM_SCHEMA = {\n type: 'object',\n additionalProperties: false,\n properties: {\n title: { type: 'string', required: true },\n type: { type: 'string', required: true },\n url: { type: 'string', required: true },\n summary: { type: 'string', required: true },\n votes: { type: 'integer', required: true },\n comments: { type: 'integer', required: true },\n author: { type: 'string', required: true },\n authority: { type: 'string', required: true },\n editTime: { type: 'string', required: true },\n },\n} as const\n\nexport function createZhihuSearchTool(options: CreateZhihuSearchToolOptions = {}) {\n const { onExecuted, ...client } = options\n return defineTool({\n name: ZHIHU_SEARCH_TOOL_NAME,\n description: '知乎站内搜索(GET /api/v1/content/zhihu_search),取社区证据;仅作社区/读者反馈参考,不构成 canon,不写入项目文件。',\n parameters: {\n query: { type: 'string', required: true, description: '搜索词,2-100 字符。' },\n count: { type: 'integer', description: `返回条数,1-${ZHIHU_SEARCH_MAX_COUNT},默认 ${ZHIHU_SEARCH_DEFAULT_COUNT}。` },\n },\n output: {\n schema: {\n type: 'object',\n additionalProperties: false,\n properties: {\n version: { type: 'integer', required: true },\n query: { type: 'string', required: true },\n count: { type: 'integer', required: true },\n items: {\n type: 'array',\n required: true,\n items: SEARCH_ITEM_SCHEMA,\n },\n emptyReason: { type: 'string' },\n },\n },\n render(_args, value) {\n return [{ type: 'text' as const, text: renderZhihuSearch(value as ZhihuSearchResult) }]\n },\n },\n isConcurrencySafe() { return true },\n async execute(args, exec) {\n const typed = args as { query: string; count?: number }\n try {\n const result = await executeZhihuSearch(typed.query, typed.count ?? ZHIHU_SEARCH_DEFAULT_COUNT, {\n ...client,\n signal: exec.signal,\n })\n reportExecuted(onExecuted, { ok: true, results: result.items.length })\n return result\n } catch (error) {\n reportExecuted(onExecuted, { ok: false, results: 0 })\n throw error\n }\n },\n })\n}\n\nconst OTHER_SEARCH_ITEM_SCHEMA = {\n type: 'object',\n additionalProperties: false,\n properties: {\n title: { type: 'string', required: true },\n type: { type: 'string', required: true },\n url: { type: 'string', required: true },\n summary: { type: 'string', required: true },\n votes: { type: 'integer', required: true },\n comments: { type: 'integer', required: true },\n author: { type: 'string', required: true },\n authority: { type: 'string', required: true },\n editTime: { type: 'string', required: true },\n },\n} as const\n\n/** 包一层计量:成功报 results,失败报 ok:false 再原样抛出。 */\nasync function metered<T>(onExecuted: ZhihuToolOptions['onExecuted'], run: () => Promise<T>, results: (value: T) => number): Promise<T> {\n try {\n const value = await run()\n reportExecuted(onExecuted, { ok: true, results: results(value) })\n return value\n } catch (error) {\n reportExecuted(onExecuted, { ok: false, results: 0 })\n throw error\n }\n}\n\nexport function createZhihuGlobalSearchTool(options: ZhihuToolOptions = {}) {\n const { onExecuted, ...client } = options\n return defineTool({\n name: ZHIHU_GLOBAL_SEARCH_TOOL_NAME,\n description: '知乎开放平台全网搜索(GET /api/v1/content/global_search),检索站外公开网页资料;仅作参考,不构成 canon,不写入项目文件。',\n parameters: {\n query: { type: 'string', required: true, description: '搜索词,2-100 字符。' },\n count: { type: 'integer', description: `返回条数,1-${ZHIHU_GLOBAL_SEARCH_MAX_COUNT},默认 ${ZHIHU_GLOBAL_SEARCH_DEFAULT_COUNT}。` },\n searchDb: { type: 'string', description: '检索库:all(默认)、realtime(实时)、static(静态)。' },\n },\n output: {\n schema: {\n type: 'object',\n additionalProperties: false,\n properties: {\n version: { type: 'integer', required: true },\n query: { type: 'string', required: true },\n count: { type: 'integer', required: true },\n searchDb: { type: 'string', required: true },\n items: { type: 'array', required: true, items: OTHER_SEARCH_ITEM_SCHEMA },\n emptyReason: { type: 'string' },\n },\n },\n render(_args, value) {\n return [{ type: 'text' as const, text: renderZhihuGlobalSearch(value as ZhihuGlobalSearchResult) }]\n },\n },\n isConcurrencySafe() { return true },\n async execute(args, exec) {\n const typed = args as { query: string; count?: number; searchDb?: string }\n const searchDb: ZhihuGlobalSearchDb = typed.searchDb === 'realtime' || typed.searchDb === 'static' ? typed.searchDb : 'all'\n return await metered(onExecuted, () => executeZhihuGlobalSearch(\n typed.query,\n typed.count ?? ZHIHU_GLOBAL_SEARCH_DEFAULT_COUNT,\n searchDb,\n { ...client, signal: exec.signal },\n ), (result) => result.items.length)\n },\n })\n}\n\nexport function createZhihuHotListTool(options: ZhihuToolOptions = {}) {\n const { onExecuted, ...client } = options\n return defineTool({\n name: ZHIHU_HOT_LIST_TOOL_NAME,\n description: '知乎热榜(GET /api/v1/content/hot_list),了解当前社区热点;仅作题材参考,不构成 canon,不写入项目文件。',\n parameters: {\n limit: { type: 'integer', description: `返回条数,1-${ZHIHU_HOT_LIST_MAX_LIMIT},默认 ${ZHIHU_HOT_LIST_DEFAULT_LIMIT}。` },\n },\n output: {\n schema: {\n type: 'object',\n additionalProperties: false,\n properties: {\n version: { type: 'integer', required: true },\n limit: { type: 'integer', required: true },\n items: {\n type: 'array',\n required: true,\n items: {\n type: 'object',\n additionalProperties: false,\n properties: {\n title: { type: 'string', required: true },\n url: { type: 'string', required: true },\n summary: { type: 'string', required: true },\n },\n },\n },\n },\n },\n render(_args, value) {\n return [{ type: 'text' as const, text: renderZhihuHotList(value as ZhihuHotListResult) }]\n },\n },\n isConcurrencySafe() { return true },\n async execute(args, exec) {\n const typed = args as { limit?: number }\n return await metered(onExecuted, () => executeZhihuHotList(\n typed.limit ?? ZHIHU_HOT_LIST_DEFAULT_LIMIT,\n { ...client, signal: exec.signal },\n ), (result) => result.items.length)\n },\n })\n}\n\nexport function createZhihuAskTool(options: ZhihuToolOptions = {}) {\n const { onExecuted, ...client } = options\n return defineTool({\n name: ZHIHU_ASK_TOOL_NAME,\n description: '知乎直答(POST /v1/chat/completions,OpenAI 兼容),基于社区内容生成综合回答,适合考据与背景调研;仅作参考,不构成 canon,不写入项目文件。',\n parameters: {\n query: { type: 'string', required: true, description: '要问的问题。' },\n model: { type: 'string', description: 'zhida-thinking-1p5(默认,带思考过程)、zhida-fast-1p5(快,仅适合简单事实查询)或 zhida-agent(最慢最强,仅在明确要求时使用)。' },\n },\n output: {\n schema: {\n type: 'object',\n additionalProperties: false,\n properties: {\n version: { type: 'integer', required: true },\n query: { type: 'string', required: true },\n model: { type: 'string', required: true },\n content: { type: 'string', required: true },\n reasoning: { type: 'string', required: true },\n },\n },\n render(_args, value) {\n return [{ type: 'text' as const, text: renderZhihuAsk(value as ZhihuAskResult) }]\n },\n },\n isConcurrencySafe() { return true },\n async execute(args, exec) {\n const typed = args as { query: string; model?: string }\n const model: ZhihuAskModel = (ZHIHU_ASK_MODELS as readonly string[]).includes(typed.model ?? '')\n ? (typed.model as ZhihuAskModel)\n : ZHIHU_ASK_DEFAULT_MODEL\n return await metered(onExecuted, () => executeZhihuAsk(\n typed.query,\n model,\n { ...client, signal: exec.signal },\n ), (result) => (result.content ? 1 : 0))\n },\n })\n}\n\nexport function createZhihuKnowledgeSearchTool(options: ZhihuToolOptions = {}) {\n const { onExecuted, ...client } = options\n return defineTool({\n name: ZHIHU_KNOWLEDGE_SEARCH_TOOL_NAME,\n description: '知乎知识库检索(POST /api/v1/knowledge/search,RAG 片段),默认只查公开库;网页端上传过资料后可加 personal/subscription 召回;仅作背景参考,不构成 canon,不写入项目文件。',\n parameters: {\n query: { type: 'string', required: true, description: '检索词。' },\n limit: { type: 'integer', description: `返回条数,1-${ZHIHU_KNOWLEDGE_SEARCH_MAX_LIMIT},默认 ${ZHIHU_KNOWLEDGE_SEARCH_DEFAULT_LIMIT}。` },\n recallScopes: {\n type: 'array',\n description: '召回范围:public(公开库,默认)、personal(个人库)、subscription(订阅库),可多选。',\n items: { type: 'string', enum: [...ZHIHU_RECALL_SCOPES] },\n },\n },\n output: {\n schema: {\n type: 'object',\n additionalProperties: false,\n properties: {\n version: { type: 'integer', required: true },\n query: { type: 'string', required: true },\n limit: { type: 'integer', required: true },\n recallScopes: { type: 'array', required: true, items: { type: 'string' } },\n items: {\n type: 'array',\n required: true,\n items: {\n type: 'object',\n additionalProperties: false,\n properties: {\n docName: { type: 'string', required: true },\n originUrl: { type: 'string', required: true },\n snippets: { type: 'array', required: true, items: { type: 'string' } },\n },\n },\n },\n },\n },\n render(_args, value) {\n return [{ type: 'text' as const, text: renderZhihuKnowledgeSearch(value as ZhihuKnowledgeSearchResult) }]\n },\n },\n isConcurrencySafe() { return true },\n async execute(args, exec) {\n const typed = args as { query: string; limit?: number; recallScopes?: unknown }\n return await metered(onExecuted, () => executeZhihuKnowledgeSearch(\n typed.query,\n typed.limit ?? ZHIHU_KNOWLEDGE_SEARCH_DEFAULT_LIMIT,\n normalizeRecallScopes(typed.recallScopes),\n { ...client, signal: exec.signal },\n ), (result) => result.items.length)\n },\n })\n}\n","import { ZHIHU_OPEN_PLATFORM_APIS, type ZhihuOpenPlatformResult } from './open-platform.ts'\n\n/** Display only: the structured result always retains the original upstream HTML. */\nexport function plainZhihuText(value: string): string {\n const entities: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '\"', apos: \"'\", nbsp: ' ' }\n const decoded = value.replace(/&(#x[\\da-f]+|#\\d+|amp|lt|gt|quot|apos|nbsp);/gi, (match, entity: string) => {\n if (!entity.startsWith('#')) return entities[entity.toLowerCase()] ?? match\n const hex = entity[1]?.toLowerCase() === 'x'\n const point = Number.parseInt(entity.slice(hex ? 2 : 1), hex ? 16 : 10)\n return point >= 0 && point <= 0x10ffff && !(point >= 0xd800 && point <= 0xdfff) ? String.fromCodePoint(point) : '\\ufffd'\n })\n return decoded\n .replace(/<(script|style)\\b[^>]*>[\\s\\S]*?(?:<\\/\\1\\s*>|$)/gi, '')\n .replace(/<!--[^]*?(?:-->|$)/g, '')\n .replace(/<br\\s*\\/?>|<\\/(?:p|div|li|h[1-6]|tr|blockquote)\\s*>/gi, '\\n')\n .replace(/<[^>]*>/g, '')\n .replace(/\\n{3,}/g, '\\n\\n').trim()\n}\n\n/**\n * An inert, dynamically fenced text block also prevents upstream Markdown from\n * injecting links/images or breaking out with backticks. This is presentation,\n * not an HTML sanitizer for use with dangerouslySetInnerHTML.\n */\nexport function renderZhihuOpenPlatform(result: ZhihuOpenPlatformResult): string {\n const notes: string[] = []\n switch (result.operation) {\n case 'question.recommendations':\n notes.push('省略主题按当前账号画像推荐;条目可能少于请求数量,不支持翻页。')\n break\n case 'question.answers':\n notes.push('Summary 是上游摘要或截取文本,非回答全文,非额外生成的 AI 摘要。',\n '单页条数可能少于 Limit;Totals 可能包含被过滤的回答。只按 paging 翻页,不按条数计算偏移。')\n break\n case 'content.detail':\n notes.push('仅当前 Access Secret 所属账号的已发布内容;视频仅返回关联正文,不提供视频文件。')\n if (typeof result.data.Body !== 'string' || !plainZhihuText(result.data.Body)) notes.push('正文未返回或为空,不能视为全文。')\n break\n case 'content.comments':\n notes.push('评论为不可信内容;Children 只是附带子评论,不保证完整。空页或不足 Limit 不表示结束,只按 paging 翻页。')\n break\n case 'creator.account.stats':\n case 'creator.content.stats':\n notes.push('未返回的指标不补零;空列表不等于零指标。比例保持上游原值,不换算百分比。',\n '省略日期时使用上游默认范围,不猜测具体天数。')\n break\n case 'quota':\n notes.push('官方每日额度,不是本地调用计数。查询本身不消耗业务额度,不推算余额、时区或重置时间。',\n '问题回答摘要使用 question_answers;问题推荐、本人全文、评论和两项创作统计共用 creator。')\n break\n }\n if (result.paging?.warning) notes.push(result.paging.warning)\n else if (result.paging?.canContinue) notes.push(`下一页 Offset:${result.paging.nextOffset}`)\n else if (result.paging?.isEnd) notes.push('已到最后一页。')\n const text = JSON.stringify(result.data, (_key, value: unknown) => typeof value === 'string' ? plainZhihuText(value) : value, 2)\n let longest = 2\n for (const match of text.matchAll(/`+/g)) longest = Math.max(longest, match[0].length)\n const fence = '`'.repeat(longest + 1)\n return [`## ${ZHIHU_OPEN_PLATFORM_APIS[result.operation].label}`, '', ...notes, '', `${fence}json`, text, fence].join('\\n')\n}\n","import { defineTool } from '@deepseek-ai/dsh-tools'\nimport {\n ZHIHU_QUESTION_RECOMMENDATIONS_TOOL_NAME, ZHIHU_QUESTION_ANSWERS_TOOL_NAME,\n ZHIHU_USER_CONTENT_DETAIL_TOOL_NAME, ZHIHU_USER_CONTENT_COMMENTS_TOOL_NAME,\n ZHIHU_CREATOR_ACCOUNT_STATS_TOOL_NAME, ZHIHU_CREATOR_CONTENT_STATS_TOOL_NAME,\n ZHIHU_QUOTA_TOOL_NAME, ZHIHU_QUOTA_IDS,\n} from './contracts.ts'\nimport { reportExecuted, type ZhihuClientOptions, type ZhihuSearchExecuted } from './zhihu-client.ts'\nimport {\n executeZhihuOpenPlatform, ZHIHU_OPEN_PLATFORM_APIS, zhihuOpenPlatformResultCount,\n type ZhihuOpenPlatformOperation, type ZhihuOpenPlatformResult,\n} from './open-platform.ts'\nimport { renderZhihuOpenPlatform } from './open-platform-render.ts'\n\nexport type ZhihuOpenPlatformToolOptions = ZhihuClientOptions & { onExecuted?: (event: ZhihuSearchExecuted) => void }\nconst PAGE_PARAMETERS = {\n offset: { type: 'string', description: '非负 Int64 十进制字符串,默认 \"0\"。下一页只用 paging.nextOffset,不按条数推算,不接受不透明游标。' },\n limit: { type: 'integer', description: '每页数量,1-50,默认 20。单页不足或为空不表示结束。' },\n} as const\nconst DATE_PARAMETERS = {\n startDate: { type: 'string', description: 'YYYY-MM-DD,必须与 endDate 同时提供。省略两者使用上游默认范围,不猜测天数。' },\n endDate: { type: 'string', description: 'YYYY-MM-DD,不得早于 startDate。' },\n} as const\nconst CONTENT_URL = { type: 'string', required: true, description: '当前账号已发布内容的 HTTPS 知乎回答、专栏文章、想法或视频链接;不是任意网页抓取。' } as const\n\nconst DEFINITIONS = {\n 'question.recommendations': {\n name: ZHIHU_QUESTION_RECOMMENDATIONS_TOOL_NAME,\n description: '推荐适合当前账号回答的问题;省略主题按画像推荐,条目可能少于 Count,不支持分页。使用 creator 额度。',\n parameters: {\n query: { type: 'string', description: '可选主题;不传才按画像推荐,空白字符串无效。' },\n count: { type: 'integer', description: '推荐数量,1-20,默认 5。' },\n },\n },\n 'question.answers': {\n name: ZHIHU_QUESTION_ANSWERS_TOOL_NAME,\n description: '读取问题下的回答摘要,非全文,也非新生成的 AI 摘要。一次一页,只有 paging.canContinue=true 时才用 nextOffset。使用 question_answers 额度。',\n parameters: {\n questionUrl: { type: 'string', required: true, description: 'https://www.zhihu.com/question/{id} 形式的问题链接。' },\n ...PAGE_PARAMETERS,\n },\n },\n 'content.detail': {\n name: ZHIHU_USER_CONTENT_DETAIL_TOOL_NAME,\n description: '读取当前账号已发布创作的全文。不能读其他账号全文;视频只给关联正文。空正文不能视为全文。使用 creator 额度。',\n parameters: { contentUrl: CONTENT_URL },\n },\n 'content.comments': {\n name: ZHIHU_USER_CONTENT_COMMENTS_TOOL_NAME,\n description: '读取当前账号创作下的根评论及附带 Children;子评论不保证完整。一次一页,只按 paging 翻页,不按条数判断结束。使用 creator 额度。',\n parameters: { contentUrl: CONTENT_URL, ...PAGE_PARAMETERS, order: { type: 'string', enum: ['score', 'reverse', 'ascending'], description: '排序,默认 score。' } },\n },\n 'creator.account.stats': {\n name: ZHIHU_CREATOR_ACCOUNT_STATS_TOOL_NAME,\n description: '读取当前账号创作数据。缺失指标不补零,比例保持原值,不换算百分比。使用 creator 额度。',\n parameters: { contentType: { type: 'string', enum: ['all', 'answer', 'article', 'pin', 'zvideo'], description: '内容类型,默认 all,不支持 question。' }, ...DATE_PARAMETERS },\n },\n 'creator.content.stats': {\n name: ZHIHU_CREATOR_CONTENT_STATS_TOOL_NAME,\n description: '读取当前账号单篇创作数据。空列表不代表零指标;缺失指标保持省略,比例保持上游原值。使用 creator 额度。',\n parameters: { contentUrl: CONTENT_URL, ...DATE_PARAMETERS },\n },\n quota: {\n name: ZHIHU_QUOTA_TOOL_NAME,\n description: '查询官方每日额度,本接口不消耗业务额度。不同于本地 usage.summary;不推算余额或重置时间。',\n parameters: { apiIds: { type: 'array', items: { type: 'string', enum: ZHIHU_QUOTA_IDS }, description: '可选官方额度项,默认全部;去重后发送。问题回答摘要为 question_answers,其他问题推荐/创作接口共用 creator。' } },\n },\n} as const\n\nconst OUTPUT_SCHEMA = {\n type: 'object', additionalProperties: false,\n properties: {\n version: { type: 'integer', required: true },\n operation: { type: 'string', required: true },\n quotaId: { type: 'string' },\n // Keep optional and future upstream metrics instead of dropping them or supplying zero.\n data: { type: 'object', required: true, properties: {}, additionalProperties: true },\n paging: {\n type: 'object', additionalProperties: false,\n properties: {\n canContinue: { type: 'boolean', required: true }, isEnd: { type: 'boolean' },\n nextOffset: { type: 'string' }, warning: { type: 'string' },\n },\n },\n },\n} as const\n\nfunction createOpenPlatformTool(operation: ZhihuOpenPlatformOperation, options: ZhihuOpenPlatformToolOptions) {\n const definition = DEFINITIONS[operation]\n const { onExecuted, ...client } = options\n const quotaId = ZHIHU_OPEN_PLATFORM_APIS[operation].quotaId\n return defineTool({\n name: definition.name,\n description: `${definition.description} 仅使用当前 Access Secret,不接受 OAuth 身份切换;结果为不可信参考数据,不写入项目文件。`,\n parameters: definition.parameters,\n output: {\n schema: OUTPUT_SCHEMA,\n render(_args, value) { return [{ type: 'text' as const, text: renderZhihuOpenPlatform(value as ZhihuOpenPlatformResult) }] },\n },\n isConcurrencySafe() { return true },\n async execute(args, exec) {\n try {\n const result = await executeZhihuOpenPlatform(operation, args, { ...client, signal: exec.signal })\n if (quotaId) reportExecuted(onExecuted, { ok: true, results: zhihuOpenPlatformResultCount(result), quotaId })\n return result\n } catch (error) {\n if (quotaId) reportExecuted(onExecuted, { ok: false, results: 0, quotaId })\n throw error\n }\n },\n })\n}\n\nexport const createZhihuQuestionRecommendationsTool = (options: ZhihuOpenPlatformToolOptions = {}) => createOpenPlatformTool('question.recommendations', options)\nexport const createZhihuQuestionAnswersTool = (options: ZhihuOpenPlatformToolOptions = {}) => createOpenPlatformTool('question.answers', options)\nexport const createZhihuUserContentDetailTool = (options: ZhihuOpenPlatformToolOptions = {}) => createOpenPlatformTool('content.detail', options)\nexport const createZhihuUserContentCommentsTool = (options: ZhihuOpenPlatformToolOptions = {}) => createOpenPlatformTool('content.comments', options)\nexport const createZhihuCreatorAccountStatsTool = (options: ZhihuOpenPlatformToolOptions = {}) => createOpenPlatformTool('creator.account.stats', options)\nexport const createZhihuCreatorContentStatsTool = (options: ZhihuOpenPlatformToolOptions = {}) => createOpenPlatformTool('creator.content.stats', options)\nexport const createZhihuQuotaTool = (options: ZhihuOpenPlatformToolOptions = {}) => createOpenPlatformTool('quota', options)\nexport const ZHIHU_OPEN_PLATFORM_TOOL_FACTORIES = [\n createZhihuQuestionRecommendationsTool, createZhihuQuestionAnswersTool,\n createZhihuUserContentDetailTool, createZhihuUserContentCommentsTool,\n createZhihuCreatorAccountStatsTool, createZhihuCreatorContentStatsTool, createZhihuQuotaTool,\n] as const\n","import type { Context } from '@deepseek-ai/cordis'\nimport type { ZhihuService } from './index.ts'\nimport { createZhihuSearchTool, createZhihuGlobalSearchTool, createZhihuHotListTool, createZhihuAskTool, createZhihuKnowledgeSearchTool } from './tool-definitions.ts'\nimport { ZHIHU_OPEN_PLATFORM_TOOL_FACTORIES } from './open-platform-tools.ts'\nexport const name = 'dsh-zhihu-tools'\nexport const inject = ['zhihu', 'tools'] as const\nexport function apply(ctx: Context): void {\n const host = ctx as Context & { zhihu: ZhihuService; tools: { register: (tool: unknown) => unknown } }\n const options = host.zhihu.toolOptions\n for (const create of [createZhihuSearchTool, createZhihuGlobalSearchTool, createZhihuHotListTool, createZhihuAskTool, createZhihuKnowledgeSearchTool, ...ZHIHU_OPEN_PLATFORM_TOOL_FACTORIES]) {\n const tool = create(options)\n const execute = tool.execute as unknown as (args: unknown, exec: { signal: AbortSignal }) => Promise<unknown>\n host.tools.register({ ...tool, execute: (args: unknown, exec: { signal: AbortSignal }) =>\n host.zhihu.run(signal => execute(args, { ...exec, signal }), exec.signal) })\n }\n}\n"],"mappings":";;;;AAUA,MAAM,qBAAqB;CACzB,MAAM;CACN,sBAAsB;CACtB,YAAY;EACV,OAAO;GAAE,MAAM;GAAU,UAAU;EAAK;EACxC,MAAM;GAAE,MAAM;GAAU,UAAU;EAAK;EACvC,KAAK;GAAE,MAAM;GAAU,UAAU;EAAK;EACtC,SAAS;GAAE,MAAM;GAAU,UAAU;EAAK;EAC1C,OAAO;GAAE,MAAM;GAAW,UAAU;EAAK;EACzC,UAAU;GAAE,MAAM;GAAW,UAAU;EAAK;EAC5C,QAAQ;GAAE,MAAM;GAAU,UAAU;EAAK;EACzC,WAAW;GAAE,MAAM;GAAU,UAAU;EAAK;EAC5C,UAAU;GAAE,MAAM;GAAU,UAAU;EAAK;CAC7C;AACF;AAEA,SAAgB,sBAAsB,UAAwC,CAAC,GAAG;CAChF,MAAM,EAAE,YAAY,GAAG,WAAW;CAClC,OAAO,WAAW;EAChB,MAAM;EACN,aAAa;EACb,YAAY;GACV,OAAO;IAAE,MAAM;IAAU,UAAU;IAAM,aAAa;GAAgB;GACtE,OAAO;IAAE,MAAM;IAAW,aAAa;GAAqE;EAC9G;EACA,QAAQ;GACN,QAAQ;IACN,MAAM;IACN,sBAAsB;IACtB,YAAY;KACV,SAAS;MAAE,MAAM;MAAW,UAAU;KAAK;KAC3C,OAAO;MAAE,MAAM;MAAU,UAAU;KAAK;KACxC,OAAO;MAAE,MAAM;MAAW,UAAU;KAAK;KACzC,OAAO;MACL,MAAM;MACN,UAAU;MACV,OAAO;KACT;KACA,aAAa,EAAE,MAAM,SAAS;IAChC;GACF;GACA,OAAO,OAAO,OAAO;IACnB,OAAO,CAAC;KAAE,MAAM;KAAiB,MAAM,kBAAkB,KA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;;;ACxHA,MAAa,OAAO;AACpB,MAAa,SAAS,CAAC,SAAS,OAAO;AACvC,SAAgB,MAAM,KAAoB;CACxC,MAAM,OAAO;CACb,MAAM,UAAU,KAAK,MAAM;CAC3B,KAAK,MAAM,UAAU;EAAC;EAAuB;EAA6B;EAAwB;EAAoB;EAAgC,GAAG;CAAkC,GAAG;EAC5L,MAAM,OAAO,OAAO,OAAO;EAC3B,MAAM,UAAU,KAAK;EACrB,KAAK,MAAM,SAAS;GAAE,GAAG;GAAM,UAAU,MAAe,SACtD,KAAK,MAAM,KAAI,WAAU,QAAQ,MAAM;IAAE,GAAG;IAAM;GAAO,CAAC,GAAG,KAAK,MAAM;EAAE,CAAC;CAC/E;AACF"}
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Zhihu",
4
+ "description": "Zhihu search, agent tools, knowledge bases, and usage tracking."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "知乎",
4
+ "description": "知乎搜索、智能体工具、知识库和用量统计。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "name": "@klarkxy/dsh-zhihu",
3
- "version": "0.1.8",
3
+ "version": "0.1.10",
4
4
  "description": "Zhihu search, agent tools, knowledge bases, and usage tracking for DeepSeek Harness.",
5
+ "icon": "./icon.svg",
5
6
  "license": "SEE LICENSE IN LICENSE",
6
7
  "type": "module",
7
8
  "engines": {
@@ -33,10 +34,12 @@
33
34
  "./client": {
34
35
  "default": "./lib/client.js"
35
36
  },
36
- "./package.json": "./package.json"
37
+ "./package.json": "./package.json",
38
+ "./locale/*.json": "./locale/*.json"
37
39
  },
38
40
  "files": [
39
41
  "icon.svg",
42
+ "locale/*.json",
40
43
  "lib/*.js",
41
44
  "lib/*.js.map",
42
45
  "lib/*.d.ts",
@@ -53,7 +56,8 @@
53
56
  "platform": "web",
54
57
  "inject": [
55
58
  "@deepseek-ai/dsh-client-connection",
56
- "@deepseek-ai/dsh-api-remotes"
59
+ "@deepseek-ai/dsh-api-remotes",
60
+ "@deepseek-ai/dsh-client-ui-primitives"
57
61
  ]
58
62
  }
59
63
  },
@@ -89,7 +93,8 @@
89
93
  "test": "vitest run --root ../.. --config vitest.editor-plugins.config.ts --maxWorkers=2 plugins/dsh-zhihu/src"
90
94
  },
91
95
  "dependencies": {
92
- "zod": "^4.1.5"
96
+ "zod": "^4.1.5",
97
+ "@klarkxy/dsh-plugin-kit": "0.1.0"
93
98
  },
94
99
  "peerDependencies": {
95
100
  "@deepseek-ai/cordis": "^4.0.4",
@@ -105,7 +110,8 @@
105
110
  "react": "^18.2.0",
106
111
  "@types/react": "18.3.31",
107
112
  "react-dom": "^18.2.0",
108
- "@types/react-dom": "^18.3.1"
113
+ "@types/react-dom": "^18.3.1",
114
+ "@deepseek-ai/dsh-client-ui-primitives": "0.1.7-rc.2"
109
115
  },
110
116
  "peerDependenciesMeta": {
111
117
  "@deepseek-ai/dsh-credentials": {
@@ -142,6 +148,6 @@
142
148
  "registry": "https://registry.npmjs.org/"
143
149
  },
144
150
  "dshRelease": {
145
- "contentHash": "abfa1b559afda73ac70b685e2d9bae00fbcc250806fbd1369f9f189fd040e0ca"
151
+ "contentHash": "1badbace8750df1849db5448e135df8930575a4a85fb743cb33940f448decfc8"
146
152
  }
147
153
  }
package/lib/operations.js DELETED
@@ -1,378 +0,0 @@
1
- import { readFile } from "node:fs/promises";
2
- import { homedir } from "node:os";
3
- import { join } from "node:path";
4
- //#region src/zhihu-client.ts
5
- /**
6
- * 知乎开放平台共享请求层:Access Secret 解析、超时封装、信封解析与执行计量。
7
- *
8
- * 端点规范(来源:github.com/klarkxy/zhihu-search,src/zhihu_search/upstream/http_client.py):
9
- * - Base URL: https://developer.zhihu.com
10
- * - 公共 Headers: Authorization: Bearer <access_secret>、X-Request-Timestamp、Accept
11
- * - 除直答外的 REST 接口返回 {Code, Message, Data} 信封,Code 非 0 表示业务错误。
12
- *
13
- * Token 解析顺序(按契约,**不**把 token 放进 schema 参数):
14
- * 1. 可选的 credential 解析器(应用设置界面写入 `ZHIHU_ACCESS_TOKEN` 后,
15
- * 通过 `ctx.credentials.resolve` 取回);命中即返回,source 标记为 `credential`。
16
- * 2. 环境变量 ZHIHU_ACCESS_TOKEN
17
- * 3. 环境变量 ZHIHU_ACCESS_SECRET(zhihu-search CLI 同名变量)
18
- * 4. ~/.config/zhihu-search/credentials.json 的 access_secret 字段
19
- * 都没有则抛出带中文配置指引的 TOKEN_MISSING。
20
- */
21
- const ZHIHU_BASE_URL = "https://developer.zhihu.com";
22
- const ZHIHU_CREDENTIALS_PRIMARY = "ZHIHU_ACCESS_TOKEN";
23
- const ZHIHU_CREDENTIALS_FALLBACK = "ZHIHU_ACCESS_SECRET";
24
- const ZHIHU_CREDENTIALS_FILE = join(homedir(), ".config", "zhihu-search", "credentials.json");
25
- const globalFetch = typeof globalThis !== "undefined" && typeof globalThis.fetch === "function" ? (input, init) => {
26
- const f = globalThis.fetch;
27
- return f(input, init);
28
- } : void 0;
29
- function looksLikeToken(value) {
30
- const trimmed = value.trim();
31
- return trimmed.length >= 8 && trimmed.length <= 256;
32
- }
33
- async function readCredentialsFile(path) {
34
- try {
35
- const raw = await readFile(path, "utf8");
36
- const parsed = JSON.parse(raw);
37
- if (parsed && typeof parsed === "object" && typeof parsed.access_secret === "string" && looksLikeToken(parsed.access_secret)) return parsed.access_secret.trim();
38
- } catch {}
39
- }
40
- async function resolveZhihuToken(env = process.env, options = {}) {
41
- if (options.resolveCredential) {
42
- const fromCredential = (await options.resolveCredential())?.trim();
43
- if (fromCredential && looksLikeToken(fromCredential)) return {
44
- token: fromCredential,
45
- source: "credential"
46
- };
47
- }
48
- const primary = env[ZHIHU_CREDENTIALS_PRIMARY]?.trim();
49
- if (primary && looksLikeToken(primary)) return {
50
- token: primary,
51
- source: "env-primary"
52
- };
53
- const fallback = env[ZHIHU_CREDENTIALS_FALLBACK]?.trim();
54
- if (fallback && looksLikeToken(fallback)) return {
55
- token: fallback,
56
- source: "env-fallback"
57
- };
58
- const fromFile = await readCredentialsFile(ZHIHU_CREDENTIALS_FILE);
59
- if (fromFile) return {
60
- token: fromFile,
61
- source: "file"
62
- };
63
- throw new ZhihuSearchError("TOKEN_MISSING", ["未找到知乎 Access Secret。请在「设置 → 知乎」中填写;", `也可设置环境变量 ${ZHIHU_CREDENTIALS_PRIMARY} 或写入 ~/.config/zhihu-search/credentials.json。`].join(""));
64
- }
65
- var ZhihuSearchError = class extends Error {
66
- code;
67
- status;
68
- constructor(code, message, status) {
69
- super(message);
70
- this.name = "ZhihuSearchError";
71
- this.code = code;
72
- if (status !== void 0) this.status = status;
73
- }
74
- };
75
- /** Metering must never break the tool itself. */
76
- function reportExecuted(hook, event) {
77
- if (!hook) return;
78
- try {
79
- hook(event);
80
- } catch {}
81
- }
82
- function isAbortError(error) {
83
- if (error instanceof Error && error.name === "AbortError") return true;
84
- return typeof error === "object" && error !== null && error.name === "AbortError";
85
- }
86
- /**
87
- * 发起一次带鉴权与超时的知乎请求,返回解析后的 JSON 原文(信封由调用方处理)。
88
- * `label` 用于中文错误文案,如「知乎搜索」「知乎热榜」。
89
- */
90
- async function zhihuFetchJson(path, init, label, options = {}) {
91
- const token = await resolveZhihuToken(options.env, { resolveCredential: options.resolveCredential });
92
- const fetcher = options.fetcher ?? globalFetch;
93
- if (!fetcher) throw new ZhihuSearchError("BAD_RESPONSE", "当前环境没有可用的 fetch。");
94
- const url = new URL(path, ZHIHU_BASE_URL);
95
- for (const [key, value] of Object.entries(init.params ?? {})) url.searchParams.set(key, value);
96
- const method = init.method ?? (init.formData || init.body !== void 0 ? "POST" : "GET");
97
- const timeout = options.timeoutMs ?? 15e3;
98
- const controller = new AbortController();
99
- const linked = options.signal;
100
- const onAbort = () => controller.abort(linked?.reason);
101
- if (linked) {
102
- if (linked.aborted) controller.abort(linked.reason);
103
- else linked.addEventListener("abort", onAbort, { once: true });
104
- }
105
- const timer = setTimeout(() => controller.abort(/* @__PURE__ */ new Error("zhihu request timeout")), timeout);
106
- let response;
107
- try {
108
- response = await fetcher(url.toString(), {
109
- method,
110
- headers: {
111
- Authorization: `Bearer ${token.token}`,
112
- "X-Request-Timestamp": String(Math.floor(Date.now() / 1e3)),
113
- Accept: "application/json",
114
- ...method === "POST" && !init.formData ? { "Content-Type": "application/json" } : {}
115
- },
116
- signal: controller.signal,
117
- ...init.formData ? { body: init.formData } : init.body !== void 0 ? { body: JSON.stringify(init.body) } : {}
118
- });
119
- } catch (error) {
120
- if (isAbortError(error) || controller.signal.aborted) throw new ZhihuSearchError("TIMEOUT", `${label}超时(${Math.round(timeout / 1e3)} 秒),请稍后再试。`);
121
- throw new ZhihuSearchError("BAD_RESPONSE", `${label}失败:${error instanceof Error ? error.message : String(error)}`);
122
- } finally {
123
- clearTimeout(timer);
124
- if (linked) linked.removeEventListener("abort", onAbort);
125
- }
126
- if (!response.ok) throw new ZhihuSearchError("HTTP_ERROR", `${label}返回 HTTP ${response.status}。`, response.status);
127
- try {
128
- return await response.json();
129
- } catch (error) {
130
- throw new ZhihuSearchError("BAD_RESPONSE", `${label}响应不是合法 JSON:${error instanceof Error ? error.message : String(error)}`);
131
- }
132
- }
133
- /** 解析 {Code, Message, Data} 信封,Code 非 0 抛出 HTTP_ERROR;返回 Data(缺省为 {})。 */
134
- function parseZhihuEnvelope(body) {
135
- if (!body || typeof body !== "object" || Array.isArray(body)) throw new ZhihuSearchError("BAD_RESPONSE", "知乎响应缺少 {Code,Message,Data} 信封。");
136
- const envelope = body;
137
- const code = Number(envelope.Code);
138
- if (!Number.isFinite(code) || code !== 0) {
139
- const msg = typeof envelope.Message === "string" ? envelope.Message : "未知错误";
140
- throw new ZhihuSearchError("HTTP_ERROR", `知乎开放平台返回错误(code=${envelope.Code ?? "?"}):${msg}`);
141
- }
142
- return envelope.Data ?? {};
143
- }
144
- function truncateSummary(text, limit) {
145
- if (text.length <= limit) return text;
146
- return `${text.slice(0, limit)}…`;
147
- }
148
- function normalizeSearchItem(raw) {
149
- const summary = typeof raw.ContentText === "string" ? raw.ContentText : "";
150
- return {
151
- title: typeof raw.Title === "string" && raw.Title.length > 0 ? raw.Title : "(无标题)",
152
- type: typeof raw.ContentType === "string" && raw.ContentType.length > 0 ? raw.ContentType : "内容",
153
- url: typeof raw.Url === "string" ? raw.Url : "",
154
- summary: truncateSummary(summary.trim(), 200),
155
- votes: typeof raw.VoteUpCount === "number" ? raw.VoteUpCount : 0,
156
- comments: typeof raw.CommentCount === "number" ? raw.CommentCount : 0,
157
- author: typeof raw.AuthorName === "string" && raw.AuthorName.length > 0 ? raw.AuthorName : "匿名",
158
- authority: typeof raw.AuthorityLevel === "string" && raw.AuthorityLevel.length > 0 ? raw.AuthorityLevel : "?",
159
- editTime: typeof raw.EditTime === "number" ? String(raw.EditTime) : ""
160
- };
161
- }
162
- const ZHIHU_SEARCH_PATH = "/api/v1/content/zhihu_search";
163
- function clampCount(value) {
164
- const n = typeof value === "number" && Number.isFinite(value) ? Math.trunc(value) : 5;
165
- if (n < 1) return 1;
166
- if (n > 10) return 10;
167
- return n;
168
- }
169
- function filterItems(data) {
170
- const row = data ?? {};
171
- return {
172
- items: Array.isArray(row.Items) ? row.Items.filter((item) => !!item && typeof item === "object" && !Array.isArray(item)) : [],
173
- emptyReason: typeof row.EmptyReason === "string" ? row.EmptyReason : void 0
174
- };
175
- }
176
- async function executeZhihuSearch(query, count, options = {}) {
177
- const trimmed = query.trim();
178
- if (!trimmed) throw new ZhihuSearchError("BAD_RESPONSE", "搜索词不能为空。");
179
- const resolvedCount = clampCount(count);
180
- const { items, emptyReason } = filterItems(parseZhihuEnvelope(await zhihuFetchJson(ZHIHU_SEARCH_PATH, { params: {
181
- Query: trimmed,
182
- Count: String(resolvedCount)
183
- } }, "知乎搜索", options)));
184
- return {
185
- version: 1,
186
- query: trimmed,
187
- count: resolvedCount,
188
- items: items.map(normalizeSearchItem),
189
- emptyReason
190
- };
191
- }
192
- function renderZhihuSearch(result) {
193
- if (result.items.length === 0) return `知乎站内搜索「${result.query}」无结果${result.emptyReason ? `(${result.emptyReason})` : ""}。`;
194
- const lines = [`知乎站内搜索「${result.query}」共 ${result.items.length} 条:`, ""];
195
- result.items.forEach((item, index) => {
196
- lines.push(`${index + 1}. [${item.title}](${item.url || "(无链接)"})`);
197
- lines.push(` - 类型:${item.type} 作者:${item.author} 权威:${item.authority}`);
198
- if (item.editTime) lines.push(` - 时间:${item.editTime}`);
199
- lines.push(` - 赞同 ${item.votes} 评论 ${item.comments}`);
200
- if (item.summary) lines.push(` - 摘要:${item.summary}`);
201
- lines.push("");
202
- });
203
- return lines.join("\n").trimEnd();
204
- }
205
- const GLOBAL_SEARCH_PATH = "/api/v1/content/global_search";
206
- const HOT_LIST_PATH = "/api/v1/content/hot_list";
207
- const ASK_PATH = "/v1/chat/completions";
208
- const KNOWLEDGE_SEARCH_PATH = "/api/v1/knowledge/search";
209
- const ZHIHU_ASK_MODELS = [
210
- "zhida-fast-1p5",
211
- "zhida-thinking-1p5",
212
- "zhida-agent"
213
- ];
214
- /** 直答的价值在于比本机模型更强的综合考据,默认用思考档;fast 只配简单事实查询。 */
215
- const ZHIHU_ASK_DEFAULT_MODEL = "zhida-thinking-1p5";
216
- function clampInt(value, fallback, max) {
217
- const n = typeof value === "number" && Number.isFinite(value) ? Math.trunc(value) : fallback;
218
- if (n < 1) return 1;
219
- if (n > max) return max;
220
- return n;
221
- }
222
- function requireQuery(query, hint) {
223
- const trimmed = query.trim();
224
- if (!trimmed) throw new ZhihuSearchError("BAD_RESPONSE", hint);
225
- return trimmed;
226
- }
227
- function objectItems(data, key = "Items") {
228
- const items = (data ?? {})[key];
229
- return Array.isArray(items) ? items.filter((item) => !!item && typeof item === "object" && !Array.isArray(item)) : [];
230
- }
231
- async function executeZhihuGlobalSearch(query, count, searchDb, options = {}) {
232
- const trimmed = requireQuery(query, "搜索词不能为空。");
233
- const resolvedCount = clampInt(count, 10, 20);
234
- const data = parseZhihuEnvelope(await zhihuFetchJson(GLOBAL_SEARCH_PATH, { params: {
235
- Query: trimmed,
236
- Count: String(resolvedCount),
237
- SearchDB: searchDb
238
- } }, "知乎全网搜索", options));
239
- return {
240
- version: 1,
241
- query: trimmed,
242
- count: resolvedCount,
243
- searchDb,
244
- items: objectItems(data).map(normalizeSearchItem),
245
- emptyReason: typeof data.EmptyReason === "string" ? data.EmptyReason : void 0
246
- };
247
- }
248
- function renderZhihuGlobalSearch(result) {
249
- if (result.items.length === 0) return `全网搜索「${result.query}」无结果${result.emptyReason ? `(${result.emptyReason})` : ""}。`;
250
- const lines = [`全网搜索「${result.query}」共 ${result.items.length} 条:`, ""];
251
- result.items.forEach((item, index) => {
252
- lines.push(`${index + 1}. [${item.title}](${item.url || "(无链接)"})`);
253
- lines.push(` - 类型:${item.type} 作者:${item.author}`);
254
- if (item.summary) lines.push(` - 摘要:${item.summary}`);
255
- lines.push("");
256
- });
257
- return lines.join("\n").trimEnd();
258
- }
259
- const ZHIHU_HOT_LIST_SUMMARY_MAX_CHARS = 200;
260
- function normalizeHotItem(raw) {
261
- const summary = typeof raw.Summary === "string" ? raw.Summary.trim() : "";
262
- return {
263
- title: typeof raw.Title === "string" && raw.Title.length > 0 ? raw.Title : "(无标题)",
264
- url: typeof raw.Url === "string" ? raw.Url : "",
265
- summary: summary.length > ZHIHU_HOT_LIST_SUMMARY_MAX_CHARS ? `${summary.slice(0, ZHIHU_HOT_LIST_SUMMARY_MAX_CHARS)}…` : summary
266
- };
267
- }
268
- async function executeZhihuHotList(limit, options = {}) {
269
- const resolvedLimit = clampInt(limit, 10, 30);
270
- return {
271
- version: 1,
272
- limit: resolvedLimit,
273
- items: objectItems(parseZhihuEnvelope(await zhihuFetchJson(HOT_LIST_PATH, { params: { Limit: String(resolvedLimit) } }, "知乎热榜", options))).map(normalizeHotItem)
274
- };
275
- }
276
- function renderZhihuHotList(result) {
277
- if (result.items.length === 0) return "知乎热榜为空。";
278
- const lines = ["知乎热榜:", ""];
279
- result.items.forEach((item, index) => {
280
- lines.push(`${index + 1}. [${item.title}](${item.url || "(无链接)"})`);
281
- if (item.summary) lines.push(` - ${item.summary}`);
282
- lines.push("");
283
- });
284
- return lines.join("\n").trimEnd();
285
- }
286
- async function executeZhihuAsk(query, model, options = {}) {
287
- const trimmed = requireQuery(query, "直答问题不能为空。");
288
- const body = await zhihuFetchJson(ASK_PATH, {
289
- method: "POST",
290
- body: {
291
- model,
292
- messages: [{
293
- role: "user",
294
- content: trimmed
295
- }],
296
- stream: false
297
- }
298
- }, "知乎直答", {
299
- ...options,
300
- timeoutMs: options.timeoutMs ?? 12e4
301
- });
302
- if (!body || typeof body !== "object" || Array.isArray(body)) throw new ZhihuSearchError("BAD_RESPONSE", "知乎直答响应不是 OpenAI 兼容格式。");
303
- const payload = body;
304
- if (payload.error) throw new ZhihuSearchError("HTTP_ERROR", `知乎直答返回错误:${typeof payload.error.message === "string" ? payload.error.message : "未知错误"}`);
305
- const message = (Array.isArray(payload.choices) ? payload.choices[0] : void 0)?.message ?? {};
306
- const content = typeof message.content === "string" ? message.content.trim() : "";
307
- const reasoning = typeof message.reasoning_content === "string" ? message.reasoning_content.trim() : "";
308
- if (!content) throw new ZhihuSearchError("BAD_RESPONSE", "知乎直答返回为空。");
309
- return {
310
- version: 1,
311
- query: trimmed,
312
- model,
313
- content,
314
- reasoning
315
- };
316
- }
317
- function renderZhihuAsk(result) {
318
- const parts = [];
319
- if (result.reasoning) parts.push(`【思考过程】\n${result.reasoning}`);
320
- parts.push(result.content);
321
- return `知乎直答「${result.query}」:\n\n${parts.join("\n\n")}`;
322
- }
323
- const ZHIHU_RECALL_SCOPES = [
324
- "personal",
325
- "subscription",
326
- "public"
327
- ];
328
- function normalizeKnowledgeItem(raw) {
329
- const content = raw.Content;
330
- const snippets = Array.isArray(content) ? content.map((snippet) => String(snippet).trim()).filter((snippet) => snippet.length > 0) : [];
331
- return {
332
- docName: typeof raw.DocName === "string" && raw.DocName.length > 0 ? raw.DocName : "(未命名文档)",
333
- originUrl: typeof raw.OriginUrl === "string" ? raw.OriginUrl : "",
334
- snippets
335
- };
336
- }
337
- /** 收敛召回范围:只保留合法档位、去重;为空或未提供时回退公开库。 */
338
- function normalizeRecallScopes(value) {
339
- if (!Array.isArray(value)) return ["public"];
340
- const scopes = [...new Set(value.filter((scope) => typeof scope === "string" && ZHIHU_RECALL_SCOPES.includes(scope)))];
341
- return scopes.length > 0 ? scopes : ["public"];
342
- }
343
- async function executeZhihuKnowledgeSearch(query, limit, recallScopes, options = {}) {
344
- const trimmed = requireQuery(query, "知识库检索词不能为空。");
345
- const resolvedLimit = clampInt(limit, 5, 10);
346
- return {
347
- version: 1,
348
- query: trimmed,
349
- limit: resolvedLimit,
350
- recallScopes,
351
- items: objectItems(parseZhihuEnvelope(await zhihuFetchJson(KNOWLEDGE_SEARCH_PATH, {
352
- method: "POST",
353
- body: {
354
- Query: trimmed,
355
- Limit: resolvedLimit,
356
- RecallScopes: recallScopes
357
- }
358
- }, "知乎知识库检索", {
359
- ...options,
360
- timeoutMs: options.timeoutMs ?? 3e4
361
- }))).map(normalizeKnowledgeItem)
362
- };
363
- }
364
- function renderZhihuKnowledgeSearch(result) {
365
- if (result.items.length === 0) return `知乎知识库检索「${result.query}」无匹配结果。`;
366
- const lines = [`知乎知识库检索「${result.query}」共 ${result.items.length} 条:`, ""];
367
- result.items.forEach((item, index) => {
368
- lines.push(`${index + 1}. ${item.docName}`);
369
- if (item.originUrl) lines.push(` - 来源:${item.originUrl}`);
370
- for (const snippet of item.snippets) lines.push(` - ${snippet}`);
371
- lines.push("");
372
- });
373
- return lines.join("\n").trimEnd();
374
- }
375
- //#endregion
376
- export { reportExecuted as _, executeZhihuGlobalSearch as a, normalizeRecallScopes as c, renderZhihuHotList as d, renderZhihuKnowledgeSearch as f, parseZhihuEnvelope as g, ZhihuSearchError as h, executeZhihuAsk as i, renderZhihuAsk as l, renderZhihuSearch as m, ZHIHU_ASK_MODELS as n, executeZhihuHotList as o, executeZhihuSearch as p, ZHIHU_RECALL_SCOPES as r, executeZhihuKnowledgeSearch as s, ZHIHU_ASK_DEFAULT_MODEL as t, renderZhihuGlobalSearch as u, zhihuFetchJson as v };
377
-
378
- //# sourceMappingURL=operations.js.map