@hansenexus/hud 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +153 -14
  2. package/dist/{access-Bc709qpl.d.ts → access-CwPCPsv0.d.ts} +1 -1
  3. package/dist/auto/runtime.d.ts +9 -9
  4. package/dist/auto.d.ts +2 -2
  5. package/dist/auto.js +1 -1
  6. package/dist/cli.js +34 -1
  7. package/dist/{define-hud-DTv3njuU.d.ts → define-hud-B0aFXrcK.d.ts} +1 -1
  8. package/dist/{design-BXG1a4we.js → design-BIXY1-Ex.js} +26 -8
  9. package/dist/{force-state-panel-mu-txJnA.js → force-state-panel-D5oDydLs.js} +1 -1
  10. package/dist/{handler-DMzSTqyG.d.ts → handler-BmFhaA2D.d.ts} +1 -1
  11. package/dist/{index-C3wzZS3o.d.ts → index-5B7foZut.d.ts} +2 -2
  12. package/dist/{index-D-hI-DRJ.d.ts → index-B2KCKkN0.d.ts} +1 -1
  13. package/dist/index-B7qaEUgh.d.ts +44 -0
  14. package/dist/{index-CQXiuMZQ.d.ts → index-BGFyuJyN.d.ts} +1 -1
  15. package/dist/{index-Caohnz3B.d.ts → index-BeqWehuh.d.ts} +38 -10
  16. package/dist/{index-BJJoAXJ2.d.ts → index-BqKysxTq.d.ts} +1 -1
  17. package/dist/{index-DLCSLWW4.d.ts → index-D97Fnoie.d.ts} +2 -2
  18. package/dist/{index-BR5OB7DO.d.ts → index-DS0yT0c-.d.ts} +1 -1
  19. package/dist/{index-BNoPbSYD.d.ts → index-DvlCkGB1.d.ts} +1 -1
  20. package/dist/index.d.ts +3 -3
  21. package/dist/index.js +49 -196
  22. package/dist/lanes-panel-Disg54DY.js +395 -0
  23. package/dist/navigation-CX6AXm7H.js +176 -0
  24. package/dist/next/config.cjs +2 -0
  25. package/dist/next/config.d.cts +1 -0
  26. package/dist/next/config.d.ts +1 -0
  27. package/dist/next/config.js +2 -0
  28. package/dist/next.d.ts +4 -1
  29. package/dist/next.js +12 -1
  30. package/dist/obstacles-CCmRFTcZ.js +176 -0
  31. package/dist/plugins/a11y.d.ts +1 -1
  32. package/dist/plugins/access/server.d.ts +3 -3
  33. package/dist/plugins/access.d.ts +2 -2
  34. package/dist/plugins/agent/server.js +1 -1
  35. package/dist/plugins/agent.d.ts +2 -2
  36. package/dist/plugins/capture.d.ts +2 -2
  37. package/dist/plugins/data/server.d.ts +1 -1
  38. package/dist/plugins/data/server.js +1 -1
  39. package/dist/plugins/data.d.ts +1 -1
  40. package/dist/plugins/design/server.d.ts +55 -15
  41. package/dist/plugins/design/server.js +187 -122
  42. package/dist/plugins/design.d.ts +3 -3
  43. package/dist/plugins/design.js +1 -1
  44. package/dist/plugins/inspect.d.ts +1 -1
  45. package/dist/plugins/lanes/server.d.ts +165 -0
  46. package/dist/plugins/lanes/server.js +845 -0
  47. package/dist/plugins/lanes.d.ts +22 -0
  48. package/dist/plugins/lanes.js +30 -0
  49. package/dist/plugins/observe.d.ts +1 -1
  50. package/dist/plugins/ops/server.d.ts +1 -1
  51. package/dist/plugins/ops.d.ts +1 -1
  52. package/dist/plugins/routes/server.d.ts +1 -1
  53. package/dist/plugins/routes.d.ts +3 -3
  54. package/dist/plugins/routes.js +381 -52
  55. package/dist/plugins/seo.d.ts +1 -1
  56. package/dist/plugins/vitals.d.ts +1 -1
  57. package/dist/{plugins-BZT-1LBe.d.ts → plugins-pL2CoWzI.d.ts} +7 -0
  58. package/dist/same-origin-BHuZO1_H.js +36 -0
  59. package/dist/server.d.ts +2 -2
  60. package/dist/store.d.ts +1 -1
  61. package/dist/store.js +1 -1
  62. package/dist/types-BkrkOP3h.js +6 -0
  63. package/dist/types-Dazn3aWZ.d.ts +86 -0
  64. package/dist/{meta-C_G7MB5w.d.ts → types-Dc6JWZR7.d.ts} +6 -6
  65. package/dist/variant-bar-BzZ0ln-C.js +768 -0
  66. package/dist/variant-picks-Byc0hC8a.js +144 -0
  67. package/dist/variants-export-vEtZ-OGC.js +75 -0
  68. package/dist/{variants-panel-B6zWcknV.js → variants-panel-D23v5KIp.js} +71 -54
  69. package/dist/variants-types-BOsZ5fDz.js +65 -0
  70. package/dist/variants-types-VkW7vFZF.d.ts +139 -0
  71. package/dist/variants.d.ts +1 -1
  72. package/dist/variants.js +1 -1
  73. package/dist/vite.d.ts +2 -2
  74. package/package.json +2 -2
  75. package/dist/index-B1vHAY9p.d.ts +0 -20
  76. package/dist/same-origin-BGet22CC.js +0 -21
  77. package/dist/variants-types-CcRf119M.d.ts +0 -63
