invariant.spec.ts 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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/assistant-stream': [{
  53. agent,
  54. frame: {
  55. type: 'start', attemptId: 'attempt-1' as never, revision: 1, turn: 1, step: 1,
  56. },
  57. }],
  58. 'agent/request-error': [
  59. {
  60. agent,
  61. turn: 1,
  62. step: 1,
  63. provider: 'p',
  64. failure: { message: 'request', code: 'UNKNOWN' },
  65. retryPolicy: undefined,
  66. signal,
  67. },
  68. () => Promise.resolve(undefined),
  69. ],
  70. 'agent/turn-stopping': [{ agent, turn: 1, signal }],
  71. 'agent/error': [{ agent, turn: 1, step: 0, error: new Error('x') }],
  72. } satisfies { [K in AgentEventName]: EventArgs<K> }
  73. const rows: Array<[string, unknown[]]> = [
  74. ...Object.entries(agentRows),
  75. ['approval/request', [{ agent, toolName: 'echo' }, () => Promise.resolve('unavailable')]],
  76. ['goal/changed', [{ agent, change: { operation: 'create', ref: { id: 'goal-a', revision: 1 } } }]],
  77. ['system-prompt/assemble', [[], { scope: agent }]],
  78. ['tools/ptc-dispatch-log', [{ exec: { callId: 'c', name: 't', arguments: {} }, agent, subCallId: 'c:code:1', name: 't', isError: false, content: [] }, () => Promise.resolve([])]],
  79. ['tools/execute', [{ callId: 'c', name: 't', arguments: {}, agent }, () => Promise.resolve({ content: [], isError: false })]],
  80. ['tools/post-execute', [{ callId: 'c', name: 't', arguments: {}, agent }, { content: [], isError: false }, () => Promise.resolve({ kind: 'accept' })]],
  81. ['tools/pre-execute', [{ callId: 'c', name: 't', arguments: {}, agent }, () => Promise.resolve({ kind: 'allow' })]],
  82. ['tools/result', [{ callId: 'c', name: 't', arguments: {}, agent }, { content: [], isError: false }]],
  83. ['user-questions/request', [{ agent, questions: [] }, () => Promise.resolve({ answers: [] })]],
  84. ]
  85. for (const [event, args] of rows) {
  86. expect(() => { emit(ctx, scopeTarget(agent, agent), event, args) }, `${event} matching`).not.toThrow()
  87. expect(() => { emit(ctx, scopeTarget(agent, other), event, args) }, `${event} mismatched`)
  88. .toThrow(/DIFFERENT subject/)
  89. }
  90. })
  91. it('requires carriers for generated presence-only scoped events without comparing a payload subject', async () => {
  92. const ctx = await setup()
  93. const agent = { id: 'a1' }
  94. const rows: Array<[string, unknown[]]> = [
  95. ['session/created', [{}]],
  96. ['session/disposed', [{}]],
  97. ['session/event', [{}, {}]],
  98. ['session/flush', [{}]],
  99. ['subagent/end', [{}]],
  100. ['subagent/start', [{}]],
  101. ]
  102. for (const [event, args] of rows) {
  103. expect(() => { emit(ctx, scopeTarget(agent, agent), event, args) }, `${event} carrier`).not.toThrow()
  104. expect(() => { emit(ctx, undefined, event, args) }, `${event} no carrier`)
  105. .toThrow(/dispatched without a scope carrier/)
  106. }
  107. })
  108. })