refactor(core): simplify read tool structured output (#64361)

This commit is contained in:
Aiden Cline 2026-11-16 23:17:40 -06:00 • committed by GitHub
parent df46f6931d
commit 2cb1818d01
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 277 additions and 317 deletions

View file

@ -28,7 +28,6 @@ const LocationInput = Schema.Struct({
})
export const Input = LocationInput
type Missing = { input: string; requested: FileAccess.Target; context: FileAccess.Invocation }
const Output = Schema.Union([ReadToolFileSystem.FileContent, ReadToolFileSystem.TextPage, ReadToolFileSystem.ListPage])
export const Plugin = {
id: "opencode.tool.read",
@ -50,7 +49,7 @@ export const Plugin = {
description:
"Read the contents of a file or directory. Supports text files, images, and PDFs. Images and PDFs are presented directly to the model. Each text line is prefixed by its 1-based line number as <line>: <content>. The prefix is for reference and is not part of the file content. Directory entries are returned one per line. Use offset and limit to read large files or directories in sections. Prefer one larger read over many small slices, and use grep to find specific content in large files.",
input: Input,
output: Output,
output: ReadToolFileSystem.Output,
execute: (input, context) => {
return Effect.gen(function* () {
if (input.limit === 0)
@ -119,7 +118,7 @@ export const Plugin = {
() => missing({ input: input.path, requested, context }),
),
)
if (content.type === "list-page") return yield* missing({ input: input.path, requested, context })
if (content.type === "directory") return yield* missing({ input: input.path, requested, context })
return {
content,
target,
@ -141,7 +140,7 @@ export const Plugin = {
// even when an upward walk from elsewhere in the project cannot reach root.
const discovered = yield* fs.up({
targets: [FILENAME],
start: result.content.type === "list-page" ? resolved : dirname(resolved),
start: result.content.type === "directory" ? resolved : dirname(resolved),
stop: root,
type: "file",
})
@ -157,9 +156,17 @@ export const Plugin = {
return { output: result.content, path: result.path }
}).pipe(
Effect.map((result) => ({
output: result.output,
output:
result.output.type === "media"
? {
type: result.output.type,
uri: result.output.uri,
mime: result.output.mime,
name: result.output.name,
}
: result.output,
content: toModelContent(result.path, input.offset, result.output),
metadata: { truncated: result.output.type === "file" ? false : result.output.truncated },
metadata: { truncated: result.output.type !== "media" && result.output.next !== undefined },
})),
Effect.mapError((error) => {
if (error instanceof ToolFailure) return error
@ -322,45 +329,46 @@ function parseSkillUri(value: string) {
return { id, target: rest === "" ? "/" : `/${rest}`, uri: Skill.uri(id, rest || undefined) }
}
export const toModelContent = (path: string, offset: number | undefined, output: typeof Output.Type) => {
if (output.type === "file" && output.encoding === "base64")
export const toModelContent = (
path: string,
offset: number | undefined,
output: ReadToolFileSystem.TextContent | ReadToolFileSystem.DirectoryContent | ReadToolFileSystem.Media,
) => {
if (output.type === "media")
return [
{ type: "text", text: output.mime === "application/pdf" ? "PDF read successfully" : "Image read successfully" },
{
type: "file",
uri: `data:${output.mime};base64,${output.content}`,
uri: `data:${output.mime};base64,${Buffer.from(output.bytes).toString("base64")}`,
mime: output.mime,
name: path,
},
] as const
if (output.type === "list-page") {
if (output.type === "directory") {
const start = offset || 1
const content = [
output.entries.length === 0
? `Read directory ${path}, 0 entries`
: `Read directory ${path}, entries ${start}-${start + output.entries.length - 1}`,
...output.entries,
]
output.entries.forEach((entry) => content.push(entry.path))
if (output.truncated && output.next !== undefined)
content.push(`[Output truncated. Continue reading with offset: ${output.next}]`)
if (output.next !== undefined) content.push(`[Output truncated. Continue reading with offset: ${output.next}]`)
return content.join("\n")
}
const start = output.type === "text-page" ? output.offset : 1
// Pages already join selected lines; a trailing newline represents a selected blank line.
const text = output.type === "file" ? output.content.replace(/\n$/, "") : output.content
const empty = output.type === "text-page" ? output.lineCount === 0 : output.content === ""
const lines = empty ? [] : text.split("\n")
const start = output.offset
// Whole-file content keeps its final newline and a selected trailing blank line is an empty last
// line, so the line count decides which pieces are lines.
const lines = output.lineCount === 0 ? [] : output.content.split("\n").slice(0, output.lineCount)
// A page that starts before the requested offset is the file's tail, returned for an offset past the end.
const total = start + lines.length - 1
const pastEnd = output.type === "text-page" && offset !== undefined && start < offset
const pastEnd = offset !== undefined && start < offset
const content = [
(lines.length === 0 ? `Read file ${path}, 0 lines` : `Read file ${path}, lines ${start}-${total}`) +
(pastEnd ? ` (offset ${offset} is past the end; the file has ${total} ${total === 1 ? "line" : "lines"})` : ""),
]
lines.forEach((line, index) => content.push(`${start + index}: ${line}`))
if (output.type === "text-page" && output.truncated && output.next !== undefined)
content.push(`[Output truncated. Continue reading with offset: ${output.next}]`)
if (output.next !== undefined) content.push(`[Output truncated. Continue reading with offset: ${output.next}]`)
return content.join("\n")
}

View file

@ -5,12 +5,10 @@ import { pathToFileURL } from "url"
import { makeLocationNode } from "@opencode/util/effect/app-node"
import { TextBoundary } from "@opencode/util/text-boundary"
import { Context, Effect, Layer, Schema } from "effect"
import { lookup } from "mime-types"
import { Environment } from "../environment/index.js"
import type { Files } from "../environment/index.js"
import { FileSystem } from "../filesystem.js"
import { Mime } from "../mime.js"
import { AbsolutePath, NonNegativeInt, PositiveInt, RelativePath } from "../schema.js"
import { AbsolutePath, NonNegativeInt, PositiveInt } from "../schema.js"
export const MAX_READ_LINES = 2_000
export const MAX_READ_BYTES = 50 * 1024
@ -74,34 +72,39 @@ export const PageInput = Schema.Struct({
})
export type PageInput = typeof PageInput.Type
export const FileContent = Schema.Struct({
type: Schema.Literal("file"),
...FileSystem.Content.fields,
}).annotate({ identifier: "ReadTool.FileContent" })
export type FileContent = typeof FileContent.Type
export class TextPage extends Schema.Class<TextPage>("ReadTool.TextPage")({
type: Schema.Literal("text-page"),
export const TextContent = Schema.Struct({
type: Schema.Literal("text"),
content: Schema.String,
lineCount: NonNegativeInt,
mime: Schema.String,
offset: PositiveInt,
truncated: Schema.Boolean,
next: Schema.optionalKey(PositiveInt),
}) {}
lineCount: NonNegativeInt,
next: Schema.optionalKey(PositiveInt).annotate({
description: "The line to continue reading from. Absent when the content reaches the end of the file.",
}),
}).annotate({ identifier: "ReadTool.TextContent" })
export type TextContent = typeof TextContent.Type
export interface ListEntry extends Schema.Schema.Type<typeof ListEntry> {}
export const ListEntry = Schema.Struct({
path: RelativePath,
type: Schema.Literals(["file", "directory", "symlink"]),
}).annotate({ identifier: "ReadTool.ListEntry" })
export const DirectoryContent = Schema.Struct({
type: Schema.Literal("directory"),
entries: Schema.Array(Schema.String),
next: Schema.optionalKey(PositiveInt).annotate({
description: "The entry to continue reading from. Absent when the listing reaches the last entry.",
}),
}).annotate({ identifier: "ReadTool.DirectoryContent" })
export type DirectoryContent = typeof DirectoryContent.Type
export class ListPage extends Schema.Class<ListPage>("ReadTool.ListPage")({
type: Schema.Literal("list-page"),
entries: Schema.Array(ListEntry),
truncated: Schema.Boolean,
next: Schema.optionalKey(PositiveInt),
}) {}
export const MediaContent = Schema.Struct({
type: Schema.Literal("media"),
uri: Schema.String,
mime: Schema.String,
name: Schema.optionalKey(Schema.String),
}).annotate({ identifier: "ReadTool.MediaContent" })
export type MediaContent = typeof MediaContent.Type
export const Output = Schema.Union([TextContent, DirectoryContent, MediaContent])
export type Output = typeof Output.Type
// Media bytes travel beside the reference so the tool can attach them without storing them in its output.
export type Media = MediaContent & { readonly name: string; readonly bytes: Uint8Array }
export interface Interface {
readonly list: (path: AbsolutePath) => ReturnType<Files["list"]>
@ -109,13 +112,11 @@ export interface Interface {
path: AbsolutePath,
resource: string,
page?: PageInput,
) => Effect.Effect<FileContent | TextPage | ListPage, ReadError>
) => Effect.Effect<TextContent | DirectoryContent | Media, ReadError>
}
export class Service extends Context.Service<Service, Interface>()("@opencode/ReadToolFileSystem") {}
const mimeType = (value: string) => lookup(value) || "application/octet-stream"
export const read = Effect.fn("ReadTool.read")(function* (
files: Files,
input: AbsolutePath,
@ -137,7 +138,7 @@ export const read = Effect.fn("ReadTool.read")(function* (
}),
),
)
if (first instanceof ListPage) return first
if ("type" in first) return first
const media = Mime.detectMedia(first.bytes)
if (media && MEDIA_MIMES.has(media)) {
@ -145,12 +146,11 @@ export const read = Effect.fn("ReadTool.read")(function* (
return yield* new MediaIngestLimitError({ resource, maximumBytes: MAX_MEDIA_INGEST_BYTES })
const whole = yield* readFile(files, input, resource)
return {
type: "file" as const,
type: "media" as const,
uri: virtual ? resource : pathToFileURL(input).href,
name: virtual ? path.posix.basename(input) : path.basename(input),
content: Buffer.from(whole.bytes).toString("base64"),
encoding: "base64" as const,
mime: media,
name: virtual ? path.posix.basename(input) : path.basename(input),
bytes: whole.bytes,
}
}
@ -163,14 +163,7 @@ export const read = Effect.fn("ReadTool.read")(function* (
if (count <= MAX_READ_LINES) {
const content = lines.map(clampLine).join("\n")
if (Buffer.byteLength(content) <= MAX_READ_BYTES)
return {
type: "file" as const,
uri: virtual ? resource : pathToFileURL(input).href,
name: virtual ? path.posix.basename(input) : path.basename(input),
content,
encoding: "utf8" as const,
mime: mimeType(input),
}
return { type: "text" as const, content, offset: 1, lineCount: count }
}
}
@ -331,48 +324,31 @@ const textPage = Effect.fnUntraced(function* (
}
if (firstNul < consumed) return yield* new BinaryFileError({ resource })
return new TextPage({
type: "text-page",
return {
type: "text" as const,
content: entries.join("\n"),
lineCount: entries.length,
mime: mimeType(input),
offset: from,
truncated: next !== undefined,
lineCount: entries.length,
...(next === undefined ? {} : { next }),
})
}
})
const list = (items: ReadonlyArray<Environment.DirEntry>, page: PageInput, sep = path.sep) => {
const list = (items: ReadonlyArray<Environment.DirEntry>, page: PageInput, sep = path.sep): DirectoryContent => {
const offset = page.offset || 1
const limit = Math.min(page.limit || MAX_READ_LINES, MAX_READ_LINES)
const visible = items
.flatMap((item) =>
item.type === "other"
? []
: [
ListEntry.make({
path: RelativePath.make(item.name + (item.type === "directory" ? sep : "")),
type: item.type,
}),
],
)
.sort((a, b) =>
a.type === "directory"
? b.type === "directory"
? a.path.localeCompare(b.path)
: -1
: b.type === "directory"
? 1
: a.path.localeCompare(b.path),
: [{ name: item.name + (item.type === "directory" ? sep : ""), directory: item.type === "directory" }],
)
.sort((a, b) => Number(b.directory) - Number(a.directory) || a.name.localeCompare(b.name))
const selected = visible.slice(offset - 1, offset - 1 + limit)
const truncated = offset - 1 + selected.length < visible.length
return new ListPage({
type: "list-page",
entries: selected,
truncated,
...(truncated ? { next: offset + selected.length } : {}),
})
return {
type: "directory",
entries: selected.map((entry) => entry.name),
...(offset - 1 + selected.length < visible.length ? { next: offset + selected.length } : {}),
}
}
const clampLine = (line: string) =>

View file

@ -1,6 +1,7 @@
import { describe, expect } from "bun:test"
import fs from "fs/promises"
import path from "path"
import { pathToFileURL } from "url"
import { Environment } from "@opencode/core/environment/index"
import { AbsolutePath } from "@opencode/core/schema"
import { ReadTool } from "@opencode/core/tool/plugin/read"
@ -22,103 +23,116 @@ const fixture = Effect.gen(function* () {
const absolute = (value: string) => AbsolutePath.make(value)
describe("ReadTool text serialization", () => {
const cases = [
const cases: {
name: string
content: string
page: ReadToolFileSystem.PageInput
output: ReadToolFileSystem.TextContent
model: string
}[] = [
{
name: "reads a partial GIF signature as text",
content: "GIF8 is text",
page: {},
output: { type: "file", content: "GIF8 is text", encoding: "utf8" },
output: { type: "text", content: "GIF8 is text", offset: 1, lineCount: 1 },
model: "Read file lines.txt, lines 1-1\n1: GIF8 is text",
},
{
name: "preserves a selected trailing blank line before continuation",
content: "alpha\n\nomega\n",
page: { offset: 1, limit: 2 },
output: { type: "text-page", content: "alpha\n", offset: 1, truncated: true, next: 3 },
output: { type: "text", content: "alpha\n", offset: 1, lineCount: 2, next: 3 },
model: "Read file lines.txt, lines 1-2\n1: alpha\n2: \n[Output truncated. Continue reading with offset: 3]",
},
{
name: "preserves multiple selected trailing blank lines at a noninitial offset",
content: "before\nalpha\n\n\nomega\n",
page: { offset: 2, limit: 3 },
output: { type: "text-page", content: "alpha\n\n", offset: 2, truncated: true, next: 5 },
output: { type: "text", content: "alpha\n\n", offset: 2, lineCount: 3, next: 5 },
model: "Read file lines.txt, lines 2-4\n2: alpha\n3: \n4: \n[Output truncated. Continue reading with offset: 5]",
},
{
name: "preserves a selected trailing blank line at EOF",
content: "alpha\n\n",
page: { limit: 2 },
output: { type: "text-page", content: "alpha\n", offset: 1, truncated: false },
output: { type: "text", content: "alpha\n", offset: 1, lineCount: 2 },
model: "Read file lines.txt, lines 1-2\n1: alpha\n2: ",
},
{
name: "preserves internal blank lines in a page",
content: "alpha\n\nomega\n",
page: { limit: 3 },
output: { type: "text-page", content: "alpha\n\nomega", offset: 1, truncated: false },
output: { type: "text", content: "alpha\n\nomega", offset: 1, lineCount: 3 },
model: "Read file lines.txt, lines 1-3\n1: alpha\n2: \n3: omega",
},
{
name: "preserves continuation for a nonblank page",
content: "alpha\n\nomega\n",
page: { limit: 1 },
output: { type: "text-page", content: "alpha", offset: 1, truncated: true, next: 2 },
output: { type: "text", content: "alpha", offset: 1, lineCount: 1, next: 2 },
model: "Read file lines.txt, lines 1-1\n1: alpha\n[Output truncated. Continue reading with offset: 2]",
},
{
name: "strips only the terminal file newline in a whole-file read",
content: "alpha\n\n",
page: {},
output: { type: "file", content: "alpha\n\n", encoding: "utf8" },
output: { type: "text", content: "alpha\n\n", offset: 1, lineCount: 2 },
model: "Read file lines.txt, lines 1-2\n1: alpha\n2: ",
},
{
name: "does not add a line for a whole-file terminal newline",
content: "alpha\n",
page: {},
output: { type: "file", content: "alpha\n", encoding: "utf8" },
output: { type: "text", content: "alpha\n", offset: 1, lineCount: 1 },
model: "Read file lines.txt, lines 1-1\n1: alpha",
},
{
name: "preserves a whole-file read without a terminal newline",
content: "alpha",
page: {},
output: { type: "file", content: "alpha", encoding: "utf8" },
output: { type: "text", content: "alpha", offset: 1, lineCount: 1 },
model: "Read file lines.txt, lines 1-1\n1: alpha",
},
{
name: "preserves empty whole-file output",
content: "",
page: {},
output: { type: "file", content: "", encoding: "utf8" },
output: { type: "text", content: "", offset: 1, lineCount: 0 },
model: "Read file lines.txt, 0 lines",
},
{
name: "preserves empty-file page output",
content: "",
page: { limit: 2 },
output: { type: "text-page", content: "", lineCount: 0, offset: 1, truncated: false },
output: { type: "text", content: "", offset: 1, lineCount: 0 },
model: "Read file lines.txt, 0 lines",
},
{
name: "numbers the only blank line in a newline-only file",
content: "\n",
page: { limit: 1 },
output: { type: "text-page", content: "", lineCount: 1, offset: 1, truncated: false },
output: { type: "text", content: "", offset: 1, lineCount: 1 },
model: "Read file lines.txt, lines 1-1\n1: ",
},
{
name: "keeps the newline of a whole newline-only file",
content: "\n",
page: {},
output: { type: "text", content: "\n", offset: 1, lineCount: 1 },
model: "Read file lines.txt, lines 1-1\n1: ",
},
{
name: "numbers a single blank line before continuation",
content: "alpha\n\nomega\n",
page: { offset: 2, limit: 1 },
output: { type: "text-page", content: "", lineCount: 1, offset: 2, truncated: true, next: 3 },
output: { type: "text", content: "", offset: 2, lineCount: 1, next: 3 },
model: "Read file lines.txt, lines 2-2\n2: \n[Output truncated. Continue reading with offset: 3]",
},
{
name: "counts the last blank line when an offset is past EOF",
content: "alpha\n\n",
page: { offset: 9, limit: 1 },
output: { type: "text-page", content: "", lineCount: 1, offset: 2, truncated: false },
output: { type: "text", content: "", offset: 2, lineCount: 1 },
model: "Read file lines.txt, lines 2-2 (offset 9 is past the end; the file has 2 lines)\n2: ",
},
]
@ -132,7 +146,7 @@ describe("ReadTool text serialization", () => {
const result = yield* ReadToolFileSystem.read(current.environment, file, "lines.txt", input.page)
expect(result).toMatchObject(input.output)
expect(result).toEqual(input.output)
expect(ReadTool.toModelContent("lines.txt", input.page.offset, result)).toBe(input.model)
}),
)
@ -149,18 +163,17 @@ describe("ReadToolFileSystem", () => {
for (const ending of ["last", "last\n", "last\r\n", "\n"]) {
const content = prefix + ending
yield* files.writeFileString(file, content)
expect(yield* read()).toMatchObject({ type: "file", content })
expect(yield* read()).toEqual({ type: "text", content, offset: 1, lineCount: 2_000 })
}
yield* files.writeFileString(file, prefix + "\r\nlast")
const page = yield* read()
expect(page.type).toBe("text-page")
if (page.type !== "text-page") return
expect(page).toMatchObject({ content: "x\n".repeat(1_999), offset: 1, next: 2_001, truncated: true })
expect(page).toEqual({ type: "text", content: "x\n".repeat(1_999), offset: 1, lineCount: 2_000, next: 2_001 })
if (page.type !== "text") return
expect(ReadTool.toModelContent("dense.txt", undefined, page)).toEndWith(
"2000: \n[Output truncated. Continue reading with offset: 2001]",
)
expect(yield* read({ offset: page.next })).toMatchObject({ content: "last", offset: 2_001, truncated: false })
expect(yield* read({ offset: page.next })).toEqual({ type: "text", content: "last", offset: 2_001, lineCount: 1 })
}),
)
@ -171,14 +184,14 @@ describe("ReadToolFileSystem", () => {
const read = () => ReadToolFileSystem.read(environment, file, "bytes.txt")
const exact = ("é".repeat(799) + "x\n").repeat(32)
yield* files.writeFileString(file, exact)
expect(yield* read()).toMatchObject({ type: "file", content: exact })
expect(yield* read()).toEqual({ type: "text", content: exact, offset: 1, lineCount: 32 })
// Each truncation marker takes more bytes than the one character it replaces.
yield* files.writeFileString(file, ("x".repeat(2_001) + "\n").repeat(25) + "é".repeat(500))
const page = yield* read()
expect(page.type).toBe("text-page")
if (page.type !== "text-page") return
expect(page).toMatchObject({ offset: 1, next: 26, truncated: true })
expect(page.type).toBe("text")
if (page.type !== "text") return
expect(page).toMatchObject({ offset: 1, lineCount: 25, next: 26 })
expect(page.content.split("\n")).toHaveLength(25)
expect(Buffer.byteLength(page.content)).toBeLessThanOrEqual(50 * 1024)
}),
@ -198,12 +211,15 @@ describe("ReadToolFileSystem", () => {
])
const file = absolute(path.join(directory, name))
yield* files.writeFile(file, bytes)
expect(yield* ReadToolFileSystem.read(environment, file, name)).toMatchObject({
type: "file",
const result = yield* ReadToolFileSystem.read(environment, file, name)
expect(result).toEqual({
type: "media",
uri: pathToFileURL(file).href,
mime: "image/gif",
encoding: "base64",
content: bytes.toString("base64"),
name,
bytes: expect.any(Uint8Array),
})
expect(result.type === "media" && Buffer.from(result.bytes).equals(bytes)).toBe(true)
}
}),
)
@ -227,13 +243,7 @@ describe("ReadToolFileSystem", () => {
const result = yield* ReadToolFileSystem.read(environment, absolute(directory), "folder")
expect(result).toMatchObject({
type: "list-page",
entries: [
{ path: `folder${path.sep}`, type: "directory" },
{ path: "file.txt", type: "file" },
],
})
expect(result).toEqual({ type: "directory", entries: [`folder${path.sep}`, "file.txt"] })
}),
)
@ -250,7 +260,7 @@ describe("ReadToolFileSystem", () => {
expect(binaryError).toBeInstanceOf(ReadToolFileSystem.BinaryFileError)
expect(binaryError.message).toBe("Cannot read binary file: archive.dat")
expect(malformedResult).toMatchObject({ type: "file", content: "hi\uFFFD", encoding: "utf8" })
expect(malformedResult).toEqual({ type: "text", content: "hi\uFFFD", offset: 1, lineCount: 1 })
}),
)
@ -262,7 +272,7 @@ describe("ReadToolFileSystem", () => {
const result = yield* ReadToolFileSystem.read(environment, absolute(file), "notes.docx")
expect(result).toMatchObject({ type: "file", content: "plain text", encoding: "utf8" })
expect(result).toEqual({ type: "text", content: "plain text", offset: 1, lineCount: 1 })
}),
)
@ -278,14 +288,7 @@ describe("ReadToolFileSystem", () => {
const result = yield* ReadToolFileSystem.read(environment, absolute(directory), "folder")
expect(result.type).toBe("list-page")
if (result.type !== "list-page") return
expect(result.entries.map((entry) => ({ ...entry, path: String(entry.path) }))).toEqual([
{ path: `folder${path.sep}`, type: "directory" },
{ path: "broken", type: "symlink" },
{ path: "escape", type: "symlink" },
{ path: "file.txt", type: "file" },
])
expect(result).toEqual({ type: "directory", entries: [`folder${path.sep}`, "broken", "escape", "file.txt"] })
}),
)
@ -301,10 +304,7 @@ describe("ReadToolFileSystem", () => {
const result = yield* ReadToolFileSystem.read(environment, absolute(link), "link")
expect(result).toMatchObject({
type: "list-page",
entries: [{ path: "file.txt", type: "file" }],
})
expect(result).toEqual({ type: "directory", entries: ["file.txt"] })
}),
)
@ -559,7 +559,7 @@ describe("ReadToolFileSystem", () => {
limit: 1,
})
expect(result).toMatchObject({ type: "text-page", content: "two", offset: 2, truncated: true, next: 3 })
expect(result).toEqual({ type: "text", content: "two", offset: 2, lineCount: 1, next: 3 })
}),
)
@ -571,10 +571,11 @@ describe("ReadToolFileSystem", () => {
const result = yield* ReadToolFileSystem.read(environment, absolute(file), "long.txt", { limit: 1 })
expect(result).toMatchObject({
type: "text-page",
expect(result).toEqual({
type: "text",
content: `${"a".repeat(1_999)}... (line truncated to 2000 chars)`,
truncated: false,
offset: 1,
lineCount: 1,
})
}),
)
@ -596,10 +597,10 @@ describe("ReadToolFileSystem", () => {
const lines = yield* ReadToolFileSystem.read(environment, absolute(linesFile), "many-lines.txt", { limit: 2_000 })
const bytes = yield* ReadToolFileSystem.read(tracked, absolute(bytesFile), "many-bytes.txt", {})
expect(lines).toMatchObject({ type: "text-page", truncated: true, next: 2_001 })
expect(lines.type === "text-page" ? lines.content.split("\n") : []).toHaveLength(2_000)
expect(bytes).toMatchObject({ type: "text-page", truncated: true, next: 26 })
expect(bytes.type === "text-page" ? Buffer.byteLength(bytes.content) : Infinity).toBeLessThanOrEqual(
expect(lines).toMatchObject({ type: "text", lineCount: 2_000, next: 2_001 })
expect(lines.type === "text" ? lines.content.split("\n") : []).toHaveLength(2_000)
expect(bytes).toMatchObject({ type: "text", lineCount: 25, next: 26 })
expect(bytes.type === "text" ? Buffer.byteLength(bytes.content) : Infinity).toBeLessThanOrEqual(
ReadToolFileSystem.MAX_READ_BYTES,
)
expect(ranges).toEqual([{ offset: 0, length: 256 * 1024 }])
@ -618,12 +619,7 @@ describe("ReadToolFileSystem", () => {
limit: 1,
})
expect(result).toMatchObject({
type: "list-page",
entries: [{ path: `z${path.sep}`, type: "directory" }],
truncated: true,
next: 3,
})
expect(result).toEqual({ type: "directory", entries: [`z${path.sep}`], next: 3 })
}),
)
@ -635,7 +631,7 @@ describe("ReadToolFileSystem", () => {
const result = yield* ReadToolFileSystem.read(environment, absolute(file), "nul.txt", { limit: 1 })
expect(result).toMatchObject({ type: "text-page", content: "one", truncated: true, next: 2 })
expect(result).toEqual({ type: "text", content: "one", offset: 1, lineCount: 1, next: 2 })
}),
)
@ -647,7 +643,7 @@ describe("ReadToolFileSystem", () => {
const read = (offset: number) => ReadToolFileSystem.read(environment, file, "nul.txt", { offset, limit: 1 })
for (const offset of [2, -3]) {
expect(yield* read(offset)).toMatchObject({ content: "selected", offset: 2, truncated: true, next: 3 })
expect(yield* read(offset)).toEqual({ type: "text", content: "selected", offset: 2, lineCount: 1, next: 3 })
}
expect(yield* read(5).pipe(Effect.flip)).toBeInstanceOf(ReadToolFileSystem.BinaryFileError)
}),
@ -661,8 +657,8 @@ describe("ReadToolFileSystem", () => {
yield* files.writeFileString(file, `${"x".repeat(256 * 1024 - 2)}\n\uFEFFselected`)
const read = (offset: number) => ReadToolFileSystem.read(environment, file, "marked.txt", { offset, limit: 1 })
expect(yield* read(3)).toMatchObject({ content: "\uFEFFselected", offset: 2, truncated: false })
expect(yield* read(-1)).toMatchObject({ content: "selected", offset: 2, truncated: false })
expect(yield* read(3)).toEqual({ type: "text", content: "\uFEFFselected", offset: 2, lineCount: 1 })
expect(yield* read(-1)).toEqual({ type: "text", content: "selected", offset: 2, lineCount: 1 })
}),
)
@ -692,7 +688,7 @@ describe("ReadToolFileSystem", () => {
limit: 1,
})
expect(result).toMatchObject({ type: "text-page", content: "second", offset: 2, truncated: false })
expect(result).toEqual({ type: "text", content: "second", offset: 2, lineCount: 1 })
}),
)
@ -707,7 +703,7 @@ describe("ReadToolFileSystem", () => {
limit: 1,
})
expect(result).toMatchObject({ type: "text-page", content: "second", offset: 2, truncated: false })
expect(result).toEqual({ type: "text", content: "second", offset: 2, lineCount: 1 })
}),
)
@ -735,12 +731,14 @@ describe("ReadToolFileSystem", () => {
const result = yield* ReadToolFileSystem.read(environment, absolute(file), "document.pdf")
expect(result).toMatchObject({
type: "file",
content: Buffer.from("%PDF-1.7\ncontent").toString("base64"),
encoding: "base64",
expect(result).toEqual({
type: "media",
uri: pathToFileURL(file).href,
mime: "application/pdf",
name: "document.pdf",
bytes: expect.any(Uint8Array),
})
expect(result.type === "media" && Buffer.from(result.bytes).toString()).toBe("%PDF-1.7\ncontent")
}),
)
})

