@zyro-sec/server 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/package.json +40 -4
  2. package/script/build.ts +28 -0
  3. package/script/pack.ts +5 -0
  4. package/script/workerd-probe.ts +59 -0
  5. package/src/api.ts +12 -0
  6. package/src/auth.ts +70 -0
  7. package/src/content-headers.ts +32 -0
  8. package/src/cors.ts +34 -0
  9. package/src/event-feed.ts +93 -0
  10. package/src/fetch.ts +67 -0
  11. package/src/handlers/agent.ts +23 -0
  12. package/src/handlers/artifact.ts +242 -0
  13. package/src/handlers/automation.ts +63 -0
  14. package/src/handlers/blob.ts +55 -0
  15. package/src/handlers/command.ts +8 -0
  16. package/src/handlers/config.ts +26 -0
  17. package/src/handlers/credential.ts +87 -0
  18. package/src/handlers/debug.ts +57 -0
  19. package/src/handlers/event.ts +38 -0
  20. package/src/handlers/form.ts +15 -0
  21. package/src/handlers/fs.ts +180 -0
  22. package/src/handlers/generate.ts +117 -0
  23. package/src/handlers/integration.ts +310 -0
  24. package/src/handlers/job.ts +29 -0
  25. package/src/handlers/location.ts +33 -0
  26. package/src/handlers/machine.ts +336 -0
  27. package/src/handlers/mcp.ts +160 -0
  28. package/src/handlers/media.ts +44 -0
  29. package/src/handlers/message.ts +82 -0
  30. package/src/handlers/migration.ts +13 -0
  31. package/src/handlers/model.ts +25 -0
  32. package/src/handlers/permission.ts +131 -0
  33. package/src/handlers/persistent-pty.ts +285 -0
  34. package/src/handlers/plugin.ts +97 -0
  35. package/src/handlers/project.ts +23 -0
  36. package/src/handlers/provider.ts +32 -0
  37. package/src/handlers/pty-socket.ts +47 -0
  38. package/src/handlers/pty.ts +181 -0
  39. package/src/handlers/push.ts +67 -0
  40. package/src/handlers/reference.ts +8 -0
  41. package/src/handlers/rpc.ts +31 -0
  42. package/src/handlers/server.ts +58 -0
  43. package/src/handlers/session-error.ts +47 -0
  44. package/src/handlers/session.ts +722 -0
  45. package/src/handlers/shell.ts +72 -0
  46. package/src/handlers/skill.ts +34 -0
  47. package/src/handlers/usage.ts +23 -0
  48. package/src/handlers/vcs.ts +104 -0
  49. package/src/handlers/voice.ts +50 -0
  50. package/src/handlers/websearch.ts +50 -0
  51. package/src/handlers/worktree.ts +60 -0
  52. package/src/handlers.ts +69 -0
  53. package/src/location.ts +86 -0
  54. package/src/media-uri.ts +13 -0
  55. package/src/middleware/authorization.ts +111 -0
  56. package/src/middleware/defect-response.ts +39 -0
  57. package/src/middleware/form-location.ts +44 -0
  58. package/src/middleware/schema-error.ts +49 -0
  59. package/src/middleware/session-location.ts +30 -0
  60. package/src/options.ts +61 -0
  61. package/src/pairing.ts +36 -0
  62. package/src/process.ts +274 -0
  63. package/src/range.ts +16 -0
  64. package/src/request-site.ts +36 -0
  65. package/src/request-tracing.ts +9 -0
  66. package/src/routes.ts +261 -0
  67. package/src/server-info.ts +41 -0
  68. package/src/service-status.ts +30 -0
  69. package/src/workerd.ts +184 -0
  70. package/test/artifact.test.ts +224 -0
  71. package/test/auth.test.ts +24 -0
  72. package/test/automation.test.ts +315 -0
  73. package/test/client-mcp.test.ts +369 -0
  74. package/test/codemode-api.test.ts +88 -0
  75. package/test/config.test.ts +104 -0
  76. package/test/cors.test.ts +24 -0
  77. package/test/defect-response.test.ts +83 -0
  78. package/test/event-feed.test.ts +201 -0
  79. package/test/fetch-option.test.ts +104 -0
  80. package/test/fetch.test.ts +698 -0
  81. package/test/fixture/mcp-starts.cjs +20 -0
  82. package/test/fixture/routes.ts +37 -0
  83. package/test/fixture/server.ts +20 -0
  84. package/test/fixture/worktree-delegate/index.ts +13 -0
  85. package/test/fixture/worktree-plugin/index.ts +47 -0
  86. package/test/flag-channel.test.ts +126 -0
  87. package/test/fs.test.ts +439 -0
  88. package/test/generate.test.ts +132 -0
  89. package/test/handler-policy.test.ts +43 -0
  90. package/test/heap-dump.test.ts +137 -0
  91. package/test/integration-policy.test.ts +93 -0
  92. package/test/job.test.ts +186 -0
  93. package/test/machine-iroh.test.ts +259 -0
  94. package/test/machine-link.test.ts +1234 -0
  95. package/test/machine-routes.test.ts +198 -0
  96. package/test/media.test.ts +343 -0
  97. package/test/message.test.ts +105 -0
  98. package/test/model.test.ts +62 -0
  99. package/test/options.test.ts +42 -0
  100. package/test/permission-saved.test.ts +73 -0
  101. package/test/persistent-pty.test.ts +1007 -0
  102. package/test/process.test.ts +261 -0
  103. package/test/provider.test.ts +88 -0
  104. package/test/pty-socket.property.test.ts +240 -0
  105. package/test/pty-socket.test.ts +89 -0
  106. package/test/pty-transport.test.ts +200 -0
  107. package/test/push-routes.test.ts +157 -0
  108. package/test/request-site.test.ts +71 -0
  109. package/test/request-tracing.test.ts +87 -0
  110. package/test/rpc-handler-errors.test.ts +76 -0
  111. package/test/schema-error.test.ts +68 -0
  112. package/test/service-status.test.ts +34 -0
  113. package/test/session-admit-location.test.ts +92 -0
  114. package/test/session-create.test.ts +65 -0
  115. package/test/session-diff.test.ts +100 -0
  116. package/test/session-form.test.ts +50 -0
  117. package/test/session-import.test.ts +152 -0
  118. package/test/session-instances.test.ts +335 -0
  119. package/test/session-unarchive.test.ts +73 -0
  120. package/test/session-update.test.ts +66 -0
  121. package/test/skill.test.ts +57 -0
  122. package/test/sse-failure.test.ts +71 -0
  123. package/test/usage.test.ts +88 -0
  124. package/test/vcs.test.ts +356 -0
  125. package/test/video-generate.test.ts +131 -0
  126. package/test/voice.test.ts +170 -0
  127. package/test/workerd.test.ts +227 -0
  128. package/test/worktree.test.ts +333 -0
  129. package/tsconfig.build.json +15 -0
  130. package/tsconfig.json +11 -0
  131. package/README.md +0 -3
