@cueloop/daemon 0.1.0-alpha.11 → 0.1.0-alpha.110

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 (85) hide show
  1. package/README.md +7 -0
  2. package/SDK.md +102 -0
  3. package/package.json +44 -22
  4. package/src/agent-tools.ts +104 -0
  5. package/src/agent-turn.test.ts +24 -0
  6. package/src/agent-turn.ts +34 -0
  7. package/src/api.test.ts +1081 -65
  8. package/src/api.ts +1483 -90
  9. package/src/capabilities.test.ts +57 -0
  10. package/src/capabilities.ts +95 -0
  11. package/src/client-errors.ts +24 -0
  12. package/src/client-reliability.test.ts +191 -0
  13. package/src/client.test.ts +37 -0
  14. package/src/client.ts +844 -95
  15. package/src/curate.ts +111 -0
  16. package/src/daemon-sdk-effect.ts +113 -0
  17. package/src/daemon-sdk.test.ts +306 -0
  18. package/src/daemon-sdk.ts +405 -0
  19. package/src/daemon-version.test.ts +142 -0
  20. package/src/diff-hot-reload.test.ts +423 -0
  21. package/src/diff-watcher.test.ts +165 -0
  22. package/src/diff-watcher.ts +363 -0
  23. package/src/examples/daemon-sdk.ts +57 -0
  24. package/src/gh.test.ts +59 -0
  25. package/src/gh.ts +78 -0
  26. package/src/ghostty-thread-surface-store.test.ts +49 -0
  27. package/src/ghostty-thread-surface-store.ts +104 -0
  28. package/src/ghostty-thread-surface.test.ts +400 -0
  29. package/src/ghostty-thread-surface.ts +273 -0
  30. package/src/harness-delivery.test.ts +269 -0
  31. package/src/harness-diagnostics.test.ts +26 -0
  32. package/src/harness-diagnostics.ts +31 -0
  33. package/src/harness-handoff.test.ts +725 -0
  34. package/src/harness-handoff.ts +27 -0
  35. package/src/harness-state-store.test.ts +93 -0
  36. package/src/harness-state-store.ts +218 -0
  37. package/src/herdr-split.test.ts +106 -0
  38. package/src/herdr-split.ts +90 -0
  39. package/src/herdr-thread-surface-store.test.ts +81 -0
  40. package/src/herdr-thread-surface-store.ts +66 -0
  41. package/src/herdr-thread-surface.test.ts +465 -0
  42. package/src/herdr-thread-surface.ts +392 -0
  43. package/src/index.ts +8 -9
  44. package/src/interruptible-wait.test.ts +127 -0
  45. package/src/interruptible-wait.ts +69 -0
  46. package/src/jj-working-tree.ts +140 -0
  47. package/src/main.ts +5 -1
  48. package/src/operation-receipts.test.ts +111 -0
  49. package/src/operation-receipts.ts +104 -0
  50. package/src/paths.ts +49 -0
  51. package/src/pr-poller.test.ts +102 -0
  52. package/src/pr-poller.ts +80 -0
  53. package/src/project-files.test.ts +134 -0
  54. package/src/project-files.ts +72 -0
  55. package/src/protocol.ts +82 -7
  56. package/src/retention.test.ts +191 -0
  57. package/src/retention.ts +131 -0
  58. package/src/sdk-identities.ts +35 -0
  59. package/src/server.test.ts +502 -42
  60. package/src/server.ts +660 -88
  61. package/src/share-blob.test.ts +142 -0
  62. package/src/share-blob.ts +57 -0
  63. package/src/shared-agent-protocol.ts +30 -0
  64. package/src/single-instance.test.ts +165 -13
  65. package/src/store.conformance.test.ts +41 -0
  66. package/src/store.jsonl.test.ts +173 -0
  67. package/src/store.ts +278 -34
  68. package/src/testing/store-conformance.ts +192 -0
  69. package/src/thread-agent-validation.ts +141 -0
  70. package/src/thread-agent.test.ts +732 -0
  71. package/src/thread-agent.ts +1171 -0
  72. package/src/thread-review.test.ts +487 -0
  73. package/src/thread-review.ts +394 -0
  74. package/src/thread-subscription.test.ts +177 -0
  75. package/src/thread-subscription.ts +138 -0
  76. package/src/thread-surface-config.test.ts +63 -0
  77. package/src/thread-surface-config.ts +61 -0
  78. package/src/validate.test.ts +290 -37
  79. package/src/validate.ts +427 -33
  80. package/src/vcs-source.test.ts +180 -0
  81. package/src/vcs-source.ts +235 -0
  82. package/src/version.ts +6 -0
  83. package/src/working-tree.ts +154 -0
  84. package/src/review.test.ts +0 -167
  85. package/src/review.ts +0 -174
package/src/client.ts CHANGED
@@ -1,171 +1,868 @@
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
+ TextCut,
35
+ } from "@cueloop/schema";
36
+ import {
37
+ BackpressureWriter,
38
+ LineBuffer,
39
+ parseInboundFrame,
40
+ type EventFrame,
41
+ type Request,
42
+ type Response,
43
+ } from "./protocol";
44
+ import type { DaemonRole } from "./capabilities";
45
+ import type { HerdrThreadSurfaceHandle } from "./herdr-thread-surface-store";
46
+ import type { GhosttyThreadSurfaceHandle } from "./ghostty-thread-surface-store";
47
+ import type { SharedMerge } from "./api";
48
+
49
+ export type { SharedMerge } from "./api";
50
+ import { cueloopHome, ownerTokenPath, socketPath } from "./paths";
51
+ import {
52
+ Params,
53
+ ThreadRecordSchema,
54
+ DiffFileContentsSchema,
55
+ HarnessBindingSchema,
56
+ DeliverySchema,
57
+ PendingDeliverySchema,
58
+ } from "./validate";
59
+ import type { WorkingTreeDiff } from "./working-tree";
60
+ import { DaemonTransportError, type DaemonRequestOptions } from "./client-errors";
61
+ export { DaemonTransportError, type DaemonRequestOptions } from "./client-errors";
62
+ import { DAEMON_VERSION } from "./version";
63
+ import { ThreadAgentSchema } from "./thread-agent-validation";
64
+ import type { AgentComment, ThreadAgentState, AgentPromptRequest } from "@cueloop/schema";
65
+
66
+ export type { EventFrame } from "./protocol";
11
67
 
