projection.ts 7.1 KB

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