coverage-edges.spec.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from '@deepseek-ai/cordis'
  3. import LlmRuntime, { createUserMessage, 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 ToolRuntime, { 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(LlmRuntime)
  17. await ctx.plugin(SessionStore)
  18. await ctx.plugin(SystemPrompt)
  19. await ctx.plugin(ToolRuntime)
  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', ({ agent: 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(createUserMessage({ 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', ({ 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(0)
  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(0)
  120. expect(ends).toHaveLength(0)
  121. expect(messages).toHaveLength(0)
  122. expect(agent.inbox.nextTurn).toHaveLength(2)
  123. })
  124. it('preserves non-Error throws from the agent/request waterfall', async () => {
  125. const adapter = new MockAdapter([textResponse('irrelevant')])
  126. const ctx = await harness(adapter)
  127. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  128. let threwOnce = false
  129. ctx.on('agent/request', async (_payload, next) => {
  130. if (!threwOnce) {
  131. threwOnce = true
  132. throw { code: 500 }
  133. }
  134. return next()
  135. })
  136. send(agent, 'go')
  137. await waitForIdle(ctx, agent)
  138. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  139. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind === 'error'
  140. ? turnEnd.data.reason.error.message
  141. : undefined).toBe('[object Object]')
  142. })
  143. })
  144. describe('durable error rendering', () => {
  145. it('renders a coded error thrown from a plugin', async () => {
  146. const adapter = new MockAdapter([textResponse('turn 1')])
  147. const ctx = await harness(adapter)
  148. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  149. let threwOnce = false
  150. ctx.on('agent/request', async (_payload, next) => {
  151. if (!threwOnce) {
  152. threwOnce = true
  153. throw new LlmError('server overloaded', 'RATE_LIMIT')
  154. }
  155. return next()
  156. })
  157. send(agent, 'go')
  158. await waitForIdle(ctx, agent)
  159. const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
  160. expect(turnEnd).toBeDefined()
  161. if (turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind === 'error') {
  162. expect(turnEnd.data.reason.error).toEqual({
  163. message: 'server overloaded',
  164. code: 'RATE_LIMIT',
  165. })
  166. }
  167. })
  168. })
  169. describe('disposed vs aborted branching', () => {
  170. it('handles dispose during model streaming producing reason "disposed"', async () => {
  171. const adapter = new MockAdapter(['hang'])
  172. const ctx = await harness(adapter)
  173. let agent!: Agent
  174. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  175. agent = inner.agentLoop.create(SessionId('scoped'), { provider: 'mock', model: 'mock' })
  176. }, { inject: ['agentLoop'] }))
  177. const reasons: TurnEndReason[] = []
  178. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  179. send(agent, 'go')
  180. await new Promise(r => setTimeout(r, 30))
  181. await fiber.dispose() // dispose during hang
  182. await driverDone(agent)
  183. // Disposal wins abort classification because the error path checks it first.
  184. expect(reasons).toContainEqual({ kind: 'aborted', reason: { kind: 'disposed' } })
  185. })
  186. })
  187. describe('structured tool error propagation (the runtime-validation Agent Note, part 2)', () => {
  188. it('forwards a tool HarnessError onto the tool/result session event', async () => {
  189. const { HarnessError } = await import('@deepseek-ai/dsh-llm')
  190. // First model turn calls the tool; second turn (after the tool result is
  191. // fed back) ends with plain text so the loop settles.
  192. const adapter = new MockAdapter([
  193. toolCallResponse('c1', 'boom', {}),
  194. textResponse('done'),
  195. ])
  196. const ctx = await harness(adapter)
  197. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  198. ctx.tools.register(defineContentToolFixture({
  199. name: 'boom',
  200. description: 'always fails',
  201. parameters: {},
  202. async execute() {
  203. throw new HarnessError('exploded', 'BOOM')
  204. },
  205. }))
  206. send(agent, 'go')
  207. await waitForIdle(ctx, agent)
  208. const toolResult = agent.session.events.find(e => e.type === 'tool/result')
  209. expect(toolResult?.type === 'tool/result' && toolResult.data.message.content[0].isError).toBe(true)
  210. expect(toolResult?.type === 'tool/result' && toolResult.data.error)
  211. .toEqual({ name: 'HarnessError', code: 'BOOM' })
  212. })
  213. })
  214. describe('request-error action edges', () => {
  215. it('ignores a retry action returned after the turn was aborted', async () => {
  216. const { LlmError } = await import('@deepseek-ai/dsh-llm')
  217. const adapter = new MockAdapter([
  218. () => { throw new LlmError('busy', 'RATE_LIMIT') },
  219. textResponse('never used'),
  220. ])
  221. const ctx = await harness(adapter)
  222. const agent = ctx.agentLoop.create(SessionId('retry-after-cancel'), { provider: 'mock', model: 'mock' })
  223. ctx.on('agent/request-error', async ({ agent: subject }) => {
  224. subject.cancel({ kind: 'user' })
  225. return { kind: 'retry' }
  226. })
  227. send(agent, 'go')
  228. await agent.whenIdle()
  229. // One failed request, no retry turn.
  230. expect(adapter.requests).toHaveLength(1)
  231. const ends = agent.session.events.filter(e => e.type === 'turn/end')
  232. expect(ends).toHaveLength(1)
  233. })
  234. it('completed recovery does not retry when cancellation raced the waterfall', async () => {
  235. const { LlmError } = await import('@deepseek-ai/dsh-llm')
  236. const adapter = new MockAdapter([
  237. () => { throw new LlmError('busy', 'RATE_LIMIT') },
  238. ])
  239. const ctx = await harness(adapter)
  240. const agent = ctx.agentLoop.create(SessionId('retry-raced'), { provider: 'mock', model: 'mock' })
  241. ctx.on('agent/request-error', async ({ agent: subject, signal }, next) => {
  242. await next()
  243. subject.cancel({ kind: 'user' })
  244. expect(signal.aborted).toBe(true)
  245. return { kind: 'retry' }
  246. })
  247. send(agent, 'go')
  248. await agent.whenIdle()
  249. expect(adapter.requests).toHaveLength(1)
  250. const end = agent.session.events.findLast(e => e.type === 'turn/end')
  251. expect(end?.type === 'turn/end' && end.data.reason.kind).toBe('aborted')
  252. })
  253. })
  254. describe('stream failure edges', () => {
  255. it('rethrows a mid-stream throw that carries no adapter failure facts', async () => {
  256. const adapter = new MockAdapter([textResponse('will be vetoed')])
  257. const ctx = await harness(adapter)
  258. const agent = ctx.agentLoop.create(SessionId('stream-no-facts'), { provider: 'mock', model: 'mock' })
  259. let recoveries = 0
  260. ctx.on('agent/request-error', async () => { recoveries += 1 })
  261. // A pre-commit chunk veto throws INSIDE the stream-consumption try, but it
  262. // is not an adapter-boundary failure, so llmFailureOf yields no facts.
  263. let vetoed = false
  264. ctx.on('internal/dispatch', (_mode, name, args) => {
  265. if (name !== 'session/event') return
  266. const event = args[1] as SessionEvent
  267. if (event.type === 'assistant/chunk' && !vetoed) {
  268. vetoed = true
  269. throw new Error('reject the first chunk')
  270. }
  271. })
  272. send(agent, 'go')
  273. await agent.whenIdle()
  274. // No facts -> not offered to recovery; the turn fails through settle().
  275. expect(recoveries).toBe(0)
  276. const end = agent.session.events.findLast(e => e.type === 'turn/end')
  277. expect(end?.type === 'turn/end' && end.data.reason.kind).toBe('error')
  278. })
  279. })
  280. describe('post-turn continuation edges', () => {
  281. it('whenIdle resolves for a waiter whose awaited run fails', async () => {
  282. const adapter = new MockAdapter([textResponse('unused')])
  283. const ctx = await harness(adapter)
  284. const agent = ctx.agentLoop.create(SessionId('whenidle-reject'), { provider: 'mock', model: 'mock' })
  285. let rejected = false
  286. ctx.on('internal/dispatch', (_mode, name, args) => {
  287. if (name !== 'session/event') return
  288. const event = args[1] as SessionEvent
  289. if (event.type === 'turn/start' && !rejected) {
  290. rejected = true
  291. throw new Error('veto turn start while a waiter is pending')
  292. }
  293. })
  294. send(agent, 'go')
  295. await expect(agent.whenIdle()).resolves.toBeUndefined()
  296. expect(agent.status).toBe('idle')
  297. })
  298. })
  299. describe('persistent step-close rejection', () => {
  300. it('still publishes the terminal status when both step-close attempts are vetoed', async () => {
  301. const adapter = new MockAdapter([textResponse('will not close')])
  302. const ctx = await harness(adapter)
  303. const agent = ctx.agentLoop.create(SessionId('stepend-double-veto'), { provider: 'mock', model: 'mock' })
  304. // Persistently reject step/end: the catch's own close attempt fails too,
  305. // and the contained failure must not strand status at running.
  306. ctx.on('internal/dispatch', (_mode, name, args) => {
  307. if (name !== 'session/event') return
  308. const event = args[1] as SessionEvent
  309. if (event.type === 'step/end') throw new Error('step close permanently rejected')
  310. })
  311. const statuses: string[] = []
  312. ctx.on('agent/status', ({ agent: subject, status }) => { if (subject === agent) statuses.push(status) })
  313. send(agent, 'go')
  314. await agent.whenIdle()
  315. expect(agent.status).toBe('idle')
  316. expect(statuses).toEqual(['running', 'idle'])
  317. })
  318. })
  319. describe('tool result meta persistence', () => {
  320. it('records a presentationMeta payload on the tool/result event', async () => {
  321. const { defineTool } = await import('@deepseek-ai/dsh-tools')
  322. const adapter = new MockAdapter([
  323. toolCallResponse('c1', 'meta-tool', {}),
  324. textResponse('done'),
  325. ])
  326. const ctx = await harness(adapter)
  327. const agent = ctx.agentLoop.create(SessionId('tool-meta'), { provider: 'mock', model: 'mock' })
  328. ctx.tools.register(defineTool({
  329. name: 'meta-tool',
  330. description: 'carries presentation meta',
  331. parameters: {},
  332. output: {
  333. schema: { type: 'string' },
  334. render: (_args, value) => [{ type: 'text', text: value }],
  335. presentationMeta: () => ({ presentation: 'diff-card' }),
  336. },
  337. async execute() {
  338. return 'ran'
  339. },
  340. }))
  341. send(agent, 'go')
  342. await waitForIdle(ctx, agent)
  343. const result = agent.session.events.find(e => e.type === 'tool/result')
  344. expect(result?.type === 'tool/result' && result.data.meta).toEqual({ presentation: 'diff-card' })
  345. })
  346. })
  347. describe('turn close failure containment', () => {
  348. it('a rejected turn/end append is contained: warn + agent/error, no retry', async () => {
  349. const adapter = new MockAdapter([textResponse('ok')])
  350. const ctx = await harness(adapter)
  351. const agent = ctx.agentLoop.create(SessionId('turnend-veto'), { provider: 'mock', model: 'mock' })
  352. let vetoed = false
  353. ctx.on('internal/dispatch', (_mode, name, args) => {
  354. if (name !== 'session/event') return
  355. const event = args[1] as SessionEvent
  356. if (event.type === 'turn/end' && !vetoed) {
  357. vetoed = true
  358. throw new Error('reject turn end')
  359. }
  360. })
  361. const errors: unknown[] = []
  362. ctx.on('agent/error', ({ error }) => { errors.push(error) })
  363. send(agent, 'go')
  364. await agent.whenIdle()
  365. // The close failure is reported live; the machine still reaches idle.
  366. expect(errors.map(e => e instanceof Error && e.message)).toContain('reject turn end')
  367. expect(agent.status).toBe('idle')
  368. expect(adapter.requests).toHaveLength(1)
  369. })
  370. })
  371. describe('recovery without a retry action', () => {
  372. it('a completed recovery that returns no action leaves the failed turn terminal', async () => {
  373. const { LlmError } = await import('@deepseek-ai/dsh-llm')
  374. const adapter = new MockAdapter([
  375. () => { throw new LlmError('down', 'SERVICE_UNAVAILABLE') },
  376. ])
  377. const ctx = await harness(adapter)
  378. const agent = ctx.agentLoop.create(SessionId('recovery-no-retry'), { provider: 'mock', model: 'mock' })
  379. let recoveries = 0
  380. ctx.on('agent/request-error', async () => { recoveries += 1 })
  381. send(agent, 'go')
  382. await agent.whenIdle()
  383. expect(recoveries).toBe(1)
  384. expect(adapter.requests).toHaveLength(1)
  385. const end = agent.session.events.findLast(e => e.type === 'turn/end')
  386. expect(end?.type === 'turn/end' && end.data.reason.kind).toBe('error')
  387. })
  388. })
  389. describe('unrenderable failure settlement', () => {
  390. it('drops the rendered message when the error chain cannot be rendered', async () => {
  391. const { LlmError } = await import('@deepseek-ai/dsh-llm')
  392. const adapter = new MockAdapter([
  393. () => {
  394. const error = new LlmError('will become hostile', 'SERVER')
  395. // A hostile message getter makes errorChain collapse to its sentinel;
  396. // settle() must then fall back to the failure facts alone.
  397. Object.defineProperty(error, 'message', {
  398. get() { throw new Error('hostile accessor') },
  399. })
  400. throw error
  401. },
  402. ])
  403. const ctx = await harness(adapter)
  404. const agent = ctx.agentLoop.create(SessionId('unrenderable'), { provider: 'mock', model: 'mock' })
  405. send(agent, 'go')
  406. await agent.whenIdle()
  407. const end = agent.session.events.findLast(e => e.type === 'turn/end')
  408. expect(end?.type === 'turn/end' && end.data.reason.kind).toBe('error')
  409. if (end?.type === 'turn/end' && end.data.reason.kind === 'error') {
  410. // The durable failure keeps the adapter facts' message, not the
  411. // unrenderable chain.
  412. expect(errorChain(end.data.reason.error.message)).not.toBe('<unrenderable value>')
  413. }
  414. })
  415. })
  416. describe('driver bookkeeping edges', () => {
  417. it('rejects a direct turn invocation without a driver reservation', async () => {
  418. const ctx = await harness(new MockAdapter([]))
  419. const agent = ctx.agentLoop.create(SessionId('turn-without-reservation'), { provider: 'mock', model: 'mock' })
  420. await expect((agent as unknown as { turn(): Promise<boolean> }).turn())
  421. .rejects.toThrow('turn without driver reservation')
  422. expect(agent.status).toBe('idle')
  423. })
  424. it('closes an entered turn as blocked when its next step is rejected', async () => {
  425. const adapter = new MockAdapter([textResponse('first step')])
  426. const ctx = await harness(adapter)
  427. const agent = ctx.agentLoop.create(SessionId('reject-next-step'), { provider: 'mock', model: 'mock' })
  428. let proposals = 0
  429. ctx.on('agent/pre-step', async (_payload, next) => {
  430. proposals += 1
  431. return proposals === 2 ? { kind: 'reject' } : next()
  432. })
  433. ctx.on('agent/turn-stopping', ({ agent: subject }) => {
  434. subject.inject(createUserMessage({
  435. content: [{ type: 'text', text: 'do not enter the next step' }],
  436. source: { kind: 'plugin', plugin: 'test' },
  437. }))
  438. })
  439. send(agent, 'go')
  440. await agent.whenIdle()
  441. expect(proposals).toBe(2)
  442. expect(adapter.requests).toHaveLength(1)
  443. const end = agent.session.events.findLast(event => event.type === 'turn/end')
  444. expect(end?.type === 'turn/end' && end.data.reason).toEqual({ kind: 'blocked' })
  445. })
  446. it('a request failure that concludes recovery after step/end closed keeps the boundary balanced', async () => {
  447. const { LlmError } = await import('@deepseek-ai/dsh-llm')
  448. // The failure finish-chunk path returns request-failed AFTER step() has
  449. // already appended step/end, so the request-failed branch's own
  450. // step-close guard must see stepOpen === false and skip the append.
  451. const adapter = new MockAdapter([
  452. [
  453. { type: 'usage' as const, usage: { inputTokens: 1, outputTokens: 0 } },
  454. { type: 'finish' as const, reason: { kind: 'error' as const, failure: { message: 'empty', code: 'EMPTY_RESPONSE' } } },
  455. ] satisfies StreamChunk[],
  456. ])
  457. const ctx = await harness(adapter)
  458. const agent = ctx.agentLoop.create(SessionId('finish-after-close'), { provider: 'mock', model: 'mock' })
  459. void LlmError
  460. send(agent, 'go')
  461. await agent.whenIdle()
  462. const types = agent.session.events.map(e => e.type)
  463. expect(types.filter(t => t === 'step/end')).toHaveLength(1)
  464. const end = agent.session.events.findLast(e => e.type === 'turn/end')
  465. expect(end?.type === 'turn/end' && end.data.reason.kind).toBe('error')
  466. })
  467. })