@eloxiv/daemon 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +6 -2
  3. package/dist/Acp.d.ts +8 -0
  4. package/dist/Acp.d.ts.map +1 -0
  5. package/dist/Acp.js +268 -0
  6. package/dist/Acp.js.map +1 -0
  7. package/dist/Canonical.d.ts +3 -0
  8. package/dist/Canonical.d.ts.map +1 -0
  9. package/dist/Canonical.js +12 -0
  10. package/dist/Canonical.js.map +1 -0
  11. package/dist/Client.d.ts +100 -0
  12. package/dist/Client.d.ts.map +1 -0
  13. package/dist/Client.js +474 -0
  14. package/dist/Client.js.map +1 -0
  15. package/dist/Commands.d.ts +85 -0
  16. package/dist/Commands.d.ts.map +1 -0
  17. package/dist/Commands.js +370 -0
  18. package/dist/Commands.js.map +1 -0
  19. package/dist/Config.d.ts +74 -0
  20. package/dist/Config.d.ts.map +1 -0
  21. package/dist/Config.js +126 -0
  22. package/dist/Config.js.map +1 -0
  23. package/dist/Daemon.d.ts +243 -0
  24. package/dist/Daemon.d.ts.map +1 -0
  25. package/dist/Daemon.js +965 -0
  26. package/dist/Daemon.js.map +1 -0
  27. package/dist/Harness.d.ts +133 -0
  28. package/dist/Harness.d.ts.map +1 -0
  29. package/dist/Harness.js +734 -0
  30. package/dist/Harness.js.map +1 -0
  31. package/dist/Http.d.ts +15 -0
  32. package/dist/Http.d.ts.map +1 -0
  33. package/dist/Http.js +548 -0
  34. package/dist/Http.js.map +1 -0
  35. package/dist/KernelLink.d.ts +145 -0
  36. package/dist/KernelLink.d.ts.map +1 -0
  37. package/dist/KernelLink.js +109 -0
  38. package/dist/KernelLink.js.map +1 -0
  39. package/dist/LocalAuth.d.ts +99 -0
  40. package/dist/LocalAuth.d.ts.map +1 -0
  41. package/dist/LocalAuth.js +225 -0
  42. package/dist/LocalAuth.js.map +1 -0
  43. package/dist/Main.d.ts +51 -0
  44. package/dist/Main.d.ts.map +1 -0
  45. package/dist/Main.js +219 -0
  46. package/dist/Main.js.map +1 -0
  47. package/dist/Secrets.d.ts +21 -0
  48. package/dist/Secrets.d.ts.map +1 -0
  49. package/dist/Secrets.js +204 -0
  50. package/dist/Secrets.js.map +1 -0
  51. package/dist/SecureUrl.d.ts +11 -0
  52. package/dist/SecureUrl.d.ts.map +1 -0
  53. package/dist/SecureUrl.js +23 -0
  54. package/dist/SecureUrl.js.map +1 -0
  55. package/dist/State.d.ts +77 -0
  56. package/dist/State.d.ts.map +1 -0
  57. package/dist/State.js +38 -0
  58. package/dist/State.js.map +1 -0
  59. package/dist/Terminals.d.ts +49 -0
  60. package/dist/Terminals.d.ts.map +1 -0
  61. package/dist/Terminals.js +203 -0
  62. package/dist/Terminals.js.map +1 -0
  63. package/dist/bin-node.d.ts +2 -0
  64. package/dist/bin-node.d.ts.map +1 -0
  65. package/dist/bin-node.js +4 -0
  66. package/dist/bin-node.js.map +1 -0
  67. package/dist/bin.d.ts +2 -0
  68. package/dist/bin.d.ts.map +1 -0
  69. package/dist/bin.js +4 -0
  70. package/dist/bin.js.map +1 -0
  71. package/dist/index.d.ts +17 -0
  72. package/dist/index.d.ts.map +1 -0
  73. package/dist/index.js +17 -0
  74. package/dist/index.js.map +1 -0
  75. package/dist/runtime/bun.d.ts +11 -0
  76. package/dist/runtime/bun.d.ts.map +1 -0
  77. package/dist/runtime/bun.js +20 -0
  78. package/dist/runtime/bun.js.map +1 -0
  79. package/dist/runtime/node.d.ts +11 -0
  80. package/dist/runtime/node.d.ts.map +1 -0
  81. package/dist/runtime/node.js +21 -0
  82. package/dist/runtime/node.js.map +1 -0
  83. package/dist/testing.d.ts +25 -0
  84. package/dist/testing.d.ts.map +1 -0
  85. package/dist/testing.js +27 -0
  86. package/dist/testing.js.map +1 -0
  87. package/fixtures/claude-code-env-vars.txt +409 -0
  88. package/fixtures/fake-acp-agent.mjs +222 -0
  89. package/fixtures/fake-harness.mjs +299 -0
  90. package/fixtures/recorded/claude-code.jsonl +7 -0
  91. package/fixtures/recorded/codex.jsonl +6 -0
  92. package/package.json +64 -3
  93. package/scripts/build-sidecar.ts +86 -0
  94. package/src/Acp.ts +292 -0
  95. package/src/Canonical.ts +9 -0
  96. package/src/Client.ts +585 -0
  97. package/src/Commands.ts +427 -0
  98. package/src/Config.ts +179 -0
  99. package/src/Daemon.ts +1092 -0
  100. package/src/Harness.ts +839 -0
  101. package/src/Http.ts +563 -0
  102. package/src/KernelLink.ts +197 -0
  103. package/src/LocalAuth.ts +301 -0
  104. package/src/Main.ts +281 -0
  105. package/src/Secrets.ts +226 -0
  106. package/src/SecureUrl.ts +21 -0
  107. package/src/State.ts +109 -0
  108. package/src/Terminals.ts +227 -0
  109. package/src/bin-node.ts +4 -0
  110. package/src/bin.ts +4 -0
  111. package/src/index.ts +16 -0
  112. package/src/runtime/bun.ts +29 -0
  113. package/src/runtime/node.ts +30 -0
  114. package/src/testing.ts +43 -0
