@broberg/lens-daemon 0.1.76 → 0.1.78

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "@broberg/lens-daemon",
3
- "version": "0.1.76",
3
+ "version": "0.1.78",
4
4
  "description": "The Lens module of the cardmem daemon (flows, critic, coverage, capture sessions, the /lens/* routes and the cardmem-lens MCP) as a package. The daemon mounts createLensRouter(deps) + createLensMcpRouter(deps). Bun runtime.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "dependencies": {
8
8
  "@broberg/ai-sdk": "0.63.0",
9
+ "@broberg/media": "0.7.0",
9
10
  "@modelcontextprotocol/sdk": "^1.0.4",
10
11
  "@mozilla/readability": "^0.6.0",
11
12
  "hono": "^4.6.14",
@@ -15,9 +16,9 @@
15
16
  "sharp": "^0.35.5",
16
17
  "turndown": "^7.2.4",
17
18
  "zod": "^3.23.8",
18
- "@broberg/lens-svg": "0.1.1",
19
+ "@broberg/lens-engine": "0.14.1",
19
20
  "@broberg/lens-measure": "0.1.7",
20
- "@broberg/lens-engine": "0.14.1"
21
+ "@broberg/lens-svg": "0.1.1"
21
22
  },
22
23
  "devDependencies": {
23
24
  "@happy-dom/global-registrator": "^20.10.6",
@@ -104,7 +104,7 @@ async function walk(dir: string, out: string[]): Promise<void> {
104
104
  export async function backfillFromDisk(deps: LensDeps & { artifactRoot?: string }): Promise<BackfillResult> {
105
105
  const root = deps.artifactRoot ?? defaultRoot();
106
106
  if (deps.storage.backend !== 'local') {
107
- // Not a failure — tigris artifacts are already durable — but it must SAY so rather
107
+ // Not a failure — r2 artifacts are already durable — but it must SAY so rather
108
108
  // than return zeros, which would read identically to "there was nothing to do".
109
109
  return {
110
110
  scanned: 0,
package/src/code-boxes.ts CHANGED
@@ -1,19 +1,45 @@
1
1
  // F010.11 — a one-time code field split into one box per character (Microsoft's
2
2
  // «Enter your code»). Shared by fill-from-owner and fill-from-mail: the code is
3
3
  // typed key by key from the first box and the page's own auto-advance moves focus.
4
+ // F009.143 — also the variant whose FIRST box takes the whole code (maxlength =
5
+ // code length, autocomplete=one-time-code) and spreads it (vn-leker's login), and
6
+ // a flow anchored on the GROUP's testid rather than on one of its inputs.
4
7
  import type { Locator } from 'playwright';
5
8
 
9
+ /** The input a code is typed into: the anchor itself, or — when the anchor is a
10
+ * wrapper such as the boxes' group — the first visible input inside it. */
11
+ export async function codeInput(loc: Locator): Promise<Locator> {
12
+ const tag = await loc.evaluate((el) => el.tagName).catch(() => '');
13
+ if (tag === 'INPUT' || tag === 'TEXTAREA') return loc;
14
+ const inner = loc.locator('input:not([type=hidden])');
15
+ return (await inner.count()) > 0 ? inner.first() : loc;
16
+ }
17
+
18
+ /** True when `el` is one box of a split code field: either a one-character box,
19
+ * or a wider box whose siblings in its group are all one-character boxes. */
6
20
  export async function isOneCharBox(loc: Locator): Promise<boolean> {
7
- return loc.evaluate((el) => (el as HTMLInputElement).maxLength === 1).catch(() => false);
21
+ return loc
22
+ .evaluate((el) => {
23
+ const input = el as HTMLInputElement;
24
+ if (input.maxLength === 1) return true;
25
+ let group: Element | null = el.parentElement;
26
+ while (group && group.querySelectorAll('input').length < 2 && group.parentElement) group = group.parentElement;
27
+ const others = [...(group?.querySelectorAll('input') ?? [])].filter((i) => i !== el) as HTMLInputElement[];
28
+ return others.length > 0 && others.every((i) => i.maxLength === 1);
29
+ })
30
+ .catch(() => false);
8
31
  }
9
32
 
10
- /** The joined value of the one-character boxes around `el`. */
33
+ /** The joined value of the code boxes around `el`. */
11
34
  function joinedBoxes(el: Element): string {
12
35
  let group: Element | null = el.parentElement;
13
36
  while (group && group.querySelectorAll('input').length < 2 && group.parentElement) group = group.parentElement;
14
- return [...(group?.querySelectorAll('input') ?? [])]
15
- .filter((i) => (i as HTMLInputElement).maxLength === 1)
16
- .map((i) => (i as HTMLInputElement).value)
37
+ const inputs = [...(group?.querySelectorAll('input') ?? [])] as HTMLInputElement[];
38
+ // A box wider than one character belongs to the code only when it is the one
39
+ // we typed into (F009.143); any other wide input in the group is not a box.
40
+ return inputs
41
+ .filter((i) => i.maxLength === 1 || i === el)
42
+ .map((i) => i.value)
17
43
  .join('');
18
44
  }
19
45
 
@@ -21,10 +47,15 @@ function joinedBoxes(el: Element): string {
21
47
  * starts the error message; the value itself is never in it. */
22
48
  export async function typeIntoBoxes(loc: Locator, value: string, failure: string, timeout: number): Promise<void> {
23
49
  await loc.focus({ timeout });
50
+ // Hold the box itself, not the locator: when the last digit submits and the
51
+ // page navigates, a locator would wait for a box that no longer exists until
52
+ // it times out; a handle fails at once with «context destroyed».
53
+ const box = await loc.elementHandle({ timeout });
24
54
  await loc.pressSequentially(value, { timeout });
25
55
  let got: string;
26
56
  try {
27
- got = await loc.evaluate(joinedBoxes);
57
+ if (!box) throw new Error('detached');
58
+ got = await box.evaluate(joinedBoxes);
28
59
  } catch (err) {
29
60
  // The last digit often submits the form; the page leaving is the code landing.
30
61
  if (/Execution context was destroyed|Cannot find context|has been closed|detached/i.test(err instanceof Error ? err.message : String(err))) return;
package/src/durability.ts CHANGED
@@ -12,7 +12,7 @@ export type EvidenceDurability = 'durable' | 'local_only' | 'unknown';
12
12
  * be catastrophic. "We did not record this" must never become a reading.
13
13
  */
14
14
  export function durabilityOf(backend: string | null | undefined): EvidenceDurability {
15
- if (backend === 'tigris') return 'durable';
15
+ if (backend === 'r2') return 'durable';
16
16
  if (backend === 'local') return 'local_only';
17
17
  return 'unknown';
18
18
  }
package/src/mail-fill.ts CHANGED
@@ -10,7 +10,7 @@
10
10
  // spent by then, and hiding it would mean not photographing the form at all.
11
11
  import type { Locator } from 'playwright';
12
12
  import { fillAndVerify } from './fill.ts';
13
- import { isOneCharBox, typeIntoBoxes } from './code-boxes.ts';
13
+ import { codeInput, isOneCharBox, typeIntoBoxes } from './code-boxes.ts';
14
14
 
15
15
  export interface MailFrom {
16
16
  to: string;
@@ -113,12 +113,13 @@ export async function fillFromMail(
113
113
  ): Promise<void> {
114
114
  const { code, id } = await waitForMailCode(mf, since, source);
115
115
  consumed.push({ to: mailboxOf(mf.to), id });
116
- if (code.length > 1 && (await isOneCharBox(loc))) {
117
- await typeIntoBoxes(loc, code, `fill from mail did not land: expected a ${code.length}-character code`, timeout);
116
+ const input = await codeInput(loc);
117
+ if (code.length > 1 && (await isOneCharBox(input))) {
118
+ await typeIntoBoxes(input, code, `fill from mail did not land: expected a ${code.length}-character code`, timeout);
118
119
  return;
119
120
  }
120
121
  try {
121
- await fillAndVerify(loc, code, timeout);
122
+ await fillAndVerify(input, code, timeout);
122
123
  } catch {
123
124
  throw new Error(`fill from mail did not land: expected a ${code.length}-character code in the field (value withheld)`);
124
125
  }
@@ -147,7 +148,16 @@ export function httpMailSource(env: Record<string, string | undefined> = process
147
148
  const base = (env.LENS_MAIL_API ?? 'https://mailmcp.webhouse.net').replace(/\/$/, '');
148
149
  const key = env.LENS_MAIL_KEY;
149
150
  const post = async (path: string, body: unknown, ms: number) => {
150
- if (!key) throw new Error('fill from mail: the daemon has no mail-mcp key (LENS_MAIL_KEY)');
151
+ // Diagnosis (bid, 6/11): the same run failed with the key present in the
152
+ // listener's env. Name the process that asked, so the next failure says where
153
+ // it came from. Names and pid only — never the value.
154
+ if (!key) {
155
+ const seen = Object.keys(env).filter((k) => k.startsWith('LENS_')).sort().join(',') || 'none';
156
+ throw new Error(
157
+ `fill from mail: the daemon has no mail-mcp key (LENS_MAIL_KEY) — pid ${process.pid}, ` +
158
+ `LENS_* names in the env this call read: ${seen}`,
159
+ );
160
+ }
151
161
  const r = await fetch(`${base}${path}`, {
152
162
  method: 'POST',
153
163
  headers: { 'x-mailmcp-key': key, 'content-type': 'application/json' },
package/src/owner-fill.ts CHANGED
@@ -13,7 +13,7 @@ import { homedir } from 'node:os';
13
13
  import { join } from 'node:path';
14
14
  import type { Locator } from 'playwright';
15
15
  import { fillAndVerify } from './fill.ts';
16
- import { isOneCharBox, typeIntoBoxes } from './code-boxes.ts';
16
+ import { codeInput, isOneCharBox, typeIntoBoxes } from './code-boxes.ts';
17
17
 
18
18
  export type OwnerKind = 'code' | 'password' | 'text';
19
19
 
@@ -90,12 +90,13 @@ export async function fillFromOwner(loc: Locator, of: OwnerFrom, fillTimeout: nu
90
90
  if (!res.answer) throw new Error('fill from owner: ARS answered with an empty value');
91
91
  // F010.11 — a code field split into one box per character (Microsoft's «Enter your
92
92
  // code»): type it key by key from the first box and let the page advance.
93
- if (res.answer.length > 1 && (await isOneCharBox(loc))) {
94
- await typeIntoBoxes(loc, res.answer, `fill from owner did not land: expected a ${res.answer.length}-character ${kind}`, fillTimeout);
93
+ const input = await codeInput(loc);
94
+ if (res.answer.length > 1 && (await isOneCharBox(input))) {
95
+ await typeIntoBoxes(input, res.answer, `fill from owner did not land: expected a ${res.answer.length}-character ${kind}`, fillTimeout);
95
96
  return;
96
97
  }
97
98
  try {
98
- await fillAndVerify(loc, res.answer, fillTimeout);
99
+ await fillAndVerify(input, res.answer, fillTimeout);
99
100
  } catch {
100
101
  throw new Error(`fill from owner did not land: expected a ${res.answer.length}-character ${kind} in the field (value withheld)`);
101
102
  }
package/src/schema.ts CHANGED
@@ -15,7 +15,7 @@ export function ensureLensSchema(db: Database): void {
15
15
  db.exec(`
16
16
  -- F074.3 — Lens runs + baselines. Metadata lives here (daemon-local
17
17
  -- SQLite); screenshot/diff BYTES live in the storage adapter (local dir
18
- -- or Tigris). Hard-scoped to project_slug so a project only ever sees
18
+ -- or R2). Hard-scoped to project_slug so a project only ever sees
19
19
  -- its own runs. The SPA dashboard (F074.8) reads these via the daemon's
20
20
  -- HTTP, the same pattern as fleet-status / audit.
21
21
  CREATE TABLE IF NOT EXISTS lens_runs (
@@ -152,8 +152,8 @@ export function ensureLensSchema(db: Database): void {
152
152
  // at capture time and never re-derived from current config.
153
153
  //
154
154
  // The re-derived version is the trap. Read the daemon's CURRENT backend and
155
- // apply it to every row, and the day LENS_TIGRIS_BUCKET is finally set, every
156
- // historic run whose PNGs are still on this Mac starts reporting `tigris`. The
155
+ // apply it to every row, and the day LENS_R2_BUCKET is finally set, every
156
+ // historic run whose PNGs are still on this Mac starts reporting `r2`. The
157
157
  // bytes have not moved; the config changed; the citation goes green. That is
158
158
  // the false-green direction, so the value is written once, at the moment the
159
159
  // bytes are actually put somewhere.
@@ -287,7 +287,7 @@ export interface LensFlowRunRow {
287
287
  * not a synonym for 'reduce'. A reader comparing two runs must refuse on a null
288
288
  * rather than assume they saw the same browser. */
289
289
  reduced_motion?: string | null;
290
- /** F272.2 — 'local' | 'tigris': where this run's step screenshots were PUT, stamped
290
+ /** F272.2 — 'local' | 'r2': where this run's step screenshots were PUT, stamped
291
291
  * at capture time. NULL means NOT RECORDED (a run older than the column) and is a
292
292
  * third fact: `unknown`, never rounded up to durable. Read from the row, never
293
293
  * re-derived from the daemon's current config — a config flip must not retroactively
package/src/service.ts CHANGED
@@ -749,11 +749,11 @@ export function flowRunView(row: LensFlowRunRow, port: number, db?: Database) {
749
749
  // F272.2 — WHERE this run's screenshots live, so a session citing the run as
750
750
  // evidence can see the answer AT CITATION TIME instead of discovering it after
751
751
  // the machine is gone. 'local' = one Mac's disk behind 127.0.0.1, reachable by
752
- // nobody else and by no one once the daemon stops. 'tigris' = durable. null =
752
+ // nobody else and by no one once the daemon stops. 'r2' = durable. null =
753
753
  // NOT RECORDED (a run predating the column) — a third fact, and `unknown` is
754
754
  // never rounded up to durable. Always present, never defaulted, for the same
755
755
  // reason reduced_motion above is.
756
- artifact_backend: (row.artifact_backend as 'local' | 'tigris' | null) ?? null,
756
+ artifact_backend: (row.artifact_backend as 'local' | 'r2' | null) ?? null,
757
757
  // F272.2 — the derived one-word answer to the only question a citation asks:
758
758
  // can the owner still open this after this machine is gone?
759
759
  evidence_durability: allInCloud ? 'durable' : durabilityOf(row.artifact_backend),
@@ -1208,7 +1208,7 @@ export interface PromoteEvidenceResult {
1208
1208
  run_id: string | null;
1209
1209
  project: string;
1210
1210
  /** What the run's backend was BEFORE this call — the reason it needed promoting. */
1211
- was: 'local' | 'tigris' | null;
1211
+ was: 'local' | 'r2' | null;
1212
1212
  promoted: PromotedStep[];
1213
1213
  /** Steps that had no screenshot at all. Reported, never silently dropped: with
1214
1214
  * today's 12% capture rate (F272.3) this is the majority, and a caller that is
@@ -1382,7 +1382,7 @@ export async function promoteEvidence(
1382
1382
  flow_run_id: input.flow_run_id!,
1383
1383
  run_id: null,
1384
1384
  project: input.project,
1385
- was: (row.artifact_backend as 'local' | 'tigris' | null) ?? null,
1385
+ was: (row.artifact_backend as 'local' | 'r2' | null) ?? null,
1386
1386
  promoted,
1387
1387
  steps_without_screenshot: withoutShot,
1388
1388
  evidence,
package/src/storage.ts CHANGED
@@ -8,20 +8,21 @@
8
8
  // Mac; the SPA fetches artifact bytes from the daemon's
9
9
  // own HTTP, the same way FleetTemplatesSection already
10
10
  // talks to 127.0.0.1:7475).
11
- // - tigris (opt-in) : S3-compatible durable storage via Bun's native
12
- // S3Client. Enabled when LENS_TIGRIS_BUCKET + creds are
13
- // in the daemon env. Region is 'auto' (Tigris is global;
14
- // the bucket itself is created in arn per project policy).
11
+ // - r2 (opt-in) : Cloudflare R2 in the EU jurisdiction via
12
+ // @broberg/media. Enabled when LENS_R2_BUCKET + R2_* creds
13
+ // are in the daemon env (D-2287db: storage is EU-bound,
14
+ // and Tigris cannot guarantee EU-only buckets — owner
15
+ // order 4/11/2026, F415.3).
15
16
  //
16
17
  // Keys are POSIX-style paths, e.g. "<project>/runs/<id>.png". The backend is
17
18
  // chosen once at construction from env; callers never branch on it.
18
19
 
19
- import { S3Client } from 'bun';
20
+ import { createMedia, type MediaStore } from '@broberg/media';
20
21
  import { mkdir, readFile, writeFile, rm } from 'node:fs/promises';
21
22
  import { dirname, isAbsolute, resolve, sep } from 'node:path';
22
23
 
23
24
  export interface LensStorage {
24
- readonly backend: 'local' | 'tigris';
25
+ readonly backend: 'local' | 'r2';
25
26
  put(key: string, bytes: Buffer, contentType?: string): Promise<void>;
26
27
  get(key: string): Promise<Buffer | null>;
27
28
  delete(key: string): Promise<void>;
@@ -61,51 +62,49 @@ class LocalDirStorage implements LensStorage {
61
62
  }
62
63
  }
63
64
 
64
- class TigrisStorage implements LensStorage {
65
- readonly backend = 'tigris' as const;
66
- constructor(private readonly client: S3Client) {}
65
+ class R2Storage implements LensStorage {
66
+ readonly backend = 'r2' as const;
67
+ constructor(private readonly media: MediaStore) {}
67
68
 
68
69
  async put(key: string, bytes: Buffer, contentType = 'image/png'): Promise<void> {
69
- await this.client.write(key, bytes, { type: contentType });
70
+ await this.media.upload(key, bytes, { contentType });
70
71
  }
71
72
 
73
+ // @broberg/media has no byte read — it hands out a presigned GET. Fetch it and
74
+ // treat any non-2xx (incl. a missing key) as "not there", as LocalDirStorage does.
72
75
  async get(key: string): Promise<Buffer | null> {
73
76
  try {
74
- const buf = await this.client.file(key).arrayBuffer();
75
- return Buffer.from(buf);
77
+ const res = await fetch(await this.media.signedUrl(key, { expiresIn: 60 }));
78
+ if (!res.ok) return null;
79
+ return Buffer.from(await res.arrayBuffer());
76
80
  } catch {
77
81
  return null;
78
82
  }
79
83
  }
80
84
 
81
85
  async delete(key: string): Promise<void> {
82
- await this.client.delete(key);
86
+ await this.media.delete(key);
83
87
  }
84
88
  }
85
89
 
86
90
  export interface StorageEnv {
87
- LENS_TIGRIS_BUCKET?: string;
88
- LENS_TIGRIS_ENDPOINT?: string;
89
- AWS_ACCESS_KEY_ID?: string;
90
- AWS_SECRET_ACCESS_KEY?: string;
91
+ LENS_R2_BUCKET?: string;
92
+ R2_ACCOUNT_ID?: string;
93
+ R2_ACCESS_KEY_ID?: string;
94
+ R2_SECRET_ACCESS_KEY?: string;
91
95
  }
92
96
 
93
- /** Build the storage backend. Tigris when a bucket + creds are present in
94
- * env; otherwise a local directory under the daemon's app-support dir. */
97
+ /** Build the storage backend. R2 (EU) when a bucket + all R2 creds are present
98
+ * in env; otherwise a local directory under the daemon's app-support dir. */
95
99
  export function createStorage(localRoot: string, env: StorageEnv = process.env as unknown as StorageEnv): LensStorage {
96
- const bucket = env.LENS_TIGRIS_BUCKET;
97
- const accessKeyId = env.AWS_ACCESS_KEY_ID;
98
- const secretAccessKey = env.AWS_SECRET_ACCESS_KEY;
99
- if (bucket && accessKeyId && secretAccessKey) {
100
- const client = new S3Client({
101
- bucket,
102
- accessKeyId,
103
- secretAccessKey,
104
- // Fly Tigris default endpoint; overridable for other S3-compatible stores.
105
- endpoint: env.LENS_TIGRIS_ENDPOINT ?? 'https://fly.storage.tigris.dev',
106
- region: 'auto',
107
- });
108
- return new TigrisStorage(client);
100
+ const bucket = env.LENS_R2_BUCKET;
101
+ const accountId = env.R2_ACCOUNT_ID;
102
+ const accessKeyId = env.R2_ACCESS_KEY_ID;
103
+ const secretAccessKey = env.R2_SECRET_ACCESS_KEY;
104
+ if (bucket && accountId && accessKeyId && secretAccessKey) {
105
+ return new R2Storage(
106
+ createMedia({ provider: 'r2', accountId, accessKeyId, secretAccessKey, bucket, jurisdiction: 'eu' }),
107
+ );
109
108
  }
110
109
  return new LocalDirStorage(localRoot);
111
110
  }