@zyro-sec/server 1.0.2 → 1.0.3

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,315 +0,0 @@
1
- import fs from "node:fs/promises"
2
- import path from "node:path"
3
- import { expect } from "bun:test"
4
- import { OpenCode } from "@zyro-sec/client"
5
- import { Effect } from "effect"
6
- import { tmpdirScoped } from "../../core/test/fixture/tmpdir"
7
- import { it } from "../../core/test/lib/effect"
8
- import { ServerFetch } from "../src/fetch"
9
- import { ServerProcess } from "../src/process"
10
- import { startServer } from "./fixture/server"
11
-
12
- const client = (handler: (request: Request) => Promise<Response>) =>
13
- OpenCode.make({
14
- baseUrl: "http://opencode.local",
15
- fetch: Object.assign((input: string | URL | Request, init?: RequestInit) => handler(new Request(input, init)), {
16
- preconnect: fetch.preconnect,
17
- }),
18
- })
19
-
20
- const hourly = { type: "every" as const, every: "1 hour" }
21
-
22
- it.live(
23
- "manages automations through the experimental API when enabled and honors a project automations override",
24
- () =>
25
- Effect.gen(function* () {
26
- const dir = (yield* tmpdirScoped("opencode-automation-api-")).path
27
- const global = path.join(dir, "global")
28
- const enabled = path.join(dir, "enabled")
29
- const ask = path.join(dir, "ask")
30
- yield* Effect.promise(async () => {
31
- await Promise.all([global, enabled, ask].map((item) => fs.mkdir(item, { recursive: true })))
32
- await fs.writeFile(path.join(global, "opencode.json"), JSON.stringify({ automations: true }))
33
- await fs.writeFile(path.join(enabled, "opencode.json"), JSON.stringify({}))
34
- await fs.writeFile(path.join(ask, "opencode.json"), JSON.stringify({ permission: { execute: "ask" } }))
35
- })
36
- const handler = yield* ServerFetch.make({
37
- app: { version: "test" },
38
- database: { path: path.join(dir, "opencode.db") },
39
- config: { directory: global, project: true, claude: false },
40
- models: { fetch: false },
41
- fs: { filewatcher: false },
42
- })
43
- const api = client(handler)
44
- const post = (body: unknown) =>
45
- handler(
46
- new Request("http://opencode.local/api/experimental/automation", {
47
- method: "POST",
48
- headers: { "content-type": "application/json" },
49
- body: JSON.stringify(body),
50
- }),
51
- )
52
-
53
- yield* Effect.promise(async () => {
54
- const session = await api.session.create({
55
- location: { directory: enabled },
56
- })
57
- await expect(
58
- api.experimental.automation.create({
59
- sessionID: session.id,
60
- name: "build watch",
61
- trigger: { type: "event", server: "ci", event: "build.changed" },
62
- action: { type: "prompt", prompt: "Check the build" },
63
- }),
64
- ).rejects.toMatchObject({
65
- _tag: "InvalidRequestError",
66
- message: expect.stringContaining("tool call"),
67
- })
68
- const created = await api.experimental.automation.create({
69
- sessionID: session.id,
70
- name: "build",
71
- trigger: hourly,
72
- expires: "in 8 hours",
73
- action: { type: "prompt", prompt: "check the build" },
74
- })
75
- expect(created).toMatchObject({
76
- sessionID: session.id,
77
- directory: enabled,
78
- name: "build",
79
- trigger: hourly,
80
- action: { type: "prompt", prompt: "check the build", to: { session: session.id } },
81
- status: "active",
82
- })
83
- expect(created.expires).toBeDefined()
84
- expect(await api.experimental.automation.list({ sessionID: session.id })).toMatchObject([{ id: created.id }])
85
- expect(await api.experimental.automation.list({ directory: enabled })).toMatchObject([{ id: created.id }])
86
- expect(await api.experimental.automation.list({})).toMatchObject([{ id: created.id }])
87
- await expect(api.experimental.automation.list({ directory: "relative" })).rejects.toMatchObject({
88
- _tag: "InvalidRequestError",
89
- })
90
- expect(await api.experimental.automation.get({ automationID: created.id })).toMatchObject({ id: created.id })
91
- expect(await api.experimental.automation.pause({ automationID: created.id })).toMatchObject({
92
- status: "paused",
93
- })
94
- expect(await api.experimental.automation.resume({ automationID: created.id })).toMatchObject({
95
- status: "active",
96
- })
97
- await api.experimental.automation.delete({ automationID: created.id })
98
- await expect(api.experimental.automation.get({ automationID: created.id })).rejects.toMatchObject({
99
- _tag: "AutomationNotFoundError",
100
- })
101
-
102
- // Without a Session, in a directory, prompting an existing Session.
103
- const standalone = await api.experimental.automation.create({
104
- name: "standalone",
105
- directory: enabled,
106
- trigger: hourly,
107
- action: {
108
- type: "prompt",
109
- prompt: "hello",
110
- to: { session: session.id },
111
- },
112
- })
113
- expect(standalone).toMatchObject({
114
- directory: enabled,
115
- action: { to: { session: session.id } },
116
- })
117
- expect(standalone.sessionID).toBeUndefined()
118
- // A subagent target needs a creating Session to be the parent of each run's child.
119
- await expect(
120
- api.experimental.automation.create({
121
- name: "orphan",
122
- directory: enabled,
123
- trigger: hourly,
124
- action: { type: "prompt", prompt: "hello", to: { subagent: "general" } },
125
- }),
126
- ).rejects.toMatchObject({ _tag: "InvalidRequestError" })
127
- const triage = await api.experimental.automation.create({
128
- sessionID: session.id,
129
- name: "triage",
130
- trigger: hourly,
131
- action: {
132
- type: "prompt",
133
- prompt: "triage",
134
- to: { subagent: "general" },
135
- },
136
- })
137
- expect(triage).toMatchObject({
138
- sessionID: session.id,
139
- action: { to: { subagent: "general" } },
140
- })
141
- await api.experimental.automation.delete({ automationID: triage.id })
142
-
143
- await expect(
144
- api.experimental.automation.create({
145
- sessionID: session.id,
146
- name: "bad",
147
- trigger: { type: "every", every: "soon" },
148
- action: { type: "prompt", prompt: "ping" },
149
- }),
150
- ).rejects.toMatchObject({ _tag: "InvalidRequestError" })
151
- // A trigger without its type, or a target naming both a Session and an agent, is rejected rather than guessed.
152
- expect(
153
- (
154
- await post({
155
- sessionID: session.id,
156
- name: "x",
157
- trigger: { every: "1 hour" },
158
- action: { type: "prompt", prompt: "x" },
159
- })
160
- ).status,
161
- ).toBe(400)
162
- expect(
163
- (
164
- await post({
165
- sessionID: session.id,
166
- name: "x",
167
- trigger: hourly,
168
- action: { type: "prompt", prompt: "x", to: { session: session.id, subagent: "general" } },
169
- })
170
- ).status,
171
- ).toBe(400)
172
- expect(await api.experimental.automation.list({ sessionID: session.id })).toEqual([])
173
-
174
- // Turn off the directory that still owns the standalone automation. Even unfiltered lists must hide it.
175
- await fs.writeFile(path.join(enabled, "opencode.json"), JSON.stringify({ automations: false }))
176
- await api.location.reload()
177
- expect(await api.experimental.automation.list({})).toEqual([])
178
- await expect(api.experimental.automation.get({ automationID: standalone.id })).rejects.toMatchObject({
179
- _tag: "ForbiddenError",
180
- })
181
- await expect(
182
- api.experimental.automation.create({
183
- sessionID: session.id,
184
- name: "x",
185
- trigger: hourly,
186
- action: { type: "prompt", prompt: "ping" },
187
- }),
188
- ).rejects.toMatchObject({ _tag: "ForbiddenError" })
189
- await expect(api.experimental.automation.list({ sessionID: session.id })).rejects.toMatchObject({
190
- _tag: "ForbiddenError",
191
- })
192
-
193
- // A code action that would need an interactive approval is refused over stateless HTTP instead of hanging.
194
- const askSession = await api.session.create({ location: { directory: ask } })
195
- await expect(
196
- api.experimental.automation.create({
197
- sessionID: askSession.id,
198
- name: "blocked",
199
- trigger: hourly,
200
- action: { type: "code", code: "return" },
201
- }),
202
- ).rejects.toMatchObject({ _tag: "ForbiddenError" })
203
- })
204
- }).pipe(Effect.scoped),
205
- // Boots three Locations (enabled, enabled again on reload, ask) as one of the suite's first server boots, which
206
- // still pay the cold Location load on Windows CI (see artifact.test.ts).
207
- 30_000,
208
- )
209
-
210
- it.live("runs due automations in standalone ServerProcess.start without lifecycle", () =>
211
- Effect.gen(function* () {
212
- const dir = (yield* tmpdirScoped("opencode-automation-serve-")).path
213
- const server = yield* startServer(dir)
214
- const api = OpenCode.make({ baseUrl: server.base, headers: server.headers })
215
-
216
- yield* Effect.promise(async () => {
217
- const session = await api.session.create({ location: { directory: dir } })
218
- const created = await api.experimental.automation.create({
219
- sessionID: session.id,
220
- name: "models",
221
- trigger: { type: "at", at: "in 150 millis" },
222
- action: {
223
- type: "code",
224
- code: 'const models = await tools.opencode.models({}); console.log("models=" + models.total); return { state: { total: models.total } }',
225
- },
226
- })
227
- expect(created.status).toBe("active")
228
-
229
- const deadline = Date.now() + 5_000
230
- let current = created
231
- while (current.status === "active" && Date.now() < deadline) {
232
- await new Promise((resolve) => setTimeout(resolve, 50))
233
- current = await api.experimental.automation.get({ automationID: created.id })
234
- }
235
- expect(current).toMatchObject({
236
- status: "done",
237
- runCount: 1,
238
- lastOutcome: "fired",
239
- lastOutput: expect.stringContaining("models="),
240
- state: { total: expect.any(Number) },
241
- })
242
- })
243
- }).pipe(Effect.scoped),
244
- )
245
-
246
- it.live("starts one child for a due automation when two servers share a database", () =>
247
- Effect.gen(function* () {
248
- const dir = (yield* tmpdirScoped("opencode-automation-leader-")).path
249
- const dbPath = path.join(dir, "shared.db")
250
- yield* Effect.promise(() =>
251
- fs.writeFile(
252
- path.join(dir, "opencode.json"),
253
- JSON.stringify({
254
- // Exercise the child's durable prompt and wake, not inference through a default provider.
255
- policies: [{ action: "provider.use", resource: "*", effect: "deny" }],
256
- }),
257
- ),
258
- )
259
-
260
- // Seed an active automation in a short-lived scope so it falls due while no server is running.
261
- const createdID = yield* Effect.scoped(
262
- Effect.gen(function* () {
263
- const handler = yield* ServerFetch.make({
264
- app: { version: "test" },
265
- database: { path: dbPath },
266
- config: { directory: dir, project: true, claude: false },
267
- models: { fetch: false },
268
- fs: { filewatcher: false },
269
- })
270
- const seededApi = client(handler)
271
- return yield* Effect.promise(async () => {
272
- const parent = await seededApi.session.create({ location: { directory: dir } })
273
- const created = await seededApi.experimental.automation.create({
274
- sessionID: parent.id,
275
- name: "single leader",
276
- trigger: { type: "at", at: "in 80 millis" },
277
- action: { type: "prompt", prompt: "single leader check", to: { subagent: "general" } },
278
- })
279
- return created.id
280
- })
281
- }),
282
- )
283
- yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 120)))
284
-
285
- const boot = () =>
286
- ServerProcess.start<never, never>({
287
- hostname: "127.0.0.1",
288
- port: 0,
289
- password: "secret",
290
- app: { version: "test-version" },
291
- database: { path: dbPath },
292
- config: { directory: dir },
293
- fs: { filewatcher: false },
294
- models: { fetch: false },
295
- })
296
- const [first] = yield* Effect.all([boot(), boot()], { concurrency: 2 })
297
- const base = `http://127.0.0.1:${"port" in first.address ? first.address.port : 0}`
298
- const api = OpenCode.make({
299
- baseUrl: base,
300
- headers: { authorization: `Basic ${btoa("opencode:secret")}` },
301
- })
302
-
303
- yield* Effect.promise(async () => {
304
- const deadline = Date.now() + 5_000
305
- let current = await api.experimental.automation.get({ automationID: createdID })
306
- while (current.status === "active" && Date.now() < deadline) {
307
- await new Promise((resolve) => setTimeout(resolve, 50))
308
- current = await api.experimental.automation.get({ automationID: createdID })
309
- }
310
- const started = (await api.session.list({})).data.filter((session) => session.title === "single leader")
311
- expect(current).toMatchObject({ status: "done", runCount: 1 })
312
- expect(started).toHaveLength(1)
313
- })
314
- }).pipe(Effect.scoped),
315
- )
@@ -1,369 +0,0 @@
1
- import { expect } from "bun:test"
2
- import { NodeHttpServer } from "@effect/platform-node"
3
- import { Location } from "@zyro-sec/core/location"
4
- import { AbsolutePath } from "@zyro-sec/core/schema"
5
- import { LocationLifecycle } from "@zyro-sec/core/location-lifecycle"
6
- import { LocationServiceMap } from "@zyro-sec/core/location-service-map"
7
- import { Mcp } from "@zyro-sec/core/mcp/index"
8
- import { Session } from "@zyro-sec/core/session"
9
- import { Tool } from "@zyro-sec/core/tool"
10
- import { McpTool } from "@zyro-sec/core/tool/mcp"
11
- import { Context, Effect, Exit, Layer, MutableHashMap, Option, Schedule, Scope } from "effect"
12
- import { HttpRouter, HttpServer } from "effect/http"
13
- import { createServer } from "node:http"
14
- import path from "node:path"
15
- import { connectClientMcp } from "../../client/src/mcp"
16
- import { tmpdirScoped } from "../../core/test/fixture/tmpdir"
17
- import { it } from "../../core/test/lib/effect"
18
- import { ServerProcess } from "../src/process"
19
- import { createRoutes } from "../src/routes"
20
-
21
- // The DOM lib hides Bun's WebSocket constructor overload that accepts upgrade request headers.
22
- declare const WebSocket: {
23
- new (url: string | URL, options?: Bun.WebSocketOptions): globalThis.WebSocket
24
- }
25
-
26
- const authorization = `Basic ${btoa("opencode:secret")}`
27
-
28
- const serve = Effect.fnUntraced(function* () {
29
- const directory = (yield* tmpdirScoped("opencode-client-mcp-")).path
30
- const context = yield* Layer.build(
31
- createRoutes({
32
- password: "secret",
33
- app: { version: "test-version" },
34
- database: { path: ":memory:" },
35
- models: { fetch: false },
36
- config: { directory, project: false, content: "{}" },
37
- fs: { filewatcher: false },
38
- }).pipe(Layer.provideMerge(NodeHttpServer.layerHttpServices)),
39
- )
40
- const server = createServer()
41
- const http = yield* NodeHttpServer.make(() => server, { port: 0, host: "127.0.0.1" })
42
- yield* Effect.addFinalizer(() => Effect.sync(() => server.closeAllConnections()))
43
- yield* http
44
- .serve(Context.get(context, HttpRouter.HttpRouter).asHttpEffect())
45
- .pipe(Effect.provide(NodeHttpServer.layerHttpServices))
46
- const base = HttpServer.formatAddress(http.address)
47
- const location = LocationServiceMap.Service.get(
48
- LocationServiceMap.canonical(Location.Ref.make({ directory: directory as Location.Ref["directory"] })),
49
- )
50
- return {
51
- base,
52
- directory,
53
- context,
54
- url: (query: Record<string, string>) => {
55
- const url = new URL("/api/experimental/client-mcp", base)
56
- url.protocol = "ws:"
57
- url.searchParams.set("location[directory]", directory)
58
- for (const [key, value] of Object.entries(query)) url.searchParams.set(key, value)
59
- return url
60
- },
61
- inLocation: <A, E>(effect: Effect.Effect<A, E, Mcp.Service | Tool.Service | McpTool.Service>) =>
62
- effect.pipe(Effect.provide(location), Effect.provideContext(context)),
63
- }
64
- })
65
-
66
- /** Hosts an MCP server over a WebSocket opened to the endpoint, recording each call's session. */
67
- const connectClient = (url: URL, headers?: Record<string, string>) =>
68
- Effect.acquireRelease(
69
- Effect.promise(async () => {
70
- const socket = new WebSocket(url, { headers })
71
- const state = { open: false, initialized: false, closed: false, code: 0 }
72
- const sessions: unknown[] = []
73
- const reply = (id: unknown, result: unknown) => socket.send(JSON.stringify({ jsonrpc: "2.0", id, result }))
74
- socket.addEventListener("open", () => {
75
- state.open = true
76
- })
77
- socket.addEventListener("message", (event) => {
78
- const message = JSON.parse(String(event.data))
79
- if (message.method === "initialize")
80
- return reply(message.id, {
81
- protocolVersion: message.params.protocolVersion,
82
- capabilities: { tools: {} },
83
- serverInfo: { name: "test-client", version: "1.0.0" },
84
- })
85
- if (message.method === "notifications/initialized") {
86
- state.initialized = true
87
- return
88
- }
89
- if (message.method === "tools/list")
90
- return reply(message.id, {
91
- tools: [{ name: "open_terminal", description: "Open a terminal", inputSchema: { type: "object" } }],
92
- })
93
- if (message.method === "tools/call") {
94
- sessions.push(message.params._meta?.["ai.opencode/sessionID"])
95
- return reply(message.id, { content: [{ type: "text", text: "opened" }] })
96
- }
97
- if (message.id !== undefined && message.method) reply(message.id, {})
98
- })
99
- socket.addEventListener("close", (event) => {
100
- state.closed = true
101
- state.code = event.code
102
- })
103
- return { socket, state, sessions }
104
- }),
105
- (client) => Effect.sync(() => client.socket.close()),
106
- )
107
-
108
- const until = (check: () => boolean | Promise<boolean>) =>
109
- Effect.promise(async () => check()).pipe(
110
- Effect.flatMap((done) => (done ? Effect.void : Effect.fail("pending"))),
111
- Effect.retry({ times: 500, schedule: Schedule.spaced("10 millis") }),
112
- Effect.orDie,
113
- )
114
-
115
- const registryIDs = Effect.gen(function* () {
116
- const registration = yield* McpTool.Service
117
- yield* registration.flush
118
- const registry = yield* Tool.Service
119
- return (yield* registry.list()).map((tool) => tool.id)
120
- })
121
-
122
- it.live(
123
- "attaches a client MCP server for the lifetime of its socket",
124
- () =>
125
- Effect.gen(function* () {
126
- const server = yield* serve()
127
- const client = yield* connectClient(server.url({ name: "tui" }), { authorization })
128
- const tools = () => Effect.runPromise(server.inLocation(Mcp.Service.use((mcp) => mcp.tools())))
129
-
130
- yield* until(async () => (await tools()).length > 0)
131
- expect((yield* Effect.promise(tools)).map((tool) => [tool.server, tool.name])).toEqual([["tui", "open_terminal"]])
132
- yield* until(() =>
133
- Effect.runPromise(server.inLocation(registryIDs)).then((ids) => ids.includes("tui_open_terminal")),
134
- )
135
-
136
- const call = (sessionID: string) =>
137
- Effect.runPromise(
138
- server.inLocation(
139
- Mcp.Service.use((mcp) =>
140
- mcp.callTool({ server: "tui", name: "open_terminal", sessionID: Session.ID.make(sessionID) }),
141
- ),
142
- ),
143
- )
144
- const result = yield* Effect.promise(() => call("ses_client_mcp"))
145
- expect(result.content).toEqual([{ type: "text", text: "opened" }])
146
- expect(client.sessions).toEqual(["ses_client_mcp"])
147
-
148
- // A second client with the same name stacks on top: it takes the calls while the first stays open.
149
- const newer = yield* connectClient(server.url({ name: "tui" }), { authorization })
150
- yield* until(() => call("ses_newer").then(() => newer.sessions.length > 0))
151
- expect(newer.sessions.every((session) => session === "ses_newer")).toBeTrue()
152
- expect(client.state.closed).toBeFalse()
153
-
154
- // Once the newest closes, calls fall back to the earlier client.
155
- const before = client.sessions.length
156
- newer.socket.close()
157
- yield* until(() => newer.state.closed)
158
- yield* until(() =>
159
- call("ses_fallback").then(
160
- () => client.sessions.length > before,
161
- () => false,
162
- ),
163
- )
164
- expect(client.sessions.at(-1)).toBe("ses_fallback")
165
-
166
- client.socket.close()
167
- yield* until(async () => (await tools()).length === 0)
168
- yield* until(() =>
169
- Effect.runPromise(server.inLocation(registryIDs)).then((ids) => !ids.includes("tui_open_terminal")),
170
- )
171
- }),
172
- 20_000,
173
- )
174
-
175
- it.live(
176
- "closes a client MCP socket with 1012 on reload and reattaches to the fresh location",
177
- () =>
178
- Effect.gen(function* () {
179
- const server = yield* serve()
180
- const events: string[] = []
181
- class RecordingWebSocket extends globalThis.WebSocket {
182
- constructor(...args: ConstructorParameters<typeof globalThis.WebSocket>) {
183
- super(...args)
184
- this.addEventListener("close", (event) => events.push(`close ${event.code}`))
185
- this.addEventListener("message", (event) => {
186
- if (String(event.data).includes('"notifications/initialized"')) events.push("attached")
187
- })
188
- }
189
- }
190
- const connection = yield* Effect.acquireRelease(
191
- Effect.sync(() =>
192
- connectClientMcp({
193
- url: server.base,
194
- name: "tui",
195
- directory: server.directory,
196
- headers: { authorization },
197
- WebSocket: RecordingWebSocket,
198
- tools: [{ name: "open_terminal", handler: () => ({ content: [{ type: "text", text: "opened" }] }) }],
199
- }),
200
- ),
201
- (connection) => Effect.promise(() => connection.close()),
202
- )
203
- yield* until(() => events.includes("attached"))
204
- const locations = Context.get(server.context, LocationServiceMap.Service)
205
- const ref = LocationServiceMap.canonical(Location.Ref.make({ directory: AbsolutePath.make(server.directory) }))
206
- const entry = () =>
207
- locations.rcMap.state._tag === "Open"
208
- ? Option.getOrUndefined(MutableHashMap.get(locations.rcMap.state.map, ref))
209
- : undefined
210
- const old = entry()
211
- expect(old).toBeDefined()
212
- // An attached client keeps the idle sweep away from its location.
213
- const lifecycle = Context.get(yield* locations.contextEffect(ref).pipe(Effect.scoped), LocationLifecycle.Service)
214
- expect(lifecycle.isRetained()).toBe(true)
215
-
216
- const response = yield* Effect.promise(() =>
217
- fetch(new URL("/api/location/reload", server.base), { method: "POST", headers: { authorization } }),
218
- )
219
- expect(response.status).toBe(204)
220
- // The socket was the old location's last borrower, so closing it let the old location close.
221
- yield* until(() => old?.scope.state._tag === "Closed")
222
- // The client reconnected on its own and the replacement location attached it.
223
- yield* until(() => events.length === 3)
224
- expect(events).toEqual(["attached", "close 1012", "attached"])
225
- expect(entry()).toBeDefined()
226
- expect(entry()).not.toBe(old)
227
-
228
- // Disconnect before the server stops, like the other tests here.
229
- yield* Effect.promise(() => connection.close())
230
- yield* until(() => events.length === 4)
231
- }),
232
- 20_000,
233
- )
234
-
235
- it.live(
236
- "accepts a single-use ticket instead of credentials",
237
- () =>
238
- Effect.gen(function* () {
239
- const server = yield* serve()
240
- const requestToken = (name: string, headers: Record<string, string>) => {
241
- const url = new URL("/api/experimental/client-mcp/token", server.base)
242
- url.searchParams.set("location[directory]", server.directory)
243
- url.searchParams.set("name", name)
244
- return fetch(url, { method: "POST", headers })
245
- }
246
- const token = (name: string) =>
247
- Effect.promise(async () => {
248
- const response = await requestToken(name, { authorization, "x-opencode-ticket": "1" })
249
- expect(response.status).toBe(200)
250
- return ((await response.json()) as { data: { ticket: string } }).data.ticket
251
- })
252
-
253
- // Without the preflight-forcing header, a ticket cannot be minted even with credentials.
254
- expect((yield* Effect.promise(() => requestToken("web", { authorization }))).status).toBe(403)
255
-
256
- const unauthenticated = yield* connectClient(server.url({ name: "web" }))
257
- yield* until(() => unauthenticated.state.closed)
258
- expect(unauthenticated.state.open).toBeFalse()
259
-
260
- const ticket = yield* token("web")
261
- const mismatched = yield* connectClient(server.url({ name: "other", ticket }))
262
- yield* until(() => mismatched.state.closed)
263
- expect(mismatched.state.open).toBeFalse()
264
-
265
- const otherDirectory = server.url({ name: "web", ticket: yield* token("web") })
266
- otherDirectory.protocol = "http:"
267
- otherDirectory.searchParams.set("location[directory]", path.join(server.directory, "other"))
268
- expect((yield* Effect.promise(() => fetch(otherDirectory))).status).toBe(403)
269
-
270
- const fresh = yield* token("web")
271
- const client = yield* connectClient(server.url({ name: "web", ticket: fresh }))
272
- yield* until(() =>
273
- Effect.runPromise(server.inLocation(Mcp.Service.use((mcp) => mcp.tools()))).then((tools) =>
274
- tools.some((tool) => tool.server === "web"),
275
- ),
276
- )
277
- expect(client.state.open).toBeTrue()
278
-
279
- const reused = yield* connectClient(server.url({ name: "web", ticket: fresh }))
280
- yield* until(() => reused.state.closed)
281
- expect(reused.state.open).toBeFalse()
282
-
283
- // The server's end of an accepted socket lives in the serving scope until the client disconnects.
284
- client.socket.close()
285
- yield* until(() => client.state.closed)
286
- }),
287
- 20_000,
288
- )
289
-
290
- it.live(
291
- "rejects an invalid client name",
292
- () =>
293
- Effect.gen(function* () {
294
- const server = yield* serve()
295
- const url = server.url({ name: "bad name!" })
296
- url.protocol = "http:"
297
- const response = yield* Effect.promise(() => fetch(url, { headers: { authorization } }))
298
- expect(response.status).toBe(400)
299
-
300
- const client = yield* connectClient(server.url({ name: "bad.name" }), { authorization })
301
- yield* until(() => client.state.closed)
302
- expect(client.state.open).toBeFalse()
303
- }),
304
- 20_000,
305
- )
306
-
307
- it.live(
308
- "closes with 1011 when the client rejects initialize",
309
- () =>
310
- Effect.gen(function* () {
311
- const server = yield* serve()
312
- const state = yield* Effect.acquireRelease(
313
- Effect.sync(() => {
314
- const socket = new WebSocket(server.url({ name: "tui" }), { headers: { authorization } })
315
- const state = { socket, closed: false, code: 0 }
316
- socket.addEventListener("message", (event) => {
317
- const message = JSON.parse(String(event.data))
318
- if (message.method !== "initialize") return
319
- socket.send(
320
- JSON.stringify({ jsonrpc: "2.0", id: message.id, error: { code: -32603, message: "not today" } }),
321
- )
322
- })
323
- socket.addEventListener("close", (event) => {
324
- state.closed = true
325
- state.code = event.code
326
- })
327
- return state
328
- }),
329
- (state) => Effect.sync(() => state.socket.close()),
330
- )
331
- yield* until(() => state.closed)
332
- expect(state.code).toBe(1011)
333
- }),
334
- 20_000,
335
- )
336
-
337
- it.live(
338
- "shuts the server down while a client is attached",
339
- () =>
340
- Effect.gen(function* () {
341
- const directory = (yield* tmpdirScoped("opencode-client-mcp-")).path
342
- // Released before the directory so the server lets go of it first; closing twice is a no-op.
343
- const scope = yield* Effect.acquireRelease(Scope.make(), (scope) => Scope.close(scope, Exit.void))
344
- const server = yield* ServerProcess.start<never, never>(
345
- {
346
- hostname: "127.0.0.1",
347
- port: 0,
348
- password: "secret",
349
- app: { version: "test-version" },
350
- database: { path: ":memory:" },
351
- models: { fetch: false },
352
- config: { directory, project: false, content: "{}" },
353
- fs: { filewatcher: false },
354
- },
355
- { onListen: () => Effect.succeed(Effect.void) },
356
- ).pipe(Scope.provide(scope))
357
- const url = new URL("/api/experimental/client-mcp", HttpServer.formatAddress(server.address))
358
- url.protocol = "ws:"
359
- url.searchParams.set("location[directory]", directory)
360
- url.searchParams.set("name", "tui")
361
- const client = yield* connectClient(url, { authorization })
362
- yield* until(() => client.state.initialized)
363
-
364
- const closed = yield* Scope.close(scope, Exit.void).pipe(Effect.timeoutOption("5 seconds"))
365
- expect(closed._tag).toBe("Some")
366
- yield* until(() => client.state.closed)
367
- }),
368
- 20_000,
369
- )