read-render.ts 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. /**
  2. * Pure read presentation: turn provider-decoded text into a bounded, line-numbered window and
  3. * model-facing envelope. Chunk scanning caps the current line, so even one newline-free giant
  4. * line cannot grow memory without bound.
  5. * @module @deepseek-ai/dsh-tool-fs/read-render
  6. */
  7. import { FsError } from '@deepseek-ai/dsh-fs'
  8. /** Default maximum characters returned for a single line (the `readMaxLineLength` config). */
  9. export const READ_MAX_LINE_LENGTH = 2000
  10. /** Default maximum bytes returned for selected file lines (the `readMaxBytes` config). */
  11. export const READ_MAX_BYTES = 50 * 1024
  12. /** Resolved read window. The consumer applies its defaults/caps before calling. */
  13. export interface ReadWindow {
  14. /** 1-based first line to return. */
  15. offset: number
  16. /** Maximum number of lines to return. */
  17. limit: number
  18. /** Maximum characters returned for a single line; overflow is truncated with a suffix. */
  19. maxLineLength: number
  20. /** Maximum bytes of selected output; overflow stops the scan and marks `truncatedByBytes`. */
  21. maxBytes: number
  22. }
  23. /** One line returned from a text file. */
  24. export interface FileTextLine {
  25. /** 1-based line number in the file. */
  26. number: number
  27. /** Line text without its trailing newline. */
  28. text: string
  29. }
  30. /** The windowed result {@link buildWindow} produces from a file's decoded text. */
  31. export interface WindowResult {
  32. /** Returned lines, already numbered. */
  33. lines: FileTextLine[]
  34. /** Exact total line count in the file. */
  35. totalLines: number
  36. /** Whether selected output hit the byte cap. */
  37. truncatedByBytes: boolean
  38. }
  39. /** Outcome of a bounded text read — what {@link formatReadOutput} renders. */
  40. export interface FileReadOutcome {
  41. /** 1-based first line requested. */
  42. offset: number
  43. /** Returned lines, already numbered. */
  44. lines: FileTextLine[]
  45. /** Exact total line count in the file. */
  46. totalLines: number
  47. /** Whether selected output hit the byte cap. */
  48. truncatedByBytes?: true
  49. }
  50. interface WindowAccumulator {
  51. lines: FileTextLine[]
  52. totalLines: number
  53. outputBytes: number
  54. truncatedByBytes: boolean
  55. }
  56. function newAccumulator(): WindowAccumulator {
  57. return { lines: [], totalLines: 0, outputBytes: 0, truncatedByBytes: false }
  58. }
  59. function truncateLine(line: string, maxLineLength: number): string {
  60. return line.length > maxLineLength ? `${line.substring(0, maxLineLength)}... (line truncated to ${maxLineLength} chars)` : line
  61. }
  62. function lineByteSize(line: string, currentLineCount: number): number {
  63. return Buffer.byteLength(line, 'utf8') + (currentLineCount > 0 ? 1 : 0)
  64. }
  65. function consumeLine(acc: WindowAccumulator, rawLine: string, request: ReadWindow): void {
  66. acc.totalLines += 1
  67. if (acc.truncatedByBytes || acc.totalLines < request.offset || acc.lines.length >= request.limit) return
  68. const text = truncateLine(rawLine, request.maxLineLength)
  69. const bytes = lineByteSize(text, acc.lines.length)
  70. if (acc.outputBytes + bytes > request.maxBytes) {
  71. acc.truncatedByBytes = true
  72. return
  73. }
  74. acc.outputBytes += bytes
  75. acc.lines.push({ number: acc.totalLines, text })
  76. }
  77. function stripCarriageReturn(line: string): string {
  78. return line.endsWith('\r') ? line.slice(0, -1) : line
  79. }
  80. function finish(acc: WindowAccumulator, request: ReadWindow, displayPath: string): WindowResult {
  81. if (!acc.truncatedByBytes && request.offset > acc.totalLines && !(acc.totalLines === 0 && request.offset === 1)) {
  82. throw new FsError(`offset ${request.offset} is out of range for "${displayPath}" (${acc.totalLines} lines)`, 'FS_NOT_FOUND')
  83. }
  84. return { lines: acc.lines, totalLines: acc.totalLines, truncatedByBytes: acc.truncatedByBytes }
  85. }
  86. /**
  87. * Build one window from streamed or whole-file chunks, enforcing line and byte caps while still
  88. * scanning to an exact total line count, and throwing `FS_NOT_FOUND` when the requested offset is
  89. * past EOF.
  90. * @param chunks - decoded text chunks in file order; chunk boundaries carry no meaning.
  91. * @param request - the resolved window; the caller has already applied its defaults and caps.
  92. * @param displayPath - the caller-facing path used in the offset-out-of-range error.
  93. * @returns the numbered window lines, the total line count seen, and the byte-cap truncation flag.
  94. */
  95. export async function buildWindow(
  96. chunks: AsyncIterable<string> | Iterable<string>,
  97. request: ReadWindow,
  98. displayPath: string,
  99. ): Promise<WindowResult> {
  100. const acc = newAccumulator()
  101. // One char past the truncation point is enough to prove a line overflows.
  102. const lineBufferCap = request.maxLineLength + 1
  103. let lineBuffer = ''
  104. function appendToLineBuffer(segment: string): void {
  105. if (lineBuffer.length >= lineBufferCap) return
  106. lineBuffer += segment
  107. if (lineBuffer.length > lineBufferCap) lineBuffer = lineBuffer.slice(0, lineBufferCap)
  108. }
  109. function flushLine(): void {
  110. consumeLine(acc, stripCarriageReturn(lineBuffer), request)
  111. lineBuffer = ''
  112. }
  113. for await (const chunk of chunks) {
  114. let startPos = 0
  115. let newlinePos: number
  116. while ((newlinePos = chunk.indexOf('\n', startPos)) !== -1) {
  117. appendToLineBuffer(chunk.slice(startPos, newlinePos))
  118. flushLine()
  119. startPos = newlinePos + 1
  120. }
  121. appendToLineBuffer(chunk.slice(startPos))
  122. }
  123. if (lineBuffer.length > 0) flushLine()
  124. return finish(acc, request, displayPath)
  125. }
  126. /**
  127. * Format a read outcome as one OpenCode-style line-numbered text block body.
  128. * @param displayPath - the backend-resolved path rendered in the envelope's `<path>` element.
  129. * @param outcome - the windowed read to render.
  130. * @returns the model-facing envelope: numbered lines plus a continuation or end-of-file footer.
  131. */
  132. export function formatReadOutput(displayPath: string, outcome: FileReadOutcome): string {
  133. const endLine = outcome.lines.at(-1)?.number ?? Math.max(0, outcome.offset - 1)
  134. let footer: string
  135. if (outcome.truncatedByBytes) {
  136. footer = `(Output capped. Showing lines ${outcome.offset}-${endLine}. Use offset=${endLine + 1} to continue.)`
  137. } else if (endLine < outcome.totalLines) {
  138. footer = `(Showing lines ${outcome.offset}-${endLine} of ${outcome.totalLines}. Use offset=${endLine + 1} to continue.)`
  139. } else {
  140. footer = `(End of file - total ${outcome.totalLines} lines)`
  141. }
  142. const body = outcome.lines.length > 0
  143. ? `${outcome.lines.map(line => `${line.number}: ${line.text}`).join('\n')}\n\n${footer}`
  144. : footer
  145. return `<path>${displayPath}</path>
  146. <type>file</type>
  147. <content>
  148. ${body}
  149. </content>`
  150. }