@leonidstern/labit 0.6.3-edge.4.1 → 0.6.3-main.10

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-AVPXXSFF.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,107 +210,6 @@ 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
- // api/_schema.mjs
292
- var VERSION = 1;
293
- var intentFromText = (text) => /^done\b/i.test(String(text ?? "").trim()) ? "done" : /^on it\b/i.test(String(text ?? "").trim()) ? "working" : void 0;
294
- function upgrade(record) {
295
- if (!record || typeof record !== "object" || (Number(record.v) || 0) >= VERSION) return record;
296
- const c = { ...record, v: VERSION };
297
- if (c.parent) {
298
- if (c.resolved === false) delete c.resolved;
299
- if (c.session && !c.intent) {
300
- const intent = intentFromText(c.text);
301
- if (intent) c.intent = intent;
302
- }
303
- }
304
- return c;
305
- }
306
-
307
213
  // local.mjs
308
214
  var SELF_DIR = path3.dirname(fileURLToPath(import.meta.url));
309
215
  var REPO = path3.basename(SELF_DIR) === "dist" ? path3.dirname(SELF_DIR) : SELF_DIR;
@@ -332,7 +238,7 @@ Run it as npx @leonidstern/labit \u2026, or node local.mjs \u2026 from a clone.
332
238
  labit add <url> [--name "title"] \xB7 labit remove <url>
