coverage-edges.spec.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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 SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  6. import ToolRegistry, { defineTool } from '@deepseek-ai/dsh-tools'
  7. import AgentRegistry, { AgentId } from '@deepseek-ai/dsh-agent'
  8. import AgentLoop, { ReactLoopAgent } from '@deepseek-ai/dsh-agent-loop'
  9. import { MockAdapter, textResponse, toolCallResponse } from './mock-adapter.ts'
  10. async function harness(adapter: MockAdapter) {
  11. const ctx = new Context()
  12. await ctx.plugin(LlmService)
  13. await ctx.plugin(SessionStore)
  14. await ctx.plugin(SystemPrompt)
  15. await ctx.plugin(ToolRegistry)
  16. await ctx.plugin(AgentRegistry)
  17. await ctx.plugin(AgentLoop, { agents: [] })
  18. ctx.llm.registerAdapter(['mock'], adapter)
  19. return ctx
  20. }
  21. function waitForIdle(ctx: Context, agent: ReactLoopAgent): Promise<void> {
  22. return new Promise((resolve) => {
  23. const dispose = ctx.on('agent/status', (subject, status) => {
  24. if (subject === agent && status === 'idle') {
  25. dispose()
  26. resolve()
  27. }
  28. })
  29. })
  30. }
  31. function send(agent: ReactLoopAgent, text: string) {
  32. agent.send([{ type: 'text', text }])
  33. }
  34. describe('turn boundary listener throws (handled in-turn, loop survives)', () => {
  35. it('a throwing agent/turn-start listener surfaces via agent/error and the loop survives', async () => {
  36. // The agent/turn-start emit happens AFTER turn/start is appended to the log,
  37. // so a throwing listener is handled inside runTurn (the turn is balanced and
  38. // closed via failTurn → agent/error), NOT rethrown to the runLoop backstop.
  39. // The second turn should proceed normally and consume the first script entry.
  40. const adapter = new MockAdapter([textResponse('turn 2')])
  41. const ctx = await harness(adapter)
  42. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  43. let threwOnce = false
  44. ctx.on('agent/turn-start', () => {
  45. if (!threwOnce) {
  46. threwOnce = true
  47. throw new Error('broken turn-start listener')
  48. }
  49. })
  50. const errors: Error[] = []
  51. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  52. send(agent, 'first')
  53. await waitForIdle(ctx, agent)
  54. expect(errors.map(e => e.message)).toEqual(['broken turn-start listener'])
  55. // The turn is balanced: its turn/start was logged, so a turn/end was owed
  56. // and appended (decided from the log, not a flag).
  57. expect(agent.session.events.at(-1)?.type).toBe('turn/end')
  58. // loop survives: second turn works fine and makes the model call
  59. send(agent, 'second')
  60. await waitForIdle(ctx, agent)
  61. expect(adapter.requests).toHaveLength(1)
  62. expect(adapter.requests[0]!.messages.some(m => m.content.some(b => 'text' in b && b.text === 'second'))).toBe(true)
  63. })
  64. it('a throwing agent/turn-end listener surfaces via agent/error and the loop survives', async () => {
  65. const adapter = new MockAdapter([textResponse('turn 1'), textResponse('turn 2')])
  66. const ctx = await harness(adapter)
  67. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  68. let threwOnce = false
  69. ctx.on('agent/turn-end', () => {
  70. if (!threwOnce) {
  71. threwOnce = true
  72. throw new Error('broken turn-end listener')
  73. }
  74. })
  75. const errors: Error[] = []
  76. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  77. send(agent, 'first')
  78. await waitForIdle(ctx, agent)
  79. // The turn-end throw happens after the model call is complete, so turn 1's
  80. // request is consumed. turn/end is already in the log (append pushes before
  81. // notifying), so the turn is balanced; the error is surfaced via agent/error.
  82. expect(errors.map(e => e.message)).toEqual(['broken turn-end listener'])
  83. // loop survives: second turn works fine
  84. send(agent, 'second')
  85. await waitForIdle(ctx, agent)
  86. expect(adapter.requests).toHaveLength(2)
  87. })
  88. it('a pre-push turn/start failure (non-serializable source) is rethrown to the runLoop backstop', async () => {
  89. // A non-serializable message source makes the turn/start append throw BEFORE
  90. // the event is pushed (Session.append validates before push), so turn/start
  91. // never enters the log. runTurn sees no logged turn/start and rethrows; the
  92. // runLoop backstop reports via agent/error (step 0) + the logger and the
  93. // driver survives. This is the ONLY path that reaches the backstop.
  94. const adapter = new MockAdapter([textResponse('turn 2')])
  95. const ctx = await harness(adapter)
  96. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  97. const errors: { turn: number; step: number; message: string }[] = []
  98. ctx.on('agent/error', (_a, turn, step, error) => void errors.push({ turn, step, message: error.message }))
  99. // A non-serializable source (BigInt) on the queued message.
  100. agent.send([{ type: 'text', text: 'first' }], { source: { kind: 'plugin', plugin: 'p', bad: 1n } as never })
  101. await waitForIdle(ctx, agent)
  102. expect(errors).toHaveLength(1)
  103. expect(errors[0]!.step).toBe(0)
  104. expect(errors[0]!.message).toMatch(/non-JSON-serializable/)
  105. // No turn boundary was written (the turn/start append threw before push).
  106. expect(agent.session.events.some(e => e.type === 'turn/start')).toBe(false)
  107. // loop survives: a well-formed second turn runs normally.
  108. send(agent, 'second')
  109. await waitForIdle(ctx, agent)
  110. expect(adapter.requests).toHaveLength(1)
  111. })
  112. })
  113. describe('tool JSON parse', () => {
  114. it('passes through non-JSON arguments string without crashing', async () => {
  115. const adapter = new MockAdapter([
  116. // model emits tool-call with malformed arguments (not valid JSON)
  117. [
  118. { type: 'block-start' as const, index: 0, blockType: 'tool-call' as const },
  119. { type: 'block-end' as const, index: 0, block: { type: 'tool-call' as const, id: CallId('c1'), name: 'echo', arguments: 'not json' } },
  120. { type: 'finish' as const, reason: { kind: 'tool-calls' as const } },
  121. ] satisfies StreamChunk[],
  122. textResponse('done'),
  123. ])
  124. const ctx = await harness(adapter)
  125. ctx.tools.register(defineTool({
  126. name: 'echo',
  127. description: 'echo tool',
  128. parameters: { input: { type: 'string' } },
  129. async execute(args: unknown) {
  130. return [{ type: 'text', text: typeof args === 'string' ? `raw: ${args}` : JSON.stringify(args) }]
  131. },
  132. }))
  133. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  134. send(agent, 'use tool')
  135. await waitForIdle(ctx, agent)
  136. // tool/call event should have recorded the raw arguments string
  137. const callEvent = agent.session.events.find(e => e.type === 'tool/call')
  138. expect(callEvent).toBeDefined()
  139. if (callEvent!.type === 'tool/call') {
  140. expect(callEvent!.data.arguments).toBe('not json')
  141. }
  142. // the loop did not crash — a result was produced
  143. expect(agent.session.events.some(e => e.type === 'tool/result')).toBe(true)
  144. })
  145. it('uses empty object when tool-call arguments are empty string', async () => {
  146. const adapter = new MockAdapter([
  147. [
  148. { type: 'block-start' as const, index: 0, blockType: 'tool-call' as const },
  149. { type: 'block-end' as const, index: 0, block: { type: 'tool-call' as const, id: CallId('c1'), name: 'noarg', arguments: '' } },
  150. { type: 'finish' as const, reason: { kind: 'tool-calls' as const } },
  151. ] satisfies StreamChunk[],
  152. textResponse('done'),
  153. ])
  154. const ctx = await harness(adapter)
  155. ctx.tools.register(defineTool({
  156. name: 'noarg',
  157. description: 'no-arg tool',
  158. parameters: {},
  159. async execute() {
  160. return [{ type: 'text', text: 'ran with empty args' }]
  161. },
  162. }))
  163. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  164. send(agent, 'use tool')
  165. await waitForIdle(ctx, agent)
  166. expect(agent.session.events.some(e => e.type === 'tool/result')).toBe(true)
  167. })
  168. })
  169. describe('toError normalization', () => {
  170. it('normalizes non-Error throws from turn-start listeners via toError', async () => {
  171. const adapter = new MockAdapter([textResponse('ok')])
  172. const ctx = await harness(adapter)
  173. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  174. let threwOnce = false
  175. ctx.on('agent/turn-start', () => {
  176. if (!threwOnce) {
  177. threwOnce = true
  178. throw 'naked string error' // non-Error throw, normalized via toError
  179. }
  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('naked string error')
  187. // A non-Error throw is wrapped in a HarnessError with code UNKNOWN, so the
  188. // turn-end error reason carries a routable code instead of degrading.
  189. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  190. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind === 'error' && turnEnd.data.reason.code).toBe('UNKNOWN')
  191. })
  192. it('normalizes non-Error throws from agent/request waterfall via inline toError in runStep catch', async () => {
  193. const adapter = new MockAdapter([textResponse('irrelevant')])
  194. const ctx = await harness(adapter)
  195. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  196. let threwOnce = false
  197. ctx.on('agent/request', async (_agent, _turn, _step, _options, _next) => {
  198. if (!threwOnce) {
  199. threwOnce = true
  200. throw { code: 500 } // non-Error throw, goes through runStep catch
  201. }
  202. return _next()
  203. })
  204. const errors: Error[] = []
  205. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  206. send(agent, 'go')
  207. await waitForIdle(ctx, agent)
  208. expect(errors).toHaveLength(1)
  209. // String() of { code: 500 } is '[object Object]'
  210. expect(errors[0]!.message).toBe('[object Object]')
  211. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  212. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind === 'error' && turnEnd.data.reason.code).toBe('UNKNOWN')
  213. })
  214. })
  215. describe('coded error data emission', () => {
  216. it('errorData includes code when a coded error (LlmError) is thrown from a plugin', async () => {
  217. const adapter = new MockAdapter([textResponse('turn 1')])
  218. const ctx = await harness(adapter)
  219. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  220. let threwOnce = false
  221. ctx.on('agent/request', async (_agent, _turn, _step, _options, next) => {
  222. if (!threwOnce) {
  223. threwOnce = true
  224. throw new LlmError('server overloaded', 'RATE_LIMIT')
  225. }
  226. return next()
  227. })
  228. const errors: Error[] = []
  229. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  230. send(agent, 'go')
  231. await waitForIdle(ctx, agent)
  232. expect(errors).toHaveLength(1)
  233. expect(errors[0]!.message).toBe('server overloaded')
  234. // turn-end error reason includes the code
  235. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  236. expect(turnEnd).toBeDefined()
  237. if (turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind === 'error') {
  238. expect(turnEnd.data.reason.code).toBe('RATE_LIMIT')
  239. }
  240. })
  241. })
  242. describe('disposed vs aborted branching', () => {
  243. it('handles dispose during model streaming producing reason "disposed"', async () => {
  244. const adapter = new MockAdapter(['hang'])
  245. const ctx = await harness(adapter)
  246. let agent!: ReactLoopAgent
  247. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  248. agent = inner.agentLoop.create(AgentId('scoped'), { model: 'mock' })
  249. }, { inject: ['agentLoop'] }))
  250. const reasons: TurnEndReason[] = []
  251. ctx.on('agent/turn-end', (_agent, _turn, reason) => void reasons.push(reason))
  252. send(agent, 'go')
  253. await new Promise(r => setTimeout(r, 30))
  254. await fiber.dispose() // dispose during hang
  255. await agent.done
  256. // The review-fixes test for 'HIGH: disposed status' already covers
  257. // this assertion path. The reason is 'disposed' because isDisposed() is
  258. // checked before the abort signal check in the error path.
  259. expect(reasons).toContainEqual({ kind: 'disposed' })
  260. })
  261. })
  262. describe('structured tool error propagation (the runtime-validation RFC, part 2)', () => {
  263. it('forwards a tool HarnessError onto the tool/result session event', async () => {
  264. const { HarnessError } = await import('@deepseek-ai/dsh-llm')
  265. // First model turn calls the tool; second turn (after the tool result is
  266. // fed back) ends with plain text so the loop settles.
  267. const adapter = new MockAdapter([
  268. toolCallResponse('c1', 'boom', {}),
  269. textResponse('done'),
  270. ])
  271. const ctx = await harness(adapter)
  272. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  273. ctx.tools.register(defineTool({
  274. name: 'boom',
  275. description: 'always fails',
  276. parameters: {},
  277. async execute() {
  278. throw new HarnessError('exploded', 'BOOM')
  279. },
  280. }))
  281. send(agent, 'go')
  282. await waitForIdle(ctx, agent)
  283. const toolResult = agent.session.events.find(e => e.type === 'tool/result')
  284. expect(toolResult?.type === 'tool/result' && toolResult.data.isError).toBe(true)
  285. expect(toolResult?.type === 'tool/result' && toolResult.data.error)
  286. .toEqual({ name: 'HarnessError', code: 'BOOM' })
  287. })
  288. })