@zyro-sec/server 1.0.2 → 1.0.4

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 (130) hide show
  1. package/package.json +8 -8
  2. package/script/build.ts +28 -28
  3. package/script/pack.ts +5 -5
  4. package/script/workerd-probe.ts +59 -59
  5. package/src/api.ts +12 -12
  6. package/src/auth.ts +70 -70
  7. package/src/content-headers.ts +32 -32
  8. package/src/cors.ts +34 -34
  9. package/src/event-feed.ts +93 -93
  10. package/src/fetch.ts +67 -67
  11. package/src/handlers/agent.ts +23 -23
  12. package/src/handlers/artifact.ts +242 -242
  13. package/src/handlers/automation.ts +63 -63
  14. package/src/handlers/blob.ts +55 -55
  15. package/src/handlers/command.ts +8 -8
  16. package/src/handlers/config.ts +26 -26
  17. package/src/handlers/credential.ts +87 -87
  18. package/src/handlers/debug.ts +57 -57
  19. package/src/handlers/event.ts +38 -38
  20. package/src/handlers/form.ts +15 -15
  21. package/src/handlers/fs.ts +180 -180
  22. package/src/handlers/generate.ts +117 -117
  23. package/src/handlers/integration.ts +310 -310
  24. package/src/handlers/job.ts +29 -29
  25. package/src/handlers/location.ts +33 -33
  26. package/src/handlers/machine.ts +336 -336
  27. package/src/handlers/mcp.ts +160 -160
  28. package/src/handlers/media.ts +44 -44
  29. package/src/handlers/message.ts +82 -82
  30. package/src/handlers/migration.ts +13 -13
  31. package/src/handlers/model.ts +25 -25
  32. package/src/handlers/permission.ts +131 -131
  33. package/src/handlers/persistent-pty.ts +285 -285
  34. package/src/handlers/plugin.ts +97 -97
  35. package/src/handlers/project.ts +23 -23
  36. package/src/handlers/provider.ts +32 -32
  37. package/src/handlers/pty-socket.ts +47 -47
  38. package/src/handlers/pty.ts +181 -181
  39. package/src/handlers/push.ts +67 -67
  40. package/src/handlers/reference.ts +8 -8
  41. package/src/handlers/rpc.ts +31 -31
  42. package/src/handlers/server.ts +58 -58
  43. package/src/handlers/session-error.ts +47 -47
  44. package/src/handlers/session.ts +722 -722
  45. package/src/handlers/shell.ts +72 -72
  46. package/src/handlers/skill.ts +34 -34
  47. package/src/handlers/usage.ts +23 -23
  48. package/src/handlers/vcs.ts +104 -104
  49. package/src/handlers/voice.ts +50 -50
  50. package/src/handlers/websearch.ts +50 -50
  51. package/src/handlers/worktree.ts +60 -60
  52. package/src/handlers.ts +69 -69
  53. package/src/location.ts +86 -86
  54. package/src/media-uri.ts +13 -13
  55. package/src/middleware/authorization.ts +111 -111
  56. package/src/middleware/defect-response.ts +39 -39
  57. package/src/middleware/form-location.ts +44 -44
  58. package/src/middleware/schema-error.ts +49 -49
  59. package/src/middleware/session-location.ts +30 -30
  60. package/src/options.ts +61 -61
  61. package/src/pairing.ts +36 -36
  62. package/src/process.ts +274 -274
  63. package/src/range.ts +16 -16
  64. package/src/request-site.ts +36 -36
  65. package/src/request-tracing.ts +9 -9
  66. package/src/routes.ts +261 -261
  67. package/src/server-info.ts +41 -41
  68. package/src/service-status.ts +30 -30
  69. package/src/workerd.ts +184 -184
  70. package/test/fixture/mcp-starts.cjs +20 -20
  71. package/test/fixture/routes.ts +37 -37
  72. package/test/fixture/server.ts +20 -20
  73. package/test/fixture/worktree-delegate/index.ts +13 -13
  74. package/test/fixture/worktree-plugin/index.ts +47 -47
  75. package/tsconfig.build.json +15 -15
  76. package/tsconfig.json +11 -11
  77. package/test/artifact.test.ts +0 -224
  78. package/test/auth.test.ts +0 -24
  79. package/test/automation.test.ts +0 -315
  80. package/test/client-mcp.test.ts +0 -369
  81. package/test/codemode-api.test.ts +0 -88
  82. package/test/config.test.ts +0 -104
  83. package/test/cors.test.ts +0 -24
  84. package/test/defect-response.test.ts +0 -83
  85. package/test/event-feed.test.ts +0 -201
  86. package/test/fetch-option.test.ts +0 -104
  87. package/test/fetch.test.ts +0 -698
  88. package/test/flag-channel.test.ts +0 -126
  89. package/test/fs.test.ts +0 -439
  90. package/test/generate.test.ts +0 -132
  91. package/test/handler-policy.test.ts +0 -43
  92. package/test/heap-dump.test.ts +0 -137
  93. package/test/integration-policy.test.ts +0 -93
  94. package/test/job.test.ts +0 -186
  95. package/test/machine-iroh.test.ts +0 -259
  96. package/test/machine-link.test.ts +0 -1234
  97. package/test/machine-routes.test.ts +0 -198
  98. package/test/media.test.ts +0 -343
  99. package/test/message.test.ts +0 -105
  100. package/test/model.test.ts +0 -62
  101. package/test/options.test.ts +0 -42
  102. package/test/permission-saved.test.ts +0 -73
  103. package/test/persistent-pty.test.ts +0 -1007
  104. package/test/process.test.ts +0 -261
  105. package/test/provider.test.ts +0 -88
  106. package/test/pty-socket.property.test.ts +0 -240
  107. package/test/pty-socket.test.ts +0 -89
  108. package/test/pty-transport.test.ts +0 -200
  109. package/test/push-routes.test.ts +0 -157
  110. package/test/request-site.test.ts +0 -71
  111. package/test/request-tracing.test.ts +0 -87
  112. package/test/rpc-handler-errors.test.ts +0 -76
  113. package/test/schema-error.test.ts +0 -68
  114. package/test/service-status.test.ts +0 -34
  115. package/test/session-admit-location.test.ts +0 -92
  116. package/test/session-create.test.ts +0 -65
  117. package/test/session-diff.test.ts +0 -100
  118. package/test/session-form.test.ts +0 -50
  119. package/test/session-import.test.ts +0 -152
  120. package/test/session-instances.test.ts +0 -335
  121. package/test/session-unarchive.test.ts +0 -73
  122. package/test/session-update.test.ts +0 -66
  123. package/test/skill.test.ts +0 -57
  124. package/test/sse-failure.test.ts +0 -71
  125. package/test/usage.test.ts +0 -88
  126. package/test/vcs.test.ts +0 -356
  127. package/test/video-generate.test.ts +0 -131
  128. package/test/voice.test.ts +0 -170
  129. package/test/workerd.test.ts +0 -227
  130. package/test/worktree.test.ts +0 -333
