feat(core): add Node's path to Code Mode behind full_codemode (#64476)

This commit is contained in:
Aiden Cline
2026-11-17 12:00:45 -06:00
committed by GitHub
Unverified
parent f0def1f86f
commit 18503ee942
6 changed files with 130 additions and 9 deletions
+32
View File
@@ -0,0 +1,32 @@
export * as CodeModePath from "./path.js"
import { Extension } from "@opencode/codemode"
import { Effect, Option } 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()`: 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: Effect.Effect<string> = module === path ? directory : Effect.succeed(module.sep)
return {
...functions,
resolve: (...parts: Array<string>) => Effect.map(base, (from) => module.resolve(from, ...parts)),
relative: (from: string, to: string) =>
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",
globals: { path: { ...flavor(path), posix: flavor(path.posix), win32: flavor(path.win32) } },
})
+11 -3
View File
@@ -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,
@@ -88,6 +90,8 @@ export const create = (
inventory: Inventory,
executeTool: (name: string, tool: Info, input: unknown, context: ToolContext) => Effect.Effect<Result, Error>,
permission: Permission.Interface,
/** With `full_codemode`, the session's Location, which turns on the experimental `path` global. */
location?: Location.Interface,
) => {
return {
name: "execute",
@@ -123,7 +127,9 @@ export const create = (
}),
)
const result = yield* runtime(inventory)
.execute(code)
.execute(code, undefined, {
extensions: location ? [CodeModeFetch.extension, CodeModePath.extension] : [CodeModeFetch.extension],
})
.pipe(
Effect.provideService(Run, {
executeTool: (name, tool, input) =>
@@ -159,6 +165,7 @@ export const create = (
// 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))
@@ -283,9 +290,10 @@ function runtime(inventory: Inventory) {
const cached = runtimes.get(inventory)
if (cached) return cached
const tools = inventoryTools(inventory)
const created = CodeMode.make<typeof tools, [typeof CodeModeFetch.extension]>({
// Every extension a run may get; `create` picks each run's.
const created = CodeMode.make<typeof tools, [typeof CodeModeFetch.extension, typeof CodeModePath.extension]>({
tools,
extensions: [CodeModeFetch.extension],
extensions: [CodeModeFetch.extension, CodeModePath.extension],
hooks: runHooks,
})
runtimes.set(inventory, created)
+1 -1
View File
@@ -146,7 +146,7 @@ const layer = Layer.effect(
const permissions = Permission.merge(agent.info.permissions, session.permissions ?? [])
const loaded = yield* Effect.all(
{
tools: registry.snapshot(permissions),
tools: registry.snapshot(permissions, location),
builtins: builtins.load(),
discovery: discovery.load(),
skills: skillInstructions.load(permissions),
+14 -5
View File
@@ -11,7 +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 { 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"
@@ -44,7 +46,8 @@ type Data = {
export interface Interface extends State.Transformable<Editor> {
readonly list: () => Effect.Effect<ReadonlyArray<Tool.Info & { readonly id: string }>>
readonly snapshot: (permissions?: Permission.Ruleset) => Effect.Effect<Snapshot>
/** 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<Snapshot>
/**
* 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`.
@@ -90,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<Tool.Content>) {
@@ -200,6 +204,7 @@ const layer = Layer.effect(
| {
data: Data
names: string
path: boolean
inventory: CodeModeTool.Inventory
value: CodeModeCatalog.Inventory
definition: ToolDefinition
@@ -263,8 +268,9 @@ 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) =>
Effect.sync(() => {
snapshot: Effect.fn("Tool.snapshot")((permissions, location) =>
Effect.map(flags.enabled("full_codemode"), (enabled) => {
const path = enabled && location !== undefined
const data = state.get()
const active = new Map<string, Tool.Info>()
const rules = permissions ?? []
@@ -282,13 +288,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.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,
path ? location : undefined,
)
: undefined
const codeModeCatalog = !codeModeEnabled
@@ -299,6 +307,7 @@ const layer = Layer.effect(
catalog = {
data,
names,
path,
inventory: codeModeInventory,
value: codeModeCatalog,
definition: codeModeDefinition,
@@ -441,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],
})
+43
View File
@@ -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,46 @@ 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"])
})
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("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"
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
+29
View File
@@ -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<Record<string, Info>
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* () {