@leonidstern/labit 0.6.1 → 0.6.3-edge.3.1

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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "labit",
3
- "version": "0.6.1",
3
+ "version": "0.6.2",
4
4
  "description": "Read and answer labit pin comments: cloud lab links and local mode (wait, fix, reply on the pin).",
5
5
  "author": {
6
6
  "name": "leonidstern",
package/CHANGELOG.md CHANGED
@@ -4,6 +4,43 @@ Versions follow [semver](https://semver.org). Before 1.0, a minor version can ch
4
4
 
5
5
  ## Unreleased
6
6
 
7
+ - Pins find their spot again more reliably after the page changes: a twin search starts inside the pin's own section, a pin on words sits on those words, pins on text in the page body follow their quote, made-up ids and classes (React `:r3:`, Radix, CSS-module and Svelte hashes) no longer count as names, and a pin whose card is gone among look-alikes shows as moved instead of landing on the wrong one.
8
+ - Replies say what they are: `labit reply <id> "…" --done | --on-it | --question` (and `intent` on the MCP reply tool). The thread closes from `--done`, not from the words; a reply starting "Done" still works for older agents.
9
+ - Resolving records when (`resolvedAt`) and by whom: the agent's `labit resolve` now records `agent`, not `owner`. Done threads are archived a month after they were resolved, not after their last message. Replies no longer carry `resolved:false`.
10
+ - Comments carry a schema version (`v: 1`); older page files and hosted records are upgraded when they load.
11
+ - The agent has its own key, kept only in `.lab/server.json`: a script on a lab page holds the browser key and can no longer wait, zoom or answer as the agent. An older labit CLI can't act as the agent on this lab.
12
+ - The 500-per-page cap no longer blocks the owner or the agent, and done threads no longer count toward it.
13
+ - One lab per folder, for sure: `.lab/lock` is taken before the store loads, a lab counts as running only if it answers on its port, and closing the terminal (SIGHUP) cleans up.
14
+ - A session that takes over a page gets whole threads for pins another session was handed, not one-line "new replies".
15
+ - `reads.json`, `claims.json` and `links.json` are written whole; a damaged one is set aside (`*.broken-<time>`) instead of read as empty and written over.
16
+
17
+ - Releases publish themselves: a version bump merged to main goes to npm as `latest` (tagged `vX.Y.Z`), and every merge to main goes out as `next` (0.6.3-main.41…). `npx @leonidstern/labit@latest` is the newest release; `@next` is main as it is now, for whoever wants each merge in their labs. From GitHub Actions with npm trusted publishing, no token.
18
+ - "Pin over controls": with it on, the pointer over the page's links, buttons and clickable cards is the pin, not their hand. The menu item shows how to do it once without the switch: (⌥ click).
19
+
20
+ ## 0.6.2 · 2026-11-17
21
+
22
+ - A go pin is a pin like any other: once it is done or resolved it wears the tick, where before it said "go" for ever and a finished one looked unfinished. Checked in both engines by the browser job.
23
+ - Option-click on a pin resolves its thread without opening it (again opens it again), for whoever may resolve it.
24
+
25
+ - A done pin is a solid green ✓, full size, even when the page changed under it: faded and small is how a pin that lost its spot looks, and done pins looked lost.
26
+ - Phones: a sent comment's card slides down whole, like any sheet, and its new pin pops in with one green ring. It used to shrink and fly into the pin, which squeezed the card, and the pin was already there while it flew (its pop-in had been dropped by a later change).
27
+
28
+ - Rules from how you reply: when a reply is about how the agent answered (too long, unclear, didn't show where), the agent offers a rule with its answer (`labit reply <id> "…" --suggest-rule "…"`) and your message shows **rule?** where its time was. One tap keeps it, ignoring it is a no, and undo on the answer takes it back. Rules live in `~/.config/labit/replies.md` (yours, every project, every agent; the same rule again counts again) and the 15 kept most go to each session once, and again when they change.
29
+ - Threads: an answer to a later message in the thread quotes it, as the chat does; a plain "go" the agent resolves without a word shows one green ✓ on your message; an open thread stays at its newest message while it gets shorter (the keyboard) or an answer comes in, as the chat does, and goes to it when you tap the reply box.
30
+ - Phone links: `labit invite --page /path` opens that page. A used or old link opened again on a device the lab already lets in takes you to its page instead of the gate, and a guest who keeps using the lab stays in (each page they open renews the day). Only a path of this lab is a landing; anything else lands on `/`.
31
+ - Phones: the quoted words of a comment are lit, not half the page. Safari painted that green over whole blocks of text that can't be selected, and with comments on the page was unselectable all the time; now only while a finger is down (the hold still never turns into a text selection).
32
+ - Phones: after a new comment is sent or dropped, the page glides back to where you were before the hold moved it up to keep the pin above the keyboard (once the card has landed in its pin; not if you scrolled yourself meanwhile).
33
+ - `test/phone/sim.mjs`: phone checks in the iOS simulator's Safari and the Chrome stand-in, real touches step by step against a recorder on the page (focus, keyboard, scroll, selection, pins and boxes, every frame). Not in CI.
34
+ - Things being tried arrive as flags: off unless somebody turns one on, tried in a real lab, then kept (the flag goes and it is simply labit) or dropped (the code goes with it). `flags` in `labit.json` or your own settings, switches under a **trying** heading in the ⋯ menu (this computer only), `labit settings` lists them, and a switch writes the project's `labit.json` so the agent sees the same thing. First two: `liveUrl` (a lab in front of a live page) and `agentPins` (a pin the agent left wears labit's own mark, the one the bar shows while an agent listens).
35
+ - A wait can no longer hold someone's turn open: `labit wait` (and `reply --wait`) sits for the full timeout only when the agent says it put the command in the background, with `--bg`. Without that it ends after a minute and says why. A wait left in an agent's foreground kept the person from saying anything to their agent until it ended, and the message they sent to reach them killed it; from inside the process a foreground run looks exactly like a background one, so `--bg` is the agent's word for it. At a terminal (a tty) nothing changes.
36
+ - The bar's counts (chat, new) are green when something is new, grey at 0.
37
+ - Settings: `labit.json` in the project (shared) and `~/.config/labit/settings.json` (yours) fill in what flags and variables leave out: port, proxy, folder, open, wifi (yours only), batchSeconds, stopListeningAfterMinutes, remindAfterMinutes, archiveAfterDays, updateCheck, name and model (yours only), shortcuts (every key on the page, shown in the bar) and zoom.skill (a project's own zoom skill). `labit settings` shows each value and where it came from. Your name moves from me.json to settings.json (me.json is still read). docs/settings.md.
38
+ - A lab's tabs share one live connection: the first tab holds it and passes every update to the others (Web Locks + BroadcastChannel; when it closes, the next tab takes over). Tabs in the background stay live, their title count and pins updating at once instead of every 20 s or so, and any number of tabs of one lab use one of the browser's 6 connections.
39
+ - Listening: the MCP server's `wait` is its own request to the lab, no longer a `labit wait` process it starts, so a cancel or the client going away ends it at once by design. A tab that drops its connection without saying bye (crashed, or frozen by a phone) stops counting as open after 90 s without checking in, not after half an hour (LAB_TAB_TTL, in seconds).
40
+ - MCP server, checked against the spec (2025-11-25, 2026-07-28) and the SDK's practice: when the client goes away (stdin closed, SIGTERM, SIGINT) a `wait` in flight stops with it, so the page no longer says an agent is listening for up to the wait's length; a `wait` refused for a bad argument no longer sends progress forever after its answer; a cancel for a request already answered is ignored (an id used again got no answer); roots are asked for after the client's `initialized`, not before; a batch gets an Invalid Request error instead of silence.
41
+ - `examples/claude-settings.json`: Claude Code settings to give people. labit's commands and MCP tools run without a prompt; `--wifi` and `invite` still ask. Checked with `claude -p` in a fresh folder.
42
+ - The last of the old name is gone: no `labfb` command (use `labit`), and `LABFB_HOME` / `LABFB_NO_UPDATE_CHECK` are no longer read (use `LABIT_HOME` / `LABIT_NO_UPDATE_CHECK`).
43
+
7
44
  ## 0.6.1 · 2026-11-16
8
45
 
9
46
  - iPhones: a new comment no longer sometimes sits behind the keyboard's bar. When Safari (or Chrome) slid the page up for the keyboard instead of scrolling it, the widget counted that slide twice and saw no keyboard at all; it now measures the slide where WebKit measures boxes, from the screen's top.
package/README.md CHANGED
@@ -29,15 +29,21 @@ It finds your running dev server (Astro, Next, Vite…) or serves plain HTML, an
29
29
 
30
30
  ```sh
31
31
  npx @leonidstern/labit wait # ends with your next comment
32
- npx @leonidstern/labit reply <id> "Done: …" # answers on the pin
32
+ npx @leonidstern/labit reply <id> --done "…" # answers on the pin and closes it
33
33
  ```
34
34
 
35
35
  Or as an MCP server: `npx @leonidstern/labit@latest mcp`.
36
36
 
37
+ Everything merged to main, before it is released: `npx @leonidstern/labit@next`.
38
+
39
+ **Fewer permission prompts (Claude Code):** copy [examples/claude-settings.json](examples/claude-settings.json) to `.claude/settings.json` in your project (or merge its `permissions` into yours). labit's commands and MCP tools then run without asking; `--wifi` and `invite`, which let another device in, still ask. Claude Code reads a project's allow rules only once you've opened the folder in it and trusted it.
40
+
37
41
  ## Good to know
38
42
 
39
43
  - `--wifi` lets your phone comment too. Each device opens a one-time link from `npx @leonidstern/labit invite`, so being on the same wifi isn't enough. The pages still travel in the clear over the wifi.
40
- - You name yourself once. The name is kept for this computer in `~/.config/labit/me.json`, so every later lab starts out knowing you — browsers keep it per port, labs don't. `labit invite [name]` carries a name to a phone the same way.
44
+ - Agents learn how you like answers: reply as usual, and when you say an answer was too long or unclear, your message shows **rule?**. Tap it and the rule goes to `~/.config/labit/replies.md`, handed to every agent with your pins.
45
+ - You name yourself once. The name is kept for this computer in `~/.config/labit/settings.json`, so every later lab starts out knowing you — browsers keep it per port, labs don't. `labit invite [name]` carries a name to a phone the same way. `--page /path` makes the link open that page. Opening a used or old link again on a phone that's already in just takes you there, and a phone that keeps using the lab stays in.
46
+ - Settings (port, your dev server, keys, how long the lab waits…): `labit.json` in the project and `~/.config/labit/settings.json` for you. `labit settings` shows them all; [docs/settings.md](docs/settings.md) explains each.
41
47
  - Comments stay in `.lab/` in your project. Add it to `.gitignore`.
42
48
  - `3` is zoom, on plain HTML pages: a comment that asks your agent for a deeper look into what it's on (3 once) or the bigger picture around it (3 again). `1` comment, `2` go, `4` pointer.
43
49
  - No dependencies, Node 22+. `--help` lists everything else.
@@ -0,0 +1,29 @@
1
+ // The shape a comment is stored in, and how an older one is read. Used by the hosted API (api/lab-comments.mjs) as it
2
+ // reads Redis and by the local lab (local.mjs) as it loads .lab/comments/: one place, so both read old records alike.
3
+ // (The _ keeps Vercel from serving this file as an endpoint of its own.)
4
+ //
5
+ // v is the version a record was saved in; a record without one is 0. upgrade() brings any record up to VERSION, filling
6
+ // new fields from the old ones, so an old file means exactly what it meant before.
7
+ // 1 (17 Nov): agent replies say what they are with intent ('done' | 'working' | 'question'), read before from the
8
+ // text ("Done: …", "On it"); a thread says when it was resolved (resolvedAt); replies no longer carry resolved:false
9
+ // (only a thread can be resolved).
10
+ export const VERSION = 1;
11
+ export const INTENTS = ['done', 'working', 'question'];
12
+
13
+ // An agent reply's intent from its words, for records (and agents) that don't say it: the rule the lab and the widget
14
+ // went by before intent existed.
15
+ export const intentFromText = (text) => (/^done\b/i.test(String(text ?? '').trim()) ? 'done' : /^on it\b/i.test(String(text ?? '').trim()) ? 'working' : undefined);
16
+
17
+ export function upgrade(record) {
18
+ if (!record || typeof record !== 'object' || (Number(record.v) || 0) >= VERSION) return record;
19
+ const c = { ...record, v: VERSION };
20
+ if (c.parent) {
21
+ if (c.resolved === false) delete c.resolved;
22
+ // Only the local lab marks the agent's own replies (session); the hosted store can't tell them from people's.
23
+ if (c.session && !c.intent) {
24
+ const intent = intentFromText(c.text);
25
+ if (intent) c.intent = intent;
26
+ }
27
+ }
28
+ return c;
29
+ }
@@ -5,6 +5,7 @@
5
5
  // LAB_HOST (e.g. lab.example.com), LAB_COMMENTS_ADMIN_TOKEN for resolving and deleting (see adminFor()).
6
6
 
7
7
  import { createHmac, timingSafeEqual } from 'node:crypto';
8
+ import { INTENTS, upgrade, VERSION } from './_schema.mjs';
8
9
 
9
10
  const LAB_HOST = process.env.LAB_HOST || '';
10
11
  const MAX = { name: 60, text: 2000, path: 300, selector: 600, context: 400, perPage: 500 };
@@ -193,7 +194,7 @@ export async function GET(request) {
193
194
  const comments = values
194
195
  .map((v) => {
195
196
  try {
196
- return JSON.parse(v);
197
+ return upgrade(JSON.parse(v));
197
198
  } catch {
198
199
  return null;
199
200
  }
@@ -303,7 +304,10 @@ function asText(path, comments, host) {
303
304
  if (a.width) lines.push(`viewport: ${a.width}${a.height ? `×${a.height}` : 'px wide'}${a.dpr ? ` @${a.dpr}x` : ''}`);
304
305
  if (a.build) lines.push(`build: ${a.build}`);
305
306
  if (a.kind !== 'page') lines.push(`selector (at comment time): ${a.selector || 'body'}`);
306
- for (const r of comments.filter((r) => r.parent === c.id)) lines.push(`reply: ${r.name}${r.from && r.from !== c.from ? ` (${r.from})` : ''} · ${stamp(r.createdAt)} · id ${r.id}: ${body(r.text)}`);
307
+ for (const r of comments.filter((r) => r.parent === c.id)) {
308
+ const rule = r.rule ? ` (kept as rule: ${r.rule})` : r.suggest ? ` (offered as rule: ${r.suggest}${r.suggestDone === 'no' ? ', they said no' : ''})` : '';
309
+ lines.push(`reply: ${r.name}${r.from && r.from !== c.from ? ` (${r.from})` : ''} · ${stamp(r.createdAt)} · id ${r.id}: ${body(r.text)}${rule}`);
310
+ }
307
311
  });
308
312
  return lines.join('\n') + '\n';
309
313
  }
@@ -343,14 +347,18 @@ export async function POST(request) {
343
347
  const own = body.action !== 'delete' && edit && typeof body.edit === 'string' && sameKey(body.edit, edit);
344
348
  if (!admin && !own) return json({ error: 'forbidden' }, 403);
345
349
  if (body.action === 'delete') {
346
- const all = ((await run('HVALS', key)) || []).map((v) => JSON.parse(v));
350
+ const all = ((await run('HVALS', key)) || []).map((v) => upgrade(JSON.parse(v)));
347
351
  if (!all.some((c) => c.id === id)) return json({ error: 'not found' }, 404);
348
352
  await run('HDEL', key, id, ...all.filter((c) => c.parent === id).map((c) => c.id));
349
353
  return json({ ok: true });
350
354
  }
351
355
  const current = await run('HGET', key, id);
352
356
  if (!current) return json({ error: 'not found' }, 404);
353
- const comment = { ...JSON.parse(current), resolved: body.action === 'resolve', resolvedBy: body.action === 'resolve' ? admin?.name || 'author' : undefined };
357
+ // Who resolved it: the agent (an admin request the lab marks as the agent's, as labit resolve and --resolve are), an
358
+ // admin by name, or whoever started the thread. Reopening clears who and when.
359
+ const by = admin && request.headers.get('x-lab-agent') === '1' ? 'agent' : admin?.name || 'author';
360
+ const resolve = body.action === 'resolve';
361
+ const comment = { ...upgrade(JSON.parse(current)), resolved: resolve, resolvedBy: resolve ? by : undefined, resolvedAt: resolve ? new Date().toISOString() : undefined };
354
362
  await run('HSET', key, id, JSON.stringify(comment));
355
363
  return json({ comment });
356
364
  }
@@ -362,7 +370,7 @@ export async function POST(request) {
362
370
  if (!isAdmin(request, path) && !(edit && typeof body.edit === 'string' && sameKey(body.edit, edit))) return json({ error: 'forbidden' }, 403);
363
371
  const current = await run('HGET', key, id);
364
372
  if (!current) return json({ error: 'not found' }, 404);
365
- const thread = JSON.parse(current);
373
+ const thread = upgrade(JSON.parse(current));
366
374
  if (thread.parent || !body.anchor || typeof body.anchor !== 'object') return json({ error: 'bad move' }, 400);
367
375
  const anchor = cleanAnchor(body.anchor);
368
376
  if (thread.anchor?.zoom && !anchor.zoom) anchor.zoom = thread.anchor.zoom; // a moved zoom stays a zoom, whatever the widget sent
@@ -383,7 +391,7 @@ export async function POST(request) {
383
391
  const was = await run('GET', nonceKey);
384
392
  const earlier = was && (await run('HGET', key, was));
385
393
  if (earlier) {
386
- const c = JSON.parse(earlier);
394
+ const c = upgrade(JSON.parse(earlier));
387
395
  const edit = c.parent ? null : editKey(path, c.id);
388
396
  return json(edit ? { comment: c, edit } : { comment: c }, 200);
389
397
  }
@@ -403,7 +411,13 @@ export async function POST(request) {
403
411
  limited ? ['INCR', hourKey] : ['HLEN', key],
404
412
  limited && ['EXPIRE', hourKey, 3600],
405
413
  );
406
- if (count >= MAX.perPage) return json({ error: 'too many comments on this page' }, 429);
414
+ // A page full of open talk takes no more from people: open threads (and their replies) count, done ones don't, so a
415
+ // long-lived page doesn't fill up for good. Admins (the owner, the agent) are never refused: an answer always lands.
416
+ if (limited && count >= MAX.perPage) {
417
+ const all = ((await run('HVALS', key)) || []).map((v) => JSON.parse(v));
418
+ const done = new Set(all.filter((c) => !c.parent && c.resolved).map((c) => c.id));
419
+ if (all.filter((c) => !done.has(c.parent || c.id)).length >= MAX.perPage) return json({ error: 'too many comments on this page' }, 429);
420
+ }
407
421
  if (limited && used > (Number(process.env.LAB_COMMENTS_PER_HOUR) || 60)) return json({ error: 'too many comments, try again later' }, 429);
408
422
 
409
423
  // Replies attach to the thread (a reply to a reply goes to its thread). Someone answering a resolved thread
@@ -411,27 +425,36 @@ export async function POST(request) {
411
425
  let thread = null;
412
426
  if (parent) {
413
427
  if (!found) return json({ error: 'thread not found' }, 404);
414
- thread = JSON.parse(found);
428
+ thread = upgrade(JSON.parse(found));
415
429
  if (thread.parent) {
416
430
  parent = thread.parent;
417
431
  const root = await run('HGET', key, parent);
418
432
  if (!root) return json({ error: 'thread not found' }, 404);
419
- thread = JSON.parse(root);
433
+ thread = upgrade(JSON.parse(root));
420
434
  }
421
435
  }
422
436
 
423
437
  const anchor = body.anchor || {};
424
438
  const comment = {
439
+ v: VERSION,
425
440
  id: crypto.randomUUID().replace(/-/g, '').slice(0, 12),
426
441
  parent,
427
442
  name,
428
443
  text,
429
444
  createdAt: new Date().toISOString(),
430
- resolved: false,
445
+ // Only a thread is open or resolved; a reply has no such state.
446
+ ...(parent ? {} : { resolved: false }),
431
447
  anchor: parent ? null : cleanAnchor(anchor),
448
+ // The message in the thread this one answers, when it isn't the first (shown as a quote).
449
+ ...(parent && body.to ? { to: clean(body.to, 40) } : {}),
450
+ // A rule the agent offers on its own, from a reply about how it answered (labit reply --suggest-rule): kept with a tap.
451
+ ...(parent && body.suggest && !limited ? { suggest: cleanText(body.suggest, 200) } : {}),
452
+ // What the agent's answer is (labit reply --done / --on-it / --question): the thread's state is read from it, not
453
+ // from the words. Admins only, as the agent always is.
454
+ ...(parent && INTENTS.includes(body.intent) && !limited ? { intent: body.intent } : {}),
432
455
  };
433
456
  // The comment, and the reopened thread when someone (not an admin) answers a resolved one: one round trip.
434
- if (thread?.resolved && limited) await run('HSET', key, comment.id, JSON.stringify(comment), parent, JSON.stringify({ ...thread, resolved: false, resolvedBy: undefined }));
457
+ if (thread?.resolved && limited) await run('HSET', key, comment.id, JSON.stringify(comment), parent, JSON.stringify({ ...thread, resolved: false, resolvedBy: undefined, resolvedAt: undefined }));
435
458
  else await run('HSET', key, comment.id, JSON.stringify(comment));
436
459
  if (nonceKey) await run('SET', nonceKey, comment.id, 'EX', 900);
437
460
  const edit = parent ? null : editKey(path, comment.id);
@@ -0,0 +1,71 @@
1
+ // lib/args.ts
2
+ function listenPages(opts, forWait = false) {
3
+ const raw = opts.pages || (forWait ? opts.page : "");
4
+ if (!raw) return null;
5
+ return String(raw).split(",").map((p) => "/" + p.trim().replace(/^\/+/, "").replace(/\.html?$/i, "")).filter((p) => p !== "/");
6
+ }
7
+ var SWITCHES = ["--wifi", "--no-open", "--resolve", "--wait", "--new", "--all", "--bg", "--fast", "--no-fast", "--done", "--on-it", "--question"];
8
+ function replyIntent(opts) {
9
+ const given = ["done", "on-it", "question"].filter((f) => opts[f]);
10
+ if (given.length > 1) return new Error(`Give one of --done, --on-it, --question, not ${given.map((f) => `--${f}`).join(" and ")}.`);
11
+ return given[0] === "on-it" ? "working" : given[0];
12
+ }
13
+ var FOREGROUND_CAP = 60;
14
+ var WAIT_DEFAULT = 1500;
15
+ function waitSeconds(opts, isTTY = false) {
16
+ const asked = Number(opts.timeout) || WAIT_DEFAULT;
17
+ if (opts.bg || isTTY || process.env.LABIT_BACKGROUND === "1") return { seconds: asked, capped: false };
18
+ return { seconds: Math.min(asked, FOREGROUND_CAP), capped: asked > FOREGROUND_CAP };
19
+ }
20
+ var WRITE_SHORT = "Write answers short: they're read in a small window, often on a phone. One point per line or two, a blank line between points, '- ' lines for lists.";
21
+ var VALUED = ["--port", "--name", "--page", "--pages", "--timeout", "--dir", "--proxy", "--model", "--suggest-rule"];
22
+ function parseArgs(argv) {
23
+ const opts = {};
24
+ const pos = [];
25
+ const unknownFlags = [];
26
+ for (let i = 0; i < argv.length; i++) {
27
+ const a = argv[i];
28
+ if (a === "--") {
29
+ pos.push(...argv.slice(i + 1));
30
+ break;
31
+ }
32
+ if (a === "--help" || a === "-h") opts.help = true;
33
+ else if (a === "--version" || a === "-v") opts.version = true;
34
+ else if (SWITCHES.includes(a)) opts[a.slice(2)] = true;
35
+ else if (a.startsWith("--") && !VALUED.includes(a)) unknownFlags.push(a);
36
+ else if (VALUED.includes(a)) {
37
+ const v = argv[i + 1];
38
+ if (v === void 0 || v.startsWith("-")) opts[a.slice(2)] = true;
39
+ else opts[a.slice(2)] = argv[++i];
40
+ } else pos.push(a);
41
+ }
42
+ return { opts, pos, unknownFlags };
43
+ }
44
+
45
+ // lib/labs.ts
46
+ import fs from "node:fs";
47
+ import os from "node:os";
48
+ import path from "node:path";
49
+ var REGISTRY = path.join(process.env.LABIT_HOME || path.join(os.homedir(), ".labit"), "servers");
50
+ var runningLabs = () => (fs.existsSync(REGISTRY) ? fs.readdirSync(REGISTRY) : []).filter((n) => n.endsWith(".json")).flatMap((n) => {
51
+ const file = path.join(REGISTRY, n);
52
+ try {
53
+ const lab = JSON.parse(fs.readFileSync(file, "utf8"));
54
+ process.kill(lab.pid, 0);
55
+ return [lab];
56
+ } catch {
57
+ fs.rmSync(file, { force: true });
58
+ return [];
59
+ }
60
+ }).sort((a, b) => a.root.localeCompare(b.root));
61
+
62
+ export {
63
+ listenPages,
64
+ replyIntent,
65
+ FOREGROUND_CAP,
66
+ waitSeconds,
67
+ WRITE_SHORT,
68
+ parseArgs,
69
+ REGISTRY,
70
+ runningLabs
71
+ };
@@ -0,0 +1,13 @@
1
+ // lib/flags.ts
2
+ var FLAGS = {
3
+ liveUrl: { name: "a lab on a live URL", since: "0.6.2" },
4
+ agentPins: { name: "agent pins wear labit's mark", since: "0.6.2" }
5
+ };
6
+ var flagDefaults = () => Object.fromEntries(Object.keys(FLAGS).map((k) => [k, false]));
7
+ var flagsOn = (flags = {}) => Object.keys(FLAGS).filter((k) => flags[k]);
8
+
9
+ export {
10
+ FLAGS,
11
+ flagDefaults,
12
+ flagsOn
13
+ };
@@ -0,0 +1,49 @@
1
+ // lib/labcall.ts
2
+ import http from "node:http";
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ function findLab(from) {
6
+ for (let dir = path.resolve(from); ; dir = path.dirname(dir)) {
7
+ const file = path.join(dir, ".lab/server.json");
8
+ if (fs.existsSync(file)) return { dir, server: JSON.parse(fs.readFileSync(file, "utf8")) };
9
+ if (path.dirname(dir) === dir) return null;
10
+ }
11
+ }
12
+ var labCall = (server, pathname, body, session, signal) => new Promise((resolve, reject) => {
13
+ const data = JSON.stringify(body);
14
+ const req = http.request(
15
+ {
16
+ host: "127.0.0.1",
17
+ port: server.port,
18
+ path: pathname,
19
+ method: "POST",
20
+ signal,
21
+ headers: {
22
+ host: `localhost:${server.port}`,
23
+ "content-type": "application/json",
24
+ "content-length": Buffer.byteLength(data),
25
+ "x-lab-admin": server.agent || server.token,
26
+ "x-lab-agent": "1",
27
+ "x-lab-session": encodeURIComponent(JSON.stringify(session))
28
+ }
29
+ },
30
+ (res) => {
31
+ let text = "";
32
+ res.on("data", (c) => text += c);
33
+ res.on("end", () => resolve({ status: res.statusCode || 0, text }));
34
+ }
35
+ );
36
+ req.on("error", reject);
37
+ req.end(data);
38
+ });
39
+ var WAIT_SAID = {
40
+ 204: "No new comments yet. Run wait again to keep listening.",
41
+ 409: "Another session is listening now; this one stopped.",
42
+ 410: "The page was closed, so this stopped listening. Wait again only when the person asks or opens the page."
43
+ };
44
+
45
+ export {
46
+ findLab,
47
+ labCall,
48
+ WAIT_SAID
49
+ };
@@ -1,35 +1,3 @@
1
- // lib/args.ts
2
- function listenPages(opts, forWait = false) {
3
- const raw = opts.pages || (forWait ? opts.page : "");
4
- if (!raw) return null;
5
- return String(raw).split(",").map((p) => "/" + p.trim().replace(/^\/+/, "").replace(/\.html?$/i, "")).filter((p) => p !== "/");
6
- }
7
- var SWITCHES = ["--wifi", "--no-open", "--resolve", "--wait", "--new", "--all", "--fast", "--no-fast"];
8
- var WRITE_SHORT = "Write answers short: they're read in a small window, often on a phone. One point per line or two, a blank line between points, '- ' lines for lists.";
9
- var VALUED = ["--port", "--name", "--page", "--pages", "--timeout", "--dir", "--proxy", "--model"];
10
- function parseArgs(argv) {
11
- const opts = {};
12
- const pos = [];
13
- const unknownFlags = [];
14
- for (let i = 0; i < argv.length; i++) {
15
- const a = argv[i];
16
- if (a === "--") {
17
- pos.push(...argv.slice(i + 1));
18
- break;
19
- }
20
- if (a === "--help" || a === "-h") opts.help = true;
21
- else if (a === "--version" || a === "-v") opts.version = true;
22
- else if (SWITCHES.includes(a)) opts[a.slice(2)] = true;
23
- else if (a.startsWith("--") && !VALUED.includes(a)) unknownFlags.push(a);
24
- else if (VALUED.includes(a)) {
25
- const v = argv[i + 1];
26
- if (v === void 0 || v.startsWith("-")) opts[a.slice(2)] = true;
27
- else opts[a.slice(2)] = argv[++i];
28
- } else pos.push(a);
29
- }
30
- return { opts, pos, unknownFlags };
31
- }
32
-
33
1
  // lib/agents.ts
34
2
  var AGENTS = {
35
3
  amp: { name: "Amp", env: ["AMP_CURRENT_THREAD_ID"] },
@@ -76,31 +44,9 @@ function mySession(asked, model) {
76
44
  };
77
45
  }
78
46
 
79
- // lib/labs.ts
80
- import fs from "node:fs";
81
- import os from "node:os";
82
- import path from "node:path";
83
- var REGISTRY = path.join(process.env.LABIT_HOME || process.env.LABFB_HOME || path.join(os.homedir(), ".labit"), "servers");
84
- var runningLabs = () => (fs.existsSync(REGISTRY) ? fs.readdirSync(REGISTRY) : []).filter((n) => n.endsWith(".json")).flatMap((n) => {
85
- const file = path.join(REGISTRY, n);
86
- try {
87
- const lab = JSON.parse(fs.readFileSync(file, "utf8"));
88
- process.kill(lab.pid, 0);
89
- return [lab];
90
- } catch {
91
- fs.rmSync(file, { force: true });
92
- return [];
93
- }
94
- }).sort((a, b) => a.root.localeCompare(b.root));
95
-
96
47
  export {
97
- listenPages,
98
- WRITE_SHORT,
99
- parseArgs,
100
48
  AGENTS,
101
49
  agentKind,
102
50
  agentNow,
103
- mySession,
104
- REGISTRY,
105
- runningLabs
51
+ mySession
106
52
  };
@@ -1,11 +1,20 @@
1
1
  import {
2
+ FOREGROUND_CAP,
2
3
  listenPages,
3
- mySession,
4
- runningLabs
5
- } from "./chunk-T4IF6ZJQ.mjs";
4
+ replyIntent,
5
+ runningLabs,
6
+ waitSeconds
7
+ } from "./chunk-AVPXXSFF.mjs";
8
+ import {
9
+ WAIT_SAID,
10
+ findLab,
11
+ labCall
12
+ } from "./chunk-QTMKKULT.mjs";
13
+ import {
14
+ mySession
15
+ } from "./chunk-X4RYDWNI.mjs";
6
16
 
7
17
  // lib/commands.ts
8
- import http from "node:http";
9
18
  import fs from "node:fs";
10
19
  import path from "node:path";
11
20
  async function runCommand({ pos, opts, HERE, CMD, ME, die }) {
@@ -38,11 +47,21 @@ ${JSON.stringify(entry(), null, 2)}`);
38
47
  const forHere = (lab) => lab.root === HERE || lab.root.startsWith(HERE + path.sep) || HERE.startsWith(lab.root + path.sep);
39
48
  const LINKS = path.join(HERE, ".lab", "links.json");
40
49
  const savedLinks = () => {
50
+ let text;
41
51
  try {
42
- return JSON.parse(fs.readFileSync(LINKS, "utf8"));
52
+ text = fs.readFileSync(LINKS, "utf8");
43
53
  } catch {
44
54
  return [];
45
55
  }
56
+ try {
57
+ const list = JSON.parse(text);
58
+ if (Array.isArray(list)) return list;
59
+ } catch {
60
+ }
61
+ const aside = `${LINKS}.broken-${Date.now()}`;
62
+ fs.renameSync(LINKS, aside);
63
+ console.error(`[lab] .lab/links.json was damaged; moved it to ${path.basename(aside)}`);
64
+ return [];
46
65
  };
47
66
  const cloudOpen = async (url) => {
48
67
  try {
@@ -75,7 +94,8 @@ ${JSON.stringify(entry(), null, 2)}`);
75
94
  list.push({ url: key, title });
76
95
  }
77
96
  fs.mkdirSync(path.dirname(LINKS), { recursive: true });
78
- fs.writeFileSync(LINKS, JSON.stringify(list, null, 2) + "\n");
97
+ fs.writeFileSync(LINKS + ".tmp", JSON.stringify(list, null, 2) + "\n");
98
+ fs.renameSync(LINKS + ".tmp", LINKS);
79
99
  console.log(pos[0] === "add" ? `Saved ${key}${title ? ` (${title})` : ""}. It shows in \`${CMD} pages\` and \`${CMD} list\`.` : `Removed ${key}.`);
80
100
  process.exit(0);
81
101
  }
@@ -134,46 +154,16 @@ ${links.map((l) => `${l.title || l.url} ${l.url}`).join("\n")}`);
134
154
  }
135
155
  if (["wait", "reply", "resolve", "invite", "zoom"].includes(pos[0])) {
136
156
  const [cmd, ref, ...words] = pos;
137
- let dir = path.resolve(opts.dir || ".");
138
- while (!fs.existsSync(path.join(dir, ".lab/server.json"))) {
139
- if (path.dirname(dir) === dir) die(`No lab server for this folder. Start one: run ${CMD} in the project.`);
140
- dir = path.dirname(dir);
141
- }
142
- const server = JSON.parse(fs.readFileSync(path.join(dir, ".lab/server.json"), "utf8"));
157
+ const lab = findLab(opts.dir || ".") || die(`No lab server for this folder. Start one: run ${CMD} in the project.`);
158
+ const { dir, server } = lab;
143
159
  const session = mySession(opts.name, opts.model);
144
- const call = (pathname, body) => new Promise((resolve) => {
145
- const data2 = JSON.stringify(body);
146
- const req = http.request(
147
- {
148
- host: "127.0.0.1",
149
- port: server.port,
150
- path: pathname,
151
- method: "POST",
152
- headers: {
153
- host: `localhost:${server.port}`,
154
- "content-type": "application/json",
155
- "content-length": Buffer.byteLength(data2),
156
- "x-lab-admin": server.token,
157
- "x-lab-agent": "1",
158
- "x-lab-session": encodeURIComponent(JSON.stringify(session))
159
- }
160
- },
161
- (res) => {
162
- let text = "";
163
- res.on("data", (c) => text += c);
164
- res.on("end", () => resolve({ status: res.statusCode || 0, text }));
165
- }
166
- );
167
- req.on(
168
- "error",
169
- () => die(
170
- process.env.CODEX_SANDBOX_NETWORK_DISABLED ? `Codex's sandbox blocks this command from reaching the lab on this computer (port ${server.port}). Use labit's MCP server instead: codex mcp add labit -- npx @leonidstern/labit@latest mcp. Or let the sandbox reach it: -c sandbox_workspace_write.network_access=true` : `The lab server for ${dir} isn't running. Start it: ${CMD} ${dir === process.cwd() ? "" : dir}`.trim() + "."
171
- )
172
- );
173
- req.end(data2);
174
- });
160
+ const call = (pathname, body) => labCall(server, pathname, body, session).catch(
161
+ () => die(
162
+ process.env.CODEX_SANDBOX_NETWORK_DISABLED ? `Codex's sandbox blocks this command from reaching the lab on this computer (port ${server.port}). Use labit's MCP server instead: codex mcp add labit -- npx @leonidstern/labit@latest mcp. Or let the sandbox reach it: -c sandbox_workspace_write.network_access=true` : `The lab server for ${dir} isn't running. Start it: ${CMD} ${dir === process.cwd() ? "" : dir}`.trim() + "."
163
+ )
164
+ );
175
165
  if (cmd === "invite") {
176
- const out = await call("/_lab/invite", { name: [ref, ...words].filter(Boolean).join(" ") });
166
+ const out = await call("/_lab/invite", { name: [ref, ...words].filter(Boolean).join(" "), page: opts.page || "" });
177
167
  if (out.status === 404) die("This lab is open to this computer only. Start it with --wifi to let a phone in.");
178
168
  if (out.status >= 300) die(`Could not make a link: ${out.text}`);
179
169
  const { links, name } = JSON.parse(out.text);
@@ -184,11 +174,14 @@ The device that opens it is ${name} in this lab.`);
184
174
  process.exit(0);
185
175
  }
186
176
  if (cmd === "wait") {
187
- const out = await call("/_lab/wait", { timeout: Number(opts.timeout) || 1500, pages: listenPages(opts, true) });
188
- if (out.status === 204) console.log("No new comments yet. Run wait again to keep listening.");
189
- else if (out.status === 409) console.log("Another session is listening now; this one stopped.");
190
- else if (out.status === 410) console.log("The page was closed, so this stopped listening. Wait again only when the person asks or opens the page.");
191
- else console.log(out.text);
177
+ const { seconds, capped } = waitSeconds(opts, process.stdout.isTTY === true);
178
+ const out = await call("/_lab/wait", { timeout: seconds, pages: listenPages(opts, true) });
179
+ console.log(WAIT_SAID[out.status] ?? out.text);
180
+ if (capped && out.status === 204)
181
+ console.log(
182
+ `
183
+ That wait was held to ${FOREGROUND_CAP} seconds. Run it in the background (your app's own way of doing that) and add --bg for the full wait: in the foreground this command holds your turn open, and the person cannot say anything to you until it ends.`
184
+ );
192
185
  process.exit(out.status < 300 || out.status === 409 || out.status === 410 ? 0 : 1);
193
186
  }
