fake-runtime.ts 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. #!/usr/bin/env node
  2. /**
  3. * Scripted stand-in for the DeepSeek Harness SDK runtime, driven entirely by
  4. * env vars — no model, no network, no harness imports. Speaks the runtime's
  5. * newline-delimited JSON-RPC protocol on stdio: answers `initialize`,
  6. * `session/prompt` (streaming scripted `session.event` notifications, then
  7. * `session.finished`, then the response), and `shutdown`.
  8. *
  9. * Script vocabulary (all optional):
  10. * - `FAKE_TEXT`: assistant text for each turn (default `hello from fake runtime`).
  11. * - `FAKE_STATUS`: the `session.finished` status (default `ok`).
  12. * - `FAKE_REASON_KIND`: the `session.finished` reason kind (default `completed`; `none` omits the reason).
  13. * - `FAKE_SUBAGENT`: also emit a child session (subagent.started + child event + subagent.finished).
  14. * - `FAKE_ECHO_CWD`: prefix the assistant text with the process cwd.
  15. * - `FAKE_ECHO_ENV`: comma-separated env names to echo as `name=value` lines in the assistant text.
  16. * - `FAKE_MALFORMED`: `initialize` returns `{}` (no serverInfo); `prompt` returns `{}` (no accepted).
  17. * - `FAKE_MALFORMED_PROMPT`: `initialize` is normal; only `prompt` returns `{}` (no accepted).
  18. * - `FAKE_INIT_ERROR`: `initialize` answers a JSON-RPC error response with code 7.
  19. * - `FAKE_INIT_ERROR_ONCE_FILE`: fail `initialize` (code 7) only when this
  20. * marker file does NOT exist yet, creating it — so the first runtime
  21. * process fails the handshake and a respawned one succeeds (retry probe).
  22. * - `FAKE_ECHO_CWD_IN_INIT`: reply `serverInfo.version` = this process's cwd
  23. * (wire-visible spawn-cwd probe).
  24. * - `FAKE_MALFORMED_EVENT`: the turn's `session.event` carries a number as
  25. * the event; `FAKE_MALFORMED_MESSAGE`: assistant/message content is not an
  26. * array; `FAKE_MESSAGE_WITHOUT_DATA`: assistant/message with no data
  27. * member; `FAKE_MALFORMED_REASON`: `session.finished` reason is a bare
  28. * string (wire-validation probes).
  29. * - `FAKE_HANG_INIT`: never answer `initialize` (mid-handshake cancel probe).
  30. * - `FAKE_INIT_READY` + `FAKE_INIT_GO`: touch the READY file when `initialize`
  31. * arrives, then poll for the GO file before answering (deterministic
  32. * cancel-during-handshake window).
  33. * - `FAKE_HANG_PROMPT`: never answer `session/prompt` (for timeout/dispose tests).
  34. * - `FAKE_STREAM_THEN_MALFORMED`: stream a text chunk for the prompt, then
  35. * answer `{}` (no accepted) — same-pipe ordering makes the chunk arrive
  36. * before the protocol failure (partial-output retention probe).
  37. * - `FAKE_IGNORE_EOF` + `FAKE_SIGTERM_FILE`: keep running after stdin EOF; touch the file on SIGTERM (ladder probe).
  38. * - `FAKE_TRAP_SIGTERM`: with `FAKE_IGNORE_EOF`, survive SIGTERM too (SIGKILL-rung probe).
  39. * - `FAKE_EXIT_BEFORE_INIT`: exit 3 immediately (spawn-then-die probe).
  40. * - `FAKE_STDERR`: write this line to stderr at boot (diagnostics-tail probe).
  41. * - `FAKE_STDERR_NO_NEWLINE`: write this to stderr WITHOUT a newline (buffer-flush probe).
  42. * - `FAKE_RECORD_INIT`: append each `initialize` params JSON to this file (handshake probe).
  43. */
  44. import { appendFileSync, existsSync, writeFileSync } from 'node:fs'
  45. import process from 'node:process'
  46. import { createInterface } from 'node:readline'
  47. const env = process.env
  48. if (env.FAKE_STDERR !== undefined) process.stderr.write(`${env.FAKE_STDERR}\n`)
  49. if (env.FAKE_STDERR_NO_NEWLINE !== undefined) process.stderr.write(env.FAKE_STDERR_NO_NEWLINE)
  50. if (env.FAKE_EXIT_BEFORE_INIT !== undefined) process.exit(3)
  51. if (env.FAKE_IGNORE_EOF !== undefined) {
  52. // Simulate a runtime that never quiesces from EOF so the dispose ladder
  53. // must escalate; record which rung fired.
  54. process.stdin.resume()
  55. process.stdin.on('end', () => { setInterval(() => {}, 1_000) })
  56. process.on('SIGTERM', () => {
  57. if (env.FAKE_SIGTERM_FILE !== undefined) writeFileSync(env.FAKE_SIGTERM_FILE, 'sigterm\n')
  58. if (env.FAKE_TRAP_SIGTERM === undefined) process.exit(0)
  59. })
  60. }
  61. function write(message: object): void {
  62. process.stdout.write(`${JSON.stringify(message)}\n`)
  63. }
  64. function notify(method: string, params: object): void {
  65. write({ jsonrpc: '2.0', method, params })
  66. }
  67. let seq = 0
  68. function event(sessionId: string, type: string, data: object): void {
  69. notify('session.event', { sessionId, event: { type, seq: seq++, time: 0, data } })
  70. }
  71. function assistantText(): string {
  72. const parts: string[] = []
  73. if (env.FAKE_ECHO_CWD !== undefined) parts.push(`cwd=${process.cwd()}`)
  74. for (const name of (env.FAKE_ECHO_ENV ?? '').split(',').filter(entry => entry.length > 0)) {
  75. parts.push(`${name}=${env[name] ?? ''}`)
  76. }
  77. parts.push(env.FAKE_TEXT ?? 'hello from fake runtime')
  78. return parts.join('\n')
  79. }
  80. function runTurn(sessionId: string): void {
  81. const text = assistantText()
  82. if (env.FAKE_MALFORMED_EVENT !== undefined) {
  83. notify('session.event', { sessionId, event: 42 })
  84. return
  85. }
  86. event(sessionId, 'turn/start', { turn: 0 })
  87. event(sessionId, 'assistant/chunk', { turn: 0, step: 0, chunk: { type: 'text-delta', index: 0, text } })
  88. if (env.FAKE_MALFORMED_MESSAGE !== undefined) {
  89. event(sessionId, 'assistant/message', {
  90. turn: 0,
  91. step: 0,
  92. message: {
  93. id: 'fake-malformed-message',
  94. role: 'assistant',
  95. content: 'not-an-array',
  96. source: { kind: 'model', provider: 'fake', model: 'fake' },
  97. },
  98. })
  99. return
  100. }
  101. if (env.FAKE_MESSAGE_WITHOUT_DATA !== undefined) {
  102. notify('session.event', { sessionId, event: { type: 'assistant/message', seq: seq++, time: 0 } })
  103. return
  104. }
  105. event(sessionId, 'assistant/message', {
  106. turn: 0,
  107. step: 0,
  108. message: {
  109. id: `fake-assistant-${seq}`,
  110. role: 'assistant',
  111. content: [{ type: 'text', text }],
  112. source: { kind: 'model', provider: 'fake', model: 'fake' },
  113. },
  114. })
  115. const reasonKind = env.FAKE_REASON_KIND ?? 'completed'
  116. event(sessionId, 'turn/end', { turn: 0, reason: { kind: reasonKind } })
  117. if (env.FAKE_SUBAGENT !== undefined) {
  118. const childId = `${sessionId}-child`
  119. notify('subagent.started', { parentSessionId: sessionId, childSessionId: childId })
  120. event(childId, 'assistant/message', {
  121. turn: 0,
  122. step: 0,
  123. content: [{ type: 'text', text: 'child says hi' }],
  124. provenance: { provider: 'fake', model: 'fake' },
  125. })
  126. notify('subagent.finished', {
  127. provider: 'spawn',
  128. agentId: childId,
  129. parentSessionId: sessionId,
  130. childSessionId: childId,
  131. status: 'ok',
  132. stopReason: 'completed',
  133. lastAssistantMessage: [{ type: 'text', text: 'child says hi' }],
  134. })
  135. }
  136. }
  137. function sessionIdOf(params: Record<string, unknown> | undefined): string {
  138. const value = params?.sessionId
  139. return typeof value === 'string' ? value : ''
  140. }
  141. const reader = createInterface({ input: process.stdin })
  142. reader.on('line', (line) => {
  143. if (line.trim().length === 0) return
  144. const frame = JSON.parse(line) as { id?: string | number; method?: string; params?: Record<string, unknown> }
  145. if (frame.method === undefined || frame.id === undefined) return
  146. const respond = (result: object): void => { write({ jsonrpc: '2.0', id: frame.id, result }) }
  147. switch (frame.method) {
  148. case 'initialize':
  149. if (env.FAKE_RECORD_INIT !== undefined) appendFileSync(env.FAKE_RECORD_INIT, `${JSON.stringify(frame.params)}\n`)
  150. if (env.FAKE_HANG_INIT !== undefined) return
  151. if (env.FAKE_INIT_READY !== undefined && env.FAKE_INIT_GO !== undefined) {
  152. writeFileSync(env.FAKE_INIT_READY, 'ready\n')
  153. const go = env.FAKE_INIT_GO
  154. const id = frame.id
  155. const poll = setInterval(() => {
  156. if (!existsSync(go)) return
  157. clearInterval(poll)
  158. write({ jsonrpc: '2.0', id, result: { serverInfo: { name: 'deepseek-harness-sdk-runtime', version: '0.0.1' } } })
  159. }, 5)
  160. return
  161. }
  162. if (env.FAKE_INIT_ERROR !== undefined) {
  163. write({ jsonrpc: '2.0', id: frame.id, error: { code: 7, message: 'scripted init failure', data: { hint: 'fake' } } })
  164. return
  165. }
  166. if (env.FAKE_INIT_ERROR_ONCE_FILE !== undefined && !existsSync(env.FAKE_INIT_ERROR_ONCE_FILE)) {
  167. writeFileSync(env.FAKE_INIT_ERROR_ONCE_FILE, 'failed-once\n')
  168. write({ jsonrpc: '2.0', id: frame.id, error: { code: 7, message: 'scripted first-boot failure' } })
  169. return
  170. }
  171. if (env.FAKE_MALFORMED !== undefined) {
  172. respond({})
  173. return
  174. }
  175. if (env.FAKE_ECHO_CWD_IN_INIT !== undefined) {
  176. respond({ serverInfo: { name: 'deepseek-harness-sdk-runtime', version: process.cwd() } })
  177. return
  178. }
  179. respond({ serverInfo: { name: 'deepseek-harness-sdk-runtime', version: '0.0.1' } })
  180. return
  181. case 'session/prompt': {
  182. const sessionId = sessionIdOf(frame.params)
  183. const messageId = `fake-user-${seq}`
  184. event(sessionId, 'agent/inbox/spliced', {
  185. target: 'next-turn',
  186. start: 0,
  187. inserted: [{
  188. id: messageId,
  189. role: 'user',
  190. content: [],
  191. source: { kind: 'user' },
  192. }],
  193. })
  194. notify('session.status', { sessionId, status: 'running' })
  195. if (env.FAKE_STREAM_THEN_MALFORMED !== undefined) {
  196. event(sessionId, 'assistant/chunk', { turn: 0, step: 0, chunk: { type: 'text-delta', index: 0, text: 'streamed then cut short' } })
  197. respond({})
  198. return
  199. }
  200. if (env.FAKE_HANG_PROMPT !== undefined) return
  201. if (env.FAKE_MALFORMED !== undefined || env.FAKE_MALFORMED_PROMPT !== undefined) {
  202. respond({})
  203. return
  204. }
  205. runTurn(sessionId)
  206. notify('session.status', { sessionId, status: 'idle' })
  207. respond({ messageId })
  208. return
  209. }
  210. case 'shutdown':
  211. respond({})
  212. // An EOF-ignoring fake also refuses the protocol exit, so the client's
  213. // dispose ladder (not this cooperative path) must reap it.
  214. if (env.FAKE_IGNORE_EOF === undefined) setImmediate(() => process.exit(0))
  215. return
  216. default:
  217. write({ jsonrpc: '2.0', id: frame.id, error: { code: -32603, message: `unknown method: ${frame.method}` } })
  218. }
  219. })