index.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. /**
  2. * Basic replay-aware compaction backend.
  3. *
  4. * @module @deepseek-ai/dsh-compact-basic
  5. */
  6. import { Context } from 'cordis'
  7. import z from 'schemastery'
  8. import { CompactService } from '@deepseek-ai/dsh-compact'
  9. import type { CompactionResult, CompactionTrigger } from '@deepseek-ai/dsh-compact'
  10. import type { Session } from '@deepseek-ai/dsh-session'
  11. import { CONTEXT_WINDOW_EXCEEDED_CODE, assertNever } from '@deepseek-ai/dsh-llm'
  12. import type { ContentBlock, LlmCallConfig } from '@deepseek-ai/dsh-llm'
  13. import type { Agent } from '@deepseek-ai/dsh-agent'
  14. // Type-only: makes the optional sibling service available to `ctx.get()`.
  15. import type {} from '@deepseek-ai/dsh-compact-tool-result-prune'
  16. import {
  17. resolveCompactSpec,
  18. resolveConfig,
  19. resolveTargetPolicy,
  20. TargetPressureConfigError,
  21. } from './config.ts'
  22. import { compactSurfaceRegion, selectCompactableRange } from './region.ts'
  23. import { summarizeWithLlm } from './summarizer.ts'
  24. import type { SummarizationInput } from './summarizer.ts'
  25. import type {
  26. BasicCompactConfig,
  27. ModelCompactPolicyConfig,
  28. ResolvedConfig,
  29. } from './types.ts'
  30. export type {
  31. BasicCompactConfig,
  32. CompactPolicyConfig,
  33. ModelCompactPolicyConfig,
  34. ResolvedCompactSpec,
  35. ResolvedConfig,
  36. ResolvedRetention,
  37. ResolvedTargetPolicy,
  38. } from './types.ts'
  39. /** Resolve the exact provider/model durably routed for the latest request. */
  40. function routedTarget(
  41. session: Session,
  42. ): Pick<LlmCallConfig, 'provider' | 'model'> | undefined {
  43. const config = session.requestHeader()?.config
  44. if (config === undefined || config.provider.length === 0 || config.model.length === 0) {
  45. return undefined
  46. }
  47. return { provider: config.provider, model: config.model }
  48. }
  49. /** Resolve the conversation target used to select an optional policy override. */
  50. function conversationTarget(
  51. agent: Agent,
  52. ): Pick<LlmCallConfig, 'provider' | 'model'> | undefined {
  53. const routed = routedTarget(agent.session)
  54. if (routed !== undefined) return routed
  55. if (agent.options.provider === undefined || agent.options.provider.length === 0
  56. || agent.options.model === undefined || agent.options.model.length === 0) return undefined
  57. return { provider: agent.options.provider, model: agent.options.model }
  58. }
  59. const thresholdRatioSchema = z.number()
  60. const retainRatioSchema = z.number()
  61. const retainTokensSchema = z.number().step(1).min(0)
  62. const summarizationProviderSchema = z.string()
  63. const summarizationModelSchema = z.string()
  64. const maxTokensSchema = z.number().step(1).min(1)
  65. const compactionRetriesSchema = z.number().step(1).min(0)
  66. const maxOverflowRetriesSchema = z.number().step(1).min(0)
  67. const modelPolicy: z<ModelCompactPolicyConfig> = z.object({
  68. provider: z.string().required(),
  69. model: z.string().required(),
  70. thresholdRatio: thresholdRatioSchema,
  71. retainRatio: retainRatioSchema,
  72. retainTokens: retainTokensSchema,
  73. summarizationProvider: summarizationProviderSchema,
  74. summarizationModel: summarizationModelSchema,
  75. maxTokens: maxTokensSchema,
  76. compactionRetries: compactionRetriesSchema,
  77. maxOverflowRetries: maxOverflowRetriesSchema,
  78. })
  79. /**
  80. * Dependency-light compaction backend using `ctx.tokenMeter` for pressure,
  81. * retention, provenance, and summary-convergence pricing.
  82. *
  83. * `summarize()` is the sole subclass customization hook; the replay and durable
  84. * mutation strategy stays fixed so every pricing decision uses the singleton
  85. * token meter.
  86. */
  87. export class BasicCompactService extends CompactService {
  88. static inject = ['llm', 'tokenMeter']
  89. static Config: z<BasicCompactConfig> = z.object({
  90. thresholdRatio: thresholdRatioSchema,
  91. retainRatio: retainRatioSchema,
  92. retainTokens: retainTokensSchema,
  93. summarizationProvider: summarizationProviderSchema,
  94. summarizationModel: summarizationModelSchema,
  95. maxTokens: maxTokensSchema,
  96. compactionRetries: compactionRetriesSchema,
  97. maxOverflowRetries: maxOverflowRetriesSchema,
  98. modelPolicies: z.array(modelPolicy),
  99. auto: z.boolean(),
  100. })
  101. /** Resolved and validated compaction configuration. */
  102. readonly config: ResolvedConfig
  103. private readonly warnedPressureConfigTargets = new Set<string>()
  104. constructor(ctx: Context, config: BasicCompactConfig = {}) {
  105. super(ctx)
  106. this.config = resolveConfig(config)
  107. if (this.config.auto) this._registerAutomaticCompaction()
  108. }
  109. /**
  110. * Register the automatic post-step pressure and context-overflow recovery
  111. * listeners. `compactIfNeeded` stays dynamically dispatched so subclass
  112. * overrides are honored at event time.
  113. */
  114. private _registerAutomaticCompaction(): void {
  115. const { ctx } = this
  116. const logResult = (result: CompactionResult, trigger: string): void => {
  117. ctx.logger.info(
  118. `compaction (${trigger}): shadowed ${result.shadowedSeqs.length} surface nodes `
  119. + `(seqs ${result.shadowedRange.start}-${result.shadowedRange.end}, `
  120. + `~${result.shadowedTokenCount} tokens)`,
  121. )
  122. }
  123. ctx.on('agent/post-step', async (
  124. agent: Agent,
  125. _turn: number,
  126. _step: number,
  127. signal: AbortSignal,
  128. ) => {
  129. if (signal.aborted) return
  130. try {
  131. const result = await this.compactIfNeeded(agent, 'pressure', signal)
  132. if (result !== null) logResult(result, 'post-step pressure')
  133. } catch (error: unknown) {
  134. if (error instanceof TargetPressureConfigError) {
  135. if (this.warnedPressureConfigTargets.has(error.targetKey)) return
  136. this.warnedPressureConfigTargets.add(error.targetKey)
  137. }
  138. const message = error instanceof Error ? error.message : String(error)
  139. ctx.logger.warn(`post-step compaction failed: ${message}; continuing the turn`)
  140. }
  141. })
  142. ctx.on('agent/request-error', async (
  143. agent,
  144. _turn,
  145. _step,
  146. _error,
  147. failure,
  148. priorFailures,
  149. signal,
  150. next,
  151. ) => {
  152. const priorOverflowFailures = priorFailures.filter(
  153. item => item.code === CONTEXT_WINDOW_EXCEEDED_CODE,
  154. ).length
  155. if (failure.code !== CONTEXT_WINDOW_EXCEEDED_CODE || signal.aborted) return next()
  156. const target = routedTarget(agent.session)
  157. if (target === undefined) return next()
  158. const policy = resolveTargetPolicy(this.config, target)
  159. if (priorOverflowFailures >= policy.maxOverflowRetries) return next()
  160. const generation = agent.session.surface.replaceGeneration
  161. let result: CompactionResult | null
  162. try {
  163. result = await this.compactIfNeeded(agent, 'context-overflow', signal)
  164. } catch (recoveryError: unknown) {
  165. const message = recoveryError instanceof Error ? recoveryError.message : String(recoveryError)
  166. // A model-free prune can land before later summary work fails. That
  167. // durable reduction is sufficient retry proof; do not discard it just
  168. // because the optional second phase threw. Cancellation still wins.
  169. // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- signal can abort while recovery is awaited.
  170. if (!signal.aborted && agent.session.surface.replaceGeneration > generation) {
  171. ctx.logger.warn(
  172. `context-overflow compaction failed after durable surface progress: ${message}; `
  173. + 'retrying from the replacement surface',
  174. )
  175. return { action: 'retry' }
  176. }
  177. ctx.logger.warn(
  178. // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- signal can abort while recovery is awaited.
  179. `context-overflow compaction failed: ${message}; ${signal.aborted
  180. ? 'cancellation prevents retry'
  181. : 'preserving the original request error'}`,
  182. )
  183. return next()
  184. }
  185. // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- signal can abort while compaction is awaited.
  186. if (signal.aborted
  187. || agent.session.surface.replaceGeneration <= generation) return next()
  188. if (result !== null) logResult(result, 'context overflow recovery')
  189. return { action: 'retry' }
  190. })
  191. }
  192. /**
  193. * Summarize the replayed conversation region through a direct one-shot
  194. * `ctx.llm.stream()` call whose prefix reuses the conversation's own system
  195. * prompt, tools, and messages so the provider's KV cache is not invalidated.
  196. * Override this sole hook for a template or remote summarizer.
  197. * @param input - replayed conversation prefix (system, tools, and leading messages) to condense.
  198. * @param agent - supplies routed-model history, fallback model, and session id.
  199. * @param signal - optional cancellation forwarded to the adapter.
  200. * @returns safe text summary blocks and exact auxiliary-call provenance.
  201. */
  202. protected async summarize(
  203. input: SummarizationInput,
  204. agent: Agent,
  205. signal?: AbortSignal,
  206. ): Promise<{ summary: ContentBlock[]; provider: string; model: string; maxTokens?: number }> {
  207. const target = conversationTarget(agent)
  208. const config = target === undefined
  209. ? this.config
  210. : resolveTargetPolicy(this.config, target)
  211. return summarizeWithLlm(this.ctx, config, input, agent, signal)
  212. }
  213. /**
  214. * Compact for replayed post-step pressure or one provider-confirmed context
  215. * overflow. Both triggers price the latest durable routed request envelope;
  216. * overflow bypasses the normal threshold and retained-tail policy so it can
  217. * force one useful balanced reduction.
  218. * @param agent - agent whose latest durable routed request is measured.
  219. * @param trigger - normal post-step pressure or context-overflow recovery.
  220. * @param signal - live turn cancellation signal forwarded to summarization.
  221. * @returns the latest summary compaction result, or `null` when no summary ran.
  222. */
  223. override async compactIfNeeded(
  224. agent: Agent,
  225. trigger: CompactionTrigger,
  226. signal: AbortSignal,
  227. ): Promise<CompactionResult | null> {
  228. const target = routedTarget(agent.session)
  229. if (target === undefined) return null
  230. const policy = resolveTargetPolicy(this.config, target)
  231. const meter = this.ctx.tokenMeter
  232. let measurement = meter.measure(agent.session)
  233. switch (trigger) {
  234. case 'context-overflow':
  235. break
  236. case 'pressure':
  237. break
  238. /* v8 ignore next -- closed-union exhaustiveness guard */
  239. default:
  240. assertNever(trigger, 'compaction trigger')
  241. }
  242. // Pruning is optional so compact-basic remains independently composable.
  243. // Overflow always qualifies; pressure first resolves the routed model's
  244. // capacity and checks its target-specific threshold.
  245. const prune = this.ctx.get('toolResultPrune')
  246. if (trigger === 'context-overflow') {
  247. if (prune !== undefined) {
  248. prune.pruneSession(agent.session)
  249. measurement = meter.measure(agent.session)
  250. }
  251. const range = selectCompactableRange(agent.session, measurement, 0)
  252. if (range === null) return null
  253. return this.compactRegion(range.start, range.end, agent, signal)
  254. }
  255. const context = (await this.ctx.llm.resolveModelInfo(target.provider, target.model, signal)).context
  256. const targetKey = `${target.provider}/${target.model}`
  257. if (context === undefined) {
  258. throw new TargetPressureConfigError(
  259. targetKey,
  260. `compact-basic: no context capacity for ${targetKey}; `
  261. + 'configure contextWindow on that adapter model',
  262. )
  263. }
  264. const spec = resolveCompactSpec(policy, context.contextWindow)
  265. if (measurement.totalTokens < spec.thresholdTokens) return null
  266. // Once pressure qualifies, land the model-free pass before choosing a
  267. // summary range, then remeasure through the singleton replay fold.
  268. if (prune !== undefined) {
  269. prune.pruneSession(agent.session)
  270. measurement = meter.measure(agent.session)
  271. }
  272. if (measurement.totalTokens < spec.thresholdTokens) return null
  273. let result: CompactionResult | null = null
  274. for (let attempt = 0; attempt <= spec.compactionRetries; attempt += 1) {
  275. const range = selectCompactableRange(agent.session, measurement, spec.retainTokens)
  276. if (range === null) {
  277. /* v8 ignore else -- concrete replacement preserves a compactable checkpoint; subclass hooks cannot mutate it. */
  278. if (result === null) return null
  279. /* v8 ignore next -- paired with the defensive post-success branch above. */
  280. break
  281. }
  282. result = await this.compactRegion(range.start, range.end, agent, signal)
  283. measurement = meter.measure(agent.session)
  284. if (measurement.totalTokens < spec.thresholdTokens) return result
  285. }
  286. throw new Error(
  287. `compaction still above threshold after ${spec.compactionRetries + 1} compaction attempts `
  288. + `(${measurement.totalTokens} estimated tokens >= threshold ${spec.thresholdTokens})`,
  289. )
  290. }
  291. /**
  292. * Compact one inclusive positional range from the agent-owned surface using
  293. * the effective token meter for all retention and shrink pricing.
  294. * @param start - inclusive first surface-node seq.
  295. * @param end - inclusive last surface-node seq.
  296. * @param agent - owner of the target session, used by the summarizer.
  297. * @param signal - optional summarization cancellation signal.
  298. * @returns the successful durable compaction result.
  299. */
  300. override async compactRegion(
  301. start: number,
  302. end: number,
  303. agent: Agent,
  304. signal?: AbortSignal,
  305. ): Promise<CompactionResult> {
  306. const session = agent.session
  307. return compactSurfaceRegion({
  308. meter: this.ctx.tokenMeter,
  309. summarize: (input, owner, abort) => this.summarize(input, owner, abort),
  310. }, session, start, end, agent, signal)
  311. }
  312. }
  313. export default BasicCompactService