agent.spec.ts 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  2. import { describe, expect, it, vi } from 'vitest'
  3. import { Context } from 'cordis'
  4. import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent'
  5. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  6. import LlmService from '@deepseek-ai/dsh-llm'
  7. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  8. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  9. import ToolRegistry from '@deepseek-ai/dsh-tools'
  10. import { MockAdapter, textResponse } from './mock-adapter.ts'
  11. async function harness(adapter: MockAdapter): Promise<Context> {
  12. const ctx = new Context()
  13. await ctx.plugin(LlmService)
  14. await ctx.plugin(SessionStore)
  15. await ctx.plugin(SystemPrompt)
  16. await ctx.plugin(ToolRegistry)
  17. await ctx.plugin(AgentRegistry)
  18. await ctx.plugin(AgentLoop, { agents: [] })
  19. ctx.llm.registerAdapter(['mock'], adapter)
  20. return ctx
  21. }
  22. function send(agent: Agent, text: string): void {
  23. agent.followup(createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } }))
  24. }
  25. describe('Agent', () => {
  26. it('idle inject() durably stages context without opening a turn', async () => {
  27. const adapter = new MockAdapter([textResponse('ok')])
  28. const ctx = await harness(adapter)
  29. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  30. agent.inject(createUserMessage({ content: [{ type: 'text', text: 'context' }], source: { kind: 'plugin', plugin: 'p' } }))
  31. expect(agent.session.events.map(event => event.type)).toEqual(['agent/inbox/spliced'])
  32. expect(agent.status).toBe('idle')
  33. expect(adapter.requests).toHaveLength(0)
  34. await agent.whenIdle()
  35. })
  36. it('inject() preserves an explicitly empty plugin source', async () => {
  37. const ctx = await harness(new MockAdapter([textResponse('ok')]))
  38. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  39. agent.inject(createUserMessage({ content: [{ type: 'text', text: 'empty plugin source' }], source: { kind: 'plugin', plugin: '' } }))
  40. const injected = agent.session.events.at(-1)
  41. expect(injected?.type === 'agent/inbox/spliced' && injected.data.inserted[0]?.source)
  42. .toEqual({ kind: 'plugin', plugin: '' })
  43. })
  44. it('emits exact inserted, claimed, and discarded inbox messages', async () => {
  45. const ctx = await harness(new MockAdapter([textResponse('ok')]))
  46. const agent = ctx.agentLoop.create(SessionId('inbox-events'), { provider: 'mock', model: 'mock' })
  47. const inserted: unknown[] = []
  48. const claimed: unknown[] = []
  49. const discarded: unknown[] = []
  50. ctx.on('agent/inbox/inserted', (subject, event) => {
  51. if (subject === agent) inserted.push(event)
  52. })
  53. ctx.on('agent/inbox/claimed', (subject, event) => {
  54. if (subject === agent) claimed.push(event)
  55. })
  56. ctx.on('agent/inbox/discarded', (subject, event) => {
  57. if (subject === agent) discarded.push(event)
  58. })
  59. const context = createUserMessage({
  60. content: [{ type: 'text', text: 'discard me' }],
  61. source: { kind: 'plugin', plugin: 'test' },
  62. })
  63. agent.inject(context)
  64. agent.inbox.remove('next-step', context.id)
  65. const prompt = createUserMessage({ content: [{ type: 'text', text: 'run' }], source: { kind: 'user' } })
  66. agent.followup(prompt)
  67. await agent.whenIdle()
  68. expect(inserted).toEqual([{ message: context }, { message: prompt }])
  69. expect(discarded).toEqual([{ message: context }])
  70. expect(claimed).toEqual([{ message: prompt, turn: 1 }])
  71. })
  72. it('idle inject() rejects invalid input before enqueue', async () => {
  73. const ctx = await harness(new MockAdapter([textResponse('ok')]))
  74. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  75. expect(() => {
  76. agent.inject(createUserMessage({ content: [{ type: 'text', text: 'x', bad: 1n } as never], source: { kind: 'plugin', plugin: 'p' } }))
  77. }).toThrow(/non-JSON-serializable/)
  78. expect(agent.session.events).toHaveLength(0)
  79. })
  80. it('steer() while idle becomes a woken prompt turn', async () => {
  81. const adapter = new MockAdapter([textResponse('ok')])
  82. const ctx = await harness(adapter)
  83. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  84. agent.steer(createUserMessage({ content: [{ type: 'text', text: 'steer idle' }], source: { kind: 'plugin', plugin: 'test' } }))
  85. await agent.whenIdle()
  86. expect(agent.session.events.some(event => event.type === 'user/message')).toBe(true)
  87. expect(adapter.requests).toHaveLength(1)
  88. })
  89. it('emits one running and idle transition for one completed turn', async () => {
  90. const ctx = await harness(new MockAdapter([textResponse('ok')]))
  91. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  92. const statuses: string[] = []
  93. ctx.on('agent/status', (subject, status) => {
  94. if (subject === agent) statuses.push(status)
  95. })
  96. send(agent, 'hi')
  97. await agent.whenIdle()
  98. expect(statuses).toEqual(['running', 'idle'])
  99. })
  100. it('whenIdle() resolves immediately without active work', async () => {
  101. const ctx = await harness(new MockAdapter([textResponse('ok')]))
  102. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  103. await agent.whenIdle()
  104. expect(agent.status).toBe('idle')
  105. })
  106. it('whenIdle() waits for active work until explicit cancellation', async () => {
  107. const ctx = await harness(new MockAdapter(['hang']))
  108. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  109. send(agent, 'queued')
  110. let settled = false
  111. const idle = agent.whenIdle().then(() => { settled = true })
  112. await Promise.resolve()
  113. expect(settled).toBe(false)
  114. agent.cancel({ kind: 'user' })
  115. await idle
  116. expect(agent.status).toBe('idle')
  117. })
  118. it('contains a throwing status listener on both transitions', async () => {
  119. const ctx = await harness(new MockAdapter([textResponse('ok')]))
  120. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
  121. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  122. ctx.on('agent/status', (_subject, status) => {
  123. throw new Error(`bad ${status} listener`)
  124. })
  125. send(agent, 'go')
  126. await agent.whenIdle()
  127. expect(agent.status).toBe('idle')
  128. expect(warn).toHaveBeenCalledWith(
  129. expect.stringContaining('agent event "agent/status" listener threw'),
  130. )
  131. })
  132. })