@eloxiv/daemon 0.0.0-stage → 0.1.0

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 (114) 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 +100 -0
  12. package/dist/Client.d.ts.map +1 -0
  13. package/dist/Client.js +474 -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/Secrets.d.ts +21 -0
  48. package/dist/Secrets.d.ts.map +1 -0
  49. package/dist/Secrets.js +204 -0
  50. package/dist/Secrets.js.map +1 -0
  51. package/dist/SecureUrl.d.ts +11 -0
  52. package/dist/SecureUrl.d.ts.map +1 -0
  53. package/dist/SecureUrl.js +23 -0
  54. package/dist/SecureUrl.js.map +1 -0
  55. package/dist/State.d.ts +77 -0
  56. package/dist/State.d.ts.map +1 -0
  57. package/dist/State.js +38 -0
  58. package/dist/State.js.map +1 -0
  59. package/dist/Terminals.d.ts +49 -0
  60. package/dist/Terminals.d.ts.map +1 -0
  61. package/dist/Terminals.js +203 -0
  62. package/dist/Terminals.js.map +1 -0
  63. package/dist/bin-node.d.ts +2 -0
  64. package/dist/bin-node.d.ts.map +1 -0
  65. package/dist/bin-node.js +4 -0
  66. package/dist/bin-node.js.map +1 -0
  67. package/dist/bin.d.ts +2 -0
  68. package/dist/bin.d.ts.map +1 -0
  69. package/dist/bin.js +4 -0
  70. package/dist/bin.js.map +1 -0
  71. package/dist/index.d.ts +17 -0
  72. package/dist/index.d.ts.map +1 -0
  73. package/dist/index.js +17 -0
  74. package/dist/index.js.map +1 -0
  75. package/dist/runtime/bun.d.ts +11 -0
  76. package/dist/runtime/bun.d.ts.map +1 -0
  77. package/dist/runtime/bun.js +20 -0
  78. package/dist/runtime/bun.js.map +1 -0
  79. package/dist/runtime/node.d.ts +11 -0
  80. package/dist/runtime/node.d.ts.map +1 -0
  81. package/dist/runtime/node.js +21 -0
  82. package/dist/runtime/node.js.map +1 -0
  83. package/dist/testing.d.ts +25 -0
  84. package/dist/testing.d.ts.map +1 -0
  85. package/dist/testing.js +27 -0
  86. package/dist/testing.js.map +1 -0
  87. package/fixtures/claude-code-env-vars.txt +409 -0
  88. package/fixtures/fake-acp-agent.mjs +222 -0
  89. package/fixtures/fake-harness.mjs +299 -0
  90. package/fixtures/recorded/claude-code.jsonl +7 -0
  91. package/fixtures/recorded/codex.jsonl +6 -0
  92. package/package.json +64 -3
  93. package/scripts/build-sidecar.ts +86 -0
  94. package/src/Acp.ts +292 -0
  95. package/src/Canonical.ts +9 -0
  96. package/src/Client.ts +585 -0
  97. package/src/Commands.ts +427 -0
  98. package/src/Config.ts +179 -0
  99. package/src/Daemon.ts +1092 -0
  100. package/src/Harness.ts +839 -0
  101. package/src/Http.ts +563 -0
  102. package/src/KernelLink.ts +197 -0
  103. package/src/LocalAuth.ts +301 -0
  104. package/src/Main.ts +281 -0
  105. package/src/Secrets.ts +226 -0
  106. package/src/SecureUrl.ts +21 -0
  107. package/src/State.ts +109 -0
  108. package/src/Terminals.ts +227 -0
  109. package/src/bin-node.ts +4 -0
  110. package/src/bin.ts +4 -0
  111. package/src/index.ts +16 -0
  112. package/src/runtime/bun.ts +29 -0
  113. package/src/runtime/node.ts +30 -0
  114. package/src/testing.ts +43 -0
