workspace-context-compaction.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import type { Context } from '@deepseek-ai/cordis'
  2. import type {} from '@deepseek-ai/dsh-agent'
  3. import { CompactionId, compactCheckpointSource } from '@deepseek-ai/dsh-compact'
  4. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  5. import type {} from '@deepseek-ai/dsh-tools'
  6. export const name = 'workspace-context-compaction'
  7. /** Replace the visible workspace baseline after the first touch is fully projected. */
  8. export function apply(ctx: Context): void {
  9. ctx.on('tools/post-execute', async (exec, result, next) => {
  10. const downstream = await next()
  11. if (result.isError
  12. || exec.agent === undefined
  13. || exec.name !== 'read'
  14. || typeof exec.arguments !== 'object'
  15. || exec.arguments === null
  16. || !('file_path' in exec.arguments)
  17. || exec.arguments.file_path !== 'nested/task.txt') return downstream
  18. const agent = exec.agent
  19. const baseline = agent.session.surface.nodes
  20. .map(seq => agent.session.events[seq])
  21. .find(event => event?.type === 'user/message'
  22. && event.data.source.kind === 'workspace-instructions'
  23. && event.data.source.baseline === true)
  24. if (baseline === undefined) throw new Error('workspace baseline missing before snapshot compaction')
  25. agent.session.append('user/message', createUserMessage({
  26. content: [{ type: 'text', text: 'Earlier context was compacted for this snapshot.' }],
  27. source: compactCheckpointSource(CompactionId('workspace-context-fixture')),
  28. }), {
  29. surfaceOp: { op: 'replace', start: baseline.seq, end: baseline.seq },
  30. sourceEventSeqs: [baseline.seq],
  31. })
  32. return downstream
  33. })
  34. }