@eloxiv/daemon 0.0.0-stage → 0.1.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 (119) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +6 -2
  3. package/dist/Acp.d.ts +8 -0
  4. package/dist/Acp.d.ts.map +1 -0
  5. package/dist/Acp.js +268 -0
  6. package/dist/Acp.js.map +1 -0
  7. package/dist/Canonical.d.ts +3 -0
  8. package/dist/Canonical.d.ts.map +1 -0
  9. package/dist/Canonical.js +12 -0
  10. package/dist/Canonical.js.map +1 -0
  11. package/dist/Client.d.ts +102 -0
  12. package/dist/Client.d.ts.map +1 -0
  13. package/dist/Client.js +482 -0
  14. package/dist/Client.js.map +1 -0
  15. package/dist/Commands.d.ts +85 -0
  16. package/dist/Commands.d.ts.map +1 -0
  17. package/dist/Commands.js +370 -0
  18. package/dist/Commands.js.map +1 -0
  19. package/dist/Config.d.ts +74 -0
  20. package/dist/Config.d.ts.map +1 -0
  21. package/dist/Config.js +126 -0
  22. package/dist/Config.js.map +1 -0
  23. package/dist/Daemon.d.ts +243 -0
  24. package/dist/Daemon.d.ts.map +1 -0
  25. package/dist/Daemon.js +965 -0
  26. package/dist/Daemon.js.map +1 -0
  27. package/dist/Harness.d.ts +133 -0
  28. package/dist/Harness.d.ts.map +1 -0
  29. package/dist/Harness.js +734 -0
  30. package/dist/Harness.js.map +1 -0
  31. package/dist/Http.d.ts +15 -0
  32. package/dist/Http.d.ts.map +1 -0
  33. package/dist/Http.js +548 -0
  34. package/dist/Http.js.map +1 -0
  35. package/dist/KernelLink.d.ts +145 -0
  36. package/dist/KernelLink.d.ts.map +1 -0
  37. package/dist/KernelLink.js +109 -0
  38. package/dist/KernelLink.js.map +1 -0
  39. package/dist/LocalAuth.d.ts +99 -0
  40. package/dist/LocalAuth.d.ts.map +1 -0
  41. package/dist/LocalAuth.js +225 -0
  42. package/dist/LocalAuth.js.map +1 -0
  43. package/dist/Main.d.ts +51 -0
  44. package/dist/Main.d.ts.map +1 -0
  45. package/dist/Main.js +219 -0
  46. package/dist/Main.js.map +1 -0
  47. package/dist/PersonSession.d.ts +49 -0
  48. package/dist/PersonSession.d.ts.map +1 -0
  49. package/dist/PersonSession.js +173 -0
  50. package/dist/PersonSession.js.map +1 -0
  51. package/dist/Secrets.d.ts +21 -0
  52. package/dist/Secrets.d.ts.map +1 -0
  53. package/dist/Secrets.js +204 -0
  54. package/dist/Secrets.js.map +1 -0
  55. package/dist/SecureUrl.d.ts +11 -0
  56. package/dist/SecureUrl.d.ts.map +1 -0
  57. package/dist/SecureUrl.js +23 -0
  58. package/dist/SecureUrl.js.map +1 -0
  59. package/dist/State.d.ts +77 -0
  60. package/dist/State.d.ts.map +1 -0
  61. package/dist/State.js +38 -0
  62. package/dist/State.js.map +1 -0
  63. package/dist/Terminals.d.ts +49 -0
  64. package/dist/Terminals.d.ts.map +1 -0
  65. package/dist/Terminals.js +203 -0
  66. package/dist/Terminals.js.map +1 -0
  67. package/dist/bin-node.d.ts +2 -0
  68. package/dist/bin-node.d.ts.map +1 -0
  69. package/dist/bin-node.js +4 -0
  70. package/dist/bin-node.js.map +1 -0
  71. package/dist/bin.d.ts +2 -0
  72. package/dist/bin.d.ts.map +1 -0
  73. package/dist/bin.js +4 -0
  74. package/dist/bin.js.map +1 -0
  75. package/dist/index.d.ts +18 -0
  76. package/dist/index.d.ts.map +1 -0
  77. package/dist/index.js +18 -0
  78. package/dist/index.js.map +1 -0
  79. package/dist/runtime/bun.d.ts +11 -0
  80. package/dist/runtime/bun.d.ts.map +1 -0
  81. package/dist/runtime/bun.js +20 -0
  82. package/dist/runtime/bun.js.map +1 -0
  83. package/dist/runtime/node.d.ts +11 -0
  84. package/dist/runtime/node.d.ts.map +1 -0
  85. package/dist/runtime/node.js +21 -0
  86. package/dist/runtime/node.js.map +1 -0
  87. package/dist/testing.d.ts +25 -0
  88. package/dist/testing.d.ts.map +1 -0
  89. package/dist/testing.js +27 -0
  90. package/dist/testing.js.map +1 -0
  91. package/fixtures/claude-code-env-vars.txt +409 -0
  92. package/fixtures/fake-acp-agent.mjs +222 -0
  93. package/fixtures/fake-harness.mjs +299 -0
  94. package/fixtures/recorded/claude-code.jsonl +7 -0
  95. package/fixtures/recorded/codex.jsonl +6 -0
  96. package/package.json +64 -3
  97. package/scripts/build-sidecar.ts +86 -0
  98. package/src/Acp.ts +292 -0
  99. package/src/Canonical.ts +9 -0
  100. package/src/Client.ts +590 -0
  101. package/src/Commands.ts +427 -0
  102. package/src/Config.ts +179 -0
  103. package/src/Daemon.ts +1092 -0
  104. package/src/Harness.ts +839 -0
  105. package/src/Http.ts +563 -0
  106. package/src/KernelLink.ts +197 -0
  107. package/src/LocalAuth.ts +301 -0
  108. package/src/Main.ts +281 -0
  109. package/src/PersonSession.ts +203 -0
  110. package/src/Secrets.ts +226 -0
  111. package/src/SecureUrl.ts +21 -0
  112. package/src/State.ts +109 -0
  113. package/src/Terminals.ts +227 -0
  114. package/src/bin-node.ts +4 -0
  115. package/src/bin.ts +4 -0
  116. package/src/index.ts +17 -0
  117. package/src/runtime/bun.ts +29 -0
  118. package/src/runtime/node.ts +30 -0
  119. package/src/testing.ts +43 -0
