@leadbay/mcp 0.36.0 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1309,6 +1309,170 @@ After I answer, call \`leadbay_report_outreach({lead_id: '{{arg:lead_id}}', note
1309
1309
  # PHASE 3 \u2014 CONFIRM
1310
1310
  Tell me the outreach was logged, name the verification.source used, and surface the response's \`outreach_id\` if present so I can refer back to it.
1311
1311
  `;
1312
+ var leadbay_new_leads = `
1313
+ ## WHAT LEADBAY SHOULD REMEMBER
1314
+
1315
+ You keep your own memory of how this user likes to work \u2014 tone, naming, formatting, what they ask you to skip. Leadbay does not store that and does not need to.
1316
+
1317
+ What Leadbay does need is anything that changes **who it should find**. When the user states targeting criteria in conversation ("I target fleets over 100 vehicles", "carriers are a bad fit unless they do last-mile delivery", "climate engineering is also my market"), call \`leadbay_refine_prompt\` so it changes what Leadbay surfaces for the whole org and on every future refresh \u2014 not just this conversation. When they say a specific lead is wrong for them, record the dislike rather than noting it.
1318
+
1319
+
1320
+ IRON LAW \u2014 NO FABRICATION. Every lead id, contact email, custom field id, mapping decision, and tool argument must trace to a value you read from the file the user attached or to an output from a leadbay_* tool call in this session. Do not invent values. Do not "fill in" a missing leadId with a name match. Do not synthesize a CRM id from a guess. If a value is missing, leave the field blank and say so.
1321
+
1322
+
1323
+ GATE \u2014 DEFER TO TOOL RENDERING. When you call a Leadbay composite that ships its own RENDERING block (every composite in 0.9.0+ does), render the response using that block's recipe verbatim \u2014 score bars, glyph palette, column order, hide-list, link priorities, all of it. Do NOT substitute prose, a numbered list, or a different column structure even when an orchestrating prompt's body suggests alternate framing. Prompt-specific commentary (motivational nudges, summaries, next-action recommendations) belongs ABOVE or BELOW the canonical table, never in place of it.
1324
+
1325
+ If the prompt's body and the tool's RENDERING appear to conflict, the tool's RENDERING wins for the structural layout; the prompt's voice wins for the commentary that surrounds it.
1326
+
1327
+
1328
+ **First, check \`leadbay_find_new_leads\` is in your tool set.** Every phase below
1329
+ calls it or \`leadbay_qualify_leads\`, and both are write-tier: on a read-only
1330
+ deployment (\`LEADBAY_MCP_WRITE=0\`) neither is registered. The MCP prompt hides
1331
+ itself there; this file is a static Claude skill with no runtime gate, so the
1332
+ check has to be here. If they're missing: say plainly that net-new search isn't
1333
+ enabled on this connection, and offer \`leadbay_pull_leads\` for today's batch
1334
+ instead. Starting a workflow whose first call does not exist is worse than
1335
+ saying so up front.
1336
+
1337
+ Find net-new leads for me. My need, in my words:
1338
+
1339
+ > {{arg:need}}
1340
+
1341
+ If that need was not supplied to you directly, take it from the message that
1342
+ started this \u2014 the request in my own words is the need, and I should never be
1343
+ asked to repeat something I already said. Only when BOTH are missing or too
1344
+ vague to name (a) who I sell to and (b) roughly how many leads I want, ask me
1345
+ ONCE \u2014 one short question \u2014 then proceed. Default count when unstated: 10.
1346
+
1347
+ # PHASE 1 \u2014 UNDERSTAND THE BUYER (no tool calls yet)
1348
+
1349
+ From my words, work out:
1350
+ - What I SELL and therefore WHO WRITES ME CHECKS \u2014 the buyer category, never
1351
+ the buyer's customers, never my competitors. If my product helps companies
1352
+ of type X serve audience Y, my buyer is X.
1353
+ - Hard constraints: geography, size band, sector, exclusions ("no
1354
+ franchises", "pas de grands groupes" \u2014 negatives BIND).
1355
+ - Contact needs: do I want a person? Which titles? Email, phone, both?
1356
+ - Buyer archetypes: if my need genuinely spans two different kinds of buyer,
1357
+ plan one search per archetype \u2014 never one blended seed.
1358
+
1359
+ # PHASE 2 \u2014 CRAFT THE SEED
1360
+
1361
+ Compose the \`example_lead\` for each archetype following the craft rules in
1362
+ the leadbay_find_new_leads description (registry-style description of a
1363
+ FICTIONAL typical buyer; no invented brand name; no event language; hard
1364
+ constraints go in \`filters\` with the FLAT keys \`employees_min\`/\`employees_max\`
1365
+ and city/state/region \`locations\` \u2014 never a country name). Show me the seed
1366
+ description(s) in one line each \u2014 I should recognize my ideal customer in
1367
+ them.
1368
+
1369
+ \`filters\` only encodes sectors, locations and employee bounds. Any constraint
1370
+ that does not fit those keys \u2014 above all EXCLUSIONS like "no franchises" or
1371
+ "pas de grands groupes" \u2014 has nowhere to live in the filter schema, so it must
1372
+ not be dropped on the floor: express it positively in the seed \`description\`
1373
+ (an independent single-site operator rather than "no franchises"), and carry
1374
+ the exclusion forward yourself to Phase 5, where you drop violating rows and
1375
+ say you dropped them. Tell me plainly if a constraint can only be enforced
1376
+ that way \u2014 after the fact, not by the search.
1377
+
1378
+ Composing this fictional seed from my words is expected and permitted: it is
1379
+ the tool's designed input, not fabricated data. What must never be invented is
1380
+ a RESULT \u2014 company names, contacts, scores, or anything presented as coming
1381
+ back from Leadbay.
1382
+
1383
+ # PHASE 3 \u2014 FREE PREVIEW
1384
+
1385
+ Call \`leadbay_find_new_leads\` with the seed, \`filters\`, \`count\`,
1386
+ \`qualify: false\`, no channels \u2014 this is FREE \u2014 and a \`request_id\` derived
1387
+ from the ask + the ARCHETYPE + today's date. \`count\` is the TOTAL I asked
1388
+ for, not a per-search number: with two archetypes and a request for 10,
1389
+ split it (5 + 5, or whatever weighting fits my ask) rather than sending 10
1390
+ to each \u2014 otherwise I get 20 leads and, on the paid pass, pay for 20.
1391
+
1392
+ When you RETRY a search \u2014 it timed out, or the job is still live \u2014 reuse the
1393
+ \`request_id\` you already sent, verbatim. Do not recompute it: rederiving from
1394
+ "today's date" after midnight yields a new key, the backend cannot dedupe, and
1395
+ a second paid, novelty-claiming search launches. Roll the date only when I am
1396
+ genuinely asking for a new batch. The archetype component is not
1397
+ optional: \`request_id\` is the idempotency key, so two archetype searches
1398
+ sharing one id dedupe to the same job and the second archetype is never
1399
+ searched. Render the delivery table and judge fit honestly: are these the
1400
+ kind of companies I asked for?
1401
+
1402
+ - **\`still_running: true\`** \u2192 the job is ALIVE. Do not judge the seed and do
1403
+ not relaunch \u2014 poll \`leadbay_lead_job_status\` (\`wait_seconds: 60\`) until
1404
+ it goes terminal, reporting progress. Relaunching now burns an active-job
1405
+ slot and rate-limit budget on a search that may be about to deliver.
1406
+ - **On-profile** (terminal) \u2192 offer Phase 4.
1407
+ - **Off-profile or empty** (terminal) \u2192 read \`funnel\` +
1408
+ \`explain.scope_notes\`, tell me what went wrong in one line (wrong
1409
+ archetype? too narrow a filter? thin universe?), reshape the seed or
1410
+ filters, and retry under a NEW request_id. Reshaping is free; do not pay
1411
+ to explore a bad seed.
1412
+
1413
+ # PHASE 4 \u2014 PAID DEPTH (only with my explicit go-ahead)
1414
+
1415
+ When I want qualification evidence and/or reachable contacts:
1416
+ 1. Quote first: \`dry_run: true\` on the tool you will actually run, with the
1417
+ exact flags I asked for, and tell me the worst-case cost in plain money.
1418
+ The two tools take DIFFERENT flags \u2014 passing the wrong one is rejected
1419
+ outright (\`additionalProperties: false\`):
1420
+ - \`leadbay_qualify_leads\`: \`qualify: true\`, \`contact_titles\`,
1421
+ \`title_gate\`, \`channels\`, \`max_cost\`. **No \`min_ai_score\`.**
1422
+ - \`leadbay_find_new_leads\`: the same, PLUS \`min_ai_score\` and \`count\`.
1423
+ 2. On my go-ahead, prefer feeding the free preview's deliveries to
1424
+ \`leadbay_qualify_leads\` (\`prior_deliveries: {job_id}\`) \u2014 one paid pass PER
1425
+ preview job when Phase 3 ran several archetypes, or merge their delivered
1426
+ refs into a single \`lead_refs\` call. Never qualify just the first job and
1427
+ call it done: the other archetypes are part of what I asked for. It only
1428
+ spends on
1429
+ companies already known to match. Paid calls need \`confirm: true\`; without
1430
+ it the tool withholds the submit and hands back a quote instead of
1431
+ spending. That applies to \`leadbay_find_new_leads\` too whenever you set
1432
+ \`qualify: true\` or ask for channels.
1433
+
1434
+ If the preview delivered FEWER than I asked for, do both halves and do not
1435
+ conflate them: qualify what the preview already found, and run the fresh
1436
+ search only for the SHORTFALL \u2014 \`count\` = what is still missing, never the
1437
+ original number, under a NEW \`request_id\`. Reusing the preview's id dedupes
1438
+ the paid submit back into the free job; keeping the original count buys a
1439
+ whole second batch, because \`novelty: org\` already excludes everything the
1440
+ preview delivered.
1441
+
1442
+ The same arithmetic applies AFTER the paid pass. A full-count preview can
1443
+ still end short once qualification disqualifies rows or a strict title /
1444
+ channel match misses: what I asked for is n QUALIFIED, CONTACTABLE leads,
1445
+ not n examined. Count the delivered-and-callable rows; if they fall short,
1446
+ tell me the gap in one line and offer to top it up \u2014 another shortfall-sized
1447
+ search under a NEW \`request_id\`, quoted first like any paid run. Never
1448
+ silently hand back fewer than I asked for and paid toward.
1449
+
1450
+ Pass the leads already EXAMINED-AND-REJECTED into that top-up's
1451
+ \`exclude_lead_ids\` \u2014 disqualified and skipped, from both the preview and
1452
+ the paid pass. \`novelty: org\` already excludes prior DELIVERIES, so
1453
+ delivered ids are redundant there; the rejected ones are exactly what it
1454
+ misses, and without them the top-up re-picks the same misses and charges
1455
+ again to close no gap. **\`exclude_lead_ids\` caps at 500** \u2014 a wide
1456
+ \`exploration_cap\` can examine more than that, so send the most recent 500
1457
+ rejects rather than an over-long list the tool refuses outright.
1458
+ 3. While the job runs, poll with \`leadbay_lead_job_status\`
1459
+ (\`wait_seconds: 60\`); report progress, not silence.
1460
+
1461
+ # PHASE 5 \u2014 DELIVER
1462
+
1463
+ Before rendering, sanity-check every row: geography inside my fence (drop
1464
+ and call out same-named-city leaks), descriptions actually matching my ask
1465
+ (especially when \`explain.seed_strategy\` is \`text_match_exemplars\` \u2014 fit
1466
+ scores run hot there), visible violations of my exclusions dropped. If the
1467
+ best fit is under 30, say "weak matches only" and propose reshaping before
1468
+ showing more than 3.
1469
+
1470
+ Render per the lead-delivery table, then ALWAYS the funnel line: matched /
1471
+ examined / qualified / disqualified / delivered / stop reason / spend. Zero
1472
+ delivered gets a diagnosis and a concrete next move, never a shrug. Close
1473
+ with NEXT STEPS from the tool description \u2014 and STOP; take no further action
1474
+ without my say-so.
1475
+ `;
1312
1476
  var leadbay_plan_tour_in_city = `
1313
1477
  Plan a field sales tour for me in **{{arg:city}}**{{arg:date_paren}}.
1314
1478
 
@@ -2702,6 +2866,14 @@ that's leadbay_prospecting_overview.
2702
2866
  `, "arguments": [], "expected_calls": ["leadbay_account_status", "leadbay_pull_leads", "leadbay_prepare_outreach", "leadbay_enrich_titles", "leadbay_bulk_enrich_status"], "failure_modes": ['Presents a gate as prose ("let me know if you want me to pull your leads") instead of CALLING the host choice widget \u2014 the click IS the lesson, and prose turns the walkthrough into a lecture', "Runs a step's tool WITHOUT firing that step's widget first and waiting for the click \u2014 the walkthrough becomes an automated demo the user only watches, which is the exact opposite of learning by doing", "Fires the widget without the EXPLAIN beat, so the user gets an unexplained button and learns nothing about what a lens or an enrichment actually is", 'Answers gate 1 with a bare "you\'re connected as X at Y" when the quota IS readable \u2014 the user clicked a button labelled `check my account status`, so the quota windows (Daily/Weekly/Monthly gauges, % used, $ spent, resets) ARE the answer, not an optional extra', 'Renders quota as raw "credits" instead of the web app\'s percentage + dollar-spend gauges, or dumps raw `resource_type` strings the user has never seen', "Opens with a wall of text \u2014 previewing all four steps, explaining lenses up front, or writing several paragraphs before the first widget. The opening is TWO lines then the button; a first-run user wants to see it work, not read a syllabus", `Ends the first message without firing gate 1's widget, leaving the user to reply "ok" before anything happens`, "Rewrites the gate's own `next_steps` payload (its `question`, `label` or `description`) instead of mapping it into the widget verbatim, or merges two gates into a single multi-option widget", 'Fires a THIRD option, or turns the exit into an alternative route ("show me my lenses instead") \u2014 each gate carries exactly one forward action plus the `I\'m done for now` exit, never a menu of paths', `Fires a single-option widget \u2014 the host requires 2\u20134 options, so a lone option is rejected or silently degrades to prose ("say the word and I'll check it"), which is the exact defect this rule exists to prevent`, 'Launches the PAID reveal at gate 4 BEFORE the user has picked leads and confirmed \u2014 beat 1 must be the free `mode:"discover"` preview (no `titles`, no `confirm`, no `email`, no `phone`); the gate click bought the free look, not the reveal, and silence is never consent', "Stops at the free preview after the user DID pick leads and confirm \u2014 they asked for real contact details, so the second call must actually run with `confirm:true` and the chosen titles", "Reports the enrichment without polling `leadbay_bulk_enrich_status` to completion, so it claims contacts it never actually saw resolve", `Reveals contacts and never says what it cost \u2014 the user just spent credits and deserves the one-line "N contacts = N credits", which is also what makes gate 1's quota numbers concrete`, 'Reports "no leads" on an empty batch while `computing_wishlist` / `computing_scores` is true \u2014 the lens is still building; render the tool\'s own two-option warm-up widget verbatim and pause', "Rewords, reorders or prose-ifies the `next_steps` payload from `leadbay_pull_leads` instead of mapping `options[]` into the widget verbatim", "Runs all four steps in one turn without waiting for the user's click between gates \u2014 the walkthrough is a sequence of gates, not a script to recite", "Skips `leadbay_pull_leads` and jumps straight to enrichment, leaving gate 4 with no `leadIds` to scope", "Passes a singular `leadId` to `leadbay_enrich_titles` on the confirmed reveal \u2014 that key does not exist on this tool, so it is dropped and the paid call falls back to the whole default wishlist selection, charging for far more than the one lead the user agreed to. it is always the `leadIds` ARRAY, even for a single lead", "Drops the pinned `lens.id` between gates, so gate 4 enriches against a different lens than the one the user just saw", "Ends the completed walkthrough without the `keep_going` cheat-sheet \u2014 the buttons disappear with the tour, so a user who was never told what to TYPE learned to click a tutorial and nothing about using Leadbay tomorrow", "Invents phrases for the cheat-sheet, or rewords them into something that sounds nicer but doesn't match the tool's real triggers \u2014 teaching a phrase that doesn't route is worse than teaching none", "SENDS the gate 3 draft, or offers to send it \u2014 the walkthrough drafts and stops there; the email is the user's to judge, and nothing leaves the chat", "Passes `enrich:true` to `leadbay_prepare_outreach` at gate 3 \u2014 that launches a PAID contact reveal off the back of a DRAFT click, spending credits the user never agreed to", "Invents a contact NAME for the gate 3 draft \u2014 `recommended_contact` still has null email/name at that point, so the draft is addressed to the job TITLE; a fabricated name is the one thing that makes the whole draft untrustworthy", "Treats the null email at gate 3 as a failure \u2014 apologising for it, retrying, or calling another tool to fill it in. It is the setup for gate 4 \u2014 an email written, nobody to send it to yet", "Pastes the drafted email into chat prose alongside `message_compose_v1` instead of letting the composer BE the answer", "Enriches leads other than the one it drafted for at gate 3 \u2014 gate 4 reveals the person that email is going to, so it is scoped to that ONE lead, one contact, one credit", "Renders the cheat-sheet on the exit and stops there, dropping the 1:1 offer \u2014 the observed failure is that the agent feels finished once the table is on screen, so the user who just stepped out never hears about the help that would bring them back. ENDING B is not complete without the offer, and the offer goes LAST", "Treats the exit click as ENDING C (typed off-script) and closes in silence, or treats a typed request as ENDING B and buries their real answer under a cheat-sheet and a booking link", "Turns the exit offer into a pitch \u2014 several sentences, a re-opened gate, or an argument for finishing the tour. They said they were done; it is one line and a link", "Fires the 1:1 offer mid-tour, or at a user who left by TYPING a different request \u2014 a booking link on top of their real question is an interruption, not an offer", "Runs the four gates at a user whose actual problem is SETUP \u2014 the connector isn't installed, they can't sign in, or their Leadbay tools aren't appearing. The tour assumes a working connection and cannot fix any of it; the setup guide can", "Pastes the setup-guide link mid-tour, between gates, instead of once at the closing \u2014 a link in the middle of the walkthrough invites the user to leave the thing they're doing"] },
2703
2867
  leadbay_import_file: { "name": "leadbay_import_file", "short_description": "Import a user-supplied CSV/file into Leadbay through five phases with\nevidence gates \u2014 scan, derive, resolve identities, preserve & commit,\nthen optionally qualify and report. The job is to maximize how many\nrows the Leadbay system actually ingests and matches.\n", "arguments": [{ "name": "file", "description": "Path or user-visible name of the CSV/file to import. If omitted, use the file the user attached or referenced.", "required": false }, { "name": "instruction", "description": 'Additional user goal, e.g. "then qualify the leads", "preserve owner phone as a custom field", or "only import restaurants in Manhattan".', "required": false }], "expected_calls": ["leadbay_resolve_import_rows", "leadbay_list_mappable_fields", "leadbay_create_custom_field", "leadbay_import_leads", "leadbay_import_and_qualify", "leadbay_add_note", "leadbay_import_status"], "failure_modes": ["Picks LEADBAY_ID from score alone, name-only, fuzzy-name-only, root-domain-only, brand-only, postcode-only, or city-only evidence", "Drops meaningful business notes or CRM record links instead of preserving them as custom fields or lead notes", "Treats a consumer mailbox domain (gmail.com, hotmail.com, ...) as the company domain", "Skips deriving company_domain from a business email when no website column exists (this kills match rate)", "Skips the COLUMN PRESERVATION PLAN byproduct before importing", "Skips the DECISION LOG byproduct before writing LEADBAY_ID", "Returns the imported records WITHOUT writing LEADBAY_ID values back into the user's file (leaves the user no audit trail of what matched)", "Fabricates leadIds, contact emails, or mapping IDs not present in the file or a tool response"] },
2704
2868
  leadbay_log_outreach: { "name": "leadbay_log_outreach", "short_description": "Log outreach (an email I sent, a call I made, a meeting I had) on a\nspecific lead. Captures verification so the SDR pipeline trusts the entry.\n", "arguments": [{ "name": "lead_id", "description": "The lead UUID. Get it from leadbay_pull_leads or leadbay_research_lead_by_id.", "required": true }, { "name": "summary", "description": "1-2 sentences describing what I did (e.g. 'Sent intro email to CTO citing recent Hornsea contract').", "required": true }], "expected_calls": ["leadbay_report_outreach"], "failure_modes": ["Calls leadbay_report_outreach without first collecting a verification source", "Fabricates a gmail_message_id or calendar_event_id (the human team treats verification as canonical)", "Records outreach to a different lead_id than the one the user supplied", "Skips the dry_run step when the user is unsure what would be sent"] },
2869
+ leadbay_new_leads: { "name": "leadbay_new_leads", "short_description": `Guided net-new lead delivery \u2014 turn a described need ("gyms around Dallas
2870
+ that would buy our flooring") into ICP-perfect NEW companies with
2871
+ qualification evidence and the right contact, via leadbay_find_new_leads.
2872
+ Trigger when the user DESCRIBES who they want: "get me N companies that
2873
+ <profile>", "we're entering <market>". A bare "find me new leads" with no
2874
+ profile, and "today's leads", are the daily lens batch \u2014 leadbay_pull_leads.
2875
+ "Qualify these companies I have" is leadbay_qualify_leads.
2876
+ `, "arguments": [{ "name": "need", "description": "What the user is looking for, in their own words (e.g. '10 gyms around Dallas that would buy modular flooring, with phone numbers'). Optional \u2014 the session starts by asking when absent.", "required": false }], "expected_calls": ["leadbay_find_new_leads", "leadbay_lead_job_status", "leadbay_qualify_leads"], "failure_modes": ["Passes the user's raw sentence as `query` instead of crafting an example_lead description (vendor-vocabulary trap \u2014 measured 0 delivered from a raw query vs on-profile results from a crafted example)", "Invents a distinctive brand name in example_lead.name (pulls matching toward name-lookalikes)", 'Puts event language ("hiring", "expanding", "just raised") into the seed description', "Launches qualify:true or channels without a dry_run quote and the user's explicit go-ahead", "Retries a failed/timed-out submit with a NEW request_id (double-spend) \u2014 the same ask must reuse the same request_id", 'Reports "no results" without narrating the funnel + scope_notes and proposing a concrete fix', "Renders delivered leads as freeform prose instead of the canonical lead-delivery table", "Blends two distinct buyer archetypes into one seed description instead of running one search per archetype", "Passes a country name in filters.locations (silently matches a same-named town \u2014 whole-country intent means OMITTING locations) or a nested employees object instead of the flat employees_min/employees_max", "Renders rows that visibly violate the user's exclusions, or presents a best-fit-under-30 table as an answer instead of flagging weak matches"] },
2705
2877
  leadbay_plan_tour_in_city: { "name": "leadbay_plan_tour_in_city", "short_description": 'Use whenever the user names a city they\'ll be in and asks who to see\n\u2014 "I\'m in SF next Tuesday, who\'s worth meeting?", "I\'m going to Berlin\n\u2014 who should I visit?", "plan my <city> tour". Any in-person/visit\nintent tied to a place routes here, NOT to `leadbay_pull_leads`. It\nsurfaces follow-ups + fresh Discover leads in the city via\n`leadbay_tour_plan`, ALWAYS offers to plot them on a map (rendering it\non yes), then offers outreach drafts + campaign persistence.\n', "arguments": [{ "name": "city", "description": "City or region the user is visiting (e.g. 'Limoges', 'Bay Area'). Used as the geo filter for both Monitor and Discover lookups. A country is not a city: this workspace already covers exactly one country, and a country name here silently fences the tour to a same-named village. Do NOT omit the argument to recover \u2014 a city-less tour returns arbitrary leads from across the whole workspace, which is not an itinerary. Ask which city or region the visit is to.", "required": true }, { "name": "date", "description": "When the visit is (e.g. 'May 24', 'next Thursday'). Surfaced in the outreach drafts as 'I'll be in <city> on <date>'.", "required": false }], "expected_calls": ["leadbay_tour_plan", "leadbay_research_lead_by_id", "leadbay_prepare_outreach", "leadbay_create_campaign"], "failure_modes": ["Calls leadbay_followups_map (Monitor-only) instead of leadbay_tour_plan \u2014 loses the Discover (fresh-lead) half that the user explicitly asked for", "Calls leadbay_pull_leads then drops the geo filter \u2014 returns the lens-wide wishlist instead of city-relevant fresh leads", 'Skips the campaign-persist step ("would you like to save these as a tour?") \u2014 leaves the rep with a one-shot map but no follow-up artifact', "Creates a campaign WITHOUT asking the user first \u2014 the persist step is high-intent; offer it, don't assume", "Fabricates lead_ids when seeding the campaign instead of using the ids returned by tour_plan"] },
