pty.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. export * as Pty from "./pty"
  2. import type { Disp, Proc } from "#pty"
  3. import { Context, Effect, Layer, Schema, Types } from "effect"
  4. import { PtyEvent, PtyInfo } from "@opencode-ai/schema/pty"
  5. import { Config } from "./config"
  6. import { EventV2 } from "./event"
  7. import { Location } from "./location"
  8. import { PositiveInt } from "./schema"
  9. import { PtyID } from "./pty/schema"
  10. import { Shell } from "./shell"
  11. import { lazy } from "./util/lazy"
  12. const BUFFER_LIMIT = 1024 * 1024 * 2
  13. // Exited sessions stay observable (status, exit code, retained output) until removed explicitly.
  14. // Cap retention so abandoned terminals do not accumulate unbounded buffers.
  15. const EXITED_LIMIT = 25
  16. const pty = lazy(() => import("#pty"))
  17. type Subscriber = {
  18. readonly onData: (chunk: string) => void
  19. readonly onEnd: (event: { exitCode?: number }) => void
  20. active: boolean
  21. detached: boolean
  22. pending: string[]
  23. end?: { exitCode?: number }
  24. }
  25. type Active = {
  26. info: Info
  27. process: Proc
  28. buffer: string
  29. bufferCursor: number
  30. cursor: number
  31. subscribers: Map<object, Subscriber>
  32. listeners: Disp[]
  33. }
  34. export const Info = PtyInfo
  35. export type Info = Types.DeepMutable<typeof Info.Type>
  36. export const CreateInput = Schema.Struct({
  37. command: Schema.optional(Schema.String),
  38. args: Schema.optional(Schema.Array(Schema.String)),
  39. cwd: Schema.optional(Schema.String),
  40. title: Schema.optional(Schema.String),
  41. env: Schema.optional(Schema.Record(Schema.String, Schema.String)),
  42. })
  43. export type CreateInput = Types.DeepMutable<typeof CreateInput.Type>
  44. export const UpdateInput = Schema.Struct({
  45. title: Schema.optional(Schema.String),
  46. size: Schema.optional(
  47. Schema.Struct({
  48. rows: PositiveInt,
  49. cols: PositiveInt,
  50. }),
  51. ),
  52. })
  53. export type UpdateInput = Types.DeepMutable<typeof UpdateInput.Type>
  54. export type AttachInput = {
  55. // Absolute output cursor to replay from. -1 tails from the current end; omitted replays the full retained buffer.
  56. readonly cursor?: number
  57. // Callbacks fire synchronously from the native PTY data path; keep them non-blocking.
  58. readonly onData: (chunk: string) => void
  59. // Fired once when the session stops producing output: process exit (exitCode set), removal, or service teardown.
  60. readonly onEnd: (event: { exitCode?: number }) => void
  61. }
  62. export type Attachment = {
  63. // Retained output from the requested cursor to the current end.
  64. readonly replay: string
  65. // Absolute output cursor after replay.
  66. readonly cursor: number
  67. readonly write: (data: string) => void
  68. // Starts live delivery after the caller has applied replay and cursor metadata.
  69. readonly activate: () => void
  70. readonly detach: () => void
  71. }
  72. export class NotFoundError extends Schema.TaggedErrorClass<NotFoundError>()("Pty.NotFoundError", {
  73. ptyID: PtyID,
  74. }) {}
  75. export class ExitedError extends Schema.TaggedErrorClass<ExitedError>()("Pty.ExitedError", {
  76. ptyID: PtyID,
  77. }) {}
  78. export const Event = PtyEvent
  79. export interface Interface {
  80. readonly list: () => Effect.Effect<Info[]>
  81. readonly get: (id: PtyID) => Effect.Effect<Info, NotFoundError>
  82. readonly create: (input: CreateInput) => Effect.Effect<Info>
  83. readonly update: (id: PtyID, input: UpdateInput) => Effect.Effect<Info, NotFoundError>
  84. readonly remove: (id: PtyID) => Effect.Effect<void, NotFoundError>
  85. readonly write: (id: PtyID, data: string) => Effect.Effect<void, NotFoundError>
  86. readonly attach: (id: PtyID, input: AttachInput) => Effect.Effect<Attachment, NotFoundError | ExitedError>
  87. }
  88. export class Service extends Context.Service<Service, Interface>()("@opencode/v2/Pty") {}
  89. export const layer = Layer.effect(
  90. Service,
  91. Effect.gen(function* () {
  92. const events = yield* EventV2.Service
  93. const location = yield* Location.Service
  94. const config = yield* Config.Service
  95. const context = yield* Effect.context()
  96. const runFork = Effect.runForkWith(context)
  97. const sessions = new Map<PtyID, Active>()
  98. const exitOrder: PtyID[] = []
  99. function notifyEnd(session: Active, event: { exitCode?: number }) {
  100. for (const subscriber of session.subscribers.values()) {
  101. if (!subscriber.active) {
  102. subscriber.end = event
  103. continue
  104. }
  105. try {
  106. subscriber.onEnd(event)
  107. } catch {}
  108. }
  109. session.subscribers.clear()
  110. }
  111. function teardown(session: Active) {
  112. for (const listener of session.listeners) listener.dispose()
  113. session.listeners.length = 0
  114. if (session.info.status === "running") {
  115. try {
  116. session.process.kill()
  117. } catch {}
  118. }
  119. notifyEnd(session, {})
  120. }
  121. yield* Effect.addFinalizer(() =>
  122. Effect.sync(() => {
  123. for (const session of sessions.values()) teardown(session)
  124. sessions.clear()
  125. exitOrder.length = 0
  126. }),
  127. )
  128. const requireSession = Effect.fn("Pty.requireSession")(function* (id: PtyID) {
  129. const session = sessions.get(id)
  130. if (!session) return yield* new NotFoundError({ ptyID: id })
  131. return session
  132. })
  133. const removeSession = Effect.fnUntraced(function* (id: PtyID) {
  134. const session = sessions.get(id)
  135. if (!session) return
  136. sessions.delete(id)
  137. const index = exitOrder.indexOf(id)
  138. if (index !== -1) exitOrder.splice(index, 1)
  139. yield* Effect.logInfo("removing session", { id })
  140. teardown(session)
  141. yield* events.publish(Event.Deleted, { id: session.info.id })
  142. })
  143. const remove = Effect.fn("Pty.remove")(function* (id: PtyID) {
  144. yield* requireSession(id)
  145. yield* removeSession(id)
  146. })
  147. const list = Effect.fn("Pty.list")(function* () {
  148. return Array.from(sessions.values()).map((session) => session.info)
  149. })
  150. const get = Effect.fn("Pty.get")(function* (id: PtyID) {
  151. return (yield* requireSession(id)).info
  152. })
  153. const create = Effect.fn("Pty.create")(function* (input: CreateInput) {
  154. const id = PtyID.ascending()
  155. const command = input.command || Shell.preferred(Config.latest(yield* config.entries(), "shell"))
  156. const args = Shell.login(command) ? [...(input.args ?? []), "-l"] : [...(input.args ?? [])]
  157. const cwd = input.cwd || location.directory
  158. const env = {
  159. ...process.env,
  160. ...input.env,
  161. TERM: "xterm-256color",
  162. OPENCODE_TERMINAL: "1",
  163. } as Record<string, string>
  164. if (process.platform === "win32") {
  165. env.LC_ALL = "C.UTF-8"
  166. env.LC_CTYPE = "C.UTF-8"
  167. env.LANG = "C.UTF-8"
  168. }
  169. yield* Effect.logInfo("creating session", { id, cmd: command, args, cwd })
  170. const { spawn } = yield* Effect.promise(() => pty())
  171. const proc = yield* Effect.sync(() => spawn(command, args, { name: "xterm-256color", cwd, env }))
  172. const info: Info = {
  173. id,
  174. title: input.title || `Terminal ${id.slice(-4)}`,
  175. command,
  176. args,
  177. cwd,
  178. status: "running",
  179. pid: proc.pid,
  180. }
  181. const session: Active = {
  182. info,
  183. process: proc,
  184. buffer: "",
  185. bufferCursor: 0,
  186. cursor: 0,
  187. subscribers: new Map(),
  188. listeners: [],
  189. }
  190. sessions.set(id, session)
  191. session.listeners.push(
  192. proc.onData((chunk) => {
  193. session.cursor += chunk.length
  194. for (const [token, subscriber] of session.subscribers.entries()) {
  195. if (!subscriber.active) {
  196. subscriber.pending.push(chunk)
  197. continue
  198. }
  199. try {
  200. subscriber.onData(chunk)
  201. } catch {
  202. session.subscribers.delete(token)
  203. }
  204. }
  205. session.buffer += chunk
  206. if (session.buffer.length <= BUFFER_LIMIT) return
  207. const excess = session.buffer.length - BUFFER_LIMIT
  208. session.buffer = session.buffer.slice(excess)
  209. session.bufferCursor += excess
  210. }),
  211. proc.onExit(({ exitCode }) => {
  212. if (session.info.status === "exited") return
  213. session.info.status = "exited"
  214. session.info.exitCode = exitCode
  215. notifyEnd(session, { exitCode })
  216. exitOrder.push(id)
  217. runFork(
  218. Effect.gen(function* () {
  219. yield* Effect.logInfo("session exited", { id, exitCode })
  220. yield* events.publish(Event.Exited, { id, exitCode })
  221. while (exitOrder.length > EXITED_LIMIT) {
  222. const oldest = exitOrder[0]
  223. if (!oldest) break
  224. yield* removeSession(oldest)
  225. }
  226. }),
  227. )
  228. }),
  229. )
  230. yield* events.publish(Event.Created, { info })
  231. return info
  232. })
  233. const update = Effect.fn("Pty.update")(function* (id: PtyID, input: UpdateInput) {
  234. const session = yield* requireSession(id)
  235. if (input.title) session.info.title = input.title
  236. if (input.size && session.info.status === "running") session.process.resize(input.size.cols, input.size.rows)
  237. yield* events.publish(Event.Updated, { info: session.info })
  238. return session.info
  239. })
  240. const write = Effect.fn("Pty.write")(function* (id: PtyID, data: string) {
  241. const session = yield* requireSession(id)
  242. if (session.info.status === "running") session.process.write(data)
  243. })
  244. const attach = Effect.fn("Pty.attach")(function* (id: PtyID, input: AttachInput) {
  245. const session = yield* requireSession(id)
  246. if (session.info.status !== "running") return yield* new ExitedError({ ptyID: id })
  247. yield* Effect.logInfo("client attached to session", { id, directory: location.directory })
  248. const token = {}
  249. const subscriber: Subscriber = {
  250. onData: input.onData,
  251. onEnd: input.onEnd,
  252. active: false,
  253. detached: false,
  254. pending: [],
  255. }
  256. session.subscribers.set(token, subscriber)
  257. const start = session.bufferCursor
  258. const end = session.cursor
  259. const from =
  260. input.cursor === -1
  261. ? end
  262. : typeof input.cursor === "number" && Number.isSafeInteger(input.cursor)
  263. ? Math.max(0, input.cursor)
  264. : 0
  265. const replay = (() => {
  266. if (!session.buffer || from >= end) return ""
  267. const offset = Math.max(0, from - start)
  268. if (offset >= session.buffer.length) return ""
  269. return session.buffer.slice(offset)
  270. })()
  271. return {
  272. replay,
  273. cursor: end,
  274. write: (data: string) => {
  275. if (session.info.status === "running") session.process.write(data)
  276. },
  277. activate: () => {
  278. if (subscriber.active || subscriber.detached) return
  279. subscriber.active = true
  280. try {
  281. for (const chunk of subscriber.pending) subscriber.onData(chunk)
  282. subscriber.pending.length = 0
  283. if (subscriber.end) subscriber.onEnd(subscriber.end)
  284. } catch {
  285. session.subscribers.delete(token)
  286. }
  287. },
  288. detach: () => {
  289. subscriber.detached = true
  290. subscriber.pending.length = 0
  291. subscriber.end = undefined
  292. session.subscribers.delete(token)
  293. },
  294. }
  295. })
  296. return Service.of({ list, get, create, update, remove, write, attach })
  297. }),
  298. )
  299. export const locationLayer = layer.pipe(Layer.provide(Config.locationLayer))