tool-order.spec.ts 5.7 KB

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