@zyro-sec/server 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/package.json +40 -4
  2. package/script/build.ts +28 -0
  3. package/script/pack.ts +5 -0
  4. package/script/workerd-probe.ts +59 -0
  5. package/src/api.ts +12 -0
  6. package/src/auth.ts +70 -0
  7. package/src/content-headers.ts +32 -0
  8. package/src/cors.ts +34 -0
  9. package/src/event-feed.ts +93 -0
  10. package/src/fetch.ts +67 -0
  11. package/src/handlers/agent.ts +23 -0
  12. package/src/handlers/artifact.ts +242 -0
  13. package/src/handlers/automation.ts +63 -0
  14. package/src/handlers/blob.ts +55 -0
  15. package/src/handlers/command.ts +8 -0
  16. package/src/handlers/config.ts +26 -0
  17. package/src/handlers/credential.ts +87 -0
  18. package/src/handlers/debug.ts +57 -0
  19. package/src/handlers/event.ts +38 -0
  20. package/src/handlers/form.ts +15 -0
  21. package/src/handlers/fs.ts +180 -0
  22. package/src/handlers/generate.ts +117 -0
  23. package/src/handlers/integration.ts +310 -0
  24. package/src/handlers/job.ts +29 -0
  25. package/src/handlers/location.ts +33 -0
  26. package/src/handlers/machine.ts +336 -0
  27. package/src/handlers/mcp.ts +160 -0
  28. package/src/handlers/media.ts +44 -0
  29. package/src/handlers/message.ts +82 -0
  30. package/src/handlers/migration.ts +13 -0
  31. package/src/handlers/model.ts +25 -0
  32. package/src/handlers/permission.ts +131 -0
  33. package/src/handlers/persistent-pty.ts +285 -0
  34. package/src/handlers/plugin.ts +97 -0
  35. package/src/handlers/project.ts +23 -0
  36. package/src/handlers/provider.ts +32 -0
  37. package/src/handlers/pty-socket.ts +47 -0
  38. package/src/handlers/pty.ts +181 -0
  39. package/src/handlers/push.ts +67 -0
  40. package/src/handlers/reference.ts +8 -0
  41. package/src/handlers/rpc.ts +31 -0
  42. package/src/handlers/server.ts +58 -0
  43. package/src/handlers/session-error.ts +47 -0
  44. package/src/handlers/session.ts +722 -0
  45. package/src/handlers/shell.ts +72 -0
  46. package/src/handlers/skill.ts +34 -0
  47. package/src/handlers/usage.ts +23 -0
  48. package/src/handlers/vcs.ts +104 -0
  49. package/src/handlers/voice.ts +50 -0
  50. package/src/handlers/websearch.ts +50 -0
  51. package/src/handlers/worktree.ts +60 -0
  52. package/src/handlers.ts +69 -0
  53. package/src/location.ts +86 -0
  54. package/src/media-uri.ts +13 -0
  55. package/src/middleware/authorization.ts +111 -0
  56. package/src/middleware/defect-response.ts +39 -0
  57. package/src/middleware/form-location.ts +44 -0
  58. package/src/middleware/schema-error.ts +49 -0
  59. package/src/middleware/session-location.ts +30 -0
  60. package/src/options.ts +61 -0
  61. package/src/pairing.ts +36 -0
  62. package/src/process.ts +274 -0
  63. package/src/range.ts +16 -0
  64. package/src/request-site.ts +36 -0
  65. package/src/request-tracing.ts +9 -0
  66. package/src/routes.ts +261 -0
  67. package/src/server-info.ts +41 -0
  68. package/src/service-status.ts +30 -0
  69. package/src/workerd.ts +184 -0
  70. package/test/artifact.test.ts +224 -0
  71. package/test/auth.test.ts +24 -0
  72. package/test/automation.test.ts +315 -0
  73. package/test/client-mcp.test.ts +369 -0
  74. package/test/codemode-api.test.ts +88 -0
  75. package/test/config.test.ts +104 -0
  76. package/test/cors.test.ts +24 -0
  77. package/test/defect-response.test.ts +83 -0
  78. package/test/event-feed.test.ts +201 -0
  79. package/test/fetch-option.test.ts +104 -0
  80. package/test/fetch.test.ts +698 -0
  81. package/test/fixture/mcp-starts.cjs +20 -0
  82. package/test/fixture/routes.ts +37 -0
  83. package/test/fixture/server.ts +20 -0
  84. package/test/fixture/worktree-delegate/index.ts +13 -0
  85. package/test/fixture/worktree-plugin/index.ts +47 -0
  86. package/test/flag-channel.test.ts +126 -0
  87. package/test/fs.test.ts +439 -0
  88. package/test/generate.test.ts +132 -0
  89. package/test/handler-policy.test.ts +43 -0
  90. package/test/heap-dump.test.ts +137 -0
  91. package/test/integration-policy.test.ts +93 -0
  92. package/test/job.test.ts +186 -0
  93. package/test/machine-iroh.test.ts +259 -0
  94. package/test/machine-link.test.ts +1234 -0
  95. package/test/machine-routes.test.ts +198 -0
  96. package/test/media.test.ts +343 -0
  97. package/test/message.test.ts +105 -0
  98. package/test/model.test.ts +62 -0
  99. package/test/options.test.ts +42 -0
  100. package/test/permission-saved.test.ts +73 -0
  101. package/test/persistent-pty.test.ts +1007 -0
  102. package/test/process.test.ts +261 -0
  103. package/test/provider.test.ts +88 -0
  104. package/test/pty-socket.property.test.ts +240 -0
  105. package/test/pty-socket.test.ts +89 -0
  106. package/test/pty-transport.test.ts +200 -0
  107. package/test/push-routes.test.ts +157 -0
  108. package/test/request-site.test.ts +71 -0
  109. package/test/request-tracing.test.ts +87 -0
  110. package/test/rpc-handler-errors.test.ts +76 -0
  111. package/test/schema-error.test.ts +68 -0
  112. package/test/service-status.test.ts +34 -0
  113. package/test/session-admit-location.test.ts +92 -0
  114. package/test/session-create.test.ts +65 -0
  115. package/test/session-diff.test.ts +100 -0
  116. package/test/session-form.test.ts +50 -0
  117. package/test/session-import.test.ts +152 -0
  118. package/test/session-instances.test.ts +335 -0
  119. package/test/session-unarchive.test.ts +73 -0
  120. package/test/session-update.test.ts +66 -0
  121. package/test/skill.test.ts +57 -0
  122. package/test/sse-failure.test.ts +71 -0
  123. package/test/usage.test.ts +88 -0
  124. package/test/vcs.test.ts +356 -0
  125. package/test/video-generate.test.ts +131 -0
  126. package/test/voice.test.ts +170 -0
  127. package/test/workerd.test.ts +227 -0
  128. package/test/worktree.test.ts +333 -0
  129. package/tsconfig.build.json +15 -0
  130. package/tsconfig.json +11 -0
  131. package/README.md +0 -3
