@litfamily/litclaude 1.0.40 → 1.0.41

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.
@@ -14,13 +14,14 @@
14
14
  // only which stage, which lane and how many; never a path, a command or a prompt.
15
15
 
16
16
  import { closeSync, lstatSync, openSync, readFileSync, readSync, readdirSync, realpathSync, statSync } from "node:fs";
17
- import { join, relative, resolve } from "node:path";
17
+ import { dirname, join, relative, resolve } from "node:path";
18
18
 
19
19
  import { DISCIPLINE_ENTRY, STAGE_UNITS, VERDICT_STATES, WORKFLOW_FAMILIES, WORKFLOW_FRESH_MS, normalizeStage, reviewLaneOf } from "./mod/workflow.mjs";
20
- import { resolveProjectStateRoot } from "./project-state-root.mjs";
20
+ import { requireStateDir, resolveProjectStateRoot } from "./project-state-root.mjs";
21
21
  import { appendLitgoalLedger } from "./litgoal/ledger.mjs";
22
22
  import { litgoalGoalsPath, litgoalLedgerPath } from "./litgoal/paths.mjs";
23
23
  import { readLitgoalState } from "./litgoal/state.mjs";
24
+ import { acquireOwnerLock, OwnerLockError, releaseOwnerLock } from "./owner-lock.mjs";
24
25
  import { readPlanProgress } from "./start-work-lifecycle.mjs";
25
26
  import { applyStackEvent, readStack, stackPath, writeStack } from "./workflow-stack.mjs";
26
27
 
@@ -59,11 +60,43 @@ const logStackTransitions = (cwd, transitions) => {
59
60
  }
60
61
  };
61
62
 
