@leonidstern/labit 0.6.3-main.15 → 0.6.3-main.17

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/dist/local.mjs CHANGED
@@ -4,14 +4,16 @@ import {
4
4
  intentFromText,
5
5
  slim,
6
6
  upgrade
7
- } from "./chunk-FRJUZ6AN.mjs";
7
+ } from "./chunk-Q4IDYYZO.mjs";
8
8
  import {
9
+ PARKED,
9
10
  REGISTRY,
10
11
  WRITE_SHORT,
11
12
  keyFor,
13
+ parkedLabs,
12
14
  parseArgs,
13
15
  runningLabs
14
- } from "./chunk-B5QP5NGM.mjs";
16
+ } from "./chunk-ZL5RPOIP.mjs";
15
17
  import {
16
18
  AGENTS,
17
19
  agentKind,
@@ -32,8 +34,6 @@ import fs from "node:fs";
32
34
  import path from "node:path";
33
35
  import zlib from "node:zlib";
34
36
  async function apiOn(db2) {
35
- process.env.KV_REST_API_URL = "http://lab.store";
36
- process.env.KV_REST_API_TOKEN = "local";
37
37
  const hash = (k) => db2.get(k) ?? (db2.set(k, /* @__PURE__ */ new Map()), db2.get(k));
38
38
  const cmds = {
39
39
  HSET: (k, ...pairs) => {
@@ -55,7 +55,7 @@ async function apiOn(db2) {
55
55
  return v;
56
56
  },
57
57
  EXPIRE: () => 1,
58
- // The one script the API sends (its SWAP): set the field only if it still holds what was read.
58
+ // Set the field only if it still holds what was read (the API's SWAP).
59
59
  EVAL: (_script, _keys, k, f, was, next) => db2.get(k)?.get(f) === was ? (db2.get(k).set(f, next), 1) : 0,
60
60
  GET: (k) => ["string", "number"].includes(typeof db2.get(k)) ? String(db2.get(k)) : null,
61
61
  SET: (k, v, ex, sec) => {
@@ -64,17 +64,15 @@ async function apiOn(db2) {
64
64
  return "OK";
65
65
  }
66
66
  };
67
- const realFetch = globalThis.fetch;
68
- const store = apiOn.store = { calls: 0 };
69
- globalThis.fetch = async (url, init) => {
70
- if (!String(url).startsWith("http://lab.store")) return realFetch(url, init);
71
- store.calls++;
72
- const one = ([name, ...args]) => cmds[name] ? { result: cmds[name](...args) } : { error: `ERR unknown ${name}` };
73
- if (new URL(String(url)).pathname === "/pipeline") return Response.json(JSON.parse(String(init?.body)).map(one));
74
- const out = one(JSON.parse(String(init?.body)));
75
- return Response.json(out, { status: out.error ? 400 : 200 });
67
+ const one = ([name, ...args]) => {
68
+ if (!cmds[name]) throw new Error(`unknown command ${name}`);
69
+ return cmds[name](...args);
76
70
  };
77
- return import("./lab-comments-XAVYAP4Z.mjs");
71
+ const run = async (...command) => one(command);
72
+ run.all = async (...commands) => commands.filter((c) => Boolean(c)).map(one);
73
+ const api2 = await import("./comments-api-Q5QSCGYS.mjs");
74
+ api2.useStore(run);
75
+ return api2;
78
76
  }
79
77
  async function callApi(fn, req, url, extraHeaders = {}) {
80
78
  const chunks = [];
@@ -219,7 +217,7 @@ var VERSION2 = JSON.parse(fs3.readFileSync(path3.join(REPO, "package.json"), "ut
219
217
  var HELP = `labit ${VERSION2}: comment on local pages, your agent (Claude, Codex, Cursor\u2026) answers on the pins.
220
218
  Run it as npx @leonidstern/labit \u2026, or node local.mjs \u2026 from a clone.
221
219
 
222
- labit [--proxy [port]] [--port 4400] [--wifi] [--no-open] [folder]
220
+ labit [--name "topic"] [--proxy [port]] [--port 4400] [--wifi] [--no-open] [folder]
223
221
  Run it in your project. If the project has a dev server (Astro, Next, Vite\u2026) running, comments go on top
224
222
  of it: it finds the server run from this folder, even with other projects' servers running. Give
225
223
  --proxy <port> to pick one yourself. A folder of HTML files is served as it is at http://localhost:4400
@@ -227,16 +225,19 @@ Run it as npx @leonidstern/labit \u2026, or node local.mjs \u2026 from a clone.
227
225
  --wifi lets phones and laptops on the same wifi comment too (as guests). Each one needs a one-time link
228
226
  (labit invite), so finding the port isn't enough. The pages still travel in the clear over the wifi.
229
227
  A folder that a running lab already serves opens in that lab; --new starts a separate one anyway.
228
+ --name gives the lab its topic ("Lab navigation"), shown in labs & pages (\u2318K) instead of the folder; it's
229
+ kept in .lab/name, so later starts keep it.
230
+ labit publish <page.html | folder> [--name "topic"]
231
+ Show a page the way an Artifact is shown: it goes into your one pages lab (pagesFolder, ~/lab-pages), which
232
+ starts if it isn't running, and the page's link is printed. Publish it again to update it, at the same link.
230
233
  labit list
231
234
  Every lab running on this computer: its address, folder, pages and open comments. Check it before starting one.
232
235
  labit pages [--all]
233
- Write .lab/lab-pages.md here: this folder's labs and saved cloud pages as links, with open comment counts.
236
+ Write .lab/lab-pages.md here: this folder's labs as links, with open comment counts.
234
237
  --all lists every lab on this computer.
235
238
  labit settings
236
239
  Each setting, its value and where it came from: a flag or variable, labit.json in the project, your own
237
240
  ~/.config/labit/settings.json, or the default. See docs/settings.md.
238
- labit add <url> [--name "title"] \xB7 labit remove <url>
239
- Save a cloud lab page (https://<lab domain>/<page>) for this folder, in .lab/links.json.
240
241
  labit mcp
241
242
  Optional: an MCP server (stdin/stdout) for agents with MCP: tools comments, reply, pin and wait, for this folder's lab.
242
243
  Claude Code: claude mcp add labit -- npx @leonidstern/labit@latest mcp
@@ -279,8 +280,8 @@ var die = (msg) => {
279
280
  };
280
281
  if (unknownFlags.length) die(`Unknown option ${unknownFlags[0]}. See: ${CMD} --help`);
281
282
  var HERE = fs3.realpathSync(path3.resolve(opts.dir || "."));
282
- var COMMANDS = ["preview", "add", "remove", "list", "pages", "wait", "reply", "resolve", "pin", "invite", "mcp", "settings"];
283
- var { loadSettings, changedShortcuts, savePersonal, saveFlag } = await import("./settings-T6OQSQH4.mjs");
283
+ var COMMANDS = ["publish", "preview", "list", "pages", "wait", "reply", "resolve", "pin", "invite", "mcp", "settings"];
284
+ var { loadSettings, changedShortcuts, savePersonal, saveFlag } = await import("./settings-OTB7HBCL.mjs");
284
285
  var { FLAGS, flagsOn } = await import("./flags-PGKWZHJC.mjs");
285
286
  var SETTINGS = loadSettings(HERE, {
286
287
  port: opts.port !== void 0 && opts.port !== true ? Number(opts.port) : void 0,
@@ -317,12 +318,12 @@ Yours: ${home(SETTINGS.files.personal)}${fs3.existsSync(SETTINGS.files.persona
317
318
  A flag or variable wins over labit.json, which wins over your file. See docs/settings.md.`);
318
319
  process.exit(SETTINGS.problems.length ? 1 : 0);
319
320
  }
320
- if (["preview", "add", "remove", "list", "pages", "wait", "reply", "resolve", "pin", "invite"].includes(pos[0])) {
321
- const { runCommand } = await import("./commands-P7L2JAN6.mjs");
321
+ if (["publish", "preview", "list", "pages", "wait", "reply", "resolve", "pin", "invite"].includes(pos[0])) {
322
+ const { runCommand } = await import("./commands-ITXC5TEQ.mjs");
322
323
  await runCommand({ pos, opts, HERE, CMD, ME, die });
323
324
  }
324
325
  if (pos[0] === "mcp") {
325
- const { runMcp } = await import("./mcp-6CQVLVZW.mjs");
326
+ const { runMcp } = await import("./mcp-VC7FJ3PY.mjs");
326
327
  await runMcp({ HERE, ME, CMD, VERSION: VERSION2, WRITE_SHORT, AGENTS, agentKind, agentNow });
327
328
  }
328
329
  if (pos[0] && !fs3.existsSync(pos[0])) die(`No folder ${pos[0]}. Run ${CMD} in your project, or name a folder (see --help)`);
@@ -406,6 +407,16 @@ var ARCHIVE = path3.join(LAB, "archive");
406
407
  var SERVER = path3.join(LAB, "server.json");
407
408
  var SEEN = path3.join(LAB, "seen");
408
409
  fs3.mkdirSync(LAB, { recursive: true });
410
+ var NAME_FILE = path3.join(LAB, "name");
411
+ var SERVES = !COMMANDS.includes(pos[0]);
412
+ if (SERVES && typeof opts.name === "string" && opts.name.trim()) fs3.writeFileSync(NAME_FILE, opts.name.trim().slice(0, 80) + "\n");
413
+ var LAB_NAME = (() => {
414
+ try {
415
+ return fs3.readFileSync(NAME_FILE, "utf8").trim() || path3.basename(ROOT);
416
+ } catch {
417
+ return path3.basename(ROOT);
418
+ }
419
+ })();
409
420
  var alreadyHere = (running) => {
410
421
  if (process.env.PORT && !opts.port && Number(process.env.PORT) !== running.port)
411
422
  die(`[lab] already running for this folder at http://localhost:${running.port}. Stop that one (Ctrl+C) to open it here.`);
@@ -485,7 +496,6 @@ var TOKEN = (() => {
485
496
  return k;
486
497
  })();
487
498
  var AGENT_KEY = randomBytes(16).toString("hex");
488
- process.env.LAB_HOST = "localhost";
489
499
  process.env.LAB_COMMENTS_ADMIN_TOKEN = TOKEN;
490
500
  var writeAtomic = (file2, text, mode2) => {
491
501
  fs3.writeFileSync(file2 + ".tmp", text, mode2 ? { mode: mode2 } : void 0);
@@ -547,7 +557,6 @@ if (migrate) {
547
557
  console.log(`[lab] comments are now kept one file per page in .lab/comments/ (the old file is .lab/comments.json.bak)`);
548
558
  }
549
559
  fs3.mkdirSync(STORE, { recursive: true });
550
- process.env.LAB_COMMENTS_PER_HOUR ||= "600";
551
560
  var api = await apiOn(db);
552
561
  var commentsOf = (page) => [...db.get(`lab:comments:${page}`)?.values() ?? []].map((v) => JSON.parse(v)).sort((a, b) => a.createdAt.localeCompare(b.createdAt));
553
562
  var pages = () => [...db.keys()].filter((k) => k.startsWith("lab:comments:") && db.get(k).size).map((k) => k.slice("lab:comments:".length));
@@ -679,7 +688,7 @@ var sourceFor = (page) => {
679
688
  var origin = "";
680
689
  var agentText = async (page) => {
681
690
  const res = await api.GET(new Request(`http://localhost/api?format=text&page=${encodeURIComponent(page)}`, { headers: { host: "localhost" } }));
682
- const text = (await res.text()).replaceAll("https://localhost", origin);
691
+ const text = (await res.text()).replaceAll("http://localhost", origin);
683
692
  const local = text.replaceAll(`${ROOT}/`, "").replace(/^to answer: POST .*$/m, `to answer: ${CMD} reply <id> "what you did" [--resolve], run in ${ROOT}`);
684
693
  return fileFor(page) ? local.replace(/^(page: .*)$/m, `$1
685
694
  file: ${fileFor(page)}`) : local;
@@ -942,19 +951,25 @@ var rulesSent = /* @__PURE__ */ new Map();
942
951
  var toldAt = /* @__PURE__ */ new Map();
943
952
  var mode = "away";
944
953
  var awayTimer;
954
+ var BETWEEN_MS = Number(process.env.LAB_BETWEEN_MS ?? 45e3);
955
+ var betweenTimer;
956
+ var recent = [];
945
957
  var setMode = (m) => {
946
958
  mode = m;
947
959
  clearTimeout(awayTimer);
948
- if (m === "working") awayTimer = setTimeout(() => setMode("away"), 6e5);
960
+ clearTimeout(betweenTimer);
961
+ if (m === "away") recent = [];
962
+ if (m === "working") awayTimer = setTimeout(() => setMode(waiters.length ? "listening" : "away"), 6e5);
949
963
  saveServer();
950
964
  broadcast();
951
965
  };
952
966
  var PORT = Number(opts.port || process.env.PORT || 4400);
967
+ var STARTED = (/* @__PURE__ */ new Date()).toISOString();
953
968
  var registryFile = () => path3.join(REGISTRY, `${PORT}.json`);
954
969
  var register = () => {
955
970
  try {
956
971
  fs3.mkdirSync(REGISTRY, { recursive: true });
957
- writeAtomic(registryFile(), JSON.stringify({ port: PORT, pid: process.pid, root: ROOT, name: path3.basename(ROOT), proxy: PROXY?.origin || null, startedAt: (/* @__PURE__ */ new Date()).toISOString() }, null, 2));
972
+ writeAtomic(registryFile(), JSON.stringify({ port: PORT, pid: process.pid, root: ROOT, name: LAB_NAME, proxy: PROXY?.origin || null, startedAt: (/* @__PURE__ */ new Date()).toISOString() }, null, 2));
958
973
  } catch {
959
974
  }
960
975
  };
@@ -964,6 +979,38 @@ setInterval(() => {
964
979
  for (const c of clients) c.res.write("event: beat\ndata: 1\n\n");
965
980
  }, 15e3).unref();
966
981
  var READS = path3.join(LAB, "reads.json");
982
+ var OPENED = path3.join(LAB, "opened.json");
983
+ var opened = (() => {
984
+ try {
985
+ return new Map(Object.entries(JSON.parse(fs3.readFileSync(OPENED, "utf8"))));
986
+ } catch {
987
+ return /* @__PURE__ */ new Map();
988
+ }
989
+ })();
990
+ var openedTimer = null;
991
+ var markOpened = (page) => {
992
+ opened.set(page, (/* @__PURE__ */ new Date()).toISOString());
993
+ openedTimer ??= setTimeout(() => {
994
+ openedTimer = null;
995
+ try {
996
+ writeAtomic(OPENED, JSON.stringify(Object.fromEntries(opened)));
997
+ } catch {
998
+ }
999
+ }, 3e3);
1000
+ };
1001
+ var ARCHIVED = path3.join(LAB, "archived.json");
1002
+ var archivedPages = (() => {
1003
+ try {
1004
+ return new Map(Object.entries(JSON.parse(fs3.readFileSync(ARCHIVED, "utf8"))));
1005
+ } catch {
1006
+ return /* @__PURE__ */ new Map();
1007
+ }
1008
+ })();
1009
+ var archivePage = (page, on) => {
1010
+ if (on) archivedPages.set(page, (/* @__PURE__ */ new Date()).toISOString());
1011
+ else archivedPages.delete(page);
1012
+ writeAtomic(ARCHIVED, JSON.stringify(Object.fromEntries(archivedPages)));
1013
+ };
967
1014
  var bare = (o) => Object.assign(/* @__PURE__ */ Object.create(null), o);
968
1015
  var readSide = (file2, what) => {
969
1016
  let text;
@@ -1010,7 +1057,7 @@ var saveHanded = saver(HANDED2, () => {
1010
1057
  }, "hand-off marks");
1011
1058
  if (Object.keys(handoff).length) saveHanded();
1012
1059
  for (const [id, mark] of Object.entries(readSide(HANDED2, "handed.json") || {})) if (Array.isArray(mark)) handoff[id] = mark;
1013
- var state = (local) => JSON.stringify({ ...version, reads: readsRev, mode, session: session && (local ? session : { name: session.name, agent: session.agent, model: session.model }) });
1060
+ var state = (local) => JSON.stringify({ ...version, reads: readsRev, mode, heard: heard(), session: session && (local ? session : { name: session.name, agent: session.agent, model: session.model }) });
1014
1061
  var broadcast = () => {
1015
1062
  for (const c of clients) c.res.write(`data: ${state(c.local)}
1016
1063
 
@@ -1078,6 +1125,15 @@ var claimed = () => {
1078
1125
  return new Set([...claims].filter(([, at]) => now - at < CLAIM_MS).map(([p]) => p));
1079
1126
  };
1080
1127
  var scopeOf = (w) => w.pages ? pages().filter((p) => w.pages.includes(p)) : pages().filter((p) => !claimed().has(p));
1128
+ var heard = () => {
1129
+ const open = [...waiters, ...recent];
1130
+ const named = new Set(open.flatMap((w) => w.pages || []));
1131
+ const all = open.some((w) => !w.pages);
1132
+ return { all, pages: [...named], except: all ? [...claimed()].filter((p) => !named.has(p)) : [] };
1133
+ };
1134
+ var remember = (w) => {
1135
+ recent = [...recent.filter((r) => r.key !== w.key), { key: w.key, pages: w.pages }];
1136
+ };
1081
1137
  var CLOSE_GRACE = Number(process.env.LAB_CLOSE_GRACE || 3600) * 1e3;
1082
1138
  var TAB_TTL = Number(process.env.LAB_TAB_TTL || 90) * 1e3;
1083
1139
  var tabs = /* @__PURE__ */ new Map();
@@ -1192,7 +1248,7 @@ function deliver(res, got, who = "") {
1192
1248
  saveHanded();
1193
1249
  for (const page of new Set(got.handed.map(([page2]) => page2))) persist(page).catch(() => {
1194
1250
  });
1195
- setMode("working");
1251
+ setMode(waiters.length ? "listening" : "working");
1196
1252
  }
1197
1253
  var SETTLE_MS = Number(process.env.LAB_SETTLE_MS ?? 2e3);
1198
1254
  var REMIND_MS = Number(process.env.LAB_REMIND_MS ?? 18e4);
@@ -1210,6 +1266,7 @@ async function wakeNow() {
1210
1266
  waiters = waiters.filter((x) => x !== w);
1211
1267
  waitEnded = Date.now();
1212
1268
  clearTimeout(w.timer);
1269
+ remember(w);
1213
1270
  deliver(w.res, got, w.who);
1214
1271
  }
1215
1272
  }
@@ -1230,8 +1287,11 @@ var flagsAttr = () => {
1230
1287
  return ` data-flags='${json.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/'/g, "&#39;")}'`;
1231
1288
  };
1232
1289
  var LABIT_ATTR = ` data-labit="${`labit ${VERSION2}${process.env.LABIT_EDGE ? ` \xB7 edge: ${process.env.LABIT_EDGE}` : ""}`.replace(/[<>&'"]/g, "")}"`;
1233
- var widget = (page, admin, me = "") => `<script src="/_lab/comments.js" data-enable="always" data-live="/_lab/live" data-on="1" data-page="${page}" data-version="${version.files}" data-lab="${version.lab}" data-widget="${version.widget}"${me ? ` data-me="${me.replace(/[<>&'"]/g, "")}"` : ""}${KEYS_ATTR}${flagsAttr()}${LABIT_ATTR}${admin ? ` data-admin="${TOKEN}"` : ""} defer></script>
1290
+ var widget = (page, admin, me = "") => {
1291
+ markOpened(page);
1292
+ return `<script src="/_lab/comments.js" data-live="/_lab/live" data-on="1" data-page="${page}" data-version="${version.files}" data-lab="${version.lab}" data-widget="${version.widget}"${me ? ` data-me="${me.replace(/[<>&'"]/g, "")}"` : ""}${KEYS_ATTR}${flagsAttr()}${LABIT_ATTR} data-lab-name="${LAB_NAME.replace(/[<>&'"]/g, "")}"${admin ? ` data-admin="${TOKEN}"` : ""} defer></script>
1234
1293
  `;
1294
+ };
1235
1295
  var inject = (html, tag) => {
1236
1296
  html = html.replace(/<script\b[^>]*\bsrc=["'][^"']*\/_lab\/comments\.js["'][^>]*>\s*<\/script>\s*/gi, "");
1237
1297
  const lower = html.toLowerCase();
@@ -1315,12 +1375,81 @@ var listing = (res, dir, urlPath) => {
1315
1375
  res.end(
1316
1376
  labPage(
1317
1377
  `labit \xB7 ${esc(path3.basename(dir))}`,
1318
- `<header><h1>${esc(path3.basename(dir))}</h1><p class="lede">${pages2.length} page${pages2.length === 1 ? "" : "s"}${open ? ` \xB7 ${open} open comment${open === 1 ? "" : "s"}` : ""} \xB7 newest first</p></header>` + (many ? `<input class="lab-filter" type="search" placeholder="Filter pages" aria-label="Filter pages" autocomplete="off">` : "") + `<ul class="lab-box lab-rows lab-pages">${li || '<li class="lab-muted" style="padding:8px 10px">No HTML pages here. Running a dev server? Start it, then run labit again.</li>'}</ul><p class="lab-muted lab-hint">On a page, press <kbd>${SET.shortcuts.toggle}</kbd> to show comments, or hold <kbd>\u2325</kbd> and click.</p>` + (many ? `<script>const f=document.querySelector('.lab-filter'),r=[...document.querySelectorAll('.lab-pages li')];f.addEventListener('input',()=>{const q=f.value.trim().toLowerCase();for(const l of r)l.hidden=!!q&&!l.textContent.toLowerCase().includes(q)});addEventListener('keydown',e=>{if(e.key==='/'&&document.activeElement!==f){e.preventDefault();f.focus()}})</script>` : "")
1378
+ `<header><h1>${esc(path3.basename(dir))}</h1><p class="lede">${pages2.length} page${pages2.length === 1 ? "" : "s"}${open ? ` \xB7 ${open} open comment${open === 1 ? "" : "s"}` : ""} \xB7 newest first</p></header>` + (many ? `<input class="lab-filter" type="search" placeholder="Filter pages" aria-label="Filter pages" autocomplete="off">` : "") + `<ul class="lab-box lab-rows lab-pages">${li || '<li class="lab-muted" style="padding:8px 10px">No HTML pages here. Running a dev server? Start it, then run labit again.</li>'}</ul><p class="lab-muted lab-hint lab-keys">On a page, press <kbd>${SET.shortcuts.toggle}</kbd> to show comments, or hold <kbd>\u2325</kbd> and click. <kbd>\u2318K</kbd> goes to another lab.</p><p class="lab-muted lab-hint lab-touch">On a page, hold a spot to comment. \u22EF then "labs &amp; pages" goes to another lab.</p><style>.lab-touch{display:none}@media (pointer:coarse){.lab-keys{display:none}.lab-touch{display:block}}</style>` + (many ? `<script>const f=document.querySelector('.lab-filter'),r=[...document.querySelectorAll('.lab-pages li')];f.addEventListener('input',()=>{const q=f.value.trim().toLowerCase();for(const l of r)l.hidden=!!q&&!l.textContent.toLowerCase().includes(q)});addEventListener('keydown',e=>{if(e.key==='/'&&document.activeElement!==f){e.preventDefault();f.focus()}})</script>` : "")
1319
1379
  )
1320
1380
  );
1321
1381
  };
1322
1382
  var sent = async (req) => JSON.parse(await new Response(req).text() || "{}");
1323
1383
  var answer = (res, data) => res.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" }).end(JSON.stringify(data));
1384
+ var oneEach = (names) => names.filter((n, i) => names.findIndex((m) => m.toLowerCase() === n.toLowerCase()) === i);
1385
+ var created = () => {
1386
+ try {
1387
+ const t = fs3.statSync(LAB).birthtimeMs;
1388
+ if (t > 0) return new Date(t).toISOString();
1389
+ } catch {
1390
+ }
1391
+ const first = pages().flatMap((k) => commentsOf(k).map((c) => c.createdAt)).sort()[0];
1392
+ return first || null;
1393
+ };
1394
+ var labInfo = () => {
1395
+ const tally = (key) => {
1396
+ const all = commentsOf(key);
1397
+ const roots = all.filter((c) => !c.parent);
1398
+ const last = all.flatMap((c) => [c.createdAt, c.resolvedAt]).filter(Boolean).sort().pop() || null;
1399
+ const replies = all.filter((c) => c.parent);
1400
+ return {
1401
+ open: roots.filter((c) => !c.resolved).length,
1402
+ done: roots.filter((c) => c.resolved).length,
1403
+ last,
1404
+ first: roots[0]?.createdAt || null,
1405
+ replies: replies.length,
1406
+ agent: replies.filter((c) => c.session).length,
1407
+ people: oneEach(all.filter((c) => !c.session && c.name).map((c) => String(c.name).trim())).slice(0, 8)
1408
+ };
1409
+ };
1410
+ const edited = (file2) => {
1411
+ try {
1412
+ return file2 ? new Date(fs3.statSync(path3.join(ROOT, file2)).mtimeMs).toISOString() : null;
1413
+ } catch {
1414
+ return null;
1415
+ }
1416
+ };
1417
+ const list = (PROXY ? [] : pagesUnder(ROOT)).map((rel) => ({ url: origin + urlOf(rel), title: titleOf(path3.join(ROOT, rel)), file: rel, key: keyFor(rel) }));
1418
+ if (PROXY) list.push({ url: origin + "/", title: "", file: "", key: "/" });
1419
+ if (PROXY) {
1420
+ for (const key of pages()) if (!list.some((p) => p.key === key)) list.push({ url: origin + key, title: "", file: fileFor(key) || "", key });
1421
+ }
1422
+ return {
1423
+ name: LAB_NAME,
1424
+ root: ROOT,
1425
+ port: PORT,
1426
+ wifi: WIFI,
1427
+ proxy: PROXY?.origin || null,
1428
+ mode: session ? mode : "away",
1429
+ listening: session?.name || null,
1430
+ heard: heard(),
1431
+ started: STARTED,
1432
+ created: created(),
1433
+ pages: list.map(({ key, ...p }) => ({ ...p, path: key, ...tally(key), edited: edited(p.file), opened: opened.get(key) || null, archived: archivedPages.get(key) || null }))
1434
+ };
1435
+ };
1436
+ var keyOk = (req) => {
1437
+ const got = Buffer.from(String(req.headers["x-lab-admin"] || ""));
1438
+ const key = Buffer.from(TOKEN);
1439
+ return got.length === key.length && timingSafeEqual(got, key);
1440
+ };
1441
+ var stopListening = () => {
1442
+ const all = waiters;
1443
+ waiters = [];
1444
+ waitEnded = Date.now();
1445
+ for (const w of all) {
1446
+ clearTimeout(w.timer);
1447
+ w.res.writeHead(423).end("stopped from the page");
1448
+ }
1449
+ recent = [];
1450
+ console.log("[lab] listening stopped from the page");
1451
+ setMode("away");
1452
+ };
1324
1453
  var handler = async (req, res) => {
1325
1454
  try {
1326
1455
  const url = new URL(req.url, origin);
@@ -1436,13 +1565,21 @@ var handler = async (req, res) => {
1436
1565
  const w = { res, pages: want, key, who: whoOf(session) };
1437
1566
  claim(want);
1438
1567
  const got = await unseen(scopeOf(w), w.who);
1439
- if (got?.text) return deliver(res, got, w.who);
1568
+ recent = recent.filter((r) => r.key !== key);
1569
+ if (got?.text) {
1570
+ remember(w);
1571
+ return deliver(res, got, w.who);
1572
+ }
1440
1573
  w.timer = setTimeout(() => {
1441
1574
  if (!waiters.includes(w)) return;
1442
1575
  waiters = waiters.filter((x) => x !== w);
1443
1576
  waitEnded = Date.now();
1444
1577
  res.writeHead(204).end();
1445
- if (!waiters.length) setMode("away");
1578
+ if (waiters.length) return broadcast();
1579
+ remember(w);
1580
+ clearTimeout(betweenTimer);
1581
+ betweenTimer = setTimeout(() => !waiters.length && mode === "listening" && setMode("away"), BETWEEN_MS);
1582
+ broadcast();
1446
1583
  }, Math.min(Number(timeout) || 1500, 7e3) * 1e3);
1447
1584
  if (!openTabs() && Date.now() - waitEnded > 12e4) closedSince = Date.now();
1448
1585
  waiters.push(w);
@@ -1455,24 +1592,117 @@ var handler = async (req, res) => {
1455
1592
  waitEnded = Date.now();
1456
1593
  clearTimeout(w.timer);
1457
1594
  if (!waiters.length) setMode("away");
1595
+ else broadcast();
1458
1596
  });
1459
1597
  return;
1460
1598
  }
1599
+ if (pathname === "/_lab/labs" && req.method === "GET") {
1600
+ const here = isLoopback(req);
1601
+ const mine = { ...labInfo(), here: true };
1602
+ const others = await Promise.all(
1603
+ runningLabs().filter((l) => l.port !== PORT).map(async (l) => {
1604
+ try {
1605
+ const r = await fetch(`http://localhost:${l.port}/_lab/pages`, { signal: AbortSignal.timeout(1500) });
1606
+ return { ...await r.json(), port: l.port, here: false };
1607
+ } catch {
1608
+ return { name: l.name, root: l.root, port: l.port, here: false, pages: [], mode: "away", unreachable: true };
1609
+ }
1610
+ })
1611
+ );
1612
+ others.sort((a, b) => a.name.localeCompare(b.name));
1613
+ if (here) return answer(res, { labs: [mine, ...others], parked: parkedLabs().filter((p) => !runningLabs().some((l) => l.port === p.port)), guest: false });
1614
+ const forGuest = (lab2, hop) => ({
1615
+ name: lab2.name,
1616
+ port: lab2.port,
1617
+ here: lab2.here,
1618
+ mode: lab2.mode,
1619
+ listening: lab2.listening,
1620
+ created: lab2.created,
1621
+ started: lab2.started,
1622
+ pages: lab2.pages.map(({ url: url2, root: _root, file: _file, ...p }) => ({ ...p, url: hop ? `/_lab/hop?port=${lab2.port}&to=${encodeURIComponent(p.path)}` : new URL(url2).pathname }))
1623
+ });
1624
+ const local = others.filter((l) => !l.wifi || l.unreachable).map((l) => ({ name: l.name, port: l.port }));
1625
+ const self = wifiAddrs().includes(String(req.socket.remoteAddress || "").replace(/^::ffff:/, "")) ? `http://localhost:${PORT}${url.searchParams.get("page") || "/"}` : null;
1626
+ return answer(res, { labs: [forGuest(mine, false), ...others.filter((l) => l.wifi && !l.unreachable).map((l) => forGuest(l, true))], parked: [], guest: true, local, self });
1627
+ }
1628
+ if (pathname === "/_lab/hop" && req.method === "GET") {
1629
+ const n = Number(url.searchParams.get("port"));
1630
+ const lab2 = runningLabs().find((l) => l.port === n && n !== PORT);
1631
+ if (!lab2) return res.writeHead(404, { "content-type": "text/plain" }).end("no such lab running");
1632
+ try {
1633
+ const srv = JSON.parse(fs3.readFileSync(path3.join(lab2.root, ".lab/server.json"), "utf8"));
1634
+ const r = await fetch(`http://localhost:${n}/_lab/invite`, {
1635
+ method: "POST",
1636
+ signal: AbortSignal.timeout(3e3),
1637
+ headers: { "content-type": "application/json", "x-lab-admin": srv.agent || srv.token, "x-lab-agent": "1", origin: `http://localhost:${n}` },
1638
+ body: JSON.stringify({ name: nameFor(req) || "", page: url.searchParams.get("to") || "/" })
1639
+ });
1640
+ if (!r.ok) return res.writeHead(r.status, { "content-type": "text/plain" }).end(await r.text());
1641
+ const { links } = await r.json();
1642
+ const host = String(req.headers.host || "").replace(/:\d+$/, "");
1643
+ const go = links.find((l) => new URL(l).hostname === host) || links[0];
1644
+ return res.writeHead(302, { location: go, "cache-control": "no-store" }).end();
1645
+ } catch {
1646
+ return res.writeHead(502, { "content-type": "text/plain" }).end("that lab did not answer");
1647
+ }
1648
+ }
1649
+ if (pathname === "/_lab/labs" && req.method === "POST") {
1650
+ if (!isLoopback(req) || !keyOk(req)) return res.writeHead(403).end("forbidden");
1651
+ const { action, port, page } = await sent(req);
1652
+ const n = Number(port);
1653
+ if (action === "archive-page" || action === "unarchive-page") {
1654
+ if (typeof page !== "string" || !page.startsWith("/")) return res.writeHead(400).end("page: /path");
1655
+ if (n === PORT) {
1656
+ archivePage(page, action === "archive-page");
1657
+ return answer(res, { ok: true });
1658
+ }
1659
+ }
1660
+ if (action === "start") {
1661
+ const p = parkedLabs().find((x) => x.port === n);
1662
+ if (!p) return res.writeHead(404).end("not parked");
1663
+ if (runningLabs().some((l) => l.port === n)) return res.writeHead(409).end("already running");
1664
+ const env = { ...process.env, ...p.edge ? { LABIT_EDGE: p.edge } : {} };
1665
+ spawn(process.execPath, [...p.execArgv, ...p.argv.filter((a) => a !== "--no-open"), "--no-open"], { cwd: p.root, env, detached: true, stdio: "ignore" }).unref();
1666
+ fs3.rmSync(path3.join(PARKED, `${n}.json`), { force: true });
1667
+ console.log(`[lab] started ${p.name} again on ${n}`);
1668
+ return answer(res, { ok: true });
1669
+ }
1670
+ const parkedFile = path3.join(PARKED, `${n}.json`);
1671
+ if ((action === "archive" || action === "unarchive") && !runningLabs().some((l) => l.port === n)) {
1672
+ const p = parkedLabs().find((x) => x.port === n);
1673
+ if (!p) return res.writeHead(404).end("not parked");
1674
+ writeAtomic(parkedFile, JSON.stringify({ ...p, archived: action === "archive", at: (/* @__PURE__ */ new Date()).toISOString() }, null, 2));
1675
+ return answer(res, { ok: true });
1676
+ }
1677
+ if (action === "unarchive") return res.writeHead(409).end("running, not archived");
1678
+ if (!["stop", "park", "archive", "archive-page", "unarchive-page"].includes(action)) return res.writeHead(400).end("action: stop, park, archive, unarchive, start, archive-page or unarchive-page");
1679
+ if (n !== PORT) {
1680
+ const lab2 = runningLabs().find((l) => l.port === n);
1681
+ if (!lab2) return res.writeHead(404).end("no lab on that port");
1682
+ try {
1683
+ const key = JSON.parse(fs3.readFileSync(path3.join(lab2.root, ".lab/server.json"), "utf8")).token;
1684
+ const r = await fetch(`http://localhost:${n}/_lab/labs`, { method: "POST", headers: { "content-type": "application/json", "x-lab-admin": key }, body: JSON.stringify({ action, port: n, page }), signal: AbortSignal.timeout(3e3) });
1685
+ return res.writeHead(r.status, { "content-type": "application/json" }).end(await r.text());
1686
+ } catch {
1687
+ return res.writeHead(502).end("that lab did not answer");
1688
+ }
1689
+ }
1690
+ stopListening();
1691
+ if (action === "stop") return answer(res, { ok: true });
1692
+ try {
1693
+ fs3.mkdirSync(PARKED, { recursive: true });
1694
+ const edge = process.env.LABIT_EDGE;
1695
+ writeAtomic(path3.join(PARKED, `${PORT}.json`), JSON.stringify({ port: PORT, root: ROOT, name: LAB_NAME, argv: process.argv.slice(1), execArgv: process.execArgv, ...edge ? { edge } : {}, ...action === "archive" ? { archived: true } : {}, at: (/* @__PURE__ */ new Date()).toISOString() }, null, 2));
1696
+ } catch {
1697
+ }
1698
+ console.log("[lab] parked from the page: start it again from the switcher (\u2318K) in another lab, or run labit here");
1699
+ answer(res, { ok: true });
1700
+ setTimeout(bye, 200);
1701
+ return;
1702
+ }
1461
1703
  if (pathname === "/_lab/pages") {
1462
1704
  if (!isLoopback(req)) return res.writeHead(403, { "content-type": "text/plain" }).end("forbidden");
1463
- const openOn = (key) => commentsOf(key).filter((c) => !c.parent && !c.resolved).length;
1464
- const list = (PROXY ? [] : pagesUnder(ROOT)).map((rel) => ({ url: origin + urlOf(rel), title: titleOf(path3.join(ROOT, rel)), file: rel, key: keyFor(rel) }));
1465
- if (PROXY) list.push({ url: origin + "/", title: "", file: "", key: "/" });
1466
- for (const key of pages()) if (!list.some((p) => p.key === key)) list.push({ url: origin + key, title: "", file: fileFor(key) || "", key });
1467
- return answer(res, {
1468
- name: path3.basename(ROOT),
1469
- root: ROOT,
1470
- port: PORT,
1471
- proxy: PROXY?.origin || null,
1472
- mode,
1473
- listening: session?.name || null,
1474
- pages: list.map(({ key, ...p }) => ({ ...p, path: key, open: openOn(key) }))
1475
- });
1705
+ return answer(res, labInfo());
1476
1706
  }
1477
1707
  if (pathname.startsWith("/_lab/agent/")) {
1478
1708
  res.writeHead(200, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" });
@@ -1610,8 +1840,15 @@ server.on("error", (e) => {
1610
1840
  /** @type {NodeJS.ErrnoException} */
1611
1841
  e.code !== "EADDRINUSE" || fixed || PORT >= Number(opts.port || 4400) + 20
1612
1842
  ) die(`[lab] could not start: ${e.message}`);
1613
- server.listen(++PORT, WIFI ? void 0 : "127.0.0.1");
1843
+ PORT = skipLabs(PORT + 1);
1844
+ server.listen(PORT, WIFI ? void 0 : "127.0.0.1");
1614
1845
  });
1846
+ function skipLabs(port) {
1847
+ if (!opts.port && process.env.PORT) return port;
1848
+ const held = new Set(runningLabs().filter((l) => l.pid !== process.pid).map((l) => l.port));
1849
+ while (held.has(port)) port++;
1850
+ return port;
1851
+ }
1615
1852
  async function newerVersion() {
1616
1853
  if (process.env.LABIT_NO_UPDATE_CHECK || process.env.CI) return null;
1617
1854
  const file2 = path3.join(path3.dirname(REGISTRY), "latest.json");
@@ -1666,4 +1903,5 @@ var bye = () => {
1666
1903
  process.on("SIGINT", bye);
1667
1904
  process.on("SIGTERM", bye);
1668
1905
  process.on("SIGHUP", bye);
1906
+ PORT = skipLabs(PORT);
1669
1907
  server.listen(PORT, WIFI ? void 0 : "127.0.0.1");
@@ -2,7 +2,7 @@ import {
2
2
  WAIT_SAID,
3
3
  findLab,
4
4
  labCall
5
- } from "./chunk-QTMKKULT.mjs";
5
+ } from "./chunk-FVO4473A.mjs";
6
6
  import {
7
7
  mySession
8
8
  } from "./chunk-X4RYDWNI.mjs";
@@ -44,9 +44,9 @@ async function runMcp({ HERE, ME, CMD, VERSION, WRITE_SHORT, AGENTS, agentKind,
44
44
  {
45
45
  name: "comments",
46
46
  title: "Read pin comments",
47
- description: "Open pin comments as plain text: this folder's local lab (all pages), or one cloud lab page when `url` is given. Each comment has its id, words, element, file, line, pixel or second.",
48
- inputSchema: { type: "object", properties: { url: { type: "string", description: "A cloud lab page, https://<lab domain>/<page>" }, dir: { type: "string", description: "The project folder, if the server started somewhere else (default: the client's root or the folder it started in)" } }, additionalProperties: false },
49
- annotations: { readOnlyHint: true, openWorldHint: true }
47
+ description: "Open pin comments as plain text: this folder's local lab (all pages). Each comment has its id, words, element, file, line, pixel or second.",
48
+ inputSchema: { type: "object", properties: { dir: { type: "string", description: "The project folder, if the server started somewhere else (default: the client's root or the folder it started in)" } }, additionalProperties: false },
49
+ annotations: { readOnlyHint: true, openWorldHint: false }
50
50
  },
51
51
  {
52
52
  name: "reply",
@@ -111,20 +111,6 @@ async function runMcp({ HERE, ME, CMD, VERSION, WRITE_SHORT, AGENTS, agentKind,
111
111
  if (extra.length) return text(`Unknown argument ${extra[0]}. ${name} takes: ${Object.keys(props).join(", ") || "nothing"}.`, true);
112
112
  if (limited()) return text("Too many calls in the last minute; wait a moment and try again.", true);
113
113
  if (name === "comments") {
114
- if (a.url !== void 0) {
115
- let u;
116
- try {
117
- u = new URL(String(a.url));
118
- } catch {
119
- }
120
- if (!u || !/^https?:$/.test(u.protocol)) return text(`Not a page address: ${a.url}`, true);
121
- try {
122
- const res = await fetch(`${u.origin}/_lab/agent${u.pathname}`, { signal: AbortSignal.timeout(1e4) });
123
- return text(await res.text(), !res.ok);
124
- } catch (e) {
125
- return text(`Could not read ${u.href}: ${e.message}`, true);
126
- }
127
- }
128
114
  const dir = project(a);
129
115
  const file = path.join(labAbove(dir) || dir, ".lab", "comments.md");
130
116
  if (!fs.existsSync(file)) return text(`No lab in ${dir}. Start one there: ${CMD} (or pass \`dir\`, the project folder)`, true);
@@ -21,6 +21,9 @@ var SPEC = {
21
21
  updateCheck: { type: "boolean", def: true },
22
22
  name: { type: "string", def: "", only: "personal" },
23
23
  model: { type: "string", def: "", only: "personal" },
24
+ // The one lab for pages that belong to no project (tries, demos, options): agents add pages there, a folder per
25
+ // topic, instead of starting a lab of their own (Leo 18 Nov: "def reuse it, why we have so much").
26
+ pagesFolder: { type: "string", def: "~/lab-pages", only: "personal" },
24
27
  shortcuts: { type: "shortcuts", def: SHORTCUTS },
25
28
  // What is being tried here (lib/flags.ts). Off unless a file or the ⋯ menu turns one on.
26
29
  flags: { type: "flags", def: flagDefaults() }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leonidstern/labit",
3
- "version": "0.6.3-main.15",
3
+ "version": "0.6.3-main.17",
4
4
  "description": "Pin comments on pages, read by your agent as plain text. Local mode: comment on pages on your computer and Claude answers on the pins.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -22,6 +22,7 @@
22
22
  "prepack": "npm run build:cli",
23
23
  "typecheck": "node ci/metrics.mjs types",
24
24
  "deadcode": "npx --yes knip@5.66.0 --include files,exports,types --no-progress",
25
+ "reuse": "node ci/reuse.mjs",
25
26
  "test": "node --import ./test/setup.mjs --test test/*.test.mjs"
26
27
  },
27
28
  "engines": {
@@ -33,8 +34,7 @@
33
34
  "review",
34
35
  "claude",
35
36
  "agent",
36
- "astro",
37
- "vercel"
37
+ "astro"
38
38
  ],
39
39
  "repository": {
40
40
  "type": "git",