Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 82 additions & 14 deletions packages/core/src/tool/plugin/patch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,17 @@ import { FileDiff } from "@opencode/schema/file-diff"
import { Effect, Result, Schema } from "effect"
import { Bom } from "@opencode/util/bom"
import { toolFailure } from "../runtime.js"
import { Config } from "../../config.js"
import { Environment } from "../../environment/index.js"
import { Formatter } from "../../formatter.js"
import { FileMutation } from "../../file-mutation.js"
import { Location } from "../../location.js"
import { FileAccess } from "../../file-access.js"
import { Patch } from "@opencode/util/patch"
import type { ConfigExperimental } from "@opencode/schema/config/experimental"
import type { Document, Entry } from "@opencode/schema/config"
import { Permission } from "../../permission.js"
import { Session } from "../../session.js"
import DESCRIPTION from "../patch.txt"
import GRAMMAR from "../patch-grammar.txt"
import { fileDiff } from "./file-diff.js"
Expand Down Expand Up @@ -51,6 +55,8 @@ type Prepared =
export const Plugin = {
id: "opencode.tool.patch",
effect: Effect.fn("PatchTool.Plugin")(function* (ctx: Context) {
const config = yield* Config.Service
const sessions = yield* Session.Service
const environment = yield* Environment.Service
const access = yield* FileAccess.Service
const fileMutation = yield* FileMutation.Service
Expand Down Expand Up @@ -272,15 +278,15 @@ export const Plugin = {
const target = change.type === "update" && change.moveTarget ? change.moveTarget : change.target
return patchFile(change, formatted.get(target.absolute))
})
const session = yield* sessions.get(context.sessionID).pipe(Effect.orElseSucceed(() => undefined))
const resultStyle = selectEditingResult(
session?.model,
configuredEditing(yield* config.entries()),
)
return {
// The multi-file patch contract intentionally leaves structured output empty.
output: {},
content: [
"Success. Updated the following files:",
...files.map(
(file) => `${file.status === "added" ? "A" : file.status === "deleted" ? "D" : "M"} ${file.file}`,
),
].join("\n"),
content: renderResult(files, resultStyle),
metadata: { files },
}
}).pipe(fileMutation.withLock(lockTargets), Effect.mapError(toolFailure("Unable to apply patch")))
Expand All @@ -290,22 +296,77 @@ export const Plugin = {
.pipe(Effect.orDie)

const hook = (event: SessionHooks["context"]) =>
Effect.sync(() => {
const usePatch =
event.model.id.includes("gpt-") && !event.model.id.includes("oss") && !event.model.id.includes("gpt-4")
if (usePatch) {
delete event.tools.edit
delete event.tools.write
return
Effect.gen(function* () {
const entries = yield* config.entries()
const tools = selectEditingTools(event.model, configuredEditing(entries))
for (const name of EDITING_TOOLS) {
if (!tools.has(name)) delete event.tools[name]
}
delete event.tools.patch
})
yield* ctx.session.hook("context", hook)
yield* ctx.session.hook("compaction", hook)
yield* ctx.session.hook("generate", hook)
}),
}

export const EDITING_TOOLS = ["patch", "edit", "write"] as const
type EditingTool = (typeof EDITING_TOOLS)[number]
type ModelRef = SessionHooks["context"]["model"]

function heuristicEditingTools(model: ModelRef): ReadonlySet<EditingTool> {
const patch = model.id.includes("gpt-") && !model.id.includes("oss") && !model.id.includes("gpt-4")
return new Set<EditingTool>(patch ? ["patch"] : ["edit", "write"])
}

function matchingRule(model: ModelRef | undefined, editing: ConfigExperimental.Editing | undefined) {
if (!model || !editing) return undefined
return editing.rules?.findLast((candidate) =>
new RegExp(candidate.match).test(`${model.providerID}/${model.id}`),
)
}

function selectEditingTools(model: ModelRef, editing: ConfigExperimental.Editing | undefined) {
const tools = new Set(heuristicEditingTools(model))
if (!editing) return tools
const delta = matchingRule(model, editing) ?? editing
for (const name of delta.add ?? []) tools.add(name)
for (const name of delta.remove ?? []) tools.delete(name)
return tools
}

function selectEditingResult(
model: ModelRef | undefined,
editing: ConfigExperimental.Editing | undefined,
): ConfigExperimental.EditingResult {
if (!editing) return "summary"
return matchingRule(model, editing)?.result_style ?? editing.result_style ?? "summary"
}

function renderResult(
files: ReadonlyArray<typeof FileDiff.Info.Type>,
style: ConfigExperimental.EditingResult,
) {
const label = (file: (typeof files)[number]) =>
`${file.status === "added" ? "A" : file.status === "deleted" ? "D" : "M"} ${file.file}${
style === "summary" ? "" : ` (+${file.additions} -${file.deletions})`
}`
return [
"Success. Updated the following files:",
...files.flatMap((file) => (style === "diff" ? [`${label(file)}\n${renderDiff(file.patch)}`] : [label(file)])),
].join("\n")
}

function renderDiff(patch: string) {
const lines = patch.split("\n")
const start = lines.findIndex((line) => line.startsWith("@@"))
if (start === -1) return ""
const body = lines.slice(start)
const limited = body.slice(0, 200)
const text = limited.join("\n")
const clipped = text.length > 12_000 ? text.slice(0, 12_000) : text
return body.length > limited.length || text.length > clipped.length ? `${clipped}\n... diff truncated ...` : clipped
}

function errorMessage(error: unknown) {
if (error instanceof Environment.NotFound) return "file does not exist"
if (error instanceof Environment.WrongKind)
Expand All @@ -314,6 +375,13 @@ function errorMessage(error: unknown) {
return error instanceof Error ? error.message : String(error)
}

// Read per field so a later config that sets other experimental options doesn't hide this one.
function configuredEditing(entries: readonly Entry[]) {
return entries.findLast(
(entry): entry is Document => entry.type === "document" && entry.info.experimental?.editing !== undefined,
)?.info.experimental?.editing
}

function patchFile(change: Prepared, after = change.after): typeof FileDiff.Info.Type {
const target = (change.type === "update" ? change.moveTarget : undefined)?.resource ?? change.target.resource
const diff = fileDiff(
Expand Down
47 changes: 47 additions & 0 deletions packages/core/test/config/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { Config } from "@opencode/core/config"
import { ConfigDiscovery } from "@opencode/core/config/discovery"
import { ConfigIntegration } from "@opencode/core/config/integration"
import { Directory, Document, type Entry, Event, Info } from "@opencode/schema/config"
import { ConfigExperimental } from "@opencode/schema/config/experimental"
import { ConfigModel } from "@opencode/schema/config/model"
import { ConfigProvider } from "@opencode/schema/config/provider"
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
Expand Down Expand Up @@ -2243,3 +2244,49 @@ describe("Config", () => {
),
)
})

describe("experimental editing", () => {
const decode = Schema.decodeUnknownSync(ConfigExperimental.Info)

test("decodes add, remove, and result style deltas", () => {
expect(decode({ editing: { add: ["patch"], remove: ["edit", "write"], result_style: "diff" } }).editing).toEqual({
add: ["patch"],
remove: ["edit", "write"],
result_style: "diff",
})
})

test("decodes ordered rules", () => {
expect(
decode({
editing: {
add: ["patch"],
rules: [{ match: "^test/claude", add: ["patch"], remove: ["edit", "write"] }],
},
}).editing?.rules,
).toEqual([{ match: "^test/claude", add: ["patch"], remove: ["edit", "write"] }])
})

test("accepts an empty editing block", () => {
expect(decode({ editing: {} }).editing).toEqual({})
})

test("rejects overlapping add and remove", () => {
expect(() => decode({ editing: { add: ["patch"], remove: ["patch"] } })).toThrow()
expect(() =>
decode({ editing: { rules: [{ match: "^test/", add: ["edit"], remove: ["edit"] }] } }),
).toThrow()
})

test("rejects unknown editing tools", () => {
expect(() => decode({ editing: { add: ["multiedit"] } })).toThrow()
})

test("rejects an unknown result style", () => {
expect(() => decode({ editing: { result_style: "verbose" } })).toThrow()
})

test("rejects an invalid match expression", () => {
expect(() => decode({ editing: { rules: [{ match: "(", add: ["patch"] }] } })).toThrow()
})
})
Loading
Loading