search.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. /**
  2. * The model-facing `web_search` tool: discover current information on the web.
  3. * Execution goes through `ctx.web` — this module owns only the model-facing
  4. * schema, argument validation, the result-count bound, and result formatting,
  5. * never provider selection or network access.
  6. */
  7. import type { Context } from 'cordis'
  8. import { defineTool } from '@deepseek-ai/dsh-tools'
  9. import type { GenericCallView, JsonValue, ToolResult, WebSearchResultView, WebSource } from '@deepseek-ai/dsh-tools'
  10. import type { WebSearchResult, WebSearchSource } from '@deepseek-ai/dsh-web'
  11. import type {} from '@deepseek-ai/dsh-system-prompt'
  12. /**
  13. * Default upper bound on returned sources (the `searchMaxResults` config).
  14. * Owned by the consumer (not the provider or model), mirroring `dsh-tool-fs`'s
  15. * `READ_LIMIT`. The model just asks a question; the product controls how much
  16. * context returns. The default `8` aligns with OpenCode's Exa default.
  17. */
  18. export const WEB_SEARCH_MAX_RESULTS = 8
  19. /**
  20. * Validate value constraints the schema DSL can't express: a non-blank
  21. * `query`. Throws a plain `Error` otherwise.
  22. *
  23. * @param args - the schema-validated `web_search` arguments.
  24. * @returns the accepted arguments, passed through unchanged.
  25. */
  26. export function parseSearchArgs(args: { query: string }): { query: string } {
  27. if (args.query.trim().length === 0) throw new Error('query must be a non-empty string')
  28. return { query: args.query }
  29. }
  30. /** Display label for a source: its title, else its hostname. */
  31. function sourceLabel(url: string, title: string | undefined): string {
  32. if (title !== undefined && title.length > 0) return title
  33. try {
  34. return new URL(url).hostname
  35. } catch {
  36. // A provider should return a valid URL, but never let a malformed one throw
  37. // out of pure formatting — fall back to the raw string.
  38. return url
  39. }
  40. }
  41. /**
  42. * Format a search result as one model-facing text block.
  43. *
  44. * @param result - the seam's search outcome.
  45. * @returns the provider answer (when any), a markdown source list with snippet
  46. * and date metadata (or `No results found.`), a refine-the-query note when
  47. * truncated, and a standing cite-your-sources instruction.
  48. */
  49. export function formatSearchOutput(result: WebSearchResult): string {
  50. const parts: string[] = []
  51. if (result.content !== undefined && result.content.length > 0) parts.push(result.content)
  52. if (result.sources.length > 0) {
  53. const lines = result.sources.map((source) => {
  54. const label = sourceLabel(source.url, source.title)
  55. const meta: string[] = []
  56. if (source.snippet !== undefined && source.snippet.length > 0) meta.push(source.snippet)
  57. if (source.publishedAt !== undefined && source.publishedAt.length > 0) meta.push(`(${source.publishedAt})`)
  58. const suffix = meta.length > 0 ? ` — ${meta.join(' ')}` : ''
  59. return `- [${label}](${source.url})${suffix}`
  60. })
  61. parts.push(`Sources:\n${lines.join('\n')}`)
  62. } else if (result.content === undefined || result.content.length === 0) {
  63. parts.push('No results found.')
  64. }
  65. if (result.truncated) parts.push(`(Showing the first ${result.sources.length} sources. Refine the query for more.)`)
  66. parts.push('Cite the relevant URLs above as markdown links in your answer.')
  67. return parts.join('\n\n')
  68. }
  69. /**
  70. * Pending-call presentation: a search card titled by the query.
  71. *
  72. * @param args - the raw tool arguments; only `query` feeds the view.
  73. * @returns the generic card view (`kind: 'search'`) shown while the call runs.
  74. */
  75. export function presentSearchCall(args: { query: string }): GenericCallView {
  76. return { card: 'generic', title: args.query, kind: 'search', rawInput: args.query }
  77. }
  78. /**
  79. * The `web_search` tool's private `tool/result` `meta` payload: the structured
  80. * sources, the optional provider answer, and the truncation flag. Attached
  81. * opaquely (as `JsonValue`) on the tool result and persisted with the session
  82. * log, so `presentResult` reproduces the search card on replay. This projection
  83. * is the only faithful route to the per-source fields, which the lossy render
  84. * text cannot carry (the owning rationale is the web-result-card Agent Note).
  85. */
  86. export interface WebSearchMeta {
  87. /** The faithful structured sources, in result order. */
  88. sources: WebSource[]
  89. /** True when the seam cut the source list to honor the result cap. */
  90. truncated: boolean
  91. /** The provider-generated answer text, when any. */
  92. answer?: string
  93. }
  94. /**
  95. * Project one seam source into a plain object that omits every absent optional
  96. * field. Shared by the canonical `execute` result and its replayable
  97. * presentation meta so both carry byte-identical source shapes.
  98. *
  99. * @param source - one source from the `ctx.web` search outcome.
  100. * @returns `{ url }` plus each present optional field.
  101. */
  102. function projectSource(source: WebSearchSource): {
  103. url: string
  104. title?: string
  105. snippet?: string
  106. publishedAt?: string
  107. } {
  108. return {
  109. url: source.url,
  110. ...source.title !== undefined ? { title: source.title } : {},
  111. ...source.snippet !== undefined ? { snippet: source.snippet } : {},
  112. ...source.publishedAt !== undefined ? { publishedAt: source.publishedAt } : {},
  113. }
  114. }
  115. /**
  116. * Project a validated `web_search` output value into its replayable
  117. * presentation meta ({@link WebSearchMeta} as opaque JSON).
  118. *
  119. * @param value - the canonical `web_search` output value (the seam's result shape).
  120. * @returns the structured sources, the truncation flag, and the answer when present.
  121. */
  122. export function searchMetaFromValue(value: WebSearchResult): JsonValue {
  123. return {
  124. sources: value.sources.map(projectSource),
  125. truncated: value.truncated,
  126. ...value.content !== undefined ? { answer: value.content } : {},
  127. }
  128. }
  129. /** Whether `value` is a valid {@link WebSource} (defensive narrowing from opaque `meta`). */
  130. function isWebSource(value: unknown): value is WebSource {
  131. if (typeof value !== 'object' || value === null || Array.isArray(value)) return false
  132. const { url, title, snippet, publishedAt } = value as Record<string, unknown>
  133. return typeof url === 'string'
  134. && (title === undefined || typeof title === 'string')
  135. && (snippet === undefined || typeof snippet === 'string')
  136. && (publishedAt === undefined || typeof publishedAt === 'string')
  137. }
  138. /**
  139. * Narrow opaque live or replayed result metadata to a {@link WebSearchMeta}.
  140. * Malformed metadata returns `undefined` so presentation can fall back to the
  141. * generic card instead of throwing during replay.
  142. *
  143. * @param meta - result metadata.
  144. * @returns the validated search meta, or `undefined` for absent or malformed data.
  145. */
  146. export function searchMetaFromResult(meta: unknown): WebSearchMeta | undefined {
  147. if (typeof meta !== 'object' || meta === null || Array.isArray(meta)) return undefined
  148. const { sources, truncated, answer } = meta as Record<string, unknown>
  149. if (!Array.isArray(sources) || !sources.every(isWebSource)) return undefined
  150. if (typeof truncated !== 'boolean') return undefined
  151. if (answer !== undefined && typeof answer !== 'string') return undefined
  152. return {
  153. sources,
  154. truncated,
  155. ...answer !== undefined ? { answer } : {},
  156. }
  157. }
  158. /**
  159. * Completed-call presentation: a `web` search card carrying the faithful
  160. * structured sources from `meta`. It sets no `content` copy — a UI without the
  161. * `web` capability falls back to the raw `tool/result` content, which is the
  162. * same text (see the web-result-card Agent Note).
  163. *
  164. * @param args - the raw tool arguments; `query` becomes the result-state title so
  165. * a window-truncated replay that dropped the call head still has one.
  166. * @param result - the final model-facing tool result; `meta` carries the sources.
  167. * @returns the search result view, or `undefined` (generic card) on failure or
  168. * malformed meta.
  169. */
  170. export function presentSearchResult(args: { query: string }, result: ToolResult): WebSearchResultView | undefined {
  171. if (result.isError) return undefined
  172. const meta = searchMetaFromResult(result.meta)
  173. if (meta === undefined) return undefined
  174. return {
  175. card: 'web',
  176. kind: 'search',
  177. title: args.query,
  178. sources: meta.sources,
  179. truncated: meta.truncated,
  180. ...meta.answer !== undefined ? { answer: meta.answer } : {},
  181. }
  182. }
  183. /**
  184. * Register the `web_search` tool and its system-prompt guidance.
  185. *
  186. * @param ctx - context whose `tools` and `systemPrompt` registries receive the
  187. * registrations; both are effect-scoped and unregister on plugin dispose.
  188. * @param maxResults - the deployment's source cap, sent as every seam
  189. * request's `maxResults`.
  190. * @param timeoutMs - the cooperative tool-call budget (ms) attached as the tool's
  191. * `ToolDefinition.timeoutMs` for `@deepseek-ai/dsh-timeout-policy` to enforce.
  192. * @param fetchEnabled - whether the same composition exposes `web_fetch`, which
  193. * controls whether search guidance may recommend that follow-up tool.
  194. */
  195. export function applyWebSearchTool(
  196. ctx: Context,
  197. maxResults: number,
  198. timeoutMs: number,
  199. fetchEnabled: boolean,
  200. ): void {
  201. ctx.systemPrompt.section({
  202. name: 'tool:web_search',
  203. order: 110,
  204. text: fetchEnabled
  205. ? 'Use the web_search tool to discover current information on the web. It returns an optional answer plus a list of source URLs. Follow up with web_fetch when you need the full content of a specific result, and cite the relevant URLs as markdown links.'
  206. : 'Use the web_search tool to discover current information on the web. It returns an optional answer plus a list of source URLs. Use the returned source snippets when available, and cite the relevant URLs as markdown links.',
  207. })
  208. ctx.tools.register(defineTool({
  209. name: 'web_search',
  210. description: 'Search the web for current information. Returns an optional summary answer and a list of source URLs.',
  211. parameters: {
  212. query: { type: 'string', required: true, description: 'The search query.' },
  213. },
  214. output: {
  215. schema: {
  216. type: 'object',
  217. additionalProperties: false,
  218. properties: {
  219. content: { type: 'string' },
  220. sources: {
  221. type: 'array',
  222. required: true,
  223. items: {
  224. type: 'object',
  225. additionalProperties: false,
  226. properties: {
  227. url: { type: 'string', required: true },
  228. title: { type: 'string' },
  229. snippet: { type: 'string' },
  230. publishedAt: { type: 'string' },
  231. },
  232. },
  233. },
  234. truncated: { type: 'boolean', required: true },
  235. },
  236. },
  237. render: (_args, value) => [{ type: 'text', text: formatSearchOutput(value) }],
  238. presentationMeta: (_args, value) => searchMetaFromValue(value),
  239. },
  240. timeoutMs,
  241. // Provider reads do not mutate parent-agent state.
  242. isConcurrencySafe: () => true,
  243. async execute(args, exec) {
  244. const input = parseSearchArgs(args)
  245. const result = await ctx.web.search(
  246. { query: input.query, maxResults },
  247. exec.signal,
  248. )
  249. return {
  250. ...result.content !== undefined ? { content: result.content } : {},
  251. sources: result.sources.map(projectSource),
  252. truncated: result.truncated,
  253. }
  254. },
  255. presentCall: presentSearchCall,
  256. presentResult: (args, result) => presentSearchResult(args, result),
  257. }))
  258. }