12
68
  export interface ConnectOptions {
13
69
  home?: string;
14
- /** Spawn the daemon when the socket is not alive. */
15
70
  autostart?: boolean;
71
+ role?: DaemonRole;
72
+ author?: string;
73
+ }
74
+
75
+ type PendingRequest = {
76
+ resolve: (value: Response["result"]) => void;
77
+ reject: (error: Error) => void;
78
+ };
79
+
80
+ const EmptyResultSchema = v.object({});
81
+ // version is optional: a daemon from before the handshake carried one reads as
82
+ // undefined, which never equals this build.
83
+ const PingResultSchema = v.object({
84
+ pid: v.number(),
85
+ version: v.optional(v.string()),
86
+ agentHarness: v.optional(v.string()),
87
+ });
88
+ const RefreshDiffResultSchema = v.object({ changed: v.boolean() });
89
+ const HerdrThreadSurfaceResultSchema = v.nullable(
90
+ v.object({
91
+ tabId: v.string(),
92
+ paneId: v.string(),
93
+ mode: v.optional(v.picklist(["tab", "pane"])),
94
+ layout: v.optional(v.literal("pair")),
95
+ }),
96
+ );
97
+ const GhosttyThreadSurfaceResultSchema = v.nullable(v.object({ terminalId: v.string() }));
98
+
99
+ /**
100
+ * The session primitives the review controller drives. DaemonClient is the local
101
+ * implementation (unix socket); the sharing gateway supplies an in-memory,
102
+ * blob-backed one. Depending on this interface - not DaemonClient - is what
103
+ * lets the same <App> render a local session or a decrypted share unchanged.
104
+ */
105
+ export interface ThreadClient {
106
+ onEvent(listener: (event: EventFrame) => void): () => void;
107
+ subscribe(): Promise<void>;
108
+ sessionGet(id: string): Promise<Thread>;
109
+ sessionCreate?(workspace: WorkspaceKey, artifact: Artifact): Promise<Thread>;
110
+ sessionList(filter?: { status?: "pending" | "resolved" }): Promise<Thread[]>;
111
+ sessionComment(
112
+ id: string,
113
+ annotation: Omit<Annotation, "createdAt">,
114
+ authorName?: string,
115
+ ): Promise<Thread>;
116
+ sessionAnnotate(
117
+ id: string,
118
+ annotation: Omit<Annotation, "createdAt">,
119
+ authorName?: string,
120
+ ): Promise<Thread>;
121
+ sessionRemoveAnnotation(id: string, annotationId: string): Promise<Thread>;
122
+ sessionSetWorkingCopy(
123
+ id: string,
124
+ workingCopy: string | undefined,
125
+ textCuts?: TextCut[],
126
+ ): Promise<Thread>;
127
+ sessionCutBlock(id: string, blockIndex: number): Promise<Thread>;
128
+ sessionRestoreBlock(id: string, baseBlockIndex: number, line?: number): Promise<Thread>;
129
+ sessionCurate(id: string, rejections: HunkRejection[]): Promise<Thread>;
130
+ sessionSetViewed(id: string, viewedPaths: string[]): Promise<Thread>;
131
+ sessionSetTitle(id: string, title: string): Promise<Thread>;
132
+ agentGet?(id: string): Promise<ThreadAgentState>;
133
+ projectFiles?(sessionId: string): Promise<string[]>;
134
+ fileContents?(sessionId: string, path: string): Promise<string | null>;
135
+ repoFiles?(cwd: string): Promise<string[]>;
136
+ repoFileContents?(cwd: string, path: string): Promise<string | null>;
137
+ repoChanges?(cwd: string): Promise<{ path: string; status: DiffFileStatus }[]>;
138
+ repoDiff?(cwd: string, vcs?: string): Promise<WorkingTreeDiff>;
139
+ sessionRefreshDiff?(id: string): Promise<{ changed: boolean }>;
140
+ sessionWorkbench?(cwd: string): Promise<Thread>;
141
+ sessionNavigate(id: string, entryId: string, summary?: string, branch?: string): Promise<Thread>;
142
+ sessionBranch(id: string, name: string): Promise<Thread>;
143
+ sessionSwitch(id: string, branch: string): Promise<Thread>;
144
+ sessionLabel(id: string, label: string): Promise<Thread>;
145
+ sessionFork(id: string): Promise<Thread>;
146
+ sessionSetShares(id: string, shares: ShareLink[]): Promise<Thread>;
147
+ sessionMergeShared(id: string, incoming: SharedMerge): Promise<Thread>;
148
+ sessionDelete(id: string): Promise<void>;
149
+ sessionSetSelfName(id: string, name: string): Promise<Thread>;
150
+ sessionSendMessage(
151
+ id: string,
152
+ outcome: MessageOutcome,
153
+ summary: string,
154
+ actionBodies?: Record<string, string>,
155
+ ): Promise<Thread>;
156
+ harnessBind?(
157
+ threadId: string,
158
+ harness: string,
159
+ harnessSessionId: string,
160
+ ): Promise<HarnessBinding>;
161
+ harnessGetBinding?(bindingId: string): Promise<HarnessBinding>;
162
+ harnessBindingsForSession?(harness: string, harnessSessionId: string): Promise<HarnessBinding[]>;
163
+ harnessConsumeApprovedRetry?(
164
+ bindingId: string,
165
+ messageId: string,
166
+ content: string,
167
+ ): Promise<boolean>;
168
+ deliveryPending?(bindingId: string): Promise<PendingDelivery[]>;
169
+ deliveryAcknowledge?(deliveryId: string): Promise<Delivery>;
170
+ close(): void;
171
+ }
172
+
173
+ /** What a connection says about itself: its role, the owner token when it claims ownership, the author it acts as otherwise. */
174
+ interface HelloParams {
175
+ role: DaemonRole;
176
+ clientVersion: string;
177
+ token?: string;
178
+ author?: string;
16
179
  }
