mcp-scraper 0.94.0 → 0.94.1

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/CHANGELOG.md CHANGED
@@ -4,6 +4,17 @@ All notable changes to MCP Scraper are documented here. The format is based on [
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.94.1] - 2026-09-25
8
+
9
+ ### Changed
10
+
11
+ - Accept up to 1,000 reviews in a Maps place request across API, MCP, dashboard, and workflows. Scale browser collection time with the requested count and preserve each saved review batch through interrupted runs.
12
+ - Read the named business first during Bright Data service and area acquisition, matching the full Bright Data place path. Retry a challenged Bright Data browser once with a fresh session and meter both sessions. Keep a visible partial run and refund its hold if Google challenges both.
13
+
14
+ ### Fixed
15
+
16
+ - Treat a profile's exhausted review total as collected even when it has fewer reviews than the requested maximum. An unknown total no longer means the business has no reviews.
17
+
7
18
  ## [0.94.0] - 2026-09-25
8
19
 
9
20
  ### Added
@@ -11,23 +22,23 @@ All notable changes to MCP Scraper are documented here. The format is based on [
11
22
  - Recoverable Maps place runs with owner-scoped status, paginated saved reviews and images, and explicit resume tools. MCP now reads the same run after a client timeout.
12
23
  - Incremental, revision-fenced Maps place checkpoints and five-minute repair of expired attempts and unsettled customer holds. Image ZIP packaging can resume from saved image URLs without reopening a browser.
13
24
  - Google Maps place calls accept an `include` declaration, including `all`, to request reviews, configured services and areas served, and images within the existing review and image limits.
14
- - Maps uses Option 2 Browser API for requested configured services and areas served, while Option 1 remains the default for direct Google Maps discovery and place details.
25
+ - Maps uses Bright Data Browser API for requested configured services and areas served, while Kernel remains the default for direct Google Maps discovery and place details.
15
26
 
16
27
  ### Changed
17
28
 
18
29
  - Maps place requests reserve the maximum declared base and review charge before browser work, then settle completed attempts to the base plus unique saved reviews. Stopped attempts are refunded; saved results survive a billing repair.
19
30
  - Ordinary Maps searches now use state-targeted mobile browser egress when `location` names a US state, then direct egress after two failed mobile attempts. Searches without a state use direct egress; the MCP tool asks for a state without exposing proxy settings.
20
31
 
21
- - Maps search and place requests now use a provider broker and report both the result provider and, for split place requests, the acquisition provider. Option 1 discovery reads the Google Maps feed; Option 2 reads the visible Businesses pack or clicks More businesses for larger service-enriched searches.
22
- - Align Option 2 Maps acquisition with the observed Google Places DOM: recognize the `udm=local` finder after More businesses, open exact `pv-` result cards, read the `#local-place-viewer` profile and its complete Services and Areas Served dialogs, and verify place identity from its `ftid` Maps link. Named service requests use Option 1's place category to reach the organic Businesses pack before Option 2 enrichment.
23
- - Option 2-only named place requests now begin on the organic Google SERP and use the matching knowledge panel's category to find the business in the organic Businesses results. A cold exact-name Places finder is reserved for profiles without a category, and a Google challenge is reported as a CAPTCHA rather than an unexplained missing business.
24
- - Option 2-only place extraction stays in the opened Google Search Places viewer to read profile details, expanded hours, declared services and areas, photos, and review cards up to the requested limits; a live run collected 30 services, 10 areas, 50 reviews, and 10 photo URLs. Maps SERP navigation preserves provider errors and allows up to two minutes for slow Browser API navigation.
25
- - Option 2 Maps search, service acquisition, and place details can start one new browser session after the provider confirms `no_ready_cookies` with zero navigations, separately from Maps extraction retries; that recovery waits five seconds after connecting before navigation.
26
- - Option 2 place review and gallery collection now scale their time and scroll allowances with the declared review and image limits. A default full declaration has a five-minute planning budget; the largest allowed request has nine minutes.
32
+ - Maps search and place requests now use a provider broker and report both the result provider and, for split place requests, the acquisition provider. Kernel discovery reads the Google Maps feed; Bright Data reads the visible Businesses pack or clicks More businesses for larger service-enriched searches.
33
+ - Align Bright Data Maps acquisition with the observed Google Places DOM: recognize the `udm=local` finder after More businesses, open exact `pv-` result cards, read the `#local-place-viewer` profile and its complete Services and Areas Served dialogs, and verify place identity from its `ftid` Maps link. Named service requests use Kernel's place category to reach the organic Businesses pack before Bright Data enrichment.
34
+ - Bright Data-only named place requests now begin on the organic Google SERP and use the matching knowledge panel's category to find the business in the organic Businesses results. A cold exact-name Places finder is reserved for profiles without a category, and a Google challenge is reported as a CAPTCHA rather than an unexplained missing business.
35
+ - Bright Data-only place extraction stays in the opened Google Search Places viewer to read profile details, expanded hours, declared services and areas, photos, and review cards up to the requested limits; a live run collected 30 services, 10 areas, 50 reviews, and 10 photo URLs. Maps SERP navigation preserves provider errors and allows up to two minutes for slow Browser API navigation.
36
+ - Bright Data Maps search, service acquisition, and place details can start one new browser session after the provider confirms `no_ready_cookies` with zero navigations, separately from Maps extraction retries; that recovery waits five seconds after connecting before navigation.
37
+ - Bright Data place review and gallery collection now scale their time and scroll allowances with the declared review and image limits. A default full declaration has a five-minute planning budget; the largest allowed request has nine minutes.
27
38
 
28
39
  ### Fixed
29
40
 
30
- - Attribute Maps provider cost to each browser actually used, including failed and retried Option 2 search, place, services acquisition, and startup recovery sessions. Option 1 rotations and broker fallbacks are linked as retries for CEO reporting, which now shows failed-attempt spend separately. Option 1 costs remain estimates; Option 2 sessions with delayed usage remain pending for reconciliation.
41
+ - Attribute Maps provider cost to each browser actually used, including failed and retried Bright Data search, place, services acquisition, and startup recovery sessions. Kernel rotations and broker fallbacks are linked as retries for CEO reporting, which now shows failed-attempt spend separately. Kernel costs remain estimates; Bright Data sessions with delayed usage remain pending for reconciliation.
31
42
  - Include web-app embedding requests in the paid-action inventory and scan web source during future cost-coverage checks.
32
43
  - Include configured S3-compatible storage and remote media processing in the paid-action inventory, and show live Stripe account fee totals separately from MCP operation costs in the CEO report.
33
44
 
@@ -43,13 +54,13 @@ All notable changes to MCP Scraper are documented here. The format is based on [
43
54
  ### Fixed
44
55
 
45
56
  - Render the CEO report headline and detail from one cost-ledger snapshot, and label cost-linked surcharge multiples as pricing targets rather than guaranteed realized margin.
46
- - Apply the owner-confirmed $1.50 per 1,000 successful Option 2 SERP requests to delivered provider receipts, with a guarded backfill for earlier successful requests. Failed attempts remain visibly unresolved until provider billing evidence is available.
57
+ - Apply the owner-confirmed $1.50 per 1,000 successful Bright Data SERP requests to delivered provider receipts, with a guarded backfill for earlier successful requests. Failed attempts remain visibly unresolved until provider billing evidence is available.
47
58
 
48
59
  ## [0.93.2] - 2026-09-24
49
60
 
50
61
  ### Fixed
51
62
 
52
- - Show Google Search and other provider costs in the CEO report with separate calculated, actual-or-measured, and unresolved receipt coverage. Failed queries now stop the report, missing Option 2 SERP rates leave an explicit delivered-but-unpriced receipt, and historical cost rows no longer imply a margin from subscription MRR.
63
+ - Show Google Search and other provider costs in the CEO report with separate calculated, actual-or-measured, and unresolved receipt coverage. Failed queries now stop the report, missing Bright Data SERP rates leave an explicit delivered-but-unpriced receipt, and historical cost rows no longer imply a margin from subscription MRR.
53
64
 
54
65
  ## [0.93.1] - 2026-09-24
55
66
 
@@ -148,7 +159,7 @@ All notable changes to MCP Scraper are documented here. The format is based on [
148
159
 
149
160
  - Retire the inactive Personal Assistant from server startup, HTTP and MCP routing, web navigation, Scheduler transitions, generated contracts, and Memory tool registration while preserving its source history, persisted data, secrets, and provider resources behind the verified archive branch.
150
161
  - Make two-page SERP capture perform a distinct page-two request, preserve page provenance and query/location intent, and report local-pack evidence as present, absent, incomplete, or unknown instead of silently claiming completeness.
151
- - Make Maps retries follow one immutable egress plan, retain location intent, close every browser/proxy attempt, and treat an already-gone Option 1 session as successful cleanup.
162
+ - Make Maps retries follow one immutable egress plan, retain location intent, close every browser/proxy attempt, and treat an already-gone Kernel session as successful cleanup.
152
163
 
153
164
  ### Fixed
154
165
 
@@ -162,13 +173,13 @@ All notable changes to MCP Scraper are documented here. The format is based on [
162
173
 
163
174
  - Add the fixture-tested operation, attempt, provider-receipt, reconciliation, and billing-link foundation needed to trace failed and retried SERP, PAA, Maps, extraction, and transcription work without treating missing provider cost as zero.
164
175
  - Add a generated MCP cost-coverage manifest and release gate that tracks every hosted input flag plus each named execution method's retry, timeout, billing, and cost-accounting owner.
165
- - Trace direct Option 2 SERP requests and Option 2/Option 1 browser attempts into the shared operation timeline, including provider identities, retry or fallback causality, immediate estimates, hourly due-gated Browser API reconciliation, and customer billing links.
166
- - Add a protected four-cell PAA benchmark runner for Option 1 and Option 2 at 20 and 40 complete questions, with a dry-run contract gate, one paid attempt per cell, sanitized provider evidence, and no automatic replacement run.
176
+ - Trace direct Bright Data SERP requests and Bright Data/Kernel browser attempts into the shared operation timeline, including provider identities, retry or fallback causality, immediate estimates, hourly due-gated Browser API reconciliation, and customer billing links.
177
+ - Add a protected four-cell PAA benchmark runner for Kernel and Bright Data at 20 and 40 complete questions, with a dry-run contract gate, one paid attempt per cell, sanitized provider evidence, and no automatic replacement run.
167
178
  - Add a once-daily due-gated purge of raw provider identifiers and verbose diagnostic errors after 30 days while preserving normalized cost facts and hashed correlation keys.
168
179
 
169
180
  ### Fixed
170
181
 
171
- - Skip Option 1 proxy resolution when the active attempt uses Option 2 Browser, removing avoidable Option 1 API traffic from Option 2-first SERP and PAA work.
182
+ - Skip Kernel proxy resolution when the active attempt uses Bright Data Browser, removing avoidable Kernel API traffic from Bright Data-first SERP and PAA work.
172
183
 
173
184
  ## [0.90.4] - 2026-09-22
174
185
 
@@ -180,21 +191,21 @@ All notable changes to MCP Scraper are documented here. The format is based on [
180
191
 
181
192
  ### Fixed
182
193
 
183
- - Route ordinary Option 2 SERP searches through the zone's native parsed proxy, returning Google results within the existing bounded deadline while preserving the REST endpoint as a configuration fallback.
194
+ - Route ordinary Bright Data SERP searches through the zone's native parsed proxy, returning Google results within the existing bounded deadline while preserving the REST endpoint as a configuration fallback.
184
195
  - Keep Browser API credentials and interactive PAA behavior independent from the native SERP transport, with one provider request and no hidden retry or browser fallback.
185
196
 
186
197
  ## [0.90.2] - 2026-09-21
187
198
 
188
199
  ### Fixed
189
200
 
190
- - Unwrap Option 2's object-valued REST response body before mapping parsed SERP fields, so successful direct searches return their organic results instead of an empty collection.
201
+ - Unwrap Bright Data's object-valued REST response body before mapping parsed SERP fields, so successful direct searches return their organic results instead of an empty collection.
191
202
 
192
203
  ## [0.90.1] - 2026-09-21
193
204
 
194
205
  ### Changed
195
206
 
196
- - Route ordinary `search_serp` calls through one parsed Option 2 SERP API request when the dedicated production zone is configured, avoiding browser startup and cleanup while leaving interactive PAA on Browser API.
197
- - Keep saved SERP identities on their existing Option 1-backed path and retain the browser path as the configuration fallback for local and unconfigured environments.
207
+ - Route ordinary `search_serp` calls through one parsed Bright Data SERP API request when the dedicated production zone is configured, avoiding browser startup and cleanup while leaving interactive PAA on Browser API.
208
+ - Keep saved SERP identities on their existing Kernel-backed path and retain the browser path as the configuration fallback for local and unconfigured environments.
198
209
 
199
210
  ### Fixed
200
211
 
@@ -237,7 +248,7 @@ All notable changes to MCP Scraper are documented here. The format is based on [
237
248
 
238
249
  ### Changed
239
250
 
240
- - Cap every Option 1 browser session at a ten-minute absolute lifetime and move expired-session reconciliation from the minute root cron to a dedicated hourly audit.
251
+ - Cap every Kernel browser session at a ten-minute absolute lifetime and move expired-session reconciliation from the minute root cron to a dedicated hourly audit.
241
252
  - Disable the inactive Personal Assistant reminder, reconciliation, and inbound cron schedules while preserving their routes and implementation.
242
253
  - Disable the inactive Personal Memory heartbeat and weekly rollup registrations in the production scheduler while preserving their implementation.
243
254
  - Pause twice-daily automatic memory optimization while preserving the workflow for deliberate use, preventing all-vault fan-out from consuming background execution capacity.
@@ -246,10 +257,10 @@ All notable changes to MCP Scraper are documented here. The format is based on [
246
257
 
247
258
  ### Fixed
248
259
 
249
- - Treat Option 1's not-found response during legacy session deletion as successful cleanup, preventing already-closed sessions from retrying forever.
260
+ - Treat Kernel's not-found response during legacy session deletion as successful cleanup, preventing already-closed sessions from retrying forever.
250
261
  - Show browser sessions awaiting provider cleanup separately in the CTO report instead of hiding them behind a non-null close timestamp.
251
262
  - Cast the analytics pruning clock before PostgreSQL interval arithmetic so the root cron no longer fails every minute while pruning scheduled occurrences.
252
- - Explicitly delete Option 1 screenshot sessions after capture, including when closing the browser connection fails.
263
+ - Explicitly delete Kernel screenshot sessions after capture, including when closing the browser connection fails.
253
264
 
254
265
  ## [0.89.7] - 2026-09-18
255
266
 
@@ -368,7 +379,7 @@ All notable changes to MCP Scraper are documented here. The format is based on [
368
379
 
369
380
  ### Fixed
370
381
 
371
- - Give each `reddit_thread` retrieval a 300-second end-to-end deadline, with two 60-second Option 1 attempts and two 60-second managed-browser backup attempts, instead of exhausting the full retry ladder in about 50 seconds. The MCP client now waits long enough to receive the endpoint's structured terminal result.
382
+ - Give each `reddit_thread` retrieval a 300-second end-to-end deadline, with two 60-second Kernel attempts and two 60-second managed-browser backup attempts, instead of exhausting the full retry ladder in about 50 seconds. The MCP client now waits long enough to receive the endpoint's structured terminal result.
372
383
 
373
384
  ## [0.88.2] - 2026-09-02
374
385
 
@@ -405,19 +416,19 @@ All notable changes to MCP Scraper are documented here. The format is based on [
405
416
 
406
417
  ### Fixed
407
418
 
408
- - Kept Option 2 telemetry lookup off the Reddit response critical path and reallocated the saved time to 17-second backup attempts, so all four provider attempts can finish before production ends the request.
419
+ - Kept Bright Data telemetry lookup off the Reddit response critical path and reallocated the saved time to 17-second backup attempts, so all four provider attempts can finish before production ends the request.
409
420
 
410
421
  ## [0.86.4] - 2026-09-02
411
422
 
412
423
  ### Fixed
413
424
 
414
- - Kept the complete two-primary, two-backup Reddit retry ladder inside the production request window by limiting Option 1 attempts to 8 seconds, Option 2 attempts to 14 seconds, and browser cleanup to 1 second.
425
+ - Kept the complete two-primary, two-backup Reddit retry ladder inside the production request window by limiting Kernel attempts to 8 seconds, Bright Data attempts to 14 seconds, and browser cleanup to 1 second.
415
426
 
416
427
  ## [0.86.3] - 2026-09-02
417
428
 
418
429
  ### Fixed
419
430
 
420
- - Applied 45-second Option 1 and 35-second Option 2 deadlines to the complete Reddit browser-attempt lifecycle, and made known-thread primary attempts find and click the target through DuckDuckGo before the residential landing.
431
+ - Applied 45-second Kernel and 35-second Bright Data deadlines to the complete Reddit browser-attempt lifecycle, and made known-thread primary attempts find and click the target through DuckDuckGo before the residential landing.
421
432
 
422
433
  ## [0.86.2] - 2026-09-02
423
434
 
@@ -566,13 +577,13 @@ All notable changes to MCP Scraper are documented here. The format is based on [
566
577
 
567
578
  ### Added
568
579
 
569
- - Added a Option 1-only Reddit workflow that searches DuckDuckGo with a `site:reddit.com` query, switches the same browser to a residential proxy before clicking the selected result, and reads modern Reddit posts plus bounded rendered-comment expansion through dedicated search, thread, and combined REST endpoints.
570
- - Added a bounded managed-browser backup for Reddit thread hydration after the primary Option 1 attempt fails or returns fewer than the semantic target, capped at 25 comments with measured bandwidth, duration, CAPTCHA, closure, and provider-cost telemetry.
580
+ - Added a Kernel-only Reddit workflow that searches DuckDuckGo with a `site:reddit.com` query, switches the same browser to a residential proxy before clicking the selected result, and reads modern Reddit posts plus bounded rendered-comment expansion through dedicated search, thread, and combined REST endpoints.
581
+ - Added a bounded managed-browser backup for Reddit thread hydration after the primary Kernel attempt fails or returns fewer than the semantic target, capped at 25 comments with measured bandwidth, duration, CAPTCHA, closure, and provider-cost telemetry.
571
582
 
572
583
  ### Changed
573
584
 
574
- - Routed the production `reddit_thread` and `reddit_trending` MCP tools through modern Reddit on Option 1 residential sessions, with DuckDuckGo site search for trend discovery; removed Google and old Reddit from their active execution path while preserving tool names, billing rates, bounded partial results, and refunds.
575
- - Cost probes now include Reddit Option 1 sessions and any managed-browser fallback bytes and cost in the same request receipt, and identify when the backup contributed to total cost.
585
+ - Routed the production `reddit_thread` and `reddit_trending` MCP tools through modern Reddit on Kernel residential sessions, with DuckDuckGo site search for trend discovery; removed Google and old Reddit from their active execution path while preserving tool names, billing rates, bounded partial results, and refunds.
586
+ - Cost probes now include Reddit Kernel sessions and any managed-browser fallback bytes and cost in the same request receipt, and identify when the backup contributed to total cost.
576
587
 
577
588
  ### Fixed
578
589
 
@@ -617,7 +628,7 @@ All notable changes to MCP Scraper are documented here. The format is based on [
617
628
 
618
629
  ### Fixed
619
630
 
620
- - Persisted per-control PAA dispatch and 0.7/1.0/1.4-second confirmation telemetry in durable checkpoints, exposed recent interaction and attempt correlation through MCP status, attached Option 2 session IDs immediately after browser launch, and finalized dangling attempt rows during lease recovery without blocking customer settlement.
631
+ - Persisted per-control PAA dispatch and 0.7/1.0/1.4-second confirmation telemetry in durable checkpoints, exposed recent interaction and attempt correlation through MCP status, attached Bright Data session IDs immediately after browser launch, and finalized dangling attempt rows during lease recovery without blocking customer settlement.
621
632
  - Prevented inline style, script, and hidden DOM text inside Google answer containers from falsely confirming that PAA answer material loaded.
622
633
  - Routed canonical `/assistant` page loads to the web app and the redacted private Assistant readiness endpoint to the main API function, preventing production 404s after the 0.79.1 launch.
623
634
 
@@ -641,7 +652,7 @@ All notable changes to MCP Scraper are documented here. The format is based on [
641
652
  - Added Scheduling as the canonical Personal Assistant setup surface, with connection readiness for Gmail, Calendar, Zoom, browser profiles, Memory, SMS, and email; exact schedule confirmation; approval and spend review; run history; and explicit watch/takeover states.
642
653
  - Added owner-scoped browser profiles that can hold multiple independently verified login bindings, while every browser schedule grant selects one exact profile, login, domain, and action set.
643
654
  - Added immutable schedule revisions, readiness receipts, append-only activation records, additive legacy schedule projection, and single-owner occurrence transition receipts so migration cannot silently infer browser authority or double-dispatch work.
644
- - Added Option 1 and private-Mac browser runtime boundaries with collision-resistant tenant namespaces, per-owner concurrency ceilings, bounded sessions, explicit and timeout cleanup, owner-qualified account deletion, and provider deletion readback.
655
+ - Added Kernel and private-Mac browser runtime boundaries with collision-resistant tenant namespaces, per-owner concurrency ceilings, bounded sessions, explicit and timeout cleanup, owner-qualified account deletion, and provider deletion readback.
645
656
  - Added an owner-controlled Personal Assistant that brings SMS/MMS, Gmail, Google Calendar, Zoom, browser work, reminders, and Memory context packets into one governed workflow with immutable plans, approval checkpoints, spend limits, and durable receipts.
646
657
  - Added Twilio number discovery, owned-number attachment, purchase and registration previews, Messaging Service readiness, signed inbound and delivery webhooks, safe MMS ingestion, deterministic opt-out handling, single and reviewed bulk messaging, and reconciliation for unknown provider outcomes.
647
658
  - Added immutable, revisioned Memory context packets with source and attachment provenance, Gmail full-message imports, MMS media metadata, lifecycle controls, and readback verification against the selected vault.
@@ -678,7 +689,7 @@ All notable changes to MCP Scraper are documented here. The format is based on [
678
689
  - Made `maxQuestions` an explicit target count rather than a traversal-depth control, with separate discovery and material-completeness diagnostics.
679
690
  - Preserved complete People Also Ask, AI Overview, and organic-result link provenance in JSON, structured MCP output, and CSV while classifying plain links and Google redirect links explicitly.
680
691
  - Resolved opaque Google `/goto` targets through bounded concurrent manual-redirect requests with active-browser interception as a fallback, without following publisher destinations and without dropping unresolved material.
681
- - Aligned the bounded PAA production-provider canary with the public `maxQuestions` contract and made Option 2 the default test provider.
692
+ - Aligned the bounded PAA production-provider canary with the public `maxQuestions` contract and made Bright Data the default test provider.
682
693
 
683
694
  ### Fixed
684
695
 
@@ -886,7 +897,7 @@ All notable changes to MCP Scraper are documented here. The format is based on [
886
897
 
887
898
  - Added portable `harvest_paa_start` and `harvest_paa_status` tools for durable long-running PAA research, with stable idempotency recovery, progress, attempt provenance, completeness, billing state, and bounded provider telemetry.
888
899
  - Added progressive PAA checkpoints that preserve and merge the best unique rows across browser retries and stale-job recovery instead of losing already captured questions when a provider session or caller is interrupted.
889
- - Added exact Option 2 browser-session identity, sanitized Session Logs enrichment, disconnect attribution, bandwidth usage telemetry, and retryable reconciliation without making provider telemetry a prerequisite for result delivery.
900
+ - Added exact Bright Data browser-session identity, sanitized Session Logs enrichment, disconnect attribution, bandwidth usage telemetry, and retryable reconciliation without making provider telemetry a prerequisite for result delivery.
890
901
 
891
902
  ### Changed
892
903
 
@@ -1619,7 +1630,7 @@ All notable changes to MCP Scraper are documented here. The format is based on [
1619
1630
 
1620
1631
  ### Changed
1621
1632
 
1622
- - PAA browser work now uses Option 1's co-located Playwright execution with stealth mode's default managed proxy and native browser metadata. Location is expressed only through Google UULE, CAPTCHA solver waiting is capped at 60 seconds, and a fresh session is allowed once only when no useful data was captured.
1633
+ - PAA browser work now uses Kernel's co-located Playwright execution with stealth mode's default managed proxy and native browser metadata. Location is expressed only through Google UULE, CAPTCHA solver waiting is capped at 60 seconds, and a fresh session is allowed once only when no useful data was captured.
1623
1634
  - PAA invocations stop browser work at 250 seconds inside the 280-second application budget, reserving 30 seconds for persistence, cleanup, and settlement. The legacy cron worker no longer claims Inngest-owned PAA jobs.
1624
1635
 
1625
1636
  ### Fixed
@@ -1855,7 +1866,7 @@ All notable changes to MCP Scraper are documented here. The format is based on [
1855
1866
 
1856
1867
  ### Changed
1857
1868
 
1858
- - `maps_search` now applies a transport ladder across its retry attempts so it can recover from Google soft-blocks instead of only retrying the same way. The first attempt is unchanged (Option 1's default stealth ISP proxy, direct navigation). Subsequent retries switch to direct egress and arrive at Google through a cross-site redirect (the combination that measurably clears blocks a cold navigation triggers); the final escalation attempt uses direct egress without the redirect and accepts any egress country. This only affects the `proxyMode: 'none'` default path and only its retries — a first-attempt success behaves exactly as before.
1869
+ - `maps_search` now applies a transport ladder across its retry attempts so it can recover from Google soft-blocks instead of only retrying the same way. The first attempt is unchanged (Kernel's default stealth ISP proxy, direct navigation). Subsequent retries switch to direct egress and arrive at Google through a cross-site redirect (the combination that measurably clears blocks a cold navigation triggers); the final escalation attempt uses direct egress without the redirect and accepts any egress country. This only affects the `proxyMode: 'none'` default path and only its retries — a first-attempt success behaves exactly as before.
1859
1870
 
1860
1871
  ## [0.32.1] - 2026-07-22
1861
1872
 
package/README.md CHANGED
@@ -175,7 +175,7 @@ Build the branded one-click bundle:
175
175
  npm run build:mcpb
176
176
  ```
177
177
 
178
- The generated bundle is written to `build/mcpb/mcp-scraper-<version>.mcpb` and copied to `public/downloads/` for the hosted download. The current public bundle is `https://mcpscraper.dev/downloads/mcp-scraper.mcpb` (`0.94.0`, SHA-256 `7c4cc327a0a1e02830e29d2358c75ef4d6ce9d803c862a6f7402c383874bc884`). Install it by opening or dragging it into Claude Desktop. Claude displays the `MCP Scraper` install card, icon, API-key configuration field, and manually curated current-release message from the bundle manifest.
178
+ The generated bundle is written to `build/mcpb/mcp-scraper-<version>.mcpb` and copied to `public/downloads/` for the hosted download. The current public bundle is `https://mcpscraper.dev/downloads/mcp-scraper.mcpb` (`0.94.1`, SHA-256 `4a5f8a8dc8cb7743ffca82fee5a9c981a9146e5e55e8f50ac7e028400913404d`). Install it by opening or dragging it into Claude Desktop. Claude displays the `MCP Scraper` install card, icon, API-key configuration field, and manually curated current-release message from the bundle manifest.
179
179
 
180
180
  The MCPB install exposes every tool — web-intelligence plus all `browser_*` tools — through the one `mcp-scraper` server.
181
181
 
@@ -366,8 +366,8 @@ The `mcp-scraper` NPX stdio server also exposes saved reports as MCP resources:
366
366
  - `MCP_SCRAPER_OUTPUT_DIR` is optional and defaults to `~/Downloads/mcp-scraper`.
367
367
  - `MCP_SCRAPER_SAVE_REPORTS=false` disables automatic Markdown report files.
368
368
  - `MCP_SCRAPER_KEY_PATH` is optional. When no API key env var is set, the server also reads `~/.mcp-scraper-key` for compatibility with older installs.
369
- - `BROWSER_AGENT_PROFILE_NAME` is optional and sets the default saved hosted browser profile for `mcp-scraper` stdio sessions. Aliases: `BROWSER_SERVICE_PROFILE_NAME`, `Option 1_BROWSER_PROFILE_NAME`, `Option 1_PROFILE_NAME`.
370
- - `BROWSER_AGENT_PROFILE_SAVE_CHANGES=true` is optional hosted setup behavior. It persists cookies and storage back to the named profile when `browser_close` deletes the hosted browser session. Aliases: `BROWSER_SERVICE_PROFILE_SAVE_CHANGES`, `Option 1_BROWSER_PROFILE_SAVE_CHANGES`, `Option 1_PROFILE_SAVE_CHANGES`.
369
+ - `BROWSER_AGENT_PROFILE_NAME` is optional and sets the default saved hosted browser profile for `mcp-scraper` stdio sessions. Aliases: `BROWSER_SERVICE_PROFILE_NAME`, `KERNEL_BROWSER_PROFILE_NAME`, `KERNEL_PROFILE_NAME`.
370
+ - `BROWSER_AGENT_PROFILE_SAVE_CHANGES=true` is optional hosted setup behavior. It persists cookies and storage back to the named profile when `browser_close` deletes the hosted browser session. Aliases: `BROWSER_SERVICE_PROFILE_SAVE_CHANGES`, `KERNEL_BROWSER_PROFILE_SAVE_CHANGES`, `KERNEL_PROFILE_SAVE_CHANGES`.
371
371
 
372
372
  Hosted operators can isolate authorization state in a dedicated Turso/libSQL database without changing the public MCP tool catalog or API-key authentication. The secured store uses atomic authorization-code exchange and refresh rotation, keyed secret lookup, bounded encrypted replay receipts, authority epochs, and fail-closed maintenance behavior. Production migration and rollback are controlled data moves, not ordinary mode flips; see [MCP OAuth operations](docs/operations/mcp-oauth-runbook.md). Existing client setup and reconnect behavior are unchanged in Phase 1.
373
373
 
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  import{readFileSync as s}from"fs";function c(){try{for(let r of s(".env","utf8").split(`
3
- `)){let o=r.indexOf("=");if(o<1||r.trimStart().startsWith("#"))continue;let e=r.slice(0,o).trim();process.env[e]||(process.env[e]=r.slice(o+1).trim())}}catch{}}c();async function a(){let[{serve:r},{app:o},{startWorker:e},{migrate:i}]=await Promise.all([import("@hono/node-server"),import("../server-SH6KWIEA.js"),import("../worker-V53ZJGJS.js"),import("../db-B6RNXKEI.js")]),n=parseInt(process.env.PORT??"3001");try{if(await i(),process.env.ANALYTICS_DATABASE_URL){let{migrateAnalytics:t}=await import("../analytics-repository-A7VMA24D.js");await t()}e(),r({fetch:o.fetch,port:n},t=>{console.log(`[server] http://localhost:${t.port}`),console.log(`[server] admin auth: ${process.env.ADMIN_KEY?"configured":"not configured"}`)})}catch(t){console.error("[startup] server preflight failed",t instanceof Error?t.name:"unknown_error"),process.exit(1)}}a();
3
+ `)){let o=r.indexOf("=");if(o<1||r.trimStart().startsWith("#"))continue;let e=r.slice(0,o).trim();process.env[e]||(process.env[e]=r.slice(o+1).trim())}}catch{}}c();async function a(){let[{serve:r},{app:o},{startWorker:e},{migrate:i}]=await Promise.all([import("@hono/node-server"),import("../server-4VUCH5QX.js"),import("../worker-5J4KF5RM.js"),import("../db-B6RNXKEI.js")]),n=parseInt(process.env.PORT??"3001");try{if(await i(),process.env.ANALYTICS_DATABASE_URL){let{migrateAnalytics:t}=await import("../analytics-repository-A7VMA24D.js");await t()}e(),r({fetch:o.fetch,port:n},t=>{console.log(`[server] http://localhost:${t.port}`),console.log(`[server] admin auth: ${process.env.ADMIN_KEY?"configured":"not configured"}`)})}catch(t){console.error("[startup] server preflight failed",t instanceof Error?t.name:"unknown_error"),process.exit(1)}}a();
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{b as E,c as N,d as M,e as L,f as T,j as U}from"../chunk-SJRXG3LV.js";import"../chunk-KJQXUZ4Y.js";import"../chunk-I46JRG5B.js";import{g as v,j as b,k as D,l as K,m as H}from"../chunk-WO3N5FH2.js";import"../chunk-HE45FFBU.js";import{a as P}from"../chunk-4SNU2TWB.js";import{Command as he}from"commander";import{spawn as ne}from"child_process";import{mkdir as ke,writeFile as Pe}from"fs/promises";import{basename as Ce,join as Z}from"path";function se(e){return e.apiKey?.trim()||"sk_live_your_key"}function ce(e){return e.packageSpec?.trim()||"mcp-scraper@latest"}function A(e={}){return["-y","--package",ce(e),"mcp-scraper"]}function pe(e){let n={MCP_SCRAPER_API_KEY:se(e)},c=e.browserProfileName?.trim();return c&&(n.BROWSER_AGENT_PROFILE_NAME=c),e.browserProfileSaveChanges===!0&&(n.BROWSER_AGENT_PROFILE_SAVE_CHANGES="true"),n}function q(){return["mcp","remove","mcp-scraper","-s","user"]}function J(){return["mcp","get","mcp-scraper"]}function B(e){let n=e.match(/^\s*Command:\s*(.+?)\s*$/m)?.[1];if(!n)return null;let c=e.match(/^\s*Args:\s*(.*?)\s*$/m)?.[1]??"",i=c.length?c.split(/\s+/):[],p={},u=e.split(/^\s*Environment:\s*$/m)[1];if(u)for(let a of u.split(`
2
+ import{b as E,c as N,d as M,e as L,f as T,j as U}from"../chunk-6ND5AFV5.js";import"../chunk-KJQXUZ4Y.js";import"../chunk-XPEJB4BZ.js";import{g as v,j as b,k as D,l as K,m as H}from"../chunk-WO3N5FH2.js";import"../chunk-HE45FFBU.js";import{a as P}from"../chunk-RK2UKLWP.js";import{Command as he}from"commander";import{spawn as ne}from"child_process";import{mkdir as ke,writeFile as Pe}from"fs/promises";import{basename as Ce,join as Z}from"path";function se(e){return e.apiKey?.trim()||"sk_live_your_key"}function ce(e){return e.packageSpec?.trim()||"mcp-scraper@latest"}function A(e={}){return["-y","--package",ce(e),"mcp-scraper"]}function pe(e){let n={MCP_SCRAPER_API_KEY:se(e)},c=e.browserProfileName?.trim();return c&&(n.BROWSER_AGENT_PROFILE_NAME=c),e.browserProfileSaveChanges===!0&&(n.BROWSER_AGENT_PROFILE_SAVE_CHANGES="true"),n}function q(){return["mcp","remove","mcp-scraper","-s","user"]}function J(){return["mcp","get","mcp-scraper"]}function B(e){let n=e.match(/^\s*Command:\s*(.+?)\s*$/m)?.[1];if(!n)return null;let c=e.match(/^\s*Args:\s*(.*?)\s*$/m)?.[1]??"",i=c.length?c.split(/\s+/):[],p={},u=e.split(/^\s*Environment:\s*$/m)[1];if(u)for(let a of u.split(`
3
3
  `)){let l=a.match(/^\s{2,}([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);if(!l){if(a.trim().length&&!/^\s{2,}/.test(a))break;continue}p[l[1]]=l[2]}return{command:n,args:i,env:p}}function j(e){let n=["mcp","add","mcp-scraper","--scope","user"];for(let[c,i]of Object.entries(e.env))n.push("--env",`${c}=${i}`);return n.push("--",e.command,...e.args),n}function G(e={}){let n=["mcp","add","mcp-scraper","--scope","user"];for(let[c,i]of Object.entries(pe(e)))n.push("--env",`${c}=${i}`);return n.push("--","npx",...A(e)),n}function O(e){if(e==="claude-code")return"claude";if(e==="claude"||D.hosts.some(n=>n.id===e))return e;throw new Error('Unknown host "'+e+'". Use: codex, claude, claude-code, claude-desktop, cursor, windsurf, cline, or user-action-only')}function ue(e){return K(e==="claude"?"claude-code":e)}function W(e,n={}){let c=O(e),i=ue(c),p="Restart the MCP client so it starts a fresh npx process.",u='MCP_SCRAPER_API_KEY="$MCP_SCRAPER_API_KEY" npx -y -p mcp-scraper@latest mcp-scraper-cli agent install claude --apply',a=`X-Ray install protocol: ${v} (${b})`;return c==="codex"?["# Codex MCP config",a,i.exactConfig,"",`Continuation: ${i.continuation}`,`Rollback: ${i.rollback}`,"",p].join(`
4
4
  `):c==="claude"?["# Claude Code command",a,i.exactConfig,"","# One-command Claude Code setup",u,"",`Continuation: ${i.continuation}`,`Rollback: ${i.rollback}`,"",p].join(`
5
5
  `):c==="claude-desktop"?["# Claude Desktop config",a,i.exactConfig,"","Desktop Extension: https://mcpscraper.dev/downloads/mcp-scraper.mcpb",`Continuation: ${i.continuation}`,`Rollback: ${i.rollback}`,p].join(`
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{a as e}from"../chunk-2GEVQBI6.js";import"../chunk-ASP7YHUY.js";import"../chunk-NZSDHDX3.js";import"../chunk-W2BVJ7S2.js";import"../chunk-DOJMTFLB.js";import"../chunk-ZUGTYD2I.js";import"../chunk-TMB56NCA.js";import"../chunk-HUV2WTRW.js";import"../chunk-YGBTTW5D.js";import"../chunk-ZGITQEFC.js";import"../chunk-SH5KB4P7.js";import"../chunk-NA76FFGD.js";import"../chunk-6DTXIZY2.js";import"../chunk-C5MWTMRD.js";import"../chunk-WO3N5FH2.js";import"../chunk-HE45FFBU.js";import"../chunk-4SNU2TWB.js";import"../chunk-ZPK5LYEN.js";var _=["harvest_paa","search_serp","extract_url","diff_page","map_site_urls","map_wayback_snapshots","extract_site","analyze_site_similarity","audit_site","check_site_export","site_export_read","site_export_image","archive_read","youtube_harvest","youtube_transcribe","facebook_page_intel","facebook_ad_search","reddit_thread","reddit_trending","video_frame_analysis","video_frame_analysis_status","facebook_ad_transcribe","google_ads_search","google_ads_page_intel","google_ads_transcribe","facebook_video_transcribe","instagram_profile_content","instagram_media_download","maps_place_intel","maps_search","trustpilot_reviews","g2_reviews","capture_serp_snapshot","capture_serp_page_snapshots"];e({toolsets:new Set(["paa","serp"]),allowedToolNames:_});
2
+ import{a as e}from"../chunk-5HALFCAC.js";import"../chunk-VCK5BJMX.js";import"../chunk-NZSDHDX3.js";import"../chunk-W2BVJ7S2.js";import"../chunk-DOJMTFLB.js";import"../chunk-ZUGTYD2I.js";import"../chunk-TMB56NCA.js";import"../chunk-HUV2WTRW.js";import"../chunk-YGBTTW5D.js";import"../chunk-ZGITQEFC.js";import"../chunk-SH5KB4P7.js";import"../chunk-NA76FFGD.js";import"../chunk-6DTXIZY2.js";import"../chunk-C5MWTMRD.js";import"../chunk-WO3N5FH2.js";import"../chunk-HE45FFBU.js";import"../chunk-RK2UKLWP.js";import"../chunk-ZPK5LYEN.js";var _=["harvest_paa","search_serp","extract_url","diff_page","map_site_urls","map_wayback_snapshots","extract_site","analyze_site_similarity","audit_site","check_site_export","site_export_read","site_export_image","archive_read","youtube_harvest","youtube_transcribe","facebook_page_intel","facebook_ad_search","reddit_thread","reddit_trending","video_frame_analysis","video_frame_analysis_status","facebook_ad_transcribe","google_ads_search","google_ads_page_intel","google_ads_transcribe","facebook_video_transcribe","instagram_profile_content","instagram_media_download","maps_place_intel","maps_search","trustpilot_reviews","g2_reviews","capture_serp_snapshot","capture_serp_page_snapshots"];e({toolsets:new Set(["paa","serp"]),allowedToolNames:_});
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{a as s}from"../chunk-C5MWTMRD.js";import{a as e}from"../chunk-4SNU2TWB.js";var r=process.argv.includes("--no-color")||process.env.NO_COLOR!==void 0||process.env.FORCE_COLOR==="0"||!process.stdout.isTTY,n=process.argv.includes("--help")||process.argv.includes("-h");n&&(process.stdout.write(["Usage: mcp-scraper-install [--no-color]","","Prints the branded MCP Scraper terminal install card and copyable install commands.","mcp-scraper prints the same card in a human terminal and runs as the MCP stdio server in clients.",""].join(`
2
+ import{a as s}from"../chunk-C5MWTMRD.js";import{a as e}from"../chunk-RK2UKLWP.js";var r=process.argv.includes("--no-color")||process.env.NO_COLOR!==void 0||process.env.FORCE_COLOR==="0"||!process.stdout.isTTY,n=process.argv.includes("--help")||process.argv.includes("-h");n&&(process.stdout.write(["Usage: mcp-scraper-install [--no-color]","","Prints the branded MCP Scraper terminal install card and copyable install commands.","mcp-scraper prints the same card in a human terminal and runs as the MCP stdio server in clients.",""].join(`
3
3
  `)),process.exit(0));process.stdout.write(s({version:e,color:!r,apiKeyConfigured:!!process.env.MCP_SCRAPER_API_KEY?.trim()}));
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{a as r}from"../chunk-2GEVQBI6.js";import"../chunk-ASP7YHUY.js";import"../chunk-NZSDHDX3.js";import"../chunk-W2BVJ7S2.js";import"../chunk-DOJMTFLB.js";import"../chunk-ZUGTYD2I.js";import"../chunk-TMB56NCA.js";import"../chunk-HUV2WTRW.js";import"../chunk-YGBTTW5D.js";import"../chunk-ZGITQEFC.js";import"../chunk-SH5KB4P7.js";import"../chunk-NA76FFGD.js";import"../chunk-6DTXIZY2.js";import"../chunk-C5MWTMRD.js";import"../chunk-WO3N5FH2.js";import"../chunk-HE45FFBU.js";import"../chunk-4SNU2TWB.js";import"../chunk-ZPK5LYEN.js";r();
2
+ import{a as r}from"../chunk-5HALFCAC.js";import"../chunk-VCK5BJMX.js";import"../chunk-NZSDHDX3.js";import"../chunk-W2BVJ7S2.js";import"../chunk-DOJMTFLB.js";import"../chunk-ZUGTYD2I.js";import"../chunk-TMB56NCA.js";import"../chunk-HUV2WTRW.js";import"../chunk-YGBTTW5D.js";import"../chunk-ZGITQEFC.js";import"../chunk-SH5KB4P7.js";import"../chunk-NA76FFGD.js";import"../chunk-6DTXIZY2.js";import"../chunk-C5MWTMRD.js";import"../chunk-WO3N5FH2.js";import"../chunk-HE45FFBU.js";import"../chunk-RK2UKLWP.js";import"../chunk-ZPK5LYEN.js";r();
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{z as t}from"../chunk-LZEBDJHY.js";import"../chunk-M5QHXNFZ.js";import{b as r}from"../chunk-SH5KB4P7.js";import"../chunk-NA76FFGD.js";import"../chunk-6DTXIZY2.js";import"../chunk-I46JRG5B.js";import"../chunk-ZPK5LYEN.js";import{Command as s,Option as a}from"commander";var i=new s;i.name("paa-harvest").description("Recursively extract Google People Also Ask questions").requiredOption("-q, --query <query>","Seed query").option("-l, --location <location>",'Location name (e.g. "austin" or "Austin,Texas,United States")').option("--gl <gl>","Google country code","us").option("--hl <hl>","Google language code","en").option("-d, --depth <depth>","BFS depth (1-30)","3").option("-m, --max-questions <n>","Max questions to harvest","100").option("-o, --output <dir>","Output directory","./paa-output").option("-f, --format <format>","Output format: json, csv, or both","both").option("--headless","Run browser in headless mode",!1).option("--profile <dir>","Persistent browser profile directory").option("--proxy <url>","Proxy server URL").option("--browser-api-key <key>","Browser service API key (or set BROWSER_SERVICE_API_KEY env var)").addOption(new a("--\u006b\u0065\u0072\u006e\u0065\u006c-api-key <key>").hideHelp()).action(async e=>{try{let o=await t({query:e.query,location:e.location,gl:e.gl,hl:e.hl,depth:parseInt(e.depth,10),maxQuestions:parseInt(e.maxQuestions,10),outputDir:e.output,format:e.format,headless:e.headless,profileDir:e.profile,proxy:e.proxy,\u006b\u0065\u0072\u006e\u0065\u006cApiKey:e.browserApiKey??e.\u006b\u0065\u0072\u006e\u0065\u006cApiKey??r()});console.log(JSON.stringify({totalQuestions:o.totalQuestions,outputDir:o.stats.seed}))}catch(o){console.error(o instanceof Error?o.message:String(o)),process.exit(1)}});async function n(){await i.parseAsync()}n();
2
+ import{z as t}from"../chunk-R6TD6OXQ.js";import"../chunk-M5QHXNFZ.js";import{b as r}from"../chunk-SH5KB4P7.js";import"../chunk-NA76FFGD.js";import"../chunk-6DTXIZY2.js";import"../chunk-XPEJB4BZ.js";import"../chunk-ZPK5LYEN.js";import{Command as s,Option as a}from"commander";var i=new s;i.name("paa-harvest").description("Recursively extract Google People Also Ask questions").requiredOption("-q, --query <query>","Seed query").option("-l, --location <location>",'Location name (e.g. "austin" or "Austin,Texas,United States")').option("--gl <gl>","Google country code","us").option("--hl <hl>","Google language code","en").option("-d, --depth <depth>","BFS depth (1-30)","3").option("-m, --max-questions <n>","Max questions to harvest","100").option("-o, --output <dir>","Output directory","./paa-output").option("-f, --format <format>","Output format: json, csv, or both","both").option("--headless","Run browser in headless mode",!1).option("--profile <dir>","Persistent browser profile directory").option("--proxy <url>","Proxy server URL").option("--browser-api-key <key>","Browser service API key (or set BROWSER_SERVICE_API_KEY env var)").addOption(new a("--kernel-api-key <key>").hideHelp()).action(async e=>{try{let o=await t({query:e.query,location:e.location,gl:e.gl,hl:e.hl,depth:parseInt(e.depth,10),maxQuestions:parseInt(e.maxQuestions,10),outputDir:e.output,format:e.format,headless:e.headless,profileDir:e.profile,proxy:e.proxy,kernelApiKey:e.browserApiKey??e.kernelApiKey??r()});console.log(JSON.stringify({totalQuestions:o.totalQuestions,outputDir:o.stats.seed}))}catch(o){console.error(o instanceof Error?o.message:String(o)),process.exit(1)}});async function n(){await i.parseAsync()}n();
@@ -1,4 +1,4 @@
1
- import{A as f,Ga as T,Ia as h,Ja as w,Ka as _,La as y,Ma as C,ga as g,ia as S,va as R,wa as E,ya as v,z as u}from"./chunk-ASP7YHUY.js";import{a as P}from"./chunk-C5MWTMRD.js";import{a as m}from"./chunk-4SNU2TWB.js";import{readFileSync as N}from"fs";import{homedir as I}from"os";import{join as A}from"path";import{serveStdio as b}from"@modelcontextprotocol/server/stdio";import{McpServer as k}from"@modelcontextprotocol/server";var x=new Map(w.map(r=>[r.upstreamName,r.id]));function O(r){let s=r.split(`
1
+ import{A as f,Ga as T,Ia as h,Ja as w,Ka as _,La as y,Ma as C,ga as g,ia as S,va as R,wa as E,ya as v,z as u}from"./chunk-VCK5BJMX.js";import{a as P}from"./chunk-C5MWTMRD.js";import{a as m}from"./chunk-RK2UKLWP.js";import{readFileSync as N}from"fs";import{homedir as I}from"os";import{join as A}from"path";import{serveStdio as b}from"@modelcontextprotocol/server/stdio";import{McpServer as k}from"@modelcontextprotocol/server";var x=new Map(w.map(r=>[r.upstreamName,r.id]));function O(r){let s=r.split(`
2
2
  `).filter(o=>o.startsWith("data:")).map(o=>o.slice(5).trim()).filter(Boolean);if(!s.length)return JSON.parse(r);for(let o of s){let e=JSON.parse(o);if(e.result||e.error)return e}throw new Error("hosted MCP returned no JSON-RPC result")}function a(r){return{content:[{type:"text",text:JSON.stringify({ok:!1,error:r})}],isError:!0}}var c=class{baseUrl;apiKey;constructor(s,o){this.baseUrl=s.replace(/\/$/,""),this.apiKey=o}async callMemoryTool(s,o){let e=x.get(s);if(!e)return a(`unknown memory tool: ${s}`);try{let n=await fetch(`${this.baseUrl}/mcp`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json, text/event-stream","x-api-key":this.apiKey},body:JSON.stringify({jsonrpc:"2.0",id:`memory:${e}`,method:"tools/call",params:{name:e,arguments:o}})}),l=await n.text();if(!n.ok)return a(`hosted memory ${e} failed (HTTP ${n.status})`);let t=O(l);return t.error?a(t.error.message??`hosted memory ${e} failed`):t.result??a(`hosted memory ${e} returned no result`)}catch(n){return a(n instanceof Error?n.message:`hosted memory ${e} call failed`)}}};function M(r,s){if(s.length===0)throw new Error("Restricted MCP tool allowlist must contain at least one tool name");let o=new Set;for(let t of s){if(typeof t!="string"||t.trim()!==t||t.length===0)throw new Error("Restricted MCP tool allowlist contains a malformed tool name");if(o.has(t))throw new Error(`Restricted MCP tool allowlist contains duplicate tool name: ${t}`);o.add(t)}let e=new Set,n=r,l=n.registerTool.bind(r);return n.registerTool=(t,i,p)=>{if(o.has(t))return e.add(t),l(t,i,p)},{assertComplete(){let t=[...o].filter(i=>!e.has(i));if(t.length>0)throw new Error(`Restricted MCP tool allowlist contains unknown or unavailable tool names: ${t.join(", ")}`)},registeredToolNames(){return[...e]}}}var L=new Set(["paa","serp","browser-agent","scheduled-results","memory"]);function $(){let s=[process.env.MCP_SCRAPER_KEY_PATH?.trim(),A(I(),".mcp-scraper-key")].filter(Boolean);for(let o of s)try{let e=N(o,"utf8").trim();if(e)return e}catch{}}function Y(r,s={}){let o=s.toolsets??L,e=process.env.MCP_SCRAPER_BASE_URL?.trim()||process.env.MCP_BASE_URL?.trim()||"https://mcpscraper.dev",n=g(),l=S({deploymentProfile:n,transportProfile:"stdio",baseUrl:e,explicitlyEnabled:process.env.MCP_SCRAPER_ALLOW_PRIVATE_NETWORK==="1"}),t=process.env.BROWSER_AGENT_CONSOLE_URL?.trim()||e,i=new k({name:"mcp-scraper",version:m},{instructions:u,cacheHints:{"server/discover":{ttlMs:3e5,cacheScope:"private"},"tools/list":{ttlMs:3e5,cacheScope:"private"},"prompts/list":{ttlMs:3e5,cacheScope:"private"},"resources/list":{ttlMs:3e5,cacheScope:"private"},"resources/templates/list":{ttlMs:3e5,cacheScope:"private"},"resources/read":{ttlMs:6e4,cacheScope:"private"}}});f(i);let p=s.allowedToolNames?M(i,s.allowedToolNames):void 0,d=s.httpExecutor??new T(e,r,{localNetworkAccess:l});return o.has("paa")&&v(i,d,{ownerId:R(r),deploymentProfile:n,transportProfile:"stdio",baseUrl:e,localNetworkAccess:l,taskHandleSecret:r}),o.has("serp")&&E(i,d,{exposeDevelopmentDiagnostics:n==="development"||n==="test"}),o.has("browser-agent")&&h(i,{baseUrl:e,apiKey:r,consoleBaseUrl:t}),o.has("scheduled-results")&&C(i,new y(e,r)),o.has("memory")&&_(i,new c(e,r)),p?.assertComplete(),i}function se(r={}){let s=process.argv.includes("--stdio")||process.env.MCP_SCRAPER_FORCE_STDIO==="1",o=!!(process.stdin.isTTY&&process.stdout.isTTY),e=process.argv.includes("--help")||process.argv.includes("-h");if(!s&&(o||e)){let l=process.argv.includes("--no-color")||process.env.NO_COLOR!==void 0||process.env.FORCE_COLOR==="0"||!process.stdout.isTTY;process.stdout.write(P({version:m,color:!l,apiKeyConfigured:!!process.env.MCP_SCRAPER_API_KEY?.trim()})),process.exit(0)}let n=(process.env.MCP_SCRAPER_API_KEY??process.env.MCP_SCRAPER_KEY??process.env.MCP_API_KEY??$())?.trim();n||(process.stderr.write(`MCP_SCRAPER_API_KEY env var or ~/.mcp-scraper-key is required
3
3
  `),process.exit(1)),b(()=>Y(n,r),{legacy:"serve",onerror(l){process.stderr.write(`${l.message}
4
4
  `)}})}export{se as a};
@@ -1,4 +1,4 @@
1
- import{c as be}from"./chunk-KJQXUZ4Y.js";import{d as T,l as ve}from"./chunk-I46JRG5B.js";import{a as _e,c as ke,d as X,e as Re,f as Se}from"./chunk-WO3N5FH2.js";function xe(e){return e.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")}import{mkdir as J,readFile as Ye,stat as Xe,writeFile as z}from"fs/promises";import{existsSync as Ze}from"fs";import{homedir as et,platform as tt}from"os";import{dirname as Z,join as U}from"path";import{execFile as rt}from"child_process";function ae(e){return e?.trim()||process.env.MCP_SCRAPER_OUTPUT_DIR?.trim()||U(et(),"Downloads","mcp-scraper")}function Ce(){return new Date().toISOString().replace(/[:.]/g,"-")}function se(e){return xe(e).replace(/^-+|-+$/g,"").slice(0,80)||"run"}var V=class e{constructor(t,n,r,i,s,a,l){this.workflowId=t;this.title=n;this.runId=r;this.baseDir=i;this.runDir=s;this.startedAt=a;this.input=l}workflowId;title;runId;baseDir;runDir;startedAt;input;artifacts=[];static async create(t,n,r,i,s){let a=new Date().toISOString(),l=s?.trim()||`${Ce()}-${se(t)}-${Math.random().toString(36).slice(2,8)}`,c=String(r.keyword??r.query??r.domain??r.state??t),p=ae(i),u=U(p,"workflows",t,`${Ce()}-${se(c)}-${se(l).slice(0,20)}`);return await J(u,{recursive:!0}),new e(t,n,l,p,u,a,r)}async remember(t,n,r,i){let s=await Xe(r).then(a=>a.size).catch(()=>{});return this.artifacts.push({kind:t,label:n,path:r,bytes:s,rows:i}),await ve({title:`${this.title} ${n}`,content:`artifact: ${r}`,source:`mcp-scraper-workflow:${this.workflowId}:${this.runId}`}),r}async writeJson(t,n,r){let i=U(this.runDir,n);return await J(Z(i),{recursive:!0}),await z(i,JSON.stringify(r,null,2),"utf8"),this.remember("json",t,i)}async writeText(t,n,r,i="markdown"){let s=U(this.runDir,n);return await J(Z(s),{recursive:!0}),await z(s,r,"utf8"),this.remember(i,t,s)}async writeCsv(t,n,r,i){let s=U(this.runDir,n);return await J(Z(s),{recursive:!0}),await z(s,be(r,i),"utf8"),this.remember("csv",t,s,i.length)}async writeHtml(t,n,r){return this.writeText(t,n,r,"html_report")}async writeManifest(t,n,r,i){let s={workflow:this.workflowId,title:this.title,runId:this.runId,status:t,startedAt:this.startedAt,completedAt:t==="running"?null:new Date().toISOString(),input:this.input,artifacts:this.artifacts,warnings:r,errors:i,counts:n},a=U(this.runDir,"manifest.json");return await z(a,JSON.stringify(s,null,2),"utf8"),await nt(s,a,this.baseDir),a}};function Ae(e=ae()){return U(e,"workflows","index.json")}async function Pe(e){let t=Ae(e);if(!Ze(t))return{runs:[]};try{return JSON.parse(await Ye(t,"utf8"))}catch{return{runs:[]}}}async function nt(e,t,n){if(e.status==="running")return;let r=Ae(n),i=await Pe(n),s=e.artifacts.find(l=>l.kind==="html_report")?.path??null,a={workflow:e.workflow,runId:e.runId,status:e.status,startedAt:e.startedAt,reportPath:s,manifestPath:t,summary:`${e.title} (${e.status})`};i.runs=[a,...i.runs.filter(l=>l.runId!==e.runId)].slice(0,200),await J(Z(r),{recursive:!0}),await z(r,JSON.stringify(i,null,2),"utf8")}async function $e(e){return(await Pe(ae(e))).runs}async function Ee(e,t){let n=await $e(t);return e==="last"?n[0]??null:n.find(r=>r.runId===e)??null}async function it(e,t){let n=await Ee(e,t);if(!n?.reportPath)throw new Error(`No report found for "${e}"`);return tt()==="darwin"&&await new Promise((r,i)=>{rt("open",[n.reportPath],s=>s?i(s):r())}),n.reportPath}import{readFile as At}from"fs/promises";import{z as dr}from"zod";var F=class{constructor(t,n,r=fetch,i={}){this.apiUrl=t;this.apiKey=n;this.fetchImpl=r;this.extraHeaders=i}apiUrl;apiKey;fetchImpl;extraHeaders;async post(t,n,r=18e4){let i=await this.fetchImpl(`${this.apiUrl.replace(/\/$/,"")}${t}`,{method:"POST",headers:{...this.extraHeaders,"Content-Type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(n),signal:AbortSignal.timeout(r)}),s=await i.json().catch(()=>({}));if(!i.ok){let a=typeof s.error=="string"?s.error:`Workflow API ${t} failed with ${i.status}`;throw new Error(a)}return s}};import{z as D}from"zod";function I(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function ot(e){let t=e.rows.map(n=>`<tr>${e.columns.map(r=>`<td>${I(n[r])}</td>`).join("")}</tr>`).join(`
1
+ import{c as be}from"./chunk-KJQXUZ4Y.js";import{d as T,l as ve}from"./chunk-XPEJB4BZ.js";import{a as _e,c as ke,d as X,e as Re,f as Se}from"./chunk-WO3N5FH2.js";function xe(e){return e.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")}import{mkdir as J,readFile as Ye,stat as Xe,writeFile as z}from"fs/promises";import{existsSync as Ze}from"fs";import{homedir as et,platform as tt}from"os";import{dirname as Z,join as U}from"path";import{execFile as rt}from"child_process";function ae(e){return e?.trim()||process.env.MCP_SCRAPER_OUTPUT_DIR?.trim()||U(et(),"Downloads","mcp-scraper")}function Ce(){return new Date().toISOString().replace(/[:.]/g,"-")}function se(e){return xe(e).replace(/^-+|-+$/g,"").slice(0,80)||"run"}var V=class e{constructor(t,n,r,i,s,a,l){this.workflowId=t;this.title=n;this.runId=r;this.baseDir=i;this.runDir=s;this.startedAt=a;this.input=l}workflowId;title;runId;baseDir;runDir;startedAt;input;artifacts=[];static async create(t,n,r,i,s){let a=new Date().toISOString(),l=s?.trim()||`${Ce()}-${se(t)}-${Math.random().toString(36).slice(2,8)}`,c=String(r.keyword??r.query??r.domain??r.state??t),p=ae(i),u=U(p,"workflows",t,`${Ce()}-${se(c)}-${se(l).slice(0,20)}`);return await J(u,{recursive:!0}),new e(t,n,l,p,u,a,r)}async remember(t,n,r,i){let s=await Xe(r).then(a=>a.size).catch(()=>{});return this.artifacts.push({kind:t,label:n,path:r,bytes:s,rows:i}),await ve({title:`${this.title} ${n}`,content:`artifact: ${r}`,source:`mcp-scraper-workflow:${this.workflowId}:${this.runId}`}),r}async writeJson(t,n,r){let i=U(this.runDir,n);return await J(Z(i),{recursive:!0}),await z(i,JSON.stringify(r,null,2),"utf8"),this.remember("json",t,i)}async writeText(t,n,r,i="markdown"){let s=U(this.runDir,n);return await J(Z(s),{recursive:!0}),await z(s,r,"utf8"),this.remember(i,t,s)}async writeCsv(t,n,r,i){let s=U(this.runDir,n);return await J(Z(s),{recursive:!0}),await z(s,be(r,i),"utf8"),this.remember("csv",t,s,i.length)}async writeHtml(t,n,r){return this.writeText(t,n,r,"html_report")}async writeManifest(t,n,r,i){let s={workflow:this.workflowId,title:this.title,runId:this.runId,status:t,startedAt:this.startedAt,completedAt:t==="running"?null:new Date().toISOString(),input:this.input,artifacts:this.artifacts,warnings:r,errors:i,counts:n},a=U(this.runDir,"manifest.json");return await z(a,JSON.stringify(s,null,2),"utf8"),await nt(s,a,this.baseDir),a}};function Ae(e=ae()){return U(e,"workflows","index.json")}async function Pe(e){let t=Ae(e);if(!Ze(t))return{runs:[]};try{return JSON.parse(await Ye(t,"utf8"))}catch{return{runs:[]}}}async function nt(e,t,n){if(e.status==="running")return;let r=Ae(n),i=await Pe(n),s=e.artifacts.find(l=>l.kind==="html_report")?.path??null,a={workflow:e.workflow,runId:e.runId,status:e.status,startedAt:e.startedAt,reportPath:s,manifestPath:t,summary:`${e.title} (${e.status})`};i.runs=[a,...i.runs.filter(l=>l.runId!==e.runId)].slice(0,200),await J(Z(r),{recursive:!0}),await z(r,JSON.stringify(i,null,2),"utf8")}async function $e(e){return(await Pe(ae(e))).runs}async function Ee(e,t){let n=await $e(t);return e==="last"?n[0]??null:n.find(r=>r.runId===e)??null}async function it(e,t){let n=await Ee(e,t);if(!n?.reportPath)throw new Error(`No report found for "${e}"`);return tt()==="darwin"&&await new Promise((r,i)=>{rt("open",[n.reportPath],s=>s?i(s):r())}),n.reportPath}import{readFile as At}from"fs/promises";import{z as dr}from"zod";var F=class{constructor(t,n,r=fetch,i={}){this.apiUrl=t;this.apiKey=n;this.fetchImpl=r;this.extraHeaders=i}apiUrl;apiKey;fetchImpl;extraHeaders;async post(t,n,r=18e4){let i=await this.fetchImpl(`${this.apiUrl.replace(/\/$/,"")}${t}`,{method:"POST",headers:{...this.extraHeaders,"Content-Type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(n),signal:AbortSignal.timeout(r)}),s=await i.json().catch(()=>({}));if(!i.ok){let a=typeof s.error=="string"?s.error:`Workflow API ${t} failed with ${i.status}`;throw new Error(a)}return s}};import{z as D}from"zod";function I(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function ot(e){let t=e.rows.map(n=>`<tr>${e.columns.map(r=>`<td>${I(n[r])}</td>`).join("")}</tr>`).join(`
2
2
  `);return["<section>",`<h2>${I(e.title)}</h2>`,'<div class="table-wrap"><table>',`<thead><tr>${e.columns.map(n=>`<th>${I(n)}</th>`).join("")}</tr></thead>`,`<tbody>${t||`<tr><td colspan="${e.columns.length}">No rows</td></tr>`}</tbody>`,"</table></div>","</section>"].join(`
3
3
  `)}function P(e){let t=e.warnings?.length?`<section class="warnings"><h2>Warnings</h2><ul>${e.warnings.map(i=>`<li>${I(i)}</li>`).join("")}</ul></section>`:"",n=(e.sections??[]).map(i=>`<section><h2>${I(i.title)}</h2><p>${I(i.body)}</p></section>`).join(`
4
4
  `),r=(e.tables??[]).map(ot).join(`
@@ -13,11 +13,11 @@ ${a}
13
13
 
14
14
  ${b}
15
15
  `),await t.artifacts.writeText("Agent tasks","tasks.md",["# Get Leads \u2014 next steps","","- [ ] Verify deliverability of the harvested emails before outreach (MX/SMTP check).",'- [ ] For "form/social only" rows, use the website contact form or the captured social profile.','- [ ] Treat "off-domain \u2014 verify" emails with care; they may belong to a web developer or parent brand.',"- [ ] Respect CAN-SPAM / GDPR \u2014 scraped contact data is not consent to email."].join(`
16
- `));let d=await t.artifacts.writeHtml("HTML report","report.html",P({title:"Get Leads",subtitle:`${e.query} \xB7 ${e.location}`,summary:b,warnings:n,tables:[{title:"Leads",columns:["position","business_name","review_stars","review_count","phone","website","email","email_2","email_status","socials","booking_url"],rows:c}]})),k=r.length?"failed":n.length?"partial":"succeeded",g={businesses:c.length,withWebsite:f,emails:p,domainMatchedEmails:u,reviewCounts:w,withSocials:v};return await t.artifacts.writeManifest(k,g,n,r),{title:"Get Leads",summary:b,status:k,counts:g,warnings:n,errors:r,reportPath:d}}};import{z as M}from"zod";var gt=M.object({query:M.string().min(1),state:M.string().min(2).default("TN"),minPopulation:M.number().int().min(0).default(1e5),maxCities:M.number().int().min(1).max(100).default(25),maxResultsPerCity:M.number().int().min(1).max(50).default(20),hydrateTop:M.number().int().min(0).max(10).default(5),maxReviews:M.number().int().min(0).max(500).default(50),concurrency:M.number().int().min(1).max(5).default(5),proxyMode:M.enum(["configured","none"]).default(T),returnPartial:M.boolean().default(!0)});async function wt(e,t,n){let r=new Array(e.length),i=0;async function s(){for(;i<e.length;){let a=i;i+=1,r[a]=await n(e[a],a)}}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>s())),r}function le(e){if(e==null||e==="")return null;let t=Number(String(e).replace(/[^\d.]/g,""));return Number.isFinite(t)?t:null}function Te(e){let t=e.filter(n=>n!==null).sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]??null:null}function je(e){let t=new Set(["the","and","for","with","that","this","was","were","are","you","our","they","had","have","not","but","from","very","great","good"]),n=new Map;for(let r of e)for(let i of r.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/))i.length<4||t.has(i)||n.set(i,(n.get(i)??0)+1);return[...n.entries()].sort((r,i)=>i[1]-r[1]).slice(0,8).map(([r,i])=>`${r} (${i})`).join("; ")}var Ue={id:"local-competitive-audit",title:"Local Competitive Audit",description:"Audit local Maps competitors, categories, review counts, and review themes across city markets.",inputSchema:gt,async run(e,t){await t.artifacts.writeManifest("running",{},[],[]);let n=[],r=[],i=await t.client.post("/directory/run",{query:e.query,state:e.state,minPopulation:e.minPopulation,maxCities:e.maxCities,maxResultsPerCity:e.maxResultsPerCity,concurrency:e.concurrency,proxyMode:e.proxyMode,saveCsv:!0,background:!1},9e5);await t.artifacts.writeJson("Directory raw JSON","raw/directory-workflow.json",i);let s=Q(i);await t.artifacts.writeCsv("Base directory CSV","exports/directory.csv",K,s);let a=i.cities.flatMap(g=>g.results.slice(0,e.hydrateTop).map(o=>({city:g,result:o}))),l=new Set,c=a.filter(({city:g,result:o})=>{let h=o.cid??o.placeUrl??`${g.location}:${o.name.toLowerCase()}`;return l.has(h)?!1:(l.add(h),!0)}),p=await wt(c,3,async({city:g,result:o},h)=>{try{let R=await t.client.post("/maps/place",{businessName:o.name,location:g.location,includeReviews:e.maxReviews>0,maxReviews:Math.max(1,e.maxReviews)},18e4);return await t.artifacts.writeJson(`${o.name} profile`,`raw/maps-place-intel/${h+1}-${o.name.toLowerCase().replace(/[^a-z0-9]+/g,"-")}.json`,R),{city:g,result:o,detail:R,error:null}}catch(R){let m=R instanceof Error?R.message:String(R);return n.push(`Profile hydration failed for ${o.name} (${g.location}): ${m}`),{city:g,result:o,detail:null,error:m}}}),u=p.map(({city:g,result:o,detail:h,error:R})=>{let m=h?.reviews??[],x=m.filter(S=>S.ownerResponse).length;return{city:g.city,state:g.state,source_location:g.location,result_position:o.position,business_name:o.name,category:h?.category??o.category,review_stars:h?.rating??o.rating,review_count:h?.reviewCount??o.reviewCount,phone:o.phone,website_url:h?.website??o.websiteUrl,place_url:o.placeUrl,cid:o.cid,cid_decimal:o.cidDecimal,hydrated:h?"true":"false",reviews_status:h?.reviewsStatus??"",review_topics:(h?.reviewTopics??[]).map(S=>`${S.label} (${S.count})`).join("; "),owner_response_rate:m.length?(x/m.length).toFixed(2):"",error:R??""}}),w=p.map(({city:g,result:o,detail:h})=>{let R=h?.reviews??[],m=R.filter(S=>Number(S.stars)>=5&&S.text).map(S=>S.text),x=R.filter(S=>Number(S.stars)>0&&Number(S.stars)<=3&&S.text).map(S=>S.text);return{city:g.city,business_name:o.name,cid:o.cid,review_count:h?.reviewCount??o.reviewCount,average_rating:h?.rating??o.rating,topics:(h?.reviewTopics??[]).map(S=>`${S.label} (${S.count})`).join("; "),praise_terms:je(m),complaint_terms:je(x),positive_sample:m[0]?.slice(0,280)??"",negative_sample:x[0]?.slice(0,280)??""}}),v=i.cities.map(g=>{let o=g.results.map(_=>le(_.reviewCount)),h=g.results.map(_=>le(_.rating)),R=g.results.slice(0,3).map(_=>le(_.reviewCount)).filter(_=>_!==null),m=new Map;for(let _ of g.results)_.category&&m.set(_.category,(m.get(_.category)??0)+1);let x=Te(o),S=Te(h),B=R.length?Math.round(R.reduce((_,L)=>_+L,0)/R.length):null,j=Math.min(100,Math.round((B??0)/20+(S??0)*10+g.results.filter(_=>_.websiteUrl).length)),N=Math.max(0,100-j);return{city:g.city,state:g.state,population:g.population,result_count:g.resultCount,median_review_count:x??"",median_rating:S??"",top_three_average_review_count:B??"",top_categories:[...m.entries()].sort((_,L)=>L[1]-_[1]).slice(0,5).map(([_,L])=>`${_} (${L})`).join("; "),opportunity_score:N,difficulty_score:j}});await t.artifacts.writeCsv("Competitors CSV","competitors.csv",["city","state","source_location","result_position","business_name","category","review_stars","review_count","phone","website_url","place_url","cid","cid_decimal","hydrated","reviews_status","review_topics","owner_response_rate","error"],u),await t.artifacts.writeCsv("Review insights CSV","review-insights.csv",["city","business_name","cid","review_count","average_rating","topics","praise_terms","complaint_terms","positive_sample","negative_sample"],w),await t.artifacts.writeCsv("City summary CSV","city-summary.csv",["city","state","population","result_count","median_review_count","median_rating","top_three_average_review_count","top_categories","opportunity_score","difficulty_score"],v),await t.artifacts.writeJson("Audit evidence","evidence.json",{input:e,directory:i,hydrated:p,citySummaryRows:v,competitorRows:u,reviewInsightRows:w}),await t.artifacts.writeText("Agent tasks","tasks.md",["# Local Competitive Audit Tasks","","- [ ] Review city opportunity and difficulty scores as heuristics, not absolute truth.","- [ ] Use review topics and samples as customer-language evidence.","- [ ] Compare target GBP category, review count, and website quality against top competitors.","- [ ] Identify cities with low review-count leaders and weak website coverage."].join(`
16
+ `));let d=await t.artifacts.writeHtml("HTML report","report.html",P({title:"Get Leads",subtitle:`${e.query} \xB7 ${e.location}`,summary:b,warnings:n,tables:[{title:"Leads",columns:["position","business_name","review_stars","review_count","phone","website","email","email_2","email_status","socials","booking_url"],rows:c}]})),k=r.length?"failed":n.length?"partial":"succeeded",g={businesses:c.length,withWebsite:f,emails:p,domainMatchedEmails:u,reviewCounts:w,withSocials:v};return await t.artifacts.writeManifest(k,g,n,r),{title:"Get Leads",summary:b,status:k,counts:g,warnings:n,errors:r,reportPath:d}}};import{z as M}from"zod";var gt=M.object({query:M.string().min(1),state:M.string().min(2).default("TN"),minPopulation:M.number().int().min(0).default(1e5),maxCities:M.number().int().min(1).max(100).default(25),maxResultsPerCity:M.number().int().min(1).max(50).default(20),hydrateTop:M.number().int().min(0).max(10).default(5),maxReviews:M.number().int().min(0).max(1e3).default(50),concurrency:M.number().int().min(1).max(5).default(5),proxyMode:M.enum(["configured","none"]).default(T),returnPartial:M.boolean().default(!0)});async function wt(e,t,n){let r=new Array(e.length),i=0;async function s(){for(;i<e.length;){let a=i;i+=1,r[a]=await n(e[a],a)}}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>s())),r}function le(e){if(e==null||e==="")return null;let t=Number(String(e).replace(/[^\d.]/g,""));return Number.isFinite(t)?t:null}function Te(e){let t=e.filter(n=>n!==null).sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]??null:null}function je(e){let t=new Set(["the","and","for","with","that","this","was","were","are","you","our","they","had","have","not","but","from","very","great","good"]),n=new Map;for(let r of e)for(let i of r.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/))i.length<4||t.has(i)||n.set(i,(n.get(i)??0)+1);return[...n.entries()].sort((r,i)=>i[1]-r[1]).slice(0,8).map(([r,i])=>`${r} (${i})`).join("; ")}var Ue={id:"local-competitive-audit",title:"Local Competitive Audit",description:"Audit local Maps competitors, categories, review counts, and review themes across city markets.",inputSchema:gt,async run(e,t){await t.artifacts.writeManifest("running",{},[],[]);let n=[],r=[],i=await t.client.post("/directory/run",{query:e.query,state:e.state,minPopulation:e.minPopulation,maxCities:e.maxCities,maxResultsPerCity:e.maxResultsPerCity,concurrency:e.concurrency,proxyMode:e.proxyMode,saveCsv:!0,background:!1},9e5);await t.artifacts.writeJson("Directory raw JSON","raw/directory-workflow.json",i);let s=Q(i);await t.artifacts.writeCsv("Base directory CSV","exports/directory.csv",K,s);let a=i.cities.flatMap(g=>g.results.slice(0,e.hydrateTop).map(o=>({city:g,result:o}))),l=new Set,c=a.filter(({city:g,result:o})=>{let h=o.cid??o.placeUrl??`${g.location}:${o.name.toLowerCase()}`;return l.has(h)?!1:(l.add(h),!0)}),p=await wt(c,3,async({city:g,result:o},h)=>{try{let R=await t.client.post("/maps/place",{businessName:o.name,location:g.location,includeReviews:e.maxReviews>0,maxReviews:Math.max(1,e.maxReviews)},18e4);return await t.artifacts.writeJson(`${o.name} profile`,`raw/maps-place-intel/${h+1}-${o.name.toLowerCase().replace(/[^a-z0-9]+/g,"-")}.json`,R),{city:g,result:o,detail:R,error:null}}catch(R){let m=R instanceof Error?R.message:String(R);return n.push(`Profile hydration failed for ${o.name} (${g.location}): ${m}`),{city:g,result:o,detail:null,error:m}}}),u=p.map(({city:g,result:o,detail:h,error:R})=>{let m=h?.reviews??[],x=m.filter(S=>S.ownerResponse).length;return{city:g.city,state:g.state,source_location:g.location,result_position:o.position,business_name:o.name,category:h?.category??o.category,review_stars:h?.rating??o.rating,review_count:h?.reviewCount??o.reviewCount,phone:o.phone,website_url:h?.website??o.websiteUrl,place_url:o.placeUrl,cid:o.cid,cid_decimal:o.cidDecimal,hydrated:h?"true":"false",reviews_status:h?.reviewsStatus??"",review_topics:(h?.reviewTopics??[]).map(S=>`${S.label} (${S.count})`).join("; "),owner_response_rate:m.length?(x/m.length).toFixed(2):"",error:R??""}}),w=p.map(({city:g,result:o,detail:h})=>{let R=h?.reviews??[],m=R.filter(S=>Number(S.stars)>=5&&S.text).map(S=>S.text),x=R.filter(S=>Number(S.stars)>0&&Number(S.stars)<=3&&S.text).map(S=>S.text);return{city:g.city,business_name:o.name,cid:o.cid,review_count:h?.reviewCount??o.reviewCount,average_rating:h?.rating??o.rating,topics:(h?.reviewTopics??[]).map(S=>`${S.label} (${S.count})`).join("; "),praise_terms:je(m),complaint_terms:je(x),positive_sample:m[0]?.slice(0,280)??"",negative_sample:x[0]?.slice(0,280)??""}}),v=i.cities.map(g=>{let o=g.results.map(_=>le(_.reviewCount)),h=g.results.map(_=>le(_.rating)),R=g.results.slice(0,3).map(_=>le(_.reviewCount)).filter(_=>_!==null),m=new Map;for(let _ of g.results)_.category&&m.set(_.category,(m.get(_.category)??0)+1);let x=Te(o),S=Te(h),B=R.length?Math.round(R.reduce((_,L)=>_+L,0)/R.length):null,j=Math.min(100,Math.round((B??0)/20+(S??0)*10+g.results.filter(_=>_.websiteUrl).length)),N=Math.max(0,100-j);return{city:g.city,state:g.state,population:g.population,result_count:g.resultCount,median_review_count:x??"",median_rating:S??"",top_three_average_review_count:B??"",top_categories:[...m.entries()].sort((_,L)=>L[1]-_[1]).slice(0,5).map(([_,L])=>`${_} (${L})`).join("; "),opportunity_score:N,difficulty_score:j}});await t.artifacts.writeCsv("Competitors CSV","competitors.csv",["city","state","source_location","result_position","business_name","category","review_stars","review_count","phone","website_url","place_url","cid","cid_decimal","hydrated","reviews_status","review_topics","owner_response_rate","error"],u),await t.artifacts.writeCsv("Review insights CSV","review-insights.csv",["city","business_name","cid","review_count","average_rating","topics","praise_terms","complaint_terms","positive_sample","negative_sample"],w),await t.artifacts.writeCsv("City summary CSV","city-summary.csv",["city","state","population","result_count","median_review_count","median_rating","top_three_average_review_count","top_categories","opportunity_score","difficulty_score"],v),await t.artifacts.writeJson("Audit evidence","evidence.json",{input:e,directory:i,hydrated:p,citySummaryRows:v,competitorRows:u,reviewInsightRows:w}),await t.artifacts.writeText("Agent tasks","tasks.md",["# Local Competitive Audit Tasks","","- [ ] Review city opportunity and difficulty scores as heuristics, not absolute truth.","- [ ] Use review topics and samples as customer-language evidence.","- [ ] Compare target GBP category, review count, and website quality against top competitors.","- [ ] Identify cities with low review-count leaders and weak website coverage."].join(`
17
17
  `));let f=`${i.selectedCityCount} cities, ${i.totalResultCount} Maps results, ${p.filter(g=>g.detail).length} hydrated profiles.`;await t.artifacts.writeText("Summary","summary.md",`# Local Competitive Audit
18
18
 
19
19
  ${f}
20
- `);let b=await t.artifacts.writeHtml("HTML report","report.html",P({title:"Local Competitive Audit",subtitle:`${e.query} \xB7 ${e.state}`,summary:f,warnings:n,tables:[{title:"City Opportunity",columns:["city","state","population","result_count","median_review_count","median_rating","top_three_average_review_count","top_categories","opportunity_score","difficulty_score"],rows:v},{title:"Hydrated Competitors",columns:["city","result_position","business_name","category","review_stars","review_count","hydrated","review_topics"],rows:u.slice(0,100)},{title:"Review Insights",columns:["city","business_name","topics","praise_terms","complaint_terms"],rows:w.slice(0,100)}]})),d=n.length||i.cities.some(g=>g.status==="failed")?"partial":"succeeded",k={cities:i.selectedCityCount,mapsResults:i.totalResultCount,hydratedProfiles:p.filter(g=>g.detail).length};return await t.artifacts.writeManifest(d,k,n,r),{title:"Local Competitive Audit",summary:f,status:d,counts:k,warnings:n,errors:r,reportPath:b}}};import{z as y}from"zod";var ft=new Set(["about","after","also","because","been","best","both","from","have","into","more","most","near","only","over","than","that","their","them","then","there","these","they","this","what","when","where","which","while","with","your","will","would","should","could","does","were","cost","costs"]);function $(e){if(!e)return null;try{return new URL(e.includes("://")?e:`https://${e}`).hostname.replace(/^www\./,"").toLowerCase()}catch{return e.replace(/^https?:\/\//,"").replace(/^www\./,"").split("/")[0]?.toLowerCase()||null}}function A(e){return $(e)??""}function H(e){if(e==null||e==="")return null;let t=Number(String(e).replace(/[^\d.]/g,""));return Number.isFinite(t)?t:null}function ue(e){let t=e.filter(n=>n!==null).sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]??null:null}function me(e,t=12){let n=new Map;for(let r of e.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/))r.length<4||ft.has(r)||n.set(r,(n.get(r)??0)+1);return[...n.entries()].sort((r,i)=>i[1]-r[1]||r[0].localeCompare(i[0])).slice(0,t).map(([r,i])=>`${r} (${i})`).join("; ")}function ht(e){let t=e.toLowerCase();return/\b(cost|price|pricing|charge|expensive|cheap)\b/.test(t)?"cost":/\b(best|top|recommended|reviews?|compare|versus|vs)\b/.test(t)?"comparison":/\b(how|steps?|process|way to)\b/.test(t)?"process":/\b(why|worth|important|benefit)\b/.test(t)?"why":/\b(near me|city|local|nearby)\b/.test(t)?"local":/\b(can|does|do|is|are|should|will)\b/.test(t)?"decision":"definition"}function ee(e){return(e?.flat??[]).filter(t=>t.question).map((t,n)=>{let r=t.source_cite??"",i=$(t.source_site??"")??A(r);return{position:n+1,intent:ht(t.question??""),question:t.question??"",answer_excerpt:(t.answer??"").slice(0,320),source_title:t.source_title??"",source_domain:i,source_url:r}})}function He(e){let t=new Map;for(let n of e){let r=String(n.source_domain??n.domain??"");if(!r)continue;let i=t.get(r)??{questions:0,urls:new Set,intents:new Map};i.questions+=n.question?1:0,(n.source_url||n.url)&&i.urls.add(String(n.source_url??n.url)),n.intent&&i.intents.set(String(n.intent),(i.intents.get(String(n.intent))??0)+1),t.set(r,i)}return[...t.entries()].map(([n,r])=>({domain:n,question_mentions:r.questions,source_url_count:r.urls.size,top_intents:[...r.intents.entries()].sort((i,s)=>s[1]-i[1]).map(([i,s])=>`${i} (${s})`).join("; ")})).sort((n,r)=>Number(r.question_mentions)-Number(n.question_mentions)||String(n.domain).localeCompare(String(r.domain)))}function Be(e){return(e??"").replace(/\s+/g," ").split(/(?<=[.!?])\s+/).map(t=>t.trim()).filter(t=>t.length>20).slice(0,20)}function Ne(e){let t=e.toLowerCase();return/\bis\b|\bare\b|\bmeans\b|\brefers to\b/.test(t)?"definition":/\binclude\b|\bconsider\b|\bfactors?\b|\bcriteria\b/.test(t)?"criteria":/\bfirst\b|\bthen\b|\bsteps?\b|\bprocess\b/.test(t)?"process":/\bvs\b|\bthan\b|\bcompare\b|\bdifference\b/.test(t)?"comparison":/\bcost\b|\bprice\b|\baverage\b|\brange\b/.test(t)?"cost":"claim"}function te(e,t){return{position:t.position??"",domain:t.domain,url:t.url,serp_title:t.title??"",page_title:e.title??"",h1:e.h1??"",meta_description:e.metaDescription??"",word_count:e.wordCount??"",heading_count:e.headings?.length??0,schema_types:(e.schemaTypes??[]).join("; ")}}async function pe(e,t,n){let r=new Array(e.length),i=0;async function s(){for(;i<e.length;){let a=i;i+=1,r[a]=await n(e[a],a)}}return await Promise.all(Array.from({length:Math.min(Math.max(1,t),e.length)},()=>s())),r}var yt=y.enum(["configured","none"]),vt=y.object({query:y.string().min(1),location:y.string().optional(),state:y.string().optional(),minPopulation:y.number().int().min(0).default(1e5),maxCities:y.number().int().min(1).max(100).default(5),maxResultsPerCity:y.number().int().min(1).max(50).default(20),hydrateTop:y.number().int().min(0).max(10).default(5),maxReviews:y.number().int().min(0).max(500).default(25),concurrency:y.number().int().min(1).max(5).default(5),proxyMode:yt.default(T),returnPartial:y.boolean().default(!0)}).refine(e=>e.location||e.state,{message:"Either location or state is required for map-comparison"}),_t=y.object({keyword:y.string().min(1),domain:y.string().optional(),url:y.string().url().optional(),location:y.string().optional(),maxResults:y.number().int().min(1).max(20).default(10),maxQuestions:y.number().int().min(1).max(100).default(40),extractTop:y.number().int().min(0).max(10).default(5),includePaa:y.boolean().default(!0),includeAiOverview:y.boolean().default(!0),returnPartial:y.boolean().default(!0)}),bt=y.object({keyword:y.string().min(1),location:y.string().optional(),maxQuestions:y.number().int().min(1).max(100).default(80),depth:y.number().int().min(1).max(6).default(3),returnPartial:y.boolean().default(!0)}),kt=y.object({keyword:y.string().min(1),domain:y.string().optional(),url:y.string().url().optional(),location:y.string().optional(),maxQuestions:y.number().int().min(1).max(100).default(40),extractTop:y.number().int().min(0).max(8).default(3),returnPartial:y.boolean().default(!0)});function Rt(e,t,n){return n.map(r=>({source_query:t,source_location:e,city:e.split(",")[0]?.trim()??e,state:e.split(",")[1]?.trim()??"",population:"",result_position:r.position,business_name:r.name,review_stars:r.rating??"",review_count:r.reviewCount??"",category:r.category??"",address:r.address??"",phone:r.phone??"",website_url:r.websiteUrl??"",place_url:r.placeUrl??"",cid:r.cid??"",cid_decimal:r.cidDecimal??"",result_status:"ok",error:""}))}function Je(e){let t=new Map;for(let n of e){let r=String(n.source_location??n.location??"");if(!r)continue;let i=t.get(r)??[];i.push(n),t.set(r,i)}return[...t.entries()].map(([n,r])=>{let i=r.map(c=>H(c.review_count)),s=r.map(c=>H(c.review_stars)),a=r.slice(0,3).map(c=>H(c.review_count)).filter(c=>c!==null),l=new Map;for(let c of r){let p=String(c.category??"");p&&l.set(p,(l.get(p)??0)+1)}return{source_location:n,result_count:r.filter(c=>c.business_name).length,median_review_count:ue(i)??"",median_rating:ue(s)??"",top_three_average_review_count:a.length?Math.round(a.reduce((c,p)=>c+p,0)/a.length):"",top_categories:[...l.entries()].sort((c,p)=>p[1]-c[1]).slice(0,5).map(([c,p])=>`${c} (${p})`).join("; "),websites_present:r.filter(c=>c.website_url).length}})}function St(e){let t=new Map;for(let n of Je(e))t.set(String(n.source_location),H(n.top_three_average_review_count)??0);return e.filter(n=>n.business_name).map(n=>{let r=H(n.review_count)??0,i=t.get(String(n.source_location))??0,s=!n.website_url,a=H(n.result_position)??999;return{source_location:n.source_location,result_position:n.result_position,business_name:n.business_name,category:n.category,review_stars:n.review_stars,review_count:n.review_count,review_gap_to_top3_average:i?Math.max(0,i-r):"",website_url:n.website_url,place_url:n.place_url,comparison_note:a<=3?"visible leader":s?"ranking without website":r<i?"review-light competitor":"visible competitor"}})}function xt(e,t){return(e?.organicResults??[]).map(n=>{let r=n.url??"",i=$(n.domain??"")??A(r);return{position:n.position??"",title:n.title??"",url:r,domain:i,snippet:n.snippet??"",is_target:t?i===t:!1}})}function Ct(e,t){let n=new Set((e?.headings??[]).map(s=>s.text.toLowerCase().replace(/[^a-z0-9\s]/g," ").trim())),r=new Set((e?.headings??[]).flatMap(s=>s.text.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(Boolean))),i=[];for(let{source:s,page:a}of t)for(let l of a.headings??[]){if(l.level>3||!l.text)continue;let c=l.text.toLowerCase().replace(/[^a-z0-9\s]/g," ").trim(),p=c.split(/\s+/).filter(v=>v.length>3),u=p.filter(v=>r.has(v)).length;(n.has(c)||u>=Math.max(2,Math.ceil(p.length/2)))&&e||i.push({source_position:s.position??"",source_domain:$(s.domain??"")??A(s.url),source_url:s.url??"",heading_level:l.level,competitor_heading:l.text,target_coverage:e?"not found in target headings":"no target page extracted",terms:me(l.text,6)})}return i.slice(0,150)}async function de(e,t,n,r){return pe(t.filter(i=>i.url),2,async(i,s)=>{try{let a=await e.client.post("/extract-url",{url:i.url},18e4);return await e.artifacts.writeJson(`${r} ${s+1}`,`raw/extract-url/${r.toLowerCase()}-${s+1}.json`,a),{source:i,page:a}}catch(a){return n.push(`Page extraction failed for ${i.url}: ${a instanceof Error?a.message:String(a)}`),null}}).then(i=>i.filter(s=>s!==null))}var ze={id:"map-comparison",title:"Maps Comparison",description:"Compare Google Maps competitors by rank, reviews, stars, categories, websites, and profile/review signals.",inputSchema:vt,async run(e,t){await t.artifacts.writeManifest("running",{},[],[]);let n=[],r,i=null,s=null;e.location?(s=await t.client.post("/maps/search",{query:e.query,location:e.location,maxResults:e.maxResultsPerCity,proxyMode:e.proxyMode},24e4),r=Rt(e.location,e.query,s.results),await t.artifacts.writeJson("Maps search raw JSON","raw/maps-search.json",s)):(i=await t.client.post("/directory/run",{query:e.query,state:e.state,minPopulation:e.minPopulation,maxCities:e.maxCities,maxResultsPerCity:e.maxResultsPerCity,concurrency:e.concurrency,proxyMode:e.proxyMode,saveCsv:!0,background:!1},9e5),r=Q(i),await t.artifacts.writeJson("Directory raw JSON","raw/directory-workflow.json",i),await t.artifacts.writeCsv("Directory CSV","exports/directory.csv",K,r),n.push(...i.warnings));let a=St(r),l=a.slice(0,e.hydrateTop*Math.max(1,e.location?1:e.maxCities)),p=(await pe(l,3,async(d,k)=>{try{let g=await t.client.post("/maps/place",{businessName:d.business_name,location:d.source_location,includeReviews:e.maxReviews>0,maxReviews:Math.max(1,e.maxReviews)},18e4);return await t.artifacts.writeJson(`${d.business_name} profile`,`raw/maps-place-intel/${k+1}-${String(d.business_name).toLowerCase().replace(/[^a-z0-9]+/g,"-")}.json`,g),{row:d,detail:g,error:""}}catch(g){let o=g instanceof Error?g.message:String(g);return n.push(`Profile hydration failed for ${d.business_name}: ${o}`),{row:d,detail:null,error:o}}})).map(({row:d,detail:k,error:g})=>({source_location:d.source_location,result_position:d.result_position,business_name:d.business_name,category:k?.category??d.category,review_stars:k?.rating??d.review_stars,review_count:k?.reviewCount??d.review_count,website_url:k?.website??d.website_url,review_topics:(k?.reviewTopics??[]).map(o=>`${o.label} (${o.count})`).join("; "),about_attributes:(k?.aboutAttributes??[]).map(o=>`${o.section}: ${o.attribute}`).join("; "),reviews_status:k?.reviewsStatus??"",error:g})),u=Je(r);await t.artifacts.writeCsv("Maps results CSV","maps-results.csv",["source_query","source_location","city","state","population","result_position","business_name","review_stars","review_count","category","address","phone","website_url","place_url","cid","cid_decimal","result_status","error"],r),await t.artifacts.writeCsv("Comparison CSV","map-comparison.csv",["source_location","result_position","business_name","category","review_stars","review_count","review_gap_to_top3_average","website_url","place_url","comparison_note"],a),await t.artifacts.writeCsv("Profile insights CSV","profile-insights.csv",["source_location","result_position","business_name","category","review_stars","review_count","website_url","review_topics","about_attributes","reviews_status","error"],p),await t.artifacts.writeJson("Maps comparison evidence","evidence.json",{input:e,directory:i,mapsSearch:s,rows:r,compareRows:a,profileRows:p,markets:u,warnings:n}),await t.artifacts.writeText("Brief","brief.md",[`# Maps Comparison: ${e.query}`,"",`Markets: ${u.map(d=>d.source_location).join(", ")}`,"","## How to Use","- Compare rank position against review count and category patterns.","- Treat review gaps and missing websites as opportunity signals, not guarantees.","- Use profile topics and attributes as evidence for local content and GBP improvements."].join(`
20
+ `);let b=await t.artifacts.writeHtml("HTML report","report.html",P({title:"Local Competitive Audit",subtitle:`${e.query} \xB7 ${e.state}`,summary:f,warnings:n,tables:[{title:"City Opportunity",columns:["city","state","population","result_count","median_review_count","median_rating","top_three_average_review_count","top_categories","opportunity_score","difficulty_score"],rows:v},{title:"Hydrated Competitors",columns:["city","result_position","business_name","category","review_stars","review_count","hydrated","review_topics"],rows:u.slice(0,100)},{title:"Review Insights",columns:["city","business_name","topics","praise_terms","complaint_terms"],rows:w.slice(0,100)}]})),d=n.length||i.cities.some(g=>g.status==="failed")?"partial":"succeeded",k={cities:i.selectedCityCount,mapsResults:i.totalResultCount,hydratedProfiles:p.filter(g=>g.detail).length};return await t.artifacts.writeManifest(d,k,n,r),{title:"Local Competitive Audit",summary:f,status:d,counts:k,warnings:n,errors:r,reportPath:b}}};import{z as y}from"zod";var ft=new Set(["about","after","also","because","been","best","both","from","have","into","more","most","near","only","over","than","that","their","them","then","there","these","they","this","what","when","where","which","while","with","your","will","would","should","could","does","were","cost","costs"]);function $(e){if(!e)return null;try{return new URL(e.includes("://")?e:`https://${e}`).hostname.replace(/^www\./,"").toLowerCase()}catch{return e.replace(/^https?:\/\//,"").replace(/^www\./,"").split("/")[0]?.toLowerCase()||null}}function A(e){return $(e)??""}function H(e){if(e==null||e==="")return null;let t=Number(String(e).replace(/[^\d.]/g,""));return Number.isFinite(t)?t:null}function ue(e){let t=e.filter(n=>n!==null).sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]??null:null}function me(e,t=12){let n=new Map;for(let r of e.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/))r.length<4||ft.has(r)||n.set(r,(n.get(r)??0)+1);return[...n.entries()].sort((r,i)=>i[1]-r[1]||r[0].localeCompare(i[0])).slice(0,t).map(([r,i])=>`${r} (${i})`).join("; ")}function ht(e){let t=e.toLowerCase();return/\b(cost|price|pricing|charge|expensive|cheap)\b/.test(t)?"cost":/\b(best|top|recommended|reviews?|compare|versus|vs)\b/.test(t)?"comparison":/\b(how|steps?|process|way to)\b/.test(t)?"process":/\b(why|worth|important|benefit)\b/.test(t)?"why":/\b(near me|city|local|nearby)\b/.test(t)?"local":/\b(can|does|do|is|are|should|will)\b/.test(t)?"decision":"definition"}function ee(e){return(e?.flat??[]).filter(t=>t.question).map((t,n)=>{let r=t.source_cite??"",i=$(t.source_site??"")??A(r);return{position:n+1,intent:ht(t.question??""),question:t.question??"",answer_excerpt:(t.answer??"").slice(0,320),source_title:t.source_title??"",source_domain:i,source_url:r}})}function He(e){let t=new Map;for(let n of e){let r=String(n.source_domain??n.domain??"");if(!r)continue;let i=t.get(r)??{questions:0,urls:new Set,intents:new Map};i.questions+=n.question?1:0,(n.source_url||n.url)&&i.urls.add(String(n.source_url??n.url)),n.intent&&i.intents.set(String(n.intent),(i.intents.get(String(n.intent))??0)+1),t.set(r,i)}return[...t.entries()].map(([n,r])=>({domain:n,question_mentions:r.questions,source_url_count:r.urls.size,top_intents:[...r.intents.entries()].sort((i,s)=>s[1]-i[1]).map(([i,s])=>`${i} (${s})`).join("; ")})).sort((n,r)=>Number(r.question_mentions)-Number(n.question_mentions)||String(n.domain).localeCompare(String(r.domain)))}function Be(e){return(e??"").replace(/\s+/g," ").split(/(?<=[.!?])\s+/).map(t=>t.trim()).filter(t=>t.length>20).slice(0,20)}function Ne(e){let t=e.toLowerCase();return/\bis\b|\bare\b|\bmeans\b|\brefers to\b/.test(t)?"definition":/\binclude\b|\bconsider\b|\bfactors?\b|\bcriteria\b/.test(t)?"criteria":/\bfirst\b|\bthen\b|\bsteps?\b|\bprocess\b/.test(t)?"process":/\bvs\b|\bthan\b|\bcompare\b|\bdifference\b/.test(t)?"comparison":/\bcost\b|\bprice\b|\baverage\b|\brange\b/.test(t)?"cost":"claim"}function te(e,t){return{position:t.position??"",domain:t.domain,url:t.url,serp_title:t.title??"",page_title:e.title??"",h1:e.h1??"",meta_description:e.metaDescription??"",word_count:e.wordCount??"",heading_count:e.headings?.length??0,schema_types:(e.schemaTypes??[]).join("; ")}}async function pe(e,t,n){let r=new Array(e.length),i=0;async function s(){for(;i<e.length;){let a=i;i+=1,r[a]=await n(e[a],a)}}return await Promise.all(Array.from({length:Math.min(Math.max(1,t),e.length)},()=>s())),r}var yt=y.enum(["configured","none"]),vt=y.object({query:y.string().min(1),location:y.string().optional(),state:y.string().optional(),minPopulation:y.number().int().min(0).default(1e5),maxCities:y.number().int().min(1).max(100).default(5),maxResultsPerCity:y.number().int().min(1).max(50).default(20),hydrateTop:y.number().int().min(0).max(10).default(5),maxReviews:y.number().int().min(0).max(1e3).default(25),concurrency:y.number().int().min(1).max(5).default(5),proxyMode:yt.default(T),returnPartial:y.boolean().default(!0)}).refine(e=>e.location||e.state,{message:"Either location or state is required for map-comparison"}),_t=y.object({keyword:y.string().min(1),domain:y.string().optional(),url:y.string().url().optional(),location:y.string().optional(),maxResults:y.number().int().min(1).max(20).default(10),maxQuestions:y.number().int().min(1).max(100).default(40),extractTop:y.number().int().min(0).max(10).default(5),includePaa:y.boolean().default(!0),includeAiOverview:y.boolean().default(!0),returnPartial:y.boolean().default(!0)}),bt=y.object({keyword:y.string().min(1),location:y.string().optional(),maxQuestions:y.number().int().min(1).max(100).default(80),depth:y.number().int().min(1).max(6).default(3),returnPartial:y.boolean().default(!0)}),kt=y.object({keyword:y.string().min(1),domain:y.string().optional(),url:y.string().url().optional(),location:y.string().optional(),maxQuestions:y.number().int().min(1).max(100).default(40),extractTop:y.number().int().min(0).max(8).default(3),returnPartial:y.boolean().default(!0)});function Rt(e,t,n){return n.map(r=>({source_query:t,source_location:e,city:e.split(",")[0]?.trim()??e,state:e.split(",")[1]?.trim()??"",population:"",result_position:r.position,business_name:r.name,review_stars:r.rating??"",review_count:r.reviewCount??"",category:r.category??"",address:r.address??"",phone:r.phone??"",website_url:r.websiteUrl??"",place_url:r.placeUrl??"",cid:r.cid??"",cid_decimal:r.cidDecimal??"",result_status:"ok",error:""}))}function Je(e){let t=new Map;for(let n of e){let r=String(n.source_location??n.location??"");if(!r)continue;let i=t.get(r)??[];i.push(n),t.set(r,i)}return[...t.entries()].map(([n,r])=>{let i=r.map(c=>H(c.review_count)),s=r.map(c=>H(c.review_stars)),a=r.slice(0,3).map(c=>H(c.review_count)).filter(c=>c!==null),l=new Map;for(let c of r){let p=String(c.category??"");p&&l.set(p,(l.get(p)??0)+1)}return{source_location:n,result_count:r.filter(c=>c.business_name).length,median_review_count:ue(i)??"",median_rating:ue(s)??"",top_three_average_review_count:a.length?Math.round(a.reduce((c,p)=>c+p,0)/a.length):"",top_categories:[...l.entries()].sort((c,p)=>p[1]-c[1]).slice(0,5).map(([c,p])=>`${c} (${p})`).join("; "),websites_present:r.filter(c=>c.website_url).length}})}function St(e){let t=new Map;for(let n of Je(e))t.set(String(n.source_location),H(n.top_three_average_review_count)??0);return e.filter(n=>n.business_name).map(n=>{let r=H(n.review_count)??0,i=t.get(String(n.source_location))??0,s=!n.website_url,a=H(n.result_position)??999;return{source_location:n.source_location,result_position:n.result_position,business_name:n.business_name,category:n.category,review_stars:n.review_stars,review_count:n.review_count,review_gap_to_top3_average:i?Math.max(0,i-r):"",website_url:n.website_url,place_url:n.place_url,comparison_note:a<=3?"visible leader":s?"ranking without website":r<i?"review-light competitor":"visible competitor"}})}function xt(e,t){return(e?.organicResults??[]).map(n=>{let r=n.url??"",i=$(n.domain??"")??A(r);return{position:n.position??"",title:n.title??"",url:r,domain:i,snippet:n.snippet??"",is_target:t?i===t:!1}})}function Ct(e,t){let n=new Set((e?.headings??[]).map(s=>s.text.toLowerCase().replace(/[^a-z0-9\s]/g," ").trim())),r=new Set((e?.headings??[]).flatMap(s=>s.text.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(Boolean))),i=[];for(let{source:s,page:a}of t)for(let l of a.headings??[]){if(l.level>3||!l.text)continue;let c=l.text.toLowerCase().replace(/[^a-z0-9\s]/g," ").trim(),p=c.split(/\s+/).filter(v=>v.length>3),u=p.filter(v=>r.has(v)).length;(n.has(c)||u>=Math.max(2,Math.ceil(p.length/2)))&&e||i.push({source_position:s.position??"",source_domain:$(s.domain??"")??A(s.url),source_url:s.url??"",heading_level:l.level,competitor_heading:l.text,target_coverage:e?"not found in target headings":"no target page extracted",terms:me(l.text,6)})}return i.slice(0,150)}async function de(e,t,n,r){return pe(t.filter(i=>i.url),2,async(i,s)=>{try{let a=await e.client.post("/extract-url",{url:i.url},18e4);return await e.artifacts.writeJson(`${r} ${s+1}`,`raw/extract-url/${r.toLowerCase()}-${s+1}.json`,a),{source:i,page:a}}catch(a){return n.push(`Page extraction failed for ${i.url}: ${a instanceof Error?a.message:String(a)}`),null}}).then(i=>i.filter(s=>s!==null))}var ze={id:"map-comparison",title:"Maps Comparison",description:"Compare Google Maps competitors by rank, reviews, stars, categories, websites, and profile/review signals.",inputSchema:vt,async run(e,t){await t.artifacts.writeManifest("running",{},[],[]);let n=[],r,i=null,s=null;e.location?(s=await t.client.post("/maps/search",{query:e.query,location:e.location,maxResults:e.maxResultsPerCity,proxyMode:e.proxyMode},24e4),r=Rt(e.location,e.query,s.results),await t.artifacts.writeJson("Maps search raw JSON","raw/maps-search.json",s)):(i=await t.client.post("/directory/run",{query:e.query,state:e.state,minPopulation:e.minPopulation,maxCities:e.maxCities,maxResultsPerCity:e.maxResultsPerCity,concurrency:e.concurrency,proxyMode:e.proxyMode,saveCsv:!0,background:!1},9e5),r=Q(i),await t.artifacts.writeJson("Directory raw JSON","raw/directory-workflow.json",i),await t.artifacts.writeCsv("Directory CSV","exports/directory.csv",K,r),n.push(...i.warnings));let a=St(r),l=a.slice(0,e.hydrateTop*Math.max(1,e.location?1:e.maxCities)),p=(await pe(l,3,async(d,k)=>{try{let g=await t.client.post("/maps/place",{businessName:d.business_name,location:d.source_location,includeReviews:e.maxReviews>0,maxReviews:Math.max(1,e.maxReviews)},18e4);return await t.artifacts.writeJson(`${d.business_name} profile`,`raw/maps-place-intel/${k+1}-${String(d.business_name).toLowerCase().replace(/[^a-z0-9]+/g,"-")}.json`,g),{row:d,detail:g,error:""}}catch(g){let o=g instanceof Error?g.message:String(g);return n.push(`Profile hydration failed for ${d.business_name}: ${o}`),{row:d,detail:null,error:o}}})).map(({row:d,detail:k,error:g})=>({source_location:d.source_location,result_position:d.result_position,business_name:d.business_name,category:k?.category??d.category,review_stars:k?.rating??d.review_stars,review_count:k?.reviewCount??d.review_count,website_url:k?.website??d.website_url,review_topics:(k?.reviewTopics??[]).map(o=>`${o.label} (${o.count})`).join("; "),about_attributes:(k?.aboutAttributes??[]).map(o=>`${o.section}: ${o.attribute}`).join("; "),reviews_status:k?.reviewsStatus??"",error:g})),u=Je(r);await t.artifacts.writeCsv("Maps results CSV","maps-results.csv",["source_query","source_location","city","state","population","result_position","business_name","review_stars","review_count","category","address","phone","website_url","place_url","cid","cid_decimal","result_status","error"],r),await t.artifacts.writeCsv("Comparison CSV","map-comparison.csv",["source_location","result_position","business_name","category","review_stars","review_count","review_gap_to_top3_average","website_url","place_url","comparison_note"],a),await t.artifacts.writeCsv("Profile insights CSV","profile-insights.csv",["source_location","result_position","business_name","category","review_stars","review_count","website_url","review_topics","about_attributes","reviews_status","error"],p),await t.artifacts.writeJson("Maps comparison evidence","evidence.json",{input:e,directory:i,mapsSearch:s,rows:r,compareRows:a,profileRows:p,markets:u,warnings:n}),await t.artifacts.writeText("Brief","brief.md",[`# Maps Comparison: ${e.query}`,"",`Markets: ${u.map(d=>d.source_location).join(", ")}`,"","## How to Use","- Compare rank position against review count and category patterns.","- Treat review gaps and missing websites as opportunity signals, not guarantees.","- Use profile topics and attributes as evidence for local content and GBP improvements."].join(`
21
21
  `));let w=`${a.length} Maps competitors compared across ${u.length} market(s); ${p.filter(d=>!d.error).length} profiles hydrated.`,v=await t.artifacts.writeHtml("HTML report","report.html",P({title:"Maps Comparison",subtitle:`${e.query}${e.location?` \xB7 ${e.location}`:e.state?` \xB7 ${e.state}`:""}`,summary:w,warnings:n,tables:[{title:"Market Benchmarks",columns:["source_location","result_count","median_review_count","median_rating","top_three_average_review_count","top_categories","websites_present"],rows:u},{title:"Competitor Comparison",columns:["source_location","result_position","business_name","category","review_stars","review_count","review_gap_to_top3_average","comparison_note"],rows:a.slice(0,120)},{title:"Profile Insights",columns:["source_location","business_name","review_topics","about_attributes","error"],rows:p}]})),f=n.length?"partial":"succeeded",b={markets:u.length,competitors:a.length,hydratedProfiles:p.filter(d=>!d.error).length};return await t.artifacts.writeManifest(f,b,n,[]),{title:"Maps Comparison",summary:w,status:f,counts:b,warnings:n,errors:[],reportPath:v}}},Ve={id:"serp-comparison",title:"SERP Comparison",description:"Compare ranking pages, SERP features, PAA evidence, AI Overview citations, and page-level content gaps.",inputSchema:_t,async run(e,t){await t.artifacts.writeManifest("running",{},[],[]);let n=[],r=$(e.domain??e.url??null),i=await t.client.post("/harvest/sync",{query:e.keyword,location:e.location,serpOnly:!0,includeAllSerpFeatures:!0,maxQuestions:1,format:"json"},62e4);await t.artifacts.writeJson("SERP raw JSON","raw/serp.json",i);let s=null;if(e.includePaa)try{s=await t.client.post("/harvest/sync",{query:e.keyword,location:e.location,maxQuestions:e.maxQuestions,includeAllSerpFeatures:!0,format:"json"},735e3),await t.artifacts.writeJson("PAA raw JSON","raw/paa.json",s)}catch(m){n.push(`PAA evidence unavailable: ${m instanceof Error?m.message:String(m)}`)}let a=xt(i,r).slice(0,e.maxResults),l=(i.organicResults??[]).slice(0,e.maxResults),c=e.url?{position:0,title:"Target page",url:e.url,domain:A(e.url)}:l.find(m=>r&&($(m.domain??"")??A(m.url))===r),p=l.filter(m=>m.url&&m.url!==c?.url).filter(m=>!r||($(m.domain??"")??A(m.url))!==r).slice(0,e.extractTop),u=c?await de(t,[c],n,"Target"):[],w=e.extractTop>0?await de(t,p,n,"Competitor"):[],v=u[0]?.page??null,f=[...u.map(({source:m,page:x})=>te(x,{url:m.url??"",domain:$(m.domain??"")??A(m.url),position:m.position,title:m.title})),...w.map(({source:m,page:x})=>te(x,{url:m.url??"",domain:$(m.domain??"")??A(m.url),position:m.position,title:m.title}))],b=Ct(v,w),d=ee(s),k=(i.aiOverview?.citations??[]).map((m,x)=>({citation_position:x+1,citation_text:m.text??"",url:m.href??"",domain:A(m.href??""),is_target:r?A(m.href??"")===r:!1}));await t.artifacts.writeCsv("Organic results CSV","organic-results.csv",["position","title","url","domain","snippet","is_target"],a),await t.artifacts.writeCsv("Page comparison CSV","page-comparison.csv",["position","domain","url","serp_title","page_title","h1","meta_description","word_count","heading_count","schema_types"],f),await t.artifacts.writeCsv("Content gaps CSV","content-gaps.csv",["source_position","source_domain","source_url","heading_level","competitor_heading","target_coverage","terms"],b),await t.artifacts.writeCsv("PAA questions CSV","paa-questions.csv",["position","intent","question","answer_excerpt","source_title","source_domain","source_url"],d),await t.artifacts.writeCsv("AI Overview citations CSV","ai-overview-citations.csv",["citation_position","citation_text","url","domain","is_target"],k),await t.artifacts.writeJson("SERP comparison evidence","evidence.json",{input:e,serp:i,paa:s,organic:a,pageRows:f,gaps:b,questions:d,aiRows:k,warnings:n}),await t.artifacts.writeText("Writer brief","brief.md",[`# SERP Comparison Brief: ${e.keyword}`,"",`Target: ${r??e.url??"not specified"}`,`Location: ${e.location??"not specified"}`,"","## Recommended Actions","- Use `content-gaps.csv` to decide which missing sections deserve coverage.","- Use `paa-questions.csv` for FAQ and answer-block candidates.","- Use `ai-overview-citations.csv` to see whether the target is cited in AI Overview evidence.","- Treat extracted page headings as evidence, not a complete semantic analysis."].join(`
22
22
  `));let g=`${a.length} organic results, ${f.length} extracted pages, ${b.length} heading gaps, ${d.length} PAA questions.`,o=await t.artifacts.writeHtml("HTML report","report.html",P({title:"SERP Comparison",subtitle:`${e.keyword}${e.location?` \xB7 ${e.location}`:""}`,summary:g,warnings:n,tables:[{title:"Organic Results",columns:["position","title","domain","is_target"],rows:a},{title:"Page Comparison",columns:["position","domain","h1","word_count","heading_count","schema_types"],rows:f},{title:"Content Gaps",columns:["source_position","source_domain","competitor_heading","target_coverage","terms"],rows:b.slice(0,80)},{title:"PAA Questions",columns:["position","intent","question","source_domain"],rows:d.slice(0,80)}]})),h=n.length?"partial":"succeeded",R={organic:a.length,pages:f.length,gaps:b.length,questions:d.length,aiCitations:k.length};return await t.artifacts.writeManifest(h,R,n,[]),{title:"SERP Comparison",summary:g,status:h,counts:R,warnings:n,errors:[],reportPath:o}}},Fe={id:"paa-expansion-brief",title:"PAA Expansion Brief",description:"Expand People Also Ask questions into an evidence-backed writer brief, section map, and source table.",inputSchema:bt,async run(e,t){await t.artifacts.writeManifest("running",{},[],[]);let n=[],r=await t.client.post("/harvest/sync",{query:e.keyword,location:e.location,maxQuestions:e.maxQuestions,depth:e.depth,format:"json"},735e3);await t.artifacts.writeJson("PAA raw JSON","raw/paa.json",r);let i=ee(r),s=He(i),a=new Map;for(let w of i){let v=a.get(String(w.intent))??[];v.push(w),a.set(String(w.intent),v)}let l=[...a.entries()].map(([w,v])=>({recommended_section:w,question_count:v.length,sample_questions:v.slice(0,5).map(f=>f.question).join(" | "),source_domains:[...new Set(v.map(f=>f.source_domain).filter(Boolean))].slice(0,5).join("; "),terms:me(v.map(f=>`${f.question} ${f.answer_excerpt}`).join(" "),10)})).sort((w,v)=>Number(v.question_count)-Number(w.question_count));await t.artifacts.writeCsv("PAA questions CSV","paa-questions.csv",["position","intent","question","answer_excerpt","source_title","source_domain","source_url"],i),await t.artifacts.writeCsv("Source domains CSV","source-domains.csv",["domain","question_mentions","source_url_count","top_intents"],s),await t.artifacts.writeCsv("Section map CSV","section-map.csv",["recommended_section","question_count","sample_questions","source_domains","terms"],l),await t.artifacts.writeJson("PAA brief evidence","evidence.json",{input:e,paa:r,questions:i,sourceRows:s,sectionRows:l}),await t.artifacts.writeText("Writer brief","writer-brief.md",[`# PAA Expansion Brief: ${e.keyword}`,"",`Location: ${e.location??"not specified"}`,"","## Suggested Page Structure",...l.map(w=>`- ${w.recommended_section}: answer ${w.question_count} related question(s). Sample: ${w.sample_questions}`),"","## Writing Rules","- Answer the highest-frequency question in the first 60 words of each section.","- Use exact customer question language from `paa-questions.csv` for H2/H3 candidates.","- Use `source-domains.csv` to identify which source types Google is already rewarding.","- Do not invent citations; cite only rows that have a source URL."].join(`
23
23
  `));let c=`${i.length} PAA questions grouped into ${l.length} writing sections.`,p=await t.artifacts.writeHtml("HTML report","report.html",P({title:"PAA Expansion Brief",subtitle:`${e.keyword}${e.location?` \xB7 ${e.location}`:""}`,summary:c,warnings:n,tables:[{title:"Section Map",columns:["recommended_section","question_count","sample_questions","source_domains","terms"],rows:l},{title:"Questions",columns:["position","intent","question","source_domain"],rows:i.slice(0,120)},{title:"Source Domains",columns:["domain","question_mentions","source_url_count","top_intents"],rows:s}]})),u={questions:i.length,sections:l.length,sourceDomains:s.length};return await t.artifacts.writeManifest("succeeded",u,n,[]),{title:"PAA Expansion Brief",summary:c,status:"succeeded",counts:u,warnings:n,errors:[],reportPath:p}}},Ge={id:"ai-overview-language",title:"AI Overview Language Brief",description:"Turn AI Overview, citation, PAA, and ranking-page evidence into answer-block and citation-hook guidance.",inputSchema:kt,async run(e,t){await t.artifacts.writeManifest("running",{},[],[]);let n=[],r=$(e.domain??e.url??null),i=await t.client.post("/harvest/sync",{query:e.keyword,location:e.location,serpOnly:!0,includeAiOverview:!0,maxQuestions:1,format:"json"},62e4);await t.artifacts.writeJson("SERP raw JSON","raw/serp.json",i);let s=null;try{s=await t.client.post("/harvest/sync",{query:e.keyword,location:e.location,maxQuestions:e.maxQuestions,includeAiOverview:!0,format:"json"},735e3),await t.artifacts.writeJson("PAA raw JSON","raw/paa.json",s)}catch(o){n.push(`PAA evidence unavailable: ${o instanceof Error?o.message:String(o)}`)}let a=(i.aiOverview?.citations??[]).map((o,h)=>{let R=A(o.href??"");return{citation_position:h+1,citation_text:o.text??"",url:o.href??"",domain:R,is_target:r?R===r:!1}}),c=Be(i.aiOverview?.text).map((o,h)=>({position:h+1,claim_type:Ne(o),sentence:o,reusable_pattern:o.length>140?`${o.slice(0,140)}...`:o})),p=ee(s),u=(i.aiOverview?.citations??[]).filter(o=>o.href).map((o,h)=>({position:h+1,title:o.text,url:o.href,domain:A(o.href)})).slice(0,e.extractTop),v=(e.extractTop>0?await de(t,u,n,"Citation"):[]).map(({source:o,page:h})=>te(h,{url:o.url??"",domain:$(o.domain??"")??A(o.url),position:o.position,title:o.title})),f=[{block:"direct_answer",guidance:"Open with a 40-70 word answer that directly resolves the query before adding context.",evidence_basis:p[0]?.question??e.keyword},{block:"criteria_or_steps",guidance:"List the criteria, steps, or decision factors Google is already compressing into AI Overview language.",evidence_basis:c.filter(o=>["criteria","process"].includes(String(o.claim_type))).map(o=>o.sentence).slice(0,3).join(" | ")},{block:"citation_hook",guidance:"Add source-worthy details competitors can cite: definitions, numbers, examples, process details, and named entity relationships.",evidence_basis:a.map(o=>`${o.domain}: ${o.citation_text}`).slice(0,5).join(" | ")},{block:"faq_followups",guidance:"Use PAA phrasing for follow-up sections so the page answers adjacent questions in Google language.",evidence_basis:p.slice(0,5).map(o=>o.question).join(" | ")}];await t.artifacts.writeCsv("AI Overview citations CSV","ai-overview-citations.csv",["citation_position","citation_text","url","domain","is_target"],a),await t.artifacts.writeCsv("AI Overview claim patterns CSV","claim-patterns.csv",["position","claim_type","sentence","reusable_pattern"],c),await t.artifacts.writeCsv("Language guidance CSV","language-guidance.csv",["block","guidance","evidence_basis"],f),await t.artifacts.writeCsv("PAA questions CSV","paa-questions.csv",["position","intent","question","answer_excerpt","source_title","source_domain","source_url"],p),await t.artifacts.writeCsv("Extracted citation pages CSV","citation-pages.csv",["position","domain","url","serp_title","page_title","h1","meta_description","word_count","heading_count","schema_types"],v),await t.artifacts.writeJson("AI Overview language evidence","evidence.json",{input:e,serp:i,paa:s,citations:a,claimRows:c,languageRows:f,extractedRows:v,warnings:n}),await t.artifacts.writeText("Answer block template","answer-block-template.md",[`# AI Overview Language Brief: ${e.keyword}`,"",`AI Overview detected: ${i.aiOverview?.detected?"yes":"no"}`,`Target cited: ${r?a.some(o=>o.is_target)?"yes":"no":"target not specified"}`,"","## Direct Answer Block","Write one compact answer block that starts with the answer, not background. Keep it clear enough that Google could lift it as a standalone summary.","","## Suggested Follow-Up Blocks",...f.map(o=>`- ${o.block}: ${o.guidance}`),"","## Evidence to Mirror",...c.slice(0,8).map(o=>`- ${o.claim_type}: ${o.sentence}`),"","## Citation Hooks",...a.slice(0,8).map(o=>`- ${o.domain}: ${o.citation_text}`)].join(`