keyless-smoke.e2e.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. import { createServer } from 'node:http'
  2. import { mkdtemp, readFile, readdir, rm } from 'node:fs/promises'
  3. import { tmpdir } from 'node:os'
  4. import { join } from 'node:path'
  5. import { fileURLToPath } from 'node:url'
  6. import { promisify } from 'node:util'
  7. import { zstdDecompress } from 'node:zlib'
  8. import { execa } from 'execa'
  9. import { describe, expect, it } from 'vitest'
  10. const binScript = fileURLToPath(new URL('../../../apps/cli/src/bin.ts', import.meta.url))
  11. const repoRoot = fileURLToPath(new URL('../../..', import.meta.url))
  12. const decompress = promisify(zstdDecompress)
  13. function waitForLine(
  14. lines: string[],
  15. predicate: (value: Record<string, unknown>) => boolean,
  16. stderr: () => string,
  17. ): Promise<Record<string, unknown>> {
  18. return new Promise((resolve, reject) => {
  19. const deadline = Date.now() + 30_000
  20. const poll = (): void => {
  21. while (lines.length > 0) {
  22. const line = lines.shift()!
  23. if (!line.trim()) continue
  24. try {
  25. const value = JSON.parse(line) as Record<string, unknown>
  26. if (predicate(value)) {
  27. resolve(value)
  28. return
  29. }
  30. } catch {
  31. reject(new Error(`non-JSON stdout from JSON-RPC agent runtime: ${line}`))
  32. return
  33. }
  34. }
  35. if (Date.now() >= deadline) {
  36. reject(new Error(`timed out waiting for JSON-RPC response; stderr=${stderr()}`))
  37. return
  38. }
  39. setTimeout(poll, 10)
  40. }
  41. poll()
  42. })
  43. }
  44. describe('Python SDK dsh profile keyless smoke', () => {
  45. it.each([
  46. { label: 'reports max-token turns with the default mapping config', envValue: undefined },
  47. { label: 'reports max-token turns with mapping enabled through env', envValue: 'true' },
  48. { label: 'reports max-token turns with mapping disabled through env', envValue: 'false' },
  49. ])('$label', async ({ envValue }) => {
  50. const root = await mkdtemp(join(tmpdir(), 'dsh-python-sdk-runtime-smoke-'))
  51. const modelRequests: Record<string, unknown>[] = []
  52. const modelServer = createServer((request, response) => {
  53. let body = ''
  54. request.setEncoding('utf8')
  55. request.on('data', (chunk: string) => { body += chunk })
  56. request.on('end', () => {
  57. modelRequests.push(JSON.parse(body) as Record<string, unknown>)
  58. response.writeHead(200, { 'content-type': 'text/event-stream' })
  59. response.write('data: {"choices":[{"delta":{"role":"assistant","content":null}}]}\n\n')
  60. response.write('data: {"choices":[{"delta":{"content":"done"}}]}\n\n')
  61. response.write('data: {"choices":[{"delta":{},"finish_reason":"length"}],"usage":{"prompt_tokens":3,"completion_tokens":1}}\n\n')
  62. response.end('data: [DONE]\n\n')
  63. })
  64. })
  65. await new Promise<void>(resolve => modelServer.listen(0, '127.0.0.1', resolve))
  66. const address = modelServer.address()
  67. if (address === null || typeof address === 'string') throw new Error('model server did not bind a TCP port')
  68. // The line-predicate protocol driving below is the genuinely custom part;
  69. // execa owns spawn, the deadline, and exit settlement around it.
  70. const child = execa(process.execPath, [
  71. '--import',
  72. 'tsx/esm',
  73. binScript,
  74. '--profile',
  75. 'sdk',
  76. ], {
  77. cwd: repoRoot,
  78. env: {
  79. DSH_HOME: join(root, '.dsh'),
  80. DSH_PERMISSION_MODE: 'danger-full-access',
  81. DSH_TELEMETRY_DISABLED: '1',
  82. DEEPSEEK_API_KEY: 'keyless-smoke-no-call',
  83. DEEPSEEK_BASE_URL: `http://127.0.0.1:${address.port}`,
  84. ...(envValue === undefined ? {} : { DSH_MAX_TOKENS_AS_SUCCESS: envValue }),
  85. },
  86. timeout: 35_000,
  87. killSignal: 'SIGKILL',
  88. reject: false,
  89. })
  90. const lines: string[] = []
  91. let stdoutBuffer = ''
  92. let stderr = ''
  93. child.stdout.on('data', (chunk: Buffer) => {
  94. stdoutBuffer += chunk.toString('utf8')
  95. const parts = stdoutBuffer.split('\n')
  96. stdoutBuffer = parts.pop() ?? ''
  97. lines.push(...parts)
  98. })
  99. child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString('utf8') })
  100. try {
  101. child.stdin.write(`${JSON.stringify({
  102. jsonrpc: '2.0',
  103. id: 1,
  104. method: 'initialize',
  105. params: { cwd: root, provider: 'deepseek-official', model: 'deepseek-v4-pro', maxTokens: 1234 },
  106. })}\n`)
  107. const initialized = await waitForLine(lines, value => value.id === 1, () => stderr)
  108. expect(initialized).toMatchObject({
  109. jsonrpc: '2.0',
  110. id: 1,
  111. result: { serverInfo: { name: 'deepseek-harness-sdk-runtime' } },
  112. })
  113. child.stdin.write(`${JSON.stringify({
  114. jsonrpc: '2.0',
  115. id: 2,
  116. method: 'session/prompt',
  117. params: { sessionId: 'main', contentBlocks: [{ type: 'text', text: 'inspect tools' }] },
  118. })}\n`)
  119. const prompt = await waitForLine(lines, value => value.id === 2, () => stderr)
  120. expect(prompt).toMatchObject({
  121. jsonrpc: '2.0',
  122. id: 2,
  123. result: { messageId: expect.any(String) as unknown },
  124. })
  125. const turnEnd = await waitForLine(lines, (value) => {
  126. if (value.method !== 'session.event') return false
  127. const params = value.params as Record<string, unknown> | undefined
  128. const event = params?.event as Record<string, unknown> | undefined
  129. return params?.sessionId === 'main' && event?.type === 'turn/end'
  130. }, () => stderr)
  131. expect(turnEnd).toMatchObject({
  132. jsonrpc: '2.0',
  133. method: 'session.event',
  134. params: {
  135. sessionId: 'main',
  136. event: {
  137. type: 'turn/end',
  138. data: { reason: { kind: 'max-tokens' } },
  139. },
  140. },
  141. })
  142. const tools = modelRequests[0]?.tools as { function?: { name?: string } }[]
  143. expect(modelRequests[0]?.max_tokens).toBe(1234)
  144. expect(tools.map(tool => tool.function?.name)).toContain('list_subagent_models')
  145. child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id: 3, method: 'shutdown' })}\n`)
  146. const shutdown = await waitForLine(lines, value => value.id === 3, () => stderr)
  147. expect(shutdown).toMatchObject({ jsonrpc: '2.0', id: 3, result: {} })
  148. const exit = await child
  149. expect(exit.exitCode, `signal=${String(exit.signal)}; stderr=${stderr}`).toBe(0)
  150. const sessionsRoot = join(root, '.dsh', 'sessions')
  151. const files = await readdir(sessionsRoot, { recursive: true })
  152. const log = files.find(file => file.endsWith('.jsonl.zstd'))
  153. expect(log).toBeDefined()
  154. const compressed = await readFile(join(sessionsRoot, log!))
  155. expect(compressed.subarray(0, 4).toString('hex')).toBe('28b52ffd')
  156. expect(JSON.parse((await decompress(compressed)).toString())).toMatchObject({ type: 'session', id: 'main' })
  157. } finally {
  158. // No-op after exit; reject: false settles on every outcome, so cleanup never races teardown.
  159. child.kill('SIGKILL')
  160. await child
  161. await new Promise<void>(resolve => modelServer.close(() => { resolve() }))
  162. await rm(root, { recursive: true, force: true })
  163. }
  164. }, 40_000)
  165. it('boots the standalone minimal profile with its exact model-facing roster', async () => {
  166. const root = await mkdtemp(join(tmpdir(), 'dsh-python-sdk-minimal-'))
  167. const modelRequests: Record<string, unknown>[] = []
  168. const modelServer = createServer((request, response) => {
  169. let body = ''
  170. request.setEncoding('utf8')
  171. request.on('data', (chunk: string) => { body += chunk })
  172. request.on('end', () => {
  173. modelRequests.push(JSON.parse(body) as Record<string, unknown>)
  174. response.writeHead(200, { 'content-type': 'text/event-stream' })
  175. response.write('data: {"choices":[{"delta":{"role":"assistant","content":null}}]}\n\n')
  176. response.write('data: {"choices":[{"delta":{"content":"done"}}]}\n\n')
  177. response.write('data: {"choices":[{"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1}}\n\n')
  178. response.end('data: [DONE]\n\n')
  179. })
  180. })
  181. await new Promise<void>(resolve => modelServer.listen(0, '127.0.0.1', resolve))
  182. const address = modelServer.address()
  183. if (address === null || typeof address === 'string') throw new Error('model server did not bind a TCP port')
  184. const child = execa(process.execPath, [
  185. '--import',
  186. 'tsx/esm',
  187. binScript,
  188. '--profile',
  189. 'sdk-minimal',
  190. ], {
  191. cwd: repoRoot,
  192. env: {
  193. DSH_HOME: join(root, '.dsh'),
  194. DSH_SYSTEM_PROMPT: 'Minimal allowlist prompt.',
  195. DEEPSEEK_API_KEY: 'keyless-smoke-no-call',
  196. DEEPSEEK_BASE_URL: `http://127.0.0.1:${address.port}`,
  197. },
  198. timeout: 35_000,
  199. killSignal: 'SIGKILL',
  200. reject: false,
  201. })
  202. const lines: string[] = []
  203. let stdoutBuffer = ''
  204. let stderr = ''
  205. child.stdout.on('data', (chunk: Buffer) => {
  206. stdoutBuffer += chunk.toString('utf8')
  207. const parts = stdoutBuffer.split('\n')
  208. stdoutBuffer = parts.pop() ?? ''
  209. lines.push(...parts)
  210. })
  211. child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString('utf8') })
  212. try {
  213. child.stdin.write(`${JSON.stringify({
  214. jsonrpc: '2.0',
  215. id: 1,
  216. method: 'initialize',
  217. params: { cwd: root, provider: 'deepseek-official', model: 'deepseek-v4-pro' },
  218. })}\n`)
  219. await waitForLine(lines, value => value.id === 1, () => stderr)
  220. child.stdin.write(`${JSON.stringify({
  221. jsonrpc: '2.0',
  222. id: 2,
  223. method: 'session/prompt',
  224. params: { sessionId: 'minimal', contentBlocks: [{ type: 'text', text: 'inspect tools' }] },
  225. })}\n`)
  226. await waitForLine(lines, (value) => {
  227. const params = value.params as Record<string, unknown> | undefined
  228. const event = params?.event as Record<string, unknown> | undefined
  229. return params?.sessionId === 'minimal' && event?.type === 'turn/end'
  230. }, () => stderr)
  231. const request = modelRequests[0] as {
  232. messages?: Array<{ role?: string; content?: unknown }>
  233. tools?: Array<{ function?: { name?: string } }>
  234. }
  235. expect(request.messages?.[0]).toMatchObject({ role: 'system', content: 'Minimal allowlist prompt.' })
  236. const shellTool = process.platform === 'win32' ? 'pwsh' : 'bash'
  237. expect(request.tools?.map(tool => tool.function?.name).sort()).toEqual([shellTool, 'str_replace_editor'].sort())
  238. const profile = JSON.parse(
  239. await readFile(join(root, '.dsh', 'profiles', 'sdk-minimal', 'package.json'), 'utf8'),
  240. ) as { dsh?: { profile?: { bundles?: string[]; patchReload?: string } } }
  241. expect(profile.dsh?.profile).toEqual({
  242. bundles: ['@deepseek-ai/dsh-sdk-minimal'],
  243. patchReload: 'startup',
  244. })
  245. child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id: 3, method: 'shutdown' })}\n`)
  246. await waitForLine(lines, value => value.id === 3, () => stderr)
  247. const exit = await child
  248. expect(exit.exitCode, `signal=${String(exit.signal)}; stderr=${stderr}`).toBe(0)
  249. } finally {
  250. child.kill('SIGKILL')
  251. await child
  252. await new Promise<void>(resolve => modelServer.close(() => { resolve() }))
  253. await rm(root, { recursive: true, force: true })
  254. }
  255. }, 40_000)
  256. it('rejects an invalid max-token success env value', async () => {
  257. const root = await mkdtemp(join(tmpdir(), 'dsh-python-sdk-runtime-invalid-'))
  258. try {
  259. const { exitCode, stdout, stderr } = await execa(process.execPath, [
  260. '--import',
  261. 'tsx/esm',
  262. binScript,
  263. '--profile',
  264. 'sdk',
  265. ], {
  266. cwd: repoRoot,
  267. env: {
  268. DSH_HOME: join(root, '.dsh'),
  269. DEEPSEEK_API_KEY: 'keyless-smoke-no-call',
  270. DSH_MAX_TOKENS_AS_SUCCESS: 'sometimes',
  271. },
  272. stdin: 'ignore',
  273. timeout: 25_000,
  274. killSignal: 'SIGKILL',
  275. reject: false,
  276. })
  277. expect(exitCode, stderr).toBe(1)
  278. expect(stdout).toBe('')
  279. expect(stderr).toContain('plugin tree failed to load')
  280. expect(stderr).toContain('failed to apply loader entry sdk-jsonrpc-server (@deepseek-ai/dsh-sdk-jsonrpc-server)')
  281. expect(stderr).toContain('sometimes')
  282. } finally {
  283. await rm(root, { recursive: true, force: true })
  284. }
  285. }, 30_000)
  286. })