index.ts 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. /**
  2. * Compaction Service Definition (`ctx.compaction`): providers decide when to
  3. * compact and replace a history range with one summary node by subclassing
  4. * {@link CompactionEngine}. This interface necessarily depends on session and LLM
  5. * vocabulary; the rationale is in the
  6. * [compaction Agent Note](../../../../.agents/notes/implemented/feature/2026-06-18-compaction-capability-seam.md).
  7. * @module @deepseek-ai/dsh-compaction
  8. */
  9. import { Context, Service } from '@deepseek-ai/cordis'
  10. import type { Session } from '@deepseek-ai/dsh-session'
  11. import type { CommandId } from '@deepseek-ai/dsh-commands/brand'
  12. import type { CompactionResult } from './types.ts'
  13. export type { CompactionResult } from './types.ts'
  14. export { CompactionId } from './brand.ts'
  15. export { toolPairingBalancedAfter, toolPairingBalancedBefore } from './tool-pairing.ts'
  16. // The checkpoint source constructor and predicate are declared on the cordis-free
  17. // `./checkpoint` leaf so client and wire programs can name them without this
  18. // root's Context merge; the root stays the host-side entry point for both.
  19. export { compactCheckpointSource, isCompactCheckpointSource } from './checkpoint.ts'
  20. export type { CompactionCheckpointSource } from './checkpoint.ts'
  21. /** Why automatic policy is asking a backend to consider compaction. */
  22. export type CompactionTrigger = 'pressure' | 'context-overflow'
  23. /** Expected failure classes for an explicit idle-session compaction request. */
  24. export type ManualCompactionErrorCode =
  25. | 'busy'
  26. | 'cancelled'
  27. | 'changed'
  28. | 'summary'
  29. | 'commit'
  30. | 'persistence'
  31. /**
  32. * Expected manual-compaction failure suitable for a direct human-command result.
  33. * Shared durable-lock entry assertions may also throw the `busy` subtype from
  34. * automatic compaction paths.
  35. */
  36. export class ManualCompactionError extends Error {
  37. override readonly name = 'ManualCompactionError'
  38. /**
  39. * Create one classified compaction failure.
  40. * @param code - stable failure class; `busy` may originate from any compaction entry path.
  41. * @param message - backend diagnostic retained as the Error message.
  42. * @param options - optional original failure.
  43. */
  44. constructor(
  45. readonly code: ManualCompactionErrorCode,
  46. message: string,
  47. options?: ErrorOptions,
  48. ) {
  49. super(message, options)
  50. }
  51. }
  52. /** Minimal agent context compaction needs without depending on the agent package. */
  53. export interface CompactionAgentContext {
  54. session: Session
  55. options: { provider?: string; model?: string }
  56. }
  57. /**
  58. * Agent capability required to serialize an explicit idle-session compaction
  59. * against driver turns. The durable `compaction/start` marker separately excludes
  60. * other compaction transactions.
  61. */
  62. export interface ManualCompactAgentContext extends CompactionAgentContext {
  63. /**
  64. * Run a non-turn maintenance operation only while the agent is idle, withholding later
  65. * waking input until it settles.
  66. * @param task - operation whose fulfillment or rejection is preserved, with an agent-owned cancellation signal.
  67. * @throws synchronously when the agent is already active.
  68. * @returns the task promise.
  69. */
  70. runMaintenance<T>(task: (signal: AbortSignal) => Promise<T>): Promise<T>
  71. }
  72. declare module '@deepseek-ai/cordis' {
  73. interface Context {
  74. compaction: CompactionEngine
  75. }
  76. }
  77. /**
  78. * Abstract compaction service. Implementations own trigger policy, retention,
  79. * and summarization, and may consume a separate measurement service. A
  80. * successful run replaces the selected surface span with one summary node and
  81. * prevents concurrent compaction of the same session. The replacement user
  82. * message uses {@link compactCheckpointSource} with the transaction identity
  83. * so consumers recognize and correlate it independently of the backend. Load
  84. * one implementation per context as `ctx.compaction`.
  85. */
  86. export abstract class CompactionEngine extends Service {
  87. constructor(ctx: Context) {
  88. super(ctx, 'compaction')
  89. }
  90. /**
  91. * Consider automatic compaction for one explicit trigger. Pressure policy
  92. * uses the latest durable routed request, while context-overflow policy may
  93. * force a useful balanced reduction even below the normal threshold. Return
  94. * `null` when no safe range can be compacted. A single oversized retained
  95. * unit or request envelope cannot be repaired through surface compaction.
  96. *
  97. * @param agent - agent context owning the session surface and routing options.
  98. * @param trigger - normal pressure or provider-confirmed context overflow.
  99. * @param signal - cancellation signal; model-backed implementations must forward it.
  100. * @returns the compaction result, or `null` if no compaction was needed.
  101. */
  102. abstract compactIfNeeded(
  103. agent: CompactionAgentContext,
  104. trigger: CompactionTrigger,
  105. signal: AbortSignal,
  106. ): Promise<CompactionResult | null>
  107. /**
  108. * Explicitly compact useful history even below automatic pressure thresholds.
  109. * Implementations synchronously start an idle task before any asynchronous
  110. * work, select a useful range without writing on a no-op, then
  111. * append a standalone `compaction/start` before summarization. That durable
  112. * marker is the compaction lock until one `compaction/end` attempt. Later waking
  113. * prompts remain accepted in FIFO order and start only after the optional
  114. * durability checkpoint and idle-task settlement. Context injected while the
  115. * summary runs may sit between the marker pair; only the selected span must
  116. * remain stable.
  117. *
  118. * @param agent - idle agent whose durable history should be compacted.
  119. * @param signal - cancellation scoped to this compaction request.
  120. * @param sourceCommandId - initiating command identity for a manual compaction.
  121. * @returns the compaction result, or `null` when no safe useful range exists.
  122. * @throws {@link ManualCompactionError} for expected busy, agent-cancellation,
  123. * changed-span, summarization/shrink, commit-stage, or persistence failures;
  124. * an aborted request preserves its exact abort reason. Failed attempts remain
  125. * visible in the log.
  126. */
  127. abstract compactNow(
  128. agent: ManualCompactAgentContext,
  129. signal: AbortSignal,
  130. sourceCommandId?: CommandId,
  131. ): Promise<CompactionResult | null>
  132. /**
  133. * Forcibly compact a range of surface nodes into a single summary node.
  134. * `start` and `end` name an inclusive span by surface position, not numeric seq
  135. * order; replacements can make visible seqs non-monotonic. Both edges must be
  136. * balanced so assistant tool calls remain paired with their results. A model-
  137. * backed implementation forwards cancellation and rejects active, missing,
  138. * reversed, or unbalanced ranges. The target session is `agent.session`.
  139. * Its replacement user message must use {@link compactCheckpointSource} with
  140. * the transaction's `CompactionId`.
  141. * Use {@link toolPairingBalancedBefore} and {@link toolPairingBalancedAfter}
  142. * for the edge checks.
  143. *
  144. * @param start - first surface seq, inclusive.
  145. * @param end - last surface seq, inclusive.
  146. * @param agent - context whose session is mutated and whose routing options guide summarization.
  147. * @param signal - optional cancellation; model-backed implementations must forward it.
  148. * @throws when compaction is active or the range is missing, reversed, or unbalanced.
  149. * @returns the appended event seqs, summary, replaced range, and token accounting.
  150. */
  151. abstract compactRegion(
  152. start: number,
  153. end: number,
  154. agent: CompactionAgentContext,
  155. signal?: AbortSignal,
  156. ): Promise<CompactionResult>
  157. }
  158. export default CompactionEngine