coverage-edges.spec.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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('request-error action edges', () => {
  227. it('ignores a retry action returned after the turn was aborted', async () => {
  228. const { LlmError } = await import('@deepseek-ai/dsh-llm')
  229. const adapter = new MockAdapter([
  230. () => { throw new LlmError('busy', 'RATE_LIMIT') },
  231. textResponse('never used'),
  232. ])
  233. const ctx = await harness(adapter)
  234. const agent = ctx.agentLoop.create(SessionId('retry-after-cancel'), { provider: 'mock', model: 'mock' })
  235. ctx.on('agent/request-error', async (subject) => {
  236. subject.cancel({ kind: 'user' })
  237. return { kind: 'retry' }
  238. })
  239. send(agent, 'go')
  240. await agent.whenIdle()
  241. // One failed request, no retry turn.
  242. expect(adapter.requests).toHaveLength(1)
  243. const ends = agent.session.events.filter(e => e.type === 'turn/end')
  244. expect(ends).toHaveLength(1)
  245. })
  246. it('completed recovery does not retry when cancellation raced the waterfall', async () => {
  247. const { LlmError } = await import('@deepseek-ai/dsh-llm')
  248. const adapter = new MockAdapter([
  249. () => { throw new LlmError('busy', 'RATE_LIMIT') },
  250. ])
  251. const ctx = await harness(adapter)
  252. const agent = ctx.agentLoop.create(SessionId('retry-raced'), { provider: 'mock', model: 'mock' })
  253. ctx.on('agent/request-error', async (
  254. subject, _turn, _step, _error, _failure, _priorFailures, _retryPolicy, signal, next,
  255. ) => {
  256. await next()
  257. subject.cancel({ kind: 'user' })
  258. expect(signal.aborted).toBe(true)
  259. return { kind: 'retry' }
  260. })
  261. send(agent, 'go')
  262. await agent.whenIdle()
  263. expect(adapter.requests).toHaveLength(1)
  264. const end = agent.session.events.findLast(e => e.type === 'turn/end')
  265. expect(end?.type === 'turn/end' && end.data.reason.kind).toBe('aborted')
  266. })
  267. })
  268. describe('stream failure edges', () => {
  269. it('rethrows a mid-stream throw that carries no adapter failure facts', async () => {
  270. const adapter = new MockAdapter([textResponse('will be vetoed')])
  271. const ctx = await harness(adapter)
  272. const agent = ctx.agentLoop.create(SessionId('stream-no-facts'), { provider: 'mock', model: 'mock' })
  273. let recoveries = 0
  274. ctx.on('agent/request-error', async () => { recoveries += 1 })
  275. // A pre-commit chunk veto throws INSIDE the stream-consumption try, but it
  276. // is not an adapter-boundary failure, so llmFailureOf yields no facts.
  277. let vetoed = false
  278. ctx.on('internal/dispatch', (_mode, name, args) => {
  279. if (name !== 'session/event') return
  280. const event = args[1] as SessionEvent
  281. if (event.type === 'assistant/chunk' && !vetoed) {
  282. vetoed = true
  283. throw new Error('reject the first chunk')
  284. }
  285. })
  286. send(agent, 'go')
  287. await agent.whenIdle()
  288. // No facts -> not offered to recovery; the turn fails through settle().
  289. expect(recoveries).toBe(0)
  290. const end = agent.session.events.findLast(e => e.type === 'turn/end')
  291. expect(end?.type === 'turn/end' && end.data.reason.kind).toBe('error')
  292. })
  293. })
  294. describe('post-turn continuation edges', () => {
  295. it('whenIdle resolves for a waiter whose awaited run fails', async () => {
  296. const adapter = new MockAdapter([textResponse('unused')])
  297. const ctx = await harness(adapter)
  298. const agent = ctx.agentLoop.create(SessionId('whenidle-reject'), { provider: 'mock', model: 'mock' })
  299. let rejected = false
  300. ctx.on('internal/dispatch', (_mode, name, args) => {
  301. if (name !== 'session/event') return
  302. const event = args[1] as SessionEvent
  303. if (event.type === 'turn/start' && !rejected) {
  304. rejected = true
  305. throw new Error('veto turn start while a waiter is pending')
  306. }
  307. })
  308. send(agent, 'go')
  309. await expect(agent.whenIdle()).resolves.toBeUndefined()
  310. expect(agent.status).toBe('idle')
  311. })
  312. })
  313. describe('persistent step-close rejection', () => {
  314. it('still publishes the terminal status when both step-close attempts are vetoed', async () => {
  315. const adapter = new MockAdapter([textResponse('will not close')])
  316. const ctx = await harness(adapter)
  317. const agent = ctx.agentLoop.create(SessionId('stepend-double-veto'), { provider: 'mock', model: 'mock' })
  318. // Persistently reject step/end: the catch's own close attempt fails too,
  319. // and the contained failure must not strand status at running.
  320. ctx.on('internal/dispatch', (_mode, name, args) => {
  321. if (name !== 'session/event') return
  322. const event = args[1] as SessionEvent
  323. if (event.type === 'step/end') throw new Error('step close permanently rejected')
  324. })
  325. const statuses: string[] = []
  326. ctx.on('agent/status', (subject, status) => { if (subject === agent) statuses.push(status) })
  327. send(agent, 'go')
  328. await agent.whenIdle()
  329. expect(agent.status).toBe('idle')
  330. expect(statuses).toEqual(['running', 'idle'])
  331. })
  332. })
  333. describe('tool result meta persistence', () => {
  334. it('records a presentationMeta payload on the tool/result event', async () => {
  335. const { defineTool } = await import('@deepseek-ai/dsh-tools')
  336. const adapter = new MockAdapter([
  337. toolCallResponse('c1', 'meta-tool', {}),
  338. textResponse('done'),
  339. ])
  340. const ctx = await harness(adapter)
  341. const agent = ctx.agentLoop.create(SessionId('tool-meta'), { provider: 'mock', model: 'mock' })
  342. ctx.tools.register(defineTool({
  343. name: 'meta-tool',
  344. description: 'carries presentation meta',
  345. parameters: {},
  346. output: {
  347. schema: { type: 'string' },
  348. render: (_args, value) => [{ type: 'text', text: value }],
  349. presentationMeta: () => ({ presentation: 'diff-card' }),
  350. },
  351. async execute() {
  352. return 'ran'
  353. },
  354. }))
  355. send(agent, 'go')
  356. await waitForIdle(ctx, agent)
  357. const result = agent.session.events.find(e => e.type === 'tool/result')
  358. expect(result?.type === 'tool/result' && result.data.meta).toEqual({ presentation: 'diff-card' })
  359. })
  360. })
  361. describe('turn close failure containment', () => {
  362. it('a rejected turn/end append is contained: warn + agent/error, no retry', async () => {
  363. const adapter = new MockAdapter([textResponse('ok')])
  364. const ctx = await harness(adapter)
  365. const agent = ctx.agentLoop.create(SessionId('turnend-veto'), { provider: 'mock', model: 'mock' })
  366. let vetoed = false
  367. ctx.on('internal/dispatch', (_mode, name, args) => {
  368. if (name !== 'session/event') return
  369. const event = args[1] as SessionEvent
  370. if (event.type === 'turn/end' && !vetoed) {
  371. vetoed = true
  372. throw new Error('reject turn end')
  373. }
  374. })
  375. const errors: unknown[] = []
  376. ctx.on('agent/error', (_agent, _turn, _step, error) => { errors.push(error) })
  377. send(agent, 'go')
  378. await agent.whenIdle()
  379. // The close failure is reported live; the machine still reaches idle.
  380. expect(errors.map(e => e instanceof Error && e.message)).toContain('reject turn end')
  381. expect(agent.status).toBe('idle')
  382. expect(adapter.requests).toHaveLength(1)
  383. })
  384. })
  385. describe('recovery without a retry action', () => {
  386. it('a completed recovery that returns no action leaves the failed turn terminal', async () => {
  387. const { LlmError } = await import('@deepseek-ai/dsh-llm')
  388. const adapter = new MockAdapter([
  389. () => { throw new LlmError('down', 'SERVICE_UNAVAILABLE') },
  390. ])
  391. const ctx = await harness(adapter)
  392. const agent = ctx.agentLoop.create(SessionId('recovery-no-retry'), { provider: 'mock', model: 'mock' })
  393. let recoveries = 0
  394. ctx.on('agent/request-error', async () => { recoveries += 1 })
  395. send(agent, 'go')
  396. await agent.whenIdle()
  397. expect(recoveries).toBe(1)
  398. expect(adapter.requests).toHaveLength(1)
  399. const end = agent.session.events.findLast(e => e.type === 'turn/end')
  400. expect(end?.type === 'turn/end' && end.data.reason.kind).toBe('error')
  401. })
  402. })
  403. describe('unrenderable failure settlement', () => {
  404. it('drops the rendered message when the error chain cannot be rendered', async () => {
  405. const { LlmError } = await import('@deepseek-ai/dsh-llm')
  406. const adapter = new MockAdapter([
  407. () => {
  408. const error = new LlmError('will become hostile', 'SERVER')
  409. // A hostile message getter makes errorChain collapse to its sentinel;
  410. // settle() must then fall back to the failure facts alone.
  411. Object.defineProperty(error, 'message', {
  412. get() { throw new Error('hostile accessor') },
  413. })
  414. throw error
  415. },
  416. ])
  417. const ctx = await harness(adapter)
  418. const agent = ctx.agentLoop.create(SessionId('unrenderable'), { provider: 'mock', model: 'mock' })
  419. send(agent, 'go')
  420. await agent.whenIdle()
  421. const end = agent.session.events.findLast(e => e.type === 'turn/end')
  422. expect(end?.type === 'turn/end' && end.data.reason.kind).toBe('error')
  423. if (end?.type === 'turn/end' && end.data.reason.kind === 'error') {
  424. // The durable failure keeps the adapter facts' message, not the
  425. // unrenderable chain.
  426. expect(end.data.reason.failure?.message).not.toBe('<unrenderable value>')
  427. }
  428. })
  429. })
  430. describe('driver bookkeeping edges', () => {
  431. it('a deferred wake settles when replacement activity rejects', async () => {
  432. const adapter = new MockAdapter([])
  433. const ctx = await harness(adapter)
  434. const agent = ctx.agentLoop.create(SessionId('rejected-deferred-wake'), {
  435. provider: 'mock',
  436. model: 'mock',
  437. })
  438. ctx.on('agent/inbox/enqueue', (subject) => {
  439. if (subject !== agent) return
  440. subject.cancel({ kind: 'user' })
  441. const mutable = subject as Agent & { done: Promise<void> }
  442. mutable.done = Promise.reject(new Error('replacement rejected'))
  443. })
  444. send(agent, 'cancel before wake')
  445. await expect(agent.whenIdle()).resolves.toBeUndefined()
  446. expect(agent.session.events).toEqual([])
  447. })
  448. it('a whenIdle waiter survives a rejected driver promise', async () => {
  449. const adapter = new MockAdapter([textResponse('ok')])
  450. const ctx = await harness(adapter)
  451. const agent = ctx.agentLoop.create(SessionId('waiter-chain'), { provider: 'mock', model: 'mock' })
  452. // A throwing terminal-notification listener rejects the driver promise
  453. // (the run's containment covers only session appends); the waiter's
  454. // catch arm must treat that rejection as quiescence instead of
  455. // propagating it.
  456. ctx.on('agent/settled', (subject) => {
  457. if (subject === agent) throw new Error('settled listener exploded')
  458. })
  459. send(agent, 'one')
  460. // Entered while the run owns the abort slot, the waiter awaits the
  461. // driver promise; its rejection must count as quiescence and resolve.
  462. await expect(agent.whenIdle()).resolves.toBeUndefined()
  463. })
  464. it('a request failure that concludes recovery after step/end closed keeps the boundary balanced', async () => {
  465. const { LlmError } = await import('@deepseek-ai/dsh-llm')
  466. // The failure finish-chunk path returns request-failed AFTER step() has
  467. // already appended step/end, so the request-failed branch's own
  468. // step-close guard must see stepOpen === false and skip the append.
  469. const adapter = new MockAdapter([
  470. [
  471. { type: 'usage' as const, usage: { inputTokens: 1, outputTokens: 0 } },
  472. { type: 'finish' as const, reason: { kind: 'error' as const, failure: { message: 'empty', code: 'EMPTY_RESPONSE' } } },
  473. ] satisfies StreamChunk[],
  474. ])
  475. const ctx = await harness(adapter)
  476. const agent = ctx.agentLoop.create(SessionId('finish-after-close'), { provider: 'mock', model: 'mock' })
  477. void LlmError
  478. send(agent, 'go')
  479. await agent.whenIdle()
  480. const types = agent.session.events.map(e => e.type)
  481. expect(types.filter(t => t === 'step/end')).toHaveLength(1)
  482. const end = agent.session.events.findLast(e => e.type === 'turn/end')
  483. expect(end?.type === 'turn/end' && end.data.reason.kind).toBe('error')
  484. })
  485. })