invariant.spec.ts 4.6 KB

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