@@ -0,0 +1,1007 @@
1
+ import { existsSync } from "node:fs"
2
+ import fs from "node:fs/promises"
3
+ import os from "node:os"
4
+ import path from "node:path"
5
+ import { expect } from "bun:test"
6
+ import { binaryPath } from "@opencode/pty"
7
+ import { PersistentPty } from "@zyro-sec/schema/persistent-pty"
8
+ import { Session } from "@zyro-sec/schema/session"
9
+ import { Effect, Exit, Schema, Scope } from "effect"
10
+ import { HttpServer } from "effect/http"
11
+ import { OpenCode } from "../../client/src/promise/index"
12
+ import { fakeDaemon } from "../../core/test/fixture/persistent-pty-daemon"
13
+ import { it } from "../../core/test/lib/effect"
14
+ import { ServerProcess } from "../src/process"
15
+
16
+ // These tests drive Unix shell commands, so they skip Windows; the package resolves no binary on unsupported platforms.
17
+ const binary = process.platform === "win32" ? undefined : (process.env.OPENCODE_PTY_BIN ?? binaryPath)
18
+ const smoke = binary !== undefined && existsSync(binary) ? it.live : it.live.skip
19
+
20
+ smoke(
21
+ "reads the latest controlled terminal with optional physical line counts through the SDK",
22
+ () =>
23
+ Effect.gen(function* () {
24
+ const fixture = yield* testDirectory()
25
+ const server = yield* ServerProcess.start<never, never>({
26
+ hostname: "127.0.0.1",
27
+ port: 0,
28
+ password: "secret",
29
+ app: { version: "test-version" },
30
+ database: { path: fixture.database },
31
+ pty: { root: fixture.directory },
32
+ fs: { filewatcher: false },
33
+ })
34
+ const base = HttpServer.formatAddress(server.address)
35
+ const client = OpenCode.make({ baseUrl: base, headers: { authorization: `Basic ${btoa("opencode:secret")}` } })
36
+ const sessionID = "ses_terminal_read"
37
+ expect(yield* Effect.promise(() => client.experimental.persistentPty.read({ sessionID }))).toBeNull()
38
+ expect(existsSync(fixture.directory)).toBeFalse()
39
+ yield* Effect.promise(async () => {
40
+ for (const lines of ["0", "-1", "1.5", "65536", "nope"]) {
41
+ const response = await fetch(`${base}/api/experimental/session/${sessionID}/terminal/read?lines=${lines}`, {
42
+ headers: { authorization: `Basic ${btoa("opencode:secret")}` },
43
+ })
44
+ expect(response.status).toBe(400)
45
+ await response.arrayBuffer()
46
+ }
47
+ })
48
+ expect(existsSync(fixture.directory)).toBeFalse()
49
+ const first = yield* Effect.promise(() =>
50
+ client.experimental.persistentPty.create({
51
+ sessionID,
52
+ command: "/bin/sh",
53
+ args: ["-c", "stty -echo; seq 1 20; exec cat"],
54
+ cwd: fixture.root,
55
+ title: "first",
56
+ env: {},
57
+ size: { cols: 40, rows: 4 },
58
+ }),
59
+ )
60
+ const second = yield* Effect.promise(() =>
61
+ client.experimental.persistentPty.create({
62
+ sessionID,
63
+ command: "/bin/sh",
64
+ args: ["-c", "printf second; exec cat"],
65
+ cwd: fixture.root,
66
+ title: "second",
67
+ env: {},
68
+ }),
69
+ )
70
+ expect(yield* waitForText(base, first.id, "20")).toContain("1\n2\n")
71
+ expect(yield* Effect.promise(() => client.experimental.persistentPty.read({ sessionID }))).toBeNull()
72
+ const controller = yield* Effect.acquireRelease(
73
+ Effect.promise(() => openTerminalSocket(base, first.id, "read-first")),
74
+ (connection) => Effect.sync(() => connection.socket.close()),
75
+ )
76
+ const observer = yield* Effect.acquireRelease(
77
+ Effect.promise(() => openTerminalSocket(base, second.id, "read-second", "observer")),
78
+ (connection) => Effect.sync(() => connection.socket.close()),
79
+ )
80
+ const current = yield* Effect.promise(() => client.experimental.persistentPty.read({ sessionID }))
81
+ if (!current) throw new Error("Expected the controller's terminal to be selected")
82
+ expect(current).toEqual({
83
+ ptyID: first.id,
84
+ title: "first",
85
+ cwd: fixture.root,
86
+ foregroundProcess: current.foregroundProcess,
87
+ screen: { text: "18\n19\n20\n", cols: 40, rows: 4, cursor: { x: 0, y: 3 } },
88
+ })
89
+ expect(current.foregroundProcess === null || typeof current.foregroundProcess === "string").toBeTrue()
90
+ expect(yield* Effect.promise(() => client.experimental.persistentPty.read({ sessionID: "ses_other" }))).toBeNull()
91
+ yield* Effect.promise(() => client.experimental.persistentPty.snapshot({ ptyID: second.id }))
92
+ for (const lines of [2, 6, 65535]) {
93
+ const value = yield* Effect.promise(() => client.experimental.persistentPty.read({ sessionID, lines }))
94
+ expect(value?.ptyID).toBe(first.id)
95
+ expect(value?.screen.rows).toBe(4)
96
+ const expected = Array.from({ length: 20 }, (_, index) => String(index + 1))
97
+ .concat("")
98
+ .slice(-lines)
99
+ expect(value?.screen.text.split("\n")).toEqual(expected)
100
+ }
101
+ observer.socket.send(controlFrame(30, 3))
102
+ expect((yield* Effect.promise(() => waitForRead(client, sessionID, second.id))).screen.rows).toBe(3)
103
+ yield* Effect.promise(() =>
104
+ client.experimental.persistentPty.update({
105
+ ptyID: first.id,
106
+ attachmentID: "read-first",
107
+ size: { cols: 42, rows: 5 },
108
+ }),
109
+ )
110
+ expect((yield* Effect.promise(() => client.experimental.persistentPty.read({ sessionID })))?.ptyID).toBe(first.id)
111
+ observer.socket.send(controlFrame(30, 3))
112
+ yield* Effect.promise(() => waitForRead(client, sessionID, second.id))
113
+ controller.socket.send(inputFrame(40, 4, "typed\n"))
114
+ yield* Effect.promise(() => waitForSocketOutput([controller], "typed"))
115
+ expect((yield* Effect.promise(() => waitForRead(client, sessionID, first.id))).screen.text).toContain("typed")
116
+ const takeover = yield* Effect.acquireRelease(
117
+ Effect.promise(() => openTerminalSocket(base, second.id, "read-takeover")),
118
+ (connection) => Effect.sync(() => connection.socket.close()),
119
+ )
120
+ expect((yield* Effect.promise(() => client.experimental.persistentPty.read({ sessionID })))?.ptyID).toBe(
121
+ second.id,
122
+ )
123
+ takeover.socket.close()
124
+ yield* Effect.promise(() => client.experimental.persistentPty.remove({ ptyID: first.id }))
125
+ expect((yield* Effect.promise(() => client.experimental.persistentPty.read({ sessionID })))?.ptyID).toBe(
126
+ second.id,
127
+ )
128
+ yield* Effect.promise(() => client.experimental.persistentPty.remove({ ptyID: second.id }))
129
+ expect(yield* Effect.promise(() => client.experimental.persistentPty.read({ sessionID }))).toBeNull()
130
+ yield* Effect.promise(() => client.experimental.persistentPty.shutdown())
131
+ expect(yield* Effect.promise(() => client.experimental.persistentPty.read({ sessionID }))).toBeNull()
132
+ }),
133
+ 20_000,
134
+ )
135
+
136
+ smoke(
137
+ "renames and resizes a terminal independently through the SDK",
138
+ () =>
139
+ Effect.gen(function* () {
140
+ const fixture = yield* testDirectory()
141
+ const server = yield* ServerProcess.start<never, never>({
142
+ hostname: "127.0.0.1",
143
+ port: 0,
144
+ password: "secret",
145
+ app: { version: "test-version" },
146
+ database: { path: fixture.database },
147
+ pty: { root: fixture.directory },
148
+ fs: { filewatcher: false },
149
+ })
150
+ const base = HttpServer.formatAddress(server.address)
151
+ const client = OpenCode.make({ baseUrl: base, headers: { authorization: `Basic ${btoa("opencode:secret")}` } })
152
+ const sessionID = Session.ID.make("ses_persistent_pty_rename")
153
+ const terminal = yield* Effect.promise(() =>
154
+ client.experimental.persistentPty.create({
155
+ sessionID,
156
+ command: "/bin/sh",
157
+ args: ["-c", "stty -echo; printf '\\033]2;from-shell\\007ready'; exec cat"],
158
+ cwd: fixture.root,
159
+ title: "created",
160
+ env: {},
161
+ size: { cols: 40, rows: 10 },
162
+ }),
163
+ )
164
+ expect(terminal.userTitle).toBeNull()
165
+ yield* waitForText(base, terminal.id, "ready")
166
+ yield* Effect.promise(() => waitForTitle(client, terminal.id, "from-shell"))
167
+ const events = yield* Effect.acquireRelease(
168
+ Effect.promise(() => openEventStream(base)),
169
+ (stream) => Effect.promise(() => stream.close()),
170
+ )
171
+
172
+ const renamed = yield* Effect.promise(() =>
173
+ client.experimental.persistentPty.update({ ptyID: terminal.id, title: "build" }),
174
+ )
175
+ expect(renamed).toMatchObject({ title: "build", userTitle: "build", size: { cols: 40, rows: 10 } })
176
+ expect(yield* Effect.promise(() => events.next("persistent-pty.updated"))).toMatchObject({
177
+ data: { sessionID, terminal: { id: terminal.id, title: "build", userTitle: "build" } },
178
+ })
179
+ expect(yield* Effect.promise(() => client.experimental.persistentPty.list({ sessionID }))).toMatchObject([
180
+ { id: terminal.id, title: "build", userTitle: "build" },
181
+ ])
182
+
183
+ const resized = yield* Effect.promise(() =>
184
+ client.experimental.persistentPty.update({ ptyID: terminal.id, size: { cols: 50, rows: 12 } }),
185
+ )
186
+ expect(resized).toMatchObject({ title: "build", userTitle: "build", size: { cols: 50, rows: 12 } })
187
+
188
+ const cleared = yield* Effect.promise(() =>
189
+ client.experimental.persistentPty.update({ ptyID: terminal.id, title: null }),
190
+ )
191
+ expect(cleared).toMatchObject({ title: "from-shell", userTitle: null, size: { cols: 50, rows: 12 } })
192
+ expect(yield* Effect.promise(() => events.next("persistent-pty.updated"))).toMatchObject({
193
+ data: { sessionID, terminal: { id: terminal.id, title: "from-shell", userTitle: null } },
194
+ })
195
+
196
+ const missing = yield* Effect.promise(async () => {
197
+ const response = await fetch(new URL("/api/experimental/persistent-pty/pty_persistent_1", base), {
198
+ method: "PUT",
199
+ headers: { authorization: `Basic ${btoa("opencode:secret")}`, "content-type": "application/json" },
200
+ body: JSON.stringify({ title: "nope" }),
201
+ })
202
+ await response.arrayBuffer()
203
+ return response.status
204
+ })
205
+ expect(missing).toBe(404)
206
+ yield* Effect.promise(() => client.experimental.persistentPty.shutdown())
207
+ }),
208
+ 20_000,
209
+ )
210
+
211
+ it.live("renames without a feature check and hides unknown terminals", () =>
212
+ Effect.gen(function* () {
213
+ const fixture = yield* testDirectory()
214
+ const daemon = yield* fakeDaemon()
215
+ const server = yield* ServerProcess.start<never, never>({
216
+ hostname: "127.0.0.1",
217
+ port: 0,
218
+ password: "secret",
219
+ app: { version: "test-version" },
220
+ database: { path: fixture.database },
221
+ pty: daemon.options,
222
+ fs: { filewatcher: false },
223
+ })
224
+ const base = HttpServer.formatAddress(server.address)
225
+ const created = yield* request(base, "POST", "/api/experimental/session/ses_v8_daemon/terminal", {
226
+ args: [],
227
+ cwd: fixture.root,
228
+ title: "created",
229
+ env: {},
230
+ })
231
+ const terminal = Schema.decodeUnknownSync(PersistentPty.Info)(created.data)
232
+ expect(terminal.userTitle).toBeNull()
233
+
234
+ const renamed = yield* request(base, "PUT", `/api/experimental/persistent-pty/${terminal.id}`, { title: "build" })
235
+ expect(renamed.data).toMatchObject({ title: "build", userTitle: "build" })
236
+ expect(daemon.ops).toContain("rename")
237
+ expect(daemon.ops).not.toContain("list")
238
+
239
+ const missing = yield* Effect.promise(async () => {
240
+ const response = await fetch(new URL("/api/experimental/persistent-pty/pty_persistent_99", base), {
241
+ headers: { authorization: `Basic ${btoa("opencode:secret")}` },
242
+ })
243
+ await response.arrayBuffer()
244
+ return response.status
245
+ })
246
+ expect(missing).toBe(404)
247
+ }),
248
+ )
249
+
250
+ async function waitForTitle(client: ReturnType<typeof OpenCode.make>, ptyID: string, title: string) {
251
+ for (let attempt = 0; attempt < 100; attempt++) {
252
+ if ((await client.experimental.persistentPty.get({ ptyID })).title === title) return
253
+ await Bun.sleep(20)
254
+ }
255
+ throw new Error(`Terminal ${ptyID} did not report the title ${title}`)
256
+ }
257
+
258
+ async function waitForRead(client: ReturnType<typeof OpenCode.make>, sessionID: string, ptyID: string) {
259
+ for (let attempt = 0; attempt < 100; attempt++) {
260
+ const result = await client.experimental.persistentPty.read({ sessionID })
261
+ if (result?.ptyID === ptyID) return result
262
+ await Bun.sleep(20)
263
+ }
264
+ throw new Error(`Terminal ${ptyID} did not become current for ${sessionID}`)
265
+ }
266
+
267
+ smoke(
268
+ "rejects a cwd that is missing or not a directory without starting a shell",
269
+ () =>
270
+ Effect.gen(function* () {
271
+ const fixture = yield* testDirectory()
272
+ const server = yield* ServerProcess.start<never, never>({
273
+ hostname: "127.0.0.1",
274
+ port: 0,
275
+ password: "secret",
276
+ app: { version: "test-version" },
277
+ database: { path: fixture.database },
278
+ pty: { root: fixture.directory },
279
+ fs: { filewatcher: false },
280
+ })
281
+ const base = HttpServer.formatAddress(server.address)
282
+ const createPath = "/api/experimental/session/ses_invalid_cwd/terminal"
283
+ const file = path.join(fixture.root, "file.txt")
284
+ yield* Effect.promise(() => fs.writeFile(file, ""))
285
+ for (const cwd of [path.join(fixture.root, "missing"), file]) {
286
+ const response = yield* Effect.promise(async () => {
287
+ const response = await fetch(new URL(createPath, base), {
288
+ method: "POST",
289
+ headers: { authorization: `Basic ${btoa("opencode:secret")}`, "content-type": "application/json" },
290
+ body: JSON.stringify({ command: "/bin/sh", args: [], cwd, title: "invalid", env: {} }),
291
+ })
292
+ return { status: response.status, body: await response.json() }
293
+ })
294
+ expect(response).toEqual({
295
+ status: 400,
296
+ body: {
297
+ _tag: "InvalidRequestError",
298
+ message: `cwd is not a directory: ${cwd}`,
299
+ kind: "invalid_cwd",
300
+ field: "cwd",
301
+ },
302
+ })
303
+ }
304
+ // The daemon is never started, so no shell can have been spawned.
305
+ expect(existsSync(fixture.directory)).toBeFalse()
306
+ expect((yield* request(base, "GET", createPath)).data).toEqual([])
307
+ const valid = { command: "/bin/sh", args: [], cwd: fixture.root, title: "valid", env: {} }
308
+ const created = yield* request(base, "POST", createPath, valid)
309
+ const terminal = Schema.decodeUnknownSync(PersistentPty.Info)(created.data)
310
+ expect(terminal.cwd).toBe(fixture.root)
311
+ yield* request(base, "POST", "/api/experimental/persistent-pty/shutdown")
312
+ }),
313
+ 20_000,
314
+ )
315
+
316
+ smoke(
317
+ "creates two persistent terminals for one session through the client API",
318
+ () =>
319
+ Effect.gen(function* () {
320
+ const fixture = yield* testDirectory()
321
+ const server = yield* ServerProcess.start<never, never>({
322
+ hostname: "127.0.0.1",
323
+ port: 0,
324
+ password: "secret",
325
+ app: { version: "test-version" },
326
+ database: { path: fixture.database },
327
+ pty: { root: fixture.directory },
328
+ fs: { filewatcher: false },
329
+ })
330
+ const base = HttpServer.formatAddress(server.address)
331
+ const sessionID = Session.ID.make("ses_persistent_pty_test")
332
+ expect(existsSync(fixture.directory)).toBeFalse()
333
+ expect(yield* request(base, "POST", "/api/experimental/persistent-pty/handoff")).toEqual({
334
+ handoff: null,
335
+ })
336
+ expect((yield* request(base, "GET", `/api/experimental/session/${sessionID}/terminal`)).data).toEqual([])
337
+ expect(existsSync(fixture.directory)).toBeFalse()
338
+ const defaults = {
339
+ args: [],
340
+ cwd: fixture.root,
341
+ title: "default shell",
342
+ env: { SHELL: "/missing/client/zsh" },
343
+ }
344
+ const createPath = `/api/experimental/session/${sessionID}/terminal`
345
+ const terminal = Schema.decodeUnknownSync(PersistentPty.Info)(
346
+ (yield* request(base, "POST", createPath, defaults)).data,
347
+ )
348
+ expect(terminal.command).toBe("/bin/sh")
349
+ expect(terminal.cwd).toBe(fixture.root)
350
+ expect(terminal.cwd).not.toBe(process.cwd())
351
+ yield* request(base, "DELETE", `/api/experimental/persistent-pty/${terminal.id}`)
352
+ const root = Schema.decodeUnknownSync(PersistentPty.Info)(
353
+ (yield* request(base, "POST", createPath, {
354
+ args: ["-c", "printf 'root-cwd:%s\\n' \"$PWD\"; cat"],
355
+ title: "root directory",
356
+ env: {},
357
+ })).data,
358
+ )
359
+ expect(root.cwd).toBe(path.parse(fixture.root).root)
360
+ expect(root.cwd).not.toBe(process.cwd())
361
+ expect(yield* waitForText(base, root.id, `root-cwd:${root.cwd}`)).toContain(`root-cwd:${root.cwd}`)
362
+ yield* request(base, "DELETE", `/api/experimental/persistent-pty/${root.id}`)
363
+ const events = yield* Effect.promise(() => openEventStream(base))
364
+ const first = Schema.decodeUnknownSync(PersistentPty.Info)(
365
+ (yield* request(base, "POST", `/api/experimental/session/${sessionID}/terminal`, {
366
+ command: "/usr/bin/env",
367
+ // Exercise transport bursts without macOS's 1024-byte canonical line buffer limit.
368
+ args: ["/bin/sh", "-c", "stty -echo -icanon min 1 time 0; printf terminal-one; cat"],
369
+ cwd: process.cwd(),
370
+ title: "first",
371
+ env: {},
372
+ })).data,
373
+ )
374
+ expect(first.command).toBe("/usr/bin/env")
375
+ expect(first.args).toEqual(["/bin/sh", "-c", "stty -echo -icanon min 1 time 0; printf terminal-one; cat"])
376
+ expect(first.cwd).toBe(process.cwd())
377
+ expect(yield* Effect.promise(() => events.next("persistent-pty.added"))).toMatchObject({
378
+ data: { sessionID, terminal: { id: first.id } },
379
+ })
380
+ expect(first.size).toEqual({ cols: 80, rows: 24 })
381
+ const directories = yield* Effect.promise(() => fs.readdir(fixture.directory))
382
+ expect(directories).toHaveLength(1)
383
+ expect(directories[0]).toMatch(/^[0-9a-f-]{36}$/)
384
+ if (!directories[0]) throw new Error("Missing daemon directory")
385
+ expect(existsSync(path.join(fixture.directory, directories[0], "service.json"))).toBeTrue()
386
+ const second = Schema.decodeUnknownSync(PersistentPty.Info)(
387
+ (yield* request(base, "POST", `/api/experimental/session/${sessionID}/terminal`, {
388
+ command: "/bin/sh",
389
+ args: ["-c", "printf terminal-two; sleep 30"],
390
+ cwd: process.cwd(),
391
+ title: "second",
392
+ env: {},
393
+ })).data,
394
+ )
395
+
396
+ const terminals = Schema.decodeUnknownSync(Schema.Array(PersistentPty.Info))(
397
+ (yield* request(base, "GET", `/api/experimental/session/${sessionID}/terminal`)).data,
398
+ )
399
+ expect(terminals.map((terminal) => terminal.id).sort()).toEqual([first.id, second.id].sort())
400
+ expect(yield* waitForText(base, first.id, "terminal-one")).toContain("terminal-one")
401
+ expect(yield* waitForText(base, second.id, "terminal-two")).toContain("terminal-two")
402
+ yield* Effect.promise(() => verifySharedControl(base, first.id))
403
+ const snapshot = yield* request(base, "GET", `/api/experimental/persistent-pty/${first.id}/snapshot`)
404
+ if (
405
+ !isRecord(snapshot.data) ||
406
+ typeof snapshot.data.checkpoint !== "string" ||
407
+ !isRecord(snapshot.data.info) ||
408
+ !isRecord(snapshot.data.info.output) ||
409
+ typeof snapshot.data.info.output.tail !== "number"
410
+ )
411
+ throw new Error("Persistent PTY snapshot response was invalid")
412
+ expect(Buffer.from(snapshot.data.checkpoint, "base64").byteLength).toBeGreaterThan(0)
413
+ expect(snapshot.data.info.output.tail).toBeGreaterThan(0)
414
+
415
+ const ticket = yield* request(
416
+ base,
417
+ "POST",
418
+ `/api/experimental/persistent-pty/${first.id}/connect-token`,
419
+ undefined,
420
+ {
421
+ "x-opencode-ticket": "1",
422
+ },
423
+ )
424
+ if (!isRecord(ticket.data) || typeof ticket.data.ticket !== "string") throw new Error("Invalid connect ticket")
425
+ const connectTicket = ticket.data.ticket
426
+ yield* request(base, "DELETE", `/api/experimental/persistent-pty/${first.id}`)
427
+ yield* Effect.promise(async () => {
428
+ const url = new URL(`/api/experimental/persistent-pty/${first.id}/connect`, base)
429
+ url.searchParams.set("ticket", "invalid")
430
+ expect((await fetch(url)).status).toBe(403)
431
+ url.protocol = "ws:"
432
+ url.searchParams.set("ticket", connectTicket)
433
+ const socket = new WebSocket(url)
434
+ try {
435
+ const closed = await new Promise<CloseEvent>((resolve, reject) => {
436
+ const timeout = setTimeout(() => reject(new Error("Removed terminal socket did not close")), 5_000)
437
+ socket.addEventListener("close", (event) => {
438
+ clearTimeout(timeout)
439
+ resolve(event)
440
+ })
441
+ socket.addEventListener("error", () => {
442
+ clearTimeout(timeout)
443
+ reject(new Error("Valid ticket should upgrade before the missing terminal is reported"))
444
+ })
445
+ })
446
+ expect(closed.code).toBe(4404)
447
+ expect(closed.reason).toBe("terminal unavailable")
448
+ } finally {
449
+ socket.close()
450
+ }
451
+ })
452
+ expect(yield* Effect.promise(() => events.next("persistent-pty.removed"))).toMatchObject({
453
+ data: { sessionID, ptyID: first.id },
454
+ })
455
+ yield* request(base, "DELETE", `/api/experimental/persistent-pty/${second.id}`)
456
+ expect((yield* request(base, "GET", `/api/experimental/session/${sessionID}/terminal`)).data).toEqual([])
457
+
458
+ yield* request(base, "POST", "/api/experimental/persistent-pty/shutdown")
459
+
460
+ const unattended = Schema.decodeUnknownSync(PersistentPty.Info)(
461
+ (yield* request(base, "POST", `/api/experimental/session/${sessionID}/terminal`, {
462
+ command: "/bin/sh",
463
+ args: ["-c", "exit 7"],
464
+ cwd: process.cwd(),
465
+ title: "unattended",
466
+ env: {},
467
+ })).data,
468
+ )
469
+ yield* waitForStatus(base, unattended.id, "exited")
470
+ expect((yield* request(base, "GET", `/api/experimental/session/${sessionID}/terminal`)).data).toMatchObject([
471
+ { id: unattended.id, status: "exited" },
472
+ ])
473
+ yield* request(base, "DELETE", `/api/experimental/persistent-pty/${unattended.id}`)
474
+
475
+ const visible = Schema.decodeUnknownSync(PersistentPty.Info)(
476
+ (yield* request(base, "POST", `/api/experimental/session/${sessionID}/terminal`, {
477
+ command: "/bin/sh",
478
+ args: ["-c", "read value"],
479
+ cwd: process.cwd(),
480
+ title: "visible",
481
+ env: {},
482
+ })).data,
483
+ )
484
+ yield* attachAndExit(base, visible.id)
485
+ yield* waitForTerminals(base, sessionID, [])
486
+ yield* Effect.promise(() => events.close())
487
+ }),
488
+ 20_000,
489
+ )
490
+
491
+ smoke(
492
+ "isolates servers sharing a database and preserves terminals only through explicit restart handoff",
493
+ () =>
494
+ Effect.gen(function* () {
495
+ const fixture = yield* testDirectory()
496
+ const scope = yield* Scope.Scope
497
+ const originalScope = yield* Scope.fork(scope)
498
+ const options = {
499
+ hostname: "127.0.0.1",
500
+ port: 0,
501
+ password: "secret",
502
+ app: { version: "test-version" },
503
+ database: { path: fixture.database },
504
+ pty: { root: fixture.directory },
505
+ fs: { filewatcher: false },
506
+ }
507
+ const original = yield* ServerProcess.start<never, never>(options).pipe(
508
+ Effect.provideService(Scope.Scope, originalScope),
509
+ )
510
+ const base = HttpServer.formatAddress(original.address)
511
+ const sessionID = Session.ID.make("ses_persistent_pty_restart")
512
+ const first = Schema.decodeUnknownSync(PersistentPty.Info)(
513
+ (yield* request(base, "POST", `/api/experimental/session/${sessionID}/terminal`, {
514
+ command: "/bin/sh",
515
+ args: ["-c", "stty -echo; printf before-restart; exec cat"],
516
+ cwd: process.cwd(),
517
+ title: "survivor",
518
+ env: {},
519
+ })).data,
520
+ )
521
+ expect(yield* waitForText(base, first.id, "before-restart")).toContain("before-restart")
522
+ yield* Effect.acquireRelease(
523
+ Effect.promise(() => openTerminalSocket(base, first.id, "before-restart")),
524
+ (connection) => Effect.sync(() => connection.socket.close()),
525
+ )
526
+ expect((yield* request(base, "GET", `/api/experimental/session/${sessionID}/terminal/read`)).data).toMatchObject({
527
+ ptyID: first.id,
528
+ })
529
+
530
+ const independent = yield* ServerProcess.start<never, never>(options)
531
+ const otherBase = HttpServer.formatAddress(independent.address)
532
+ expect((yield* request(otherBase, "GET", `/api/experimental/session/${sessionID}/terminal`)).data).toEqual([])
533
+ expect((yield* request(otherBase, "GET", `/api/experimental/session/${sessionID}/terminal/read`)).data).toBeNull()
534
+
535
+ const handoff = Schema.decodeUnknownSync(PersistentPty.Handoff)(
536
+ (yield* request(base, "POST", "/api/experimental/persistent-pty/handoff")).handoff,
537
+ )
538
+ const registration = Schema.decodeUnknownSync(Schema.Struct({ pid: Schema.Number }))(
539
+ yield* Effect.promise(() => Bun.file(path.join(handoff.directory, "service.json")).json()),
540
+ )
541
+ yield* Scope.close(originalScope, Exit.void)
542
+ expect(process.kill(registration.pid, 0)).toBeTrue()
543
+ expect(process.kill(first.pid, 0)).toBeTrue()
544
+
545
+ const replacementScope = yield* Scope.fork(scope)
546
+ const replacement = yield* ServerProcess.start<never, never>({ ...options, pty: { ...options.pty, handoff } }).pipe(
547
+ Effect.provideService(Scope.Scope, replacementScope),
548
+ )
549
+ const replacementBase = HttpServer.formatAddress(replacement.address)
550
+ expect(
551
+ (yield* request(replacementBase, "GET", `/api/experimental/session/${sessionID}/terminal`)).data,
552
+ ).toMatchObject([{ id: first.id, pid: first.pid }])
553
+ expect(yield* waitForText(replacementBase, first.id, "before-restart")).toContain("before-restart")
554
+ expect(
555
+ (yield* request(replacementBase, "GET", `/api/experimental/session/${sessionID}/terminal/read`)).data,
556
+ ).toBeNull()
557
+
558
+ yield* Scope.close(replacementScope, Exit.void)
559
+ yield* waitForExit(registration.pid)
560
+ yield* waitForExit(first.pid)
561
+ expect(existsSync(path.join(handoff.directory, "service.json"))).toBeFalse()
562
+ }),
563
+ 30_000,
564
+ )
565
+
566
+ smoke(
567
+ "boots fresh on restart when the handed-off registration is gone",
568
+ () =>
569
+ Effect.gen(function* () {
570
+ const fixture = yield* testDirectory()
571
+ const scope = yield* Scope.Scope
572
+ const options = {
573
+ hostname: "127.0.0.1",
574
+ port: 0,
575
+ password: "secret",
576
+ app: { version: "test-version" },
577
+ database: { path: fixture.database },
578
+ fs: { filewatcher: false },
579
+ pty: { root: fixture.directory },
580
+ }
581
+ const sessionID = Session.ID.make("ses_persistent_pty_gone")
582
+ const originalScope = yield* Scope.fork(scope)
583
+ const original = yield* ServerProcess.start<never, never>(options).pipe(
584
+ Effect.provideService(Scope.Scope, originalScope),
585
+ )
586
+ const base = HttpServer.formatAddress(original.address)
587
+ const first = Schema.decodeUnknownSync(PersistentPty.Info)(
588
+ (yield* request(base, "POST", `/api/experimental/session/${sessionID}/terminal`, {
589
+ command: "/bin/sh",
590
+ args: ["-c", "stty -echo; printf before-restart; exec cat"],
591
+ cwd: process.cwd(),
592
+ title: "first",
593
+ env: {},
594
+ })).data,
595
+ )
596
+ expect(yield* waitForText(base, first.id, "before-restart")).toContain("before-restart")
597
+ const handoff = Schema.decodeUnknownSync(PersistentPty.Handoff)(
598
+ (yield* request(base, "POST", "/api/experimental/persistent-pty/handoff")).handoff,
599
+ )
600
+ yield* Scope.close(originalScope, Exit.void)
601
+ // Simulate macOS purging the registration while the daemon waits for its successor.
602
+ yield* Effect.promise(() => fs.rm(path.join(handoff.directory, "service.json")))
603
+
604
+ const fresh = yield* ServerProcess.start<never, never>({ ...options, pty: { ...options.pty, handoff } })
605
+ const freshBase = HttpServer.formatAddress(fresh.address)
606
+ expect((yield* request(freshBase, "GET", `/api/experimental/session/${sessionID}/terminal`)).data).toEqual([])
607
+ const second = Schema.decodeUnknownSync(PersistentPty.Info)(
608
+ (yield* request(freshBase, "POST", `/api/experimental/session/${sessionID}/terminal`, {
609
+ command: "/bin/sh",
610
+ args: ["-c", "printf after-restart; exec cat"],
611
+ cwd: process.cwd(),
612
+ title: "fresh",
613
+ env: {},
614
+ })).data,
615
+ )
616
+ expect(yield* waitForText(freshBase, second.id, "after-restart")).toContain("after-restart")
617
+ }),
618
+ 30_000,
619
+ )
620
+
621
+ function testDirectory() {
622
+ return Effect.acquireRelease(
623
+ Effect.promise(async () => {
624
+ const environment = { binary: process.env.OPENCODE_PTY_BIN, shell: process.env.SHELL }
625
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-pty-server-test-"))
626
+ process.env.OPENCODE_PTY_BIN = binary
627
+ process.env.SHELL = "/bin/sh"
628
+ return {
629
+ database: path.join(root, "opencode.db"),
630
+ directory: path.join(root, "runtime"),
631
+ environment,
632
+ root,
633
+ }
634
+ }),
635
+ (fixture) =>
636
+ Effect.promise(async () => {
637
+ await fs.rm(fixture.root, { recursive: true, force: true })
638
+ restore("OPENCODE_PTY_BIN", fixture.environment.binary)
639
+ restore("SHELL", fixture.environment.shell)
640
+ }),
641
+ )
642
+ }
643
+
644
+ function waitForExit(pid: number) {
645
+ return Effect.promise(async () => {
646
+ for (let attempt = 0; attempt < 100; attempt++) {
647
+ try {
648
+ process.kill(pid, 0)
649
+ } catch (error) {
650
+ if (isRecord(error) && error.code === "ESRCH") return
651
+ throw error
652
+ }
653
+ await Bun.sleep(20)
654
+ }
655
+ throw new Error(`Process ${pid} survived its server scope`)
656
+ })
657
+ }
658
+
659
+ function request(base: string, method: string, pathname: string, body?: unknown, headers?: Record<string, string>) {
660
+ return Effect.tryPromise({
661
+ try: async () => {
662
+ const response = await fetch(new URL(pathname, base), {
663
+ method,
664
+ headers: {
665
+ authorization: `Basic ${btoa("opencode:secret")}`,
666
+ ...headers,
667
+ ...(body === undefined ? {} : { "content-type": "application/json" }),
668
+ },
669
+ body: body === undefined ? undefined : JSON.stringify(body),
670
+ })
671
+ if (!response.ok) throw new Error(`${method} ${pathname} failed (${response.status}): ${await response.text()}`)
672
+ if (response.status === 204) return {}
673
+ const value: unknown = await response.json()
674
+ if (!isRecord(value)) throw new Error(`${method} ${pathname} returned a non-object response`)
675
+ return value
676
+ },
677
+ catch: (cause) => (cause instanceof Error ? cause : new Error(String(cause))),
678
+ })
679
+ }
680
+
681
+ async function openEventStream(base: string) {
682
+ const response = await fetch(new URL("/api/event", base), {
683
+ headers: { authorization: `Basic ${btoa("opencode:secret")}` },
684
+ })
685
+ if (!response.ok || !response.body) throw new Error(`Persistent PTY event stream failed (${response.status})`)
686
+ const reader = response.body.getReader()
687
+ const decoder = new TextDecoder()
688
+ let pending = ""
689
+ return {
690
+ async next(type: string) {
691
+ while (true) {
692
+ const boundary = pending.indexOf("\n\n")
693
+ if (boundary !== -1) {
694
+ const frame = pending.slice(0, boundary)
695
+ pending = pending.slice(boundary + 2)
696
+ const data = frame
697
+ .split("\n")
698
+ .find((line) => line.startsWith("data: "))
699
+ ?.slice(6)
700
+ if (!data) continue
701
+ const event: unknown = JSON.parse(data)
702
+ if (isRecord(event) && event.type === type) return event
703
+ continue
704
+ }
705
+ const chunk = await reader.read()
706
+ if (chunk.done) throw new Error(`Persistent PTY event stream closed before ${type}`)
707
+ pending += decoder.decode(chunk.value, { stream: true })
708
+ }
709
+ },
710
+ close: () => reader.cancel(),
711
+ }
712
+ }
713
+
714
+ function waitForText(base: string, ptyID: string, expected: string) {
715
+ return Effect.tryPromise({
716
+ try: async () => {
717
+ for (let attempt = 0; attempt < 40; attempt++) {
718
+ const response = await Effect.runPromise(
719
+ request(base, "GET", `/api/experimental/persistent-pty/${ptyID}/snapshot`),
720
+ )
721
+ if (isRecord(response.data) && typeof response.data.text === "string" && response.data.text.includes(expected))
722
+ return response.data.text
723
+ await Bun.sleep(50)
724
+ }
725
+ throw new Error(`Persistent PTY snapshot did not contain ${expected}`)
726
+ },
727
+ catch: (cause) => (cause instanceof Error ? cause : new Error(String(cause))),
728
+ })
729
+ }
730
+
731
+ function waitForStatus(base: string, ptyID: string, status: string) {
732
+ return Effect.tryPromise({
733
+ try: async () => {
734
+ for (let attempt = 0; attempt < 40; attempt++) {
735
+ const response = await Effect.runPromise(request(base, "GET", `/api/experimental/persistent-pty/${ptyID}`))
736
+ if (isRecord(response.data) && response.data.status === status) return
737
+ await Bun.sleep(50)
738
+ }
739
+ throw new Error(`Persistent PTY ${ptyID} did not reach status ${status}`)
740
+ },
741
+ catch: (cause) => (cause instanceof Error ? cause : new Error(String(cause))),
742
+ })
743
+ }
744
+
745
+ function attachAndExit(base: string, ptyID: string) {
746
+ return Effect.tryPromise({
747
+ try: async () => {
748
+ const response = await Effect.runPromise(
749
+ request(base, "POST", `/api/experimental/persistent-pty/${ptyID}/connect-token`, undefined, {
750
+ "x-opencode-ticket": "1",
751
+ }),
752
+ )
753
+ if (!isRecord(response.data) || typeof response.data.ticket !== "string")
754
+ throw new Error("Persistent PTY connect token response was invalid")
755
+ const url = new URL(`/api/experimental/persistent-pty/${ptyID}/connect`, base)
756
+ url.protocol = "ws:"
757
+ url.searchParams.set("ticket", response.data.ticket)
758
+ await new Promise<void>((resolve, reject) => {
759
+ const socket = new WebSocket(url)
760
+ const timeout = setTimeout(() => {
761
+ socket.close()
762
+ reject(new Error("Persistent PTY did not exit while attached"))
763
+ }, 5_000)
764
+ socket.addEventListener("message", (event) => {
765
+ if (typeof event.data !== "string") return
766
+ const message: unknown = JSON.parse(event.data)
767
+ if (!isRecord(message)) return
768
+ if (message.type === "attached") socket.send(new Uint8Array([4]))
769
+ if (message.type !== "exited") return
770
+ clearTimeout(timeout)
771
+ socket.close()
772
+ resolve()
773
+ })
774
+ socket.addEventListener("error", () => {
775
+ clearTimeout(timeout)
776
+ reject(new Error("Persistent PTY WebSocket failed"))
777
+ })
778
+ })
779
+ },
780
+ catch: (cause) => (cause instanceof Error ? cause : new Error(String(cause))),
781
+ })
782
+ }
783
+
784
+ async function verifySharedControl(base: string, ptyID: string) {
785
+ const first = await openTerminalSocket(base, ptyID, "first")
786
+ const second = await openTerminalSocket(base, ptyID, "second", "observer")
787
+ try {
788
+ first.socket.send(controlFrame(90, 25))
789
+ first.socket.send(inputFrame(90, 25, "from-first\n"))
790
+ await waitForSocketOutput([first, second], "from-first")
791
+
792
+ second.socket.send(inputFrame(70, 20, "from-second\n"))
793
+ await waitForSocketOutput([first, second], "from-second")
794
+
795
+ // opencode-pty reads the foreground process from /proc on Linux and reports none elsewhere
796
+ // (foreground_process in packages/process-daemon/src/service.rs).
797
+ if (process.platform === "linux") await waitForForegroundProcess([first, second], "cat")
798
+ if (process.platform !== "linux") {
799
+ expect(first.foregroundProcess).toBeNull()
800
+ expect(second.foregroundProcess).toBeNull()
801
+ }
802
+
803
+ for (const character of "printf abc | rev\n") second.socket.send(inputFrame(70, 20, character))
804
+ await waitForSocketOutput([first, second], "printf abc | rev")
805
+
806
+ second.socket.send(inputFrame(70, 20, "x".repeat(1024)))
807
+ second.socket.send(inputFrame(70, 20, "after-burst\n"))
808
+ await waitForSocketOutput([first, second], "after-burst")
809
+ expect(first.output).toContain("x".repeat(1024) + "after-burst")
810
+ expect(second.output).toContain("x".repeat(1024) + "after-burst")
811
+ expect(first.closed).toBeFalse()
812
+ expect(second.closed).toBeFalse()
813
+ expect(first.resizes).toBeGreaterThan(0)
814
+ expect(second.resizes).toBeGreaterThan(0)
815
+ expect(first.output).not.toContain("\0")
816
+ expect(second.output).not.toContain("\0")
817
+ expect(first.size).toEqual({ cols: 70, rows: 20 })
818
+ expect(second.size).toEqual({ cols: 70, rows: 20 })
819
+
820
+ await waitForController(first, "second")
821
+ second.socket.close()
822
+ // Promotion is emitted by the daemon only after the server detaches the closed socket.
823
+ await waitForController(first, "first")
824
+ expect(second.closed).toBeTrue()
825
+ first.socket.send(inputFrame(70, 20, "after-detach\n"))
826
+ await waitForSocketOutput([first], "after-detach")
827
+
828
+ const replay = await openTerminalSocket(base, ptyID, "replay", "observer")
829
+ try {
830
+ // openTerminalSocket resolves at replay_complete, before any new input is sent.
831
+ expect(replay.output).toContain("from-first")
832
+ expect(replay.output).toContain("from-second")
833
+ expect(replay.output).toContain("after-detach")
834
+ first.socket.send(inputFrame(70, 20, "after-replay\n"))
835
+ await waitForSocketOutput([first, replay], "after-replay")
836
+ } finally {
837
+ replay.socket.close()
838
+ }
839
+ } finally {
840
+ first.socket.close()
841
+ second.socket.close()
842
+ }
843
+ }
844
+
845
+ async function openTerminalSocket(
846
+ base: string,
847
+ ptyID: string,
848
+ attachmentID: string,
849
+ role: "controller" | "observer" = "controller",
850
+ ) {
851
+ const response = await Effect.runPromise(
852
+ request(base, "POST", `/api/experimental/persistent-pty/${ptyID}/connect-token`, undefined, {
853
+ "x-opencode-ticket": "1",
854
+ }),
855
+ )
856
+ if (!isRecord(response.data) || typeof response.data.ticket !== "string")
857
+ throw new Error("Persistent PTY connect token response was invalid")
858
+ const url = new URL(`/api/experimental/persistent-pty/${ptyID}/connect`, base)
859
+ url.protocol = "ws:"
860
+ url.searchParams.set("ticket", response.data.ticket)
861
+ url.searchParams.set("attachment_id", attachmentID)
862
+ url.searchParams.set("role", role)
863
+ url.searchParams.set("takeover", "true")
864
+ url.searchParams.set("input_protocol", "1")
865
+ const state = {
866
+ socket: new WebSocket(url),
867
+ output: "",
868
+ closed: false,
869
+ resizes: 0,
870
+ size: undefined as { cols: number; rows: number } | undefined,
871
+ controller: undefined as string | undefined,
872
+ foregroundProcess: null as string | null,
873
+ }
874
+ state.socket.binaryType = "arraybuffer"
875
+ await new Promise<void>((resolve, reject) => {
876
+ const timeout = setTimeout(() => reject(new Error("Persistent PTY WebSocket did not attach")), 5_000)
877
+ let attached = false
878
+ state.socket.addEventListener("message", (event) => {
879
+ if (event.data instanceof ArrayBuffer) {
880
+ state.output += new TextDecoder().decode(event.data)
881
+ return
882
+ }
883
+ if (typeof event.data !== "string") return
884
+ const message: unknown = JSON.parse(event.data)
885
+ if (!isRecord(message)) return
886
+ if (message.type === "resized") {
887
+ if (typeof message.checkpoint !== "string") {
888
+ clearTimeout(timeout)
889
+ reject(new Error("Persistent PTY resize omitted its checkpoint"))
890
+ return
891
+ }
892
+ state.resizes++
893
+ if (typeof message.cols === "number" && typeof message.rows === "number")
894
+ state.size = { cols: message.cols, rows: message.rows }
895
+ return
896
+ }
897
+ if (message.type === "controller_changed") {
898
+ state.controller = typeof message.attachmentID === "string" ? message.attachmentID : undefined
899
+ return
900
+ }
901
+ if (message.type === "foreground_process_changed") {
902
+ state.foregroundProcess = typeof message.process === "string" ? message.process : null
903
+ return
904
+ }
905
+ if (message.type === "attached") {
906
+ if (message.inputProtocol === 1) {
907
+ if (isRecord(message.info) && typeof message.info.foregroundProcess === "string")
908
+ state.foregroundProcess = message.info.foregroundProcess
909
+ attached = true
910
+ return
911
+ }
912
+ clearTimeout(timeout)
913
+ reject(new Error("Persistent PTY WebSocket did not negotiate framed input"))
914
+ return
915
+ }
916
+ if (message.type !== "replay_complete" || !attached) return
917
+ clearTimeout(timeout)
918
+ resolve()
919
+ })
920
+ state.socket.addEventListener("close", () => {
921
+ state.closed = true
922
+ })
923
+ state.socket.addEventListener("error", () => {
924
+ clearTimeout(timeout)
925
+ reject(new Error("Persistent PTY WebSocket failed"))
926
+ })
927
+ })
928
+ return state
929
+ }
930
+
931
+ async function waitForController(socket: { controller: string | undefined; closed: boolean }, expected: string) {
932
+ for (let attempt = 0; attempt < 100; attempt++) {
933
+ if (socket.controller === expected) return
934
+ if (socket.closed) throw new Error("Persistent PTY observer disconnected")
935
+ await Bun.sleep(20)
936
+ }
937
+ throw new Error(`Persistent PTY controller did not become ${expected}: ${socket.controller}`)
938
+ }
939
+
940
+ async function waitForForegroundProcess(
941
+ sockets: Array<{ foregroundProcess: string | null; closed: boolean }>,
942
+ expected: string,
943
+ ) {
944
+ for (let attempt = 0; attempt < 100; attempt++) {
945
+ if (sockets.every((socket) => socket.foregroundProcess === expected)) return
946
+ if (sockets.some((socket) => socket.closed)) throw new Error("Persistent PTY observer disconnected")
947
+ await Bun.sleep(20)
948
+ }
949
+ throw new Error(
950
+ `Persistent PTY sockets did not both report ${expected}: ${JSON.stringify(sockets.map((socket) => socket.foregroundProcess))}`,
951
+ )
952
+ }
953
+
954
+ function inputFrame(cols: number, rows: number, input: string) {
955
+ const data = new TextEncoder().encode(input)
956
+ const frame = new Uint8Array(5 + data.byteLength)
957
+ const view = new DataView(frame.buffer)
958
+ frame[0] = 1
959
+ view.setUint16(1, cols)
960
+ view.setUint16(3, rows)
961
+ frame.set(data, 5)
962
+ return frame
963
+ }
964
+
965
+ function controlFrame(cols: number, rows: number) {
966
+ const frame = new Uint8Array(5)
967
+ const view = new DataView(frame.buffer)
968
+ view.setUint16(1, cols)
969
+ view.setUint16(3, rows)
970
+ return frame
971
+ }
972
+
973
+ async function waitForSocketOutput(sockets: Array<{ output: string; closed: boolean }>, expected: string) {
974
+ for (let attempt = 0; attempt < 100; attempt++) {
975
+ if (sockets.every((socket) => socket.output.includes(expected))) return
976
+ if (sockets.some((socket) => socket.closed)) throw new Error("Persistent PTY observer disconnected")
977
+ await Bun.sleep(20)
978
+ }
979
+ throw new Error(
980
+ `Persistent PTY sockets did not both receive ${expected}: ${JSON.stringify(sockets.map((socket) => socket.output))}`,
981
+ )
982
+ }
983
+
984
+ function waitForTerminals(base: string, sessionID: string, expected: unknown[]) {
985
+ return Effect.tryPromise({
986
+ try: async () => {
987
+ for (let attempt = 0; attempt < 40; attempt++) {
988
+ const response = await Effect.runPromise(
989
+ request(base, "GET", `/api/experimental/session/${sessionID}/terminal`),
990
+ )
991
+ if (JSON.stringify(response.data) === JSON.stringify(expected)) return
992
+ await Bun.sleep(50)
993
+ }
994
+ throw new Error(`Persistent PTYs for ${sessionID} did not reconcile`)
995
+ },
996
+ catch: (cause) => (cause instanceof Error ? cause : new Error(String(cause))),
997
+ })
998
+ }
999
+
1000
+ function restore(key: string, value: string | undefined) {
1001
+ if (value === undefined) delete process.env[key]
1002
+ if (value !== undefined) process.env[key] = value
1003
+ }
1004
+
1005
+ function isRecord(value: unknown): value is Record<string, unknown> {
1006
+ return typeof value === "object" && value !== null && !Array.isArray(value)
1007
+ }