keyless-smoke.e2e.ts 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. import { spawn } from 'node:child_process'
  2. import { createServer } from 'node:http'
  3. import { mkdtemp, readFile, readdir, rm } from 'node:fs/promises'
  4. import { tmpdir } from 'node:os'
  5. import { join } from 'node:path'
  6. import { fileURLToPath } from 'node:url'
  7. import { promisify } from 'node:util'
  8. import { zstdDecompress } from 'node:zlib'
  9. import { describe, expect, it } from 'vitest'
  10. const binScript = fileURLToPath(new URL('../../../packages/examples/jsonrpc-demo/src/bin.ts', import.meta.url))
  11. const configPath = fileURLToPath(new URL('../cordis.yml', import.meta.url))
  12. const repoRoot = fileURLToPath(new URL('../../..', import.meta.url))
  13. const decompress = promisify(zstdDecompress)
  14. function waitForLine(
  15. lines: string[],
  16. predicate: (value: Record<string, unknown>) => boolean,
  17. stderr: () => string,
  18. ): Promise<Record<string, unknown>> {
  19. return new Promise((resolve, reject) => {
  20. const deadline = Date.now() + 30_000
  21. const poll = (): void => {
  22. while (lines.length > 0) {
  23. const line = lines.shift()!
  24. if (!line.trim()) continue
  25. try {
  26. const value = JSON.parse(line) as Record<string, unknown>
  27. if (predicate(value)) {
  28. resolve(value)
  29. return
  30. }
  31. } catch {
  32. reject(new Error(`non-JSON stdout from JSON-RPC agent runtime: ${line}`))
  33. return
  34. }
  35. }
  36. if (Date.now() >= deadline) {
  37. reject(new Error(`timed out waiting for JSON-RPC response; stderr=${stderr()}`))
  38. return
  39. }
  40. setTimeout(poll, 10)
  41. }
  42. poll()
  43. })
  44. }
  45. describe('jsonrpc-agent keyless smoke', () => {
  46. it.each([
  47. { label: 'accepts max-token results by default', envValue: undefined, expectedStatus: 'ok' },
  48. { label: 'accepts max-token results when enabled through env', envValue: 'true', expectedStatus: 'ok' },
  49. { label: 'reports max-token results as errors when disabled through env', envValue: 'false', expectedStatus: 'error' },
  50. ])('$label', async ({ envValue, expectedStatus }) => {
  51. const root = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-agent-smoke-'))
  52. const modelRequests: Record<string, unknown>[] = []
  53. const modelServer = createServer((request, response) => {
  54. let body = ''
  55. request.setEncoding('utf8')
  56. request.on('data', (chunk: string) => { body += chunk })
  57. request.on('end', () => {
  58. modelRequests.push(JSON.parse(body) as Record<string, unknown>)
  59. response.writeHead(200, { 'content-type': 'text/event-stream' })
  60. response.write('data: {"choices":[{"delta":{"role":"assistant","content":null}}]}\n\n')
  61. response.write('data: {"choices":[{"delta":{"content":"done"}}]}\n\n')
  62. response.write('data: {"choices":[{"delta":{},"finish_reason":"length"}],"usage":{"prompt_tokens":3,"completion_tokens":1}}\n\n')
  63. response.end('data: [DONE]\n\n')
  64. })
  65. })
  66. await new Promise<void>(resolve => modelServer.listen(0, '127.0.0.1', resolve))
  67. const address = modelServer.address()
  68. if (address === null || typeof address === 'string') throw new Error('model server did not bind a TCP port')
  69. const child = spawn(process.execPath, [
  70. '--import',
  71. 'tsx',
  72. binScript,
  73. configPath,
  74. ], {
  75. cwd: repoRoot,
  76. env: {
  77. ...process.env,
  78. DEEPSEEK_API_KEY: 'keyless-smoke-no-call',
  79. DEEPSEEK_BASE_URL: `http://127.0.0.1:${address.port}`,
  80. DSH_CWD: root,
  81. DSH_SESSION_ROOT: join(root, '.sessions'),
  82. ...(envValue === undefined ? {} : { DSH_MAX_TOKENS_AS_SUCCESS: envValue }),
  83. },
  84. stdio: ['pipe', 'pipe', 'pipe'],
  85. })
  86. const lines: string[] = []
  87. let stdoutBuffer = ''
  88. let stderr = ''
  89. child.stdout.setEncoding('utf8')
  90. child.stdout.on('data', (chunk: string) => {
  91. stdoutBuffer += chunk
  92. const parts = stdoutBuffer.split('\n')
  93. stdoutBuffer = parts.pop() ?? ''
  94. lines.push(...parts)
  95. })
  96. child.stderr.setEncoding('utf8')
  97. child.stderr.on('data', (chunk: string) => { stderr += chunk })
  98. try {
  99. child.stdin.write(`${JSON.stringify({
  100. jsonrpc: '2.0',
  101. id: 1,
  102. method: 'initialize',
  103. params: { cwd: root, provider: 'deepseek', model: 'deepseek-v4-pro' },
  104. })}\n`)
  105. const initialized = await waitForLine(lines, value => value.id === 1, () => stderr)
  106. expect(initialized).toMatchObject({
  107. jsonrpc: '2.0',
  108. id: 1,
  109. result: { serverInfo: { name: 'deepseek-harness-sdk-runtime' } },
  110. })
  111. child.stdin.write(`${JSON.stringify({
  112. jsonrpc: '2.0',
  113. id: 2,
  114. method: 'session/prompt',
  115. params: { sessionId: 'main', contentBlocks: [{ type: 'text', text: 'inspect tools' }] },
  116. })}\n`)
  117. const finished = await waitForLine(lines, value => value.method === 'session.finished', () => stderr)
  118. expect(finished).toMatchObject({
  119. jsonrpc: '2.0',
  120. method: 'session.finished',
  121. params: {
  122. sessionId: 'main',
  123. status: expectedStatus,
  124. reason: { kind: 'max-tokens' },
  125. },
  126. })
  127. const prompt = await waitForLine(lines, value => value.id === 2, () => stderr)
  128. expect(prompt).toMatchObject({ jsonrpc: '2.0', id: 2, result: { accepted: true } })
  129. const tools = modelRequests[0]?.tools as { function?: { name?: string } }[]
  130. expect(tools.map(tool => tool.function?.name).sort()).toEqual([
  131. 'bash',
  132. 'edit',
  133. 'read',
  134. 'subagent',
  135. 'todo_write',
  136. 'write',
  137. ])
  138. child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id: 3, method: 'shutdown' })}\n`)
  139. const shutdown = await waitForLine(lines, value => value.id === 3, () => stderr)
  140. expect(shutdown).toMatchObject({ jsonrpc: '2.0', id: 3, result: {} })
  141. if (child.exitCode === null) {
  142. await new Promise<void>((resolve, reject) => {
  143. child.once('exit', (code) => {
  144. if (code === 0) resolve()
  145. else reject(new Error(`runtime exited ${code}; stderr=${stderr}`))
  146. })
  147. })
  148. } else {
  149. expect(child.exitCode, stderr).toBe(0)
  150. }
  151. const sessionsRoot = join(root, '.sessions')
  152. const files = await readdir(sessionsRoot, { recursive: true })
  153. const log = files.find(file => file.endsWith('.jsonl.zstd'))
  154. expect(log).toBeDefined()
  155. const compressed = await readFile(join(sessionsRoot, log!))
  156. expect(compressed.subarray(0, 4).toString('hex')).toBe('28b52ffd')
  157. expect(JSON.parse((await decompress(compressed)).toString())).toMatchObject({ type: 'session', id: 'main' })
  158. } finally {
  159. if (child.exitCode === null) child.kill('SIGKILL')
  160. await new Promise<void>(resolve => modelServer.close(() => { resolve() }))
  161. await rm(root, { recursive: true, force: true })
  162. }
  163. }, 40_000)
  164. it('rejects an invalid max-token success env value', async () => {
  165. const child = spawn(process.execPath, [
  166. '--import',
  167. 'tsx',
  168. binScript,
  169. configPath,
  170. ], {
  171. cwd: repoRoot,
  172. env: {
  173. ...process.env,
  174. DEEPSEEK_API_KEY: 'keyless-smoke-no-call',
  175. DSH_MAX_TOKENS_AS_SUCCESS: 'sometimes',
  176. },
  177. stdio: ['ignore', 'pipe', 'pipe'],
  178. })
  179. let stdout = ''
  180. let stderr = ''
  181. child.stdout.setEncoding('utf8')
  182. child.stdout.on('data', (chunk: string) => { stdout += chunk })
  183. child.stderr.setEncoding('utf8')
  184. child.stderr.on('data', (chunk: string) => { stderr += chunk })
  185. const exitCode = await new Promise<number | null>((resolve, reject) => {
  186. child.once('error', reject)
  187. child.once('exit', resolve)
  188. })
  189. expect(exitCode, stderr).toBe(1)
  190. expect(stdout).toBe('')
  191. expect(stderr).toContain('plugin(s) failed to load: @deepseek-ai/dsh-jsonrpc')
  192. }, 10_000)
  193. })