automatic.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /**
  2. * Automatic pre-step pressure listener for compact-basic.
  3. *
  4. * @module @deepseek-ai/dsh-compact-basic/automatic
  5. */
  6. import type { Context } from 'cordis'
  7. import type { CompactionResult } from '@deepseek-ai/dsh-compact'
  8. import type { Message } from '@deepseek-ai/dsh-llm'
  9. import type { Agent } from '@deepseek-ai/dsh-agent'
  10. interface AutomaticCompactor {
  11. compactIfNeeded(
  12. agent: Agent,
  13. fullSystemPrompt: string,
  14. sessionPrefix: readonly Message[],
  15. signal: AbortSignal,
  16. ): Promise<CompactionResult | null>
  17. }
  18. /**
  19. * Register the implementation-owned automatic compaction listener.
  20. * @param ctx - context owning the listener effect and logger.
  21. * @param service - compactor whose public methods remain dynamically dispatched.
  22. */
  23. export function registerAutomaticCompaction(
  24. ctx: Context,
  25. service: AutomaticCompactor,
  26. ): void {
  27. ctx.on('agent/pre-step', async (
  28. agent: Agent,
  29. _turn: number,
  30. _step: number,
  31. fullSystemPrompt: string,
  32. sessionPrefix: readonly Message[],
  33. signal: AbortSignal,
  34. ) => {
  35. try {
  36. const result = await service.compactIfNeeded(agent, fullSystemPrompt, sessionPrefix, signal)
  37. if (result !== null) {
  38. ctx.logger.info(
  39. `compaction: shadowed ${result.shadowedSeqs.length} surface nodes `
  40. + `(seqs ${result.shadowedRange.start}-${result.shadowedRange.end}, `
  41. + `~${result.shadowedTokenCount} tokens)`,
  42. )
  43. }
  44. } catch (error: unknown) {
  45. const message = error instanceof Error ? error.message : String(error)
  46. ctx.logger.warn(`compaction failed: ${message}; proceeding with full history`)
  47. }
  48. })
  49. }