@leadbay/mcp 0.36.0 → 0.37.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/dist/bin.js +2664 -80
- package/dist/http-server.js +2677 -133
- package/dist/installer-electron.js +1 -1
- package/dist/installer-gui.js +1 -1
- package/package.json +1 -1
package/dist/http-server.js
CHANGED
|
@@ -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(
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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((
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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",
|
|
@@ -4620,7 +4974,7 @@ Context: Leadbay auto-qualifies roughly the top 10 of each daily batch. Leads be
|
|
|
4620
4974
|
|
|
4621
4975
|
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
4976
|
|
|
4623
|
-
WHEN NOT TO USE: to qualify a single specific lead \u2014 that's leadbay_qualify_lead (granular, advanced).
|
|
4977
|
+
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
4978
|
|
|
4625
4979
|
## A launched job cannot be stopped
|
|
4626
4980
|
|
|
@@ -5252,7 +5606,7 @@ var leadbay_extend_lens = `## WHEN TO USE
|
|
|
5252
5606
|
|
|
5253
5607
|
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
5608
|
|
|
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\`.
|
|
5609
|
+
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
5610
|
|
|
5257
5611
|
Prefer when: user has bigger appetite than the daily lens fill delivers \u2014 additive refill on same criteria
|
|
5258
5612
|
|
|
@@ -5341,6 +5695,256 @@ Pick the row matching the response \`status\`. Seed-picking is internal; do NOT
|
|
|
5341
5695
|
|
|
5342
5696
|
If nothing matches cleanly, default to "pull leads now to see what's queued" \u2014 never invent a tool that doesn't exist.
|
|
5343
5697
|
`;
|
|
5698
|
+
var leadbay_find_new_leads = `## WHEN TO USE
|
|
5699
|
+
|
|
5700
|
+
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".
|
|
5701
|
+
|
|
5702
|
+
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\`.
|
|
5703
|
+
|
|
5704
|
+
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.
|
|
5705
|
+
|
|
5706
|
+
Examples that SHOULD invoke this tool:
|
|
5707
|
+
- "Find me 10 gyms around Dallas that would buy our flooring, with someone I can call."
|
|
5708
|
+
- "Get me 20 new US SaaS companies, 50-2000 employees, with the VP People's email."
|
|
5709
|
+
- "We're launching in Lyon \u2014 find 15 hotels that fit our ICP."
|
|
5710
|
+
|
|
5711
|
+
Examples that should NOT invoke this tool (sound similar, route elsewhere):
|
|
5712
|
+
- "Show me today's leads."
|
|
5713
|
+
- "Which leads should I follow up with this week?"
|
|
5714
|
+
- "Qualify these 40 websites from my spreadsheet."
|
|
5715
|
+
|
|
5716
|
+
## RENDER (quick)
|
|
5717
|
+
|
|
5718
|
+
3-col table of delivered leads in returned order: col 1 = 10-segment fit
|
|
5719
|
+
bar + linked company \xB7 location \xB7 size; col 2 = why-fits \u226420 words; col 3
|
|
5720
|
+
= contact + purchased channels. ALWAYS close with the honest funnel line
|
|
5721
|
+
(matched/examined/delivered/stop reason/spend) \u2014 especially on 0
|
|
5722
|
+
delivered. Full algorithm below.
|
|
5723
|
+
|
|
5724
|
+
---
|
|
5725
|
+
|
|
5726
|
+
Submit a net-new lead search: the backend matches an ICP seed against the full
|
|
5727
|
+
company universe, applies hard filters, skips what the org already knows
|
|
5728
|
+
(\`novelty: org\`), optionally qualifies against the org's own intelligence
|
|
5729
|
+
(questions, tags, ideal buyer profile \u2014 frozen at submit), and optionally buys
|
|
5730
|
+
contact channels. Polls up to \`wait_seconds\` (default 45); a longer job returns
|
|
5731
|
+
\`still_running\` + \`next_poll\` \u2014 hand off to \`leadbay_lead_job_status\`. Jobs run
|
|
5732
|
+
\u226430 min, results kept 30 days.
|
|
5733
|
+
|
|
5734
|
+
**Free vs paid \u2014 never spend silently.** Default (\`qualify: false\`,
|
|
5735
|
+
\`channels: []\`) is FREE: company profile + fit score + cached research +
|
|
5736
|
+
contact identity. Paid: \`qualify: true\` (~94 cost_cents per candidate
|
|
5737
|
+
EXAMINED, capped by \`exploration_cap\`/\`max_cost\`) and \`channels\` (email 25c /
|
|
5738
|
+
phone 250c, success-only). Enforced in code: a paid call is WITHHELD unless it
|
|
5739
|
+
carries \`confirm: true\` \u2014 nothing is submitted and you get
|
|
5740
|
+
\`mode: "needs_confirmation"\` with a real quote to show the user. Re-call with
|
|
5741
|
+
\`confirm: true\` on their go-ahead ("spend / get their emails" counts).
|
|
5742
|
+
\`confirm: false\` vetoes. Free needs no consent. **Preview free first** \u2014
|
|
5743
|
+
reshaping an off-profile seed is free, exploring it with \`qualify: true\` is
|
|
5744
|
+
not.
|
|
5745
|
+
|
|
5746
|
+
**Ad-hoc exclusions ("no chains") are enforced by NO tier** \u2014 \`filters\` has no
|
|
5747
|
+
exclusion key, and \`qualify\` scores against the org's FROZEN questions and IBP,
|
|
5748
|
+
which need not mention chains; the seed's inverse only shifts ranking.
|
|
5749
|
+
Violators can survive, be paid for and be delivered \u2014 post-filter them yourself
|
|
5750
|
+
and say the tier didn't enforce it. Durable enforcement \u2192
|
|
5751
|
+
\`leadbay_refine_prompt\`.
|
|
5752
|
+
|
|
5753
|
+
### Crafting the \`example_lead\` seed \u2014 the input that decides result quality
|
|
5754
|
+
|
|
5755
|
+
The \`example_lead\` is a FICTIONAL typical ideal customer, matched against real
|
|
5756
|
+
registry/website descriptions \u2014 which state what a company **IS**, never what
|
|
5757
|
+
is happening. Write it the same way or the matcher drifts. Every rule below is
|
|
5758
|
+
measured:
|
|
5759
|
+
|
|
5760
|
+
1. **Describe the BUYER, never the seller.** Ask: "would this company write a
|
|
5761
|
+
check to my user?" A seed describing what the user SELLS surfaces their
|
|
5762
|
+
*competitors and vendors*. If the product helps companies of type X serve
|
|
5763
|
+
customers of type Y, the seed describes X \u2014 never Y.
|
|
5764
|
+
2. **Put everything in \`description\`; leave \`name\` unset.** An invented brand
|
|
5765
|
+
name pulls matching toward name-lookalikes \u2014 a seed named "Meridian
|
|
5766
|
+
Analytics" returned five unrelated "Meridian" companies.
|
|
5767
|
+
3. **Registry style, one sentence to ~250 chars.** Industry niche, business
|
|
5768
|
+
model, what they sell or operate, who they serve, observable scale. Write
|
|
5769
|
+
it like the first paragraph of their About-Us page.
|
|
5770
|
+
- STRONG: "Operator of full-service fitness centers offering strength
|
|
5771
|
+
areas, group classes and personal training to members across multiple
|
|
5772
|
+
clubs."
|
|
5773
|
+
- WEAK (generic): "A gym in Texas."
|
|
5774
|
+
- WRONG (seller-side): "Supplier of durable modular flooring for gyms."
|
|
5775
|
+
4. **No event language.** "hiring", "expanding", "just raised" are not
|
|
5776
|
+
filters \u2014 registry descriptions never contain them, so they dilute the
|
|
5777
|
+
profile. Purchase triggers belong in the org's qualification questions.
|
|
5778
|
+
5. **No meta-markers.** Never "(example)", "(fictional)", "(placeholder)".
|
|
5779
|
+
6. **Hard constraints go in \`filters\`, not prose \u2014 exact keys:**
|
|
5780
|
+
\`sectors: string[]\`, \`locations: string[]\`, \`employees_min: number\`,
|
|
5781
|
+
\`employees_max: number\`. FLAT numbers \u2014 nested \`employees: {min, max}\`
|
|
5782
|
+
exists only in RESULT payloads. \`example_lead.employees\` does not filter.
|
|
5783
|
+
\`locations\` take city/state/region names ("Dallas, TX", "\xCEle-de-France");
|
|
5784
|
+
a country name is refused in code \u2014 whole-country intent = omit it.
|
|
5785
|
+
7. **Prefer \`example_lead\` over \`query\`.** Query matches topic *vocabulary*:
|
|
5786
|
+
"gyms that need durable flooring" surfaced flooring VENDORS, 0 delivered.
|
|
5787
|
+
Use \`query\` only for signal an example can't express.
|
|
5788
|
+
8. **One seed per buyer archetype.** An ask spanning two segments ("gyms and
|
|
5789
|
+
warehouses") needs one search each with its own description and
|
|
5790
|
+
\`request_id\` \u2014 a blended seed lands between the clusters and matches
|
|
5791
|
+
neither.
|
|
5792
|
+
|
|
5793
|
+
|
|
5794
|
+
**Parameter notes**
|
|
5795
|
+
- \`request_id\` (REQUIRED) is the retry contract: SAME value retrying the same
|
|
5796
|
+
ask (same live job, no double spend); NEW for a changed ask. Derive from ask
|
|
5797
|
+
+ archetype + date: \`gyms-dallas-2026-07-28\`.
|
|
5798
|
+
- Never lower \`min_ai_score\` together with \`channels\` \u2014 that buys emails for
|
|
5799
|
+
leads the AI just scored as junk.
|
|
5800
|
+
- \`count\` \u2264 50; \u22643 active jobs/org; \u226410 submits/hour (429 + Retry-After \u2014
|
|
5801
|
+
wait, don't hammer).
|
|
5802
|
+
|
|
5803
|
+
**Read the result honestly** \u2014 \`funnel\` + \`explain.scope_notes\` tell the story;
|
|
5804
|
+
zero delivered gets a cause and a next move (rules in RENDERING).
|
|
5805
|
+
|
|
5806
|
+
---
|
|
5807
|
+
|
|
5808
|
+
## RENDERING \u2014 delivery table + honest funnel line
|
|
5809
|
+
|
|
5810
|
+
Render delivered leads (\`leads[]\`, i.e. items with status \`delivered\` or
|
|
5811
|
+
\`degraded\`) as a markdown table **in the order returned**. Exactly three
|
|
5812
|
+
columns. Then ALWAYS close with the funnel line (below) \u2014 even, especially,
|
|
5813
|
+
when nothing was delivered.
|
|
5814
|
+
|
|
5815
|
+
**Column 1 \u2014 Company**
|
|
5816
|
+
|
|
5817
|
+
- Line 1: 10-segment fit bar in inline-code backticks from \`lead.fit.score\`
|
|
5818
|
+
(0-100): \`filled = round(score/10)\`, glyphs \`\u25B0\` filled / \`\u25B1\` empty. When
|
|
5819
|
+
\`lead.fit.components.qualification.available\` is true AND \`ai_score > 0\`,
|
|
5820
|
+
replace the LAST filled segment with \`\u2756\` (AI-confirmed cap). When
|
|
5821
|
+
\`fit.available\` is false, render \`\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\` and say "unscored" in col 2.
|
|
5822
|
+
Never print the numeric score.
|
|
5823
|
+
- Insert \`<br>\`, then: linked company name (target \`company.website\`, bare
|
|
5824
|
+
hostnames get \`https://\`; unlinked plain text when absent) + \` \xB7 \` + short
|
|
5825
|
+
location (City, ST / City, Country) + \` \xB7 \` + employees as \`min\u2013max\` (omit
|
|
5826
|
+
when \`employees.known\` is false).
|
|
5827
|
+
|
|
5828
|
+
**Column 2 \u2014 Why it fits**
|
|
5829
|
+
|
|
5830
|
+
- One sentence \u2264 20 words. Priority: \`fit.reasoning\` \u2192 gist of
|
|
5831
|
+
\`company.description\` \u2192 top \`fit.components.qualification.matched_tags\`.
|
|
5832
|
+
- If the item status is \`degraded\` or a requested channel failed, append the
|
|
5833
|
+
honest flag in italics, e.g. *(email could not be sourced)*.
|
|
5834
|
+
|
|
5835
|
+
**Column 3 \u2014 Contact**
|
|
5836
|
+
|
|
5837
|
+
- \`[Name](linkedin) \xB7 role\` (linked name mandatory when a LinkedIn URL
|
|
5838
|
+
exists; plain name otherwise). Below it, the PURCHASED channels only:
|
|
5839
|
+
\`\u2709 value\` / \`\u260E value\` inline as plain text (they auto-linkify).
|
|
5840
|
+
- Channel statuses: \`delivered\` \u2192 show value; \`already_owned\` \u2192 value +
|
|
5841
|
+
*(already yours)*; \`masked\` \u2192 "on file \u2014 reveal via channels";
|
|
5842
|
+
\`not_requested\` \u2192 omit; \`failed_*\` \u2192 *(no verified email/phone)*.
|
|
5843
|
+
- No contact on the item (\`contact\` null): render \`\u2014\` (title_gate \`prefer\`
|
|
5844
|
+
delivers such rows flagged; say so in col 2 only when contact_titles were
|
|
5845
|
+
requested).
|
|
5846
|
+
|
|
5847
|
+
**The funnel line (mandatory, after the table):**
|
|
5848
|
+
|
|
5849
|
+
One short line narrating the delivery honestly, from \`funnel\` + \`cost\` +
|
|
5850
|
+
\`explain.scope_notes\`:
|
|
5851
|
+
|
|
5852
|
+
> Matched N \xB7 examined E \xB7 qualified Q \xB7 disqualified D \u2192 **delivered X of
|
|
5853
|
+
> the Y asked** \xB7 stopped: <stop_reason in plain words> \xB7 spent C.CC.
|
|
5854
|
+
|
|
5855
|
+
**Money: divide, then symbol.** Every amount (\`cost.spent\`,
|
|
5856
|
+
\`estimated_cost.max\`, quotes) is \`cost_cents\` \u2014 divide by 100, two decimals,
|
|
5857
|
+
so \`165\` renders \`1.65\`, NEVER \`165.00\`. Symbol from the account region: US
|
|
5858
|
+
\`$\`, France \`\u20AC\`, unknown \u2192 bare. Never hard-code \`$\`: it misstates a charge.
|
|
5859
|
+
|
|
5860
|
+
"of the Y asked" needs \`summary.items_requested\`, which submits carry but a
|
|
5861
|
+
later \`leadbay_lead_job_status\` snapshot does not. Without it write **delivered
|
|
5862
|
+
X** and stop \u2014 never back-fill Y from \`matched\`/\`examined\` (they count
|
|
5863
|
+
candidates), never guess it.
|
|
5864
|
+
|
|
5865
|
+
Plain-word stop reasons: \`target_reached\` \u2192 omit (success), \`pool_exhausted\` \u2192
|
|
5866
|
+
"ran out of matching candidates", \`max_cost\` \u2192 "hit the cost cap", \`quota\` \u2192
|
|
5867
|
+
"hit an org quota", \`time_budget\` \u2192 "hit the 30-min time budget".
|
|
5868
|
+
|
|
5869
|
+
**When \`delivered\` is 0**: NEVER say just "no results". Render no table; give
|
|
5870
|
+
the funnel line plus the relevant \`explain.scope_notes\` (the backend's own
|
|
5871
|
+
diagnosis), then propose the concrete fix (reshape the seed per the craft
|
|
5872
|
+
rules, lower \`min_ai_score\`, raise \`max_cost\`, drop a filter) as NEXT STEPS.
|
|
5873
|
+
|
|
5874
|
+
**Weak batch**: when the BEST delivered \`fit.score\` is under 30, don't present
|
|
5875
|
+
the table as an answer \u2014 open with "weak matches only", show at most the top 3,
|
|
5876
|
+
propose reshaping the seed/filters first. The count was filled with
|
|
5877
|
+
barely-better-than-random candidates.
|
|
5878
|
+
|
|
5879
|
+
**Sanity-check every row**: (a) geo \u2014 \`city\`/\`region\` must sit inside any
|
|
5880
|
+
requested fence; drop and call out leaks (same-named cities slip through).
|
|
5881
|
+
(b) When \`explain.seed_strategy\` is \`text_match_exemplars\` (the standard FR
|
|
5882
|
+
path), fit is calibrated for lead-to-lead distances, not exemplar centroids \u2014
|
|
5883
|
+
treat high scores skeptically and verify each row's \`description\`.
|
|
5884
|
+
|
|
5885
|
+
**Skipped items** (\`skipped[]\`, qualify jobs mostly): render a compact second
|
|
5886
|
+
table \`Ref \u2192 Outcome\` translating \`status_reason\` to plain words:
|
|
5887
|
+
\`not_in_universe\` \u2192 "not in the Leadbay universe (import it first)",
|
|
5888
|
+
\`low_confidence_identity\` \u2192 "couldn't safely match \u2014 check \`resolution.alternatives\`",
|
|
5889
|
+
\`no_matching_contact\` \u2192 "no contact with the requested title",
|
|
5890
|
+
\`disqualified\` \u2192 "evaluated: does not fit" (evidence is in the item when owned),
|
|
5891
|
+
\`enrichment_failed\` \u2192 "channel could not be sourced (not billed)".
|
|
5892
|
+
|
|
5893
|
+
**\`items_truncated\`**: rows are a PREFIX, not the batch. Say so, and offer
|
|
5894
|
+
\`leadbay_lead_job_status(job_id, since: next_since)\` for the rest.
|
|
5895
|
+
|
|
5896
|
+
**Hide from the user:** UUIDs (keep for tool calls, never render), cursors,
|
|
5897
|
+
\`explain.model\`/\`intelligence_snapshot\`, raw \`distance\`/\`calibration\`,
|
|
5898
|
+
\`seq\`/\`from_cache\`, empty arrays.
|
|
5899
|
+
|
|
5900
|
+
## Linking a contact's name
|
|
5901
|
+
|
|
5902
|
+
**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.**
|
|
5903
|
+
|
|
5904
|
+
URL priority (first applicable wins):
|
|
5905
|
+
|
|
5906
|
+
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).
|
|
5907
|
+
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.
|
|
5908
|
+
|
|
5909
|
+
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.
|
|
5910
|
+
|
|
5911
|
+
|
|
5912
|
+
|
|
5913
|
+
---
|
|
5914
|
+
|
|
5915
|
+
## NEXT STEPS \u2014 after a find_new_leads delivery
|
|
5916
|
+
|
|
5917
|
+
**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.
|
|
5918
|
+
|
|
5919
|
+
**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.
|
|
5920
|
+
|
|
5921
|
+
**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.
|
|
5922
|
+
- Skip example: "Show me today's leads and then research the top one for me." \u2192 after research completes, emit STOP without the widget.
|
|
5923
|
+
- 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.
|
|
5924
|
+
|
|
5925
|
+
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):
|
|
5926
|
+
- \`ask_user_input_v0\`: \`{questions:[{question,type:"single_select",options:["<Suggest 1>","<Suggest 2>"]}]}\`
|
|
5927
|
+
- \`AskUserQuestion\`: \`{questions:[{question,header:"Next step",multiSelect:false,options:[{label:"<\u22645 words>",description:"<Suggest 1>"}]}]}\`
|
|
5928
|
+
|
|
5929
|
+
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.
|
|
5930
|
+
|
|
5931
|
+
---
|
|
5932
|
+
|
|
5933
|
+
|
|
5934
|
+
|
|
5935
|
+
Pick the 2-3 options that match what actually happened \u2014 never all seven:
|
|
5936
|
+
|
|
5937
|
+
| Observation | Suggest | Calls |
|
|
5938
|
+
|---|---|---|
|
|
5939
|
+
| Job still running (\`still_running: true\`) | "Check on it in ~1 min" | leadbay_lead_job_status(job_id, wait_seconds: 60) |
|
|
5940
|
+
| Free run delivered on-profile leads | "Qualify these N against your criteria (paid \u2014 \`dry_run\` first)" | leadbay_qualify_leads(prior_deliveries: {job_id}) |
|
|
5941
|
+
| Delivered leads look right | "Draft outreach for the top ones" | leadbay_prepare_outreach |
|
|
5942
|
+
| Delivered 0 or off-profile | "Reshape the example and retry" (name the fix from funnel + scope_notes) | leadbay_find_new_leads (NEW request_id) |
|
|
5943
|
+
| 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) |
|
|
5944
|
+
| 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 |
|
|
5945
|
+
| Stopped on org quota and the user does not want to wait | "Top up to finish this run" | leadbay_create_topup_link |
|
|
5946
|
+
| User wants these tracked in Leadbay | "Add the keepers to a campaign" | leadbay_create_campaign / leadbay_add_leads_to_campaign |
|
|
5947
|
+
`;
|
|
5344
5948
|
var leadbay_followups_map = `## WHEN TO USE
|
|
5345
5949
|
|
|
5346
5950
|
Trigger phrases: "I'm going to <city>", "visit in person", "map of leads", "plan my itinerary".
|
|
@@ -6205,6 +6809,199 @@ spend before spending it again.
|
|
|
6205
6809
|
|
|
6206
6810
|
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
6811
|
`;
|
|
6812
|
+
var leadbay_lead_job_status = `## WHEN TO USE
|
|
6813
|
+
|
|
6814
|
+
Trigger phrases: "is the lead search done", "any results yet on that job", "check on the delivery".
|
|
6815
|
+
|
|
6816
|
+
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\`.
|
|
6817
|
+
|
|
6818
|
+
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.
|
|
6819
|
+
|
|
6820
|
+
Examples that SHOULD invoke this tool:
|
|
6821
|
+
- "Any leads yet from that search you started?"
|
|
6822
|
+
- "Wait for the qualification job to finish and show me everything."
|
|
6823
|
+
|
|
6824
|
+
Examples that should NOT invoke this tool (sound similar, route elsewhere):
|
|
6825
|
+
- "Is the email enrichment finished?"
|
|
6826
|
+
- "Is my CSV import done?"
|
|
6827
|
+
|
|
6828
|
+
## RENDER (quick)
|
|
6829
|
+
|
|
6830
|
+
Terminal job -> render the full delivery per the lead-delivery table +
|
|
6831
|
+
honest funnel line. Still running -> one progress line (examined /
|
|
6832
|
+
delivered / spent so far) and offer to check again in ~1 min. Never
|
|
6833
|
+
render UUIDs or cursors.
|
|
6834
|
+
|
|
6835
|
+
---
|
|
6836
|
+
|
|
6837
|
+
Cumulative snapshot of a lead-delivery job: state, funnel counters, every
|
|
6838
|
+
item emitted so far (full lead payloads for delivered/degraded, honest
|
|
6839
|
+
status_reason for skipped), spend + breakdown, and the \`explain\` block
|
|
6840
|
+
(basis, seed strategy, scope notes). Items are immutable once emitted \u2014
|
|
6841
|
+
polling never re-reads live data, so numbers only ever grow.
|
|
6842
|
+
|
|
6843
|
+
\`wait_seconds: 0\` (default) answers instantly; set ~60 to block-wait for
|
|
6844
|
+
completion when the user asked for results "in this reply". \`since\` (from a
|
|
6845
|
+
prior poll's \`next_since\`) pages only the new items. Jobs terminalize
|
|
6846
|
+
server-side: past the 30-min wall clock a job reads \`completed_partial\`
|
|
6847
|
+
(time budget), past 30 days \`expired\` (items no longer listed \u2014 re-read
|
|
6848
|
+
billed leads via leadbay_qualify_leads \`prior_deliveries\`). A 404 means
|
|
6849
|
+
unknown job or another org's job.
|
|
6850
|
+
|
|
6851
|
+
---
|
|
6852
|
+
|
|
6853
|
+
## RENDERING \u2014 delivery table + honest funnel line
|
|
6854
|
+
|
|
6855
|
+
Render delivered leads (\`leads[]\`, i.e. items with status \`delivered\` or
|
|
6856
|
+
\`degraded\`) as a markdown table **in the order returned**. Exactly three
|
|
6857
|
+
columns. Then ALWAYS close with the funnel line (below) \u2014 even, especially,
|
|
6858
|
+
when nothing was delivered.
|
|
6859
|
+
|
|
6860
|
+
**Column 1 \u2014 Company**
|
|
6861
|
+
|
|
6862
|
+
- Line 1: 10-segment fit bar in inline-code backticks from \`lead.fit.score\`
|
|
6863
|
+
(0-100): \`filled = round(score/10)\`, glyphs \`\u25B0\` filled / \`\u25B1\` empty. When
|
|
6864
|
+
\`lead.fit.components.qualification.available\` is true AND \`ai_score > 0\`,
|
|
6865
|
+
replace the LAST filled segment with \`\u2756\` (AI-confirmed cap). When
|
|
6866
|
+
\`fit.available\` is false, render \`\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\` and say "unscored" in col 2.
|
|
6867
|
+
Never print the numeric score.
|
|
6868
|
+
- Insert \`<br>\`, then: linked company name (target \`company.website\`, bare
|
|
6869
|
+
hostnames get \`https://\`; unlinked plain text when absent) + \` \xB7 \` + short
|
|
6870
|
+
location (City, ST / City, Country) + \` \xB7 \` + employees as \`min\u2013max\` (omit
|
|
6871
|
+
when \`employees.known\` is false).
|
|
6872
|
+
|
|
6873
|
+
**Column 2 \u2014 Why it fits**
|
|
6874
|
+
|
|
6875
|
+
- One sentence \u2264 20 words. Priority: \`fit.reasoning\` \u2192 gist of
|
|
6876
|
+
\`company.description\` \u2192 top \`fit.components.qualification.matched_tags\`.
|
|
6877
|
+
- If the item status is \`degraded\` or a requested channel failed, append the
|
|
6878
|
+
honest flag in italics, e.g. *(email could not be sourced)*.
|
|
6879
|
+
|
|
6880
|
+
**Column 3 \u2014 Contact**
|
|
6881
|
+
|
|
6882
|
+
- \`[Name](linkedin) \xB7 role\` (linked name mandatory when a LinkedIn URL
|
|
6883
|
+
exists; plain name otherwise). Below it, the PURCHASED channels only:
|
|
6884
|
+
\`\u2709 value\` / \`\u260E value\` inline as plain text (they auto-linkify).
|
|
6885
|
+
- Channel statuses: \`delivered\` \u2192 show value; \`already_owned\` \u2192 value +
|
|
6886
|
+
*(already yours)*; \`masked\` \u2192 "on file \u2014 reveal via channels";
|
|
6887
|
+
\`not_requested\` \u2192 omit; \`failed_*\` \u2192 *(no verified email/phone)*.
|
|
6888
|
+
- No contact on the item (\`contact\` null): render \`\u2014\` (title_gate \`prefer\`
|
|
6889
|
+
delivers such rows flagged; say so in col 2 only when contact_titles were
|
|
6890
|
+
requested).
|
|
6891
|
+
|
|
6892
|
+
**The funnel line (mandatory, after the table):**
|
|
6893
|
+
|
|
6894
|
+
One short line narrating the delivery honestly, from \`funnel\` + \`cost\` +
|
|
6895
|
+
\`explain.scope_notes\`:
|
|
6896
|
+
|
|
6897
|
+
> Matched N \xB7 examined E \xB7 qualified Q \xB7 disqualified D \u2192 **delivered X of
|
|
6898
|
+
> the Y asked** \xB7 stopped: <stop_reason in plain words> \xB7 spent C.CC.
|
|
6899
|
+
|
|
6900
|
+
**Money: divide, then symbol.** Every amount (\`cost.spent\`,
|
|
6901
|
+
\`estimated_cost.max\`, quotes) is \`cost_cents\` \u2014 divide by 100, two decimals,
|
|
6902
|
+
so \`165\` renders \`1.65\`, NEVER \`165.00\`. Symbol from the account region: US
|
|
6903
|
+
\`$\`, France \`\u20AC\`, unknown \u2192 bare. Never hard-code \`$\`: it misstates a charge.
|
|
6904
|
+
|
|
6905
|
+
"of the Y asked" needs \`summary.items_requested\`, which submits carry but a
|
|
6906
|
+
later \`leadbay_lead_job_status\` snapshot does not. Without it write **delivered
|
|
6907
|
+
X** and stop \u2014 never back-fill Y from \`matched\`/\`examined\` (they count
|
|
6908
|
+
candidates), never guess it.
|
|
6909
|
+
|
|
6910
|
+
Plain-word stop reasons: \`target_reached\` \u2192 omit (success), \`pool_exhausted\` \u2192
|
|
6911
|
+
"ran out of matching candidates", \`max_cost\` \u2192 "hit the cost cap", \`quota\` \u2192
|
|
6912
|
+
"hit an org quota", \`time_budget\` \u2192 "hit the 30-min time budget".
|
|
6913
|
+
|
|
6914
|
+
**When \`delivered\` is 0**: NEVER say just "no results". Render no table; give
|
|
6915
|
+
the funnel line plus the relevant \`explain.scope_notes\` (the backend's own
|
|
6916
|
+
diagnosis), then propose the concrete fix (reshape the seed per the craft
|
|
6917
|
+
rules, lower \`min_ai_score\`, raise \`max_cost\`, drop a filter) as NEXT STEPS.
|
|
6918
|
+
|
|
6919
|
+
**Weak batch**: when the BEST delivered \`fit.score\` is under 30, don't present
|
|
6920
|
+
the table as an answer \u2014 open with "weak matches only", show at most the top 3,
|
|
6921
|
+
propose reshaping the seed/filters first. The count was filled with
|
|
6922
|
+
barely-better-than-random candidates.
|
|
6923
|
+
|
|
6924
|
+
**Sanity-check every row**: (a) geo \u2014 \`city\`/\`region\` must sit inside any
|
|
6925
|
+
requested fence; drop and call out leaks (same-named cities slip through).
|
|
6926
|
+
(b) When \`explain.seed_strategy\` is \`text_match_exemplars\` (the standard FR
|
|
6927
|
+
path), fit is calibrated for lead-to-lead distances, not exemplar centroids \u2014
|
|
6928
|
+
treat high scores skeptically and verify each row's \`description\`.
|
|
6929
|
+
|
|
6930
|
+
**Skipped items** (\`skipped[]\`, qualify jobs mostly): render a compact second
|
|
6931
|
+
table \`Ref \u2192 Outcome\` translating \`status_reason\` to plain words:
|
|
6932
|
+
\`not_in_universe\` \u2192 "not in the Leadbay universe (import it first)",
|
|
6933
|
+
\`low_confidence_identity\` \u2192 "couldn't safely match \u2014 check \`resolution.alternatives\`",
|
|
6934
|
+
\`no_matching_contact\` \u2192 "no contact with the requested title",
|
|
6935
|
+
\`disqualified\` \u2192 "evaluated: does not fit" (evidence is in the item when owned),
|
|
6936
|
+
\`enrichment_failed\` \u2192 "channel could not be sourced (not billed)".
|
|
6937
|
+
|
|
6938
|
+
**\`items_truncated\`**: rows are a PREFIX, not the batch. Say so, and offer
|
|
6939
|
+
\`leadbay_lead_job_status(job_id, since: next_since)\` for the rest.
|
|
6940
|
+
|
|
6941
|
+
**Hide from the user:** UUIDs (keep for tool calls, never render), cursors,
|
|
6942
|
+
\`explain.model\`/\`intelligence_snapshot\`, raw \`distance\`/\`calibration\`,
|
|
6943
|
+
\`seq\`/\`from_cache\`, empty arrays.
|
|
6944
|
+
|
|
6945
|
+
## Linking a contact's name
|
|
6946
|
+
|
|
6947
|
+
**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.**
|
|
6948
|
+
|
|
6949
|
+
URL priority (first applicable wins):
|
|
6950
|
+
|
|
6951
|
+
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).
|
|
6952
|
+
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.
|
|
6953
|
+
|
|
6954
|
+
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.
|
|
6955
|
+
|
|
6956
|
+
|
|
6957
|
+
|
|
6958
|
+
**Delivered \u2260 endorsed.** This tool DELIVERS org-owned companies that FAILED
|
|
6959
|
+
qualification, carrying their negative evidence \u2014 so a delivered item is not
|
|
6960
|
+
automatically a prospect. An item whose \`status_reason\` is \`disqualified\`, or
|
|
6961
|
+
whose \`fit.components.qualification\` is available with a negative \`ai_score\`,
|
|
6962
|
+
must NOT go in the fit table: its firmographic score can still be high, and a
|
|
6963
|
+
full bar beside "why it fits" reads as a recommendation to call an account the
|
|
6964
|
+
evaluation just rejected.
|
|
6965
|
+
|
|
6966
|
+
Give those their own short section after the fit table, titled
|
|
6967
|
+
**Evaluated \u2014 does not fit**: linked company, then the verdict in plain
|
|
6968
|
+
words from the
|
|
6969
|
+
qualification evidence (failed question verdicts, missed tags, IBP reasoning).
|
|
6970
|
+
That is the deliverable \u2014 "here's why to skip this account" \u2014 not a defect to
|
|
6971
|
+
hide.
|
|
6972
|
+
|
|
6973
|
+
|
|
6974
|
+
---
|
|
6975
|
+
|
|
6976
|
+
## NEXT STEPS \u2014 after a job status poll
|
|
6977
|
+
|
|
6978
|
+
**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.
|
|
6979
|
+
|
|
6980
|
+
**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.
|
|
6981
|
+
|
|
6982
|
+
**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.
|
|
6983
|
+
- Skip example: "Show me today's leads and then research the top one for me." \u2192 after research completes, emit STOP without the widget.
|
|
6984
|
+
- 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.
|
|
6985
|
+
|
|
6986
|
+
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):
|
|
6987
|
+
- \`ask_user_input_v0\`: \`{questions:[{question,type:"single_select",options:["<Suggest 1>","<Suggest 2>"]}]}\`
|
|
6988
|
+
- \`AskUserQuestion\`: \`{questions:[{question,header:"Next step",multiSelect:false,options:[{label:"<\u22645 words>",description:"<Suggest 1>"}]}]}\`
|
|
6989
|
+
|
|
6990
|
+
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.
|
|
6991
|
+
|
|
6992
|
+
---
|
|
6993
|
+
|
|
6994
|
+
|
|
6995
|
+
|
|
6996
|
+
Pick the ONE row matching the job's state and offer at most two options \u2014 this
|
|
6997
|
+
is a status tool, keep it terse:
|
|
6998
|
+
|
|
6999
|
+
| Observation | Suggest | Calls |
|
|
7000
|
+
|---|---|---|
|
|
7001
|
+
| Still running | "Keep waiting (~1 min) or leave it \u2014 results are kept 30 days" | leadbay_lead_job_status(job_id, wait_seconds: 60) |
|
|
7002
|
+
| Terminal (completed / partial / failed) | Render the delivery per the RENDERING block, then offer the matching find_new_leads / qualify_leads NEXT STEPS | \u2014 |
|
|
7003
|
+
| \`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}) |
|
|
7004
|
+
`;
|
|
6208
7005
|
var leadbay_like_lead = `## WHEN TO USE
|
|
6209
7006
|
|
|
6210
7007
|
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 +7900,7 @@ var leadbay_pull_leads = `## WHEN TO USE
|
|
|
7103
7900
|
|
|
7104
7901
|
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
7902
|
|
|
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\`.
|
|
7903
|
+
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
7904
|
|
|
7108
7905
|
Prefer when: fresh Discover leads; if a lens is named, pass \`lensId\` and pin it
|
|
7109
7906
|
|
|
@@ -7112,6 +7909,7 @@ Examples that SHOULD invoke this tool:
|
|
|
7112
7909
|
- "Pull my best new prospects."
|
|
7113
7910
|
|
|
7114
7911
|
Examples that should NOT invoke this tool (sound similar, route elsewhere):
|
|
7912
|
+
- "Find me 10 gyms around Dallas that would buy our flooring."
|
|
7115
7913
|
- "Which leads should I follow up with this week?"
|
|
7116
7914
|
- "I'm flying to Berlin Thursday \u2014 who should I meet?"
|
|
7117
7915
|
- "I'm in San Francisco next Tuesday \u2014 who's worth meeting?"
|
|
@@ -7141,7 +7939,7 @@ Every lead carries \`recommended_contact\` (with \`linkedin_page\` when the back
|
|
|
7141
7939
|
|
|
7142
7940
|
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
7941
|
|
|
7144
|
-
WHEN NOT TO USE: when the user has named a specific lens \u2014 pass \`lensId\` to override the auto-resolution.
|
|
7942
|
+
WHEN NOT TO USE: when the user has named a specific lens \u2014 pass \`lensId\` to override the auto-resolution.
|
|
7145
7943
|
|
|
7146
7944
|
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
7945
|
|
|
@@ -7291,79 +8089,304 @@ spend before spending it again.
|
|
|
7291
8089
|
|
|
7292
8090
|
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
8091
|
`;
|
|
7294
|
-
var
|
|
8092
|
+
var leadbay_qualify_leads = `## WHEN TO USE
|
|
7295
8093
|
|
|
7296
|
-
|
|
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.
|
|
8094
|
+
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
8095
|
|
|
7299
|
-
|
|
8096
|
+
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
8097
|
|
|
7301
|
-
|
|
8098
|
+
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
8099
|
|
|
7303
|
-
|
|
8100
|
+
Examples that SHOULD invoke this tool:
|
|
8101
|
+
- "Here are 60 restaurant websites from my Austin sweep \u2014 which fit, and who's the owner?"
|
|
8102
|
+
- "Re-qualify last week's delivery and get phone numbers for the good ones."
|
|
8103
|
+
- "Vet these 12 accounts from my spreadsheet against our criteria."
|
|
7304
8104
|
|
|
7305
|
-
|
|
8105
|
+
Examples that should NOT invoke this tool (sound similar, route elsewhere):
|
|
8106
|
+
- "Find me 10 new gyms in Texas."
|
|
8107
|
+
- "Qualify the top 10 leads in my batch."
|
|
8108
|
+
- "I have a CSV of 400 attendees to import."
|
|
7306
8109
|
|
|
7307
|
-
##
|
|
8110
|
+
## RENDER (quick)
|
|
7308
8111
|
|
|
7309
|
-
|
|
7310
|
-
|
|
7311
|
-
|
|
7312
|
-
|
|
7313
|
-
job, and \`cancelled: true\` on an earlier result means we stopped watching, not
|
|
7314
|
-
that the work stopped.
|
|
8112
|
+
3-col table for delivered items (fit bar + company / why-fits \u226420 words /
|
|
8113
|
+
contact + channels) in returned order, then a compact Ref \u2192 Outcome table
|
|
8114
|
+
for skipped refs (not_in_universe, low_confidence_identity, ... in plain
|
|
8115
|
+
words), then the honest funnel + cost line. Full algorithm below.
|
|
7315
8116
|
|
|
7316
|
-
|
|
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.
|
|
8117
|
+
---
|
|
7319
8118
|
|
|
7320
|
-
|
|
7321
|
-
|
|
7322
|
-
|
|
8119
|
+
Submit a qualify batch over companies the org already has (or that exist in
|
|
8120
|
+
the Leadbay universe): each ref is resolved to a known company, freshly
|
|
8121
|
+
researched + AI-qualified against the org's questions / tags / ideal buyer
|
|
8122
|
+
profile (frozen at submit), matched to the requested contact titles, and \u2014
|
|
8123
|
+
when asked \u2014 enriched with verified channels. Answers arrive per-item from a
|
|
8124
|
+
job; this tool polls up to \`wait_seconds\` (default 45) and hands off to
|
|
8125
|
+
\`leadbay_lead_job_status\` when the batch needs longer.
|
|
8126
|
+
|
|
8127
|
+
**Refs are flexible; outcomes are per-item.** \`lead_refs\` accepts any mix of
|
|
8128
|
+
\`lead_id\`, \`website\`, \`name\`(+\`location\`), or a stable \`contact_id\` from a
|
|
8129
|
+
prior result (enrichment then targets exactly that person, never a re-match).
|
|
8130
|
+
\`prior_deliveries\` expands past MCP deliveries into refs \u2014 billed leads stay
|
|
8131
|
+
re-readable this way even after the 30-day result window. Duplicates collapse.
|
|
8132
|
+
A ref that can't be served comes back \`skipped\` with an honest
|
|
8133
|
+
\`status_reason\` (\`not_in_universe\`, \`low_confidence_identity\` with the
|
|
8134
|
+
\`resolution.alternatives\` to choose from, \`no_matching_contact\`, ...) \u2014 that
|
|
8135
|
+
is an ANSWER about the ref, not an error, and it costs nothing.
|
|
8136
|
+
|
|
8137
|
+
**Disqualified \u2260 dropped.** Companies the org owns that fail qualification
|
|
8138
|
+
are DELIVERED with their negative evidence (question verdicts, tag misses,
|
|
8139
|
+
IBP reasoning) \u2014 "here's why to skip this account" is a deliverable.
|
|
8140
|
+
|
|
8141
|
+
**Cost \u2014 never spend silently.** Resolution and identity are free.
|
|
8142
|
+
\`qualify: true\` (the default) costs ~94 cost_cents per lead needing FRESH
|
|
8143
|
+
research+scoring \u2014 but repeat calls reuse every fresh cached stage
|
|
8144
|
+
(\`from_cache\` flags on the items) and converge to near-zero cost. \`channels\`
|
|
8145
|
+
purchase verified email (25c) / phone (250c) on success only;
|
|
8146
|
+
\`already_owned\` values cost nothing.
|
|
8147
|
+
|
|
8148
|
+
The gate is enforced in code, not just here: a PAID call (\`qualify\` left at
|
|
8149
|
+
its default or set true, and/or any \`channels\`) is WITHHELD unless it carries
|
|
8150
|
+
\`confirm: true\`. Without it the tool submits nothing and returns
|
|
8151
|
+
\`mode: "needs_confirmation"\` with a real backend quote \u2014 show that quote to
|
|
8152
|
+
the user, get the go-ahead (an explicit "spend / get their emails" in their
|
|
8153
|
+
message counts), then re-call with \`confirm: true\`. \`confirm: false\` is a
|
|
8154
|
+
veto: nothing is submitted and no quote round-trip is made. A fully FREE
|
|
8155
|
+
call (\`qualify: false\`, no \`channels\`) needs no \`confirm\` and passes straight
|
|
8156
|
+
through. Set \`request_id\` and reuse it on retries of the same batch.
|
|
8157
|
+
|
|
8158
|
+
**Limits**: 500 refs/job, 3 active jobs/org, 10 submits/hour (429 +
|
|
8159
|
+
Retry-After beyond \u2014 wait, don't hammer), 30-min job wall clock.
|
|
7323
8160
|
|
|
7324
|
-
|
|
7325
|
-
a launcher only for a subset that never started, never for the whole batch:
|
|
8161
|
+
---
|
|
7326
8162
|
|
|
7327
|
-
|
|
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.
|
|
8163
|
+
## RENDERING \u2014 delivery table + honest funnel line
|
|
7341
8164
|
|
|
7342
|
-
|
|
8165
|
+
Render delivered leads (\`leads[]\`, i.e. items with status \`delivered\` or
|
|
8166
|
+
\`degraded\`) as a markdown table **in the order returned**. Exactly three
|
|
8167
|
+
columns. Then ALWAYS close with the funnel line (below) \u2014 even, especially,
|
|
8168
|
+
when nothing was delivered.
|
|
7343
8169
|
|
|
7344
|
-
|
|
7345
|
-
`;
|
|
7346
|
-
var leadbay_refine_prompt = `## WHEN TO USE
|
|
8170
|
+
**Column 1 \u2014 Company**
|
|
7347
8171
|
|
|
7348
|
-
|
|
8172
|
+
- Line 1: 10-segment fit bar in inline-code backticks from \`lead.fit.score\`
|
|
8173
|
+
(0-100): \`filled = round(score/10)\`, glyphs \`\u25B0\` filled / \`\u25B1\` empty. When
|
|
8174
|
+
\`lead.fit.components.qualification.available\` is true AND \`ai_score > 0\`,
|
|
8175
|
+
replace the LAST filled segment with \`\u2756\` (AI-confirmed cap). When
|
|
8176
|
+
\`fit.available\` is false, render \`\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\` and say "unscored" in col 2.
|
|
8177
|
+
Never print the numeric score.
|
|
8178
|
+
- Insert \`<br>\`, then: linked company name (target \`company.website\`, bare
|
|
8179
|
+
hostnames get \`https://\`; unlinked plain text when absent) + \` \xB7 \` + short
|
|
8180
|
+
location (City, ST / City, Country) + \` \xB7 \` + employees as \`min\u2013max\` (omit
|
|
8181
|
+
when \`employees.known\` is false).
|
|
7349
8182
|
|
|
7350
|
-
|
|
8183
|
+
**Column 2 \u2014 Why it fits**
|
|
7351
8184
|
|
|
7352
|
-
|
|
8185
|
+
- One sentence \u2264 20 words. Priority: \`fit.reasoning\` \u2192 gist of
|
|
8186
|
+
\`company.description\` \u2192 top \`fit.components.qualification.matched_tags\`.
|
|
8187
|
+
- If the item status is \`degraded\` or a requested channel failed, append the
|
|
8188
|
+
honest flag in italics, e.g. *(email could not be sourced)*.
|
|
7353
8189
|
|
|
7354
|
-
|
|
7355
|
-
- "Focus on hospitals that run their own IT in-house."
|
|
7356
|
-
- "Prioritize companies that have recently expanded headcount."
|
|
8190
|
+
**Column 3 \u2014 Contact**
|
|
7357
8191
|
|
|
7358
|
-
|
|
7359
|
-
|
|
7360
|
-
|
|
7361
|
-
-
|
|
8192
|
+
- \`[Name](linkedin) \xB7 role\` (linked name mandatory when a LinkedIn URL
|
|
8193
|
+
exists; plain name otherwise). Below it, the PURCHASED channels only:
|
|
8194
|
+
\`\u2709 value\` / \`\u260E value\` inline as plain text (they auto-linkify).
|
|
8195
|
+
- Channel statuses: \`delivered\` \u2192 show value; \`already_owned\` \u2192 value +
|
|
8196
|
+
*(already yours)*; \`masked\` \u2192 "on file \u2014 reveal via channels";
|
|
8197
|
+
\`not_requested\` \u2192 omit; \`failed_*\` \u2192 *(no verified email/phone)*.
|
|
8198
|
+
- No contact on the item (\`contact\` null): render \`\u2014\` (title_gate \`prefer\`
|
|
8199
|
+
delivers such rows flagged; say so in col 2 only when contact_titles were
|
|
8200
|
+
requested).
|
|
8201
|
+
|
|
8202
|
+
**The funnel line (mandatory, after the table):**
|
|
8203
|
+
|
|
8204
|
+
One short line narrating the delivery honestly, from \`funnel\` + \`cost\` +
|
|
8205
|
+
\`explain.scope_notes\`:
|
|
8206
|
+
|
|
8207
|
+
> Matched N \xB7 examined E \xB7 qualified Q \xB7 disqualified D \u2192 **delivered X of
|
|
8208
|
+
> the Y asked** \xB7 stopped: <stop_reason in plain words> \xB7 spent C.CC.
|
|
8209
|
+
|
|
8210
|
+
**Money: divide, then symbol.** Every amount (\`cost.spent\`,
|
|
8211
|
+
\`estimated_cost.max\`, quotes) is \`cost_cents\` \u2014 divide by 100, two decimals,
|
|
8212
|
+
so \`165\` renders \`1.65\`, NEVER \`165.00\`. Symbol from the account region: US
|
|
8213
|
+
\`$\`, France \`\u20AC\`, unknown \u2192 bare. Never hard-code \`$\`: it misstates a charge.
|
|
8214
|
+
|
|
8215
|
+
"of the Y asked" needs \`summary.items_requested\`, which submits carry but a
|
|
8216
|
+
later \`leadbay_lead_job_status\` snapshot does not. Without it write **delivered
|
|
8217
|
+
X** and stop \u2014 never back-fill Y from \`matched\`/\`examined\` (they count
|
|
8218
|
+
candidates), never guess it.
|
|
8219
|
+
|
|
8220
|
+
Plain-word stop reasons: \`target_reached\` \u2192 omit (success), \`pool_exhausted\` \u2192
|
|
8221
|
+
"ran out of matching candidates", \`max_cost\` \u2192 "hit the cost cap", \`quota\` \u2192
|
|
8222
|
+
"hit an org quota", \`time_budget\` \u2192 "hit the 30-min time budget".
|
|
8223
|
+
|
|
8224
|
+
**When \`delivered\` is 0**: NEVER say just "no results". Render no table; give
|
|
8225
|
+
the funnel line plus the relevant \`explain.scope_notes\` (the backend's own
|
|
8226
|
+
diagnosis), then propose the concrete fix (reshape the seed per the craft
|
|
8227
|
+
rules, lower \`min_ai_score\`, raise \`max_cost\`, drop a filter) as NEXT STEPS.
|
|
8228
|
+
|
|
8229
|
+
**Weak batch**: when the BEST delivered \`fit.score\` is under 30, don't present
|
|
8230
|
+
the table as an answer \u2014 open with "weak matches only", show at most the top 3,
|
|
8231
|
+
propose reshaping the seed/filters first. The count was filled with
|
|
8232
|
+
barely-better-than-random candidates.
|
|
8233
|
+
|
|
8234
|
+
**Sanity-check every row**: (a) geo \u2014 \`city\`/\`region\` must sit inside any
|
|
8235
|
+
requested fence; drop and call out leaks (same-named cities slip through).
|
|
8236
|
+
(b) When \`explain.seed_strategy\` is \`text_match_exemplars\` (the standard FR
|
|
8237
|
+
path), fit is calibrated for lead-to-lead distances, not exemplar centroids \u2014
|
|
8238
|
+
treat high scores skeptically and verify each row's \`description\`.
|
|
8239
|
+
|
|
8240
|
+
**Skipped items** (\`skipped[]\`, qualify jobs mostly): render a compact second
|
|
8241
|
+
table \`Ref \u2192 Outcome\` translating \`status_reason\` to plain words:
|
|
8242
|
+
\`not_in_universe\` \u2192 "not in the Leadbay universe (import it first)",
|
|
8243
|
+
\`low_confidence_identity\` \u2192 "couldn't safely match \u2014 check \`resolution.alternatives\`",
|
|
8244
|
+
\`no_matching_contact\` \u2192 "no contact with the requested title",
|
|
8245
|
+
\`disqualified\` \u2192 "evaluated: does not fit" (evidence is in the item when owned),
|
|
8246
|
+
\`enrichment_failed\` \u2192 "channel could not be sourced (not billed)".
|
|
8247
|
+
|
|
8248
|
+
**\`items_truncated\`**: rows are a PREFIX, not the batch. Say so, and offer
|
|
8249
|
+
\`leadbay_lead_job_status(job_id, since: next_since)\` for the rest.
|
|
8250
|
+
|
|
8251
|
+
**Hide from the user:** UUIDs (keep for tool calls, never render), cursors,
|
|
8252
|
+
\`explain.model\`/\`intelligence_snapshot\`, raw \`distance\`/\`calibration\`,
|
|
8253
|
+
\`seq\`/\`from_cache\`, empty arrays.
|
|
7362
8254
|
|
|
7363
|
-
##
|
|
8255
|
+
## Linking a contact's name
|
|
7364
8256
|
|
|
7365
|
-
|
|
7366
|
-
|
|
8257
|
+
**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.**
|
|
8258
|
+
|
|
8259
|
+
URL priority (first applicable wins):
|
|
8260
|
+
|
|
8261
|
+
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).
|
|
8262
|
+
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.
|
|
8263
|
+
|
|
8264
|
+
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.
|
|
8265
|
+
|
|
8266
|
+
|
|
8267
|
+
|
|
8268
|
+
**Delivered \u2260 endorsed.** This tool DELIVERS org-owned companies that FAILED
|
|
8269
|
+
qualification, carrying their negative evidence \u2014 so a delivered item is not
|
|
8270
|
+
automatically a prospect. An item whose \`status_reason\` is \`disqualified\`, or
|
|
8271
|
+
whose \`fit.components.qualification\` is available with a negative \`ai_score\`,
|
|
8272
|
+
must NOT go in the fit table: its firmographic score can still be high, and a
|
|
8273
|
+
full bar beside "why it fits" reads as a recommendation to call an account the
|
|
8274
|
+
evaluation just rejected.
|
|
8275
|
+
|
|
8276
|
+
Give those their own short section after the fit table, titled
|
|
8277
|
+
**Evaluated \u2014 does not fit**: linked company, then the verdict in plain
|
|
8278
|
+
words from the
|
|
8279
|
+
qualification evidence (failed question verdicts, missed tags, IBP reasoning).
|
|
8280
|
+
That is the deliverable \u2014 "here's why to skip this account" \u2014 not a defect to
|
|
8281
|
+
hide.
|
|
8282
|
+
|
|
8283
|
+
|
|
8284
|
+
---
|
|
8285
|
+
|
|
8286
|
+
## NEXT STEPS \u2014 after a qualify_leads delivery
|
|
8287
|
+
|
|
8288
|
+
**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.
|
|
8289
|
+
|
|
8290
|
+
**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.
|
|
8291
|
+
|
|
8292
|
+
**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.
|
|
8293
|
+
- Skip example: "Show me today's leads and then research the top one for me." \u2192 after research completes, emit STOP without the widget.
|
|
8294
|
+
- 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.
|
|
8295
|
+
|
|
8296
|
+
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):
|
|
8297
|
+
- \`ask_user_input_v0\`: \`{questions:[{question,type:"single_select",options:["<Suggest 1>","<Suggest 2>"]}]}\`
|
|
8298
|
+
- \`AskUserQuestion\`: \`{questions:[{question,header:"Next step",multiSelect:false,options:[{label:"<\u22645 words>",description:"<Suggest 1>"}]}]}\`
|
|
8299
|
+
|
|
8300
|
+
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.
|
|
8301
|
+
|
|
8302
|
+
---
|
|
8303
|
+
|
|
8304
|
+
|
|
8305
|
+
|
|
8306
|
+
Pick the 2-3 options that match what actually happened:
|
|
8307
|
+
|
|
8308
|
+
| Observation | Suggest | Calls |
|
|
8309
|
+
|---|---|---|
|
|
8310
|
+
| Job still running | "Check on it in ~1 min" | leadbay_lead_job_status(job_id, wait_seconds: 60) |
|
|
8311
|
+
| Fit leads with contacts delivered | "Draft outreach for the qualified ones" | leadbay_prepare_outreach |
|
|
8312
|
+
| Items skipped \`not_in_universe\` | "Import those companies first, then re-qualify" | leadbay_import_leads \u2192 leadbay_qualify_leads |
|
|
8313
|
+
| Items skipped \`low_confidence_identity\` | "Pick the right match" (show \`resolution.alternatives\`) | leadbay_qualify_leads with the chosen lead_id |
|
|
8314
|
+
| Contacts delivered without channels | "Purchase verified emails/phones for the keepers (state cost first)" | leadbay_qualify_leads(lead_refs with contact_id, channels) |
|
|
8315
|
+
| Disqualified with evidence | "Review why \u2014 adjust qualification questions if the criteria are off" | leadbay_get_qualification_questions |
|
|
8316
|
+
`;
|
|
8317
|
+
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:
|
|
8318
|
+
|
|
8319
|
+
- **\`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).
|
|
8320
|
+
- **\`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.
|
|
8321
|
+
|
|
8322
|
+
**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.
|
|
8323
|
+
|
|
8324
|
+
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.
|
|
8325
|
+
|
|
8326
|
+
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.
|
|
8327
|
+
|
|
8328
|
+
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.
|
|
8329
|
+
|
|
8330
|
+
## A launched job cannot be stopped
|
|
8331
|
+
|
|
8332
|
+
Leadbay has no cancel. A job started by \`leadbay_enrich_titles\`,
|
|
8333
|
+
\`leadbay_bulk_qualify_leads\`, \`leadbay_import_leads\` or
|
|
8334
|
+
\`leadbay_import_and_qualify\` runs to completion on Leadbay. The user cancelling
|
|
8335
|
+
in the chat, a request timeout, or a closed stream stops YOUR waiting, never the
|
|
8336
|
+
job, and \`cancelled: true\` on an earlier result means we stopped watching, not
|
|
8337
|
+
that the work stopped.
|
|
8338
|
+
|
|
8339
|
+
**This tool only reads.** Calling it again launches nothing and spends no quota,
|
|
8340
|
+
so poll it as often as the job needs \u2014 a timeout here is a reason to call it
|
|
8341
|
+
again, not a reason to stop.
|
|
8342
|
+
|
|
8343
|
+
One import state does NOT progress: a chunk cancelled before its mappings were
|
|
8344
|
+
committed reads \`running\` / \`committing\` forever. If the counts hold flat across
|
|
8345
|
+
several spaced polls, say so and stop, rather than polling on.
|
|
8346
|
+
|
|
8347
|
+
What must not be repeated is the LAUNCH \u2014 for work that actually launched. Re-run
|
|
8348
|
+
a launcher only for a subset that never started, never for the whole batch:
|
|
8349
|
+
|
|
8350
|
+
- \`failed[]\` entries with \`error:"not_queued"\`;
|
|
8351
|
+
- a \`rows_pending_upload\` count;
|
|
8352
|
+
- leads in \`still_running\` after a CANCELLED \`leadbay_import_and_qualify\`. Its
|
|
8353
|
+
fan-out is sequential, so an interruption leaves the remainder unlaunched and
|
|
8354
|
+
folds them in with the ones that did launch. Nothing in the result tells the
|
|
8355
|
+
two apart, and this tool cannot start either. Wait until the REST of the batch
|
|
8356
|
+
has settled: what launched settles in order, so leads still unanswered after
|
|
8357
|
+
that are the ones that never started. Only then call
|
|
8358
|
+
\`leadbay_bulk_qualify_leads({leadIds, lensId})\` for exactly those ids. A lead
|
|
8359
|
+
that is merely slow looks identical to one that never launched over a few
|
|
8360
|
+
polls, and re-launching it charges the user twice \u2014 when unsure, tell the user
|
|
8361
|
+
rather than guess.
|
|
8362
|
+
`;
|
|
8363
|
+
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.
|
|
8364
|
+
|
|
8365
|
+
WHEN TO USE: before leadbay_enrich_titles, to plan which titles to order.
|
|
8366
|
+
|
|
8367
|
+
WHEN NOT TO USE: when you already know the exact titles you want to enrich.
|
|
8368
|
+
`;
|
|
8369
|
+
var leadbay_refine_prompt = `## WHEN TO USE
|
|
8370
|
+
|
|
8371
|
+
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".
|
|
8372
|
+
|
|
8373
|
+
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\`.
|
|
8374
|
+
|
|
8375
|
+
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.
|
|
8376
|
+
|
|
8377
|
+
Examples that SHOULD invoke this tool:
|
|
8378
|
+
- "Focus on hospitals that run their own IT in-house."
|
|
8379
|
+
- "Prioritize companies that have recently expanded headcount."
|
|
8380
|
+
|
|
8381
|
+
Examples that should NOT invoke this tool (sound similar, route elsewhere):
|
|
8382
|
+
- "Create a lens specialized in automobile."
|
|
8383
|
+
- "Add fintech to my Joinery lens."
|
|
8384
|
+
- "Show me my lenses."
|
|
8385
|
+
|
|
8386
|
+
## RENDER (quick)
|
|
8387
|
+
|
|
8388
|
+
On success: confirm the refinement applied to the active lens. If a
|
|
8389
|
+
clarification was raised, surface its question (route via ask_user_input_v0).
|
|
7367
8390
|
|
|
7368
8391
|
---
|
|
7369
8392
|
|
|
@@ -9019,6 +10042,255 @@ Keep it secondary \u2014 the three window gauges are the headline. Omit when nul
|
|
|
9019
10042
|
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
10043
|
|
|
9021
10044
|
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.
|
|
10045
|
+
`,
|
|
10046
|
+
leadbay_find_new_leads: `## WHEN TO USE
|
|
10047
|
+
|
|
10048
|
+
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".
|
|
10049
|
+
|
|
10050
|
+
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\`.
|
|
10051
|
+
|
|
10052
|
+
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.
|
|
10053
|
+
|
|
10054
|
+
Examples that SHOULD invoke this tool:
|
|
10055
|
+
- "Find me 10 gyms around Dallas that would buy our flooring, with someone I can call."
|
|
10056
|
+
- "Get me 20 new US SaaS companies, 50-2000 employees, with the VP People's email."
|
|
10057
|
+
- "We're launching in Lyon \u2014 find 15 hotels that fit our ICP."
|
|
10058
|
+
|
|
10059
|
+
Examples that should NOT invoke this tool (sound similar, route elsewhere):
|
|
10060
|
+
- "Show me today's leads."
|
|
10061
|
+
- "Which leads should I follow up with this week?"
|
|
10062
|
+
- "Qualify these 40 websites from my spreadsheet."
|
|
10063
|
+
|
|
10064
|
+
## RENDER (quick)
|
|
10065
|
+
|
|
10066
|
+
3-col table of delivered leads in returned order: col 1 = 10-segment fit
|
|
10067
|
+
bar + linked company \xB7 location \xB7 size; col 2 = why-fits \u226420 words; col 3
|
|
10068
|
+
= contact + purchased channels. ALWAYS close with the honest funnel line
|
|
10069
|
+
(matched/examined/delivered/stop reason/spend) \u2014 especially on 0
|
|
10070
|
+
delivered. Full algorithm below.
|
|
10071
|
+
|
|
10072
|
+
---
|
|
10073
|
+
|
|
10074
|
+
Submit a net-new lead search: the backend matches an ICP seed against the full
|
|
10075
|
+
company universe, applies hard filters, skips what the org already knows
|
|
10076
|
+
(\`novelty: org\`), optionally qualifies against the org's own intelligence
|
|
10077
|
+
(questions, tags, ideal buyer profile \u2014 frozen at submit), and optionally buys
|
|
10078
|
+
contact channels. Polls up to \`wait_seconds\` (default 45); a longer job returns
|
|
10079
|
+
\`still_running\` + \`next_poll\` \u2014 hand off to \`leadbay_lead_job_status\`. Jobs run
|
|
10080
|
+
\u226430 min, results kept 30 days.
|
|
10081
|
+
|
|
10082
|
+
**Free vs paid \u2014 never spend silently.** Default (\`qualify: false\`,
|
|
10083
|
+
\`channels: []\`) is FREE: company profile + fit score + cached research +
|
|
10084
|
+
contact identity. Paid: \`qualify: true\` (~94 cost_cents per candidate
|
|
10085
|
+
EXAMINED, capped by \`exploration_cap\`/\`max_cost\`) and \`channels\` (email 25c /
|
|
10086
|
+
phone 250c, success-only). Enforced in code: a paid call is WITHHELD unless it
|
|
10087
|
+
carries \`confirm: true\` \u2014 nothing is submitted and you get
|
|
10088
|
+
\`mode: "needs_confirmation"\` with a real quote to show the user. Re-call with
|
|
10089
|
+
\`confirm: true\` on their go-ahead ("spend / get their emails" counts).
|
|
10090
|
+
\`confirm: false\` vetoes. Free needs no consent. **Preview free first** \u2014
|
|
10091
|
+
reshaping an off-profile seed is free, exploring it with \`qualify: true\` is
|
|
10092
|
+
not.
|
|
10093
|
+
|
|
10094
|
+
**Ad-hoc exclusions ("no chains") are enforced by NO tier** \u2014 \`filters\` has no
|
|
10095
|
+
exclusion key, and \`qualify\` scores against the org's FROZEN questions and IBP,
|
|
10096
|
+
which need not mention chains; the seed's inverse only shifts ranking.
|
|
10097
|
+
Violators can survive, be paid for and be delivered \u2014 post-filter them yourself
|
|
10098
|
+
and say the tier didn't enforce it. Durable enforcement \u2192
|
|
10099
|
+
\`leadbay_refine_prompt\`.
|
|
10100
|
+
|
|
10101
|
+
### Crafting the \`example_lead\` seed \u2014 the input that decides result quality
|
|
10102
|
+
|
|
10103
|
+
The \`example_lead\` is a FICTIONAL typical ideal customer, matched against real
|
|
10104
|
+
registry/website descriptions \u2014 which state what a company **IS**, never what
|
|
10105
|
+
is happening. Write it the same way or the matcher drifts. Every rule below is
|
|
10106
|
+
measured:
|
|
10107
|
+
|
|
10108
|
+
1. **Describe the BUYER, never the seller.** Ask: "would this company write a
|
|
10109
|
+
check to my user?" A seed describing what the user SELLS surfaces their
|
|
10110
|
+
*competitors and vendors*. If the product helps companies of type X serve
|
|
10111
|
+
customers of type Y, the seed describes X \u2014 never Y.
|
|
10112
|
+
2. **Put everything in \`description\`; leave \`name\` unset.** An invented brand
|
|
10113
|
+
name pulls matching toward name-lookalikes \u2014 a seed named "Meridian
|
|
10114
|
+
Analytics" returned five unrelated "Meridian" companies.
|
|
10115
|
+
3. **Registry style, one sentence to ~250 chars.** Industry niche, business
|
|
10116
|
+
model, what they sell or operate, who they serve, observable scale. Write
|
|
10117
|
+
it like the first paragraph of their About-Us page.
|
|
10118
|
+
- STRONG: "Operator of full-service fitness centers offering strength
|
|
10119
|
+
areas, group classes and personal training to members across multiple
|
|
10120
|
+
clubs."
|
|
10121
|
+
- WEAK (generic): "A gym in Texas."
|
|
10122
|
+
- WRONG (seller-side): "Supplier of durable modular flooring for gyms."
|
|
10123
|
+
4. **No event language.** "hiring", "expanding", "just raised" are not
|
|
10124
|
+
filters \u2014 registry descriptions never contain them, so they dilute the
|
|
10125
|
+
profile. Purchase triggers belong in the org's qualification questions.
|
|
10126
|
+
5. **No meta-markers.** Never "(example)", "(fictional)", "(placeholder)".
|
|
10127
|
+
6. **Hard constraints go in \`filters\`, not prose \u2014 exact keys:**
|
|
10128
|
+
\`sectors: string[]\`, \`locations: string[]\`, \`employees_min: number\`,
|
|
10129
|
+
\`employees_max: number\`. FLAT numbers \u2014 nested \`employees: {min, max}\`
|
|
10130
|
+
exists only in RESULT payloads. \`example_lead.employees\` does not filter.
|
|
10131
|
+
\`locations\` take city/state/region names ("Dallas, TX", "\xCEle-de-France");
|
|
10132
|
+
a country name is refused in code \u2014 whole-country intent = omit it.
|
|
10133
|
+
7. **Prefer \`example_lead\` over \`query\`.** Query matches topic *vocabulary*:
|
|
10134
|
+
"gyms that need durable flooring" surfaced flooring VENDORS, 0 delivered.
|
|
10135
|
+
Use \`query\` only for signal an example can't express.
|
|
10136
|
+
8. **One seed per buyer archetype.** An ask spanning two segments ("gyms and
|
|
10137
|
+
warehouses") needs one search each with its own description and
|
|
10138
|
+
\`request_id\` \u2014 a blended seed lands between the clusters and matches
|
|
10139
|
+
neither.
|
|
10140
|
+
|
|
10141
|
+
|
|
10142
|
+
**Parameter notes**
|
|
10143
|
+
- \`request_id\` (REQUIRED) is the retry contract: SAME value retrying the same
|
|
10144
|
+
ask (same live job, no double spend); NEW for a changed ask. Derive from ask
|
|
10145
|
+
+ archetype + date: \`gyms-dallas-2026-07-28\`.
|
|
10146
|
+
- Never lower \`min_ai_score\` together with \`channels\` \u2014 that buys emails for
|
|
10147
|
+
leads the AI just scored as junk.
|
|
10148
|
+
- \`count\` \u2264 50; \u22643 active jobs/org; \u226410 submits/hour (429 + Retry-After \u2014
|
|
10149
|
+
wait, don't hammer).
|
|
10150
|
+
|
|
10151
|
+
**Read the result honestly** \u2014 \`funnel\` + \`explain.scope_notes\` tell the story;
|
|
10152
|
+
zero delivered gets a cause and a next move (rules in RENDERING).
|
|
10153
|
+
|
|
10154
|
+
---
|
|
10155
|
+
|
|
10156
|
+
## RENDERING \u2014 delivery table + honest funnel line
|
|
10157
|
+
|
|
10158
|
+
Render delivered leads (\`leads[]\`, i.e. items with status \`delivered\` or
|
|
10159
|
+
\`degraded\`) as a markdown table **in the order returned**. Exactly three
|
|
10160
|
+
columns. Then ALWAYS close with the funnel line (below) \u2014 even, especially,
|
|
10161
|
+
when nothing was delivered.
|
|
10162
|
+
|
|
10163
|
+
**Column 1 \u2014 Company**
|
|
10164
|
+
|
|
10165
|
+
- Line 1: 10-segment fit bar in inline-code backticks from \`lead.fit.score\`
|
|
10166
|
+
(0-100): \`filled = round(score/10)\`, glyphs \`\u25B0\` filled / \`\u25B1\` empty. When
|
|
10167
|
+
\`lead.fit.components.qualification.available\` is true AND \`ai_score > 0\`,
|
|
10168
|
+
replace the LAST filled segment with \`\u2756\` (AI-confirmed cap). When
|
|
10169
|
+
\`fit.available\` is false, render \`\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\` and say "unscored" in col 2.
|
|
10170
|
+
Never print the numeric score.
|
|
10171
|
+
- Insert \`<br>\`, then: linked company name (target \`company.website\`, bare
|
|
10172
|
+
hostnames get \`https://\`; unlinked plain text when absent) + \` \xB7 \` + short
|
|
10173
|
+
location (City, ST / City, Country) + \` \xB7 \` + employees as \`min\u2013max\` (omit
|
|
10174
|
+
when \`employees.known\` is false).
|
|
10175
|
+
|
|
10176
|
+
**Column 2 \u2014 Why it fits**
|
|
10177
|
+
|
|
10178
|
+
- One sentence \u2264 20 words. Priority: \`fit.reasoning\` \u2192 gist of
|
|
10179
|
+
\`company.description\` \u2192 top \`fit.components.qualification.matched_tags\`.
|
|
10180
|
+
- If the item status is \`degraded\` or a requested channel failed, append the
|
|
10181
|
+
honest flag in italics, e.g. *(email could not be sourced)*.
|
|
10182
|
+
|
|
10183
|
+
**Column 3 \u2014 Contact**
|
|
10184
|
+
|
|
10185
|
+
- \`[Name](linkedin) \xB7 role\` (linked name mandatory when a LinkedIn URL
|
|
10186
|
+
exists; plain name otherwise). Below it, the PURCHASED channels only:
|
|
10187
|
+
\`\u2709 value\` / \`\u260E value\` inline as plain text (they auto-linkify).
|
|
10188
|
+
- Channel statuses: \`delivered\` \u2192 show value; \`already_owned\` \u2192 value +
|
|
10189
|
+
*(already yours)*; \`masked\` \u2192 "on file \u2014 reveal via channels";
|
|
10190
|
+
\`not_requested\` \u2192 omit; \`failed_*\` \u2192 *(no verified email/phone)*.
|
|
10191
|
+
- No contact on the item (\`contact\` null): render \`\u2014\` (title_gate \`prefer\`
|
|
10192
|
+
delivers such rows flagged; say so in col 2 only when contact_titles were
|
|
10193
|
+
requested).
|
|
10194
|
+
|
|
10195
|
+
**The funnel line (mandatory, after the table):**
|
|
10196
|
+
|
|
10197
|
+
One short line narrating the delivery honestly, from \`funnel\` + \`cost\` +
|
|
10198
|
+
\`explain.scope_notes\`:
|
|
10199
|
+
|
|
10200
|
+
> Matched N \xB7 examined E \xB7 qualified Q \xB7 disqualified D \u2192 **delivered X of
|
|
10201
|
+
> the Y asked** \xB7 stopped: <stop_reason in plain words> \xB7 spent C.CC.
|
|
10202
|
+
|
|
10203
|
+
**Money: divide, then symbol.** Every amount (\`cost.spent\`,
|
|
10204
|
+
\`estimated_cost.max\`, quotes) is \`cost_cents\` \u2014 divide by 100, two decimals,
|
|
10205
|
+
so \`165\` renders \`1.65\`, NEVER \`165.00\`. Symbol from the account region: US
|
|
10206
|
+
\`$\`, France \`\u20AC\`, unknown \u2192 bare. Never hard-code \`$\`: it misstates a charge.
|
|
10207
|
+
|
|
10208
|
+
"of the Y asked" needs \`summary.items_requested\`, which submits carry but a
|
|
10209
|
+
later \`leadbay_lead_job_status\` snapshot does not. Without it write **delivered
|
|
10210
|
+
X** and stop \u2014 never back-fill Y from \`matched\`/\`examined\` (they count
|
|
10211
|
+
candidates), never guess it.
|
|
10212
|
+
|
|
10213
|
+
Plain-word stop reasons: \`target_reached\` \u2192 omit (success), \`pool_exhausted\` \u2192
|
|
10214
|
+
"ran out of matching candidates", \`max_cost\` \u2192 "hit the cost cap", \`quota\` \u2192
|
|
10215
|
+
"hit an org quota", \`time_budget\` \u2192 "hit the 30-min time budget".
|
|
10216
|
+
|
|
10217
|
+
**When \`delivered\` is 0**: NEVER say just "no results". Render no table; give
|
|
10218
|
+
the funnel line plus the relevant \`explain.scope_notes\` (the backend's own
|
|
10219
|
+
diagnosis), then propose the concrete fix (reshape the seed per the craft
|
|
10220
|
+
rules, lower \`min_ai_score\`, raise \`max_cost\`, drop a filter) as NEXT STEPS.
|
|
10221
|
+
|
|
10222
|
+
**Weak batch**: when the BEST delivered \`fit.score\` is under 30, don't present
|
|
10223
|
+
the table as an answer \u2014 open with "weak matches only", show at most the top 3,
|
|
10224
|
+
propose reshaping the seed/filters first. The count was filled with
|
|
10225
|
+
barely-better-than-random candidates.
|
|
10226
|
+
|
|
10227
|
+
**Sanity-check every row**: (a) geo \u2014 \`city\`/\`region\` must sit inside any
|
|
10228
|
+
requested fence; drop and call out leaks (same-named cities slip through).
|
|
10229
|
+
(b) When \`explain.seed_strategy\` is \`text_match_exemplars\` (the standard FR
|
|
10230
|
+
path), fit is calibrated for lead-to-lead distances, not exemplar centroids \u2014
|
|
10231
|
+
treat high scores skeptically and verify each row's \`description\`.
|
|
10232
|
+
|
|
10233
|
+
**Skipped items** (\`skipped[]\`, qualify jobs mostly): render a compact second
|
|
10234
|
+
table \`Ref \u2192 Outcome\` translating \`status_reason\` to plain words:
|
|
10235
|
+
\`not_in_universe\` \u2192 "not in the Leadbay universe (import it first)",
|
|
10236
|
+
\`low_confidence_identity\` \u2192 "couldn't safely match \u2014 check \`resolution.alternatives\`",
|
|
10237
|
+
\`no_matching_contact\` \u2192 "no contact with the requested title",
|
|
10238
|
+
\`disqualified\` \u2192 "evaluated: does not fit" (evidence is in the item when owned),
|
|
10239
|
+
\`enrichment_failed\` \u2192 "channel could not be sourced (not billed)".
|
|
10240
|
+
|
|
10241
|
+
**\`items_truncated\`**: rows are a PREFIX, not the batch. Say so, and offer
|
|
10242
|
+
\`leadbay_lead_job_status(job_id, since: next_since)\` for the rest.
|
|
10243
|
+
|
|
10244
|
+
**Hide from the user:** UUIDs (keep for tool calls, never render), cursors,
|
|
10245
|
+
\`explain.model\`/\`intelligence_snapshot\`, raw \`distance\`/\`calibration\`,
|
|
10246
|
+
\`seq\`/\`from_cache\`, empty arrays.
|
|
10247
|
+
|
|
10248
|
+
## Linking a contact's name
|
|
10249
|
+
|
|
10250
|
+
**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.**
|
|
10251
|
+
|
|
10252
|
+
URL priority (first applicable wins):
|
|
10253
|
+
|
|
10254
|
+
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).
|
|
10255
|
+
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.
|
|
10256
|
+
|
|
10257
|
+
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.
|
|
10258
|
+
|
|
10259
|
+
|
|
10260
|
+
|
|
10261
|
+
---
|
|
10262
|
+
|
|
10263
|
+
## NEXT STEPS \u2014 after a find_new_leads delivery
|
|
10264
|
+
|
|
10265
|
+
**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.
|
|
10266
|
+
|
|
10267
|
+
**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.
|
|
10268
|
+
|
|
10269
|
+
**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.
|
|
10270
|
+
- Skip example: "Show me today's leads and then research the top one for me." \u2192 after research completes, emit STOP without the widget.
|
|
10271
|
+
- 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.
|
|
10272
|
+
|
|
10273
|
+
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):
|
|
10274
|
+
- \`ask_user_input_v0\`: \`{questions:[{question,type:"single_select",options:["<Suggest 1>","<Suggest 2>"]}]}\`
|
|
10275
|
+
- \`AskUserQuestion\`: \`{questions:[{question,header:"Next step",multiSelect:false,options:[{label:"<\u22645 words>",description:"<Suggest 1>"}]}]}\`
|
|
10276
|
+
|
|
10277
|
+
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.
|
|
10278
|
+
|
|
10279
|
+
---
|
|
10280
|
+
|
|
10281
|
+
|
|
10282
|
+
|
|
10283
|
+
Pick the 2-3 options that match what actually happened \u2014 never all seven:
|
|
10284
|
+
|
|
10285
|
+
| Observation | Suggest | Calls |
|
|
10286
|
+
|---|---|---|
|
|
10287
|
+
| Job still running (\`still_running: true\`) | "Check on it in ~1 min" | leadbay_lead_job_status(job_id, wait_seconds: 60) |
|
|
10288
|
+
| Free run delivered on-profile leads | "Qualify these N against your criteria (paid \u2014 \`dry_run\` first)" | leadbay_qualify_leads(prior_deliveries: {job_id}) |
|
|
10289
|
+
| Delivered leads look right | "Draft outreach for the top ones" | leadbay_prepare_outreach |
|
|
10290
|
+
| Delivered 0 or off-profile | "Reshape the example and retry" (name the fix from funnel + scope_notes) | leadbay_find_new_leads (NEW request_id) |
|
|
10291
|
+
| 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) |
|
|
10292
|
+
| 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 |
|
|
10293
|
+
| User wants these tracked in Leadbay | "Add the keepers to a campaign" | leadbay_create_campaign / leadbay_add_leads_to_campaign |
|
|
9022
10294
|
`,
|
|
9023
10295
|
leadbay_scan_portfolio_signals: `## WHEN TO USE
|
|
9024
10296
|
|
|
@@ -15640,12 +16912,12 @@ var CITY_ALIASES = {
|
|
|
15640
16912
|
vegas: "Las Vegas",
|
|
15641
16913
|
nola: "New Orleans"
|
|
15642
16914
|
};
|
|
15643
|
-
function expandAlias(
|
|
15644
|
-
const key =
|
|
15645
|
-
return CITY_ALIASES[key] ??
|
|
16915
|
+
function expandAlias(text2) {
|
|
16916
|
+
const key = text2.trim().toLowerCase();
|
|
16917
|
+
return CITY_ALIASES[key] ?? text2;
|
|
15646
16918
|
}
|
|
15647
|
-
function scoreMatch(
|
|
15648
|
-
const t =
|
|
16919
|
+
function scoreMatch(text2, match) {
|
|
16920
|
+
const t = text2.trim().toLowerCase();
|
|
15649
16921
|
const n = match.name.trim().toLowerCase();
|
|
15650
16922
|
if (n === t)
|
|
15651
16923
|
return 1;
|
|
@@ -15668,8 +16940,8 @@ async function resolveLocations(client, texts) {
|
|
|
15668
16940
|
const resolved = [...direct];
|
|
15669
16941
|
const ambiguities = [];
|
|
15670
16942
|
for (const originalText of free) {
|
|
15671
|
-
const
|
|
15672
|
-
const path = `/geo/search?q=${encodeURIComponent(
|
|
16943
|
+
const text2 = expandAlias(originalText);
|
|
16944
|
+
const path = `/geo/search?q=${encodeURIComponent(text2)}`;
|
|
15673
16945
|
let response;
|
|
15674
16946
|
try {
|
|
15675
16947
|
response = await client.request("GET", path);
|
|
@@ -15708,7 +16980,7 @@ async function resolveLocations(client, texts) {
|
|
|
15708
16980
|
name: r.name,
|
|
15709
16981
|
country: r.country,
|
|
15710
16982
|
level: r.level,
|
|
15711
|
-
score: scoreMatch(
|
|
16983
|
+
score: scoreMatch(text2, r)
|
|
15712
16984
|
})).sort((a, b) => {
|
|
15713
16985
|
if (b.score !== a.score)
|
|
15714
16986
|
return b.score - a.score;
|
|
@@ -16874,9 +18146,9 @@ ${firm.short_description}`);
|
|
|
16874
18146
|
out.push(`### ${sec.section_emoji ?? ""} ${label}`.trim());
|
|
16875
18147
|
const entries = Array.isArray(sec.entries) ? sec.entries : [];
|
|
16876
18148
|
for (const e of entries.slice(0, 5)) {
|
|
16877
|
-
const
|
|
18149
|
+
const text2 = e.text ?? e.summary ?? JSON.stringify(e).slice(0, 200);
|
|
16878
18150
|
const hot = e.hot === true ? " \u{1F525}" : "";
|
|
16879
|
-
out.push(`- ${
|
|
18151
|
+
out.push(`- ${text2}${hot}`);
|
|
16880
18152
|
}
|
|
16881
18153
|
if (entries.length > 5)
|
|
16882
18154
|
out.push(`- _${entries.length - 5} more \u2026_`);
|
|
@@ -21457,8 +22729,8 @@ function tokens(s) {
|
|
|
21457
22729
|
return [];
|
|
21458
22730
|
return s.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean);
|
|
21459
22731
|
}
|
|
21460
|
-
function bestMatches(
|
|
21461
|
-
const want = new Set(tokens(
|
|
22732
|
+
function bestMatches(text2, taxonomy) {
|
|
22733
|
+
const want = new Set(tokens(text2));
|
|
21462
22734
|
if (want.size === 0)
|
|
21463
22735
|
return [];
|
|
21464
22736
|
const ranked = taxonomy.map((s) => {
|
|
@@ -21487,12 +22759,12 @@ async function resolveSectors(client, texts, ctx) {
|
|
|
21487
22759
|
}
|
|
21488
22760
|
const resolved = [...direct];
|
|
21489
22761
|
const ambiguities = [];
|
|
21490
|
-
for (const
|
|
21491
|
-
const matches = bestMatches(
|
|
22762
|
+
for (const text2 of free) {
|
|
22763
|
+
const matches = bestMatches(text2, taxonomy);
|
|
21492
22764
|
if (matches.length === 1 || matches.length >= 2 && matches[0].score >= 0.66 && matches[0].score - matches[1].score >= 0.34) {
|
|
21493
22765
|
resolved.push(matches[0].id);
|
|
21494
22766
|
} else {
|
|
21495
|
-
ambiguities.push({ sector_text:
|
|
22767
|
+
ambiguities.push({ sector_text: text2, matches });
|
|
21496
22768
|
}
|
|
21497
22769
|
}
|
|
21498
22770
|
return { resolved, ambiguities };
|
|
@@ -22157,50 +23429,1266 @@ var seedCandidates = {
|
|
|
22157
23429
|
}
|
|
22158
23430
|
};
|
|
22159
23431
|
|
|
22160
|
-
// ../core/dist/composite/
|
|
22161
|
-
|
|
22162
|
-
|
|
22163
|
-
|
|
22164
|
-
|
|
22165
|
-
|
|
22166
|
-
|
|
22167
|
-
|
|
22168
|
-
|
|
22169
|
-
|
|
22170
|
-
|
|
22171
|
-
|
|
22172
|
-
|
|
23432
|
+
// ../core/dist/composite/_mcp-job-helpers.js
|
|
23433
|
+
import { createHash as createHash4 } from "crypto";
|
|
23434
|
+
var TERMINAL_JOB_STATES = /* @__PURE__ */ new Set([
|
|
23435
|
+
"completed",
|
|
23436
|
+
"completed_partial",
|
|
23437
|
+
"failed",
|
|
23438
|
+
"expired"
|
|
23439
|
+
]);
|
|
23440
|
+
var MCP_JOB_POLL = { intervalMs: 4e3 };
|
|
23441
|
+
var SNAPSHOT_TIMEOUT_MS = 3e4;
|
|
23442
|
+
var PAGE_LIMIT = 100;
|
|
23443
|
+
var MAX_JOB_ITEMS = 1e3;
|
|
23444
|
+
var MIN_PAGES = 20;
|
|
23445
|
+
var maxPagesFor = (pageLimit) => Math.max(MIN_PAGES, Math.ceil(MAX_JOB_ITEMS / pageLimit) + 1);
|
|
23446
|
+
var JOB_ID_CHARSET = /^[A-Za-z0-9._~-]+$/;
|
|
23447
|
+
var MAX_JOB_ID_LENGTH = 200;
|
|
23448
|
+
function assertSafeJobId(jobId) {
|
|
23449
|
+
const reject = (why) => {
|
|
23450
|
+
throw {
|
|
23451
|
+
error: true,
|
|
23452
|
+
code: "INVALID_JOB_ID",
|
|
23453
|
+
message: `job_id ${why}.`,
|
|
23454
|
+
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
23455
|
};
|
|
22174
|
-
}
|
|
22175
|
-
|
|
23456
|
+
};
|
|
23457
|
+
if (typeof jobId !== "string" || jobId.length === 0)
|
|
23458
|
+
return reject("must be a non-empty string");
|
|
23459
|
+
if (jobId.length > MAX_JOB_ID_LENGTH)
|
|
23460
|
+
return reject(`is ${jobId.length} chars \u2014 the maximum is ${MAX_JOB_ID_LENGTH}`);
|
|
23461
|
+
if (/^\.+$/.test(jobId))
|
|
23462
|
+
return reject("cannot be a dot segment");
|
|
23463
|
+
if (!JOB_ID_CHARSET.test(jobId))
|
|
23464
|
+
return reject("contains characters that are not valid in a job handle");
|
|
23465
|
+
return encodeURIComponent(jobId);
|
|
23466
|
+
}
|
|
23467
|
+
async function collectJobSnapshot(client, jobId, since, limit, signal, timeoutMs = SNAPSHOT_TIMEOUT_MS) {
|
|
23468
|
+
if (signal?.aborted)
|
|
23469
|
+
throw cancelledError(jobId);
|
|
23470
|
+
const pageLimit = Math.min(Math.max(limit ?? PAGE_LIMIT, 1), PAGE_LIMIT);
|
|
23471
|
+
const safeJobId = assertSafeJobId(jobId);
|
|
23472
|
+
const qs = (cursor2) => `/mcp/jobs/${safeJobId}?limit=${pageLimit}` + (cursor2 ? `&since=${encodeURIComponent(cursor2)}` : "");
|
|
23473
|
+
const maxPages = maxPagesFor(pageLimit);
|
|
23474
|
+
const deadlineAt = Date.now() + timeoutMs;
|
|
23475
|
+
const remaining = () => deadlineAt - Date.now();
|
|
23476
|
+
let page = await client.request("GET", qs(since), void 0, {
|
|
23477
|
+
signal,
|
|
23478
|
+
// totalTimeoutMs, not timeoutMs: what is left of the wait must cover a 401
|
|
23479
|
+
// backoff and its retry too, or a blip buys the poll a second full budget.
|
|
23480
|
+
totalTimeoutMs: remaining()
|
|
23481
|
+
});
|
|
23482
|
+
const items = [...page.items];
|
|
23483
|
+
let cursor = page.next_since ?? since ?? null;
|
|
23484
|
+
let pages = 1;
|
|
23485
|
+
while (page.items.length >= pageLimit && page.next_since && pages < maxPages && !signal?.aborted) {
|
|
23486
|
+
if (remaining() <= 0)
|
|
23487
|
+
break;
|
|
23488
|
+
let next;
|
|
23489
|
+
try {
|
|
23490
|
+
next = await client.request("GET", qs(page.next_since), void 0, { signal, totalTimeoutMs: remaining() });
|
|
23491
|
+
} catch (e) {
|
|
23492
|
+
if (isTimeout(e))
|
|
23493
|
+
break;
|
|
23494
|
+
throw e;
|
|
23495
|
+
}
|
|
23496
|
+
items.push(...next.items);
|
|
23497
|
+
pages += 1;
|
|
23498
|
+
page = next;
|
|
23499
|
+
if (next.items.length === 0) {
|
|
23500
|
+
break;
|
|
23501
|
+
}
|
|
23502
|
+
cursor = next.next_since ?? cursor;
|
|
22176
23503
|
}
|
|
23504
|
+
const itemsTruncated = page.items.length >= pageLimit && !!page.next_since;
|
|
23505
|
+
return {
|
|
23506
|
+
...page,
|
|
23507
|
+
items,
|
|
23508
|
+
next_since: cursor,
|
|
23509
|
+
...itemsTruncated ? { items_truncated: true } : {}
|
|
23510
|
+
};
|
|
22177
23511
|
}
|
|
22178
|
-
|
|
23512
|
+
function sleepUnlessAborted(ms, signal) {
|
|
23513
|
+
if (signal?.aborted)
|
|
23514
|
+
return Promise.resolve();
|
|
23515
|
+
return new Promise((resolve) => {
|
|
23516
|
+
const done = () => {
|
|
23517
|
+
clearTimeout(timer);
|
|
23518
|
+
signal?.removeEventListener("abort", done);
|
|
23519
|
+
resolve();
|
|
23520
|
+
};
|
|
23521
|
+
const timer = setTimeout(done, ms);
|
|
23522
|
+
signal?.addEventListener("abort", done, { once: true });
|
|
23523
|
+
});
|
|
23524
|
+
}
|
|
23525
|
+
function cancelledError(jobId) {
|
|
23526
|
+
return {
|
|
23527
|
+
error: true,
|
|
23528
|
+
code: "REQUEST_CANCELLED",
|
|
23529
|
+
message: `The wait for job ${jobId} was cancelled before any status was read.`,
|
|
23530
|
+
hint: "The job itself is backend-owned and keeps running. Poll leadbay_lead_job_status when you want its result."
|
|
23531
|
+
};
|
|
23532
|
+
}
|
|
23533
|
+
function snapshotBudget(remainingMs) {
|
|
23534
|
+
return Math.min(SNAPSHOT_TIMEOUT_MS, Math.max(remainingMs, 1));
|
|
23535
|
+
}
|
|
23536
|
+
function isTimeout(e) {
|
|
23537
|
+
return typeof e === "object" && e !== null && e.code === "TIMEOUT";
|
|
23538
|
+
}
|
|
23539
|
+
function jobReadTimedOutError(jobId, waitSeconds) {
|
|
23540
|
+
return {
|
|
23541
|
+
error: true,
|
|
23542
|
+
code: "JOB_READ_TIMEOUT",
|
|
23543
|
+
// Structured, not just interpolated: a caller recovering programmatically
|
|
23544
|
+
// should not have to parse the message to find the handle.
|
|
23545
|
+
job_id: jobId,
|
|
23546
|
+
message: `Job ${jobId} was submitted and is running, but its status could not be read within ${waitSeconds}s.`,
|
|
23547
|
+
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.`
|
|
23548
|
+
};
|
|
23549
|
+
}
|
|
23550
|
+
function jobHandleError(jobId, cause) {
|
|
23551
|
+
const c = cause;
|
|
23552
|
+
if (c?.job_id === jobId)
|
|
23553
|
+
return cause;
|
|
23554
|
+
return {
|
|
23555
|
+
error: true,
|
|
23556
|
+
code: c?.code ?? "JOB_READ_FAILED",
|
|
23557
|
+
job_id: jobId,
|
|
23558
|
+
message: `Job ${jobId} was submitted and is running, but reading its status failed: ${c?.message ?? String(cause)}`,
|
|
23559
|
+
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.`
|
|
23560
|
+
};
|
|
23561
|
+
}
|
|
23562
|
+
async function snapshotAfterSubmit(client, jobId, waitSeconds, ctx, itemsRequested) {
|
|
22179
23563
|
try {
|
|
22180
|
-
|
|
22181
|
-
|
|
22182
|
-
|
|
22183
|
-
return null;
|
|
23564
|
+
return waitSeconds > 0 ? await waitForJob(client, jobId, waitSeconds, ctx, itemsRequested) : await collectJobSnapshot(client, jobId, void 0, void 0, ctx?.signal);
|
|
23565
|
+
} catch (e) {
|
|
23566
|
+
throw jobHandleError(jobId, e);
|
|
22184
23567
|
}
|
|
22185
23568
|
}
|
|
22186
|
-
async function
|
|
23569
|
+
async function waitForJob(client, jobId, waitSeconds, ctx, itemsRequested, since, limit) {
|
|
23570
|
+
const startedAt = Date.now();
|
|
23571
|
+
const remainingMsOf = () => waitSeconds * 1e3 - (Date.now() - startedAt);
|
|
23572
|
+
if (ctx?.signal?.aborted)
|
|
23573
|
+
throw cancelledError(jobId);
|
|
23574
|
+
let snap;
|
|
22187
23575
|
try {
|
|
22188
|
-
|
|
22189
|
-
|
|
22190
|
-
|
|
22191
|
-
|
|
23576
|
+
snap = await collectJobSnapshot(client, jobId, since, limit, ctx?.signal, snapshotBudget(remainingMsOf()));
|
|
23577
|
+
} catch (e) {
|
|
23578
|
+
if (isTimeout(e))
|
|
23579
|
+
throw jobReadTimedOutError(jobId, waitSeconds);
|
|
23580
|
+
throw e;
|
|
23581
|
+
}
|
|
23582
|
+
while (!TERMINAL_JOB_STATES.has(snap.job.state) && (Date.now() - startedAt) / 1e3 < waitSeconds && !ctx?.signal?.aborted) {
|
|
23583
|
+
const remainingMs = waitSeconds * 1e3 - (Date.now() - startedAt);
|
|
23584
|
+
if (remainingMs <= 0)
|
|
23585
|
+
break;
|
|
23586
|
+
await sleepUnlessAborted(Math.min(MCP_JOB_POLL.intervalMs, remainingMs), ctx?.signal);
|
|
23587
|
+
if (ctx?.signal?.aborted)
|
|
23588
|
+
break;
|
|
23589
|
+
if (remainingMsOf() <= 0)
|
|
23590
|
+
break;
|
|
23591
|
+
try {
|
|
23592
|
+
const fresh = await collectJobSnapshot(client, jobId, since, limit, ctx?.signal, snapshotBudget(remainingMsOf()));
|
|
23593
|
+
const regressed = fresh.items.length < snap.items.length;
|
|
23594
|
+
snap = regressed ? {
|
|
23595
|
+
...fresh,
|
|
23596
|
+
items: snap.items,
|
|
23597
|
+
next_since: snap.next_since ?? fresh.next_since,
|
|
23598
|
+
...snap.items_truncated ? { items_truncated: true } : {}
|
|
23599
|
+
} : fresh;
|
|
23600
|
+
} catch (e) {
|
|
23601
|
+
if (ctx?.signal?.aborted)
|
|
23602
|
+
break;
|
|
23603
|
+
if (isTimeout(e))
|
|
23604
|
+
break;
|
|
23605
|
+
throw e;
|
|
23606
|
+
}
|
|
23607
|
+
const f = snap.funnel;
|
|
23608
|
+
ctx?.progress?.({
|
|
23609
|
+
progress: f.delivered ?? 0,
|
|
23610
|
+
total: itemsRequested,
|
|
23611
|
+
message: `${snap.job.state}: ${f.examined ?? 0} examined, ${f.delivered ?? 0} delivered, ${snap.cost.spent}c spent`
|
|
23612
|
+
});
|
|
22192
23613
|
}
|
|
23614
|
+
return snap;
|
|
22193
23615
|
}
|
|
22194
|
-
function
|
|
22195
|
-
|
|
22196
|
-
|
|
22197
|
-
|
|
22198
|
-
|
|
22199
|
-
|
|
22200
|
-
|
|
22201
|
-
|
|
22202
|
-
|
|
22203
|
-
|
|
23616
|
+
function refIdentity(ref) {
|
|
23617
|
+
if (!ref || typeof ref !== "object" || Array.isArray(ref))
|
|
23618
|
+
return null;
|
|
23619
|
+
const o = ref;
|
|
23620
|
+
const str = (f) => {
|
|
23621
|
+
const v = o[f];
|
|
23622
|
+
if (typeof v !== "string")
|
|
23623
|
+
return null;
|
|
23624
|
+
const t = v.trim().toLowerCase();
|
|
23625
|
+
return t ? t : null;
|
|
23626
|
+
};
|
|
23627
|
+
const website = str("website");
|
|
23628
|
+
const parts = [
|
|
23629
|
+
normalizeUuid(o.lead_id) ?? null,
|
|
23630
|
+
normalizeUuid(o.contact_id) ?? null,
|
|
23631
|
+
website ? normalizeDomain(website) ?? website : null,
|
|
23632
|
+
str("name"),
|
|
23633
|
+
str("location")
|
|
23634
|
+
];
|
|
23635
|
+
return parts.some((p) => p !== null) ? JSON.stringify(parts) : null;
|
|
23636
|
+
}
|
|
23637
|
+
function remapInputIndexes(items, refs) {
|
|
23638
|
+
const list = Array.isArray(refs) ? refs : [];
|
|
23639
|
+
if (list.length === 0)
|
|
23640
|
+
return { items, remapped: false };
|
|
23641
|
+
const byIdentity = /* @__PURE__ */ new Map();
|
|
23642
|
+
list.forEach((ref, i) => {
|
|
23643
|
+
const key = refIdentity(ref);
|
|
23644
|
+
if (!key)
|
|
23645
|
+
return;
|
|
23646
|
+
const at = byIdentity.get(key);
|
|
23647
|
+
if (at)
|
|
23648
|
+
at.push(i);
|
|
23649
|
+
else
|
|
23650
|
+
byIdentity.set(key, [i]);
|
|
23651
|
+
});
|
|
23652
|
+
const next = [];
|
|
23653
|
+
let ok = true;
|
|
23654
|
+
for (const item of items) {
|
|
23655
|
+
const ref = item.ref;
|
|
23656
|
+
if (!ref || ref.input_indexes == null) {
|
|
23657
|
+
next.push(item);
|
|
23658
|
+
continue;
|
|
23659
|
+
}
|
|
23660
|
+
const key = refIdentity(ref.requested_as) ?? refIdentity({ lead_id: ref.lead_id ?? void 0 });
|
|
23661
|
+
const found = key ? byIdentity.get(key) : void 0;
|
|
23662
|
+
if (!found) {
|
|
23663
|
+
ok = false;
|
|
23664
|
+
break;
|
|
23665
|
+
}
|
|
23666
|
+
next.push({ ...item, ref: { ...ref, input_indexes: found } });
|
|
23667
|
+
}
|
|
23668
|
+
if (!ok) {
|
|
23669
|
+
return {
|
|
23670
|
+
items: items.map((item) => item.ref && item.ref.input_indexes != null ? { ...item, ref: { ...item.ref, input_indexes: null } } : item),
|
|
23671
|
+
remapped: false
|
|
23672
|
+
};
|
|
23673
|
+
}
|
|
23674
|
+
return { items: next, remapped: true };
|
|
23675
|
+
}
|
|
23676
|
+
function canonicalSet(values) {
|
|
23677
|
+
const list = values === void 0 || values === null ? [] : Array.isArray(values) ? values : [values];
|
|
23678
|
+
return [...new Set(list.map((v) => JSON.stringify(v)))].sort().map((v) => JSON.parse(v));
|
|
23679
|
+
}
|
|
23680
|
+
function coerceArrayParams(params, keys) {
|
|
23681
|
+
const out = { ...params };
|
|
23682
|
+
for (const key of keys) {
|
|
23683
|
+
const v = out[key];
|
|
23684
|
+
if (v !== void 0 && v !== null && !Array.isArray(v)) {
|
|
23685
|
+
out[key] = [v];
|
|
23686
|
+
}
|
|
23687
|
+
}
|
|
23688
|
+
return out;
|
|
23689
|
+
}
|
|
23690
|
+
var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
23691
|
+
function presentRequestId(value) {
|
|
23692
|
+
if (typeof value !== "string")
|
|
23693
|
+
return void 0;
|
|
23694
|
+
const trimmed = value.trim();
|
|
23695
|
+
return trimmed ? trimmed : void 0;
|
|
23696
|
+
}
|
|
23697
|
+
function isUuidShaped(value) {
|
|
23698
|
+
return typeof value === "string" && UUID_RE2.test(value.trim());
|
|
23699
|
+
}
|
|
23700
|
+
function normalizeUuid(value) {
|
|
23701
|
+
if (typeof value !== "string")
|
|
23702
|
+
return null;
|
|
23703
|
+
const v = value.trim();
|
|
23704
|
+
if (!v)
|
|
23705
|
+
return null;
|
|
23706
|
+
return UUID_RE2.test(v) ? v.toLowerCase() : v;
|
|
23707
|
+
}
|
|
23708
|
+
function canonicalIdSet(values) {
|
|
23709
|
+
const list = values === void 0 || values === null ? [] : Array.isArray(values) ? values : [values];
|
|
23710
|
+
return canonicalSet(list.map(normalizeUuid).filter((v) => !!v));
|
|
23711
|
+
}
|
|
23712
|
+
function canonicalLabelSet(values) {
|
|
23713
|
+
const list = values === void 0 || values === null ? [] : Array.isArray(values) ? values : [values];
|
|
23714
|
+
return canonicalSet(list.filter((v) => typeof v === "string").map((v) => v.trim().toLowerCase()).filter(Boolean));
|
|
23715
|
+
}
|
|
23716
|
+
function canonicalOptionalObject(value) {
|
|
23717
|
+
if (!value)
|
|
23718
|
+
return null;
|
|
23719
|
+
const out = {};
|
|
23720
|
+
for (const [k, v] of Object.entries(value)) {
|
|
23721
|
+
if (v === void 0 || v === null)
|
|
23722
|
+
continue;
|
|
23723
|
+
if (Array.isArray(v) && v.length === 0)
|
|
23724
|
+
continue;
|
|
23725
|
+
out[k] = v;
|
|
23726
|
+
}
|
|
23727
|
+
return Object.keys(out).length === 0 ? null : out;
|
|
23728
|
+
}
|
|
23729
|
+
function canonicalize(value) {
|
|
23730
|
+
if (Array.isArray(value))
|
|
23731
|
+
return value.map(canonicalize);
|
|
23732
|
+
if (value && typeof value === "object") {
|
|
23733
|
+
const out = {};
|
|
23734
|
+
for (const k of Object.keys(value).sort()) {
|
|
23735
|
+
out[k] = canonicalize(value[k]);
|
|
23736
|
+
}
|
|
23737
|
+
return out;
|
|
23738
|
+
}
|
|
23739
|
+
return value;
|
|
23740
|
+
}
|
|
23741
|
+
function derivedKey(prefix, shape) {
|
|
23742
|
+
const serialized = typeof shape === "string" ? shape : JSON.stringify(canonicalize(shape));
|
|
23743
|
+
return `${prefix}-${createHash4("sha256").update(serialized).digest("hex").slice(0, 32)}`;
|
|
23744
|
+
}
|
|
23745
|
+
function mockedSubmitPreview(submit, tool, region) {
|
|
23746
|
+
const s = submit ?? {};
|
|
23747
|
+
if (typeof s.job_id === "string" && s.job_id)
|
|
23748
|
+
return null;
|
|
23749
|
+
if (process.env.LEADBAY_MOCK !== "1") {
|
|
23750
|
+
throw {
|
|
23751
|
+
error: true,
|
|
23752
|
+
code: "MALFORMED_SUBMIT_RESPONSE",
|
|
23753
|
+
message: `${tool}: the submit succeeded but the response carried no job_id, so the job cannot be polled.`,
|
|
23754
|
+
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."
|
|
23755
|
+
};
|
|
23756
|
+
}
|
|
23757
|
+
return {
|
|
23758
|
+
mocked: true,
|
|
23759
|
+
tool,
|
|
23760
|
+
submitted: false,
|
|
23761
|
+
would_call: s.would_call ?? null,
|
|
23762
|
+
note: "LEADBAY_MOCK=1 \u2014 the job was not submitted, so there is no job to poll.",
|
|
23763
|
+
region
|
|
23764
|
+
};
|
|
23765
|
+
}
|
|
23766
|
+
function splitItems(snapshot) {
|
|
23767
|
+
const leads = [];
|
|
23768
|
+
const skipped = [];
|
|
23769
|
+
for (const item of snapshot.items) {
|
|
23770
|
+
if (item.status === "skipped")
|
|
23771
|
+
skipped.push(item);
|
|
23772
|
+
else
|
|
23773
|
+
leads.push(item);
|
|
23774
|
+
}
|
|
23775
|
+
return { leads, skipped };
|
|
23776
|
+
}
|
|
23777
|
+
function compactBody(body) {
|
|
23778
|
+
return Object.fromEntries(Object.entries(body).filter(([, v]) => v !== void 0));
|
|
23779
|
+
}
|
|
23780
|
+
var COUNTRY_ALIASES = [
|
|
23781
|
+
"united states",
|
|
23782
|
+
"united states of america",
|
|
23783
|
+
"usa",
|
|
23784
|
+
"us",
|
|
23785
|
+
"america",
|
|
23786
|
+
"etats unis",
|
|
23787
|
+
"etats unis d amerique",
|
|
23788
|
+
"france",
|
|
23789
|
+
"fr",
|
|
23790
|
+
"french republic",
|
|
23791
|
+
"republique francaise"
|
|
23792
|
+
];
|
|
23793
|
+
var SUBNATIONAL_EXEMPTIONS = {
|
|
23794
|
+
us: new Set(["georgia", "georgie"].map(countryKey2)),
|
|
23795
|
+
fr: new Set([
|
|
23796
|
+
"guadeloupe",
|
|
23797
|
+
"martinique",
|
|
23798
|
+
"reunion",
|
|
23799
|
+
"mayotte",
|
|
23800
|
+
"french guiana",
|
|
23801
|
+
"guyane francaise",
|
|
23802
|
+
"new caledonia",
|
|
23803
|
+
"nouvelle caledonie",
|
|
23804
|
+
"french polynesia",
|
|
23805
|
+
"polynesie francaise",
|
|
23806
|
+
"saint martin",
|
|
23807
|
+
"saint barthelemy",
|
|
23808
|
+
"saint pierre and miquelon",
|
|
23809
|
+
"saint pierre et miquelon",
|
|
23810
|
+
"wallis and futuna",
|
|
23811
|
+
"wallis et futuna"
|
|
23812
|
+
].map(countryKey2))
|
|
23813
|
+
};
|
|
23814
|
+
var ALL_EXEMPTIONS = new Set(Object.values(SUBNATIONAL_EXEMPTIONS).flatMap((s) => [...s]));
|
|
23815
|
+
function exemptionsFor(region) {
|
|
23816
|
+
const key = typeof region === "string" ? region.trim().toLowerCase() : "";
|
|
23817
|
+
return SUBNATIONAL_EXEMPTIONS[key] ?? ALL_EXEMPTIONS;
|
|
23818
|
+
}
|
|
23819
|
+
function buildCountryLocationValues() {
|
|
23820
|
+
const values = new Set(COUNTRY_ALIASES.map(countryKey2));
|
|
23821
|
+
try {
|
|
23822
|
+
const A = "A".charCodeAt(0);
|
|
23823
|
+
const displays = ["en", "fr"].map((locale) => new Intl.DisplayNames([locale], { type: "region", fallback: "none" }));
|
|
23824
|
+
for (let i = 0; i < 26; i++) {
|
|
23825
|
+
for (let j = 0; j < 26; j++) {
|
|
23826
|
+
const code = String.fromCharCode(A + i) + String.fromCharCode(A + j);
|
|
23827
|
+
for (const display of displays) {
|
|
23828
|
+
const name = display.of(code);
|
|
23829
|
+
if (!name || name === code)
|
|
23830
|
+
continue;
|
|
23831
|
+
values.add(countryKey2(name));
|
|
23832
|
+
}
|
|
23833
|
+
}
|
|
23834
|
+
}
|
|
23835
|
+
} catch {
|
|
23836
|
+
}
|
|
23837
|
+
return values;
|
|
23838
|
+
}
|
|
23839
|
+
var COUNTRY_LOCATION_VALUES = buildCountryLocationValues();
|
|
23840
|
+
function countryKey2(raw) {
|
|
23841
|
+
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();
|
|
23842
|
+
}
|
|
23843
|
+
var MAX_EXCLUDE_LEAD_IDS = 500;
|
|
23844
|
+
function rejectMalformedExclusions(ids) {
|
|
23845
|
+
if (ids === void 0 || ids === null)
|
|
23846
|
+
return;
|
|
23847
|
+
const list = Array.isArray(ids) ? ids : [ids];
|
|
23848
|
+
const bad = [];
|
|
23849
|
+
list.forEach((v, i) => {
|
|
23850
|
+
if (typeof v !== "string") {
|
|
23851
|
+
bad.push(`${i} (${v === null ? "null" : typeof v})`);
|
|
23852
|
+
} else if (!v.trim()) {
|
|
23853
|
+
bad.push(`${i} (blank)`);
|
|
23854
|
+
}
|
|
23855
|
+
});
|
|
23856
|
+
if (bad.length === 0)
|
|
23857
|
+
return;
|
|
23858
|
+
throw {
|
|
23859
|
+
error: true,
|
|
23860
|
+
code: "INVALID_EXCLUDE_LEAD_ID",
|
|
23861
|
+
message: `exclude_lead_ids has ${bad.length} entr${bad.length === 1 ? "y" : "ies"} that is not a lead id: ${bad.join(", ")}.`,
|
|
23862
|
+
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."
|
|
23863
|
+
};
|
|
23864
|
+
}
|
|
23865
|
+
function rejectOversizedExclusions(ids) {
|
|
23866
|
+
if (ids === void 0 || ids === null)
|
|
23867
|
+
return;
|
|
23868
|
+
const unique = canonicalIdSet(ids);
|
|
23869
|
+
if (unique.length <= MAX_EXCLUDE_LEAD_IDS)
|
|
23870
|
+
return;
|
|
23871
|
+
throw {
|
|
23872
|
+
error: true,
|
|
23873
|
+
code: "TOO_MANY_EXCLUSIONS",
|
|
23874
|
+
message: `exclude_lead_ids carries ${unique.length} ids \u2014 the maximum is ${MAX_EXCLUDE_LEAD_IDS}.`,
|
|
23875
|
+
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."
|
|
23876
|
+
};
|
|
23877
|
+
}
|
|
23878
|
+
var MAX_LEAD_REFS = 500;
|
|
23879
|
+
function rejectOversizedLeadRefs(refs) {
|
|
23880
|
+
if (refs === void 0 || refs === null)
|
|
23881
|
+
return;
|
|
23882
|
+
const list = Array.isArray(refs) ? refs : [refs];
|
|
23883
|
+
const unique = /* @__PURE__ */ new Set();
|
|
23884
|
+
let unkeyed = 0;
|
|
23885
|
+
for (const ref of list) {
|
|
23886
|
+
const key = refIdentity(ref);
|
|
23887
|
+
if (key === null)
|
|
23888
|
+
unkeyed += 1;
|
|
23889
|
+
else
|
|
23890
|
+
unique.add(key);
|
|
23891
|
+
}
|
|
23892
|
+
const count = unique.size + unkeyed;
|
|
23893
|
+
if (count <= MAX_LEAD_REFS)
|
|
23894
|
+
return;
|
|
23895
|
+
throw {
|
|
23896
|
+
error: true,
|
|
23897
|
+
code: "TOO_MANY_LEAD_REFS",
|
|
23898
|
+
message: `lead_refs carries ${count} companies \u2014 the maximum is ${MAX_LEAD_REFS}.`,
|
|
23899
|
+
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.`
|
|
23900
|
+
};
|
|
23901
|
+
}
|
|
23902
|
+
function readSpendFlag(value, field) {
|
|
23903
|
+
if (value === void 0 || value === null)
|
|
23904
|
+
return void 0;
|
|
23905
|
+
if (typeof value === "boolean")
|
|
23906
|
+
return value;
|
|
23907
|
+
if (typeof value === "string") {
|
|
23908
|
+
const t = value.trim().toLowerCase();
|
|
23909
|
+
if (t === "true")
|
|
23910
|
+
return true;
|
|
23911
|
+
if (t === "false")
|
|
23912
|
+
return false;
|
|
23913
|
+
}
|
|
23914
|
+
throw {
|
|
23915
|
+
error: true,
|
|
23916
|
+
code: "BAD_INPUT",
|
|
23917
|
+
message: `${field} must be a boolean (got ${Array.isArray(value) ? "array" : typeof value}: ${JSON.stringify(value)}).`,
|
|
23918
|
+
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.`
|
|
23919
|
+
};
|
|
23920
|
+
}
|
|
23921
|
+
function rejectCountryLocations(locations, region) {
|
|
23922
|
+
if (locations === void 0 || locations === null)
|
|
23923
|
+
return;
|
|
23924
|
+
const exempt = exemptionsFor(region);
|
|
23925
|
+
const list = Array.isArray(locations) ? locations : [locations];
|
|
23926
|
+
for (const loc of list) {
|
|
23927
|
+
if (typeof loc !== "string")
|
|
23928
|
+
continue;
|
|
23929
|
+
const key = countryKey2(loc);
|
|
23930
|
+
if (!exempt.has(key) && COUNTRY_LOCATION_VALUES.has(key)) {
|
|
23931
|
+
throw {
|
|
23932
|
+
error: true,
|
|
23933
|
+
code: "COUNTRY_LEVEL_LOCATION",
|
|
23934
|
+
message: `filters.locations value "${loc}" is country-level \u2014 it would silently fence the search to a same-named town, not the whole country.`,
|
|
23935
|
+
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").'
|
|
23936
|
+
};
|
|
23937
|
+
}
|
|
23938
|
+
}
|
|
23939
|
+
}
|
|
23940
|
+
function normalizeSearchFilters(filters) {
|
|
23941
|
+
if (filters == null)
|
|
23942
|
+
return void 0;
|
|
23943
|
+
const { employees, employeesMin, employeesMax, ...rest } = filters;
|
|
23944
|
+
const out = { ...rest };
|
|
23945
|
+
if (out.employees_min == null) {
|
|
23946
|
+
out.employees_min = employees?.min ?? employees?.employees_min ?? employeesMin;
|
|
23947
|
+
}
|
|
23948
|
+
if (out.employees_max == null) {
|
|
23949
|
+
out.employees_max = employees?.max ?? employees?.employees_max ?? employeesMax;
|
|
23950
|
+
}
|
|
23951
|
+
if (out.employees_min == null)
|
|
23952
|
+
delete out.employees_min;
|
|
23953
|
+
if (out.employees_max == null)
|
|
23954
|
+
delete out.employees_max;
|
|
23955
|
+
for (const key of ["sectors", "locations"]) {
|
|
23956
|
+
const v = out[key];
|
|
23957
|
+
if (typeof v === "string")
|
|
23958
|
+
out[key] = v.trim() ? [v] : void 0;
|
|
23959
|
+
if (out[key] === void 0)
|
|
23960
|
+
delete out[key];
|
|
23961
|
+
}
|
|
23962
|
+
return out;
|
|
23963
|
+
}
|
|
23964
|
+
function clampWaitSeconds(requested, fallback) {
|
|
23965
|
+
if (requested == null || Number.isNaN(requested))
|
|
23966
|
+
return fallback;
|
|
23967
|
+
return Math.min(Math.max(requested, 0), 180);
|
|
23968
|
+
}
|
|
23969
|
+
|
|
23970
|
+
// ../core/dist/composite/find-new-leads.js
|
|
23971
|
+
var DEFAULT_WAIT_SECONDS = 45;
|
|
23972
|
+
function sortFilterLists(filters) {
|
|
23973
|
+
if (!filters)
|
|
23974
|
+
return null;
|
|
23975
|
+
const out = { ...filters };
|
|
23976
|
+
for (const key of ["sectors", "locations"]) {
|
|
23977
|
+
if (Array.isArray(out[key])) {
|
|
23978
|
+
out[key] = canonicalLabelSet(out[key]);
|
|
23979
|
+
}
|
|
23980
|
+
}
|
|
23981
|
+
return out;
|
|
23982
|
+
}
|
|
23983
|
+
var findNewLeads = {
|
|
23984
|
+
name: "leadbay_find_new_leads",
|
|
23985
|
+
annotations: {
|
|
23986
|
+
title: "Find new leads (net-new ICP search)",
|
|
23987
|
+
readOnlyHint: false,
|
|
23988
|
+
// The tool CAN bill (qualify:true and/or channels) and records deliveries
|
|
23989
|
+
// in the org novelty ledger, so it advertises destructive like the other
|
|
23990
|
+
// paid composites — annotations are static and must describe the worst
|
|
23991
|
+
// case, not the default. The free path is protected in execute() instead:
|
|
23992
|
+
// a paid call is withheld until `confirm: true`.
|
|
23993
|
+
destructiveHint: true,
|
|
23994
|
+
// The mandatory request_id dedups: re-submitting the same request returns
|
|
23995
|
+
// the SAME live job instead of double-spending.
|
|
23996
|
+
idempotentHint: true,
|
|
23997
|
+
openWorldHint: true
|
|
23998
|
+
},
|
|
23999
|
+
write: true,
|
|
24000
|
+
description: leadbay_find_new_leads,
|
|
24001
|
+
inputSchema: {
|
|
24002
|
+
type: "object",
|
|
24003
|
+
properties: {
|
|
24004
|
+
query: {
|
|
24005
|
+
type: "string",
|
|
24006
|
+
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."
|
|
24007
|
+
},
|
|
24008
|
+
example_lead: {
|
|
24009
|
+
type: "object",
|
|
24010
|
+
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).",
|
|
24011
|
+
properties: {
|
|
24012
|
+
name: { type: "string" },
|
|
24013
|
+
description: { type: "string" },
|
|
24014
|
+
location: { type: "string" },
|
|
24015
|
+
employees: { type: "number" }
|
|
24016
|
+
},
|
|
24017
|
+
additionalProperties: false
|
|
24018
|
+
},
|
|
24019
|
+
filters: {
|
|
24020
|
+
type: "object",
|
|
24021
|
+
description: "HARD constraints (the seed only shapes ranking). Sector/location labels resolve at submit; an unresolvable value is a 400 naming it.",
|
|
24022
|
+
properties: {
|
|
24023
|
+
sectors: { type: "array", items: { type: "string" } },
|
|
24024
|
+
locations: { type: "array", items: { type: "string" } },
|
|
24025
|
+
employees_min: { type: "number" },
|
|
24026
|
+
employees_max: { type: "number" }
|
|
24027
|
+
},
|
|
24028
|
+
additionalProperties: false
|
|
24029
|
+
},
|
|
24030
|
+
count: {
|
|
24031
|
+
type: "number",
|
|
24032
|
+
description: "Target DELIVERED leads, 1-50. With qualify:true this means n SURVIVORS of qualification, not n candidates examined."
|
|
24033
|
+
},
|
|
24034
|
+
qualify: {
|
|
24035
|
+
type: "boolean",
|
|
24036
|
+
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)."
|
|
24037
|
+
},
|
|
24038
|
+
min_ai_score: {
|
|
24039
|
+
type: "number",
|
|
24040
|
+
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."
|
|
24041
|
+
},
|
|
24042
|
+
contact_titles: {
|
|
24043
|
+
type: "array",
|
|
24044
|
+
items: { type: "string" },
|
|
24045
|
+
description: "Wanted decision-maker titles (max 10), matched semantically cross-language."
|
|
24046
|
+
},
|
|
24047
|
+
title_gate: {
|
|
24048
|
+
type: "string",
|
|
24049
|
+
enum: ["strict", "prefer"],
|
|
24050
|
+
description: "strict = only leads with a matching known contact; prefer (default when contact_titles set) = matched first, rest flagged."
|
|
24051
|
+
},
|
|
24052
|
+
channels: {
|
|
24053
|
+
type: "array",
|
|
24054
|
+
items: { type: "string", enum: ["email", "phone"] },
|
|
24055
|
+
description: "Contact channels to PURCHASE (email 25c, phone 250c, billed on success only). Empty = free identity tier."
|
|
24056
|
+
},
|
|
24057
|
+
exclude_lead_ids: {
|
|
24058
|
+
type: "array",
|
|
24059
|
+
items: { type: "string" },
|
|
24060
|
+
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)."
|
|
24061
|
+
},
|
|
24062
|
+
novelty: {
|
|
24063
|
+
type: "string",
|
|
24064
|
+
enum: ["org", "none"],
|
|
24065
|
+
description: "org (default) = only companies NEW to the org (excludes org leads, lens members, CRM ids, prior MCP deliveries)."
|
|
24066
|
+
},
|
|
24067
|
+
max_cost: {
|
|
24068
|
+
type: "number",
|
|
24069
|
+
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)."
|
|
24070
|
+
},
|
|
24071
|
+
exploration_cap: {
|
|
24072
|
+
type: "number",
|
|
24073
|
+
description: "Max candidates the qualify gate may examine. Default min(3n,150), ceiling min(20n,1000)."
|
|
24074
|
+
},
|
|
24075
|
+
request_id: {
|
|
24076
|
+
type: "string",
|
|
24077
|
+
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."
|
|
24078
|
+
},
|
|
24079
|
+
lang: { type: "string", description: "Output language (default: user's language)." },
|
|
24080
|
+
confirm: {
|
|
24081
|
+
type: "boolean",
|
|
24082
|
+
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."
|
|
24083
|
+
},
|
|
24084
|
+
dry_run: {
|
|
24085
|
+
type: "boolean",
|
|
24086
|
+
description: "Validate + worst-case cost estimate + quota forecast. No job, no spend. Use before the first PAID run of a session."
|
|
24087
|
+
},
|
|
24088
|
+
wait_seconds: {
|
|
24089
|
+
type: "number",
|
|
24090
|
+
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."
|
|
24091
|
+
}
|
|
24092
|
+
},
|
|
24093
|
+
required: ["count", "request_id"],
|
|
24094
|
+
additionalProperties: false
|
|
24095
|
+
},
|
|
24096
|
+
execute: async (client, params, ctx) => {
|
|
24097
|
+
params = coerceArrayParams(params, [
|
|
24098
|
+
"contact_titles",
|
|
24099
|
+
"channels",
|
|
24100
|
+
"exclude_lead_ids"
|
|
24101
|
+
]);
|
|
24102
|
+
rejectCountryLocations(params.filters?.locations, client.region);
|
|
24103
|
+
rejectMalformedExclusions(params.exclude_lead_ids);
|
|
24104
|
+
rejectOversizedExclusions(params.exclude_lead_ids);
|
|
24105
|
+
const qualify = readSpendFlag(params.qualify, "qualify");
|
|
24106
|
+
const dryRun = readSpendFlag(params.dry_run, "dry_run");
|
|
24107
|
+
const confirm = readSpendFlag(params.confirm, "confirm");
|
|
24108
|
+
params = { ...params, qualify, dry_run: dryRun, confirm };
|
|
24109
|
+
const buysChannels = (params.channels?.length ?? 0) > 0;
|
|
24110
|
+
const buysQualification = qualify === true;
|
|
24111
|
+
const isPaid = buysQualification || buysChannels;
|
|
24112
|
+
const vetoed = confirm === false;
|
|
24113
|
+
const consented = !vetoed && confirm === true;
|
|
24114
|
+
const requestId = presentRequestId(params.request_id) ?? derivedKey(
|
|
24115
|
+
"search-auto",
|
|
24116
|
+
// Passed as an OBJECT: derivedKey canonicalizes recursively, so nested
|
|
24117
|
+
// property order (example_lead, filters) can never fork the key. Fields
|
|
24118
|
+
// with a documented backend default are canonicalized TO that default,
|
|
24119
|
+
// so an approval that omits one and a retry that passes it explicitly
|
|
24120
|
+
// derive the same key rather than launching a second paid,
|
|
24121
|
+
// novelty-claiming job.
|
|
24122
|
+
{
|
|
24123
|
+
query: params.query ?? null,
|
|
24124
|
+
example_lead: params.example_lead ?? null,
|
|
24125
|
+
// Sector/location lists are unordered sets to the backend — sort
|
|
24126
|
+
// them so a reordered retry still dedupes.
|
|
24127
|
+
filters: canonicalOptionalObject(sortFilterLists(normalizeSearchFilters(params.filters))),
|
|
24128
|
+
count: params.count ?? null,
|
|
24129
|
+
qualify: params.qualify === true,
|
|
24130
|
+
min_ai_score: params.min_ai_score ?? 0,
|
|
24131
|
+
contact_titles: canonicalLabelSet(params.contact_titles),
|
|
24132
|
+
title_gate: params.title_gate ?? ((params.contact_titles?.length ?? 0) > 0 ? "prefer" : null),
|
|
24133
|
+
channels: canonicalSet(params.channels),
|
|
24134
|
+
// Sorted so ordering alone never forks the key, but PRESENT — a
|
|
24135
|
+
// top-up differing only by exclude_lead_ids is a different approved
|
|
24136
|
+
// search, and hashing it the same would return the first job as a
|
|
24137
|
+
// duplicate with the exclusions never applied.
|
|
24138
|
+
exclude_lead_ids: canonicalIdSet(params.exclude_lead_ids),
|
|
24139
|
+
novelty: params.novelty ?? "org",
|
|
24140
|
+
max_cost: params.max_cost ?? null,
|
|
24141
|
+
// Documented backend default is min(3n,150), so an omitted cap is
|
|
24142
|
+
// canonicalized TO it — same principle as min_ai_score/novelty above.
|
|
24143
|
+
// Otherwise an approval that omits the cap and a retry that passes the
|
|
24144
|
+
// materialized default ask for identical work under different keys,
|
|
24145
|
+
// and the retry escapes dedupe into a second paid, novelty-claiming
|
|
24146
|
+
// job. An explicit non-default cap still hashes distinctly.
|
|
24147
|
+
exploration_cap: params.exploration_cap ?? (typeof params.count === "number" && params.count > 0 ? Math.min(3 * params.count, 150) : null),
|
|
24148
|
+
lang: params.lang ?? null
|
|
24149
|
+
}
|
|
24150
|
+
);
|
|
24151
|
+
const body = compactBody({
|
|
24152
|
+
query: params.query,
|
|
24153
|
+
example_lead: params.example_lead,
|
|
24154
|
+
filters: normalizeSearchFilters(params.filters),
|
|
24155
|
+
count: params.count,
|
|
24156
|
+
qualify,
|
|
24157
|
+
min_ai_score: params.min_ai_score,
|
|
24158
|
+
contact_titles: params.contact_titles,
|
|
24159
|
+
title_gate: params.title_gate,
|
|
24160
|
+
channels: params.channels,
|
|
24161
|
+
// Wire the SAME list the cap guard counted and the idempotency key was
|
|
24162
|
+
// derived from. Posting the raw array instead let a 600-entry list that
|
|
24163
|
+
// dedupes to 400 clear the guard and still be refused by the backend.
|
|
24164
|
+
// Kept undefined when absent so compactBody drops it rather than
|
|
24165
|
+
// sending an empty array.
|
|
24166
|
+
exclude_lead_ids: params.exclude_lead_ids ? canonicalIdSet(params.exclude_lead_ids) : void 0,
|
|
24167
|
+
novelty: params.novelty,
|
|
24168
|
+
max_cost: params.max_cost,
|
|
24169
|
+
exploration_cap: params.exploration_cap,
|
|
24170
|
+
request_id: requestId,
|
|
24171
|
+
lang: params.lang,
|
|
24172
|
+
dry_run: dryRun
|
|
24173
|
+
});
|
|
24174
|
+
if (dryRun === true) {
|
|
24175
|
+
const forecast = await client.request("POST", "/mcp/search", body);
|
|
24176
|
+
return {
|
|
24177
|
+
dry_run: true,
|
|
24178
|
+
...forecast,
|
|
24179
|
+
region: client.region
|
|
24180
|
+
};
|
|
24181
|
+
}
|
|
24182
|
+
if (isPaid && !consented) {
|
|
24183
|
+
const forecast = vetoed ? null : await client.request("POST", "/mcp/search", {
|
|
24184
|
+
...body,
|
|
24185
|
+
dry_run: true
|
|
24186
|
+
});
|
|
24187
|
+
return {
|
|
24188
|
+
mode: "needs_confirmation",
|
|
24189
|
+
submitted: false,
|
|
24190
|
+
vetoed,
|
|
24191
|
+
paid_because: [
|
|
24192
|
+
buysQualification ? "qualify: true (~94 cost_cents per candidate EXAMINED)" : null,
|
|
24193
|
+
buysChannels ? `channels requested: ${params.channels.join(", ")}` : null
|
|
24194
|
+
].filter(Boolean),
|
|
24195
|
+
quote: forecast,
|
|
24196
|
+
estimated_cost: forecast?.estimated_cost ?? null,
|
|
24197
|
+
items_requested: forecast?.items_requested ?? null,
|
|
24198
|
+
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.",
|
|
24199
|
+
region: client.region
|
|
24200
|
+
};
|
|
24201
|
+
}
|
|
24202
|
+
const submit = await client.request("POST", "/mcp/search", body, { preSendSignal: ctx?.signal });
|
|
24203
|
+
const mocked = mockedSubmitPreview(submit, "leadbay_find_new_leads", client.region);
|
|
24204
|
+
if (mocked)
|
|
24205
|
+
return mocked;
|
|
24206
|
+
const waitSeconds = clampWaitSeconds(params.wait_seconds, DEFAULT_WAIT_SECONDS);
|
|
24207
|
+
const snapshot = await snapshotAfterSubmit(client, submit.job_id, waitSeconds, ctx, params.count);
|
|
24208
|
+
const done = TERMINAL_JOB_STATES.has(snapshot.job.state);
|
|
24209
|
+
const { leads, skipped } = splitItems(snapshot);
|
|
24210
|
+
return {
|
|
24211
|
+
job_id: submit.job_id,
|
|
24212
|
+
request_id: requestId,
|
|
24213
|
+
duplicate_submit: submit.duplicate ?? false,
|
|
24214
|
+
state: snapshot.job.state,
|
|
24215
|
+
done,
|
|
24216
|
+
summary: {
|
|
24217
|
+
// Named items_requested (not `requested`) to match qualify_leads and
|
|
24218
|
+
// the shared renderer, which reads summary.items_requested for the
|
|
24219
|
+
// "delivered X of the Y asked" clause.
|
|
24220
|
+
items_requested: submit.items_requested ?? params.count,
|
|
24221
|
+
delivered: snapshot.funnel.delivered ?? 0,
|
|
24222
|
+
delivered_callable: snapshot.funnel.delivered_callable ?? 0,
|
|
24223
|
+
delivered_title_only: snapshot.funnel.delivered_title_only ?? 0,
|
|
24224
|
+
degraded: snapshot.funnel.degraded ?? 0,
|
|
24225
|
+
stop_reason: snapshot.funnel.stop_reason ?? null
|
|
24226
|
+
},
|
|
24227
|
+
funnel: snapshot.funnel,
|
|
24228
|
+
leads,
|
|
24229
|
+
skipped,
|
|
24230
|
+
items_truncated: snapshot.items_truncated ?? false,
|
|
24231
|
+
// Top-level, not only inside next_poll: on a TERMINAL job that truncated,
|
|
24232
|
+
// next_poll used to be null, so the rendering rule telling the agent to
|
|
24233
|
+
// fetch the rest with `since: next_since` named a cursor the response did
|
|
24234
|
+
// not contain. The rows are paid for; the way to reach them cannot be
|
|
24235
|
+
// conditional on the job still running.
|
|
24236
|
+
next_since: snapshot.next_since ?? null,
|
|
24237
|
+
cost: snapshot.cost,
|
|
24238
|
+
estimated_cost: submit.estimated_cost,
|
|
24239
|
+
explain: snapshot.explain,
|
|
24240
|
+
still_running: !done,
|
|
24241
|
+
// A finished job can still owe rows: truncation means the drain stopped
|
|
24242
|
+
// early, so there is a follow-up action even when done is true. It is a
|
|
24243
|
+
// page fetch, not a wait, hence suggested_wait_seconds 0.
|
|
24244
|
+
next_poll: done && !(snapshot.items_truncated ?? false) ? null : {
|
|
24245
|
+
tool: "leadbay_lead_job_status",
|
|
24246
|
+
job_id: submit.job_id,
|
|
24247
|
+
// Hand the cursor forward so the follow-up poll continues
|
|
24248
|
+
// INCREMENTALLY instead of re-reading (and re-rendering) the
|
|
24249
|
+
// rows already delivered in this response.
|
|
24250
|
+
since: snapshot.next_since ?? null,
|
|
24251
|
+
suggested_wait_seconds: done ? 0 : 60
|
|
24252
|
+
},
|
|
24253
|
+
region: client.region
|
|
24254
|
+
};
|
|
24255
|
+
}
|
|
24256
|
+
};
|
|
24257
|
+
|
|
24258
|
+
// ../core/dist/composite/qualify-leads.js
|
|
24259
|
+
var DEFAULT_WAIT_SECONDS2 = 45;
|
|
24260
|
+
function normalizeLeadRefs(refs) {
|
|
24261
|
+
if (!Array.isArray(refs))
|
|
24262
|
+
return refs;
|
|
24263
|
+
return refs.map((ref) => {
|
|
24264
|
+
if (typeof ref !== "string")
|
|
24265
|
+
return ref;
|
|
24266
|
+
const value = ref.trim();
|
|
24267
|
+
if (!value)
|
|
24268
|
+
return ref;
|
|
24269
|
+
if (isUuidShaped(value))
|
|
24270
|
+
return { lead_id: value };
|
|
24271
|
+
return normalizeDomain(value) ? { website: value } : { name: value };
|
|
24272
|
+
});
|
|
24273
|
+
}
|
|
24274
|
+
var LEAD_REF_FIELDS = [
|
|
24275
|
+
"lead_id",
|
|
24276
|
+
"website",
|
|
24277
|
+
"name",
|
|
24278
|
+
"location",
|
|
24279
|
+
"contact_id"
|
|
24280
|
+
];
|
|
24281
|
+
function rejectMalformedLeadRefs(refs) {
|
|
24282
|
+
if (!Array.isArray(refs))
|
|
24283
|
+
return;
|
|
24284
|
+
const bad = [];
|
|
24285
|
+
refs.forEach((ref, i) => {
|
|
24286
|
+
if (ref === null || typeof ref !== "object" || Array.isArray(ref)) {
|
|
24287
|
+
bad.push(`${i} (not an object)`);
|
|
24288
|
+
return;
|
|
24289
|
+
}
|
|
24290
|
+
for (const field of LEAD_REF_FIELDS) {
|
|
24291
|
+
const value = ref[field];
|
|
24292
|
+
if (value !== void 0 && typeof value !== "string") {
|
|
24293
|
+
bad.push(`${i}.${field} (${value === null ? "null" : typeof value})`);
|
|
24294
|
+
}
|
|
24295
|
+
}
|
|
24296
|
+
});
|
|
24297
|
+
if (bad.length === 0)
|
|
24298
|
+
return;
|
|
24299
|
+
throw {
|
|
24300
|
+
error: true,
|
|
24301
|
+
code: "INVALID_LEAD_REF",
|
|
24302
|
+
message: `lead_refs has ${bad.length} invalid entr${bad.length === 1 ? "y" : "ies"}: ${bad.join(", ")}.`,
|
|
24303
|
+
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."
|
|
24304
|
+
};
|
|
24305
|
+
}
|
|
24306
|
+
function text(value) {
|
|
24307
|
+
if (typeof value !== "string")
|
|
24308
|
+
return null;
|
|
24309
|
+
const v = value.trim().toLowerCase();
|
|
24310
|
+
return v ? v : null;
|
|
24311
|
+
}
|
|
24312
|
+
function derivedRequestId(params) {
|
|
24313
|
+
const refs = canonicalSet((params.lead_refs ?? []).map((r) => {
|
|
24314
|
+
const website = text(r.website);
|
|
24315
|
+
return [
|
|
24316
|
+
// UUIDs are case-insensitive to the backend, so an uppercase id and
|
|
24317
|
+
// its lowercase form are the same lead and must share a key.
|
|
24318
|
+
normalizeUuid(r.lead_id),
|
|
24319
|
+
normalizeUuid(r.contact_id),
|
|
24320
|
+
// Normalize the website the SAME way the resolver does, so a pasted
|
|
24321
|
+
// "https://Acme.com/" and a retry's "acme.com" resolve to one company
|
|
24322
|
+
// AND to one key. Fall back to the trimmed/lowercased raw value when
|
|
24323
|
+
// it is not domain-shaped, rather than dropping the field.
|
|
24324
|
+
website ? normalizeDomain(website) ?? website : null,
|
|
24325
|
+
text(r.name),
|
|
24326
|
+
text(r.location)
|
|
24327
|
+
];
|
|
24328
|
+
}));
|
|
24329
|
+
const shape = {
|
|
24330
|
+
refs,
|
|
24331
|
+
// The WHOLE selector, not just the job id: qualifying the first 50 of a
|
|
24332
|
+
// delivery job and then the next 50 are different batches, and collapsing
|
|
24333
|
+
// them to one key would make the second submit look like a duplicate and
|
|
24334
|
+
// leave those refs unqualified.
|
|
24335
|
+
prior: [
|
|
24336
|
+
// UUID-folded like the refs above: the backend resolves the same
|
|
24337
|
+
// delivery job regardless of casing, so casing alone must not fork
|
|
24338
|
+
// the key and re-run a paid batch.
|
|
24339
|
+
normalizeUuid(params.prior_deliveries?.job_id),
|
|
24340
|
+
params.prior_deliveries?.since ?? null,
|
|
24341
|
+
params.prior_deliveries?.limit ?? null
|
|
24342
|
+
],
|
|
24343
|
+
// Canonicalize to the value the BACKEND will apply, so an approval that
|
|
24344
|
+
// omits a field and a retry that passes that field's documented default
|
|
24345
|
+
// derive the same key instead of launching a second paid job.
|
|
24346
|
+
qualify: params.qualify !== false,
|
|
24347
|
+
channels: canonicalSet(params.channels),
|
|
24348
|
+
contact_titles: canonicalLabelSet(params.contact_titles),
|
|
24349
|
+
// Same canonicalization as the search path: with contact_titles present
|
|
24350
|
+
// the backend applies `prefer` when the field is omitted, so an approval
|
|
24351
|
+
// that omits it and a retry that passes the materialized default describe
|
|
24352
|
+
// identical work. Hashing the omission as null forked the key and let the
|
|
24353
|
+
// retry escape dedupe into a second paid qualification / channel purchase.
|
|
24354
|
+
title_gate: params.title_gate ?? ((params.contact_titles?.length ?? 0) > 0 ? "prefer" : null),
|
|
24355
|
+
// The cap is part of the approval: raising it after a stop_reason:max_cost
|
|
24356
|
+
// is a NEW approved run, and must not dedupe onto the capped job.
|
|
24357
|
+
max_cost: params.max_cost ?? null,
|
|
24358
|
+
// Same for the output language — re-running the batch in another language
|
|
24359
|
+
// must not return the earlier job with evidence in the previous one.
|
|
24360
|
+
lang: params.lang ?? null
|
|
24361
|
+
};
|
|
24362
|
+
return derivedKey("qualify-auto", shape);
|
|
24363
|
+
}
|
|
24364
|
+
var qualifyLeads = {
|
|
24365
|
+
name: "leadbay_qualify_leads",
|
|
24366
|
+
annotations: {
|
|
24367
|
+
title: "Qualify + get the right contact on known leads",
|
|
24368
|
+
readOnlyHint: false,
|
|
24369
|
+
// Spends real money (fresh qualification, and email/phone reveals when
|
|
24370
|
+
// channels are requested), same as bulk_qualify_leads / enrich-titles.
|
|
24371
|
+
// Hosts and approval layers key their prompts off this flag, so a paid
|
|
24372
|
+
// job submitter must not advertise itself as harmless.
|
|
24373
|
+
destructiveHint: true,
|
|
24374
|
+
idempotentHint: false,
|
|
24375
|
+
openWorldHint: true
|
|
24376
|
+
},
|
|
24377
|
+
write: true,
|
|
24378
|
+
description: leadbay_qualify_leads,
|
|
24379
|
+
inputSchema: {
|
|
24380
|
+
type: "object",
|
|
24381
|
+
properties: {
|
|
24382
|
+
lead_refs: {
|
|
24383
|
+
type: "array",
|
|
24384
|
+
description: "Companies to qualify (max 500). Each ref needs at least one identifying field. Duplicate lead_ids collapse into one item.",
|
|
24385
|
+
items: {
|
|
24386
|
+
type: "object",
|
|
24387
|
+
properties: {
|
|
24388
|
+
lead_id: { type: "string", description: "Leadbay lead UUID." },
|
|
24389
|
+
website: { type: "string" },
|
|
24390
|
+
name: { type: "string" },
|
|
24391
|
+
location: {
|
|
24392
|
+
type: "string",
|
|
24393
|
+
description: "Disambiguates name-only refs (city/region)."
|
|
24394
|
+
},
|
|
24395
|
+
contact_id: {
|
|
24396
|
+
type: "string",
|
|
24397
|
+
description: "Stable lead_contact id from a prior result \u2014 enrichment then targets EXACTLY this person, never a re-match."
|
|
24398
|
+
}
|
|
24399
|
+
},
|
|
24400
|
+
additionalProperties: false
|
|
24401
|
+
}
|
|
24402
|
+
},
|
|
24403
|
+
prior_deliveries: {
|
|
24404
|
+
type: "object",
|
|
24405
|
+
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.",
|
|
24406
|
+
properties: {
|
|
24407
|
+
job_id: { type: "string" },
|
|
24408
|
+
since: { type: "string", description: "ISO instant lower bound." },
|
|
24409
|
+
limit: { type: "number" }
|
|
24410
|
+
},
|
|
24411
|
+
additionalProperties: false
|
|
24412
|
+
},
|
|
24413
|
+
qualify: {
|
|
24414
|
+
type: "boolean",
|
|
24415
|
+
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."
|
|
24416
|
+
},
|
|
24417
|
+
contact_titles: {
|
|
24418
|
+
type: "array",
|
|
24419
|
+
items: { type: "string" },
|
|
24420
|
+
description: "Wanted decision-maker titles (max 10), matched semantically."
|
|
24421
|
+
},
|
|
24422
|
+
title_gate: {
|
|
24423
|
+
type: "string",
|
|
24424
|
+
enum: ["strict", "prefer"],
|
|
24425
|
+
description: "strict = only items with a matching known contact deliver a contact; prefer = matched first, rest flagged."
|
|
24426
|
+
},
|
|
24427
|
+
channels: {
|
|
24428
|
+
type: "array",
|
|
24429
|
+
items: { type: "string", enum: ["email", "phone"] },
|
|
24430
|
+
description: "Channels to PURCHASE (email 25c, phone 250c, success-only, already-owned values are free). Empty = free identity tier."
|
|
24431
|
+
},
|
|
24432
|
+
max_cost: {
|
|
24433
|
+
type: "number",
|
|
24434
|
+
description: "Spend cap in cost_cents (plan-tier default when unset)."
|
|
24435
|
+
},
|
|
24436
|
+
request_id: {
|
|
24437
|
+
type: "string",
|
|
24438
|
+
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."
|
|
24439
|
+
},
|
|
24440
|
+
lang: { type: "string", description: "Output language (default: user's language)." },
|
|
24441
|
+
confirm: {
|
|
24442
|
+
type: "boolean",
|
|
24443
|
+
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."
|
|
24444
|
+
},
|
|
24445
|
+
dry_run: {
|
|
24446
|
+
type: "boolean",
|
|
24447
|
+
description: "Validate + worst-case cost + quota forecast. No job, no spend."
|
|
24448
|
+
},
|
|
24449
|
+
wait_seconds: {
|
|
24450
|
+
type: "number",
|
|
24451
|
+
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."
|
|
24452
|
+
}
|
|
24453
|
+
},
|
|
24454
|
+
additionalProperties: false
|
|
24455
|
+
},
|
|
24456
|
+
execute: async (client, params, ctx) => {
|
|
24457
|
+
params = coerceArrayParams(params, [
|
|
24458
|
+
"lead_refs",
|
|
24459
|
+
"contact_titles",
|
|
24460
|
+
"channels"
|
|
24461
|
+
]);
|
|
24462
|
+
params = { ...params, lead_refs: normalizeLeadRefs(params.lead_refs) };
|
|
24463
|
+
rejectMalformedLeadRefs(params.lead_refs);
|
|
24464
|
+
rejectOversizedLeadRefs(params.lead_refs);
|
|
24465
|
+
const qualify = readSpendFlag(params.qualify, "qualify");
|
|
24466
|
+
const dryRun = readSpendFlag(params.dry_run, "dry_run");
|
|
24467
|
+
const confirm = readSpendFlag(params.confirm, "confirm");
|
|
24468
|
+
params = { ...params, qualify, dry_run: dryRun, confirm };
|
|
24469
|
+
const buysChannels = (params.channels?.length ?? 0) > 0;
|
|
24470
|
+
const buysQualification = qualify !== false;
|
|
24471
|
+
const isPaid = buysQualification || buysChannels;
|
|
24472
|
+
const vetoed = confirm === false;
|
|
24473
|
+
const consented = !vetoed && confirm === true;
|
|
24474
|
+
const requestId = presentRequestId(params.request_id) ?? (isPaid ? derivedRequestId(params) : void 0);
|
|
24475
|
+
const body = compactBody({
|
|
24476
|
+
lead_refs: params.lead_refs,
|
|
24477
|
+
prior_deliveries: params.prior_deliveries,
|
|
24478
|
+
qualify,
|
|
24479
|
+
contact_titles: params.contact_titles,
|
|
24480
|
+
title_gate: params.title_gate,
|
|
24481
|
+
channels: params.channels,
|
|
24482
|
+
max_cost: params.max_cost,
|
|
24483
|
+
request_id: requestId,
|
|
24484
|
+
lang: params.lang,
|
|
24485
|
+
dry_run: dryRun
|
|
24486
|
+
});
|
|
24487
|
+
if (dryRun === true) {
|
|
24488
|
+
const forecast = await client.request("POST", "/mcp/qualify", body);
|
|
24489
|
+
return { dry_run: true, ...forecast, region: client.region };
|
|
24490
|
+
}
|
|
24491
|
+
if (isPaid && !consented) {
|
|
24492
|
+
const forecast = vetoed ? null : await client.request("POST", "/mcp/qualify", {
|
|
24493
|
+
...body,
|
|
24494
|
+
dry_run: true
|
|
24495
|
+
});
|
|
24496
|
+
return {
|
|
24497
|
+
mode: "needs_confirmation",
|
|
24498
|
+
submitted: false,
|
|
24499
|
+
vetoed,
|
|
24500
|
+
paid_because: [
|
|
24501
|
+
buysQualification ? "qualify is on (backend default is true \u2014 pass qualify:false to keep it free)" : null,
|
|
24502
|
+
buysChannels ? `channels requested: ${params.channels.join(", ")}` : null
|
|
24503
|
+
].filter(Boolean),
|
|
24504
|
+
quote: forecast,
|
|
24505
|
+
estimated_cost: forecast?.estimated_cost ?? null,
|
|
24506
|
+
items_requested: forecast?.items_requested ?? null,
|
|
24507
|
+
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.",
|
|
24508
|
+
region: client.region
|
|
24509
|
+
};
|
|
24510
|
+
}
|
|
24511
|
+
const submit = await client.request("POST", "/mcp/qualify", body, { preSendSignal: ctx?.signal });
|
|
24512
|
+
const mocked = mockedSubmitPreview(submit, "leadbay_qualify_leads", client.region);
|
|
24513
|
+
if (mocked)
|
|
24514
|
+
return mocked;
|
|
24515
|
+
const waitSeconds = clampWaitSeconds(params.wait_seconds, DEFAULT_WAIT_SECONDS2);
|
|
24516
|
+
const snapshot = await snapshotAfterSubmit(client, submit.job_id, waitSeconds, ctx, submit.items_requested);
|
|
24517
|
+
const done = TERMINAL_JOB_STATES.has(snapshot.job.state);
|
|
24518
|
+
const indexed = submit.duplicate ?? false ? remapInputIndexes(snapshot.items, params.lead_refs) : { items: snapshot.items, remapped: true };
|
|
24519
|
+
const view = { ...snapshot, items: indexed.items };
|
|
24520
|
+
return {
|
|
24521
|
+
job_id: submit.job_id,
|
|
24522
|
+
// Echo the key actually sent, so a retry can reuse it verbatim.
|
|
24523
|
+
request_id: requestId ?? null,
|
|
24524
|
+
duplicate_submit: submit.duplicate ?? false,
|
|
24525
|
+
state: snapshot.job.state,
|
|
24526
|
+
done,
|
|
24527
|
+
summary: {
|
|
24528
|
+
refs_submitted: params.lead_refs?.length ?? 0,
|
|
24529
|
+
items_requested: submit.items_requested,
|
|
24530
|
+
delivered: snapshot.funnel.delivered ?? 0,
|
|
24531
|
+
delivered_callable: snapshot.funnel.delivered_callable ?? 0,
|
|
24532
|
+
degraded: snapshot.funnel.degraded ?? 0,
|
|
24533
|
+
resolved: snapshot.funnel.resolved ?? null,
|
|
24534
|
+
not_in_universe: snapshot.funnel.not_in_universe ?? null,
|
|
24535
|
+
stop_reason: snapshot.funnel.stop_reason ?? null
|
|
24536
|
+
},
|
|
24537
|
+
funnel: snapshot.funnel,
|
|
24538
|
+
// Per-item outcomes in input order where known (ref.input_indexes maps
|
|
24539
|
+
// back to the caller's lead_refs positions). Items carry the full
|
|
24540
|
+
// QualifiedLead payload when delivered/degraded, and an honest
|
|
24541
|
+
// status_reason (not_in_universe, low_confidence_identity, ...) when
|
|
24542
|
+
// skipped — a skip is an ANSWER about that ref, not an error.
|
|
24543
|
+
items: view.items,
|
|
24544
|
+
// On a duplicate submit whose indexes could not be re-pointed at this
|
|
24545
|
+
// caller's refs, input_indexes are null rather than stale — match items
|
|
24546
|
+
// by `ref.requested_as` / `lead_id` instead.
|
|
24547
|
+
input_indexes_remapped: submit.duplicate ?? false ? indexed.remapped : null,
|
|
24548
|
+
// ...and the same outcomes pre-split, because the shared
|
|
24549
|
+
// rendering/lead-delivery-table contract this tool's description
|
|
24550
|
+
// mandates reads deliveries from `leads[]` and skips from `skipped[]`.
|
|
24551
|
+
// Returning only `items` left an agent following the RENDER block with
|
|
24552
|
+
// two empty tables; the sibling tools (find_new_leads, lead_job_status)
|
|
24553
|
+
// both split. `items` stays for input-order per-ref mapping.
|
|
24554
|
+
...splitItems(view),
|
|
24555
|
+
items_truncated: snapshot.items_truncated ?? false,
|
|
24556
|
+
// Top-level, not only inside next_poll: a TERMINAL job that truncated had
|
|
24557
|
+
// next_poll null, so the rendering rule pointing at `since: next_since`
|
|
24558
|
+
// named a cursor the response did not carry.
|
|
24559
|
+
next_since: snapshot.next_since ?? null,
|
|
24560
|
+
cost: snapshot.cost,
|
|
24561
|
+
estimated_cost: submit.estimated_cost,
|
|
24562
|
+
explain: snapshot.explain,
|
|
24563
|
+
still_running: !done,
|
|
24564
|
+
// A finished job can still owe rows: truncation means the drain stopped
|
|
24565
|
+
// early, so there is a follow-up action even when done is true.
|
|
24566
|
+
next_poll: done && !(snapshot.items_truncated ?? false) ? null : {
|
|
24567
|
+
tool: "leadbay_lead_job_status",
|
|
24568
|
+
job_id: submit.job_id,
|
|
24569
|
+
// Hand the cursor forward so the follow-up poll continues
|
|
24570
|
+
// INCREMENTALLY instead of re-reading (and re-rendering) the
|
|
24571
|
+
// rows already delivered in this response.
|
|
24572
|
+
since: snapshot.next_since ?? null,
|
|
24573
|
+
suggested_wait_seconds: done ? 0 : 60
|
|
24574
|
+
},
|
|
24575
|
+
region: client.region
|
|
24576
|
+
};
|
|
24577
|
+
}
|
|
24578
|
+
};
|
|
24579
|
+
|
|
24580
|
+
// ../core/dist/composite/lead-job-status.js
|
|
24581
|
+
var leadJobStatus = {
|
|
24582
|
+
name: "leadbay_lead_job_status",
|
|
24583
|
+
annotations: {
|
|
24584
|
+
title: "Poll a lead-delivery job",
|
|
24585
|
+
readOnlyHint: true,
|
|
24586
|
+
destructiveHint: false,
|
|
24587
|
+
idempotentHint: true,
|
|
24588
|
+
openWorldHint: true
|
|
24589
|
+
},
|
|
24590
|
+
description: leadbay_lead_job_status,
|
|
24591
|
+
inputSchema: {
|
|
24592
|
+
type: "object",
|
|
24593
|
+
properties: {
|
|
24594
|
+
job_id: {
|
|
24595
|
+
type: "string",
|
|
24596
|
+
description: "The job_id returned by leadbay_find_new_leads or leadbay_qualify_leads."
|
|
24597
|
+
},
|
|
24598
|
+
since: {
|
|
24599
|
+
type: "string",
|
|
24600
|
+
description: "Opaque cursor from a previous poll's next_since \u2014 returns only items emitted after it. Omit for the full snapshot."
|
|
24601
|
+
},
|
|
24602
|
+
limit: {
|
|
24603
|
+
type: "number",
|
|
24604
|
+
description: "Items per page, 1-100 (default 100; pages are auto-collected)."
|
|
24605
|
+
},
|
|
24606
|
+
wait_seconds: {
|
|
24607
|
+
type: "number",
|
|
24608
|
+
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."
|
|
24609
|
+
}
|
|
24610
|
+
},
|
|
24611
|
+
required: ["job_id"],
|
|
24612
|
+
additionalProperties: false
|
|
24613
|
+
},
|
|
24614
|
+
execute: async (client, params, ctx) => {
|
|
24615
|
+
const waitSeconds = clampWaitSeconds(params.wait_seconds, 0);
|
|
24616
|
+
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);
|
|
24617
|
+
const done = TERMINAL_JOB_STATES.has(snapshot.job.state);
|
|
24618
|
+
const { leads, skipped } = splitItems(snapshot);
|
|
24619
|
+
return {
|
|
24620
|
+
job_id: params.job_id,
|
|
24621
|
+
state: snapshot.job.state,
|
|
24622
|
+
done,
|
|
24623
|
+
funnel: snapshot.funnel,
|
|
24624
|
+
leads,
|
|
24625
|
+
skipped,
|
|
24626
|
+
// Surfaced so the renderer never presents a partial page set as the whole
|
|
24627
|
+
// result: `leads` is a prefix, and next_since resumes it.
|
|
24628
|
+
items_truncated: snapshot.items_truncated ?? false,
|
|
24629
|
+
next_since: snapshot.next_since ?? null,
|
|
24630
|
+
cost: snapshot.cost,
|
|
24631
|
+
explain: snapshot.explain,
|
|
24632
|
+
still_running: !done,
|
|
24633
|
+
// Truncation leaves rows unread even on a finished job, so the follow-up
|
|
24634
|
+
// action survives `done` — same rule as the two submit tools.
|
|
24635
|
+
next_poll: done && !(snapshot.items_truncated ?? false) ? null : {
|
|
24636
|
+
tool: "leadbay_lead_job_status",
|
|
24637
|
+
job_id: params.job_id,
|
|
24638
|
+
// Same incremental handoff as the submit tools — following
|
|
24639
|
+
// next_poll without the cursor re-reads the rows just returned.
|
|
24640
|
+
since: snapshot.next_since ?? null,
|
|
24641
|
+
suggested_wait_seconds: done ? 0 : 60
|
|
24642
|
+
},
|
|
24643
|
+
region: client.region
|
|
24644
|
+
};
|
|
24645
|
+
}
|
|
24646
|
+
};
|
|
24647
|
+
|
|
24648
|
+
// ../core/dist/composite/extend-lens.js
|
|
24649
|
+
function httpStatus(err) {
|
|
24650
|
+
return err?._meta?.http_status;
|
|
24651
|
+
}
|
|
24652
|
+
async function readExtraRefillQuota(client) {
|
|
24653
|
+
try {
|
|
24654
|
+
const me = await client.resolveMe();
|
|
24655
|
+
const quota = await client.request("GET", `/organizations/${me.organization.id}/quota_status`);
|
|
24656
|
+
const isRefill = (r) => r.resource_type?.toUpperCase() === "LENS_EXTRA_REFILL";
|
|
24657
|
+
const entry = quota.org?.resources?.find(isRefill) ?? quota.user?.resources?.find(isRefill);
|
|
24658
|
+
return {
|
|
24659
|
+
count: entry?.count ?? null,
|
|
24660
|
+
resets_at: entry?.resets_at ?? null
|
|
24661
|
+
};
|
|
24662
|
+
} catch {
|
|
24663
|
+
return { count: null, resets_at: null };
|
|
24664
|
+
}
|
|
24665
|
+
}
|
|
24666
|
+
async function readAvailablePool(client, lensId) {
|
|
24667
|
+
try {
|
|
24668
|
+
const preview = await client.request("GET", `/lenses/${lensId}/extra_refill_preview`);
|
|
24669
|
+
return typeof preview?.available_count === "number" ? preview.available_count : null;
|
|
24670
|
+
} catch {
|
|
24671
|
+
return null;
|
|
24672
|
+
}
|
|
24673
|
+
}
|
|
24674
|
+
async function readLensLeadTotal(client, lensId) {
|
|
24675
|
+
try {
|
|
24676
|
+
const page = await client.request("GET", `/lenses/${lensId}/leads/wishlist?count=1&page=0`);
|
|
24677
|
+
return typeof page?.pagination?.total === "number" ? page.pagination.total : null;
|
|
24678
|
+
} catch {
|
|
24679
|
+
return null;
|
|
24680
|
+
}
|
|
24681
|
+
}
|
|
24682
|
+
function noCandidatesReason(held, shape) {
|
|
24683
|
+
const { geoSentence, ...extras } = shape;
|
|
24684
|
+
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.";
|
|
24685
|
+
if (held === 0) {
|
|
24686
|
+
return {
|
|
24687
|
+
code: "audience_too_narrow",
|
|
24688
|
+
retryable: false,
|
|
24689
|
+
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).",
|
|
24690
|
+
...extras
|
|
24691
|
+
};
|
|
22204
24692
|
}
|
|
22205
24693
|
if (held !== null) {
|
|
22206
24694
|
return {
|
|
@@ -23506,8 +25994,8 @@ var sendFeedback = {
|
|
|
23506
25994
|
}
|
|
23507
25995
|
},
|
|
23508
25996
|
execute: async (client, params, ctx) => {
|
|
23509
|
-
const
|
|
23510
|
-
if (!
|
|
25997
|
+
const text2 = typeof params.message === "string" ? params.message.trim() : "";
|
|
25998
|
+
if (!text2) {
|
|
23511
25999
|
return {
|
|
23512
26000
|
error: true,
|
|
23513
26001
|
code: "BAD_INPUT",
|
|
@@ -23515,7 +26003,7 @@ var sendFeedback = {
|
|
|
23515
26003
|
hint: "Ask the user what they'd like to tell the Leadbay team, then call again with their words in `message`."
|
|
23516
26004
|
};
|
|
23517
26005
|
}
|
|
23518
|
-
const message =
|
|
26006
|
+
const message = text2.length > MESSAGE_MAX2 ? `${text2.slice(0, MESSAGE_MAX2 - 1)}\u2026` : text2;
|
|
23519
26007
|
if (!ctx?.sendFeedback) {
|
|
23520
26008
|
return {
|
|
23521
26009
|
sent: false,
|
|
@@ -23646,6 +26134,13 @@ granularTools.forEach((t) => {
|
|
|
23646
26134
|
t.advanced = true;
|
|
23647
26135
|
});
|
|
23648
26136
|
var compositeReadTools = [
|
|
26137
|
+
// Poll surface for the MCP-first lead-delivery jobs (find_new_leads /
|
|
26138
|
+
// qualify_leads). Read-only snapshot of a backend-owned job. The backend
|
|
26139
|
+
// routes (`POST /1.6/mcp/search`, `POST /1.6/mcp/qualify`,
|
|
26140
|
+
// `GET /1.6/mcp/jobs/{id}`) shipped to production in backend v3.22.0
|
|
26141
|
+
// (2026-08-22) and were verified live on both regions, so the opt-in
|
|
26142
|
+
// LEADBAY_MCP_LEAD_DELIVERY flag that held these three back is gone.
|
|
26143
|
+
leadJobStatus,
|
|
23649
26144
|
pullLeads,
|
|
23650
26145
|
pullFollowups,
|
|
23651
26146
|
followupsMap,
|
|
@@ -23708,6 +26203,11 @@ var compositeReadTools = [
|
|
|
23708
26203
|
// leadbay_new_lens / leadbay_adjust_audience). Without it the agent can only
|
|
23709
26204
|
// probe sectors by trial-and-error or ask the user to read the web UI.
|
|
23710
26205
|
listSectors,
|
|
26206
|
+
// listLocations, same rationale on the geography axis. The delivery tools
|
|
26207
|
+
// reject an unresolvable filters.locations with a 400 naming the value and
|
|
26208
|
+
// send the agent here to look up the real admin area — a recovery path that
|
|
26209
|
+
// only works if the lookup is reachable without LEADBAY_MCP_ADVANCED=1.
|
|
26210
|
+
listLocations,
|
|
23711
26211
|
// Billing / top-up tools — granular-shaped but ALWAYS exposed because
|
|
23712
26212
|
// they're the canonical recovery path from a QUOTA_EXCEEDED wall. If
|
|
23713
26213
|
// they were gated behind LEADBAY_MCP_ADVANCED=1 the agent would
|
|
@@ -23737,7 +26237,21 @@ var compositeReadTools = [
|
|
|
23737
26237
|
// tools/) so it carries no _triggered_by mandate for a kit fetch.
|
|
23738
26238
|
artifactKit
|
|
23739
26239
|
];
|
|
26240
|
+
var mcpFirstDeliveryTools = [
|
|
26241
|
+
// Write-tier: submits create server-side jobs that can spend money
|
|
26242
|
+
// (qualification research, channel purchase) and claim novelty in the
|
|
26243
|
+
// org's delivery ledger — same posture as the other spending composites.
|
|
26244
|
+
// The FREE tier (qualify:false, channels:[]) is the default ask, and a paid
|
|
26245
|
+
// call is withheld in code until `confirm: true`.
|
|
26246
|
+
findNewLeads,
|
|
26247
|
+
qualifyLeads
|
|
26248
|
+
];
|
|
26249
|
+
var mcpFirstDeliveryAllTools = [
|
|
26250
|
+
...mcpFirstDeliveryTools,
|
|
26251
|
+
leadJobStatus
|
|
26252
|
+
];
|
|
23740
26253
|
var compositeWriteTools = [
|
|
26254
|
+
...mcpFirstDeliveryTools,
|
|
23741
26255
|
bulkQualifyLeads,
|
|
23742
26256
|
enrichTitles,
|
|
23743
26257
|
adjustAudience,
|
|
@@ -24598,8 +27112,22 @@ function buildProtocolPrimitivesParagraph(has) {
|
|
|
24598
27112
|
"import_and_qualify",
|
|
24599
27113
|
"enrich_titles",
|
|
24600
27114
|
"bulk_enrich_status",
|
|
24601
|
-
"qualify_status"
|
|
27115
|
+
"qualify_status",
|
|
27116
|
+
// The MCP-first delivery jobs block-poll for 45s by default and up to
|
|
27117
|
+
// 180s. Without a progressToken ctx.progress is absent, so the call looks
|
|
27118
|
+
// frozen for minutes — the exact case this paragraph exists to prevent.
|
|
27119
|
+
// `.filter(has)` keeps the iter-12 invariant: a deployment without the
|
|
27120
|
+
// delivery flag never sees them named.
|
|
27121
|
+
"find_new_leads",
|
|
27122
|
+
"qualify_leads",
|
|
27123
|
+
"lead_job_status"
|
|
24602
27124
|
].filter((n) => has(`leadbay_${n}`));
|
|
27125
|
+
const legacyRunners = longRunners.filter(
|
|
27126
|
+
(n) => !["find_new_leads", "qualify_leads", "lead_job_status"].includes(n)
|
|
27127
|
+
);
|
|
27128
|
+
const deliveryRunners = longRunners.filter(
|
|
27129
|
+
(n) => ["find_new_leads", "qualify_leads", "lead_job_status"].includes(n)
|
|
27130
|
+
);
|
|
24603
27131
|
const elicitTools = [
|
|
24604
27132
|
"refine_prompt clarifications",
|
|
24605
27133
|
"report_outreach.user_confirmed"
|
|
@@ -24618,9 +27146,20 @@ function buildProtocolPrimitivesParagraph(has) {
|
|
|
24618
27146
|
"(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
27147
|
);
|
|
24620
27148
|
}
|
|
24621
|
-
if (
|
|
27149
|
+
if (legacyRunners.length > 0 || deliveryRunners.length > 0) {
|
|
27150
|
+
const clauses = [];
|
|
27151
|
+
if (legacyRunners.length > 0) {
|
|
27152
|
+
clauses.push(
|
|
27153
|
+
"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."
|
|
27154
|
+
);
|
|
27155
|
+
}
|
|
27156
|
+
if (deliveryRunners.length > 0) {
|
|
27157
|
+
clauses.push(
|
|
27158
|
+
"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."
|
|
27159
|
+
);
|
|
27160
|
+
}
|
|
24622
27161
|
parts.push(
|
|
24623
|
-
"(2) `notifications/cancelled` \u2014 when the user clicks Cancel in the host UI, the polling loop exits within \u22642 seconds.
|
|
27162
|
+
"(2) `notifications/cancelled` \u2014 when the user clicks Cancel in the host UI, the polling loop exits within \u22642 seconds. " + clauses.join(" ")
|
|
24624
27163
|
);
|
|
24625
27164
|
} else {
|
|
24626
27165
|
parts.push(
|
|
@@ -24827,11 +27366,16 @@ function buildServer(client, opts = {}) {
|
|
|
24827
27366
|
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
24828
27367
|
tools: toolsListPayload([...toolByName.values()])
|
|
24829
27368
|
}));
|
|
27369
|
+
const promptGate = { includeWrite: Boolean(opts.includeWrite) };
|
|
24830
27370
|
server.setRequestHandler(ListPromptsRequestSchema, async () => ({
|
|
24831
|
-
prompts: listPrompts()
|
|
27371
|
+
prompts: listPrompts(promptGate)
|
|
24832
27372
|
}));
|
|
24833
27373
|
server.setRequestHandler(GetPromptRequestSchema, async (req) => {
|
|
24834
|
-
return getPrompt(
|
|
27374
|
+
return getPrompt(
|
|
27375
|
+
req.params.name,
|
|
27376
|
+
req.params.arguments ?? {},
|
|
27377
|
+
promptGate
|
|
27378
|
+
);
|
|
24835
27379
|
});
|
|
24836
27380
|
server.setRequestHandler(ListResourcesRequestSchema, async () => ({
|
|
24837
27381
|
resources: listResources()
|
|
@@ -25568,7 +28112,7 @@ function parseWriteEnv(env = process.env) {
|
|
|
25568
28112
|
}
|
|
25569
28113
|
|
|
25570
28114
|
// src/http-server.ts
|
|
25571
|
-
var VERSION = true ? "0.
|
|
28115
|
+
var VERSION = true ? "0.37.0" : "0.0.0-dev";
|
|
25572
28116
|
var PORT = Number(process.env.PORT ?? 8080);
|
|
25573
28117
|
var HOST = process.env.HOST ?? "0.0.0.0";
|
|
25574
28118
|
var logger = {
|