plugin-apply.spec.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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-core'
  10. import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl'
  11. import * as jsonrpc from '../src/index.ts'
  12. /**
  13. * apply()-level lifecycle coverage for the @deepseek-ai/dsh-jsonrpc plugin:
  14. * the plugin is mounted through the REAL namespace mount path —
  15. * `ctx.plugin(jsonrpc, config)` over the module namespace object, exactly what
  16. * the Loader hands cordis after `unwrapExports` (plugin-shape.spec pins that
  17. * identity) — with the runtime-only `input`/`output`/`exit` seams from
  18. * {@link jsonrpc.JsonRpcConfig} replacing the process stdio, so the whole
  19. * pipeline (line transport → HarnessSdkServer → notifications back onto the
  20. * wire) runs in-process. The scenarios pin the plugin's exit-lifecycle split:
  21. * a `shutdown` REQUEST answers first, then disposes the plugin's own fiber and
  22. * calls `exit(0)` exactly once (a racing second `shutdown` must not re-exit);
  23. * a bare fiber dispose (HMR-style unload, no request) only stops serving and
  24. * never touches `exit`.
  25. */
  26. /** One ordered observation on the plugin's outward-facing seams: a JSON-RPC frame written to `output`, or an `exit(code)` call. */
  27. type WireEvent =
  28. | { kind: 'frame'; frame: Record<string, unknown> }
  29. | { kind: 'write-complete'; ids: (string | number)[] }
  30. | { kind: 'exit'; code: number }
  31. interface ApplyHarness {
  32. ctx: Context
  33. /** The jsonrpc plugin's own fiber (NOT the root), for the HMR-style dispose scenario. */
  34. fiber: Awaited<ReturnType<Context['plugin']>>
  35. /** Every output frame and exit call, in observation order — ordering assertions read this. */
  36. events: WireEvent[]
  37. outputErrors: Error[]
  38. send(frame: Record<string, unknown>): void
  39. sendRaw(text: string): void
  40. frames(): Record<string, unknown>[]
  41. exits(): number[]
  42. waitForFrame(predicate: (frame: Record<string, unknown>) => boolean, description: string): Promise<Record<string, unknown>>
  43. dispose(): Promise<void>
  44. }
  45. /** Poll `get` until it yields a value (5s cap) — the output side is fed asynchronously from the transport's read loop. */
  46. async function waitFor<T>(get: () => T | undefined, description: string): Promise<T> {
  47. const deadline = Date.now() + 5000
  48. for (;;) {
  49. const value = get()
  50. if (value !== undefined) return value
  51. if (Date.now() > deadline) throw new Error(`timed out waiting for ${description}`)
  52. await new Promise(resolve => setTimeout(resolve, 5))
  53. }
  54. }
  55. /** Let pending microtasks, setImmediate callbacks, and stream events drain — for asserting that something did NOT happen. */
  56. async function settle(): Promise<void> {
  57. await new Promise(resolve => setTimeout(resolve, 25))
  58. }
  59. /**
  60. * Boot a minimal harness context (agent-core bundle + JSONL persistence, the
  61. * server.spec recipe) and mount the jsonrpc plugin on it through the real
  62. * namespace mount path, with in-memory seams standing in for stdio/exit.
  63. */
  64. async function mountPlugin(
  65. storageDir: string,
  66. options: { writeDelayMs?: number; failFlush?: boolean } = {},
  67. ): Promise<ApplyHarness> {
  68. const ctx = new Context()
  69. await ctx.plugin(agentCore)
  70. await ctx.plugin(SessionPersistenceJsonl, { root: storageDir })
  71. await new Promise(resolve => setTimeout(resolve, 50))
  72. const input = new PassThrough()
  73. const events: WireEvent[] = []
  74. const outputErrors: Error[] = []
  75. let pendingOutput = ''
  76. // A hand-rolled Writable (not a PassThrough): _write records frames on
  77. // admission and write-complete only when its callback fires, so a delayed
  78. // output proves exit waits for the transport's flush barrier.
  79. const output = new Writable({
  80. write(chunk: Buffer, _encoding, callback) {
  81. const ids: (string | number)[] = []
  82. pendingOutput += chunk.toString('utf8')
  83. for (;;) {
  84. const newline = pendingOutput.indexOf('\n')
  85. if (newline < 0) break
  86. const line = pendingOutput.slice(0, newline).trim()
  87. pendingOutput = pendingOutput.slice(newline + 1)
  88. if (line) {
  89. const frame = JSON.parse(line) as Record<string, unknown>
  90. events.push({ kind: 'frame', frame })
  91. if (typeof frame.id === 'string' || typeof frame.id === 'number') ids.push(frame.id)
  92. }
  93. }
  94. const complete = (): void => {
  95. if (options.failFlush === true && chunk.length === 0) {
  96. callback(new Error('flush callback failed'))
  97. return
  98. }
  99. events.push({ kind: 'write-complete', ids })
  100. callback()
  101. }
  102. if ((options.writeDelayMs ?? 0) > 0) setTimeout(complete, options.writeDelayMs)
  103. else complete()
  104. },
  105. })
  106. output.on('error', (error: Error) => { outputErrors.push(error) })
  107. const exit = (code: number): void => { events.push({ kind: 'exit', code }) }
  108. const fiber = await ctx.plugin(jsonrpc, { input, output, exit })
  109. const frames = (): Record<string, unknown>[] =>
  110. events.flatMap(event => event.kind === 'frame' ? [event.frame] : [])
  111. return {
  112. ctx,
  113. fiber,
  114. events,
  115. outputErrors,
  116. send: (frame) => { input.write(`${JSON.stringify(frame)}\n`) },
  117. sendRaw: (text) => { input.write(text) },
  118. frames,
  119. exits: () => events.flatMap(event => event.kind === 'exit' ? [event.code] : []),
  120. waitForFrame: (predicate, description) => waitFor(() => frames().find(predicate), description),
  121. dispose: async () => { await ctx.fiber.dispose() },
  122. }
  123. }
  124. const servers: Server[] = []
  125. afterEach(async () => {
  126. await Promise.all(servers.splice(0).map(server => new Promise(resolve => server.close(resolve))))
  127. vi.unstubAllEnvs()
  128. })
  129. /** The server.spec mock OpenAI-compatible SSE endpoint, so a prompt turn completes without a real key. */
  130. async function mockCompletionServer(): Promise<{ url: string; requests: unknown[] }> {
  131. const requests: unknown[] = []
  132. const server = createServer((request: IncomingMessage, response: ServerResponse) => {
  133. let body = ''
  134. request.on('data', (chunk: Buffer) => { body += chunk.toString('utf8') })
  135. request.on('end', () => {
  136. requests.push(JSON.parse(body))
  137. response.writeHead(200, { 'content-type': 'text/event-stream' })
  138. response.write('data: {"choices":[{"delta":{"role":"assistant","content":null,"reasoning_content":""}}]}\n\n')
  139. response.write('data: {"choices":[{"delta":{"content":"done"}}]}\n\n')
  140. response.write('data: {"choices":[{"delta":{"content":""},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1}}\n\n')
  141. response.write('data: [DONE]\n\n')
  142. response.end()
  143. })
  144. })
  145. servers.push(server)
  146. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
  147. const address = server.address()
  148. if (address === null || typeof address === 'string') throw new Error('no port')
  149. return { url: `http://127.0.0.1:${address.port}`, requests }
  150. }
  151. describe('dsh-jsonrpc plugin apply', () => {
  152. it('serves initialize over the injected stdio pair', async () => {
  153. const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-apply-init-'))
  154. vi.stubEnv('DEEPSEEK_API_KEY', 'test-key')
  155. const harness = await mountPlugin(storageDir)
  156. try {
  157. harness.send({ jsonrpc: '2.0', id: 'init-1', method: 'initialize', params: { cwd: storageDir, model: 'apply-model' } })
  158. const response = await harness.waitForFrame(frame => frame.id === 'init-1', 'initialize response')
  159. expect(response).toEqual({
  160. jsonrpc: '2.0',
  161. id: 'init-1',
  162. result: { serverInfo: { name: 'deepseek-harness-sdk-runtime', version: '0.0.1' } },
  163. })
  164. expect(harness.exits()).toEqual([])
  165. } finally {
  166. await harness.dispose()
  167. await rm(storageDir, { recursive: true, force: true })
  168. }
  169. })
  170. it('drives a session/prompt turn end-to-end and forwards session notifications as output frames', async () => {
  171. const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-apply-prompt-'))
  172. const llmServer = await mockCompletionServer()
  173. vi.stubEnv('DEEPSEEK_API_KEY', 'test-key')
  174. vi.stubEnv('DEEPSEEK_BASE_URL', llmServer.url)
  175. const harness = await mountPlugin(storageDir)
  176. try {
  177. harness.send({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { cwd: storageDir, model: 'dsagent-model' } })
  178. await harness.waitForFrame(frame => frame.id === 1, 'initialize response')
  179. harness.send({
  180. jsonrpc: '2.0',
  181. id: 2,
  182. method: 'session/prompt',
  183. params: { sessionId: 'main', contentBlocks: [{ type: 'text', text: 'fix it' }] },
  184. })
  185. const response = await harness.waitForFrame(frame => frame.id === 2, 'prompt response')
  186. expect(response.result).toEqual({ accepted: true })
  187. expect(llmServer.requests).toHaveLength(1)
  188. const body = llmServer.requests[0] as { model: string; messages: { role: string }[] }
  189. expect(body.model).toBe('dsagent-model')
  190. expect(body.messages.at(-1)?.role).toBe('user')
  191. // The server's notify() path rides the SAME transport apply() built:
  192. // session.event / session.finished arrive as id-less frames on output.
  193. const notifications = harness.frames().filter(frame => frame.id === undefined)
  194. expect(notifications.some(frame => frame.method === 'session.event')).toBe(true)
  195. expect(notifications.find(frame => frame.method === 'session.finished')).toMatchObject({
  196. jsonrpc: '2.0',
  197. params: { sessionId: 'main', status: 'ok' },
  198. })
  199. } finally {
  200. await harness.dispose()
  201. await rm(storageDir, { recursive: true, force: true })
  202. }
  203. })
  204. it('answers shutdown before exiting 0 exactly once, even against a racing second shutdown', async () => {
  205. const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-apply-shutdown-'))
  206. const harness = await mountPlugin(storageDir, { writeDelayMs: 10 })
  207. try {
  208. // Two shutdown frames in ONE chunk: both are dispatched from the same
  209. // read-loop pass, so both setImmediate exit callbacks get scheduled and
  210. // the second must hit the `exiting` guard instead of re-entering.
  211. const first = { jsonrpc: '2.0', id: 'sd-1', method: 'shutdown' }
  212. const second = { jsonrpc: '2.0', id: 'sd-2', method: 'shutdown' }
  213. harness.sendRaw(`${JSON.stringify(first)}\n${JSON.stringify(second)}\n`)
  214. await waitFor(() => harness.exits().length > 0 ? true : undefined, 'exit recorder call')
  215. expect(harness.exits()).toEqual([0])
  216. // Response-then-exit ordering: both response write callbacks and the
  217. // empty flush barrier complete before exit(0), even on delayed output.
  218. const exitIndex = harness.events.findIndex(event => event.kind === 'exit')
  219. const firstResponse = harness.events.findIndex(event => event.kind === 'frame' && event.frame.id === 'sd-1')
  220. const secondResponse = harness.events.findIndex(event => event.kind === 'frame' && event.frame.id === 'sd-2')
  221. const firstComplete = harness.events.findIndex(event => event.kind === 'write-complete' && event.ids.includes('sd-1'))
  222. const secondComplete = harness.events.findIndex(event => event.kind === 'write-complete' && event.ids.includes('sd-2'))
  223. const flushComplete = harness.events.findIndex(event => event.kind === 'write-complete' && event.ids.length === 0)
  224. expect(firstResponse).toBeGreaterThanOrEqual(0)
  225. expect(secondResponse).toBeGreaterThanOrEqual(0)
  226. expect(firstComplete).toBeGreaterThan(firstResponse)
  227. expect(secondComplete).toBeGreaterThan(secondResponse)
  228. expect(flushComplete).toBeGreaterThan(firstComplete)
  229. expect(flushComplete).toBeGreaterThan(secondComplete)
  230. expect(exitIndex).toBeGreaterThan(flushComplete)
  231. // Idempotent: the racing second shutdown never produces a second exit.
  232. await settle()
  233. expect(harness.exits()).toEqual([0])
  234. // The plugin fiber is disposed: the transport reads no further frames.
  235. const before = harness.frames().length
  236. harness.send({ jsonrpc: '2.0', id: 'after-exit', method: 'initialize', params: { cwd: storageDir, model: 'x' } })
  237. await settle()
  238. expect(harness.frames().length).toBe(before)
  239. } finally {
  240. await harness.dispose()
  241. await rm(storageDir, { recursive: true, force: true })
  242. }
  243. })
  244. it('still disposes and exits once when the flush callback fails', async () => {
  245. const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-apply-flush-failure-'))
  246. const harness = await mountPlugin(storageDir, { failFlush: true })
  247. try {
  248. harness.send({ jsonrpc: '2.0', id: 'sd-fail', method: 'shutdown' })
  249. await waitFor(() => harness.exits().length > 0 ? true : undefined, 'exit after flush failure')
  250. await settle()
  251. expect(harness.exits()).toEqual([0])
  252. expect(harness.outputErrors.map(error => error.message)).toEqual(['flush callback failed'])
  253. const before = harness.frames().length
  254. harness.send({ jsonrpc: '2.0', id: 'after-flush-failure', method: 'initialize', params: { cwd: storageDir, model: 'x' } })
  255. await settle()
  256. expect(harness.frames().length).toBe(before)
  257. } finally {
  258. await harness.dispose()
  259. await rm(storageDir, { recursive: true, force: true })
  260. }
  261. })
  262. it('stops serving on a bare fiber dispose (HMR-style unload) without calling exit', async () => {
  263. const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-apply-dispose-'))
  264. const harness = await mountPlugin(storageDir)
  265. try {
  266. // Prove the pipeline is live first (an unknown method still answers, as
  267. // a JSON-RPC error frame — the transport's handler-rejection path).
  268. harness.send({ jsonrpc: '2.0', id: 'probe-1', method: 'nope/unknown' })
  269. const error = await harness.waitForFrame(frame => frame.id === 'probe-1', 'error response for unknown method')
  270. expect(error.error).toMatchObject({
  271. code: -32603,
  272. message: 'unknown DeepSeek Harness SDK runtime method: nope/unknown',
  273. })
  274. await harness.fiber.dispose()
  275. // The effect disposer shut the server and closed the transport — later
  276. // frames are never read — and the exit seam was never touched.
  277. const before = harness.frames().length
  278. harness.send({ jsonrpc: '2.0', id: 'probe-2', method: 'initialize', params: { cwd: storageDir, model: 'x' } })
  279. await settle()
  280. expect(harness.frames().length).toBe(before)
  281. expect(harness.exits()).toEqual([])
  282. } finally {
  283. await harness.dispose()
  284. await rm(storageDir, { recursive: true, force: true })
  285. }
  286. })
  287. })