@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/Secrets.ts ADDED
@@ -0,0 +1,226 @@
1
+ /**
2
+ * Custody of the device credential: a small secret store over the operating system's secure storage, with a
3
+ * file fallback.
4
+ *
5
+ * - `libsecret` (Linux: GNOME Keyring, KWallet through the Secret Service) via `secret-tool`;
6
+ * - `keychain` (macOS) via `security`;
7
+ * - `wincred` (Windows Credential Manager) via PowerShell and `CredRead`/`CredWrite`;
8
+ * - `file`: `<state dir>/secrets.json`, mode 0600 in a 0700 directory, written atomically. Anyone who can read
9
+ * the user's files can read it; use it only where no secure storage exists (headless servers, CI).
10
+ *
11
+ * `auto` picks the platform's store when its tool works (probed with a throwaway secret) and falls back to the
12
+ * file store, saying so in the status. Secrets never go in argv where the tool allows otherwise (`secret-tool`
13
+ * reads stdin; `security` and PowerShell get the value through stdin or the environment).
14
+ */
15
+ import { execFile, spawn } from "node:child_process"
16
+ import { createHash } from "node:crypto"
17
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"
18
+ import { join } from "node:path"
19
+
20
+ export type SecretStoreKind = "auto" | "file" | "libsecret" | "keychain" | "wincred"
21
+
22
+ export interface SecretStore {
23
+ /** The store in use (never `auto`). */
24
+ readonly kind: Exclude<SecretStoreKind, "auto">
25
+ readonly get: (key: string) => Promise<string | undefined>
26
+ readonly set: (key: string, value: string) => Promise<void>
27
+ readonly delete: (key: string) => Promise<void>
28
+ }
29
+
30
+ const SERVICE = "eloxiv-daemon"
31
+
32
+ const run = (command: string, args: ReadonlyArray<string>, options: { input?: string; env?: NodeJS.ProcessEnv } = {}) =>
33
+ new Promise<{ code: number; stdout: string; stderr: string }>((resolve) => {
34
+ const child = spawn(command, [...args], { stdio: ["pipe", "pipe", "pipe"], env: options.env ?? process.env })
35
+ let stdout = ""
36
+ let stderr = ""
37
+ const timer = setTimeout(() => child.kill("SIGKILL"), 15_000)
38
+ child.stdout.setEncoding("utf8").on("data", (chunk: string) => (stdout += chunk))
39
+ child.stderr.setEncoding("utf8").on("data", (chunk: string) => (stderr += chunk))
40
+ child.on("error", (error) => {
41
+ clearTimeout(timer)
42
+ resolve({ code: -1, stdout, stderr: String(error) })
43
+ })
44
+ child.on("close", (code) => {
45
+ clearTimeout(timer)
46
+ resolve({ code: code ?? -1, stdout, stderr })
47
+ })
48
+ child.stdin.end(options.input ?? "")
49
+ })
50
+
51
+ const onPath = (command: string) =>
52
+ new Promise<boolean>((resolve) => {
53
+ execFile(process.platform === "win32" ? "where" : "which", [command], (error) => resolve(error === null))
54
+ })
55
+
56
+ /** The file store: `<dir>/secrets.json`, 0600, written by rename so a crash never leaves half a file. */
57
+ export const fileSecretStore = (dir: string): SecretStore => {
58
+ const path = join(dir, "secrets.json")
59
+ const read = (): Record<string, string> => {
60
+ if (!existsSync(path)) return {}
61
+ return JSON.parse(readFileSync(path, "utf8")) as Record<string, string>
62
+ }
63
+ const write = (secrets: Record<string, string>) => {
64
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
65
+ const temporary = `${path}.${process.pid}.tmp`
66
+ writeFileSync(temporary, `${JSON.stringify(secrets)}\n`, { mode: 0o600 })
67
+ chmodSync(temporary, 0o600)
68
+ renameSync(temporary, path)
69
+ }
70
+ return {
71
+ kind: "file",
72
+ get: async (key) => read()[key],
73
+ set: async (key, value) => write({ ...read(), [key]: value }),
74
+ delete: async (key) => {
75
+ const secrets = read()
76
+ if (!(key in secrets)) return
77
+ delete secrets[key]
78
+ write(secrets)
79
+ },
80
+ }
81
+ }
82
+
83
+ export const libsecretStore = (): SecretStore => ({
84
+ kind: "libsecret",
85
+ get: async (key) => {
86
+ const result = await run("secret-tool", ["lookup", "service", SERVICE, "account", key])
87
+ return result.code === 0 && result.stdout.length > 0 ? result.stdout : undefined
88
+ },
89
+ set: async (key, value) => {
90
+ const result = await run(
91
+ "secret-tool",
92
+ ["store", `--label=Eloxiv daemon (${key})`, "service", SERVICE, "account", key],
93
+ {
94
+ input: value,
95
+ },
96
+ )
97
+ if (result.code !== 0) throw new Error(`secret-tool store failed: ${result.stderr.trim()}`)
98
+ },
99
+ delete: async (key) => {
100
+ await run("secret-tool", ["clear", "service", SERVICE, "account", key])
101
+ },
102
+ })
103
+
104
+ export const keychainStore = (): SecretStore => ({
105
+ kind: "keychain",
106
+ get: async (key) => {
107
+ const result = await run("security", ["find-generic-password", "-s", SERVICE, "-a", key, "-w"])
108
+ return result.code === 0 ? result.stdout.replace(/\n$/u, "") : undefined
109
+ },
110
+ set: async (key, value) => {
111
+ // `-w` as the last option with no value makes `security` read the password from stdin (twice: entry and
112
+ // confirmation), so it never appears in the process list.
113
+ const result = await run("security", ["add-generic-password", "-U", "-s", SERVICE, "-a", key, "-w"], {
114
+ input: `${value}\n${value}\n`,
115
+ })
116
+ if (result.code !== 0) throw new Error(`security add-generic-password failed: ${result.stderr.trim()}`)
117
+ },
118
+ delete: async (key) => {
119
+ await run("security", ["delete-generic-password", "-s", SERVICE, "-a", key])
120
+ },
121
+ })
122
+
123
+ /** CredRead/CredWrite/CredDelete through PowerShell; the value travels in an environment variable. */
124
+ const WINCRED_SCRIPT = `
125
+ $ErrorActionPreference = 'Stop'
126
+ Add-Type -TypeDefinition @"
127
+ using System; using System.Runtime.InteropServices; using System.Text;
128
+ public static class EloxivCred {
129
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
130
+ public struct CREDENTIAL { public int Flags; public int Type; public string TargetName; public string Comment;
131
+ public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten; public int CredentialBlobSize;
132
+ public IntPtr CredentialBlob; public int Persist; public int AttributeCount; public IntPtr Attributes;
133
+ public string TargetAlias; public string UserName; }
134
+ [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
135
+ public static extern bool CredRead(string target, int type, int flags, out IntPtr cred);
136
+ [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
137
+ public static extern bool CredWrite(ref CREDENTIAL cred, int flags);
138
+ [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
139
+ public static extern bool CredDelete(string target, int type, int flags);
140
+ [DllImport("advapi32.dll")] public static extern void CredFree(IntPtr cred);
141
+ public static string Read(string target) {
142
+ IntPtr p; if (!CredRead(target, 1, 0, out p)) return null;
143
+ var c = (CREDENTIAL)Marshal.PtrToStructure(p, typeof(CREDENTIAL));
144
+ var s = Marshal.PtrToStringUni(c.CredentialBlob, c.CredentialBlobSize / 2); CredFree(p); return s; }
145
+ public static void Write(string target, string value) {
146
+ var bytes = Encoding.Unicode.GetBytes(value); var c = new CREDENTIAL(); c.Type = 1; c.TargetName = target;
147
+ c.CredentialBlobSize = bytes.Length; c.CredentialBlob = Marshal.AllocHGlobal(bytes.Length);
148
+ Marshal.Copy(bytes, 0, c.CredentialBlob, bytes.Length); c.Persist = 2; c.UserName = "eloxiv";
149
+ try { if (!CredWrite(ref c, 0)) throw new Exception("CredWrite " + Marshal.GetLastWin32Error()); }
150
+ finally { Marshal.FreeHGlobal(c.CredentialBlob); } }
151
+ }
152
+ "@
153
+ switch ($env:ELOXIV_CRED_OP) {
154
+ 'get' { $v = [EloxivCred]::Read($env:ELOXIV_CRED_TARGET); if ($v -ne $null) { [Console]::Out.Write($v) } else { exit 2 } }
155
+ 'set' { [EloxivCred]::Write($env:ELOXIV_CRED_TARGET, $env:ELOXIV_CRED_VALUE) }
156
+ 'delete' { [void][EloxivCred]::CredDelete($env:ELOXIV_CRED_TARGET, 1, 0) }
157
+ }
158
+ `
159
+
160
+ export const wincredStore = (): SecretStore => {
161
+ const call = (op: string, key: string, value = "") =>
162
+ run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", "-"], {
163
+ input: WINCRED_SCRIPT,
164
+ env: { ...process.env, ELOXIV_CRED_OP: op, ELOXIV_CRED_TARGET: `${SERVICE}:${key}`, ELOXIV_CRED_VALUE: value },
165
+ })
166
+ return {
167
+ kind: "wincred",
168
+ get: async (key) => {
169
+ const result = await call("get", key)
170
+ return result.code === 0 ? result.stdout : undefined
171
+ },
172
+ set: async (key, value) => {
173
+ const result = await call("set", key, value)
174
+ if (result.code !== 0) throw new Error(`CredWrite failed: ${result.stderr.trim()}`)
175
+ },
176
+ delete: async (key) => {
177
+ await call("delete", key)
178
+ },
179
+ }
180
+ }
181
+
182
+ /** Does `store` work here? Store, read back and delete a throwaway secret. */
183
+ const works = async (store: SecretStore) => {
184
+ const key = `probe-${process.pid}-${Date.now()}`
185
+ try {
186
+ await store.set(key, "probe")
187
+ const value = await store.get(key)
188
+ await store.delete(key)
189
+ return value === "probe"
190
+ } catch {
191
+ return false
192
+ }
193
+ }
194
+
195
+ /**
196
+ * The store for `kind`. `auto` tries the platform's secure storage and falls back to the file store; an
197
+ * explicit kind is used as asked (and fails loudly if it does not work).
198
+ */
199
+ export const selectSecretStore = async (kind: SecretStoreKind, stateDir: string): Promise<SecretStore> => {
200
+ switch (kind) {
201
+ case "file":
202
+ return fileSecretStore(stateDir)
203
+ case "libsecret":
204
+ return libsecretStore()
205
+ case "keychain":
206
+ return keychainStore()
207
+ case "wincred":
208
+ return wincredStore()
209
+ case "auto": {
210
+ const candidate =
211
+ process.platform === "linux" && process.env["DBUS_SESSION_BUS_ADDRESS"] && (await onPath("secret-tool"))
212
+ ? libsecretStore()
213
+ : process.platform === "darwin" && (await onPath("security"))
214
+ ? keychainStore()
215
+ : process.platform === "win32"
216
+ ? wincredStore()
217
+ : undefined
218
+ if (candidate !== undefined && (await works(candidate))) return candidate
219
+ return fileSecretStore(stateDir)
220
+ }
221
+ }
222
+ }
223
+
224
+ /** The key the device credential is stored under: one per state directory, so daemons on one machine never share. */
225
+ export const credentialKey = (stateDir: string) =>
226
+ `device-credential-${createHash("sha256").update(stateDir).digest("hex").slice(0, 16)}`
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The transport rule for every URL the daemon sends a credential to (the kernel it pairs with, LocalClient's
3
+ * kernel and zero-cache): https, or http only on loopback. Anything else would put the credential on the wire in
4
+ * clear.
5
+ */
6
+ export class InsecureUrl extends Error {
7
+ override readonly name = "InsecureUrl"
8
+ }
9
+
10
+ /** `raw` without a trailing slash when it is https or loopback http; otherwise `InsecureUrl`. */
11
+ export const secureUrl = (raw: string, what = "The kernel"): string => {
12
+ let url: URL
13
+ try {
14
+ url = new URL(raw)
15
+ } catch {
16
+ throw new InsecureUrl(`Not a URL: ${raw}`)
17
+ }
18
+ const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)
19
+ if (url.protocol === "https:" || (url.protocol === "http:" && loopback)) return url.toString().replace(/\/+$/u, "")
20
+ throw new InsecureUrl(`${what} must be https (or http on loopback): ${raw}`)
21
+ }
package/src/State.ts ADDED
@@ -0,0 +1,109 @@
1
+ /**
2
+ * The daemon's persistent state: `<state dir>/state.json` (0600 in a 0700 directory, written atomically).
3
+ * It holds the kernel pairing (never the credential, which is in the secret store), the local clients paired
4
+ * with the daemon (their tokens only as SHA-256 hashes) and the turn a runner is working on.
5
+ */
6
+ import type { HarnessKind } from "@eloxiv/contracts"
7
+ import { createHash } from "node:crypto"
8
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"
9
+ import { homedir } from "node:os"
10
+ import { join } from "node:path"
11
+
12
+ export interface KernelPairing {
13
+ readonly url: string
14
+ readonly deviceId: string
15
+ readonly orgId: string
16
+ readonly subject: string
17
+ readonly name: string
18
+ readonly kind: "desktop" | "runner"
19
+ readonly pairedAt: string
20
+ /** Set when the kernel refused the credential (the device was revoked, or its person left). */
21
+ readonly revokedAt?: string | undefined
22
+ }
23
+
24
+ export interface LocalClient {
25
+ readonly id: string
26
+ readonly name: string
27
+ readonly kind: "shell" | "browser-extension" | "cli" | "computer-use" | "desktop-app"
28
+ readonly tokenHash: string
29
+ readonly pairedAt: string
30
+ }
31
+
32
+ export interface DaemonState {
33
+ readonly version: 1
34
+ readonly kernel?: KernelPairing | undefined
35
+ readonly localClients: ReadonlyArray<LocalClient>
36
+ /** The turn a runner claimed and has not settled (diagnostics; the kernel's lease is authoritative). */
37
+ readonly inflight?: { readonly turnId: string; readonly attempt: number; readonly since: string } | undefined
38
+ /** A finished turn's outcome the kernel has not taken yet: reported before anything else, also after a restart. */
39
+ readonly pendingCompletion?: PendingCompletion | undefined
40
+ /** The harness sessions resumable turns kept: the only ones a follow-up may resume (newest last). */
41
+ readonly harnessSessions?: ReadonlyArray<HarnessSessionRecord> | undefined
42
+ }
43
+
44
+ /** A harness session a resumable turn kept, and the working directory it belongs to. */
45
+ export interface HarnessSessionRecord {
46
+ /** The harness's own session (Claude Code) or thread (Codex) id. */
47
+ readonly id: string
48
+ readonly harness: HarnessKind
49
+ readonly cwd: string
50
+ /** The daemon created `cwd` for the session (removed when the session is forgotten). */
51
+ readonly owned: boolean
52
+ readonly turnId: string
53
+ readonly lastUsedAt: string
54
+ }
55
+
56
+ export interface PendingCompletion {
57
+ readonly turnId: string
58
+ readonly lease: string
59
+ readonly outcome: "succeeded" | "failed"
60
+ readonly result: string | null
61
+ readonly usage: {
62
+ readonly inputTokens: number
63
+ readonly outputTokens: number
64
+ readonly cachedInputTokens: number | null
65
+ readonly costUsd: number | null
66
+ } | null
67
+ readonly error: string | null
68
+ readonly sessionId?: string | null
69
+ }
70
+
71
+ export const emptyState: DaemonState = { version: 1, localClients: [] }
72
+
73
+ export const sha256Hex = (value: string) => createHash("sha256").update(value, "utf8").digest("hex")
74
+
75
+ /** The default state directory: per user, per platform. */
76
+ export const defaultStateDir = (env: Readonly<Record<string, string | undefined>> = process.env) => {
77
+ if (process.platform === "win32")
78
+ return join(env["APPDATA"] ?? join(homedir(), "AppData", "Roaming"), "Eloxiv", "daemon")
79
+ if (process.platform === "darwin") return join(homedir(), "Library", "Application Support", "Eloxiv", "daemon")
80
+ return join(env["XDG_STATE_HOME"] ?? join(homedir(), ".local", "state"), "eloxiv", "daemon")
81
+ }
82
+
83
+ export class StateFile {
84
+ readonly path: string
85
+ #state: DaemonState
86
+
87
+ readonly dir: string
88
+
89
+ constructor(dir: string) {
90
+ this.dir = dir
91
+ this.path = join(dir, "state.json")
92
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
93
+ this.#state = existsSync(this.path) ? (JSON.parse(readFileSync(this.path, "utf8")) as DaemonState) : emptyState
94
+ }
95
+
96
+ get current(): DaemonState {
97
+ return this.#state
98
+ }
99
+
100
+ update(change: (state: DaemonState) => DaemonState): DaemonState {
101
+ const next = change(this.#state)
102
+ const temporary = `${this.path}.${process.pid}.tmp`
103
+ writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 })
104
+ chmodSync(temporary, 0o600)
105
+ renameSync(temporary, this.path)
106
+ this.#state = next
107
+ return next
108
+ }
109
+ }
@@ -0,0 +1,227 @@
1
+ /**
2
+ * Terminal sessions for the person's local clients (DeviceControl): an interactive shell in the daemon's workspace,
3
+ * its output streamed to the client that opened it and its input written by that client only. On Bun the shell
4
+ * runs in a pseudo-terminal (`Bun.spawn`'s `terminal`); on Node, which has none built in, it runs with pipes
5
+ * (`pty: false`: no line editing or full-screen programs).
6
+ *
7
+ * Off unless the daemon serves terminal commands (`--allow-commands terminal`, with a workspace). The shell runs as
8
+ * the daemon's OS user with the harnesses' environment allow-list (no credentials), in its own process group, which
9
+ * is killed when the terminal is closed, when its shell exits, when no client has watched it for ten minutes, and
10
+ * when the daemon stops.
11
+ */
12
+ import { spawn, type ChildProcess } from "node:child_process"
13
+ import { randomUUID } from "node:crypto"
14
+ import { harnessEnv } from "./Harness.ts"
15
+
16
+ /** Terminals open at once, per daemon. */
17
+ export const MAX_TERMINALS = 8
18
+ /** Output kept for a client that (re)attaches (characters). */
19
+ const BACKLOG = 64 * 1024
20
+ /** A terminal no client has watched for this long is closed (ms). */
21
+ export const TERMINAL_IDLE_MS = 10 * 60_000
22
+
23
+ type Listener = (
24
+ event: { readonly type: "output"; readonly data: string } | { readonly type: "exit"; readonly code: number | null },
25
+ ) => void
26
+
27
+ interface BunTerminal {
28
+ write(data: string): void
29
+ resize(cols: number, rows: number): void
30
+ close(): void
31
+ }
32
+
33
+ interface Terminal {
34
+ readonly id: string
35
+ readonly owner: string
36
+ readonly pty: boolean
37
+ readonly startedAt: string
38
+ readonly write: (data: string) => void
39
+ readonly resize: (cols: number, rows: number) => void
40
+ readonly kill: () => void
41
+ backlog: string
42
+ exited: { code: number | null } | undefined
43
+ readonly listeners: Set<Listener>
44
+ idleSince: number
45
+ }
46
+
47
+ export class TerminalError extends Error {
48
+ readonly status: 403 | 404 | 429
49
+ constructor(status: 403 | 404 | 429, message: string) {
50
+ super(message)
51
+ this.status = status
52
+ }
53
+ }
54
+
55
+ const bunSpawn = (globalThis as { Bun?: { spawn?: (...args: Array<unknown>) => unknown; Terminal?: unknown } }).Bun
56
+
57
+ /** Whether terminals here get a pseudo-terminal (Bun) or pipes (Node). */
58
+ export const ptyAvailable = () => typeof bunSpawn?.Terminal === "function"
59
+
60
+ /** Every daemon's terminals in this process, closed when the process exits (their shells are process groups). */
61
+ const everyTerminals = new Set<Terminals>()
62
+ let exitHook = false
63
+
64
+ export class Terminals {
65
+ readonly #open = new Map<string, Terminal>()
66
+ readonly #sweep: ReturnType<typeof setInterval>
67
+ readonly #onChange: (terminal: { id: string; startedAt: string; endedAt: string | null; pty: boolean }) => void
68
+
69
+ constructor(onChange: (terminal: { id: string; startedAt: string; endedAt: string | null; pty: boolean }) => void) {
70
+ this.#onChange = onChange
71
+ this.#sweep = setInterval(() => {
72
+ const now = Date.now()
73
+ for (const terminal of this.#open.values()) {
74
+ if (terminal.listeners.size === 0 && now - terminal.idleSince > TERMINAL_IDLE_MS) this.#end(terminal)
75
+ }
76
+ }, 60_000)
77
+ this.#sweep.unref()
78
+ everyTerminals.add(this)
79
+ if (!exitHook) {
80
+ exitHook = true
81
+ process.once("exit", () => {
82
+ for (const terminals of everyTerminals) terminals.closeAll()
83
+ })
84
+ }
85
+ }
86
+
87
+ /** Open a shell in `cwd` for the client `owner`. */
88
+ open(owner: string, input: { readonly cwd: string; readonly cols: number; readonly rows: number }) {
89
+ if (this.#open.size >= MAX_TERMINALS)
90
+ throw new TerminalError(429, `At most ${MAX_TERMINALS} terminals are open at once`)
91
+ const id = randomUUID()
92
+ const windows = process.platform === "win32"
93
+ const shell = windows ? "cmd.exe" : "/bin/sh"
94
+ const env = harnessEnv({ TERM: "xterm-256color" })
95
+ const terminal: Terminal = {
96
+ id,
97
+ owner,
98
+ pty: ptyAvailable(),
99
+ startedAt: new Date().toISOString(),
100
+ write: () => {},
101
+ resize: () => {},
102
+ kill: () => {},
103
+ backlog: "",
104
+ exited: undefined,
105
+ listeners: new Set(),
106
+ idleSince: Date.now(),
107
+ }
108
+ const emit = (data: string) => {
109
+ terminal.backlog = (terminal.backlog + data).slice(-BACKLOG)
110
+ for (const listener of terminal.listeners) listener({ type: "output", data })
111
+ }
112
+ const exited = (code: number | null) => {
113
+ if (terminal.exited !== undefined) return
114
+ terminal.exited = { code }
115
+ for (const listener of terminal.listeners) listener({ type: "exit", code })
116
+ this.#end(terminal)
117
+ }
118
+ if (terminal.pty) {
119
+ const decoder = new TextDecoder()
120
+ const proc = bunSpawn!.spawn!([shell], {
121
+ cwd: input.cwd,
122
+ env,
123
+ terminal: {
124
+ cols: input.cols,
125
+ rows: input.rows,
126
+ data: (_t: unknown, data: Uint8Array) => emit(decoder.decode(data, { stream: true })),
127
+ },
128
+ }) as { pid: number; terminal: BunTerminal; exited: Promise<number>; kill: (signal?: string) => void }
129
+ Object.assign(terminal, {
130
+ write: (data: string) => proc.terminal.write(data),
131
+ resize: (cols: number, rows: number) => proc.terminal.resize(cols, rows),
132
+ kill: () => {
133
+ try {
134
+ process.kill(-proc.pid, "SIGKILL")
135
+ } catch {
136
+ proc.kill("SIGKILL")
137
+ }
138
+ proc.terminal.close()
139
+ },
140
+ })
141
+ void proc.exited.then((code) => exited(code))
142
+ } else {
143
+ const child: ChildProcess = spawn(shell, windows ? [] : ["-i"], {
144
+ cwd: input.cwd,
145
+ env,
146
+ stdio: ["pipe", "pipe", "pipe"],
147
+ detached: !windows,
148
+ })
149
+ child.stdout!.setEncoding("utf8").on("data", emit)
150
+ child.stderr!.setEncoding("utf8").on("data", emit)
151
+ child.on("error", () => exited(null))
152
+ child.on("close", (code) => exited(code))
153
+ Object.assign(terminal, {
154
+ write: (data: string) => child.stdin!.write(data),
155
+ kill: () => {
156
+ try {
157
+ if (!windows && child.pid !== undefined) process.kill(-child.pid, "SIGKILL")
158
+ else child.kill("SIGKILL")
159
+ } catch {
160
+ // Already gone.
161
+ }
162
+ },
163
+ })
164
+ }
165
+ this.#open.set(id, terminal)
166
+ this.#onChange({ id, startedAt: terminal.startedAt, endedAt: null, pty: terminal.pty })
167
+ return { id, pty: terminal.pty }
168
+ }
169
+
170
+ /** The terminal `id` if `owner` opened it (anyone else: not found). */
171
+ #owned(owner: string, id: string) {
172
+ const terminal = this.#open.get(id)
173
+ if (terminal === undefined || terminal.owner !== owner) throw new TerminalError(404, "No such terminal")
174
+ return terminal
175
+ }
176
+
177
+ list(owner: string) {
178
+ return [...this.#open.values()]
179
+ .filter((terminal) => terminal.owner === owner)
180
+ .map(({ id, pty, startedAt }) => ({ id, pty, startedAt }))
181
+ }
182
+
183
+ write(owner: string, id: string, data: string) {
184
+ this.#owned(owner, id).write(data)
185
+ }
186
+
187
+ resize(owner: string, id: string, cols: number, rows: number) {
188
+ this.#owned(owner, id).resize(cols, rows)
189
+ }
190
+
191
+ /** Watch a terminal: its backlog first, then what follows; the returned function stops watching. */
192
+ watch(owner: string, id: string, listener: Listener): () => void {
193
+ const terminal = this.#owned(owner, id)
194
+ if (terminal.backlog.length > 0) listener({ type: "output", data: terminal.backlog })
195
+ terminal.listeners.add(listener)
196
+ return () => {
197
+ terminal.listeners.delete(listener)
198
+ terminal.idleSince = Date.now()
199
+ }
200
+ }
201
+
202
+ close(owner: string, id: string) {
203
+ this.#end(this.#owned(owner, id))
204
+ }
205
+
206
+ #end(terminal: Terminal) {
207
+ if (!this.#open.delete(terminal.id)) return
208
+ terminal.kill()
209
+ if (terminal.exited === undefined) {
210
+ terminal.exited = { code: null }
211
+ for (const listener of terminal.listeners) listener({ type: "exit", code: null })
212
+ }
213
+ this.#onChange({
214
+ id: terminal.id,
215
+ startedAt: terminal.startedAt,
216
+ endedAt: new Date().toISOString(),
217
+ pty: terminal.pty,
218
+ })
219
+ }
220
+
221
+ /** Close every terminal (the daemon stops). */
222
+ closeAll() {
223
+ clearInterval(this.#sweep)
224
+ everyTerminals.delete(this)
225
+ for (const terminal of Array.from(this.#open.values())) this.#end(terminal)
226
+ }
227
+ }
@@ -0,0 +1,4 @@
1
+ /** Run the daemon on Node (fallback): `node --conditions=@eloxiv/source src/bin-node.ts`. */
2
+ import { runMain } from "./runtime/node.ts"
3
+
4
+ runMain()
package/src/bin.ts ADDED
@@ -0,0 +1,4 @@
1
+ /** The sidecar entry point, compiled by `build:sidecar` with `bun build --compile`. */
2
+ import { runMain } from "./runtime/bun.ts"
3
+
4
+ runMain()
package/src/index.ts ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * The Eloxiv device daemon: pairing with the kernel and custody of the device credential, a loopback relay for
3
+ * local clients and harnesses, local agent harnesses (Claude Code, Codex) on the person's own subscriptions,
4
+ * and a headless runner. Ships as a Bun-compiled sidecar binary (`build:sidecar`); `runtime/bun` and
5
+ * `runtime/node` run it in process.
6
+ */
7
+ export * from "./Client.ts"
8
+ export * from "./Config.ts"
9
+ export * from "./Daemon.ts"
10
+ export * from "./Harness.ts"
11
+ export * from "./Http.ts"
12
+ export * from "./KernelLink.ts"
13
+ export * from "./LocalAuth.ts"
14
+ export * from "./Main.ts"
15
+ export * from "./PersonSession.ts"
16
+ export * from "./Secrets.ts"
17
+ export * from "./State.ts"
@@ -0,0 +1,29 @@
1
+ /** Run the daemon on Bun: the runtime the sidecar binary is compiled for. */
2
+ // Each module on its own: the package's index also loads the Redis client, which the daemon never uses.
3
+ import * as BunHttpServer from "@effect/platform-bun/BunHttpServer"
4
+ import * as BunRuntime from "@effect/platform-bun/BunRuntime"
5
+ import type { SyncSqliteDatabase } from "@eloxiv/client/storage"
6
+ import { createRequire } from "node:module"
7
+ import { HOSTNAME, type DaemonConfig } from "../Config.ts"
8
+ import type { Daemon } from "../Daemon.ts"
9
+ import { daemonLayer, mainFor, runnerOf } from "../Main.ts"
10
+
11
+ /** This runtime's synchronous SQLite (`bun:sqlite`), for LocalClient's replica; loaded only when a `clientApp` is served. */
12
+ export const openSqlite = (path: string): SyncSqliteDatabase => {
13
+ const { Database } = createRequire(import.meta.url)("bun:sqlite") as {
14
+ Database: new (path: string) => SyncSqliteDatabase
15
+ }
16
+ return new Database(path)
17
+ }
18
+
19
+ export const serverLayer = (
20
+ config: Pick<DaemonConfig, "port"> & Partial<Pick<DaemonConfig, "headless" | "kernelUrl" | "name">>,
21
+ daemon: Daemon,
22
+ ) => daemonLayer(BunHttpServer.layer({ hostname: HOSTNAME, port: config.port }), daemon, runnerOf(config))
23
+
24
+ /** Run the daemon on this runtime: the generic sidecar, or an app's own with a `clientApp` (decision 14). */
25
+ export const runMain = mainFor({
26
+ serverLayer: (config, daemon) => serverLayer(config, daemon),
27
+ runMain: (effect, options) => BunRuntime.runMain(effect, options),
28
+ openSqlite,
29
+ })
@@ -0,0 +1,30 @@
1
+ /** Run the daemon on Node: the fallback runtime, kept working by CI. */
2
+ import { createServer } from "node:http"
3
+ // Each module on its own: the package's index also loads the Redis client, which the daemon never uses.
4
+ import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"
5
+ import * as NodeRuntime from "@effect/platform-node/NodeRuntime"
6
+ import type { SyncSqliteDatabase } from "@eloxiv/client/storage"
7
+ import { createRequire } from "node:module"
8
+ import { HOSTNAME, type DaemonConfig } from "../Config.ts"
9
+ import type { Daemon } from "../Daemon.ts"
10
+ import { daemonLayer, mainFor, runnerOf } from "../Main.ts"
11
+
12
+ /** This runtime's synchronous SQLite (`node:sqlite`), for LocalClient's replica; loaded only when a `clientApp` is served. */
13
+ export const openSqlite = (path: string): SyncSqliteDatabase => {
14
+ const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite") as {
15
+ DatabaseSync: new (path: string) => SyncSqliteDatabase
16
+ }
17
+ return new DatabaseSync(path)
18
+ }
19
+
20
+ export const serverLayer = (
21
+ config: Pick<DaemonConfig, "port"> & Partial<Pick<DaemonConfig, "headless" | "kernelUrl" | "name">>,
22
+ daemon: Daemon,
23
+ ) => daemonLayer(NodeHttpServer.layer(createServer, { host: HOSTNAME, port: config.port }), daemon, runnerOf(config))
24
+
25
+ /** Run the daemon on this runtime: the generic sidecar, or an app's own with a `clientApp` (decision 14). */
26
+ export const runMain = mainFor({
27
+ serverLayer: (config, daemon) => serverLayer(config, daemon),
28
+ runMain: (effect, options) => NodeRuntime.runMain(effect, options),
29
+ openSqlite,
30
+ })