@zyro-sec/sdk 1.0.0 → 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/package.json +16 -24
- 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
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
export * as EmbeddedHost from "./host"
|
|
2
|
+
|
|
3
|
+
import { SdkPlugins } from "@zyro-sec/core/plugin/sdk"
|
|
4
|
+
import type { Plugin } from "@zyro-sec/plugin/effect/plugin"
|
|
5
|
+
import { SessionRestart } from "@zyro-sec/core/session/execution/restart"
|
|
6
|
+
import { Session } from "@zyro-sec/core/session"
|
|
7
|
+
import { Workspace } from "@zyro-sec/core/workspace"
|
|
8
|
+
import { WorkspaceDriver } from "@zyro-sec/core/workspace/driver"
|
|
9
|
+
import { createEmbeddedRoutes } from "@zyro-sec/server/routes"
|
|
10
|
+
import type { ServerOptions } from "@zyro-sec/server/options"
|
|
11
|
+
import type { LayerNode } from "@zyro-sec/util/effect/layer-node"
|
|
12
|
+
import { Context, Effect, Layer, ManagedRuntime, Scope } from "effect"
|
|
13
|
+
import { HttpEffect, HttpRouter, HttpServer, HttpServerRequest } from "effect/http"
|
|
14
|
+
import { context, layer, type LogOptions } from "../logging"
|
|
15
|
+
import { OwnedFetch } from "./fetch"
|
|
16
|
+
import { SdkInstances } from "./instances"
|
|
17
|
+
|
|
18
|
+
export interface CreateOptions<R = never> extends Omit<ServerOptions, "hostname" | "port" | "password"> {
|
|
19
|
+
readonly log?: LogOptions
|
|
20
|
+
readonly plugins?: ReadonlyArray<Plugin>
|
|
21
|
+
readonly workspaceProviders?: Readonly<Record<string, WorkspaceDriver.Interface>>
|
|
22
|
+
readonly instances?: SdkInstances.Options<R>
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Host hooks for embedding opencode on a non-default runtime profile. */
|
|
26
|
+
export interface EmbedOptions {
|
|
27
|
+
readonly overrides?: LayerNode.Replacements
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export const create = Effect.fn("EmbeddedHost.create")(function* <R = never>(
|
|
31
|
+
options: CreateOptions<R> = {},
|
|
32
|
+
embed: EmbedOptions = {},
|
|
33
|
+
) {
|
|
34
|
+
const { log, plugins, workspaceProviders, instances, ...server } = options
|
|
35
|
+
const selector = instances ? SdkInstances.provide(instances, yield* Effect.context<R>()) : undefined
|
|
36
|
+
const runtime = ManagedRuntime.make(
|
|
37
|
+
createEmbeddedRoutes(
|
|
38
|
+
{
|
|
39
|
+
...server,
|
|
40
|
+
app: { ...server.app, name: server.app?.name ?? "sdk" },
|
|
41
|
+
database: { path: ":memory:", ...server.database },
|
|
42
|
+
},
|
|
43
|
+
workspaceProviders
|
|
44
|
+
? [...(embed.overrides ?? []), WorkspaceDriver.node.replace(WorkspaceDriver.registryNode(workspaceProviders))]
|
|
45
|
+
: embed.overrides,
|
|
46
|
+
selector ? (replacements) => SdkInstances.node(selector, replacements) : undefined,
|
|
47
|
+
).pipe(Layer.provide(HttpServer.layerServices), Layer.provideMerge(layer(log))),
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
return yield* Effect.gen(function* () {
|
|
51
|
+
const services = yield* runtime.contextEffect
|
|
52
|
+
const sdkPlugins = Context.get(services, SdkPlugins.Service)
|
|
53
|
+
for (const plugin of plugins ?? []) yield* sdkPlugins.register(plugin)
|
|
54
|
+
// The sweep is a no-op when nothing is suspended. ManagedRuntime owns the
|
|
55
|
+
// fiber so recovery never delays startup but still stops with the host.
|
|
56
|
+
runtime.runFork(Context.get(services, SessionRestart.Service).resumeSuspendedSessions)
|
|
57
|
+
const handler = HttpEffect.toWebHandlerWith<never, HttpServerRequest.HttpServerRequest | Scope.Scope>(
|
|
58
|
+
context(services),
|
|
59
|
+
)(Context.get(services, HttpRouter.HttpRouter).asHttpEffect())
|
|
60
|
+
const transport = OwnedFetch.make(handler, runtime.dispose)
|
|
61
|
+
|
|
62
|
+
return {
|
|
63
|
+
runtime,
|
|
64
|
+
fetch: transport.fetch,
|
|
65
|
+
plugins: sdkPlugins,
|
|
66
|
+
sessions: Context.get(services, Session.Service),
|
|
67
|
+
workspace: Context.get(services, Workspace.Service),
|
|
68
|
+
close: transport.close,
|
|
69
|
+
}
|
|
70
|
+
}).pipe(Effect.onError(() => runtime.disposeEffect))
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
export type Interface = Effect.Success<ReturnType<typeof create>>
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
export * as SdkInstances from "./instances"
|
|
2
|
+
|
|
3
|
+
import { Instance } from "@zyro-sec/core/instance"
|
|
4
|
+
import { LocationServiceMap } from "@zyro-sec/core/location-service-map"
|
|
5
|
+
import { Plugin } from "@zyro-sec/core/plugin"
|
|
6
|
+
import type { InstancePlugins } from "@zyro-sec/core/plugin/instance"
|
|
7
|
+
import type { Session } from "@zyro-sec/schema/session"
|
|
8
|
+
import { makeGlobalNode } from "@zyro-sec/util/effect/app-node"
|
|
9
|
+
import type { LayerNode } from "@zyro-sec/util/effect/layer-node"
|
|
10
|
+
import { Context, Duration, Effect, Layer, LayerMap, RcMap, Scope } from "effect"
|
|
11
|
+
|
|
12
|
+
export interface Configuration {
|
|
13
|
+
readonly plugins: InstancePlugins.List
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface Options<R = never> {
|
|
17
|
+
/** Select a sharing key within the Session's current Location. Must not initialize plugins. */
|
|
18
|
+
readonly key: (session: Session.Info) => string
|
|
19
|
+
/**
|
|
20
|
+
* Reconstruct configuration on a cache miss. Resources belong to the instance Scope; other requirements
|
|
21
|
+
* are the services the SDK entrypoint was built with.
|
|
22
|
+
*/
|
|
23
|
+
readonly configure: (key: string) => Effect.Effect<Configuration, unknown, R | Scope.Scope>
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Closes `configure` over services captured where the SDK entrypoint was built; the host graph has none of its own. */
|
|
27
|
+
export function provide<R>(options: Options<R>, context: Context.Context<R>): Options {
|
|
28
|
+
return {
|
|
29
|
+
key: options.key,
|
|
30
|
+
// The ambient side wins the merge, so the instance Scope owns configured resources rather than the
|
|
31
|
+
// build Scope that was captured alongside the services.
|
|
32
|
+
configure: (key) =>
|
|
33
|
+
options
|
|
34
|
+
.configure(key)
|
|
35
|
+
.pipe(Effect.updateContext((ambient: Context.Context<Scope.Scope>) => Context.merge(context, ambient))),
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Replaces the host's `Instance.node`; `replacements` resolves lazily so instances inherit the final host graph. */
|
|
40
|
+
export function node(options: Options, replacements: () => LayerNode.Replacements) {
|
|
41
|
+
return makeGlobalNode({
|
|
42
|
+
service: Instance.Service,
|
|
43
|
+
layer: layer(options, replacements),
|
|
44
|
+
deps: [LocationServiceMap.node],
|
|
45
|
+
})
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function layer(options: Options, replacements: () => LayerNode.Replacements) {
|
|
49
|
+
return Layer.effect(
|
|
50
|
+
Instance.Service,
|
|
51
|
+
Effect.gen(function* () {
|
|
52
|
+
const scope = yield* Effect.scope
|
|
53
|
+
const locations = yield* LocationServiceMap.Service
|
|
54
|
+
const key = (session: Session.Info) => ({
|
|
55
|
+
key: options.key(session),
|
|
56
|
+
...LocationServiceMap.canonical(session.location),
|
|
57
|
+
})
|
|
58
|
+
const provide = (session: Session.Info) => Effect.provide(instances.get(key(session)))
|
|
59
|
+
const instances: LayerMap.LayerMap<
|
|
60
|
+
ReturnType<typeof key>,
|
|
61
|
+
Instance.Services,
|
|
62
|
+
Instance.Error
|
|
63
|
+
> = yield* LayerMap.make(
|
|
64
|
+
(input: ReturnType<typeof key>) =>
|
|
65
|
+
Layer.unwrap(
|
|
66
|
+
Effect.gen(function* () {
|
|
67
|
+
const configuration = yield* options.configure(input.key).pipe(Effect.orDie)
|
|
68
|
+
return Instance.layer(input, {
|
|
69
|
+
plugins: configuration.plugins,
|
|
70
|
+
replacements: [
|
|
71
|
+
...replacements(),
|
|
72
|
+
// Instances borrow this selector and the host's Location map instead of retaining
|
|
73
|
+
// their Layer scopes; retaining the selector would block its shutdown on its own entries.
|
|
74
|
+
Instance.node.replace(Layer.succeed(Instance.Service, { provide })),
|
|
75
|
+
LocationServiceMap.node.replace(Layer.succeed(LocationServiceMap.Service, locations)),
|
|
76
|
+
],
|
|
77
|
+
}).pipe(
|
|
78
|
+
Layer.tap((context) =>
|
|
79
|
+
Effect.gen(function* () {
|
|
80
|
+
const plugins = yield* Plugin.Service
|
|
81
|
+
yield* plugins.awaitActivation
|
|
82
|
+
// Covers setup failures and IDs colliding with host plugins; Core reports both in the inventory.
|
|
83
|
+
const failed = (yield* plugins.list()).filter(
|
|
84
|
+
(plugin) =>
|
|
85
|
+
plugin.state.status === "failed" &&
|
|
86
|
+
configuration.plugins.some((configured) => configured.id === plugin.id),
|
|
87
|
+
)
|
|
88
|
+
if (failed.length > 0)
|
|
89
|
+
yield* Effect.die(
|
|
90
|
+
new Error(`Instance plugin setup failed: ${failed.map((plugin) => plugin.id).join(", ")}`),
|
|
91
|
+
)
|
|
92
|
+
}).pipe(Effect.provide(context)),
|
|
93
|
+
),
|
|
94
|
+
)
|
|
95
|
+
}),
|
|
96
|
+
).pipe(
|
|
97
|
+
// Eviction can close the lookup's scope; do not make that fiber wait on itself.
|
|
98
|
+
Layer.tapCause(() =>
|
|
99
|
+
instances.invalidate(input).pipe(Effect.forkIn(scope, { startImmediately: true }), Effect.asVoid),
|
|
100
|
+
),
|
|
101
|
+
),
|
|
102
|
+
{ idleTimeToLive: Duration.infinity },
|
|
103
|
+
)
|
|
104
|
+
return Instance.Service.of({ provide, live: (session) => RcMap.has(instances.rcMap, key(session)) })
|
|
105
|
+
}),
|
|
106
|
+
)
|
|
107
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export * as WorkerdProfile from "./workerd"
|
|
2
|
+
|
|
3
|
+
import type { Config } from "@zyro-sec/schema/config"
|
|
4
|
+
import { ServerWorkerd } from "@zyro-sec/server/workerd"
|
|
5
|
+
|
|
6
|
+
export type Configuration = Omit<typeof Config.Info.Encoded, "plugins">
|
|
7
|
+
|
|
8
|
+
export interface Options extends Omit<ServerWorkerd.Options, "password" | "config"> {
|
|
9
|
+
readonly config?: Configuration
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function make({ config, ...options }: Options) {
|
|
13
|
+
const server = {
|
|
14
|
+
...options,
|
|
15
|
+
config: config === undefined ? undefined : { content: JSON.stringify(config) },
|
|
16
|
+
}
|
|
17
|
+
return {
|
|
18
|
+
options: ServerWorkerd.serverOptions(server),
|
|
19
|
+
replacements: ServerWorkerd.replacements(server),
|
|
20
|
+
}
|
|
21
|
+
}
|
package/src/logging.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { Context, Formatter, Layer, Logger, References } from "effect"
|
|
2
|
+
|
|
3
|
+
export type LogLevel = "trace" | "debug" | "info" | "warn" | "error" | "fatal"
|
|
4
|
+
|
|
5
|
+
export type LogEntry = {
|
|
6
|
+
readonly level: LogLevel
|
|
7
|
+
readonly message: string
|
|
8
|
+
readonly attributes?: Readonly<Record<string, unknown>>
|
|
9
|
+
readonly cause?: unknown
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export type LogWriter = (entry: LogEntry) => void
|
|
13
|
+
|
|
14
|
+
export type LogOptions = {
|
|
15
|
+
readonly level?: LogLevel
|
|
16
|
+
readonly emit: LogWriter
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const levels: Record<LogLevel, Logger.Options<unknown>["logLevel"]> = {
|
|
20
|
+
trace: "Trace",
|
|
21
|
+
debug: "Debug",
|
|
22
|
+
info: "Info",
|
|
23
|
+
warn: "Warn",
|
|
24
|
+
error: "Error",
|
|
25
|
+
fatal: "Fatal",
|
|
26
|
+
}
|
|
27
|
+
const levelNames = new Map<Logger.Options<unknown>["logLevel"], LogLevel>([
|
|
28
|
+
[levels.trace, "trace"],
|
|
29
|
+
[levels.debug, "debug"],
|
|
30
|
+
[levels.info, "info"],
|
|
31
|
+
[levels.warn, "warn"],
|
|
32
|
+
[levels.error, "error"],
|
|
33
|
+
[levels.fatal, "fatal"],
|
|
34
|
+
])
|
|
35
|
+
|
|
36
|
+
export function layer(log?: LogOptions) {
|
|
37
|
+
const logger = Logger.make((options) => {
|
|
38
|
+
if (!log) return
|
|
39
|
+
const level = levelNames.get(options.logLevel)
|
|
40
|
+
if (!level) return
|
|
41
|
+
const entry = Logger.formatStructured.log(options)
|
|
42
|
+
const values = Array.isArray(entry.message) ? entry.message : [entry.message]
|
|
43
|
+
const [message, ...data] = values
|
|
44
|
+
const details =
|
|
45
|
+
data.length === 1 && typeof data[0] === "object" && data[0] !== null && !Array.isArray(data[0])
|
|
46
|
+
? (data[0] as Readonly<Record<string, unknown>>)
|
|
47
|
+
: undefined
|
|
48
|
+
const { cause: detailCause, ...detailAttributes } = details ?? {}
|
|
49
|
+
const attributes = {
|
|
50
|
+
...entry.annotations,
|
|
51
|
+
...detailAttributes,
|
|
52
|
+
...(Object.keys(entry.spans).length > 0 ? { spans: entry.spans } : {}),
|
|
53
|
+
...(!details && data.length > 0 ? { data: data.length === 1 ? data[0] : data } : {}),
|
|
54
|
+
}
|
|
55
|
+
try {
|
|
56
|
+
log.emit({
|
|
57
|
+
level,
|
|
58
|
+
message: typeof message === "string" ? message : Formatter.format(message),
|
|
59
|
+
...(Object.keys(attributes).length > 0 ? { attributes } : {}),
|
|
60
|
+
...(entry.cause === undefined && detailCause === undefined ? {} : { cause: entry.cause ?? detailCause }),
|
|
61
|
+
})
|
|
62
|
+
} catch {
|
|
63
|
+
// A host logger must not break OpenCode operations.
|
|
64
|
+
}
|
|
65
|
+
})
|
|
66
|
+
return Layer.merge(
|
|
67
|
+
Logger.layer([logger], { mergeWithExisting: false }),
|
|
68
|
+
Layer.succeed(References.MinimumLogLevel, levels[log?.level ?? "info"]),
|
|
69
|
+
)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function context(source: Context.Context<never>) {
|
|
73
|
+
return Context.make(Logger.CurrentLoggers, Context.get(source, Logger.CurrentLoggers)).pipe(
|
|
74
|
+
Context.add(References.MinimumLogLevel, Context.get(source, References.MinimumLogLevel)),
|
|
75
|
+
)
|
|
76
|
+
}
|
package/src/opencode.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { PromiseSdk } from "./promise"
|
|
2
|
+
|
|
3
|
+
export type { LogEntry, LogLevel, LogOptions, LogWriter } from "./logging"
|
|
4
|
+
|
|
5
|
+
export type CreateOptions = PromiseSdk.CreateOptions
|
|
6
|
+
export type InstanceOptions = PromiseSdk.InstanceOptions
|
|
7
|
+
export type InstanceConfiguration = PromiseSdk.InstanceConfiguration
|
|
8
|
+
export type Interface = PromiseSdk.Interface
|
|
9
|
+
|
|
10
|
+
export const create = (options: CreateOptions = {}) => PromiseSdk.create(options)
|
package/src/promise.ts
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
export * as PromiseSdk from "./promise"
|
|
2
|
+
|
|
3
|
+
import { OpenCode, type OpenCodeClient } from "@zyro-sec/client"
|
|
4
|
+
import type { Plugin } from "@zyro-sec/plugin"
|
|
5
|
+
import { Session } from "@zyro-sec/schema/session"
|
|
6
|
+
import { Effect, Schema } from "effect"
|
|
7
|
+
import { EmbeddedHost } from "./internal/host"
|
|
8
|
+
|
|
9
|
+
export interface InstanceConfiguration {
|
|
10
|
+
readonly plugins: ReadonlyArray<Plugin.Plugin>
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface InstanceOptions {
|
|
14
|
+
/** Select a sharing key within the Session's current Location. Must not initialize plugins. */
|
|
15
|
+
readonly key: (session: typeof Session.Info.Encoded) => string
|
|
16
|
+
/** Reconstruct configuration on a cache miss, including after a host restart. */
|
|
17
|
+
readonly configure: (key: string) => InstanceConfiguration | Promise<InstanceConfiguration>
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface CreateOptions
|
|
21
|
+
extends Omit<EmbeddedHost.CreateOptions, "plugins" | "workspaceProviders" | "instances"> {
|
|
22
|
+
readonly plugins?: ReadonlyArray<Plugin.Plugin>
|
|
23
|
+
readonly instances?: InstanceOptions
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export type Interface = Omit<OpenCodeClient, "plugin"> & {
|
|
27
|
+
readonly sessions: OpenCodeClient["session"]
|
|
28
|
+
readonly events: OpenCodeClient["event"]
|
|
29
|
+
readonly plugin: ((plugin: Plugin.Plugin) => Promise<void>) & OpenCodeClient["plugin"]
|
|
30
|
+
readonly close: () => Promise<void>
|
|
31
|
+
readonly [Symbol.asyncDispose]: () => Promise<void>
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export async function createWithHost(
|
|
35
|
+
options: CreateOptions = {},
|
|
36
|
+
embed: EmbeddedHost.EmbedOptions = {},
|
|
37
|
+
): Promise<{ readonly sdk: Interface; readonly host: EmbeddedHost.Interface }> {
|
|
38
|
+
const { plugins, instances, ...hostOptions } = options
|
|
39
|
+
const host = await Effect.runPromise(
|
|
40
|
+
EmbeddedHost.create(
|
|
41
|
+
{
|
|
42
|
+
...hostOptions,
|
|
43
|
+
plugins: await adaptPlugins(plugins),
|
|
44
|
+
instances: instances
|
|
45
|
+
? {
|
|
46
|
+
key: (session) => instances.key(Schema.encodeSync(Session.Info)(session)),
|
|
47
|
+
configure: (key) =>
|
|
48
|
+
Effect.gen(function* () {
|
|
49
|
+
const { PluginPromise } = yield* Effect.promise(() => import("@zyro-sec/core/plugin/promise"))
|
|
50
|
+
const configuration = yield* Effect.tryPromise(async () => instances.configure(key))
|
|
51
|
+
return { plugins: configuration.plugins.map(PluginPromise.fromPromise) }
|
|
52
|
+
}),
|
|
53
|
+
}
|
|
54
|
+
: undefined,
|
|
55
|
+
},
|
|
56
|
+
embed,
|
|
57
|
+
),
|
|
58
|
+
)
|
|
59
|
+
const client = OpenCode.make({ baseUrl: "http://opencode.local", fetch: host.fetch })
|
|
60
|
+
const register = async (plugin: Plugin.Plugin) => {
|
|
61
|
+
const { PluginPromise } = await import("@zyro-sec/core/plugin/promise")
|
|
62
|
+
return host.runtime.runPromise(host.plugins.register(PluginPromise.fromPromise(plugin)))
|
|
63
|
+
}
|
|
64
|
+
return {
|
|
65
|
+
host,
|
|
66
|
+
sdk: {
|
|
67
|
+
...client,
|
|
68
|
+
sessions: client.session,
|
|
69
|
+
events: client.event,
|
|
70
|
+
plugin: Object.assign(register, client.plugin),
|
|
71
|
+
close: host.close,
|
|
72
|
+
[Symbol.asyncDispose]: host.close,
|
|
73
|
+
},
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export async function create(options: CreateOptions = {}): Promise<Interface> {
|
|
78
|
+
return (await createWithHost(options)).sdk
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function adaptPlugins(plugins: ReadonlyArray<Plugin.Plugin> | undefined) {
|
|
82
|
+
if (!plugins?.length) return undefined
|
|
83
|
+
const { PluginPromise } = await import("@zyro-sec/core/plugin/promise")
|
|
84
|
+
return plugins.map(PluginPromise.fromPromise)
|
|
85
|
+
}
|
package/src/tool.ts
ADDED
package/src/workerd.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
export * as OpenCodeWorkerd from "./workerd"
|
|
2
|
+
|
|
3
|
+
import { WorkerdProfile } from "./internal/workerd"
|
|
4
|
+
import type { LogOptions } from "./logging"
|
|
5
|
+
import { PromiseSdk } from "./promise"
|
|
6
|
+
|
|
7
|
+
export type Configuration = WorkerdProfile.Configuration
|
|
8
|
+
|
|
9
|
+
export interface CreateOptions extends WorkerdProfile.Options {
|
|
10
|
+
readonly log?: LogOptions
|
|
11
|
+
readonly plugins?: PromiseSdk.CreateOptions["plugins"]
|
|
12
|
+
readonly instances?: PromiseSdk.CreateOptions["instances"]
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export type Interface = PromiseSdk.Interface & {
|
|
16
|
+
/** Suspends any workspaces past their idle threshold; call from the Durable Object's `alarm()` method. */
|
|
17
|
+
readonly alarm: () => Promise<void>
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Boots the embedded opencode SDK on the workerd runtime profile: the full
|
|
22
|
+
* application graph inside a Cloudflare Durable Object, with the database on
|
|
23
|
+
* the injected `DurableObjectStorage` SQLite and every intentionally-local
|
|
24
|
+
* service replaced or disabled (see `ServerWorkerd.replacements`).
|
|
25
|
+
*
|
|
26
|
+
* Suspended Sessions resume on boot (as on every runtime) because a Durable
|
|
27
|
+
* Object can be evicted mid-turn with no teardown; the write-ahead execution
|
|
28
|
+
* claim marks the turn and the boot-time sweep replays it.
|
|
29
|
+
*
|
|
30
|
+
* Forward the Durable Object's `alarm()` lifecycle method to `opencode.alarm()`
|
|
31
|
+
* so idle remote workspaces suspend while the Durable Object hibernates at
|
|
32
|
+
* zero idle cost.
|
|
33
|
+
*
|
|
34
|
+
* Returns the same typed `OpenCode.Interface` as `OpenCode.create` plus
|
|
35
|
+
* `alarm()` — typed session operations plus the live `events.subscribe()`
|
|
36
|
+
* stream — served over an in-process fetch transport, so no request leaves the
|
|
37
|
+
* isolate.
|
|
38
|
+
*/
|
|
39
|
+
export const create = async (options: CreateOptions): Promise<Interface> => {
|
|
40
|
+
const profile = WorkerdProfile.make(options)
|
|
41
|
+
const created = await PromiseSdk.createWithHost(
|
|
42
|
+
{ ...profile.options, log: options.log, plugins: options.plugins, instances: options.instances },
|
|
43
|
+
{ overrides: profile.replacements },
|
|
44
|
+
)
|
|
45
|
+
return {
|
|
46
|
+
...created.sdk,
|
|
47
|
+
alarm: async () => {
|
|
48
|
+
await created.host.runtime.runPromise(created.host.workspace.suspendIdle())
|
|
49
|
+
},
|
|
50
|
+
}
|
|
51
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { expect, test } from "bun:test"
|
|
2
|
+
import { EnvironmentDriver } from "@zyro-sec/core/environment/driver"
|
|
3
|
+
import { EnvironmentFiles } from "@zyro-sec/core/environment/files"
|
|
4
|
+
import { Location as CoreLocation } from "@zyro-sec/core/location"
|
|
5
|
+
import { Identity } from "@zyro-sec/core/machine/identity"
|
|
6
|
+
import { WorkerClient } from "@zyro-sec/core/machine/worker-client"
|
|
7
|
+
import { WorkspaceDriver } from "@zyro-sec/core/workspace/driver"
|
|
8
|
+
import { SessionInbox as CoreSessionInbox } from "@zyro-sec/core/session/inbox"
|
|
9
|
+
import { SessionMessage as CoreSessionMessage } from "@zyro-sec/core/session/message"
|
|
10
|
+
import { Agent } from "@zyro-sec/schema/agent"
|
|
11
|
+
import { Config } from "@zyro-sec/schema/config"
|
|
12
|
+
import { Event } from "@zyro-sec/schema/event"
|
|
13
|
+
import { Location } from "@zyro-sec/schema/location"
|
|
14
|
+
import { Model } from "@zyro-sec/schema/model"
|
|
15
|
+
import { Project } from "@zyro-sec/schema/project"
|
|
16
|
+
import { Provider } from "@zyro-sec/schema/provider"
|
|
17
|
+
import { WebSearch } from "@zyro-sec/schema/websearch"
|
|
18
|
+
import { Session } from "@zyro-sec/schema/session"
|
|
19
|
+
import { SessionInbox } from "@zyro-sec/schema/session-inbox"
|
|
20
|
+
import { SessionMessage } from "@zyro-sec/schema/session-message"
|
|
21
|
+
import { Workspace } from "@zyro-sec/schema/workspace"
|
|
22
|
+
import { Worktree } from "@zyro-sec/schema/worktree"
|
|
23
|
+
import { Api } from "@zyro-sec/server/api"
|
|
24
|
+
import { ClientApi, clientNamespace, groupNames, promiseOmitEndpoints } from "@zyro-sec/protocol/client"
|
|
25
|
+
import { compile, emitPromise } from "@zyro-sec/httpapi-codegen"
|
|
26
|
+
|
|
27
|
+
const SDK = await import("../src/index")
|
|
28
|
+
const SDKEffect = await import("../src/effect")
|
|
29
|
+
const CoreAgent = await import("@zyro-sec/core/agent")
|
|
30
|
+
const CoreModel = await import("@zyro-sec/core/model")
|
|
31
|
+
const CoreProject = await import("@zyro-sec/core/project")
|
|
32
|
+
const CoreSession = await import("@zyro-sec/core/session")
|
|
33
|
+
const CoreWorktree = await import("@zyro-sec/core/worktree")
|
|
34
|
+
|
|
35
|
+
test("re-exports canonical contracts directly from Schema", () => {
|
|
36
|
+
expect(SDK.Agent).toBe(Agent)
|
|
37
|
+
expect(SDK.Config).toBe(Config)
|
|
38
|
+
expect(SDK.Event).toBe(Event)
|
|
39
|
+
expect(SDK.Model).toBe(Model)
|
|
40
|
+
expect(SDK.WebSearch).toBe(WebSearch)
|
|
41
|
+
expect(SDK.Session).toBe(Session)
|
|
42
|
+
expect(SDK.Worktree).toBe(Worktree)
|
|
43
|
+
expect(SDK.Workspace).toBe(Workspace)
|
|
44
|
+
expect(Object.keys(SDK).sort()).toEqual([
|
|
45
|
+
"AbsolutePath",
|
|
46
|
+
"Agent",
|
|
47
|
+
"ClientError",
|
|
48
|
+
"Command",
|
|
49
|
+
"Config",
|
|
50
|
+
"Credential",
|
|
51
|
+
"Event",
|
|
52
|
+
"FileSystem",
|
|
53
|
+
"Integration",
|
|
54
|
+
"Location",
|
|
55
|
+
"Model",
|
|
56
|
+
"OpenCode",
|
|
57
|
+
"Permission",
|
|
58
|
+
"PermissionSaved",
|
|
59
|
+
"Project",
|
|
60
|
+
"Prompt",
|
|
61
|
+
"PromptInput",
|
|
62
|
+
"Provider",
|
|
63
|
+
"Pty",
|
|
64
|
+
"Question",
|
|
65
|
+
"Reference",
|
|
66
|
+
"RelativePath",
|
|
67
|
+
"Session",
|
|
68
|
+
"SessionInbox",
|
|
69
|
+
"SessionMessage",
|
|
70
|
+
"Skill",
|
|
71
|
+
"Tool",
|
|
72
|
+
"WebSearch",
|
|
73
|
+
"Workspace",
|
|
74
|
+
"Worktree",
|
|
75
|
+
])
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
test("Core and Server reuse the authoritative Schema and Protocol values", () => {
|
|
79
|
+
expect(CoreAgent.ID).toBe(Agent.ID)
|
|
80
|
+
expect(CoreLocation.Ref).toBe(Location.Ref)
|
|
81
|
+
expect(CoreModel.Ref).toBe(Model.Ref)
|
|
82
|
+
expect(CoreSession.Info).toBe(Session.Info)
|
|
83
|
+
expect(CoreProject.Current).toBe(Project.Current)
|
|
84
|
+
expect(CoreWorktree.DirectoryUnavailableError).toBeDefined()
|
|
85
|
+
expect(CoreWorktree.List).toBe(Worktree.List)
|
|
86
|
+
expect(CoreWorktree.Info).toBe(Worktree.Info)
|
|
87
|
+
expect(CoreSessionInbox.Item).toBe(SessionInbox.Item)
|
|
88
|
+
expect(CoreSessionInbox.User).toBe(SessionInbox.User)
|
|
89
|
+
expect(CoreSessionInbox.Synthetic).toBe(SessionInbox.Synthetic)
|
|
90
|
+
expect(CoreSessionMessage.Info).toBe(SessionMessage.Info)
|
|
91
|
+
expect(CoreSessionMessage.AssistantText).toBe(SessionMessage.AssistantText)
|
|
92
|
+
expect(Api.groups["server.session"].identifier).toBe("server.session")
|
|
93
|
+
expect(Api.groups["server.project"].identifier).toBe("server.project")
|
|
94
|
+
expect(Object.keys(ClientApi.groups)).toEqual(Object.keys(Api.groups))
|
|
95
|
+
expect(Session.ID.create()).toStartWith("ses_")
|
|
96
|
+
expect(String(Project.ID.global)).toBe("global")
|
|
97
|
+
expect(String(Provider.ID.anthropic)).toBe("anthropic")
|
|
98
|
+
expect(Workspace.ID.create()).toStartWith("wrk_")
|
|
99
|
+
})
|
|
100
|
+
|
|
101
|
+
test("client and Server contracts generate identically", () => {
|
|
102
|
+
const server = compile(Api, { groupNames, omitEndpoints: promiseOmitEndpoints, namespace: clientNamespace })
|
|
103
|
+
const client = compile(ClientApi, { groupNames, omitEndpoints: promiseOmitEndpoints, namespace: clientNamespace })
|
|
104
|
+
|
|
105
|
+
expect(emitPromise(client)).toEqual(emitPromise(server))
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
test("re-exports workspace and environment driver contracts from @zyro-sec/sdk/effect", () => {
|
|
109
|
+
expect(SDKEffect.WorkspaceDriver).toBe(WorkspaceDriver)
|
|
110
|
+
expect(SDKEffect.EnvironmentDriver).toBe(EnvironmentDriver)
|
|
111
|
+
expect(SDKEffect.EnvironmentFiles).toBe(EnvironmentFiles)
|
|
112
|
+
expect(SDKEffect.Identity).toBe(Identity)
|
|
113
|
+
expect(SDKEffect.WorkerClient).toBe(WorkerClient)
|
|
114
|
+
})
|