pty.ts 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. export * as Pty from "./pty"
  2. import type { Disp, Proc } from "#pty"
  3. import { Context, Effect, Layer, Schema, Types } from "effect"
  4. import { EventV2 } from "./event"
  5. import { Location } from "./location"
  6. import { NonNegativeInt, PositiveInt } from "./schema"
  7. import { PtyID } from "./pty/schema"
  8. import { lazy } from "./util/lazy"
  9. import * as Log from "./util/log"
  10. const log = Log.create({ service: "pty" })
  11. const BUFFER_LIMIT = 1024 * 1024 * 2
  12. const BUFFER_CHUNK = 64 * 1024
  13. const encoder = new TextEncoder()
  14. const pty = lazy(() => import("#pty"))
  15. type Socket = {
  16. readyState: number
  17. data?: unknown
  18. send: (data: string | Uint8Array | ArrayBuffer) => void
  19. close: (code?: number, reason?: string) => void
  20. }
  21. type Active = {
  22. info: Info
  23. process: Proc
  24. buffer: string
  25. bufferCursor: number
  26. cursor: number
  27. subscribers: Map<unknown, Socket>
  28. listeners: Disp[]
  29. }
  30. const sock = (ws: Socket) => (ws.data && typeof ws.data === "object" ? ws.data : ws)
  31. // WebSocket control frame: 0x00 + UTF-8 JSON.
  32. const meta = (cursor: number) => {
  33. const json = JSON.stringify({ cursor })
  34. const bytes = encoder.encode(json)
  35. const out = new Uint8Array(bytes.length + 1)
  36. out[0] = 0
  37. out.set(bytes, 1)
  38. return out
  39. }
  40. export const Info = Schema.Struct({
  41. id: PtyID,
  42. title: Schema.String,
  43. command: Schema.String,
  44. args: Schema.Array(Schema.String),
  45. cwd: Schema.String,
  46. status: Schema.Literals(["running", "exited"]),
  47. // Windows ConPTY assigns the child pid asynchronously, so 0 is valid at spawn time.
  48. pid: NonNegativeInt,
  49. }).annotate({ identifier: "Pty" })
  50. export type Info = Types.DeepMutable<typeof Info.Type>
  51. export const CreateInput = Schema.Struct({
  52. command: Schema.optional(Schema.String),
  53. args: Schema.optional(Schema.Array(Schema.String)),
  54. cwd: Schema.optional(Schema.String),
  55. title: Schema.optional(Schema.String),
  56. env: Schema.optional(Schema.Record(Schema.String, Schema.String)),
  57. })
  58. export type CreateInput = Types.DeepMutable<typeof CreateInput.Type>
  59. export type PreparedCreate = {
  60. readonly command: string
  61. readonly args: string[]
  62. readonly cwd: string
  63. readonly title?: string
  64. readonly env: Record<string, string>
  65. }
  66. export const UpdateInput = Schema.Struct({
  67. title: Schema.optional(Schema.String),
  68. size: Schema.optional(
  69. Schema.Struct({
  70. rows: PositiveInt,
  71. cols: PositiveInt,
  72. }),
  73. ),
  74. })
  75. export type UpdateInput = Types.DeepMutable<typeof UpdateInput.Type>
  76. export class NotFoundError extends Schema.TaggedErrorClass<NotFoundError>()("Pty.NotFoundError", {
  77. ptyID: PtyID,
  78. }) {}
  79. export const Event = {
  80. Created: EventV2.define({ type: "pty.created", schema: { info: Info } }),
  81. Updated: EventV2.define({ type: "pty.updated", schema: { info: Info } }),
  82. Exited: EventV2.define({ type: "pty.exited", schema: { id: PtyID, exitCode: NonNegativeInt } }),
  83. Deleted: EventV2.define({ type: "pty.deleted", schema: { id: PtyID } }),
  84. }
  85. export interface Interface {
  86. readonly list: () => Effect.Effect<Info[]>
  87. readonly get: (id: PtyID) => Effect.Effect<Info, NotFoundError>
  88. readonly create: (input: PreparedCreate) => Effect.Effect<Info>
  89. readonly update: (id: PtyID, input: UpdateInput) => Effect.Effect<Info, NotFoundError>
  90. readonly remove: (id: PtyID) => Effect.Effect<void, NotFoundError>
  91. readonly resize: (id: PtyID, cols: number, rows: number) => Effect.Effect<void, NotFoundError>
  92. readonly write: (id: PtyID, data: string) => Effect.Effect<void, NotFoundError>
  93. readonly connect: (
  94. id: PtyID,
  95. ws: Socket,
  96. cursor?: number,
  97. ) => Effect.Effect<
  98. { onMessage: (message: string | ArrayBuffer) => void; onClose: () => void } | undefined,
  99. NotFoundError
  100. >
  101. }
  102. export class Service extends Context.Service<Service, Interface>()("@opencode/v2/Pty") {}
  103. export const layer = Layer.effect(
  104. Service,
  105. Effect.gen(function* () {
  106. const events = yield* EventV2.Service
  107. const location = yield* Location.Service
  108. const context = yield* Effect.context()
  109. const runFork = Effect.runForkWith(context)
  110. const sessions = new Map<PtyID, Active>()
  111. function teardown(session: Active) {
  112. for (const listener of session.listeners) listener.dispose()
  113. session.listeners.length = 0
  114. try {
  115. session.process.kill()
  116. } catch {}
  117. for (const [sub, ws] of session.subscribers.entries()) {
  118. try {
  119. if (sock(ws) === sub) ws.close()
  120. } catch {}
  121. }
  122. session.subscribers.clear()
  123. }
  124. yield* Effect.addFinalizer(() =>
  125. Effect.sync(() => {
  126. for (const session of sessions.values()) teardown(session)
  127. sessions.clear()
  128. }),
  129. )
  130. const requireSession = Effect.fn("Pty.requireSession")(function* (id: PtyID) {
  131. const session = sessions.get(id)
  132. if (!session) return yield* new NotFoundError({ ptyID: id })
  133. return session
  134. })
  135. const removeSession = Effect.fnUntraced(function* (id: PtyID) {
  136. const session = sessions.get(id)
  137. if (!session) return false
  138. sessions.delete(id)
  139. log.info("removing session", { id })
  140. teardown(session)
  141. yield* events.publish(Event.Deleted, { id: session.info.id })
  142. return true
  143. })
  144. const remove = Effect.fn("Pty.remove")(function* (id: PtyID) {
  145. yield* requireSession(id)
  146. yield* removeSession(id)
  147. })
  148. const list = Effect.fn("Pty.list")(function* () {
  149. return Array.from(sessions.values()).map((session) => session.info)
  150. })
  151. const get = Effect.fn("Pty.get")(function* (id: PtyID) {
  152. return (yield* requireSession(id)).info
  153. })
  154. const create = Effect.fn("Pty.create")(function* (input: PreparedCreate) {
  155. const id = PtyID.ascending()
  156. log.info("creating session", { id, cmd: input.command, args: input.args, cwd: input.cwd })
  157. const { spawn } = yield* Effect.promise(() => pty())
  158. const proc = yield* Effect.sync(() =>
  159. spawn(input.command, input.args, {
  160. name: "xterm-256color",
  161. cwd: input.cwd,
  162. env: input.env,
  163. }),
  164. )
  165. const info = {
  166. id,
  167. title: input.title || `Terminal ${id.slice(-4)}`,
  168. command: input.command,
  169. args: input.args,
  170. cwd: input.cwd,
  171. status: "running",
  172. pid: proc.pid,
  173. } as const
  174. const session: Active = {
  175. info,
  176. process: proc,
  177. buffer: "",
  178. bufferCursor: 0,
  179. cursor: 0,
  180. subscribers: new Map(),
  181. listeners: [],
  182. }
  183. sessions.set(id, session)
  184. session.listeners.push(
  185. proc.onData((chunk) => {
  186. session.cursor += chunk.length
  187. for (const [key, ws] of session.subscribers.entries()) {
  188. if (ws.readyState !== 1 || sock(ws) !== key) {
  189. session.subscribers.delete(key)
  190. continue
  191. }
  192. try {
  193. ws.send(chunk)
  194. } catch {
  195. session.subscribers.delete(key)
  196. }
  197. }
  198. session.buffer += chunk
  199. if (session.buffer.length <= BUFFER_LIMIT) return
  200. const excess = session.buffer.length - BUFFER_LIMIT
  201. session.buffer = session.buffer.slice(excess)
  202. session.bufferCursor += excess
  203. }),
  204. proc.onExit(({ exitCode }) => {
  205. if (session.info.status === "exited") return
  206. runFork(
  207. Effect.gen(function* () {
  208. log.info("session exited", { id, exitCode })
  209. session.info.status = "exited"
  210. yield* events.publish(Event.Exited, { id, exitCode })
  211. yield* removeSession(id)
  212. }),
  213. )
  214. }),
  215. )
  216. yield* events.publish(Event.Created, { info })
  217. return info
  218. })
  219. const update = Effect.fn("Pty.update")(function* (id: PtyID, input: UpdateInput) {
  220. const session = yield* requireSession(id)
  221. if (input.title) session.info.title = input.title
  222. if (input.size) session.process.resize(input.size.cols, input.size.rows)
  223. yield* events.publish(Event.Updated, { info: session.info })
  224. return session.info
  225. })
  226. const resize = Effect.fn("Pty.resize")(function* (id: PtyID, cols: number, rows: number) {
  227. const session = yield* requireSession(id)
  228. if (session.info.status === "running") session.process.resize(cols, rows)
  229. })
  230. const write = Effect.fn("Pty.write")(function* (id: PtyID, data: string) {
  231. const session = yield* requireSession(id)
  232. if (session.info.status === "running") session.process.write(data)
  233. })
  234. const connect = Effect.fn("Pty.connect")(function* (id: PtyID, ws: Socket, cursor?: number) {
  235. const session = yield* requireSession(id).pipe(Effect.tapError(() => Effect.sync(() => ws.close())))
  236. log.info("client connected to session", { id, directory: location.directory })
  237. const sub = sock(ws)
  238. session.subscribers.delete(sub)
  239. session.subscribers.set(sub, ws)
  240. const cleanup = () => session.subscribers.delete(sub)
  241. const start = session.bufferCursor
  242. const end = session.cursor
  243. const from =
  244. cursor === -1 ? end : typeof cursor === "number" && Number.isSafeInteger(cursor) ? Math.max(0, cursor) : 0
  245. const data = (() => {
  246. if (!session.buffer || from >= end) return ""
  247. const offset = Math.max(0, from - start)
  248. if (offset >= session.buffer.length) return ""
  249. return session.buffer.slice(offset)
  250. })()
  251. if (data) {
  252. try {
  253. for (let i = 0; i < data.length; i += BUFFER_CHUNK) ws.send(data.slice(i, i + BUFFER_CHUNK))
  254. } catch {
  255. cleanup()
  256. ws.close()
  257. return
  258. }
  259. }
  260. try {
  261. ws.send(meta(end))
  262. } catch {
  263. cleanup()
  264. ws.close()
  265. return
  266. }
  267. return {
  268. onMessage: (message: string | ArrayBuffer) => {
  269. session.process.write(typeof message === "string" ? message : new TextDecoder().decode(message))
  270. },
  271. onClose: () => {
  272. log.info("client disconnected from session", { id })
  273. cleanup()
  274. },
  275. }
  276. })
  277. return Service.of({ list, get, create, update, remove, resize, write, connect })
  278. }),
  279. )
  280. export const locationLayer = layer