@zyro-sec/server 1.0.2 → 1.0.4

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 (130) hide show
  1. package/package.json +8 -8
  2. package/script/build.ts +28 -28
  3. package/script/pack.ts +5 -5
  4. package/script/workerd-probe.ts +59 -59
  5. package/src/api.ts +12 -12
  6. package/src/auth.ts +70 -70
  7. package/src/content-headers.ts +32 -32
  8. package/src/cors.ts +34 -34
  9. package/src/event-feed.ts +93 -93
  10. package/src/fetch.ts +67 -67
  11. package/src/handlers/agent.ts +23 -23
  12. package/src/handlers/artifact.ts +242 -242
  13. package/src/handlers/automation.ts +63 -63
  14. package/src/handlers/blob.ts +55 -55
  15. package/src/handlers/command.ts +8 -8
  16. package/src/handlers/config.ts +26 -26
  17. package/src/handlers/credential.ts +87 -87
  18. package/src/handlers/debug.ts +57 -57
  19. package/src/handlers/event.ts +38 -38
  20. package/src/handlers/form.ts +15 -15
  21. package/src/handlers/fs.ts +180 -180
  22. package/src/handlers/generate.ts +117 -117
  23. package/src/handlers/integration.ts +310 -310
  24. package/src/handlers/job.ts +29 -29
  25. package/src/handlers/location.ts +33 -33
  26. package/src/handlers/machine.ts +336 -336
  27. package/src/handlers/mcp.ts +160 -160
  28. package/src/handlers/media.ts +44 -44
  29. package/src/handlers/message.ts +82 -82
  30. package/src/handlers/migration.ts +13 -13
  31. package/src/handlers/model.ts +25 -25
  32. package/src/handlers/permission.ts +131 -131
  33. package/src/handlers/persistent-pty.ts +285 -285
  34. package/src/handlers/plugin.ts +97 -97
  35. package/src/handlers/project.ts +23 -23
  36. package/src/handlers/provider.ts +32 -32
  37. package/src/handlers/pty-socket.ts +47 -47
  38. package/src/handlers/pty.ts +181 -181
  39. package/src/handlers/push.ts +67 -67
  40. package/src/handlers/reference.ts +8 -8
  41. package/src/handlers/rpc.ts +31 -31
  42. package/src/handlers/server.ts +58 -58
  43. package/src/handlers/session-error.ts +47 -47
  44. package/src/handlers/session.ts +722 -722
  45. package/src/handlers/shell.ts +72 -72
  46. package/src/handlers/skill.ts +34 -34
  47. package/src/handlers/usage.ts +23 -23
  48. package/src/handlers/vcs.ts +104 -104
  49. package/src/handlers/voice.ts +50 -50
  50. package/src/handlers/websearch.ts +50 -50
  51. package/src/handlers/worktree.ts +60 -60
  52. package/src/handlers.ts +69 -69
  53. package/src/location.ts +86 -86
  54. package/src/media-uri.ts +13 -13
  55. package/src/middleware/authorization.ts +111 -111
  56. package/src/middleware/defect-response.ts +39 -39
  57. package/src/middleware/form-location.ts +44 -44
  58. package/src/middleware/schema-error.ts +49 -49
  59. package/src/middleware/session-location.ts +30 -30
  60. package/src/options.ts +61 -61
  61. package/src/pairing.ts +36 -36
  62. package/src/process.ts +274 -274
  63. package/src/range.ts +16 -16
  64. package/src/request-site.ts +36 -36
  65. package/src/request-tracing.ts +9 -9
  66. package/src/routes.ts +261 -261
  67. package/src/server-info.ts +41 -41
  68. package/src/service-status.ts +30 -30
  69. package/src/workerd.ts +184 -184
  70. package/test/fixture/mcp-starts.cjs +20 -20
  71. package/test/fixture/routes.ts +37 -37
  72. package/test/fixture/server.ts +20 -20
  73. package/test/fixture/worktree-delegate/index.ts +13 -13
  74. package/test/fixture/worktree-plugin/index.ts +47 -47
  75. package/tsconfig.build.json +15 -15
  76. package/tsconfig.json +11 -11
  77. package/test/artifact.test.ts +0 -224
  78. package/test/auth.test.ts +0 -24
  79. package/test/automation.test.ts +0 -315
  80. package/test/client-mcp.test.ts +0 -369
  81. package/test/codemode-api.test.ts +0 -88
  82. package/test/config.test.ts +0 -104
  83. package/test/cors.test.ts +0 -24
  84. package/test/defect-response.test.ts +0 -83
  85. package/test/event-feed.test.ts +0 -201
  86. package/test/fetch-option.test.ts +0 -104
  87. package/test/fetch.test.ts +0 -698
  88. package/test/flag-channel.test.ts +0 -126
  89. package/test/fs.test.ts +0 -439
  90. package/test/generate.test.ts +0 -132
  91. package/test/handler-policy.test.ts +0 -43
  92. package/test/heap-dump.test.ts +0 -137
  93. package/test/integration-policy.test.ts +0 -93
  94. package/test/job.test.ts +0 -186
  95. package/test/machine-iroh.test.ts +0 -259
  96. package/test/machine-link.test.ts +0 -1234
  97. package/test/machine-routes.test.ts +0 -198
  98. package/test/media.test.ts +0 -343
  99. package/test/message.test.ts +0 -105
  100. package/test/model.test.ts +0 -62
  101. package/test/options.test.ts +0 -42
  102. package/test/permission-saved.test.ts +0 -73
  103. package/test/persistent-pty.test.ts +0 -1007
  104. package/test/process.test.ts +0 -261
  105. package/test/provider.test.ts +0 -88
  106. package/test/pty-socket.property.test.ts +0 -240
  107. package/test/pty-socket.test.ts +0 -89
  108. package/test/pty-transport.test.ts +0 -200
  109. package/test/push-routes.test.ts +0 -157
  110. package/test/request-site.test.ts +0 -71
  111. package/test/request-tracing.test.ts +0 -87
  112. package/test/rpc-handler-errors.test.ts +0 -76
  113. package/test/schema-error.test.ts +0 -68
  114. package/test/service-status.test.ts +0 -34
  115. package/test/session-admit-location.test.ts +0 -92
  116. package/test/session-create.test.ts +0 -65
  117. package/test/session-diff.test.ts +0 -100
  118. package/test/session-form.test.ts +0 -50
  119. package/test/session-import.test.ts +0 -152
  120. package/test/session-instances.test.ts +0 -335
  121. package/test/session-unarchive.test.ts +0 -73
  122. package/test/session-update.test.ts +0 -66
  123. package/test/skill.test.ts +0 -57
  124. package/test/sse-failure.test.ts +0 -71
  125. package/test/usage.test.ts +0 -88
  126. package/test/vcs.test.ts +0 -356
  127. package/test/video-generate.test.ts +0 -131
  128. package/test/voice.test.ts +0 -170
  129. package/test/workerd.test.ts +0 -227
  130. package/test/worktree.test.ts +0 -333
@@ -1,9 +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
- )
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 CHANGED
@@ -1,261 +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
- }
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
+ }
@@ -1,41 +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"
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"