@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/Daemon.ts ADDED
@@ -0,0 +1,1092 @@
1
+ /**
2
+ * The daemon's core, independent of the HTTP layer: the kernel pairing and the credential's custody, local
3
+ * clients, the relay's kernel sessions, local harness turns, the headless runner loop, and the sessions it
4
+ * reports (DeviceControl).
5
+ */
6
+ import type {
7
+ ClaimedCommand,
8
+ CommandKind,
9
+ DaemonStatus,
10
+ DeviceAvailability,
11
+ DeviceCapabilities,
12
+ DeviceSession,
13
+ HarnessEvent,
14
+ HarnessKind,
15
+ HarnessStatus,
16
+ PairingStarted,
17
+ PushSubscriptionInfo,
18
+ } from "@eloxiv/contracts"
19
+ import { commandKindOf } from "@eloxiv/contracts"
20
+ import { randomBytes } from "node:crypto"
21
+ import { chmodSync, mkdirSync, mkdtempSync, rmdirSync, rmSync, writeFileSync } from "node:fs"
22
+ import { hostname, platform, tmpdir } from "node:os"
23
+ import { join, resolve } from "node:path"
24
+ import { canonicalize } from "./Canonical.ts"
25
+ import { LocalClientService, type ClientApp } from "./Client.ts"
26
+ import type { SyncSqliteDatabase } from "@eloxiv/client/storage"
27
+ import { CompanionQueue, confine, isLocalKind, runLocalCommand, type CommandOutcome } from "./Commands.ts"
28
+ import { ptyAvailable, TerminalError, Terminals } from "./Terminals.ts"
29
+ import { runAcpHarness } from "./Acp.ts"
30
+ import { detectHarness, harnessConfigs, runHarness, type HarnessConfig, type HarnessResult } from "./Harness.ts"
31
+ import { DeviceRevoked, KernelError, KernelLink, pollPairing, startPairing } from "./KernelLink.ts"
32
+ import { LocalAuth, type AuthenticatedClient, type LocalPairingOptions } from "./LocalAuth.ts"
33
+ import { credentialKey, type SecretStore } from "./Secrets.ts"
34
+ import { secureUrl } from "./SecureUrl.ts"
35
+ import { sha256Hex, StateFile, type HarnessSessionRecord, type PendingCompletion } from "./State.ts"
36
+
37
+ export interface DaemonOptions {
38
+ readonly mode: "desktop" | "headless"
39
+ readonly stateDir: string
40
+ readonly secrets: SecretStore
41
+ readonly hostSecret?: string | undefined
42
+ readonly trustedOrigins: ReadonlyArray<string>
43
+ /** Harness commands (default: `claude` and `codex` on the PATH, or the environment's overrides). */
44
+ readonly harnesses?: Partial<Record<HarnessKind, HarnessConfig>> | undefined
45
+ /**
46
+ * The working directory turns run in when they name none; never inside the state directory. Default: a fresh,
47
+ * empty temporary directory per turn, removed when the turn ends.
48
+ */
49
+ readonly workspace?: string | undefined
50
+ /** Where diagnostics go (default: stderr; stdout carries only the ready line). */
51
+ readonly log?: ((line: string) => void) | undefined
52
+ /** Local pairing settings. */
53
+ readonly localPairing?: LocalPairingOptions | undefined
54
+ /** How long a runner's long poll waits (ms, default 25 s). */
55
+ readonly pollWaitMs?: number | undefined
56
+ /** The longest wait between retries of a turn's report (ms, default 30 s). */
57
+ readonly retryBackoffMaxMs?: number | undefined
58
+ /** Print the ready line on stdout once listening (default true; in-process tests turn it off). */
59
+ readonly announce?: boolean | undefined
60
+ /**
61
+ * The device command kinds this daemon serves (DeviceControl): `terminal` and `files` (in the workspace, which
62
+ * they need), `browser` and `computer` (through a companion). None by default.
63
+ */
64
+ readonly commands?: ReadonlyArray<CommandKind> | undefined
65
+ /** The tools-only profile: turns never get workspace tools, and the terminal and files cannot be enabled. */
66
+ readonly toolsOnly?: boolean | undefined
67
+ /**
68
+ * The app this sidecar serves LocalClient for (decision 14; `/client/v1`): its sync schema, named queries,
69
+ * mutators and module contracts. Without it, `/client/v1` answers `404 ClientNotConfigured`.
70
+ */
71
+ readonly clientApp?: ClientApp | undefined
72
+ /** The runtime's synchronous SQLite (`bun:sqlite`, `node:sqlite`) for LocalClient's replica (default memory). */
73
+ readonly sqlite?: ((path: string) => SyncSqliteDatabase) | undefined
74
+ /** The environment a `clientApp` reads its defaults from (default `process.env`). */
75
+ readonly env?: Readonly<Record<string, string | undefined>> | undefined
76
+ }
77
+
78
+ const KINDS: ReadonlyArray<HarnessKind> = ["claude-code", "codex", "opencode", "acp"]
79
+
80
+ /** How often a command the daemon took asks the kernel whether it was cancelled (ms). */
81
+ export const COMMAND_CHECK_MS = 1_000
82
+
83
+ /** The device commands one daemon runs at once. */
84
+ export const MAX_COMMANDS_AT_ONCE = 4
85
+
86
+ /** Events per `appendTurnEvents` call: a larger backlog goes in several calls, in order. */
87
+ export const EVENT_PAGE = 200
88
+
89
+ /** The daemon refused a kernel pairing it was asked for. */
90
+ export class PairingRefused extends Error {
91
+ override readonly name = "PairingRefused"
92
+ readonly tag: "AlreadyPaired" | "InvalidInput"
93
+ constructor(tag: "AlreadyPaired" | "InvalidInput", message: string) {
94
+ super(message)
95
+ this.tag = tag
96
+ }
97
+ }
98
+
99
+ /**
100
+ * A kernel the daemon may pair with: `https`, or `http` only on loopback (a local kernel). A plain-http kernel
101
+ * elsewhere would see the device credential in clear.
102
+ */
103
+ export const checkKernelUrl = (raw: string) => {
104
+ try {
105
+ return secureUrl(raw)
106
+ } catch (error) {
107
+ throw new PairingRefused("InvalidInput", (error as Error).message)
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Where turns that name no directory work: one fresh directory each, under a root per state directory, outside
113
+ * it; the root is emptied when a daemon starts, so a killed process leaves nothing behind for long.
114
+ */
115
+ export const turnRootFor = (stateDir: string) =>
116
+ join(tmpdir(), `eloxiv-turns-${sha256Hex(resolve(stateDir)).slice(0, 16)}`)
117
+
118
+ /**
119
+ * Where resumable turns that name no directory keep theirs: one per kept harness session, outside the state
120
+ * directory, removed when the session is forgotten (never emptied at start-up: a follow-up needs it).
121
+ */
122
+ export const sessionRootFor = (stateDir: string) =>
123
+ join(tmpdir(), `eloxiv-sessions-${sha256Hex(resolve(stateDir)).slice(0, 16)}`)
124
+
125
+ /** How many harness sessions the daemon keeps for follow-ups; the least recently used beyond it are forgotten. */
126
+ export const MAX_HARNESS_SESSIONS = 50
127
+
128
+ /** The file `eloxiv-daemon approve-client` reads the daemon's control secret from (0600). */
129
+ export const controlSecretPath = (stateDir: string) => join(stateDir, "control.secret")
130
+
131
+ export class Daemon {
132
+ readonly state: StateFile
133
+ readonly auth: LocalAuth
134
+ readonly log: (line: string) => void
135
+ readonly harnesses: Record<HarnessKind, HarnessConfig>
136
+ #port = 0
137
+ #pairing: { started: PairingStarted; url: string; done: Promise<void> } | undefined
138
+ #pairingError: string | undefined
139
+ #harnessStatus: ReadonlyArray<HarnessStatus> | undefined
140
+ #runner: { stop: () => void; done: Promise<void> } | undefined
141
+ /** Relay sessions for local clients' MCP use (agent-originated), by client id. */
142
+ readonly #relaySessions = new Map<string, { token: string; expiresAt: number }>()
143
+ /** Per-turn occurrence counters for runner tool calls (idempotency keys). */
144
+ readonly #occurrences = new Map<string, Map<string, number>>()
145
+ /** The runner turn being served, by id: asks the kernel (a heartbeat) whether it was cancelled, stopping it if so. */
146
+ readonly #turnChecks = new Map<string, () => Promise<boolean>>()
147
+ readonly #sessions = new Map<string, DeviceSession>()
148
+ /** The session report in flight, if any: the next waits for it (`reportSessions`). */
149
+ #reportingSessions: Promise<void> = Promise.resolve()
150
+ #commandLoop: { stop: () => void; done: Promise<void> } | undefined
151
+ #commandsRunning = 0
152
+ /** The capabilities last reported to the kernel (JSON), so only a change is reported again. */
153
+ #reportedCapabilities: string | undefined
154
+ /** Browser and computer commands waiting for their companion. */
155
+ readonly companions: CompanionQueue
156
+ /** Terminal sessions of local clients (`POST /terminals`). */
157
+ readonly terminals: Terminals
158
+ /** LocalClient (`/client/v1`), when the sidecar was composed with a `clientApp`. */
159
+ readonly client: LocalClientService | undefined
160
+
161
+ readonly options: DaemonOptions
162
+
163
+ constructor(options: DaemonOptions) {
164
+ this.options = options
165
+ // The terminal and files act in the workspace, which they need; the tools-only profile allows neither.
166
+ const local = (options.commands ?? []).filter(isLocalKind)
167
+ if (local.length > 0 && options.toolsOnly === true) {
168
+ throw new Error(`The tools-only profile cannot serve ${local.join(" or ")} commands`)
169
+ }
170
+ if (local.length > 0 && options.workspace === undefined) {
171
+ throw new Error(`${local.join(" and ")} commands need a workspace (--workspace)`)
172
+ }
173
+ this.companions = new CompanionQueue(() => this.capabilitiesChanged())
174
+ this.terminals = new Terminals((terminal) => {
175
+ this.#sessions.set(`terminal:${terminal.id}`, {
176
+ id: `terminal:${terminal.id}`,
177
+ kind: "terminal",
178
+ label: `terminal ${terminal.id}`,
179
+ startedAt: terminal.startedAt,
180
+ endedAt: terminal.endedAt,
181
+ detail: terminal.pty ? "pty" : "pipes",
182
+ })
183
+ void this.reportSessions()
184
+ })
185
+ this.log = options.log ?? ((line) => process.stderr.write(`[eloxiv-daemon] ${line}\n`))
186
+ this.state = new StateFile(options.stateDir)
187
+ // A per-start secret for `eloxiv-daemon approve-client` (the person at this machine, acting as the host).
188
+ const controlSecret = randomBytes(32).toString("base64url")
189
+ writeFileSync(controlSecretPath(options.stateDir), `${controlSecret}\n`, { mode: 0o600 })
190
+ chmodSync(controlSecretPath(options.stateDir), 0o600)
191
+ this.auth = new LocalAuth(this.state, {
192
+ ...options.localPairing,
193
+ hostSecret: options.hostSecret,
194
+ controlSecret,
195
+ trustedOrigins: options.trustedOrigins,
196
+ log: this.log,
197
+ })
198
+ this.harnesses = { ...harnessConfigs(), ...options.harnesses }
199
+ this.client = this.#clientService(options)
200
+ // A runner that died mid-turn: the kernel takes the turn back when this process says it is fresh.
201
+ if (this.state.current.inflight !== undefined) this.state.update((s) => ({ ...s, inflight: undefined }))
202
+ // Private files of turns a killed process left behind.
203
+ rmSync(join(options.stateDir, "turns"), { recursive: true, force: true })
204
+ // Working directories of turns a killed process left behind (outside the state directory).
205
+ rmSync(turnRootFor(options.stateDir), { recursive: true, force: true })
206
+ for (const client of this.state.current.localClients) {
207
+ this.#sessions.set(`client:${client.id}`, {
208
+ id: `client:${client.id}`,
209
+ kind: client.kind,
210
+ label: client.name,
211
+ startedAt: client.pairedAt,
212
+ endedAt: null,
213
+ detail: null,
214
+ })
215
+ }
216
+ }
217
+
218
+ /** LocalClient's service, for a sidecar composed with a `clientApp`. */
219
+ #clientService(options: DaemonOptions): LocalClientService | undefined {
220
+ if (options.clientApp === undefined) return undefined
221
+ return new LocalClientService({
222
+ app: options.clientApp,
223
+ stateDir: options.stateDir,
224
+ secrets: options.secrets,
225
+ sqlite: options.sqlite,
226
+ port: () => this.#port,
227
+ credentials: async () => [await this.credential()],
228
+ env: options.env,
229
+ log: this.log,
230
+ })
231
+ }
232
+
233
+ get port() {
234
+ return this.#port
235
+ }
236
+
237
+ set port(port: number) {
238
+ this.#port = port
239
+ this.auth.port = port
240
+ }
241
+
242
+ // --- kernel pairing and custody ------------------------------------------------------------------------------
243
+
244
+ private credential = () => this.options.secrets.get(credentialKey(this.options.stateDir))
245
+
246
+ /** Is the daemon paired with a kernel that (as far as it knows) still accepts it? */
247
+ get paired() {
248
+ const kernel = this.state.current.kernel
249
+ return kernel !== undefined && kernel.revokedAt === undefined
250
+ }
251
+
252
+ /** The kernel as this device, or undefined when unpaired or revoked. */
253
+ kernel(): KernelLink | undefined {
254
+ const kernel = this.state.current.kernel
255
+ if (kernel === undefined || kernel.revokedAt !== undefined) return undefined
256
+ return new KernelLink(kernel.url, this.credential)
257
+ }
258
+
259
+ /** The kernel refused the credential: forget it, and say so. */
260
+ async markRevoked(reason: string) {
261
+ if (this.state.current.kernel === undefined || this.state.current.kernel.revokedAt !== undefined) return
262
+ this.log(`the kernel refused this device (${reason}); it is no longer paired`)
263
+ this.state.update((s) => ({ ...s, kernel: s.kernel && { ...s.kernel, revokedAt: new Date().toISOString() } }))
264
+ await this.options.secrets.delete(credentialKey(this.options.stateDir))
265
+ this.#relaySessions.clear()
266
+ this.#runner?.stop()
267
+ this.#commandLoop?.stop()
268
+ this.forgetSessions(() => true)
269
+ }
270
+
271
+ /**
272
+ * Run `body` against the kernel. A refused credential is checked once more (`GET /kernel/device/me`): only
273
+ * when the kernel refuses the device itself is it marked revoked and the credential deleted.
274
+ */
275
+ async withKernel<A>(body: (kernel: KernelLink) => Promise<A>): Promise<A> {
276
+ const kernel = this.kernel()
277
+ if (kernel === undefined) throw new DeviceRevoked("This daemon is not paired with a kernel")
278
+ try {
279
+ return await body(kernel)
280
+ } catch (error) {
281
+ if (error instanceof DeviceRevoked) await this.confirmRevocation(kernel, error.message)
282
+ throw error
283
+ }
284
+ }
285
+
286
+ private async confirmRevocation(kernel: KernelLink, reason: string) {
287
+ try {
288
+ await kernel.me()
289
+ } catch (error) {
290
+ if (error instanceof DeviceRevoked) await this.markRevoked(reason)
291
+ }
292
+ }
293
+
294
+ /** Is the daemon started with this command kind (`--allow-commands`)? */
295
+ commandEnabled(kind: CommandKind) {
296
+ return (this.options.commands ?? []).includes(kind)
297
+ }
298
+
299
+ /** Each command kind's availability now: enabled, and for a browser or the computer, a companion connected. */
300
+ availability(): DeviceAvailability {
301
+ const local = (kind: "terminal" | "files") => ({
302
+ enabled: this.commandEnabled(kind),
303
+ available: this.commandEnabled(kind),
304
+ reason: this.commandEnabled(kind)
305
+ ? null
306
+ : this.options.toolsOnly === true
307
+ ? "This daemon runs the tools-only profile"
308
+ : `Not enabled on this daemon (start it with --allow-commands ${kind} and a --workspace)`,
309
+ })
310
+ const companion = (kind: "browser" | "computer", client: string) => {
311
+ const enabled = this.commandEnabled(kind)
312
+ const connected = this.companions.connected(kind)
313
+ return {
314
+ enabled,
315
+ available: enabled && connected,
316
+ reason: !enabled
317
+ ? `Not enabled on this daemon (start it with --allow-commands ${kind})`
318
+ : connected
319
+ ? null
320
+ : `No ${client} companion is connected to this daemon`,
321
+ }
322
+ }
323
+ return {
324
+ terminal: local("terminal"),
325
+ files: local("files"),
326
+ browser: companion("browser", "browser-extension"),
327
+ computer: companion("computer", "computer-use"),
328
+ pty: ptyAvailable(),
329
+ toolsOnly: this.options.toolsOnly === true,
330
+ }
331
+ }
332
+
333
+ /** The command kinds the daemon can serve now. */
334
+ availableKinds(): ReadonlyArray<CommandKind> {
335
+ const availability = this.availability()
336
+ return (["terminal", "files", "browser", "computer"] as const).filter((kind) => availability[kind].available)
337
+ }
338
+
339
+ async capabilities(): Promise<DeviceCapabilities> {
340
+ const statuses = await this.harnessStatus()
341
+ const kinds = this.availableKinds()
342
+ return {
343
+ harnesses: statuses.filter((status) => status.available).map((status) => status.kind),
344
+ computerUse: kinds.includes("computer"),
345
+ browserExtension: kinds.includes("browser"),
346
+ commands: kinds,
347
+ toolsOnly: this.options.toolsOnly === true,
348
+ }
349
+ }
350
+
351
+ /** Tell the kernel what the device offers now, if that changed since the last report. */
352
+ async reportCapabilities() {
353
+ if (!this.paired) return
354
+ const capabilities = await this.capabilities()
355
+ const json = JSON.stringify(capabilities)
356
+ if (json === this.#reportedCapabilities) return
357
+ try {
358
+ await this.withKernel((kernel) => kernel.reportCapabilities(capabilities))
359
+ this.#reportedCapabilities = json
360
+ } catch {
361
+ // Best effort: the next change (or the command loop) reports again.
362
+ }
363
+ }
364
+
365
+ /** A companion connected or went away: report what the device offers, and its sessions. */
366
+ private capabilitiesChanged() {
367
+ void this.reportCapabilities()
368
+ void this.reportSessions()
369
+ }
370
+
371
+ /**
372
+ * Start pairing with the kernel at `url`: the kernel's user code is in the returned status (and the log). The
373
+ * daemon polls in the background and stores the credential once a signed-in person confirms the code.
374
+ */
375
+ async startKernelPairing(raw: string, request: { name?: string | undefined; kind: "desktop" | "runner" }) {
376
+ if (this.#pairing !== undefined) return this.#pairing
377
+ const url = checkKernelUrl(raw)
378
+ // One kernel at a time: pairing elsewhere first needs this pairing revoked (or `eloxiv-daemon unpair`).
379
+ if (this.paired) {
380
+ throw new PairingRefused(
381
+ "AlreadyPaired",
382
+ `This daemon is paired with ${this.state.current.kernel!.url}; revoke it there or run \`eloxiv-daemon unpair\` first`,
383
+ )
384
+ }
385
+ const started = await startPairing(url, {
386
+ name: (request.name ?? `${hostname()} (${request.kind})`).slice(0, 100),
387
+ kind: request.kind,
388
+ platform: `${platform()}-${process.arch}`,
389
+ capabilities: await this.capabilities(),
390
+ })
391
+ this.#pairingError = undefined
392
+ // Never the code: logs are collected, and whoever reads the code first can confirm it under their own account.
393
+ // It is shown only to the authenticated host or control channel (`/status`, `eloxiv-daemon pairing-code`) and
394
+ // in interactive output (`eloxiv-daemon pair`, a headless start on a terminal).
395
+ this.log(
396
+ `pairing with ${url}: confirm the code at ${started.verificationUri}; it is shown in the desktop app, by \`eloxiv-daemon pairing-code\` or \`eloxiv-daemon pair\``,
397
+ )
398
+ const done = this.pollUntilPaired(url, started, request.kind).finally(() => {
399
+ this.#pairing = undefined
400
+ })
401
+ this.#pairing = { started, url, done }
402
+ return this.#pairing
403
+ }
404
+
405
+ private async pollUntilPaired(url: string, started: PairingStarted, kind: "desktop" | "runner") {
406
+ while (true) {
407
+ await new Promise((resolve) => setTimeout(resolve, started.interval * 1000))
408
+ let result
409
+ try {
410
+ result = await pollPairing(url, started.pairingId, started.pollSecret)
411
+ } catch (error) {
412
+ if (error instanceof KernelError) {
413
+ this.#pairingError = error.message
414
+ throw error
415
+ }
416
+ continue
417
+ }
418
+ if (result.status === "pending") continue
419
+ if (result.status !== "paired") {
420
+ this.#pairingError = `The pairing was ${result.status}`
421
+ throw new Error(this.#pairingError)
422
+ }
423
+ await this.options.secrets.set(credentialKey(this.options.stateDir), result.credential)
424
+ this.state.update((s) => ({
425
+ ...s,
426
+ kernel: {
427
+ url,
428
+ deviceId: result.deviceId,
429
+ orgId: result.orgId,
430
+ subject: result.subject,
431
+ name: `${hostname()} (${kind})`,
432
+ kind,
433
+ pairedAt: new Date().toISOString(),
434
+ },
435
+ }))
436
+ this.log(`paired as device ${result.deviceId} in ${result.orgId}`)
437
+ void this.reportSessions()
438
+ this.startCommands()
439
+ return
440
+ }
441
+ }
442
+
443
+ /** Forget the kernel pairing (the device stays listed on the kernel until someone revokes it there). */
444
+ async unpair() {
445
+ this.#runner?.stop()
446
+ this.#commandLoop?.stop()
447
+ await this.options.secrets.delete(credentialKey(this.options.stateDir))
448
+ this.state.update((s) => ({ ...s, kernel: undefined }))
449
+ this.forgetSessions(() => true)
450
+ }
451
+
452
+ // --- harness sessions (follow-ups) ---------------------------------------------------------------------------
453
+
454
+ /** The harness sessions resumable turns kept, newest last. */
455
+ get harnessSessions(): ReadonlyArray<HarnessSessionRecord> {
456
+ return this.state.current.harnessSessions ?? []
457
+ }
458
+
459
+ /** Forget the kept sessions `which` selects, removing the directories the daemon created for them. */
460
+ private forgetSessions(which: (record: HarnessSessionRecord) => boolean) {
461
+ const forgotten = this.harnessSessions.filter(which)
462
+ if (forgotten.length === 0) return
463
+ const kept = this.harnessSessions.filter((record) => !which(record))
464
+ this.state.update((s) => ({ ...s, harnessSessions: kept }))
465
+ for (const record of forgotten) {
466
+ if (record.owned && !kept.some((other) => other.cwd === record.cwd)) {
467
+ rmSync(record.cwd, { recursive: true, force: true })
468
+ }
469
+ }
470
+ }
471
+
472
+ /** Keep `record` (replacing the session it continues), and forget the least recently used beyond the limit. */
473
+ private keepSession(record: HarnessSessionRecord, replaces: string | undefined) {
474
+ const others = this.harnessSessions.filter((r) => r.id !== record.id && r.id !== replaces)
475
+ this.state.update((s) => ({ ...s, harnessSessions: [...others, record] }))
476
+ const excess = this.harnessSessions.length - MAX_HARNESS_SESSIONS
477
+ if (excess > 0) {
478
+ const oldest = new Set(this.harnessSessions.slice(0, excess).map((r) => r.id))
479
+ this.forgetSessions((r) => oldest.has(r.id))
480
+ }
481
+ }
482
+
483
+ async harnessStatus(refresh = false): Promise<ReadonlyArray<HarnessStatus>> {
484
+ if (this.#harnessStatus === undefined || refresh) {
485
+ this.#harnessStatus = await Promise.all(KINDS.map((kind) => detectHarness(this.harnesses[kind])))
486
+ }
487
+ return this.#harnessStatus
488
+ }
489
+
490
+ async status(): Promise<DaemonStatus> {
491
+ const kernel = this.state.current.kernel
492
+ const pairing = this.#pairing
493
+ return {
494
+ mode: this.options.mode,
495
+ kernel: {
496
+ state:
497
+ pairing !== undefined
498
+ ? "pairing"
499
+ : kernel === undefined
500
+ ? "unpaired"
501
+ : kernel.revokedAt !== undefined
502
+ ? "revoked"
503
+ : "paired",
504
+ url: pairing?.url ?? kernel?.url ?? null,
505
+ deviceId: kernel?.deviceId ?? null,
506
+ orgId: kernel?.orgId ?? null,
507
+ userCode: pairing?.started.userCode ?? null,
508
+ verificationUri: pairing?.started.verificationUriComplete ?? null,
509
+ },
510
+ secretStore: this.options.secrets.kind,
511
+ harnesses: await this.harnessStatus(),
512
+ }
513
+ }
514
+
515
+ get pairingError() {
516
+ return this.#pairingError
517
+ }
518
+
519
+ // --- relay ---------------------------------------------------------------------------------------------------
520
+
521
+ /**
522
+ * The kernel credential a relayed call uses: a harness's turn session (agent-originated), a short-lived agent
523
+ * session for a local client's MCP use, or the device credential (the person) for a local client's action
524
+ * calls. Never returned to the client.
525
+ */
526
+ async relayToken(client: AuthenticatedClient, purpose: "action" | "mcp"): Promise<string | undefined> {
527
+ if (client.turn !== undefined) return client.turn.agentToken
528
+ if (purpose === "action") return undefined // the device credential, read by KernelLink
529
+ const cached = this.#relaySessions.get(client.id)
530
+ if (cached !== undefined && cached.expiresAt > Date.now() + 60_000) return cached.token
531
+ const session = await this.withKernel((kernel) =>
532
+ kernel.relaySession(`mcp for ${client.kind} ${client.name}`, 3600),
533
+ )
534
+ this.#relaySessions.set(client.id, { token: session.token, expiresAt: Date.parse(session.expiresAt) })
535
+ return session.token
536
+ }
537
+
538
+ /**
539
+ * The idempotency key a runner turn's tool call gets: the turn, the tool, its input and how many identical
540
+ * calls came before it in this attempt. A re-run attempt making the same calls replays them instead of acting
541
+ * again; a different call is a new key.
542
+ */
543
+ idempotencyKey(client: AuthenticatedClient, tool: string, input: unknown): string | undefined {
544
+ const scope = client.turn?.idempotencyScope
545
+ if (scope === undefined) return undefined
546
+ const hash = sha256Hex(`${tool}\u0000${canonicalize(input)}`).slice(0, 24)
547
+ const counters = this.#occurrences.get(scope) ?? new Map<string, number>()
548
+ this.#occurrences.set(scope, counters)
549
+ const occurrence = counters.get(hash) ?? 0
550
+ counters.set(hash, occurrence + 1)
551
+ return `${scope}:${hash}:${occurrence}`
552
+ }
553
+
554
+ /**
555
+ * Before the relay forwards a call of a runner turn's harness: whether the turn was cancelled (or its lease
556
+ * lost). The runner otherwise hears of a cancellation only at its next heartbeat, and the harness could act in
557
+ * between; this asks the kernel now (a heartbeat), and a cancelled turn's harness is stopped before the call is
558
+ * refused. Not a runner turn (a local client's): false.
559
+ */
560
+ async turnStopped(client: AuthenticatedClient): Promise<boolean> {
561
+ const turnId = client.turn?.turnId
562
+ const check = turnId === undefined ? undefined : this.#turnChecks.get(turnId)
563
+ return check === undefined ? false : await check()
564
+ }
565
+
566
+ // --- turns ---------------------------------------------------------------------------------------------------
567
+
568
+ /**
569
+ * Run one harness turn on this machine with the Eloxiv tools through the relay, as the device's subject's
570
+ * agent (an agent session bound to this device). `scope` makes tool calls idempotent per turn (runner turns).
571
+ */
572
+ async runTurn(input: {
573
+ readonly turnId: string
574
+ readonly harness: HarnessKind
575
+ readonly prompt: string
576
+ readonly cwd: string | null
577
+ readonly model: string | null
578
+ readonly timeoutMs: number
579
+ readonly idempotencyScope?: string | undefined
580
+ /** A turn the kernel queued (a runner turn): its relay session carries the authority of whoever queued it. */
581
+ readonly kernelTurn?: boolean | undefined
582
+ /** The Eloxiv actions the turn may call (undefined or null: every action the person's policy allows). */
583
+ readonly actions?: ReadonlyArray<string> | null | undefined
584
+ readonly workspaceTools?: boolean | undefined
585
+ /** Keep the harness session (and its working directory) for a follow-up. */
586
+ readonly resumable?: boolean | undefined
587
+ /** Resume a session a resumable turn kept here (a follow-up); any other fails the turn without running. */
588
+ readonly resume?: string | null | undefined
589
+ readonly signal?: AbortSignal | undefined
590
+ readonly onEvent?: ((event: HarnessEvent) => void) | undefined
591
+ readonly onRawLine?: ((line: string) => void) | undefined
592
+ }): Promise<HarnessResult> {
593
+ // A follow-up resumes only a session this daemon kept, with its harness, in its working directory.
594
+ const resume = input.resume ?? undefined
595
+ const resumed =
596
+ resume === undefined
597
+ ? undefined
598
+ : this.harnessSessions.find((r) => r.id === resume && r.harness === input.harness)
599
+ if (resume !== undefined && resumed === undefined) {
600
+ return {
601
+ outcome: "failed",
602
+ result: null,
603
+ usage: null,
604
+ error: `This device keeps no ${input.harness} session ${resume} to follow up`,
605
+ events: [],
606
+ sessionId: null,
607
+ }
608
+ }
609
+ // The tools-only profile never gives a harness its built-in file and shell tools.
610
+ if (input.workspaceTools === true && this.options.toolsOnly === true) {
611
+ return {
612
+ outcome: "failed",
613
+ result: null,
614
+ usage: null,
615
+ error: "This device runs the tools-only profile: turns cannot have workspace tools",
616
+ events: [],
617
+ sessionId: null,
618
+ }
619
+ }
620
+ const keep = input.resumable === true || resumed !== undefined
621
+ const session = await this.withKernel((kernel) =>
622
+ kernel.relaySession(
623
+ `turn ${input.turnId}`,
624
+ input.timeoutMs / 1000 + 300,
625
+ input.kernelTurn === true ? input.turnId : undefined,
626
+ ),
627
+ )
628
+ const grant = this.auth.grantHarness({
629
+ turnId: input.turnId,
630
+ agentToken: session.token,
631
+ idempotencyScope: input.idempotencyScope,
632
+ actions: input.actions === undefined || input.actions === null ? undefined : new Set(input.actions),
633
+ })
634
+ // No named directory: a fresh, empty one, outside the state directory, removed with the turn.
635
+ const turnRoot = turnRootFor(this.options.stateDir)
636
+ let scratchCwd: string | undefined
637
+ let sessionCwd: string | undefined
638
+ if (resumed === undefined && input.cwd === null && this.options.workspace === undefined) {
639
+ if (keep) {
640
+ // A resumable turn's directory outlives the turn: the follow-up resumes the session in it.
641
+ const root = sessionRootFor(this.options.stateDir)
642
+ mkdirSync(root, { recursive: true, mode: 0o700 })
643
+ sessionCwd = mkdtempSync(join(root, "session-"))
644
+ } else {
645
+ mkdirSync(turnRoot, { recursive: true, mode: 0o700 })
646
+ scratchCwd = mkdtempSync(join(turnRoot, "turn-"))
647
+ }
648
+ }
649
+ const cwd = resumed?.cwd ?? input.cwd ?? this.options.workspace ?? sessionCwd ?? scratchCwd!
650
+ const sessionId = `turn:${input.turnId}`
651
+ this.#sessions.set(sessionId, {
652
+ id: sessionId,
653
+ kind: "harness",
654
+ label: `${input.harness} turn ${input.turnId}`,
655
+ startedAt: new Date().toISOString(),
656
+ endedAt: null,
657
+ detail: input.harness,
658
+ })
659
+ void this.reportSessions()
660
+ let kept = false
661
+ try {
662
+ const config = this.harnesses[input.harness]
663
+ const result = await (config.protocol === "acp" ? runAcpHarness : runHarness)(config, {
664
+ prompt: input.prompt,
665
+ cwd,
666
+ resumable: keep,
667
+ resume,
668
+ workspaceTools: input.workspaceTools,
669
+ model: input.model,
670
+ timeoutMs: input.timeoutMs,
671
+ mcp: { url: `http://127.0.0.1:${this.#port}/mcp`, token: grant.token },
672
+ scratchRoot: join(this.options.stateDir, "turns"),
673
+ signal: input.signal,
674
+ onEvent: input.onEvent,
675
+ onRawLine: input.onRawLine,
676
+ })
677
+ if (keep && result.sessionId !== null) {
678
+ this.keepSession(
679
+ {
680
+ id: result.sessionId,
681
+ harness: input.harness,
682
+ cwd,
683
+ owned: resumed?.owned ?? sessionCwd !== undefined,
684
+ turnId: input.turnId,
685
+ lastUsedAt: new Date().toISOString(),
686
+ },
687
+ resumed?.id,
688
+ )
689
+ kept = true
690
+ }
691
+ return result
692
+ } finally {
693
+ grant.revoke()
694
+ // A resumable turn that left no session to resume: its directory goes with it.
695
+ if (sessionCwd !== undefined && !kept) rmSync(sessionCwd, { recursive: true, force: true })
696
+ if (scratchCwd !== undefined) {
697
+ rmSync(scratchCwd, { recursive: true, force: true })
698
+ // The root too, once no other turn uses it.
699
+ try {
700
+ rmdirSync(turnRoot)
701
+ } catch {
702
+ // Another turn is still working in it.
703
+ }
704
+ }
705
+ if (input.idempotencyScope !== undefined) this.#occurrences.delete(input.idempotencyScope)
706
+ const session = this.#sessions.get(sessionId)
707
+ if (session !== undefined) this.#sessions.set(sessionId, { ...session, endedAt: new Date().toISOString() })
708
+ void this.reportSessions()
709
+ }
710
+ }
711
+
712
+ // --- the headless runner -------------------------------------------------------------------------------------
713
+
714
+ /** Serve turns addressed to this device until stopped or revoked. */
715
+ startRunner() {
716
+ if (this.#runner !== undefined) return this.#runner
717
+ const controller = new AbortController()
718
+ const done = this.runnerLoop(controller.signal).finally(() => {
719
+ this.#runner = undefined
720
+ })
721
+ this.#runner = { stop: () => controller.abort(), done }
722
+ return this.#runner
723
+ }
724
+
725
+ private async runnerLoop(signal: AbortSignal) {
726
+ // A result a previous process could not report goes first: asking for work as a fresh runner would put
727
+ // its turn back in the queue and run it again.
728
+ const pending = this.state.current.pendingCompletion
729
+ if (pending !== undefined) await this.complete(pending, signal)
730
+ if (signal.aborted) return
731
+ let fresh = true
732
+ let backoff = 500
733
+ while (!signal.aborted && this.paired) {
734
+ let claimed
735
+ try {
736
+ claimed = await this.withKernel((kernel) => kernel.nextTurn(this.options.pollWaitMs ?? 25_000, fresh, signal))
737
+ fresh = false
738
+ backoff = 500
739
+ } catch (error) {
740
+ if (signal.aborted || error instanceof DeviceRevoked) return
741
+ this.log(`runner: could not reach the kernel (${String(error)}); retrying`)
742
+ await new Promise((resolve) => setTimeout(resolve, backoff))
743
+ backoff = Math.min(backoff * 2, 10_000)
744
+ continue
745
+ }
746
+ if (claimed.turn === null) continue
747
+ await this.serveTurn(claimed.turn, signal)
748
+ }
749
+ }
750
+
751
+ private async serveTurn(
752
+ turn: NonNullable<Awaited<ReturnType<KernelLink["nextTurn"]>>["turn"]>,
753
+ stopSignal: AbortSignal,
754
+ ) {
755
+ this.log(`runner: turn ${turn.id} attempt ${turn.attempt} (${turn.harness})`)
756
+ this.state.update((s) => ({
757
+ ...s,
758
+ inflight: { turnId: turn.id, attempt: turn.attempt, since: new Date().toISOString() },
759
+ }))
760
+ const controller = new AbortController()
761
+ const onStop = () => controller.abort()
762
+ stopSignal.addEventListener("abort", onStop, { once: true })
763
+ const pending: Array<HarnessEvent & { seq: number }> = []
764
+ let seq = 0
765
+ let flushing: Promise<void> = Promise.resolve()
766
+ let lost = false
767
+ /**
768
+ * Send what is pending in pages (or an empty heartbeat); stop the harness when the kernel says so. A page the
769
+ * kernel did not take stays pending, in order, for the next call: nothing is dropped.
770
+ */
771
+ const send = async (): Promise<void> => {
772
+ do {
773
+ if (lost) return
774
+ const batch = pending.slice(0, EVENT_PAGE)
775
+ try {
776
+ const answer = await this.withKernel((kernel) => kernel.appendEvents(turn.id, turn.lease, batch))
777
+ pending.splice(0, batch.length)
778
+ if (answer.stop) controller.abort()
779
+ } catch (error) {
780
+ if ((error instanceof KernelError && error.status === 409) || error instanceof DeviceRevoked) {
781
+ lost = true
782
+ controller.abort()
783
+ }
784
+ return
785
+ }
786
+ } while (pending.length > 0)
787
+ }
788
+ const flush = () => {
789
+ flushing = flushing.then(send)
790
+ return flushing
791
+ }
792
+ // A relayed call asks first (`turnStopped`): pending events and a heartbeat go out, and a stop is acted on.
793
+ this.#turnChecks.set(turn.id, async () => {
794
+ await flush()
795
+ return controller.signal.aborted
796
+ })
797
+ // Heartbeat and batching: events go out every 300 ms, and an empty batch renews the lease.
798
+ let lastFlush = Date.now()
799
+ const ticker = setInterval(
800
+ () => {
801
+ if (pending.length > 0 || Date.now() - lastFlush > turn.leaseMs / 3) {
802
+ lastFlush = Date.now()
803
+ void flush()
804
+ }
805
+ },
806
+ Math.min(300, turn.leaseMs / 4),
807
+ )
808
+ let result: HarnessResult
809
+ try {
810
+ result = await this.runTurn({
811
+ turnId: turn.id,
812
+ harness: turn.harness,
813
+ prompt: turn.prompt,
814
+ cwd: turn.cwd,
815
+ model: turn.model,
816
+ timeoutMs: turn.timeoutMs,
817
+ idempotencyScope: `device-turn:${turn.id}`,
818
+ kernelTurn: true,
819
+ actions: turn.actions,
820
+ workspaceTools: turn.workspaceTools,
821
+ resumable: turn.resumable,
822
+ resume: turn.resume,
823
+ signal: controller.signal,
824
+ onEvent: (event) => {
825
+ pending.push({ ...event, seq: seq++ })
826
+ },
827
+ })
828
+ } catch (error) {
829
+ result = {
830
+ outcome: "failed",
831
+ result: null,
832
+ usage: null,
833
+ error: String(error),
834
+ events: [],
835
+ sessionId: null,
836
+ }
837
+ } finally {
838
+ clearInterval(ticker)
839
+ stopSignal.removeEventListener("abort", onStop)
840
+ this.#turnChecks.delete(turn.id)
841
+ }
842
+ // The events still pending go out (in pages) while the lease holds; give up on them only once it is lost.
843
+ for (let attempt = 0; attempt < 20; attempt++) {
844
+ if (pending.length === 0 || lost || stopSignal.aborted) break
845
+ await flush()
846
+ if (pending.length > 0) await new Promise((resolve) => setTimeout(resolve, Math.min(250 * 2 ** attempt, 5_000)))
847
+ }
848
+ await flush()
849
+ if (stopSignal.aborted && result.outcome === "cancelled") return // the daemon is stopping: leave the turn leased
850
+ if (!lost) {
851
+ await this.complete(
852
+ {
853
+ turnId: turn.id,
854
+ lease: turn.lease,
855
+ outcome: result.outcome === "succeeded" ? "succeeded" : "failed",
856
+ result: result.result,
857
+ usage: result.usage,
858
+ error: result.error,
859
+ sessionId: turn.resumable === true || (turn.resume ?? null) !== null ? result.sessionId : null,
860
+ },
861
+ stopSignal,
862
+ )
863
+ }
864
+ this.state.update((s) => ({ ...s, inflight: undefined }))
865
+ }
866
+
867
+ /**
868
+ * Report a turn's outcome until the kernel takes it: the result is kept in the state file first, so a restart
869
+ * reports it too, and it is retried (with backoff, without a cap on attempts) until the kernel settles the
870
+ * turn, says this attempt lost its lease, or refuses the device. Only those clear it.
871
+ */
872
+ private async complete(completion: PendingCompletion, signal: AbortSignal) {
873
+ this.state.update((s) => ({ ...s, pendingCompletion: completion }))
874
+ const max = this.options.retryBackoffMaxMs ?? 30_000
875
+ let backoff = Math.min(250, max)
876
+ while (!signal.aborted) {
877
+ try {
878
+ const settled = await this.withKernel((kernel) => kernel.completeTurn(completion))
879
+ this.log(
880
+ `runner: turn ${completion.turnId} ${settled.duplicate ? "was already settled" : `settled ${completion.outcome}`}`,
881
+ )
882
+ break
883
+ } catch (error) {
884
+ if (error instanceof KernelError && error.status === 409) {
885
+ this.log(`runner: turn ${completion.turnId} is no longer this attempt's; its result is dropped`)
886
+ break
887
+ }
888
+ if (error instanceof DeviceRevoked && !this.paired) break
889
+ await new Promise((resolve) => setTimeout(resolve, backoff))
890
+ backoff = Math.min(backoff * 2, max)
891
+ }
892
+ }
893
+ if (!signal.aborted) this.state.update((s) => ({ ...s, pendingCompletion: undefined }))
894
+ }
895
+
896
+ async stopRunner() {
897
+ const runner = this.#runner
898
+ runner?.stop()
899
+ await runner?.done
900
+ }
901
+
902
+ // --- device commands (DeviceControl) -------------------------------------------------------------------------
903
+
904
+ /** Serve device commands (when the daemon is paired and enabled for some kind) until stopped or revoked. */
905
+ startCommands() {
906
+ if (this.#commandLoop !== undefined || (this.options.commands ?? []).length === 0 || !this.paired) return
907
+ const controller = new AbortController()
908
+ const done = this.commandLoop(controller.signal).finally(() => {
909
+ this.#commandLoop = undefined
910
+ })
911
+ this.#commandLoop = { stop: () => controller.abort(), done }
912
+ }
913
+
914
+ async stopCommands() {
915
+ const loop = this.#commandLoop
916
+ loop?.stop()
917
+ await loop?.done
918
+ }
919
+
920
+ /** Stop everything that serves the kernel (the runner and the command loop). */
921
+ async stop() {
922
+ this.terminals.closeAll()
923
+ await Promise.all([this.stopRunner(), this.stopCommands(), this.client?.close()])
924
+ }
925
+
926
+ /** Open a terminal for a local client, in the workspace (or a directory in it). Only with the terminal enabled. */
927
+ openTerminal(
928
+ owner: string,
929
+ input: { readonly cwd?: string | undefined; readonly cols: number; readonly rows: number },
930
+ ) {
931
+ if (!this.commandEnabled("terminal")) {
932
+ throw new TerminalError(403, "The terminal is not enabled on this daemon (--allow-commands terminal)")
933
+ }
934
+ let cwd: string
935
+ try {
936
+ cwd = confine(this.options.workspace!, this.options.stateDir, input.cwd)
937
+ } catch (error) {
938
+ throw new TerminalError(403, (error as Error).message)
939
+ }
940
+ return this.terminals.open(owner, { cwd, cols: input.cols, rows: input.rows })
941
+ }
942
+
943
+ private async commandLoop(signal: AbortSignal) {
944
+ let backoff = 500
945
+ const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
946
+ while (!signal.aborted && this.paired) {
947
+ // Companions that stopped asking no longer count as connected.
948
+ this.companions.prune()
949
+ await this.reportCapabilities()
950
+ const kinds = this.availableKinds()
951
+ if (kinds.length === 0 || this.#commandsRunning >= MAX_COMMANDS_AT_ONCE) {
952
+ await wait(250)
953
+ continue
954
+ }
955
+ let claimed
956
+ try {
957
+ // A short poll: a companion that connects meanwhile is asked for at the next one.
958
+ const waitMs = Math.min(this.options.pollWaitMs ?? 25_000, 10_000)
959
+ claimed = await this.withKernel((kernel) => kernel.nextCommand(kinds, waitMs, signal))
960
+ backoff = 500
961
+ } catch (error) {
962
+ if (signal.aborted || error instanceof DeviceRevoked) return
963
+ this.log(`commands: could not reach the kernel (${String(error)}); retrying`)
964
+ await wait(backoff)
965
+ backoff = Math.min(backoff * 2, 10_000)
966
+ continue
967
+ }
968
+ if (claimed.command !== null) void this.serveCommand(claimed.command, signal)
969
+ }
970
+ }
971
+
972
+ /** Run one command (here, or through its companion) and report it once, before its deadline. */
973
+ private async serveCommand(command: ClaimedCommand, signal: AbortSignal) {
974
+ this.#commandsRunning += 1
975
+ try {
976
+ const kind = commandKindOf(command.operation)
977
+ /** Whether the kernel says the command should stop (cancelled, or no longer this device's). */
978
+ const stopped = () =>
979
+ this.withKernel((kernel) => kernel.checkCommand({ commandId: command.id, lease: command.lease })).then(
980
+ (answer) => answer.stop,
981
+ () => false,
982
+ )
983
+ let outcome: CommandOutcome
984
+ if (!this.commandEnabled(kind)) {
985
+ // Fails closed: a kind the daemon was not started with never runs, whatever the kernel handed out.
986
+ outcome = { outcome: "failed", result: null, error: `${kind} commands are not enabled on this device` }
987
+ } else if (await stopped()) {
988
+ // Asked once more just before acting: a command cancelled after it was taken never runs.
989
+ outcome = { outcome: "cancelled", result: null, error: "Cancelled before the device ran it; it never ran" }
990
+ } else {
991
+ // While it waits or runs, the kernel is asked again: a cancellation stops what can still be stopped.
992
+ const cancel = new AbortController()
993
+ const check = async () => {
994
+ if (await stopped()) cancel.abort()
995
+ }
996
+ const watcher = setInterval(() => void check(), COMMAND_CHECK_MS)
997
+ try {
998
+ if (isLocalKind(kind)) {
999
+ const controller = new AbortController()
1000
+ const onAbort = () => controller.abort()
1001
+ signal.addEventListener("abort", onAbort, { once: true })
1002
+ outcome = await runLocalCommand(command, {
1003
+ workspace: this.options.workspace!,
1004
+ stateDir: this.options.stateDir,
1005
+ signal: controller.signal,
1006
+ cancel: cancel.signal,
1007
+ })
1008
+ signal.removeEventListener("abort", onAbort)
1009
+ } else {
1010
+ outcome = await this.companions.run(kind, command, signal, cancel.signal)
1011
+ }
1012
+ } finally {
1013
+ clearInterval(watcher)
1014
+ }
1015
+ }
1016
+ this.log(`commands: ${command.operation} ${command.id} ${outcome.outcome}`)
1017
+ // Reported until the kernel takes it, refuses it, or its deadline (and the network's grace) has passed.
1018
+ const until = Date.parse(command.deadline) + 10_000
1019
+ let backoff = 250
1020
+ while (!signal.aborted && Date.now() < until) {
1021
+ try {
1022
+ await this.withKernel((kernel) =>
1023
+ kernel.completeCommand({ commandId: command.id, lease: command.lease, ...outcome }),
1024
+ )
1025
+ return
1026
+ } catch (error) {
1027
+ if (error instanceof KernelError || error instanceof DeviceRevoked) return
1028
+ await new Promise((resolve) => setTimeout(resolve, backoff))
1029
+ backoff = Math.min(backoff * 2, 5_000)
1030
+ }
1031
+ }
1032
+ } finally {
1033
+ this.#commandsRunning -= 1
1034
+ }
1035
+ }
1036
+
1037
+ /** Register (or with null remove) the push subscription of the host beside this daemon. */
1038
+ registerPush(subscription: PushSubscriptionInfo | null) {
1039
+ return this.withKernel((kernel) => kernel.registerPush(subscription))
1040
+ }
1041
+
1042
+ // --- sessions (DeviceControl) --------------------------------------------------------------------------------
1043
+
1044
+ sessions(): ReadonlyArray<DeviceSession> {
1045
+ // A companion's session says where it runs (a browser extension's origin) while it is connected.
1046
+ for (const companion of this.companions.companions()) {
1047
+ const session = this.#sessions.get(`client:${companion.client}`)
1048
+ if (session !== undefined && companion.origin !== null && session.detail !== companion.origin) {
1049
+ this.#sessions.set(session.id, { ...session, detail: companion.origin })
1050
+ }
1051
+ }
1052
+ const open = [...this.#sessions.values()].filter((s) => s.endedAt === null)
1053
+ const ended = [...this.#sessions.values()].filter((s) => s.endedAt !== null).slice(-20)
1054
+ return [...open, ...ended]
1055
+ }
1056
+
1057
+ /**
1058
+ * Report the sessions, one report at a time, each read when it is sent: two reports in flight at once (a client
1059
+ * paired, then its companion connected) could commit at the kernel in the other order and leave the older state
1060
+ * standing, with nothing to report again.
1061
+ */
1062
+ reportSessions(): Promise<void> {
1063
+ if (!this.paired) return Promise.resolve()
1064
+ const previous = this.#reportingSessions
1065
+ const report = (async () => {
1066
+ await previous
1067
+ try {
1068
+ await this.withKernel((kernel) => kernel.reportSessions(this.sessions()))
1069
+ } catch {
1070
+ // Best effort: the next change reports again.
1071
+ }
1072
+ })()
1073
+ this.#reportingSessions = report
1074
+ return report
1075
+ }
1076
+
1077
+ onLocalClientPaired(client: {
1078
+ clientId: string
1079
+ name: string
1080
+ kind: "shell" | "browser-extension" | "cli" | "computer-use" | "desktop-app"
1081
+ }) {
1082
+ this.#sessions.set(`client:${client.clientId}`, {
1083
+ id: `client:${client.clientId}`,
1084
+ kind: client.kind,
1085
+ label: client.name,
1086
+ startedAt: new Date().toISOString(),
1087
+ endedAt: null,
1088
+ detail: null,
1089
+ })
1090
+ void this.reportSessions()
1091
+ }
1092
+ }