@phren/cli 0.3.71 → 0.3.72

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 (107) hide show
  1. package/dist/bridge/browser-env.d.ts +5 -0
  2. package/dist/bridge/browser-env.js +86 -0
  3. package/dist/bridge/browser-protocol.d.ts +120 -0
  4. package/dist/bridge/browser-protocol.js +70 -0
  5. package/dist/bridge/browser-recordings.d.ts +63 -0
  6. package/dist/bridge/browser-recordings.js +148 -0
  7. package/dist/bridge/browser-registry.d.ts +64 -0
  8. package/dist/bridge/browser-registry.js +262 -0
  9. package/dist/bridge/browser-routes.d.ts +4 -0
  10. package/dist/bridge/browser-routes.js +39 -0
  11. package/dist/bridge/browser-shim/phren-playwright.cjs +184 -0
  12. package/dist/bridge/browser-socket.d.ts +2 -0
  13. package/dist/bridge/browser-socket.js +10 -0
  14. package/dist/bridge/browser-stream.d.ts +3 -0
  15. package/dist/bridge/browser-stream.js +129 -0
  16. package/dist/bridge/dispatch.d.ts +10 -0
  17. package/dist/bridge/dispatch.js +3 -1
  18. package/dist/bridge/dream-schedule.d.ts +133 -0
  19. package/dist/bridge/dream-schedule.js +322 -0
  20. package/dist/bridge/herdr.js +15 -6
  21. package/dist/bridge/install.js +4 -0
  22. package/dist/bridge/launch-brief.d.ts +11 -0
  23. package/dist/bridge/launch-brief.js +22 -0
  24. package/dist/bridge/pane-status.js +1 -1
  25. package/dist/bridge/server-routes.d.ts +3 -0
  26. package/dist/bridge/server-routes.js +15 -15
  27. package/dist/bridge/server-stream.d.ts +4 -0
  28. package/dist/bridge/server-stream.js +24 -5
  29. package/dist/bridge/server.js +23 -3
  30. package/dist/bridge/session-move.d.ts +10 -4
  31. package/dist/bridge/session-move.js +65 -34
  32. package/dist/bridge/simulator-stream.d.ts +2 -0
  33. package/dist/bridge/simulator-stream.js +2 -0
  34. package/dist/bridge/tab-activity.d.ts +2 -0
  35. package/dist/bridge/tab-activity.js +15 -2
  36. package/dist/bridge/task-routes.d.ts +20 -16
  37. package/dist/bridge/task-routes.js +1 -1
  38. package/dist/bridge/terminal-herdr.js +2 -1
  39. package/dist/bridge/terminal-tmux.js +2 -1
  40. package/dist/bridge/worker-reports.js +15 -3
  41. package/dist/bridge-hook.mjs +36800 -35213
  42. package/dist/capabilities/mcp.js +1 -1
  43. package/dist/cli/config-dreaming.d.ts +7 -0
  44. package/dist/cli/config-dreaming.js +72 -0
  45. package/dist/cli/config.js +6 -0
  46. package/dist/cli/dream.d.ts +59 -0
  47. package/dist/cli/dream.js +315 -0
  48. package/dist/cli/namespaces-tasks.js +14 -0
  49. package/dist/cli-registry.js +24 -1
  50. package/dist/config/dreaming.d.ts +82 -0
  51. package/dist/config/dreaming.js +195 -0
  52. package/dist/config/resolve.js +11 -0
  53. package/dist/config/schema.d.ts +4 -4
  54. package/dist/config/schema.js +157 -1
  55. package/dist/content/citation-freshness.js +6 -0
  56. package/dist/content/learning.d.ts +1 -0
  57. package/dist/content/learning.js +2 -0
  58. package/dist/data/access.d.ts +1 -1
  59. package/dist/data/access.js +3 -1
  60. package/dist/data/task-contract.d.ts +5 -4
  61. package/dist/data/tasks.d.ts +5 -0
  62. package/dist/data/tasks.js +28 -2
  63. package/dist/dream/apply.d.ts +69 -0
  64. package/dist/dream/apply.js +372 -0
  65. package/dist/dream/budget.d.ts +78 -0
  66. package/dist/dream/budget.js +180 -0
  67. package/dist/dream/collect.d.ts +86 -0
  68. package/dist/dream/collect.js +449 -0
  69. package/dist/dream/eval/dream-adapter.d.ts +16 -0
  70. package/dist/dream/eval/dream-adapter.js +21 -0
  71. package/dist/dream/eval/fixture.d.ts +53 -0
  72. package/dist/dream/eval/fixture.js +172 -0
  73. package/dist/dream/eval/index.d.ts +40 -0
  74. package/dist/dream/eval/index.js +78 -0
  75. package/dist/dream/eval/score.d.ts +34 -0
  76. package/dist/dream/eval/score.js +99 -0
  77. package/dist/dream/eval/scripted-model.d.ts +19 -0
  78. package/dist/dream/eval/scripted-model.js +70 -0
  79. package/dist/dream/pages.d.ts +68 -0
  80. package/dist/dream/pages.js +220 -0
  81. package/dist/dream/privacy.d.ts +3 -0
  82. package/dist/dream/privacy.js +18 -0
  83. package/dist/dream/prompt.d.ts +13 -0
  84. package/dist/dream/prompt.js +84 -0
  85. package/dist/dream/run.d.ts +98 -0
  86. package/dist/dream/run.js +317 -0
  87. package/dist/dream/types.d.ts +74 -0
  88. package/dist/dream/types.js +4 -0
  89. package/dist/finding/lifecycle.d.ts +2 -2
  90. package/dist/finding/lifecycle.js +5 -2
  91. package/dist/finding/versions.d.ts +4 -0
  92. package/dist/finding/versions.js +28 -0
  93. package/dist/index.js +1 -0
  94. package/dist/modules/registry.js +9 -7
  95. package/dist/project-config.d.ts +3 -0
  96. package/dist/task/merge-links.d.ts +38 -0
  97. package/dist/task/merge-links.js +45 -0
  98. package/dist/task/reconcile.d.ts +39 -0
  99. package/dist/task/reconcile.js +201 -0
  100. package/dist/task/report-links.d.ts +10 -0
  101. package/dist/task/report-links.js +47 -0
  102. package/dist/tools/config.js +46 -4
  103. package/dist/tools/dispatch.js +2 -1
  104. package/dist/tools/dream.d.ts +3 -0
  105. package/dist/tools/dream.js +123 -0
  106. package/dist/tools/tasks.js +4 -1
  107. package/package.json +1 -1
