@radheim/sdk 0.0.0-stage → 2.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +148 -3
  2. package/dist/chunks/contracts-21rejh3w.js +79 -0
  3. package/dist/chunks/contracts-4gf949th.js +14 -0
  4. package/dist/chunks/contracts-6ard325q.js +23 -0
  5. package/dist/chunks/contracts-9921d0eq.js +18 -0
  6. package/dist/chunks/contracts-9rqn6x4v.js +16 -0
  7. package/dist/chunks/contracts-9ybt1tz4.js +14 -0
  8. package/dist/chunks/contracts-d8k8mt5a.js +49 -0
  9. package/dist/chunks/contracts-f8tdk121.js +128 -0
  10. package/dist/chunks/contracts-fc2gzwgc.js +52 -0
  11. package/dist/chunks/contracts-q7txhdnb.js +25 -0
  12. package/dist/chunks/contracts-r4rmkqh9.js +44 -0
  13. package/dist/chunks/contracts-rnpbh5as.js +55 -0
  14. package/dist/chunks/contracts-v8gt2qd1.js +29 -0
  15. package/dist/contracts.d.ts +26 -0
  16. package/dist/contracts.js +58 -0
  17. package/dist/effect/index.d.ts +10 -0
  18. package/dist/effect/index.js +85 -0
  19. package/dist/effect/opencode.d.ts +55 -0
  20. package/dist/effect/opencode.js +17 -0
  21. package/dist/effect/tool.d.ts +3 -0
  22. package/dist/effect/tool.js +8 -0
  23. package/dist/effect/workerd.d.ts +34 -0
  24. package/dist/effect/workerd.js +44 -0
  25. package/dist/index.d.ts +5 -0
  26. package/dist/index.js +75 -0
  27. package/dist/internal/effect.d.ts +12 -0
  28. package/dist/internal/effect.js +14 -0
  29. package/dist/internal/fetch.d.ts +7 -0
  30. package/dist/internal/fetch.js +8 -0
  31. package/dist/internal/host.d.ts +64 -0
  32. package/dist/internal/host.js +11 -0
  33. package/dist/internal/instances.d.ts +21 -0
  34. package/dist/internal/instances.js +10 -0
  35. package/dist/internal/promise.d.ts +8 -0
  36. package/dist/internal/promise.js +12 -0
  37. package/dist/internal/workerd.d.ts +12 -0
  38. package/dist/internal/workerd.js +8 -0
  39. package/dist/logging.d.ts +14 -0
  40. package/dist/logging.js +6 -0
  41. package/dist/opencode.d.ts +31 -0
  42. package/dist/opencode.js +13 -0
  43. package/dist/tool.d.ts +3 -0
  44. package/dist/tool.js +8 -0
  45. package/dist/workerd.d.ts +51 -0
  46. package/dist/workerd.js +41 -0
  47. package/package.json +59 -4
