coverage-edges.spec.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import LlmService, { LlmError, StreamChunk } from '@deepseek-ai/dsh-llm'
  4. import SessionStore, { TurnEndReason } from '@deepseek-ai/dsh-session'
  5. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  6. import ToolRegistry, { defineTool } from '@deepseek-ai/dsh-tools'
  7. import AgentRegistry from '@deepseek-ai/dsh-agent'
  8. import AgentLoop, { LoopAgent } from '@deepseek-ai/dsh-agent-loop'
  9. import { MockAdapter, textResponse } from './mock-adapter.ts'
  10. async function harness(adapter: MockAdapter) {
  11. const ctx = new Context()
  12. await ctx.plugin(LlmService)
  13. await ctx.plugin(SessionStore)
  14. await ctx.plugin(SystemPrompt)
  15. await ctx.plugin(ToolRegistry)
  16. await ctx.plugin(AgentRegistry)
  17. await ctx.plugin(AgentLoop, { agents: [] })
  18. ctx.llm.registerAdapter(['mock'], adapter)
  19. return ctx
  20. }
  21. function waitForIdle(ctx: Context, agent: LoopAgent): Promise<void> {
  22. return new Promise((resolve) => {
  23. const dispose = ctx.on('agent/status', (subject, status) => {
  24. if (subject === agent && status === 'idle') {
  25. dispose()
  26. resolve()
  27. }
  28. })
  29. })
  30. }
  31. function send(agent: LoopAgent, text: string) {
  32. agent.send([{ type: 'text', text }])
  33. }
  34. describe('loop backstop catch', () => {
  35. it('a throwing turn-start listener is caught by the backstop and loop survives', async () => {
  36. // The first turn will abort before the model call (turn-start throw).
  37. // The second turn should proceed normally and consume the first script entry.
  38. const adapter = new MockAdapter([textResponse('turn 2')])
  39. const ctx = await harness(adapter)
  40. const agent = ctx.agentLoop.create('a1', { model: 'mock' })
  41. let threwOnce = false
  42. ctx.on('agent/turn-start', () => {
  43. if (!threwOnce) {
  44. threwOnce = true
  45. throw new Error('broken turn-start listener')
  46. }
  47. })
  48. const errors: Error[] = []
  49. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  50. send(agent, 'first')
  51. await waitForIdle(ctx, agent)
  52. expect(errors.map(e => e.message)).toEqual(['broken turn-start listener'])
  53. // loop survives: second turn works fine and makes the model call
  54. send(agent, 'second')
  55. await waitForIdle(ctx, agent)
  56. expect(adapter.requests).toHaveLength(1)
  57. expect(adapter.requests[0]!.messages.some(m => m.content.some(b => 'text' in b && b.text === 'second'))).toBe(true)
  58. })
  59. it('a throwing turn-end listener is caught by the backstop and loop survives', async () => {
  60. const adapter = new MockAdapter([textResponse('turn 1'), textResponse('turn 2')])
  61. const ctx = await harness(adapter)
  62. const agent = ctx.agentLoop.create('a1', { model: 'mock' })
  63. let threwOnce = false
  64. ctx.on('agent/turn-end', () => {
  65. if (!threwOnce) {
  66. threwOnce = true
  67. throw new Error('broken turn-end listener')
  68. }
  69. })
  70. const errors: Error[] = []
  71. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  72. send(agent, 'first')
  73. await waitForIdle(ctx, agent)
  74. // The turn-end throw happens after the model call is complete, so turn 1's
  75. // request is consumed. The error is surfaced by the backstop.
  76. expect(errors.map(e => e.message)).toEqual(['broken turn-end listener'])
  77. // loop survives: second turn works fine
  78. send(agent, 'second')
  79. await waitForIdle(ctx, agent)
  80. expect(adapter.requests).toHaveLength(2)
  81. })
  82. })
  83. describe('tool JSON parse', () => {
  84. it('passes through non-JSON arguments string without crashing', async () => {
  85. const adapter = new MockAdapter([
  86. // model emits tool-call with malformed arguments (not valid JSON)
  87. [
  88. { type: 'block-start' as const, index: 0, blockType: 'tool-call' as const },
  89. { type: 'block-end' as const, index: 0, block: { type: 'tool-call' as const, id: 'c1', name: 'echo', arguments: 'not json' } },
  90. { type: 'finish' as const, reason: { kind: 'tool-calls' as const } },
  91. ] satisfies StreamChunk[],
  92. textResponse('done'),
  93. ])
  94. const ctx = await harness(adapter)
  95. ctx.tools.register(defineTool({
  96. name: 'echo',
  97. description: 'echo tool',
  98. parameters: { input: { type: 'string' } },
  99. async execute(args: unknown) {
  100. return [{ type: 'text', text: typeof args === 'string' ? `raw: ${args}` : JSON.stringify(args) }]
  101. },
  102. }))
  103. const agent = ctx.agentLoop.create('a1', { model: 'mock' })
  104. send(agent, 'use tool')
  105. await waitForIdle(ctx, agent)
  106. // tool/call event should have recorded the raw arguments string
  107. const callEvent = agent.session.events.find(e => e.type === 'tool/call')
  108. expect(callEvent).toBeDefined()
  109. if (callEvent!.type === 'tool/call') {
  110. expect(callEvent!.data.arguments).toBe('not json')
  111. }
  112. // the loop did not crash — a result was produced
  113. expect(agent.session.events.some(e => e.type === 'tool/result')).toBe(true)
  114. })
  115. it('uses empty object when tool-call arguments are empty string', async () => {
  116. const adapter = new MockAdapter([
  117. [
  118. { type: 'block-start' as const, index: 0, blockType: 'tool-call' as const },
  119. { type: 'block-end' as const, index: 0, block: { type: 'tool-call' as const, id: 'c1', name: 'noarg', arguments: '' } },
  120. { type: 'finish' as const, reason: { kind: 'tool-calls' as const } },
  121. ] satisfies StreamChunk[],
  122. textResponse('done'),
  123. ])
  124. const ctx = await harness(adapter)
  125. ctx.tools.register(defineTool({
  126. name: 'noarg',
  127. description: 'no-arg tool',
  128. parameters: {},
  129. async execute() {
  130. return [{ type: 'text', text: 'ran with empty args' }]
  131. },
  132. }))
  133. const agent = ctx.agentLoop.create('a1', { model: 'mock' })
  134. send(agent, 'use tool')
  135. await waitForIdle(ctx, agent)
  136. expect(agent.session.events.some(e => e.type === 'tool/result')).toBe(true)
  137. })
  138. })
  139. describe('toError normalization', () => {
  140. it('normalizes non-Error throws from turn-start listeners via toError in the backstop', async () => {
  141. const adapter = new MockAdapter([textResponse('ok')])
  142. const ctx = await harness(adapter)
  143. const agent = ctx.agentLoop.create('a1', { model: 'mock' })
  144. let threwOnce = false
  145. ctx.on('agent/turn-start', () => {
  146. if (!threwOnce) {
  147. threwOnce = true
  148. throw 'naked string error' // non-Error throw, goes through backstop's toError
  149. }
  150. })
  151. const errors: Error[] = []
  152. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  153. send(agent, 'go')
  154. await waitForIdle(ctx, agent)
  155. expect(errors).toHaveLength(1)
  156. expect(errors[0]!.message).toBe('naked string error')
  157. })
  158. it('normalizes non-Error throws from agent/request waterfall via inline toError in runStep catch', async () => {
  159. const adapter = new MockAdapter([textResponse('irrelevant')])
  160. const ctx = await harness(adapter)
  161. const agent = ctx.agentLoop.create('a1', { model: 'mock' })
  162. let threwOnce = false
  163. ctx.on('agent/request', async (_agent, _turn, _step, _options, _next) => {
  164. if (!threwOnce) {
  165. threwOnce = true
  166. throw { code: 500 } // non-Error throw, goes through runStep catch
  167. }
  168. return _next()
  169. })
  170. const errors: Error[] = []
  171. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  172. send(agent, 'go')
  173. await waitForIdle(ctx, agent)
  174. expect(errors).toHaveLength(1)
  175. // String() of { code: 500 } is '[object Object]'
  176. expect(errors[0]!.message).toBe('[object Object]')
  177. })
  178. })
  179. describe('coded error data emission', () => {
  180. it('errorData includes code when a coded error (LlmError) is thrown from a plugin', async () => {
  181. const adapter = new MockAdapter([textResponse('turn 1')])
  182. const ctx = await harness(adapter)
  183. const agent = ctx.agentLoop.create('a1', { model: 'mock' })
  184. let threwOnce = false
  185. ctx.on('agent/request', async (_agent, _turn, _step, _options, next) => {
  186. if (!threwOnce) {
  187. threwOnce = true
  188. throw new LlmError('server overloaded', 'RATE_LIMIT')
  189. }
  190. return next()
  191. })
  192. const errors: Error[] = []
  193. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  194. send(agent, 'go')
  195. await waitForIdle(ctx, agent)
  196. expect(errors).toHaveLength(1)
  197. expect(errors[0]!.message).toBe('server overloaded')
  198. // session error event includes the code
  199. const errorEvent = agent.session.events.find(e => e.type === 'error')
  200. expect(errorEvent).toBeDefined()
  201. if (errorEvent!.type === 'error') {
  202. expect(errorEvent!.data.code).toBe('RATE_LIMIT')
  203. }
  204. })
  205. })
  206. describe('disposed vs aborted branching', () => {
  207. it('handles dispose during model streaming producing reason "disposed"', async () => {
  208. const adapter = new MockAdapter(['hang'])
  209. const ctx = await harness(adapter)
  210. let agent!: LoopAgent
  211. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  212. agent = inner.agentLoop.create('scoped', { model: 'mock' })
  213. }, { inject: ['agentLoop'] }))
  214. const reasons: TurnEndReason[] = []
  215. ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
  216. send(agent, 'go')
  217. await new Promise(r => setTimeout(r, 30))
  218. await fiber.dispose() // dispose during hang
  219. await agent.done
  220. // The review-fixes test for 'HIGH: disposed status' already covers
  221. // this assertion path. The reason is 'disposed' because isDisposed() is
  222. // checked before the abort signal check in the error path.
  223. expect(reasons).toContainEqual({ kind: 'disposed' })
  224. })
  225. })