invariant.spec.ts 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. import { freezeMessage, MessageId } from '@deepseek-ai/dsh-llm'
  2. import { describe, expect, it } from 'vitest'
  3. import { Context } from 'cordis'
  4. import type { Events } from '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 InvariantService from '@deepseek-ai/dsh-invariants'
  9. async function setup(): Promise<Context> {
  10. const ctx = new Context()
  11. await ctx.plugin(InvariantService)
  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, 1, 0, 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, '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, 'startup'],
  50. 'agent/pre-step': [agent, [message], { turn: 1, step: 1, signal }, () => Promise.resolve({ kind: 'enter', messages: [message] })],
  51. 'agent/request': [agent, 1, 1, signal, () => Promise.resolve(config)],
  52. 'agent/request-error': [
  53. agent,
  54. {
  55. turn: 1,
  56. step: 1,
  57. provider: 'p',
  58. failure: { message: 'request', code: 'UNKNOWN' },
  59. retryPolicy: undefined,
  60. },
  61. signal,
  62. () => Promise.resolve(undefined),
  63. ],
  64. 'agent/turn-stopping': [agent, 1, signal],
  65. 'agent/error': [agent, 1, 0, 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, { 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. ]
  78. for (const [event, args] of rows) {
  79. expect(() => { emit(ctx, scopeTarget(agent, agent), event, args) }, `${event} matching`).not.toThrow()
  80. expect(() => { emit(ctx, scopeTarget(agent, other), event, args) }, `${event} mismatched`)
  81. .toThrow(/DIFFERENT subject/)
  82. }
  83. })
  84. it('requires carriers for generated presence-only scoped events without comparing a payload subject', async () => {
  85. const ctx = await setup()
  86. const agent = { id: 'a1' }
  87. const rows: Array<[string, unknown[]]> = [
  88. ['session/created', [{}]],
  89. ['session/disposed', [{}]],
  90. ['session/event', [{}, {}]],
  91. ['session/flush', [{}]],
  92. ['subagent/end', [{}]],
  93. ['subagent/start', [{}]],
  94. ]
  95. for (const [event, args] of rows) {
  96. expect(() => { emit(ctx, scopeTarget(agent, agent), event, args) }, `${event} carrier`).not.toThrow()
  97. expect(() => { emit(ctx, undefined, event, args) }, `${event} no carrier`)
  98. .toThrow(/dispatched without a scope carrier/)
  99. }
  100. })
  101. })