crossroom 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1148 @@
1
+ import { createRequire as __parleyRequire } from 'node:module'; const require = __parleyRequire(import.meta.url);
2
+ import {
3
+ insideLocation,
4
+ sameLocation
5
+ } from "./chunk-5TLKYAI3.mjs";
6
+ import {
7
+ external_exports,
8
+ oneLine,
9
+ resolveBin
10
+ } from "./chunk-O3GNP4DR.mjs";
11
+ import "./chunk-P7MSGDOB.mjs";
12
+
13
+ // src/discovery/index.ts
14
+ import path7 from "node:path";
15
+
16
+ // ../shared/src/sessions.ts
17
+ var Harness = external_exports.enum(["opencode", "codex", "claude", "grok"]);
18
+
19
+ // src/discovery/native.ts
20
+ async function bounded(operation, milliseconds, message) {
21
+ let timer;
22
+ try {
23
+ return await Promise.race([
24
+ operation,
25
+ new Promise((_, reject) => {
26
+ timer = setTimeout(() => reject(new Error(message)), milliseconds);
27
+ })
28
+ ]);
29
+ } finally {
30
+ clearTimeout(timer);
31
+ }
32
+ }
33
+
34
+ // src/discovery/claude.ts
35
+ import path4 from "node:path";
36
+
37
+ // src/discovery/claude-records.ts
38
+ import path3 from "node:path";
39
+
40
+ // src/discovery/files.ts
41
+ import { constants } from "node:fs";
42
+ import { open, readdir, realpath, stat } from "node:fs/promises";
43
+ import path from "node:path";
44
+ var FORBIDDEN = [
45
+ /\.key$/i,
46
+ /\.pem$/i,
47
+ /^auth\.json$/i,
48
+ /credential/i,
49
+ /secret/i,
50
+ /token/i,
51
+ /password/i,
52
+ /^service\.json$/i,
53
+ /^\.env/i
54
+ ];
55
+ function normalizedName(file) {
56
+ let name = path.win32.basename(file);
57
+ const stream = name.indexOf(":");
58
+ if (stream >= 0) name = name.slice(0, stream);
59
+ return name.replace(/[. ]+$/, "").toLowerCase();
60
+ }
61
+ function forbidden(file) {
62
+ const name = normalizedName(file);
63
+ return FORBIDDEN.some((pattern) => pattern.test(name));
64
+ }
65
+ var ForbiddenFile = class extends Error {
66
+ constructor() {
67
+ super("Discovery does not open credential files.");
68
+ }
69
+ };
70
+ function sameFile(a, b, platform = process.platform) {
71
+ if (a.ino !== b.ino) return false;
72
+ return a.dev === b.dev || platform === "win32" && (a.dev === 0n || b.dev === 0n);
73
+ }
74
+ var OPEN_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
75
+ async function openWithin(file, scope) {
76
+ if (forbidden(file)) throw new ForbiddenFile();
77
+ let real;
78
+ let root;
79
+ try {
80
+ [real, root] = await Promise.all([realpath(file), realpath(scope.root)]);
81
+ } catch {
82
+ return void 0;
83
+ }
84
+ if (forbidden(real) || !within(real, root)) return void 0;
85
+ let checked;
86
+ try {
87
+ checked = await stat(real, { bigint: true });
88
+ } catch {
89
+ return void 0;
90
+ }
91
+ if (!checked.isFile()) return void 0;
92
+ let handle;
93
+ try {
94
+ handle = await open(real, OPEN_FLAGS);
95
+ const opened = await handle.stat({ bigint: true });
96
+ if (opened.isFile() && sameFile(opened, checked)) return handle;
97
+ } catch {
98
+ }
99
+ await handle?.close().catch(() => {
100
+ });
101
+ return void 0;
102
+ }
103
+ async function readSmall(file, maxBytes, scope) {
104
+ const handle = await openWithin(file, scope);
105
+ if (!handle) return void 0;
106
+ try {
107
+ const { size } = await handle.stat();
108
+ if (size > maxBytes) return void 0;
109
+ const buffer = Buffer.alloc(size);
110
+ const { bytesRead } = await handle.read(buffer, 0, size, 0);
111
+ return buffer.subarray(0, bytesRead).toString("utf8");
112
+ } catch {
113
+ return void 0;
114
+ } finally {
115
+ await handle.close().catch(() => {
116
+ });
117
+ }
118
+ }
119
+ async function readPart(file, maxBytes, scope) {
120
+ const handle = await openWithin(file, scope);
121
+ if (!handle) return void 0;
122
+ try {
123
+ const { size } = await handle.stat();
124
+ const length = Math.min(size, maxBytes);
125
+ const buffer = Buffer.alloc(length);
126
+ const { bytesRead } = await handle.read(buffer, 0, length, scope.fromEnd ? size - length : 0);
127
+ return { text: buffer.subarray(0, bytesRead).toString("utf8"), whole: length === size };
128
+ } catch {
129
+ return void 0;
130
+ } finally {
131
+ await handle.close().catch(() => {
132
+ });
133
+ }
134
+ }
135
+ async function readFirstLine(file, maxBytes, scope) {
136
+ const part = await readPart(file, maxBytes, scope);
137
+ if (!part) return void 0;
138
+ const end = part.text.indexOf("\n");
139
+ if (end >= 0) return part.text.slice(0, end).replace(/\r$/, "");
140
+ return part.whole ? part.text : void 0;
141
+ }
142
+ async function listDir(dir) {
143
+ try {
144
+ return await readdir(dir);
145
+ } catch {
146
+ return [];
147
+ }
148
+ }
149
+ async function modifiedAt(file) {
150
+ try {
151
+ return (await stat(file)).mtimeMs;
152
+ } catch {
153
+ return void 0;
154
+ }
155
+ }
156
+ function parseJson(text) {
157
+ if (text === void 0) return void 0;
158
+ try {
159
+ return JSON.parse(text);
160
+ } catch {
161
+ return void 0;
162
+ }
163
+ }
164
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
165
+ var str = (value, max = 4096) => typeof value === "string" && value.length > 0 && value.length <= max ? value : void 0;
166
+ var num = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
167
+ var time = (value) => {
168
+ if (typeof value === "number" && Number.isFinite(value)) return value < 1e12 ? value * 1e3 : value;
169
+ if (typeof value === "string") {
170
+ const ms = Date.parse(value);
171
+ return Number.isFinite(ms) ? ms : void 0;
172
+ }
173
+ return void 0;
174
+ };
175
+ var foldCase = process.platform === "win32" || process.platform === "darwin";
176
+ function samePath(a, b) {
177
+ return sameLocation(a, b, { foldCase });
178
+ }
179
+ function insidePath(child, parent) {
180
+ return insideLocation(child, parent, { foldCase });
181
+ }
182
+ function within(child, parent) {
183
+ const fold = (p) => process.platform === "win32" || process.platform === "darwin" ? p.toLowerCase() : p;
184
+ const relative = path.relative(fold(path.resolve(parent)), fold(path.resolve(child)));
185
+ return relative === "" || relative !== ".." && !relative.startsWith(".." + path.sep) && !path.isAbsolute(relative);
186
+ }
187
+
188
+ // src/discovery/probe.ts
189
+ import os from "node:os";
190
+
191
+ // src/discovery/process.ts
192
+ import { execFile } from "node:child_process";
193
+ import { openSync, closeSync } from "node:fs";
194
+ import { readFile } from "node:fs/promises";
195
+ import path2 from "node:path";
196
+ var validPid = (pid) => Number.isSafeInteger(pid) && pid > 0;
197
+ function pidAlive(pid) {
198
+ if (!validPid(pid)) return false;
199
+ try {
200
+ process.kill(pid, 0);
201
+ return true;
202
+ } catch (error) {
203
+ return error.code === "EPERM";
204
+ }
205
+ }
206
+ function run(file, args, options) {
207
+ return new Promise((resolve, reject) => {
208
+ execFile(
209
+ file,
210
+ args,
211
+ { encoding: "utf8", timeout: options.timeoutMs, maxBuffer: options.maxBytes, windowsHide: true, shell: false, cwd: options.cwd },
212
+ (error, stdout) => error ? reject(error) : resolve(stdout)
213
+ );
214
+ });
215
+ }
216
+ var FILETIME_EPOCH = 116444736000000000n;
217
+ function fileTimeToMs(value) {
218
+ if (!/^\d{15,20}$/.test(value)) return void 0;
219
+ const ms = Number((BigInt(value) - FILETIME_EPOCH) / 10000n);
220
+ return Number.isFinite(ms) && ms > 0 ? ms : void 0;
221
+ }
222
+ var powershell = () => path2.join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
223
+ async function processStartedAt(pid, timeoutMs = 3e3) {
224
+ if (!validPid(pid)) return void 0;
225
+ try {
226
+ if (process.platform === "win32") {
227
+ const out2 = await run(
228
+ powershell(),
229
+ ["-NoProfile", "-NonInteractive", "-Command", `(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToFileTimeUtc()`],
230
+ { timeoutMs, maxBytes: 4096 }
231
+ );
232
+ return fileTimeToMs(out2.trim());
233
+ }
234
+ if (process.platform === "linux") {
235
+ const stat2 = await readFile(`/proc/${pid}/stat`, "utf8");
236
+ const fields = stat2.slice(stat2.lastIndexOf(")") + 2).split(" ");
237
+ const ticks = Number(fields[19]);
238
+ const boot = /^btime (\d+)$/m.exec(await readFile("/proc/stat", "utf8"))?.[1];
239
+ return Number.isFinite(ticks) && boot ? Number(boot) * 1e3 + ticks * 10 : void 0;
240
+ }
241
+ const ps = resolveBin("ps");
242
+ if (!ps) return void 0;
243
+ const out = await run(ps, ["-o", "lstart=", "-p", String(pid)], { timeoutMs, maxBytes: 4096 });
244
+ const ms = Date.parse(out.trim());
245
+ return Number.isFinite(ms) ? ms : void 0;
246
+ } catch {
247
+ return void 0;
248
+ }
249
+ }
250
+ async function locksHeld(files) {
251
+ const result = /* @__PURE__ */ new Map();
252
+ if (!files.length) return result;
253
+ if (process.platform === "win32") {
254
+ for (const file of files) {
255
+ try {
256
+ closeSync(openSync(file, "r+"));
257
+ result.set(file, false);
258
+ } catch (error) {
259
+ const code = error.code;
260
+ result.set(file, code === "EBUSY" || code === "EPERM" ? true : code === "ENOENT" ? false : void 0);
261
+ }
262
+ }
263
+ return result;
264
+ }
265
+ const lsof = resolveBin("lsof");
266
+ if (!lsof) {
267
+ for (const file of files) result.set(file, void 0);
268
+ return result;
269
+ }
270
+ let out = "";
271
+ try {
272
+ out = await run(lsof, ["-Fn", "--", ...files], { timeoutMs: 3e3, maxBytes: 256 * 1024 });
273
+ } catch (error) {
274
+ const failed = error;
275
+ if (failed.code !== 1 || failed.killed) {
276
+ for (const file of files) result.set(file, void 0);
277
+ return result;
278
+ }
279
+ out = failed.stdout ?? "";
280
+ }
281
+ const open2 = new Set(
282
+ out.split("\n").filter((line) => line.startsWith("n")).map((line) => path2.basename(line.slice(1)))
283
+ );
284
+ for (const file of files) result.set(file, open2.has(path2.basename(file)));
285
+ return result;
286
+ }
287
+ var STARTED_TTL_MS = 1e4;
288
+ var started = /* @__PURE__ */ new Map();
289
+ function cachedStartedAt(pid) {
290
+ const now = Date.now();
291
+ const hit = started.get(pid);
292
+ if (hit && now - hit.at < STARTED_TTL_MS) return hit.value;
293
+ if (started.size > 256) {
294
+ for (const [key, entry] of started) if (now - entry.at >= STARTED_TTL_MS) started.delete(key);
295
+ }
296
+ const value = processStartedAt(pid);
297
+ started.set(pid, { at: now, value });
298
+ return value;
299
+ }
300
+ var systemProcess = {
301
+ alive: pidAlive,
302
+ startedAt: cachedStartedAt,
303
+ locksHeld,
304
+ run
305
+ };
306
+ async function sameProcess(ops, pid, recorded) {
307
+ if (!ops.alive(pid)) return false;
308
+ if (recorded.start === void 0 && recorded.after === void 0) return true;
309
+ const observed = await ops.startedAt(pid);
310
+ if (observed === void 0) return true;
311
+ if (recorded.start !== void 0) return Math.abs(observed - recorded.start) <= 1e3;
312
+ return observed <= recorded.after + 2e3;
313
+ }
314
+
315
+ // src/discovery/probe.ts
316
+ function probeContext(partial) {
317
+ return {
318
+ home: partial.home ?? os.homedir(),
319
+ env: partial.env ?? (partial.home ? {} : process.env),
320
+ process: partial.process ?? systemProcess,
321
+ now: partial.now ?? Date.now,
322
+ driver: partial.driver
323
+ };
324
+ }
325
+ var SESSION_ID = /^[0-9A-Za-z][0-9A-Za-z_-]{0,199}$/;
326
+ var SESSION_STATUS = (value) => value === "idle" || value === "busy" || value === "waiting" ? value : "unknown";
327
+
328
+ // src/discovery/claude-records.ts
329
+ var HEAD_BYTES = 64 * 1024;
330
+ var TAIL_BYTES = 64 * 1024;
331
+ var FILES_MAX = 2e3;
332
+ var PROJECTS_MAX = 2e3;
333
+ var TITLE_MAX = 1e3;
334
+ var SESSION_FILE = /^([0-9A-Za-z][0-9A-Za-z_-]{0,199})\.jsonl$/;
335
+ var lines = (text) => text.split("\n").map((line) => line.replace(/\r$/, ""));
336
+ function promptOf(entry) {
337
+ if (entry.type !== "user" || entry.isMeta === true || entry.isSidechain === true || !isRecord(entry.message)) return void 0;
338
+ const content = entry.message.content;
339
+ const text = typeof content === "string" ? content : Array.isArray(content) ? content.map((part) => isRecord(part) && part.type === "text" && typeof part.text === "string" ? part.text : "").join(" ") : "";
340
+ const trimmed = text.trim();
341
+ if (!trimmed || trimmed.startsWith("<")) return void 0;
342
+ return trimmed.slice(0, TITLE_MAX);
343
+ }
344
+ async function readSession(file, id, root, lastModified) {
345
+ const head = await readPart(file, HEAD_BYTES, { root });
346
+ if (!head) return void 0;
347
+ let cwd;
348
+ let entrypoint;
349
+ let firstPrompt;
350
+ const headLines = lines(head.text);
351
+ if (!head.whole) headLines.pop();
352
+ for (const line of headLines) {
353
+ const entry = parseJson(line);
354
+ if (!isRecord(entry)) continue;
355
+ cwd ??= str(entry.cwd);
356
+ entrypoint ??= str(entry.entrypoint, 80);
357
+ firstPrompt ??= promptOf(entry);
358
+ if (cwd && entrypoint && firstPrompt) break;
359
+ }
360
+ const tail = head.whole ? head : await readPart(file, TAIL_BYTES, { root, fromEnd: true });
361
+ let customTitle;
362
+ let aiTitle;
363
+ let summary2;
364
+ if (tail) {
365
+ const tailLines = lines(tail.text);
366
+ if (!tail.whole) tailLines.shift();
367
+ for (const line of tailLines.reverse()) {
368
+ const entry = parseJson(line);
369
+ if (!isRecord(entry)) continue;
370
+ if (entry.type === "custom-title") customTitle ??= str(entry.customTitle, TITLE_MAX);
371
+ else if (entry.type === "ai-title") aiTitle ??= str(entry.aiTitle, TITLE_MAX);
372
+ else if (entry.type === "summary") summary2 ??= str(entry.summary, TITLE_MAX);
373
+ }
374
+ }
375
+ return {
376
+ info: {
377
+ sessionId: id,
378
+ summary: customTitle ?? aiTitle ?? summary2 ?? firstPrompt ?? "",
379
+ lastModified,
380
+ ...customTitle ? { customTitle } : {},
381
+ ...firstPrompt ? { firstPrompt } : {},
382
+ ...cwd ? { cwd } : {}
383
+ },
384
+ programmatic: entrypoint?.startsWith("sdk") === true
385
+ };
386
+ }
387
+ function claudeRecords(configDir) {
388
+ const projects = path3.join(configDir, "projects");
389
+ const sessionFiles2 = async () => {
390
+ const folders = (await listDir(projects)).slice(0, PROJECTS_MAX);
391
+ const found = [];
392
+ for (const folder of folders) {
393
+ for (const name of await listDir(path3.join(projects, folder))) {
394
+ const match = SESSION_FILE.exec(name);
395
+ if (!match) continue;
396
+ const file = path3.join(projects, folder, name);
397
+ const at = await modifiedAt(file);
398
+ if (at !== void 0) found.push({ file, id: match[1], at });
399
+ }
400
+ }
401
+ return found.sort((a, b) => b.at - a.at).slice(0, FILES_MAX);
402
+ };
403
+ return {
404
+ async listSessions({ dir, limit = 50, includeProgrammatic = true }) {
405
+ const out = [];
406
+ for (const { file, id, at } of await sessionFiles2()) {
407
+ if (out.length >= limit) break;
408
+ const read = await readSession(file, id, configDir, at);
409
+ if (!read || read.programmatic && !includeProgrammatic) continue;
410
+ if (dir && !(read.info.cwd && samePath(read.info.cwd, dir))) continue;
411
+ out.push(read.info);
412
+ }
413
+ return out;
414
+ },
415
+ async getSessionInfo(id) {
416
+ if (!SESSION_ID.test(id)) return void 0;
417
+ for (const folder of (await listDir(projects)).slice(0, PROJECTS_MAX)) {
418
+ const file = path3.join(projects, folder, id + ".jsonl");
419
+ const at = await modifiedAt(file);
420
+ if (at === void 0) continue;
421
+ return (await readSession(file, id, configDir, at))?.info;
422
+ }
423
+ return void 0;
424
+ }
425
+ };
426
+ }
427
+
428
+ // src/discovery/claude.ts
429
+ var SESSION_FILE2 = /^\d+\.json$/;
430
+ var SESSION_FILE_MAX = 64 * 1024;
431
+ var SESSION_FILES_MAX = 512;
432
+ var AGENTS_TIMEOUT_MS = 6e3;
433
+ var AGENTS_MAX_BYTES = 512 * 1024;
434
+ function allowlisted(value) {
435
+ if (!isRecord(value)) return void 0;
436
+ const pid = num(value.pid);
437
+ const sessionId = str(value.sessionId, 200);
438
+ if (!pid || !Number.isSafeInteger(pid) || pid <= 0 || !sessionId) return void 0;
439
+ return {
440
+ pid,
441
+ sessionId,
442
+ cwd: str(value.cwd),
443
+ status: str(value.status, 40),
444
+ kind: str(value.kind, 40),
445
+ entrypoint: str(value.entrypoint, 80),
446
+ procStart: str(value.procStart, 40),
447
+ startedAt: num(value.startedAt),
448
+ name: str(value.name, 1e3),
449
+ version: str(value.version, 80)
450
+ };
451
+ }
452
+ var claudeDir = (ctx) => ctx.env.CLAUDE_CONFIG_DIR || path4.join(ctx.home, ".claude");
453
+ async function sessionFiles(ctx) {
454
+ const dir = path4.join(claudeDir(ctx), "sessions");
455
+ const names = (await listDir(dir)).filter((name) => SESSION_FILE2.test(name)).slice(0, SESSION_FILES_MAX);
456
+ const records = await Promise.all(
457
+ names.map(async (name) => {
458
+ const record = allowlisted(parseJson(await readSmall(path4.join(dir, name), SESSION_FILE_MAX, { root: claudeDir(ctx) })));
459
+ return record && record.pid === Number(name.slice(0, -".json".length)) ? record : void 0;
460
+ })
461
+ );
462
+ return records.filter((record) => record !== void 0);
463
+ }
464
+ async function agentsCli(ctx) {
465
+ const binary = ctx.driver().executable ?? resolveBin("claude");
466
+ if (!binary) throw new Error("Claude Code is not on PATH");
467
+ const out = await ctx.process.run(binary, ["agents", "--json"], { timeoutMs: AGENTS_TIMEOUT_MS, maxBytes: AGENTS_MAX_BYTES });
468
+ const value = parseJson(out);
469
+ if (!Array.isArray(value)) throw new Error("claude agents --json printed something other than a list");
470
+ return value.map(allowlisted).filter((record) => record !== void 0);
471
+ }
472
+ function claudeSurface(record) {
473
+ if (record.kind === "background") return "background";
474
+ if (record.entrypoint === "claude-vscode") return "vscode";
475
+ if (record.entrypoint === "cli") return "terminal";
476
+ return "unknown";
477
+ }
478
+ var claudeKind = (record) => record.entrypoint?.startsWith("sdk") ? "exec" : "interactive";
479
+ var recordedStart = (record) => process.platform === "win32" && record.procStart ? fileTimeToMs(record.procStart) : void 0;
480
+ function liveState(record, procStart) {
481
+ return {
482
+ pid: record.pid,
483
+ ...procStart !== void 0 ? { procStart: String(procStart) } : {},
484
+ status: SESSION_STATUS(record.status),
485
+ surface: claudeSurface(record),
486
+ exit: "pid"
487
+ };
488
+ }
489
+ var fromNative = (session) => ({
490
+ nativeId: session.id,
491
+ cwd: session.cwd,
492
+ title: session.title,
493
+ lastActiveAt: session.updatedAt,
494
+ live: null,
495
+ source: "sdk",
496
+ nativeVersion: session.version
497
+ });
498
+ function claudeProbe(ctx, sdk = claudeRecords(claudeDir(ctx))) {
499
+ const live = async (id, hint) => {
500
+ if (hint?.pid) {
501
+ if (!await sameProcess(ctx.process, hint.pid, { start: hint.procStart ? Number(hint.procStart) : void 0 })) return null;
502
+ const record = allowlisted(parseJson(await readSmall(path4.join(claudeDir(ctx), "sessions", hint.pid + ".json"), SESSION_FILE_MAX, { root: claudeDir(ctx) })));
503
+ return liveState(record ?? { pid: hint.pid, sessionId: id }, hint.procStart ? Number(hint.procStart) : void 0);
504
+ }
505
+ for (const record of await sessionFiles(ctx)) {
506
+ if (record.sessionId !== id || !ctx.process.alive(record.pid)) continue;
507
+ const start = recordedStart(record);
508
+ if (await sameProcess(ctx.process, record.pid, { start, after: start === void 0 ? record.startedAt : void 0 }))
509
+ return liveState(record, start);
510
+ }
511
+ return null;
512
+ };
513
+ return {
514
+ harness: "claude",
515
+ live,
516
+ async list(options) {
517
+ const files = await sessionFiles(ctx);
518
+ let records;
519
+ let liveSource = "cli";
520
+ let detail;
521
+ try {
522
+ const byPid = new Map(files.map((record) => [record.pid, record]));
523
+ records = (await agentsCli(ctx)).map((record) => {
524
+ const file = byPid.get(record.pid);
525
+ return { ...record, entrypoint: file?.entrypoint, procStart: file?.procStart, version: file?.version };
526
+ });
527
+ } catch {
528
+ liveSource = "files";
529
+ records = files.filter((record) => ctx.process.alive(record.pid));
530
+ }
531
+ if (options.directory) records = records.filter((record) => record.cwd && samePath(record.cwd, options.directory));
532
+ const sessions = /* @__PURE__ */ new Map();
533
+ let source = liveSource;
534
+ let truncated = false;
535
+ if (!options.liveOnly) {
536
+ try {
537
+ const driver = ctx.driver();
538
+ const listed = driver.listSessions ? (await driver.listSessions({ limit: options.limit, directory: options.directory, signal: options.signal })).map(fromNative) : (await sdk.listSessions({ dir: options.directory, limit: options.limit, includeProgrammatic: false })).map(
539
+ (info) => fromNative({ id: info.sessionId, cwd: info.cwd, title: info.customTitle ?? info.summary, updatedAt: info.lastModified })
540
+ );
541
+ for (const session of listed) sessions.set(session.nativeId, session);
542
+ truncated = listed.length >= options.limit;
543
+ source = "sdk";
544
+ } catch (error) {
545
+ detail = "Recent Claude sessions could not be listed: " + (error instanceof Error ? error.message : String(error));
546
+ }
547
+ }
548
+ for (const record of records) {
549
+ const state = liveState(record, recordedStart(record));
550
+ const known = sessions.get(record.sessionId);
551
+ if (known) {
552
+ known.live = state;
553
+ known.nativeVersion ??= record.version;
554
+ known.kind ??= claudeKind(record);
555
+ known.lastActiveAt = Math.max(known.lastActiveAt ?? 0, record.startedAt ?? 0) || void 0;
556
+ } else
557
+ sessions.set(record.sessionId, {
558
+ nativeId: record.sessionId,
559
+ cwd: record.cwd,
560
+ title: record.name,
561
+ lastActiveAt: record.startedAt,
562
+ live: state,
563
+ source: liveSource,
564
+ nativeVersion: record.version,
565
+ kind: claudeKind(record)
566
+ });
567
+ }
568
+ return { sessions: [...sessions.values()], source, truncated, detail };
569
+ },
570
+ async find(id) {
571
+ if (!SESSION_ID.test(id)) return void 0;
572
+ const record = (await sessionFiles(ctx)).find((entry) => entry.sessionId === id);
573
+ const info = await sdk.getSessionInfo(id).catch(() => void 0);
574
+ if (!record && !info) return void 0;
575
+ let state = null;
576
+ if (record && ctx.process.alive(record.pid)) {
577
+ const start = recordedStart(record);
578
+ if (await sameProcess(ctx.process, record.pid, { start, after: start === void 0 ? record.startedAt : void 0 }))
579
+ state = liveState(record, start ?? await ctx.process.startedAt(record.pid));
580
+ }
581
+ return {
582
+ nativeId: id,
583
+ cwd: info?.cwd ?? record?.cwd,
584
+ title: info ? info.customTitle ?? info.summary : record?.name,
585
+ lastActiveAt: info?.lastModified ?? record?.startedAt,
586
+ live: state,
587
+ source: info ? "sdk" : "files",
588
+ nativeVersion: record?.version,
589
+ ...record ? { kind: claudeKind(record) } : {}
590
+ };
591
+ }
592
+ };
593
+ }
594
+
595
+ // src/discovery/codex.ts
596
+ import path5 from "node:path";
597
+ var META_MAX = 256 * 1024;
598
+ var INDEX_MAX = 2 * 1024 * 1024;
599
+ var ROLLOUTS_MAX = 5e3;
600
+ var ROLLOUT = /^rollout-.+-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i;
601
+ var CODEX_ID = /^[0-9A-Za-z][0-9A-Za-z_-]{0,99}$/;
602
+ var LOCK = /^([0-9A-Za-z][0-9A-Za-z_-]{0,99})\.lock$/;
603
+ var codexDir = (env, home) => env.CODEX_HOME || path5.join(home, ".codex");
604
+ var codexLockFile = (dir, threadId) => path5.join(dir, "thread-writer-locks", threadId + ".lock");
605
+ function codexOrigin(source, originator, parentId) {
606
+ const name = typeof source === "string" ? source : isRecord(source) ? Object.keys(source)[0] : void 0;
607
+ if (parentId || name && /^sub_?agent/i.test(name)) return { kind: "subagent", surface: "background" };
608
+ const kind = name === "exec" ? "exec" : "interactive";
609
+ if (originator && /desktop/i.test(originator)) return { kind, surface: "desktop" };
610
+ if (name === "vscode" || originator === "codex_vscode") return { kind, surface: "vscode" };
611
+ if (name === "cli" || originator === "codex_cli_rs") return { kind, surface: "terminal" };
612
+ return { kind, surface: "unknown" };
613
+ }
614
+ function meta(line) {
615
+ const value = parseJson(line);
616
+ if (!isRecord(value) || value.type !== "session_meta" || !isRecord(value.payload)) return void 0;
617
+ const payload = value.payload;
618
+ const id = str(payload.id, 100);
619
+ if (!id || !CODEX_ID.test(id)) return void 0;
620
+ const originator = str(payload.originator, 100);
621
+ return {
622
+ id,
623
+ cwd: str(payload.cwd),
624
+ originator,
625
+ version: str(payload.cli_version, 80),
626
+ ...codexOrigin(payload.source, originator, str(payload.parent_thread_id, 100))
627
+ };
628
+ }
629
+ async function rollouts(dir) {
630
+ const root = path5.join(dir, "sessions");
631
+ const found = [];
632
+ const desc = (names, pattern) => names.filter((name) => pattern.test(name)).sort().reverse();
633
+ outer: for (const year of desc(await listDir(root), /^\d{4}$/))
634
+ for (const month of desc(await listDir(path5.join(root, year)), /^\d{2}$/))
635
+ for (const day of desc(await listDir(path5.join(root, year, month)), /^\d{2}$/))
636
+ for (const name of desc(await listDir(path5.join(root, year, month, day)), ROLLOUT)) {
637
+ found.push({ file: path5.join(root, year, month, day, name), id: ROLLOUT.exec(name)[1] });
638
+ if (found.length >= ROLLOUTS_MAX) break outer;
639
+ }
640
+ const stamped = await Promise.all(found.map(async (entry) => ({ ...entry, mtime: await modifiedAt(entry.file) ?? 0 })));
641
+ return stamped.sort((a, b) => b.mtime - a.mtime);
642
+ }
643
+ async function titles(dir) {
644
+ const names = /* @__PURE__ */ new Map();
645
+ const part = await readPart(path5.join(dir, "session_index.jsonl"), INDEX_MAX, { root: dir, fromEnd: true });
646
+ if (!part) return names;
647
+ const lines2 = part.text.split("\n");
648
+ if (!part.whole) lines2.shift();
649
+ for (const line of lines2) {
650
+ const value = parseJson(line);
651
+ if (!isRecord(value)) continue;
652
+ const id = str(value.id, 100);
653
+ const name = str(value.thread_name, 1e3);
654
+ if (id && name) names.set(id, name);
655
+ }
656
+ return names;
657
+ }
658
+ function liveState2(held, surface) {
659
+ if (held === false) return null;
660
+ return held ? { lock: true, status: "unknown", surface, exit: "lock" } : { status: "unknown", surface, exit: "none" };
661
+ }
662
+ var fromMeta = (entry, title, lastActiveAt) => ({
663
+ nativeId: entry.id,
664
+ cwd: entry.cwd,
665
+ title,
666
+ lastActiveAt,
667
+ live: null,
668
+ source: "files",
669
+ nativeVersion: entry.version,
670
+ kind: entry.kind,
671
+ originator: entry.originator
672
+ });
673
+ var fromNative2 = (session) => ({
674
+ nativeId: session.id,
675
+ cwd: session.cwd,
676
+ title: session.title,
677
+ lastActiveAt: session.updatedAt,
678
+ live: null,
679
+ source: "server",
680
+ nativeVersion: session.version,
681
+ kind: session.kind ?? (session.parentId ? "subagent" : "interactive"),
682
+ originator: session.originator
683
+ });
684
+ function codexProbe(ctx) {
685
+ const dir = codexDir(ctx.env, ctx.home);
686
+ const surfaces = /* @__PURE__ */ new Map();
687
+ const held = async (id) => {
688
+ const file = codexLockFile(dir, id);
689
+ return (await ctx.process.locksHeld([file])).get(file);
690
+ };
691
+ const findMeta = async (id, all) => {
692
+ for (const entry of all) {
693
+ if (entry.id !== id) continue;
694
+ const found = meta(await readFirstLine(entry.file, META_MAX, { root: dir }));
695
+ if (found?.id === id) return { meta: found, mtime: entry.mtime };
696
+ }
697
+ return void 0;
698
+ };
699
+ return {
700
+ harness: "codex",
701
+ async live(id) {
702
+ return CODEX_ID.test(id) ? liveState2(await held(id), surfaces.get(id) ?? "unknown") : null;
703
+ },
704
+ async list(options) {
705
+ const lockDir = path5.join(dir, "thread-writer-locks");
706
+ const lockIds = (await listDir(lockDir)).map((name) => LOCK.exec(name)?.[1]).filter((id) => !!id).slice(0, 2e3);
707
+ const heldFiles = await ctx.process.locksHeld(lockIds.map((id) => codexLockFile(dir, id)));
708
+ const locks = new Map(lockIds.map((id) => [id, heldFiles.get(codexLockFile(dir, id))]));
709
+ const sessions = /* @__PURE__ */ new Map();
710
+ let source = "files";
711
+ let truncated = false;
712
+ let all;
713
+ const files = () => all ??= rollouts(dir);
714
+ const names = await titles(dir);
715
+ if (!options.liveOnly) {
716
+ const driver = ctx.driver();
717
+ try {
718
+ if (!driver.listSessions) throw new Error("This Codex adapter cannot list threads");
719
+ const listed = await driver.listSessions({ limit: options.limit, directory: options.directory, signal: options.signal });
720
+ for (const session of listed) {
721
+ if (session.surface) surfaces.set(session.id, session.surface);
722
+ sessions.set(session.id, fromNative2(session));
723
+ }
724
+ truncated = listed.length >= options.limit;
725
+ source = "server";
726
+ } catch {
727
+ let read = 0;
728
+ for (const entry of await files()) {
729
+ if (sessions.size >= options.limit) {
730
+ truncated = true;
731
+ break;
732
+ }
733
+ if (++read > options.limit * 4 + 100 || options.signal.aborted) break;
734
+ const found = meta(await readFirstLine(entry.file, META_MAX, { root: dir }));
735
+ if (!found || found.id !== entry.id || found.kind === "subagent") continue;
736
+ if (options.directory && !(found.cwd && samePath(found.cwd, options.directory))) continue;
737
+ surfaces.set(found.id, found.surface);
738
+ sessions.set(found.id, fromMeta(found, names.get(found.id), entry.mtime));
739
+ }
740
+ }
741
+ }
742
+ for (const [id, state] of locks) {
743
+ if (state === false || sessions.has(id) || options.signal.aborted) continue;
744
+ const found = await findMeta(id, await files());
745
+ if (!found || found.meta.kind === "subagent") continue;
746
+ if (options.directory && !(found.meta.cwd && samePath(found.meta.cwd, options.directory))) continue;
747
+ surfaces.set(id, found.meta.surface);
748
+ sessions.set(id, fromMeta(found.meta, names.get(id), found.mtime));
749
+ }
750
+ let unknown = 0;
751
+ for (const session of sessions.values()) {
752
+ const state = locks.has(session.nativeId) ? locks.get(session.nativeId) : false;
753
+ if (state === void 0) unknown++;
754
+ session.live = liveState2(state, surfaces.get(session.nativeId) ?? "unknown");
755
+ session.title ??= names.get(session.nativeId);
756
+ }
757
+ return {
758
+ sessions: [...sessions.values()],
759
+ source,
760
+ truncated,
761
+ ...unknown ? { detail: "Crossroom cannot tell which Codex threads are open on this computer (install lsof), so it offers copies of them only." } : {}
762
+ };
763
+ },
764
+ async find(id) {
765
+ if (!CODEX_ID.test(id)) return void 0;
766
+ const found = await findMeta(id, await rollouts(dir));
767
+ if (!found) return void 0;
768
+ surfaces.set(id, found.meta.surface);
769
+ const session = fromMeta(found.meta, (await titles(dir)).get(id), found.mtime);
770
+ session.live = liveState2(await held(id), found.meta.surface);
771
+ return session;
772
+ }
773
+ };
774
+ }
775
+
776
+ // src/discovery/grok.ts
777
+ import path6 from "node:path";
778
+ var ACTIVE_MAX = 256 * 1024;
779
+ var SUMMARY_MAX = 64 * 1024;
780
+ var DIRS_MAX = 1e3;
781
+ var SESSIONS_MAX = 5e3;
782
+ var GROK_ID = /^[0-9A-Za-z][0-9A-Za-z_-]{0,99}$/;
783
+ var grokDir = (ctx) => ctx.env.GROK_HOME || path6.join(ctx.home, ".grok");
784
+ async function actives(dir) {
785
+ const value = parseJson(await readSmall(path6.join(dir, "active_sessions.json"), ACTIVE_MAX, { root: dir }));
786
+ if (!Array.isArray(value)) return [];
787
+ return value.flatMap((entry) => {
788
+ if (!isRecord(entry)) return [];
789
+ const id = str(entry.session_id, 100);
790
+ const pid = num(entry.pid);
791
+ if (!id || !GROK_ID.test(id) || !pid || !Number.isSafeInteger(pid) || pid <= 0) return [];
792
+ return [{ id, pid, cwd: str(entry.cwd), openedAt: time(entry.opened_at) }];
793
+ });
794
+ }
795
+ function summary(text, id) {
796
+ const value = parseJson(text);
797
+ if (!isRecord(value)) return void 0;
798
+ const info = isRecord(value.info) ? value.info : {};
799
+ if (str(info.id, 100) !== id) return void 0;
800
+ const kind = str(value.session_kind, 80);
801
+ return {
802
+ id,
803
+ cwd: str(info.cwd),
804
+ title: str(value.generated_title, 1e3),
805
+ lastActiveAt: time(value.last_active_at) ?? time(value.updated_at),
806
+ kind: kind && /sub.?agent/i.test(kind) ? "subagent" : "interactive"
807
+ };
808
+ }
809
+ function liveState3(active) {
810
+ return { pid: active.pid, status: "unknown", surface: "unknown", exit: "pid" };
811
+ }
812
+ async function candidates(dir) {
813
+ const root = path6.join(dir, "sessions");
814
+ const found = [];
815
+ outer: for (const folder of (await listDir(root)).slice(0, DIRS_MAX))
816
+ for (const id of await listDir(path6.join(root, folder))) {
817
+ if (!GROK_ID.test(id)) continue;
818
+ found.push({ file: path6.join(root, folder, id, "summary.json"), id });
819
+ if (found.length >= SESSIONS_MAX) break outer;
820
+ }
821
+ const stamped = await Promise.all(found.map(async (entry) => ({ ...entry, mtime: await modifiedAt(entry.file) })));
822
+ return stamped.filter((entry) => entry.mtime !== void 0).sort((a, b) => b.mtime - a.mtime);
823
+ }
824
+ function grokProbe(ctx) {
825
+ const dir = grokDir(ctx);
826
+ const live = async (id, hint) => {
827
+ if (hint?.pid) {
828
+ return await sameProcess(ctx.process, hint.pid, { start: hint.procStart ? Number(hint.procStart) : void 0 }) ? { pid: hint.pid, procStart: hint.procStart, status: "unknown", surface: "unknown", exit: "pid" } : null;
829
+ }
830
+ for (const active of await actives(dir))
831
+ if (active.id === id && await sameProcess(ctx.process, active.pid, { after: active.openedAt })) return liveState3(active);
832
+ return null;
833
+ };
834
+ return {
835
+ harness: "grok",
836
+ live,
837
+ async list(options) {
838
+ const open2 = (await actives(dir)).filter(
839
+ (active) => ctx.process.alive(active.pid) && (!options.directory || active.cwd && samePath(active.cwd, options.directory))
840
+ );
841
+ const byId = new Map(open2.map((active) => [active.id, active]));
842
+ const sessions = /* @__PURE__ */ new Map();
843
+ let truncated = false;
844
+ const all = await candidates(dir);
845
+ const wanted = options.liveOnly ? all.filter((entry) => byId.has(entry.id)) : all;
846
+ let read = 0;
847
+ for (const entry of wanted) {
848
+ if (sessions.size >= options.limit && !byId.has(entry.id)) {
849
+ truncated = true;
850
+ continue;
851
+ }
852
+ if (++read > options.limit * 4 + 100 + byId.size || options.signal.aborted) break;
853
+ const found = summary(await readSmall(entry.file, SUMMARY_MAX, { root: dir }), entry.id);
854
+ if (!found || found.kind === "subagent") continue;
855
+ if (options.directory && !(found.cwd && samePath(found.cwd, options.directory))) continue;
856
+ const active = byId.get(found.id);
857
+ sessions.set(found.id, {
858
+ nativeId: found.id,
859
+ cwd: found.cwd ?? active?.cwd,
860
+ title: found.title,
861
+ lastActiveAt: found.lastActiveAt ?? entry.mtime,
862
+ live: active ? liveState3(active) : null,
863
+ source: "files"
864
+ });
865
+ }
866
+ for (const active of open2)
867
+ if (!sessions.has(active.id))
868
+ sessions.set(active.id, {
869
+ nativeId: active.id,
870
+ cwd: active.cwd,
871
+ lastActiveAt: active.openedAt,
872
+ live: liveState3(active),
873
+ source: "files"
874
+ });
875
+ return { sessions: [...sessions.values()], source: "files", truncated };
876
+ },
877
+ async find(id) {
878
+ if (!GROK_ID.test(id)) return void 0;
879
+ const entry = (await candidates(dir)).find((candidate) => candidate.id === id);
880
+ const found = entry ? summary(await readSmall(entry.file, SUMMARY_MAX, { root: dir }), id) : void 0;
881
+ const active = (await actives(dir)).find((candidate) => candidate.id === id);
882
+ if (!found && !active) return void 0;
883
+ let state = null;
884
+ if (active && await sameProcess(ctx.process, active.pid, { after: active.openedAt })) {
885
+ const start = await ctx.process.startedAt(active.pid);
886
+ state = { ...liveState3(active), ...start !== void 0 ? { procStart: String(start) } : {} };
887
+ }
888
+ return {
889
+ nativeId: id,
890
+ cwd: found?.cwd ?? active?.cwd,
891
+ title: found?.title,
892
+ lastActiveAt: found?.lastActiveAt ?? entry?.mtime ?? active?.openedAt,
893
+ live: state,
894
+ source: "files",
895
+ kind: found?.kind
896
+ };
897
+ }
898
+ };
899
+ }
900
+
901
+ // src/discovery/opencode.ts
902
+ var STATUS_TIMEOUT_MS = 6e3;
903
+ var STATUS_TTL_MS = 3e4;
904
+ function serviceRunning(output) {
905
+ if (/\b(not running|stopped|inactive|not installed)\b/i.test(output)) return false;
906
+ if (/\b(running|active)\b/i.test(output)) return true;
907
+ return void 0;
908
+ }
909
+ var possiblyOpen = { status: "unknown", surface: "unknown", exit: "none" };
910
+ function openCodeProbe(ctx) {
911
+ let known;
912
+ const executable = () => ctx.driver().executable ?? resolveBin("opencode");
913
+ const status = async () => {
914
+ let running;
915
+ const binary = executable();
916
+ if (binary && !/\.(cmd|bat)$/i.test(binary)) {
917
+ try {
918
+ running = serviceRunning(await ctx.process.run(binary, ["service", "status"], { timeoutMs: STATUS_TIMEOUT_MS, maxBytes: 64 * 1024 }));
919
+ } catch (error) {
920
+ const stdout = error.stdout;
921
+ running = stdout ? serviceRunning(stdout) : void 0;
922
+ }
923
+ }
924
+ known = { running, at: ctx.now() };
925
+ return running;
926
+ };
927
+ const state = (running) => running === false ? null : { ...possiblyOpen };
928
+ const fromNative3 = (session, running) => ({
929
+ nativeId: session.id,
930
+ cwd: session.cwd,
931
+ title: session.title,
932
+ lastActiveAt: session.updatedAt,
933
+ live: state(running),
934
+ source: "server",
935
+ nativeVersion: session.version,
936
+ kind: session.parentId ? "subagent" : session.kind
937
+ });
938
+ return {
939
+ harness: "opencode",
940
+ live() {
941
+ return Promise.resolve(known && ctx.now() - known.at < STATUS_TTL_MS ? state(known.running) : { ...possiblyOpen });
942
+ },
943
+ async list(options) {
944
+ if (!executable()) return { sessions: [], source: "server" };
945
+ const driver = ctx.driver();
946
+ if (!driver.listSessions) throw new Error("This OpenCode adapter cannot list sessions yet.");
947
+ const running = await status();
948
+ if (options.liveOnly && running === false) return { sessions: [], source: "server" };
949
+ const listed = await driver.listSessions({ limit: options.limit, directory: options.directory, signal: options.signal });
950
+ return {
951
+ sessions: listed.map((session) => fromNative3(session, running)),
952
+ source: "server",
953
+ truncated: listed.length >= options.limit,
954
+ ...running === void 0 ? { detail: "Crossroom cannot tell whether the OpenCode service is running, so it offers copies of its sessions only." } : running ? { detail: "The OpenCode service is running and may have any of these open, so Crossroom offers copies only." } : {}
955
+ };
956
+ }
957
+ };
958
+ }
959
+
960
+ // src/discovery/index.ts
961
+ var DISCOVERY = {
962
+ /** Sessions per harness when the caller does not say. */
963
+ limit: 50,
964
+ maxLimit: 200,
965
+ probeMs: 6e3,
966
+ totalMs: 1e4,
967
+ cacheMs: 5e3,
968
+ titleChars: 160
969
+ };
970
+ var NAMES = { claude: "Claude Code", codex: "Codex", grok: "Grok", opencode: "OpenCode" };
971
+ var PRIMARY = { claude: "sdk", codex: "server", grok: "files", opencode: "server" };
972
+ function normalizeReportOptions(options = {}) {
973
+ const harnesses = [...new Set((options.harnesses ?? Harness.options).filter((h) => Harness.options.includes(h)))];
974
+ const limit = Number.isSafeInteger(options.limit) && options.limit > 0 ? Math.min(options.limit, DISCOVERY.maxLimit) : DISCOVERY.limit;
975
+ return {
976
+ harnesses: harnesses.length ? harnesses : [...Harness.options],
977
+ ...options.directory ? { directory: path7.resolve(options.directory) } : {},
978
+ limit,
979
+ liveOnly: options.liveOnly === true
980
+ };
981
+ }
982
+ var cleanTitle = (title) => {
983
+ const line = oneLine(title ?? "");
984
+ if (!line) return "Untitled session";
985
+ return line.length > DISCOVERY.titleChars ? line.slice(0, DISCOVERY.titleChars - 1).trimEnd() + "\u2026" : line;
986
+ };
987
+ var clipDetail = (text) => {
988
+ const line = oneLine(text);
989
+ return line.length > 300 ? line.slice(0, 299) + "\u2026" : line;
990
+ };
991
+ var byRecency = (a, b) => (b.lastActiveAt ?? -1) - (a.lastActiveAt ?? -1) || a.harness.localeCompare(b.harness) || a.nativeId.localeCompare(b.nativeId);
992
+ var shown = (live) => live ? { ...live.pid !== void 0 ? { pid: live.pid } : {}, status: live.status, surface: live.surface } : null;
993
+ var SessionDiscovery = class {
994
+ constructor(options) {
995
+ this.options = options;
996
+ this.now = options.now ?? Date.now;
997
+ this.probeMs = options.timeouts?.probeMs ?? DISCOVERY.probeMs;
998
+ this.totalMs = options.timeouts?.totalMs ?? DISCOVERY.totalMs;
999
+ this.cacheMs = options.timeouts?.cacheMs ?? DISCOVERY.cacheMs;
1000
+ const context = (harness) => probeContext({ home: options.home, env: options.env, process: options.process, now: options.now, driver: () => options.driver?.(harness) ?? {} });
1001
+ const probes = options.probes ?? [
1002
+ claudeProbe(context("claude")),
1003
+ codexProbe(context("codex")),
1004
+ grokProbe(context("grok")),
1005
+ openCodeProbe(context("opencode"))
1006
+ ];
1007
+ for (const probe of probes) this.probes.set(probe.harness, probe);
1008
+ this.ownFolders = [path7.resolve(options.dataDirectory)];
1009
+ }
1010
+ options;
1011
+ probes = /* @__PURE__ */ new Map();
1012
+ inflight = /* @__PURE__ */ new Map();
1013
+ cache = /* @__PURE__ */ new Map();
1014
+ now;
1015
+ probeMs;
1016
+ totalMs;
1017
+ cacheMs;
1018
+ /** Folders Crossroom's own work runs in: hosted seats' directories, under its data directory. */
1019
+ ownFolders;
1020
+ /** Never throws: a probe that fails or runs out of time is a probes[] entry with ok false. */
1021
+ report(options = {}) {
1022
+ const normalized = normalizeReportOptions(options);
1023
+ const key = JSON.stringify(normalized);
1024
+ const now = this.now();
1025
+ for (const [stale, entry] of this.cache) if (now - entry.at >= this.cacheMs) this.cache.delete(stale);
1026
+ const cached = this.cache.get(key);
1027
+ if (cached) return Promise.resolve(cached.report);
1028
+ const running = this.inflight.get(key);
1029
+ if (running) return running;
1030
+ const work = this.run(normalized).then((report) => {
1031
+ this.cache.set(key, { at: this.now(), report });
1032
+ return report;
1033
+ });
1034
+ const settled = work.finally(() => this.inflight.delete(key));
1035
+ this.inflight.set(key, settled);
1036
+ return settled;
1037
+ }
1038
+ /** One session by its native id, classified as a report would, or undefined when no probe can find it. */
1039
+ async find(harness, id) {
1040
+ const probe = this.probes.get(harness);
1041
+ if (!probe || !SESSION_ID.test(id)) return void 0;
1042
+ const controller = new AbortController();
1043
+ try {
1044
+ const session = probe.find ? await bounded(probe.find(id, { signal: controller.signal }), this.probeMs, "Session lookup timed out") : (await bounded(
1045
+ probe.list({ limit: DISCOVERY.maxLimit, signal: controller.signal }),
1046
+ this.probeMs,
1047
+ "Session lookup timed out"
1048
+ )).sessions.find((entry) => entry.nativeId === id);
1049
+ if (!session || session.nativeId !== id) return void 0;
1050
+ return this.classify(harness, session, true);
1051
+ } catch {
1052
+ controller.abort();
1053
+ return void 0;
1054
+ }
1055
+ }
1056
+ /**
1057
+ * Whether a session is open elsewhere right now: files and pids only, so a watcher can poll it.
1058
+ * When the probe cannot answer, the session is reported open, with an exit Crossroom cannot see.
1059
+ */
1060
+ async live(harness, id, hint) {
1061
+ const probe = this.probes.get(harness);
1062
+ if (!probe) return null;
1063
+ if (!SESSION_ID.test(id)) return { status: "unknown", surface: "unknown", exit: "none" };
1064
+ try {
1065
+ return await bounded(probe.live(id, hint), this.probeMs, "Liveness check timed out");
1066
+ } catch {
1067
+ return { status: "unknown", surface: "unknown", exit: "none" };
1068
+ }
1069
+ }
1070
+ async run(options) {
1071
+ const deadline = Date.now() + this.totalMs;
1072
+ const results = await Promise.all(options.harnesses.map((harness) => this.probe(harness, options, deadline)));
1073
+ let truncated = false;
1074
+ const sessions = [];
1075
+ const probes = [];
1076
+ for (const result of results) {
1077
+ const visible = result.sessions.map((session) => this.classify(result.entry.harness, session, false)).filter((session) => session !== void 0).filter((session) => !options.liveOnly || session.live !== null).sort(byRecency);
1078
+ if (visible.length > options.limit || result.truncated) truncated = true;
1079
+ const kept = visible.slice(0, options.limit);
1080
+ sessions.push(...kept);
1081
+ probes.push({ ...result.entry, count: kept.length });
1082
+ }
1083
+ return { checkedAt: this.now(), truncated, sessions: sessions.sort(byRecency), probes };
1084
+ }
1085
+ async probe(harness, options, deadline) {
1086
+ const started2 = Date.now();
1087
+ const probe = this.probes.get(harness);
1088
+ const failed = (detail) => ({
1089
+ entry: { harness, ok: false, source: PRIMARY[harness], elapsedMs: Date.now() - started2, count: 0, detail: clipDetail(detail) },
1090
+ sessions: [],
1091
+ truncated: false
1092
+ });
1093
+ if (!probe) return failed("Crossroom has no way to look for " + NAMES[harness] + " sessions.");
1094
+ const budget = Math.max(0, Math.min(this.probeMs, deadline - Date.now()));
1095
+ const controller = new AbortController();
1096
+ try {
1097
+ const result = await bounded(
1098
+ probe.list({ limit: options.limit, directory: options.directory, liveOnly: options.liveOnly, signal: controller.signal }),
1099
+ budget,
1100
+ NAMES[harness] + " took longer than " + Math.round(budget / 100) / 10 + " s to list its sessions."
1101
+ );
1102
+ return {
1103
+ entry: {
1104
+ harness,
1105
+ ok: true,
1106
+ source: result.source,
1107
+ elapsedMs: Date.now() - started2,
1108
+ count: 0,
1109
+ ...result.detail ? { detail: clipDetail(result.detail) } : {}
1110
+ },
1111
+ sessions: result.sessions,
1112
+ truncated: result.truncated === true
1113
+ };
1114
+ } catch (error) {
1115
+ controller.abort();
1116
+ return failed(error instanceof Error ? error.message : String(error));
1117
+ }
1118
+ }
1119
+ /**
1120
+ * Who owns a session. Undefined hides it from a report: subagent threads belong to the session
1121
+ * that spawned them. A lookup by id still answers.
1122
+ */
1123
+ classify(harness, session, lookup) {
1124
+ const base = {
1125
+ harness,
1126
+ nativeId: session.nativeId,
1127
+ ...session.cwd ? { cwd: session.cwd } : {},
1128
+ title: cleanTitle(session.title),
1129
+ ...session.lastActiveAt !== void 0 ? { lastActiveAt: session.lastActiveAt } : {},
1130
+ live: shown(session.live),
1131
+ owner: "external",
1132
+ source: session.source,
1133
+ ...session.nativeVersion ? { nativeVersion: session.nativeVersion } : {}
1134
+ };
1135
+ const parley = (reason) => ({ ...base, owner: "parley", reason });
1136
+ if (session.cwd && this.ownFolders.some((folder) => insidePath(session.cwd, folder)))
1137
+ return parley("Crossroom started it for its own work.");
1138
+ if (harness === "codex" && session.originator === "parley") return parley("Crossroom started it.");
1139
+ if (session.kind === "subagent") return lookup ? { ...base, reason: "A subagent thread, which belongs to the session that started it." } : void 0;
1140
+ return base;
1141
+ }
1142
+ };
1143
+ export {
1144
+ DISCOVERY,
1145
+ SessionDiscovery,
1146
+ cleanTitle,
1147
+ normalizeReportOptions
1148
+ };