@@ -0,0 +1,845 @@
1
+ import { i as definePlugin } from "../../plugins-CcW_K7c2.js";
2
+ import { t as refuseCrossSite } from "../../same-origin-BHuZO1_H.js";
3
+ import { sameOriginUrl, screenshot } from "../capture/server.js";
4
+ import { n as LANES_ID, t as LANES_CAPABILITY } from "../../types-BkrkOP3h.js";
5
+ //#region src/plugins/lanes/box.ts
6
+ const LANE_NAME = /^(.+?)-(?:issue|takeover)-(\d+)(?:-|$)/;
7
+ /** `hud-issue-101-slug` → `{ repo: "hud", issue: 101 }`; a name off the pattern keeps its folder's repo. */
8
+ function parseLaneName(name) {
9
+ const m = LANE_NAME.exec(name);
10
+ return m?.[1] && m[2] ? {
11
+ repo: m[1],
12
+ issue: Number(m[2])
13
+ } : {};
14
+ }
15
+ /** Processes that listen but are no dev server: the agent CLIs' own IDE and MCP sockets. */
16
+ const NOT_DEV = /* @__PURE__ */ new Set([
17
+ "claude",
18
+ "codex",
19
+ "hermes"
20
+ ]);
21
+ /** The ephemeral range (IANA, and macOS's default): OS-assigned ports, never a dev server's. */
22
+ const EPHEMERAL = 49152;
23
+ /**
24
+ * `lsof -nP -iTCP -sTCP:LISTEN -Fpcn` → one entry per pid and port. Ports
25
+ * below 1024 or in the ephemeral range, and agent CLI processes, are dropped.
26
+ */
27
+ function parseListeners(out) {
28
+ const found = /* @__PURE__ */ new Map();
29
+ let pid = 0;
30
+ let skip = false;
31
+ for (const line of out.split("\n")) if (line.startsWith("p")) {
32
+ pid = Number(line.slice(1));
33
+ skip = false;
34
+ } else if (line.startsWith("c")) skip = NOT_DEV.has(line.slice(1).toLowerCase());
35
+ else if (line.startsWith("n") && pid > 0 && !skip) {
36
+ const name = line.slice(1);
37
+ const colon = name.lastIndexOf(":");
38
+ const port = Number(name.slice(colon + 1));
39
+ if (!Number.isInteger(port) || port < 1024 || port >= EPHEMERAL) continue;
40
+ const addr = name.slice(0, colon).replace(/^\[|\]$/g, "");
41
+ const loopback = addr === "::1" || addr.startsWith("127.") || addr === "localhost";
42
+ const key = `${pid}:${port}`;
43
+ const seen = found.get(key);
44
+ found.set(key, {
45
+ pid,
46
+ port,
47
+ loopback: (seen?.loopback ?? true) && loopback
48
+ });
49
+ }
50
+ return [...found.values()];
51
+ }
52
+ /** `lsof -a -d cwd -p <pids> -Fpn` → pid → working directory. */
53
+ function parseCwds(out) {
54
+ const cwds = /* @__PURE__ */ new Map();
55
+ let pid = 0;
56
+ for (const line of out.split("\n")) if (line.startsWith("p")) pid = Number(line.slice(1));
57
+ else if (line.startsWith("n") && pid > 0) cwds.set(pid, line.slice(1));
58
+ return cwds;
59
+ }
60
+ /** The newest open ledger record working in `lane`. */
61
+ function pickWorker(records, lane) {
62
+ let best;
63
+ for (const r of records) {
64
+ if (r.lane !== lane || typeof r.sid !== "string" || r.state === "closed") continue;
65
+ const seen = typeof r.last_seen === "string" ? r.last_seen : "";
66
+ if (best && best.seen >= seen) continue;
67
+ best = {
68
+ sid: r.sid,
69
+ state: typeof r.state === "string" ? r.state : "unknown",
70
+ seen,
71
+ ...typeof r.theme === "string" ? { theme: r.theme } : {}
72
+ };
73
+ }
74
+ if (!best) return void 0;
75
+ const { seen: _seen, ...worker } = best;
76
+ return worker;
77
+ }
78
+ /** The first terminal handle anywhere in `lane-runtime terminal list`'s JSON (as kommandant's session-mirror reads it). */
79
+ function firstHandle(value) {
80
+ if (Array.isArray(value)) for (const item of value) {
81
+ const found = firstHandle(item);
82
+ if (found) return found;
83
+ }
84
+ else if (value !== null && typeof value === "object") {
85
+ const bag = value;
86
+ if (typeof bag.handle === "string" && bag.handle !== "") return bag.handle;
87
+ for (const v of Object.values(bag)) {
88
+ const found = firstHandle(v);
89
+ if (found) return found;
90
+ }
91
+ }
92
+ }
93
+ /** Arguments that put a dev script on `port` and `address`, by framework. */
94
+ function devArgs(target, port, address) {
95
+ const next = [
96
+ "--port",
97
+ String(port),
98
+ "--hostname",
99
+ address
100
+ ];
101
+ const vite = [
102
+ "--port",
103
+ String(port),
104
+ "--host",
105
+ address,
106
+ "--strictPort"
107
+ ];
108
+ if (/\bnext\b/.test(target.dev)) return next;
109
+ if (/\bvite\b/.test(target.dev)) return vite;
110
+ const deps = {
111
+ ...target.pkg.dependencies,
112
+ ...target.pkg.devDependencies
113
+ };
114
+ if ("next" in deps && !("vite" in deps)) return next;
115
+ if ("vite" in deps && !("next" in deps)) return vite;
116
+ return [];
117
+ }
118
+ /** `bun run --cwd playground dev`, `cd web && vite`: the folder a root `dev` hands over to. */
119
+ function delegatedDir(dev) {
120
+ const dir = (/--cwd[ =](\S+)\s+(?:run\s+)?dev\b/.exec(dev) ?? /^\s*cd\s+(\S+)\s*&&/.exec(dev))?.[1];
121
+ return dir && !dir.includes("..") && !dir.startsWith("/") ? dir.replace(/\/$/, "") : void 0;
122
+ }
123
+ /** `bun run dev`, `pnpm run dev` or `npm run dev --`, by lockfile. */
124
+ function runDev(files, extra) {
125
+ if (files.has("pnpm-lock.yaml")) return [
126
+ "pnpm",
127
+ "run",
128
+ "dev",
129
+ ...extra
130
+ ];
131
+ if (files.has("package-lock.json")) return [
132
+ "npm",
133
+ "run",
134
+ "dev",
135
+ ...extra.length ? ["--", ...extra] : []
136
+ ];
137
+ return [
138
+ "bun",
139
+ "run",
140
+ "dev",
141
+ ...extra
142
+ ];
143
+ }
144
+ /** What the worker reads in its terminal. One line: a terminal send submits on newline. */
145
+ function messageLine(kind, m, file) {
146
+ const where = m.url ? ` on ${m.url}` : "";
147
+ const size = m.viewport ? ` at ${m.viewport.width}x${m.viewport.height}` : "";
148
+ const text = m.text.replace(/\s+/g, " ").trim();
149
+ if (kind === "screenshot") return `HUD screenshot from the owner${where}${size}: ${file ?? "(not saved)"}${text ? ` — ${text}` : ""}`;
150
+ return `HUD comment from the owner${where}${size}: ${text}`;
151
+ }
152
+ async function loadNode() {
153
+ const [childProcess, fsp, os, path, crypto, proc] = await Promise.all([
154
+ import("node:child_process"),
155
+ import("node:fs/promises"),
156
+ import("node:os"),
157
+ import("node:path"),
158
+ import("node:crypto"),
159
+ import("node:process")
160
+ ]);
161
+ return {
162
+ childProcess,
163
+ fsp,
164
+ os,
165
+ path,
166
+ crypto,
167
+ env: proc.env,
168
+ cwd: proc.cwd()
169
+ };
170
+ }
171
+ function execWith(node) {
172
+ return (command, args, options = {}) => new Promise((resolve) => {
173
+ node.childProcess.execFile(command, args, {
174
+ cwd: options.cwd,
175
+ timeout: options.timeoutMs ?? 15e3,
176
+ maxBuffer: 8388608
177
+ }, (error, stdout, stderr) => {
178
+ const raw = error?.code;
179
+ resolve({
180
+ code: error ? typeof raw === "number" ? raw : raw === "ENOENT" ? 127 : 1 : 0,
181
+ stdout: String(stdout),
182
+ stderr: String(stderr || (error?.message ?? ""))
183
+ });
184
+ });
185
+ });
186
+ }
187
+ /**
188
+ * The real launcher: a detached `sh` takes the port's lease with its own pid,
189
+ * then `exec`s the dev script, so the lease holder *is* the dev server and
190
+ * the lease dies with it. It prints `leased` once the lease is taken; exit 3
191
+ * means someone else holds the port.
192
+ */
193
+ const WRAPPER = `port=$1 lane=$2 theme=$3 log=$4; shift 4
194
+ hn-lease "port:$port" acquire --session "hud-preview:$lane" --pid $$ --lane "$lane" --theme "$theme" --ttl 24h --purpose "hud lane preview" >>"$log" 2>&1 || exit 3
195
+ echo leased
196
+ [ -d "$HUD_LANE_ROOT/node_modules" ] || (cd "$HUD_LANE_ROOT" && bun install) >>"$log" 2>&1
197
+ exec "$@" >>"$log" 2>&1`;
198
+ function launchWith(node) {
199
+ return (order) => new Promise((resolve) => {
200
+ const child = node.childProcess.spawn("sh", [
201
+ "-c",
202
+ WRAPPER,
203
+ "sh",
204
+ String(order.port),
205
+ order.lane,
206
+ order.theme,
207
+ order.log,
208
+ ...order.command
209
+ ], {
210
+ cwd: order.cwd,
211
+ detached: true,
212
+ stdio: [
213
+ "ignore",
214
+ "pipe",
215
+ "ignore"
216
+ ],
217
+ env: {
218
+ ...node.env,
219
+ ...order.env
220
+ }
221
+ });
222
+ let settled = false;
223
+ const done = (result) => {
224
+ if (settled) return;
225
+ settled = true;
226
+ clearTimeout(timer);
227
+ child.stdout?.destroy();
228
+ child.unref();
229
+ resolve(result);
230
+ };
231
+ const timer = setTimeout(() => done({
232
+ status: "failed",
233
+ error: "no lease within 10 s"
234
+ }), 1e4);
235
+ child.stdout?.on("data", (chunk) => {
236
+ if (String(chunk).includes("leased")) done({ status: "leased" });
237
+ });
238
+ child.on("error", (error) => done({
239
+ status: "failed",
240
+ error: error.message
241
+ }));
242
+ child.on("exit", (code) => done(code === 3 ? { status: "held" } : {
243
+ status: "failed",
244
+ error: `exited ${code}, see ${order.log}`
245
+ }));
246
+ });
247
+ }
248
+ /** The real box: lsof, git, the session ledger, `hn-lease`, `lane-runtime` and `gh`. */
249
+ function nodeBox(options = {}) {
250
+ let nodePromise;
251
+ const node = () => {
252
+ nodePromise ??= loadNode();
253
+ return nodePromise;
254
+ };
255
+ const exec = async (...args) => (options.exec ?? execWith(await node()))(...args);
256
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
257
+ let hostCache;
258
+ let addressCache;
259
+ async function home() {
260
+ return options.home ?? (await node()).os.homedir();
261
+ }
262
+ async function roots() {
263
+ if (options.roots) return options.roots;
264
+ const h = await home();
265
+ return [`${h}/lanes`, `${h}/orca/workspaces`];
266
+ }
267
+ async function stateDir() {
268
+ const n = await node();
269
+ const dir = options.stateDir ?? n.path.join(n.os.tmpdir(), "hud-lanes");
270
+ await n.fsp.mkdir(dir, { recursive: true });
271
+ return dir;
272
+ }
273
+ async function listDirs(dir) {
274
+ try {
275
+ return (await (await node()).fsp.readdir(dir, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name);
276
+ } catch {
277
+ return [];
278
+ }
279
+ }
280
+ /** Every lane folder: `{ lane, repo, path }`. The first root wins on a duplicate name. */
281
+ async function laneDirs() {
282
+ const out = /* @__PURE__ */ new Map();
283
+ for (const root of await roots()) for (const repo of await listDirs(root)) for (const lane of await listDirs(`${root}/${repo}`)) if (!out.has(lane)) out.set(lane, {
284
+ lane,
285
+ repo,
286
+ path: `${root}/${repo}/${lane}`
287
+ });
288
+ return [...out.values()];
289
+ }
290
+ /**
291
+ * Where the lane's dev script runs: `apps/<repo>` when that app has one (a
292
+ * monorepo named after its main app), else the root unless its `dev` is a
293
+ * `turbo` fan-out over every app, else the one app that has a `dev` script.
294
+ */
295
+ async function devTarget(path, repo) {
296
+ const at = async (dir) => {
297
+ const pkg = await readJson(`${dir}/package.json`);
298
+ const dev = pkg?.scripts?.dev;
299
+ return pkg && typeof dev === "string" ? {
300
+ dir,
301
+ pkg,
302
+ dev
303
+ } : void 0;
304
+ };
305
+ const own = await at(`${path}/apps/${repo}`);
306
+ if (own) return own;
307
+ const root = await at(path);
308
+ const handedTo = root && delegatedDir(root.dev);
309
+ if (handedTo) {
310
+ const sub = await at(`${path}/${handedTo}`);
311
+ if (sub) return sub;
312
+ }
313
+ if (root && !/^\s*turbo\b/.test(root.dev)) return root;
314
+ const found = (await Promise.all((await listDirs(`${path}/apps`)).map((a) => at(`${path}/apps/${a}`)))).filter((a) => a !== void 0);
315
+ return found.length === 1 ? found[0] : void 0;
316
+ }
317
+ async function findLane(lane) {
318
+ if (!/^[\w.-]+$/.test(lane)) return void 0;
319
+ return (await laneDirs()).find((d) => d.lane === lane);
320
+ }
321
+ async function readJson(path) {
322
+ try {
323
+ return JSON.parse(await (await node()).fsp.readFile(path, "utf8"));
324
+ } catch {
325
+ return;
326
+ }
327
+ }
328
+ async function sessionsDir() {
329
+ return options.sessionsDir ?? `${await home()}/.claude/sessions`;
330
+ }
331
+ async function ledger() {
332
+ const dir = `${await sessionsDir()}/ledger`;
333
+ let names = [];
334
+ try {
335
+ names = await (await node()).fsp.readdir(dir);
336
+ } catch {
337
+ return [];
338
+ }
339
+ return (await Promise.all(names.filter((n) => n.endsWith(".json")).map((n) => readJson(`${dir}/${n}`)))).filter((r) => typeof r === "object" && r !== null);
340
+ }
341
+ async function host() {
342
+ if (options.host) return options.host;
343
+ const env = (await node()).env.HUD_PREVIEW_HOST;
344
+ if (env) return env;
345
+ hostCache ??= exec("tailscale", ["status", "--json"]).then((r) => {
346
+ try {
347
+ const name = JSON.parse(r.stdout).Self?.DNSName;
348
+ return typeof name === "string" && name ? name.replace(/\.$/, "") : null;
349
+ } catch {
350
+ return null;
351
+ }
352
+ });
353
+ return hostCache;
354
+ }
355
+ async function bindAddress() {
356
+ if (options.bindAddress) return options.bindAddress;
357
+ addressCache ??= exec("tailscale", ["ip", "-4"]).then((r) => r.stdout.split("\n")[0]?.trim() || null);
358
+ return addressCache;
359
+ }
360
+ async function listeners() {
361
+ const found = parseListeners((await exec("lsof", [
362
+ "-nP",
363
+ "-iTCP",
364
+ "-sTCP:LISTEN",
365
+ "-Fpcn"
366
+ ])).stdout);
367
+ if (found.length === 0) return [];
368
+ const pids = [...new Set(found.map((l) => l.pid))];
369
+ const cwd = parseCwds((await exec("lsof", [
370
+ "-a",
371
+ "-d",
372
+ "cwd",
373
+ "-p",
374
+ pids.join(","),
375
+ "-Fpn"
376
+ ])).stdout);
377
+ return found.flatMap((l) => {
378
+ const dir = cwd.get(l.pid);
379
+ return dir ? [{
380
+ ...l,
381
+ cwd: dir
382
+ }] : [];
383
+ });
384
+ }
385
+ async function terminal(path) {
386
+ const list = await exec("lane-runtime", [
387
+ "terminal",
388
+ "list",
389
+ "--worktree",
390
+ `path:${path}`
391
+ ]);
392
+ if (list.code !== 0) return void 0;
393
+ try {
394
+ return firstHandle(JSON.parse(list.stdout));
395
+ } catch {
396
+ return;
397
+ }
398
+ }
399
+ const inside = (dir, path) => dir === path || dir.startsWith(`${path}/`);
400
+ async function lanes() {
401
+ const [dirs, listening, records, name] = await Promise.all([
402
+ laneDirs(),
403
+ listeners(),
404
+ ledger(),
405
+ host()
406
+ ]);
407
+ const own = options.cwd ?? (await node()).cwd;
408
+ return Promise.all(dirs.map(async ({ lane, repo, path }) => {
409
+ const parsed = parseLaneName(lane);
410
+ const [branch, target] = await Promise.all([exec("git", [
411
+ "-C",
412
+ path,
413
+ "rev-parse",
414
+ "--abbrev-ref",
415
+ "HEAD"
416
+ ]).then((r) => r.code === 0 ? r.stdout.trim() : void 0), devTarget(path, repo)]);
417
+ const ports = /* @__PURE__ */ new Map();
418
+ for (const l of listening) {
419
+ if (!inside(l.cwd, path) || ports.has(l.port)) continue;
420
+ const server = {
421
+ port: l.port,
422
+ pid: l.pid,
423
+ url: `http://${name ?? "localhost"}:${l.port}/`
424
+ };
425
+ if (l.loopback) server.loopback = true;
426
+ ports.set(l.port, server);
427
+ }
428
+ const found = pickWorker(records, lane);
429
+ const worker = found ? {
430
+ sid: found.sid,
431
+ state: found.state
432
+ } : void 0;
433
+ const info = {
434
+ lane,
435
+ repo: parsed.repo ?? repo,
436
+ servers: [...ports.values()].sort((a, b) => a.port - b.port),
437
+ startable: target !== void 0
438
+ };
439
+ if (parsed.issue) info.issue = parsed.issue;
440
+ if (branch) info.branch = branch;
441
+ if (worker) info.worker = worker;
442
+ if (inside(own, path)) info.current = true;
443
+ return info;
444
+ })).then((all) => all.sort((a, b) => Number(!!b.current) - Number(!!a.current) || a.lane.localeCompare(b.lane)));
445
+ }
446
+ async function start(lane) {
447
+ const dir = await findLane(lane);
448
+ if (!dir) return {
449
+ ok: false,
450
+ error: `lane ${lane} not found on this box`
451
+ };
452
+ const n = await node();
453
+ const target = await devTarget(dir.path, dir.repo);
454
+ if (!target) return {
455
+ ok: false,
456
+ error: "the lane has no dev script to start"
457
+ };
458
+ const [name, address] = await Promise.all([host(), bindAddress()]);
459
+ if (!address) return {
460
+ ok: false,
461
+ error: "no tailnet address (tailscale ip -4); refusing to bind wider"
462
+ };
463
+ const files = new Set(await n.fsp.readdir(dir.path).catch(() => []));
464
+ const busy = new Set((await listeners()).map((l) => l.port));
465
+ const [low, high] = options.ports ?? [3100, 3999];
466
+ const { issue } = parseLaneName(lane);
467
+ const theme = issue ? `${dir.repo}#${issue}` : dir.repo;
468
+ const log = n.path.join(await stateDir(), `${lane}.log`);
469
+ const launch = options.launch ?? launchWith(n);
470
+ for (let port = low; port <= high; port++) {
471
+ if (busy.has(port)) continue;
472
+ const result = await launch({
473
+ cwd: target.dir,
474
+ port,
475
+ lane,
476
+ theme,
477
+ log,
478
+ command: runDev(files, devArgs(target, port, address)),
479
+ env: {
480
+ PORT: String(port),
481
+ HUD_LANE_ROOT: dir.path,
482
+ ...name ? {
483
+ HUD_PREVIEW_HOST: name,
484
+ __VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS: name
485
+ } : {}
486
+ }
487
+ });
488
+ if (result.status === "held") continue;
489
+ if (result.status === "failed") return {
490
+ ok: false,
491
+ error: result.error
492
+ };
493
+ return {
494
+ ok: true,
495
+ lane,
496
+ port,
497
+ url: `http://${name ?? address}:${port}/`,
498
+ log
499
+ };
500
+ }
501
+ return {
502
+ ok: false,
503
+ error: `no free port in ${low}-${high}`
504
+ };
505
+ }
506
+ /** One ledger event, written as the skills ledger writes it; its id is the session-mirror's. */
507
+ async function appendEvent(entry) {
508
+ const n = await node();
509
+ const line = JSON.stringify(entry);
510
+ const file = `${await sessionsDir()}/events.jsonl`;
511
+ await n.fsp.mkdir(n.path.dirname(file), { recursive: true });
512
+ await n.fsp.appendFile(file, `${line}\n`);
513
+ return n.crypto.createHash("sha256").update(line).digest("hex").slice(0, 32);
514
+ }
515
+ async function deliver(lane, kind, m, extra = {}) {
516
+ const notes = [...extra.notes ?? []];
517
+ const dir = await findLane(lane);
518
+ if (!dir) return {
519
+ ok: false,
520
+ delivered: false,
521
+ notes,
522
+ error: `lane ${lane} not found on this box`
523
+ };
524
+ const worker = pickWorker(await ledger(), lane);
525
+ const line = messageLine(kind, m, extra.file);
526
+ const result = {
527
+ ok: false,
528
+ delivered: false,
529
+ notes
530
+ };
531
+ if (extra.file) result.file = extra.file;
532
+ if (extra.prComment) result.prComment = extra.prComment;
533
+ if (worker) {
534
+ const n = await node();
535
+ const id = await appendEvent({
536
+ ts: now().toISOString().replace(/\.\d{3}Z$/, "Z"),
537
+ event: kind === "comment" ? "hud-comment" : "hud-screenshot",
538
+ sid: worker.sid,
539
+ box: n.os.hostname().replace(/\.local$/, ""),
540
+ theme: worker.theme ?? null,
541
+ from: "hud",
542
+ lane,
543
+ text: m.text,
544
+ ...m.url ? { url: m.url } : {},
545
+ ...m.viewport ? { viewport: m.viewport } : {},
546
+ ...extra.file ? { file: extra.file } : {},
547
+ ...extra.prComment ? { pr_comment: extra.prComment } : {}
548
+ });
549
+ result.ref = `ledger:${worker.sid}:${id}`;
550
+ } else notes.push("no open session in this lane's ledger; nothing recorded");
551
+ const handle = await terminal(dir.path);
552
+ if (handle) {
553
+ const sent = await exec("lane-runtime", [
554
+ "terminal",
555
+ "send",
556
+ "--terminal",
557
+ handle,
558
+ "--text",
559
+ line
560
+ ]);
561
+ result.delivered = sent.code === 0;
562
+ if (!result.delivered) notes.push(`terminal send failed: ${sent.stderr.slice(0, 200)}`);
563
+ } else notes.push("no lane terminal to type into (not a laned session); the worker reads it from the ledger");
564
+ result.ok = result.delivered || result.ref !== void 0;
565
+ if (!result.ok) result.error = "nobody to deliver to: no worker and no terminal in this lane";
566
+ return result;
567
+ }
568
+ /** Push the PNG as a one-file commit on the shots branch and comment it on the lane's PR. */
569
+ async function postToPr(path, file, name, m) {
570
+ const branch = options.shotsBranch ?? "hud-shots";
571
+ const pr = await exec("gh", [
572
+ "pr",
573
+ "view",
574
+ "--json",
575
+ "number,url"
576
+ ], { cwd: path });
577
+ if (pr.code !== 0) throw new Error("no open PR for this lane");
578
+ const { number, url } = JSON.parse(pr.stdout);
579
+ const repoUrl = url.replace(/\/pull\/\d+$/, "");
580
+ const git = (args, timeoutMs = 15e3) => exec("git", [
581
+ "-C",
582
+ path,
583
+ ...args
584
+ ], { timeoutMs });
585
+ const blob = await git([
586
+ "hash-object",
587
+ "-w",
588
+ file
589
+ ]);
590
+ if (blob.code !== 0) throw new Error(`git hash-object: ${blob.stderr.trim()}`);
591
+ const tree = await exec("sh", [
592
+ "-c",
593
+ "printf \"100644 blob %s\\t%s\\n\" \"$1\" \"$2\" | git -C \"$3\" mktree",
594
+ "sh",
595
+ blob.stdout.trim(),
596
+ name,
597
+ path
598
+ ]);
599
+ if (tree.code !== 0) throw new Error(`git mktree: ${tree.stderr.trim()}`);
600
+ let commit = "";
601
+ for (let attempt = 0; attempt < 2; attempt++) {
602
+ const parent = (await git([
603
+ "fetch",
604
+ "--no-tags",
605
+ "--depth=1",
606
+ "origin",
607
+ branch
608
+ ], 3e4)).code === 0 ? ["-p", "FETCH_HEAD"] : [];
609
+ const made = await git([
610
+ "commit-tree",
611
+ tree.stdout.trim(),
612
+ ...parent,
613
+ "-m",
614
+ `hud screenshot ${name}`
615
+ ]);
616
+ if (made.code !== 0) throw new Error(`git commit-tree: ${made.stderr.trim()}`);
617
+ commit = made.stdout.trim();
618
+ const pushed = await git([
619
+ "push",
620
+ "origin",
621
+ `${commit}:refs/heads/${branch}`
622
+ ], 3e4);
623
+ if (pushed.code === 0) break;
624
+ if (attempt === 1) throw new Error(`git push: ${pushed.stderr.trim().slice(0, 200)}`);
625
+ }
626
+ const image = `${repoUrl}/blob/${commit}/${name}?raw=true`;
627
+ const body = [
628
+ `**HUD screenshot**${m.viewport ? ` at ${m.viewport.width}×${m.viewport.height}` : ""}${m.url ? ` of \`${new URL(m.url).pathname}\`` : ""}`,
629
+ ...m.text.trim() ? ["", m.text.trim()] : [],
630
+ "",
631
+ `![screenshot](${image})`
632
+ ].join("\n");
633
+ const posted = await exec("gh", [
634
+ "pr",
635
+ "comment",
636
+ String(number),
637
+ "--body",
638
+ body
639
+ ], { cwd: path });
640
+ if (posted.code !== 0) throw new Error(`gh pr comment: ${posted.stderr.trim().slice(0, 200)}`);
641
+ return posted.stdout.trim().split("\n").pop() ?? url;
642
+ }
643
+ async function shot(lane, png, m) {
644
+ const dir = await findLane(lane);
645
+ if (!dir) return {
646
+ ok: false,
647
+ delivered: false,
648
+ notes: [],
649
+ error: `lane ${lane} not found on this box`
650
+ };
651
+ const n = await node();
652
+ const name = `${lane}-${now().toISOString().replace(/[:.]/g, "-")}-${m.viewport?.width ?? 0}w.png`;
653
+ const shots = n.path.join(await stateDir(), "shots");
654
+ await n.fsp.mkdir(shots, { recursive: true });
655
+ const file = n.path.join(shots, name);
656
+ await n.fsp.writeFile(file, png);
657
+ const notes = [];
658
+ let prComment;
659
+ try {
660
+ prComment = await postToPr(dir.path, file, name, m);
661
+ } catch (error) {
662
+ notes.push(`not posted to the PR: ${error instanceof Error ? error.message : String(error)}`);
663
+ }
664
+ return deliver(lane, "screenshot", m, {
665
+ file,
666
+ notes,
667
+ ...prComment ? { prComment } : {}
668
+ });
669
+ }
670
+ return {
671
+ host,
672
+ lanes,
673
+ start,
674
+ message: (lane, m) => deliver(lane, "comment", m),
675
+ shot
676
+ };
677
+ }
678
+ //#endregion
679
+ //#region src/plugins/lanes/server.ts
680
+ const NO_STORE = { "cache-control": "no-store" };
681
+ const TEXT_MAX = 4e3;
682
+ function isRecord(value) {
683
+ return typeof value === "object" && value !== null && !Array.isArray(value);
684
+ }
685
+ function message(error) {
686
+ return error instanceof Error ? error.message : String(error);
687
+ }
688
+ function viewportOf(value) {
689
+ if (!isRecord(value)) return void 0;
690
+ const { width, height } = value;
691
+ if (typeof width !== "number" || typeof height !== "number") return void 0;
692
+ if (!(width >= 200 && width <= 4e3 && height >= 200 && height <= 4e3)) return void 0;
693
+ return {
694
+ width: Math.round(width),
695
+ height: Math.round(height)
696
+ };
697
+ }
698
+ function laneOf(value) {
699
+ return typeof value.lane === "string" && /^[\w.-]{1,200}$/.test(value.lane) ? value.lane : void 0;
700
+ }
701
+ function parseComment(value) {
702
+ if (!isRecord(value)) return null;
703
+ const lane = laneOf(value);
704
+ const text = typeof value.text === "string" ? value.text.trim() : "";
705
+ if (!lane || !text || text.length > TEXT_MAX) return null;
706
+ const body = {
707
+ lane,
708
+ text
709
+ };
710
+ if (typeof value.url === "string") body.url = value.url;
711
+ const viewport = viewportOf(value.viewport);
712
+ if (viewport) body.viewport = viewport;
713
+ return body;
714
+ }
715
+ function parseShot(value) {
716
+ if (!isRecord(value)) return null;
717
+ const lane = laneOf(value);
718
+ const viewport = viewportOf(value.viewport);
719
+ const text = typeof value.text === "string" ? value.text.trim() : "";
720
+ if (!lane || !viewport || typeof value.url !== "string" || text.length > TEXT_MAX) return null;
721
+ return {
722
+ lane,
723
+ url: value.url,
724
+ viewport,
725
+ ...text ? { text } : {}
726
+ };
727
+ }
728
+ function fromBase64(base64) {
729
+ if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(base64, "base64"));
730
+ return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
731
+ }
732
+ const failed = (status, error) => Response.json({
733
+ ok: false,
734
+ delivered: false,
735
+ notes: [],
736
+ error
737
+ }, {
738
+ status,
739
+ headers: NO_STORE
740
+ });
741
+ /**
742
+ * Server half of `lanes`: `GET /lanes` lists the box's lanes with their dev
743
+ * servers and workers, `POST /start` starts a lane's dev script on a leased
744
+ * port, `POST /comment` hands the worker a message over the ledger, and
745
+ * `POST /screenshot` renders the page at the viewer's width, posts it to the
746
+ * lane's PR and hands it to the worker. Everything is this machine's: mount it
747
+ * only on a dev server that runs on the box the lanes live on.
748
+ */
749
+ function lanes({ box = nodeBox(), capture } = {}) {
750
+ const render = screenshot(capture).routes["/screenshot"]?.POST;
751
+ return definePlugin({
752
+ id: LANES_ID,
753
+ capability: LANES_CAPABILITY,
754
+ routes: {
755
+ "/lanes": { GET: async () => {
756
+ const [host, list] = await Promise.all([box.host(), box.lanes()]);
757
+ return Response.json({
758
+ host,
759
+ lanes: list
760
+ }, { headers: NO_STORE });
761
+ } },
762
+ "/start": { POST: async (request) => {
763
+ const refusal = refuseCrossSite(request);
764
+ if (refusal) return refusal;
765
+ const raw = await request.json().catch(() => null);
766
+ const lane = isRecord(raw) ? laneOf(raw) : void 0;
767
+ if (!lane) return Response.json({
768
+ ok: false,
769
+ error: "invalid start"
770
+ }, { status: 400 });
771
+ try {
772
+ const result = await box.start(lane);
773
+ return Response.json(result, {
774
+ status: result.ok ? 200 : 409,
775
+ headers: NO_STORE
776
+ });
777
+ } catch (error) {
778
+ return Response.json({
779
+ ok: false,
780
+ error: message(error)
781
+ }, { status: 502 });
782
+ }
783
+ } },
784
+ "/comment": { POST: async (request) => {
785
+ const refusal = refuseCrossSite(request);
786
+ if (refusal) return refusal;
787
+ const body = parseComment(await request.json().catch(() => null));
788
+ if (!body) return failed(400, "invalid comment");
789
+ try {
790
+ const { lane, ...m } = body;
791
+ const result = await box.message(lane, m);
792
+ return Response.json(result, {
793
+ status: result.ok ? 200 : 409,
794
+ headers: NO_STORE
795
+ });
796
+ } catch (error) {
797
+ return failed(502, message(error));
798
+ }
799
+ } },
800
+ "/screenshot": { POST: async (request) => {
801
+ const refusal = refuseCrossSite(request);
802
+ if (refusal) return refusal;
803
+ const body = parseShot(await request.json().catch(() => null));
804
+ if (!body) return failed(400, "invalid screenshot request");
805
+ if (!sameOriginUrl(body.url, request)) return failed(400, "url must be same-origin");
806
+ if (!render) return failed(500, "no screenshot route");
807
+ const headers = new Headers(request.headers);
808
+ headers.set("content-type", "application/json");
809
+ const rendered = await render(new Request(request.url, {
810
+ method: "POST",
811
+ headers,
812
+ body: JSON.stringify({
813
+ url: body.url,
814
+ viewport: body.viewport
815
+ })
816
+ }));
817
+ const image = await rendered.json();
818
+ if (!image.ok) return Response.json({
819
+ ok: false,
820
+ delivered: false,
821
+ notes: image.hint ? [image.hint] : [],
822
+ error: image.error
823
+ }, {
824
+ status: rendered.status,
825
+ headers: NO_STORE
826
+ });
827
+ try {
828
+ const result = await box.shot(body.lane, fromBase64(image.base64), {
829
+ text: body.text ?? "",
830
+ url: body.url,
831
+ viewport: body.viewport
832
+ });
833
+ return Response.json(result, {
834
+ status: result.ok ? 200 : 409,
835
+ headers: NO_STORE
836
+ });
837
+ } catch (error) {
838
+ return failed(502, message(error));
839
+ }
840
+ } }
841
+ }
842
+ });
843
+ }
844
+ //#endregion
845
+ export { delegatedDir, devArgs, firstHandle, lanes, messageLine, nodeBox, parseCwds, parseLaneName, parseListeners, pickWorker, runDev };