@zyro-sec/sdk 0.0.0-stage → 1.0.1
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/README.md +147 -2
- package/package.json +39 -4
- package/script/build.ts +28 -0
- package/script/pack.ts +5 -0
- package/script/verify-package.ts +252 -0
- package/src/contracts.ts +26 -0
- package/src/effect/index.ts +11 -0
- package/src/effect/opencode.ts +78 -0
- package/src/effect/tool.ts +3 -0
- package/src/effect/workerd.ts +48 -0
- package/src/index.ts +6 -0
- package/src/internal/fetch.ts +117 -0
- package/src/internal/host.ts +73 -0
- package/src/internal/instances.ts +107 -0
- package/src/internal/workerd.ts +21 -0
- package/src/logging.ts +76 -0
- package/src/opencode.ts +10 -0
- package/src/promise.ts +85 -0
- package/src/tool.ts +3 -0
- package/src/workerd.ts +51 -0
- package/test/contract-identity.test.ts +114 -0
- package/test/embedded.test.ts +748 -0
- package/test/import-boundaries.test.ts +40 -0
- package/test/instances-effect.test.ts +302 -0
- package/test/instances-lifecycle.test.ts +66 -0
- package/test/instances.test.ts +389 -0
- package/test/logging.test.ts +20 -0
- package/test/promise.test.ts +66 -0
- package/test/request-retention.test.ts +133 -0
- package/test/transport.test.ts +70 -0
- package/test/worktree.test.ts +65 -0
- package/tsconfig.build.json +15 -0
- package/tsconfig.json +11 -0
package/README.md
CHANGED
|
@@ -1,3 +1,148 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @zyro-sec/sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
In-process OpenCode host for Promise and Effect applications. The SDK executes Server's assembled HTTP router in memory, opening no listener and adding no network hop.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { OpenCode } from "@zyro-sec/sdk"
|
|
7
|
+
|
|
8
|
+
await using opencode = await OpenCode.create()
|
|
9
|
+
const session = await opencode.sessions.create({
|
|
10
|
+
location: { directory: "/workspace" },
|
|
11
|
+
})
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
Pass imported Promise plugins in `plugins`, or register one later with `await opencode.plugin(plugin)`.
|
|
15
|
+
|
|
16
|
+
The Promise API uses the same values, errors, request options, and `AsyncIterable` streams as `@zyro-sec/client`.
|
|
17
|
+
|
|
18
|
+
Embedded hosts are silent by default. Set `log` to receive structured log entries:
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
await using opencode = await OpenCode.create({
|
|
22
|
+
log: {
|
|
23
|
+
level: "warn",
|
|
24
|
+
emit: (entry) => console.error(entry.message, entry.attributes, entry.cause),
|
|
25
|
+
},
|
|
26
|
+
})
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
`close()` and `Symbol.asyncDispose` release router resources, Location services, fibers, and scoped plugin registrations.
|
|
30
|
+
|
|
31
|
+
## Session-Selected Plugins
|
|
32
|
+
|
|
33
|
+
Use `instances` when Sessions in the same directory need different application plugins. The application selects a stable key from Session metadata; the SDK constructs and caches an instance for that key and the Session's current Location.
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import { OpenCode } from "@zyro-sec/sdk"
|
|
37
|
+
import { threads } from "./threads"
|
|
38
|
+
import { slackPlugin } from "./slack-plugin"
|
|
39
|
+
|
|
40
|
+
await using opencode = await OpenCode.create({
|
|
41
|
+
database: { path: "./sessions.db" },
|
|
42
|
+
instances: {
|
|
43
|
+
key(session) {
|
|
44
|
+
const threadID = session.metadata?.threadID
|
|
45
|
+
if (typeof threadID !== "string") throw new Error("Session has no thread ID")
|
|
46
|
+
return threadID
|
|
47
|
+
},
|
|
48
|
+
configure: async (threadID) => ({
|
|
49
|
+
plugins: [slackPlugin(await threads.get(threadID))],
|
|
50
|
+
}),
|
|
51
|
+
},
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
const session = await opencode.sessions.create({
|
|
55
|
+
location: { directory: "/workspace" },
|
|
56
|
+
metadata: { threadID: "thread-42" },
|
|
57
|
+
})
|
|
58
|
+
await opencode.sessions.prompt({ sessionID: session.id, text: "Review the changes" })
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
`threads` and `slackPlugin` are application-owned modules. `key` is synchronous and should only select identity, not initialize plugins. `configure` returns plugin definitions; their setup receives the selected instance's `ctx.location`.
|
|
62
|
+
|
|
63
|
+
- The same key and Location share one live instance. Different directories or workspace IDs always select separate instances, even with the same application key.
|
|
64
|
+
- `configure` runs on a cache miss, not on each prompt. Loaded instances live until the host closes; change the application key or restart the host to reconstruct their birth configuration. Plugin transforms and reloads remain available within that lifetime.
|
|
65
|
+
- Session metadata, message, inbox, and context reads do not initialize plugins; permission and form lists read instance services and therefore acquire the Session's instance. Configuration failure or a supplied plugin reported as failed after activation, including initial setup failure or an ID that collides with a host `plugins` entry (the host plugin keeps the ID), prevents capability acquisition, without falling back to another instance. A subsequent request can retry a failed construction.
|
|
66
|
+
- Existing HTTP prompt middleware also acquires capabilities for an idempotent retry. After restart, that retry can reconstruct plugins before returning the original admission; prompt preparation and hooks do not rerun. Configuration failure can therefore block the retry even when its input was already saved.
|
|
67
|
+
- Instance selection is not an authorization or storage-isolation boundary. Plugin Session APIs and the existing plugin-ID-based durable storage retain their normal scope.
|
|
68
|
+
- Omitting `instances` preserves default Location sharing. Host-wide plugins remain separate from Session-selected configuration; retain host-wide catalog policy when locationless generation needs it.
|
|
69
|
+
|
|
70
|
+
### Restart and Lifetime
|
|
71
|
+
|
|
72
|
+
The selector is installed before automatic recovery starts. Its callbacks must be able to load application data without depending on the returned `opencode` handle or a later registration call. Functions are reconstructed, not serialized.
|
|
73
|
+
|
|
74
|
+
Use a persistent `database.path` to recover Sessions after restart; the default database is in memory. Workerd uses its injected Durable Object storage. After restart, the next capability-dependent operation or recovery drain rebuilds the selected instance from saved Session metadata and application data.
|
|
75
|
+
|
|
76
|
+
Promise plugin resources should be acquired in `setup` and released by its cleanup function. Effect configuration can acquire resources in its supplied instance Scope and require services provided to the SDK entrypoint (see the Effect section).
|
|
77
|
+
|
|
78
|
+
## Workerd
|
|
79
|
+
|
|
80
|
+
Use the Workerd entrypoint inside a Cloudflare Durable Object. Hold one host for the lifetime of the object instance rather than creating one per request.
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
import { OpenCodeWorkerd } from "@zyro-sec/sdk/workerd"
|
|
84
|
+
import myPlugin from "./my-plugin"
|
|
85
|
+
|
|
86
|
+
export class OpenCodeDO {
|
|
87
|
+
private readonly opencode: Promise<OpenCodeWorkerd.Interface>
|
|
88
|
+
|
|
89
|
+
constructor(state: DurableObjectState) {
|
|
90
|
+
this.opencode = state.blockConcurrencyWhile(() =>
|
|
91
|
+
OpenCodeWorkerd.create({
|
|
92
|
+
storage: state.storage,
|
|
93
|
+
config: { default_agent: "build" },
|
|
94
|
+
plugins: [myPlugin],
|
|
95
|
+
}),
|
|
96
|
+
)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async fetch() {
|
|
100
|
+
const opencode = await this.opencode
|
|
101
|
+
return Response.json(await opencode.server.info())
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async alarm() {
|
|
105
|
+
const opencode = await this.opencode
|
|
106
|
+
await opencode.alarm()
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
`blockConcurrencyWhile` keeps every Durable Object event out until the host is ready and resets the object if initialization fails. The retained Promise gives request handlers direct access to the same host after startup. Configuration is a typed JavaScript object, and plugins are imported values bundled with the Worker.
|
|
112
|
+
|
|
113
|
+
## Effect
|
|
114
|
+
|
|
115
|
+
The Effect-native API remains available from `@zyro-sec/sdk/effect`:
|
|
116
|
+
|
|
117
|
+
```ts
|
|
118
|
+
import { OpenCode } from "@zyro-sec/sdk/effect"
|
|
119
|
+
|
|
120
|
+
const opencode = yield * OpenCode.create()
|
|
121
|
+
const session = yield * opencode.sessions.get({ sessionID })
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
The Effect Workerd entrypoint is `@zyro-sec/sdk/workerd/effect` (forward the Durable Object's `alarm()` method to `opencode.alarm`, or `opencode.workspace.suspendIdle()` when consuming `OpenCodeWorkerd.layer`).
|
|
125
|
+
|
|
126
|
+
Effect configuration uses the same keys and lifetime rules, with canonical `Session.Info` values and an Effect-returning factory. `configure` may require services; `OpenCode.create` and `OpenCode.layer` carry those requirements, so the application satisfies them where it builds the SDK, as with any other Effect callback:
|
|
127
|
+
|
|
128
|
+
```ts
|
|
129
|
+
import { OpenCode } from "@zyro-sec/sdk/effect"
|
|
130
|
+
import { Effect, Layer, Schema } from "effect"
|
|
131
|
+
import { Threads } from "./threads-effect"
|
|
132
|
+
import { slackPlugin } from "./slack-plugin-effect"
|
|
133
|
+
|
|
134
|
+
const threadMetadata = Schema.decodeUnknownSync(Schema.Struct({ threadID: Schema.String }))
|
|
135
|
+
const opencode = OpenCode.layer({
|
|
136
|
+
database: { path: "./sessions.db" },
|
|
137
|
+
instances: {
|
|
138
|
+
key: (session) => threadMetadata(session.metadata).threadID,
|
|
139
|
+
configure: (threadID) =>
|
|
140
|
+
Effect.gen(function* () {
|
|
141
|
+
const threads = yield* Threads
|
|
142
|
+
return { plugins: [slackPlugin(yield* threads.get(threadID))] }
|
|
143
|
+
}),
|
|
144
|
+
},
|
|
145
|
+
}).pipe(Layer.provide(Threads.layer))
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
Resources acquired in `configure` still belong to the instance, not to the Scope the SDK was built in. Both Workerd entrypoints also accept `instances`. The public `OpenCode.InstanceOptions` and `OpenCode.InstanceConfiguration` types describe the corresponding Promise or Effect callbacks.
|
package/package.json
CHANGED
|
@@ -1,6 +1,41 @@
|
|
|
1
1
|
{
|
|
2
|
+
"$schema": "https://json.schemastore.org/package.json",
|
|
3
|
+
"version": "1.0.1",
|
|
2
4
|
"name": "@zyro-sec/sdk",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/anomalyco/opencode.git",
|
|
10
|
+
"directory": "packages/sdk"
|
|
11
|
+
},
|
|
12
|
+
"publishConfig": {
|
|
13
|
+
"access": "public"
|
|
14
|
+
},
|
|
15
|
+
"scripts": {
|
|
16
|
+
"build": "bun run script/build.ts",
|
|
17
|
+
"pack": "bun run script/pack.ts",
|
|
18
|
+
"test": "bun test --timeout 5000",
|
|
19
|
+
"typecheck": "bun check --no-script -b",
|
|
20
|
+
"typecheck:tsc": "tsc -b",
|
|
21
|
+
"verify:package": "bun run script/verify-package.ts"
|
|
22
|
+
},
|
|
23
|
+
"dependencies": {
|
|
24
|
+
"@zyro-sec/client": "^1.0.1",
|
|
25
|
+
"@zyro-sec/core": "^1.0.1",
|
|
26
|
+
"@zyro-sec/plugin": "^1.0.1",
|
|
27
|
+
"@zyro-sec/schema": "^1.0.1",
|
|
28
|
+
"@zyro-sec/server": "^1.0.1",
|
|
29
|
+
"@zyro-sec/util": "^1.0.1",
|
|
30
|
+
"effect": "4.1.0"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"@zyro-sec/ai": "^1.0.1",
|
|
34
|
+
"@zyro-sec/httpapi-codegen": "^1.0.1",
|
|
35
|
+
"@zyro-sec/protocol": "^1.0.1",
|
|
36
|
+
"@tsconfig/bun": "1.0.9",
|
|
37
|
+
"@types/bun": "1.4.3",
|
|
38
|
+
"@typescript/native": "npm:typescript@7.1.0-beta"
|
|
39
|
+
},
|
|
40
|
+
"main": "src/index.ts"
|
|
41
|
+
}
|
package/script/build.ts
ADDED
|
@@ -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,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
|
+
}
|
package/src/contracts.ts
ADDED
|
@@ -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,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
|