@agentproto/collect 0.0.0-stage → 0.1.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.
package/README.md CHANGED
@@ -1,3 +1,643 @@
1
- # Temporary Holding Version
1
+ # @agentproto/collect
2
+
3
+ Building blocks for collecting public posts, articles and metrics with
4
+ provenance. The root entry is pure: no filesystem, no network, one runtime
5
+ dependency (`zod`). Only the `@agentproto/collect/node` entry touches the
6
+ filesystem (Node built-ins only).
7
+
8
+ ## What is in it
9
+
10
+ - **Schemas** (zod, with inferred types): `CollectItem`, `Observation`,
11
+ `Actor` (with audience readings), `Pickup`, `Recipe`, `RunReport`,
12
+ `Coverage`.
13
+ - **Ids**: `itemId(source, nativeId)` gives `source:nativeId`;
14
+ `itemIdFromUrl(source, url)` hashes the canonical URL when a platform gives
15
+ no id.
16
+ - **`canonicalUrl(url)`**: lowercase host, no fragment, no credentials, no
17
+ default port, tracking parameters removed (`utm_*`, `fbclid`, `gclid`,
18
+ `mc_cid`, `mc_eid`, `ref_src`, `igshid`, ...; `si` on YouTube hosts only), remaining
19
+ parameters sorted, no trailing slash. It only normalises http(s); any other
20
+ input comes back trimmed and unchanged. The result is a dedup key: keep the
21
+ original URL too, and pass the final URL (redirects are not followed).
22
+ - **`textFingerprint(text)`**: SHA-256 of the text after case, whitespace and
23
+ punctuation normalisation. Hashing goes through Web Crypto
24
+ (`crypto.subtle`), so it is async and needs no Node built-in. Text that normalises to nothing
25
+ returns `undefined` (no content id).
26
+ - **`STORE_SCHEMA_VERSION`**: version of the stored shapes.
27
+ - **`CollectStore`**: the port the engine writes to (raws by content hash,
28
+ items, observations, actors, pickups, a seen index, run records, a writer
29
+ lock), and `memoryStore()` implementing it. Reads are streaming `Reader`s
30
+ that expose a `skipped` count of unreadable lines.
31
+ - **`@agentproto/collect/node`**: `initStore(path)` / `openStore(path)`, the
32
+ same port on disk (Node built-ins only). See "On-disk store" below.
33
+ - **Engine**: `createCollector({ store, transports, secrets, connectors, clock?, random? })`
34
+ with `run(recipe, { signal, onEvent, runId? })` and `resume(runId)`. A
35
+ connector (`defineConnector`, `registerConnector`) plans tasks, fetches
36
+ through the transports it declares (`api`, `http`, `browser`, tried in
37
+ order), and parses stored raws. 401/403/429, an empty body or a thrown
38
+ `blocked`/`empty` error moves a task to the next transport (the report
39
+ records the escalation); other statuses are `http` failures with no
40
+ fallback. A verification (challenge) page seen by `http` or `api` moves the
41
+ task to the next transport too, and fails it with cause `challenge` when none
42
+ remains. A challenge seen by the `browser` is a hard stop: the raw is kept,
43
+ there is no fallback, no new request is started for the connector for the
44
+ rest of the run (requests already in flight are aborted) and its queued tasks are `skipped` with reason
45
+ `challenge`.
46
+ The whole root plan is written first in one atomic `plan.jsonl`. The engine
47
+ stores every raw, parses and validates every raw of a task before writing
48
+ anything, dedups on native id and canonical URL (the same exact text under two URLs keeps two items that share one `contentId`; the seen index maps
49
+ each key to the item that owns it, so observations and links resolve to the
50
+ owner), writes, then marks the task `done` with its counters. Observations
51
+ and pickups carry `runId` and `taskId`, so a task redone after a crash does
52
+ not double-count (readers drop the identical copy). A connector with no usable
53
+ transport is `skipped` and the run goes on. A transport that throws
54
+ `MissingSecretError` hands the task to the next declared transport; when none
55
+ remains the task is `skipped` with reason `missing_secret:<NAME>` (the
56
+ secret's name only) and a connector whose tasks were all skipped that way is
57
+ reported `skipped`.
58
+ Scheduling: a bounded pool (`recipe.workers`, default 8) for api/http
59
+ attempts and a browser lane of one; each attempt is queued in the lane of its
60
+ own transport, so a fallback moves the task between lanes. Every request goes
61
+ through a per-host FIFO gate shared by all connectors (zero delay included).
62
+ The host gate covers the `http` and `api` transports. The browser lane is
63
+ serialised and paced by the connector delay (on `open` and `fetchInPage`);
64
+ requests a page makes by itself are outside the engine.
65
+ Start order is guaranteed per lane (by global order key) and non-browser
66
+ tasks start first; there is no global order across the two lanes, by design.
67
+ Each engine-written observation, pickup and actor carries a `recordKey` (hash of run,
68
+ task, raw hash and position in the parse output): readers keep the first
69
+ record of a key, so a task redone after a crash that fetches the same bytes never double-counts (a page whose bytes changed is a new raw and a new reading) while
70
+ distinct readings with equal values are all kept. Limitation: two raws of the same task with identical bytes share record keys, so the second copy is dropped (identical bytes give identical readings). Each task start is recorded
71
+ once (`started`) and charges the cap budget, so a crash after a start still
72
+ counts. Resuming a run with no plan file plans it again from the frozen recipe.
73
+ Also a per-connector cap, one writer, and the store lock held for the whole
74
+ run and released last. One collector drives one store (the store lock makes a
75
+ second run wait). A store failure surfaces as a `CollectRunError` after the
76
+ active work has settled.
77
+ `resume(runId)` reloads the frozen recipe, the plan and the task log, never
78
+ refetches a `done` task, and redoes `pending`, `failed` and `skipped` ones in
79
+ their recorded global order. Caps are restored from the task states: a
80
+ retried failed task takes no new budget, and a task that took budget keeps its
81
+ charge (`charged` on its records) even when it ends `skipped`.
82
+ `computeCoverage(store, connectors)` gives the coverage cells;
83
+ `withPrimaryMetric` counts only a declared primary counter. The transports are
84
+ contracts only here (`HttpTransport`, `BrowserTransport`, `SecretsPort`,
85
+ `TransportError`); implementations are supplied by the caller.
86
+ - `Recipe.sampling` is applied by the engine (see "Recipe sampling" below).
87
+
88
+ ## Rules baked into the schemas
89
+
90
+ - A counter that is not available is absent from `metrics` and listed in
91
+ `missing` with a reason. It is never zero.
92
+ - An item may have no subject and no author audience.
93
+ - An unknown audience is a reading with an `unknown` reason, never a zero.
94
+ Karma stays typed `karma`.
95
+
96
+ ```ts
97
+ import { CollectItem, canonicalUrl, itemIdFromUrl, textFingerprint } from "@agentproto/collect"
98
+
99
+ const url = canonicalUrl("https://Example.com/a/?utm_source=x#top") // https://example.com/a
100
+ const id = await itemIdFromUrl("web", url)
101
+ const contentId = await textFingerprint("Some article text")
102
+ CollectItem.parse({ id, source: "web", kind: "article", contentId, firstSeenAt: new Date().toISOString() })
103
+ ```
104
+
105
+ ## License
106
+
107
+ Apache-2.0
108
+
109
+ ## On-disk store
110
+
111
+ ```ts
112
+ import { initStore, openStore } from "@agentproto/collect/node"
113
+
114
+ const store = await initStore("./data") // creates it, or opens it if it exists
115
+ const lock = await store.acquireLock()
116
+ try {
117
+ // ... write
118
+ } finally {
119
+ await lock.release()
120
+ }
121
+ ```
122
+
123
+ ```
124
+ <store>/
125
+ collect.json { "schemaVersion": 1 }
126
+ raw/<connector>/<yyyy-mm>/<sha256>.<ext>.gz
127
+ raw/index.jsonl one line per fetch (url, date, status, transport, run, failure cause)
128
+ items/<source>.jsonl last line for an id wins
129
+ observations/<source>.jsonl append-only
130
+ actors/<source>.jsonl append-only
131
+ pickups.jsonl append-only
132
+ seen.idx one dedup key per line (id:, url:, content:)
133
+ runs/<runId>/ recipe.json, tasks.jsonl, sampling.jsonl, events.jsonl, report.json
134
+ ```
135
+
136
+ - **Raws** are gzip, named by the SHA-256 of the body (the input bytes are
137
+ copied before hashing). The same bytes for the same connector and month land
138
+ on the same path and are written once; an existing file is verified (gunzip
139
+ and hash) and rewritten if it is corrupt, in which case `stored` is `true`.
140
+ The index line is appended on every fetch, failures included. Refs are
141
+ parsed strictly (`parseRawRef`): anything but
142
+ `raw/<connector>/<yyyy-mm>/<sha256>.<ext>.gz` is rejected.
143
+ - **Source filter**: items, observations and actors are filed by the prefix of
144
+ their id (`hn` for `hn:1`, also for an actor ref). The `source` argument of
145
+ `items()`, `observations()` and `actors()` means that prefix, in both stores.
146
+ - **Reads** skip lines that are not JSON or fail schema validation and count
147
+ them in `reader.skipped`; they never throw. Only a missing file counts as
148
+ empty; any other I/O error is raised. `getItem(id)` streams one source file
149
+ and keeps the last match. A full `items()` read keeps the last line per id
150
+ and buffers the unique ids of the files it reads in a map; run `compact`
151
+ (planned) to keep files small.
152
+ - **Torn appends**: before the first append to a log file in a process (inside
153
+ the write queue), a file whose last byte is not a newline gets a newline, so
154
+ a torn tail stays a single skipped line. A torn `seen.idx` tail is ignored
155
+ on load and removed once the lock is held.
156
+ - **Lock**: `collect.lock` is written to a unique tmp file and hard-linked into
157
+ place, so it never exists empty; `EEXIST` means held, and a second
158
+ `acquireLock()` throws `StoreLockedError`. A lock is stale when it was
159
+ written on this host by a pid that is not alive (`pidAlive`, default
160
+ `process.kill(pid, 0)`); a stale lock is broken automatically: the file is
161
+ renamed to `collect.lock.stale-<token>` (one process wins the rename), read
162
+ again, and only removed if it is still the dead holder's pid and token;
163
+ otherwise it is linked back and the store is reported locked. A lock from
164
+ another host, or an unreadable one, is never broken: remove it by hand.
165
+ Taking the lock reloads the seen index from disk.
166
+ - **Writes** inside a process go through one queue, so appends never
167
+ interleave; `seenAdd` persists before it updates the in-memory set and
168
+ `rebuildSeenIndex` runs entirely inside the queue. One writer per store is
169
+ assumed across processes: take the lock. Writing a task, sampling line,
170
+ event or report for a run that was not created throws.
171
+ - **Versions**: `openStore` accepts the current schema version and refuses a
172
+ newer one with `StoreVersionError`. For an older one it takes the lock
173
+ (`StoreLockedError` if held), reads the version again, runs
174
+ `options.migrations` (`{ [fromVersion]: ({ root }) => Promise<void> }`, each
175
+ step moves N to N + 1) and rewrites `collect.json` after each step. A
176
+ migration can be interrupted and run again, so write it to be idempotent. A
177
+ missing step throws `StoreMigrationError`. `initStore` creates `collect.json`
178
+ with an exclusive create, so concurrent calls are safe.
179
+ - `rebuildSeenIndex()` rewrites `seen.idx` from the current item of each id.
180
+
181
+ ## HTTP and API transports (`@agentproto/collect/node`)
182
+
183
+ ```ts
184
+ import { createApiTransport, createHttpTransport } from "@agentproto/collect/node"
185
+
186
+ const http = createHttpTransport({ minIntervalMs: 0 }) // the engine already gates each host
187
+ const api = createApiTransport({ http, secrets, auth: { type: "bearer", secret: "SERVICE_KEY" } })
188
+ const collector = createCollector({ store, transports: { http, api }, connectors })
189
+ ```
190
+
191
+ `createHttpTransport(options)` is `fetch` with a policy, Node built-ins only:
192
+
193
+ - **Timeout** per attempt (`timeoutMs`, default 30 s; a request's own `timeoutMs` wins).
194
+ - **Retries** (`maxAttempts`, default 3) on network errors, 429 and 5xx, with
195
+ exponential backoff and jitter (`baseDelayMs`, `maxBackoffMs`; `random` and
196
+ `clock` are injectable). POST and PATCH are not retried unless
197
+ `retryUnsafeMethods`.
198
+ - **`Retry-After`** replaces the backoff on 429 and 503. It is a
199
+ non-negative integer number of seconds or an HTTP date (IMF-fixdate, RFC 850
200
+ or asctime); anything else is ignored. Above `maxRetryAfterMs` (default
201
+ 30 s) the request gives up at once with cause `http` and the response status.
202
+ Only a 429 then falls back to the next transport; a 503 is a final `http`
203
+ failure.
204
+ - **Redirects** are followed by hand (at most `maxRedirects`); `url` in the
205
+ response is the final one. `Authorization`, `Cookie`, `Proxy-Authorization`
206
+ and the credential headers set by `createApiTransport` are dropped when a
207
+ hop changes origin; a request whose credential is in the URL (query
208
+ authentication) refuses such a hop with a `blocked` error. A redirect that
209
+ turns a POST into a GET drops the body and its `Content-*` headers.
210
+ - **User-Agent** is `agentproto-collect` unless you set `userAgent` or a request header.
211
+ - **Size cap** (`maxBytes`, default 10 MiB): a 2xx body over the cap, declared
212
+ or streamed, aborts the transfer with cause `http` and the response status
213
+ (not retried, no fallback: a bigger page is not a transport problem). A
214
+ non-2xx body is truncated to the cap instead.
215
+ - **Limiter** (`minIntervalMs`, default 1000, 0 turns it off): one pacing
216
+ point at the send boundary. It paces the first send, every retry and every
217
+ redirect hop to the same host, and a wait in its queue ends when the request
218
+ is aborted. The engine gates the start of each task by the connector's
219
+ `pace.delayMs`, so the first send of a task is paced by both; the two
220
+ overlap (the later deadline wins) and do not add up. Retries and redirect
221
+ hops never go back through the engine, so only this limiter paces them, even
222
+ inside the engine: set `minIntervalMs` to the gap you want between those
223
+ extra sends (0 leaves them unpaced). Used alone, keep the default.
224
+ - **Error responses**: once the headers arrived, the status and `Retry-After`
225
+ are kept; a body that stalls or resets is cut short and the response still
226
+ classifies by status. A cancellation by the caller always wins.
227
+ - Options are validated: a non-finite, negative or out-of-range value throws a
228
+ `RangeError`.
229
+
230
+ Errors are always `TransportError`, with the failed body and extension kept
231
+ for the raw store:
232
+
233
+ | Situation | `cause` | Engine reaction |
234
+ |---|---|---|
235
+ | 401, 403 | `blocked` | falls back |
236
+ | 429 (retries used up or `Retry-After` too long) | `http`, status 429 | falls back |
237
+ | 503 (same) and other 5xx | `http`, status 5xx | final |
238
+ | verification page | `challenge` | falls back; stops the connector only when the browser met it |
239
+ | 2xx with no body | `empty` | falls back |
240
+ | DNS, reset, TLS, timeout, abort | `network` | no fallback |
241
+ | other 4xx, 5xx after retries, size cap | `http` | final |
242
+
243
+ A response is a verification page only with real evidence: the header
244
+ `cf-mitigated: challenge`; or a status of 403, 429 or 503 together with an
245
+ interstitial marker in the first 64 KiB of HTML (titles such as "Just a
246
+ moment" or "Attention required", "verify you are human", "checking your
247
+ browser", or a verification widget such as reCAPTCHA, hCaptcha or Turnstile);
248
+ or a page that is nothing but the interstitial (under 4 KiB, a marker or
249
+ widget, under 120 characters of visible text). A normal page that embeds a
250
+ widget or quotes a verification phrase is content, and non-HTML content types
251
+ are never flagged. These are heuristics: a page they miss is stored as a
252
+ normal response.
253
+
254
+ `createApiTransport({ http, secrets, auth })` adds the secret on every request:
255
+ `{ type: "bearer" | "header" | "query" }` (`name` for header and query,
256
+ `prefix` for header). A missing or empty secret throws `MissingSecretError`
257
+ before any request; the engine tries the next declared transport, else skips
258
+ the task with `missing_secret:<NAME>`. The secret value never leaves the
259
+ transport: every occurrence (raw, percent-encoded and form-encoded) is
260
+ replaced by `[redacted]` in the body bytes and headers of successful
261
+ responses, and in the message, url and body of errors; a query-parameter
262
+ secret is removed from the returned `url`, and the underlying error object is
263
+ dropped.
264
+
265
+ ## Browser transport over an MCP client (`@agentproto/collect/node`)
266
+
267
+ `createMcpClient({ endpoint, headers?, protocolVersion?, timeoutMs?, signal? })`
268
+ is a streamable-HTTP MCP client on Node built-ins: `initialize`,
269
+ `notifications/initialized`, `listTools()`, `callTool(name, args, { signal, timeoutMs, detached })`.
270
+
271
+ - Replies are plain JSON or an event stream, read incrementally: each complete
272
+ frame is consumed once (a bare CR, a bare LF or CRLF ends a line, also across
273
+ chunks; multi-byte characters split across chunks are decoded whole), and
274
+ only the JSON-RPC response whose id matches the request counts;
275
+ notifications and other responses are ignored. The call returns as soon as
276
+ its response is complete, even if the server keeps the stream open.
277
+ - The session id (`Mcp-Session-Id`) and the negotiated protocol version are
278
+ taken from a successful `initialize` only, whose result must carry a
279
+ `protocolVersion`. A server that gives no session id is used statelessly.
280
+ Recovery is driven by the HTTP status 404 alone on a request that carried a
281
+ session (the body is optional and read defensively: empty, `null`, an array
282
+ with a `null`, or not JSON all work), uses the session generation the request
283
+ carried, and is one serialised re-initialisation however many calls met it. A
284
+ session whose replay fails is invalidated, never kept. A detached call
285
+ (cleanup) waits for a handshake or recovery started by someone else only
286
+ within its own deadline, and starts its own when that one was cancelled.
287
+ - Redirects are never followed by the platform (`redirect: "manual"`). A
288
+ redirect to the same origin is followed, and the credentials are resent there
289
+ only; a redirect to another origin is refused with a typed `http` error, for
290
+ every method (a `DELETE` that ends the session included), and nothing is sent
291
+ there. The location is not repeated in the message.
292
+ - Once its reply is read, the client lets go of the response stream without
293
+ waiting for it to finish closing.
294
+ - Failures are `McpError` (`kind`: `http`, `rpc`, `protocol`, `timeout`,
295
+ `aborted`, `network`) and keep the HTTP `status` and the JSON-RPC `code`.
296
+ - Scrubbing. The configured header values (any length) and credentials in the
297
+ endpoint URL are removed from remote data before it leaves the client, field
298
+ by field: every string of every content block (except its `type` and
299
+ `mimeType`), structured content (keys and values), tool descriptions, error
300
+ messages, error data and causes (an abort or timeout cause is rebuilt from a
301
+ scrubbed message). Protocol control fields (`isError`, `type`, the shape of
302
+ the result) are never touched. A caller that decodes wrappers itself (the
303
+ proxy wrapper, a JSON text) passes `scrub: false`, decodes first, and then
304
+ scrubs only the payload with `scrubResult` / `scrubValue` (decoded payload object keys included): raw JSON text that
305
+ carries protocol structure is never scrubbed, and tool descriptors keep their
306
+ name, schema keywords and property names (only `title` and `description`
307
+ text is scrubbed). A raw occurrence is replaced by `[redacted]`. A text that
308
+ still carries a value once its wrappers are removed (percent-encoding in
309
+ either case, form `+`, JSON escapes such as `\uXXXX`, double encoding, inside
310
+ JSON text) cannot be cut safely: it is dropped whole and replaced by
311
+ `REDACTED_NOTICE`. Result blocks are scrubbed one by one, then the scrubbed
312
+ concatenation is checked: a value that still shows there crosses a block
313
+ boundary, and only the blocks that span touches are replaced.
314
+ `client.scrub(text)` applies the same text rule.
315
+
316
+ `createBrowserTransport({ client, profile, instance?, proxy?, tools?, pace?, maxPages?, signal? })`
317
+ returns a `BrowserTransport` (`open`, `evaluate`, `fetchInPage`, `scroll`,
318
+ `waitFor`, `close`) plus `closeAll()`, `openPages()`, `pagesUsed()`,
319
+ `canList()` and `probe()`.
320
+
321
+ Tool profiles say how a browser server is driven:
322
+
323
+ | Profile | Tools | Addressing | Evaluate | Result |
324
+ |---|---|---|---|---|
325
+ | `CHROME_DEVTOOLS_PROFILE` (`chrome-devtools`) | `new_page`, `navigate_page`, `evaluate_script`, `close_page`, `list_pages` (chrome-devtools-mcp v1.14 and later) | the stable numeric `pageId` on every page tool | `function` argument | JSON in a fenced block |
326
+ | `CHROME_DEVTOOLS_INDEX_PROFILE` (`chrome-devtools-index`) | the same, plus `select_page` | fallback for servers that name pages by index (`pageIdx`) and act on the selected page | `function` argument | JSON in a fenced block |
327
+ | `TAB_TOOLS_PROFILE` (`tab-tools`) | `browser_new_tab`, `browser_navigate`, `browser_evaluate { expression, tabId, instance }`, `browser_close_tab`, `browser_list_owned_tabs` (optional) | the browser-issued `tabId` on every call | `expression`, so the body is wrapped as an IIFE | `content[0].text` is JSON `{ value, truncated }` |
328
+
329
+ `tools` overrides any tool name. `proxy: { tool, alias }` sends every call
330
+ through one tool taking `{ alias, toolName, args }`. `instance` is sent with
331
+ every call of a profile that takes one.
332
+
333
+ ### The ownership lock
334
+
335
+ One lock per transport handle, separate from pacing, serialises verify, select,
336
+ act, close, create registration, sweeps and the page-budget reservation, so no
337
+ two of them interleave and an index never changes between the check and the
338
+ call. The engine runs one browser task at a time, so it costs nothing. Pacing
339
+ waits happen outside it. Cleanup (`close`, `closeAll`) takes it with its own
340
+ deadline (`cleanupTimeoutMs`) and, if it is still held then, acts anyway: it
341
+ only ever closes what it can prove is its own.
342
+
343
+ ### Ownership of tabs
344
+
345
+ - **`tab-tools`**: the id the browser issued when the tab was created is the
346
+ identity. Every call addresses that id. Nothing is ever matched by URL or by
347
+ order.
348
+ - **`chrome-devtools`** (chrome-devtools-mcp v1.14 and later): the tools take a
349
+ stable numeric `pageId` (`select_page`, `close_page`, `navigate_page`,
350
+ `evaluate_script`), listed by `list_pages` as `<id>: <title> (<url>)`, and ids
351
+ are never reused. Ownership is by id: a new page is created on a marker URL
352
+ (a data URL with a full random UUID) and its id is the listed page whose URL
353
+ equals that marker exactly. The transport never changes the browser's
354
+ selection. If the server runs with page-id routing off it would act on the
355
+ selected page, so right after a create the transport checks that a script run
356
+ on the page it addressed really ran there, and fails closed (typed `blocked`)
357
+ otherwise. `collect doctor` also says when the profile does not match the
358
+ server's schema (`pageId` against `pageIdx`).
359
+ - **`chrome-devtools-index`** is the fallback for servers that return no page
360
+ id: they name pages by index. It works in **exclusive mode only** (a browser
361
+ session no other client drives). A page is found once, by its exact marker
362
+ URL. After that, ownership is continuity: right before each call the pages are
363
+ listed again, the count must be the one this transport's own opens and
364
+ closes produce, and the page must still be at its index; a page that has not
365
+ been navigated yet must still show its exact marker, so another page at the
366
+ same index is never accepted. A different URL on a navigated page is a
367
+ transition, checked for a verification page first. If continuity cannot be
368
+ re-established nothing is done and the error is a typed `blocked` one. Every
369
+ index-based mutation, cleanup included, runs under the ownership lock: if
370
+ cleanup cannot get it within its deadline it does not close by index, and
371
+ `leftOpen()` reports the tab (the CLI prints a warning).
372
+ When the browser is shared, use `tab-tools` or `chrome-devtools`.
373
+
374
+ ### Behaviour
375
+
376
+ - `evaluate(page, script)`: `script` is an expression (`document.title`) or a
377
+ function body that returns (`const a = 1; return a`); the transport compiles
378
+ it, without running it, to tell which. The value must be JSON. A `truncated: true` result is an error (`empty`, with the
379
+ reason), never used silently. `isError: true`, a JSON-RPC error (`-32603`) and
380
+ a timeout are `TransportError`s.
381
+ - `fetchInPage(page, request)`: only GET and HEAD. It navigates the tab to the
382
+ target origin first when needed, then runs a same-origin `fetch` in the page
383
+ and returns `{ status, headers, body, url }` (text bodies). A cross-origin
384
+ redirect or a CORS failure has cause `blocked`. A response header that
385
+ demands a verification (`cf-mitigated: challenge`, an `x-amzn-waf-action` of
386
+ `captcha` or `challenge`) is a `challenge`, recognised from the headers
387
+ alone, before the body is read. Otherwise only a bounded prefix (at most
388
+ `maxBodyChars`) of the body is read; a larger body is cut off and is an
389
+ `empty` error (its head is still checked for a verification page).
390
+ - Tabs: every tab is created on a unique marker URL
391
+ (`data:text/html,collect-<random uuid>`, a tiny document that loads at once),
392
+ one per `open`, closed by `close`. When `open` fails after creating the tab it
393
+ closes it before throwing. When a create fails, times out or is cancelled
394
+ without the tab id being learned, the tabs are listed and any whose URL is
395
+ exactly that marker is closed.
396
+ - Late creates: `closeAll()` closes the tabs still open, lets creates still in
397
+ flight settle (or reach their own deadline), sweeps, and, if a create that
398
+ gave up left its tab unaccounted for, waits `lateCreateGraceMs` (3 s) and
399
+ sweeps once more. **Without a list tool this is impossible**: a tab whose
400
+ creation timed out cannot be found afterwards. `canList()` tells, and
401
+ `collect doctor` reports it.
402
+ - Cleanup survives cancellation: closing and listing use their own deadline
403
+ (`cleanupTimeoutMs`, 5 s) and ignore the run's `signal`.
404
+ - Pace: before each page action (open, evaluate, fetch, each scroll step) a
405
+ wait drawn between `pace.minMs` and `pace.maxMs` (defaults 2 s and 6 s;
406
+ `random` and `clock` are injectable). Reservations go through one queue, so
407
+ concurrent actions never share a slot. `waitFor` polls no faster than
408
+ `pace.pollMinMs` (500 ms), with a random extra up to `pollMaxMs`, and what is
409
+ left of its deadline bounds each poll.
410
+ - Page budget: `maxPages` (default 100) is reserved under the lock before a tab
411
+ is created (concurrent opens at the cap: exactly the free slots succeed) and
412
+ enforced at navigation boundaries: the navigation that would exceed it is
413
+ refused before it happens. Redirect
414
+ hops the browser followed and page transitions (a URL other than the expected
415
+ one after an action) are counted, so the next navigation can be refused.
416
+ - Challenges: after a navigation, after each evaluate, each scroll step, each
417
+ `waitFor` poll and the evaluation of each `fetchInPage`, and before acting on a page that moved to another URL,
418
+ the page is checked for a bot-check interstitial (`CHALLENGE_SCRIPT`): a
419
+ challenge form or running-check container, on a short page (under 3 000
420
+ characters of text) a turnstile or captcha widget or iframe (a normal article
421
+ can carry a captcha badge, so a long page is never judged on it), a title such as "Just a moment" or "Attention required", or a short
422
+ page (under 3 000 characters) that asks to verify the visitor, says the
423
+ browser is being checked or mentions a captcha. A fetched response is checked
424
+ the same way (`detectChallengeInBody`, `challengeInHeaders`). The error has
425
+ cause `challenge`, which the engine turns into a hard stop of the connector;
426
+ nothing is bypassed. A long article that talks about captchas is not a
427
+ challenge.
428
+ - Outward-facing URLs (the `url` of an error, the final URL of a fetch, `openPages()`) are scrubbed; the raw URL is used for navigation only.
429
+ - Read-only: the transport has no click, type or form operation, and
430
+ `fetchInPage` refuses anything but GET and HEAD.
431
+ - `probe()` (used by `collect doctor`): opens a probe tab, navigates it to a
432
+ safe `data:` URL, evaluates `1+1` in it and closes it. A probe tab that cannot
433
+ be closed is an error (the browser is not healthy), not something to swallow.
434
+
435
+ ### Trust boundary
436
+
437
+ `evaluate` runs the connector's own script in the page, so a connector can do
438
+ anything a script in that page can do. Connectors are trusted code: they are
439
+ written or reviewed by whoever runs them, and the transport is not a sandbox
440
+ for them. What the transport guarantees is the surface it exposes (no click,
441
+ type, fill or form helper, GET and HEAD only for `fetchInPage`, only tabs it
442
+ opened), and the read-only rule binds connector authors: a connector must
443
+ never open a compose or publish field, and must not use `evaluate` to submit,
444
+ post or change anything. Do not run a connector you do not trust against a
445
+ browser that holds a logged-in session.
446
+
447
+ A connector with `access: { level: "session", site }` may declare
448
+ `sessionCheck: { url, evaluate }`. `collect doctor` opens `url` and runs
449
+ `evaluate` (a function body) in the page, wrapped there: an exception is caught
450
+ in the page, and only one of three fixed codes leaves it: `open` (the body
451
+ returned exactly `true`), `none` (anything else) or `error` (it threw). The
452
+ report uses four fixed words, `open`, `none`, `unknown` and `error`, and never
453
+ repeats page text or error messages. A check must answer from what the page
454
+ shows, never return cookies or tokens.
455
+
456
+ ## Recipe sampling
457
+
458
+ `recipe.sampling` thins the candidate items a connector's `parse` returns from
459
+ listing or search tasks. Tasks of `kind: "read"` (an item fetched by URL) are
460
+ never sampled. Without a `sampling` block nothing changes.
461
+
462
+ ```yaml
463
+ sampling:
464
+ bands:
465
+ - { metric: views, min: 0, max: 999, quota: 50 }
466
+ - { min: 1000, max: 99999, quota: 50 } # metric omitted: the connector's primary counter
467
+ keepMissingMetric: false
468
+ perDomainCap: 2
469
+ seed: 42
470
+ ```
471
+
472
+ Steps, in this order, for each candidate:
473
+
474
+ 1. **Bands.** The candidate falls in the first band whose range contains its
475
+ counter value (`min` and `max` are both inclusive; either may be omitted).
476
+ The value comes from the observations the same parse returned for that item.
477
+ A candidate with no value for any band's counter is dropped with rule
478
+ `no_metric`, or kept outside every band when `keepMissingMetric` is true.
479
+ A candidate with a value that fits no band is dropped as `out_of_bands`.
480
+ A band keeps at most `quota` candidates (`band_quota` otherwise).
481
+ 2. **Per-domain cap.** At most `perDomainCap` kept items per host. The host is
482
+ the lower-cased hostname with a leading `www.` stripped (no public-suffix
483
+ list) of the item's canonical URL; for a `submission` it is the host of
484
+ `links.target` when that is a URL, else of the first `outboundLinks` entry,
485
+ so a submission counts against the article's site, not the aggregator's.
486
+ Beyond the cap the candidate is dropped as `domain_cap`. A candidate that
487
+ fails a rule does not use up the quota or cap of the other rule.
488
+ 3. **Seed.** When a quota or cap forces a choice, `seed` makes it
489
+ deterministic: within each task's candidates, a mulberry32 shuffle seeded
490
+ from `seed` and the task decides the order (candidates sorted by stable id
491
+ first), so the same recipe, seed and candidates give the same selection
492
+ whatever order the connector listed them in. Without a seed the first seen
493
+ in plan order is kept.
494
+
495
+ Quotas, caps and the seed are all per connector: two connectors in one recipe
496
+ each have their own band counters and their own per-domain counts.
497
+
498
+ **Guarantee.** Fetching and parsing run in parallel, but outcomes are committed
499
+ (sampling, dedup, writes) strictly in plan order (`order` of the task, a
500
+ follow-up task right after its parent). A terminal failure or skip releases its
501
+ turn; a task in transport fallback keeps it. So the kept set does not depend on
502
+ worker count, latency or which transport answered first: it is identical to a
503
+ `workers: 1` run.
504
+
505
+ Results held behind a slow task are bounded: a task is launched only while
506
+ fewer than `lookahead` tasks are live (default `4 * workers`, set it in the
507
+ recipe) and its slot is within `lookahead` positions of the commit cursor. The
508
+ head of the order and a task in transport fallback always launch, so the window
509
+ cannot stall a run. A connector stopped by a challenge commits nothing more:
510
+ work of it that was waiting for its turn or arrives late writes and samples
511
+ nothing, creates no follow-up task, and its task is recorded as skipped with
512
+ reason `challenge`. A cancelled run or a failed store stops further commits; a
513
+ task that was already the head when the run was cancelled still completes.
514
+
515
+ **Which candidates are sampled.** An item that already exists in the store
516
+ (same id or same canonical URL) is a known item: it is not sampled, uses no
517
+ quota or cap, and gets its new observation as usual. Among the new ones, a
518
+ repeated id and several ids sharing one canonical URL form one candidate, so
519
+ aliases cannot use several slots; it is decided on the member with the highest
520
+ counter (ties: smaller URL, then smaller id), and a later alias of a decided
521
+ candidate's own URL follows that decision without a line of its own.
522
+
523
+ Every distinct candidate gets exactly one line in `runs/<id>/sampling.jsonl`:
524
+ `candidate`, `decision` (`kept` or `dropped`), `rule` when dropped, `band`,
525
+ `url`, `domain`, `seed`, `connector`, `taskId`, `at`. A dropped candidate writes no
526
+ item, no observation, no pickup, no seen key, and no actor only it
527
+ referenced, and is not counted as new, so coverage counts kept items only.
528
+
529
+ A task's lines are written in one append (`appendSamplingBatch`) before any
530
+ counter moves; if that write fails the run stops with a run error and nothing of
531
+ that task is ingested. On `resume` the counters are rebuilt from
532
+ `sampling.jsonl`, and a task that has its decisions but is not `done` reuses
533
+ them by candidate id; a candidate that is new after the refetch is decided
534
+ fresh. A decision kept for a candidate that a changed page no longer returns
535
+ stays reserved against its quota or cap (accepted: the page changed between
536
+ attempts). The report adds, per connector,
537
+ `sampled: { candidates, kept, dropped: { [rule]: n } }`.
538
+
539
+ ## Per-connector API credentials, redaction, abort grace
540
+
541
+ - `transports.api` may be a factory `(connector) => HttpTransport`, called once
542
+ per connector and run, so each keyed connector carries its own credential
543
+ while a connector without a key can be given a plain transport.
544
+ - `recordSecrets(port)` wraps a `SecretsPort` and remembers every value it
545
+ resolves. Give the same recorder to the collector and to anything else that
546
+ resolves secrets (an API transport). The engine scrubs those values (raw,
547
+ percent-encoded, JSON-escaped; values of 4 characters or more) from events,
548
+ task records, plans, reports, `onEvent` payloads and the message of a
549
+ `CollectRunError`.
550
+ - Raw index entries carry `taskId` (`<connector>/<task id>`), so a stored raw
551
+ can be parsed again with the task that fetched it. The run record keeps
552
+ `connectorModules` when the host passes `connectorModules` to `run`.
553
+ - `abortGraceMs` (default 10000): after the signal aborts, tasks that never
554
+ settle (a connector that ignores the signal) are given up on after this
555
+ long. The run writes a warning event, releases the store lock and returns;
556
+ their tasks stay `started` (so `resume` redoes them) and their later writes
557
+ are refused.
558
+
559
+ ## Shipped connectors (`@agentproto/collect/connectors`)
560
+
561
+ Pure entry (no Node built-ins). `shippedConnectors` lists them; the `collect`
562
+ binary registers them by default.
563
+
564
+ ### `web`: an article read by its URL
565
+
566
+ Capability `read-by-url`; transports `http`, then `browser` (declared: the
567
+ engine records that no browser transport is available until one is supplied);
568
+ access `none`; no counters; default pace one request per second per host.
569
+
570
+ - **Plan.** One task per URL, with the canonical URL as task id and kind
571
+ `read` (never sampled). URLs come from `sources[].options.urls` (array of
572
+ strings) and from queries whose text is an http(s) URL (the query's subject
573
+ labels the item, `source.instance` becomes `sourceInstance`). An entry that
574
+ is not a URL becomes a task that fails visibly (cause `other`) instead of
575
+ being dropped. Other connectors queue articles with
576
+ `webTask(url, { subjects?, sourceInstance?, query?, from?, canonicalAliases?, maxInputBytes?, maxChars? })`, which gives
577
+ the same task id for the same canonical URL.
578
+ - **Fetch.** `http` with an HTML `Accept` header; the response `Content-Type`
579
+ is recorded with the raw (`contentType` on the raw index entry), and a
580
+ browser snapshot is stored as UTF-8 and marked so. A 2xx HTML page whose text
581
+ extraction is empty (a script-only shell, a redirect stub, a page that is
582
+ only links) throws an `empty` transport error with its body, so the raw is
583
+ kept and the engine falls back to the next transport. A verification page,
584
+ whether the transport flagged it or the page only looks like one (a marker
585
+ plus almost no content), is a `challenge`: over `http` it falls back, in the
586
+ browser it stops the connector, and it is never turned into an article. A
587
+ non-HTML content type (`application/pdf`, others) is stored as a raw (`pdf` or
588
+ `bin`) and yields no item. 401, 403 and 429 follow the transport's
589
+ classification.
590
+ - **Parse** (pure, replayable on stored raws): `extractArticle(html, url)`. The
591
+ HTML is read with `parse5` (spec-compliant tokenizing and the full entity
592
+ table; it is a plain JavaScript dependency of this package with no Node
593
+ built-ins, and already used by the monorepo's test tooling), then copied into
594
+ a bounded tree. A readability-style scorer works on it: paragraph density,
595
+ comma and length bonuses spread over every ancestor, class and id hints, a
596
+ link-density penalty, and removal of navigation, footers, asides, forms,
597
+ scripts, hidden elements, share bars, related lists, newsletter and paywall
598
+ prompts and comment threads, inside the article as well. Paragraph breaks are
599
+ kept (`\n\n`), `pre` blocks keep their lines, list items start with `- `.
600
+ - **Bounds.** The HTTP transport caps the download (10 MiB) and the whole body is stored; at most 5 MiB of it is decoded and read (`options.maxInputBytes`), 150 000
601
+ nodes are kept (deeper nesting is merged into its ancestor), 1 000 links,
602
+ and rendering stops at 200 000 characters (`options.maxChars`). Hitting a
603
+ bound sets `textTruncated` and a `note` in `ext` (`input_truncated`,
604
+ `node_cap`, `text_cap`, `link_cap`).
605
+ - **Encoding.** BOM, then the recorded `Content-Type` charset, then a
606
+ `<meta>` of the first bytes (comments and unrelated attributes ignored),
607
+ then UTF-8; a replay or `reparse` decodes the same way.
608
+ - title: `og:title`, then `<title>` (the site suffix is trimmed), then the
609
+ first `h1`;
610
+ - author: the page's JSON-LD article (found by its `url` or `@id`, or through
611
+ `mainEntity`; references by `@id` are resolved), `meta author`,
612
+ `article:author`, `rel=author`, `itemprop=author`, byline elements, then a
613
+ leading `By Name` line. A profile link is attached only when it belongs to
614
+ the chosen author;
615
+ - `publishedAt`: `article:published_time`, JSON-LD `datePublished`, other
616
+ date metas, then `<time datetime>`. Every candidate must be a real calendar
617
+ date (no February 30); a timestamp with no zone is read as UTC, never in the
618
+ host's zone, and a text date is only read when it names its zone;
619
+ - `language`: `html lang`, then `og:locale` (primary subtag);
620
+ - `canonicalUrl`: `link rel=canonical` only when it is on exactly the page's
621
+ own host (`www.` ignored), or on a host listed in
622
+ `options.canonicalAliases`; otherwise the cleaned final URL. The item id
623
+ is `web:` plus the hash of it. `url` stays the URL that was asked for;
624
+ the final URL after redirects only resolves links and the canonical URL;
625
+ - `outboundLinks`: links of the kept text only (`pre` blocks included),
626
+ resolved against `<base>`, absolute, canonical, de-duplicated, with
627
+ same-page anchors and self links removed;
628
+ - `wordCount`, `textTruncated`, `hasMedia`;
629
+ - the extraction is `ok` only with editorial evidence: at least 15 words, a
630
+ paragraph of real text with few links, and a text that is not mostly links.
631
+ - **Item.** `kind: article`, `source: web`, `contentId` from the text
632
+ fingerprint, `authorRef: web:<domain>/<author-slug>` with an `Actor` record
633
+ when an author is found, and `ext`:
634
+ `{ site, extractedAuthor?, extraction: "ok" | "empty" | "not_html" | "blocked", paywalled?, note? }`.
635
+ `extractArticle` returns the four statuses; only `ok` pages produce an item,
636
+ so an item's `ext.extraction` is always `ok` and the other statuses are the
637
+ reason no item was written. `paywalled` is set when the page's JSON-LD says the content is
638
+ not free.
639
+
640
+ ```sh
641
+ collect run --source web --subject docs --query https://example.com/post
642
+ ```
2
643
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.