Skip to content

Commit c19186e

Browse files
authored
feat(sdk): add Promise-first embedded host (anomalyco#44746)
1 parent 563943c commit c19186e

21 files changed

Lines changed: 733 additions & 282 deletions

File tree

‎packages/plugin/src/promise/adapter.ts‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { Tool } from "@opencode-ai/schema/tool"
2-
import { Effect, Schema, SchemaAST, Scope, Stream } from "effect"
2+
import { Effect, Schema, SchemaAST, Stream } from "effect"
3+
import type { Scope } from "effect"
34
import { HttpApiEndpoint, HttpApiSchema } from "effect/unstable/httpapi"
45
import { define } from "../effect/plugin.js"
56
import type { Context, Plugin } from "./plugin.js"
@@ -84,12 +85,11 @@ export function fromPromise(plugin: Plugin) {
8485
const SessionEndpoints = ClientApi.groups["server.session"].endpoints
8586
const SkillEndpoints = ClientApi.groups["server.skill"].endpoints
8687
const WebSearchEndpoints = ClientApi.groups["server.websearch"].endpoints
87-
const scope = yield* Scope.Scope
8888
const context = yield* Effect.context<Scope.Scope>()
8989

9090
// Run a hook registration on the plugin scope and resolve once it is registered.
9191
const register = (effect: Effect.Effect<HostRegistration, never, Scope.Scope>): Promise<Registration> =>
92-
Effect.runPromiseWith(context)(Scope.provide(scope)(effect)).then((registration) => ({
92+
Effect.runPromiseWith(context)(effect).then((registration) => ({
9393
dispose: () => Effect.runPromiseWith(context)(registration.dispose),
9494
}))
9595

@@ -325,9 +325,10 @@ export function fromPromise(plugin: Plugin) {
325325
},
326326
}
327327

328-
const cleanup = yield* Effect.promise(() => Promise.resolve(plugin.setup(context2)))
329-
if (!cleanup) return
330-
yield* Effect.addFinalizer(() => Effect.promise(() => Promise.resolve(cleanup())))
328+
yield* Effect.acquireRelease(
329+
Effect.promise(() => Promise.resolve(plugin.setup(context2))),
330+
(cleanup) => (cleanup ? Effect.promise(() => Promise.resolve(cleanup())) : Effect.void),
331+
)
331332
}),
332333
})
333334
}

‎packages/sdk/README.md‎

Lines changed: 49 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,72 @@
11
# @opencode-ai/sdk
22

3-
Effect-native scoped OpenCode host for in-process applications.
4-
5-
The SDK executes Server's assembled HTTP router in memory. It opens no listener and performs no network I/O, while preserving the same routing, middleware, handlers, codecs, and errors as the network client.
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.
64

75
```ts
86
import { OpenCode } from "@opencode-ai/sdk"
97

10-
const opencode = yield * OpenCode.create()
11-
const session = yield * opencode.sessions.get({ sessionID })
8+
await using opencode = await OpenCode.create()
9+
const session = await opencode.sessions.create({
10+
location: { directory: "/workspace" },
11+
})
1212
```
1313

14-
It also exports `Tool` for plugins that add tools with `ctx.tool.transform(...)`. Embedded plugins run through the ordinary discovery flow and register tools into each Location's `ToolRegistry` through the normal `Tools.Service.register(...)` path. Closing the owning Effect Scope releases router resources, location services, fibers, and scoped tool registrations.
14+
Pass imported Promise plugins in `plugins`, or register one later with `await opencode.plugin(plugin)`.
1515

16-
Embedded hosts are silent by default. Set `log` to receive structured log entries at the selected minimum level:
16+
The Promise API uses the same values, errors, request options, and `AsyncIterable` streams as `@opencode-ai/client`.
17+
18+
Embedded hosts are silent by default. Set `log` to receive structured log entries:
1719

1820
```ts
19-
const opencode =
20-
yield *
21-
OpenCode.create({
22-
log: {
23-
level: "warn",
24-
emit: (entry) => console.error(entry.message, entry.attributes, entry.cause),
25-
},
26-
})
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+
})
2727
```
2828

29-
`sessions.events({ sessionID, after })` replays durable events after the optional aggregate sequence, then emits newly committed durable events. `sessions.interrupt(...)` targets execution owned by this host, and `sessions.message(...)` retrieves one projected Session message.
29+
`close()` and `Symbol.asyncDispose` release router resources, Location services, fibers, and scoped plugin registrations.
3030

31-
The same constructor is available as a service Layer:
31+
## Workerd
32+
33+
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.
3234

