coverage-edges.spec.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import LlmService, { CallId, 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, toolCallResponse } 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: CallId('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: CallId('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. // A non-Error throw is wrapped in a HarnessError with code UNKNOWN, so the
  158. // session error event carries a routable code instead of degrading.
  159. const errorEvent = agent.session.events.find(e => e.type === 'error')
  160. expect(errorEvent?.type === 'error' && errorEvent.data.code).toBe('UNKNOWN')
  161. })
  162. it('normalizes non-Error throws from agent/request waterfall via inline toError in runStep catch', async () => {
  163. const adapter = new MockAdapter([textResponse('irrelevant')])
  164. const ctx = await harness(adapter)
  165. const agent = ctx.agentLoop.create('a1', { model: 'mock' })
  166. let threwOnce = false
  167. ctx.on('agent/request', async (_agent, _turn, _step, _options, _next) => {
  168. if (!threwOnce) {
  169. threwOnce = true
  170. throw { code: 500 } // non-Error throw, goes through runStep catch
  171. }
  172. return _next()
  173. })
  174. const errors: Error[] = []
  175. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  176. send(agent, 'go')
  177. await waitForIdle(ctx, agent)
  178. expect(errors).toHaveLength(1)
  179. // String() of { code: 500 } is '[object Object]'
  180. expect(errors[0]!.message).toBe('[object Object]')
  181. const errorEvent = agent.session.events.find(e => e.type === 'error')
  182. expect(errorEvent?.type === 'error' && errorEvent.data.code).toBe('UNKNOWN')
  183. })
  184. })
  185. describe('coded error data emission', () => {
  186. it('errorData includes code when a coded error (LlmError) is thrown from a plugin', async () => {
  187. const adapter = new MockAdapter([textResponse('turn 1')])
  188. const ctx = await harness(adapter)
  189. const agent = ctx.agentLoop.create('a1', { model: 'mock' })
  190. let threwOnce = false
  191. ctx.on('agent/request', async (_agent, _turn, _step, _options, next) => {
  192. if (!threwOnce) {
  193. threwOnce = true
  194. throw new LlmError('server overloaded', 'RATE_LIMIT')
  195. }
  196. return next()
  197. })
  198. const errors: Error[] = []
  199. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  200. send(agent, 'go')
  201. await waitForIdle(ctx, agent)
  202. expect(errors).toHaveLength(1)
  203. expect(errors[0]!.message).toBe('server overloaded')
  204. // session error event includes the code
  205. const errorEvent = agent.session.events.find(e => e.type === 'error')
  206. expect(errorEvent).toBeDefined()
  207. if (errorEvent!.type === 'error') {
  208. expect(errorEvent!.data.code).toBe('RATE_LIMIT')
  209. }
  210. })
  211. })
  212. describe('disposed vs aborted branching', () => {
  213. it('handles dispose during model streaming producing reason "disposed"', async () => {
  214. const adapter = new MockAdapter(['hang'])
  215. const ctx = await harness(adapter)
  216. let agent!: LoopAgent
  217. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  218. agent = inner.agentLoop.create('scoped', { model: 'mock' })
  219. }, { inject: ['agentLoop'] }))
  220. const reasons: TurnEndReason[] = []
  221. ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
  222. send(agent, 'go')
  223. await new Promise(r => setTimeout(r, 30))
  224. await fiber.dispose() // dispose during hang
  225. await agent.done
  226. // The review-fixes test for 'HIGH: disposed status' already covers
  227. // this assertion path. The reason is 'disposed' because isDisposed() is
  228. // checked before the abort signal check in the error path.
  229. expect(reasons).toContainEqual({ kind: 'disposed' })
  230. })
  231. })
  232. describe('structured tool error propagation (RFC 005 pt 2)', () => {
  233. it('forwards a tool HarnessError onto the tool/result session event', async () => {
  234. const { HarnessError } = await import('@deepseek-ai/dsh-llm')
  235. // First model turn calls the tool; second turn (after the tool result is
  236. // fed back) ends with plain text so the loop settles.
  237. const adapter = new MockAdapter([
  238. toolCallResponse('c1', 'boom', {}),
  239. textResponse('done'),
  240. ])
  241. const ctx = await harness(adapter)
  242. const agent = ctx.agentLoop.create('a1', { model: 'mock' })
  243. ctx.tools.register(defineTool({
  244. name: 'boom',
  245. description: 'always fails',
  246. parameters: {},
  247. async execute() {
  248. throw new HarnessError('exploded', 'BOOM')
  249. },
  250. }))
  251. send(agent, 'go')
  252. await waitForIdle(ctx, agent)
  253. const toolResult = agent.session.events.find(e => e.type === 'tool/result')
  254. expect(toolResult?.type === 'tool/result' && toolResult.data.isError).toBe(true)
  255. expect(toolResult?.type === 'tool/result' && toolResult.data.error)
  256. .toEqual({ name: 'HarnessError', code: 'BOOM' })
  257. })
  258. })