package/README.md CHANGED
@@ -1,3 +1,148 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # @radheim/sdk
2
+
3
+ In-process radhe.im 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 { Radhe } from "@radheim/sdk"
7
+
8
+ await using opencode = await Radhe.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 `@radheim/client`.
17
+
18
+ Embedded hosts are silent by default. Set `log` to receive structured log entries:
19
+
20
+ ```ts
21
+ await using opencode = await Radhe.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 { Radhe } from "@radheim/sdk"
37
+ import { threads } from "./threads"
38
+ import { slackPlugin } from "./slack-plugin"
39
+
40
+ await using opencode = await Radhe.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 { RadheWorkerd } from "@radheim/sdk/workerd"
84
+ import myPlugin from "./my-plugin"
85
+
86
+ export class RadheDO {
87
+ private readonly opencode: Promise<RadheWorkerd.Interface>
88
+
89
+ constructor(state: DurableObjectState) {
90
+ this.opencode = state.blockConcurrencyWhile(() =>
91
+ RadheWorkerd.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 `@radheim/sdk/effect`:
116
+
117
+ ```ts
118
+ import { Radhe } from "@radheim/sdk/effect"
119
+
120
+ const opencode = yield * Radhe.create()
121
+ const session = yield * opencode.sessions.get({ sessionID })
122
+ ```
123
+
124
+ The Effect Workerd entrypoint is `@radheim/sdk/workerd/effect` (forward the Durable Object's `alarm()` method to `opencode.alarm`, or `opencode.workspace.suspendIdle()` when consuming `RadheWorkerd.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; `Radhe.create` and `Radhe.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 { Radhe } from "@radheim/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 = Radhe.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.
@@ -0,0 +1,79 @@
1
+ import {
2
+ layer3
3
+ } from "./contracts-d8k8mt5a.js";
4
+ import {
5
+ make3
6
+ } from "./contracts-f8tdk121.js";
7
+ import {
8
+ provide2,
9
+ node2
10
+ } from "./contracts-fc2gzwgc.js";
11
+ import {
12
+ __export
13
+ } from "./contracts-9rqn6x4v.js";
14
+
15
+ // src/internal/host.ts
16
+ var exports_host = {};
17
+ __export(exports_host, {
18
+ EmbeddedHost: () => exports_host,
19
+ create: () => create5
20
+ });
21
+ import { Automation } from "@radheim/core/automation";
22
+ import { Instance } from "@radheim/core/instance/service";
23
+ import { SdkPlugins } from "@radheim/core/plugin/sdk";
24
+ import { Session } from "@radheim/core/session";
25
+ import { Workspace } from "@radheim/core/workspace";
26
+ import { WorkspaceDriver } from "@radheim/core/workspace/driver";
27
+ import { ServerFetch } from "@radheim/server/fetch";
28
+ import { createEmbeddedRoutes } from "@radheim/server/routes";
29
+ import { Context, Effect, Layer, ManagedRuntime, Scope } from "effect";
30
+ import { Base64 } from "effect/encoding";
31
+ var create5 = Effect.fn("EmbeddedHost.create")(function* (options = {}, embed = {}) {
32
+ const { log, plugins, workspaceProviders, instances, ...server } = options;
33
+ const selector = instances ? provide2(instances, yield* Effect.context()) : undefined;
34
+ const overrides = [
35
+ ...selector ? [Instance.node.replace(node2(selector))] : [],
36
+ ...embed.overrides ?? [],
37
+ ...workspaceProviders ? [WorkspaceDriver.node.replace(WorkspaceDriver.registryNode(workspaceProviders))] : []
38
+ ];
39
+ const routes = embed.profile ? embed.profile.routes(overrides) : createEmbeddedRoutes({
40
+ ...server,
41
+ app: { ...server.app, name: server.app?.name ?? "sdk" },
42
+ database: { path: ":memory:", ...server.database }
43
+ }, overrides);
44
+ const runtime = ManagedRuntime.make(Layer.effectContext(ServerFetch.build(routes.pipe(Layer.provideMerge(layer3(log))))));
45
+ return yield* Effect.gen(function* () {
46
+ const services = yield* runtime.contextEffect;
47
+ const sdkPlugins = Context.get(services, SdkPlugins.Service);
48
+ for (const plugin of plugins ?? [])
49
+ yield* sdkPlugins.register(plugin);
50
+ const serve = embed.profile ? embed.profile.serve(services) : ServerFetch.serve(services);
51
+ const served = runtime.runSync(serve.pipe(Effect.provideService(Scope.Scope, runtime.scope)));
52
+ runtime.runFork(Context.get(services, Automation.Service).run);
53
+ const transport = make3(served, runtime.dispose);
54
+ return {
55
+ runtime,
56
+ served,
57
+ fetch: withPassword(transport.fetch, embed.profile?.password),
58
+ handler: (request) => transport.fetch(request),
59
+ plugins: sdkPlugins,
60
+ sessions: Context.get(services, Session.Service),
61
+ workspace: Context.get(services, Workspace.Service),
62
+ close: transport.close
63
+ };
64
+ }).pipe(Effect.onError(() => runtime.disposeEffect));
65
+ });
66
+ function withPassword(fetch, password) {
67
+ if (!password)
68
+ return fetch;
69
+ const authorization = `Basic ${Base64.encode(`opencode:${password}`)}`;
70
+ return Object.assign((input, init) => {
71
+ const request = new Request(input, init);
72
+ request.headers.set("authorization", authorization);
73
+ return fetch(request);
74
+ }, { preconnect: () => {
75
+ return;
76
+ } });
77
+ }
78
+
79
+ export { create5, exports_host };
@@ -0,0 +1,14 @@
1
+ import {
2
+ __export
3
+ } from "./contracts-9rqn6x4v.js";
4
+
5
+ // src/effect/tool.ts
6
+ var exports_tool = {};
7
+ __export(exports_tool, {
8
+ Error: () => Error2,
9
+ RegistrationError: () => RegistrationError2
10
+ });
11
+ import { RegistrationError as RegistrationError2 } from "@radheim/core/tool";
12
+ import { Error as Error2 } from "@radheim/schema/tool";
13
+
14
+ export { exports_tool, RegistrationError2, Error2 };
@@ -0,0 +1,23 @@
1
+ import {
2
+ create4
3
+ } from "./contracts-r4rmkqh9.js";
4
+ import {
5
+ __export
6
+ } from "./contracts-9rqn6x4v.js";
7
+
8
+ // src/effect/opencode.ts
9
+ var exports_opencode = {};
10
+ __export(exports_opencode, {
11
+ Radhe: () => exports_opencode,
12
+ Service: () => Service2,
13
+ create: () => create2,
14
+ layer: () => layer2
15
+ });
16
+ import { Context, Layer } from "effect";
17
+ var create2 = create4;
18
+
19
+ class Service2 extends Context.Service()("@radheim/sdk/OpenCode") {
20
+ }
21
+ var layer2 = (options = {}) => Layer.effect(Service2, create2(options));
22
+
23
+ export { create2, Service2, layer2, exports_opencode };
@@ -0,0 +1,18 @@
1
+ import {
2
+ createWithHost2
3
+ } from "./contracts-rnpbh5as.js";
4
+ import {
5
+ __export
6
+ } from "./contracts-9rqn6x4v.js";
7
+
8
+ // src/opencode.ts
9
+ var exports_opencode2 = {};
10
+ __export(exports_opencode2, {
11
+ Radhe: () => exports_opencode2,
12
+ create: () => create3
13
+ });
14
+ async function create3(options = {}) {
15
+ return (await createWithHost2(options)).sdk;
16
+ }
17
+
18
+ export { create3, exports_opencode2 };
@@ -0,0 +1,16 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __returnValue = (v) => v;
3
+ function __exportSetter(name, newValue) {
4
+ this[name] = __returnValue.bind(null, newValue);
5
+ }
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, {
9
+ get: all[name],
10
+ enumerable: true,
11
+ configurable: true,
12
+ set: __exportSetter.bind(all, name)
13
+ });
14
+ };
15
+
16
+ export { __export };
@@ -0,0 +1,14 @@
1
+ import {
2
+ __export
3
+ } from "./contracts-9rqn6x4v.js";
4
+
5
+ // src/tool.ts
6
+ var exports_tool2 = {};
7
+ __export(exports_tool2, {
8
+ Error: () => Error3,
9
+ RegistrationError: () => RegistrationError3
10
+ });
11
+ import { RegistrationError as RegistrationError3 } from "@radheim/core/tool";
12
+ import { Error as Error3 } from "@radheim/schema/tool";
13
+
14
+ export { exports_tool2, RegistrationError3, Error3 };
@@ -0,0 +1,49 @@
1
+ // src/logging.ts
2
+ import { Formatter, Layer, Logger, References } from "effect";
3
+ var levels = {
4
+ trace: "Trace",
5
+ debug: "Debug",
6
+ info: "Info",
7
+ warn: "Warn",
8
+ error: "Error",
9
+ fatal: "Fatal"
10
+ };
11
+ var levelNames = new Map([
12
+ [levels.trace, "trace"],
13
+ [levels.debug, "debug"],
14
+ [levels.info, "info"],
15
+ [levels.warn, "warn"],
16
+ [levels.error, "error"],
17
+ [levels.fatal, "fatal"]
18
+ ]);
19
+ function layer3(log) {
20
+ const logger = Logger.make((options) => {
21
+ if (!log)
22
+ return;
23
+ const level = levelNames.get(options.logLevel);
24
+ if (!level)
25
+ return;
26
+ const entry = Logger.formatStructured.log(options);
27
+ const values = Array.isArray(entry.message) ? entry.message : [entry.message];
28
+ const [message, ...data] = values;
29
+ const details = data.length === 1 && typeof data[0] === "object" && data[0] !== null && !Array.isArray(data[0]) ? data[0] : undefined;
30
+ const { cause: detailCause, ...detailAttributes } = details ?? {};
31
+ const attributes = {
32
+ ...entry.annotations,
33
+ ...detailAttributes,
34
+ ...Object.keys(entry.spans).length > 0 ? { spans: entry.spans } : {},
35
+ ...!details && data.length > 0 ? { data: data.length === 1 ? data[0] : data } : {}
36
+ };
37
+ try {
38
+ log.emit({
39
+ level,
40
+ message: typeof message === "string" ? message : Formatter.format(message),
41
+ ...Object.keys(attributes).length > 0 ? { attributes } : {},
42
+ ...entry.cause === undefined && detailCause === undefined ? {} : { cause: entry.cause ?? detailCause }
43
+ });
44
+ } catch {}
45
+ });
46
+ return Layer.merge(Logger.layer([logger], { mergeWithExisting: false }), Layer.succeed(References.MinimumLogLevel, levels[log?.level ?? "info"]));
47
+ }
48
+
49
+ export { layer3 };
@@ -0,0 +1,128 @@
1
+ import {
2
+ __export
3
+ } from "./contracts-9rqn6x4v.js";
4
+
5
+ // src/internal/fetch.ts
6
+ var exports_fetch = {};
7
+ __export(exports_fetch, {
8
+ OwnedFetch: () => exports_fetch,
9
+ make: () => make3
10
+ });
11
+ function make3(handler, dispose) {
12
+ const requests = new Map;
13
+ const closed = new Error("OpenCode host is closed");
14
+ let closePromise;
15
+ const fetch = Object.assign((input, init) => {
16
+ if (closePromise)
17
+ return Promise.reject(closed);
18
+ const source = new Request(input, init);
19
+ if (source.signal.aborted)
20
+ return Promise.reject(source.signal.reason);
21
+ const controller = new AbortController;
22
+ const abort = () => controller.abort(source.signal.reason);
23
+ source.signal.addEventListener("abort", abort, { once: true });
24
+ const request = new Request(source, { signal: controller.signal });
25
+ const lifetime = Promise.withResolvers();
26
+ const finish = () => {
27
+ source.signal.removeEventListener("abort", abort);
28
+ requests.delete(controller);
29
+ lifetime.resolve();
30
+ };
31
+ requests.set(controller, lifetime.promise);
32
+ const handled = handler(request);
33
+ return rejectOnAbort(handled, request.signal).then((response) => trackResponse(response, request.signal, finish), (cause) => {
34
+ handled.then(finish, finish);
35
+ throw cause;
36
+ });
37
+ }, { preconnect: () => {
38
+ return;
39
+ } });
40
+ const close = () => {
41
+ if (closePromise)
42
+ return closePromise;
43
+ closePromise = Promise.resolve().then(async () => {
44
+ requests.forEach((_, controller) => controller.abort(closed));
45
+ await Promise.allSettled(requests.values());
46
+ await dispose();
47
+ });
48
+ return closePromise;
49
+ };
50
+ return { fetch, close };
51
+ }
52
+ function rejectOnAbort(promise, signal) {
53
+ if (signal.aborted)
54
+ return Promise.reject(signal.reason);
55
+ return new Promise((resolve, reject) => {
56
+ const abort = () => reject(signal.reason);
57
+ signal.addEventListener("abort", abort, { once: true });
58
+ promise.then((value) => {
59
+ signal.removeEventListener("abort", abort);
60
+ resolve(value);
61
+ }, (cause) => {
62
+ signal.removeEventListener("abort", abort);
63
+ reject(cause);
64
+ });
65
+ });
66
+ }
67
+ function trackResponse(response, signal, finish) {
68
+ if (!response.body) {
69
+ finish();
70
+ return response;
71
+ }
72
+ const reader = response.body.getReader();
73
+ let done = false;
74
+ let abort = () => {};
75
+ const complete = () => {
76
+ if (done)
77
+ return false;
78
+ done = true;
79
+ signal.removeEventListener("abort", abort);
80
+ return true;
81
+ };
82
+ const body = new ReadableStream({
83
+ start(controller) {
84
+ abort = () => {
85
+ if (!complete())
86
+ return;
87
+ controller.error(signal.reason);
88
+ reader.cancel(signal.reason).then(finish, finish);
89
+ };
90
+ if (signal.aborted)
91
+ abort();
92
+ else
93
+ signal.addEventListener("abort", abort, { once: true });
94
+ },
95
+ async pull(controller) {
96
+ try {
97
+ const next = await reader.read();
98
+ if (done)
99
+ return;
100
+ if (!next.done) {
101
+ controller.enqueue(next.value);
102
+ return;
103
+ }
104
+ if (!complete())
105
+ return;
106
+ controller.close();
107
+ finish();
108
+ } catch (cause) {
109
+ if (!complete())
110
+ return;
111
+ controller.error(cause);
112
+ finish();
113
+ }
114
+ },
115
+ async cancel(reason) {
116
+ if (!complete())
117
+ return;
118
+ try {
119
+ await reader.cancel(reason);
120
+ } finally {
121
+ finish();
122
+ }
123
+ }
124
+ });
125
+ return new Response(body, response);
126
+ }
127
+
128
+ export { make3, exports_fetch };
@@ -0,0 +1,52 @@
1
+ import {
2
+ __export
3
+ } from "./contracts-9rqn6x4v.js";
4
+
5
+ // src/internal/instances.ts
6
+ var exports_instances = {};
7
+ __export(exports_instances, {
8
+ SdkInstances: () => exports_instances,
9
+ node: () => node2,
10
+ provide: () => provide2
11
+ });
12
+ import { Instance } from "@radheim/core/instance";
13
+ import { LocationServiceMap } from "@radheim/core/location-service-map";
14
+ import { Plugin } from "@radheim/core/plugin";
15
+ import { makeGlobalNode } from "@radheim/util/effect/app-node";
16
+ import { Context, Effect, Layer } from "effect";
17
+ function provide2(options, context) {
18
+ return {
19
+ key: options.key,
20
+ configure: (key) => options.configure(key).pipe(Effect.updateContext((ambient) => Context.merge(context, ambient)))
21
+ };
22
+ }
23
+ function node2(options) {
24
+ return makeGlobalNode({
25
+ service: Instance.Service,
26
+ layer: layer(options),
27
+ deps: [LocationServiceMap.node]
28
+ });
29
+ }
30
+ function layer(options) {
31
+ return Layer.effect(Instance.Service, Effect.gen(function* () {
32
+ const locations = yield* LocationServiceMap.Service;
33
+ if (!locations.instances)
34
+ return yield* Effect.die(new Error("SdkInstances needs the host's own LocationServiceMap"));
35
+ const instances = yield* locations.instances((ref, key, host) => Layer.unwrap(Effect.gen(function* () {
36
+ const configuration = yield* options.configure(key).pipe(Effect.orDie);
37
+ return Instance.layer(ref, { plugins: configuration.plugins, host }).pipe(Layer.tap((context) => Effect.gen(function* () {
38
+ const plugins = yield* Plugin.Service;
39
+ yield* plugins.awaitActivation;
40
+ const failed = (yield* plugins.list()).filter((plugin) => plugin.state.status === "failed" && configuration.plugins.some((configured) => configured.id === plugin.id));
41
+ if (failed.length > 0)
42
+ yield* Effect.die(new Error(`Instance plugin setup failed: ${failed.map((plugin) => plugin.id).join(", ")}`));
43
+ }).pipe(Effect.provide(context))));
44
+ })));
45
+ return Instance.Service.of({
46
+ provide: (session) => Effect.provide(instances.get(session.location, options.key(session))),
47
+ live: (session) => instances.has(session.location, options.key(session))
48
+ });
49
+ }));
50
+ }
51
+
52
+ export { provide2, node2, exports_instances };
@@ -0,0 +1,25 @@
1
+ import {
2
+ __export
3
+ } from "./contracts-9rqn6x4v.js";
4
+
5
+ // src/internal/workerd.ts
6
+ var exports_workerd = {};
7
+ __export(exports_workerd, {
8
+ WorkerdProfile: () => exports_workerd,
9
+ make: () => make2
10
+ });
11
+ import { ServerWorkerd } from "@radheim/server/workerd";
12
+ function make2(options) {
13
+ const server = {
14
+ ...options,
15
+ app: { ...options.app, name: options.app?.name ?? "sdk" },
16
+ config: options.config === undefined ? undefined : { content: JSON.stringify(options.config) }
17
+ };
18
+ return {
19
+ routes: (overrides) => ServerWorkerd.routes(server, overrides),
20
+ serve: (context) => ServerWorkerd.serve(context, server),
21
+ password: options.password
22
+ };
23
+ }
24
+
25
+ export { make2, exports_workerd };
@@ -0,0 +1,44 @@
1
+ import {
2
+ create5
3
+ } from "./contracts-21rejh3w.js";
4
+ import {
5
+ __export
6
+ } from "./contracts-9rqn6x4v.js";
7
+
8
+ // src/internal/effect.ts
9
+ var exports_effect = {};
10
+ __export(exports_effect, {
11
+ EffectSdk: () => exports_effect,
12
+ create: () => create4,
13
+ createWithHost: () => createWithHost3
14
+ });
15
+ import { Radhe } from "@radheim/client/effect";
16
+ import { Effect } from "effect";
17
+ import { FetchHttpClient, HttpClient } from "effect/http";
18
+ var create4 = (options, embed) => Effect.map(createWithHost3(options, embed), (created) => created.sdk);
19
+ var createWithHost3 = Effect.fn("OpenCode.create")(function* (options = {}, embed = {}) {
20
+ const host = yield* Effect.acquireRelease(create5(options, embed), (host) => Effect.promise(host.close));
21
+ const httpClient = yield* HttpClient.HttpClient.pipe(Effect.provide(FetchHttpClient.layer));
22
+ const client = yield* Radhe.make({ baseUrl: "http://opencode.local" }).pipe(Effect.provideService(HttpClient.HttpClient, HttpClient.transformResponse(httpClient, Effect.provideService(FetchHttpClient.Fetch, host.fetch))));
23
+ const sdk = {
24
+ ...client,
25
+ sessions: {
26
+ ...client.session,
27
+ create: host.sessions.create,
28
+ get: (input) => host.sessions.get(input.sessionID),
29
+ move: host.sessions.move
30
+ },
31
+ events: client.event,
32
+ workspace: {
33
+ create: host.workspace.create,
34
+ attach: host.workspace.attach,
35
+ provision: ({ workspaceID }) => host.workspace.provision(workspaceID),
36
+ destroy: ({ workspaceID }) => host.workspace.destroy(workspaceID),
37
+ suspendIdle: host.workspace.suspendIdle
38
+ },
39
+ plugin: Object.assign(host.plugins.register, client.plugin)
40
+ };
41
+ return { sdk, host };
42
+ });
43
+
44
+ export { create4, createWithHost3, exports_effect };
@@ -0,0 +1,55 @@
1
+ import {
2
+ create5
3
+ } from "./contracts-21rejh3w.js";
4
+ import {
5
+ __export
6
+ } from "./contracts-9rqn6x4v.js";
7
+
8
+ // src/internal/promise.ts
9
+ var exports_promise = {};
10
+ __export(exports_promise, {
11
+ PromiseSdk: () => exports_promise,
12
+ createWithHost: () => createWithHost2
13
+ });
14
+ import { Radhe } from "@radheim/client";
15
+ import { Session } from "@radheim/schema/session";
16
+ import { Effect, Schema } from "effect";
17
+ async function createWithHost2(options = {}, embed = {}) {
18
+ const { plugins, instances, ...hostOptions } = options;
19
+ const host = await Effect.runPromise(create5({
20
+ ...hostOptions,
21
+ plugins: await adaptPlugins(plugins),
22
+ instances: instances ? {
23
+ key: (session) => instances.key(Schema.encodeSync(Session.Info)(session)),
24
+ configure: (key) => Effect.gen(function* () {
25
+ const { PluginPromise } = yield* Effect.promise(() => import("@radheim/core/plugin/promise"));
26
+ const configuration = yield* Effect.tryPromise(async () => instances.configure(key));
27
+ return { plugins: configuration.plugins.map(PluginPromise.fromPromise) };
28
+ })
29
+ } : undefined
30
+ }, embed));
31
+ const client = Radhe.make({ baseUrl: "http://opencode.local", fetch: host.fetch });
32
+ const register = async (plugin) => {
33
+ const { PluginPromise } = await import("@radheim/core/plugin/promise");
34
+ return host.runtime.runPromise(host.plugins.register(PluginPromise.fromPromise(plugin)));
35
+ };
36
+ return {
37
+ host,
38
+ sdk: {
39
+ ...client,
40
+ sessions: client.session,
41
+ events: client.event,
42
+ plugin: Object.assign(register, client.plugin),
43
+ close: host.close,
44
+ [Symbol.asyncDispose]: host.close
45
+ }
46
+ };
47
+ }
48
+ async function adaptPlugins(plugins) {
49
+ if (!plugins?.length)
50
+ return;
51
+ const { PluginPromise } = await import("@radheim/core/plugin/promise");
52
+ return plugins.map(PluginPromise.fromPromise);
53
+ }
54
+
55
+ export { createWithHost2, exports_promise };