coverage-edges.spec.ts 10 KB

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