@zyro-sec/sdk 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.
@@ -1,389 +0,0 @@
1
- import { expect, test } from "bun:test"
2
- import { mkdir } from "node:fs/promises"
3
- import { join } from "node:path"
4
- import { Schema } from "effect"
5
- import { tmpdir } from "../../core/test/fixture/tmpdir"
6
- import { OpenCode, Session, SessionMessage } from "../src"
7
-
8
- const metadata = Schema.decodeUnknownSync(Schema.Struct({ account: Schema.String }))
9
- const hostOptions = (directory: string) => ({
10
- database: { path: join(directory, "opencode.sqlite") },
11
- config: { directory, project: false, content: "{}" },
12
- models: { fetch: false },
13
- fs: { filewatcher: false },
14
- })
15
-
16
- test("Promise instances are lazy, share by key and Location, and stay isolated between hosts", async () => {
17
- await using directory = await tmpdir("opencode-promise-instances-")
18
- const otherDirectory = join(directory.path, "other")
19
- await mkdir(otherDirectory)
20
- const configured: string[] = []
21
- const setups: string[] = []
22
- const cleanups: string[] = []
23
- const createHost = (name: string) => {
24
- const instances: OpenCode.InstanceOptions = {
25
- key(session) {
26
- expect(typeof session.time.created).toBe("number")
27
- return metadata(session.metadata).account
28
- },
29
- configure(key): OpenCode.InstanceConfiguration {
30
- configured.push(`${name}:${key}`)
31
- return {
32
- plugins: [
33
- {
34
- id: "account-prompts",
35
- async setup(ctx) {
36
- const activation = `${name}:${key}@${ctx.location.directory}`
37
- setups.push(activation)
38
- await ctx.session.hook("prompt", (event) => {
39
- event.prompt.text = `${activation}: ${event.prompt.text}`
40
- })
41
- return () => {
42
- cleanups.push(activation)
43
- }
44
- },
45
- },
46
- ],
47
- }
48
- },
49
- }
50
- return OpenCode.create({
51
- ...hostOptions(directory.path),
52
- database: { path: join(directory.path, `${name}.sqlite`) },
53
- instances,
54
- })
55
- }
56
-
57
- await using first = await createHost("first")
58
- await using second = await createHost("second")
59
- const sessionID = Session.ID.create()
60
- const original = await first.sessions.create({
61
- id: sessionID,
62
- location: { directory: directory.path },
63
- metadata: { account: "alpha", labels: ["review", 2] },
64
- })
65
- const sameKey = await first.sessions.create({
66
- location: { directory: directory.path },
67
- metadata: original.metadata,
68
- })
69
- const separateKey = await first.sessions.create({
70
- location: { directory: directory.path },
71
- metadata: { account: "beta" },
72
- })
73
- const separateLocation = await first.sessions.create({
74
- location: { directory: otherDirectory },
75
- metadata: { account: "alpha" },
76
- })
77
- const separateHost = await second.sessions.create({
78
- id: sessionID,
79
- location: { directory: directory.path },
80
- metadata: original.metadata,
81
- })
82
-
83
- expect(await first.sessions.get({ sessionID })).toEqual(original)
84
- expect((await first.sessions.list()).data).toHaveLength(4)
85
- expect((await first.message.list({ sessionID })).data).toEqual([])
86
- expect(await first.sessions.context({ sessionID })).toEqual([])
87
- expect(await first.sessions.inbox.list({ sessionID })).toEqual([])
88
- expect(await second.sessions.get({ sessionID })).toEqual(separateHost)
89
- expect(configured).toEqual([])
90
- expect(setups).toEqual([])
91
- // Permission and form lists read instance services, so they acquire the Session's instance.
92
- expect(await first.permission.list({ sessionID })).toEqual([])
93
- expect(await first.session.form.list({ sessionID })).toEqual([])
94
- expect(configured).toEqual(["first:alpha"])
95
-
96
- await Promise.all(
97
- [
98
- { host: first, session: original, prefix: `first:alpha@${directory.path}` },
99
- { host: first, session: sameKey, prefix: `first:alpha@${directory.path}` },
100
- { host: first, session: separateKey, prefix: `first:beta@${directory.path}` },
101
- { host: first, session: separateLocation, prefix: `first:alpha@${otherDirectory}` },
102
- { host: second, session: separateHost, prefix: `second:alpha@${directory.path}` },
103
- ].map(async (input) => {
104
- const admitted = await input.host.sessions.prompt({
105
- sessionID: input.session.id,
106
- text: "Review this change",
107
- resume: false,
108
- })
109
- expect(admitted.payload.text).toBe(`${input.prefix}: Review this change`)
110
- expect(await input.host.sessions.inbox.list({ sessionID: input.session.id })).toEqual([admitted])
111
- }),
112
- )
113
-
114
- await first.sessions.switchAgent({ sessionID, agent: "plan" })
115
- const fork = await first.sessions.fork({ sessionID })
116
- expect(fork.metadata).toEqual(original.metadata)
117
- expect(fork.location).toEqual(original.location)
118
- expect(fork.fork?.sessionID).toBe(sessionID)
119
- const inherited = await first.sessions.prompt({ sessionID: fork.id, text: "Review the fork", resume: false })
120
- expect(inherited.payload.text).toBe(`first:alpha@${directory.path}: Review the fork`)
121
- expect(await first.sessions.inbox.list({ sessionID: fork.id })).toEqual([
122
- expect.objectContaining({ type: "synthetic", sessionID: fork.id, id: `msg_fork_notice_${fork.id}` }),
123
- inherited,
124
- ])
125
-
126
- expect(configured.toSorted()).toEqual(["first:alpha", "first:alpha", "first:beta", "second:alpha"])
127
- expect(setups.toSorted()).toEqual(
128
- [
129
- `first:alpha@${directory.path}`,
130
- `first:alpha@${otherDirectory}`,
131
- `first:beta@${directory.path}`,
132
- `second:alpha@${directory.path}`,
133
- ].toSorted(),
134
- )
135
- expect(cleanups).toEqual([])
136
- expect(await first.sessions.active()).toEqual({})
137
- await first.close()
138
- expect(cleanups.toSorted()).toEqual(setups.filter((activation) => activation.startsWith("first:")).toSorted())
139
-
140
- const continued = await second.sessions.prompt({ sessionID, text: "Keep working", resume: false })
141
- expect(continued.payload.text).toBe(`second:alpha@${directory.path}: Keep working`)
142
- expect(await second.sessions.inbox.list({ sessionID })).toHaveLength(2)
143
- expect(configured).toHaveLength(4)
144
- await second.close()
145
- expect(cleanups.toSorted()).toEqual(setups.toSorted())
146
- }, 20_000)
147
-
148
- test("a throwing fork hook still returns the saved fork", async () => {
149
- await using directory = await tmpdir("opencode-fork-hook-")
150
- const seen: string[] = []
151
- await using host = await OpenCode.create({
152
- ...hostOptions(directory.path),
153
- plugins: [
154
- {
155
- id: "broken-fork-hook",
156
- async setup(ctx) {
157
- await ctx.session.hook("fork", ({ sessionID }) => {
158
- seen.push(sessionID)
159
- throw new Error("fork hook failed")
160
- })
161
- },
162
- },
163
- ],
164
- })
165
- const parent = await host.sessions.create({ location: { directory: directory.path } })
166
- await host.sessions.switchAgent({ sessionID: parent.id, agent: "plan" })
167
- const fork = await host.sessions.fork({ sessionID: parent.id })
168
- expect(seen).toEqual([fork.id])
169
- expect(await host.sessions.get({ sessionID: fork.id })).toMatchObject({ id: fork.id, fork: { sessionID: parent.id } })
170
- })
171
-
172
- test.each(["configuration", "plugin setup"])(
173
- "Promise instance %s failure admits nothing, preserves healthy instances, and can be retried",
174
- async (failure) => {
175
- await using directory = await tmpdir("opencode-promise-instance-failure-")
176
- const configured: string[] = []
177
- const setups: string[] = []
178
- const cleanups: string[] = []
179
- await using opencode = await OpenCode.create({
180
- ...hostOptions(directory.path),
181
- instances: {
182
- key: (session) => metadata(session.metadata).account,
183
- async configure(key) {
184
- configured.push(key)
185
- if (key === "retry" && failure === "configuration" && configured.filter((item) => item === key).length === 1)
186
- throw new Error("Account configuration unavailable")
187
- return {
188
- plugins: [
189
- {
190
- id: "account-prompts",
191
- async setup(ctx) {
192
- setups.push(key)
193
- await ctx.session.hook("prompt", (event) => {
194
- event.prompt.text = `${key}: ${event.prompt.text}`
195
- })
196
- if (
197
- key === "retry" &&
198
- failure === "plugin setup" &&
199
- setups.filter((item) => item === key).length === 1
200
- )
201
- throw new Error("Account plugin unavailable")
202
- return () => {
203
- cleanups.push(key)
204
- }
205
- },
206
- },
207
- ],
208
- }
209
- },
210
- },
211
- })
212
- const healthy = await opencode.sessions.create({
213
- location: { directory: directory.path },
214
- metadata: { account: "healthy" },
215
- })
216
- const retry = await opencode.sessions.create({
217
- location: { directory: directory.path },
218
- metadata: { account: "retry" },
219
- })
220
- const before = await opencode.sessions.prompt({ sessionID: healthy.id, text: "Before failure", resume: false })
221
- expect(before.payload.text).toBe("healthy: Before failure")
222
- const input = { sessionID: retry.id, id: SessionMessage.ID.create(), text: "Retry this input", resume: false }
223
-
224
- expect(await opencode.sessions.prompt(input).catch((error: unknown) => error)).toMatchObject({
225
- name: "ClientError",
226
- reason: "UnexpectedStatus",
227
- })
228
- expect(await opencode.sessions.inbox.list({ sessionID: retry.id })).toEqual([])
229
- expect((await opencode.message.list({ sessionID: retry.id })).data).toEqual([])
230
- expect(await opencode.sessions.get({ sessionID: retry.id })).toEqual(retry)
231
- expect(configured).toEqual(["healthy", "retry"])
232
- expect(cleanups).toEqual([])
233
-
234
- const after = await opencode.sessions.prompt({ sessionID: healthy.id, text: "After failure", resume: false })
235
- expect(after.payload.text).toBe("healthy: After failure")
236
- expect(await opencode.sessions.inbox.list({ sessionID: healthy.id })).toEqual([before, after])
237
- const admitted = await opencode.sessions.prompt(input)
238
- expect(admitted.id).toBe(input.id)
239
- expect(admitted.payload.text).toBe("retry: Retry this input")
240
- expect(await opencode.sessions.inbox.list({ sessionID: retry.id })).toEqual([admitted])
241
- expect(configured).toEqual(["healthy", "retry", "retry"])
242
- expect(setups).toEqual(failure === "configuration" ? ["healthy", "retry"] : ["healthy", "retry", "retry"])
243
- expect(cleanups).toEqual([])
244
- await opencode.close()
245
- expect(cleanups.toSorted()).toEqual(["healthy", "retry"])
246
- },
247
- 20_000,
248
- )
249
-
250
- test("Promise instances reconstruct callbacks for persisted Sessions only on a cold prompt", async () => {
251
- await using directory = await tmpdir("opencode-promise-instance-restart-")
252
- const sessionID = Session.ID.create()
253
- const configured: string[] = []
254
- const setups: number[] = []
255
- const cleanups: number[] = []
256
- const options: OpenCode.CreateOptions = {
257
- ...hostOptions(directory.path),
258
- instances: {
259
- key: (session) => metadata(session.metadata).account,
260
- configure(key) {
261
- configured.push(key)
262
- const generation = configured.length
263
- return {
264
- plugins: [
265
- {
266
- id: "account-prompts",
267
- async setup(ctx) {
268
- setups.push(generation)
269
- await ctx.session.hook("prompt", (event) => {
270
- event.prompt.text = `${key}/${generation}: ${event.prompt.text}`
271
- })
272
- return () => {
273
- cleanups.push(generation)
274
- }
275
- },
276
- },
277
- ],
278
- }
279
- },
280
- },
281
- }
282
- await using first = await OpenCode.create(options)
283
- const created = await first.sessions.create({
284
- id: sessionID,
285
- location: { directory: directory.path },
286
- metadata: { account: "alpha", labels: ["review"] },
287
- })
288
- const before = await first.sessions.prompt({ sessionID, text: "Before restart", resume: false })
289
- expect(before.payload.text).toBe("alpha/1: Before restart")
290
- await first.close()
291
- expect(cleanups).toEqual([1])
292
-
293
- await using second = await OpenCode.create(options)
294
- expect(await second.sessions.get({ sessionID })).toMatchObject({
295
- id: sessionID,
296
- location: created.location,
297
- metadata: created.metadata,
298
- time: { created: created.time.created },
299
- })
300
- expect((await second.sessions.list()).data.map((session) => session.id)).toEqual([sessionID])
301
- expect(await second.sessions.inbox.list({ sessionID })).toEqual([before])
302
- expect((await second.message.list({ sessionID })).data).toEqual([])
303
- expect(configured).toEqual(["alpha"])
304
- expect(setups).toEqual([1])
305
-
306
- // The HTTP prompt boundary still acquires capabilities, even when Core reconciles an existing admission.
307
- expect(await second.sessions.prompt({ sessionID, id: before.id, text: "Already admitted", resume: false })).toEqual(
308
- before,
309
- )
310
- expect(configured).toEqual(["alpha", "alpha"])
311
- expect(setups).toEqual([1, 2])
312
- expect(await second.sessions.active()).toEqual({})
313
-
314
- const after = await second.sessions.prompt({ sessionID, text: "After restart", resume: false })
315
- expect(after.payload.text).toBe("alpha/2: After restart")
316
- expect(await second.sessions.inbox.list({ sessionID })).toEqual([before, after])
317
- expect(configured).toEqual(["alpha", "alpha"])
318
- expect(setups).toEqual([1, 2])
319
- expect(cleanups).toEqual([1])
320
- await second.close()
321
- expect(cleanups).toEqual([1, 2])
322
- }, 20_000)
323
-
324
- test("Promise instance plugin ID collisions reject admission and reconstruct on retry", async () => {
325
- await using directory = await tmpdir("opencode-promise-instance-collision-")
326
- const configured: string[] = []
327
- const setups: string[] = []
328
- const cleanups: string[] = []
329
- await using opencode = await OpenCode.create({
330
- ...hostOptions(directory.path),
331
- plugins: [
332
- {
333
- id: "account-prompts",
334
- setup() {
335
- setups.push("host")
336
- return () => {
337
- cleanups.push("host")
338
- }
339
- },
340
- },
341
- ],
342
- instances: {
343
- key: (session) => metadata(session.metadata).account,
344
- configure(key) {
345
- configured.push(key)
346
- return {
347
- plugins: [
348
- {
349
- id: configured.length === 1 ? "account-prompts" : "instance-prompts",
350
- async setup(ctx) {
351
- setups.push(key)
352
- await ctx.session.hook("prompt", (event) => {
353
- event.prompt.text = `${key}: ${event.prompt.text}`
354
- })
355
- },
356
- },
357
- ],
358
- }
359
- },
360
- },
361
- })
362
- const session = await opencode.sessions.create({
363
- location: { directory: directory.path },
364
- metadata: { account: "alpha" },
365
- })
366
- const input = { sessionID: session.id, id: SessionMessage.ID.create(), text: "Retry this input", resume: false }
367
- expect(configured).toEqual([])
368
-
369
- expect(await opencode.sessions.prompt(input).catch((error: unknown) => error)).toMatchObject({
370
- name: "ClientError",
371
- reason: "UnexpectedStatus",
372
- })
373
- expect(await opencode.sessions.inbox.list({ sessionID: session.id })).toEqual([])
374
- expect((await opencode.message.list({ sessionID: session.id })).data).toEqual([])
375
- expect(configured).toEqual(["alpha"])
376
- // The host plugin wins the ID and activates inside the instance before the colliding instance plugin
377
- // is reported failed; rejecting the instance tears that generation down again.
378
- expect(setups).toEqual(["host"])
379
- expect(cleanups).toEqual(["host"])
380
-
381
- const admitted = await opencode.sessions.prompt(input)
382
- expect(admitted.id).toBe(input.id)
383
- expect(admitted.payload.text).toBe("alpha: Retry this input")
384
- expect(await opencode.sessions.inbox.list({ sessionID: session.id })).toEqual([admitted])
385
- expect(configured).toEqual(["alpha", "alpha"])
386
- // The reconstructed instance runs a fresh generation: host plugin again, then the renamed instance plugin.
387
- expect(setups).toEqual(["host", "host", "alpha"])
388
- expect(cleanups).toEqual(["host"])
389
- }, 20_000)
@@ -1,20 +0,0 @@
1
- import { expect, test } from "bun:test"
2
- import { Effect } from "effect"
3
- import type { LogEntry } from "../src/logging"
4
- import { layer } from "../src/logging"
5
-
6
- test("maps Effect log levels to SDK log levels", async () => {
7
- const entries: LogEntry[] = []
8
- await Effect.runPromise(
9
- Effect.gen(function* () {
10
- yield* Effect.logTrace("trace")
11
- yield* Effect.logDebug("debug")
12
- yield* Effect.logInfo("info")
13
- yield* Effect.logWarning("warn")
14
- yield* Effect.logError("error")
15
- yield* Effect.logFatal("fatal")
16
- }).pipe(Effect.provide(layer({ level: "trace", emit: (entry) => entries.push(entry) }))),
17
- )
18
-
19
- expect(entries.map((entry) => entry.level)).toEqual(["trace", "debug", "info", "warn", "error", "fatal"])
20
- })
@@ -1,66 +0,0 @@
1
- import { expect, test } from "bun:test"
2
- import { mkdir } from "node:fs/promises"
3
- import { join } from "node:path"
4
- import { tmpdir } from "../../core/test/fixture/tmpdir"
5
- import { OpenCode, Session } from "../src"
6
-
7
- test("Promise host uses the embedded router", async () => {
8
- await using directory = await tmpdir("opencode-promise-sdk-")
9
- const config = join(directory.path, "config")
10
- await mkdir(config)
11
- const opencode = await OpenCode.create({
12
- events: { persist: true },
13
- config: { directory: config, project: false, content: "{}" },
14
- })
15
-
16
- try {
17
- const location = { directory: directory.path }
18
- const session = await opencode.sessions.create({ location })
19
- const selected = await opencode.sessions.get({ sessionID: session.id })
20
- const page = await opencode.sessions.list({ directory: directory.path })
21
- const events = Array.fromAsync(opencode.experimental.session.log({ sessionID: session.id }))
22
-
23
- expect(selected.id).toBe(session.id)
24
- expect(page.data.some((item) => item.id === session.id)).toBe(true)
25
- expect((await events).some((event) => event.type === "session.created")).toBe(true)
26
-
27
- const missingSessionID = Session.ID.create()
28
- const missing = await opencode.sessions.get({ sessionID: missingSessionID }).catch((error: unknown) => error)
29
- expect(missing).toMatchObject({ _tag: "SessionNotFoundError", sessionID: missingSessionID })
30
- } finally {
31
- await opencode.close()
32
- await opencode.close()
33
- }
34
- })
35
-
36
- test("Promise event streams support cancellation", async () => {
37
- await using directory = await tmpdir("opencode-promise-stream-")
38
- const config = join(directory.path, "config")
39
- await mkdir(config)
40
- {
41
- await using opencode = await OpenCode.create({ config: { directory: config, project: false, content: "{}" } })
42
- const controller = new AbortController()
43
- const events = opencode.events.subscribe({ signal: controller.signal })[Symbol.asyncIterator]()
44
- expect(await events.next()).toMatchObject({ value: { type: "server.connected" }, done: false })
45
- const pending = events.next()
46
- controller.abort()
47
- // A caller abort ends only this subscriber; client tests pin closing the shared transport after the last one.
48
- expect(await pending).toEqual({ done: true, value: undefined })
49
- await events.return?.()
50
- }
51
- })
52
-
53
- test("closing cancels active Promise event streams", async () => {
54
- await using directory = await tmpdir("opencode-promise-stream-close-")
55
- const config = join(directory.path, "config")
56
- await mkdir(config)
57
- const opencode = await OpenCode.create({ config: { directory: config, project: false, content: "{}" } })
58
- const events = opencode.events.subscribe()[Symbol.asyncIterator]()
59
- expect(await events.next()).toMatchObject({ value: { type: "server.connected" }, done: false })
60
- // Closing rejects the read before close resolves, so the handler has to be attached first.
61
- const pending = events.next().catch((error: unknown) => error)
62
-
63
- await opencode.close()
64
- const error = await pending
65
- expect(error).toMatchObject({ name: "ClientError", reason: "Transport" })
66
- })
@@ -1,133 +0,0 @@
1
- import { expect } from "bun:test"
2
- import { fullGC, heapStats } from "bun:jsc"
3
- import { Effect, Layer } from "effect"
4
- import { tmpdirScoped } from "../../core/test/fixture/tmpdir"
5
- import { testEffect } from "../../core/test/lib/effect"
6
- import { OpenCode } from "../src/effect"
7
- import { OwnedFetch } from "../src/internal/fetch"
8
-
9
- const it = testEffect(Layer.empty)
10
-
11
- it.live("releases completed embedded requests while the host stays open", () =>
12
- Effect.gen(function* () {
13
- const directory = yield* tmpdirScoped()
14
- const client = yield* OpenCode.create({
15
- app: { version: "request-retention-test" },
16
- config: { directory: directory.path, project: false, content: "{}" },
17
- events: { persist: true },
18
- models: { fetch: false },
19
- fs: { filewatcher: false },
20
- })
21
-
22
- fullGC()
23
- const before = heapStats().objectTypeCounts.Request ?? 0
24
- for (let index = 0; index < 200; index++) {
25
- expect((yield* client.server.info()).version).toBe("request-retention-test")
26
- }
27
-
28
- // Completed response cleanup crosses an event-loop turn in the embedded transport.
29
- yield* Effect.promise(() => Bun.sleep(100))
30
- fullGC()
31
- expect((heapStats().objectTypeCounts.Request ?? 0) - before).toBeLessThan(20)
32
- }),
33
- )
34
-
35
- it.live("releases failed embedded requests while the host and caller signal stay open", () =>
36
- Effect.promise(async () => {
37
- const caller = new AbortController()
38
- const requests: WeakRef<Request>[] = []
39
- const transport = OwnedFetch.make(
40
- async (request) => {
41
- requests.push(new WeakRef(request))
42
- request.signal.addEventListener("abort", () => void request.url)
43
- throw new Error("handler failed")
44
- },
45
- async () => {},
46
- )
47
-
48
- for (let index = 0; index < 120; index++) {
49
- expect(
50
- await transport
51
- .fetch(`http://opencode.local/${index}`, { signal: caller.signal })
52
- .catch((cause: unknown) => cause),
53
- ).toMatchObject({
54
- message: "handler failed",
55
- })
56
- }
57
-
58
- await Bun.sleep(50)
59
- fullGC()
60
- expect(caller.signal.aborted).toBe(false)
61
- expect(requests.filter((ref) => ref.deref() !== undefined).length).toBeLessThanOrEqual(3)
62
- await transport.close()
63
- }),
64
- )
65
-
66
- it.live("keeps caller abort and host shutdown wired to active requests", () =>
67
- Effect.promise(async () => {
68
- const seen: unknown[] = []
69
- let disposed = false
70
- const transport = OwnedFetch.make(
71
- async (request) => {
72
- await new Promise<void>((resolve) => {
73
- request.signal.addEventListener(
74
- "abort",
75
- () => {
76
- seen.push(request.signal.reason)
77
- resolve()
78
- },
79
- { once: true },
80
- )
81
- })
82
- return new Response("aborted")
83
- },
84
- async () => {
85
- disposed = true
86
- },
87
- )
88
- const controller = new AbortController()
89
- const first = transport.fetch("http://opencode.local/", { signal: controller.signal })
90
- controller.abort("caller")
91
- expect(await first.catch((error: unknown) => error)).toBe("caller")
92
-
93
- const second = transport.fetch("http://opencode.local/")
94
- const closed = transport.close()
95
- const failure = await second.catch((error: unknown) => error)
96
- expect(failure).toBeInstanceOf(Error)
97
- expect(failure).toMatchObject({ message: "OpenCode host is closed" })
98
- await closed
99
- expect(disposed).toBe(true)
100
- expect(seen).toEqual(["caller", failure])
101
- }),
102
- )
103
-
104
- it.live("cancels an open response body on host shutdown before disposing the handler", () =>
105
- Effect.promise(async () => {
106
- const cancelled = Promise.withResolvers<unknown>()
107
- let disposed = false
108
- const transport = OwnedFetch.make(
109
- async () =>
110
- new Response(
111
- new ReadableStream({
112
- cancel(reason) {
113
- cancelled.resolve(reason)
114
- },
115
- }),
116
- ),
117
- async () => {
118
- disposed = true
119
- },
120
- )
121
-
122
- const response = await transport.fetch("http://opencode.local/stream")
123
- const reading = response.body!.getReader().read()
124
- const closing = transport.close()
125
- const reason = await cancelled.promise
126
-
127
- expect(reason).toBeInstanceOf(Error)
128
- expect(reason).toMatchObject({ message: "OpenCode host is closed" })
129
- expect(await reading.catch((cause: unknown) => cause)).toBe(reason)
130
- await closing
131
- expect(disposed).toBe(true)
132
- }),
133
- )
@@ -1,70 +0,0 @@
1
- import { expect } from "bun:test"
2
- import { Context, Effect, Exit, Layer, Scope, Stream } from "effect"
3
- import { FetchHttpClient } from "effect/http"
4
- import { tmpdirScoped } from "../../core/test/fixture/tmpdir"
5
- import { testEffect } from "../../core/test/lib/effect"
6
- import { AbsolutePath, Location, OpenCode, Session } from "../src/effect"
7
-
8
- const it = testEffect(Layer.empty)
9
-
10
- for (const entrypoint of ["create", "layer"] as const) {
11
- it.live(`${entrypoint} keeps requests and streams on its own transport despite an ambient Fetch`, () =>
12
- Effect.gen(function* () {
13
- const directory = yield* tmpdirScoped()
14
- const calls: string[] = []
15
- const ambient = Object.assign(
16
- (input: RequestInfo | URL) => {
17
- calls.push(input instanceof Request ? input.url : String(input))
18
- return Promise.reject(new Error("The caller's Fetch must not receive embedded SDK requests"))
19
- },
20
- { preconnect: () => undefined },
21
- )
22
- const parent = yield* Effect.scope
23
- const scope = yield* Scope.fork(parent)
24
- const options: OpenCode.CreateOptions = {
25
- app: { version: "transport-test" },
26
- config: { directory: directory.path, project: false, content: "{}" },
27
- events: { persist: true },
28
- models: { fetch: false },
29
- fs: { filewatcher: false },
30
- }
31
- const client = yield* (
32
- entrypoint === "create"
33
- ? OpenCode.create(options).pipe(Scope.provide(scope))
34
- : Layer.buildWithScope(OpenCode.layer(options), scope).pipe(Effect.map(Context.get(OpenCode.Service)))
35
- ).pipe(Effect.provideService(FetchHttpClient.Fetch, ambient))
36
-
37
- yield* Effect.gen(function* () {
38
- expect(yield* client.server.info()).toMatchObject({ version: "transport-test" })
39
- const session = yield* client.sessions.create({
40
- location: Location.Ref.make({ directory: AbsolutePath.make(directory.path) }),
41
- })
42
- expect((yield* client.sessions.get({ sessionID: session.id })).id).toBe(session.id)
43
- const events = yield* client.experimental.session.log({ sessionID: session.id }).pipe(Stream.runCollect)
44
- expect(events.some((event) => event.type === "session.created")).toBe(true)
45
- expect(yield* client.events.subscribe().pipe(Stream.take(1), Stream.runCollect)).toMatchObject([
46
- { type: "server.connected" },
47
- ])
48
- const missing = Session.ID.create()
49
- // Error responses must decode over the SDK transport too; sessions.get is served by core without HTTP.
50
- expect(yield* client.experimental.session.export({ sessionID: missing }).pipe(Effect.flip)).toMatchObject({
51
- _tag: "SessionNotFoundError",
52
- })
53
- expect(yield* client.sessions.get({ sessionID: missing }).pipe(Effect.flip)).toMatchObject({
54
- _tag: "Session.NotFoundError",
55
- })
56
- // Binding the SDK's transport must not change the caller's surrounding context.
57
- expect(yield* FetchHttpClient.Fetch).toBe(ambient)
58
- }).pipe(Effect.provideService(FetchHttpClient.Fetch, ambient))
59
- expect(calls).toEqual([])
60
-
61
- yield* Scope.close(scope, Exit.void)
62
- expect(
63
- Exit.isFailure(
64
- yield* client.server.info().pipe(Effect.provideService(FetchHttpClient.Fetch, ambient), Effect.exit),
65
- ),
66
- ).toBe(true)
67
- expect(calls).toEqual([])
68
- }),
69
- )
70
- }