@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,132 +0,0 @@
1
- import fs from "node:fs/promises"
2
- import path from "node:path"
3
- import { expect } from "bun:test"
4
- import { Config } from "@zyro-sec/core/config"
5
- import { Generate } from "@zyro-sec/core/generate"
6
- import { makeLocationNode } from "@zyro-sec/util/effect/app-node"
7
- import { Effect, Layer, Predicate } from "effect"
8
- import { tmpdir } from "../../core/test/fixture/tmpdir"
9
- import { it } from "../../core/test/lib/effect"
10
- import { ServerFetch } from "../src/fetch"
11
-
12
- const generate = makeLocationNode({
13
- service: Generate.Service,
14
- layer: Layer.effect(
15
- Generate.Service,
16
- Effect.gen(function* () {
17
- const config = yield* Config.Service
18
- return Generate.Service.of({
19
- text: () =>
20
- config.entries().pipe(
21
- Effect.map((entries) =>
22
- JSON.stringify({
23
- model: Config.latest(entries, "model"),
24
- }),
25
- ),
26
- ),
27
- image: () => Effect.die("unused"),
28
- decisions: () => Effect.die("unused"),
29
- video: {
30
- start: () => Effect.die("unused"),
31
- status: () => Effect.die("unused"),
32
- result: () => Effect.die("unused"),
33
- cancel: () => Effect.die("unused"),
34
- },
35
- })
36
- }),
37
- ),
38
- deps: [Config.node],
39
- })
40
-
41
- it.live("uses base configuration without depending on process.cwd()", () =>
42
- Effect.gen(function* () {
43
- const tmp = yield* Effect.acquireDisposable(Effect.promise(() => tmpdir("opencode-generate-endpoint-")))
44
- const global = path.join(tmp.path, "global")
45
- const project = path.join(tmp.path, "project")
46
- yield* Effect.promise(() => Promise.all([fs.mkdir(global), fs.mkdir(project)]))
47
- yield* Effect.promise(() =>
48
- Promise.all([
49
- fs.writeFile(path.join(global, "opencode.json"), JSON.stringify({ model: "base/default" })),
50
- fs.writeFile(path.join(project, "opencode.json"), JSON.stringify({ model: "project/default" })),
51
- ]),
52
- )
53
- const handler = yield* ServerFetch.make(
54
- {
55
- database: { path: ":memory:" },
56
- config: { directory: global },
57
- fs: { filewatcher: false },
58
- models: { fetch: false },
59
- },
60
- { overrides: [Generate.node.replace(generate)] },
61
- )
62
-
63
- expect(global).not.toBe(process.cwd())
64
- expect(yield* request(handler, new URL("http://opencode.local/api/experimental/generate/text"))).toEqual({
65
- model: { providerID: "base", model: "default" },
66
- })
67
-
68
- const legacy = new URL("http://opencode.local/api/experimental/generate/text")
69
- legacy.searchParams.set("location[directory]", project)
70
- expect(yield* request(handler, legacy)).toEqual({
71
- model: { providerID: "base", model: "default" },
72
- })
73
-
74
- const deprecatedPath = new URL("http://opencode.local/api/experimental/generate")
75
- expect(yield* request(handler, deprecatedPath)).toEqual({
76
- model: { providerID: "base", model: "default" },
77
- })
78
- }),
79
- )
80
-
81
- it.live("rejects unknown image and decision models and duplicate question names", () =>
82
- Effect.gen(function* () {
83
- const tmp = yield* Effect.acquireDisposable(Effect.promise(() => tmpdir("opencode-generate-media-")))
84
- const handler = yield* ServerFetch.make({
85
- database: { path: ":memory:" },
86
- config: { directory: tmp.path },
87
- fs: { filewatcher: false },
88
- models: { fetch: false },
89
- })
90
- const model = { providerID: "nowhere", id: "nothing" }
91
- const question = { type: "predicate", name: "refund", instructions: "Is this a refund request?" }
92
- const post = (path: string, body: unknown) =>
93
- Effect.promise(() =>
94
- handler(
95
- new Request(`http://opencode.local/api/experimental/generate/${path}`, {
96
- method: "POST",
97
- headers: { "content-type": "application/json" },
98
- body: JSON.stringify(body),
99
- }),
100
- ),
101
- )
102
- for (const [path, body] of [
103
- ["image", { model, prompt: "a red square" }],
104
- ["decisions", { model, input: [{ type: "text", text: "I was charged twice." }], questions: [question] }],
105
- ] as const) {
106
- const response = yield* post(path, body)
107
- expect(response.status).toBe(404)
108
- expect(yield* Effect.promise(() => response.json())).toMatchObject({ _tag: "ModelNotFoundError" })
109
- }
110
- const duplicate = yield* post("decisions", { model, input: [], questions: [question, question] })
111
- expect(duplicate.status).toBe(400)
112
- }),
113
- )
114
-
115
- function request(handler: (request: Request) => Promise<Response>, url: URL) {
116
- return Effect.promise(() =>
117
- handler(
118
- new Request(url, {
119
- method: "POST",
120
- headers: { "content-type": "application/json" },
121
- body: JSON.stringify({ prompt: "hello" }),
122
- }),
123
- ).then(async (response) => {
124
- expect(response.status).toBe(200)
125
- const body: unknown = await response.json()
126
- if (!Predicate.isObject(body) || !Predicate.isObject(body.data) || typeof body.data.text !== "string")
127
- throw new Error("Expected a generate response")
128
- const result: unknown = JSON.parse(body.data.text)
129
- return result
130
- }),
131
- )
132
- }
@@ -1,43 +0,0 @@
1
- import { Session } from "@zyro-sec/core/session"
2
- import { SessionMessage } from "@zyro-sec/core/session/message"
3
- import { SessionNotFoundError, UnknownError } from "@zyro-sec/protocol/errors"
4
- import { expect, test } from "bun:test"
5
- import { Effect, Logger, References } from "effect"
6
- import { failedMessageDecode, missingSession } from "../src/handlers/session-error"
7
-
8
- test("yieldable session errors preserve the handler failure policy", async () => {
9
- const sessionID = Session.ID.create()
10
- const error = await Effect.runPromise(
11
- Effect.fail(new Session.NotFoundError({ sessionID })).pipe(
12
- Effect.catchTag("Session.NotFoundError", missingSession),
13
- Effect.flip,
14
- ),
15
- )
16
-
17
- expect(error).toBeInstanceOf(SessionNotFoundError)
18
- expect(error).toMatchObject({ sessionID, message: `Session not found: ${sessionID}` })
19
- })
20
-
21
- test("message decode policy preserves its reference and log annotations", async () => {
22
- const sessionID = Session.ID.create()
23
- const messageID = SessionMessage.ID.create()
24
- const messages: unknown[] = []
25
- const annotations: Array<Record<string, unknown>> = []
26
- const logger = Logger.make<unknown, void>((options) => {
27
- messages.push(options.message)
28
- annotations.push({ ...options.fiber.getRef(References.CurrentLogAnnotations) })
29
- })
30
- const error = await Effect.runPromise(
31
- Effect.fail(new Session.MessageDecodeError({ sessionID, messageID })).pipe(
32
- Effect.catchTag("Session.MessageDecodeError", failedMessageDecode),
33
- Effect.flip,
34
- Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
35
- ),
36
- )
37
-
38
- expect(error).toBeInstanceOf(UnknownError)
39
- expect(error.message).toBe("Unexpected server error. Check server logs for details.")
40
- expect(error.ref).toMatch(/^err_[0-9a-f]{8}$/)
41
- expect(messages).toEqual([["failed to decode session message"]])
42
- expect(annotations).toEqual([{ ref: error.ref, sessionID, messageID }])
43
- })
@@ -1,137 +0,0 @@
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
- )
@@ -1,93 +0,0 @@
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 DELETED
@@ -1,186 +0,0 @@
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
- )