Skip to content

Incremental engine for long horizon agents 🌟 Star if you like it!

feat(examples): CocoIndex Agents researches a topic on the web (#2833)

Jiangzhou26d494bcec51
diff --git a/examples/cocoindex_agents/DESIGN.md b/examples/cocoindex_agents/DESIGN.md
index e53a9afc..8a578566 100644
--- a/examples/cocoindex_agents/DESIGN.md
+++ b/examples/cocoindex_agents/DESIGN.md
@@ -19,7 +19,11 @@ become its own repository, so it is more elaborate than the other examples.
It was called coco-harness until 2026-11-05. Amended 2026-11-05 for
documents the model reads natively (Β§3, *Documents*), with the `orders` flow,
and the same day for a Google Drive folder as a source (Β§3, *Sources: a
-Google Drive folder*; Β§7), with the `drive` flow.
+Google Drive folder*; Β§7), with the `drive` flow. Amended 2026-11-21 for the
+web as a source (Β§0, *Vocabulary*; Β§3, *Sources: the web*; Β§5, *Search*; Β§7;
+Β§8), with the `research` flow, after an owner's review of the abstraction
+and four rounds of an independent design review (the proposal's history is
+in git under `flows/research/`).
---
@@ -55,6 +59,23 @@ prompt should be written.
`child/<key>`).
- **Handle**: a stable name for a live object (`src:docs`), with a **card**
listing its methods.
+- **Resource**: one thing a worker can read whole β€” a local file, a Drive
+ file, a web page β€” with an **identity** that is global within its kind's
+ space (root plus path; account plus folder plus path; the canonical final
+ URL), a **content state** its memo state carries (mtime and digest;
+ `modifiedTime` and MD5; a content digest), and one way to be read. The
+ engine's `FileLike` (`cocoindex.resources.file`) is the contract.
+- **Listing**: how a session *finds* resources β€” walking a folder, running
+ searches, taking a list of URLs. Session-local, recorded as an
+ observation; two listings may yield the same resource.
+- **Source**: a `src:` handle, a listing with four methods (`stats`,
+ `sample`, `read`, `keys`). A **kind** is a listing kind and names the
+ resources it yields: `localfs` and `google_drive` list files; `web_search`
+ and `web_pages` list pages. A folder fuses container and listing; a search
+ is a listing over a space it does not own.
+- **Item**: one listed resource under a source-local key, `Item(key,
+ resource)`, the unit of a `for_each`. Cards and tool descriptions say
+ *item*, never *file*, since 2026-11-21.
- **Transcript**: the canonical sequence of (model output, tool results) of
one session; **`prev`** is the one stored by the last successful run.
- **Scratch**: a run-local channel from a turn back to the session loop (Β§4).
@@ -100,12 +121,24 @@ Two engine facts shape the design:
| **B. Map β†’ reduce β†’ answer** | "What do 2,000 interview notes say about pricing? Write report.md with quotes." | `for_each(collect)`, `reduce`, `declare(value=res:…)` |
| **C. Observe β†’ plan β†’ map** | "Turn this folder of invoices into a table; figure out the columns." | `observe(inputs=[src])`, `for_each` |
| **D. Group-by reduce** | "Per person, list open action items across all meeting notes." | `for_each`, `reduce` with a grouping step (target, Β§8) |
+| **E. Search β†’ read β†’ follow β†’ report** | "What is incremental computation and where is it used? Search the web, read what you find, follow the leads worth following, and write `./out/report.md` with citations." | `open_source(kind="web_search", queries=…)`, `for_each(collect)`, `reduce(key="leads")`, `open_source(kind="web_pages", urls=["res:leads"])`, `for_each(collect)`, `reduce(key="report", collection=[…])`, `declare(value="res:report")` |
What reruns after a change is defined once, in Β§7 (reuse model) and Β§6
(reduce locality); the shapes above only pick tools. A shape does not depend
on what the files are or where they are: the `orders` flow is shape A over
PDFs, which the model reads natively (Β§3, *Documents*), and the `drive` flow
is shape A over a Google Drive folder (Β§3, *Sources: a Google Drive folder*).
+Shape E (added 2026-11-21, the `research` flow) is shape B twice over with a
+search in place of a folder: the first fan-out reads the pages the searches
+found, its reduce lists the leads worth following, a second source lists the
+leads' pages, the second fan-out reads them, and one reduce over both
+collections writes the report (Β§3, *Sources: the web*). The page is the unit
+of delegation as the file is in A–C: a closed worker per page, memoized on
+the page's content, and an orchestrator that never reads a page or a search
+result. The recipe also says what to do with nothing to read: a search card
+showing `items: 0` means no page could be found or fetched and the report
+says so; a leads reduce that names no URL gives a `web_pages` source with no
+items, an empty second collection, and a report reduced from the first.
Directions kept in view, not in v1:
@@ -160,7 +193,7 @@ package's API: JSON calls are canonical, comparable and pickable (Β§4).
| Tool | What it does | CocoIndex primitive | In the transcript | Closed? |
|---|---|---|---|---|
-| `open_source(kind, name, path, patterns?)` | `localfs` (a directory), `google_drive` (a folder, by link or id) | connector β†’ `FileLike`… | card | no |
+| `open_source(kind, name, …)` | `localfs` (`path`, `patterns?`: a directory), `google_drive` (`path`: a folder by link or id, `patterns?`), `web_search` (`queries`), `web_pages` (`urls`: `res:` handles or URLs); each kind holds to its own arguments | connector β†’ `FileLike`… | card | no |
| `open_target(kind, name, path)` | a directory of files in v1 | `mount_target` | card | no |
| `call_agent(key, task, role?, inputs?)` | run an open subagent and wait | `use_mount` at `child/<key>` | `{result: res:key, chars}` | no |
| `start_agent(key, task, role?, inputs?)` | run in the background; effects only through targets in `inputs` | `mount` at `child/<key>` | `{job: job:key}` | no |
@@ -235,6 +268,13 @@ another kind of handle, is an error; it is never written as literal text.
**Volatile methods are role-gated.** `keys()` is available only to planners.
+**`reduce` takes one collection or several.** `collection` is a `coll:`
+handle or a non-empty list of distinct ones; their item keys must not
+collide (a key is a reducer slot's identity, Β§6, and a collision is the
+model's error); an empty member is allowed when the union is not, which is
+how shape E reduces a report from a first collection and an empty second
+one; `omitted` sums the members' failed counts.
+
**Method arguments are checked by name.** A card lists each method's
argument names, and `call` rejects any other name as the model's error
(`sample does not take ['count']; it takes ['k']`) rather than letting the
@@ -360,10 +400,11 @@ else), `test_an_open_session_samples_documents_by_size_and_reads_them_attached`
### Sources: a Google Drive folder
(Added 2026-11-05, with the `drive` flow.) A source is a folder of files
-wherever the folder is; `FolderSource` (`tools/folder.py`) is the contract
-both kinds keep β€” the four methods and their cards, every read recorded β€”
-and a kind supplies the walk, the record keys, the fan-out's listing entries
-and the read. The second kind is a Google Drive folder
+wherever the folder is; `Source` (`tools/source.py`, called `FolderSource`
+in `tools/folder.py` until the web kinds arrived) is the contract both kinds
+keep β€” the four methods and their cards, every read recorded β€” and a kind
+supplies the walk, the record keys, the fan-out's listing entries and the
+read. The second kind is a Google Drive folder
(`tools/drive.py`, over the `google_drive` connector), opened with
`open_source(kind="google_drive", path=<link or id>)`.
@@ -416,6 +457,237 @@ do), `::test_another_account_or_no_sign_in_reruns_what_was_read`,
`::test_a_revoked_sign_in_reruns_the_session_instead_of_failing_the_run`,
`::test_folder_ids_come_from_links_or_ids`.
+
+### Sources: the web
+
+(Added 2026-11-21, with the `research` flow; the owner's review replaced a
+first draft that called the web "a folder of pages" with the vocabulary of
+Β§0, and four rounds of an independent design review settled the contracts
+below.) Two listing kinds, one resource kind, in `tools/web.py`:
+
+```
+open_source(kind="web_search", name="web", queries=["incremental computing", …])
+open_source(kind="web_pages", name="leads", urls=["res:leads"])
+```
+
+`open_source`'s arguments are per kind; the handler reports a missing or
+foreign one as the model's error (`web_search does not take ['path']; it
+takes ['queries']`), as `call` does for method arguments. The card names the
+kind, the engine for a search, the arguments as given, and `items` widened.
+
+**A page is a resource.** `WebPage` is a `FileLike`: its identity and key is
+the canonical final URL (scheme and host lower-cased, default port and
+fragment dropped, tracking parameters dropped, query parameters sorted,
+taken after redirects; two results that redirect to one page are one item);
+its content is the page *normalized* β€” for HTML the title (`<title>` or
+`og:title`) and the main content as Markdown with links and tables,
+boilerplate, navigation and comments stripped (trafilatura, precision first,
+its default extractor when precision yields under 500 characters); for text
+and Markdown the text; for a PDF the bytes, read as a document (*Documents*,
+above) β€” capped at 40,000 characters with a `[truncated]` line; and its
+content state is the digest of that normalized content (sha256 of title and
+text; the engine's fingerprint of a PDF), so a worker over an unchanged
+digest is skipped whole and a timestamp, a nonce or a comment count that
+the normalization removes changes nothing. The text a worker reads begins
+with a header the system writes, `# <title>` and `URL: <url>`, so it can
+cite; **no time is in it** (*No polling, no time*; fetch times are in the
+`--plan` tree, below, and never in a tool result).
+
+**Two listings.** `web_search` lists the pages a set of queries finds
+through the configured engine, by one pure function
+`frontier(prev, results, k, budget)` applied identically by the body and the
+validator: each query asks for `2k` ranked results (`k` = 4; the budget is
+12 pages for a search source and 6 for a page set, constants in `web.py`,
+chosen inside the `8–16` and `4–8` count buckets so a page or two
+unavailable does not move the card); `rank(u)` is a URL's best rank over all
+queries; **incumbents** (URLs of `prev`, the set this source chose last run,
+that some query still returns within its top `2k`) come first by `(rank,
+URL)`, then **newcomers** (URLs some query returns within its top `k`), cut
+at the budget; no per-query quota. A full frontier is unchanged by any rank
+movement inside the top `2k`; an underfilled one may grow when jitter brings
+a URL into a top `k`. Incumbency is judged on requested URLs, which is what
+engines return, and the requested-to-final mapping is recorded, so an
+incumbent reached through a redirect stays one. `prev` comes from
+`use_state("web")` in the body and from the record in the validator; both
+were written by the same body run.
+
+`web_pages` lists the URLs named β€” every `http(s)` URL in each `res:`
+handle's text, then the literal URLs, canonical, deduplicated, in the order
+given β€” **minus the exclusion set**, in two stages: before fetching, a
+requested URL already among the requested or final URLs of another web
+source in the handle-table snapshot the turn runs against (*Calls in one
+turn are independent*: a source opened in an earlier turn is excluded from,
+a sibling of the same turn is not); after fetching, an item whose final URL
+is among those final URLs (a lead that is an alias of a page already read),
+kept in the recorded mapping so that the alias later redirecting to a new
+page is a changed listing. The source's **identity** β€” its memo key as an
+input of an open child and its record key, one immutable value β€” is the
+kind, the sorted admitted requested URLs and both frozen exclusion sets, so
+a leads reducer that rewords or reorders its answer around the same URLs
+changes nothing downstream, and a child that saw an empty page set because
+its lead was an alias of a search result re-runs when the search no longer
+lists that page.
+
+**Fetching: conditional, polite, once per run, never by a worker.** Every
+fetch happens in the listing, in the body of the session that opened the
+source, through one `httpx.AsyncClient` with the project's `User-Agent`.
+Two stores in the session's `use_state("web")`, tied by the payload
+version: the **response cache**, per canonical requested URL β€” the final
+URL, the validators the origin sent (`ETag`, `Last-Modified`) and the digest
+of the payload those validators were obtained with β€” and the **payload
+store**, per (final URL, digest), immutable once written β€” the title, the
+Markdown or PDF bytes (under 8 MiB) and the time this version was first
+fetched, for the trace. A fetch of a known URL sends `If-None-Match` /
+`If-Modified-Since`; a 304 reuses exactly the version its validators name,
+or, if that version is gone, fetches again unconditionally; a 200 is
+normalized and its digest compared. Redirects are followed hop by hop (five
+at most) and a chain that lands on a final URL already fetched in this body
+run takes that fetch's response snapshot, so two aliases of one page cannot
+observe two versions in one run and no validator is ever paired with another
+response's payload. When the body finishes, response entries no listing of
+this run named are dropped, then payload versions no entry references; a
+skipped body leaves both untouched; a validator that found new validators
+with the same digest refreshes the record, not the cache (one 200 instead of
+a 304 next time); a failed fetch keeps its entry and its version but is not
+an item. Politeness: `robots.txt` per host, cached for the run, consulted
+before every fetch (a disallowed URL is never fetched); `Crawl-delay` up to
+10 s; one request at a time per host and at most four in flight; a 20 s
+timeout; 2 MiB for HTML (cut and marked `[truncated]`) and 8 MiB for a PDF
+(never truncated: over the cap it is unavailable); no cookies; `GET` only;
+no sign-in β€” a 401 or 403, a redirect to a `login`/`signin`/`auth` path, or
+a page whose normalized text is under 200 characters and asks to sign in is
+unavailable. Workers never fetch: their item holds the page, so the
+fan-out's roles stay closed, exactly as over a folder.
+
+**Unavailable pages.** A *permanent* outcome β€” 404 or 410, 401 or 403, a
+robots refusal, a sign-in page, an unsupported media type, a PDF over the
+cap β€” is data: the page is left out of the items and recorded in the
+listing's state with its reason; the next run's validation re-tries it, and
+a page that comes back is a changed listing. An *exhausted transient*
+outcome β€” 429, 503, a timeout or a reset, after `errors.retrying` β€” is an
+environment failure **contained per page** (the owner's decision of
+2026-11-21, an amendment to Β§7): the page is left out, marked `transient`,
+and recorded as a contained failure of the session (`page:<url>`), so the
+session's memo is not reused and the fetch is tried again next run, while
+the `open_source` result stays `ok=True` for the pages that were fetched.
+Fetch trouble never reaches a fan-out's `failed` count, because workers do
+not fetch; a worker can still fail as any worker can. Only the engine's own
+failures β€” the search API down after retries, no search engine registered β€”
+fail the tool itself, contained by the open session as `ok=False` (Β§7); a
+run that absorbed one mounts no worker, so the engine drops the workers'
+memos with their paths and the pages are read again when the engine is back.
+The `--plan` tree lists each web source's pages (URL, digest, first fetched)
+and its unavailable pages with their reasons under the `open_source` action
+(`ActionTrace.details`); `--stats` names the transient ones under *re-runs
+next run*.
+
+**Records and validation.** A web source records **one observation per
+run** whatever was observed through it (`stats`, `sample`, `keys`, the
+fan-out's listing are pure functions of the listing): key = the engine
+identity, `k` and the queries (`web.SEARCH_OBSERVATION`) or the source's
+identity (`web.PAGES_OBSERVATION`); state = the frontier (sorted requested
+URLs), the requested-to-final mapping (suppressed aliases included), each
+page's validators and the digest they were obtained with, and the
+unavailable URLs with their reasons (transient ones included, so a recovery
+is a change). **The validator reproduces the listing from the record
+alone** β€” searches again and applies `frontier` with the recorded frontier
+as `prev`, applies the recorded exclusions, fetches every chosen URL
+conditionally with the recorded validators (a 304 confirms the recorded
+digest; a 200 is normalized and compared) β€” and is valid iff the record is
+unchanged. So an unchanged rerun is skipped whole after one search per query
+and one conditional request per page, with no body run and no model call;
+a changed result or page re-runs the body with zero inference and probes the
+workers, of which only the changed or new pages run. **Validators never
+raise for the environment**: an engine outage or an exhausted transient
+fetch makes the record invalid (the previous state is kept), the body
+re-runs and contains the trouble where it meets it; cancellation and
+deadline expiry propagate. A planner's `read(key)` is `web.PAGE_READ`: key
+= the canonical URL, state = (final URL, validators, digest) or `None` for a
+page that did not exist; one conditional request validates it.
+
+Observed with the scripted web (`test_research.py`): on a run whose body
+re-runs, the engine validates the root session's records **twice** before
+the body runs β€” for its component entry and for the memoized function's
+entry β€” so a listing is searched and fetched twice by validators and once by
+the body. A directory walk twice costs nothing; here it is a request per
+page. A window that reused a verdict for a few seconds would hand a stale
+one to a user who edits and reruns at once, so none is kept; the
+per-operation validation cache belongs in the engine (Β§7, *Framework
+roadmap*).
+
+**The engine is a tracked input.** A record names the engine it was made
+with and its validator searches with that engine, which alone would let a
+run that switched engines validate the old records and skip. So the selected
+engine's **identity** β€” its name and the configuration that affects results
+(`wikipedia:en`, `tavily:basic`), never a credential β€” is
+`AgentsConfig.search_engine`, part of the config's memo key and so an input
+of every session (Β§7); switching engines re-runs every body, their turns
+hit where transcripts are unchanged, and the `open_source` card, which names
+the engine, differs. The engine *object* is registered by identity
+(`web.register_engine`), so validators find it without a component context;
+`default_engine(os.environ)` picks Tavily with `TAVILY_API_KEY` and
+Wikipedia otherwise. A `SearchEngine` is a protocol (`search(query, k) ->
+[SearchHit(url, title)]`); `wikipedia` is the MediaWiki search API (no key,
+free, a descriptive `User-Agent`; its results are articles, and the
+`web_pages` round reaches the open web through their references), `tavily`
+is Tavily Search at basic depth (a free tier of 1,000 credits a month; only
+its URLs and titles are used, so a page's provenance is the same under both
+engines). The recipe asks for short, title-like queries: a long string of
+keywords matched the wrong articles on the first drive. Rejected for v1,
+with reasons in `flows/research/SURVEY.md`: Brave (free tier withdrawn,
+terms forbid storing results), Exa, Serper, SerpAPI, Jina (now needs a key),
+DuckDuckGo's HTML endpoint (unofficial), SearXNG public instances, a model's
+native web search (per-call price, prose results, provider lock-in), hosted
+extraction (no origin validators, a key or a rate limit), Playwright
+(hundreds of megabytes), and a version stamp in the model's text (a clock
+reading in a tool result; the owner chose no time).
+
+**Extraction's guarantees are stated per page type** and tested with
+fixtures: for an article, a documentation page, an encyclopedia article and
+plain text or Markdown, a material edit to the main content changes the
+digest and an edit to boilerplate (a timestamp, a comment count, a
+navigation link, an ad slot) does not. Repository pages (a GitHub repository
+page extracts to its sidebar), forums, listings and JavaScript-rendered
+pages are accepted limitations outside that guarantee: the text is thin or
+beside the point, the worker says so, and the flow does not special-case
+hosts.
+
+**The report and its citations.** A page worker's answer has the shape the
+recipe gives verbatim: findings as bullets, each a fact with a short quote
+and the citation `(URL)` copied from the page header; then `Leads:` with up
+to three URLs from the page worth reading, or `Leads: none`. The leads
+reducer lists the distinct lead URLs not among the pages read, at most six;
+the report reducer keeps every claim's citation and ends with a `Sources`
+section, one line per cited URL. Citations survive the reduce because they
+are text in the members and the task says to keep them. When one source
+changed, the user sees that source's findings change in the report and, in
+the `--plan` tree, that page's new fetch time while every other page keeps
+its own; the prose of the reducer group containing the changed member is
+rewritten (Β§6 locality), untouched groups are byte-identical.
+
+*Acceptance:* `test_research.py` β€”
+`test_a_research_run_reuses_unchanged_pages_and_reruns_only_a_changed_one`
+(a report with citations; no call and only conditional requests on an
+unchanged rerun; a boilerplate change re-runs nothing; a content change
+re-runs one worker's answer turn and the two reducers; validators twice and
+the body once on a re-running rerun),
+`test_the_frontier_keeps_a_set_under_rank_jitter_and_moves_only_at_its_edges`
+(jitter, an incumbent sliding while a newcomer enters, a departure, a
+redirect alias as one item),
+`test_web_pages_excludes_what_the_search_read_and_is_keyed_on_the_url_set`
+(the alias suppressed after fetching and admitted when it redirects to a new
+page; a reworded leads answer changes nothing downstream),
+`test_unavailable_pages_are_data_and_exhausted_transient_fetches_are_contained`
+(robots, 403, a sign-in redirect, a PDF over the cap, a 404; a 503 omitted,
+recorded, retried and recovered; `failed` untouched),
+`test_an_engine_outage_is_contained_in_the_body_and_invalidates_in_a_validator`,
+`test_switching_the_search_engine_reruns_the_search`,
+`test_empty_outcomes_are_reported_honestly_and_recover`,
+`test_a_pdf_on_the_web_is_a_document`,
+`test_open_source_holds_each_kind_to_its_arguments_and_reduce_checks_its_collections`,
+`test_the_normalizer_keeps_content_edits_and_drops_boilerplate_edits_per_page_type`,
+`test_frontier_rule_examples`, `test_canonical_urls_and_urls_in_text`.
+
## 4. Replay policy: "dump once"
### The turn and its key
@@ -607,6 +879,23 @@ stores `prev` yet (Β§8).
(bottom-k) and the head of each. A new item changes the sample with
probability about k/N.
+### Search
+
+(Added 2026-11-21.) Search results change between runs, and no session
+reads them: a search is part of a listing observation and only widened item
+counts reach a card; the orchestrator decides the queries from the prompt
+alone; the leads come out of a reduce as a URL set, and the `web_pages`
+source is keyed on that sorted set, not on the reducer's prose. The frontier
+rule (Β§3, *Sources: the web*) keeps a full frontier unchanged under any rank
+movement inside the top `2k`; a URL leaving every top `2k` frees a place and
+one entering a top `k` with a free place takes it β€” the correct dependency β€”
+and an underfilled frontier may grow. Duplicate URLs, URLs that redirect to
+a page already listed, tracking parameters and fragments are absorbed before
+the listing is recorded. The budgets (12 and 6) sit inside their count
+buckets so the common full-budget case with a page or two unavailable keeps
+its card; a sparse search can still cross a bucket when a page is added or
+lost, and recorded count hysteresis stays a target (above).
+
### Stable hash
Every hash used for grouping or sampling β€” bisection (Β§6), bottom-k β€” is a
@@ -747,9 +1036,16 @@ A session's inputs β€” and so what invalidates it β€” are:
the turns after the read miss;
- for an open session: the memo keys of its `inputs` handles (a source's
identity, a collection's content hash) and its **recorded reads** (below);
+ a web source's identity includes, for a page set, its frozen exclusions
+ (Β§3, *Sources: the web*);
+- for a closed **page worker**: its item β€” the canonical final URL, then
+ the page's content digest; validators, raw bytes and fetch times are not
+ in the key;
- the **agents config** it reads through `AGENTS_CONFIG`: roles, tool specs,
- model and version, fingerprinted when the config is provided (the key
- detects changes), because a session builds its children's specs from it;
+ model, version and the **search engine identity**, fingerprinted when the
+ config is provided (the key detects changes), because a session builds its
+ children's specs from it and a web record's validator searches with the
+ engine the record names (Β§3, *Sources: the web*);
- tool **logic**: a handler's own source is tracked because handlers are
`coco.fn`-wrapped; editing one invalidates the closed sessions that ran it
(their turns still hit where the transcript is unchanged, so this costs tool
@@ -878,6 +1174,18 @@ Deadline expiry (`DeadlineExceededError`), cancellation, and a second
unresolvable replay pick in one turn (Β§4) are never contained: they fail the
session and the run, and completed turns keep their memos.
+**A sub-operation of a tool may be contained on its own** (amended
+2026-11-21, the owner's decision for the web source). A listing that fetches
+twelve pages and meets an exhausted transient failure on one leaves that page
+out, records the failure as a contained one (`page:<url>`, never valid, so
+the session re-runs and tries again) and returns `ok=True` for the rest; the
+trace names the page. Under the letter above the whole `open_source` call
+would fail for one flaky host, the model would have no source that run, and
+every worker's memo would be dropped with its path. Validators of such a
+source return an invalid outcome for environment trouble instead of raising
+(the engine propagates a validator's exception), as the Drive validators do
+for a refused sign-in.
+
*Acceptance:* `test_errors.py`;
`test_replay.py::test_environment_errors_are_results_in_open_sessions_and_heal_next_run`,
`::test_argument_validation_is_the_models_error_and_internal_errors_are_reported`,
@@ -1014,7 +1322,7 @@ workers skipped) pins that the trace changed nothing memoized.
|---|---|---|---|
| Progress survives failure | solved by `use_mount` per turn | βœ… | partial fn-memo flush on failure (S–M; pure entries only) |
| Skip unchanged **open** sessions | shipped: `coco.DataDep` + `use_data_dep` + `cannot_skip`; adopted 2026-11-04 (*Open vs closed*) | βœ… | β€” |
-| Skip the **parent** of an open session | shipped: transitive validation by path (engine PR #2671, 2026-11-04); no change on this side | βœ… | per-run validation cache (one validation per record per operation; S) |
+| Skip the **parent** of an open session | shipped: transitive validation by path (engine PR #2671, 2026-11-04); no change on this side | βœ… | per-run validation cache (one validation per record per operation; S): observed 2026-11-21 with the web source, whose records are validated twice (component entry, then function entry) when the body re-runs, a search and a request per page each time (Β§3, *Sources: the web*) |
| Memo probe ("would this hit?") | deferred | β€” | S |
| A component hit keeps its `use_state` values | engine behaviour | βœ… | β€” |
@@ -1069,6 +1377,7 @@ input of a worker whose key must cover everything (*Open vs closed*).
| Trace and report: stats line per shape and run, skipped subtrees credited from their stored trace, reasons, plan rendering | `test_observability.py` (Β§7 *Observability*) |
| Documents: a PDF by reference in the transcript and attached in the rendered request, text files unchanged, no call on an unchanged rerun, one replaced PDF re-running that worker's content turns only; a source's `sample` showing a document by media type and size and its `read` attaching it | `test_documents.py`, `test_rendering.py` (Β§3 *Documents*) |
| A Google Drive folder as a source with the local folder's contract: the folder named, the account never; exports of Google-native files, a PDF as a document; no call, no tool and no download on an unchanged rerun; one edited Doc re-running one worker's content turns; a reader skipped on `modifiedTime` alone and re-run on an edit or a rename; another account or no sign-in re-running what was read | `test_google_drive.py` (Β§3 *Sources: a Google Drive folder*) |
+| The web as a source: a search and a page set over a fake engine and `httpx.MockTransport` pages; a report with citations; no call and only conditional requests on an unchanged rerun; a boilerplate change re-running nothing and a content change one worker's answer turn and the reducers; the frontier under jitter, departures and aliases; exclusion of pages already read, after redirects; unavailable classes, per-page containment of exhausted transient fetches, an engine outage contained in the body and invalid in a validator; the engine as a tracked input; empty outcomes; a PDF on the web as a document; per-kind `open_source` arguments; `reduce` over several collections; the normalizer's guarantees per page type | `test_research.py` (Β§3 *Sources: the web*) |
**Implemented, not covered by a test:**
@@ -1085,7 +1394,11 @@ input of a worker whose key must cover everything (*Open vs closed*).
|---|---|---|
| `group_by` reduce (shape D) | Β§2, Β§6 | no API yet |
| Stats hysteresis via `use_state` | Β§5 | helper exists, state not stored |
-| Table targets (sqlite/postgres), other sources | Β§3 | sources: `localfs`, `google_drive`; targets: `localfs_dir` only |
+| Table targets (sqlite/postgres), other sources | Β§3 | sources: `localfs`, `google_drive`, `web_search`, `web_pages`; targets: `localfs_dir` only |
+| A web resource in CocoIndex proper | Β§3 | a `FileLike` over HTTP with conditional requests is useful beyond this example; proposed, not built here |
+| Shape A over pages (one output per page) | Β§2, Β§3 | needs an output-naming rule for keys that are not file names |
+| A model-native search engine; a planner over search results | Β§3, Β§5 | engines today: `wikipedia`, `tavily` |
+| Delta prompting in the report reducer | Β§6 | so an unchanged group's prose stays byte-identical |
| A Drive folder named by name, or a shared drive, in `open_source` | Β§3 | a link or an id only; a name would need a lookup recorded as a read |
| Drive change notifications in place of a walk per validation | Β§3, Β§7 | every validation walks the folder through the API; fine at the sizes tried |
| Always-on / live mode | Β§2 | no watcher, no refresh design |
@@ -1119,20 +1432,24 @@ cocoindex_agents/
documents.py Document (bytes + reference), Documents (the run-local store), the media-type rule
tools/ Tool (closed_ok; key_arg = the argument that names the child slot),
ToolRegistry (validate_args), AgentsConfig (spec, version; change-detected);
- folder (FolderSource: the contract a source keeps, whatever holds the
- folder), sources (the local kind, its OBSERVATION and FILE_READ records,
- and the open_source / call / read_input tools), drive (the Google Drive
- kind and its records, over the google_drive connector's signed-in
- account), targets, agents, reduce, stats
+ source (Source: the contract every source keeps, a listing of
+ resources), sources (the local kind, its OBSERVATION and FILE_READ
+ records, and the open_source / call / read_input tools), drive (the
+ Google Drive kind and its records, over the google_drive connector's
+ signed-in account), web (the web_search and web_pages kinds: the
+ frontier, the fetcher, the normalizer, WebPage, the stores, the
+ records and their validators, the search engines), targets, agents,
+ reduce, stats
roles.py default roles, the protocol text, and the orchestrator's recipes
litellm_client.py renders a transcript to messages and calls LiteLLM (API call untested);
sums the usage the provider reports
testing.py ScriptedModel (test-only tools live in tests/helpers.py)
app.py default config; build a coco.App from a flow prompt; CLI
tests/ see the Acceptance lines in Β§3–§7 and the table in Β§8
-flows/ five sample flows (shapes A–C of Β§2, shape A over PDFs, shape A over a
- Google Drive folder) with user-level prompts, data, a runner, and the
- stability and model calls measured with a real model
+flows/ six sample flows (shapes A–C of Β§2, shape A over PDFs, shape A over a
+ Google Drive folder, shape E over the web) with user-level prompts,
+ data, a runner, and the stability and model calls measured with a
+ real model; flows/research/SURVEY.md is the survey behind the web source
```
Tests use a scripted model that counts its calls, so assertions are about
@@ -1180,3 +1497,13 @@ Pointers only; the substance is in the owning section.
read as the signed-in account, the model naming the folder and never a
credential, records keyed by path and account and validated through the
Drive API, Google-native files as their export β€” Β§3, Β§7
+- Resource, listing, source, item as the vocabulary; a source is a listing
+ of resources, a folder and a search are two listings, a file and a page
+ two resources; cards say items β€” Β§0, Β§3
+- The web as a source: pages as resources memoized on normalized content;
+ the frontier rule; two-stage exclusion with the frozen sets in the
+ identity; conditional fetching from a response cache tied to a versioned
+ payload store; one record per source per run; validators that never
+ raise; permanent outcomes as data and exhausted transient fetches
+ contained per page; the engine identity as a tracked input; no time in the
+ model's text β€” Β§3, Β§5, Β§7
diff --git a/examples/cocoindex_agents/README.md b/examples/cocoindex_agents/README.md
index f4bcdcc3..f527292d 100644
--- a/examples/cocoindex_agents/README.md
+++ b/examples/cocoindex_agents/README.md
@@ -60,15 +60,22 @@ Two more ways to run it:
See [`flows/README.md`](flows/README.md).
- **A Google Drive folder** of your own, read as your account after a one-time
sign-in: see *The `drive` flow* in [`flows/README.md`](flows/README.md).
+- **The web**: a prompt that names a topic to research makes the orchestrator
+ search (Wikipedia with no key, Tavily with `TAVILY_API_KEY`), read the
+ pages, follow the leads and write a cited report; a rerun fetches each page
+ conditionally and re-reads only what changed. Needs `trafilatura`
+ (`uv pip install trafilatura`). See *The `research` flow* in
+ [`flows/README.md`](flows/README.md).
## Layout
- `cocoindex_agents/` β€” the package (see DESIGN.md Β§9 for the module map, Β§8 for
what is implemented and tested)
- `tests/` β€” scripted-model tests; no API keys needed
-- `flows/` β€” five sample flows with their data and a runner: one per shape
- of DESIGN.md Β§2, one over PDFs the model reads natively, and one over a
- Google Drive folder read as the signed-in account; see
+- `flows/` β€” six sample flows with their data and a runner: one per shape
+ of DESIGN.md Β§2, one over PDFs the model reads natively, one over a
+ Google Drive folder read as the signed-in account, and one that researches
+ a topic on the web (`flows/research/`, with the survey behind it); see
[`flows/README.md`](flows/README.md) for how to run them and the measured
model calls (`--stats` for cache usage, `--plan` for the plan it chose and
what it reused)
diff --git a/examples/cocoindex_agents/cocoindex_agents/app.py b/examples/cocoindex_agents/cocoindex_agents/app.py
index 2230d05b..53451265 100644
--- a/examples/cocoindex_agents/cocoindex_agents/app.py
+++ b/examples/cocoindex_agents/cocoindex_agents/app.py
@@ -31,6 +31,7 @@ from .tools import (
agents,
sources,
targets,
+ web,
)
from .trace import SessionScratch
@@ -55,12 +56,18 @@ def builtin_tools() -> list[Tool]:
def default_config(
- default_model: str, extra_tools: list[Tool] | None = None
+ default_model: str,
+ extra_tools: list[Tool] | None = None,
+ search_engine: str = "",
) -> AgentsConfig:
+ """``search_engine`` is the identity of a registered ``web.SearchEngine``
+ (``web.default_engine(os.environ).identity``); empty leaves the web kinds
+ unusable, which a flow over folders never notices."""
return AgentsConfig(
roles=default_roles(),
tools=ToolRegistry([*builtin_tools(), *(extra_tools or [])]),
default_model=default_model,
+ search_engine=search_engine,
)
@@ -100,7 +107,10 @@ def main(argv: list[str] | None = None) -> int:
# directory sits beside the data, as the sample flows keep theirs.
db_path = pathlib.Path(os.environ.get("COCOINDEX_DB") or ".coco_db")
env = coco.Environment(coco.Settings.from_env(db_path=db_path))
- config = default_config(os.environ.get("LLM_MODEL", DEFAULT_MODEL))
+ config = default_config(
+ os.environ.get("LLM_MODEL", DEFAULT_MODEL),
+ search_engine=web.default_engine(os.environ).identity,
+ )
env.context_provider.provide(MODEL_CLIENT, LiteLLMClient())
env.context_provider.provide(AGENTS_CONFIG, config)
app = build_app("cocoindex_agents", " ".join(args), env=env, config=config)
diff --git a/examples/cocoindex_agents/cocoindex_agents/documents.py b/examples/cocoindex_agents/cocoindex_agents/documents.py
index bdcef597..bdbaad76 100644
--- a/examples/cocoindex_agents/cocoindex_agents/documents.py
+++ b/examples/cocoindex_agents/cocoindex_agents/documents.py
@@ -12,11 +12,12 @@ changes the digest in the reference, so exactly the turns that saw it miss;
an unchanged one renders byte-identical, so the turn memo and the
provider's prompt cache both hit.
-Which files are documents is decided by media type, from the file name,
-never by flow. Today the set is ``application/pdf`` alone: the one type
-every provider accepts inline through LiteLLM's ``file`` content part
-(OpenAI chat completions take only PDFs that way; Anthropic and Gemini
-take more). A file of any other type is read as text, as before.
+Which resources are documents is decided by media type β€” the one the
+resource declares (a web page, from its ``Content-Type``) or, failing that,
+a guess from its name β€” never by flow. Today the set is ``application/pdf``
+alone: the one type every provider accepts inline through LiteLLM's ``file``
+content part (OpenAI chat completions take only PDFs that way; Anthropic and
+Gemini take more). A resource of any other type is read as text, as before.
"""
from __future__ import annotations
@@ -33,11 +34,21 @@ DOCUMENT_MEDIA_TYPES = frozenset({"application/pdf"})
def document_media_type(name: str) -> str | None:
- """The media type of a file the model reads natively, from its name; ``None`` for text."""
+ """The media type of a resource the model reads natively, from its name; ``None`` for text."""
media_type, _ = mimetypes.guess_type(name)
return media_type if media_type in DOCUMENT_MEDIA_TYPES else None
+def resource_media_type(key: str, resource: object) -> str | None:
+ """The document media type of a resource: the one it declares (``media_type``
+ attribute, a page's ``Content-Type``) when it has one, else a guess from its
+ key; ``None`` for text."""
+ declared = getattr(resource, "media_type", None)
+ if isinstance(declared, str):
+ return declared if declared in DOCUMENT_MEDIA_TYPES else None
+ return document_media_type(key)
+
+
@dataclass(frozen=True)
class Document:
"""One document a tool read: its bytes, and the reference that stands for it in the transcript."""
diff --git a/examples/cocoindex_agents/cocoindex_agents/handles.py b/examples/cocoindex_agents/cocoindex_agents/handles.py
index 93df98c3..2bb345c2 100644
--- a/examples/cocoindex_agents/cocoindex_agents/handles.py
+++ b/examples/cocoindex_agents/cocoindex_agents/handles.py
@@ -175,6 +175,13 @@ class HandleTable:
own = set(self._objects)
return own | self._parent.names() if self._parent is not None else own
+ def objects(self) -> dict[str, HandleObject]:
+ """Every handle visible from this table, parents included: the snapshot a
+ call of one turn sees (DESIGN.md Β§3, *Calls in one turn are independent*)."""
+ out = dict(self._parent.objects()) if self._parent is not None else {}
+ out.update(self._objects)
+ return out
+
def __contains__(self, handle: str) -> bool:
return self._lookup(handle) is not None
diff --git a/examples/cocoindex_agents/cocoindex_agents/report.py b/examples/cocoindex_agents/cocoindex_agents/report.py
index f637284a..16e05f5c 100644
--- a/examples/cocoindex_agents/cocoindex_agents/report.py
+++ b/examples/cocoindex_agents/cocoindex_agents/report.py
@@ -220,6 +220,8 @@ def _render_session(
_line(lines, indent + 2, left, tags)
if action.task:
lines.append(" " * (indent + 7) + f'"{action.task}"')
+ for detail in action.details:
+ lines.append(" " * (indent + 7) + detail)
if action.child is not None:
_render_child(lines, action.child, indent + 5, stored)
if not stored:
diff --git a/examples/cocoindex_agents/cocoindex_agents/roles.py b/examples/cocoindex_agents/cocoindex_agents/roles.py
index f787edab..4dbefe72 100644
--- a/examples/cocoindex_agents/cocoindex_agents/roles.py
+++ b/examples/cocoindex_agents/cocoindex_agents/roles.py
@@ -30,7 +30,7 @@ You are one session of CocoIndex Agents, an incremental agent system. Rules:
everything that depends on it, even when it means the same thing.
- If the task lists inputs, those handles are already open for you; use them
by name. You cannot open anything a closed session was not given.
-- A file the model reads natively (a PDF) comes back from read_input or read
+- An item the model reads natively (a PDF) comes back from read_input or read
as a reference ({key, media_type, bytes, digest}) and the document itself
is attached to the message that follows that result: read it there.
- A declared file exists once the run finishes. Targets have no read
@@ -59,20 +59,20 @@ keys, so that the same task decomposes the same way every run:
pass a credential. Open a source with patterns only when the task
restricts the files.
-2. One output per input file (a summary per doc, a row per invoice):
+2. One output per input item (a summary per doc, a row per invoice):
for_each(source, key="items", task=..., inputs=[the target]), with
collect left at its default: the card it returns, with failed=0, is your
proof that every output was written (collect=false runs the workers in
- the background and returns no card). Each worker reads its file with
+ the background and returns no card). Each worker reads its item with
read_input, declares its output into the target, and answers in one line.
Its task must state the exact output file name rule ("for `a.md` write
`a.summary.md`"), the content and format wanted, and any plan the workers
must follow, verbatim.
-3. One combined output over all files (a report, an answer about the
+3. One combined output over all items (a report, an answer about the
corpus): for_each(source, key="items", collect=true, task=...) with a task
- that extracts from one file what the combination needs and keeps the
- file's identity with it (its date, its name); then
+ that extracts from one item what the combination needs and keeps the
+ item's identity with it (its date, its name, its URL); then
reduce(collection, key="combined", task=...) whose task describes the
final text's exact structure; then declare(target, key=<file name>,
value="res:combined") to write it. Never read the result to copy it.
@@ -83,6 +83,33 @@ keys, so that the same task decomposes the same way every run:
depend on it. Decide what you can from the task alone; observe only for
what the task says to take from the data.
+5. Research on the web (a topic to search, read and report on): in the first
+ turn open the target and open_source(kind="web_search", name="web",
+ queries=[three to five queries you write from the topic]). A query is
+ short, two to four words, the kind of phrase that is the title of an
+ encyclopedia article or a reference page ("incremental computing",
+ "build automation", "materialized view"); a long string of keywords
+ matches the wrong pages.
+ Then for_each(src:web, key="pages", collect=true, task=READ) where READ,
+ written from the topic, says: read the page with read_input; answer with
+ "Findings:" then bullets, each one fact relevant to the topic with a short
+ quote and the citation `(URL)` copied from the page header's URL line;
+ then "Leads:" with up to three URLs named in the page worth reading for
+ the topic, each with a few words why, or "Leads: none". Then
+ reduce(coll:pages, key="leads", task="List the distinct URLs under Leads
+ worth reading next that are not pages already read, most useful first, at
+ most six, one per line as `URL β€” why`; or the single word none.") Then
+ open_source(kind="web_pages", name="leads", urls=["res:leads"]) and
+ for_each(src:leads, key="pages2", collect=true, task=READ) with the same
+ READ text. Then reduce(collection=["coll:pages", "coll:pages2"],
+ key="report", task=...) whose task gives the report's exact structure, says
+ to keep every claim's `(URL)` citation, and ends with a "Sources" section
+ listing each cited URL once; then declare(target, key=<file name>,
+ value="res:report"). If the web_search card shows items 0, nothing could
+ be found or fetched: declare a report that says so and answer with that
+ status. If src:leads shows items 0, skip its for_each and reduce the
+ report from coll:pages alone.
+
Rules:
- Counts are widened everywhere on purpose. Never spend a session to count
@@ -125,7 +152,7 @@ PLANNER = RoleSpec(
+ "\nYou are a planner. Look at the data, then answer with the plan and "
"nothing else: no account of what you sampled, of what changed since last "
"run, or of why you kept it. Observe in one turn: stats and sample(k) "
- "together; read a file only when the heads in the sample are not enough. "
+ "together; read an item only when the heads in the sample are not enough. "
"Name what the plan names after the data's own labels, snake_cased, never "
"after synonyms you invent: a name read from the data comes out the same "
"every run, an invented one does not. Cover each labelled field of the "
diff --git a/examples/cocoindex_agents/cocoindex_agents/session.py b/examples/cocoindex_agents/cocoindex_agents/session.py
index 8d32908a..db11d342 100644
--- a/examples/cocoindex_agents/cocoindex_agents/session.py
+++ b/examples/cocoindex_agents/cocoindex_agents/session.py
@@ -300,6 +300,8 @@ async def _session_loop(
)
if output.answer is not None:
+ for finish in ctx.on_finish:
+ finish()
steps.append(Step(output, ()))
step_traces.append(
answer_step(served, from_step, calls, _notes_since(state, notes_before))
@@ -346,6 +348,7 @@ async def _session_loop(
task=task_of(c),
child=a.child,
declared=a.declared,
+ details=tuple(a.details),
)
for c, r, d, a in zip(
output.calls, executed.results, differs, executed.actions
diff --git a/examples/cocoindex_agents/cocoindex_agents/spec.py b/examples/cocoindex_agents/cocoindex_agents/spec.py
index 3e49387b..57c74de4 100644
--- a/examples/cocoindex_agents/cocoindex_agents/spec.py
+++ b/examples/cocoindex_agents/cocoindex_agents/spec.py
@@ -92,14 +92,15 @@ class SessionResult:
@dataclass(frozen=True)
class Item:
- """One source item as a closed session's input: its key within the source, and the file.
+ """One source item as a closed session's input: its key within the source, and the resource.
- Fingerprinted as a dataclass: the key by value, the file by its own memo
- key and memo state (path identity, then mtime/content fingerprint).
+ Fingerprinted as a dataclass: the key by value, the resource by its own
+ memo key and memo state (its identity, then its content state: a file's
+ mtime and fingerprint, a page's content digest).
"""
key: str
- file: FileLike[Any]
+ resource: FileLike[Any]
# What a session was mounted for: a source item (closed worker), the partial
diff --git a/examples/cocoindex_agents/cocoindex_agents/tools/__init__.py b/examples/cocoindex_agents/cocoindex_agents/tools/__init__.py
index af58815d..fb70d900 100644
--- a/examples/cocoindex_agents/cocoindex_agents/tools/__init__.py
+++ b/examples/cocoindex_agents/cocoindex_agents/tools/__init__.py
@@ -30,10 +30,14 @@ from __future__ import annotations
from collections.abc import Awaitable, Callable, Iterable
from dataclasses import dataclass, field, replace
-from typing import cast
+from typing import Any, TypeVar, cast
import cocoindex as coco
+# The handle ``use_state`` returns is not exported yet; this package is its
+# second consumer, as with the retry helpers in ``errors.py``.
+from cocoindex._internal.api import StateHandle
+
from ..documents import Documents
from ..errors import ToolError
from ..handles import HandleTable
@@ -60,6 +64,9 @@ __all__ = [
]
+_S = TypeVar("_S")
+
+
@dataclass
class SessionContext:
"""What a tool handler sees: the session, its input, its handles, the config.
@@ -69,6 +76,11 @@ class SessionContext:
where a tool that mounts a child leaves the child's trace. ``documents``
holds the documents the session's tools attached this run, for the
client to render beside the results that refer to them (``documents.py``).
+ ``states`` and ``on_finish`` are shared by every call of the session (the
+ loop forks the context per call but these objects are the same): a tool
+ that keeps state on the session component declares it once through
+ ``state()``, and registers with ``on_finish`` work the loop runs when the
+ body is about to return (``web.py`` prunes its stores there).
"""
spec: SessionSpec
@@ -79,6 +91,8 @@ class SessionContext:
trace: TraceSink = field(default_factory=TraceSink)
action: ActionSink = field(default_factory=ActionSink)
documents: Documents = field(default_factory=Documents)
+ states: dict[str, Any] = field(default_factory=dict)
+ on_finish: list[Callable[[], None]] = field(default_factory=list)
def claim_slot(self, key: str) -> None:
"""Reserve a child key for this session; a repeat is the model's error."""
@@ -88,6 +102,16 @@ class SessionContext:
)
self.used_slots.add(key)
+ def state(self, name: str, initial: _S, type_hint: type[_S]) -> StateHandle[_S]:
+ """The session component's ``use_state(name)``, declared once per run and
+ shared by every tool call of the session (the engine refuses a second
+ declaration of one key in a run)."""
+ handle = self.states.get(name)
+ if handle is None:
+ handle = coco.use_state(name, initial_value=initial, type_hint=type_hint)
+ self.states[name] = handle
+ return cast("StateHandle[_S]", handle)
+
ToolHandler = Callable[[SessionContext, dict[str, Json]], Awaitable[Json]]
@@ -153,18 +177,31 @@ def validate_args(spec: ToolSpec, args: object) -> dict[str, Json]:
prop = props.get(name)
if prop is None:
raise ToolError(f"unknown argument {name!r}")
- expected = _JSON_TYPES.get(prop.get("type", ""))
- if expected is not None:
- bad_bool = prop.get("type") in ("integer", "number") and isinstance(
+ declared = prop.get("type", "")
+ # A property may allow several JSON types (``["string", "array"]``).
+ types = declared if isinstance(declared, list) else [declared]
+ expected = tuple(
+ t for name_ in types for t in _as_tuple(_JSON_TYPES.get(name_))
+ )
+ if expected:
+ bad_bool = any(t in ("integer", "number") for t in types) and isinstance(
value, bool
)
if bad_bool or not isinstance(value, expected):
- raise ToolError(f"argument {name!r} must be of type {prop['type']}")
+ raise ToolError(
+ f"argument {name!r} must be of type {' or '.join(map(str, types))}"
+ )
if "enum" in prop and value not in prop["enum"]:
raise ToolError(f"argument {name!r} must be one of {prop['enum']}")
return args
+def _as_tuple(types: type | tuple[type, ...] | None) -> tuple[type, ...]:
+ if types is None:
+ return ()
+ return types if isinstance(types, tuple) else (types,)
+
+
class ToolRegistry:
def __init__(self, tools: Iterable[Tool] = ()) -> None:
self._tools: dict[str, Tool] = {}
@@ -224,12 +261,19 @@ class AgentsConfig:
is everything a spec can be built from. The config is frozen because its
fingerprint is taken when it is provided: an edit is a new config
(``dataclasses.replace``), provided anew.
+
+ ``search_engine`` is the identity of the web search engine the ``web``
+ sources use (``web.py``: a name and the configuration that affects
+ results, never a credential), tracked here because a record's validator
+ searches with the engine the record names and could not otherwise notice
+ a switch (DESIGN.md Β§3, *Sources: the web*). Empty means none configured.
"""
roles: dict[str, RoleSpec]
tools: ToolRegistry = field(default_factory=ToolRegistry)
default_model: str = "unspecified"
- version: int = 3
+ version: int = 4
+ search_engine: str = ""
def __coco_memo_key__(self) -> object:
return (
@@ -238,6 +282,7 @@ class AgentsConfig:
self.tools.specs(),
self.default_model,
self.version,
+ self.search_engine,
)
def role(self, name: str) -> RoleSpec:
diff --git a/examples/cocoindex_agents/cocoindex_agents/tools/agents.py b/examples/cocoindex_agents/cocoindex_agents/tools/agents.py
index ac1b0961..5e571b1f 100644
--- a/examples/cocoindex_agents/cocoindex_agents/tools/agents.py
+++ b/examples/cocoindex_agents/cocoindex_agents/tools/agents.py
@@ -21,6 +21,7 @@ items in the collection.
from __future__ import annotations
from dataclasses import replace
+from typing import NamedTuple
import cocoindex as coco
@@ -38,7 +39,7 @@ from ..trace import ChildTrace, Member, SessionScratch, child_members, child_ses
from ..transcript import canonical_json
from . import SessionContext, tool
from .reduce import Group, GroupItem, ReduceError, hierarchical_reduce, leaf_item
-from .folder import FolderSource
+from .source import Source
from .stats import format_range, widen_count
_DEFAULT_REDUCE_THRESHOLD_TOKENS = 6000
@@ -162,7 +163,7 @@ _CLOSED_SKIPPED = "input unchanged"
"call_agent",
"Run one open subagent with `task` and wait for it. `key` names it stably across "
"runs; `inputs` lists the handles it may use. Returns a res: handle to its answer, "
- "never the text. For one piece of work over the whole data; per-file work is "
+ "never the text. For one piece of work over the whole data; per-item work is "
"for_each.",
{
"type": "object",
@@ -277,8 +278,8 @@ async def observe(ctx: SessionContext, args: dict[str, Json]) -> Json:
@tool(
"for_each",
- "Run one closed worker per file of a source, in parallel. `key` names the fan-out "
- "stably across runs; `task` is every worker's instruction (each reads its own file "
+ "Run one closed worker per item of a source, in parallel. `key` names the fan-out "
+ "stably across runs; `task` is every worker's instruction (each reads its own item "
"with read_input); `inputs` lists the handles the workers may use: the target they "
"write to, a result they must follow. With collect=true (the default) the answers are "
"gathered into a coll: handle for reduce; its card shows a widened count and how many "
@@ -301,7 +302,7 @@ async def observe(ctx: SessionContext, args: dict[str, Json]) -> Json:
async def for_each(ctx: SessionContext, args: dict[str, Json]) -> Json:
key: str = args["key"]
src = ctx.handles.get(args["source"])
- if not isinstance(src, FolderSource):
+ if not isinstance(src, Source):
raise ToolError("for_each needs a src: handle")
handles, cards = _child_inputs(ctx, args, closed=True)
child = _closed_spec(ctx, args.get("role", "worker"), args["task"], cards)
@@ -365,13 +366,14 @@ async def for_each(ctx: SessionContext, args: dict[str, Json]) -> Json:
@tool(
"reduce",
- "Combine every successful item of a coll: handle into one text with `task`, "
- "hierarchically, so any number of items fits. Returns a res: handle to the text and "
- 'how many failed items were left out; write it with declare(value="res:<key>").',
+ "Combine every successful item of one coll: handle, or of several (a list of "
+ "handles), into one text with `task`, hierarchically, so any number of items fits. "
+ "Returns a res: handle to the text and how many failed items were left out; write "
+ 'it with declare(value="res:<key>").',
{
"type": "object",
"properties": {
- "collection": {"type": "string"},
+ "collection": {"type": ["string", "array"], "items": {"type": "string"}},
"key": {"type": "string"},
"task": {"type": "string"},
"role": {"type": "string"},
@@ -383,9 +385,7 @@ async def for_each(ctx: SessionContext, args: dict[str, Json]) -> Json:
)
async def reduce(ctx: SessionContext, args: dict[str, Json]) -> Json:
key: str = args["key"]
- coll = ctx.handles.get(args["collection"])
- if not isinstance(coll, Collection):
- raise ToolError("reduce needs a coll: handle")
+ members = _collections(ctx, args["collection"])
child = _closed_spec(ctx, args.get("role", "reducer"), args["task"], ())
threshold: int = args.get("threshold_tokens", _DEFAULT_REDUCE_THRESHOLD_TOKENS)
if threshold < 2:
@@ -394,7 +394,7 @@ async def reduce(ctx: SessionContext, args: dict[str, Json]) -> Json:
items: list[GroupItem[str]] = [
leaf_item(item_key, _estimate_tokens(text), text)
- for item_key, text in coll.entries
+ for item_key, text in members.entries
]
groups: list[Member] = []
@@ -445,7 +445,44 @@ async def reduce(ctx: SessionContext, args: dict[str, Json]) -> Json:
failed=0,
skipped_reason="members unchanged",
)
- return _result(ctx, key, answer, omitted=len(coll.failed))
+ return _result(ctx, key, answer, omitted=members.omitted)
+
+
+class Members(NamedTuple):
+ entries: list[tuple[str, str]] # (item key, answer) of every success
+ omitted: int # failed members, over every collection
+
+
+def _collections(ctx: SessionContext, arg: Json) -> Members:
+ """The successes of one collection, or of several concatenated, and how many
+ members failed in all of them.
+
+ Several collections must be distinct handles whose item keys do not collide
+ (a key is a reducer slot's identity, Β§6); an empty member is allowed when
+ the union is not (a second round that found nothing, DESIGN.md Β§2 shape E).
+ """
+ names = [arg] if isinstance(arg, str) else list(arg)
+ if not names or not all(isinstance(n, str) for n in names):
+ raise ToolError("reduce needs a coll: handle or a non-empty list of them")
+ if len(set(names)) != len(names):
+ raise ToolError("reduce lists the same collection twice")
+ entries: list[tuple[str, str]] = []
+ omitted = 0
+ seen: dict[str, str] = {}
+ for name in names:
+ coll = ctx.handles.get(name)
+ if not isinstance(coll, Collection):
+ raise ToolError(f"{name!r} is a {coll.kind} handle, not a collection")
+ for item_key, text in coll.entries:
+ if item_key in seen:
+ raise ToolError(
+ f"item {item_key!r} is in both {seen[item_key]} and {name}; "
+ "a reduce needs distinct item keys"
+ )
+ seen[item_key] = name
+ entries.append((item_key, text))
+ omitted += len(coll.failed)
+ return Members(entries, omitted)
def _estimate_tokens(text: str) -> int:
diff --git a/examples/cocoindex_agents/cocoindex_agents/tools/drive.py b/examples/cocoindex_agents/cocoindex_agents/tools/drive.py
index b16bf255..7459b150 100644
--- a/examples/cocoindex_agents/cocoindex_agents/tools/drive.py
+++ b/examples/cocoindex_agents/cocoindex_agents/tools/drive.py
@@ -1,6 +1,6 @@
"""A Google Drive folder as a source (DESIGN.md Β§3, *Sources*; Β§7).
-The same contract as the local folder (``sources.FolderSource``): widened
+The same contract as the local folder (``source.Source``): widened
``stats``, a hash-stable ``sample``, ``read(key)``, the planner-only
``keys``, and every read recorded as a data dependency of the session that
made it. What differs is where the records point and how they validate:
@@ -46,12 +46,12 @@ from cocoindex.resources.file import PatternFilePathMatcher
from ..documents import Document
from ..errors import ToolError
from ..spec import Json
-from .folder import (
- FolderSource,
+from .source import (
+ Source,
content_of,
digest_bytes,
digest_of_json,
- file_key_arg,
+ item_key_arg,
)
# A pasted Drive link: https://drive.google.com/drive/folders/<id>, with or
@@ -152,7 +152,7 @@ async def _validate_file_read(
if src is None:
return coco.MemoStateOutcome(state=prev)
try:
- file = (await src.files()).get(key.key)
+ file = (await src.resources()).get(key.key)
except google_drive.SignInError: # refused at refresh: expired or revoked
return coco.MemoStateOutcome(state=prev)
if prev is None or file is None:
@@ -191,7 +191,7 @@ async def _file_state(file: google_drive.DriveFile) -> tuple[str, str, str]:
return (file.info.file_id, _modified_time(file), fingerprint)
-class GoogleDriveFolderSource(FolderSource[google_drive.DriveFile]):
+class GoogleDriveFolderSource(Source[google_drive.DriveFile]):
"""A ``src:`` handle over one Drive folder, read as the signed-in account."""
kind = "google_drive"
@@ -225,7 +225,7 @@ class GoogleDriveFolderSource(FolderSource[google_drive.DriveFile]):
else None
)
- async def files(self) -> dict[str, google_drive.DriveFile]:
+ async def resources(self) -> dict[str, google_drive.DriveFile]:
"""One walk through the Drive API, keyed by path; a path two files share keeps both.
Drive allows two files of one name in a folder; the second (by id)
@@ -251,10 +251,10 @@ class GoogleDriveFolderSource(FolderSource[google_drive.DriveFile]):
def observation_key(self, method: str, args: str) -> object:
return DriveObservation(self.ref(), method, args)
- async def entries(self, files: dict[str, google_drive.DriveFile]) -> Json:
+ async def entries(self, resources: dict[str, google_drive.DriveFile]) -> Json:
return [
(key, file.info.file_id, _modified_time(file), file.info.md5_checksum or "")
- for key, file in files.items()
+ for key, file in resources.items()
]
async def read(self, args: dict[str, Json]) -> str | Document:
@@ -262,8 +262,8 @@ class GoogleDriveFolderSource(FolderSource[google_drive.DriveFile]):
as a read of that path alone: the walk itself is not recorded, so an edit
elsewhere in the folder does not touch the session.
"""
- file_key = file_key_arg(args)
- file = (await self.files()).get(file_key)
+ file_key = item_key_arg(args)
+ file = (await self.resources()).get(file_key)
state: DriveFileState = None
data = b""
if file is not None:
diff --git a/examples/cocoindex_agents/cocoindex_agents/tools/folder.py b/examples/cocoindex_agents/cocoindex_agents/tools/folder.py
deleted file mode 100644
index 7d30cfcc..00000000
--- a/examples/cocoindex_agents/cocoindex_agents/tools/folder.py
+++ /dev/null
@@ -1,221 +0,0 @@
-"""The contract a folder source keeps, whatever holds the folder (``sources.py``, ``drive.py``).
-
-A source handle exposes stable observations (widened ``stats``, hash-stable
-``sample``), per-item reads, and β€” for planners only β€” the volatile ``keys``.
-A source's contents are not an argument of anyone, so every read through it is
-**recorded** as a data dependency of the session that made it
-(``coco.use_data_dep``, DESIGN.md Β§7): the session is skipped next run only
-while every recorded read validates. Two kinds of record per source kind:
-
-- an *observation* β€” ``stats``, ``sample``, ``keys`` and the ``listing`` a
- ``for_each`` walks. Keyed by the source and the call; the state is a digest
- of what came back. Validated by observing again and comparing, so a change
- that leaves the observation byte-identical (a new file inside the same
- widened bucket, a sample that did not move) keeps the session skippable.
-- a *file read* β€” ``read(key)``. Keyed by the file; the state is its
- modification time and content digest, or ``None`` when it did not exist. An
- unchanged modification time validates without reading the file.
-
-``FolderSource`` holds what both kinds share: the methods and their cards,
-the recording, and the observations computed from a walk. A kind supplies the
-walk, the record keys, the listing entries and the read.
-
-A source may only be an input of open sessions: a closed session's memo key
-must cover everything it reads, and ``open_source`` is not ``closed_ok``.
-
-What a read returns is decided by the file's media type (``documents.py``):
-text as text; a document (a PDF) as a reference, with the bytes attached to
-the session for the client to render. ``sample`` shows a document's media
-type and size in place of a text head.
-"""
-
-from __future__ import annotations
-
-import hashlib
-from abc import ABC, abstractmethod
-from typing import Any, ClassVar, Generic, NamedTuple, TypeVar
-
-import cocoindex as coco
-from cocoindex.resources.file import FileLike
-
-from ..documents import Document, document_media_type
-from ..errors import ToolError
-from ..handles import MethodSpec, Volatility, int_arg
-from ..spec import Item, Json
-from ..transcript import canonical_json, digest_json
-from .stats import bottom_k, format_range, widen_count
-
-_SAMPLE_HEAD_CHARS = 400
-
-# What ``for_each`` walks: every file by key with what identifies its content,
-# so an edit, a touch, an addition or a removal all re-run the fan-out's
-# session. Not a model-visible method: ``call`` rejects it.
-LISTING = "listing"
-
-
-def digest_bytes(data: bytes) -> bytes:
- return hashlib.sha256(data).digest()
-
-
-def digest_of_json(value: Json) -> bytes:
- return digest_bytes(canonical_json(value).encode("utf-8"))
-
-
-# The file type a kind's walk yields: ``localfs.File``, ``google_drive.DriveFile``.
-FileT = TypeVar("FileT", bound=FileLike[Any])
-
-
-class Listing(NamedTuple):
- items: dict[str, Item]
- digest: str # of the walk, for the session's trace
-
-
-class FolderSource(ABC, Generic[FileT]):
- """A ``src:`` handle over a folder of files, whatever holds the folder.
-
- Its memo key is its identity, not its contents: what a session read
- through it is recorded per call, as the module docstring says. A kind
- supplies ``files`` (the walk), ``observation_key`` (what identifies an
- observation of it in a record), ``entries`` (what the fan-out's walk
- records per file) and ``read``.
- """
-
- kind: ClassVar[str]
- observation: ClassVar[coco.DataDep] # the kind's observation records
- closed_input_ok = False
- patterns: tuple[str, ...]
-
- @abstractmethod
- def __coco_memo_key__(self) -> object: ...
-
- @abstractmethod
- async def files(self) -> dict[str, FileT]:
- """One walk: every file by its key, in key order. Records nothing."""
-
- @abstractmethod
- def observation_key(self, method: str, args: str) -> object:
- """The record key of one observation (``args`` is the call's canonical JSON)."""
-
- @abstractmethod
- async def entries(self, files: dict[str, FileT]) -> Json:
- """What the fan-out's walk records: every file with what identifies its content."""
-
- @abstractmethod
- async def read(self, args: dict[str, Json]) -> str | Document:
- """One file, recorded as a read of that file alone: its text, or a document."""
-
- def methods(self) -> tuple[MethodSpec, ...]:
- return (
- MethodSpec(
- "stats",
- "Widened file count (a range, not an exact number).",
- Volatility.STABLE,
- ),
- MethodSpec(
- "sample",
- "`k` representative files (default 5) with the head of each text file; "
- "a PDF shows its media type and size instead. The set is hash-stable, "
- "so it barely changes when files are added.",
- Volatility.STABLE,
- args=("k",),
- ),
- MethodSpec(
- "read",
- "One file by key: its full text, or for a PDF a reference with the "
- "document attached to your next message.",
- Volatility.PER_ITEM,
- args=("key",),
- ),
- MethodSpec(
- "keys",
- "Every file key (optionally under `prefix`). Volatile: planners only.",
- Volatility.VOLATILE,
- args=("prefix",),
- ),
- )
-
- async def call(self, method: str, args: dict[str, Json]) -> Json:
- """A model-visible method: observe or read, and record what was seen."""
- if method == "read":
- return await self.read(args)
- if method not in {m.name for m in self.methods()}:
- raise ToolError(f"unknown method {method!r} on a {self.kind} source")
- return await self._observe_recorded(method, args)
-
- async def listing(self) -> Listing:
- """Every file as a ``for_each`` item, recorded as one observation of the walk."""
- files = await self.files()
- walk = await self._observe_recorded(LISTING, {}, files)
- return Listing(
- {key: Item(key, file) for key, file in files.items()}, digest_json(walk)
- )
-
- async def _observe_recorded(
- self,
- method: str,
- args: dict[str, Json],
- files: dict[str, FileT] | None = None,
- ) -> Json:
- result = await self.observe(method, args, files)
- coco.use_data_dep(
- self.observation,
- key=self.observation_key(method, canonical_json(args)),
- state=digest_of_json(result),
- )
- return result
-
- async def observe(
- self,
- method: str,
- args: dict[str, Json],
- files: dict[str, FileT] | None = None,
- ) -> Json:
- """Compute an observation without recording it (the validator's path).
-
- ``files`` is the walk to observe; a caller that already walked passes it.
- """
- if files is None:
- files = await self.files()
- if method == "stats":
- # Target (DESIGN.md Β§5): hysteresis against the previous bucket, kept in
- # use_state on the session component. Not implemented yet.
- return {"files": format_range(widen_count(len(files)))}
- if method == "sample":
- return [
- await _sample_entry(key, files[key])
- for key in bottom_k(files, int_arg(args, "k", 5))
- ]
- if method == "keys":
- prefix = str(args.get("prefix", ""))
- return [k for k in files if k.startswith(prefix)]
- if method == LISTING:
- return await self.entries(files)
- raise ValueError(f"not an observation: {method!r}") # call() screens the model
-
-
-def file_key_arg(args: dict[str, Json]) -> str:
- file_key = args.get("key")
- if not isinstance(file_key, str):
- raise ToolError("read needs a string `key`")
- return file_key
-
-
-async def content_of(key: str, file: FileLike[Any], data: bytes) -> str | Document:
- """What ``read`` returns for a file whose bytes ``data`` were just read: its
- text (decoded by the file, from the bytes it cached), or the document itself.
-
- A document is returned as is; the ``call`` tool attaches it to the
- session and returns its reference.
- """
- media_type = document_media_type(key)
- if media_type is None:
- return await file.read_text()
- return Document.of(key, media_type, data)
-
-
-async def _sample_entry(key: str, file: FileLike[Any]) -> dict[str, Json]:
- """A text file's head; a document's media type and size (its content is not text)."""
- media_type = document_media_type(key)
- if media_type is None:
- return {"key": key, "head": (await file.read_text())[:_SAMPLE_HEAD_CHARS]}
- return {"key": key, "media_type": media_type, "bytes": await file.size()}
diff --git a/examples/cocoindex_agents/cocoindex_agents/tools/source.py b/examples/cocoindex_agents/cocoindex_agents/tools/source.py
new file mode 100644
index 00000000..13fdf77b
--- /dev/null
+++ b/examples/cocoindex_agents/cocoindex_agents/tools/source.py
@@ -0,0 +1,240 @@
+"""The contract every source keeps, whatever it lists (DESIGN.md Β§0, Β§3).
+
+Vocabulary: a **resource** is one thing a worker can read whole β€” a local
+file, a Drive file, a web page β€” with an identity that is global within its
+kind's space and a content state its memo state carries; it is a ``FileLike``
+(``cocoindex.resources.file``). A **listing** is how a session finds
+resources: walking a folder, running searches, taking a list of URLs; it is
+session-local and recorded as an observation. A **source** (``src:`` handle)
+is a listing with four methods: widened ``stats``, hash-stable ``sample``,
+per-item ``read``, and β€” for planners only β€” the volatile ``keys``. An
+**item** is one listed resource under a source-local key, the unit of a
+``for_each``.
+
+A source's contents are not an argument of anyone, so every read through it
+is **recorded** as a data dependency of the session that made it
+(``coco.use_data_dep``, DESIGN.md Β§7): the session is skipped next run only
+while every recorded read validates. Two kinds of record per source kind:
+
+- an *observation* β€” ``stats``, ``sample``, ``keys`` and the ``listing`` a
+ ``for_each`` walks. Keyed by the source and the call; the state is, by
+ default, a digest of what came back, validated by observing again and
+ comparing, so a change that leaves the observation byte-identical (a new
+ item inside the same widened bucket, a sample that did not move) keeps the
+ session skippable. A kind may record a richer state (``web.py`` records
+ what its validator needs to reproduce a listing).
+- a *resource read* β€” ``read(key)``. Keyed by the resource; the state is what
+ identifies its content (a file's modification time and digest, a page's
+ validators and digest), or ``None`` when it did not exist.
+
+``Source`` holds what every kind shares: the methods and their cards, the
+recording, and the observations computed from a listing. A kind supplies the
+listing (``resources``), the record keys, the listing entries and the read.
+The kinds: ``sources.LocalDirSource`` and ``drive.GoogleDriveFolderSource``
+list files; ``web.WebSearchSource`` and ``web.WebPagesSource`` list pages.
+
+A source may only be an input of open sessions: a closed session's memo key
+must cover everything it reads, and ``open_source`` is not ``closed_ok``.
+
+What a read returns is decided by the resource's media type
+(``documents.py``): text as text; a document (a PDF) as a reference, with the
+bytes attached to the session for the client to render. ``sample`` shows a
+document's media type and size in place of a text head.
+"""
+
+from __future__ import annotations
+
+import hashlib
+from abc import ABC, abstractmethod
+from typing import Any, ClassVar, Generic, NamedTuple, TypeVar
+
+import cocoindex as coco
+from cocoindex.resources.file import FileLike
+
+from ..documents import Document, resource_media_type
+from ..errors import ToolError
+from ..handles import MethodSpec, Volatility, int_arg
+from ..spec import Item, Json
+from ..transcript import canonical_json, digest_json
+from .stats import bottom_k, format_range, widen_count
+
+_SAMPLE_HEAD_CHARS = 400
+
+# What ``for_each`` walks: every item by key with what identifies its content,
+# so an edit, a touch, an addition or a removal all re-run the fan-out's
+# session. Not a model-visible method: ``call`` rejects it.
+LISTING = "listing"
+
+
+def digest_bytes(data: bytes) -> bytes:
+ return hashlib.sha256(data).digest()
+
+
+def digest_of_json(value: Json) -> bytes:
+ return digest_bytes(canonical_json(value).encode("utf-8"))
+
+
+# The resource type a kind lists: ``localfs.File``, ``google_drive.DriveFile``,
+# ``web.WebPage``.
+ResourceT = TypeVar("ResourceT", bound=FileLike[Any])
+
+
+class Listing(NamedTuple):
+ items: dict[str, Item]
+ digest: str # of the walk, for the session's trace
+
+
+class Source(ABC, Generic[ResourceT]):
+ """A ``src:`` handle: a listing of resources, whatever it lists.
+
+ Its memo key is its identity, not its contents: what a session read
+ through it is recorded per call, as the module docstring says. A kind
+ supplies ``resources`` (the listing), ``observation_key`` (what identifies
+ an observation of it in a record), ``entries`` (what the fan-out's listing
+ records per item), ``read``, and may override ``observation_state``.
+ """
+
+ kind: ClassVar[str]
+ observation: ClassVar[coco.DataDep] # the kind's observation records
+ closed_input_ok = False
+ patterns: tuple[str, ...]
+
+ @abstractmethod
+ def __coco_memo_key__(self) -> object: ...
+
+ @abstractmethod
+ async def resources(self) -> dict[str, ResourceT]:
+ """One listing: every resource by its item key, in key order. Records nothing."""
+
+ @abstractmethod
+ def observation_key(self, method: str, args: str) -> object:
+ """The record key of one observation (``args`` is the call's canonical JSON)."""
+
+ @abstractmethod
+ async def entries(self, resources: dict[str, ResourceT]) -> Json:
+ """What the fan-out's listing records: every item with what identifies its content."""
+
+ @abstractmethod
+ async def read(self, args: dict[str, Json]) -> str | Document:
+ """One resource, recorded as a read of it alone: its text, or a document."""
+
+ def observation_state(self, method: str, result: Json) -> object:
+ """The state recorded for an observation; a digest of the result by default."""
+ return digest_of_json(result)
+
+ def methods(self) -> tuple[MethodSpec, ...]:
+ return (
+ MethodSpec(
+ "stats",
+ "Widened item count (a range, not an exact number).",
+ Volatility.STABLE,
+ ),
+ MethodSpec(
+ "sample",
+ "`k` representative items (default 5) with the head of each text item; "
+ "a PDF shows its media type and size instead. The set is hash-stable, "
+ "so it barely changes when items are added.",
+ Volatility.STABLE,
+ args=("k",),
+ ),
+ MethodSpec(
+ "read",
+ "One item by key: its full text, or for a PDF a reference with the "
+ "document attached to your next message.",
+ Volatility.PER_ITEM,
+ args=("key",),
+ ),
+ MethodSpec(
+ "keys",
+ "Every item key (optionally under `prefix`). Volatile: planners only.",
+ Volatility.VOLATILE,
+ args=("prefix",),
+ ),
+ )
+
+ async def call(self, method: str, args: dict[str, Json]) -> Json:
+ """A model-visible method: observe or read, and record what was seen."""
+ if method == "read":
+ return await self.read(args)
+ if method not in {m.name for m in self.methods()}:
+ raise ToolError(f"unknown method {method!r} on a {self.kind} source")
+ return await self._observe_recorded(method, args)
+
+ async def listing(self) -> Listing:
+ """Every resource as a ``for_each`` item, recorded as one observation of the listing."""
+ resources = await self.resources()
+ walk = await self._observe_recorded(LISTING, {}, resources)
+ return Listing(
+ {key: Item(key, resource) for key, resource in resources.items()},
+ digest_json(walk),
+ )
+
+ async def _observe_recorded(
+ self,
+ method: str,
+ args: dict[str, Json],
+ resources: dict[str, ResourceT] | None = None,
+ ) -> Json:
+ result = await self.observe(method, args, resources)
+ coco.use_data_dep(
+ self.observation,
+ key=self.observation_key(method, canonical_json(args)),
+ state=self.observation_state(method, result),
+ )
+ return result
+
+ async def observe(
+ self,
+ method: str,
+ args: dict[str, Json],
+ resources: dict[str, ResourceT] | None = None,
+ ) -> Json:
+ """Compute an observation without recording it (the validator's path).
+
+ ``resources`` is the listing to observe; a caller that already listed passes it.
+ """
+ if resources is None:
+ resources = await self.resources()
+ if method == "stats":
+ # Target (DESIGN.md Β§5): hysteresis against the previous bucket, kept in
+ # use_state on the session component. Not implemented yet.
+ return {"items": format_range(widen_count(len(resources)))}
+ if method == "sample":
+ return [
+ await _sample_entry(key, resources[key])
+ for key in bottom_k(resources, int_arg(args, "k", 5))
+ ]
+ if method == "keys":
+ prefix = str(args.get("prefix", ""))
+ return [k for k in resources if k.startswith(prefix)]
+ if method == LISTING:
+ return await self.entries(resources)
+ raise ValueError(f"not an observation: {method!r}") # call() screens the model
+
+
+def item_key_arg(args: dict[str, Json]) -> str:
+ key = args.get("key")
+ if not isinstance(key, str):
+ raise ToolError("read needs a string `key`")
+ return key
+
+
+async def content_of(key: str, resource: FileLike[Any], data: bytes) -> str | Document:
+ """What ``read`` returns for a resource whose bytes ``data`` were just read: its
+ text (decoded by the resource, from the bytes it cached), or the document itself.
+
+ A document is returned as is; the ``call`` tool attaches it to the
+ session and returns its reference.
+ """
+ media_type = resource_media_type(key, resource)
+ if media_type is None:
+ return await resource.read_text()
+ return Document.of(key, media_type, data)
+
+
+async def _sample_entry(key: str, resource: FileLike[Any]) -> dict[str, Json]:
+ """A text item's head; a document's media type and size (its content is not text)."""
+ media_type = resource_media_type(key, resource)
+ if media_type is None:
+ return {"key": key, "head": (await resource.read_text())[:_SAMPLE_HEAD_CHARS]}
+ return {"key": key, "media_type": media_type, "bytes": await resource.size()}
diff --git a/examples/cocoindex_agents/cocoindex_agents/tools/sources.py b/examples/cocoindex_agents/cocoindex_agents/tools/sources.py
index 56771f7a..25de993e 100644
--- a/examples/cocoindex_agents/cocoindex_agents/tools/sources.py
+++ b/examples/cocoindex_agents/cocoindex_agents/tools/sources.py
@@ -1,7 +1,7 @@
-"""Source handles and the tools over them: a local directory, or a Google Drive
-folder (``drive.py``). The contract both keep is ``folder.FolderSource``; this
-module holds the local kind's records and walk, and the ``open_source``,
-``call`` and ``read_input`` tools.
+"""Source handles and the tools over them: a local directory, a Google Drive
+folder (``drive.py``), a web search or a set of web pages (``web.py``). The
+contract all keep is ``source.Source``; this module holds the local kind's
+records and walk, and the ``open_source``, ``call`` and ``read_input`` tools.
The local kind's records: an ``OBSERVATION`` is keyed by the root, the
patterns and the call, and validated by walking again; a ``FILE_READ`` is
@@ -23,13 +23,13 @@ import cocoindex as coco
from cocoindex.connectors import localfs
from cocoindex.resources.file import PatternFilePathMatcher
-from ..documents import Document, document_media_type
+from ..documents import Document, resource_media_type
from ..errors import ToolError
-from ..handles import Volatility
+from ..handles import ResultValue, Volatility, is_handle
from ..spec import Item, Json
from ..transcript import digest_json, normalize_json
-from . import SessionContext, drive, tool
-from .folder import FolderSource, content_of, digest_bytes, digest_of_json, file_key_arg
+from . import SessionContext, drive, tool, web
+from .source import Source, content_of, digest_bytes, digest_of_json, item_key_arg
# mtime and digest of a file that was read; ``None`` when it did not exist.
FileState = tuple[int, bytes] | None
@@ -86,7 +86,7 @@ def _mtime_ns(path: pathlib.Path) -> int | None:
return None
-class LocalDirSource(FolderSource[localfs.File]):
+class LocalDirSource(Source[localfs.File]):
"""A ``src:`` handle over ``localfs.walk_dir``."""
kind = "localfs"
@@ -109,17 +109,17 @@ class LocalDirSource(FolderSource[localfs.File]):
def walker(self) -> localfs.DirWalker:
return localfs.walk_dir(self.root, recursive=True, path_matcher=self._matcher())
- async def files(self) -> dict[str, localfs.File]:
+ async def resources(self) -> dict[str, localfs.File]:
found = {key: file async for key, file in self.walker().items()}
return dict(sorted(found.items()))
def observation_key(self, method: str, args: str) -> object:
return Observation(str(self.root), self.patterns, method, args)
- async def entries(self, files: dict[str, localfs.File]) -> Json:
+ async def entries(self, resources: dict[str, localfs.File]) -> Json:
def stat_all() -> list[tuple[str, int, int]]:
out: list[tuple[str, int, int]] = []
- for key, file in files.items():
+ for key, file in resources.items():
st = os.stat(file.file_path.resolve())
out.append((key, st.st_mtime_ns, st.st_size))
return out
@@ -131,7 +131,7 @@ class LocalDirSource(FolderSource[localfs.File]):
record covers this file and not the listing: an edit elsewhere under
the root does not touch the session.
"""
- file_key = file_key_arg(args)
+ file_key = item_key_arg(args)
path = self._path_of(file_key)
# Stat before reading, so the recorded mtime is never newer than the bytes.
mtime = await asyncio.to_thread(_mtime_ns, path)
@@ -164,37 +164,128 @@ class LocalDirSource(FolderSource[localfs.File]):
return path
+# What each kind of source takes besides ``kind`` and ``name``: the shallow
+# validator admits every optional argument, and the handler holds each kind to
+# its own, as ``call`` holds a method to the arguments its card lists.
+_KIND_ARGS: dict[str, tuple[frozenset[str], frozenset[str]]] = {
+ # kind: (required, optional)
+ "localfs": (frozenset({"path"}), frozenset({"patterns"})),
+ "google_drive": (frozenset({"path"}), frozenset({"patterns"})),
+ "web_search": (frozenset({"queries"}), frozenset()),
+ "web_pages": (frozenset({"urls"}), frozenset()),
+}
+
+
@tool(
"open_source",
- "Open a data source and get a handle (src:<name>) plus a card of its methods. "
- "Kinds: localfs (args: path, patterns?); google_drive (args: path = the Drive "
- "folder's link or id, patterns?), read with the Google account signed in on "
- "this machine.",
+ "Open a source of items and get a handle (src:<name>) plus a card of its methods. "
+ "Kinds: localfs (args: path, patterns?) lists the files under a directory; "
+ "google_drive (args: path = the Drive folder's link or id, patterns?) lists the "
+ "files of a folder, read with the Google account signed in on this machine; "
+ "web_search (args: queries = a list of search queries) lists the web pages the "
+ "queries find; web_pages (args: urls = a list of res: handles whose text names "
+ "URLs, or of URLs) lists those pages, minus the pages a source opened in an "
+ "earlier turn already listed. Every item is read by a worker through read_input.",
{
"type": "object",
"properties": {
- "kind": {"type": "string", "enum": ["localfs", "google_drive"]},
+ "kind": {
+ "type": "string",
+ "enum": ["localfs", "google_drive", "web_search", "web_pages"],
+ },
"name": {"type": "string"},
"path": {"type": "string"},
"patterns": {"type": "array", "items": {"type": "string"}},
+ "queries": {"type": "array", "items": {"type": "string"}},
+ "urls": {"type": "array", "items": {"type": "string"}},
},
- "required": ["kind", "name", "path"],
+ "required": ["kind", "name"],
},
)
async def open_source(ctx: SessionContext, args: dict[str, Json]) -> Json:
- patterns = tuple(args.get("patterns", ()))
- src: FolderSource[Any]
+ kind: str = args["kind"]
+ required, optional = _KIND_ARGS[kind]
+ given = set(args) - {"kind", "name"}
+ missing = sorted(required - given)
+ foreign = sorted(given - required - optional)
+ if missing or foreign:
+ takes = sorted(required | optional)
+ detail = []
+ if missing:
+ detail.append(f"needs {missing}")
+ if foreign:
+ detail.append(f"does not take {foreign}")
+ raise ToolError(f"{kind} {' and '.join(detail)}; it takes {takes}")
+ src: Source[Any]
where: dict[str, Json]
- if args["kind"] == "google_drive":
- src = drive.GoogleDriveFolderSource(drive.folder_id_of(args["path"]), patterns)
- where = {"folder": src.folder_id}
+ if kind == "web_search":
+ queries = tuple(_strings(args["queries"], "queries"))
+ if not queries:
+ raise ToolError("web_search needs at least one query")
+ if not ctx.config.search_engine:
+ raise RuntimeError(
+ "no search engine is configured (AgentsConfig.search_engine)"
+ )
+ src = web.WebSearchSource(
+ ctx.config.search_engine, queries, sink=ctx.trace, ctx=ctx
+ )
+ where = {"engine": ctx.config.search_engine, "queries": list(queries)}
+ elif kind == "web_pages":
+ named = _named_urls(ctx, _strings(args["urls"], "urls"))
+ exclude_requested, exclude_final = web.exclusions(
+ ctx.handles.objects().values()
+ )
+ src = web.WebPagesSource.admit(
+ named, exclude_requested, exclude_final, sink=ctx.trace, ctx=ctx
+ )
+ where = {"urls": list(args["urls"])}
else:
- src = LocalDirSource(pathlib.Path(args["path"]), patterns)
- where = {"root": str(src.root)}
+ patterns = tuple(_strings(args.get("patterns", ()), "patterns"))
+ if kind == "google_drive":
+ src = drive.GoogleDriveFolderSource(
+ drive.folder_id_of(args["path"]), patterns
+ )
+ where = {"folder": src.folder_id, "patterns": list(patterns)}
+ else:
+ local = LocalDirSource(pathlib.Path(args["path"]), patterns)
+ src = local
+ where = {"root": str(local.root), "patterns": list(patterns)}
handle = ctx.handles.register("src", args["name"], src)
stats = await src.call("stats", {})
ctx.trace.note_read(f"stats of {handle}", digest_json(stats))
- return ctx.handles.card(handle, **where, patterns=list(src.patterns), **stats)
+ if isinstance(src, web.WebSource):
+ ctx.action.details.extend(src.details())
+ return ctx.handles.card(handle, **where, **stats)
+
+
+def _strings(value: Json, name: str) -> list[str]:
+ # The shallow validator does not type array items.
+ if not isinstance(value, (list, tuple)) or not all(
+ isinstance(v, str) for v in value
+ ):
+ raise ToolError(f"{name} must be a list of strings")
+ return list(value)
+
+
+def _named_urls(ctx: SessionContext, entries: list[str]) -> list[str]:
+ """The URLs a ``web_pages`` source is given: the URLs in each result's text,
+ then the literal URLs, canonical, deduplicated, in the order given."""
+ named: list[str] = []
+ for entry in entries:
+ if is_handle(entry):
+ res = ctx.handles.get(entry)
+ if not isinstance(res, ResultValue):
+ raise ToolError(f"{entry!r} is a {res.kind} handle, not a result")
+ urls = web.urls_in(res.text)
+ else:
+ url = web.canonical_url(entry)
+ if url is None:
+ raise ToolError(
+ f"{entry!r} is neither a res: handle nor an http(s) URL"
+ )
+ urls = [url]
+ named.extend(u for u in urls if u not in named)
+ return named
@tool(
@@ -252,7 +343,7 @@ async def call_method(ctx: SessionContext, args: dict[str, Json]) -> Json:
@tool(
"read_input",
- "Read this session's input: for a text file, {key, text}; for a PDF, a reference "
+ "Read this session's input: for a text item, {key, text}; for a PDF, a reference "
"{key, media_type, bytes, digest} with the document attached to your next message; "
"for a reduce, the list of partial results.",
closed_ok=True,
@@ -261,9 +352,9 @@ async def read_input(ctx: SessionContext, args: dict[str, Json]) -> Json:
if ctx.input is None:
raise ToolError("this session has no input; it is an open session")
if isinstance(ctx.input, Item):
- media_type = document_media_type(ctx.input.key)
+ media_type = resource_media_type(ctx.input.key, ctx.input.resource)
if media_type is None:
- return {"key": ctx.input.key, "text": await ctx.input.file.read_text()}
- data = await ctx.input.file.read()
+ return {"key": ctx.input.key, "text": await ctx.input.resource.read_text()}
+ data = await ctx.input.resource.read()
return ctx.documents.attach(Document.of(ctx.input.key, media_type, data))
return list(ctx.input)
diff --git a/examples/cocoindex_agents/cocoindex_agents/tools/web.py b/examples/cocoindex_agents/cocoindex_agents/tools/web.py
new file mode 100644
index 00000000..7b32eb7b
--- /dev/null
+++ b/examples/cocoindex_agents/cocoindex_agents/tools/web.py
@@ -0,0 +1,1437 @@
+"""The web as a source: a search or a set of pages lists pages (DESIGN.md Β§0, Β§3).
+
+Two listing kinds, one resource kind:
+
+- ``web_search`` lists the pages a set of queries finds, through a
+ ``SearchEngine`` chosen by the environment (never by the model), with a
+ **frontier** rule that keeps the set stable under rank jitter: a page
+ chosen last run stays while any query still returns it within its top
+ ``2k``; new pages enter from a query's top ``k`` while the budget has room.
+- ``web_pages`` lists the pages a result (``res:`` handle) or a literal list
+ names, minus the pages another web source of the session already listed,
+ so a lead that is an alias of a page already read is one resource, not two.
+
+A page is a resource (``WebPage``, a ``FileLike``): its key is the canonical
+final URL, its content is the page normalized (title and main content as
+Markdown by trafilatura; a PDF as a document), and its content state is the
+digest of that normalized content, so a worker over an unchanged digest is
+skipped and a timestamp, a nonce or a comment count changes nothing.
+
+Every fetch happens in the listing, in the body of the session that opened
+the source, never in a worker: conditional requests from a **response cache**
+(per requested URL: final URL, validators, and the digest of the payload the
+validators were obtained with), payloads kept by version in a **payload
+store** (per final URL and digest), both in the session's ``use_state`` and
+pruned to the current listings when the body finishes. A 304 reuses exactly
+the version its validators name, or the URL is fetched again. Redirects are
+followed hop by hop, and a chain that lands on a final URL already fetched
+this run takes that fetch's response snapshot, so two aliases cannot observe
+two versions in one run.
+
+What a listing records (``SEARCH_OBSERVATION``, ``PAGES_OBSERVATION``) is
+what its validator needs to reproduce it from the record alone: the frontier,
+the requested-to-final mapping, each page's validators and digest, and the
+unavailable pages with their reasons. Validators never raise for the
+environment: an engine outage or an exhausted transient fetch makes the record
+invalid, the body re-runs and contains the trouble where it meets it.
+
+Unavailable pages: a permanent outcome (404, 403, robots, a sign-in page, an
+unsupported media type, a PDF over the cap) is data β€” the page is left out and
+recorded with its reason; an exhausted transient outcome (429, 503, a timeout,
+after retries) is an environment failure contained per page β€” left out,
+marked ``transient``, and recorded as a contained failure of the session so
+the fetch is tried again next run. Fetch trouble never reaches a fan-out's
+``failed`` count, because workers do not fetch.
+
+Politeness: one ``User-Agent`` naming the project, ``robots.txt`` per host,
+``Crawl-delay`` honoured up to ten seconds, one request at a time per host and
+at most four in flight, a 20-second timeout, 2 MiB for HTML and 8 MiB for a
+PDF, five redirect hops, no cookies, ``GET`` only, and no sign-in: a 401 or
+403, a login path, or a page that only asks to sign in is unavailable.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import base64
+import hashlib
+import logging
+import re
+import time
+import urllib.parse
+import urllib.robotparser
+from collections.abc import Callable, Iterable, Mapping
+from dataclasses import dataclass, field, replace
+from datetime import datetime, timezone
+from pathlib import PurePath, PurePosixPath
+from typing import TYPE_CHECKING, ClassVar, Protocol, Self
+
+import cocoindex as coco
+import httpx
+import lxml.etree
+import lxml.html
+import trafilatura
+from cocoindex._internal.api import StateHandle
+from cocoindex.connectorkits.fingerprint import fingerprint_bytes
+from cocoindex.resources import file as _file
+
+from ..documents import Document
+from ..errors import ToolError, TransientError, record_contained_failure, retrying
+from ..spec import Json
+from ..trace import TraceSink
+from ..transcript import canonical_json
+from .source import Source, content_of, item_key_arg
+
+if TYPE_CHECKING:
+ from . import SessionContext
+
+logger = logging.getLogger(__name__)
+
+USER_AGENT = "cocoindex-agents/0.1 (+https://github.com/cocoindex-io/cocoindex)"
+
+# The frontier: ``K`` results per query are candidates, ``2 * K`` keep an
+# incumbent; a search source reads at most SEARCH_BUDGET pages and a page set
+# at most PAGES_BUDGET. Both budgets sit inside one widened-count bucket
+# (9–15 render ``8–16``, 4–7 render ``4–8``), so a page or two unavailable does
+# not move the card (DESIGN.md Β§5).
+K = 4
+SEARCH_BUDGET = 12
+PAGES_BUDGET = 6
+
+HTML_CAP = 2 * 1024 * 1024
+PDF_CAP = 8 * 1024 * 1024
+TEXT_CAP = 40_000 # characters of normalized text a worker reads
+TIMEOUT_SECONDS = 20.0
+MAX_HOPS = 5
+MAX_IN_FLIGHT = 4
+MAX_CRAWL_DELAY = 10.0
+# trafilatura's precision mode drops link-heavy sections; under this many
+# characters its default extractor is tried instead.
+THIN_PRECISION = 500
+# A page whose normalized text is this short and asks to sign in is a sign-in page.
+SIGN_IN_TEXT = 200
+
+_SIGN_IN_PATH = re.compile(r"/(login|log-in|signin|sign-in|auth)(/|$)", re.I)
+_SIGN_IN_TEXT = re.compile(r"\b(sign in|log in|login|signin)\b", re.I)
+_URL = re.compile(r"https?://[^\s<>()\"'\]\[]+")
+_TRACKING = {"fbclid", "gclid", "mc_cid", "mc_eid", "igshid", "ref_src"}
+
+EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
+
+
+# --- search engines -----------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class SearchHit:
+ url: str
+ title: str
+
+
+class SearchEngine(Protocol):
+ """A ranked web search. ``identity`` names the engine and the configuration
+ that affects its results (``wikipedia:en``, ``tavily:basic``), never a
+ credential; it is tracked through ``AgentsConfig.search_engine`` and named
+ in every record."""
+
+ @property
+ def identity(self) -> str: ...
+
+ async def search(self, query: str, k: int) -> list[SearchHit]:
+ """The top ``k`` hits. Raises ``TransientError`` for trouble worth a
+ retry (a 429, a 5xx, a timeout); anything else is an environment
+ failure."""
+ ...
+
+
+# The engines a process knows, by identity. Validators run without a component
+# context, so they look the engine up here from the identity the record names;
+# an identity nobody registered makes the record invalid, not the run fail.
+_ENGINES: dict[str, SearchEngine] = {}
+# The HTTP transport every client of this module uses: ``None`` is the network;
+# a test sets ``httpx.MockTransport``.
+_TRANSPORT: httpx.AsyncBaseTransport | None = None
+# The backoff ``errors.retrying`` uses here; ``None`` is its default (one second
+# to thirty). A test sets a zero backoff so an exhausted retry takes no time.
+_backoff: Callable[[int], float] | None = None
+# The key under which a session's context remembers that this body run already
+# bumped the stores' run index and registered the pruning hook.
+_RUN_STARTED = "web:run-started"
+
+
+def register_engine(engine: SearchEngine) -> SearchEngine:
+ _ENGINES[engine.identity] = engine
+ return engine
+
+
+def set_transport(transport: httpx.AsyncBaseTransport | None) -> None:
+ global _TRANSPORT
+ _TRANSPORT = transport
+
+
+def http_client() -> httpx.AsyncClient:
+ """One client per listing or validation: no cookies, no automatic redirects
+ (they are followed hop by hop, below), the project's ``User-Agent``."""
+ return httpx.AsyncClient(
+ transport=_TRANSPORT,
+ follow_redirects=False,
+ timeout=TIMEOUT_SECONDS,
+ headers={
+ "User-Agent": USER_AGENT,
+ "Accept": "text/html,application/xhtml+xml,application/pdf,text/plain,text/markdown;q=0.9,*/*;q=0.5",
+ },
+ )
+
+
+def _transient_status(status: int) -> bool:
+ return status == 429 or status >= 500
+
+
+class WikipediaSearch:
+ """The MediaWiki search API: no key, free, a descriptive ``User-Agent``
+ (Wikimedia's policy) and well under its 200 requests a minute."""
+
+ def __init__(self, language: str = "en") -> None:
+ self.language = language
+
+ @property
+ def identity(self) -> str:
+ return f"wikipedia:{self.language}"
+
+ async def search(self, query: str, k: int) -> list[SearchHit]:
+ host = f"https://{self.language}.wikipedia.org"
+ params = {
+ "action": "query",
+ "list": "search",
+ "srsearch": query,
+ "srlimit": str(k),
+ "format": "json",
+ }
+ async with http_client() as client:
+ try:
+ response = await client.get(f"{host}/w/api.php", params=params)
+ except httpx.TransportError as exc:
+ raise TransientError(f"wikipedia search: {exc}") from exc
+ if _transient_status(response.status_code):
+ raise TransientError(f"wikipedia search: HTTP {response.status_code}")
+ response.raise_for_status()
+ hits = response.json().get("query", {}).get("search", [])
+ return [
+ SearchHit(
+ f"{host}/wiki/" + urllib.parse.quote(h["title"].replace(" ", "_")),
+ h["title"],
+ )
+ for h in hits
+ ]
+
+
+class TavilySearch:
+ """Tavily Search, basic depth: one credit per query on its free tier."""
+
+ def __init__(self, api_key: str) -> None:
+ self._api_key = api_key
+
+ @property
+ def identity(self) -> str:
+ return "tavily:basic"
+
+ async def search(self, query: str, k: int) -> list[SearchHit]:
+ async with http_client() as client:
+ try:
+ response = await client.post(
+ "https://api.tavily.com/search",
+ json={"query": query, "max_results": k, "search_depth": "basic"},
+ headers={"Authorization": f"Bearer {self._api_key}"},
+ )
+ except httpx.TransportError as exc:
+ raise TransientError(f"tavily search: {exc}") from exc
+ if _transient_status(response.status_code):
+ raise TransientError(f"tavily search: HTTP {response.status_code}")
+ response.raise_for_status()
+ return [
+ SearchHit(r["url"], r.get("title") or r["url"])
+ for r in response.json().get("results", [])
+ ]
+
+
+# --- URLs ---------------------------------------------------------------------
+
+
+def canonical_url(url: str) -> str | None:
+ """The canonical form of an ``http(s)`` URL, or ``None`` for anything else.
+
+ Scheme and host lower-cased, the default port and the fragment dropped,
+ tracking parameters dropped, query parameters sorted, an empty path made
+ ``/``. Two spellings of one address are one key.
+ """
+ try:
+ parts = urllib.parse.urlsplit(url.strip())
+ except ValueError:
+ return None
+ scheme = parts.scheme.lower()
+ if scheme not in ("http", "https") or not parts.hostname:
+ return None
+ host = parts.hostname.lower()
+ port = parts.port
+ if port is not None and port != (443 if scheme == "https" else 80):
+ host = f"{host}:{port}"
+ query = [
+ (k, v)
+ for k, v in urllib.parse.parse_qsl(parts.query, keep_blank_values=True)
+ if not (k.startswith("utm_") or k in _TRACKING)
+ ]
+ return urllib.parse.urlunsplit(
+ (scheme, host, parts.path or "/", urllib.parse.urlencode(sorted(query)), "")
+ )
+
+
+def urls_in(text: str) -> list[str]:
+ """The canonical ``http(s)`` URLs a text names, deduplicated, in first-seen order."""
+ out: list[str] = []
+ for raw in _URL.findall(text):
+ url = canonical_url(raw.rstrip(".,;:!?"))
+ if url is not None and url not in out:
+ out.append(url)
+ return out
+
+
+# --- fetching -----------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class Validators:
+ etag: str | None = None
+ last_modified: str | None = None
+
+ def headers(self) -> dict[str, str]:
+ out = {}
+ if self.etag:
+ out["If-None-Match"] = self.etag
+ if self.last_modified:
+ out["If-Modified-Since"] = self.last_modified
+ return out
+
+ @classmethod
+ def of(cls, response: httpx.Response) -> Validators:
+ return cls(response.headers.get("etag"), response.headers.get("last-modified"))
+
+
+@dataclass(frozen=True)
+class Fetched:
+ """A final response: a 200 with its body, or a 304 (``body`` is ``None``)."""
+
+ final_url: str
+ status: int
+ validators: Validators
+ content_type: str
+ body: bytes | None
+ truncated: bool = False # an HTML body cut at the cap
+
+
+@dataclass(frozen=True)
+class Unavailable:
+ """A page that could not be read. ``transient`` marks an exhausted retry
+ (an environment failure contained per page); the rest is data."""
+
+ reason: str
+ transient: bool = False
+ detail: str = ""
+
+
+class Fetcher:
+ """Polite fetching for one run: robots per host, one request at a time per
+ host, a global ceiling, hop-by-hop redirects, and one response snapshot per
+ final URL so aliases share a fetch."""
+
+ def __init__(self, client: httpx.AsyncClient) -> None:
+ self._client = client
+ self._robots: dict[str, urllib.robotparser.RobotFileParser | None] = {}
+ self._host_locks: dict[str, asyncio.Lock] = {}
+ self._last_request: dict[str, float] = {}
+ self._in_flight = asyncio.Semaphore(MAX_IN_FLIGHT)
+ self.snapshots: dict[str, Fetched] = {} # by final URL, this run
+
+ async def fetch(
+ self, requested: str, previous: tuple[str, Validators] | None
+ ) -> Fetched | Unavailable:
+ """Fetch a requested URL; ``previous`` is the final URL and validators of
+ the response the caller holds, sent as a conditional request when the
+ chain reaches that final URL again. Transient trouble is retried
+ (``errors.retrying``); when exhausted it is an ``Unavailable`` marked
+ transient, never an exception."""
+ try:
+ return await retrying(
+ lambda: self._fetch_once(requested, previous), backoff=_backoff
+ )
+ except TransientError as exc:
+ return Unavailable("transient", transient=True, detail=str(exc))
+
+ async def _fetch_once(
+ self, requested: str, previous: tuple[str, Validators] | None
+ ) -> Fetched | Unavailable:
+ url = requested
+ for _hop in range(MAX_HOPS + 1):
+ if url in self.snapshots:
+ return self.snapshots[url]
+ if _SIGN_IN_PATH.search(urllib.parse.urlsplit(url).path):
+ return Unavailable("sign-in", detail=url)
+ if not await self._allowed(url):
+ return Unavailable("robots", detail=url)
+ headers = {}
+ if previous is not None and previous[0] == url:
+ headers = previous[1].headers()
+ response = await self._request(url, headers)
+ status = response.status_code
+ if 300 <= status < 400 and response.headers.get("location"):
+ nxt = canonical_url(
+ urllib.parse.urljoin(url, response.headers["location"])
+ )
+ if nxt is None:
+ return Unavailable("redirect", detail=response.headers["location"])
+ url = nxt
+ continue
+ if status == 304:
+ assert previous is not None
+ return Fetched(url, 304, previous[1], "", None)
+ if status in (401, 403):
+ return Unavailable("sign-in", detail=f"HTTP {status}")
+ if status in (404, 410):
+ return Unavailable("not-found", detail=f"HTTP {status}")
+ if _transient_status(status):
+ raise TransientError(f"HTTP {status} for {url}")
+ if status != 200:
+ return Unavailable(f"http-{status}")
+ content_type = (
+ response.headers.get("content-type", "").split(";")[0].strip().lower()
+ )
+ kind = _content_kind(content_type)
+ if kind is None:
+ return Unavailable("unsupported-media-type", detail=content_type)
+ cap = PDF_CAP if kind == "pdf" else HTML_CAP
+ body, over = await _read_capped(response, cap)
+ if over and kind == "pdf":
+ return Unavailable("too-large", detail=f"over {PDF_CAP} bytes")
+ fetched = Fetched(
+ url, 200, Validators.of(response), content_type, body, over
+ )
+ self.snapshots[url] = fetched
+ return fetched
+ return Unavailable("redirect", detail=f"more than {MAX_HOPS} hops")
+
+ async def _request(self, url: str, headers: dict[str, str]) -> httpx.Response:
+ host = _host_of(url)
+ lock = self._host_locks.setdefault(host, asyncio.Lock())
+ async with lock:
+ # The crawl delay is waited out under the host's lock alone, so a
+ # slow host does not hold one of the four in-flight slots idle.
+ wait = self._last_request.get(host, 0.0) + self._crawl_delay(host)
+ if wait > time.monotonic():
+ await asyncio.sleep(wait - time.monotonic())
+ async with self._in_flight:
+ try:
+ return await self._client.send(
+ self._client.build_request("GET", url, headers=headers),
+ stream=True,
+ )
+ except httpx.TransportError as exc:
+ raise TransientError(f"{type(exc).__name__} for {url}") from exc
+ finally:
+ self._last_request[host] = time.monotonic()
+
+ async def _allowed(self, url: str) -> bool:
+ host = _host_of(url)
+ if host not in self._robots:
+ self._robots[host] = await self._load_robots(host)
+ rules = self._robots[host]
+ return rules is None or rules.can_fetch(USER_AGENT, url)
+
+ async def _load_robots(
+ self, host: str
+ ) -> urllib.robotparser.RobotFileParser | None:
+ """The host's robots.txt, or ``None`` when it has none we can read (then
+ everything is allowed, as the protocol says for a missing file)."""
+ try:
+ response = await self._client.get(f"{host}/robots.txt")
+ except httpx.TransportError:
+ return None
+ if response.status_code != 200:
+ return None
+ rules = urllib.robotparser.RobotFileParser()
+ rules.parse(response.text.splitlines())
+ return rules
+
+ def _crawl_delay(self, host: str) -> float:
+ rules = self._robots.get(host)
+ delay = rules.crawl_delay(USER_AGENT) if rules is not None else None
+ return min(float(delay), MAX_CRAWL_DELAY) if delay else 0.0
+
+
+def _host_of(url: str) -> str:
+ """The robots and politeness key: scheme and authority."""
+ parts = urllib.parse.urlsplit(url)
+ return f"{parts.scheme}://{parts.netloc}"
+
+
+def _content_kind(content_type: str) -> str | None:
+ if content_type in ("text/html", "application/xhtml+xml"):
+ return "html"
+ if content_type in ("text/plain", "text/markdown", "text/x-markdown"):
+ return "text"
+ if content_type == "application/pdf":
+ return "pdf"
+ return None
+
+
+async def _read_capped(response: httpx.Response, cap: int) -> tuple[bytes, bool]:
+ chunks: list[bytes] = []
+ size = 0
+ over = False
+ try:
+ async for chunk in response.aiter_bytes():
+ chunks.append(chunk)
+ size += len(chunk)
+ if size > cap:
+ over = True
+ break
+ except httpx.TransportError as exc:
+ raise TransientError(
+ f"{type(exc).__name__} while reading {response.url}"
+ ) from exc
+ finally:
+ await response.aclose()
+ return b"".join(chunks)[:cap], over
+
+
+# --- normalization ------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class Normalized:
+ """A page's content as the model reads it: a title and Markdown, or a PDF."""
+
+ title: str
+ text: str | None # Markdown; ``None`` for a document
+ pdf: bytes | None = None
+ truncated: bool = False
+
+ @property
+ def media_type(self) -> str | None:
+ return "application/pdf" if self.pdf is not None else None
+
+ def digest(self) -> str:
+ """The content state: title and text, or the engine's fingerprint of the PDF."""
+ if self.pdf is not None:
+ return fingerprint_bytes(self.pdf).hex()
+ return hashlib.sha256(
+ (self.title + "\n\x00\n" + (self.text or "")).encode("utf-8")
+ ).hexdigest()
+
+
+def normalize(fetched: Fetched) -> Normalized:
+ """A pure function of the response: trafilatura for HTML (precision first, its
+ default extractor when precision is thin), the text itself for text and
+ Markdown, the bytes for a PDF. No clock, no metadata extraction."""
+ assert fetched.body is not None
+ kind = _content_kind(fetched.content_type)
+ if kind == "pdf":
+ return Normalized(
+ title=PurePosixPath(fetched.final_url).name, text=None, pdf=fetched.body
+ )
+ text = fetched.body.decode("utf-8", errors="replace")
+ if kind == "text":
+ return Normalized(_first_line(text), _cap_text(text, fetched.truncated))
+ title = _html_title(text) or PurePosixPath(fetched.final_url).name
+
+ def extract(favor_precision: bool) -> str | None:
+ return trafilatura.extract(
+ text,
+ url=fetched.final_url,
+ output_format="markdown",
+ include_links=True,
+ include_tables=True,
+ include_comments=False,
+ deduplicate=False,
+ with_metadata=False,
+ favor_precision=favor_precision,
+ )
+
+ body = extract(favor_precision=True)
+ if body is None or len(body) < THIN_PRECISION:
+ body = extract(favor_precision=False) or body or ""
+ return Normalized(
+ title, _cap_text(body, fetched.truncated), truncated=fetched.truncated
+ )
+
+
+def _cap_text(text: str, truncated_body: bool) -> str:
+ text = text.strip()
+ if len(text) > TEXT_CAP or truncated_body:
+ return text[:TEXT_CAP].rstrip() + "\n\n[truncated]"
+ return text
+
+
+def _first_line(text: str) -> str:
+ for line in text.splitlines():
+ if line.strip():
+ return line.strip().lstrip("# ")[:200]
+ return ""
+
+
+def _html_title(html: str) -> str:
+ try:
+ tree = lxml.html.fromstring(html)
+ except (ValueError, lxml.etree.ParserError, lxml.etree.XMLSyntaxError):
+ return ""
+ for xpath in ('//meta[@property="og:title"]/@content', "//title/text()"):
+ found = tree.xpath(xpath)
+ if found and str(found[0]).strip():
+ return " ".join(str(found[0]).split())[:200]
+ return ""
+
+
+def looks_like_sign_in(normalized: Normalized) -> bool:
+ text = normalized.text or ""
+ return len(text) < SIGN_IN_TEXT and bool(
+ _SIGN_IN_TEXT.search(text + " " + normalized.title)
+ )
+
+
+# --- the resource -------------------------------------------------------------
+
+
+class PageUrl(_file.FilePath[str]):
+ """A page's address as its ``FilePath``: the resolved path is the URL itself."""
+
+ __slots__ = ("_url",)
+
+ def __init__(self, url: str) -> None:
+ super().__init__(None, PurePosixPath(urllib.parse.urlsplit(url).path or "/"))
+ self._url = url
+
+ def resolve(self) -> str:
+ return self._url
+
+ def _with_path(self, path: PurePath) -> Self:
+ return type(self)(self._url) # type: ignore[return-value]
+
+ def __coco_memo_key__(self) -> object:
+ return ("web", self._url)
+
+ def __eq__(self, other: object) -> bool:
+ return isinstance(other, PageUrl) and other._url == self._url
+
+ def __hash__(self) -> int:
+ return hash(self._url)
+
+
+class WebPage(_file.FileLike[str]):
+ """A page as a resource: keyed by its canonical final URL, memoized on the
+ digest of its normalized content (``FileMetadata.content_fingerprint``;
+ the modification time is fixed, so only the digest decides).
+
+ What ``read()`` returns is what a worker reads: a header the system
+ writes (``# <title>``, ``URL: <url>``) and the Markdown, or a PDF's bytes.
+ No time is in it (DESIGN.md Β§3, no timestamps in tool results).
+ """
+
+ def __init__(self, url: str, normalized: Normalized, digest: str) -> None:
+ self.title = normalized.title
+ self.digest = digest
+ self.media_type = normalized.media_type
+ if normalized.pdf is not None:
+ self._data = normalized.pdf
+ else:
+ header = f"# {normalized.title}\nURL: {url}\n\n"
+ self._data = (header + (normalized.text or "")).encode("utf-8")
+ super().__init__(
+ PageUrl(url),
+ _metadata=_file.FileMetadata(
+ size=len(self._data),
+ modified_time=EPOCH,
+ content_fingerprint=bytes.fromhex(digest),
+ ),
+ )
+
+ @property
+ def url(self) -> str:
+ return self._file_path.resolve()
+
+ async def _fetch_metadata(self) -> _file.FileMetadata:
+ assert self._metadata is not None
+ return self._metadata
+
+ async def _read_impl(self, size: int = -1) -> bytes:
+ return self._data if size < 0 else self._data[:size]
+
+
+# --- stores in use_state ------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class ResponseEntry:
+ """What a requested URL last answered: where it ended, the validators, and
+ the digest of the payload those validators were obtained with."""
+
+ final_url: str
+ etag: str | None
+ last_modified: str | None
+ digest: str
+ run: int
+
+ def validators(self) -> Validators:
+ return Validators(self.etag, self.last_modified)
+
+
+@dataclass(frozen=True)
+class Payload:
+ """One version of a page's content, immutable once written."""
+
+ title: str
+ text: str | None
+ pdf_b64: str | None
+ truncated: bool
+ first_fetched: str # UTC, to the minute: for the trace, never for the model
+ run: int
+
+ def normalized(self) -> Normalized:
+ pdf = base64.b64decode(self.pdf_b64) if self.pdf_b64 is not None else None
+ return Normalized(self.title, self.text, pdf, self.truncated)
+
+
+def payload_key(final_url: str, digest: str) -> str:
+ return f"{final_url}\n{digest}"
+
+
+@dataclass
+class WebStores:
+ """The session's response cache, payload store and frontier history."""
+
+ run: int = 0
+ responses: dict[str, ResponseEntry] = field(default_factory=dict)
+ payloads: dict[str, Payload] = field(default_factory=dict)
+ frontiers: dict[str, tuple[str, ...]] = field(default_factory=dict)
+
+ def prune(self, run: int) -> None:
+ """Drop response entries no listing of ``run`` named, then payload
+ versions no response entry references."""
+ self.responses = {u: e for u, e in self.responses.items() if e.run == run}
+ live = {payload_key(e.final_url, e.digest) for e in self.responses.values()}
+ self.payloads = {k: p for k, p in self.payloads.items() if k in live}
+
+
+def _now_minute() -> str:
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%MZ")
+
+
+# --- records ------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class PageRecord:
+ """One requested URL in a listing's record: where it ended and what it held,
+ or why it was unavailable."""
+
+ requested: str
+ final_url: str | None = None
+ etag: str | None = None
+ last_modified: str | None = None
+ digest: str | None = None
+ reason: str | None = None
+ transient: bool = False
+
+ def validators(self) -> Validators:
+ return Validators(self.etag, self.last_modified)
+
+ def summary(self) -> str:
+ return self.reason or (self.digest or "?")[:8]
+
+
+@dataclass(frozen=True)
+class ListingRecord:
+ """What a web source records, once per run whatever was observed through it:
+ enough for its validator to reproduce the listing and compare. Every
+ observation of the source (``stats``, ``sample``, ``keys``, the fan-out's
+ listing) is a pure function of the listing, so they share one record under
+ one key, and an unchanged rerun validates the source once: one search per
+ query and one conditional request per page. ``frontier`` is the sorted set
+ of requested URLs chosen; ``pages`` is sorted by requested URL."""
+
+ frontier: tuple[str, ...]
+ pages: tuple[PageRecord, ...]
+
+ def content(self) -> tuple[object, ...]:
+ """What decides validity: the frontier and each page's final URL, digest
+ and reason β€” not its validators, which an origin may rotate (a CDN's
+ ETag per edge) while the content stands; a validation that saw new
+ validators refreshes the record and stays valid."""
+ return (
+ self.frontier,
+ tuple(
+ (p.requested, p.final_url, p.digest, p.reason, p.transient)
+ for p in self.pages
+ ),
+ )
+
+ def differences(self, other: ListingRecord) -> list[str]:
+ """What changed between two records, for the log."""
+ out = []
+ if self.frontier != other.frontier:
+ out.append(f"frontier {sorted(set(self.frontier) ^ set(other.frontier))}")
+ mine = {p.requested: p for p in self.pages}
+ theirs = {p.requested: p for p in other.pages}
+ for requested in sorted(set(mine) | set(theirs)):
+ a, b = mine.get(requested), theirs.get(requested)
+ if a is None or b is None:
+ out.append(f"{requested}: {'gone' if b is None else 'new'}")
+ elif (a.final_url, a.digest, a.reason) != (b.final_url, b.digest, b.reason):
+ out.append(f"{requested}: {a.summary()} -> {b.summary()}")
+ return out
+
+
+@dataclass(frozen=True)
+class SearchKey:
+ engine: str
+ k: int
+ queries: tuple[str, ...]
+
+
+@dataclass(frozen=True)
+class PagesKey:
+ urls: tuple[str, ...] # sorted admitted requested URLs
+ exclude_requested: tuple[str, ...]
+ exclude_final: tuple[str, ...]
+
+
+# A page read by an open session (a planner): the canonical URL, and what it held.
+PageReadState = tuple[str, str | None, str | None, str] | None
+
+
+# --- the listing computation --------------------------------------------------
+
+
+def frontier(
+ prev: Iterable[str], results: Mapping[str, list[str]], k: int, budget: int
+) -> list[str]:
+ """The pure frontier rule (DESIGN.md Β§3): incumbents β€” URLs of ``prev`` that
+ some query still returns within its top ``2k`` β€” ordered by (best rank,
+ URL), then newcomers from the queries' top ``k``, ordered the same, cut at
+ ``budget``. No per-query quota."""
+ rank: dict[str, int] = {}
+ newcomer_ok: set[str] = set()
+ for urls in results.values():
+ seen: set[str] = set()
+ for i, url in enumerate(urls[: 2 * k]):
+ if url in seen:
+ continue
+ seen.add(url)
+ rank[url] = min(rank.get(url, i + 1), i + 1)
+ if i < k:
+ newcomer_ok.add(url)
+ prev_set = set(prev)
+ incumbents = sorted((u for u in rank if u in prev_set), key=lambda u: (rank[u], u))
+ newcomers = sorted(
+ (u for u in newcomer_ok if u not in prev_set), key=lambda u: (rank[u], u)
+ )
+ return (incumbents + newcomers)[:budget]
+
+
+@dataclass(frozen=True)
+class Page:
+ """A page a listing yielded this run."""
+
+ final_url: str
+ validators: Validators
+ normalized: Normalized
+ digest: str
+ first_fetched: str
+
+
+@dataclass
+class ListingResult:
+ frontier: list[str]
+ pages: dict[str, Page] # by final URL
+ records: dict[str, PageRecord] # by requested URL
+ transient: dict[str, str] # requested URL -> detail, for containment
+
+ def record(self) -> ListingRecord:
+ return ListingRecord(
+ tuple(sorted(self.frontier)),
+ tuple(self.records[u] for u in sorted(self.records)),
+ )
+
+
+class _History(Protocol):
+ """Where a listing takes its previous validators and payloads from: the
+ session's stores in the body, the record alone in a validator."""
+
+ def previous(self, requested: str) -> tuple[str, Validators, str] | None:
+ """(final URL, validators, digest) of the last response, if known."""
+ ...
+
+ def payload(self, final_url: str, digest: str) -> Normalized | None: ...
+
+ def first_fetched(self, final_url: str, digest: str) -> str | None:
+ """When this version was first fetched, if the history holds it."""
+ ...
+
+ def frontier(self, identity: str) -> tuple[str, ...]:
+ """The requested URLs a search source chose last run."""
+ ...
+
+ def remember_frontier(self, identity: str, chosen: Iterable[str]) -> None: ...
+
+
+class _StoreHistory:
+ def __init__(self, stores: WebStores) -> None:
+ self._stores = stores
+
+ def frontier(self, identity: str) -> tuple[str, ...]:
+ return self._stores.frontiers.get(identity, ())
+
+ def remember_frontier(self, identity: str, chosen: Iterable[str]) -> None:
+ self._stores.frontiers[identity] = tuple(sorted(chosen))
+
+ def previous(self, requested: str) -> tuple[str, Validators, str] | None:
+ entry = self._stores.responses.get(requested)
+ if entry is None:
+ return None
+ return entry.final_url, entry.validators(), entry.digest
+
+ def payload(self, final_url: str, digest: str) -> Normalized | None:
+ payload = self._stores.payloads.get(payload_key(final_url, digest))
+ return payload.normalized() if payload is not None else None
+
+ def first_fetched(self, final_url: str, digest: str) -> str | None:
+ payload = self._stores.payloads.get(payload_key(final_url, digest))
+ return payload.first_fetched if payload is not None else None
+
+
+# What a validator holds for a page a 304 confirmed: it compares digests and
+# never reads content, so any placeholder stands for the payload.
+_CONFIRMED = Normalized("", None)
+
+
+class _RecordHistory:
+ """A validator knows validators and digests, never payloads: a 304 confirms
+ the recorded digest (the placeholder above stands for the content), a 200 is
+ normalized and compared."""
+
+ def __init__(self, record: ListingRecord) -> None:
+ self._record = record
+ self._pages = {p.requested: p for p in record.pages}
+
+ def frontier(self, identity: str) -> tuple[str, ...]:
+ return self._record.frontier
+
+ def remember_frontier(self, identity: str, chosen: Iterable[str]) -> None:
+ pass # a validator records nothing
+
+ def previous(self, requested: str) -> tuple[str, Validators, str] | None:
+ page = self._pages.get(requested)
+ if page is None or page.final_url is None or page.digest is None:
+ return None
+ return page.final_url, page.validators(), page.digest
+
+ def payload(self, final_url: str, digest: str) -> Normalized | None:
+ return _CONFIRMED
+
+ def first_fetched(self, final_url: str, digest: str) -> str | None:
+ return None
+
+
+async def fetch_listing(
+ requested_urls: list[str],
+ fetcher: Fetcher,
+ history: _History,
+ *,
+ exclude_final: frozenset[str] = frozenset(),
+) -> ListingResult:
+ """Fetch every requested URL (conditionally where history allows), normalize,
+ and yield the pages by final URL. A requested URL whose final URL is in
+ ``exclude_final`` is suppressed after fetching and kept in the records as
+ an alias (DESIGN.md Β§3, ``web_pages``)."""
+ result = ListingResult(list(requested_urls), {}, {}, {})
+
+ async def one(requested: str) -> None:
+ prev = history.previous(requested)
+ outcome = await fetcher.fetch(
+ requested, (prev[0], prev[1]) if prev is not None else None
+ )
+ if isinstance(outcome, Unavailable):
+ result.records[requested] = PageRecord(
+ requested, reason=outcome.reason, transient=outcome.transient
+ )
+ if outcome.transient:
+ result.transient[requested] = outcome.detail
+ return
+ if outcome.status == 304:
+ assert prev is not None
+ final_url, validators, digest = prev
+ normalized = history.payload(final_url, digest)
+ if normalized is None:
+ # The version the validators name is gone: fetch again, unconditionally.
+ again = await fetcher.fetch(requested, None)
+ if isinstance(again, Unavailable):
+ result.records[requested] = PageRecord(
+ requested, reason=again.reason, transient=again.transient
+ )
+ if again.transient:
+ result.transient[requested] = again.detail
+ return
+ outcome = again
+ else:
+ _add_page(
+ result,
+ requested,
+ final_url,
+ validators,
+ normalized,
+ digest,
+ history,
+ exclude_final,
+ )
+ return
+ assert outcome.body is not None
+ normalized = normalize(outcome)
+ if looks_like_sign_in(normalized):
+ result.records[requested] = PageRecord(requested, reason="sign-in")
+ return
+ _add_page(
+ result,
+ requested,
+ outcome.final_url,
+ outcome.validators,
+ normalized,
+ normalized.digest(),
+ history,
+ exclude_final,
+ )
+
+ await asyncio.gather(*(one(u) for u in requested_urls))
+ return result
+
+
+def _add_page(
+ result: ListingResult,
+ requested: str,
+ final_url: str,
+ validators: Validators,
+ normalized: Normalized,
+ digest: str,
+ history: _History,
+ exclude_final: frozenset[str],
+) -> None:
+ result.records[requested] = PageRecord(
+ requested, final_url, validators.etag, validators.last_modified, digest
+ )
+ if final_url in exclude_final:
+ return # an alias of a page another listing read: suppressed, recorded
+ if final_url not in result.pages:
+ # The version's first-fetched time: kept when the payload store already
+ # holds this version (the body's history), new otherwise.
+ first = history.first_fetched(final_url, digest) or _now_minute()
+ result.pages[final_url] = Page(final_url, validators, normalized, digest, first)
+
+
+# --- the two sources ----------------------------------------------------------
+
+
+class WebSource(Source[WebPage]):
+ """What the two web kinds share: the run-local listing, the stores, the
+ records and the details for the plan."""
+
+ kind: ClassVar[str]
+ observation: ClassVar[coco.DataDep]
+
+ def __init__(self, sink: TraceSink | None, ctx: SessionContext | None) -> None:
+ # The session's context gives the stores (``ctx.state``) and the finish
+ # hook; a validator builds a source with neither and records nothing.
+ self._sink = sink
+ self._ctx = ctx
+ self._listing: ListingResult | None = None
+ self.patterns: tuple[str, ...] = ()
+
+ # -- the listing, once per run --
+
+ async def resources(self) -> dict[str, WebPage]:
+ listing = await self.listed()
+ return {
+ url: WebPage(url, page.normalized, page.digest)
+ for url, page in sorted(listing.pages.items())
+ }
+
+ async def listed(self) -> ListingResult:
+ if self._listing is None:
+ self._listing = await self._list_in_body()
+ return self._listing
+
+ def _stores(self) -> StateHandle[WebStores]:
+ assert self._ctx is not None
+ return self._ctx.state("web", WebStores(), WebStores)
+
+ def _begin_run(self) -> StateHandle[WebStores]:
+ """The stores for this body run: the first web source to touch them bumps
+ the run index and registers the pruning for when the body finishes."""
+ assert self._ctx is not None
+ handle = self._stores()
+ if _RUN_STARTED not in self._ctx.states:
+ handle.value.run += 1
+ self._ctx.states[_RUN_STARTED] = True
+ self._ctx.on_finish.append(lambda: self._finish(handle))
+ return handle
+
+ async def _list_in_body(self) -> ListingResult:
+ handle = self._begin_run()
+ stores = handle.value
+ async with http_client() as client:
+ result = await self._compute(Fetcher(client), _StoreHistory(stores))
+ self._remember(stores, result)
+ handle.value = stores
+ for requested, detail in sorted(result.transient.items()):
+ if self._sink is not None:
+ record_contained_failure(
+ self._sink, f"page:{requested}", TransientError(detail)
+ )
+ return result
+
+ def _finish(self, handle: StateHandle[WebStores]) -> None:
+ stores = handle.value
+ stores.prune(stores.run)
+ handle.value = stores
+
+ def _remember(self, stores: WebStores, result: ListingResult) -> None:
+ for page in result.pages.values():
+ key = payload_key(page.final_url, page.digest)
+ if key not in stores.payloads:
+ n = page.normalized
+ stores.payloads[key] = Payload(
+ n.title,
+ n.text,
+ base64.b64encode(n.pdf).decode("ascii")
+ if n.pdf is not None
+ else None,
+ n.truncated,
+ page.first_fetched,
+ stores.run,
+ )
+ else:
+ stores.payloads[key] = replace(stores.payloads[key], run=stores.run)
+ for requested, record in result.records.items():
+ if record.final_url is not None and record.digest is not None:
+ stores.responses[requested] = ResponseEntry(
+ record.final_url,
+ record.etag,
+ record.last_modified,
+ record.digest,
+ stores.run,
+ )
+ elif requested in stores.responses:
+ # Unavailable this run: the entry and its version stay, marked
+ # live, so the next run can still ask conditionally.
+ stores.responses[requested] = replace(
+ stores.responses[requested], run=stores.run
+ )
+
+ async def _compute(self, fetcher: Fetcher, history: _History) -> ListingResult:
+ """The listing: in the body over the session's stores, in a validator
+ over the record alone."""
+ raise NotImplementedError
+
+ # -- observations: one record per source, carrying the listing --
+
+ def observation_state(self, method: str, result: Json) -> object:
+ assert self._listing is not None
+ return self._listing.record()
+
+ async def entries(self, resources: dict[str, WebPage]) -> Json:
+ return [(url, page.digest) for url, page in resources.items()]
+
+ # -- what the plan shows --
+
+ def details(self) -> list[str]:
+ assert self._listing is not None
+ lines = []
+ for url, page in sorted(self._listing.pages.items()):
+ lines.append(f"{url} Β· {page.digest[:8]} Β· fetched {page.first_fetched}")
+ for requested in sorted(self._listing.records):
+ record = self._listing.records[requested]
+ if record.reason is not None:
+ lines.append(f"unavailable {requested} Β· {record.reason}")
+ return lines
+
+ # -- a read by an open session --
+
+ async def read(self, args: dict[str, Json]) -> str | Document:
+ url = canonical_url(item_key_arg(args))
+ if url is None:
+ raise ToolError("read needs an http(s) URL as `key`")
+ handle = self._begin_run()
+ stores = handle.value
+ async with http_client() as client:
+ result = await fetch_listing([url], Fetcher(client), _StoreHistory(stores))
+ self._remember(stores, result)
+ handle.value = stores
+ record = result.records[url]
+ state: PageReadState = None
+ if record.final_url is not None and record.digest is not None:
+ state = (record.final_url, record.etag, record.last_modified, record.digest)
+ coco.use_data_dep(PAGE_READ, key=url, state=state)
+ if url in result.transient and self._sink is not None:
+ record_contained_failure(
+ self._sink, f"page:{url}", TransientError(result.transient[url])
+ )
+ page = next(iter(result.pages.values()), None)
+ if page is None:
+ raise ToolError(f"page {url!r} is unavailable: {record.reason}")
+ resource = WebPage(page.final_url, page.normalized, page.digest)
+ return await content_of(page.final_url, resource, await resource.read())
+
+
+class WebSearchSource(WebSource):
+ """``web_search``: the pages a set of queries finds."""
+
+ kind = "web_search"
+
+ def __init__(
+ self,
+ engine_identity: str,
+ queries: tuple[str, ...],
+ sink: TraceSink | None = None,
+ ctx: SessionContext | None = None,
+ ) -> None:
+ super().__init__(sink, ctx)
+ self.engine_identity = engine_identity
+ self.queries = queries
+
+ def _identity(self) -> tuple[str, str, int, tuple[str, ...]]:
+ return ("web_search", self.engine_identity, K, self.queries)
+
+ def __coco_memo_key__(self) -> object:
+ return self._identity()
+
+ def identity_json(self) -> str:
+ """The memo key as a string: the frontier history's key in the stores."""
+ return canonical_json(list(self._identity()))
+
+ def observation_key(self, method: str, args: str) -> object:
+ return SearchKey(self.engine_identity, K, self.queries)
+
+ async def _compute(self, fetcher: Fetcher, history: _History) -> ListingResult:
+ engine = _ENGINES.get(self.engine_identity)
+ if engine is None:
+ raise RuntimeError(
+ f"no search engine registered for {self.engine_identity!r}"
+ )
+ prev_frontier = history.frontier(self.identity_json())
+
+ async def search(query: str) -> tuple[str, list[str]]:
+ hits = await retrying(lambda: engine.search(query, 2 * K), backoff=_backoff)
+ urls = [u for h in hits if (u := canonical_url(h.url)) is not None]
+ return query, urls
+
+ results = dict(await asyncio.gather(*(search(q) for q in self.queries)))
+ chosen = frontier(prev_frontier, results, K, SEARCH_BUDGET)
+ result = await fetch_listing(chosen, fetcher, history)
+ history.remember_frontier(self.identity_json(), chosen)
+ return result
+
+
+class WebPagesSource(WebSource):
+ """``web_pages``: the pages a list of URLs names, minus the pages other web
+ sources of the session listed (the turn's handle-table snapshot)."""
+
+ kind = "web_pages"
+
+ def __init__(
+ self,
+ urls: tuple[str, ...],
+ exclude_requested: frozenset[str],
+ exclude_final: frozenset[str],
+ sink: TraceSink | None = None,
+ ctx: SessionContext | None = None,
+ ) -> None:
+ super().__init__(sink, ctx)
+ self.urls = urls # sorted admitted requested URLs
+ self.exclude_requested = exclude_requested
+ self.exclude_final = exclude_final
+
+ @classmethod
+ def admit(
+ cls,
+ named: Iterable[str],
+ exclude_requested: frozenset[str],
+ exclude_final: frozenset[str],
+ sink: TraceSink | None = None,
+ ctx: SessionContext | None = None,
+ ) -> WebPagesSource:
+ """Apply the first exclusion stage and the budget in the order given,
+ then freeze the sorted effective list as the identity."""
+ admitted: list[str] = []
+ for url in named:
+ if url in exclude_requested or url in exclude_final or url in admitted:
+ continue
+ admitted.append(url)
+ if len(admitted) == PAGES_BUDGET:
+ break
+ return cls(tuple(sorted(admitted)), exclude_requested, exclude_final, sink, ctx)
+
+ def __coco_memo_key__(self) -> object:
+ return (
+ "web_pages",
+ self.urls,
+ tuple(sorted(self.exclude_requested)),
+ tuple(sorted(self.exclude_final)),
+ )
+
+ def observation_key(self, method: str, args: str) -> object:
+ return PagesKey(
+ self.urls,
+ tuple(sorted(self.exclude_requested)),
+ tuple(sorted(self.exclude_final)),
+ )
+
+ async def _compute(self, fetcher: Fetcher, history: _History) -> ListingResult:
+ return await fetch_listing(
+ list(self.urls), fetcher, history, exclude_final=self.exclude_final
+ )
+
+
+def exclusions(objects: Iterable[object]) -> tuple[frozenset[str], frozenset[str]]:
+ """The requested and final URLs every web source among ``objects`` has
+ listed: the exclusion sets of a ``web_pages`` source opened in a later turn."""
+ requested: set[str] = set()
+ final: set[str] = set()
+ for obj in objects:
+ if isinstance(obj, WebSource) and obj._listing is not None:
+ requested.update(obj._listing.records)
+ final.update(obj._listing.pages)
+ final.update(
+ r.final_url for r in obj._listing.records.values() if r.final_url
+ )
+ return frozenset(requested), frozenset(final)
+
+
+# --- validators ---------------------------------------------------------------
+
+# Observed with the scripted web (``test_research.py``): on a run whose body
+# re-runs, the engine validates the root session's records twice before the
+# body runs (its component entry, then the memoized function's entry), so a
+# listing is searched and fetched twice by validators and once by the body. A
+# localfs walk twice costs nothing; here it is a request per page. A window that
+# reused a verdict for a few seconds would hand a stale one to a user who edits
+# and reruns at once, so none is kept: the per-operation validation cache
+# belongs in the engine (DESIGN.md Β§7, framework roadmap).
+
+
+async def _validate_listing(
+ source: WebSource, prev: ListingRecord
+) -> coco.MemoStateOutcome:
+ """Reproduce the listing from the record alone and compare. Trouble with
+ the environment makes the record invalid; it never raises (the engine
+ would fail the run), except for cancellation and deadline expiry."""
+ try:
+ async with http_client() as client:
+ result = await source._compute(Fetcher(client), _RecordHistory(prev))
+ except (TransientError, httpx.HTTPError, RuntimeError, ValueError) as exc:
+ logger.warning("web listing validation could not run: %s", exc)
+ return coco.MemoStateOutcome(state=prev)
+ if result.transient:
+ return coco.MemoStateOutcome(state=prev)
+ record = result.record()
+ valid = record.content() == prev.content()
+ if not valid:
+ logger.debug("web listing changed: %s", "; ".join(prev.differences(record)))
+ return coco.MemoStateOutcome(state=record, memo_valid=valid)
+
+
+async def _validate_search(
+ key: SearchKey, prev: ListingRecord
+) -> coco.MemoStateOutcome:
+ return await _validate_listing(WebSearchSource(key.engine, key.queries), prev)
+
+
+async def _validate_pages(key: PagesKey, prev: ListingRecord) -> coco.MemoStateOutcome:
+ source = WebPagesSource(
+ key.urls, frozenset(key.exclude_requested), frozenset(key.exclude_final)
+ )
+ return await _validate_listing(source, prev)
+
+
+async def _validate_page_read(key: str, prev: PageReadState) -> coco.MemoStateOutcome:
+ """One conditional request; a page that did not exist validates while it
+ still does not."""
+ try:
+ async with http_client() as client:
+ fetcher = Fetcher(client)
+ previous = (
+ (prev[0], Validators(prev[1], prev[2])) if prev is not None else None
+ )
+ outcome = await fetcher.fetch(key, previous)
+ except (TransientError, httpx.HTTPError) as exc:
+ logger.warning("page read validation could not run: %s", exc)
+ return coco.MemoStateOutcome(state=prev)
+ if isinstance(outcome, Unavailable):
+ if outcome.transient:
+ return coco.MemoStateOutcome(state=prev)
+ return coco.MemoStateOutcome(state=None, memo_valid=prev is None)
+ if prev is None:
+ return coco.MemoStateOutcome(state=prev)
+ if outcome.status == 304:
+ return coco.MemoStateOutcome(state=prev, memo_valid=True)
+ normalized = normalize(outcome)
+ digest = normalized.digest()
+ state: PageReadState = (
+ outcome.final_url,
+ outcome.validators.etag,
+ outcome.validators.last_modified,
+ digest,
+ )
+ return coco.MemoStateOutcome(state=state, memo_valid=digest == prev[3])
+
+
+SEARCH_OBSERVATION = coco.DataDep(
+ "cocoindex_agents.web_search.observation", validate=_validate_search
+)
+PAGES_OBSERVATION = coco.DataDep(
+ "cocoindex_agents.web_pages.observation", validate=_validate_pages
+)
+PAGE_READ = coco.DataDep("cocoindex_agents.web.page", validate=_validate_page_read)
+
+WebSearchSource.observation = SEARCH_OBSERVATION
+WebPagesSource.observation = PAGES_OBSERVATION
+
+
+# --- configuration ------------------------------------------------------------
+
+
+def default_engine(environ: Mapping[str, str]) -> SearchEngine:
+ """The engine the environment selects: Tavily with ``TAVILY_API_KEY``, else
+ Wikipedia, which needs no key. Registered, so validators find it too."""
+ key = environ.get("TAVILY_API_KEY")
+ return register_engine(TavilySearch(key) if key else WikipediaSearch())
+
+
+__all__ = [
+ "K",
+ "PAGES_BUDGET",
+ "SEARCH_BUDGET",
+ "ListingRecord",
+ "PageRecord",
+ "SearchEngine",
+ "SearchHit",
+ "TavilySearch",
+ "WebPage",
+ "WebPagesSource",
+ "WebSearchSource",
+ "WebStores",
+ "WikipediaSearch",
+ "canonical_url",
+ "default_engine",
+ "exclusions",
+ "frontier",
+ "http_client",
+ "normalize",
+ "register_engine",
+ "set_transport",
+ "urls_in",
+]
diff --git a/examples/cocoindex_agents/cocoindex_agents/trace.py b/examples/cocoindex_agents/cocoindex_agents/trace.py
index a21ef9ef..1ad3dfc5 100644
--- a/examples/cocoindex_agents/cocoindex_agents/trace.py
+++ b/examples/cocoindex_agents/cocoindex_agents/trace.py
@@ -132,6 +132,9 @@ class ActionTrace:
task: str | None = None # a child's task, elided
child: ChildTrace | None = None
declared: DeclaredFile | None = None # a declare's file
+ details: tuple[
+ str, ...
+ ] = () # lines a tool reports about what it did (a web listing's pages)
@dataclass(frozen=True)
@@ -255,10 +258,12 @@ class TraceSink:
@dataclass
class ActionSink:
- """What one tool call reports: the child it mounted, or the file it declared."""
+ """What one tool call reports: the child it mounted, the file it declared,
+ or lines of detail for the plan (what a web listing fetched, and when)."""
child: ChildTrace | None = None
declared: DeclaredFile | None = None
+ details: list[str] = field(default_factory=list)
def answer_step(
diff --git a/examples/cocoindex_agents/flows/README.md b/examples/cocoindex_agents/flows/README.md
index 497c0ea0..18785c9d 100644
--- a/examples/cocoindex_agents/flows/README.md
+++ b/examples/cocoindex_agents/flows/README.md
@@ -1,8 +1,8 @@
# Sample flows
-Five small flows: one per shape of DESIGN.md Β§2, one over PDFs, and one over
-a Google Drive folder, each a directory with a `prompt.md` and (except
-`drive`) a few short input files. The prompts are written as a user
+Six small flows: one per shape of DESIGN.md Β§2, one over PDFs, one over a
+Google Drive folder and one over the web, each a directory with a
+`prompt.md` and (except `drive` and `research`) a few short input files. The prompts are written as a user
would write them: the outcome, where the data is, where the output goes, the
file naming when it matters, and what to answer. They do not mention workers,
planners or reducers; the orchestrator decomposes the task itself, following
@@ -17,6 +17,7 @@ many model calls the run made, per role.
| `table` | C. observe β†’ plan β†’ map | one JSON object per invoice under `invoices/`, columns chosen from the data |
| `orders` | A. map β†’ targets, over PDFs | one JSON object per purchase order under `orders/`, with the fields the prompt names, including which box of the Approval section is ticked |
| `drive` | A. map β†’ targets, over a Google Drive folder | one summary file per file in the Drive folder `$DRIVE_FOLDER`, `Meeting notes` β†’ `Meeting notes.summary.md` |
+| `research` | E. search β†’ read β†’ follow β†’ report, over the web | what incremental computation is and where it is used; search the web, read what is found, follow the leads worth following, write `out/report.md` with citations |
The purchase orders are PDFs the model reads natively (DESIGN.md Β§3,
*Documents*): one page each, a ruled line-item table, totals, and three
@@ -56,6 +57,37 @@ changes into.
To see the incrementality, run a flow twice unchanged (the second run makes no
model call), then edit one input file and run again.
+### The `research` flow: the web as a source
+
+The `research` flow searches the web, reads the pages it finds, follows the
+leads worth following and writes a report with citations (DESIGN.md Β§3,
+*Sources: the web*). Without a search key it searches **Wikipedia** (no key,
+no cost) and reaches the open web through the articles' references; with
+`TAVILY_API_KEY` set it searches with Tavily (a free tier of 1,000 credits a
+month). The engine's identity is part of every record, so switching engines
+re-runs the searches and the pages they find.
+
+The agent fetches pages itself: it identifies itself as `cocoindex-agents`
+with this repository's address, obeys `robots.txt` and `Crawl-delay`, sends
+one request at a time per host, follows no sign-in, posts nothing, and
+reads at most 12 pages from the searches and 6 from the leads. Pages are
+normalized locally (title and main content as Markdown, by trafilatura); a
+PDF is read by the model natively. The normalized pages are kept in the
+flow's state (`.coco_db`) so that a `304 Not Modified` can reuse them;
+delete `.coco_db` to start from scratch. The flow needs `trafilatura`
+installed beside CocoIndex (`uv pip install trafilatura`, or install the
+example with its dependencies).
+
+A rerun reuses every step whose inputs did not change: an unchanged page
+costs one conditional request and no model call; a page that changed only in
+a timestamp, an ad or a comment count costs nothing either, because a
+worker is memoized on the page's normalized content; only a real change
+reaches the model, and only that page's worker and the reducers on its path
+run again. The `--plan` tree lists each source's pages with their digest and
+when the current content was first fetched, and its unavailable pages with
+the reason; citations in the report carry the URL only (DESIGN.md Β§3: no
+time in a tool result).
+
### The `drive` flow: a Google Drive folder of your own
The `drive` flow reads a folder in your Google Drive as you, through the
@@ -186,6 +218,42 @@ prompts that still named workers and planners) measured 15/15/18 calls on a
first run, 0 unchanged and 2/2/3 after one edit; its findings are in the
next section.
+## Measured: the `research` flow against the real web
+
+Measured 2026-11-21 with `openai/gpt-6.1-terra` and the `wikipedia` engine
+(no search key), three to five queries written by the orchestrator from the
+prompt, from an empty `.coco_db`. The orchestrator followed recipe 5: it
+opened the target and a `web_search` source in one turn, fanned out over the
+12 pages the searches found, reduced the leads, opened a `web_pages` source
+over them (five of six leads fetched: the Gradle incremental-build guide,
+the GCC incremental-compiler wiki, an arXiv abstract and two PDFs read
+natively; one PDF link was a 404), fanned out over those, reduced the report
+from both collections and declared it.
+
+| Run | Model calls | `stats:` |
+|---|---|---|
+| fresh | 46 (orchestrator 8, workers 34, reducers 4) | `model calls 46, sessions 20, tool calls 27, spent tokens 193265 in (provider-cached 23209 / 12%), 8068 out, files 1, 63.1s` |
+| unchanged | 0 | `model calls 46 (reused 46 / 100%), sessions 20 (skipped 20 / 100%), tool calls 27 (reused 27 / 100%), files 1 (unchanged 1 / 100%), 1.1s` |
+| one source changed | not yet measured: it needs a page under the user's control (a gist, or a page they name); the scripted drive of the same case is `test_research.py::test_a_research_run_reuses_unchanged_pages_and_reruns_only_a_changed_one` (one worker's answer turn and the two reducers: 3 calls) | |
+
+What the runs show:
+
+- A first drive with the recipe's original wording ("three to five short
+ search queries") read only three pages per round: the orchestrator wrote
+ long strings of keywords, which Wikipedia's search matched to AI articles.
+ The recipe now asks for two-to-four-word, title-like queries, and the next
+ drive read twelve relevant pages. That is the one prompt change the drive
+ caused.
+- The unchanged rerun makes no model call and runs no tool: the root
+ session's one record per web source is validated by searching again (five
+ queries) and sending one conditional request per page (17 pages), and the
+ whole run is skipped in about a second. An earlier unchanged rerun had
+ re-run the orchestrator's body with no inference because a page's ETag had
+ rotated while its content had not; validity now rests on the normalized
+ content, and the record refreshes its validators.
+- Changing a source the flow actually reads needs a page under the user's
+ control; see the note in the row above.
+
## Measured: the `drive` flow against a real account
Not yet measured: the three runs (fresh, unchanged, one file edited in
diff --git a/examples/cocoindex_agents/flows/research/SURVEY.md b/examples/cocoindex_agents/flows/research/SURVEY.md
new file mode 100644
index 00000000..3d6c94b7
--- /dev/null
+++ b/examples/cocoindex_agents/flows/research/SURVEY.md
@@ -0,0 +1,262 @@
+# Survey: searching, fetching and reading the web for a research flow (2026-11-21)
+
+What exists today for an agent that searches the Internet, reads pages and
+writes a report, and what it means for a flow whose reruns must reuse every
+step whose inputs did not change. Three readings, each verified against the
+pages cited on 2026-11-21 (vendor documentation, pricing and terms pages,
+GitHub sources, papers), plus two measurements made from this machine. Items
+no primary source confirmed are marked *unverified*. The design that follows
+from it is `DESIGN-proposal.md`; the raw per-URL measurements are
+`survey/results.md`.
+
+## 1. Hosted fetch-and-extract services
+
+| Service | Key | Free tier | Price | Returns | Normalized? | Origin caching headers? | Notes |
+|---|---|---|---|---|---|---|---|
+| Firecrawl `/v2/scrape` | yes | 1,000 credits/month, no card, 10 req/min | 1 credit/page; $19/5k, $99/100k | Markdown (default), cleaned/raw HTML, links, metadata (title, description, language, status; no date) | yes (`onlyMainContent` default); own cache 2 days (`maxAge`); `changeTracking` diffs against *its* previous scrape | no | `/extract` and the deep-research endpoint are removed 2026-12-10; terms unclear on storing output |
+| Jina Reader `r.jina.ai` | **no** (20 req/min per IP); key: 500 req/min, 10M free tokens | tokens on output (β‰ˆ$0.05/M, *unverified*) | Markdown or JSON (title, description, url, finalUrl, content, metadata, publishedTime when found) | yes; 5-minute cache (`X-No-Cache`); byte-stable on a probe | no (`cache-control: no-transform` only) | `s.jina.ai` search now needs a key (`401` measured); Apache-2.0 self-hostable |
+| Tavily Extract | yes | 1,000 credits/month, no card, 100 req/min | 0.2 credit/URL basic, 0.4 advanced | `raw_content` Markdown or text, beta `published_date`; **no title** | yes; no documented cache | no | ≀20 URLs/request; terms: internal business use |
+| Exa `/contents` | yes | $10/month credit | $1/1k pages per content type | title, url, publishedDate, author, text, highlights, summary; `source: cached\|crawled` | yes; cache-first (`maxAgeHours`, `snapshotAsOf`) | no | terms bar copying/storing output beyond a browser cache |
+| Diffbot Article | yes | 10,000 calls/month, 5/min | 1 credit/page; $299/250k | title, text, normalized HTML, date, author, siteName, language, tags | yes; richest metadata | no | Crawlbot honours robots.txt |
+| ScrapingBee | yes | 1,000 trial credits | 1–75 credits/request | raw HTML (optional Markdown/text) | optional | **yes** (`Spb-` prefixed pass-through) | the only service that forwards origin headers |
+
+Observations: no hosted extractor exposes the origin's `ETag`,
+`Last-Modified` or `Cache-Control`, or a content hash of its own, except
+ScrapingBee's header pass-through; every one of them caches on its side with
+a freshness knob; the storage terms differ widely (Jina claims no rights in
+output; Exa and Firecrawl are broad enough to be unclear; Tavily is internal
+use). Change detection therefore has to be done by the client on normalized
+content, which a local extractor does as well and for free.
+
+## 2. Search APIs
+
+| Service | Key | Free tier | Price | Returns | Notes |
+|---|---|---|---|---|---|
+| Tavily Search | yes | 1,000 credits/month, no card | 1 credit basic, 2 advanced; PAYG $0.008/credit | title, url, snippet, score, optional raw content and published date; ≀20 results | the default engine of GPT Researcher and LangChain's open deep research; terms: internal use, no sharing of API access |
+| Exa Search | yes | $10/month | $4–$15 per 1k | title, url, publishedDate, author, optional contents | 10 QPS |
+| Brave Search | yes (card) | $5 credit/month (β‰ˆ1k queries); the free plan was withdrawn for new sign-ups in February 2026 | $5 per 1k | title, url, description, extra snippets | terms forbid storing or caching results beyond transient use and require "Powered by Brave"; the most restrictive surveyed |
+| Serper | yes | 2,500 queries once | $0.30–$1.00 per 1k | Google organic results | scrapes Google; terms *unverified* |
+| SerpApi | yes | 250/month | from $25 per 1k | organic fields, raw SERP, Markdown | cached searches free for an hour |
+| Jina `s.jina.ai` | yes | 10M tokens/key | β‰₯10,000 tokens/request | 5 results in Reader form | blocked without a key |
+| You.com | yes; a free MCP endpoint with 100 queries/day needs none | $10 (+$90 after verification) | $5 per 1k; live pages $1 per 1k | title, url, snippets or page content | terms *unverified* |
+| Bing Search APIs | β€” | β€” | retired 2025-08-11 | β€” | replaced by Grounding with Bing ($14 per 1k): no raw results, display rules |
+| DuckDuckGo | no | unofficial | free | Instant Answers officially; `html`/`lite` endpoints are what scrapers use | `ddgs` 9.16 scrapes ten engines "for educational purposes only"; a `202` challenge was seen on the HTML endpoint; not for a public example |
+| SearXNG | no | free (self-host) | infrastructure | url, title, content, engines, score | JSON output must be enabled; public instances rate-limit scripted clients |
+| Wikipedia / Wikidata | no (descriptive `User-Agent` required) | 200 req/min | free | search API; REST `page/html` and `page/summary` | **the only keyless source with origin validators**: `ETag W/"<revision>/<tid>"` and a `304` measured on `page/html`; article pages give `Last-Modified` and `304`; CC BY-SA 4.0 (Wikidata CC0), storage allowed |
+| Common Crawl index | no | free | free | CDX rows with a SHA-1 `digest`; WARC/WAT hold origin headers | a lookup by URL in a past crawl, not a search engine |
+
+### What the model providers offer natively
+
+| Tool | Price | What comes back | Content to the developer? |
+|---|---|---|---|
+| OpenAI `web_search` (Responses API; chat completions only via `gpt-5-search-api`; the `-search-preview` models shut down 2026-07-23) | $10 per 1k calls + search content tokens ($25 per 1k for the preview tool on non-reasoning models) | `url_citation` annotations (url, title, offsets); all URLs consulted on request | no |
+| Anthropic `web_search` | $10 per 1k searches + tokens | results with url, title, page_age, `encrypted_content`; citations with up to 150 characters of `cited_text` | no (opaque) |
+| Anthropic `web_fetch` | tokens only (β‰ˆ2,500 per 10 kB page) | full plain text or PDF, title, **`retrieved_at`** | yes; honours robots.txt; only URLs already in the context; server-side cache (`use_cache`) |
+| Gemini Google Search grounding | 5,000 free requests/month on Gemini 3+, then $14 per 1k | queries, `url_citation`, search suggestions that must be displayed | no; terms forbid training on grounded results and limit storage |
+| Gemini `url_context` | tokens | retrieval status per URL; 20 URLs/request, 34 MB each | no |
+
+LiteLLM 1.110.2 exposes `web_search_options` (`search_context_size`,
+`user_location`) on chat completions for openai, xai, vertex_ai, anthropic,
+gemini and perplexity, and the `web_search_preview` tool on its Responses
+API; Anthropic's `web_fetch` is not documented in LiteLLM, and citation
+formats are not normalized across providers. A model-native search is a
+prose answer with citations, priced per call on top of tokens, and tied to
+the model's provider; it is not a ranked result list a validator can repeat.
+
+## 3. Local extraction libraries
+
+| Library | Task | Deterministic? | Boilerplate quality (F1) | Footprint | License | Last release |
+|---|---|---|---|---|---|---|
+| trafilatura 2.3.1 | main content + metadata, txt/Markdown/XML/JSON | yes with `include_comments=False`, no dedup, no metadata (dedup uses a process-wide LRU; metadata calls htmldate with today's date) | own eval 0.926; Scrapinghub 0.958; Bevendorff 2023 0.883 (best mean); Sandia 2024 0.937 | lxml + six pure-Python deps | Apache-2.0 | 2026-10-06 |
+| readability-lxml 0.9 | main content as an HTML fragment | yes | own-eval 0.853; Scrapinghub 0.922; Bevendorff median 0.970 (best median); multilingual 0.838 (best) | lxml, chardet, cssselect | Apache-2.0 | 2026-08-27 |
+| Mozilla Readability.js 0.6 | the reference algorithm | yes, but needs Node | Scrapinghub 0.947 | Node + jsdom | Apache-2.0 | 2025-03 |
+| Resiliparse 2.0.1 | fast text, simple main-content filter | yes | 0.811 at 0.3Γ— trafilatura's time; Bevendorff 0.859 | 1.75 MB wheel (Rust) | Apache-2.0 | 2026-11-04 |
+| jusText 3.0.2 | paragraph classifier | yes (needs a language) | 0.862; it is trafilatura's fallback | lxml | BSD-2 | 2025-02 |
+| boilerpy3 1.0.7 | Boilerpipe port | yes | 0.807 | none | Apache-2.0 | 2023-11 (stale) |
+| newspaper4k 0.9.6 | news articles | date scoring reads the clock | 0.803, 6.8Γ— slower | 11 deps | MIT | 2026-11-01 |
+| goose3 3.1.22 | articles | langdetect seed risk | 0.810 | 8 deps | Apache-2.0 | 2026-07 |
+| markdownify 1.2.4 / html2text 2025.4 / inscriptis 2.7.7 | HTML β†’ Markdown or text, no boilerplate removal | yes | β€” (0.66–0.69) | bs4 / none / lxml | MIT / **GPL-3.0** / Apache-2.0 | 2026-11 / 2025-04 / 2026-11 |
+| crawl4ai 0.9.6 | Playwright crawler + Markdown + pruning/BM25/LLM filters | rendering no; filters yes | unbenchmarked | β‰ˆ35 deps + Chromium, hundreds of MB | Apache-2.0 + attribution | 2026-11-20 |
+| Playwright 1.65 | JavaScript rendering | no (live DOM) | β€” | 53 MB wheel + β‰ˆ281 MB Chromium (β‰ˆ78 MiB headless shell); β‰ˆ0.7 GB RAM | Apache-2.0 | 2026-11-14 |
+| htmldate 1.11 | publication date | only with `max_date` pinned | date F 0.926/0.949 | lxml, dateparser | Apache-2.0 | 2026-10 |
+| pypdf 7.1 / pdfminer.six / pdfplumber | PDF text | yes | β€” | pure Python / MIT deps | BSD-3 / MIT / MIT | 2026-11 |
+| PyMuPDF 2.1 | PDF text, fastest | yes | β€” | 69 MB wheel | **AGPL-3.0** or commercial | 2026-11 |
+| docling 2.151 | PDF/Office β†’ Markdown with layout models | not guaranteed (ML) | β€” | torch + β‰ˆ530 MB models, 2.4–6.2 GB RAM | MIT | 2026-11 |
+| ReaderLM-v2 / MinerU-HTML | model-based extraction | no (generative, GPU) | WCXB 0.741 / 0.827 at 10 s / 1.6 s per page on an A100 | 1.5B / 0.6B models | CC-BY-NC / Apache-2.0 | 2025-03 / 2026-11 |
+
+What the benchmarks say, read across trafilatura's own evaluation
+(2026-10, 990 pages), Scrapinghub's article benchmark (181 pages, archived
+2026-06), Bevendorff et al. SIGIR 2023 (3,985 pages, 14 extractors), Sandia
+2024, a SIGIR 2025 multilingual study and WCXB 2026 (2,008 pages, seven page
+types): on article-like pages trafilatura and readability tie at the top
+(differences ≀0.03 F1, not significant in Sandia's test), readability is
+more stable on non-English pages, Resiliparse is within 0.02–0.03 at three
+times the speed, model-based extractors win only on forums and listings at
+a GPU second per page, and nothing heuristic exceeds about 0.80 on forums,
+listings and product pages. Every benchmark was built from HTML fetched with
+JavaScript off: article pages generally do not need rendering.
+
+## 4. How current deep-research systems work
+
+| System | Planning | Following leads | Citations | Cost bounds | Published cost or length |
+|---|---|---|---|---|---|
+| OpenAI Deep Research (ChatGPT; the API models `o3-deep-research`/`o4-mini-deep-research` shut down 2026-07-23) | learned end to end; the UI clarifies and lets the plan be edited | internal; since 2026-02 the user can interrupt and restrict sites | `url_citation` spans (url, title, offsets); a "sources used" list | 5–30 minutes; historically $10/$40 per M tokens plus $10 per 1k searches | β€” |
+| Perplexity Deep Research / Agent API (Sonar chat completions ended 2026-09-27) | effort levels bundle model, step budget and tools; `ultra` runs three agents and merges | step budgets 1/5/15/40/300 with reminders; a 10k-token fetch budget; a small model extracts "only the relevant passages, quoted exactly" (5,561 β†’ 293 tokens) | `[n]`/`[web:n]` markers over `search_results` with stable ids | steps, tokens per search, compaction at 150k | 2–4 minutes; `ultra` $21.71 per task on WANDR |
+| Gemini Deep Research (app and the Interactions API agent) | returns a plan for approval (`collaborative_planning`) | gap-driven loop; 60-minute hard cap, β‰ˆ20 typical | a `citations` field (format undocumented) | time cap; list-rate tokens | β‰ˆ80 searches, 250k input and 60k output tokens, **$1–3 per task**; Max β‰ˆ160 searches, 900k in, $3–7 |
+| Anthropic Research + `web_search`/`web_fetch` | a lead agent decomposes and saves the plan to memory; 1 / 2–4 / 10+ subagents by complexity | subagents reflect after every result; source-quality heuristics; `max_uses` | always-on citations with ≀150 characters of quoted text; a CitationAgent attaches citations after drafting; `web_fetch` returns `retrieved_at` | `max_uses`, `max_content_tokens`, 45-minute cap | 5–15 minutes; agents use β‰ˆ4Γ— the tokens of chat, multi-agent β‰ˆ15Γ—; token volume explained 80% of quality variance |
+| GPT Researcher | one search, then 3 sub-queries (`MAX_ITERATIONS`); deep mode a breadth Γ— depth tree | static fan-out, 5 results per query, a visited-URL set, an embedding filter at 0.42 | `([cite](url))` inline plus an APA list, prompt-enforced | 3 iterations, 1,200 words, 25k-word context | β‰ˆ3 minutes; deep mode β‰ˆ$0.40 and β‰ˆ5 minutes |
+| STORM / Co-STORM | perspectives from related articles' tables of contents, simulated expert conversations, outline first | fixed 3Γ—3Γ—3Γ—3 budget; Co-STORM's moderator asks about retrieved-but-unused material | inline `[n]` into one reference table; citation precision and recall β‰ˆ85% | the structural knobs | the one open-source system with resumable stage artifacts (`do_research=False`), for the same topic only |
+| LangChain open_deep_research | clarify β†’ research brief β†’ a supervisor splits by sub-topic | `think_tool` reflection; stop after 5 calls, 3 sources or 2 similar searches; 6 supervisor rounds; URLs deduplicated across queries; pages cut at 50k characters and summarized | `[n]` plus a `### Sources` list; "preserve sources verbatim" through compression | iterations Γ— units Γ— calls | β‰ˆ$0.46–1.87 per report on Deep Research Bench |
+| Hugging Face open-deep-research (smolagents) | a code-agent manager and a browser agent, replanning every 4 steps | ReAct within 12/20 steps | none | step caps | GAIA 55% |
+| dzhng/deep-research | breadth 4, depth 2; 3 queries β†’ 3 learnings β†’ 3 follow-ups, breadth halving per level | follow-up questions only | a `## Sources` list of visited URLs, no inline citations | breadth, depth, 5 results, 25k characters per page | β€” |
+| Jina node-DeepResearch | no upfront plan; a FIFO queue of gap questions | query deduplication by embeddings, URL ranking with a reranker, two URLs per host, a 1M-token budget with "beast mode" at the end | GFM footnotes with url, title, **exact quote and dateTime** (page date or `Last-Modified`), ≀10 references | the token budget | "hundreds" of queries |
+| Firecrawl deep research (removed 2026-12-10) / `/v2/agent` | key research areas, then iterative search | `maxDepth` 7, `timeLimit` 270 s, `maxUrls` 20 | a `sources` list | credits per URL; `maxCredits` 2,500 on the agent | "a few hundred credits" per agent run |
+| Tavily `/research` | Planning β†’ WebSearch β†’ ResearchSubtopic (pro) β†’ Generating | opaque | numbered, MLA, APA or Chicago plus `sources` | credit floors and ceilings | mini 4–110 credits, pro 15–250 (β‰ˆ$0.03–2.00) |
+
+Patterns. Every system is plan β†’ search β†’ read β†’ reflect β†’ repeat β†’ write;
+the commercial ones push the loop into a trained model and expose only an
+envelope (steps, tokens, minutes); the open-source ones split into static
+fan-outs (GPT Researcher, STORM, dzhng), supervisor-plus-reflection
+(LangChain, Anthropic's published design) and one budget-forced loop (Jina,
+smolagents). What made outputs stable: a fixed fan-out, one final writing
+pass over compressed findings (LangChain dropped parallel section writing
+because it "produced disjoint reports"), and a dedicated citation pass or a
+strict carry-through rule. What made them unstable: recursion per result,
+contradictory citation prompts, relevance thresholds that differ between
+config and code, and search-engine nondeterminism, which nobody controls.
+Only Anthropic's `web_fetch` records a fetch time; only Jina and Anthropic
+keep an exact quote; only Perplexity's Agent API uses stable result ids. The
+2026 trend is page-level extraction before reading, to control the dominant
+cost, and "run several researchers and merge" at $4–20 a task.
+
+**None of them reruns incrementally.** No system reuses a previous run's
+sources, findings or report when the question is repeated or a source
+changed; the nearest things are STORM's resumable stage files (same topic
+only), the server-side page caches of Anthropic's `web_fetch`, OpenAI's
+cache-only mode and Exa's index (invisible, unaddressable), and job stores
+that re-serve a finished report. Every run pays the full search, fetch and
+token bill again. That gap is the point of the flow proposed here.
+
+## 5. Measured on this machine
+
+### Conditional requests and byte stability (51 URLs, two fetches ten minutes apart)
+
+The table is `survey/results.md`, produced by `survey/measure.py` over
+`survey/urls.txt`. In short: 45 of 51 fetched; 33 send a validator, 31
+answer `304` to it at once and 22 still do ten minutes later with the stored
+validators (the GitHub, Hugging Face, Tavily and Exa pages rotate their ETag
+per response; four home pages had new content); 20 of 42 HTML pages differed
+byte-for-byte although their content had not changed (median line similarity
+0.993), and after trafilatura all 41 extractable pages, including every one
+of those 19, were identical; readability + markdownify likewise 42 of 42;
+every PDF was byte-identical and carried validators; `robots.txt` allowed
+the agent on 46 of 51 URLs; Medium, Reuters, AP, the New York Times and
+Stack Overflow refused the fetch outright. trafilatura's output was
+identical on repeated extraction of the same HTML, and with `include_links`
+the Markdown carries 20–120 absolute links per page, which is what a lead
+needs.
+
+### Keyless endpoints, probed once each
+
+| Endpoint | Result |
+|---|---|
+| `s.jina.ai` search | `401 AuthenticationRequiredError` |
+| `r.jina.ai` reader | `200`, Markdown with title, URL and published time; `x-ratelimit-limit: 20` per minute; `cache-control: no-transform`; no origin validators |
+| `html.duckduckgo.com/html/?q=` | `200` with ten parseable results from one host; the agent survey saw a `202` challenge on another attempt |
+| `lite.duckduckgo.com/lite/?q=` | `202` (a challenge page) |
+| Wikipedia search API (`list=search`) | `200`, five results with titles, snippets and sizes |
+| Wikipedia REST `page/html/<title>` | `200`, `etag: W/"<revision>/<tid>/view"`, `last-modified`; `304` on `If-None-Match` |
+| Brave Search API without a token | `422`, token required |
+| Tavily without a key | `401` |
+
+## 6. What this decides for the design
+
+1. Reuse rests on conditional requests where the origin honours them and on
+ a digest of *normalized* content everywhere: raw bytes change under an
+ unchanged page about half the time; normalized text did not change once.
+2. Local extraction with trafilatura is the normalizer: deterministic, top
+ of every benchmark on articles, Apache-2.0, no key, no cost, and it gives
+ the links a lead needs; readability is the fallback of equal quality.
+3. Search is behind one protocol: Wikipedia without a key (the only keyless
+ engine that is official and storable, and whose pages carry validators),
+ Tavily with one (free tier, no card, the engine the open-source research
+ agents use). Brave's terms and the loss of its free plan, Jina's new key
+ requirement, and DuckDuckGo's unofficial endpoints rule them out.
+4. Citations carry URL, fetch time and a short quote, as Jina's references
+ and Anthropic's `web_fetch` do; the systems that keep citations through
+ synthesis do it by carrying them verbatim through every compression step.
+5. Costs: a first run of the proposed flow is of the order of Gemini Deep
+ Research's published envelope (tens of searches, β‰ˆ250k input tokens); a
+ rerun with unchanged sources is zero model calls, which no surveyed system
+ offers.
+
+## Sources
+
+Hosted services and search APIs (read 2026-11-21): firecrawl.dev/pricing;
+docs.firecrawl.dev (scrape, search, crawl, extract, alpha/deep-research);
+firecrawl.dev/terms-of-service; jina.ai/reader, jina.ai/api-dashboard/rate-limit,
+jina.ai/legal, github.com/jina-ai/reader; docs.tavily.com (extract, search,
+api-credits, rate-limits, search-crawler), tavily.com/terms; docs.exa.ai
+(get-contents, search, rate-limits), exa.ai/pricing, crawler.exa.ai, Exa's
+terms PDF; diffbot.com/pricing and docs; scrapingbee.com/pricing and
+documentation; brave.com/search/api, api-dashboard.search.brave.com
+(documentation, terms of service), implicator.ai and alternativeto.net on the
+February 2026 plan change, brave.com/blog/most-powerful-search-api-for-ai;
+serper.dev; serpapi.com/pricing, /legal, /search-api; you.com/docs (billing,
+rate-limits, retrieve-page-content), you.com/plans;
+learn.microsoft.com (bing-search-api-retirement, foundry web-search tool),
+microsoft.com/bing/apis; pypi.org/project/ddgs and /duckduckgo-search,
+github.com/deedy5/ddgs, duckduckgo.com/terms; docs.searxng.org (search_api,
+limiter), searx.space; mediawiki.org (Wikimedia_APIs/Rate_limits,
+API:Etiquette, Wikimedia_APIs/Conditional_requests), foundation.wikimedia.org
+User-Agent policy, en.wikipedia.org/api/rest_v1 spec,
+wikidata.org/wiki/Wikidata:Data_access; commoncrawl.org/get-started and
+/terms-of-use, index.commoncrawl.org; developers.openai.com/api/docs
+(guides/tools-web-search, pricing, deprecations);
+platform.claude.com/docs (web-search-tool, web-fetch-tool, pricing);
+aistudio.google.com/docs (google-search, url-context, pricing, terms,
+deep-research); docs.litellm.ai (completion/web_search, providers/anthropic,
+providers/gemini, response_api), github.com/BerriAI/litellm/releases.
+
+Extraction libraries: pypi.org and GitHub pages of trafilatura,
+readability-lxml, mozilla/readability, ReadabiliPy, newspaper4k, goose3,
+boilerpy3, jusText, inscriptis, Resiliparse, html2text, markdownify,
+crawl4ai, playwright, htmldate, docling, pypdf, pdfminer.six, pdfplumber,
+PyMuPDF, markitdown, defuddle, dom-to-semantic-markdown, ReaderLM-v2,
+mineru-html, magic-html; trafilatura.readthedocs.io (evaluation,
+usage-python, settings) and its `core.py`, `deduplication.py`, `metadata.py`,
+`settings.py`; readability's `readability.py`; Readability.js source;
+htmldate's `settings.py` and `validators.py`; playwright.dev/python/docs/browsers;
+datawookie.dev (2025-06-06) on Playwright memory; almanac.httparchive.org 2024
+JavaScript chapter. Benchmarks: github.com/scrapinghub/article-extraction-benchmark;
+Bevendorff et al., SIGIR 2023 (downloads.webis.de/publications/papers/bevendorff_2023c.pdf);
+Sandia SAND2024-10208 (osti.gov/servlets/purl/2429881); Fundus
+(arxiv.org/html/2403.15279v1); Bournonville et al., SIGIR 2025
+(dias.users.greyc.fr/publications/sigir2025.pdf); WCXB (arxiv.org/html/2605.21097v1);
+MainWebBench/AICC (arxiv.org/html/2511.16397v1); Dripper (arxiv.org/html/2511.23119v1).
+
+Deep-research systems: openai.com/index/introducing-deep-research,
+openai.com/index/deep-research-system-card, OpenAI's model, deprecation and
+pricing pages, the deep-research cookbook, help.openai.com deep-research FAQ,
+the-decoder.com (2026-02) on the GPT-5.2 update; perplexity.ai/hub/blog
+(introducing-perplexity-deep-research, improvements-to-every-agent-api-effort-level),
+docs.perplexity.ai (sonar-deep-research, agent-api/effort, tools/web-search,
+models, pricing, changelog), openrouter.ai/perplexity/sonar-deep-research;
+blog.google (2024-12-11, 2025-12-11, 2026-04-21), aistudio.google.com/docs/deep-research,
+discuss.ai.google.dev thread 112804; claude.com/blog/research,
+claude.com/blog/integrations, anthropic.com/engineering/multi-agent-research-system;
+x.ai/news/grok-3, the-decoder.com (2025-03-22); gpt-researcher's README,
+`config/variables/default.py`, `skills/researcher.py`, `skills/deep_research.py`,
+`context/compression.py`, `prompts.py`, docs.gptr.dev (config, deep_research,
+building-gpt-researcher); arxiv.org/abs/2402.14207 and /2408.15232,
+stanford-oval/storm README and `storm_wiki/engine.py`, `collaborative_storm/engine.py`;
+langchain.com/blog/open-deep-research, open_deep_research README,
+`configuration.py`, `prompts.py`, `utils.py`; huggingface.co/blog/open-deep-research,
+smolagents `examples/open_deep_research`; dzhng/deep-research README and
+`src/deep-research.ts`; jina-ai/node-DeepResearch README, `src/agent.ts`,
+`src/utils/schemas.ts`, jina.ai/news/a-practical-guide-to-implementing-deepsearch-deepresearch;
+docs.firecrawl.dev/features/agent and alpha/deep-research,
+firecrawl.dev/blog/deep-research-api; docs.tavily.com research endpoint,
+research-streaming tutorial, api-credits; Alibaba-NLP/DeepResearch README and
+arxiv.org/abs/2510.24701; MiroMindAI/MiroThinker README;
+moonshotai.github.io/Kimi-Researcher; arxiv.org/abs/2506.11763 (DeepResearch Bench).
diff --git a/examples/cocoindex_agents/flows/research/prompt.md b/examples/cocoindex_agents/flows/research/prompt.md
new file mode 100644
index 00000000..246722e2
--- /dev/null
+++ b/examples/cocoindex_agents/flows/research/prompt.md
@@ -0,0 +1,6 @@
+Research what incremental computation is and where it is used in build
+systems and databases. Search the web, read what you find, follow the leads
+worth following, and write ./out/report.md: an overview, the main approaches
+with their trade-offs, and notable systems, each claim with its source. End
+with a Sources section listing every page used, with its URL. Answer with a
+one-line status.
diff --git a/examples/cocoindex_agents/flows/research/survey/measure.py b/examples/cocoindex_agents/flows/research/survey/measure.py
new file mode 100644
index 00000000..e087a770
--- /dev/null
+++ b/examples/cocoindex_agents/flows/research/survey/measure.py
@@ -0,0 +1,224 @@
+# mypy: ignore-errors
+# A one-off measurement script (flows/research/SURVEY.md), not part of the package.
+"""Measure how the pages a research flow hits behave under HTTP caching.
+
+Pass 1: GET each URL (recording ETag, Last-Modified, Cache-Control, Age, Vary,
+Content-Type), save the body, then re-request with If-None-Match and with
+If-Modified-Since to see whether the origin answers 304. Pass 2, DELAY seconds
+later: GET again; compare the raw bytes (identical? line similarity) and the
+text after deterministic extraction (trafilatura; readability+markdownify), and
+redo the conditional requests with pass 1's validators, as a rerun would.
+Also checks robots.txt for each URL.
+"""
+
+import difflib
+import hashlib
+import json
+import re
+import sys
+import time
+import urllib.robotparser
+from pathlib import Path
+import httpx
+import trafilatura
+from readability import Document as RDoc
+from markdownify import markdownify
+
+DATA = Path(sys.argv[1])
+DATA.mkdir(parents=True, exist_ok=True)
+DELAY = int(sys.argv[2]) if len(sys.argv) > 2 else 600
+UA = "cocoindex-agents-survey/0.1 (+https://github.com/cocoindex-io/cocoindex)"
+URLS = [
+ line.strip()
+ for line in (Path(__file__).with_name("urls.txt")).read_text().splitlines()
+ if line.strip() and not line.startswith("#")
+]
+
+client = httpx.Client(
+ follow_redirects=True,
+ timeout=30,
+ headers={"User-Agent": UA, "Accept": "text/html,application/pdf,*/*;q=0.8"},
+)
+robots: dict[str, object] = {}
+
+
+def allowed(url: str):
+ host = re.match(r"https?://[^/]+", url).group(0)
+ if host not in robots:
+ rp = urllib.robotparser.RobotFileParser(host + "/robots.txt")
+ try:
+ r = client.get(host + "/robots.txt")
+ if r.status_code == 200:
+ rp.parse(r.text.splitlines())
+ robots[host] = rp
+ else:
+ robots[host] = r.status_code
+ except Exception as e:
+ robots[host] = f"error {type(e).__name__}"
+ rp = robots[host]
+ if isinstance(rp, urllib.robotparser.RobotFileParser):
+ return {
+ "robots": "present",
+ "allowed": rp.can_fetch(UA, url),
+ "allowed_star": rp.can_fetch("*", url),
+ "crawl_delay": rp.crawl_delay("*"),
+ }
+ return {"robots": str(rp), "allowed": None}
+
+
+def hdrs(r):
+ h = r.headers
+ return {
+ k: h.get(k)
+ for k in (
+ "etag",
+ "last-modified",
+ "cache-control",
+ "age",
+ "vary",
+ "content-type",
+ "expires",
+ "x-cache",
+ "cf-cache-status",
+ )
+ }
+
+
+def get(url, extra=None):
+ t = time.time()
+ try:
+ r = client.get(url, headers=extra or {})
+ return {
+ "status": r.status_code,
+ "headers": hdrs(r),
+ "final_url": str(r.url),
+ "body": r.content,
+ "secs": round(time.time() - t, 2),
+ }
+ except Exception as e:
+ return {
+ "status": None,
+ "error": f"{type(e).__name__}: {e}",
+ "secs": round(time.time() - t, 2),
+ }
+
+
+def extract(body: bytes, ctype: str):
+ if "pdf" in (ctype or ""):
+ return {"trafilatura": None, "readability": None}
+ html = body.decode("utf-8", "replace")
+ try:
+ t = trafilatura.extract(
+ html,
+ include_comments=False,
+ include_tables=True,
+ output_format="markdown",
+ favor_precision=True,
+ )
+ except Exception as e:
+ t = f"ERR {type(e).__name__}"
+ try:
+ rd = markdownify(RDoc(html).summary(), heading_style="ATX")
+ except Exception as e:
+ rd = f"ERR {type(e).__name__}"
+ return {"trafilatura": t, "readability": rd}
+
+
+def sim(a: bytes, b: bytes):
+ if a == b:
+ return 1.0
+ la, lb = (
+ a.decode("utf-8", "replace").splitlines(),
+ b.decode("utf-8", "replace").splitlines(),
+ )
+ if len(la) > 20000 or len(lb) > 20000: # huge: byte-level quick ratio
+ return round(
+ difflib.SequenceMatcher(None, a[:400000], b[:400000]).quick_ratio(), 4
+ )
+ return round(difflib.SequenceMatcher(None, la, lb).ratio(), 4)
+
+
+def cond(url, h):
+ out = {}
+ if h.get("etag"):
+ r = get(url, {"If-None-Match": h["etag"]})
+ out["if_none_match"] = r["status"]
+ if h.get("last-modified"):
+ r = get(url, {"If-Modified-Since": h["last-modified"]})
+ out["if_modified_since"] = r["status"]
+ return out
+
+
+def sha(b):
+ return hashlib.sha256(b).hexdigest()[:16]
+
+
+results = {}
+print(f"pass 1 over {len(URLS)} urls", file=sys.stderr)
+for i, url in enumerate(URLS):
+ rec = {"url": url, "robots": allowed(url)}
+ r1 = get(url)
+ rec["pass1"] = {k: v for k, v in r1.items() if k != "body"}
+ if r1.get("body") is not None:
+ (DATA / f"{i:02d}.p1").write_bytes(r1["body"])
+ rec["pass1"]["bytes"] = len(r1["body"])
+ rec["pass1"]["sha"] = sha(r1["body"])
+ rec["pass1"]["conditional"] = cond(url, r1["headers"])
+ ex = extract(r1["body"], r1["headers"].get("content-type"))
+ rec["pass1"]["extract"] = {
+ k: (len(v) if isinstance(v, str) else None) for k, v in ex.items()
+ }
+ (DATA / f"{i:02d}.p1.json").write_text(json.dumps(ex))
+ results[url] = rec
+ print(
+ f" {i:02d} {r1.get('status')} {rec['pass1'].get('bytes')}B etag={bool(r1.get('headers', {}).get('etag'))} lm={bool(r1.get('headers', {}).get('last-modified'))} cc={r1.get('headers', {}).get('cache-control')!r} {url}",
+ file=sys.stderr,
+ )
+ time.sleep(0.5)
+(DATA / "pass1.json").write_text(json.dumps(results, indent=1, default=str))
+
+print(f"sleeping {DELAY}s", file=sys.stderr)
+time.sleep(DELAY)
+
+print("pass 2", file=sys.stderr)
+for i, url in enumerate(URLS):
+ rec = results[url]
+ r2 = get(url)
+ rec["pass2"] = {k: v for k, v in r2.items() if k != "body"}
+ p1 = DATA / f"{i:02d}.p1"
+ if r2.get("body") is not None and p1.exists():
+ b1 = p1.read_bytes()
+ b2 = r2["body"]
+ (DATA / f"{i:02d}.p2").write_bytes(b2)
+ rec["pass2"]["bytes"] = len(b2)
+ rec["pass2"]["sha"] = sha(b2)
+ rec["pass2"]["raw_identical"] = b1 == b2
+ rec["pass2"]["raw_similarity"] = sim(b1, b2)
+ ex1 = json.loads((DATA / f"{i:02d}.p1.json").read_text())
+ ex2 = extract(b2, r2["headers"].get("content-type"))
+ rec["pass2"]["extract_identical"] = {
+ k: (ex1.get(k) == ex2.get(k)) if ex1.get(k) is not None else None
+ for k in ex2
+ }
+ rec["pass2"]["extract_similarity"] = {
+ k: (
+ sim(ex1[k].encode(), ex2[k].encode())
+ if isinstance(ex1.get(k), str) and isinstance(ex2.get(k), str)
+ else None
+ )
+ for k in ex2
+ }
+ rec["pass2"]["validators_unchanged"] = {
+ k: rec["pass1"]["headers"].get(k) == r2["headers"].get(k)
+ for k in ("etag", "last-modified")
+ }
+ rec["pass2"]["conditional_with_pass1_validators"] = cond(
+ url, rec["pass1"]["headers"]
+ )
+ print(
+ f" {i:02d} {r2.get('status')} ident={rec['pass2'].get('raw_identical')} sim={rec['pass2'].get('raw_similarity')} ext={rec['pass2'].get('extract_identical')} cond={rec['pass2'].get('conditional_with_pass1_validators')} {url}",
+ file=sys.stderr,
+ )
+ time.sleep(0.5)
+(DATA / "results.json").write_text(json.dumps(results, indent=1, default=str))
+print("done", file=sys.stderr)
diff --git a/examples/cocoindex_agents/flows/research/survey/results.md b/examples/cocoindex_agents/flows/research/survey/results.md
new file mode 100644
index 00000000..37baf156
--- /dev/null
+++ b/examples/cocoindex_agents/flows/research/survey/results.md
@@ -0,0 +1,76 @@
+# Measured: 51 pages, two fetches ten minutes apart (2026-11-21)
+
+Produced by `measure.py` over `urls.txt` from a Linux host with `User-Agent: cocoindex-agents-survey/0.1 (+https://github.com/cocoindex-io/cocoindex)`. Raw data: `/tmp/research-survey/data/results.json` on the machine that ran it (not checked in: it holds page bodies' digests and headers only, 60 KB).
+
+| Measure | Result |
+|---|---|
+| URLs tried | 51 (docs 11, blogs 11, news 9, Wikipedia 4, GitHub 5, PDFs 4, papers and vendor pages 7) |
+| Fetched (200) in both passes | 45 of 51; refused outright (401/403): 5 (Medium, Reuters, AP, NYT, Stack Overflow); 1 multiple-choice (300) |
+| `robots.txt` allows our agent | 46 of 51 (3 hosts had no robots file; 2 disallow) |
+| Send `ETag` | 24 of 45 |
+| Send `Last-Modified` | 16 of 45 |
+| Send either validator | 33 of 45 |
+| Answer 304 to a conditional request right away | 31 of 33 pages (21 of 24 to `If-None-Match`; every `Last-Modified` to `If-Modified-Since`) |
+| Answer 304 ten minutes later with the stored validators (a rerun) | 22 of 33; the other 11 send a validator that no longer matches: four GitHub repository pages, Hugging Face, Tavily and Exa rotate their ETag per response, and four home pages (BBC, the Guardian, Simon Willison, Joel on Software) had new content |
+| `Cache-Control` | 35 of 45 send one; `max-age=0`/`must-revalidate`/`no-cache`/`no-store`/`private` on 25; a positive `max-age` on 12 (60 s to a day) |
+| Raw bytes identical between the two fetches | 25 of 45 (HTML 22 of 42; every PDF) |
+| Raw similarity of the HTML pages that differed (difflib on lines) | median 0.993, minimum 0.667 (Hacker News front page) |
+| Normalized text identical (trafilatura, Markdown, no comments) | 41 of 41 HTML pages, including all 19 of the 19 whose bytes differed |
+| Normalized text identical (readability-lxml + markdownify) | 42 of 42 |
+| Extracted size, trafilatura | median β‰ˆ 8k characters on articles, docs and Wikipedia; news front pages under 1k; GitHub repository pages 3–15k |
+
+## Per URL
+
+| URL | Status | ETag | Last-Modified | 304 now | 304 after 10 min | Cache-Control | Raw same | Raw sim. | trafilatura same | readability same |
+|---|---|---|---|---|---|---|---|---|---|---|
+| docs.python.org/3/library/asyncio.html | 200 | yes | yes | yes | yes | `β€”` | yes | 1.0 | yes | yes |
+| developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag | 200 | yes | yes | yes | yes | `public, max-age=3600` | yes | 1.0 | yes | yes |
+| docs.astral.sh/uv/ | 200 | no | no | β€” | β€” | `public, max-age=0, must-revalidate` | no | 0.9997 | yes | yes |
+| www.postgresql.org/docs/current/mvcc-intro.html | 200 | no | no | β€” | β€” | `β€”` | yes | 1.0 | yes | yes |
+| kubernetes.io/docs/concepts/overview/ | 200 | yes | no | yes | yes | `public,max-age=0,must-revalidate` | yes | 1.0 | yes | yes |
+| react.dev/learn | 200 | yes | no | yes | yes | `public, max-age=0, must-revalidate` | yes | 1.0 | yes | yes |
+| docs.rs/tokio/latest/tokio/ | 200 | yes | no | yes | yes | `max-age=0` | yes | 1.0 | yes | yes |
+| docs.anthropic.com/en/docs/agents-and-tools/tool-use/web-search-tool | 200 | no | no | β€” | β€” | `private, no-cache, no-store, max-age=0, must-revalidate` | no | 0.9892 | yes | yes |
+| platform.openai.com/docs/guides/tools-web-search | 200 | yes | yes | yes | yes | `public, max-age=0, must-revalidate` | yes | 1.0 | yes | yes |
+| www.rfc-editor.org/rfc/rfc9111.html | 200 | yes | no | yes | yes | `β€”` | yes | 1.0 | yes | yes |
+| docs.github.com/en/rest | 200 | no | no | β€” | β€” | `public, max-age=60` | yes | 1.0 | yes | yes |
+| simonwillison.net/ | 200 | no | yes | yes | no | `s-maxage=200` | no | 0.9995 | yes | yes |
+| www.joelonsoftware.com/2000/08/09/the-joel-test-12-steps-to-better-code/ | 200 | no | yes | yes | no | `max-age=58, must-revalidate` | no | 0.9908 | yes | yes |
+| martinfowler.com/articles/microservices.html | 200 | yes | yes | yes | yes | `β€”` | yes | 1.0 | yes | yes |
+| blog.cloudflare.com/ | 200 | no | no | β€” | β€” | `β€”` | no | 0.9459 | yes | yes |
+| engineering.fb.com/ | 200 | no | no | β€” | β€” | `max-age=300, must-revalidate` | yes | 1.0 | yes | yes |
+| cocoindex.io/blogs/ | 200 | no | yes | yes | yes | `max-age=600` | no | 0.9375 | yes | yes |
+| huggingface.co/blog | 200 | yes | no | no | no | `β€”` | no | 0.9814 | yes | yes |
+| openai.com/index/introducing-deep-research/ | 200 | no | no | β€” | β€” | `public, max-age=0, must-revalidate` | no | 0.9989 | yes | yes |
+| www.lesswrong.com/ | 200 | no | no | β€” | β€” | `public, max-age=0, must-revalidate` | no | 0.907 | yes | yes |
+| medium.com/@trafilatura | 403 | no | no | β€” | β€” | `β€”` | no | 0.0 | β€” | yes |
+| trafilatura.readthedocs.io/en/latest/evaluation.html | 200 | yes | yes | yes | yes | `max-age=1800, stale-if-error=86400, public` | yes | 1.0 | yes | yes |
+| www.bbc.com/news | 200 | yes | no | no | no | `private, stale-if-error=90, stale-while-revalidate=30, max-age=0, must-revalidate` | no | 0.9984 | yes | yes |
+| www.reuters.com/technology/ | 401 | no | no | β€” | β€” | `max-age=0, private, no-cache, no-store, must-revalidate` | no | 0.0 | yes | yes |
+| techcrunch.com/ | 200 | no | no | β€” | β€” | `max-age=300, must-revalidate` | yes | 1.0 | yes | yes |
+| www.theverge.com/ | 200 | yes | no | yes | yes | `no-store,private` | yes | 1.0 | yes | yes |
+| arstechnica.com/ | 200 | no | no | β€” | β€” | `β€”` | no | 0.9931 | yes | yes |
+| news.ycombinator.com/ | 200 | no | no | β€” | β€” | `private; max-age=0` | no | 0.6667 | β€” | yes |
+| apnews.com/ | 403 | no | no | β€” | β€” | `β€”` | no | 0.0 | β€” | yes |
+| www.theguardian.com/technology | 200 | yes | no | yes | no | `max-age=60, stale-while-revalidate=6, stale-if-error=864000, private` | no | 0.9978 | yes | yes |
+| www.nytimes.com/section/technology | 403 | no | no | β€” | β€” | `max-age=0, private, no-cache, no-store, must-revalidate` | no | 0.0 | yes | yes |
+| en.wikipedia.org/wiki/HTTP_ETag | 200 | no | yes | yes | yes | `private, s-maxage=0, max-age=0, must-revalidate, no-transform` | yes | 1.0 | yes | yes |
+| en.wikipedia.org/wiki/Web_scraping | 200 | no | yes | yes | yes | `private, s-maxage=0, max-age=0, must-revalidate, no-transform` | yes | 1.0 | yes | yes |
+| en.wikipedia.org/wiki/Incremental_computing | 200 | no | yes | yes | yes | `private, s-maxage=0, max-age=0, must-revalidate, no-transform` | yes | 1.0 | yes | yes |
+| en.wikipedia.org/wiki/Large_language_model | 200 | no | yes | yes | yes | `private, s-maxage=0, max-age=0, must-revalidate, no-transform` | yes | 1.0 | yes | yes |
+| github.com/cocoindex-io/cocoindex | 200 | yes | no | yes | no | `max-age=0, private, must-revalidate` | no | 0.9942 | yes | yes |
+| github.com/adbar/trafilatura | 200 | yes | no | yes | no | `max-age=0, private, must-revalidate` | no | 0.9936 | yes | yes |
+| github.com/mendableai/firecrawl | 200 | yes | no | yes | no | `max-age=0, private, must-revalidate` | no | 0.9961 | yes | yes |
+| github.com/assafelovic/gpt-researcher | 200 | yes | no | yes | no | `max-age=0, private, must-revalidate` | no | 0.9939 | yes | yes |
+| raw.githubusercontent.com/cocoindex-io/cocoindex/main/README.md | 200 | yes | no | yes | yes | `max-age=300` | yes | 1.0 | yes | yes |
+| arxiv.org/pdf/2402.14207 | 200 | yes | yes | yes | yes | `β€”` | yes | 1.0 | β€” | β€” |
+| arxiv.org/pdf/1706.03762 | 200 | yes | yes | yes | yes | `β€”` | yes | 1.0 | β€” | β€” |
+| www.rfc-editor.org/rfc/rfc9111.pdf | 200 | yes | no | yes | yes | `public, max-age=86400` | yes | 1.0 | β€” | β€” |
+| www.w3.org/TR/2008/REC-xml-20081126/REC-xml-20081126.pdf | 300 | no | no | β€” | β€” | `max-age=31536000` | yes | 1.0 | yes | yes |
+| arxiv.org/abs/2402.14207 | 200 | no | yes | yes | yes | `max-age=3600` | yes | 1.0 | yes | yes |
+| pypi.org/project/trafilatura/ | 200 | yes | no | yes | yes | `β€”` | yes | 1.0 | yes | yes |
+| stackoverflow.com/questions/11177548/what-is-the-difference-between-etag-and-last-modified | 403 | no | no | β€” | β€” | `β€”` | no | 0.0 | β€” | yes |
+| jina.ai/reader/ | 200 | no | yes | yes | yes | `max-age=600` | yes | 1.0 | yes | yes |
+| www.firecrawl.dev/pricing | 200 | no | no | β€” | β€” | `private, no-cache, no-store, max-age=0, must-revalidate` | no | 0.9868 | yes | yes |
+| tavily.com/ | 200 | yes | no | yes | no | `s-maxage=300` | no | 0.987 | yes | yes |
+| exa.ai/ | 200 | yes | no | yes | no | `public, max-age=0, must-revalidate` | no | 0.9961 | yes | yes |
diff --git a/examples/cocoindex_agents/flows/research/survey/review-round1.md b/examples/cocoindex_agents/flows/research/survey/review-round1.md
new file mode 100644
index 00000000..19a514ce
--- /dev/null
+++ b/examples/cocoindex_agents/flows/research/survey/review-round1.md
@@ -0,0 +1,68 @@
+Reviewed the requested files and checked the proposal against the implementation. No files changed; no tests ran.
+
+1. **must-fix β€” Β§3 β€œA page is a resource” / citations: timestamps enter memo keys.**
+ `Fetched: <UTC>` enters `read_input`’s tool result and therefore every later turn’s transcript key; copied citations also enter reducer arguments. Excluding the timestamp from the page digest does not fix this: a task or version change can rerun the worker with identical content but a new timestamp.
+ **Evidence:** [proposal:123](/home/jiangzhou/.reduce/projects/cocoindex/.claude/worktrees/cocoindex-agents-a-research-flow/examples/cocoindex_agents/flows/research/DESIGN-proposal.md:123), proposal:318–322; frozen `DESIGN.md:192–195` explicitly forbids timestamps in tool results.
+ **Change:** Remove fetch times from model-visible headers and citations. Keep them in trace metadata. Make the digest cover all remaining worker-visible content, including the title.
+
+2. **must-fix β€” Β§3 β€œTwo listings” / records: exclusion depends on unstated session state.**
+ β€œMinus the keys any other listing … has yielded this run” makes membership depend on execution order, including concurrent source openings. The record specifies only β€œthe URL list,” without establishing whether it contains requested URLs or the effective list after exclusion; a validator cannot reproduce the former without the other listings.
+ **Evidence:** [proposal:149](/home/jiangzhou/.reduce/projects/cocoindex/.claude/worktrees/cocoindex-agents-a-research-flow/examples/cocoindex_agents/flows/research/DESIGN-proposal.md:149), proposal:204–212; frozen `DESIGN.md:197–205` requires independent calls within a turn.
+ **Change:** Resolve exclusion against an explicitly defined snapshot, then freeze the effective URL list into the source identity and record. Define same-turn behavior without depending on which fetch finishes first.
+
+3. **must-fix β€” Β§3 frontier: the stored set does not fully specify hysteresis.**
+ The rule does not define how retained URLs consume per-query quotas when they appear under several queries, or how requested URLs match previously selected final URLs after redirects. It also says the body uses the previous recorded frontier without specifying how the body obtains that history.
+ **Evidence:** [proposal:139](/home/jiangzhou/.reduce/projects/cocoindex/.claude/worktrees/cocoindex-agents-a-research-flow/examples/cocoindex_agents/flows/research/DESIGN-proposal.md:139), proposal:112–115, 204–210; `use_data_dep` records state and returns `None` (`python/cocoindex/_internal/data_dep.py:168`).
+ **Change:** Specify one pure selection function, its complete inputs, deterministic query allocation, and persisted history available to the body. Store candidate URLs and their final-URL mappings separately. Test an incumbent reached through a redirect moving from rank 3 to 5, and incumbents moving between overlapping queries.
+
+4. **must-fix β€” Β§7 failures: validator exceptions bypass open-session containment.**
+ The proposal promises that search outages and network failures become contained failures in the session opening the source, but those same operations run during validation before that body executes. An exception there fails the run directly.
+ **Evidence:** [proposal:363](/home/jiangzhou/.reduce/projects/cocoindex/.claude/worktrees/cocoindex-agents-a-research-flow/examples/cocoindex_agents/flows/research/DESIGN-proposal.md:363); `python/cocoindex/_internal/data_dep.py:327–351` explicitly propagates validator exceptions, including processor-free descendant validation. The Drive implementation handles this boundary in `tools/drive.py:139–144`.
+ **Change:** After appropriate retries, validators should return an invalid record for environment failures; the body then retries and reports them through the existing containment mechanism. Preserve cancellation and deadline propagation.
+
+5. **must-fix Β· DECISION β€” Β§3 fetching / Β§7: β€œunavailable” changes the frozen failure policy.**
+ Treating exhausted 429/503 retries and timeouts as reusable absence contradicts Β§7’s rule that exhausted transient errors become environment failures. Separately, fetching before workers cannot guarantee `failed=0`: model, rendering, or other worker failures still populate the collection’s failure count.
+ **Evidence:** [proposal:183](/home/jiangzhou/.reduce/projects/cocoindex/.claude/worktrees/cocoindex-agents-a-research-flow/examples/cocoindex_agents/flows/research/DESIGN-proposal.md:183), proposal:190–198, 464–465; frozen `DESIGN.md:842–873`; `tools/agents.py:341–348`.
+ **Change:** Obtain an explicit owner decision on amending the frozen failure policy. Otherwise classify permanent outcomes such as 404, robots refusal, and unsupported media as data, and retain environment handling for exhausted transient failures. Replace the zero-failure guarantee with β€œfetch unavailability does not increment worker failures,” and specify how report readers learn about omitted sources.
+
+6. **should-fix β€” Β§3 page cache / Β§7: the cache lifecycle is incomplete.**
+ Validators cannot access the session’s `use_state`, so a changed-page validation followed by a body run can fetch that page twice; refreshed validator metadata can also advance while the skipped body’s cache stays unchanged. The cache has no pruning rule, so the 24-page run budget does not bound accumulated text or PDF storage.
+ **Evidence:** [proposal:161](/home/jiangzhou/.reduce/projects/cocoindex/.claude/worktrees/cocoindex-agents-a-research-flow/examples/cocoindex_agents/flows/research/DESIGN-proposal.md:161), proposal:204–215, 371–374; `python/cocoindex/_internal/data_dep.py:344–351` states that descendant validation has no component state handler.
+ **Change:** Keep the persistent payload cache separate from the current run’s checked results. Define behavior for skipped bodies, refreshed validators, and failed fetches retaining an older payload. Prune entries outside the current listings. The smallest implementation can explicitly permit another fetch after validation misses and correct the network estimates.
+
+7. **should-fix β€” Β§3 fetching: cutting a PDF at the byte cap produces invalid input.**
+ Streaming β€œand cut at the cap” can turn a valid oversized PDF into an incomplete document that is nevertheless handed to the model. This also undermines the claim that page-fetch trouble cannot become a worker failure.
+ **Evidence:** [proposal:181](/home/jiangzhou/.reduce/projects/cocoindex/.claude/worktrees/cocoindex-agents-a-research-flow/examples/cocoindex_agents/flows/research/DESIGN-proposal.md:181); `documents.py:51–52` accepts the supplied bytes without repairing a truncated PDF.
+ **Change:** Detect overflow and classify an oversized PDF as `too-large`; never attach a truncated PDF. Distinguish transport-size rejection from the explicitly marked text truncation.
+
+8. **should-fix β€” Β§3 extraction / implementation risks: the proposed fallback misses the measured failure.**
+ The fallback activates below 500 extracted characters, but the documented GitHub failure produces roughly 3,000 characters of sidebar text. That output passes the fallback threshold and becomes the content fingerprint despite omitting the repository content.
+ **Evidence:** [proposal:118](/home/jiangzhou/.reduce/projects/cocoindex/.claude/worktrees/cocoindex-agents-a-research-flow/examples/cocoindex_agents/flows/research/DESIGN-proposal.md:118), proposal:531–535.
+ **Change:** Add a saved GitHub-page fixture that asserts relevant content and a material edit survive extraction. Either provide a deterministic repository-content path with explicit provenance or report this page type as unsupported. Repeated extraction being identical is insufficient evidence of useful extraction.
+
+9. **should-fix β€” Β§0 vocabulary: item keys and resource identities are conflated.**
+ A path under a root is not globally unique within `localfs`: two roots can both contain `README.md`. Conversely, one web page is the same resource across the two different listing kinds, `web_search` and `web_pages`.
+ **Evidence:** [proposal:29](/home/jiangzhou/.reduce/projects/cocoindex/.claude/worktrees/cocoindex-agents-a-research-flow/examples/cocoindex_agents/flows/research/DESIGN-proposal.md:29); existing `tools/sources.py:99–100` includes the root in source identity.
+ **Change:** Define resource identity separately from the source-local item key: root plus path, account/folder plus path, or canonical page URL. Describe the web kinds as listing kinds. Cut the prospective title-based output-naming clause until shape A over pages is implemented.
+
+10. **should-fix β€” Β§3 `web_pages` / Β§5: ordered-list and set semantics contradict each other.**
+ The source uses first-seen URL order and applies a budget, while Β§5 calls its identity a URL set and promises that prose changes around the same URLs change nothing downstream. Reordering the same URLs can change the memo key, and beyond the budget can change membership.
+ **Evidence:** [proposal:149](/home/jiangzhou/.reduce/projects/cocoindex/.claude/worktrees/cocoindex-agents-a-research-flow/examples/cocoindex_agents/flows/research/DESIGN-proposal.md:149), proposal:343–346.
+ **Change:** Define admission order separately from identity: choose budgeted membership deterministically, then sort the selected canonical URLs for the source key and record. If ranking changes are intended dependencies, document that exception instead.
+
+11. **should-fix β€” schema changes: multi-collection reduce lacks merge semantics.**
+ Accepting a list is a small change, but concatenation can introduce duplicate item identities; those identities determine hash grouping and reducer slots. The proposal does not define duplicate collection handles, colliding item keys, or malformed list members.
+ **Evidence:** [proposal:503](/home/jiangzhou/.reduce/projects/cocoindex/.claude/worktrees/cocoindex-agents-a-research-flow/examples/cocoindex_agents/flows/research/DESIGN-proposal.md:503), proposal:524; `tools/agents.py:395–397` derives reducer identities directly from item keys.
+ **Change:** Normalize string-or-list input at the boundary into a nonempty list of strings, reject duplicate handles and colliding item keys, and preserve existing keys for valid inputs. Per-kind `open_source` checks can remain in its handler; no larger validation framework is needed.
+
+12. **should-fix β€” Β§5 widened counts: the chosen budgets sit on bucket boundaries.**
+ Sixteen items render as `16–32`, whereas fifteen render as `8–16`; eight render as `8–16`, whereas seven render as `4–8`. Thus one unavailable page can change both cards in the ordinary full-budget case.
+ **Evidence:** [proposal:334](/home/jiangzhou/.reduce/projects/cocoindex/.claude/worktrees/cocoindex-agents-a-research-flow/examples/cocoindex_agents/flows/research/DESIGN-proposal.md:334); `tools/stats.py:15–16,38–39` defines half-open buckets.
+ **Change:** Correct the examples and the no-orchestrator-inference claims. If stable cards across those transitions are required, implement recorded count hysteresis rather than leaving it as a target.
+
+13. **should-fix β€” cost estimates: reducer sessions are counted as single calls.**
+ Cold reducers first call `read_input`, then answer; the proposed 60-call total counts four reducer sessions as four calls instead of eight. The fixed change-cost figures also assume a stable tree shape and bounded worker-answer sizes, neither of which the proposal establishes.
+ **Evidence:** [proposal:456](/home/jiangzhou/.reduce/projects/cocoindex/.claude/worktrees/cocoindex-agents-a-research-flow/examples/cocoindex_agents/flows/research/DESIGN-proposal.md:456); `flows/README.md:109` measures two calls for one cold reducer; frozen `DESIGN.md:673–683` limits locality claims to unchanged tree shapes.
+ **Change:** Count two calls per cold reducer session and one answer call per changed, previously mounted reducer session. Under the stated four-session assumption the first-run total is approximately 64. Present regrouping and network retries separately, derive token estimates from explicit answer-size assumptions, and reconcile the differing survey totals before quoting them as evidence.
+
+**Verdict: needs rework.** The frontier’s persisted history, exclusion inputs, and cache lifecycle need a precise shared contract before implementation. Remove timestamps from model inputs, settle the unavailable-page policy with the owner, and specify validator failure handling; then revise the acceptance cases and cost table around those decisions.
diff --git a/examples/cocoindex_agents/flows/research/survey/review-round2.md b/examples/cocoindex_agents/flows/research/survey/review-round2.md
new file mode 100644
index 00000000..c89c757e
--- /dev/null
+++ b/examples/cocoindex_agents/flows/research/survey/review-round2.md
@@ -0,0 +1,87 @@
+# Research flow proposal β€” round 2 review
+
+Reviewed revision 2 of DESIGN-proposal.md against the frozen design, the existing implementation, the round-1 report, and the supplied measurements. No worktree files were edited and no tests were run. This is a design review; the proposed acceptance tests have not been implemented or executed.
+
+Paths below are relative to /home/jiangzhou/.reduce/projects/cocoindex/.claude/worktrees/cocoindex-agents-a-research-flow/. β€œP” means examples/cocoindex_agents/flows/research/DESIGN-proposal.md, β€œD” means examples/cocoindex_agents/DESIGN.md, and package paths such as tools/agents.py are under examples/cocoindex_agents/cocoindex_agents/.
+
+## Disposition of every round-1 finding
+
+1. **Timestamps in memo keys β€” partially resolved; DECISION remains.** P:121–152 now includes the title in the digest and preserves the cached stamp across identical 200s, 304s, and task changes. That resolves the ordinary repeated-fetch problem, but option (a) still explicitly amends the frozen no-time rule, and its stability argument does not cover changing requested aliases for the same final resource; see new finding 2. P:429–432 also incorrectly asserts that changed content necessarily changes the findings and therefore the stamp cannot cause an extra reducer run. Option (b) closes the timestamp finding without changing the frozen rule. The owner must choose; a review cannot approve that policy on their behalf.
+
+2. **Exclusion and hidden session state β€” partially resolved.** The handle-table snapshot and sorted effective requested-URL list are now explicit (P:190–204), so ordinary direct-URL exclusion and same-turn ordering are defined and independently validatable. A lead that reaches an already-read final URL through a previously unseen alias still survives exclusion, creates a duplicate worker, and collides in multi-collection reduce; see new finding 1. The global no-two-fan-outs claim at P:58–61 is also stronger than the deliberately permitted same-turn overlap.
+
+3. **Undefined frontier/history β€” resolved at the design-contract level.** P:156–183 supplies the pure function, removes per-query allocation, distinguishes requested and final identities, and gives the body and validator the same previous requested-URL set. The acceptance cases at P:501 cover the previously missing overlap and redirect history. A separate limit on the rank-jitter guarantee remains; see new finding 4. Frontier comparison should use selected membership, not the incidental rank order of retained members.
+
+4. **Validator exception containment β€” resolved.** P:310–316 explicitly returns an invalid outcome with the prior state for exhausted transient failures and engine outages, while propagating cancellation and deadlines; P:504 requires coverage. This matches the existing Drive boundary and the processor-free validator contract.
+
+5. **Unavailable/failure classification and failed=0 β€” partially resolved; DECISION remains.** P:252–288 now distinguishes permanent outcomes from exhausted transient environment failures, records a never-valid failure per transiently unavailable URL, and correctly limits the claim about failed. The owner still must approve containing a failed sub-operation while the tool returns ok=True. Before presenting that decision, correct P:273–275 and P:614: under frozen D:857–865 an open_source environment failure is an ok=False tool result contained by the open session, not automatically a failed research run. Also correct P:278–279: an unrepaired model-facing error does not itself mark a worker failed; D:850–856 permits the worker to finish successfully after such a result. The plan/stats channel for omissions is now specified; that is the proposed product choice, not evidence that the report file itself communicates omissions.
+
+6. **Page-cache lifecycle β€” partially resolved.** P:211–238 specifies pruning, skipped bodies, stale payload retention without serving it, refreshed record validators, and the accepted second fetch after validation misses. Those parts are resolved. The cache is still indexed by requested URL rather than final resource identity, leaving the alias/payload/version interaction in new findings 1 and 2. The run-level claims should say once per requested URL in a body run unless final-response reuse is also specified; validation plus body is explicitly two rounds.
+
+7. **Truncated PDF β€” resolved.** P:243–247 rejects an oversized PDF as too-large instead of attaching partial bytes, and P:503 requires that case. HTML transport truncation is separately marked.
+
+8. **Extraction fallback and meaningful-change coverage β€” partially resolved.** P:386–395 stops claiming the under-500-character fallback repairs a 3k-character sidebar extraction and states the unsupported-quality cases. However, P:392–394 and P:506 still require a material main-content edit to change the digest for each page type, explicitly including a repository page, while P:387–390 accepts extracting only its sidebar. A README-only edit in that known case cannot satisfy both statements. State which page types must pass positive content-coverage tests; make the repository fixture either pass that requirement through a real extraction change or explicitly document an accepted limitation outside that guarantee. Do not call a fixture that merely records the sidebar a passing material-change test.
+
+9. **Resource identity versus item key and premature naming β€” resolved.** P:33–60 distinguishes global resource identity, source-local keys, and the two listing kinds sharing a page resource. P:69–71 removes the speculative title-based output naming. No additional model-facing resource API is needed for this vocabulary change.
+
+10. **Ordered admission versus set identity β€” resolved.** P:190–204 defines admission order, exclusion, budget selection, sorted identity, and the membership-changing exception at the budget boundary. The rewording/reordering acceptance case at P:502 now has a coherent meaning.
+
+11. **Multi-collection reduce semantics β€” resolved.** P:647–651 defines a string or nonempty list of distinct handles, colliding item keys as a model-facing error, and summed omitted counts; P:507 specifies tests. Preserve existing item keys for valid inputs and explicitly type-check list members at the handler boundary, as round 1 requested. This remains a small change; no generic schema framework is necessary. Its collision rejection correctly reveals, rather than fixes, the redirect-deduplication bug in new finding 1.
+
+12. **Budgets on count boundaries β€” resolved.** P:444–451 moves full sources to 12 and 6, states the half-open buckets, limits the stability claim to the common case, and leaves count hysteresis deferred. The common full-budget one-page-loss case no longer crosses a bucket. This does not imply all sparse search results fit those buckets.
+
+13. **Cost accounting β€” partially resolved.** P:570–591 now states page counts, approximate answer sizes, one-group assumptions, two cold calls per worker/reducer session, and separate validator/body requests. The 48-call cold arithmetic follows those assumptions. P:592 is still wrong: if every child's task changes, each reducer's read_input turn misses too, because the SessionSpec is part of every turn key (D:432–433; session.py:273–279), so the two reducers cost four calls, not two. Replaying old orchestrator actions also preserves their old child task strings; separate that case from genuinely composing new child tasks. Limit the three-call material-edit row to a search-round page with unchanged follow membership; an edited follow-round page normally costs two calls, and changed leads can add cold follow workers. Finally, the survey totals remain unreconciled: P:535 says 21 of 24 ETags versus survey/results.md:13's 22, and P:537 says Cache-Control 33/45 and restrictive directives 26 versus survey/results.md:15's 35/45 and 25. Correct these from the raw evidence or label the figures unresolved.
+
+## New findings and newly exposed interactions
+
+1. **must-fix β€” Β§3 β€œTwo listings” / resource deduplication: exclusion before redirects does not ensure one worker per page.**
+
+ **Problem:** Suppose the search source requested A and yielded final page F; the leads source later requests B, where B is absent from the snapshot's requested/final sets but redirects to F. B survives exclusion, becomes a second item keyed F, and the prescribed final reduce rejects the two collections for colliding item keys.
+
+ **Evidence:** P:178–183 deduplicates requested URLs by final URL within a search listing; P:190–204 excludes the leads' requested URLs before fetching. P:647–651 rejects duplicate item keys across collections. P:58–61 nevertheless promises no duplicate workers across fan-outs. The scenario requires no same-turn race.
+
+ **Change:** Apply final-resource exclusion after resolving redirects as well as requested-URL exclusion before fetching. Freeze the relevant snapshot exclusions in the record so validation can reproduce that filtering without handles. Keep the requested-to-final observation for a suppressed alias, so a later redirect from B to a new page G invalidates the listing and admits G. Distinguish a requested-URL response/redirect cache from a final-resource payload store. Add the A→F, B→F, then B→G acceptance case. Limit the one-worker claim to the recipe/defined exclusion scope; same-turn sibling sources explicitly can overlap.
+
+2. **must-fix Β· DECISION β€” Β§3 version stamp / cache: option (a) does not yet make the stamp a stable property of a resource version.**
+
+ **Problem:** The stamp lives in a cache keyed by requested URL, so replacing A→F with a previously unseen B→F can give the unchanged final resource F and unchanged digest a new stamp; the worker's memo key does not cover that change. Independently, a normalized page edit can leave topic-relevant findings byte-identical, while the forced new citation stamp changes reducer input and causes inference that value-based reuse would otherwise avoid.
+
+ **Evidence:** P:137–152 says the stamp moves only with the digest and calls it a content-version property; P:211–219 stores it per requested URL and prunes old aliases; P:473–476 keys the worker on final URL plus digest. P:429–432 asserts that changed content implies changed findings, which is not a valid inference.
+
+ **Change:** Prefer option (b) if preserving the frozen no-time contract is the goal. If the owner chooses (a), persist the stamp with the final resource version and reuse it across alias replacement while that resource remains live; define its lifecycle under pruning and reintroduction and ensure every model-visible change is covered by the worker and read-validation contracts. Add an alias-replacement followed by a task-change test. Explicitly accept the potential extra reducer reruns when findings stay identical; remove the claim that timestamps cost no extra reducer calls. Owner approval is still required for the clock-in-tool-results amendment.
+
+3. **must-fix β€” Β§3 β€œSearch engines” / Β§7 invalidation: naming an engine in stored records does not detect a change of selected engine.**
+
+ **Problem:** If a successful keyless run stored Wikipedia records and the next run selects Tavily, the root can still validate the old records with Wikipedia and skip before open_source observes the new selection. The proposal promises invalidation but does not specify a tracked dependency on the currently selected engine.
+
+ **Evidence:** P:294–303 reconstructs validation from the stored engine name; P:346–349 puts selection behind a context key β€œas the model is” and claims that another engine reruns the search. ContextKey defaults to detect_change=False (python/cocoindex/_internal/context_keys.py:104); the existing agent config deliberately uses detect_change=True (tools/__init__.py:275–277). The frozen design explicitly excludes the model client object from change tracking (D:764–768), so copying that arrangement does not supply this guarantee.
+
+ **Change:** Specify that the selected engine's stable identity and result-affecting configuration are a tracked input of the root memoized session/config, or provide an equivalent invalidation mechanism before ancestor reuse. Do not fingerprint credentials. Validators must remain usable without a live source object or descendant component context. Add a same-state-directory Wikipedia→Tavily test asserting that the old Wikipedia frontier is not silently reused.
+
+4. **should-fix β€” Β§3 frontier / Β§5 volatility: rank jitter can expand an underfilled frontier.**
+
+ **Problem:** With one query, k=4, budget=12, and prev={A,B,C,D}, moving D from rank 4 to 5 while E moves from 5 to 4 retains all four incumbents and admits E into a free place. Thus the specified function is deterministic, but rank movement wholly within top-2k can change membership and run a new worker.
+
+ **Evidence:** P:165–171 admits all top-k newcomers whenever the budget has room; P:185–188 and P:452–455 describe rank jitter as changing nothing, and P:501 requires rank jitter to keep the set without stating a full-frontier precondition.
+
+ **Change:** Keep the defined function and qualify the stability guarantee and tests: jitter alone preserves membership when the frontier is full, or when it admits no eligible newcomer. Add the underfilled example as an expected expansion. If stability for underfilled sources is a requirement, change the admission rule explicitly rather than asserting that the present rule provides it.
+
+5. **should-fix β€” Β§3 citations / PDF input: timestamp option (a) has no model-visible stamp for a PDF.**
+
+ **Problem:** PDF workers are instructed to copy a version stamp from the page header, but their read_input result is a document reference with no header or stamp. The existing reference contains only key, media_type, bytes and digest, so the PDF path cannot follow the proposed citation recipe under option (a).
+
+ **Evidence:** P:337 specifies a document reference for PDFs; P:407–419 requires the copied stamp in findings and Sources. documents.py:54–61 defines the reference, and tools/sources.py:267–268 returns it directly after attaching the bytes.
+
+ **Change:** Under option (a), include the stable page-version metadata in the small PDF read result/reference and apply the same covered-input contract as text pages; never prepend textual headers to PDF bytes. Add a PDF citation assertion, not just a document-attachment assertion. Under option (b), URL-only citations already fit the existing reference and this finding closes.
+
+6. **should-fix β€” Β§8 acceptance / recipe: expected empty research outcomes are untested.**
+
+ **Problem:** A query can return no hits, or every admitted page can be permanently unavailable, leaving the first collection empty and the recipe's leads reduce unable to run. No current acceptance row defines the report/completion behavior for that expected state or its recovery on the next run.
+
+ **Evidence:** P:83–88 prescribes the first fan-out followed by a leads reduce; P:254–258 omits permanent unavailable pages from items; P:498–507 covers individual unavailable outcomes but no all-empty case. Frozen D:649–650 makes an empty reduce a model-facing tool error.
+
+ **Change:** Add end-to-end cases for no search hits, all initial pages unavailable, and no follow leads. Specify that an empty initial corpus produces an honest no-evidence report/status rather than an apparently successful substantive report, and verify recovery when one page becomes available. The no-follow-leads case should permit reducing the nonempty first collection together with an empty second collection. Reuse existing tools and model-facing empty-reduce behavior; no new public API is needed.
+
+## Verdict
+
+**Ready after the must-fixes and the two recorded owner decisions.** The core frontier and record contracts are now concrete enough to implement once final-resource deduplication and selected-engine invalidation are specified. Timestamp option (a) also needs the alias/version and PDF contracts above; option (b) avoids that additional model-visible state. Correct the remaining extraction-test contradiction, rank-jitter wording, and cost/measurement claims, then implement the acceptance cases before claiming the stated reuse behavior. No implementation approval or policy choice is implied by this review.
diff --git a/examples/cocoindex_agents/flows/research/survey/review-round3.md b/examples/cocoindex_agents/flows/research/survey/review-round3.md
new file mode 100644
index 00000000..03e7a2fd
--- /dev/null
+++ b/examples/cocoindex_agents/flows/research/survey/review-round3.md
@@ -0,0 +1,73 @@
+# Research flow proposal β€” round 3 review
+
+Reviewed revision 3 against the complete round-2 report, the frozen design, the existing handle/mount contracts, and the saved survey results. No worktree files were edited. No application tests were run; the proposed tests remain acceptance requirements, not executed evidence. The only additional computation was a read-only recount of the saved survey JSON.
+
+Paths below are relative to /home/jiangzhou/.reduce/projects/cocoindex/.claude/worktrees/cocoindex-agents-a-research-flow/. P means examples/cocoindex_agents/flows/research/DESIGN-proposal.md; D means examples/cocoindex_agents/DESIGN.md. Package paths such as tools/agents.py are under examples/cocoindex_agents/cocoindex_agents/.
+
+## Disposition of the six new round-2 findings
+
+1. **Alias Bβ†’F bypassing exclusion β€” resolved for the recipe's deduplication rule.** P:215–242 now separates requested-URL filtering from final-resource filtering, freezes both exclusion sets in the record, and retains suppressed aliases so Bβ†’G later invalidates the observation. P:575 specifies the exact Aβ†’F, Bβ†’F, Bβ†’G acceptance case. P:61–64 limits the one-worker claim to the sequential recipe and explicitly allows same-turn overlap. A newly exposed source-identity issue with those frozen exclusions remains in new finding 2; the two-stage filtering algorithm itself is now specified.
+
+2. **Version stamp as an unstable resource property β€” resolved under the recommended option (b); owner DECISION remains.** P:137–170 removes time from model-visible text in the path revision 3 commits to describing. Under the retained option (a), the stamp belongs to the final resource version, alias replacement preserves it, and extra reducer work when only the stamp changes is acknowledged. This closes the former claim that a clock field necessarily costs no inference. Selecting (a) would still amend the frozen no-time rule and requires the owner's decision. The cache coherence requirement in new finding 1 applies to both options; choosing (b) does not require implementing the optional stamp machinery.
+
+3. **Engine selection not tracked before reuse β€” resolved.** P:362–374 puts the result-affecting engine identity in the change-detected AgentsConfig and separates it from the untracked client object and credentials. P:578 requires a same-state-directory engine-switch test. Adding the field to AgentsConfig.__coco_memo_key__ is part of implementing this stated contract; merely adding a dataclass field would not suffice because the class has an explicit memo-key method.
+
+4. **Underfilled frontier grows under jitter β€” resolved.** P:183–213 defines selection as a membership set and qualifies stability by a full frontier or no eligible newcomer. The D/E example is explicitly expected expansion, and P:574 requires that behavior. No further hysteresis mechanism is required for this rule.
+
+5. **PDF cannot supply the citation stamp β€” resolved under option (b), with option (a)'s change explicitly specified.** P:149–164 supplies URL-only citations in the default text and requires the stamp in the small PDF reference only if the owner selects (a). No textual prefix is added to PDF bytes. This is sufficient at the design level; an implementation of (a) must test the citation metadata, not only attachment of the PDF.
+
+6. **Empty research outcomes undefined β€” resolved.** P:94–99 and P:495–501 define an honest no-evidence report for an empty initial collection and allow an empty follow collection when the union is nonempty. P:580–582 requires no-hit, all-unavailable, no-lead and recovery cases, and makes empty-member semantics explicit for multi-collection reduce. No new tool is needed.
+
+## Carry-over dispositions from the round-2 review of round 1
+
+These cover the additional unresolved matters recorded in round 2, so none is silently dropped.
+
+1. **Timestamps β€” resolved under (b), pending the existing owner DECISION.** The frozen rule holds for the proposed URL-only header/citations (P:137–170, 474–493). Do not build both options before the owner chooses.
+
+2. **Exclusion and hidden state β€” partially resolved.** Snapshot selection, replayable exclusion records and post-redirect filtering are resolved (P:215–242, 336–347). The source's own memo identity still omits a result-affecting exclusion input; see new finding 2.
+
+3. **Frontier function/history β€” resolved.** P:174–213 defines the pure function, body history, requested identities, final mapping, and membership comparison. The corresponding test cases are listed at P:574.
+
+4. **Validator exceptions β€” resolved.** P:354–360 preserves the invalid-record boundary for environment failures and propagates cancellation/deadlines. P:577 requires coverage.
+
+5. **Failure policy/failed count β€” resolved technically, pending the existing per-page-containment DECISION.** P:293–330 correctly identifies exhausted transient fetches as environment failures and records them so reuse cannot hide recovery; permanent outcomes remain data. It also corrects the previous assertion that a model-facing error inherently marks a worker failed. The whole-tool alternative is now described as a contained ok=False result rather than an automatically failed app run. The further statements that the model could do nothing and that no report would be written are recipe expectations, not consequences of Β§7: the model could still write a no-evidence report. That wording should not be used as the technical justification for the policy decision. Omission visibility remains a stated plan/stats choice, not a guarantee about the report file.
+
+6. **Cache lifecycle β€” partially resolved.** P:249–279 now defines separate requested-response and final-payload stores, pruning, skipped bodies, retained old payloads that are not served after failure, and separate validation/body fetch rounds. The response-to-payload version association is still missing; see new finding 1.
+
+7. **Truncated PDF β€” resolved.** P:284–288 rejects oversized PDFs rather than attaching truncated bytes; P:576 requires it.
+
+8. **Normalizer coverage contradiction β€” resolved.** P:444–460 explicitly scopes the positive material-edit/boilerplate-edit fixture requirement to covered page types and records repository/sidebar behavior as a limitation outside that guarantee. P:581 follows that distinction. This is an honest limit, not a claim that the normalizer detects every relevant edit on the open web. The examples and README must preserve that scope.
+
+9. **Vocabulary/identity β€” resolved at the resource/item level.** P:33–64 separates resource identity, item keys, and listing kinds, and P:72–74 leaves page-output naming out of scope. New finding 2 concerns the identity of the filtered listing handle, not the page resource identity.
+
+10. **Admission order versus identity β€” resolved for order and budget membership.** P:215–242 specifies ordered admission followed by a sorted effective requested list and documents the budget-boundary exception. The additional exclusion-dependent identity issue is new finding 2.
+
+11. **Multi-collection reduce β€” resolved.** P:732–738 and P:582 require typed distinct handle names, collision rejection, unchanged item keys, summed omissions, and a nonempty union while allowing empty members. This remains the smallest honest extension to the existing tool.
+
+12. **Count buckets β€” resolved.** P:513–526 covers the full-budget case, explicitly allows sparse results to cross buckets, and defers count hysteresis. No general zero-orchestrator-inference guarantee should be inferred outside the stated unchanged-card case.
+
+13. **Cost arithmetic and measurements β€” resolved as estimates under the stated assumptions.** P:647–674 counts both turns when a task changes, separates reused tasks from newly composed tasks, distinguishes search-round and follow-round edits, and accounts for new follow workers. The saved raw JSON at /tmp/research-survey/data/results.json independently gives 45 pages fetched in both passes, 24 ETag pages, 21 answering If-None-Match with 304, 22 ETag pages answering either conditional with 304, 35 Cache-Control pages, and 25 with the stated restrictive directives. Thus P:611's 21 and survey/results.md's 22 describe different predicates; the explicit If-None-Match wording resolves the earlier discrepancy. P:613 matches the raw counts. The residual precise call/network figures are scenarios, not upper bounds or acceptance results. Changing a digest need not change the worker answer or final findings; identical outputs can still stop downstream work.
+
+## New findings
+
+1. **must-fix β€” Β§3 β€œTwo stores in use_state” / conditional requests: validators are not tied to the payload version they validate.**
+
+ **Problem:** A requested response stores only final URL plus HTTP validators, while the final URL points to one mutable payload; after another alias advances that payload, the older alias's validator can no longer safely authorize reusing it. Likewise, if Aβ†’F returns content C1/ETag E1 and Bβ†’F later returns C2/E2 in one body run, β€œnormalize once” can leave B's E2 associated with C1; a later 304 for E2 would then serve the wrong content.
+
+ **Evidence:** P:249–257 defines the response fields without a payload digest/version and allows one payload per final URL; P:267–270 says a 304 simply keeps that payload. P:265 retains older payload/cache information after a failed fetch, so cross-run alias entries can also refer to different observed versions. P:579 currently tests normalization once but not the validator/payload association.
+
+ **Change:** Store the normalized payload digest/version that each response validator was obtained with, and reuse a 304 only when the matching payload is actually available. If the single final-payload slot holds another version, retry that requested URL unconditionally or retain immutable payload versions while a live response entry references them. For multiple aliases in one body run, either reuse one final-URL response snapshot before issuing another final GET, or process differing successful responses coherently; do not attach validators from an ignored response to the first payload. β€œNormalize once” is an optimization conditional on reusing the same response snapshot, not a correctness rule for different bytes. Add a fixture where two aliases observe different versions, and one where an old alias is retained after a failure while another alias advances the payload; ensure a subsequent 304 never returns a payload the validator did not validate. Align Β§0's β€œfetched once per run” wording with the actual once-per-requested-URL-per-body-run contract.
+
+2. **must-fix β€” Β§3 web_pages identity / Β§7 open-session reuse: the filtered source's memo key must include its frozen exclusions.**
+
+ **Problem:** The dependency record includes the exclusion sets, but the source's memo identity is still only the effective requested list, even though post-redirect exclusions can change its items without changing that list. An open child passed the source can therefore reuse a memo validated against the old exclusions while receiving a logically different source on the new run.
+
+ **Evidence:** P:218–220 and P:237 define source identity as the sorted effective requested list; P:225–229 makes items additionally depend on the final-URL exclusion set; P:336–338 includes those sets only in the record key. The existing API allows sources as inputs to open children (tools/agents.py:108–123); D:784–807 requires those children to skip only when their arguments and recorded reads still cover the source they received.
+
+ **Counterexample:** In run 1, the earlier search lists F, the page-set source requests B→F and suppresses F, and a planner child given that source observes zero items. In run 2 the search no longer lists F, but the same B still redirects to unchanged F, so the new page-set source has one item. Its requested list and current stated memo key are still [B]; the child's old record replays its frozen exclusion of F and still validates as empty. The child can incorrectly skip and return the old zero-item plan.
+
+ **Change:** Use the full immutable filtered-listing identity for both the source memo key and its record key: listing kind, sorted admitted requested URLs, and the relevant frozen requested/final exclusion sets. These are identity/scope inputs, not page payloads. A source passed across a mount then changes identity whenever the filtering semantics change, while its closed workers remain keyed only on the resulting page items. Add the open-child counterexample above as an acceptance case. No model-facing exclude argument is needed.
+
+## Verdict
+
+**Ready after the two must-fixes and the two existing owner decisions.** The round-2 findings are closed for the recommended no-time path, apart from the cache and source-identity interactions identified above; no further product surface or engine change is needed to address them. Keep timestamps out of model text unless the owner explicitly selects the alternative, and obtain the per-page containment decision before implementation. The remaining corrections are narrow contracts that belong in the source/cache implementation and its acceptance tests; another broad redesign is not indicated.
diff --git a/examples/cocoindex_agents/flows/research/survey/review-round4.md b/examples/cocoindex_agents/flows/research/survey/review-round4.md
new file mode 100644
index 00000000..c355acd6
--- /dev/null
+++ b/examples/cocoindex_agents/flows/research/survey/review-round4.md
@@ -0,0 +1,42 @@
+# Research flow proposal β€” round 4 review
+
+Reviewed revision 4 against the two round-3 must-fixes and the carry-over failure-policy wording note. No worktree files were edited. No application tests were run: the acceptance rows describe required implementation checks, not completed evidence. Project knowledge could not be read during this turn; this review uses the supplied proposal, frozen design, source contracts, and previous review reports, without treating an earlier project-knowledge response as current.
+
+Paths below are relative to /home/jiangzhou/.reduce/projects/cocoindex/.claude/worktrees/cocoindex-agents-a-research-flow/. P means examples/cocoindex_agents/flows/research/DESIGN-proposal.md; D means examples/cocoindex_agents/DESIGN.md.
+
+## Disposition of the round-3 must-fixes
+
+1. **Response validators versus payload version β€” resolved at the design-contract level.**
+
+ P:258–290 now ties each response entry's validators to a specific digest and stores immutable payload versions under (final URL, digest). A 304 can reuse only that version, and absence of the version requires an unconditional refetch. Keeping an old alias after a failed fetch no longer lets another alias silently replace the payload its validators authorize.
+
+ P:270–277 also closes the within-run alias counterexample: hop-by-hop redirects reuse an already obtained final-URL response snapshot, including its validators and digest. The one-normalization behavior follows from sharing that snapshot rather than ignoring a different successful response. P:279–290 defines reference-based pruning so live response entries retain their versions without accumulating unreferenced history.
+
+ **Evidence:** P:259–269 supplies the response-to-version association and missing-version fallback; P:270–290 supplies snapshot reuse, pruning, and failure retention; P:584–589 repeats the integration contract. P:609 requires the different-version aliases, missing-version 304, and shared-response-snapshot cases. The once-per-requested/final-URL wording is corrected in Β§0 at P:59–64.
+
+ **Implementation check:** The per-body-run response snapshot must include in-flight fetches, not only completed entries, so concurrent aliases share the same final fetch. This implements the stated one-snapshot contract; it is not an additional API or design requirement. Test the invariant with concurrent aliases as well as sequential ones. A record-only validator may compare a 304 against its stored digest without loading payload bytes; the body is the path that must possess the named payload or refetch it.
+
+2. **Filtered source memo identity omits exclusions β€” resolved.**
+
+ P:217–246 now makes a web_pages source's memo identity the listing kind, sorted admitted requested URLs, and both frozen exclusion sets, exactly as its dependency-record key. Consequently, a planner receiving [B] with F excluded and later receiving [B] with F admitted receives a changed source identity even while Bβ†’F and the page content remain unchanged. Its former empty-source memo cannot match the new input.
+
+ **Evidence:** P:221–225 states the full identity across a mount; P:240–246 explains the planner counterexample; P:361–368 makes the record/source identity equality explicit; P:590–595 repeats it under integration. P:610 requires the exact open-child regression case.
+
+ **Implementation check:** Construct one immutable identity value and use it for both memo-key rendering and record-key construction, rather than maintaining two parallel tuples. Canonicalize the exclusion sets themselves as well as the admitted URL list. This follows the existing identity contract and prevents insertion order from introducing unrelated misses.
+
+## Carry-over wording note
+
+**Resolved.** P:335–342 now describes the whole-tool alternative as an environment failure contained by the open session, followed by the recipe's no-evidence report, with the eleven successfully fetched pages deferred to a later run. It distinguishes that recipe behavior from an app-run failure and no longer claims that the model cannot write any report. This fairly states the consequence of the owner choosing whole-tool rather than per-page containment; it does not change D Β§7 by itself.
+
+## New findings
+
+None. No new must-fix, should-fix, or nit finding is raised in this round. The two fixes close the previously demonstrated correctness counterexamples without requiring another public tool, a model-facing exclusion argument, or an engine change. The implementation checks above are verification of the now-explicit contracts, not new review blockers.
+
+## Owner decisions still pending
+
+- **DECISION β€” citation time (P:147–171, 738–743).** The proposal is written for recommended option (b): URL-only citations, with fetch provenance in the plan trace. That preserves the frozen no-time rule. Selecting alternative (a) deliberately amends that rule and carries the already-stated PDF, alias/version, and reducer-reuse consequences. Implement the selected option rather than exposing a new configuration knob for both.
+- **DECISION β€” exhausted transient page fetches (P:324–342, 744–748).** Recommended per-page containment keeps open_source successful for the fetched subset while recording a never-valid failure for each exhausted page. It still needs the owner's approval as an amendment to Β§7's tool-level ok=False contract. The whole-tool alternative remains technically coherent and has a defined no-evidence outcome.
+
+## Verdict
+
+**Ready to implement once the two recorded owner decisions are made.** No technical must-fix remains in the design for the recommended URL-only citation path. Close the design review and move verification to the stated implementation tests and real-model drives; those results must establish the reuse and cost claims before they are reported as measured behavior. This verdict does not approve either policy choice on the owner's behalf and does not claim that unimplemented tests have passed.
diff --git a/examples/cocoindex_agents/flows/research/survey/urls.txt b/examples/cocoindex_agents/flows/research/survey/urls.txt
new file mode 100644
index 00000000..2efd4f38
--- /dev/null
+++ b/examples/cocoindex_agents/flows/research/survey/urls.txt
@@ -0,0 +1,58 @@
+# docs
+https://docs.python.org/3/library/asyncio.html
+https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag
+https://docs.astral.sh/uv/
+https://www.postgresql.org/docs/current/mvcc-intro.html
+https://kubernetes.io/docs/concepts/overview/
+https://react.dev/learn
+https://docs.rs/tokio/latest/tokio/
+https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/web-search-tool
+https://platform.openai.com/docs/guides/tools-web-search
+https://www.rfc-editor.org/rfc/rfc9111.html
+https://docs.github.com/en/rest
+# blogs
+https://simonwillison.net/
+https://www.joelonsoftware.com/2000/08/09/the-joel-test-12-steps-to-better-code/
+https://martinfowler.com/articles/microservices.html
+https://blog.cloudflare.com/
+https://engineering.fb.com/
+https://cocoindex.io/blogs/
+https://huggingface.co/blog
+https://openai.com/index/introducing-deep-research/
+https://www.lesswrong.com/
+https://medium.com/@trafilatura
+https://trafilatura.readthedocs.io/en/latest/evaluation.html
+# news
+https://www.bbc.com/news
+https://www.reuters.com/technology/
+https://techcrunch.com/
+https://www.theverge.com/
+https://arstechnica.com/
+https://news.ycombinator.com/
+https://apnews.com/
+https://www.theguardian.com/technology
+https://www.nytimes.com/section/technology
+# wikipedia
+https://en.wikipedia.org/wiki/HTTP_ETag
+https://en.wikipedia.org/wiki/Web_scraping
+https://en.wikipedia.org/wiki/Incremental_computing
+https://en.wikipedia.org/wiki/Large_language_model
+# github
+https://github.com/cocoindex-io/cocoindex
+https://github.com/adbar/trafilatura
+https://github.com/mendableai/firecrawl
+https://github.com/assafelovic/gpt-researcher
+https://raw.githubusercontent.com/cocoindex-io/cocoindex/main/README.md
+# pdfs
+https://arxiv.org/pdf/2402.14207
+https://arxiv.org/pdf/1706.03762
+https://www.rfc-editor.org/rfc/rfc9111.pdf
+https://www.w3.org/TR/2008/REC-xml-20081126/REC-xml-20081126.pdf
+# papers, forums, vendors
+https://arxiv.org/abs/2402.14207
+https://pypi.org/project/trafilatura/
+https://stackoverflow.com/questions/11177548/what-is-the-difference-between-etag-and-last-modified
+https://jina.ai/reader/
+https://www.firecrawl.dev/pricing
+https://tavily.com/
+https://exa.ai/
diff --git a/examples/cocoindex_agents/flows/run.py b/examples/cocoindex_agents/flows/run.py
index 62988b5b..843ee2f7 100644
--- a/examples/cocoindex_agents/flows/run.py
+++ b/examples/cocoindex_agents/flows/run.py
@@ -31,7 +31,7 @@ from cocoindex_agents.app import DEFAULT_MODEL, build_app, default_config # noq
from cocoindex_agents.litellm_client import LiteLLMClient # noqa: E402
from cocoindex_agents.model import MODEL_CLIENT # noqa: E402
from cocoindex_agents.report import RunReport, render_plan, render_stats_line # noqa: E402
-from cocoindex_agents.tools import AGENTS_CONFIG # noqa: E402
+from cocoindex_agents.tools import AGENTS_CONFIG, web # noqa: E402
from cocoindex_agents.trace import SessionScratch # noqa: E402
FLOWS = pathlib.Path(__file__).resolve().parent
@@ -103,7 +103,9 @@ def main(argv: list[str] | None = None) -> int:
litellm.disable_aiohttp_transport = True
env = coco.Environment(coco.Settings.from_env(db_path=flow_dir / ".coco_db"))
client = LiteLLMClient()
- config = default_config(args.model)
+ config = default_config(
+ args.model, search_engine=web.default_engine(os.environ).identity
+ )
env.context_provider.provide(MODEL_CLIENT, client)
env.context_provider.provide(AGENTS_CONFIG, config)
scratch = SessionScratch()
diff --git a/examples/cocoindex_agents/pyproject.toml b/examples/cocoindex_agents/pyproject.toml
index 64e35328..7f706a4e 100644
--- a/examples/cocoindex_agents/pyproject.toml
+++ b/examples/cocoindex_agents/pyproject.toml
@@ -6,7 +6,14 @@ requires-python = ">=3.11"
# use_state, memo_key on components and the APIs this example builds on: v1.1.0 and
# later; `coco.DataDep` and the Google Drive source's `google_drive.UserAccount`
# sign-in: v1.2.0 and later.
-dependencies = ["cocoindex[google_drive]>=1.2.0"]
+dependencies = [
+ "cocoindex[google_drive]>=1.2.0",
+ # The web source (tools/web.py): one HTTP client, and the main-content
+ # extractor whose output is the memo state of a page (DESIGN.md Β§3).
+ "httpx>=0.27.0",
+ "lxml>=5",
+ "trafilatura>=2.0",
+]
[project.optional-dependencies]
llm = ["litellm!=1.107.0"]
diff --git a/examples/cocoindex_agents/tests/test_research.py b/examples/cocoindex_agents/tests/test_research.py
new file mode 100644
index 00000000..8ea5987b
--- /dev/null
+++ b/examples/cocoindex_agents/tests/test_research.py
@@ -0,0 +1,1160 @@
+"""The web as a source (DESIGN.md Β§3, *Sources: the web*): shape E over a fake
+search engine and fake pages served by ``httpx.MockTransport``.
+
+Every test counts model calls (inference) and HTTP requests: an unchanged
+rerun makes no call and only conditional requests; a page that changed in its
+boilerplate re-runs nothing; a page that changed materially re-runs its
+worker's answer turn and the reducers on its path; the frontier rule, the
+exclusion of pages already read, the unavailable classes, the validators'
+behaviour under an outage, the engine as a tracked input, the empty outcomes
+and the normalizer's guarantees per page type.
+"""
+
+from __future__ import annotations
+
+import pathlib
+import re
+from collections import Counter
+from collections.abc import Iterator
+from dataclasses import dataclass, field
+
+import httpx
+import pytest
+
+import cocoindex as coco
+
+from cocoindex_agents import (
+ AGENTS_CONFIG,
+ MODEL_CLIENT,
+ AgentsConfig,
+ RoleSpec,
+ SessionResult,
+ run_open_session,
+)
+from cocoindex_agents.errors import TransientError
+from cocoindex_agents.hints import RunHints
+from cocoindex_agents.report import RunReport, render_plan, render_stats_line
+from cocoindex_agents.spec import SessionSpec
+from cocoindex_agents.testing import CountingRegistry, ScriptedModel
+from cocoindex_agents.tools import agents, sources, targets, web
+from cocoindex_agents.trace import SessionScratch
+from cocoindex_agents.transcript import ModelOutput, ToolCall, ToolResult, Transcript
+
+ORCHESTRATOR = RoleSpec(
+ "orchestrator",
+ "test",
+ ("open_source", "open_target", "for_each", "reduce", "declare", "call"),
+)
+WORKER = RoleSpec("worker", "test", ("read_input",))
+REDUCER = RoleSpec("reducer", "test", ("read_input",))
+READER = RoleSpec("reader", "test", ("call",), volatile_ok=True)
+
+READ = "read the page and report findings and leads"
+LEADS = "list the lead URLs"
+REPORT = "write the report"
+
+
+def call(tool: str, **args: object) -> ToolCall:
+ return ToolCall(tool, dict(args))
+
+
+# --- fake pages and a fake engine ----------------------------------------------
+
+
+PARAGRAPHS = [
+ "Incremental computation re-evaluates a program after a change so that only "
+ "the parts affected by the change are recomputed, by recording dependencies "
+ "between inputs and outputs and checking them against what changed.",
+ "Build systems such as Make, Bazel and Shake are the classic examples: a target "
+ "is rebuilt only when one of its inputs has a newer timestamp or a different "
+ "content hash than it had the last time the target was built.",
+ "In databases, incremental view maintenance keeps a materialized view current "
+ "by applying only the rows that changed, instead of recomputing the whole query "
+ "from scratch after every write to one of its base tables.",
+ "The common thread is a dependency graph and a notion of what counts as a "
+ "change; engines differ in how they record the graph and how fine-grained the "
+ "change detection is, from whole files down to individual cells.",
+]
+
+
+def html_page(
+ title: str,
+ paragraphs: list[str],
+ *,
+ links: tuple[str, ...] = (),
+ stamp: str = "2026-11-21 07:00",
+ comments: int = 0,
+) -> str:
+ """An article with the boilerplate a real page carries: navigation, an ad with a
+ nonce, a comments section and a footer with a timestamp and a request id."""
+ body = "".join(f"<p>{p}</p>\n" for p in paragraphs)
+ see = "".join(
+ f'<p>See also <a href="{u}">{u}</a> for more on this subject.</p>'
+ for u in links
+ )
+ talk = "".join(
+ f'<div class="comment"><p>Comment {i}: nice post, thanks for sharing this '
+ "with everyone here today.</p></div>"
+ for i in range(comments)
+ )
+ return (
+ f"<!DOCTYPE html><html><head><title>{title}</title>"
+ f'<meta property="og:title" content="{title}"></head><body>'
+ '<nav><ul><li><a href="/">Home</a></li><li><a href="/about">About</a></li>'
+ '<li><a href="/blog">Blog</a></li></ul></nav>'
+ f"<header><h1>{title}</h1></header><main><article>{body}{see}</article></main>"
+ '<aside><div class="ad">Buy now! Limited offer id=4f9a</div></aside>'
+ f'<section id="comments"><h2>Comments ({comments})</h2>{talk}</section>'
+ f"<footer><p>Generated at {stamp} Β· request id 8c1e2</p><p>Β© Example Inc.</p>"
+ "</footer></body></html>"
+ )
+
+
+def article(name: str, links: tuple[str, ...] = (), **kw: object) -> str:
+ """A distinct article per name: the first paragraph names the page."""
+ paragraphs = [f"This page is about {name}. " + PARAGRAPHS[0], *PARAGRAPHS[1:]]
+ return html_page(f"Page {name}", paragraphs, links=links, **kw) # type: ignore[arg-type]
+
+
+@dataclass
+class Page:
+ body: str | bytes
+ content_type: str = "text/html"
+ etag: str | None = None
+ last_modified: str | None = None
+ status: int = 200
+ redirect: str | None = None
+
+
+@dataclass
+class FakeWeb:
+ """Pages by canonical URL, served through ``httpx.MockTransport`` with
+ conditional requests honoured, redirects, robots and status codes; every
+ request is counted."""
+
+ pages: dict[str, Page] = field(default_factory=dict)
+ robots: dict[str, str] = field(default_factory=dict) # host -> robots.txt
+ gets: Counter[str] = field(default_factory=Counter)
+ downloads: Counter[str] = field(default_factory=Counter)
+ not_modified: Counter[str] = field(default_factory=Counter)
+
+ def transport(self) -> httpx.MockTransport:
+ return httpx.MockTransport(self.handle)
+
+ def handle(self, request: httpx.Request) -> httpx.Response:
+ if request.url.path == "/robots.txt":
+ text = self.robots.get(request.url.host)
+ return (
+ httpx.Response(200, text=text)
+ if text is not None
+ else httpx.Response(404)
+ )
+ url = web.canonical_url(str(request.url))
+ assert url is not None
+ self.gets[url] += 1
+ page = self.pages.get(url)
+ if page is None:
+ return httpx.Response(404)
+ if page.redirect is not None:
+ return httpx.Response(302, headers={"location": page.redirect})
+ if page.status != 200:
+ return httpx.Response(page.status)
+ if (page.etag and request.headers.get("if-none-match") == page.etag) or (
+ page.last_modified
+ and request.headers.get("if-modified-since") == page.last_modified
+ ):
+ self.not_modified[url] += 1
+ return httpx.Response(304)
+ self.downloads[url] += 1
+ headers = {"content-type": page.content_type}
+ if page.etag:
+ headers["etag"] = page.etag
+ if page.last_modified:
+ headers["last-modified"] = page.last_modified
+ body = page.body.encode() if isinstance(page.body, str) else page.body
+ return httpx.Response(200, content=body, headers=headers)
+
+ def reset_counts(self) -> None:
+ self.gets.clear()
+ self.downloads.clear()
+ self.not_modified.clear()
+
+
+@dataclass
+class FakeEngine:
+ results: dict[str, list[str]] # query -> ranked URLs
+ identity: str = "fake:test"
+ outage: bool = False
+ calls: Counter[str] = field(default_factory=Counter)
+
+ async def search(self, query: str, k: int) -> list[web.SearchHit]:
+ if self.outage:
+ raise TransientError("search engine down")
+ self.calls[query] += 1
+ return [
+ web.SearchHit(u, u.rsplit("/", 1)[-1])
+ for u in self.results.get(query, [])[:k]
+ ]
+
+
+# --- the scripted sessions ------------------------------------------------------
+
+
+_URLS = re.compile(r"https?://[^\s)\]]+")
+
+
+@dataclass
+class Script:
+ """Shape E as the recipe prescribes, followed by every role; the orchestrator
+ reads cards as a real model would (items 0 β†’ the no-evidence report)."""
+
+ out: pathlib.Path
+ queries: list[str]
+ leads_task: str = LEADS
+ report_task: str = REPORT
+ reword_leads: bool = False # the leads reducer phrases its answer differently
+
+ def __call__(
+ self, spec: SessionSpec, prefix: Transcript, hints: RunHints
+ ) -> ModelOutput:
+ role = spec.role.name
+ if role == "orchestrator":
+ return self.orchestrate(prefix)
+ if role == "worker":
+ return self.work(prefix)
+ if role == "reducer":
+ return self.reduce(spec, prefix)
+ raise AssertionError(role)
+
+ def orchestrate(self, prefix: Transcript) -> ModelOutput:
+ n = len(prefix.steps)
+ results = [s.results for s in prefix.steps]
+ if n == 0:
+ return ModelOutput(
+ calls=(
+ call(
+ "open_source",
+ kind="web_search",
+ name="web",
+ queries=self.queries,
+ ),
+ call(
+ "open_target",
+ kind="localfs_dir",
+ name="out",
+ path=str(self.out),
+ ),
+ )
+ )
+ card = results[0][0]
+ if not card.ok:
+ return ModelOutput(answer=f"could not open the web: {card.value}")
+ if card.value["items"] == "0":
+ if n == 1:
+ return ModelOutput(
+ calls=(
+ call(
+ "declare",
+ target="tgt:out",
+ key="report.md",
+ value="# Report\n\nNo evidence could be found or fetched.\n",
+ ),
+ )
+ )
+ return ModelOutput(answer="no evidence")
+ if n == 1:
+ return ModelOutput(
+ calls=(call("for_each", source="src:web", key="pages", task=READ),)
+ )
+ if n == 2:
+ return ModelOutput(
+ calls=(
+ call(
+ "reduce",
+ collection="coll:pages",
+ key="leads",
+ task=self.leads_task,
+ ),
+ )
+ )
+ if n == 3:
+ return ModelOutput(
+ calls=(
+ call(
+ "open_source",
+ kind="web_pages",
+ name="leads",
+ urls=["res:leads"],
+ ),
+ )
+ )
+ leads_card = results[3][0]
+ has_leads = leads_card.ok and leads_card.value["items"] != "0"
+ if n == 4 and has_leads:
+ return ModelOutput(
+ calls=(call("for_each", source="src:leads", key="pages2", task=READ),)
+ )
+ step_report = 5 if has_leads else 4
+ if n == step_report:
+ collections = ["coll:pages", "coll:pages2"] if has_leads else ["coll:pages"]
+ return ModelOutput(
+ calls=(
+ call(
+ "reduce",
+ collection=collections,
+ key="report",
+ task=self.report_task,
+ ),
+ )
+ )
+ if n == step_report + 1:
+ return ModelOutput(
+ calls=(
+ call(
+ "declare", target="tgt:out", key="report.md", value="res:report"
+ ),
+ )
+ )
+ return ModelOutput(answer="report written")
+
+ def work(self, prefix: Transcript) -> ModelOutput:
+ if not prefix.steps:
+ return ModelOutput(calls=(call("read_input"),))
+ value = prefix.steps[0].results[0].value
+ if "text" not in value: # a document reference (a PDF)
+ return ModelOutput(
+ answer=f"Findings:\n- a PDF of {value['bytes']} bytes, digest "
+ f"{value['digest'][:8]} ({value['key']})\nLeads: none"
+ )
+ key, text = value["key"], value["text"]
+ body = text.split("\n\n", 1)[1] if "\n\n" in text else text
+ snippet = body.split(". ", 1)[0][:80]
+ leads = [u for u in _URLS.findall(body) if u != key][:3]
+ lines = [f"Findings:\n- {snippet} ({key})"]
+ lines.append(
+ "Leads:\n" + "\n".join(f"- {u} β€” linked from the page" for u in leads)
+ if leads
+ else "Leads: none"
+ )
+ return ModelOutput(answer="\n".join(lines))
+
+ def reduce(self, spec: SessionSpec, prefix: Transcript) -> ModelOutput:
+ if not prefix.steps:
+ return ModelOutput(calls=(call("read_input"),))
+ members: list[str] = prefix.steps[0].results[0].value
+ if spec.task == self.leads_task or spec.task.startswith(LEADS):
+ cited = {u for m in members for u in _URLS.findall(m.split("Leads", 1)[0])}
+ leads: list[str] = []
+ for m in members:
+ for line in m.split("Leads", 1)[-1].splitlines():
+ for u in _URLS.findall(line):
+ if u not in cited and u not in leads:
+ leads.append(u)
+ # The same URLs in other words of the same length, so the result's
+ # widened size does not move either.
+ why = "a link" if self.reword_leads else "a lead"
+ return ModelOutput(
+ answer="\n".join(f"{u} β€” {why}" for u in leads) or "none"
+ )
+ sources_ = sorted(
+ {u for m in members for u in _URLS.findall(m.split("Leads", 1)[0])}
+ )
+ return ModelOutput(
+ answer="# Report\n\n"
+ + "\n\n".join(members)
+ + "\n\nSources:\n"
+ + "\n".join(f"- {u}" for u in sources_)
+ )
+
+
+# --- the fixture ----------------------------------------------------------------
+
+
+@dataclass
+class Fixture:
+ env: coco.Environment
+ out: pathlib.Path
+ model: ScriptedModel
+ tools: CountingRegistry
+ web: FakeWeb
+ engine: FakeEngine
+ script: Script
+ config: AgentsConfig
+ scratch: SessionScratch = field(default_factory=SessionScratch)
+ result: SessionResult | None = None
+ _app: coco.App[..., SessionResult] | None = None
+
+ def app(self) -> coco.App[..., SessionResult]:
+ # One App per environment (a name registers once); the scratch is shared
+ # and reset per run.
+ if self._app is None:
+ self.env.context_provider.provide(AGENTS_CONFIG, self.config)
+ self._app = coco.App(
+ coco.AppConfig(name="research", environment=self.env),
+ run_open_session,
+ self.config.spec("orchestrator", "research incremental computation"),
+ scratch=self.scratch,
+ )
+ return self._app
+
+ def run(self) -> SessionResult:
+ self.model.reset()
+ self.tools.reset()
+ self.web.reset_counts()
+ self.engine.calls.clear()
+ self.scratch.ran = False
+ result = self.app().update_blocking()
+ assert isinstance(result, SessionResult)
+ self.result = result
+ return result
+
+ def calls(self, role: str) -> int:
+ return self.model.calls_for(role)
+
+ def executed(self) -> dict[str, int]:
+ return dict(self.tools.executed)
+
+ def report(self) -> str:
+ return (self.out / "report.md").read_text()
+
+ def plan(self) -> str:
+ assert self.result is not None
+ return render_plan(self.run_report())
+
+ def stats(self) -> str:
+ return render_stats_line(self.run_report())
+
+ def run_report(self) -> RunReport:
+ assert self.result is not None
+ return RunReport.from_result(
+ "research",
+ self.result.trace,
+ ran=self.scratch.ran,
+ model="scripted",
+ wall_seconds=0.0,
+ usage=None,
+ )
+
+ def switch_engine(self, engine: FakeEngine) -> None:
+ """Another engine, re-provided through the config key (its memo key names
+ the engine): the same App, a changed tracked input."""
+ web.register_engine(engine)
+ self.engine = engine
+ self.config = AgentsConfig(
+ roles=self.config.roles, tools=self.tools, search_engine=engine.identity
+ )
+ self.env.context_provider.provide(AGENTS_CONFIG, self.config)
+
+
+def setup(
+ coco_env: coco.Environment,
+ tmp_path: pathlib.Path,
+ monkeypatch: pytest.MonkeyPatch,
+ fake: FakeWeb,
+ engine: FakeEngine,
+ queries: list[str],
+ *,
+ extra_roles: tuple[RoleSpec, ...] = (),
+) -> Fixture:
+ web.set_transport(fake.transport())
+ web.register_engine(engine)
+ monkeypatch.setattr(web, "_backoff", lambda attempt: 0.0)
+ out = tmp_path / "out"
+ script = Script(out, queries)
+ model = ScriptedModel(script)
+ tools = CountingRegistry(
+ [
+ sources.open_source,
+ sources.call_method,
+ sources.read_input,
+ targets.open_target,
+ targets.declare,
+ agents.for_each,
+ agents.reduce,
+ ]
+ )
+ config = AgentsConfig(
+ roles={r.name: r for r in (ORCHESTRATOR, WORKER, REDUCER, *extra_roles)},
+ tools=tools,
+ search_engine=engine.identity,
+ )
+ coco_env.context_provider.provide(MODEL_CLIENT, model)
+ return Fixture(coco_env, out, model, tools, fake, engine, script, config)
+
+
[email protected](autouse=True)
+def _network_off() -> Iterator[None]:
+ yield
+ web.set_transport(None)
+
+
+def site(fake: FakeWeb, **pages: Page) -> None:
+ for name, page in pages.items():
+ fake.pages[f"https://example.org/{name}"] = page
+
+
+def url(name: str) -> str:
+ return f"https://example.org/{name}"
+
+
+# --- tests -----------------------------------------------------------------------
+
+
+def test_a_research_run_reuses_unchanged_pages_and_reruns_only_a_changed_one(
+ coco_env: coco.Environment, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ fake = FakeWeb()
+ site(
+ fake,
+ a=Page(article("a", links=(url("l1"), url("l2"))), etag='"a1"'),
+ b=Page(article("b", links=(url("l1"),)), etag='"b1"'),
+ c=Page(
+ article("c", links=(url("a"),)),
+ last_modified="Mon, 17 Nov 2026 10:00:00 GMT",
+ ),
+ d=Page(article("d")), # no validators: fetched and compared by digest
+ l1=Page(article("l1"), etag='"l1"'),
+ l2=Page(article("l2")),
+ )
+ engine = FakeEngine(
+ {"q1": [url("a"), url("b"), url("c")], "q2": [url("b"), url("d")]}
+ )
+ f = setup(coco_env, tmp_path, monkeypatch, fake, engine, ["q1", "q2"])
+
+ # Fresh: four pages from the searches, two leads (a is excluded: already read).
+ assert f.run().answer == "report written"
+ report = f.report()
+ for name in ("a", "b", "c", "d", "l1", "l2"):
+ assert f"({url(name)})" in report
+ assert f.calls("orchestrator") == 8
+ assert f.calls("worker") == 12 and f.calls("reducer") == 4
+ assert fake.downloads[url("b")] == 1 # one fetch, although two queries returned it
+ assert "fetched 20" in f.plan() and "example.org/a" in f.plan()
+
+ # Unchanged: no model call, no tool, one search per query and one conditional
+ # request per page by the validators (one record per source, however many
+ # observations were made through it); validators answer 304, d is
+ # re-downloaded and compared by digest.
+ f.run()
+ assert f.model.calls == 0 and f.executed() == {}
+ assert dict(engine.calls) == {"q1": 1, "q2": 1}
+ assert fake.not_modified[url("a")] == 1 and fake.not_modified[url("c")] == 1
+ assert fake.downloads[url("d")] == 1 and fake.downloads[url("a")] == 0
+ assert fake.gets[url("l1")] == 1
+ assert (f.out / "report.md").read_text() == report
+
+ # A trivial change: d's footer timestamp and a comment count; the digest of
+ # the normalized page is unchanged, so nothing runs.
+ fake.pages[url("d")] = Page(article("d", stamp="2026-11-22 09:30", comments=3))
+ f.run()
+ assert f.model.calls == 0 and f.executed() == {}
+
+ # A rotated ETag on an unchanged page (a CDN edge): the conditional request
+ # is answered 200, the digest is the same, the record refreshes its
+ # validators and the session stays skipped; the next run gets a 304 again.
+ fake.pages[url("a")] = Page(article("a", links=(url("l1"), url("l2"))), etag='"a2"')
+ f.run()
+ assert f.model.calls == 0 and f.executed() == {}
+ assert fake.downloads[url("a")] == 1
+ f.run()
+ assert f.model.calls == 0 and fake.not_modified[url("a")] == 1
+
+ # A material change to b, with a new ETag: b's worker answers again (its
+ # read_input turn hits), then the leads reducer and the report reducer.
+ fake.pages[url("b")] = Page(
+ html_page(
+ "Page b",
+ ["This page is about b, revised. " + PARAGRAPHS[0], *PARAGRAPHS[1:]],
+ links=(url("l1"),),
+ ),
+ etag='"b2"',
+ )
+ f.run()
+ assert f.calls("worker") == 1 and f.calls("reducer") == 2
+ assert f.calls("orchestrator") == 0
+ assert "about b, revised" in f.report()
+ # The validators fetched every page twice (the engine probes the root's records
+ # for its component entry and for its memoized function's entry when the body
+ # re-runs) with the refreshed validators and were answered 304; the body's
+ # response cache still held a's rotated-away ETag, so its one request was a
+ # 200 that normalized to the same digest and refreshed the cache.
+ assert fake.gets[url("a")] == 3 and fake.not_modified[url("a")] == 2
+ assert fake.downloads[url("a")] == 1
+
+
+def test_the_frontier_keeps_a_set_under_rank_jitter_and_moves_only_at_its_edges(
+ coco_env: coco.Environment, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ fake = FakeWeb()
+ names = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
+ site(fake, **{n: Page(article(n), etag=f'"{n}"') for n in names})
+ # a2 is an alias: it redirects to a.
+ fake.pages[url("a2")] = Page("", redirect=url("a"))
+ ranked = [url(n) for n in names]
+ engine = FakeEngine({"q": ranked, "q2": [url("a2"), url("b")]})
+ f = setup(coco_env, tmp_path, monkeypatch, fake, engine, ["q", "q2"])
+
+ # k = 4: the top four of q and q2's two, deduplicated by final URL β†’ a, b, c, d.
+ f.run()
+ assert f.calls("worker") == 8
+ assert fake.downloads[url("a")] == 1 and fake.gets[url("a2")] == 1
+
+ # Jitter inside the top 2k with no newcomer in a top k: the set is unchanged.
+ engine.results["q"] = [url("b"), url("a"), url("d"), url("c"), *ranked[4:]]
+ f.run()
+ assert f.model.calls == 0 and f.executed() == {}
+
+ # An incumbent (d) slides to rank 5 while e enters the top 4: d stays (it is
+ # within the top 2k), e is a newcomer with a free place β†’ one new worker.
+ engine.results["q"] = [
+ url("a"),
+ url("b"),
+ url("c"),
+ url("e"),
+ url("d"),
+ *ranked[5:],
+ ]
+ f.run()
+ assert f.calls("worker") == 2 and f.calls("reducer") == 2
+ assert f.calls("orchestrator") == 0 # 5 items are still "4–8"
+
+ # d leaves every top 2k: its worker is dropped, no worker runs, the reducers do.
+ engine.results["q"] = [
+ url("a"),
+ url("b"),
+ url("c"),
+ url("e"),
+ *ranked[5:],
+ url("d"),
+ ]
+ f.run()
+ assert f.calls("worker") == 0 and f.calls("reducer") == 2
+ assert f"({url('d')})" not in f.report()
+
+
+def test_web_pages_excludes_what_the_search_read_and_is_keyed_on_the_url_set(
+ coco_env: coco.Environment, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ fake = FakeWeb()
+ site(
+ fake,
+ f=Page(article("f", links=(url("b"), url("g1"))), etag='"f"'),
+ g1=Page(article("g1"), etag='"g1"'),
+ g=Page(article("g"), etag='"g"'),
+ )
+ fake.pages[url("a")] = Page("", redirect=url("f")) # the search reaches f through a
+ fake.pages[url("b")] = Page("", redirect=url("f")) # a lead that is an alias of f
+ engine = FakeEngine({"q": [url("a")]})
+ f = setup(coco_env, tmp_path, monkeypatch, fake, engine, ["q"])
+
+ # The lead b redirects to f, already read: suppressed after fetching; g1 is read.
+ f.run()
+ assert f.calls("worker") == 4
+ assert f.report().count(f"({url('f')})") == 1
+ assert "unavailable" not in f.plan()
+
+ # f changes materially and the leads reducer, re-run, rewords its answer
+ # around the same URLs: the page-set source's identity is the URL set, so
+ # g1's worker hits; only f's worker, the leads reducer and the report run.
+ fake.pages[url("f")] = Page(
+ html_page(
+ "Page f",
+ ["This page is about f, revised. " + PARAGRAPHS[0], *PARAGRAPHS[1:]],
+ links=(url("b"), url("g1")),
+ ),
+ etag='"f2"',
+ )
+ f.script.reword_leads = True
+ f.run()
+ assert f.calls("worker") == 1 and f.calls("reducer") == 2
+ assert f.calls("orchestrator") == 0
+
+ # The alias b now redirects to a new page g: the recorded mapping b β†’ f is
+ # stale, the listing re-runs, and g is admitted.
+ fake.pages[url("b")] = Page("", redirect=url("g"))
+ f.run()
+ assert f.calls("worker") == 2
+ assert f"({url('g')})" in f.report()
+
+
+def test_unavailable_pages_are_data_and_exhausted_transient_fetches_are_contained(
+ coco_env: coco.Environment, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(web, "PDF_CAP", 2000)
+ fake = FakeWeb()
+ fake.robots["example.org"] = "User-agent: *\nDisallow: /private/\n"
+ site(
+ fake,
+ ok=Page(article("ok"), etag='"ok"'),
+ forbidden=Page("", status=403),
+ gate=Page("", redirect="https://example.org/login?next=gate"),
+ flaky=Page("", status=503),
+ )
+ fake.pages[url("private/x")] = Page(article("x"))
+ fake.pages[url("big.pdf")] = Page(
+ b"%PDF-1.4 " + b"0" * 5000, content_type="application/pdf"
+ )
+ engine = FakeEngine(
+ {
+ "q": [
+ url("ok"),
+ url("forbidden"),
+ url("gate"),
+ url("private/x"),
+ url("big.pdf"),
+ url("flaky"),
+ url("missing"),
+ ]
+ }
+ )
+ monkeypatch.setattr(web, "K", 8)
+ f = setup(coco_env, tmp_path, monkeypatch, fake, engine, ["q"])
+
+ result = f.run()
+ assert result.answer == "report written"
+ assert f.calls("worker") == 2 # only ok was read
+ assert fake.gets[url("private/x")] == 0 # never fetched
+ plan = f.plan()
+ for reason in ("sign-in", "robots", "too-large", "transient", "not-found"):
+ assert f"Β· {reason}" in plan, reason
+ # The fan-out's failed count stays 0; the transient page is a contained failure.
+ assert result.trace.failures == ("page:" + url("flaky"),)
+ assert "re-runs next run" in f.stats()
+
+ # Still flaky: the session re-runs (the contained failure never validates), the
+ # cards are unchanged, so no model call; still contained.
+ f.run()
+ assert f.model.calls == 0 and f.executed()["open_source"] == 2
+ assert f.result is not None and f.result.trace.failures == ("page:" + url("flaky"),)
+
+ # Fixed: the page appears, its worker runs, the reducers follow, nothing
+ # failed. The item count went from 1 to 2, which crosses a bucket ("1–2" to
+ # "2–4"), so the orchestrator sees a changed card and re-infers from there.
+ fake.pages[url("flaky")] = Page(article("flaky"), etag='"flaky"')
+ f.run()
+ assert (
+ f.calls("worker") == 2
+ and f.result is not None
+ and f.result.trace.failures == ()
+ )
+ assert f.calls("orchestrator") > 0
+ assert f"({url('flaky')})" in f.report()
+
+
+def test_an_engine_outage_is_contained_in_the_body_and_invalidates_in_a_validator(
+ coco_env: coco.Environment, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ fake = FakeWeb()
+ site(fake, a=Page(article("a"), etag='"a"'))
+ engine = FakeEngine({"q": [url("a")]})
+ f = setup(coco_env, tmp_path, monkeypatch, fake, engine, ["q"])
+ f.run()
+ assert f.calls("worker") == 2
+
+ # Down during validation: the record is invalid (no exception), the body
+ # re-runs, open_source fails as an ok=False result the model reads.
+ engine.outage = True
+ result = f.run()
+ assert result.answer.startswith("could not open the web")
+ assert f.result is not None and f.result.trace.failures == ("tool:open_source",)
+
+ # Back: the body re-runs (a contained failure never validates). The run that
+ # failed mounted no worker, so the engine dropped the worker's memo with its
+ # path: the page is read again (the price of a whole-tool failure), and the
+ # report is rewritten.
+ engine.outage = False
+ result = f.run()
+ assert result.answer == "report written"
+ assert f.calls("worker") == 2
+ f.run()
+ assert f.model.calls == 0
+
+
+def test_switching_the_search_engine_reruns_the_search(
+ coco_env: coco.Environment, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ fake = FakeWeb()
+ site(fake, a=Page(article("a"), etag='"a"'), b=Page(article("b"), etag='"b"'))
+ f = setup(
+ coco_env, tmp_path, monkeypatch, fake, FakeEngine({"q": [url("a")]}), ["q"]
+ )
+ f.run()
+ assert f"({url('a')})" in f.report()
+ f.run()
+ assert f.model.calls == 0
+
+ # Another engine, same state directory: the old frontier is not reused; the
+ # new engine's page is read and the report rewritten.
+ f.switch_engine(FakeEngine({"q": [url("b")]}, identity="fake:other"))
+ f.run()
+ assert f.calls("worker") == 2
+ report = f.report()
+ assert f"({url('b')})" in report and f"({url('a')})" not in report
+
+
+def test_empty_outcomes_are_reported_honestly_and_recover(
+ coco_env: coco.Environment, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ fake = FakeWeb()
+ site(fake, a=Page(article("a"), etag='"a"')) # no links: no leads
+ engine = FakeEngine({"q": []})
+ f = setup(coco_env, tmp_path, monkeypatch, fake, engine, ["q"])
+
+ # No hit: items 0, the orchestrator declares the no-evidence report.
+ assert f.run().answer == "no evidence"
+ assert "No evidence" in f.report()
+ assert f.calls("worker") == 0
+
+ # A hit appears: the search card changes, the flow runs; a has no leads, so
+ # the page set is empty and the report is reduced from the first collection.
+ engine.results["q"] = [url("a")]
+ assert f.run().answer == "report written"
+ assert f.calls("worker") == 2 and f.calls("reducer") == 4
+ assert f"({url('a')})" in f.report()
+ f.run()
+ assert f.model.calls == 0
+
+
+def test_a_planner_reading_a_page_is_skipped_while_the_page_is_unchanged(
+ coco_env: coco.Environment, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """``read(key)`` on a web source by an open session: recorded as a page read,
+ validated by one conditional request, re-run on a content change."""
+ fake = FakeWeb()
+ site(fake, a=Page(article("a"), etag='"a1"'), b=Page(article("b")))
+ engine = FakeEngine({"q": [url("a")]})
+ reads: list[str] = []
+
+ def script(spec: SessionSpec, prefix: Transcript, hints: RunHints) -> ModelOutput:
+ n = len(prefix.steps)
+ if spec.role.name == "reader":
+ if n == 0:
+ return ModelOutput(
+ calls=(
+ call(
+ "call",
+ handle="src:web",
+ method="read",
+ args={"key": url("b")},
+ ),
+ )
+ )
+ text = prefix.steps[0].results[0].value
+ reads.append(text)
+ return ModelOutput(answer=text.split("\n\n", 1)[1][:40])
+ if n == 0:
+ return ModelOutput(
+ calls=(
+ call("open_source", kind="web_search", name="web", queries=["q"]),
+ )
+ )
+ if n == 1:
+ return ModelOutput(
+ calls=(
+ call(
+ "call_agent",
+ key="reader",
+ task="read b",
+ role="reader",
+ inputs=["src:web"],
+ ),
+ )
+ )
+ return ModelOutput(answer="done")
+
+ web.set_transport(fake.transport())
+ web.register_engine(engine)
+ monkeypatch.setattr(web, "_backoff", lambda attempt: 0.0)
+ tools = CountingRegistry(
+ [sources.open_source, sources.call_method, agents.call_agent]
+ )
+ config = AgentsConfig(
+ roles={
+ r.name: r
+ for r in (
+ RoleSpec("orchestrator", "test", ("open_source", "call_agent")),
+ READER,
+ )
+ },
+ tools=tools,
+ search_engine=engine.identity,
+ )
+ model = ScriptedModel(script)
+ coco_env.context_provider.provide(MODEL_CLIENT, model)
+ coco_env.context_provider.provide(AGENTS_CONFIG, config)
+ app = coco.App(
+ coco.AppConfig(name="reader", environment=coco_env),
+ run_open_session,
+ config.spec("orchestrator", "read one page"),
+ )
+
+ def run() -> None:
+ model.reset()
+ tools.reset()
+ fake.reset_counts()
+ app.update_blocking()
+
+ run()
+ assert model.calls_for("reader") == 2 and reads[0].startswith("# Page b\nURL: ")
+ assert fake.downloads[url("b")] == 1
+
+ # Unchanged: the page read validates by one request (b has no validators, so
+ # a download compared by digest); nothing runs.
+ run()
+ assert model.calls == 0 and tools.executed == {}
+ assert fake.downloads[url("b")] == 1
+
+ # b changes: the reader re-runs its answer turn; the orchestrator's body runs
+ # with no inference because its child's read changed.
+ fake.pages[url("b")] = Page(article("b", stamp="x", comments=2))
+ run()
+ assert model.calls == 0 and tools.executed == {} # boilerplate only: still skipped
+ fake.pages[url("b")] = Page(html_page("Page b", ["Changed. " + PARAGRAPHS[0]]))
+ run()
+ assert model.calls_for("reader") == 1 and model.calls_for("orchestrator") == 0
+
+
+def test_a_pdf_on_the_web_is_a_document(
+ coco_env: coco.Environment, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ fake = FakeWeb()
+ fake.pages[url("paper")] = Page(
+ b"%PDF-1.4 fake pdf body", content_type="application/pdf", etag='"p"'
+ )
+ f = setup(
+ coco_env, tmp_path, monkeypatch, fake, FakeEngine({"q": [url("paper")]}), ["q"]
+ )
+ f.run()
+ assert "a PDF of 22 bytes" in f.report()
+ f.run()
+ assert f.model.calls == 0
+
+
+def test_open_source_holds_each_kind_to_its_arguments_and_reduce_checks_its_collections(
+ coco_env: coco.Environment, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ fake = FakeWeb()
+ site(fake, a=Page(article("a")))
+ engine = FakeEngine({"q": [url("a")]})
+ outcomes: list[ToolResult] = []
+
+ def script(spec: SessionSpec, prefix: Transcript, hints: RunHints) -> ModelOutput:
+ n = len(prefix.steps)
+ if spec.role.name != "orchestrator":
+ return (
+ ModelOutput(calls=(call("read_input"),))
+ if n == 0
+ else ModelOutput(answer="x")
+ )
+ if n == 0:
+ return ModelOutput(
+ calls=(
+ call(
+ "open_source",
+ kind="web_search",
+ name="w1",
+ path="x",
+ queries=["q"],
+ ),
+ call("open_source", kind="web_search", name="w2"),
+ call("open_source", kind="localfs", name="d", queries=["q"]),
+ call("open_source", kind="web_pages", name="p", urls=["res:none"]),
+ call("open_source", kind="web_search", name="web", queries=["q"]),
+ )
+ )
+ if n == 1:
+ return ModelOutput(
+ calls=(call("for_each", source="src:web", key="pages", task=READ),)
+ )
+ if n == 2:
+ return ModelOutput(
+ calls=(
+ call(
+ "reduce",
+ collection=["coll:pages", "coll:pages"],
+ key="r1",
+ task=REPORT,
+ ),
+ call("reduce", collection=[], key="r2", task=REPORT),
+ call("reduce", collection="src:web", key="r3", task=REPORT),
+ call("reduce", collection=["coll:pages"], key="r4", task=REPORT),
+ )
+ )
+ outcomes.extend(prefix.steps[0].results)
+ outcomes.extend(prefix.steps[2].results)
+ return ModelOutput(answer="done")
+
+ web.set_transport(fake.transport())
+ web.register_engine(engine)
+ monkeypatch.setattr(web, "_backoff", lambda attempt: 0.0)
+ tools = CountingRegistry(
+ [
+ sources.open_source,
+ sources.read_input,
+ sources.call_method,
+ targets.open_target,
+ targets.declare,
+ agents.for_each,
+ agents.reduce,
+ ]
+ )
+ config = AgentsConfig(
+ roles={r.name: r for r in (ORCHESTRATOR, WORKER, REDUCER)},
+ tools=tools,
+ search_engine=engine.identity,
+ )
+ coco_env.context_provider.provide(MODEL_CLIENT, ScriptedModel(script))
+ coco_env.context_provider.provide(AGENTS_CONFIG, config)
+ app = coco.App(
+ coco.AppConfig(name="args", environment=coco_env),
+ run_open_session,
+ config.spec("orchestrator", "check arguments"),
+ )
+ result = app.update_blocking()
+ assert isinstance(result, SessionResult) and result.answer == "done"
+ texts = [(r.ok, str(r.value)) for r in outcomes]
+ assert texts[0] == (
+ False,
+ "web_search does not take ['path']; it takes ['queries']",
+ ), texts
+ assert texts[1] == (False, "web_search needs ['queries']; it takes ['queries']")
+ assert texts[2] == (
+ False,
+ "localfs needs ['path'] and does not take ['queries']; it takes ['path', 'patterns']",
+ )
+ assert texts[3][0] is False and "unknown handle 'res:none'" in texts[3][1]
+ assert texts[4][0] is True
+ assert texts[5] == (False, "reduce lists the same collection twice")
+ assert texts[6] == (
+ False,
+ "reduce needs a coll: handle or a non-empty list of them",
+ )
+ assert texts[7] == (False, "'src:web' is a web_search handle, not a collection")
+ assert texts[8][0] is True
+
+
+# --- the normalizer, per page type -----------------------------------------------
+
+
+def _digest(html: str, url_: str = "https://example.org/page") -> str:
+ return web.normalize(
+ web.Fetched(url_, 200, web.Validators(), "text/html", html.encode())
+ ).digest()
+
+
+def test_the_normalizer_keeps_content_edits_and_drops_boilerplate_edits_per_page_type() -> (
+ None
+):
+ # An article: the fixture above.
+ base = article("x", links=(url("y"),))
+ assert _digest(base) == _digest(
+ article("x", links=(url("y"),), stamp="2027-01-01", comments=5)
+ )
+ assert _digest(base) != _digest(
+ html_page(
+ "Page x",
+ ["This page is about x, changed. " + PARAGRAPHS[0], *PARAGRAPHS[1:]],
+ )
+ )
+
+ # A documentation page: a sidebar of links, a code block, a version footer.
+ def docs(body_note: str, version: str) -> str:
+ side = "".join(
+ f'<li><a href="/docs/{i}">Section {i}</a></li>' for i in range(30)
+ )
+ return (
+ "<html><head><title>Docs</title></head><body>"
+ f'<nav class="sidebar"><ul>{side}</ul></nav><main>'
+ f"<h1>Using the thing</h1><p>{PARAGRAPHS[0]} {body_note}</p>"
+ f"<pre><code>thing --update ./docs</code></pre><p>{PARAGRAPHS[1]}</p></main>"
+ f"<footer>Built with docs-tool {version} at 2026-11-21T07:00Z</footer></body></html>"
+ )
+
+ assert _digest(docs("", "1.0")) == _digest(docs("", "1.1"))
+ assert _digest(docs("", "1.0")) != _digest(
+ docs("Now with a new paragraph of guidance.", "1.0")
+ )
+
+ # An encyclopedia article: an infobox table, references, a last-edited line.
+ def wiki(extra: str, edited: str) -> str:
+ return (
+ "<html><head><title>Incremental computing</title></head><body>"
+ '<div id="mw-navigation"><a href="/wiki/Main_Page">Main page</a> <a href="/wiki/Random">Random</a></div>'
+ f'<div id="content"><h1>Incremental computing</h1><table class="infobox"><tr><th>Paradigm</th><td>Reactive</td></tr></table>'
+ f"<p>{PARAGRAPHS[0]}</p><p>{PARAGRAPHS[3]} {extra}</p>"
+ f'<h2>References</h2><ol><li><a href="https://example.org/ref1">A paper</a></li></ol></div>'
+ f'<div id="footer">This page was last edited on {edited}.</div></body></html>'
+ )
+
+ assert _digest(wiki("", "21 November 2026")) == _digest(
+ wiki("", "22 November 2026")
+ )
+ assert _digest(wiki("", "x")) != _digest(wiki("A new sentence of content.", "x"))
+
+ # Plain text and Markdown are themselves.
+ def text(body: str) -> str:
+ return web.normalize(
+ web.Fetched(
+ "https://example.org/t.md",
+ 200,
+ web.Validators(),
+ "text/markdown",
+ body.encode(),
+ )
+ ).digest()
+
+ assert text("# T\n\nbody") == text("# T\n\nbody\n") and text("# T\n\nbody") != text(
+ "# T\n\nbody two"
+ )
+
+ # A repository page is an accepted limitation: the extractor returns the
+ # sidebar-like parts deterministically; whether a README edit changes the
+ # digest is not guaranteed and not asserted.
+ def repo(readme: str) -> str:
+ files = "".join(
+ f'<tr><td><a href="/x/blob/f{i}">file{i}.py</a></td><td>fix things</td><td>2 days ago</td></tr>'
+ for i in range(20)
+ )
+ return (
+ "<html><head><title>x/repo</title></head><body>"
+ f'<nav><a href="/">Code</a><a href="/issues">Issues</a><a href="/pulls">Pull requests</a></nav>'
+ f"<table>{files}</table><article><p>{readme}</p></article>"
+ "<aside><h2>About</h2><p>No description</p><p>Stars 12</p></aside></body></html>"
+ )
+
+ assert _digest(repo(PARAGRAPHS[0])) == _digest(repo(PARAGRAPHS[0]))
+
+
+def test_frontier_rule_examples() -> None:
+ results = {"q": ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]}
+ assert web.frontier([], results, 4, 12) == ["a", "b", "c", "d"]
+ # Incumbents stay while within the top 2k, newcomers come from the top k.
+ assert web.frontier(
+ ["d", "h"], {"q": ["a", "b", "c", "e", "d", "f", "g", "h"]}, 4, 12
+ ) == [
+ "d",
+ "h",
+ "a",
+ "b",
+ "c",
+ "e",
+ ]
+ # Rank order then URL; the budget cuts.
+ assert web.frontier([], {"q": ["b", "a"], "r": ["a", "c"]}, 4, 2) == ["a", "b"]
+ # An incumbent that left every top 2k is gone.
+ assert web.frontier(["z"], results, 4, 12) == ["a", "b", "c", "d"]
+
+
+def test_canonical_urls_and_urls_in_text() -> None:
+ assert web.canonical_url(
+ "HTTPS://Example.org:443/a/b?utm_source=x&b=2&a=1#frag"
+ ) == ("https://example.org/a/b?a=1&b=2")
+ assert web.canonical_url("http://example.org:8080/") == "http://example.org:8080/"
+ assert web.canonical_url("ftp://example.org/x") is None
+ assert web.canonical_url("not a url") is None
+ assert web.urls_in(
+ "see https://example.org/a β€” and (https://example.org/b). https://example.org/a"
+ ) == [
+ "https://example.org/a",
+ "https://example.org/b",
+ ]