Skip to content

Commit 4d0eb97

Browse files
authored
feat(sdk): configure session-selected instances (anomalyco#46496)
1 parent d117a33 commit 4d0eb97

15 files changed

Lines changed: 947 additions & 27 deletions

‎packages/core/src/location-service-map.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { Context, Effect, Layer, LayerMap } from "effect"
22
import { LayerNode } from "@opencode-ai/util/effect/layer-node"
33
import { Node } from "@opencode-ai/util/effect/app-node"
4+
import { AbsolutePath } from "@opencode-ai/schema/schema"
5+
import path from "path"
46
import { Location } from "./location.js"
57
import type { Instance } from "./instance.js"
68

@@ -15,4 +17,12 @@ export class Service extends Context.Service<
1517

1618
export const node = LayerNode.unbound(Service, Node.tags.values.global)
1719

20+
/** Normalize equivalent placements before they become resource-cache keys. */
21+
export function canonical(ref: Location.Ref) {
22+
return Location.Ref.make({
23+
directory: AbsolutePath.make(process.platform === "win32" ? path.normalize(ref.directory) : ref.directory),
24+
workspaceID: ref.workspaceID,
25+
})
26+
}
27+
1828
export * as LocationServiceMap from "./location-service-map.js"

‎packages/core/src/location-services.ts‎

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
import { Duration, Effect, Layer, LayerMap } from "effect"
22
import { existsSync } from "fs"
3-
import path from "path"
43
import { LayerNode } from "@opencode-ai/util/effect/layer-node"
54
import { Instance } from "./instance.js"
65
import { Location } from "./location.js"
76
import { LocationServiceMap } from "./location-service-map.js"
8-
import { AbsolutePath } from "./schema.js"
97

108
export { LocationServiceMap } from "./location-service-map.js"
119

@@ -15,13 +13,6 @@ export type LocationError = Instance.Error
1513
export function buildLocationServiceMap(
1614
replacements: LayerNode.Replacements = [],
1715
): Layer.Layer<LocationServiceMap.Service> {
18-
// Structural Equal distinguishes optional-key shape and Windows separator style.
19-
// The RcMap caches the raw key before the build callback, so normalize both here.
20-
const canonical = (ref: Location.Ref) =>
21-
Location.Ref.make({
22-
directory: AbsolutePath.make(process.platform === "win32" ? path.normalize(ref.directory) : ref.directory),
23-
workspaceID: ref.workspaceID,
24-
})
2516
return Layer.effect(
2617
LocationServiceMap.Service,
2718
Effect.gen(function* () {
@@ -35,10 +26,10 @@ export function buildLocationServiceMap(
3526
})
3627
const map = {
3728
...inner,
38-
get: (ref: Location.Ref) => inner.get(canonical(ref)),
39-
contextEffect: (ref: Location.Ref) => inner.contextEffect(canonical(ref)),
40-
contextEffectOption: (ref: Location.Ref) => inner.contextEffectOption(canonical(ref)),
41-
invalidate: (ref: Location.Ref) => inner.invalidate(canonical(ref)),
29+
get: (ref: Location.Ref) => inner.get(LocationServiceMap.canonical(ref)),
30+
contextEffect: (ref: Location.Ref) => inner.contextEffect(LocationServiceMap.canonical(ref)),
31+
contextEffectOption: (ref: Location.Ref) => inner.contextEffectOption(LocationServiceMap.canonical(ref)),
32+
invalidate: (ref: Location.Ref) => inner.invalidate(LocationServiceMap.canonical(ref)),
4233
}
4334
// Cached instances borrow their owner instead of retaining its Layer scope.
4435
const bindings: LayerNode.Replacements = [

‎packages/sdk/README.md‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,53 @@ await using opencode = await OpenCode.create({
2828

2929
`close()` and `Symbol.asyncDispose` release router resources, Location services, fibers, and scoped plugin registrations.
3030

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 "@opencode-ai/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, an instance plugin ID that collides with a host `plugins` entry, or initial setup failure of a supplied plugin 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; capture application services before creating the SDK host.
77+
3178
## Workerd
3279

3380
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.
@@ -70,3 +117,25 @@ const session = yield * opencode.sessions.get({ sessionID })
70117
```
71118

72119
The Effect Workerd entrypoint is `@opencode-ai/sdk/workerd/effect`.
120+
121+
Effect configuration uses the same keys and lifetime rules, with canonical `Session.Info` values and an Effect-returning factory:
122+
123+
```ts
124+
import { OpenCode } from "@opencode-ai/sdk/effect"
125+
import { Effect, Schema } from "effect"
126+
import { threads } from "./threads-effect"
127+
import { slackPlugin } from "./slack-plugin-effect"
128+
129+
const threadMetadata = Schema.decodeUnknownSync(Schema.Struct({ threadID: Schema.String }))
130+
const opencode =
131+
yield *
132+
OpenCode.create({
133+
database: { path: "./sessions.db" },
134+
instances: {
135+
key: (session) => threadMetadata(session.metadata).threadID,
136+
configure: (threadID) => threads.get(threadID).pipe(Effect.map((thread) => ({ plugins: [slackPlugin(thread)] }))),
137+
},
138+
})
139+
```
140+
141+
Both Workerd entrypoints also accept `instances`. The public `OpenCode.InstanceOptions` and `OpenCode.InstanceConfiguration` types describe the corresponding Promise or Effect callbacks.

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

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,9 +105,30 @@ import { OpenCodeWorkerd } from "@opencode-ai/sdk/workerd"
105105
106106
export class OpenCodeDO {
107107
constructor(state) {
108+
this.configurations = 0
108109
this.opencode = state.blockConcurrencyWhile(() => OpenCodeWorkerd.create({
109110
storage: state.storage,
110111
app: { version: "packed-workerd" },
112+
models: { fetch: false },
113+
instances: {
114+
key: session => String(session.metadata.thread),
115+
configure: key => {
116+
this.configurations++
117+
return {
118+
plugins: [{
119+
id: "packed-instance",
120+
async setup(ctx) {
121+
if (ctx.app.version !== "packed-workerd" || ctx.location.directory !== "/workspace") {
122+
throw new Error("Selected instance did not inherit the host configuration")
123+
}
124+
await ctx.session.hook("prompt", event => {
125+
event.prompt.text += ":" + key
126+
})
127+
},
128+
}],
129+
}
130+
},
131+
},
111132
}))
112133
}
113134
@@ -116,6 +137,18 @@ export class OpenCodeDO {
116137
throw new Error("Packed workerd SHA-256 mismatch")
117138
}
118139
const opencode = await this.opencode
140+
const sessions = await Promise.all([1, 2].map(() => opencode.sessions.create({
141+
location: { directory: "/workspace" },
142+
metadata: { thread: "packed-thread" },
143+
})))
144+
const admitted = await Promise.all(sessions.map(session => opencode.sessions.prompt({
145+
sessionID: session.id,
146+
text: "Packed prompt",
147+
resume: false,
148+
})))
149+
if (this.configurations !== 1 || admitted.some(item => item.payload.text !== "Packed prompt:packed-thread")) {
150+
throw new Error("Packed instance configuration did not share or prepare prompts correctly")
151+
}
119152
return Response.json(await opencode.health.get())
120153
}
121154
}

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,14 @@ import { Context, Effect, Layer } from "effect"
66
import type { Config, Scope } from "effect"
77
import { FetchHttpClient } from "effect/unstable/http"
88
import { EmbeddedHost } from "../internal/host"
9+
import type { SdkInstances } from "../internal/instances"
910

1011
export type { LogEntry, LogLevel, LogOptions, LogWriter } from "../logging"
1112

1213
export type CreateOptions = EmbeddedHost.CreateOptions
1314
export type EmbedOptions = EmbeddedHost.EmbedOptions
15+
export type InstanceOptions = SdkInstances.Options
16+
export type InstanceConfiguration = SdkInstances.Configuration
1417

1518
export type Interface = Omit<OpenCodeClient, "plugin" | "workspace"> & {
1619
readonly sessions: OpenCodeClient["session"]

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

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,15 @@ export type Configuration = WorkerdProfile.Configuration
1010
export interface CreateOptions extends WorkerdProfile.Options {
1111
readonly log?: OpenCode.CreateOptions["log"]
1212
readonly workspaceProviders?: OpenCode.CreateOptions["workspaceProviders"]
13+
readonly instances?: OpenCode.CreateOptions["instances"]
1314
}
1415

15-
export const create = ({ log, workspaceProviders, ...options }: CreateOptions) => {
16+
export const create = ({ log, workspaceProviders, instances, ...options }: CreateOptions) => {
1617
const profile = WorkerdProfile.make(options)
17-
return OpenCode.create({ ...profile.options, log, workspaceProviders }, { overrides: profile.replacements })
18+
return OpenCode.create(
19+
{ ...profile.options, log, workspaceProviders, instances },
20+
{ overrides: profile.replacements },
21+
)
1822
}
1923

2024
export const layer = (options: CreateOptions): Layer.Layer<OpenCode.Service, Config.ConfigError | Error> =>

‎packages/sdk/src/internal/host.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,12 @@ import { Context, Effect, Layer, ManagedRuntime, Scope } from "effect"
1111
import { HttpEffect, HttpRouter, HttpServer, HttpServerRequest } from "effect/unstable/http"
1212
import { context, layer, type LogOptions } from "../logging"
1313
import { OwnedFetch } from "./fetch"
14+
import { SdkInstances } from "./instances"
1415

1516
export interface CreateOptions extends Omit<ServerOptions, "hostname" | "port" | "password"> {
1617
readonly log?: LogOptions
1718
readonly workspaceProviders?: Readonly<Record<string, WorkspaceDriver.Interface>>
19+
readonly instances?: SdkInstances.Options
1820
}
1921

2022
/** Host hooks for embedding opencode on a non-default runtime profile. */
@@ -26,7 +28,7 @@ export const create = Effect.fn("EmbeddedHost.create")(function* (
2628
options: CreateOptions = {},
2729
embed: EmbedOptions = {},
2830
) {
29-
const { log, workspaceProviders, ...server } = options
31+
const { log, workspaceProviders, instances, ...server } = options
3032
const runtime = ManagedRuntime.make(
3133
createEmbeddedRoutes(
3234
{
@@ -37,6 +39,7 @@ export const create = Effect.fn("EmbeddedHost.create")(function* (
3739
workspaceProviders
3840
? [...(embed.overrides ?? []), WorkspaceDriver.node.replace(WorkspaceDriver.registryNode(workspaceProviders))]
3941
: embed.overrides,
42+
instances ? (replacements) => SdkInstances.node(instances, replacements) : undefined,
4043
).pipe(Layer.provide(HttpServer.layerServices), Layer.provideMerge(layer(log))),
4144
)
4245

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
export * as SdkInstances from "./instances"
2+
3+
import { Instance } from "@opencode-ai/core/instance"
4+
import { LocationServiceMap } from "@opencode-ai/core/location-service-map"
5+
import { Plugin } from "@opencode-ai/core/plugin"
6+
import type { InstancePlugins } from "@opencode-ai/core/plugin/instance"
7+
import { SdkPlugins } from "@opencode-ai/core/plugin/sdk"
8+
import { Location } from "@opencode-ai/schema/location"
9+
import type { Session } from "@opencode-ai/schema/session"
10+
import { makeGlobalNode } from "@opencode-ai/util/effect/app-node"
11+
import type { LayerNode } from "@opencode-ai/util/effect/layer-node"
12+
import { Duration, Effect, Layer, LayerMap, Scope } from "effect"
13+
14+
export interface Configuration {
15+
readonly plugins: InstancePlugins.List
16+
}
17+
18+
export interface Options {
19+
/** Select a sharing key within the Session's current Location. Must not initialize plugins. */
20+
readonly key: (session: Session.Info) => string
21+
/** Reconstruct configuration on a cache miss. Resources belong to the instance Scope. */
22+
readonly configure: (key: string) => Effect.Effect<Configuration, unknown, Scope.Scope>
23+
}
24+
25+
/** Replaces the host's `Instance.node`; `replacements` resolves lazily so instances inherit the final host graph. */
26+
export function node(options: Options, replacements: () => LayerNode.Replacements) {
27+
return makeGlobalNode({
28+
service: Instance.Service,
29+
layer: layer(options, replacements),
30+
deps: [LocationServiceMap.node, SdkPlugins.node],
31+
})
32+
}
33+
34+
export function layer(options: Options, replacements: () => LayerNode.Replacements) {
35+
return Layer.effect(
36+
Instance.Service,
37+
Effect.gen(function* () {
38+
const scope = yield* Effect.scope
39+
const locations = yield* LocationServiceMap.Service
40+
const sdk = yield* SdkPlugins.Service
41+
const key = (session: Session.Info) => ({
42+
key: options.key(session),
43+
...LocationServiceMap.canonical(session.location),
44+
})
45+
const provide = (session: Session.Info) => Effect.provide(instances.get(key(session)))
46+
const instances: LayerMap.LayerMap<ReturnType<typeof key>, Instance.Services> = yield* LayerMap.make(
47+
(input: ReturnType<typeof key>) =>
48+
Layer.unwrap(
49+
Effect.gen(function* () {
50+
const configuration = yield* options.configure(input.key).pipe(Effect.orDie)
51+
// A host/instance ID collision fails the whole plugin generation, which leaves no inventory
52+
// trace to check after activation. Reject it before constructing anything.
53+
const collisions = configuration.plugins.filter((plugin) =>
54+
sdk.all().some((host) => host.id === plugin.id),
55+
)
56+
if (collisions.length > 0)
57+
yield* Effect.die(
58+
new Error(
59+
`Instance plugin IDs collide with host plugins: ${collisions.map((plugin) => plugin.id).join(", ")}`,
60+
),
61+
)
62+
return Instance.layer(Location.Ref.make({ directory: input.directory, workspaceID: input.workspaceID }), {
63+
plugins: configuration.plugins,
64+
replacements: [
65+
...replacements(),
66+
// Instances borrow this selector and the host's Location map instead of retaining
67+
// their Layer scopes; retaining the selector would block its shutdown on its own entries.
68+
Instance.node.replace(Layer.succeed(Instance.Service, { provide })),
69+
LocationServiceMap.node.replace(Layer.succeed(LocationServiceMap.Service, locations)),
70+
],
71+
}).pipe(
72+
Layer.tap((context) =>
73+
Effect.gen(function* () {
74+
const plugins = yield* Plugin.Service
75+
yield* plugins.awaitActivation
76+
const failed = (yield* plugins.list()).filter(
77+
(plugin) =>
78+
plugin.state.status === "failed" &&
79+
configuration.plugins.some((configured) => configured.id === plugin.id),
80+
)
81+
if (failed.length > 0)
82+
yield* Effect.die(
83+
new Error(`Instance plugin setup failed: ${failed.map((plugin) => plugin.id).join(", ")}`),
84+
)
85+
}).pipe(Effect.provide(context)),
86+
),
87+
)
88+
}),
89+
).pipe(
90+
// Eviction can close the lookup's scope; do not make that fiber wait on itself.
91+
Layer.tapCause(() =>
92+
instances.invalidate(input).pipe(Effect.forkIn(scope, { startImmediately: true }), Effect.asVoid),
93+
),
94+
),
95+
{ idleTimeToLive: Duration.infinity },
96+
)
97+
return Instance.Service.of({ provide })
98+
}),
99+
)
100+
}

‎packages/sdk/src/opencode.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import { PromiseSdk } from "./promise"
33
export type { LogEntry, LogLevel, LogOptions, LogWriter } from "./logging"
44

55
export type CreateOptions = PromiseSdk.CreateOptions
6+
export type InstanceOptions = PromiseSdk.InstanceOptions
7+
export type InstanceConfiguration = PromiseSdk.InstanceConfiguration
68
export type Interface = PromiseSdk.Interface
79

810
export const create = (options: CreateOptions = {}) => PromiseSdk.create(options)

0 commit comments

Comments
 (0)