@zyro-sec/sdk 1.0.0 → 1.0.2

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "name": "@zyro-sec/sdk",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -12,9 +12,6 @@
12
12
  "publishConfig": {
13
13
  "access": "public"
14
14
  },
15
- "files": [
16
- "dist"
17
- ],
18
15
  "exports": {
19
16
  ".": "./src/index.ts",
20
17
  "./effect": "./src/effect/index.ts",
@@ -30,20 +27,21 @@
30
27
  "verify:package": "bun run script/verify-package.ts"
31
28
  },
32
29
  "dependencies": {
33
- "@zyro-sec/client": "^1.0.0",
34
- "@zyro-sec/core": "^1.0.0",
35
- "@zyro-sec/plugin": "^1.0.0",
36
- "@zyro-sec/schema": "^1.0.0",
37
- "@zyro-sec/server": "^1.0.0",
38
- "@zyro-sec/util": "^1.0.0",
39
- "effect": "catalog:"
30
+ "@zyro-sec/client": "^1.0.2",
31
+ "@zyro-sec/core": "^1.0.2",
32
+ "@zyro-sec/plugin": "^1.0.2",
33
+ "@zyro-sec/schema": "^1.0.2",
34
+ "@zyro-sec/server": "^1.0.2",
35
+ "@zyro-sec/util": "^1.0.2",
36
+ "effect": "4.1.0"
40
37
  },
41
38
  "devDependencies": {
42
- "@zyro-sec/ai": "^1.0.0",
43
- "@zyro-sec/httpapi-codegen": "^1.0.0",
44
- "@zyro-sec/protocol": "^1.0.0",
45
- "@tsconfig/bun": "catalog:",
46
- "@types/bun": "catalog:",
47
- "@typescript/native": "catalog:"
48
- }
39
+ "@zyro-sec/ai": "^1.0.2",
40
+ "@zyro-sec/httpapi-codegen": "^1.0.2",
41
+ "@zyro-sec/protocol": "^1.0.2",
42
+ "@tsconfig/bun": "1.0.9",
43
+ "@types/bun": "1.4.3",
44
+ "@typescript/native": "npm:typescript@7.1.0-beta"
45
+ },
46
+ "main": "src/index.ts"
49
47
  }