@@ -1,698 +0,0 @@
1
- import { expect } from "bun:test"
2
- import fs from "node:fs/promises"
3
- import { createServer } from "node:http"
4
- import path from "node:path"
5
- import { Agent } from "@zyro-sec/schema/agent"
6
- import { Integration } from "@zyro-sec/schema/integration"
7
- import { ServerInfo } from "@zyro-sec/protocol/groups/server"
8
- import { Effect, Schedule, Schema } from "effect"
9
- import { Session } from "@zyro-sec/schema/session"
10
- import { tmpdir } from "../../core/test/fixture/tmpdir"
11
- import { it } from "../../core/test/lib/effect"
12
- import { ServerFetch } from "../src/fetch"
13
-
14
- const options = {
15
- app: { version: "test-version" },
16
- database: { path: ":memory:" },
17
- config: { project: false },
18
- models: { fetch: false },
19
- fs: { filewatcher: false },
20
- } as const
21
-
22
- it.live("returns LocationNotFoundError for a missing folder and recovers once it exists", () =>
23
- Effect.gen(function* () {
24
- const config = yield* Effect.acquireDisposable(Effect.promise(() => tmpdir("opencode-directory-errors-")))
25
- const directory = path.join(config.path, "project")
26
- const handler = yield* ServerFetch.make({ ...options, config: { directory: config.path } })
27
- // Session creation only resolves its placement; it does not boot the Location graph.
28
- const created = yield* Effect.promise(() =>
29
- handler(
30
- new Request("http://opencode.local/api/session", {
31
- method: "POST",
32
- headers: { "content-type": "application/json", "x-opencode-directory": encodeURIComponent(directory) },
33
- body: JSON.stringify({ location: { directory } }),
34
- }),
35
- ),
36
- )
37
- expect(created.status).toBe(200)
38
- const session = Schema.decodeUnknownSync(Schema.Struct({ data: Session.Info }))(
39
- yield* Effect.promise(() => created.json()),
40
- ).data
41
- const endpoints = [
42
- "/api/model",
43
- "/api/integration",
44
- `/api/session/${session.id}/permission`,
45
- "/api/session/global/form",
46
- ]
47
- for (const endpoint of endpoints) {
48
- const response = yield* Effect.promise(() =>
49
- handler(
50
- new Request(`http://opencode.local${endpoint}`, {
51
- headers: { "x-opencode-directory": encodeURIComponent(directory) },
52
- }),
53
- ),
54
- )
55
- expect({ endpoint, status: response.status }).toEqual({ endpoint, status: 404 })
56
- expect(yield* Effect.promise(() => response.json())).toEqual({
57
- _tag: "LocationNotFoundError",
58
- location: { directory },
59
- message: `Location not found: ${directory}`,
60
- })
61
- }
62
- yield* Effect.promise(() => fs.mkdir(directory))
63
- const recovered = yield* Effect.promise(() =>
64
- handler(
65
- new Request("http://opencode.local/api/model", {
66
- headers: { "x-opencode-directory": encodeURIComponent(directory) },
67
- }),
68
- ),
69
- )
70
- expect(recovered.status).toBe(200)
71
- }),
72
- )
73
-
74
- it.live("manages a session whose directory was deleted", () =>
75
- Effect.gen(function* () {
76
- const config = yield* Effect.acquireDisposable(Effect.promise(() => tmpdir("opencode-deleted-directory-")))
77
- const directory = path.join(config.path, "project")
78
- yield* Effect.promise(() => fs.mkdir(directory))
79
- const handler = yield* ServerFetch.make({ ...options, config: { directory: config.path } })
80
- const request = (endpoint: string, method: string, body?: unknown) =>
81
- Effect.promise(() =>
82
- handler(
83
- new Request(`http://opencode.local${endpoint}`, {
84
- method,
85
- headers: { "content-type": "application/json" },
86
- body: body === undefined ? undefined : JSON.stringify(body),
87
- }),
88
- ),
89
- )
90
- const created = yield* request("/api/session", "POST", { location: { directory } })
91
- expect(created.status).toBe(200)
92
- const session = Schema.decodeUnknownSync(Schema.Struct({ data: Session.Info }))(
93
- yield* Effect.promise(() => created.json()),
94
- ).data
95
- yield* Effect.promise(() => fs.rm(directory, { recursive: true }))
96
-
97
- const statuses = [
98
- yield* request(`/api/session/${session.id}`, "PATCH", { title: "Renamed" }),
99
- yield* request(`/api/session/${session.id}`, "PATCH", { archived: true }),
100
- yield* request(`/api/session/${session.id}/interrupt`, "POST"),
101
- yield* request(`/api/experimental/session/${session.id}/instructions/entries`, "GET"),
102
- ].map((response) => response.status)
103
- expect(statuses).toEqual([204, 204, 200, 200])
104
-
105
- const fetched = yield* request(`/api/session/${session.id}`, "GET")
106
- const updated = Schema.decodeUnknownSync(Schema.Struct({ data: Session.Info }))(
107
- yield* Effect.promise(() => fetched.json()),
108
- ).data
109
- expect(updated.title).toBe("Renamed")
110
- expect(updated.time.archived).toBeDefined()
111
-
112
- // Title generation still runs in the session's folder.
113
- const generated = yield* request(`/api/session/${session.id}`, "PATCH", { title: "" })
114
- expect(generated.status).toBe(404)
115
- expect(yield* Effect.promise(() => generated.json())).toEqual({
116
- _tag: "LocationNotFoundError",
117
- location: { directory },
118
- message: `Location not found: ${directory}`,
119
- })
120
-
121
- const missing = yield* request("/api/session/ses_missing/interrupt", "POST")
122
- expect(missing.status).toBe(404)
123
- expect(((yield* Effect.promise(() => missing.json())) as { _tag: string })._tag).toBe("SessionNotFoundError")
124
- }),
125
- )
126
-
127
- type Handler = (request: Request) => Promise<Response>
128
-
129
- function occupy(port: number, cancel = false) {
130
- return Effect.gen(function* () {
131
- const requests: string[] = []
132
- // A localhost listener occupies only one family; Bun can bind the other.
133
- const servers = ["127.0.0.1", "::1"].map((host) => ({
134
- host,
135
- server: createServer((request, response) => {
136
- requests.push(request.url ?? "")
137
- response.end(cancel ? "cancelled" : "still running", () => {
138
- if (cancel)
139
- servers.forEach((item) => {
140
- // Bun clears its native handle in close(), so force-close connections first.
141
- item.server.closeAllConnections()
142
- item.server.close()
143
- })
144
- })
145
- }),
146
- }))
147
- yield* Effect.addFinalizer(() =>
148
- Effect.forEach(servers, (item) =>
149
- Effect.callback<void>((resume) => {
150
- item.server.closeAllConnections()
151
- item.server.close(() => resume(Effect.void))
152
- }),
153
- ),
154
- )
155
- yield* Effect.forEach(servers, (item) =>
156
- Effect.callback<void, Error>((resume) => {
157
- const onError = (error: Error) => resume(Effect.fail(error))
158
- item.server.once("error", onError)
159
- item.server.listen(port, item.host, () => {
160
- item.server.off("error", onError)
161
- resume(Effect.void)
162
- })
163
- }),
164
- )
165
- return requests
166
- })
167
- }
168
-
169
- // A server without its own config directory reads the developer's global config, whose remote MCP servers would
170
- // reach the network.
171
- const isolated = Effect.gen(function* () {
172
- const config = yield* Effect.acquireDisposable(Effect.promise(() => tmpdir("opencode-openai-oauth-")))
173
- return yield* ServerFetch.make({ ...options, config: { ...options.config, directory: config.path } })
174
- })
175
-
176
- const connectOpenAI = (handler: Handler) =>
177
- Effect.gen(function* () {
178
- // Catalog endpoints no longer wait for plugin initialization.
179
- yield* Effect.gen(function* () {
180
- const response = yield* Effect.promise(() => handler(new Request("http://opencode.local/api/integration")))
181
- expect(response.status).toBe(200)
182
- const body = Schema.decodeUnknownSync(Schema.Struct({ data: Schema.Array(Integration.Info) }))(
183
- yield* Effect.promise(() => response.json()),
184
- )
185
- return body.data.some(
186
- (integration) =>
187
- integration.id === "openai" &&
188
- integration.methods.some((method) => method.type === "oauth" && method.id === "chatgpt-browser"),
189
- )
190
- }).pipe(
191
- Effect.filterOrFail((ready) => ready),
192
- Effect.retry(Schedule.spaced("10 millis")),
193
- Effect.timeout("2 seconds"),
194
- )
195
- return yield* Effect.promise(() =>
196
- handler(
197
- new Request("http://opencode.local/api/integration/openai/connect/oauth", {
198
- method: "POST",
199
- headers: { "content-type": "application/json" },
200
- body: JSON.stringify({ methodID: "chatgpt-browser" }),
201
- }),
202
- ),
203
- )
204
- })
205
-
206
- it.live("serves the HttpApi and enforces Basic auth like the Node server", () =>
207
- Effect.gen(function* () {
208
- const handler = yield* ServerFetch.make({ ...options, password: "secret" })
209
-
210
- const denied = yield* Effect.promise(() => handler(new Request("http://opencode.local/api/info")))
211
- expect(denied.status).toBe(401)
212
-
213
- const response = yield* Effect.promise(() =>
214
- handler(
215
- new Request("http://opencode.local/api/info", {
216
- headers: { authorization: `Basic ${btoa("opencode:secret")}` },
217
- }),
218
- ),
219
- )
220
- expect(response.status).toBe(200)
221
- const body = yield* Effect.promise(() => response.json()).pipe(
222
- Effect.flatMap(Schema.decodeUnknownEffect(ServerInfo)),
223
- )
224
- expect(body.version).toBe("test-version")
225
- expect(body.paths.tmp).toEndWith("opencode")
226
- expect(body.capabilities?.persistentPty).toBe(true)
227
- }),
228
- )
229
-
230
- it.live("activates credentials through the HttpApi", () =>
231
- Effect.gen(function* () {
232
- const handler = yield* ServerFetch.make(options)
233
- const response = yield* Effect.promise(() =>
234
- handler(new Request("http://opencode.local/api/credential/cred_missing/activate", { method: "POST" })),
235
- )
236
- expect(response.status).toBe(204)
237
- }),
238
- )
239
-
240
- it.live("removes credentials through the HttpApi", () =>
241
- Effect.gen(function* () {
242
- const handler = yield* ServerFetch.make(options)
243
- const response = yield* Effect.promise(() =>
244
- handler(new Request("http://opencode.local/api/credential/cred_missing", { method: "DELETE" })),
245
- )
246
- expect(response.status).toBe(204)
247
- }),
248
- )
249
-
250
- it.live("serves unauthenticated and answers CORS preflight when no password is configured", () =>
251
- Effect.gen(function* () {
252
- const handler = yield* ServerFetch.make(options)
253
-
254
- const response = yield* Effect.promise(() => handler(new Request("http://opencode.local/api/info")))
255
- expect(response.status).toBe(200)
256
-
257
- const preflight = yield* Effect.promise(() =>
258
- handler(
259
- new Request("http://opencode.local/api/info", {
260
- method: "OPTIONS",
261
- headers: {
262
- origin: "http://localhost:3000",
263
- "access-control-request-method": "GET",
264
- },
265
- }),
266
- ),
267
- )
268
- expect(preflight.headers.get("access-control-allow-origin")).toBe("http://localhost:3000")
269
- }),
270
- )
271
-
272
- it.live("applies custom CORS origins to HTTP responses and PTY ticket checks", () =>
273
- Effect.gen(function* () {
274
- const handler = yield* ServerFetch.make({
275
- ...options,
276
- password: "secret",
277
- cors: ["http://192.168.1.10:3001"],
278
- })
279
- yield* Effect.forEach(
280
- ["http://192.168.1.10:3001", "http://localhost:3000", "https://untrusted.example.com"],
281
- (origin) =>
282
- Effect.gen(function* () {
283
- const allowed = origin !== "https://untrusted.example.com"
284
- const preflight = yield* Effect.promise(() =>
285
- handler(
286
- new Request("http://opencode.local/api/info", {
287
- method: "OPTIONS",
288
- headers: {
289
- origin,
290
- "access-control-request-method": "GET",
291
- "access-control-request-headers": "authorization",
292
- },
293
- }),
294
- ),
295
- )
296
- expect(preflight.status).toBe(204)
297
- expect(preflight.headers.get("access-control-allow-origin")).toBe(allowed ? origin : null)
298
- expect(preflight.headers.get("access-control-allow-headers")).toBe("authorization")
299
-
300
- const response = yield* Effect.promise(() =>
301
- handler(
302
- new Request("http://opencode.local/api/info", {
303
- headers: { origin, authorization: `Basic ${btoa("opencode:secret")}` },
304
- }),
305
- ),
306
- )
307
- expect(response.status).toBe(200)
308
- expect(response.headers.get("access-control-allow-origin")).toBe(allowed ? origin : null)
309
-
310
- const ticket = yield* Effect.promise(() =>
311
- handler(
312
- new Request("http://opencode.local/api/experimental/persistent-pty/pty_missing/connect-token", {
313
- method: "POST",
314
- headers: { origin, authorization: `Basic ${btoa("opencode:secret")}`, "x-opencode-ticket": "1" },
315
- }),
316
- ),
317
- )
318
- // Allowed origins pass the ticket guard and reach the missing-terminal lookup.
319
- expect(ticket.status).toBe(allowed ? 404 : 403)
320
-
321
- const invalidTicket = yield* Effect.promise(() =>
322
- handler(
323
- new Request("http://opencode.local/api/pty/pty_missing/connect?ticket=invalid&location[directory]=/tmp", {
324
- headers: { origin },
325
- }),
326
- ),
327
- )
328
- expect(invalidTicket.status).toBe(403)
329
-
330
- const invalidMcpTicket = yield* Effect.promise(() =>
331
- handler(
332
- new Request(
333
- "http://opencode.local/api/experimental/client-mcp?ticket=invalid&location[directory]=/tmp&name=tui",
334
- {
335
- headers: { origin },
336
- },
337
- ),
338
- ),
339
- )
340
- expect(invalidMcpTicket.status).toBe(403)
341
-
342
- const connect = yield* Effect.promise(() =>
343
- handler(
344
- new Request("http://opencode.local/api/pty/pty_missing/connect", {
345
- headers: { origin, authorization: `Basic ${btoa("opencode:secret")}` },
346
- }),
347
- ),
348
- )
349
- expect(connect.status).toBe(allowed ? 404 : 403)
350
-
351
- const persistentConnect = yield* Effect.promise(() =>
352
- handler(
353
- new Request("http://opencode.local/api/experimental/persistent-pty/pty_missing/connect?cursor=-1", {
354
- headers: { origin, authorization: `Basic ${btoa("opencode:secret")}` },
355
- }),
356
- ),
357
- )
358
- expect(persistentConnect.status).toBe(allowed ? 400 : 403)
359
- }),
360
- )
361
-
362
- const loaded = yield* Effect.promise(() =>
363
- handler(
364
- new Request("http://opencode.local/api/debug/location", {
365
- headers: { authorization: `Basic ${btoa("opencode:secret")}` },
366
- }),
367
- ).then((response) => response.json()),
368
- )
369
- expect(loaded).toEqual([{ directory: process.cwd() }])
370
-
371
- const created = (yield* Effect.promise(() =>
372
- handler(
373
- new Request("http://opencode.local/api/pty", {
374
- method: "POST",
375
- headers: {
376
- authorization: `Basic ${btoa("opencode:secret")}`,
377
- "content-type": "application/json",
378
- },
379
- body: JSON.stringify({ command: process.execPath, args: ["-e", "setInterval(() => {}, 1000)"] }),
380
- }),
381
- ).then((response) => response.json()),
382
- )) as { data: { id: string } }
383
- const issued = (yield* Effect.promise(() =>
384
- handler(
385
- new Request(`http://opencode.local/api/pty/${created.data.id}/connect-token`, {
386
- method: "POST",
387
- headers: {
388
- authorization: `Basic ${btoa("opencode:secret")}`,
389
- "x-opencode-ticket": "1",
390
- },
391
- }),
392
- ).then((response) => response.json()),
393
- )) as { data: { ticket: string } }
394
- yield* Effect.promise(() =>
395
- handler(
396
- new Request(`http://opencode.local/api/pty/${created.data.id}`, {
397
- method: "DELETE",
398
- headers: { authorization: `Basic ${btoa("opencode:secret")}` },
399
- }),
400
- ),
401
- )
402
-
403
- const consumed = yield* Effect.promise(() =>
404
- handler(new Request(`http://opencode.local/api/pty/${created.data.id}/connect?ticket=${issued.data.ticket}`)),
405
- )
406
- expect(consumed.status).toBe(404)
407
-
408
- const replayed = yield* Effect.promise(() =>
409
- handler(new Request(`http://opencode.local/api/pty/${created.data.id}/connect?ticket=${issued.data.ticket}`)),
410
- )
411
- expect(replayed.status).toBe(403)
412
- }).pipe(Effect.scoped),
413
- )
414
-
415
- it.live("returns 404 when a previously readable file is deleted", () =>
416
- Effect.acquireUseRelease(
417
- Effect.promise(() => tmpdir("opencode-fs-read-endpoint-")),
418
- (tmp) =>
419
- Effect.gen(function* () {
420
- const handler = yield* ServerFetch.make(options)
421
- const file = path.join(tmp.path, "deleted.txt")
422
- yield* Effect.promise(() => fs.writeFile(file, "content"))
423
- const url = new URL("http://opencode.local/api/fs/read/deleted.txt")
424
- url.searchParams.set("location[directory]", tmp.path)
425
-
426
- const readable = yield* Effect.promise(() => handler(new Request(url)))
427
- expect(readable.status).toBe(200)
428
- expect(yield* Effect.promise(() => readable.text())).toBe("content")
429
-
430
- yield* Effect.promise(() => fs.unlink(file))
431
- const missing = yield* Effect.promise(() => handler(new Request(url)))
432
- expect(missing.status).toBe(404)
433
- expect(yield* Effect.promise(() => missing.json())).toEqual({
434
- _tag: "FileNotFoundError",
435
- path: "deleted.txt",
436
- message: "File not found: deleted.txt",
437
- })
438
- }),
439
- (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
440
- ).pipe(Effect.scoped),
441
- )
442
-
443
- it.live("cancels a stale OpenAI OAuth callback server before falling back", () =>
444
- Effect.gen(function* () {
445
- const requests = yield* occupy(1455, true)
446
- const handler = yield* isolated
447
- const response = yield* connectOpenAI(handler)
448
-
449
- expect(response.status).toBe(200)
450
- expect(requests).toContain("/cancel")
451
- const body = (yield* Effect.promise(() => response.json())) as { data: { url: string } }
452
- expect(new URL(body.data.url).searchParams.get("redirect_uri")).toBe("http://localhost:1455/auth/callback")
453
- }),
454
- )
455
-
456
- it.live("falls back to port 1457 when OpenAI OAuth port 1455 remains busy", () =>
457
- Effect.gen(function* () {
458
- const requests = yield* occupy(1455)
459
- const handler = yield* isolated
460
- const response = yield* connectOpenAI(handler)
461
-
462
- expect(response.status).toBe(200)
463
- expect(requests).toContain("/cancel")
464
- const body = (yield* Effect.promise(() => response.json())) as { data: { url: string } }
465
- expect(new URL(body.data.url).searchParams.get("redirect_uri")).toBe("http://localhost:1457/auth/callback")
466
- }),
467
- )
468
-
469
- it.live(
470
- "explains how to recover when both OpenAI OAuth callback ports are busy",
471
- () =>
472
- Effect.gen(function* () {
473
- yield* occupy(1455)
474
- yield* occupy(1457)
475
- const handler = yield* isolated
476
- const response = yield* connectOpenAI(handler)
477
-
478
- expect(response.status).toBe(400)
479
- expect(yield* Effect.promise(() => response.json())).toEqual({
480
- _tag: "InvalidRequestError",
481
- message:
482
- "OpenAI browser login needs local port 1455 or 1457, but both are already in use. Stop the processes using those ports or choose Codex device code (legacy), then try again.",
483
- kind: "integration_authorization",
484
- })
485
- }),
486
- // Real retries wait 18 * 200 ms; startup and scoped cleanup also count toward the deadline.
487
- { timeout: 10_000 },
488
- )
489
-
490
- it.live("serves the session view operation and missing-session error", () =>
491
- Effect.gen(function* () {
492
- const handler = yield* ServerFetch.make(options)
493
- const created = yield* Effect.promise(() =>
494
- handler(
495
- new Request("http://opencode.local/api/session", {
496
- method: "POST",
497
- headers: { "content-type": "application/json" },
498
- body: "{}",
499
- }),
500
- ).then((response) => response.json()),
501
- )
502
- if (typeof created !== "object" || created === null || !("data" in created))
503
- return yield* Effect.die(new Error("Expected a session response"))
504
- const data = created.data
505
- if (typeof data !== "object" || data === null || !("id" in data) || typeof data.id !== "string")
506
- return yield* Effect.die(new Error("Expected a session ID"))
507
-
508
- const viewed = yield* Effect.promise(() =>
509
- handler(
510
- new Request(`http://opencode.local/api/session/${data.id}/view`, {
511
- method: "POST",
512
- headers: { "content-type": "application/json" },
513
- body: JSON.stringify({ idle: 0 }),
514
- }),
515
- ),
516
- )
517
- expect(viewed.status).toBe(204)
518
-
519
- const invalid = yield* Effect.promise(() =>
520
- handler(new Request(`http://opencode.local/api/session/${data.id}/view`, { method: "POST" })),
521
- )
522
- expect(invalid.status).toBe(400)
523
-
524
- const missing = yield* Effect.promise(() =>
525
- handler(
526
- new Request("http://opencode.local/api/session/ses_missing_view/view", {
527
- method: "POST",
528
- headers: { "content-type": "application/json" },
529
- body: JSON.stringify({ idle: 0 }),
530
- }),
531
- ),
532
- )
533
- expect(missing.status).toBe(404)
534
- }),
535
- )
536
-
537
- it.live("routes pending requests through the Session's instance", () =>
538
- Effect.gen(function* () {
539
- const config = yield* Effect.acquireDisposable(Effect.promise(() => tmpdir("opencode-pending-read-")))
540
- const handler = yield* ServerFetch.make({
541
- ...options,
542
- config: {
543
- directory: config.path,
544
- project: false,
545
- content: JSON.stringify({ permissions: [{ action: "shell", resource: "*", effect: "ask" }] }),
546
- },
547
- })
548
- const created = (yield* Effect.promise(() =>
549
- handler(
550
- new Request("http://opencode.local/api/session", {
551
- method: "POST",
552
- headers: { "content-type": "application/json" },
553
- body: "{}",
554
- }),
555
- ).then((response) => response.json()),
556
- )) as { data: { id: string } }
557
-
558
- const loaded = () =>
559
- Effect.promise(() =>
560
- handler(new Request("http://opencode.local/api/debug/location")).then(
561
- (response) => response.json() as Promise<unknown[]>,
562
- ),
563
- )
564
-
565
- // Session routing must ignore the caller's unrelated Location.
566
- const headers = { "x-opencode-directory": encodeURIComponent(config.path) }
567
- expect(yield* loaded()).toEqual([])
568
- for (const resource of ["permission", "form"]) {
569
- const response = yield* Effect.promise(() =>
570
- handler(new Request(`http://opencode.local/api/session/${created.data.id}/${resource}`, { headers })),
571
- )
572
- expect(response.status).toBe(200)
573
- expect(yield* Effect.promise(() => response.json())).toEqual({ data: [] })
574
-
575
- const missing = yield* Effect.promise(() =>
576
- handler(new Request(`http://opencode.local/api/session/ses_missing_pending/${resource}`, { headers })),
577
- )
578
- expect(missing.status).toBe(404)
579
- }
580
- const global = yield* Effect.promise(() =>
581
- handler(
582
- new Request("http://opencode.local/api/session/global/form", {
583
- headers: { "x-opencode-directory": encodeURIComponent(process.cwd()) },
584
- }),
585
- ),
586
- )
587
- expect(global.status).toBe(200)
588
- expect(yield* Effect.promise(() => global.json())).toEqual({ data: [] })
589
- expect(yield* loaded()).toEqual([{ directory: process.cwd() }])
590
-
591
- const createdForm = yield* Effect.promise(() =>
592
- handler(
593
- new Request(`http://opencode.local/api/session/${created.data.id}/form`, {
594
- method: "POST",
595
- headers: { "content-type": "application/json", ...headers },
596
- body: JSON.stringify({ title: "Test form", fields: [{ key: "answer", type: "string" }] }),
597
- }),
598
- ),
599
- )
600
- expect(createdForm.status).toBe(200)
601
-
602
- const forms = yield* Effect.promise(() =>
603
- handler(new Request(`http://opencode.local/api/session/${created.data.id}/form`, { headers })),
604
- )
605
- expect(forms.status).toBe(200)
606
- expect(yield* Effect.promise(() => forms.json())).toMatchObject({
607
- data: [{ title: "Test form" }],
608
- })
609
- expect(yield* loaded()).toHaveLength(1)
610
-
611
- const globalForm = yield* Effect.promise(() =>
612
- handler(
613
- new Request("http://opencode.local/api/session/global/form", {
614
- method: "POST",
615
- headers: {
616
- "content-type": "application/json",
617
- "x-opencode-directory": encodeURIComponent(process.cwd()),
618
- },
619
- body: JSON.stringify({ title: "Global form", fields: [{ key: "answer", type: "string" }] }),
620
- }),
621
- ),
622
- )
623
- expect(globalForm.status).toBe(200)
624
-
625
- const globalForms = yield* Effect.promise(() =>
626
- handler(
627
- new Request("http://opencode.local/api/session/global/form", {
628
- headers: { "x-opencode-directory": encodeURIComponent(process.cwd()) },
629
- }),
630
- ),
631
- )
632
- expect(globalForms.status).toBe(200)
633
- expect(yield* Effect.promise(() => globalForms.json())).toMatchObject({ data: [{ title: "Global form" }] })
634
-
635
- // Agent permission policy is installed by plugin activation.
636
- yield* Effect.gen(function* () {
637
- const response = yield* Effect.promise(() => handler(new Request("http://opencode.local/api/agent")))
638
- expect(response.status).toBe(200)
639
- const body = Schema.decodeUnknownSync(Schema.Struct({ data: Schema.Array(Agent.Info) }))(
640
- yield* Effect.promise(() => response.json()),
641
- )
642
- return body.data.some(
643
- (agent) =>
644
- agent.id === "build" &&
645
- agent.permissions.some((rule) => rule.action === "shell" && rule.resource === "*" && rule.effect === "ask"),
646
- )
647
- }).pipe(
648
- Effect.filterOrFail((ready) => ready),
649
- Effect.retry(Schedule.spaced("10 millis")),
650
- Effect.timeout("2 seconds"),
651
- )
652
- const createdPermission = yield* Effect.promise(() =>
653
- handler(
654
- new Request(`http://opencode.local/api/session/${created.data.id}/permission`, {
655
- method: "POST",
656
- headers: { "content-type": "application/json", ...headers },
657
- body: JSON.stringify({ id: "per_pending_read", action: "shell", resources: ["pwd"] }),
658
- }),
659
- ),
660
- )
661
- expect(createdPermission.status).toBe(200)
662
- expect(yield* Effect.promise(() => createdPermission.json())).toEqual({
663
- data: { id: "per_pending_read", effect: "ask" },
664
- })
665
-
666
- const permissions = yield* Effect.promise(() =>
667
- handler(new Request(`http://opencode.local/api/session/${created.data.id}/permission`, { headers })),
668
- )
669
- expect(permissions.status).toBe(200)
670
- expect(yield* Effect.promise(() => permissions.json())).toMatchObject({
671
- data: [{ id: "per_pending_read", sessionID: created.data.id, action: "shell", resources: ["pwd"] }],
672
- })
673
- expect(yield* loaded()).toHaveLength(1)
674
- }),
675
- )
676
-
677
- // Pins the eager-boot guarantee: the application layer is built before the handler returns, so
678
- // an aborted first request cannot interrupt layer construction and wedge every later request
679
- // (the Effect-TS/effect#6319 failure class that lazy first-request builds are prone to).
680
- it.live("stays serviceable when the first request aborts", () =>
681
- Effect.gen(function* () {
682
- const handler = yield* ServerFetch.make(options)
683
-
684
- const aborted = yield* Effect.promise(() => {
685
- const controller = new AbortController()
686
- const first = handler(new Request("http://opencode.local/api/info", { signal: controller.signal }))
687
- controller.abort()
688
- return first.then(
689
- () => "resolved" as const,
690
- () => "rejected" as const,
691
- )
692
- })
693
- expect(["resolved", "rejected"]).toContain(aborted)
694
-
695
- const second = yield* Effect.promise(() => handler(new Request("http://opencode.local/api/info")))
696
- expect(second.status).toBe(200)
697
- }),
698
- )