surface.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. /**
  2. * Surface layer on top of the session event log: a derived, cached linked list
  3. * of events that produce LLM messages. Rebuilt deterministically from
  4. * `surfaceOp` markers in the log — the log is the source of truth; the surface
  5. * is a view.
  6. *
  7. * @module @deepseek-ai/dsh-session/surface
  8. */
  9. import type { SessionEvent, SurfaceEvent, SurfaceEventType, SurfaceOp } from './types.ts'
  10. /**
  11. * The set of event type strings that are eligible for the surface linked list.
  12. * Mirrors the {@link SurfaceEventType} union; kept as a runtime set so the
  13. * type guard can check membership without a chain of string comparisons.
  14. */
  15. const SURFACE_EVENT_TYPES = new Set<string>([
  16. 'user/message',
  17. 'assistant/message',
  18. 'tool/result',
  19. 'context/message',
  20. 'steering/message',
  21. ])
  22. /**
  23. * Whether an event's `type` is surface-eligible (one of the five
  24. * message-producing {@link SurfaceEventType} values). This is the TYPE check
  25. * only — it does NOT require `surfaceOp` to be present. Use it to detect a
  26. * surface-eligible event that is MISSING its mandatory marker (e.g. validating
  27. * a seed/load log); use {@link isSurfaceEvent} to narrow to a fully-formed
  28. * {@link SurfaceEvent} with `surfaceOp` present.
  29. * @param type - the event type string to test.
  30. * @returns true when the type is one of the five message-producing types.
  31. */
  32. export function isSurfaceEligibleType(type: string): boolean {
  33. return SURFACE_EVENT_TYPES.has(type)
  34. }
  35. /**
  36. * Narrow a {@link SessionEvent} to {@link SurfaceEvent}: checks that the
  37. * event's `type` is surface-eligible AND that `surfaceOp` is present.
  38. * The narrowed type has mandatory {@link SurfaceOp}.
  39. * @param event - the event to narrow.
  40. * @returns true when the event is surface-eligible and carries its `surfaceOp` marker.
  41. */
  42. export function isSurfaceEvent(event: SessionEvent): event is SurfaceEvent {
  43. if (!SURFACE_EVENT_TYPES.has(event.type)) return false
  44. // surfaceOp is optional on SessionEvent (even for surface-eligible types)
  45. // but mandatory on SurfaceEvent — this check is the narrowing gate.
  46. if ((event as SessionEvent<SurfaceEventType>).surfaceOp === undefined) return false
  47. return true
  48. }
  49. /** One node in the surface linked list. */
  50. export interface SurfaceNode {
  51. /** The event seq of this surface node. */
  52. seq: number
  53. /** The previous surface node's seq, or null if this is the head. */
  54. prev: number | null
  55. /** The next surface node's seq, or null if this is the tail. */
  56. next: number | null
  57. }
  58. /**
  59. * Maintains a cached linked list of surface nodes, rebuilt lazily from
  60. * `surfaceOp` markers in the event log. Because the log is append-only, it
  61. * processes only the delta since the last rebuild — new events are folded
  62. * into the existing surface in O(new events) rather than rescanning the
  63. * whole log.
  64. */
  65. export class SurfaceManager {
  66. /** Surface nodes in linked-list order (head to tail). Empty until first access. */
  67. private _nodes: SurfaceNode[] = []
  68. /** Map from event seq → node. */
  69. private _nodeBySeq = new Map<number, SurfaceNode>()
  70. /** The last processed seq. -1 forces a full rebuild on first access. */
  71. private _lastProcessedSeq = -1
  72. /** Rewrite generation — see {@link replaceGeneration}. */
  73. private _replaceGeneration = 0
  74. constructor(private log: readonly SessionEvent[]) {}
  75. /**
  76. * Reset to unprocessed state. Call after the log has been replaced
  77. * wholesale (e.g. after Session seed). Not needed for normal appends —
  78. * those are picked up incrementally.
  79. */
  80. invalidate(): void {
  81. this._lastProcessedSeq = -1
  82. this._nodes = []
  83. this._nodeBySeq.clear()
  84. // A wholesale rebuild is a rewrite: bump the generation so incremental
  85. // consumers (the session's derived-message cache) discard their view.
  86. this._replaceGeneration += 1
  87. }
  88. /**
  89. * The surface's rewrite generation: bumped by every folded `replace` op and
  90. * by {@link invalidate}. A replace is the ONE operation that rewrites the
  91. * surface non-monotonically, so an incremental consumer of {@link nodes}
  92. * (the session's derived-message cache) compares this between visits — an
  93. * unchanged generation guarantees every node it has not seen is a pure tail
  94. * append; a changed one means its view must rebuild. Monotonic: it never
  95. * moves backwards, so comparisons cannot be fooled by a re-fold.
  96. */
  97. get replaceGeneration(): number {
  98. if (this._lastProcessedSeq < this.log.length - 1) this._processDelta()
  99. return this._replaceGeneration
  100. }
  101. /** The surface nodes in linked-list order (head to tail). */
  102. get nodes(): readonly SurfaceNode[] {
  103. if (this._lastProcessedSeq < this.log.length - 1) this._processDelta()
  104. return this._nodes
  105. }
  106. /**
  107. * Process events from `_lastProcessedSeq + 1` through the end of the log,
  108. * folding new surface markers into the existing linked list.
  109. */
  110. private _processDelta(): void {
  111. for (let i = this._lastProcessedSeq + 1; i < this.log.length; i++) {
  112. // Index is bounded by i < this.log.length — never undefined.
  113. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  114. const event = this.log[i]!
  115. // isSurfaceEvent checks event.type first (is it a surface-eligible type?)
  116. // then checks that surfaceOp is present. Only after both pass do we treat
  117. // it as a SurfaceEvent with mandatory surfaceOp.
  118. if (!isSurfaceEvent(event)) continue
  119. if (event.surfaceOp === 'append') {
  120. const tail = this._nodes.length > 0 ? this._nodes[this._nodes.length - 1] : undefined
  121. const node: SurfaceNode = { seq: event.seq, prev: tail?.seq ?? null, next: null }
  122. if (tail) tail.next = event.seq
  123. this._nodes.push(node)
  124. this._nodeBySeq.set(event.seq, node)
  125. } else {
  126. this._replace(event.seq, event.surfaceOp)
  127. }
  128. }
  129. this._lastProcessedSeq = this.log.length - 1
  130. }
  131. /** Apply a replace operation to the in-progress surface. */
  132. private _replace(
  133. newSeq: number,
  134. op: Extract<SurfaceOp, { op: 'replace' }>,
  135. ): void {
  136. const startNode = this._nodeBySeq.get(op.start)
  137. if (!startNode) {
  138. throw new Error(`surface replace: start seq ${op.start} not found in surface`)
  139. }
  140. const endNode = this._nodeBySeq.get(op.end)
  141. if (!endNode) {
  142. throw new Error(`surface replace: end seq ${op.end} not found in surface`)
  143. }
  144. const startIdx = this._nodes.indexOf(startNode)
  145. const endIdx = this._nodes.indexOf(endNode)
  146. if (startIdx > endIdx) {
  147. throw new Error(`surface replace: start seq ${op.start} (index ${startIdx}) is after end seq ${op.end} (index ${endIdx})`)
  148. }
  149. // Remove shadowed nodes from `[startIdx, endIdx]` inclusive.
  150. const count = endIdx - startIdx + 1
  151. const removed = this._nodes.splice(startIdx, count)
  152. for (const r of removed) this._nodeBySeq.delete(r.seq)
  153. // Insert the new node where the removed range was.
  154. const prevNode = startIdx > 0 ? this._nodes[startIdx - 1] : undefined
  155. const nextNode = startIdx < this._nodes.length ? this._nodes[startIdx] : undefined
  156. const newNode: SurfaceNode = {
  157. seq: newSeq,
  158. prev: prevNode?.seq ?? null,
  159. next: nextNode?.seq ?? null,
  160. }
  161. if (prevNode) prevNode.next = newSeq
  162. if (nextNode) nextNode.prev = newSeq
  163. this._nodes.splice(startIdx, 0, newNode)
  164. this._nodeBySeq.set(newSeq, newNode)
  165. this._replaceGeneration += 1
  166. }
  167. }