coverage-edges.spec.ts 11 KB

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