3335
```ts
34-
const program = Effect.gen(function* () {
35-
const opencode = yield* OpenCode.Service
36-
return yield* opencode.sessions.get({ sessionID })
37-
})
36+
import { OpenCodeWorkerd } from "@opencode-ai/sdk/workerd"
37+
import myPlugin from "./my-plugin"
3838

39-
yield * program.pipe(Effect.provide(OpenCode.layer()))
39+
export class OpenCodeDO {
40+
private readonly opencode: Promise<OpenCodeWorkerd.Interface>
41+
42+
constructor(state: DurableObjectState) {
43+
this.opencode = state.blockConcurrencyWhile(() =>
44+
OpenCodeWorkerd.create({
45+
storage: state.storage,
46+
config: { default_agent: "build" },
47+
plugins: [myPlugin],
48+
}),
49+
)
50+
}
51+
52+
async fetch() {
53+
const opencode = await this.opencode
54+
return Response.json(await opencode.health.get())
55+
}
56+
}
4057
```
4158

42-
`OpenCode.layer(options)` adapts the scoped `OpenCode.create(options)` convenience constructor for dependency injection.
59+
`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.
4360

44-
Workspace providers are host infrastructure configured when the SDK is constructed. Workspace lifecycle operations remain on the typed facade:
61+
## Effect
62+
63+
The Effect-native API remains available from `@opencode-ai/sdk/effect`:
4564

4665
```ts
47-
const opencode = yield * OpenCode.create({ workspaceProviders: { modal: modalWorkspaceProvider } })
48-
const workspace = yield * opencode.workspace.create({ provider: "modal" })
49-
yield * opencode.workspace.destroy({ workspaceID: workspace.id })
66+
import { OpenCode } from "@opencode-ai/sdk/effect"
67+
68+
const opencode = yield * OpenCode.create()
69+
const session = yield * opencode.sessions.get({ sessionID })
5070
```
71+
72+
The Effect Workerd entrypoint is `@opencode-ai/sdk/workerd/effect`.

‎packages/sdk/package.json‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@
1717
],
1818
"exports": {
1919
".": "./src/index.ts",
20-
"./workerd": "./src/workerd.ts"
20+
"./effect": "./src/effect/index.ts",
21+
"./workerd": "./src/workerd.ts",
22+
"./workerd/effect": "./src/effect/workerd.ts"
2123
},
2224
"scripts": {
2325
"build": "bun run script/build.ts",
@@ -28,6 +30,7 @@
2830
"dependencies": {
2931
"@opencode-ai/client": "workspace:*",
3032
"@opencode-ai/core": "workspace:*",
33+
"@opencode-ai/plugin": "workspace:*",
3134
"@opencode-ai/schema": "workspace:*",
3235
"@opencode-ai/server": "workspace:*",
3336
"@opencode-ai/util": "workspace:*",

‎packages/sdk/script/verify-package.ts‎

Lines changed: 46 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,19 @@ import { join } from "node:path"
77
import { fileURLToPath } from "node:url"
88

99
const root = fileURLToPath(new URL("../../..", import.meta.url))
10-
const names = ["schema", "codemode", "ai", "util", "protocol", "client", "plugin", "core", "simulation", "server", "sdk"]
10+
const names = [
11+
"schema",
12+
"codemode",
13+
"ai",
14+
"util",
15+
"protocol",
16+
"client",
17+
"plugin",
18+
"core",
19+
"simulation",
20+
"server",
21+
"sdk",
22+
]
1123
const temporary = await mkdtemp(join(tmpdir(), "opencode-sdk-package-"))
1224
const archives = new Map<string, string>()
1325

@@ -29,7 +41,8 @@ try {
2941
const unpacked = Object.keys(pkg.dependencies).filter(
3042
(dependency) => dependency.startsWith("@opencode-ai/") && !archives.has(dependency),
3143
)
32-
if (unpacked.length > 0) throw new Error(`${pkg.name} has unpacked workspace dependencies: ${unpacked.join(", ")}`)
44+
if (unpacked.length > 0)
45+
throw new Error(`${pkg.name} has unpacked workspace dependencies: ${unpacked.join(", ")}`)
3346
pkg.dependencies = Object.fromEntries(
3447
Object.entries(pkg.dependencies).map(([dependency, version]) => {
3548
const local = archives.get(dependency)
@@ -50,7 +63,10 @@ try {
5063
Object.entries(pkg.imports).map(([key, conditions]) => [
5164
key,
5265
Object.fromEntries(
53-
Object.entries(conditions).map(([condition, value]) => [condition, output(name, value, condition === "types")]),
66+
Object.entries(conditions).map(([condition, value]) => [
67+
condition,
68+
output(name, value, condition === "types"),
69+
]),
5470
),
5571
]),
5672
)
@@ -86,28 +102,21 @@ try {
86102
join(consumer, "worker.js"),
87103
`import { bodyDigest } from "@opencode-ai/core/models-dev"
88104
import { OpenCodeWorkerd } from "@opencode-ai/sdk/workerd"
89-
import { Effect } from "effect"
90105
91106
export class OpenCodeDO {
92107
constructor(state) {
93-
this.state = state
108+
this.opencode = state.blockConcurrencyWhile(() => OpenCodeWorkerd.create({
109+
storage: state.storage,
110+
app: { version: "packed-workerd" },
111+
}))
94112
}
95113
96-
fetch() {
114+
async fetch() {
97115
if (bodyDigest("packed-workerd") !== "5fc174bf63e8dd108ebb6c53d85e7bbc4525b2f4c1c43280364cdbfd9b37aaf5") {
98116
throw new Error("Packed workerd SHA-256 mismatch")
99117
}
100-
const storage = this.state.storage
101-
return Effect.runPromise(
102-
Effect.gen(function* () {
103-
const sdk = yield* OpenCodeWorkerd.create({
104-
storage,
105-
app: { version: "packed-workerd" },
106-
config: { content: "{}" },
107-
})
108-
return Response.json(yield* sdk.health.get())
109-
}).pipe(Effect.scoped),
110-
)
118+
const opencode = await this.opencode
119+
return Response.json(await opencode.health.get())
111120
}
112121
}
113122
@@ -142,13 +151,30 @@ try {
142151
} finally {
143152
await miniflare.dispose()
144153
}
154+
`,
155+
),
156+
Bun.write(
157+
join(consumer, "imports.mjs"),
158+
`const modules = await Promise.all([
159+
import("@opencode-ai/sdk"),
160+
import("@opencode-ai/sdk/effect"),
161+
import("@opencode-ai/sdk/workerd"),
162+
import("@opencode-ai/sdk/workerd/effect"),
163+
])
164+
165+
for (const module of modules) {
166+
const api = module.OpenCode ?? module.OpenCodeWorkerd
167+
if (typeof api?.create !== "function") throw new Error("Packed SDK entrypoint is missing create()")
168+
}
145169
`,
146170
),
147171
])
148172

149173
const sdk = archives.get("@opencode-ai/sdk")
150174
if (!sdk) throw new Error("Packed SDK archive was not created")
151175
await $`npm install --ignore-scripts --no-audit --no-fund --package-lock=false ${sdk} wrangler@4.110.0`.cwd(consumer)
176+
await $`bun imports.mjs`.cwd(consumer)
177+
await $`bun --conditions=workerd imports.mjs`.cwd(consumer)
152178
await $`node_modules/.bin/wrangler deploy --dry-run --config wrangler.jsonc --outdir dist`.cwd(consumer)
153179

154180
const transpiler = new Bun.Transpiler({ loader: "js" })
@@ -159,12 +185,12 @@ try {
159185
const bunGlobals = Array.from(new Set(bundled.match(/\bBun\.[A-Za-z_$][\w$]*/g) ?? []))
160186
if (bunGlobals.length > 0) throw new Error(`Packed workerd bundle references Bun globals: ${bunGlobals.join(", ")}`)
161187
const leaked = [
162-
...transpiler.scanImports(bundled)
188+
...transpiler
189+
.scanImports(bundled)
163190
.filter((imported) => imported.kind !== "dynamic-import")
164191
.map((imported) => imported.path),
165192
...Array.from(bundled.matchAll(/\brequire\(\s*["']([^"']+)["']\s*\)/g), (match) => match[1]),
166-
]
167-
.filter((specifier) => specifier === "bun" || specifier.startsWith("bun:"))
193+
].filter((specifier) => specifier === "bun" || specifier.startsWith("bun:"))
168194
if (leaked.length > 0) throw new Error(`Packed workerd bundle statically imports Bun builtins: ${leaked.join(", ")}`)
169195

170196
await $`node boot.mjs`.cwd(consumer)

‎packages/sdk/src/contracts.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
export { Agent } from "@opencode-ai/schema/agent"
2+
export { Command } from "@opencode-ai/schema/command"
3+
export { Config } from "@opencode-ai/schema/config"
4+
export { Credential } from "@opencode-ai/schema/credential"
5+
export { Event } from "@opencode-ai/schema/event"
6+
export { FileSystem } from "@opencode-ai/schema/filesystem"
7+
export { Integration } from "@opencode-ai/schema/integration"
8+
export { Location } from "@opencode-ai/schema/location"
9+
export { Model } from "@opencode-ai/schema/model"
10+
export { Permission } from "@opencode-ai/schema/permission"
11+
export { PermissionSaved } from "@opencode-ai/schema/permission-saved"
12+
export { Project } from "@opencode-ai/schema/project"
13+
export { Worktree } from "@opencode-ai/schema/worktree"
14+
export { Prompt } from "@opencode-ai/schema/prompt"
15+
export { PromptInput } from "@opencode-ai/schema/prompt-input"
16+
export { Provider } from "@opencode-ai/schema/provider"
17+
export { Pty } from "@opencode-ai/schema/pty"
18+
export { Question } from "@opencode-ai/schema/question"
19+
export { Reference } from "@opencode-ai/schema/reference"
20+
export { WebSearch } from "@opencode-ai/schema/websearch"
21+
export { AbsolutePath, RelativePath } from "@opencode-ai/schema/schema"
22+
export { Session } from "@opencode-ai/schema/session"
23+
export { SessionInbox } from "@opencode-ai/schema/session-inbox"
24+
export { SessionMessage } from "@opencode-ai/schema/session-message"
25+
export { Skill } from "@opencode-ai/schema/skill"
26+
export { Workspace } from "@opencode-ai/schema/workspace"

‎packages/sdk/src/effect/index.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
export * as OpenCode from "./opencode"
2+
export * as Tool from "./tool"
3+
4+
export { ClientError } from "@opencode-ai/client/effect"
5+
export type { OpenCodeEvent } from "@opencode-ai/client/effect"
6+
export * from "../contracts"
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
export * as OpenCode from "./opencode"
2+
3+
import { OpenCode, type OpenCodeClient } from "@opencode-ai/client/effect"
4+
import type { Workspace } from "@opencode-ai/core/workspace"
5+
import { Context, Effect, Layer } from "effect"
6+
import type { Config, Scope } from "effect"
7+
import { FetchHttpClient } from "effect/unstable/http"
8+
import { EmbeddedHost } from "../internal/host"
9+
10+
export type { LogEntry, LogLevel, LogOptions, LogWriter } from "../logging"
11+
12+
export type CreateOptions = EmbeddedHost.CreateOptions
13+
export type EmbedOptions = EmbeddedHost.EmbedOptions
14+
15+
export type Interface = Omit<OpenCodeClient, "plugin" | "workspace"> & {
16+
readonly sessions: OpenCodeClient["session"]
17+
readonly events: OpenCodeClient["event"]
18+
readonly workspace: {
19+
readonly create: (options: { readonly provider: string }) => ReturnType<Workspace.Interface["create"]>
20+
readonly provision: (options: {
21+
readonly workspaceID: Workspace.ID
22+
}) => ReturnType<Workspace.Interface["provision"]>
23+
readonly destroy: (options: { readonly workspaceID: Workspace.ID }) => ReturnType<Workspace.Interface["destroy"]>
24+
}
25+
readonly plugin: EmbeddedHost.Interface["plugins"]["register"] & OpenCodeClient["plugin"]
26+
}
27+
28+
export const create: (
29+
options?: CreateOptions,
30+
embed?: EmbedOptions,
31+
) => Effect.Effect<Interface, Config.ConfigError | Error, Scope.Scope> = Effect.fn("OpenCode.create")(function* (
32+
options: CreateOptions = {},
33+
embed: EmbedOptions = {},
34+
) {
35+
const host = yield* Effect.acquireRelease(EmbeddedHost.create(options, embed), (host) => Effect.promise(host.close))
36+
const client = yield* OpenCode.make({ baseUrl: "http://opencode.local" }).pipe(
37+
Effect.provide(
38+
FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, host.fetch)), Layer.fresh),
39+
),
40+
)
41+
42+
return {
43+
...client,
44+
sessions: client.session,
45+
events: client.event,
46+
workspace: {
47+
create: ({ provider }: { readonly provider: string }) => host.workspace.create(provider),
48+
provision: ({ workspaceID }: { readonly workspaceID: Workspace.ID }) => host.workspace.provision(workspaceID),
49+
destroy: ({ workspaceID }: { readonly workspaceID: Workspace.ID }) => host.workspace.destroy(workspaceID),
50+
},
51+
plugin: Object.assign(host.plugins.register, client.plugin),
52+
}
53+
})
54+
55+
export class Service extends Context.Service<Service, Interface>()("@opencode-ai/sdk/OpenCode") {}
56+
57+
export const layer = (options: CreateOptions = {}): Layer.Layer<Service, Config.ConfigError | Error> =>
58+
Layer.effect(Service, create(options))

‎packages/sdk/src/effect/tool.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
export { RegistrationError } from "@opencode-ai/core/tool"
2+
export { Error } from "@opencode-ai/schema/tool"
3+
export type { Context, Info } from "@opencode-ai/schema/tool"

0 commit comments

Comments
 (0)