index.ts 16 KB

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