package/src/Http.ts ADDED
@@ -0,0 +1,563 @@
1
+ /**
2
+ * The daemon's loopback HTTP surface (the Daemon and DeviceControl contracts), as one web-standard handler
3
+ * mounted on the platform server by `DaemonHttp`. Every request is checked for a loopback `Host` and a trusted
4
+ * `Origin` (when it has one); every route but `/health` and the local pairing handshake needs a local client's
5
+ * token (see `LocalAuth`).
6
+ *
7
+ * GET /health liveness (no token)
8
+ * GET /status mode, kernel pairing (never the credential), secret store, harnesses
9
+ * POST /local/pair/start start pairing a local client (the code is shown out of band)
10
+ * POST /local/pair/confirm exchange the code for a local client token
11
+ * GET /local/pairings pending local pairings with their codes (the host only)
12
+ * POST /kernel-pairing/start pair this device with a kernel (the host, or a paired shell or CLI)
13
+ * POST /relay/actions/<action> an Eloxiv action through the kernel's invocation path
14
+ * * /mcp the kernel's MCP tools, relayed with an agent session
15
+ * GET /harnesses harness CLIs and their sign-in state
16
+ * POST /turns run a harness turn now (server-sent events)
17
+ * GET /sessions the device's sessions (DeviceControl)
18
+ * GET /capabilities what the device offers now: each command kind's availability (DeviceControl)
19
+ * GET /computer-use the computer-use capability
20
+ * POST /companion/commands/next a companion (browser extension, computer use) asks for a command of its kind
21
+ * POST /companion/commands/<id>/result and reports it
22
+ * POST /push register the host's push subscription with the kernel (or remove it)
23
+ * POST /terminals open a terminal (the host, the shell or a CLI; the terminal enabled)
24
+ * GET /terminals the caller's terminals
25
+ * GET /terminals/<id>/stream its output (server-sent events: output, exit)
26
+ * POST /terminals/<id>/input, /terminals/<id>/resize; DELETE /terminals/<id>
27
+ * * /client/v1/... LocalClient (decision 14; `Client.ts`): the host and desktop apps only;
28
+ * its sign-in callback is the one browser-facing route, checked by its state
29
+ */
30
+ import {
31
+ DaemonHealth,
32
+ HarnessKind,
33
+ PushSubscriptionInfo,
34
+ MAX_TURN_PROMPT,
35
+ MAX_TURN_TIMEOUT_MS,
36
+ DEFAULT_TURN_TIMEOUT_MS,
37
+ MCP_IDEMPOTENCY_META,
38
+ PairingConfirm,
39
+ PairingRequestLocal,
40
+ toolName,
41
+ } from "@eloxiv/contracts"
42
+ import { Effect, Schema } from "effect"
43
+ import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http"
44
+ import { companionKindOf } from "./Commands.ts"
45
+ import { TerminalError } from "./Terminals.ts"
46
+ import { credentialKey } from "./Secrets.ts"
47
+ import { PairingRefused, type Daemon } from "./Daemon.ts"
48
+ import { DeviceRevoked, KernelError } from "./KernelLink.ts"
49
+ import { LocalAuthError, type AuthenticatedClient } from "./LocalAuth.ts"
50
+ import { CLIENT_CALLBACK, clientRefusal, isClientPath, serveClient } from "./Client.ts"
51
+
52
+ /** Keep in step with package.json (a test checks it). */
53
+ export const DAEMON_VERSION = "0.1.1"
54
+
55
+ export type DaemonRuntime = "bun" | "node"
56
+
57
+ export const currentRuntime = (): DaemonRuntime => (typeof process.versions["bun"] === "string" ? "bun" : "node")
58
+
59
+ /** Origins the shell runs at: the Tauri webview (Linux/macOS and Windows), and in development the Vite dev server. */
60
+ export const trustedOriginsFor = (build: string): ReadonlyArray<string> =>
61
+ build === "release"
62
+ ? ["tauri://localhost", "http://tauri.localhost"]
63
+ : ["http://localhost:5173", "tauri://localhost", "http://tauri.localhost"]
64
+
65
+ /** The development set (`trustedOriginsFor("development")`). */
66
+ export const DEFAULT_TRUSTED_ORIGINS: ReadonlyArray<string> = trustedOriginsFor("development")
67
+
68
+ const MAX_BODY = 1024 * 1024
69
+
70
+ const HarnessTurnInput = Schema.Struct({
71
+ harness: HarnessKind,
72
+ prompt: Schema.String.check(Schema.isMaxLength(MAX_TURN_PROMPT)),
73
+ cwd: Schema.optionalKey(Schema.NullOr(Schema.String)),
74
+ model: Schema.optionalKey(Schema.NullOr(Schema.String)),
75
+ timeoutMs: Schema.optionalKey(Schema.Number.check(Schema.isGreaterThan(0))),
76
+ actions: Schema.optionalKey(Schema.NullOr(Schema.Array(Schema.String))),
77
+ workspaceTools: Schema.optionalKey(Schema.Boolean),
78
+ /** Keep the harness session for a follow-up; its id is the result's `sessionId`. */
79
+ resumable: Schema.optionalKey(Schema.Boolean),
80
+ /** Follow up: resume a session a resumable turn kept on this device. */
81
+ resume: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(200))),
82
+ })
83
+
84
+ const CompanionNext = Schema.Struct({ waitMs: Schema.optionalKey(Schema.Number) })
85
+ const CompanionResult = Schema.Struct({
86
+ outcome: Schema.Literals(["succeeded", "failed"]),
87
+ result: Schema.optionalKey(Schema.Unknown),
88
+ error: Schema.optionalKey(Schema.NullOr(Schema.String.check(Schema.isMaxLength(10_000)))),
89
+ })
90
+ const PushInput = Schema.Struct({ subscription: Schema.NullOr(PushSubscriptionInfo) })
91
+ const Size = Schema.Number.check(Schema.isInt(), Schema.isBetween({ minimum: 1, maximum: 1000 }))
92
+ const TerminalOpen = Schema.Struct({
93
+ cwd: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(1000))),
94
+ cols: Schema.optionalKey(Size),
95
+ rows: Schema.optionalKey(Size),
96
+ })
97
+ const TerminalInput = Schema.Struct({ data: Schema.String.check(Schema.isMaxLength(64 * 1024)) })
98
+ const TerminalResize = Schema.Struct({ cols: Size, rows: Size })
99
+
100
+ const KernelPairingInput = Schema.Struct({
101
+ kernelUrl: Schema.String.check(Schema.isPattern(/^https?:\/\/[^\s]+$/u)),
102
+ name: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(100))),
103
+ })
104
+
105
+ class HttpProblem extends Error {
106
+ readonly status: number
107
+ readonly tag: string
108
+ constructor(status: number, tag: string, message: string) {
109
+ super(message)
110
+ this.status = status
111
+ this.tag = tag
112
+ }
113
+ }
114
+
115
+ const readJson = async <A, I>(request: Request, schema: Schema.Codec<A, I>): Promise<A> => {
116
+ const text = await request.text()
117
+ if (text.length > MAX_BODY) throw new HttpProblem(413, "TooLarge", "The body is too large")
118
+ let raw: unknown
119
+ try {
120
+ raw = text.length === 0 ? {} : JSON.parse(text)
121
+ } catch {
122
+ throw new HttpProblem(400, "InvalidInput", "Invalid JSON")
123
+ }
124
+ try {
125
+ return Schema.decodeUnknownSync(schema)(raw)
126
+ } catch (error) {
127
+ throw new HttpProblem(400, "InvalidInput", String(error))
128
+ }
129
+ }
130
+
131
+ export const makeHandler = (daemon: Daemon) => {
132
+ const trusted = daemon.options.trustedOrigins
133
+
134
+ const cors = (origin: string | undefined): Record<string, string> =>
135
+ origin !== undefined && trusted.includes(origin)
136
+ ? { "access-control-allow-origin": origin, vary: "Origin", "access-control-expose-headers": "mcp-session-id" }
137
+ : {}
138
+
139
+ /** Remove any kernel credential from text going back to a local client (defence in depth: none is expected). */
140
+ const scrub = async (text: string, extra: ReadonlyArray<string | undefined> = []) => {
141
+ let out = text
142
+ const credential = await daemon.options.secrets.get(credentialKey(daemon.options.stateDir))
143
+ for (const secret of [credential, ...extra]) {
144
+ if (secret !== undefined && secret.length > 0) out = out.split(secret).join("[redacted]")
145
+ }
146
+ return out
147
+ }
148
+
149
+ const client = (request: Request): AuthenticatedClient =>
150
+ daemon.auth.authenticate(request.headers.get("authorization") ?? undefined)
151
+
152
+ const notHarness = (who: AuthenticatedClient) => {
153
+ if (who.kind === "harness") throw new HttpProblem(403, "Forbidden", "A harness may use only the relay and MCP")
154
+ }
155
+
156
+ /** The kernel refused a relayed call: is it the device itself? (A refused credential marks it revoked.) */
157
+ const checkDevice = async () => {
158
+ try {
159
+ await daemon.withKernel((kernel) => kernel.me())
160
+ } catch {
161
+ // `withKernel` recorded a revocation; anything else leaves the pairing as it is.
162
+ }
163
+ }
164
+
165
+ /** A harness limited to some actions may call only those. */
166
+ const allowed = (who: AuthenticatedClient, action: string) =>
167
+ who.turn?.actions === undefined || who.turn.actions.has(action)
168
+
169
+ /** A runner turn the kernel cancelled (`Daemon.turnStopped`, which stops its harness): its calls are refused. */
170
+ const TURN_STOPPED = "This turn was cancelled; the call was not made"
171
+
172
+ const relayAction = async (request: Request, who: AuthenticatedClient, action: string) => {
173
+ if (!allowed(who, action)) throw new HttpProblem(403, "ToolNotAllowed", `This turn may not call ${action}`)
174
+ if (await daemon.turnStopped(who)) throw new HttpProblem(409, "TurnCancelled", TURN_STOPPED)
175
+ const text = await request.text()
176
+ if (text.length > MAX_BODY) throw new HttpProblem(413, "TooLarge", "The body is too large")
177
+ let input: unknown = {}
178
+ try {
179
+ input = text.length === 0 ? {} : JSON.parse(text)
180
+ } catch {
181
+ throw new HttpProblem(400, "InvalidInput", "Invalid JSON")
182
+ }
183
+ const headers: Record<string, string> = { "content-type": "application/json" }
184
+ const key = request.headers.get("idempotency-key") ?? daemon.idempotencyKey(who, action, input)
185
+ if (key !== undefined && key !== null) headers["idempotency-key"] = key
186
+ const version = request.headers.get("x-eloxiv-client-version")
187
+ if (version !== null) headers["x-eloxiv-client-version"] = version
188
+ const token = await daemon.relayToken(who, "action")
189
+ const response = await daemon.withKernel((kernel) =>
190
+ kernel.forward(`/api/actions/${encodeURIComponent(action)}`, { method: "POST", headers, body: text, token }),
191
+ )
192
+ if (response.status === 401) await checkDevice()
193
+ const body = await scrub(await response.text(), [token])
194
+ return new Response(body, {
195
+ status: response.status,
196
+ headers: { "content-type": response.headers.get("content-type") ?? "application/json" },
197
+ })
198
+ }
199
+
200
+ /** Add an idempotency key to each `tools/call` of a runner turn, so a re-run attempt replays. */
201
+ const keyToolCalls = (who: AuthenticatedClient, text: string) => {
202
+ if (who.turn?.idempotencyScope === undefined) return text
203
+ let parsed: unknown
204
+ try {
205
+ parsed = JSON.parse(text)
206
+ } catch {
207
+ return text
208
+ }
209
+ const messages = Array.isArray(parsed) ? parsed : [parsed]
210
+ for (const message of messages) {
211
+ const record = message as { method?: unknown; params?: Record<string, unknown> }
212
+ if (record?.method !== "tools/call" || typeof record.params !== "object" || record.params === null) continue
213
+ const meta = (record.params["_meta"] ?? {}) as Record<string, unknown>
214
+ if (meta[MCP_IDEMPOTENCY_META] !== undefined) continue
215
+ const key = daemon.idempotencyKey(who, String(record.params["name"]), record.params["arguments"] ?? {})
216
+ if (key !== undefined) record.params["_meta"] = { ...meta, [MCP_IDEMPOTENCY_META]: key }
217
+ }
218
+ return JSON.stringify(parsed)
219
+ }
220
+
221
+ /** A `tools/call` outside the turn's actions: answered here, never forwarded. */
222
+ const refusedToolCall = (who: AuthenticatedClient, text: string): Response | undefined => {
223
+ if (who.turn?.actions === undefined) return undefined
224
+ const names = new Set([...who.turn.actions].map((action) => toolName(action)))
225
+ let parsed: unknown
226
+ try {
227
+ parsed = JSON.parse(text)
228
+ } catch {
229
+ return undefined
230
+ }
231
+ for (const message of Array.isArray(parsed) ? parsed : [parsed]) {
232
+ const record = message as { id?: unknown; method?: unknown; params?: { name?: unknown } }
233
+ if (record?.method === "tools/call" && !names.has(String(record.params?.name))) {
234
+ return Response.json({
235
+ jsonrpc: "2.0",
236
+ id: record.id ?? null,
237
+ error: { code: -32602, message: `This turn may not call ${String(record.params?.name)}` },
238
+ })
239
+ }
240
+ }
241
+ return undefined
242
+ }
243
+
244
+ /** A `tools/call` of a runner turn the kernel cancelled: answered here (an error), never forwarded. */
245
+ const stoppedToolCall = async (who: AuthenticatedClient, text: string): Promise<Response | undefined> => {
246
+ if (who.turn === undefined) return undefined
247
+ let parsed: unknown
248
+ try {
249
+ parsed = JSON.parse(text)
250
+ } catch {
251
+ return undefined
252
+ }
253
+ const calls = (Array.isArray(parsed) ? parsed : [parsed]).filter(
254
+ (message) => (message as { method?: unknown })?.method === "tools/call",
255
+ ) as ReadonlyArray<{ id?: unknown }>
256
+ if (calls.length === 0 || !(await daemon.turnStopped(who))) return undefined
257
+ return Response.json({ jsonrpc: "2.0", id: calls[0]?.id ?? null, error: { code: -32000, message: TURN_STOPPED } })
258
+ }
259
+
260
+ const mcp = async (request: Request, who: AuthenticatedClient) => {
261
+ const token = await daemon.relayToken(who, "mcp")
262
+ const headers: Record<string, string> = {}
263
+ for (const name of ["content-type", "accept", "mcp-session-id", "mcp-protocol-version", "last-event-id"]) {
264
+ const value = request.headers.get(name)
265
+ if (value !== null) headers[name] = value
266
+ }
267
+ let body: string | undefined
268
+ if (request.method === "POST") {
269
+ body = await request.text()
270
+ if (body.length > MAX_BODY) throw new HttpProblem(413, "TooLarge", "The body is too large")
271
+ const refused = refusedToolCall(who, body)
272
+ if (refused !== undefined) return refused
273
+ const stopped = await stoppedToolCall(who, body)
274
+ if (stopped !== undefined) return stopped
275
+ body = keyToolCalls(who, body)
276
+ }
277
+ const response = await daemon.withKernel((kernel) =>
278
+ kernel.forward("/mcp", { method: request.method, headers, body: body ?? null, token }),
279
+ )
280
+ if (response.status === 401) {
281
+ await checkDevice()
282
+ // Never pass the kernel's OAuth challenge on: the harness authenticates to the daemon, not the kernel.
283
+ await response.body?.cancel()
284
+ throw new HttpProblem(401, "Unauthenticated", "The kernel refused this relay session")
285
+ }
286
+ const out: Record<string, string> = {}
287
+ for (const name of ["content-type", "mcp-session-id", "mcp-protocol-version"]) {
288
+ const value = response.headers.get(name)
289
+ if (value !== null) out[name] = value
290
+ }
291
+ return new Response(response.body, { status: response.status, headers: out })
292
+ }
293
+
294
+ const runTurn = async (request: Request, who: AuthenticatedClient) => {
295
+ notHarness(who)
296
+ const input = await readJson(request, HarnessTurnInput)
297
+ if (!daemon.paired) throw new HttpProblem(409, "NotPaired", "Pair this device with a kernel first")
298
+ const controller = new AbortController()
299
+ const encoder = new TextEncoder()
300
+ const turnId = `local-${crypto.randomUUID()}`
301
+ const stream = new ReadableStream<Uint8Array>({
302
+ start: (sink) => {
303
+ const send = (event: string, data: unknown) => {
304
+ try {
305
+ sink.enqueue(encoder.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`))
306
+ } catch {
307
+ // The client went away.
308
+ }
309
+ }
310
+ send("started", { turnId })
311
+ daemon
312
+ .runTurn({
313
+ turnId,
314
+ harness: input.harness,
315
+ prompt: input.prompt,
316
+ cwd: input.cwd ?? null,
317
+ model: input.model ?? null,
318
+ timeoutMs: Math.min(input.timeoutMs ?? DEFAULT_TURN_TIMEOUT_MS, MAX_TURN_TIMEOUT_MS),
319
+ actions: input.actions ?? null,
320
+ workspaceTools: input.workspaceTools ?? false,
321
+ resumable: input.resumable ?? false,
322
+ resume: input.resume ?? null,
323
+ signal: controller.signal,
324
+ onEvent: (event) => send("harness", event),
325
+ })
326
+ .then(
327
+ (result) => send("result", { ...result, events: undefined }),
328
+ (error: unknown) => send("result", { outcome: "failed", error: String(error) }),
329
+ )
330
+ .finally(() => {
331
+ try {
332
+ sink.close()
333
+ } catch {
334
+ // Already closed.
335
+ }
336
+ })
337
+ },
338
+ // Closing the request cancels the turn.
339
+ cancel: () => controller.abort(),
340
+ })
341
+ return new Response(stream, { headers: { "content-type": "text/event-stream", "cache-control": "no-store" } })
342
+ }
343
+
344
+ /** Terminals: only the host, the shell and CLIs (never a companion or a harness), each its own terminals. */
345
+ const terminals = async (request: Request, who: AuthenticatedClient, path: string): Promise<Response> => {
346
+ if (who.kind !== "host" && who.kind !== "shell" && who.kind !== "cli") {
347
+ throw new HttpProblem(403, "Forbidden", "Only the host, the shell or a CLI opens terminals")
348
+ }
349
+ const method = request.method
350
+ if (path === "/terminals" && method === "POST") {
351
+ const input = await readJson(request, TerminalOpen)
352
+ const opened = daemon.openTerminal(who.id, { cwd: input.cwd, cols: input.cols ?? 80, rows: input.rows ?? 24 })
353
+ return Response.json(opened, { status: 201 })
354
+ }
355
+ if (path === "/terminals" && method === "GET") return Response.json(daemon.terminals.list(who.id))
356
+ const match = /^\/terminals\/([^/]+)(?:\/(stream|input|resize))?$/u.exec(path)
357
+ if (match === null) throw new HttpProblem(404, "NotFound", `No route ${method} ${path}`)
358
+ const id = decodeURIComponent(match[1]!)
359
+ const action = match[2]
360
+ if (action === undefined && method === "DELETE") {
361
+ daemon.terminals.close(who.id, id)
362
+ return Response.json({ closed: true })
363
+ }
364
+ if (action === "input" && method === "POST") {
365
+ daemon.terminals.write(who.id, id, (await readJson(request, TerminalInput)).data)
366
+ return Response.json({ written: true })
367
+ }
368
+ if (action === "resize" && method === "POST") {
369
+ const size = await readJson(request, TerminalResize)
370
+ daemon.terminals.resize(who.id, id, size.cols, size.rows)
371
+ return Response.json({ resized: true })
372
+ }
373
+ if (action === "stream" && method === "GET") {
374
+ const encoder = new TextEncoder()
375
+ let stop: (() => void) | undefined
376
+ const stream = new ReadableStream<Uint8Array>({
377
+ start: (sink) => {
378
+ stop = daemon.terminals.watch(who.id, id, (event) => {
379
+ try {
380
+ sink.enqueue(encoder.encode(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`))
381
+ if (event.type === "exit") sink.close()
382
+ } catch {
383
+ // The client went away.
384
+ }
385
+ })
386
+ },
387
+ cancel: () => stop?.(),
388
+ })
389
+ return new Response(stream, { headers: { "content-type": "text/event-stream", "cache-control": "no-store" } })
390
+ }
391
+ throw new HttpProblem(404, "NotFound", `No route ${method} ${path}`)
392
+ }
393
+
394
+ const route = async (request: Request, path: string): Promise<Response> => {
395
+ const method = request.method
396
+ if (isClientPath(path)) return serveClient(daemon.client, request, path, () => client(request))
397
+ if (method === "GET" && path === "/health") {
398
+ return Response.json(
399
+ Schema.encodeSync(DaemonHealth)({
400
+ status: "ok",
401
+ version: DAEMON_VERSION,
402
+ runtime: currentRuntime(),
403
+ paired: daemon.paired,
404
+ }),
405
+ )
406
+ }
407
+ if (method === "POST" && path === "/local/pair/start") {
408
+ const input = await readJson(request, PairingRequestLocal)
409
+ return Response.json(daemon.auth.startPairing(input), { status: 201 })
410
+ }
411
+ if (method === "POST" && path === "/local/pair/confirm") {
412
+ const input = await readJson(request, PairingConfirm)
413
+ const { kind, ...result } = daemon.auth.confirmPairing(input)
414
+ daemon.onLocalClientPaired({ clientId: result.clientId, name: input.clientName, kind })
415
+ return Response.json(result)
416
+ }
417
+ const who = client(request)
418
+ if (method === "GET" && path === "/local/pairings") {
419
+ if (who.kind !== "host") throw new HttpProblem(403, "Forbidden", "Only the host sees pairing codes")
420
+ return Response.json(daemon.auth.pendingPairings())
421
+ }
422
+ const approval = /^\/local\/pairings\/([^/]+)\/approve$/u.exec(path)
423
+ if (method === "POST" && approval !== null) {
424
+ if (who.kind !== "host") throw new HttpProblem(403, "Forbidden", "Only the host approves pairings")
425
+ return Response.json(daemon.auth.approvePairing(decodeURIComponent(approval[1]!)))
426
+ }
427
+ if (path === "/mcp") return mcp(request, who)
428
+ if (method === "POST" && path.startsWith("/relay/actions/")) {
429
+ return relayAction(request, who, decodeURIComponent(path.slice("/relay/actions/".length)))
430
+ }
431
+ notHarness(who)
432
+ if (method === "GET" && path === "/status") return Response.json(await daemon.status())
433
+ if (method === "POST" && path === "/kernel-pairing/start") {
434
+ if (who.kind === "browser-extension") throw new HttpProblem(403, "Forbidden", "Not for browser extensions")
435
+ const input = await readJson(request, KernelPairingInput)
436
+ await daemon.startKernelPairing(input.kernelUrl, {
437
+ name: input.name,
438
+ kind: daemon.options.mode === "headless" ? "runner" : "desktop",
439
+ })
440
+ return Response.json(await daemon.status())
441
+ }
442
+ if (method === "GET" && path === "/harnesses") {
443
+ return Response.json(await daemon.harnessStatus(new URL(request.url).searchParams.get("refresh") === "1"))
444
+ }
445
+ if (method === "POST" && path === "/turns") return runTurn(request, who)
446
+ if (method === "GET" && path === "/sessions") return Response.json(daemon.sessions())
447
+ if (method === "GET" && path === "/capabilities") return Response.json(daemon.availability())
448
+ if (method === "GET" && path === "/computer-use") {
449
+ const computer = daemon.availability().computer
450
+ return Response.json({
451
+ available: computer.available,
452
+ reason: computer.reason ?? "A computer-use companion is connected",
453
+ })
454
+ }
455
+ if (method === "POST" && path === "/companion/commands/next") {
456
+ const kind = companionKindOf(who.kind)
457
+ if (kind === undefined) {
458
+ throw new HttpProblem(403, "Forbidden", "Only a browser-extension or computer-use client serves commands")
459
+ }
460
+ if (!daemon.commandEnabled(kind)) {
461
+ throw new HttpProblem(403, "CommandsNotEnabled", `${kind} commands are not enabled on this daemon`)
462
+ }
463
+ const input = await readJson(request, CompanionNext)
464
+ const command = await daemon.companions.next(
465
+ who,
466
+ kind,
467
+ Math.max(0, Math.min(input.waitMs ?? 0, 30_000)),
468
+ request.headers.get("origin"),
469
+ )
470
+ return Response.json({ command })
471
+ }
472
+ const result = /^\/companion\/commands\/([^/]+)\/result$/u.exec(path)
473
+ if (method === "POST" && result !== null) {
474
+ const input = await readJson(request, CompanionResult)
475
+ const taken = daemon.companions.settle(who.id, decodeURIComponent(result[1]!), {
476
+ outcome: input.outcome,
477
+ result: input.result ?? null,
478
+ error: input.error ?? (input.outcome === "failed" ? "The companion reported a failure" : null),
479
+ })
480
+ if (!taken) throw new HttpProblem(404, "NotFound", "This client holds no such command")
481
+ return Response.json({ accepted: true })
482
+ }
483
+ if (path === "/terminals" || path.startsWith("/terminals/")) return terminals(request, who, path)
484
+ if (method === "POST" && path === "/push") {
485
+ if (who.kind !== "host" && who.kind !== "shell" && who.kind !== "cli") {
486
+ throw new HttpProblem(403, "Forbidden", "Only the host, the shell or a CLI registers push")
487
+ }
488
+ const input = await readJson(request, PushInput)
489
+ if (!daemon.paired) throw new HttpProblem(409, "NotPaired", "Pair this device with a kernel first")
490
+ return Response.json(await daemon.registerPush(input.subscription))
491
+ }
492
+ throw new HttpProblem(404, "NotFound", `No route ${method} ${path}`)
493
+ }
494
+
495
+ return async (request: Request, host: string | undefined): Promise<Response> => {
496
+ const origin = request.headers.get("origin") ?? undefined
497
+ const path = new URL(request.url, "http://daemon").pathname
498
+ const headers = cors(origin)
499
+ let response: Response
500
+ try {
501
+ daemon.auth.checkHost(host)
502
+ if (request.method === "OPTIONS") {
503
+ daemon.auth.checkOrigin(origin)
504
+ return new Response(null, {
505
+ status: 204,
506
+ headers: {
507
+ ...headers,
508
+ "access-control-allow-methods": "GET, POST, DELETE",
509
+ "access-control-allow-headers":
510
+ "authorization, content-type, idempotency-key, mcp-session-id, mcp-protocol-version, last-event-id",
511
+ "access-control-max-age": "600",
512
+ },
513
+ })
514
+ }
515
+ // The sign-in callback is a browser's top-level navigation from the app's sign-in page: checked by its state.
516
+ if (path !== "/health" && path !== CLIENT_CALLBACK) daemon.auth.checkOrigin(origin)
517
+ response = await route(request, path)
518
+ } catch (error) {
519
+ if (isClientPath(path)) {
520
+ response = clientRefusal(error)
521
+ } else if (error instanceof LocalAuthError) {
522
+ response = Response.json(
523
+ { error: error.tag, message: error.message, ...error.detail },
524
+ { status: error.status, headers: error.status === 401 ? { "www-authenticate": "Bearer" } : {} },
525
+ )
526
+ } else if (error instanceof TerminalError) {
527
+ response = Response.json({ error: "TerminalRefused", message: error.message }, { status: error.status })
528
+ } else if (error instanceof HttpProblem) {
529
+ response = Response.json({ error: error.tag, message: error.message }, { status: error.status })
530
+ } else if (error instanceof PairingRefused) {
531
+ response = Response.json(
532
+ { error: error.tag, message: error.message },
533
+ { status: error.tag === "AlreadyPaired" ? 409 : 400 },
534
+ )
535
+ } else if (error instanceof DeviceRevoked) {
536
+ response = Response.json({ error: "DeviceNotPaired", message: error.message }, { status: 401 })
537
+ } else if (error instanceof KernelError) {
538
+ response = Response.json({ error: error.tag, message: error.message }, { status: 502 })
539
+ } else {
540
+ daemon.log(`request failed: ${String(error)}`)
541
+ response = Response.json({ error: "InternalError", message: "The daemon failed" }, { status: 500 })
542
+ }
543
+ }
544
+ for (const [name, value] of Object.entries(headers)) response.headers.set(name, value)
545
+ response.headers.set("cache-control", response.headers.get("cache-control") ?? "no-store")
546
+ return response
547
+ }
548
+ }
549
+
550
+ /** The daemon's HTTP application, ready for a platform `HttpServer`. */
551
+ export const DaemonHttp = (daemon: Daemon, options: { readonly requestLog?: boolean | undefined } = {}) => {
552
+ const handle = makeHandler(daemon)
553
+ return HttpRouter.serve(
554
+ HttpRouter.add("*", "/*", (request) =>
555
+ Effect.gen(function* () {
556
+ const web = yield* HttpServerRequest.toWeb(request).pipe(Effect.orDie)
557
+ const response = yield* Effect.promise(() => handle(web, request.headers["host"]))
558
+ return HttpServerResponse.fromWeb(response)
559
+ }),
560
+ ),
561
+ { disableLogger: options.requestLog !== true, disableListenLog: true },
562
+ )
563
+ }