17
180
 
18
- type Pending = { resolve: (v: unknown) => void; reject: (e: Error) => void };
181
+ /** The token as the daemon writes it: 32 random bytes in hex. */
182
+ const OwnerTokenSchema = v.pipe(v.string(), v.trim(), v.regex(/^[0-9a-f]{64}$/));
183
+
184
+ /** The owner token in `home`, or undefined when the daemon there never wrote one. */
185
+ function readOwnerToken(home: string): string | undefined {
186
+ const path = ownerTokenPath(home);
187
+
188
+ if (!existsSync(path)) return undefined;
19
189
 
20
- export class DaemonClient {
21
- private socket: Awaited<ReturnType<typeof Bun.connect>> | null = null;
22
- private pending = new Map<number, Pending>();
190
+ const parsed = v.safeParse(OwnerTokenSchema, readFileSync(path, "utf8"));
191
+
192
+ if (!parsed.success) {
193
+ throw new DaemonClientError(
194
+ "invalid_owner_token",
195
+ `${path} is not an owner token; restart the daemon to mint a fresh one`,
196
+ );
197
+ }
198
+
199
+ return parsed.output;
200
+ }
201
+
202
+ export class DaemonClient implements ThreadClient {
203
+ private socket: { end(): void } | null = null;
204
+ private writer: BackpressureWriter | null = null;
205
+ private connectionEpoch = 0;
206
+ private pending = new Map<number, PendingRequest>();
207
+ /** The connected daemon's build version, learned from the ping handshake. */
208
+ private daemonVersion: string | undefined;
23
209
  private nextId = 1;
24
- private eventListeners = new Set<(e: EventFrame) => void>();
210
+ private eventListeners = new Set<(event: EventFrame) => void>();
211
+ private disconnectListeners = new Set<(reason: DaemonTransportError) => void>();
212
+ private disconnectReason: DaemonTransportError | undefined;
25
213
  private closed = false;
214
+ private role: DaemonRole = "owner";
215
+ private author: string | undefined;
216
+ private home = cueloopHome();
26
217
 
27
- static async connect(opts: ConnectOptions = {}): Promise<DaemonClient> {
28
- const home = opts.home ?? cueloopHome();
218
+ static async connect(options: ConnectOptions = {}): Promise<DaemonClient> {
219
+ const home = options.home ?? cueloopHome();
29
220
  const path = socketPath(home);
30
221
  const client = new DaemonClient();
222
+
223
+ client.role = options.role ?? "owner";
224
+ client.author = options.author;
225
+ client.home = home;
31
226
  try {
32
227
  await client.dial(path);
33
- return client;
228
+
229
+ if (client.daemonVersion === DAEMON_VERSION) return client;
230
+
231
+ const daemonVersion = client.daemonVersion ?? "unknown";
232
+
233
+ client.close();
234
+ throw new DaemonClientError(
235
+ "version_mismatch",
236
+ `daemon is version ${daemonVersion}, but this client is ${DAEMON_VERSION}; align cueloop versions before restarting the daemon`,
237
+ );
34
238
  } catch (err) {
35
- if (!opts.autostart) throw err;
239
+ // Autostart repairs an unavailable socket, never a live incompatible daemon.
240
+ if (!options.autostart || err instanceof DaemonClientError) {
241
+ client.close();
242
+
243
+ throw err instanceof DaemonClientError || err instanceof DaemonTransportError
244
+ ? err
245
+ : new DaemonTransportError(
246
+ "connection",
247
+ "Daemon connection failed",
248
+ "not_sent",
249
+ undefined,
250
+ { cause: err },
251
+ );
252
+ }
36
253
  }
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);
254
+
255
+ // Socket dead or absent: let the new daemon own stale socket cleanup.
256
+ return client.attachFreshDaemon(home, path);
257
+ }
258
+
259
+ /** Reset per-connection state so a fresh dial() can reuse this client instance. */
260
+ private resetConnection(): void {
261
+ this.connectionEpoch += 1;
262
+ this.socket = null;
263
+ this.writer = null;
264
+ this.closed = false;
265
+ for (const pendingRequest of this.pending.values())
266
+ pendingRequest.reject(
267
+ new DaemonTransportError("connection", "daemon connection replaced", "unknown"),
268
+ );
269
+ this.pending.clear();
270
+ }
271
+
272
+ /** Spawn a detached daemon and dial the lock owner until it answers. */
273
+ private async attachFreshDaemon(home: string, path: string): Promise<DaemonClient> {
274
+ const startupLogPath = spawnDaemon(home);
40
275
  // Generous: a cold or loaded machine pays for a runtime start before the
41
276
  // socket exists, and giving up early looks to callers like a broken daemon.
42
277
  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);
278
+ let lastError: unknown;
279
+
280
+ try {
281
+ while (Date.now() < deadline) {
282
+ try {
283
+ await this.dial(path);
284
+
285
+ if (this.daemonVersion !== DAEMON_VERSION) {
286
+ this.close();
287
+
288
+ if (typeof Bun === "undefined") {
289
+ throw new DaemonClientError(
290
+ "version_mismatch",
291
+ `installed cueloop is ${this.daemonVersion ?? "unknown"}, but this adapter is ${DAEMON_VERSION}; run cueloop update`,
292
+ );
293
+ }
294
+
295
+ throw new Error("daemon autostarted an older build");
296
+ }
297
+
298
+ return this;
299
+ } catch (err) {
300
+ if (err instanceof DaemonClientError) throw err;
301
+
302
+ this.socket?.end();
303
+ this.resetConnection();
304
+ lastError = err;
305
+ await sleep(50);
306
+ }
51
307
  }
308
+ const output = readFileSync(startupLogPath, "utf8").trim();
309
+ const detail = output ? `\ndaemon startup output:\n${output.slice(-4_096)}` : "";
310
+
311
+ throw new DaemonTransportError(
312
+ "connection",
313
+ `Daemon startup failed at ${path}: ${String(lastError)}${detail}`,
314
+ "not_sent",
315
+ );
316
+ } finally {
317
+ rmSync(startupLogPath, { force: true });
52
318
  }
53
- throw new Error(`daemon did not come up at ${path}: ${String(lastErr)}`);
54
319
  }
55
320
 
56
321
  private async dial(path: string): Promise<void> {
57
322
  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));
