index.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. private readonly overflowRetries = new WeakMap<Agent, number>()
  105. private readonly overflowAgents = new WeakMap<Session, Agent>()
  106. constructor(ctx: Context, config: BasicCompactConfig = {}) {
  107. super(ctx)
  108. this.config = resolveConfig(config)
  109. if (this.config.auto) this._registerAutomaticCompaction()
  110. }
  111. /**
  112. * Register automatic between-step pressure and model-request overflow
  113. * recovery. `compactIfNeeded` stays dynamically dispatched so subclass
  114. * overrides are honored at event time.
  115. */
  116. private _registerAutomaticCompaction(): void {
  117. const { ctx } = this
  118. const logResult = (result: CompactionResult, trigger: string): void => {
  119. ctx.logger.info(
  120. `compaction (${trigger}): shadowed ${result.shadowedSeqs.length} surface nodes `
  121. + `(seqs ${result.shadowedRange.start}-${result.shadowedRange.end}, `
  122. + `~${result.shadowedTokenCount} tokens)`,
  123. )
  124. }
  125. ctx.on('agent/step', async (
  126. agent: Agent,
  127. _turn: number,
  128. _step: number,
  129. signal: AbortSignal,
  130. ) => {
  131. if (signal.aborted) return
  132. try {
  133. const result = await this.compactIfNeeded(agent, 'pressure', signal)
  134. if (result !== null) logResult(result, 'step pressure')
  135. } catch (error: unknown) {
  136. if (error instanceof TargetPressureConfigError) {
  137. if (this.warnedPressureConfigTargets.has(error.targetKey)) return
  138. this.warnedPressureConfigTargets.add(error.targetKey)
  139. }
  140. const message = error instanceof Error ? error.message : String(error)
  141. ctx.logger.warn(`step compaction failed: ${message}; continuing the turn`)
  142. }
  143. })
  144. ctx.on('agent/settled', (agent) => {
  145. this.overflowRetries.delete(agent)
  146. })
  147. // A successful response starts a fresh overflow-recovery sequence even
  148. // when tool calls continue the same turn into another request.
  149. ctx.on('session/event', (session, event) => {
  150. if (event.type !== 'assistant/message') return
  151. const agent = this.overflowAgents.get(session)
  152. if (agent !== undefined) this.overflowRetries.delete(agent)
  153. })
  154. ctx.on('agent/request-error', async (
  155. agent,
  156. _turn,
  157. _step,
  158. _error,
  159. failure,
  160. _priorFailures,
  161. _retryPolicy,
  162. signal,
  163. next,
  164. ) => {
  165. if (failure.code !== CONTEXT_WINDOW_EXCEEDED_CODE || signal.aborted) return next()
  166. this.overflowAgents.set(agent.session, agent)
  167. const target = routedTarget(agent.session)
  168. if (target === undefined) return next()
  169. const policy = resolveTargetPolicy(this.config, target)
  170. const retries = this.overflowRetries.get(agent) ?? 0
  171. if (retries >= policy.maxOverflowRetries) return next()
  172. const generation = agent.session.surface.replaceGeneration
  173. let result: CompactionResult | null
  174. try {
  175. result = await this.compactIfNeeded(agent, 'context-overflow', signal)
  176. } catch (recoveryError: unknown) {
  177. const message = recoveryError instanceof Error ? recoveryError.message : String(recoveryError)
  178. // A model-free prune can land before later summary work fails. That
  179. // durable reduction is sufficient retry proof; do not discard it just
  180. // because the optional second phase threw. Cancellation still wins.
  181. // oxlint-disable-next-line typescript/no-unnecessary-condition -- the signal can abort while recovery is awaited.
  182. if (!signal.aborted && agent.session.surface.replaceGeneration > generation) {
  183. ctx.logger.warn(
  184. `context-overflow compaction failed after durable surface progress: ${message}; `
  185. + 'retrying from the replacement surface',
  186. )
  187. this.overflowRetries.set(agent, retries + 1)
  188. return { kind: 'retry' }
  189. }
  190. ctx.logger.warn(
  191. // oxlint-disable-next-line typescript/no-unnecessary-condition -- the signal can abort while recovery is awaited.
  192. `context-overflow compaction failed: ${message}; ${signal.aborted
  193. ? 'cancellation prevents retry'
  194. : 'preserving the original request error'}`,
  195. )
  196. return next()
  197. }
  198. // oxlint-disable-next-line typescript/no-unnecessary-condition -- the signal can abort while compaction is awaited.
  199. if (signal.aborted
  200. || agent.session.surface.replaceGeneration <= generation) return next()
  201. if (result !== null) logResult(result, 'context overflow recovery')
  202. this.overflowRetries.set(agent, retries + 1)
  203. return { kind: 'retry' }
  204. })
  205. }
  206. /**
  207. * Summarize the replayed conversation region through a direct one-shot
  208. * `ctx.llm.stream()` call whose prefix reuses the conversation's own system
  209. * prompt, tools, and messages so the provider's KV cache is not invalidated.
  210. * Override this sole hook for a template or remote summarizer.
  211. * @param input - replayed conversation prefix (system, tools, and leading messages) to condense.
  212. * @param agent - supplies routed-model history, fallback model, and session id.
  213. * @param signal - optional cancellation forwarded to the adapter.
  214. * @returns safe text summary blocks and exact auxiliary-call provenance.
  215. */
  216. protected async summarize(
  217. input: SummarizationInput,
  218. agent: Agent,
  219. signal?: AbortSignal,
  220. ): Promise<{ summary: ContentBlock[]; provider: string; model: string; maxTokens?: number }> {
  221. const target = conversationTarget(agent)
  222. const config = target === undefined
  223. ? this.config
  224. : resolveTargetPolicy(this.config, target)
  225. return summarizeWithLlm(this.ctx, config, input, agent, signal)
  226. }
  227. /**
  228. * Compact for replayed step-boundary pressure or one provider-confirmed context
  229. * overflow. Both triggers price the latest durable routed request envelope;
  230. * overflow bypasses the normal threshold and retained-tail policy so it can
  231. * force one useful balanced reduction.
  232. * @param agent - agent whose latest durable routed request is measured.
  233. * @param trigger - normal step-boundary pressure or context-overflow recovery.
  234. * @param signal - live turn cancellation signal forwarded to summarization.
  235. * @returns the latest summary compaction result, or `null` when no summary ran.
  236. */
  237. override async compactIfNeeded(
  238. agent: Agent,
  239. trigger: CompactionTrigger,
  240. signal: AbortSignal,
  241. ): Promise<CompactionResult | null> {
  242. const target = routedTarget(agent.session)
  243. if (target === undefined) return null
  244. const policy = resolveTargetPolicy(this.config, target)
  245. const meter = this.ctx.tokenMeter
  246. let measurement = meter.measure(agent.session)
  247. switch (trigger) {
  248. case 'context-overflow':
  249. break
  250. case 'pressure':
  251. break
  252. /* v8 ignore next -- closed-union exhaustiveness guard */
  253. default:
  254. assertNever(trigger, 'compaction trigger')
  255. }
  256. // Pruning is optional so compact-basic remains independently composable.
  257. // Overflow always qualifies; pressure first resolves the routed model's
  258. // capacity and checks its target-specific threshold.
  259. const prune = this.ctx.get('toolResultPrune')
  260. if (trigger === 'context-overflow') {
  261. if (prune !== undefined) {
  262. prune.pruneSession(agent.session)
  263. measurement = meter.measure(agent.session)
  264. }
  265. const range = selectCompactableRange(agent.session, measurement, 0)
  266. if (range === null) return null
  267. return this.compactRegion(range.start, range.end, agent, signal)
  268. }
  269. const context = (await this.ctx.llm.resolveModelInfo(target.provider, target.model, signal)).context
  270. const targetKey = `${target.provider}/${target.model}`
  271. if (context === undefined) {
  272. throw new TargetPressureConfigError(
  273. targetKey,
  274. `compact-basic: no context capacity for ${targetKey}; `
  275. + 'configure contextWindow on that adapter model',
  276. )
  277. }
  278. const spec = resolveCompactSpec(policy, context.contextWindow)
  279. if (measurement.totalTokens < spec.thresholdTokens) return null
  280. // Once pressure qualifies, land the model-free pass before choosing a
  281. // summary range, then remeasure through the singleton replay fold.
  282. if (prune !== undefined) {
  283. prune.pruneSession(agent.session)
  284. measurement = meter.measure(agent.session)
  285. }
  286. if (measurement.totalTokens < spec.thresholdTokens) return null
  287. let result: CompactionResult | null = null
  288. for (let attempt = 0; attempt <= spec.compactionRetries; attempt += 1) {
  289. const range = selectCompactableRange(agent.session, measurement, spec.retainTokens)
  290. if (range === null) {
  291. /* v8 ignore else -- concrete replacement preserves a compactable checkpoint; subclass hooks cannot mutate it. */
  292. if (result === null) return null
  293. /* v8 ignore next -- paired with the defensive post-success branch above. */
  294. break
  295. }
  296. result = await this.compactRegion(range.start, range.end, agent, signal)
  297. measurement = meter.measure(agent.session)
  298. if (measurement.totalTokens < spec.thresholdTokens) return result
  299. }
  300. throw new Error(
  301. `compaction still above threshold after ${spec.compactionRetries + 1} compaction attempts `
  302. + `(${measurement.totalTokens} estimated tokens >= threshold ${spec.thresholdTokens})`,
  303. )
  304. }
  305. /**
  306. * Compact one inclusive positional range from the agent-owned surface using
  307. * the effective token meter for all retention and shrink pricing.
  308. * @param start - inclusive first surface-node seq.
  309. * @param end - inclusive last surface-node seq.
  310. * @param agent - owner of the target session, used by the summarizer.
  311. * @param signal - optional summarization cancellation signal.
  312. * @returns the successful durable compaction result.
  313. */
  314. override async compactRegion(
  315. start: number,
  316. end: number,
  317. agent: Agent,
  318. signal?: AbortSignal,
  319. ): Promise<CompactionResult> {
  320. const session = agent.session
  321. return compactSurfaceRegion({
  322. meter: this.ctx.tokenMeter,
  323. summarize: (input, owner, abort) => this.summarize(input, owner, abort),
  324. }, session, start, end, agent, signal)
  325. }
  326. }
  327. export default BasicCompactService