invariant.spec.ts 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. import { freezeMessage, MessageId } from '@deepseek-ai/dsh-llm'
  2. import { describe, expect, it } from 'vitest'
  3. import { Context } from '@deepseek-ai/cordis'
  4. import type { Events } from '@deepseek-ai/cordis'
  5. import type { Agent } from '@deepseek-ai/dsh-agent'
  6. import { scopeTarget } from '@deepseek-ai/dsh-scope'
  7. import * as ScopeInvariant from '@deepseek-ai/dsh-scope/invariant'
  8. import InvariantRegistry from '@deepseek-ai/dsh-invariants'
  9. async function setup(): Promise<Context> {
  10. const ctx = new Context()
  11. await ctx.plugin(InvariantRegistry)
  12. await ctx.plugin(ScopeInvariant)
  13. return ctx
  14. }
  15. function emit(ctx: Context, receiver: object | undefined, event: string, args: unknown[]): void {
  16. const dispatch = ctx.emit.bind(ctx) as (...values: unknown[]) => void
  17. if (receiver === undefined) dispatch(event, ...args)
  18. else dispatch(receiver, event, ...args)
  19. }
  20. describe('scoped-dispatch invariants', () => {
  21. type AgentEventName = Extract<keyof Events, `agent/${string}`>
  22. type EventArgs<K extends keyof Events> = Events[K] extends (...args: infer Args) => unknown ? Args : never
  23. it('ignores ordinary events and rejects a scoped dispatch without a carrier', async () => {
  24. const ctx = await setup()
  25. expect(() => { emit(ctx, undefined, 'ordinary/event', []) }).not.toThrow()
  26. const agent = { id: 'a1' }
  27. expect(() => { emit(ctx, undefined, 'agent/error', [{ agent, turn: 1, step: 0, error: new Error('x') }]) })
  28. .toThrow(/dispatched without a scope carrier/)
  29. })
  30. it('checks every generated subject resolver against the carrier key', async () => {
  31. const ctx = await setup()
  32. const agent = { id: 'a1' } as unknown as Agent
  33. const other = { id: 'a2' } as unknown as Agent
  34. const signal = new AbortController().signal
  35. const config = { provider: 'p', model: 'm' }
  36. const message = freezeMessage({
  37. id: MessageId('m'),
  38. role: 'user',
  39. content: [],
  40. source: { kind: 'user' },
  41. })
  42. const agentRows = {
  43. 'agent/created': [{ agent }],
  44. 'agent/disposed': [{ agent }],
  45. 'agent/status': [{ agent, status: 'idle' }],
  46. 'agent/inbox/inserted': [{ agent, message }],
  47. 'agent/inbox/claimed': [{ agent, message, turn: 1 }],
  48. 'agent/inbox/discarded': [{ agent, message }],
  49. 'agent/session-start': [{ agent, source: 'startup' }],
  50. 'agent/pre-step': [{ agent, messages: [message], turn: 1, step: 1, signal }, () => Promise.resolve({ kind: 'enter', messages: [message] })],
  51. 'agent/request': [{ agent, turn: 1, step: 1, signal }, () => Promise.resolve(config)],
  52. 'agent/request-error': [
  53. {
  54. agent,
  55. turn: 1,
  56. step: 1,
  57. provider: 'p',
  58. failure: { message: 'request', code: 'UNKNOWN' },
  59. retryPolicy: undefined,
  60. signal,
  61. },
  62. () => Promise.resolve(undefined),
  63. ],
  64. 'agent/turn-stopping': [{ agent, turn: 1, signal }],
  65. 'agent/error': [{ agent, turn: 1, step: 0, error: new Error('x') }],
  66. } satisfies { [K in AgentEventName]: EventArgs<K> }
  67. const rows: Array<[string, unknown[]]> = [
  68. ...Object.entries(agentRows),
  69. ['approval/request', [{ agent, toolName: 'echo' }, () => Promise.resolve('unavailable')]],
  70. ['goal/changed', [{ agent, change: { operation: 'create', ref: { id: 'goal-a', revision: 1 } } }]],
  71. ['system-prompt/assemble', [[], { scope: agent }]],
  72. ['tools/code-dispatch-log', [{ exec: { callId: 'c', name: 't', arguments: {} }, agent, subCallId: 'c:code:1', name: 't', isError: false, content: [] }, () => Promise.resolve([])]],
  73. ['tools/execute', [{ callId: 'c', name: 't', arguments: {}, agent }, () => Promise.resolve({ content: [], isError: false })]],
  74. ['tools/post-execute', [{ callId: 'c', name: 't', arguments: {}, agent }, { content: [], isError: false }, () => Promise.resolve({ kind: 'accept' })]],
  75. ['tools/pre-execute', [{ callId: 'c', name: 't', arguments: {}, agent }, () => Promise.resolve({ kind: 'allow' })]],
  76. ['tools/result', [{ callId: 'c', name: 't', arguments: {}, agent }, { content: [], isError: false }]],
  77. ['user-questions/request', [{ agent, questions: [] }, () => Promise.resolve({ answers: [] })]],
  78. ]
  79. for (const [event, args] of rows) {
  80. expect(() => { emit(ctx, scopeTarget(agent, agent), event, args) }, `${event} matching`).not.toThrow()
  81. expect(() => { emit(ctx, scopeTarget(agent, other), event, args) }, `${event} mismatched`)
  82. .toThrow(/DIFFERENT subject/)
  83. }
  84. })
  85. it('requires carriers for generated presence-only scoped events without comparing a payload subject', async () => {
  86. const ctx = await setup()
  87. const agent = { id: 'a1' }
  88. const rows: Array<[string, unknown[]]> = [
  89. ['session/created', [{}]],
  90. ['session/disposed', [{}]],
  91. ['session/event', [{}, {}]],
  92. ['session/flush', [{}]],
  93. ['subagent/end', [{}]],
  94. ['subagent/start', [{}]],
  95. ]
  96. for (const [event, args] of rows) {
  97. expect(() => { emit(ctx, scopeTarget(agent, agent), event, args) }, `${event} carrier`).not.toThrow()
  98. expect(() => { emit(ctx, undefined, event, args) }, `${event} no carrier`)
  99. .toThrow(/dispatched without a scope carrier/)
  100. }
  101. })
  102. })