333
239
  Save a cloud lab page (https://<lab domain>/<page>) for this folder, in .lab/links.json.
334
240
  labit mcp
335
- 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.
336
242
  Claude Code: claude mcp add labit -- npx @leonidstern/labit@latest mcp
337
243
  Codex: codex mcp add labit -- npx @leonidstern/labit@latest mcp
338
244
  labit preview [folder]
@@ -355,8 +261,9 @@ For the agent, from the project (any folder under it):
355
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
356
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.
357
263
  labit resolve <id> [--page /path]
358
- labit zoom <id> <file>
359
- 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.
360
267
 
361
268
  Files in .lab/ inside the folder: comments.md (every open comment as text), comments/ (the store, one file per
362
269
  page), archive/ (done threads with nothing new in 30 days), server.json (port, keys, session; owner-only), seen.
@@ -372,8 +279,8 @@ var die = (msg) => {
372
279
  };
373
280
  if (unknownFlags.length) die(`Unknown option ${unknownFlags[0]}. See: ${CMD} --help`);
374
281
  var HERE = fs3.realpathSync(path3.resolve(opts.dir || "."));
375
- var COMMANDS = ["preview", "add", "remove", "list", "pages", "wait", "reply", "resolve", "invite", "zoom", "mcp", "settings"];
376
- 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");
377
284
  var { FLAGS, flagsOn } = await import("./flags-PGKWZHJC.mjs");
378
285
  var SETTINGS = loadSettings(HERE, {
379
286
  port: opts.port !== void 0 && opts.port !== true ? Number(opts.port) : void 0,
@@ -398,7 +305,7 @@ if (fromFile("model") && SET.model) process.env.LAB_MODEL = SET.model;
398
305
  for (const p of SETTINGS.problems) console.error(`[labit] ${p}`);
399
306
  if (pos[0] === "settings") {
400
307
  const changed = changedShortcuts(SET.shortcuts);
401
- 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);
402
309
  const home = (f) => f.replace(os2.homedir(), "~");
403
310
  const src = (f) => f.split(" + ").map((x) => x === SETTINGS.files.project ? "labit.json" : x === SETTINGS.files.personal ? "your settings" : x).join(" + ");
404
311
  console.log(`Project: ${SETTINGS.files.project ? home(SETTINGS.files.project) : `no labit.json in ${home(HERE)} or above`}
@@ -410,12 +317,12 @@ Yours: ${home(SETTINGS.files.personal)}${fs3.existsSync(SETTINGS.files.persona
410
317
  A flag or variable wins over labit.json, which wins over your file. See docs/settings.md.`);
411
318
  process.exit(SETTINGS.problems.length ? 1 : 0);
412
319
  }
413
- if (["preview", "add", "remove", "list", "pages", "wait", "reply", "resolve", "invite", "zoom"].includes(pos[0])) {
414
- const { runCommand } = await import("./commands-L2RJ7R5W.mjs");
320
+ if (["preview", "add", "remove", "list", "pages", "wait", "reply", "resolve", "pin", "invite"].includes(pos[0])) {
321
+ const { runCommand } = await import("./commands-P7L2JAN6.mjs");
415
322
  await runCommand({ pos, opts, HERE, CMD, ME, die });
416
323
  }
417
324
  if (pos[0] === "mcp") {
418
- const { runMcp } = await import("./mcp-CNZISCIA.mjs");
325
+ const { runMcp } = await import("./mcp-6CQVLVZW.mjs");
419
326
  await runMcp({ HERE, ME, CMD, VERSION: VERSION2, WRITE_SHORT, AGENTS, agentKind, agentNow });
420
327
  }
421
328
  if (pos[0] && !fs3.existsSync(pos[0])) die(`No folder ${pos[0]}. Run ${CMD} in your project, or name a folder (see --help)`);
@@ -445,7 +352,7 @@ var runningServer = async () => {
445
352
  }
446
353
  };
447
354
  var alreadyRunning = Boolean(await runningServer());
448
- if (!alreadyRunning && !opts.new && !["wait", "reply", "resolve", "zoom"].includes(pos[0])) {
355
+ if (!alreadyRunning && !opts.new && !["wait", "reply", "resolve", "pin"].includes(pos[0])) {
449
356
  const home = runningLabs().find((lab) => ROOT.startsWith(lab.root + path3.sep));
450
357
  if (home) {
451
358
  const url = `http://localhost:${home.port}/${path3.relative(home.root, ROOT).split(path3.sep).map(encodeURIComponent).join("/")}/`;
@@ -591,7 +498,8 @@ var storeName = (page) => {
591
498
  var savePage = (page, dir = STORE) => {
592
499
  const h = db.get(`lab:comments:${page}`);
593
500
  const file2 = path3.join(dir, storeName(page));
594
- if (h?.size) writeAtomic(file2, `{"v":${VERSION},"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(",")}}}`);
595
503
  else fs3.rmSync(file2, { force: true });
596
504
  };
597
505
  var putAside = (file2, what) => {
@@ -600,6 +508,9 @@ var putAside = (file2, what) => {
600
508
  console.log(`[lab] ${what} was damaged; moved it to ${path3.relative(LAB, aside)}`);
601
509
  };
602
510
  var saved = {};
511
+ var handoff = /* @__PURE__ */ Object.create(null);
512
+ var outdated = [];
513
+ var homes = /* @__PURE__ */ new Map();
603
514
  var migrate = !fs3.existsSync(STORE) && fs3.existsSync(OLD_DATA);
604
515
  if (migrate) {
605
516
  try {
@@ -614,15 +525,17 @@ if (migrate) {
614
525
  if (!name.endsWith(".json")) continue;
615
526
  const file2 = path3.join(STORE, name);
616
527
  try {
617
- const { page, comments } = JSON.parse(fs3.readFileSync(file2, "utf8"));
528
+ const { v, page, comments, file: rel, fid } = JSON.parse(fs3.readFileSync(file2, "utf8"));
618
529
  if (typeof page !== "string" || !page.startsWith("/") || !comments || typeof comments !== "object") throw new Error("not a page");
619
530
  saved[page] = comments;
531
+ if (typeof rel === "string" && /^[\d.]+$/.test(fid)) homes.set(page, [rel, fid]);
532
+ if (v !== VERSION) outdated.push(page);
620
533
  } catch {
621
534
  putAside(file2, `comments/${name}`);
622
535
  }
623
536
  }
624
537
  }
625
- 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))]))]));
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))]))]));
626
539
  saved = null;