@@ -0,0 +1,34 @@
1
+ import { expect } from "bun:test"
2
+ import { Effect } from "effect"
3
+ import { it } from "../../core/test/lib/effect"
4
+ import { Status } from "../src/service-status"
5
+
6
+ it.effect("moves from starting to ready", () =>
7
+ Effect.gen(function* () {
8
+ const status = yield* Status.make()
9
+ expect(yield* status.current).toEqual({ type: "starting" })
10
+ yield* status.ready
11
+ expect(yield* status.current).toEqual({ type: "ready" })
12
+ }),
13
+ )
14
+
15
+ it.effect("keeps a startup failure until shutdown", () =>
16
+ Effect.gen(function* () {
17
+ const status = yield* Status.make()
18
+ yield* status.fail
19
+ yield* status.ready
20
+ yield* status.fail
21
+ expect(yield* status.current).toEqual({ type: "failed" })
22
+ }),
23
+ )
24
+
25
+ it.effect("keeps stopping after shutdown begins", () =>
26
+ Effect.gen(function* () {
27
+ const status = yield* Status.make()
28
+
29
+ yield* status.beginStopping
30
+ expect(yield* status.current).toEqual({ type: "stopping" })
31
+ yield* status.beginStopping
32
+ expect(yield* status.current).toEqual({ type: "stopping" })
33
+ }),
34
+ )
@@ -0,0 +1,92 @@
1
+ import fs from "fs/promises"
2
+ import { expect } from "bun:test"
3
+ import { App } from "@zyro-sec/core/app"
4
+ import { Bus } from "@zyro-sec/core/bus"
5
+ import { Database } from "@zyro-sec/core/database/database"
6
+ import { Watcher } from "@zyro-sec/core/filesystem/watcher"
7
+ import { LocationServiceMap } from "@zyro-sec/core/location-service-map"
8
+ import { ModelsDev } from "@zyro-sec/core/models-dev"
9
+ import { Session } from "@zyro-sec/core/session"
10
+ import { SessionExecution } from "@zyro-sec/core/session/execution"
11
+ import { Location } from "@zyro-sec/schema/location"
12
+ import { AbsolutePath } from "@zyro-sec/schema/schema"
13
+ import { LayerNode } from "@zyro-sec/util/effect/layer-node"
14
+ import { Global } from "@zyro-sec/util/global"
15
+ import { Context, Effect, Layer, RcMap } from "effect"
16
+ import { HttpEffect, HttpRouter, HttpServer } from "effect/http"
17
+ import { tempGlobalLayer } from "../../core/test/fixture/global"
18
+ import { tmpdirScoped } from "../../core/test/fixture/tmpdir"
19
+ import { it } from "../../core/test/lib/effect"
20
+ import { createEmbeddedRoutes } from "../src/routes"
21
+
22
+ it.live("admits synthetic messages and compaction requests without booting or requiring the session Location", () =>
23
+ Effect.gen(function* () {
24
+ const activeDir = yield* tmpdirScoped()
25
+ const deletedDir = yield* tmpdirScoped()
26
+ const activeLocation = LocationServiceMap.canonical(
27
+ Location.Ref.make({ directory: AbsolutePath.make(activeDir.path) }),
28
+ )
29
+ const deletedLocation = LocationServiceMap.canonical(
30
+ Location.Ref.make({ directory: AbsolutePath.make(deletedDir.path) }),
31
+ )
32
+
33
+ const replacements: LayerNode.Replacements = [
34
+ Global.node.replace(tempGlobalLayer),
35
+ Database.node.replace(Database.node),
36
+ Bus.node.replace(Bus.node),
37
+ App.node.replace(App.node),
38
+ ModelsDev.node.replace(ModelsDev.configured({ fetch: false })),
39
+ Watcher.node.replace(Watcher.configured({ enabled: false })),
40
+ SessionExecution.node.replace(SessionExecution.noopLayer),
41
+ ]
42
+
43
+ const context = yield* Layer.build(
44
+ createEmbeddedRoutes({}, replacements).pipe(Layer.provide(HttpServer.layerServices)),
45
+ )
46
+ const sessions = Context.get(context, Session.Service)
47
+ const locations = Context.get(context, LocationServiceMap.Service)
48
+ const handler = Context.get(context, HttpRouter.HttpRouter)
49
+ .asHttpEffect()
50
+ .pipe(HttpEffect.toWebHandlerWith(context))
51
+
52
+ const post = (route: string, body: unknown) =>
53
+ Effect.promise(() =>
54
+ handler(
55
+ new Request(`http://opencode.local${route}`, {
56
+ method: "POST",
57
+ headers: { "content-type": "application/json" },
58
+ body: JSON.stringify(body),
59
+ }),
60
+ ),
61
+ )
62
+
63
+ const coldSession = yield* sessions.create({ location: activeLocation, title: "cold" })
64
+ const strandedSession = yield* sessions.create({ location: deletedLocation, title: "stranded" })
65
+
66
+ // Remove the worktree directory after session creation to model a pruned worktree.
67
+ yield* Effect.promise(() => fs.rm(deletedDir.path, { recursive: true, force: true }))
68
+ expect(Array.from(yield* RcMap.keys(locations.rcMap))).toEqual([])
69
+
70
+ const coldSynthetic = yield* post(`/api/session/${coldSession.id}/synthetic`, {
71
+ text: "background notice",
72
+ resume: false,
73
+ })
74
+ expect(coldSynthetic.status).toBe(200)
75
+ expect(Array.from(yield* RcMap.keys(locations.rcMap))).toEqual([])
76
+
77
+ const coldCompact = yield* post(`/api/session/${coldSession.id}/compact`, {})
78
+ expect(coldCompact.status).toBe(200)
79
+ expect(Array.from(yield* RcMap.keys(locations.rcMap))).toEqual([])
80
+
81
+ const strandedSynthetic = yield* post(`/api/session/${strandedSession.id}/synthetic`, {
82
+ text: "note on deleted worktree",
83
+ resume: false,
84
+ })
85
+ expect(strandedSynthetic.status).toBe(200)
86
+
87
+ const strandedCompact = yield* post(`/api/session/${strandedSession.id}/compact`, {})
88
+ expect(strandedCompact.status).toBe(200)
89
+
90
+ expect((yield* sessions.inbox(strandedSession.id)).map((item) => item.type)).toEqual(["synthetic", "compaction"])
91
+ }),
92
+ )
@@ -0,0 +1,65 @@
1
+ import { expect } from "bun:test"
2
+ import { Session } from "@zyro-sec/schema/session"
3
+ import { Effect, Schema } from "effect"
4
+ import { it } from "../../core/test/lib/effect"
5
+ import { ServerFetch } from "../src/fetch"
6
+
7
+ const SessionResponse = Schema.Struct({ data: Schema.toEncoded(Session.Info) })
8
+ const SessionsResponse = Schema.Struct({ data: Schema.Array(Schema.toEncoded(Session.Info)) })
9
+
10
+ it.live("creates a child at its parent's location and lists it under the parent", () =>
11
+ Effect.gen(function* () {
12
+ const handler = yield* ServerFetch.make({
13
+ app: { version: "test" },
14
+ database: { path: ":memory:" },
15
+ fs: { filewatcher: false },
16
+ })
17
+ const create = (body: unknown) =>
18
+ Effect.promise(async () => {
19
+ const response = await handler(
20
+ new Request("http://opencode.local/api/session", {
21
+ method: "POST",
22
+ headers: { "content-type": "application/json" },
23
+ body: JSON.stringify(body),
24
+ }),
25
+ )
26
+ expect(response.status).toBe(200)
27
+ return Schema.decodeUnknownSync(SessionResponse)(await response.json()).data
28
+ })
29
+ const parent = yield* create({ title: "Parent" })
30
+ const child = yield* create({ parentID: parent.id, title: "Child", location: { directory: "/unused" } })
31
+ const response = yield* Effect.promise(() =>
32
+ handler(new Request(`http://opencode.local/api/session?parentID=${parent.id}`)),
33
+ )
34
+ expect(response.status).toBe(200)
35
+ const children = Schema.decodeUnknownSync(SessionsResponse)(yield* Effect.promise(() => response.json()))
36
+
37
+ expect(child).toMatchObject({ parentID: parent.id, location: parent.location })
38
+ expect(children.data.map((session) => session.id)).toEqual([child.id])
39
+ }).pipe(Effect.scoped),
40
+ )
41
+
42
+ it.live("returns not found when creating a child of a missing session", () =>
43
+ Effect.gen(function* () {
44
+ const handler = yield* ServerFetch.make({
45
+ app: { version: "test" },
46
+ database: { path: ":memory:" },
47
+ fs: { filewatcher: false },
48
+ })
49
+ const parentID = Session.ID.create()
50
+ const response = yield* Effect.promise(() =>
51
+ handler(
52
+ new Request("http://opencode.local/api/session", {
53
+ method: "POST",
54
+ headers: { "content-type": "application/json" },
55
+ body: JSON.stringify({ parentID, title: "Child" }),
56
+ }),
57
+ ),
58
+ )
59
+ expect(response.status).toBe(404)
60
+ expect(yield* Effect.promise(() => response.json())).toMatchObject({
61
+ _tag: "SessionNotFoundError",
62
+ sessionID: parentID,
63
+ })
64
+ }).pipe(Effect.scoped),
65
+ )
@@ -0,0 +1,100 @@
1
+ import { expect, setDefaultTimeout } from "bun:test"
2
+ import { Agent } from "@zyro-sec/core/agent"
3
+ import { Bus } from "@zyro-sec/core/bus"
4
+ import { Model } from "@zyro-sec/core/model"
5
+ import { Provider } from "@zyro-sec/core/provider"
6
+ import { Session } from "@zyro-sec/core/session"
7
+ import { SessionEvent } from "@zyro-sec/core/session/event"
8
+ import { SessionExecution } from "@zyro-sec/core/session/execution"
9
+ import { SessionMessage } from "@zyro-sec/core/session/message"
10
+ import { Money } from "@zyro-sec/schema/money"
11
+ import { makeGlobalNode } from "@zyro-sec/util/effect/app-node"
12
+ import { Effect, Layer } from "effect"
13
+ import { tmpdir } from "../../core/test/fixture/tmpdir"
14
+ import { it } from "../../core/test/lib/effect"
15
+ import { ServerFetch } from "../src/fetch"
16
+
17
+ setDefaultTimeout(30_000)
18
+
19
+ it.live("serves turn diffs by user message with range validation", () =>
20
+ Effect.gen(function* () {
21
+ const tmp = yield* Effect.acquireDisposable(Effect.promise(() => tmpdir("opencode-session-diff-")))
22
+ const ids = { user: SessionMessage.ID.create(), assistant: SessionMessage.ID.create() }
23
+ // Deliver the prompt and one step the way the runner would, without a model.
24
+ const execution = Layer.effect(
25
+ SessionExecution.Service,
26
+ Effect.gen(function* () {
27
+ const bus = yield* Bus.Service
28
+ return SessionExecution.Service.of({
29
+ active: Effect.succeed(new Set()),
30
+ isActive: () => Effect.succeed(false),
31
+ resume: () => Effect.void,
32
+ wake: (sessionID) =>
33
+ Effect.gen(function* () {
34
+ yield* bus.publish(SessionEvent.InboxDelivered, { sessionID, inboxID: ids.user })
35
+ yield* bus.publish(SessionEvent.Step.Started, {
36
+ sessionID,
37
+ assistantMessageID: ids.assistant,
38
+ agent: Agent.defaultID,
39
+ model: { id: Model.ID.make("model"), providerID: Provider.ID.make("provider") },
40
+ started: 0,
41
+ })
42
+ yield* bus.publish(SessionEvent.Step.Ended, {
43
+ sessionID,
44
+ assistantMessageID: ids.assistant,
45
+ finish: "stop",
46
+ cost: Money.USD.zero,
47
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
48
+ })
49
+ }),
50
+ interrupt: () => Effect.succeed(false),
51
+ awaitIdle: () => Effect.void,
52
+ })
53
+ }),
54
+ )
55
+ const handler = yield* ServerFetch.make(
56
+ {
57
+ app: { version: "test-version" },
58
+ config: { directory: tmp.path, project: false },
59
+ database: { path: ":memory:" },
60
+ fs: { filewatcher: false },
61
+ models: { fetch: false },
62
+ },
63
+ {
64
+ overrides: [
65
+ SessionExecution.node.replace(
66
+ makeGlobalNode({ service: SessionExecution.Service, layer: execution, deps: [Bus.node] }),
67
+ ),
68
+ ],
69
+ },
70
+ )
71
+ const request = (path: string, body?: unknown) =>
72
+ Effect.promise(async () => {
73
+ const response = await handler(
74
+ new Request(`http://opencode.local${path}`, {
75
+ method: body === undefined ? "GET" : "POST",
76
+ headers: body === undefined ? undefined : { "content-type": "application/json" },
77
+ body: body === undefined ? undefined : JSON.stringify(body),
78
+ }),
79
+ )
80
+ return { status: response.status, body: (await response.json()) as Record<string, unknown> }
81
+ })
82
+ const created = yield* request("/api/session", { location: { directory: tmp.path } })
83
+ const sessionID = Session.ID.make((created.body.data as { id: string }).id)
84
+ const diff = (query = "") => request(`/api/session/${sessionID}/diff${query}`)
85
+
86
+ expect(yield* diff()).toEqual({ status: 200, body: { data: [] } })
87
+ expect((yield* request(`/api/session/${sessionID}/prompt`, { id: ids.user, text: "prompt" })).status).toBe(200)
88
+ // Not a git repository, so steps record no snapshots and the turn has no diff.
89
+ expect(yield* diff(`?from=${ids.user}&context=3`)).toEqual({ status: 200, body: { data: [] } })
90
+ expect(yield* diff(`?from=${ids.assistant}`)).toMatchObject({
91
+ status: 400,
92
+ body: { _tag: "InvalidRequestError", field: "from" },
93
+ })
94
+ expect(yield* diff(`?from=${SessionMessage.ID.create()}`)).toMatchObject({
95
+ status: 404,
96
+ body: { _tag: "MessageNotFoundError" },
97
+ })
98
+ expect((yield* request(`/api/session/${Session.ID.create()}/diff`)).status).toBe(404)
99
+ }),
100
+ )
@@ -0,0 +1,50 @@
1
+ import { expect } from "bun:test"
2
+ import fs from "fs/promises"
3
+ import { Effect } from "effect"
4
+ import { tmpdirScoped } from "../../core/test/fixture/tmpdir"
5
+ import { it } from "../../core/test/lib/effect"
6
+ import { ServerFetch } from "../src/fetch"
7
+
8
+ it.live("lists no forms for a Session whose Location is not live, and pending forms once it is", () =>
9
+ Effect.gen(function* () {
10
+ const handler = yield* ServerFetch.make({
11
+ app: { version: "test" },
12
+ database: { path: ":memory:" },
13
+ fs: { filewatcher: false },
14
+ models: { fetch: false },
15
+ })
16
+ const request = (path: string, body?: unknown) =>
17
+ Effect.promise(async () => {
18
+ const response = await handler(
19
+ new Request(`http://opencode.local${path}`, {
20
+ method: body === undefined ? "GET" : "POST",
21
+ headers: { "content-type": "application/json" },
22
+ body: body === undefined ? undefined : JSON.stringify(body),
23
+ }),
24
+ )
25
+ return { status: response.status, body: await response.json() }
26
+ })
27
+ const create = (directory: string) =>
28
+ request("/api/session", { location: { directory } }).pipe(
29
+ Effect.map((response) => (response.body as { data: { id: string } }).data.id),
30
+ )
31
+
32
+ // A subagent whose worktree was deleted must not boot or 404.
33
+ const deleted = yield* tmpdirScoped()
34
+ const orphan = yield* create(deleted.path)
35
+ yield* Effect.promise(() => fs.rm(deleted.path, { recursive: true, force: true }))
36
+ expect(yield* request(`/api/session/${orphan}/form`)).toEqual({ status: 200, body: { data: [] } })
37
+
38
+ const directory = yield* tmpdirScoped()
39
+ const live = yield* create(directory.path)
40
+ const created = yield* request(`/api/session/${live}/form`, {
41
+ title: "Pick one",
42
+ fields: [{ key: "answer", type: "string" }],
43
+ })
44
+ expect(created.status).toBe(200)
45
+ expect(yield* request(`/api/session/${live}/form`)).toEqual({
46
+ status: 200,
47
+ body: { data: [(created.body as { data: unknown }).data] },
48
+ })
49
+ }).pipe(Effect.scoped),
50
+ )
@@ -0,0 +1,152 @@
1
+ import { expect } from "bun:test"
2
+ import { Session } from "@zyro-sec/schema/session"
3
+ import { Effect, Schema } from "effect"
4
+ import { it } from "../../core/test/lib/effect"
5
+ import { ServerFetch } from "../src/fetch"
6
+
7
+ const SessionResponse = Schema.Struct({ data: Schema.toEncoded(Session.Info) })
8
+ const SessionsResponse = Schema.Struct({ data: Schema.Array(Schema.toEncoded(Session.Info)) })
9
+
10
+ const setup = Effect.gen(function* () {
11
+ const handler = yield* ServerFetch.make({
12
+ app: { version: "test" },
13
+ database: { path: ":memory:" },
14
+ fs: { filewatcher: false },
15
+ })
16
+ return (path: string, body?: unknown, status = 200) =>
17
+ Effect.promise(async () => {
18
+ const response = await handler(
19
+ new Request(`http://opencode.local${path}`, {
20
+ method: body === undefined ? "GET" : "POST",
21
+ headers: { "content-type": "application/json" },
22
+ body: body === undefined ? undefined : JSON.stringify(body),
23
+ }),
24
+ )
25
+ const json: unknown = await response.json()
26
+ expect(response.status).toBe(status)
27
+ return json
28
+ })
29
+ })
30
+
31
+ it.live("preserves imported parentID through HTTP import, read, and parent filter", () =>
32
+ Effect.gen(function* () {
33
+ const request = yield* setup
34
+ const parent = Schema.decodeUnknownSync(SessionResponse)(yield* request("/api/session", { title: "Parent" }))
35
+ const id = Session.ID.create()
36
+ const imported = Schema.decodeUnknownSync(SessionResponse)(
37
+ yield* request("/api/experimental/session/import", {
38
+ info: { ...parent.data, id, parentID: parent.data.id, title: "Imported child" },
39
+ messages: [],
40
+ }),
41
+ )
42
+ const read = Schema.decodeUnknownSync(SessionResponse)(yield* request(`/api/session/${id}`))
43
+ const children = Schema.decodeUnknownSync(SessionsResponse)(
44
+ yield* request(`/api/session?parentID=${parent.data.id}`),
45
+ )
46
+ expect({
47
+ imported: imported.data.parentID,
48
+ read: read.data.parentID,
49
+ children: children.data.map((child) => child.id),
50
+ }).toEqual({ imported: parent.data.id, read: parent.data.id, children: [id] })
51
+ }).pipe(Effect.scoped),
52
+ )
53
+
54
+ it.live("upgrades native data in transcripts exported before v2.1", () =>
55
+ Effect.gen(function* () {
56
+ const request = yield* setup
57
+ const template = Schema.decodeUnknownSync(SessionResponse)(yield* request("/api/session", {}))
58
+ const id = Session.ID.create()
59
+ yield* request("/api/experimental/session/import", {
60
+ info: { ...template.data, id },
61
+ messages: [
62
+ {
63
+ id: "msg_legacy",
64
+ type: "assistant",
65
+ agent: "build",
66
+ model: { providerID: "anthropic", id: "claude" },
67
+ providerState: { finish: "kept" },
68
+ content: [
69
+ { type: "text", text: "Answer", state: { signature: "text" } },
70
+ { type: "reasoning", text: "Thinking", state: { signature: "reasoning" } },
71
+ {
72
+ type: "tool",
73
+ id: "call",
74
+ name: "web_search",
75
+ executed: true,
76
+ providerState: { call: "kept" },
77
+ providerResultState: { result: "kept" },
78
+ state: { status: "completed", input: {}, content: [{ type: "text", text: "Found" }] },
79
+ time: { created: 1, ran: 1, completed: 2 },
80
+ },
81
+ ],
82
+ time: { created: 1, completed: 2 },
83
+ },
84
+ {
85
+ id: "msg_compaction",
86
+ type: "compaction",
87
+ status: "completed",
88
+ reason: "manual",
89
+ summary: "Summary",
90
+ recent: "[User]: kept",
91
+ providerState: { compaction: "kept" },
92
+ time: { created: 3 },
93
+ },
94
+ { id: "msg_moved", type: "location-switched", location: { directory: "/moved" }, time: { created: 4 } },
95
+ ],
96
+ })
97
+ expect(yield* request(`/api/session/${id}/message?order=asc`)).toMatchObject({
98
+ data: [
99
+ {
100
+ id: "msg_legacy",
101
+ native: { finish: "kept" },
102
+ content: [
103
+ { type: "text", native: { signature: "text" } },
104
+ { type: "reasoning", native: { signature: "reasoning" } },
105
+ { type: "tool", native: { call: "kept", result: "kept" } },
106
+ ],
107
+ },
108
+ { id: "msg_compaction", native: { compaction: "kept" }, metadata: { recent: "[User]: kept" } },
109
+ { id: "msg_moved", location: { directory: "/moved" } },
110
+ ],
111
+ })
112
+ }).pipe(Effect.scoped),
113
+ )
114
+
115
+ it.live("rejects an invalid imported message without creating the session", () =>
116
+ Effect.gen(function* () {
117
+ const request = yield* setup
118
+ const template = Schema.decodeUnknownSync(SessionResponse)(yield* request("/api/session", {}))
119
+ const id = Session.ID.create()
120
+ const error = yield* request(
121
+ "/api/experimental/session/import",
122
+ { info: { ...template.data, id }, messages: [{ id: "msg_invalid", type: "assistant" }] },
123
+ 400,
124
+ )
125
+ expect(error).toMatchObject({
126
+ _tag: "InvalidRequestError",
127
+ kind: "Payload",
128
+ message: expect.stringContaining(`["messages"][0]`),
129
+ })
130
+ expect(yield* request(`/api/session/${id}`, undefined, 404)).toMatchObject({ _tag: "SessionNotFoundError" })
131
+ }).pipe(Effect.scoped),
132
+ )
133
+ ;["missing", "self"].forEach((parent) => {
134
+ it.live(`rejects a ${parent} parent without creating the imported session`, () =>
135
+ Effect.gen(function* () {
136
+ const request = yield* setup
137
+ const template = Schema.decodeUnknownSync(SessionResponse)(yield* request("/api/session", {}))
138
+ const id = Session.ID.create()
139
+ const parentID = parent === "self" ? id : Session.ID.create()
140
+ const error = yield* request(
141
+ "/api/experimental/session/import",
142
+ { info: { ...template.data, id, parentID }, messages: [] },
143
+ 404,
144
+ )
145
+ expect(error).toMatchObject({ _tag: "SessionNotFoundError", sessionID: parentID })
146
+ expect(yield* request(`/api/session/${id}`, undefined, 404)).toMatchObject({
147
+ _tag: "SessionNotFoundError",
148
+ sessionID: id,
149
+ })
150
+ }).pipe(Effect.scoped),
151
+ )
152
+ })