index.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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, PreStepDecision } 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/pre-step', async (
  133. agent: Agent,
  134. _messages,
  135. { 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,
  165. context,
  166. signal,
  167. next,
  168. ) => {
  169. const { failure } = context
  170. if (failure.code !== CONTEXT_WINDOW_EXCEEDED_CODE || signal.aborted) return next()
  171. this.overflowAgents.set(agent.session, agent)
  172. const target = routedTarget(agent.session)
  173. if (target === undefined) return next()
  174. const policy = resolveTargetPolicy(this.config, target)
  175. const retries = this.overflowRetries.get(agent) ?? 0
  176. if (retries >= policy.maxOverflowRetries) return next()
  177. const generation = agent.session.surface.replaceGeneration
  178. let result: CompactionResult | null
  179. try {
  180. result = await this.compactIfNeeded(agent, 'context-overflow', signal)
  181. } catch (recoveryError: unknown) {
  182. const message = recoveryError instanceof Error ? recoveryError.message : String(recoveryError)
  183. // A model-free prune can land before later summary work fails. That
  184. // durable reduction is sufficient retry proof; do not discard it just
  185. // because the optional second phase threw. Cancellation still wins.
  186. // oxlint-disable-next-line typescript/no-unnecessary-condition -- the signal can abort while recovery is awaited.
  187. if (!signal.aborted && agent.session.surface.replaceGeneration > generation) {
  188. ctx.logger.warn(
  189. `context-overflow compaction failed after durable surface progress: ${message}; `
  190. + 'retrying from the replacement surface',
  191. )
  192. this.overflowRetries.set(agent, retries + 1)
  193. return { kind: 'retry' }
  194. }
  195. ctx.logger.warn(
  196. // oxlint-disable-next-line typescript/no-unnecessary-condition -- the signal can abort while recovery is awaited.
  197. `context-overflow compaction failed: ${message}; ${signal.aborted
  198. ? 'cancellation prevents retry'
  199. : 'preserving the original request error'}`,
  200. )
  201. return next()
  202. }
  203. // oxlint-disable-next-line typescript/no-unnecessary-condition -- the signal can abort while compaction is awaited.
  204. if (signal.aborted
  205. || agent.session.surface.replaceGeneration <= generation) return next()
  206. if (result !== null) logResult(result, 'context overflow recovery')
  207. this.overflowRetries.set(agent, retries + 1)
  208. return { kind: 'retry' }
  209. })
  210. }
  211. /**
  212. * Summarize the replayed conversation region through a direct one-shot
  213. * `ctx.llm.stream()` call whose prefix reuses the conversation's own system
  214. * prompt, tools, and messages so the provider's KV cache is not invalidated.
  215. * Override this sole hook for a template or remote summarizer.
  216. * @param input - replayed conversation prefix (system, tools, and leading messages) to condense.
  217. * @param agent - supplies routed-model history, fallback model, and session id.
  218. * @param signal - optional cancellation forwarded to the adapter.
  219. * @returns safe text summary blocks and exact auxiliary-call provenance.
  220. */
  221. protected async summarize(
  222. input: SummarizationInput,
  223. agent: Agent,
  224. signal?: AbortSignal,
  225. ): Promise<SummaryResult> {
  226. const target = conversationTarget(agent)
  227. const config = target === undefined
  228. ? this.config
  229. : resolveTargetPolicy(this.config, target)
  230. return summarizeWithLlm(this.ctx, config, input, agent, signal)
  231. }
  232. /**
  233. * Compact for replayed step-boundary pressure or one provider-confirmed context
  234. * overflow. Both triggers price the latest durable routed request envelope;
  235. * overflow bypasses the normal threshold and retained-tail policy so it can
  236. * force one useful balanced reduction.
  237. * @param agent - agent whose latest durable routed request is measured.
  238. * @param trigger - normal step-boundary pressure or context-overflow recovery.
  239. * @param signal - live turn cancellation signal forwarded to summarization.
  240. * @returns the latest summary compaction result, or `null` when no summary ran.
  241. */
  242. override async compactIfNeeded(
  243. agent: Agent,
  244. trigger: CompactionTrigger,
  245. signal: AbortSignal,
  246. ): Promise<CompactionResult | null> {
  247. const target = routedTarget(agent.session)
  248. if (target === undefined) return null
  249. const policy = resolveTargetPolicy(this.config, target)
  250. const meter = this.ctx.tokenMeter
  251. let measurement = meter.measure(agent.session)
  252. switch (trigger) {
  253. case 'context-overflow':
  254. break
  255. case 'pressure':
  256. break
  257. /* v8 ignore next -- closed-union exhaustiveness guard */
  258. default:
  259. assertNever(trigger, 'compaction trigger')
  260. }
  261. // Pruning is optional so compact-basic remains independently composable.
  262. // Overflow always qualifies; pressure first resolves the routed model's
  263. // capacity and checks its target-specific threshold.
  264. const prune = this.ctx.get('toolResultPrune')
  265. if (trigger === 'context-overflow') {
  266. if (prune !== undefined) {
  267. prune.pruneSession(agent.session)
  268. measurement = meter.measure(agent.session)
  269. }
  270. const range = selectCompactableRange(agent.session, measurement, 0)
  271. if (range === null) return null
  272. return this.compactRegion(range.start, range.end, agent, signal)
  273. }
  274. const context = (await this.ctx.llm.resolveModelInfo(target.provider, target.model, signal)).context
  275. assertNoActiveCompaction(agent.session, 'automatic pressure compaction')
  276. const targetKey = `${target.provider}/${target.model}`
  277. if (context === undefined) {
  278. throw new TargetPressureConfigError(
  279. targetKey,
  280. `compact-basic: no context capacity for ${targetKey}; `
  281. + 'configure contextWindow on that adapter model',
  282. )
  283. }
  284. const spec = resolveCompactSpec(policy, context.contextWindow)
  285. if (measurement.totalTokens < spec.thresholdTokens) return null
  286. // Once pressure qualifies, land the model-free pass before choosing a
  287. // summary range, then remeasure through the singleton replay fold.
  288. if (prune !== undefined) {
  289. prune.pruneSession(agent.session)
  290. measurement = meter.measure(agent.session)
  291. }
  292. if (measurement.totalTokens < spec.thresholdTokens) return null
  293. let result: CompactionResult | null = null
  294. for (let attempt = 0; attempt <= spec.compactionRetries; attempt += 1) {
  295. const range = selectCompactableRange(agent.session, measurement, spec.retainTokens)
  296. if (range === null) {
  297. /* v8 ignore else -- concrete replacement preserves a compactable checkpoint; subclass hooks cannot mutate it. */
  298. if (result === null) return null
  299. /* v8 ignore next -- paired with the defensive post-success branch above. */
  300. break
  301. }
  302. result = await this.compactRegion(range.start, range.end, agent, signal)
  303. measurement = meter.measure(agent.session)
  304. if (measurement.totalTokens < spec.thresholdTokens) return result
  305. }
  306. throw new Error(
  307. `compaction still above threshold after ${spec.compactionRetries + 1} compaction attempts `
  308. + `(${measurement.totalTokens} estimated tokens >= threshold ${spec.thresholdTokens})`,
  309. )
  310. }
  311. /**
  312. * Compact one inclusive positional range from the agent-owned surface using
  313. * the effective token meter for all retention and shrink pricing.
  314. * @param start - inclusive first surface-node seq.
  315. * @param end - inclusive last surface-node seq.
  316. * @param agent - owner of the target session, used by the summarizer.
  317. * @param signal - optional summarization cancellation signal.
  318. * @returns the successful durable compaction result.
  319. */
  320. override async compactRegion(
  321. start: number,
  322. end: number,
  323. agent: Agent,
  324. signal?: AbortSignal,
  325. ): Promise<CompactionResult> {
  326. return compactSurfaceRegion(
  327. this.regionDependencies(),
  328. agent.session,
  329. start,
  330. end,
  331. agent,
  332. { owner: 'current-turn', stability: 'whole-surface' },
  333. signal,
  334. )
  335. }
  336. /**
  337. * Force one useful idle-session compaction below the pressure threshold, and
  338. * resolve only after its standalone marker pair is durably checkpointed.
  339. * @param agent - idle agent whose next-turn admission this call reserves.
  340. * @param signal - cancellation scoped to this compaction request.
  341. * @returns the committed result, or `null` when no safe useful range exists.
  342. */
  343. override compactNow(agent: Agent, signal: AbortSignal): Promise<CompactionResult | null> {
  344. signal.throwIfAborted()
  345. try {
  346. return agent.runMaintenance(async (agentSignal) => {
  347. const operationSignal = AbortSignal.any([agentSignal, signal])
  348. try {
  349. operationSignal.throwIfAborted()
  350. const range = selectCompactableRange(
  351. agent.session,
  352. this.ctx.tokenMeter.measure(agent.session),
  353. 0,
  354. )
  355. if (range === null) return null
  356. return await compactSurfaceRegion(
  357. this.regionDependencies(),
  358. agent.session,
  359. range.start,
  360. range.end,
  361. agent,
  362. {
  363. owner: null,
  364. stability: 'selected-span',
  365. flush: () => this.ctx.sessions.flush(agent.session),
  366. },
  367. operationSignal,
  368. )
  369. } catch (error: unknown) {
  370. if (agentSignal.aborted && operationSignal.reason === agentSignal.reason) {
  371. throw new ManualCompactionError(
  372. 'cancelled',
  373. 'manual compaction was cancelled',
  374. { cause: error },
  375. )
  376. }
  377. operationSignal.throwIfAborted()
  378. throw error
  379. }
  380. })
  381. } catch (error: unknown) {
  382. throw new ManualCompactionError(
  383. 'busy',
  384. 'manual compaction requires an idle agent with no waking queued work',
  385. { cause: error },
  386. )
  387. }
  388. }
  389. /** Bind the effective token meter and dynamically dispatched summarizer hook. */
  390. private regionDependencies(): { meter: TokenMeterService; summarize: RegionSummarize } {
  391. return {
  392. meter: this.ctx.tokenMeter,
  393. summarize: (input, owner, abort) => this.summarize(input, owner, abort),
  394. }
  395. }
  396. }
  397. export default BasicCompactService