feat(core): move worktree tools into core (#53981)

This commit is contained in:
James Long
2026-10-08 17:23:43 -04:00
committed by GitHub
Unverified
parent 886e236b7c
commit 7d179e83f4
4 changed files with 298 additions and 50 deletions
+99 -1
View File
@@ -7,6 +7,10 @@ import { Model } from "@opencode/schema/model"
import { AbsolutePath } from "@opencode/schema/schema"
import { Session } from "@opencode/schema/session"
import { Effect, Schema } from "effect"
import { FileAccess } from "../../file-access.js"
import { Git } from "../../git.js"
import { Permission } from "../../permission.js"
import { Worktree } from "../../worktree.js"
export const RenameInput = Schema.Struct({
sessionID: Schema.optionalKey(Session.ID).annotate({ description: "Omit to rename the current session." }),
@@ -24,6 +28,21 @@ export const MoveInput = Schema.Struct({
const MoveOutput = Schema.Struct({ sessionID: Session.ID, directory: AbsolutePath })
export const WorktreeCreateInput = Schema.Struct({
name: Schema.Trim.check(Schema.isNonEmpty()).annotate({ description: "Worktree name." }),
})
export const WorktreeRemoveInput = Schema.Struct({
directory: AbsolutePath.check(Schema.isMinLength(1)).annotate({
description: "Absolute path of the worktree to remove.",
}),
force: Schema.optionalKey(Schema.Boolean).annotate({
description: "Discard modified and untracked files. Only set this when the user has confirmed forced removal.",
}),
})
const WorktreeRemoveOutput = Schema.Struct({ directory: AbsolutePath, removed: Schema.Boolean })
export const ModelsInput = Schema.Struct({
query: Schema.optionalKey(Schema.String).annotate({
description: "Text to search for in model names and IDs.",
@@ -68,6 +87,8 @@ const ModelsOutput = Schema.Struct({
export const Plugin = {
id: "opencode.tools",
effect: Effect.fn("OpenCodeTools.Plugin")(function* (ctx: Context) {
const access = yield* FileAccess.Service
const permission = yield* Permission.Service
const hook = (event: SessionHooks["context"]) =>
Effect.sync(() => {
event.system.push(
@@ -84,7 +105,7 @@ export const Plugin = {
draft.namespace({
name: "opencode",
description:
"Tools for managing OpenCode itself, such as working with sessions, searching the available models, and reading MCP resources.",
"Tools for managing OpenCode itself, such as working with sessions and worktrees, searching the available models, and reading MCP resources.",
})
draft.add({
name: "session_rename",
@@ -131,6 +152,70 @@ export const Plugin = {
),
),
})
draft.add({
name: "worktree_create",
description: "Create a named worktree. Returns its directory.",
input: WorktreeCreateInput,
output: Worktree.Info,
options: { namespace: "opencode", codemode: true, pinned: true },
execute: (input) =>
ctx.worktree.create({ projectID: ctx.location.project.id, name: input.name }).pipe(
Effect.map((output) => ({ output, content: `Created worktree in ${output.directory}.` })),
Effect.mapError(
(error) => new ToolFailure({ message: `Unable to create worktree ${input.name}`, error }),
),
),
})
draft.add({
name: "worktree_list",
description: "List a repository's worktrees.",
input: Schema.Struct({}),
output: Schema.Struct({ worktrees: Worktree.List }),
options: { namespace: "opencode", codemode: true, pinned: true },
execute: () =>
ctx.worktree.list({ projectID: ctx.location.project.id }).pipe(
Effect.map((worktrees) => ({ output: { worktrees } })),
Effect.mapError((error) => new ToolFailure({ message: "Unable to list worktrees", error })),
),
})
draft.add({
name: "worktree_remove",
description:
"Remove a worktree. The repository location selects configuration; directory identifies the worktree to remove.",
input: WorktreeRemoveInput,
output: WorktreeRemoveOutput,
options: { namespace: "opencode", codemode: true, pinned: true, permission: "edit" },
execute: (input, context) =>
Effect.gen(function* () {
// Removing a worktree deletes files, so it requires the same approval as editing them.
const target = yield* access.resolve({ path: input.directory, kind: "directory" })
yield* permission.assert({
action: "edit",
resources: [target.resource],
save: ["*"],
sessionID: context.sessionID,
agent: context.agent,
source: { type: "tool", messageID: context.messageID, id: context.id },
})
yield* ctx.worktree
.remove({
projectID: ctx.location.project.id,
directory: target.absolute,
force: input.force ?? false,
})
.pipe(Effect.mapError((error) => new ToolFailure({ message: removeFailure(target.absolute, error) })))
return {
output: { directory: target.absolute, removed: true },
content: `Removed worktree ${target.absolute}.`,
}
}).pipe(
Effect.mapError((error) =>
error instanceof ToolFailure
? error
: new ToolFailure({ message: `Unable to remove worktree ${input.directory}`, error }),
),
),
})
draft.add({
name: "models",
description:
@@ -199,3 +284,16 @@ export const Plugin = {
.pipe(Effect.orDie)
}),
}
// Worktree errors carry no model-facing message, and Git's own text suggests forcing removal.
function removeFailure(directory: string, error: unknown) {
if (error instanceof Worktree.DirectoryUnavailableError)
return `Unable to remove worktree ${directory}: the directory does not exist or is not a directory.`
if (error instanceof Worktree.InvalidDirectoryError)
return `Unable to remove ${directory}: it is not a worktree of this project. Use worktree_list to see the project's worktrees.`
if (error instanceof Worktree.StrategyUnavailableError)
return `Unable to remove worktree ${directory}: its worktree strategy ${error.strategy} is not available.`
if ((error instanceof Git.WorktreeError || error instanceof Worktree.OperationError) && error.forceRequired)
return `Unable to remove worktree ${directory}: it has modified or untracked files.`
return `Unable to remove worktree ${directory}.`
}
+55 -48
View File
@@ -3,6 +3,8 @@ import { AISDK } from "@opencode/core/aisdk"
import { Command } from "@opencode/core/command"
import { Config } from "@opencode/core/config"
import { Credential } from "@opencode/core/credential"
import { Database } from "@opencode/core/database/database"
import { FileAccess } from "@opencode/core/file-access"
import { LayerNodePlatform } from "@opencode/util/effect/app-node-platform"
import { AppProcess } from "@opencode/util/process"
import { LayerNode } from "@opencode/util/effect/layer-node"
@@ -68,51 +70,56 @@ const permissionLayer = Layer.succeed(
}),
)
export const PluginTestLayer = AppNodeBuilder.build(
LayerNode.group([
AppProcess.node,
FileSystem.node,
FSUtil.node,
Location.node,
Npm.node,
Credential.node,
Config.node,
Bus.node,
Form.node,
Generate.node,
LayerNodePlatform.httpClient,
Plugin.node,
Agent.node,
AISDK.node,
Provider.node,
Model.node,
Command.node,
Integration.node,
KV.node,
ManagedPolicy.node,
Mcp.node,
Session.node,
PersistentPty.node,
LocationServiceMap.node,
Permission.node,
PluginHooks.node,
Reference.node,
Rpc.node,
Skill.node,
SkillDiscovery.node,
Tool.node,
Vcs.node,
Watcher.node,
WebSearch.node,
Worktree.node,
WorktreeStrategies.node,
]),
[
Location.node.replace(tempLocationLayer),
Npm.node.replace(npmLayer),
Config.node.replace(configLayer),
Mcp.node.replace(emptyMcpLayer),
Generate.node.replace(generateLayer),
Permission.node.replace(permissionLayer),
],
).pipe(Layer.provideMerge(configLayer))
export const makePluginTestLayer = (permission = permissionLayer) =>
AppNodeBuilder.build(
LayerNode.group([
AppProcess.node,
FileSystem.node,
FSUtil.node,
Location.node,
Npm.node,
Credential.node,
Config.node,
Database.node,
FileAccess.node,
Bus.node,
Form.node,
Generate.node,
LayerNodePlatform.httpClient,
Plugin.node,
Agent.node,
AISDK.node,
Provider.node,
Model.node,
Command.node,
Integration.node,
KV.node,
ManagedPolicy.node,
Mcp.node,
Session.node,
PersistentPty.node,
LocationServiceMap.node,
Permission.node,
PluginHooks.node,
Reference.node,
Rpc.node,
Skill.node,
SkillDiscovery.node,
Tool.node,
Vcs.node,
Watcher.node,
WebSearch.node,
Worktree.node,
WorktreeStrategies.node,
]),
[
Location.node.replace(tempLocationLayer),
Npm.node.replace(npmLayer),
Config.node.replace(configLayer),
Mcp.node.replace(emptyMcpLayer),
Generate.node.replace(generateLayer),
Permission.node.replace(permission),
],
).pipe(Layer.provideMerge(configLayer))
export const PluginTestLayer = makePluginTestLayer()
+125 -1
View File
@@ -1,16 +1,27 @@
import { expect } from "bun:test"
import fs from "fs/promises"
import path from "path"
import { Database } from "@opencode/core/database/database"
import { Location } from "@opencode/core/location"
import { Permission } from "@opencode/core/permission"
import { Plugin } from "@opencode/core/plugin"
import { PluginHost } from "@opencode/core/plugin/host"
import { ProjectTable } from "@opencode/core/project/sql"
import { Provider } from "@opencode/core/provider"
import { AbsolutePath } from "@opencode/core/schema"
import { Session } from "@opencode/core/session"
import { Tool } from "@opencode/core/tool"
import { OpenCodeTools } from "@opencode/core/tool/plugin/opencode"
import { WorktreeTable } from "@opencode/core/worktree/sql"
import { WorktreeStrategies } from "@opencode/core/worktree/strategies"
import { Model } from "@opencode/schema/model"
import { Effect } from "effect"
import { initRepo } from "./fixture/git"
import { tmpdirScoped } from "./fixture/tmpdir"
import { testEffect } from "./lib/effect"
import { permissionLayer } from "./lib/permission"
import { executeTool, toolIdentity } from "./lib/tool"
import { PluginTestLayer } from "./plugin/fixture"
import { makePluginTestLayer, PluginTestLayer } from "./plugin/fixture"
const it = testEffect(PluginTestLayer)
@@ -132,3 +143,116 @@ it.effect("groups available models by provider with paging", () =>
expect(yield* run({ provider: "other", query: "alpha" })).toEqual({ providers: [], total: 0, next: null })
}),
)
const approvals = { assertions: [] as Permission.AssertInput[], denyEdit: false }
const worktreeIt = testEffect(
makePluginTestLayer(
permissionLayer({
assert: (input) =>
Effect.sync(() => approvals.assertions.push(input)).pipe(
Effect.andThen(
approvals.denyEdit && input.action === "edit"
? Effect.fail(
new Permission.BlockedError({ rules: [], permission: input.action, resources: input.resources }),
)
: Effect.void,
),
),
}),
),
)
worktreeIt.live("creates, lists, and removes worktrees for the plugin's project", () =>
Effect.gen(function* () {
const plugins = yield* Plugin.Service
const sessions = yield* Session.Service
const location = yield* Location.Service
const strategies = yield* WorktreeStrategies.Service
const database = yield* Database.Service
const parent = yield* tmpdirScoped()
yield* Effect.promise(() => initRepo(location.directory))
yield* database.db
.insert(ProjectTable)
.values({
id: location.project.id,
worktree: location.directory,
sandboxes: [],
time_created: 1,
time_updated: 1,
})
.onConflictDoUpdate({ target: ProjectTable.id, set: { worktree: location.directory } })
.run()
.pipe(Effect.orDie)
yield* database.db
.insert(WorktreeTable)
.values({ project_id: location.project.id, directory: location.directory })
.onConflictDoNothing()
.run()
.pipe(Effect.orDie)
yield* strategies.transform((editor) => editor.configure({ directory: AbsolutePath.make(parent.path) }))
yield* OpenCodeTools.Plugin.effect(yield* PluginHost.make(plugins))
const session = yield* sessions.create({ location: Location.Ref.make({ directory: location.directory }) })
const registry = yield* Tool.Service
const call = (name: string, input: Record<string, unknown>) =>
executeTool(registry, {
sessionID: session.id,
...toolIdentity,
call: {
type: "tool-call",
id: `call-${name}-${JSON.stringify(input)}`,
name: "execute",
input: { code: `return await tools.opencode.${name}(${JSON.stringify(input)})` },
},
})
const run = (name: string, input: Record<string, unknown>) =>
call(name, input).pipe(
Effect.map((result) => JSON.parse(result.content?.[0]?.type === "text" ? result.content[0].text : "")),
)
const directory = path.join(parent.path, "task")
expect(yield* run("worktree_create", { name: " task " })).toEqual({ directory })
expect(yield* Effect.promise(() => fs.stat(directory).then((stat) => stat.isDirectory()))).toBe(true)
expect((yield* run("worktree_list", {})).worktrees).toContainEqual({ directory, strategy: "git" })
// The project checkout is not a removable worktree.
expect(yield* call("worktree_remove", { directory: location.directory })).toMatchObject({
content: [
{
type: "text",
text: `Unable to remove ${location.directory}: it is not a worktree of this project. Use worktree_list to see the project's worktrees.`,
},
],
metadata: { error: true },
})
expect(yield* Effect.promise(() => fs.stat(location.directory).then((stat) => stat.isDirectory()))).toBe(true)
// A dirty worktree is kept, and the failure leaves the choice to force removal to the model.
yield* Effect.promise(() => fs.writeFile(path.join(directory, "draft.txt"), "draft"))
expect(yield* call("worktree_remove", { directory })).toMatchObject({
content: [{ type: "text", text: `Unable to remove worktree ${directory}: it has modified or untracked files.` }],
})
expect(yield* Effect.promise(() => Bun.file(path.join(directory, "draft.txt")).exists())).toBe(true)
yield* Effect.promise(() => fs.rm(path.join(directory, "draft.txt")))
// Removal requires the same approval as editing files in the worktree.
approvals.assertions.length = 0
approvals.denyEdit = true
expect(yield* call("worktree_remove", { directory })).toMatchObject({ metadata: { error: true } })
expect(yield* Effect.promise(() => Bun.file(path.join(directory, ".git")).exists())).toBe(true)
approvals.denyEdit = false
// Relative paths resolve from the session's directory for both approval and removal.
expect(yield* run("worktree_remove", { directory: path.relative(location.directory, directory) })).toEqual({
directory,
removed: true,
})
expect(yield* Effect.promise(() => Bun.file(path.join(directory, ".git")).exists())).toBe(false)
// Permission resources always use forward slashes, including on Windows.
const resource = directory.replaceAll("\\", "/")
expect(approvals.assertions).toMatchObject([
{ action: "edit", resources: [resource], save: ["*"], sessionID: session.id },
{ action: "edit", resources: [resource], save: ["*"], sessionID: session.id },
])
expect((yield* run("worktree_list", {})).worktrees).not.toContainEqual({ directory, strategy: "git" })
}),
)
+19
View File
@@ -233,6 +233,25 @@ Rename this session to "Timeout cleanup", then move it to the new worktree.
These utilities do not request a built-in permission action.
### Worktrees
The same namespace manages worktrees for the session's project:
- `worktree_create` creates a worktree from a `name` and returns its
`directory`. The project's worktree configuration selects the destination and
strategy.
- `worktree_list` lists the project's worktrees.
- `worktree_remove` removes a worktree OpenCode recorded for the project. Set
`force` to discard uncommitted changes.
```text
Create a worktree named "login" and move this session into it.
```
`worktree_remove` uses the `edit` permission with the worktree directory as its
resource. The other worktree utilities do not request a built-in permission
action.
## Browser
The `browser` Code Mode namespace controls the browser attached by the OpenCode