tool-output-store.ts 7.8 KB

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