plugin-apply.spec.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. import { createServer } from 'node:http'
  2. import type { IncomingMessage, Server, ServerResponse } from 'node:http'
  3. import { mkdtemp, rm } from 'node:fs/promises'
  4. import { join } from 'node:path'
  5. import { tmpdir } from 'node:os'
  6. import { PassThrough, Writable } from 'node:stream'
  7. import { afterEach, describe, expect, it, vi } from 'vitest'
  8. import { Context } from 'cordis'
  9. import * as agentCore from '@deepseek-ai/dsh-agent-spine-demo'
  10. import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl'
  11. import * as jsonrpc from '../src/index.ts'
  12. /**
  13. * Mount the real namespace plugin with in-memory stdio and exit seams. Covers
  14. * the full transport/server path, response-before-exit shutdown exactly once,
  15. * and bare-fiber disposal without process exit.
  16. */
  17. /** One ordered frame, write completion, or exit observation. */
  18. type WireEvent =
  19. | { kind: 'frame'; frame: Record<string, unknown> }
  20. | { kind: 'write-complete'; ids: (string | number)[] }
  21. | { kind: 'exit'; code: number }
  22. interface ApplyHarness {
  23. ctx: Context
  24. /** The plugin fiber used by the bare-dispose case. */
  25. fiber: Awaited<ReturnType<Context['plugin']>>
  26. /** Frames, write completions, and exits in observation order. */
  27. events: WireEvent[]
  28. outputErrors: Error[]
  29. send(frame: Record<string, unknown>): void
  30. sendRaw(text: string): void
  31. frames(): Record<string, unknown>[]
  32. exits(): number[]
  33. waitForFrame(predicate: (frame: Record<string, unknown>) => boolean, description: string): Promise<Record<string, unknown>>
  34. dispose(): Promise<void>
  35. }
  36. /** Poll asynchronous output for up to five seconds. */
  37. async function waitFor<T>(get: () => T | undefined, description: string): Promise<T> {
  38. const deadline = Date.now() + 5000
  39. for (;;) {
  40. const value = get()
  41. if (value !== undefined) return value
  42. if (Date.now() > deadline) throw new Error(`timed out waiting for ${description}`)
  43. await new Promise(resolve => setTimeout(resolve, 5))
  44. }
  45. }
  46. /** Drain asynchronous work before a negative assertion. */
  47. async function settle(): Promise<void> {
  48. await new Promise(resolve => setTimeout(resolve, 25))
  49. }
  50. /** Mount the real plugin on a minimal harness with in-memory stdio and exit. */
  51. async function mountPlugin(
  52. storageDir: string,
  53. options: { writeDelayMs?: number; failFlush?: boolean } = {},
  54. ): Promise<ApplyHarness> {
  55. const ctx = new Context()
  56. await ctx.plugin(agentCore, { workspaceContext: false })
  57. await ctx.plugin(SessionPersistenceJsonl, { root: storageDir })
  58. await new Promise(resolve => setTimeout(resolve, 50))
  59. const input = new PassThrough()
  60. const events: WireEvent[] = []
  61. const outputErrors: Error[] = []
  62. let pendingOutput = ''
  63. // Record frame admission separately from write completion so delayed output
  64. // tests the flush barrier.
  65. const output = new Writable({
  66. write(chunk: Buffer, _encoding, callback) {
  67. const ids: (string | number)[] = []
  68. pendingOutput += chunk.toString('utf8')
  69. for (;;) {
  70. const newline = pendingOutput.indexOf('\n')
  71. if (newline < 0) break
  72. const line = pendingOutput.slice(0, newline).trim()
  73. pendingOutput = pendingOutput.slice(newline + 1)
  74. if (line) {
  75. const frame = JSON.parse(line) as Record<string, unknown>
  76. events.push({ kind: 'frame', frame })
  77. if (typeof frame.id === 'string' || typeof frame.id === 'number') ids.push(frame.id)
  78. }
  79. }
  80. const complete = (): void => {
  81. if (options.failFlush === true && chunk.length === 0) {
  82. callback(new Error('flush callback failed'))
  83. return
  84. }
  85. events.push({ kind: 'write-complete', ids })
  86. callback()
  87. }
  88. if ((options.writeDelayMs ?? 0) > 0) setTimeout(complete, options.writeDelayMs)
  89. else complete()
  90. },
  91. })
  92. output.on('error', (error: Error) => { outputErrors.push(error) })
  93. const exit = (code: number): void => { events.push({ kind: 'exit', code }) }
  94. const fiber = await ctx.plugin(jsonrpc, { input, output, exit })
  95. const frames = (): Record<string, unknown>[] =>
  96. events.flatMap(event => event.kind === 'frame' ? [event.frame] : [])
  97. return {
  98. ctx,
  99. fiber,
  100. events,
  101. outputErrors,
  102. send: (frame) => { input.write(`${JSON.stringify(frame)}\n`) },
  103. sendRaw: (text) => { input.write(text) },
  104. frames,
  105. exits: () => events.flatMap(event => event.kind === 'exit' ? [event.code] : []),
  106. waitForFrame: (predicate, description) => waitFor(() => frames().find(predicate), description),
  107. dispose: async () => { await ctx.fiber.dispose() },
  108. }
  109. }
  110. const servers: Server[] = []
  111. afterEach(async () => {
  112. await Promise.all(servers.splice(0).map(server => new Promise(resolve => server.close(resolve))))
  113. vi.unstubAllEnvs()
  114. })
  115. /** Keyless SSE endpoint for completing a prompt turn. */
  116. async function mockCompletionServer(): Promise<{ url: string; requests: unknown[] }> {
  117. const requests: unknown[] = []
  118. const server = createServer((request: IncomingMessage, response: ServerResponse) => {
  119. let body = ''
  120. request.on('data', (chunk: Buffer) => { body += chunk.toString('utf8') })
  121. request.on('end', () => {
  122. requests.push(JSON.parse(body))
  123. response.writeHead(200, { 'content-type': 'text/event-stream' })
  124. response.write('data: {"choices":[{"delta":{"role":"assistant","content":null,"reasoning_content":""}}]}\n\n')
  125. response.write('data: {"choices":[{"delta":{"content":"done"}}]}\n\n')
  126. response.write('data: {"choices":[{"delta":{"content":""},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1}}\n\n')
  127. response.write('data: [DONE]\n\n')
  128. response.end()
  129. })
  130. })
  131. servers.push(server)
  132. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
  133. const address = server.address()
  134. if (address === null || typeof address === 'string') throw new Error('no port')
  135. return { url: `http://127.0.0.1:${address.port}`, requests }
  136. }
  137. describe('dsh-jsonrpc plugin apply', () => {
  138. it('serves initialize over the injected stdio pair', async () => {
  139. const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-apply-init-'))
  140. vi.stubEnv('DEEPSEEK_API_KEY', 'test-key')
  141. const harness = await mountPlugin(storageDir)
  142. try {
  143. harness.send({ jsonrpc: '2.0', id: 'init-1', method: 'initialize', params: { cwd: storageDir, provider: 'deepseek', model: 'apply-model' } })
  144. const response = await harness.waitForFrame(frame => frame.id === 'init-1', 'initialize response')
  145. expect(response).toEqual({
  146. jsonrpc: '2.0',
  147. id: 'init-1',
  148. result: { serverInfo: { name: 'deepseek-harness-sdk-runtime', version: '0.0.1' } },
  149. })
  150. expect(harness.exits()).toEqual([])
  151. } finally {
  152. await harness.dispose()
  153. await rm(storageDir, { recursive: true, force: true })
  154. }
  155. })
  156. it('drives a session/prompt turn end-to-end and forwards session notifications as output frames', async () => {
  157. const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-apply-prompt-'))
  158. const llmServer = await mockCompletionServer()
  159. vi.stubEnv('DEEPSEEK_API_KEY', 'test-key')
  160. vi.stubEnv('DEEPSEEK_BASE_URL', llmServer.url)
  161. const harness = await mountPlugin(storageDir)
  162. try {
  163. harness.send({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { cwd: storageDir, provider: 'deepseek', model: 'dsagent-model' } })
  164. await harness.waitForFrame(frame => frame.id === 1, 'initialize response')
  165. harness.send({
  166. jsonrpc: '2.0',
  167. id: 2,
  168. method: 'session/prompt',
  169. params: { sessionId: 'main', contentBlocks: [{ type: 'text', text: 'fix it' }] },
  170. })
  171. const response = await harness.waitForFrame(frame => frame.id === 2, 'prompt response')
  172. expect(response.result).toEqual({ accepted: true })
  173. expect(llmServer.requests).toHaveLength(1)
  174. const body = llmServer.requests[0] as { model: string; messages: { role: string }[] }
  175. expect(body.model).toBe('dsagent-model')
  176. expect(body.messages.at(-1)?.role).toBe('user')
  177. // Notifications use the same transport and arrive as id-less frames.
  178. const notifications = harness.frames().filter(frame => frame.id === undefined)
  179. expect(notifications.some(frame => frame.method === 'session.event')).toBe(true)
  180. expect(notifications.find(frame => frame.method === 'session.finished')).toMatchObject({
  181. jsonrpc: '2.0',
  182. params: { sessionId: 'main', status: 'ok' },
  183. })
  184. } finally {
  185. await harness.dispose()
  186. await rm(storageDir, { recursive: true, force: true })
  187. }
  188. })
  189. it('answers shutdown before exiting 0 exactly once, even against a racing second shutdown', async () => {
  190. const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-apply-shutdown-'))
  191. const harness = await mountPlugin(storageDir, { writeDelayMs: 10 })
  192. try {
  193. // One chunk makes the two deferred exit callbacks race.
  194. const first = { jsonrpc: '2.0', id: 'sd-1', method: 'shutdown' }
  195. const second = { jsonrpc: '2.0', id: 'sd-2', method: 'shutdown' }
  196. harness.sendRaw(`${JSON.stringify(first)}\n${JSON.stringify(second)}\n`)
  197. await waitFor(() => harness.exits().length > 0 ? true : undefined, 'exit recorder call')
  198. expect(harness.exits()).toEqual([0])
  199. // Both response writes and the flush barrier complete before exit.
  200. const exitIndex = harness.events.findIndex(event => event.kind === 'exit')
  201. const firstResponse = harness.events.findIndex(event => event.kind === 'frame' && event.frame.id === 'sd-1')
  202. const secondResponse = harness.events.findIndex(event => event.kind === 'frame' && event.frame.id === 'sd-2')
  203. const firstComplete = harness.events.findIndex(event => event.kind === 'write-complete' && event.ids.includes('sd-1'))
  204. const secondComplete = harness.events.findIndex(event => event.kind === 'write-complete' && event.ids.includes('sd-2'))
  205. const flushComplete = harness.events.findIndex(event => event.kind === 'write-complete' && event.ids.length === 0)
  206. expect(firstResponse).toBeGreaterThanOrEqual(0)
  207. expect(secondResponse).toBeGreaterThanOrEqual(0)
  208. expect(firstComplete).toBeGreaterThan(firstResponse)
  209. expect(secondComplete).toBeGreaterThan(secondResponse)
  210. expect(flushComplete).toBeGreaterThan(firstComplete)
  211. expect(flushComplete).toBeGreaterThan(secondComplete)
  212. expect(exitIndex).toBeGreaterThan(flushComplete)
  213. await settle()
  214. expect(harness.exits()).toEqual([0])
  215. const before = harness.frames().length
  216. harness.send({ jsonrpc: '2.0', id: 'after-exit', method: 'initialize', params: { cwd: storageDir, provider: 'deepseek', model: 'x' } })
  217. await settle()
  218. expect(harness.frames().length).toBe(before)
  219. } finally {
  220. await harness.dispose()
  221. await rm(storageDir, { recursive: true, force: true })
  222. }
  223. })
  224. it('still disposes and exits once when the flush callback fails', async () => {
  225. const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-apply-flush-failure-'))
  226. const harness = await mountPlugin(storageDir, { failFlush: true })
  227. try {
  228. harness.send({ jsonrpc: '2.0', id: 'sd-fail', method: 'shutdown' })
  229. await waitFor(() => harness.exits().length > 0 ? true : undefined, 'exit after flush failure')
  230. await settle()
  231. expect(harness.exits()).toEqual([0])
  232. expect(harness.outputErrors.map(error => error.message)).toEqual(['flush callback failed'])
  233. const before = harness.frames().length
  234. harness.send({ jsonrpc: '2.0', id: 'after-flush-failure', method: 'initialize', params: { cwd: storageDir, provider: 'deepseek', model: 'x' } })
  235. await settle()
  236. expect(harness.frames().length).toBe(before)
  237. } finally {
  238. await harness.dispose()
  239. await rm(storageDir, { recursive: true, force: true })
  240. }
  241. })
  242. it('stops serving on a bare fiber dispose (HMR-style unload) without calling exit', async () => {
  243. const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-apply-dispose-'))
  244. const harness = await mountPlugin(storageDir)
  245. try {
  246. // Prove the handler-rejection path is live before disposal.
  247. harness.send({ jsonrpc: '2.0', id: 'probe-1', method: 'nope/unknown' })
  248. const error = await harness.waitForFrame(frame => frame.id === 'probe-1', 'error response for unknown method')
  249. expect(error.error).toMatchObject({
  250. code: -32603,
  251. message: 'unknown DeepSeek Harness SDK runtime method: nope/unknown',
  252. })
  253. await harness.fiber.dispose()
  254. const before = harness.frames().length
  255. harness.send({ jsonrpc: '2.0', id: 'probe-2', method: 'initialize', params: { cwd: storageDir, provider: 'deepseek', model: 'x' } })
  256. await settle()
  257. expect(harness.frames().length).toBe(before)
  258. expect(harness.exits()).toEqual([])
  259. } finally {
  260. await harness.dispose()
  261. await rm(storageDir, { recursive: true, force: true })
  262. }
  263. })
  264. })