invariant.ts 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. /** Package-owned tool-pipeline invariants. @module @deepseek-ai/dsh-tools/invariant */
  2. import type { Context } from '@deepseek-ai/cordis'
  3. import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
  4. import type { InvariantFailure, InvariantInstaller } from '@deepseek-ai/dsh-invariants'
  5. import type { ToolExecution, ToolExecutionResult } from './index.ts'
  6. const PACKAGE_NAME = '@deepseek-ai/dsh-tools'
  7. /** Cordis companion plugin name. */
  8. export const name = 'tools-invariant'
  9. /** Service required before the companion can reserve package ownership. */
  10. export const inject = ['invariants']
  11. type ToolStage = 'pre' | 'execute' | 'post'
  12. /** Validate the immutable final execution/result snapshot. */
  13. function validateResult(
  14. exec: Readonly<ToolExecution>,
  15. result: Readonly<ToolExecutionResult>,
  16. fail: InvariantFailure,
  17. ): void {
  18. if (!Object.isFrozen(exec)) fail('tools/result execution must be frozen before publication')
  19. if (!Object.isFrozen(result) || !Object.isFrozen(result.content)) {
  20. fail('tools/result outcome and content must be frozen before publication')
  21. }
  22. if (exec.name.length === 0 || String(exec.callId).length === 0) {
  23. fail('tools/result execution must carry non-empty name and callId')
  24. }
  25. }
  26. /** Install monotonic pipeline, final-snapshot, and code-dispatch enclosure checks. */
  27. const install: InvariantInstaller = Object.assign((ctx: Context, fail: InvariantFailure) => {
  28. const stages = new WeakMap<object, ToolStage>()
  29. const openTurns = new WeakMap<Session, number | null>()
  30. const dispatchRoots = new WeakMap<Session, Map<string, string>>()
  31. const validateDispatch = (session: Session, event: SessionEvent): void => {
  32. if (event.type !== 'tool/code-dispatch-start' && event.type !== 'tool/code-dispatch') return
  33. const root = String(event.data.rootCallId)
  34. const parent = String(event.data.parentCallId)
  35. const child = String(event.data.subCallId)
  36. if (root.length === 0 || parent.length === 0 || child.length === 0) {
  37. fail(`${event.type} must carry non-empty rootCallId, parentCallId, and subCallId`)
  38. return
  39. }
  40. const roots = dispatchRoots.get(session)
  41. const known = roots?.get(child)
  42. if (known !== undefined && known !== root) fail(`${event.type} changed rootCallId for subCallId ${child}`)
  43. if (parent !== root && roots?.get(parent) !== root) {
  44. fail(`${event.type} parentCallId ${parent} does not belong to rootCallId ${root}`)
  45. }
  46. }
  47. const commitDispatch = (session: Session, event: SessionEvent): void => {
  48. if (event.type !== 'tool/code-dispatch-start' && event.type !== 'tool/code-dispatch') return
  49. const roots = dispatchRoots.get(session) as Map<string, string>
  50. roots.set(String(event.data.subCallId), String(event.data.rootCallId))
  51. }
  52. const seed = (session: Session): number | null => {
  53. let openTurn: number | null = null
  54. dispatchRoots.set(session, new Map())
  55. for (const event of session.events) {
  56. validateDispatch(session, event)
  57. commitDispatch(session, event)
  58. if (event.type === 'turn/start') openTurn = event.data.turn
  59. else if (event.type === 'turn/end') openTurn = null
  60. else if ((event.type === 'tool/code-dispatch-start' || event.type === 'tool/code-dispatch')
  61. && openTurn === null) {
  62. fail(`${event.type} appended outside any open turn`)
  63. }
  64. }
  65. openTurns.set(session, openTurn)
  66. return openTurn
  67. }
  68. const openTurnFor = (session: Session): number | null => openTurns.get(session) ?? seed(session)
  69. for (const session of ctx.sessions.list()) seed(session)
  70. ctx.on('session/created', (session) => { seed(session) }, { global: true })
  71. ctx.on('session/event', (session, event) => {
  72. validateDispatch(session, event)
  73. commitDispatch(session, event)
  74. if (event.type === 'turn/start') openTurns.set(session, event.data.turn)
  75. else if (event.type === 'turn/end') openTurns.set(session, null)
  76. }, { global: true })
  77. ctx.on('internal/dispatch', (_mode, eventName, args) => {
  78. if (eventName === 'session/event') {
  79. const [session, event] = args as [Session, SessionEvent]
  80. validateDispatch(session, event)
  81. if ((event.type === 'tool/code-dispatch-start' || event.type === 'tool/code-dispatch')
  82. && openTurnFor(session) === null) {
  83. fail(`${event.type} appended outside any open turn`)
  84. }
  85. return
  86. }
  87. if (eventName === 'tools/pre-execute') {
  88. const exec = args[0] as ToolExecution
  89. if (stages.has(exec)) fail('tools/pre-execute repeated for one execution')
  90. stages.set(exec, 'pre')
  91. return
  92. }
  93. if (eventName === 'tools/execute') {
  94. const exec = args[0] as ToolExecution
  95. if (stages.get(exec) !== 'pre') fail('tools/execute must follow tools/pre-execute')
  96. stages.set(exec, 'execute')
  97. return
  98. }
  99. if (eventName === 'tools/post-execute') {
  100. const exec = args[0] as ToolExecution
  101. const previous = stages.get(exec)
  102. if (previous !== 'pre' && previous !== 'execute') {
  103. fail('tools/post-execute must follow tools/pre-execute or tools/execute')
  104. }
  105. stages.set(exec, 'post')
  106. return
  107. }
  108. if (eventName !== 'tools/result') return
  109. const [exec, result] = args as [Readonly<ToolExecution>, Readonly<ToolExecutionResult>]
  110. validateResult(exec, result, fail)
  111. stages.delete(exec)
  112. }, { global: true })
  113. }, { inject: ['sessions'] })
  114. /**
  115. * Register the tools invariant companion.
  116. * @param ctx - Cordis context carrying the invariant service.
  117. * @returns the installed registration's disposer after setup succeeds.
  118. */
  119. export const apply = (ctx: Context): Promise<() => void> =>
  120. Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))