323
+
324
+ this.disconnectReason = undefined;
325
+ const epoch = ++this.connectionEpoch;
326
+
327
+ const close = () => {
328
+ if (this.connectionEpoch !== epoch) return;
329
+
330
+ this.closed = true;
331
+ for (const pendingRequest of this.pending.values())
332
+ pendingRequest.reject(
333
+ new DaemonTransportError("connection", "daemon connection closed", "unknown"),
334
+ );
335
+ this.pending.clear();
336
+ const reason =
337
+ this.disconnectReason ??
338
+ new DaemonTransportError("connection", "daemon connection closed", "unknown");
339
+
340
+ for (const listener of this.disconnectListeners) listener(reason);
341
+ };
342
+
343
+ if (typeof Bun !== "undefined") {
344
+ const socket = await Bun.connect({
345
+ unix: path,
346
+ socket: {
347
+ data: (_socket, data) => {
348
+ buffer.push(data.toString(), (line) => this.routeInboundFrame(line));
349
+ },
350
+ drain: () => this.writer?.drain(),
351
+ close,
352
+ error() {},
64
353
  },
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();
354
+ });
355
+
356
+ this.socket = socket;
357
+ this.writer = new BackpressureWriter(socket);
358
+ } else {
359
+ const socket = createConnection(path);
360
+
361
+ await new Promise<void>((resolve, reject) => {
362
+ socket.once("connect", resolve);
363
+ socket.once("error", reject);
364
+ });
365
+ socket.on("data", (data) => {
366
+ buffer.push(data.toString(), (line) => this.routeInboundFrame(line));
367
+ });
368
+ socket.on("close", close);
369
+ socket.on("error", () => {});
370
+ this.socket = socket;
371
+ // Node queues the complete Buffer internally when write returns false.
372
+ this.writer = new BackpressureWriter({
373
+ write(data) {
374
+ socket.write(data);
375
+
376
+ return data.length;
69
377
  },
70
- error() {},
71
- },
72
- });
378
+ });
379
+ }
380
+
73
381
  // 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);
382
+ // only to fail later, so a ping is the actual handshake. It also carries the
383
+ // daemon's build version, so connect() can reject incompatible clients.
384
+ const pong = await this.request("daemon.ping", {}, PingResultSchema, 2_000);
385
+
386
+ this.daemonVersion = pong.version;
387
+ // Every connection starts as a collaborator; the owner proves itself with
388
+ // the token the daemon wrote into the home it serves, which only the home's
389
+ // user can read. A capped role just names itself.
390
+ await this.request("daemon.hello", this.helloParams(), EmptyResultSchema, 2_000);
391
+ }
392
+
393
+ private helloParams(): HelloParams {
394
+ if (this.role !== "owner") {
395
+ return this.author === undefined
396
+ ? { role: this.role, clientVersion: DAEMON_VERSION }
397
+ : { role: this.role, clientVersion: DAEMON_VERSION, author: this.author };
398
+ }
399
+
400
+ const token = readOwnerToken(this.home);
401
+
402
+ // a daemon from before owner tokens has no file; it still knows the bare hello
403
+ return token === undefined
404
+ ? { role: "owner", clientVersion: DAEMON_VERSION }
405
+ : { role: "owner", clientVersion: DAEMON_VERSION, token };
76
406
  }
77
407
 
