@cueloop/daemon 0.1.0-alpha.8 → 0.1.0-alpha.81

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 (56) hide show
  1. package/package.json +37 -22
  2. package/src/api.test.ts +940 -65
  3. package/src/api.ts +1095 -88
  4. package/src/capabilities.test.ts +57 -0
  5. package/src/capabilities.ts +89 -0
  6. package/src/client.test.ts +24 -0
  7. package/src/client.ts +669 -86
  8. package/src/curate.ts +109 -0
  9. package/src/daemon-version.test.ts +93 -0
  10. package/src/diff-hot-reload.test.ts +272 -0
  11. package/src/diff-watcher.ts +274 -0
  12. package/src/gh.ts +37 -0
  13. package/src/ghostty-thread-surface-store.test.ts +49 -0
  14. package/src/ghostty-thread-surface-store.ts +101 -0
  15. package/src/ghostty-thread-surface.test.ts +398 -0
  16. package/src/ghostty-thread-surface.ts +267 -0
  17. package/src/harness-delivery.test.ts +208 -0
  18. package/src/harness-state-store.test.ts +65 -0
  19. package/src/harness-state-store.ts +181 -0
  20. package/src/herdr-split.test.ts +106 -0
  21. package/src/herdr-split.ts +92 -0
  22. package/src/herdr-thread-surface-store.test.ts +81 -0
  23. package/src/herdr-thread-surface-store.ts +64 -0
  24. package/src/herdr-thread-surface.test.ts +411 -0
  25. package/src/herdr-thread-surface.ts +355 -0
  26. package/src/index.ts +8 -9
  27. package/src/interruptible-wait.test.ts +127 -0
  28. package/src/interruptible-wait.ts +66 -0
  29. package/src/main.ts +4 -1
  30. package/src/paths.ts +49 -0
  31. package/src/pr-poller.test.ts +76 -0
  32. package/src/pr-poller.ts +74 -0
  33. package/src/project-files.test.ts +124 -0
  34. package/src/project-files.ts +56 -0
  35. package/src/protocol.ts +79 -7
  36. package/src/retention.test.ts +191 -0
  37. package/src/retention.ts +123 -0
  38. package/src/server.test.ts +432 -42
  39. package/src/server.ts +423 -89
  40. package/src/share-blob.test.ts +112 -0
  41. package/src/share-blob.ts +55 -0
  42. package/src/single-instance.test.ts +162 -13
  43. package/src/store.conformance.test.ts +41 -0
  44. package/src/store.jsonl.test.ts +159 -0
  45. package/src/store.ts +264 -34
  46. package/src/testing/store-conformance.ts +194 -0
  47. package/src/thread-review.test.ts +394 -0
  48. package/src/thread-review.ts +314 -0
  49. package/src/thread-surface-config.test.ts +63 -0
  50. package/src/thread-surface-config.ts +61 -0
  51. package/src/validate.test.ts +214 -35
  52. package/src/validate.ts +306 -25
  53. package/src/version.ts +6 -0
  54. package/src/working-tree.ts +149 -0
  55. package/src/review.test.ts +0 -167
  56. package/src/review.ts +0 -174
package/src/client.ts CHANGED
@@ -1,122 +1,472 @@
1
1
  /**
2
- * Daemon client: the one library every consumer shares - CLI verbs, the TUI,
3
- * adapters, and tests. Also owns the lazy-launch story (#14): connect() with
2
+ * Daemon client: the one library every consumer shares - CLI primitives, the TUI,
3
+ * adapters, and tests. Also owns the lazy-launch story: connect() with
4
4
  * autostart spawns a detached daemon when the socket is dead, then attaches.
5
5
  */
6
6
 
7
- import { existsSync, rmSync } from "node:fs";
8
- import type { Annotation, Artifact, ReviewSession, VerdictKind, WorkspaceKey } from "@cueloop/schema";
9
- import { LineBuffer, type EventFrame, type Response } from "./protocol";
10
- import { cueloopHome, socketPath } from "./paths";
7
+ import { spawn } from "node:child_process";
8
+ import { randomBytes } from "node:crypto";
9
+ import {
10
+ appendFileSync,
11
+ closeSync,
12
+ existsSync,
13
+ mkdirSync,
14
+ openSync,
15
+ readFileSync,
16
+ rmSync,
17
+ } from "node:fs";
18
+ import { createConnection } from "node:net";
19
+ import { join } from "node:path";
20
+ import * as v from "valibot";
21
+ import type {
22
+ Annotation,
23
+ Artifact,
24
+ DiffFileStatus,
25
+ DiffFileContents,
26
+ HunkRejection,
27
+ ShareLink,
28
+ Thread,
29
+ HarnessBinding,
30
+ Delivery,
31
+ PendingDelivery,
32
+ MessageOutcome,
33
+ WorkspaceKey,
34
+ } from "@cueloop/schema";
35
+ import {
36
+ BackpressureWriter,
37
+ LineBuffer,
38
+ parseInboundFrame,
39
+ type EventFrame,
40
+ type Request,
41
+ type Response,
42
+ } from "./protocol";
43
+ import type { DaemonRole } from "./capabilities";
44
+ import type { HerdrThreadSurfaceHandle } from "./herdr-thread-surface-store";
45
+ import type { GhosttyThreadSurfaceHandle } from "./ghostty-thread-surface-store";
46
+ import type { SharedMerge } from "./api";
47
+
48
+ export type { SharedMerge } from "./api";
49
+ import { cueloopHome, ownerTokenPath, socketPath } from "./paths";
50
+ import {
51
+ Params,
52
+ ThreadRecordSchema,
53
+ DiffFileContentsSchema,
54
+ HarnessBindingSchema,
55
+ DeliverySchema,
56
+ PendingDeliverySchema,
57
+ } from "./validate";
58
+ import type { WorkingTreeDiff } from "./working-tree";
59
+ import { DAEMON_VERSION } from "./version";
60
+
61
+ export type { EventFrame } from "./protocol";
11
62
 