package/src/Client.ts ADDED
@@ -0,0 +1,585 @@
1
+ /**
2
+ * LocalClient v1 (decision 14; docs/contracts/local-client.md): the client core (`ClientRuntime`, from
3
+ * `@eloxiv/client/runtime`) served to native clients under `/client/v1` on the loopback relay, for an app that
4
+ * composed its sidecar with a `clientApp` (its sync schema, named queries, mutators and module contracts).
5
+ *
6
+ * The daemon holds a **person session** of its own, obtained by desktop sign-in with its own loopback callback
7
+ * (`/client/v1/sign-in/callback`) and kept in the secret store under its own key (`personSessionKey`), never in
8
+ * `state.json`; it is a second identity beside the device credential, which it never touches. Only the host and
9
+ * paired `desktop-app` clients may use it; no answer or event carries a kernel credential.
10
+ */
11
+ import {
12
+ ClientNotConfigured,
13
+ Forbidden,
14
+ InvalidInput,
15
+ LOCAL_CLIENT_BASE,
16
+ LOCAL_CLIENT_FEATURES,
17
+ LOCAL_CLIENT_HEARTBEAT_MS,
18
+ LOCAL_CLIENT_PROTOCOL,
19
+ LOCAL_CLIENT_SIGN_IN_TTL_MS,
20
+ LOCAL_CLIENT_VERSION,
21
+ LocalClientActionCall,
22
+ LocalClientError,
23
+ LocalClientFollowRun,
24
+ LocalClientSelectOrg,
25
+ LocalClientSubscribe,
26
+ LocalClientWrite,
27
+ ProtocolVersion,
28
+ Unauthenticated,
29
+ type AnyModuleContract,
30
+ } from "@eloxiv/contracts"
31
+ import type { SessionStore } from "@eloxiv/client"
32
+ import { makeClientRuntime, type ClientRuntime, type RuntimeEvent } from "@eloxiv/client/runtime"
33
+ import { sqliteStorage, type SyncSqliteDatabase } from "@eloxiv/client/storage"
34
+ import { createHash, timingSafeEqual } from "node:crypto"
35
+ import { mkdirSync, rmSync } from "node:fs"
36
+ import { join } from "node:path"
37
+ import { Schema } from "effect"
38
+ import { LocalAuthError, type AuthenticatedClient } from "./LocalAuth.ts"
39
+ import type { SecretStore } from "./Secrets.ts"
40
+ import { secureUrl } from "./SecureUrl.ts"
41
+
42
+ /** What an app composes into its sidecar so the daemon can serve LocalClient for it. */
43
+ export interface ClientApp {
44
+ /** The app's module contracts (`contracts` from `eloxiv.modules.ts`): its typed actions. */
45
+ readonly modules: ReadonlyArray<AnyModuleContract>
46
+ /** The app's sync schema, named queries and mutators (`eloxiv.sync.ts`). */
47
+ readonly schema: unknown
48
+ readonly queries: object
49
+ readonly mutators?: object | undefined
50
+ /** The kernel and zero-cache (default `ELOXIV_KERNEL_URL` and `ELOXIV_ZERO_URL`, read at start). */
51
+ readonly kernelUrl?: string | undefined
52
+ readonly zeroUrl?: string | undefined
53
+ /**
54
+ * The app's web page that approves a desktop sign-in (it calls `approveDesktopSignIn` with the `challenge`,
55
+ * `redirect_uri` and `state` it is opened with). Default `ELOXIV_SIGN_IN_PAGE`, else the web shell's
56
+ * `/desktop/sign-in` (the reference shell's approval page) at `shellUrl`.
57
+ */
58
+ readonly signInPage?: string | undefined
59
+ /**
60
+ * The app's web shell (its origin), whose `/desktop/sign-in` approves a desktop sign-in when `signInPage` is not
61
+ * given. Default `ELOXIV_SHELL_URL`, else `http://localhost:5173` (the shell's development server, which the
62
+ * kernel trusts by default).
63
+ */
64
+ readonly shellUrl?: string | undefined
65
+ /** The app build's version, sent with calls and writes. */
66
+ readonly clientVersion?: string | undefined
67
+ }
68
+
69
+ /** The reference web shell's approval page for a desktop sign-in (the Foldkit shell's `/desktop/sign-in`). */
70
+ const DESKTOP_SIGN_IN_PATH = "/desktop/sign-in"
71
+ /** The web shell's origin when nothing names it: its development server, a default trusted origin of the kernel. */
72
+ const DEFAULT_SHELL_URL = "http://localhost:5173"
73
+
74
+ /** The page a desktop sign-in opens: the app's `signInPage`, `ELOXIV_SIGN_IN_PAGE`, else the web shell's own. */
75
+ export const signInPageOf = (
76
+ app: Pick<ClientApp, "signInPage" | "shellUrl">,
77
+ env: Readonly<Record<string, string | undefined>>,
78
+ ): string =>
79
+ app.signInPage ??
80
+ env["ELOXIV_SIGN_IN_PAGE"] ??
81
+ `${(app.shellUrl ?? env["ELOXIV_SHELL_URL"] ?? DEFAULT_SHELL_URL).replace(/\/+$/u, "")}${DESKTOP_SIGN_IN_PATH}`
82
+
83
+ /** The secret-store key the person's session is kept under (per state directory, apart from the device credential). */
84
+ export const personSessionKey = (stateDir: string) =>
85
+ `person-session-${createHash("sha256").update(stateDir).digest("hex").slice(0, 16)}`
86
+
87
+ /** Where the replica's SQLite files live (one per person and organisation). */
88
+ export const replicaDirFor = (stateDir: string) => join(stateDir, "replicas")
89
+
90
+ /** A failure on `/client/v1`: its status and its LocalClient error. */
91
+ export class ClientProblem extends Error {
92
+ readonly status: number
93
+ readonly body: Record<string, unknown>
94
+ constructor(
95
+ status: number,
96
+ body: { readonly _tag: string; readonly message: string; readonly [key: string]: unknown },
97
+ ) {
98
+ super(body.message)
99
+ this.status = status
100
+ this.body = body
101
+ }
102
+ }
103
+
104
+ const STATUS: Record<string, number> = {
105
+ Unauthenticated: 401,
106
+ Forbidden: 403,
107
+ ApprovalRequired: 409,
108
+ ConsentRequired: 409,
109
+ IdempotencyConflict: 422,
110
+ InvalidInput: 400,
111
+ UnknownAction: 404,
112
+ ActionFailed: 500,
113
+ ClientOutdated: 426,
114
+ ClientNotConfigured: 404,
115
+ NotSignedIn: 409,
116
+ UnknownSubscription: 404,
117
+ UnknownQuery: 404,
118
+ UnknownMutator: 404,
119
+ StaleGeneration: 409,
120
+ SignInFailed: 502,
121
+ ProtocolVersion: 400,
122
+ }
123
+
124
+ const encodeError = Schema.encodeUnknownSync(LocalClientError)
125
+
126
+ /** A thrown value as a LocalClient refusal (`{ _tag, message, ...fields }`) with its status. */
127
+ export const problemOf = (error: unknown): ClientProblem => {
128
+ if (error instanceof ClientProblem) return error
129
+ const tag = (error as { readonly _tag?: unknown } | undefined)?._tag
130
+ if (typeof tag === "string" && tag in STATUS) {
131
+ let body: Record<string, unknown>
132
+ try {
133
+ body = encodeError(error)
134
+ } catch {
135
+ const message = (error as { readonly message?: unknown }).message
136
+ body = { ...(error as object), _tag: tag, message: typeof message === "string" ? message : String(error) }
137
+ }
138
+ return new ClientProblem(STATUS[tag]!, body as { _tag: string; message: string })
139
+ }
140
+ return new ClientProblem(500, { _tag: "ActionFailed", action: "client", message: "The daemon failed" })
141
+ }
142
+
143
+ /** The person's session in the daemon's secret store. */
144
+ const secretSessionStore = (secrets: SecretStore, key: string, onChange: (token: string | undefined) => void) => {
145
+ const store: SessionStore = {
146
+ load: async () => {
147
+ const token = await secrets.get(key)
148
+ onChange(token)
149
+ return token
150
+ },
151
+ save: async (token) => {
152
+ await secrets.set(key, token)
153
+ onChange(token)
154
+ },
155
+ clear: async () => {
156
+ await secrets.delete(key)
157
+ onChange(undefined)
158
+ },
159
+ }
160
+ return store
161
+ }
162
+
163
+ interface Stream {
164
+ readonly client: string
165
+ seq: number
166
+ readonly send: (text: string) => void
167
+ readonly end: () => void
168
+ }
169
+
170
+ const same = (a: string, b: string) => {
171
+ const left = createHash("sha256").update(a).digest()
172
+ const right = createHash("sha256").update(b).digest()
173
+ return timingSafeEqual(left, right)
174
+ }
175
+
176
+ const page = (title: string, text: string) =>
177
+ `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width">` +
178
+ `<title>${title}</title></head><body style="font-family:system-ui,sans-serif;margin:3rem auto;max-width:28rem">` +
179
+ `<h1 style="font-size:1.25rem">${title}</h1><p>${text}</p></body></html>`
180
+
181
+ const html = (status: number, title: string, text: string) =>
182
+ new Response(page(title, text), {
183
+ status,
184
+ headers: {
185
+ "content-type": "text/html; charset=utf-8",
186
+ "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'",
187
+ "referrer-policy": "no-referrer",
188
+ "x-frame-options": "DENY",
189
+ },
190
+ })
191
+
192
+ const MAX_BODY = 1024 * 1024
193
+
194
+ const readBody = async <A, I>(request: Request, schema: Schema.Codec<A, I>): Promise<A> => {
195
+ const text = await request.text()
196
+ if (text.length > MAX_BODY) throw new InvalidInput({ message: "The body is too large" })
197
+ let raw: unknown
198
+ try {
199
+ raw = text.length === 0 ? {} : JSON.parse(text)
200
+ } catch {
201
+ throw new InvalidInput({ message: "Invalid JSON" })
202
+ }
203
+ try {
204
+ return Schema.decodeUnknownSync(schema)(raw)
205
+ } catch (error) {
206
+ throw new InvalidInput({ message: String(error) })
207
+ }
208
+ }
209
+
210
+ export interface LocalClientServiceOptions {
211
+ readonly app: ClientApp
212
+ readonly stateDir: string
213
+ readonly secrets: SecretStore
214
+ /** Opens the runtime's synchronous SQLite (`bun:sqlite`, `node:sqlite`); memory storage without one. */
215
+ readonly sqlite?: ((path: string) => SyncSqliteDatabase) | undefined
216
+ /** The daemon's port, once listening (the callback's redirect names it). */
217
+ readonly port: () => number
218
+ /** Credentials no answer may carry (the device credential), for the scrub. */
219
+ readonly credentials: () => Promise<ReadonlyArray<string | undefined>>
220
+ readonly env?: Readonly<Record<string, string | undefined>> | undefined
221
+ readonly log: (line: string) => void
222
+ }
223
+
224
+ /** `/client/v1`, over one `ClientRuntime` for the daemon's person session. */
225
+ export class LocalClientService {
226
+ readonly runtime: ClientRuntime
227
+ readonly kernelUrl: string
228
+ readonly #options: LocalClientServiceOptions
229
+ readonly #streams = new Map<string, Stream>()
230
+ #personToken: string | undefined
231
+ /** The device credential and any other the daemon holds, refreshed with each request (for the scrub). */
232
+ #credentials: ReadonlyArray<string | undefined> = []
233
+ #pending: { readonly login: Parameters<ClientRuntime["completeSignIn"]>[0]; readonly expiresAt: number } | undefined
234
+ #expiry: ReturnType<typeof setTimeout> | undefined
235
+ #started: Promise<unknown> | undefined
236
+
237
+ constructor(options: LocalClientServiceOptions) {
238
+ this.#options = options
239
+ const env = options.env ?? process.env
240
+ const kernelUrl = options.app.kernelUrl ?? env["ELOXIV_KERNEL_URL"]
241
+ const zeroUrl = options.app.zeroUrl ?? env["ELOXIV_ZERO_URL"]
242
+ if (kernelUrl === undefined || zeroUrl === undefined) {
243
+ throw new Error(
244
+ "A clientApp needs its kernel and zero-cache URLs (kernelUrl, zeroUrl or ELOXIV_KERNEL_URL, ELOXIV_ZERO_URL)",
245
+ )
246
+ }
247
+ // Checked before the person session is loaded: it goes to both, so neither may be plain http off loopback.
248
+ this.kernelUrl = secureUrl(kernelUrl, "The kernel")
249
+ const zero = secureUrl(zeroUrl, "zero-cache")
250
+ let storage: ReturnType<typeof sqliteStorage> | undefined
251
+ if (options.sqlite !== undefined) {
252
+ const directory = replicaDirFor(options.stateDir)
253
+ mkdirSync(directory, { recursive: true, mode: 0o700 })
254
+ storage = sqliteStorage(options.sqlite, { directory, remove: (path) => rmSync(path, { force: true }) })
255
+ }
256
+ this.runtime = makeClientRuntime({
257
+ kernelUrl: this.kernelUrl,
258
+ zeroUrl: zero,
259
+ schema: options.app.schema as never,
260
+ queries: options.app.queries,
261
+ mutators: options.app.mutators,
262
+ modules: options.app.modules,
263
+ sessionStore: secretSessionStore(options.secrets, personSessionKey(options.stateDir), (token) => {
264
+ if (token !== undefined) this.#personToken = token
265
+ }),
266
+ storage: storage?.storage,
267
+ clientVersion: options.app.clientVersion,
268
+ log: (line) => options.log(`client: ${line}`),
269
+ })
270
+ this.runtime.onEvent((event) => this.#broadcast(event))
271
+ }
272
+
273
+ /** Check the stored person session (once, when the daemon is listening). */
274
+ start(): Promise<unknown> {
275
+ this.#started ??= Promise.all([this.#refreshCredentials(), this.runtime.start()]).catch((error: unknown) =>
276
+ this.#options.log(`client: start failed: ${String(error)}`),
277
+ )
278
+ return this.#started
279
+ }
280
+
281
+ async #refreshCredentials() {
282
+ this.#credentials = await this.#options.credentials()
283
+ }
284
+
285
+ async close() {
286
+ if (this.#expiry !== undefined) clearTimeout(this.#expiry)
287
+ for (const stream of this.#streams.values()) stream.end()
288
+ this.#streams.clear()
289
+ await this.runtime.close()
290
+ }
291
+
292
+ /** Remove every credential from text going to a local client (defence in depth: none is expected). */
293
+ #scrub(text: string): string {
294
+ let out = text
295
+ for (const secret of [this.#personToken, ...this.#credentials]) {
296
+ if (secret !== undefined && secret.length > 0) out = out.split(secret).join("[redacted]")
297
+ }
298
+ return out
299
+ }
300
+
301
+ #broadcast(event: RuntimeEvent) {
302
+ const { owner, ...rest } = event
303
+ for (const stream of this.#streams.values()) {
304
+ if (owner !== undefined && owner !== stream.client) continue
305
+ stream.seq += 1
306
+ stream.send(`data: ${this.#scrub(JSON.stringify({ seq: stream.seq, ...rest }))}\n\n`)
307
+ }
308
+ }
309
+
310
+ #json(body: unknown, status = 200): Response {
311
+ return new Response(this.#scrub(JSON.stringify(body)), {
312
+ status,
313
+ headers: { "content-type": "application/json", "cache-control": "no-store" },
314
+ })
315
+ }
316
+
317
+ /** A refusal as LocalClient answers it. */
318
+ refusal(error: unknown): Response {
319
+ const problem = problemOf(error)
320
+ if (problem.status === 500) this.#options.log(`client: request failed: ${String(error)}`)
321
+ return this.#json(problem.body, problem.status)
322
+ }
323
+
324
+ /** The redirect the browser comes back to: the daemon's own callback, on 127.0.0.1 (the kernel accepts no other). */
325
+ #redirectUri = () => `http://127.0.0.1:${this.#options.port()}/client/v1/sign-in/callback`
326
+
327
+ /** The sign-in waiting for `state`, if it is the one this daemon issued and has not expired. */
328
+ #pendingFor(state: string) {
329
+ const pending = this.#pending
330
+ if (pending === undefined || pending.expiresAt <= Date.now() || state.length === 0) return undefined
331
+ return same(state, pending.login.state) ? pending : undefined
332
+ }
333
+
334
+ /** The browser's redirect: state-checked, accepted once and within the sign-in's time; no local token. */
335
+ async callback(request: Request): Promise<Response> {
336
+ const url = new URL(request.url, "http://daemon")
337
+ const code = url.searchParams.get("code") ?? ""
338
+ const state = url.searchParams.get("state") ?? ""
339
+ const pending = this.#pendingFor(state)
340
+ if (pending === undefined || code.length === 0 || code.length > 512) {
341
+ return html(400, "This sign-in link is not valid", "Start signing in again from the app.")
342
+ }
343
+ // One use: forgotten before it is redeemed, so a second arrival (a reload, a replay) is refused.
344
+ this.#pending = undefined
345
+ if (this.#expiry !== undefined) clearTimeout(this.#expiry)
346
+ try {
347
+ await this.runtime.completeSignIn(pending.login, { code, state })
348
+ } catch (error) {
349
+ this.#options.log(`client: the sign-in failed: ${error instanceof Error ? error.message : String(error)}`)
350
+ return html(502, "The sign-in did not complete", "Return to the app and try again.")
351
+ }
352
+ return html(200, "You are signed in", "You can return to the app.")
353
+ }
354
+
355
+ /** The routes under `/client/v1` (after the prefix), each for an authenticated host or desktop app. */
356
+ readonly #routes: ReadonlyArray<
357
+ readonly [string, RegExp, (request: Request, owner: string, match: RegExpExecArray) => Promise<Response> | Response]
358
+ > = [
359
+ ["GET", /^\/hello$/u, () => this.#json(this.#hello())],
360
+ ["GET", /^\/session$/u, () => this.#json(this.runtime.session())],
361
+ ["POST", /^\/sign-in$/u, (request) => this.#signIn(request)],
362
+ [
363
+ "POST",
364
+ /^\/org$/u,
365
+ async (request) => {
366
+ const input = await readBody(request, LocalClientSelectOrg)
367
+ return this.#json({ generation: await this.runtime.selectOrg(input.orgId) })
368
+ },
369
+ ],
370
+ [
371
+ "POST",
372
+ /^\/sign-out$/u,
373
+ async (request) => {
374
+ await readBody(request, Schema.Struct({}))
375
+ this.#pending = undefined
376
+ await this.runtime.signOut()
377
+ return this.#json({ ok: true })
378
+ },
379
+ ],
380
+ ["GET", /^\/events$/u, (request, owner) => this.#events(request, owner)],
381
+ [
382
+ "POST",
383
+ /^\/subscriptions$/u,
384
+ async (request, owner) =>
385
+ this.#json(await this.runtime.subscribe(await readBody(request, LocalClientSubscribe), owner)),
386
+ ],
387
+ [
388
+ "DELETE",
389
+ /^\/subscriptions\/([^/]+)$/u,
390
+ (_request, owner, match) => {
391
+ this.runtime.unsubscribe(decodeURIComponent(match[1]!), owner)
392
+ return this.#json({ ok: true })
393
+ },
394
+ ],
395
+ [
396
+ "POST",
397
+ /^\/writes$/u,
398
+ async (request, owner) => this.#json(await this.runtime.write(await readBody(request, LocalClientWrite), owner)),
399
+ ],
400
+ [
401
+ "POST",
402
+ /^\/runs$/u,
403
+ async (request, owner) =>
404
+ this.#json(await this.runtime.followRun(await readBody(request, LocalClientFollowRun), owner)),
405
+ ],
406
+ [
407
+ "DELETE",
408
+ /^\/runs\/([^/]+)$/u,
409
+ (_request, owner, match) => {
410
+ this.runtime.unfollowRun(decodeURIComponent(match[1]!), owner)
411
+ return this.#json({ ok: true })
412
+ },
413
+ ],
414
+ ["GET", /^\/agent\/readiness$/u, async () => this.#json(await this.runtime.agentReadiness())],
415
+ [
416
+ "POST",
417
+ /^\/actions\/([^/]+)$/u,
418
+ async (request, _owner, match) => {
419
+ const input = await readBody(request, LocalClientActionCall)
420
+ return this.#json(
421
+ await this.runtime.call(
422
+ decodeURIComponent(match[1]!),
423
+ input.input ?? {},
424
+ input.idempotencyKey,
425
+ input.generation,
426
+ ),
427
+ )
428
+ },
429
+ ],
430
+ ]
431
+
432
+ #hello() {
433
+ return {
434
+ protocol: LOCAL_CLIENT_PROTOCOL,
435
+ version: LOCAL_CLIENT_VERSION,
436
+ features: [...LOCAL_CLIENT_FEATURES],
437
+ app: this.runtime.app,
438
+ }
439
+ }
440
+
441
+ /** Start a desktop sign-in: the callback is bound (this daemon's), its state kept for 60 s, once. */
442
+ async #signIn(request: Request): Promise<Response> {
443
+ await readBody(request, Schema.Struct({}))
444
+ const login = await this.runtime.beginSignIn(this.#redirectUri())
445
+ this.#pending = { login, expiresAt: Date.now() + LOCAL_CLIENT_SIGN_IN_TTL_MS }
446
+ if (this.#expiry !== undefined) clearTimeout(this.#expiry)
447
+ this.#expiry = setTimeout(() => {
448
+ if (this.#pending?.login !== login) return
449
+ this.#pending = undefined
450
+ this.runtime.cancelSignIn()
451
+ }, LOCAL_CLIENT_SIGN_IN_TTL_MS)
452
+ this.#expiry.unref?.()
453
+ const env = this.#options.env ?? process.env
454
+ const pageUrl = signInPageOf(this.#options.app, env)
455
+ return this.#json({ url: `${pageUrl}${pageUrl.includes("?") ? "&" : "?"}${login.query}`, state: login.state })
456
+ }
457
+
458
+ /** Every other `/client/v1` route, for an authenticated client: only the host and desktop apps. */
459
+ async handle(request: Request, path: string, who: AuthenticatedClient): Promise<Response> {
460
+ if (who.kind !== "host" && who.kind !== "desktop-app") {
461
+ throw new Forbidden({ action: "client/v1", message: "Only the host and paired desktop apps use LocalClient" })
462
+ }
463
+ const asked = request.headers.get("x-eloxiv-local-client")
464
+ if (asked !== null && asked.split(".")[0] !== LOCAL_CLIENT_VERSION.split(".")[0]) {
465
+ throw new ProtocolVersion({
466
+ version: LOCAL_CLIENT_VERSION,
467
+ message: `This daemon speaks LocalClient ${LOCAL_CLIENT_VERSION}`,
468
+ })
469
+ }
470
+ await this.start()
471
+ await this.#refreshCredentials()
472
+ const route = path.slice(LOCAL_CLIENT_BASE.length)
473
+ for (const [method, pattern, run] of this.#routes) {
474
+ const match = method === request.method ? pattern.exec(route) : null
475
+ if (match !== null) return run(request, who.id, match)
476
+ }
477
+ throw new ClientProblem(404, {
478
+ _tag: "UnknownAction",
479
+ action: route,
480
+ message: `No route ${request.method} ${path}`,
481
+ })
482
+ }
483
+
484
+ /** The client's event stream: one per client (a new one closes the old); closing it ends its subscriptions. */
485
+ #events(request: Request, owner: string): Response {
486
+ this.#streams.get(owner)?.end()
487
+ const encoder = new TextEncoder()
488
+ let heartbeat: ReturnType<typeof setInterval> | undefined
489
+ let stream: Stream | undefined
490
+ const finish = () => {
491
+ if (heartbeat !== undefined) clearInterval(heartbeat)
492
+ heartbeat = undefined
493
+ if (stream !== undefined && this.#streams.get(owner) === stream) {
494
+ this.#streams.delete(owner)
495
+ this.runtime.unsubscribeAll(owner)
496
+ this.runtime.unfollowAll(owner)
497
+ }
498
+ }
499
+ const body = new ReadableStream<Uint8Array>({
500
+ start: (sink) => {
501
+ let open = true
502
+ stream = {
503
+ client: owner,
504
+ seq: 0,
505
+ send: (text) => {
506
+ if (!open) return
507
+ try {
508
+ sink.enqueue(encoder.encode(text))
509
+ } catch {
510
+ open = false
511
+ finish()
512
+ }
513
+ },
514
+ end: () => {
515
+ if (!open) return
516
+ open = false
517
+ finish()
518
+ try {
519
+ sink.close()
520
+ } catch {
521
+ // Already closed.
522
+ }
523
+ },
524
+ }
525
+ this.#streams.set(owner, stream)
526
+ // The stream opens with the current session, so a client starts from it.
527
+ stream.seq += 1
528
+ const first = this.#scrub(JSON.stringify({ seq: stream.seq, type: "session", session: this.runtime.session() }))
529
+ stream.send(`retry: 2000\ndata: ${first}\n\n`)
530
+ heartbeat = setInterval(() => stream?.send(": heartbeat\n\n"), LOCAL_CLIENT_HEARTBEAT_MS)
531
+ heartbeat.unref?.()
532
+ request.signal?.addEventListener("abort", () => stream?.end(), { once: true })
533
+ },
534
+ cancel: () => stream?.end(),
535
+ })
536
+ return new Response(body, {
537
+ headers: { "content-type": "text/event-stream", "cache-control": "no-store", "x-accel-buffering": "no" },
538
+ })
539
+ }
540
+ }
541
+
542
+ /** `/client/v1` on a daemon without a `clientApp`. */
543
+ const notConfigured = () =>
544
+ new ClientNotConfigured({
545
+ message: "This daemon was not composed with an app (clientApp): LocalClient is not served",
546
+ })
547
+
548
+ /** Whether `path` is one of LocalClient's (under `/client/v1`). */
549
+ export const isClientPath = (path: string) => path === LOCAL_CLIENT_BASE || path.startsWith(`${LOCAL_CLIENT_BASE}/`)
550
+ /** The one browser-facing route: no token, no Origin check, checked by its state. */
551
+ export const CLIENT_CALLBACK = `${LOCAL_CLIENT_BASE}/sign-in/callback`
552
+
553
+ /** A refusal on `/client/v1` before the service answers (no app, the Host or Origin, the token): `{ _tag, message }`. */
554
+ export const clientRefusal = (error: unknown): Response => {
555
+ const problem = problemOf(
556
+ error instanceof LocalAuthError
557
+ ? error.status === 401
558
+ ? new Unauthenticated({ message: error.message })
559
+ : { _tag: error.status === 403 ? "Forbidden" : "InvalidInput", action: "client/v1", message: error.message }
560
+ : error,
561
+ )
562
+ return Response.json(problem.body, {
563
+ status: problem.status,
564
+ headers: problem.status === 401 ? { "www-authenticate": "Bearer" } : {},
565
+ })
566
+ }
567
+
568
+ /**
569
+ * Serve one `/client/v1` request: `404 ClientNotConfigured` without a service; the callback without a token;
570
+ * everything else for the client `authenticate` names (it throws for a missing or unknown token).
571
+ */
572
+ export const serveClient = async (
573
+ service: LocalClientService | undefined,
574
+ request: Request,
575
+ path: string,
576
+ authenticate: () => AuthenticatedClient,
577
+ ): Promise<Response> => {
578
+ try {
579
+ if (service === undefined) throw notConfigured()
580
+ if (request.method === "GET" && path === CLIENT_CALLBACK) return await service.callback(request)
581
+ return await service.handle(request, path, authenticate())
582
+ } catch (error) {
583
+ return service === undefined || error instanceof LocalAuthError ? clientRefusal(error) : service.refusal(error)
584
+ }
585
+ }