surface.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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 marks the initial lazy build. */
  71. private _lastProcessedSeq = -1
  72. /** Replacement generation — see {@link replaceGeneration}. */
  73. private _replaceGeneration = 0
  74. constructor(private log: readonly SessionEvent[]) {}
  75. /**
  76. * The surface's replacement generation, bumped by every folded `replace` op.
  77. * A replace is the ONE operation that rewrites the surface non-monotonically,
  78. * so an incremental consumer of {@link nodes} (the session's derived-message
  79. * cache) compares this between visits — an unchanged generation guarantees
  80. * every node it has not seen is a pure tail append; a changed one means its
  81. * view must rebuild.
  82. */
  83. get replaceGeneration(): number {
  84. if (this._lastProcessedSeq < this.log.length - 1) this._processDelta()
  85. return this._replaceGeneration
  86. }
  87. /** The surface nodes in linked-list order (head to tail). */
  88. get nodes(): readonly SurfaceNode[] {
  89. if (this._lastProcessedSeq < this.log.length - 1) this._processDelta()
  90. return this._nodes
  91. }
  92. /**
  93. * Process events from `_lastProcessedSeq + 1` through the end of the log,
  94. * folding new surface markers into the existing linked list.
  95. */
  96. private _processDelta(): void {
  97. for (let i = this._lastProcessedSeq + 1; i < this.log.length; i++) {
  98. // Index is bounded by i < this.log.length — never undefined.
  99. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  100. const event = this.log[i]!
  101. // isSurfaceEvent checks event.type first (is it a surface-eligible type?)
  102. // then checks that surfaceOp is present. Only after both pass do we treat
  103. // it as a SurfaceEvent with mandatory surfaceOp.
  104. if (!isSurfaceEvent(event)) continue
  105. if (event.surfaceOp === 'append') {
  106. const tail = this._nodes.length > 0 ? this._nodes[this._nodes.length - 1] : undefined
  107. const node: SurfaceNode = { seq: event.seq, prev: tail?.seq ?? null, next: null }
  108. if (tail) tail.next = event.seq
  109. this._nodes.push(node)
  110. this._nodeBySeq.set(event.seq, node)
  111. } else {
  112. this._replace(event.seq, event.surfaceOp)
  113. }
  114. }
  115. this._lastProcessedSeq = this.log.length - 1
  116. }
  117. /** Apply a replace operation to the in-progress surface. */
  118. private _replace(
  119. newSeq: number,
  120. op: Extract<SurfaceOp, { op: 'replace' }>,
  121. ): void {
  122. const startNode = this._nodeBySeq.get(op.start)
  123. if (!startNode) {
  124. throw new Error(`surface replace: start seq ${op.start} not found in surface`)
  125. }
  126. const endNode = this._nodeBySeq.get(op.end)
  127. if (!endNode) {
  128. throw new Error(`surface replace: end seq ${op.end} not found in surface`)
  129. }
  130. const startIdx = this._nodes.indexOf(startNode)
  131. const endIdx = this._nodes.indexOf(endNode)
  132. if (startIdx > endIdx) {
  133. throw new Error(`surface replace: start seq ${op.start} (index ${startIdx}) is after end seq ${op.end} (index ${endIdx})`)
  134. }
  135. // Remove shadowed nodes from `[startIdx, endIdx]` inclusive.
  136. const count = endIdx - startIdx + 1
  137. const removed = this._nodes.splice(startIdx, count)
  138. for (const r of removed) this._nodeBySeq.delete(r.seq)
  139. // Insert the new node where the removed range was.
  140. const prevNode = startIdx > 0 ? this._nodes[startIdx - 1] : undefined
  141. const nextNode = startIdx < this._nodes.length ? this._nodes[startIdx] : undefined
  142. const newNode: SurfaceNode = {
  143. seq: newSeq,
  144. prev: prevNode?.seq ?? null,
  145. next: nextNode?.seq ?? null,
  146. }
  147. if (prevNode) prevNode.next = newSeq
  148. if (nextNode) nextNode.prev = newSeq
  149. this._nodes.splice(startIdx, 0, newNode)
  150. this._nodeBySeq.set(newSeq, newNode)
  151. this._replaceGeneration += 1
  152. }
  153. }