From 01daacc6882878513df5da72cc017ecb20d7d2fc Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Mon, 23 Nov 2026 16:05:49 -0800 Subject: [PATCH] feat(core): add unified Environments entry point (#65926) --- packages/core/src/environment/environment.ts | 61 ++- packages/core/src/environment/environments.ts | 72 +++ packages/core/src/environment/index.ts | 2 + packages/core/src/environment/path.ts | 68 +++ packages/core/src/file-access.ts | 90 ++-- packages/core/src/instance.ts | 2 + packages/core/src/machine/path.ts | 54 +-- packages/core/src/session/context.ts | 4 +- packages/core/src/session/cwd-instructions.ts | 11 +- packages/core/src/session/cwd-store.ts | 66 +++ packages/core/src/session/cwd.ts | 117 +---- packages/core/src/session/info.ts | 4 +- packages/core/src/session/projector.ts | 8 +- packages/core/src/session/runner/llm.ts | 4 +- packages/core/src/session/to-session-error.ts | 8 +- packages/core/src/workspace.ts | 17 +- packages/core/test/environments.test.ts | 415 ++++++++++++++++++ packages/core/test/fixture/codemode.ts | 7 + packages/core/test/session-cwd.test.ts | 2 + 19 files changed, 815 insertions(+), 197 deletions(-) create mode 100644 packages/core/src/environment/environments.ts create mode 100644 packages/core/src/environment/path.ts create mode 100644 packages/core/src/session/cwd-store.ts create mode 100644 packages/core/test/environments.test.ts diff --git a/packages/core/src/environment/environment.ts b/packages/core/src/environment/environment.ts index 74b396e8db6..d22ddef2c1e 100644 --- a/packages/core/src/environment/environment.ts +++ b/packages/core/src/environment/environment.ts @@ -1,10 +1,10 @@ import { CrossSpawnSpawner } from "@opencode/util/cross-spawn-spawner" import { makeLocationNode } from "@opencode/util/effect/app-node" -import { Context, Effect, Layer, Schema } from "effect" -import { ChildProcessSpawner } from "effect/process/ChildProcessSpawner" -import type { PlatformPath } from "node:path" +import { Context, Effect, Layer, PlatformError, Schema } from "effect" +import { ChildProcessSpawner } from "effect/process" +import { posix, type PlatformPath } from "node:path" import type { Driver } from "./driver.js" -import type { Files } from "./files.js" +import { Failed, type Files } from "./files.js" import { makeFiles } from "./exec-defaults.js" import { makeLocalDriver } from "./local.js" import { EnvironmentUnavailable } from "./unavailable.js" @@ -45,7 +45,7 @@ export interface Facts { export interface Interface extends Facts { readonly id: ID readonly files: Files - readonly spawner: ChildProcessSpawner["Service"] + readonly spawner: ChildProcessSpawner.ChildProcessSpawner["Service"] } export class Service extends Context.Service()("@opencode/Environment") {} @@ -58,7 +58,7 @@ export const make = (id: ID, driver: Driver, facts?: Facts): Interface => ({ }) /** The computer the server runs on. */ -export const local = (spawner: ChildProcessSpawner["Service"]) => +export const local = (spawner: ChildProcessSpawner.ChildProcessSpawner["Service"]) => make( localID, makeLocalDriver(spawner), @@ -66,6 +66,46 @@ export const local = (spawner: ChildProcessSpawner["Service"]) => spawner === EnvironmentUnavailable.spawner ? {} : { hostsServer: true, searchable: true }, ) +/** A workspace sandbox environment; runs ripgrep through its own spawner and uses POSIX path rules. */ +export const workspace = (id: Workspace.ID, driver: Driver) => + make(ID.make(id), driver, { path: posix, searchable: true }) + +/** + * A total environment handle that fails every file and command operation loudly with `cause` instead of + * silently falling back to the server host. + */ +export const unavailable = (id: ID, cause: Error): Interface => { + const spawner = ChildProcessSpawner.make(() => + Effect.fail( + PlatformError.systemError({ + _tag: "Unknown", + module: "Environment", + method: "spawn", + description: cause.message, + cause, + }), + ), + ) + const fail = (path: string) => Effect.fail(new Failed({ path, cause })) + return make( + id, + { + spawner, + overrides: { + read: (path) => fail(path), + write: (path) => fail(path), + stat: (path) => fail(path), + list: (path) => fail(path), + remove: (path) => fail(path), + move: (from) => fail(from), + mkdir: (path) => fail(path), + append: (path) => fail(path), + }, + }, + { path: posix, shell: "sh" }, + ) +} + /** * A session's own working directory, bound to its environment, provided by the runner around a step. * Absent unless the session sets one, so bare paths and commands stay on the Location's directory. @@ -91,19 +131,18 @@ export const workingDirectoryResolver = Effect.map(workingDirectory, (fallback) const layer = Layer.effect( Service, Effect.gen(function* () { - const spawner = yield* ChildProcessSpawner + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner const location = yield* Location.Service - const workspace = yield* Workspace.Service + const workspaces = yield* Workspace.Service if (!location.workspaceID) return Service.of(local(spawner)) - const driver = yield* workspace.connect(location.workspaceID).pipe( + const driver = yield* workspaces.connect(location.workspaceID).pipe( // Environment has no error channel; an unknown or destroyed placement is a configuration defect by design. Effect.mapError( (cause) => new Error(`Failed to bind Environment to workspace ${location.workspaceID}`, { cause }), ), Effect.orDie, ) - // A workspace runs ripgrep through its own spawner. Nothing of the server's reaches it otherwise. - return Service.of(make(ID.make(location.workspaceID), driver, { searchable: true })) + return Service.of(workspace(location.workspaceID, driver)) }), ) diff --git a/packages/core/src/environment/environments.ts b/packages/core/src/environment/environments.ts new file mode 100644 index 00000000000..545d9b34e8e --- /dev/null +++ b/packages/core/src/environment/environments.ts @@ -0,0 +1,72 @@ +export * as Environments from "./environments.js" + +import { CrossSpawnSpawner } from "@opencode/util/cross-spawn-spawner" +import { makeGlobalNode } from "@opencode/util/effect/app-node" +import { Context, Effect, Layer } from "effect" +import { ChildProcessSpawner } from "effect/process/ChildProcessSpawner" +import { Machines } from "../machine/machines.js" +import { Workspace } from "../workspace.js" +import { Environment } from "./index.js" + +export interface Interface { + /** + * Total lookup for any environment ID: local, a paired machine, or a workspace sandbox. + * Returns a failing handle when a machine was removed instead of falling back to the host. + * Never boots a Location and never holds a workspace lease longer than one operation. + */ + readonly get: (id: Environment.ID) => Effect.Effect + /** + * Strict lookup for an environment ID typed by a user or model. + * Fails immediately with NotFound when a machine or workspace does not exist, without waking lazy sandboxes. + */ + readonly lookup: (id: Environment.ID) => Effect.Effect + /** Whether an environment is currently reachable in memory without waking a cold/lazy sandbox. */ + readonly ready: (id: Environment.ID) => Effect.Effect +} + +export class Service extends Context.Service()("@opencode/Environments") {} + +const layer = Layer.effect( + Service, + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner + const machines = yield* Machines.Service + const workspaces = yield* Workspace.Service + const local = Environment.local(spawner) + + const sandbox = Effect.fnUntraced(function* (id: Workspace.ID) { + // Workspace.connect builds a lazy per-operation driver without waking or provisioning here. + const driver = yield* workspaces.connect(id).pipe(Effect.orDie) + return Environment.workspace(id, driver) + }) + + return Service.of({ + get: Effect.fn("Environments.get")(function* (id: Environment.ID) { + if (id === Environment.localID) return local + if (Workspace.isID(id)) return yield* sandbox(id) + return yield* machines + .get(id) + .pipe(Effect.catchTag("Machines.NotFound", (error) => Effect.succeed(Environment.unavailable(id, error)))) + }), + lookup: Effect.fn("Environments.lookup")(function* (id: Environment.ID) { + if (id === Environment.localID) return local + if (Workspace.isID(id)) { + if (!(yield* workspaces.exists(id))) return yield* new Workspace.NotFound({ workspaceID: id }) + return yield* sandbox(id) + } + return yield* machines.get(id) + }), + ready: Effect.fn("Environments.ready")(function* (id: Environment.ID) { + if (id === Environment.localID) return true + if (Workspace.isID(id)) return yield* workspaces.connected(id) + return true + }), + }) + }), +) + +export const node = makeGlobalNode({ + service: Service, + layer, + deps: [CrossSpawnSpawner.node, Machines.node, Workspace.node], +}) diff --git a/packages/core/src/environment/index.ts b/packages/core/src/environment/index.ts index 632e351e29f..79d506b7135 100644 --- a/packages/core/src/environment/index.ts +++ b/packages/core/src/environment/index.ts @@ -26,6 +26,8 @@ export { node, Place, Service, + unavailable, workingDirectory, + workspace, workingDirectoryResolver, } from "./environment.js" diff --git a/packages/core/src/environment/path.ts b/packages/core/src/environment/path.ts new file mode 100644 index 00000000000..8864296c7d7 --- /dev/null +++ b/packages/core/src/environment/path.ts @@ -0,0 +1,68 @@ +export * as EnvironmentPath from "./path.js" + +import { Effect, Schema } from "effect" +import { Machines } from "../machine/machines.js" +import { Workspace } from "../workspace.js" +import { Environment } from "./index.js" + +export interface Parsed { + readonly environment: Environment.ID + /** The rest as written, `/...` or `~...`: locating a path owner normalizes it. */ + readonly path: string +} + +export class NotAbsolute extends Schema.TaggedError()("Machine.NotAbsolute", { + machine: Environment.ID, +}) { + override get message() { + return `Machine paths are absolute or start with ~/: write ${this.machine}:/… or ${this.machine}:~/… (for a local folder with that name, start with ./)` + } +} + +const isEnvironmentPrefix = (name: string) => + name === Environment.localID || Workspace.isID(name) || Schema.is(Machines.Name)(name) + +/** Splits `env:rest` at a name an environment could have (local, workspace ID, or machine name). */ +const split = (text: string): Parsed | undefined => { + const colon = text.indexOf(":") + if (colon <= 0) return + const environment = text.slice(0, colon) + if (!isEnvironmentPrefix(environment)) return + return { environment: Environment.ID.make(environment), path: text.slice(colon + 1) } +} + +const rooted = (path: string) => path.startsWith("/") || path.startsWith("~") + +/** + * Splits `local:/a`, `gpu:/work/a`, `gpu:~/a`, or `wrk_...:/workspace` into an environment and the rest. + * A Windows drive or any URL (`skill://`, `https://`) is not an environment path. + */ +export const parse = (text: string): Parsed | undefined => { + const named = split(text) + if (!named || !rooted(named.path) || named.path.startsWith("//")) return + return named +} + +/** + * Reads text someone typed: an environment path, or nothing when it is a plain path in the current environment. + * Non-rooted `name:relative` text is refused for reserved environment prefixes (`local:`, `wrk_...:`) and + * known paired machines so typos never silently misroute to another environment's relative path. + */ +export const typed = Effect.fnUntraced(function* (text: string, machines: Machines.Interface) { + const parsed = parse(text) + if (parsed) return parsed + const named = split(text) + if (!named || rooted(named.path)) return + if ( + named.environment === Environment.localID || + Workspace.isID(named.environment) || + (yield* machines.list()).some((info) => info.id === named.environment) + ) + return yield* new NotAbsolute({ machine: named.environment }) +}) + +/** An environment path's text: what `parse` reads back. */ +export const format = (environment: Environment.ID, path: string) => `${environment}:${path}` + +/** A local path's text, kept from reading as an environment path via a leading `./`. */ +export const local = (path: string) => (parse(path) ? `./${path}` : path) diff --git a/packages/core/src/file-access.ts b/packages/core/src/file-access.ts index d43dce91aca..391bc69da9e 100644 --- a/packages/core/src/file-access.ts +++ b/packages/core/src/file-access.ts @@ -5,16 +5,18 @@ import { FSUtil } from "@opencode/util/fs-util" import { Global } from "@opencode/util/global" import { Array, Context, Effect, Layer, Schema } from "effect" import path from "path" +import { Environments } from "./environment/environments.js" import { Environment } from "./environment/index.js" +import { EnvironmentPath } from "./environment/path.js" import { Flag } from "./flag.js" import { Location } from "./location.js" import { Machines } from "./machine/machines.js" -import { MachinePath } from "./machine/path.js" import { Permission } from "./permission.js" import { Project } from "./project.js" import { AbsolutePath } from "./schema.js" import type { SessionErrors } from "./session/error.js" import type { Tool } from "./tool.js" +import { Workspace } from "./workspace.js" export const Kind = Schema.Literals(["file", "directory"]) export type Kind = typeof Kind.Type @@ -73,7 +75,7 @@ export const key = (target: { readonly absolute: string; readonly environment: { `${target.environment.id.length}:${target.environment.id}:${target.absolute}` /** The rule "always" saves for a file action: every file on the target's machine. */ -export const always = (target: Target) => (target.machine ? MachinePath.format(target.machine, "*") : "*") +export const always = (target: Target) => (target.machine ? EnvironmentPath.format(target.machine, "*") : "*") export type Invocation = Pick @@ -131,6 +133,7 @@ const layer = Layer.effect( const currentWorkingDirectory = yield* Environment.workingDirectoryResolver const permission = yield* Permission.Service const flags = yield* Flag.Service + const environments = yield* Environments.Service const machines = yield* Machines.Service // The flag and the working directory are read once per operation by `locate` and `resolve`, which both call this. @@ -140,40 +143,51 @@ const layer = Layer.effect( enabled: boolean, workingDirectory: Environment.Place, ) { - // Only text the model typed can name a machine: text derived from a target is a plain path on that target's - // machine, and a shell there does not understand `gpu:`. - const machine = - !base && enabled - ? yield* MachinePath.typed(text, machines).pipe( + // Only text the model typed on the server's own Location can address another environment: a sandboxed workspace + // Location stays confined to its own environment and cannot escape to `local:/...`, paired machines, or other + // sandboxes. Text derived from a target is always a plain path in that target's environment. + const crossEnvironment = enabled && environment.id === Environment.localID + const parsed = + !base && crossEnvironment + ? yield* EnvironmentPath.typed(text, machines).pipe( Effect.mapError((cause) => new Environment.Failed({ path: text, cause })), ) : undefined const from = base ?? workingDirectory - const id = machine?.machine ?? from.environment.id - if (!machine && id === environment.id) + const id = parsed?.environment ?? from.environment.id + if (id === environment.id) { + const written = parsed?.path ?? text + const origin = parsed ? location.directory : from.absolute return { - absolute: AbsolutePath.make(resolvePath(from.absolute, text)), + absolute: AbsolutePath.make(resolvePath(origin, written)), environment: { id }, } satisfies Environment.Place - // Another environment's paths follow its own path rules (falling back to POSIX when unknown), and `~` there is - // that machine's home, never this server's. Only `~` and `~/` are read: another user's home or a shell's `~+` is - // not known here. With the flag off no home is asked for, so a base on another machine refuses every `~`. - const target = enabled - ? yield* machines.get(id).pipe(Effect.catchTag("Machines.NotFound", () => Effect.undefined)) + } + // Another environment's paths follow its own path rules (falling back to POSIX when unknown). Only `~` and `~/` + // are expanded: paired machines report their home in hello, while sandboxes do not expose a home directory. + // With the flag off no home is asked for, so a base on another machine refuses every `~`. + const target = crossEnvironment + ? yield* environments.lookup(id).pipe( + Effect.catchTags({ + "Machines.NotFound": () => Effect.undefined, + "Workspace.NotFound": () => Effect.undefined, + }), + ) : undefined const rules = target ? (target.path ?? path) : path.posix - const written = machine?.path ?? text + const written = parsed?.path ?? text + const isHome = written === "~" || written.startsWith("~/") const rooted = - enabled && (written === "~" || written.startsWith("~/")) + crossEnvironment && isHome && !Workspace.isID(id) ? rules.join( yield* machines.home(id).pipe(Effect.mapError((cause) => new Environment.Failed({ path: text, cause }))), written.slice(1), ) : written if (rooted.startsWith("~")) - return yield* new Environment.Failed({ path: text, cause: new MachinePath.NotAbsolute({ machine: id }) }) + return yield* new Environment.Failed({ path: text, cause: new EnvironmentPath.NotAbsolute({ machine: id }) }) // A relative text is relative to the directory it was written in, which is the base when there is one and - // otherwise the working directory itself: a session cwd on another machine is still a directory there. + // otherwise the working directory itself: a session cwd in another environment is still a directory there. return { absolute: AbsolutePath.make(rules.resolve(from.absolute, rooted)), environment: { id }, @@ -217,8 +231,8 @@ const layer = Layer.effect( const relative = slash(path.relative(base, absolute) || ".") return { absolute, - // With machines on, a local folder can be named like a machine path, and its permission name stays its own. - resource: enabled ? MachinePath.local(relative) : relative, + // With cross-environment prefixes on, a local folder can be named like an environment path, so keep it local. + resource: enabled && environment.id === Environment.localID ? EnvironmentPath.local(relative) : relative, environment, } satisfies Target } @@ -249,24 +263,36 @@ const layer = Layer.effect( kind: Kind | undefined, insideWorkingDirectory: boolean, ) { - const machineEnvironment = yield* machines - .get(place.environment.id) + const targetEnvironment = yield* environments + .lookup(place.environment.id) .pipe(Effect.mapError((cause) => new Environment.Failed({ path: place.absolute, cause }))) - const rules = machineEnvironment.path ?? path + const rules = targetEnvironment.path ?? path + // Never wake a cold/lazy sandbox just to stat the approval boundary before permission is granted. + const ready = yield* environments.ready(place.environment.id) const type = kind ?? - (yield* Environment.typeFollowing(machineEnvironment.files, place.absolute).pipe( - Effect.catchTag("Environment.NotFound", () => Effect.undefined), - )) - const directory = AbsolutePath.make(type === "directory" ? place.absolute : rules.dirname(place.absolute)) - const contents = MachinePath.format(place.environment.id, rules.join(directory, "*")) + (ready + ? yield* Environment.typeFollowing(targetEnvironment.files, place.absolute).pipe( + Effect.catchTag("Environment.NotFound", () => Effect.undefined), + ) + : undefined) + // When a cold sandbox's target type is unknown, narrow the boundary to the path itself rather than widening + // to its parent directory (which would save a wider rule such as `wrk_...:*` on "always"). + const narrowCold = !ready && type === undefined + const directory = AbsolutePath.make( + type === "directory" || narrowCold ? place.absolute : rules.dirname(place.absolute), + ) + const contents = EnvironmentPath.format( + place.environment.id, + narrowCold ? place.absolute : rules.join(directory, "*"), + ) return { absolute: place.absolute, - resource: MachinePath.format(place.environment.id, place.absolute), + resource: EnvironmentPath.format(place.environment.id, place.absolute), ...(insideWorkingDirectory ? {} : { externalDirectory: { action: "external_directory", directory, resource: contents, save: contents } }), - environment: machineEnvironment, + environment: targetEnvironment, machine: place.environment.id, } satisfies Target }) @@ -324,5 +350,5 @@ const layer = Layer.effect( export const node = makeLocationNode({ service: Service, layer, - deps: [Environment.node, Flag.node, Location.node, Machines.node, Permission.node], + deps: [Environment.node, Environments.node, Flag.node, Location.node, Machines.node, Permission.node], }) diff --git a/packages/core/src/instance.ts b/packages/core/src/instance.ts index 384d223ed13..1335e4d9657 100644 --- a/packages/core/src/instance.ts +++ b/packages/core/src/instance.ts @@ -12,6 +12,7 @@ import { LayerNode } from "@opencode/util/effect/layer-node" import { Node } from "@opencode/util/effect/app-node" import { FileMutation } from "./file-mutation.js" import { FileWrite } from "./file-write.js" +import { Environments } from "./environment/environments.js" import { Environment } from "./environment/index.js" import { Formatter } from "./formatter.js" import { FileSystem } from "./filesystem.js" @@ -65,6 +66,7 @@ const nodes = [ Location.node, LocationLifecycle.node, Environment.node, + Environments.node, Config.node, Flag.node, Agent.node, diff --git a/packages/core/src/machine/path.ts b/packages/core/src/machine/path.ts index 78644cfc7ef..a8d5def03f7 100644 --- a/packages/core/src/machine/path.ts +++ b/packages/core/src/machine/path.ts @@ -2,56 +2,40 @@ export * as MachinePath from "./path.js" import { Effect, Schema } from "effect" import { Environment } from "../environment/index.js" +import { EnvironmentPath } from "../environment/path.js" import { Machines } from "./machines.js" +export const NotAbsolute = EnvironmentPath.NotAbsolute +export type NotAbsolute = EnvironmentPath.NotAbsolute + export interface Parsed { readonly machine: Environment.ID /** The rest as written, `/...` or `~...`: locating a path owner normalizes it. */ readonly path: string } -export class NotAbsolute extends Schema.TaggedError()("Machine.NotAbsolute", { - machine: Environment.ID, -}) { - override get message() { - return `Machine paths are absolute or start with ~/: write ${this.machine}:/… or ${this.machine}:~/… (for a local folder with that name, start with ./)` - } +/** Splits `gpu:/work/a` or `gpu:~/a` into a machine and the rest. A Windows drive, URL, `local:`, or workspace ID is not one. */ +export const parse = (text: string): Parsed | undefined => { + const parsed = EnvironmentPath.parse(text) + if (!parsed || !Schema.is(Machines.Name)(parsed.environment)) return + return { machine: parsed.environment, path: parsed.path } } -/** Splits `name:rest` at a name a machine could have. A Windows drive is not one. */ -const split = (text: string): Parsed | undefined => { - const colon = text.indexOf(":") - if (colon <= 0) return - const machine = text.slice(0, colon) - if (!Schema.is(Machines.Name)(machine)) return - return { machine: Environment.ID.make(machine), path: text.slice(colon + 1) } -} - -const rooted = (path: string) => path.startsWith("/") || path.startsWith("~") - -/** Splits `gpu:/work/a` or `gpu:~/a` into a machine and the rest. A Windows drive or any URL is not one. */ -export const parse = (text: string) => { - const named = split(text) - if (!named || !rooted(named.path) || named.path.startsWith("//")) return - return named -} - -/** - * Reads text someone typed: a machine path, or nothing when it is a path on this server. A machine path is absolute - * or starts with ~/, so `gpu:work` is no machine path and would quietly be this server's folder. Only a name that is a - * machine here is refused: another name stays a local folder, as before. - */ +/** Reads text someone typed as a paired machine path, refusing non-rooted paths for known paired machines. */ export const typed = Effect.fnUntraced(function* (text: string, machines: Machines.Interface) { const parsed = parse(text) if (parsed) return parsed - const named = split(text) - if (!named || rooted(named.path)) return - if ((yield* machines.list()).some((info) => info.id === named.machine)) - return yield* new NotAbsolute({ machine: named.machine }) + const colon = text.indexOf(":") + if (colon <= 0) return + const machine = text.slice(0, colon) + const rest = text.slice(colon + 1) + if (!Schema.is(Machines.Name)(machine) || rest.startsWith("/") || rest.startsWith("~")) return + if ((yield* machines.list()).some((info) => info.id === machine)) + return yield* new NotAbsolute({ machine: Environment.ID.make(machine) }) }) /** A machine path's text: what `parse` reads back. */ -export const format = (machine: Environment.ID, path: string) => `${machine}:${path}` +export const format = EnvironmentPath.format -/** A local path's text, kept from reading as a machine path: a folder here can be named like one, and `./` keeps it local. */ +/** A local path's text, kept from reading as a machine path via a leading `./`. */ export const local = (path: string) => (parse(path) ? `./${path}` : path) diff --git a/packages/core/src/session/context.ts b/packages/core/src/session/context.ts index e6ff23cb883..e751171ad23 100644 --- a/packages/core/src/session/context.ts +++ b/packages/core/src/session/context.ts @@ -20,7 +20,7 @@ import { Instructions } from "../instructions/index.js" import { InstructionBuiltIns } from "../instructions/builtins.js" import { Location } from "../location.js" import { MachineInstructions } from "../machine/instructions.js" -import { Machines } from "../machine/machines.js" +import { Environments } from "../environment/environments.js" import { McpInstructions } from "../mcp/instructions.js" import { McpTool } from "../tool/mcp.js" import { ReferenceInstructions } from "../reference/instructions.js" @@ -278,7 +278,7 @@ export const node = makeLocationNode({ InstructionEntry.node, Location.node, MachineInstructions.node, - Machines.node, + Environments.node, McpInstructions.node, McpTool.node, ReferenceInstructions.node, diff --git a/packages/core/src/session/cwd-instructions.ts b/packages/core/src/session/cwd-instructions.ts index c5bb78ca4b4..38ef69a5af5 100644 --- a/packages/core/src/session/cwd-instructions.ts +++ b/packages/core/src/session/cwd-instructions.ts @@ -6,6 +6,7 @@ import { eq } from "drizzle-orm" import { Context, Effect, Layer, Option, Result, Schema } from "effect" import { join } from "path" import { Database } from "../database/database.js" +import { Environments } from "../environment/environments.js" import { Environment } from "../environment/index.js" import { InstructionDiscovery } from "../instruction-discovery.js" import { Instructions } from "../instructions/index.js" @@ -60,6 +61,7 @@ const layer = Layer.effect( const database = Option.getOrUndefined(yield* Effect.serviceOption(Database.Service)) const discovery = yield* InstructionDiscovery.Service const environment = yield* Environment.Service + const environments = yield* Environments.Service const location = yield* Location.Service const hasStoredInstructions = (sessionID: SessionSchema.ID | undefined) => { @@ -125,6 +127,13 @@ const layer = Layer.effect( sessionID?: SessionSchema.ID, ) { if (!cwd || !discovery.project || coveredByDiscovery(cwd)) return source(Effect.succeed(Instructions.removed)) + // Do not wake a cold or lazy sandbox just to probe for AGENTS.md before the model calls a tool. + if (!(yield* environments.ready(cwd.environment.id))) + return source( + hasStoredInstructions(sessionID).pipe( + Effect.map((stored) => (stored ? Instructions.unavailable : Instructions.removed)), + ), + ) return source(read(cwd, sessionID)) }), }) @@ -134,5 +143,5 @@ const layer = Layer.effect( export const node = makeLocationNode({ service: Service, layer, - deps: [Database.node, Environment.node, InstructionDiscovery.node, Location.node], + deps: [Database.node, Environment.node, Environments.node, InstructionDiscovery.node, Location.node], }) diff --git a/packages/core/src/session/cwd-store.ts b/packages/core/src/session/cwd-store.ts new file mode 100644 index 00000000000..291ea3f5ec1 --- /dev/null +++ b/packages/core/src/session/cwd-store.ts @@ -0,0 +1,66 @@ +export * as SessionCwdStore from "./cwd-store.js" + +import { eq } from "drizzle-orm" +import { Effect, Option, Schema } from "effect" +import type { Database } from "../database/database.js" +import { Environment } from "../environment/index.js" +import type { SessionSchema } from "./schema.js" +import { SessionTable } from "./sql.js" + +// Experimental storage inside session_v2.metadata so this stays internal with zero DB migration. +// Stripped from public Session.Info.metadata and preserved across MetadataUpdated. +const metadataKey = "$opencode_experimental_cwd" +const decodePlace = Schema.decodeUnknownOption(Environment.Place) + +export function readStored(metadata: SessionSchema.Metadata | null | undefined): { + readonly cwd: Environment.Place | undefined + readonly metadata: SessionSchema.Metadata | undefined +} { + if (!metadata) return { cwd: undefined, metadata: undefined } + if (!Object.hasOwn(metadata, metadataKey)) return { cwd: undefined, metadata } + const cwd = Option.getOrUndefined(decodePlace(metadata[metadataKey])) + const rest = Object.fromEntries(Object.entries(metadata).filter(([key]) => key !== metadataKey)) + return { cwd, metadata: Object.keys(rest).length > 0 ? rest : undefined } +} + +export function writeStored( + metadata: SessionSchema.Metadata | null | undefined, + cwd: Environment.Place | undefined, +): SessionSchema.Metadata | null { + if (!cwd && (!metadata || !Object.hasOwn(metadata, metadataKey))) return metadata ?? null + const clean = Object.fromEntries(Object.entries(metadata ?? {}).filter(([key]) => key !== metadataKey)) + const next = cwd ? { ...clean, [metadataKey]: cwd } : clean + return Object.keys(next).length > 0 ? next : null +} + +export const read = Effect.fn("SessionCwd.read")(function* (db: Database.Interface["db"], sessionID: SessionSchema.ID) { + const row = yield* db + .select({ metadata: SessionTable.metadata }) + .from(SessionTable) + .where(eq(SessionTable.id, sessionID)) + .get() + .pipe(Effect.orDie) + return readStored(row?.metadata).cwd +}) + +export const write = Effect.fn("SessionCwd.write")(function* ( + db: Database.Interface["db"], + sessionID: SessionSchema.ID, + cwd: Environment.Place | undefined, +) { + const row = yield* db + .select({ metadata: SessionTable.metadata }) + .from(SessionTable) + .where(eq(SessionTable.id, sessionID)) + .get() + .pipe(Effect.orDie) + if (!row) return + const existing = readStored(row.metadata) + if (existing.cwd?.absolute === cwd?.absolute && existing.cwd?.environment.id === cwd?.environment.id) return + yield* db + .update(SessionTable) + .set({ metadata: writeStored(row.metadata, cwd) }) + .where(eq(SessionTable.id, sessionID)) + .run() + .pipe(Effect.orDie) +}) diff --git a/packages/core/src/session/cwd.ts b/packages/core/src/session/cwd.ts index 306d19337e5..2705901187a 100644 --- a/packages/core/src/session/cwd.ts +++ b/packages/core/src/session/cwd.ts @@ -1,24 +1,18 @@ export * as SessionCwd from "./cwd.js" -import { eq } from "drizzle-orm" -import { Effect, Option, PlatformError, Schema } from "effect" -import { ChildProcessSpawner } from "effect/process" -import { posix } from "node:path" +import { Effect, Option } from "effect" import { Database } from "../database/database.js" +import { Environments } from "../environment/environments.js" import { Environment } from "../environment/index.js" +import { EnvironmentPath } from "../environment/path.js" import { FileAccess } from "../file-access.js" import { Flag } from "../flag.js" -import { Machines } from "../machine/machines.js" -import { MachinePath } from "../machine/path.js" -import { AbsolutePath } from "../schema.js" +import type { AbsolutePath } from "../schema.js" +import { read, readStored, write, writeStored } from "./cwd-store.js" import { CwdError } from "./error.js" import type { SessionSchema } from "./schema.js" -import { SessionTable } from "./sql.js" -// Experimental storage inside session_v2.metadata so this stays internal with zero DB migration. -// Stripped from public Session.Info.metadata and preserved across MetadataUpdated. -const metadataKey = "$opencode_experimental_cwd" -const decodePlace = Schema.decodeUnknownOption(Environment.Place) +export { read, readStored, write, writeStored } /** A session cwd bound to its environment: where it is, and the files and commands it resolves against. */ export interface Resolved { @@ -28,7 +22,7 @@ export interface Resolved { /** A path in a cwd's environment as the model writes it: plain on the Location's own environment, `machine:/path` elsewhere. */ export const format = (cwd: Resolved, path: string, locationEnvironmentID: Environment.ID) => - cwd.environment.id === locationEnvironmentID ? path : MachinePath.format(cwd.environment.id, path) + cwd.environment.id === locationEnvironmentID ? path : EnvironmentPath.format(cwd.environment.id, path) /** The cwd as the model writes it, naming the machine when the directory is on a paired machine. */ export const describe = (cwd: Resolved, locationEnvironmentID: Environment.ID) => ({ @@ -36,61 +30,8 @@ export const describe = (cwd: Resolved, locationEnvironmentID: Environment.ID) = machine: cwd.environment.id === locationEnvironmentID ? undefined : cwd.environment.id, }) -export function readStored(metadata: SessionSchema.Metadata | null | undefined): { - readonly cwd: Environment.Place | undefined - readonly metadata: SessionSchema.Metadata | undefined -} { - if (!metadata) return { cwd: undefined, metadata: undefined } - if (!Object.hasOwn(metadata, metadataKey)) return { cwd: undefined, metadata } - const cwd = Option.getOrUndefined(decodePlace(metadata[metadataKey])) - const rest = Object.fromEntries(Object.entries(metadata).filter(([key]) => key !== metadataKey)) - return { cwd, metadata: Object.keys(rest).length > 0 ? rest : undefined } -} - -export function writeStored( - metadata: SessionSchema.Metadata | null | undefined, - cwd: Environment.Place | undefined, -): SessionSchema.Metadata | null { - if (!cwd && (!metadata || !Object.hasOwn(metadata, metadataKey))) return metadata ?? null - const clean = Object.fromEntries(Object.entries(metadata ?? {}).filter(([key]) => key !== metadataKey)) - const next = cwd ? { ...clean, [metadataKey]: cwd } : clean - return Object.keys(next).length > 0 ? next : null -} - -export const read = Effect.fn("SessionCwd.read")(function* (db: Database.Interface["db"], sessionID: SessionSchema.ID) { - const row = yield* db - .select({ metadata: SessionTable.metadata }) - .from(SessionTable) - .where(eq(SessionTable.id, sessionID)) - .get() - .pipe(Effect.orDie) - return readStored(row?.metadata).cwd -}) - -export const write = Effect.fn("SessionCwd.write")(function* ( - db: Database.Interface["db"], - sessionID: SessionSchema.ID, - cwd: Environment.Place | undefined, -) { - const row = yield* db - .select({ metadata: SessionTable.metadata }) - .from(SessionTable) - .where(eq(SessionTable.id, sessionID)) - .get() - .pipe(Effect.orDie) - if (!row) return - const existing = readStored(row.metadata) - if (existing.cwd?.absolute === cwd?.absolute && existing.cwd?.environment.id === cwd?.environment.id) return - yield* db - .update(SessionTable) - .set({ metadata: writeStored(row.metadata, cwd) }) - .where(eq(SessionTable.id, sessionID)) - .run() - .pipe(Effect.orDie) -}) - /** - * Experimental: resolves a typed cwd string in this Location (local path or paired machine path) + * Experimental: resolves a typed cwd string in this Location (local path, paired machine, or sandbox path) * and verifies that the target exists and is a directory. */ export const locate = Effect.fn("SessionCwd.locate")(function* (text: string) { @@ -113,7 +54,7 @@ export const make = Effect.gen(function* () { const database = Option.getOrUndefined(yield* Effect.serviceOption(Database.Service)) const flags = Option.getOrUndefined(yield* Effect.serviceOption(Flag.Service)) const environment = Option.getOrUndefined(yield* Effect.serviceOption(Environment.Service)) - const machines = Option.getOrUndefined(yield* Effect.serviceOption(Machines.Service)) + const environments = Option.getOrUndefined(yield* Effect.serviceOption(Environments.Service)) const resolve = Effect.fn("SessionCwd.current")(function* (sessionID: SessionSchema.ID) { if (!database || !flags || !environment) return undefined @@ -121,11 +62,8 @@ export const make = Effect.gen(function* () { const cwd = yield* read(database.db, sessionID) if (!cwd) return undefined if (cwd.environment.id === environment.id) return { absolute: cwd.absolute, environment } - if (!machines) return undefined - const machine = yield* machines - .get(cwd.environment.id) - .pipe(Effect.catchTag("Machines.NotFound", (error) => Effect.succeed(missingMachine(cwd.environment.id, error)))) - return { absolute: cwd.absolute, environment: machine } + if (!environments) return undefined + return { absolute: cwd.absolute, environment: yield* environments.get(cwd.environment.id) } }) return { current: resolve } @@ -135,36 +73,3 @@ export const current = Effect.fn("SessionCwd.current")(function* (sessionID: Ses const resolver = yield* make return yield* resolver.current(sessionID) }) - -// A session whose cwd names a removed machine must fail loudly rather than silently falling back to this server. -const missingMachine = (id: Environment.ID, error: Machines.NotFound): Environment.Interface => { - const spawner = ChildProcessSpawner.make(() => - Effect.fail( - PlatformError.systemError({ - _tag: "Unknown", - module: "Machine", - method: "spawn", - description: error.message, - cause: error, - }), - ), - ) - const fail = (path: string) => Effect.fail(new Environment.Failed({ path, cause: error })) - return Environment.make( - id, - { - spawner, - overrides: { - read: (path) => fail(path), - write: (path) => fail(path), - stat: (path) => fail(path), - list: (path) => fail(path), - remove: (path) => fail(path), - move: (from) => fail(from), - mkdir: (path) => fail(path), - append: (path) => fail(path), - }, - }, - { path: posix, shell: "sh" }, - ) -} diff --git a/packages/core/src/session/info.ts b/packages/core/src/session/info.ts index 82c72e49dfd..b64e938c444 100644 --- a/packages/core/src/session/info.ts +++ b/packages/core/src/session/info.ts @@ -2,7 +2,7 @@ import { DateTime, Schema } from "effect" import { Model } from "@opencode/schema/model" import { Provider } from "@opencode/schema/provider" import { AbsolutePath, RelativePath } from "../schema.js" -import { SessionCwd } from "./cwd.js" +import { SessionCwdStore } from "./cwd-store.js" import { SessionSchema } from "./schema.js" import type { SessionTable } from "./sql.js" import { PersistedRevert } from "@opencode/schema/session-revert" @@ -46,7 +46,7 @@ export function fromRow(row: typeof SessionTable.$inferSelect): SessionSchema.In workspaceID: row.workspace_id ?? undefined, }, subpath: row.path ? RelativePath.make(row.path) : undefined, - metadata: SessionCwd.readStored(row.metadata).metadata, + metadata: SessionCwdStore.readStored(row.metadata).metadata, permissions: row.permission ?? undefined, revert: row.revert ? decodeRevert(row.revert) : undefined, outcome: row.idle_outcome ?? undefined, diff --git a/packages/core/src/session/projector.ts b/packages/core/src/session/projector.ts index d8a8ae75bef..9c4db42a604 100644 --- a/packages/core/src/session/projector.ts +++ b/packages/core/src/session/projector.ts @@ -10,7 +10,7 @@ import { DatabaseBatch } from "../database/batch.js" import { Bus } from "../bus.js" import { makeGlobalNode } from "@opencode/util/effect/app-node" import { Model } from "@opencode/schema/model" -import { SessionCwd } from "./cwd.js" +import { SessionCwdStore } from "./cwd-store.js" import { SessionEvent } from "./event.js" import { SessionMessage } from "./message.js" import { SessionMessageUpdater } from "./message-updater.js" @@ -885,7 +885,7 @@ const layer = Layer.effectDiscard( title: event.data.title, agent: event.data.agent, model: event.data.model, - metadata: SessionCwd.writeStored(event.data.metadata, undefined), + metadata: SessionCwdStore.writeStored(event.data.metadata, undefined), permission: event.data.permissions, version: event.data.version, time_created: event.created, @@ -988,9 +988,9 @@ const layer = Layer.effectDiscard( ) yield* bus.project(SessionEvent.MetadataUpdated, (event) => Effect.gen(function* () { - const existing = yield* SessionCwd.read(db, event.data.sessionID) + const existing = yield* SessionCwdStore.read(db, event.data.sessionID) yield* setSession(db, event.data.sessionID, { - metadata: SessionCwd.writeStored(event.data.metadata, existing), + metadata: SessionCwdStore.writeStored(event.data.metadata, existing), time_updated: event.created, }) }), diff --git a/packages/core/src/session/runner/llm.ts b/packages/core/src/session/runner/llm.ts index d70d1638d6d..8d2767758e1 100644 --- a/packages/core/src/session/runner/llm.ts +++ b/packages/core/src/session/runner/llm.ts @@ -8,7 +8,7 @@ import { Bus } from "../../bus.js" import { Environment } from "../../environment/index.js" import { Flag } from "../../flag.js" import { LocationLifecycle } from "../../location-lifecycle.js" -import { Machines } from "../../machine/machines.js" +import { Environments } from "../../environment/environments.js" import { SessionCwd } from "../cwd.js" import { InstructionState } from "../instruction-state.js" import { SessionCompaction } from "../compaction.js" @@ -463,7 +463,7 @@ export const node = makeLocationNode({ Environment.node, Flag.node, LocationLifecycle.node, - Machines.node, + Environments.node, llmClient, SessionContext.node, SessionModelTransport.node, diff --git a/packages/core/src/session/to-session-error.ts b/packages/core/src/session/to-session-error.ts index d72143a6a48..cb4ade71561 100644 --- a/packages/core/src/session/to-session-error.ts +++ b/packages/core/src/session/to-session-error.ts @@ -12,6 +12,7 @@ import { Integration } from "../integration.js" import { AgentNotFoundError, StepFailedError } from "./error.js" import { ModelResolver } from "../model-resolver.js" import { ModelRetry } from "../model-retry.js" +import { Workspace } from "../workspace.js" import { SessionRunnerModel } from "./runner/model.js" const tokenSharingMessages = { @@ -163,7 +164,12 @@ function providerError(type: string, reason: AIError["reason"]): SessionError.Er const machineMessage = (error: unknown): string | undefined => { if (error instanceof Machine.NotSent || error instanceof Machine.Unknown || error instanceof Machine.ProcessLost) return error.message - if (error instanceof Machines.NotFound || error instanceof MachinePath.NotAbsolute) return error.message + if ( + error instanceof Machines.NotFound || + error instanceof Workspace.NotFound || + error instanceof MachinePath.NotAbsolute + ) + return error.message if ( error instanceof Environment.Failed || error instanceof AppProcess.AppProcessError || diff --git a/packages/core/src/workspace.ts b/packages/core/src/workspace.ts index 05cc5eba934..124feec8a80 100644 --- a/packages/core/src/workspace.ts +++ b/packages/core/src/workspace.ts @@ -17,6 +17,9 @@ import { WorkspaceTable } from "./workspace/sql.js" export const ID = Workspace.ID export type ID = Workspace.ID +/** Disjoint from Machines.Name (which disallows underscores) and from "local". */ +export const isID = (value: string): value is ID => /^wrk_[A-Za-z0-9_-]+$/.test(value) + export class Info extends Schema.Class("Workspace.Info")({ id: ID, provider: Schema.String, @@ -25,7 +28,11 @@ export class Info extends Schema.Class("Workspace.Info")({ lastUsedAt: Schema.Number, }) {} -export class NotFound extends Schema.TaggedError()("Workspace.NotFound", { workspaceID: ID }) {} +export class NotFound extends Schema.TaggedError()("Workspace.NotFound", { workspaceID: ID }) { + override get message() { + return `No workspace named ${JSON.stringify(this.workspaceID)}.` + } +} export class CreateConflict extends Schema.TaggedError()("Workspace.CreateConflict", { workspaceID: ID, @@ -46,6 +53,10 @@ export interface Interface { readonly connect: ( workspaceID: ID, ) => Effect.Effect + /** Whether a logical workspace row exists; never wakes or provisions the backing resource. */ + readonly exists: (workspaceID: ID) => Effect.Effect + /** Whether the workspace currently holds a live connection in memory; never wakes or provisions it. */ + readonly connected: (workspaceID: ID) => Effect.Effect /** Makes the workspace absent; reports whether this call destroyed an existing workspace. */ readonly destroy: ( workspaceID: ID, @@ -314,6 +325,10 @@ const layer = (options: Options) => } return { spawner, overrides } }), + exists: Effect.fn("Workspace.exists")(function* (workspaceID) { + return (yield* find(workspaceID)) !== undefined + }), + connected: (workspaceID) => Effect.sync(() => connections.has(workspaceID)), destroy: Effect.fn("Workspace.destroy")(function* (workspaceID) { // Settling the shared attempt cancels its racing provision body and fails // waiters with NotFound before teardown commits. Accepted tradeoffs: if the diff --git a/packages/core/test/environments.test.ts b/packages/core/test/environments.test.ts new file mode 100644 index 00000000000..0fa1db5aad7 --- /dev/null +++ b/packages/core/test/environments.test.ts @@ -0,0 +1,415 @@ +import { describe, expect, test } from "bun:test" +import { Effect, Layer } from "effect" +import { Agent } from "@opencode/core/agent" +import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" +import { Database } from "@opencode/core/database/database" +import { Environments } from "@opencode/core/environment/environments" +import { Environment, makeMemoryDriver } from "@opencode/core/environment/index" +import { EnvironmentPath } from "@opencode/core/environment/path" +import { FileAccess } from "@opencode/core/file-access" +import { Flag } from "@opencode/core/flag" +import { InstructionDiscovery } from "@opencode/core/instruction-discovery" +import { Location } from "@opencode/core/location" +import { Machines } from "@opencode/core/machine/machines" +import { MachinePath } from "@opencode/core/machine/path" +import { Permission } from "@opencode/core/permission" +import { Project } from "@opencode/core/project" +import { ProjectTable } from "@opencode/core/project/sql" +import { AbsolutePath } from "@opencode/core/schema" +import { SessionCwd } from "@opencode/core/session/cwd" +import { SessionCwdInstructions } from "@opencode/core/session/cwd-instructions" +import { InstructionState } from "@opencode/core/session/instruction-state" +import { SessionSchema } from "@opencode/core/session/schema" +import { SessionTable } from "@opencode/core/session/sql" +import { toSessionError } from "@opencode/core/session/to-session-error" +import { Workspace } from "@opencode/core/workspace" +import { WorkspaceDriver } from "@opencode/core/workspace/driver" +import { SessionMessage } from "@opencode/schema/session-message" +import { Tool } from "@opencode/schema/tool" +import { Global } from "@opencode/util/global" +import { LayerNode } from "@opencode/util/effect/layer-node" +import { location } from "./fixture/location" +import { tmpdirScoped } from "./fixture/tmpdir" +import { testEffect } from "./lib/effect" +import { readInitial } from "./lib/instructions" + +const bytes = (value: string) => new TextEncoder().encode(value) +const text = (value: Uint8Array) => new TextDecoder().decode(value) + +describe("EnvironmentPath", () => { + const cases: ReadonlyArray = [ + ["local:/tmp/out.txt", { environment: "local", path: "/tmp/out.txt" }], + ["local:~/notes.md", { environment: "local", path: "~/notes.md" }], + ["local:~", { environment: "local", path: "~" }], + ["gpu:/work/train.py", { environment: "gpu", path: "/work/train.py" }], + ["gpu:~/notes", { environment: "gpu", path: "~/notes" }], + ["wrk_01JXYZ:/workspace/app.ts", { environment: "wrk_01JXYZ", path: "/workspace/app.ts" }], + ["wrk_sandbox:/", { environment: "wrk_sandbox", path: "/" }], + ["wrk_:/x", undefined], + ["C:/Users/x", undefined], + ["https://host/x", undefined], + ["skill://thing", undefined], + ["local:relative", undefined], + ["wrk_sandbox:relative", undefined], + ["/plain/path", undefined], + ] + + for (const [input, expected] of cases) { + test(`parse ${JSON.stringify(input)}`, () => { + const parsed = EnvironmentPath.parse(input) + expect(parsed && { environment: `${parsed.environment}`, path: parsed.path }).toEqual(expected) + }) + } + + test("local() escapes environment-shaped paths", () => { + expect(EnvironmentPath.local("local:/tmp")).toBe("./local:/tmp") + expect(EnvironmentPath.local("wrk_1:/app")).toBe("./wrk_1:/app") + expect(EnvironmentPath.local("gpu:/work")).toBe("./gpu:/work") + expect(EnvironmentPath.local("src/index.ts")).toBe("src/index.ts") + }) +}) + +const makeSandboxDriver = (calls: string[], memory = makeMemoryDriver()) => + WorkspaceDriver.make({ + create: ({ workspaceID }) => { + calls.push("create") + return Effect.succeed({ binding: { workspaceID } }) + }, + connect: () => { + calls.push("connect") + return Effect.succeed(memory) + }, + suspendForIdle: () => Effect.void, + destroy: () => Effect.void, + }) + +const buildLayer = (options: { + readonly directory: AbsolutePath + readonly dataDirectory?: string + readonly workspaceID?: Workspace.ID + readonly driver: WorkspaceDriver.Interface + readonly machinesFlag?: boolean + readonly denyExternal?: boolean +}) => + AppNodeBuilder.build( + LayerNode.group([ + Database.node, + Environment.node, + Environments.node, + FileAccess.node, + Machines.node, + Permission.node, + SessionCwdInstructions.node, + Workspace.node, + ]), + [ + Location.node.replace( + Layer.succeed( + Location.Service, + Location.Service.of(location({ directory: options.directory, workspaceID: options.workspaceID })), + ), + ), + Global.node.replace( + Global.layerWith({ + config: options.dataDirectory ?? options.directory, + tmp: options.dataDirectory ?? options.directory, + }), + ), + Flag.node.replace(Flag.testLayer([], { overrides: options.machinesFlag === false ? "-machines" : "machines" })), + InstructionDiscovery.node.replace( + Layer.mock(InstructionDiscovery.Service, { project: true, global: true, claude: true }), + ), + ...(options.denyExternal + ? [ + Permission.node.replace( + Layer.mock(Permission.Service, { + assert: (input) => + Effect.fail( + new Permission.BlockedError({ + permission: input.action, + resources: [...input.resources], + rules: [], + }), + ), + }), + ), + ] + : []), + WorkspaceDriver.node.replace( + Layer.succeed( + WorkspaceDriver.RegistryService, + WorkspaceDriver.RegistryService.of({ + get: (provider) => + provider === "fake" + ? Effect.succeed(options.driver) + : Effect.fail(new WorkspaceDriver.ProviderNotFound({ provider })), + }), + ), + ), + ], + ) + +const it = testEffect(Layer.empty) + +describe("Environments", () => { + it.live("resolves local to the server host and fails loudly for removed machines", () => + Effect.gen(function* () { + const tmp = yield* tmpdirScoped() + const layer = buildLayer({ directory: AbsolutePath.make(tmp.path), driver: makeSandboxDriver([]) }) + + yield* Effect.gen(function* () { + const environments = yield* Environments.Service + const local = yield* environments.get(Environment.localID) + expect(local.id).toBe(Environment.localID) + expect(local.hostsServer).toBe(true) + + const removedID = Environment.ID.make("ghost") + const removed = yield* environments.get(removedID) + const removedRead = yield* removed.files.read("/x").pipe(Effect.flip) + expect(removedRead).toBeInstanceOf(Environment.Failed) + expect(removedRead.cause).toBeInstanceOf(Machines.NotFound) + expect(yield* environments.lookup(removedID).pipe(Effect.flip)).toBeInstanceOf(Machines.NotFound) + expect(toSessionError(new Tool.Error({ message: "Read failed", error: removedRead }))).toMatchObject({ + type: "tool.execution", + message: 'No machine named "ghost".', + }) + }).pipe(Effect.provide(layer)) + }), + ) + + it.live("fails lookup immediately for missing workspaces without provisioning", () => + Effect.gen(function* () { + const tmp = yield* tmpdirScoped() + const calls: string[] = [] + const layer = buildLayer({ directory: AbsolutePath.make(tmp.path), driver: makeSandboxDriver(calls) }) + + yield* Effect.gen(function* () { + const environments = yield* Environments.Service + const missingErr = yield* environments.lookup(Environment.ID.make("wrk_missing")).pipe(Effect.flip) + expect(missingErr).toBeInstanceOf(Workspace.NotFound) + expect( + toSessionError( + new Tool.Error({ + message: "Read failed", + error: new Environment.Failed({ path: "/workspace", cause: missingErr }), + }), + ), + ).toMatchObject({ + type: "tool.execution", + message: 'No workspace named "wrk_missing".', + }) + expect(calls).toEqual([]) + }).pipe(Effect.provide(layer)) + }), + ) + + it.live("keeps a lazy workspace cold until first file operation and never widens cold approval rules", () => + Effect.gen(function* () { + const tmp = yield* tmpdirScoped() + const calls: string[] = [] + const layer = buildLayer({ directory: AbsolutePath.make(tmp.path), driver: makeSandboxDriver(calls) }) + + yield* Effect.gen(function* () { + const environments = yield* Environments.Service + const workspaces = yield* Workspace.Service + const access = yield* FileAccess.Service + + const wrkID = yield* workspaces.create({ provider: "fake" }) + const wrkEnvID = Environment.ID.make(wrkID) + expect(yield* environments.ready(wrkEnvID)).toBe(false) + const sandbox = yield* environments.get(wrkEnvID) + expect(calls).toEqual([]) + + // Unknown-kind cold resolution narrows to the exact path instead of widening to parent (e.g. wrk_...:/*). + const coldUnknown = yield* access.resolve({ path: `${wrkID}:/workspace` }) + expect(coldUnknown.externalDirectory).toMatchObject({ + action: "external_directory", + resource: `${wrkID}:/workspace`, + save: `${wrkID}:/workspace`, + }) + expect(calls).toEqual([]) + + // Explicit file kind uses the file's directory glob without waking the sandbox. + const target = yield* access.resolve({ path: `${wrkID}:/workspace/hello.txt`, kind: "file" }) + expect(target.environment.id).toBe(wrkEnvID) + expect(target.resource).toBe(`${wrkID}:/workspace/hello.txt`) + expect(target.externalDirectory).toMatchObject({ + action: "external_directory", + resource: `${wrkID}:/workspace/*`, + }) + expect(calls).toEqual([]) + + // First file write wakes and provisions the sandbox. + yield* target.environment.files.mkdir("/workspace") + yield* target.environment.files.write("/workspace/hello.txt", bytes("from sandbox")) + expect(calls).toEqual(["create", "connect"]) + expect(yield* environments.ready(wrkEnvID)).toBe(true) + expect(text((yield* sandbox.files.read("/workspace/hello.txt")).bytes)).toBe("from sandbox") + + // Once warm, unknown-kind resolution detects directories cleanly. + const warmDir = yield* access.resolve({ path: `${wrkID}:/workspace` }) + expect(warmDir.externalDirectory).toMatchObject({ + action: "external_directory", + resource: `${wrkID}:/workspace/*`, + }) + }).pipe(Effect.provide(layer)) + }), + ) + + it.live("routes explicit local:/ paths back to the host from a foreign cwd and refuses non-rooted prefixes", () => + Effect.gen(function* () { + const tmp = yield* tmpdirScoped() + const layer = buildLayer({ directory: AbsolutePath.make(tmp.path), driver: makeSandboxDriver([]) }) + + yield* Effect.gen(function* () { + const environments = yield* Environments.Service + const workspaces = yield* Workspace.Service + const access = yield* FileAccess.Service + const wrkID = yield* workspaces.create({ provider: "fake" }) + const sandbox = yield* environments.get(Environment.ID.make(wrkID)) + + const localTarget = yield* access.resolve({ path: `local:${tmp.path}/spill.txt`, kind: "file" }).pipe( + Effect.provideService(Environment.CurrentWorkingDirectory, { + absolute: AbsolutePath.make("/workspace"), + environment: sandbox, + }), + ) + expect(localTarget.environment.id).toBe(Environment.localID) + expect(`${localTarget.absolute}`).toBe(`${tmp.path}/spill.txt`) + + for (const bad of [`${wrkID}:~/notes`, `${wrkID}:relative`, "local:relative"]) { + const err = yield* access.locate(bad).pipe(Effect.flip) + expect(err.cause).toBeInstanceOf(MachinePath.NotAbsolute) + } + }).pipe(Effect.provide(layer)) + }), + ) + + it.live("does not provision a cold sandbox when authorizeRead is denied", () => + Effect.gen(function* () { + const tmp = yield* tmpdirScoped() + const calls: string[] = [] + const layer = buildLayer({ + directory: AbsolutePath.make(tmp.path), + driver: makeSandboxDriver(calls), + denyExternal: true, + }) + + yield* Effect.gen(function* () { + const workspaces = yield* Workspace.Service + const access = yield* FileAccess.Service + const wrkID = yield* workspaces.create({ provider: "fake" }) + + const denied = yield* access + .authorizeRead(`${wrkID}:/workspace/secret.txt`, { + sessionID: SessionSchema.ID.make("ses_deny"), + agent: Agent.ID.make("build"), + messageID: SessionMessage.ID.make("msg_1"), + id: Tool.CallID.make("call_1"), + }) + .pipe(Effect.flip) + expect(denied._tag).toBe("Permission.BlockedError") + expect(calls).toEqual([]) + }).pipe(Effect.provide(layer)) + }), + ) + + it.live("confines a sandboxed workspace Location so local:/ cannot escape to the host", () => + Effect.gen(function* () { + const tmp = yield* tmpdirScoped() + const calls: string[] = [] + const wrkID = Workspace.ID.make("wrk_confined") + const layer = buildLayer({ + directory: AbsolutePath.make("/workspace"), + dataDirectory: tmp.path, + workspaceID: wrkID, + driver: makeSandboxDriver(calls), + }) + + yield* Effect.gen(function* () { + const access = yield* FileAccess.Service + for (const attempt of ["local:/etc/passwd", "local:~/secret", `${wrkID}:~/secret`]) { + const target = yield* access.resolve({ path: attempt, kind: "file" }) + // Stays inside the sandbox environment instead of jumping to the server host. + expect(target.environment.id).toBe(Environment.ID.make(wrkID)) + } + }).pipe(Effect.provide(layer)) + }), + ) + + it.live("treats local:/ and wrk_...:/ as plain paths when the machines flag is off", () => + Effect.gen(function* () { + const tmp = yield* tmpdirScoped() + const calls: string[] = [] + const layer = buildLayer({ + directory: AbsolutePath.make(tmp.path), + driver: makeSandboxDriver(calls), + machinesFlag: false, + }) + + yield* Effect.gen(function* () { + const access = yield* FileAccess.Service + const localPrefixed = yield* access.resolve({ path: "local:/x", kind: "file" }) + expect(localPrefixed.environment.id).toBe(Environment.localID) + expect(`${localPrefixed.absolute}`).toBe(`${tmp.path}/local:/x`) + + const wrkPrefixed = yield* access.resolve({ path: "wrk_other:/x", kind: "file" }) + expect(wrkPrefixed.environment.id).toBe(Environment.localID) + expect(`${wrkPrefixed.absolute}`).toBe(`${tmp.path}/wrk_other:/x`) + expect(calls).toEqual([]) + }).pipe(Effect.provide(layer)) + }), + ) + + it.live("skips AGENTS.md probe on a cold lazy sandbox and loads it once connected", () => + Effect.gen(function* () { + const tmp = yield* tmpdirScoped() + const calls: string[] = [] + const layer = buildLayer({ directory: AbsolutePath.make(tmp.path), driver: makeSandboxDriver(calls) }) + + yield* Effect.gen(function* () { + const db = (yield* Database.Service).db + const environments = yield* Environments.Service + const workspaces = yield* Workspace.Service + const cwdInstructions = yield* SessionCwdInstructions.Service + + const dir = AbsolutePath.make(tmp.path) + const sessionID = SessionSchema.ID.make("ses_lazy_sandbox_inst") + yield* db + .insert(ProjectTable) + .values({ id: Project.ID.global, worktree: dir, sandboxes: [] }) + .onConflictDoNothing() + .run() + .pipe(Effect.orDie) + yield* db + .insert(SessionTable) + .values({ id: sessionID, project_id: Project.ID.global, directory: dir, slug: "lazy", version: "test" }) + .run() + .pipe(Effect.orDie) + + const wrkID = yield* workspaces.create({ provider: "fake" }) + const wrkEnvID = Environment.ID.make(wrkID) + const sandbox = yield* environments.get(wrkEnvID) + const cwd: SessionCwd.Resolved = { absolute: AbsolutePath.make("/workspace"), environment: sandbox } + + // Step 1: sandbox is cold -> instruction read returns removed without waking or provisioning. + const coldList = yield* cwdInstructions.load(cwd, sessionID) + const coldObs = yield* InstructionState.observe(db, coldList, sessionID) + expect(coldObs.current["core/cwd-instructions"]).toBeUndefined() + expect(calls).toEqual([]) + + // First tool wakes the sandbox and writes AGENTS.md. + yield* sandbox.files.mkdir("/workspace") + yield* sandbox.files.write("/workspace/AGENTS.md", bytes("Sandbox rules")) + expect(calls).toEqual(["create", "connect"]) + + // Step 2: sandbox is now ready -> AGENTS.md loads automatically. + const warmList = yield* cwdInstructions.load(cwd, sessionID) + const warmObs = yield* InstructionState.observe(db, warmList, sessionID) + expect(warmObs.current["core/cwd-instructions"]).toBeDefined() + const rendered = yield* readInitial(warmList) + expect(rendered.text).toContain(`Instructions from: ${wrkID}:/workspace/AGENTS.md\nSandbox rules`) + }).pipe(Effect.provide(layer)) + }), + ) +}) diff --git a/packages/core/test/fixture/codemode.ts b/packages/core/test/fixture/codemode.ts index a05bb42520c..e5ad9d51911 100644 --- a/packages/core/test/fixture/codemode.ts +++ b/packages/core/test/fixture/codemode.ts @@ -1,5 +1,6 @@ import { CodeModeTool } from "@opencode/core/codemode/tool" import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" +import { Environments } from "@opencode/core/environment/environments" import { Environment } from "@opencode/core/environment/index" import { FileAccess } from "@opencode/core/file-access" import { FileMutation } from "@opencode/core/file-mutation" @@ -48,6 +49,12 @@ export const codeModeServices = ( get: (id) => Effect.fail(new Machines.NotFound({ machine: id })), }), ), + Environments.node.replace( + Layer.mock(Environments.Service, { + lookup: (id) => Effect.fail(new Machines.NotFound({ machine: id })), + ready: () => Effect.succeed(true), + }), + ), Permission.node.replace(permissionLayer(permission)), ], ), diff --git a/packages/core/test/session-cwd.test.ts b/packages/core/test/session-cwd.test.ts index 99c766847b5..205e8a5915c 100644 --- a/packages/core/test/session-cwd.test.ts +++ b/packages/core/test/session-cwd.test.ts @@ -7,6 +7,7 @@ import { Agent } from "@opencode/core/agent" import { Bus } from "@opencode/core/bus" import { Config } from "@opencode/core/config" import { Database } from "@opencode/core/database/database" +import { Environments } from "@opencode/core/environment/environments" import { Environment } from "@opencode/core/environment/index" import { FileAccess } from "@opencode/core/file-access" import { FileMutation } from "@opencode/core/file-mutation" @@ -207,6 +208,7 @@ const graph = (fixture: Fixture, realPermissions = false) => Tool.node, toolPlugins, Environment.node, + Environments.node, FileAccess.node, FileMutation.node, Flag.node,