tool-output-store.ts 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. export * as ToolOutputStore from "./tool-output-store"
  2. import path from "path"
  3. import { Context, Duration, Effect, Layer, Option, Schedule, Schema } from "effect"
  4. import { Config } from "./config"
  5. import { FSUtil } from "./fs-util"
  6. import { Global } from "./global"
  7. import { SessionSchema } from "./session/schema"
  8. import { Identifier } from "./util/identifier"
  9. import type { ToolOutput } from "@opencode-ai/llm"
  10. export const MAX_LINES = 2_000
  11. export const MAX_BYTES = 50 * 1024
  12. export const RETENTION = Duration.days(7)
  13. export const MANAGED_DIRECTORY = "tool-output"
  14. export interface BoundInput {
  15. readonly sessionID: SessionSchema.ID
  16. readonly toolCallID: string
  17. readonly output: ToolOutput
  18. }
  19. export interface BoundResult {
  20. readonly output: ToolOutput
  21. readonly outputPaths: ReadonlyArray<string>
  22. }
  23. export class StorageError extends Schema.TaggedErrorClass<StorageError>()("ToolOutputStore.StorageError", {
  24. operation: Schema.Literals(["encode", "write"]),
  25. cause: Schema.Defect(),
  26. }) {
  27. override get message() {
  28. const detail = this.cause instanceof Error ? this.cause.message : String(this.cause)
  29. return `Failed to ${this.operation} tool output${detail ? `: ${detail}` : ""}`
  30. }
  31. }
  32. export type Error = StorageError
  33. export interface Interface {
  34. readonly limits: () => Effect.Effect<{ readonly maxLines: number; readonly maxBytes: number }>
  35. readonly bound: (input: BoundInput) => Effect.Effect<BoundResult, Error>
  36. readonly cleanup: () => Effect.Effect<void>
  37. }
  38. export class Service extends Context.Service<Service, Interface>()("@opencode/v2/ToolOutputStore") {}
  39. const takePrefix = (input: string, maximumBytes: number) => {
  40. let bytes = 0
  41. let content = ""
  42. for (const char of input) {
  43. const size = Buffer.byteLength(char, "utf-8")
  44. if (bytes + size > maximumBytes) break
  45. content += char
  46. bytes += size
  47. }
  48. return content
  49. }
  50. const takeSuffix = (input: string, maximumBytes: number) => {
  51. let bytes = 0
  52. const content: string[] = []
  53. for (const char of Array.from(input).toReversed()) {
  54. const size = Buffer.byteLength(char, "utf-8")
  55. if (bytes + size > maximumBytes) break
  56. content.unshift(char)
  57. bytes += size
  58. }
  59. return content.join("")
  60. }
  61. const preview = (text: string, maxLines: number, maxBytes: number) => {
  62. const lines = text.split("\n")
  63. const headLines = Math.ceil(maxLines / 2)
  64. const tailLines = Math.floor(maxLines / 2)
  65. const sampled =
  66. lines.length <= maxLines
  67. ? text
  68. : [
  69. lines.slice(0, headLines).join("\n"),
  70. ...(tailLines > 0 ? [lines.slice(lines.length - tailLines).join("\n")] : []),
  71. ].join("\n")
  72. if (Buffer.byteLength(sampled, "utf-8") <= maxBytes) {
  73. return lines.length <= maxLines
  74. ? { head: sampled, tail: "" }
  75. : {
  76. head: lines.slice(0, headLines).join("\n"),
  77. tail: tailLines > 0 ? lines.slice(lines.length - tailLines).join("\n") : "",
  78. }
  79. }
  80. const headBytes = Math.ceil(maxBytes / 2)
  81. const tailBytes = Math.floor(maxBytes / 2)
  82. return { head: takePrefix(sampled, headBytes), tail: takeSuffix(sampled, tailBytes) }
  83. }
  84. const boundedPreview = (text: string, marker: string, maxLines: number, maxBytes: number) => {
  85. const markerOnly = takePrefix(marker, maxBytes).split("\n").slice(0, maxLines).join("\n")
  86. const markerBytes = Buffer.byteLength(marker, "utf-8")
  87. if (maxLines <= 4 || maxBytes <= markerBytes + 4) return markerOnly
  88. const bounded = preview(text, maxLines - 4, maxBytes - markerBytes - 4)
  89. return bounded.tail ? `${bounded.head}\n\n${marker}\n\n${bounded.tail}` : `${bounded.head}\n\n${marker}`
  90. }
  91. const lineCount = (text: string) => {
  92. let count = 1
  93. for (const char of text) if (char === "\n") count++
  94. return count
  95. }
  96. export const layer = Layer.effect(
  97. Service,
  98. Effect.gen(function* () {
  99. const fs = yield* FSUtil.Service
  100. const global = yield* Global.Service
  101. const config = yield* Effect.serviceOption(Config.Service)
  102. const directory = path.join(global.data, MANAGED_DIRECTORY)
  103. const limits = Effect.fn("ToolOutputStore.limits")(function* () {
  104. if (Option.isNone(config)) return { maxLines: MAX_LINES, maxBytes: MAX_BYTES }
  105. const entries = yield* config.value.entries().pipe(Effect.catch(() => Effect.succeed([] as Config.Entry[])))
  106. const configured = Object.assign(
  107. {},
  108. ...entries.flatMap((entry) => (entry.type === "document" ? [entry.info.tool_output ?? {}] : [])),
  109. )
  110. return { maxLines: configured.max_lines ?? MAX_LINES, maxBytes: configured.max_bytes ?? MAX_BYTES }
  111. })
  112. const write = Effect.fn("ToolOutputStore.write")(function* (content: string) {
  113. const file = path.join(directory, `tool_${Identifier.ascending()}`)
  114. yield* fs.ensureDir(directory).pipe(Effect.mapError((cause) => new StorageError({ operation: "write", cause })))
  115. yield* fs
  116. .writeFileString(file, content, { flag: "wx" })
  117. .pipe(Effect.mapError((cause) => new StorageError({ operation: "write", cause })))
  118. return file
  119. })
  120. const bound = Effect.fn("ToolOutputStore.bound")(function* (input: BoundInput) {
  121. const outputLimits = yield* limits()
  122. const media = input.output.content.filter((item) => item.type === "file")
  123. const text = input.output.content.filter((item) => item.type === "text")
  124. const contextual =
  125. input.output.content.length === 0
  126. ? yield* Effect.try({
  127. try: () => JSON.stringify(input.output.structured, null, 2) ?? String(input.output.structured),
  128. catch: (cause) => new StorageError({ operation: "encode", cause }),
  129. })
  130. : text.map((item) => item.text).join("")
  131. if (
  132. lineCount(contextual) <= outputLimits.maxLines &&
  133. Buffer.byteLength(contextual, "utf-8") <= outputLimits.maxBytes
  134. )
  135. return {
  136. output: input.output,
  137. outputPaths: [],
  138. }
  139. const outputPath = yield* write(contextual)
  140. const marker = `... output truncated; full content saved to ${outputPath} ...`
  141. return {
  142. output: {
  143. structured: input.output.structured,
  144. content: [
  145. {
  146. type: "text" as const,
  147. text: boundedPreview(contextual, marker, outputLimits.maxLines, outputLimits.maxBytes),
  148. },
  149. ...media,
  150. ],
  151. },
  152. outputPaths: [outputPath],
  153. }
  154. })
  155. const cleanup = Effect.fn("ToolOutputStore.cleanup")(function* () {
  156. const entries = yield* fs.readDirectory(directory).pipe(Effect.catch(() => Effect.succeed([])))
  157. const cutoff = Date.now() - Duration.toMillis(RETENTION)
  158. for (const entry of entries) {
  159. if (!entry.startsWith("tool_")) continue
  160. const file = path.join(directory, entry)
  161. const info = yield* fs.stat(file).pipe(Effect.catch(() => Effect.void))
  162. const modified = info?.mtime.pipe(
  163. Option.map((date) => date.getTime()),
  164. Option.getOrElse(() => 0),
  165. )
  166. if (modified !== undefined && modified < cutoff) yield* fs.remove(file).pipe(Effect.catch(() => Effect.void))
  167. }
  168. })
  169. return Service.of({ limits, bound, cleanup })
  170. }),
  171. )
  172. export const defaultLayer = layer.pipe(Layer.provide(FSUtil.defaultLayer), Layer.provide(Global.defaultLayer))
  173. /** Runs retention scanning once globally rather than once per active Location. */
  174. export const cleanupLayer = Layer.effectDiscard(
  175. Effect.gen(function* () {
  176. const store = yield* Service
  177. yield* store.cleanup().pipe(Effect.repeat(Schedule.spaced(Duration.hours(1))), Effect.forkScoped)
  178. }),
  179. )
  180. export const defaultCleanupLayer = Layer.merge(defaultLayer, cleanupLayer.pipe(Layer.provide(defaultLayer)))