194
187
  const data = {};
@@ -204,7 +197,7 @@ The device that opens it is ${name} in this lab.`);
204
197
  }
205
198
  const want = opts.page ? "/" + opts.page.replace(/^\/+/, "") : null;
206
199
  let hit = null;
207
- for (const [page, list] of Object.entries(data)) if (list[ref]) hit = { page, id: list[ref].parent || ref };
200
+ for (const [page, list] of Object.entries(data)) if (list[ref]) hit = { page, id: list[ref].parent || ref, to: list[ref].parent ? ref : "" };
208
201
  if (!hit && /^\d+$/.test(ref || "")) {
209
202
  const hits = Object.entries(data).filter(([page]) => !want || page === want).map(([page, list]) => {
210
203
  const open = Object.values(list).filter((c) => !c.parent && !c.resolved).sort((a, b) => a.createdAt.localeCompare(b.createdAt));
@@ -233,9 +226,11 @@ The device that opens it is ${name} in this lab.`);
233
226
  }
234
227
  if (cmd === "reply") {
235
228
  if (!words.length) die(`Reply text is missing: ${CMD} reply <id> "what you did"`);
229
+ const intent = replyIntent(opts);
230
+ if (intent instanceof Error) die(intent.message);
236
231
  const who = process.env.LAB_AGENT_NAME || session.agent;
237
232
  const name = `${who}${session.name !== session.agent ? ` \xB7 ${session.name}` : ""}`;
238
- const out = await call("/_lab/api/comments", { page: hit.page, parent: hit.id, name, text: words.join(" ") });
233
+ const out = await call("/_lab/api/comments", { page: hit.page, parent: hit.id, ...hit.to ? { to: hit.to } : {}, name, text: words.join(" "), ...typeof opts["suggest-rule"] === "string" ? { suggest: opts["suggest-rule"] } : {}, ...intent ? { intent } : {} });
239
234
  if (out.status >= 300) die(`Could not reply: ${out.text}`);
240
235
  }
