@cueloop/daemon 0.1.0-alpha.0 → 0.1.0-alpha.100

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 (80) hide show
  1. package/README.md +7 -0
  2. package/SDK.md +102 -0
  3. package/package.json +43 -16
  4. package/src/agent-tools.ts +98 -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 +1425 -89
  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 +189 -0
  13. package/src/client.test.ts +37 -0
  14. package/src/client.ts +820 -94
  15. package/src/curate.ts +109 -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 +397 -0
  19. package/src/daemon-version.test.ts +142 -0
  20. package/src/diff-hot-reload.test.ts +419 -0
  21. package/src/diff-watcher.test.ts +117 -0
  22. package/src/diff-watcher.ts +326 -0
  23. package/src/examples/daemon-sdk.ts +55 -0
  24. package/src/gh.test.ts +59 -0
  25. package/src/gh.ts +74 -0
  26. package/src/ghostty-thread-surface-store.test.ts +49 -0
  27. package/src/ghostty-thread-surface-store.ts +101 -0
  28. package/src/ghostty-thread-surface.test.ts +398 -0
  29. package/src/ghostty-thread-surface.ts +267 -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 +30 -0
  33. package/src/harness-state-store.test.ts +93 -0
  34. package/src/harness-state-store.ts +213 -0
  35. package/src/herdr-split.test.ts +106 -0
  36. package/src/herdr-split.ts +85 -0
  37. package/src/herdr-thread-surface-store.test.ts +81 -0
  38. package/src/herdr-thread-surface-store.ts +66 -0
  39. package/src/herdr-thread-surface.test.ts +465 -0
  40. package/src/herdr-thread-surface.ts +378 -0
  41. package/src/index.ts +8 -8
  42. package/src/interruptible-wait.test.ts +127 -0
  43. package/src/interruptible-wait.ts +66 -0
  44. package/src/jj-working-tree.ts +131 -0
  45. package/src/main.ts +4 -1
  46. package/src/operation-receipts.test.ts +111 -0
  47. package/src/operation-receipts.ts +91 -0
  48. package/src/paths.ts +49 -0
  49. package/src/pr-poller.test.ts +102 -0
  50. package/src/pr-poller.ts +73 -0
  51. package/src/project-files.test.ts +134 -0
  52. package/src/project-files.ts +68 -0
  53. package/src/protocol.ts +78 -7
  54. package/src/retention.test.ts +191 -0
  55. package/src/retention.ts +123 -0
  56. package/src/sdk-identities.ts +35 -0
  57. package/src/server.test.ts +465 -40
  58. package/src/server.ts +601 -88
  59. package/src/share-blob.test.ts +119 -0
  60. package/src/share-blob.ts +57 -0
  61. package/src/single-instance.test.ts +162 -13
  62. package/src/store.conformance.test.ts +41 -0
  63. package/src/store.jsonl.test.ts +173 -0
  64. package/src/store.ts +267 -34
  65. package/src/testing/store-conformance.ts +192 -0
  66. package/src/thread-agent-validation.ts +119 -0
  67. package/src/thread-agent.test.ts +412 -0
  68. package/src/thread-agent.ts +713 -0
  69. package/src/thread-review.test.ts +483 -0
  70. package/src/thread-review.ts +382 -0
  71. package/src/thread-subscription.test.ts +174 -0
  72. package/src/thread-subscription.ts +129 -0
  73. package/src/thread-surface-config.test.ts +63 -0
  74. package/src/thread-surface-config.ts +61 -0
  75. package/src/validate.test.ts +366 -21
  76. package/src/validate.ts +458 -47
  77. package/src/vcs-source.test.ts +180 -0
  78. package/src/vcs-source.ts +229 -0
  79. package/src/version.ts +6 -0
  80. package/src/working-tree.ts +150 -0
package/src/server.ts CHANGED
@@ -1,26 +1,55 @@
1
1
  /**
2
2
  * The socket server: binds DaemonCore's methods to the unix socket, owns the
3
- * pidfile, stale-socket cleanup, and the idle-exit timer (#14). File
3
+ * pidfile, stale-socket cleanup, and the idle-exit timer. File
4
4
  * permissions are the local auth: the socket and state dir are 0700/0600.
5
5
  */
6
6
 
7
- import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";
7
+ import {
8
+ chmodSync,
9
+ closeSync,
10
+ existsSync,
11
+ fstatSync,
12
+ linkSync,
13
+ mkdirSync,
14
+ openSync,
15
+ readFileSync,
16
+ rmSync,
17
+ statSync,
18
+ writeFileSync,
19
+ } from "node:fs";
20
+ import type { AgentHarnessTools } from "@cueloop/schema";
8
21
  import { DaemonCore, type DaemonEvent } from "./api";
9
22
  import { DaemonError } from "./errors";