62
- const applyAndWrite = (cwd, sessionId, event, now = new Date()) => {
63
+ // Hooks run as separate processes, and five background reviewers can stop within the same second:
64
+ // each move reads, applies and writes under the stack's lock, so one never drops another's verdict.
65
+ // A lock held past the timeout leaves the move unlocked rather than lost.
66
+ const withStackLock = (cwd, sessionId, body) => {
67
+ const lockDir = `${stackPath(cwd, sessionId)}.lock`;
68
+ requireStateDir(dirname(lockDir));
69
+ let owner = null;
70
+ try {
71
+ owner = acquireOwnerLock(lockDir, { timeoutMs: 2_000, staleMs: 30_000 });
72
+ } catch (error) {
73
+ if (!(error instanceof OwnerLockError)) throw error;
74
+ }
75
+ try {
76
+ return body();
77
+ } finally {
78
+ if (owner) releaseOwnerLock(lockDir, owner);
79
+ }
80
+ };
81
+
82
+ const applyAndWrite = (cwd, sessionId, event, now = new Date()) => withStackLock(cwd, sessionId, () => {
63
83
  const { stack, transitions } = applyStackEvent(readStack(cwd, sessionId), event, now);
64
84
  writeStack(cwd, sessionId, stack);
65
85
  logStackTransitions(cwd, transitions);
66
86
  return { stack, transitions };
87
+ });
88
+
89
+ /**
90
+ * SessionEnd: marks the session's stack `endedAt`, so other sessions' cards drop its row at once
91
+ * instead of after the stack goes quiet. The next move of a resumed session writes the stack anew,
92
+ * without the mark. A session with no frames writes nothing.
93
+ */
94
+ export const endWorkflowStack = (cwd, sessionId, now = new Date()) => {
95
+ if (typeof sessionId !== "string" || !sessionId) return;
96
+ withStackLock(cwd, sessionId, () => {
97
+ const stack = readStack(cwd, sessionId);
98
+ if (stack.frames.length) writeStack(cwd, sessionId, { ...stack, endedAt: now.toISOString() });
99
+ });
67
100
  };
68
101
 
69
102
  /**
@@ -409,40 +442,89 @@ export const observeWorkflowPostTool = (cwd, input, { filePaths = [], lifecycleR
409
442
  return moved;
410
443
  };
411
444
 
412
- // The prompt a reviewer was given: the first user message in the head of its transcript.
413
- const transcriptPrompt = (path, bytes = 65_536) => {
445
+ // `bytes` of a reviewer's transcript from `at` ("head" or "tail"), or "" when it is not a file.
446
+ const readTranscript = (path, bytes, at) => {
414
447
  if (typeof path !== "string" || !path.endsWith(".jsonl")) return "";
415
448
  let fd;
416
- let head = "";
417
449
  try {
418
- if (!lstatSync(path).isFile()) return "";
450
+ const info = lstatSync(path);
451
+ if (!info.isFile()) return "";
419
452
  fd = openSync(path, "r");
420
- const buffer = Buffer.alloc(bytes);
421
- head = buffer.subarray(0, readSync(fd, buffer, 0, bytes, 0)).toString("utf8");
453
+ const start = at === "tail" ? Math.max(0, info.size - bytes) : 0;
454
+ const buffer = Buffer.alloc(Math.min(bytes, info.size));
455
+ return buffer.subarray(0, readSync(fd, buffer, 0, buffer.length, start)).toString("utf8");
422
456
  } catch {
423
457
  return "";
424
458
  } finally {
425
459
  if (fd !== undefined) closeSync(fd);
426
460
  }
427
- for (const line of head.split("\n").slice(0, 20)) {
428
- try {
429
- const entry = JSON.parse(line);
430
- const message = entry?.message;
431
- if (entry?.type === "user" || message?.role === "user") return resultText(message?.content ?? message);
432
- } catch {
433
- // A line cut off at the end of the head, or not an entry at all.
434
- }
461
+ };
462
+
463
+ const entryOf = (line) => {
464
+ try {
465
+ return JSON.parse(line);
466
+ } catch {
467
+ return null; // A line cut off at either end of the read, or not an entry at all.
468
+ }
469
+ };
470
+
471
+ // The prompt a reviewer was given: the first user message in the head of its transcript.
472
+ const transcriptPrompt = (path) => {
473
+ for (const line of readTranscript(path, 65_536, "head").split("\n").slice(0, 20)) {
474
+ const entry = entryOf(line);
475
+ if (entry?.type === "user" || entry?.message?.role === "user") return resultText(entry.message?.content ?? entry.message);
476
+ }
477
+ return "";
478
+ };
479
+
480
+ // A reviewer's final report from the end of its transcript: the message of its `SubagentHandback`
481
+ // call (how a background agent reports), or the text of a last assistant message that calls no
482
+ // tool. "" while the last assistant entry is still mid-work or not on disk yet.
483
+ const transcriptReport = (path) => {
484
+ const lines = readTranscript(path, 262_144, "tail").split("\n");
485
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
486
+ const entry = entryOf(lines[index]);
487
+ const content = entry?.type === "assistant" || entry?.message?.role === "assistant" ? entry.message?.content : undefined;
488
+ if (!Array.isArray(content)) continue;
489
+ const handback = content.findLast((block) => block?.type === "tool_use" && block.name === "SubagentHandback");
490
+ if (handback) return typeof handback.input?.message === "string" ? handback.input.message : "";
491
+ if (content.some((block) => block?.type === "tool_use")) return "";
492
+ return content.filter((block) => block?.type === "text").map((block) => block.text).join("\n");
435
493
  }
436
494
  return "";
437
495
  };
438
496
 
439
- /** SubagentStop: a reviewer's verdict, from its last message, for the lane its prompt named. */
497
+ // The host can run SubagentStop before it flushes the lane's last entries to the transcript, so a
498
+ // lane's report is read again for a short while until it is on disk.
499
+ const REPORT_WAIT_MS = 3_000;
500
+ const REPORT_POLL_MS = 100;
501
+ const awaitReport = (path) => {
502
+ const deadline = Date.now() + REPORT_WAIT_MS;
503
+ for (;;) {
504
+ const report = transcriptReport(path);
505
+ if (report || Date.now() >= deadline) return report;
506
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, REPORT_POLL_MS);
507
+ }
508
+ };
509
+
510
+ /**
511
+ * SubagentStop: a reviewer's verdict for the lane its prompt names: a `Review lane:` title, else
512
+ * (for a lane review-work already marked) the prompt's first line, which is how the model headed a
513
+ * background lane's prompt on the host. The verdict is the last message's, else the transcript's
514
+ * final report.
515
+ */
440
516
  export const observeWorkflowSubagentStop = (cwd, input) => {
441
517
  const sessionId = typeof input?.session_id === "string" ? input.session_id : null;
442
- const verdict = verdictFrom(input?.last_assistant_message);
443
- if (!sessionId || !verdict) return null;
444
- const lane = laneFromTitle(transcriptPrompt(input.agent_transcript_path));
445
- return lane ? markLane(cwd, sessionId, currentRecord(cwd, sessionId), lane, verdict) : null;
518
+ if (!sessionId) return null;
519
+ const prompt = transcriptPrompt(input.agent_transcript_path);
520
+ let lane = laneFromTitle(prompt);
521
+ if (!lane) {
522
+ const heading = reviewLaneOf(prompt.trimStart().split("\n", 1)[0]);
523
+ lane = heading && nearestRecord(cwd, sessionId, "main", "review")?.verdicts?.[heading] ? heading : null;
524
+ }
525
+ if (!lane) return null;
526
+ const verdict = verdictFrom(input.last_assistant_message) ?? verdictFrom(awaitReport(input.agent_transcript_path));
527
+ return verdict ? markLane(cwd, sessionId, currentRecord(cwd, sessionId), lane, verdict) : null;
446
528
  };
