@leonidstern/labit 0.6.3-main.1 → 0.6.3-main.11

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
@@ -1,10 +1,17 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ VERSION,
4
+ intentFromText,
5
+ slim,
6
+ upgrade
7
+ } from "./chunk-FRJUZ6AN.mjs";
2
8
  import {
3
9
  REGISTRY,
4
10
  WRITE_SHORT,
11
+ keyFor,
5
12
  parseArgs,
6
13
  runningLabs
7
- } from "./chunk-XZUZQFBJ.mjs";
14
+ } from "./chunk-B5QP5NGM.mjs";
8
15
  import {
9
16
  AGENTS,
10
17
  agentKind,
@@ -24,8 +31,7 @@ import { fileURLToPath } from "node:url";
24
31
  import fs from "node:fs";
25
32
  import path from "node:path";
26
33
  import zlib from "node:zlib";
27
- import { pathToFileURL } from "node:url";
28
- async function apiOn(db2, repo) {
34
+ async function apiOn(db2) {
29
35
  process.env.KV_REST_API_URL = "http://lab.store";
30
36
  process.env.KV_REST_API_TOKEN = "local";
31
37
  const hash = (k) => db2.get(k) ?? (db2.set(k, /* @__PURE__ */ new Map()), db2.get(k));
@@ -43,13 +49,14 @@ async function apiOn(db2, repo) {
43
49
  HDEL: (k, ...fs4) => fs4.filter((f) => db2.get(k)?.delete(f)).length,
44
50
  HVALS: (k) => [...db2.get(k)?.values() ?? []],
45
51
  HLEN: (k) => db2.get(k)?.size ?? 0,
46
- HEXISTS: (k, f) => db2.get(k)?.has(f) ? 1 : 0,
47
52
  INCR: (k) => {
48
53
  const v = (db2.get(k) || 0) + 1;
49
54
  db2.set(k, v);
50
55
  return v;
51
56
  },
52
57
  EXPIRE: () => 1,
58
+ // The one script the API sends (its SWAP): set the field only if it still holds what was read.
59
+ EVAL: (_script, _keys, k, f, was, next) => db2.get(k)?.get(f) === was ? (db2.get(k).set(f, next), 1) : 0,
53
60
  GET: (k) => typeof db2.get(k) === "string" ? db2.get(k) : null,
54
61
  SET: (k, v, ex, sec) => {
55
62
  db2.set(k, String(v));
@@ -67,7 +74,7 @@ async function apiOn(db2, repo) {
67
74
  const out = one(JSON.parse(String(init?.body)));
68
75
  return Response.json(out, { status: out.error ? 400 : 200 });
69
76
  };
70
- return import(pathToFileURL(path.join(repo, "api/lab-comments.mjs")).href);
77
+ return import("./lab-comments-IWYSOZ4X.mjs");
71
78
  }
72
79
  async function callApi(fn, req, url, extraHeaders = {}) {
73
80
  const chunks = [];
@@ -203,98 +210,13 @@ How the person wants answers, for the rest of this session (sent once, and again
203
210
  ${rules.map((r) => `- ${r.text}`).join("\n")}` : "";
204
211
  }
205
212
 
206
- // lib/zoom.ts
207
- var dirOf = (zoom) => zoom === "in" || zoom === "out" ? zoom : null;
208
- var zoomName = (dir) => dir === "out" ? "bigger picture" : "deeper look";
209
- var reEsc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
210
- var VOID = /^(area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)$/i;
211
- function elementAt(html, m) {
212
- const tag = m[1];
213
- const start = m.index;
214
- if (VOID.test(tag) || m[0].endsWith("/>")) return { tag, open: m[0], start, end: start + m[0].length, outer: m[0] };
215
- const re = new RegExp(`<(/?)${reEsc(tag)}\\b[^>]*>`, "gi");
216
- re.lastIndex = start + m[0].length;
217
- let depth = 1;
218
- let k;
219
- while (k = re.exec(html)) {
220
- if (k[0].endsWith("/>")) continue;
221
- depth += k[1] ? -1 : 1;
222
- if (!depth) return { tag, open: m[0], start, end: re.lastIndex, outer: html.slice(start, re.lastIndex) };
223
- }
224
- return null;
225
- }
226
- var TAG = "<([a-zA-Z][a-zA-Z0-9-]*)\\b[^>]*";
227
- function blockById(html, id) {
228
- const m = new RegExp(`${TAG}\\bid="${reEsc(id)}"[^>]*>`).exec(html);
229
- return m ? elementAt(html, m) : null;
230
- }
231
- function topLevel(html) {
232
- const re = /<([a-zA-Z][a-zA-Z0-9-]*)\b[^>]*>/g;
233
- const out = [];
234
- let m;
235
- while (m = re.exec(html)) {
236
- const e = elementAt(html, m);
237
- if (!e) throw new ZoomError(`a <${m[1]}> in what you sent is not closed`);
238
- out.push(e);
239
- re.lastIndex = e.end;
240
- }
241
- return out;
242
- }
243
- var ZoomError = class extends Error {
244
- };
245
- var MARKS = /\s(?:id|data-zoom|data-zoom-of)="[^"]*"/g;
246
- function partOf(html, block) {
247
- const sec = /<section\b[^>]*>/gi;
248
- let q;
249
- while ((q = sec.exec(html)) && q.index <= block.start) {
250
- const e = elementAt(html, Object.assign(q, { 1: "section" }));
251
- if (e && e.start <= block.start && e.end >= block.end) return e;
252
- if (e) sec.lastIndex = e.end;
253
- }
254
- const m = /<(main)\b[^>]*>/i.exec(html) || /<(body)\b[^>]*>/i.exec(html);
255
- const box = m ? elementAt(html, m) : null;
256
- if (!box || block.start < box.start || block.end > box.end) return block;
257
- const re = /<([a-zA-Z][a-zA-Z0-9-]*)\b[^>]*>/g;
258
- re.lastIndex = box.start + box.open.length;
259
- let k;
260
- while ((k = re.exec(html)) && k.index < box.end) {
261
- const e = elementAt(html, k);
262
- if (!e) break;
263
- if (e.start <= block.start && e.end >= block.end) return e;
264
- re.lastIndex = e.end;
265
- }
266
- return block;
267
- }
268
- function place(p) {
269
- const block = blockById(p.html, p.block);
270
- if (!block) throw new ZoomError(`no block with id "${p.block}" on the page`);
271
- const els = topLevel(p.made);
272
- if (els.length !== 1) throw new ZoomError(`send one element (a <section> with everything inside it), you sent ${els.length}`);
273
- const el = els[0];
274
- const base = `${p.block}-${p.dir === "out" ? "bigger" : "deeper"}`;
275
- let id = base;
276
- for (let n = 2; blockById(p.html, id); n++) id = `${base}-${n}`;
277
- const open = el.open.replace(MARKS, "").replace(new RegExp(`^<${reEsc(el.tag)}`), `<${el.tag} id="${id}" data-zoom="${p.dir}" data-zoom-of="${p.block}"`);
278
- const placed = el.outer.replace(el.open, open).trim();
279
- const part = partOf(p.html, block);
280
- let end = part.end;
281
- for (; ; ) {
282
- const m = /^\s*<([a-zA-Z][a-zA-Z0-9-]*)\b[^>]*\bdata-zoom="in"[^>]*>/.exec(p.html.slice(end));
283
- const next = m && elementAt(p.html, Object.assign(m, { index: end + m[0].indexOf("<") }));
284
- if (!next) break;
285
- end = next.end;
286
- }
287
- const html = p.dir === "in" ? p.html.slice(0, end) + "\n" + placed + p.html.slice(end) : p.html.slice(0, part.start) + placed + "\n" + p.html.slice(part.start);
288
- return { html, id };
289
- }
290
-
291
213
  // local.mjs
292
214
  var SELF_DIR = path3.dirname(fileURLToPath(import.meta.url));
293
215
  var REPO = path3.basename(SELF_DIR) === "dist" ? path3.dirname(SELF_DIR) : SELF_DIR;
294
216
  var ME = fileURLToPath(import.meta.url);
295
217
  var CMD = REPO.split(path3.sep).includes("node_modules") ? "npx @leonidstern/labit" : `node ${ME}`;
296
- var VERSION = JSON.parse(fs3.readFileSync(path3.join(REPO, "package.json"), "utf8")).version;
297
- var HELP = `labit ${VERSION}: comment on local pages, your agent (Claude, Codex, Cursor\u2026) answers on the pins.
218
+ var VERSION2 = JSON.parse(fs3.readFileSync(path3.join(REPO, "package.json"), "utf8")).version;
219
+ var HELP = `labit ${VERSION2}: comment on local pages, your agent (Claude, Codex, Cursor\u2026) answers on the pins.
298
220
  Run it as npx @leonidstern/labit \u2026, or node local.mjs \u2026 from a clone.
299
221
 
300
222
  labit [--proxy [port]] [--port 4400] [--wifi] [--no-open] [folder]
@@ -316,7 +238,7 @@ Run it as npx @leonidstern/labit \u2026, or node local.mjs \u2026 from a clone.
316
238
  labit add <url> [--name "title"] \xB7 labit remove <url>
317
239
  Save a cloud lab page (https://<lab domain>/<page>) for this folder, in .lab/links.json.
318
240
  labit mcp
319
- Optional: an MCP server (stdin/stdout) for agents with MCP: tools comments, reply and wait, for this folder's lab.
241
+ Optional: an MCP server (stdin/stdout) for agents with MCP: tools comments, reply, pin and wait, for this folder's lab.
320
242
  Claude Code: claude mcp add labit -- npx @leonidstern/labit@latest mcp
321
243
  Codex: codex mcp add labit -- npx @leonidstern/labit@latest mcp
322
244
  labit preview [folder]
@@ -335,18 +257,20 @@ For the agent, from the project (any folder under it):
335
257
  wait left in the foreground holds the person's turn open and they can't say anything to you until it ends.
336
258
  An agent that isn't told when a background command ends runs it in the foreground: wait --timeout 50, in a loop.
337
259
  The page then says it talks to this session. With the page closed it keeps waiting, and ends after an hour of no page.
338
- labit reply <id> "what you did" [--resolve] [--wait] [--page /path]
339
- Answer on the pin. Use the id that wait printed (the number on the card works too, but shifts after a delete). --resolve closes the thread; --wait listens again right after.
260
+ labit reply <id> "what you did" [--done | --on-it | --question] [--resolve] [--wait] [--page /path]
261
+ Answer on the pin. Use the id that wait printed (the number on the card works too, but shifts after a delete). --done says the ask is done (the
262
+ thread closes), --on-it that you're working on it, --question that you need the person; --resolve closes the thread; --wait listens again right after.
340
263
  labit resolve <id> [--page /path]
341
- labit zoom <id> <file>
342
- Answer a zoom: <file> holds one element, the deeper look or the bigger picture. The lab places it on the page.
264
+ labit pin <selector> "text" [--page /path] [--at x,y]
265
+ Leave your own pin on a spot: for suggestions and questions about the page, one pin per point, numbered, instead
266
+ of a list in a reply. --at: where on the element, as shares of it (default 0.5,0.5, its middle). Prints the pin's id.
343
267
 
344
268
  Files in .lab/ inside the folder: comments.md (every open comment as text), comments/ (the store, one file per
345
- page), archive/ (done threads with nothing new in 30 days), server.json (port, key, session; owner-only), seen.
269
+ page), archive/ (done threads with nothing new in 30 days), server.json (port, keys, session; owner-only), seen.
346
270
  Delete .lab to start over.`;
347
271
  var { opts, pos, unknownFlags } = parseArgs(process.argv.slice(2));
348
272
  if (opts.help || opts.version) {
349
- console.log(opts.version ? VERSION : HELP);
273
+ console.log(opts.version ? VERSION2 : HELP);
350
274
  process.exit(0);
351
275
  }
352
276
  var die = (msg) => {
@@ -355,8 +279,8 @@ var die = (msg) => {
355
279
  };
356
280
  if (unknownFlags.length) die(`Unknown option ${unknownFlags[0]}. See: ${CMD} --help`);
357
281
  var HERE = fs3.realpathSync(path3.resolve(opts.dir || "."));
358
- var COMMANDS = ["preview", "add", "remove", "list", "pages", "wait", "reply", "resolve", "invite", "zoom", "mcp", "settings"];
359
- var { loadSettings, changedShortcuts, savePersonal, saveFlag } = await import("./settings-XLFKONNN.mjs");
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");
360
284
  var { FLAGS, flagsOn } = await import("./flags-PGKWZHJC.mjs");
361
285
  var SETTINGS = loadSettings(HERE, {
362
286
  port: opts.port !== void 0 && opts.port !== true ? Number(opts.port) : void 0,
@@ -381,7 +305,7 @@ if (fromFile("model") && SET.model) process.env.LAB_MODEL = SET.model;
381
305
  for (const p of SETTINGS.problems) console.error(`[labit] ${p}`);
382
306
  if (pos[0] === "settings") {
383
307
  const changed = changedShortcuts(SET.shortcuts);
384
- const show = (k, v) => k === "shortcuts" ? Object.keys(changed).length ? Object.entries(changed).map(([a, key]) => `${a} ${key}`).join(", ") : "the defaults" : k === "zoom" ? v.skill || "the built-in skill" : k === "flags" ? flagsOn(v).join(", ") || "none on" : String(v === "" ? "(none)" : v);
308
+ const show = (k, v) => k === "shortcuts" ? Object.keys(changed).length ? Object.entries(changed).map(([a, key]) => `${a} ${key}`).join(", ") : "the defaults" : k === "flags" ? flagsOn(v).join(", ") || "none on" : String(v === "" ? "(none)" : v);
385
309
  const home = (f) => f.replace(os2.homedir(), "~");
386
310
  const src = (f) => f.split(" + ").map((x) => x === SETTINGS.files.project ? "labit.json" : x === SETTINGS.files.personal ? "your settings" : x).join(" + ");
387
311
  console.log(`Project: ${SETTINGS.files.project ? home(SETTINGS.files.project) : `no labit.json in ${home(HERE)} or above`}
@@ -393,25 +317,42 @@ Yours: ${home(SETTINGS.files.personal)}${fs3.existsSync(SETTINGS.files.persona
393
317
  A flag or variable wins over labit.json, which wins over your file. See docs/settings.md.`);
394
318
  process.exit(SETTINGS.problems.length ? 1 : 0);
395
319
  }
396
- if (["preview", "add", "remove", "list", "pages", "wait", "reply", "resolve", "invite", "zoom"].includes(pos[0])) {
397
- const { runCommand } = await import("./commands-LAQNMF2X.mjs");
320
+ if (["preview", "add", "remove", "list", "pages", "wait", "reply", "resolve", "pin", "invite"].includes(pos[0])) {
321
+ const { runCommand } = await import("./commands-P7L2JAN6.mjs");
398
322
  await runCommand({ pos, opts, HERE, CMD, ME, die });
399
323
  }
400
324
  if (pos[0] === "mcp") {
401
- const { runMcp } = await import("./mcp-4UPGXLZR.mjs");
402
- await runMcp({ HERE, ME, CMD, VERSION, WRITE_SHORT, AGENTS, agentKind, agentNow });
325
+ const { runMcp } = await import("./mcp-6CQVLVZW.mjs");
326
+ await runMcp({ HERE, ME, CMD, VERSION: VERSION2, WRITE_SHORT, AGENTS, agentKind, agentNow });
403
327
  }
404
328
  if (pos[0] && !fs3.existsSync(pos[0])) die(`No folder ${pos[0]}. Run ${CMD} in your project, or name a folder (see --help)`);
405
329
  var ROOT = fs3.realpathSync(path3.resolve(pos[0] || "."));
406
- var alreadyRunning = (() => {
330
+ var answersHere = (port) => new Promise((done) => {
331
+ if (!Number.isInteger(port) || port <= 0) return done(false);
332
+ const req = http.get({ host: "127.0.0.1", port, path: "/_lab/pages", headers: { host: `localhost:${port}` }, timeout: 1500 }, (res) => {
333
+ let t = "";
334
+ res.on("data", (c) => t += c);
335
+ res.on("end", () => {
336
+ try {
337
+ done(JSON.parse(t).root === ROOT);
338
+ } catch {
339
+ done(false);
340
+ }
341
+ });
342
+ });
343
+ req.on("timeout", () => req.destroy());
344
+ req.on("error", () => done(false));
345
+ });
346
+ var runningServer = async () => {
407
347
  try {
408
- process.kill(JSON.parse(fs3.readFileSync(path3.join(ROOT, ".lab/server.json"), "utf8")).pid, 0);
409
- return true;
348
+ const running = JSON.parse(fs3.readFileSync(path3.join(ROOT, ".lab/server.json"), "utf8"));
349
+ return await answersHere(running.port) ? running : null;
410
350
  } catch {
411
- return false;
351
+ return null;
412
352
  }
413
- })();
414
- if (!alreadyRunning && !opts.new && !["wait", "reply", "resolve", "zoom"].includes(pos[0])) {
353
+ };
354
+ var alreadyRunning = Boolean(await runningServer());
355
+ if (!alreadyRunning && !opts.new && !["wait", "reply", "resolve", "pin"].includes(pos[0])) {
415
356
  const home = runningLabs().find((lab) => ROOT.startsWith(lab.root + path3.sep));
416
357
  if (home) {
417
358
  const url = `http://localhost:${home.port}/${path3.relative(home.root, ROOT).split(path3.sep).map(encodeURIComponent).join("/")}/`;
@@ -465,15 +406,73 @@ var ARCHIVE = path3.join(LAB, "archive");
465
406
  var SERVER = path3.join(LAB, "server.json");
466
407
  var SEEN = path3.join(LAB, "seen");
467
408
  fs3.mkdirSync(LAB, { recursive: true });
468
- try {
469
- const running = JSON.parse(fs3.readFileSync(SERVER, "utf8"));
470
- process.kill(running.pid, 0);
409
+ var alreadyHere = (running) => {
471
410
  if (process.env.PORT && !opts.port && Number(process.env.PORT) !== running.port)
472
411
  die(`[lab] already running for this folder at http://localhost:${running.port}. Stop that one (Ctrl+C) to open it here.`);
473
412
  console.log(`[lab] already running for this folder: http://localhost:${running.port}`);
474
413
  process.exit(0);
475
- } catch {
414
+ };
415
+ {
416
+ const running = await runningServer();
417
+ if (running) alreadyHere(running);
476
418
  }
419
+ var LOCK = path3.join(LAB, "lock");
420
+ var takeLock = () => {
421
+ try {
422
+ fs3.writeSync(fs3.openSync(LOCK, "wx", 384), JSON.stringify({ pid: process.pid, at: Date.now() }));
423
+ return true;
424
+ } catch (e) {
425
+ if (
426
+ /** @type {NodeJS.ErrnoException} */
427
+ e.code !== "EEXIST"
428
+ ) throw e;
429
+ return false;
430
+ }
431
+ };
432
+ var readLock = () => {
433
+ try {
434
+ return JSON.parse(fs3.readFileSync(LOCK, "utf8"));
435
+ } catch {
436
+ return null;
437
+ }
438
+ };
439
+ var alive = (pid) => {
440
+ try {
441
+ process.kill(pid, 0);
442
+ return true;
443
+ } catch (e) {
444
+ return (
445
+ /** @type {NodeJS.ErrnoException} */
446
+ e.code === "EPERM"
447
+ );
448
+ }
449
+ };
450
+ for (let tries = 0; !takeLock(); tries++) {
451
+ const held = readLock();
452
+ if (held?.port && await answersHere(held.port)) alreadyHere(held);
453
+ const running = await runningServer();
454
+ if (running) alreadyHere(running);
455
+ const age = (() => {
456
+ try {
457
+ return Date.now() - fs3.statSync(LOCK).mtimeMs;
458
+ } catch {
459
+ return Infinity;
460
+ }
461
+ })();
462
+ const stale = !held ? age > 5e3 : !Number.isInteger(held.pid) || !alive(held.pid) || Date.now() - (Number(held.at) || 0) > 6e4 && tries >= 2;
463
+ if (stale && JSON.stringify(readLock()) === JSON.stringify(held)) {
464
+ fs3.rmSync(LOCK, { force: true });
465
+ if (takeLock()) break;
466
+ }
467
+ if (tries >= 40) die(`[lab] another lab is starting for this folder (pid ${held?.pid}) and hasn't answered. If it hangs, stop it, or delete ${LOCK}.`);
468
+ await new Promise((r) => setTimeout(r, 250));
469
+ }
470
+ process.on("exit", () => {
471
+ try {
472
+ if (JSON.parse(fs3.readFileSync(LOCK, "utf8")).pid === process.pid) fs3.rmSync(LOCK);
473
+ } catch {
474
+ }
475
+ });
477
476
  var KEY = path3.join(LAB, "key");
478
477
  var TOKEN = (() => {
479
478
  try {
@@ -485,6 +484,7 @@ var TOKEN = (() => {
485
484
  fs3.writeFileSync(KEY, k, { mode: 384 });
486
485
  return k;
487
486
  })();
487
+ var AGENT_KEY = randomBytes(16).toString("hex");
488
488
  process.env.LAB_HOST = "localhost";
489
489
  process.env.LAB_COMMENTS_ADMIN_TOKEN = TOKEN;
490
490
  var writeAtomic = (file2, text, mode2) => {
@@ -498,7 +498,8 @@ var storeName = (page) => {
498
498
  var savePage = (page, dir = STORE) => {
499
499
  const h = db.get(`lab:comments:${page}`);
500
500
  const file2 = path3.join(dir, storeName(page));
501
- if (h?.size) writeAtomic(file2, `{"page":${JSON.stringify(page)},"comments":{${[...h].map(([id, v]) => `${JSON.stringify(id)}:${v}`).join(",")}}}`);
501
+ const home = homes.get(page);
502
+ if (h?.size) writeAtomic(file2, `{"v":${VERSION},"page":${JSON.stringify(page)},${home ? `"file":${JSON.stringify(home[0])},"fid":"${home[1]}",` : ""}"comments":{${[...h].map(([id, v]) => `${JSON.stringify(id)}:${v}`).join(",")}}}`);
502
503
  else fs3.rmSync(file2, { force: true });
503
504
  };
504
505
  var putAside = (file2, what) => {
@@ -507,6 +508,9 @@ var putAside = (file2, what) => {
507
508
  console.log(`[lab] ${what} was damaged; moved it to ${path3.relative(LAB, aside)}`);
508
509
  };
509
510
  var saved = {};
511
+ var handoff = /* @__PURE__ */ Object.create(null);
512
+ var outdated = [];
513
+ var homes = /* @__PURE__ */ new Map();
510
514
  var migrate = !fs3.existsSync(STORE) && fs3.existsSync(OLD_DATA);
511
515
  if (migrate) {
512
516
  try {
@@ -521,15 +525,17 @@ if (migrate) {
521
525
  if (!name.endsWith(".json")) continue;
522
526
  const file2 = path3.join(STORE, name);
523
527
  try {
524
- const { page, comments } = JSON.parse(fs3.readFileSync(file2, "utf8"));
528
+ const { v, page, comments, file: rel, fid } = JSON.parse(fs3.readFileSync(file2, "utf8"));
525
529
  if (typeof page !== "string" || !page.startsWith("/") || !comments || typeof comments !== "object") throw new Error("not a page");
526
530
  saved[page] = comments;
531
+ if (typeof rel === "string" && /^[\d.]+$/.test(fid)) homes.set(page, [rel, fid]);
532
+ if (v !== VERSION) outdated.push(page);
527
533
  } catch {
528
534
  putAside(file2, `comments/${name}`);
529
535
  }
530
536
  }
531
537
  }
532
- var db = new Map(Object.entries(saved).map(([page, h]) => [`lab:comments:${page}`, new Map(Object.entries(h).map(([id, c]) => [id, JSON.stringify(c)]))]));
538
+ var db = new Map(Object.entries(saved).map(([page, h]) => [`lab:comments:${page}`, new Map(Object.entries(h).map(([id, c]) => [id, JSON.stringify(upgrade(c, handoff))]))]));
533
539
  saved = null;
534
540
  if (migrate) {
535
541
  const fresh = `${STORE}.new`;
@@ -542,7 +548,7 @@ if (migrate) {
542
548
  }
543
549
  fs3.mkdirSync(STORE, { recursive: true });
544
550
  process.env.LAB_COMMENTS_PER_HOUR ||= "600";
545
- var api = await apiOn(db, REPO);
551
+ var api = await apiOn(db);
546
552
  var commentsOf = (page) => [...db.get(`lab:comments:${page}`)?.values() ?? []].map((v) => JSON.parse(v)).sort((a, b) => a.createdAt.localeCompare(b.createdAt));
547
553
  var pages = () => [...db.keys()].filter((k) => k.startsWith("lab:comments:") && db.get(k).size).map((k) => k.slice("lab:comments:".length));
548
554
  var ARCHIVE_DAYS = SET.archiveAfterDays;
@@ -553,7 +559,8 @@ function archiveOld(now = Date.now()) {
553
559
  const h = db.get(`lab:comments:${page}`);
554
560
  const all = [...h.values()].map((v) => JSON.parse(v));
555
561
  const old = all.filter((c) => !c.parent && c.resolved).map((root) => [root, ...all.filter((c) => c.parent === root.id)]).filter((thread) => {
556
- const newest = Math.max(...thread.map((c) => Date.parse(c.createdAt)));
562
+ const dates = [...thread.map((c) => c.createdAt), ...thread[0].resolvedAt ? [thread[0].resolvedAt] : []];
563
+ const newest = Math.max(...dates.map((d) => Date.parse(d)));
557
564
  return Number.isFinite(newest) && now - newest > ARCHIVE_DAYS * 864e5;
558
565
  });
559
566
  if (!old.length) continue;
@@ -566,7 +573,7 @@ function archiveOld(now = Date.now()) {
566
573
  }
567
574
  try {
568
575
  fs3.mkdirSync(ARCHIVE, { recursive: true });
569
- writeAtomic(file2, JSON.stringify({ page, comments: { ...kept, ...Object.fromEntries(old.flat().map((c) => [c.id, c])) } }));
576
+ writeAtomic(file2, JSON.stringify({ v: VERSION, page, comments: { ...kept, ...Object.fromEntries(old.flat().map((c) => [c.id, c])) } }));
570
577
  } catch (e) {
571
578
  console.error(`[lab] could not archive done threads on ${page}:`, e.message);
572
579
  continue;
@@ -579,9 +586,6 @@ function archiveOld(now = Date.now()) {
579
586
  return changed;
580
587
  }
581
588
  for (const p of archiveOld()) savePage(p);
582
- var keyFor = (rel) => "/" + rel.replace(/\.html?$/i, "").split(path3.sep).map(
583
- (seg) => [...Buffer.from(seg.toLowerCase())].map((b, i) => /[a-z0-9]/.test(String.fromCharCode(b)) || b === 45 && i ? String.fromCharCode(b) : `_${b.toString(16)}`).join("")
584
- ).join("/");
585
589
  var fileIndex = null;
586
590
  var fileMemo = /* @__PURE__ */ new Map();
587
591
  var fileMemoAt = Date.now();
@@ -593,24 +597,50 @@ var fileFor = (page) => {
593
597
  if (!fileMemo.has(page)) fileMemo.set(page, findFile(page));
594
598
  return fileMemo.get(page);
595
599
  };
596
- var ZOOM_SKILL = SET.zoom.skill || path3.join(REPO, "skills/labit/zoom.md");
597
600
  var findFile = (page) => {
598
601
  if (!fileIndex) {
599
- fileIndex = /* @__PURE__ */ new Map();
600
- const walk = (dir, depth) => {
601
- for (const d of fs3.readdirSync(dir, { withFileTypes: true })) {
602
- if (d.name.startsWith(".") || d.name === "node_modules") continue;
603
- const full = path3.join(dir, d.name);
604
- if (d.isDirectory() && depth < 6) walk(full, depth + 1);
605
- else if (/\.html?$/i.test(d.name)) fileIndex.set(keyFor(path3.relative(ROOT, full)), path3.relative(ROOT, full));
606
- }
607
- };
608
- walk(ROOT, 0);
602
+ fileIndex = new Map(pagesUnder(ROOT).map((rel) => [keyFor(rel), rel]));
603
+ rehome();
609
604
  }
610
605
  const html = fileIndex.get(page);
611
606
  if (PROXY) return sourceFor(page) || (html && html !== "index.html" ? html : null);
612
607
  return html || sourceFor(page);
613
608
  };
609
+ var fidOf = (rel) => {
610
+ try {
611
+ const st = fs3.statSync(path3.join(ROOT, rel));
612
+ return `${st.ino}.${Math.round(st.birthtimeMs)}`;
613
+ } catch {
614
+ return "";
615
+ }
616
+ };
617
+ function rehome() {
618
+ let byFid = null;
619
+ for (const page of PROXY ? [] : pages()) {
620
+ const [was, fid] = homes.get(page) || [];
621
+ const rel = fileIndex.get(page);
622
+ if (rel) {
623
+ const now = fidOf(rel);
624
+ if (now === fid && rel === was) continue;
625
+ homes.set(page, [rel, now]);
626
+ unsaved.add(page);
627
+ continue;
628
+ }
629
+ byFid ||= new Map([...fileIndex].map(([key, f]) => [fidOf(f), key]));
630
+ const to = fid && byFid.get(fid);
631
+ if (!to) continue;
632
+ const there = db.get(`lab:comments:${to}`) ?? /* @__PURE__ */ new Map();
633
+ for (const [id, c] of db.get(`lab:comments:${page}`)) there.set(id, c);
634
+ db.set(`lab:comments:${to}`, there);
635
+ db.delete(`lab:comments:${page}`);
636
+ homes.delete(page);
637
+ homes.set(to, [fileIndex.get(to), fid]);
638
+ for (const mine of Object.values(reads)) if (mine[page]) mine[to] = [...mine[to] || [], ...mine[page]];
639
+ console.log(`[lab] ${was} is now ${fileIndex.get(to)}: its comments went with it`);
640
+ for (const p of [page, to]) persist(p).catch((e) => console.error("[lab] could not save comments:", e.message));
641
+ broadcast();
642
+ }
643
+ }
614
644
  var realCase = (rel) => {
615
645
  let dir = ROOT;
616
646
  const out = [];
@@ -710,6 +740,7 @@ var shot = /* @__PURE__ */ new Map();
710
740
  var changeLog = [];
711
741
  var takeShot = (p) => new Map(db.get(`lab:comments:${p}`) || []);
712
742
  for (const p of pages()) shot.set(p, takeShot(p));
743
+ for (const p of outdated) unsaved.add(p);
713
744
  function logChanges(page, rev) {
714
745
  for (const p of page ? [page] : [.../* @__PURE__ */ new Set([...pages(), ...shot.keys()])]) {
715
746
  const was = shot.get(p) || /* @__PURE__ */ new Map();
@@ -872,7 +903,11 @@ var redeem = (req, res, code, me = "", to = "") => {
872
903
  if (NAME_OK(me)) cookies.push(`lab_me=${encodeURIComponent(me.trim())}; Path=/; Max-Age=2592000; SameSite=Lax`);
873
904
  return res.writeHead(302, { location: landing(to), "set-cookie": cookies }).end();
874
905
  };
875
- var isAgent = (req) => req.headers["x-lab-agent"] === "1" && req.headers["x-lab-admin"] === TOKEN;
906
+ var isAgent = (req) => {
907
+ const sent2 = Buffer.from(String(req.headers["x-lab-admin"] || ""));
908
+ const key = Buffer.from(AGENT_KEY);
909
+ return req.headers["x-lab-agent"] === "1" && sent2.length === key.length && timingSafeEqual(sent2, key);
910
+ };
876
911
  var sessionFrom = (req) => {
877
912
  try {
878
913
  const s = JSON.parse(decodeURIComponent(req.headers["x-lab-session"] || ""));
@@ -893,6 +928,7 @@ var sessionFrom = (req) => {
893
928
  };
894
929
  var session = null;
895
930
  var rulesSent = /* @__PURE__ */ new Map();
931
+ var toldAt = /* @__PURE__ */ new Map();
896
932
  var mode = "away";
897
933
  var awayTimer;
898
934
  var setMode = (m) => {
@@ -911,31 +947,58 @@ var register = () => {
911
947
  } catch {
912
948
  }
913
949
  };
914
- var saveServer = () => writeAtomic(SERVER, JSON.stringify({ port: PORT, pid: process.pid, token: TOKEN, session }, null, 2), 384);
950
+ var saveServer = () => writeAtomic(SERVER, JSON.stringify({ port: PORT, pid: process.pid, token: TOKEN, agent: AGENT_KEY, session }, null, 2), 384);
915
951
  var clients = /* @__PURE__ */ new Set();
916
952
  setInterval(() => {
917
953
  for (const c of clients) c.res.write("event: beat\ndata: 1\n\n");
918
954
  }, 15e3).unref();
919
955
  var READS = path3.join(LAB, "reads.json");
920
956
  var bare = (o) => Object.assign(/* @__PURE__ */ Object.create(null), o);
921
- var reads = (() => {
957
+ var readSide = (file2, what) => {
958
+ let text;
922
959
  try {
923
- const raw = JSON.parse(fs3.readFileSync(READS, "utf8")) || {};
924
- const out = /* @__PURE__ */ Object.create(null);
925
- for (const [name, pagesOf] of Object.entries(raw)) if (pagesOf && typeof pagesOf === "object") out[name] = bare(pagesOf);
926
- return out;
960
+ text = fs3.readFileSync(file2, "utf8");
927
961
  } catch {
928
- return /* @__PURE__ */ Object.create(null);
962
+ return null;
929
963
  }
964
+ try {
965
+ const data = JSON.parse(text);
966
+ if (data && typeof data === "object" && !Array.isArray(data)) return data;
967
+ } catch {
968
+ }
969
+ putAside(file2, what);
970
+ return null;
971
+ };
972
+ var reads = (() => {
973
+ const out = /* @__PURE__ */ Object.create(null);
974
+ for (const [name, pagesOf] of Object.entries(readSide(READS, "reads.json") || {})) if (pagesOf && typeof pagesOf === "object") out[name] = bare(pagesOf);
975
+ return out;
930
976
  })();
931
977
  var readsBroadcast = 0;
932
978
  var readsRev = 0;
933
979
  var plainName = (n) => String(n || "").replace(/\s+/g, " ").trim().toLowerCase().slice(0, 80);
934
- var readsTimer;
935
- var saveReads = () => {
936
- clearTimeout(readsTimer);
937
- readsTimer = setTimeout(() => fs3.promises.writeFile(READS, JSON.stringify(reads)).catch((e) => console.error("[lab] could not save read marks:", e.message)), 300);
980
+ var saver = (file2, data, what) => {
981
+ let timer;
982
+ return () => {
983
+ clearTimeout(timer);
984
+ timer = setTimeout(() => {
985
+ try {
986
+ writeAtomic(file2, JSON.stringify(data()));
987
+ } catch (e) {
988
+ console.error(`[lab] could not save ${what}:`, e.message);
989
+ }
990
+ }, 300);
991
+ };
938
992
  };
993
+ var saveReads = saver(READS, () => reads, "read marks");
994
+ var HANDED2 = path3.join(LAB, "handed.json");
995
+ var saveHanded = saver(HANDED2, () => {
996
+ const live = new Set(pages().flatMap((p) => [...db.get(`lab:comments:${p}`).keys()]));
997
+ for (const id of Object.keys(handoff)) if (!live.has(id)) delete handoff[id];
998
+ return handoff;
999
+ }, "hand-off marks");
1000
+ if (Object.keys(handoff).length) saveHanded();
1001
+ for (const [id, mark] of Object.entries(readSide(HANDED2, "handed.json") || {})) if (Array.isArray(mark)) handoff[id] = mark;
939
1002
  var state = (local) => JSON.stringify({ ...version, reads: readsRev, mode, session: session && (local ? session : { name: session.name, agent: session.agent, model: session.model }) });
940
1003
  var broadcast = () => {
941
1004
  for (const c of clients) c.res.write(`data: ${state(c.local)}
@@ -959,6 +1022,7 @@ if (!PROXY) fs3.watch(ROOT, { recursive: true }, (event, file2) => {
959
1022
  fileIndex = null;
960
1023
  fileMemo.clear();
961
1024
  indexStale = false;
1025
+ if (pages().length) fileFor(pages()[0]);
962
1026
  }
963
1027
  const hotOnly = !otherSaved && hotSaved.size > 0;
964
1028
  const hot = [...hotSaved].slice(0, 50).map(([p, kind2]) => ({ path: p, kind: kind2 }));
@@ -986,20 +1050,14 @@ var waiters = [];
986
1050
  var CLAIM_MS = 18e5;
987
1051
  var CLAIMS_FILE = path3.join(LAB, "claims.json");
988
1052
  var claims = new Map(
989
- (() => {
990
- try {
991
- return Object.entries(JSON.parse(fs3.readFileSync(CLAIMS_FILE, "utf8"))).filter(([p, at]) => typeof p === "string" && p.startsWith("/") && Number.isFinite(at) && Date.now() - at < CLAIM_MS);
992
- } catch {
993
- return [];
994
- }
995
- })()
1053
+ Object.entries(readSide(CLAIMS_FILE, "claims.json") || {}).filter(([p, at]) => typeof p === "string" && p.startsWith("/") && Number.isFinite(at) && Date.now() - at < CLAIM_MS)
996
1054
  );
997
1055
  var claim = (pages2) => {
998
1056
  if (!pages2?.length) return;
999
1057
  const now = Date.now();
1000
1058
  for (const p of pages2) claims.set(p, now);
1001
1059
  try {
1002
- fs3.writeFileSync(CLAIMS_FILE, JSON.stringify(Object.fromEntries([...claims].filter(([, at]) => now - at < CLAIM_MS))));
1060
+ writeAtomic(CLAIMS_FILE, JSON.stringify(Object.fromEntries([...claims].filter(([, at]) => now - at < CLAIM_MS))));
1003
1061
  } catch {
1004
1062
  }
1005
1063
  };
@@ -1055,18 +1113,18 @@ var rulesOnce = () => {
1055
1113
  rulesSent.set(who, rules);
1056
1114
  return rules;
1057
1115
  };
1058
- async function unseen(scope = pages()) {
1059
- const fresh = scope.flatMap((page) => commentsOf(page).filter((c) => !c.session && !(c.resolved && !c.parent) && stamp(c) > (c.deliveredAt || seen)).map((c) => ({ page, c })));
1116
+ var whoOf = (s) => s?.id || s?.name || "";
1117
+ async function unseen(scope = pages(), who = "") {
1118
+ const fresh = scope.flatMap((page) => commentsOf(page).filter((c) => !c.session && !(c.resolved && !c.parent) && stamp(c) > (handoff[c.id]?.[0] || seen)).map((c) => ({ page, c })));
1060
1119
  const now = Date.now();
1061
1120
  const lastBy = (c, mine) => [c, ...commentsOf(c._page).filter((r) => r.parent === c.id)].filter((m) => Boolean(m.session) === mine).map((m) => m.createdAt).sort().pop() || "";
1062
- const missed = scope.flatMap((page) => commentsOf(page).filter((c) => !c.parent && !c.resolved && c.handedAt).map((c) => ({ page, c: Object.assign(Object.create(c), { _page: page }) }))).filter(({ c }) => now - Date.parse(c.handedAt) > REMIND_MS && lastBy(c, false) > lastBy(c, true) && !(c.remindedAt && now - Date.parse(c.remindedAt) < 6e5)).filter(({ page, c }) => !fresh.some((f) => f.page === page && (f.c.id === c.id || f.c.parent === c.id)));
1121
+ const missed = scope.flatMap((page) => commentsOf(page).filter((c) => !c.parent && !c.resolved && c.handedAt).map((c) => ({ page, c: Object.assign(Object.create(c), { _page: page }) }))).filter(({ c }) => now - Date.parse(c.handedAt) > REMIND_MS && lastBy(c, false) > lastBy(c, true) && !(now - Date.parse(handoff[c.id]?.[2]) < 6e5)).filter(({ page, c }) => !fresh.some((f) => f.page === page && (f.c.id === c.id || f.c.parent === c.id)));
1063
1122
  if (!fresh.length && !missed.length) return null;
1064
1123
  const blocks = [];
1065
- const sent = /* @__PURE__ */ new Set();
1124
+ const sent2 = /* @__PURE__ */ new Set();
1066
1125
  const known = (f) => {
1067
- if (!f.c.parent) return false;
1068
- const root = commentsOf(f.page).find((c) => c.id === f.c.parent);
1069
- return Boolean(root?.deliveredAt) && !fresh.some((g) => g.c.id === root.id);
1126
+ const mark = handoff[f.c.parent];
1127
+ return Boolean(mark?.[0]) && (mark[1] == null || mark[1] === who) && !fresh.some((g) => g.c.id === f.c.parent);
1070
1128
  };
1071
1129
  const replies = fresh.filter(known);
1072
1130
  const whole = fresh.filter((f) => !known(f));
@@ -1074,7 +1132,7 @@ async function unseen(scope = pages()) {
1074
1132
  const block = await threadsText(page, [...new Set(whole.filter((f) => f.page === page).map((f) => f.c.parent || f.c.id))]);
1075
1133
  if (block) {
1076
1134
  blocks.push(block.text);
1077
- block.ids.forEach((id) => sent.add(`${page}
1135
+ block.ids.forEach((id) => sent2.add(`${page}
1078
1136
  ${id}`));
1079
1137
  }
1080
1138
  }
@@ -1084,7 +1142,7 @@ ${id}`));
1084
1142
  const root = commentsOf(f.page).find((c) => c.id === f.c.parent);
1085
1143
  const guest = f.c.from === "wifi guest" ? " (wifi guest)" : "";
1086
1144
  lines.push(`- ${f.page} \xB7 thread id ${root.id} "${root.text.replace(/\s+/g, " ").slice(0, 70)}": ${f.c.name}${guest} \xB7 ${when(f.c)} \xB7 id ${f.c.id}: ${f.c.text.replace(/\s+/g, " ")}`);
1087
- sent.add(`${f.page}
1145
+ sent2.add(`${f.page}
1088
1146
  ${root.id}`);
1089
1147
  }
1090
1148
  if (lines.length) blocks.push(`# New replies (whole threads: http://localhost:${PORT}/_lab/agent/<page>)
@@ -1092,32 +1150,36 @@ ${lines.join("\n")}`);
1092
1150
  if (missed.length) {
1093
1151
  blocks.push(`# Still waiting for your answer (handed to you earlier)
1094
1152
  ${missed.map(({ page, c }) => `- ${page} \xB7 id ${c.id}${c.from === "wifi guest" ? " (wifi guest)" : ""} "${c.text.replace(/\s+/g, " ").slice(0, 90)}"`).join("\n")}`);
1095
- for (const { page, c } of missed) setComment(page, c.id, { remindedAt: new Date(now).toISOString() });
1153
+ for (const { c } of missed) (handoff[c.id] ||= ["", null])[2] = new Date(now).toISOString();
1154
+ saveHanded();
1096
1155
  }
1097
- const given = fresh.filter((f) => sent.has(`${f.page}
1156
+ const given = fresh.filter((f) => sent2.has(`${f.page}
1098
1157
  ${f.c.parent || f.c.id}`));
1099
1158
  if (!given.length && !missed.length) return null;
1100
1159
  const count = [given.filter((f) => !f.c.parent || !known(f)).length && `${given.filter((f) => !f.c.parent || !known(f)).length} new`, replies.length && `${replies.length} repl${replies.length === 1 ? "y" : "ies"}`, missed.length && `${missed.length} still waiting`].filter(Boolean).join(", ");
1160
+ const full = !(now - toldAt.get(who) < 18e5);
1101
1161
  const text = `In this message: ${count}. Read all of it; each one is marked handed to you.
1102
1162
 
1103
- ` + (blocks.length ? `# New comments
1163
+ ${whole.length ? "# New comments\n\n" : ""}${blocks.join("\n\n")}
1104
1164
 
1105
- ${blocks.join("\n\n")}` : "") + `
1106
-
1107
- Answer each: ${CMD} reply <id> "what you did" [--resolve] (run in ${ROOT}); add --wait to the last one to listen again in the same command.` + (/\nzoom: (in|out)\b/.test(blocks.join("\n")) ? `
1108
- A pin that says "zoom": read ${ZOOM_SKILL} first. Write one block to a file, then ${CMD} zoom <id> <file>, then reply.` : "") + (given.some((f) => f.c.parent) ? `
1109
- A reply about how you answered rather than the work (too long, unclear, didn't show or link it, the same misread twice): answer it and add --suggest-rule "<one short rule>"; they keep it with a tap. Not for the work itself or a one-off correction.` : "") + `
1110
- ${WRITE_SHORT}` + rulesOnce();
1111
- const handed = [...sent].map((k) => k.split("\n"));
1165
+ Answer each: ${CMD} reply <id> "what you did" [--done | --on-it | --question]${full ? ` [--resolve] (run in ${ROOT}); add --wait to the last one to listen again in the same command.` : " [--wait]"}` + (given.some((f) => f.c.parent) ? `
1166
+ A reply about how you answered rather than the work (too long, unclear, didn't show or link it, the same misread twice): answer it and add --suggest-rule "<one short rule>"; they keep it with a tap. Not for the work itself or a one-off correction.` : "") + (full ? `
1167
+ ${WRITE_SHORT}` : "") + rulesOnce();
1168
+ const handed = [...sent2].map((k) => k.split("\n"));
1112
1169
  const marks = given.map(({ page, c }) => [page, c.id, stamp(c)]);
1113
- return { text, marks, handed };
1170
+ return { text, marks, handed, full };
1114
1171
  }
1115
- function deliver(res, got) {
1172
+ function deliver(res, got, who = "") {
1116
1173
  res.writeHead(200, { "content-type": "text/plain; charset=utf-8" }).end(got.text);
1117
- for (const [page, id, at2] of got.marks) setComment(page, id, { deliveredAt: at2 });
1174
+ if (got.full) toldAt.set(who, Date.now());
1175
+ for (const [, id, at2] of got.marks) handoff[id] = [at2, who];
1118
1176
  const at = (/* @__PURE__ */ new Date()).toISOString();
1119
- for (const [page, id] of got.handed) setComment(page, id, { handedAt: at });
1120
- for (const page of new Set([...got.marks, ...got.handed].map(([page2]) => page2))) persist(page).catch(() => {
1177
+ for (const [page, id] of got.handed) {
1178
+ (handoff[id] ||= ["", who])[1] = who;
1179
+ setComment(page, id, { handedAt: at });
1180
+ }
1181
+ saveHanded();
1182
+ for (const page of new Set(got.handed.map(([page2]) => page2))) persist(page).catch(() => {
1121
1183
  });
1122
1184
  setMode("working");
1123
1185
  }
@@ -1132,12 +1194,12 @@ function wake() {
1132
1194
  async function wakeNow() {
1133
1195
  for (const w of Array.from(waiters)) {
1134
1196
  if (!waiters.includes(w)) continue;
1135
- const got = await unseen(scopeOf(w));
1197
+ const got = await unseen(scopeOf(w), w.who);
1136
1198
  if (!got?.text || !waiters.includes(w)) continue;
1137
1199
  waiters = waiters.filter((x) => x !== w);
1138
1200
  waitEnded = Date.now();
1139
1201
  clearTimeout(w.timer);
1140
- deliver(w.res, got);
1202
+ deliver(w.res, got, w.who);
1141
1203
  }
1142
1204
  }
1143
1205
  var setComment = (page, id, patch) => {
@@ -1156,7 +1218,8 @@ var flagsAttr = () => {
1156
1218
  const json = JSON.stringify(Object.fromEntries(Object.entries(FLAGS).map(([k, f]) => [k, { name: f.name, on: SET.flags[k] === true }])));
1157
1219
  return ` data-flags='${json.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/'/g, "&#39;")}'`;
1158
1220
  };
1159
- 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()}${admin ? ` data-admin="${TOKEN}"` : ""} defer></script>
1221
+ var LABIT_ATTR = ` data-labit="${`labit ${VERSION2}${process.env.LABIT_EDGE ? ` \xB7 edge: ${process.env.LABIT_EDGE}` : ""}`.replace(/[<>&'"]/g, "")}"`;
1222
+ 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>
1160
1223
  `;
1161
1224
  var inject = (html, tag) => {
1162
1225
  html = html.replace(/<script\b[^>]*\bsrc=["'][^"']*\/_lab\/comments\.js["'][^>]*>\s*<\/script>\s*/gi, "");
@@ -1207,9 +1270,9 @@ var titleOf = (file2) => {
1207
1270
  }
1208
1271
  };
1209
1272
  var labPage = (title, body) => `<!doctype html><meta charset=utf-8><meta name=viewport content="width=device-width, initial-scale=1, viewport-fit=cover"><title>${title}</title><link rel=icon href="/_lab/favicon.svg"><link rel=stylesheet href="/_lab/lab.css"><body class=lab><main><a class="lab-brand" href="/">${markSvg(20)}labit</a>${body}</main></body>`;
1273
+ var esc = (s) => s.replace(/[&<>"]/g, (c) => `&#${c.charCodeAt(0)};`);
1210
1274
  var notFound = (req, res, what) => {
1211
1275
  if (!/text\/html/.test(req.headers.accept || "")) return res.writeHead(404, { "content-type": "text/plain" }).end("not found");
1212
- const esc = (s) => s.replace(/[&<>"]/g, (c) => `&#${c.charCodeAt(0)};`);
1213
1276
  res.writeHead(404, { "content-type": "text/html; charset=utf-8" });
1214
1277
  return res.end(labPage("labit \xB7 not found", `<header><h1>Not found</h1><p class="lede">There's no page at <code>${esc(what)}</code> in this lab.</p></header><p><a class="lab-button" href="/" style="text-decoration:none;display:inline-block">All pages</a></p>`));
1215
1278
  };
@@ -1222,7 +1285,6 @@ var ago = (ms) => {
1222
1285
  return new Date(ms).toLocaleDateString("en-GB", { day: "numeric", month: "short" });
1223
1286
  };
1224
1287
  var listing = (res, dir, urlPath) => {
1225
- const esc = (s) => s.replace(/[&<>"]/g, (c) => `&#${c.charCodeAt(0)};`);
1226
1288
  const pages2 = pagesUnder(dir).map((rel) => {
1227
1289
  const file2 = path3.join(dir, rel);
1228
1290
  let mtime = 0;
@@ -1246,6 +1308,8 @@ var listing = (res, dir, urlPath) => {
1246
1308
  )
1247
1309
  );
1248
1310
  };
1311
+ var sent = async (req) => JSON.parse(await new Response(req).text() || "{}");
1312
+ var answer = (res, data) => res.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" }).end(JSON.stringify(data));
1249
1313
  var handler = async (req, res) => {
1250
1314
  try {
1251
1315
  const url = new URL(req.url, origin);
@@ -1291,19 +1355,18 @@ var handler = async (req, res) => {
1291
1355
  return;
1292
1356
  }
1293
1357
  if (pathname === "/_lab/rule" && req.method === "POST") {
1294
- const b = JSON.parse(await new Response(req).text() || "{}");
1358
+ const b = await sent(req);
1295
1359
  const page = String(b.page || "");
1296
- if (b.action === "keep" || b.action === "no") {
1297
- const c2 = commentsOf(page).find((x) => x.id === b.id && x.suggest && x.session);
1298
- if (!c2) return res.writeHead(404).end("no offer");
1299
- if (!c2.suggestDone && b.action === "keep") addRule(c2.suggest);
1300
- if (!c2.suggestDone) setComment(page, c2.id, b.action === "keep" ? { suggestDone: "kept", rule: c2.suggest } : { suggestDone: "no" });
1301
- return res.writeHead(204).end();
1360
+ const c = commentsOf(page).find((x) => x.id === b.id && x.suggest && x.session);
1361
+ const to = b.action === "keep" ? "kept" : b.action === "no" ? "no" : "undone";
1362
+ if (!c || to === "undone" && !c.suggest.state) return res.writeHead(404).end("no rule");
1363
+ if (c.suggest.state === (to === "undone" ? "kept" : void 0)) {
1364
+ if (to !== "no") (to === "kept" ? addRule : dropRule)(c.suggest.text);
1365
+ setComment(page, c.id, { suggest: { ...c.suggest, state: to } });
1366
+ persist(page).catch(() => {
1367
+ });
1368
+ broadcast();
1302
1369
  }
1303
- const c = commentsOf(page).find((x) => x.id === b.id && x.rule && x.session);
1304
- if (!c) return res.writeHead(404).end("no rule");
1305
- if (!c.ruleUndone) dropRule(c.rule);
1306
- setComment(page, c.id, { ruleUndone: true });
1307
1370
  return res.writeHead(204).end();
1308
1371
  }
1309
1372
  if (pathname === "/_lab/invite") {
@@ -1311,31 +1374,29 @@ var handler = async (req, res) => {
1311
1374
  if (!WIFI) return res.writeHead(404).end("this lab is open to this computer only");
1312
1375
  const code = newPass();
1313
1376
  const hosts = [`${hostName}.local`, ...wifiAddrs()];
1314
- const body = JSON.parse(await new Response(req).text() || "{}");
1377
+ const body = await sent(req);
1315
1378
  const asked = body.name;
1316
1379
  const who = NAME_OK(asked) ? asked.trim() : myName;
1317
1380
  const q = new URLSearchParams();
1318
1381
  if (who) q.set("me", who);
1319
1382
  if (body.page) q.set("to", landing("/" + String(body.page).replace(/^\/+/, "")));
1320
1383
  const tail = q.size ? `?${q}` : "";
1321
- res.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" });
1322
- return res.end(JSON.stringify({ name: who, links: hosts.map((h) => `http://${h}:${PORT}/_lab/j/${code}${tail}`) }));
1384
+ return answer(res, { name: who, links: hosts.map((h) => `http://${h}:${PORT}/_lab/j/${code}${tail}`) });
1323
1385
  }
1324
1386
  if (pathname === "/_lab/flags") {
1325
1387
  if (!isLoopback(req)) return res.writeHead(403).end("forbidden");
1326
- const { flag, on } = JSON.parse(await new Response(req).text() || "{}");
1388
+ const { flag, on } = await sent(req);
1327
1389
  if (!(flag in FLAGS)) return res.writeHead(400).end("no such flag");
1328
1390
  const file3 = saveFlag(HERE, flag, Boolean(on));
1329
1391
  SET.flags = { ...SET.flags, [flag]: Boolean(on) };
1330
1392
  console.log(`[lab] trying ${flag}: ${on ? "on" : "off"} (${file3})`);
1331
1393
  version = { ...version, files: version.files + 1 };
1332
1394
  pagesChanged();
1333
- res.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" });
1334
- return res.end(JSON.stringify({ flags: SET.flags, file: file3 }));
1395
+ return answer(res, { flags: SET.flags, file: file3 });
1335
1396
  }
1336
1397
  if (pathname === "/_lab/me") {
1337
1398
  if (!isLoopback(req)) return res.writeHead(403).end("forbidden");
1338
- const { name } = JSON.parse(await new Response(req).text() || "{}");
1399
+ const { name } = await sent(req);
1339
1400
  if (!NAME_OK(name)) return res.writeHead(400).end("name: 1 to 60 characters");
1340
1401
  const was = myName;
1341
1402
  myName = writeMe(name);
@@ -1343,7 +1404,7 @@ var handler = async (req, res) => {
1343
1404
  return res.writeHead(204).end();
1344
1405
  }
1345
1406
  if (pathname === "/_lab/bye") {
1346
- const { tab } = JSON.parse(await new Response(req).text() || "{}");
1407
+ const { tab } = await sent(req);
1347
1408
  const gone = tabs.get(tab);
1348
1409
  if (gone) gone.gone = true;
1349
1410
  tabs.delete(tab);
@@ -1352,7 +1413,7 @@ var handler = async (req, res) => {
1352
1413
  }
1353
1414
  if (pathname === "/_lab/wait") {
1354
1415
  if (!isAgent(req)) return res.writeHead(403).end("forbidden");
1355
- const { timeout, pages: only } = JSON.parse(await new Response(req).text() || "{}");
1416
+ const { timeout, pages: only } = await sent(req);
1356
1417
  const want = Array.isArray(only) && only.length ? only.map(String).sort() : null;
1357
1418
  const key = want ? want.join(",") : "*";
1358
1419
  for (const old of waiters.filter((w2) => w2.key === key)) {
@@ -1361,10 +1422,10 @@ var handler = async (req, res) => {
1361
1422
  old.res.writeHead(409).end("another session is listening now");
1362
1423
  }
1363
1424
  session = sessionFrom(req);
1364
- const w = { res, pages: want, key };
1425
+ const w = { res, pages: want, key, who: whoOf(session) };
1365
1426
  claim(want);
1366
- const got = await unseen(scopeOf(w));
1367
- if (got?.text) return deliver(res, got);
1427
+ const got = await unseen(scopeOf(w), w.who);
1428
+ if (got?.text) return deliver(res, got, w.who);
1368
1429
  w.timer = setTimeout(() => {
1369
1430
  if (!waiters.includes(w)) return;
1370
1431
  waiters = waiters.filter((x) => x !== w);
@@ -1392,8 +1453,7 @@ var handler = async (req, res) => {
1392
1453
  const list = (PROXY ? [] : pagesUnder(ROOT)).map((rel) => ({ url: origin + urlOf(rel), title: titleOf(path3.join(ROOT, rel)), file: rel, key: keyFor(rel) }));
1393
1454
  if (PROXY) list.push({ url: origin + "/", title: "", file: "", key: "/" });
1394
1455
  for (const key of pages()) if (!list.some((p) => p.key === key)) list.push({ url: origin + key, title: "", file: fileFor(key) || "", key });
1395
- res.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" });
1396
- return res.end(JSON.stringify({
1456
+ return answer(res, {
1397
1457
  name: path3.basename(ROOT),
1398
1458
  root: ROOT,
1399
1459
  port: PORT,
@@ -1401,7 +1461,7 @@ var handler = async (req, res) => {
1401
1461
  mode,
1402
1462
  listening: session?.name || null,
1403
1463
  pages: list.map(({ key, ...p }) => ({ ...p, path: key, open: openOn(key) }))
1404
- }));
1464
+ });
1405
1465
  }
1406
1466
  if (pathname.startsWith("/_lab/agent/")) {
1407
1467
  res.writeHead(200, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" });
@@ -1410,12 +1470,11 @@ var handler = async (req, res) => {
1410
1470
  if (pathname === "/_lab/api/changes" && req.method === "GET") {
1411
1471
  const out = commentChangesSince(url.searchParams.get("page") || "", Number(url.searchParams.get("since")));
1412
1472
  if (out && !isLoopback(req)) out.set = out.set.map(forGuests);
1413
- res.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" });
1414
- return res.end(JSON.stringify(out || { full: true }));
1473
+ return answer(res, out || { full: true });
1415
1474
  }
1416
1475
  if (pathname === "/_lab/api/reads") {
1417
1476
  if (req.method === "POST") {
1418
- const b = JSON.parse(await new Response(req).text() || "{}");
1477
+ const b = await sent(req);
1419
1478
  const name2 = plainName(b.name);
1420
1479
  const page = String(b.page || "").slice(0, 500);
1421
1480
  if (!name2 || !page || !db.has(`lab:comments:${page}`)) return res.writeHead(400, { "content-type": "text/plain" }).end("name and a page with comments needed");
@@ -1436,31 +1495,7 @@ var handler = async (req, res) => {
1436
1495
  }
1437
1496
  const name = plainName(url.searchParams.get("name"));
1438
1497
  const ids = name && reads[name]?.[url.searchParams.get("page") || ""] || [];
1439
- res.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" });
1440
- return res.end(JSON.stringify({ ids }));
1441
- }
1442
- if (pathname === "/_lab/api/zoom" && req.method === "POST") {
1443
- if (!isAgent(req)) return res.writeHead(403).end();
1444
- const b = JSON.parse(await new Response(req).text() || "{}");
1445
- const fail = (status, error) => res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify({ error }));
1446
- const page = String(b.page || "");
1447
- const c = commentsOf(page).find((x) => x.id === b.id && !x.parent);
1448
- const dir = dirOf(c?.anchor?.zoom);
1449
- if (!c || !dir) return fail(404, "that pin is not a zoom");
1450
- if (c.zoomed) return fail(409, `the ${zoomName(dir)} for this pin is already on the page: #${c.zoomed}`);
1451
- if (!c.anchor.block) return fail(409, `the spot is in no element with an id: put the ${zoomName(dir)} on the page yourself, next to the spot`);
1452
- const rel = !PROXY && fileFor(page);
1453
- if (!rel || !/\.html?$/i.test(rel)) return fail(409, `this page is not a plain HTML file the lab can write: put the ${zoomName(dir)} on the page yourself`);
1454
- try {
1455
- const out = place({ html: fs3.readFileSync(path3.join(ROOT, rel), "utf8"), block: c.anchor.block, dir, made: String(b.html || "") });
1456
- fs3.writeFileSync(path3.join(ROOT, rel), out.html);
1457
- setComment(page, c.id, { zoomed: out.id });
1458
- res.writeHead(200, { "content-type": "application/json" });
1459
- return res.end(JSON.stringify({ id: out.id, dir, file: rel }));
1460
- } catch (e) {
1461
- if (e instanceof ZoomError) return fail(422, e.message);
1462
- throw e;
1463
- }
1498
+ return answer(res, { ids });
1464
1499
  }
1465
1500
  if (pathname === "/_lab/api/comments") {
1466
1501
  const agent = isAgent(req);
@@ -1471,33 +1506,23 @@ var handler = async (req, res) => {
1471
1506
  const kept = listing2 && cachedList(listPage, kind);
1472
1507
  if (kept) return res.writeHead(kept.status, kept.headers).end(kept.out);
1473
1508
  const fn = api[req.method] || (() => new Response("", { status: 405 }));
1474
- const out = await callApi(fn, req, `http://localhost/api${url.search}`, { host: "localhost" });
1509
+ const out = await callApi(fn, req, `http://localhost/api${url.search}`, { host: "localhost", "x-lab-agent": agent ? "1" : "0", ...agent ? { "x-lab-admin": TOKEN } : {} });
1475
1510
  const text = await out.text();
1476
1511
  if (req.method === "POST" && out.ok) {
1477
1512
  const { comment } = JSON.parse(text);
1478
1513
  if (out.status === 201) {
1479
1514
  const [key, h] = [...db].find(([k, m]) => k.startsWith("lab:comments:") && m.has(comment.id));
1480
- const stored = { ...JSON.parse(h.get(comment.id)), ...agent ? { session: sessionFrom(req) } : { from: isLoopback(req) ? "this computer" : "wifi guest" } };
1481
- if (!agent) delete stored.suggest;
1515
+ const stored = { ...JSON.parse(h.get(comment.id)), ...agent ? { session: slim(sessionFrom(req)) } : { from: isLoopback(req) ? "this computer" : "wifi guest" } };
1516
+ const said = stored.intent;
1517
+ if (agent && stored.parent) stored.intent ||= intentFromText(stored.text);
1482
1518
  h.set(comment.id, JSON.stringify(stored));
1483
- if (!agent && stored.parent && h.has(stored.parent)) {
1484
- const root = JSON.parse(h.get(stored.parent));
1485
- if (root.resolved) h.set(stored.parent, JSON.stringify({ ...root, resolved: false, resolvedBy: void 0 }));
1486
- }
1487
- if (agent && stored.parent && h.has(stored.parent) && /^done\b/i.test(String(stored.text).trim())) {
1519
+ if (agent && stored.parent && h.has(stored.parent)) {
1488
1520
  const root = JSON.parse(h.get(stored.parent));
1489
1521
  const thread = [root, ...[...h.values()].map((v) => JSON.parse(v)).filter((x) => x.parent === root.id && x.id !== stored.id)].sort((x, y) => String(x.createdAt).localeCompare(String(y.createdAt)));
1490
- const lastAgent = thread.map((x) => Boolean(x.session)).lastIndexOf(true);
1491
- const asks = thread.slice(lastAgent + 1).filter((x) => !x.session);
1522
+ const asks = thread.slice(thread.map((x) => Boolean(x.session)).lastIndexOf(true) + 1).filter((x) => !x.session);
1492
1523
  const listy = (t) => String(t).split("\n").filter((l) => /^\s*(?:[-*•]|\d+[.)])\s+/.test(l)).length >= 2;
1493
- const oneThing = asks.length === 1 && !listy(asks[0].text);
1494
- if (oneThing && !root.resolved && root.anchor?.kind !== "page") h.set(stored.parent, JSON.stringify({ ...root, resolved: true, resolvedBy: "agent" }));
1495
- }
1496
- if (agent && stored.parent && h.has(stored.parent)) {
1497
- const root = JSON.parse(h.get(stored.parent));
1498
- const more = [...h.values()].map((v) => JSON.parse(v)).some((x) => x.parent === root.id && x.id !== stored.id && !x.session);
1499
- const placed = root.anchor?.zoom && root.zoomed && !root.resolved && !more;
1500
- if (placed) h.set(stored.parent, JSON.stringify({ ...root, resolved: true, resolvedBy: "agent" }));
1524
+ const done = stored.intent === "done" && (said || asks.length === 1 && !listy(asks[0].text)) && root.anchor?.kind !== "page";
1525
+ if (done && !root.resolved) h.set(stored.parent, JSON.stringify({ ...root, resolved: true, resolvedBy: "agent", resolvedAt: stored.createdAt }));
1501
1526
  }
1502
1527
  if (!agent) announce(key.slice("lab:comments:".length), stored);
1503
1528
  }
@@ -1596,14 +1621,15 @@ async function newerVersion() {
1596
1621
  }
1597
1622
  }
1598
1623
  const parts = (v) => String(v).split("-")[0].split(".").map(Number);
1599
- const [a, b] = [parts(latest), parts(VERSION)];
1624
+ const [a, b] = [parts(latest), parts(VERSION2)];
1600
1625
  for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i] ? latest : null;
1601
1626
  return null;
1602
1627
  }
1603
1628
  server.on("listening", async () => {
1604
- newerVersion().then((v) => v && console.log(`[lab] labit ${v} is out (you have ${VERSION}): npx @leonidstern/labit@latest`));
1629
+ newerVersion().then((v) => v && console.log(`[lab] labit ${v} is out (you have ${VERSION2}): npx @leonidstern/labit@latest`));
1605
1630
  origin = `http://localhost:${PORT}`;
1606
1631
  saveServer();
1632
+ writeAtomic(LOCK, JSON.stringify({ pid: process.pid, at: Date.now(), port: PORT }), 384);
1607
1633
  register();
1608
1634
  await persist();
1609
1635
  console.log(`[lab] ${origin} \xB7 ${PROXY ? `pages from the dev server at ${PROXY.origin}, comments in` : "pages from"} ${ROOT}`);
@@ -1628,4 +1654,5 @@ var bye = () => {
1628
1654
  };
1629
1655
  process.on("SIGINT", bye);
1630
1656
  process.on("SIGTERM", bye);
1657
+ process.on("SIGHUP", bye);
1631
1658
  server.listen(PORT, WIFI ? void 0 : "127.0.0.1");