10
- import { isKnownMethod, parseParams } from "./validate";
11
- import { LineBuffer, type Request } from "./protocol";
12
- import { cueloopHome, lockPath, pidPath, socketPath } from "./paths";
23
+ import { DEFAULT_ROLE, roleAllowsMethod, type DaemonRole } from "./capabilities";
24
+ import { isKnownMethod, parseParams, type MethodName } from "./validate";
25
+ import {
26
+ BackpressureWriter,
27
+ LineBuffer,
28
+ parseRequestFrame,
29
+ type Request,
30
+ type Response,
31
+ } from "./protocol";
32
+ import { cueloopHome, lockPath, ownerTokenPath, pidPath, socketPath } from "./paths";
33
+ import { DAEMON_VERSION } from "./version";
34
+ import { randomUUID, randomBytes } from "node:crypto";
35
+ import { parseAgentToolInput, assertAgentToolScope } from "./agent-tools";
36
+ import { ThreadAgentManager, type ThreadAgentOptions } from "./thread-agent";
13
37
 
14
- interface Conn {
38
+ interface Connection {
39
+ author?: string;
15
40
  write(data: string): void;
16
41
  subscribed: boolean;
42
+ role: DaemonRole;
17
43
  }
18
44
 
45
+ type MethodHandler = (connection: Connection, request: Request) => Response["result"];
46
+
19
47
  export interface DaemonOptions {
48
+ threadAgent?: Pick<ThreadAgentOptions, "enabled" | "enabledForThread" | "adapter">;
20
49
  home?: string;
21
- /** Idle-exit delay; 0 disables (tests, foreground runs). */
22
50
  idleExitMs?: number;
23
51
  onIdleExit?: () => void;
52
+ version?: string;
24
53
  }
25
54
 
26
55
  /**
@@ -29,24 +58,86 @@ export interface DaemonOptions {
29
58
  * so in-process ownership is tracked separately.
30
59
  */
31
60
  const HELD_HOMES = new Set<string>();
61
+ const LOCK_WAIT = new Int32Array(new SharedArrayBuffer(4));
32
62
 
33
63
  export class DaemonServer {
64
+ private readonly threadAgent: ThreadAgentManager;
34
65
  readonly core: DaemonCore;
35
66
  readonly home: string;
36
- private conns = new Set<Conn>();
67
+ private connections = new Set<Connection>();
37
68
  private server: ReturnType<typeof Bun.listen> | null = null;
38
69
  private idleTimer: ReturnType<typeof setTimeout> | null = null;
39
70
  private lockFd: number | null = null;
71
+ /** The secret that proves ownership; minted per daemon run, readable by the home's user only. */
72
+ private ownerToken = "";
40
73
  private readonly idleExitMs: number;
41
74
  private readonly onIdleExit: () => void;
75
+ private readonly version: string;
42
76
 
43
- constructor(opts: DaemonOptions = {}) {
44
- this.home = opts.home ?? cueloopHome();
45
- this.idleExitMs = opts.idleExitMs ?? 15 * 60 * 1000;
46
- this.onIdleExit = opts.onIdleExit ?? (() => process.exit(0));
77
+ constructor(options: DaemonOptions = {}) {
78
+ this.home = options.home ?? cueloopHome();
79
+ this.idleExitMs = options.idleExitMs ?? 15 * 60 * 1000;
80
+ this.onIdleExit = options.onIdleExit ?? (() => process.exit(0));
81
+ this.version = options.version ?? DAEMON_VERSION;
47
82
  mkdirSync(this.home, { recursive: true, mode: 0o700 });
48
83
  this.core = new DaemonCore(this.home);
49
- this.core.onEvent((e) => this.broadcast(e));
84
+ this.threadAgent = new ThreadAgentManager({
85
+ home: this.home,
86
+ enabled: options.threadAgent?.enabled ?? false,
87
+ enabledForThread: options.threadAgent?.enabledForThread,
88
+ adapter: options.threadAgent?.adapter,
89
+ getThread: (id) => this.core.sessionGet(id),
90
+ tools: (thread): AgentHarnessTools => ({
91
+ definitions: [
92
+ {
93
+ name: "send_message",
94
+ description:
95
+ "Return the Thread and its comments to the main session using the existing Send message action.",
96
+ inputSchema: {
97
+ type: "object",
98
+ properties: {
99
+ id: { type: "string" },
100
+ outcome: { type: "string", enum: ["comment", "approved", "changes_requested"] },
101
+ summary: { type: "string" },
102
+ },
103
+ required: ["id", "outcome"],
104
+ },
105
+ },
106
+ {
107
+ name: "reply_to_comment",
108
+ description:
109
+ "Append a reply to an existing comment discussion, preserving its quote and Changes origin.",
110
+ inputSchema: {
111
+ type: "object",
112
+ properties: {
113
+ id: { type: "string" },
114
+ commentId: { type: "string" },
115
+ body: { type: "string" },
116
+ },
117
+ required: ["id", "commentId", "body"],
118
+ },
119
+ },
120
+ {
121
+ name: "cueloop_api",
122
+ description:
123
+ "Call a cueloop API operation on this Thread or its repository. Use session.get to inspect this Thread. Global harness, sharing, deletion and Thread creation operations are unavailable. Parameters follow the cueloop socket API.",
124
+ inputSchema: {
125
+ type: "object",
126
+ properties: { method: { type: "string" }, params: { type: "object" } },
127
+ required: ["method", "params"],
128
+ },
129
+ },
130
+ ],
131
+ call: async (name, input) => this.callAgentTool(thread.id, name, input),
132
+ }),
133
+ onChange: (id) => {
134
+ for (const connection of this.connections) {
135
+ if (connection.subscribed && connection.role === "owner")
136
+ connection.write(JSON.stringify({ event: "agent.updated", sessionId: id }) + "\n");
137
+ }
138
+ },
139
+ });
140
+ this.core.onEvent((event) => this.broadcast(event));
50
141
  }
51
142
 
52
143
  /**
@@ -59,18 +150,37 @@ export class DaemonServer {
59
150
  private acquireLock(): boolean {
60
151
  if (HELD_HOMES.has(this.home)) return false; // another instance here owns it
61
152
  const path = lockPath(this.home);
153
+
62
154
  for (let attempt = 0; attempt < 3; attempt++) {
155
+ const preparedPath = `${path}.${process.pid}.${randomBytes(8).toString("hex")}.tmp`;
156
+ const fd = openSync(preparedPath, "wx", 0o600);
157
+
63
158
  try {
64
- // "wx" fails when the file exists - the atomic part of the handshake
65
- const fd = openSync(path, "wx");
159
+ // Publish the complete pid atomically. A competing daemon must never
160
+ // mistake a newly created, still-empty lock for a crashed owner.
66
161
  writeFileSync(fd, String(process.pid));
162
+ linkSync(preparedPath, path);
67
163
  this.lockFd = fd;
68
164
  HELD_HOMES.add(this.home);
165
+
69
166
  return true;
70
- } catch {
167
+ } catch (error) {
168
+ closeSync(fd);
169
+ if (!(error instanceof Error && "code" in error && error.code === "EEXIST")) throw error;
170
+
71
171
  let ownerPid = 0;
172
+
72
173
  try {
73
- ownerPid = Number(readFileSync(path, "utf8").trim());
174
+ let ownerText = readFileSync(path, "utf8").trim();
175
+
176
+ // Older daemon builds published the lock before writing their pid.
177
+ // Give that live owner time to finish instead of stealing its socket.
178
+ for (let probe = 0; !ownerText && probe < 25; probe++) {
179
+ Atomics.wait(LOCK_WAIT, 0, 0, 20);
180
+ ownerText = readFileSync(path, "utf8").trim();
181
+ }
182
+ if (!ownerText && Date.now() - statSync(path).mtimeMs < 5_000) return false;
183
+ ownerPid = Number(ownerText);
74
184
  } catch {
75
185
  // the owner vanished between open and read; retry
76
186
  continue;
@@ -78,6 +188,7 @@ export class DaemonServer {
78
188
  if (ownerPid && ownerPid !== process.pid) {
79
189
  try {
80
190
  process.kill(ownerPid, 0); // throws when the pid is gone
191
+
81
192
  return false; // a live daemon owns this home
82
193
  } catch {
83
194
  // stale lock from a crashed daemon
@@ -90,14 +201,23 @@ export class DaemonServer {
90
201
  } catch {
91
202
  return false;
92
203
  }
204
+ } finally {
205
+ rmSync(preparedPath, { force: true });
93
206
  }
94
207
  }
208
+
95
209
  return false;
96
210
  }
97
211
 
98
212
  private releaseLock(): void {
99
213
  HELD_HOMES.delete(this.home);
100
214
  if (this.lockFd !== null) {
215
+ try {
216
+ if (statSync(lockPath(this.home)).ino === fstatSync(this.lockFd).ino)
217
+ rmSync(lockPath(this.home), { force: true });
218
+ } catch {
219
+ // the lock was already removed or replaced
220
+ }
101
221
  try {
102
222
  closeSync(this.lockFd);
103
223
  } catch {
@@ -105,7 +225,6 @@ export class DaemonServer {
105
225
  }
106
226
  this.lockFd = null;
107
227
  }
108
- rmSync(lockPath(this.home), { force: true });
109
228
  }
110
229
 
111
230
  /**
@@ -115,27 +234,47 @@ export class DaemonServer {
115
234
  start(): string | null {
116
235
  if (!this.acquireLock()) return null;
117
236
  const path = socketPath(this.home);
237
+
118
238
  // safe now: holding the lock means no live daemon owns this home, so any
119
239
  // socket file left behind is stale
120
240
  if (existsSync(path)) rmSync(path, { force: true });
121
- const self = this;
122
- this.server = Bun.listen<{ buffer: LineBuffer; conn: Conn }>({
241
+ // the token exists before the socket does: the first client to connect
242
+ // must be able to prove ownership
243
+ this.ownerToken = randomBytes(32).toString("hex");
244
+ writeFileSync(ownerTokenPath(this.home), this.ownerToken, { mode: 0o600 });
245
+ chmodSync(ownerTokenPath(this.home), 0o600);
246
+ this.server = Bun.listen<{
247
+ buffer: LineBuffer;
248
+ connection: Connection;
249
+ writer: BackpressureWriter;
250
+ }>({
123
251
  unix: path,
124
252
  socket: {
125
- open(socket) {
126
- const conn: Conn = { write: (d) => socket.write(d), subscribed: false };
127
- socket.data = { buffer: new LineBuffer(), conn };
128
- self.conns.add(conn);
129
- self.scheduleIdleCheck();
253
+ open: (socket) => {
254
+ const writer = new BackpressureWriter(socket);
255
+ const connection: Connection = {
256
+ write: (data) => writer.write(data),
257
+ subscribed: false,
258
+ role: DEFAULT_ROLE,
259
+ };
260
+
261
+ socket.data = { buffer: new LineBuffer(), connection, writer };
262
+ this.connections.add(connection);
263
+ this.scheduleIdleCheck();
130
264
  },
131
- data(socket, data) {
265
+ data: (socket, data) => {
132
266
  socket.data.buffer.push(data.toString(), (line) => {
133
- void self.handleLine(socket.data.conn, line);
267
+ void this.respondToRequestLine(socket.data.connection, line);
134
268
  });
135
269
  },
136
- close(socket) {
137
- self.conns.delete(socket.data.conn);
138
- self.scheduleIdleCheck();
270
+ drain(socket) {
271
+ // drain can fire before open has attached data on some platforms;
272
+ // a throw here would take the whole daemon down with the socket
273
+ socket.data?.writer.drain();
274
+ },
275
+ close: (socket) => {
276
+ this.connections.delete(socket.data.connection);
277
+ this.scheduleIdleCheck();
139
278
  },
140
279
  error() {},
141
280
  },
@@ -143,21 +282,27 @@ export class DaemonServer {
143
282
  chmodSync(path, 0o600);
144
283
  writeFileSync(pidPath(this.home), String(process.pid));
145
284
  this.scheduleIdleCheck();
285
+
146
286
  return path;
147
287
  }
148
288
 
149
289
  stop(): void {
290
+ this.threadAgent.dispose();
291
+ this.core.dispose();
292
+ if (this.lockFd === null) return;
150
293
  this.server?.stop(true);
151
294
  this.server = null;
152
295
  rmSync(socketPath(this.home), { force: true });
153
296
  rmSync(pidPath(this.home), { force: true });
297
+ rmSync(ownerTokenPath(this.home), { force: true });
154
298
  if (this.idleTimer) clearTimeout(this.idleTimer);
155
299
  this.releaseLock();
156
300
  }
157
301
 
158
- private broadcast(e: DaemonEvent): void {
159
- const frame = JSON.stringify(e) + "\n";
160
- for (const c of this.conns) if (c.subscribed) c.write(frame);
302
+ private broadcast(event: DaemonEvent): void {
303
+ const frame = JSON.stringify(event) + "\n";
304
+
305
+ for (const connection of this.connections) if (connection.subscribed) connection.write(frame);
161
306
  this.scheduleIdleCheck();
162
307
  }
163
308
 
@@ -166,7 +311,7 @@ export class DaemonServer {
166
311
  if (this.idleExitMs <= 0) return;
167
312
  if (this.idleTimer) clearTimeout(this.idleTimer);
168
313
  this.idleTimer = setTimeout(() => {
169
- if (this.conns.size === 0 && !this.core.hasPendingSessions()) {
314
+ if (this.connections.size === 0 && !this.core.hasPendingSessions()) {
170
315
  this.stop();
171
316
  this.onIdleExit();
172
317
  } else {
@@ -175,76 +320,444 @@ export class DaemonServer {
175
320
  }, this.idleExitMs);
176
321
  }
177
322
 
178
- private async handleLine(conn: Conn, line: string): Promise<void> {
179
- let req: Request;
323
+ private async respondToRequestLine(connection: Connection, line: string): Promise<void> {
324
+ let request: Request;
325
+
180
326
  try {
181
- req = JSON.parse(line) as Request;
327
+ request = parseRequestFrame(line);
182
328
  } catch {
183
- conn.write(JSON.stringify({ id: -1, error: { code: "bad_json", message: "unparseable request" } }) + "\n");
329
+ connection.write(
330
+ JSON.stringify({ id: -1, error: { code: "bad_json", message: "unparseable request" } }) +
331
+ "\n",
332
+ );
333
+
184
334
  return;
185
335
  }
186
336
  try {
187
- const result = await this.dispatch(conn, req);
188
- conn.write(JSON.stringify({ id: req.id, result }) + "\n");
337
+ const result = await this.dispatch(connection, request);
338
+
339
+ connection.write(JSON.stringify({ id: request.id, result }) + "\n");
189
340
  } catch (err) {
190
341
  const code = err instanceof DaemonError ? err.code : "internal";
191
342
  const message = err instanceof Error ? err.message : String(err);
192
- conn.write(JSON.stringify({ id: req.id, error: { code, message } }) + "\n");
343
+
344
+ connection.write(JSON.stringify({ id: request.id, error: { code, message } }) + "\n");
193
345
  }
194
346
  }
195
347
 
196
- private async dispatch(conn: Conn, req: Request): Promise<unknown> {
197
- // The wire is untrusted JSON: validate before DaemonCore sees anything.
198
- if (typeof req.method !== "string" || !isKnownMethod(req.method)) {
199
- throw new DaemonError("unknown_method", `unknown method ${String(req.method)}`);
348
+ private async callAgentTool(threadId: string, name: string, input: string): Promise<string> {
349
+ const args = parseAgentToolInput(name, input);
350
+ const origin = this.core.sessionGet(threadId);
351
+
352
+ assertAgentToolScope(origin, args);
353
+ if (args.kind === "api" && args.method === "session.list") {
354
+ const { filter } = parseParams("session.list", args.params);
355
+
356
+ return JSON.stringify(!filter?.status || origin.status === filter.status ? [origin] : []);
200
357
  }
201
- const core = this.core;
202
- switch (req.method) {
203
- case "daemon.ping":
204
- return { pid: process.pid };
205
- case "daemon.shutdown":
206
- setTimeout(() => {
207
- this.stop();
208
- this.onIdleExit();
209
- }, 10);
210
- return {};
211
- case "events.subscribe":
212
- conn.subscribed = true;
213
- return {};
214
- case "session.create": {
215
- const p = parseParams("session.create", req.params);
216
- return core.sessionCreate({ workspace: p.workspace, artifact: p.artifact });
217
- }
218
- case "session.get":
219
- return core.sessionGet(parseParams("session.get", req.params).id);
220
- case "session.list":
221
- return core.sessionList(parseParams("session.list", req.params).filter);
222
- case "session.wait": {
223
- const p = parseParams("session.wait", req.params);
224
- return core.sessionWait(p.id, p.timeoutMs);
225
- }
226
- case "session.annotate": {
227
- const p = parseParams("session.annotate", req.params);
228
- return core.sessionAnnotate(p.id, p.annotation);
229
- }
230
- case "session.removeAnnotation": {
231
- const p = parseParams("session.removeAnnotation", req.params);
232
- return core.sessionRemoveAnnotation(p.id, p.annotationId);
358
+ if (args.kind === "reply") {
359
+ const thread = origin;
360
+ const comment = thread.annotations.find((entry) => entry.id === args.commentId);
361
+
362
+ if (!comment) return JSON.stringify(this.replyAgentComment(args));
363
+ const root =
364
+ thread.annotations.find((entry) => entry.id === (comment.replyTo ?? comment.id)) ?? comment;
365
+
366
+ return JSON.stringify(
367
+ this.core.sessionAnnotate(
368
+ args.id,
369
+ {
370
+ id: randomUUID(),
371
+ kind: "comment",
372
+ anchor: root.anchor,
373
+ target: root.target,
374
+ replyTo: root.id,
375
+ body: args.body,
376
+ author: "embedded-agent",
377
+ },
378
+ "Agent",
379
+ ),
380
+ );
381
+ }
382
+ const method = args.method;
383
+
384
+ if (!isKnownMethod(method)) throw new Error("Thread agent tool API method is unavailable");
385
+
386
+ return JSON.stringify(
387
+ await this.handlers[method](
388
+ { role: "owner", subscribed: false, write: () => {} },
389
+ { id: 0, method, params: args.params },
390
+ ),
391
+ );
392
+ }
393
+
394
+ private replyAgentComment(params: {
395
+ id: string;
396
+ commentId: string;
397
+ body: string;
398
+ }): ReturnType<ThreadAgentManager["reply"]> {
399
+ this.threadAgent.assertEnabled(params.id);
400
+
401
+ return this.threadAgent.reply(params.id, params.commentId, params.body);
402
+ }
403
+
404
+ private readonly handlers: Record<MethodName, MethodHandler> = {
405
+ "agent.configure": (_connection, request) => {
406
+ const params = parseParams("agent.configure", request.params);
407
+
408
+ this.threadAgent.assertEnabled(params.id);
409
+
410
+ return this.threadAgent.configure(params);
411
+ },
412
+ "agent.get": (_connection, request) => {
413
+ const { id } = parseParams("agent.get", request.params);
414
+
415
+ this.threadAgent.assertEnabled(id);
416
+
417
+ return this.threadAgent.get(id);
418
+ },
419
+ "agent.prompt": (_connection, request) => {
420
+ const params = parseParams("agent.prompt", request.params);
421
+
422
+ this.threadAgent.assertEnabled(params.id);
423
+
424
+ return this.threadAgent.prompt(params);
425
+ },
426
+ "agent.cancel": (_connection, request) => {
427
+ const { id } = parseParams("agent.cancel", request.params);
428
+
429
+ this.threadAgent.assertEnabled(id);
430
+
431
+ return this.threadAgent.cancel(id);
432
+ },
433
+ "agent.reply": (_connection, request) => {
434
+ const params = parseParams("agent.reply", request.params);
435
+
436
+ return this.replyAgentComment(params);
437
+ },
438
+ "agent.comment": (_connection, request) => {
439
+ const params = parseParams("agent.comment", request.params);
440
+
441
+ this.threadAgent.assertEnabled(params.id);
442
+
443
+ return this.threadAgent.comment(params);
444
+ },
445
+ "agent.permission": (_connection, request) => {
446
+ const params = parseParams("agent.permission", request.params);
447
+
448
+ this.threadAgent.assertEnabled(params.id);
449
+
450
+ return this.threadAgent.permission(params);
451
+ },
452
+ "daemon.ping": () => ({ pid: process.pid, version: this.version }),
453
+ "daemon.hello": (connection, request) => {
454
+ const params = parseParams("daemon.hello", request.params);
455
+
456
+ // ownership is proven, never declared: the token lives in the home
457
+ // directory the daemon serves, readable by its user alone
458
+ if (params.role === "owner" && params.token !== this.ownerToken) {
459
+ throw new DaemonError("forbidden", "owner token required");
233
460
  }
234
- case "session.setWorkingCopy": {
235
- const p = parseParams("session.setWorkingCopy", req.params);
236
- return core.sessionSetWorkingCopy(p.id, p.workingCopy);
461
+ if (params.clientVersion !== this.version) {
462
+ throw new DaemonError(
463
+ "version_mismatch",
464
+ `daemon is version ${this.version}, but this client is ${params.clientVersion ?? "unknown"}; align cueloop versions before restarting the daemon`,
465
+ );
237
466
  }
238
- case "session.resolve": {
239
- const p = parseParams("session.resolve", req.params);
240
- return core.sessionResolve(p.id, p.verdictKind, p.summary);
467
+
468
+ connection.role = params.role;
469
+ // identity is bound once, here; a non-owner never names it per call
470
+ if (params.role !== "owner" && params.author !== undefined) connection.author = params.author;
471
+
472
+ return {};
473
+ },
474
+ "daemon.shutdown": () => {
475
+ setTimeout(() => {
476
+ this.stop();
477
+ this.onIdleExit();
478
+ }, 10);
479
+
480
+ return {};
481
+ },
482
+ "events.subscribe": (connection) => {
483
+ connection.subscribed = true;
484
+
485
+ return {};
486
+ },
487
+ "session.create": (_connection, request) => {
488
+ const params = parseParams("session.create", request.params);
489
+
490
+ return this.core.sessionCreate({ workspace: params.workspace, artifact: params.artifact });
491
+ },
492
+ "session.get": (_connection, request) =>
493
+ this.core.sessionGet(parseParams("session.get", request.params).id),
494
+ "session.list": (_connection, request) =>
495
+ this.core.sessionList(parseParams("session.list", request.params).filter),
496
+ "session.wait": (_connection, request) => {
497
+ const params = parseParams("session.wait", request.params);
498
+
499
+ return this.core.sessionWait(params.id, params.timeoutMs);
500
+ },
501
+ "session.annotate": (_connection, request) => {
502
+ const params = parseParams("session.annotate", request.params);
503
+
504
+ if (this.threadAgent.isReadOnly(params.id, params.annotation.id))
505
+ throw new Error("Thread agent submitted comments are read-only");
506
+
507
+ return this.core.sessionAnnotate(params.id, params.annotation, params.authorName);
508
+ },
509
+ "session.comment": (_connection, request) => {
510
+ const params = parseParams("session.comment", request.params);
511
+
512
+ if (this.threadAgent.isReadOnly(params.id, params.annotation.id))
513
+ throw new Error("Thread agent submitted comments are read-only");
514
+
515
+ return this.core.sessionAnnotate(params.id, params.annotation, params.authorName);
516
+ },
517
+ "session.removeAnnotation": (connection, request) => {
518
+ const params = parseParams("session.removeAnnotation", request.params);
519
+
520
+ // the owner removes any comment; a non-owner only the ones of the author it is bound to
521
+ if (connection.role !== "owner" && connection.author === undefined) {
522
+ throw new DaemonError(
523
+ "forbidden",
524
+ "a non-owner connection removes comments as its bound author",
525
+ );
241
526
  }
242
- case "session.submitRevision": {
243
- const p = parseParams("session.submitRevision", req.params);
244
- return core.sessionSubmitRevision(p.id, p.content);
527
+
528
+ if (this.threadAgent.isReadOnly(params.id, params.annotationId))
529
+ throw new Error("Thread agent submitted comments are read-only");
530
+
531
+ return this.core.sessionRemoveAnnotation(
532
+ params.id,
533
+ params.annotationId,
534
+ connection.role === "owner" ? undefined : connection.author,
535
+ );
536
+ },
537
+ "session.setParticipantName": (connection, request) => {
538
+ const params = parseParams("session.setParticipantName", request.params);
539
+
540
+ // the owner names anyone; a non-owner names only the author it is bound to
541
+ if (connection.role !== "owner" && params.author !== connection.author) {
542
+ throw new DaemonError("forbidden", "a non-owner connection names only its bound author");
245
543
  }
246
- default:
247
- throw new DaemonError("unknown_method", `unknown method ${req.method}`);
544
+
545
+ return this.core.sessionSetParticipantName(params.id, params.author, params.name);
546
+ },
547
+ "session.setWorkingCopy": (_connection, request) => {
548
+ const params = parseParams("session.setWorkingCopy", request.params);
549
+
550
+ return this.core.sessionSetWorkingCopy(params.id, params.workingCopy, params.textCuts);
551
+ },
552
+ "session.cutBlock": (_connection, request) => {
553
+ const params = parseParams("session.cutBlock", request.params);
554
+
555
+ return this.core.sessionCutBlock(params.id, params.blockIndex);
556
+ },
557
+ "session.navigate": (_connection, request) => {
558
+ const params = parseParams("session.navigate", request.params);
559
+
560
+ return this.core.sessionNavigate(params.id, params.entryId, params.summary, params.branch);
561
+ },
562
+ "session.branch": (_connection, request) => {
563
+ const params = parseParams("session.branch", request.params);
564
+
565
+ return this.core.sessionBranch(params.id, params.name);
566
+ },
567
+ "session.switch": (_connection, request) => {
568
+ const params = parseParams("session.switch", request.params);
569
+
570
+ return this.core.sessionSwitch(params.id, params.branch);
571
+ },
572
+ "session.label": (_connection, request) => {
573
+ const params = parseParams("session.label", request.params);
574
+
575
+ return this.core.sessionLabel(params.id, params.label);
576
+ },
577
+ "session.fork": (_connection, request) => {
578
+ const params = parseParams("session.fork", request.params);
579
+
580
+ return this.core.sessionFork(params.id);
581
+ },
582
+ "session.restoreBlock": (_connection, request) => {
583
+ const params = parseParams("session.restoreBlock", request.params);
584
+
585
+ return this.core.sessionRestoreBlock(params.id, params.baseBlockIndex, params.line);
586
+ },
587
+ "session.curate": (_connection, request) => {
588
+ const params = parseParams("session.curate", request.params);
589
+
590
+ return this.core.sessionCurate(params.id, params.rejections);
591
+ },
592
+ "session.setViewed": (_connection, request) => {
593
+ const params = parseParams("session.setViewed", request.params);
594
+
595
+ return this.core.sessionSetViewed(params.id, params.viewedPaths);
596
+ },
597
+ "session.setTitle": (_connection, request) => {
598
+ const params = parseParams("session.setTitle", request.params);
599
+
600
+ return this.core.sessionSetTitle(params.id, params.title);
601
+ },
602
+ "session.projectFiles": (_connection, request) =>
603
+ this.core.projectFiles(parseParams("session.projectFiles", request.params).id),
604
+ "session.fileContents": (_connection, request) => {
605
+ const params = parseParams("session.fileContents", request.params);
606
+
607
+ return this.core.fileContents(params.id, params.path);
608
+ },
609
+ "repo.files": (_connection, request) =>
610
+ this.core.repoFiles(parseParams("repo.files", request.params).cwd),
611
+ "repo.fileContents": (_connection, request) => {
612
+ const params = parseParams("repo.fileContents", request.params);
613
+
614
+ return this.core.repoFileContents(params.cwd, params.path);
615
+ },
616
+ "repo.changes": (_connection, request) =>
617
+ this.core.repoChanges(parseParams("repo.changes", request.params).cwd),
618
+ "repo.diff": (_connection, request) => {
619
+ const params = parseParams("repo.diff", request.params);
620
+
621
+ return this.core.repoDiff(params.cwd, params.vcs);
622
+ },
623
+ "session.workbench": (_connection, request) =>
624
+ this.core.workbenchSession(parseParams("session.workbench", request.params).cwd),
625
+ "session.workbenchReview": (_connection, request) =>
626
+ this.core.workbenchReview(parseParams("session.workbenchReview", request.params).cwd),
627
+ "session.refreshDiff": (_connection, request) => {
628
+ const params = parseParams("session.refreshDiff", request.params);
629
+
630
+ return this.core.sessionRefreshDiff(params.id);
631
+ },
632
+ "session.setShares": (_connection, request) => {
633
+ const params = parseParams("session.setShares", request.params);
634
+
635
+ return this.core.sessionSetShares(params.id, params.shares);
636
+ },
637
+ "session.delete": (_connection, request) => {
638
+ const { id } = parseParams("session.delete", request.params);
639
+
640
+ this.core.sessionDelete(id);
641
+ this.threadAgent.remove(id);
642
+
643
+ return {};
644
+ },
645
+ "session.mergeShared": (_connection, request) => {
646
+ const params = parseParams("session.mergeShared", request.params);
647
+
648
+ return this.core.sessionMergeShared(params.id, {
649
+ shareId: params.shareId,
650
+ annotations: params.annotations,
651
+ participants: params.participants,
652
+ removals: params.removals,
653
+ });
654
+ },
655
+ "session.sendMessage": (_connection, request) => {
656
+ const params = parseParams("session.sendMessage", request.params);
657
+
658
+ return this.core.sessionSendMessage(
659
+ params.id,
660
+ params.outcome,
661
+ params.summary,
662
+ params.actionBodies,
663
+ params.operationId,
664
+ );
665
+ },
666
+ "harness.bind": (_connection, request) => {
667
+ const params = parseParams("harness.bind", request.params);
668
+
669
+ return this.core.harnessBind(params);
670
+ },
671
+ "harness.getBinding": (_connection, request) => {
672
+ const params = parseParams("harness.getBinding", request.params);
673
+
674
+ return this.core.harnessGetBinding(params.bindingId);
675
+ },
676
+ "harness.bindingsForSession": (_connection, request) => {
677
+ const params = parseParams("harness.bindingsForSession", request.params);
678
+
679
+ return this.core.harnessBindingsForSession(params.harness, params.harnessSessionId);
680
+ },
681
+ "harness.consumeApprovedRetry": (_connection, request) => {
682
+ const params = parseParams("harness.consumeApprovedRetry", request.params);
683
+
684
+ return this.core.harnessConsumeApprovedRetry(
685
+ params.bindingId,
686
+ params.messageId,
687
+ params.content,
688
+ );
689
+ },
690
+ "delivery.pending": (_connection, request) => {
691
+ const params = parseParams("delivery.pending", request.params);
692
+
693
+ return this.core.deliveryPending(params.bindingId);
694
+ },
695
+ "delivery.acknowledge": (_connection, request) => {
696
+ const params = parseParams("delivery.acknowledge", request.params);
697
+
698
+ return this.core.deliveryAcknowledge(params.deliveryId);
699
+ },
700
+ "session.submitRevision": (_connection, request) => {
701
+ const params = parseParams("session.submitRevision", request.params);
702
+
703
+ return this.core.sessionSubmitRevision(
704
+ params.id,
705
+ params.content,
706
+ params.addressedAnnotationIds,
707
+ params.files,
708
+ params.source,
709
+ );
710
+ },
711
+ "herdr.getThreadSurface": (_connection, request) =>
712
+ this.core.herdrGetThreadSurface(parseParams("herdr.getThreadSurface", request.params).id),
713
+ "herdr.setThreadSurface": (_connection, request) => {
714
+ const params = parseParams("herdr.setThreadSurface", request.params);
715
+
716
+ this.core.herdrSetThreadSurface(params.id, {
717
+ tabId: params.tabId,
718
+ paneId: params.paneId,
719
+ mode: params.mode,
720
+ layout: params.layout,
721
+ });
722
+
723
+ return {};
724
+ },
725
+ "ghostty.getThreadSurface": (_connection, request) =>
726
+ this.core.ghosttyGetThreadSurface(parseParams("ghostty.getThreadSurface", request.params).id),
727
+ "ghostty.setThreadSurface": (_connection, request) => {
728
+ const params = parseParams("ghostty.setThreadSurface", request.params);
729
+
730
+ this.core.ghosttySetThreadSurface(params.id, { terminalId: params.terminalId });
731
+
732
+ return {};
733
+ },
734
+ "ghostty.claimThreadSurface": (_connection, request) =>
735
+ this.core.ghosttyClaimThreadSurface(
736
+ parseParams("ghostty.claimThreadSurface", request.params).id,
737
+ ),
738
+ "ghostty.releaseThreadSurface": (_connection, request) => {
739
+ this.core.ghosttyReleaseThreadSurface(
740
+ parseParams("ghostty.releaseThreadSurface", request.params).id,
741
+ );
742
+
743
+ return {};
744
+ },
745
+ };
746
+
747
+ private async dispatch(connection: Connection, request: Request): Promise<Response["result"]> {
748
+ // The wire is untrusted JSON: validate before DaemonCore sees anything.
749
+ if (!isKnownMethod(request.method)) {
750
+ throw new DaemonError("unknown_method", `unknown method ${request.method}`);
248
751
  }
752
+ // Capability gate: a capped role (a review-side agent) cannot escalate past
753
+ // read + annotate, whatever primitive it sends.
754
+ if (!roleAllowsMethod(connection.role, request.method)) {
755
+ throw new DaemonError("forbidden", `role ${connection.role} cannot call ${request.method}`);
756
+ }
757
+ if (!Object.hasOwn(this.handlers, request.method)) {
758
+ throw new DaemonError("unknown_method", `unknown method ${request.method}`);
759
+ }
760
+
761
+ return this.handlers[request.method](connection, request);
249
762
  }
250
763
  }