fetch.ts 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /**
  2. * The model-facing `web_fetch` tool. This module owns its schema, validation, and presentation;
  3. * `ctx.web` owns retrieval. Timeout is deployment policy, not a model argument: config becomes
  4. * `ToolDefinition.timeoutMs`, timeout policy enforces it, and this tool forwards the resulting
  5. * signal. A provider timeout remains a backstop for direct seam callers.
  6. */
  7. import type { Context } from 'cordis'
  8. import { defineTool } from '@deepseek-ai/dsh-tools'
  9. import type { GenericCallView } from '@deepseek-ai/dsh-tools'
  10. import type { ContentBlock } from '@deepseek-ai/dsh-llm'
  11. import type { WebFetchBody, WebFetchResult } from '@deepseek-ai/dsh-web'
  12. import { assertNever } from '@deepseek-ai/dsh-llm'
  13. import type {} from '@deepseek-ai/dsh-system-prompt'
  14. import { htmlToMarkdown } from './html.ts'
  15. /**
  16. * Validate value constraints the schema DSL can't express: a non-blank `url`.
  17. * Throws a plain `Error` otherwise. No timeout parameter — the tool-call budget
  18. * is deployment policy declared via `fetchTimeoutMs` config and enforced by
  19. * `@deepseek-ai/dsh-timeout-policy`, not a model argument.
  20. *
  21. * @param args - the schema-validated `web_fetch` arguments.
  22. * @returns the arguments as the seam's request fields.
  23. */
  24. export function parseFetchArgs(args: { url: string }): { url: string } {
  25. if (args.url.trim().length === 0) throw new Error('url must be a non-empty string')
  26. return { url: args.url }
  27. }
  28. /**
  29. * Render a fetched body to model-facing markdown text.
  30. *
  31. * @param body - the decoded body; `html` is converted via
  32. * {@link htmlToMarkdown}, `text` passes through verbatim.
  33. * @returns the text for the tool's output block.
  34. */
  35. export function renderBody(body: WebFetchBody): string {
  36. switch (body.kind) {
  37. case 'html':
  38. return htmlToMarkdown(body.content)
  39. case 'text':
  40. return body.content
  41. /* v8 ignore next 2 -- WebFetchBody is a closed union; this arm is unreachable and only makes adding a kind a compile error. */
  42. default:
  43. return assertNever(body, 'unhandled web fetch body kind')
  44. }
  45. }
  46. /**
  47. * Format a fetch result as one model-facing text block.
  48. *
  49. * @param result - the seam's fetch outcome.
  50. * @returns a `Fetched <url> (HTTP <status>)` header, the rendered body, and a
  51. * fetch-something-narrower notice when the provider truncated the content.
  52. */
  53. export function formatFetchOutput(result: WebFetchResult): string {
  54. const header = `Fetched ${result.url} (HTTP ${result.statusCode})`
  55. const footer = result.truncated ? '\n\n(Content truncated. Fetch a more specific URL or section for the full text.)' : ''
  56. return `${header}\n\n${renderBody(result.body)}${footer}`
  57. }
  58. /**
  59. * Pending-call presentation: a fetch card titled by the URL.
  60. *
  61. * @param args - the raw tool arguments; only `url` feeds the view.
  62. * @returns the generic card view (`kind: 'fetch'`) shown while the call runs.
  63. */
  64. export function presentFetchCall(args: { url: string }): GenericCallView {
  65. return { card: 'generic', title: args.url, kind: 'fetch', rawInput: args.url }
  66. }
  67. /**
  68. * Register the `web_fetch` tool and its system-prompt guidance.
  69. *
  70. * @param ctx - context whose `tools` and `systemPrompt` registries receive the
  71. * registrations; both are effect-scoped and unregister on plugin dispose.
  72. * @param timeoutMs - the cooperative tool-call budget (ms) attached as the tool's
  73. * `ToolDefinition.timeoutMs` for `@deepseek-ai/dsh-timeout-policy` to enforce.
  74. */
  75. export function applyWebFetchTool(ctx: Context, timeoutMs: number): void {
  76. ctx.systemPrompt.section({
  77. name: 'tool:web_fetch',
  78. order: 111,
  79. text: 'Use the web_fetch tool to retrieve the content of a specific HTTP(S) URL (for example a result from web_search). It returns the page content decoded to text. Cite the URL as a markdown link when you use its content.',
  80. })
  81. ctx.tools.register(defineTool({
  82. name: 'web_fetch',
  83. description: 'Fetch the content of a specific HTTP(S) URL and return it decoded to text.',
  84. parameters: {
  85. url: { type: 'string', required: true, description: 'The HTTP(S) URL to fetch.' },
  86. },
  87. timeoutMs,
  88. async execute(args, exec): Promise<ContentBlock[]> {
  89. const input = parseFetchArgs(args)
  90. const result = await ctx.web.fetch(
  91. { url: input.url },
  92. exec.signal,
  93. )
  94. return [{ type: 'text', text: formatFetchOutput(result) }]
  95. },
  96. presentCall: presentFetchCall,
  97. }))
  98. }