12
63
  export interface ConnectOptions {
13
64
  home?: string;
14
65
  /** Spawn the daemon when the socket is not alive. */
15
66
  autostart?: boolean;
67
+ /** Capability role for this connection; a review-side agent connects capped. Defaults to owner. */
68
+ role?: DaemonRole;
69
+ /** The author a non-owner connection acts as; its comments, removals, and name are bound to it. */
70
+ author?: string;
16
71
  }
17
72
 
18
- type Pending = { resolve: (v: unknown) => void; reject: (e: Error) => void };
73
+ type PendingRequest = {
74
+ resolve: (value: Response["result"]) => void;
75
+ reject: (error: Error) => void;
76
+ };
77
+
78
+ const EmptyResultSchema = v.object({});
79
+ // version is optional: a daemon from before the handshake carried one reads as
80
+ // undefined, which never equals this build - so it is treated as stale and replaced
81
+ const PingResultSchema = v.object({ pid: v.number(), version: v.optional(v.string()) });
82
+ const RefreshDiffResultSchema = v.object({ changed: v.boolean() });
83
+ const HerdrThreadSurfaceResultSchema = v.nullable(
84
+ v.object({
85
+ tabId: v.string(),
86
+ paneId: v.string(),
87
+ mode: v.optional(v.picklist(["tab", "pane"])),
88
+ }),
89
+ );
90
+ const GhosttyThreadSurfaceResultSchema = v.nullable(v.object({ terminalId: v.string() }));
91
+
92
+ /**
93
+ * The session primitives the review controller drives. DaemonClient is the local
94
+ * implementation (unix socket); the sharing gateway supplies an in-memory,
95
+ * blob-backed one. Depending on this interface - not DaemonClient - is what
96
+ * lets the same <App> render a local session or a decrypted share unchanged.
97
+ */
98
+ export interface ThreadClient {
99
+ onEvent(listener: (event: EventFrame) => void): () => void;
100
+ subscribe(): Promise<void>;
101
+ sessionGet(id: string): Promise<Thread>;
102
+ sessionList(filter?: { status?: "pending" | "resolved" }): Promise<Thread[]>;
103
+ /** Add a comment; the primary annotate method. `sessionAnnotate` is the retained alias. */
104
+ sessionComment(
105
+ id: string,
106
+ annotation: Omit<Annotation, "createdAt">,
107
+ authorName?: string,
108
+ ): Promise<Thread>;
109
+ sessionAnnotate(
110
+ id: string,
111
+ annotation: Omit<Annotation, "createdAt">,
112
+ authorName?: string,
113
+ ): Promise<Thread>;
114
+ /** Remove a comment; a non-owner connection removes only the comments of the author it is bound to. */
115
+ sessionRemoveAnnotation(id: string, annotationId: string): Promise<Thread>;
116
+ sessionSetWorkingCopy(id: string, workingCopy: string | undefined): Promise<Thread>;
117
+ /** Cut the `blockIndex`-th block of the working copy. */
118
+ sessionCutBlock(id: string, blockIndex: number): Promise<Thread>;
119
+ /** Re-insert the `baseBlockIndex`-th block of the submitted revision before `line` (default: the end). */
120
+ sessionRestoreBlock(id: string, baseBlockIndex: number, line?: number): Promise<Thread>;
121
+ /** Replace a diff review's reject decisions; the working copy follows. */
122
+ sessionCurate(id: string, rejections: HunkRejection[]): Promise<Thread>;
123
+ /** Replace the private-share allowlist of GitHub logins; presence marks the share private. */
124
+ sessionSetAccess(id: string, githubLogins: string[]): Promise<Thread>;
125
+ sessionSetViewed(id: string, viewedPaths: string[]): Promise<Thread>;
126
+ /** Rename a session's display title; an empty title restores the derived default. */
127
+ sessionSetTitle(id: string, title: string): Promise<Thread>;
128
+ /** Tracked, repo-relative file paths for the session's workspace; a client with no local repo (a share) omits it. */
129
+ projectFiles?(sessionId: string): Promise<string[]>;
130
+ /** UTF-8 contents of a repo-relative file, or null when it cannot be read safely; omitted by a client with no local repo. */
131
+ fileContents?(sessionId: string, path: string): Promise<string | null>;
132
+ /** Tracked, repo-relative paths for the git repo containing `cwd`, for the no-session welcome shell. */
133
+ repoFiles?(cwd: string): Promise<string[]>;
134
+ /** UTF-8 contents of a repo-relative file in `cwd`'s repo, or null when unreadable. */
135
+ repoFileContents?(cwd: string, path: string): Promise<string | null>;
136
+ /** Changed files (path plus git status) in the working tree at `cwd`. */
137
+ repoChanges?(cwd: string): Promise<{ path: string; status: DiffFileStatus }[]>;
138
+ /** The live working-tree diff (patch plus per-file contents) at `cwd`. */
139
+ repoDiff?(cwd: string): Promise<WorkingTreeDiff>;
140
+ /** Find-or-create the per-repo workbench thread for `cwd`, so a bare launch's first comment persists. */
141
+ sessionWorkbench?(cwd: string): Promise<Thread>;
142
+ /** Move a branch's tip (the current one, or `branch` after switching to it) back to an entry on its path; a summary records the abandoned segment. */
143
+ sessionNavigate(id: string, entryId: string, summary?: string, branch?: string): Promise<Thread>;
144
+ /** Start a branch at the current tip and switch to it. */
145
+ sessionBranch(id: string, name: string): Promise<Thread>;
146
+ sessionSwitch(id: string, branch: string): Promise<Thread>;
147
+ /** Name the current tip as a checkpoint. */
148
+ sessionLabel(id: string, label: string): Promise<Thread>;
149
+ /** Copy the current path into a new session; returns the fork. */
150
+ sessionFork(id: string): Promise<Thread>;
151
+ sessionSetShareId(id: string, shareId: string): Promise<Thread>;
152
+ sessionSetShares(id: string, shares: ShareLink[]): Promise<Thread>;
153
+ sessionMergeShared(id: string, incoming: SharedMerge): Promise<Thread>;
154
+ sessionDelete(id: string): Promise<void>;
155
+ /** Record the caller's own identity name (collaborator self-naming on a share). */
156
+ sessionSetSelfName(id: string, name: string): Promise<Thread>;
157
+ sessionSendMessage(
158
+ id: string,
159
+ outcome: MessageOutcome,
160
+ summary: string,
161
+ actionBodies?: Record<string, string>,
162
+ ): Promise<Thread>;
163
+ harnessBind?(
164
+ threadId: string,
165
+ harness: string,
166
+ harnessSessionId: string,
167
+ ): Promise<HarnessBinding>;
168
+ harnessGetBinding?(bindingId: string): Promise<HarnessBinding>;
169
+ harnessBindingsForSession?(harness: string, harnessSessionId: string): Promise<HarnessBinding[]>;
170
+ harnessConsumeApprovedRetry?(
171
+ bindingId: string,
172
+ messageId: string,
173
+ content: string,
174
+ ): Promise<boolean>;
175
+ deliveryPending?(bindingId: string): Promise<PendingDelivery[]>;
176
+ deliveryAcknowledge?(deliveryId: string): Promise<Delivery>;
177
+ close(): void;
178
+ }
19
179
 