78
- onEvent(listener: (e: EventFrame) => void): () => void {
408
+ onEvent(listener: (event: EventFrame) => void): () => void {
79
409
  this.eventListeners.add(listener);
410
+
80
411
  return () => this.eventListeners.delete(listener);
81
412
  }
82
413
 
83
- private handleFrame(line: string): void {
84
- let frame: Response | EventFrame;
414
+ /** Notify an adapter when its daemon socket closes so it can reconnect and replay Messages. */
415
+ onDisconnect(listener: (reason: DaemonTransportError) => void): () => void {
416
+ this.disconnectListeners.add(listener);
417
+
418
+ return () => this.disconnectListeners.delete(listener);
419
+ }
420
+
421
+ private routeInboundFrame(line: string): void {
422
+ let frame;
423
+
85
424
  try {
86
- frame = JSON.parse(line) as Response | EventFrame;
87
- } catch {
425
+ frame = parseInboundFrame(line);
426
+ } catch (cause) {
427
+ this.disconnectReason = new DaemonTransportError(
428
+ "protocol",
429
+ "daemon sent a malformed frame",
430
+ "unknown",
431
+ undefined,
432
+ { cause },
433
+ );
434
+ for (const pendingRequest of this.pending.values())
435
+ pendingRequest.reject(
436
+ new DaemonTransportError(
437
+ "protocol",
438
+ "daemon sent a malformed frame",
439
+ "unknown",
440
+ undefined,
441
+ { cause },
442
+ ),
443
+ );
444
+ this.pending.clear();
445
+ this.close();
446
+
88
447
  return;
89
448
  }
449
+
90
450
  if ("event" in frame) {
91
- for (const l of this.eventListeners) l(frame);
451
+ for (const listener of this.eventListeners) listener(frame);
452
+
92
453
  return;
93
454
  }
94
- const p = this.pending.get(frame.id);
95
- if (!p) return;
455
+
456
+ const pendingRequest = this.pending.get(frame.id);
457
+
458
+ if (!pendingRequest) return;
459
+
96
460
  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);
461
+
462
+ if (frame.error)
463
+ pendingRequest.reject(new DaemonClientError(frame.error.code, frame.error.message));
464
+ else pendingRequest.resolve(frame.result);
99
465
  }
100
466
 
101
- request<T = unknown>(method: string, params: unknown, timeoutMs = 30_000): Promise<T> {
102
- if (this.closed || !this.socket) return Promise.reject(new Error("not connected"));
467
+ request<TOutput>(
468
+ method: string,
469
+ params: Request["params"],
470
+ resultSchema: v.GenericSchema<unknown, TOutput>,
471
+ options: number | DaemonRequestOptions = 30_000,
472
+ ): Promise<TOutput> {
473
+ const { timeoutMs = 30_000, signal } = v.is(v.number(), options)
474
+ ? { timeoutMs: options }
475
+ : options;
476
+
477
+ if (signal?.aborted)
478
+ return Promise.reject(
479
+ new DaemonTransportError("cancelled", `request ${method} cancelled`, "not_sent", method),
480
+ );
481
+
482
+ if (this.closed || !this.socket)
483
+ return Promise.reject(
484
+ new DaemonTransportError("connection", "not connected", "not_sent", method),
485
+ );
486
+
103
487
  const id = this.nextId++;
104
- return new Promise<T>((resolve, reject) => {
105
- const timer = setTimeout(() => {
488
+
489
+ return new Promise<TOutput>((resolve, reject) => {
490
+ const cleanup = () => {
491
+ clearTimeout(timer);
492
+ signal?.removeEventListener("abort", abort);
106
493
  this.pending.delete(id);
107
- reject(new Error(`request ${method} timed out`));
494
+ };
495
+ const fail = (error: Error) => {
496
+ cleanup();
497
+ reject(error);
498
+ };
499
+ const abort = () =>
500
+ fail(
501
+ new DaemonTransportError("cancelled", `request ${method} cancelled`, "unknown", method),
502
+ );
503
+ const timer = setTimeout(() => {
504
+ fail(new DaemonTransportError("timeout", `request ${method} timed out`, "unknown", method));
108
505
  }, timeoutMs);
506
+
109
507
  this.pending.set(id, {
110
- resolve: (v) => {
111
- clearTimeout(timer);
112
- resolve(v as T);
113
- },
114
- reject: (e) => {
115
- clearTimeout(timer);
116
- reject(e);
508
+ resolve: (value) => {
509
+ cleanup();
510
+ try {
511
+ const parsed = v.safeParse(resultSchema, value);
512
+
513
+ if (!parsed.success)
514
+ throw new DaemonTransportError(
515
+ "protocol",
516
+ `request ${method} returned an invalid result`,
517
+ "unknown",
518
+ method,
519
+ { cause: parsed.issues },
520
+ );
521
+
522
+ resolve(parsed.output);
523
+ } catch (cause) {
524
+ reject(
525
+ cause instanceof DaemonTransportError
526
+ ? cause
527
+ : new DaemonTransportError(
528
+ "protocol",
529
+ `request ${method} returned an invalid result`,
530
+ "unknown",
531
+ method,
532
+ { cause },
533
+ ),
534
+ );
535
+ }
117
536
  },
537
+ reject: fail,
118
538
  });
119
- this.socket!.write(JSON.stringify({ id, method, params }) + "\n");
539
+ signal?.addEventListener("abort", abort, { once: true });
540
+ try {
541
+ this.writer!.write(JSON.stringify({ id, method, params }) + "\n");
542
+ } catch (cause) {
543
+ fail(
544
+ new DaemonTransportError(
545
+ "connection",
546
+ `request ${method} could not be written`,
547
+ "unknown",
548
+ method,
549
+ { cause },
550
+ ),
551
+ );
552
+ }
120
553
  });
121
554
  }
122
555
 
123
556
  close(): void {
124
557
  this.closed = true;
558
+ for (const pendingRequest of this.pending.values())
559
+ pendingRequest.reject(
560
+ new DaemonTransportError("connection", "daemon connection closed", "unknown"),
561
+ );
562
+ this.pending.clear();
125
563
  this.socket?.end();
126
564
  }
127
565
 
128
- // ── typed verbs ─────────────────────────────
129
- ping(): Promise<{ pid: number }> {
130
- return this.request("daemon.ping", {});
566
+ // ── typed primitives ─────────────────────────────
567
+ /** Read the agent transcript without starting a model request. */
568
+ agentGet(id: string, options?: DaemonRequestOptions): Promise<ThreadAgentState> {
569
+ return this.request("agent.get", { id }, ThreadAgentSchema, options);
570
+ }
571
+ /** Submit a question and optional selected passage to the daemon-owned agent. */
572
+ agentPrompt(
573
+ params: AgentPromptRequest,
574
+ options?: DaemonRequestOptions,
575
+ ): Promise<ThreadAgentState> {
576
+ return this.request("agent.prompt", params, ThreadAgentSchema, options);
577
+ }
578
+ /** Cancel the active turn; the daemon retains partial output. */
579
+ agentCancel(id: string): Promise<ThreadAgentState> {
580
+ return this.request("agent.cancel", { id }, ThreadAgentSchema);
581
+ }
582
+ /** Save quote-primary feedback on a finalized agent answer. */
583
+ agentComment(params: { id: string; comment: AgentComment }): Promise<ThreadAgentState> {
584
+ return this.request("agent.comment", params, ThreadAgentSchema);
585
+ }
586
+ /** Configure only an option advertised by the current harness. */
587
+ agentConfigure(params: {
588
+ id: string;
589
+ configId?: string;
590
+ value?: string;
591
+ }): Promise<ThreadAgentState> {
592
+ return this.request("agent.configure", params, ThreadAgentSchema);
593
+ }
594
+
595
+ /** Select an option from the active agent permission card. */
596
+ agentPermission(params: {
597
+ id: string;
598
+ requestId: string;
599
+ optionId: string;
600
+ }): Promise<ThreadAgentState> {
601
+ return this.request("agent.permission", params, ThreadAgentSchema);
602
+ }
603
+ ping(): Promise<{ pid: number; agentHarness?: string }> {
604
+ return this.request("daemon.ping", {}, PingResultSchema);
131
605
  }
132
606
  subscribe(): Promise<void> {
133
- return this.request("events.subscribe", {});
607
+ return this.request("events.subscribe", {}, EmptyResultSchema).then(() => undefined);
134
608
  }
135
- sessionCreate(workspace: WorkspaceKey, artifact: Artifact): Promise<ReviewSession> {
136
- return this.request("session.create", { workspace, artifact });
609
+ sessionCreate(workspace: WorkspaceKey, artifact: Artifact): Promise<Thread> {
610
+ return this.request("session.create", { workspace, artifact }, ThreadRecordSchema);
137
611
  }
138
- sessionGet(id: string): Promise<ReviewSession> {
139
- return this.request("session.get", { id });
612
+ sessionGet(id: string): Promise<Thread> {
613
+ return this.request("session.get", { id }, ThreadRecordSchema);
140
614
  }
141
- sessionList(filter?: { status?: "pending" | "resolved" }): Promise<ReviewSession[]> {
142
- return this.request("session.list", { filter });
615
+ sessionList(filter?: { status?: "pending" | "resolved" }): Promise<Thread[]> {
616
+ return this.request("session.list", { filter }, v.array(ThreadRecordSchema));
143
617
  }
144
618
  /** 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);
619
+ sessionWait(id: string, timeoutMs: number): Promise<Thread | null> {
620
+ return this.request(
621
+ "session.wait",
622
+ { id, timeoutMs },
623
+ v.nullable(ThreadRecordSchema),
624
+ timeoutMs + 10_000,
625
+ );
626
+ }
627
+ sessionComment(
628
+ id: string,
629
+ annotation: Omit<Annotation, "createdAt">,
630
+ authorName?: string,
631
+ ): Promise<Thread> {
632
+ return this.request("session.comment", { id, annotation, authorName }, ThreadRecordSchema);
633
+ }
634
+ sessionAnnotate(
635
+ id: string,
636
+ annotation: Omit<Annotation, "createdAt">,
637
+ authorName?: string,
638
+ ): Promise<Thread> {
639
+ return this.request("session.annotate", { id, annotation, authorName }, ThreadRecordSchema);
640
+ }
641
+ sessionRemoveAnnotation(id: string, annotationId: string): Promise<Thread> {
642
+ return this.request("session.removeAnnotation", { id, annotationId }, ThreadRecordSchema);
643
+ }
644
+ /** Register a display name for a participant - a collaborator's or an agent's own, on a share or locally. */
645
+ sessionSetParticipantName(id: string, author: string, name: string): Promise<Thread> {
646
+ return this.request("session.setParticipantName", { id, author, name }, ThreadRecordSchema);
647
+ }
648
+ sessionSetWorkingCopy(
649
+ id: string,
650
+ workingCopy: string | undefined,
651
+ textCuts?: TextCut[],
652
+ ): Promise<Thread> {
653
+ return this.request(
654
+ "session.setWorkingCopy",
655
+ { id, workingCopy, textCuts },
656
+ ThreadRecordSchema,
657
+ );
658
+ }
659
+ sessionCutBlock(id: string, blockIndex: number): Promise<Thread> {
660
+ return this.request("session.cutBlock", { id, blockIndex }, ThreadRecordSchema);
661
+ }
662
+ sessionNavigate(id: string, entryId: string, summary?: string, branch?: string): Promise<Thread> {
663
+ const params: v.InferInput<(typeof Params)["session.navigate"]> = { id, entryId };
664
+
665
+ if (summary !== undefined) params.summary = summary;
666
+
667
+ if (branch !== undefined) params.branch = branch;
668
+
669
+ return this.request("session.navigate", params, ThreadRecordSchema);
670
+ }
671
+ sessionBranch(id: string, name: string): Promise<Thread> {
672
+ return this.request("session.branch", { id, name }, ThreadRecordSchema);
673
+ }
674
+ sessionSwitch(id: string, branch: string): Promise<Thread> {
675
+ return this.request("session.switch", { id, branch }, ThreadRecordSchema);
676
+ }
677
+ sessionLabel(id: string, label: string): Promise<Thread> {
678
+ return this.request("session.label", { id, label }, ThreadRecordSchema);
679
+ }
680
+ sessionFork(id: string): Promise<Thread> {
681
+ return this.request("session.fork", { id }, ThreadRecordSchema);
682
+ }
683
+ sessionRestoreBlock(id: string, baseBlockIndex: number, line?: number): Promise<Thread> {
684
+ return this.request(
685
+ "session.restoreBlock",
686
+ line === undefined ? { id, baseBlockIndex } : { id, baseBlockIndex, line },
687
+ ThreadRecordSchema,
688
+ );
689
+ }
690
+ sessionCurate(id: string, rejections: HunkRejection[]): Promise<Thread> {
691
+ return this.request("session.curate", { id, rejections }, ThreadRecordSchema);
692
+ }
693
+ sessionSetViewed(id: string, viewedPaths: string[]): Promise<Thread> {
694
+ return this.request("session.setViewed", { id, viewedPaths }, ThreadRecordSchema);
695
+ }
696
+ sessionSetTitle(id: string, title: string): Promise<Thread> {
697
+ return this.request("session.setTitle", { id, title }, ThreadRecordSchema);
698
+ }
699
+ projectFiles(sessionId: string): Promise<string[]> {
700
+ return this.request("session.projectFiles", { id: sessionId }, v.array(v.string()));
147
701
  }
148
- sessionAnnotate(id: string, annotation: Omit<Annotation, "createdAt">): Promise<ReviewSession> {
149
- return this.request("session.annotate", { id, annotation });
702
+ fileContents(sessionId: string, path: string): Promise<string | null> {
703
+ return this.request("session.fileContents", { id: sessionId, path }, v.nullable(v.string()));
150
704
  }
151
- sessionRemoveAnnotation(id: string, annotationId: string): Promise<ReviewSession> {
152
- return this.request("session.removeAnnotation", { id, annotationId });
705
+ repoFiles(cwd: string): Promise<string[]> {
706
+ return this.request("repo.files", { cwd }, v.array(v.string()));
153
707
  }
154
- sessionSetWorkingCopy(id: string, workingCopy: string | undefined): Promise<ReviewSession> {
155
- return this.request("session.setWorkingCopy", { id, workingCopy });
708
+ repoFileContents(cwd: string, path: string): Promise<string | null> {
709
+ return this.request("repo.fileContents", { cwd, path }, v.nullable(v.string()));
156
710
  }
157
- sessionResolve(id: string, verdictKind: VerdictKind, summary: string): Promise<ReviewSession> {
158
- return this.request("session.resolve", { id, verdictKind, summary });
711
+ repoChanges(cwd: string): Promise<{ path: string; status: DiffFileStatus }[]> {
712
+ return this.request(
713
+ "repo.changes",
714
+ { cwd },
715
+ v.array(v.object({ path: v.string(), status: v.picklist(["added", "modified", "deleted"]) })),
716
+ );
159
717
  }
160
- sessionSubmitRevision(id: string, content: string): Promise<ReviewSession> {
161
- return this.request("session.submitRevision", { id, content });
718
+ repoDiff(
719
+ cwd: string,
720
+ vcs?: string,
721
+ ): Promise<
722
+ WorkingTreeDiff & { vcs?: string; source?: { changeId?: string; revisionId: string } }
723
+ > {
724
+ return this.request(
725
+ "repo.diff",
726
+ { cwd, vcs },
727
+ v.object({
728
+ patch: v.string(),
729
+ files: v.array(DiffFileContentsSchema),
730
+ vcs: v.optional(v.string()),
731
+ source: v.optional(v.object({ changeId: v.optional(v.string()), revisionId: v.string() })),
732
+ }),
733
+ );
734
+ }
735
+ sessionWorkbench(cwd: string): Promise<Thread> {
736
+ return this.request("session.workbench", { cwd }, ThreadRecordSchema);
737
+ }
738
+ /** Open a workbench with the diff snapshot used for its first frame. */
739
+ workbenchReview(cwd: string): Promise<{ session: Thread; diff: WorkingTreeDiff }> {
740
+ return this.request(
741
+ "session.workbenchReview",
742
+ { cwd },
743
+ v.object({
744
+ session: ThreadRecordSchema,
745
+ diff: v.object({
746
+ patch: v.string(),
747
+ files: v.array(DiffFileContentsSchema),
748
+ vcs: v.string(),
749
+ source: v.optional(
750
+ v.object({ changeId: v.optional(v.string()), revisionId: v.string() }),
751
+ ),
752
+ }),
753
+ }),
754
+ );
755
+ }
756
+ /** Re-capture a diff session's working tree; changed=true when the patch moved and an event fired. */
757
+ sessionRefreshDiff(id: string): Promise<{ changed: boolean }> {
758
+ return this.request("session.refreshDiff", { id }, RefreshDiffResultSchema);
759
+ }
760
+
761
+ sessionSetShares(id: string, shares: ShareLink[]): Promise<Thread> {
762
+ return this.request("session.setShares", { id, shares }, ThreadRecordSchema);
763
+ }
764
+ sessionMergeShared(id: string, incoming: SharedMerge): Promise<Thread> {
765
+ return this.request("session.mergeShared", { id, ...incoming }, ThreadRecordSchema);
766
+ }
767
+ sessionDelete(id: string): Promise<void> {
768
+ return this.request("session.delete", { id }, EmptyResultSchema).then(() => undefined);
769
+ }
770
+ /** Local sessions have no collaborator self-name; the share client owns this. */
771
+ sessionSetSelfName(id: string, _name: string): Promise<Thread> {
772
+ return this.sessionGet(id);
773
+ }
774
+ sessionSendMessage(
775
+ id: string,
776
+ outcome: MessageOutcome,
777
+ summary: string,
778
+ actionBodies?: Record<string, string>,
779
+ operationId?: string,
780
+ options?: DaemonRequestOptions,
781
+ ): Promise<Thread> {
782
+ return this.request(
783
+ "session.sendMessage",
784
+ { id, outcome, summary, actionBodies, operationId },
785
+ ThreadRecordSchema,
786
+ options,
787
+ );
788
+ }
789
+ harnessBind(
790
+ threadId: string,
791
+ harness: string,
792
+ harnessSessionId: string,
793
+ ): Promise<HarnessBinding> {
794
+ return this.request(
795
+ "harness.bind",
796
+ { threadId, harness, harnessSessionId },
797
+ HarnessBindingSchema,
798
+ );
799
+ }
800
+ harnessGetBinding(bindingId: string): Promise<HarnessBinding> {
801
+ return this.request("harness.getBinding", { bindingId }, HarnessBindingSchema);
802
+ }
803
+ harnessBindingsForSession(harness: string, harnessSessionId: string): Promise<HarnessBinding[]> {
804
+ return this.request(
805
+ "harness.bindingsForSession",
806
+ { harness, harnessSessionId },
807
+ v.array(HarnessBindingSchema),
808
+ );
809
+ }
810
+ harnessConsumeApprovedRetry(
811
+ bindingId: string,
812
+ messageId: string,
813
+ content: string,
814
+ ): Promise<boolean> {
815
+ return this.request(
816
+ "harness.consumeApprovedRetry",
817
+ { bindingId, messageId, content },
818
+ v.boolean(),
819
+ );
820
+ }
821
+ deliveryPending(bindingId: string): Promise<PendingDelivery[]> {
822
+ return this.request("delivery.pending", { bindingId }, v.array(PendingDeliverySchema));
823
+ }
824
+ deliveryAcknowledge(deliveryId: string): Promise<Delivery> {
825
+ return this.request("delivery.acknowledge", { deliveryId }, DeliverySchema);
826
+ }
827
+ sessionSubmitRevision(
828
+ id: string,
829
+ content: string,
830
+ addressedAnnotationIds: string[] = [],
831
+ files?: DiffFileContents[],
832
+ source?: import("@cueloop/schema").DiffSource,
833
+ ): Promise<Thread> {
834
+ return this.request(
835
+ "session.submitRevision",
836
+ { id, content, addressedAnnotationIds, files, source },
837
+ ThreadRecordSchema,
838
+ );
839
+ }
840
+ /** Read Herdr's local Thread surface handle, outside the ThreadClient contract. */
841
+ herdrGetThreadSurface(id: string): Promise<HerdrThreadSurfaceHandle | null> {
842
+ return this.request("herdr.getThreadSurface", { id }, HerdrThreadSurfaceResultSchema);
843
+ }
844
+ async herdrSetThreadSurface(id: string, handle: HerdrThreadSurfaceHandle): Promise<void> {
845
+ await this.request("herdr.setThreadSurface", { id, ...handle }, EmptyResultSchema);
846
+ }
847
+ ghosttyGetThreadSurface(id: string): Promise<GhosttyThreadSurfaceHandle | null> {
848
+ return this.request("ghostty.getThreadSurface", { id }, GhosttyThreadSurfaceResultSchema);
849
+ }
850
+ async ghosttySetThreadSurface(id: string, handle: GhosttyThreadSurfaceHandle): Promise<void> {
851
+ await this.request("ghostty.setThreadSurface", { id, ...handle }, EmptyResultSchema);
852
+ }
853
+ ghosttyClaimThreadSurface(id: string): Promise<boolean> {
854
+ return this.request("ghostty.claimThreadSurface", { id }, v.boolean());
855
+ }
856
+ async ghosttyReleaseThreadSurface(id: string): Promise<void> {
857
+ await this.request("ghostty.releaseThreadSurface", { id }, EmptyResultSchema);
162
858
  }
163
859
  shutdown(): Promise<void> {
164
- return this.request("daemon.shutdown", {});
860
+ return this.request("daemon.shutdown", {}, EmptyResultSchema).then(() => undefined);
165
861
  }
166
862
  }
167
863
 
168
864
  export class DaemonClientError extends Error {
865
+ readonly _tag = "DaemonClientError";
169
866
  constructor(
170
867
  readonly code: string,
171
868
  message: string,
@@ -174,10 +871,62 @@ export class DaemonClientError extends Error {
174
871
  }
175
872
  }
176
873
 
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();
874
+ // A compiled binary re-execs `cueloop daemon --autostart` (idle-exits like main.ts,
875
+ // unlike the never-exiting foreground daemon); source also uses the CLI composition root. In
876
+ // dev (CUELOOP_DEV_WATCH=1, source only) it runs under --watch so daemon-code edits
877
+ // reload the daemon without a manual restart - the version handshake only catches
878
+ // release upgrades, not same-version source changes.
879
+ export function daemonSpawnCommand(
880
+ execPath: string,
881
+ moduleUrl: string,
882
+ devWatch = process.env.CUELOOP_DEV_WATCH === "1",
883
+ entry = process.env.CUELOOP_DAEMON_ENTRY,
884
+ ): string[] {
885
+ const compiled =
886
+ moduleUrl.includes("$bunfs") || moduleUrl.includes("~BUN") || moduleUrl.includes("%7EBUN");
887
+
888
+ if (compiled) return [execPath, "daemon", "--autostart"];
889
+
890
+ const mainPath = entry ?? new URL("./main.ts", moduleUrl).pathname;
891
+
892
+ const args = entry ? ["daemon", "--autostart"] : [];
893
+
894
+ return devWatch
895
+ ? [execPath, "--watch", "run", mainPath, ...args]
896
+ : [execPath, "run", mainPath, ...args];
897
+ }
898
+
899
+ function spawnDaemon(home: string): string {
900
+ mkdirSync(home, { recursive: true, mode: 0o700 });
901
+ const startupLogPath = join(
902
+ home,
903
+ `daemon-startup-${process.pid}-${randomBytes(6).toString("hex")}.log`,
904
+ );
905
+ const logFd = openSync(startupLogPath, "wx", 0o600);
906
+
907
+ try {
908
+ if (typeof Bun === "undefined") {
909
+ const child = spawn(process.env.CUELOOP_EXECUTABLE ?? "cueloop", ["daemon", "--autostart"], {
910
+ env: { ...process.env, CUELOOP_HOME: home },
911
+ stdio: ["ignore", logFd, logFd],
912
+ detached: true,
913
+ });
914
+
915
+ child.on("error", (error) => appendFileSync(startupLogPath, `${String(error)}\n`));
916
+ child.unref();
917
+ } else {
918
+ Bun.spawn(daemonSpawnCommand(process.execPath, import.meta.url), {
919
+ env: { ...process.env, CUELOOP_HOME: home },
920
+ stdio: ["ignore", logFd, logFd],
921
+ }).unref();
922
+ }
923
+ } finally {
924
+ closeSync(logFd);
925
+ }
926
+
927
+ return startupLogPath;
928
+ }
929
+
930
+ function sleep(durationMs: number): Promise<void> {
931
+ return new Promise((resolve) => setTimeout(resolve, durationMs));
183
932
  }