invariant.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132
  1. /** Package-owned agent lifecycle invariants. @module @deepseek-ai/dsh-agent/invariant */
  2. import type { Context } from '@deepseek-ai/cordis'
  3. import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
  4. import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent'
  5. const PACKAGE_NAME = '@deepseek-ai/dsh-agent'
  6. /** Cordis companion plugin name. */
  7. export const name = 'agent-invariant'
  8. /** Services required before the companion can register. */
  9. export const inject = ['invariants']
  10. /** Install the agent contribution into its child registration fiber. */
  11. const install: InvariantInstaller = (ctx, fail) => {
  12. const lastStatus = new WeakMap<Agent, AgentStatus>()
  13. ctx.on('agent/status', ({ agent, status }) => {
  14. const previous = lastStatus.get(agent)
  15. if (previous === status) {
  16. fail(`agent/status repeated ${status} (no-op transition)`)
  17. }
  18. lastStatus.set(agent, status)
  19. }, { global: true })
  20. }
  21. /**
  22. * Register the agent invariant companion.
  23. * @param ctx - Cordis context carrying the invariant service.
  24. * @returns the installed registration's disposer after setup succeeds.
  25. */
  26. export const apply = (ctx: Context): Promise<() => void> =>
  27. Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))