627
540
  if (migrate) {
628
541
  const fresh = `${STORE}.new`;
@@ -635,7 +548,7 @@ if (migrate) {
635
548
  }
636
549
  fs3.mkdirSync(STORE, { recursive: true });
637
550
  process.env.LAB_COMMENTS_PER_HOUR ||= "600";
638
- var api = await apiOn(db, REPO);
551
+ var api = await apiOn(db);
639
552
  var commentsOf = (page) => [...db.get(`lab:comments:${page}`)?.values() ?? []].map((v) => JSON.parse(v)).sort((a, b) => a.createdAt.localeCompare(b.createdAt));
640
553
  var pages = () => [...db.keys()].filter((k) => k.startsWith("lab:comments:") && db.get(k).size).map((k) => k.slice("lab:comments:".length));
641
554
  var ARCHIVE_DAYS = SET.archiveAfterDays;
@@ -673,9 +586,6 @@ function archiveOld(now = Date.now()) {
673
586
  return changed;
674
587
  }
675
588
  for (const p of archiveOld()) savePage(p);
676
- var keyFor = (rel) => "/" + rel.replace(/\.html?$/i, "").split(path3.sep).map(
677
- (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("")
678
- ).join("/");
679
589
  var fileIndex = null;
680
590
  var fileMemo = /* @__PURE__ */ new Map();
681
591
  var fileMemoAt = Date.now();
@@ -687,24 +597,50 @@ var fileFor = (page) => {
687
597
  if (!fileMemo.has(page)) fileMemo.set(page, findFile(page));
688
598
  return fileMemo.get(page);
689
599
  };
690
- var ZOOM_SKILL = SET.zoom.skill || path3.join(REPO, "skills/labit/zoom.md");
691
600
  var findFile = (page) => {
692
601
  if (!fileIndex) {
693
- fileIndex = /* @__PURE__ */ new Map();
694
- const walk = (dir, depth) => {
695
- for (const d of fs3.readdirSync(dir, { withFileTypes: true })) {
696
- if (d.name.startsWith(".") || d.name === "node_modules") continue;
697
- const full = path3.join(dir, d.name);
698
- if (d.isDirectory() && depth < 6) walk(full, depth + 1);
699
- else if (/\.html?$/i.test(d.name)) fileIndex.set(keyFor(path3.relative(ROOT, full)), path3.relative(ROOT, full));
700
- }
701
- };
702
- walk(ROOT, 0);
602
+ fileIndex = new Map(pagesUnder(ROOT).map((rel) => [keyFor(rel), rel]));
603
+ rehome();
703
604
  }
704
605
  const html = fileIndex.get(page);
705
606
  if (PROXY) return sourceFor(page) || (html && html !== "index.html" ? html : null);
706
607
  return html || sourceFor(page);
707
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
+ }
708
644
  var realCase = (rel) => {
709
645
  let dir = ROOT;
710
646
  const out = [];
@@ -804,6 +740,7 @@ var shot = /* @__PURE__ */ new Map();
804
740
  var changeLog = [];
805
741
  var takeShot = (p) => new Map(db.get(`lab:comments:${p}`) || []);
806
742
  for (const p of pages()) shot.set(p, takeShot(p));
743
+ for (const p of outdated) unsaved.add(p);
807
744
  function logChanges(page, rev) {
808
745
  for (const p of page ? [page] : [.../* @__PURE__ */ new Set([...pages(), ...shot.keys()])]) {
809
746
  const was = shot.get(p) || /* @__PURE__ */ new Map();
@@ -823,7 +760,6 @@ var forGuests = (c) => {
823
760
  if (!c || typeof c !== "object") return c;
824
761
  const rest = { ...c };
825
762
  if (rest.session) rest.session = { name: rest.session.name, agent: rest.session.agent, kind: rest.session.kind };
826
- delete rest.deliveredTo;
827
763
  return rest;
828
764
  };
829
765
  function commentChangesSince(page, since) {
@@ -968,9 +904,9 @@ var redeem = (req, res, code, me = "", to = "") => {
968
904
  return res.writeHead(302, { location: landing(to), "set-cookie": cookies }).end();
969
905
  };
970
906
  var isAgent = (req) => {
971
- const sent = Buffer.from(String(req.headers["x-lab-admin"] || ""));
907
+ const sent2 = Buffer.from(String(req.headers["x-lab-admin"] || ""));
972
908
  const key = Buffer.from(AGENT_KEY);
973
- return req.headers["x-lab-agent"] === "1" && sent.length === key.length && timingSafeEqual(sent, key);
909
+ return req.headers["x-lab-agent"] === "1" && sent2.length === key.length && timingSafeEqual(sent2, key);
974
910
  };
975
911
  var sessionFrom = (req) => {
976
912
  try {
@@ -992,6 +928,7 @@ var sessionFrom = (req) => {
992
928
  };
993
929
  var session = null;
994
930
  var rulesSent = /* @__PURE__ */ new Map();
931
+ var toldAt = /* @__PURE__ */ new Map();
995
932
  var mode = "away";
996
933
  var awayTimer;
997
934
  var setMode = (m) => {
@@ -1040,17 +977,28 @@ var reads = (() => {
1040
977
  var readsBroadcast = 0;
1041
978
  var readsRev = 0;
1042
979
  var plainName = (n) => String(n || "").replace(/\s+/g, " ").trim().toLowerCase().slice(0, 80);
1043
- var readsTimer;
1044
- var saveReads = () => {
1045
- clearTimeout(readsTimer);
1046
- readsTimer = setTimeout(() => {
1047
- try {
1048
- writeAtomic(READS, JSON.stringify(reads));
1049
- } catch (e) {
1050
- console.error("[lab] could not save read marks:", e.message);
1051
- }
1052
- }, 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
+ };
1053
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;
1054
1002
  var state = (local) => JSON.stringify({ ...version, reads: readsRev, mode, session: session && (local ? session : { name: session.name, agent: session.agent, model: session.model }) });
1055
1003
  var broadcast = () => {
1056
1004
  for (const c of clients) c.res.write(`data: ${state(c.local)}
@@ -1074,6 +1022,7 @@ if (!PROXY) fs3.watch(ROOT, { recursive: true }, (event, file2) => {
1074
1022
  fileIndex = null;
1075
1023
  fileMemo.clear();
1076
1024
  indexStale = false;
1025
+ if (pages().length) fileFor(pages()[0]);
1077
1026
  }
1078
1027
  const hotOnly = !otherSaved && hotSaved.size > 0;
1079
1028
  const hot = [...hotSaved].slice(0, 50).map(([p, kind2]) => ({ path: p, kind: kind2 }));
@@ -1166,17 +1115,16 @@ var rulesOnce = () => {
1166
1115
  };
1167
1116
  var whoOf = (s) => s?.id || s?.name || "";
1168
1117
  async function unseen(scope = pages(), who = "") {
1169
- const fresh = scope.flatMap((page) => commentsOf(page).filter((c) => !c.session && !(c.resolved && !c.parent) && stamp(c) > (c.deliveredAt || seen)).map((c) => ({ page, c })));
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 })));
1170
1119
  const now = Date.now();
1171
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() || "";
1172
- 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)));
1173
1122
  if (!fresh.length && !missed.length) return null;
1174
1123
  const blocks = [];
1175
- const sent = /* @__PURE__ */ new Set();
1124
+ const sent2 = /* @__PURE__ */ new Set();
1176
1125
  const known = (f) => {
1177
- if (!f.c.parent) return false;
1178
- const root = commentsOf(f.page).find((c) => c.id === f.c.parent);
1179
- return Boolean(root?.deliveredAt) && (root.deliveredTo === void 0 || root.deliveredTo === who) && !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);
1180
1128
  };
1181
1129
  const replies = fresh.filter(known);
1182
1130
  const whole = fresh.filter((f) => !known(f));
@@ -1184,7 +1132,7 @@ async function unseen(scope = pages(), who = "") {
1184
1132
  const block = await threadsText(page, [...new Set(whole.filter((f) => f.page === page).map((f) => f.c.parent || f.c.id))]);
1185
1133
  if (block) {
1186
1134
  blocks.push(block.text);
1187
- block.ids.forEach((id) => sent.add(`${page}
1135
+ block.ids.forEach((id) => sent2.add(`${page}
1188
1136
  ${id}`));
1189
1137
  }
1190
1138
  }
@@ -1194,7 +1142,7 @@ ${id}`));
1194
1142
  const root = commentsOf(f.page).find((c) => c.id === f.c.parent);
1195
1143
  const guest = f.c.from === "wifi guest" ? " (wifi guest)" : "";
1196
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, " ")}`);
1197
- sent.add(`${f.page}
1145
+ sent2.add(`${f.page}
1198
1146
  ${root.id}`);
1199
1147
  }
1200
1148
  if (lines.length) blocks.push(`# New replies (whole threads: http://localhost:${PORT}/_lab/agent/<page>)
@@ -1202,32 +1150,36 @@ ${lines.join("\n")}`);
1202
1150
  if (missed.length) {
1203
1151
  blocks.push(`# Still waiting for your answer (handed to you earlier)
1204
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")}`);
1205
- 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();
1206
1155
  }
1207
- const given = fresh.filter((f) => sent.has(`${f.page}
1156
+ const given = fresh.filter((f) => sent2.has(`${f.page}
1208
1157
  ${f.c.parent || f.c.id}`));
1209
1158
  if (!given.length && !missed.length) return null;
1210
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);
1211
1161
  const text = `In this message: ${count}. Read all of it; each one is marked handed to you.
1212
1162
 
1213
- ` + (blocks.length ? `# New comments
1214
-
1215
- ${blocks.join("\n\n")}` : "") + `
1163
+ ${whole.length ? "# New comments\n\n" : ""}${blocks.join("\n\n")}
1216
1164
 
1217
- Answer each: ${CMD} reply <id> "what you did" [--done | --on-it | --question] [--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")) ? `
1218
- 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) ? `
1219
- 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.` : "") + `
1220
- ${WRITE_SHORT}` + rulesOnce();
1221
- 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"));
1222
1169
  const marks = given.map(({ page, c }) => [page, c.id, stamp(c)]);
1223
- return { text, marks, handed };
1170
+ return { text, marks, handed, full };
1224
1171
  }
1225
1172
  function deliver(res, got, who = "") {
1226
1173
  res.writeHead(200, { "content-type": "text/plain; charset=utf-8" }).end(got.text);
1227
- for (const [page, id, at2] of got.marks) setComment(page, id, { deliveredAt: at2, deliveredTo: who });
1174
+ if (got.full) toldAt.set(who, Date.now());
1175
+ for (const [, id, at2] of got.marks) handoff[id] = [at2, who];
1228
1176
  const at = (/* @__PURE__ */ new Date()).toISOString();
1229
- for (const [page, id] of got.handed) setComment(page, id, { handedAt: at, deliveredTo: who });
1230
- 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(() => {
1231
1183
  });
1232
1184
  setMode("working");
1233
1185
  }
@@ -1266,7 +1218,8 @@ var flagsAttr = () => {
1266
1218
  const json = JSON.stringify(Object.fromEntries(Object.entries(FLAGS).map(([k, f]) => [k, { name: f.name, on: SET.flags[k] === true }])));
1267
1219
  return ` data-flags='${json.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/'/g, "&#39;")}'`;
1268
1220
  };
1269
- 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>
1270
1223
  `;
1271
1224
  var inject = (html, tag) => {
1272
1225
  html = html.replace(/<script\b[^>]*\bsrc=["'][^"']*\/_lab\/comments\.js["'][^>]*>\s*<\/script>\s*/gi, "");
@@ -1317,9 +1270,9 @@ var titleOf = (file2) => {
1317
1270
  }
1318
1271
  };
1319
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)};`);
1320
1274
  var notFound = (req, res, what) => {
1321
1275
  if (!/text\/html/.test(req.headers.accept || "")) return res.writeHead(404, { "content-type": "text/plain" }).end("not found");
1322
- const esc = (s) => s.replace(/[&<>"]/g, (c) => `&#${c.charCodeAt(0)};`);
1323
1276
  res.writeHead(404, { "content-type": "text/html; charset=utf-8" });
1324
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>`));
1325
1278
  };
@@ -1332,7 +1285,6 @@ var ago = (ms) => {
1332
1285
  return new Date(ms).toLocaleDateString("en-GB", { day: "numeric", month: "short" });
1333
1286
  };
1334
1287
  var listing = (res, dir, urlPath) => {
1335
- const esc = (s) => s.replace(/[&<>"]/g, (c) => `&#${c.charCodeAt(0)};`);
1336
1288
  const pages2 = pagesUnder(dir).map((rel) => {
1337
1289
  const file2 = path3.join(dir, rel);
1338
1290
  let mtime = 0;
@@ -1356,6 +1308,8 @@ var listing = (res, dir, urlPath) => {
1356
1308
  )
1357
1309
  );
1358
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));
1359
1313
  var handler = async (req, res) => {
1360
1314
  try {
1361
1315
  const url = new URL(req.url, origin);
@@ -1401,19 +1355,18 @@ var handler = async (req, res) => {
1401
1355
  return;
1402
1356
  }
1403
1357
  if (pathname === "/_lab/rule" && req.method === "POST") {
1404
- const b = JSON.parse(await new Response(req).text() || "{}");
1358
+ const b = await sent(req);
1405
1359
  const page = String(b.page || "");
1406
- if (b.action === "keep" || b.action === "no") {
1407
- const c2 = commentsOf(page).find((x) => x.id === b.id && x.suggest && x.session);
1408
- if (!c2) return res.writeHead(404).end("no offer");
1409
- if (!c2.suggestDone && b.action === "keep") addRule(c2.suggest);
1410
- if (!c2.suggestDone) setComment(page, c2.id, b.action === "keep" ? { suggestDone: "kept", rule: c2.suggest } : { suggestDone: "no" });
1411
- 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();
1412
1369
  }
1413
- const c = commentsOf(page).find((x) => x.id === b.id && x.rule && x.session);
1414
- if (!c) return res.writeHead(404).end("no rule");
1415
- if (!c.ruleUndone) dropRule(c.rule);
1416
- setComment(page, c.id, { ruleUndone: true });
1417
1370
  return res.writeHead(204).end();
1418
1371
  }
1419
1372
  if (pathname === "/_lab/invite") {
@@ -1421,31 +1374,29 @@ var handler = async (req, res) => {
1421
1374
  if (!WIFI) return res.writeHead(404).end("this lab is open to this computer only");
1422
1375
  const code = newPass();
1423
1376
  const hosts = [`${hostName}.local`, ...wifiAddrs()];
1424
- const body = JSON.parse(await new Response(req).text() || "{}");
1377
+ const body = await sent(req);
1425
1378
  const asked = body.name;
1426
1379
  const who = NAME_OK(asked) ? asked.trim() : myName;
1427
1380
  const q = new URLSearchParams();
1428
1381
  if (who) q.set("me", who);
1429
1382
  if (body.page) q.set("to", landing("/" + String(body.page).replace(/^\/+/, "")));
1430
1383
  const tail = q.size ? `?${q}` : "";
1431
- res.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" });
1432
- 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}`) });
1433
1385
  }
1434
1386
  if (pathname === "/_lab/flags") {
1435
1387
  if (!isLoopback(req)) return res.writeHead(403).end("forbidden");
1436
- const { flag, on } = JSON.parse(await new Response(req).text() || "{}");
1388
+ const { flag, on } = await sent(req);
1437
1389
  if (!(flag in FLAGS)) return res.writeHead(400).end("no such flag");
1438
1390
  const file3 = saveFlag(HERE, flag, Boolean(on));
1439
1391
  SET.flags = { ...SET.flags, [flag]: Boolean(on) };
1440
1392
  console.log(`[lab] trying ${flag}: ${on ? "on" : "off"} (${file3})`);
1441
1393
  version = { ...version, files: version.files + 1 };
1442
1394
  pagesChanged();
1443
- res.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" });
1444
- return res.end(JSON.stringify({ flags: SET.flags, file: file3 }));
1395
+ return answer(res, { flags: SET.flags, file: file3 });
1445
1396
  }
1446
1397
  if (pathname === "/_lab/me") {
1447
1398
  if (!isLoopback(req)) return res.writeHead(403).end("forbidden");
1448
- const { name } = JSON.parse(await new Response(req).text() || "{}");
1399
+ const { name } = await sent(req);
1449
1400
  if (!NAME_OK(name)) return res.writeHead(400).end("name: 1 to 60 characters");
1450
1401
  const was = myName;
1451
1402
  myName = writeMe(name);
@@ -1453,7 +1404,7 @@ var handler = async (req, res) => {
1453
1404
  return res.writeHead(204).end();
1454
1405
  }
1455
1406
  if (pathname === "/_lab/bye") {
1456
- const { tab } = JSON.parse(await new Response(req).text() || "{}");
1407
+ const { tab } = await sent(req);
1457
1408
  const gone = tabs.get(tab);
1458
1409
  if (gone) gone.gone = true;
1459
1410
  tabs.delete(tab);
@@ -1462,7 +1413,7 @@ var handler = async (req, res) => {
1462
1413
  }
1463
1414
  if (pathname === "/_lab/wait") {
1464
1415
  if (!isAgent(req)) return res.writeHead(403).end("forbidden");
1465
- const { timeout, pages: only } = JSON.parse(await new Response(req).text() || "{}");
1416
+ const { timeout, pages: only } = await sent(req);
1466
1417
  const want = Array.isArray(only) && only.length ? only.map(String).sort() : null;
1467
1418
  const key = want ? want.join(",") : "*";
1468
1419
  for (const old of waiters.filter((w2) => w2.key === key)) {
@@ -1502,8 +1453,7 @@ var handler = async (req, res) => {
1502
1453
  const list = (PROXY ? [] : pagesUnder(ROOT)).map((rel) => ({ url: origin + urlOf(rel), title: titleOf(path3.join(ROOT, rel)), file: rel, key: keyFor(rel) }));
1503
1454
  if (PROXY) list.push({ url: origin + "/", title: "", file: "", key: "/" });
1504
1455
  for (const key of pages()) if (!list.some((p) => p.key === key)) list.push({ url: origin + key, title: "", file: fileFor(key) || "", key });
1505
- res.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" });
1506
- return res.end(JSON.stringify({
1456
+ return answer(res, {
1507
1457
  name: path3.basename(ROOT),
1508
1458
  root: ROOT,
1509
1459
  port: PORT,
@@ -1511,7 +1461,7 @@ var handler = async (req, res) => {
1511
1461
  mode,
1512
1462
  listening: session?.name || null,
1513
1463
  pages: list.map(({ key, ...p }) => ({ ...p, path: key, open: openOn(key) }))
1514
- }));
1464
+ });
1515
1465
  }
1516
1466
  if (pathname.startsWith("/_lab/agent/")) {
1517
1467
  res.writeHead(200, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" });
@@ -1520,12 +1470,11 @@ var handler = async (req, res) => {
1520
1470
  if (pathname === "/_lab/api/changes" && req.method === "GET") {
1521
1471
  const out = commentChangesSince(url.searchParams.get("page") || "", Number(url.searchParams.get("since")));
1522
1472
  if (out && !isLoopback(req)) out.set = out.set.map(forGuests);
1523
- res.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" });
1524
- return res.end(JSON.stringify(out || { full: true }));
1473
+ return answer(res, out || { full: true });
1525
1474
  }
1526
1475
  if (pathname === "/_lab/api/reads") {
1527
1476
  if (req.method === "POST") {
1528
- const b = JSON.parse(await new Response(req).text() || "{}");
1477
+ const b = await sent(req);
1529
1478
  const name2 = plainName(b.name);
1530
1479
  const page = String(b.page || "").slice(0, 500);
1531
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");
@@ -1546,31 +1495,7 @@ var handler = async (req, res) => {
1546
1495
  }
1547
1496
  const name = plainName(url.searchParams.get("name"));
1548
1497
  const ids = name && reads[name]?.[url.searchParams.get("page") || ""] || [];
1549
- res.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" });
1550
- return res.end(JSON.stringify({ ids }));
1551
- }
1552
- if (pathname === "/_lab/api/zoom" && req.method === "POST") {
1553
- if (!isAgent(req)) return res.writeHead(403).end();
1554
- const b = JSON.parse(await new Response(req).text() || "{}");
1555
- const fail = (status, error) => res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify({ error }));
1556
- const page = String(b.page || "");
1557
- const c = commentsOf(page).find((x) => x.id === b.id && !x.parent);
1558
- const dir = dirOf(c?.anchor?.zoom);
1559
- if (!c || !dir) return fail(404, "that pin is not a zoom");
1560
- if (c.zoomed) return fail(409, `the ${zoomName(dir)} for this pin is already on the page: #${c.zoomed}`);
1561
- 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`);
1562
- const rel = !PROXY && fileFor(page);
1563
- 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`);
1564
- try {
1565
- const out = place({ html: fs3.readFileSync(path3.join(ROOT, rel), "utf8"), block: c.anchor.block, dir, made: String(b.html || "") });
1566
- fs3.writeFileSync(path3.join(ROOT, rel), out.html);
1567
- setComment(page, c.id, { zoomed: out.id });
1568
- res.writeHead(200, { "content-type": "application/json" });
1569
- return res.end(JSON.stringify({ id: out.id, dir, file: rel }));
1570
- } catch (e) {
1571
- if (e instanceof ZoomError) return fail(422, e.message);
1572
- throw e;
1573
- }
1498
+ return answer(res, { ids });
1574
1499
  }
1575
1500
  if (pathname === "/_lab/api/comments") {
1576
1501
  const agent = isAgent(req);
@@ -1581,36 +1506,23 @@ var handler = async (req, res) => {
1581
1506
  const kept = listing2 && cachedList(listPage, kind);
1582
1507
  if (kept) return res.writeHead(kept.status, kept.headers).end(kept.out);
1583
1508
  const fn = api[req.method] || (() => new Response("", { status: 405 }));
1584
- const out = await callApi(fn, req, `http://localhost/api${url.search}`, { host: "localhost", ...agent ? { "x-lab-admin": TOKEN } : {} });
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 } : {} });
1585
1510
  const text = await out.text();
1586
1511
  if (req.method === "POST" && out.ok) {
1587
1512
  const { comment } = JSON.parse(text);
1588
1513
  if (out.status === 201) {
1589
1514
  const [key, h] = [...db].find(([k, m]) => k.startsWith("lab:comments:") && m.has(comment.id));
1590
- const stored = { ...JSON.parse(h.get(comment.id)), ...agent ? { session: sessionFrom(req) } : { from: isLoopback(req) ? "this computer" : "wifi guest" } };
1591
- if (!agent) delete stored.suggest;
1592
- if (!agent) delete stored.intent;
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);
1593
1518
  h.set(comment.id, JSON.stringify(stored));
1594
- if (!agent && stored.parent && h.has(stored.parent)) {
1595
- const root = JSON.parse(h.get(stored.parent));
1596
- if (root.resolved) h.set(stored.parent, JSON.stringify({ ...root, resolved: false, resolvedBy: void 0, resolvedAt: void 0 }));
1597
- }
1598
- const said = stored.intent || intentFromText(stored.text);
1599
- if (agent && stored.parent && h.has(stored.parent) && said === "done") {
1519
+ if (agent && stored.parent && h.has(stored.parent)) {
1600
1520
  const root = JSON.parse(h.get(stored.parent));
1601
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)));
1602
- const lastAgent = thread.map((x) => Boolean(x.session)).lastIndexOf(true);
1603
- 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);
1604
1523
  const listy = (t) => String(t).split("\n").filter((l) => /^\s*(?:[-*•]|\d+[.)])\s+/.test(l)).length >= 2;
1605
- const oneThing = asks.length === 1 && !listy(asks[0].text);
1606
- if ((stored.intent === "done" || oneThing) && !root.resolved && root.anchor?.kind !== "page")
1607
- h.set(stored.parent, JSON.stringify({ ...root, resolved: true, resolvedBy: "agent", resolvedAt: stored.createdAt }));
1608
- }
1609
- if (agent && stored.parent && h.has(stored.parent)) {
1610
- const root = JSON.parse(h.get(stored.parent));
1611
- const more = [...h.values()].map((v) => JSON.parse(v)).some((x) => x.parent === root.id && x.id !== stored.id && !x.session);
1612
- const placed = root.anchor?.zoom && root.zoomed && !root.resolved && !more;
1613
- if (placed) h.set(stored.parent, JSON.stringify({ ...root, resolved: true, resolvedBy: "agent", resolvedAt: stored.createdAt }));
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 }));
1614
1526
  }
1615
1527
  if (!agent) announce(key.slice("lab:comments:".length), stored);
1616
1528
  }