GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(server): apply plugin pty environment (#32296) · comio/opencode@7ad68f8

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • CONTEXT.md
  • packages
    • core/src
      • pty.ts
    • opencode
      • src
        • plugin
          • pty-environment.ts
        • server/routes/instance/httpapi
          • server.ts
      • test/server
        • httpapi-v2-pty.test.ts
    • server/src
      • handlers
        • pty.ts
      • pty-environment.ts
      • routes.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎CONTEXT.md‎

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 numberDiff line numberDiff line change
@@ -52,6 +52,9 @@ _Avoid_: Request body, wire options
5252
**Generation Controls**:
5353
Provider-neutral sampling and output controls, partitioned from provider semantics and compatibility wire fields when model metadata enters the Catalog.
5454

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+
5558
## Relationships
5659

5760
- 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
99102
- A model/provider switch always starts a new **Context Epoch** while preserving chronological conversation history.
100103
- **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.
101104
- **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.
102107
- A **Mid-Conversation System Message** lowers to the provider's native chronological instruction role when supported and to a wrapped chronological fallback otherwise.
103108
- 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.
104109
- Ambient project instruction discovery honors `OPENCODE_DISABLE_PROJECT_CONFIG`; global instructions remain eligible.
Collapse file

‎packages/core/src/pty.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/pty.ts
-2Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -197,8 +197,6 @@ export const layer = Layer.effect(
197197
const command = input.command || Shell.preferred(Config.latest(yield* config.entries(), "shell"))
198198
const args = Shell.login(command) ? [...(input.args ?? []), "-l"] : [...(input.args ?? [])]
199199
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.
202200
const env = {
203201
...process.env,
204202
...input.env,
Collapse file

‎packages/opencode/src/plugin/pty-environment.ts‎

Copy file name to clipboard
+24Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
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

‎packages/opencode/src/server/routes/instance/httpapi/server.ts‎

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 numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import { MCP } from "@/mcp"
2121
import { McpAuth } from "@/mcp/auth"
2222
import { Permission } from "@/permission"
2323
import { Plugin } from "@/plugin"
24+
import { PluginPtyEnvironment } from "@/plugin/pty-environment"
2425
import { InstanceStore } from "@/project/instance-store"
2526
import { Project } from "@/project/project"
2627
import { Vcs } from "@/project/vcs"
@@ -166,6 +167,7 @@ const instanceRoutes = instanceApiRoutes.pipe(
166167
)
167168
const serverRoutes = HttpApiBuilder.layer(Api).pipe(
168169
Layer.provide(handlers),
170+
Layer.provide(PluginPtyEnvironment.layer),
169171
Layer.provide([serverHttpApiAuthLayer, v2SchemaErrorLayer]),
170172
)
171173

Collapse file

‎packages/opencode/test/server/httpapi-v2-pty.test.ts‎

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 numberDiff line numberDiff line change
@@ -3,6 +3,9 @@ import { Context, Config as EffectConfig, Effect, Layer, Queue, Schema } from "e
33
import { NodeHttpServer, NodeServices } from "@effect/platform-node"
44
import { HttpClient, HttpClientRequest, HttpRouter, HttpServer } from "effect/unstable/http"
55
import * as Socket from "effect/unstable/socket/Socket"
6+
import path from "path"
7+
import { pathToFileURL } from "url"
8+
import { mkdir } from "fs/promises"
69
import { Location } from "@opencode-ai/core/location"
710
import { Pty } from "@opencode-ai/core/pty"
811
import { PtyTicket } from "@opencode-ai/core/pty/ticket"
@@ -171,4 +174,78 @@ describe("v2 pty HttpApi", () => {
171174
expect(removed.status).toBe(204)
172175
}),
173176
)
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+
)
174251
})
Collapse file

‎packages/server/src/handlers/pty.ts‎

Copy file name to clipboardExpand all lines: packages/server/src/handlers/pty.ts
+9-1Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { CorsConfig, isAllowedRequestOrigin } from "../cors"
1111
import { ForbiddenError, PtyNotFoundError } from "../errors"
1212
import { PTY_CONNECT_TICKET_QUERY, PTY_CONNECT_TOKEN_HEADER, PTY_CONNECT_TOKEN_HEADER_VALUE } from "../groups/pty"
1313
import { response } from "../groups/location"
14+
import { PtyEnvironment } from "../pty-environment"
1415

1516
const ticketScope = Effect.gen(function* () {
1617
const location = yield* Location.Service
@@ -21,6 +22,7 @@ export const PtyHandler = HttpApiBuilder.group(Api, "server.pty", (handlers) =>
2122
Effect.gen(function* () {
2223
const tickets = yield* PtyTicket.Service
2324
const cors = yield* CorsConfig
25+
const environment = yield* PtyEnvironment.Service
2426

2527
return handlers
2628
.handle(
@@ -33,11 +35,17 @@ export const PtyHandler = HttpApiBuilder.group(Api, "server.pty", (handlers) =>
3335
"pty.create",
3436
Effect.fn(function* (ctx) {
3537
const pty = yield* Pty.Service
38+
const location = yield* Location.Service
39+
const cwd = ctx.payload.cwd || location.directory
3640
return yield* response(
3741
pty.create({
3842
...ctx.payload,
3943
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+
},
4149
}),
4250
)
4351
}),
Collapse file

‎packages/server/src/pty-environment.ts‎

Copy file name to clipboard
+16Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
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

‎packages/server/src/routes.ts‎

Copy file name to clipboardExpand all lines: packages/server/src/routes.ts
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,12 @@ import { ServerAuth } from "./auth"
99
import { handlers } from "./handlers"
1010
import { authorizationLayer } from "./middleware/authorization"
1111
import { schemaErrorLayer } from "./middleware/schema-error"
12+
import { PtyEnvironment } from "./pty-environment"
1213

1314
export function createRoutes(password?: string) {
1415
return HttpApiBuilder.layer(Api, { openapiPath: "/openapi.json" }).pipe(
1516
Layer.provide(handlers),
17+
Layer.provide(PtyEnvironment.defaultLayer),
1618
Layer.provide(authorizationLayer),
1719
Layer.provide(schemaErrorLayer),
1820
Layer.provide(

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.