@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
@@ -0,0 +1,427 @@
1
+ /**
2
+ * Device commands (DeviceControl): one operation a person, or their agent with consent, asks a paired device to
3
+ * run. The daemon serves the **terminal** (`terminal.exec`: one shell command) and the **files** of its workspace
4
+ * (`files.read`, `files.write`, `files.edit`, `files.list`, `files.search`) itself; **browser** and **computer**
5
+ * operations go to a companion, a local client that paired with the daemon as a `browser-extension` or a
6
+ * `computer-use` client and asks for work (`CompanionQueue`).
7
+ *
8
+ * Every kind is off unless the daemon was started with it (`--allow-commands`). Paths are relative to the
9
+ * workspace and never leave it (symbolic links included), nor reach the state directory. A shell command runs
10
+ * as the daemon's OS user, in the workspace, with the harnesses' environment allow-list (no credentials), in its
11
+ * own process group, killed at its deadline; its output is capped.
12
+ */
13
+ import type { ClaimedCommand, CommandKind, CommandOperation } from "@eloxiv/contracts"
14
+ import { spawn } from "node:child_process"
15
+ import {
16
+ existsSync,
17
+ lstatSync,
18
+ mkdirSync,
19
+ readdirSync,
20
+ readFileSync,
21
+ realpathSync,
22
+ statSync,
23
+ writeFileSync,
24
+ } from "node:fs"
25
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path"
26
+ import { harnessEnv } from "./Harness.ts"
27
+
28
+ /** A command's answer: what goes back to the kernel (and from there to whoever asked). */
29
+ export interface CommandOutcome {
30
+ /** `cancelled`: the device did not act (the command was cancelled before it ran). */
31
+ readonly outcome: "succeeded" | "failed" | "cancelled"
32
+ readonly result: unknown
33
+ readonly error: string | null
34
+ }
35
+
36
+ const failed = (error: string): CommandOutcome => ({ outcome: "failed", result: null, error })
37
+ const succeeded = (result: unknown): CommandOutcome => ({ outcome: "succeeded", result, error: null })
38
+
39
+ /** The most of a command's stdout and of its stderr kept (characters each). */
40
+ export const MAX_OUTPUT = 64 * 1024
41
+ /** The largest file `files.read` returns, and `files.search` looks into (bytes). */
42
+ export const MAX_FILE = 1024 * 1024
43
+ const MAX_ENTRIES = 1_000
44
+ const MAX_MATCHES = 200
45
+ const SKIPPED = new Set([".git", "node_modules"])
46
+
47
+ /** A path a command named that is not inside the workspace (or is inside the state directory). */
48
+ class OutsideWorkspace extends Error {}
49
+
50
+ /** Whether an entry exists at `path`, a dangling symbolic link included. */
51
+ const present = (path: string) => {
52
+ try {
53
+ lstatSync(path)
54
+ return true
55
+ } catch {
56
+ return false
57
+ }
58
+ }
59
+
60
+ /**
61
+ * `path` (relative to the workspace) as an absolute path inside it: its nearest existing ancestor's real path
62
+ * (symbolic links resolved) must be the workspace's or under it, and never the state directory's.
63
+ */
64
+ /** The state directory's real path (it may be inside the workspace: file commands never reach it). */
65
+ const realState = (stateDir: string) => (existsSync(stateDir) ? realpathSync(stateDir) : resolve(stateDir))
66
+
67
+ /** Whether the real path `path` is `base` or inside it. */
68
+ const inside = (path: string, base: string) => path === base || path.startsWith(`${base}${sep}`)
69
+
70
+ export const confine = (workspace: string, stateDir: string, path: string | undefined): string => {
71
+ const root = realpathSync(workspace)
72
+ const state = realState(stateDir)
73
+ if (path !== undefined && isAbsolute(path)) throw new OutsideWorkspace(`${path} is not relative to the workspace`)
74
+ const target = resolve(root, path ?? ".")
75
+ // The nearest entry that exists, a symbolic link included (`lstat`: `existsSync` is false for a dangling link,
76
+ // which a write would then follow out of the workspace). A link must resolve: a dangling one is refused.
77
+ let existing = target
78
+ while (!present(existing)) existing = dirname(existing)
79
+ let resolved: string
80
+ try {
81
+ resolved = realpathSync(existing)
82
+ } catch {
83
+ throw new OutsideWorkspace(`${path ?? "."} goes through a symbolic link that leads nowhere`)
84
+ }
85
+ const real = join(resolved, relative(existing, target))
86
+ const within = (base: string) => inside(real, base)
87
+ if (!within(root)) throw new OutsideWorkspace(`${path ?? "."} is outside the workspace`)
88
+ if (within(state)) throw new OutsideWorkspace(`${path ?? "."} is inside the daemon's state directory`)
89
+ return real
90
+ }
91
+
92
+ const clipOutput = (text: string) => (text.length > MAX_OUTPUT ? text.slice(0, MAX_OUTPUT) : text)
93
+
94
+ /** What a cancellation that stopped a running command says: it was stopped, and nothing it did is undone. */
95
+ export const INTERRUPTED =
96
+ "Cancelled while it ran: the command was stopped; whatever it did before it stopped was not undone"
97
+
98
+ /**
99
+ * `terminal.exec`: one shell command in the workspace, killed (with whatever it started) at the deadline, when the
100
+ * daemon stops (`signal`) or when it is cancelled (`cancel`): then it ends failed, interrupted, with its output so far.
101
+ */
102
+ const exec = (cwd: string, command: string, timeoutMs: number, signal: AbortSignal, cancel?: AbortSignal) =>
103
+ new Promise<CommandOutcome>((done) => {
104
+ const windows = process.platform === "win32"
105
+ const child = spawn(windows ? "cmd.exe" : "/bin/sh", windows ? ["/d", "/s", "/c", command] : ["-c", command], {
106
+ cwd,
107
+ env: harnessEnv({}),
108
+ stdio: ["ignore", "pipe", "pipe"],
109
+ detached: !windows,
110
+ })
111
+ let stdout = ""
112
+ let stderr = ""
113
+ let truncated = false
114
+ let timedOut = false
115
+ const kill = () => {
116
+ try {
117
+ if (!windows && child.pid !== undefined) process.kill(-child.pid, "SIGKILL")
118
+ else child.kill("SIGKILL")
119
+ } catch {
120
+ // Already gone.
121
+ }
122
+ }
123
+ const timer = setTimeout(() => {
124
+ timedOut = true
125
+ kill()
126
+ }, timeoutMs)
127
+ const onAbort = () => kill()
128
+ signal.addEventListener("abort", onAbort, { once: true })
129
+ cancel?.addEventListener("abort", onAbort, { once: true })
130
+ child.stdout.setEncoding("utf8").on("data", (chunk: string) => {
131
+ if (stdout.length + chunk.length > MAX_OUTPUT) truncated = true
132
+ stdout = clipOutput(stdout + chunk)
133
+ })
134
+ child.stderr.setEncoding("utf8").on("data", (chunk: string) => {
135
+ if (stderr.length + chunk.length > MAX_OUTPUT) truncated = true
136
+ stderr = clipOutput(stderr + chunk)
137
+ })
138
+ child.on("error", (error) => {
139
+ clearTimeout(timer)
140
+ done(failed(`Could not start the shell: ${error.message}`))
141
+ })
142
+ child.on("close", (code, killedBy) => {
143
+ clearTimeout(timer)
144
+ signal.removeEventListener("abort", onAbort)
145
+ cancel?.removeEventListener("abort", onAbort)
146
+ // Nothing the command started outlives it.
147
+ kill()
148
+ const result = { exitCode: code, signal: killedBy, stdout, stderr, truncated }
149
+ if (timedOut) done({ outcome: "failed", result, error: `The command exceeded its time limit (${timeoutMs} ms)` })
150
+ else if (cancel?.aborted === true && killedBy !== null) done({ outcome: "failed", result, error: INTERRUPTED })
151
+ else done(succeeded(result))
152
+ })
153
+ })
154
+
155
+ const isText = (buffer: Buffer) => !buffer.subarray(0, 8_000).includes(0)
156
+
157
+ /**
158
+ * `files.search`: files under `root` containing `text` (a literal string), with the matching lines. The daemon's
159
+ * state directory (`state`, a real path) is skipped; symbolic links are not followed, so every path is real.
160
+ */
161
+ const search = (root: string, base: string, state: string, text: string) => {
162
+ const matches: Array<{ path: string; line: number; text: string }> = []
163
+ const visit = (dir: string) => {
164
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
165
+ if (matches.length >= MAX_MATCHES) return
166
+ if (SKIPPED.has(entry.name)) continue
167
+ const path = join(dir, entry.name)
168
+ if (inside(path, state)) continue
169
+ if (entry.isDirectory()) visit(path)
170
+ else if (entry.isFile() && statSync(path).size <= MAX_FILE) {
171
+ const content = readFileSync(path)
172
+ if (!isText(content)) continue
173
+ content
174
+ .toString("utf8")
175
+ .split("\n")
176
+ .forEach((line, index) => {
177
+ if (matches.length < MAX_MATCHES && line.includes(text)) {
178
+ matches.push({ path: relative(base, path), line: index + 1, text: line.slice(0, 500) })
179
+ }
180
+ })
181
+ }
182
+ }
183
+ }
184
+ visit(root)
185
+ return { matches, truncated: matches.length >= MAX_MATCHES }
186
+ }
187
+
188
+ /**
189
+ * Run a terminal or files command in `workspace` (the kernel validated its input against the operation's schema;
190
+ * it is checked again here, defensively, by what each operation reads). Never throws.
191
+ */
192
+ export const runLocalCommand = async (
193
+ command: ClaimedCommand,
194
+ context: {
195
+ readonly workspace: string
196
+ readonly stateDir: string
197
+ readonly signal: AbortSignal
198
+ /** Aborted when the command is cancelled while it runs: a shell command is stopped. */
199
+ readonly cancel?: AbortSignal | undefined
200
+ },
201
+ ): Promise<CommandOutcome> => {
202
+ const input = (command.input ?? {}) as Record<string, unknown>
203
+ const text = (name: string) => (typeof input[name] === "string" ? input[name] : undefined)
204
+ const path = (name = "path") => confine(context.workspace, context.stateDir, text(name))
205
+ const shown = (absolute: string) => relative(realpathSync(context.workspace), absolute) || "."
206
+ try {
207
+ switch (command.operation) {
208
+ case "terminal.exec": {
209
+ const line = text("command")
210
+ if (line === undefined || line.length === 0) return failed("terminal.exec needs a command")
211
+ return await exec(path("cwd"), line, command.timeoutMs, context.signal, context.cancel)
212
+ }
213
+ case "files.read": {
214
+ const file = path()
215
+ const size = statSync(file).size
216
+ if (size > MAX_FILE) return failed(`${shown(file)} is larger than ${MAX_FILE} bytes`)
217
+ const content = readFileSync(file)
218
+ if (!isText(content)) return failed(`${shown(file)} is not a text file`)
219
+ return succeeded({ path: shown(file), content: content.toString("utf8"), bytes: size })
220
+ }
221
+ case "files.write": {
222
+ const file = path()
223
+ const content = text("content")
224
+ if (content === undefined) return failed("files.write needs content")
225
+ mkdirSync(dirname(file), { recursive: true })
226
+ writeFileSync(file, content)
227
+ return succeeded({ path: shown(file), bytes: Buffer.byteLength(content) })
228
+ }
229
+ case "files.edit": {
230
+ const file = path()
231
+ const oldText = text("oldText")
232
+ const newText = text("newText")
233
+ if (oldText === undefined || oldText.length === 0 || newText === undefined) {
234
+ return failed("files.edit needs oldText and newText")
235
+ }
236
+ const content = readFileSync(file, "utf8")
237
+ const count = content.split(oldText).length - 1
238
+ if (count !== 1) return failed(`oldText occurs ${count} times in ${shown(file)}; it must occur exactly once`)
239
+ writeFileSync(
240
+ file,
241
+ content.replace(oldText, () => newText),
242
+ )
243
+ return succeeded({ path: shown(file), replaced: 1 })
244
+ }
245
+ case "files.list": {
246
+ const dir = path()
247
+ const state = realState(context.stateDir)
248
+ // The state directory is not listed (nor can it be read, written or listed: `confine`).
249
+ const entries = readdirSync(dir, { withFileTypes: true })
250
+ .filter((entry) => !inside(join(dir, entry.name), state))
251
+ .slice(0, MAX_ENTRIES)
252
+ .map((entry) => {
253
+ const kind = entry.isDirectory() ? "directory" : entry.isFile() ? "file" : "other"
254
+ return { name: entry.name, kind, size: kind === "file" ? statSync(join(dir, entry.name)).size : null }
255
+ })
256
+ return succeeded({ path: shown(dir), entries, truncated: entries.length >= MAX_ENTRIES })
257
+ }
258
+ case "files.search": {
259
+ const needle = text("text")
260
+ if (needle === undefined || needle.length === 0) return failed("files.search needs text")
261
+ return succeeded(search(path(), realpathSync(context.workspace), realState(context.stateDir), needle))
262
+ }
263
+ default:
264
+ return failed(`${command.operation} is not served by the daemon itself`)
265
+ }
266
+ } catch (error) {
267
+ if (error instanceof OutsideWorkspace) return failed(error.message)
268
+ const code = (error as NodeJS.ErrnoException).code
269
+ return failed(code === "ENOENT" ? "No such file or directory" : ((error as Error).message ?? String(error)))
270
+ }
271
+ }
272
+
273
+ /** The local client kind that serves each companion command kind. */
274
+ export const COMPANION_KIND = { browser: "browser-extension", computer: "computer-use" } as const
275
+ export type CompanionCommandKind = keyof typeof COMPANION_KIND
276
+
277
+ /** How long after its last request a companion still counts as connected (ms). */
278
+ export const COMPANION_PRESENCE_MS = 35_000
279
+
280
+ interface Handed {
281
+ readonly command: ClaimedCommand
282
+ readonly client: string
283
+ readonly settle: (outcome: CommandOutcome) => void
284
+ }
285
+
286
+ /**
287
+ * Browser and computer commands, waiting for their companion: a companion asks for work (`next`, a long poll),
288
+ * gets the oldest command of its kind, and reports it (`settle`); only the companion that took a command may
289
+ * report it. A command no companion took or reported before its deadline fails.
290
+ */
291
+ export class CompanionQueue {
292
+ readonly #waiting = new Map<CompanionCommandKind, Array<Handed & { readonly kind: CompanionCommandKind }>>()
293
+ readonly #handed = new Map<string, Handed>()
294
+ readonly #wakers = new Map<CompanionCommandKind, Set<() => void>>()
295
+ /** The last request of each companion, by client id, and its kind and origin. */
296
+ readonly #seen = new Map<string, { kind: CompanionCommandKind; at: number; origin: string | null; name: string }>()
297
+ readonly #onChange: () => void
298
+
299
+ constructor(onChange: () => void) {
300
+ this.#onChange = onChange
301
+ }
302
+
303
+ /** Is a companion of `kind` connected (it asked for work recently)? */
304
+ connected(kind: CompanionCommandKind, now = Date.now()): boolean {
305
+ return [...this.#seen.values()].some((seen) => seen.kind === kind && now - seen.at < COMPANION_PRESENCE_MS)
306
+ }
307
+
308
+ /** The companions connected now, for the device's sessions. */
309
+ companions(now = Date.now()) {
310
+ return [...this.#seen.entries()]
311
+ .filter(([, seen]) => now - seen.at < COMPANION_PRESENCE_MS)
312
+ .map(([client, seen]) => Object.assign({ client }, seen))
313
+ }
314
+
315
+ /**
316
+ * Hand `command` to a companion of `kind`, and wait for its report (or the deadline). Cancelled (`cancel`) before a
317
+ * companion took it: it is withdrawn and never runs. Once taken it runs to its end: the companion's report stands.
318
+ */
319
+ run(
320
+ kind: CompanionCommandKind,
321
+ command: ClaimedCommand,
322
+ signal: AbortSignal,
323
+ cancel?: AbortSignal,
324
+ ): Promise<CommandOutcome> {
325
+ return new Promise((done) => {
326
+ let finished = false
327
+ const settle = (outcome: CommandOutcome) => {
328
+ if (finished) return
329
+ finished = true
330
+ clearTimeout(timer)
331
+ signal.removeEventListener("abort", onAbort)
332
+ cancel?.removeEventListener("abort", onCancel)
333
+ this.#handed.delete(command.id)
334
+ const queue = this.#waiting.get(kind) ?? []
335
+ this.#waiting.set(
336
+ kind,
337
+ queue.filter((entry) => entry.command.id !== command.id),
338
+ )
339
+ done(outcome)
340
+ }
341
+ const timer = setTimeout(
342
+ () => settle(failed(`No ${COMPANION_KIND[kind]} companion completed the command in time`)),
343
+ Math.max(0, Date.parse(command.deadline) - Date.now()),
344
+ )
345
+ const onAbort = () => settle(failed("The daemon stopped"))
346
+ signal.addEventListener("abort", onAbort, { once: true })
347
+ // Withdrawn only while no companion has it.
348
+ const onCancel = () => {
349
+ if (!this.#handed.has(command.id)) {
350
+ settle({ outcome: "cancelled", result: null, error: "Cancelled before a companion took it; it never ran" })
351
+ }
352
+ }
353
+ cancel?.addEventListener("abort", onCancel, { once: true })
354
+ const queue = this.#waiting.get(kind) ?? []
355
+ queue.push({ kind, command, client: "", settle })
356
+ this.#waiting.set(kind, queue)
357
+ for (const wake of this.#wakers.get(kind) ?? []) wake()
358
+ })
359
+ }
360
+
361
+ /** A companion asks for work: the oldest command of its kind, waiting up to `waitMs` for one. */
362
+ async next(
363
+ client: { readonly id: string; readonly name: string },
364
+ kind: CompanionCommandKind,
365
+ waitMs: number,
366
+ origin: string | null,
367
+ ): Promise<ClaimedCommand | null> {
368
+ const fresh = !this.connected(kind)
369
+ this.#seen.set(client.id, { kind, at: Date.now(), origin, name: client.name })
370
+ if (fresh) this.#onChange()
371
+ const take = () => {
372
+ const queue = this.#waiting.get(kind) ?? []
373
+ const entry = queue.shift()
374
+ if (entry === undefined) return null
375
+ this.#handed.set(entry.command.id, { ...entry, client: client.id })
376
+ return entry.command
377
+ }
378
+ const now = take()
379
+ if (now !== null || waitMs <= 0) return now
380
+ return new Promise((done) => {
381
+ const wakers = this.#wakers.get(kind) ?? new Set()
382
+ this.#wakers.set(kind, wakers)
383
+ const finish = (value: ClaimedCommand | null) => {
384
+ clearTimeout(timer)
385
+ wakers.delete(wake)
386
+ // Still connected while it waits.
387
+ const seen = this.#seen.get(client.id)
388
+ if (seen !== undefined) seen.at = Date.now()
389
+ done(value)
390
+ }
391
+ const wake = () => {
392
+ const command = take()
393
+ if (command !== null) finish(command)
394
+ }
395
+ const timer = setTimeout(() => finish(null), waitMs)
396
+ wakers.add(wake)
397
+ })
398
+ }
399
+
400
+ /** A companion reports a command it took. False when it holds no such command. */
401
+ settle(clientId: string, commandId: string, outcome: CommandOutcome): boolean {
402
+ const handed = this.#handed.get(commandId)
403
+ if (handed === undefined || handed.client !== clientId) return false
404
+ handed.settle(outcome)
405
+ return true
406
+ }
407
+
408
+ /** Forget companions that stopped asking (called when sessions are reported). */
409
+ prune(now = Date.now()) {
410
+ let changed = false
411
+ for (const [client, seen] of this.#seen) {
412
+ if (now - seen.at >= COMPANION_PRESENCE_MS) {
413
+ this.#seen.delete(client)
414
+ changed = true
415
+ }
416
+ }
417
+ if (changed) this.#onChange()
418
+ }
419
+ }
420
+
421
+ /** The kind a local client serves as a companion, if any. */
422
+ export const companionKindOf = (clientKind: string): CompanionCommandKind | undefined =>
423
+ clientKind === "browser-extension" ? "browser" : clientKind === "computer-use" ? "computer" : undefined
424
+
425
+ export const isLocalKind = (kind: CommandKind): kind is "terminal" | "files" => kind === "terminal" || kind === "files"
426
+
427
+ export type { CommandOperation }
package/src/Config.ts ADDED
@@ -0,0 +1,179 @@
1
+ /**
2
+ * Daemon start-up options from argv and the environment.
3
+ *
4
+ * eloxiv-daemon [serve] [--port <n>] [--stdin-lifeline] [--headless] [--kernel <url>] [--name <name>]
5
+ * [--state-dir <dir>] [--secret-store auto|file|libsecret|keychain|wincred] [--workspace <dir>]
6
+ * [--allow-commands terminal,files,browser,computer] [--tools-only]
7
+ * eloxiv-daemon pair --kernel <url> [--name <name>] [--runner] [--state-dir <dir>] [--secret-store <kind>]
8
+ * eloxiv-daemon status [--state-dir <dir>]
9
+ * eloxiv-daemon unpair [--state-dir <dir>]
10
+ * eloxiv-daemon approve-client [<pairing id>] [--state-dir <dir>]
11
+ * eloxiv-daemon pairing-code [--state-dir <dir>]
12
+ *
13
+ * `serve` (the default, and what the Tauri host runs) serves the loopback surface. `--headless` also runs the
14
+ * runner: it serves turns addressed to this device (pairing first with `--kernel` when it is not paired).
15
+ * `--allow-commands` (or `ELOXIV_DAEMON_COMMANDS`) lets the device serve those kinds of device commands (none by
16
+ * default; terminal and files need `--workspace`); `--tools-only` (or `ELOXIV_DAEMON_TOOLS_ONLY=1`) is the hosted
17
+ * profile: turns get only the Eloxiv tools, and the terminal and files cannot be enabled.
18
+ */
19
+ import type { CommandKind } from "@eloxiv/contracts"
20
+ import type { SecretStoreKind } from "./Secrets.ts"
21
+ import { defaultStateDir } from "./State.ts"
22
+
23
+ /**
24
+ * 4191, not 4190: 4190 (ManageSieve) is on the WHATWG Fetch "bad ports" list,
25
+ * so browsers, webviews and Node's fetch refuse to connect to it.
26
+ */
27
+ export const DEFAULT_PORT = 4191
28
+ /** The daemon only listens on loopback. */
29
+ export const HOSTNAME = "127.0.0.1"
30
+
31
+ export type DaemonCommand = "serve" | "pair" | "status" | "unpair" | "approve-client" | "pairing-code"
32
+
33
+ export interface DaemonConfig {
34
+ readonly command: DaemonCommand
35
+ readonly port: number
36
+ /** Exit when stdin closes: lets a host that dies without cleaning up take its sidecar with it. */
37
+ readonly stdinLifeline: boolean
38
+ /** Run the headless runner beside the loopback surface. */
39
+ readonly headless: boolean
40
+ /** Browser origins allowed to use the daemon, from `ELOXIV_TRUSTED_ORIGINS` (comma separated) when set. */
41
+ readonly trustedOrigins: ReadonlyArray<string> | undefined
42
+ readonly stateDir: string
43
+ readonly secretStore: SecretStoreKind
44
+ readonly kernelUrl: string | undefined
45
+ readonly name: string | undefined
46
+ /** `pair --runner`: pair as a runner rather than a desktop daemon. */
47
+ readonly runner: boolean
48
+ /** The working directory turns run in when they name none (default: the state directory's `workspace`). */
49
+ readonly workspace: string | undefined
50
+ /** The host's per-launch secret (`ELOXIV_DAEMON_HOST_SECRET`), if a host started the daemon. */
51
+ readonly hostSecret: string | undefined
52
+ /** `approve-client <pairing id>`: the pairing to approve (none: list the pending ones). */
53
+ readonly pairingId: string | undefined
54
+ /** The device command kinds this daemon serves (`--allow-commands`; none by default). */
55
+ readonly commands: ReadonlyArray<CommandKind>
56
+ /** The tools-only profile: no workspace tools, no terminal or files (`--tools-only`). */
57
+ readonly toolsOnly: boolean
58
+ }
59
+
60
+ const COMMAND_KINDS: ReadonlySet<string> = new Set(["terminal", "files", "browser", "computer"])
61
+
62
+ /** `terminal,files,...`: the command kinds a daemon serves; an unknown one is a configuration error. */
63
+ export const parseCommandKinds = (raw: string | undefined): ReadonlyArray<CommandKind> => {
64
+ const kinds = (raw ?? "")
65
+ .split(",")
66
+ .map((kind) => kind.trim())
67
+ .filter((kind) => kind.length > 0)
68
+ for (const kind of kinds) if (!COMMAND_KINDS.has(kind)) throw new DaemonConfigError(`Unknown command kind ${kind}`)
69
+ return [...new Set(kinds)] as ReadonlyArray<CommandKind>
70
+ }
71
+
72
+ /**
73
+ * The host's secret from `ELOXIV_DAEMON_HOST_SECRET` (at least 32 characters), removed from `env` once read so
74
+ * nothing the daemon starts inherits it. (The operating system may still show a process's initial environment
75
+ * to the same user, as it shows its files.)
76
+ */
77
+ export const readHostSecret = (env: Record<string, string | undefined>): string | undefined => {
78
+ const secret = env["ELOXIV_DAEMON_HOST_SECRET"]
79
+ delete env["ELOXIV_DAEMON_HOST_SECRET"]
80
+ return secret === undefined || secret.length < 32 ? undefined : secret
81
+ }
82
+
83
+ export class DaemonConfigError extends Error {
84
+ override readonly name = "DaemonConfigError"
85
+ }
86
+
87
+ const parsePort = (raw: string, source: string): number => {
88
+ const port = Number(raw)
89
+ if (!/^\d+$/.test(raw.trim()) || !Number.isInteger(port) || port < 0 || port > 65535) {
90
+ throw new DaemonConfigError(`Invalid port from ${source}: ${JSON.stringify(raw)}`)
91
+ }
92
+ return port
93
+ }
94
+
95
+ const STORES: ReadonlySet<string> = new Set(["auto", "file", "libsecret", "keychain", "wincred"])
96
+ const COMMANDS: ReadonlySet<string> = new Set(["serve", "pair", "status", "unpair", "approve-client", "pairing-code"])
97
+ const FLAGS: ReadonlySet<string> = new Set(["--stdin-lifeline", "--headless", "--runner", "--tools-only"])
98
+
99
+ /**
100
+ * Resolve the config: `--port <n>` or `--port=<n>` wins over `ELOXIV_DAEMON_PORT`, which wins over 4191. Port 0
101
+ * picks a free port; the ready line reports it. `--stdin-lifeline` (or `ELOXIV_DAEMON_STDIN_LIFELINE=1`) turns
102
+ * on the lifeline. Every `--flag value` also accepts `--flag=value`.
103
+ */
104
+ export const resolveConfig = (
105
+ argv: ReadonlyArray<string>,
106
+ env: Readonly<Record<string, string | undefined>>,
107
+ ): DaemonConfig => {
108
+ const args = [...argv]
109
+ let command: DaemonCommand = "serve"
110
+ if (args[0] !== undefined && !args[0].startsWith("-")) {
111
+ const first = args.shift()!
112
+ if (!COMMANDS.has(first)) throw new DaemonConfigError(`Unknown command ${first}`)
113
+ command = first as DaemonCommand
114
+ }
115
+ // `approve-client <pairing id>`: the id is the command's operand.
116
+ const pairingId =
117
+ command === "approve-client" && args[0] !== undefined && !args[0].startsWith("-") ? args.shift() : undefined
118
+ const values = new Map<string, string>()
119
+ const flags = new Set<string>()
120
+ const valued = new Set([
121
+ "--port",
122
+ "--state-dir",
123
+ "--secret-store",
124
+ "--kernel",
125
+ "--name",
126
+ "--workspace",
127
+ "--allow-commands",
128
+ ])
129
+ for (let i = 0; i < args.length; i++) {
130
+ const arg = args[i]!
131
+ const eq = arg.indexOf("=")
132
+ const name = eq > 0 ? arg.slice(0, eq) : arg
133
+ if (valued.has(name)) {
134
+ const value = eq > 0 ? arg.slice(eq + 1) : args[++i]
135
+ if (value === undefined) throw new DaemonConfigError(`${name} needs a value`)
136
+ values.set(name, value)
137
+ } else if (FLAGS.has(arg)) {
138
+ flags.add(arg)
139
+ } else {
140
+ throw new DaemonConfigError(`Unknown option ${arg}`)
141
+ }
142
+ }
143
+ let port = values.has("--port") ? parsePort(values.get("--port")!, "--port") : undefined
144
+ const fromEnv = env["ELOXIV_DAEMON_PORT"]
145
+ if (port === undefined && fromEnv !== undefined && fromEnv !== "") port = parsePort(fromEnv, "ELOXIV_DAEMON_PORT")
146
+ const origins = env["ELOXIV_TRUSTED_ORIGINS"]
147
+ const trustedOrigins =
148
+ origins === undefined || origins.trim() === ""
149
+ ? undefined
150
+ : origins
151
+ .split(",")
152
+ .map((origin) => origin.trim())
153
+ .filter((origin) => origin !== "")
154
+ const secretStore = (values.get("--secret-store") ?? env["ELOXIV_DAEMON_SECRET_STORE"] ?? "auto") as SecretStoreKind
155
+ if (!STORES.has(secretStore)) throw new DaemonConfigError(`Unknown secret store ${secretStore}`)
156
+ const kernelUrl = values.get("--kernel") ?? env["ELOXIV_DAEMON_KERNEL_URL"]
157
+ if (command === "pair" && kernelUrl === undefined) throw new DaemonConfigError("pair needs --kernel <url>")
158
+ const hostSecret = env["ELOXIV_DAEMON_HOST_SECRET"]
159
+ return {
160
+ pairingId,
161
+ command,
162
+ port: port ?? DEFAULT_PORT,
163
+ stdinLifeline: flags.has("--stdin-lifeline") || env["ELOXIV_DAEMON_STDIN_LIFELINE"] === "1",
164
+ headless: flags.has("--headless"),
165
+ trustedOrigins,
166
+ stateDir: values.get("--state-dir") ?? env["ELOXIV_DAEMON_STATE_DIR"] ?? defaultStateDir(env),
167
+ secretStore,
168
+ kernelUrl,
169
+ name: values.get("--name"),
170
+ runner: flags.has("--runner"),
171
+ workspace: values.get("--workspace") ?? env["ELOXIV_DAEMON_WORKSPACE"],
172
+ hostSecret: hostSecret === undefined || hostSecret.length < 32 ? undefined : hostSecret,
173
+ commands: parseCommandKinds(values.get("--allow-commands") ?? env["ELOXIV_DAEMON_COMMANDS"]),
174
+ toolsOnly: flags.has("--tools-only") || env["ELOXIV_DAEMON_TOOLS_ONLY"] === "1",
175
+ }
176
+ }
177
+
178
+ /** The one line a host waits for on stdout. */
179
+ export const readyLine = (port: number) => `ELOXIV_DAEMON_READY port=${port}`