coverage-edges.spec.ts 11 KB

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