diff --git a/packages/core/src/tool/plugin/patch.ts b/packages/core/src/tool/plugin/patch.ts index b957cfe0593a..b322d1b90194 100644 --- a/packages/core/src/tool/plugin/patch.ts +++ b/packages/core/src/tool/plugin/patch.ts @@ -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" @@ -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 @@ -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"))) @@ -290,15 +296,12 @@ 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) @@ -306,6 +309,64 @@ export const Plugin = { }), } +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 { + const patch = model.id.includes("gpt-") && !model.id.includes("oss") && !model.id.includes("gpt-4") + return new Set(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, + 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) @@ -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( diff --git a/packages/core/test/config/config.test.ts b/packages/core/test/config/config.test.ts index b85604282bbe..c1039e55acfe 100644 --- a/packages/core/test/config/config.test.ts +++ b/packages/core/test/config/config.test.ts @@ -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" @@ -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() + }) +}) diff --git a/packages/core/test/tool-patch.test.ts b/packages/core/test/tool-patch.test.ts index dd38220e383c..d791014c6ae0 100644 --- a/packages/core/test/tool-patch.test.ts +++ b/packages/core/test/tool-patch.test.ts @@ -3,6 +3,7 @@ import path from "path" import { describe, expect } from "bun:test" import { Effect, Exit, Layer } from "effect" import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" +import { Config } from "@opencode/core/config" import { LayerNode } from "@opencode/util/effect/layer-node" import { Environment } from "@opencode/core/environment/index" import { Formatter } from "@opencode/core/formatter" @@ -17,6 +18,8 @@ import { Session } from "@opencode/core/session" import { Tool } from "@opencode/core/tool" import { PatchTool } from "@opencode/core/tool/plugin/patch" import type { SessionHooks } from "@opencode/plugin/effect/session" +import { Document, type Entry, Info } from "@opencode/schema/config" +import { ConfigExperimental } from "@opencode/schema/config/experimental" import { transformEnvironmentFiles } from "./fixture/environment" import { location } from "./fixture/location" import { tmpdir, withTempDir } from "./fixture/tmpdir" @@ -47,6 +50,8 @@ const patchToolNode = makeLocationNode({ Formatter.node, Location.node, Permission.node, + Config.node, + Session.node, ], }) @@ -60,6 +65,8 @@ let readsBeforeEditApproval = 0 let editApproved = false let afterEditApproval = (): Effect.Effect => Effect.void let formatFile = (_target: string): Effect.Effect => Effect.succeed(false) +let configEntries: Entry[] = [] +let sessionModelID = "claude-sonnet-4" const permission = permissionLayer({ assert: (input) => @@ -96,6 +103,8 @@ const reset = () => { editApproved = false afterEditApproval = () => Effect.void formatFile = () => Effect.succeed(false) + configEntries = [] + sessionModelID = "claude-sonnet-4" } const withTool = ( @@ -137,6 +146,16 @@ const withTool = ( Location.node.replace(activeLocation), Formatter.node.replace(formatter), Permission.node.replace(permission), + Config.node.replace(Config.testLayer(configEntries)), + Session.node.replace( + Layer.succeed(Session.Service, { + get: (sessionID: Session.ID) => + Effect.succeed({ + id: sessionID, + model: Model.Ref.make({ providerID: Provider.ID.make("test"), id: Model.ID.make(sessionModelID) }), + } as Session.Info), + } as unknown as Session.Interface), + ), ]), ), ) @@ -156,34 +175,46 @@ const exists = (target: string) => ), ) const it = testEffect(Layer.empty) -const withTempTool = (body: (directory: string, registry: Tool.Interface) => Effect.Effect) => +const withTempTool = ( + body: (directory: string, registry: Tool.Interface) => Effect.Effect, + entries: Entry[] = [], +) => withTempDir((tmp) => { reset() + configEntries = entries return withTool(tmp.path, (registry) => body(tmp.path, registry)) }) +const editingConfig = (editing: ConfigExperimental.Editing) => [ + new Document({ + type: "document", + info: new Info({ experimental: new ConfigExperimental.Info({ editing }) }), + }), +] + +const contextEvent = (id: string): SessionHooks["context"] => ({ + sessionID, + agent: toolIdentity.agent, + model: Model.Ref.make({ providerID: Provider.ID.make("test"), id: Model.ID.make(id) }), + system: [], + messages: [], + tools: Object.fromEntries( + ["patch", "edit", "write", "read"].map((name) => [name, { description: name, input: { type: "object" } }]), + ), + options: {}, +}) + describe("PatchTool", () => { it.live("selects the same edit tools for compaction and generate requests as the agent loop", () => withTempTool(() => Effect.gen(function* () { - const event = (id: string): SessionHooks["context"] => ({ - sessionID, - agent: toolIdentity.agent, - model: Model.Ref.make({ providerID: Provider.ID.make("test"), id: Model.ID.make(id) }), - system: [], - messages: [], - tools: Object.fromEntries( - ["patch", "edit", "write", "read"].map((name) => [name, { description: name, input: { type: "object" } }]), - ), - options: {}, - }) for (const name of ["context", "compaction", "generate"]) { const hook = sessionHooks.get(name) expect(hook).toBeDefined() - const claude = event("claude-sonnet-4") + const claude = contextEvent("claude-sonnet-4") yield* hook!(claude) expect(Object.keys(claude.tools)).toEqual(["edit", "write", "read"]) - const gpt = event("gpt-5") + const gpt = contextEvent("gpt-5") yield* hook!(gpt) expect(Object.keys(gpt.tools)).toEqual(["patch", "read"]) } @@ -191,6 +222,166 @@ describe("PatchTool", () => { ), ) + it.live("applies experimental editing add and remove deltas", () => + withTempTool( + () => + Effect.gen(function* () { + const hook = sessionHooks.get("context")! + for (const id of ["claude-sonnet-4", "gpt-5"]) { + const event = contextEvent(id) + yield* hook(event) + expect(Object.keys(event.tools)).toEqual(["patch", "read"]) + } + }), + editingConfig({ add: ["patch"], remove: ["edit", "write"] }), + ), + ) + + it.live("keeps the model-dependent base when only remove is configured", () => + withTempTool( + () => + Effect.gen(function* () { + const hook = sessionHooks.get("context")! + const gpt = contextEvent("gpt-5") + yield* hook(gpt) + expect(Object.keys(gpt.tools)).toEqual(["patch", "read"]) + const claude = contextEvent("claude-sonnet-4") + yield* hook(claude) + expect(Object.keys(claude.tools)).toEqual(["read"]) + }), + editingConfig({ remove: ["edit", "write"] }), + ), + ) + + it.live("uses the last matching editing rule over the top-level delta", () => + withTempTool( + () => + Effect.gen(function* () { + const hook = sessionHooks.get("context")! + const claude = contextEvent("claude-sonnet-4") + yield* hook(claude) + expect(Object.keys(claude.tools)).toEqual(["patch", "read"]) + const gpt = contextEvent("gpt-5") + yield* hook(gpt) + expect(Object.keys(gpt.tools)).toEqual(["edit", "write", "read"]) + }), + editingConfig({ + add: ["edit", "write"], + remove: ["patch"], + rules: [{ match: "^test/claude", add: ["patch"], remove: ["edit", "write"] }], + }), + ), + ) + + it.live("reports patch results without counts when result_style is summary", () => + withTempTool( + (directory, registry) => + Effect.gen(function* () { + const settled = yield* executeTool( + registry, + call("*** Begin Patch\n*** Add File: style-summary.txt\n+created\n*** End Patch"), + ) + expect(settled.status).toBe("completed") + if (settled.status !== "completed") return + const text = settled.content?.[0]?.type === "text" ? settled.content[0].text : "" + expect(text).toContain("A style-summary.txt") + expect(text).not.toContain("(+") + expect(yield* Effect.promise(() => fs.readFile(path.join(directory, "style-summary.txt"), "utf8"))).toBe( + "created\n", + ) + }), + editingConfig({ result_style: "summary" }), + ), + ) + + it.live("keeps the base patch result when no editing config is set", () => + withTempTool((directory, registry) => + Effect.gen(function* () { + const settled = yield* executeTool( + registry, + call("*** Begin Patch\n*** Add File: default-style.txt\n+created\n*** End Patch"), + ) + expect(settled.status).toBe("completed") + if (settled.status !== "completed") return + expect(settled.content).toEqual([ + { type: "text", text: "Success. Updated the following files:\nA default-style.txt" }, + ]) + expect(yield* Effect.promise(() => fs.readFile(path.join(directory, "default-style.txt"), "utf8"))).toBe( + "created\n", + ) + }), + ), + ) + + it.live("keeps editing when a later config sets another experimental option", () => + withTempTool( + () => + Effect.gen(function* () { + const hook = sessionHooks.get("context")! + const claude = contextEvent("claude-sonnet-4") + yield* hook(claude) + expect(Object.keys(claude.tools)).toEqual(["patch", "read"]) + }), + [ + ...editingConfig({ add: ["patch"], remove: ["edit", "write"] }), + new Document({ + type: "document", + info: new Info({ experimental: new ConfigExperimental.Info({ subagent_depth: 2 }) }), + }), + ], + ), + ) + + it.live("includes the applied diff when result_style is diff and a rule overrides it", () => + withTempTool( + (directory, registry) => + Effect.gen(function* () { + sessionModelID = "claude-sonnet-4" + const settled = yield* executeTool( + registry, + call("*** Begin Patch\n*** Add File: style-diff.txt\n+created\n*** End Patch"), + ) + expect(settled.status).toBe("completed") + if (settled.status !== "completed") return + const text = settled.content?.[0]?.type === "text" ? settled.content[0].text : "" + expect(text).toContain("A style-diff.txt (+1 -0)") + expect(text).toContain("+created") + expect(text).toContain("@@") + expect(text).not.toContain("Index:") + expect(text).not.toContain(directory) + expect(yield* Effect.promise(() => fs.readFile(path.join(directory, "style-diff.txt"), "utf8"))).toBe( + "created\n", + ) + }), + editingConfig({ + result_style: "summary", + rules: [{ match: "^test/claude", result_style: "diff" }], + }), + ), + ) + + it.live("truncates a large diff before returning it to the model", () => + withTempTool( + (directory, registry) => + Effect.gen(function* () { + const lines = Array.from({ length: 250 }, (_, index) => `+line ${index}`).join("\n") + const settled = yield* executeTool( + registry, + call(`*** Begin Patch\n*** Add File: large-diff.txt\n${lines}\n*** End Patch`), + ) + expect(settled.status).toBe("completed") + if (settled.status !== "completed") return + const text = settled.content?.[0]?.type === "text" ? settled.content[0].text : "" + expect(text).toContain("... diff truncated ...") + expect(text).not.toContain("line 249") + expect(yield* Effect.promise(() => fs.readFile(path.join(directory, "large-diff.txt"), "utf8"))).toContain( + "line 249", + ) + }), + editingConfig({ result_style: "diff" }), + ), + ) + it.live("registers and sequentially applies add, update, and delete hunks", () => withTempDir((tmp) => { reset() diff --git a/packages/schema/src/config/experimental.ts b/packages/schema/src/config/experimental.ts index d46710bcdcc7..5e087519a34b 100644 --- a/packages/schema/src/config/experimental.ts +++ b/packages/schema/src/config/experimental.ts @@ -6,6 +6,67 @@ import { ConfigFlag } from "./flag.js" import { ConfigModel } from "./model.js" import { ConfigPolicy } from "./policy.js" +const EditingTool = Schema.Literals(["patch", "edit", "write"]) +export type EditingTool = typeof EditingTool.Type + +const EditingResult = Schema.Literals(["summary", "counts", "diff"]) +export type EditingResult = typeof EditingResult.Type + +const EditingTools = EditingTool.pipe(Schema.Array) + +const EditingDeltaFields = { + add: EditingTools.pipe(optional).annotate({ + description: "Editing tools to add to the model's built-in editing set", + }), + remove: EditingTools.pipe(optional).annotate({ + description: "Editing tools to remove from the model's built-in editing set", + }), + result_style: EditingResult.pipe(optional).annotate({ + description: + "How patch results are reported to the model: file list, line counts, or the applied diff. Defaults to the file list.", + }), +} + +const overlap = (value: { readonly add?: readonly EditingTool[]; readonly remove?: readonly EditingTool[] }) => + (value.add ?? []).some((tool) => (value.remove ?? []).includes(tool)) + +const Match = Schema.String.pipe( + // JavaScript has no separate regex validation, so compile once at decode time. + Schema.refine( + (value): value is typeof value => { + try { + new RegExp(value) + return true + } catch { + return false + } + }, + { message: "match must be a valid regular expression" }, + ), +).annotate({ description: "Regular expression matched against providerID/modelID" }) + +export const EditingRule = Schema.Struct({ + match: Match, + ...EditingDeltaFields, +}).pipe( + Schema.refine((value): value is typeof value => !overlap(value), { + message: "editing rule add and remove must not contain the same tool", + }), +) +export interface EditingRule extends Schema.Schema.Type {} + +export const Editing = Schema.Struct({ + ...EditingDeltaFields, + rules: EditingRule.pipe(Schema.Array, optional).annotate({ + description: "Ordered overrides. The last matching rule wins and replaces the top-level add/remove.", + }), +}).pipe( + Schema.refine((value): value is typeof value => !overlap(value), { + message: "editing add and remove must not contain the same tool", + }), +) +export interface Editing extends Schema.Schema.Type {} + export class Info extends Schema.Class("ConfigExperimental.Info")({ portable_shell_scanner: Schema.Boolean.pipe(optional).annotate({ description: "Deprecated: the built-in shell permission scanner is now always enabled.", @@ -40,6 +101,10 @@ export class Info extends Schema.Class("ConfigExperimental.Info")({ description: "Settings for the experimental_image_generate tool, which is offered while a connected provider has an image model.", }), + editing: Editing.pipe(optional).annotate({ + description: + "Adjust which editing tools (patch, edit, write) are offered per model. This does not remove any other tool.", + }), subagent_depth: NonNegativeInt.pipe(optional).annotate({ description: "Maximum subagent nesting depth. Defaults to 1.", }), diff --git a/services/site/src/docs/content/config.mdx b/services/site/src/docs/content/config.mdx index 0cded3ea2dae..60164adbb65e 100644 --- a/services/site/src/docs/content/config.mdx +++ b/services/site/src/docs/content/config.mdx @@ -675,6 +675,48 @@ picks another image model automatically. } ``` +### Editing tools + +`editing` adjusts which editing tools OpenCode offers per model. It changes only `patch`, `edit`, and `write`; every +other tool is untouched. + +```jsonc +{ + "experimental": { + "editing": { + "add": ["patch"], + "remove": ["edit", "write"], + "result_style": "diff", + "rules": [ + { "match": "^anthropic/", "add": ["patch"], "remove": ["edit", "write"] }, + ], + }, + }, +} +``` + +`add` and `remove` adjust the built-in editing set. That set is `patch` for GPT model IDs containing `gpt-` but not +`oss` or `gpt-4`, and `edit` and `write` for every other model. Because the base set is model-dependent, `remove` +alone is not model-independent; normalize both sides to force one set. + +`rules` override the top-level `add`/`remove` when their `match` regular expression matches `providerID/modelID`. The +last matching rule wins, and rules do not accumulate. An empty rule resets to the built-in set. `add` and `remove` +in the same scope must not contain the same tool, or configuration decoding fails. + +`result_style` controls the `patch` success message. `summary` lists the files, `counts` adds `+N -M`, and `diff` +includes the applied diff without file headers and caps very large output. A rule may set its own style. Otherwise the +top-level value applies, and the default is `summary`, so existing behavior is unchanged when this config is absent. + +```jsonc +{ + "experimental": { + "editing": { + "result_style": "summary", + }, + }, +} +``` + ### Location idle timeout `location_idle_timeout` controls how long a project location can go without session activity before OpenCode unloads diff --git a/services/site/src/docs/content/tools.mdx b/services/site/src/docs/content/tools.mdx index 6f7dac76f35b..8b4d133f27d1 100644 --- a/services/site/src/docs/content/tools.mdx +++ b/services/site/src/docs/content/tools.mdx @@ -98,8 +98,10 @@ sections. Use patch to rename src/old.ts to src/new.ts and update its exported name. ``` -OpenCode exposes `patch` for supported GPT models; other models receive `edit` -and `write` instead. Permission: `edit` with every affected path as a resource. +By default OpenCode exposes `patch` for supported GPT models; other models +receive `edit` and `write` instead. Configure +[`experimental.editing`](/config#editing-tools) to add or remove the editing +tools per model. Permission: `edit` with every affected path as a resource. Paths outside the active Location or its project worktree are also checked against `external_directory`, which is allowed by default. See