From a32c55976de42cdbf544f5dad20727156e653870 Mon Sep 17 00:00:00 2001 From: Aiden Cline Date: Tue, 17 Nov 2026 10:58:09 -0600 Subject: [PATCH 1/4] feat(core): add Node's path to Code Mode behind full_codemode --- packages/core/src/codemode/path.ts | 30 +++++++++++ packages/core/src/codemode/tool.ts | 72 +++++++++++++++++-------- packages/core/src/session/context.ts | 7 ++- packages/core/src/tool.ts | 12 +++-- packages/core/test/tool-execute.test.ts | 46 ++++++++++++++++ 5 files changed, 140 insertions(+), 27 deletions(-) create mode 100644 packages/core/src/codemode/path.ts diff --git a/packages/core/src/codemode/path.ts b/packages/core/src/codemode/path.ts new file mode 100644 index 000000000000..233b79288d5f --- /dev/null +++ b/packages/core/src/codemode/path.ts @@ -0,0 +1,30 @@ +export * as CodeModePath from "./path.js" + +import { Extension } from "@opencode/codemode" +import { Effect } from "effect" +import path from "path" +import { Location } from "../location.js" + +// Only functions and separators cross; `posix` and `win32` point back at their module, which a global can't hold, so +// each becomes a copy of its own functions. Programs have no `process.cwd()`: resolve and relative start from the +// session's directory. +const flavor = (module: path.PlatformPath) => { + const { posix: _posix, win32: _win32, ...functions } = module + return { + ...functions, + resolve: (...parts: Array) => + Location.Service.use((location) => Effect.succeed(module.resolve(location.directory, ...parts))), + relative: (from: string, to: string) => + Location.Service.use((location) => + Effect.succeed( + module.relative(module.resolve(location.directory, from), module.resolve(location.directory, to)), + ), + ), + } +} + +/** The host's own path module, as Node gives it, with `path.posix` and `path.win32`. */ +export const extension = Extension.make({ + name: "path", + globals: { path: { ...flavor(path), posix: flavor(path.posix), win32: flavor(path.win32) } }, +}) diff --git a/packages/core/src/codemode/tool.ts b/packages/core/src/codemode/tool.ts index 8c757a7c3601..b7a0ae593d36 100644 --- a/packages/core/src/codemode/tool.ts +++ b/packages/core/src/codemode/tool.ts @@ -16,10 +16,12 @@ import { CallID } from "@opencode/schema/tool" import { Clock, Context, Effect, Ref, Schema, Scope, Semaphore } from "effect" import { toSessionError } from "../session/to-session-error.js" import { definition, normalizedName } from "../tool/runtime.js" +import { Location } from "../location.js" import { Permission } from "../permission.js" import { CodeModeCatalog } from "./catalog.js" import { CodeModeExecution } from "./execution.js" import { CodeModeFetch } from "./fetch.js" +import { CodeModePath } from "./path.js" const ExecuteFile = Schema.Struct({ data: Schema.String, @@ -74,24 +76,29 @@ export type Inventory = { } // Invariant model-facing guidance; the changing tool catalog is delivered through Instructions. -const description = [ - "Run JavaScript in a confined Code Mode runtime to script tool calls and HTTP requests and compose their results.", - "Write plain JavaScript and send it exactly as written: no code fence, and no JSON or other wrapper around it.", - "`fetch` is available for HTTP requests. Imports, direct filesystem access, and timers are unavailable: there is no `setTimeout` or sleep. All other external access goes through `tools`.", - "Inside `execute`, the only callable tools are those explicitly listed in the Code Mode catalog instructions or returned by the `search` function. Ignore tools shown outside the Code Mode catalog. They are not available in the Code Mode runtime.", - 'Call tools through `tools` using only exact paths and signatures from the catalog. Do not infer or normalize tool names; preserve bracket notation such as `tools.["tool-name"](input)`.', - "Prefer an explicit `return`; if omitted, the final top-level expression becomes the result.", - "Await every call whose completion matters; pending calls are interrupted when execution ends. Run independent calls concurrently with `Promise.allSettled`.", -].join("\n") +const description = (path: boolean) => + [ + "Run JavaScript in a confined Code Mode runtime to script tool calls and HTTP requests and compose their results.", + "Write plain JavaScript and send it exactly as written: no code fence, and no JSON or other wrapper around it.", + path + ? "`fetch` is available for HTTP requests, and Node's `path` (also importable as `node:path`), whose `resolve` starts from the session directory. Other imports, direct filesystem access, and timers are unavailable: there is no `setTimeout` or sleep. All other external access goes through `tools`." + : "`fetch` is available for HTTP requests. Imports, direct filesystem access, and timers are unavailable: there is no `setTimeout` or sleep. All other external access goes through `tools`.", + "Inside `execute`, the only callable tools are those explicitly listed in the Code Mode catalog instructions or returned by the `search` function. Ignore tools shown outside the Code Mode catalog. They are not available in the Code Mode runtime.", + 'Call tools through `tools` using only exact paths and signatures from the catalog. Do not infer or normalize tool names; preserve bracket notation such as `tools.["tool-name"](input)`.', + "Prefer an explicit `return`; if omitted, the final top-level expression becomes the result.", + "Await every call whose completion matters; pending calls are interrupted when execution ends. Run independent calls concurrently with `Promise.allSettled`.", + ].join("\n") export const create = ( inventory: Inventory, executeTool: (name: string, tool: Info, input: unknown, context: ToolContext) => Effect.Effect, permission: Permission.Interface, + /** The session's Location, which turns on the experimental `path` global. */ + location?: Location.Interface, ) => { return { name: "execute", - description, + description: description(location !== undefined), input: CodeMode.Input, freeform: { type: "text" }, output: ExecuteOutput, @@ -122,9 +129,10 @@ export const create = ( yield* Effect.sleep(wait).pipe(Effect.andThen(lock.withPermit(publish)), Effect.forkIn(scope)) }), ) - const result = yield* runtime(inventory) - .execute(code) - .pipe( + const program = location + ? pathRuntime(inventory).execute(code).pipe(Effect.provideService(Location.Service, location)) + : runtime(inventory).execute(code) + const result = yield* program.pipe( Effect.provideService(Run, { executeTool: (name, tool, input) => Effect.gen(function* () { @@ -278,17 +286,35 @@ function renderCatalog(root: CatalogNode): ReadonlyArray>() +const pathRuntimes = new WeakMap< + Inventory, + CodeMode.Runtime +>() + +const runtime = (inventory: Inventory) => + cached(runtimes, inventory, (tools) => + CodeMode.make({ + tools, + extensions: [CodeModeFetch.extension], + hooks: runHooks, + }), + ) -function runtime(inventory: Inventory) { - const cached = runtimes.get(inventory) - if (cached) return cached - const tools = inventoryTools(inventory) - const created = CodeMode.make({ - tools, - extensions: [CodeModeFetch.extension], - hooks: runHooks, - }) - runtimes.set(inventory, created) +// The runtime with the experimental `path` global. +const pathRuntime = (inventory: Inventory) => + cached(pathRuntimes, inventory, (tools) => + CodeMode.make({ + tools, + extensions: [CodeModeFetch.extension, CodeModePath.extension], + hooks: runHooks, + }), + ) + +function cached(cache: WeakMap, inventory: Inventory, make: (tools: Tools) => T) { + const found = cache.get(inventory) + if (found) return found + const created = make(inventoryTools(inventory)) + cache.set(inventory, created) return created } diff --git a/packages/core/src/session/context.ts b/packages/core/src/session/context.ts index eea20c76fb22..8385e639be13 100644 --- a/packages/core/src/session/context.ts +++ b/packages/core/src/session/context.ts @@ -7,6 +7,7 @@ import { Agent } from "../agent.js" import type { SessionRequestKind } from "@opencode/plugin/effect/session" import { CodeModeInstructions } from "../codemode/instructions.js" import { Database } from "../database/database.js" +import { Flag } from "../flag.js" import { makeLocationNode } from "@opencode/util/effect/app-node" import { InstructionDiscovery } from "../instruction-discovery.js" import { Instructions } from "../instructions/index.js" @@ -90,6 +91,7 @@ const layer = Layer.effect( const skillInstructions = yield* SkillInstructions.Service const store = yield* SessionStore.Service const registry = yield* Tool.Service + const flags = yield* Flag.Service const resolveModel = ( session: SessionSchema.Info, @@ -146,7 +148,9 @@ const layer = Layer.effect( const permissions = Permission.merge(agent.info.permissions, session.permissions ?? []) const loaded = yield* Effect.all( { - tools: registry.snapshot(permissions), + tools: flags + .enabled("full_codemode") + .pipe(Effect.flatMap((enabled) => registry.snapshot(permissions, enabled ? location : undefined))), builtins: builtins.load(), discovery: discovery.load(), skills: skillInstructions.load(permissions), @@ -217,6 +221,7 @@ export const node = makeLocationNode({ layer, deps: [ Agent.node, + Flag.node, Model.node, Database.node, InstructionBuiltIns.node, diff --git a/packages/core/src/tool.ts b/packages/core/src/tool.ts index 1dd64796bfb5..4bb6c4cce0a7 100644 --- a/packages/core/src/tool.ts +++ b/packages/core/src/tool.ts @@ -11,6 +11,7 @@ import type { Agent } from "./agent.js" import { CodeModeCatalog } from "./codemode/catalog.js" import { CodeModeJob } from "./codemode/job.js" import { CodeModeTool } from "./codemode/tool.js" +import type { Location } from "./location.js" import { Image } from "./image.js" import { Permission } from "./permission.js" import { PluginHooks } from "./plugin/hooks.js" @@ -44,7 +45,8 @@ type Data = { export interface Interface extends State.Transformable { readonly list: () => Effect.Effect> - readonly snapshot: (permissions?: Permission.Ruleset) => Effect.Effect + /** `location` turns on the experimental `path` global in Code Mode, resolving against its directory. */ + readonly snapshot: (permissions?: Permission.Ruleset, location?: Location.Interface) => Effect.Effect /** * Runs a Code Mode program with no model step over only the Code Mode tools named in `tools` (still subject to * whole-tool permission filtering and each tool's own executor policy), with no `fetch`. @@ -200,6 +202,7 @@ const layer = Layer.effect( | { data: Data names: string + location: Location.Interface | undefined inventory: CodeModeTool.Inventory value: CodeModeCatalog.Inventory definition: ToolDefinition @@ -263,7 +266,7 @@ const layer = Layer.effect( transform: state.transform, reload: state.reload, list: () => Effect.sync(() => Array.from(state.get().tools.values())), - snapshot: Effect.fn("Tool.snapshot")((permissions) => + snapshot: Effect.fn("Tool.snapshot")((permissions, location) => Effect.sync(() => { const data = state.get() const active = new Map() @@ -282,13 +285,15 @@ const layer = Layer.effect( // Discovery is immutable for a registry revision and visible tool set. Keep executors // fresh, but share the inventory, whose prepared runtime and much larger rendered catalog // are cached by identity, and the execute tool's definition across steps. - const cached = catalog?.data === data && catalog.names === names ? catalog : undefined + const cached = + catalog?.data === data && catalog.names === names && catalog.location === location ? catalog : undefined const codeModeInventory = cached?.inventory ?? { tools: codeModeTools, namespaces: data.namespaces } const codeModeTool = codeModeEnabled ? CodeModeTool.create( codeModeInventory, (name, tool, input, context) => run(codeModeInventory.tools, tool, name, input, context), permission, + location, ) : undefined const codeModeCatalog = !codeModeEnabled @@ -299,6 +304,7 @@ const layer = Layer.effect( catalog = { data, names, + location, inventory: codeModeInventory, value: codeModeCatalog, definition: codeModeDefinition, diff --git a/packages/core/test/tool-execute.test.ts b/packages/core/test/tool-execute.test.ts index 05023200b082..f53525e09105 100644 --- a/packages/core/test/tool-execute.test.ts +++ b/packages/core/test/tool-execute.test.ts @@ -1,5 +1,7 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test" +import path from "path" import { CodeModeTool } from "@opencode/core/codemode/tool" +import { AbsolutePath } from "@opencode/core/schema" import { Permission } from "@opencode/core/permission" import { Tool } from "@opencode/core/tool" import { execute } from "@opencode/core/tool/runtime" @@ -9,6 +11,7 @@ import { SessionMessage } from "@opencode/schema/session-message" import type { Info } from "@opencode/schema/tool" import { Deferred, Effect, Fiber, Schema } from "effect" import { TestClock } from "effect/testing" +import { location } from "./fixture/location" import { it } from "./lib/effect" import { permissionService } from "./lib/permission" @@ -152,6 +155,49 @@ test("execute rejects filesystem fetches", async () => { expect(result.output.output).toContain("fetch cannot be used for filesystem access.") }) +describe("path", () => { + const directory = AbsolutePath.make(path.resolve("/session/dir")) + const withPath = () => + CodeModeTool.create( + { tools: new Map() }, + (_, tool, input, context) => execute(tool, input, context), + allowAll, + location({ directory }), + ) + const run = async (code: string, codeMode = withPath()) => + JSON.parse((await Effect.runPromise(codeMode.execute({ code }, context))).output.output) + + test("without the experimental flag there is no path", async () => { + expect(await run("return [typeof path]", createCodeMode(new Map()))).toEqual(["undefined"]) + expect(createCodeMode(new Map()).description).not.toContain("`path`") + expect(withPath().description).toContain("`path`") + }) + + test("path is the host's path module, resolving against the session's directory", async () => { + expect( + await run( + `return [path.resolve("a", "b"), path.relative("a", "c"), path.join("out", "..", "x.txt"), path.basename("/a/b.ts", ".ts"), path.posix.join("a", "b"), path.win32.join("a", "b"), path.sep]`, + ), + ).toEqual([ + path.resolve(directory, "a", "b"), + path.join("..", "c"), + "x.txt", + "b", + "a/b", + "a\\b", + path.sep, + ]) + }) + + test("path is importable by its Node module names", async () => { + expect( + await run(`import { join } from "node:path" + const posix = require("path").posix + return [join("a", "b"), posix.dirname("a/b")]`), + ).toEqual([path.join("a", "b"), "a"]) + }) +}) + describe("execute output", () => { const run = async (code: string) => (await Effect.runPromise(createCodeMode(new Map()).execute({ code }, context))).output.output From 13d1a9253b8d5f359b13e3d9800068d77ced4429 Mon Sep 17 00:00:00 2001 From: Aiden Cline Date: Tue, 17 Nov 2026 11:05:54 -0600 Subject: [PATCH 2/4] refactor(core): gate Code Mode path on full_codemode in the registry, and leave the execute description alone --- packages/core/src/codemode/tool.ts | 93 +++++++++++------------- packages/core/src/session/context.ts | 7 +- packages/core/src/tool.ts | 19 +++-- packages/core/test/tool-execute.test.ts | 12 +-- packages/core/test/tool-registry.test.ts | 29 ++++++++ 5 files changed, 86 insertions(+), 74 deletions(-) diff --git a/packages/core/src/codemode/tool.ts b/packages/core/src/codemode/tool.ts index b7a0ae593d36..8180b16cc723 100644 --- a/packages/core/src/codemode/tool.ts +++ b/packages/core/src/codemode/tool.ts @@ -76,29 +76,26 @@ export type Inventory = { } // Invariant model-facing guidance; the changing tool catalog is delivered through Instructions. -const description = (path: boolean) => - [ - "Run JavaScript in a confined Code Mode runtime to script tool calls and HTTP requests and compose their results.", - "Write plain JavaScript and send it exactly as written: no code fence, and no JSON or other wrapper around it.", - path - ? "`fetch` is available for HTTP requests, and Node's `path` (also importable as `node:path`), whose `resolve` starts from the session directory. Other imports, direct filesystem access, and timers are unavailable: there is no `setTimeout` or sleep. All other external access goes through `tools`." - : "`fetch` is available for HTTP requests. Imports, direct filesystem access, and timers are unavailable: there is no `setTimeout` or sleep. All other external access goes through `tools`.", - "Inside `execute`, the only callable tools are those explicitly listed in the Code Mode catalog instructions or returned by the `search` function. Ignore tools shown outside the Code Mode catalog. They are not available in the Code Mode runtime.", - 'Call tools through `tools` using only exact paths and signatures from the catalog. Do not infer or normalize tool names; preserve bracket notation such as `tools.["tool-name"](input)`.', - "Prefer an explicit `return`; if omitted, the final top-level expression becomes the result.", - "Await every call whose completion matters; pending calls are interrupted when execution ends. Run independent calls concurrently with `Promise.allSettled`.", - ].join("\n") +const description = [ + "Run JavaScript in a confined Code Mode runtime to script tool calls and HTTP requests and compose their results.", + "Write plain JavaScript and send it exactly as written: no code fence, and no JSON or other wrapper around it.", + "`fetch` is available for HTTP requests. Imports, direct filesystem access, and timers are unavailable: there is no `setTimeout` or sleep. All other external access goes through `tools`.", + "Inside `execute`, the only callable tools are those explicitly listed in the Code Mode catalog instructions or returned by the `search` function. Ignore tools shown outside the Code Mode catalog. They are not available in the Code Mode runtime.", + 'Call tools through `tools` using only exact paths and signatures from the catalog. Do not infer or normalize tool names; preserve bracket notation such as `tools.["tool-name"](input)`.', + "Prefer an explicit `return`; if omitted, the final top-level expression becomes the result.", + "Await every call whose completion matters; pending calls are interrupted when execution ends. Run independent calls concurrently with `Promise.allSettled`.", +].join("\n") export const create = ( inventory: Inventory, executeTool: (name: string, tool: Info, input: unknown, context: ToolContext) => Effect.Effect, permission: Permission.Interface, - /** The session's Location, which turns on the experimental `path` global. */ + /** With `full_codemode`, the session's Location, which turns on the experimental `path` global. */ location?: Location.Interface, ) => { return { name: "execute", - description: description(location !== undefined), + description, input: CodeMode.Input, freeform: { type: "text" }, output: ExecuteOutput, @@ -133,41 +130,39 @@ export const create = ( ? pathRuntime(inventory).execute(code).pipe(Effect.provideService(Location.Service, location)) : runtime(inventory).execute(code) const result = yield* program.pipe( - Effect.provideService(Run, { - executeTool: (name, tool, input) => - Effect.gen(function* () { - const index = yield* Ref.getAndUpdate(callIndex, (index) => index + 1) - // Its own ID, so plugin hooks and traces can tell the program's calls apart. It has no row, so - // until the program ends its permission requests show on this call's. - const id = CallID.make(`call_${Identifier.ascending()}`) - yield* permission.nested(id, context.id).pipe(Scope.provide(scope)) - // The program sees the same failure text the model gets for a direct call. - const executed = yield* executeTool(name, tool, input, { - ...context, - id, - // Progress replaces the execute call's own, so an inner tool's updates would hide the call rows. - progress: () => Effect.void, - // A stop is the execute call's to handle: a nested call never fails it with its own error. - cancel: undefined, - }).pipe( - Effect.mapError((error) => new ToolFailure({ message: toSessionError(error).message, error })), - ) - const content = resultContent(executed) - const outputFileParts = outputFiles(content) - if (outputFileParts.length > 0) - yield* Ref.update(files, (items) => [...items, { index, files: outputFileParts }]) - return resultValue(executed) - }), - hooks: progressHooks(record), - }), - // A failed or interrupted call keeps its last progress, so send pending rows before it settles. - Effect.onError(() => - lock.withPermit(Ref.get(trailing).pipe(Effect.flatMap((pending) => (pending ? publish : Effect.void)))), - ), - // Readers outlive the fetch call that returned them, up to the end of this program's scope. - Effect.provideService(CodeModeExecution.Service, { ...context, signal: yield* Effect.abortSignal }), - Effect.provideService(Permission.Service, permission), - ) + Effect.provideService(Run, { + executeTool: (name, tool, input) => + Effect.gen(function* () { + const index = yield* Ref.getAndUpdate(callIndex, (index) => index + 1) + // Its own ID, so plugin hooks and traces can tell the program's calls apart. It has no row, so + // until the program ends its permission requests show on this call's. + const id = CallID.make(`call_${Identifier.ascending()}`) + yield* permission.nested(id, context.id).pipe(Scope.provide(scope)) + // The program sees the same failure text the model gets for a direct call. + const executed = yield* executeTool(name, tool, input, { + ...context, + id, + // Progress replaces the execute call's own, so an inner tool's updates would hide the call rows. + progress: () => Effect.void, + // A stop is the execute call's to handle: a nested call never fails it with its own error. + cancel: undefined, + }).pipe(Effect.mapError((error) => new ToolFailure({ message: toSessionError(error).message, error }))) + const content = resultContent(executed) + const outputFileParts = outputFiles(content) + if (outputFileParts.length > 0) + yield* Ref.update(files, (items) => [...items, { index, files: outputFileParts }]) + return resultValue(executed) + }), + hooks: progressHooks(record), + }), + // A failed or interrupted call keeps its last progress, so send pending rows before it settles. + Effect.onError(() => + lock.withPermit(Ref.get(trailing).pipe(Effect.flatMap((pending) => (pending ? publish : Effect.void)))), + ), + // Readers outlive the fetch call that returned them, up to the end of this program's scope. + Effect.provideService(CodeModeExecution.Service, { ...context, signal: yield* Effect.abortSignal }), + Effect.provideService(Permission.Service, permission), + ) const toolCalls = yield* Ref.get(calls) const collected = (yield* Ref.get(files)) .toSorted((left, right) => left.index - right.index) diff --git a/packages/core/src/session/context.ts b/packages/core/src/session/context.ts index 8385e639be13..ca15f25d42e4 100644 --- a/packages/core/src/session/context.ts +++ b/packages/core/src/session/context.ts @@ -7,7 +7,6 @@ import { Agent } from "../agent.js" import type { SessionRequestKind } from "@opencode/plugin/effect/session" import { CodeModeInstructions } from "../codemode/instructions.js" import { Database } from "../database/database.js" -import { Flag } from "../flag.js" import { makeLocationNode } from "@opencode/util/effect/app-node" import { InstructionDiscovery } from "../instruction-discovery.js" import { Instructions } from "../instructions/index.js" @@ -91,7 +90,6 @@ const layer = Layer.effect( const skillInstructions = yield* SkillInstructions.Service const store = yield* SessionStore.Service const registry = yield* Tool.Service - const flags = yield* Flag.Service const resolveModel = ( session: SessionSchema.Info, @@ -148,9 +146,7 @@ const layer = Layer.effect( const permissions = Permission.merge(agent.info.permissions, session.permissions ?? []) const loaded = yield* Effect.all( { - tools: flags - .enabled("full_codemode") - .pipe(Effect.flatMap((enabled) => registry.snapshot(permissions, enabled ? location : undefined))), + tools: registry.snapshot(permissions, location), builtins: builtins.load(), discovery: discovery.load(), skills: skillInstructions.load(permissions), @@ -221,7 +217,6 @@ export const node = makeLocationNode({ layer, deps: [ Agent.node, - Flag.node, Model.node, Database.node, InstructionBuiltIns.node, diff --git a/packages/core/src/tool.ts b/packages/core/src/tool.ts index 4bb6c4cce0a7..04de7d8752b0 100644 --- a/packages/core/src/tool.ts +++ b/packages/core/src/tool.ts @@ -11,8 +11,9 @@ import type { Agent } from "./agent.js" import { CodeModeCatalog } from "./codemode/catalog.js" import { CodeModeJob } from "./codemode/job.js" import { CodeModeTool } from "./codemode/tool.js" -import type { Location } from "./location.js" +import { Flag } from "./flag.js" import { Image } from "./image.js" +import type { Location } from "./location.js" import { Permission } from "./permission.js" import { PluginHooks } from "./plugin/hooks.js" import { SessionMessage } from "./session/message.js" @@ -45,7 +46,7 @@ type Data = { export interface Interface extends State.Transformable { readonly list: () => Effect.Effect> - /** `location` turns on the experimental `path` global in Code Mode, resolving against its directory. */ + /** With `full_codemode`, Code Mode gets the experimental `path` global, resolving against `location`'s directory. */ readonly snapshot: (permissions?: Permission.Ruleset, location?: Location.Interface) => Effect.Effect /** * Runs a Code Mode program with no model step over only the Code Mode tools named in `tools` (still subject to @@ -92,6 +93,7 @@ const layer = Layer.effect( const hooks = yield* PluginHooks.Service const image = yield* Image.Service const permission = yield* Permission.Service + const flags = yield* Flag.Service type NormalizedItem = Tool.Content | "decode" | "size" const normalizeImages = Effect.fnUntraced(function* (content: ReadonlyArray) { @@ -202,7 +204,7 @@ const layer = Layer.effect( | { data: Data names: string - location: Location.Interface | undefined + path: boolean inventory: CodeModeTool.Inventory value: CodeModeCatalog.Inventory definition: ToolDefinition @@ -267,7 +269,8 @@ const layer = Layer.effect( reload: state.reload, list: () => Effect.sync(() => Array.from(state.get().tools.values())), snapshot: Effect.fn("Tool.snapshot")((permissions, location) => - Effect.sync(() => { + Effect.map(flags.enabled("full_codemode"), (enabled) => { + const path = enabled && location !== undefined const data = state.get() const active = new Map() const rules = permissions ?? [] @@ -286,14 +289,14 @@ const layer = Layer.effect( // fresh, but share the inventory, whose prepared runtime and much larger rendered catalog // are cached by identity, and the execute tool's definition across steps. const cached = - catalog?.data === data && catalog.names === names && catalog.location === location ? catalog : undefined + catalog?.data === data && catalog.names === names && catalog.path === path ? catalog : undefined const codeModeInventory = cached?.inventory ?? { tools: codeModeTools, namespaces: data.namespaces } const codeModeTool = codeModeEnabled ? CodeModeTool.create( codeModeInventory, (name, tool, input, context) => run(codeModeInventory.tools, tool, name, input, context), permission, - location, + path ? location : undefined, ) : undefined const codeModeCatalog = !codeModeEnabled @@ -304,7 +307,7 @@ const layer = Layer.effect( catalog = { data, names, - location, + path, inventory: codeModeInventory, value: codeModeCatalog, definition: codeModeDefinition, @@ -447,5 +450,5 @@ function namespaceError(name: string) { export const node = makeLocationNode({ service: Service, layer, - deps: [PluginHooks.node, Image.node, Permission.node], + deps: [PluginHooks.node, Image.node, Permission.node, Flag.node], }) diff --git a/packages/core/test/tool-execute.test.ts b/packages/core/test/tool-execute.test.ts index f53525e09105..1bfaa85019aa 100644 --- a/packages/core/test/tool-execute.test.ts +++ b/packages/core/test/tool-execute.test.ts @@ -169,8 +169,6 @@ describe("path", () => { test("without the experimental flag there is no path", async () => { expect(await run("return [typeof path]", createCodeMode(new Map()))).toEqual(["undefined"]) - expect(createCodeMode(new Map()).description).not.toContain("`path`") - expect(withPath().description).toContain("`path`") }) test("path is the host's path module, resolving against the session's directory", async () => { @@ -178,15 +176,7 @@ describe("path", () => { await run( `return [path.resolve("a", "b"), path.relative("a", "c"), path.join("out", "..", "x.txt"), path.basename("/a/b.ts", ".ts"), path.posix.join("a", "b"), path.win32.join("a", "b"), path.sep]`, ), - ).toEqual([ - path.resolve(directory, "a", "b"), - path.join("..", "c"), - "x.txt", - "b", - "a/b", - "a\\b", - path.sep, - ]) + ).toEqual([path.resolve(directory, "a", "b"), path.join("..", "c"), "x.txt", "b", "a/b", "a\\b", path.sep]) }) test("path is importable by its Node module names", async () => { diff --git a/packages/core/test/tool-registry.test.ts b/packages/core/test/tool-registry.test.ts index 755ad4e7872a..110afd5f1fa9 100644 --- a/packages/core/test/tool-registry.test.ts +++ b/packages/core/test/tool-registry.test.ts @@ -1,6 +1,8 @@ import { describe, expect } from "bun:test" import { Agent } from "@opencode/core/agent" import { Permission } from "@opencode/core/permission" +import { Flag } from "@opencode/core/flag" +import { AbsolutePath } from "@opencode/core/schema" import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" import { Image } from "@opencode/core/image" import { PluginHooks } from "@opencode/core/plugin/hooks" @@ -14,6 +16,7 @@ import { codeModeListings, executeTool, toolDefinitions, toolNodeReplacements } import { Deferred, Effect, Exit, Fiber, Layer, Logger, Schema, SchemaGetter, SchemaIssue, Scope } from "effect" import { z } from "zod" import { testEffect } from "./lib/effect" +import { location } from "./fixture/location" const imageStore = Layer.mock(Image.Service, { normalize: (resource, content) => { @@ -42,6 +45,7 @@ const registryLayer = AppNodeBuilder.build(LayerNode.group([Tool.node, PluginHoo Image.node.replace(imageStore), ]) const it = testEffect(registryLayer) +const codeModeIt = testEffect(registryLayer.pipe(Layer.provide(Layer.succeed(Flag.Overrides, "full_codemode")))) const identity = { agent: Agent.ID.make("build"), messageID: SessionMessage.ID.make("msg_registry"), @@ -74,6 +78,31 @@ const transform = (service: Tool.Interface, tools: Readonly Object.entries(tools).forEach(([name, tool]) => editor.add({ ...tool, name, options: options ?? tool.options })), ) +describe("Code Mode path", () => { + const session = location({ directory: AbsolutePath.make("/session/dir") }) + const typeOfPath = Effect.gen(function* () { + const tools = yield* Tool.Service + const snapshot = yield* tools.snapshot(undefined, session) + const result = yield* snapshot.execute({ + ...call("execute"), + call: { type: "tool-call", id: "call-path", name: "execute", input: { code: `return [typeof path]` } }, + }) + return JSON.parse(result.output.output) + }) + + it.effect("is not available without full_codemode", () => + Effect.gen(function* () { + expect(yield* typeOfPath).toEqual(["undefined"]) + }), + ) + + codeModeIt.effect("is available with full_codemode", () => + Effect.gen(function* () { + expect(yield* typeOfPath).toEqual(["object"]) + }), + ) +}) + describe("Tool", () => { it.effect("reads the current editor tools by effective name", () => Effect.gen(function* () { From 1061f45ee0106f7ac5a0f74c7ce31c055a65a4cd Mon Sep 17 00:00:00 2001 From: Aiden Cline Date: Tue, 17 Nov 2026 11:07:17 -0600 Subject: [PATCH 3/4] fix(core): keep Code Mode path's other-platform resolve off the server's working directory --- packages/core/src/codemode/path.ts | 10 ++++++---- packages/core/test/tool-execute.test.ts | 7 +++++++ 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/packages/core/src/codemode/path.ts b/packages/core/src/codemode/path.ts index 233b79288d5f..39d43e802c2d 100644 --- a/packages/core/src/codemode/path.ts +++ b/packages/core/src/codemode/path.ts @@ -6,18 +6,20 @@ import path from "path" import { Location } from "../location.js" // Only functions and separators cross; `posix` and `win32` point back at their module, which a global can't hold, so -// each becomes a copy of its own functions. Programs have no `process.cwd()`: resolve and relative start from the -// session's directory. +// each becomes a copy of its own functions. Programs have no `process.cwd()`: the host's flavour resolves from the +// session's directory. The other flavour can't read that directory as absolute (`C:\\proj` isn't a POSIX path), so it +// resolves from its own root instead of falling back to the server's working directory. const flavor = (module: path.PlatformPath) => { const { posix: _posix, win32: _win32, ...functions } = module + const base = (directory: string) => (module === path ? directory : module.sep) return { ...functions, resolve: (...parts: Array) => - Location.Service.use((location) => Effect.succeed(module.resolve(location.directory, ...parts))), + Location.Service.use((location) => Effect.succeed(module.resolve(base(location.directory), ...parts))), relative: (from: string, to: string) => Location.Service.use((location) => Effect.succeed( - module.relative(module.resolve(location.directory, from), module.resolve(location.directory, to)), + module.relative(module.resolve(base(location.directory), from), module.resolve(base(location.directory), to)), ), ), } diff --git a/packages/core/test/tool-execute.test.ts b/packages/core/test/tool-execute.test.ts index 1bfaa85019aa..6af0132eb6e9 100644 --- a/packages/core/test/tool-execute.test.ts +++ b/packages/core/test/tool-execute.test.ts @@ -179,6 +179,13 @@ describe("path", () => { ).toEqual([path.resolve(directory, "a", "b"), path.join("..", "c"), "x.txt", "b", "a/b", "a\\b", path.sep]) }) + test("the other platform's flavour resolves from its own root, not the server's working directory", async () => { + const other = path.sep === "/" ? "win32" : "posix" + const [resolved] = await run(`return [path.${other}.resolve("a")]`) + expect(resolved).toBe(path[other].resolve(path[other].sep, "a")) + expect(resolved).not.toContain(process.cwd()) + }) + test("path is importable by its Node module names", async () => { expect( await run(`import { join } from "node:path" From a032035db4e409af83c2dc3aa6fcc74bf41f54af Mon Sep 17 00:00:00 2001 From: Aiden Cline Date: Tue, 17 Nov 2026 11:23:35 -0600 Subject: [PATCH 4/4] refactor(core): keep one Code Mode runtime and give path only to runs with full_codemode --- packages/core/src/codemode/path.ts | 18 ++--- packages/core/src/codemode/tool.ts | 117 +++++++++++++---------------- 2 files changed, 61 insertions(+), 74 deletions(-) diff --git a/packages/core/src/codemode/path.ts b/packages/core/src/codemode/path.ts index 39d43e802c2d..d86ff1d4a797 100644 --- a/packages/core/src/codemode/path.ts +++ b/packages/core/src/codemode/path.ts @@ -1,7 +1,7 @@ export * as CodeModePath from "./path.js" import { Extension } from "@opencode/codemode" -import { Effect } from "effect" +import { Effect, Option } from "effect" import path from "path" import { Location } from "../location.js" @@ -11,20 +11,20 @@ import { Location } from "../location.js" // resolves from its own root instead of falling back to the server's working directory. const flavor = (module: path.PlatformPath) => { const { posix: _posix, win32: _win32, ...functions } = module - const base = (directory: string) => (module === path ? directory : module.sep) + const base: Effect.Effect = module === path ? directory : Effect.succeed(module.sep) return { ...functions, - resolve: (...parts: Array) => - Location.Service.use((location) => Effect.succeed(module.resolve(base(location.directory), ...parts))), + resolve: (...parts: Array) => Effect.map(base, (from) => module.resolve(from, ...parts)), relative: (from: string, to: string) => - Location.Service.use((location) => - Effect.succeed( - module.relative(module.resolve(base(location.directory), from), module.resolve(base(location.directory), to)), - ), - ), + Effect.map(base, (start) => module.relative(module.resolve(start, from), module.resolve(start, to))), } } +// A run gets `path` only with the session's Location (see `CodeModeTool.create`). +const directory = Effect.flatMap(Effect.serviceOption(Location.Service), (location) => + Option.isSome(location) ? Effect.succeed(location.value.directory) : Effect.die("Code Mode path needs a Location."), +) + /** The host's own path module, as Node gives it, with `path.posix` and `path.win32`. */ export const extension = Extension.make({ name: "path", diff --git a/packages/core/src/codemode/tool.ts b/packages/core/src/codemode/tool.ts index 8180b16cc723..a4483a2d6c5b 100644 --- a/packages/core/src/codemode/tool.ts +++ b/packages/core/src/codemode/tool.ts @@ -126,43 +126,47 @@ export const create = ( yield* Effect.sleep(wait).pipe(Effect.andThen(lock.withPermit(publish)), Effect.forkIn(scope)) }), ) - const program = location - ? pathRuntime(inventory).execute(code).pipe(Effect.provideService(Location.Service, location)) - : runtime(inventory).execute(code) - const result = yield* program.pipe( - Effect.provideService(Run, { - executeTool: (name, tool, input) => - Effect.gen(function* () { - const index = yield* Ref.getAndUpdate(callIndex, (index) => index + 1) - // Its own ID, so plugin hooks and traces can tell the program's calls apart. It has no row, so - // until the program ends its permission requests show on this call's. - const id = CallID.make(`call_${Identifier.ascending()}`) - yield* permission.nested(id, context.id).pipe(Scope.provide(scope)) - // The program sees the same failure text the model gets for a direct call. - const executed = yield* executeTool(name, tool, input, { - ...context, - id, - // Progress replaces the execute call's own, so an inner tool's updates would hide the call rows. - progress: () => Effect.void, - // A stop is the execute call's to handle: a nested call never fails it with its own error. - cancel: undefined, - }).pipe(Effect.mapError((error) => new ToolFailure({ message: toSessionError(error).message, error }))) - const content = resultContent(executed) - const outputFileParts = outputFiles(content) - if (outputFileParts.length > 0) - yield* Ref.update(files, (items) => [...items, { index, files: outputFileParts }]) - return resultValue(executed) - }), - hooks: progressHooks(record), - }), - // A failed or interrupted call keeps its last progress, so send pending rows before it settles. - Effect.onError(() => - lock.withPermit(Ref.get(trailing).pipe(Effect.flatMap((pending) => (pending ? publish : Effect.void)))), - ), - // Readers outlive the fetch call that returned them, up to the end of this program's scope. - Effect.provideService(CodeModeExecution.Service, { ...context, signal: yield* Effect.abortSignal }), - Effect.provideService(Permission.Service, permission), - ) + const result = yield* runtime(inventory) + .execute(code, undefined, { + extensions: location ? [CodeModeFetch.extension, CodeModePath.extension] : [CodeModeFetch.extension], + }) + .pipe( + Effect.provideService(Run, { + executeTool: (name, tool, input) => + Effect.gen(function* () { + const index = yield* Ref.getAndUpdate(callIndex, (index) => index + 1) + // Its own ID, so plugin hooks and traces can tell the program's calls apart. It has no row, so + // until the program ends its permission requests show on this call's. + const id = CallID.make(`call_${Identifier.ascending()}`) + yield* permission.nested(id, context.id).pipe(Scope.provide(scope)) + // The program sees the same failure text the model gets for a direct call. + const executed = yield* executeTool(name, tool, input, { + ...context, + id, + // Progress replaces the execute call's own, so an inner tool's updates would hide the call rows. + progress: () => Effect.void, + // A stop is the execute call's to handle: a nested call never fails it with its own error. + cancel: undefined, + }).pipe( + Effect.mapError((error) => new ToolFailure({ message: toSessionError(error).message, error })), + ) + const content = resultContent(executed) + const outputFileParts = outputFiles(content) + if (outputFileParts.length > 0) + yield* Ref.update(files, (items) => [...items, { index, files: outputFileParts }]) + return resultValue(executed) + }), + hooks: progressHooks(record), + }), + // A failed or interrupted call keeps its last progress, so send pending rows before it settles. + Effect.onError(() => + lock.withPermit(Ref.get(trailing).pipe(Effect.flatMap((pending) => (pending ? publish : Effect.void)))), + ), + // Readers outlive the fetch call that returned them, up to the end of this program's scope. + Effect.provideService(CodeModeExecution.Service, { ...context, signal: yield* Effect.abortSignal }), + Effect.provideService(Permission.Service, permission), + (program) => (location ? Effect.provideService(program, Location.Service, location) : program), + ) const toolCalls = yield* Ref.get(calls) const collected = (yield* Ref.get(files)) .toSorted((left, right) => left.index - right.index) @@ -281,35 +285,18 @@ function renderCatalog(root: CatalogNode): ReadonlyArray>() -const pathRuntimes = new WeakMap< - Inventory, - CodeMode.Runtime ->() - -const runtime = (inventory: Inventory) => - cached(runtimes, inventory, (tools) => - CodeMode.make({ - tools, - extensions: [CodeModeFetch.extension], - hooks: runHooks, - }), - ) -// The runtime with the experimental `path` global. -const pathRuntime = (inventory: Inventory) => - cached(pathRuntimes, inventory, (tools) => - CodeMode.make({ - tools, - extensions: [CodeModeFetch.extension, CodeModePath.extension], - hooks: runHooks, - }), - ) - -function cached(cache: WeakMap, inventory: Inventory, make: (tools: Tools) => T) { - const found = cache.get(inventory) - if (found) return found - const created = make(inventoryTools(inventory)) - cache.set(inventory, created) +function runtime(inventory: Inventory) { + const cached = runtimes.get(inventory) + if (cached) return cached + const tools = inventoryTools(inventory) + // Every extension a run may get; `create` picks each run's. + const created = CodeMode.make({ + tools, + extensions: [CodeModeFetch.extension, CodeModePath.extension], + hooks: runHooks, + }) + runtimes.set(inventory, created) return created }