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