coverage-edges.spec.ts 11 KB

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