integration.spec.ts 8.2 KB

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