integration.spec.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. /**
  2. * Integration: the real fetch backend (`dsh-web-fetch-local`) + 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-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 'cordis'
  12. import { CallId } from '@deepseek-ai/dsh-llm'
  13. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  14. import ToolRegistry from '@deepseek-ai/dsh-tools'
  15. import WebService from '@deepseek-ai/dsh-web'
  16. import * as WebFetchLocal from '@deepseek-ai/dsh-web-fetch-local'
  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-timeout-policy'
  20. type Handler = (req: IncomingMessage, res: ServerResponse) => void
  21. let server: Server
  22. let base: string
  23. let handler: Handler
  24. let ctx: Context
  25. let fiber: Awaited<ReturnType<Context['plugin']>>
  26. beforeEach(async () => {
  27. handler = (_req, res) => { res.writeHead(200, { 'content-type': 'text/html' }); res.end('<h1>Hello</h1><p>World</p>') }
  28. server = createServer((req, res) => { handler(req, res) })
  29. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
  30. base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`
  31. ctx = new Context()
  32. await ctx.plugin(SystemPrompt)
  33. await ctx.plugin(ToolRegistry)
  34. await ctx.plugin(WebService, { searchProvider: WebSearchExa.EXA_PROVIDER_ID, fetchProvider: WebFetchLocal.LOCAL_FETCH_PROVIDER_ID })
  35. await ctx.plugin(WebFetchLocal, {})
  36. await ctx.plugin(WebSearchExa, { apiKey: 'exa-key', baseURL: 'https://api.exa.test' })
  37. // The shipped deployment shape: the tool-call budget is declared by tool-web
  38. // config (default 30s, attached as ToolDefinition.timeoutMs) and enforced by
  39. // the zero-config timeout-policy plugin, set above the provider backstop so the
  40. // policy normally wins.
  41. await ctx.plugin(TimeoutPolicy)
  42. fiber = await ctx.plugin(ToolWeb)
  43. })
  44. afterEach(async () => {
  45. await fiber.dispose()
  46. vi.unstubAllGlobals()
  47. await new Promise<void>(resolve => server.close(() => { resolve() }))
  48. })
  49. let counter = 0
  50. type ToolResult = { isError: boolean; content: { type: string; text?: string }[]; error?: { code: string } }
  51. function call(name: string, args: unknown): Promise<ToolResult> {
  52. return ctx.tools.execute({ 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.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.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?.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?.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', { query: 'deepseek' })
  88. expect(out.isError).toBe(false)
  89. expect(out.content.map(b => 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> }
  97. expect(Object.keys(fetchParams.properties)).toEqual(['url'])
  98. expect('timeout_ms' in fetchParams.properties).toBe(false)
  99. expect(Object.keys(searchParams.properties)).toEqual(['query'])
  100. })
  101. })
  102. describe('tool-call timeout returns TOOL_TIMEOUT (deadline wins over a slow fetch)', () => {
  103. let slowServer: Server
  104. let slowBase: string
  105. let openSockets: ServerResponse[]
  106. let tctx: Context
  107. let tfiber: Awaited<ReturnType<Context['plugin']>>
  108. beforeEach(async () => {
  109. // A server that never responds: it holds the connection open until the
  110. // client aborts. The cooperative deadline (via exec.signal → the fetch
  111. // provider → undici) is what ends the call.
  112. openSockets = []
  113. slowServer = createServer((_req, res) => { openSockets.push(res) })
  114. await new Promise<void>(resolve => slowServer.listen(0, '127.0.0.1', resolve))
  115. slowBase = `http://127.0.0.1:${(slowServer.address() as AddressInfo).port}`
  116. tctx = new Context()
  117. await tctx.plugin(SystemPrompt)
  118. await tctx.plugin(ToolRegistry)
  119. await tctx.plugin(WebService, { fetchProvider: WebFetchLocal.LOCAL_FETCH_PROVIDER_ID })
  120. // Provider backstop well ABOVE the tool-call budget, so the policy wins.
  121. await tctx.plugin(WebFetchLocal, { timeoutMs: 30_000 })
  122. await tctx.plugin(TimeoutPolicy)
  123. // The tool-call budget is declared by tool-web config, enforced by the policy.
  124. tfiber = await tctx.plugin(ToolWeb, { fetchTimeoutMs: 50 })
  125. })
  126. afterEach(async () => {
  127. for (const res of openSockets) res.destroy()
  128. await tfiber.dispose()
  129. await new Promise<void>(resolve => slowServer.close(() => { resolve() }))
  130. })
  131. it('returns a structured TOOL_TIMEOUT (not the provider WEB_FETCH_TIMEOUT) when the tool-call budget wins', async () => {
  132. const out = await tctx.tools.execute({ callId: CallId('slow-1'), name: 'web_fetch', arguments: { url: slowBase } })
  133. expect(out.isError).toBe(true)
  134. // The outer tool-call deadline won: TOOL_TIMEOUT, owned by dsh-timeout-policy,
  135. // NOT the provider's own WEB_FETCH_TIMEOUT (its 30s backstop never fired).
  136. expect(out.error?.code).toBe('TOOL_TIMEOUT')
  137. const text = out.content.map(b => (b.type === 'text' ? b.text : '')).join('')
  138. expect(text).toContain('timed out after 50ms')
  139. })
  140. it('the provider backstop still protects a direct provider call (no tool-call policy in that path)', async () => {
  141. // A direct provider caller bypasses tools/execute, so a short configured backstop
  142. // must produce provider-owned WEB_FETCH_TIMEOUT rather than TOOL_TIMEOUT.
  143. const direct = new WebFetchLocal.LocalFetchProvider({
  144. maxUrlLength: 2048,
  145. maxResponseBytes: 5_000_000,
  146. maxBodyChars: 100_000,
  147. timeoutMs: 50,
  148. maxRedirects: 5,
  149. userAgent: 'integration-test',
  150. })
  151. const err = await direct.fetch({ url: slowBase }).then(
  152. () => undefined,
  153. (e: unknown) => e as { code?: string },
  154. )
  155. expect(err?.code).toBe('WEB_FETCH_TIMEOUT')
  156. })
  157. })