package/src/Main.ts ADDED
@@ -0,0 +1,281 @@
1
+ /**
2
+ * Platform-neutral start-up: build the daemon's core, announce readiness once listening, start the runner in
3
+ * headless mode, watch the stdin lifeline, and map shutdown to a clean exit; and the one-shot commands
4
+ * (`pair`, `status`, `unpair`). `runtime/bun` and `runtime/node` supply the HTTP server.
5
+ */
6
+ import type { DaemonStatus } from "@eloxiv/contracts"
7
+ import { mkdirSync, readFileSync } from "node:fs"
8
+ import { resolve, sep } from "node:path"
9
+ import { Cause, Effect, Exit, Layer } from "effect"
10
+ import { HttpServer } from "effect/http"
11
+ import type { Teardown } from "effect/Runtime"
12
+ import type { SyncSqliteDatabase } from "@eloxiv/client/storage"
13
+ import type { Effect as EffectType } from "effect/Effect"
14
+ import { readHostSecret, readyLine, resolveConfig, type DaemonConfig } from "./Config.ts"
15
+ import type { ClientApp } from "./Client.ts"
16
+ import { controlSecretPath, Daemon, type DaemonOptions } from "./Daemon.ts"
17
+ import { DaemonHttp, trustedOriginsFor } from "./Http.ts"
18
+ import { selectSecretStore } from "./Secrets.ts"
19
+
20
+ /** `release` in the compiled sidecar (`build:sidecar` defines it), `development` when run from source. */
21
+ declare const ELOXIV_DAEMON_BUILD: string | undefined
22
+ export const DAEMON_BUILD: string = typeof ELOXIV_DAEMON_BUILD === "string" ? ELOXIV_DAEMON_BUILD : "development"
23
+
24
+ /** The port the platform server actually bound (differs from the config when it asked for 0). */
25
+ export const boundPort = Effect.gen(function* () {
26
+ const server = yield* HttpServer.HttpServer
27
+ return server.address._tag === "UnixPathAddress" ? 0 : server.address.port
28
+ })
29
+
30
+ /** The daemon's core for a config: its state directory, secret store and harnesses. */
31
+ export const createDaemon = async (
32
+ config: Pick<DaemonConfig, "stateDir" | "secretStore" | "headless" | "trustedOrigins" | "workspace" | "hostSecret"> &
33
+ Partial<Pick<DaemonConfig, "commands" | "toolsOnly">>,
34
+ overrides: Partial<DaemonOptions> = {},
35
+ ): Promise<Daemon> => {
36
+ mkdirSync(config.stateDir, { recursive: true, mode: 0o700 })
37
+ const stateDir = resolve(config.stateDir)
38
+ const workspace = config.workspace === undefined ? undefined : resolve(config.workspace)
39
+ // A harness works in its workspace: it must never be the state directory (the credential's file store, the
40
+ // control secret, state.json) or inside it. The state directory may be inside the workspace (a home directory as
41
+ // the workspace, the default state under it): file commands exclude it (`Commands.ts`).
42
+ if (workspace !== undefined && (workspace === stateDir || workspace.startsWith(`${stateDir}${sep}`))) {
43
+ throw new Error(`The workspace (${workspace}) must be outside the state directory (${stateDir})`)
44
+ }
45
+ if (workspace !== undefined) mkdirSync(workspace, { recursive: true })
46
+ return new Daemon({
47
+ mode: config.headless ? "headless" : "desktop",
48
+ stateDir: config.stateDir,
49
+ secrets: await selectSecretStore(config.secretStore, config.stateDir),
50
+ hostSecret: config.hostSecret,
51
+ trustedOrigins: config.trustedOrigins ?? trustedOriginsFor(DAEMON_BUILD),
52
+ workspace,
53
+ commands: config.commands,
54
+ toolsOnly: config.toolsOnly,
55
+ ...overrides,
56
+ })
57
+ }
58
+
59
+ /**
60
+ * Once listening: tell the core its port, start the runner (headless; pairing first when `--kernel` is given
61
+ * and the device is not paired), and print the ready line.
62
+ */
63
+ const started = (daemon: Daemon, config: Pick<DaemonConfig, "headless" | "kernelUrl" | "name">) =>
64
+ Effect.gen(function* () {
65
+ daemon.port = yield* boundPort
66
+ // Device commands, in either mode, once paired (a pairing completed later starts them too).
67
+ if (daemon.paired) daemon.startCommands()
68
+ // LocalClient: the stored person session is checked in the background (the kernel may not be up yet).
69
+ if (daemon.client !== undefined) void daemon.client.start()
70
+ if (config.headless) {
71
+ if (daemon.paired) daemon.startRunner()
72
+ else if (config.kernelUrl !== undefined) {
73
+ const pairing = yield* Effect.promise(() =>
74
+ daemon.startKernelPairing(config.kernelUrl!, { name: config.name, kind: "runner" }),
75
+ )
76
+ // The code goes to a person at a terminal only, never to a log (`eloxiv-daemon pairing-code` reads it).
77
+ if (process.stderr.isTTY) {
78
+ process.stderr.write(
79
+ `To pair this runner, confirm the code ${pairing.started.userCode} at ${pairing.started.verificationUri}\n`,
80
+ )
81
+ }
82
+ pairing.done.then(
83
+ () => daemon.startRunner(),
84
+ (error: unknown) => daemon.log(`pairing failed: ${String(error)}`),
85
+ )
86
+ } else {
87
+ daemon.log("headless, but not paired: run `eloxiv-daemon pair --kernel <url> --runner` or pass --kernel")
88
+ }
89
+ }
90
+ if (daemon.options.announce !== false) yield* Effect.sync(() => process.stdout.write(`${readyLine(daemon.port)}\n`))
91
+ })
92
+
93
+ /** The runner settings of a config, as `daemonLayer` takes them. */
94
+ export const runnerOf = (config: Partial<Pick<DaemonConfig, "headless" | "kernelUrl" | "name">>) => ({
95
+ headless: config.headless ?? false,
96
+ kernelUrl: config.kernelUrl,
97
+ name: config.name,
98
+ })
99
+
100
+ /**
101
+ * The daemon application over some platform `HttpServer` layer, which must already be bound to the configured
102
+ * host and port. The server stays in the output so callers can read the bound address.
103
+ */
104
+ export const daemonLayer = <E, R>(
105
+ server: Layer.Layer<HttpServer.HttpServer, E, R>,
106
+ daemon: Daemon,
107
+ config: Pick<DaemonConfig, "headless" | "kernelUrl" | "name"> = {
108
+ headless: false,
109
+ kernelUrl: undefined,
110
+ name: undefined,
111
+ },
112
+ ) =>
113
+ DaemonHttp(daemon).pipe(
114
+ Layer.tap(() => started(daemon, config)),
115
+ Layer.provideMerge(server),
116
+ )
117
+
118
+ /** Completes when stdin reaches end of file (the parent closed its end or died). */
119
+ export const stdinClosed = Effect.callback<void>((resume) => {
120
+ const done = () => resume(Effect.void)
121
+ process.stdin.once("end", done)
122
+ process.stdin.once("close", done)
123
+ process.stdin.resume()
124
+ return Effect.sync(() => {
125
+ process.stdin.off("end", done)
126
+ process.stdin.off("close", done)
127
+ process.stdin.pause()
128
+ })
129
+ })
130
+
131
+ /** Run the daemon until interrupted (SIGTERM/SIGINT) or, with the lifeline, until stdin closes. */
132
+ export const program = <E, R>(app: Layer.Layer<never, E, R>, config: Pick<DaemonConfig, "stdinLifeline">) => {
133
+ const serve = Layer.launch(app)
134
+ return config.stdinLifeline ? Effect.raceFirst(serve, stdinClosed) : serve
135
+ }
136
+
137
+ /** Shutting down on a signal or on the lifeline is a clean exit (0); anything else is 1. */
138
+ export const teardown: Teardown = (exit, onExit) => {
139
+ const clean = Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause)
140
+ onExit(clean ? 0 : 1)
141
+ // runMain only exits by itself after a signal or a failure; the lifeline path ends here.
142
+ if (clean) process.exit(0)
143
+ }
144
+
145
+ /**
146
+ * `approve-client`: the person at this machine approves a local client's pairing with the running daemon (the
147
+ * port from `ELOXIV_DAEMON_PORT` or --port), acting as the host through the control secret in the state
148
+ * directory. Without an id it lists the pending requests; with one it approves it and prints the code to type
149
+ * into the client.
150
+ */
151
+ const approveClient = async (config: DaemonConfig): Promise<number> => {
152
+ const secret = readFileSync(controlSecretPath(config.stateDir), "utf8").trim()
153
+ const base = `http://127.0.0.1:${config.port}`
154
+ const headers = { authorization: `Bearer ${secret}`, "content-type": "application/json" }
155
+ if (config.pairingId === undefined) {
156
+ const pending = (await (await fetch(`${base}/local/pairings`, { headers })).json()) as ReadonlyArray<{
157
+ pairingId: string
158
+ clientName: string
159
+ kind: string
160
+ approved: boolean
161
+ }>
162
+ if (pending.length === 0) process.stdout.write("No local client is waiting to pair.\n")
163
+ for (const entry of pending) {
164
+ process.stdout.write(
165
+ `${entry.pairingId} ${entry.kind} ${JSON.stringify(entry.clientName)}${entry.approved ? " (approved)" : ""}\n`,
166
+ )
167
+ }
168
+ return 0
169
+ }
170
+ const answer = await fetch(`${base}/local/pairings/${encodeURIComponent(config.pairingId)}/approve`, {
171
+ method: "POST",
172
+ headers,
173
+ body: "{}",
174
+ })
175
+ if (!answer.ok) {
176
+ process.stdout.write(`Could not approve ${config.pairingId}: ${await answer.text()}\n`)
177
+ return 1
178
+ }
179
+ const approved = (await answer.json()) as { code: string; clientName: string }
180
+ process.stdout.write(`Approved ${JSON.stringify(approved.clientName)}. Type this code into it: ${approved.code}\n`)
181
+ return 0
182
+ }
183
+
184
+ /**
185
+ * `pairing-code`: the kernel pairing code of the running daemon (the port from `ELOXIV_DAEMON_PORT` or --port),
186
+ * read through the control secret in the state directory, for the person at this machine. The daemon never logs it.
187
+ */
188
+ const pairingCode = async (config: DaemonConfig): Promise<number> => {
189
+ const secret = readFileSync(controlSecretPath(config.stateDir), "utf8").trim()
190
+ const answer = await fetch(`http://127.0.0.1:${config.port}/status`, {
191
+ headers: { authorization: `Bearer ${secret}` },
192
+ })
193
+ if (!answer.ok) {
194
+ process.stdout.write(`Could not read the daemon's status: ${await answer.text()}\n`)
195
+ return 1
196
+ }
197
+ const status = (await answer.json()) as DaemonStatus
198
+ if (status.kernel.userCode === null) {
199
+ process.stdout.write(`No kernel pairing is in progress (this device is ${status.kernel.state}).\n`)
200
+ return 1
201
+ }
202
+ process.stdout.write(
203
+ `Confirm the code ${status.kernel.userCode} at ${status.kernel.verificationUri ?? status.kernel.url ?? "the kernel"}\n`,
204
+ )
205
+ return 0
206
+ }
207
+
208
+ /**
209
+ * `pair`, `status`, `unpair`, `approve-client` and `pairing-code`: one-shot commands, printing to stdout. Resolves to
210
+ * the exit code.
211
+ */
212
+ export const runCommand = async (config: DaemonConfig): Promise<number> => {
213
+ // They talk to the running daemon; starting a second core here would replace that daemon's control secret.
214
+ if (config.command === "approve-client") return approveClient(config)
215
+ if (config.command === "pairing-code") return pairingCode(config)
216
+ const daemon = await createDaemon(config)
217
+ switch (config.command) {
218
+ case "pair": {
219
+ const pairing = await daemon.startKernelPairing(config.kernelUrl!, {
220
+ name: config.name,
221
+ kind: config.runner ? "runner" : "desktop",
222
+ })
223
+ process.stdout.write(
224
+ `To pair this device, sign in at ${pairing.started.verificationUri} and confirm the code ${pairing.started.userCode}\n` +
225
+ `(${pairing.started.verificationUriComplete}). Waiting...\n`,
226
+ )
227
+ try {
228
+ await pairing.done
229
+ } catch (error) {
230
+ process.stdout.write(`Pairing failed: ${String(error instanceof Error ? error.message : error)}\n`)
231
+ return 1
232
+ }
233
+ const kernel = daemon.state.current.kernel!
234
+ process.stdout.write(
235
+ `Paired as device ${kernel.deviceId} in ${kernel.orgId}; the credential is in the ${daemon.options.secrets.kind} store.\n`,
236
+ )
237
+ return 0
238
+ }
239
+ case "status":
240
+ process.stdout.write(`${JSON.stringify(await daemon.status(), null, 2)}\n`)
241
+ return 0
242
+ case "unpair":
243
+ await daemon.unpair()
244
+ process.stdout.write("Unpaired: the credential was deleted (revoke the device on the kernel too).\n")
245
+ return 0
246
+ case "serve":
247
+ return 0
248
+ }
249
+ }
250
+
251
+ /** What a runtime entry (`runtime/bun`, `runtime/node`) gives `mainFor`: its server layer, run-main and SQLite. */
252
+ export interface RuntimeEntry {
253
+ readonly serverLayer: (config: DaemonConfig, daemon: Daemon) => Layer.Layer<never, unknown>
254
+ readonly runMain: (effect: EffectType<unknown, unknown>, options: { readonly teardown: Teardown }) => void
255
+ readonly openSqlite: (path: string) => SyncSqliteDatabase
256
+ }
257
+
258
+ /**
259
+ * The daemon's main for a runtime: the generic sidecar (`bin.ts`), or an app's own with `clientApp` (what it serves
260
+ * LocalClient for, decision 14). One-shot commands run and exit; `serve` runs until interrupted or the lifeline ends.
261
+ */
262
+ export const mainFor =
263
+ (entry: RuntimeEntry) =>
264
+ (
265
+ argv: ReadonlyArray<string> = process.argv.slice(2),
266
+ env: Record<string, string | undefined> = process.env,
267
+ options: { readonly clientApp?: ClientApp | undefined } = {},
268
+ ) => {
269
+ // The host's secret leaves the environment at once: nothing the daemon starts inherits it.
270
+ const config = { ...resolveConfig(argv, env), hostSecret: readHostSecret(env) }
271
+ if (config.command !== "serve") {
272
+ void runCommand(config).then((code) => process.exit(code))
273
+ return
274
+ }
275
+ const overrides =
276
+ options.clientApp === undefined ? {} : { clientApp: options.clientApp, sqlite: entry.openSqlite, env }
277
+ const app = Layer.unwrap(
278
+ Effect.promise(() => createDaemon(config, overrides)).pipe(Effect.map((d) => entry.serverLayer(config, d))),
279
+ )
280
+ entry.runMain(program(app, config), { teardown })
281
+ }
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
+ }