tool-order.spec.ts 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. /**
  2. * Loop-level tool-order determinism: the request/header event — and therefore the frozen
  3. * request the adapter receives — carries the assembly's canonical tool order (system-prompt's
  4. * `toolOrder` config, or lexicographic name order), regardless of the order tool plugins
  5. * happened to register in. Registration order is a concurrent loading artifact
  6. * and must not leak downstream.
  7. */
  8. import { describe, expect, it } from 'vitest'
  9. import { Context } from 'cordis'
  10. import LlmService from '@deepseek-ai/dsh-llm'
  11. import SessionStore, { foldRequestHeader } from '@deepseek-ai/dsh-session'
  12. import SystemPrompt, { TOOL_ORDER_REST } from '@deepseek-ai/dsh-system-prompt'
  13. import type { Config as SystemPromptConfig } from '@deepseek-ai/dsh-system-prompt'
  14. import ToolRegistry, { defineTool } from '@deepseek-ai/dsh-tools'
  15. import AgentRegistry, { AgentId } from '@deepseek-ai/dsh-agent'
  16. import AgentExecutionProvider from '@deepseek-ai/dsh-agent-execution'
  17. import AgentLoop, { ReactLoopAgent } from '@deepseek-ai/dsh-agent-loop'
  18. import { MockAdapter, textResponse } from './mock-adapter.ts'
  19. async function harness(adapter: MockAdapter, toolOrder?: SystemPromptConfig['toolOrder']) {
  20. const ctx = new Context()
  21. await ctx.plugin(LlmService)
  22. await ctx.plugin(SessionStore)
  23. await ctx.plugin(SystemPrompt, { persona: 'stable base', ...toolOrder !== undefined ? { toolOrder } : {} })
  24. await ctx.plugin(ToolRegistry)
  25. await ctx.plugin(AgentRegistry)
  26. await ctx.plugin(AgentExecutionProvider)
  27. await ctx.plugin(AgentLoop, { agents: [] })
  28. ctx.llm.registerAdapter(['mock'], adapter)
  29. return ctx
  30. }
  31. function waitForIdle(ctx: Context, agent: ReactLoopAgent): Promise<void> {
  32. return new Promise((resolve) => {
  33. const dispose = ctx.on('agent/status', (subject, status) => {
  34. if (subject === agent && status === 'idle') {
  35. dispose()
  36. resolve()
  37. }
  38. })
  39. })
  40. }
  41. function registerNamed(ctx: Context, name: string) {
  42. ctx.tools.register(defineTool({
  43. name,
  44. description: `the ${name} tool`,
  45. parameters: {},
  46. async execute() {
  47. return [{ type: 'text', text: name }]
  48. },
  49. }))
  50. }
  51. /** Run one text-only turn and return the harness context + agent. */
  52. async function runTurn(registrationOrder: string[], toolOrder?: SystemPromptConfig['toolOrder']) {
  53. const adapter = new MockAdapter([textResponse('done')])
  54. const ctx = await harness(adapter, toolOrder)
  55. for (const name of registrationOrder) registerNamed(ctx, name)
  56. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  57. agent.send([{ type: 'text', text: 'go' }])
  58. await waitForIdle(ctx, agent)
  59. return { ctx, agent, adapter }
  60. }
  61. describe('loop-level canonical tool order', () => {
  62. it('logs the request/header with tools in canonical order, not registration order', async () => {
  63. const { agent, adapter } = await runTurn(['zulu', 'alpha', 'mike'])
  64. const header = foldRequestHeader(agent.session.events)
  65. expect(header?.tools?.map(tool => tool.name)).toEqual(['alpha', 'mike', 'zulu'])
  66. // The dispatched request is built FROM the logged header (whose tools the
  67. // assembly already canonicalized) and reaches the adapter deep-frozen —
  68. // the marker the reconstruction invariant keys on.
  69. expect(adapter.requests[0]?.tools?.map(tool => tool.name)).toEqual(['alpha', 'mike', 'zulu'])
  70. expect(Object.isFrozen(adapter.requests[0])).toBe(true)
  71. expect(adapter.requests[0]?.sessionId).toBe(agent.session.id)
  72. })
  73. it('produces the same header order for any registration order', async () => {
  74. const first = await runTurn(['alpha', 'mike', 'zulu'])
  75. const second = await runTurn(['zulu', 'mike', 'alpha'])
  76. const names = (run: typeof first) => foldRequestHeader(run.agent.session.events)?.tools?.map(tool => tool.name)
  77. expect(names(first)).toEqual(['alpha', 'mike', 'zulu'])
  78. expect(names(second)).toEqual(names(first))
  79. })
  80. it('honors a configured toolOrder in the logged header and the dispatched request', async () => {
  81. const { agent, adapter } = await runTurn(['alpha', 'zulu', 'mike'], ['zulu', TOOL_ORDER_REST])
  82. const header = foldRequestHeader(agent.session.events)
  83. expect(header?.tools?.map(tool => tool.name)).toEqual(['zulu', 'alpha', 'mike'])
  84. expect(adapter.requests[0]?.tools?.map(tool => tool.name)).toEqual(['zulu', 'alpha', 'mike'])
  85. expect(Object.isFrozen(adapter.requests[0])).toBe(true)
  86. })
  87. it('fails the turn — no model request — when toolOrder names an unregistered tool', async () => {
  88. // Unknown tool order fails before step or request creation and returns the agent to idle.
  89. const adapter = new MockAdapter([textResponse('never sent')])
  90. const ctx = await harness(adapter, ['ghost', TOOL_ORDER_REST])
  91. registerNamed(ctx, 'alpha')
  92. const errors: Error[] = []
  93. ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error))
  94. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  95. agent.send([{ type: 'text', text: 'go' }])
  96. await waitForIdle(ctx, agent)
  97. expect(adapter.requests).toHaveLength(0)
  98. expect(errors.map(e => e.message)).toEqual(['toolOrder lists unregistered tool "ghost"; known tools: alpha'])
  99. expect(foldRequestHeader(agent.session.events)).toBeUndefined()
  100. const end = agent.session.events.find(e => e.type === 'turn/end')
  101. expect(end?.type === 'turn/end' && end.data.reason).toMatchObject({ kind: 'error', step: 1 })
  102. // The turn is balanced (turn/start → turn/end) with no step events inside.
  103. expect(agent.session.events.some(e => e.type === 'step/start')).toBe(false)
  104. })
  105. })