# polite-crawler
**Fetch a source one time, keep it, and read it many times.** `polite-crawler` is a polite web crawler for research and for AI agents. It obeys robots.txt, sends one request at a time to each site, and keeps each response on your disk. Then it answers each later question from a local full-text index, with no new request.
[](https://www.npmjs.com/package/polite-crawler)
[](https://github.com/mark1russell7/crawler/actions/workflows/ci.yml)
[](https://github.com/mark1russell7/crawler/blob/main/LICENSE)
The site has interactive demos with the real code:
- **Polite.** The crawler obeys robots.txt (RFC 9309), and the rules for `Claude-User` too when an assistant asks. It sends one request at a time to each host and obeys `Retry-After`. A challenge, a 401, a 402 or a 403 stops the host for a time.
- **Fetch one time.** Each response goes into a capture log and a store of bodies by hash. A repeated question reads the disk, so it costs no request.
- **Read the cheap way.** The crawler reads JSON-LD, the visible text and the links with no browser. It opens a headless browser only for a page that shows almost nothing without JavaScript.
- **Cite exact text.** Full-text search (SQLite FTS5) gives ranked passages. A quote check finds the exact span in the stored text, with the capture id to cite.
- **An MCP server.** The package [`polite-crawler-mcp`](https://www.npmjs.com/package/polite-crawler-mcp) gives Claude and other MCP clients nine tools. They fetch, find, read and verify pages, check field values, discover and crawl a site, compare versions and list the watched pages.
- **Web archives.** An export writes the stored captures as WARC or WACZ. Archive tools read them, for example `warcio`, pywb and ReplayWeb.page.
- **Find and crawl a site.** `discover` lists the pages of a site from its sitemaps and feeds. `crawl` follows the links of a site within a budget, at the pace of the site.
- **Watch and compare.** `watch` checks pages again on a schedule and tells what changed. `diff` compares two versions, and `read` takes `at`: the page as it was at a time.
- **Archived copies, on request.** When a site refuses a page or is down, `fallback: "archive"` gives a copy from the Wayback Machine or Common Crawl. The result marks the copy as archived, with its date.
- **Signed requests.** With an Ed25519 key, the crawler signs each request (Web Bot Auth). A site can then verify that a request comes from your crawler.
- **Recipes.** `readVenue` reads the opening hours of a venue from its site, and `readProduct` reads a product page. `defineRecipe` makes a recipe of your own.
## Install
```sh
npm install polite-crawler
```
The package needs Node.js 22.19 or later. Older versions of Node.js 22 have no full-text search (FTS5) in their SQLite. For pages that need JavaScript, install the optional browser too:
```sh
npm install playwright-core
npx playwright-core install chromium-headless-shell
```
Without the browser, the crawler reads each page as plain HTML. It checks for the browser one time, so a page that needs JavaScript gets a note at once, with no wait.
Hybrid search (search by meaning and by words) is optional too. It uses a local model: transformers.js in the process (`npm install @huggingface/transformers`), or a local Ollama server. [Hybrid search](#hybrid-search) tells how.
The package is ESM only, and it includes its TypeScript declarations. It has these entry points:
| Entry point | What it gives | In a browser |
| --- | --- | --- |
| `polite-crawler` | `openCrawler`, and the parts of the runtime for an application | No. It needs Node.js. |
| `polite-crawler/robots` | The robots.txt parser and matcher | Yes |
| `polite-crawler/hours` | The opening-hours reader | Yes |
| `polite-crawler/html` | The page reader: JSON-LD, visible text and links | Yes. It contains linkedom and Readability, so it is the largest. |
| `polite-crawler/classify` | The outcome of a response | Yes |
| `polite-crawler/politeness` | The queue that keeps one request in progress for each host | Yes |
| `polite-crawler/signals` | The reader of usage signals (`Content-Signal`) | Yes |
| `polite-crawler/urls` | The canonical form of a URL, its cache key and its site. It imports no module. | Yes |
| `polite-crawler/text` | The decoder of a body in its declared encoding. It imports no module. | Yes |
| `polite-crawler/api` | The polite send of a documented API, with conditional polls and the OAuth 2.0 client credentials grant. [Send to a documented API](#send-to-a-documented-api) tells how. | Yes |
| `polite-crawler/pinned` | The download of a file that the client names by its SHA-256, from the mirrors first, at the pace of each host. [Download a pinned file](#download-a-pinned-file) tells how. | No. It needs Node.js. |
The entry points that work in a browser import no Node.js module. The package loads no MCP SDK and no `zod`: the MCP server is the package `polite-crawler-mcp`.
## Use it from the command line
```sh
npx polite-crawler fetch https://en.wikipedia.org/wiki/Web_crawler
npx polite-crawler find "robots exclusion"
npx polite-crawler read "url:https://en.wikipedia.org/wiki/Web_crawler" --length 2000
npx polite-crawler verify "url:https://en.wikipedia.org/wiki/Web_crawler" "robots.txt protocol"
npx polite-crawler extract "url:https://en.wikipedia.org/wiki/Web_crawler" --field "name=Web crawler"
```
The store is in `~/.polite-crawler`. Use `--dir` or `POLITE_CRAWLER_DIR` for a different folder. A path that starts with `~` is in your home folder, and a relative path starts at the working folder. Use `--json` for output that a program reads. `npx polite-crawler --help` shows all the options.
- `--allow-private` (or `POLITE_CRAWLER_ALLOW_PRIVATE=1`) lets the crawler fetch loopback, private and link-local addresses. By default, the crawler refuses them.
- `read --user-provided` reads a page that asked not to be AI input. Use it only for a URL that you gave yourself. The crawler records each such read.
- `--max-age 0` fetches a page again, also when the store has a copy.
- `fetch --archive-fallback` gives an archived copy when a site refuses a page or is down. [Archived copies after a refusal](#archived-copies-after-a-refusal) tells the rules.
- `--sign-key ` and `--signature-agent ` sign each request. `key-directory --sign-key ` prints the key directory to host. [Signed requests](#signed-requests-web-bot-auth) tells how.
- `find --rank fast` makes a long question faster, and its results can be different. [Fast ranking](#fast-ranking) gives the measured difference.
- `find --rank hybrid --embedder transformers` (or `--embedder ollama`) also finds the pages with a similar meaning. `embed --embedder ` gives vectors to each stored page first. [Hybrid search](#hybrid-search) tells the options.
- `reindex` builds the index again. The documents of a recipe that the command cannot read (the recipes of another application) stay. The output counts them, and the captures that it skipped.
- `export --out ` writes the stored captures as a WARC or a WACZ file. [Export to a web archive](#export-to-a-web-archive) tells what goes into the file.
- `extract --field name=value[:kind]` checks the values that you propose for the fields of a stored page. Repeat `--field` for each field. `--capture` checks the text of one capture, and `--at` the version that was current at a time. [Check field values against a page](#check-field-values-against-a-page) tells the statuses.
To find the pages of a site, or to fetch a part of a site, use `discover` and `crawl`:
```sh
npx polite-crawler discover https://example.com/
npx polite-crawler crawl https://example.com/ --max-pages 50 --max-depth 2 --budget 2m
```
- `discover` prints each URL of the sitemaps and feeds of the site, with its `lastmod`. `--max-urls` limits the list (the default is 1000), and `--feed ` reads one more feed.
- `crawl` prints each page when its fetch ends, and then a summary. The options are `--max-pages` (default 100), `--max-depth` (default 3) and `--budget` (default `10m`).
- `crawl` also takes `--include` and `--exclude` (patterns, which you can repeat), `--sitemaps`, `--render` and `--max-age`.
- `discover` and `crawl` take `--allow-host ` for more hosts. The first `Ctrl+C` stops a crawl, and the summary prints.
To read a page as it was, to compare two versions, or to watch pages, use `read --at`, `diff` and `watch`:
```sh
npx polite-crawler read "url:https://example.com/" --at 2026-10-01T12:00:00Z
npx polite-crawler diff "url:https://example.com/" --from 2026-10-01 --to fetch.5d41402abc4b
npx polite-crawler watch add https://example.com/hours --every 6h
npx polite-crawler watch run --budget 2m
npx polite-crawler watch list
```
- `read --at` and `verify --at` use the version that was current at that time. [Read a page as it was at a time](#read-a-page-as-it-was-at-a-time) gives the rules.
- `diff` prints the changed lines as a unified diff. A changed line marks its words with `[-removed-]` and `{+added+}`. `--from` and `--to` take a capture id or a time.
- `watch add` takes `--every` (1 hour or more, `24h` by default), `--confirm 1` or `2`, `--render`, `--scope` and `--label `.
- `watch run` takes `--budget` (default `10m`) and `--max-pages` (default 100). It prints each check, then a summary. A scheduler of the operator starts it.
- `daemon` checks the watch list on a schedule, until you stop it. With `--mcp-http`, it also serves the MCP tools over local HTTP. [The daemon](#the-daemon) tells how.
To read the hours of a venue or a product page, use `venue` and `product`. They use the recipes of the package:
```sh
npx polite-crawler venue https://forno-esempio.example/ --name "Forno Esempio" --pages 2
npx polite-crawler venue https://forno-esempio.example/ --compare kept-week.json
npx polite-crawler product "https://bottega-campione.example/products/olio-esempio?variant=222"
```
- `venue` prints the week of the site and each reading with its URL, its rank and its quote. It also prints the days where the readings disagree, the menus, the phone, the pages and the notes.
- `venue` takes `--name`, `--require-name`, `--address`, `--lat` and `--lon`, `--osm ` and `--pages <0-8>`. [Read the hours of a venue](#read-the-hours-of-a-venue) tells what each one does.
- Write a number below zero after `=`, for example `--lon=-20.5`. Else the command line reads it as an option.
- `venue --compare ` compares the week of the site with a week that you keep, as JSON. It prints `same`, `changed`, `new` or `not read` for each day. The file is a week, for example `{"mon": [["07:00", "15:00"]], "sun": []}`, or the `from_site` of `venue --json`.
- `product` prints the name, the brand, the SKU and the GTIN, and the price as money with the range of the offers. It also prints the availability, the variant, the seller, and a wall or a held-back page.
- The two commands take `--render`, `--max-age`, `--budget`, `--user-provided`, `--archive-fallback` and `--archive-despite-robots`. `--on-behalf-of ` applies the robots.txt rules of an agent too, for example `Claude-User`.
- `--json` prints the `VenueResult` or the `ProductResult` of the library.
The command gives these exit codes:
| Code | Meaning |
| --- | --- |
| `0` | The command did its work. |
| `1` | The command did not do its work: a page that the crawler did not fetch, no search result, a quote that is not in the document, a document that is not stored or that is held back, or an error. `discover` gives 1 when it finds no URL, and `crawl` when it gets no page. `read --at` and `verify --at` give 1 for a time before the first capture. `watch run` gives 1 when a check is `refused` or an `error`, or when entries stay due. `watch remove` gives 1 for a URL that is not on the list. With `--archive-fallback`, a page with an archived copy counts as done. `extract` gives 1 when a field is not `verified` or `normalized`. `embed` gives 1 when its budget stops it before each page has vectors. |
| `2` | The command line is wrong. The command opens no store. |
| `3` | `venue` and `product` read nothing: no opening hours of the site or no Product data, a page that is held back, or a page that did not come. |
| `4` | `venue` and `product`: the site refused the crawler (a wall). The causes are a 401, a 402 or a 403, a challenge, a bot check, robots.txt or a stop of the host. The crawler does not try a different identity. |
## Use it from Claude (MCP)
The MCP server is the package [`polite-crawler-mcp`](https://www.npmjs.com/package/polite-crawler-mcp). It gives nine tools over the same store as the command line. Add it to Claude Code:
```sh
claude mcp add polite-crawler -- npx -y polite-crawler-mcp
```
Its README tells the tools, the envelope of the page text, the pages that refuse AI input and the options of the server.
Until 0.2.0, the server was the entry point `polite-crawler/mcp` and the command `polite-crawler mcp`. The command still starts the server in 0.2.x when `polite-crawler-mcp` is installed next to polite-crawler, with a note that it is deprecated. Without the package, it tells you to start `npx polite-crawler-mcp`, and it exits with 2. Version 0.3.0 removes the command.
## Use it as a library
```ts
import { openCrawler } from "polite-crawler";
const crawler = openCrawler({ dir: "./crawl", contact: "ops@example.com" });
const page = await crawler.fetch("https://example.com/", { maxAge: "24h" });
console.log(page.outcome, page.title, page.capture, page.fetched_at, page.from_cache);
for (const hit of await crawler.find('"documentation examples"')) console.log(hit.doc, hit.snippet);
const read = await crawler.read(page.doc!, { length: 2000 });
const check = await crawler.verify(page.doc!, "for use in documentation examples");
// later, after a new fetch: the quote is still in the capture that the citation names
const cited = await crawler.verify(page.doc!, "for use in documentation examples", {
capture: check.capture!,
});
await crawler.close();
```
- Each method gives a promise, `find` and `verify` too.
- A result of `fetch` gives `capture`, `fetched_at` and `from_cache`. A result of `read` gives the `capture` and the `fetched_at` of its text.
- `verify` gives the `capture`, the `blob` and the `fetched_at` of the text that holds the quote, with the positions in that text. `stale` is true when only an earlier capture holds the quote.
- `read` and `verify` take `capture`: they then use the text of that capture, not the current text. A citation of a capture thus stays true after the page changes.
- `extract` checks the values that you propose for the fields of a page, and gives the span and the capture of each value. [Check field values against a page](#check-field-values-against-a-page) tells how.
- `versions(doc)` gives the versions of a document, the newest first.
- `read` and `verify` take `at`: the version that was current at that time. [Read a page as it was at a time](#read-a-page-as-it-was-at-a-time) tells the rules.
- `diff(doc, { from, to })` compares two versions. [Compare two versions](#compare-two-versions) tells what it gives.
- `watch` is the watch list: `add`, `remove`, `list` and `run`. [Watch pages](#watch-pages) tells the rules.
- `find` reads a query syntax. Text in double quotes is a phrase, and `bake*` is a prefix. The documents that hold each word come first. Case, accents and Unicode forms do not change a match, and Chinese, Japanese and Thai words match too.
- `find` takes `rank`. The default is `exact`, and `fast` makes a long question faster. [Fast ranking](#fast-ranking) tells the difference. `hybrid` also finds by meaning, with the option `embedder` of `openCrawler`. [Hybrid search](#hybrid-search) tells how.
- A page that asks not to be AI input is held back in each result. `fetch` gives no title, and `read` gives no title, no text and only the structural metadata. `verify` gives `found: false`, and `find` leaves the page out. Only `userProvided` lifts the hold, and the crawler logs it.
- The hold applies to each version too. When a later capture does not ask it, the current text is not held back, but the earlier versions that asked it stay held back. `verify` with no `capture` does not examine them, `read` and `verify` of their capture hold them back, and `versions` shows no title for them.
### Fast ranking
The default ranking (`rank: "exact"`) gives a BM25 score to each document that matches. A long question is the slowest search, because its common words match almost each document. `rank: "fast"` changes only the second part of a search, the documents that hold one word of the question:
- It leaves out each word that more than 20 percent of the documents hold (`FAST_RANK_SHARE`). When each word is that common, the rarest word stays.
- A document that holds only common words is not in that part of the results. The common words do not add to the score of that part.
- The documents that hold each word come first in the two modes, with the same rank.
The command line has `find --rank fast`, and the tool `crawl_find` has the parameter `rank`. `DocIndex.rankWithin` takes `{ rank: "fast" }` too. It then leaves out each document that holds only common words.
The benchmark `bench/find.mts` measured the two modes in CI ([the results](https://github.com/mark1russell7/crawler/actions/runs/39057146797)). The index had 30,000 documents of 900 words, with a Zipf spread of the words. Each time is the median of 12 questions on Node.js 24:
| Search | `exact` | `fast` | Speed | Same top 10 | Same order |
| --- | ---: | ---: | ---: | ---: | ---: |
| `find`, 1 word | 3.5 ms | 3.4 ms | 1.0 times | 100 % | 1.00 |
| `find`, 4 words | 4.4 ms | 4.7 ms | 0.9 times | 98 % | 1.00 |
| `find`, 16 words | 37 ms | 15 ms | 2.5 times | 85 % | 0.62 |
| `rankWithin` of 40,000 ids, 16 words | 87 ms | 39 ms | 2.2 times | 85 % | 0.62 |
- "Same top 10" is the share of the exact top 10 that `fast` also gives (overlap at 10). "Same order" is the Kendall tau of the documents that the two lists share. A value of 1 is the same order.
- In the corpus of the review, almost each word is in almost each document. There, `fast` was 2.2 times faster for 16 words, but its top 10 had only 43 percent of the exact top 10.
- For 16 words, `rankWithin` with `fast` gave 22 percent of the documents that `exact` gave.
Use `fast` only when the speed of a long question is more important than its exact rank. To measure again, start the workflow `bench.yml`.
The MCP server is the package `polite-crawler-mcp`:
```ts
import { openCrawler } from "polite-crawler";
import { createMcpServer, startMcpServer } from "polite-crawler-mcp";
await startMcpServer({ dir: "./crawl" }); // standard input and output
const server = createMcpServer(openCrawler({ dir: "./crawl" }), { onBehalfOf: ["Claude-User"] });
```
`createMcpServer` takes these options: `onBehalfOf` (the default is `["Claude-User"]`), `allowUserProvided` (the opt-in of the operator) and `renderOff` (the reason for a server with no browser).
The root entry point also exports the parts of the runtime, for an application that builds its own:
- `createRuntime`: the parts of a store, made in one place. `openCrawler` uses it. Give `dir`, or your own `log`, `blobs` and `index` (any `ReadingIndex`).
- `catchUpIndex(runtime)`: the step of `openCrawler` at open. It rebuilds a stale index, and gives an index that is behind the log the captures that it missed. Use it after `createRuntime`.
- `Crawler`, `CaptureLog`, `DocIndex`, `FileBlobStore`, `SqliteHostStateStore`, `Extractors`, `fetchAndIndex`, `fetchPage` and `reindex`.
- `readDocument`, `verifyQuote`, `findDocuments`, `isHeldBack`, `heldBackMeta` and `recordOverride`: the read, the verification and the rule for a held-back page, over a runtime.
- `extractDocument` and `checkFields`: the check of field values over a runtime, and over a text and its metadata with no store.
- `extractPage`, `typesOf`, `decodeBody` and `bodyEncoding`: the page reader and the decoder of a body in its declared encoding.
- `readPdf` and `isPdf`: the PDF reader. `PdfOptions` sets limits on the pages, the characters, the time and the inflated bytes.
- `fromText`, `fromSchemaOrg`, `fromCompact` and `describeWeek`: the opening-hours reader. `compareHours` compares a reading with a week that you keep.
- `parseRobots` and `decide`: the robots.txt parser and matcher.
- `RenderRefused`: the error of a renderer that did not render a page, with the reason `refused`, `download`, `scheme` or `browser`. A crawler does not count it as a failure of the host. After the reason `browser`, the crawler renders no more pages.
The readers give more facts than before:
- `PageExtract` has `canonical` (the canonical URL on the same site), `redirect` (the target of a quick ``), `blocked` (the name of a bot check or a firewall that sent its page in place of the content) and `notes` (what the reader left out).
- `PageExtract` also has `feeds` (the RSS and Atom feeds that the page links). `extractPage` always gives it. The field is optional, so a `PageExtract` of 0.1.1 stays correct.
- `Hours` has `partial` (the reader left out a rule or a line) and `season` (the season or the dates of the hours). The text reader reads English only.
### The options of `Crawler`
`CrawlerOptions` has these options for the policy:
- `egress`: the addresses that the crawler fetches. By default, the crawler fetches only public addresses. Set `allowPrivate: true` for loopback, private and link-local addresses, or name hosts and ranges in `allowHosts`. With a dispatcher of your own, put `egressLookup` in its connection options.
- `politeness`: the limits of the policy, for each host or for some hosts (`hosts: { "*.example.org": { pageIntervalMs: 10_000 } }`). `DEFAULT_POLICY` has the defaults. A value that is not valid throws a `RangeError`.
- `hostState`: the store of the pace, the counts, the stops and the validator memo of each host (`HostStateStore`). The default keeps them in memory (`MemoryHostStateStore`). `SqliteHostStateStore` keeps them in a file that processes share.
- `onEvent`: a function that gets an event for each request, response, wait, stop and skip.
- `obeyDefaultToken`: a crawler with a token of your own also obeys the group of `PoliteCrawler` when its `User-Agent` links the bot page of polite-crawler. Site owners read that page. The stricter rules apply. Set false when you host a bot page of your own.
- `maxRenders`: the pages that the browser renders at one time. The default is 2, because each render holds a browser context. A render waits for a slot before the lease of its host, so the wait is not time of the host.
- `signer`: the signer of each request (Web Bot Auth). [Signed requests](#signed-requests-web-bot-auth) tells its options.
- `scope`, `labels` and `scopeRank`: the labels of each record. One fetch of a robots.txt can serve requests of different scopes. Its record takes the labels of each request and the scope with the highest `scopeRank`, the most private one.
`openCrawler` takes `egress`, `politeness` and `hostState` too, and also `clock`, `scope`, `onEvent`, `extractors` and `recipes` ([the recipes of an application](#writing-a-recipe)). Its default `hostState` is the file `hosts.sqlite` in the store. Thus the processes on one store share the pace, the stops and the validator memo of each host.
`FetchRequest.maxAgeMs` can be `"auto"`: the crawler then uses the freshness that the server gave (`Cache-Control`, `Expires`, or 10 percent of the age of `Last-Modified`). `crawler.resetHosts(host?)` removes the stops and the failure counts of one host or of each host, for a process that runs for a long time.
### Which parts are stable
Before version 1.0.0, a minor version can change the API, and `CHANGELOG.md` tells what to change. Some parts change only for a strong reason. Other parts are the engine, and they change more often. The declaration of each part of the engine has the TSDoc tag `@beta`, so your editor shows it. [The API review](https://github.com/mark1russell7/crawler/blob/main/docs/API-REVIEW.md) gives the tier of each export.
These parts are the stable API:
- `openCrawler` and the methods of `PoliteCrawler`: `fetch`, `find`, `read`, `verify`, `versions`, `discover`, `crawl`, `reindex`, `close`, `diff`, `watch` and `extract`. `openCrawler` gives an `OpenedCrawler`: a `PoliteCrawler` that has `discover`, `crawl`, `diff`, `watch` and `extract`. The five are optional in `PoliteCrawler`, so an object of your own that implements it stays correct.
- The options of `openCrawler`: `OpenOptions` and `RuntimeOptions`, which `OpenOptions` extends, with `Extractor` and `ExtractedDoc` for the option `extractors` and `CrawlEvent` and `FetchOutcome` for `onEvent`. The options `log`, `blobs`, `index` and `renderer` of `RuntimeOptions` and the member `PoliteCrawler.runtime` are the engine.
- The interfaces of the store on disk: `CaptureRecord`, `CaptureReader`, `CaptureFilter`, `ScanOptions`, `DamagedLine` and `BlobStore`.
- The options and the results of these methods: `OpenOptions`, `FetchOptions`, `PageResult`, `Found`, `ReadResult`, `VerifyResult`, `DocVersion` and `ReindexResult`. `at` of `ReadOptions` and `VerifyOptions`, and `at` and `before_first` of their results, are stable too.
- The options and the results of `extract`: `ExtractOptions`, `ExtractResult`, `ExtractSummary`, `FieldClaim`, `FieldKind`, `FieldStatus`, `FieldResult`, `FieldSpan` and `FieldCandidate`, with the names of the normalizations.
- The diff: `diffTexts`, `DIFF_LIMITS`, `DiffOptions`, `DiffResult`, `DiffSide`, `DiffSummary`, `DiffHunk`, `DiffLine`, `WordPart`, `MetaChange`, `VersionChoice`, `DiffLimits`, `DiffInput` and `TextDiff`.
- The time travel: `isoTime` and `VersionAt`.
- The watch list: `WatchList`, `WatchOptions`, `WatchEntry`, `WatchPending`, `WatchKind`, `WatchRun`, `WatchRunOptions`, `WatchEvent`, `WatchSummary`, `WatchStop`, `WATCH_LIMITS` and the file `watch.sqlite` (`WATCH_SCHEMA`).
- The daemon: `startDaemon`, `scheduleWatches`, `changeCommand`, `readDaemonState`, `daemonStateFile`, `DAEMON_DEFAULTS`, their options and results, and the state file (`DAEMON_STATE_SCHEMA`). The MCP seam of the daemon is the engine: `DaemonMcpHooks`, `DaemonMcpHost`, `DaemonMcpOptions`, `DaemonMcpService`, the options `mcp` and `mcpHost`, and `Daemon.mcp`. The MCP server of the daemon is `mcpHttpHost` of `polite-crawler-mcp`.
- The options and the results of `discover` and `crawl`: `DiscoverOptions`, `DiscoverResult`, `DiscoveredUrl`, `DiscoverSource`, `DiscoverStop`, `CrawlOptions`, `CrawlRun`, `CrawlPage`, `CrawlSummary`, `CrawlStop`, `UrlPattern` and `ScopeOptions`.
- The readers: `polite-crawler/robots`, `/hours`, `/html`, `/classify`, `/politeness`, `/signals`, `/urls` and `/text`. The site and its tools use them in the browser.
- The command line, its exit codes, the store on disk and `polite-crawler/record.schema.json`.
- The export: `exportWarc` and `exportWacz`, their options (`ArchiveOptions`, `ArchiveFilter`, `ArchiveSource`), their results (`WarcResult`, `WaczResult`, `ArchiveCounts`) and the records of the archive.
- The archived fallback: `fallback` and `archiveDespiteRobots` of `FetchOptions`, the field `archived` of the results, and the types `Archived` and `WebArchive`.
- Signed requests: `createWebBotAuthSigner`, `keyDirectory`, `verifySignature`, `KEY_DIRECTORY_PATH`, `KEY_DIRECTORY_TYPE`, the option `signer`, and the types `WebBotAuthOptions`, `WebBotAuthSigner`, `RequestSigner`, `KeyDirectory`, `DirectoryKey`, `KeyInput`, `SignatureAgentType`, `SignedRequest` and `SignatureCheck`.
- The headers of a signature follow the draft. When the draft changes, the headers change with it, and `CHANGELOG.md` says so.
- Hybrid search: the option `embedder` of `OpenOptions`, the interface `Embedder` (the extension point) with `EmbedCallOptions`, and the adapters `transformersEmbedder` and `ollamaEmbedder` with their options (`TransformersEmbedderOptions`, `OllamaEmbedderOptions`, `Pooling`, `EmbeddingModel`).
- Also stable: `HybridCrawler` (the result of `openCrawler`), `rank: "hybrid"` (`SearchRank`, `SearchOptions`), `embed`, `rankWithin` with `RankOptions` and `Ranked`, and `hybrid` (`HybridSearch`). The three members are optional in `PoliteCrawler`, and `OpenedCrawler` does not change.
- The options and the results of hybrid search are stable too: `HybridOptions`, `HybridFindOptions`, `EmbedOptions`, `EmbedResult`, `EmbedStop`, `Passage` and `Found.passage`. So are `HYBRID_DEFAULTS`, `OLLAMA_MODELS`, `TRANSFORMERS_MODELS`, `NO_EMBEDDER`, `NO_OLLAMA` and `NO_TRANSFORMERS`.
- The recipe SDK: `defineRecipe`, `runRecipe`, `readJson`, the option `recipes` of `openCrawler` and `createRuntime`, and `RESERVED_RECIPES`. Its types are `Recipe`, `RecipeDefinition`, `RecipeExtract`, `RecipeCapture`, `RecipeRequest`, `RecipeRequestOptions`, `RecipeRunOptions`, `RecipeResult`, `RecipeDoc` and `RecipeTarget`.
- The recipes: `readVenue`, `venueReadingsOf`, `compareHours`, `readProduct` and `productOf`. Their options and results are stable too: `VenueOptions`, `VenueResult`, `VenueReading`, `VenuePage`, `VenueLink`, `VenueLocation`, `VenueOsm`, `VenueSource`, `VenueRead`, `HoursComparison`, `ProductOptions`, `ProductResult`, `ProductRead`, `ProductVariant` and `Money`.
The other exports of the root entry point are the engine. Examples are `createRuntime`, `catchUpIndex`, `Crawler`, `CaptureLog`, `DocIndex`, `FileBlobStore`, `SqliteHostStateStore`, `Extractors`, `fetchAndIndex` and `makeRecord`. An application can build on them. A minor version before 1.0.0 can change them, and its section in `CHANGELOG.md` says so.
The engine of the check of fields is `checkFields`, `extractDocument`, `FIELD_KINDS`, `ExtractSource` and `FieldsChecked`.
The engine of discovery and of the crawl is `discoverSite`, `crawlSite`, `readSitemap`, `feedDate`, `DISCOVER_LIMITS`, `CRAWL_LIMITS`, `SITEMAP_LIMITS` and `DEADLINE_NOTE`. It also includes `Crawler.robotsAllow` and the `deadline` of `FetchRequest`, `RenderRequest` and `PageOptions`.
The engine of the time travel, the diff and the watch list is `versionAtTime`, `diffDocument`, `WatchStore`, `WatchStoreOptions`, `runWatch`, `WatchRunnerOptions` and `WatchRescheduleOptions`. It also includes the optional method `ReadingIndex.versionAt`, `DocIndex.versionAt` and `Crawler.hostStop`, the optional method `WatchList.reschedule` and the option `keepSchedule` of `WatchOptions`. Each of these functions operates on a runtime of your own. The methods `diff`, `read` with `at` and `watch` of the crawler are the stable way.
The engine of hybrid search is `createHybridSearch`, `HybridSearchOptions`, `VectorStore`, `VECTORS_SCHEMA` and the types of the vector store. It also includes `chunkText`, `chunkTokensOf`, `estimateTokens`, `CHUNK_LIMITS`, `fuseRanks`, `unitVector`, `isLoopback`, `FeatureExtractor`, `TransformersModule`, the optional method `ReadingIndex.digests` and `DocIndex.digests`. The file `vectors.sqlite` is a projection, as the index is: it is not part of the stable store.
The engine of the recipes is `registerRecipe`, `rankHoursLinks`, `chooseVenueReadings`, `namesVenue`, `locationMatches`, `pickProduct`, `pickVariant`, `readAmount`, `VENUE_LIMITS`, `PRODUCT_LIMITS`, `RECIPE_LIMITS` and the `steps` of `VenueRead` and `ProductRead`. The words that rank a link or a label are the engine too, so a version can improve them.
The engine of the archived fallback and of the signatures is `archiveExtractor`, `archivedDocId`, and the `fallback` and `archiveDespiteRobots` of `PageOptions`. It also includes `range`, `signalLines` and `originalHeaderPrefix` of `FetchRequest`, `ai_input` of `ExtractedDoc`, `sign` of `RenderOptions` and `signer` of `CrawlerOptions`.
Each export of `polite-crawler/api` is the engine too. This includes the reaction of the crawler: `outcomeResult` and `reactToOutcome`, with `OutcomeFacts`, `ReactionContext` and `HostReaction`.
Version 0.2.0 removed five exports from the root entry point: `checkedRenderer`, `renderedKey`, `pageDocId`, `renderAndIndex` and `pageExtractor`. No documented use needed them. `durationMs` stays in the engine, because `polite-crawler-mcp` uses it.
## Hybrid search
Hybrid search finds the pages that hold the words of a question, and also the pages with a similar meaning. It is opt-in: the default ranking stays exact BM25.
```ts
import { openCrawler, transformersEmbedder } from "polite-crawler";
const crawler = openCrawler({ dir: "./crawl", embedder: transformersEmbedder() });
await crawler.embed({ budget: "10m" }); // vectors for each stored page
for (const hit of await crawler.find("a loaf with a dark crust", { rank: "hybrid" })) {
console.log(hit.doc, hit.score, hit.passage, hit.snippet);
}
```
- `rank: "hybrid"` needs an embedder. Without one, the search rejects with `NO_EMBEDDER`. It does not change to BM25 in silence.
- `crawler.rankWithin(q, docs, { rank: "hybrid" })` ranks a set of stored documents in the same way.
- `openCrawler` gives a `HybridCrawler`: an `OpenedCrawler` with `hybrid`, `embed` and `rankWithin`, and a `find` that takes `rank: "hybrid"`.
- The command line has `--embedder`, `find --rank hybrid` and `embed`. The MCP tool `crawl_find` takes `rank: "hybrid"` when the server has an embedder.
```sh
npx polite-crawler embed --embedder ollama --budget 30m
npx polite-crawler find "a loaf with a dark crust" --rank hybrid --embedder ollama
```
### transformers.js
This embedder uses the model in the process of the crawler. The package `@huggingface/transformers` is an optional peer, and the embedder loads it at its first text.
```sh
npm install @huggingface/transformers
```
```ts
import { transformersEmbedder } from "polite-crawler";
const embedder = transformersEmbedder({ model: "Xenova/bge-small-en-v1.5", quantized: true });
```
- The default model is `Xenova/bge-small-en-v1.5`: 384 dimensions and an input of 512 tokens. The 8-bit model (`quantized: true`, the default) is approximately 34 MB.
- The first use downloads the model from the Hugging Face Hub (`huggingface.co`). This download does not go through the polite crawler, so robots.txt, the pace and the capture log do not apply to it.
- transformers.js keeps the files in `cacheDir`. Its default is `node_modules/@huggingface/transformers/.cache/`. The command line uses `/models`. With `localOnly: true`, the embedder uses only the cache and downloads nothing.
- The embedder pools the vectors of the tokens as the model expects: `cls` for BGE and `mean` for the other models. The option `pooling` changes it.
### Ollama
This embedder sends the texts to a local Ollama server (`POST /api/embed`). The package has no dependency for it.
1. Install Ollama from , and start it with `ollama serve`.
2. Pull a model: `ollama pull nomic-embed-text`.
```ts
import { ollamaEmbedder } from "polite-crawler";
const embedder = ollamaEmbedder({ model: "nomic-embed-text", baseUrl: "http://127.0.0.1:11434" });
```
| Model | Size | Dimensions | Input in tokens |
| --- | ---: | ---: | ---: |
| `nomic-embed-text` (the default) | approximately 274 MB | 768 | 8,192 |
| `all-minilm` | approximately 46 MB | 384 | 256 |
| `mxbai-embed-large` | approximately 670 MB | 1,024 | 512 |
- The embedder sends 32 texts in each request (`batch`). It adds the prefixes that `nomic-embed-text` and `mxbai-embed-large` expect.
- An error tells what to do: `ollama serve` when no server answers, and `ollama pull ` when the model is not there.
- The embedder accepts only a server on this computer (a loopback address). `allowRemote: true` (`--allow-remote-ollama`) permits a different computer.
### An embedder of your own
An application can give an embedder of its own, as it can give a renderer:
```ts
import type { Embedder } from "polite-crawler";
const embedder: Embedder = {
id: "my-model-v1", // the model and its version: the store keeps it with each vector
dimensions: 384,
maxInputTokens: 512,
embed: async (texts, { signal, purpose }) => myModel.embed(texts, { signal, purpose }),
};
```
`purpose` is `"document"` for the chunks of a page and `"query"` for a question. Give a new `id` when the vectors of the model change.
### What goes where
- The embedder gets the text of the stored pages and the words of each question. With transformers.js, the text stays in the process. With Ollama, the text goes to the Ollama server.
- A page that asks not to be AI input does not go to the embedder, and no hybrid result gives it. The rule applies to each version, as for `find`.
- Only the download of a transformers.js model goes to the internet, to the Hugging Face Hub.
### How a hybrid search ranks
1. Full-text search gives the BM25 candidates (`candidates`, 50 by default). A candidate whose text has no vectors gets them first.
2. The vector search gives the documents with the closest chunks (`neighbors`, 50 by default). It compares the vector of the question with each stored vector (a brute-force cosine).
3. Reciprocal rank fusion makes one list. Each document gets the sum of 1 / (k + rank) over the two lists, with the rank from 1. The constant k is `fusionK`, 60 by default.
- The snippet and the `passage` of each hit come from its best chunk. `passage.start` and `passage.end` are positions in the text of the capture of the hit, for `read`.
- A search gives vectors only to its candidates. Thus a page with the meaning and none of the words comes back only after `embed` gave it vectors.
- `embed` takes `budget` (`10m` by default), `maxDocs` and `kind`. Start it again to continue: it does not send a text with vectors again.
- `find` and `rankWithin` take `candidates`, `neighbors`, `fusionK` and `signal`. `HYBRID_DEFAULTS` has the defaults.
### Chunks and storage
- A chunk is a window of whole sentences. It ends at the end of a paragraph when it can, and a longer sentence is cut at its spaces.
- A chunk has the input limit of the model in tokens with a margin of 10 percent, and 512 tokens at most. Two chunks next to each other share approximately 10 percent of their tokens. A text gives 64 chunks at most.
- The vectors go into `vectors.sqlite` in the store. The key of a row is the SHA-256 of the text, the number of the chunk and the `id` of the embedder. Thus a reindex keeps each vector, and the same text gets its vectors one time for each model.
- The file is a projection, as `index.sqlite` is. Delete it, and `embed` makes the vectors again.
- A vector takes 4 bytes for each dimension: 1.5 KiB for 384 dimensions and 3 KiB for 768. With the keys and the indexes of SQLite, a chunk of 384 dimensions took 2.4 KiB of the file in the benchmark.
- The first hybrid search reads the vectors of the embedder into memory. Thus the memory is approximately the size of the vectors.
The benchmark `bench/find.mts --hybrid` measured the time in CI ([the results](https://github.com/mark1russell7/crawler/actions/runs/39082851222)). A fake embedder of almost no cost gave the vectors, so the time of a real model comes on top. The index had 30,000 documents of 900 words, which gave 89,100 chunks of 384 dimensions. Each time is the median of 12 questions on Node.js 24:
| Step | Time |
| --- | ---: |
| The cosine of a question and each of the 89,100 vectors | 82 ms |
| `find`, `rank: "hybrid"`, 1 word | 88 ms |
| `find`, `rank: "hybrid"`, 16 words | 122 ms |
| `rankWithin` of 40,000 ids, `rank: "hybrid"`, 16 words | 528 ms |
| The first search: it reads 131 MiB of vectors into memory | 714 ms |
| `embed` of the 30,000 documents, with no time for a model | 17 s |
- The brute-force cosine is linear in the number of chunks. It is a good fit up to approximately 100,000 chunks (approximately 30,000 pages of this size). A search then takes approximately 0.1 s, and the vectors take approximately 150 MiB of memory at 384 dimensions.
- One million chunks take approximately 1 s for each search and 1.5 GiB of memory. A larger store needs an index of the vectors, and the package does not have one.
- `vectors.sqlite` was 210 MiB for the 89,100 chunks.
## Read a page as it was at a time
Each capture of a document is a version, and the index keeps each version. `read` and `verify` take `at`, a time. They then use the version that was current at that time.
```ts
const then = await crawler.read("url:https://example.com/", { at: "2026-10-01T12:00:00Z" });
console.log(then.capture, then.fetched_at, then.before_first, then.text);
const check = await crawler.verify("url:https://example.com/", "open on Sundays", { at: new Date("2026-10-01") });
```
- `at` is an ISO 8601 text or a `Date`. A date with no time is the start of that day in UTC.
- The rules that choose the current version apply to the versions of that time. Thus a render stays current while the plain body under it stays the same, and the richer recipe wins.
- The result names the `capture` and the `fetched_at` of the version, and it gives `at`.
- When `at` is before the first capture, no version answers. `before_first` is true, and the note gives the time of the first capture. `read` then gives no text, and `verify` gives `found: false`.
- `verify` with `at` examines that version only, as `verify` with `capture` does. A match is not `stale`.
- Give `capture` or `at`, not the two. The two together are an error.
- The hold of a page that asked not to be AI input applies as before. A version that was held back at that time stays held back. When the document is held back at this time, each of its versions is held back too.
- The command line has `read --at