@@ -0,0 +1,5 @@
1
+ export declare function browserShimPath(): string;
2
+ export declare function browserEnv(session: string, existing?: string): Record<string, string>;
3
+ export declare function printBrowserEnv(session?: string): void;
4
+ /** Ask sockets are independent of producer sockets; closing one cancels its help request. */
5
+ export declare function runBrowser(args: string[]): Promise<number>;
@@ -0,0 +1,86 @@
1
+ import { existsSync, realpathSync } from "node:fs";
2
+ import { fileURLToPath } from "node:url";
3
+ import path from "node:path";
4
+ import { connect } from "node:net";
5
+ import { BROWSER_ID, BrowserMessageReader, browserWire } from "./browser-protocol.js";
6
+ import { browserSocketPath } from "./browser-socket.js";
7
+ import { bridgeRoot } from "./protocol.js";
8
+ export function browserShimPath() {
9
+ // Normal tsc modules and the standalone bridge-hook.mjs bundle.
10
+ const local = fileURLToPath(new URL("./browser-shim/phren-playwright.cjs", import.meta.url));
11
+ return existsSync(local) ? local : fileURLToPath(new URL("./bridge/browser-shim/phren-playwright.cjs", import.meta.url));
12
+ }
13
+ export function browserEnv(session, existing = process.env.NODE_OPTIONS ?? "") {
14
+ const installed = path.join(bridgeRoot(), "current/bridge/browser-shim/phren-playwright.cjs");
15
+ const shim = realpathSync(existsSync(installed) ? installed : browserShimPath());
16
+ const requireOption = `--require=${JSON.stringify(shim)}`;
17
+ return { NODE_OPTIONS: `${existing}${existing ? " " : ""}${requireOption}`, PHREN_BROWSER_SOCKET: browserSocketPath(), PHREN_BROWSER_SESSION: session };
18
+ }
19
+ export function printBrowserEnv(session = process.env.PHREN_BROWSER_SESSION ?? process.env.HERDR_PANE_ID ?? process.env.TMUX_PANE ?? "shell") {
20
+ for (const [key, value] of Object.entries(browserEnv(session)))
21
+ console.log(`export ${key}='${value.replace(/'/g, "'\\''")}'`);
22
+ }
23
+ /** Ask sockets are independent of producer sockets; closing one cancels its help request. */
24
+ export async function runBrowser(args) {
25
+ if (args.length === 1 && args[0] === "env") {
26
+ printBrowserEnv();
27
+ return 0;
28
+ }
29
+ const usage = 'Usage: phren browser env | phren browser ask "<reason>" [--browser <id>] [--timeout <seconds, default 900>]';
30
+ if (args.length === 0 || args.includes("--help")) {
31
+ console.log(usage);
32
+ return 0;
33
+ }
34
+ let browserId, timeout = 900;
35
+ const reason = args[1];
36
+ if (args[0] !== "ask" || !reason?.trim() || reason.length > 16_384) {
37
+ console.error(usage);
38
+ return 1;
39
+ }
40
+ for (let i = 2; i < args.length; i += 2) {
41
+ const value = args[i + 1];
42
+ if (!value) {
43
+ console.error(usage);
44
+ return 1;
45
+ }
46
+ if (args[i] === "--browser" && BROWSER_ID.test(value))
47
+ browserId = value;
48
+ else if (args[i] === "--timeout" && Number.isFinite(Number(value)) && Number(value) > 0 && Number(value) <= 2_147_483)
49
+ timeout = Number(value);
50
+ else {
51
+ console.error(usage);
52
+ return 1;
53
+ }
54
+ }
55
+ return new Promise(resolve => {
56
+ const socket = connect(process.env.PHREN_BROWSER_SOCKET || browserSocketPath());
57
+ const reader = new BrowserMessageReader();
58
+ let finished = false;
59
+ const finish = (outcome) => {
60
+ if (finished)
61
+ return;
62
+ finished = true;
63
+ clearTimeout(timer);
64
+ process.off("SIGINT", interrupt);
65
+ socket.destroy();
66
+ console.log(`Browser help: ${outcome}`);
67
+ resolve(outcome === "done" ? 0 : 1);
68
+ };
69
+ const interrupt = () => finish("cancelled");
70
+ const timer = setTimeout(() => finish("timeout"), timeout * 1000 + 1000);
71
+ process.once("SIGINT", interrupt);
72
+ socket.on("connect", () => socket.write(browserWire(0x05, { browserId, session: process.env.PHREN_BROWSER_SESSION, reason, timeout })));
73
+ socket.on("data", (chunk) => {
74
+ try {
75
+ for (const message of reader.push(chunk))
76
+ if (message.type === 0x13)
77
+ finish(message.data.outcome);
78
+ }
79
+ catch {
80
+ finish("connection-error");
81
+ }
82
+ });
83
+ socket.on("error", () => finish("connection-error"));
84
+ socket.on("close", () => finish("connection-closed"));
85
+ });
86
+ }
@@ -0,0 +1,120 @@
1
+ import { z } from "zod";
2
+ export declare const BROWSER_ID: RegExp;
3
+ declare const schemas: {
4
+ 1: z.ZodObject<{
5
+ browserId: z.ZodString;
6
+ v: z.ZodLiteral<1>;
7
+ pid: z.ZodNumber;
8
+ session: z.ZodString;
9
+ cwd: z.ZodString;
10
+ engine: z.ZodLiteral<"chromium">;
11
+ headless: z.ZodBoolean;
12
+ playwright: z.ZodString;
13
+ }, z.core.$strip>;
14
+ 2: z.ZodObject<{
15
+ browserId: z.ZodString;
16
+ pageId: z.ZodString;
17
+ url: z.ZodString;
18
+ title: z.ZodString;
19
+ width: z.ZodNumber;
20
+ height: z.ZodNumber;
21
+ }, z.core.$strip>;
22
+ 3: z.ZodObject<{
23
+ browserId: z.ZodString;
24
+ pageId: z.ZodString;
25
+ t: z.ZodNumber;
26
+ width: z.ZodNumber;
27
+ height: z.ZodNumber;
28
+ }, z.core.$strip>;
29
+ 4: z.ZodObject<{
30
+ browserId: z.ZodString;
31
+ pageId: z.ZodOptional<z.ZodString>;
32
+ }, z.core.$strip>;
33
+ 5: z.ZodObject<{
34
+ browserId: z.ZodOptional<z.ZodString>;
35
+ session: z.ZodOptional<z.ZodString>;
36
+ reason: z.ZodString;
37
+ timeout: z.ZodOptional<z.ZodNumber>;
38
+ }, z.core.$strip>;
39
+ 16: z.ZodIntersection<z.ZodObject<{
40
+ browserId: z.ZodString;
41
+ pageId: z.ZodString;
42
+ }, z.core.$strip>, z.ZodDiscriminatedUnion<[z.ZodObject<{
43
+ event: z.ZodLiteral<"click">;
44
+ x: z.ZodNumber;
45
+ y: z.ZodNumber;
46
+ }, z.core.$strip>, z.ZodObject<{
47
+ event: z.ZodLiteral<"wheel">;
48
+ x: z.ZodNumber;
49
+ y: z.ZodNumber;
50
+ dx: z.ZodNumber;
51
+ dy: z.ZodNumber;
52
+ }, z.core.$strip>, z.ZodObject<{
53
+ event: z.ZodLiteral<"text">;
54
+ text: z.ZodString;
55
+ }, z.core.$strip>, z.ZodObject<{
56
+ event: z.ZodLiteral<"key">;
57
+ key: z.ZodEnum<{
58
+ ArrowDown: "ArrowDown";
59
+ ArrowLeft: "ArrowLeft";
60
+ ArrowRight: "ArrowRight";
61
+ ArrowUp: "ArrowUp";
62
+ Backspace: "Backspace";
63
+ Enter: "Enter";
64
+ Escape: "Escape";
65
+ Tab: "Tab";
66
+ }>;
67
+ }, z.core.$strip>], "event">>;
68
+ 18: z.ZodObject<{
69
+ browserId: z.ZodString;
70
+ }, z.core.$strip>;
71
+ 19: z.ZodObject<{
72
+ outcome: z.ZodEnum<{
73
+ done: "done";
74
+ ended: "ended";
75
+ "no-browser": "no-browser";
76
+ timeout: "timeout";
77
+ }>;
78
+ }, z.core.$strip>;
79
+ };
80
+ export type Hello = z.infer<typeof schemas[1]>;
81
+ export type PageInfo = z.infer<typeof schemas[2]>;
82
+ export type FrameInfo = z.infer<typeof schemas[3]>;
83
+ export type Ask = z.infer<typeof schemas[5]>;
84
+ export type BrowserInput = z.infer<typeof schemas[16]>;
85
+ export type BrowserOutcome = z.infer<typeof schemas[19]>["outcome"];
86
+ export type ProducerMessage = {
87
+ type: 1;
88
+ data: Hello;
89
+ } | {
90
+ type: 2;
91
+ data: PageInfo;
92
+ } | {
93
+ type: 3;
94
+ data: FrameInfo;
95
+ jpeg: Buffer;
96
+ } | {
97
+ type: 4;
98
+ data: z.infer<typeof schemas[4]>;
99
+ };
100
+ export type BrowserMessage = ProducerMessage | {
101
+ type: 5;
102
+ data: Ask;
103
+ } | {
104
+ type: 16;
105
+ data: BrowserInput;
106
+ } | {
107
+ type: 18;
108
+ data: z.infer<typeof schemas[18]>;
109
+ } | {
110
+ type: 19;
111
+ data: z.infer<typeof schemas[19]>;
112
+ };
113
+ export declare function browserWire(type: number, data: unknown): Buffer;
114
+ export declare const MAX_BROWSER_MESSAGE: number;
115
+ /** Incremental framing; reject lengths before allocating the claimed body. */
116
+ export declare class BrowserMessageReader {
117
+ private buffer;
118
+ push(chunk: Buffer): BrowserMessage[];
119
+ }
120
+ export {};
@@ -0,0 +1,70 @@
1
+ import { z } from "zod";
2
+ export const BROWSER_ID = /^[A-Za-z0-9_-]{8,64}$/;
3
+ const id = z.string().regex(BROWSER_ID);
4
+ const text = z.string().max(16_384);
5
+ const size = z.number().int().min(0).max(32_768);
6
+ const base = { browserId: id };
7
+ const schemas = {
8
+ 1: z.object({ ...base, v: z.literal(1), pid: z.number().int().positive(), session: text, cwd: text, engine: z.literal("chromium"), headless: z.boolean(), playwright: text }),
9
+ 2: z.object({ ...base, pageId: id, url: text, title: text, width: size, height: size }),
10
+ 3: z.object({ ...base, pageId: id, t: z.number().finite().nonnegative(), width: size, height: size }),
11
+ 4: z.object({ ...base, pageId: id.optional() }),
12
+ // Optional timeout carries the CLI deadline; older ask clients use 900 seconds.
13
+ 5: z.object({ browserId: id.optional(), session: text.optional(), reason: z.string().min(1).max(16_384), timeout: z.number().positive().max(2_147_483).optional() }),
14
+ 16: z.object({ ...base, pageId: id }).and(z.discriminatedUnion("event", [
15
+ z.object({ event: z.literal("click"), x: z.number().finite(), y: z.number().finite() }),
16
+ z.object({ event: z.literal("wheel"), x: z.number().finite(), y: z.number().finite(), dx: z.number().finite(), dy: z.number().finite() }),
17
+ z.object({ event: z.literal("text"), text: z.string().max(1000) }),
18
+ z.object({ event: z.literal("key"), key: z.enum(["Enter", "Backspace", "Tab", "Escape", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"]) }),
19
+ ])),
20
+ 18: z.object({ browserId: id }),
21
+ 19: z.object({ outcome: z.enum(["no-browser", "done", "ended", "timeout"]) }),
22
+ };
23
+ export function browserWire(type, data) {
24
+ const body = Buffer.from(JSON.stringify(data)), head = Buffer.alloc(5);
25
+ head.writeUInt32BE(body.length + 1);
26
+ head[4] = type;
27
+ return Buffer.concat([head, body]);
28
+ }
29
+ export const MAX_BROWSER_MESSAGE = 4 * 1024 * 1024;
30
+ /** Incremental framing; reject lengths before allocating the claimed body. */
31
+ export class BrowserMessageReader {
32
+ buffer = Buffer.alloc(0);
33
+ push(chunk) {
34
+ const messages = [];
35
+ // Consume in bounded slices even if a sender coalesces many messages.
36
+ while (chunk.length) {
37
+ const needed = this.buffer.length < 4 ? 4 : 4 + this.buffer.readUInt32BE(0);
38
+ const take = Math.min(chunk.length, needed - this.buffer.length);
39
+ this.buffer = Buffer.concat([this.buffer, chunk.subarray(0, take)]);
40
+ chunk = chunk.subarray(take);
41
+ if (this.buffer.length < 4)
42
+ continue;
43
+ const length = this.buffer.readUInt32BE(0);
44
+ if (length < 2 || length > MAX_BROWSER_MESSAGE)
45
+ throw new Error("Invalid browser message length");
46
+ if (this.buffer.length < length + 4)
47
+ continue;
48
+ const body = this.buffer.subarray(4), type = body[0];
49
+ if (type === 3) {
50
+ if (body.length < 6)
51
+ throw new Error("Invalid browser frame");
52
+ const j = body.readUInt32BE(1);
53
+ if (!j || j > body.length - 6)
54
+ throw new Error("Invalid browser frame header");
55
+ const data = schemas[3].parse(JSON.parse(body.subarray(5, 5 + j).toString("utf8")));
56
+ const jpeg = body.subarray(5 + j);
57
+ if (jpeg.length < 4 || jpeg[0] !== 0xff || jpeg[1] !== 0xd8 || jpeg.at(-2) !== 0xff || jpeg.at(-1) !== 0xd9)
58
+ throw new Error("Invalid JPEG");
59
+ messages.push({ type, data, jpeg });
60
+ }
61
+ else if (type === 1 || type === 2 || type === 4 || type === 5 || type === 16 || type === 18 || type === 19) {
62
+ messages.push({ type, data: schemas[type].parse(JSON.parse(body.subarray(1).toString("utf8"))) });
63
+ }
64
+ else
65
+ throw new Error("Unknown browser message");
66
+ this.buffer = Buffer.alloc(0);
67
+ }
68
+ return messages;
69
+ }
70
+ }
@@ -0,0 +1,63 @@
1
+ import { type Hello, type PageInfo, type FrameInfo } from "./browser-protocol.js";
2
+ export interface BrowserHandoff {
3
+ t: number;
4
+ kind: "take" | "release" | "help";
5
+ reason?: string;
6
+ }
7
+ export interface RecordingMeta {
8
+ id: string;
9
+ browserId: string;
10
+ session: string;
11
+ cwd: string;
12
+ engine: string;
13
+ headless: boolean;
14
+ startedAt: number;
15
+ endedAt: number | null;
16
+ frames: number;
17
+ bytes: number;
18
+ pages: {
19
+ pageId: string;
20
+ url: string;
21
+ title: string;
22
+ t: number;
23
+ }[];
24
+ handoffs: BrowserHandoff[];
25
+ navigations: {
26
+ t: number;
27
+ pageId: string;
28
+ url: string;
29
+ title: string;
30
+ }[];
31
+ }
32
+ interface IndexFrame {
33
+ t: number;
34
+ pageId: string;
35
+ offset: number;
36
+ length: number;
37
+ width: number;
38
+ height: number;
39
+ }
40
+ export declare function browserId(value: string | null): string;
41
+ export declare class BrowserRecordings {
42
+ readonly root: string;
43
+ private active;
44
+ constructor(root: string);
45
+ private dir;
46
+ private save;
47
+ start(hello: Hello, now?: number): void;
48
+ page(page: PageInfo, now?: number): void;
49
+ frame(info: FrameInfo, jpeg: Buffer): void;
50
+ handoff(id: string, kind: BrowserHandoff["kind"], reason?: string): void;
51
+ end(id: string, now?: number): void;
52
+ list(): RecordingMeta[];
53
+ index(id: string): {
54
+ meta: RecordingMeta;
55
+ frames: IndexFrame[];
56
+ };
57
+ frameAt(id: string, n: number): Buffer;
58
+ remove(id: string): void;
59
+ /** Recover archives left open by a Hook crash before accepting new producers. */
60
+ recover(now?: number): void;
61
+ retain(now?: number, budget?: number): void;
62
+ }
63
+ export {};
@@ -0,0 +1,148 @@
1
+ import * as fs from "node:fs";
2
+ import path from "node:path";
3
+ import { BridgeError } from "./protocol.js";
4
+ import { BROWSER_ID } from "./browser-protocol.js";
5
+ export function browserId(value) {
6
+ if (!value || !BROWSER_ID.test(value))
7
+ throw new BridgeError(400, "Invalid browser identifier.");
8
+ return value;
9
+ }
10
+ export class BrowserRecordings {
11
+ root;
12
+ active = new Map();
13
+ constructor(root) {
14
+ this.root = root;
15
+ fs.mkdirSync(root, { recursive: true, mode: 0o700 });
16
+ }
17
+ dir(id) { return path.join(this.root, browserId(id)); }
18
+ save(meta) {
19
+ const dir = this.dir(meta.id);
20
+ fs.writeFileSync(path.join(dir, "meta.tmp"), JSON.stringify(meta), { mode: 0o600 });
21
+ fs.renameSync(path.join(dir, "meta.tmp"), path.join(dir, "meta.json"));
22
+ }
23
+ start(hello, now = Date.now()) {
24
+ const dir = this.dir(hello.browserId);
25
+ fs.mkdirSync(dir, { mode: 0o700 }); // never overwrite an earlier recording
26
+ fs.writeFileSync(path.join(dir, "frames.bin"), "", { mode: 0o600 });
27
+ fs.writeFileSync(path.join(dir, "index.jsonl"), "", { mode: 0o600 });
28
+ const meta = { id: hello.browserId, browserId: hello.browserId, session: hello.session, cwd: hello.cwd, engine: hello.engine, headless: hello.headless, startedAt: now, endedAt: null, frames: 0, bytes: 0, pages: [], navigations: [], handoffs: [] };
29
+ this.save(meta);
30
+ this.active.set(meta.id, { meta, last: new Map() });
31
+ }
32
+ page(page, now = Date.now()) {
33
+ const state = this.active.get(page.browserId);
34
+ if (!state)
35
+ return;
36
+ const nav = { t: now, pageId: page.pageId, url: page.url, title: page.title };
37
+ const previous = state.meta.navigations.filter(n => n.pageId === page.pageId).at(-1);
38
+ if (previous?.url === page.url && previous.title === page.title)
39
+ return;
40
+ const existing = state.meta.pages.find(p => p.pageId === page.pageId);
41
+ // A copy: the page entry follows the latest navigation, the timeline keeps each one as it was.
42
+ if (existing)
43
+ Object.assign(existing, { url: nav.url, title: nav.title });
44
+ else
45
+ state.meta.pages.push({ ...nav });
46
+ // The shim announces a navigation before its title loads; the title then completes that entry.
47
+ if (previous?.url === page.url && !previous.title)
48
+ previous.title = page.title;
49
+ else
50
+ state.meta.navigations.push(nav);
51
+ this.save(state.meta);
52
+ }
53
+ frame(info, jpeg) {
54
+ const state = this.active.get(info.browserId);
55
+ if (!state)
56
+ return;
57
+ const last = state.last.get(info.pageId);
58
+ if (last && (info.t - last.t < 250 || jpeg.equals(last.jpeg)))
59
+ return;
60
+ // Bound an individual live recording too, so a long-running browser cannot fill disk between sweeps.
61
+ if (state.meta.bytes + jpeg.length > 1024 ** 3)
62
+ return;
63
+ const dir = this.dir(info.browserId);
64
+ const row = { t: info.t, pageId: info.pageId, offset: state.meta.bytes, length: jpeg.length, width: info.width, height: info.height };
65
+ fs.appendFileSync(path.join(dir, "frames.bin"), jpeg);
66
+ fs.appendFileSync(path.join(dir, "index.jsonl"), JSON.stringify(row) + "\n");
67
+ state.meta.bytes += jpeg.length;
68
+ state.meta.frames++;
69
+ state.last.set(info.pageId, { t: info.t, jpeg });
70
+ this.save(state.meta);
71
+ }
72
+ handoff(id, kind, reason) {
73
+ const state = this.active.get(id);
74
+ if (!state)
75
+ return;
76
+ state.meta.handoffs.push({ t: Date.now(), kind, ...(reason ? { reason } : {}) });
77
+ this.save(state.meta);
78
+ }
79
+ end(id, now = Date.now()) {
80
+ const state = this.active.get(id);
81
+ if (!state)
82
+ return;
83
+ state.meta.endedAt = now;
84
+ this.save(state.meta);
85
+ this.active.delete(id);
86
+ }
87
+ list() {
88
+ return fs.readdirSync(this.root).filter(id => BROWSER_ID.test(id)).flatMap(id => {
89
+ try {
90
+ return [JSON.parse(fs.readFileSync(path.join(this.dir(id), "meta.json"), "utf8"))];
91
+ }
92
+ catch {
93
+ return [];
94
+ }
95
+ }).sort((a, b) => b.startedAt - a.startedAt);
96
+ }
97
+ index(id) {
98
+ const dir = this.dir(id);
99
+ try {
100
+ return { meta: JSON.parse(fs.readFileSync(path.join(dir, "meta.json"), "utf8")), frames: fs.readFileSync(path.join(dir, "index.jsonl"), "utf8").split("\n").filter(Boolean).map(line => JSON.parse(line)) };
101
+ }
102
+ catch {
103
+ throw new BridgeError(404, "Recording not found.");
104
+ }
105
+ }
106
+ frameAt(id, n) {
107
+ const row = this.index(id).frames[n];
108
+ if (!row)
109
+ throw new BridgeError(404, "Frame not found.");
110
+ const fd = fs.openSync(path.join(this.dir(id), "frames.bin"), "r");
111
+ try {
112
+ const bytes = Buffer.alloc(row.length);
113
+ if (fs.readSync(fd, bytes, 0, bytes.length, row.offset) !== bytes.length)
114
+ throw new BridgeError(404, "Frame unavailable.");
115
+ return bytes;
116
+ }
117
+ finally {
118
+ fs.closeSync(fd);
119
+ }
120
+ }
121
+ remove(id) {
122
+ browserId(id);
123
+ if (this.active.has(id))
124
+ throw new BridgeError(409, "Browser is still recording.");
125
+ fs.rmSync(this.dir(id), { recursive: true, force: true });
126
+ }
127
+ /** Recover archives left open by a Hook crash before accepting new producers. */
128
+ recover(now = Date.now()) {
129
+ for (const meta of this.list())
130
+ if (meta.endedAt === null && !this.active.has(meta.id)) {
131
+ meta.endedAt = now;
132
+ this.save(meta);
133
+ }
134
+ }
135
+ retain(now = Date.now(), budget = 1024 ** 3) {
136
+ const all = this.list();
137
+ const sizes = new Map(all.map(m => [m.id, fs.readdirSync(this.dir(m.id)).reduce((n, file) => n + fs.statSync(path.join(this.dir(m.id), file)).size, 0)]));
138
+ let total = [...sizes.values()].reduce((a, b) => a + b, 0);
139
+ for (const meta of all.reverse()) {
140
+ if (now - meta.startedAt >= 86_400_000 || total > budget) {
141
+ // Retention includes live recordings. Capture continues live after its expired archive is removed.
142
+ this.active.delete(meta.id);
143
+ this.remove(meta.id);
144
+ total -= sizes.get(meta.id) ?? 0;
145
+ }
146
+ }
147
+ }
148
+ }
@@ -0,0 +1,64 @@
1
+ import { EventEmitter } from "node:events";
2
+ import { type ProducerMessage, type BrowserInput } from "./browser-protocol.js";
3
+ import { BrowserRecordings } from "./browser-recordings.js";
4
+ export interface BrowserPage {
5
+ id: string;
6
+ url: string;
7
+ title: string;
8
+ width: number;
9
+ height: number;
10
+ live: boolean;
11
+ }
12
+ export interface BrowserHelp {
13
+ reason: string;
14
+ t: number;
15
+ }
16
+ export interface BrowserSession {
17
+ id: string;
18
+ session: string;
19
+ cwd: string;
20
+ engine: string;
21
+ headless: boolean;
22
+ startedAt: number;
23
+ endedAt: number | null;
24
+ live: boolean;
25
+ pages: BrowserPage[];
26
+ control: {
27
+ held: boolean;
28
+ since: number | null;
29
+ };
30
+ help: BrowserHelp | null;
31
+ }
32
+ export declare class BrowserRegistry extends EventEmitter {
33
+ readonly root: string;
34
+ private browsers;
35
+ private owners;
36
+ private controls;
37
+ private asks;
38
+ private frames;
39
+ private server?;
40
+ private sockets;
41
+ private timer?;
42
+ readonly recordings: BrowserRecordings;
43
+ constructor(root: string);
44
+ list(now?: number): BrowserSession[];
45
+ get(id: string): BrowserSession | undefined;
46
+ last(browser: string, page: string): Buffer | undefined;
47
+ accept(owner: object, message: ProducerMessage): void;
48
+ controlState(id: string, connection: object): {
49
+ type: "control";
50
+ holder: "you" | "other" | null;
51
+ help: BrowserHelp | null;
52
+ };
53
+ take(id: string, holder: object): void;
54
+ release(id: string, holder: object, reason?: string): void;
55
+ input(id: string, holder: object, input: BrowserInput): boolean;
56
+ private handoff;
57
+ private controlChanged;
58
+ private finishAsk;
59
+ private ask;
60
+ disconnect(owner: object): void;
61
+ private end;
62
+ start(): Promise<void>;
63
+ close(): void;
64
+ }