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