coverage-edges.spec.ts 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import LlmService, { CallId, LlmError, StreamChunk, errorChain } from '@deepseek-ai/dsh-llm'
  4. import SessionStore, { SessionId, TurnEndReason } from '@deepseek-ai/dsh-session'
  5. import type { SessionEvent } from '@deepseek-ai/dsh-session'
  6. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  7. import ToolRegistry, { defineContentToolFixture } from '@deepseek-ai/dsh-tools'
  8. import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent'
  9. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  10. import { MockAdapter, textResponse, toolCallResponse } from './mock-adapter.ts'
  11. function driverDone(agent: Agent): Promise<void> {
  12. return (agent as Agent & { done: Promise<void> }).done
  13. }
  14. async function harness(adapter: MockAdapter) {
  15. const ctx = new Context()
  16. await ctx.plugin(LlmService)
  17. await ctx.plugin(SessionStore)
  18. await ctx.plugin(SystemPrompt)
  19. await ctx.plugin(ToolRegistry)
  20. await ctx.plugin(AgentRegistry)
  21. await ctx.plugin(AgentLoop, { agents: [] })
  22. ctx.llm.registerAdapter(['mock'], adapter)
  23. return ctx
  24. }
  25. function waitForIdle(ctx: Context, agent: Agent): Promise<void> {
  26. return new Promise((resolve) => {
  27. const dispose = ctx.on('agent/status', (subject, status) => {
  28. if (subject === agent && status === 'idle') {
  29. dispose()
  30. resolve()
  31. }
  32. })
  33. })
  34. }
  35. function send(agent: Agent, text: string) {
  36. agent.followup({ content: [{ type: 'text', text }], source: { kind: 'user' } })
  37. }
  38. describe('tool JSON parse', () => {
  39. it('passes through non-JSON arguments string without crashing', async () => {
  40. const adapter = new MockAdapter([
  41. // model emits tool-call with malformed arguments (not valid JSON)
  42. [
  43. { type: 'block-start' as const, index: 0, blockType: 'tool-call' as const },
  44. { type: 'block-end' as const, index: 0, block: { type: 'tool-call' as const, id: CallId('c1'), name: 'echo', arguments: 'not json' } },
  45. { type: 'finish' as const, reason: { kind: 'tool-calls' as const } },
  46. ] satisfies StreamChunk[],
  47. textResponse('done'),
  48. ])
  49. const ctx = await harness(adapter)
  50. ctx.tools.register(defineContentToolFixture({
  51. name: 'echo',
  52. description: 'echo tool',
  53. parameters: { input: { type: 'string' } },
  54. async execute(args: unknown) {
  55. return [{ type: 'text', text: typeof args === 'string' ? `raw: ${args}` : JSON.stringify(args) }]
  56. },
  57. }))
  58. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  59. send(agent, 'use tool')
  60. await waitForIdle(ctx, agent)
  61. // tool/call event should have recorded the raw arguments string
  62. const callEvent = agent.session.events.find(e => e.type === 'tool/call')
  63. expect(callEvent).toBeDefined()
  64. if (callEvent!.type === 'tool/call') {
  65. expect(callEvent!.data.arguments).toBe('not json')
  66. }
  67. // the loop did not crash — a result was produced
  68. expect(agent.session.events.some(e => e.type === 'tool/result')).toBe(true)
  69. })
  70. it('uses empty object when tool-call arguments are empty string', async () => {
  71. const adapter = new MockAdapter([
  72. [
  73. { type: 'block-start' as const, index: 0, blockType: 'tool-call' as const },
  74. { type: 'block-end' as const, index: 0, block: { type: 'tool-call' as const, id: CallId('c1'), name: 'noarg', arguments: '' } },
  75. { type: 'finish' as const, reason: { kind: 'tool-calls' as const } },
  76. ] satisfies StreamChunk[],
  77. textResponse('done'),
  78. ])
  79. const ctx = await harness(adapter)
  80. ctx.tools.register(defineContentToolFixture({
  81. name: 'noarg',
  82. description: 'no-arg tool',
  83. parameters: {},
  84. async execute() {
  85. return [{ type: 'text', text: 'ran with empty args' }]
  86. },
  87. }))
  88. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  89. send(agent, 'use tool')
  90. await waitForIdle(ctx, agent)
  91. expect(agent.session.events.some(e => e.type === 'tool/result')).toBe(true)
  92. })
  93. })
  94. describe('thrown-value propagation', () => {
  95. it('preserves non-Error throws from pre-commit dispatch validation', async () => {
  96. const adapter = new MockAdapter([textResponse('ok')])
  97. const ctx = await harness(adapter)
  98. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  99. let threwOnce = false
  100. ctx.on('internal/dispatch', (_mode, name, args) => {
  101. if (name !== 'session/event') return
  102. const event = args[1] as SessionEvent
  103. if (event.type === 'turn/start' && !threwOnce) {
  104. threwOnce = true
  105. throw 'naked string error'
  106. }
  107. })
  108. const errors: unknown[] = []
  109. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  110. send(agent, 'fails before turn start')
  111. send(agent, 'survives as the next item')
  112. await waitForIdle(ctx, agent)
  113. expect(errors).toHaveLength(1)
  114. expect(errors[0]).toBe('naked string error')
  115. expect(adapter.requests).toHaveLength(1)
  116. const starts = agent.session.events.filter(event => event.type === 'turn/start')
  117. const ends = agent.session.events.filter(event => event.type === 'turn/end')
  118. const messages = agent.session.events.filter(event => event.type === 'user/message')
  119. expect(starts).toHaveLength(1)
  120. // The rejected turn/start committed nothing, so the survivor reuses turn 1
  121. // and the rejected prompt does not leak into it.
  122. expect(starts[0]?.type === 'turn/start' && starts[0].data.turn).toBe(1)
  123. expect(ends).toHaveLength(1)
  124. expect(messages).toHaveLength(1)
  125. expect(messages[0]?.type === 'user/message' && messages[0].data.content).toEqual([
  126. { type: 'text', text: 'survives as the next item' },
  127. ])
  128. })
  129. it('preserves non-Error throws from the agent/request waterfall', async () => {
  130. const adapter = new MockAdapter([textResponse('irrelevant')])
  131. const ctx = await harness(adapter)
  132. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  133. let threwOnce = false
  134. ctx.on('agent/request', async (_agent, _turn, _step, _signal, next) => {
  135. if (!threwOnce) {
  136. threwOnce = true
  137. throw { code: 500 }
  138. }
  139. return next()
  140. })
  141. const errors: unknown[] = []
  142. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  143. send(agent, 'go')
  144. await waitForIdle(ctx, agent)
  145. expect(errors).toHaveLength(1)
  146. expect(errors[0]).toEqual({ code: 500 })
  147. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  148. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind === 'error'
  149. && ('failure' in turnEnd.data.reason ? turnEnd.data.reason.failure.code : turnEnd.data.reason.code))
  150. .toBeUndefined()
  151. })
  152. })
  153. describe('coded error data emission', () => {
  154. it('errorData includes code when a coded error (LlmError) is thrown from a plugin', async () => {
  155. const adapter = new MockAdapter([textResponse('turn 1')])
  156. const ctx = await harness(adapter)
  157. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  158. let threwOnce = false
  159. ctx.on('agent/request', async (_agent, _turn, _step, _signal, next) => {
  160. if (!threwOnce) {
  161. threwOnce = true
  162. throw new LlmError('server overloaded', 'RATE_LIMIT')
  163. }
  164. return next()
  165. })
  166. const errors: unknown[] = []
  167. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  168. send(agent, 'go')
  169. await waitForIdle(ctx, agent)
  170. expect(errors).toHaveLength(1)
  171. expect(errorChain(errors[0])).toBe('server overloaded')
  172. // turn-end error reason includes the code
  173. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  174. expect(turnEnd).toBeDefined()
  175. if (turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind === 'error') {
  176. expect('failure' in turnEnd.data.reason ? turnEnd.data.reason.failure.code : turnEnd.data.reason.code)
  177. .toBe('RATE_LIMIT')
  178. }
  179. })
  180. })
  181. describe('disposed vs aborted branching', () => {
  182. it('handles dispose during model streaming producing reason "disposed"', async () => {
  183. const adapter = new MockAdapter(['hang'])
  184. const ctx = await harness(adapter)
  185. let agent!: Agent
  186. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  187. agent = inner.agentLoop.create(SessionId('scoped'), { provider: 'mock', model: 'mock' })
  188. }, { inject: ['agentLoop'] }))
  189. const reasons: TurnEndReason[] = []
  190. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  191. send(agent, 'go')
  192. await new Promise(r => setTimeout(r, 30))
  193. await fiber.dispose() // dispose during hang
  194. await driverDone(agent)
  195. // Disposal wins abort classification because the error path checks it first.
  196. expect(reasons).toContainEqual({ kind: 'disposed' })
  197. })
  198. })
  199. describe('structured tool error propagation (the runtime-validation Agent Note, part 2)', () => {
  200. it('forwards a tool HarnessError onto the tool/result session event', async () => {
  201. const { HarnessError } = await import('@deepseek-ai/dsh-llm')
  202. // First model turn calls the tool; second turn (after the tool result is
  203. // fed back) ends with plain text so the loop settles.
  204. const adapter = new MockAdapter([
  205. toolCallResponse('c1', 'boom', {}),
  206. textResponse('done'),
  207. ])
  208. const ctx = await harness(adapter)
  209. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  210. ctx.tools.register(defineContentToolFixture({
  211. name: 'boom',
  212. description: 'always fails',
  213. parameters: {},
  214. async execute() {
  215. throw new HarnessError('exploded', 'BOOM')
  216. },
  217. }))
  218. send(agent, 'go')
  219. await waitForIdle(ctx, agent)
  220. const toolResult = agent.session.events.find(e => e.type === 'tool/result')
  221. expect(toolResult?.type === 'tool/result' && toolResult.data.isError).toBe(true)
  222. expect(toolResult?.type === 'tool/result' && toolResult.data.error)
  223. .toEqual({ name: 'HarnessError', code: 'BOOM' })
  224. })
  225. })