@zyro-sec/server 1.0.0 → 1.0.2
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 +15 -18
- 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
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { expect } from "bun:test"
|
|
2
|
+
import fs from "node:fs/promises"
|
|
3
|
+
import path from "node:path"
|
|
4
|
+
import { Global } from "@zyro-sec/util/global"
|
|
5
|
+
import { Effect } from "effect"
|
|
6
|
+
import { tmpdir } from "../../core/test/fixture/tmpdir"
|
|
7
|
+
import { it } from "../../core/test/lib/effect"
|
|
8
|
+
import { ServerFetch } from "../src/fetch"
|
|
9
|
+
|
|
10
|
+
const authorization = `Basic ${btoa("opencode:secret")}`
|
|
11
|
+
|
|
12
|
+
const server = Effect.fnUntraced(function* (root: string) {
|
|
13
|
+
const log = path.join(root, "log")
|
|
14
|
+
const handler = yield* ServerFetch.make(
|
|
15
|
+
{
|
|
16
|
+
app: { version: "test-version" },
|
|
17
|
+
password: "secret",
|
|
18
|
+
database: { path: ":memory:" },
|
|
19
|
+
config: { project: false, directory: path.join(root, "config") },
|
|
20
|
+
models: { fetch: false },
|
|
21
|
+
fs: { filewatcher: false },
|
|
22
|
+
},
|
|
23
|
+
{ overrides: [Global.node.replace(Global.layerWith({ config: path.join(root, "config"), log }))] },
|
|
24
|
+
)
|
|
25
|
+
const dump = (headers: Record<string, string> = { authorization }, directory?: string) =>
|
|
26
|
+
Effect.promise(() =>
|
|
27
|
+
handler(
|
|
28
|
+
new Request(
|
|
29
|
+
`http://opencode.local/api/debug/heap-dump${directory === undefined ? "" : `?directory=${encodeURIComponent(directory)}`}`,
|
|
30
|
+
{
|
|
31
|
+
method: "POST",
|
|
32
|
+
headers,
|
|
33
|
+
},
|
|
34
|
+
),
|
|
35
|
+
),
|
|
36
|
+
)
|
|
37
|
+
return { log, dump }
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
// Each snapshot serializes the whole test process heap, which takes seconds on Windows CI.
|
|
41
|
+
it.live(
|
|
42
|
+
"writes completed private snapshots of the server process, one at a time",
|
|
43
|
+
() =>
|
|
44
|
+
Effect.gen(function* () {
|
|
45
|
+
const root = yield* Effect.acquireDisposable(Effect.promise(() => tmpdir("opencode-heap-dump-")))
|
|
46
|
+
const api = yield* server(root.path)
|
|
47
|
+
|
|
48
|
+
expect((yield* api.dump({})).status).toBe(401)
|
|
49
|
+
|
|
50
|
+
const responses = yield* Effect.all([api.dump(), api.dump()], { concurrency: "unbounded" })
|
|
51
|
+
expect(responses.map((response) => response.status)).toEqual([200, 200])
|
|
52
|
+
const results = yield* Effect.promise(() =>
|
|
53
|
+
Promise.all(
|
|
54
|
+
responses.map(
|
|
55
|
+
(response): Promise<{ path: string; pid: number; memory: Record<string, number> }> => response.json(),
|
|
56
|
+
),
|
|
57
|
+
),
|
|
58
|
+
)
|
|
59
|
+
expect(new Set(results.map((result) => result.path)).size).toBe(2)
|
|
60
|
+
expect((yield* Effect.promise(() => fs.readdir(api.log))).toSorted()).toEqual(
|
|
61
|
+
results.map((result) => path.basename(result.path)).toSorted(),
|
|
62
|
+
)
|
|
63
|
+
for (const result of results) {
|
|
64
|
+
expect(result.pid).toBe(process.pid)
|
|
65
|
+
// Read before the snapshot: the process's footprint beyond the heap the file holds.
|
|
66
|
+
expect(Object.keys(result.memory).toSorted()).toEqual([
|
|
67
|
+
"arrayBuffers",
|
|
68
|
+
"external",
|
|
69
|
+
"heapTotal",
|
|
70
|
+
"heapUsed",
|
|
71
|
+
"rss",
|
|
72
|
+
])
|
|
73
|
+
expect(result.memory.rss).toBeGreaterThan(result.memory.heapUsed)
|
|
74
|
+
expect(path.dirname(result.path)).toBe(api.log)
|
|
75
|
+
expect(path.basename(result.path)).toStartWith(`heap-${process.pid}-`)
|
|
76
|
+
if (process.platform !== "win32")
|
|
77
|
+
expect((yield* Effect.promise(() => fs.stat(result.path))).mode & 0o777).toBe(0o600)
|
|
78
|
+
const snapshot = yield* Effect.promise(() => Bun.file(result.path).json())
|
|
79
|
+
expect(snapshot.snapshot.node_count).toBeGreaterThan(0)
|
|
80
|
+
expect(snapshot.snapshot.meta.node_fields).toContain("self_size")
|
|
81
|
+
}
|
|
82
|
+
}),
|
|
83
|
+
60_000,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
it.live(
|
|
87
|
+
"reports a failed write without blocking later snapshots",
|
|
88
|
+
() =>
|
|
89
|
+
Effect.gen(function* () {
|
|
90
|
+
const root = yield* Effect.acquireDisposable(Effect.promise(() => tmpdir("opencode-heap-dump-")))
|
|
91
|
+
const api = yield* server(root.path)
|
|
92
|
+
// A file where the log directory should be makes the write fail.
|
|
93
|
+
yield* Effect.promise(() => fs.rm(api.log, { recursive: true }))
|
|
94
|
+
yield* Effect.promise(() => fs.writeFile(api.log, ""))
|
|
95
|
+
|
|
96
|
+
const failed = yield* api.dump()
|
|
97
|
+
expect(failed.status).toBe(500)
|
|
98
|
+
expect(yield* Effect.promise(() => failed.json())).toMatchObject({
|
|
99
|
+
_tag: "UnknownError",
|
|
100
|
+
// The filesystem's own reason, naming the path it could not create.
|
|
101
|
+
message: expect.stringMatching(
|
|
102
|
+
new RegExp(`^Failed to write heap snapshot: E[A-Z]+: .*${RegExp.escape(api.log)}`),
|
|
103
|
+
),
|
|
104
|
+
ref: expect.stringMatching(/^err_/),
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
yield* Effect.promise(() => fs.rm(api.log))
|
|
108
|
+
const recovered = yield* api.dump()
|
|
109
|
+
expect(recovered.status).toBe(200)
|
|
110
|
+
const result: { path: string } = yield* Effect.promise(() => recovered.json())
|
|
111
|
+
expect(yield* Effect.promise(() => Bun.file(result.path).exists())).toBe(true)
|
|
112
|
+
}),
|
|
113
|
+
30_000,
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
it.live(
|
|
117
|
+
"writes into a requested directory, creating it, and rejects a relative one",
|
|
118
|
+
() =>
|
|
119
|
+
Effect.gen(function* () {
|
|
120
|
+
const root = yield* Effect.acquireDisposable(Effect.promise(() => tmpdir("opencode-heap-dump-")))
|
|
121
|
+
const api = yield* server(root.path)
|
|
122
|
+
const directory = path.join(root.path, "capture", "nested")
|
|
123
|
+
|
|
124
|
+
const relative = yield* api.dump(undefined, "capture")
|
|
125
|
+
expect(relative.status).toBe(400)
|
|
126
|
+
expect(yield* Effect.promise(() => relative.json())).toMatchObject({ _tag: "InvalidRequestError" })
|
|
127
|
+
|
|
128
|
+
const written = yield* api.dump(undefined, directory)
|
|
129
|
+
expect(written.status).toBe(200)
|
|
130
|
+
const result: { path: string } = yield* Effect.promise(() => written.json())
|
|
131
|
+
expect(path.dirname(result.path)).toBe(directory)
|
|
132
|
+
expect(yield* Effect.promise(() => fs.readdir(directory))).toEqual([path.basename(result.path)])
|
|
133
|
+
const logged = yield* Effect.promise(() => fs.readdir(api.log).catch(() => []))
|
|
134
|
+
expect(logged.filter((file) => file.endsWith(".heapsnapshot"))).toEqual([])
|
|
135
|
+
}),
|
|
136
|
+
30_000,
|
|
137
|
+
)
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { expect } from "bun:test"
|
|
2
|
+
import { Context, Effect, Layer } from "effect"
|
|
3
|
+
import { HttpEffect, HttpRouter, HttpServer } from "effect/http"
|
|
4
|
+
import { tmpdirScoped } from "../../core/test/fixture/tmpdir"
|
|
5
|
+
import { it } from "../../core/test/lib/effect"
|
|
6
|
+
import { createRoutes } from "../src/routes"
|
|
7
|
+
import { pluginsLoaded } from "./fixture/routes"
|
|
8
|
+
|
|
9
|
+
it.live("integration policy filters /connect and blocks denied integrations and providers", () =>
|
|
10
|
+
Effect.gen(function* () {
|
|
11
|
+
const tmp = yield* tmpdirScoped("opencode-integration-policy-")
|
|
12
|
+
const context = yield* Layer.build(
|
|
13
|
+
createRoutes({
|
|
14
|
+
password: "secret",
|
|
15
|
+
database: { path: ":memory:" },
|
|
16
|
+
models: { fetch: false },
|
|
17
|
+
fs: { filewatcher: false },
|
|
18
|
+
config: {
|
|
19
|
+
directory: tmp.path,
|
|
20
|
+
project: false,
|
|
21
|
+
content: JSON.stringify({
|
|
22
|
+
providers: {
|
|
23
|
+
custom: {
|
|
24
|
+
name: "Configured Custom Provider",
|
|
25
|
+
package: "@zyro-sec/ai/providers/openai-compatible",
|
|
26
|
+
settings: { apiKey: "secret" },
|
|
27
|
+
models: { chat: {} },
|
|
28
|
+
},
|
|
29
|
+
},
|
|
30
|
+
mcp: { servers: { wiki: { type: "remote", url: "http://127.0.0.1:9/mcp" } } },
|
|
31
|
+
policies: [
|
|
32
|
+
{ action: "integration.connect", resource: "*", effect: "deny" },
|
|
33
|
+
{ action: "integration.connect", resource: "opencode", effect: "allow" },
|
|
34
|
+
{ action: "integration.use", resource: "*", effect: "deny" },
|
|
35
|
+
{ action: "integration.use", resource: "opencode#org_01M3CAP8H43Z49CER6NT0Y3ZF1", effect: "allow" },
|
|
36
|
+
],
|
|
37
|
+
}),
|
|
38
|
+
},
|
|
39
|
+
}).pipe(Layer.provide(HttpServer.layerServices)),
|
|
40
|
+
)
|
|
41
|
+
const handler = Context.get(context, HttpRouter.HttpRouter)
|
|
42
|
+
.asHttpEffect()
|
|
43
|
+
.pipe(HttpEffect.toWebHandlerWith(context))
|
|
44
|
+
const request = (method: "GET" | "POST", route: string, body?: unknown) =>
|
|
45
|
+
Effect.promise(async (signal) => {
|
|
46
|
+
const url = new URL(route, "http://opencode.local")
|
|
47
|
+
url.searchParams.set("location[directory]", tmp.path)
|
|
48
|
+
const response = await handler(
|
|
49
|
+
new Request(url, {
|
|
50
|
+
method,
|
|
51
|
+
headers: {
|
|
52
|
+
authorization: `Basic ${btoa("opencode:secret")}`,
|
|
53
|
+
...(body === undefined ? {} : { "content-type": "application/json" }),
|
|
54
|
+
},
|
|
55
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
56
|
+
signal,
|
|
57
|
+
}),
|
|
58
|
+
)
|
|
59
|
+
return { status: response.status, body: response.status === 204 ? undefined : await response.json() }
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
yield* pluginsLoaded(context, tmp.path)
|
|
63
|
+
const integrations = yield* request("GET", "/api/integration")
|
|
64
|
+
expect(integrations.status).toBe(200)
|
|
65
|
+
// MCP sign-ins are outside integration policy; `mcp.use` governs MCP servers.
|
|
66
|
+
const listed: { id: string; metadata?: { source?: string } }[] = integrations.body.data
|
|
67
|
+
expect(listed.filter((integration) => integration.metadata?.source !== "mcp").map((item) => item.id)).toEqual([
|
|
68
|
+
"opencode",
|
|
69
|
+
])
|
|
70
|
+
const mcp = listed.find((integration) => integration.metadata?.source === "mcp")
|
|
71
|
+
expect(mcp?.id).toStartWith("mcp_")
|
|
72
|
+
const signIn = yield* request("POST", `/api/integration/${encodeURIComponent(mcp?.id ?? "")}/connect/oauth`, {
|
|
73
|
+
methodID: mcp?.id,
|
|
74
|
+
})
|
|
75
|
+
expect(signIn.body?.kind).not.toBe("integration_policy")
|
|
76
|
+
|
|
77
|
+
const denied = yield* request("POST", "/api/integration/anthropic/connect/key", { key: "sk-test" })
|
|
78
|
+
expect(denied.status).toBe(400)
|
|
79
|
+
expect(denied.body).toMatchObject({ _tag: "InvalidRequestError", kind: "integration_policy" })
|
|
80
|
+
const credential = yield* request("POST", "/api/credential", {
|
|
81
|
+
integrationID: "anthropic",
|
|
82
|
+
value: { type: "key", key: "sk-test" },
|
|
83
|
+
})
|
|
84
|
+
expect(credential.status).toBe(400)
|
|
85
|
+
expect(credential.body).toMatchObject({ _tag: "InvalidRequestError", kind: "integration_policy" })
|
|
86
|
+
expect((yield* request("GET", "/api/credential")).body.data).toEqual([])
|
|
87
|
+
const wellknown = yield* request("POST", "/api/experimental/integration/wellknown", { url: "https://ai.acme.com" })
|
|
88
|
+
expect(wellknown.body).toMatchObject({ kind: "integration_policy" })
|
|
89
|
+
|
|
90
|
+
// The signed-out free tier and the authored provider are both denied.
|
|
91
|
+
expect((yield* request("GET", "/api/provider")).body.data).toEqual([])
|
|
92
|
+
}),
|
|
93
|
+
)
|
package/test/job.test.ts
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import fs from "node:fs/promises"
|
|
2
|
+
import path from "node:path"
|
|
3
|
+
import { expect } from "bun:test"
|
|
4
|
+
import { OpenCode } from "@zyro-sec/client"
|
|
5
|
+
import { Database } from "@zyro-sec/core/database/database"
|
|
6
|
+
import { Job } from "@zyro-sec/core/job"
|
|
7
|
+
import { Session } from "@zyro-sec/core/session"
|
|
8
|
+
import { makeGlobalNode } from "@zyro-sec/util/effect/app-node"
|
|
9
|
+
import { Deferred, Effect, Layer } from "effect"
|
|
10
|
+
import { tmpdirScoped } from "../../core/test/fixture/tmpdir"
|
|
11
|
+
import { it } from "../../core/test/lib/effect"
|
|
12
|
+
import { ServerFetch } from "../src/fetch"
|
|
13
|
+
|
|
14
|
+
const client = (handler: (request: Request) => Promise<Response>) =>
|
|
15
|
+
OpenCode.make({
|
|
16
|
+
baseUrl: "http://opencode.local",
|
|
17
|
+
fetch: Object.assign((input: string | URL | Request, init?: RequestInit) => handler(new Request(input, init)), {
|
|
18
|
+
preconnect: fetch.preconnect,
|
|
19
|
+
}),
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
it.live("lists background jobs by session, kind, and descendants until completion notice clears them", () =>
|
|
23
|
+
Effect.gen(function* () {
|
|
24
|
+
const dir = (yield* tmpdirScoped("opencode-job-api-")).path
|
|
25
|
+
const global = path.join(dir, "global")
|
|
26
|
+
const project = path.join(dir, "project")
|
|
27
|
+
yield* Effect.promise(() => Promise.all([global, project].map((item) => fs.mkdir(item, { recursive: true }))))
|
|
28
|
+
|
|
29
|
+
const captured = yield* Deferred.make<Job.Interface>()
|
|
30
|
+
const jobNode = makeGlobalNode({
|
|
31
|
+
service: Job.Service,
|
|
32
|
+
layer: Layer.effect(
|
|
33
|
+
Job.Service,
|
|
34
|
+
Job.make.pipe(Effect.tap((service) => Deferred.succeed(captured, service))),
|
|
35
|
+
),
|
|
36
|
+
deps: [Database.node],
|
|
37
|
+
})
|
|
38
|
+
const handler = yield* ServerFetch.make(
|
|
39
|
+
{
|
|
40
|
+
app: { version: "test" },
|
|
41
|
+
database: { path: path.join(dir, "opencode.db") },
|
|
42
|
+
config: { directory: global, project: false, claude: false },
|
|
43
|
+
models: { fetch: false },
|
|
44
|
+
fs: { filewatcher: false },
|
|
45
|
+
},
|
|
46
|
+
{ overrides: [Job.node.replace(jobNode)] },
|
|
47
|
+
)
|
|
48
|
+
const jobs = yield* Deferred.await(captured)
|
|
49
|
+
const api = client(handler)
|
|
50
|
+
|
|
51
|
+
const root = yield* Effect.promise(() => api.session.create({ location: { directory: project } }))
|
|
52
|
+
const child = yield* Effect.promise(() => api.session.create({ parentID: root.id }))
|
|
53
|
+
const other = yield* Effect.promise(() => api.session.create({ location: { directory: project } }))
|
|
54
|
+
const rootID = Session.ID.make(root.id)
|
|
55
|
+
const childID = Session.ID.make(child.id)
|
|
56
|
+
const otherID = Session.ID.make(other.id)
|
|
57
|
+
|
|
58
|
+
yield* Effect.promise(async () => {
|
|
59
|
+
await expect(api.experimental.job.list({ sessionID: Session.ID.create() })).rejects.toMatchObject({
|
|
60
|
+
_tag: "SessionNotFoundError",
|
|
61
|
+
})
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
const fgGate = yield* Deferred.make<string>()
|
|
65
|
+
const shellGate = yield* Deferred.make<string>()
|
|
66
|
+
const subagentGate = yield* Deferred.make<string>()
|
|
67
|
+
const childShellGate = yield* Deferred.make<string>()
|
|
68
|
+
const imageGate = yield* Deferred.make<string>()
|
|
69
|
+
|
|
70
|
+
// Foreground jobs stay invisible until moved to the background.
|
|
71
|
+
yield* jobs.start({
|
|
72
|
+
id: "sh_fg",
|
|
73
|
+
type: "shell",
|
|
74
|
+
title: "echo fg",
|
|
75
|
+
recovery: { kind: "shell", sessionID: rootID, shellID: "sh_fg", command: "echo fg" },
|
|
76
|
+
run: Deferred.await(fgGate),
|
|
77
|
+
})
|
|
78
|
+
expect(yield* Effect.promise(() => api.experimental.job.list({ sessionID: root.id }))).toEqual([])
|
|
79
|
+
|
|
80
|
+
yield* jobs.start({
|
|
81
|
+
id: "sh_root",
|
|
82
|
+
type: "shell",
|
|
83
|
+
title: "bun test",
|
|
84
|
+
recovery: { kind: "shell", sessionID: rootID, shellID: "sh_root", command: "bun test" },
|
|
85
|
+
run: Deferred.await(shellGate),
|
|
86
|
+
})
|
|
87
|
+
const shellBg = yield* jobs.background("sh_root")
|
|
88
|
+
|
|
89
|
+
yield* jobs.start({
|
|
90
|
+
id: child.id,
|
|
91
|
+
type: "subagent",
|
|
92
|
+
title: "audit routes",
|
|
93
|
+
recovery: {
|
|
94
|
+
kind: "subagent",
|
|
95
|
+
parentSessionID: rootID,
|
|
96
|
+
childSessionID: childID,
|
|
97
|
+
agent: "explore",
|
|
98
|
+
description: "audit routes",
|
|
99
|
+
},
|
|
100
|
+
run: Deferred.await(subagentGate),
|
|
101
|
+
})
|
|
102
|
+
const subagentBg = yield* jobs.background(child.id)
|
|
103
|
+
|
|
104
|
+
yield* jobs.start({
|
|
105
|
+
id: "sh_child",
|
|
106
|
+
type: "shell",
|
|
107
|
+
title: "pytest",
|
|
108
|
+
recovery: { kind: "shell", sessionID: childID, shellID: "sh_child", command: "pytest" },
|
|
109
|
+
run: Deferred.await(childShellGate),
|
|
110
|
+
})
|
|
111
|
+
const childShellBg = yield* jobs.background("sh_child")
|
|
112
|
+
|
|
113
|
+
yield* jobs.start({
|
|
114
|
+
id: "img_other",
|
|
115
|
+
type: "generate_image",
|
|
116
|
+
title: "diagram",
|
|
117
|
+
recovery: { kind: "image", sessionID: otherID, path: "/tmp/diagram", model: "openai/gpt-image-1" },
|
|
118
|
+
run: Deferred.await(imageGate),
|
|
119
|
+
})
|
|
120
|
+
const imageBg = yield* jobs.background("img_other")
|
|
121
|
+
|
|
122
|
+
// Direct session query returns only root's own shell + subagent jobs, not child's shell or other's image.
|
|
123
|
+
const direct = yield* Effect.promise(() => api.experimental.job.list({ sessionID: root.id }))
|
|
124
|
+
expect(direct).toMatchObject([
|
|
125
|
+
{ kind: "shell", id: "sh_root", sessionID: root.id, status: "running", shellID: "sh_root", command: "bun test" },
|
|
126
|
+
{
|
|
127
|
+
kind: "subagent",
|
|
128
|
+
id: child.id,
|
|
129
|
+
sessionID: root.id,
|
|
130
|
+
status: "running",
|
|
131
|
+
childSessionID: child.id,
|
|
132
|
+
agent: "explore",
|
|
133
|
+
description: "audit routes",
|
|
134
|
+
},
|
|
135
|
+
])
|
|
136
|
+
|
|
137
|
+
// Kind filter selects shell jobs for that session directly.
|
|
138
|
+
const rootShells = yield* Effect.promise(() => api.experimental.job.list({ sessionID: root.id, kind: "shell" }))
|
|
139
|
+
expect(rootShells.map((item) => item.id)).toEqual(["sh_root"])
|
|
140
|
+
|
|
141
|
+
// Descendants includes child session jobs while excluding unrelated sessions.
|
|
142
|
+
const withDescendants = yield* Effect.promise(() =>
|
|
143
|
+
api.experimental.job.list({ sessionID: root.id, descendants: true }),
|
|
144
|
+
)
|
|
145
|
+
expect(withDescendants.map((item) => item.id)).toEqual(["sh_root", child.id, "sh_child"])
|
|
146
|
+
|
|
147
|
+
// Unfiltered list returns every unconsumed background job on the server.
|
|
148
|
+
const all = yield* Effect.promise(() => api.experimental.job.list())
|
|
149
|
+
expect(all.map((item) => item.id)).toEqual(["sh_root", child.id, "sh_child", "img_other"])
|
|
150
|
+
|
|
151
|
+
// Settled background work stays visible as "completed" until completeBackground clears its notice.
|
|
152
|
+
yield* Deferred.succeed(shellGate, "passed")
|
|
153
|
+
yield* jobs.wait({ id: "sh_root" })
|
|
154
|
+
const settled = yield* Effect.promise(() => api.experimental.job.list({ sessionID: root.id, kind: "shell" }))
|
|
155
|
+
expect(settled).toMatchObject([
|
|
156
|
+
{
|
|
157
|
+
kind: "shell",
|
|
158
|
+
id: "sh_root",
|
|
159
|
+
status: "completed",
|
|
160
|
+
time: { started: expect.any(Number), completed: expect.any(Number) },
|
|
161
|
+
},
|
|
162
|
+
])
|
|
163
|
+
expect(
|
|
164
|
+
(yield* Effect.promise(() => api.experimental.job.list({ sessionID: root.id, status: "running" }))).map(
|
|
165
|
+
(item) => item.id,
|
|
166
|
+
),
|
|
167
|
+
).toEqual([child.id])
|
|
168
|
+
expect(
|
|
169
|
+
(yield* Effect.promise(() => api.experimental.job.list({ sessionID: root.id, status: "completed" }))).map(
|
|
170
|
+
(item) => item.id,
|
|
171
|
+
),
|
|
172
|
+
).toEqual(["sh_root"])
|
|
173
|
+
|
|
174
|
+
if (shellBg?.notificationID) yield* jobs.completeBackground(shellBg.notificationID)
|
|
175
|
+
expect(yield* Effect.promise(() => api.experimental.job.list({ sessionID: root.id, kind: "shell" }))).toEqual([])
|
|
176
|
+
|
|
177
|
+
// Cleanup remaining test jobs.
|
|
178
|
+
yield* Deferred.succeed(fgGate, "done")
|
|
179
|
+
yield* Deferred.succeed(subagentGate, "done")
|
|
180
|
+
yield* Deferred.succeed(childShellGate, "done")
|
|
181
|
+
yield* Deferred.succeed(imageGate, "done")
|
|
182
|
+
if (subagentBg?.notificationID) yield* jobs.completeBackground(subagentBg.notificationID)
|
|
183
|
+
if (childShellBg?.notificationID) yield* jobs.completeBackground(childShellBg.notificationID)
|
|
184
|
+
if (imageBg?.notificationID) yield* jobs.completeBackground(imageBg.notificationID)
|
|
185
|
+
}),
|
|
186
|
+
)
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
import { expect } from "bun:test"
|
|
2
|
+
import { NodeHttpServer } from "@effect/platform-node"
|
|
3
|
+
import { OpenCode } from "@zyro-sec/client"
|
|
4
|
+
import { Environment } from "@zyro-sec/core/environment/index"
|
|
5
|
+
import { Identity } from "@zyro-sec/core/machine/identity"
|
|
6
|
+
import { Iroh } from "@zyro-sec/core/machine/iroh"
|
|
7
|
+
import loadBinding from "@zyro-sec/core/machine/iroh-binding"
|
|
8
|
+
import { Join } from "@zyro-sec/core/machine/join"
|
|
9
|
+
import { Link } from "@zyro-sec/core/machine/link"
|
|
10
|
+
import { Machines } from "@zyro-sec/core/machine/machines"
|
|
11
|
+
import { Global } from "@zyro-sec/util/global"
|
|
12
|
+
import { Context, Deferred, Effect, Exit, Layer, Option, Scope, Stream } from "effect"
|
|
13
|
+
import { HttpRouter, HttpServer, type HttpServerRequest, type HttpServerResponse } from "effect/http"
|
|
14
|
+
import { randomBytes } from "node:crypto"
|
|
15
|
+
import { createServer } from "node:http"
|
|
16
|
+
import { makeWorker } from "../../core/test/fixture/machine-worker"
|
|
17
|
+
import { tmpdirScoped } from "../../core/test/fixture/tmpdir"
|
|
18
|
+
import { it } from "../../core/test/lib/effect"
|
|
19
|
+
import { createRoutes } from "../src/routes"
|
|
20
|
+
|
|
21
|
+
// The link over Iroh, offline: the home binds on loopback with no relays or address lookup, and a second endpoint of
|
|
22
|
+
// the same binding, standing in for the worker, dials the home key at the home's bound address.
|
|
23
|
+
|
|
24
|
+
const ALPN = Array.from(new TextEncoder().encode("opencode-link/1"))
|
|
25
|
+
|
|
26
|
+
/** Deterministic read boundaries, without a native stream coalescing or splitting the fixture. */
|
|
27
|
+
const reading = (chunks: number[][]) => {
|
|
28
|
+
const unused = () => {
|
|
29
|
+
throw new Error("unexpected stream operation")
|
|
30
|
+
}
|
|
31
|
+
return Iroh.carrier(
|
|
32
|
+
{
|
|
33
|
+
recv: {
|
|
34
|
+
read: async () => chunks.shift() ?? [],
|
|
35
|
+
readExact: unused,
|
|
36
|
+
readToEnd: unused,
|
|
37
|
+
id: unused,
|
|
38
|
+
bytesRead: unused,
|
|
39
|
+
stop: unused,
|
|
40
|
+
receivedReset: unused,
|
|
41
|
+
},
|
|
42
|
+
send: {
|
|
43
|
+
write: unused,
|
|
44
|
+
writeAll: unused,
|
|
45
|
+
finish: unused,
|
|
46
|
+
reset: unused,
|
|
47
|
+
setPriority: unused,
|
|
48
|
+
priority: unused,
|
|
49
|
+
stopped: unused,
|
|
50
|
+
id: unused,
|
|
51
|
+
},
|
|
52
|
+
},
|
|
53
|
+
unused,
|
|
54
|
+
)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
it.effect("reads many Iroh messages intact and in order from one read", () =>
|
|
58
|
+
Effect.gen(function* () {
|
|
59
|
+
const messages = Array.from({ length: 900 }, (_, index) => {
|
|
60
|
+
const message = new Uint8Array(70).fill(index % 256)
|
|
61
|
+
new DataView(message.buffer).setUint16(0, index)
|
|
62
|
+
return message
|
|
63
|
+
})
|
|
64
|
+
const carrier = reading([messages.flatMap((message) => [0, message.length, ...message])])
|
|
65
|
+
const received = yield* Effect.forEach(messages, () => carrier.receive)
|
|
66
|
+
expect(received).toEqual(messages)
|
|
67
|
+
received[0][0] ^= 1
|
|
68
|
+
expect(received[1]).toEqual(messages[1])
|
|
69
|
+
expect(yield* carrier.receive.pipe(Effect.flip)).toEqual(new Link.Closed())
|
|
70
|
+
}),
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
it.effect("reassembles an Iroh message split across two reads after an earlier message", () =>
|
|
74
|
+
Effect.gen(function* () {
|
|
75
|
+
const carrier = reading([
|
|
76
|
+
[0, 3, 1, 2, 3, 0, 4, 4],
|
|
77
|
+
[5, 6, 7],
|
|
78
|
+
])
|
|
79
|
+
const first = yield* carrier.receive
|
|
80
|
+
expect(yield* carrier.receive).toEqual(Uint8Array.of(4, 5, 6, 7))
|
|
81
|
+
expect(first).toEqual(Uint8Array.of(1, 2, 3))
|
|
82
|
+
expect(yield* carrier.receive.pipe(Effect.flip)).toEqual(new Link.Closed())
|
|
83
|
+
}),
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
type Endpoint = Effect.Success<ReturnType<typeof Iroh.listen>>
|
|
87
|
+
|
|
88
|
+
/** The server's routes on a port of their own, counting every import of the Iroh binding. */
|
|
89
|
+
const home = Effect.fnUntraced(function* (machines: boolean) {
|
|
90
|
+
const directory = (yield* tmpdirScoped("opencode-machine-iroh-")).path
|
|
91
|
+
const server = createServer()
|
|
92
|
+
const http = yield* NodeHttpServer.make(() => server, { port: 0, host: "127.0.0.1" })
|
|
93
|
+
yield* Effect.addFinalizer(() => Effect.sync(() => server.closeAllConnections()))
|
|
94
|
+
const routes =
|
|
95
|
+
yield* Deferred.make<
|
|
96
|
+
Effect.Effect<HttpServerResponse.HttpServerResponse, unknown, HttpServerRequest.HttpServerRequest | Scope.Scope>
|
|
97
|
+
>()
|
|
98
|
+
yield* http.serve(Effect.flatten(Deferred.await(routes))).pipe(Effect.provide(NodeHttpServer.layerHttpServices))
|
|
99
|
+
const overrides = [
|
|
100
|
+
Global.node.replace(
|
|
101
|
+
Global.layerWith({
|
|
102
|
+
data: directory,
|
|
103
|
+
cache: directory,
|
|
104
|
+
config: directory,
|
|
105
|
+
state: directory,
|
|
106
|
+
tmp: directory,
|
|
107
|
+
bin: directory,
|
|
108
|
+
log: directory,
|
|
109
|
+
repos: directory,
|
|
110
|
+
}),
|
|
111
|
+
),
|
|
112
|
+
]
|
|
113
|
+
const state = { loads: 0, endpoint: undefined as Endpoint | undefined }
|
|
114
|
+
const options = {
|
|
115
|
+
password: "secret",
|
|
116
|
+
app: { version: "test-version" },
|
|
117
|
+
database: { path: ":memory:" },
|
|
118
|
+
models: { fetch: false },
|
|
119
|
+
config: { directory, project: false, content: JSON.stringify({ experimental: { machines } }) },
|
|
120
|
+
fs: { filewatcher: false },
|
|
121
|
+
}
|
|
122
|
+
const context = yield* Layer.build(
|
|
123
|
+
createRoutes(options, () => [], overrides).pipe(Layer.provideMerge(NodeHttpServer.layerHttpServices)),
|
|
124
|
+
).pipe(
|
|
125
|
+
Effect.provideService(Iroh.Testing, {
|
|
126
|
+
offline: true,
|
|
127
|
+
load: () => {
|
|
128
|
+
state.loads++
|
|
129
|
+
return loadBinding()
|
|
130
|
+
},
|
|
131
|
+
watch: (endpoint) => {
|
|
132
|
+
state.endpoint = endpoint
|
|
133
|
+
},
|
|
134
|
+
}),
|
|
135
|
+
)
|
|
136
|
+
yield* Deferred.succeed(routes, Context.get(context, HttpRouter.HttpRouter).asHttpEffect())
|
|
137
|
+
return {
|
|
138
|
+
state,
|
|
139
|
+
context,
|
|
140
|
+
machines: Context.get(context, Machines.Service),
|
|
141
|
+
api: OpenCode.make({
|
|
142
|
+
baseUrl: HttpServer.formatAddress(http.address),
|
|
143
|
+
headers: { authorization: `Basic ${btoa("opencode:secret")}` },
|
|
144
|
+
}),
|
|
145
|
+
}
|
|
146
|
+
})
|
|
147
|
+
|
|
148
|
+
/** A worker's endpoint on loopback, and a dial of the home key over it whose stream is the link's carrier. */
|
|
149
|
+
const workerEndpoint = Effect.fnUntraced(function* (home: Endpoint) {
|
|
150
|
+
const binding = yield* Effect.promise(() => loadBinding())
|
|
151
|
+
if (!binding) return yield* Effect.die(new Error("no Iroh build for this platform"))
|
|
152
|
+
const builder = binding.Endpoint.builder()
|
|
153
|
+
builder.applyMinimal()
|
|
154
|
+
builder.bindAddr("127.0.0.1:0")
|
|
155
|
+
const endpoint = yield* Effect.acquireRelease(
|
|
156
|
+
Effect.promise(() => builder.bind()),
|
|
157
|
+
(endpoint) => Effect.promise(() => endpoint.close()),
|
|
158
|
+
)
|
|
159
|
+
return (key: Uint8Array) =>
|
|
160
|
+
Effect.gen(function* () {
|
|
161
|
+
const address = new binding.EndpointAddr(binding.EndpointId.fromBytes(Array.from(key)), null, home.boundSockets())
|
|
162
|
+
const connection = yield* Effect.acquireRelease(
|
|
163
|
+
Effect.promise(() => endpoint.connect(address, ALPN)),
|
|
164
|
+
(connection) => Effect.sync(() => connection.close(0n, [])),
|
|
165
|
+
)
|
|
166
|
+
const stream = yield* Effect.promise(() => connection.openBi())
|
|
167
|
+
return { connection, carrier: Iroh.carrier(stream, () => connection.close(0n, [])) }
|
|
168
|
+
})
|
|
169
|
+
})
|
|
170
|
+
|
|
171
|
+
const until = Effect.fnUntraced(function* (condition: Effect.Effect<boolean>) {
|
|
172
|
+
const deadline = Date.now() + 10_000
|
|
173
|
+
while (!(yield* condition)) {
|
|
174
|
+
if (Date.now() > deadline) return yield* Effect.die(new Error("timed out"))
|
|
175
|
+
yield* Effect.sleep("10 millis")
|
|
176
|
+
}
|
|
177
|
+
})
|
|
178
|
+
|
|
179
|
+
it.live("pairs a worker over Iroh, carries its frames, and refuses a bad join with 1008", () =>
|
|
180
|
+
Effect.gen(function* () {
|
|
181
|
+
const server = yield* home(true)
|
|
182
|
+
yield* Effect.promise(() => server.api.experimental.machine.list())
|
|
183
|
+
expect(server.state.loads).toBe(0)
|
|
184
|
+
|
|
185
|
+
const added = yield* Effect.promise(() => server.api.experimental.machine.add({ name: "gpu", reach: [] }))
|
|
186
|
+
expect(server.state.loads).toBe(1)
|
|
187
|
+
const join = Option.getOrThrow(Join.decode(added.join))
|
|
188
|
+
expect(join.reach).toEqual([{ type: "iroh" }])
|
|
189
|
+
expect(added.reach).toEqual(join.reach)
|
|
190
|
+
const dial = yield* workerEndpoint(server.state.endpoint!)
|
|
191
|
+
|
|
192
|
+
// A stranger with a wrong secret: refused, and the home closes the connection with 1008.
|
|
193
|
+
const stranger = yield* dial(join.home)
|
|
194
|
+
const refused = yield* Link.connect(stranger.carrier, {
|
|
195
|
+
home: join.home,
|
|
196
|
+
identity: Identity.fromSeed(randomBytes(32)),
|
|
197
|
+
secret: randomBytes(32),
|
|
198
|
+
}).pipe(Effect.flip)
|
|
199
|
+
expect(refused._tag).toBe("Link.Refused")
|
|
200
|
+
expect(yield* Effect.promise(() => stranger.connection.closed())).toContain("1008")
|
|
201
|
+
|
|
202
|
+
// The worker pairs with the join secret, dialing the home key, and files go both ways over the link.
|
|
203
|
+
const identity = Identity.fromSeed(randomBytes(32))
|
|
204
|
+
const fake = yield* makeWorker({
|
|
205
|
+
connect: (connection) =>
|
|
206
|
+
Effect.scoped(
|
|
207
|
+
Effect.gen(function* () {
|
|
208
|
+
const dialed = yield* dial(join.home)
|
|
209
|
+
const linked = yield* Link.connect(dialed.carrier, { home: join.home, identity, secret: join.secret })
|
|
210
|
+
linked.send(connection.hello)
|
|
211
|
+
yield* Effect.raceFirst(
|
|
212
|
+
Stream.runForEach(linked.messages, (message) => Effect.sync(() => connection.send(message))),
|
|
213
|
+
Stream.runForEach(connection.messages, (message) => Effect.sync(() => linked.send(message))),
|
|
214
|
+
)
|
|
215
|
+
}),
|
|
216
|
+
),
|
|
217
|
+
})
|
|
218
|
+
yield* fake.restore
|
|
219
|
+
yield* until(Effect.map(server.machines.list(), (list) => list.some((machine) => machine.online)))
|
|
220
|
+
const listed = yield* Effect.promise(() => server.api.experimental.machine.list())
|
|
221
|
+
expect(listed[0].connection).toMatchObject({ kind: "iroh", path: "direct" })
|
|
222
|
+
expect(listed[0].connection?.rtt).toBeGreaterThanOrEqual(0)
|
|
223
|
+
const files = (yield* server.machines.get(Environment.ID.make("gpu"))).files
|
|
224
|
+
const bytes = randomBytes(200_000)
|
|
225
|
+
yield* files.write("/note.bin", bytes)
|
|
226
|
+
expect(Buffer.compare((yield* files.read("/note.bin")).bytes, bytes)).toBe(0)
|
|
227
|
+
expect(server.state.loads).toBe(1)
|
|
228
|
+
}),
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
it.live("refuses an Iroh connection while machines are off", () =>
|
|
232
|
+
Effect.gen(function* () {
|
|
233
|
+
const server = yield* home(true)
|
|
234
|
+
const endpoint = yield* Iroh.listen(Effect.succeed(false)).pipe(
|
|
235
|
+
Effect.provide(server.context),
|
|
236
|
+
Effect.provideService(Iroh.Testing, { offline: true, load: loadBinding, watch: () => {} }),
|
|
237
|
+
)
|
|
238
|
+
const identity = Context.get(server.context, Identity.Service)
|
|
239
|
+
const dial = yield* workerEndpoint(endpoint)
|
|
240
|
+
const dialed = yield* Effect.exit(Effect.scoped(dial(yield* identity.publicKey())))
|
|
241
|
+
expect(Exit.isFailure(dialed)).toBe(true)
|
|
242
|
+
}),
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
it.live("never imports Iroh while machines are off, or on with no machines", () =>
|
|
246
|
+
Effect.gen(function* () {
|
|
247
|
+
const off = yield* home(false)
|
|
248
|
+
const results = yield* Effect.promise(() =>
|
|
249
|
+
Promise.allSettled([
|
|
250
|
+
off.api.experimental.machine.list(),
|
|
251
|
+
off.api.experimental.machine.add({ name: "gpu", reach: [] }),
|
|
252
|
+
]),
|
|
253
|
+
)
|
|
254
|
+
expect(results.map((result) => result.status)).toEqual(["rejected", "rejected"])
|
|
255
|
+
const on = yield* home(true)
|
|
256
|
+
yield* Effect.promise(() => on.api.experimental.machine.list())
|
|
257
|
+
expect([off.state.loads, on.state.loads]).toEqual([0, 0])
|
|
258
|
+
}),
|
|
259
|
+
)
|