Skip to content

Commit 668d77b

Browse files
authored
refactor(tool): yield InstanceState context (anomalyco#25199)
1 parent 5c2e06f commit 668d77b

8 files changed

Lines changed: 51 additions & 36 deletions

File tree

‎packages/opencode/src/session/prompt.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,8 @@ export const layer = Layer.effect(
256256

257257
const assistantMessage = input.messages.findLast((msg) => msg.info.role === "assistant")
258258
if (input.agent.name !== "plan" && assistantMessage?.info.agent === "plan") {
259-
const plan = Session.plan(input.session)
259+
const ctx = yield* InstanceState.context
260+
const plan = Session.plan(input.session, ctx)
260261
if (!(yield* fsys.existsSafe(plan))) return input.messages
261262
const part = yield* sessions.updatePart({
262263
id: PartID.ascending(),
@@ -272,7 +273,8 @@ export const layer = Layer.effect(
272273

273274
if (input.agent.name !== "plan" || assistantMessage?.info.agent === "plan") return input.messages
274275

275-
const plan = Session.plan(input.session)
276+
const ctx = yield* InstanceState.context
277+
const plan = Session.plan(input.session, ctx)
276278
const exists = yield* fsys.existsSafe(plan)
277279
if (!exists) yield* fsys.ensureDir(path.dirname(plan)).pipe(Effect.catch(Effect.die))
278280
const part = yield* sessions.updatePart({

‎packages/opencode/src/session/session.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ import { ProjectTable } from "../project/project.sql"
2626
import { Storage } from "@/storage/storage"
2727
import * as Log from "@opencode-ai/core/util/log"
2828
import { MessageV2 } from "./message-v2"
29-
import { Instance } from "../project/instance"
29+
import { Instance, type InstanceContext } from "../project/instance"
3030
import { InstanceState } from "@/effect/instance-state"
3131
import { Snapshot } from "@/snapshot"
3232
import { ProjectID } from "../project/schema"
@@ -311,9 +311,9 @@ export const Event = {
311311
),
312312
}
313313

314-
export function plan(input: { slug: string; time: { created: number } }) {
315-
const base = Instance.project.vcs
316-
? path.join(Instance.worktree, ".opencode", "plans")
314+
export function plan(input: { slug: string; time: { created: number } }, instance: InstanceContext) {
315+
const base = instance.project.vcs
316+
? path.join(instance.worktree, ".opencode", "plans")
317317
: path.join(Global.Path.data, "plans")
318318
return path.join(base, [input.time.created, input.slug].join("-") + ".md")
319319
}

‎packages/opencode/src/tool/apply_patch.ts‎

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { Effect, Schema } from "effect"
33
import * as Tool from "./tool"
44
import { Bus } from "../bus"
55
import { FileWatcher } from "../file/watcher"
6-
import { Instance } from "../project/instance"
6+
import { InstanceState } from "@/effect/instance-state"
77
import { Patch } from "../patch"
88
import { createTwoFilesPatch, diffLines } from "diff"
99
import { assertExternalDirectoryEffect } from "./external-directory"
@@ -52,6 +52,8 @@ export const ApplyPatchTool = Tool.define(
5252
return yield* Effect.fail(new Error("apply_patch verification failed: no hunks found"))
5353
}
5454

55+
const instance = yield* InstanceState.context
56+
5557
// Validate file paths and check permissions
5658
const fileChanges: Array<{
5759
filePath: string
@@ -68,7 +70,7 @@ export const ApplyPatchTool = Tool.define(
6870
let totalDiff = ""
6971

7072
for (const hunk of hunks) {
71-
const filePath = path.resolve(Instance.directory, hunk.path)
73+
const filePath = path.resolve(instance.directory, hunk.path)
7274
yield* assertExternalDirectoryEffect(ctx, filePath)
7375

7476
switch (hunk.type) {
@@ -133,7 +135,7 @@ export const ApplyPatchTool = Tool.define(
133135
if (change.removed) deletions += change.count || 0
134136
}
135137

136-
const movePath = hunk.move_path ? path.resolve(Instance.directory, hunk.move_path) : undefined
138+
const movePath = hunk.move_path ? path.resolve(instance.directory, hunk.move_path) : undefined
137139
yield* assertExternalDirectoryEffect(ctx, movePath)
138140

139141
fileChanges.push({
@@ -187,7 +189,7 @@ export const ApplyPatchTool = Tool.define(
187189
// Build per-file metadata for UI rendering (used for both permission and result)
188190
const files = fileChanges.map((change) => ({
189191
filePath: change.filePath,
190-
relativePath: path.relative(Instance.worktree, change.movePath ?? change.filePath).replaceAll("\\", "/"),
192+
relativePath: path.relative(instance.worktree, change.movePath ?? change.filePath).replaceAll("\\", "/"),
191193
type: change.type,
192194
patch: change.diff,
193195
additions: change.additions,
@@ -196,7 +198,7 @@ export const ApplyPatchTool = Tool.define(
196198
}))
197199

198200
// Check permissions if needed
199-
const relativePaths = fileChanges.map((c) => path.relative(Instance.worktree, c.filePath).replaceAll("\\", "/"))
201+
const relativePaths = fileChanges.map((c) => path.relative(instance.worktree, c.filePath).replaceAll("\\", "/"))
200202
yield* ctx.ask({
201203
permission: "edit",
202204
patterns: relativePaths,
@@ -267,13 +269,13 @@ export const ApplyPatchTool = Tool.define(
267269
// Generate output summary
268270
const summaryLines = fileChanges.map((change) => {
269271
if (change.type === "add") {
270-
return `A ${path.relative(Instance.worktree, change.filePath).replaceAll("\\", "/")}`
272+
return `A ${path.relative(instance.worktree, change.filePath).replaceAll("\\", "/")}`
271273
}
272274
if (change.type === "delete") {
273-
return `D ${path.relative(Instance.worktree, change.filePath).replaceAll("\\", "/")}`
275+
return `D ${path.relative(instance.worktree, change.filePath).replaceAll("\\", "/")}`
274276
}
275277
const target = change.movePath ?? change.filePath
276-
return `M ${path.relative(Instance.worktree, target).replaceAll("\\", "/")}`
278+
return `M ${path.relative(instance.worktree, target).replaceAll("\\", "/")}`
277279
})
278280
let output = `Success. Updated the following files:\n${summaryLines.join("\n")}`
279281

@@ -282,7 +284,7 @@ export const ApplyPatchTool = Tool.define(
282284
const target = change.movePath ?? change.filePath
283285
const block = LSP.Diagnostic.report(target, diagnostics[AppFileSystem.normalizePath(target)] ?? [])
284286
if (!block) continue
285-
const rel = path.relative(Instance.worktree, target).replaceAll("\\", "/")
287+
const rel = path.relative(instance.worktree, target).replaceAll("\\", "/")
286288
output += `\n\nLSP errors detected in ${rel}, please fix:\n${block}`
287289
}
288290

‎packages/opencode/src/tool/bash.ts‎

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import * as Tool from "./tool"
66
import path from "path"
77
import DESCRIPTION from "./bash.txt"
88
import * as Log from "@opencode-ai/core/util/log"
9-
import { Instance } from "../project/instance"
9+
import { Instance, type InstanceContext } from "../project/instance"
1010
import { lazy } from "@/util/lazy"
1111
import { Language, type Node } from "web-tree-sitter"
1212

@@ -363,7 +363,13 @@ export const BashTool = Tool.define(
363363
return yield* resolvePath(next, cwd, shell)
364364
})
365365

366-
const collect = Effect.fn("BashTool.collect")(function* (root: Node, cwd: string, ps: boolean, shell: string) {
366+
const collect = Effect.fn("BashTool.collect")(function* (
367+
root: Node,
368+
cwd: string,
369+
ps: boolean,
370+
shell: string,
371+
instance: InstanceContext,
372+
) {
367373
const scan: Scan = {
368374
dirs: new Set<string>(),
369375
patterns: new Set<string>(),
@@ -379,7 +385,7 @@ export const BashTool = Tool.define(
379385
for (const arg of pathArgs(command, ps)) {
380386
const resolved = yield* argPath(arg, cwd, ps, shell)
381387
log.info("resolved path", { arg, resolved })
382-
if (!resolved || Instance.containsPath(resolved)) continue
388+
if (!resolved || Instance.containsPath(resolved, instance)) continue
383389
const dir = (yield* fs.isDir(resolved)) ? resolved : path.dirname(resolved)
384390
scan.dirs.add(dir)
385391
}
@@ -589,9 +595,10 @@ export const BashTool = Tool.define(
589595
parameters: Parameters,
590596
execute: (params: Schema.Schema.Type<typeof Parameters>, ctx: Tool.Context) =>
591597
Effect.gen(function* () {
598+
const executeInstance = yield* InstanceState.context
592599
const cwd = params.workdir
593-
? yield* resolvePath(params.workdir, Instance.directory, shell)
594-
: Instance.directory
600+
? yield* resolvePath(params.workdir, executeInstance.directory, shell)
601+
: executeInstance.directory
595602
if (params.timeout !== undefined && params.timeout < 0) {
596603
throw new Error(`Invalid timeout value: ${params.timeout}. Timeout must be a positive number.`)
597604
}
@@ -602,8 +609,8 @@ export const BashTool = Tool.define(
602609
const tree = yield* Effect.acquireRelease(parse(params.command, ps), (tree) =>
603610
Effect.sync(() => tree.delete()),
604611
)
605-
const scan = yield* collect(tree.rootNode, cwd, ps, shell)
606-
if (!Instance.containsPath(cwd)) scan.dirs.add(cwd)
612+
const scan = yield* collect(tree.rootNode, cwd, ps, shell, executeInstance)
613+
if (!Instance.containsPath(cwd, executeInstance)) scan.dirs.add(cwd)
607614
yield* ask(ctx, scan)
608615
}),
609616
)

‎packages/opencode/src/tool/edit.ts‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import { File } from "../file"
1313
import { FileWatcher } from "../file/watcher"
1414
import { Bus } from "../bus"
1515
import { Format } from "../format"
16-
import { Instance } from "../project/instance"
16+
import { InstanceState } from "@/effect/instance-state"
1717
import { Snapshot } from "@/snapshot"
1818
import { assertExternalDirectoryEffect } from "./external-directory"
1919
import { AppFileSystem } from "@opencode-ai/core/filesystem"
@@ -76,9 +76,10 @@ export const EditTool = Tool.define(
7676
throw new Error("No changes to apply: oldString and newString are identical.")
7777
}
7878

79+
const instance = yield* InstanceState.context
7980
const filePath = path.isAbsolute(params.filePath)
8081
? params.filePath
81-
: path.join(Instance.directory, params.filePath)
82+
: path.join(instance.directory, params.filePath)
8283
yield* assertExternalDirectoryEffect(ctx, filePath)
8384

8485
let diff = ""
@@ -96,7 +97,7 @@ export const EditTool = Tool.define(
9697
diff = trimDiff(createTwoFilesPatch(filePath, filePath, contentOld, contentNew))
9798
yield* ctx.ask({
9899
permission: "edit",
99-
patterns: [path.relative(Instance.worktree, filePath)],
100+
patterns: [path.relative(instance.worktree, filePath)],
100101
always: ["*"],
101102
metadata: {
102103
filepath: filePath,
@@ -139,7 +140,7 @@ export const EditTool = Tool.define(
139140
)
140141
yield* ctx.ask({
141142
permission: "edit",
142-
patterns: [path.relative(Instance.worktree, filePath)],
143+
patterns: [path.relative(instance.worktree, filePath)],
143144
always: ["*"],
144145
metadata: {
145146
filepath: filePath,
@@ -201,7 +202,7 @@ export const EditTool = Tool.define(
201202
diff,
202203
filediff,
203204
},
204-
title: `${path.relative(Instance.worktree, filePath)}`,
205+
title: `${path.relative(instance.worktree, filePath)}`,
205206
output,
206207
}
207208
}),

‎packages/opencode/src/tool/lsp.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import * as Tool from "./tool"
33
import path from "path"
44
import { LSP } from "@/lsp/lsp"
55
import DESCRIPTION from "./lsp.txt"
6-
import { Instance } from "../project/instance"
6+
import { InstanceState } from "@/effect/instance-state"
77
import { pathToFileURL } from "url"
88
import { assertExternalDirectoryEffect } from "./external-directory"
99
import { AppFileSystem } from "@opencode-ai/core/filesystem"
@@ -44,7 +44,8 @@ export const LspTool = Tool.define(
4444
parameters: Parameters,
4545
execute: (args: Schema.Schema.Type<typeof Parameters>, ctx: Tool.Context) =>
4646
Effect.gen(function* () {
47-
const file = path.isAbsolute(args.filePath) ? args.filePath : path.join(Instance.directory, args.filePath)
47+
const instance = yield* InstanceState.context
48+
const file = path.isAbsolute(args.filePath) ? args.filePath : path.join(instance.directory, args.filePath)
4849
yield* assertExternalDirectoryEffect(ctx, file)
4950
const meta =
5051
args.operation === "workspaceSymbol"
@@ -61,7 +62,7 @@ export const LspTool = Tool.define(
6162

6263
const uri = pathToFileURL(file).href
6364
const position = { file, line: args.line - 1, character: args.character - 1 }
64-
const relPath = path.relative(Instance.worktree, file)
65+
const relPath = path.relative(instance.worktree, file)
6566
const detail =
6667
args.operation === "workspaceSymbol"
6768
? ""

‎packages/opencode/src/tool/plan.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { Question } from "../question"
55
import { Session } from "@/session/session"
66
import { MessageV2 } from "../session/message-v2"
77
import { Provider } from "@/provider/provider"
8-
import { Instance } from "../project/instance"
8+
import { InstanceState } from "@/effect/instance-state"
99
import { type SessionID, MessageID, PartID } from "../session/schema"
1010
import EXIT_DESCRIPTION from "./plan-exit.txt"
1111

@@ -30,8 +30,9 @@ export const PlanExitTool = Tool.define(
3030
parameters: Parameters,
3131
execute: (_params: {}, ctx: Tool.Context) =>
3232
Effect.gen(function* () {
33+
const instance = yield* InstanceState.context
3334
const info = yield* session.get(ctx.sessionID)
34-
const plan = path.relative(Instance.worktree, Session.plan(info))
35+
const plan = path.relative(instance.worktree, Session.plan(info, instance))
3536
const answers = yield* question.ask({
3637
sessionID: ctx.sessionID,
3738
questions: [

‎packages/opencode/src/tool/write.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import { File } from "../file"
1010
import { FileWatcher } from "../file/watcher"
1111
import { Format } from "../format"
1212
import { AppFileSystem } from "@opencode-ai/core/filesystem"
13-
import { Instance } from "../project/instance"
13+
import { InstanceState } from "@/effect/instance-state"
1414
import { trimDiff } from "./edit"
1515
import { assertExternalDirectoryEffect } from "./external-directory"
1616
import * as Bom from "@/util/bom"
@@ -37,9 +37,10 @@ export const WriteTool = Tool.define(
3737
parameters: Parameters,
3838
execute: (params: { content: string; filePath: string }, ctx: Tool.Context) =>
3939
Effect.gen(function* () {
40+
const instance = yield* InstanceState.context
4041
const filepath = path.isAbsolute(params.filePath)
4142
? params.filePath
42-
: path.join(Instance.directory, params.filePath)
43+
: path.join(instance.directory, params.filePath)
4344
yield* assertExternalDirectoryEffect(ctx, filepath)
4445

4546
const exists = yield* fs.existsSafe(filepath)
@@ -52,7 +53,7 @@ export const WriteTool = Tool.define(
5253
const diff = trimDiff(createTwoFilesPatch(filepath, filepath, contentOld, contentNew))
5354
yield* ctx.ask({
5455
permission: "edit",
55-
patterns: [path.relative(Instance.worktree, filepath)],
56+
patterns: [path.relative(instance.worktree, filepath)],
5657
always: ["*"],
5758
metadata: {
5859
filepath,
@@ -89,7 +90,7 @@ export const WriteTool = Tool.define(
8990
}
9091

9192
return {
92-
title: path.relative(Instance.worktree, filepath),
93+
title: path.relative(instance.worktree, filepath),
9394
metadata: {
9495
diagnostics,
9596
filepath,

0 commit comments

Comments
 (0)