tool-order.spec.ts 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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, { SessionId, 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, { defineContentToolFixture } from '@deepseek-ai/dsh-tools'
  15. import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent'
  16. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  17. import { MockAdapter, textResponse } from './mock-adapter.ts'
  18. async function harness(adapter: MockAdapter, toolOrder?: SystemPromptConfig['toolOrder']) {
  19. const ctx = new Context()
  20. await ctx.plugin(LlmService)
  21. await ctx.plugin(SessionStore)
  22. await ctx.plugin(SystemPrompt, { persona: 'stable base', ...toolOrder !== undefined ? { toolOrder } : {} })
  23. await ctx.plugin(ToolRegistry)
  24. await ctx.plugin(AgentRegistry)
  25. await ctx.plugin(AgentLoop, { agents: [] })
  26. ctx.llm.registerAdapter(['mock'], adapter)
  27. return ctx
  28. }
  29. function waitForIdle(ctx: Context, agent: Agent): Promise<void> {
  30. return new Promise((resolve) => {
  31. const dispose = ctx.on('agent/status', (subject, status) => {
  32. if (subject === agent && status === 'idle') {
  33. dispose()
  34. resolve()
  35. }
  36. })
  37. })
  38. }
  39. function registerNamed(ctx: Context, name: string) {
  40. ctx.tools.register(defineContentToolFixture({
  41. name,
  42. description: `the ${name} tool`,
  43. parameters: {},
  44. async execute() {
  45. return [{ type: 'text', text: name }]
  46. },
  47. }))
  48. }
  49. /** Run one text-only turn and return the harness context + agent. */
  50. async function runTurn(registrationOrder: string[], toolOrder?: SystemPromptConfig['toolOrder']) {
  51. const adapter = new MockAdapter([textResponse('done')])
  52. const ctx = await harness(adapter, toolOrder)
  53. for (const name of registrationOrder) registerNamed(ctx, name)
  54. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  55. agent.followup({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } })
  56. await waitForIdle(ctx, agent)
  57. return { ctx, agent, adapter }
  58. }
  59. describe('loop-level canonical tool order', () => {
  60. it('logs the request/header with tools in canonical order, not registration order', async () => {
  61. const { agent, adapter } = await runTurn(['zulu', 'alpha', 'mike'])
  62. const header = foldRequestHeader(agent.session.events)
  63. expect(header?.tools?.map(tool => tool.name)).toEqual(['alpha', 'mike', 'zulu'])
  64. // The dispatched request is built FROM the logged header (whose tools the
  65. // assembly already canonicalized) and reaches the adapter deep-frozen —
  66. // the marker the reconstruction invariant keys on.
  67. expect(adapter.requests[0]?.tools?.map(tool => tool.name)).toEqual(['alpha', 'mike', 'zulu'])
  68. expect(Object.isFrozen(adapter.requests[0])).toBe(true)
  69. expect(adapter.requests[0]?.sessionId).toBe(agent.session.id)
  70. })
  71. it('produces the same header order for any registration order', async () => {
  72. const first = await runTurn(['alpha', 'mike', 'zulu'])
  73. const second = await runTurn(['zulu', 'mike', 'alpha'])
  74. const names = (run: typeof first) => foldRequestHeader(run.agent.session.events)?.tools?.map(tool => tool.name)
  75. expect(names(first)).toEqual(['alpha', 'mike', 'zulu'])
  76. expect(names(second)).toEqual(names(first))
  77. })
  78. it('honors a configured toolOrder in the logged header and the dispatched request', async () => {
  79. const { agent, adapter } = await runTurn(['alpha', 'zulu', 'mike'], ['zulu', TOOL_ORDER_REST])
  80. const header = foldRequestHeader(agent.session.events)
  81. expect(header?.tools?.map(tool => tool.name)).toEqual(['zulu', 'alpha', 'mike'])
  82. expect(adapter.requests[0]?.tools?.map(tool => tool.name)).toEqual(['zulu', 'alpha', 'mike'])
  83. expect(Object.isFrozen(adapter.requests[0])).toBe(true)
  84. })
  85. it('fails the turn — no model request — when toolOrder names an unregistered tool', async () => {
  86. // Unknown tool order fails before step or request creation and returns the agent to idle.
  87. const adapter = new MockAdapter([textResponse('never sent')])
  88. const ctx = await harness(adapter, ['ghost', TOOL_ORDER_REST])
  89. registerNamed(ctx, 'alpha')
  90. const errors: Error[] = []
  91. ctx.on('agent/error', (_agent, _turn, _step, error) => {
  92. if (error instanceof Error) errors.push(error)
  93. })
  94. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  95. agent.followup({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } })
  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. })