coverage-edges.spec.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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, { AgentId } from '@deepseek-ai/dsh-agent'
  8. import AgentLoop, { ReactLoopAgent } 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: ReactLoopAgent): 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: ReactLoopAgent, text: string) {
  32. agent.send([{ type: 'text', text }])
  33. }
  34. describe('turn boundary listener throws (handled in-turn, loop survives)', () => {
  35. it('a pre-push turn/start failure (non-serializable source) is rethrown to the runLoop backstop', async () => {
  36. // A non-serializable message source makes the turn/start append throw BEFORE
  37. // the event is pushed (Session.append validates before push), so turn/start
  38. // never enters the log. runTurn sees no logged turn/start and rethrows; the
  39. // runLoop backstop reports via agent/error (step 0) + the logger and the
  40. // driver survives. This is the ONLY path that reaches the backstop.
  41. const adapter = new MockAdapter([textResponse('turn 2')])
  42. const ctx = await harness(adapter)
  43. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  44. const errors: { turn: number; step: number; message: string }[] = []
  45. ctx.on('agent/error', (_a, turn, step, error) => void errors.push({ turn, step, message: error.message }))
  46. // A non-serializable source (BigInt) on the queued message.
  47. agent.send([{ type: 'text', text: 'first' }], { source: { kind: 'plugin', plugin: 'p', bad: 1n } as never })
  48. await waitForIdle(ctx, agent)
  49. expect(errors).toHaveLength(1)
  50. expect(errors[0]!.step).toBe(0)
  51. expect(errors[0]!.message).toMatch(/non-JSON-serializable/)
  52. // No turn boundary was written (the turn/start append threw before push).
  53. expect(agent.session.events.some(e => e.type === 'turn/start')).toBe(false)
  54. // loop survives: a well-formed second turn runs normally.
  55. send(agent, 'second')
  56. await waitForIdle(ctx, agent)
  57. expect(adapter.requests).toHaveLength(1)
  58. })
  59. })
  60. describe('tool JSON parse', () => {
  61. it('passes through non-JSON arguments string without crashing', async () => {
  62. const adapter = new MockAdapter([
  63. // model emits tool-call with malformed arguments (not valid JSON)
  64. [
  65. { type: 'block-start' as const, index: 0, blockType: 'tool-call' as const },
  66. { type: 'block-end' as const, index: 0, block: { type: 'tool-call' as const, id: CallId('c1'), name: 'echo', arguments: 'not json' } },
  67. { type: 'finish' as const, reason: { kind: 'tool-calls' as const } },
  68. ] satisfies StreamChunk[],
  69. textResponse('done'),
  70. ])
  71. const ctx = await harness(adapter)
  72. ctx.tools.register(defineTool({
  73. name: 'echo',
  74. description: 'echo tool',
  75. parameters: { input: { type: 'string' } },
  76. async execute(args: unknown) {
  77. return [{ type: 'text', text: typeof args === 'string' ? `raw: ${args}` : JSON.stringify(args) }]
  78. },
  79. }))
  80. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  81. send(agent, 'use tool')
  82. await waitForIdle(ctx, agent)
  83. // tool/call event should have recorded the raw arguments string
  84. const callEvent = agent.session.events.find(e => e.type === 'tool/call')
  85. expect(callEvent).toBeDefined()
  86. if (callEvent!.type === 'tool/call') {
  87. expect(callEvent!.data.arguments).toBe('not json')
  88. }
  89. // the loop did not crash — a result was produced
  90. expect(agent.session.events.some(e => e.type === 'tool/result')).toBe(true)
  91. })
  92. it('uses empty object when tool-call arguments are empty string', async () => {
  93. const adapter = new MockAdapter([
  94. [
  95. { type: 'block-start' as const, index: 0, blockType: 'tool-call' as const },
  96. { type: 'block-end' as const, index: 0, block: { type: 'tool-call' as const, id: CallId('c1'), name: 'noarg', arguments: '' } },
  97. { type: 'finish' as const, reason: { kind: 'tool-calls' as const } },
  98. ] satisfies StreamChunk[],
  99. textResponse('done'),
  100. ])
  101. const ctx = await harness(adapter)
  102. ctx.tools.register(defineTool({
  103. name: 'noarg',
  104. description: 'no-arg tool',
  105. parameters: {},
  106. async execute() {
  107. return [{ type: 'text', text: 'ran with empty args' }]
  108. },
  109. }))
  110. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  111. send(agent, 'use tool')
  112. await waitForIdle(ctx, agent)
  113. expect(agent.session.events.some(e => e.type === 'tool/result')).toBe(true)
  114. })
  115. })
  116. describe('toError normalization', () => {
  117. it('normalizes non-Error throws from a turn/start session-event listener via toError', async () => {
  118. const adapter = new MockAdapter([textResponse('ok')])
  119. const ctx = await harness(adapter)
  120. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  121. let threwOnce = false
  122. ctx.on('session/event', (_session, event) => {
  123. if (event.type === 'turn/start' && !threwOnce) {
  124. threwOnce = true
  125. throw 'naked string error' // non-Error throw, normalized via toError
  126. }
  127. })
  128. const errors: Error[] = []
  129. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  130. send(agent, 'go')
  131. await waitForIdle(ctx, agent)
  132. expect(errors).toHaveLength(1)
  133. expect(errors[0]!.message).toBe('naked string error')
  134. // A non-Error throw is wrapped in a HarnessError with code UNKNOWN, so the
  135. // turn-end error reason carries a routable code instead of degrading.
  136. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  137. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind === 'error' && turnEnd.data.reason.code).toBe('UNKNOWN')
  138. })
  139. it('normalizes non-Error throws from agent/request waterfall via inline toError in runStep catch', async () => {
  140. const adapter = new MockAdapter([textResponse('irrelevant')])
  141. const ctx = await harness(adapter)
  142. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  143. let threwOnce = false
  144. ctx.on('agent/request', async (_agent, _turn, _step, _options, _next) => {
  145. if (!threwOnce) {
  146. threwOnce = true
  147. throw { code: 500 } // non-Error throw, goes through runStep catch
  148. }
  149. return _next()
  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. // String() of { code: 500 } is '[object Object]'
  157. expect(errors[0]!.message).toBe('[object Object]')
  158. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  159. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind === 'error' && turnEnd.data.reason.code).toBe('UNKNOWN')
  160. })
  161. })
  162. describe('coded error data emission', () => {
  163. it('errorData includes code when a coded error (LlmError) is thrown from a plugin', async () => {
  164. const adapter = new MockAdapter([textResponse('turn 1')])
  165. const ctx = await harness(adapter)
  166. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  167. let threwOnce = false
  168. ctx.on('agent/request', async (_agent, _turn, _step, _options, next) => {
  169. if (!threwOnce) {
  170. threwOnce = true
  171. throw new LlmError('server overloaded', 'RATE_LIMIT')
  172. }
  173. return next()
  174. })
  175. const errors: Error[] = []
  176. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  177. send(agent, 'go')
  178. await waitForIdle(ctx, agent)
  179. expect(errors).toHaveLength(1)
  180. expect(errors[0]!.message).toBe('server overloaded')
  181. // turn-end error reason includes the code
  182. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  183. expect(turnEnd).toBeDefined()
  184. if (turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind === 'error') {
  185. expect(turnEnd.data.reason.code).toBe('RATE_LIMIT')
  186. }
  187. })
  188. })
  189. describe('disposed vs aborted branching', () => {
  190. it('handles dispose during model streaming producing reason "disposed"', async () => {
  191. const adapter = new MockAdapter(['hang'])
  192. const ctx = await harness(adapter)
  193. let agent!: ReactLoopAgent
  194. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  195. agent = inner.agentLoop.create(AgentId('scoped'), { model: 'mock' })
  196. }, { inject: ['agentLoop'] }))
  197. const reasons: TurnEndReason[] = []
  198. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  199. send(agent, 'go')
  200. await new Promise(r => setTimeout(r, 30))
  201. await fiber.dispose() // dispose during hang
  202. await agent.done
  203. // The review-fixes test for 'HIGH: disposed status' already covers
  204. // this assertion path. The reason is 'disposed' because isDisposed() is
  205. // checked before the abort signal check in the error path.
  206. expect(reasons).toContainEqual({ kind: 'disposed' })
  207. })
  208. })
  209. describe('structured tool error propagation (the runtime-validation RFC, part 2)', () => {
  210. it('forwards a tool HarnessError onto the tool/result session event', async () => {
  211. const { HarnessError } = await import('@deepseek-ai/dsh-llm')
  212. // First model turn calls the tool; second turn (after the tool result is
  213. // fed back) ends with plain text so the loop settles.
  214. const adapter = new MockAdapter([
  215. toolCallResponse('c1', 'boom', {}),
  216. textResponse('done'),
  217. ])
  218. const ctx = await harness(adapter)
  219. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  220. ctx.tools.register(defineTool({
  221. name: 'boom',
  222. description: 'always fails',
  223. parameters: {},
  224. async execute() {
  225. throw new HarnessError('exploded', 'BOOM')
  226. },
  227. }))
  228. send(agent, 'go')
  229. await waitForIdle(ctx, agent)
  230. const toolResult = agent.session.events.find(e => e.type === 'tool/result')
  231. expect(toolResult?.type === 'tool/result' && toolResult.data.isError).toBe(true)
  232. expect(toolResult?.type === 'tool/result' && toolResult.data.error)
  233. .toEqual({ name: 'HarnessError', code: 'BOOM' })
  234. })
  235. })