projection.ts 7.1 KB

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