index.ts 17 KB

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