447
529
 
448
530
  const USAGE = `Usage: litclaude-ai workflow-stage <family> <stage> [--n N] [--total M] [--unit ${STAGE_UNITS.join("|")}] [--verdict <name>=${VERDICT_STATES.join("|")}]... [--session <id>] [--json]
@@ -75,7 +75,8 @@ title, the author and date from the page's metadata, and a `rel=license` link if
75
75
  Every fetch is https only, on the first request and on each redirect. Redirects are followed one
76
76
  hop at a time, at most five, and a hop to `localhost`, a loopback, link-local or private address, or
77
77
  a name that resolves to one is refused, so a public page cannot bounce the capture into the cloud
78
- metadata service or the local network. The body is counted while it streams and dropped past 20 MiB,
78
+ metadata service or the local network. The connection goes to the address the check approved, so a
79
+ name that answers again with a private address cannot move it. The body is counted while it streams and dropped past 20 MiB,
79
80
  whatever length the server declares. For an `http://` page, ask the user for a saved copy and capture
80
81
  it with `--kind file --url <url>`.
81
82
 
@@ -6,8 +6,10 @@ import { spawnSync } from "node:child_process";
6
6
  import { createHash } from "node:crypto";
7
7
  import { lookup as dnsLookup } from "node:dns/promises";
8
8
  import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
9
+ import { request as httpsRequest } from "node:https";
9
10
  import { isIP, isIPv4, isIPv6 } from "node:net";
10
11
  import { extname, isAbsolute, join, relative, resolve } from "node:path";
12
+ import { Readable } from "node:stream";
11
13
  import { fileURLToPath } from "node:url";
12
14
 
13
15
  export const LEDGER_SCHEMA = "litclaude.hijack-ledger.v1";
