senado-br-mcp 3.27.0 → 3.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -14,7 +14,7 @@
14
14
  [![License: MIT](https://img.shields.io/github/license/SidneyBissoli/senado-br-mcp-cloudflare)](LICENSE)
15
15
  [![Status](https://img.shields.io/website?url=https%3A%2F%2Fsenado.sidneybissoli.com%2Fhealth&up_message=online&down_message=offline&label=status)](https://senado.sidneybissoli.com/status)
16
16
 
17
- 🇧🇷 [Leia em Português](LEIA-ME.md)
17
+ 🇧🇷 [Leia em Português](https://github.com/SidneyBissoli/senado-br-mcp-cloudflare/blob/master/LEIA-ME.md)
18
18
 
19
19
  A **public, hosted** MCP server that gives AI assistants live, structured access to **Brazilian Senate open data** — **no installation, no account, no API key**. Point your MCP client at the hosted endpoint and start asking about senators, bills, votes, expenses, and more. It runs on Cloudflare Workers over Streamable HTTP.
20
20
 
@@ -24,6 +24,7 @@ It exposes **69 tools**, **4 prompts**, and **5 resources** across two domains:
24
24
  - **Administrative** — CEAPS parliamentary-quota expenses; housing allowance; civil servants and payroll; overtime; interns; procurement contracts and biddings; outsourced staff; petty-cash funds; and budget execution.
25
25
 
26
26
  Data comes from three official sources — the [legislative open-data API](https://legis.senado.leg.br/dadosabertos/), the [administrative open-data API](https://adm.senado.gov.br/adm-dadosabertos/swagger-ui/index.html), and the e-Cidadania portal. All tool responses are in Portuguese (pt-BR). See [CHANGELOG.md](CHANGELOG.md) for release history.
27
+ > **Independent project.** This is an unofficial, community-built client of the Brazilian Federal Senate's public data (open-data APIs and the e-Cidadania portal). It is not affiliated with or endorsed by the Senado Federal; the data is the Senate's, served as published.
27
28
 
28
29
  ## See it in action
29
30
 
@@ -164,7 +165,7 @@ Claude Code auto-discovers it when you work in this repo. To use it elsewhere, c
164
165
  - **SDK:** `@modelcontextprotocol/server` 2.x (per-request McpServer instances; the v1 `@modelcontextprotocol/sdk` is not installed — `agents` still lists it as a peer, satisfied via `legacy-peer-deps`)
165
166
  - **Validation:** Zod schemas for all tool inputs
166
167
  - **Caching:** 2-layer (L0 memory + L1 Cache API) with SHA-256 keying
167
- - **e-Cidadania store:** D1 database — since 3.26.0 every e-Cidadania tool reads the daily copy of the dataset (layer 3, `c3_*` tables) with per-block origin and collection instant; the corpus (refreshed daily + 2h Cron) answers only for items not yet in the copy, and the live scrape only when neither has them (see [e-Cidadania](#e-cidadania-d1-backed-cron-refreshed))
168
+ - **e-Cidadania store:** D1 database — every e-Cidadania tool reads the daily copy of the dataset (layer 3, `c3_*` tables) with per-block origin and collection instant; the corpus (refreshed daily + 2h Cron) answers only for items not yet in the copy, and the live scrape only when neither has them (see [e-Cidadania](#e-cidadania-d1-backed-cron-refreshed))
168
169
  - **Rate limiting:** Token bucket — global (8 req/s) + per-client (2 req/s)
169
170
  - **Upstream throttle:** Max 6 concurrent requests, 10s budget per trip, retry on 429/5xx/network with exponential backoff and `Retry-After` (portfolio shared fetch `@sbissoli/mcp-upstream`); every response's provenance carries the measured `retrieval` diagnostics (trips, attempts, anomalies)
170
171
  - **Auth:** Optional Bearer token (set the `API_KEY` secret; open access when unset). Constant-time comparison.
@@ -470,11 +471,11 @@ Used by Groups O, P, Q, R via `admFetch` (no `.json` suffix; HTTP 404 treated as
470
471
 
471
472
  ### e-Cidadania (D1-backed, Cron-refreshed)
472
473
 
473
- The e-Cidadania **list** data is persisted in a **D1 database** (`ecidadania_current/_history/_scrape_runs`, discriminated by `entidade`; plus `ecidadania_comentarios` for the audiência comment level and `ecidadania_detalhe_cursor` for the resumable detail backfill — added in schema v2) and read from there instead of being scraped on every call. **Three cadences** write into it:
474
+ The e-Cidadania **list** data is persisted in a **D1 database** (`ecidadania_current/_history/_scrape_runs`, discriminated by `entidade`; plus `ecidadania_comentarios` for the audiência comment level and `ecidadania_detalhe_cursor` for the resumable detail backfill) and read from there instead of being scraped on every call. **Three cadences** write into it:
474
475
 
475
- - a **daily off-Worker GitHub Action** owns the **full corpus** of the three live entities (`consultas`, `eventos`, `ideias`; see below) — the source of truth. Daily (not weekly) because the first-seen series `MIN(scraped_at)` is the only measurable entry-rhythm signal and every skipped day permanently shortens it (ROADMAP Etapa 2, decisão D3);
476
- - a **weekly ingest Action** (`.github/workflows/verify-consultas-votos.yml` — historical filename) for the `consultas_votos` acervo: the Senado republishes the Arquimedes CSV periodically (confirmed 2026-07-20), so the weekly run re-ingests the current vintage under the same anomaly guards as the other corpora (see below);
477
- - an in-Worker **Cron Trigger** (`0 */2 * * *`, `src/scraper/pipeline.ts → refreshEcidadania`) does only a **targeted metric splice** of the ~5 REST highlights per live entity (`restcolecaomaismateria/ideia/audiencia` — votos/comentários/apoios), recorded as `ok-metrica` so it never re-breaks the corpus baseline and never touches the long tail. In v2 the eventos splice **preserves** the corpus's canonical comment count (the daily crawl is the source of truth for `comentarios`, so the splice can't ping-pong it against the degraded REST count).
476
+ - **daily off-Worker GitHub Actions** (`.github/workflows/ingest-ecidadania-*.yml`, one per entity) own the **full corpus** of the three live entities (`consultas`, `eventos`, `ideias`; see below) — the source of truth. Daily because the first-seen series `MIN(scraped_at)` is the only measurable entry-rhythm signal and every skipped day permanently shortens it;
477
+ - a **weekly ingest Action** (`.github/workflows/verify-consultas-votos.yml`) for the `consultas_votos` acervo: the Senado republishes the Arquimedes CSV periodically, so the weekly run re-ingests the current vintage under the same anomaly guards as the other corpora (see below);
478
+ - an in-Worker **Cron Trigger** (`0 */2 * * *`, `src/scraper/pipeline.ts → refreshEcidadania`) does only a **targeted metric splice** of the ~5 REST highlights per live entity (`restcolecaomaismateria/ideia/audiencia` — votos/comentários/apoios), recorded as `ok-metrica` so it never re-breaks the corpus baseline and never touches the long tail. The eventos splice **preserves** the corpus's canonical comment count (the daily crawl is the source of truth for `comentarios`, so the splice can't ping-pong it against the degraded REST count).
478
479
 
479
480
  Both writers build payloads through the canonical `buildXResumo` builders + shared `contentHash`, so their rows are byte-identical. Each write:
480
481
 
@@ -484,29 +485,29 @@ Both writers build payloads through the canonical `buildXResumo` builders + shar
484
485
 
485
486
  An **anomaly guard** (`src/scraper/anomaly.ts`, `classifyRun`) ensures a failed or anomalous corpus run (zero rows, or fewer than `ECIDADANIA_CORPUS_MIN_PCT`% of the last good run) **never overwrites** the last good state.
486
487
 
487
- The **list / analysis tools** (`listar_*`, `consultas_analise`, `sugerir_tema_enquete`, `consultas_votos`) read from D1 via `resolveList` (`src/scraper/store.ts`): D1-first. Because every entity is now a full corpus, a stale corpus is served from D1 **flagged** (`possivelDesatualizacao: true`) rather than collapsing to the ~5-item live highlights (the original coverage bug); the live scrape is reserved for an empty D1 (cold start, before the first weekly run). Staleness uses `ECIDADANIA_CORPUS_STALE_MAX_MIN` (~10 days). Every list response carries an additive `meta` (`fonte`, `lastScrapedAt`, `possivelDesatualizacao`) so callers always see the data's real age and never get stale data silently.
488
+ The **list / analysis tools** (`listar_*`, `consultas_analise`, `sugerir_tema_enquete`, `consultas_votos`) read from D1 via `resolveList` (`src/scraper/store.ts`): D1-first. Because every entity is a full corpus, a stale corpus is served from D1 **flagged** (`possivelDesatualizacao: true`) rather than collapsing to the ~5-item live highlights; the live scrape is reserved for an empty D1 (cold start, before the first run). Staleness uses `ECIDADANIA_CORPUS_STALE_MAX_MIN` (~10 days). Every list response carries an additive `meta` (`fonte`, `lastScrapedAt`, `possivelDesatualizacao`) so callers always see the data's real age and never get stale data silently.
488
489
 
489
490
  The **detail tools** (`obter_*`) stay **live** (HTML scraped with CSS-class-targeted regex) for freshness, and write their richer payload through to `ecidadania_detalhe` fire-and-forget (deduped by `content_hash`), so detail history accrues without adding latency to the response.
490
491
 
491
- **Since 3.26.0 (ROADMAP D3) the tools read layer 3 first.** The daily observations job (`observacoes-ecidadania.yml`) projects the published dataset tables it builds (`scripts/publicacao/`) into D1 as `c3_*` tables (`scripts/publicacao/projetar-d1.ts`; names in `src/scraper/camada3-tabelas.ts`; DDL generated from the 3.0.0 dictionary), writing only the rows that changed since the last applied projection (a key × hash snapshot kept in the private bucket). `src/scraper/camada3.ts` reads them: lists filter/sort/page in SQL, `obter_ideia` adds `serieApoios` and `situacaoNoTempo`, `obter_consulta` adds `serieVotos` (change points only, capped at 60 with a cut notice), and every item says where and when each page block came from (`origem…`/`coletadoEm…`, the dictionary names). Items not yet in layer 3 come from the corpus (marked `corpus`); `obter_*` of an item in neither falls back to the live path above. Without the `c3_*` tables (stdio channel, cold D1) every tool behaves as described above.
492
+ **The tools read layer 3 first.** The daily observations job (`observacoes-ecidadania.yml`) projects the published dataset tables it builds (`scripts/publicacao/`) into D1 as `c3_*` tables (`scripts/publicacao/projetar-d1.ts`; names in `src/scraper/camada3-tabelas.ts`; DDL generated from the dataset dictionary), writing only the rows that changed since the last applied projection (a key × hash snapshot kept in the private bucket). `src/scraper/camada3.ts` reads them: lists filter/sort/page in SQL, `obter_ideia` adds `serieApoios` and `situacaoNoTempo`, `obter_consulta` adds `serieVotos` (change points only, capped at 60 with a cut notice), and every item says where and when each page block came from (`origem…`/`coletadoEm…`, the dictionary names). Items not yet in layer 3 come from the corpus (marked `corpus`); `obter_*` of an item in neither falls back to the live path above. Without the `c3_*` tables (stdio channel, cold D1) every tool behaves as described above.
492
493
 
493
- **Since 3.27.0 (ROADMAP E1) `obter_consulta` and `obter_ideia` also return `materiasOficiais`:** the official bill each item is tied to (Senate `codigoMateria` or Chamber proposition id — the consultation id already is the bill code; an idea's proposition is read from the link the portal publishes, never by name), its identification, the reading status at the official source, and the authors with their role (`iniciativa` = who introduced it, `texto` = author of the text under consideration, `camara` = Chamber), `codigoParlamentar` (follow with `senado_obter_senador`) or `idDeputado`. Read from `c3_vinculos_materias` / `c3_vinculos_autores` (dataset tables `vinculos/materias` and `vinculos/autores`, built from the official API responses the `autoria` job archives daily); D1 keeps only what the tools show (no links of the per-UF vote archive). Without those tables the field is absent.
494
+ **`obter_consulta` and `obter_ideia` also return `materiasOficiais`:** the official bill each item is tied to (Senate `codigoMateria` or Chamber proposition id — the consultation id already is the bill code; an idea's proposition is read from the link the portal publishes, never by name), its identification, the reading status at the official source, and the authors with their role (`iniciativa` = who introduced it, `texto` = author of the text under consideration, `camara` = Chamber), `codigoParlamentar` (follow with `senado_obter_senador`) or `idDeputado`. Read from `c3_vinculos_materias` / `c3_vinculos_autores` (dataset tables `vinculos/materias` and `vinculos/autores`, built from the official API responses the `autoria` job archives daily); D1 keeps only what the tools show (no links of the per-UF vote archive). Without those tables the field is absent.
494
495
 
495
496
  #### Full-corpus ingestion (off-Worker)
496
497
 
497
- The three live e-Cidadania corpora are owned by the **daily** Action (`.github/workflows/ingest-ecidadania.yml`), each with its own `scripts/ingest-ecidadania/index-*.ts` orchestrator emitting batched `out-*.sql` the apply step bulk-loads:
498
+ The three live e-Cidadania corpora are owned by **daily** Actions (`.github/workflows/ingest-ecidadania-*.yml`), each with its own `scripts/ingest-ecidadania/index-*.ts` orchestrator emitting batched `out-*.sql` the apply step loads:
498
499
 
499
- - **`consultas`** — open consultations (detailed below). In v2 each crawled matter is also **enriched from its detail page** (`visualizacaomateria`) for `autoria`/`relator`; those are immutable, so only rows not yet enriched are fetched.
500
- - **`eventos`** — audiências/eventos from the `principalaudiencia?p=N` HTML listing; status comes straight from the listing block (no `/processo` bridge). In v2 every event is **enriched from its detail page** (canonical `data`/`hora` + `comissaoNomeCompleto`/`local`/`descricao`/`pauta`/`convidados`/`videoUrl`) and its **AJAX comment fragment** (canonical count + one `ecidadania_comentarios` row per comment, diffed against the stored hashes and emitted as `out-eventos-comentarios-*.sql`).
501
- - **`ideias`** — ideias legislativas (~113.7k) from `pesquisaideia?situacao=N&p=M`, crawled **per `situacao` bucket** (the listing has no inline status) and emitted in ~10k-statement batches. In v2 the listing crawl **preserves** the immutable detail fields, and a **separate resumable backfill** (`index-ideias-detalhe.ts`, run via `ingest:ecidadania:ideias-detalhe`) fills them a chunk per run — because ~113.7k detail fetches don't fit one Action, it persists a cursor in `ecidadania_detalhe_cursor` and wraps around at the end.
500
+ - **`consultas`** — open consultations (detailed below). Each crawled matter is also **enriched from its detail page** (`visualizacaomateria`) for `autoria`/`relator`; those are immutable, so only rows not yet enriched are fetched.
501
+ - **`eventos`** — audiências/eventos from the `principalaudiencia?p=N` HTML listing; status comes straight from the listing block (no `/processo` bridge). Every event is **enriched from its detail page** (canonical `data`/`hora` + `comissaoNomeCompleto`/`local`/`descricao`/`pauta`/`convidados`/`videoUrl`) and its **AJAX comment fragment** (canonical count + one `ecidadania_comentarios` row per comment, diffed against the stored hashes and emitted as `out-eventos-comentarios-*.sql`).
502
+ - **`ideias`** — ideias legislativas (~113.7k) from `pesquisaideia?situacao=N&p=M`, crawled **per `situacao` bucket** (the listing has no inline status) and emitted in ~10k-statement batches. The listing crawl **preserves** the immutable detail fields, and a **separate resumable backfill** (`index-ideias-detalhe.ts`, run via `ingest:ecidadania:ideias-detalhe`) fills them a chunk per run — because ~113.7k detail fetches don't fit one Action, it persists a cursor in `ecidadania_detalhe_cursor` and wraps around at the end.
502
503
 
503
- The fourth entity, **`consultas_votos`**, is a separate **historical** acervo of votes-by-UF parsed from the ~33 MB Arquimedes CSV (`Proposições-com-votos.csv`), aggregated to one record per matéria with a `votosPorUf` breakdown. The CSV's "dados atualizados até" stamp becomes the provenance `data_vintage`; it is excluded from the row hash (`consultaVotoCore`) so a re-ingest with unchanged votes doesn't churn `_history`. `STATUS ATUAL` is uniformly "Descontinuado", hence archival, not a migration of the open consultations. Served by `senado_ecidadania_consultas_votos` with provenance pointing at the CSV (`ECIDADANIA_ARQUIMEDES`). It is **excluded from the daily job** and owned by its own **weekly ingest** Action (`.github/workflows/verify-consultas-votos.yml` — the filename keeps the historical `verify-` prefix): the acervo was originally treated as a frozen single vintage (ROADMAP Etapa 2, decisão D1) and the weekly run only *verified* it, but on 2026-07-20 the Senado republished the CSV as a fresh vintage (+43 matérias, 648 updated), so the scheduled run now re-ingests the current vintage under the standard anomaly guards (empty/truncated CSV and the catastrophic floor still fail without writing; `force` dispatch overrides the floor). The script's verify mode (`INGEST_CONSULTAS_VOTOS_VERIFY=1` / `--verify`) remains available as an on-demand integrity check.
504
+ The fourth entity, **`consultas_votos`**, is a separate **historical** acervo of votes-by-UF parsed from the ~33 MB Arquimedes CSV (`Proposições-com-votos.csv`), aggregated to one record per matéria with a `votosPorUf` breakdown. The CSV's "dados atualizados até" stamp becomes the provenance `data_vintage`; it is excluded from the row hash (`consultaVotoCore`) so a re-ingest with unchanged votes doesn't churn `_history`. `STATUS ATUAL` is uniformly "Descontinuado", hence archival, not a migration of the open consultations. Served by `senado_ecidadania_consultas_votos` with provenance pointing at the CSV (`ECIDADANIA_ARQUIMEDES`). It is **excluded from the daily jobs** and owned by its own **weekly ingest** Action (`.github/workflows/verify-consultas-votos.yml`): the Senado republishes the CSV as a fresh vintage from time to time, so the scheduled run re-ingests the current vintage under the standard anomaly guards (empty/truncated CSV and the catastrophic floor still fail without writing; `force` dispatch overrides the floor). The script's verify mode (`INGEST_CONSULTAS_VOTOS_VERIFY=1` / `--verify`) remains available as an on-demand integrity check.
504
505
 
505
506
  The `consultas` job is the reference implementation:
506
507
 
507
- `consultas` covers the **full set of OPEN consultations** — every matter currently in tramitação (~7.7k), not just the ~5 highlights. Confirmed on the first run: the `pesquisamateria` listing is **in-tramitação-only**, so closed/historical consultations are **not** captured by this source (a pre-ingestion historical backfill is out of scope). Three settled design decisions:
508
+ `consultas` covers the **full set of OPEN consultations** — every matter currently in tramitação (~7.7k), not just the ~5 highlights. The `pesquisamateria` listing is **in-tramitação-only**, so closed/historical consultations are **not** captured by this source (a pre-ingestion historical backfill is out of scope). Three design decisions:
508
509
 
509
- 1. **Decoupled ingestion.** The open set is acquired by an **off-Worker TypeScript job** (`scripts/ingest-ecidadania/`, run by a daily GitHub Action — `.github/workflows/ingest-ecidadania.yml`) that paginates the HTML listing (`pesquisamateria?p=1..N`, the only full-coverage source for open consultations) for ids + vote counts and **bulk-loads D1**; the Worker only reads. The brittle, long crawl is kept out of the request/Cron path.
510
+ 1. **Decoupled ingestion.** The open set is acquired by an **off-Worker TypeScript job** (`scripts/ingest-ecidadania/`, run by a daily GitHub Action — `.github/workflows/ingest-ecidadania-consultas.yml`) that paginates the HTML listing (`pesquisamateria?p=1..N`, the only full-coverage source for open consultations) for ids + vote counts and **loads D1**; the Worker only reads. The brittle, long crawl is kept out of the request/Cron path.
510
511
  2. **Status from `/processo`, not HTML.** A consultation runs from presentation until the end of tramitação, so `status` is a function of the matter: **aberta ⟺ the `codigoMateria` is in the `/processo` `tramitando=S` set**, derived from robust JSON (never scraped). Every consultation enters as `aberta` (the listing only yields in-tramitação matters); on each **complete** run the job re-derives status for **all stored rows** by `/processo` membership (not by listing-absence, which can be transient), so a consultation whose matter leaves tramitação flips to `encerrada`. The `encerrada`/`todas` sets therefore grow over time; consultations that closed **before** the first ingestion aren't captured (out of scope). The list/analysis tools default to `status: aberta`.
511
512
  3. **Two reconciled cadences (one shared writer contract).** The job **reuses** `contentHash` + the `ConsultaResumo` builder + `classifyRun` from `src/scraper/`, so its rows are byte-identical to the Cron's. The daily job owns the long tail; the **2h Cron** keeps the ~5 hot/open highlights fresh via a *targeted metric splice* (recorded as `ok-metrica`, bypassing the corpus `classifyRun` baseline). Corpus freshness (`possivelDesatualizacao`) is computed from the last `status='ok'` run and uses a larger window (`ECIDADANIA_CORPUS_STALE_MAX_MIN`), and a stale consultas corpus is served from D1 flagged rather than collapsing back to the live highlights.
512
513
 
@@ -514,7 +515,7 @@ Write guards on the load: an **incomplete crawl** (any page failed) or an incomp
514
515
 
515
516
  ```bash
516
517
  CLOUDFLARE_API_TOKEN=… npm run ingest:ecidadania # writes scripts/ingest-ecidadania/out.sql
517
- npx wrangler d1 execute senado-ecidadania --remote --file=scripts/ingest-ecidadania/out.sql
518
+ scripts/apply-d1.sh scripts/ingest-ecidadania/out.sql
518
519
  ```
519
520
 
520
521
  ## Caching
@@ -557,19 +558,19 @@ Coverage spans all four upstream sources, each with its own `source`/`citation`/
557
558
  - **Senado Federal — Execução Orçamentária e Financeira** — Arquimedes/Financeiro feed at `senado.gov.br`
558
559
  - **Senado Federal — Portal e-Cidadania** — `www12.senado.leg.br/ecidadania`
559
560
 
560
- Fields of the `concise` block (contract v1.3 since 3.18.5; per response — one tool, one source; keys in this fixed order; the first seven are always present, with `null` when the source does not expose the value; the optional ones are **absent**, never empty, when they do not apply):
561
+ Fields of the `concise` block (contract v1.3; per response — one tool, one source; keys in this fixed order; the first seven are always present, with `null` when the source does not expose the value; the optional ones are **absent**, never empty, when they do not apply):
561
562
 
562
563
  | Field | Meaning |
563
564
  |-------|---------|
564
565
  | `source` | Official source name (e.g. *Senado Federal — Dados Abertos (Legislativo)*) |
565
566
  | `source_url` | Canonical endpoint/item URL consulted (e.g. `…/processo/{id}`) |
566
- | `data_vintage` | Vintage/competência of the data (e.g. `2024-03-15`, `2019`) — named `reference_period` before v3.5.0 |
567
+ | `data_vintage` | Vintage/competência of the data (e.g. `2024-03-15`, `2019`) |
567
568
  | `retrieved_at` | ISO-8601 of the **upstream extraction** — carried through the cache, so it reflects when the data was actually fetched, not the build or the cache-hit time; on merged responses, the oldest of the parts |
568
- | `retrieval` | Measured diagnostics of the trip to the source (attempts, outcome), or `null` when nothing was fetched in the call (pure cache, local data) — since 3.11.0 (v1.1) |
569
+ | `retrieval` | Measured diagnostics of the trip to the source (attempts, outcome), or `null` when nothing was fetched in the call (pure cache, local data) |
569
570
  | `citation` | Ready-to-use citation string (human-readable) |
570
571
  | `license` | Source terms (Dados Abertos do Senado Federal) |
571
- | `field_sources` | *Optional.* Per-field sub-sources, each with its own extraction instant — only on responses that merge reads (v1.2, since 3.17.0; see below) |
572
- | `derived` / `derivation_note` | *Optional.* `true` + a fixed pt-BR note naming the calculation whenever the server computed values instead of copying them (since 3.19.0, the whole class): the `estatisticas` modes (distribution, aggregates, rankings); group sums, counts and averages — CEAPS `valorTotal` and its per-senator/type/month/supplier modes, the budget execution aggregates (`por-ano`, the default, included), the payroll `resumo`, the overtime `valorTotal`, the `relatoria` distribution, seated senators per party/UF, the historical e-Cidadania national totals; the payroll gross (`bruto`, sum of seven components); servants assigned to an org subtree (`subordinadasA`); a vote tally counted from nominal votes when the source publishes none (plenary open roll calls, committee votes without totals); e-Cidadania percentages, consensus/polarisation rankings and the estimated idea creation date; the current legislature's period. Absent when every number is the source's own (raw lists, `detalhe` of the budget, published tallies). The individual values cited remain the Senate's |
572
+ | `field_sources` | *Optional.* Per-field sub-sources, each with its own extraction instant — only on responses that merge reads (see below) |
573
+ | `derived` / `derivation_note` | *Optional.* `true` + a fixed pt-BR note naming the calculation whenever the server computed values instead of copying them: the `estatisticas` modes (distribution, aggregates, rankings); group sums, counts and averages — CEAPS `valorTotal` and its per-senator/type/month/supplier modes, the budget execution aggregates (`por-ano`, the default, included), the payroll `resumo`, the overtime `valorTotal`, the `relatoria` distribution, seated senators per party/UF, the historical e-Cidadania national totals; the payroll gross (`bruto`, sum of seven components); servants assigned to an org subtree (`subordinadasA`); a vote tally counted from nominal votes when the source publishes none (plenary open roll calls, committee votes without totals); e-Cidadania percentages, consensus/polarisation rankings and the estimated idea creation date; the current legislature's period. Absent when every number is the source's own (raw lists, `detalhe` of the budget, published tallies). The individual values cited remain the Senate's |
573
574
  | `revision` | Whether the figure may still change at the source: `status` is `current` for every Senate source (the version in force at extraction; none is claimed `final`), and `note` says, for the administrative and budget sources, that the Senate may correct published data later |
574
575
 
575
576
  No Senate source publishes notices alongside the data, so `notices` (also part of v1.3) does not appear. The text footer gains a line only for exceptions — here, the computed-values line on the `estatisticas` modes.
@@ -580,9 +581,9 @@ In addition to the `provenance` envelope, `structuredContent` carries a top-leve
580
581
 
581
582
  **Out-of-band mirror in `_meta`.** The same `provenance` and `attribution` are also mirrored on the result's `_meta` under namespaced keys (`com.sidneybissoli.senado/provenance` and `com.sidneybissoli.senado/attribution`). The MCP spec keeps `_meta` for metadata *about* a result that should not steer the model, which is where the still-incubating trust/attribution work from #711 (split into an experimental extensions track, not yet in core) points; mirroring there gives audit and UI consumers the provenance without reading the model-facing data channel, at no model-token cost, while `structuredContent` keeps it visible so the model can cite the source. The mirror survives the ChatGPT-app profile minimizer (which only strips `structuredContent.meta`).
582
583
 
583
- **Field-level granularity.** Most tools are single-source, so one envelope suffices. The few that merge reads in one response fill `field_sources` — a list of `{ fields, source_url, dataset_id, data_vintage, retrieved_at, served_from_cache }` attributing specific output fields to their real origin, and the block's `retrieved_at` is the oldest of them. `served_from_cache` is `true`/`false` for reads through the server cache and `null` where the notion does not apply (the bundled org-chart snapshot, the e-Cidadania corpus in D1). The merging tools (since 3.18.2): `senado_obter_materia` `secao=detalhe` (`/processo/{id}` + `ementa` from `/processo` + `relator` from `/processo/relatoria`), `senado_obter_senador` and the Deep Research `fetch` of a senator (biography + `mandatos`/`emExercicio` from `/senador/{codigo}/mandatos`), `senado_servidores` with `subordinadasA` (payroll + org-chart snapshot), `senado_suprimento_fundos` statistics on `atos-concessao` (acts + beneficiary names from the supridos registry), `senado_ecidadania_obter_evento` (live detail + `comentarios` from the corpus), `senado_listar_senadores` with `legislatura` (since 3.24.0: the legislature list + `emExercicio` from `/senador/lista/atual`) and `senado_ecidadania_sugerir_tema_enquete` (consultas and ideias corpora). **Only a read that becomes a field of the answer is a sub-source**: a read that only resolves or checks an identifier (a committee acronym → its code, the parent check in `senado_contratacao_detalhe`) is left out, otherwise a cached lookup table would make the whole answer claim to be as old as it. `attribution` always lists every distinct underlying `source_url`.
584
+ **Field-level granularity.** Most tools are single-source, so one envelope suffices. The few that merge reads in one response fill `field_sources` — a list of `{ fields, source_url, dataset_id, data_vintage, retrieved_at, served_from_cache }` attributing specific output fields to their real origin, and the block's `retrieved_at` is the oldest of them. `served_from_cache` is `true`/`false` for reads through the server cache and `null` where the notion does not apply (the bundled org-chart snapshot, the e-Cidadania corpus in D1). The merging tools: `senado_obter_materia` `secao=detalhe` (`/processo/{id}` + `ementa` from `/processo` + `relator` from `/processo/relatoria`), `senado_obter_senador` and the Deep Research `fetch` of a senator (biography + `mandatos`/`emExercicio` from `/senador/{codigo}/mandatos`), `senado_servidores` with `subordinadasA` (payroll + org-chart snapshot), `senado_suprimento_fundos` statistics on `atos-concessao` (acts + beneficiary names from the supridos registry), `senado_ecidadania_obter_evento` (live detail + `comentarios` from the corpus), `senado_listar_senadores` with `legislatura` (the legislature list + `emExercicio` from `/senador/lista/atual`) and `senado_ecidadania_sugerir_tema_enquete` (consultas and ideias corpora). **Only a read that becomes a field of the answer is a sub-source**: a read that only resolves or checks an identifier (a committee acronym → its code, the parent check in `senado_contratacao_detalhe`) is left out, otherwise a cached lookup table would make the whole answer claim to be as old as it. `attribution` always lists every distinct underlying `source_url`.
584
585
 
585
- `retrieved_at` fidelity is provided by the cache layer (`cachedFetchWithMeta`), which persists the fetch timestamp alongside the value, so it reflects the real upstream extraction even on a cache hit. Two exceptions report an honest live timestamp instead: the e-Cidadania **list** tools (read from D1) use the corpus's `lastScrapedAt` — the true age of the stored data, or the live scrape instant when the corpus is empty or stale and the list falls back to the portal (since 3.18.3; before, the stale corpus's instant leaked into the live answer) — while e-Cidadania **detail** tools, scraped live, use the fetch time and a level-3 canonical item URL. The only path that falls back to the build-time default is the in-code static reference catalog (`senado_tabelas_referencia` `tipos-materia`), which has no upstream extraction instant.
586
+ `retrieved_at` fidelity is provided by the cache layer (`cachedFetchWithMeta`), which persists the fetch timestamp alongside the value, so it reflects the real upstream extraction even on a cache hit. Two exceptions report an honest live timestamp instead: the e-Cidadania **list** tools (read from D1) use the corpus's `lastScrapedAt` — the true age of the stored data, or the live scrape instant when the corpus is empty or stale and the list falls back to the portal — while e-Cidadania **detail** tools, scraped live, use the fetch time and a level-3 canonical item URL. The only path that falls back to the build-time default is the in-code static reference catalog (`senado_tabelas_referencia` `tipos-materia`), which has no upstream extraction instant.
586
587
 
587
588
  Coverage is **universal**: all 69 tools carry the envelope — the 67 `senado_*` tools via `resultWithProvenance(` (verify with `grep -c 'resultWithProvenance(' src/tools/*.ts`) and the two Deep Research tools via `provenanceExtras` (same block, in `structuredContent`/`_meta`, since their text channel is the contract's JSON). The **⊕** marks in the inventory below denote the original pilot tools (votes, bills, processes); the envelope now extends to every tool, so the marks are historical.
588
589
 
@@ -639,7 +640,7 @@ The frozen NDJSON is **not** committed (built from the sovereign D1 corpus on de
639
640
 
640
641
  | Tool | Description |
641
642
  |------|-------------|
642
- | `senado_buscar_materias` ⊕ | Busca matérias por tipo, número, ano, palavra-chave, autor ou tramitação (via v3 `/processo`) |
643
+ | `senado_buscar_materias` ⊕ | Busca matérias por tipo, número, ano, palavra-chave, autor ou tramitação (via v3 `/processo`); com `agruparPor: "partido"` e `ano`, conta quantas matérias cada partido apresentou no ano, numa chamada |
643
644
  | `senado_obter_materia` ⊕ | Dados de uma matéria via `secao` enum: detalhe (situação/relator), tramitacao (histórico) ou textos (documentos) |
644
645
 
645
646
  ### Group C — Processes (5 tools)
@@ -679,7 +680,7 @@ The frozen NDJSON is **not** committed (built from the sovereign D1 corpus on de
679
680
  | `senado_agenda_plenario` | Plenary schedule — by day, month or Congress (escopo dia/mes/cn) |
680
681
  | `senado_resultado_plenario` | Session results: items deliberated, opinions, outcomes (SF/CN/month) |
681
682
  | `senado_orientacao_bancada` | Party leadership voting instructions per vote, with tallies |
682
- | `senado_vetos` | Presidential vetoes by year or tramitation status |
683
+ | `senado_vetos` | Presidential vetoes by year or tramitation status; with `apuracao`, how many of a year's vetoes were overridden, partly overridden or upheld, in one call |
683
684
  | `senado_resultado_veto` | Nominal veto vote results (by veto, vetoed bill or device) |
684
685
  | `senado_encontro_plenario` | Legislative session detail, agenda items, results or summary |
685
686
  | `senado_tabelas_plenario` | Session types, attendance types, legislatures list |
@@ -754,7 +755,7 @@ The frozen NDJSON is **not** committed (built from the sovereign D1 corpus on de
754
755
  |------|-------------|
755
756
  | `senado_servidores` | Civil servants by status (active/effective/commissioned/inactive), filterable by name, unit, position |
756
757
  | `senado_remuneracoes_servidores` | Monthly payroll — summary by payroll type or per-person composition with computed gross; `estatisticas=true` returns whole-payroll stats (min/max/mean/median/percentiles) + top/bottom ranking, with `campo`, `consolidarPorServidor`, `agruparPor` and `topN` |
757
- | `senado_horas_extras` | Overtime payments by month with totals; `estatisticas=true` returns whole-set distribution stats (min/max/mean/median/percentiles) + top/bottom ranking, or a per-servant ranking by summed value via `agruparPor` (name/competência), with `topN` |
758
+ | `senado_horas_extras` | Overtime payments by month with totals — or, without `mes`, the whole year in one call (monthly series by payment month; merges the rows the source splits); `estatisticas=true` returns whole-set distribution stats (min/max/mean/median/percentiles) + top/bottom ranking, or a per-servant ranking by summed value via `agruparPor` (name/competência), with `topN` |
758
759
  | `senado_pessoal_tabelas` | Tabelas de pessoal via `tabela` enum: quantitativos (pessoal, cargos-funcoes, previsao-aposentadoria, senadores) e listas (estagiarios, pensionistas, lotacoes, cargos) |
759
760
 
760
761
  ### Group Q — Contratações (6 tools)
@@ -869,7 +870,7 @@ src/
869
870
  ├── orcamento-senado.ts # Group S — 1 budget execution tool
870
871
  └── estrutura.ts # Group T — 1 org-structure tool (reads src/data/ snapshot via src/estrutura/)
871
872
  scripts/
872
- └── ingest-ecidadania/ # Off-Worker full-corpus consultas ingestion (run via `npm run ingest:ecidadania`)
873
+ └── ingest-ecidadania/ # Off-Worker full-corpus ingestion (consultas, eventos, ideias) (run via `npm run ingest:ecidadania`)
873
874
  ├── index.ts # Orchestrator: crawl → status (/processo) → normalize → guards → out.sql
874
875
  ├── listing.ts # Pure listing parser (parseConsultaListingPage, findLastPage)
875
876
  ├── status.ts # tramitando=S set from /processo → aberta/encerrada (deriveStatus)
@@ -878,7 +879,7 @@ scripts/
878
879
  ├── d1.ts # D1 pre-reads (existing meta, payloads, last good rows) via wrangler
879
880
  ├── verify.ts # consultas_votos on-demand integrity-check verdict (verifyAcervoIntegrity)
880
881
  └── sql.ts # out.sql generation (mirrors SQL.upsert/SQL.history; reuses SyncRecord)
881
- .github/workflows/ # ingest-ecidadania.yml (daily D1 corpus load), verify-consultas-votos.yml
882
+ .github/workflows/ # ingest-ecidadania-*.yml (daily D1 corpus loads), verify-consultas-votos.yml
882
883
  # (weekly frozen-acervo integrity check), publish-mcp.yml (registry),
883
884
  # usage-report.yml (monthly Analytics report), deprecate-registry.yml
884
885
  # (all pinned to current Node 24 action majors — see each YAML for exact versions)
@@ -1,7 +1,7 @@
1
1
  export const ESTRUTURA_ORGANIZACIONAL = {
2
- "extraidoEm": "2026-11-01T17:20:35.706Z",
2
+ "extraidoEm": "2026-12-02T00:53:19.422Z",
3
3
  "fonteUrl": "https://www12.senado.leg.br/institucional/estrutura/orgaosenado",
4
- "total": 820,
4
+ "total": 818,
5
5
  "orgaos": [
6
6
  {
7
7
  "cod": -2072346465,
@@ -4887,18 +4887,6 @@ export const ESTRUTURA_ORGANIZACIONAL = {
4887
4887
  "nome": "Coordenação do Observatório da Mulher Contra a Violência",
4888
4888
  "codSuperior": 8852
4889
4889
  },
4890
- {
4891
- "cod": 10860,
4892
- "sigla": "GSLPEREI",
4893
- "nome": "Gabinete da Senadora Lourdinha Pereira",
4894
- "codSuperior": 108
4895
- },
4896
- {
4897
- "cod": 10861,
4898
- "sigla": null,
4899
- "nome": "Escritório de Apoio Nº 01 da Senadora Lourdinha Pereira",
4900
- "codSuperior": 10860
4901
- },
4902
4890
  {
4903
4891
  "cod": 10862,
4904
4892
  "sigla": "GSSREGIN",
package/dist/envelope.js CHANGED
@@ -1,257 +1,31 @@
1
1
  /**
2
- * Leitura do ENVELOPE da resposta — o que transforma "o container devolveu
3
- * HTTP 200" em "esta mensagem deu certo / esta falhou, e por quê".
4
- *
5
- * O PROBLEMA QUE ESTE ARQUIVO RESOLVE, E QUE AQUI É PIOR QUE NO `sih`. A
6
- * telemetria deste Worker decide o desfecho pelo HTTP da resposta, e em cima
7
- * disso `protocolNamesFromBody` (em src/instrument.ts) tinha a linha `if (status < 400) continue`, com
8
- * o comentário "o hook de tools já gravou esta". A reconciliação era por STATUS,
9
- * e supunha que 200 implica que o hook gravou. Quando a tool NÃO CHEGA A RODAR
10
- * — recusa de esquema do zod, antes do handler — ninguém grava, e o `continue`
11
- * fecha a única outra porta. O `sih` carimbava `ok` numa falha: número errado.
12
- * Aqui não havia número NENHUM: a chamada não era contada nem como chamada.
13
- *
14
- * Medido na produção em 24/09/2026, pela rota do dono, no ilo, uis, senado e
15
- * bcb — os quatro idênticos, e são DUAS formas, não uma: recusa de esquema sai
16
- * HTTP 200 com `result.isError: true` e SEM código JSON-RPC; ferramenta
17
- * inexistente sai HTTP 200 com o código −32602 (não −32601). Os dois são 200,
18
- * então os dois caíam no `continue`.
19
- *
20
- * POR QUE NÃO BUFFERIZAR. Este Worker não é proxy — quem produz a resposta é o
21
- * `createMcpHandler` aqui dentro —, mas a técnica é a mesma e pelo mesmo motivo:
22
- * segurar bytes para ler o fim trocaria um defeito de medição por um defeito de
23
- * produto (a lição do `sih`, cuja série de 34 anos leva ~30 s). O corpo é TEADO
24
- * (`ReadableStream.tee()`): um ramo segue intocado para o cliente, no mesmo
25
- * ritmo de antes, e o outro é lido aqui em `ctx.waitUntil`, depois que a
26
- * resposta já saiu.
27
- *
28
- * O TEE RESOLVE, DE QUEBRA, UM PROBLEMA DE TEMPO. O hook de tools escreve
29
- * durante a execução da tool, que num transporte SSE pode terminar DEPOIS de o
30
- * handler já ter devolvido a Response. Ler o envelope até o fim do stream é,
31
- * por construção, esperar a tool acabar — é só então que se sabe o que o hook
32
- * gravou, e a reconciliação por nome (src/instrument.ts) só vale aí.
33
- *
34
- * REGRA DE OURO DESTE MÓDULO: ele nunca lança e nunca segura bytes. Qualquer
35
- * coisa que ele não entenda vira "sem desfecho", e quem chama cai no critério
36
- * antigo (o HTTP). Medir pior é aceitável; atrapalhar a resposta do usuário não é.
37
- *
38
- * DOIS TETOS, pelo mesmo motivo. Um evento SSE acumulado passa de
39
- * `MAX_EVENTO_BYTES` → é descartado sem parsear (o `isError` pode estar no fim
40
- * do JSON, mas mensagem de erro é curta: evento gigante é quase certamente
41
- * resultado feliz, e o teto troca uma classificação improvável por um limite de
42
- * memória e de CPU garantido). Mais de `MAX_DESFECHOS` respostas no mesmo corpo
43
- * → o resto é ignorado; lote JSON-RPC de verdade tem punhado de mensagens.
44
- *
45
- * O CAMINHO DE ERRO-MOLE FICA DE FORA, de propósito. Ferramenta que responde
46
- * ausência como DADO — uma resposta de SUCESSO cujo payload diz "não há" — está
47
- * funcionando, e continua sendo `ok`. O que conta como falha é `isError: true`
48
- * ou um erro JSON-RPC, nada mais. (No `sih`, de onde este arquivo vem, isso é a
49
- * decisão 38 e seis ferramentas dependem dela; aqui o erro de tool já nasce de
50
- * `IlostatUserError` / `IlostatUpstreamError` e vira `isError`.)
51
- *
52
- * Cópia de sih-br-mcp/worker/src/envelope.ts, porque o classificador não pode
53
- * divergir entre os sete. O que muda é só este cabeçalho e o `teeResposta` do
54
- * fim, que lá não existe: o `sih` monta a Response do zero a partir do upstream
55
- * e teia no caminho; aqui a Response já vem pronta do handler.
2
+ * Leitura do ENVELOPE da resposta — o que transforma "o servidor devolveu HTTP 200" em "esta
3
+ * mensagem JSON-RPC deu certo / falhou, e por quê" (recusa de esquema sai 200 com `isError`;
4
+ * ferramenta inexistente sai 200 com −32602 — medido em produção em 24/09/2026).
5
+ *
6
+ * Desde 01/12/2026 a leitura mora no `@sbissoli/mcp-telemetry` (mcp-br-commons): os sete servidores
7
+ * copiavam este arquivo, e as cópias já divergiam (232 a 296 linhas). O pacote leva também o PRAZO
8
+ * da leitura, que este servidor estreou na 3.38.3 (o `subscriptions/listen` do protocolo 2026-07-28
9
+ * deixa o stream aberto e a leitura em `waitUntil` era cancelada pela Cloudflare — 9 a 22 avisos por
10
+ * hora nos logs). Aqui fica só o que é DESTE servidor: a regra de classe do `call-shape.ts`, ligada
11
+ * ao pacote, com os nomes de sempre (index.ts, instrument.ts e os testes não mudam).
56
12
  */
13
+ import { LeitorDeEnvelope as LeitorDoPacote, MAX_DESFECHOS, MAX_EVENTO_BYTES, PRAZO_LEITURA_ENVELOPE_MS, desfechoDaResposta as desfechoDoPacote, desfechosDoCorpo as desfechosDoPacote, resolveDesfecho, teeResposta, } from "@sbissoli/mcp-telemetry";
57
14
  import { classeDoErroRpc, classifyError, errorText } from "./call-shape.js";
58
- /** Teto de bytes acumulados por evento SSE (ou por linha) antes de desistir dele. */
59
- export const MAX_EVENTO_BYTES = 64 * 1024;
60
- /** Teto de respostas rastreadas por corpo. */
61
- export const MAX_DESFECHOS = 64;
62
- /**
63
- * Desfecho de uma resposta JSON-RPC, com o `id` que a liga ao pedido.
64
- * `null` quando o objeto não é uma resposta identificável:
65
- * - sem `id` (ou `id: null`, que é a resposta a um pedido que nem parseou) —
66
- * não há a que ligar, e o chamador fica com o critério do HTTP;
67
- * - sem `result` e sem `error` — não é resposta (é notificação, ou lixo).
68
- */
15
+ export { MAX_DESFECHOS, MAX_EVENTO_BYTES, PRAZO_LEITURA_ENVELOPE_MS, resolveDesfecho, teeResposta };
16
+ /** A regra de classe deste servidor: código JSON-RPC reservado decide; fora dele, a frase. */
17
+ export const CLASSIFICADOR = {
18
+ erroRpc: (codigo, mensagem) => classeDoErroRpc(codigo, mensagem),
19
+ erroDeFerramenta: (result) => classifyError(errorText(result)),
20
+ };
69
21
  export function desfechoDaResposta(msg) {
70
- if (!msg || typeof msg !== "object" || Array.isArray(msg))
71
- return null;
72
- const m = msg;
73
- if (typeof m.id !== "string" && typeof m.id !== "number")
74
- return null;
75
- const id = String(m.id);
76
- if (m.error && typeof m.error === "object") {
77
- const e = m.error;
78
- const code = typeof e.code === "number" ? e.code : undefined;
79
- const texto = typeof e.message === "string" ? e.message : "";
80
- return { id, desfecho: { erro: true, classe: classeDoErroRpc(code, texto) } };
81
- }
82
- if (m.result && typeof m.result === "object") {
83
- const r = m.result;
84
- if (r.isError === true) {
85
- return { id, desfecho: { erro: true, classe: classifyError(errorText(m.result)) } };
86
- }
87
- return { id, desfecho: { erro: false, classe: "" } };
88
- }
89
- // `result` primitivo (o SDK responde `{}` em alguns métodos, mas nunca um
90
- // escalar) ainda é sucesso; o que não é resposta é o objeto sem os dois.
91
- if (m.result !== undefined)
92
- return { id, desfecho: { erro: false, classe: "" } };
93
- return null;
94
- }
95
- /**
96
- * O desfecho de UMA mensagem do pedido, já com o CRITÉRIO DE RESERVA aplicado.
97
- *
98
- * Regra: vale o que o envelope disse. Quando o envelope não disse nada — `id`
99
- * ausente (notificação), stream cortado, evento grande demais, resposta que
100
- * não parseou —, vale o HTTP do container, que era o critério único até
101
- * 24/09/2026. Nunca se inventa classe: sem leitura, a classe é "".
102
- */
103
- export function resolveDesfecho(id, desfechos, falhouHttp) {
104
- const lido = id === "" ? undefined : desfechos.get(id);
105
- return lido ?? { erro: falhouHttp, classe: "" };
22
+ return desfechoDoPacote(msg, CLASSIFICADOR);
106
23
  }
107
- /**
108
- * Lê o corpo da resposta aos pedaços e vai colhendo desfechos por `id`.
109
- *
110
- * Aceita os dois formatos que o transporte Streamable HTTP usa: SSE (`data:`
111
- * por evento, evento fechado por linha em branco, várias linhas `data:` do
112
- * mesmo evento juntadas por `\n`) e JSON cru (resposta direta, sem stream).
113
- * Linhas `event:`, `id:`, `retry:` e comentários (`:`) são ignoradas.
114
- */
115
- export class LeitorDeEnvelope {
116
- resto = "";
117
- descartandoLinha = false;
118
- evento = [];
119
- bytesDoEvento = 0;
120
- eventoEstourado = false;
121
- viuSse = false;
122
- cru = "";
123
- /** Desfechos colhidos, por `id` de mensagem JSON-RPC. */
124
- desfechos = new Map();
125
- /** Entrega mais um pedaço de TEXTO já decodificado. Nunca lança. */
126
- push(texto) {
127
- if (!this.viuSse && this.cru.length < MAX_EVENTO_BYTES)
128
- this.cru += texto;
129
- this.resto += texto;
130
- for (;;) {
131
- const quebra = this.resto.indexOf("\n");
132
- if (quebra < 0)
133
- break;
134
- const linha = this.resto.slice(0, quebra);
135
- this.resto = this.resto.slice(quebra + 1);
136
- if (this.descartandoLinha) {
137
- // Fim da linha gigante que foi descartada: o evento inteiro cai junto,
138
- // porque o JSON dele está incompleto.
139
- this.descartandoLinha = false;
140
- this.eventoEstourado = true;
141
- continue;
142
- }
143
- this.linha(linha.endsWith("\r") ? linha.slice(0, -1) : linha);
144
- }
145
- // Linha sem fim à vista e já maior que o teto: para de acumular em vez de
146
- // crescer com o corpo (uma resposta de 34 anos é uma única linha `data:`).
147
- if (this.resto.length > MAX_EVENTO_BYTES) {
148
- this.resto = "";
149
- this.descartandoLinha = true;
150
- }
151
- }
152
- /** Fecha o que ficou pendente. Chamar uma vez, ao fim do stream. */
153
- end() {
154
- if (this.resto !== "" && !this.descartandoLinha) {
155
- const linha = this.resto.endsWith("\r") ? this.resto.slice(0, -1) : this.resto;
156
- this.resto = "";
157
- this.linha(linha);
158
- }
159
- this.fechaEvento();
160
- // Corpo que nunca teve uma linha `data:` é JSON cru.
161
- if (!this.viuSse)
162
- this.registra(this.cru);
163
- }
164
- linha(linha) {
165
- if (linha === "") {
166
- this.fechaEvento();
167
- return;
168
- }
169
- if (!linha.startsWith("data:"))
170
- return;
171
- this.viuSse = true;
172
- const pedaco = linha.slice(5).replace(/^ /, "");
173
- this.bytesDoEvento += pedaco.length;
174
- if (this.bytesDoEvento > MAX_EVENTO_BYTES) {
175
- this.eventoEstourado = true;
176
- this.evento = [];
177
- return;
178
- }
179
- this.evento.push(pedaco);
180
- }
181
- fechaEvento() {
182
- const partes = this.evento;
183
- const estourou = this.eventoEstourado;
184
- this.evento = [];
185
- this.bytesDoEvento = 0;
186
- this.eventoEstourado = false;
187
- if (estourou || partes.length === 0)
188
- return;
189
- this.registra(partes.join("\n"));
190
- }
191
- registra(json) {
192
- if (json === "" || this.desfechos.size >= MAX_DESFECHOS)
193
- return;
194
- let obj;
195
- try {
196
- obj = JSON.parse(json);
197
- }
198
- catch {
199
- return; // pedaço cortado ao meio, ou não era JSON: fica sem desfecho
200
- }
201
- for (const item of Array.isArray(obj) ? obj : [obj]) {
202
- if (this.desfechos.size >= MAX_DESFECHOS)
203
- return;
204
- const d = desfechoDaResposta(item);
205
- if (d)
206
- this.desfechos.set(d.id, d.desfecho);
207
- }
208
- }
209
- }
210
- /**
211
- * Consome um stream inteiro e devolve os desfechos por `id`. Nunca lança: se o
212
- * stream for cortado no meio (cliente desconectou, container caiu), vale o que
213
- * deu para ler até ali e o resto fica sem desfecho.
214
- */
215
- export async function desfechosDoCorpo(corpo) {
216
- const leitor = new LeitorDeEnvelope();
217
- const decoder = new TextDecoder();
218
- const reader = corpo.getReader();
219
- try {
220
- for (;;) {
221
- const { done, value } = await reader.read();
222
- if (done)
223
- break;
224
- if (value)
225
- leitor.push(decoder.decode(value, { stream: true }));
226
- }
227
- leitor.push(decoder.decode());
228
- }
229
- catch {
230
- // Stream interrompido: o que já foi lido continua valendo.
24
+ export class LeitorDeEnvelope extends LeitorDoPacote {
25
+ constructor() {
26
+ super(CLASSIFICADOR);
231
27
  }
232
- finally {
233
- try {
234
- reader.releaseLock();
235
- }
236
- catch {
237
- // ignorado
238
- }
239
- }
240
- leitor.end();
241
- return leitor.desfechos;
242
28
  }
243
- /**
244
- * Parte o corpo da resposta em dois: o que vai para o cliente e o que a
245
- * telemetria lê. Só isto, e nunca mais que isto — a Response devolvida tem o
246
- * mesmo status, o mesmo statusText e os mesmos cabeçalhos da original.
247
- *
248
- * Resposta sem corpo (204, HEAD, erro montado na borda) devolve `corpo: null` e
249
- * a própria Response intacta: não há o que teiar, e `new Response(null, resp)`
250
- * seria uma cópia à toa.
251
- */
252
- export function teeResposta(resposta) {
253
- if (!resposta.body)
254
- return { paraCliente: resposta, paraLeitura: null };
255
- const [cliente, leitura] = resposta.body.tee();
256
- return { paraCliente: new Response(cliente, resposta), paraLeitura: leitura };
29
+ export function desfechosDoCorpo(corpo, prazoMs = PRAZO_LEITURA_ENVELOPE_MS) {
30
+ return desfechosDoPacote(corpo, CLASSIFICADOR, { prazoMs });
257
31
  }