coverage-edges.spec.ts 10 KB

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