241
236
  if (cmd === "resolve" || opts.resolve) {
@@ -244,8 +239,12 @@ The device that opens it is ${name} in this lab.`);
244
239
  }
245
240
  console.log(`${cmd === "reply" ? opts.resolve ? "Replied and resolved" : "Replied" : "Resolved"} on ${hit.page}.`);
246
241
  if (opts.wait) {
247
- const out = await call("/_lab/wait", { timeout: Number(opts.timeout) || 1500, pages: listenPages(opts) });
248
- console.log(out.status === 204 ? "No new comments yet. Run wait again to keep listening." : out.status === 409 ? "Another session is listening now; this one stopped." : out.status === 410 ? "The page was closed, so this stopped listening." : out.text);
242
+ const { seconds, capped } = waitSeconds(opts, process.stdout.isTTY === true);
243
+ const out = await call("/_lab/wait", { timeout: seconds, pages: listenPages(opts) });
244
+ console.log(WAIT_SAID[out.status] ?? out.text);
245
+ if (capped && out.status === 204)
246
+ console.log(`
247
+ That wait was held to ${FOREGROUND_CAP} seconds: run the command in the background and add --bg for the full wait.`);
249
248
  }
250
249
  process.exit(0);
251
250
  }
@@ -0,0 +1,10 @@
1
+ import {
2
+ FLAGS,
3
+ flagDefaults,
4
+ flagsOn
5
+ } from "./chunk-DIR2O7SK.mjs";
6
+ export {
7
+ FLAGS,
8
+ flagDefaults,
9
+ flagsOn
10
+ };