@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
@@ -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,16 @@
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 "./Secrets.ts"
16
+ 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
+ })
package/src/testing.ts ADDED
@@ -0,0 +1,43 @@
1
+ /**
2
+ * For tests and conformance kits: the fake harness binary, which speaks Claude Code's and Codex's stream
3
+ * formats (recorded from real runs, `fixtures/recorded/`) and calls tools through the daemon's MCP relay, so no
4
+ * subscription is needed.
5
+ */
6
+ import type { HarnessKind } from "@eloxiv/contracts"
7
+ import { fileURLToPath } from "node:url"
8
+ import type { Daemon } from "./Daemon.ts"
9
+ import type { HarnessConfig } from "./Harness.ts"
10
+
11
+ /** The daemon's server layer on `port` (0: any free port) for this runtime (Bun or Node). */
12
+ export const serverLayerFor = async (port: number, daemon: Daemon) => {
13
+ const runtime =
14
+ typeof process.versions["bun"] === "string" ? await import("./runtime/bun.ts") : await import("./runtime/node.ts")
15
+ return runtime.serverLayer({ port }, daemon)
16
+ }
17
+
18
+ /** `fixtures/fake-harness.mjs`, resolved from both `src` and `dist`. */
19
+ export const fakeHarnessPath = fileURLToPath(new URL("../fixtures/fake-harness.mjs", import.meta.url))
20
+
21
+ /** `fixtures/fake-acp-agent.mjs`: an Agent Client Protocol agent that runs the same prompt scripts. */
22
+ export const fakeAcpAgentPath = fileURLToPath(new URL("../fixtures/fake-acp-agent.mjs", import.meta.url))
23
+
24
+ /** The recorded real outputs (`claude-code.jsonl`, `codex.jsonl`). */
25
+ export const recordedStreamPath = (kind: HarnessKind) =>
26
+ fileURLToPath(new URL(`../fixtures/recorded/${kind}.jsonl`, import.meta.url))
27
+
28
+ /**
29
+ * Harness configs that run the fake harness on this runtime (Bun or Node) for every kind: the CLIs' streams for
30
+ * Claude Code and Codex, the fake ACP agent for OpenCode (not tools-only, as OpenCode is not) and for a configured ACP
31
+ * agent the person declared tools-only.
32
+ */
33
+ export const fakeHarnesses = (): Record<HarnessKind, HarnessConfig> => ({
34
+ "claude-code": { kind: "claude-code", command: [process.execPath, fakeHarnessPath] },
35
+ codex: { kind: "codex", command: [process.execPath, fakeHarnessPath] },
36
+ opencode: { kind: "opencode", command: [process.execPath, fakeAcpAgentPath], protocol: "acp", toolsOnly: false },
37
+ acp: { kind: "acp", command: [process.execPath, fakeAcpAgentPath], protocol: "acp", toolsOnly: true },
38
+ })
39
+
40
+ /** This runtime's synchronous SQLite opener (`bun:sqlite` or `node:sqlite`), for a daemon serving LocalClient. */
41
+ export const runtimeSqlite = async () =>
42
+ (typeof process.versions["bun"] === "string" ? await import("./runtime/bun.ts") : await import("./runtime/node.ts"))
43
+ .openSqlite