index.ts 17 KB

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