@@ -556,6 +558,8 @@ export const buildImplementerBrief = (run) => {
556
558
  // A capture follows redirects by hand: every hop must be https and name a public host, so a public
557
559
  // page cannot bounce the fetch into loopback, the cloud metadata address or the local network. The
558
560
  // body is counted as it streams and dropped past the cap, whatever length the server declared.
561
+ // The connection goes to the address the check approved, so a name that answers again with a
562
+ // private address (DNS rebinding) cannot move it; TLS still checks the certificate for the name.
559
563
  const FETCH_HOPS = 5;
560
564
  const privateV4 = (ip) => {
561
565
  const [a, b] = ip.split(".").map(Number);
@@ -579,12 +583,31 @@ const checkHop = async (href, lookup) => {
579
583
  if (url.protocol !== "https:") throw new Error(`refusing ${url.protocol} ${href}: captures fetch https only`);
580
584
  const host = url.hostname.replace(/^\[|\]$/gu, "");
581
585
  if (host === "localhost" || host.endsWith(".localhost") || isPrivateAddress(host)) throw new Error(`refusing ${href}: a loopback, link-local or private host`);
582
- if (!isIP(host) && lookup) {
583
- const addresses = await lookup(host, { all: true });
584
- if (addresses.some(({ address }) => isPrivateAddress(address))) throw new Error(`refusing ${href}: ${host} resolves to a private address`);
585
- }
586
- return url.href;
587
- };
586
+ if (isIP(host)) return { href: url.href, address: host, family: isIP(host) };
587
+ if (!lookup) return { href: url.href, address: null, family: 0 };
588
+ const addresses = await lookup(host, { all: true });
589
+ if (addresses.length === 0) throw new Error(`refusing ${href}: ${host} does not resolve`);
590
+ if (addresses.some(({ address }) => isPrivateAddress(address))) throw new Error(`refusing ${href}: ${host} resolves to a private address`);
591
+ return { href: url.href, address: addresses[0].address, family: addresses[0].family };
592
+ };
593
+ // node:https with a lookup that answers only with the approved address, read back as a Response.
594
+ const pinnedFetch = (request) => (href, { headers, signal }, { address, family }) => new Promise((resolveResponse, reject) => {
595
+ const pin = (_host, options, callback) => (options?.all ? callback(null, [{ address, family }]) : callback(null, address, family));
596
+ const req = request(href, { headers, signal, lookup: pin }, (res) => {
597
+ const answer = new Headers();
598
+ for (const [name, value] of Object.entries(res.headers)) for (const item of [value].flat()) if (item !== undefined) answer.append(name, String(item));
599
+ const empty = [204, 205, 304].includes(res.statusCode);
600
+ if (empty) res.resume();
601
+ try {
602
+ resolveResponse(new Response(empty ? null : Readable.toWeb(res), { status: res.statusCode, headers: answer }));
603
+ } catch (error) {
604
+ res.destroy();
605
+ reject(error);
606
+ }
607
+ });
608
+ req.on("error", reject);
609
+ req.end();
610
+ });
588
611
  const readCapped = async (response, url, limit) => {
589
612
  const declared = Number(response.headers.get("content-length"));
590
613
  const tooLarge = () => new Error(`${url} is larger than ${limit} bytes`);
@@ -612,16 +635,21 @@ const readCapped = async (response, url, limit) => {
612
635
  }
613
636
  };
614
637
 
615
- /** Fetches a public https URL; `fetchImpl` and `lookup` are injectable for tests. */
616
- export const fetchBytes = async (url, { fetchImpl = fetch, lookup = fetchImpl === fetch ? dnsLookup : null, limit = FETCH_LIMIT } = {}) => {
617
- let current = await checkHop(url, lookup);
638
+ /**
639
+ * Fetches a public https URL over a connection pinned to the checked address. `fetchImpl` (a
640
+ * fetch-shaped stub, unpinned), `request` (node:https's) and `lookup` are injectable for tests.
641
+ */
642
+ export const fetchBytes = async (url, { fetchImpl = null, request = httpsRequest, lookup = fetchImpl ? null : dnsLookup, limit = FETCH_LIMIT } = {}) => {
643
+ const send = fetchImpl ? (href, init) => fetchImpl(href, init) : pinnedFetch(request);
644
+ let hop = await checkHop(url, lookup);
618
645
  const signal = AbortSignal.timeout(30_000);
619
- for (let hop = 0; hop <= FETCH_HOPS; hop += 1) {
620
- const response = await fetchImpl(current, { headers: { "user-agent": "litclaude-lit-hijack/1 (+capture)" }, redirect: "manual", signal });
646
+ for (let count = 0; count <= FETCH_HOPS; count += 1) {
647
+ const current = hop.href;
648
+ const response = await send(current, { headers: { "user-agent": "litclaude-lit-hijack/1 (+capture)" }, redirect: "manual", signal }, hop);
621
649
  const location = response.status >= 300 && response.status < 400 ? response.headers.get("location") : null;
622
650
  if (location) {
623
651
  await response.body?.cancel?.();
624
- current = await checkHop(new URL(location, current).href, lookup);
652
+ hop = await checkHop(new URL(location, current).href, lookup);
625
653
  continue;
626
654
  }
627
655
  if (!response.ok) throw new Error(`${current} answered HTTP ${response.status}`);
@@ -8,8 +8,10 @@
8
8
  import { createHash } from "node:crypto";
9
9
  import { lookup as dnsLookup } from "node:dns/promises";
10
10
  import { mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
11
+ import { request as httpsRequest } from "node:https";
11
12
  import { isIP, isIPv4, isIPv6 } from "node:net";
12
13
  import path from "node:path";
14
+ import { Readable } from "node:stream";
13
15
  import { EXIT } from "../core/constants.mjs";
14
16
  import { BlockedError } from "./chrome.mjs";
15
17
  import { rasterInfo } from "./stage-serve.mjs";
@@ -84,6 +86,8 @@ export function pageFacts(html, base) {
84
86
  // Every hop, the first request and each redirect, must be https to a public host: a product page
85
87
  // or README image must not bounce the fetch into loopback, the cloud metadata address or the local
86
88
  // network. Bodies are counted as they stream, so a missing or false content-length cannot buffer more.
89
+ // The request connects to the address the check approved, so a name that answers again with a
90
+ // private address (DNS rebinding) cannot move it; TLS still checks the certificate for the name.
87
91
  const MAX_HOPS = 5;
88
92
  const privateV4 = (ip) => {
89
93
  const [a, b] = ip.split(".").map(Number);
@@ -107,11 +111,32 @@ async function checkHop(href, lookup) {
107
111
  if (url.protocol !== "https:") throw new Error(`refusing ${url.protocol} ${href}: assets are fetched over https only`);
108
112
  const host = url.hostname.replace(/^\[|\]$/gu, "");
109
113
  if (host === "localhost" || host.endsWith(".localhost") || privateAddress(host)) throw new Error(`refusing ${href}: a loopback, link-local or private host`);
110
- if (!isIP(host) && lookup) {
111
- const addresses = await lookup(host, { all: true });
112
- if (addresses.some(({ address }) => privateAddress(address))) throw new Error(`refusing ${href}: ${host} resolves to a private address`);
113
- }
114
- return url.href;
114
+ if (isIP(host)) return { href: url.href, address: host, family: isIP(host) };
115
+ if (!lookup) return { href: url.href, address: null, family: 0 };
116
+ const addresses = await lookup(host, { all: true });
117
+ if (addresses.length === 0) throw new Error(`refusing ${href}: ${host} does not resolve`);
118
+ if (addresses.some(({ address }) => privateAddress(address))) throw new Error(`refusing ${href}: ${host} resolves to a private address`);
119
+ return { href: url.href, address: addresses[0].address, family: addresses[0].family };
120
+ }
121
+ // node:https with a lookup that answers only with the approved address, read back as a Response.
122
+ function pinnedFetch(request) {
123
+ return (href, { headers, signal }, { address, family }) => new Promise((resolve, reject) => {
124
+ const pin = (_host, options, callback) => (options?.all ? callback(null, [{ address, family }]) : callback(null, address, family));
125
+ const req = request(href, { headers, signal, lookup: pin }, (res) => {
126
+ const answer = new Headers();
127
+ for (const [name, value] of Object.entries(res.headers)) for (const item of [value].flat()) if (item !== undefined) answer.append(name, String(item));
128
+ const empty = [204, 205, 304].includes(res.statusCode);
129
+ if (empty) res.resume();
130
+ try {
131
+ resolve(new Response(empty ? null : Readable.toWeb(res), { status: res.statusCode, headers: answer }));
132
+ } catch (error) {
133
+ res.destroy();
134
+ reject(error);
135
+ }
136
+ });
137
+ req.on("error", reject);
138
+ req.end();
139
+ });
115
140
  }
116
141
  async function readCapped(res, url, limit) {
117
142
  const declared = Number(res.headers.get("content-length"));
@@ -139,15 +164,16 @@ async function readCapped(res, url, limit) {
139
164
  }
140
165
  }
141
166
 
142
- async function get(fetchImpl, url, { accept, limit, lookup }) {
143
- let current = await checkHop(url, lookup);
167
+ async function get(send, url, { accept, limit, lookup }) {
168
+ let hop = await checkHop(url, lookup);
144
169
  const signal = AbortSignal.timeout(ASSET_LIMITS.timeoutMs);
145
- for (let hop = 0; hop <= MAX_HOPS; hop += 1) {
146
- const res = await fetchImpl(current, { headers: { accept, "user-agent": "lit-typographic-motion-assets" }, redirect: "manual", signal });
170
+ for (let count = 0; count <= MAX_HOPS; count += 1) {
171
+ const current = hop.href;
172
+ const res = await send(current, { headers: { accept, "user-agent": "lit-typographic-motion-assets" }, redirect: "manual", signal }, hop);
147
173
  const location = res.status >= 300 && res.status < 400 ? res.headers.get("location") : null;
148
174
  if (location) {
149
175
  await res.body?.cancel?.();
150
- current = await checkHop(new URL(location, current).href, lookup);
176
+ hop = await checkHop(new URL(location, current).href, lookup);
151
177
  continue;
152
178
  }
153
179
  if (!res.ok) throw new Error(`${res.status} from ${current}`);
@@ -162,10 +188,12 @@ function roleFor(url, fallback) {
162
188
  }
163
189
 
164
190
  /**
165
- * Fetch a product's assets into <out>. `fetchImpl` is injectable for tests. Returns { code, message,
166
- * product }; throws BlockedError 22 when nothing could be reached.
191
+ * Fetch a product's assets into <out> over connections pinned to each checked address. `fetchImpl` (a
192
+ * fetch-shaped stub, unpinned), `request` (node:https's) and `lookup` are injectable for tests.
193
+ * Returns { code, message, product }; throws BlockedError 22 when nothing could be reached.
167
194
  */
168
- export async function fetchAssets({ out, url, into = "stage", fetchImpl = globalThis.fetch, lookup = fetchImpl === globalThis.fetch ? dnsLookup : null, now = () => new Date() }) {
195
+ export async function fetchAssets({ out, url, into = "stage", fetchImpl = null, request = httpsRequest, lookup = fetchImpl ? null : dnsLookup, now = () => new Date() }) {
196
+ const send = fetchImpl ? (href, init) => fetchImpl(href, init) : pinnedFetch(request);
169
197
  let link;
170
198
  try {
171
199
  link = new URL(url);
@@ -187,7 +215,7 @@ export async function fetchAssets({ out, url, into = "stage", fetchImpl = global
187
215
  const [, owner, rname] = repo;
188
216
  name = rname;
189
217
  try {
190
- const meta = JSON.parse((await get(fetchImpl, `https://api.github.com/repos/${owner}/${rname}`, { accept: "application/vnd.github+json", limit: ASSET_LIMITS.pageBytes, lookup })).toString("utf8"));
218
+ const meta = JSON.parse((await get(send, `https://api.github.com/repos/${owner}/${rname}`, { accept: "application/vnd.github+json", limit: ASSET_LIMITS.pageBytes, lookup })).toString("utf8"));
191
219
  Object.assign(words, { name: meta.name ?? rname, description: meta.description ?? null, homepage: meta.homepage || null, topics: meta.topics ?? [] });
192
220
  name = meta.name ?? rname;
193
221
  if (meta.owner?.avatar_url) candidates.push({ url: meta.owner.avatar_url, role: "icon", note: "owner avatar" });
@@ -195,7 +223,7 @@ export async function fetchAssets({ out, url, into = "stage", fetchImpl = global
195
223
  problems.push(`repository: ${error.message}`);
196
224
  }
197
225
  try {
198
- const readme = (await get(fetchImpl, `https://api.github.com/repos/${owner}/${rname}/readme`, { accept: "application/vnd.github.raw", limit: ASSET_LIMITS.pageBytes, lookup })).toString("utf8");
226
+ const readme = (await get(send, `https://api.github.com/repos/${owner}/${rname}/readme`, { accept: "application/vnd.github.raw", limit: ASSET_LIMITS.pageBytes, lookup })).toString("utf8");
199
227
  writeFileSync(path.join(wordsDir, "README.md"), readme);
200
228
  words.readme = "product/README.md";
201
229
  const images = readmeImages(readme, `https://raw.githubusercontent.com/${owner}/${rname}/HEAD/`).map((u) => ({ url: u.replace(/^https:\/\/github\.com\/([^/]+\/[^/]+)\/blob\//u, "https://raw.githubusercontent.com/$1/"), role: "readme-image" }));
@@ -205,7 +233,7 @@ export async function fetchAssets({ out, url, into = "stage", fetchImpl = global
205
233
  }
206
234
  } else {
207
235
  try {
208
- const html = (await get(fetchImpl, link.href, { accept: "text/html", limit: ASSET_LIMITS.pageBytes, lookup })).toString("utf8");
236
+ const html = (await get(send, link.href, { accept: "text/html", limit: ASSET_LIMITS.pageBytes, lookup })).toString("utf8");
209
237
  const facts = pageFacts(html, link.href);
210
238
  Object.assign(words, { title: facts.title, description: facts.description });
211
239
  if (facts.title) name = facts.title.split(/\s[|·—–-]\s/u)[0].trim() || name;
@@ -221,7 +249,7 @@ export async function fetchAssets({ out, url, into = "stage", fetchImpl = global
221
249
  for (const c of candidates) {
222
250
  if (assets.length >= ASSET_LIMITS.files) break;
223
251
  try {
224
- const buf = await get(fetchImpl, c.url, { accept: "image/*", limit: ASSET_LIMITS.fileBytes, lookup });
252
+ const buf = await get(send, c.url, { accept: "image/*", limit: ASSET_LIMITS.fileBytes, lookup });
225
253
  const kind = sniffImage(buf);
226
254
  if (!kind) throw new Error("not an image");
227
255
  if (kind === "svg" && !cleanSvg(buf.toString("utf8"))) throw new Error("an SVG with script or outside links");
@@ -157,7 +157,8 @@ node scripts/motion.mjs assets --out <dir> --url <the link from the request>
157
157
  ```
158
158
 
159
159
  It reaches only `https` pages, on every redirect too: a hop to `localhost` or a loopback, link-local
160
- or private address is refused, and each body is counted as it streams. For a GitHub repository it
160
+ or private address is refused, each connection goes to the address that check approved, and each
161
+ body is counted as it streams. For a GitHub repository it
161
162
  reads the repository metadata, the owner avatar and the README with its images (badges skipped); for
162
163
  another site, its `og:image` and icons. Each raster is sniffed and decoded before it is kept,
163
164
  animated images are skipped, an SVG is cleaned of scripts, and the limits are 8 files, 4 MB a file