GeezerVison is showing github.com — fix(server): apply plugin pty environment (#32296) · rodboev/opencode@7ad68f8
File treeExpand file treeCollapse file tree Open diff view settings server/routes/instance/httpapi
Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: CONTEXT.md +5Lines changed: 5 additions & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
@@ -52,6 +52,9 @@ _Avoid_: Request body, wire options | 52 | 52 | **Generation Controls**: | 53 | 53 | Provider-neutral sampling and output controls, partitioned from provider semantics and compatibility wire fields when model metadata enters the Catalog. | 54 | 54 |
| | 55 | +**PTY Environment**: | | 56 | +The host-supplied environment overlay applied by the server when creating a PTY, observed for the request Location and resolved PTY working directory. | | 57 | + | 55 | 58 | ## Relationships | 56 | 59 |
| 57 | 60 | - A **System Context** is an opaque carrier composed from zero or more **Context Sources**. | @@ -99,6 +102,8 @@ Provider-neutral sampling and output controls, partitioned from provider semanti | 99 | 102 | - A model/provider switch always starts a new **Context Epoch** while preserving chronological conversation history. | 100 | 103 | - **Model Request Options** remain provider-semantic through Catalog resolution. The Session runner maps them into the LLM package's provider-option namespace; the selected protocol adapter alone owns provider wire encoding. | 101 | 104 | - **Generation Controls**, protocol-semantic **Model Request Options**, and compatibility request body fields are separate Catalog domains. A shared ingestion adapter partitions legacy and models.dev AI-SDK-shaped options before routing. | | 105 | +- The **PTY Environment** is a server concern rather than a Core PTY concern. PTY creation merges caller values, then the host overlay, then Core-forced terminal invariants such as `TERM` and `OPENCODE_TERMINAL`. | | 106 | +- A **PTY Environment** adapter observes plugins in the request Location while passing the resolved PTY working directory to the hook; standalone servers use an empty adapter. | 102 | 107 | - A **Mid-Conversation System Message** lowers to the provider's native chronological instruction role when supported and to a wrapped chronological fallback otherwise. | 103 | 108 | - When the effective aggregate instruction set changes, its **Mid-Conversation System Message** includes the complete current ordered set and supersedes the prior aggregate value; when no ambient instructions remain, the message states that previously loaded instructions no longer apply. | 104 | 109 | - Ambient project instruction discovery honors `OPENCODE_DISABLE_PROJECT_CONFIG`; global instructions remain eligible. | |
Collapse file Copy file name to clipboardExpand all lines: packages/core/src/pty.ts -2Lines changed: 0 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -197,8 +197,6 @@ export const layer = Layer.effect( | 197 | 197 | const command = input.command || Shell.preferred(Config.latest(yield* config.entries(), "shell")) | 198 | 198 | const args = Shell.login(command) ? [...(input.args ?? []), "-l"] : [...(input.args ?? [])] | 199 | 199 | const cwd = input.cwd || location.directory | 200 | | - // TODO: Apply plugin shell.env environment augmentation once V2 plugin hooks exist; legacy | 201 | | - // routes merge plugin-provided values into input.env at the boundary. | 202 | 200 | const env = { | 203 | 201 | ...process.env, | 204 | 202 | ...input.env, | |
Collapse file Copy file name to clipboard +24Lines changed: 24 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +export * as PluginPtyEnvironment from "./pty-environment" | | 2 | + | | 3 | +import { PtyEnvironment } from "@opencode-ai/server/pty-environment" | | 4 | +import { Effect, Layer } from "effect" | | 5 | +import { InstanceStore } from "@/project/instance-store" | | 6 | +import { Plugin } from "." | | 7 | + | | 8 | +export const layer = Layer.effect( | | 9 | + PtyEnvironment.Service, | | 10 | + Effect.gen(function* () { | | 11 | + const plugin = yield* Plugin.Service | | 12 | + const instances = yield* InstanceStore.Service | | 13 | + return PtyEnvironment.Service.of({ | | 14 | + get: Effect.fn("PtyEnvironment.get")(function* (input) { | | 15 | + return yield* instances.provide( | | 16 | + { directory: input.directory }, | | 17 | + plugin | | 18 | + .trigger("shell.env", { cwd: input.cwd }, { env: {} as Record<string, string> }) | | 19 | + .pipe(Effect.map((result) => result.env)), | | 20 | + ) | | 21 | + }), | | 22 | + }) | | 23 | + }), | | 24 | +) |
Collapse file Copy file name to clipboardExpand all lines: packages/opencode/src/server/routes/instance/httpapi/server.ts +2Lines changed: 2 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -21,6 +21,7 @@ import { MCP } from "@/mcp" | 21 | 21 | import { McpAuth } from "@/mcp/auth" | 22 | 22 | import { Permission } from "@/permission" | 23 | 23 | import { Plugin } from "@/plugin" | | 24 | +import { PluginPtyEnvironment } from "@/plugin/pty-environment" | 24 | 25 | import { InstanceStore } from "@/project/instance-store" | 25 | 26 | import { Project } from "@/project/project" | 26 | 27 | import { Vcs } from "@/project/vcs" | @@ -166,6 +167,7 @@ const instanceRoutes = instanceApiRoutes.pipe( | 166 | 167 | ) | 167 | 168 | const serverRoutes = HttpApiBuilder.layer(Api).pipe( | 168 | 169 | Layer.provide(handlers), | | 170 | + Layer.provide(PluginPtyEnvironment.layer), | 169 | 171 | Layer.provide([serverHttpApiAuthLayer, v2SchemaErrorLayer]), | 170 | 172 | ) | 171 | 173 |
| |
Collapse file Copy file name to clipboardExpand all lines: packages/opencode/test/server/httpapi-v2-pty.test.ts +77Lines changed: 77 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -3,6 +3,9 @@ import { Context, Config as EffectConfig, Effect, Layer, Queue, Schema } from "e | 3 | 3 | import { NodeHttpServer, NodeServices } from "@effect/platform-node" | 4 | 4 | import { HttpClient, HttpClientRequest, HttpRouter, HttpServer } from "effect/unstable/http" | 5 | 5 | import * as Socket from "effect/unstable/socket/Socket" | | 6 | +import path from "path" | | 7 | +import { pathToFileURL } from "url" | | 8 | +import { mkdir } from "fs/promises" | 6 | 9 | import { Location } from "@opencode-ai/core/location" | 7 | 10 | import { Pty } from "@opencode-ai/core/pty" | 8 | 11 | import { PtyTicket } from "@opencode-ai/core/pty/ticket" | @@ -171,4 +174,78 @@ describe("v2 pty HttpApi", () => { | 171 | 174 | expect(removed.status).toBe(204) | 172 | 175 | }), | 173 | 176 | ) | | 177 | + | | 178 | + ;(process.platform === "win32" ? effectIt.live.skip : effectIt.live)( | | 179 | + "applies plugin shell environment before forced PTY values", | | 180 | + () => | | 181 | + Effect.gen(function* () { | | 182 | + const dir = yield* tmpdirScoped({ git: true, config: { formatter: false, lsp: false } }) | | 183 | + const plugin = path.join(dir, "plugin.ts") | | 184 | + const cwd = path.join(dir, "child") | | 185 | + yield* Effect.promise(() => mkdir(cwd)) | | 186 | + yield* Effect.promise(() => | | 187 | + Bun.write( | | 188 | + plugin, | | 189 | + [ | | 190 | + "export default async () => ({", | | 191 | + ' "shell.env": (input, output) => {', | | 192 | + ' output.env.SHARED = "plugin"', | | 193 | + ' output.env.PLUGIN = "plugin"', | | 194 | + ' output.env.TERM = "plugin"', | | 195 | + " output.env.HOOK_CWD = input.cwd", | | 196 | + " },", | | 197 | + "})", | | 198 | + "", | | 199 | + ].join("\n"), | | 200 | + ), | | 201 | + ) | | 202 | + yield* Effect.promise(() => | | 203 | + Bun.write( | | 204 | + path.join(dir, "opencode.json"), | | 205 | + JSON.stringify({ plugin: [pathToFileURL(plugin).href], formatter: false, lsp: false }), | | 206 | + ), | | 207 | + ) | | 208 | + | | 209 | + const created = yield* HttpClientRequest.post("/api/pty").pipe( | | 210 | + directoryHeader(dir), | | 211 | + HttpClientRequest.bodyJson({ | | 212 | + command: "/bin/sh", | | 213 | + args: [ | | 214 | + "-c", | | 215 | + 'printf "%s|%s|%s|%s|%s\\n" "$CALLER" "$SHARED" "$PLUGIN" "$TERM" "$HOOK_CWD"; sleep 5', | | 216 | + ], | | 217 | + cwd, | | 218 | + env: { CALLER: "caller", SHARED: "caller", TERM: "caller" }, | | 219 | + }), | | 220 | + Effect.flatMap(HttpClient.execute), | | 221 | + ) | | 222 | + expect(created.status).toBe(200) | | 223 | + const info = (yield* Schema.decodeUnknownEffect(Location.response(Pty.Info))(yield* created.json)).data | | 224 | + | | 225 | + const socket = yield* Socket.makeWebSocket( | | 226 | + `${(yield* serverUrl()).replace(/^http/, "ws")}/api/pty/${info.id}/connect?cursor=0&location[directory]=${encodeURIComponent(dir)}`, | | 227 | + { closeCodeIsError: () => false }, | | 228 | + ) | | 229 | + const messages = yield* Queue.unbounded<string>() | | 230 | + yield* socket | | 231 | + .runRaw((message) => | | 232 | + Queue.offer(messages, typeof message === "string" ? message : new TextDecoder().decode(message)), | | 233 | + ) | | 234 | + .pipe(Effect.catch(() => Effect.void), Effect.forkScoped) | | 235 | + const write = yield* socket.writer | | 236 | + | | 237 | + const takeUntil = (expected: string, seen = ""): Effect.Effect<string, unknown> => | | 238 | + Effect.gen(function* () { | | 239 | + const next = seen + (yield* Queue.take(messages).pipe(Effect.timeout("5 seconds"))) | | 240 | + if (next.includes(expected)) return next | | 241 | + return yield* takeUntil(expected, next) | | 242 | + }) | | 243 | + | | 244 | + expect(yield* takeUntil(`caller|plugin|plugin|xterm-256color|${cwd}`)).toContain( | | 245 | + `caller|plugin|plugin|xterm-256color|${cwd}`, | | 246 | + ) | | 247 | + yield* write(new Socket.CloseEvent(1000, "done")).pipe(Effect.catch(() => Effect.void)) | | 248 | + yield* HttpClientRequest.delete(`/api/pty/${info.id}`).pipe(directoryHeader(dir), HttpClient.execute) | | 249 | + }), | | 250 | + ) | 174 | 251 | }) |
Collapse file Copy file name to clipboardExpand all lines: packages/server/src/handlers/pty.ts +9-1Lines changed: 9 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -11,6 +11,7 @@ import { CorsConfig, isAllowedRequestOrigin } from "../cors" | 11 | 11 | import { ForbiddenError, PtyNotFoundError } from "../errors" | 12 | 12 | import { PTY_CONNECT_TICKET_QUERY, PTY_CONNECT_TOKEN_HEADER, PTY_CONNECT_TOKEN_HEADER_VALUE } from "../groups/pty" | 13 | 13 | import { response } from "../groups/location" | | 14 | +import { PtyEnvironment } from "../pty-environment" | 14 | 15 |
| 15 | 16 | const ticketScope = Effect.gen(function* () { | 16 | 17 | const location = yield* Location.Service | @@ -21,6 +22,7 @@ export const PtyHandler = HttpApiBuilder.group(Api, "server.pty", (handlers) => | 21 | 22 | Effect.gen(function* () { | 22 | 23 | const tickets = yield* PtyTicket.Service | 23 | 24 | const cors = yield* CorsConfig | | 25 | + const environment = yield* PtyEnvironment.Service | 24 | 26 |
| 25 | 27 | return handlers | 26 | 28 | .handle( | @@ -33,11 +35,17 @@ export const PtyHandler = HttpApiBuilder.group(Api, "server.pty", (handlers) => | 33 | 35 | "pty.create", | 34 | 36 | Effect.fn(function* (ctx) { | 35 | 37 | const pty = yield* Pty.Service | | 38 | + const location = yield* Location.Service | | 39 | + const cwd = ctx.payload.cwd || location.directory | 36 | 40 | return yield* response( | 37 | 41 | pty.create({ | 38 | 42 | ...ctx.payload, | 39 | 43 | args: ctx.payload.args ? [...ctx.payload.args] : undefined, | 40 | | - env: ctx.payload.env ? { ...ctx.payload.env } : undefined, | | 44 | + cwd, | | 45 | + env: { | | 46 | + ...ctx.payload.env, | | 47 | + ...(yield* environment.get({ directory: location.directory, cwd })), | | 48 | + }, | 41 | 49 | }), | 42 | 50 | ) | 43 | 51 | }), | |
Collapse file Copy file name to clipboard +16Lines changed: 16 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +export * as PtyEnvironment from "./pty-environment" | | 2 | + | | 3 | +import { Context, Effect, Layer } from "effect" | | 4 | + | | 5 | +export interface Interface { | | 6 | + readonly get: (input: { directory: string; cwd: string }) => Effect.Effect<Record<string, string>> | | 7 | +} | | 8 | + | | 9 | +export class Service extends Context.Service<Service, Interface>()("@opencode/ServerPtyEnvironment") {} | | 10 | + | | 11 | +export const defaultLayer = Layer.succeed( | | 12 | + Service, | | 13 | + Service.of({ | | 14 | + get: () => Effect.succeed({}), | | 15 | + }), | | 16 | +) |
Collapse file Copy file name to clipboardExpand all lines: packages/server/src/routes.ts +2Lines changed: 2 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -9,10 +9,12 @@ import { ServerAuth } from "./auth" | 9 | 9 | import { handlers } from "./handlers" | 10 | 10 | import { authorizationLayer } from "./middleware/authorization" | 11 | 11 | import { schemaErrorLayer } from "./middleware/schema-error" | | 12 | +import { PtyEnvironment } from "./pty-environment" | 12 | 13 |
| 13 | 14 | export function createRoutes(password?: string) { | 14 | 15 | return HttpApiBuilder.layer(Api, { openapiPath: "/openapi.json" }).pipe( | 15 | 16 | Layer.provide(handlers), | | 17 | + Layer.provide(PtyEnvironment.defaultLayer), | 16 | 18 | Layer.provide(authorizationLayer), | 17 | 19 | Layer.provide(schemaErrorLayer), | 18 | 20 | Layer.provide( | |
|