Skip to content

Commit 3b5433d

Browse files
committed
feat(opencode): enforce PTY session ownership and expose terminal context
PTY routes accept a sessionID claim; a foreign claim gets 404 with no existence leak, unowned PTYs keep legacy behavior. New terminal_context config (off default / tool-only / ambient / ambient-full) gates a terminal tool for fetching captured commands plus a bounded ambient context block, with failed-command output auto-attached at ambient-full. Refs anomalyco#43758
1 parent f179dd5 commit 3b5433d

8 files changed

Lines changed: 410 additions & 18 deletions

File tree

‎packages/core/src/v1/config/config.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,10 @@ export const Info = Schema.Struct({
3434
description: "JSON schema reference for configuration validation",
3535
}),
3636
shell: Schema.optional(Schema.String).annotate({ description: "Default shell to use for terminal and bash tool" }),
37+
terminal_context: Schema.optional(Schema.Literals(["off", "tool-only", "ambient", "ambient-full"])).annotate({
38+
description:
39+
"How GUI terminal activity reaches the model: 'off' (default) exposes nothing, 'tool-only' allows fetching via the terminal tool, 'ambient' additionally injects bounded command/exit-code metadata each turn, 'ambient-full' also auto-attaches bounded output of failed commands",
40+
}),
3741
logLevel: Schema.optional(LogLevelRef).annotate({ description: "Log level" }),
3842
server: Schema.optional(ConfigServerV1.Server).annotate({
3943
description: "Server configuration for opencode serve and web commands",

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

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { Pty } from "@opencode-ai/core/pty"
22
import { PtyTicket } from "@opencode-ai/core/pty/ticket"
33
import { PtyID } from "@opencode-ai/core/pty/schema"
4+
import { SessionID } from "@opencode-ai/schema/session-id"
45
import { PTY_CONNECT_TICKET_QUERY } from "@/server/shared/pty-ticket"
56
import { Schema } from "effect"
67
import { HttpApi, HttpApiEndpoint, HttpApiError, HttpApiGroup, OpenApi } from "effect/unstable/httpapi"
@@ -16,9 +17,15 @@ import { described } from "./metadata"
1617

1718
const root = "/pty"
1819
export const Params = Schema.Struct({ ptyID: PtyID })
20+
// Session-ownership claim; enforced against Pty.Info.sessionID when both are present.
21+
export const SessionQuery = Schema.Struct({
22+
...WorkspaceRoutingQueryFields,
23+
sessionID: Schema.optional(SessionID),
24+
})
1925
export const CursorQuery = Schema.Struct({
2026
...WorkspaceRoutingQueryFields,
2127
cursor: Schema.optional(Schema.String),
28+
sessionID: Schema.optional(SessionID),
2229
})
2330
export const ShellItem = Schema.Struct({
2431
path: Schema.String,
@@ -52,7 +59,7 @@ export const PtyApi = HttpApi.make("pty")
5259
}),
5360
),
5461
HttpApiEndpoint.get("list", PtyPaths.list, {
55-
query: WorkspaceRoutingQuery,
62+
query: SessionQuery,
5663
success: described(Schema.Array(Pty.Info), "List of sessions"),
5764
}).annotateMerge(
5865
OpenApi.annotations({
@@ -75,7 +82,7 @@ export const PtyApi = HttpApi.make("pty")
7582
),
7683
HttpApiEndpoint.get("get", PtyPaths.get, {
7784
params: { ptyID: PtyID },
78-
query: WorkspaceRoutingQuery,
85+
query: SessionQuery,
7986
success: described(Pty.Info, "Session info"),
8087
error: PtyNotFoundError,
8188
}).annotateMerge(
@@ -87,7 +94,7 @@ export const PtyApi = HttpApi.make("pty")
8794
),
8895
HttpApiEndpoint.put("update", PtyPaths.update, {
8996
params: { ptyID: PtyID },
90-
query: WorkspaceRoutingQuery,
97+
query: SessionQuery,
9198
payload: Pty.UpdateInput,
9299
success: described(Pty.Info, "Updated session"),
93100
error: [PtyNotFoundError, HttpApiError.BadRequest],
@@ -100,7 +107,7 @@ export const PtyApi = HttpApi.make("pty")
100107
),
101108
HttpApiEndpoint.delete("remove", PtyPaths.remove, {
102109
params: { ptyID: PtyID },
103-
query: WorkspaceRoutingQuery,
110+
query: SessionQuery,
104111
success: described(Schema.Boolean, "Session removed"),
105112
error: PtyNotFoundError,
106113
}).annotateMerge(
@@ -112,7 +119,7 @@ export const PtyApi = HttpApi.make("pty")
112119
),
113120
HttpApiEndpoint.post("connectToken", PtyPaths.connectToken, {
114121
params: { ptyID: PtyID },
115-
query: WorkspaceRoutingQuery,
122+
query: SessionQuery,
116123
success: described(PtyTicket.ConnectToken, "WebSocket connect token"),
117124
error: [PtyForbiddenError, PtyNotFoundError],
118125
}).annotateMerge(
@@ -155,7 +162,7 @@ export const PtyConnectApi = HttpApi.make("pty-connect").add(
155162
...operation,
156163
parameters: [
157164
...(operation.parameters ?? []),
158-
...["directory", "workspace", "cursor", PTY_CONNECT_TICKET_QUERY].map((name) => ({
165+
...["directory", "workspace", "cursor", "sessionID", PTY_CONNECT_TICKET_QUERY].map((name) => ({
159166
in: "query",
160167
name,
161168
schema: { type: "string" },

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

Lines changed: 35 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,13 @@ const ticketScope = Effect.gen(function* () {
3535
return { directory: instance?.directory, workspaceID }
3636
})
3737

38+
// Cross-session isolation: a request claiming a session may not touch a PTY owned by another
39+
// session (404, not 403, to avoid leaking existence). Requests without a claim and unowned
40+
// PTYs keep legacy workspace-scoped behavior.
41+
function ownedByOther(info: { sessionID?: string }, sessionID: string | undefined) {
42+
return info.sessionID !== undefined && sessionID !== undefined && info.sessionID !== sessionID
43+
}
44+
3845
// Legacy surface compatibility: before exited-session retention, sessions vanished the moment
3946
// their process exited. These routes preserve that observable behavior — exited sessions are
4047
// invisible here — while the canonical /api/pty surface exposes them until removal.
@@ -61,8 +68,8 @@ export const ptyHandlers = HttpApiBuilder.group(InstanceHttpApi, "pty", (handler
6168
return yield* Effect.promise(() => Shell.list())
6269
})
6370

64-
const list = Effect.fn("PtyHttpApi.list")(function* () {
65-
const sessions = yield* pty(Pty.Service.use((service) => service.list()))
71+
const list = Effect.fn("PtyHttpApi.list")(function* (ctx: { query: { sessionID?: string } }) {
72+
const sessions = yield* pty(Pty.Service.use((service) => service.list({ sessionID: ctx.query.sessionID })))
6673
return sessions.filter((info) => info.status === "running")
6774
})
6875

@@ -81,7 +88,10 @@ export const ptyHandlers = HttpApiBuilder.group(InstanceHttpApi, "pty", (handler
8188
)
8289
})
8390

84-
const get = Effect.fn("PtyHttpApi.get")(function* (ctx: { params: { ptyID: PtyID } }) {
91+
const get = Effect.fn("PtyHttpApi.get")(function* (ctx: {
92+
params: { ptyID: PtyID }
93+
query: { sessionID?: string }
94+
}) {
8595
return yield* pty(Pty.Service.use((service) => service.get(ctx.params.ptyID))).pipe(
8696
Effect.catchTag(
8797
"Pty.NotFoundError",
@@ -92,7 +102,7 @@ export const ptyHandlers = HttpApiBuilder.group(InstanceHttpApi, "pty", (handler
92102
}),
93103
),
94104
Effect.flatMap((info) =>
95-
info.status === "running"
105+
info.status === "running" && !ownedByOther(info, ctx.query.sessionID)
96106
? Effect.succeed(info)
97107
: new ApiError.PtyNotFoundError({
98108
ptyID: ctx.params.ptyID,
@@ -104,6 +114,7 @@ export const ptyHandlers = HttpApiBuilder.group(InstanceHttpApi, "pty", (handler
104114

105115
const update = Effect.fn("PtyHttpApi.update")(function* (ctx: {
106116
params: { ptyID: PtyID }
117+
query: { sessionID?: string }
107118
payload: typeof Pty.UpdateInput.Type
108119
}) {
109120
yield* get(ctx)
@@ -126,7 +137,10 @@ export const ptyHandlers = HttpApiBuilder.group(InstanceHttpApi, "pty", (handler
126137
)
127138
})
128139

129-
const remove = Effect.fn("PtyHttpApi.remove")(function* (ctx: { params: { ptyID: PtyID } }) {
140+
const remove = Effect.fn("PtyHttpApi.remove")(function* (ctx: {
141+
params: { ptyID: PtyID }
142+
query: { sessionID?: string }
143+
}) {
130144
yield* get(ctx)
131145
yield* pty(Pty.Service.use((service) => service.remove(ctx.params.ptyID))).pipe(
132146
Effect.catchTag(
@@ -141,12 +155,15 @@ export const ptyHandlers = HttpApiBuilder.group(InstanceHttpApi, "pty", (handler
141155
return true
142156
})
143157

144-
const connectToken = Effect.fn("PtyHttpApi.connectToken")(function* (ctx: { params: { ptyID: PtyID } }) {
158+
const connectToken = Effect.fn("PtyHttpApi.connectToken")(function* (ctx: {
159+
params: { ptyID: PtyID }
160+
query: { sessionID?: string }
161+
}) {
145162
const request = yield* HttpServerRequest.HttpServerRequest
146163
if (request.headers[PTY_CONNECT_TOKEN_HEADER] !== PTY_CONNECT_TOKEN_HEADER_VALUE || !validOrigin(request, cors))
147164
return yield* new ApiError.PtyForbiddenError({ message: "Invalid PTY connect token request" })
148165
yield* get(ctx)
149-
return yield* tickets.issue({ ptyID: ctx.params.ptyID, ...(yield* ticketScope) })
166+
return yield* tickets.issue({ ptyID: ctx.params.ptyID, ...(yield* ticketScope), sessionID: ctx.query.sessionID })
150167
})
151168

152169
return handlers
@@ -184,18 +201,24 @@ export const ptyConnectHandlers = HttpApiBuilder.group(PtyConnectApi, "pty-conne
184201
params: { ptyID: PtyID }
185202
request: HttpServerRequest.HttpServerRequest
186203
}) {
187-
const exists = yield* pty(Pty.Service.use((service) => service.get(ctx.params.ptyID))).pipe(
188-
Effect.map((info) => info.status === "running"),
189-
Effect.catchTag("Pty.NotFoundError", () => Effect.succeed(false)),
204+
const info = yield* pty(Pty.Service.use((service) => service.get(ctx.params.ptyID))).pipe(
205+
Effect.map((found) => (found.status === "running" ? found : undefined)),
206+
Effect.catchTag("Pty.NotFoundError", () => Effect.succeed(undefined)),
190207
)
191-
if (!exists) return HttpServerResponse.empty({ status: 404 })
208+
if (!info) return HttpServerResponse.empty({ status: 404 })
192209

193210
const query = Schema.decodeUnknownOption(CursorQuery)(yield* HttpServerRequest.ParsedSearchParams)
194211
if (Option.isNone(query)) return HttpServerResponse.empty({ status: 400 })
212+
if (ownedByOther(info, query.value.sessionID)) return HttpServerResponse.empty({ status: 404 })
195213
const ticket = new URL(ctx.request.url, "http://localhost").searchParams.get(PTY_CONNECT_TICKET_QUERY)
196214
if (ticket) {
197215
const valid = validOrigin(ctx.request, cors)
198-
? yield* tickets.consume({ ticket, ptyID: ctx.params.ptyID, ...(yield* ticketScope) })
216+
? yield* tickets.consume({
217+
ticket,
218+
ptyID: ctx.params.ptyID,
219+
...(yield* ticketScope),
220+
sessionID: query.value.sessionID,
221+
})
199222
: false
200223
if (!valid) return HttpServerResponse.empty({ status: 403 })
201224
}

‎packages/opencode/src/session/prompt.ts‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import path from "path"
44
import { SessionV1 } from "@opencode-ai/core/v1/session"
55
import os from "os"
66
import { SessionID, MessageID, PartID } from "./schema"
7+
import { PtyCapture } from "@opencode-ai/core/pty/capture"
78
import { MessageV2 } from "./message-v2"
89
import { SessionRevert } from "./revert"
910
import { Session } from "./session"
@@ -128,6 +129,7 @@ const layer = Layer.effect(
128129
const lsp = yield* LSP.Service
129130
const registry = yield* ToolRegistry.Service
130131
const truncate = yield* Truncate.Service
132+
const capture = yield* PtyCapture.Service
131133
const image = yield* Image.Service
132134
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner
133135
const scope = yield* Scope.Scope
@@ -1078,6 +1080,62 @@ const layer = Layer.effect(
10781080
throw new Error("Impossible")
10791081
})
10801082

1083+
// Ambient terminal context (tier 1): bounded metadata about commands captured from this
1084+
// session's integrated terminals, injected as a non-persisted synthetic part each turn.
1085+
// 'ambient-full' additionally inlines bounded output of failures since the last user message.
1086+
const injectTerminalContext = Effect.fn("SessionPrompt.terminalContext")(function* (
1087+
sessionID: SessionID,
1088+
msgs: SessionV1.WithParts[],
1089+
) {
1090+
const mode = (yield* config.get()).terminal_context ?? "off"
1091+
if (mode !== "ambient" && mode !== "ambient-full") return
1092+
const lastUser = msgs.findLast((msg) => msg.info.role === "user")
1093+
if (!lastUser) return
1094+
const commands = yield* capture.list(sessionID)
1095+
if (commands.length === 0) return
1096+
const recent = commands.slice(-5)
1097+
const lines = recent.map((command) => {
1098+
const state = command.status === "running" ? "running" : `exit ${command.exitCode ?? "?"}`
1099+
const text = command.command.length > 120 ? command.command.slice(0, 120) + "..." : command.command
1100+
return `[${command.id}] (${state}) $ ${text}`
1101+
})
1102+
const block = [
1103+
"<terminal-context>",
1104+
"Commands the user ran in this chat session's integrated terminal (most recent last).",
1105+
"Use the terminal tool with action 'output' and a commandID to read a command's captured output.",
1106+
...lines,
1107+
]
1108+
if (mode === "ambient-full") {
1109+
const since = lastUser.info.time.created
1110+
const failed = recent
1111+
.filter(
1112+
(command) =>
1113+
command.status === "completed" && (command.exitCode ?? 0) !== 0 && (command.time.end ?? 0) >= since,
1114+
)
1115+
.slice(-2)
1116+
for (const info of failed) {
1117+
const record = yield* capture.output(sessionID, info.id)
1118+
if (!record) continue
1119+
const gap = record.info.truncated ? "\n... (truncated) ...\n" : ""
1120+
const full = record.head + gap + record.tail
1121+
const tail = full.length > 2000 ? "..." + full.slice(-2000) : full
1122+
block.push(
1123+
`--- output of failed [${info.id}] $ ${info.command} (exit ${info.exitCode}) ---`,
1124+
tail || "(no output)",
1125+
)
1126+
}
1127+
}
1128+
block.push("</terminal-context>")
1129+
lastUser.parts.push({
1130+
id: PartID.ascending(),
1131+
messageID: lastUser.info.id,
1132+
sessionID,
1133+
type: "text",
1134+
text: block.join("\n"),
1135+
synthetic: true,
1136+
})
1137+
})
1138+
10811139
const runLoop: (sessionID: SessionID) => Effect.Effect<SessionV1.WithParts> = Effect.fn("SessionPrompt.run")(
10821140
function* (sessionID: SessionID) {
10831141
const ctx = yield* InstanceState.context
@@ -1182,6 +1240,7 @@ const layer = Layer.effect(
11821240
Effect.provideService(FSUtil.Service, fsys),
11831241
Effect.provideService(Session.Service, sessions),
11841242
)
1243+
yield* injectTerminalContext(sessionID, msgs)
11851244

11861245
const msg: SessionV1.Assistant = {
11871246
id: MessageID.ascending(),
@@ -1625,6 +1684,7 @@ export const node = LayerNode.make({
16251684
EventV2Bridge.node,
16261685
RuntimeFlags.node,
16271686
Database.node,
1687+
PtyCapture.node,
16281688
],
16291689
})
16301690

‎packages/opencode/src/tool/registry.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import { Provider } from "@/provider/provider"
2727

2828
import { WebSearchTool } from "./websearch"
2929
import { LspTool } from "./lsp"
30+
import { TerminalTool } from "./terminal"
3031
import * as Truncate from "./truncate"
3132
import { ApplyPatchTool } from "./apply_patch"
3233
import { Glob } from "@opencode-ai/core/util/glob"
@@ -54,6 +55,7 @@ import { ModelV2 } from "@opencode-ai/core/model"
5455
import { MCP } from "@/mcp"
5556
import { PermissionV1 } from "@opencode-ai/core/v1/permission"
5657
import { McpCatalog } from "@/mcp/catalog"
58+
import { PtyCapture } from "@opencode-ai/core/pty/capture"
5759

5860
export function webSearchEnabled(providerID: ProviderV2.ID, flags = { exa: false, parallel: false }) {
5961
return (
@@ -114,6 +116,7 @@ const layer = Layer.effect(
114116
const greptool = yield* GrepTool
115117
const patchtool = yield* ApplyPatchTool
116118
const skilltool = yield* SkillTool
119+
const terminaltool = yield* TerminalTool
117120
const agent = yield* Agent.Service
118121
const codeMode = flags.experimentalCodeMode ? yield* Effect.promise(() => import("./code-mode")) : undefined
119122
const codeModeTool = codeMode ? yield* codeMode.CodeModeTool : undefined
@@ -205,6 +208,7 @@ const layer = Layer.effect(
205208

206209
yield* config.get()
207210
const questionEnabled = ["app", "cli", "desktop"].includes(flags.client) || flags.enableQuestionTool
211+
const terminalEnabled = ((yield* config.get()).terminal_context ?? "off") !== "off"
208212

209213
const tool = yield* Effect.all({
210214
invalid: Tool.init(invalid),
@@ -223,6 +227,7 @@ const layer = Layer.effect(
223227
question: Tool.init(question),
224228
lsp: Tool.init(lsptool),
225229
plan: Tool.init(plan),
230+
terminal: Tool.init(terminaltool),
226231
...(codeModeTool ? { execute: Tool.init(codeModeTool) } : {}),
227232
})
228233

@@ -243,6 +248,7 @@ const layer = Layer.effect(
243248
tool.search,
244249
tool.skill,
245250
tool.patch,
251+
...(terminalEnabled ? [tool.terminal] : []),
246252
...(tool.execute ? [tool.execute] : []),
247253
...(flags.experimentalLspTool ? [tool.lsp] : []),
248254
...(flags.experimentalPlanMode && flags.client === "cli" ? [tool.plan] : []),
@@ -449,6 +455,7 @@ export const node = LayerNode.make({
449455
MCP.node,
450456
Database.node,
451457
Ripgrep.node,
458+
PtyCapture.node,
452459
],
453460
})
454461

0 commit comments

Comments
 (0)