View file

@ -1,18 +1,18 @@
import { beforeEach, describe, expect } from "bun:test"
import fs from "fs/promises"
import path from "path"
import { pathToFileURL } from "url"
import { Effect, Exit, Layer, Result } from "effect"
import { Config } from "@opencode/core/config"
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
import { LayerNode } from "@opencode/util/effect/layer-node"
import { FileSystem } from "@opencode/core/filesystem"
import { FSUtil } from "@opencode/util/fs-util"
import { Location } from "@opencode/core/location"
import { Image } from "@opencode/core/image"
import { Permission } from "@opencode/core/permission"
import { Session } from "@opencode/core/session"
import { Skill } from "@opencode/core/skill"
import { AbsolutePath, RelativePath } from "@opencode/core/schema"
import { AbsolutePath } from "@opencode/core/schema"
import { Global } from "@opencode/util/global"
import { FileAccess } from "@opencode/core/file-access"
import { hostEnvironmentLayer } from "./fixture/environment"
@ -56,14 +56,19 @@ const listCalls: AbsolutePath[] = []
let readDefect: unknown
let missingDirectories: string[] = []
let directoryEntryDetails: Environment.DirEntry[] = []
let readResult: ReadToolFileSystem.FileContent | ReadToolFileSystem.TextPage | ReadToolFileSystem.ListPage = {
type: "file",
uri: "file:///README.md",
name: "README.md",
let readResult: ReadToolFileSystem.TextContent | ReadToolFileSystem.DirectoryContent | ReadToolFileSystem.Media = {
type: "text",
content: "hello",
encoding: "utf8",
mime: "text/plain",
offset: 1,
lineCount: 1,
}
const mediaResult = (name: string, mime: string, base64: string) => ({
type: "media" as const,
uri: `file:///${name}`,
name,
mime,
bytes: Buffer.from(base64, "base64"),
})
let readFailure: ReadToolFileSystem.ReadError | undefined
let readOverride: ReadToolFileSystem.Interface["read"] | undefined
const reader = Layer.succeed(
@ -131,16 +136,15 @@ const readLayer = (imageLayer: Layer.Layer<Image.Service>) =>
const it = testEffect(readLayer(imageLayer))
// Real-file tests provide their own layer per temp folder.
const live = testEffect(Layer.empty)
// Reads through the real filesystem with the location at `directory`; returns the failure message.
const readMissing = (directory: string, file: string) =>
// Reads through the real filesystem with the location at `directory`.
const readReal = (directory: string, file: string) =>
Effect.gen(function* () {
const registry = yield* Tool.Service
const result = yield* executeTool(registry, {
return yield* executeTool(registry, {
sessionID,
...toolIdentity,
call: { type: "tool-call", id: "call-suggest", name: "read", input: { path: file } },
})
return result.error?.message
}).pipe(
Effect.provide(
Layer.mergeAll(
@ -159,6 +163,9 @@ const readMissing = (directory: string, file: string) =>
),
),
)
// Returns the failure message of a real-filesystem read.
const readMissing = (directory: string, file: string) =>
readReal(directory, file).pipe(Effect.map((result) => result.error?.message))
const write = (file: string) =>
Effect.promise(() => fs.mkdir(path.dirname(file), { recursive: true }).then(() => fs.writeFile(file, "x\n")))
const itWithoutResizer = testEffect(readLayer(unavailableImage))
@ -174,14 +181,7 @@ describe("ReadTool", () => {
readDefect = undefined
missingDirectories = []
directoryEntryDetails = []
readResult = {
type: "file",
uri: "file:///README.md",
name: "README.md",
content: "hello",
encoding: "utf8",
mime: "text/plain",
}
readResult = { type: "text", content: "hello", offset: 1, lineCount: 1 }
readFailure = undefined
readOverride = undefined
})
@ -203,14 +203,8 @@ describe("ReadTool", () => {
})
expect(execution.status).toBe("completed")
if (execution.status !== "completed") return
expect(execution.output).toEqual({
type: "file",
uri: "file:///README.md",
name: "README.md",
content: "hello",
encoding: "utf8",
mime: "text/plain",
})
expect(execution.output).toEqual({ type: "text", content: "hello", offset: 1, lineCount: 1 })
expect(execution.metadata).toEqual({ truncated: false })
expect(execution.content).toEqual([{ type: "text", text: "Read file README.md, lines 1-1\n1: hello" }])
expect(assertions).toMatchObject([{ sessionID, action: "read", resources: ["README.md"], save: ["*"] }])
expect(readCalls).toEqual([
@ -267,14 +261,7 @@ describe("ReadTool", () => {
it.effect("returns a small PNG as native media instead of durable base64 text", () =>
Effect.gen(function* () {
const png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
readResult = {
type: "file",
uri: "file:///pixel.png",
name: "pixel.png",
content: png,
encoding: "base64",
mime: "image/png",
}
readResult = mediaResult("pixel.png", "image/png", png)
const registry = yield* Tool.Service
const execution = yield* executeTool(registry, {
@ -284,6 +271,12 @@ describe("ReadTool", () => {
})
expect(execution.status).toBe("completed")
if (execution.status !== "completed") return
expect(execution.output).toEqual({
type: "media",
uri: "file:///pixel.png",
mime: "image/png",
name: "pixel.png",
})
expect(execution.content).toEqual([
{ type: "text", text: "Image read successfully" },
{ type: "file", uri: `data:image/png;base64,${png}`, mime: "image/png", name: "pixel.png" },
@ -318,14 +311,7 @@ describe("ReadTool", () => {
const png = Buffer.from(source.get_bytes()).toString("base64")
source.free()
expect(Buffer.byteLength(png)).toBeGreaterThan(50 * 1024)
readResult = {
type: "file",
uri: "file:///large.png",
name: "large.png",
content: png,
encoding: "base64",
mime: "image/png",
}
readResult = mediaResult("large.png", "image/png", png)
const registry = yield* Tool.Service
const settled = yield* executeTool(registry, {
@ -336,12 +322,7 @@ describe("ReadTool", () => {
expect(settled.status).toBe("completed")
if (settled.status !== "completed") return
expect(settled.output).toMatchObject({
uri: "file:///large.png",
name: "large.png",
mime: "image/png",
encoding: "base64",
})
expect(settled.output).toEqual({ type: "media", uri: "file:///large.png", name: "large.png", mime: "image/png" })
expect(settled.content).toEqual([
{ type: "text", text: "Image read successfully" },
{ type: "file", uri: `data:image/png;base64,${png}`, mime: "image/png", name: "large.png" },
@ -352,14 +333,7 @@ describe("ReadTool", () => {
itWithoutResizer.effect("returns the original image when the resizer is unavailable", () =>
Effect.gen(function* () {
const png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
readResult = {
type: "file",
uri: "file:///pixel.png",
name: "pixel.png",
content: png,
encoding: "base64",
mime: "image/png",
}
readResult = mediaResult("pixel.png", "image/png", png)
const registry = yield* Tool.Service
expect(
@ -377,14 +351,7 @@ describe("ReadTool", () => {
it.effect("drops undecodable image data from the outcome", () =>
Effect.gen(function* () {
readResult = {
type: "file",
uri: "file:///truncated.png",
name: "truncated.png",
content: "iVBORw0KGgo=",
encoding: "base64",
mime: "image/png",
}
readResult = mediaResult("truncated.png", "image/png", "iVBORw0KGgo=")
const registry = yield* Tool.Service
expect(
@ -409,14 +376,7 @@ describe("ReadTool", () => {
const source = new photon.PhotonImage(new Uint8Array(Array.from({ length: 16 * 4 }, () => 255)), 16, 1)
const base64 = Buffer.from(source.get_bytes()).toString("base64")
source.free()
readResult = {
type: "file",
uri: "file:///wide.png",
name: "wide.png",
content: base64,
encoding: "base64",
mime: "image/png",
}
readResult = mediaResult("wide.png", "image/png", base64)
const image = yield* Image.Service
yield* image.transform((editor) => editor.configure({ autoResize: false, maxWidth: 4 }))
const registry = yield* Tool.Service
@ -443,14 +403,7 @@ describe("ReadTool", () => {
const source = new photon.PhotonImage(new Uint8Array(Array.from({ length: 16 * 4 }, () => 255)), 16, 1)
const base64 = Buffer.from(source.get_bytes()).toString("base64")
source.free()
readResult = {
type: "file",
uri: "file:///wide.png",
name: "wide.png",
content: base64,
encoding: "base64",
mime: "image/png",
}
readResult = mediaResult("wide.png", "image/png", base64)
const image = yield* Image.Service
yield* image.transform((editor) => editor.configure({ maxWidth: 4 }))
const registry = yield* Tool.Service
@ -483,14 +436,7 @@ describe("ReadTool", () => {
const opaqueSource = new photon.PhotonImage(opaquePixels, width, height)
const opaqueBase64 = Buffer.from(opaqueSource.get_bytes()).toString("base64")
opaqueSource.free()
readResult = {
type: "file",
uri: "file:///screenshot.png",
name: "screenshot.png",
content: opaqueBase64,
encoding: "base64",
mime: "image/png",
}
readResult = mediaResult("screenshot.png", "image/png", opaqueBase64)
const registry = yield* Tool.Service
const result = yield* executeTool(registry, {
sessionID,
@ -590,14 +536,7 @@ describe("ReadTool", () => {
it.effect("drops images that cannot fit max base64 bytes after resize attempts", () =>
Effect.gen(function* () {
const png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
readResult = {
type: "file",
uri: "file:///pixel.png",
name: "pixel.png",
content: png,
encoding: "base64",
mime: "image/png",
}
readResult = mediaResult("pixel.png", "image/png", png)
const image = yield* Image.Service
yield* image.transform((editor) => editor.configure({ maxBase64Bytes: 1 }))
const registry = yield* Tool.Service
@ -621,14 +560,7 @@ describe("ReadTool", () => {
it.effect("returns supported image contents despite a misleading binary extension", () =>
Effect.gen(function* () {
const png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
readResult = {
type: "file",
uri: "file:///pixel.bin",
name: "pixel.bin",
content: png,
encoding: "base64",
mime: "image/png",
}
readResult = mediaResult("pixel.bin", "image/png", png)
const registry = yield* Tool.Service
expect(
@ -647,14 +579,7 @@ describe("ReadTool", () => {
it.effect("returns PDFs as native media", () =>
Effect.gen(function* () {
const pdf = "JVBERi0xLjcK"
readResult = {
type: "file",
uri: "file:///document.pdf",
name: "document.pdf",
content: pdf,
encoding: "base64",
mime: "application/pdf",
}
readResult = mediaResult("document.pdf", "application/pdf", pdf)
const registry = yield* Tool.Service
expect(
@ -665,6 +590,7 @@ describe("ReadTool", () => {
}),
).toMatchObject({
status: "completed",
output: { type: "media", uri: "file:///document.pdf", mime: "application/pdf", name: "document.pdf" },
content: [
{ type: "text", text: "PDF read successfully" },
{ type: "file", uri: `data:application/pdf;base64,${pdf}`, mime: "application/pdf", name: "document.pdf" },
@ -673,6 +599,54 @@ describe("ReadTool", () => {
}),
)
live.live("attaches real image and PDF files without their bytes in the structured output", () =>
withTempDir((tmp) =>
Effect.gen(function* () {
const files = [
{
name: "pixel.png",
mime: "image/png",
text: "Image read successfully",
bytes: Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=",
"base64",
),
},
{
name: "document.pdf",
mime: "application/pdf",
text: "PDF read successfully",
bytes: Buffer.from("%PDF-1.7\ncontent"),
},
]
for (const file of files) {
const absolute = path.join(tmp.path, file.name)
yield* Effect.promise(() => fs.writeFile(absolute, file.bytes))
const result = yield* readReal(tmp.path, file.name)
expect(result.status).toBe("completed")
if (result.status !== "completed") return
expect(result.output).toEqual({
type: "media",
uri: pathToFileURL(absolute).href,
mime: file.mime,
name: file.name,
})
expect(result.content).toEqual([
{ type: "text", text: file.text },
{
type: "file",
uri: `data:${file.mime};base64,${file.bytes.toString("base64")}`,
mime: file.mime,
name: file.name,
},
])
}
}),
),
)
it.effect("returns expected filesystem failures to the model", () =>
Effect.gen(function* () {
readFailure = new ReadToolFileSystem.BinaryFileError({ resource: "archive.dat" })
@ -1035,7 +1009,7 @@ describe("ReadTool", () => {
readOverride = (input) =>
input === requestedAbsolute
? Effect.fail(new Environment.NotFound({ path: requestedAbsolute }))
: Effect.succeed(new ReadToolFileSystem.ListPage({ type: "list-page", entries: [], truncated: false }))
: Effect.succeed({ type: "directory" as const, entries: [] })
const registry = yield* Tool.Service
expect(
@ -1052,15 +1026,7 @@ describe("ReadTool", () => {
it.effect("lists a bounded directory page through read", () =>
Effect.gen(function* () {
readResult = new ReadToolFileSystem.ListPage({
type: "list-page",
entries: [
FileSystem.Entry.make({ path: RelativePath.make("components/"), type: "directory" }),
FileSystem.Entry.make({ path: RelativePath.make("index.ts"), type: "file" }),
],
truncated: true,
next: 4,
})
readResult = { type: "directory", entries: ["components/", "index.ts"], next: 4 }
const registry = yield* Tool.Service
const result = yield* executeTool(registry, {
@ -1075,7 +1041,7 @@ describe("ReadTool", () => {
})
expect(result).toMatchObject({
status: "completed",
output: { entries: readResult.entries, truncated: true, next: 4 },
output: { type: "directory", entries: ["components/", "index.ts"], next: 4 },
})
if (result.status !== "completed") return
expect(result.metadata).toEqual({ truncated: true })
@ -1094,12 +1060,7 @@ describe("ReadTool", () => {
it.effect("normalizes a zero directory offset in the model heading", () =>
Effect.gen(function* () {
readResult = new ReadToolFileSystem.ListPage({
type: "list-page",
entries: [FileSystem.Entry.make({ path: RelativePath.make("index.ts"), type: "file" })],
truncated: true,
next: 2,
})
readResult = { type: "directory", entries: ["index.ts"], next: 2 }
const registry = yield* Tool.Service
const result = yield* executeTool(registry, {
@ -1144,15 +1105,7 @@ describe("ReadTool", () => {
it.effect("forwards pagination and returns bounded text pages with continuation", () =>
Effect.gen(function* () {
readResult = new ReadToolFileSystem.TextPage({
type: "text-page",
content: "hello",
lineCount: 1,
mime: "text/plain",
offset: 2,
truncated: true,
next: 3,
})
readResult = { type: "text", content: "hello", offset: 2, lineCount: 1, next: 3 }
const registry = yield* Tool.Service
const result = yield* executeTool(registry, {
@ -1167,7 +1120,7 @@ describe("ReadTool", () => {
})
expect(result).toMatchObject({
status: "completed",
output: { type: "text-page", content: "hello", mime: "text/plain", offset: 2, truncated: true, next: 3 },
output: { type: "text", content: "hello", offset: 2, lineCount: 1, next: 3 },
})
if (result.status !== "completed") return
expect(result.metadata).toEqual({ truncated: true })
@ -1185,15 +1138,7 @@ describe("ReadTool", () => {
it.effect("forwards a negative offset and shows the real line numbers and continuation", () =>
Effect.gen(function* () {
readResult = new ReadToolFileSystem.TextPage({
type: "text-page",
content: "nine\nten",
lineCount: 2,
mime: "text/plain",
offset: 9,
truncated: true,
next: 11,
})
readResult = { type: "text", content: "nine\nten", offset: 9, lineCount: 2, next: 11 }
const registry = yield* Tool.Service
const result = yield* executeTool(registry, {
@ -1250,6 +1195,7 @@ describe("ReadTool", () => {
}),
{
"references/style.md": "Line 1\nLine 2",
"references/guide.pdf": "%PDF-1.7\nguide",
},
),
)
@ -1276,6 +1222,7 @@ describe("ReadTool", () => {
})
expect(file).toMatchObject({
status: "completed",
output: { type: "text", content: "Line 2", offset: 2, lineCount: 1 },
content: [{ type: "text", text: "Read file skill://guide/references/style.md, lines 2-2\n2: Line 2" }],
})
@ -1286,6 +1233,7 @@ describe("ReadTool", () => {
})
expect(root).toMatchObject({
status: "completed",
output: { type: "directory", entries: ["references/", "SKILL.md"] },
content: [
{
type: "text",
@ -1323,6 +1271,36 @@ describe("ReadTool", () => {
])
expect(readCalls).toEqual([])
const pdf = yield* executeTool(registry, {
sessionID,
...toolIdentity,
call: {
type: "tool-call",
id: "call-skill-pdf",
name: "read",
input: { path: "skill://guide/references/guide.pdf" },
},
})
expect(pdf).toMatchObject({
status: "completed",
content: [
{ type: "text", text: "PDF read successfully" },
{
type: "file",
uri: `data:application/pdf;base64,${Buffer.from("%PDF-1.7\nguide").toString("base64")}`,
mime: "application/pdf",
name: "skill://guide/references/guide.pdf",
},
],
})
if (pdf.status !== "completed") return
expect(pdf.output).toEqual({
type: "media",
uri: "skill://guide/references/guide.pdf",
mime: "application/pdf",
name: "guide.pdf",
})
deniedResource = "guide"
expect(
yield* executeTool(registry, {