2706
2878
  leadbay_prospecting_overview: { "name": "leadbay_prospecting_overview", "short_description": `Orientation for working with Leadbay from any host \u2014 discovery vs.
2707
2879
  follow-up, the outreach loop, outcome recording, imports, pushback /
@@ -2726,6 +2898,7 @@ var PROMPT_CATALOG_BULLETS = {
2726
2898
  leadbay_getting_started: `- \`leadbay_getting_started\`: Guided first-run walkthrough \u2014 four clicks that actually use Leadbay: check the account, pull today's leads, draft a first email to the top one, then reveal who to send it to. Use when the user is new or asks to be SHOWN how Leadbay works ("walk me through Leadbay", "I'm new", "how do I use this", "give me a tour"). Don't use it for orientation prose with no clicking \u2014 that's leadbay_prospecting_overview.`,
2727
2899
  leadbay_import_file: `- \`leadbay_import_file\` (optional args: file, instruction): Import a user-supplied CSV/file into Leadbay through five phases with evidence gates \u2014 scan, derive, resolve identities, preserve & commit, then optionally qualify and report. The job is to maximize how many rows the Leadbay system actually ingests and matches.`,
2728
2900
  leadbay_log_outreach: `- \`leadbay_log_outreach\` (required args: lead_id, summary): Log outreach (an email I sent, a call I made, a meeting I had) on a specific lead. Captures verification so the SDR pipeline trusts the entry.`,
2901
+ leadbay_new_leads: `- \`leadbay_new_leads\` (optional args: need): Guided net-new lead delivery \u2014 turn a described need ("gyms around Dallas that would buy our flooring") into ICP-perfect NEW companies with qualification evidence and the right contact, via leadbay_find_new_leads. Trigger when the user DESCRIBES who they want: "get me N companies that <profile>", "we're entering <market>". A bare "find me new leads" with no profile, and "today's leads", are the daily lens batch \u2014 leadbay_pull_leads. "Qualify these companies I have" is leadbay_qualify_leads.`,
2729
2902
  leadbay_plan_tour_in_city: `- \`leadbay_plan_tour_in_city\` (required args: city; optional args: date): Use whenever the user names a city they'll be in and asks who to see \u2014 "I'm in SF next Tuesday, who's worth meeting?", "I'm going to Berlin \u2014 who should I visit?", "plan my <city> tour". Any in-person/visit intent tied to a place routes here, NOT to \`leadbay_pull_leads\`. It surfaces follow-ups + fresh Discover leads in the city via \`leadbay_tour_plan\`, ALWAYS offers to plot them on a map (rendering it on yes), then offers outreach drafts + campaign persistence.`,
2730
2903
  leadbay_prospecting_overview: `- \`leadbay_prospecting_overview\`: Orientation for working with Leadbay from any host \u2014 discovery vs. follow-up, the outreach loop, outcome recording, imports, pushback / snooze, and the connected-outreach-tool registry. Trigger when the conversation involves Leadbay leads, prospecting, pipeline, follow-up, outreach, or lens / ICP \u2014 anything from "show me my leads" to "what should I follow up on" to "I'll send via lemlist".`,
2731
2904
  leadbay_qualify_top_n: `- \`leadbay_qualify_top_n\` (optional args: count): Bulk-qualify the top N un-qualified leads in the active lens. Uses leadbay_bulk_qualify_leads with a sensible default budget.`,
@@ -2737,8 +2910,8 @@ var PROMPT_CATALOG_BULLETS = {
2737
2910
  };
2738
2911
 
2739
2912
  // src/prompts.ts
2740
- function userMessage(text) {
2741
- return { role: "user", content: { type: "text", text } };
2913
+ function userMessage(text2) {
2914
+ return { role: "user", content: { type: "text", text: text2 } };
2742
2915
  }
2743
2916
  function substitutePlaceholders(body, substitutions) {
2744
2917
  let out = body;
@@ -2765,6 +2938,18 @@ var CATALOG = [
2765
2938
  arguments: promptArguments("leadbay_prospecting_overview"),
2766
2939
  render: () => [userMessage(leadbay_prospecting_overview)]
2767
2940
  },
2941
+ {
2942
+ name: "leadbay_new_leads",
2943
+ description: PROMPT_META.leadbay_new_leads.short_description,
2944
+ arguments: promptArguments("leadbay_new_leads"),
2945
+ render: (args) => [
2946
+ userMessage(
2947
+ substitutePlaceholders(leadbay_new_leads, {
2948
+ need: args.need ?? "(not provided \u2014 ask me first)"
2949
+ })
2950
+ )
2951
+ ]
2952
+ },
2768
2953
  {
2769
2954
  name: "leadbay_research_a_domain",
2770
2955
  description: PROMPT_META.leadbay_research_a_domain.short_description,
@@ -2923,18 +3108,38 @@ var CATALOG = [
2923
3108
  render: () => [userMessage(leadbay_getting_started)]
2924
3109
  }
2925
3110
  ];
2926
- function listPrompts() {
3111
+ var GATED_PROMPTS = {
3112
+ // Needs the write surface: every phase calls leadbay_find_new_leads /
3113
+ // leadbay_qualify_leads, which are write-tier, so a read-only server
3114
+ // (LEADBAY_MCP_WRITE=0) would offer a workflow whose tools are absent from
3115
+ // tools/list. The backend-rollout half of this gate is gone — the
3116
+ // /1.6/mcp/* routes shipped in backend v3.22.0.
3117
+ leadbay_new_leads: (opts) => opts.includeWrite !== false
3118
+ };
3119
+ function listAllPrompts() {
2927
3120
  return CATALOG.map((c) => ({
2928
3121
  name: c.name,
2929
3122
  description: c.description,
2930
3123
  arguments: c.arguments
2931
3124
  }));
2932
3125
  }
2933
- function getPrompt(name, args = {}) {
3126
+ function listPrompts(opts = {}) {
3127
+ return listAllPrompts().filter((p) => {
3128
+ const gate = GATED_PROMPTS[p.name];
3129
+ return gate ? gate(opts) : true;
3130
+ });
3131
+ }
3132
+ function getPrompt(name, args = {}, opts = {}) {
2934
3133
  const entry = CATALOG.find((c) => c.name === name);
2935
3134
  if (!entry) {
2936
3135
  throw new Error(`Unknown prompt: ${name}`);
2937
3136
  }
3137
+ const gate = GATED_PROMPTS[name];
3138
+ if (gate && !gate(opts)) {
3139
+ throw new Error(
3140
+ `Prompt ${name} is not enabled in this deployment (requires the write surface \u2014 LEADBAY_MCP_WRITE must not be 0).`
3141
+ );
3142
+ }
2938
3143
  const missing = entry.arguments.filter((a) => a.required && (args[a.name] === void 0 || args[a.name] === "")).map((a) => a.name);
2939
3144
  if (missing.length > 0) {
2940
3145
  throw new Error(
@@ -3054,6 +3259,13 @@ var REGIONS = {
3054
3259
  };
3055
3260
  var API_VERSION = "1.6";
3056
3261
  var API_PREFIX = `/${API_VERSION}`;
3262
+ function timeoutError(what, timeoutMs) {
3263
+ const err = new Error(what);
3264
+ err.code = "TIMEOUT";
3265
+ if (timeoutMs !== void 0)
3266
+ err.timeout_ms = timeoutMs;
3267
+ return err;
3268
+ }
3057
3269
  function httpsRequest(method, url, headers, body, timeoutMs, signal) {
3058
3270
  const deadlineMs = timeoutMs ?? defaultTimeoutMs();
3059
3271
  const abortSignal = signal ?? requestSignalStore.getStore();
@@ -3082,7 +3294,12 @@ function httpsRequest(method, url, headers, body, timeoutMs, signal) {
3082
3294
  port: 443,
3083
3295
  path: parsed.pathname + parsed.search,
3084
3296
  method,
3085
- headers: reqHeaders
3297
+ headers: reqHeaders,
3298
+ // Node aborts the socket and emits an AbortError on `error`, which the
3299
+ // handler below rejects with. Without this a cancelled tool call sat on
3300
+ // an in-flight GET until the server answered — the polling loop cannot
3301
+ // honour its advertised <=2s exit while blocked inside one.
3302
+ signal
3086
3303
  }, (res) => {
3087
3304
  const chunks = [];
3088
3305
  res.on("data", (chunk) => chunks.push(chunk));
@@ -3348,18 +3565,70 @@ var LeadbayClient = class _LeadbayClient {
3348
3565
  get _semaphoreState() {
3349
3566
  return { active: this.activeRequests, queued: this.waitQueue.length };
3350
3567
  }
3351
- async acquireSemaphore() {
3568
+ // `signal` makes a QUEUED acquisition abortable. Without it a cancelled call
3569
+ // that arrived when all MAX_CONCURRENT slots were busy could not observe the
3570
+ // abort until an unrelated request finished — the signal was only forwarded
3571
+ // to the socket, which this call had not reached yet. Against slow or stalled
3572
+ // peers that stranded the caller well past the <=2s exit the delivery tools
3573
+ // advertise.
3574
+ // `deadlineAt` is an ABSOLUTE epoch-ms bound covering the queue wait itself.
3575
+ // Without it a bounded call could still be stranded here without limit: the
3576
+ // deadline was only handed to httpsRequest, which does not start until this
3577
+ // resolves, so five slow peers let even `wait_seconds: 1` run unbounded. The
3578
+ // wait a caller asked for is wall-clock, not socket time.
3579
+ // `budgetMs` is the DURATION `deadlineAt` was derived from. Only the caller
3580
+ // knows it — an absolute deadline cannot be turned back into "how long did we
3581
+ // agree to wait" here — and the timeout error needs it, or the envelope
3582
+ // reports the 600,000ms default instead of the seconds actually granted.
3583
+ async acquireSemaphore(signal, deadlineAt, budgetMs) {
3584
+ if (signal?.aborted)
3585
+ throw this.cancelledBeforeSendError();
3586
+ if (deadlineAt !== void 0 && Date.now() >= deadlineAt) {
3587
+ throw timeoutError("Request deadline expired before a request slot was free", budgetMs);
3588
+ }
3352
3589
  if (this.activeRequests < MAX_CONCURRENT) {
3353
3590
  this.activeRequests++;
3354
3591
  return;
3355
3592
  }
3356
- return new Promise((resolve) => {
3357
- this.waitQueue.push(() => {
3593
+ return new Promise((resolve, reject) => {
3594
+ let timer;
3595
+ const waiter = () => {
3596
+ cleanup();
3358
3597
  this.activeRequests++;
3359
3598
  resolve();
3360
- });
3599
+ };
3600
+ const drop = () => {
3601
+ const i = this.waitQueue.indexOf(waiter);
3602
+ if (i !== -1)
3603
+ this.waitQueue.splice(i, 1);
3604
+ cleanup();
3605
+ };
3606
+ const onAbort = () => {
3607
+ drop();
3608
+ reject(this.cancelledBeforeSendError());
3609
+ };
3610
+ const onDeadline = () => {
3611
+ drop();
3612
+ reject(timeoutError("Request deadline expired while queued for a request slot", budgetMs));
3613
+ };
3614
+ const cleanup = () => {
3615
+ signal?.removeEventListener("abort", onAbort);
3616
+ if (timer !== void 0)
3617
+ clearTimeout(timer);
3618
+ };
3619
+ signal?.addEventListener("abort", onAbort, { once: true });
3620
+ if (deadlineAt !== void 0) {
3621
+ timer = setTimeout(onDeadline, Math.max(deadlineAt - Date.now(), 0));
3622
+ timer.unref?.();
3623
+ }
3624
+ this.waitQueue.push(waiter);
3361
3625
  });
3362
3626
  }
3627
+ // Cancelled while queued — nothing was ever put on the wire, which is what
3628
+ // makes this safe to report as "not sent" even for a write.
3629
+ cancelledBeforeSendError() {
3630
+ return this.makeError("REQUEST_CANCELLED", "The request was cancelled before it was sent.", "Re-call the tool if you still want the result \u2014 nothing reached the API, so nothing was charged.");
3631
+ }
3363
3632
  releaseSemaphore() {
3364
3633
  this.activeRequests--;
3365
3634
  const next = this.waitQueue.shift();
@@ -3401,16 +3670,52 @@ var LeadbayClient = class _LeadbayClient {
3401
3670
  // The 250ms backoff releases the concurrency slot first (release → sleep →
3402
3671
  // re-acquire) so a wave of 401s doesn't pin all MAX_CONCURRENT slots in
3403
3672
  // setTimeout and stall the queue.
3404
- httpsRequestWithRetry = async (method, url, headers, body, timeoutMs) => {
3405
- const res = await httpsRequest(method, url, headers, body, timeoutMs);
3673
+ httpsRequestWithRetry = async (method, url, headers, body, timeoutMs, signal, held, totalDeadlineAt) => {
3674
+ const perAttemptOptOut = timeoutMs !== void 0 && timeoutMs <= 0;
3675
+ const retryStartedAt = Date.now();
3676
+ const phaseBudget = () => {
3677
+ const now = Date.now();
3678
+ const perAttempt = timeoutMs !== void 0 && !perAttemptOptOut ? now + timeoutMs : void 0;
3679
+ const deadline = totalDeadlineAt === void 0 ? perAttempt : perAttempt === void 0 ? totalDeadlineAt : Math.min(perAttempt, totalDeadlineAt);
3680
+ if (deadline === void 0)
3681
+ return perAttemptOptOut ? timeoutMs : void 0;
3682
+ const left = deadline - now;
3683
+ if (left <= 0) {
3684
+ throw timeoutError(`Request deadline expired: ${method} ${url}`, Math.max(0, deadline - retryStartedAt));
3685
+ }
3686
+ return left;
3687
+ };
3688
+ const phaseDeadline = () => {
3689
+ const b = phaseBudget();
3690
+ if (b === void 0 || b <= 0)
3691
+ return void 0;
3692
+ return Date.now() + b;
3693
+ };
3694
+ const res = await httpsRequest(method, url, headers, body, phaseBudget(), signal);
3406
3695
  if (res.status === 401 && retriesOn401(method)) {
3696
+ if (signal?.aborted)
3697
+ return res;
3407
3698
  this.releaseSemaphore();
3699
+ if (held)
3700
+ held.value = false;
3408
3701
  try {
3409
- await new Promise((r) => setTimeout(r, 250));
3702
+ await new Promise((resolve) => {
3703
+ const t = setTimeout(done, 250);
3704
+ function done() {
3705
+ clearTimeout(t);
3706
+ signal?.removeEventListener("abort", done);
3707
+ resolve();
3708
+ }
3709
+ signal?.addEventListener("abort", done, { once: true });
3710
+ });
3410
3711
  } finally {
3411
- await this.acquireSemaphore();
3712
+ await this.acquireSemaphore(held ? signal : void 0, phaseDeadline(), phaseBudget());
3713
+ if (held)
3714
+ held.value = true;
3412
3715
  }
3413
- return httpsRequest(method, url, headers, body, timeoutMs);
3716
+ if (signal?.aborted)
3717
+ return res;
3718
+ return httpsRequest(method, url, headers, body, phaseBudget(), signal);
3414
3719
  }
3415
3720
  return res;
3416
3721
  };
@@ -3423,8 +3728,43 @@ var LeadbayClient = class _LeadbayClient {
3423
3728
  }
3424
3729
  const retryOn401 = opts?.retryOn401 !== false;
3425
3730
  const retriedOn401 = retryOn401 && retriesOn401(method);
3426
- await this.acquireSemaphore();
3731
+ const held = { value: true };
3732
+ const startedAt = Date.now();
3733
+ const totalDeadlineAt = opts?.totalTimeoutMs !== void 0 ? startedAt + opts.totalTimeoutMs : void 0;
3734
+ const perAttemptOptOut = opts?.timeoutMs !== void 0 && opts.timeoutMs <= 0;
3735
+ const phaseDeadlineAt = () => {
3736
+ const now = Date.now();
3737
+ const perAttempt = opts?.timeoutMs !== void 0 && !perAttemptOptOut ? now + opts.timeoutMs : void 0;
3738
+ if (totalDeadlineAt === void 0)
3739
+ return perAttempt;
3740
+ if (perAttempt === void 0)
3741
+ return totalDeadlineAt;
3742
+ return Math.min(perAttempt, totalDeadlineAt);
3743
+ };
3744
+ const grantedBudget = () => {
3745
+ const bounds = [opts?.timeoutMs, opts?.totalTimeoutMs].filter((n) => typeof n === "number" && n > 0);
3746
+ return bounds.length ? Math.min(...bounds) : void 0;
3747
+ };
3748
+ const remainingBudget = () => {
3749
+ const deadline = phaseDeadlineAt();
3750
+ if (deadline === void 0)
3751
+ return perAttemptOptOut ? opts?.timeoutMs : void 0;
3752
+ const left = deadline - Date.now();
3753
+ if (left <= 0) {
3754
+ throw timeoutError(`Request deadline expired: ${method} ${path}`, grantedBudget());
3755
+ }
3756
+ return left;
3757
+ };
3758
+ const queueDeadlineAt = () => totalDeadlineAt;
3759
+ const queueBudget = () => typeof opts?.totalTimeoutMs === "number" && opts.totalTimeoutMs > 0 ? opts.totalTimeoutMs : void 0;
3760
+ try {
3761
+ await this.acquireSemaphore(opts?.signal ?? opts?.preSendSignal, queueDeadlineAt(), queueBudget());
3762
+ } catch (e) {
3763
+ throw this.mapTransportError(e, `${method} ${path}`);
3764
+ }
3427
3765
  try {
3766
+ if (opts?.preSendSignal?.aborted)
3767
+ throw this.cancelledBeforeSendError();
3428
3768
  const url = `${this._baseUrl}${API_PREFIX}${path}`;
3429
3769
  const headers = {
3430
3770
  Authorization: `Bearer ${this.token}`
@@ -3432,7 +3772,17 @@ var LeadbayClient = class _LeadbayClient {
3432
3772
  if (body) {
3433
3773
  headers["Content-Type"] = "application/json";
3434
3774
  }
3435
- const res = await (retryOn401 ? this.httpsRequestWithRetry : httpsRequest)(method, url, headers, body ? JSON.stringify(body) : void 0, opts?.timeoutMs);
3775
+ const payload = body ? JSON.stringify(body) : void 0;
3776
+ const res = retryOn401 ? await this.httpsRequestWithRetry(method, url, headers, payload, opts?.timeoutMs, opts?.signal, held, totalDeadlineAt) : await httpsRequest(
3777
+ method,
3778
+ url,
3779
+ headers,
3780
+ payload,
3781
+ // What is LEFT after queueing, not the original budget — otherwise
3782
+ // the queue wait and the socket wait each get the full allowance.
3783
+ remainingBudget(),
3784
+ opts?.signal
3785
+ );
3436
3786
  this._lastMeta = {
3437
3787
  region: this._region,
3438
3788
  endpoint: `${method} ${path}`,
@@ -3449,7 +3799,8 @@ var LeadbayClient = class _LeadbayClient {
3449
3799
  } catch (e) {
3450
3800
  throw this.mapTransportError(e, `${method} ${path}`);
3451
3801
  } finally {
3452
- this.releaseSemaphore();
3802
+ if (held.value)
3803
+ this.releaseSemaphore();
3453
3804
  }
3454
3805
  }
3455
3806
  async requestVoid(method, path, body) {
@@ -3938,6 +4289,7 @@ var COMPOSITE_FILE_TOOL_NAMES = /* @__PURE__ */ new Set([
3938
4289
  "leadbay_delete_custom_field",
3939
4290
  "leadbay_enrich_titles",
3940
4291
  "leadbay_extend_lens",
4292
+ "leadbay_find_new_leads",
3941
4293
  "leadbay_followups_map",
3942
4294
  "leadbay_get_lead_custom_fields",
3943
4295
  "leadbay_get_qualification_questions",
@@ -3945,12 +4297,14 @@ var COMPOSITE_FILE_TOOL_NAMES = /* @__PURE__ */ new Set([
3945
4297
  "leadbay_import_and_qualify",
3946
4298
  "leadbay_import_leads",
3947
4299
  "leadbay_import_status",
4300
+ "leadbay_lead_job_status",
3948
4301
  "leadbay_list_campaigns",
3949
4302
  "leadbay_my_lenses",
3950
4303
  "leadbay_new_lens",
3951
4304
  "leadbay_prepare_outreach",
3952
4305
  "leadbay_pull_followups",
3953
4306
  "leadbay_pull_leads",
4307
+ "leadbay_qualify_leads",
3954
4308
  "leadbay_qualify_status",
3955
4309
  "leadbay_recall_ordered_titles",
3956
4310
  "leadbay_refine_prompt",
@@ -4191,7 +4545,7 @@ account resurfaced:
4191
4545
  `;
4192
4546
  var leadbay_account_status = `## WHEN TO USE
4193
4547
 
4194
- Trigger phrases: "what's my account status", "how much quota do I have", "what lens am I on", "I topped up / I bought credits / I added credits".
4548
+ Trigger phrases: "what's my account status", "how much quota do I have", "what lens am I on", "I topped up / I bought credits / I added credits", "what version of Leadbay am I running".
4195
4549
 
4196
4550
  Do NOT use for: "show me leads" \u2192 \`leadbay_pull_leads\`.
4197
4551
 
@@ -4200,6 +4554,7 @@ Prefer when: meta question about account, quota, active lens, or top-up recovery
4200
4554
  Examples that SHOULD invoke this tool:
4201
4555
  - "What's my account status?"
4202
4556
  - "How much quota do I have left this week?"
4557
+ - "Which version of the Leadbay connector is this?"
4203
4558
 
4204
4559
  Examples that should NOT invoke this tool (sound similar, route elsewhere):
4205
4560
  - "Show me today's leads."
@@ -4225,6 +4580,8 @@ Show the user's account state \u2014 admin rights, language, last-active lens, q
4225
4580
 
4226
4581
  **After a user tops up, do NOT keep refusing \u2014 RETRY.** If the user signals they topped up / bought credits / added credits, the previous QUOTA_EXCEEDED is invalidated the moment the Stripe webhook lands. RE-CALL \`leadbay_account_status\` to pick up the new state AND retry the originally failed call. The retry itself does not require a successful account_status check first \u2014 a topped-up user has cleared the throttle whether or not your cached snapshot reflects it yet. If the retry hits the wall again, only then re-offer top-up / wait. **A stale quota snapshot is never a reason to gate-keep a topped-up user.**
4227
4582
 
4583
+ **\`mcp_version\`** is the version of the Leadbay MCP server answering the call. When the user asks which Leadbay version they are running, answer with it.
4584
+
4228
4585
  **\`notifications\` block.** The response now includes a top-level \`notifications\` array listing background work the user (or agent) initiated that has since completed (\`bulk_enrich\`, \`bulk_qualify\`, \`import\`). These are signals to revise prior agent outputs the just-finished work might have made stale \u2014 they're NOT a pending-task list for the user. After revising (or confirming nothing is affected), call \`leadbay_acknowledge_notification(notification_id)\`. Full handling protocol below.
4229
4586
 
4230
4587
  ## GATE \u2014 INSPECT \`_meta.notifications\` ON EVERY RESPONSE
@@ -4620,7 +4977,7 @@ Context: Leadbay auto-qualifies roughly the top 10 of each daily batch. Leads be
4620
4977
 
4621
4978
  WHEN TO USE: when the user wants more qualified leads than what's currently shown, or when a lead looks promising in leadbay_pull_leads but has an empty \`qualification_summary\`.
4622
4979
 
4623
- WHEN NOT TO USE: to qualify a single specific lead \u2014 that's leadbay_qualify_lead (granular, advanced).
4980
+ WHEN NOT TO USE: to qualify a single specific lead \u2014 that's leadbay_qualify_lead (granular, advanced). And NOT for companies the user names or lists themselves (CRM rows, websites, prior deliveries) \u2014 that's leadbay_qualify_leads (server-side batch with per-item verdicts and contact matching); this tool only walks the ACTIVE LENS top-down.
4624
4981
 
4625
4982
  ## A launched job cannot be stopped
4626
4983
 
@@ -5252,7 +5609,7 @@ var leadbay_extend_lens = `## WHEN TO USE
5252
5609
 
5253
5610
  Trigger phrases: "I want more leads on this lens", "extend the lens", "I need a bigger batch today", "fill more leads, I've burned through these", "more leads like the ones in this lens".
5254
5611
 
5255
- Do NOT use for: "show me today's leads" \u2192 \`leadbay_pull_leads\`; "narrow the audience" \u2192 \`leadbay_adjust_audience\`; "stop showing me X" \u2192 \`leadbay_refine_prompt\`.
5612
+ Do NOT use for: "show me today's leads" \u2192 \`leadbay_pull_leads\`; "find me companies that <different profile than the lens>" \u2192 \`leadbay_find_new_leads\`; "narrow the audience" \u2192 \`leadbay_adjust_audience\`; "stop showing me X" \u2192 \`leadbay_refine_prompt\`.
5256
5613
 
5257
5614
  Prefer when: user has bigger appetite than the daily lens fill delivers \u2014 additive refill on same criteria
5258
5615
 
@@ -5341,6 +5698,256 @@ Pick the row matching the response \`status\`. Seed-picking is internal; do NOT
5341
5698
 
5342
5699
  If nothing matches cleanly, default to "pull leads now to see what's queued" \u2014 never invent a tool that doesn't exist.
5343
5700
  `;
5701
+ var leadbay_find_new_leads = `## WHEN TO USE
5702
+
5703
+ Trigger phrases: "find me N companies that <profile>", "get me new prospects like <company>", "I need leads in <place> that <do X>", "search for companies that would buy <product>", "net-new leads outside my current pipeline", "we're entering <market> \u2014 who should we target".
5704
+
5705
+ Do NOT use for: "show me today's leads / what's new today" \u2192 \`leadbay_pull_leads\`; "find me new leads (no profile, no count named)" \u2192 \`leadbay_pull_leads\`; "more leads like the ones in my lens" \u2192 \`leadbay_extend_lens\`; "qualify / vet these companies I have" \u2192 \`leadbay_qualify_leads\`; "qualify the top N of my batch" \u2192 \`leadbay_bulk_qualify_leads\`; "leads I should follow up with" \u2192 \`leadbay_pull_followups\`; "tell me about <one company>" \u2192 \`leadbay_research_lead_by_name_fuzzy\`.
5706
+
5707
+ Prefer when: the user describes a target profile or names a count of NEW companies \u2014 craft the example_lead per the seed rules below BEFORE calling; never pass the user's raw sentence as query.
5708
+
5709
+ Examples that SHOULD invoke this tool:
5710
+ - "Find me 10 gyms around Dallas that would buy our flooring, with someone I can call."
5711
+ - "Get me 20 new US SaaS companies, 50-2000 employees, with the VP People's email."
5712
+ - "We're launching in Lyon \u2014 find 15 hotels that fit our ICP."
5713
+
5714
+ Examples that should NOT invoke this tool (sound similar, route elsewhere):
5715
+ - "Show me today's leads."
5716
+ - "Which leads should I follow up with this week?"
5717
+ - "Qualify these 40 websites from my spreadsheet."
5718
+
5719
+ ## RENDER (quick)
5720
+
5721
+ 3-col table of delivered leads in returned order: col 1 = 10-segment fit
5722
+ bar + linked company \xB7 location \xB7 size; col 2 = why-fits \u226420 words; col 3
5723
+ = contact + purchased channels. ALWAYS close with the honest funnel line
5724
+ (matched/examined/delivered/stop reason/spend) \u2014 especially on 0
5725
+ delivered. Full algorithm below.
5726
+
5727
+ ---
5728
+
5729
+ Submit a net-new lead search: the backend matches an ICP seed against the full
5730
+ company universe, applies hard filters, skips what the org already knows
5731
+ (\`novelty: org\`), optionally qualifies against the org's own intelligence
5732
+ (questions, tags, ideal buyer profile \u2014 frozen at submit), and optionally buys
5733
+ contact channels. Polls up to \`wait_seconds\` (default 45); a longer job returns
5734
+ \`still_running\` + \`next_poll\` \u2014 hand off to \`leadbay_lead_job_status\`. Jobs run
5735
+ \u226430 min, results kept 30 days.
5736
+
5737
+ **Free vs paid \u2014 never spend silently.** Default (\`qualify: false\`,
5738
+ \`channels: []\`) is FREE: company profile + fit score + cached research +
5739
+ contact identity. Paid: \`qualify: true\` (~94 cost_cents per candidate
5740
+ EXAMINED, capped by \`exploration_cap\`/\`max_cost\`) and \`channels\` (email 25c /
5741
+ phone 250c, success-only). Enforced in code: a paid call is WITHHELD unless it
5742
+ carries \`confirm: true\` \u2014 nothing is submitted and you get
5743
+ \`mode: "needs_confirmation"\` with a real quote to show the user. Re-call with
5744
+ \`confirm: true\` on their go-ahead ("spend / get their emails" counts).
5745
+ \`confirm: false\` vetoes. Free needs no consent. **Preview free first** \u2014
5746
+ reshaping an off-profile seed is free, exploring it with \`qualify: true\` is
5747
+ not.
5748
+
5749
+ **Ad-hoc exclusions ("no chains") are enforced by NO tier** \u2014 \`filters\` has no
5750
+ exclusion key, and \`qualify\` scores against the org's FROZEN questions and IBP,
5751
+ which need not mention chains; the seed's inverse only shifts ranking.
5752
+ Violators can survive, be paid for and be delivered \u2014 post-filter them yourself
5753
+ and say the tier didn't enforce it. Durable enforcement \u2192
5754
+ \`leadbay_refine_prompt\`.
5755
+
5756
+ ### Crafting the \`example_lead\` seed \u2014 the input that decides result quality
5757
+
5758
+ The \`example_lead\` is a FICTIONAL typical ideal customer, matched against real
5759
+ registry/website descriptions \u2014 which state what a company **IS**, never what
5760
+ is happening. Write it the same way or the matcher drifts. Every rule below is
5761
+ measured:
5762
+
5763
+ 1. **Describe the BUYER, never the seller.** Ask: "would this company write a
5764
+ check to my user?" A seed describing what the user SELLS surfaces their
5765
+ *competitors and vendors*. If the product helps companies of type X serve
5766
+ customers of type Y, the seed describes X \u2014 never Y.
5767
+ 2. **Put everything in \`description\`; leave \`name\` unset.** An invented brand
5768
+ name pulls matching toward name-lookalikes \u2014 a seed named "Meridian
5769
+ Analytics" returned five unrelated "Meridian" companies.
5770
+ 3. **Registry style, one sentence to ~250 chars.** Industry niche, business
5771
+ model, what they sell or operate, who they serve, observable scale. Write
5772
+ it like the first paragraph of their About-Us page.
5773
+ - STRONG: "Operator of full-service fitness centers offering strength
5774
+ areas, group classes and personal training to members across multiple
5775
+ clubs."
5776
+ - WEAK (generic): "A gym in Texas."
5777
+ - WRONG (seller-side): "Supplier of durable modular flooring for gyms."
5778
+ 4. **No event language.** "hiring", "expanding", "just raised" are not
5779
+ filters \u2014 registry descriptions never contain them, so they dilute the
5780
+ profile. Purchase triggers belong in the org's qualification questions.
5781
+ 5. **No meta-markers.** Never "(example)", "(fictional)", "(placeholder)".
5782
+ 6. **Hard constraints go in \`filters\`, not prose \u2014 exact keys:**
5783
+ \`sectors: string[]\`, \`locations: string[]\`, \`employees_min: number\`,
5784
+ \`employees_max: number\`. FLAT numbers \u2014 nested \`employees: {min, max}\`
5785
+ exists only in RESULT payloads. \`example_lead.employees\` does not filter.
5786
+ \`locations\` take city/state/region names ("Dallas, TX", "\xCEle-de-France");
5787
+ a country name is refused in code \u2014 whole-country intent = omit it.
5788
+ 7. **Prefer \`example_lead\` over \`query\`.** Query matches topic *vocabulary*:
5789
+ "gyms that need durable flooring" surfaced flooring VENDORS, 0 delivered.
5790
+ Use \`query\` only for signal an example can't express.
5791
+ 8. **One seed per buyer archetype.** An ask spanning two segments ("gyms and
5792
+ warehouses") needs one search each with its own description and
5793
+ \`request_id\` \u2014 a blended seed lands between the clusters and matches
5794
+ neither.
5795
+
5796
+
5797
+ **Parameter notes**
5798
+ - \`request_id\` (REQUIRED) is the retry contract: SAME value retrying the same
5799
+ ask (same live job, no double spend); NEW for a changed ask. Derive from ask
5800
+ + archetype + date: \`gyms-dallas-2026-07-28\`.
5801
+ - Never lower \`min_ai_score\` together with \`channels\` \u2014 that buys emails for
5802
+ leads the AI just scored as junk.
5803
+ - \`count\` \u2264 50; \u22643 active jobs/org; \u226410 submits/hour (429 + Retry-After \u2014
5804
+ wait, don't hammer).
5805
+
5806
+ **Read the result honestly** \u2014 \`funnel\` + \`explain.scope_notes\` tell the story;
5807
+ zero delivered gets a cause and a next move (rules in RENDERING).
5808
+
5809
+ ---
5810
+
5811
+ ## RENDERING \u2014 delivery table + honest funnel line
5812
+
5813
+ Render delivered leads (\`leads[]\`, i.e. items with status \`delivered\` or
5814
+ \`degraded\`) as a markdown table **in the order returned**. Exactly three
5815
+ columns. Then ALWAYS close with the funnel line (below) \u2014 even, especially,
5816
+ when nothing was delivered.
5817
+
5818
+ **Column 1 \u2014 Company**
5819
+
5820
+ - Line 1: 10-segment fit bar in inline-code backticks from \`lead.fit.score\`
5821
+ (0-100): \`filled = round(score/10)\`, glyphs \`\u25B0\` filled / \`\u25B1\` empty. When
5822
+ \`lead.fit.components.qualification.available\` is true AND \`ai_score > 0\`,
5823
+ replace the LAST filled segment with \`\u2756\` (AI-confirmed cap). When
5824
+ \`fit.available\` is false, render \`\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\` and say "unscored" in col 2.
5825
+ Never print the numeric score.
5826
+ - Insert \`<br>\`, then: linked company name (target \`company.website\`, bare
5827
+ hostnames get \`https://\`; unlinked plain text when absent) + \` \xB7 \` + short
5828
+ location (City, ST / City, Country) + \` \xB7 \` + employees as \`min\u2013max\` (omit
5829
+ when \`employees.known\` is false).
5830
+
5831
+ **Column 2 \u2014 Why it fits**
5832
+
5833
+ - One sentence \u2264 20 words. Priority: \`fit.reasoning\` \u2192 gist of
5834
+ \`company.description\` \u2192 top \`fit.components.qualification.matched_tags\`.
5835
+ - If the item status is \`degraded\` or a requested channel failed, append the
5836
+ honest flag in italics, e.g. *(email could not be sourced)*.
5837
+
5838
+ **Column 3 \u2014 Contact**
5839
+
5840
+ - \`[Name](linkedin) \xB7 role\` (linked name mandatory when a LinkedIn URL
5841
+ exists; plain name otherwise). Below it, the PURCHASED channels only:
5842
+ \`\u2709 value\` / \`\u260E value\` inline as plain text (they auto-linkify).
5843
+ - Channel statuses: \`delivered\` \u2192 show value; \`already_owned\` \u2192 value +
5844
+ *(already yours)*; \`masked\` \u2192 "on file \u2014 reveal via channels";
5845
+ \`not_requested\` \u2192 omit; \`failed_*\` \u2192 *(no verified email/phone)*.
5846
+ - No contact on the item (\`contact\` null): render \`\u2014\` (title_gate \`prefer\`
5847
+ delivers such rows flagged; say so in col 2 only when contact_titles were
5848
+ requested).
5849
+
5850
+ **The funnel line (mandatory, after the table):**
5851
+
5852
+ One short line narrating the delivery honestly, from \`funnel\` + \`cost\` +
5853
+ \`explain.scope_notes\`:
5854
+
5855
+ > Matched N \xB7 examined E \xB7 qualified Q \xB7 disqualified D \u2192 **delivered X of
5856
+ > the Y asked** \xB7 stopped: <stop_reason in plain words> \xB7 spent C.CC.
5857
+
5858
+ **Money: divide, then symbol.** Every amount (\`cost.spent\`,
5859
+ \`estimated_cost.max\`, quotes) is \`cost_cents\` \u2014 divide by 100, two decimals,
5860
+ so \`165\` renders \`1.65\`, NEVER \`165.00\`. Symbol from the account region: US
5861
+ \`$\`, France \`\u20AC\`, unknown \u2192 bare. Never hard-code \`$\`: it misstates a charge.
5862
+
5863
+ "of the Y asked" needs \`summary.items_requested\`, which submits carry but a
5864
+ later \`leadbay_lead_job_status\` snapshot does not. Without it write **delivered
5865
+ X** and stop \u2014 never back-fill Y from \`matched\`/\`examined\` (they count
5866
+ candidates), never guess it.
5867
+
5868
+ Plain-word stop reasons: \`target_reached\` \u2192 omit (success), \`pool_exhausted\` \u2192
5869
+ "ran out of matching candidates", \`max_cost\` \u2192 "hit the cost cap", \`quota\` \u2192
5870
+ "hit an org quota", \`time_budget\` \u2192 "hit the 30-min time budget".
5871
+
5872
+ **When \`delivered\` is 0**: NEVER say just "no results". Render no table; give
5873
+ the funnel line plus the relevant \`explain.scope_notes\` (the backend's own
5874
+ diagnosis), then propose the concrete fix (reshape the seed per the craft
5875
+ rules, lower \`min_ai_score\`, raise \`max_cost\`, drop a filter) as NEXT STEPS.
5876
+
5877
+ **Weak batch**: when the BEST delivered \`fit.score\` is under 30, don't present
5878
+ the table as an answer \u2014 open with "weak matches only", show at most the top 3,
5879
+ propose reshaping the seed/filters first. The count was filled with
5880
+ barely-better-than-random candidates.
5881
+
5882
+ **Sanity-check every row**: (a) geo \u2014 \`city\`/\`region\` must sit inside any
5883
+ requested fence; drop and call out leaks (same-named cities slip through).
5884
+ (b) When \`explain.seed_strategy\` is \`text_match_exemplars\` (the standard FR
5885
+ path), fit is calibrated for lead-to-lead distances, not exemplar centroids \u2014
5886
+ treat high scores skeptically and verify each row's \`description\`.
5887
+
5888
+ **Skipped items** (\`skipped[]\`, qualify jobs mostly): render a compact second
5889
+ table \`Ref \u2192 Outcome\` translating \`status_reason\` to plain words:
5890
+ \`not_in_universe\` \u2192 "not in the Leadbay universe (import it first)",
5891
+ \`low_confidence_identity\` \u2192 "couldn't safely match \u2014 check \`resolution.alternatives\`",
5892
+ \`no_matching_contact\` \u2192 "no contact with the requested title",
5893
+ \`disqualified\` \u2192 "evaluated: does not fit" (evidence is in the item when owned),
5894
+ \`enrichment_failed\` \u2192 "channel could not be sourced (not billed)".
5895
+
5896
+ **\`items_truncated\`**: rows are a PREFIX, not the batch. Say so, and offer
5897
+ \`leadbay_lead_job_status(job_id, since: next_since)\` for the rest.
5898
+
5899
+ **Hide from the user:** UUIDs (keep for tool calls, never render), cursors,
5900
+ \`explain.model\`/\`intelligence_snapshot\`, raw \`distance\`/\`calibration\`,
5901
+ \`seq\`/\`from_cache\`, empty arrays.
5902
+
5903
+ ## Linking a contact's name
5904
+
5905
+ **MANDATORY: every contact name in your output \u2014 table cells, prose, headers, "Reach <Name>" callouts \u2014 MUST be wrapped in markdown link syntax \`[Name](URL)\`. Never render a contact name as bare text. A plain-text name is a broken contact card; the underlined name is the user's primary affordance for "take me to this person's profile". No "no URL available" exception \u2014 the search URL below is always constructable from name + company.**
5906
+
5907
+ URL priority (first applicable wins):
5908
+
5909
+ 1. **Real profile** \u2014 \`contact.linkedin_page\` when it's a string starting with \`https://\` (the MCP coerces the legacy literal \`"null"\` string to real null before you see it).
5910
+ 2. **Constructed people-search** \u2014 \`https://www.linkedin.com/search/results/people/?keywords=<First>+<Last>+<Company>\`. URL-encode params. Strip Inc / LLC / Corp / Ltd / GmbH / Co / S.A. / S.L. / PLC / AG / SAS / SARL suffixes from the company. Append a trailing \` \xB0\` to the rendered name ONLY when this fallback is in use AND \`social_presence.linkedin == false\`. Never append \`\xB0\` when a real \`linkedin_page\` was used.
5911
+
5912
+ Never link a person's name to the company's LinkedIn page (and vice versa) \u2014 the two surfaces are different and conflating them quietly degrades the workflow.
5913
+
5914
+
5915
+
5916
+ ---
5917
+
5918
+ ## NEXT STEPS \u2014 after a find_new_leads delivery
5919
+
5920
+ **ALWAYS render NEXT STEPS via your host's next-step widget.** Use whichever is in your tool set \u2014 the NAME and SCHEMA differ: **\`ask_user_input_v0\`** (Claude chat / ChatGPT) takes plain-string options with \`type:"single_select"\`; **\`AskUserQuestion\`** (Claude cowork / Claude Code) takes object options \`{label, description}\` plus a required short \`header\` (\u226412 chars) and \`multiSelect\`, NO \`type\` field, and never add an "Other" option (the host adds it). Match the schema to the tool you actually have \u2014 the wrong schema fails silently and you fall back to prose. Prose bullets are the fallback ONLY when NEITHER widget exists. Any turn that would end with a choice must be the widget \u2014 the widget IS the question.
5921
+
5922
+ **If the tool result carries a \`next_steps\` object, that is the source of truth \u2014 use it directly.** Each option has a short \`.label\` (\u22645 words) and a full \`.description\`. Map \`next_steps.options[]\` into your host widget VERBATIM and in order: for \`AskUserQuestion\` (cowork / Claude Code) pass each as \`{label, description}\`; for \`ask_user_input_v0\` (Claude chat / ChatGPT, string options only) pass each option's \`.description\` as the string (it's the full sentence). Do NOT reword, reorder, drop, or prose-ify them \u2014 they're built deterministically by the server so the offer (incl. the artifact option at position 0) fires every time. Fall back to the table below only when there is NO \`next_steps\` field.
5923
+
5924
+ **One exception \u2014 skip the widget** when the user's original message contained a complete sequential instruction chain ("show me X and then do Y") AND all stated steps have been completed. In that case, end with STOP directly \u2014 the user stated their full plan and does not need a "what next?" prompt.
5925
+ - Skip example: "Show me today's leads and then research the top one for me." \u2192 after research completes, emit STOP without the widget.
5926
+ - Do NOT skip for: plain requests ("show me today's leads", "run my check-in"), recurring-language requests ("I do this every day"), or requests where only one action was stated.
5927
+
5928
+ Pick 2\u20134 rows from the (Observation, Suggest, Calls) table below most relevant to the response, then call your host's widget with ITS schema (per the schema rules above \u2014 wrong schema fails silently):
5929
+ - \`ask_user_input_v0\`: \`{questions:[{question,type:"single_select",options:["<Suggest 1>","<Suggest 2>"]}]}\`
5930
+ - \`AskUserQuestion\`: \`{questions:[{question,header:"Next step",multiSelect:false,options:[{label:"<\u22645 words>",description:"<Suggest 1>"}]}]}\`
5931
+
5932
+ User picks \u2192 call the matching \`Calls\` tool. Constraints: 2\u20134 mutually-exclusive options, AskUserQuestion labels \u22645 words (full text in \`description\`), max 3 questions. Table stays internal; never recite it.
5933
+
5934
+ ---
5935
+
5936
+
5937
+
5938
+ Pick the 2-3 options that match what actually happened \u2014 never all seven:
5939
+
5940
+ | Observation | Suggest | Calls |
5941
+ |---|---|---|
5942
+ | Job still running (\`still_running: true\`) | "Check on it in ~1 min" | leadbay_lead_job_status(job_id, wait_seconds: 60) |
5943
+ | Free run delivered on-profile leads | "Qualify these N against your criteria (paid \u2014 \`dry_run\` first)" | leadbay_qualify_leads(prior_deliveries: {job_id}) |
5944
+ | Delivered leads look right | "Draft outreach for the top ones" | leadbay_prepare_outreach |
5945
+ | Delivered 0 or off-profile | "Reshape the example and retry" (name the fix from funnel + scope_notes) | leadbay_find_new_leads (NEW request_id) |
5946
+ | Stopped at cost cap (\`stop_reason: max_cost\`) | "Raise the cap to X and get the remaining N" \u2014 X in the account's currency per the funnel-line rule, never a hard-coded \`$\` | leadbay_find_new_leads, NEW request_id (same-id only dedupes onto a LIVE job) + higher max_cost + \`count\` = the SHORTFALL (\`items_requested\` \u2212 delivered), not the original + \`exclude_lead_ids\` = the examined-but-REJECTED ids (novelty covers delivered; these are what it misses \u2014 without them the rerun re-buys the same losers) |
5947
+ | Stopped on org quota (\`stop_reason: quota\`) | "Check which window is exhausted and when it resets" \u2014 never a re-run: it cannot clear an org quota and burns a submit slot to stop in the same place | leadbay_account_status |
5948
+ | Stopped on org quota and the user does not want to wait | "Top up to finish this run" | leadbay_create_topup_link |
5949
+ | User wants these tracked in Leadbay | "Add the keepers to a campaign" | leadbay_create_campaign / leadbay_add_leads_to_campaign |
5950
+ `;
5344
5951
  var leadbay_followups_map = `## WHEN TO USE
5345
5952
 
5346
5953
  Trigger phrases: "I'm going to <city>", "visit in person", "map of leads", "plan my itinerary".
@@ -6205,6 +6812,199 @@ spend before spending it again.
6205
6812
 
6206
6813
  This tool MUTATES state. The caller (agent or human-in-the-loop) is responsible for confirming intent before invocation; the MCP server does not soft-prompt for confirmation. See \`annotations.destructiveHint\`.
6207
6814
  `;
6815
+ var leadbay_lead_job_status = `## WHEN TO USE
6816
+
6817
+ Trigger phrases: "is the lead search done", "any results yet on that job", "check on the delivery".
6818
+
6819
+ Do NOT use for: "is the enrichment done" \u2192 \`leadbay_bulk_enrich_status\`; "is my import done" \u2192 \`leadbay_import_status\`; "is the top-N qualification done" \u2192 \`leadbay_qualify_status\`.
6820
+
6821
+ Prefer when: a find_new_leads / qualify_leads result carried next_poll \u2014 pass its job_id; use wait_seconds ~60 when the user asked to wait for results.
6822
+
6823
+ Examples that SHOULD invoke this tool:
6824
+ - "Any leads yet from that search you started?"
6825
+ - "Wait for the qualification job to finish and show me everything."
6826
+
6827
+ Examples that should NOT invoke this tool (sound similar, route elsewhere):
6828
+ - "Is the email enrichment finished?"
6829
+ - "Is my CSV import done?"
6830
+
6831
+ ## RENDER (quick)
6832
+
6833
+ Terminal job -> render the full delivery per the lead-delivery table +
6834
+ honest funnel line. Still running -> one progress line (examined /
6835
+ delivered / spent so far) and offer to check again in ~1 min. Never
6836
+ render UUIDs or cursors.
6837
+
6838
+ ---
6839
+
6840
+ Cumulative snapshot of a lead-delivery job: state, funnel counters, every
6841
+ item emitted so far (full lead payloads for delivered/degraded, honest
6842
+ status_reason for skipped), spend + breakdown, and the \`explain\` block
6843
+ (basis, seed strategy, scope notes). Items are immutable once emitted \u2014
6844
+ polling never re-reads live data, so numbers only ever grow.
6845
+
6846
+ \`wait_seconds: 0\` (default) answers instantly; set ~60 to block-wait for
6847
+ completion when the user asked for results "in this reply". \`since\` (from a
6848
+ prior poll's \`next_since\`) pages only the new items. Jobs terminalize
6849
+ server-side: past the 30-min wall clock a job reads \`completed_partial\`
6850
+ (time budget), past 30 days \`expired\` (items no longer listed \u2014 re-read
6851
+ billed leads via leadbay_qualify_leads \`prior_deliveries\`). A 404 means
6852
+ unknown job or another org's job.
6853
+
6854
+ ---
6855
+
6856
+ ## RENDERING \u2014 delivery table + honest funnel line
6857
+
6858
+ Render delivered leads (\`leads[]\`, i.e. items with status \`delivered\` or
6859
+ \`degraded\`) as a markdown table **in the order returned**. Exactly three
6860
+ columns. Then ALWAYS close with the funnel line (below) \u2014 even, especially,
6861
+ when nothing was delivered.
6862
+
6863
+ **Column 1 \u2014 Company**
6864
+
6865
+ - Line 1: 10-segment fit bar in inline-code backticks from \`lead.fit.score\`
6866
+ (0-100): \`filled = round(score/10)\`, glyphs \`\u25B0\` filled / \`\u25B1\` empty. When
6867
+ \`lead.fit.components.qualification.available\` is true AND \`ai_score > 0\`,
6868
+ replace the LAST filled segment with \`\u2756\` (AI-confirmed cap). When
6869
+ \`fit.available\` is false, render \`\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\` and say "unscored" in col 2.
6870
+ Never print the numeric score.
6871
+ - Insert \`<br>\`, then: linked company name (target \`company.website\`, bare
6872
+ hostnames get \`https://\`; unlinked plain text when absent) + \` \xB7 \` + short
6873
+ location (City, ST / City, Country) + \` \xB7 \` + employees as \`min\u2013max\` (omit
6874
+ when \`employees.known\` is false).
6875
+
6876
+ **Column 2 \u2014 Why it fits**
6877
+
6878
+ - One sentence \u2264 20 words. Priority: \`fit.reasoning\` \u2192 gist of
6879
+ \`company.description\` \u2192 top \`fit.components.qualification.matched_tags\`.
6880
+ - If the item status is \`degraded\` or a requested channel failed, append the
6881
+ honest flag in italics, e.g. *(email could not be sourced)*.
6882
+
6883
+ **Column 3 \u2014 Contact**
6884
+
6885
+ - \`[Name](linkedin) \xB7 role\` (linked name mandatory when a LinkedIn URL
6886
+ exists; plain name otherwise). Below it, the PURCHASED channels only:
6887
+ \`\u2709 value\` / \`\u260E value\` inline as plain text (they auto-linkify).
6888
+ - Channel statuses: \`delivered\` \u2192 show value; \`already_owned\` \u2192 value +
6889
+ *(already yours)*; \`masked\` \u2192 "on file \u2014 reveal via channels";
6890
+ \`not_requested\` \u2192 omit; \`failed_*\` \u2192 *(no verified email/phone)*.
6891
+ - No contact on the item (\`contact\` null): render \`\u2014\` (title_gate \`prefer\`
6892
+ delivers such rows flagged; say so in col 2 only when contact_titles were
6893
+ requested).
6894
+
6895
+ **The funnel line (mandatory, after the table):**
6896
+
6897
+ One short line narrating the delivery honestly, from \`funnel\` + \`cost\` +
6898
+ \`explain.scope_notes\`:
6899
+
6900
+ > Matched N \xB7 examined E \xB7 qualified Q \xB7 disqualified D \u2192 **delivered X of
6901
+ > the Y asked** \xB7 stopped: <stop_reason in plain words> \xB7 spent C.CC.
6902
+
6903
+ **Money: divide, then symbol.** Every amount (\`cost.spent\`,
6904
+ \`estimated_cost.max\`, quotes) is \`cost_cents\` \u2014 divide by 100, two decimals,
6905
+ so \`165\` renders \`1.65\`, NEVER \`165.00\`. Symbol from the account region: US
6906
+ \`$\`, France \`\u20AC\`, unknown \u2192 bare. Never hard-code \`$\`: it misstates a charge.
6907
+
6908
+ "of the Y asked" needs \`summary.items_requested\`, which submits carry but a
6909
+ later \`leadbay_lead_job_status\` snapshot does not. Without it write **delivered
6910
+ X** and stop \u2014 never back-fill Y from \`matched\`/\`examined\` (they count
6911
+ candidates), never guess it.
6912
+
6913
+ Plain-word stop reasons: \`target_reached\` \u2192 omit (success), \`pool_exhausted\` \u2192
6914
+ "ran out of matching candidates", \`max_cost\` \u2192 "hit the cost cap", \`quota\` \u2192
6915
+ "hit an org quota", \`time_budget\` \u2192 "hit the 30-min time budget".
6916
+
6917
+ **When \`delivered\` is 0**: NEVER say just "no results". Render no table; give
6918
+ the funnel line plus the relevant \`explain.scope_notes\` (the backend's own
6919
+ diagnosis), then propose the concrete fix (reshape the seed per the craft
6920
+ rules, lower \`min_ai_score\`, raise \`max_cost\`, drop a filter) as NEXT STEPS.
6921
+
6922
+ **Weak batch**: when the BEST delivered \`fit.score\` is under 30, don't present
6923
+ the table as an answer \u2014 open with "weak matches only", show at most the top 3,
6924
+ propose reshaping the seed/filters first. The count was filled with
6925
+ barely-better-than-random candidates.
6926
+
6927
+ **Sanity-check every row**: (a) geo \u2014 \`city\`/\`region\` must sit inside any
6928
+ requested fence; drop and call out leaks (same-named cities slip through).
6929
+ (b) When \`explain.seed_strategy\` is \`text_match_exemplars\` (the standard FR
6930
+ path), fit is calibrated for lead-to-lead distances, not exemplar centroids \u2014
6931
+ treat high scores skeptically and verify each row's \`description\`.
6932
+
6933
+ **Skipped items** (\`skipped[]\`, qualify jobs mostly): render a compact second
6934
+ table \`Ref \u2192 Outcome\` translating \`status_reason\` to plain words:
6935
+ \`not_in_universe\` \u2192 "not in the Leadbay universe (import it first)",
6936
+ \`low_confidence_identity\` \u2192 "couldn't safely match \u2014 check \`resolution.alternatives\`",
6937
+ \`no_matching_contact\` \u2192 "no contact with the requested title",
6938
+ \`disqualified\` \u2192 "evaluated: does not fit" (evidence is in the item when owned),
6939
+ \`enrichment_failed\` \u2192 "channel could not be sourced (not billed)".
6940
+
6941
+ **\`items_truncated\`**: rows are a PREFIX, not the batch. Say so, and offer
6942
+ \`leadbay_lead_job_status(job_id, since: next_since)\` for the rest.
6943
+
6944
+ **Hide from the user:** UUIDs (keep for tool calls, never render), cursors,
6945
+ \`explain.model\`/\`intelligence_snapshot\`, raw \`distance\`/\`calibration\`,
6946
+ \`seq\`/\`from_cache\`, empty arrays.
6947
+
6948
+ ## Linking a contact's name
6949
+
6950
+ **MANDATORY: every contact name in your output \u2014 table cells, prose, headers, "Reach <Name>" callouts \u2014 MUST be wrapped in markdown link syntax \`[Name](URL)\`. Never render a contact name as bare text. A plain-text name is a broken contact card; the underlined name is the user's primary affordance for "take me to this person's profile". No "no URL available" exception \u2014 the search URL below is always constructable from name + company.**
6951
+
6952
+ URL priority (first applicable wins):
6953
+
6954
+ 1. **Real profile** \u2014 \`contact.linkedin_page\` when it's a string starting with \`https://\` (the MCP coerces the legacy literal \`"null"\` string to real null before you see it).
6955
+ 2. **Constructed people-search** \u2014 \`https://www.linkedin.com/search/results/people/?keywords=<First>+<Last>+<Company>\`. URL-encode params. Strip Inc / LLC / Corp / Ltd / GmbH / Co / S.A. / S.L. / PLC / AG / SAS / SARL suffixes from the company. Append a trailing \` \xB0\` to the rendered name ONLY when this fallback is in use AND \`social_presence.linkedin == false\`. Never append \`\xB0\` when a real \`linkedin_page\` was used.
6956
+
6957
+ Never link a person's name to the company's LinkedIn page (and vice versa) \u2014 the two surfaces are different and conflating them quietly degrades the workflow.
6958
+
6959
+
6960
+
6961
+ **Delivered \u2260 endorsed.** This tool DELIVERS org-owned companies that FAILED
6962
+ qualification, carrying their negative evidence \u2014 so a delivered item is not
6963
+ automatically a prospect. An item whose \`status_reason\` is \`disqualified\`, or
6964
+ whose \`fit.components.qualification\` is available with a negative \`ai_score\`,
6965
+ must NOT go in the fit table: its firmographic score can still be high, and a
6966
+ full bar beside "why it fits" reads as a recommendation to call an account the
6967
+ evaluation just rejected.
6968
+
6969
+ Give those their own short section after the fit table, titled
6970
+ **Evaluated \u2014 does not fit**: linked company, then the verdict in plain
6971
+ words from the
6972
+ qualification evidence (failed question verdicts, missed tags, IBP reasoning).
6973
+ That is the deliverable \u2014 "here's why to skip this account" \u2014 not a defect to
6974
+ hide.
6975
+
6976
+
6977
+ ---
6978
+
6979
+ ## NEXT STEPS \u2014 after a job status poll
6980
+
6981
+ **ALWAYS render NEXT STEPS via your host's next-step widget.** Use whichever is in your tool set \u2014 the NAME and SCHEMA differ: **\`ask_user_input_v0\`** (Claude chat / ChatGPT) takes plain-string options with \`type:"single_select"\`; **\`AskUserQuestion\`** (Claude cowork / Claude Code) takes object options \`{label, description}\` plus a required short \`header\` (\u226412 chars) and \`multiSelect\`, NO \`type\` field, and never add an "Other" option (the host adds it). Match the schema to the tool you actually have \u2014 the wrong schema fails silently and you fall back to prose. Prose bullets are the fallback ONLY when NEITHER widget exists. Any turn that would end with a choice must be the widget \u2014 the widget IS the question.
6982
+
6983
+ **If the tool result carries a \`next_steps\` object, that is the source of truth \u2014 use it directly.** Each option has a short \`.label\` (\u22645 words) and a full \`.description\`. Map \`next_steps.options[]\` into your host widget VERBATIM and in order: for \`AskUserQuestion\` (cowork / Claude Code) pass each as \`{label, description}\`; for \`ask_user_input_v0\` (Claude chat / ChatGPT, string options only) pass each option's \`.description\` as the string (it's the full sentence). Do NOT reword, reorder, drop, or prose-ify them \u2014 they're built deterministically by the server so the offer (incl. the artifact option at position 0) fires every time. Fall back to the table below only when there is NO \`next_steps\` field.
6984
+
6985
+ **One exception \u2014 skip the widget** when the user's original message contained a complete sequential instruction chain ("show me X and then do Y") AND all stated steps have been completed. In that case, end with STOP directly \u2014 the user stated their full plan and does not need a "what next?" prompt.
6986
+ - Skip example: "Show me today's leads and then research the top one for me." \u2192 after research completes, emit STOP without the widget.
6987
+ - Do NOT skip for: plain requests ("show me today's leads", "run my check-in"), recurring-language requests ("I do this every day"), or requests where only one action was stated.
6988
+
6989
+ Pick 2\u20134 rows from the (Observation, Suggest, Calls) table below most relevant to the response, then call your host's widget with ITS schema (per the schema rules above \u2014 wrong schema fails silently):
6990
+ - \`ask_user_input_v0\`: \`{questions:[{question,type:"single_select",options:["<Suggest 1>","<Suggest 2>"]}]}\`
6991
+ - \`AskUserQuestion\`: \`{questions:[{question,header:"Next step",multiSelect:false,options:[{label:"<\u22645 words>",description:"<Suggest 1>"}]}]}\`
6992
+
6993
+ User picks \u2192 call the matching \`Calls\` tool. Constraints: 2\u20134 mutually-exclusive options, AskUserQuestion labels \u22645 words (full text in \`description\`), max 3 questions. Table stays internal; never recite it.
6994
+
6995
+ ---
6996
+
6997
+
6998
+
6999
+ Pick the ONE row matching the job's state and offer at most two options \u2014 this
7000
+ is a status tool, keep it terse:
7001
+
7002
+ | Observation | Suggest | Calls |
7003
+ |---|---|---|
7004
+ | Still running | "Keep waiting (~1 min) or leave it \u2014 results are kept 30 days" | leadbay_lead_job_status(job_id, wait_seconds: 60) |
7005
+ | Terminal (completed / partial / failed) | Render the delivery per the RENDERING block, then offer the matching find_new_leads / qualify_leads NEXT STEPS | \u2014 |
7006
+ | \`expired\` (past the 30-day window) | "Re-read the billed leads from your delivery ledger" \u2014 there is nothing left to render: the job terminalized and its items are no longer listed, so do NOT present an empty delivery as a result | leadbay_qualify_leads(prior_deliveries: {job_id}) |
7007
+ `;
6208
7008
  var leadbay_like_lead = `## WHEN TO USE
6209
7009
 
6210
7010
  Trigger phrases: "I like this lead", "thumbs up", "this one looks good", "save this one", "this is a good fit", "more like this", "yes to this one".
@@ -7103,7 +7903,7 @@ var leadbay_pull_leads = `## WHEN TO USE
7103
7903
 
7104
7904
  Trigger phrases: "show me leads", "show me new leads", "show me today's leads", "today's prospects", "best new leads", "fresh leads", "what's new today".
7105
7905
 
7106
- Do NOT use for: "leads I should follow up with" \u2192 \`leadbay_pull_followups\`; "I'm going to <city>" \u2192 \`leadbay_tour_plan\`; "I'm in <city> next week \u2014 who's worth meeting" \u2192 \`leadbay_tour_plan\`; "who should I meet in <city>" \u2192 \`leadbay_tour_plan\`; "visiting <city> \u2014 who's worth meeting / seeing" \u2192 \`leadbay_tour_plan\`; "leads I should reach out to" \u2192 \`leadbay_pull_followups\`; "leads to get back to" \u2192 \`leadbay_pull_followups\`; "leads to contact today" \u2192 \`leadbay_pull_followups\`; "should I contact" \u2192 \`leadbay_pull_followups\`; "reconnect with" \u2192 \`leadbay_pull_followups\`; "re-engage" \u2192 \`leadbay_pull_followups\`.
7906
+ Do NOT use for: "find me N companies that <specific profile>" \u2192 \`leadbay_find_new_leads\`; "new prospects like <company> with their emails" \u2192 \`leadbay_find_new_leads\`; "leads I should follow up with" \u2192 \`leadbay_pull_followups\`; "I'm going to <city>" \u2192 \`leadbay_tour_plan\`; "I'm in <city> next week \u2014 who's worth meeting" \u2192 \`leadbay_tour_plan\`; "who should I meet in <city>" \u2192 \`leadbay_tour_plan\`; "visiting <city> \u2014 who's worth meeting / seeing" \u2192 \`leadbay_tour_plan\`; "leads I should reach out to" \u2192 \`leadbay_pull_followups\`; "leads to get back to" \u2192 \`leadbay_pull_followups\`; "leads to contact today" \u2192 \`leadbay_pull_followups\`; "should I contact" \u2192 \`leadbay_pull_followups\`; "reconnect with" \u2192 \`leadbay_pull_followups\`; "re-engage" \u2192 \`leadbay_pull_followups\`.
7107
7907
 
7108
7908
  Prefer when: fresh Discover leads; if a lens is named, pass \`lensId\` and pin it
7109
7909
 
@@ -7112,6 +7912,7 @@ Examples that SHOULD invoke this tool:
7112
7912
  - "Pull my best new prospects."
7113
7913
 
7114
7914
  Examples that should NOT invoke this tool (sound similar, route elsewhere):
7915
+ - "Find me 10 gyms around Dallas that would buy our flooring."
7115
7916
  - "Which leads should I follow up with this week?"
7116
7917
  - "I'm flying to Berlin Thursday \u2014 who should I meet?"
7117
7918
  - "I'm in San Francisco next Tuesday \u2014 who's worth meeting?"
@@ -7141,7 +7942,7 @@ Every lead carries \`recommended_contact\` (with \`linkedin_page\` when the back
7141
7942
 
7142
7943
  WHEN TO USE: as the agent's default opening move when the user wants to see leads, or as a daily check-in for what's new today.
7143
7944
 
7144
- WHEN NOT TO USE: when the user has named a specific lens \u2014 pass \`lensId\` to override the auto-resolution. Replaces the older leadbay_find_prospects (removed in v0.2.0).
7945
+ WHEN NOT TO USE: when the user has named a specific lens \u2014 pass \`lensId\` to override the auto-resolution.
7145
7946
 
7146
7947
  The active lens can change between calls (5-min cache + backend \`last_requested_lens\`). If a multi-step workflow depends on staying on one lens, **capture \`response.lens.id\` from the first response and pass it as the \`lensId\` argument on every subsequent Leadbay call** \u2014 including re-pulls, bulk qualifies, and research. (Field-name caveat: response nests it as \`lens.id\`; the parameter is \`lensId\`.) Re-pulling without \`lensId\` after a long-running tool may silently switch to a different lens and discard prior work.
7147
7948
 
@@ -7291,78 +8092,303 @@ spend before spending it again.
7291
8092
 
7292
8093
  This tool MUTATES state. The caller (agent or human-in-the-loop) is responsible for confirming intent before invocation; the MCP server does not soft-prompt for confirmation. See \`annotations.destructiveHint\`.
7293
8094
  `;
7294
- var leadbay_qualify_status = `Retrieve the current state of a bulk_qualify_leads or import_and_qualify launch. Which ids to pass depends on which tool launched it, because only one of them creates a qualification job on the backend:
8095
+ var leadbay_qualify_leads = `## WHEN TO USE
7295
8096
 
7296
- - **\`leadbay_bulk_qualify_leads\`** returns a \`notification_id\`. Pass it for progress in ONE call, and add the \`lead_ids\` + \`lens_id\` it also returned for per-lead detail (which settled, which are still running).
7297
- - **\`leadbay_import_and_qualify\`** returns NO qualification \`notification_id\` \u2014 its qualify phase runs per-lead, so no job notification exists. Pass the \`lead_ids\` + \`lens_id\` it returned. Its \`notification_ids[]\` are the FILE-IMPORT notifications; handing one of those to this tool is rejected as the wrong kind, and \`leadbay_import_status({importIds})\` is where the import half is polled.
8097
+ Trigger phrases: "qualify these companies", "vet this list", "which of these fit our ICP", "score these websites / accounts", "get me the right contact at these companies", "re-qualify what you delivered last week".
7298
8098
 
7299
- **When it is finished:** \`status\` is always \`"launched"\` \u2014 it is not a progress field. On the \`notification_id\` path the job is done when \`in_progress\` is false (or \`bulk_progress.success_count + failure_count\` reaches \`total_count\`); \`still_running[]\` is empty on that path from the very first poll and must NOT be read as "done". On the \`lead_ids\` path the job is done when \`still_running[]\` is empty. Pass both and you get both signals in one call.
8099
+ Do NOT use for: "find me new leads / companies that <profile>" \u2192 \`leadbay_find_new_leads\`; "qualify the top N of my lens batch" \u2192 \`leadbay_bulk_qualify_leads\`; "import this CSV file" \u2192 \`leadbay_import_leads\`; "tell me about <one company> in depth" \u2192 \`leadbay_research_lead_by_name_fuzzy\`; "add emails to the contacts I selected" \u2192 \`leadbay_enrich_titles\`.
7300
8100
 
7301
- Everything comes straight out of the launch response \u2014 nothing is stored on the MCP side. A backend job is scoped to the user who launched it, so a \`notification_id\` resolves from a later message, a later conversation, or the next day.
8101
+ Prefer when: the user points at SPECIFIC companies (ids, websites, names, a pasted list, "what you found yesterday") and wants fit verdicts and/or the right person to talk to.
7302
8102
 
7303
- WHEN TO USE: after leadbay_bulk_qualify_leads or leadbay_import_and_qualify came back with a non-empty \`still_running[]\`, call this tool a few minutes later (or hours) with those ids to retrieve the now-completed qualifications without re-running the import or re-spending qualify quota.
8103
+ Examples that SHOULD invoke this tool:
8104
+ - "Here are 60 restaurant websites from my Austin sweep \u2014 which fit, and who's the owner?"
8105
+ - "Re-qualify last week's delivery and get phone numbers for the good ones."
8106
+ - "Vet these 12 accounts from my spreadsheet against our criteria."
7304
8107
 
7305
- WHEN NOT TO USE: as a substitute for leadbay_research_lead_by_id \u2014 that's a deeper per-lead profile and includes contacts. This tool is purely the qualification answers + signals_count.
8108
+ Examples that should NOT invoke this tool (sound similar, route elsewhere):
8109
+ - "Find me 10 new gyms in Texas."
8110
+ - "Qualify the top 10 leads in my batch."
8111
+ - "I have a CSV of 400 attendees to import."
7306
8112
 
7307
- ## A launched job cannot be stopped
8113
+ ## RENDER (quick)
7308
8114
 
7309
- Leadbay has no cancel. A job started by \`leadbay_enrich_titles\`,
7310
- \`leadbay_bulk_qualify_leads\`, \`leadbay_import_leads\` or
7311
- \`leadbay_import_and_qualify\` runs to completion on Leadbay. The user cancelling
7312
- in the chat, a request timeout, or a closed stream stops YOUR waiting, never the
7313
- job, and \`cancelled: true\` on an earlier result means we stopped watching, not
7314
- that the work stopped.
8115
+ 3-col table for delivered items (fit bar + company / why-fits \u226420 words /
8116
+ contact + channels) in returned order, then a compact Ref \u2192 Outcome table
8117
+ for skipped refs (not_in_universe, low_confidence_identity, ... in plain
8118
+ words), then the honest funnel + cost line. Full algorithm below.
7315
8119
 
7316
- **This tool only reads.** Calling it again launches nothing and spends no quota,
7317
- so poll it as often as the job needs \u2014 a timeout here is a reason to call it
7318
- again, not a reason to stop.
8120
+ ---
7319
8121
 
7320
- One import state does NOT progress: a chunk cancelled before its mappings were
7321
- committed reads \`running\` / \`committing\` forever. If the counts hold flat across
7322
- several spaced polls, say so and stop, rather than polling on.
8122
+ Submit a qualify batch over companies the org already has (or that exist in
8123
+ the Leadbay universe): each ref is resolved to a known company, freshly
8124
+ researched + AI-qualified against the org's questions / tags / ideal buyer
8125
+ profile (frozen at submit), matched to the requested contact titles, and \u2014
8126
+ when asked \u2014 enriched with verified channels. Answers arrive per-item from a
8127
+ job; this tool polls up to \`wait_seconds\` (default 45) and hands off to
8128
+ \`leadbay_lead_job_status\` when the batch needs longer.
8129
+
8130
+ **Refs are flexible; outcomes are per-item.** \`lead_refs\` accepts any mix of
8131
+ \`lead_id\`, \`website\`, \`name\`(+\`location\`), or a stable \`contact_id\` from a
8132
+ prior result (enrichment then targets exactly that person, never a re-match).
8133
+ \`prior_deliveries\` expands past MCP deliveries into refs \u2014 billed leads stay
8134
+ re-readable this way even after the 30-day result window. Duplicates collapse.
8135
+ A ref that can't be served comes back \`skipped\` with an honest
8136
+ \`status_reason\` (\`not_in_universe\`, \`low_confidence_identity\` with the
8137
+ \`resolution.alternatives\` to choose from, \`no_matching_contact\`, ...) \u2014 that
8138
+ is an ANSWER about the ref, not an error, and it costs nothing.
8139
+
8140
+ **Disqualified \u2260 dropped.** Companies the org owns that fail qualification
8141
+ are DELIVERED with their negative evidence (question verdicts, tag misses,
8142
+ IBP reasoning) \u2014 "here's why to skip this account" is a deliverable.
8143
+
8144
+ **Cost \u2014 never spend silently.** Resolution and identity are free.
8145
+ \`qualify: true\` (the default) costs ~94 cost_cents per lead needing FRESH
8146
+ research+scoring \u2014 but repeat calls reuse every fresh cached stage
8147
+ (\`from_cache\` flags on the items) and converge to near-zero cost. \`channels\`
8148
+ purchase verified email (25c) / phone (250c) on success only;
8149
+ \`already_owned\` values cost nothing.
8150
+
8151
+ The gate is enforced in code, not just here: a PAID call (\`qualify\` left at
8152
+ its default or set true, and/or any \`channels\`) is WITHHELD unless it carries
8153
+ \`confirm: true\`. Without it the tool submits nothing and returns
8154
+ \`mode: "needs_confirmation"\` with a real backend quote \u2014 show that quote to
8155
+ the user, get the go-ahead (an explicit "spend / get their emails" in their
8156
+ message counts), then re-call with \`confirm: true\`. \`confirm: false\` is a
8157
+ veto: nothing is submitted and no quote round-trip is made. A fully FREE
8158
+ call (\`qualify: false\`, no \`channels\`) needs no \`confirm\` and passes straight
8159
+ through. Set \`request_id\` and reuse it on retries of the same batch.
8160
+
8161
+ **Limits**: 500 refs/job, 3 active jobs/org, 10 submits/hour (429 +
8162
+ Retry-After beyond \u2014 wait, don't hammer), 30-min job wall clock.
7323
8163
 
7324
- What must not be repeated is the LAUNCH \u2014 for work that actually launched. Re-run
7325
- a launcher only for a subset that never started, never for the whole batch:
8164
+ ---
7326
8165
 
7327
- - \`failed[]\` entries with \`error:"not_queued"\`;
7328
- - a \`rows_pending_upload\` count;
7329
- - leads in \`still_running\` after a CANCELLED \`leadbay_import_and_qualify\`. Its
7330
- fan-out is sequential, so an interruption leaves the remainder unlaunched and
7331
- folds them in with the ones that did launch. Nothing in the result tells the
7332
- two apart, and this tool cannot start either. Wait until the REST of the batch
7333
- has settled: what launched settles in order, so leads still unanswered after
7334
- that are the ones that never started. Only then call
7335
- \`leadbay_bulk_qualify_leads({leadIds, lensId})\` for exactly those ids. A lead
7336
- that is merely slow looks identical to one that never launched over a few
7337
- polls, and re-launching it charges the user twice \u2014 when unsure, tell the user
7338
- rather than guess.
7339
- `;
7340
- var leadbay_recall_ordered_titles = `Show job titles the org has previously enriched, so the agent can repeat the same titles for new leads (or skip already-saturated ones). Two implementation paths: (1) PREFERRED \u2014 a selection-scoped preview call that reads \`previously_enriched_titles\` from the backend (newer prod field). (2) FALLBACK \u2014 live aggregation across each lead's enriched contacts. The composite picks transparently.
8166
+ ## RENDERING \u2014 delivery table + honest funnel line
7341
8167
 
7342
- WHEN TO USE: before leadbay_enrich_titles, to plan which titles to order.
8168
+ Render delivered leads (\`leads[]\`, i.e. items with status \`delivered\` or
8169
+ \`degraded\`) as a markdown table **in the order returned**. Exactly three
8170
+ columns. Then ALWAYS close with the funnel line (below) \u2014 even, especially,
8171
+ when nothing was delivered.
7343
8172
 
7344
- WHEN NOT TO USE: when you already know the exact titles you want to enrich.
7345
- `;
7346
- var leadbay_refine_prompt = `## WHEN TO USE
8173
+ **Column 1 \u2014 Company**
7347
8174
 
7348
- Trigger phrases: "focus on companies that <qualitative trait>", "I prefer leads that <behavior/characteristic>", "prioritize companies running their own IT", "deprioritize companies that just raised".
8175
+ - Line 1: 10-segment fit bar in inline-code backticks from \`lead.fit.score\`
8176
+ (0-100): \`filled = round(score/10)\`, glyphs \`\u25B0\` filled / \`\u25B1\` empty. When
8177
+ \`lead.fit.components.qualification.available\` is true AND \`ai_score > 0\`,
8178
+ replace the LAST filled segment with \`\u2756\` (AI-confirmed cap). When
8179
+ \`fit.available\` is false, render \`\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\` and say "unscored" in col 2.
8180
+ Never print the numeric score.
8181
+ - Insert \`<br>\`, then: linked company name (target \`company.website\`, bare
8182
+ hostnames get \`https://\`; unlinked plain text when absent) + \` \xB7 \` + short
8183
+ location (City, ST / City, Country) + \` \xB7 \` + employees as \`min\u2013max\` (omit
8184
+ when \`employees.known\` is false).
7349
8185
 
7350
- Do NOT use for: "create a new lens / a lens specialized into <X>" \u2192 \`leadbay_new_lens\`; "add/remove <sector> to/from my <name> lens" \u2192 \`leadbay_adjust_audience\`; "narrow the audience to <sector> / <size>" \u2192 \`leadbay_adjust_audience\`; "show me / list / switch my lenses" \u2192 \`leadbay_my_lenses\`.
8186
+ **Column 2 \u2014 Why it fits**
7351
8187
 
7352
- Prefer when: ADMIN-ONLY. Qualitative refinement of the active lens that sector/size can't express. Creating/naming/listing/switching/sector-editing a lens routes elsewhere. Non-admin user \u2192 do NOT pick this.
8188
+ - One sentence \u2264 20 words. Priority: \`fit.reasoning\` \u2192 gist of
8189
+ \`company.description\` \u2192 top \`fit.components.qualification.matched_tags\`.
8190
+ - If the item status is \`degraded\` or a requested channel failed, append the
8191
+ honest flag in italics, e.g. *(email could not be sourced)*.
7353
8192
 
7354
- Examples that SHOULD invoke this tool:
7355
- - "Focus on hospitals that run their own IT in-house."
7356
- - "Prioritize companies that have recently expanded headcount."
8193
+ **Column 3 \u2014 Contact**
7357
8194
 
7358
- Examples that should NOT invoke this tool (sound similar, route elsewhere):
7359
- - "Create a lens specialized in automobile."
7360
- - "Add fintech to my Joinery lens."
7361
- - "Show me my lenses."
8195
+ - \`[Name](linkedin) \xB7 role\` (linked name mandatory when a LinkedIn URL
8196
+ exists; plain name otherwise). Below it, the PURCHASED channels only:
8197
+ \`\u2709 value\` / \`\u260E value\` inline as plain text (they auto-linkify).
8198
+ - Channel statuses: \`delivered\` \u2192 show value; \`already_owned\` \u2192 value +
8199
+ *(already yours)*; \`masked\` \u2192 "on file \u2014 reveal via channels";
8200
+ \`not_requested\` \u2192 omit; \`failed_*\` \u2192 *(no verified email/phone)*.
8201
+ - No contact on the item (\`contact\` null): render \`\u2014\` (title_gate \`prefer\`
8202
+ delivers such rows flagged; say so in col 2 only when contact_titles were
8203
+ requested).
8204
+
8205
+ **The funnel line (mandatory, after the table):**
8206
+
8207
+ One short line narrating the delivery honestly, from \`funnel\` + \`cost\` +
8208
+ \`explain.scope_notes\`:
8209
+
8210
+ > Matched N \xB7 examined E \xB7 qualified Q \xB7 disqualified D \u2192 **delivered X of
8211
+ > the Y asked** \xB7 stopped: <stop_reason in plain words> \xB7 spent C.CC.
8212
+
8213
+ **Money: divide, then symbol.** Every amount (\`cost.spent\`,
8214
+ \`estimated_cost.max\`, quotes) is \`cost_cents\` \u2014 divide by 100, two decimals,
8215
+ so \`165\` renders \`1.65\`, NEVER \`165.00\`. Symbol from the account region: US
8216
+ \`$\`, France \`\u20AC\`, unknown \u2192 bare. Never hard-code \`$\`: it misstates a charge.
8217
+
8218
+ "of the Y asked" needs \`summary.items_requested\`, which submits carry but a
8219
+ later \`leadbay_lead_job_status\` snapshot does not. Without it write **delivered
8220
+ X** and stop \u2014 never back-fill Y from \`matched\`/\`examined\` (they count
8221
+ candidates), never guess it.
8222
+
8223
+ Plain-word stop reasons: \`target_reached\` \u2192 omit (success), \`pool_exhausted\` \u2192
8224
+ "ran out of matching candidates", \`max_cost\` \u2192 "hit the cost cap", \`quota\` \u2192
8225
+ "hit an org quota", \`time_budget\` \u2192 "hit the 30-min time budget".
8226
+
8227
+ **When \`delivered\` is 0**: NEVER say just "no results". Render no table; give
8228
+ the funnel line plus the relevant \`explain.scope_notes\` (the backend's own
8229
+ diagnosis), then propose the concrete fix (reshape the seed per the craft
8230
+ rules, lower \`min_ai_score\`, raise \`max_cost\`, drop a filter) as NEXT STEPS.
8231
+
8232
+ **Weak batch**: when the BEST delivered \`fit.score\` is under 30, don't present
8233
+ the table as an answer \u2014 open with "weak matches only", show at most the top 3,
8234
+ propose reshaping the seed/filters first. The count was filled with
8235
+ barely-better-than-random candidates.
8236
+
8237
+ **Sanity-check every row**: (a) geo \u2014 \`city\`/\`region\` must sit inside any
8238
+ requested fence; drop and call out leaks (same-named cities slip through).
8239
+ (b) When \`explain.seed_strategy\` is \`text_match_exemplars\` (the standard FR
8240
+ path), fit is calibrated for lead-to-lead distances, not exemplar centroids \u2014
8241
+ treat high scores skeptically and verify each row's \`description\`.
8242
+
8243
+ **Skipped items** (\`skipped[]\`, qualify jobs mostly): render a compact second
8244
+ table \`Ref \u2192 Outcome\` translating \`status_reason\` to plain words:
8245
+ \`not_in_universe\` \u2192 "not in the Leadbay universe (import it first)",
8246
+ \`low_confidence_identity\` \u2192 "couldn't safely match \u2014 check \`resolution.alternatives\`",
8247
+ \`no_matching_contact\` \u2192 "no contact with the requested title",
8248
+ \`disqualified\` \u2192 "evaluated: does not fit" (evidence is in the item when owned),
8249
+ \`enrichment_failed\` \u2192 "channel could not be sourced (not billed)".
8250
+
8251
+ **\`items_truncated\`**: rows are a PREFIX, not the batch. Say so, and offer
8252
+ \`leadbay_lead_job_status(job_id, since: next_since)\` for the rest.
8253
+
8254
+ **Hide from the user:** UUIDs (keep for tool calls, never render), cursors,
8255
+ \`explain.model\`/\`intelligence_snapshot\`, raw \`distance\`/\`calibration\`,
8256
+ \`seq\`/\`from_cache\`, empty arrays.
7362
8257
 
7363
- ## RENDER (quick)
8258
+ ## Linking a contact's name
7364
8259
 
7365
- On success: confirm the refinement applied to the active lens. If a
8260
+ **MANDATORY: every contact name in your output \u2014 table cells, prose, headers, "Reach <Name>" callouts \u2014 MUST be wrapped in markdown link syntax \`[Name](URL)\`. Never render a contact name as bare text. A plain-text name is a broken contact card; the underlined name is the user's primary affordance for "take me to this person's profile". No "no URL available" exception \u2014 the search URL below is always constructable from name + company.**
8261
+
8262
+ URL priority (first applicable wins):
8263
+
8264
+ 1. **Real profile** \u2014 \`contact.linkedin_page\` when it's a string starting with \`https://\` (the MCP coerces the legacy literal \`"null"\` string to real null before you see it).
8265
+ 2. **Constructed people-search** \u2014 \`https://www.linkedin.com/search/results/people/?keywords=<First>+<Last>+<Company>\`. URL-encode params. Strip Inc / LLC / Corp / Ltd / GmbH / Co / S.A. / S.L. / PLC / AG / SAS / SARL suffixes from the company. Append a trailing \` \xB0\` to the rendered name ONLY when this fallback is in use AND \`social_presence.linkedin == false\`. Never append \`\xB0\` when a real \`linkedin_page\` was used.
8266
+
8267
+ Never link a person's name to the company's LinkedIn page (and vice versa) \u2014 the two surfaces are different and conflating them quietly degrades the workflow.
8268
+
8269
+
8270
+
8271
+ **Delivered \u2260 endorsed.** This tool DELIVERS org-owned companies that FAILED
8272
+ qualification, carrying their negative evidence \u2014 so a delivered item is not
8273
+ automatically a prospect. An item whose \`status_reason\` is \`disqualified\`, or
8274
+ whose \`fit.components.qualification\` is available with a negative \`ai_score\`,
8275
+ must NOT go in the fit table: its firmographic score can still be high, and a
8276
+ full bar beside "why it fits" reads as a recommendation to call an account the
8277
+ evaluation just rejected.
8278
+
8279
+ Give those their own short section after the fit table, titled
8280
+ **Evaluated \u2014 does not fit**: linked company, then the verdict in plain
8281
+ words from the
8282
+ qualification evidence (failed question verdicts, missed tags, IBP reasoning).
8283
+ That is the deliverable \u2014 "here's why to skip this account" \u2014 not a defect to
8284
+ hide.
8285
+
8286
+
8287
+ ---
8288
+
8289
+ ## NEXT STEPS \u2014 after a qualify_leads delivery
8290
+
8291
+ **ALWAYS render NEXT STEPS via your host's next-step widget.** Use whichever is in your tool set \u2014 the NAME and SCHEMA differ: **\`ask_user_input_v0\`** (Claude chat / ChatGPT) takes plain-string options with \`type:"single_select"\`; **\`AskUserQuestion\`** (Claude cowork / Claude Code) takes object options \`{label, description}\` plus a required short \`header\` (\u226412 chars) and \`multiSelect\`, NO \`type\` field, and never add an "Other" option (the host adds it). Match the schema to the tool you actually have \u2014 the wrong schema fails silently and you fall back to prose. Prose bullets are the fallback ONLY when NEITHER widget exists. Any turn that would end with a choice must be the widget \u2014 the widget IS the question.
8292
+
8293
+ **If the tool result carries a \`next_steps\` object, that is the source of truth \u2014 use it directly.** Each option has a short \`.label\` (\u22645 words) and a full \`.description\`. Map \`next_steps.options[]\` into your host widget VERBATIM and in order: for \`AskUserQuestion\` (cowork / Claude Code) pass each as \`{label, description}\`; for \`ask_user_input_v0\` (Claude chat / ChatGPT, string options only) pass each option's \`.description\` as the string (it's the full sentence). Do NOT reword, reorder, drop, or prose-ify them \u2014 they're built deterministically by the server so the offer (incl. the artifact option at position 0) fires every time. Fall back to the table below only when there is NO \`next_steps\` field.
8294
+
8295
+ **One exception \u2014 skip the widget** when the user's original message contained a complete sequential instruction chain ("show me X and then do Y") AND all stated steps have been completed. In that case, end with STOP directly \u2014 the user stated their full plan and does not need a "what next?" prompt.
8296
+ - Skip example: "Show me today's leads and then research the top one for me." \u2192 after research completes, emit STOP without the widget.
8297
+ - Do NOT skip for: plain requests ("show me today's leads", "run my check-in"), recurring-language requests ("I do this every day"), or requests where only one action was stated.
8298
+
8299
+ Pick 2\u20134 rows from the (Observation, Suggest, Calls) table below most relevant to the response, then call your host's widget with ITS schema (per the schema rules above \u2014 wrong schema fails silently):
8300
+ - \`ask_user_input_v0\`: \`{questions:[{question,type:"single_select",options:["<Suggest 1>","<Suggest 2>"]}]}\`
8301
+ - \`AskUserQuestion\`: \`{questions:[{question,header:"Next step",multiSelect:false,options:[{label:"<\u22645 words>",description:"<Suggest 1>"}]}]}\`
8302
+
8303
+ User picks \u2192 call the matching \`Calls\` tool. Constraints: 2\u20134 mutually-exclusive options, AskUserQuestion labels \u22645 words (full text in \`description\`), max 3 questions. Table stays internal; never recite it.
8304
+
8305
+ ---
8306
+
8307
+
8308
+
8309
+ Pick the 2-3 options that match what actually happened:
8310
+
8311
+ | Observation | Suggest | Calls |
8312
+ |---|---|---|
8313
+ | Job still running | "Check on it in ~1 min" | leadbay_lead_job_status(job_id, wait_seconds: 60) |
8314
+ | Fit leads with contacts delivered | "Draft outreach for the qualified ones" | leadbay_prepare_outreach |
8315
+ | Items skipped \`not_in_universe\` | "Import those companies first, then re-qualify" | leadbay_import_leads \u2192 leadbay_qualify_leads |
8316
+ | Items skipped \`low_confidence_identity\` | "Pick the right match" (show \`resolution.alternatives\`) | leadbay_qualify_leads with the chosen lead_id |
8317
+ | Contacts delivered without channels | "Purchase verified emails/phones for the keepers (state cost first)" | leadbay_qualify_leads(lead_refs with contact_id, channels) |
8318
+ | Disqualified with evidence | "Review why \u2014 adjust qualification questions if the criteria are off" | leadbay_get_qualification_questions |
8319
+ `;
8320
+ var leadbay_qualify_status = `Retrieve the current state of a bulk_qualify_leads or import_and_qualify launch. Which ids to pass depends on which tool launched it, because only one of them creates a qualification job on the backend:
8321
+
8322
+ - **\`leadbay_bulk_qualify_leads\`** returns a \`notification_id\`. Pass it for progress in ONE call, and add the \`lead_ids\` + \`lens_id\` it also returned for per-lead detail (which settled, which are still running).
8323
+ - **\`leadbay_import_and_qualify\`** returns NO qualification \`notification_id\` \u2014 its qualify phase runs per-lead, so no job notification exists. Pass the \`lead_ids\` + \`lens_id\` it returned. Its \`notification_ids[]\` are the FILE-IMPORT notifications; handing one of those to this tool is rejected as the wrong kind, and \`leadbay_import_status({importIds})\` is where the import half is polled.
8324
+
8325
+ **When it is finished:** \`status\` is always \`"launched"\` \u2014 it is not a progress field. On the \`notification_id\` path the job is done when \`in_progress\` is false (or \`bulk_progress.success_count + failure_count\` reaches \`total_count\`); \`still_running[]\` is empty on that path from the very first poll and must NOT be read as "done". On the \`lead_ids\` path the job is done when \`still_running[]\` is empty. Pass both and you get both signals in one call.
8326
+
8327
+ Everything comes straight out of the launch response \u2014 nothing is stored on the MCP side. A backend job is scoped to the user who launched it, so a \`notification_id\` resolves from a later message, a later conversation, or the next day.
8328
+
8329
+ WHEN TO USE: after leadbay_bulk_qualify_leads or leadbay_import_and_qualify came back with a non-empty \`still_running[]\`, call this tool a few minutes later (or hours) with those ids to retrieve the now-completed qualifications without re-running the import or re-spending qualify quota.
8330
+
8331
+ WHEN NOT TO USE: as a substitute for leadbay_research_lead_by_id \u2014 that's a deeper per-lead profile and includes contacts. This tool is purely the qualification answers + signals_count.
8332
+
8333
+ ## A launched job cannot be stopped
8334
+
8335
+ Leadbay has no cancel. A job started by \`leadbay_enrich_titles\`,
8336
+ \`leadbay_bulk_qualify_leads\`, \`leadbay_import_leads\` or
8337
+ \`leadbay_import_and_qualify\` runs to completion on Leadbay. The user cancelling
8338
+ in the chat, a request timeout, or a closed stream stops YOUR waiting, never the
8339
+ job, and \`cancelled: true\` on an earlier result means we stopped watching, not
8340
+ that the work stopped.
8341
+
8342
+ **This tool only reads.** Calling it again launches nothing and spends no quota,
8343
+ so poll it as often as the job needs \u2014 a timeout here is a reason to call it
8344
+ again, not a reason to stop.
8345
+
8346
+ One import state does NOT progress: a chunk cancelled before its mappings were
8347
+ committed reads \`running\` / \`committing\` forever. If the counts hold flat across
8348
+ several spaced polls, say so and stop, rather than polling on.
8349
+
8350
+ What must not be repeated is the LAUNCH \u2014 for work that actually launched. Re-run
8351
+ a launcher only for a subset that never started, never for the whole batch:
8352
+
8353
+ - \`failed[]\` entries with \`error:"not_queued"\`;
8354
+ - a \`rows_pending_upload\` count;
8355
+ - leads in \`still_running\` after a CANCELLED \`leadbay_import_and_qualify\`. Its
8356
+ fan-out is sequential, so an interruption leaves the remainder unlaunched and
8357
+ folds them in with the ones that did launch. Nothing in the result tells the
8358
+ two apart, and this tool cannot start either. Wait until the REST of the batch
8359
+ has settled: what launched settles in order, so leads still unanswered after
8360
+ that are the ones that never started. Only then call
8361
+ \`leadbay_bulk_qualify_leads({leadIds, lensId})\` for exactly those ids. A lead
8362
+ that is merely slow looks identical to one that never launched over a few
8363
+ polls, and re-launching it charges the user twice \u2014 when unsure, tell the user
8364
+ rather than guess.
8365
+ `;
8366
+ var leadbay_recall_ordered_titles = `Show job titles the org has previously enriched, so the agent can repeat the same titles for new leads (or skip already-saturated ones). Two implementation paths: (1) PREFERRED \u2014 a selection-scoped preview call that reads \`previously_enriched_titles\` from the backend (newer prod field). (2) FALLBACK \u2014 live aggregation across each lead's enriched contacts. The composite picks transparently.
8367
+
8368
+ WHEN TO USE: before leadbay_enrich_titles, to plan which titles to order.
8369
+
8370
+ WHEN NOT TO USE: when you already know the exact titles you want to enrich.
8371
+ `;
8372
+ var leadbay_refine_prompt = `## WHEN TO USE
8373
+
8374
+ Trigger phrases: "focus on companies that <qualitative trait>", "I prefer leads that <behavior/characteristic>", "prioritize companies running their own IT", "deprioritize companies that just raised".
8375
+
8376
+ Do NOT use for: "create a new lens / a lens specialized into <X>" \u2192 \`leadbay_new_lens\`; "add/remove <sector> to/from my <name> lens" \u2192 \`leadbay_adjust_audience\`; "narrow the audience to <sector> / <size>" \u2192 \`leadbay_adjust_audience\`; "show me / list / switch my lenses" \u2192 \`leadbay_my_lenses\`.
8377
+
8378
+ Prefer when: ADMIN-ONLY. Qualitative refinement of the active lens that sector/size can't express. Creating/naming/listing/switching/sector-editing a lens routes elsewhere. Non-admin user \u2192 do NOT pick this.
8379
+
8380
+ Examples that SHOULD invoke this tool:
8381
+ - "Focus on hospitals that run their own IT in-house."
8382
+ - "Prioritize companies that have recently expanded headcount."
8383
+
8384
+ Examples that should NOT invoke this tool (sound similar, route elsewhere):
8385
+ - "Create a lens specialized in automobile."
8386
+ - "Add fintech to my Joinery lens."
8387
+ - "Show me my lenses."
8388
+
8389
+ ## RENDER (quick)
8390
+
8391
+ On success: confirm the refinement applied to the active lens. If a
7366
8392
  clarification was raised, surface its question (route via ask_user_input_v0).
7367
8393
 
7368
8394
  ---
@@ -8869,7 +9895,7 @@ This tool MUTATES state. The caller (agent or human-in-the-loop) is responsible
8869
9895
  var NO_COMMERCE_TOOL_DESCRIPTIONS = {
8870
9896
  leadbay_account_status: `## WHEN TO USE
8871
9897
 
8872
- Trigger phrases: "what's my account status", "how much quota do I have", "what lens am I on", "I topped up / I bought credits / I added credits".
9898
+ Trigger phrases: "what's my account status", "how much quota do I have", "what lens am I on", "I topped up / I bought credits / I added credits", "what version of Leadbay am I running".
8873
9899
 
8874
9900
  Do NOT use for: "show me leads" \u2192 \`leadbay_pull_leads\`.
8875
9901
 
@@ -8878,6 +9904,7 @@ Prefer when: meta question about account, quota, active lens, or top-up recovery
8878
9904
  Examples that SHOULD invoke this tool:
8879
9905
  - "What's my account status?"
8880
9906
  - "How much quota do I have left this week?"
9907
+ - "Which version of the Leadbay connector is this?"
8881
9908
 
8882
9909
  Examples that should NOT invoke this tool (sound similar, route elsewhere):
8883
9910
  - "Show me today's leads."
@@ -8899,6 +9926,8 @@ Show the user's account state \u2014 admin rights, language, last-active lens, q
8899
9926
 
8900
9927
  **After a user tops up, do NOT keep refusing \u2014 RETRY.** If the user signals they topped up / bought credits / added credits, the previous QUOTA_EXCEEDED is invalidated the moment the Stripe webhook lands. RE-CALL \`leadbay_account_status\` to pick up the new state AND retry the originally failed call. The retry itself does not require a successful account_status check first \u2014 a topped-up user has cleared the throttle whether or not your cached snapshot reflects it yet. **A stale quota snapshot is never a reason to gate-keep a topped-up user.**
8901
9928
 
9929
+ **\`mcp_version\`** is the version of the Leadbay MCP server answering the call. When the user asks which Leadbay version they are running, answer with it.
9930
+
8902
9931
  **\`notifications\` block.** The response now includes a top-level \`notifications\` array listing background work the user (or agent) initiated that has since completed (\`bulk_enrich\`, \`bulk_qualify\`, \`import\`). These are signals to revise prior agent outputs the just-finished work might have made stale \u2014 they're NOT a pending-task list for the user. After revising (or confirming nothing is affected), call \`leadbay_acknowledge_notification(notification_id)\`. Full handling protocol below.
8903
9932
 
8904
9933
  ## GATE \u2014 INSPECT \`_meta.notifications\` ON EVERY RESPONSE
@@ -9019,6 +10048,255 @@ Keep it secondary \u2014 the three window gauges are the headline. Omit when nul
9019
10048
  WHEN TO USE: at the start of a session to know what the agent can/can't do, after a 429 to explain to the user which resource window was exhausted and when it resets, and after the user signals a top-up so the agent can resume the interrupted workflow.
9020
10049
 
9021
10050
  WHEN NOT TO USE: as a pre-flight gate before bulk ops \u2014 operations themselves return 429; this tool is for context, not gating. And: a recent quota snapshot showing "exhausted" is NOT a reason to refuse a write call when the user has just topped up \u2014 re-call this tool first, then proceed.
10051
+ `,
10052
+ leadbay_find_new_leads: `## WHEN TO USE
10053
+
10054
+ Trigger phrases: "find me N companies that <profile>", "get me new prospects like <company>", "I need leads in <place> that <do X>", "search for companies that would buy <product>", "net-new leads outside my current pipeline", "we're entering <market> \u2014 who should we target".
10055
+
10056
+ Do NOT use for: "show me today's leads / what's new today" \u2192 \`leadbay_pull_leads\`; "find me new leads (no profile, no count named)" \u2192 \`leadbay_pull_leads\`; "more leads like the ones in my lens" \u2192 \`leadbay_extend_lens\`; "qualify / vet these companies I have" \u2192 \`leadbay_qualify_leads\`; "qualify the top N of my batch" \u2192 \`leadbay_bulk_qualify_leads\`; "leads I should follow up with" \u2192 \`leadbay_pull_followups\`; "tell me about <one company>" \u2192 \`leadbay_research_lead_by_name_fuzzy\`.
10057
+
10058
+ Prefer when: the user describes a target profile or names a count of NEW companies \u2014 craft the example_lead per the seed rules below BEFORE calling; never pass the user's raw sentence as query.
10059
+
10060
+ Examples that SHOULD invoke this tool:
10061
+ - "Find me 10 gyms around Dallas that would buy our flooring, with someone I can call."
10062
+ - "Get me 20 new US SaaS companies, 50-2000 employees, with the VP People's email."
10063
+ - "We're launching in Lyon \u2014 find 15 hotels that fit our ICP."
10064
+
10065
+ Examples that should NOT invoke this tool (sound similar, route elsewhere):
10066
+ - "Show me today's leads."
10067
+ - "Which leads should I follow up with this week?"
10068
+ - "Qualify these 40 websites from my spreadsheet."
10069
+
10070
+ ## RENDER (quick)
10071
+
10072
+ 3-col table of delivered leads in returned order: col 1 = 10-segment fit
10073
+ bar + linked company \xB7 location \xB7 size; col 2 = why-fits \u226420 words; col 3
10074
+ = contact + purchased channels. ALWAYS close with the honest funnel line
10075
+ (matched/examined/delivered/stop reason/spend) \u2014 especially on 0
10076
+ delivered. Full algorithm below.
10077
+
10078
+ ---
10079
+
10080
+ Submit a net-new lead search: the backend matches an ICP seed against the full
10081
+ company universe, applies hard filters, skips what the org already knows
10082
+ (\`novelty: org\`), optionally qualifies against the org's own intelligence
10083
+ (questions, tags, ideal buyer profile \u2014 frozen at submit), and optionally buys
10084
+ contact channels. Polls up to \`wait_seconds\` (default 45); a longer job returns
10085
+ \`still_running\` + \`next_poll\` \u2014 hand off to \`leadbay_lead_job_status\`. Jobs run
10086
+ \u226430 min, results kept 30 days.
10087
+
10088
+ **Free vs paid \u2014 never spend silently.** Default (\`qualify: false\`,
10089
+ \`channels: []\`) is FREE: company profile + fit score + cached research +
10090
+ contact identity. Paid: \`qualify: true\` (~94 cost_cents per candidate
10091
+ EXAMINED, capped by \`exploration_cap\`/\`max_cost\`) and \`channels\` (email 25c /
10092
+ phone 250c, success-only). Enforced in code: a paid call is WITHHELD unless it
10093
+ carries \`confirm: true\` \u2014 nothing is submitted and you get
10094
+ \`mode: "needs_confirmation"\` with a real quote to show the user. Re-call with
10095
+ \`confirm: true\` on their go-ahead ("spend / get their emails" counts).
10096
+ \`confirm: false\` vetoes. Free needs no consent. **Preview free first** \u2014
10097
+ reshaping an off-profile seed is free, exploring it with \`qualify: true\` is
10098
+ not.
10099
+
10100
+ **Ad-hoc exclusions ("no chains") are enforced by NO tier** \u2014 \`filters\` has no
10101
+ exclusion key, and \`qualify\` scores against the org's FROZEN questions and IBP,
10102
+ which need not mention chains; the seed's inverse only shifts ranking.
10103
+ Violators can survive, be paid for and be delivered \u2014 post-filter them yourself
10104
+ and say the tier didn't enforce it. Durable enforcement \u2192
10105
+ \`leadbay_refine_prompt\`.
10106
+
10107
+ ### Crafting the \`example_lead\` seed \u2014 the input that decides result quality
10108
+
10109
+ The \`example_lead\` is a FICTIONAL typical ideal customer, matched against real
10110
+ registry/website descriptions \u2014 which state what a company **IS**, never what
10111
+ is happening. Write it the same way or the matcher drifts. Every rule below is
10112
+ measured:
10113
+
10114
+ 1. **Describe the BUYER, never the seller.** Ask: "would this company write a
10115
+ check to my user?" A seed describing what the user SELLS surfaces their
10116
+ *competitors and vendors*. If the product helps companies of type X serve
10117
+ customers of type Y, the seed describes X \u2014 never Y.
10118
+ 2. **Put everything in \`description\`; leave \`name\` unset.** An invented brand
10119
+ name pulls matching toward name-lookalikes \u2014 a seed named "Meridian
10120
+ Analytics" returned five unrelated "Meridian" companies.
10121
+ 3. **Registry style, one sentence to ~250 chars.** Industry niche, business
10122
+ model, what they sell or operate, who they serve, observable scale. Write
10123
+ it like the first paragraph of their About-Us page.
10124
+ - STRONG: "Operator of full-service fitness centers offering strength
10125
+ areas, group classes and personal training to members across multiple
10126
+ clubs."
10127
+ - WEAK (generic): "A gym in Texas."
10128
+ - WRONG (seller-side): "Supplier of durable modular flooring for gyms."
10129
+ 4. **No event language.** "hiring", "expanding", "just raised" are not
10130
+ filters \u2014 registry descriptions never contain them, so they dilute the
10131
+ profile. Purchase triggers belong in the org's qualification questions.
10132
+ 5. **No meta-markers.** Never "(example)", "(fictional)", "(placeholder)".
10133
+ 6. **Hard constraints go in \`filters\`, not prose \u2014 exact keys:**
10134
+ \`sectors: string[]\`, \`locations: string[]\`, \`employees_min: number\`,
10135
+ \`employees_max: number\`. FLAT numbers \u2014 nested \`employees: {min, max}\`
10136
+ exists only in RESULT payloads. \`example_lead.employees\` does not filter.
10137
+ \`locations\` take city/state/region names ("Dallas, TX", "\xCEle-de-France");
10138
+ a country name is refused in code \u2014 whole-country intent = omit it.
10139
+ 7. **Prefer \`example_lead\` over \`query\`.** Query matches topic *vocabulary*:
10140
+ "gyms that need durable flooring" surfaced flooring VENDORS, 0 delivered.
10141
+ Use \`query\` only for signal an example can't express.
10142
+ 8. **One seed per buyer archetype.** An ask spanning two segments ("gyms and
10143
+ warehouses") needs one search each with its own description and
10144
+ \`request_id\` \u2014 a blended seed lands between the clusters and matches
10145
+ neither.
10146
+
10147
+
10148
+ **Parameter notes**
10149
+ - \`request_id\` (REQUIRED) is the retry contract: SAME value retrying the same
10150
+ ask (same live job, no double spend); NEW for a changed ask. Derive from ask
10151
+ + archetype + date: \`gyms-dallas-2026-07-28\`.
10152
+ - Never lower \`min_ai_score\` together with \`channels\` \u2014 that buys emails for
10153
+ leads the AI just scored as junk.
10154
+ - \`count\` \u2264 50; \u22643 active jobs/org; \u226410 submits/hour (429 + Retry-After \u2014
10155
+ wait, don't hammer).
10156
+
10157
+ **Read the result honestly** \u2014 \`funnel\` + \`explain.scope_notes\` tell the story;
10158
+ zero delivered gets a cause and a next move (rules in RENDERING).
10159
+
10160
+ ---
10161
+
10162
+ ## RENDERING \u2014 delivery table + honest funnel line
10163
+
10164
+ Render delivered leads (\`leads[]\`, i.e. items with status \`delivered\` or
10165
+ \`degraded\`) as a markdown table **in the order returned**. Exactly three
10166
+ columns. Then ALWAYS close with the funnel line (below) \u2014 even, especially,
10167
+ when nothing was delivered.
10168
+
10169
+ **Column 1 \u2014 Company**
10170
+
10171
+ - Line 1: 10-segment fit bar in inline-code backticks from \`lead.fit.score\`
10172
+ (0-100): \`filled = round(score/10)\`, glyphs \`\u25B0\` filled / \`\u25B1\` empty. When
10173
+ \`lead.fit.components.qualification.available\` is true AND \`ai_score > 0\`,
10174
+ replace the LAST filled segment with \`\u2756\` (AI-confirmed cap). When
10175
+ \`fit.available\` is false, render \`\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\` and say "unscored" in col 2.
10176
+ Never print the numeric score.
10177
+ - Insert \`<br>\`, then: linked company name (target \`company.website\`, bare
10178
+ hostnames get \`https://\`; unlinked plain text when absent) + \` \xB7 \` + short
10179
+ location (City, ST / City, Country) + \` \xB7 \` + employees as \`min\u2013max\` (omit
10180
+ when \`employees.known\` is false).
10181
+
10182
+ **Column 2 \u2014 Why it fits**
10183
+
10184
+ - One sentence \u2264 20 words. Priority: \`fit.reasoning\` \u2192 gist of
10185
+ \`company.description\` \u2192 top \`fit.components.qualification.matched_tags\`.
10186
+ - If the item status is \`degraded\` or a requested channel failed, append the
10187
+ honest flag in italics, e.g. *(email could not be sourced)*.
10188
+
10189
+ **Column 3 \u2014 Contact**
10190
+
10191
+ - \`[Name](linkedin) \xB7 role\` (linked name mandatory when a LinkedIn URL
10192
+ exists; plain name otherwise). Below it, the PURCHASED channels only:
10193
+ \`\u2709 value\` / \`\u260E value\` inline as plain text (they auto-linkify).
10194
+ - Channel statuses: \`delivered\` \u2192 show value; \`already_owned\` \u2192 value +
10195
+ *(already yours)*; \`masked\` \u2192 "on file \u2014 reveal via channels";
10196
+ \`not_requested\` \u2192 omit; \`failed_*\` \u2192 *(no verified email/phone)*.
10197
+ - No contact on the item (\`contact\` null): render \`\u2014\` (title_gate \`prefer\`
10198
+ delivers such rows flagged; say so in col 2 only when contact_titles were
10199
+ requested).
10200
+
10201
+ **The funnel line (mandatory, after the table):**
10202
+
10203
+ One short line narrating the delivery honestly, from \`funnel\` + \`cost\` +
10204
+ \`explain.scope_notes\`:
10205
+
10206
+ > Matched N \xB7 examined E \xB7 qualified Q \xB7 disqualified D \u2192 **delivered X of
10207
+ > the Y asked** \xB7 stopped: <stop_reason in plain words> \xB7 spent C.CC.
10208
+
10209
+ **Money: divide, then symbol.** Every amount (\`cost.spent\`,
10210
+ \`estimated_cost.max\`, quotes) is \`cost_cents\` \u2014 divide by 100, two decimals,
10211
+ so \`165\` renders \`1.65\`, NEVER \`165.00\`. Symbol from the account region: US
10212
+ \`$\`, France \`\u20AC\`, unknown \u2192 bare. Never hard-code \`$\`: it misstates a charge.
10213
+
10214
+ "of the Y asked" needs \`summary.items_requested\`, which submits carry but a
10215
+ later \`leadbay_lead_job_status\` snapshot does not. Without it write **delivered
10216
+ X** and stop \u2014 never back-fill Y from \`matched\`/\`examined\` (they count
10217
+ candidates), never guess it.
10218
+
10219
+ Plain-word stop reasons: \`target_reached\` \u2192 omit (success), \`pool_exhausted\` \u2192
10220
+ "ran out of matching candidates", \`max_cost\` \u2192 "hit the cost cap", \`quota\` \u2192
10221
+ "hit an org quota", \`time_budget\` \u2192 "hit the 30-min time budget".
10222
+
10223
+ **When \`delivered\` is 0**: NEVER say just "no results". Render no table; give
10224
+ the funnel line plus the relevant \`explain.scope_notes\` (the backend's own
10225
+ diagnosis), then propose the concrete fix (reshape the seed per the craft
10226
+ rules, lower \`min_ai_score\`, raise \`max_cost\`, drop a filter) as NEXT STEPS.
10227
+
10228
+ **Weak batch**: when the BEST delivered \`fit.score\` is under 30, don't present
10229
+ the table as an answer \u2014 open with "weak matches only", show at most the top 3,
10230
+ propose reshaping the seed/filters first. The count was filled with
10231
+ barely-better-than-random candidates.
10232
+
10233
+ **Sanity-check every row**: (a) geo \u2014 \`city\`/\`region\` must sit inside any
10234
+ requested fence; drop and call out leaks (same-named cities slip through).
10235
+ (b) When \`explain.seed_strategy\` is \`text_match_exemplars\` (the standard FR
10236
+ path), fit is calibrated for lead-to-lead distances, not exemplar centroids \u2014
10237
+ treat high scores skeptically and verify each row's \`description\`.
10238
+
10239
+ **Skipped items** (\`skipped[]\`, qualify jobs mostly): render a compact second
10240
+ table \`Ref \u2192 Outcome\` translating \`status_reason\` to plain words:
10241
+ \`not_in_universe\` \u2192 "not in the Leadbay universe (import it first)",
10242
+ \`low_confidence_identity\` \u2192 "couldn't safely match \u2014 check \`resolution.alternatives\`",
10243
+ \`no_matching_contact\` \u2192 "no contact with the requested title",
10244
+ \`disqualified\` \u2192 "evaluated: does not fit" (evidence is in the item when owned),
10245
+ \`enrichment_failed\` \u2192 "channel could not be sourced (not billed)".
10246
+
10247
+ **\`items_truncated\`**: rows are a PREFIX, not the batch. Say so, and offer
10248
+ \`leadbay_lead_job_status(job_id, since: next_since)\` for the rest.
10249
+
10250
+ **Hide from the user:** UUIDs (keep for tool calls, never render), cursors,
10251
+ \`explain.model\`/\`intelligence_snapshot\`, raw \`distance\`/\`calibration\`,
10252
+ \`seq\`/\`from_cache\`, empty arrays.
10253
+
10254
+ ## Linking a contact's name
10255
+
10256
+ **MANDATORY: every contact name in your output \u2014 table cells, prose, headers, "Reach <Name>" callouts \u2014 MUST be wrapped in markdown link syntax \`[Name](URL)\`. Never render a contact name as bare text. A plain-text name is a broken contact card; the underlined name is the user's primary affordance for "take me to this person's profile". No "no URL available" exception \u2014 the search URL below is always constructable from name + company.**
10257
+
10258
+ URL priority (first applicable wins):
10259
+
10260
+ 1. **Real profile** \u2014 \`contact.linkedin_page\` when it's a string starting with \`https://\` (the MCP coerces the legacy literal \`"null"\` string to real null before you see it).
10261
+ 2. **Constructed people-search** \u2014 \`https://www.linkedin.com/search/results/people/?keywords=<First>+<Last>+<Company>\`. URL-encode params. Strip Inc / LLC / Corp / Ltd / GmbH / Co / S.A. / S.L. / PLC / AG / SAS / SARL suffixes from the company. Append a trailing \` \xB0\` to the rendered name ONLY when this fallback is in use AND \`social_presence.linkedin == false\`. Never append \`\xB0\` when a real \`linkedin_page\` was used.
10262
+
10263
+ Never link a person's name to the company's LinkedIn page (and vice versa) \u2014 the two surfaces are different and conflating them quietly degrades the workflow.
10264
+
10265
+
10266
+
10267
+ ---
10268
+
10269
+ ## NEXT STEPS \u2014 after a find_new_leads delivery
10270
+
10271
+ **ALWAYS render NEXT STEPS via your host's next-step widget.** Use whichever is in your tool set \u2014 the NAME and SCHEMA differ: **\`ask_user_input_v0\`** (Claude chat / ChatGPT) takes plain-string options with \`type:"single_select"\`; **\`AskUserQuestion\`** (Claude cowork / Claude Code) takes object options \`{label, description}\` plus a required short \`header\` (\u226412 chars) and \`multiSelect\`, NO \`type\` field, and never add an "Other" option (the host adds it). Match the schema to the tool you actually have \u2014 the wrong schema fails silently and you fall back to prose. Prose bullets are the fallback ONLY when NEITHER widget exists. Any turn that would end with a choice must be the widget \u2014 the widget IS the question.
10272
+
10273
+ **If the tool result carries a \`next_steps\` object, that is the source of truth \u2014 use it directly.** Each option has a short \`.label\` (\u22645 words) and a full \`.description\`. Map \`next_steps.options[]\` into your host widget VERBATIM and in order: for \`AskUserQuestion\` (cowork / Claude Code) pass each as \`{label, description}\`; for \`ask_user_input_v0\` (Claude chat / ChatGPT, string options only) pass each option's \`.description\` as the string (it's the full sentence). Do NOT reword, reorder, drop, or prose-ify them \u2014 they're built deterministically by the server so the offer (incl. the artifact option at position 0) fires every time. Fall back to the table below only when there is NO \`next_steps\` field.
10274
+
10275
+ **One exception \u2014 skip the widget** when the user's original message contained a complete sequential instruction chain ("show me X and then do Y") AND all stated steps have been completed. In that case, end with STOP directly \u2014 the user stated their full plan and does not need a "what next?" prompt.
10276
+ - Skip example: "Show me today's leads and then research the top one for me." \u2192 after research completes, emit STOP without the widget.
10277
+ - Do NOT skip for: plain requests ("show me today's leads", "run my check-in"), recurring-language requests ("I do this every day"), or requests where only one action was stated.
10278
+
10279
+ Pick 2\u20134 rows from the (Observation, Suggest, Calls) table below most relevant to the response, then call your host's widget with ITS schema (per the schema rules above \u2014 wrong schema fails silently):
10280
+ - \`ask_user_input_v0\`: \`{questions:[{question,type:"single_select",options:["<Suggest 1>","<Suggest 2>"]}]}\`
10281
+ - \`AskUserQuestion\`: \`{questions:[{question,header:"Next step",multiSelect:false,options:[{label:"<\u22645 words>",description:"<Suggest 1>"}]}]}\`
10282
+
10283
+ User picks \u2192 call the matching \`Calls\` tool. Constraints: 2\u20134 mutually-exclusive options, AskUserQuestion labels \u22645 words (full text in \`description\`), max 3 questions. Table stays internal; never recite it.
10284
+
10285
+ ---
10286
+
10287
+
10288
+
10289
+ Pick the 2-3 options that match what actually happened \u2014 never all seven:
10290
+
10291
+ | Observation | Suggest | Calls |
10292
+ |---|---|---|
10293
+ | Job still running (\`still_running: true\`) | "Check on it in ~1 min" | leadbay_lead_job_status(job_id, wait_seconds: 60) |
10294
+ | Free run delivered on-profile leads | "Qualify these N against your criteria (paid \u2014 \`dry_run\` first)" | leadbay_qualify_leads(prior_deliveries: {job_id}) |
10295
+ | Delivered leads look right | "Draft outreach for the top ones" | leadbay_prepare_outreach |
10296
+ | Delivered 0 or off-profile | "Reshape the example and retry" (name the fix from funnel + scope_notes) | leadbay_find_new_leads (NEW request_id) |
10297
+ | Stopped at cost cap (\`stop_reason: max_cost\`) | "Raise the cap to X and get the remaining N" \u2014 X in the account's currency per the funnel-line rule, never a hard-coded \`$\` | leadbay_find_new_leads, NEW request_id (same-id only dedupes onto a LIVE job) + higher max_cost + \`count\` = the SHORTFALL (\`items_requested\` \u2212 delivered), not the original + \`exclude_lead_ids\` = the examined-but-REJECTED ids (novelty covers delivered; these are what it misses \u2014 without them the rerun re-buys the same losers) |
10298
+ | Stopped on org quota (\`stop_reason: quota\`) | "Check which window is exhausted and when it resets" \u2014 never a re-run: it cannot clear an org quota and burns a submit slot to stop in the same place | leadbay_account_status |
10299
+ | User wants these tracked in Leadbay | "Add the keepers to a campaign" | leadbay_create_campaign / leadbay_add_leads_to_campaign |
9022
10300
  `,
9023
10301
  leadbay_scan_portfolio_signals: `## WHEN TO USE
9024
10302
 
@@ -15640,12 +16918,12 @@ var CITY_ALIASES = {
15640
16918
  vegas: "Las Vegas",
15641
16919
  nola: "New Orleans"
15642
16920
  };
15643
- function expandAlias(text) {
15644
- const key = text.trim().toLowerCase();
15645
- return CITY_ALIASES[key] ?? text;
16921
+ function expandAlias(text2) {
16922
+ const key = text2.trim().toLowerCase();
16923
+ return CITY_ALIASES[key] ?? text2;
15646
16924
  }
15647
- function scoreMatch(text, match) {
15648
- const t = text.trim().toLowerCase();
16925
+ function scoreMatch(text2, match) {
16926
+ const t = text2.trim().toLowerCase();
15649
16927
  const n = match.name.trim().toLowerCase();
15650
16928
  if (n === t)
15651
16929
  return 1;
@@ -15668,8 +16946,8 @@ async function resolveLocations(client, texts) {
15668
16946
  const resolved = [...direct];
15669
16947
  const ambiguities = [];
15670
16948
  for (const originalText of free) {
15671
- const text = expandAlias(originalText);
15672
- const path = `/geo/search?q=${encodeURIComponent(text)}`;
16949
+ const text2 = expandAlias(originalText);
16950
+ const path = `/geo/search?q=${encodeURIComponent(text2)}`;
15673
16951
  let response;
15674
16952
  try {
15675
16953
  response = await client.request("GET", path);
@@ -15708,7 +16986,7 @@ async function resolveLocations(client, texts) {
15708
16986
  name: r.name,
15709
16987
  country: r.country,
15710
16988
  level: r.level,
15711
- score: scoreMatch(text, r)
16989
+ score: scoreMatch(text2, r)
15712
16990
  })).sort((a, b) => {
15713
16991
  if (b.score !== a.score)
15714
16992
  return b.score - a.score;
@@ -16874,9 +18152,9 @@ ${firm.short_description}`);
16874
18152
  out.push(`### ${sec.section_emoji ?? ""} ${label}`.trim());
16875
18153
  const entries = Array.isArray(sec.entries) ? sec.entries : [];
16876
18154
  for (const e of entries.slice(0, 5)) {
16877
- const text = e.text ?? e.summary ?? JSON.stringify(e).slice(0, 200);
18155
+ const text2 = e.text ?? e.summary ?? JSON.stringify(e).slice(0, 200);
16878
18156
  const hot = e.hot === true ? " \u{1F525}" : "";
16879
- out.push(`- ${text}${hot}`);
18157
+ out.push(`- ${text2}${hot}`);
16880
18158
  }
16881
18159
  if (entries.length > 5)
16882
18160
  out.push(`- _${entries.length - 5} more \u2026_`);
@@ -18803,6 +20081,11 @@ var accountStatus = {
18803
20081
  agent_memory: { type: "object" }
18804
20082
  }
18805
20083
  },
20084
+ // Set by the MCP server wrapper (NOT this composite) on every call.
20085
+ mcp_version: {
20086
+ type: "string",
20087
+ description: "Version of the Leadbay MCP server answering this call. Answer 'what version of Leadbay are you running' with this value."
20088
+ },
18806
20089
  // Auto-update block. Populated by the MCP server wrapper (NOT this
18807
20090
  // composite) when a newer release is published on GitHub AND the
18808
20091
  // user hasn't suppressed it. When present, the agent should prompt
@@ -21457,8 +22740,8 @@ function tokens(s) {
21457
22740
  return [];
21458
22741
  return s.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean);
21459
22742
  }
21460
- function bestMatches(text, taxonomy) {
21461
- const want = new Set(tokens(text));
22743
+ function bestMatches(text2, taxonomy) {
22744
+ const want = new Set(tokens(text2));
21462
22745
  if (want.size === 0)
21463
22746
  return [];
21464
22747
  const ranked = taxonomy.map((s) => {
@@ -21487,12 +22770,12 @@ async function resolveSectors(client, texts, ctx) {
21487
22770
  }
21488
22771
  const resolved = [...direct];
21489
22772
  const ambiguities = [];
21490
- for (const text of free) {
21491
- const matches = bestMatches(text, taxonomy);
22773
+ for (const text2 of free) {
22774
+ const matches = bestMatches(text2, taxonomy);
21492
22775
  if (matches.length === 1 || matches.length >= 2 && matches[0].score >= 0.66 && matches[0].score - matches[1].score >= 0.34) {
21493
22776
  resolved.push(matches[0].id);
21494
22777
  } else {
21495
- ambiguities.push({ sector_text: text, matches });
22778
+ ambiguities.push({ sector_text: text2, matches });
21496
22779
  }
21497
22780
  }
21498
22781
  return { resolved, ambiguities };
@@ -22157,48 +23440,1264 @@ var seedCandidates = {
22157
23440
  }
22158
23441
  };
22159
23442
 
22160
- // ../core/dist/composite/extend-lens.js
22161
- function httpStatus(err) {
22162
- return err?._meta?.http_status;
22163
- }
22164
- async function readExtraRefillQuota(client) {
22165
- try {
22166
- const me = await client.resolveMe();
22167
- const quota = await client.request("GET", `/organizations/${me.organization.id}/quota_status`);
22168
- const isRefill = (r) => r.resource_type?.toUpperCase() === "LENS_EXTRA_REFILL";
22169
- const entry = quota.org?.resources?.find(isRefill) ?? quota.user?.resources?.find(isRefill);
22170
- return {
22171
- count: entry?.count ?? null,
22172
- resets_at: entry?.resets_at ?? null
23443
+ // ../core/dist/composite/_mcp-job-helpers.js
23444
+ import { createHash as createHash4 } from "crypto";
23445
+ var TERMINAL_JOB_STATES = /* @__PURE__ */ new Set([
23446
+ "completed",
23447
+ "completed_partial",
23448
+ "failed",
23449
+ "expired"
23450
+ ]);
23451
+ var MCP_JOB_POLL = { intervalMs: 4e3 };
23452
+ var SNAPSHOT_TIMEOUT_MS = 3e4;
23453
+ var PAGE_LIMIT = 100;
23454
+ var MAX_JOB_ITEMS = 1e3;
23455
+ var MIN_PAGES = 20;
23456
+ var maxPagesFor = (pageLimit) => Math.max(MIN_PAGES, Math.ceil(MAX_JOB_ITEMS / pageLimit) + 1);
23457
+ var JOB_ID_CHARSET = /^[A-Za-z0-9._~-]+$/;
23458
+ var MAX_JOB_ID_LENGTH = 200;
23459
+ function assertSafeJobId(jobId) {
23460
+ const reject = (why) => {
23461
+ throw {
23462
+ error: true,
23463
+ code: "INVALID_JOB_ID",
23464
+ message: `job_id ${why}.`,
23465
+ hint: "Pass the job_id exactly as leadbay_find_new_leads or leadbay_qualify_leads returned it \u2014 it is an opaque handle, not a path."
22173
23466
  };
22174
- } catch {
22175
- return { count: null, resets_at: null };
23467
+ };
23468
+ if (typeof jobId !== "string" || jobId.length === 0)
23469
+ return reject("must be a non-empty string");
23470
+ if (jobId.length > MAX_JOB_ID_LENGTH)
23471
+ return reject(`is ${jobId.length} chars \u2014 the maximum is ${MAX_JOB_ID_LENGTH}`);
23472
+ if (/^\.+$/.test(jobId))
23473
+ return reject("cannot be a dot segment");
23474
+ if (!JOB_ID_CHARSET.test(jobId))
23475
+ return reject("contains characters that are not valid in a job handle");
23476
+ return encodeURIComponent(jobId);
23477
+ }
23478
+ async function collectJobSnapshot(client, jobId, since, limit, signal, timeoutMs = SNAPSHOT_TIMEOUT_MS) {
23479
+ if (signal?.aborted)
23480
+ throw cancelledError(jobId);
23481
+ const pageLimit = Math.min(Math.max(limit ?? PAGE_LIMIT, 1), PAGE_LIMIT);
23482
+ const safeJobId = assertSafeJobId(jobId);
23483
+ const qs = (cursor2) => `/mcp/jobs/${safeJobId}?limit=${pageLimit}` + (cursor2 ? `&since=${encodeURIComponent(cursor2)}` : "");
23484
+ const maxPages = maxPagesFor(pageLimit);
23485
+ const deadlineAt = Date.now() + timeoutMs;
23486
+ const remaining = () => deadlineAt - Date.now();
23487
+ let page = await client.request("GET", qs(since), void 0, {
23488
+ signal,
23489
+ // totalTimeoutMs, not timeoutMs: what is left of the wait must cover a 401
23490
+ // backoff and its retry too, or a blip buys the poll a second full budget.
23491
+ totalTimeoutMs: remaining()
23492
+ });
23493
+ const items = [...page.items];
23494
+ let cursor = page.next_since ?? since ?? null;
23495
+ let pages = 1;
23496
+ while (page.items.length >= pageLimit && page.next_since && pages < maxPages && !signal?.aborted) {
23497
+ if (remaining() <= 0)
23498
+ break;
23499
+ let next;
23500
+ try {
23501
+ next = await client.request("GET", qs(page.next_since), void 0, { signal, totalTimeoutMs: remaining() });
23502
+ } catch (e) {
23503
+ if (isTimeout(e))
23504
+ break;
23505
+ throw e;
23506
+ }
23507
+ items.push(...next.items);
23508
+ pages += 1;
23509
+ page = next;
23510
+ if (next.items.length === 0) {
23511
+ break;
23512
+ }
23513
+ cursor = next.next_since ?? cursor;
22176
23514
  }
23515
+ const itemsTruncated = page.items.length >= pageLimit && !!page.next_since;
23516
+ return {
23517
+ ...page,
23518
+ items,
23519
+ next_since: cursor,
23520
+ ...itemsTruncated ? { items_truncated: true } : {}
23521
+ };
22177
23522
  }
22178
- async function readAvailablePool(client, lensId) {
23523
+ function sleepUnlessAborted(ms, signal) {
23524
+ if (signal?.aborted)
23525
+ return Promise.resolve();
23526
+ return new Promise((resolve) => {
23527
+ const done = () => {
23528
+ clearTimeout(timer);
23529
+ signal?.removeEventListener("abort", done);
23530
+ resolve();
23531
+ };
23532
+ const timer = setTimeout(done, ms);
23533
+ signal?.addEventListener("abort", done, { once: true });
23534
+ });
23535
+ }
23536
+ function cancelledError(jobId) {
23537
+ return {
23538
+ error: true,
23539
+ code: "REQUEST_CANCELLED",
23540
+ message: `The wait for job ${jobId} was cancelled before any status was read.`,
23541
+ hint: "The job itself is backend-owned and keeps running. Poll leadbay_lead_job_status when you want its result."
23542
+ };
23543
+ }
23544
+ function snapshotBudget(remainingMs) {
23545
+ return Math.min(SNAPSHOT_TIMEOUT_MS, Math.max(remainingMs, 1));
23546
+ }
23547
+ function isTimeout(e) {
23548
+ return typeof e === "object" && e !== null && e.code === "TIMEOUT";
23549
+ }
23550
+ function jobReadTimedOutError(jobId, waitSeconds) {
23551
+ return {
23552
+ error: true,
23553
+ code: "JOB_READ_TIMEOUT",
23554
+ // Structured, not just interpolated: a caller recovering programmatically
23555
+ // should not have to parse the message to find the handle.
23556
+ job_id: jobId,
23557
+ message: `Job ${jobId} was submitted and is running, but its status could not be read within ${waitSeconds}s.`,
23558
+ hint: `Pass job_id ${jobId} to leadbay_lead_job_status to read it \u2014 the job is backend-owned, still running, and its results are kept for 30 days.`
23559
+ };
23560
+ }
23561
+ function jobHandleError(jobId, cause) {
23562
+ const c = cause;
23563
+ if (c?.job_id === jobId)
23564
+ return cause;
23565
+ return {
23566
+ error: true,
23567
+ code: c?.code ?? "JOB_READ_FAILED",
23568
+ job_id: jobId,
23569
+ message: `Job ${jobId} was submitted and is running, but reading its status failed: ${c?.message ?? String(cause)}`,
23570
+ hint: `Pass job_id ${jobId} to leadbay_lead_job_status to read it \u2014 the job is backend-owned, keeps running whatever happened to this call, and its results are kept for 30 days.`
23571
+ };
23572
+ }
23573
+ async function snapshotAfterSubmit(client, jobId, waitSeconds, ctx, itemsRequested) {
22179
23574
  try {
22180
- const preview = await client.request("GET", `/lenses/${lensId}/extra_refill_preview`);
22181
- return typeof preview?.available_count === "number" ? preview.available_count : null;
22182
- } catch {
22183
- return null;
23575
+ return waitSeconds > 0 ? await waitForJob(client, jobId, waitSeconds, ctx, itemsRequested) : await collectJobSnapshot(client, jobId, void 0, void 0, ctx?.signal);
23576
+ } catch (e) {
23577
+ throw jobHandleError(jobId, e);
22184
23578
  }
22185
23579
  }
22186
- async function readLensLeadTotal(client, lensId) {
23580
+ async function waitForJob(client, jobId, waitSeconds, ctx, itemsRequested, since, limit) {
23581
+ const startedAt = Date.now();
23582
+ const remainingMsOf = () => waitSeconds * 1e3 - (Date.now() - startedAt);
23583
+ if (ctx?.signal?.aborted)
23584
+ throw cancelledError(jobId);
23585
+ let snap;
22187
23586
  try {
22188
- const page = await client.request("GET", `/lenses/${lensId}/leads/wishlist?count=1&page=0`);
22189
- return typeof page?.pagination?.total === "number" ? page.pagination.total : null;
22190
- } catch {
22191
- return null;
23587
+ snap = await collectJobSnapshot(client, jobId, since, limit, ctx?.signal, snapshotBudget(remainingMsOf()));
23588
+ } catch (e) {
23589
+ if (isTimeout(e))
23590
+ throw jobReadTimedOutError(jobId, waitSeconds);
23591
+ throw e;
23592
+ }
23593
+ while (!TERMINAL_JOB_STATES.has(snap.job.state) && (Date.now() - startedAt) / 1e3 < waitSeconds && !ctx?.signal?.aborted) {
23594
+ const remainingMs = waitSeconds * 1e3 - (Date.now() - startedAt);
23595
+ if (remainingMs <= 0)
23596
+ break;
23597
+ await sleepUnlessAborted(Math.min(MCP_JOB_POLL.intervalMs, remainingMs), ctx?.signal);
23598
+ if (ctx?.signal?.aborted)
23599
+ break;
23600
+ if (remainingMsOf() <= 0)
23601
+ break;
23602
+ try {
23603
+ const fresh = await collectJobSnapshot(client, jobId, since, limit, ctx?.signal, snapshotBudget(remainingMsOf()));
23604
+ const regressed = fresh.items.length < snap.items.length;
23605
+ snap = regressed ? {
23606
+ ...fresh,
23607
+ items: snap.items,
23608
+ next_since: snap.next_since ?? fresh.next_since,
23609
+ ...snap.items_truncated ? { items_truncated: true } : {}
23610
+ } : fresh;
23611
+ } catch (e) {
23612
+ if (ctx?.signal?.aborted)
23613
+ break;
23614
+ if (isTimeout(e))
23615
+ break;
23616
+ throw e;
23617
+ }
23618
+ const f = snap.funnel;
23619
+ ctx?.progress?.({
23620
+ progress: f.delivered ?? 0,
23621
+ total: itemsRequested,
23622
+ message: `${snap.job.state}: ${f.examined ?? 0} examined, ${f.delivered ?? 0} delivered, ${snap.cost.spent}c spent`
23623
+ });
22192
23624
  }
23625
+ return snap;
22193
23626
  }
22194
- function noCandidatesReason(held, shape) {
22195
- const { geoSentence, ...extras } = shape;
22196
- const futile = " Extending again is futile \u2014 a refill on a lens with an empty candidate pool reports queued, consumes no quota and delivers nothing.";
22197
- if (held === 0) {
22198
- return {
22199
- code: "audience_too_narrow",
22200
- retryable: false,
22201
- message: "This lens holds no leads and has none left to add: its criteria intersect to nothing." + geoSentence + futile + " Tell the user which criteria are in play and offer to widen the audience (leadbay_adjust_audience).",
23627
+ function refIdentity(ref) {
23628
+ if (!ref || typeof ref !== "object" || Array.isArray(ref))
23629
+ return null;
23630
+ const o = ref;
23631
+ const str = (f) => {
23632
+ const v = o[f];
23633
+ if (typeof v !== "string")
23634
+ return null;
23635
+ const t = v.trim().toLowerCase();
23636
+ return t ? t : null;
23637
+ };
23638
+ const website = str("website");
23639
+ const parts = [
23640
+ normalizeUuid(o.lead_id) ?? null,
23641
+ normalizeUuid(o.contact_id) ?? null,
23642
+ website ? normalizeDomain(website) ?? website : null,
23643
+ str("name"),
23644
+ str("location")
23645
+ ];
23646
+ return parts.some((p) => p !== null) ? JSON.stringify(parts) : null;
23647
+ }
23648
+ function remapInputIndexes(items, refs) {
23649
+ const list = Array.isArray(refs) ? refs : [];
23650
+ if (list.length === 0)
23651
+ return { items, remapped: false };
23652
+ const byIdentity = /* @__PURE__ */ new Map();
23653
+ list.forEach((ref, i) => {
23654
+ const key = refIdentity(ref);
23655
+ if (!key)
23656
+ return;
23657
+ const at = byIdentity.get(key);
23658
+ if (at)
23659
+ at.push(i);
23660
+ else
23661
+ byIdentity.set(key, [i]);
23662
+ });
23663
+ const next = [];
23664
+ let ok = true;
23665
+ for (const item of items) {
23666
+ const ref = item.ref;
23667
+ if (!ref || ref.input_indexes == null) {
23668
+ next.push(item);
23669
+ continue;
23670
+ }
23671
+ const key = refIdentity(ref.requested_as) ?? refIdentity({ lead_id: ref.lead_id ?? void 0 });
23672
+ const found = key ? byIdentity.get(key) : void 0;
23673
+ if (!found) {
23674
+ ok = false;
23675
+ break;
23676
+ }
23677
+ next.push({ ...item, ref: { ...ref, input_indexes: found } });
23678
+ }
23679
+ if (!ok) {
23680
+ return {
23681
+ items: items.map((item) => item.ref && item.ref.input_indexes != null ? { ...item, ref: { ...item.ref, input_indexes: null } } : item),
23682
+ remapped: false
23683
+ };
23684
+ }
23685
+ return { items: next, remapped: true };
23686
+ }
23687
+ function canonicalSet(values) {
23688
+ const list = values === void 0 || values === null ? [] : Array.isArray(values) ? values : [values];
23689
+ return [...new Set(list.map((v) => JSON.stringify(v)))].sort().map((v) => JSON.parse(v));
23690
+ }
23691
+ function coerceArrayParams(params, keys) {
23692
+ const out = { ...params };
23693
+ for (const key of keys) {
23694
+ const v = out[key];
23695
+ if (v !== void 0 && v !== null && !Array.isArray(v)) {
23696
+ out[key] = [v];
23697
+ }
23698
+ }
23699
+ return out;
23700
+ }
23701
+ var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
23702
+ function presentRequestId(value) {
23703
+ if (typeof value !== "string")
23704
+ return void 0;
23705
+ const trimmed = value.trim();
23706
+ return trimmed ? trimmed : void 0;
23707
+ }
23708
+ function isUuidShaped(value) {
23709
+ return typeof value === "string" && UUID_RE2.test(value.trim());
23710
+ }
23711
+ function normalizeUuid(value) {
23712
+ if (typeof value !== "string")
23713
+ return null;
23714
+ const v = value.trim();
23715
+ if (!v)
23716
+ return null;
23717
+ return UUID_RE2.test(v) ? v.toLowerCase() : v;
23718
+ }
23719
+ function canonicalIdSet(values) {
23720
+ const list = values === void 0 || values === null ? [] : Array.isArray(values) ? values : [values];
23721
+ return canonicalSet(list.map(normalizeUuid).filter((v) => !!v));
23722
+ }
23723
+ function canonicalLabelSet(values) {
23724
+ const list = values === void 0 || values === null ? [] : Array.isArray(values) ? values : [values];
23725
+ return canonicalSet(list.filter((v) => typeof v === "string").map((v) => v.trim().toLowerCase()).filter(Boolean));
23726
+ }
23727
+ function canonicalOptionalObject(value) {
23728
+ if (!value)
23729
+ return null;
23730
+ const out = {};
23731
+ for (const [k, v] of Object.entries(value)) {
23732
+ if (v === void 0 || v === null)
23733
+ continue;
23734
+ if (Array.isArray(v) && v.length === 0)
23735
+ continue;
23736
+ out[k] = v;
23737
+ }
23738
+ return Object.keys(out).length === 0 ? null : out;
23739
+ }
23740
+ function canonicalize(value) {
23741
+ if (Array.isArray(value))
23742
+ return value.map(canonicalize);
23743
+ if (value && typeof value === "object") {
23744
+ const out = {};
23745
+ for (const k of Object.keys(value).sort()) {
23746
+ out[k] = canonicalize(value[k]);
23747
+ }
23748
+ return out;
23749
+ }
23750
+ return value;
23751
+ }
23752
+ function derivedKey(prefix, shape) {
23753
+ const serialized = typeof shape === "string" ? shape : JSON.stringify(canonicalize(shape));
23754
+ return `${prefix}-${createHash4("sha256").update(serialized).digest("hex").slice(0, 32)}`;
23755
+ }
23756
+ function mockedSubmitPreview(submit, tool, region) {
23757
+ const s = submit ?? {};
23758
+ if (typeof s.job_id === "string" && s.job_id)
23759
+ return null;
23760
+ if (process.env.LEADBAY_MOCK !== "1") {
23761
+ throw {
23762
+ error: true,
23763
+ code: "MALFORMED_SUBMIT_RESPONSE",
23764
+ message: `${tool}: the submit succeeded but the response carried no job_id, so the job cannot be polled.`,
23765
+ hint: "The job may still be running server-side. Do not re-submit blindly \u2014 reuse the same request_id so a retry dedupes instead of double-spending."
23766
+ };
23767
+ }
23768
+ return {
23769
+ mocked: true,
23770
+ tool,
23771
+ submitted: false,
23772
+ would_call: s.would_call ?? null,
23773
+ note: "LEADBAY_MOCK=1 \u2014 the job was not submitted, so there is no job to poll.",
23774
+ region
23775
+ };
23776
+ }
23777
+ function splitItems(snapshot) {
23778
+ const leads = [];
23779
+ const skipped = [];
23780
+ for (const item of snapshot.items) {
23781
+ if (item.status === "skipped")
23782
+ skipped.push(item);
23783
+ else
23784
+ leads.push(item);
23785
+ }
23786
+ return { leads, skipped };
23787
+ }
23788
+ function compactBody(body) {
23789
+ return Object.fromEntries(Object.entries(body).filter(([, v]) => v !== void 0));
23790
+ }
23791
+ var COUNTRY_ALIASES = [
23792
+ "united states",
23793
+ "united states of america",
23794
+ "usa",
23795
+ "us",
23796
+ "america",
23797
+ "etats unis",
23798
+ "etats unis d amerique",
23799
+ "france",
23800
+ "fr",
23801
+ "french republic",
23802
+ "republique francaise"
23803
+ ];
23804
+ var SUBNATIONAL_EXEMPTIONS = {
23805
+ us: new Set(["georgia", "georgie"].map(countryKey2)),
23806
+ fr: new Set([
23807
+ "guadeloupe",
23808
+ "martinique",
23809
+ "reunion",
23810
+ "mayotte",
23811
+ "french guiana",
23812
+ "guyane francaise",
23813
+ "new caledonia",
23814
+ "nouvelle caledonie",
23815
+ "french polynesia",
23816
+ "polynesie francaise",
23817
+ "saint martin",
23818
+ "saint barthelemy",
23819
+ "saint pierre and miquelon",
23820
+ "saint pierre et miquelon",
23821
+ "wallis and futuna",
23822
+ "wallis et futuna"
23823
+ ].map(countryKey2))
23824
+ };
23825
+ var ALL_EXEMPTIONS = new Set(Object.values(SUBNATIONAL_EXEMPTIONS).flatMap((s) => [...s]));
23826
+ function exemptionsFor(region) {
23827
+ const key = typeof region === "string" ? region.trim().toLowerCase() : "";
23828
+ return SUBNATIONAL_EXEMPTIONS[key] ?? ALL_EXEMPTIONS;
23829
+ }
23830
+ function buildCountryLocationValues() {
23831
+ const values = new Set(COUNTRY_ALIASES.map(countryKey2));
23832
+ try {
23833
+ const A = "A".charCodeAt(0);
23834
+ const displays = ["en", "fr"].map((locale) => new Intl.DisplayNames([locale], { type: "region", fallback: "none" }));
23835
+ for (let i = 0; i < 26; i++) {
23836
+ for (let j = 0; j < 26; j++) {
23837
+ const code = String.fromCharCode(A + i) + String.fromCharCode(A + j);
23838
+ for (const display of displays) {
23839
+ const name = display.of(code);
23840
+ if (!name || name === code)
23841
+ continue;
23842
+ values.add(countryKey2(name));
23843
+ }
23844
+ }
23845
+ }
23846
+ } catch {
23847
+ }
23848
+ return values;
23849
+ }
23850
+ var COUNTRY_LOCATION_VALUES = buildCountryLocationValues();
23851
+ function countryKey2(raw) {
23852
+ return raw.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[-_,]/g, " ").replace(/^\s*(l|d)['’]\s*/, "").replace(/['’.]/g, "").replace(/\s+/g, " ").trim().replace(/^(les|the|la|le|l)\s+/, "").trim();
23853
+ }
23854
+ var MAX_EXCLUDE_LEAD_IDS = 500;
23855
+ function rejectMalformedExclusions(ids) {
23856
+ if (ids === void 0 || ids === null)
23857
+ return;
23858
+ const list = Array.isArray(ids) ? ids : [ids];
23859
+ const bad = [];
23860
+ list.forEach((v, i) => {
23861
+ if (typeof v !== "string") {
23862
+ bad.push(`${i} (${v === null ? "null" : typeof v})`);
23863
+ } else if (!v.trim()) {
23864
+ bad.push(`${i} (blank)`);
23865
+ }
23866
+ });
23867
+ if (bad.length === 0)
23868
+ return;
23869
+ throw {
23870
+ error: true,
23871
+ code: "INVALID_EXCLUDE_LEAD_ID",
23872
+ message: `exclude_lead_ids has ${bad.length} entr${bad.length === 1 ? "y" : "ies"} that is not a lead id: ${bad.join(", ")}.`,
23873
+ hint: "Drop or fix those entries and re-call \u2014 every entry must be a non-blank lead id string. Silently skipping them would run the search without an exclusion you asked for, and could re-deliver and charge for that exact lead."
23874
+ };
23875
+ }
23876
+ function rejectOversizedExclusions(ids) {
23877
+ if (ids === void 0 || ids === null)
23878
+ return;
23879
+ const unique = canonicalIdSet(ids);
23880
+ if (unique.length <= MAX_EXCLUDE_LEAD_IDS)
23881
+ return;
23882
+ throw {
23883
+ error: true,
23884
+ code: "TOO_MANY_EXCLUSIONS",
23885
+ message: `exclude_lead_ids carries ${unique.length} ids \u2014 the maximum is ${MAX_EXCLUDE_LEAD_IDS}.`,
23886
+ hint: "Drop the DELIVERED ids first: novelty:'org' already excludes those. Send the examined-but-rejected ones (disqualified + skipped), most recent first, capped at 500."
23887
+ };
23888
+ }
23889
+ var MAX_LEAD_REFS = 500;
23890
+ function rejectOversizedLeadRefs(refs) {
23891
+ if (refs === void 0 || refs === null)
23892
+ return;
23893
+ const list = Array.isArray(refs) ? refs : [refs];
23894
+ const unique = /* @__PURE__ */ new Set();
23895
+ let unkeyed = 0;
23896
+ for (const ref of list) {
23897
+ const key = refIdentity(ref);
23898
+ if (key === null)
23899
+ unkeyed += 1;
23900
+ else
23901
+ unique.add(key);
23902
+ }
23903
+ const count = unique.size + unkeyed;
23904
+ if (count <= MAX_LEAD_REFS)
23905
+ return;
23906
+ throw {
23907
+ error: true,
23908
+ code: "TOO_MANY_LEAD_REFS",
23909
+ message: `lead_refs carries ${count} companies \u2014 the maximum is ${MAX_LEAD_REFS}.`,
23910
+ hint: `Split the batch into runs of ${MAX_LEAD_REFS} or fewer and call leadbay_qualify_leads once per run, each with its OWN request_id. Results accumulate in the org ledger, so a later run can re-read the earlier ones via prior_deliveries.`
23911
+ };
23912
+ }
23913
+ function readSpendFlag(value, field) {
23914
+ if (value === void 0 || value === null)
23915
+ return void 0;
23916
+ if (typeof value === "boolean")
23917
+ return value;
23918
+ if (typeof value === "string") {
23919
+ const t = value.trim().toLowerCase();
23920
+ if (t === "true")
23921
+ return true;
23922
+ if (t === "false")
23923
+ return false;
23924
+ }
23925
+ throw {
23926
+ error: true,
23927
+ code: "BAD_INPUT",
23928
+ message: `${field} must be a boolean (got ${Array.isArray(value) ? "array" : typeof value}: ${JSON.stringify(value)}).`,
23929
+ hint: `Re-call the tool with ${field}: true or ${field}: false as a JSON boolean, not a string or a number. This flag decides whether the user is charged, so an unrecognised value is refused rather than guessed.`
23930
+ };
23931
+ }
23932
+ function rejectCountryLocations(locations, region) {
23933
+ if (locations === void 0 || locations === null)
23934
+ return;
23935
+ const exempt = exemptionsFor(region);
23936
+ const list = Array.isArray(locations) ? locations : [locations];
23937
+ for (const loc of list) {
23938
+ if (typeof loc !== "string")
23939
+ continue;
23940
+ const key = countryKey2(loc);
23941
+ if (!exempt.has(key) && COUNTRY_LOCATION_VALUES.has(key)) {
23942
+ throw {
23943
+ error: true,
23944
+ code: "COUNTRY_LEVEL_LOCATION",
23945
+ message: `filters.locations value "${loc}" is country-level \u2014 it would silently fence the search to a same-named town, not the whole country.`,
23946
+ hint: 'Whole-country intent = OMIT filters.locations entirely (each universe is single-country). Use city/state/region names for narrower fences. If you meant a town that shares the name, qualify it with its state or region (e.g. "Lebanon, Kentucky").'
23947
+ };
23948
+ }
23949
+ }
23950
+ }
23951
+ function normalizeSearchFilters(filters) {
23952
+ if (filters == null)
23953
+ return void 0;
23954
+ const { employees, employeesMin, employeesMax, ...rest } = filters;
23955
+ const out = { ...rest };
23956
+ if (out.employees_min == null) {
23957
+ out.employees_min = employees?.min ?? employees?.employees_min ?? employeesMin;
23958
+ }
23959
+ if (out.employees_max == null) {
23960
+ out.employees_max = employees?.max ?? employees?.employees_max ?? employeesMax;
23961
+ }
23962
+ if (out.employees_min == null)
23963
+ delete out.employees_min;
23964
+ if (out.employees_max == null)
23965
+ delete out.employees_max;
23966
+ for (const key of ["sectors", "locations"]) {
23967
+ const v = out[key];
23968
+ if (typeof v === "string")
23969
+ out[key] = v.trim() ? [v] : void 0;
23970
+ if (out[key] === void 0)
23971
+ delete out[key];
23972
+ }
23973
+ return out;
23974
+ }
23975
+ function clampWaitSeconds(requested, fallback) {
23976
+ if (requested == null || Number.isNaN(requested))
23977
+ return fallback;
23978
+ return Math.min(Math.max(requested, 0), 180);
23979
+ }
23980
+
23981
+ // ../core/dist/composite/find-new-leads.js
23982
+ var DEFAULT_WAIT_SECONDS = 45;
23983
+ function sortFilterLists(filters) {
23984
+ if (!filters)
23985
+ return null;
23986
+ const out = { ...filters };
23987
+ for (const key of ["sectors", "locations"]) {
23988
+ if (Array.isArray(out[key])) {
23989
+ out[key] = canonicalLabelSet(out[key]);
23990
+ }
23991
+ }
23992
+ return out;
23993
+ }
23994
+ var findNewLeads = {
23995
+ name: "leadbay_find_new_leads",
23996
+ annotations: {
23997
+ title: "Find new leads (net-new ICP search)",
23998
+ readOnlyHint: false,
23999
+ // The tool CAN bill (qualify:true and/or channels) and records deliveries
24000
+ // in the org novelty ledger, so it advertises destructive like the other
24001
+ // paid composites — annotations are static and must describe the worst
24002
+ // case, not the default. The free path is protected in execute() instead:
24003
+ // a paid call is withheld until `confirm: true`.
24004
+ destructiveHint: true,
24005
+ // The mandatory request_id dedups: re-submitting the same request returns
24006
+ // the SAME live job instead of double-spending.
24007
+ idempotentHint: true,
24008
+ openWorldHint: true
24009
+ },
24010
+ write: true,
24011
+ description: leadbay_find_new_leads,
24012
+ inputSchema: {
24013
+ type: "object",
24014
+ properties: {
24015
+ query: {
24016
+ type: "string",
24017
+ description: "Natural-language ICP ask. Matches topic VOCABULARY \u2014 can surface vendors of a product as easily as buyers of it. Prefer example_lead; use query only when the user's wording carries signal an example can't."
24018
+ },
24019
+ example_lead: {
24020
+ type: "object",
24021
+ description: "A FICTIONAL typical ideal customer used as a look-alike seed \u2014 the highest-leverage input. Put everything in `description` (registry 'About Us' style, what the company IS); leave `name` unset (a distinctive invented name pulls matches toward name-lookalikes).",
24022
+ properties: {
24023
+ name: { type: "string" },
24024
+ description: { type: "string" },
24025
+ location: { type: "string" },
24026
+ employees: { type: "number" }
24027
+ },
24028
+ additionalProperties: false
24029
+ },
24030
+ filters: {
24031
+ type: "object",
24032
+ description: "HARD constraints (the seed only shapes ranking). Sector/location labels resolve at submit; an unresolvable value is a 400 naming it.",
24033
+ properties: {
24034
+ sectors: { type: "array", items: { type: "string" } },
24035
+ locations: { type: "array", items: { type: "string" } },
24036
+ employees_min: { type: "number" },
24037
+ employees_max: { type: "number" }
24038
+ },
24039
+ additionalProperties: false
24040
+ },
24041
+ count: {
24042
+ type: "number",
24043
+ description: "Target DELIVERED leads, 1-50. With qualify:true this means n SURVIVORS of qualification, not n candidates examined."
24044
+ },
24045
+ qualify: {
24046
+ type: "boolean",
24047
+ description: "Run fresh AI qualification and drop candidates scoring below min_ai_score. PAID: ~94 cost_cents per candidate EXAMINED (survivor or not). Default false (free)."
24048
+ },
24049
+ min_ai_score: {
24050
+ type: "number",
24051
+ description: "Disqualification floor on the [-30,+30] qualification DELTA (not the 0-100 fit score). Default 0. Lower to -30 to keep every evaluated lead with its evidence."
24052
+ },
24053
+ contact_titles: {
24054
+ type: "array",
24055
+ items: { type: "string" },
24056
+ description: "Wanted decision-maker titles (max 10), matched semantically cross-language."
24057
+ },
24058
+ title_gate: {
24059
+ type: "string",
24060
+ enum: ["strict", "prefer"],
24061
+ description: "strict = only leads with a matching known contact; prefer (default when contact_titles set) = matched first, rest flagged."
24062
+ },
24063
+ channels: {
24064
+ type: "array",
24065
+ items: { type: "string", enum: ["email", "phone"] },
24066
+ description: "Contact channels to PURCHASE (email 25c, phone 250c, billed on success only). Empty = free identity tier."
24067
+ },
24068
+ exclude_lead_ids: {
24069
+ type: "array",
24070
+ items: { type: "string" },
24071
+ description: "Caller-side novelty belt on top of the server-side one (max 500 ids \u2014 over that the call is refused, so drop the DELIVERED ids first: novelty:'org' already covers those, and the examined-but-rejected ones are what it misses)."
24072
+ },
24073
+ novelty: {
24074
+ type: "string",
24075
+ enum: ["org", "none"],
24076
+ description: "org (default) = only companies NEW to the org (excludes org leads, lens members, CRM ids, prior MCP deliveries)."
24077
+ },
24078
+ max_cost: {
24079
+ type: "number",
24080
+ description: "Spend cap for the whole job in cost_cents. Defaults by plan tier (500/2000/5000). The job stops honestly at the cap (stop_reason max_cost)."
24081
+ },
24082
+ exploration_cap: {
24083
+ type: "number",
24084
+ description: "Max candidates the qualify gate may examine. Default min(3n,150), ceiling min(20n,1000)."
24085
+ },
24086
+ request_id: {
24087
+ type: "string",
24088
+ description: "REQUIRED idempotency key. Derive it from the ask (e.g. 'gyms-texas-2026-07-28'); REUSE the exact same value when retrying the same ask \u2014 a duplicate returns the SAME job instead of double-spending. Use a NEW value only for a genuinely new ask."
24089
+ },
24090
+ lang: { type: "string", description: "Output language (default: user's language)." },
24091
+ confirm: {
24092
+ type: "boolean",
24093
+ description: "Explicit spend decision, required only for a PAID search (qualify:true and/or channels). true = the user approved the quote, go ahead. false = a veto (returns mode:'needs_confirmation', spends nothing). Omitted on a paid call \u2192 the tool withholds the submit and returns a free quote to show the user first. The default FREE search (no qualify, no channels) needs no confirm."
24094
+ },
24095
+ dry_run: {
24096
+ type: "boolean",
24097
+ description: "Validate + worst-case cost estimate + quota forecast. No job, no spend. Use before the first PAID run of a session."
24098
+ },
24099
+ wait_seconds: {
24100
+ type: "number",
24101
+ description: "How long to poll before returning (default 45, max 180, 0 = submit + one snapshot). Free searches usually finish inside the window; paid exploration can take minutes \u2014 the result then carries still_running:true and the job_id to check with leadbay_lead_job_status."
24102
+ }
24103
+ },
24104
+ required: ["count", "request_id"],
24105
+ additionalProperties: false
24106
+ },
24107
+ execute: async (client, params, ctx) => {
24108
+ params = coerceArrayParams(params, [
24109
+ "contact_titles",
24110
+ "channels",
24111
+ "exclude_lead_ids"
24112
+ ]);
24113
+ rejectCountryLocations(params.filters?.locations, client.region);
24114
+ rejectMalformedExclusions(params.exclude_lead_ids);
24115
+ rejectOversizedExclusions(params.exclude_lead_ids);
24116
+ const qualify = readSpendFlag(params.qualify, "qualify");
24117
+ const dryRun = readSpendFlag(params.dry_run, "dry_run");
24118
+ const confirm = readSpendFlag(params.confirm, "confirm");
24119
+ params = { ...params, qualify, dry_run: dryRun, confirm };
24120
+ const buysChannels = (params.channels?.length ?? 0) > 0;
24121
+ const buysQualification = qualify === true;
24122
+ const isPaid = buysQualification || buysChannels;
24123
+ const vetoed = confirm === false;
24124
+ const consented = !vetoed && confirm === true;
24125
+ const requestId = presentRequestId(params.request_id) ?? derivedKey(
24126
+ "search-auto",
24127
+ // Passed as an OBJECT: derivedKey canonicalizes recursively, so nested
24128
+ // property order (example_lead, filters) can never fork the key. Fields
24129
+ // with a documented backend default are canonicalized TO that default,
24130
+ // so an approval that omits one and a retry that passes it explicitly
24131
+ // derive the same key rather than launching a second paid,
24132
+ // novelty-claiming job.
24133
+ {
24134
+ query: params.query ?? null,
24135
+ example_lead: params.example_lead ?? null,
24136
+ // Sector/location lists are unordered sets to the backend — sort
24137
+ // them so a reordered retry still dedupes.
24138
+ filters: canonicalOptionalObject(sortFilterLists(normalizeSearchFilters(params.filters))),
24139
+ count: params.count ?? null,
24140
+ qualify: params.qualify === true,
24141
+ min_ai_score: params.min_ai_score ?? 0,
24142
+ contact_titles: canonicalLabelSet(params.contact_titles),
24143
+ title_gate: params.title_gate ?? ((params.contact_titles?.length ?? 0) > 0 ? "prefer" : null),
24144
+ channels: canonicalSet(params.channels),
24145
+ // Sorted so ordering alone never forks the key, but PRESENT — a
24146
+ // top-up differing only by exclude_lead_ids is a different approved
24147
+ // search, and hashing it the same would return the first job as a
24148
+ // duplicate with the exclusions never applied.
24149
+ exclude_lead_ids: canonicalIdSet(params.exclude_lead_ids),
24150
+ novelty: params.novelty ?? "org",
24151
+ max_cost: params.max_cost ?? null,
24152
+ // Documented backend default is min(3n,150), so an omitted cap is
24153
+ // canonicalized TO it — same principle as min_ai_score/novelty above.
24154
+ // Otherwise an approval that omits the cap and a retry that passes the
24155
+ // materialized default ask for identical work under different keys,
24156
+ // and the retry escapes dedupe into a second paid, novelty-claiming
24157
+ // job. An explicit non-default cap still hashes distinctly.
24158
+ exploration_cap: params.exploration_cap ?? (typeof params.count === "number" && params.count > 0 ? Math.min(3 * params.count, 150) : null),
24159
+ lang: params.lang ?? null
24160
+ }
24161
+ );
24162
+ const body = compactBody({
24163
+ query: params.query,
24164
+ example_lead: params.example_lead,
24165
+ filters: normalizeSearchFilters(params.filters),
24166
+ count: params.count,
24167
+ qualify,
24168
+ min_ai_score: params.min_ai_score,
24169
+ contact_titles: params.contact_titles,
24170
+ title_gate: params.title_gate,
24171
+ channels: params.channels,
24172
+ // Wire the SAME list the cap guard counted and the idempotency key was
24173
+ // derived from. Posting the raw array instead let a 600-entry list that
24174
+ // dedupes to 400 clear the guard and still be refused by the backend.
24175
+ // Kept undefined when absent so compactBody drops it rather than
24176
+ // sending an empty array.
24177
+ exclude_lead_ids: params.exclude_lead_ids ? canonicalIdSet(params.exclude_lead_ids) : void 0,
24178
+ novelty: params.novelty,
24179
+ max_cost: params.max_cost,
24180
+ exploration_cap: params.exploration_cap,
24181
+ request_id: requestId,
24182
+ lang: params.lang,
24183
+ dry_run: dryRun
24184
+ });
24185
+ if (dryRun === true) {
24186
+ const forecast = await client.request("POST", "/mcp/search", body);
24187
+ return {
24188
+ dry_run: true,
24189
+ ...forecast,
24190
+ region: client.region
24191
+ };
24192
+ }
24193
+ if (isPaid && !consented) {
24194
+ const forecast = vetoed ? null : await client.request("POST", "/mcp/search", {
24195
+ ...body,
24196
+ dry_run: true
24197
+ });
24198
+ return {
24199
+ mode: "needs_confirmation",
24200
+ submitted: false,
24201
+ vetoed,
24202
+ paid_because: [
24203
+ buysQualification ? "qualify: true (~94 cost_cents per candidate EXAMINED)" : null,
24204
+ buysChannels ? `channels requested: ${params.channels.join(", ")}` : null
24205
+ ].filter(Boolean),
24206
+ quote: forecast,
24207
+ estimated_cost: forecast?.estimated_cost ?? null,
24208
+ items_requested: forecast?.items_requested ?? null,
24209
+ hint: vetoed ? "confirm:false vetoed the spend \u2014 nothing was submitted. Re-call with confirm:true to proceed, or drop qualify/channels for a free search." : "Show the user this worst-case quote and get an explicit go-ahead, then re-call with confirm:true. For a free search instead: omit qualify and channels.",
24210
+ region: client.region
24211
+ };
24212
+ }
24213
+ const submit = await client.request("POST", "/mcp/search", body, { preSendSignal: ctx?.signal });
24214
+ const mocked = mockedSubmitPreview(submit, "leadbay_find_new_leads", client.region);
24215
+ if (mocked)
24216
+ return mocked;
24217
+ const waitSeconds = clampWaitSeconds(params.wait_seconds, DEFAULT_WAIT_SECONDS);
24218
+ const snapshot = await snapshotAfterSubmit(client, submit.job_id, waitSeconds, ctx, params.count);
24219
+ const done = TERMINAL_JOB_STATES.has(snapshot.job.state);
24220
+ const { leads, skipped } = splitItems(snapshot);
24221
+ return {
24222
+ job_id: submit.job_id,
24223
+ request_id: requestId,
24224
+ duplicate_submit: submit.duplicate ?? false,
24225
+ state: snapshot.job.state,
24226
+ done,
24227
+ summary: {
24228
+ // Named items_requested (not `requested`) to match qualify_leads and
24229
+ // the shared renderer, which reads summary.items_requested for the
24230
+ // "delivered X of the Y asked" clause.
24231
+ items_requested: submit.items_requested ?? params.count,
24232
+ delivered: snapshot.funnel.delivered ?? 0,
24233
+ delivered_callable: snapshot.funnel.delivered_callable ?? 0,
24234
+ delivered_title_only: snapshot.funnel.delivered_title_only ?? 0,
24235
+ degraded: snapshot.funnel.degraded ?? 0,
24236
+ stop_reason: snapshot.funnel.stop_reason ?? null
24237
+ },
24238
+ funnel: snapshot.funnel,
24239
+ leads,
24240
+ skipped,
24241
+ items_truncated: snapshot.items_truncated ?? false,
24242
+ // Top-level, not only inside next_poll: on a TERMINAL job that truncated,
24243
+ // next_poll used to be null, so the rendering rule telling the agent to
24244
+ // fetch the rest with `since: next_since` named a cursor the response did
24245
+ // not contain. The rows are paid for; the way to reach them cannot be
24246
+ // conditional on the job still running.
24247
+ next_since: snapshot.next_since ?? null,
24248
+ cost: snapshot.cost,
24249
+ estimated_cost: submit.estimated_cost,
24250
+ explain: snapshot.explain,
24251
+ still_running: !done,
24252
+ // A finished job can still owe rows: truncation means the drain stopped
24253
+ // early, so there is a follow-up action even when done is true. It is a
24254
+ // page fetch, not a wait, hence suggested_wait_seconds 0.
24255
+ next_poll: done && !(snapshot.items_truncated ?? false) ? null : {
24256
+ tool: "leadbay_lead_job_status",
24257
+ job_id: submit.job_id,
24258
+ // Hand the cursor forward so the follow-up poll continues
24259
+ // INCREMENTALLY instead of re-reading (and re-rendering) the
24260
+ // rows already delivered in this response.
24261
+ since: snapshot.next_since ?? null,
24262
+ suggested_wait_seconds: done ? 0 : 60
24263
+ },
24264
+ region: client.region
24265
+ };
24266
+ }
24267
+ };
24268
+
24269
+ // ../core/dist/composite/qualify-leads.js
24270
+ var DEFAULT_WAIT_SECONDS2 = 45;
24271
+ function normalizeLeadRefs(refs) {
24272
+ if (!Array.isArray(refs))
24273
+ return refs;
24274
+ return refs.map((ref) => {
24275
+ if (typeof ref !== "string")
24276
+ return ref;
24277
+ const value = ref.trim();
24278
+ if (!value)
24279
+ return ref;
24280
+ if (isUuidShaped(value))
24281
+ return { lead_id: value };
24282
+ return normalizeDomain(value) ? { website: value } : { name: value };
24283
+ });
24284
+ }
24285
+ var LEAD_REF_FIELDS = [
24286
+ "lead_id",
24287
+ "website",
24288
+ "name",
24289
+ "location",
24290
+ "contact_id"
24291
+ ];
24292
+ function rejectMalformedLeadRefs(refs) {
24293
+ if (!Array.isArray(refs))
24294
+ return;
24295
+ const bad = [];
24296
+ refs.forEach((ref, i) => {
24297
+ if (ref === null || typeof ref !== "object" || Array.isArray(ref)) {
24298
+ bad.push(`${i} (not an object)`);
24299
+ return;
24300
+ }
24301
+ for (const field of LEAD_REF_FIELDS) {
24302
+ const value = ref[field];
24303
+ if (value !== void 0 && typeof value !== "string") {
24304
+ bad.push(`${i}.${field} (${value === null ? "null" : typeof value})`);
24305
+ }
24306
+ }
24307
+ });
24308
+ if (bad.length === 0)
24309
+ return;
24310
+ throw {
24311
+ error: true,
24312
+ code: "INVALID_LEAD_REF",
24313
+ message: `lead_refs has ${bad.length} invalid entr${bad.length === 1 ? "y" : "ies"}: ${bad.join(", ")}.`,
24314
+ hint: "Each ref is an object whose fields are STRINGS \u2014 {lead_id} | {website} | {name, location?} | {contact_id}. A bare string is accepted and reshaped; null, numbers, arrays and non-string field values are not. Fix or drop those entries and re-call."
24315
+ };
24316
+ }
24317
+ function text(value) {
24318
+ if (typeof value !== "string")
24319
+ return null;
24320
+ const v = value.trim().toLowerCase();
24321
+ return v ? v : null;
24322
+ }
24323
+ function derivedRequestId(params) {
24324
+ const refs = canonicalSet((params.lead_refs ?? []).map((r) => {
24325
+ const website = text(r.website);
24326
+ return [
24327
+ // UUIDs are case-insensitive to the backend, so an uppercase id and
24328
+ // its lowercase form are the same lead and must share a key.
24329
+ normalizeUuid(r.lead_id),
24330
+ normalizeUuid(r.contact_id),
24331
+ // Normalize the website the SAME way the resolver does, so a pasted
24332
+ // "https://Acme.com/" and a retry's "acme.com" resolve to one company
24333
+ // AND to one key. Fall back to the trimmed/lowercased raw value when
24334
+ // it is not domain-shaped, rather than dropping the field.
24335
+ website ? normalizeDomain(website) ?? website : null,
24336
+ text(r.name),
24337
+ text(r.location)
24338
+ ];
24339
+ }));
24340
+ const shape = {
24341
+ refs,
24342
+ // The WHOLE selector, not just the job id: qualifying the first 50 of a
24343
+ // delivery job and then the next 50 are different batches, and collapsing
24344
+ // them to one key would make the second submit look like a duplicate and
24345
+ // leave those refs unqualified.
24346
+ prior: [
24347
+ // UUID-folded like the refs above: the backend resolves the same
24348
+ // delivery job regardless of casing, so casing alone must not fork
24349
+ // the key and re-run a paid batch.
24350
+ normalizeUuid(params.prior_deliveries?.job_id),
24351
+ params.prior_deliveries?.since ?? null,
24352
+ params.prior_deliveries?.limit ?? null
24353
+ ],
24354
+ // Canonicalize to the value the BACKEND will apply, so an approval that
24355
+ // omits a field and a retry that passes that field's documented default
24356
+ // derive the same key instead of launching a second paid job.
24357
+ qualify: params.qualify !== false,
24358
+ channels: canonicalSet(params.channels),
24359
+ contact_titles: canonicalLabelSet(params.contact_titles),
24360
+ // Same canonicalization as the search path: with contact_titles present
24361
+ // the backend applies `prefer` when the field is omitted, so an approval
24362
+ // that omits it and a retry that passes the materialized default describe
24363
+ // identical work. Hashing the omission as null forked the key and let the
24364
+ // retry escape dedupe into a second paid qualification / channel purchase.
24365
+ title_gate: params.title_gate ?? ((params.contact_titles?.length ?? 0) > 0 ? "prefer" : null),
24366
+ // The cap is part of the approval: raising it after a stop_reason:max_cost
24367
+ // is a NEW approved run, and must not dedupe onto the capped job.
24368
+ max_cost: params.max_cost ?? null,
24369
+ // Same for the output language — re-running the batch in another language
24370
+ // must not return the earlier job with evidence in the previous one.
24371
+ lang: params.lang ?? null
24372
+ };
24373
+ return derivedKey("qualify-auto", shape);
24374
+ }
24375
+ var qualifyLeads = {
24376
+ name: "leadbay_qualify_leads",
24377
+ annotations: {
24378
+ title: "Qualify + get the right contact on known leads",
24379
+ readOnlyHint: false,
24380
+ // Spends real money (fresh qualification, and email/phone reveals when
24381
+ // channels are requested), same as bulk_qualify_leads / enrich-titles.
24382
+ // Hosts and approval layers key their prompts off this flag, so a paid
24383
+ // job submitter must not advertise itself as harmless.
24384
+ destructiveHint: true,
24385
+ idempotentHint: false,
24386
+ openWorldHint: true
24387
+ },
24388
+ write: true,
24389
+ description: leadbay_qualify_leads,
24390
+ inputSchema: {
24391
+ type: "object",
24392
+ properties: {
24393
+ lead_refs: {
24394
+ type: "array",
24395
+ description: "Companies to qualify (max 500). Each ref needs at least one identifying field. Duplicate lead_ids collapse into one item.",
24396
+ items: {
24397
+ type: "object",
24398
+ properties: {
24399
+ lead_id: { type: "string", description: "Leadbay lead UUID." },
24400
+ website: { type: "string" },
24401
+ name: { type: "string" },
24402
+ location: {
24403
+ type: "string",
24404
+ description: "Disambiguates name-only refs (city/region)."
24405
+ },
24406
+ contact_id: {
24407
+ type: "string",
24408
+ description: "Stable lead_contact id from a prior result \u2014 enrichment then targets EXACTLY this person, never a re-match."
24409
+ }
24410
+ },
24411
+ additionalProperties: false
24412
+ }
24413
+ },
24414
+ prior_deliveries: {
24415
+ type: "object",
24416
+ description: "Selector expanding the org's past MCP deliveries into refs \u2014 billed leads stay re-readable after result expiry. Combine with lead_refs or use alone.",
24417
+ properties: {
24418
+ job_id: { type: "string" },
24419
+ since: { type: "string", description: "ISO instant lower bound." },
24420
+ limit: { type: "number" }
24421
+ },
24422
+ additionalProperties: false
24423
+ },
24424
+ qualify: {
24425
+ type: "boolean",
24426
+ description: "Fresh AI qualification (default true; ~94 cost_cents per lead needing fresh research+scoring, cache-free when a fresh dossier exists). Owned disqualified leads come back WITH their negative evidence."
24427
+ },
24428
+ contact_titles: {
24429
+ type: "array",
24430
+ items: { type: "string" },
24431
+ description: "Wanted decision-maker titles (max 10), matched semantically."
24432
+ },
24433
+ title_gate: {
24434
+ type: "string",
24435
+ enum: ["strict", "prefer"],
24436
+ description: "strict = only items with a matching known contact deliver a contact; prefer = matched first, rest flagged."
24437
+ },
24438
+ channels: {
24439
+ type: "array",
24440
+ items: { type: "string", enum: ["email", "phone"] },
24441
+ description: "Channels to PURCHASE (email 25c, phone 250c, success-only, already-owned values are free). Empty = free identity tier."
24442
+ },
24443
+ max_cost: {
24444
+ type: "number",
24445
+ description: "Spend cap in cost_cents (plan-tier default when unset)."
24446
+ },
24447
+ request_id: {
24448
+ type: "string",
24449
+ description: "Recommended idempotency key \u2014 REUSE the same value when retrying the same batch so a retry returns the SAME job instead of re-spending."
24450
+ },
24451
+ lang: { type: "string", description: "Output language (default: user's language)." },
24452
+ confirm: {
24453
+ type: "boolean",
24454
+ description: "Explicit spend decision for the PAID work (fresh qualification and/or channel purchases). true = the user approved the quote, go ahead. false = a veto (returns mode:'needs_confirmation', spends nothing). Omitted on a paid call \u2192 the tool withholds the submit and returns a free quote to show the user first. A fully FREE call (qualify:false and no channels) needs no confirm."
24455
+ },
24456
+ dry_run: {
24457
+ type: "boolean",
24458
+ description: "Validate + worst-case cost + quota forecast. No job, no spend."
24459
+ },
24460
+ wait_seconds: {
24461
+ type: "number",
24462
+ description: "How long to poll before returning (default 45, max 180, 0 = submit + one snapshot). Large or research-heavy batches can take minutes \u2014 the result then carries still_running:true and the job_id for leadbay_lead_job_status."
24463
+ }
24464
+ },
24465
+ additionalProperties: false
24466
+ },
24467
+ execute: async (client, params, ctx) => {
24468
+ params = coerceArrayParams(params, [
24469
+ "lead_refs",
24470
+ "contact_titles",
24471
+ "channels"
24472
+ ]);
24473
+ params = { ...params, lead_refs: normalizeLeadRefs(params.lead_refs) };
24474
+ rejectMalformedLeadRefs(params.lead_refs);
24475
+ rejectOversizedLeadRefs(params.lead_refs);
24476
+ const qualify = readSpendFlag(params.qualify, "qualify");
24477
+ const dryRun = readSpendFlag(params.dry_run, "dry_run");
24478
+ const confirm = readSpendFlag(params.confirm, "confirm");
24479
+ params = { ...params, qualify, dry_run: dryRun, confirm };
24480
+ const buysChannels = (params.channels?.length ?? 0) > 0;
24481
+ const buysQualification = qualify !== false;
24482
+ const isPaid = buysQualification || buysChannels;
24483
+ const vetoed = confirm === false;
24484
+ const consented = !vetoed && confirm === true;
24485
+ const requestId = presentRequestId(params.request_id) ?? (isPaid ? derivedRequestId(params) : void 0);
24486
+ const body = compactBody({
24487
+ lead_refs: params.lead_refs,
24488
+ prior_deliveries: params.prior_deliveries,
24489
+ qualify,
24490
+ contact_titles: params.contact_titles,
24491
+ title_gate: params.title_gate,
24492
+ channels: params.channels,
24493
+ max_cost: params.max_cost,
24494
+ request_id: requestId,
24495
+ lang: params.lang,
24496
+ dry_run: dryRun
24497
+ });
24498
+ if (dryRun === true) {
24499
+ const forecast = await client.request("POST", "/mcp/qualify", body);
24500
+ return { dry_run: true, ...forecast, region: client.region };
24501
+ }
24502
+ if (isPaid && !consented) {
24503
+ const forecast = vetoed ? null : await client.request("POST", "/mcp/qualify", {
24504
+ ...body,
24505
+ dry_run: true
24506
+ });
24507
+ return {
24508
+ mode: "needs_confirmation",
24509
+ submitted: false,
24510
+ vetoed,
24511
+ paid_because: [
24512
+ buysQualification ? "qualify is on (backend default is true \u2014 pass qualify:false to keep it free)" : null,
24513
+ buysChannels ? `channels requested: ${params.channels.join(", ")}` : null
24514
+ ].filter(Boolean),
24515
+ quote: forecast,
24516
+ estimated_cost: forecast?.estimated_cost ?? null,
24517
+ items_requested: forecast?.items_requested ?? null,
24518
+ hint: vetoed ? "confirm:false vetoed the spend \u2014 nothing was submitted. Re-call with confirm:true to proceed, or qualify:false with no channels for a free pass." : "Show the user this worst-case quote and get an explicit go-ahead, then re-call with confirm:true. For a free pass instead: qualify:false and no channels.",
24519
+ region: client.region
24520
+ };
24521
+ }
24522
+ const submit = await client.request("POST", "/mcp/qualify", body, { preSendSignal: ctx?.signal });
24523
+ const mocked = mockedSubmitPreview(submit, "leadbay_qualify_leads", client.region);
24524
+ if (mocked)
24525
+ return mocked;
24526
+ const waitSeconds = clampWaitSeconds(params.wait_seconds, DEFAULT_WAIT_SECONDS2);
24527
+ const snapshot = await snapshotAfterSubmit(client, submit.job_id, waitSeconds, ctx, submit.items_requested);
24528
+ const done = TERMINAL_JOB_STATES.has(snapshot.job.state);
24529
+ const indexed = submit.duplicate ?? false ? remapInputIndexes(snapshot.items, params.lead_refs) : { items: snapshot.items, remapped: true };
24530
+ const view = { ...snapshot, items: indexed.items };
24531
+ return {
24532
+ job_id: submit.job_id,
24533
+ // Echo the key actually sent, so a retry can reuse it verbatim.
24534
+ request_id: requestId ?? null,
24535
+ duplicate_submit: submit.duplicate ?? false,
24536
+ state: snapshot.job.state,
24537
+ done,
24538
+ summary: {
24539
+ refs_submitted: params.lead_refs?.length ?? 0,
24540
+ items_requested: submit.items_requested,
24541
+ delivered: snapshot.funnel.delivered ?? 0,
24542
+ delivered_callable: snapshot.funnel.delivered_callable ?? 0,
24543
+ degraded: snapshot.funnel.degraded ?? 0,
24544
+ resolved: snapshot.funnel.resolved ?? null,
24545
+ not_in_universe: snapshot.funnel.not_in_universe ?? null,
24546
+ stop_reason: snapshot.funnel.stop_reason ?? null
24547
+ },
24548
+ funnel: snapshot.funnel,
24549
+ // Per-item outcomes in input order where known (ref.input_indexes maps
24550
+ // back to the caller's lead_refs positions). Items carry the full
24551
+ // QualifiedLead payload when delivered/degraded, and an honest
24552
+ // status_reason (not_in_universe, low_confidence_identity, ...) when
24553
+ // skipped — a skip is an ANSWER about that ref, not an error.
24554
+ items: view.items,
24555
+ // On a duplicate submit whose indexes could not be re-pointed at this
24556
+ // caller's refs, input_indexes are null rather than stale — match items
24557
+ // by `ref.requested_as` / `lead_id` instead.
24558
+ input_indexes_remapped: submit.duplicate ?? false ? indexed.remapped : null,
24559
+ // ...and the same outcomes pre-split, because the shared
24560
+ // rendering/lead-delivery-table contract this tool's description
24561
+ // mandates reads deliveries from `leads[]` and skips from `skipped[]`.
24562
+ // Returning only `items` left an agent following the RENDER block with
24563
+ // two empty tables; the sibling tools (find_new_leads, lead_job_status)
24564
+ // both split. `items` stays for input-order per-ref mapping.
24565
+ ...splitItems(view),
24566
+ items_truncated: snapshot.items_truncated ?? false,
24567
+ // Top-level, not only inside next_poll: a TERMINAL job that truncated had
24568
+ // next_poll null, so the rendering rule pointing at `since: next_since`
24569
+ // named a cursor the response did not carry.
24570
+ next_since: snapshot.next_since ?? null,
24571
+ cost: snapshot.cost,
24572
+ estimated_cost: submit.estimated_cost,
24573
+ explain: snapshot.explain,
24574
+ still_running: !done,
24575
+ // A finished job can still owe rows: truncation means the drain stopped
24576
+ // early, so there is a follow-up action even when done is true.
24577
+ next_poll: done && !(snapshot.items_truncated ?? false) ? null : {
24578
+ tool: "leadbay_lead_job_status",
24579
+ job_id: submit.job_id,
24580
+ // Hand the cursor forward so the follow-up poll continues
24581
+ // INCREMENTALLY instead of re-reading (and re-rendering) the
24582
+ // rows already delivered in this response.
24583
+ since: snapshot.next_since ?? null,
24584
+ suggested_wait_seconds: done ? 0 : 60
24585
+ },
24586
+ region: client.region
24587
+ };
24588
+ }
24589
+ };
24590
+
24591
+ // ../core/dist/composite/lead-job-status.js
24592
+ var leadJobStatus = {
24593
+ name: "leadbay_lead_job_status",
24594
+ annotations: {
24595
+ title: "Poll a lead-delivery job",
24596
+ readOnlyHint: true,
24597
+ destructiveHint: false,
24598
+ idempotentHint: true,
24599
+ openWorldHint: true
24600
+ },
24601
+ description: leadbay_lead_job_status,
24602
+ inputSchema: {
24603
+ type: "object",
24604
+ properties: {
24605
+ job_id: {
24606
+ type: "string",
24607
+ description: "The job_id returned by leadbay_find_new_leads or leadbay_qualify_leads."
24608
+ },
24609
+ since: {
24610
+ type: "string",
24611
+ description: "Opaque cursor from a previous poll's next_since \u2014 returns only items emitted after it. Omit for the full snapshot."
24612
+ },
24613
+ limit: {
24614
+ type: "number",
24615
+ description: "Items per page, 1-100 (default 100; pages are auto-collected)."
24616
+ },
24617
+ wait_seconds: {
24618
+ type: "number",
24619
+ description: "0 (default) = instant snapshot. >0 = keep polling up to this many seconds until the job is terminal \u2014 use ~60 when the user asked to wait for results."
24620
+ }
24621
+ },
24622
+ required: ["job_id"],
24623
+ additionalProperties: false
24624
+ },
24625
+ execute: async (client, params, ctx) => {
24626
+ const waitSeconds = clampWaitSeconds(params.wait_seconds, 0);
24627
+ const snapshot = waitSeconds > 0 ? await waitForJob(client, params.job_id, waitSeconds, ctx, void 0, params.since, params.limit) : await collectJobSnapshot(client, params.job_id, params.since, params.limit, ctx?.signal);
24628
+ const done = TERMINAL_JOB_STATES.has(snapshot.job.state);
24629
+ const { leads, skipped } = splitItems(snapshot);
24630
+ return {
24631
+ job_id: params.job_id,
24632
+ state: snapshot.job.state,
24633
+ done,
24634
+ funnel: snapshot.funnel,
24635
+ leads,
24636
+ skipped,
24637
+ // Surfaced so the renderer never presents a partial page set as the whole
24638
+ // result: `leads` is a prefix, and next_since resumes it.
24639
+ items_truncated: snapshot.items_truncated ?? false,
24640
+ next_since: snapshot.next_since ?? null,
24641
+ cost: snapshot.cost,
24642
+ explain: snapshot.explain,
24643
+ still_running: !done,
24644
+ // Truncation leaves rows unread even on a finished job, so the follow-up
24645
+ // action survives `done` — same rule as the two submit tools.
24646
+ next_poll: done && !(snapshot.items_truncated ?? false) ? null : {
24647
+ tool: "leadbay_lead_job_status",
24648
+ job_id: params.job_id,
24649
+ // Same incremental handoff as the submit tools — following
24650
+ // next_poll without the cursor re-reads the rows just returned.
24651
+ since: snapshot.next_since ?? null,
24652
+ suggested_wait_seconds: done ? 0 : 60
24653
+ },
24654
+ region: client.region
24655
+ };
24656
+ }
24657
+ };
24658
+
24659
+ // ../core/dist/composite/extend-lens.js
24660
+ function httpStatus(err) {
24661
+ return err?._meta?.http_status;
24662
+ }
24663
+ async function readExtraRefillQuota(client) {
24664
+ try {
24665
+ const me = await client.resolveMe();
24666
+ const quota = await client.request("GET", `/organizations/${me.organization.id}/quota_status`);
24667
+ const isRefill = (r) => r.resource_type?.toUpperCase() === "LENS_EXTRA_REFILL";
24668
+ const entry = quota.org?.resources?.find(isRefill) ?? quota.user?.resources?.find(isRefill);
24669
+ return {
24670
+ count: entry?.count ?? null,
24671
+ resets_at: entry?.resets_at ?? null
24672
+ };
24673
+ } catch {
24674
+ return { count: null, resets_at: null };
24675
+ }
24676
+ }
24677
+ async function readAvailablePool(client, lensId) {
24678
+ try {
24679
+ const preview = await client.request("GET", `/lenses/${lensId}/extra_refill_preview`);
24680
+ return typeof preview?.available_count === "number" ? preview.available_count : null;
24681
+ } catch {
24682
+ return null;
24683
+ }
24684
+ }
24685
+ async function readLensLeadTotal(client, lensId) {
24686
+ try {
24687
+ const page = await client.request("GET", `/lenses/${lensId}/leads/wishlist?count=1&page=0`);
24688
+ return typeof page?.pagination?.total === "number" ? page.pagination.total : null;
24689
+ } catch {
24690
+ return null;
24691
+ }
24692
+ }
24693
+ function noCandidatesReason(held, shape) {
24694
+ const { geoSentence, ...extras } = shape;
24695
+ const futile = " Extending again is futile \u2014 a refill on a lens with an empty candidate pool reports queued, consumes no quota and delivers nothing.";
24696
+ if (held === 0) {
24697
+ return {
24698
+ code: "audience_too_narrow",
24699
+ retryable: false,
24700
+ message: "This lens holds no leads and has none left to add: its criteria intersect to nothing." + geoSentence + futile + " Tell the user which criteria are in play and offer to widen the audience (leadbay_adjust_audience).",
22202
24701
  ...extras
22203
24702
  };
22204
24703
  }
@@ -23506,8 +26005,8 @@ var sendFeedback = {
23506
26005
  }
23507
26006
  },
23508
26007
  execute: async (client, params, ctx) => {
23509
- const text = typeof params.message === "string" ? params.message.trim() : "";
23510
- if (!text) {
26008
+ const text2 = typeof params.message === "string" ? params.message.trim() : "";
26009
+ if (!text2) {
23511
26010
  return {
23512
26011
  error: true,
23513
26012
  code: "BAD_INPUT",
@@ -23515,7 +26014,7 @@ var sendFeedback = {
23515
26014
  hint: "Ask the user what they'd like to tell the Leadbay team, then call again with their words in `message`."
23516
26015
  };
23517
26016
  }
23518
- const message = text.length > MESSAGE_MAX2 ? `${text.slice(0, MESSAGE_MAX2 - 1)}\u2026` : text;
26017
+ const message = text2.length > MESSAGE_MAX2 ? `${text2.slice(0, MESSAGE_MAX2 - 1)}\u2026` : text2;
23519
26018
  if (!ctx?.sendFeedback) {
23520
26019
  return {
23521
26020
  sent: false,
@@ -23646,6 +26145,13 @@ granularTools.forEach((t) => {
23646
26145
  t.advanced = true;
23647
26146
  });
23648
26147
  var compositeReadTools = [
26148
+ // Poll surface for the MCP-first lead-delivery jobs (find_new_leads /
26149
+ // qualify_leads). Read-only snapshot of a backend-owned job. The backend
26150
+ // routes (`POST /1.6/mcp/search`, `POST /1.6/mcp/qualify`,
26151
+ // `GET /1.6/mcp/jobs/{id}`) shipped to production in backend v3.22.0
26152
+ // (2026-08-22) and were verified live on both regions, so the opt-in
26153
+ // LEADBAY_MCP_LEAD_DELIVERY flag that held these three back is gone.
26154
+ leadJobStatus,
23649
26155
  pullLeads,
23650
26156
  pullFollowups,
23651
26157
  followupsMap,
@@ -23708,6 +26214,11 @@ var compositeReadTools = [
23708
26214
  // leadbay_new_lens / leadbay_adjust_audience). Without it the agent can only
23709
26215
  // probe sectors by trial-and-error or ask the user to read the web UI.
23710
26216
  listSectors,
26217
+ // listLocations, same rationale on the geography axis. The delivery tools
26218
+ // reject an unresolvable filters.locations with a 400 naming the value and
26219
+ // send the agent here to look up the real admin area — a recovery path that
26220
+ // only works if the lookup is reachable without LEADBAY_MCP_ADVANCED=1.
26221
+ listLocations,
23711
26222
  // Billing / top-up tools — granular-shaped but ALWAYS exposed because
23712
26223
  // they're the canonical recovery path from a QUOTA_EXCEEDED wall. If
23713
26224
  // they were gated behind LEADBAY_MCP_ADVANCED=1 the agent would
@@ -23737,7 +26248,21 @@ var compositeReadTools = [
23737
26248
  // tools/) so it carries no _triggered_by mandate for a kit fetch.
23738
26249
  artifactKit
23739
26250
  ];
26251
+ var mcpFirstDeliveryTools = [
26252
+ // Write-tier: submits create server-side jobs that can spend money
26253
+ // (qualification research, channel purchase) and claim novelty in the
26254
+ // org's delivery ledger — same posture as the other spending composites.
26255
+ // The FREE tier (qualify:false, channels:[]) is the default ask, and a paid
26256
+ // call is withheld in code until `confirm: true`.
26257
+ findNewLeads,
26258
+ qualifyLeads
26259
+ ];
26260
+ var mcpFirstDeliveryAllTools = [
26261
+ ...mcpFirstDeliveryTools,
26262
+ leadJobStatus
26263
+ ];
23740
26264
  var compositeWriteTools = [
26265
+ ...mcpFirstDeliveryTools,
23741
26266
  bulkQualifyLeads,
23742
26267
  enrichTitles,
23743
26268
  adjustAudience,
@@ -24598,8 +27123,22 @@ function buildProtocolPrimitivesParagraph(has) {
24598
27123
  "import_and_qualify",
24599
27124
  "enrich_titles",
24600
27125
  "bulk_enrich_status",
24601
- "qualify_status"
27126
+ "qualify_status",
27127
+ // The MCP-first delivery jobs block-poll for 45s by default and up to
27128
+ // 180s. Without a progressToken ctx.progress is absent, so the call looks
27129
+ // frozen for minutes — the exact case this paragraph exists to prevent.
27130
+ // `.filter(has)` keeps the iter-12 invariant: a deployment without the
27131
+ // delivery flag never sees them named.
27132
+ "find_new_leads",
27133
+ "qualify_leads",
27134
+ "lead_job_status"
24602
27135
  ].filter((n) => has(`leadbay_${n}`));
27136
+ const legacyRunners = longRunners.filter(
27137
+ (n) => !["find_new_leads", "qualify_leads", "lead_job_status"].includes(n)
27138
+ );
27139
+ const deliveryRunners = longRunners.filter(
27140
+ (n) => ["find_new_leads", "qualify_leads", "lead_job_status"].includes(n)
27141
+ );
24603
27142
  const elicitTools = [
24604
27143
  "refine_prompt clarifications",
24605
27144
  "report_outreach.user_confirmed"
@@ -24618,9 +27157,20 @@ function buildProtocolPrimitivesParagraph(has) {
24618
27157
  "(1) `notifications/progress` \u2014 when you pass `_meta.progressToken` on a tools/call, long-running composites stream per-unit-of-work progress (none of the long-runners are currently exposed in this configuration)."
24619
27158
  );
24620
27159
  }
24621
- if (longRunners.length > 0) {
27160
+ if (legacyRunners.length > 0 || deliveryRunners.length > 0) {
27161
+ const clauses = [];
27162
+ if (legacyRunners.length > 0) {
27163
+ clauses.push(
27164
+ "On " + legacyRunners.map((n) => `leadbay_${n}`).join(", ") + " the job itself keeps running on the backend; poll its notification_id / importIds later to pick it up."
27165
+ );
27166
+ }
27167
+ if (deliveryRunners.length > 0) {
27168
+ clauses.push(
27169
+ "On " + deliveryRunners.map((n) => `leadbay_${n}`).join(", ") + " the job is BACKEND-owned and likewise keeps running. Any work already paid for still completes; poll `leadbay_lead_job_status` with the `job_id` later to collect it."
27170
+ );
27171
+ }
24622
27172
  parts.push(
24623
- "(2) `notifications/cancelled` \u2014 when the user clicks Cancel in the host UI, the polling loop exits within \u22642 seconds. The job itself keeps running on the backend; poll its notification_id / importIds later to pick it up."
27173
+ "(2) `notifications/cancelled` \u2014 when the user clicks Cancel in the host UI, the polling loop exits within \u22642 seconds. " + clauses.join(" ")
24624
27174
  );
24625
27175
  } else {
24626
27176
  parts.push(
@@ -24827,11 +27377,16 @@ function buildServer(client, opts = {}) {
24827
27377
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
24828
27378
  tools: toolsListPayload([...toolByName.values()])
24829
27379
  }));
27380
+ const promptGate = { includeWrite: Boolean(opts.includeWrite) };
24830
27381
  server.setRequestHandler(ListPromptsRequestSchema, async () => ({
24831
- prompts: listPrompts()
27382
+ prompts: listPrompts(promptGate)
24832
27383
  }));
24833
27384
  server.setRequestHandler(GetPromptRequestSchema, async (req) => {
24834
- return getPrompt(req.params.name, req.params.arguments ?? {});
27385
+ return getPrompt(
27386
+ req.params.name,
27387
+ req.params.arguments ?? {},
27388
+ promptGate
27389
+ );
24835
27390
  });
24836
27391
  server.setRequestHandler(ListResourcesRequestSchema, async () => ({
24837
27392
  resources: listResources()
@@ -25172,6 +27727,9 @@ ${url}
25172
27727
  }) === true
25173
27728
  }));
25174
27729
  await maybeAttachUpdate(name, result);
27730
+ if (name === "leadbay_account_status" && result !== null && typeof result === "object" && !Array.isArray(result) && result.error !== true) {
27731
+ result.mcp_version = serverVersion;
27732
+ }
25175
27733
  maybeAttachNotifications(result);
25176
27734
  if (result && typeof result === "object" && result.error === true) {
25177
27735
  const envText = formatErrorForLLM(result);
@@ -25568,7 +28126,7 @@ function parseWriteEnv(env = process.env) {
25568
28126
  }
25569
28127
 
25570
28128
  // src/http-server.ts
25571
- var VERSION = true ? "0.36.0" : "0.0.0-dev";
28129
+ var VERSION = true ? "0.38.0" : "0.0.0-dev";
25572
28130
  var PORT = Number(process.env.PORT ?? 8080);
25573
28131
  var HOST = process.env.HOST ?? "0.0.0.0";
25574
28132
  var logger = {