tool-order.spec.ts 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  2. /**
  3. * Loop-level tool-order determinism: the request/header event — and therefore the frozen
  4. * request the adapter receives — carries the assembly's canonical tool order (system-prompt's
  5. * `toolOrder` config, or lexicographic name order), regardless of the order tool plugins
  6. * happened to register in. Registration order is a concurrent loading artifact
  7. * and must not leak downstream.
  8. */
  9. import { describe, expect, it } from 'vitest'
  10. import { Context } from '@deepseek-ai/cordis'
  11. import LlmRuntime from '@deepseek-ai/dsh-llm'
  12. import SessionStore, { SessionId, 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 ToolRuntime, { defineContentToolFixture } from '@deepseek-ai/dsh-tools'
  16. import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent'
  17. import AgentLoop 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(LlmRuntime)
  22. await ctx.plugin(SessionStore)
  23. await ctx.plugin(SystemPrompt, { persona: 'stable base', ...toolOrder !== undefined ? { toolOrder } : {} })
  24. await ctx.plugin(ToolRuntime)
  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: Agent): Promise<void> {
  31. return new Promise((resolve) => {
  32. const dispose = ctx.on('agent/status', ({ agent: 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(defineContentToolFixture({
  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(SessionId('a1'), { provider: 'mock', model: 'mock' })
  56. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  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('closes a no-step turn when toolOrder names an unregistered tool', async () => {
  87. const adapter = new MockAdapter([textResponse('never sent')])
  88. const ctx = await harness(adapter, ['ghost', TOOL_ORDER_REST])
  89. registerNamed(ctx, 'alpha')
  90. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  91. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  92. await waitForIdle(ctx, agent)
  93. expect(adapter.requests).toHaveLength(0)
  94. expect(foldRequestHeader(agent.session.events)).toBeUndefined()
  95. expect(agent.session.events.some(e => e.type === 'turn/start')).toBe(true)
  96. expect(agent.session.events.some(e => e.type === 'turn/end')).toBe(true)
  97. expect(agent.session.events.some(e => e.type === 'step/start')).toBe(false)
  98. expect(agent.session.events.some(e => e.type === 'step/end')).toBe(false)
  99. })
  100. })