index.ts 17 KB

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