@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,335 +0,0 @@
1
- import { expect } from "bun:test"
2
- import { App } from "@zyro-sec/core/app"
3
- import { Bus } from "@zyro-sec/core/bus"
4
- import { Database } from "@zyro-sec/core/database/database"
5
- import { llmClient } from "@zyro-sec/core/effect/app-node-platform"
6
- import { Watcher } from "@zyro-sec/core/filesystem/watcher"
7
- import { Form } from "@zyro-sec/core/form"
8
- import { Instance } from "@zyro-sec/core/instance"
9
- import { LocationServiceMap } from "@zyro-sec/core/location-service-map"
10
- import { ModelsDev } from "@zyro-sec/core/models-dev"
11
- import { Permission } from "@zyro-sec/core/permission"
12
- import { Plugin } from "@zyro-sec/core/plugin"
13
- import { Session } from "@zyro-sec/core/session"
14
- import { SessionRunnerModel } from "@zyro-sec/core/session/runner/model"
15
- import { define } from "@zyro-sec/plugin/effect/plugin"
16
- import type { SessionHooks } from "@zyro-sec/plugin/effect/session"
17
- import { Agent } from "@zyro-sec/schema/agent"
18
- import { Location } from "@zyro-sec/schema/location"
19
- import { AbsolutePath } from "@zyro-sec/schema/schema"
20
- import { LayerNode } from "@zyro-sec/util/effect/layer-node"
21
- import { makeGlobalNode } from "@zyro-sec/util/effect/app-node"
22
- import { Global } from "@zyro-sec/util/global"
23
- import { Context, Duration, Effect, Layer, LayerMap, RcMap, Schema } from "effect"
24
- import { HttpEffect, HttpRouter, HttpServer } from "effect/http"
25
- import { LanguageModel, LLMClient } from "../../ai/src/effect"
26
- import { OpenAIChat } from "../../ai/src/protocols/openai-chat"
27
- import { TestLLM } from "../../ai/src/testing"
28
- import { tempGlobalLayer } from "../../core/test/fixture/global"
29
- import { tmpdirScoped } from "../../core/test/fixture/tmpdir"
30
- import { it } from "../../core/test/lib/effect"
31
- import { createEmbeddedRoutes } from "../src/routes"
32
-
33
- it.live(
34
- "isolates same-directory Session tools, hooks, commands, and HTTP requests through one selector",
35
- () =>
36
- Effect.gen(function* () {
37
- const directory = yield* tmpdirScoped()
38
- const location = Location.Ref.make({ directory: AbsolutePath.make(directory.path) })
39
- const first = { id: Session.ID.make("ses_instance_first"), tool: "instance_first", temperature: 0.1 }
40
- const second = { id: Session.ID.make("ses_instance_second"), tool: "instance_second", temperature: 0.2 }
41
- const configs = [first, second]
42
- const boots: Session.ID[] = []
43
- const executed: Session.ID[] = []
44
- const commands: Session.ID[] = []
45
- const llm = yield* TestLLM.Test.pipe(Effect.provide(TestLLM.testLayer()))
46
- const model = SessionRunnerModel.resolved(
47
- LanguageModel.make({ id: "instance-model", provider: "test", route: OpenAIChat.route }),
48
- {
49
- capabilities: { tools: true, input: ["text"], output: ["text"] },
50
- cost: [],
51
- limit: { context: 200_000, output: 8_192 },
52
- },
53
- )
54
- // Host and private instances must reuse the same global layer identities.
55
- const replacements: LayerNode.Replacements = [
56
- Global.node.replace(tempGlobalLayer),
57
- Database.node.replace(Database.node),
58
- Bus.node.replace(Bus.node),
59
- App.node.replace(App.node),
60
- ModelsDev.node.replace(ModelsDev.configured({ fetch: false })),
61
- Watcher.node.replace(Watcher.configured({ enabled: false })),
62
- llmClient.replace(Layer.succeed(LLMClient.Service, llm)),
63
- SessionRunnerModel.node.replace(
64
- Layer.succeed(SessionRunnerModel.Service, { select: (session) => Effect.fail(new SessionRunnerModel.ModelNotSelectedError({ sessionID: session.id })), resolve: () => Effect.succeed(model) }),
65
- ),
66
- Instance.node.replace(
67
- makeGlobalNode({
68
- service: Instance.Service,
69
- deps: [LocationServiceMap.node],
70
- layer: Layer.effect(
71
- Instance.Service,
72
- Effect.gen(function* () {
73
- const locations = yield* LocationServiceMap.Service
74
- const instances = yield* LayerMap.make(
75
- (id: Session.ID) => {
76
- const config = configs.find((config) => config.id === id)
77
- if (!config) throw new Error(`No instance configuration for ${id}`)
78
- return Instance.layer(location, {
79
- discovery: false,
80
- replacements: bindings,
81
- plugins: [
82
- define({
83
- id: "session-instance",
84
- effect: Effect.fnUntraced(function* (ctx) {
85
- boots.push(config.id)
86
- yield* ctx.agent.transform((editor) =>
87
- editor.update("build", (agent) => {
88
- agent.permissions = [{ action: "*", resource: "*", effect: "allow" }]
89
- }),
90
- )
91
- yield* ctx.session.hook("prompt", (event) =>
92
- Effect.sync(() => {
93
- event.prompt.text += ` [${config.tool}]`
94
- }),
95
- )
96
- const tune = (event: SessionHooks["context"]) =>
97
- Effect.sync(() => {
98
- event.options.temperature = config.temperature
99
- })
100
- yield* ctx.session.hook("context", tune)
101
- yield* ctx.session.hook("generate", tune)
102
- yield* ctx.permission.hook("evaluate", (event) =>
103
- Effect.sync(() => {
104
- event.effect = event.action === "instance-test" ? "ask" : "allow"
105
- if (event.action === "instance-test") event.message = config.tool
106
- }),
107
- )
108
- yield* ctx.tool.transform((editor) =>
109
- editor.add({
110
- name: config.tool,
111
- description: `Tool for ${config.id}`,
112
- input: Schema.Struct({}),
113
- output: Schema.String,
114
- options: { codemode: false },
115
- execute: () =>
116
- Effect.sync(() => {
117
- executed.push(config.id)
118
- return { output: config.id, content: config.id }
119
- }),
120
- }),
121
- )
122
- yield* ctx.command.transform((editor) =>
123
- editor.add({
124
- name: "instance-check",
125
- execute: (input) =>
126
- ctx.session
127
- .prompt({
128
- sessionID: input.sessionID,
129
- text: `command ${config.tool}`,
130
- delivery: input.delivery,
131
- resume: false,
132
- })
133
- .pipe(
134
- Effect.tap(() => Effect.sync(() => commands.push(config.id))),
135
- Effect.asVoid,
136
- ),
137
- }),
138
- )
139
- }),
140
- }),
141
- ],
142
- })
143
- },
144
- { idleTimeToLive: Duration.infinity },
145
- )
146
- const selector = Instance.Service.of({
147
- provide: (session) => Effect.provide(instances.get(session.id)),
148
- })
149
- const bindings: LayerNode.Replacements = [
150
- ...replacements,
151
- Instance.node.replace(Layer.succeed(Instance.Service, selector)),
152
- LocationServiceMap.node.replace(Layer.succeed(LocationServiceMap.Service, locations)),
153
- ]
154
- return selector
155
- }),
156
- ),
157
- }),
158
- ),
159
- ]
160
- const context = yield* Layer.build(
161
- createEmbeddedRoutes({}, replacements).pipe(Layer.provide(HttpServer.layerServices)),
162
- )
163
- const sessions = Context.get(context, Session.Service)
164
- const instances = Context.get(context, Instance.Service)
165
- const locations = Context.get(context, LocationServiceMap.Service)
166
- const handler = Context.get(context, HttpRouter.HttpRouter)
167
- .asHttpEffect()
168
- .pipe(HttpEffect.toWebHandlerWith(context))
169
- const request = (route: string, body?: unknown) =>
170
- Effect.promise(() =>
171
- handler(
172
- new Request(
173
- `http://opencode.local${route}`,
174
- body === undefined
175
- ? undefined
176
- : { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) },
177
- ),
178
- ),
179
- )
180
-
181
- yield* Effect.forEach(configs, (config) =>
182
- sessions.create({
183
- id: config.id,
184
- title: config.tool,
185
- agent: Agent.ID.make("build"),
186
- model: model.ref,
187
- location,
188
- }),
189
- )
190
- expect((yield* sessions.list()).data.map((session) => session.location)).toEqual([location, location])
191
- expect(yield* sessions.messages({ sessionID: first.id })).toEqual([])
192
- yield* sessions.get(second.id)
193
- for (const config of configs) {
194
- for (const resource of ["permission", "form"]) {
195
- const response = yield* request(`/api/session/${config.id}/${resource}`)
196
- expect(response.status).toBe(200)
197
- expect(yield* Effect.promise<unknown>(() => response.json())).toEqual({ data: [] })
198
- }
199
- }
200
- // Reading permissions or forms builds the Session's Instance and starts its plugin activation at once; the
201
- // ordering assertion after the prompts is what proves each Session boots exactly once.
202
-
203
- for (const config of configs) {
204
- const session = yield* sessions.get(config.id)
205
- yield* Plugin.Service.use((plugins) => plugins.awaitActivation).pipe(instances.provide(session))
206
- const admitted = yield* sessions.prompt({ sessionID: config.id, text: "run", resume: false })
207
- expect(admitted.payload.text).toBe(`run [${config.tool}]`)
208
- }
209
- expect(boots).toEqual([first.id, second.id])
210
-
211
- for (const config of configs) {
212
- yield* llm.push(TestLLM.toolCall(`call_${config.tool}`, config.tool, {}), TestLLM.text(config.id, config.tool))
213
- yield* sessions.resume(config.id)
214
- }
215
- expect(executed).toEqual([first.id, second.id])
216
-
217
- for (const config of configs) {
218
- yield* llm.push(TestLLM.text(`generated ${config.id}`, config.tool))
219
- expect((yield* sessions.generate({ sessionID: config.id, prompt: "summarize" })).text).toBe(`generated ${config.id}`)
220
- yield* sessions.command({ sessionID: config.id, command: "instance-check", text: "" })
221
- expect(yield* sessions.inbox(config.id)).toMatchObject([
222
- { type: "user", payload: { text: `command ${config.tool} [${config.tool}]` } },
223
- ])
224
- }
225
- expect(commands).toEqual([first.id, second.id])
226
- expect(
227
- (yield* llm.requests()).map((request) => ({
228
- temperature: request.temperature,
229
- tools: request.tools?.filter((tool) => tool.name.startsWith("instance_")).map((tool) => tool.name),
230
- })),
231
- ).toEqual(
232
- [first, first, second, second, first, second].map((config) => ({
233
- temperature: config.temperature,
234
- tools: [config.tool],
235
- })),
236
- )
237
-
238
- // Seed through Core, then use HTTP to reach those exact private instances.
239
- const pending = yield* Effect.forEach(configs, (config) =>
240
- Effect.gen(function* () {
241
- const session = yield* sessions.get(config.id)
242
- return yield* Effect.gen(function* () {
243
- const forms = yield* Form.Service
244
- const permissions = yield* Permission.Service
245
- const form = yield* forms.create({
246
- sessionID: config.id,
247
- title: config.tool,
248
- fields: [{ key: "answer", type: "string" }],
249
- })
250
- const permission = {
251
- id: Permission.ID.create(),
252
- sessionID: config.id,
253
- action: "instance-test",
254
- resources: [config.tool],
255
- }
256
- expect(yield* permissions.ask(permission)).toEqual({ id: permission.id, effect: "ask" })
257
- const foreignID = config.id === first.id ? second.id : first.id
258
- const foreignForm = yield* forms.create({
259
- sessionID: foreignID,
260
- title: "Foreign form",
261
- fields: [{ key: "answer", type: "string" }],
262
- })
263
- const foreignPermission = yield* permissions.ask({
264
- ...permission,
265
- id: Permission.ID.create(),
266
- sessionID: foreignID,
267
- })
268
- return {
269
- session,
270
- form,
271
- permission: { ...permission, message: config.tool },
272
- foreignForm,
273
- foreignPermission,
274
- }
275
- }).pipe(instances.provide(session))
276
- }),
277
- )
278
- for (const entry of pending) {
279
- const forms = yield* request(`/api/session/${entry.session.id}/form`)
280
- expect(forms.status).toBe(200)
281
- expect(yield* Effect.promise<unknown>(() => forms.json())).toEqual({ data: [entry.form] })
282
- const permissions = yield* request(`/api/session/${entry.session.id}/permission`)
283
- expect(permissions.status).toBe(200)
284
- expect(yield* Effect.promise<unknown>(() => permissions.json())).toEqual({ data: [entry.permission] })
285
-
286
- // These IDs exist in the selected instance, but belong to the other Session.
287
- expect((yield* request(`/api/session/${entry.session.id}/form/${entry.foreignForm.id}`)).status).toBe(404)
288
- expect(
289
- (yield* request(`/api/session/${entry.session.id}/permission/${entry.foreignPermission.id}`)).status,
290
- ).toBe(404)
291
- expect(
292
- (yield* request(`/api/session/${entry.session.id}/form/${entry.foreignForm.id}/reply`, {
293
- answer: { answer: "wrong" },
294
- })).status,
295
- ).toBe(404)
296
- expect(
297
- (yield* request(`/api/session/${entry.session.id}/permission/${entry.foreignPermission.id}/reply`, {
298
- decision: "once",
299
- })).status,
300
- ).toBe(404)
301
- yield* Effect.gen(function* () {
302
- const forms = yield* Form.Service
303
- const permissions = yield* Permission.Service
304
- expect(yield* forms.state(entry.foreignForm.id)).toEqual({ status: "pending" })
305
- expect(yield* permissions.get(entry.foreignPermission.id)).toMatchObject({
306
- sessionID: entry.foreignForm.sessionID,
307
- })
308
- }).pipe(instances.provide(entry.session))
309
- }
310
- for (const entry of pending) {
311
- expect(
312
- (yield* request(`/api/session/${entry.session.id}/form/${entry.form.id}/reply`, {
313
- answer: { answer: entry.session.id },
314
- })).status,
315
- ).toBe(204)
316
- expect(
317
- (yield* request(`/api/session/${entry.session.id}/permission/${entry.permission.id}/reply`, {
318
- decision: "once",
319
- })).status,
320
- ).toBe(204)
321
- yield* Effect.gen(function* () {
322
- const forms = yield* Form.Service
323
- const permissions = yield* Permission.Service
324
- expect(yield* forms.state(entry.form.id)).toEqual({
325
- status: "answered",
326
- answer: { answer: entry.session.id },
327
- })
328
- expect(yield* permissions.get(entry.permission.id)).toBeUndefined()
329
- }).pipe(instances.provide(entry.session))
330
- }
331
- expect(boots).toEqual([first.id, second.id])
332
- expect(Array.from(yield* RcMap.keys(locations.rcMap))).toEqual([])
333
- }),
334
- 15_000,
335
- )
@@ -1,73 +0,0 @@
1
- import { expect } from "bun:test"
2
- import { Session } from "@zyro-sec/schema/session"
3
- import { Effect, Schema } from "effect"
4
- import { it } from "../../core/test/lib/effect"
5
- import { ServerFetch } from "../src/fetch"
6
-
7
- const SessionResponse = Schema.Struct({ data: Schema.toEncoded(Session.Info) })
8
-
9
- const makeRequest = Effect.fn(function* () {
10
- const handler = yield* ServerFetch.make({
11
- app: { version: "test" },
12
- database: { path: ":memory:" },
13
- fs: { filewatcher: false },
14
- models: { fetch: false },
15
- })
16
- return (path: string, method: string, body?: unknown) =>
17
- Effect.promise(async () => {
18
- const response = await handler(
19
- new Request(`http://opencode.local${path}`, {
20
- method,
21
- headers: { "content-type": "application/json" },
22
- body: body === undefined ? undefined : JSON.stringify(body),
23
- }),
24
- )
25
- expect(response.status).toBeLessThan(300)
26
- return response.status === 204 ? undefined : response.json()
27
- })
28
- })
29
-
30
- const archivedSession = Effect.fn(function* (request: Effect.Success<ReturnType<typeof makeRequest>>) {
31
- const created = Schema.decodeUnknownSync(SessionResponse)(yield* request("/api/session", "POST", {}))
32
- const id = created.data.id
33
- yield* request(`/api/session/${id}`, "PATCH", { archived: true })
34
- const archived = () =>
35
- request(`/api/session/${id}`, "GET").pipe(
36
- Effect.map((body) => Schema.decodeUnknownSync(SessionResponse)(body).data.time.archived !== undefined),
37
- )
38
- expect(yield* archived()).toBe(true)
39
- return { id, archived }
40
- })
41
-
42
- it.live("a user prompt unarchives an archived session", () =>
43
- Effect.gen(function* () {
44
- const request = yield* makeRequest()
45
- const session = yield* archivedSession(request)
46
-
47
- yield* request(`/api/session/${session.id}/prompt`, "POST", { text: "hello", resume: false })
48
-
49
- expect(yield* session.archived()).toBe(false)
50
- }).pipe(Effect.scoped),
51
- )
52
-
53
- it.live("a user shell command unarchives an archived session", () =>
54
- Effect.gen(function* () {
55
- const request = yield* makeRequest()
56
- const session = yield* archivedSession(request)
57
-
58
- yield* request(`/api/session/${session.id}/shell`, "POST", { command: "true" })
59
-
60
- expect(yield* session.archived()).toBe(false)
61
- }).pipe(Effect.scoped),
62
- )
63
-
64
- it.live("synthetic input leaves an archived session archived", () =>
65
- Effect.gen(function* () {
66
- const request = yield* makeRequest()
67
- const session = yield* archivedSession(request)
68
-
69
- yield* request(`/api/session/${session.id}/synthetic`, "POST", { text: "background notice", resume: false })
70
-
71
- expect(yield* session.archived()).toBe(true)
72
- }).pipe(Effect.scoped),
73
- )
@@ -1,66 +0,0 @@
1
- import { expect } from "bun:test"
2
- import { Session } from "@zyro-sec/schema/session"
3
- import { Effect, Schema } from "effect"
4
- import { it } from "../../core/test/lib/effect"
5
- import { ServerFetch } from "../src/fetch"
6
-
7
- const SessionResponse = Schema.Struct({ data: Schema.toEncoded(Session.Info) })
8
- const SessionsResponse = Schema.Struct({ data: Schema.Array(Schema.toEncoded(Session.Info)) })
9
-
10
- const makeRequest = Effect.fn(function* () {
11
- const handler = yield* ServerFetch.make({
12
- app: { version: "test" },
13
- database: { path: ":memory:" },
14
- fs: { filewatcher: false },
15
- models: { fetch: false },
16
- })
17
- return (path: string, method: string, body?: unknown) =>
18
- Effect.promise(async () => {
19
- const response = await handler(
20
- new Request(`http://opencode.local${path}`, {
21
- method,
22
- headers: { "content-type": "application/json" },
23
- body: body === undefined ? undefined : JSON.stringify(body),
24
- }),
25
- )
26
- expect(response.status).toBe(method === "PATCH" ? 204 : 200)
27
- return response.status === 204 ? undefined : response.json()
28
- })
29
- })
30
-
31
- it.live("updates session metadata through PATCH", () =>
32
- Effect.gen(function* () {
33
- const request = yield* makeRequest()
34
- const created = Schema.decodeUnknownSync(SessionResponse)(
35
- yield* request("/api/session", "POST", { metadata: { source: "create", stale: true } }),
36
- )
37
- yield* request(`/api/session/${created.data.id}`, "PATCH", { metadata: { source: "patch" } })
38
- const updated = Schema.decodeUnknownSync(SessionResponse)(yield* request(`/api/session/${created.data.id}`, "GET"))
39
-
40
- expect(updated.data.metadata).toEqual({ source: "patch" })
41
- }).pipe(Effect.scoped),
42
- )
43
-
44
- it.live("archives and unarchives a session through PATCH", () =>
45
- Effect.gen(function* () {
46
- const request = yield* makeRequest()
47
- const created = Schema.decodeUnknownSync(SessionResponse)(yield* request("/api/session", "POST", {}))
48
- const get = () =>
49
- request(`/api/session/${created.data.id}`, "GET").pipe(
50
- Effect.map((body) => Schema.decodeUnknownSync(SessionResponse)(body).data),
51
- )
52
- const listed = (archived: boolean) =>
53
- request(`/api/session?archived=${archived}`, "GET").pipe(
54
- Effect.map((body) => Schema.decodeUnknownSync(SessionsResponse)(body).data.map((item) => item.id)),
55
- )
56
-
57
- yield* request(`/api/session/${created.data.id}`, "PATCH", { archived: true })
58
- expect((yield* get()).time.archived).toBeNumber()
59
- expect(yield* listed(true)).toContain(created.data.id)
60
- expect(yield* listed(false)).not.toContain(created.data.id)
61
-
62
- yield* request(`/api/session/${created.data.id}`, "PATCH", { archived: false })
63
- expect((yield* get()).time.archived).toBeUndefined()
64
- expect(yield* listed(false)).toContain(created.data.id)
65
- }).pipe(Effect.scoped),
66
- )
@@ -1,57 +0,0 @@
1
- import fs from "node:fs/promises"
2
- import path from "node:path"
3
- import { expect } from "bun:test"
4
- import { Effect } from "effect"
5
- import { tmpdir } from "../../core/test/fixture/tmpdir"
6
- import { it } from "../../core/test/lib/effect"
7
- import { serveRoutes } from "./fixture/routes"
8
-
9
- it.live("lists configured skills and reads their files", () =>
10
- Effect.gen(function* () {
11
- const tmp = yield* Effect.acquireDisposable(Effect.promise(() => tmpdir("opencode-skill-endpoint-")))
12
- yield* Effect.promise(() => fs.mkdir(path.join(tmp.path, "skills", "demo"), { recursive: true }))
13
- yield* Effect.promise(() =>
14
- fs.writeFile(
15
- path.join(tmp.path, "skills", "demo", "SKILL.md"),
16
- "---\nname: demo\ndescription: Demo skill\n---\nbody\n",
17
- ),
18
- )
19
- yield* Effect.promise(() =>
20
- fs.writeFile(path.join(tmp.path, "opencode.json"), JSON.stringify({ skills: [path.join(tmp.path, "skills")] })),
21
- )
22
- const server = yield* serveRoutes({
23
- database: { path: ":memory:" },
24
- config: { directory: tmp.path },
25
- fs: { filewatcher: false },
26
- models: { fetch: false },
27
- })
28
- yield* server.pluginsLoaded(tmp.path)
29
- const url = new URL("/api/skill", "http://opencode.local")
30
- url.searchParams.set("location[directory]", tmp.path)
31
- const response = yield* Effect.promise(() => server.fetch(url))
32
-
33
- expect(response.status).toBe(200)
34
- const body: unknown = yield* Effect.promise(() => response.json())
35
- if (!isRecord(body) || !Array.isArray(body["data"])) throw new Error("Expected a skill list response")
36
- expect(body["data"].some((skill) => isRecord(skill) && skill["name"] === "demo")).toBeTrue()
37
-
38
- const file = (id: string, name: string) => {
39
- const url = new URL(`/api/experimental/skill/${id}/file/${name}`, "http://opencode.local")
40
- url.searchParams.set("location[directory]", tmp.path)
41
- return Effect.promise(() => server.fetch(url))
42
- }
43
- const found = yield* file("demo", "SKILL.md")
44
- expect(found.status).toBe(200)
45
- expect(yield* Effect.promise(() => found.text())).toBe("body\n")
46
- const missingFile = yield* file("demo", "other.md")
47
- expect(missingFile.status).toBe(404)
48
- expect(yield* Effect.promise(() => missingFile.json())).toMatchObject({ _tag: "FileNotFoundError" })
49
- const missingSkill = yield* file("missing", "SKILL.md")
50
- expect(missingSkill.status).toBe(404)
51
- expect(yield* Effect.promise(() => missingSkill.json())).toMatchObject({ _tag: "SkillNotFoundError" })
52
- }),
53
- )
54
-
55
- function isRecord(value: unknown): value is Record<string, unknown> {
56
- return typeof value === "object" && value !== null && !Array.isArray(value)
57
- }
@@ -1,71 +0,0 @@
1
- import { expect } from "bun:test"
2
- import { OpenCode } from "@zyro-sec/client/effect"
3
- import { ClientApi } from "@zyro-sec/protocol/client"
4
- import { Authorization } from "@zyro-sec/protocol/middleware/authorization"
5
- import { Event } from "@zyro-sec/schema/event"
6
- import { Session } from "@zyro-sec/schema/session"
7
- import { Cause, Effect, Exit, Layer, Stream } from "effect"
8
- import { HttpClient, HttpClientResponse, HttpRouter, HttpServer } from "effect/http"
9
- import { HttpApi, HttpApiBuilder, HttpApiGroup } from "effect/http-api"
10
- import { it } from "../../core/test/lib/effect"
11
- import { schemaErrorLayer } from "../src/middleware/schema-error"
12
-
13
- // Serve the real protocol declaration for the session log stream, so the server encoder and the
14
- // generated Effect client agree on the reserved SSE failure event for this Effect version.
15
- const LogApi = HttpApi.make("log").add(
16
- HttpApiGroup.make("server.session").add(ClientApi.groups["server.session"].endpoints["session.log"]),
17
- )
18
- const synced = { type: "log.synced" as const, aggregateID: "ses_test", seq: Event.Seq.make(1) }
19
-
20
- const handler = HttpRouter.toWebHandler(
21
- HttpApiBuilder.layer(LogApi).pipe(
22
- Layer.provide(
23
- HttpApiBuilder.group(LogApi, "server.session", (handlers) =>
24
- handlers.handle("session.log", () =>
25
- Effect.succeed(Stream.make(synced).pipe(Stream.concat(Stream.die(new Error("log reader failed"))))),
26
- ),
27
- ),
28
- ),
29
- Layer.provide(schemaErrorLayer),
30
- Layer.provide(
31
- Layer.succeed(
32
- Authorization,
33
- Authorization.of((effect) => effect),
34
- ),
35
- ),
36
- Layer.provide(HttpServer.layerServices),
37
- ),
38
- ).handler
39
-
40
- const fetchLog = (request: Request) => Effect.promise(() => handler(request))
41
-
42
- it.live("encodes a mid-stream session log failure as the reserved SSE failure event", () =>
43
- Effect.gen(function* () {
44
- const response = yield* fetchLog(new Request("http://opencode.local/api/experimental/session/ses_test/log"))
45
- const body = yield* Effect.promise(() => response.text())
46
- expect(response.headers.get("content-type")).toContain("text/event-stream")
47
- expect(body).toContain("event: effect/http-api/stream/failure")
48
- }),
49
- )
50
-
51
- it.live("the generated Effect client fails the session log stream with the server's defect", () =>
52
- Effect.gen(function* () {
53
- const httpClient = HttpClient.make((request) =>
54
- fetchLog(new Request(request.url, { method: request.method })).pipe(
55
- Effect.map((response) => HttpClientResponse.fromWeb(request, response)),
56
- ),
57
- )
58
- const received: unknown[] = []
59
- const exit = yield* Effect.gen(function* () {
60
- const client = yield* OpenCode.make({ baseUrl: "http://opencode.local" })
61
- return yield* client.experimental.session
62
- .log({ sessionID: Session.ID.make("ses_test") })
63
- .pipe(Stream.runForEach((item) => Effect.sync(() => received.push(item))))
64
- }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient), Effect.exit)
65
-
66
- expect(received).toEqual([synced])
67
- expect(Exit.isFailure(exit) && Cause.hasDies(exit.cause)).toBe(true)
68
- if (Exit.isSuccess(exit)) return
69
- expect(Cause.squash(exit.cause)).toMatchObject({ message: "log reader failed" })
70
- }),
71
- )