projection.ts 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. /** Current-surface projection and byte-bounded rendering. */
  2. import { isCompactCheckpointSource } from '@deepseek-ai/dsh-compaction'
  3. import type { SessionSurfaceSnapshot } from '@deepseek-ai/dsh-session-query'
  4. import { assertNever } from '@deepseek-ai/dsh-llm'
  5. import { TextRetainer } from '@deepseek-ai/dsh-output-retention'
  6. import { stringifyTagSafeJson } from './serialization.ts'
  7. import type { ReferencedConversationItem } from './types.ts'
  8. interface ProjectedItem extends ReferencedConversationItem {
  9. checkpoint: boolean
  10. originalText: string
  11. omittedBytes: number
  12. }
  13. /** Snapshot data serialized inside the untrusted prompt. */
  14. export interface ReferencedSessionData {
  15. sessionId: string
  16. label: string
  17. cwd: string | null
  18. capturedThroughSeq: number | null
  19. conversation: ReferencedConversationItem[]
  20. }
  21. /** Retention facts stored beside the durable context. */
  22. export interface ReferenceRetentionStats {
  23. compacted: boolean
  24. originalMessages: number
  25. retainedMessages: number
  26. omittedMessages: number
  27. omittedBytes: number
  28. truncated: boolean
  29. }
  30. /** Project current user/assistant conversation while excluding tools, reasoning, and injected context. */
  31. function projectSessionConversation(snapshot: SessionSurfaceSnapshot): ProjectedItem[] {
  32. const conversation: ProjectedItem[] = []
  33. for (const event of snapshot.events) {
  34. switch (event.type) {
  35. case 'user/message': {
  36. const checkpoint = isCompactCheckpointSource(event.data.source)
  37. if (!checkpoint && event.data.source.kind !== 'user') break
  38. const text = textContent(event.data.content)
  39. if (text !== '') conversation.push({ role: 'user', text, checkpoint, originalText: text, omittedBytes: 0 })
  40. break
  41. }
  42. case 'assistant/message': {
  43. const text = textContent(event.data.message.content)
  44. if (text !== '') conversation.push({ role: 'assistant', text, checkpoint: false, originalText: text, omittedBytes: 0 })
  45. break
  46. }
  47. case 'tool/result':
  48. break
  49. /* v8 ignore next 2 -- SurfaceEventType is closed and every variant is handled above. */
  50. default:
  51. assertNever(event, 'session-reference surface event')
  52. }
  53. }
  54. return conversation
  55. }
  56. /**
  57. * Fit one projected snapshot into an exact rendered JSON-object byte cap.
  58. * @param snapshot - current-surface source observation.
  59. * @param label - host-provided display label serialized with the source.
  60. * @param maxBytes - maximum UTF-8 bytes for the serialized data object.
  61. * @returns retained data and stats, or `undefined` when fixed data cannot fit.
  62. */
  63. export function retainReferencedSession(
  64. snapshot: SessionSurfaceSnapshot,
  65. label: string,
  66. maxBytes: number,
  67. ): { data: ReferencedSessionData; stats: ReferenceRetentionStats } | undefined {
  68. const original = projectSessionConversation(snapshot)
  69. const retained = original.map(item => ({ ...item }))
  70. let omittedMessages = 0
  71. let droppedOmittedBytes = 0
  72. const data = (): ReferencedSessionData => ({
  73. sessionId: snapshot.session.id,
  74. label,
  75. cwd: snapshot.session.cwd ?? null,
  76. capturedThroughSeq: snapshot.capturedThroughSeq,
  77. conversation: retained.map(({ role, text }) => ({ role, text })),
  78. })
  79. const size = (): number => Buffer.byteLength(stringifyTagSafeJson(data()), 'utf8')
  80. while (size() > maxBytes) {
  81. const newestIndex = retained.length - 1
  82. const dropIndex = retained.findIndex((item, index) => !item.checkpoint && index !== newestIndex)
  83. if (dropIndex < 0) break
  84. const removed = retained.splice(dropIndex, 1)[0]
  85. /* v8 ignore next 3 -- dropIndex came from this exact array and is non-negative. */
  86. if (removed === undefined) {
  87. throw new Error('session-reference retention selected a missing message')
  88. }
  89. omittedMessages += 1
  90. droppedOmittedBytes += Buffer.byteLength(removed.originalText, 'utf8')
  91. }
  92. while (size() > maxBytes) {
  93. let longestIndex = -1
  94. let longestBytes = 0
  95. for (const [index, item] of retained.entries()) {
  96. const bytes = Buffer.byteLength(item.text, 'utf8')
  97. if (bytes > longestBytes) {
  98. longestBytes = bytes
  99. longestIndex = index
  100. }
  101. }
  102. if (longestIndex < 0 || longestBytes === 0) return undefined
  103. const overflow = size() - maxBytes
  104. const target = Math.max(0, longestBytes - overflow)
  105. const item = retained[longestIndex]
  106. /* v8 ignore next 3 -- longestIndex was selected from this exact array's entries. */
  107. if (item === undefined) {
  108. throw new Error('session-reference retention selected a missing longest message')
  109. }
  110. const shortened = truncateWithNotice(item.originalText, target)
  111. /* v8 ignore next -- strictly lowering the byte target must change a complete-string retention result. */
  112. if (shortened.text === retained[longestIndex]?.text) return undefined
  113. retained[longestIndex] = { ...item, text: shortened.text, omittedBytes: shortened.omittedBytes }
  114. }
  115. const compacted = original.some(item => item.checkpoint)
  116. const retainedOmittedBytes = retained.reduce((sum, item) => sum + item.omittedBytes, 0)
  117. const omittedBytes = retainedOmittedBytes + droppedOmittedBytes
  118. return {
  119. data: data(),
  120. stats: {
  121. compacted,
  122. originalMessages: original.length,
  123. retainedMessages: retained.length,
  124. omittedMessages,
  125. omittedBytes,
  126. truncated: omittedMessages > 0 || omittedBytes > 0,
  127. },
  128. }
  129. }
  130. function textContent(content: readonly { type: string; text?: string }[]): string {
  131. return content.flatMap(block => block.type === 'text' && typeof block.text === 'string' ? [block.text] : []).join('\n')
  132. }
  133. function truncateWithNotice(text: string, maxOutputBytes: number): { text: string; omittedBytes: number } {
  134. /* v8 ignore next -- callers invoke this only with a target smaller than the selected original text. */
  135. if (Buffer.byteLength(text, 'utf8') <= maxOutputBytes) return { text, omittedBytes: 0 }
  136. let low = 0
  137. let high = maxOutputBytes
  138. let best = { text: '', omittedBytes: Buffer.byteLength(text, 'utf8') }
  139. while (low <= high) {
  140. const retainedBytes = Math.floor((low + high) / 2)
  141. const headBytes = Math.ceil(retainedBytes / 2)
  142. const tailBytes = Math.floor(retainedBytes / 2)
  143. const retainer = new TextRetainer({ kind: 'headTail', headBytes, tailBytes })
  144. retainer.push(text)
  145. const result = retainer.finish()
  146. // The complete source string was pushed before `finish()`, so omission is exact.
  147. /* v8 ignore next 3 -- complete-string TextRetainer input cannot report a lower bound. */
  148. if (result.omittedBytes.kind !== 'exact') {
  149. throw new Error('session-reference retention did not report exact omitted bytes')
  150. }
  151. const omitted = result.omittedBytes.count
  152. const candidate = `${result.text}\n[… omitted ${omitted} UTF-8 bytes …]`
  153. if (Buffer.byteLength(candidate, 'utf8') <= maxOutputBytes) {
  154. best = { text: candidate, omittedBytes: omitted }
  155. low = retainedBytes + 1
  156. } else {
  157. high = retainedBytes - 1
  158. }
  159. }
  160. return best
  161. }