@zyro-sec/server 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +40 -4
- package/script/build.ts +28 -0
- package/script/pack.ts +5 -0
- package/script/workerd-probe.ts +59 -0
- package/src/api.ts +12 -0
- package/src/auth.ts +70 -0
- package/src/content-headers.ts +32 -0
- package/src/cors.ts +34 -0
- package/src/event-feed.ts +93 -0
- package/src/fetch.ts +67 -0
- package/src/handlers/agent.ts +23 -0
- package/src/handlers/artifact.ts +242 -0
- package/src/handlers/automation.ts +63 -0
- package/src/handlers/blob.ts +55 -0
- package/src/handlers/command.ts +8 -0
- package/src/handlers/config.ts +26 -0
- package/src/handlers/credential.ts +87 -0
- package/src/handlers/debug.ts +57 -0
- package/src/handlers/event.ts +38 -0
- package/src/handlers/form.ts +15 -0
- package/src/handlers/fs.ts +180 -0
- package/src/handlers/generate.ts +117 -0
- package/src/handlers/integration.ts +310 -0
- package/src/handlers/job.ts +29 -0
- package/src/handlers/location.ts +33 -0
- package/src/handlers/machine.ts +336 -0
- package/src/handlers/mcp.ts +160 -0
- package/src/handlers/media.ts +44 -0
- package/src/handlers/message.ts +82 -0
- package/src/handlers/migration.ts +13 -0
- package/src/handlers/model.ts +25 -0
- package/src/handlers/permission.ts +131 -0
- package/src/handlers/persistent-pty.ts +285 -0
- package/src/handlers/plugin.ts +97 -0
- package/src/handlers/project.ts +23 -0
- package/src/handlers/provider.ts +32 -0
- package/src/handlers/pty-socket.ts +47 -0
- package/src/handlers/pty.ts +181 -0
- package/src/handlers/push.ts +67 -0
- package/src/handlers/reference.ts +8 -0
- package/src/handlers/rpc.ts +31 -0
- package/src/handlers/server.ts +58 -0
- package/src/handlers/session-error.ts +47 -0
- package/src/handlers/session.ts +722 -0
- package/src/handlers/shell.ts +72 -0
- package/src/handlers/skill.ts +34 -0
- package/src/handlers/usage.ts +23 -0
- package/src/handlers/vcs.ts +104 -0
- package/src/handlers/voice.ts +50 -0
- package/src/handlers/websearch.ts +50 -0
- package/src/handlers/worktree.ts +60 -0
- package/src/handlers.ts +69 -0
- package/src/location.ts +86 -0
- package/src/media-uri.ts +13 -0
- package/src/middleware/authorization.ts +111 -0
- package/src/middleware/defect-response.ts +39 -0
- package/src/middleware/form-location.ts +44 -0
- package/src/middleware/schema-error.ts +49 -0
- package/src/middleware/session-location.ts +30 -0
- package/src/options.ts +61 -0
- package/src/pairing.ts +36 -0
- package/src/process.ts +274 -0
- package/src/range.ts +16 -0
- package/src/request-site.ts +36 -0
- package/src/request-tracing.ts +9 -0
- package/src/routes.ts +261 -0
- package/src/server-info.ts +41 -0
- package/src/service-status.ts +30 -0
- package/src/workerd.ts +184 -0
- package/test/artifact.test.ts +224 -0
- package/test/auth.test.ts +24 -0
- package/test/automation.test.ts +315 -0
- package/test/client-mcp.test.ts +369 -0
- package/test/codemode-api.test.ts +88 -0
- package/test/config.test.ts +104 -0
- package/test/cors.test.ts +24 -0
- package/test/defect-response.test.ts +83 -0
- package/test/event-feed.test.ts +201 -0
- package/test/fetch-option.test.ts +104 -0
- package/test/fetch.test.ts +698 -0
- package/test/fixture/mcp-starts.cjs +20 -0
- package/test/fixture/routes.ts +37 -0
- package/test/fixture/server.ts +20 -0
- package/test/fixture/worktree-delegate/index.ts +13 -0
- package/test/fixture/worktree-plugin/index.ts +47 -0
- package/test/flag-channel.test.ts +126 -0
- package/test/fs.test.ts +439 -0
- package/test/generate.test.ts +132 -0
- package/test/handler-policy.test.ts +43 -0
- package/test/heap-dump.test.ts +137 -0
- package/test/integration-policy.test.ts +93 -0
- package/test/job.test.ts +186 -0
- package/test/machine-iroh.test.ts +259 -0
- package/test/machine-link.test.ts +1234 -0
- package/test/machine-routes.test.ts +198 -0
- package/test/media.test.ts +343 -0
- package/test/message.test.ts +105 -0
- package/test/model.test.ts +62 -0
- package/test/options.test.ts +42 -0
- package/test/permission-saved.test.ts +73 -0
- package/test/persistent-pty.test.ts +1007 -0
- package/test/process.test.ts +261 -0
- package/test/provider.test.ts +88 -0
- package/test/pty-socket.property.test.ts +240 -0
- package/test/pty-socket.test.ts +89 -0
- package/test/pty-transport.test.ts +200 -0
- package/test/push-routes.test.ts +157 -0
- package/test/request-site.test.ts +71 -0
- package/test/request-tracing.test.ts +87 -0
- package/test/rpc-handler-errors.test.ts +76 -0
- package/test/schema-error.test.ts +68 -0
- package/test/service-status.test.ts +34 -0
- package/test/session-admit-location.test.ts +92 -0
- package/test/session-create.test.ts +65 -0
- package/test/session-diff.test.ts +100 -0
- package/test/session-form.test.ts +50 -0
- package/test/session-import.test.ts +152 -0
- package/test/session-instances.test.ts +335 -0
- package/test/session-unarchive.test.ts +73 -0
- package/test/session-update.test.ts +66 -0
- package/test/skill.test.ts +57 -0
- package/test/sse-failure.test.ts +71 -0
- package/test/usage.test.ts +88 -0
- package/test/vcs.test.ts +356 -0
- package/test/video-generate.test.ts +131 -0
- package/test/voice.test.ts +170 -0
- package/test/workerd.test.ts +227 -0
- package/test/worktree.test.ts +333 -0
- package/tsconfig.build.json +15 -0
- package/tsconfig.json +11 -0
- package/README.md +0 -3
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export * as RequestSite from "./request-site"
|
|
2
|
+
|
|
3
|
+
import { Effect } from "effect"
|
|
4
|
+
import { HttpMiddleware, HttpServerRequest, HttpServerResponse } from "effect/http"
|
|
5
|
+
import { type CorsOptions, isAllowedRequestOrigin } from "./cors"
|
|
6
|
+
|
|
7
|
+
// Artifact pages render in sandboxed frames, so their own requests come from an opaque origin.
|
|
8
|
+
const ARTIFACT_VIEW = /^\/api\/experimental\/artifacts\/[^/]+\/view(\/|$)/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* API routes are called by scripts and native clients, not opened as pages from other sites. Browsers label requests
|
|
12
|
+
* with Sec-Fetch-Site and Sec-Fetch-Mode; another site may navigate to the API or call it only from an allowed CORS
|
|
13
|
+
* origin. Clients that send no Sec-Fetch headers (CLI, TUI, SDK, mobile) and same-origin or typed-in requests pass.
|
|
14
|
+
*/
|
|
15
|
+
export function rejected(request: HttpServerRequest.HttpServerRequest, options?: CorsOptions) {
|
|
16
|
+
const site = request.headers["sec-fetch-site"]
|
|
17
|
+
if (site !== "cross-site" && site !== "same-site") return false
|
|
18
|
+
const pathname = new URL(request.url, "http://localhost").pathname
|
|
19
|
+
if (pathname !== "/api" && !pathname.startsWith("/api/")) return false
|
|
20
|
+
if (ARTIFACT_VIEW.test(pathname)) return false
|
|
21
|
+
if (request.headers["sec-fetch-mode"] === "navigate") return true
|
|
22
|
+
const origin = request.headers.origin
|
|
23
|
+
return origin !== undefined && !isAllowedRequestOrigin(origin, request.headers.host, options)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export const middleware = (options?: CorsOptions) =>
|
|
27
|
+
HttpMiddleware.make((app) =>
|
|
28
|
+
Effect.gen(function* () {
|
|
29
|
+
const request = yield* HttpServerRequest.HttpServerRequest
|
|
30
|
+
if (!rejected(request, options)) return yield* app
|
|
31
|
+
return HttpServerResponse.jsonUnsafe(
|
|
32
|
+
{ _tag: "ForbiddenError", message: "Cross-site requests to the API are not allowed" },
|
|
33
|
+
{ status: 403 },
|
|
34
|
+
)
|
|
35
|
+
}),
|
|
36
|
+
)
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { Context, Effect, Tracer } from "effect"
|
|
2
|
+
|
|
3
|
+
// ParentSpan is optional, so removing it never takes away a requirement of the effect.
|
|
4
|
+
export const withoutParentSpan = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
|
|
5
|
+
effect.pipe(
|
|
6
|
+
Effect.updateContext(
|
|
7
|
+
(context: Context.Context<R>) => Context.omit(Tracer.ParentSpan)(context) as Context.Context<R>,
|
|
8
|
+
),
|
|
9
|
+
)
|
package/src/routes.ts
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
import { Database } from "@zyro-sec/core/database/database"
|
|
2
|
+
import { V1Migration } from "@zyro-sec/core/database/v1-migration"
|
|
3
|
+
import { App } from "@zyro-sec/core/app"
|
|
4
|
+
import { CodeModeApi } from "@zyro-sec/core/codemode/api"
|
|
5
|
+
import { LayerNode } from "@zyro-sec/util/effect/layer-node"
|
|
6
|
+
import { Node } from "@zyro-sec/util/effect/app-node"
|
|
7
|
+
import { fetchLayer, httpClient, httpFetch } from "@zyro-sec/util/effect/app-node-platform"
|
|
8
|
+
import { AppNodeBuilder } from "@zyro-sec/core/effect/app-node-builder"
|
|
9
|
+
import { Bus } from "@zyro-sec/core/bus"
|
|
10
|
+
import { EventLogger } from "@zyro-sec/core/event-logger"
|
|
11
|
+
import { FileSystemSearch } from "@zyro-sec/core/filesystem/search"
|
|
12
|
+
import { Credential } from "@zyro-sec/core/credential"
|
|
13
|
+
import { Config } from "@zyro-sec/core/config"
|
|
14
|
+
import { PermissionSaved } from "@zyro-sec/core/permission/saved"
|
|
15
|
+
import { PtyTicket } from "@zyro-sec/core/pty/ticket"
|
|
16
|
+
import { PersistentPty } from "@zyro-sec/core/persistent-pty"
|
|
17
|
+
import { Project } from "@zyro-sec/core/project"
|
|
18
|
+
import { BlobStore } from "@zyro-sec/core/blob-store"
|
|
19
|
+
import { VideoGeneration } from "@zyro-sec/core/video-generation"
|
|
20
|
+
import { Worktree } from "@zyro-sec/core/worktree"
|
|
21
|
+
import { Session } from "@zyro-sec/core/session"
|
|
22
|
+
import { Instance } from "@zyro-sec/core/instance/service"
|
|
23
|
+
import { SessionTransfer } from "@zyro-sec/core/session/transfer"
|
|
24
|
+
import { InstructionEntry } from "@zyro-sec/core/session/instruction-entry"
|
|
25
|
+
import { ShellSelect } from "@zyro-sec/core/shell/select"
|
|
26
|
+
import { Shell } from "@zyro-sec/core/shell"
|
|
27
|
+
import { Job } from "@zyro-sec/core/job"
|
|
28
|
+
import { KV } from "@zyro-sec/core/kv"
|
|
29
|
+
import { Mcp } from "@zyro-sec/core/mcp/index"
|
|
30
|
+
import { Global } from "@zyro-sec/util/global"
|
|
31
|
+
import { FSUtil } from "@zyro-sec/util/fs-util"
|
|
32
|
+
import { InstructionDiscovery } from "@zyro-sec/core/instruction-discovery"
|
|
33
|
+
import { LocationServiceMap } from "@zyro-sec/core/location-service-map"
|
|
34
|
+
import { LocationActivity } from "@zyro-sec/core/location-activity"
|
|
35
|
+
import { Identity } from "@zyro-sec/core/machine/identity"
|
|
36
|
+
import { Machines } from "@zyro-sec/core/machine/machines"
|
|
37
|
+
import { SessionSearchBuild } from "@zyro-sec/core/session/search-build"
|
|
38
|
+
import { ModelsDev } from "@zyro-sec/core/models-dev"
|
|
39
|
+
import { SessionRestart } from "@zyro-sec/core/session/execution/restart"
|
|
40
|
+
import { Automation } from "@zyro-sec/core/automation"
|
|
41
|
+
import { PluginUpdate } from "@zyro-sec/core/plugin/update"
|
|
42
|
+
import { SdkPlugins } from "@zyro-sec/core/plugin/sdk"
|
|
43
|
+
import { WellKnown } from "@zyro-sec/core/wellknown"
|
|
44
|
+
import { PushList } from "@zyro-sec/core/push/list"
|
|
45
|
+
import { PushSender } from "@zyro-sec/core/push/sender"
|
|
46
|
+
import { PushWatcher } from "@zyro-sec/core/push/watcher"
|
|
47
|
+
import { Workspace } from "@zyro-sec/core/workspace"
|
|
48
|
+
import { Watcher } from "@zyro-sec/core/filesystem/watcher"
|
|
49
|
+
import { FileWatch } from "@zyro-sec/core/filesystem/file-watch"
|
|
50
|
+
import { HttpEffect, HttpRouter } from "effect/http"
|
|
51
|
+
import { HttpApiBuilder } from "effect/http-api"
|
|
52
|
+
import { Context, Effect, Layer, Option } from "effect"
|
|
53
|
+
import { Base64 } from "effect/encoding"
|
|
54
|
+
import { Api } from "./api"
|
|
55
|
+
import { ServerAuth } from "./auth"
|
|
56
|
+
import { CorsConfig } from "./cors"
|
|
57
|
+
import { handlers } from "./handlers"
|
|
58
|
+
import { authorizationLayer } from "./middleware/authorization"
|
|
59
|
+
import { schemaErrorLayer } from "./middleware/schema-error"
|
|
60
|
+
import { defectResponseLayer } from "./middleware/defect-response"
|
|
61
|
+
import { ServerPairing } from "./pairing"
|
|
62
|
+
import { layer } from "./location"
|
|
63
|
+
import { formLocationLayer } from "./middleware/form-location"
|
|
64
|
+
import { sessionLocationLayer } from "./middleware/session-location"
|
|
65
|
+
import { ServerInfo } from "./server-info"
|
|
66
|
+
import type { ServerOptions } from "./options"
|
|
67
|
+
|
|
68
|
+
const applicationServiceNodes = [
|
|
69
|
+
App.node,
|
|
70
|
+
CodeModeApi.node,
|
|
71
|
+
Global.node,
|
|
72
|
+
FSUtil.node,
|
|
73
|
+
Database.node,
|
|
74
|
+
KV.node,
|
|
75
|
+
Bus.node,
|
|
76
|
+
// Before the jobs and sessions, so they are released after them: a shutdown's interrupted shell calls and jobs
|
|
77
|
+
// still reach the daemon to stop their commands, and a command being created never falls back to spawning.
|
|
78
|
+
PersistentPty.node,
|
|
79
|
+
// Daemon-run shell commands belong to the server, so a Location closing never takes them down.
|
|
80
|
+
Shell.daemonNode,
|
|
81
|
+
EventLogger.node,
|
|
82
|
+
httpClient,
|
|
83
|
+
Job.node,
|
|
84
|
+
Project.node,
|
|
85
|
+
Project.sweepNode,
|
|
86
|
+
Worktree.node,
|
|
87
|
+
Session.node,
|
|
88
|
+
Instance.node,
|
|
89
|
+
SessionTransfer.node,
|
|
90
|
+
InstructionEntry.node,
|
|
91
|
+
SdkPlugins.node,
|
|
92
|
+
PluginUpdate.node,
|
|
93
|
+
PermissionSaved.node,
|
|
94
|
+
PtyTicket.node,
|
|
95
|
+
Credential.node,
|
|
96
|
+
WellKnown.node,
|
|
97
|
+
ServerPairing.node,
|
|
98
|
+
LocationServiceMap.node,
|
|
99
|
+
LocationActivity.node,
|
|
100
|
+
SessionRestart.node,
|
|
101
|
+
Automation.node,
|
|
102
|
+
// Read by the blob route.
|
|
103
|
+
BlobStore.node,
|
|
104
|
+
// Started with the server, so its leader election and polling resume jobs even before anyone calls the video API.
|
|
105
|
+
VideoGeneration.node,
|
|
106
|
+
SessionSearchBuild.node,
|
|
107
|
+
Workspace.node,
|
|
108
|
+
// The machine list: where a carrier hands over the workers dialing in from other computers.
|
|
109
|
+
Machines.node,
|
|
110
|
+
// The home's key, which the link's handshake signs with.
|
|
111
|
+
Identity.node,
|
|
112
|
+
FileWatch.node,
|
|
113
|
+
PushList.node,
|
|
114
|
+
PushSender.node,
|
|
115
|
+
PushWatcher.node,
|
|
116
|
+
] as const
|
|
117
|
+
const applicationServices = LayerNode.group(applicationServiceNodes)
|
|
118
|
+
|
|
119
|
+
export function createRoutes(
|
|
120
|
+
options: ServerOptions = {},
|
|
121
|
+
serviceURLs: () => ReadonlyArray<string> = () => [],
|
|
122
|
+
overrides: LayerNode.Replacements = [],
|
|
123
|
+
) {
|
|
124
|
+
return makeRoutes(options.password ? Option.some(options.password) : Option.none(), options, serviceURLs, overrides)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
type InstanceNode = (
|
|
128
|
+
replacements: () => LayerNode.Replacements,
|
|
129
|
+
) => LayerNode.Provider<Instance.Service, never, typeof Node.tags.values.global>
|
|
130
|
+
|
|
131
|
+
export function createEmbeddedRoutes(
|
|
132
|
+
options: ServerOptions = {},
|
|
133
|
+
overrides: LayerNode.Replacements = [],
|
|
134
|
+
instances?: InstanceNode,
|
|
135
|
+
) {
|
|
136
|
+
return makeRoutes(Option.none(), options, () => [], overrides, instances)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function makeRoutes(
|
|
140
|
+
password: Option.Option<string>,
|
|
141
|
+
options: ServerOptions,
|
|
142
|
+
serviceURLs: () => ReadonlyArray<string>,
|
|
143
|
+
// Runtime-profile replacements (e.g. workerd) applied after the standard set, so later entries win.
|
|
144
|
+
overrides: LayerNode.Replacements,
|
|
145
|
+
instances?: InstanceNode,
|
|
146
|
+
) {
|
|
147
|
+
const auth = ServerAuth.Config.configLayer({ password })
|
|
148
|
+
// Code Mode `opencode://` fetches go straight to this router, set once the router below is built. They carry the
|
|
149
|
+
// server's own credential, added here after the script handed the request over, so the script never sees it.
|
|
150
|
+
const credential = Option.map(password, (value) => `Basic ${Base64.encode(`opencode:${value}`)}`)
|
|
151
|
+
let internal: ((request: Request) => Promise<Response>) | undefined
|
|
152
|
+
const standard: LayerNode.Replacements = [
|
|
153
|
+
CodeModeApi.node.replace(
|
|
154
|
+
Layer.succeed(
|
|
155
|
+
CodeModeApi.Service,
|
|
156
|
+
CodeModeApi.Service.of({
|
|
157
|
+
fetch: (request) =>
|
|
158
|
+
Effect.suspend(() => {
|
|
159
|
+
const handle = internal
|
|
160
|
+
if (!handle) return Effect.fail(new Error("The OpenCode API is not ready yet."))
|
|
161
|
+
if (Option.isSome(credential)) request.headers.set("authorization", credential.value)
|
|
162
|
+
return Effect.tryPromise({
|
|
163
|
+
try: () => handle(request),
|
|
164
|
+
catch: (error) => (error instanceof Error ? error : new Error(String(error))),
|
|
165
|
+
})
|
|
166
|
+
}),
|
|
167
|
+
}),
|
|
168
|
+
),
|
|
169
|
+
),
|
|
170
|
+
Database.node.replace(Database.configured(options.database)),
|
|
171
|
+
PersistentPty.node.replace(PersistentPty.configured(options.pty)),
|
|
172
|
+
Bus.node.replace(Bus.configured({ persist: options.events?.persist })),
|
|
173
|
+
App.node.replace(App.configured(options.app)),
|
|
174
|
+
ModelsDev.node.replace(ModelsDev.configured(options.models)),
|
|
175
|
+
httpFetch.replace(fetchLayer(options.fetch)),
|
|
176
|
+
Watcher.node.replace(Watcher.configured({ enabled: options.fs?.filewatcher })),
|
|
177
|
+
FileWatch.node.replace(FileWatch.configured({ enabled: options.fs?.filewatcher })),
|
|
178
|
+
FileSystemSearch.node.replace(FileSystemSearch.configured({ fff: options.fs?.fff })),
|
|
179
|
+
Global.node.replace(Global.layerWith(options.config?.directory ? { config: options.config.directory } : {})),
|
|
180
|
+
Config.node.replace(
|
|
181
|
+
Config.configured({
|
|
182
|
+
project: options.config?.project,
|
|
183
|
+
claude: options.config?.claude,
|
|
184
|
+
file: options.config?.file,
|
|
185
|
+
content: options.config?.content,
|
|
186
|
+
}),
|
|
187
|
+
),
|
|
188
|
+
InstructionDiscovery.node.replace(
|
|
189
|
+
InstructionDiscovery.configured({
|
|
190
|
+
project: options.config?.project,
|
|
191
|
+
claude: options.instructions?.claude,
|
|
192
|
+
}),
|
|
193
|
+
),
|
|
194
|
+
ShellSelect.node.replace(ShellSelect.configured({ gitbash: options.windows?.gitbash })),
|
|
195
|
+
Mcp.node.replace(
|
|
196
|
+
Mcp.configured({
|
|
197
|
+
clientInfo: {
|
|
198
|
+
name: "opencode",
|
|
199
|
+
version: options.app?.version ?? "unknown",
|
|
200
|
+
},
|
|
201
|
+
}),
|
|
202
|
+
),
|
|
203
|
+
]
|
|
204
|
+
const build = (overrides: LayerNode.Replacements) => {
|
|
205
|
+
const replacements: LayerNode.Replacements = [
|
|
206
|
+
...standard,
|
|
207
|
+
// Private instances resolve this list lazily so they inherit the complete host graph, including the selector.
|
|
208
|
+
...(instances ? [Instance.node.replace(instances(() => replacements))] : []),
|
|
209
|
+
...overrides,
|
|
210
|
+
]
|
|
211
|
+
return AppNodeBuilder.build(applicationServices, replacements)
|
|
212
|
+
}
|
|
213
|
+
const serviceLayer = options.simulation
|
|
214
|
+
? Layer.unwrap(
|
|
215
|
+
Effect.gen(function* () {
|
|
216
|
+
const { simulationReplacements } = yield* Effect.promise(() => import("@zyro-sec/simulation/backend"))
|
|
217
|
+
const simulation = yield* simulationReplacements({ version: App.make(options.app).version })
|
|
218
|
+
return build([...overrides, ...simulation])
|
|
219
|
+
}),
|
|
220
|
+
)
|
|
221
|
+
: build(overrides)
|
|
222
|
+
return serviceLayer.pipe(
|
|
223
|
+
Layer.flatMap((context) => {
|
|
224
|
+
const services = Layer.succeedContext(context)
|
|
225
|
+
const requestServices = Layer.merge(
|
|
226
|
+
Layer.succeedContext(
|
|
227
|
+
Context.pick(
|
|
228
|
+
Database.Service,
|
|
229
|
+
Credential.Service,
|
|
230
|
+
PermissionSaved.Service,
|
|
231
|
+
PluginUpdate.Service,
|
|
232
|
+
Project.Service,
|
|
233
|
+
WellKnown.Service,
|
|
234
|
+
)(context),
|
|
235
|
+
),
|
|
236
|
+
ServerInfo.layer(serviceURLs, Context.get(context, Global.Service).tmp, options.app),
|
|
237
|
+
)
|
|
238
|
+
const api = HttpApiBuilder.layer(Api, { openapiPath: "/openapi.json" }).pipe(
|
|
239
|
+
Layer.provide(handlers.pipe(Layer.provide(services), Layer.provide(Layer.succeed(CorsConfig, options)))),
|
|
240
|
+
Layer.provide(formLocationLayer),
|
|
241
|
+
Layer.provide(sessionLocationLayer),
|
|
242
|
+
Layer.provide(layer),
|
|
243
|
+
Layer.provide(authorizationLayer),
|
|
244
|
+
Layer.provide(schemaErrorLayer),
|
|
245
|
+
Layer.provide(auth),
|
|
246
|
+
HttpRouter.provideRequest(requestServices),
|
|
247
|
+
Layer.merge(defectResponseLayer),
|
|
248
|
+
Layer.provideMerge(services),
|
|
249
|
+
Layer.provideMerge(HttpRouter.layer),
|
|
250
|
+
Layer.tap((context) =>
|
|
251
|
+
Effect.sync(() => {
|
|
252
|
+
internal = Context.get(context, HttpRouter.HttpRouter)
|
|
253
|
+
.asHttpEffect()
|
|
254
|
+
.pipe(HttpEffect.toWebHandlerWith(context))
|
|
255
|
+
}),
|
|
256
|
+
),
|
|
257
|
+
)
|
|
258
|
+
return Layer.merge(api, V1Migration.layer.pipe(Layer.provide(services)))
|
|
259
|
+
}),
|
|
260
|
+
)
|
|
261
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { Context, Layer } from "effect"
|
|
2
|
+
import { networkInterfaces } from "node:os"
|
|
3
|
+
import type { ServerOptions } from "./options"
|
|
4
|
+
|
|
5
|
+
export class Service extends Context.Service<
|
|
6
|
+
Service,
|
|
7
|
+
{
|
|
8
|
+
readonly urls: () => ReadonlyArray<string>
|
|
9
|
+
readonly app: NonNullable<ServerOptions["app"]>
|
|
10
|
+
readonly paths: { readonly tmp: string }
|
|
11
|
+
}
|
|
12
|
+
>()("@zyro-sec/server/ServerInfo") {}
|
|
13
|
+
|
|
14
|
+
export function layer(urls: () => ReadonlyArray<string>, tmp: string, app: ServerOptions["app"] = {}) {
|
|
15
|
+
return Layer.succeed(Service, Service.of({ urls, app, paths: { tmp } }))
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function connectionURLs(value: string, requestedHostname?: string) {
|
|
19
|
+
const url = new URL(value)
|
|
20
|
+
const hostname = requestedHostname ?? url.hostname
|
|
21
|
+
const family = hostname === "0.0.0.0" ? "IPv4" : hostname === "::" || hostname === "[::]" ? "IPv6" : undefined
|
|
22
|
+
if (family === undefined) return [value]
|
|
23
|
+
|
|
24
|
+
const loopback = new URL(value)
|
|
25
|
+
loopback.hostname = family === "IPv6" ? "[::1]" : "127.0.0.1"
|
|
26
|
+
return [
|
|
27
|
+
...new Set([
|
|
28
|
+
loopback.toString().replace(/\/$/, ""),
|
|
29
|
+
...Object.values(networkInterfaces())
|
|
30
|
+
.flatMap((entries) => entries ?? [])
|
|
31
|
+
.filter((entry) => !entry.internal && entry.family === family)
|
|
32
|
+
.map((entry) => {
|
|
33
|
+
const result = new URL(value)
|
|
34
|
+
result.hostname = family === "IPv6" ? `[${entry.address}]` : entry.address
|
|
35
|
+
return result.toString().replace(/\/$/, "")
|
|
36
|
+
}),
|
|
37
|
+
]),
|
|
38
|
+
]
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export * as ServerInfo from "./server-info"
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export * as Status from "./service-status"
|
|
2
|
+
|
|
3
|
+
import { Effect, Ref } from "effect"
|
|
4
|
+
|
|
5
|
+
export type State =
|
|
6
|
+
| { readonly type: "starting" }
|
|
7
|
+
| { readonly type: "ready" }
|
|
8
|
+
| { readonly type: "stopping" }
|
|
9
|
+
| { readonly type: "failed" }
|
|
10
|
+
|
|
11
|
+
export interface Interface {
|
|
12
|
+
readonly current: Effect.Effect<State>
|
|
13
|
+
readonly ready: Effect.Effect<void>
|
|
14
|
+
readonly fail: Effect.Effect<void>
|
|
15
|
+
readonly beginStopping: Effect.Effect<void>
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export const make = Effect.fnUntraced(function* (options: { readonly initial?: State } = {}) {
|
|
19
|
+
const current = yield* Ref.make(options.initial ?? ({ type: "starting" } satisfies State))
|
|
20
|
+
const beginStopping = Ref.update(current, (status) =>
|
|
21
|
+
status.type === "stopping" ? status : ({ type: "stopping" } satisfies State),
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
return {
|
|
25
|
+
current: Ref.get(current),
|
|
26
|
+
ready: Ref.update(current, (status) => (status.type === "starting" ? ({ type: "ready" } satisfies State) : status)),
|
|
27
|
+
fail: Ref.update(current, (status) => (status.type === "starting" ? ({ type: "failed" } satisfies State) : status)),
|
|
28
|
+
beginStopping,
|
|
29
|
+
} satisfies Interface
|
|
30
|
+
})
|
package/src/workerd.ts
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
export * as ServerWorkerd from "./workerd"
|
|
2
|
+
|
|
3
|
+
import { Context, Effect, Layer } from "effect"
|
|
4
|
+
import { BlobStore } from "@zyro-sec/core/blob-store"
|
|
5
|
+
import { ConfigPluginSource } from "@zyro-sec/core/config/plugin/source"
|
|
6
|
+
import { Database } from "@zyro-sec/core/database/database"
|
|
7
|
+
import { sqliteLayer } from "@zyro-sec/core/database/sqlite.workerd"
|
|
8
|
+
import type { DurableObjectStorage } from "@zyro-sec/core/database/sqlite.workerd"
|
|
9
|
+
import { EnvironmentUnavailable } from "@zyro-sec/core/environment/unavailable"
|
|
10
|
+
import { Identity } from "@zyro-sec/core/machine/identity"
|
|
11
|
+
import { Pty } from "@zyro-sec/core/pty"
|
|
12
|
+
import { Snapshot } from "@zyro-sec/core/snapshot"
|
|
13
|
+
import { Vcs } from "@zyro-sec/core/vcs"
|
|
14
|
+
import { VideoGeneration } from "@zyro-sec/core/video-generation"
|
|
15
|
+
import { Workspace } from "@zyro-sec/core/workspace"
|
|
16
|
+
import { CrossSpawnSpawner } from "@zyro-sec/util/cross-spawn-spawner"
|
|
17
|
+
import type { LayerNode } from "@zyro-sec/util/effect/layer-node"
|
|
18
|
+
import { Npm } from "@zyro-sec/util/npm"
|
|
19
|
+
import { ServerFetch } from "./fetch"
|
|
20
|
+
import type { ServerOptions } from "./options"
|
|
21
|
+
import { withoutParentSpan } from "./request-tracing"
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The workerd runtime profile: boots opencode core and server inside a
|
|
25
|
+
* Cloudflare Durable Object, with every intentionally-local service replaced
|
|
26
|
+
* or disabled.
|
|
27
|
+
*
|
|
28
|
+
* - Database runs on the injected `DurableObjectStorage` SQLite.
|
|
29
|
+
* - `Workspace` is configured with `keepWarm: 0`, `pollInterval: null`, and
|
|
30
|
+
* `storage.setAlarm` scheduling so the Durable Object can hibernate at zero
|
|
31
|
+
* idle cost. Callers forward the Durable Object's `alarm()` method to
|
|
32
|
+
* `handler.alarm()` (or `opencode.alarm()` via `@zyro-sec/sdk/workerd`).
|
|
33
|
+
* - Watcher and fff are disabled through their existing option flags; pty, fff,
|
|
34
|
+
* and photon native modules resolve to inert stubs under the `workerd` bundle
|
|
35
|
+
* condition.
|
|
36
|
+
* - Bare locations use a typed no-execution-plane process spawner; FileSystem
|
|
37
|
+
* and FileSystemSearch route through Environment (working on attached remote
|
|
38
|
+
* workspaces and failing cleanly on bare locations). Pty fails with a clear
|
|
39
|
+
* defect; Npm fails package installs with a typed workerd error; Snapshot and
|
|
40
|
+
* Vcs degrade to no-op results.
|
|
41
|
+
* - Blob storage and video generation report themselves unsupported: blobs are files on a local disk.
|
|
42
|
+
* - Config is injected as a string (no filesystem); plugin discovery is
|
|
43
|
+
* precompiled-only, and stdio MCP reports the same no-plane failure as Shell.
|
|
44
|
+
*
|
|
45
|
+
* Bundle with the `workerd` condition, e.g.
|
|
46
|
+
* `bun build src/workerd.ts --conditions=workerd --target=node`
|
|
47
|
+
* (see `script/workerd-probe.ts`).
|
|
48
|
+
*/
|
|
49
|
+
export interface Options {
|
|
50
|
+
/** Durable Object storage whose SQLite database backs the opencode database. */
|
|
51
|
+
readonly storage: DurableObjectStorage
|
|
52
|
+
readonly app?: ServerOptions["app"]
|
|
53
|
+
readonly password?: string
|
|
54
|
+
/** Inline opencode config content (JSON), same as `ServerOptions.config.content`. */
|
|
55
|
+
readonly config?: { readonly content?: string }
|
|
56
|
+
/** models.dev catalog options; the bundled snapshot is the boot-time floor either way. */
|
|
57
|
+
readonly models?: ServerOptions["models"]
|
|
58
|
+
/** Replaces `globalThis.fetch` for OpenCode's own HTTP requests, e.g. to route them through a Service Binding. */
|
|
59
|
+
readonly fetch?: ServerOptions["fetch"]
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface Handler {
|
|
63
|
+
(request: Request): Promise<Response>
|
|
64
|
+
/** Suspends any workspaces past their idle threshold; call from the Durable Object's `alarm()` method. */
|
|
65
|
+
readonly alarm: () => Promise<void>
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Builds the web-standard fetch + alarm handler for a Durable Object. The
|
|
70
|
+
* application layer builds eagerly in the caller's scope, so hold it in the
|
|
71
|
+
* Durable Object instance rather than per request.
|
|
72
|
+
*
|
|
73
|
+
* Callers must forward the Durable Object's `alarm()` lifecycle method to
|
|
74
|
+
* `handler.alarm()`: this profile disables background idle polling so the
|
|
75
|
+
* isolate can hibernate at zero idle cost.
|
|
76
|
+
*/
|
|
77
|
+
export const create = Effect.fn("ServerWorkerd.create")(function* (options: Options) {
|
|
78
|
+
// Eviction can kill the isolate between a turn's Started and terminal events with no
|
|
79
|
+
// teardown. The write-ahead execution claim plus ServerFetch.make's boot-time resume
|
|
80
|
+
// recovers such orphaned turns by replaying the drain from durable history on the next wake.
|
|
81
|
+
const server = yield* ServerFetch.makeWithContext(serverOptions(options), {
|
|
82
|
+
overrides: replacements(options),
|
|
83
|
+
})
|
|
84
|
+
const run = Effect.runPromiseWith(yield* withoutParentSpan(Effect.context()))
|
|
85
|
+
const workspace = Context.get(server.context, Workspace.Service)
|
|
86
|
+
const handler: Handler = Object.assign(server.handler, {
|
|
87
|
+
alarm: () => run(Effect.asVoid(workspace.suspendIdle())),
|
|
88
|
+
})
|
|
89
|
+
return handler
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
export function serverOptions(options: Options): ServerOptions {
|
|
93
|
+
return {
|
|
94
|
+
app: options.app,
|
|
95
|
+
password: options.password,
|
|
96
|
+
fs: { filewatcher: false, fff: false },
|
|
97
|
+
// Durable event history is how a turn orphaned by eviction is recovered:
|
|
98
|
+
// the boot-time resume replays it. A runtime that dies without teardown
|
|
99
|
+
// cannot opt out of it, so this is not exposed as an option.
|
|
100
|
+
events: { persist: true },
|
|
101
|
+
config: { content: options.config?.content },
|
|
102
|
+
models: options.models,
|
|
103
|
+
fetch: options.fetch,
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** The workerd replacement graph, applied after the standard server replacements. */
|
|
108
|
+
export function replacements(options: Options): LayerNode.Replacements {
|
|
109
|
+
return [
|
|
110
|
+
Database.node.replace(Database.configuredClient(sqliteLayer({ storage: options.storage }))),
|
|
111
|
+
Identity.node.replace(Identity.kvNode),
|
|
112
|
+
Workspace.node.replace(
|
|
113
|
+
Workspace.configured({
|
|
114
|
+
keepWarm: 0,
|
|
115
|
+
pollInterval: null,
|
|
116
|
+
onIdleScheduled: (atMs) => Effect.tryPromise(() => options.storage.setAlarm(atMs)),
|
|
117
|
+
}),
|
|
118
|
+
),
|
|
119
|
+
CrossSpawnSpawner.node.replace(EnvironmentUnavailable.layer),
|
|
120
|
+
Snapshot.node.replace(Snapshot.noopLayer),
|
|
121
|
+
Vcs.node.replace(vcsLayer),
|
|
122
|
+
Pty.node.replace(ptyLayer),
|
|
123
|
+
Npm.node.replace(npmLayer),
|
|
124
|
+
// Blobs need a local `blobs/` folder, which a Durable Object doesn't have.
|
|
125
|
+
BlobStore.node.replace(BlobStore.unsupportedLayer),
|
|
126
|
+
VideoGeneration.node.replace(VideoGeneration.unsupportedLayer),
|
|
127
|
+
// Precompiled (internal and SDK) plugins only: no plugin-directory scan, npm
|
|
128
|
+
// install, or import of plugin code from disk.
|
|
129
|
+
ConfigPluginSource.node.replace(ConfigPluginSource.empty),
|
|
130
|
+
]
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const unavailable = (what: string) => Effect.die(new Error(`${what} is unavailable in the workerd profile`))
|
|
134
|
+
|
|
135
|
+
const npmUnavailable = (what: string, pkg: string) =>
|
|
136
|
+
Effect.fail(
|
|
137
|
+
new Npm.InstallFailedError({
|
|
138
|
+
add: [pkg],
|
|
139
|
+
dir: "",
|
|
140
|
+
cause: new Error(`${what} is unavailable in the workerd profile`),
|
|
141
|
+
}),
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
const npmLayer = Layer.succeed(
|
|
145
|
+
Npm.Service,
|
|
146
|
+
Npm.Service.of({
|
|
147
|
+
add: (pkg) => npmUnavailable("Npm.add", pkg),
|
|
148
|
+
resolve: (name) => Effect.succeed({ directory: "", name }),
|
|
149
|
+
check: () => Effect.succeed(false),
|
|
150
|
+
update: (pkg) => npmUnavailable("Npm.update", pkg),
|
|
151
|
+
follows: () => Effect.succeed(false),
|
|
152
|
+
reject: () => Effect.succeed(false),
|
|
153
|
+
which: () => Effect.undefined,
|
|
154
|
+
}),
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
// Vcs degrades to empty results, matching its behavior for locations without a
|
|
158
|
+
// supported VCS, so read-only clients never need to special-case this runtime.
|
|
159
|
+
const vcsLayer = Layer.succeed(
|
|
160
|
+
Vcs.Service,
|
|
161
|
+
Vcs.Service.of({
|
|
162
|
+
base: () => Effect.succeed(null),
|
|
163
|
+
initialize: () => Effect.fail(new Vcs.InitializeError({ kind: "unsupported" })),
|
|
164
|
+
transform: () => Effect.succeed({ dispose: Effect.void }),
|
|
165
|
+
reload: () => Effect.void,
|
|
166
|
+
info: () => Effect.succeed({ branch: {} }),
|
|
167
|
+
branches: () => Effect.succeed([]),
|
|
168
|
+
status: () => Effect.succeed([]),
|
|
169
|
+
diff: () => Effect.succeed([]),
|
|
170
|
+
}),
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
const ptyLayer = Layer.succeed(
|
|
174
|
+
Pty.Service,
|
|
175
|
+
Pty.Service.of({
|
|
176
|
+
list: () => Effect.succeed([]),
|
|
177
|
+
get: (ptyID) => Effect.fail(new Pty.NotFoundError({ ptyID })),
|
|
178
|
+
create: () => unavailable("Pty.create"),
|
|
179
|
+
update: (ptyID) => Effect.fail(new Pty.NotFoundError({ ptyID })),
|
|
180
|
+
remove: (ptyID) => Effect.fail(new Pty.NotFoundError({ ptyID })),
|
|
181
|
+
write: (ptyID) => Effect.fail(new Pty.NotFoundError({ ptyID })),
|
|
182
|
+
attach: (ptyID) => Effect.fail(new Pty.NotFoundError({ ptyID })),
|
|
183
|
+
}),
|
|
184
|
+
)
|