integration.spec.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. /**
  2. * Integration: the real fetch backend (`dsh-web-fetch-http`) + a real search provider
  3. * (`dsh-web-search-exa`) + the real seam (`dsh-web`) + the model tool (`dsh-tool-web`) + the
  4. * tool-call timeout policy (`dsh-tool-call-timeout-policy`), exercised through `ctx.tools.execute()` —
  5. * nothing bypasses the tool registry. Fetch verifies world effects against loopback HTTP with
  6. * public-address resolution replaced by the fixture address; search uses the real Exa provider
  7. * with only its network boundary stubbed.
  8. */
  9. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
  10. import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'
  11. import { AddressInfo } from 'node:net'
  12. import { Context } from '@deepseek-ai/cordis'
  13. import { ToolCallId } from '@deepseek-ai/dsh-llm'
  14. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  15. import ToolRuntime, { type ToolExecutionResult } from '@deepseek-ai/dsh-tools'
  16. import WebRuntime from '@deepseek-ai/dsh-web'
  17. import * as WebFetchLocal from '@deepseek-ai/dsh-web-fetch-http'
  18. import * as WebSearchExa from '@deepseek-ai/dsh-web-search-exa'
  19. import * as ToolWeb from '@deepseek-ai/dsh-tool-web'
  20. import * as TimeoutPolicy from '@deepseek-ai/dsh-tool-call-timeout-policy'
  21. import { publicHttpNetwork } from '../../web-fetch-http/src/network.ts'
  22. const testToolSignal = new AbortController().signal
  23. type Handler = (req: IncomingMessage, res: ServerResponse) => void
  24. let server: Server
  25. let base: string
  26. let handler: Handler
  27. let ctx: Context
  28. let fiber: Awaited<ReturnType<Context['plugin']>>
  29. beforeEach(async () => {
  30. vi.spyOn(publicHttpNetwork, 'resolve').mockResolvedValue([{ address: '127.0.0.1', family: 4 }])
  31. handler = (_req, res) => { res.writeHead(200, { 'content-type': 'text/html' }); res.end('<h1>Hello</h1><p>World</p>') }
  32. server = createServer((req, res) => { handler(req, res) })
  33. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
  34. base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`
  35. ctx = new Context()
  36. await ctx.plugin(SystemPrompt)
  37. await ctx.plugin(ToolRuntime)
  38. await ctx.plugin(WebRuntime, { searchProvider: WebSearchExa.EXA_PROVIDER_ID, fetchProvider: WebFetchLocal.LOCAL_FETCH_PROVIDER_ID })
  39. await ctx.plugin(WebFetchLocal, {})
  40. await ctx.plugin(WebSearchExa, { apiKey: 'exa-key', baseURL: 'https://api.exa.test' })
  41. // The shipped deployment shape: the tool-call budget is declared by tool-web
  42. // config (default 30s, attached as ToolDefinition.timeoutMs) and enforced by
  43. // the zero-config timeout-policy plugin, set above the provider backstop so the
  44. // policy normally wins.
  45. await ctx.plugin(TimeoutPolicy)
  46. fiber = await ctx.plugin(ToolWeb)
  47. })
  48. afterEach(async () => {
  49. await fiber.dispose()
  50. vi.unstubAllGlobals()
  51. vi.restoreAllMocks()
  52. await new Promise<void>(resolve => server.close(() => { resolve() }))
  53. })
  54. let counter = 0
  55. function call(name: string, args: unknown): Promise<ToolExecutionResult> {
  56. return ctx.tools.execute({ signal: testToolSignal, callId: ToolCallId(`call-${++counter}`), name, arguments: args })
  57. }
  58. describe('web_fetch integration over the real backend', () => {
  59. it('fetches an html page and renders it to markdown', async () => {
  60. const out = await call('web_fetch', { url: base })
  61. expect(out.isError).toBe(false)
  62. const text = out.content.map(b => b.type === 'text' ? b.text : '').join('')
  63. expect(text).toContain(`Fetched ${base}`)
  64. expect(text).toContain('# Hello')
  65. expect(text).toContain('World')
  66. })
  67. it('reports a 404 as a result, not an error', async () => {
  68. handler = (_req, res) => { res.writeHead(404, { 'content-type': 'text/plain' }); res.end('missing') }
  69. const out = await call('web_fetch', { url: base })
  70. expect(out.isError).toBe(false)
  71. expect(out.content.map(b => b.type === 'text' ? b.text : '').join('')).toContain('HTTP 404')
  72. })
  73. it('surfaces WEB_INVALID_URL as a structured tool error', async () => {
  74. const out = await call('web_fetch', { url: 'ftp://example.com' })
  75. expect(out.isError).toBe(true)
  76. expect(out.error?.info?.code).toBe('WEB_INVALID_URL')
  77. })
  78. it('surfaces a blocked cross-origin redirect as WEB_REDIRECT_BLOCKED', async () => {
  79. handler = (_req, res) => { res.writeHead(302, { location: 'https://example.com/' }); res.end() }
  80. const out = await call('web_fetch', { url: base })
  81. expect(out.isError).toBe(true)
  82. expect(out.error?.info?.code).toBe('WEB_REDIRECT_BLOCKED')
  83. })
  84. })
  85. describe('web_search integration over the real Exa provider', () => {
  86. it('runs web_search end-to-end and formats the provider result', async () => {
  87. vi.stubGlobal('fetch', vi.fn(async () => new Response(
  88. JSON.stringify({ results: [{ url: 'https://result.test', title: 'Result', highlights: ['a highlight'] }] }),
  89. { status: 200, headers: { 'content-type': 'application/json' } },
  90. )))
  91. const out = await call('web_search', { queries: ['deepseek-official'] })
  92. expect(out.isError).toBe(false)
  93. expect(out.content.map(b => b.type === 'text' ? b.text : '').join('')).toContain('[Result](https://result.test)')
  94. })
  95. })
  96. describe('tool-call timeout policy over the migrated web tools', () => {
  97. it('neither model schema exposes a timeout parameter after the migration', () => {
  98. const byName = new Map(ctx.tools.schemas().map(s => [s.name, s]))
  99. const fetchParams = byName.get('web_fetch')!.parameters as { properties: Record<string, unknown> }
  100. const searchParams = byName.get('web_search')!.parameters as { properties: Record<string, unknown>; required?: string[] }
  101. expect(Object.keys(fetchParams.properties)).toEqual(['url'])
  102. expect('timeout_ms' in fetchParams.properties).toBe(false)
  103. expect(Object.keys(searchParams.properties)).toEqual(['queries'])
  104. expect(searchParams.required).toEqual(['queries'])
  105. })
  106. })
  107. describe('tool-call timeout returns TOOL_TIMEOUT (deadline wins over a slow fetch)', () => {
  108. let slowServer: Server
  109. let slowBase: string
  110. let openSockets: ServerResponse[]
  111. let tctx: Context
  112. let tfiber: Awaited<ReturnType<Context['plugin']>>
  113. beforeEach(async () => {
  114. // A server that never responds: it holds the connection open until the
  115. // client aborts. The cooperative deadline (via exec.signal → the fetch
  116. // provider → undici) is what ends the call.
  117. openSockets = []
  118. slowServer = createServer((_req, res) => { openSockets.push(res) })
  119. await new Promise<void>(resolve => slowServer.listen(0, '127.0.0.1', resolve))
  120. slowBase = `http://127.0.0.1:${(slowServer.address() as AddressInfo).port}`
  121. tctx = new Context()
  122. await tctx.plugin(SystemPrompt)
  123. await tctx.plugin(ToolRuntime)
  124. await tctx.plugin(WebRuntime, { fetchProvider: WebFetchLocal.LOCAL_FETCH_PROVIDER_ID })
  125. // Provider backstop well ABOVE the tool-call budget, so the policy wins.
  126. await tctx.plugin(WebFetchLocal, { timeoutMs: 30_000 })
  127. await tctx.plugin(TimeoutPolicy)
  128. // The tool-call budget is declared by tool-web config, enforced by the policy.
  129. tfiber = await tctx.plugin(ToolWeb, { fetchTimeoutMs: 50 })
  130. })
  131. afterEach(async () => {
  132. for (const res of openSockets) res.destroy()
  133. await tfiber.dispose()
  134. await new Promise<void>(resolve => slowServer.close(() => { resolve() }))
  135. })
  136. it('returns a structured TOOL_TIMEOUT (not the provider WEB_FETCH_TIMEOUT) when the tool-call budget wins', async () => {
  137. const out = await tctx.tools.execute({ signal: testToolSignal, callId: ToolCallId('slow-1'), name: 'web_fetch', arguments: { url: slowBase } })
  138. expect(out.isError).toBe(true)
  139. // The outer tool-call deadline won: TOOL_TIMEOUT, owned by dsh-tool-call-timeout-policy,
  140. // NOT the provider's own WEB_FETCH_TIMEOUT (its 30s backstop never fired).
  141. expect(out.error?.info?.code).toBe('TOOL_TIMEOUT')
  142. const text = out.content.map(b => (b.type === 'text' ? b.text : '')).join('')
  143. expect(text).toContain('timed out after 50ms')
  144. })
  145. it('the provider backstop still protects a direct provider call (no tool-call policy in that path)', async () => {
  146. // A direct provider caller bypasses tools/execute, so a short configured backstop
  147. // must produce provider-owned WEB_FETCH_TIMEOUT rather than TOOL_TIMEOUT.
  148. const direct = new WebFetchLocal.HttpFetchProvider({
  149. maxResponseBytes: 5_000_000,
  150. maxBodyChars: 100_000,
  151. timeoutMs: 50,
  152. maxRedirects: 5,
  153. userAgent: 'integration-test',
  154. })
  155. const err = await direct.fetch({ url: slowBase }).then(
  156. () => undefined,
  157. (e: unknown) => e as { code?: string },
  158. )
  159. expect(err?.code).toBe('WEB_FETCH_TIMEOUT')
  160. })
  161. })