agent.spec.ts 7.0 KB

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