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,424 @@
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
+ LOCAL_COPY_HEADER,
8
+ dataDir,
9
+ savedRooms,
10
+ searchItems,
11
+ searchTerms
12
+ } from "./chunk-GWFVXAVQ.mjs";
13
+ import {
14
+ oneLine,
15
+ slotLetter
16
+ } from "./chunk-O3GNP4DR.mjs";
17
+
18
+ // src/commands/memory-notes.ts
19
+ import { randomBytes } from "node:crypto";
20
+ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
21
+ import os from "node:os";
22
+ import path from "node:path";
23
+
24
+ // src/commands/loopback.ts
25
+ import http from "node:http";
26
+ var ANSWER_MAX = 8 * 1024 * 1024;
27
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "[::1]"]);
28
+ function loopbackBase(raw) {
29
+ if (typeof raw !== "string" || raw.length > 64) return void 0;
30
+ let url;
31
+ try {
32
+ url = new URL(raw);
33
+ } catch {
34
+ return void 0;
35
+ }
36
+ if (url.protocol !== "http:" || !LOOPBACK_HOSTS.has(url.hostname) || url.username || url.password) return void 0;
37
+ if (url.pathname !== "/" && url.pathname !== "" || url.search || url.hash || raw.includes("#") || raw.includes("?")) return void 0;
38
+ return url.origin;
39
+ }
40
+ var loopbackFetch = (url, init) => new Promise((resolve, reject) => {
41
+ const target = new URL(url);
42
+ const body = init.body;
43
+ const request = http.request(
44
+ {
45
+ hostname: target.hostname.replace(/^\[|\]$/g, ""),
46
+ port: target.port,
47
+ path: target.pathname + target.search,
48
+ method: init.method,
49
+ headers: { ...init.headers, ...body === void 0 ? {} : { "content-length": String(Buffer.byteLength(body)) } },
50
+ signal: init.signal
51
+ },
52
+ (response) => {
53
+ const chunks = [];
54
+ let size = 0;
55
+ response.on("data", (chunk) => {
56
+ size += chunk.length;
57
+ if (size > ANSWER_MAX) request.destroy(new Error("answer too large"));
58
+ else chunks.push(chunk);
59
+ });
60
+ response.on("end", () => {
61
+ const text = Buffer.concat(chunks).toString("utf8");
62
+ resolve({ status: response.statusCode ?? 0, text: () => Promise.resolve(text) });
63
+ });
64
+ response.on("error", reject);
65
+ }
66
+ );
67
+ request.on("error", reject);
68
+ request.end(body);
69
+ });
70
+
71
+ // src/commands/memory-notes.ts
72
+ var MEMORY_KEPT = 200;
73
+ var RECALL_MAX = 1500;
74
+ var RECALL_AUTO_ROOMS = 3;
75
+ var RECALL_TITLE = "Notes from earlier rooms";
76
+ var ID = /^[A-Za-z0-9_-]{1,64}$/;
77
+ var TITLE_MAX = 160;
78
+ var NAME_MAX = 60;
79
+ var DIR_MAX = 400;
80
+ var REQUEST_MS = 15e3;
81
+ var memoryDir = () => path.join(dataDir(), "memory");
82
+ var indexFile = () => path.join(memoryDir(), "index.json");
83
+ function noteFile(id) {
84
+ return ID.test(id) ? path.join(memoryDir(), `${id}.md`) : void 0;
85
+ }
86
+ function writeWhole(file, text) {
87
+ mkdirSync(path.dirname(file), { recursive: true, mode: 448 });
88
+ const temp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
89
+ try {
90
+ writeFileSync(temp, text, { mode: 384 });
91
+ renameSync(temp, file);
92
+ } catch (error) {
93
+ rmSync(temp, { force: true });
94
+ throw error;
95
+ }
96
+ }
97
+ var isEntry = (e) => {
98
+ const x = e;
99
+ return !!x && typeof x.id === "string" && ID.test(x.id) && typeof x.title === "string" && typeof x.ended === "string" && Array.isArray(x.dirs) && Array.isArray(x.seats);
100
+ };
101
+ function readIndex() {
102
+ try {
103
+ const list = JSON.parse(readFileSync(indexFile(), "utf8"));
104
+ return Array.isArray(list) ? list.filter(isEntry) : [];
105
+ } catch {
106
+ return [];
107
+ }
108
+ }
109
+ function writeIndex(list) {
110
+ const sorted = [...new Map(list.map((e) => [e.id, e])).values()].sort((a, b) => b.ended.localeCompare(a.ended) || b.savedAt.localeCompare(a.savedAt));
111
+ const kept = sorted.slice(0, MEMORY_KEPT);
112
+ writeWhole(indexFile(), `${JSON.stringify(kept, null, 2)}
113
+ `);
114
+ const keep = new Set(kept.map((e) => `${e.id}.md`));
115
+ let files = [];
116
+ try {
117
+ files = readdirSync(memoryDir());
118
+ } catch {
119
+ return;
120
+ }
121
+ for (const name of files) if (name.endsWith(".md") && !keep.has(name)) rmSync(path.join(memoryDir(), name), { force: true });
122
+ }
123
+ var yaml = (s) => JSON.stringify(s);
124
+ function noteText(entry, digest) {
125
+ const lines = [
126
+ "---",
127
+ `id: ${entry.id}`,
128
+ `title: ${yaml(entry.title)}`,
129
+ `ended: ${entry.ended}`,
130
+ ...entry.dirs.length ? ["dirs:", ...entry.dirs.map((d) => ` - ${yaml(d)}`)] : ["dirs: []"],
131
+ ...entry.topic ? [`topic: ${yaml(entry.topic)}`] : [],
132
+ "seats:",
133
+ ...entry.seats.flatMap((s) => [` - letter: ${s.letter}`, ` name: ${yaml(s.name)}`, ` provider: ${s.provider ? yaml(s.provider) : "null"}`]),
134
+ "---",
135
+ "",
136
+ digest.replace(/\s+$/, ""),
137
+ "",
138
+ `Full record: crossroom minutes ${entry.id}`,
139
+ ""
140
+ ];
141
+ return lines.join("\n");
142
+ }
143
+ function noteDigest(text) {
144
+ const body = text.replace(/\r\n/g, "\n");
145
+ const end = body.startsWith("---\n") ? body.indexOf("\n---\n", 4) : -1;
146
+ const after = end >= 0 ? body.slice(end + 5) : body;
147
+ return after.replace(/\n*Full record: crossroom minutes \S+\s*$/, "").trim();
148
+ }
149
+ var forgottenFile = () => path.join(memoryDir(), "forgotten.json");
150
+ var FORGOTTEN_KEPT = 1e3;
151
+ function forgottenIds() {
152
+ try {
153
+ const list = JSON.parse(readFileSync(forgottenFile(), "utf8"));
154
+ return new Set(Array.isArray(list) ? list.filter((id) => typeof id === "string" && ID.test(id)) : []);
155
+ } catch {
156
+ return /* @__PURE__ */ new Set();
157
+ }
158
+ }
159
+ function forgetNote(id, { forever = false } = {}) {
160
+ const file = noteFile(id);
161
+ if (!file) return false;
162
+ if (forever) {
163
+ const kept = [id, ...[...forgottenIds()].filter((x) => x !== id)].slice(0, FORGOTTEN_KEPT);
164
+ writeWhole(forgottenFile(), `${JSON.stringify(kept)}
165
+ `);
166
+ }
167
+ const list = readIndex();
168
+ const had = existsSync(file) || list.some((e) => e.id === id);
169
+ if (!had) return false;
170
+ rmSync(file, { force: true });
171
+ writeIndex(list.filter((e) => e.id !== id));
172
+ return true;
173
+ }
174
+ var clip = (s, max) => oneLine(s).slice(0, max);
175
+ var owned = (room, extra = {}) => ({ "x-parley-owner": room.owner, accept: "application/json", ...extra });
176
+ async function get(send, url, headers, signal) {
177
+ const response = await send(url, { method: "GET", headers, signal: signal ?? AbortSignal.timeout(REQUEST_MS), redirect: "error" });
178
+ return { status: response.status, text: await response.text() };
179
+ }
180
+ async function rememberRoom(room, options = {}) {
181
+ const base = loopbackBase(room.base);
182
+ if (!base || !ID.test(room.id) || !room.owner) return "refused";
183
+ const send = options.fetch ?? loopbackFetch;
184
+ const at = `${base}/api/sessions/${encodeURIComponent(room.id)}`;
185
+ let snap;
186
+ try {
187
+ snap = await get(send, at, owned(room), options.signal);
188
+ } catch {
189
+ return "unreachable";
190
+ }
191
+ if (snap.status === 404) {
192
+ forgetNote(room.id);
193
+ return "gone";
194
+ }
195
+ if (snap.status !== 200) return "unreachable";
196
+ let body;
197
+ try {
198
+ body = JSON.parse(snap.text);
199
+ } catch {
200
+ return "unreachable";
201
+ }
202
+ if (body.session?.e2ee) return "e2ee";
203
+ if (body.session?.status !== "ended") return "live";
204
+ let digest;
205
+ try {
206
+ digest = await get(send, `${at}/minutes?style=digest`, owned(room, { accept: "text/markdown", [LOCAL_COPY_HEADER]: "1" }), options.signal);
207
+ } catch {
208
+ return "unreachable";
209
+ }
210
+ if (digest.status === 404) {
211
+ forgetNote(room.id);
212
+ return "gone";
213
+ }
214
+ if (digest.status !== 200) return digest.status === 409 ? "e2ee" : "unreachable";
215
+ const hints = options.hints ?? {};
216
+ const participants = [...body.participants ?? []].filter((p) => typeof p.slot === "number").sort((a, b) => a.slot - b.slot);
217
+ const hostedDirs = participants.flatMap((p) => typeof p.hosted?.cwd === "string" ? [p.hosted.cwd] : []);
218
+ const dirs = [...new Set([...hints.dirs ?? room.dirs ?? [], ...hostedDirs].map((d) => clip(d, DIR_MAX)).filter(Boolean))];
219
+ const topic = hints.topic ?? room.topic;
220
+ const entry = {
221
+ id: room.id,
222
+ title: clip(body.session?.title || room.title || "A Crossroom room", TITLE_MAX) || "A Crossroom room",
223
+ ended: typeof body.session?.endedAt === "string" ? body.session.endedAt : (/* @__PURE__ */ new Date()).toISOString(),
224
+ dirs,
225
+ ...topic ? { topic: clip(topic, TITLE_MAX) } : {},
226
+ seats: participants.map((p) => {
227
+ const provider = hints.providers?.[p.slot] ?? p.provider ?? null;
228
+ return { letter: slotLetter(p.slot), name: clip(p.name ?? "", NAME_MAX) || `Seat ${slotLetter(p.slot)}`, provider: provider ? clip(provider, NAME_MAX) : null };
229
+ }),
230
+ savedAt: (/* @__PURE__ */ new Date()).toISOString()
231
+ };
232
+ writeWhole(noteFile(room.id), noteText(entry, digest.text));
233
+ writeIndex([entry, ...readIndex().filter((e) => e.id !== room.id)]);
234
+ return "written";
235
+ }
236
+ async function syncMemory(options = {}) {
237
+ const send = options.fetch ?? loopbackFetch;
238
+ const rooms = (options.rooms ?? savedRooms()).filter((r) => loopbackBase(r.base) && ID.test(r.id) && (options.only?.(r) ?? true));
239
+ const result = { written: [], removed: [], unreachable: 0 };
240
+ const have = new Set(readIndex().map((e) => e.id));
241
+ const forgotten = forgottenIds();
242
+ for (const base of new Set(rooms.map((r) => loopbackBase(r.base)))) {
243
+ const mine = rooms.filter((r) => loopbackBase(r.base) === base);
244
+ const found = /* @__PURE__ */ new Map();
245
+ let reached = true;
246
+ for (let i = 0; i < mine.length; i += 50) {
247
+ try {
248
+ const response = await send(`${base}/api/sessions/lookup`, {
249
+ method: "POST",
250
+ headers: { "content-type": "application/json", accept: "application/json" },
251
+ body: JSON.stringify({ rooms: mine.slice(i, i + 50).map((r) => ({ id: r.id, owner: r.owner })) }),
252
+ signal: AbortSignal.timeout(REQUEST_MS),
253
+ redirect: "error"
254
+ });
255
+ const text = await response.text();
256
+ if (response.status !== 200) {
257
+ reached = false;
258
+ break;
259
+ }
260
+ for (const s of JSON.parse(text)) found.set(s.id, s);
261
+ } catch {
262
+ reached = false;
263
+ break;
264
+ }
265
+ }
266
+ if (!reached) {
267
+ result.unreachable += mine.length;
268
+ continue;
269
+ }
270
+ for (const room of mine) {
271
+ const s = found.get(room.id);
272
+ if (!s) {
273
+ if (forgetNote(room.id)) result.removed.push(room.id);
274
+ continue;
275
+ }
276
+ if (s.e2ee || s.status !== "ended" || have.has(room.id) || forgotten.has(room.id)) continue;
277
+ const done = await rememberRoom(room, { fetch: send });
278
+ if (done === "written") result.written.push(room.id);
279
+ else if (done === "gone") result.removed.push(room.id);
280
+ else if (done === "unreachable") result.unreachable++;
281
+ }
282
+ }
283
+ return result;
284
+ }
285
+ function findNote(word) {
286
+ if (!word) return void 0;
287
+ const list = readIndex();
288
+ const exact = list.find((e) => e.id === word);
289
+ if (exact) return exact;
290
+ const starts = list.filter((e) => e.id.startsWith(word));
291
+ return starts.length === 1 ? starts[0] : void 0;
292
+ }
293
+ function readNote(id) {
294
+ const file = noteFile(id);
295
+ if (!file) return void 0;
296
+ try {
297
+ return readFileSync(file, "utf8");
298
+ } catch {
299
+ return void 0;
300
+ }
301
+ }
302
+ var SEARCH_SHOWN = 10;
303
+ function searchNotes(query, only = () => true) {
304
+ const entries = readIndex().filter(only).reverse();
305
+ const digests = new Map(
306
+ entries.map((e) => [
307
+ e.id,
308
+ noteDigest(readNote(e.id) ?? "").split("\n").filter((line) => !NOT_RECALLED.some((start) => line.trim().startsWith(start))).join("\n")
309
+ ])
310
+ );
311
+ const hits = searchItems(entries, query, (e) => ({
312
+ title: e.title,
313
+ about: e.topic ?? "",
314
+ source: e.dirs.join(" "),
315
+ from: e.seats.map((s) => `${s.name} ${s.provider ?? ""}`).join(" "),
316
+ kind: "",
317
+ body: digests.get(e.id) ?? ""
318
+ }));
319
+ return hits.map(({ item, score, matched }) => ({ entry: item, score, matched, line: bestLine(digests.get(item.id) ?? "", matched) }));
320
+ }
321
+ function bestLine(digest, matched) {
322
+ let best = "";
323
+ let most = 0;
324
+ for (const raw of digest.split("\n")) {
325
+ const line = oneLine(raw).trim();
326
+ if (!line || line.startsWith("## ") || NOT_RECALLED.some((start) => line.startsWith(start))) continue;
327
+ const terms = searchTerms(line);
328
+ const n = matched.filter((m) => terms.some((t) => t === m || m.length >= 3 && t.length >= 3 && (t.startsWith(m) || m.startsWith(t)))).length;
329
+ if (n && n >= most) {
330
+ most = n;
331
+ best = line;
332
+ }
333
+ }
334
+ return best;
335
+ }
336
+ var tooBroad = (dir) => {
337
+ const resolved = path.resolve(dir);
338
+ return sameLocation(resolved, os.homedir()) || path.parse(resolved).root === resolved;
339
+ };
340
+ function overlaps(a, b) {
341
+ if (tooBroad(a) || tooBroad(b)) return sameLocation(a, b) && !tooBroad(a);
342
+ return sameLocation(a, b) || insideLocation(a, b) || insideLocation(b, a);
343
+ }
344
+ function relatedNotes(context, max = RECALL_AUTO_ROOMS) {
345
+ return readIndex().filter((e) => e.id !== context.exclude).filter((e) => context.topic && e.topic === context.topic || e.dirs.some((d) => context.dirs.some((t) => overlaps(d, t)))).slice(0, max);
346
+ }
347
+ function recallText(entries, max = RECALL_MAX) {
348
+ if (!entries.length) return "";
349
+ const share = Math.floor((max - (entries.length - 1)) / entries.length);
350
+ const parts = [];
351
+ for (const e of entries) {
352
+ const head = `Room ${e.id} "${clip(e.title, 80)}", ended ${e.ended.slice(0, 10)}${e.topic ? `, topic "${clip(e.topic, 40)}"` : ""}:`;
353
+ const lines = [head.slice(0, share)];
354
+ let used = lines[0].length;
355
+ for (const raw of noteDigest(readNote(e.id) ?? "").split("\n")) {
356
+ const line = oneLine(raw).trim();
357
+ if (!line || NOT_RECALLED.some((start) => line.startsWith(start))) continue;
358
+ if (used + 1 + line.length > share) {
359
+ const room = share - used - 1;
360
+ if (room > 20) lines.push(`${line.slice(0, room - 1)}\u2026`);
361
+ break;
362
+ }
363
+ lines.push(line);
364
+ used += 1 + line.length;
365
+ }
366
+ parts.push(lines.join("\n"));
367
+ }
368
+ return parts.join("\n").slice(0, max);
369
+ }
370
+ var NOT_RECALLED = ["<!--", "---", "Signed by ", "_Deterministic minutes", "[The room]("];
371
+ function recallNotes(spec, context) {
372
+ if (spec === "auto") return relatedNotes(context);
373
+ const one = findNote(spec);
374
+ if (!one) throw new RecallError(`No note in ${memoryDir()} has the room id ${clip(spec, 40)}. \`crossroom memory list\` shows them.`);
375
+ return [one];
376
+ }
377
+ var RecallError = class extends Error {
378
+ };
379
+ async function postRecall(room, body, send = loopbackFetch) {
380
+ const base = loopbackBase(room.base);
381
+ if (!base) throw new RecallError("Notes from earlier rooms go only into a room on this computer.");
382
+ const response = await send(`${base}/api/sessions/${encodeURIComponent(room.id)}/context`, {
383
+ method: "POST",
384
+ headers: owned(room, { "content-type": "application/json" }),
385
+ body: JSON.stringify({ title: RECALL_TITLE, body, kind: "summary", source: "crossroom memory" }),
386
+ signal: AbortSignal.timeout(REQUEST_MS),
387
+ redirect: "error"
388
+ });
389
+ if (response.status !== 201) {
390
+ const text = await response.text();
391
+ let message = `${response.status}`;
392
+ try {
393
+ message = JSON.parse(text).error ?? message;
394
+ } catch {
395
+ }
396
+ throw new RecallError(`Crossroom refused the notes from earlier rooms: ${clip(message, 200)}`);
397
+ }
398
+ }
399
+
400
+ export {
401
+ MEMORY_KEPT,
402
+ RECALL_MAX,
403
+ RECALL_AUTO_ROOMS,
404
+ RECALL_TITLE,
405
+ memoryDir,
406
+ noteFile,
407
+ readIndex,
408
+ noteText,
409
+ noteDigest,
410
+ forgottenIds,
411
+ forgetNote,
412
+ rememberRoom,
413
+ syncMemory,
414
+ findNote,
415
+ readNote,
416
+ SEARCH_SHOWN,
417
+ searchNotes,
418
+ overlaps,
419
+ relatedNotes,
420
+ recallText,
421
+ recallNotes,
422
+ RecallError,
423
+ postRecall
424
+ };
@@ -0,0 +1,157 @@
1
+ import { createRequire as __parleyRequire } from 'node:module'; const require = __parleyRequire(import.meta.url);
2
+
3
+ // src/client-version.ts
4
+ import { mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
5
+ import path from "node:path";
6
+ var CHECK_EVERY_MS = 24 * 60 * 60 * 1e3;
7
+ var CHECK_TIMEOUT_MS = 2e3;
8
+ var RETRY_AFTER_FAILURE_MS = 60 * 60 * 1e3;
9
+ var noted = /* @__PURE__ */ new Set();
10
+ function noteInstance(base) {
11
+ try {
12
+ noted.add(new URL(base).origin);
13
+ } catch {
14
+ }
15
+ }
16
+ var notedInstances = () => [...noted];
17
+ var VERSION_SHAPE = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/;
18
+ function versionParts(v) {
19
+ const m = VERSION_SHAPE.exec(v.trim());
20
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
21
+ }
22
+ function isPrerelease(v) {
23
+ return Boolean(VERSION_SHAPE.exec(v.trim())?.[4]);
24
+ }
25
+ function olderThan(have, min) {
26
+ const a = versionParts(have);
27
+ const b = versionParts(min);
28
+ if (!a || !b) return false;
29
+ for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] < b[i];
30
+ return isPrerelease(have) && !isPrerelease(min);
31
+ }
32
+ function realScript(script) {
33
+ if (!script) return null;
34
+ try {
35
+ return realpathSync(script).replace(/\\/g, "/");
36
+ } catch {
37
+ return null;
38
+ }
39
+ }
40
+ function checkoutOf(real) {
41
+ if (real.includes("/node_modules/")) return null;
42
+ const pkgDir = path.dirname(path.dirname(real));
43
+ if (path.basename(path.dirname(real)) !== "dist") return null;
44
+ try {
45
+ const pkg = JSON.parse(readFileSync(path.join(pkgDir, "package.json"), "utf8"));
46
+ if (pkg.name !== "crossroom" || !statSync(path.join(pkgDir, "src")).isDirectory()) return null;
47
+ } catch {
48
+ return null;
49
+ }
50
+ return { pkgDir, root: path.resolve(pkgDir, "..", "..") };
51
+ }
52
+ function installKind(script = process.argv[1]) {
53
+ const real = realScript(script);
54
+ if (!real) return "unknown";
55
+ if (real.includes("/_npx/")) return "npx";
56
+ if (/\/(Cellar|homebrew|linuxbrew)\//i.test(real)) return "brew";
57
+ if (real.includes("/node_modules/crossroom/")) return "npm";
58
+ if (checkoutOf(real)) return "checkout";
59
+ return "unknown";
60
+ }
61
+ function updateHint(version, script = process.argv[1]) {
62
+ const tag = isPrerelease(version) ? "crossroom@beta" : "crossroom";
63
+ switch (installKind(script)) {
64
+ case "npx":
65
+ return `Run the newest with: npx ${isPrerelease(version) ? tag : "crossroom@latest"}`;
66
+ case "brew":
67
+ return "Update with: brew upgrade crossroom";
68
+ case "checkout": {
69
+ const at = checkoutOf(realScript(script) ?? "");
70
+ return `Update the checkout it runs from with git pull, then rebuild: ${rebuildCommand(at?.root ?? "<checkout>")}`;
71
+ }
72
+ default:
73
+ return `Update with: npm install -g ${tag}`;
74
+ }
75
+ }
76
+ function rebuildCommand(root) {
77
+ return `pnpm -C ${/\s/.test(root) ? `"${root}"` : root} --filter crossroom build`;
78
+ }
79
+ function staleBuild(version, script = process.argv[1]) {
80
+ if (!versionParts(version)) return null;
81
+ const real = realScript(script);
82
+ const at = real ? checkoutOf(real) : null;
83
+ if (!at) return null;
84
+ let source;
85
+ try {
86
+ source = JSON.parse(readFileSync(path.join(at.pkgDir, "package.json"), "utf8")).version;
87
+ } catch {
88
+ return null;
89
+ }
90
+ if (typeof source !== "string" || source === version) return null;
91
+ return { built: version, source, rebuild: rebuildCommand(at.root) };
92
+ }
93
+ function staleBuildLine(stale) {
94
+ return `This crossroom was built as ${stale.built}; its checkout is now ${stale.source}. Rebuild it with: ${stale.rebuild}`;
95
+ }
96
+ function readSeen(file) {
97
+ try {
98
+ const v = JSON.parse(readFileSync(file, "utf8"));
99
+ return v && typeof v === "object" && !Array.isArray(v) ? v : {};
100
+ } catch {
101
+ return {};
102
+ }
103
+ }
104
+ async function warnIfOutdated(o) {
105
+ if (!noted.size || !versionParts(o.version) || process.env.CROSSROOM_NO_VERSION_CHECK === "1") return;
106
+ const file = path.join(o.dataDir, "client-check.json");
107
+ const now = (o.now ?? Date.now)();
108
+ const seen = readSeen(file);
109
+ let changed = false;
110
+ for (const origin of noted) {
111
+ let entry = seen[origin];
112
+ const stale = !entry?.at || now - entry.at > CHECK_EVERY_MS;
113
+ const resting = typeof entry?.failedAt === "number" && now - entry.failedAt >= 0 && now - entry.failedAt < RETRY_AFTER_FAILURE_MS;
114
+ if (stale && !resting) {
115
+ const min = await readMin(origin, o.fetch ?? fetch);
116
+ entry = min === void 0 ? { at: entry?.at ?? 0, min: entry?.min ?? null, failedAt: now } : { at: now, min };
117
+ seen[origin] = entry;
118
+ changed = true;
119
+ }
120
+ if (entry?.min && olderThan(o.version, entry.min))
121
+ o.say(`This crossroom is ${o.version}; ${new URL(origin).host} supports ${entry.min} and newer. ${updateHint(o.version, o.script)}`);
122
+ }
123
+ if (changed) {
124
+ try {
125
+ mkdirSync(o.dataDir, { recursive: true });
126
+ writeFileSync(file, `${JSON.stringify(seen, null, 2)}
127
+ `);
128
+ } catch {
129
+ }
130
+ }
131
+ }
132
+ async function readMin(origin, f) {
133
+ try {
134
+ const res = await f(`${origin}/api/features`, { headers: { accept: "application/json" }, redirect: "error", signal: AbortSignal.timeout(CHECK_TIMEOUT_MS) });
135
+ if (!res.ok) return void 0;
136
+ const body = await res.json();
137
+ const min = body?.client?.min;
138
+ return typeof min === "string" && versionParts(min) ? min : null;
139
+ } catch {
140
+ return void 0;
141
+ }
142
+ }
143
+
144
+ export {
145
+ CHECK_EVERY_MS,
146
+ RETRY_AFTER_FAILURE_MS,
147
+ noteInstance,
148
+ notedInstances,
149
+ versionParts,
150
+ isPrerelease,
151
+ olderThan,
152
+ installKind,
153
+ updateHint,
154
+ staleBuild,
155
+ staleBuildLine,
156
+ warnIfOutdated
157
+ };
@@ -0,0 +1,60 @@
1
+ import { createRequire as __parleyRequire } from 'node:module'; const require = __parleyRequire(import.meta.url);
2
+ import {
3
+ Usage,
4
+ dataDir
5
+ } from "./chunk-GWFVXAVQ.mjs";
6
+
7
+ // src/commands/local-agent.ts
8
+ import { spawn } from "node:child_process";
9
+ import { closeSync, mkdirSync, openSync } from "node:fs";
10
+ import path from "node:path";
11
+ var UNCONFINED = /* @__PURE__ */ new Set(["codex", "grok"]);
12
+ function checkConfinement(a) {
13
+ if (UNCONFINED.has(a.runtime) && !a.unconfinedOk)
14
+ throw new Usage(
15
+ `${a.label} can read files outside the folder it works in (its sandbox confines writes, not reads). Pass --unconfined-reads-ok to start it anyway, or --with claude, which is confined. Nothing was opened.`
16
+ );
17
+ }
18
+ function joinArgs(a) {
19
+ return [
20
+ "join",
21
+ "-",
22
+ "--dir",
23
+ a.dir,
24
+ "--with",
25
+ a.runtime,
26
+ ...a.model ? ["--model", a.model] : [],
27
+ ...UNCONFINED.has(a.runtime) && a.unconfinedOk ? ["--unconfined-reads-ok"] : []
28
+ ];
29
+ }
30
+ var shellArg = (s) => /^[\w@%+=:,./\\-]+$/.test(s) ? s : `"${s.replace(/"/g, '\\"')}"`;
31
+ var agentLogPath = (roomId, letter) => path.join(dataDir(), "agents", `${roomId.slice(0, 12)}-${letter}.log`);
32
+ function startLocalAgent(link, a, where, o = {}) {
33
+ if (!o.spawn && process.env.PARLEY_NO_LOCAL_AGENTS === "1") throw new Usage("Starting an agent on this computer is turned off here (PARLEY_NO_LOCAL_AGENTS).");
34
+ const start = o.spawn ?? spawn;
35
+ const log = agentLogPath(where.roomId, where.letter);
36
+ mkdirSync(path.dirname(log), { recursive: true });
37
+ const fd = openSync(log, "a");
38
+ try {
39
+ const child = start(process.execPath, [...process.execArgv, process.argv[1], ...joinArgs(a)], {
40
+ detached: true,
41
+ stdio: ["pipe", fd, fd],
42
+ windowsHide: true,
43
+ cwd: a.dir
44
+ });
45
+ child.stdin.end(`${link}
46
+ `);
47
+ child.unref();
48
+ } finally {
49
+ closeSync(fd);
50
+ }
51
+ return { log };
52
+ }
53
+
54
+ export {
55
+ checkConfinement,
56
+ joinArgs,
57
+ shellArg,
58
+ agentLogPath,
59
+ startLocalAgent
60
+ };
@@ -0,0 +1,20 @@
1
+ import { createRequire as __parleyRequire } from 'node:module'; const require = __parleyRequire(import.meta.url);
2
+
3
+ // ../../node_modules/.pnpm/@anthropic-ai+sdk@1.3.0_zod@4.6.7/node_modules/@anthropic-ai/sdk/internal/node.mjs
4
+ import * as child_process from "node:child_process";
5
+ import * as crypto from "node:crypto";
6
+ import * as fs from "node:fs";
7
+ import * as os from "node:os";
8
+ import * as path from "node:path";
9
+ import * as stream from "node:stream";
10
+ import * as util from "node:util";
11
+
12
+ export {
13
+ child_process,
14
+ crypto,
15
+ fs,
16
+ os,
17
+ path,
18
+ stream,
19
+ util
20
+ };