20
- export class DaemonClient {
21
- private socket: Awaited<ReturnType<typeof Bun.connect>> | null = null;
22
- private pending = new Map<number, Pending>();
180
+ /** What a connection says about itself: its role, the owner token when it claims ownership, the author it acts as otherwise. */
181
+ interface HelloParams {
182
+ role: DaemonRole;
183
+ token?: string;
184
+ author?: string;
185
+ }
186
+
187
+ /** The token as the daemon writes it: 32 random bytes in hex. */
188
+ const OwnerTokenSchema = v.pipe(v.string(), v.trim(), v.regex(/^[0-9a-f]{64}$/));
189
+
190
+ /** The owner token in `home`, or undefined when the daemon there never wrote one. */
191
+ function readOwnerToken(home: string): string | undefined {
192
+ const path = ownerTokenPath(home);
193
+
194
+ if (!existsSync(path)) return undefined;
195
+ const parsed = v.safeParse(OwnerTokenSchema, readFileSync(path, "utf8"));
196
+
197
+ if (!parsed.success) {
198
+ throw new DaemonClientError(
199
+ "invalid_owner_token",
200
+ `${path} is not an owner token; restart the daemon to mint a fresh one`,
201
+ );
202
+ }
203
+
204
+ return parsed.output;
205
+ }
206
+
207
+ export class DaemonClient implements ThreadClient {
208
+ private socket: { end(): void } | null = null;
209
+ private writer: BackpressureWriter | null = null;
210
+ private connectionEpoch = 0;
211
+ private pending = new Map<number, PendingRequest>();
212
+ /** The connected daemon's build version and pid, learned from the ping handshake. */
213
+ private daemonVersion: string | undefined;
214
+ private daemonPid: number | undefined;
23
215
  private nextId = 1;
24
- private eventListeners = new Set<(e: EventFrame) => void>();
216
+ private eventListeners = new Set<(event: EventFrame) => void>();
217
+ private disconnectListeners = new Set<() => void>();
25
218
  private closed = false;
219
+ private role: DaemonRole = "owner";
220
+ private author: string | undefined;
221
+ private home = cueloopHome();
26
222
 
27
- static async connect(opts: ConnectOptions = {}): Promise<DaemonClient> {
28
- const home = opts.home ?? cueloopHome();
223
+ static async connect(options: ConnectOptions = {}): Promise<DaemonClient> {
224
+ const home = options.home ?? cueloopHome();
29
225
  const path = socketPath(home);
30
226
  const client = new DaemonClient();
227
+
228
+ client.role = options.role ?? "owner";
229
+ client.author = options.author;
230
+ client.home = home;
31
231
  try {
32
232
  await client.dial(path);
33
- return client;
233
+ // A daemon from an earlier build lingers after an upgrade; talking to it
234
+ // means new client, old behaviour. The owner replaces it so an upgrade
235
+ // never needs a manual restart; without autostart there is nothing to
236
+ // replace it with, so the caller hears exactly why.
237
+ if (client.daemonVersion === DAEMON_VERSION) return client;
238
+ if (!options.autostart) {
239
+ client.close();
240
+ throw new DaemonClientError(
241
+ "version_mismatch",
242
+ `daemon is version ${client.daemonVersion ?? "unknown"}, but this client is ${DAEMON_VERSION}; restart the daemon`,
243
+ );
244
+ }
245
+ await client.stopStaleDaemon(path);
34
246
  } catch (err) {
35
- if (!opts.autostart) throw err;
247
+ // a live daemon that refused the handshake is not a dead socket: the
248
+ // caller hears why instead of the client replacing a running daemon
249
+ if (!options.autostart || err instanceof DaemonClientError) throw err;
250
+ }
251
+ // Socket dead, absent, or just-replaced: let the new daemon own socket cleanup.
252
+ return client.attachFreshDaemon(home, path);
253
+ }
254
+
255
+ /**
256
+ * Tear down a daemon from an earlier build so a fresh one can bind: ask it to
257
+ * shut down (owner-gated) or, failing that, signal its pid, then wait for it to
258
+ * release the socket. Best-effort - the next daemon reclaims stale socket
259
+ * and lock files after it takes ownership.
260
+ */
261
+ private async stopStaleDaemon(path: string): Promise<void> {
262
+ const pid = this.daemonPid;
263
+
264
+ try {
265
+ await this.request("daemon.shutdown", {}, EmptyResultSchema, 2_000);
266
+ } catch {
267
+ if (pid !== undefined) {
268
+ try {
269
+ process.kill(pid);
270
+ } catch {}
271
+ }
36
272
  }
37
- // Socket dead or absent: clean a stale file and spawn the daemon detached.
38
- if (existsSync(path)) rmSync(path, { force: true });
39
- spawnDaemon(home);
273
+ this.socket?.end();
274
+ this.resetConnection();
275
+ // the old daemon removes its socket in stop(); wait so the new one binds cleanly
276
+ const deadline = Date.now() + 5_000;
277
+
278
+ while (Date.now() < deadline && existsSync(path)) await sleep(50);
279
+ }
280
+
281
+ /** Reset per-connection state so a fresh dial() can reuse this client instance. */
282
+ private resetConnection(): void {
283
+ this.connectionEpoch += 1;
284
+ this.socket = null;
285
+ this.writer = null;
286
+ this.closed = false;
287
+ for (const pendingRequest of this.pending.values())
288
+ pendingRequest.reject(new Error("daemon connection replaced"));
289
+ this.pending.clear();
290
+ }
291
+
292
+ /** Spawn a detached daemon and dial the lock owner until it answers. */
293
+ private async attachFreshDaemon(home: string, path: string): Promise<DaemonClient> {
294
+ const startupLogPath = spawnDaemon(home);
40
295
  // Generous: a cold or loaded machine pays for a runtime start before the
41
296
  // socket exists, and giving up early looks to callers like a broken daemon.
42
297
  const deadline = Date.now() + Number(process.env.CUELOOP_START_TIMEOUT_MS ?? 30_000);
43
- let lastErr: unknown;
44
- while (Date.now() < deadline) {
45
- try {
46
- await client.dial(path);
47
- return client;
48
- } catch (err) {
49
- lastErr = err;
50
- await Bun.sleep(50);
298
+ let lastError: unknown;
299
+
300
+ try {
301
+ while (Date.now() < deadline) {
302
+ try {
303
+ await this.dial(path);
304
+ if (this.daemonVersion !== DAEMON_VERSION) {
305
+ this.close();
306
+ if (typeof Bun === "undefined") {
307
+ throw new DaemonClientError(
308
+ "version_mismatch",
309
+ `installed cueloop is ${this.daemonVersion ?? "unknown"}, but this adapter is ${DAEMON_VERSION}; run cueloop update`,
310
+ );
311
+ }
312
+
313
+ throw new Error("daemon autostarted an older build");
314
+ }
315
+
316
+ return this;
317
+ } catch (err) {
318
+ if (err instanceof DaemonClientError) throw err;
319
+ this.socket?.end();
320
+ this.resetConnection();
321
+ lastError = err;
322
+ await sleep(50);
323
+ }
51
324
  }
325
+ const output = readFileSync(startupLogPath, "utf8").trim();
326
+ const detail = output ? `\ndaemon startup output:\n${output.slice(-4_096)}` : "";
327
+
328
+ throw new Error(`daemon did not come up at ${path}: ${String(lastError)}${detail}`);
329
+ } finally {
330
+ rmSync(startupLogPath, { force: true });
52
331
  }
53
- throw new Error(`daemon did not come up at ${path}: ${String(lastErr)}`);
54
332
  }
55
333
 
56
334
  private async dial(path: string): Promise<void> {
57
335
  const buffer = new LineBuffer();
58
- const self = this;
59
- this.socket = await Bun.connect({
60
- unix: path,
61
- socket: {
62
- data(_socket, data) {
63
- buffer.push(data.toString(), (line) => self.handleFrame(line));
336
+ const epoch = ++this.connectionEpoch;
337
+
338
+ const close = () => {
339
+ if (this.connectionEpoch !== epoch) return;
340
+ this.closed = true;
341
+ for (const pendingRequest of this.pending.values())
342
+ pendingRequest.reject(new Error("daemon connection closed"));
343
+ this.pending.clear();
344
+ for (const listener of this.disconnectListeners) listener();
345
+ };
346
+
347
+ if (typeof Bun !== "undefined") {
348
+ const socket = await Bun.connect({
349
+ unix: path,
350
+ socket: {
351
+ data: (_socket, data) => {
352
+ buffer.push(data.toString(), (line) => this.routeInboundFrame(line));
353
+ },
354
+ drain: () => this.writer?.drain(),
355
+ close,
356
+ error() {},
64
357
  },
65
- close() {
66
- self.closed = true;
67
- for (const p of self.pending.values()) p.reject(new Error("daemon connection closed"));
68
- self.pending.clear();
358
+ });
359
+
360
+ this.socket = socket;
361
+ this.writer = new BackpressureWriter(socket);
362
+ } else {
363
+ const socket = createConnection(path);
364
+
365
+ await new Promise<void>((resolve, reject) => {
366
+ socket.once("connect", resolve);
367
+ socket.once("error", reject);
368
+ });
369
+ socket.on("data", (data) => {
370
+ buffer.push(data.toString(), (line) => this.routeInboundFrame(line));
371
+ });
372
+ socket.on("close", close);
373
+ socket.on("error", () => {});
374
+ this.socket = socket;
375
+ // Node queues the complete Buffer internally when write returns false.
376
+ this.writer = new BackpressureWriter({
377
+ write(data) {
378
+ socket.write(data);
379
+
380
+ return data.length;
69
381
  },
70
- error() {},
71
- },
72
- });
382
+ });
383
+ }
73
384
  // Verify liveness: a dead socket file accepts connects on some platforms
74
- // only to fail later, so a ping is the actual handshake.
75
- await this.request("daemon.ping", {}, 2_000);
385
+ // only to fail later, so a ping is the actual handshake. It also carries the
386
+ // daemon's build version and pid, so connect() can replace a stale daemon.
387
+ const pong = await this.request("daemon.ping", {}, PingResultSchema, 2_000);
388
+
389
+ this.daemonVersion = pong.version;
390
+ this.daemonPid = pong.pid;
391
+ // Every connection starts as a collaborator; the owner proves itself with
392
+ // the token the daemon wrote into the home it serves, which only the home's
393
+ // user can read. A capped role just names itself.
394
+ await this.request("daemon.hello", this.helloParams(), EmptyResultSchema, 2_000);
395
+ }
396
+
397
+ private helloParams(): HelloParams {
398
+ if (this.role !== "owner") {
399
+ return this.author === undefined
400
+ ? { role: this.role }
401
+ : { role: this.role, author: this.author };
402
+ }
403
+ const token = readOwnerToken(this.home);
404
+
405
+ // a daemon from before owner tokens has no file; it still knows the bare hello
406
+ return token === undefined ? { role: "owner" } : { role: "owner", token };
76
407
  }
77
408
 
78
- onEvent(listener: (e: EventFrame) => void): () => void {
409
+ onEvent(listener: (event: EventFrame) => void): () => void {
79
410
  this.eventListeners.add(listener);
411
+
80
412
  return () => this.eventListeners.delete(listener);
81
413
  }
82
414
 
83
- private handleFrame(line: string): void {
84
- let frame: Response | EventFrame;
415
+ /** Notify an adapter when its daemon socket closes so it can reconnect and replay Messages. */
416
+ onDisconnect(listener: () => void): () => void {
417
+ this.disconnectListeners.add(listener);
418
+
419
+ return () => this.disconnectListeners.delete(listener);
420
+ }
421
+
422
+ private routeInboundFrame(line: string): void {
423
+ let frame;
424
+
85
425
  try {
86
- frame = JSON.parse(line) as Response | EventFrame;
426
+ frame = parseInboundFrame(line);
87
427
  } catch {
88
428
  return;
89
429
  }
90
430
  if ("event" in frame) {
91
- for (const l of this.eventListeners) l(frame);
431
+ for (const listener of this.eventListeners) listener(frame);
432
+
92
433
  return;
93
434
  }
94
- const p = this.pending.get(frame.id);
95
- if (!p) return;
435
+ const pendingRequest = this.pending.get(frame.id);
436
+
437
+ if (!pendingRequest) return;
96
438
  this.pending.delete(frame.id);
97
- if (frame.error) p.reject(new DaemonClientError(frame.error.code, frame.error.message));
98
- else p.resolve(frame.result);
439
+ if (frame.error)
440
+ pendingRequest.reject(new DaemonClientError(frame.error.code, frame.error.message));
441
+ else pendingRequest.resolve(frame.result);
99
442
  }
100
443
 
101
- request<T = unknown>(method: string, params: unknown, timeoutMs = 30_000): Promise<T> {
444
+ request<TOutput>(
445
+ method: string,
446
+ params: Request["params"],
447
+ resultSchema: v.GenericSchema<unknown, TOutput>,
448
+ timeoutMs = 30_000,
449
+ ): Promise<TOutput> {
102
450
  if (this.closed || !this.socket) return Promise.reject(new Error("not connected"));
103
451
  const id = this.nextId++;
104
- return new Promise<T>((resolve, reject) => {
452
+
453
+ return new Promise<TOutput>((resolve, reject) => {
105
454
  const timer = setTimeout(() => {
106
455
  this.pending.delete(id);
107
456
  reject(new Error(`request ${method} timed out`));
108
457
  }, timeoutMs);
458
+
109
459
  this.pending.set(id, {
110
- resolve: (v) => {
460
+ resolve: (value) => {
111
461
  clearTimeout(timer);
112
- resolve(v as T);
462
+ resolve(v.parse(resultSchema, value));
113
463
  },
114
- reject: (e) => {
464
+ reject: (error) => {
115
465
  clearTimeout(timer);
116
- reject(e);
466
+ reject(error);
117
467
  },
118
468
  });
119
- this.socket!.write(JSON.stringify({ id, method, params }) + "\n");
469
+ this.writer!.write(JSON.stringify({ id, method, params }) + "\n");
120
470
  });
121
471
  }
122
472
 
@@ -125,43 +475,230 @@ export class DaemonClient {
125
475
  this.socket?.end();
126
476
  }
127
477
 
128
- // ── typed verbs ─────────────────────────────
478
+ // ── typed primitives ─────────────────────────────
129
479
  ping(): Promise<{ pid: number }> {
130
- return this.request("daemon.ping", {});
480
+ return this.request("daemon.ping", {}, PingResultSchema);
131
481
  }
132
482
  subscribe(): Promise<void> {
133
- return this.request("events.subscribe", {});
483
+ return this.request("events.subscribe", {}, EmptyResultSchema).then(() => undefined);
134
484
  }
135
- sessionCreate(workspace: WorkspaceKey, artifact: Artifact): Promise<ReviewSession> {
136
- return this.request("session.create", { workspace, artifact });
485
+ sessionCreate(workspace: WorkspaceKey, artifact: Artifact): Promise<Thread> {
486
+ return this.request("session.create", { workspace, artifact }, ThreadRecordSchema);
137
487
  }
138
- sessionGet(id: string): Promise<ReviewSession> {
139
- return this.request("session.get", { id });
488
+ sessionGet(id: string): Promise<Thread> {
489
+ return this.request("session.get", { id }, ThreadRecordSchema);
140
490
  }
141
- sessionList(filter?: { status?: "pending" | "resolved" }): Promise<ReviewSession[]> {
142
- return this.request("session.list", { filter });
491
+ sessionList(filter?: { status?: "pending" | "resolved" }): Promise<Thread[]> {
492
+ return this.request("session.list", { filter }, v.array(ThreadRecordSchema));
143
493
  }
144
494
  /** Long-poll; null = still pending after timeoutMs (re-poll to collect). */
145
- sessionWait(id: string, timeoutMs: number): Promise<ReviewSession | null> {
146
- return this.request("session.wait", { id, timeoutMs }, timeoutMs + 10_000);
495
+ sessionWait(id: string, timeoutMs: number): Promise<Thread | null> {
496
+ return this.request(
497
+ "session.wait",
498
+ { id, timeoutMs },
499
+ v.nullable(ThreadRecordSchema),
500
+ timeoutMs + 10_000,
501
+ );
502
+ }
503
+ sessionComment(
504
+ id: string,
505
+ annotation: Omit<Annotation, "createdAt">,
506
+ authorName?: string,
507
+ ): Promise<Thread> {
508
+ return this.request("session.comment", { id, annotation, authorName }, ThreadRecordSchema);
509
+ }
510
+ sessionAnnotate(
511
+ id: string,
512
+ annotation: Omit<Annotation, "createdAt">,
513
+ authorName?: string,
514
+ ): Promise<Thread> {
515
+ return this.request("session.annotate", { id, annotation, authorName }, ThreadRecordSchema);
516
+ }
517
+ sessionRemoveAnnotation(id: string, annotationId: string): Promise<Thread> {
518
+ return this.request("session.removeAnnotation", { id, annotationId }, ThreadRecordSchema);
519
+ }
520
+ /** Register a display name for a participant - a collaborator's or an agent's own, on a share or locally. */
521
+ sessionSetParticipantName(id: string, author: string, name: string): Promise<Thread> {
522
+ return this.request("session.setParticipantName", { id, author, name }, ThreadRecordSchema);
523
+ }
524
+ sessionSetWorkingCopy(id: string, workingCopy: string | undefined): Promise<Thread> {
525
+ return this.request("session.setWorkingCopy", { id, workingCopy }, ThreadRecordSchema);
526
+ }
527
+ sessionCutBlock(id: string, blockIndex: number): Promise<Thread> {
528
+ return this.request("session.cutBlock", { id, blockIndex }, ThreadRecordSchema);
529
+ }
530
+ sessionNavigate(id: string, entryId: string, summary?: string, branch?: string): Promise<Thread> {
531
+ const params: v.InferInput<(typeof Params)["session.navigate"]> = { id, entryId };
532
+
533
+ if (summary !== undefined) params.summary = summary;
534
+ if (branch !== undefined) params.branch = branch;
535
+
536
+ return this.request("session.navigate", params, ThreadRecordSchema);
537
+ }
538
+ sessionBranch(id: string, name: string): Promise<Thread> {
539
+ return this.request("session.branch", { id, name }, ThreadRecordSchema);
540
+ }
541
+ sessionSwitch(id: string, branch: string): Promise<Thread> {
542
+ return this.request("session.switch", { id, branch }, ThreadRecordSchema);
147
543
  }
148
- sessionAnnotate(id: string, annotation: Omit<Annotation, "createdAt">): Promise<ReviewSession> {
149
- return this.request("session.annotate", { id, annotation });
544
+ sessionLabel(id: string, label: string): Promise<Thread> {
545
+ return this.request("session.label", { id, label }, ThreadRecordSchema);
150
546
  }
151
- sessionRemoveAnnotation(id: string, annotationId: string): Promise<ReviewSession> {
152
- return this.request("session.removeAnnotation", { id, annotationId });
547
+ sessionFork(id: string): Promise<Thread> {
548
+ return this.request("session.fork", { id }, ThreadRecordSchema);
153
549
  }
154
- sessionSetWorkingCopy(id: string, workingCopy: string | undefined): Promise<ReviewSession> {
155
- return this.request("session.setWorkingCopy", { id, workingCopy });
550
+ sessionRestoreBlock(id: string, baseBlockIndex: number, line?: number): Promise<Thread> {
551
+ return this.request(
552
+ "session.restoreBlock",
553
+ line === undefined ? { id, baseBlockIndex } : { id, baseBlockIndex, line },
554
+ ThreadRecordSchema,
555
+ );
156
556
  }
157
- sessionResolve(id: string, verdictKind: VerdictKind, summary: string): Promise<ReviewSession> {
158
- return this.request("session.resolve", { id, verdictKind, summary });
557
+ sessionCurate(id: string, rejections: HunkRejection[]): Promise<Thread> {
558
+ return this.request("session.curate", { id, rejections }, ThreadRecordSchema);
559
+ }
560
+ sessionSetAccess(id: string, githubLogins: string[]): Promise<Thread> {
561
+ return this.request("session.setAccess", { id, githubLogins }, ThreadRecordSchema);
562
+ }
563
+ sessionSetViewed(id: string, viewedPaths: string[]): Promise<Thread> {
564
+ return this.request("session.setViewed", { id, viewedPaths }, ThreadRecordSchema);
565
+ }
566
+ sessionSetTitle(id: string, title: string): Promise<Thread> {
567
+ return this.request("session.setTitle", { id, title }, ThreadRecordSchema);
568
+ }
569
+ projectFiles(sessionId: string): Promise<string[]> {
570
+ return this.request("session.projectFiles", { id: sessionId }, v.array(v.string()));
571
+ }
572
+ fileContents(sessionId: string, path: string): Promise<string | null> {
573
+ return this.request("session.fileContents", { id: sessionId, path }, v.nullable(v.string()));
574
+ }
575
+ repoFiles(cwd: string): Promise<string[]> {
576
+ return this.request("repo.files", { cwd }, v.array(v.string()));
577
+ }
578
+ repoFileContents(cwd: string, path: string): Promise<string | null> {
579
+ return this.request("repo.fileContents", { cwd, path }, v.nullable(v.string()));
580
+ }
581
+ repoChanges(cwd: string): Promise<{ path: string; status: DiffFileStatus }[]> {
582
+ return this.request(
583
+ "repo.changes",
584
+ { cwd },
585
+ v.array(v.object({ path: v.string(), status: v.picklist(["added", "modified", "deleted"]) })),
586
+ );
587
+ }
588
+ repoDiff(cwd: string): Promise<WorkingTreeDiff> {
589
+ return this.request(
590
+ "repo.diff",
591
+ { cwd },
592
+ v.object({ patch: v.string(), files: v.array(DiffFileContentsSchema) }),
593
+ );
594
+ }
595
+ sessionWorkbench(cwd: string): Promise<Thread> {
596
+ return this.request("session.workbench", { cwd }, ThreadRecordSchema);
597
+ }
598
+ /** Re-capture a diff session's working tree; changed=true when the patch moved and an event fired. */
599
+ sessionRefreshDiff(id: string): Promise<{ changed: boolean }> {
600
+ return this.request("session.refreshDiff", { id }, RefreshDiffResultSchema);
601
+ }
602
+ sessionSetShareId(id: string, shareId: string): Promise<Thread> {
603
+ return this.request("session.setShareId", { id, shareId }, ThreadRecordSchema);
604
+ }
605
+
606
+ sessionSetShares(id: string, shares: ShareLink[]): Promise<Thread> {
607
+ return this.request("session.setShares", { id, shares }, ThreadRecordSchema);
159
608
  }
160
- sessionSubmitRevision(id: string, content: string): Promise<ReviewSession> {
161
- return this.request("session.submitRevision", { id, content });
609
+ sessionMergeShared(id: string, incoming: SharedMerge): Promise<Thread> {
610
+ return this.request("session.mergeShared", { id, ...incoming }, ThreadRecordSchema);
611
+ }
612
+ sessionDelete(id: string): Promise<void> {
613
+ return this.request("session.delete", { id }, EmptyResultSchema).then(() => undefined);
614
+ }
615
+ /** Local sessions have no collaborator self-name; the share client owns this. */
616
+ sessionSetSelfName(id: string, _name: string): Promise<Thread> {
617
+ return this.sessionGet(id);
618
+ }
619
+ sessionSendMessage(
620
+ id: string,
621
+ outcome: MessageOutcome,
622
+ summary: string,
623
+ actionBodies?: Record<string, string>,
624
+ ): Promise<Thread> {
625
+ return this.request(
626
+ "session.sendMessage",
627
+ { id, outcome, summary, actionBodies },
628
+ ThreadRecordSchema,
629
+ );
630
+ }
631
+ harnessBind(
632
+ threadId: string,
633
+ harness: string,
634
+ harnessSessionId: string,
635
+ ): Promise<HarnessBinding> {
636
+ return this.request(
637
+ "harness.bind",
638
+ { threadId, harness, harnessSessionId },
639
+ HarnessBindingSchema,
640
+ );
641
+ }
642
+ harnessGetBinding(bindingId: string): Promise<HarnessBinding> {
643
+ return this.request("harness.getBinding", { bindingId }, HarnessBindingSchema);
644
+ }
645
+ harnessBindingsForSession(harness: string, harnessSessionId: string): Promise<HarnessBinding[]> {
646
+ return this.request(
647
+ "harness.bindingsForSession",
648
+ { harness, harnessSessionId },
649
+ v.array(HarnessBindingSchema),
650
+ );
651
+ }
652
+ harnessConsumeApprovedRetry(
653
+ bindingId: string,
654
+ messageId: string,
655
+ content: string,
656
+ ): Promise<boolean> {
657
+ return this.request(
658
+ "harness.consumeApprovedRetry",
659
+ { bindingId, messageId, content },
660
+ v.boolean(),
661
+ );
662
+ }
663
+ deliveryPending(bindingId: string): Promise<PendingDelivery[]> {
664
+ return this.request("delivery.pending", { bindingId }, v.array(PendingDeliverySchema));
665
+ }
666
+ deliveryAcknowledge(deliveryId: string): Promise<Delivery> {
667
+ return this.request("delivery.acknowledge", { deliveryId }, DeliverySchema);
668
+ }
669
+ sessionSubmitRevision(
670
+ id: string,
671
+ content: string,
672
+ addressedAnnotationIds: string[] = [],
673
+ files?: DiffFileContents[],
674
+ ): Promise<Thread> {
675
+ return this.request(
676
+ "session.submitRevision",
677
+ { id, content, addressedAnnotationIds, files },
678
+ ThreadRecordSchema,
679
+ );
680
+ }
681
+ /** Read Herdr's local Thread surface handle, outside the ThreadClient contract. */
682
+ herdrGetThreadSurface(id: string): Promise<HerdrThreadSurfaceHandle | null> {
683
+ return this.request("herdr.getThreadSurface", { id }, HerdrThreadSurfaceResultSchema);
684
+ }
685
+ async herdrSetThreadSurface(id: string, handle: HerdrThreadSurfaceHandle): Promise<void> {
686
+ await this.request("herdr.setThreadSurface", { id, ...handle }, EmptyResultSchema);
687
+ }
688
+ ghosttyGetThreadSurface(id: string): Promise<GhosttyThreadSurfaceHandle | null> {
689
+ return this.request("ghostty.getThreadSurface", { id }, GhosttyThreadSurfaceResultSchema);
690
+ }
691
+ async ghosttySetThreadSurface(id: string, handle: GhosttyThreadSurfaceHandle): Promise<void> {
692
+ await this.request("ghostty.setThreadSurface", { id, ...handle }, EmptyResultSchema);
693
+ }
694
+ ghosttyClaimThreadSurface(id: string): Promise<boolean> {
695
+ return this.request("ghostty.claimThreadSurface", { id }, v.boolean());
696
+ }
697
+ async ghosttyReleaseThreadSurface(id: string): Promise<void> {
698
+ await this.request("ghostty.releaseThreadSurface", { id }, EmptyResultSchema);
162
699
  }
163
700
  shutdown(): Promise<void> {
164
- return this.request("daemon.shutdown", {});
701
+ return this.request("daemon.shutdown", {}, EmptyResultSchema).then(() => undefined);
165
702
  }
166
703
  }
167
704
 
@@ -174,10 +711,56 @@ export class DaemonClientError extends Error {
174
711
  }
175
712
  }
176
713
 
177
- function spawnDaemon(home: string): void {
178
- const entry = new URL("./main.ts", import.meta.url).pathname;
179
- Bun.spawn([process.execPath, "run", entry], {
180
- env: { ...process.env, CUELOOP_HOME: home },
181
- stdio: ["ignore", "ignore", "ignore"],
182
- }).unref();
714
+ // A compiled binary re-execs `cueloop daemon --autostart` (idle-exits like main.ts,
715
+ // unlike the never-exiting foreground daemon); from source, bun runs main.ts. In
716
+ // dev (CUELOOP_DEV_WATCH=1, source only) it runs under --watch so daemon-code edits
717
+ // reload the daemon without a manual restart - the version handshake only catches
718
+ // release upgrades, not same-version source changes.
719
+ export function daemonSpawnCommand(
720
+ execPath: string,
721
+ moduleUrl: string,
722
+ devWatch = process.env.CUELOOP_DEV_WATCH === "1",
723
+ ): string[] {
724
+ const compiled =
725
+ moduleUrl.includes("$bunfs") || moduleUrl.includes("~BUN") || moduleUrl.includes("%7EBUN");
726
+
727
+ if (compiled) return [execPath, "daemon", "--autostart"];
728
+ const mainPath = new URL("./main.ts", moduleUrl).pathname;
729
+
730
+ return devWatch ? [execPath, "--watch", "run", mainPath] : [execPath, "run", mainPath];
731
+ }
732
+
733
+ function spawnDaemon(home: string): string {
734
+ mkdirSync(home, { recursive: true, mode: 0o700 });
735
+ const startupLogPath = join(
736
+ home,
737
+ `daemon-startup-${process.pid}-${randomBytes(6).toString("hex")}.log`,
738
+ );
739
+ const logFd = openSync(startupLogPath, "wx", 0o600);
740
+
741
+ try {
742
+ if (typeof Bun === "undefined") {
743
+ const child = spawn(process.env.CUELOOP_EXECUTABLE ?? "cueloop", ["daemon", "--autostart"], {
744
+ env: { ...process.env, CUELOOP_HOME: home },
745
+ stdio: ["ignore", logFd, logFd],
746
+ detached: true,
747
+ });
748
+
749
+ child.on("error", (error) => appendFileSync(startupLogPath, `${String(error)}\n`));
750
+ child.unref();
751
+ } else {
752
+ Bun.spawn(daemonSpawnCommand(process.execPath, import.meta.url), {
753
+ env: { ...process.env, CUELOOP_HOME: home },
754
+ stdio: ["ignore", logFd, logFd],
755
+ }).unref();
756
+ }
757
+ } finally {
758
+ closeSync(logFd);
759
+ }
760
+
761
+ return startupLogPath;
762
+ }
763
+
764
+ function sleep(durationMs: number): Promise<void> {
765
+ return new Promise((resolve) => setTimeout(resolve, durationMs));
183
766
  }