coverage-edges.spec.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import LlmService, { CallId, LlmError, StreamChunk, errorChain } 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, { defineContentToolFixture } 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.followup({ content: [{ type: 'text', text }], source: { kind: 'user' } })
  37. }
  38. describe('tool JSON parse', () => {
  39. it('passes through non-JSON arguments string without crashing', async () => {
  40. const adapter = new MockAdapter([
  41. // model emits tool-call with malformed arguments (not valid JSON)
  42. [
  43. { type: 'block-start' as const, index: 0, blockType: 'tool-call' as const },
  44. { type: 'block-end' as const, index: 0, block: { type: 'tool-call' as const, id: CallId('c1'), name: 'echo', arguments: 'not json' } },
  45. { type: 'finish' as const, reason: { kind: 'tool-calls' as const } },
  46. ] satisfies StreamChunk[],
  47. textResponse('done'),
  48. ])
  49. const ctx = await harness(adapter)
  50. ctx.tools.register(defineContentToolFixture({
  51. name: 'echo',
  52. description: 'echo tool',
  53. parameters: { input: { type: 'string' } },
  54. async execute(args: unknown) {
  55. return [{ type: 'text', text: typeof args === 'string' ? `raw: ${args}` : JSON.stringify(args) }]
  56. },
  57. }))
  58. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  59. send(agent, 'use tool')
  60. await waitForIdle(ctx, agent)
  61. // tool/call event should have recorded the raw arguments string
  62. const callEvent = agent.session.events.find(e => e.type === 'tool/call')
  63. expect(callEvent).toBeDefined()
  64. if (callEvent!.type === 'tool/call') {
  65. expect(callEvent!.data.arguments).toBe('not json')
  66. }
  67. // the loop did not crash — a result was produced
  68. expect(agent.session.events.some(e => e.type === 'tool/result')).toBe(true)
  69. })
  70. it('uses empty object when tool-call arguments are empty string', async () => {
  71. const adapter = new MockAdapter([
  72. [
  73. { type: 'block-start' as const, index: 0, blockType: 'tool-call' as const },
  74. { type: 'block-end' as const, index: 0, block: { type: 'tool-call' as const, id: CallId('c1'), name: 'noarg', arguments: '' } },
  75. { type: 'finish' as const, reason: { kind: 'tool-calls' as const } },
  76. ] satisfies StreamChunk[],
  77. textResponse('done'),
  78. ])
  79. const ctx = await harness(adapter)
  80. ctx.tools.register(defineContentToolFixture({
  81. name: 'noarg',
  82. description: 'no-arg tool',
  83. parameters: {},
  84. async execute() {
  85. return [{ type: 'text', text: 'ran with empty args' }]
  86. },
  87. }))
  88. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  89. send(agent, 'use tool')
  90. await waitForIdle(ctx, agent)
  91. expect(agent.session.events.some(e => e.type === 'tool/result')).toBe(true)
  92. })
  93. })
  94. describe('thrown-value propagation', () => {
  95. it('preserves non-Error throws from pre-commit dispatch validation', async () => {
  96. const adapter = new MockAdapter([textResponse('ok')])
  97. const ctx = await harness(adapter)
  98. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  99. let threwOnce = false
  100. ctx.on('internal/dispatch', (_mode, name, args) => {
  101. if (name !== 'session/event') return
  102. const event = args[1] as SessionEvent
  103. if (event.type === 'turn/start' && !threwOnce) {
  104. threwOnce = true
  105. throw 'naked string error'
  106. }
  107. })
  108. const errors: unknown[] = []
  109. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  110. send(agent, 'fails before turn start')
  111. send(agent, 'survives as the next item')
  112. await waitForIdle(ctx, agent)
  113. expect(errors).toHaveLength(1)
  114. expect(errors[0]).toBe('naked string error')
  115. expect(adapter.requests).toHaveLength(1)
  116. const starts = agent.session.events.filter(event => event.type === 'turn/start')
  117. const ends = agent.session.events.filter(event => event.type === 'turn/end')
  118. const messages = agent.session.events.filter(event => event.type === 'user/message')
  119. expect(starts).toHaveLength(1)
  120. // The rejected turn/start committed nothing, so the survivor reuses turn 1
  121. // and the rejected prompt does not leak into it.
  122. expect(starts[0]?.type === 'turn/start' && starts[0].data.turn).toBe(1)
  123. expect(ends).toHaveLength(1)
  124. expect(messages).toHaveLength(1)
  125. expect(messages[0]?.type === 'user/message' && messages[0].data.content).toEqual([
  126. { type: 'text', text: 'survives as the next item' },
  127. ])
  128. })
  129. it('preserves non-Error throws from the agent/request waterfall', async () => {
  130. const adapter = new MockAdapter([textResponse('irrelevant')])
  131. const ctx = await harness(adapter)
  132. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  133. let threwOnce = false
  134. ctx.on('agent/request', async (_agent, _turn, _step, _signal, next) => {
  135. if (!threwOnce) {
  136. threwOnce = true
  137. throw { code: 500 }
  138. }
  139. return next()
  140. })
  141. const errors: unknown[] = []
  142. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  143. send(agent, 'go')
  144. await waitForIdle(ctx, agent)
  145. expect(errors).toHaveLength(1)
  146. expect(errors[0]).toEqual({ code: 500 })
  147. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  148. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind === 'error'
  149. && ('failure' in turnEnd.data.reason ? turnEnd.data.reason.failure.code : turnEnd.data.reason.code))
  150. .toBeUndefined()
  151. })
  152. })
  153. describe('coded error data emission', () => {
  154. it('errorData includes code when a coded error (LlmError) is thrown from a plugin', async () => {
  155. const adapter = new MockAdapter([textResponse('turn 1')])
  156. const ctx = await harness(adapter)
  157. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  158. let threwOnce = false
  159. ctx.on('agent/request', async (_agent, _turn, _step, _signal, next) => {
  160. if (!threwOnce) {
  161. threwOnce = true
  162. throw new LlmError('server overloaded', 'RATE_LIMIT')
  163. }
  164. return next()
  165. })
  166. const errors: unknown[] = []
  167. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  168. send(agent, 'go')
  169. await waitForIdle(ctx, agent)
  170. expect(errors).toHaveLength(1)
  171. expect(errorChain(errors[0])).toBe('server overloaded')
  172. // turn-end error reason includes the code
  173. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  174. expect(turnEnd).toBeDefined()
  175. if (turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind === 'error') {
  176. expect('failure' in turnEnd.data.reason ? turnEnd.data.reason.failure.code : turnEnd.data.reason.code)
  177. .toBe('RATE_LIMIT')
  178. }
  179. })
  180. })
  181. describe('disposed vs aborted branching', () => {
  182. it('handles dispose during model streaming producing reason "disposed"', async () => {
  183. const adapter = new MockAdapter(['hang'])
  184. const ctx = await harness(adapter)
  185. let agent!: Agent
  186. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  187. agent = inner.agentLoop.create(SessionId('scoped'), { provider: 'mock', model: 'mock' })
  188. }, { inject: ['agentLoop'] }))
  189. const reasons: TurnEndReason[] = []
  190. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  191. send(agent, 'go')
  192. await new Promise(r => setTimeout(r, 30))
  193. await fiber.dispose() // dispose during hang
  194. await driverDone(agent)
  195. // Disposal wins abort classification because the error path checks it first.
  196. expect(reasons).toContainEqual({ kind: 'disposed' })
  197. })
  198. })
  199. describe('structured tool error propagation (the runtime-validation Agent Note, part 2)', () => {
  200. it('forwards a tool HarnessError onto the tool/result session event', async () => {
  201. const { HarnessError } = await import('@deepseek-ai/dsh-llm')
  202. // First model turn calls the tool; second turn (after the tool result is
  203. // fed back) ends with plain text so the loop settles.
  204. const adapter = new MockAdapter([
  205. toolCallResponse('c1', 'boom', {}),
  206. textResponse('done'),
  207. ])
  208. const ctx = await harness(adapter)
  209. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  210. ctx.tools.register(defineContentToolFixture({
  211. name: 'boom',
  212. description: 'always fails',
  213. parameters: {},
  214. async execute() {
  215. throw new HarnessError('exploded', 'BOOM')
  216. },
  217. }))
  218. send(agent, 'go')
  219. await waitForIdle(ctx, agent)
  220. const toolResult = agent.session.events.find(e => e.type === 'tool/result')
  221. expect(toolResult?.type === 'tool/result' && toolResult.data.isError).toBe(true)
  222. expect(toolResult?.type === 'tool/result' && toolResult.data.error)
  223. .toEqual({ name: 'HarnessError', code: 'BOOM' })
  224. })
  225. })
  226. describe('retry() edges', () => {
  227. it('throws while a turn runs with no request-error window open', async () => {
  228. const adapter = new MockAdapter(['hang'])
  229. const ctx = await harness(adapter)
  230. const agent = ctx.agentLoop.create(SessionId('retry-busy'), { provider: 'mock', model: 'mock' })
  231. send(agent, 'go')
  232. // Wait until the hung request is in flight (the run owns this.abort).
  233. await new Promise(r => setTimeout(r, 30))
  234. expect(() => { agent.retry() }).toThrow('cannot retry while busy')
  235. agent.cancel({ kind: 'user' })
  236. await agent.whenIdle()
  237. })
  238. it('ignores a retry request arriving after the recovery window was aborted', async () => {
  239. const { LlmError } = await import('@deepseek-ai/dsh-llm')
  240. const adapter = new MockAdapter([
  241. () => { throw new LlmError('busy', 'RATE_LIMIT') },
  242. textResponse('never used'),
  243. ])
  244. const ctx = await harness(adapter)
  245. const agent = ctx.agentLoop.create(SessionId('retry-after-cancel'), { provider: 'mock', model: 'mock' })
  246. ctx.on('agent/request-error', async (subject) => {
  247. // Cancellation lands first; the window survives structurally but its
  248. // signal is aborted, so the request must not arm a retry turn.
  249. subject.cancel({ kind: 'user' })
  250. subject.retry()
  251. })
  252. send(agent, 'go')
  253. await agent.whenIdle()
  254. // One failed request, no retry turn.
  255. expect(adapter.requests).toHaveLength(1)
  256. const ends = agent.session.events.filter(e => e.type === 'turn/end')
  257. expect(ends).toHaveLength(1)
  258. })
  259. it('completed recovery does not retry when cancellation raced the waterfall', async () => {
  260. const { LlmError } = await import('@deepseek-ai/dsh-llm')
  261. const adapter = new MockAdapter([
  262. () => { throw new LlmError('busy', 'RATE_LIMIT') },
  263. ])
  264. const ctx = await harness(adapter)
  265. const agent = ctx.agentLoop.create(SessionId('retry-raced'), { provider: 'mock', model: 'mock' })
  266. ctx.on('agent/request-error', async (subject, _turn, _step, _error, _failure, signal, next) => {
  267. await next()
  268. // Recovery completes and requested the retry, but the turn signal
  269. // aborts before the loop reads the window.
  270. subject.retry()
  271. subject.cancel({ kind: 'user' })
  272. expect(signal.aborted).toBe(true)
  273. })
  274. send(agent, 'go')
  275. await agent.whenIdle()
  276. expect(adapter.requests).toHaveLength(1)
  277. const end = agent.session.events.findLast(e => e.type === 'turn/end')
  278. expect(end?.type === 'turn/end' && end.data.reason.kind).toBe('aborted')
  279. })
  280. })
  281. describe('stream failure edges', () => {
  282. it('rethrows a mid-stream throw that carries no adapter failure facts', async () => {
  283. const adapter = new MockAdapter([textResponse('will be vetoed')])
  284. const ctx = await harness(adapter)
  285. const agent = ctx.agentLoop.create(SessionId('stream-no-facts'), { provider: 'mock', model: 'mock' })
  286. let recoveries = 0
  287. ctx.on('agent/request-error', async () => { recoveries += 1 })
  288. // A pre-commit chunk veto throws INSIDE the stream-consumption try, but it
  289. // is not an adapter-boundary failure, so llmFailureOf yields no facts.
  290. let vetoed = false
  291. ctx.on('internal/dispatch', (_mode, name, args) => {
  292. if (name !== 'session/event') return
  293. const event = args[1] as SessionEvent
  294. if (event.type === 'assistant/chunk' && !vetoed) {
  295. vetoed = true
  296. throw new Error('reject the first chunk')
  297. }
  298. })
  299. send(agent, 'go')
  300. await agent.whenIdle()
  301. // No facts -> not offered to recovery; the turn fails through settle().
  302. expect(recoveries).toBe(0)
  303. const end = agent.session.events.findLast(e => e.type === 'turn/end')
  304. expect(end?.type === 'turn/end' && end.data.reason.kind).toBe('error')
  305. })
  306. })
  307. describe('post-turn continuation edges', () => {
  308. it('an agent/idle listener that enqueues a waking prompt preempts continueOrIdle', async () => {
  309. const adapter = new MockAdapter([textResponse('one'), textResponse('two')])
  310. const ctx = await harness(adapter)
  311. const agent = ctx.agentLoop.create(SessionId('idle-preempt'), { provider: 'mock', model: 'mock' })
  312. let injected = false
  313. ctx.on('agent/idle', (subject) => {
  314. if (subject !== agent || injected) return
  315. injected = true
  316. // kick() installs the next admission synchronously, so the following
  317. // continueOrIdle() sees an abort owner and yields to it.
  318. send(agent, 'follow-up from idle listener')
  319. })
  320. send(agent, 'go')
  321. await agent.whenIdle()
  322. expect(adapter.requests).toHaveLength(2)
  323. const starts = agent.session.events.filter(e => e.type === 'turn/start')
  324. expect(starts).toHaveLength(2)
  325. // The busy interval never broke between the turns: one running->idle cycle.
  326. })
  327. it('whenIdle resolves for a waiter whose awaited run fails', async () => {
  328. const adapter = new MockAdapter([textResponse('unused')])
  329. const ctx = await harness(adapter)
  330. const agent = ctx.agentLoop.create(SessionId('whenidle-reject'), { provider: 'mock', model: 'mock' })
  331. let rejected = false
  332. ctx.on('internal/dispatch', (_mode, name, args) => {
  333. if (name !== 'session/event') return
  334. const event = args[1] as SessionEvent
  335. if (event.type === 'turn/start' && !rejected) {
  336. rejected = true
  337. throw new Error('veto turn start while a waiter is pending')
  338. }
  339. })
  340. send(agent, 'go')
  341. await expect(agent.whenIdle()).resolves.toBeUndefined()
  342. expect(agent.status).toBe('idle')
  343. })
  344. })
  345. describe('tool result meta persistence', () => {
  346. it('records a presentationMeta payload on the tool/result event', async () => {
  347. const { defineTool } = await import('@deepseek-ai/dsh-tools')
  348. const adapter = new MockAdapter([
  349. toolCallResponse('c1', 'meta-tool', {}),
  350. textResponse('done'),
  351. ])
  352. const ctx = await harness(adapter)
  353. const agent = ctx.agentLoop.create(SessionId('tool-meta'), { provider: 'mock', model: 'mock' })
  354. ctx.tools.register(defineTool({
  355. name: 'meta-tool',
  356. description: 'carries presentation meta',
  357. parameters: {},
  358. output: {
  359. schema: { type: 'string' },
  360. render: (_args, value) => [{ type: 'text', text: value }],
  361. presentationMeta: () => ({ presentation: 'diff-card' }),
  362. },
  363. async execute() {
  364. return 'ran'
  365. },
  366. }))
  367. send(agent, 'go')
  368. await waitForIdle(ctx, agent)
  369. const result = agent.session.events.find(e => e.type === 'tool/result')
  370. expect(result?.type === 'tool/result' && result.data.meta).toEqual({ presentation: 'diff-card' })
  371. })
  372. })
  373. describe('turn close failure containment', () => {
  374. it('a rejected turn/end append is contained: warn + agent/error, no retry', async () => {
  375. const adapter = new MockAdapter([textResponse('ok')])
  376. const ctx = await harness(adapter)
  377. const agent = ctx.agentLoop.create(SessionId('turnend-veto'), { provider: 'mock', model: 'mock' })
  378. let vetoed = false
  379. ctx.on('internal/dispatch', (_mode, name, args) => {
  380. if (name !== 'session/event') return
  381. const event = args[1] as SessionEvent
  382. if (event.type === 'turn/end' && !vetoed) {
  383. vetoed = true
  384. throw new Error('reject turn end')
  385. }
  386. })
  387. const errors: unknown[] = []
  388. ctx.on('agent/error', (_agent, _turn, _step, error) => { errors.push(error) })
  389. send(agent, 'go')
  390. await agent.whenIdle()
  391. // The close failure is reported live; the machine still reaches idle.
  392. expect(errors.map(e => e instanceof Error && e.message)).toContain('reject turn end')
  393. expect(agent.status).toBe('idle')
  394. expect(adapter.requests).toHaveLength(1)
  395. })
  396. })
  397. describe('recovery without a retry request', () => {
  398. it('a completed recovery that never calls retry() leaves the failed turn terminal', async () => {
  399. const { LlmError } = await import('@deepseek-ai/dsh-llm')
  400. const adapter = new MockAdapter([
  401. () => { throw new LlmError('down', 'SERVICE_UNAVAILABLE') },
  402. ])
  403. const ctx = await harness(adapter)
  404. const agent = ctx.agentLoop.create(SessionId('recovery-no-retry'), { provider: 'mock', model: 'mock' })
  405. let recoveries = 0
  406. ctx.on('agent/request-error', async () => { recoveries += 1 })
  407. send(agent, 'go')
  408. await agent.whenIdle()
  409. expect(recoveries).toBe(1)
  410. expect(adapter.requests).toHaveLength(1)
  411. const end = agent.session.events.findLast(e => e.type === 'turn/end')
  412. expect(end?.type === 'turn/end' && end.data.reason.kind).toBe('error')
  413. })
  414. })
  415. describe('unrenderable failure settlement', () => {
  416. it('drops the rendered message when the error chain cannot be rendered', async () => {
  417. const { LlmError } = await import('@deepseek-ai/dsh-llm')
  418. const adapter = new MockAdapter([
  419. () => {
  420. const error = new LlmError('will become hostile', 'SERVER')
  421. // A hostile message getter makes errorChain collapse to its sentinel;
  422. // settle() must then fall back to the failure facts alone.
  423. Object.defineProperty(error, 'message', {
  424. get() { throw new Error('hostile accessor') },
  425. })
  426. throw error
  427. },
  428. ])
  429. const ctx = await harness(adapter)
  430. const agent = ctx.agentLoop.create(SessionId('unrenderable'), { provider: 'mock', model: 'mock' })
  431. send(agent, 'go')
  432. await agent.whenIdle()
  433. const end = agent.session.events.findLast(e => e.type === 'turn/end')
  434. expect(end?.type === 'turn/end' && end.data.reason.kind).toBe('error')
  435. if (end?.type === 'turn/end' && end.data.reason.kind === 'error') {
  436. // The durable failure keeps the adapter facts' message, not the
  437. // unrenderable chain.
  438. expect(end.data.reason.failure?.message).not.toBe('<unrenderable value>')
  439. }
  440. })
  441. })