@@ -0,0 +1,28 @@
1
+ #!/usr/bin/env bun
2
+
3
+ import { $ } from "bun"
4
+ import { rm } from "node:fs/promises"
5
+ import path from "node:path"
6
+ import { fileURLToPath } from "node:url"
7
+
8
+ process.chdir(fileURLToPath(new URL("..", import.meta.url)))
9
+
10
+ await rm("dist", { recursive: true, force: true })
11
+ await $`bun tsc -p tsconfig.build.json`
12
+ const root = path.resolve("src")
13
+ const result = await Bun.build({
14
+ entrypoints: await Array.fromAsync(new Bun.Glob("**/*.ts").scan({ cwd: root, absolute: true })).then((files) =>
15
+ files.filter((file) => !file.endsWith(".d.ts")),
16
+ ),
17
+ root,
18
+ outdir: "dist",
19
+ target: "node",
20
+ format: "esm",
21
+ packages: "external",
22
+ splitting: true,
23
+ naming: {
24
+ entry: "[dir]/[name].[ext]",
25
+ chunk: "chunks/[name]-[hash].[ext]",
26
+ },
27
+ })
28
+ if (!result.success) throw new AggregateError(result.logs, "Failed to build SDK")
package/script/pack.ts ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env bun
2
+ import path from "node:path"
3
+ import { pack } from "@zyro-sec/script/pack"
4
+
5
+ await pack(path.resolve(import.meta.dir, ".."))
@@ -0,0 +1,252 @@
1
+ #!/usr/bin/env bun
2
+
3
+ import { $ } from "bun"
4
+ import { mkdtemp, rm } from "node:fs/promises"
5
+ import { tmpdir } from "node:os"
6
+ import { join } from "node:path"
7
+ import { fileURLToPath } from "node:url"
8
+
9
+ const root = fileURLToPath(new URL("../../..", import.meta.url))
10
+ const names = [
11
+ "schema",
12
+ "codemode",
13
+ "ai",
14
+ "util",
15
+ "protocol",
16
+ "client",
17
+ "plugin",
18
+ "plugin-browser",
19
+ "core",
20
+ "simulation",
21
+ "server",
22
+ "sdk",
23
+ ]
24
+ const temporary = await mkdtemp(join(tmpdir(), "opencode-sdk-package-"))
25
+ const archives = new Map<string, string>()
26
+
27
+ try {
28
+ for (const name of names) {
29
+ const directory = join(root, "packages", name)
30
+ await $`bun run build`.cwd(directory)
31
+ const original = await Bun.file(join(directory, "package.json")).text()
32
+ // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion -- package manifests are validated by their package builds.
33
+ const pkg = JSON.parse(original) as {
34
+ name: string
35
+ dependencies?: Record<string, string>
36
+ exports?: Record<string, string | { types: string; import: string }>
37
+ imports?: Record<string, Record<string, string>>
38
+ }
39
+ const archive = join(temporary, `${name}.tgz`)
40
+
41
+ if (pkg.dependencies) {
42
+ const unpacked = Object.entries(pkg.dependencies)
43
+ .filter(([dependency, version]) => version.startsWith("workspace:") && !archives.has(dependency))
44
+ .map(([dependency]) => dependency)
45
+ if (unpacked.length > 0)
46
+ throw new Error(`${pkg.name} has unpacked workspace dependencies: ${unpacked.join(", ")}`)
47
+ pkg.dependencies = Object.fromEntries(
48
+ Object.entries(pkg.dependencies).map(([dependency, version]) => {
49
+ const local = archives.get(dependency)
50
+ return [dependency, local ? `file:${local}` : version]
51
+ }),
52
+ )
53
+ }
54
+ if (pkg.exports) {
55
+ pkg.exports = Object.fromEntries(
56
+ Object.entries(pkg.exports).map(([key, value]) => {
57
+ if (typeof value !== "string") return [key, value]
58
+ return [key, { types: output(name, value, true), import: output(name, value) }]
59
+ }),
60
+ )
61
+ }
62
+ if (pkg.imports) {
63
+ pkg.imports = Object.fromEntries(
64
+ Object.entries(pkg.imports).map(([key, conditions]) => [
65
+ key,
66
+ Object.fromEntries(
67
+ Object.entries(conditions).map(([condition, value]) => [
68
+ condition,
69
+ output(name, value, condition === "types"),
70
+ ]),
71
+ ),
72
+ ]),
73
+ )
74
+ }
75
+
76
+ await Bun.write(join(directory, "package.json"), JSON.stringify(pkg, null, 2) + "\n")
77
+ try {
78
+ await $`bun pm pack --filename ${archive} --ignore-scripts --quiet`.cwd(directory)
79
+ } finally {
80
+ await Bun.write(join(directory, "package.json"), original)
81
+ }
82
+ archives.set(pkg.name, archive)
83
+ }
84
+
85
+ const consumer = join(temporary, "consumer")
86
+ await Bun.write(
87
+ join(consumer, "package.json"),
88
+ JSON.stringify({ name: "opencode-sdk-consumer", private: true, type: "module" }),
89
+ )
90
+ await Promise.all([
91
+ Bun.write(
92
+ join(consumer, "wrangler.jsonc"),
93
+ JSON.stringify({
94
+ name: "opencode-sdk-packed-consumer",
95
+ main: "worker.js",
96
+ compatibility_date: "2026-07-15",
97
+ compatibility_flags: ["nodejs_compat"],
98
+ durable_objects: { bindings: [{ name: "OPENCODE", class_name: "OpenCodeDO" }] },
99
+ migrations: [{ tag: "v1", new_sqlite_classes: ["OpenCodeDO"] }],
100
+ }),
101
+ ),
102
+ Bun.write(
103
+ join(consumer, "worker.js"),
104
+ `import { bodyDigest } from "@zyro-sec/core/models-dev"
105
+ import { OpenCodeWorkerd } from "@zyro-sec/sdk/workerd"
106
+
107
+ export class OpenCodeDO {
108
+ constructor(state) {
109
+ this.configurations = 0
110
+ this.opencode = state.blockConcurrencyWhile(() => OpenCodeWorkerd.create({
111
+ storage: state.storage,
112
+ app: { version: "packed-workerd" },
113
+ models: { fetch: false },
114
+ instances: {
115
+ key: session => String(session.metadata.thread),
116
+ configure: key => {
117
+ this.configurations++
118
+ return {
119
+ plugins: [{
120
+ id: "packed-instance",
121
+ async setup(ctx) {
122
+ if (ctx.app.version !== "packed-workerd" || ctx.location.directory !== "/workspace") {
123
+ throw new Error("Selected instance did not inherit the host configuration")
124
+ }
125
+ await ctx.session.hook("prompt", event => {
126
+ event.prompt.text += ":" + key
127
+ })
128
+ },
129
+ }],
130
+ }
131
+ },
132
+ },
133
+ }))
134
+ }
135
+
136
+ async fetch() {
137
+ if (bodyDigest("packed-workerd") !== "5fc174bf63e8dd108ebb6c53d85e7bbc4525b2f4c1c43280364cdbfd9b37aaf5") {
138
+ throw new Error("Packed workerd SHA-256 mismatch")
139
+ }
140
+ const opencode = await this.opencode
141
+ const sessions = await Promise.all([1, 2].map(() => opencode.sessions.create({
142
+ location: { directory: "/workspace" },
143
+ metadata: { thread: "packed-thread" },
144
+ })))
145
+ const admitted = await Promise.all(sessions.map(session => opencode.sessions.prompt({
146
+ sessionID: session.id,
147
+ text: "Packed prompt",
148
+ resume: false,
149
+ })))
150
+ if (this.configurations !== 1 || admitted.some(item => item.payload.text !== "Packed prompt:packed-thread")) {
151
+ throw new Error("Packed instance configuration did not share or prepare prompts correctly")
152
+ }
153
+ await opencode.alarm()
154
+ return Response.json(await opencode.server.info())
155
+ }
156
+
157
+ async alarm() {
158
+ const opencode = await this.opencode
159
+ await opencode.alarm()
160
+ }
161
+ }
162
+
163
+ export default {
164
+ fetch(request, env) {
165
+ return env.OPENCODE.get(env.OPENCODE.idFromName("packed-consumer")).fetch(request)
166
+ },
167
+ }
168
+ `,
169
+ ),
170
+ Bun.write(
171
+ join(consumer, "boot.mjs"),
172
+ `import { Miniflare } from "miniflare"
173
+ import { fileURLToPath } from "node:url"
174
+
175
+ const miniflare = new Miniflare({
176
+ compatibilityDate: "2026-07-15",
177
+ compatibilityFlags: ["nodejs_compat"],
178
+ modules: true,
179
+ scriptPath: fileURLToPath(new URL("./dist/worker.js", import.meta.url)),
180
+ durableObjects: { OPENCODE: { className: "OpenCodeDO", useSQLite: true } },
181
+ })
182
+
183
+ try {
184
+ const response = await miniflare.dispatchFetch("http://opencode.local/health")
185
+ if (response.status !== 200) throw new Error(
186
+ "Packed workerd health returned " + response.status + ": " + await response.text(),
187
+ )
188
+ const body = await response.json()
189
+ if (body.version !== "packed-workerd" || body.pid !== 1 || !Array.isArray(body.urls)) {
190
+ throw new Error("Unexpected packed workerd health: " + JSON.stringify(body))
191
+ }
192
+ } finally {
193
+ await miniflare.dispose()
194
+ }
195
+ `,
196
+ ),
197
+ Bun.write(
198
+ join(consumer, "imports.mjs"),
199
+ `const modules = await Promise.all([
200
+ import("@zyro-sec/sdk"),
201
+ import("@zyro-sec/sdk/effect"),
202
+ import("@zyro-sec/sdk/workerd"),
203
+ import("@zyro-sec/sdk/workerd/effect"),
204
+ ])
205
+
206
+ for (const module of modules) {
207
+ const api = module.OpenCode ?? module.OpenCodeWorkerd
208
+ if (typeof api?.create !== "function") throw new Error("Packed SDK entrypoint is missing create()")
209
+ }
210
+ `,
211
+ ),
212
+ ])
213
+
214
+ const sdk = archives.get("@zyro-sec/sdk")
215
+ if (!sdk) throw new Error("Packed SDK archive was not created")
216
+ await $`npm install --ignore-scripts --no-audit --no-fund --package-lock=false ${sdk} wrangler@4.110.0`.cwd(consumer)
217
+ const runtimes = (await $`npm ls effect --all --parseable`.cwd(consumer).text()).trim().split("\n")
218
+ if (runtimes.length !== 1) {
219
+ throw new Error(`Packed SDK consumer resolved multiple Effect runtimes:\n${runtimes.join("\n")}`)
220
+ }
221
+ await $`bun imports.mjs`.cwd(consumer)
222
+ await $`node imports.mjs`.cwd(consumer)
223
+ await $`bun --conditions=workerd imports.mjs`.cwd(consumer)
224
+ await $`node_modules/.bin/wrangler deploy --dry-run --config wrangler.jsonc --outdir dist`.cwd(consumer)
225
+
226
+ const transpiler = new Bun.Transpiler({ loader: "js" })
227
+ const bundled = await Bun.file(join(consumer, "dist/worker.js")).text()
228
+ // Quoted strings are skipped: an error message naming `Bun.write` isn't a reference to the global.
229
+ const code = bundled.replace(/"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'/g, '""')
230
+ const bunGlobals = Array.from(new Set(code.match(/\bBun\.[A-Za-z_$][\w$]*/g) ?? []))
231
+ if (bunGlobals.length > 0) throw new Error(`Packed workerd bundle references Bun globals: ${bunGlobals.join(", ")}`)
232
+ const leaked = [
233
+ ...transpiler
234
+ .scanImports(bundled)
235
+ .filter((imported) => imported.kind !== "dynamic-import")
236
+ .map((imported) => imported.path),
237
+ ...Array.from(bundled.matchAll(/\brequire\(\s*["']([^"']+)["']\s*\)/g), (match) => match[1]),
238
+ ].filter((specifier) => specifier === "bun" || specifier.startsWith("bun:"))
239
+ if (leaked.length > 0) throw new Error(`Packed workerd bundle statically imports Bun builtins: ${leaked.join(", ")}`)
240
+
241
+ // Boot in workerd to catch eager Node initializers; lazy createRequire calls
242
+ // in native-only code are valid and must not fail a bundle-wide text check.
243
+ await $`node boot.mjs`.cwd(consumer)
244
+ console.log("packed SDK consumer OK")
245
+ } finally {
246
+ await rm(temporary, { recursive: true, force: true })
247
+ }
248
+
249
+ function output(name: string, value: string, types = false) {
250
+ const root = name === "core" && types ? "./dist/types/" : "./dist/"
251
+ return value.replace("./src/", root).replace(/\.ts$/, types ? ".d.ts" : ".js")
252
+ }
@@ -0,0 +1,26 @@
1
+ export { Agent } from "@zyro-sec/schema/agent"
2
+ export { Command } from "@zyro-sec/schema/command"
3
+ export { Config } from "@zyro-sec/schema/config"
4
+ export { Credential } from "@zyro-sec/schema/credential"
5
+ export { Event } from "@zyro-sec/schema/event"
6
+ export { FileSystem } from "@zyro-sec/schema/filesystem"
7
+ export { Integration } from "@zyro-sec/schema/integration"
8
+ export { Location } from "@zyro-sec/schema/location"
9
+ export { Model } from "@zyro-sec/schema/model"
10
+ export { Permission } from "@zyro-sec/schema/permission"
11
+ export { PermissionSaved } from "@zyro-sec/schema/permission-saved"
12
+ export { Project } from "@zyro-sec/schema/project"
13
+ export { Worktree } from "@zyro-sec/schema/worktree"
14
+ export { Prompt } from "@zyro-sec/schema/prompt"
15
+ export { PromptInput } from "@zyro-sec/schema/prompt-input"
16
+ export { Provider } from "@zyro-sec/schema/provider"
17
+ export { Pty } from "@zyro-sec/schema/pty"
18
+ export { Question } from "@zyro-sec/schema/question"
19
+ export { Reference } from "@zyro-sec/schema/reference"
20
+ export { WebSearch } from "@zyro-sec/schema/websearch"
21
+ export { AbsolutePath, RelativePath } from "@zyro-sec/schema/schema"
22
+ export { Session } from "@zyro-sec/schema/session"
23
+ export { SessionInbox } from "@zyro-sec/schema/session-inbox"
24
+ export { SessionMessage } from "@zyro-sec/schema/session-message"
25
+ export { Skill } from "@zyro-sec/schema/skill"
26
+ export { Workspace } from "@zyro-sec/schema/workspace"
@@ -0,0 +1,11 @@
1
+ export * as OpenCode from "./opencode"
2
+ export * as Tool from "./tool"
3
+ export { EnvironmentDriver } from "@zyro-sec/core/environment/driver"
4
+ export { EnvironmentFiles } from "@zyro-sec/core/environment/files"
5
+ export { Identity } from "@zyro-sec/core/machine/identity"
6
+ export { WorkerClient } from "@zyro-sec/core/machine/worker-client"
7
+ export { WorkspaceDriver } from "@zyro-sec/core/workspace/driver"
8
+
9
+ export { ClientError } from "@zyro-sec/client/effect"
10
+ export type { OpenCodeEvent } from "@zyro-sec/client/effect"
11
+ export * from "../contracts"
@@ -0,0 +1,78 @@
1
+ export * as OpenCode from "./opencode"
2
+
3
+ import { OpenCode, type OpenCodeClient } from "@zyro-sec/client/effect"
4
+ import type { Session } from "@zyro-sec/core/session"
5
+ import type { Workspace } from "@zyro-sec/core/workspace"
6
+ import { Context, Effect, Layer } from "effect"
7
+ import type { Config, Scope } from "effect"
8
+ import { FetchHttpClient, HttpClient } from "effect/http"
9
+ import { EmbeddedHost } from "../internal/host"
10
+ import type { SdkInstances } from "../internal/instances"
11
+
12
+ export type { LogEntry, LogLevel, LogOptions, LogWriter } from "../logging"
13
+
14
+ export type CreateOptions<R = never> = EmbeddedHost.CreateOptions<R>
15
+ export type EmbedOptions = EmbeddedHost.EmbedOptions
16
+ export type InstanceOptions<R = never> = SdkInstances.Options<R>
17
+ export type InstanceConfiguration = SdkInstances.Configuration
18
+
19
+ export type Interface = Omit<OpenCodeClient, "plugin" | "workspace"> & {
20
+ readonly sessions: Omit<OpenCodeClient["session"], "create" | "get" | "move"> & {
21
+ readonly create: Session.Interface["create"]
22
+ readonly get: (input: { readonly sessionID: Session.ID }) => ReturnType<Session.Interface["get"]>
23
+ readonly move: Session.Interface["move"]
24
+ }
25
+ readonly events: OpenCodeClient["event"]
26
+ readonly workspace: {
27
+ readonly create: Workspace.Interface["create"]
28
+ readonly attach: Workspace.Interface["attach"]
29
+ readonly provision: (options: {
30
+ readonly workspaceID: Workspace.ID
31
+ }) => ReturnType<Workspace.Interface["provision"]>
32
+ readonly destroy: (options: { readonly workspaceID: Workspace.ID }) => ReturnType<Workspace.Interface["destroy"]>
33
+ readonly suspendIdle: Workspace.Interface["suspendIdle"]
34
+ }
35
+ readonly plugin: EmbeddedHost.Interface["plugins"]["register"] & OpenCodeClient["plugin"]
36
+ }
37
+
38
+ export const create: <R = never>(
39
+ options?: CreateOptions<R>,
40
+ embed?: EmbedOptions,
41
+ ) => Effect.Effect<Interface, Config.ConfigError | Error, Scope.Scope | R> = Effect.fn("OpenCode.create")(function* <
42
+ R = never,
43
+ >(options: CreateOptions<R> = {}, embed: EmbedOptions = {}) {
44
+ const host = yield* Effect.acquireRelease(EmbeddedHost.create(options, embed), (host) => Effect.promise(host.close))
45
+ const httpClient = yield* HttpClient.HttpClient.pipe(Effect.provide(FetchHttpClient.layer))
46
+ const client = yield* OpenCode.make({ baseUrl: "http://opencode.local" }).pipe(
47
+ Effect.provideService(
48
+ HttpClient.HttpClient,
49
+ // FetchHttpClient reads Fetch at request time; callers must not replace this host's in-process transport.
50
+ HttpClient.transformResponse(httpClient, Effect.provideService(FetchHttpClient.Fetch, host.fetch)),
51
+ ),
52
+ )
53
+
54
+ return {
55
+ ...client,
56
+ sessions: {
57
+ ...client.session,
58
+ create: host.sessions.create,
59
+ get: (input: { readonly sessionID: Session.ID }) => host.sessions.get(input.sessionID),
60
+ move: host.sessions.move,
61
+ },
62
+ events: client.event,
63
+ workspace: {
64
+ create: host.workspace.create,
65
+ attach: host.workspace.attach,
66
+ provision: ({ workspaceID }: { readonly workspaceID: Workspace.ID }) => host.workspace.provision(workspaceID),
67
+ destroy: ({ workspaceID }: { readonly workspaceID: Workspace.ID }) => host.workspace.destroy(workspaceID),
68
+ suspendIdle: host.workspace.suspendIdle,
69
+ },
70
+ plugin: Object.assign(host.plugins.register, client.plugin),
71
+ }
72
+ })
73
+
74
+ export class Service extends Context.Service<Service, Interface>()("@zyro-sec/sdk/OpenCode") {}
75
+
76
+ export const layer = <R = never>(
77
+ options: CreateOptions<R> = {},
78
+ ): Layer.Layer<Service, Config.ConfigError | Error, Exclude<R, Scope.Scope>> => Layer.effect(Service, create(options))
@@ -0,0 +1,3 @@
1
+ export { RegistrationError } from "@zyro-sec/core/tool"
2
+ export { Error } from "@zyro-sec/schema/tool"
3
+ export type { Context, Info } from "@zyro-sec/schema/tool"
@@ -0,0 +1,48 @@
1
+ export * as OpenCodeWorkerd from "./workerd"
2
+
3
+ import { Effect, Layer } from "effect"
4
+ import type { Config, Scope } from "effect"
5
+ import { WorkerdProfile } from "../internal/workerd"
6
+ import { OpenCode } from "./opencode"
7
+
8
+ export type Configuration = WorkerdProfile.Configuration
9
+
10
+ export interface CreateOptions<R = never> extends WorkerdProfile.Options {
11
+ readonly log?: OpenCode.CreateOptions["log"]
12
+ readonly plugins?: OpenCode.CreateOptions["plugins"]
13
+ readonly workspaceProviders?: OpenCode.CreateOptions["workspaceProviders"]
14
+ readonly instances?: OpenCode.CreateOptions<R>["instances"]
15
+ }
16
+
17
+ export type Interface = OpenCode.Interface & {
18
+ /** Suspends any workspaces past their idle threshold; run from the Durable Object's `alarm()` method. */
19
+ readonly alarm: Effect.Effect<void>
20
+ }
21
+
22
+ export const create = <R = never>(
23
+ options: CreateOptions<R>,
24
+ ): Effect.Effect<Interface, Config.ConfigError | Error, Scope.Scope | R> => {
25
+ const profile = WorkerdProfile.make(options)
26
+ return OpenCode.create(
27
+ {
28
+ ...profile.options,
29
+ log: options.log,
30
+ plugins: options.plugins,
31
+ workspaceProviders: options.workspaceProviders,
32
+ instances: options.instances,
33
+ },
34
+ { overrides: profile.replacements },
35
+ ).pipe(
36
+ Effect.map((opencode) => ({
37
+ ...opencode,
38
+ alarm: Effect.asVoid(opencode.workspace.suspendIdle()),
39
+ })),
40
+ )
41
+ }
42
+
43
+ export const layer = <R = never>(
44
+ options: CreateOptions<R>,
45
+ ): Layer.Layer<OpenCode.Service, Config.ConfigError | Error, Exclude<R, Scope.Scope>> =>
46
+ Layer.effect(OpenCode.Service, create(options))
47
+
48
+ export type Requirements = Scope.Scope
package/src/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ export * as OpenCode from "./opencode"
2
+ export * as Tool from "./tool"
3
+
4
+ export { ClientError } from "@zyro-sec/client"
5
+ export type { OpenCodeEvent } from "@zyro-sec/client"
6
+ export * from "./contracts"
@@ -0,0 +1,117 @@
1
+ export * as OwnedFetch from "./fetch"
2
+
3
+ export function make(handler: (request: Request) => Promise<Response>, dispose: () => Promise<void>) {
4
+ const requests = new Map<AbortController, Promise<void>>()
5
+ const closed = new Error("OpenCode host is closed")
6
+ let closePromise: Promise<void> | undefined
7
+ const fetch = Object.assign(
8
+ (input: RequestInfo | URL, init?: RequestInit) => {
9
+ if (closePromise) return Promise.reject(closed)
10
+ const source = new Request(input, init)
11
+ if (source.signal.aborted) return Promise.reject(source.signal.reason)
12
+ const controller = new AbortController()
13
+ const abort = () => controller.abort(source.signal.reason)
14
+ source.signal.addEventListener("abort", abort, { once: true })
15
+ const request = new Request(source, { signal: controller.signal })
16
+ const lifetime = Promise.withResolvers<void>()
17
+ const finish = () => {
18
+ source.signal.removeEventListener("abort", abort)
19
+ requests.delete(controller)
20
+ lifetime.resolve()
21
+ }
22
+ requests.set(controller, lifetime.promise)
23
+
24
+ const handled = handler(request)
25
+ return rejectOnAbort(handled, request.signal).then(
26
+ (response) => trackResponse(response, request.signal, finish),
27
+ (cause) => {
28
+ void handled.then(finish, finish)
29
+ throw cause
30
+ },
31
+ )
32
+ },
33
+ { preconnect: () => undefined },
34
+ ) satisfies typeof globalThis.fetch
35
+ const close = () => {
36
+ if (closePromise) return closePromise
37
+ closePromise = Promise.resolve().then(async () => {
38
+ requests.forEach((_, controller) => controller.abort(closed))
39
+ await Promise.allSettled(requests.values())
40
+ await dispose()
41
+ })
42
+ return closePromise
43
+ }
44
+ return { fetch, close }
45
+ }
46
+
47
+ function rejectOnAbort<A>(promise: Promise<A>, signal: AbortSignal): Promise<A> {
48
+ if (signal.aborted) return Promise.reject(signal.reason)
49
+ return new Promise((resolve, reject) => {
50
+ const abort = () => reject(signal.reason)
51
+ signal.addEventListener("abort", abort, { once: true })
52
+ promise.then(
53
+ (value) => {
54
+ signal.removeEventListener("abort", abort)
55
+ resolve(value)
56
+ },
57
+ (cause) => {
58
+ signal.removeEventListener("abort", abort)
59
+ reject(cause)
60
+ },
61
+ )
62
+ })
63
+ }
64
+
65
+ function trackResponse(response: Response, signal: AbortSignal, finish: () => void): Response {
66
+ if (!response.body) {
67
+ finish()
68
+ return response
69
+ }
70
+
71
+ const reader = response.body.getReader()
72
+ let done = false
73
+ let abort = () => {}
74
+ const complete = () => {
75
+ if (done) return false
76
+ done = true
77
+ signal.removeEventListener("abort", abort)
78
+ return true
79
+ }
80
+ const body = new ReadableStream<Uint8Array>({
81
+ start(controller) {
82
+ abort = () => {
83
+ if (!complete()) return
84
+ controller.error(signal.reason)
85
+ void reader.cancel(signal.reason).then(finish, finish)
86
+ }
87
+ if (signal.aborted) abort()
88
+ else signal.addEventListener("abort", abort, { once: true })
89
+ },
90
+ async pull(controller) {
91
+ try {
92
+ const next = await reader.read()
93
+ if (done) return
94
+ if (!next.done) {
95
+ controller.enqueue(next.value)
96
+ return
97
+ }
98
+ if (!complete()) return
99
+ controller.close()
100
+ finish()
101
+ } catch (cause) {
102
+ if (!complete()) return
103
+ controller.error(cause)
104
+ finish()
105
+ }
106
+ },
107
+ async cancel(reason) {
108
+ if (!complete()) return
109
+ try {
110
+ await reader.cancel(reason)
111
+ } finally {
112
+ finish()
113
+ }
114
+ },
115
+ })
116
+ return new Response(body, response)
117
+ }