Skip to content
Closed
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
3 changes: 2 additions & 1 deletion packages/opencode/src/session/prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { type Tool as AITool, tool, jsonSchema } from "ai"
import type { JSONSchema7 } from "@ai-sdk/provider"
import { SessionCompaction } from "./compaction"
import { SystemPrompt } from "./system"
import { Workdir } from "./workdir"
import { Instruction } from "./instruction"
import { Plugin } from "../plugin"
import { MAX_STEPS_PROMPT } from "@opencode-ai/core/session/runner/max-steps"
Expand Down Expand Up @@ -1730,7 +1731,7 @@ const layer = Layer.effect(

const [skills, env, instructions, mcpInstructions, toolOverview, delegation] = yield* Effect.all([
sys.skills(agent),
sys.environment(model),
sys.environment(model, Workdir.of(session)),
instruction.system().pipe(Effect.orDie),
sys.mcp(agent, session.permission),
catalog.overview(session.id),
Expand Down
20 changes: 17 additions & 3 deletions packages/opencode/src/session/system.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,13 @@ export function provider(model: Provider.Model) {
}

export interface Interface {
readonly environment: (model: Provider.Model) => Effect.Effect<string[]>
/**
* @param directory the session's file-tool working folder. When it differs
* from the instance/project directory, the prompt shows both and says that
* shell cwd still uses the project directory. The child still has to know
* which project its permissions are measured against.
*/
readonly environment: (model: Provider.Model, directory?: string) => Effect.Effect<string[]>
readonly skills: (agent: Agent.Info) => Effect.Effect<string | undefined>
readonly mcp: (agent: Agent.Info, permission?: PermissionV1.Ruleset) => Effect.Effect<string | undefined>
readonly delegation: (agent: Agent.Info, permission?: PermissionV1.Ruleset) => Effect.Effect<string | undefined>
Expand All @@ -89,8 +95,9 @@ const layer = Layer.effect(
const global = yield* Global.Service

return Service.of({
environment: Effect.fn("SystemPrompt.environment")(function* (model: Provider.Model) {
environment: Effect.fn("SystemPrompt.environment")(function* (model: Provider.Model, directory?: string) {
const ctx = yield* InstanceState.context
const cwd = directory ?? ctx.directory
const shell = Shell.name(Shell.acceptable((yield* config.get()).shell))
const references = yield* Effect.gen(function* () {
return (yield* (yield* Reference.Service).list()).filter((reference) => reference.description !== undefined)
Expand All @@ -100,7 +107,14 @@ const layer = Layer.effect(
`You are powered by the model named ${model.api.id}. The exact model ID is ${model.providerID}/${model.api.id}`,
`Here is some useful information about the environment you are running in:`,
`<env>`,
` Working directory: ${ctx.directory}`,
` Working directory: ${cwd}`,
...(cwd === ctx.directory
? []
: [
` Project directory: ${ctx.directory}`,
` File/search/edit tools use the working directory above.`,
` Shell commands run in the project directory by default; a relative shell workdir also resolves from the project directory. To run a shell command in the working directory above, pass its absolute path as shell workdir.`,
]),
` Desktop directory: ${global.desktop ?? "unavailable (do not infer a path)"}`,
` Workspace root folder: ${ctx.worktree}`,
` Is directory a git repo: ${ctx.project.vcs === "git" ? "yes" : "no"}`,
Expand Down
5 changes: 5 additions & 0 deletions packages/opencode/src/session/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { ProviderV2 } from "@opencode-ai/core/provider"
import { ModelV2 } from "@opencode-ai/core/model"
import { isRecord } from "@/util/record"
import { RuntimeFlags } from "@/effect/runtime-flags"
import { Workdir } from "./workdir"

const MCP_RESOURCE_TOOLS = {
list: "list_mcp_resources",
Expand Down Expand Up @@ -70,6 +71,10 @@ export const resolve = Effect.fn("SessionTools.resolve")(function* (input: {

const context = (args: Record<string, unknown>, options: ToolExecutionOptions): Tool.Context => ({
sessionID: input.session.id,
// The folder this session works in, which is the project directory unless a
// delegated child was given one. It resolves paths only; permission checks
// keep measuring against the instance through `external-directory`.
cwd: Workdir.of(input.session),
abort: options.abortSignal!,
messageID: input.processor.message.id,
callID: options.toolCallId,
Expand Down
124 changes: 124 additions & 0 deletions packages/opencode/src/session/workdir.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import os from "os"
import path from "path"
import { Effect } from "effect"
import { FSUtil } from "@opencode-ai/core/fs-util"

/**
* The working folder a session resolves its paths from.
*
* A folder is a resolution base, never a permission boundary. The instance the
* session runs in stays the anchor every `external_directory` decision is
* measured against, so choosing a folder outside the project - which a user may
* legitimately do to reach a home directory or a sibling project - grants no
* access to it: reaching those paths still asks the permissions that already
* gate them. Inherited rulesets are untouched as well, so a nested child cannot
* escape its ancestor's denies by choosing a folder of its own.
*
* Both the inherited and the requested folder end up canonical here: a selection
* that reaches its target through a symlink or junction is stored as the real
* directory, so an external tree can never be read as if it were internal.
*/

// Stored on the session row instead of in a new column: the selection is part of
// the same per-session record as the effort level, so it survives a restart and
// a resume without a migration.
const Key = "workdir"

export function read(metadata: Record<string, unknown> | undefined) {
const value = metadata?.[Key]
return typeof value === "string" && value.length > 0 ? value : undefined
}

export function select(metadata: Record<string, unknown> | undefined, directory: string) {
return { ...metadata, [Key]: directory }
}

/** The folder this session works in: its own selection, else the folder it was created in. */
export function of(session: { metadata?: Record<string, unknown>; directory: string }) {
return read(session.metadata) ?? session.directory
}

/** The platform whose path rules decide what a request means. */
export type Platform = NodeJS.Platform

/**
* Windows compares paths case-insensitively, so the same folder respelled with
* different case is still the same folder and a resume may keep it. Every other
* platform compares them exactly, where a case difference names a different
* folder (or no folder at all) and the resume is refused.
*/
export function same(a: string, b: string, platform: Platform = process.platform) {
return platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b
}

// The user's home shorthand, and only that: `$HOME` and deeper shell expansion
// stay in the shell, where quoting decides what the caller meant.
const Home = /^~(?=$|[\\/])/

export function expand(directory: string, home: string = os.homedir()) {
return Home.test(directory) ? home + directory.slice(1) : directory
}

/**
* What a request names, in the terms the platform decides with.
*
* `absolute` names its own target, including a Windows UNC path
* (`\\server\share\folder`), which is why those can be used as they are.
* `relative` is resolved from the session's folder. `process-relative` names a
* location that depends on state nobody asked about - `C:folder` follows that
* drive's current directory and `\folder` follows the process's current drive -
* so it is refused rather than silently resolved from somewhere else.
*
* The platform is a parameter so both rule sets can be exercised on either
* runner: the Linux leg proves the Windows spellings without a Windows machine,
* and the Windows leg still proves the real thing.
*/
export type Spelling = "absolute" | "relative" | "process-relative"

export function classify(requested: string, platform: Platform = process.platform): Spelling {
if (platform !== "win32") return path.posix.isAbsolute(requested) ? "absolute" : "relative"
if (/^[A-Za-z]:(?![\\/])/.test(requested)) return "process-relative"
if (/^[\\/](?![\\/])/.test(requested)) return "process-relative"
return path.win32.isAbsolute(requested) ? "absolute" : "relative"
}

/**
* Resolve a requested working folder against the folder its caller already works
* in, and canonicalize it. Existence and directory-ness are checked here so a
* child can never be pointed at a folder it would fail to open on every call.
*/
export const resolve = Effect.fn("Workdir.resolve")(function* (input: {
fs: FSUtil.Interface
requested: string
base: string
}) {
const requested = expand(input.requested)
if (requested.length === 0) {
return yield* Effect.fail(new Error("The working folder cannot be empty."))
}
// `C:folder` is relative to that drive's own current directory and `\folder`
// is rooted on the process's current drive; neither names a folder the caller
// asked for, so resolving either against the session's folder would land
// somewhere nobody asked for.
const spelling = classify(requested)
if (spelling === "process-relative") {
return yield* Effect.fail(new Error(`The working folder must be an absolute path: ${requested}`))
}
const target = spelling === "absolute" ? requested : path.resolve(input.base, requested)
const directory = yield* Effect.try({
try: () => FSUtil.resolve(target),
catch: (error) =>
new Error(
`Cannot resolve the working folder ${requested}: ${error instanceof Error ? error.message : String(error)}`,
),
})
if (!(yield* input.fs.existsSafe(directory))) {
return yield* Effect.fail(new Error(`The working folder does not exist: ${directory}`))
}
if (!(yield* input.fs.isDir(directory))) {
return yield* Effect.fail(new Error(`The working folder is not a directory: ${directory}`))
}
return directory
})

export * as Workdir from "./workdir"
7 changes: 5 additions & 2 deletions packages/opencode/src/tool/apply_patch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ export const ApplyPatchTool = Tool.define(
}

const instance = yield* InstanceState.context
// Relative patch paths resolve from the session's working folder, which is
// the project directory unless a delegated child was given another one.
const cwd = ctx.cwd ?? instance.directory

// Validate file paths and check permissions
const fileChanges: Array<{
Expand All @@ -70,7 +73,7 @@ export const ApplyPatchTool = Tool.define(
let totalDiff = ""

for (const hunk of hunks) {
const filePath = path.resolve(instance.directory, hunk.path)
const filePath = path.resolve(cwd, hunk.path)
yield* assertExternalDirectoryEffect(ctx, filePath)

switch (hunk.type) {
Expand Down Expand Up @@ -139,7 +142,7 @@ export const ApplyPatchTool = Tool.define(
if (change.removed) deletions += change.count || 0
}

const movePath = hunk.move_path ? path.resolve(instance.directory, hunk.move_path) : undefined
const movePath = hunk.move_path ? path.resolve(cwd, hunk.move_path) : undefined
yield* assertExternalDirectoryEffect(ctx, movePath)

fileChanges.push({
Expand Down
4 changes: 3 additions & 1 deletion packages/opencode/src/tool/edit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,11 @@ export const EditTool = Tool.define(
}

const instance = yield* InstanceState.context
// Relative paths resolve from the session's working folder, which is the
// project directory unless a delegated child was given another one.
const filePath = path.isAbsolute(params.filePath)
? params.filePath
: path.join(instance.directory, params.filePath)
: path.join(ctx.cwd ?? instance.directory, params.filePath)
yield* assertExternalDirectoryEffect(ctx, filePath)

let diff = ""
Expand Down
8 changes: 6 additions & 2 deletions packages/opencode/src/tool/glob.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,12 @@ export const GlobTool = Tool.define(
},
})

let search = params.path ?? ins.directory
search = path.isAbsolute(search) ? search : path.resolve(ins.directory, search)
// The default search root is the session's working folder, which is the
// project directory unless a delegated child was given another one. The
// external check below still measures against the instance.
const cwd = ctx.cwd ?? ins.directory
let search = params.path ?? cwd
search = path.isAbsolute(search) ? search : path.resolve(cwd, search)
const info = yield* fs.stat(search).pipe(Effect.catch(() => Effect.succeed(undefined)))
if (info?.type === "File") {
throw new Error(`glob path must be a directory: ${search}`)
Expand Down
10 changes: 7 additions & 3 deletions packages/opencode/src/tool/grep.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,13 @@ export const GrepTool = Tool.define(
})

const ins = yield* InstanceState.context
const requested = path.isAbsolute(params.path ?? ins.directory)
? (params.path ?? ins.directory)
: path.join(ins.directory, params.path ?? ".")
// The default search root is the session's working folder, which is the
// project directory unless a delegated child was given another one. The
// external check below still measures against the instance.
const base = ctx.cwd ?? ins.directory
const requested = path.isAbsolute(params.path ?? base)
? (params.path ?? base)
: path.join(base, params.path ?? ".")
const requestedInfo = yield* fs.stat(requested).pipe(Effect.catch(() => Effect.succeed(undefined)))
yield* assertExternalDirectoryEffect(ctx, requested, {
bypass: false,
Expand Down
7 changes: 5 additions & 2 deletions packages/opencode/src/tool/read.ts
Original file line number Diff line number Diff line change
Expand Up @@ -247,9 +247,12 @@ export const ReadTool = Tool.define<
() => Effect.succeed(undefined),
),
)
// Relative paths resolve from the session's working folder, which is the
// project directory unless a delegated child was given another one.
const cwd = ctx.cwd ?? instance.directory
let filepath = params.filePath
if (!path.isAbsolute(filepath)) {
filepath = path.resolve(instance.directory, filepath)
filepath = path.resolve(cwd, filepath)
}
if (process.platform === "win32") {
filepath = FSUtil.normalizePath(filepath)
Expand All @@ -267,7 +270,7 @@ export const ReadTool = Tool.define<
if (pipeAt > 0) {
const candidate = unquote(params.filePath.slice(0, pipeAt).trim())
if (candidate) {
const resolved = path.isAbsolute(candidate) ? candidate : path.resolve(instance.directory, candidate)
const resolved = path.isAbsolute(candidate) ? candidate : path.resolve(cwd, candidate)
const normalized = process.platform === "win32" ? FSUtil.normalizePath(resolved) : resolved
const piped = yield* statOrUndefined(normalized)
if (piped) {
Expand Down
44 changes: 44 additions & 0 deletions packages/opencode/src/tool/task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ import { Database } from "@opencode-ai/core/database/database"
import { AgentEffort } from "@opencode-ai/schema/agent-effort"
import { NotFoundError } from "@/storage/storage"
import { Permission } from "@/permission"
import { Workdir } from "@/session/workdir"
import { FSUtil } from "@opencode-ai/core/fs-util"
import type { PermissionV1 } from "@opencode-ai/core/v1/permission"

export interface TaskPromptOps {
Expand Down Expand Up @@ -115,6 +117,10 @@ const BaseParameterFields = {
task_id: Schema.optional(Schema.String).annotate({
description: "Resume a previous subagent session by its task_id",
}),
directory: Schema.optional(Schema.String).annotate({
description:
"Working folder for the child's file/search/edit tools; their relative paths resolve from it. Omit to inherit this session's folder. Shell commands still default to the project directory; use an absolute shell workdir for the child's folder. A resumed task keeps the folder it was created with. Choosing a folder is not an authorization: paths outside the project still ask the usual permissions.",
}),
command: Schema.optional(Schema.String).annotate({ description: "Triggering command" }),
}

Expand Down Expand Up @@ -216,6 +222,7 @@ export const TaskTool = Tool.define(
receipts.set(background, receipted)
const config = yield* Config.Service
const sessions = yield* Session.Service
const fs = yield* FSUtil.Service
const scope = yield* Scope.Scope
const database = yield* Database.Service
const events = yield* EventV2Bridge.Service
Expand Down Expand Up @@ -427,6 +434,40 @@ export const TaskTool = Tool.define(
(session.parentID !== ctx.sessionID || session.agent !== next.name)
)
return yield* Effect.fail(new Error("Workflow stages cannot reuse a child owned by another session."))
// The folder this dispatch works in. A relative request resolves from the
// folder the caller already works in, so it means the same thing whether the
// caller is the project session or a child that was given a folder of its
// own. Canonicalizing here is what keeps the external boundary honest: a
// folder reached through a symlink is recorded as its real target, so an
// external tree can never be selected under an internal-looking name.
//
// Selection is not authorization. Nothing below adds an allow rule, and the
// instance this session runs in stays the anchor every `external_directory`
// decision is measured against, so this folder - and the paths under it when
// it sits outside the project - is reached through the permissions that
// already gate them.
const parentDirectory = Workdir.of(parent)
const requestedDirectory =
params.directory === undefined
? undefined
: yield* Workdir.resolve({ fs, requested: params.directory, base: parentDirectory })
// A session's folder is fixed when it is created. Resume keeps the recorded
// selection - or, for a session created before folders were selectable, the
// project directory it was created in - so a resumed child cannot silently
// start resolving its paths somewhere its earlier work never happened.
const recordedDirectory = session ? Workdir.of(session) : undefined
if (
recordedDirectory !== undefined &&
requestedDirectory !== undefined &&
!Workdir.same(recordedDirectory, requestedDirectory)
)
return yield* Effect.fail(
new Error(
`Task ${session!.id} already works in ${recordedDirectory}. A resumed task keeps its working folder; start a new task to work in ${requestedDirectory}.`,
),
)
const workdir = recordedDirectory ?? requestedDirectory ?? parentDirectory

const childPermission = deriveSubagentSessionPermission({
parentSessionPermission: parent.permission ?? [],
subagent: next,
Expand All @@ -441,6 +482,9 @@ export const TaskTool = Tool.define(
parentID: ctx.sessionID,
title: params.description + ` (@${next.name} subagent)`,
agent: next.name,
// Recorded once, at creation, so the foreground run, the background run
// and every later resume resolve from the same folder.
metadata: Workdir.select(undefined, workdir),
permission: [
...childPermission,
...childToolDenies.filter(
Expand Down
Loading
Loading