tool-order.spec.ts 5.5 KB

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