host-runtime.spec.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'
  2. import { tmpdir } from 'node:os'
  3. import { join } from 'node:path'
  4. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
  5. import type { Context } from 'cordis'
  6. import type { Agent } from '@deepseek-ai/dsh-agent'
  7. import { agentEvents } from '@deepseek-ai/dsh-agent'
  8. import type { GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm'
  9. import { LlmAdapter } from '@deepseek-ai/dsh-llm'
  10. import type { SessionId } from '@deepseek-ai/dsh-session'
  11. import type { HostFrame, MuxFrame } from '@deepseek-ai/dsh-host-apiproxy/api'
  12. import type { RpcRequest, RpcResponse } from '@deepseek-ai/dsh-host-apiproxy/api/rpc'
  13. import { RpcId } from '@deepseek-ai/dsh-host-apiproxy/api/rpc'
  14. import { bootHost, startHost, type HostHandle, type RunningHost } from '../src/index.ts'
  15. /** Scripted adapter: each model call consumes the next chunk list; 'hang' streams then waits for abort. */
  16. class ScriptedAdapter extends LlmAdapter {
  17. readonly requests: GenerateOptions[] = []
  18. constructor(private script: (StreamChunk[] | 'hang')[]) {
  19. super()
  20. }
  21. async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
  22. this.requests.push(options)
  23. const entry = this.script.shift()
  24. if (!entry) throw new Error('ScriptedAdapter: script exhausted')
  25. if (entry === 'hang') {
  26. yield { type: 'block-start', index: 0, blockType: 'text' }
  27. await new Promise<void>((_resolve, reject) => {
  28. options.signal?.addEventListener('abort', () => { reject(new Error('aborted')) }, { once: true })
  29. })
  30. return
  31. }
  32. yield * entry
  33. }
  34. }
  35. function textResponse(text: string): StreamChunk[] {
  36. return [
  37. { type: 'block-start', index: 0, blockType: 'text' },
  38. { type: 'text-delta', index: 0, text },
  39. { type: 'block-end', index: 0, block: { type: 'text', text } },
  40. { type: 'usage', usage: { inputTokens: 10, outputTokens: text.length } },
  41. { type: 'finish', reason: { kind: 'stop' } },
  42. ]
  43. }
  44. function request<P>(payload: P): RpcRequest<P> {
  45. return { rpcId: RpcId(`req-${String(nextRpc++)}`), payload }
  46. }
  47. let nextRpc = 1
  48. function waitForIdle(ctx: Context, agent: Agent): Promise<void> {
  49. return new Promise((resolve) => {
  50. const dispose = ctx.on('agent/status', (subject: Agent, status: string) => {
  51. if (subject === agent && status === 'idle') {
  52. dispose()
  53. resolve()
  54. }
  55. })
  56. })
  57. }
  58. function expectOk<T>(response: RpcResponse<T>): T {
  59. expect(response.result.ok).toBe(true)
  60. if (!response.result.ok) throw new Error('unreachable')
  61. return response.result.value
  62. }
  63. let host: RunningHost | undefined
  64. beforeEach(() => {
  65. vi.stubEnv('DEEPSEEK_API_KEY', 'spec-placeholder-key')
  66. })
  67. afterEach(async () => {
  68. await host?.dispose()
  69. host = undefined
  70. vi.unstubAllEnvs()
  71. })
  72. async function boot(script: (StreamChunk[] | 'hang')[] = []): Promise<RunningHost> {
  73. host = await startHost({
  74. boot: {
  75. persistenceRoot: mkdtempSync(join(tmpdir(), 'dsh-host-runtime-')),
  76. workspaceContext: false,
  77. provider: 'scripted',
  78. model: 'test-model',
  79. },
  80. })
  81. host.ctx.llm.registerAdapter(['scripted'], new ScriptedAdapter(script))
  82. return host
  83. }
  84. describe('bootHost / startHost', () => {
  85. it('falls back to the deepseek defaults and disposes idempotently', async () => {
  86. const handle: HostHandle = await bootHost({
  87. persistenceRoot: mkdtempSync(join(tmpdir(), 'dsh-boot-')),
  88. workspaceContext: false,
  89. })
  90. expect(handle.defaults).toMatchObject({ provider: 'deepseek', model: 'deepseek-v4-flash' })
  91. expect(typeof handle.defaults.cwd).toBe('string')
  92. await handle.dispose()
  93. })
  94. it('startHost assembles api + handler over the same defaults and dedupes dispose', async () => {
  95. const running = await boot()
  96. expect(running.defaults).toMatchObject({ provider: 'scripted', model: 'test-model' })
  97. const body = JSON.stringify({ type: 'client-request', rpcId: 'r-h', method: 'host.describe', payload: {} })
  98. const response = await running.handler.fetch(new Request('http://x/api/host.describe', { method: 'POST', body }))
  99. const parsed = await response.json() as { result: { ok: boolean; value: { provider: string } } }
  100. expect(parsed.result.value.provider).toBe('scripted')
  101. const first = running.dispose()
  102. expect(running.dispose()).toBe(first)
  103. await first
  104. host = undefined
  105. })
  106. it('routes workspace instructions through the assembled agent request prefix', async () => {
  107. const workspace = mkdtempSync(join(tmpdir(), 'dsh-host-workspace-'))
  108. mkdirSync(join(workspace, '.git'))
  109. writeFileSync(join(workspace, 'AGENTS.md'), 'host-workspace-context-probe\n')
  110. const adapter = new ScriptedAdapter([textResponse('done')])
  111. host = await startHost({
  112. boot: {
  113. persistenceRoot: mkdtempSync(join(tmpdir(), 'dsh-host-workspace-sessions-')),
  114. workspaceContext: { dshHome: join(workspace, '.dsh'), maxBytes: 65_536 },
  115. provider: 'scripted',
  116. model: 'test-model',
  117. cwd: workspace,
  118. },
  119. })
  120. host.ctx.llm.registerAdapter(['scripted'], adapter)
  121. const { sessionId } = expectOk(await host.api.sessions.create(request({})))
  122. const agent = host.ctx.agents.get(sessionId) as Agent
  123. const idle = waitForIdle(host.ctx, agent)
  124. expectOk(await host.api.sessions.prompt(request({
  125. sessionId,
  126. mode: 'queue' as const,
  127. content: [{ type: 'text' as const, text: 'go' }],
  128. })))
  129. await idle
  130. const requestText = adapter.requests[0]?.messages
  131. .flatMap(message => message.content)
  132. .filter(block => block.type === 'text')
  133. .map(block => block.text)
  134. .join('\n') ?? ''
  135. expect(requestText).toContain('Instructions from: AGENTS.md')
  136. expect(requestText).toContain('host-workspace-context-probe')
  137. })
  138. })
  139. describe('host.describe', () => {
  140. it('reports version, cwd, defaults, and the attached count', async () => {
  141. const { api } = await boot()
  142. const value = expectOk(await api.host.describe(request({})))
  143. expect(value).toMatchObject({ version: '0.0.1', cwd: process.cwd(), provider: 'scripted', model: 'test-model', attachedSessions: 0 })
  144. })
  145. })
  146. describe('sessions.create / list', () => {
  147. it('creates a session (echoing the request rpcId) and lists it newest-first', async () => {
  148. const { api } = await boot()
  149. const created = await api.sessions.create(request({ cwd: '/tmp' }))
  150. const { sessionId } = expectOk(created)
  151. expect(created.rpcId).toMatch(/^req-/)
  152. const second = expectOk(await api.sessions.create(request({}))).sessionId
  153. const { items } = expectOk(await api.sessions.list(request({})))
  154. expect(items.map(item => item.sessionId)).toContain(sessionId)
  155. expect(items.map(item => item.sessionId)).toContain(second)
  156. const first = items.find(item => item.sessionId === sessionId)
  157. expect(first?.cwd).toBe('/tmp')
  158. expect(first?.running).toBe(false)
  159. expect(first?.parentSessionId).toBeUndefined()
  160. })
  161. })
  162. describe('sessions.prompt / cancel', () => {
  163. it('queues a prompt whose rpcId rides into user/message, then the reply lands', async () => {
  164. const running = await boot([textResponse('pong')])
  165. const { api, ctx } = running
  166. const { sessionId } = expectOk(await api.sessions.create(request({})))
  167. const agent = ctx.agents.get(sessionId)
  168. expect(agent).toBeDefined()
  169. const idle = waitForIdle(ctx, agent as Agent)
  170. const promptRequest = request({ sessionId, mode: 'queue' as const, content: [{ type: 'text' as const, text: 'ping' }] })
  171. expectOk(await api.sessions.prompt(promptRequest))
  172. await idle
  173. const value = expectOk(await api.sessions.history(request({ sessionId })))
  174. const events = value.events.map(entry => entry.event)
  175. const userEvent = events.find(event => event.type === 'user/message') as
  176. | { data: { source?: { rpcId?: string } } } | undefined
  177. expect(userEvent?.data.source?.rpcId).toBe(promptRequest.rpcId)
  178. const reply = events.find(event => event.type === 'assistant/message')
  179. expect(reply).toBeDefined()
  180. })
  181. it('steer on an idle agent falls through to send', async () => {
  182. const running = await boot([textResponse('steered')])
  183. const { api, ctx } = running
  184. const { sessionId } = expectOk(await api.sessions.create(request({})))
  185. const idle = waitForIdle(ctx, ctx.agents.get(sessionId) as Agent)
  186. expectOk(await api.sessions.prompt(request({ sessionId, mode: 'steer' as const, content: [{ type: 'text' as const, text: 'now' }] })))
  187. await idle
  188. })
  189. it('errors session-not-found on a ghost session', async () => {
  190. const { api } = await boot()
  191. const response = await api.sessions.prompt(request({ sessionId: 'session-void' as SessionId, mode: 'queue' as const, content: [{ type: 'text' as const, text: 'x' }] }))
  192. expect(response.result.ok).toBe(false)
  193. if (!response.result.ok) expect(response.result.error.code).toBe('session-not-found')
  194. })
  195. it('maps a synchronous send throw to agent-busy', async () => {
  196. const { api } = await boot()
  197. const { sessionId } = expectOk(await api.sessions.create(request({})))
  198. const poisoned = [{ type: 'text', text: 'x', bad: () => 1 }] as never
  199. const response = await api.sessions.prompt(request({ sessionId, mode: 'queue' as const, content: poisoned }))
  200. expect(response.result.ok).toBe(false)
  201. if (!response.result.ok) expect(response.result.error.code).toBe('agent-busy')
  202. })
  203. it('cancels an attached agent and rejects an unattached one', async () => {
  204. const running = await boot(['hang'])
  205. const { api, ctx } = running
  206. const { sessionId } = expectOk(await api.sessions.create(request({})))
  207. const agent = ctx.agents.get(sessionId) as Agent
  208. agent.send([{ type: 'text', text: 'run forever' }])
  209. expectOk(await api.sessions.cancel(request({ sessionId })))
  210. const missing = await api.sessions.cancel(request({ sessionId: 'session-none' as SessionId }))
  211. expect(missing.result.ok).toBe(false)
  212. if (!missing.result.ok) expect(missing.result.error.code).toBe('session-not-found')
  213. })
  214. })
  215. describe('sessions.history', () => {
  216. it('implicitly resumes a cold session, deduplicating concurrent calls to one attach', async () => {
  217. const persistenceRoot = mkdtempSync(join(tmpdir(), 'dsh-host-resume-'))
  218. const first = await startHost({
  219. boot: { persistenceRoot, workspaceContext: false, provider: 'scripted', model: 'test-model' },
  220. })
  221. first.ctx.llm.registerAdapter(['scripted'], new ScriptedAdapter([textResponse('persisted')]))
  222. const { sessionId } = expectOk(await first.api.sessions.create(request({})))
  223. const agent = first.ctx.agents.get(sessionId) as Agent
  224. const idle = waitForIdle(first.ctx, agent)
  225. agent.send([{ type: 'text', text: 'save me' }])
  226. await idle
  227. await first.dispose()
  228. host = await startHost({
  229. boot: { persistenceRoot, workspaceContext: false, provider: 'scripted', model: 'test-model' },
  230. })
  231. host.ctx.llm.registerAdapter(['scripted'], new ScriptedAdapter([]))
  232. expect(host.ctx.agents.get(sessionId)).toBeUndefined()
  233. const [a, b] = await Promise.all([
  234. host.api.sessions.history(request({ sessionId })),
  235. host.api.sessions.history(request({ sessionId })),
  236. ])
  237. for (const response of [a, b]) {
  238. const value = expectOk(response)
  239. expect(value.events.some(entry => entry.event.type === 'assistant/message')).toBe(true)
  240. }
  241. expect(host.ctx.agents.get(sessionId)).toBeDefined()
  242. expect(host.ctx.agents.list()).toHaveLength(1)
  243. })
  244. it('errors session-not-found when resume fails, deduplicating concurrent resumes', async () => {
  245. const { api } = await boot()
  246. const ghost = 'session-ghost' as SessionId
  247. const [first, second] = await Promise.all([
  248. api.sessions.history(request({ sessionId: ghost })),
  249. api.sessions.history(request({ sessionId: ghost })),
  250. ])
  251. for (const response of [first, second]) {
  252. expect(response.result.ok).toBe(false)
  253. if (!response.result.ok) expect(response.result.error.code).toBe('session-not-found')
  254. }
  255. })
  256. it('paginates backwards on message boundaries with hasMore', async () => {
  257. const running = await boot([textResponse('a1'), textResponse('a2'), textResponse('a3')])
  258. const { api, ctx } = running
  259. const { sessionId } = expectOk(await api.sessions.create(request({})))
  260. const agent = ctx.agents.get(sessionId) as Agent
  261. for (const text of ['q1', 'q2', 'q3']) {
  262. const idle = waitForIdle(ctx, agent)
  263. agent.send([{ type: 'text', text }])
  264. await idle
  265. }
  266. const all = expectOk(await api.sessions.history(request({ sessionId })))
  267. expect(all.hasMore).toBe(false)
  268. const messageCount = all.events.filter(entry => entry.event.type === 'user/message' || entry.event.type === 'assistant/message').length
  269. expect(messageCount).toBe(6)
  270. const lastPage = expectOk(await api.sessions.history(request({ sessionId, maxMessages: 1 })))
  271. expect(lastPage.hasMore).toBe(true)
  272. expect(lastPage.events.filter(entry => entry.event.type === 'assistant/message')).toHaveLength(1)
  273. expect(lastPage.events.filter(entry => entry.event.type === 'user/message')).toHaveLength(0)
  274. const firstSeq = lastPage.events[0]?.event.seq as number
  275. const olderPage = expectOk(await api.sessions.history(request({ sessionId, beforeSeq: firstSeq, maxMessages: 2 })))
  276. expect(olderPage.events.at(-1)?.event.seq).toBeLessThan(firstSeq)
  277. expect(olderPage.hasMore).toBe(true)
  278. expect(olderPage.events.filter(entry => entry.event.type === 'user/message' || entry.event.type === 'assistant/message').length).toBe(2)
  279. })
  280. })
  281. describe('events streams', () => {
  282. it('mux: a pending pull wakes when a frame arrives (waiter path)', async () => {
  283. const running = await boot()
  284. const { api } = running
  285. const ac = new AbortController()
  286. const stream = api.events.mux(request({}), ac.signal)[Symbol.asyncIterator]()
  287. // no sessions yet: next() must pend on the queue's waiter, not the buffer
  288. const pending = stream.next()
  289. const { sessionId } = expectOk(await api.sessions.create(request({})))
  290. const frame = (await pending).value as RpcRequest<MuxFrame>
  291. expect(frame.payload).toMatchObject({ type: 'session/subscribed', sessionId })
  292. ac.abort()
  293. expect((await stream.next()).done).toBe(true)
  294. })
  295. it('lists fork lineage and announces it on the host stream', async () => {
  296. const running = await boot()
  297. const { api, ctx } = running
  298. const { sessionId: parent } = expectOk(await api.sessions.create(request({})))
  299. const ac = new AbortController()
  300. const stream = api.events.host(request({}), ac.signal)[Symbol.asyncIterator]()
  301. const child = `session-child-${String(Date.now())}` as SessionId
  302. const handle = await ctx.agents.create({ sessionId: child, meta: { parentSession: parent }, agentOptions: { provider: 'scripted', model: 'test-model' } })
  303. expect(handle.agent.id).toBe(child)
  304. const added = (await stream.next()).value as RpcRequest<HostFrame>
  305. expect(added.payload).toMatchObject({ type: 'host/session-added', sessionId: child, parentSessionId: parent })
  306. const { items } = expectOk(await api.sessions.list(request({})))
  307. expect(items.find(item => item.sessionId === child)?.parentSessionId).toBe(parent)
  308. await handle.dispose()
  309. let frame: RpcRequest<HostFrame>
  310. do frame = (await stream.next()).value as RpcRequest<HostFrame>
  311. while (frame.payload.type !== 'host/session-removed')
  312. expect(frame.payload).toMatchObject({ type: 'host/session-removed', sessionId: child })
  313. ac.abort()
  314. })
  315. it('mux: emits subscribed baselines, live session events, and new-session subscriptions until abort', async () => {
  316. const running = await boot([textResponse('live')])
  317. const { api, ctx } = running
  318. const { sessionId } = expectOk(await api.sessions.create(request({})))
  319. const ac = new AbortController()
  320. const stream = api.events.mux(request({}), ac.signal)[Symbol.asyncIterator]()
  321. const baseline = await stream.next()
  322. expect((baseline.value as RpcRequest<MuxFrame>).payload).toMatchObject({ type: 'session/subscribed', sessionId })
  323. const agent = ctx.agents.get(sessionId) as Agent
  324. const idle = waitForIdle(ctx, agent)
  325. agent.send([{ type: 'text', text: 'go' }])
  326. await idle
  327. const live = await stream.next()
  328. expect((live.value as RpcRequest<MuxFrame>).payload.type).toBe('session/event')
  329. const other = expectOk(await api.sessions.create(request({}))).sessionId
  330. let frame: RpcRequest<MuxFrame>
  331. do frame = (await stream.next()).value as RpcRequest<MuxFrame>
  332. while (!(frame.payload.type === 'session/subscribed' && frame.payload.sessionId === other))
  333. ac.abort()
  334. expect((await stream.next()).done).toBe(true)
  335. })
  336. it('host: session lifecycle, status flips (disposed suppressed), and agent errors', async () => {
  337. const running = await boot([textResponse('x')])
  338. const { api, ctx } = running
  339. const ac = new AbortController()
  340. const stream = api.events.host(request({}), ac.signal)[Symbol.asyncIterator]()
  341. const { sessionId } = expectOk(await api.sessions.create(request({})))
  342. const added = await stream.next()
  343. expect((added.value as RpcRequest<HostFrame>).payload).toMatchObject({ type: 'host/session-added', sessionId })
  344. const agent = ctx.agents.get(sessionId) as Agent
  345. const idle = waitForIdle(ctx, agent)
  346. agent.send([{ type: 'text', text: 'run' }])
  347. await idle
  348. const runningFrame = await stream.next()
  349. expect((runningFrame.value as RpcRequest<HostFrame>).payload).toMatchObject({ type: 'host/session-status', running: true })
  350. const idleFrame = await stream.next()
  351. expect((idleFrame.value as RpcRequest<HostFrame>).payload).toMatchObject({ type: 'host/session-status', running: false })
  352. // Raw ctx.emit lacks the scope carrier the mounted invariants plugin now
  353. // enforces; dispatch the way the loop does.
  354. agentEvents(ctx, agent).emit('agent/error', 1, 1, new Error('boom'))
  355. const errorFrame = await stream.next()
  356. expect((errorFrame.value as RpcRequest<HostFrame>).payload).toMatchObject({ type: 'host/agent-error', message: 'Error: boom' })
  357. ac.abort()
  358. // Push-after-done: an event landing between abort and generator wind-down
  359. // must be dropped silently, not crash the queue.
  360. agentEvents(ctx, agent).emit('agent/error', 1, 1, new Error('late'))
  361. expect((await stream.next()).done).toBe(true)
  362. })
  363. })
  364. describe('respond stub', () => {
  365. it('always reports not-pending (step2 registry pending)', async () => {
  366. const { api } = await boot()
  367. const receipt = await api.respond({ type: 'client-response', rpcId: RpcId('r'), result: { ok: true, value: null } })
  368. expect(receipt).toEqual({ accepted: false, reason: 'not-pending' })
  369. })
  370. })