coverage-edges.spec.ts 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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, 'go')
  129. await waitForIdle(ctx, agent)
  130. expect(errors).toHaveLength(1)
  131. expect(errors[0]).toMatchObject({ message: 'naked string error', code: 'UNKNOWN' })
  132. expect(adapter.requests).toEqual([])
  133. expect(agent.session.events.some(event => event.type === 'turn/start' || event.type === 'turn/end')).toBe(false)
  134. })
  135. it('normalizes non-Error throws from agent/request waterfall via inline toError in runStep catch', async () => {
  136. const adapter = new MockAdapter([textResponse('irrelevant')])
  137. const ctx = await harness(adapter)
  138. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  139. let threwOnce = false
  140. ctx.on('agent/request', async (_agent, _turn, _step, _options, _next) => {
  141. if (!threwOnce) {
  142. threwOnce = true
  143. throw { code: 500 } // non-Error throw, goes through runStep catch
  144. }
  145. return _next()
  146. })
  147. const errors: Error[] = []
  148. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  149. send(agent, 'go')
  150. await waitForIdle(ctx, agent)
  151. expect(errors).toHaveLength(1)
  152. // String() of { code: 500 } is '[object Object]'
  153. expect(errors[0]!.message).toBe('[object Object]')
  154. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  155. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind === 'error' && turnEnd.data.reason.code).toBe('UNKNOWN')
  156. })
  157. })
  158. describe('coded error data emission', () => {
  159. it('errorData includes code when a coded error (LlmError) is thrown from a plugin', async () => {
  160. const adapter = new MockAdapter([textResponse('turn 1')])
  161. const ctx = await harness(adapter)
  162. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  163. let threwOnce = false
  164. ctx.on('agent/request', async (_agent, _turn, _step, _options, next) => {
  165. if (!threwOnce) {
  166. threwOnce = true
  167. throw new LlmError('server overloaded', 'RATE_LIMIT')
  168. }
  169. return next()
  170. })
  171. const errors: Error[] = []
  172. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  173. send(agent, 'go')
  174. await waitForIdle(ctx, agent)
  175. expect(errors).toHaveLength(1)
  176. expect(errors[0]!.message).toBe('server overloaded')
  177. // turn-end error reason includes the code
  178. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  179. expect(turnEnd).toBeDefined()
  180. if (turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind === 'error') {
  181. expect(turnEnd.data.reason.code).toBe('RATE_LIMIT')
  182. }
  183. })
  184. })
  185. describe('disposed vs aborted branching', () => {
  186. it('handles dispose during model streaming producing reason "disposed"', async () => {
  187. const adapter = new MockAdapter(['hang'])
  188. const ctx = await harness(adapter)
  189. let agent!: ReactLoopAgent
  190. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  191. agent = inner.agentLoop.create(AgentId('scoped'), { model: 'mock' })
  192. }, { inject: ['agentLoop'] }))
  193. const reasons: TurnEndReason[] = []
  194. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  195. send(agent, 'go')
  196. await new Promise(r => setTimeout(r, 30))
  197. await fiber.dispose() // dispose during hang
  198. await agent.done
  199. // Disposal wins abort classification because the error path checks it first.
  200. expect(reasons).toContainEqual({ kind: 'disposed' })
  201. })
  202. })
  203. describe('structured tool error propagation (the runtime-validation RFC, part 2)', () => {
  204. it('forwards a tool HarnessError onto the tool/result session event', async () => {
  205. const { HarnessError } = await import('@deepseek-ai/dsh-llm')
  206. // First model turn calls the tool; second turn (after the tool result is
  207. // fed back) ends with plain text so the loop settles.
  208. const adapter = new MockAdapter([
  209. toolCallResponse('c1', 'boom', {}),
  210. textResponse('done'),
  211. ])
  212. const ctx = await harness(adapter)
  213. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  214. ctx.tools.register(defineTool({
  215. name: 'boom',
  216. description: 'always fails',
  217. parameters: {},
  218. async execute() {
  219. throw new HarnessError('exploded', 'BOOM')
  220. },
  221. }))
  222. send(agent, 'go')
  223. await waitForIdle(ctx, agent)
  224. const toolResult = agent.session.events.find(e => e.type === 'tool/result')
  225. expect(toolResult?.type === 'tool/result' && toolResult.data.isError).toBe(true)
  226. expect(toolResult?.type === 'tool/result' && toolResult.data.error)
  227. .toEqual({ name: 'HarnessError', code: 'BOOM' })
  228. })
  229. })