Skip to content

Commit f179dd5

Browse files
committed
feat(core): session-owned PTYs with command capture
PTYs carry an optional owning sessionID (schema, create, list filter, connect-ticket scope). bash terminals get OSC 133/633 shell integration injected via --rcfile; a stream parser records typed commands, exit codes, cwd, and bounded output into an in-memory per-session ring. Refs anomalyco#43758
1 parent bbe4c95 commit f179dd5

12 files changed

Lines changed: 674 additions & 7 deletions

File tree

‎packages/core/src/pty.ts‎

Lines changed: 67 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ import { Pty } from "@opencode-ai/schema/pty"
77
import { Config } from "./config"
88
import { EventV2 } from "./event"
99
import { Location } from "./location"
10+
import { PtyCapture } from "./pty/capture"
11+
import { PtyIntegration } from "./pty/integration"
12+
import { PtyOsc } from "./pty/osc"
1013
import { PtyID } from "./pty/schema"
1114
import { Shell } from "./shell"
1215
import { lazy } from "./util/lazy"
@@ -78,7 +81,7 @@ export class ExitedError extends Schema.TaggedErrorClass<ExitedError>()("Pty.Exi
7881
}) {}
7982

8083
export interface Interface {
81-
readonly list: () => Effect.Effect<Info[]>
84+
readonly list: (filter?: { readonly sessionID?: string }) => Effect.Effect<Info[]>
8285
readonly get: (id: PtyID) => Effect.Effect<Info, NotFoundError>
8386
readonly create: (input: CreateInput) => Effect.Effect<Info>
8487
readonly update: (id: PtyID, input: UpdateInput) => Effect.Effect<Info, NotFoundError>
@@ -95,6 +98,7 @@ const layer = Layer.effect(
9598
const events = yield* EventV2.Service
9699
const location = yield* Location.Service
97100
const config = yield* Config.Service
101+
const capture = yield* PtyCapture.Service
98102
const context = yield* Effect.context()
99103
const runFork = Effect.runForkWith(context)
100104
const sessions = new Map<PtyID, Active>()
@@ -154,8 +158,10 @@ const layer = Layer.effect(
154158
yield* removeSession(id)
155159
})
156160

157-
const list = Effect.fn("Pty.list")(function* () {
158-
return Array.from(sessions.values()).map((session) => session.info)
161+
const list = Effect.fn("Pty.list")(function* (filter?: { readonly sessionID?: string }) {
162+
const all = Array.from(sessions.values()).map((session) => session.info)
163+
if (filter?.sessionID === undefined) return all
164+
return all.filter((info) => info.sessionID === filter.sessionID)
159165
})
160166

161167
const get = Effect.fn("Pty.get")(function* (id: PtyID) {
@@ -165,11 +171,15 @@ const layer = Layer.effect(
165171
const create = Effect.fn("Pty.create")(function* (input: CreateInput) {
166172
const id = PtyID.ascending()
167173
const command = input.command || Shell.preferred(Config.latest(yield* config.entries(), "shell"))
168-
const args = Shell.login(command) ? [...(input.args ?? []), "-l"] : [...(input.args ?? [])]
174+
const baseArgs = Shell.login(command) ? [...(input.args ?? []), "-l"] : [...(input.args ?? [])]
175+
// Integration failure (e.g. tmpdir not writable) degrades to an untouched spawn.
176+
const integration = yield* Effect.promise(() => PtyIntegration.setup(command, baseArgs).catch(() => undefined))
177+
const args = integration ? integration.args : baseArgs
169178
const cwd = input.cwd || location.directory
170179
const env = {
171180
...process.env,
172181
...input.env,
182+
...integration?.env,
173183
TERM: "xterm-256color",
174184
OPENCODE_TERMINAL: "1",
175185
} as Record<string, string>
@@ -189,6 +199,7 @@ const layer = Layer.effect(
189199
cwd,
190200
status: "running",
191201
pid: proc.pid,
202+
sessionID: input.sessionID,
192203
}
193204
const session: Active = {
194205
info,
@@ -200,8 +211,50 @@ const layer = Layer.effect(
200211
listeners: [],
201212
}
202213
sessions.set(id, session)
214+
// Command capture: observe the output stream for shell-integration markers.
215+
const parser = integration ? PtyOsc.createParser() : undefined
216+
const observe = (chunk: string) => {
217+
if (!parser) return
218+
for (const event of parser.push(chunk)) {
219+
if (event.type === "cwd") {
220+
observed.cwd = event.cwd
221+
continue
222+
}
223+
if (event.type === "command-line") {
224+
observed.command = event.command
225+
continue
226+
}
227+
if (event.type === "pre-exec") {
228+
const begun = Effect.runSync(
229+
capture.begin({
230+
ptyID: id,
231+
sessionID: session.info.sessionID,
232+
terminalTitle: session.info.title,
233+
command: observed.command ?? "(unknown)",
234+
cwd: observed.cwd,
235+
}),
236+
)
237+
observed.command = undefined
238+
observed.active = begun.id
239+
runFork(events.publish(Pty.CommandEvent.Started, { command: begun }))
240+
continue
241+
}
242+
if (event.type === "output") {
243+
if (observed.active) Effect.runSync(capture.append(observed.active, PtyOsc.stripControl(event.data)))
244+
continue
245+
}
246+
if (event.type === "finished") {
247+
if (!observed.active) continue
248+
const finished = Effect.runSync(capture.finish(observed.active, event.exitCode))
249+
observed.active = undefined
250+
if (finished) runFork(events.publish(Pty.CommandEvent.Finished, { command: finished }))
251+
}
252+
}
253+
}
254+
const observed: { command?: string; cwd?: string; active?: string } = { cwd }
203255
session.listeners.push(
204256
proc.onData((chunk) => {
257+
observe(chunk)
205258
session.cursor += chunk.length
206259
for (const [token, subscriber] of session.subscribers.entries()) {
207260
if (!subscriber.active) {
@@ -224,6 +277,11 @@ const layer = Layer.effect(
224277
if (session.info.status === "exited") return
225278
session.info.status = "exited"
226279
session.info.exitCode = exitCode
280+
if (observed.active) {
281+
const finished = Effect.runSync(capture.finish(observed.active))
282+
observed.active = undefined
283+
if (finished) runFork(events.publish(Pty.CommandEvent.Finished, { command: finished }))
284+
}
227285
notifyEnd(session, { exitCode })
228286
exitOrder.push(id)
229287
runFork(
@@ -315,4 +373,8 @@ const layer = Layer.effect(
315373

316374
export const locationLayer = layer.pipe(Layer.provide(Config.locationLayer))
317375

318-
export const node = makeLocationNode({ service: Service, layer, deps: [EventV2.node, Location.node, Config.node] })
376+
export const node = makeLocationNode({
377+
service: Service,
378+
layer,
379+
deps: [EventV2.node, Location.node, Config.node, PtyCapture.node],
380+
})

‎packages/core/src/pty/capture.ts‎

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
export * as PtyCapture from "./capture"
2+
3+
import { Context, Effect, Layer } from "effect"
4+
import { Pty } from "@opencode-ai/schema/pty"
5+
import { ascending } from "@opencode-ai/schema/identifier"
6+
import { makeGlobalNode } from "../effect/app-node"
7+
8+
// In-memory, bounded capture of shell commands observed via OSC 133 markers.
9+
// Nothing is persisted to disk; rings cap retention per session.
10+
const COMMANDS_PER_SESSION = 50
11+
// Output kept per command: first HEAD_LIMIT bytes plus a rolling tail.
12+
const HEAD_LIMIT = 8 * 1024
13+
const TAIL_LIMIT = 56 * 1024
14+
15+
export type Record = {
16+
info: Pty.Command
17+
head: string
18+
tail: string
19+
}
20+
21+
export type BeginInput = {
22+
readonly ptyID: Pty.Command["ptyID"]
23+
readonly sessionID?: string
24+
readonly terminalTitle: string
25+
readonly command: string
26+
readonly cwd?: string
27+
}
28+
29+
export interface Interface {
30+
readonly begin: (input: BeginInput) => Effect.Effect<Pty.Command>
31+
readonly append: (commandID: string, data: string) => Effect.Effect<void>
32+
readonly finish: (commandID: string, exitCode?: number) => Effect.Effect<Pty.Command | undefined>
33+
readonly list: (sessionID: string) => Effect.Effect<Pty.Command[]>
34+
readonly output: (sessionID: string, commandID: string) => Effect.Effect<Record | undefined>
35+
}
36+
37+
export class Service extends Context.Service<Service, Interface>()("@opencode/PtyCapture") {}
38+
39+
const layer = Layer.sync(Service, () => {
40+
const records = new Map<string, Record>()
41+
const bySession = new Map<string, string[]>()
42+
43+
const evict = (sessionID: string) => {
44+
const ids = bySession.get(sessionID)
45+
if (!ids) return
46+
while (ids.length > COMMANDS_PER_SESSION) {
47+
const oldest = ids.shift()
48+
if (oldest) records.delete(oldest)
49+
}
50+
}
51+
52+
return Service.of({
53+
begin: Effect.fnUntraced(function* (input: BeginInput) {
54+
const info: Pty.Command = {
55+
id: "ptycmd_" + ascending(),
56+
ptyID: input.ptyID,
57+
sessionID: input.sessionID as Pty.Command["sessionID"],
58+
terminalTitle: input.terminalTitle,
59+
command: input.command,
60+
cwd: input.cwd,
61+
status: "running",
62+
time: { start: Date.now() },
63+
outputBytes: 0,
64+
truncated: false,
65+
}
66+
records.set(info.id, { info, head: "", tail: "" })
67+
if (input.sessionID) {
68+
const ids = bySession.get(input.sessionID) ?? []
69+
ids.push(info.id)
70+
bySession.set(input.sessionID, ids)
71+
evict(input.sessionID)
72+
}
73+
return info
74+
}),
75+
append: Effect.fnUntraced(function* (commandID: string, data: string) {
76+
const record = records.get(commandID)
77+
if (!record || record.info.status !== "running") return
78+
record.info = { ...record.info, outputBytes: record.info.outputBytes + data.length }
79+
if (record.head.length < HEAD_LIMIT) {
80+
const take = Math.min(HEAD_LIMIT - record.head.length, data.length)
81+
record.head += data.slice(0, take)
82+
data = data.slice(take)
83+
}
84+
if (!data) return
85+
record.tail += data
86+
if (record.tail.length > TAIL_LIMIT) {
87+
record.tail = record.tail.slice(record.tail.length - TAIL_LIMIT)
88+
record.info = { ...record.info, truncated: true }
89+
}
90+
}),
91+
finish: Effect.fnUntraced(function* (commandID: string, exitCode?: number) {
92+
const record = records.get(commandID)
93+
if (!record) return undefined
94+
record.info = {
95+
...record.info,
96+
status: "completed",
97+
exitCode,
98+
time: { ...record.info.time, end: Date.now() },
99+
}
100+
return record.info
101+
}),
102+
list: Effect.fnUntraced(function* (sessionID: string) {
103+
const ids = bySession.get(sessionID) ?? []
104+
return ids.flatMap((id) => {
105+
const record = records.get(id)
106+
return record ? [record.info] : []
107+
})
108+
}),
109+
output: Effect.fnUntraced(function* (sessionID: string, commandID: string) {
110+
const record = records.get(commandID)
111+
if (!record) return undefined
112+
if (record.info.sessionID !== sessionID) return undefined
113+
return record
114+
}),
115+
})
116+
})
117+
118+
export const node = makeGlobalNode({ service: Service, layer, deps: [] })
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
export * as PtyIntegration from "./integration"
2+
3+
import path from "path"
4+
import os from "os"
5+
import { promises as fs } from "fs"
6+
7+
// Bash shell integration: emits OSC 133 lifecycle markers plus a VS Code-style
8+
// OSC 633;E carrying the exact command line. Injected via --rcfile (which
9+
// replaces ~/.bashrc, so the script sources it first). Terminals ignore the
10+
// unknown sequences; the capture parser consumes them.
11+
const BASH_SCRIPT = `# opencode shell integration (generated; do not edit)
12+
if [ -f ~/.bashrc ]; then . ~/.bashrc; fi
13+
__oc_esc() { printf '%s' "$1" | sed -e 's/\\\\/\\\\\\\\/g' -e 's/;/\\\\x3b/g' | tr '\\n' ' '; }
14+
# Typed command line from history (pre-alias-expansion); BASH_COMMAND is post-expansion.
15+
__oc_histline() { HISTTIMEFORMAT= builtin history 1 2>/dev/null | sed '1 s/^ *[0-9][0-9]*[* ] //'; }
16+
__oc_prev_hist=""
17+
__oc_state=0
18+
__oc_preexec() {
19+
[ "$__oc_state" = 1 ] || return 0
20+
case "$BASH_COMMAND" in __oc_*) return 0 ;; esac
21+
[ -n "$COMP_LINE" ] && return 0
22+
__oc_state=2
23+
local __oc_cmd_line
24+
__oc_cmd_line=$(__oc_histline)
25+
# History skipped the entry (HISTCONTROL ignorespace/ignoredups): fall back to expanded text.
26+
[ "$__oc_cmd_line" = "$__oc_prev_hist" ] && __oc_cmd_line="$BASH_COMMAND"
27+
printf '\\033]633;E;%s\\007' "$(__oc_esc "$__oc_cmd_line")"
28+
printf '\\033]133;C\\007'
29+
}
30+
__oc_precmd() {
31+
local __oc_st=$?
32+
[ "$__oc_state" = 2 ] && printf '\\033]133;D;%s\\007' "$__oc_st"
33+
__oc_state=0
34+
printf '\\033]133;A\\007'
35+
printf '\\033]7;file://%s%s\\007' "\${HOSTNAME:-localhost}" "$PWD"
36+
__oc_prev_hist=$(__oc_histline)
37+
__oc_state=1
38+
}
39+
trap '__oc_preexec' DEBUG
40+
PROMPT_COMMAND="__oc_precmd\${PROMPT_COMMAND:+;\$PROMPT_COMMAND}"
41+
PS1="\${PS1}\\[\\033]133;B\\007\\]"
42+
export OPENCODE_SHELL_INTEGRATION=1
43+
`
44+
45+
let scriptPath: string | undefined
46+
47+
async function ensureScript() {
48+
if (scriptPath) return scriptPath
49+
const dir = path.join(os.tmpdir(), "opencode-shell-integration")
50+
await fs.mkdir(dir, { recursive: true })
51+
const file = path.join(dir, "integration.bash")
52+
await fs.writeFile(file, BASH_SCRIPT)
53+
scriptPath = file
54+
return file
55+
}
56+
57+
export type Setup = {
58+
readonly args: string[]
59+
readonly env: Record<string, string>
60+
}
61+
62+
// Returns adjusted spawn args for shells we can integrate, or undefined to spawn untouched.
63+
// bash only for now: --rcfile is ignored by login shells, so the -l flag is dropped and the
64+
// script sources ~/.bashrc itself.
65+
export async function setup(command: string, args: string[]): Promise<Setup | undefined> {
66+
const name = path.basename(command).toLowerCase()
67+
if (name !== "bash") return undefined
68+
const file = await ensureScript()
69+
return {
70+
args: ["--rcfile", file, ...args.filter((arg) => arg !== "-l")],
71+
env: { OPENCODE_SHELL_INTEGRATION: "1" },
72+
}
73+
}

0 commit comments

Comments
 (0)