@leadbay/mcp 0.31.0 → 0.32.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.
@@ -1167,7 +1167,7 @@ Build the final mappings yourself. Start from \`leadbay_resolve_import_rows.mapp
1167
1167
 
1168
1168
  # PHASE 5 \u2014 QUALIFY (optional) + REPORT
1169
1169
 
1170
- Prefer \`leadbay_import_and_qualify\` when the user asks to qualify/research after import; otherwise use \`leadbay_import_leads\`. For large files or short client timeouts, pass \`wait_for_completion=false\` and poll \`leadbay_import_status\`. After import, qualify only lead IDs returned by the import. Rows that came back \`uncrawled\` are pending a background crawl (not failures); the leads Leadbay adds for them populate in the user's Leadbay account as the crawl completes \u2014 tell the user that, not that a tool call will fetch them (\`import_status\` refreshes status/progress only; \`pull_leads\` reads the active lens, so an imported lead outside it may not appear; re-running the import later re-reconciles those companies).
1170
+ Prefer \`leadbay_import_and_qualify\` when the user asks to qualify/research after import; otherwise use \`leadbay_import_leads\`. For large files or short client timeouts, pass \`wait_for_completion=false\` and poll \`leadbay_import_status\`. After import, qualify only lead IDs returned by the import. Rows that came back \`uncrawled\` are pending a background crawl (not failures); the leads Leadbay adds for them populate in the user's Leadbay account as the crawl completes \u2014 tell the user that, not that a tool call will fetch them (\`import_status\` reports the rows the wizard already placed, not leads a later crawl adds; \`pull_leads\` reads the active lens, so an imported lead outside it may not appear; re-running the import later re-reconciles those companies).
1171
1171
 
1172
1172
  **Deliver the augmented file back to the user**: the original file plus a new \`LEADBAY_ID\` column populated from the resolution step. This is the second deliverable of a job well done.
1173
1173
 
@@ -1732,10 +1732,17 @@ Research the company name or domain '{{arg:domain}}' for me using Leadbay.
1732
1732
 
1733
1733
  # PHASE 1 \u2014 RESOLVE + DEEP DIVE
1734
1734
  Call \`leadbay_research_lead_by_name_fuzzy\` with
1735
- \`companyName:'{{arg:domain}}'\`. Omit \`lensId\`: the default search deliberately
1736
- covers the user's visible Discover, Monitor, and Activate corpus, including
1737
- other lenses and leads outside the active lens's first page. The composite
1738
- resolves the lead and returns the full deep-research payload in one call.
1735
+ \`companyName:'{{arg:domain}}'\`. If the user gave a domain or a contact email
1736
+ anywhere in the conversation, also pass \`website\` (or \`email\`) \u2014 that is the
1737
+ match key that finds a company they do not own yet. Omit \`lensId\`: the default
1738
+ search covers the user's visible Discover, Monitor, and Activate corpus \u2014
1739
+ including other lenses and leads outside the active lens's first page \u2014 and
1740
+ then the Leadbay company registry. The composite resolves the lead and returns
1741
+ the full deep-research payload in one call.
1742
+
1743
+ If it returns \`{resolution:"ambiguous"}\`, several companies match. Ask the user
1744
+ which one via \`ask_user_input_v0\`, then call \`leadbay_research_lead_by_id\` with
1745
+ the leadId they pick.
1739
1746
 
1740
1747
  Render the result using the canonical single-record card layout \u2014 detect MODE A
1741
1748
  (Discovery) since the user asked to research a company rather than prepare
@@ -1812,10 +1819,14 @@ When the response carries \`social_urls\` (the post-fix multi-platform URL block
1812
1819
 
1813
1820
 
1814
1821
  # PHASE 2 \u2014 NOT FOUND
1815
- If the resolver returns \`LEAD_NOT_FOUND\`, say that the existing visible corpus
1816
- was searched. **Do NOT call \`leadbay_import_and_qualify\` automatically.** Offer
1817
- to import and qualify the company as a separate, explicit next step; only call
1818
- it after the user agrees.
1822
+ If the resolver returns \`LEAD_NOT_FOUND\`, read its hint: it names the field
1823
+ that would have found the company (\`would_help\`, usually \`website\`). **Ask the
1824
+ user for that field first** \u2014 "what's their website?" \u2014 and call the tool again
1825
+ with it. Only when they cannot supply it should you say both their leads and
1826
+ the Leadbay registry were searched.
1827
+ **Do NOT call \`leadbay_import_and_qualify\` automatically.**
1828
+ Offer to import and qualify as a separate, explicit next step; only call it
1829
+ after the user agrees.
1819
1830
 
1820
1831
  # PHASE 3 \u2014 SUMMARY
1821
1832
  Place a 2\u20133 sentence summary ABOVE the card with:
@@ -8575,7 +8586,7 @@ The model \u2014 two layers. Primitives: \`lb.field\` (value + API-populated opt
8575
8586
 
8576
8587
  Canonical uses: a cold-call sheet (\`lb.callList\` + per-row \`lb.outreach\`/\`lb.leadHistory\`); a manager dashboard (\`lb.teamActivity\` \u2192 leaderboard table + Chart.js trend); a live enrichment view (\`lb.enrichment\` \u2192 progress + refresh). Live auto-poll is host-dependent \u2014 always wire a Refresh.
8577
8588
 
8578
- Write-call footguns (in the guide, repeated because they bite): for \`leadbay_report_outreach\` (status/disposition) the \`args\` MUST include \`verification:{source:"user_confirmed",ref:"\u2026"}\` AND \`_triggered_by:"<the user's request>"\`, or the call is rejected. \`leadbay_add_leads_to_campaign\` needs \`_triggered_by\` too. \`leadbay_add_note\`/\`leadbay_like_lead\`/\`leadbay_dislike_lead\` need only their own args. Snoozing (pushback) and standalone status are advanced-gated \u2014 not callable from a default artifact; use \`report_outreach\`'s \`epilogue_status\` for outcomes.
8589
+ Write-call footguns (in the guide, repeated because they bite): for \`leadbay_report_outreach\` (status/disposition) the \`args\` MUST include \`verification:{source:"user_confirmed",ref:"\u2026"}\` AND \`_triggered_by:"<the user's request>"\`, or the call is rejected. \`leadbay_add_leads_to_campaign\` needs \`_triggered_by\` too. \`leadbay_add_note\`/\`leadbay_like_lead\`/\`leadbay_dislike_lead\` need only their own args. Snoozing (pushback) is advanced-gated \u2014 not callable from a default artifact. Org CRM status IS available: \`lb.leadStatus()\` gives the Wanted/Won/Lost/Unwanted picker field and \`lb.setStatus()\` the write (\`leadbay_set_lead_status\`), with the partial-write check baked in. Keep it distinct from \`report_outreach\`'s \`epilogue_status\`, which records how one outreach ATTEMPT went.
8579
8590
 
8580
8591
  WHEN TO USE: the user asks for a clickable / interactive artifact, dashboard, or call sheet that DOES things (not just displays data).
8581
8592
 
@@ -9160,8 +9171,10 @@ Examples that should NOT invoke this tool (sound similar, route elsewhere):
9160
9171
 
9161
9172
  \`queued\` \u2192 \u2705 "Queued <N> extra leads on lens <id>. Pull in ~30s." Do NOT
9162
9173
  list \`accepted_seeds\`; they're internal.
9163
- \`quota_exceeded\` \u2192 render three options via your host's choice widget (\`ask_user_input_v0\` or \`AskUserQuestion\`) (smaller
9164
- count / wait until reset / upgrade).
9174
+ \`no_candidates\` \u2192 \u26D4 surface \`reason.message\`, name the criteria, offer
9175
+ \`leadbay_adjust_audience\`. Never re-call this tool on that lens.
9176
+ \`quota_exceeded\` \u2192 three options via the host's choice widget
9177
+ (smaller count / wait for reset / upgrade).
9165
9178
  \`refresh_in_progress\` \u2192 "lens is filling, retry in a minute".
9166
9179
  \`no_valid_seeds\` \u2192 silently re-call \`leadbay_seed_candidates\`, retry once.
9167
9180
 
@@ -9181,6 +9194,9 @@ Queue an additive extra-refill on a lens \u2014 more leads on the same criteria,
9181
9194
  - \`status: "quota_exceeded"\` \u2014 daily LENS_EXTRA_REFILL hit. Response carries \`quota: {used_today, resets_at}\` + a \`message\` to surface. **Render three options via your host's choice widget (\`ask_user_input_v0\` or \`AskUserQuestion\`)**: (1) smaller \`extra_count\`, (2) wait until \`resets_at\`, (3) upgrade plan (TIER1=150, TIER2=1000). Do NOT silently retry.
9182
9195
  - \`status: "refresh_in_progress"\` \u2014 a refresh or extra-refill is already running. Tell the user to wait and call \`leadbay_pull_leads\` in ~30s.
9183
9196
  - \`status: "no_valid_seeds"\` \u2014 seeds went stale. Silently re-call \`leadbay_seed_candidates\` and retry once; only surface to the user if the second attempt also fails.
9197
+ - \`status: "no_candidates"\` \u2014 **the refill was NOT queued.** The lens's candidate pool is empty, so a refill would report success, consume no quota and deliver nothing. \`reason\` carries the same \`{code, message, retryable, criteria?, narrow_locations?}\` shape \`leadbay_pull_leads\` returns in \`empty_reason\`, with \`retryable: false\`. **Stop. Do not re-call this tool on this lens** \u2014 the outcome cannot change until the audience changes. Surface \`reason.message\`, name the criteria in play, and offer \`leadbay_adjust_audience\` (or \`leadbay_pull_followups\` when \`reason.code\` is \`no_new_leads\` and the lens already holds leads).
9198
+
9199
+ **Extendability is checked before the write.** Every response carries \`available_count\` \u2014 how many leads a refill could still draw, read from the lens's own pool. \`0\` means the call was refused (\`no_candidates\`); \`null\` means the pool could not be read and the refill was queued anyway. An empty lens is NOT evidence of a broken refill: it is usually a lens that never had candidates. Reach for \`leadbay_adjust_audience\`, not another \`leadbay_extend_lens\`.
9184
9200
 
9185
9201
  WHEN TO USE: when the user has a bigger appetite than the daily lens fill delivers \u2014 they want MORE of the same kind of leads, on demand. Canonical phrasings: "I want more leads on this lens", "extend the lens", "give me a bigger batch today". The \`leadbay_extend_my_lens\` prompt is the user-facing entry point that orchestrates the whole flow.
9186
9202
 
@@ -9221,6 +9237,8 @@ Pick the row matching the response \`status\`. Seed-picking is internal; do NOT
9221
9237
  | \`quota_exceeded\` | "Upgrade plan for a higher daily limit" | (no call \u2014 direct user to contact account manager / sales) |
9222
9238
  | \`refresh_in_progress\` | "Lens is already filling \u2014 pull leads in a minute" | \`leadbay_pull_leads()\` (after a short wait) |
9223
9239
  | \`no_valid_seeds\` | (silent retry \u2014 re-call \`leadbay_seed_candidates\` then \`leadbay_extend_lens\`) | internal \u2014 only surface if the second attempt also fails |
9240
+ | \`no_candidates\` | "Widen the audience \u2014 this lens has nothing left to add" | \`leadbay_adjust_audience()\` \u2014 never \`leadbay_extend_lens\` again |
9241
+ | \`no_candidates\` (\`reason.code: no_new_leads\`) | "Work the leads already in the lens" | \`leadbay_pull_followups()\` |
9224
9242
 
9225
9243
  If nothing matches cleanly, default to "pull leads now to see what's queued" \u2014 never invent a tool that doesn't exist.
9226
9244
  `;
@@ -9426,9 +9444,31 @@ WHEN NOT TO USE: to answer the question \u2014 use leadbay_answer_clarification.
9426
9444
  `;
9427
9445
  var leadbay_get_contacts = `Get contacts for a lead, including enriched email and phone data. Returns both organization contacts and enrichable contacts with IDs, tagged with \`source:'org'|'paid'\`.
9428
9446
 
9429
- WHEN TO USE: to check enrichment status (\`contact.enrichment.done\`) on individual leads after a bulk enrichment was launched, or to find the \`contact_id\` needed by leadbay_enrich_contacts.
9447
+ WHEN TO USE: to check enrichment status (\`contact.enrichment\`) on individual leads after a bulk enrichment was launched, or to find the \`contact_id\` needed by leadbay_enrich_contacts.
9430
9448
 
9431
9449
  WHEN NOT TO USE: as a substitute for leadbay_research_lead_by_id, which already includes enriched contacts in its return.
9450
+
9451
+ ## Reading \`contact.enrichment\`
9452
+
9453
+ \`enrichment\` is the per-contact reveal record. Four states. Read \`done\` and \`credits_used\` **together** \u2014 neither is a verdict on its own.
9454
+
9455
+ | \`enrichment\` | \`done\` | \`credits_used\` | Meaning | What to do |
9456
+ |---|---|---|---|---|
9457
+ | missing / \`null\` | \u2014 | \u2014 | Never requested. | Enrichable \u2014 launch it. |
9458
+ | present | \`false\` | any | Reservation in flight. | Poll. Do NOT re-launch. |
9459
+ | present | \`true\` | \`0\` | Settled, found nothing. | **Terminal. Stop.** |
9460
+ | present | \`true\` | \`> 0\` | Resolved. | The channel is on the org-source twin, not here \u2014 see below. |
9461
+
9462
+ **\`done: true\` with \`credits_used: 0\` is terminal for that contact.** The enrichment completed and the provider returned nothing. Do not re-attempt it on a later run \u2014 the answer will not change. Roughly 29% of all enrichments land here, so it is an ordinary outcome, not an anomaly. Tell the user plainly that there is no reachable contact rather than reporting it as still pending. The one exception: a launch that errored in this same session settles its reservation as a zero-credit failure, so retry that one once, then treat it as terminal.
9463
+
9464
+ Two ways to misread the pair:
9465
+
9466
+ - **\`credits_used: 0\` alone means nothing.** An in-flight reservation also reports \`0\` (with \`done: false\`). Gate every read of \`credits_used\` on \`done: true\`.
9467
+ - **An absent \`credits_used\` is unknown, not zero.** The field is optional. When it is missing you cannot conclude terminal-empty \u2014 only an explicit \`0\` alongside \`done: true\` means "we looked and found nothing".
9468
+
9469
+ A missing or \`null\` \`enrichment\` is not the same as \`done: false\`. It means the contact was never requested, so \`enrichment?.done\` reading falsy does NOT mean a reveal is running. Treat missing/\`null\` as enrichable and \`done: false\` as in-flight.
9470
+
9471
+ **Where a resolved channel lands.** A \`source:'paid'\` contact keeps its \`enrichment\` record but never carries the revealed \`email\` / \`phone_number\` itself \u2014 the reveal materializes a \`source:'org'\` twin of the same person, and the channel is on that entry. So a paid contact reading \`done: true, credits_used: 1\` with a null \`email\` is RESOLVED, not failed: find the org-source entry with the same name and read the channel there. Judge success by the channel you can actually see across both entries, never by \`enrichment\` on the paid record alone.
9432
9472
  `;
9433
9473
  var leadbay_get_enrichment_job_titles = `List the actual job titles present across the leads currently in the user's selection \u2014 the candidate set the user can ask to enrich.
9434
9474
 
@@ -9743,7 +9783,7 @@ WHEN NOT TO USE: discovery (use leadbay_pull_leads); single-lead deep dive (use
9743
9783
 
9744
9784
  Budgets: \`total_budget_ms\` caps wall-clock; \`per_lead_budget_ms\` caps each lead's poll. For short transport timeouts, pass \`wait_for_completion:false\` and poll \`leadbay_import_status\`. Outputs \`qualified[]\`, \`still_running[]\`, \`not_imported[]\`, \`qualify_id\` (resumable handle). Idempotent within a 5-min window. \`dry_run:'preview'\` returns mapping hints + custom-field candidates without importing.
9745
9785
 
9746
- \`not_imported\` rows with \`reason:"uncrawled"\` are **pending a background crawl**, NOT failures: Leadbay just hasn't matched/crawled that domain yet and will add the lead asynchronously (the label doesn't verify the URL resolves \u2014 don't call the site bad, but don't certify it valid either). Surface them as pending; the leads populate in the user's Leadbay account as the crawl completes (no tool here fetches them on demand \u2014 \`leadbay_import_status\` returns status/progress only, and \`leadbay_pull_leads\` reads the active lens's wishlist so an imported lead outside that lens may not appear). To pull those specific companies back through the MCP, re-run the import later. A large \`uncrawled\` share on a fresh list is normal.
9786
+ \`not_imported\` rows with \`reason:"uncrawled"\` are **pending a background crawl**, NOT failures: Leadbay just hasn't matched/crawled that domain yet and will add the lead asynchronously (the label doesn't verify the URL resolves \u2014 don't call the site bad, but don't certify it valid either). Surface them as pending; the leads populate in the user's Leadbay account as the crawl completes (no tool here fetches them on demand \u2014 \`leadbay_import_status\` reports the rows the wizard has already placed, not leads a later crawl adds, and \`leadbay_pull_leads\` reads the active lens's wishlist so an imported lead outside that lens may not appear). To pull those specific companies back through the MCP, re-run the import later. A large \`uncrawled\` share on a fresh list is normal.
9747
9787
 
9748
9788
  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\`.
9749
9789
 
@@ -9768,7 +9808,8 @@ Otherwise, partition \`not_imported\` by \`reason\` into these buckets before yo
9768
9808
  **Header \u2014 single line, choose by status:**
9769
9809
 
9770
9810
  - Completed: \`"\u2713 Import complete \u2014 N imported \xB7 P pending crawl \xB7 Q need attention"\` (drop any segment whose count is 0)
9771
- - Running: \`"\u23F3 Import running \u2014 handle_id <id>; poll leadbay_import_status"\`
9811
+ - Running, \`handle_id\` present: \`"\u23F3 Import running \u2014 handle_id <id>; poll leadbay_import_status"\`
9812
+ - Running with \`timed_out:true\` (blocking call ran out of poll budget): the import is FINE and still running server-side \u2014 never render this as an error or a failure. \`"\u23F3 Import still running (the backend is slow today) \u2014 I'll check back."\` Then call \`leadbay_import_status({importIds})\`, do NOT re-run leadbay_import_leads. If \`rows_pending_upload\` is present, add \`"\u26A0 K rows weren't submitted \u2014 re-import just those."\`
9772
9813
  - Pending qualification (\`leadbay_import_and_qualify\`): \`"\u2713 Imported N leads \xB7 qualifying M of them \u2014 qualify_id <id>"\`
9773
9814
 
9774
9815
  Count \`uncrawled\` rows as **pending**, never as failures \u2014 never say "M failed" when the M is mostly/entirely uncrawled rows.
@@ -9817,7 +9858,9 @@ User picks \u2192 call the matching \`Calls\` tool. Constraints: 2\u20134 mutual
9817
9858
 
9818
9859
  | Observation | Suggest | Calls |
9819
9860
  |------------------------------------------------|---------------------------------------------------------------|--------------------------------------------------------|
9820
- | Status: running | "Check progress" | leadbay_import_status(handle_id) |
9861
+ | Status: running, \`handle_id\` present | "Check progress" | leadbay_import_status(handle_id) |
9862
+ | Status: running with \`timed_out:true\` | "Check progress" \u2014 NOT "retry the import" | leadbay_import_status(importIds, dry_run if the result carried it) after ~30s; \`result.leads\` carries the leadIds once complete |
9863
+ | \`rows_pending_upload\` present | "Import the rows that never got submitted" | leadbay_import_leads (that subset only) |
9821
9864
  | Status: complete, imports succeeded | "Run AI qualification on the imported leads" | leadbay_bulk_qualify_leads([leadIds]) \u2014 or use leadbay_import_and_qualify next time |
9822
9865
  | Pending-crawl (\`uncrawled\`) rows present | "Re-run the import for those domains later, once Leadbay has crawled them" | leadbay_import_leads (re-run with just the uncrawled domains, later \u2014 they re-reconcile once crawled). NOTE: not a live-fetch of the added leads; those populate in the user's Leadbay account as the crawl completes |
9823
9866
  | Ambiguous / unresolved rows present | "Resolve the ambiguous rows" | leadbay_resolve_import_rows(records, identity_mappings)|
@@ -9827,9 +9870,11 @@ User picks \u2192 call the matching \`Calls\` tool. Constraints: 2\u20134 mutual
9827
9870
  `;
9828
9871
  var leadbay_import_leads = `Import leads into Leadbay's CRM via the file-import wizard. Returns stable Leadbay leadIds for downstream chaining into leadbay_bulk_qualify_leads / leadbay_research_lead_by_id. For MCP clients with short transport timeouts, pass \`wait_for_completion:false\` to return quickly with \`{status:'running', handle_id}\`; poll leadbay_import_status with that handle. For end-to-end import+qualify in one call, prefer leadbay_import_and_qualify. For messy files, prefer the \`leadbay_import_file\` prompt which walks an agent through scan \u2192 resolve \u2192 preserve \u2192 commit phases.
9829
9872
 
9873
+ SLOW BACKEND \u21D2 \`{status:'running', timed_out:true, importIds}\`. The wizard is sometimes slow; when the poll budget runs out this tool returns that SUCCESS result, not an error. The import is still running server-side. **Do NOT call leadbay_import_leads again** \u2014 that re-uploads the file and leaves a duplicate CRM-imports row. Call \`leadbay_import_status({importIds})\` after ~30s \u2014 and pass \`dry_run:true\` too if the result carried it; on \`complete\` it returns \`result.leads\` with the leadIds, while \`phase:"committing"\` just means keep polling. Tell the user it's running and you'll check back \u2014 it is not a problem to report. Exception: \`rows_pending_upload\` rows never reached the backend and DO need a fresh call for that subset only. In records mode the result also carries \`row_ids\` \u2014 the synthetic id of each input row, in your \`records[]\` order \u2014 because \`leadbay_import_status\` reports recovered leads by that id; keep it to map them back to your source rows.
9874
+
9830
9875
  TWO MODES: (A) Domain-list shortcut \u2014 pass \`domains: [{domain, name?}]\`. The tool builds a 2-column CSV (LEAD_NAME, LEAD_WEBSITE) and imports with the default mapping. (B) Custom records + mapping \u2014 pass \`records: [{Col1, Col2, ...}]\` plus \`mappings.fields: {Col1: 'LEAD_NAME', ...}\`. \`mappings.fields\` must include LEADBAY_ID, CRM_ID, SIREN, LEAD_NAME, or LEAD_WEBSITE (resolver needs at least one identity key). Pass exactly one of \`domains\` / \`records\`. Reserved column \`MCP_ROW_ID\` cannot appear in records/mappings \u2014 the tool injects it for stable reconciliation.
9831
9876
 
9832
- \`not_imported\` rows with \`reason:"uncrawled"\` are **pending a background crawl**, NOT failures: Leadbay just hasn't matched/crawled that domain yet and will add the lead asynchronously (the label doesn't verify the URL resolves \u2014 don't call the site bad, but don't certify it valid either). Surface them as pending; the leads populate in the user's Leadbay account as the crawl completes (no tool here fetches them on demand \u2014 \`leadbay_import_status\` returns status/progress only, and \`leadbay_pull_leads\` reads the active lens's wishlist so an imported lead outside that lens may not appear). To pull those specific companies back through the MCP, re-run the import later. A large \`uncrawled\` share on a fresh list is normal.
9877
+ \`not_imported\` rows with \`reason:"uncrawled"\` are **pending a background crawl**, NOT failures: Leadbay just hasn't matched/crawled that domain yet and will add the lead asynchronously (the label doesn't verify the URL resolves \u2014 don't call the site bad, but don't certify it valid either). Surface them as pending; the leads populate in the user's Leadbay account as the crawl completes (no tool here fetches them on demand \u2014 \`leadbay_import_status\` reports the rows the wizard has already placed, not leads a later crawl adds, and \`leadbay_pull_leads\` reads the active lens's wishlist so an imported lead outside that lens may not appear). To pull those specific companies back through the MCP, re-run the import later. A large \`uncrawled\` share on a fresh list is normal.
9833
9878
 
9834
9879
  MUTATES USER STATE: each call creates a row in the user's CRM-imports list (visible in the web UI) and touches onboarding state. Suitable for occasional automation, NOT for high-cadence (>5 calls/day). Imported leads are NOT auto-promoted to the user's Monitor view; lens-scoring threshold decides. For messy files call leadbay_resolve_import_rows first, then pass \`records_for_import\`/\`mappings_for_import\` here. Agents should inspect every column, build a preservation plan, and pass an explicit final mapping. For each meaningful column decide standard field, CONTACT_* field, Leadbay note, custom field, derived helper, or skip with a reason. For contact-only exports, derive a company-domain column from CONTACT_EMAIL only when it's a real business domain. Multiple rows can share the same LEADBAY_ID and import as separate contacts on that lead. Custom fields use \`CUSTOM.<id>\` in \`mappings.fields\` or the \`mappings.custom_fields\` shorthand. For source-system deep links create a custom field via leadbay_create_custom_field first (prefer EXTERNAL_ID + url_template). Preserve meaningful per-lead notes by calling leadbay_add_note after import returns lead IDs.
9835
9880
 
@@ -9860,7 +9905,8 @@ Otherwise, partition \`not_imported\` by \`reason\` into these buckets before yo
9860
9905
  **Header \u2014 single line, choose by status:**
9861
9906
 
9862
9907
  - Completed: \`"\u2713 Import complete \u2014 N imported \xB7 P pending crawl \xB7 Q need attention"\` (drop any segment whose count is 0)
9863
- - Running: \`"\u23F3 Import running \u2014 handle_id <id>; poll leadbay_import_status"\`
9908
+ - Running, \`handle_id\` present: \`"\u23F3 Import running \u2014 handle_id <id>; poll leadbay_import_status"\`
9909
+ - Running with \`timed_out:true\` (blocking call ran out of poll budget): the import is FINE and still running server-side \u2014 never render this as an error or a failure. \`"\u23F3 Import still running (the backend is slow today) \u2014 I'll check back."\` Then call \`leadbay_import_status({importIds})\`, do NOT re-run leadbay_import_leads. If \`rows_pending_upload\` is present, add \`"\u26A0 K rows weren't submitted \u2014 re-import just those."\`
9864
9910
  - Pending qualification (\`leadbay_import_and_qualify\`): \`"\u2713 Imported N leads \xB7 qualifying M of them \u2014 qualify_id <id>"\`
9865
9911
 
9866
9912
  Count \`uncrawled\` rows as **pending**, never as failures \u2014 never say "M failed" when the M is mostly/entirely uncrawled rows.
@@ -9909,7 +9955,9 @@ User picks \u2192 call the matching \`Calls\` tool. Constraints: 2\u20134 mutual
9909
9955
 
9910
9956
  | Observation | Suggest | Calls |
9911
9957
  |------------------------------------------------|---------------------------------------------------------------|--------------------------------------------------------|
9912
- | Status: running | "Check progress" | leadbay_import_status(handle_id) |
9958
+ | Status: running, \`handle_id\` present | "Check progress" | leadbay_import_status(handle_id) |
9959
+ | Status: running with \`timed_out:true\` | "Check progress" \u2014 NOT "retry the import" | leadbay_import_status(importIds, dry_run if the result carried it) after ~30s; \`result.leads\` carries the leadIds once complete |
9960
+ | \`rows_pending_upload\` present | "Import the rows that never got submitted" | leadbay_import_leads (that subset only) |
9913
9961
  | Status: complete, imports succeeded | "Run AI qualification on the imported leads" | leadbay_bulk_qualify_leads([leadIds]) \u2014 or use leadbay_import_and_qualify next time |
9914
9962
  | Pending-crawl (\`uncrawled\`) rows present | "Re-run the import for those domains later, once Leadbay has crawled them" | leadbay_import_leads (re-run with just the uncrawled domains, later \u2014 they re-reconcile once crawled). NOTE: not a live-fetch of the added leads; those populate in the user's Leadbay account as the crawl completes |
9915
9963
  | Ambiguous / unresolved rows present | "Resolve the ambiguous rows" | leadbay_resolve_import_rows(records, identity_mappings)|
@@ -9917,7 +9965,7 @@ User picks \u2192 call the matching \`Calls\` tool. Constraints: 2\u20134 mutual
9917
9965
  | User wants to see the imported leads | "See the imported leads in your view" | leadbay_pull_leads |
9918
9966
  | User had follow-up intent for the imports | "Prep outreach for [a specific imported lead]" | leadbay_prepare_outreach(leadId) |
9919
9967
  `;
9920
- var leadbay_import_status = `Retrieve the current **status/progress** of a lead import. Pass \`handle_id\` \u2014 returned by either \`leadbay_import_leads\` OR \`leadbay_import_and_qualify\` when called with \`wait_for_completion:false\` \u2014 to resolve the stored result (leads + not_imported) once that async run has completed in this MCP instance. **If you were given a \`handle_id\`, poll with it, not with \`importIds[]\`** \u2014 only the \`handle_id\` path returns the stored result/not_imported breakdown. Pass \`importIds[]\` (a completed import returns \`importIds\`; \`leadbay_import_and_qualify\` returns \`import_ids\`) only when you don't have a handle, to refresh the backend wizard rows' phase + record counts. Note: the \`importIds[]\` path returns status/progress only \u2014 it does NOT re-reconcile records or return refreshed leads/not_imported. This status call performs a single refresh pass and never polls in a loop.
9968
+ var leadbay_import_status = `Retrieve the current **status/progress** of a lead import, and its leadIds once it finishes. Pass \`handle_id\` \u2014 returned by either \`leadbay_import_leads\` OR \`leadbay_import_and_qualify\` when called with \`wait_for_completion:false\` \u2014 to resolve the stored result (leads + not_imported) for that async run. Pass \`importIds[]\` when you don't have a handle: after a blocking \`leadbay_import_leads\` returned \`{status:'running', timed_out:true, importIds}\`, or from any completed import's \`importIds\` (\`leadbay_import_and_qualify\` calls the same field \`import_ids\`). **Both paths return leads.** The \`importIds[]\` path reads the wizard's records directly, so once every named import is \`complete\` (and it wasn't a dry run) the response carries \`result.leads\` + \`result.not_imported\` \u2014 that is how you recover the leadIds from an import that timed out mid-poll, without re-importing. \`result.still_settling\` counts rows the wizard hasn't finished placing; they are neither imported nor failed, so poll again rather than reporting them. If \`result\` is absent on a \`complete\` import the records weren't readable \u2014 report completion without inventing counts. \`phase:"committing"\` means the import is still being committed, NOT that it finished with nothing: keep polling. Pass \`dry_run:true\` when the importIds came from a dry run (a \`{timed_out:true}\` result carries \`dry_run\` \u2014 hand it straight back); a finished dry run and an import mid-commit are identical on the wire, so without that flag this tool reports \`committing\` rather than risk rendering a validation pass as a real import. This status call performs a single refresh pass and never polls in a loop.
9921
9969
 
9922
9970
  WHEN TO USE: after an async import (\`leadbay_import_leads\` OR \`leadbay_import_and_qualify\` with \`wait_for_completion:false\`) returns \`{status:'running', handle_id}\`, poll with that \`handle_id\`; OR to check whether a finished import is still processing. This tool does NOT surface the leads Leadbay adds later for pending-crawl (\`uncrawled\`) rows \u2014 those populate in the user's Leadbay account as the crawl completes; no tool here fetches them on demand (re-run the import to pull them back through the MCP).
9923
9971
 
@@ -9941,12 +9989,14 @@ After the status line, propose the obvious refresh / progress-check / recovery a
9941
9989
 
9942
9990
  Specifically for import status:
9943
9991
 
9944
- This tool returns \`status\`, \`importIds\`, and \`progress\` ({phase, records_processed, records_total}). It carries a \`result\` object (with \`leads\` + \`not_imported\`) ONLY when resolving an async \`handle_id\` whose run completed in this MCP instance \u2014 the \`importIds[]\` status-check path does NOT return \`result\`. **Render only from the fields actually present; never invent counts.**
9992
+ This tool returns \`status\`, \`importIds\`, and \`progress\` ({phase, records_processed, records_total}). It carries a \`result\` object (with \`leads\` + \`not_imported\`) when resolving an async \`handle_id\` whose run completed in this MCP instance, AND on the \`importIds[]\` path once every named import is \`complete\` and it wasn't a dry run. A \`complete\` import with no \`result\` means the records weren't readable \u2014 render completion only. **Render only from the fields actually present; never invent counts.**
9945
9993
 
9946
9994
  Caveat on \`progress\`: \`records_processed\` counts only the rows that MATCHED an existing lead (backend \`imported_records\`), not every row that finished processing \u2014 so for a complete import whose rows are mostly/all \`uncrawled\` (pending crawl), \`records_processed\` is legitimately low or 0. Never read a low \`records_processed\` on a \`complete\` import as "stuck" or "failed": once \`status:"complete"\`, processing is done; the pending-crawl rows just matched no existing lead yet.
9947
9995
 
9948
- - Running \u2192 \`"\u23F3 Import still running \u2014 phase <phase>; check back in ~M minutes."\` (use the phase; don't turn the matched-count into an "X/Y processed" progress bar).
9949
- - Complete, **no \`result\`** (the usual \`importIds\` status check) \u2192 \`"\u2713 Import complete."\` Do NOT append a \`records_processed/records_total\` fraction (it undercounts pending-crawl rows and looks stuck) and do NOT report pending-crawl / need-attention bucket counts \u2014 the row-level \`not_imported\` breakdown isn't in this response.
9996
+ - Running \u2192 \`"\u23F3 Import still running \u2014 phase <phase>; check back in ~M minutes."\` (use the phase; don't turn the matched-count into an "X/Y processed" progress bar). \`phase:"committing"\` is normal for an import that timed out \u2014 say it's still being committed, never that it failed or finished empty.
9997
+ - Complete with **\`dry_run:true\`** on the response \u2192 a VALIDATION pass; nothing was committed. \`"\u{1F50E} Dry run complete \u2014 input validated, nothing imported. Re-run without dry_run to commit."\` Never render this as a completed import, and never quote a lead count.
9998
+ - Complete, **no \`result\`** \u2192 \`"\u2713 Import complete."\` Do NOT append a \`records_processed/records_total\` fraction (it undercounts pending-crawl rows and looks stuck) and do NOT report pending-crawl / need-attention bucket counts \u2014 the row-level \`not_imported\` breakdown isn't in this response.
9999
+ - Complete with \`result.still_settling > 0\` \u2192 say \`"\u2713 Import complete \u2014 N imported, S rows still being placed."\` Never count \`still_settling\` rows as failures.
9950
10000
  - Complete, **\`result\` present AND it was a dry run** (\`result.dry_run:true\`, or every \`result.not_imported\` row has \`reason:"dry_run"\`) \u2192 this resolved handle was a VALIDATION pass, nothing committed. Render \`"\u{1F50E} Dry run complete \u2014 V rows validated, nothing imported. Re-run without dry_run to commit."\` \u2014 do NOT render it as a real import completion or use the pending/attention buckets.
9951
10001
  - Complete, **\`result\` present** (async handle resolved, real import) \u2192 then, and only then, partition \`result.not_imported\` as in the shared import-result render block below \u2014 \`"\u2713 Import complete \u2014 N imported \xB7 P pending crawl \xB7 Q need attention"\` where **pending crawl** is \`uncrawled\` rows that HAVE a \`domain\` (not failures) and no-\`domain\` \`uncrawled\` rows fall under need-attention. Drop any zero segment.
9952
10002
  - Error / failed \u2192 \`"\u26A0 Import failed: <error>. See leadbay_resolve_import_rows for diagnosis."\` \u2014 reserve this ONLY for a true transport/backend error on the import itself, never for \`uncrawled\` rows.
@@ -9970,9 +10020,10 @@ How the OTHER reasons map to the "Need attention" bucket (see the render block a
9970
10020
 
9971
10021
  | Observation | Suggest | Calls |
9972
10022
  |--------------------------------------|------------------------------------------------------|--------------------------------|
10023
+ | Status: complete, \`result.leads\` present | "Qualify the imported leads" | leadbay_bulk_qualify_leads(result.leads[].leadId) |
9973
10024
  | Status: complete | "See the imported (matched) leads" | leadbay_pull_leads |
9974
10025
  | Pending-crawl (\`uncrawled\`) rows | "Re-run the import for those domains later, once Leadbay has crawled them" | leadbay_import_leads (re-run with just the uncrawled domains, later \u2014 they re-reconcile once crawled). The added leads otherwise populate in the user's Leadbay account as the crawl completes; no live-fetch here |
9975
- | Status: running | "Check again in N minutes" | leadbay_import_status \u2014 re-call|
10026
+ | Status: running (incl. \`committing\`) | "Check again in N minutes" | leadbay_import_status \u2014 re-call (pass \`dry_run:true\` if the ids came from a dry run) |
9976
10027
  | Status: error / failed (true error) | "Diagnose the failure" | leadbay_resolve_import_rows |
9977
10028
  `;
9978
10029
  var leadbay_launch_bulk_enrichment = `Launch a bulk-enrichment job against the current selection. The backend requires \`email=true\` OR \`phone=true\` (both can be true). Returns 204 with no body \u2014 there is no bulk_id and no per-job status endpoint. Track results by polling individual leads via leadbay_get_contacts after ~60s; a contact is done for this run only when the REQUESTED channel landed (requested \`email\` and/or \`phone_number\` present), not \`contact.enrichment.done\` alone (that flag is already true for a contact enriched on the other channel earlier). \`dry_run:true\` returns the call shape without contacting the backend.
@@ -11504,35 +11555,38 @@ Trigger phrases: "look up <Company>", "research <Company>", "what do we know abo
11504
11555
 
11505
11556
  Do NOT use for: "picked row with leadId" \u2192 \`leadbay_research_lead_by_id\`; "draft outreach for <Contact>" \u2192 \`leadbay_prepare_outreach\`.
11506
11557
 
11507
- Prefer when: company name in prose and no Leadbay id yet
11558
+ Prefer when: a company name or domain in prose, no Leadbay id yet \u2014 always pass \`website\` if a domain was mentioned
11508
11559
 
11509
11560
  Examples that SHOULD invoke this tool:
11510
11561
  - "Look up Acme Corp for me."
11511
11562
  - "Find Initech in my pipeline."
11563
+ - "Who is Wink Lab? Their email is at @wink-lab.com."
11512
11564
 
11513
11565
  Examples that should NOT invoke this tool (sound similar, route elsewhere):
11514
11566
  - "Tell me about that lead I just picked."
11515
11567
  - "Draft outreach to Acme's CTO."
11568
+ - "Show me today's leads."
11516
11569
 
11517
11570
  ---
11518
11571
 
11519
- Resolves \`companyName\` across visible Discover, Monitor, and Activate leads,
11520
- then delegates to **leadbay_research_lead_by_id**. Supplying \`lensId\`
11521
- deliberately restricts the backend search to that lens. The result matches
11522
- \`_by_id\`, plus:
11572
+ Resolves across the user's visible Discover/Monitor/Activate leads AND the
11573
+ **Leadbay company registry** \u2014 so a company they do not own yet is still
11574
+ findable \u2014 then delegates to **leadbay_research_lead_by_id**.
11523
11575
 
11524
- - \`_meta.resolved_from\`: \`"companyName"\`
11525
- - \`_meta.resolved_query\`: the original query
11526
- - \`_meta.match_candidates[]\`: up to 4 \`{leadId, name, score}\` alternatives
11576
+ **Pass \`website\` whenever the user mentioned a domain** \u2014 the strongest match
11577
+ key. It survives a misspelled company name and is what turns "not in your
11578
+ list" into an answer. With only a contact email, pass \`email\`: the company
11579
+ domain is derived from it, consumer mailboxes ignored.
11527
11580
 
11528
- \`LEAD_NOT_FOUND\` identifies whether the complete visible corpus, an explicit
11529
- lens, or only a degraded active-lens fallback was searched.
11581
+ When the registry cannot pick one company it returns \`{resolution:
11582
+ "ambiguous", query, candidates:[{leadId, name, website, location, \u2026}]}\`
11583
+ instead of a card. Ask which one; never guess from \`score\`.
11530
11584
 
11531
- WHEN TO USE: for a company/domain/contact reference
11532
- without a \`lead_id\`. Offer \`_meta.match_candidates\` when present.
11585
+ \`LEAD_NOT_FOUND\` is not a dead end: its hint names the field that would have
11586
+ found it \u2014 \`website\` or \`registry_number\`, both params. Ask for it and call
11587
+ again. Do not offer an import before asking.
11533
11588
 
11534
- WHEN NOT TO USE: with a UUID; call
11535
- leadbay_research_lead_by_id directly.
11589
+ Offer \`_meta.match_candidates\` when present.
11536
11590
 
11537
11591
  ---
11538
11592
 
@@ -11671,6 +11725,10 @@ out?"\`
11671
11725
  | User is done with this lead | "Back to the inbox" | leadbay_pull_leads |
11672
11726
 
11673
11727
 
11728
+ When \`resolution\` is \`"ambiguous"\`, render no card: use \`ask_user_input_v0\`,
11729
+ ONE \`single_select\` question ("Which one?"), one short label per candidate
11730
+ combining \`name\` and \`location\`.
11731
+
11674
11732
  When \`_meta.match_candidates\` is non-empty, prepend one extra NEXT STEPS row:
11675
11733
 
11676
11734
  | Observation | Suggest | Calls |
@@ -12065,6 +12123,84 @@ WHEN TO USE: low-level.
12065
12123
 
12066
12124
  WHEN NOT TO USE: from agent flow \u2014 leadbay_report_outreach pairs this with a note + verification, which is what humans actually need to see in Leadbay.
12067
12125
 
12126
+ 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\`.
12127
+ `;
12128
+ var leadbay_set_lead_status = `## WHEN TO USE
12129
+
12130
+ Trigger phrases: "we won this deal", "mark this lead as won", "we lost them", "mark as lost", "this one is a target", "add them to my wanted list", "set the status on these leads", "closed the deal with", "they signed", "not a target anymore".
12131
+
12132
+ **Memory:** recall + capture via \`leadbay_agent_memory_*\` tools.
12133
+
12134
+ Do NOT use for: "I sent the email / left a voicemail \u2014 log the outcome" \u2192 \`leadbay_report_outreach\`; "thumbs up, I like this lead" \u2192 \`leadbay_like_lead\`; "remind me about this lead next week / snooze it" \u2192 \`leadbay_set_pushback\`.
12135
+
12136
+ Prefer when: user states a COMMERCIAL outcome or pipeline stage, not an outreach event; pass \`lead_ids\` + the uppercase \`status\`, and \`status_date\` when they name a close date
12137
+
12138
+ Examples that SHOULD invoke this tool:
12139
+ - "We just signed Acme Corp \u2014 mark them as won."
12140
+ - "Mark these three as lost, they went with a competitor."
12141
+ - "Add Northwind to my wanted list, they're a priority target."
12142
+
12143
+ Examples that should NOT invoke this tool (sound similar, route elsewhere):
12144
+ - "I emailed the CTO this morning, log it."
12145
+ - "Thumbs up on this one, show me more like it."
12146
+ - "Snooze this lead until next quarter."
12147
+
12148
+ ## RENDER (quick)
12149
+
12150
+ One short confirmation line per status applied ("\u2705 **Acme Corp** \u2192 WON
12151
+ (closed 2026-03-14)"). If \`failed\` is non-empty, list those leads with
12152
+ their error underneath. Don't re-render the full lead card.
12153
+
12154
+ ---
12155
+
12156
+ Set the **org-wide CRM lead status** \u2014 the same field the Leadbay website's status
12157
+ selector writes, and the one a CSV import maps via \`mappings.statuses\`. It is shared
12158
+ across the whole organization: every rep sees the value this call sets.
12159
+
12160
+ Two distinct status systems exist in Leadbay. Do not confuse them:
12161
+
12162
+ | System | Values | Written by | Means |
12163
+ |---|---|---|---|
12164
+ | **Lead status** (this tool) | \`WANTED\` \`WON\` \`LOST\` \`UNWANTED\` (plus system-set \`DEFAULT\`, \`INBOUND\`) | this tool, CSV import | Commercial/pipeline outcome, org-wide |
12165
+ | **Epilogue status** | \`STILL_CHASING\` \`COULD_NOT_REACH_STILL_TRYING\` \`INTEREST_VALIDATED_OR_MEETING_PLANED\` \`NOT_INTERESTED_LOST\` | \`leadbay_report_outreach\`, \`leadbay_set_epilogue_status\` | Disposition of a specific outreach attempt; drives \`leadbay_pull_followups\` ranking |
12166
+
12167
+ A deal outcome is a **lead status**. "She didn't pick up" is an **epilogue status**.
12168
+ Setting one never sets the other \u2014 when the user reports both in one breath ("called
12169
+ them, they signed"), make both calls.
12170
+
12171
+ ## Parameters
12172
+
12173
+ - \`lead_ids\` (required) \u2014 1\u2013200 lead UUIDs. Every lead gets the same status.
12174
+ - \`status\` (required) \u2014 one of \`WANTED\`, \`WON\`, \`LOST\`, \`UNWANTED\`. Accepted
12175
+ case-insensitively (\`won\` \u2192 \`WON\`); no synonyms are guessed, so "closed-won"
12176
+ or "dead" are rejected rather than silently mapped. \`DEFAULT\` and \`INBOUND\`
12177
+ are accepted but are normally set by Leadbay itself \u2014 don't offer them as
12178
+ user choices.
12179
+ - \`status_date\` (optional) \u2014 \`YYYY-MM-DD\`, the date the status was actually
12180
+ reached (a close date, the day the deal was lost). Omit it and the backend
12181
+ stamps now. Pass it whenever the user names a date; a deal closed last month
12182
+ stamped as today distorts every pipeline report.
12183
+
12184
+ ## Behaviour
12185
+
12186
+ Each lead is written individually (\`POST /leads/{leadId}/set_status\`, then
12187
+ \`POST /leads/{leadId}/set_status_date\` when \`status_date\` is given), so a partial
12188
+ failure is possible. The return is
12189
+ \`{ applied, count, status, status_date?, failed: [{lead_id, message}] }\` \u2014
12190
+ **always check \`failed\`** and report those leads to the user rather than claiming
12191
+ a clean sweep. \`applied\` is \`false\` when every lead failed.
12192
+
12193
+ Re-sending the same status is idempotent \u2014 no error, no duplicate entry.
12194
+
12195
+ WHEN TO USE: the user states a commercial outcome or pipeline
12196
+ position for specific leads: "we won them", "that one's dead", "these are my targets
12197
+ this quarter". Also use it from an artifact's status dropdown.
12198
+
12199
+ WHEN NOT TO USE: the user is reporting that an outreach
12200
+ *happened* (use \`leadbay_report_outreach\` \u2014 its \`epilogue_status\` covers the
12201
+ follow-up disposition), expressing taste rather than an outcome (\`leadbay_like_lead\`
12202
+ / \`leadbay_dislike_lead\`), or temporarily deferring a lead (\`leadbay_set_pushback\`).
12203
+
12068
12204
  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\`.
12069
12205
  `;
12070
12206
  var leadbay_set_pushback = `Snooze (pushback) one or more leads for 3, 6, or 12 months. The leads remain in the user's pipeline but are excluded from \`leadbay_pull_followups\` until the pushback window expires. Use this when the user says "not now", "next quarter", "follow up in 3 months", "6 months out", "next year", or any equivalent deferral.
@@ -12820,6 +12956,52 @@ var getContacts = {
12820
12956
  required: ["leadId"],
12821
12957
  additionalProperties: false
12822
12958
  },
12959
+ outputSchema: {
12960
+ type: "object",
12961
+ properties: {
12962
+ contacts: {
12963
+ type: "array",
12964
+ description: "Merged org+paid contacts. Each: {id, first_name, last_name, email, phone_number, linkedin_page, job_title, recommended, enrichment, source:'org'|'paid'}.",
12965
+ items: {
12966
+ type: "object",
12967
+ properties: {
12968
+ id: { type: "string" },
12969
+ first_name: { type: ["string", "null"] },
12970
+ last_name: { type: ["string", "null"] },
12971
+ email: { type: ["string", "null"] },
12972
+ phone_number: { type: ["string", "null"] },
12973
+ linkedin_page: { type: ["string", "null"] },
12974
+ job_title: { type: ["string", "null"] },
12975
+ recommended: { type: "boolean" },
12976
+ source: { type: "string", enum: ["org", "paid"] },
12977
+ enrichment: {
12978
+ type: ["object", "null"],
12979
+ description: "Per-contact reveal record. Missing or null = the contact was NEVER requested (enrichable \u2014 not the same as done:false). Read `done` and `credits_used` TOGETHER: done:false = reservation in flight, poll and do not re-launch; done:true with credits_used:0 = the reveal SETTLED and found nothing, which is TERMINAL \u2014 do not re-attempt it on a later run; done:true with credits_used>0 = resolved, but the revealed channel lands on the source:'org' twin of this person, not on the source:'paid' record itself, so a null email here is not a failure. credits_used:0 on its own is NOT a verdict (an in-flight reservation reports 0 too), and an ABSENT credits_used means the cost is unknown, not zero.",
12980
+ properties: {
12981
+ done: {
12982
+ type: "boolean",
12983
+ description: "False = reservation in flight. True = settled, either with a result (credits_used>0) or empty (credits_used:0). Per-contact, not per-channel."
12984
+ },
12985
+ credits_used: {
12986
+ type: "number",
12987
+ description: "Credits charged for this reveal. Only meaningful when done:true. An explicit 0 alongside done:true means the provider returned nothing. Optional \u2014 when absent the cost is unknown and terminal-empty must NOT be inferred."
12988
+ },
12989
+ email_requested: { type: "boolean" },
12990
+ phone_requested: { type: "boolean" }
12991
+ }
12992
+ }
12993
+ },
12994
+ required: ["id", "source"]
12995
+ }
12996
+ },
12997
+ _fetch_errors: {
12998
+ type: "array",
12999
+ description: "Present only when one of the two contact endpoints failed. Each: {endpoint:'org'|'paid', code?, retry_after?}. A rejected endpoint contributes no contacts, so an empty `contacts` alongside this field is a fetch failure, NOT 'no contacts'.",
13000
+ items: { type: "object" }
13001
+ }
13002
+ },
13003
+ required: ["contacts"]
13004
+ },
12823
13005
  execute: async (client, params) => {
12824
13006
  const [orgResult, paidResult] = await Promise.allSettled([
12825
13007
  client.request("GET", `/leads/${params.leadId}/contacts?IncludeEnriched=true`),
@@ -15034,56 +15216,8 @@ async function refreshLeadStates(client, leadIds, questionOrder) {
15034
15216
 
15035
15217
  // ../core/dist/composite/import-leads.js
15036
15218
  import { createHash as createHash3, randomUUID as randomUUID2 } from "crypto";
15037
- function isImportLeadsRunningResult(result) {
15038
- return "status" in result && result.status === "running";
15039
- }
15040
- var CHUNK_SIZE = 100;
15041
- var POLL_INTERVAL_MS2 = 2e3;
15042
- var DEFAULT_PER_PHASE_BUDGET_MS = 6e4;
15043
- var DEFAULT_TOTAL_BUDGET_MS = 3e5;
15044
- var STABILIZATION_POLLS = 2;
15045
- var MAX_COLUMN_NAME_LEN = 128;
15046
- var RESERVED_COLUMN_RE = /^mcp_row_id$/i;
15047
- var CUSTOM_FIELD_RE = /^CUSTOM\.(\d+)$/;
15048
- var IMPORT_RESOLVER_FIELDS = /* @__PURE__ */ new Set([
15049
- "LEADBAY_ID",
15050
- "CRM_ID",
15051
- "LEAD_NAME",
15052
- "LEAD_WEBSITE",
15053
- "SIREN"
15054
- ]);
15055
- function isCustomFieldMappingValue(v) {
15056
- return CUSTOM_FIELD_RE.test(v);
15057
- }
15058
- function customFieldIdOf(v) {
15059
- const m = CUSTOM_FIELD_RE.exec(v);
15060
- return m ? m[1] : null;
15061
- }
15062
- var PUBLIC_MAILBOX_DOMAINS = /* @__PURE__ */ new Set([
15063
- "gmail.com",
15064
- "googlemail.com",
15065
- "yahoo.com",
15066
- "ymail.com",
15067
- "outlook.com",
15068
- "hotmail.com",
15069
- "live.com",
15070
- "icloud.com",
15071
- "me.com",
15072
- "mac.com",
15073
- "aol.com",
15074
- "proton.me",
15075
- "protonmail.com",
15076
- "tutanota.com",
15077
- "gmx.com",
15078
- "gmx.net",
15079
- "gmx.de",
15080
- "mail.com",
15081
- "yandex.com",
15082
- "yandex.ru",
15083
- "qq.com",
15084
- "163.com",
15085
- "126.com"
15086
- ]);
15219
+
15220
+ // ../core/dist/composite/_import-records.js
15087
15221
  function normalizeDomain(input) {
15088
15222
  if (!input || typeof input !== "string")
15089
15223
  return null;
@@ -15114,6 +15248,216 @@ function normalizeDomain(input) {
15114
15248
  return null;
15115
15249
  return v;
15116
15250
  }
15251
+ var PUBLIC_MAILBOX_DOMAINS = /* @__PURE__ */ new Set([
15252
+ "gmail.com",
15253
+ "googlemail.com",
15254
+ "yahoo.com",
15255
+ "ymail.com",
15256
+ "outlook.com",
15257
+ "hotmail.com",
15258
+ "live.com",
15259
+ "icloud.com",
15260
+ "me.com",
15261
+ "mac.com",
15262
+ "aol.com",
15263
+ "proton.me",
15264
+ "protonmail.com",
15265
+ "tutanota.com",
15266
+ "gmx.com",
15267
+ "gmx.net",
15268
+ "gmx.de",
15269
+ "mail.com",
15270
+ "yandex.com",
15271
+ "yandex.ru",
15272
+ "qq.com",
15273
+ "163.com",
15274
+ "126.com",
15275
+ // Regional aliases of the same providers, plus the consumer ISP mailboxes
15276
+ // that dominate a French user base. Without these, `orange.fr` or
15277
+ // `yahoo.fr` reads as a company domain (codex review, mcp#188).
15278
+ "yahoo.fr",
15279
+ "yahoo.co.uk",
15280
+ "yahoo.es",
15281
+ "yahoo.it",
15282
+ "yahoo.de",
15283
+ "yahoo.ca",
15284
+ "yahoo.com.br",
15285
+ "yahoo.co.jp",
15286
+ "hotmail.fr",
15287
+ "hotmail.co.uk",
15288
+ "hotmail.es",
15289
+ "hotmail.it",
15290
+ "hotmail.de",
15291
+ "hotmail.be",
15292
+ "outlook.fr",
15293
+ "outlook.es",
15294
+ "outlook.de",
15295
+ "outlook.it",
15296
+ "live.fr",
15297
+ "live.be",
15298
+ "live.co.uk",
15299
+ "msn.com",
15300
+ "orange.fr",
15301
+ "wanadoo.fr",
15302
+ "free.fr",
15303
+ "sfr.fr",
15304
+ "laposte.net",
15305
+ "bbox.fr",
15306
+ "neuf.fr",
15307
+ "aliceadsl.fr",
15308
+ "numericable.fr",
15309
+ "club-internet.fr",
15310
+ "gmx.fr",
15311
+ "gmx.at",
15312
+ "gmx.ch",
15313
+ "web.de",
15314
+ "t-online.de",
15315
+ "libero.it",
15316
+ "wp.pl",
15317
+ "seznam.cz"
15318
+ ]);
15319
+ var MCP_ROW_ID_COLUMN = "MCP_ROW_ID";
15320
+ var MCP_ROW_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
15321
+ function ourRowId(raw) {
15322
+ if (raw == null)
15323
+ return void 0;
15324
+ const v = raw.trim();
15325
+ return MCP_ROW_ID_RE.test(v) ? v : void 0;
15326
+ }
15327
+ function cellNames(c) {
15328
+ return [c?.column_name, c?.key, c?.field].filter((n) => n != null && n !== "").map((n) => String(n).toLowerCase());
15329
+ }
15330
+ function readCell(record, key) {
15331
+ const want = key.toLowerCase();
15332
+ const arr = record.records;
15333
+ if (Array.isArray(arr)) {
15334
+ for (const c of arr) {
15335
+ if (cellNames(c).includes(want)) {
15336
+ const v = c?.value ?? null;
15337
+ return v != null ? String(v) : null;
15338
+ }
15339
+ }
15340
+ }
15341
+ const cells = record.cells;
15342
+ if (cells && typeof cells === "object" && !Array.isArray(cells)) {
15343
+ for (const [k, v] of Object.entries(cells)) {
15344
+ if (k.toLowerCase() === want) {
15345
+ return v != null ? String(v) : null;
15346
+ }
15347
+ }
15348
+ }
15349
+ if (Array.isArray(cells)) {
15350
+ for (const c of cells) {
15351
+ if (cellNames(c).includes(want)) {
15352
+ const v = c?.value ?? null;
15353
+ return v != null ? String(v) : null;
15354
+ }
15355
+ }
15356
+ }
15357
+ return null;
15358
+ }
15359
+ function recordMatchType(record) {
15360
+ return (record.match_type ?? record.matchType ?? "").toString().toUpperCase();
15361
+ }
15362
+ function isRecordTerminal(record) {
15363
+ const status = (record.status ?? "").toString().toUpperCase();
15364
+ return recordMatchType(record) === "NO_MATCH" || status === "IMPORTED";
15365
+ }
15366
+ function settlingDeficit(declaredTotal, fetched) {
15367
+ return Math.max(0, declaredTotal - fetched);
15368
+ }
15369
+ function reconcileRecords(records) {
15370
+ const leads = [];
15371
+ const not_imported = [];
15372
+ const pendingLeadIds = /* @__PURE__ */ new Set();
15373
+ let pending = 0;
15374
+ let distinct = 0;
15375
+ const seenRowIds = /* @__PURE__ */ new Set();
15376
+ for (const rec of records) {
15377
+ const rowId = ourRowId(readCell(rec, MCP_ROW_ID_COLUMN));
15378
+ const dedupeKey = rowId !== void 0 ? `row:${rowId}` : rec.id != null ? `rec:${String(rec.id)}` : null;
15379
+ if (dedupeKey !== null) {
15380
+ if (seenRowIds.has(dedupeKey))
15381
+ continue;
15382
+ seenRowIds.add(dedupeKey);
15383
+ }
15384
+ distinct++;
15385
+ const websiteCell = readCell(rec, "LEAD_WEBSITE");
15386
+ const domain = normalizeDomain(websiteCell ?? "") ?? normalizeDomain(rec.lead?.website ?? "") ?? void 0;
15387
+ if (!isRecordTerminal(rec)) {
15388
+ pending++;
15389
+ if (rec.lead?.id)
15390
+ pendingLeadIds.add(rec.lead.id);
15391
+ continue;
15392
+ }
15393
+ if (rec.lead?.id) {
15394
+ leads.push({
15395
+ ...rowId ? { rowId } : {},
15396
+ ...domain ? { domain } : {},
15397
+ leadId: rec.lead.id,
15398
+ name: rec.lead.name ?? null
15399
+ });
15400
+ continue;
15401
+ }
15402
+ if (recordMatchType(rec) === "NO_MATCH") {
15403
+ not_imported.push({
15404
+ ...rowId ? { rowId } : {},
15405
+ ...domain ? { domain } : {},
15406
+ reason: domain && PUBLIC_MAILBOX_DOMAINS.has(domain) ? "no_match" : "uncrawled"
15407
+ });
15408
+ continue;
15409
+ }
15410
+ pending++;
15411
+ }
15412
+ return { leads, not_imported, pending, distinct, pendingLeadIds };
15413
+ }
15414
+
15415
+ // ../core/dist/composite/_import-commit-log.js
15416
+ var MAX_ENTRIES = 500;
15417
+ var failures = /* @__PURE__ */ new Map();
15418
+ function recordCommitFailure(importId, reason) {
15419
+ if (failures.size >= MAX_ENTRIES) {
15420
+ const oldest = failures.keys().next().value;
15421
+ if (oldest !== void 0)
15422
+ failures.delete(oldest);
15423
+ }
15424
+ failures.set(importId, reason);
15425
+ }
15426
+ function commitFailureFor(importIds) {
15427
+ for (const id of importIds) {
15428
+ const reason = failures.get(id);
15429
+ if (reason !== void 0)
15430
+ return reason;
15431
+ }
15432
+ return void 0;
15433
+ }
15434
+
15435
+ // ../core/dist/composite/import-leads.js
15436
+ function isImportLeadsRunningResult(result) {
15437
+ return "status" in result && result.status === "running";
15438
+ }
15439
+ var CHUNK_SIZE = 100;
15440
+ var POLL_INTERVAL_MS2 = 2e3;
15441
+ var DEFAULT_PER_PHASE_BUDGET_MS = 6e4;
15442
+ var DEFAULT_TOTAL_BUDGET_MS = 3e5;
15443
+ var STABILIZATION_POLLS = 2;
15444
+ var MAX_COLUMN_NAME_LEN = 128;
15445
+ var RESERVED_COLUMN_RE = /^mcp_row_id$/i;
15446
+ var CUSTOM_FIELD_RE = /^CUSTOM\.(\d+)$/;
15447
+ var IMPORT_RESOLVER_FIELDS = /* @__PURE__ */ new Set([
15448
+ "LEADBAY_ID",
15449
+ "CRM_ID",
15450
+ "LEAD_NAME",
15451
+ "LEAD_WEBSITE",
15452
+ "SIREN"
15453
+ ]);
15454
+ function isCustomFieldMappingValue(v) {
15455
+ return CUSTOM_FIELD_RE.test(v);
15456
+ }
15457
+ function customFieldIdOf(v) {
15458
+ const m = CUSTOM_FIELD_RE.exec(v);
15459
+ return m ? m[1] : null;
15460
+ }
15117
15461
  function escapeCsvCell(raw) {
15118
15462
  if (raw == null)
15119
15463
  return "";
@@ -15167,6 +15511,19 @@ function importFingerprint(params, prep) {
15167
15511
  };
15168
15512
  return createHash3("sha256").update(stableStringify(payload)).digest("hex");
15169
15513
  }
15514
+ var ImportPhaseTimeout = class extends Error {
15515
+ phase;
15516
+ importId;
15517
+ budgetMs;
15518
+ code = "IMPORT_TIMEOUT";
15519
+ constructor(phase, importId, budgetMs) {
15520
+ super(`Import ${phase} phase did not finish within ${budgetMs}ms; the wizard is still running server-side. Poll leadbay_import_status with importIds=["${importId}"].`);
15521
+ this.phase = phase;
15522
+ this.importId = importId;
15523
+ this.budgetMs = budgetMs;
15524
+ this.name = "ImportPhaseTimeout";
15525
+ }
15526
+ };
15170
15527
  function checkAborted(signal) {
15171
15528
  if (signal?.aborted) {
15172
15529
  throw Object.assign(new Error("aborted"), { name: "AbortError" });
@@ -15193,37 +15550,6 @@ async function sleepWithAbort2(ms, signal) {
15193
15550
  signal.addEventListener("abort", onAbort, { once: true });
15194
15551
  });
15195
15552
  }
15196
- function readCell(record, key) {
15197
- const want = key.toLowerCase();
15198
- const arr = record.records;
15199
- if (Array.isArray(arr)) {
15200
- for (const c of arr) {
15201
- const k = (c?.column_name ?? c?.key ?? c?.field ?? "").toString().toLowerCase();
15202
- if (k === want) {
15203
- const v = c?.value ?? null;
15204
- return v != null ? String(v) : null;
15205
- }
15206
- }
15207
- }
15208
- const cells = record.cells;
15209
- if (cells && typeof cells === "object" && !Array.isArray(cells)) {
15210
- for (const [k, v] of Object.entries(cells)) {
15211
- if (k.toLowerCase() === want) {
15212
- return v != null ? String(v) : null;
15213
- }
15214
- }
15215
- }
15216
- if (Array.isArray(cells)) {
15217
- for (const c of cells) {
15218
- const k = (c?.key ?? c?.field ?? c?.column_name ?? "").toString().toLowerCase();
15219
- if (k === want) {
15220
- const v = c?.value ?? null;
15221
- return v != null ? String(v) : null;
15222
- }
15223
- }
15224
- }
15225
- return null;
15226
- }
15227
15553
  function validateColumnName(client, name, path) {
15228
15554
  if (typeof name !== "string" || name.length === 0) {
15229
15555
  throw client.makeError("IMPORT_INVALID_COLUMN_NAME", `Column name at ${path} must be a non-empty string`, `Use a plain string column name (1-${MAX_COLUMN_NAME_LEN} chars).`, "POST /imports");
@@ -15482,7 +15808,7 @@ async function pollUntil(fn, done, budgetMs, signal, ctx, label) {
15482
15808
  async function pollPreprocess(client, importId, budgetMs, ctx, signal) {
15483
15809
  const result = await pollUntil(() => client.request("GET", `/imports/${importId}`), (r) => Boolean(r.pre_processing?.finished), budgetMs, signal, ctx, "preprocess");
15484
15810
  if (!result.pre_processing?.finished) {
15485
- throw client.makeError("IMPORT_BUDGET_EXHAUSTED", `Preprocess phase did not finish within ${budgetMs}ms`, `Increase per_phase_budget_ms (current: ${budgetMs}) or split the batch. importId=${importId}.`, `GET /imports/${importId}`);
15811
+ throw new ImportPhaseTimeout("preprocess", importId, budgetMs);
15486
15812
  }
15487
15813
  if (result.pre_processing.error) {
15488
15814
  throw client.makeError("IMPORT_PREPROCESS_FAILED", `Preprocess failed: ${result.pre_processing.error}`, `Check the input domains. importId=${importId} for backend debugging.`, `GET /imports/${importId}`);
@@ -15492,7 +15818,7 @@ async function pollPreprocess(client, importId, budgetMs, ctx, signal) {
15492
15818
  async function pollProcess(client, importId, budgetMs, ctx, signal) {
15493
15819
  const result = await pollUntil(() => client.request("GET", `/imports/${importId}`), (r) => Boolean(r.processing?.finished), budgetMs, signal, ctx, "process");
15494
15820
  if (!result.processing?.finished) {
15495
- throw client.makeError("IMPORT_BUDGET_EXHAUSTED", `Process phase did not finish within ${budgetMs}ms`, `Increase per_phase_budget_ms (current: ${budgetMs}) or split the batch. importId=${importId}.`, `GET /imports/${importId}`);
15821
+ throw new ImportPhaseTimeout("process", importId, budgetMs);
15496
15822
  }
15497
15823
  if (result.processing.error != null) {
15498
15824
  throw client.makeError("IMPORT_PROCESSING_FAILED", `Backend processing failed: ${result.processing.error}`, `importId=${importId}.`, `GET /imports/${importId}`);
@@ -15519,10 +15845,7 @@ async function pollRecordsToTerminal(client, importId, budgetMs, expectedRowCoun
15519
15845
  records.push(...res.items);
15520
15846
  total = res.pagination.total ?? records.length;
15521
15847
  for (const r of res.items) {
15522
- const status = (r.status ?? "").toString().toUpperCase();
15523
- const matchType = (r.match_type ?? r.matchType ?? "").toString().toUpperCase();
15524
- const isTerminal = matchType === "NO_MATCH" || status === "IMPORTED";
15525
- if (!isTerminal)
15848
+ if (!isRecordTerminal(r))
15526
15849
  transient++;
15527
15850
  }
15528
15851
  const totalPages = res.pagination.pages ?? 0;
@@ -15550,14 +15873,15 @@ async function pollRecordsToTerminal(client, importId, budgetMs, expectedRowCoun
15550
15873
  }
15551
15874
  if (Date.now() >= deadline) {
15552
15875
  ctx?.logger?.warn?.(`import-leads: records did not stabilize (transient=${transient}, total=${total}); returning best-effort`);
15553
- throw client.makeError("IMPORT_NOT_TERMINAL", `Backend hasn't fully settled records within ${budgetMs}ms`, `Retry leadbay_import_leads with the same input in 30s, or split the batch. importId=${importId}.`, `GET /imports/${importId}/records`);
15876
+ throw new ImportPhaseTimeout("reconcile", importId, budgetMs);
15554
15877
  }
15555
15878
  await sleepWithAbort2(POLL_INTERVAL_MS2, signal);
15556
15879
  }
15557
15880
  }
15558
- async function runOneChunk(client, chunk, chunkIdx, totalChunks, header, mappings, dryRun, perPhaseBudgetMs, totalDeadline, ctx, signal, onImportId) {
15881
+ async function runOneChunk(client, chunk, chunkIdx, totalChunks, header, mappings, dryRun, perPhaseBudgetMs, totalDeadline, ctx, signal, onImportId, onNotificationId, onUploaded) {
15559
15882
  const upload = await uploadOneChunk(client, chunk, chunkIdx, totalChunks, header, ctx, onImportId);
15560
- return completeUploadedChunk(client, upload, mappings, dryRun, perPhaseBudgetMs, totalDeadline, ctx, signal);
15883
+ onUploaded?.(upload);
15884
+ return completeUploadedChunk(client, upload, mappings, dryRun, perPhaseBudgetMs, totalDeadline, ctx, signal, onNotificationId);
15561
15885
  }
15562
15886
  async function uploadOneChunk(client, chunk, chunkIdx, totalChunks, header, ctx, onImportId) {
15563
15887
  const csv = synthesizeCsv(header, chunk.map((c) => c.row));
@@ -15569,27 +15893,30 @@ async function uploadOneChunk(client, chunk, chunkIdx, totalChunks, header, ctx,
15569
15893
  onImportId(importId);
15570
15894
  return { importId, chunk, chunkIdx, totalChunks };
15571
15895
  }
15572
- async function completeUploadedChunk(client, upload, mappings, dryRun, perPhaseBudgetMs, totalDeadline, ctx, signal) {
15573
- const { importId, chunk } = upload;
15574
- const phaseBudget = Math.min(perPhaseBudgetMs, Math.max(1, totalDeadline - Date.now()));
15575
- await pollPreprocess(client, importId, phaseBudget, ctx, signal);
15576
- ctx?.logger?.info?.(`import-leads: preprocess done for importId=${importId}`);
15577
- if (dryRun) {
15578
- return { importId, records: [], notification_id: null };
15579
- }
15580
- let updateMappingsResp = null;
15896
+ async function commitMappings(client, importId, mappings, ctx) {
15581
15897
  try {
15582
- updateMappingsResp = await client.request("POST", `/imports/${importId}/update_mappings`, mappings);
15898
+ const resp = await client.request("POST", `/imports/${importId}/update_mappings`, mappings);
15899
+ return resp?.notification_id ?? null;
15583
15900
  } catch (err) {
15584
15901
  if (err?.code === "API_ERROR" || err?.code === "NOT_FOUND") {
15585
15902
  ctx?.logger?.warn?.(`import-leads: update_mappings raw error (${err?.code}); retrying void`);
15586
15903
  await client.requestVoid("POST", `/imports/${importId}/update_mappings`, mappings);
15587
- } else {
15588
- throw err;
15904
+ return null;
15589
15905
  }
15906
+ throw err;
15907
+ }
15908
+ }
15909
+ async function completeUploadedChunk(client, upload, mappings, dryRun, perPhaseBudgetMs, totalDeadline, ctx, signal, onNotificationId) {
15910
+ const { importId, chunk } = upload;
15911
+ const phaseBudget = Math.min(perPhaseBudgetMs, Math.max(1, totalDeadline - Date.now()));
15912
+ await pollPreprocess(client, importId, phaseBudget, ctx, signal);
15913
+ ctx?.logger?.info?.(`import-leads: preprocess done for importId=${importId}`);
15914
+ if (dryRun) {
15915
+ return { importId, records: [], notification_id: null };
15590
15916
  }
15591
- const importNotificationId = updateMappingsResp?.notification_id ?? null;
15917
+ const importNotificationId = await commitMappings(client, importId, mappings, ctx);
15592
15918
  if (importNotificationId) {
15919
+ onNotificationId?.(importNotificationId);
15593
15920
  ctx?.logger?.info?.(`import-leads: notification_id=${importNotificationId} importId=${importId}`);
15594
15921
  }
15595
15922
  ctx?.logger?.info?.(`import-leads: mappings committed for importId=${importId}`);
@@ -15640,7 +15967,7 @@ function reconcileOneChunk(prep, chunk, matched, notImported) {
15640
15967
  }
15641
15968
  seenInputIndex.add(inputIdx);
15642
15969
  const inp = prep.validInputs[inputIdx];
15643
- const matchType = (rec.match_type ?? rec.matchType ?? "").toString();
15970
+ const matchType = recordMatchType(rec);
15644
15971
  if (rec.lead?.id) {
15645
15972
  matched.set(inputIdx, {
15646
15973
  domain: inp.outputDomain,
@@ -15835,7 +16162,20 @@ var importLeads = {
15835
16162
  },
15836
16163
  handle_id: {
15837
16164
  type: "string",
15838
- description: "Persisted UUID handle to pass to leadbay_import_status."
16165
+ description: "Persisted UUID handle to pass to leadbay_import_status. Only on the wait_for_completion=false path; absent when a blocking call timed out (use importIds then)."
16166
+ },
16167
+ timed_out: {
16168
+ type: "boolean",
16169
+ description: "True when a blocking call ran out of poll budget. The import is still running server-side \u2014 poll leadbay_import_status(importIds). Do NOT re-issue the import."
16170
+ },
16171
+ rows_pending_upload: {
16172
+ type: "number",
16173
+ description: "Rows from later chunks that were never uploaded before the budget ran out. These are NOT running anywhere; re-import just those rows."
16174
+ },
16175
+ row_ids: {
16176
+ type: "array",
16177
+ description: "Records mode only: the synthetic MCP_ROW_ID of each input row, in the order you passed `records[]`. leadbay_import_status reports recovered leads by that id \u2014 use this to map them back to your source rows.",
16178
+ items: { type: "string" }
15839
16179
  },
15840
16180
  progress: {
15841
16181
  type: "object",
@@ -15865,7 +16205,7 @@ var importLeads = {
15865
16205
  required: ["importIds", "region", "_meta"],
15866
16206
  anyOf: [
15867
16207
  { required: ["leads", "not_imported", "importIds", "region", "_meta"] },
15868
- { required: ["status", "handle_id", "importIds", "progress", "region", "_meta"] }
16208
+ { required: ["status", "importIds", "progress", "region", "_meta"] }
15869
16209
  ]
15870
16210
  },
15871
16211
  execute: async (client, params, ctx) => {
@@ -15992,23 +16332,33 @@ var importLeads = {
15992
16332
  const matched = /* @__PURE__ */ new Map();
15993
16333
  const notImported = /* @__PURE__ */ new Map();
15994
16334
  let cancelled = false;
16335
+ let timedOut = null;
16336
+ let rowsStarted = 0;
16337
+ const lastUpload = { current: null };
15995
16338
  const recordImportId = (id) => {
15996
16339
  if (!importIds.includes(id))
15997
16340
  importIds.push(id);
15998
16341
  };
16342
+ const recordNotificationId = (id) => {
16343
+ if (!notificationIds.includes(id))
16344
+ notificationIds.push(id);
16345
+ };
15999
16346
  try {
16000
16347
  for (let i = 0; i < chunks.length; i++) {
16001
16348
  const chunk = chunks[i];
16002
- const out = await runOneChunk(client, chunk, i, chunks.length, prep.header, prep.mappings, dryRun, perPhaseBudget, totalDeadline, ctx, signal, recordImportId);
16003
- if (out.notification_id && !notificationIds.includes(out.notification_id)) {
16004
- notificationIds.push(out.notification_id);
16005
- }
16349
+ rowsStarted += chunk.length;
16350
+ const out = await runOneChunk(client, chunk, i, chunks.length, prep.header, prep.mappings, dryRun, perPhaseBudget, totalDeadline, ctx, signal, recordImportId, recordNotificationId, (u) => {
16351
+ lastUpload.current = u;
16352
+ });
16006
16353
  if (!dryRun) {
16007
16354
  reconcileOneChunk(prep, out, matched, notImported);
16008
16355
  }
16009
16356
  }
16010
16357
  } catch (err) {
16011
- if (err?.name === "AbortError") {
16358
+ if (err instanceof ImportPhaseTimeout) {
16359
+ timedOut = err;
16360
+ ctx?.logger?.warn?.(`import-leads: ${err.phase} budget exhausted after ${err.budgetMs}ms; returning status=running importIds=${importIds.join(",")}`);
16361
+ } else if (err?.name === "AbortError") {
16012
16362
  cancelled = true;
16013
16363
  ctx?.logger?.info?.(`import-leads: aborted via signal; importIds=${importIds.join(",")}`);
16014
16364
  } else if (err?.error === true) {
@@ -16023,9 +16373,54 @@ var importLeads = {
16023
16373
  throw err;
16024
16374
  }
16025
16375
  }
16376
+ if (timedOut) {
16377
+ if (timedOut.phase === "preprocess" && // A dry run is SUPPOSED to stop after preprocess — committing its
16378
+ // mappings would turn a validation pass into a real import.
16379
+ !dryRun && lastUpload.current && lastUpload.current.importId === timedOut.importId) {
16380
+ resumeParkedUpload(client, lastUpload.current, prep.mappings, ctx);
16381
+ }
16382
+ const rowsPendingUpload = prep.validInputs.length - rowsStarted;
16383
+ const malformed = prep.malformedDomains.map((d) => ({ domain: d, reason: "malformed" }));
16384
+ return {
16385
+ status: "running",
16386
+ timed_out: true,
16387
+ importIds,
16388
+ notification_ids: notificationIds,
16389
+ ...malformed.length > 0 ? { not_imported: malformed } : {},
16390
+ ...dryRun ? { dry_run: true } : {},
16391
+ ...prep.mode === "records" ? { row_ids: prep.validInputs.map((i) => i.rowId) } : {},
16392
+ progress: {
16393
+ phase: timedOut.phase,
16394
+ records_processed: matched.size,
16395
+ records_total: prep.validInputs.length
16396
+ },
16397
+ ...rowsPendingUpload > 0 ? { rows_pending_upload: rowsPendingUpload } : {},
16398
+ region: client.region,
16399
+ _meta: client.lastMeta ?? {
16400
+ region: client.region,
16401
+ endpoint: `GET /imports/${timedOut.importId}`,
16402
+ latency_ms: null,
16403
+ retry_after: null
16404
+ }
16405
+ };
16406
+ }
16026
16407
  return buildImportLeadsResult(client, prep, importIds, matched, notImported, dryRun, cancelled, notificationIds);
16027
16408
  }
16028
16409
  };
16410
+ var RESUME_COMMIT_BUDGET_MS = 10 * 6e4;
16411
+ function resumeParkedUpload(client, upload, mappings, ctx) {
16412
+ const bgCtx = { logger: ctx?.logger };
16413
+ const { importId } = upload;
16414
+ setTimeout(() => {
16415
+ void (async () => {
16416
+ await pollPreprocess(client, importId, RESUME_COMMIT_BUDGET_MS, bgCtx, void 0);
16417
+ await commitMappings(client, importId, mappings, bgCtx);
16418
+ })().then(() => ctx?.logger?.info?.(`import-leads: parked upload ${importId} committed; backend is processing`), (err) => {
16419
+ recordCommitFailure(importId, err?.message ?? err?.code ?? "mapping commit failed");
16420
+ ctx?.logger?.warn?.(`import-leads: parked upload ${importId} could not be committed (${err?.code ?? err?.message ?? "unknown"})`);
16421
+ });
16422
+ }, 0);
16423
+ }
16029
16424
  async function runImportInBackground(client, prep, uploadedChunks, opts, ctx, handleId) {
16030
16425
  const tracker = ctx.bulkTracker;
16031
16426
  if (!tracker)
@@ -17821,33 +18216,152 @@ var likeLead = {
17821
18216
  }
17822
18217
  };
17823
18218
 
17824
- // ../core/dist/tools/dislike-lead.js
17825
- var dislikeLead = {
17826
- name: "leadbay_dislike_lead",
18219
+ // ../core/dist/tools/dislike-lead.js
18220
+ var dislikeLead = {
18221
+ name: "leadbay_dislike_lead",
18222
+ annotations: {
18223
+ title: "Dislike a lead",
18224
+ readOnlyHint: false,
18225
+ destructiveHint: true,
18226
+ idempotentHint: true,
18227
+ openWorldHint: true
18228
+ },
18229
+ description: leadbay_dislike_lead,
18230
+ optional: true,
18231
+ write: true,
18232
+ inputSchema: {
18233
+ type: "object",
18234
+ properties: {
18235
+ lead_id: {
18236
+ type: "string",
18237
+ description: "UUID of the lead to dislike."
18238
+ }
18239
+ },
18240
+ required: ["lead_id"],
18241
+ additionalProperties: false
18242
+ },
18243
+ execute: async (client, params) => {
18244
+ await client.requestVoid("POST", `/leads/${params.lead_id}/dislike`);
18245
+ return { applied: true, lead_id: params.lead_id, action: "disliked" };
18246
+ }
18247
+ };
18248
+
18249
+ // ../core/dist/tools/set-lead-status.js
18250
+ var statusPath = (leadId) => `/leads/${encodeURIComponent(leadId)}/set_status`;
18251
+ var statusDatePath = (leadId) => `/leads/${encodeURIComponent(leadId)}/set_status_date`;
18252
+ var statusBody = (status) => ({ status });
18253
+ var statusDateBody = (date) => ({ date: `${date}T00:00:00Z` });
18254
+ var MAX_LEADS = 200;
18255
+ var CONCURRENCY = 6;
18256
+ var LEAD_STATUS_SET2 = new Set(LEAD_STATUSES);
18257
+ var SETTABLE_LEAD_STATUSES = ["WANTED", "WON", "LOST", "UNWANTED"];
18258
+ var ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
18259
+ function messageOf(e) {
18260
+ if (e && typeof e === "object" && "message" in e)
18261
+ return String(e.message);
18262
+ return String(e);
18263
+ }
18264
+ async function writeAll(client, leadIds, status, statusDate) {
18265
+ const failed = [];
18266
+ let cursor = 0;
18267
+ async function worker() {
18268
+ for (; ; ) {
18269
+ const i = cursor++;
18270
+ if (i >= leadIds.length)
18271
+ return;
18272
+ const id = leadIds[i];
18273
+ try {
18274
+ await client.requestVoid("POST", statusPath(id), statusBody(status));
18275
+ if (statusDate) {
18276
+ await client.requestVoid("POST", statusDatePath(id), statusDateBody(statusDate));
18277
+ }
18278
+ } catch (e) {
18279
+ failed.push({ lead_id: id, message: messageOf(e) });
18280
+ }
18281
+ }
18282
+ }
18283
+ await Promise.all(Array.from({ length: Math.min(CONCURRENCY, leadIds.length) }, () => worker()));
18284
+ return failed;
18285
+ }
18286
+ var setLeadStatus = {
18287
+ name: "leadbay_set_lead_status",
17827
18288
  annotations: {
17828
- title: "Dislike a lead",
18289
+ title: "Set lead CRM status",
17829
18290
  readOnlyHint: false,
18291
+ // Org-wide and overwrites whatever the last rep set — destructive in the
18292
+ // MCP sense (not reversible from the value we replaced).
17830
18293
  destructiveHint: true,
17831
18294
  idempotentHint: true,
17832
18295
  openWorldHint: true
17833
18296
  },
17834
- description: leadbay_dislike_lead,
18297
+ description: leadbay_set_lead_status,
17835
18298
  optional: true,
17836
18299
  write: true,
17837
18300
  inputSchema: {
17838
18301
  type: "object",
17839
18302
  properties: {
17840
- lead_id: {
18303
+ lead_ids: {
18304
+ type: "array",
18305
+ items: { type: "string" },
18306
+ description: `Lead UUIDs (1-${MAX_LEADS}). Every lead gets the same status.`
18307
+ },
18308
+ status: {
17841
18309
  type: "string",
17842
- description: "UUID of the lead to dislike."
18310
+ description: "One of: WANTED, WON, LOST, UNWANTED (case-insensitive). DEFAULT and INBOUND are accepted but are normally set by Leadbay itself."
18311
+ },
18312
+ status_date: {
18313
+ type: "string",
18314
+ description: "Optional YYYY-MM-DD \u2014 the date the status was actually reached (close date). Omit to let the backend stamp now."
17843
18315
  }
17844
18316
  },
17845
- required: ["lead_id"],
18317
+ required: ["lead_ids", "status"],
17846
18318
  additionalProperties: false
17847
18319
  },
17848
18320
  execute: async (client, params) => {
17849
- await client.requestVoid("POST", `/leads/${params.lead_id}/dislike`);
17850
- return { applied: true, lead_id: params.lead_id, action: "disliked" };
18321
+ const leadIds = (params.lead_ids ?? []).filter((id) => typeof id === "string" && id.trim() !== "");
18322
+ if (leadIds.length === 0) {
18323
+ return {
18324
+ error: true,
18325
+ code: "BAD_INPUT",
18326
+ message: "lead_ids is empty",
18327
+ hint: "Pass at least one lead UUID."
18328
+ };
18329
+ }
18330
+ if (leadIds.length > MAX_LEADS) {
18331
+ return {
18332
+ error: true,
18333
+ code: "BAD_INPUT",
18334
+ message: `lead_ids has ${leadIds.length} entries, max is ${MAX_LEADS}`,
18335
+ hint: `Call leadbay_set_lead_status again per chunk of ${MAX_LEADS} lead_ids or fewer.`
18336
+ };
18337
+ }
18338
+ const status = String(params.status ?? "").trim().toUpperCase();
18339
+ if (!LEAD_STATUS_SET2.has(status)) {
18340
+ return {
18341
+ error: true,
18342
+ code: "BAD_INPUT",
18343
+ message: `Unknown lead status: ${JSON.stringify(params.status)}`,
18344
+ hint: `Use one of ${SETTABLE_LEAD_STATUSES.join(", ")} (case-insensitive).`
18345
+ };
18346
+ }
18347
+ const statusDate = params.status_date?.trim() || void 0;
18348
+ if (statusDate && !ISO_DATE.test(statusDate)) {
18349
+ return {
18350
+ error: true,
18351
+ code: "BAD_INPUT",
18352
+ message: `status_date ${JSON.stringify(params.status_date)} is not YYYY-MM-DD`,
18353
+ hint: "Pass a calendar date like 2026-03-14, or omit it to stamp now."
18354
+ };
18355
+ }
18356
+ const failed = await writeAll(client, leadIds, status, statusDate);
18357
+ const count = leadIds.length - failed.length;
18358
+ return {
18359
+ applied: count > 0,
18360
+ count,
18361
+ status,
18362
+ ...statusDate ? { status_date: statusDate } : {},
18363
+ failed
18364
+ };
17851
18365
  }
17852
18366
  };
17853
18367
 
@@ -18333,6 +18847,45 @@ var prepareOutreach = {
18333
18847
  }
18334
18848
  };
18335
18849
 
18850
+ // ../core/dist/lead-order.js
18851
+ var LEAD_ORDERS = [
18852
+ "SCORE:DESC",
18853
+ "SCORE:ASC",
18854
+ "NAME:ASC",
18855
+ "NAME:DESC",
18856
+ "SIZE:DESC",
18857
+ "SIZE:ASC",
18858
+ "SECTOR:ASC",
18859
+ "SECTOR:DESC",
18860
+ "STATUS:ASC",
18861
+ "STATUS:DESC",
18862
+ "CONTACT_COUNT:DESC",
18863
+ "CONTACT_COUNT:ASC",
18864
+ "LAST_PROSPECTING_ACTION_AT:DESC",
18865
+ "LAST_PROSPECTING_ACTION_AT:ASC",
18866
+ "EPILOGUE_STATUS_SET_AT:DESC",
18867
+ "EPILOGUE_STATUS_SET_AT:ASC",
18868
+ "LIKED:DESC",
18869
+ "DISLIKED:DESC"
18870
+ ];
18871
+ var LEAD_ORDER_SET = new Set(LEAD_ORDERS);
18872
+ function resolveLeadOrder(raw, tool) {
18873
+ const order = raw?.trim().toUpperCase();
18874
+ if (!order)
18875
+ return {};
18876
+ if (!LEAD_ORDER_SET.has(order)) {
18877
+ return {
18878
+ error: {
18879
+ error: true,
18880
+ code: "BAD_INPUT",
18881
+ message: `Unknown order: ${JSON.stringify(raw)}`,
18882
+ hint: `Call ${tool} again with one of: ${LEAD_ORDERS.join(", ")}.`
18883
+ }
18884
+ };
18885
+ }
18886
+ return { order };
18887
+ }
18888
+
18336
18889
  // ../core/dist/composite/_empty-lens-reason.js
18337
18890
  var CITY_LEVEL = 7;
18338
18891
  function criteriaOf(filter) {
@@ -18370,6 +18923,21 @@ function narrowGeoSentence(narrow) {
18370
18923
  return "";
18371
18924
  return ` Its geography is pinned to ${names.join(", ")} \u2014 a city-scale area or smaller, which on an empty lens is almost always the criterion to relax first.`;
18372
18925
  }
18926
+ async function readAudienceShape(client, lensId) {
18927
+ let filter = null;
18928
+ try {
18929
+ filter = await client.request("GET", `/lenses/${lensId}/filter`);
18930
+ } catch {
18931
+ }
18932
+ const criteria = criteriaOf(filter);
18933
+ const summary = summariseCriteria(criteria);
18934
+ const narrow = narrowLocationsOf(filter, criteria);
18935
+ return {
18936
+ ...summary ? { criteria: summary } : {},
18937
+ ...narrow.length > 0 ? { narrow_locations: narrow } : {},
18938
+ geoSentence: narrowGeoSentence(narrow)
18939
+ };
18940
+ }
18373
18941
  async function diagnoseEmptyLens(client, lensId, computing) {
18374
18942
  if (computing.wishlist || computing.scores) {
18375
18943
  return {
@@ -18384,19 +18952,8 @@ async function diagnoseEmptyLens(client, lensId, computing) {
18384
18952
  row = lenses.find((l) => String(l.id) === String(lensId));
18385
18953
  } catch {
18386
18954
  }
18387
- let filter = null;
18388
- try {
18389
- filter = await client.request("GET", `/lenses/${lensId}/filter`);
18390
- } catch {
18391
- }
18392
- const criteria = criteriaOf(filter);
18393
- const summary = summariseCriteria(criteria);
18394
- const narrow = narrowLocationsOf(filter, criteria);
18395
- const geo = narrowGeoSentence(narrow);
18396
- const extras = {
18397
- ...summary ? { criteria: summary } : {},
18398
- ...narrow.length > 0 ? { narrow_locations: narrow } : {}
18399
- };
18955
+ const { geoSentence: geo, ...extras } = await readAudienceShape(client, lensId);
18956
+ const summary = extras.criteria;
18400
18957
  if (row?.not_enough_lead_candidates) {
18401
18958
  return {
18402
18959
  code: "no_candidates",
@@ -18522,6 +19079,10 @@ var pullLeads = {
18522
19079
  },
18523
19080
  count: { type: "number", description: "Leads per page, max 50 (default 20)" },
18524
19081
  page: { type: "number", description: "Page number, 0-indexed (default 0)" },
19082
+ order: {
19083
+ type: "string",
19084
+ description: "Optional sort, FIELD:ASC|DESC (SCORE, NAME, SIZE, SECTOR, STATUS, CONTACT_COUNT, LAST_PROSPECTING_ACTION_AT, LIKED). Omit for the lens's own Discover ranking. An unknown value is rejected and the error lists every accepted order."
19085
+ },
18525
19086
  verbose: {
18526
19087
  type: "boolean",
18527
19088
  description: "If true, include the full set of lead-summary fields. Default false: returns the trimmed agent-friendly form."
@@ -18630,7 +19191,11 @@ var pullLeads = {
18630
19191
  const page = params.page ?? 0;
18631
19192
  const count = Math.min(params.count ?? 20, 50);
18632
19193
  const verbose = params.verbose ?? false;
18633
- const res = await client.request("GET", `/lenses/${lensId}/leads/wishlist?count=${count}&page=${page}&contacts=true`);
19194
+ const resolvedOrder = resolveLeadOrder(params.order, "leadbay_pull_leads");
19195
+ if (resolvedOrder.error)
19196
+ return resolvedOrder.error;
19197
+ const orderQs = resolvedOrder.order ? `&order=${encodeURIComponent(resolvedOrder.order)}` : "";
19198
+ const res = await client.request("GET", `/lenses/${lensId}/leads/wishlist?count=${count}&page=${page}&contacts=true${orderQs}`);
18634
19199
  const summaries = await Promise.all(res.items.map(async (lead) => {
18635
19200
  try {
18636
19201
  const r = await client.request("GET", `/leads/${lead.id}/ai_agent_responses`);
@@ -18899,6 +19464,10 @@ var pullFollowups = {
18899
19464
  type: "number",
18900
19465
  description: "Leads per page, max 200 (default 20)."
18901
19466
  },
19467
+ order: {
19468
+ type: "string",
19469
+ description: "Optional sort, FIELD:ASC|DESC (SCORE, NAME, SIZE, SECTOR, STATUS, CONTACT_COUNT, LAST_PROSPECTING_ACTION_AT, LIKED). Omit for the Monitor's own ranking. An unknown value is rejected and the error lists every accepted order."
19470
+ },
18902
19471
  page: {
18903
19472
  type: "number",
18904
19473
  description: "Page number, 0-indexed (default 0)."
@@ -19008,7 +19577,7 @@ var pullFollowups = {
19008
19577
  if (params.city_id)
19009
19578
  geoTexts.push(params.city_id);
19010
19579
  if (geoTexts.length > 0) {
19011
- const { resolved, ambiguities } = await resolveLocations(client, geoTexts);
19580
+ const { resolved: resolved2, ambiguities } = await resolveLocations(client, geoTexts);
19012
19581
  if (ambiguities.length > 0) {
19013
19582
  return withAgentMemoryMeta(client, {
19014
19583
  status: "ambiguous_locations",
@@ -19023,8 +19592,8 @@ var pullFollowups = {
19023
19592
  }
19024
19593
  }, ctx);
19025
19594
  }
19026
- if (resolved.length > 0) {
19027
- effectiveSetFilter = mergeLocationIds(effectiveSetFilter, resolved);
19595
+ if (resolved2.length > 0) {
19596
+ effectiveSetFilter = mergeLocationIds(effectiveSetFilter, resolved2);
19028
19597
  }
19029
19598
  }
19030
19599
  if (effectiveSetFilter) {
@@ -19034,12 +19603,17 @@ var pullFollowups = {
19034
19603
  ctx?.logger?.warn?.(`pull_followups: POST /monitor/filter failed: ${err?.message ?? err?.code ?? err}`);
19035
19604
  }
19036
19605
  }
19606
+ const resolved = resolveLeadOrder(params.order, "leadbay_pull_followups");
19607
+ if (resolved.error)
19608
+ return resolved.error;
19609
+ const order = resolved.order;
19037
19610
  const qs = new URLSearchParams({
19038
19611
  personal: String(personal),
19039
19612
  liked: String(liked),
19040
19613
  filtered: String(filtered),
19041
19614
  count: String(count),
19042
- page: String(page)
19615
+ page: String(page),
19616
+ ...order ? { order } : {}
19043
19617
  }).toString();
19044
19618
  const [filterR, monitorR] = await Promise.allSettled([
19045
19619
  filtered ? client.request("GET", "/monitor/filter") : Promise.resolve(null),
@@ -20243,7 +20817,7 @@ var researchLeadById = {
20243
20817
  },
20244
20818
  _meta: {
20245
20819
  type: "object",
20246
- description: "Operator context: region (us/fr/custom), lens_id (the lens used for the lead-by-id fetch), web_fetch_in_progress (true if the backend is still hydrating signals), has_reachable_contact (true if at least one contact or recommended_contact has email or phone \u2014 drives NEXT STEPS routing between enrichment vs outreach). When the call was routed via leadbay_research_lead_by_name_fuzzy, also: resolved_from='companyName', resolved_query='<needle>', match_candidates=[{leadId,name,score}].",
20820
+ description: "Operator context: region (us/fr/custom), lens_id (the lens used for the lead-by-id fetch), web_fetch_in_progress (true if the backend is still hydrating signals), has_reachable_contact (true if at least one contact or recommended_contact has email or phone \u2014 drives NEXT STEPS routing between enrichment vs outreach). When the call was routed via leadbay_research_lead_by_name_fuzzy, also: resolved_from='companyName' (matched in the user's own leads) or 'resolver' (matched in the Leadbay company registry), resolved_query='<needle>', resolved_matched_on=['website_exact',\u2026] on the resolver path, match_candidates=[{leadId,name,score}].",
20247
20821
  properties: {
20248
20822
  region: { type: "string" },
20249
20823
  lens_id: { type: "number" },
@@ -20255,6 +20829,10 @@ var researchLeadById = {
20255
20829
  type: ["array", "null"],
20256
20830
  items: { type: "object" }
20257
20831
  },
20832
+ resolved_matched_on: {
20833
+ type: ["array", "null"],
20834
+ items: { type: "string" }
20835
+ },
20258
20836
  agent_memory: { type: "object" }
20259
20837
  },
20260
20838
  // _meta is an open envelope: the MCP server layer injects
@@ -20427,7 +21005,8 @@ var researchLeadById = {
20427
21005
  has_reachable_contact: hasReachableContact,
20428
21006
  resolved_from: params._resolved?.from ?? null,
20429
21007
  resolved_query: params._resolved?.query ?? null,
20430
- match_candidates: params._resolved?.candidates ?? null
21008
+ match_candidates: params._resolved?.candidates ?? null,
21009
+ resolved_matched_on: params._resolved?.matched_on ?? null
20431
21010
  }
20432
21011
  }, _ctx);
20433
21012
  }
@@ -20449,16 +21028,8 @@ researchLeadById.execute = async (client, params, ctx) => {
20449
21028
  };
20450
21029
 
20451
21030
  // ../core/dist/composite/research-lead-by-name-fuzzy.js
20452
- function rankSubstringMatches(needle, candidates) {
20453
- const n = needle.toLowerCase();
20454
- const hits = candidates.filter((c) => typeof c.name === "string" && c.name.toLowerCase().includes(n));
20455
- hits.sort((a, b) => {
20456
- const aScore = a.score ?? -Infinity;
20457
- const bScore = b.score ?? -Infinity;
20458
- return bScore - aScore;
20459
- });
20460
- return hits;
20461
- }
21031
+ var RESOLVE_TIMEOUT_MS = 1e4;
21032
+ var MAX_AMBIGUOUS_CANDIDATES = 4;
20462
21033
  function parseLensId(value) {
20463
21034
  const parsed = typeof value === "number" ? value : typeof value === "string" && value.trim() !== "" ? Number(value) : Number.NaN;
20464
21035
  return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : void 0;
@@ -20473,6 +21044,34 @@ function suggestionLeadId(suggestion) {
20473
21044
  function isLeadbayError(error) {
20474
21045
  return typeof error === "object" && error !== null && error.error === true && typeof error.code === "string" && typeof error.message === "string" && typeof error.hint === "string";
20475
21046
  }
21047
+ function businessDomainFromEmail(email) {
21048
+ if (!email || typeof email !== "string")
21049
+ return null;
21050
+ const at = email.lastIndexOf("@");
21051
+ if (at === -1)
21052
+ return null;
21053
+ const domain = normalizeDomain(email.slice(at + 1));
21054
+ if (!domain)
21055
+ return null;
21056
+ return PUBLIC_MAILBOX_DOMAINS.has(domain) ? null : domain;
21057
+ }
21058
+ function buildResolvePayload(params) {
21059
+ const queryDomain = normalizeDomain(params.query);
21060
+ const website = (params.website ? normalizeDomain(params.website) : null) ?? queryDomain ?? businessDomainFromEmail(params.email);
21061
+ const payload = {};
21062
+ if (!queryDomain)
21063
+ payload.name = params.query;
21064
+ if (website)
21065
+ payload.website = website;
21066
+ if (params.email)
21067
+ payload.email = params.email;
21068
+ if (params.registry_number)
21069
+ payload.registry_number = params.registry_number;
21070
+ return payload;
21071
+ }
21072
+ function hasStrongIdentityKey(payload) {
21073
+ return Boolean(payload.website || payload.registry_number);
21074
+ }
20476
21075
  async function resolveWithinLens(client, query, lensId) {
20477
21076
  const results = await client.request("GET", `/lenses/${lensId}/leads/wishlist?q=${encodeURIComponent(query)}&count=50&page=0&contacts=false`);
20478
21077
  return results.items.map((lead) => ({
@@ -20494,6 +21093,24 @@ async function resolveAcrossVisibleCorpus(client, query) {
20494
21093
  };
20495
21094
  }).filter((suggestion) => suggestion.id !== "" && suggestion.name !== "");
20496
21095
  }
21096
+ async function hydrateAmbiguous(client, candidates, lensId) {
21097
+ const selected = candidates.slice(0, MAX_AMBIGUOUS_CANDIDATES);
21098
+ const settled = await Promise.allSettled(selected.map((c) => client.request("GET", `/lenses/${lensId}/leads/${c.lead_id}`)));
21099
+ return selected.map((c, i) => {
21100
+ const r = settled[i];
21101
+ const lead = r.status === "fulfilled" ? r.value : null;
21102
+ return {
21103
+ leadId: c.lead_id,
21104
+ name: lead?.name ?? null,
21105
+ website: lead?.website ?? null,
21106
+ location: lead?.location?.full ?? lead?.location?.city ?? lead?.location?.country ?? null,
21107
+ registry_ids: lead?.registry_ids ?? null,
21108
+ score: c.score,
21109
+ matched_on: c.matched_on,
21110
+ lead_fields_populated: c.lead_fields_populated
21111
+ };
21112
+ });
21113
+ }
20497
21114
  var researchLeadByNameFuzzy = {
20498
21115
  name: "leadbay_research_lead_by_name_fuzzy",
20499
21116
  annotations: {
@@ -20509,11 +21126,23 @@ var researchLeadByNameFuzzy = {
20509
21126
  properties: {
20510
21127
  companyName: {
20511
21128
  type: "string",
20512
- description: "Company name, domain, or contact name to resolve across visible Leadbay leads in Discover, Monitor, and Activate."
21129
+ description: "Company name, domain, or contact name. Resolved against the user's own Discover/Monitor/Activate leads and the Leadbay company registry."
21130
+ },
21131
+ website: {
21132
+ type: "string",
21133
+ description: "Company domain or website when you have one (`acme.com`, `https://www.acme.com/` \u2014 both fine). This is the single strongest match key; pass it whenever the user mentioned a domain, and a company outside their leads becomes findable."
21134
+ },
21135
+ email: {
21136
+ type: "string",
21137
+ description: "A contact email at the company. Used to derive the company domain when `website` is absent; consumer mailboxes (gmail, orange.fr, \u2026) are ignored."
21138
+ },
21139
+ registry_number: {
21140
+ type: "string",
21141
+ description: "Company registry number (SIREN/SIRET in France, company number elsewhere). The other exact match key \u2014 pass it when the user supplies one, or when a previous LEAD_NOT_FOUND hint asked for it."
20513
21142
  },
20514
21143
  lensId: {
20515
21144
  type: "number",
20516
- description: "Optional strict scope. When supplied, search only this lens's wishlist; normally omit to search all visible Leadbay leads."
21145
+ description: "Optional strict scope. When supplied, search only this lens's wishlist and do NOT fall through to the registry; normally omit."
20517
21146
  },
20518
21147
  concise: {
20519
21148
  type: "boolean",
@@ -20529,59 +21158,123 @@ var researchLeadByNameFuzzy = {
20529
21158
  additionalProperties: false
20530
21159
  },
20531
21160
  // Output shape matches leadbay_research_lead_by_id; the only additions are
20532
- // _meta.resolved_from / resolved_query / match_candidates which are
20533
- // documented on _by_id's output schema. Defer to _by_id for the schema —
20534
- // duplicating it would just rot.
21161
+ // _meta.resolved_from / resolved_query / resolved_matched_on /
21162
+ // match_candidates which are documented on _by_id's output schema. Defer to
21163
+ // _by_id for the schema — duplicating it would just rot. The one exception
21164
+ // is the ambiguous branch, which returns a disambiguation payload instead
21165
+ // of a research card.
20535
21166
  outputSchema: {
20536
21167
  type: "object",
20537
- description: "Same shape as leadbay_research_lead_by_id, with _meta.resolved_from='companyName', _meta.resolved_query='<needle>', and _meta.match_candidates=[{leadId,name,score}] populated.",
21168
+ description: "Same shape as leadbay_research_lead_by_id, with _meta.resolved_from='companyName'|'resolver', _meta.resolved_query='<needle>', _meta.resolved_matched_on=[...], and _meta.match_candidates=[{leadId,name,score}] populated. When the registry resolver cannot pick one company, returns {resolution:'ambiguous', query, candidates:[{leadId,name,website,location,registry_ids,score,matched_on}]} instead \u2014 ask the user which one, then call leadbay_research_lead_by_id.",
20538
21169
  additionalProperties: true
20539
21170
  },
20540
21171
  execute: async (client, params, ctx) => {
20541
21172
  if (!params.companyName || typeof params.companyName !== "string" || params.companyName.trim() === "") {
20542
- throw client.makeError("INVALID_PARAMS", "companyName is required", "Pass the company name as a string. If you already have the lead UUID, call leadbay_research_lead_by_id directly.");
21173
+ throw client.makeError("INVALID_PARAMS", "companyName is required and must be a non-empty string", "Pass the company name, domain, or contact name as `companyName` \u2014 e.g. companyName:'Wink Lab'. Add `website` (the strongest match key) or `email` when you have one. If you already have the lead UUID, call leadbay_research_lead_by_id with leadId instead.");
20543
21174
  }
20544
21175
  const query = params.companyName.trim();
20545
- let ranked;
20546
21176
  let lensId = params.lensId;
20547
- let usedActiveLensFallback = false;
20548
- if (lensId !== void 0) {
20549
- ranked = await resolveWithinLens(client, query, lensId);
20550
- } else {
21177
+ if (params.lensId !== void 0) {
21178
+ const scoped = await resolveWithinLens(client, query, params.lensId);
21179
+ if (scoped.length > 0) {
21180
+ return await delegate(scoped, params.lensId);
21181
+ }
21182
+ throw client.makeError("LEAD_NOT_FOUND", `No lead matching "${query}" in lens ${params.lensId}`, "This lookup was intentionally restricted to the supplied lens. Omit lensId to search your visible leads across Discover, Monitor, and Activate and then the Leadbay company registry.");
21183
+ }
21184
+ async function delegate(matches, fallbackLens) {
21185
+ const [primary, ...rest] = matches;
21186
+ const resolvedLens = primary.lensId ?? fallbackLens ?? await client.resolveDefaultLens();
21187
+ return await researchLeadById.execute(client, {
21188
+ leadId: primary.id,
21189
+ lensId: resolvedLens,
21190
+ concise: params.concise,
21191
+ response_format: params.response_format,
21192
+ _resolved: {
21193
+ from: "companyName",
21194
+ query,
21195
+ candidates: rest.slice(0, MAX_AMBIGUOUS_CANDIDATES).map((m) => ({
21196
+ leadId: m.id,
21197
+ name: m.name,
21198
+ score: m.score
21199
+ }))
21200
+ }
21201
+ }, ctx);
21202
+ }
21203
+ const payload = buildResolvePayload({
21204
+ query,
21205
+ website: params.website,
21206
+ email: params.email,
21207
+ registry_number: params.registry_number
21208
+ });
21209
+ let corpusSearched = false;
21210
+ let ranked = [];
21211
+ const searchCorpus = async (strict) => {
20551
21212
  try {
20552
21213
  ranked = await resolveAcrossVisibleCorpus(client, query);
21214
+ corpusSearched = true;
20553
21215
  } catch (error) {
20554
- if (isLeadbayError(error))
21216
+ if (strict && isLeadbayError(error))
20555
21217
  throw error;
20556
- lensId = await client.resolveDefaultLens();
20557
- usedActiveLensFallback = true;
20558
- ctx?.logger?.warn?.("Cross-tab company search was unavailable; falling back to the active lens for this lookup.");
20559
- ranked = rankSubstringMatches(query, await resolveWithinLens(client, query, lensId));
20560
- }
20561
- }
20562
- if (ranked.length === 0) {
20563
- const scope = usedActiveLensFallback ? `in active lens ${lensId}; cross-tab search was unavailable` : params.lensId === void 0 ? "across your visible Leadbay leads" : `in lens ${params.lensId}`;
20564
- const hint = usedActiveLensFallback ? `Only active lens ${lensId} was checked because cross-tab search was unavailable. Retry later before concluding the company is missing or offering to import it.` : params.lensId === void 0 ? "Search checks company names, domains, and contact names across Discover, Monitor, and Activate. Confirm the spelling or domain, or add/import the company first." : "This lookup was intentionally restricted to the supplied lens. Omit lensId to search visible leads across Discover, Monitor, and Activate.";
20565
- throw client.makeError("LEAD_NOT_FOUND", `No lead matching "${query}" ${scope}`, hint);
20566
- }
20567
- const [primary, ...rest] = ranked;
20568
- lensId = primary.lensId ?? lensId ?? await client.resolveDefaultLens();
20569
- const candidates = rest.slice(0, 4).map((m) => ({
20570
- leadId: m.id,
20571
- name: m.name,
20572
- score: m.score
20573
- }));
20574
- return await researchLeadById.execute(client, {
20575
- leadId: primary.id,
20576
- lensId,
20577
- concise: params.concise,
20578
- response_format: params.response_format,
20579
- _resolved: {
20580
- from: "companyName",
20581
- query,
20582
- candidates
21218
+ ctx?.logger?.warn?.("Cross-tab company search was unavailable; resolving against the Leadbay registry instead.");
20583
21219
  }
20584
- }, ctx);
21220
+ };
21221
+ const registryFirst = hasStrongIdentityKey(payload);
21222
+ if (!registryFirst) {
21223
+ await searchCorpus(true);
21224
+ if (ranked.length > 0)
21225
+ return await delegate(ranked);
21226
+ }
21227
+ let resolved;
21228
+ try {
21229
+ resolved = await client.request("POST", "/leads/resolve", payload, { timeoutMs: RESOLVE_TIMEOUT_MS });
21230
+ } catch (error) {
21231
+ if (isLeadbayError(error))
21232
+ throw error;
21233
+ throw client.makeError("LEAD_NOT_FOUND", `Could not reach the Leadbay company registry while looking up "${query}"`, "The registry lookup did not complete. Retry once; if it fails again, say so rather than concluding the company is missing.", "POST /leads/resolve");
21234
+ }
21235
+ if (resolved.type === "matched") {
21236
+ lensId = lensId ?? await client.resolveDefaultLens();
21237
+ return await researchLeadById.execute(client, {
21238
+ leadId: resolved.lead_id,
21239
+ lensId,
21240
+ concise: params.concise,
21241
+ response_format: params.response_format,
21242
+ _resolved: {
21243
+ from: "resolver",
21244
+ query,
21245
+ candidates: [],
21246
+ matched_on: resolved.matched_on
21247
+ }
21248
+ }, ctx);
21249
+ }
21250
+ if (resolved.type === "ambiguous" && resolved.candidates.length > 0) {
21251
+ const hydrationLens = lensId ?? await client.resolveDefaultLens();
21252
+ const candidates = await hydrateAmbiguous(client, resolved.candidates, hydrationLens);
21253
+ return {
21254
+ resolution: "ambiguous",
21255
+ query,
21256
+ resolver_payload: payload,
21257
+ candidates,
21258
+ next_step: "Ask the user which company they mean, then call leadbay_research_lead_by_id with the chosen leadId. Do not guess from score \u2014 it is a tied evidence band, not a confidence.",
21259
+ _meta: {
21260
+ region: client.region,
21261
+ lens_id: hydrationLens,
21262
+ resolved_from: "resolver",
21263
+ resolved_query: query
21264
+ }
21265
+ };
21266
+ }
21267
+ if (!corpusSearched) {
21268
+ await searchCorpus(false);
21269
+ if (ranked.length > 0)
21270
+ return await delegate(ranked);
21271
+ }
21272
+ const registryScope = payload.website ? `the Leadbay company registry (domain ${payload.website})` : "the Leadbay company registry";
21273
+ const searched = corpusSearched ? `in your visible Leadbay leads and in ${registryScope}` : `in ${registryScope} \u2014 your own leads could NOT be searched, the search route was unreachable`;
21274
+ const wanted = resolved.type === "none" && resolved.would_help.length > 0 ? resolved.would_help : ["website", "registry_number"];
21275
+ const asks = wanted.map((f) => f === "registry_number" ? "a registry number (SIREN/SIRET) for `registry_number`" : f === "website" ? "the company website for `website`" : `\`${f}\``).join(" or ");
21276
+ const hint = resolved.type === "unidentifiable" ? `The registry could not identify a company from this input (${resolved.reason}). Ask the user for ${asks}, then call this tool again with it.` : `The registry found no company for what was supplied. It would match on ${asks}. Ask the user for that \u2014 "what's their website?" usually settles it \u2014 then call this tool again. Do not offer an import before asking.`;
21277
+ throw client.makeError("LEAD_NOT_FOUND", `No company matching "${query}" ${searched}`, hint, "POST /leads/resolve");
20585
21278
  }
20586
21279
  };
20587
21280
 
@@ -22632,6 +23325,19 @@ var importAndQualify = {
22632
23325
  type: "string",
22633
23326
  description: "Import handle to pass to leadbay_import_status when wait_for_completion=false."
22634
23327
  },
23328
+ timed_out: {
23329
+ type: "boolean",
23330
+ description: "True when the underlying import ran out of poll budget. Still running server-side \u2014 poll leadbay_import_status(import_ids). Do NOT re-issue the import."
23331
+ },
23332
+ rows_pending_upload: {
23333
+ type: "number",
23334
+ description: "Rows from later chunks that never reached the backend. These are NOT running anywhere; re-import just those rows."
23335
+ },
23336
+ row_ids: {
23337
+ type: "array",
23338
+ description: "Records mode only: the synthetic row id of each input row, in the order you passed `records[]`. leadbay_import_status reports recovered leads by that id \u2014 use this to map them back to your source rows.",
23339
+ items: { type: "string" }
23340
+ },
22635
23341
  // preview-shape keys
22636
23342
  mapping_hints: {
22637
23343
  type: "array",
@@ -22775,7 +23481,7 @@ var importAndQualify = {
22775
23481
  return {
22776
23482
  kind: "result",
22777
23483
  status: "running",
22778
- handle_id: queued.handle_id,
23484
+ ...queued.handle_id ? { handle_id: queued.handle_id } : {},
22779
23485
  ...chosenBudgets ? { chosen_budgets: chosenBudgets } : {},
22780
23486
  qualify_id: null,
22781
23487
  import_ids: queued.importIds,
@@ -22807,7 +23513,35 @@ var importAndQualify = {
22807
23513
  wait_for_completion: true
22808
23514
  }, ctx);
22809
23515
  if (isImportLeadsRunningResult(importResultRaw)) {
22810
- throw client.makeError("IMPORT_ASYNC_UNEXPECTED", "Import returned an async handle while import_and_qualify was waiting for completion", "Retry with wait_for_completion=false and poll leadbay_import_status, or retry the blocking call.", "POST /imports");
23516
+ return {
23517
+ kind: "result",
23518
+ status: "running",
23519
+ ...importResultRaw.handle_id ? { handle_id: importResultRaw.handle_id } : {},
23520
+ // Everything the rendering contract keys off has to survive the
23521
+ // wrapper. Without `timed_out` the agent can't tell this from a
23522
+ // deliberate async launch; without `rows_pending_upload` a >100-row
23523
+ // batch silently loses every unuploaded chunk; without `dry_run`
23524
+ // leadbay_import_status can't tell a validation pass from a real
23525
+ // import still committing.
23526
+ ...importResultRaw.timed_out ? { timed_out: true } : {},
23527
+ ...importResultRaw.rows_pending_upload !== void 0 ? { rows_pending_upload: importResultRaw.rows_pending_upload } : {},
23528
+ ...importResultRaw.dry_run ? { dry_run: true } : {},
23529
+ ...importResultRaw.row_ids ? { row_ids: importResultRaw.row_ids } : {},
23530
+ ...chosenBudgets ? { chosen_budgets: chosenBudgets } : {},
23531
+ qualify_id: null,
23532
+ import_ids: importResultRaw.importIds,
23533
+ notification_ids: importResultRaw.notification_ids ?? [],
23534
+ imported: [],
23535
+ not_imported: (importResultRaw.not_imported ?? []).map(toNotImportedEntry),
23536
+ qualified: [],
23537
+ still_running: [],
23538
+ failed: [],
23539
+ quota_exceeded: false,
23540
+ skipped_already_qualified: [],
23541
+ not_in_lens: [],
23542
+ region: client.region,
23543
+ _meta: importResultRaw._meta
23544
+ };
22811
23545
  }
22812
23546
  const importResult = importResultRaw;
22813
23547
  if (importResult.cancelled) {
@@ -23067,7 +23801,7 @@ async function runPreview(client, params, ctx, perPhaseBudget, _totalBudget) {
23067
23801
  throw Object.assign(new Error("aborted"), { name: "AbortError" });
23068
23802
  }
23069
23803
  if (!fileImport) {
23070
- throw client.makeError("IMPORT_BUDGET_EXHAUSTED", `Preview preprocess did not finish within ${perPhaseBudget}ms`, "Increase per_phase_budget_ms or shrink the input. The wizard row will eventually be cleaned up.", `GET /imports/${importId}`);
23804
+ throw client.makeError("IMPORT_TIMEOUT", `Preview preprocess did not finish within ${perPhaseBudget}ms`, `Raise per_phase_budget_ms above ${perPhaseBudget} or send fewer rows \u2014 re-running the identical call will not help. The wizard row will eventually be cleaned up.`, `GET /imports/${importId}`);
23071
23805
  }
23072
23806
  if (fileImport.pre_processing?.error) {
23073
23807
  throw client.makeError("IMPORT_PREPROCESS_FAILED", `Preview preprocess failed: ${fileImport.pre_processing.error}`, "Inspect the input rows for encoding / shape issues.", `GET /imports/${importId}`);
@@ -23150,6 +23884,72 @@ function summarizeImports(imports, dryRun) {
23150
23884
  records_total: recordsTotal
23151
23885
  };
23152
23886
  }
23887
+ var RECORDS_PAGE_SIZE = 100;
23888
+ var RECORDS_MAX_PAGES = 20;
23889
+ var ImportNotReady = class extends Error {
23890
+ };
23891
+ function isInProgress(err) {
23892
+ return /in_progress/i.test(String(err?.message ?? ""));
23893
+ }
23894
+ async function fetchReconciledRecords(client, importIds, declaredTotal, ctx) {
23895
+ const canonicalLeadIds = /* @__PURE__ */ new Set();
23896
+ for (const importId of importIds) {
23897
+ try {
23898
+ const res = await client.request("GET", `/imports/${importId}/leads`);
23899
+ for (const id of res?.lead_ids ?? [])
23900
+ canonicalLeadIds.add(id);
23901
+ } catch (err) {
23902
+ if (isInProgress(err))
23903
+ throw new ImportNotReady();
23904
+ if (err?.code !== "NOT_FOUND" && err?._meta?.http_status !== 404)
23905
+ throw err;
23906
+ ctx?.logger?.warn?.(`import-status: /imports/${importId}/leads not available on this backend (404) \u2014 using records only`);
23907
+ }
23908
+ }
23909
+ const all = [];
23910
+ for (const importId of importIds) {
23911
+ for (let page = 0; page < RECORDS_MAX_PAGES; page++) {
23912
+ const qs = `count=${RECORDS_PAGE_SIZE}&page=${page}&automatic_match=true&manual_match=true&no_match=true&matching=true&importing=true&imported=true`;
23913
+ let res;
23914
+ try {
23915
+ res = await client.request("GET", `/imports/${importId}/records?${qs}`);
23916
+ } catch (err) {
23917
+ if (isInProgress(err))
23918
+ throw new ImportNotReady();
23919
+ throw err;
23920
+ }
23921
+ all.push(...res.items);
23922
+ const totalPages = res.pagination.pages ?? 0;
23923
+ if (page + 1 >= totalPages)
23924
+ break;
23925
+ if (page + 1 === RECORDS_MAX_PAGES) {
23926
+ ctx?.logger?.warn?.(`import-status: importId=${importId} has >${RECORDS_MAX_PAGES} record pages; skipping reconciliation`);
23927
+ return null;
23928
+ }
23929
+ }
23930
+ }
23931
+ const { leads, not_imported, pending, distinct, pendingLeadIds } = reconcileRecords(all);
23932
+ const deficit = settlingDeficit(declaredTotal, distinct);
23933
+ const seenLeadIds = new Set(leads.map((l) => l.leadId));
23934
+ const merged = [...leads];
23935
+ if (deficit === 0) {
23936
+ for (const id of canonicalLeadIds) {
23937
+ if (seenLeadIds.has(id))
23938
+ continue;
23939
+ if (pendingLeadIds.has(id))
23940
+ continue;
23941
+ merged.push({ leadId: id, name: null });
23942
+ }
23943
+ }
23944
+ return {
23945
+ leads: merged,
23946
+ not_imported,
23947
+ // A snapshot short of the declared row count is not final — see
23948
+ // `settlingDeficit`. Measured on DISTINCT rows: `all.length` counts a
23949
+ // re-paged row twice and would mask a genuine shortfall.
23950
+ still_settling: pending + deficit
23951
+ };
23952
+ }
23153
23953
  var importStatus = {
23154
23954
  name: "leadbay_import_status",
23155
23955
  annotations: {
@@ -23169,8 +23969,12 @@ var importStatus = {
23169
23969
  },
23170
23970
  importIds: {
23171
23971
  type: "array",
23172
- description: "Legacy backend file-import ids to inspect directly.",
23972
+ description: "Backend file-import ids to inspect directly \u2014 from a completed import's `importIds`, or from a `{status:'running', timed_out:true}` result.",
23173
23973
  items: { type: "string" }
23974
+ },
23975
+ dry_run: {
23976
+ type: "boolean",
23977
+ description: "Pass true when the importIds came from a dry run. A dry run and an import still committing its mappings look identical on the wire, so without this the tool reports the dry run as still running rather than risk rendering it as a real import."
23174
23978
  }
23175
23979
  },
23176
23980
  additionalProperties: false
@@ -23184,9 +23988,13 @@ var importStatus = {
23184
23988
  progress: { type: "object" },
23185
23989
  result: {
23186
23990
  type: "object",
23187
- description: "Final import result when the handle has completed in this MCP instance."
23991
+ description: "Final import result: {leads, not_imported, importIds, still_settling?}. Present when a handle_id resolves a completed run in this MCP instance, OR when the importIds[] path finds every import complete and reconciles the wizard's records."
23188
23992
  },
23189
23993
  error: { type: "string" },
23994
+ dry_run: {
23995
+ type: "boolean",
23996
+ description: "True when these importIds came from a dry run. NOTHING was committed to the CRM \u2014 render it as a validation pass, never as a completed import."
23997
+ },
23190
23998
  region: { type: "string" },
23191
23999
  _meta: { type: "object" }
23192
24000
  },
@@ -23195,7 +24003,7 @@ var importStatus = {
23195
24003
  execute: async (client, params, ctx) => {
23196
24004
  let handleId = params.handle_id;
23197
24005
  let importIds = params.importIds ?? [];
23198
- let handleDryRun;
24006
+ let handleDryRun = params.dry_run;
23199
24007
  if (handleId) {
23200
24008
  if (!isValidBulkId(handleId)) {
23201
24009
  throw client.makeError("BULK_INVALID_ID", "handle_id is not a valid UUIDv4", "Pass the handle_id returned by leadbay_import_leads verbatim.", "");
@@ -23212,7 +24020,7 @@ var importStatus = {
23212
24020
  throw client.makeError("BULK_NOT_FOUND", "No import record for that handle_id", "It may have expired (30-day TTL) or the MCP process was restarted without persistence.", "");
23213
24021
  }
23214
24022
  importIds = record.import_ids;
23215
- handleDryRun = record.dry_run;
24023
+ handleDryRun = record.dry_run ?? handleDryRun;
23216
24024
  if (record.status === "complete" && record.result) {
23217
24025
  return {
23218
24026
  status: "complete",
@@ -23273,6 +24081,7 @@ var importStatus = {
23273
24081
  };
23274
24082
  }
23275
24083
  }
24084
+ importIds = [...new Set(importIds)];
23276
24085
  if (importIds.length === 0) {
23277
24086
  throw client.makeError("IMPORT_STATUS_INPUT_REQUIRED", "Pass either handle_id or importIds[]", "Call leadbay_import_leads with wait_for_completion=false first, then pass its handle_id.", "");
23278
24087
  }
@@ -23288,14 +24097,40 @@ var importStatus = {
23288
24097
  return Boolean(i.processing?.finished);
23289
24098
  return Boolean(i.processing?.finished || i.pre_processing?.finished && !i.processing);
23290
24099
  });
24100
+ let reconciled = null;
24101
+ const commitError = commitFailureFor(importIds);
24102
+ let notReady = false;
24103
+ const declaredTotal = imports.reduce((n, i) => n + Number(i.total_records ?? 0), 0);
24104
+ if (!failed && complete && handleDryRun !== true && importIds.length > 0) {
24105
+ try {
24106
+ reconciled = await fetchReconciledRecords(client, importIds, declaredTotal, ctx);
24107
+ } catch (err) {
24108
+ if (err instanceof ImportNotReady) {
24109
+ notReady = true;
24110
+ ctx?.logger?.info?.(`import-status: wizard reports in_progress; mappings not committed yet \u2014 reporting running`);
24111
+ } else {
24112
+ ctx?.logger?.warn?.(`import-status: records reconciliation failed (${err?.code ?? err?.message ?? "unknown"}); returning status only`);
24113
+ }
24114
+ }
24115
+ }
24116
+ const settled = complete && !notReady;
23291
24117
  return {
23292
- status: failed ? "failed" : complete ? "complete" : "running",
24118
+ status: failed || commitError ? "failed" : settled ? "complete" : "running",
23293
24119
  ...handleId ? { handle_id: handleId } : {},
23294
24120
  importIds,
23295
- progress,
24121
+ ...handleDryRun === true ? { dry_run: true } : {},
24122
+ progress: notReady ? { ...progress, phase: "committing" } : progress,
24123
+ ...reconciled ? {
24124
+ result: {
24125
+ leads: reconciled.leads,
24126
+ not_imported: reconciled.not_imported,
24127
+ importIds,
24128
+ ...reconciled.still_settling > 0 ? { still_settling: reconciled.still_settling } : {}
24129
+ }
24130
+ } : {},
23296
24131
  ...failed ? {
23297
24132
  error: failed.pre_processing?.error ?? failed.processing?.error ?? "import failed"
23298
- } : {},
24133
+ } : commitError ? { error: `Import mappings were rejected: ${commitError}` } : {},
23299
24134
  region: client.region,
23300
24135
  _meta: client.lastMeta ?? {
23301
24136
  region: client.region,
@@ -25140,6 +25975,48 @@ async function readExtraRefillQuota(client) {
25140
25975
  return { count: null, resets_at: null };
25141
25976
  }
25142
25977
  }
25978
+ async function readAvailablePool(client, lensId) {
25979
+ try {
25980
+ const preview = await client.request("GET", `/lenses/${lensId}/extra_refill_preview`);
25981
+ return typeof preview?.available_count === "number" ? preview.available_count : null;
25982
+ } catch {
25983
+ return null;
25984
+ }
25985
+ }
25986
+ async function readLensLeadTotal(client, lensId) {
25987
+ try {
25988
+ const page = await client.request("GET", `/lenses/${lensId}/leads/wishlist?count=1&page=0`);
25989
+ return typeof page?.pagination?.total === "number" ? page.pagination.total : null;
25990
+ } catch {
25991
+ return null;
25992
+ }
25993
+ }
25994
+ function noCandidatesReason(held, shape) {
25995
+ const { geoSentence, ...extras } = shape;
25996
+ 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.";
25997
+ if (held === 0) {
25998
+ return {
25999
+ code: "audience_too_narrow",
26000
+ retryable: false,
26001
+ 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).",
26002
+ ...extras
26003
+ };
26004
+ }
26005
+ if (held !== null) {
26006
+ return {
26007
+ code: "no_new_leads",
26008
+ retryable: false,
26009
+ message: `Every company matching this lens has already been delivered \u2014 all ${held} of them \u2014 so there is nothing left to add.` + futile + " Tell the user; offer to widen the audience (leadbay_adjust_audience) or work the leads already in the lens (leadbay_pull_followups).",
26010
+ ...extras
26011
+ };
26012
+ }
26013
+ return {
26014
+ code: "no_candidates",
26015
+ retryable: false,
26016
+ message: "This lens has no candidates left to add." + geoSentence + futile + " Tell the user and offer to widen the audience (leadbay_adjust_audience).",
26017
+ ...extras
26018
+ };
26019
+ }
25143
26020
  var extendLens = {
25144
26021
  name: "leadbay_extend_lens",
25145
26022
  annotations: {
@@ -25176,7 +26053,7 @@ var extendLens = {
25176
26053
  properties: {
25177
26054
  status: {
25178
26055
  type: "string",
25179
- description: "queued | quota_exceeded | refresh_in_progress | no_valid_seeds"
26056
+ description: "queued | no_candidates | quota_exceeded | refresh_in_progress | no_valid_seeds"
25180
26057
  },
25181
26058
  lens: {
25182
26059
  type: "object",
@@ -25191,6 +26068,35 @@ var extendLens = {
25191
26068
  type: "string",
25192
26069
  description: "Human-readable summary. On error statuses, this is the line to surface to the user."
25193
26070
  },
26071
+ available_count: {
26072
+ type: ["number", "null"],
26073
+ description: "How many leads a refill on this lens could still draw, read from /extra_refill_preview before queueing. 0 means the refill was NOT queued (status=no_candidates). null means the pool could not be read and the refill was queued anyway."
26074
+ },
26075
+ reason: {
26076
+ type: "object",
26077
+ description: "Only present on status=no_candidates. Same shape and `code` vocabulary as leadbay_pull_leads' empty_reason, so one routing rule covers both tools.",
26078
+ properties: {
26079
+ code: {
26080
+ type: "string",
26081
+ description: "audience_too_narrow (lens holds nothing and its criteria intersect to nothing) | no_new_leads (everything matching has already been delivered) | no_candidates (pool is empty; which of the two could not be determined)"
26082
+ },
26083
+ message: { type: "string" },
26084
+ retryable: {
26085
+ type: "boolean",
26086
+ description: "Always false here. Re-calling leadbay_extend_lens cannot change the outcome \u2014 widen the audience instead."
26087
+ },
26088
+ criteria: {
26089
+ type: "object",
26090
+ description: "The criteria in play, so the agent can name them."
26091
+ },
26092
+ narrow_locations: {
26093
+ type: "array",
26094
+ description: "Include-locations that resolved to city-scale or smaller \u2014 the usual thing to relax first.",
26095
+ items: { type: "object" }
26096
+ }
26097
+ },
26098
+ required: ["code", "message", "retryable"]
26099
+ },
25194
26100
  quota: {
25195
26101
  type: "object",
25196
26102
  description: "Only present on status=quota_exceeded. Shows the org's daily LENS_EXTRA_REFILL state.",
@@ -25204,6 +26110,21 @@ var extendLens = {
25204
26110
  },
25205
26111
  execute: async (client, params) => {
25206
26112
  const lensId = params.lensId ?? await client.resolveDefaultLens();
26113
+ const availableCount = await readAvailablePool(client, lensId);
26114
+ if (availableCount === 0) {
26115
+ const [shape, held] = await Promise.all([
26116
+ readAudienceShape(client, lensId),
26117
+ readLensLeadTotal(client, lensId)
26118
+ ]);
26119
+ const reason = noCandidatesReason(held, shape);
26120
+ return {
26121
+ status: "no_candidates",
26122
+ lens: { id: lensId },
26123
+ available_count: 0,
26124
+ reason,
26125
+ message: reason.message
26126
+ };
26127
+ }
25207
26128
  const body = {
25208
26129
  seed_lead_ids: params.seed_lead_ids ?? []
25209
26130
  };
@@ -25215,6 +26136,7 @@ var extendLens = {
25215
26136
  return {
25216
26137
  status: "queued",
25217
26138
  lens: { id: lensId },
26139
+ available_count: availableCount,
25218
26140
  accepted_seeds: res.accepted_seeds,
25219
26141
  message: "Extra refill queued. Leads stream in asynchronously \u2014 call leadbay_pull_leads in ~30s to see them."
25220
26142
  };
@@ -26363,9 +27285,9 @@ var sendFeedback = {
26363
27285
  };
26364
27286
 
26365
27287
  // ../core/dist/artifact-runtime.generated.js
26366
- var ARTIFACT_KIT_VERSION = "0.3.1";
26367
- var ARTIFACT_RUNTIME = '"use strict";(()=>{var _=Object.defineProperty;var k=(e,t,n)=>t in e?_(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var o=(e,t,n)=>k(e,typeof t!="symbol"?t+"":t,n);var T="0.3.1",d=class extends Error{constructor(n,i={}){super(n);o(this,"code");o(this,"raw");this.name="LbError",this.code=i.code,this.raw=i.raw}},v=null,f=3e4;function L(){let e=globalThis.cowork;return e&&typeof e.callMcpTool=="function"?(t,n)=>e.callMcpTool(t,n):null}function p(e){if(e&&typeof e=="object"&&"content"in e){let t=e.content;if(Array.isArray(t)&&t[0]&&typeof t[0].text=="string")return t[0].text}return null}function y(e){if(!e||typeof e!="object")return e;let t=e;if(t.isError)throw new d(p(e)??"tool call failed",{raw:e});if("structuredContent"in t&&t.structuredContent!=null)return t.structuredContent;let n=p(e);if(n!=null)try{return JSON.parse(n)}catch{return n}return e}function E(e){return e instanceof Error?e.message:String(e)}function m(e){let t=e instanceof d?e.code:void 0;return{message:E(e),unavailable:t==="unavailable",code:t}}function S(e={}){v=e.call??null,f=e.timeoutMs??3e4}async function w(e,t){if(!f||f<=0)return e;let n,i=new Promise((r,a)=>{n=setTimeout(()=>a(new d(`"${t}" timed out after ${f}ms`,{code:"timeout"})),f)});try{return await Promise.race([e,i])}finally{n&&clearTimeout(n)}}async function s(e,t={}){if(v)return y(await w(Promise.resolve(v(e,t)),e));let n=L();if(!n)throw new d("Leadbay bridge unavailable (window.cowork absent)",{code:"unavailable"});return y(await w(Promise.resolve(n(e,t)),e))}var c=class{constructor(){o(this,"subs",new Set)}subscribe(t){return this.subs.add(t),t(this),()=>this.subs.delete(t)}emit(){for(let t of this.subs)t(this)}};function A(e){return Array.isArray(e)?e.map(t=>t&&typeof t=="object"?t:{value:t,label:String(t)}):[]}var h=class extends c{constructor(n={}){super();o(this,"kind");o(this,"value");o(this,"options",[]);o(this,"loading",!1);o(this,"error",null);o(this,"ready",!1);o(this,"cfg");o(this,"depUnsubs",[]);o(this,"seq",0);this.cfg=n,this.kind=n.kind,this.value=n.value??"";for(let i of n.dependsOn??[]){let r=i.value;this.depUnsubs.push(i.subscribe(()=>{i.value!==r&&(r=i.value,this.cfg.load&&this.load())}))}n.load&&(n.autoLoad??!0)&&this.load()}async load(){if(!this.cfg.load)return;let n=++this.seq;this.loading=!0,this.error=null,this.emit();try{let i=await this.cfg.load();if(n!==this.seq)return;this.options=this.cfg.options?this.cfg.options(i):A(i),this.ready=!0;let r=this.value==null?"":String(this.value);this.options.length&&(r===""||!this.options.some(a=>String(a.value)===r))&&(this.value=this.options[0].value)}catch(i){if(n!==this.seq)return;this.options=[],this.error=m(i)}finally{n===this.seq&&(this.loading=!1,this.emit())}}setValue(n){this.value=n;let i=this.validate();this.error=i?{message:i,unavailable:!1}:null,this.emit()}validate(){return this.cfg.validate?this.cfg.validate(this.value):null}get valid(){return this.validate()==null}reset(){this.value=this.cfg.value??"",this.error=null,this.emit()}dispose(){for(let n of this.depUnsubs)n();this.depUnsubs=[]}},l=class extends c{constructor(n){super();o(this,"loading",!1);o(this,"error",null);o(this,"lastResult",null);o(this,"cfg");this.cfg=n}async run(){if(this.loading)return;for(let i of this.cfg.fields??[]){let r=i.validate();if(r!=null){this.error={message:r,unavailable:!1},this.emit();return}}if(this.cfg.confirm&&typeof globalThis.confirm=="function"&&!globalThis.confirm(this.cfg.confirm))return;this.loading=!0,this.error=null,this.emit();let n;try{let i=typeof this.cfg.args=="function"?this.cfg.args():this.cfg.args??{};n=await s(this.cfg.tool,i)}catch(i){this.error=m(i),this.loading=!1,this.emit(),this.cfg.onError?.(this.error);return}return this.lastResult=n,this.loading=!1,this.emit(),this.cfg.onSuccess?.(n),n}reset(){this.error=null,this.lastResult=null,this.emit()}},u=class extends c{constructor(n){super();o(this,"data",null);o(this,"loading",!1);o(this,"refreshing",!1);o(this,"error",null);o(this,"done",!1);o(this,"cfg");o(this,"timer",null);o(this,"seq",0);this.cfg=n,(n.autoLoad??!0)&&this.load()}async load(){this.clearTimer();let n=++this.seq;this.data==null?this.loading=!0:this.refreshing=!0,this.error=null,this.emit();try{let r=await this.cfg.load();if(n!==this.seq)return;this.data=r,this.done=this.cfg.until?this.cfg.until(r):!0,this.cfg.pollEvery&&!this.done&&(this.timer=setTimeout(()=>void this.load(),this.cfg.pollEvery))}catch(r){if(n!==this.seq)return;this.error=m(r)}finally{n===this.seq&&(this.loading=!1,this.refreshing=!1,this.emit())}}refresh(){return this.load()}stop(){this.clearTimer()}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null)}},b=class extends c{constructor(n){super();o(this,"items",[]);o(this,"page",0);o(this,"pageSize");o(this,"total",0);o(this,"loading",!1);o(this,"error",null);o(this,"cfg");o(this,"seq",0);this.cfg=n,this.pageSize=n.pageSize??20,(n.autoLoad??!0)&&this.loadPage(0)}async loadPage(n){let i=++this.seq;this.loading=!0,this.error=null,this.emit();try{let r=await this.cfg.load({page:n,pageSize:this.pageSize});if(i!==this.seq)return;this.items=r.items??[],this.total=r.total??this.items.length,this.page=n}catch(r){if(i!==this.seq)return;this.error=m(r)}finally{i===this.seq&&(this.loading=!1,this.emit())}}next(){return this.loadPage(this.page+1)}prev(){return this.loadPage(Math.max(0,this.page-1))}get hasMore(){return(this.page+1)*this.pageSize<this.total}};function x(e,t){let n=t.error?.unavailable?"unavailable":t.loading?"loading":t.error?"error":"ready";e.setAttribute("data-lb-state",n),t.error?e.setAttribute("data-lb-error",t.error.message):e.removeAttribute("data-lb-error")}function C(e,t){let n=()=>t.setValue(e.value);e.addEventListener("change",n);let i=t.subscribe(()=>{x(e,t),e.disabled=t.loading,e.innerHTML="";for(let r of t.options){let a=document.createElement("option");a.value=String(r.value),a.textContent=r.label,e.appendChild(a)}e.value=t.value==null?"":String(t.value)});return()=>{e.removeEventListener("change",n),i()}}function R(e,t){let n=e.type==="checkbox",i=e.tagName==="SELECT"?"change":"input",r=()=>t.setValue(n?e.checked:e.value);e.addEventListener(i,r);let a=t.subscribe(()=>{if(n)e.checked=!!t.value;else{let g=t.value==null?"":String(t.value);e.value!==g&&(e.value=g)}e.setAttribute("data-lb-state",t.error?"error":"ready"),t.error?e.setAttribute("data-lb-error",t.error.message):e.removeAttribute("data-lb-error")});return()=>{e.removeEventListener(i,r),a()}}function I(e,t){let n=r=>{r.preventDefault(),t.run()};e.addEventListener("click",n);let i=t.subscribe(()=>{let r=t.error?.unavailable?"unavailable":t.loading?"loading":t.error?"error":t.lastResult!=null?"success":"idle";e.setAttribute("data-lb-state",r),"disabled"in e&&(e.disabled=t.loading),t.error?e.setAttribute("data-lb-error",t.error.message):e.removeAttribute("data-lb-error")});return()=>{e.removeEventListener("click",n),i()}}var O=["STILL_CHASING","COULD_NOT_REACH_STILL_TRYING","INTEREST_VALIDATED_OR_MEETING_PLANED","NOT_INTERESTED_LOST"];function P(e){return new h({kind:"select",load:()=>s("leadbay_list_campaigns",{_triggered_by:e}),options:t=>(t?.campaigns??[]).map(i=>{let r=i?.campaign??i;return r?.id?{value:r.id,label:r.name??r.ai_generated_name??String(r.id)}:null}).filter(i=>i!=null)})}function M(e){return new l({tool:"leadbay_report_outreach",fields:e.note?[e.note]:[],args:()=>({lead_id:e.leadId,...e.status?{epilogue_status:e.status.value}:{},note:e.note?e.note.value:"",verification:{source:"user_confirmed",ref:e.ref??"logged from artifact"},_triggered_by:e.ask})})}function F(e){return new l({tool:"leadbay_add_note",fields:[e.note],args:()=>({leadId:e.leadId,note:e.note.value})})}function q(e){return new l({tool:"leadbay_like_lead",args:{lead_id:e}})}function H(e){return new l({tool:"leadbay_dislike_lead",args:{lead_id:e}})}function z(e,t){return new u({autoLoad:!1,load:()=>s("leadbay_account_history",{leadId:e,_triggered_by:t})})}function N(e,t){return new u({autoLoad:!1,load:()=>s("leadbay_research_lead_by_id",{leadId:e,_triggered_by:t})})}function U(e){let t=null;return new u({...e.autoLoad!==void 0?{autoLoad:e.autoLoad}:{},pollEvery:e.pollEvery??4e3,until:n=>!!n?.all_done,load:async()=>{if(!t){let n=await s("leadbay_enrich_titles",{...e.leadIds?{leadIds:e.leadIds}:{},titles:e.titles,...e.email!==void 0?{email:e.email}:{},...e.phone!==void 0?{phone:e.phone}:{},...e.confirm!==void 0?{confirm:e.confirm}:{},_triggered_by:e.ask});if(t=n?.bulk_id??null,!t)return{...n,all_done:!0,no_job:!0}}return s("leadbay_bulk_enrich_status",{bulk_id:t,_triggered_by:e.ask})}})}function D(e){let t=e.source??"followups";return new b({pageSize:e.pageSize??20,load:async({page:n,pageSize:i})=>{let a=t==="campaign"?await s("leadbay_campaign_call_sheet",{campaign_id:e.campaignId,page:n,count:i,_triggered_by:e.ask}):await s("leadbay_pull_followups",{page:n,count:i,...e.city?{city:e.city}:{},_triggered_by:e.ask}),g=a.leads??a.items??[];return{items:g,total:a.total_leads??a.pagination?.total??g.length}}})}function V(e){return new u({load:()=>s("leadbay_team_activity",{weeks:e.weeks??4,_triggered_by:e.ask})})}var j={VERSION:T,configure:S,call:s,field:e=>new h(e),action:e=>new l(e),resource:e=>new u(e),list:e=>new b(e),bindSelect:C,bindValue:R,bindAction:I,campaigns:P,outreach:M,note:F,like:q,dislike:H,leadHistory:z,leadProfile:N,enrichment:U,callList:D,teamActivity:V,EPILOGUE_STATUSES:O};typeof globalThis<"u"&&(globalThis.LeadbayArtifacts=j);})();';
26368
- var ARTIFACT_USAGE_GUIDE = '# Leadbay Artifact Kit \u2014 headless domain components\n\nYou are building a single-file HTML **artifact** the user runs inside cowork. This\nkit gives you **headless view-models** that own a control\'s whole data lifecycle \u2014\nload/populate from a Leadbay call, hold value/state, poll, validate, and\nencapsulate the API call + business rules. **You own 100% of markup/layout/style.**\nThe library renders nothing. Inline the runtime once as a `<script>`; it exposes\none global `window.LeadbayArtifacts` (call it `lb`). Vanilla, no React, no build.\n\nPass every tool you use as the artifact\'s `mcp_tools` so the host permits it.\n\n## Two layers\n\n**Primitives** (generic):\n- `lb.field({ load, options, value, validate, dependsOn })` \u2014 a value + optionally\n API-populated options. `.value/.setValue/.options/.loading/.error/.valid/.subscribe`.\n- `lb.action({ tool, args, fields, confirm, onSuccess, onError })` \u2014 a write/submit.\n `.run()/.loading/.error/.lastResult/.subscribe`.\n- `lb.resource({ load, pollEvery?, until?, autoLoad? })` \u2014 one read that may change:\n load-on-click or poll-until-`until`. `.data/.loading/.refreshing/.error/.done/.load()/.refresh()/.stop()/.subscribe`.\n- `lb.list({ load, pageSize })` \u2014 paginated rows. `.items/.page/.total/.loading/.loadPage(n)/.next()/.prev()/.hasMore/.subscribe`.\n\n`.error` is `{ message, unavailable } | null`. `subscribe(cb)` fires immediately\nthen on every change \u2014 render your own DOM from it.\n\n**Domain components** (pre-wired \u2014 bake in the tool name, arg shape, and footguns):\n\n| Call | Returns | For |\n|---|---|---|\n| `lb.campaigns(ask)` | field | a campaign `<select>`, options from `leadbay_list_campaigns` |\n| `lb.outreach({leadId, ask, status?, note?})` | action | log a call \u2192 `report_outreach` (verification + `_triggered_by` baked in) |\n| `lb.note({leadId, note})` | action | add a note \u2192 `add_note` |\n| `lb.like(leadId)` / `lb.dislike(leadId)` | action | taste signal |\n| `lb.leadHistory(leadId, ask)` | resource (lazy) | notes + activities + engagement \u2192 `account_history` |\n| `lb.leadProfile(leadId, ask)` | resource (lazy) | full lead profile \u2192 `research_lead_by_id` |\n| `lb.callList({source:\'followups\'\\|\'campaign\', campaignId?, city?, ask})` | list | a cold-call list (Monitor or a campaign) |\n| `lb.enrichment({leadIds, titles, ask, pollEvery?})` | resource (polling) | launch + watch contact enrichment |\n| `lb.teamActivity({weeks, ask})` | resource | manager leaderboard + activity trend \u2192 `leadbay_team_activity` |\n\n`lb.EPILOGUE_STATUSES` = the 4 disposition values\n(`STILL_CHASING`, `COULD_NOT_REACH_STILL_TRYING`, `INTEREST_VALIDATED_OR_MEETING_PLANED`, `NOT_INTERESTED_LOST`).\n\n**Binding sugar** (optional; binds a view-model to YOUR native element, no style):\n`lb.bindSelect(selectEl, field)` (populates options + value), `lb.bindValue(inputEl, field)`,\n`lb.bindAction(buttonEl, action)`. They set `data-lb-state`\n(`ready|loading|error|success|unavailable`) + `data-lb-error` on your element as\nstyling hooks. For lists/resources, use `.subscribe()` and render yourself.\n\n`ask` is the user\'s request this artifact serves \u2014 it becomes `_triggered_by`.\n\n## Recipe: cold-call sheet (one row per lead)\n\n```js\nconst lb = window.LeadbayArtifacts; lb.configure();\nconst ASK = "<the user\'s request>";\n\nconst list = lb.callList({ source: "campaign", campaignId: CID, ask: ASK });\nlist.subscribe((l) => renderRows(l.items, l.loading)); // your render\n\n// per lead row (call when you build a row):\nfunction wireRow(lead, els) {\n const status = lb.field({ value: "STILL_CHASING" }); // static-enum <select>\n const note = lb.field({ validate: (v) => (v && v.trim() ? null : "Add a note") });\n lb.bindValue(els.status, status);\n lb.bindValue(els.note, note);\n lb.bindAction(els.log, lb.outreach({ leadId: lead.id, ask: ASK, status, note }));\n lb.bindAction(els.like, lb.like(lead.id));\n\n const history = lb.leadHistory(lead.id, ASK); // lazy\n history.subscribe((h) => renderHistory(els.history, h));\n els.expand.onclick = () => history.load(); // load on click\n}\n```\n\n## Recipe: manager dashboard\n\n```js\nconst team = lb.teamActivity({ weeks: 4, ask: ASK });\nteam.subscribe((t) => {\n if (t.loading) showSpinner();\n if (t.data) {\n renderLeaderboard(t.data.reps); // sorted by total_activities; cols: name, notes, meetings_or_interest, lost\u2026\n renderTrendChart(t.data.trend); // [{date,count}] \u2192 Chart.js (allowed from CDN)\n }\n});\nrefreshBtn.onclick = () => team.refresh();\n```\n\n## Recipe: live enrichment\n\n```js\nconst job = lb.enrichment({ leadIds: [LEAD], titles: ["CEO", "VP Sales"], ask: ASK });\njob.subscribe((j) => {\n const p = j.data && j.data.overall_progress; // {done,total,done_ratio}\n renderBar(p);\n if (j.done) renderContacts(j.data.leads); // enriched contacts\n});\nrefreshBtn.onclick = () => job.refresh();\n```\n\n## Write-call rules\n\nThe domain factories handle these for you. If you hand-roll an action:\n`leadbay_report_outreach` args MUST include `verification:{source:"user_confirmed", ref}`\nAND `_triggered_by`; `leadbay_add_leads_to_campaign` needs `_triggered_by`;\n`add_note`/`like_lead`/`dislike_lead` take only their own args. `epilogue_status` is\none of `lb.EPILOGUE_STATUSES`. Snoozing (pushback) and org WON/LOST status are\nadvanced-gated \u2014 not callable from a default artifact; use the epilogue values.\n\n## Degradation + live updates\n\nIf the host bridge is absent, a view-model\'s `.error` is set with `.error.unavailable\n=== true` (bind helpers set `data-lb-state="unavailable"`) \u2014 nothing throws. Every\ncall also has a **30s timeout** (configurable via `lb.configure({ timeoutMs })`): a\nhost call that never settles becomes `.error` with `code:"timeout"`, so a control is\nnever stuck loading forever \u2014 always render the `.error` branch so the user can retry.\nAuto-poll (`pollEvery`) depends on the cowork host serving FRESH reads; `.refresh()`\nis the guaranteed manual path \u2014 always wire a Refresh control for polling resources.';
27288
+ var ARTIFACT_KIT_VERSION = "0.5.0";
27289
+ var ARTIFACT_RUNTIME = '"use strict";(()=>{var L=Object.defineProperty;var A=(e,r,t)=>r in e?L(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var a=(e,r,t)=>A(e,typeof r!="symbol"?r+"":r,t);var S=`\n:root{\n--color-black:#191919;--color-white:#fff;\n--color-gray-1:#f9f9f9;--color-gray-2:#f0f0f0;--color-gray-3:#e0e0e0;--color-gray-4:#cecece;\n--color-gray-5:#c4c4c4;--color-gray-6:#8d8d8d;--color-gray-7:#787878;--color-gray-8:#646464;\n--color-gray-9:#202020;\n--color-linkedin:#0a66c2;\n--color-blue-background:oklch(0.947 0.029 251);--color-blue-foreground:oklch(0.564 0.181 251);\n--color-green-background:oklch(0.947 0.029 141);--color-green-foreground:oklch(0.564 0.181 141);\n--color-red-background:oklch(0.947 0.029 26);--color-red-foreground:oklch(0.564 0.191 26);\n--color-gold-background:oklch(0.972 0.049 91);--color-gold-foreground:oklch(0.667 0.177 91);\n--color-cherry-background:oklch(0.947 0.029 15);--color-cherry-foreground:oklch(0.44 0.146 15);\n--color-red-like:var(--color-cherry-foreground);\n--lb-font:"Nikkei Maru",system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;\n--lb-radius:1rem;--lb-radius-sm:0.625rem;--lb-gap:0.75rem;\n--lb-surface:var(--color-gray-1);--lb-border:var(--color-gray-3);\n--lb-fg:var(--color-black);--lb-muted:var(--color-gray-8);--lb-field:var(--color-white);\n}\n:root[data-theme=dark],:root[data-lb-theme=dark]{\n--lb-surface:var(--color-gray-9);--lb-border:var(--color-gray-8);\n--lb-fg:var(--color-white);--lb-muted:var(--color-gray-3);--lb-field:var(--color-gray-9);\n}\n@media(prefers-color-scheme:dark){:root:not([data-theme=light]):not([data-lb-theme=light]){\n--lb-surface:var(--color-gray-9);--lb-border:var(--color-gray-8);\n--lb-fg:var(--color-white);--lb-muted:var(--color-gray-3);--lb-field:var(--color-gray-9);\n}}\n.lb-card{display:grid;gap:var(--lb-gap);padding:0.875rem;\nbackground-color:var(--lb-surface);border:1px solid var(--lb-border);\nborder-radius:var(--lb-radius);corner-shape:squircle;color:var(--lb-fg);\nfont-family:var(--lb-font);\nbox-shadow:0 1rem 2.5rem color-mix(in srgb,var(--color-gray-9) 6%,transparent),\n0 0.125rem 0.5rem color-mix(in srgb,var(--color-gray-9) 4%,transparent)}\n.lb-card-head{display:flex;justify-content:space-between;align-items:baseline;gap:var(--lb-gap)}\n.lb-title{font-size:0.875rem;font-weight:600;line-height:1.25rem;color:var(--lb-fg)}\n.lb-sub{font-size:0.8125rem;line-height:1.125rem;color:var(--lb-muted)}\n.lb-row{display:flex;align-items:center;gap:var(--lb-gap);flex-wrap:wrap}\n.lb-stack{display:grid;gap:var(--lb-gap)}\n.lb-select,.lb-input{font:inherit;font-family:var(--lb-font);font-size:0.8125rem;color:var(--lb-fg);\nbackground-color:var(--lb-field);border:1px solid var(--lb-border);\nborder-radius:var(--lb-radius-sm);corner-shape:squircle;padding:0.4rem 0.55rem;min-height:2.125rem}\n.lb-btn{font:inherit;font-family:var(--lb-font);font-size:0.8125rem;font-weight:600;\ncolor:var(--lb-fg);background-color:var(--lb-field);border:1px solid var(--lb-border);\nborder-radius:var(--lb-radius-sm);corner-shape:squircle;padding:0.4rem 0.85rem;min-height:2.125rem;\ncursor:pointer;transition:background-color .15s,border-color .15s,color .15s}\n.lb-btn:hover:not([disabled]){border-color:var(--color-gray-6)}\n.lb-btn:focus-visible,.lb-select:focus-visible,.lb-input:focus-visible{\noutline:2px solid var(--color-blue-foreground);outline-offset:1px}\n.lb-btn[data-lb-state=loading]{opacity:.55;cursor:progress}\n.lb-btn[data-lb-state=success]{background-color:var(--color-green-background);\nborder-color:var(--color-green-foreground);color:var(--color-green-foreground)}\n.lb-btn[data-lb-state=error],.lb-select[data-lb-state=error]{\nbackground-color:var(--color-red-background);border-color:var(--color-red-foreground);\ncolor:var(--color-red-foreground)}\n.lb-btn[data-lb-state=unavailable],.lb-btn[disabled]{opacity:.5;cursor:not-allowed}\n.lb-msg{font-size:0.8125rem;line-height:1.125rem;color:var(--lb-muted)}\n.lb-msg[data-tone=error]{color:var(--color-red-foreground)}\n.lb-msg[data-tone=ok]{color:var(--color-green-foreground)}\n.lb-chip{display:inline-flex;align-items:center;gap:.25rem;white-space:nowrap;\nfont-size:0.75rem;font-weight:600;line-height:1rem;padding:0.125rem 0.5rem;\nborder-radius:var(--lb-radius-sm);corner-shape:squircle;\nbackground-color:var(--color-gray-2);color:var(--lb-muted)}\n.lb-chip[data-status=WANTED]{background-color:var(--color-blue-background);color:var(--color-blue-foreground)}\n.lb-chip[data-status=WON]{background-color:var(--color-green-background);color:var(--color-green-foreground)}\n.lb-chip[data-status=LOST]{background-color:var(--color-red-background);color:var(--color-red-foreground)}\n.lb-chip[data-status=UNWANTED]{background-color:var(--color-gray-2);color:var(--color-gray-7)}\n.lb-chip[data-taste=liked]{background-color:var(--color-cherry-background);color:var(--color-red-like)}\n.lb-chip[data-taste=disliked]{background-color:var(--color-gray-2);color:var(--color-gray-7)}\n.lb-chips{display:flex;align-items:center;gap:.35rem;flex-wrap:wrap}\n.lb-chip[hidden]{display:none}\n.lb-table{width:100%;border-collapse:collapse;font-family:var(--lb-font);color:var(--lb-fg)}\n.lb-table th,.lb-table td{text-align:left;padding:0.5rem 0.4rem;\nborder-bottom:1px solid var(--lb-border);vertical-align:middle;font-size:0.8125rem}\n.lb-table th{font-size:0.75rem;font-weight:600;color:var(--lb-muted);\ntext-transform:uppercase;letter-spacing:.04em}\n.lb-link{color:var(--color-blue-foreground);text-decoration:none}\n.lb-link:hover{text-decoration:underline}\n/* Quiet text link out of the artifact. Button-height so it shares the row\'s\n baseline; understated so it never competes with the actions beside it. The\n arrow is a bare diagonal stroke \\u2014 an escape-hatch marker, not an icon that\n asks to be read. */\n.lb-link-out{display:inline-flex;align-items:center;gap:.3rem;\nfont-size:0.75rem;line-height:1rem;min-height:2.125rem;\ncolor:var(--lb-fg);text-decoration:none;opacity:.65;transition:opacity .15s}\n.lb-link-out:hover{opacity:1;text-decoration:underline}\n.lb-link-out:focus-visible{outline:2px solid var(--color-blue-foreground);outline-offset:1px;\nborder-radius:var(--lb-radius-sm)}\n.lb-link-out svg{width:.85em;height:.85em;flex-shrink:0}\n/* Pushes whatever follows it to the right edge of an .lb-row, so a trailing\n link sits on the SAME baseline as the row\'s buttons instead of on its own\n line below them. */\n.lb-spacer{flex:1 1 auto}\n.lb-spinner{display:inline-block;width:.7em;height:.7em;border:2px solid var(--lb-border);\nborder-top-color:var(--color-blue-foreground);border-radius:50%;animation:lb-spin .8s linear infinite}\n@keyframes lb-spin{to{transform:rotate(1turn)}}\n@media(prefers-reduced-motion:reduce){.lb-spinner{animation:none}\n.lb-btn{transition-property:none}}\n`,p="lb-styles";var x="0.5.0",c=class extends Error{constructor(t,o={}){super(t);a(this,"code");a(this,"raw");this.name="LbError",this.code=o.code,this.raw=o.raw}},y=null,f=3e4;function C(){let e=globalThis.cowork;return e&&typeof e.callMcpTool=="function"?(r,t)=>e.callMcpTool(r,t):null}function _(e){if(e&&typeof e=="object"&&"content"in e){let r=e.content;if(Array.isArray(r)&&r[0]&&typeof r[0].text=="string")return r[0].text}return null}function E(e){if(!e||typeof e!="object")return e;let r=e;if(r.isError)throw new c(_(e)??"tool call failed",{raw:e});if("structuredContent"in r&&r.structuredContent!=null)return r.structuredContent;let t=_(e);if(t!=null)try{return JSON.parse(t)}catch{return t}return e}function I(e){return e instanceof Error?e.message:String(e)}function v(e){let r=e instanceof c?e.code:void 0;return{message:I(e),unavailable:r==="unavailable",code:r}}function O(e={}){y=e.call??null,f=e.timeoutMs??3e4}function R(){if(typeof document>"u"||!document.head)return null;let e=document.getElementById(p);if(e)return e;let r=document.createElement("style");return r.id=p,r.textContent=S,document.head.appendChild(r),r}async function T(e,r){if(!f||f<=0)return e;let t,o=new Promise((n,i)=>{t=setTimeout(()=>i(new c(`"${r}" timed out after ${f}ms`,{code:"timeout"})),f)});try{return await Promise.race([e,o])}finally{t&&clearTimeout(t)}}async function l(e,r={}){if(y)return E(await T(Promise.resolve(y(e,r)),e));let t=C();if(!t)throw new c("Leadbay bridge unavailable (window.cowork absent)",{code:"unavailable"});return E(await T(Promise.resolve(t(e,r)),e))}var g=class{constructor(){a(this,"subs",new Set)}subscribe(r){return this.subs.add(r),r(this),()=>this.subs.delete(r)}emit(){for(let r of this.subs)r(this)}};function N(e){return Array.isArray(e)?e.map(r=>r&&typeof r=="object"?r:{value:r,label:String(r)}):[]}var b=class extends g{constructor(t={}){super();a(this,"kind");a(this,"value");a(this,"options",[]);a(this,"loading",!1);a(this,"error",null);a(this,"ready",!1);a(this,"cfg");a(this,"depUnsubs",[]);a(this,"seq",0);this.cfg=t,this.kind=t.kind,this.value=t.value??"";for(let o of t.dependsOn??[]){let n=o.value;this.depUnsubs.push(o.subscribe(()=>{o.value!==n&&(n=o.value,this.cfg.load&&this.load())}))}t.load&&(t.autoLoad??!0)&&this.load()}async load(){if(!this.cfg.load)return;let t=++this.seq;this.loading=!0,this.error=null,this.emit();try{let o=await this.cfg.load();if(t!==this.seq)return;this.options=this.cfg.options?this.cfg.options(o):N(o),this.ready=!0;let n=this.value==null?"":String(this.value);this.options.length&&(n===""||!this.options.some(i=>String(i.value)===n))&&(this.value=this.options[0].value)}catch(o){if(t!==this.seq)return;this.options=[],this.error=v(o)}finally{t===this.seq&&(this.loading=!1,this.emit())}}setValue(t){this.value=t;let o=this.validate();this.error=o?{message:o,unavailable:!1}:null,this.emit()}validate(){return this.cfg.validate?this.cfg.validate(this.value):null}get valid(){return this.validate()==null}reset(){this.value=this.cfg.value??"",this.error=null,this.emit()}dispose(){for(let t of this.depUnsubs)t();this.depUnsubs=[]}};function P(e){if(!e||typeof e!="object")return null;let r=e;if(r.error!==!0)return null;let t=typeof r.message=="string"&&r.message?r.message:"tool call failed",o=typeof r.hint=="string"&&r.hint?` \\u2014 ${r.hint}`:"";return`${t}${o}`}var s=class extends g{constructor(t){super();a(this,"loading",!1);a(this,"error",null);a(this,"lastResult",null);a(this,"cfg");this.cfg=t}async run(){if(this.loading)return;for(let n of this.cfg.fields??[]){let i=n.validate();if(i!=null){this.error={message:i,unavailable:!1},this.emit();return}}if(this.cfg.confirm&&typeof globalThis.confirm=="function"&&!globalThis.confirm(this.cfg.confirm))return;this.loading=!0,this.error=null,this.emit();let t;try{let n=typeof this.cfg.args=="function"?this.cfg.args():this.cfg.args??{};t=await l(this.cfg.tool,n)}catch(n){this.error=v(n),this.loading=!1,this.emit(),this.cfg.onError?.(this.error);return}let o=P(t)??this.cfg.checkResult?.(t)??null;if(o!=null){this.error={message:o,unavailable:!1},this.loading=!1,this.emit(),this.cfg.onError?.(this.error);return}return this.lastResult=t,this.loading=!1,this.emit(),this.cfg.onSuccess?.(t),t}reset(){this.error=null,this.lastResult=null,this.emit()}},d=class extends g{constructor(t){super();a(this,"data",null);a(this,"loading",!1);a(this,"refreshing",!1);a(this,"error",null);a(this,"done",!1);a(this,"cfg");a(this,"timer",null);a(this,"seq",0);this.cfg=t,(t.autoLoad??!0)&&this.load()}async load(){this.clearTimer();let t=++this.seq;this.data==null?this.loading=!0:this.refreshing=!0,this.error=null,this.emit();try{let n=await this.cfg.load();if(t!==this.seq)return;this.data=n,this.done=this.cfg.until?this.cfg.until(n):!0,this.cfg.pollEvery&&!this.done&&(this.timer=setTimeout(()=>void this.load(),this.cfg.pollEvery))}catch(n){if(t!==this.seq)return;this.error=v(n)}finally{t===this.seq&&(this.loading=!1,this.refreshing=!1,this.emit())}}refresh(){return this.load()}stop(){this.clearTimer()}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null)}},h=class extends g{constructor(t){super();a(this,"items",[]);a(this,"page",0);a(this,"pageSize");a(this,"total",0);a(this,"loading",!1);a(this,"error",null);a(this,"cfg");a(this,"seq",0);this.cfg=t,this.pageSize=t.pageSize??20,(t.autoLoad??!0)&&this.loadPage(0)}async loadPage(t){let o=++this.seq;this.loading=!0,this.error=null,this.emit();try{let n=await this.cfg.load({page:t,pageSize:this.pageSize});if(o!==this.seq)return;this.items=n.items??[],this.total=n.total??this.items.length,this.page=t}catch(n){if(o!==this.seq)return;this.error=v(n)}finally{o===this.seq&&(this.loading=!1,this.emit())}}next(){return this.loadPage(this.page+1)}prev(){return this.loadPage(Math.max(0,this.page-1))}get hasMore(){return(this.page+1)*this.pageSize<this.total}};function M(e,r){let t=r.error?.unavailable?"unavailable":r.loading?"loading":r.error?"error":"ready";e.setAttribute("data-lb-state",t),r.error?e.setAttribute("data-lb-error",r.error.message):e.removeAttribute("data-lb-error")}function D(e,r){let t=()=>r.setValue(e.value);e.addEventListener("change",t);let o=r.subscribe(()=>{M(e,r),e.disabled=r.loading,e.innerHTML="";for(let n of r.options){let i=document.createElement("option");i.value=String(n.value),i.textContent=n.label,e.appendChild(i)}e.value=r.value==null?"":String(r.value)});return()=>{e.removeEventListener("change",t),o()}}function z(e,r){let t=e.type==="checkbox",o=e.tagName==="SELECT"?"change":"input",n=()=>r.setValue(t?e.checked:e.value);e.addEventListener(o,n);let i=r.subscribe(()=>{if(t)e.checked=!!r.value;else{let u=r.value==null?"":String(r.value);e.value!==u&&(e.value=u)}e.setAttribute("data-lb-state",r.error?"error":"ready"),r.error?e.setAttribute("data-lb-error",r.error.message):e.removeAttribute("data-lb-error")});return()=>{e.removeEventListener(o,n),i()}}function F(e,r){let t=n=>{n.preventDefault(),r.run()};e.addEventListener("click",t);let o=r.subscribe(()=>{let n=r.error?.unavailable?"unavailable":r.loading?"loading":r.error?"error":r.lastResult!=null?"success":"idle";e.setAttribute("data-lb-state",n),"disabled"in e&&(e.disabled=r.loading),r.error?e.setAttribute("data-lb-error",r.error.message):e.removeAttribute("data-lb-error")});return()=>{e.removeEventListener("click",t),o()}}var q=["STILL_CHASING","COULD_NOT_REACH_STILL_TRYING","INTEREST_VALIDATED_OR_MEETING_PLANED","NOT_INTERESTED_LOST"],k=[{value:"",label:"Default ranking"},{value:"SCORE:DESC",label:"Score \\u2193"},{value:"SCORE:ASC",label:"Score \\u2191"},{value:"NAME:ASC",label:"Name A\\u2192Z"},{value:"NAME:DESC",label:"Name Z\\u2192A"},{value:"SIZE:DESC",label:"Size \\u2193"},{value:"SIZE:ASC",label:"Size \\u2191"},{value:"SECTOR:ASC",label:"Sector A\\u2192Z"},{value:"STATUS:ASC",label:"Status A\\u2192Z"},{value:"CONTACT_COUNT:DESC",label:"Contacts \\u2193"},{value:"LAST_PROSPECTING_ACTION_AT:DESC",label:"Last action \\u2193"},{value:"LAST_PROSPECTING_ACTION_AT:ASC",label:"Last action \\u2191"},{value:"EPILOGUE_STATUS_SET_AT:DESC",label:"Outcome set \\u2193"},{value:"LIKED:DESC",label:"Liked first"},{value:"DISLIKED:DESC",label:"Disliked first"}];function U(e){let r=String(e??"").trim().toUpperCase(),t=k.some(o=>o.value===r);return new b({kind:"select",value:t?r:"",load:async()=>k.slice()})}var m=[{value:"WANTED",label:"Wanted"},{value:"WON",label:"Won"},{value:"LOST",label:"Lost"},{value:"UNWANTED",label:"Unwanted"}],H={value:"",label:"\\u2014 Not set \\u2014"};function W(e){let r=String(e??"").trim().toUpperCase(),t=m.some(o=>o.value===r);return new b({kind:"select",value:t?r:"",validate:o=>String(o??"")===""?"Pick a status":null,load:async()=>t?m.slice():[H,...m]})}function $(e){let r=()=>{let t=typeof e.leadIds=="function"?e.leadIds():e.leadIds;return Array.isArray(t)?t:e.leadId?[e.leadId]:[]};return new s({tool:"leadbay_set_lead_status",fields:e.date?[e.status,e.date]:[e.status],confirm:e.confirm,args:()=>({lead_ids:r(),status:e.status.value,...e.date&&e.date.value?{status_date:e.date.value}:{},...e.ask?{_triggered_by:e.ask}:{}}),checkResult:t=>{let o=t?.failed;if(!Array.isArray(o)||o.length===0)return null;let n=r().length,i=o[0]?.message??"write rejected";return o.length===n?`Status not applied: ${i}`:`${o.length} of ${n} leads failed: ${i}`}})}function j(e){return new b({kind:"select",load:()=>l("leadbay_list_campaigns",{_triggered_by:e}),options:r=>(r?.campaigns??[]).map(o=>{let n=o?.campaign??o;return n?.id?{value:n.id,label:n.name??n.ai_generated_name??String(n.id)}:null}).filter(o=>o!=null)})}function V(e){return new s({tool:"leadbay_report_outreach",fields:e.note?[e.note]:[],args:()=>({lead_id:e.leadId,...e.status?{epilogue_status:e.status.value}:{},note:e.note?e.note.value:"",verification:{source:"user_confirmed",ref:e.ref??"logged from artifact"},_triggered_by:e.ask})})}function G(e){return new s({tool:"leadbay_add_note",fields:[e.note],args:()=>({leadId:e.leadId,note:e.note.value})})}function Z(e){return new s({tool:"leadbay_like_lead",args:{lead_id:e}})}function Y(e){return new s({tool:"leadbay_dislike_lead",args:{lead_id:e}})}function B(e,r){return new d({autoLoad:!1,load:()=>l("leadbay_account_history",{leadId:e,_triggered_by:r})})}function K(e,r){return new d({autoLoad:!1,load:()=>l("leadbay_research_lead_by_id",{leadId:e,_triggered_by:r})})}function J(e){let r=null;return new d({...e.autoLoad!==void 0?{autoLoad:e.autoLoad}:{},pollEvery:e.pollEvery??4e3,until:t=>!!t?.all_done,load:async()=>{if(!r){let t=await l("leadbay_enrich_titles",{...e.leadIds?{leadIds:e.leadIds}:{},titles:e.titles,...e.email!==void 0?{email:e.email}:{},...e.phone!==void 0?{phone:e.phone}:{},...e.confirm!==void 0?{confirm:e.confirm}:{},_triggered_by:e.ask});if(r=t?.bulk_id??null,!r)return{...t,all_done:!0,no_job:!0}}return l("leadbay_bulk_enrich_status",{bulk_id:r,_triggered_by:e.ask})}})}function Q(e){let r=()=>typeof e.order=="string"?e.order:String(e.order?.value??"");return new h({pageSize:e.pageSize??20,load:async({page:t,pageSize:o})=>{let n=await l("leadbay_pull_leads",{page:t,count:o,...e.lensId?{lensId:e.lensId}:{},...r()?{order:r()}:{},_triggered_by:e.ask}),i=n.leads??[];return{items:i,total:n.pagination?.total??i.length}}})}function X(e){let r=e.source??"followups",t=()=>typeof e.order=="string"?e.order:String(e.order?.value??"");return new h({pageSize:e.pageSize??20,load:async({page:o,pageSize:n})=>{let u=r==="campaign"?await l("leadbay_campaign_call_sheet",{campaign_id:e.campaignId,page:o,count:n,_triggered_by:e.ask}):await l("leadbay_pull_followups",{page:o,count:n,...e.city?{city:e.city}:{},...t()?{order:t()}:{},_triggered_by:e.ask}),w=u.leads??u.items??[];return{items:w,total:u.total_leads??u.pagination?.total??w.length}}})}function ee(e){return new d({load:()=>l("leadbay_team_activity",{weeks:e.weeks??4,_triggered_by:e.ask})})}var re={VERSION:x,configure:O,styles:R,call:l,field:e=>new b(e),action:e=>new s(e),resource:e=>new d(e),list:e=>new h(e),bindSelect:D,bindValue:z,bindAction:F,campaigns:j,outreach:V,note:G,like:Z,dislike:Y,leadStatus:W,setStatus:$,sortOrder:U,leadHistory:B,leadProfile:K,enrichment:J,callList:X,leadList:Q,teamActivity:ee,EPILOGUE_STATUSES:q,LEAD_STATUSES:m,SORT_ORDERS:k};typeof globalThis<"u"&&(globalThis.LeadbayArtifacts=re);})();';
27290
+ var ARTIFACT_USAGE_GUIDE = '# Leadbay Artifact Kit \u2014 headless domain components\n\nYou are building a single-file HTML **artifact** the user runs inside cowork. This\nkit gives you **headless view-models** that own a control\'s whole data lifecycle \u2014\nload/populate from a Leadbay call, hold value/state, poll, validate, and\nencapsulate the API call + business rules. **You own 100% of markup/layout/style.**\nThe library renders nothing. Inline the runtime once as a `<script>`; it exposes\none global `window.LeadbayArtifacts` (call it `lb`). Vanilla, no React, no build.\n\nPass every tool you use as the artifact\'s `mcp_tools` so the host permits it.\n\n## Two layers\n\n**Primitives** (generic):\n- `lb.field({ load, options, value, validate, dependsOn })` \u2014 a value + optionally\n API-populated options. `.value/.setValue/.options/.loading/.error/.valid/.subscribe`.\n- `lb.action({ tool, args, fields, confirm, onSuccess, onError })` \u2014 a write/submit.\n `.run()/.loading/.error/.lastResult/.subscribe`.\n- `lb.resource({ load, pollEvery?, until?, autoLoad? })` \u2014 one read that may change:\n load-on-click or poll-until-`until`. `.data/.loading/.refreshing/.error/.done/.load()/.refresh()/.stop()/.subscribe`.\n- `lb.list({ load, pageSize })` \u2014 paginated rows. `.items/.page/.total/.loading/.loadPage(n)/.next()/.prev()/.hasMore/.subscribe`.\n\n`.error` is `{ message, unavailable } | null`. `subscribe(cb)` fires immediately\nthen on every change \u2014 render your own DOM from it.\n\n**Domain components** (pre-wired \u2014 bake in the tool name, arg shape, and footguns):\n\n| Call | Returns | For |\n|---|---|---|\n| `lb.campaigns(ask)` | field | a campaign `<select>`, options from `leadbay_list_campaigns` |\n| `lb.outreach({leadId, ask, status?, note?})` | action | log a call \u2192 `report_outreach` (verification + `_triggered_by` baked in) |\n| `lb.note({leadId, note})` | action | add a note \u2192 `add_note` |\n| `lb.like(leadId)` / `lb.dislike(leadId)` | action | taste signal |\n| `lb.leadStatus(current?)` | field | a status `<select>` (Wanted/Won/Lost/Unwanted) |\n| `lb.setStatus({leadId or leadIds, status, date?, ask})` | action | write the org CRM status \u2192 `set_lead_status` |\n| `lb.leadHistory(leadId, ask)` | resource (lazy) | notes + activities + engagement \u2192 `account_history` |\n| `lb.leadProfile(leadId, ask)` | resource (lazy) | full lead profile \u2192 `research_lead_by_id` |\n| `lb.sortOrder(current?)` | field | a sort `<select>` mirroring the app\'s TableSort |\n| `lb.leadList({lensId?, order?, ask})` | list | a sortable Discover batch \u2192 `pull_leads` |\n| `lb.callList({source:\'followups\'\\|\'campaign\', campaignId?, city?, ask})` | list | a cold-call list (Monitor or a campaign) |\n| `lb.enrichment({leadIds, titles, ask, pollEvery?})` | resource (polling) | launch + watch contact enrichment |\n| `lb.teamActivity({weeks, ask})` | resource | manager leaderboard + activity trend \u2192 `leadbay_team_activity` |\n\n`lb.EPILOGUE_STATUSES` = the 4 disposition values\n(`STILL_CHASING`, `COULD_NOT_REACH_STILL_TRYING`, `INTEREST_VALIDATED_OR_MEETING_PLANED`, `NOT_INTERESTED_LOST`).\n`lb.LEAD_STATUSES` = the 4 org CRM statuses as `{value,label}` (`WANTED`, `WON`, `LOST`, `UNWANTED`).\n`lb.SORT_ORDERS` = the sort options as `{value,label}`; values are the backend `FIELD:ASC|DESC` enum.\n\n**Sorting is a SERVER concern.** `lb.leadList` and `lb.callList` take an `order`\n(a `lb.sortOrder()` field or a literal) and send it upstream; the backend sorts\nthe whole lens / Monitor and returns the requested page of that. Never re-sort\nrows in the browser \u2014 you would be reordering one page of a larger set, showing\nleads that do not belong at that position. The empty value means "no order\nparam", i.e. the tab\'s own ranking, which is the right default. Changing the\nsort should reset to page 0. Campaign call sheets cannot sort:\n`leadbay_campaign_call_sheet` has no `order` param, and `lb.callList` drops it\nfor that source rather than sending something the tool would reject.\n\n**Two different systems.** Epilogue = how one outreach attempt went (drives\nfollow-up ranking). Lead status = the commercial outcome, org-wide \u2014 the same\nfield the website\'s status selector writes. A won deal is a LEAD STATUS;\n"she didn\'t pick up" is an EPILOGUE. Setting one never sets the other, so when\nthe user reports both in one breath, fire both actions.\n\n**Binding sugar** (optional; binds a view-model to YOUR native element, no style):\n`lb.bindSelect(selectEl, field)` (populates options + value), `lb.bindValue(inputEl, field)`,\n`lb.bindAction(buttonEl, action)`. They set `data-lb-state`\n(`ready|loading|error|success|unavailable`) + `data-lb-error` on your element as\nstyling hooks. For lists/resources, use `.subscribe()` and render yourself.\n\n`ask` is the user\'s request this artifact serves \u2014 it becomes `_triggered_by`.\n\n## The skin (optional) \u2014 `lb.styles()`\n\nCall it once and you get a small `lb-*` stylesheet, so every artifact you build\nshares one visual language instead of re-inventing padding and colours. It is\n**opt-in**: skip it and you get exactly the unstyled HTML you wrote. It injects\nno markup and never touches your `class` attributes.\n\n```js\nlb.styles(); // idempotent \u2014 safe to call per row\n```\n\n| Class | For |\n|---|---|\n| `lb-card` / `lb-card-head` / `lb-title` / `lb-sub` | a lead card + its header |\n| `lb-row` / `lb-stack` / `lb-spacer` | control row / vertical spacing / flex filler that right-aligns what follows |\n| `lb-link-out` | quiet external link (icon inherits currentColor) \u2014 "Open in Leadbay" |\n| `lb-select` / `lb-input` / `lb-btn` | form controls (state-aware, see below) |\n| `lb-msg` (`data-tone="error\\|ok"`) | inline feedback |\n| `lb-chip` (`data-status="WON\\|LOST"`) | a status pill |\n| `lb-table` | leads table |\n| `lb-spinner` | inline busy indicator |\n\nControls react to the `data-lb-state` the bind helpers already set \u2014 a bound\n`lb-btn` dims while loading, goes green on success, red on error, all with no\nextra CSS from you.\n\nThe palette is the **product design system**, ported from\n`frontend/packages/style/color.css` \u2014 same `--color-gray-1\u20269` ramp, same\nsemantic `--color-{green,red,blue,gold}-{background,foreground}` pairs, same\n`1rem` / `0.625rem` radii and `corner-shape: squircle` as the app\'s components.\nAn artifact therefore looks like Leadbay, not like a generic page.\n\nUse the tokens rather than hardcoded colours \u2014 the same rule the style package\nenforces. Re-theme by overriding them; don\'t fight specificity:\n\n```css\n:root { --lb-surface: var(--color-gray-2); --lb-radius: 0.5rem; }\n```\n\nDark mode works two ways: `data-theme="dark"` on `<html>` (the frontend\'s own\nhook) **and** `prefers-color-scheme`, because an artifact renders inside a host\nwhose theme attribute it cannot set. Never hardcode a light background over the\nskin.\n\nThe product face is `Nikkei Maru`; the stack names it first and falls back to\nthe system UI font. Do **not** add an `@font-face` \u2014 artifacts are inline-only\nand a remote font URL will silently fail.\n\n## What every lead card MUST carry\n\nA card is the artifact form of the `pull_leads` table, and it inherits that\ntable\'s rules. A card with a name and a button is not enough: the rep cannot\ntell *why* this lead is on screen. Four lines, in this order.\n\n```html\n<div class="lb-card">\n <div class="lb-card-head">\n <span class="lb-title"></span> <!-- 1. company -->\n <span class="lb-chips"> <!-- 2. state -->\n <span class="lb-chip" data-taste hidden></span>\n <span class="lb-chip" data-status hidden></span>\n </span>\n </div>\n <div class="lb-sub"></div> <!-- 3. firmographics -->\n <div class="lb-sub" data-why></div> <!-- 4. why it fits -->\n <div class="lb-row"><!-- actions --></div>\n</div>\n```\n\n1. **Company** \u2014 `name`, linked to `website` (prefix `https://` on a bare host).\n Never render the numeric `score`; use the `\u25B0\u2756\u25B1` bar if you want the signal.\n\n Also give every card an **Open in Leadbay** link to the lead\'s panel in the\n product. Put it at the **right-hand end of the card\'s last action row** \u2014\n same row as the buttons, pushed right by an `lb-spacer`, not on a line of\n its own. Style it `lb-link-out`: quiet text plus a plain arrow-up-right,\n never a filled button. It is an escape hatch, not a call to action.\n\n ```html\n <div class="lb-row">\n <button class="lb-btn">Like</button>\n <button class="lb-btn">Set status</button>\n <span class="lb-spacer"></span> <!-- pushes the link right -->\n <a class="lb-link-out" data-k="open" target="_blank" rel="noopener">\n Open in Leadbay\n <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"\n stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">\n <line x1="7" y1="17" x2="17" y2="7"/><polyline points="7 7 17 7 17 17"/>\n </svg>\n </a>\n </div>\n ```\n\n Keep the arrow a bare diagonal stroke \u2014 the text already says where the link\n goes, so the glyph only has to mark "leaves this page". Mark the `<svg>`\n `aria-hidden="true"`: it is decorative, and the link text is the accessible\n name.\n **Pick the view the lead actually lives in** \u2014 the URL is\n `/app/<view>?lead=<uuid>`, and the three views are `discover`, `monitor`,\n `campaign`. Landing a Monitor lead on Discover drops the rep into a list\n that does not contain it:\n\n ```js\n function leadUrl(lead, campaignId) {\n const id = encodeURIComponent(lead.id);\n // A campaign card carries TWO params \u2014 the campaign selects the list, the\n // lead opens the panel inside it. Campaign wins even when in_monitor is\n // also true, because that is the list the rep is looking at.\n if (campaignId) {\n return `https://leadbay.app/app/campaign?campaign=${encodeURIComponent(campaignId)}&lead=${id}`;\n }\n const view = lead.in_monitor ? "monitor" : "discover";\n return `https://leadbay.app/app/${view}?lead=${id}`;\n }\n openEl.href = leadUrl(lead, campaignId);\n ```\n\n `in_monitor` / `in_discover` are booleans on the `pull_followups` payload \u2014\n every follow-up carries `in_monitor: true`, so a call sheet must link to\n `monitor`. `pull_leads` omits both flags entirely; its leads are the Discover\n batch by definition, so `discover` is the default. A campaign card\n (`lb.callList({source:"campaign", campaignId})`) needs `?campaign=<id>&lead=<id>`\n \u2014 the param names are `CAMPAIGN_QUERY_PARAM` and `LEAD_QUERY_PARAM`, and the\n app\'s own `useLeadPanel` preserves whatever params are already set, so the\n two coexist by design. Omitting `campaign=` opens an empty campaign view.\n\n Inline the glyph as SVG rather than an emoji or `\u2197` \u2014 it inherits\n `currentColor` and scales with the text, so it stays legible in both themes.\n `?lead=<uuid>` is the real deep-link (`LEAD_QUERY_PARAM` in the web app, read\n on load; the panel is an overlay, so the view choice only decides what sits\n behind it). This is the ONE place a card may use `lead.id`: as a link target,\n never as visible text.\n2. **State chips** \u2014 taste (`data-taste`) and CRM status (`data-status`) are\n INDEPENDENT axes; render both, hide the empty one. Never collapse to one chip.\n3. **Firmographics** \u2014 sector of activity first, then city, then size, then the\n contact. `sector_id` is a RAW ID (`"5136"`), not a label: resolve it via\n `leadbay_list_sectors` (1346 rows \u2014 fetch once, cache, never inline the lot)\n or omit it. Never print the raw id.\n\n **Always show whether the lead is reachable \u2014 and never merge the person\n with the company\'s switchboard.** These are two separate lines:\n\n ```js\n // WHO \u2014 recommended_contact. Name, and job_title ONLY when present; on list\n // payloads it is usually null, and inventing one is worse than omitting it.\n const rc = lead.recommended_contact;\n const who = rc ? [rc.first_name, rc.last_name].filter(Boolean).join(" ") : null;\n const whoLine = who ? who + (rc.job_title ? " \xB7 " + rc.job_title : "") : "No named contact";\n\n // HOW \u2014 company-level channels. `phone_numbers` and `email` belong to the\n // COMPANY, not to `recommended_contact`. Rendering "Jean \xB7 \u260E 0123\u2026" claims a\n // direct line that does not exist; it is the switchboard.\n const phone = (lead.phone_numbers || [])[0] || null;\n // The API returns the STRING "null" for a missing email \u2014 guard for it or\n // you will print the word "null" as an address.\n const email = lead.email && lead.email !== "null" ? lead.email : null;\n const howLine = [phone && "\u260E " + phone, email && "\u2709 " + email].filter(Boolean)\n .join(" \xB7 ") || "No direct channel \u2014 enrich to reveal";\n ```\n\n ```html\n <div class="lb-sub">Sector \xB7 City \xB7 Size</div>\n <div class="lb-sub">\u{1F464} Jean-Fran\xE7ois Froemer \xB7 G\xE9rant</div> <!-- WHO -->\n <div class="lb-sub">\u{1F3E2} \u260E 01 23 45 67 89</div> <!-- HOW: company -->\n ```\n\n Label the channel line as the **company\'s**, so a rep reading fast cannot\n mistake it for a direct line. A per-contact email or phone exists only after\n enrichment \u2014 `research_lead_by_id` exposes it as `contacts.reachable[]`, and\n `_meta.has_reachable_contact` is the authoritative flag. The list payloads\n carry neither, so a card built from `pull_leads` / `pull_followups` can only\n ever show company channels. Say "enrich to reveal" rather than implying the\n contact is callable.\n\n Two things that look like reachability and are not: a `linkedin_page` alone\n (the rep cannot message a URL without leaving the artifact \u2014 same rule\n `research_lead_by_id` applies), and `contacts_count > 0` (it counts known\n people, not people you can contact; a lead can show 2518 contacts and zero\n channels). `pull_followups` carries `has_phone` as a ready-made boolean;\n `pull_leads` omits it, so derive from `phone_numbers` there.\n4. **Why it fits** \u2014 one sentence, \u226420 words. Walk this chain and stop at the\n first hit:\n\n 1. `short_description`\n 2. `description` (longer; only on `research_lead_by_id` /\n `research_lead_by_name_fuzzy` \u2014 the trim payloads omit it)\n 3. top 2 `tags[].display_name`\n 4. `qualification_summary.best_response_excerpt`, trimmed to one sentence\n 5. `keywords`, first 3, joined with ` \xB7 `\n 6. the resolved sector label \u2014 better than nothing, and if step 3 already\n printed the sector on the firmographics line, skip to step 7\n 7. the literal *"No description yet \u2014 run qualification to generate one"*\n\n Never leave this line blank: a silent gap reads as a rendering bug, whereas\n the fallback tells the rep the data is missing and what fixes it.\n\n **The two list payloads are complementary, so the chain must span both.**\n `pull_leads` returns `short_description` on every lead but no `sector_id`;\n `pull_followups` returns `sector_id` but no `short_description` at all. A\n card fed by one will fall through to a different step than the same card fed\n by the other \u2014 that is expected, not a bug. Never call\n `research_lead_by_id` per row just to fill this line: it is one request per\n lead. Fetch it lazily when the rep expands a card.\n\n**Never show** on a card: `id`, `sector_id`, `location.pos`, `location.country`\n(unless city and state are both missing), `is_hq`, `*_in_progress`,\n`highlighted_fields`, `custom_fields`, `stale_at`, `deal_insights`,\n`need_attention*`, any count that is 0, any value that is the string `"null"`.\n\n**Minimum actions.** A card that only displays is a table row that costs more \u2014\nif you are not wiring an action, render the markdown table instead. Wire at\nleast one write, and prefer the set the rep actually needs:\n\n| Card is for | Wire |\n|---|---|\n| triage a discovery batch | `lb.like` / `lb.dislike` + `lb.setStatus` |\n| working a call list | `lb.outreach` (gated on a note) + `lb.leadHistory` |\n| pipeline review | `lb.setStatus` + `lb.note` |\n\nAlways render the `.error` branch of every view-model \u2014 a control that cannot\nreach the host must say so, not sit silent.\n\n## Recipe: cold-call sheet (one row per lead)\n\n```js\nconst lb = window.LeadbayArtifacts; lb.configure();\nconst ASK = "<the user\'s request>";\n\nconst list = lb.callList({ source: "campaign", campaignId: CID, ask: ASK });\nlist.subscribe((l) => renderRows(l.items, l.loading)); // your render\n\n// per lead row (call when you build a row):\nfunction wireRow(lead, els) {\n const status = lb.field({ value: "STILL_CHASING" }); // static-enum <select>\n const note = lb.field({ validate: (v) => (v && v.trim() ? null : "Add a note") });\n lb.bindValue(els.status, status);\n lb.bindValue(els.note, note);\n lb.bindAction(els.log, lb.outreach({ leadId: lead.id, ask: ASK, status, note }));\n lb.bindAction(els.like, lb.like(lead.id));\n\n const history = lb.leadHistory(lead.id, ASK); // lazy\n history.subscribe((h) => renderHistory(els.history, h));\n els.expand.onclick = () => history.load(); // load on click\n}\n```\n\n## Recipe: lead-status dropdown (Wanted / Won / Lost)\n\nThe org-wide CRM status, as a `<select>` + Apply button. You write the markup;\n`lb.leadStatus` fills the options and holds the value, `lb.setStatus` does the write.\n\n```html\n<div class="lb-card">\n <div class="lb-card-head">\n <span class="lb-title">Acme Corp</span>\n <span class="lb-chips">\n <span id="taste" class="lb-chip" data-taste="liked">Liked</span>\n <span id="crm" class="lb-chip" data-status="WANTED">Wanted</span>\n </span>\n </div>\n <div class="lb-row">\n <select id="st" class="lb-select"></select>\n <button id="go" class="lb-btn">Apply</button>\n <span id="msg" class="lb-msg"></span>\n </div>\n</div>\n```\n\n**Two badges, never one.** Taste (`liked`/`disliked`, from `lb.like`/`lb.dislike`)\nand CRM status (`WANTED`/`WON`/`LOST`/`UNWANTED`, from `lb.setStatus`) are\nindependent axes \u2014 a lead can be liked *and* lost. Collapsing them into a single\nchip destroys information: the rep can no longer see that a lead they liked went\nnowhere. Render `data-taste` and `data-status` as separate chips inside\n`lb-chips`, and hide the one that has no value rather than reusing it.\n\n```js\nlb.styles(); // once per artifact \u2014 see below\n\nconst status = lb.leadStatus(lead.org_lead_status); // seed with the CURRENT value\nconst save = lb.setStatus({ leadId: lead.id, status, ask: ASK });\n\nlb.bindSelect(document.getElementById("st"), status); // populates the 4 options\nlb.bindAction(document.getElementById("go"), save); // click \u2192 write\n\nsave.subscribe((a) => { // render your own feedback\n msg.textContent = a.loading ? "Saving\u2026"\n : a.error ? a.error.message // includes partial failures\n : a.lastResult ? `Set to ${a.lastResult.status}` : "";\n msg.dataset.tone = a.error ? "error" : a.lastResult ? "ok" : "";\n});\n```\n\nLoading / success / error styling comes free: `bindAction` and `bindSelect` set\n`data-lb-state` (`ready|loading|error|success|unavailable`) and the skin already\ntargets those attributes. No extra wiring.\n\nSave-on-change instead of an Apply button \u2014 drop `bindAction` and run it yourself:\n\n```js\ndocument.getElementById("st").addEventListener("change", () => save.run());\n```\n\n**Bulk apply** across checked rows \u2014 pass `leadIds` and a `confirm`, since one\nclick rewrites a field every rep in the org sees:\n\n```js\nconst bulk = lb.setStatus({\n leadIds: () => checkedIds, // \u2190 read at run() time, not at build time\n status, ask: ASK,\n confirm: "Set this status on every selected lead?",\n});\n```\n\n`leadIds` is read when the action runs, so a live selection works \u2014 but pass the\narray itself if your selection is fixed. A partial write (some leads rejected)\nsurfaces as `.error`, never as a green button: `setStatus` checks the `failed[]`\nthe tool returns.\n\nThe backend stamps the status date as "now" on every write, which is what a rep\nclicking a dropdown means. Don\'t add a date picker unless the user asks to\nbackdate \u2014 then pass an optional `date` field holding `YYYY-MM-DD`:\n`lb.setStatus({ leadId, status, date, ask })`.\n\n## Recipe: manager dashboard\n\n```js\nconst team = lb.teamActivity({ weeks: 4, ask: ASK });\nteam.subscribe((t) => {\n if (t.loading) showSpinner();\n if (t.data) {\n renderLeaderboard(t.data.reps); // sorted by total_activities; cols: name, notes, meetings_or_interest, lost\u2026\n renderTrendChart(t.data.trend); // [{date,count}] \u2192 Chart.js (allowed from CDN)\n }\n});\nrefreshBtn.onclick = () => team.refresh();\n```\n\n## Recipe: live enrichment\n\n```js\nconst job = lb.enrichment({ leadIds: [LEAD], titles: ["CEO", "VP Sales"], ask: ASK });\njob.subscribe((j) => {\n const p = j.data && j.data.overall_progress; // {done,total,done_ratio}\n renderBar(p);\n if (j.done) renderContacts(j.data.leads); // enriched contacts\n});\nrefreshBtn.onclick = () => job.refresh();\n```\n\n## Write-call rules\n\nThe domain factories handle these for you. If you hand-roll an action:\n`leadbay_report_outreach` args MUST include `verification:{source:"user_confirmed", ref}`\nAND `_triggered_by`; `leadbay_add_leads_to_campaign` needs `_triggered_by`;\n`add_note`/`like_lead`/`dislike_lead` take only their own args. `epilogue_status` is\none of `lb.EPILOGUE_STATUSES`. Snoozing (pushback) is advanced-gated \u2014 not\ncallable from a default artifact. Org lead status IS on the default surface:\nuse `lb.setStatus`, which owns the arg shape AND the partial-write check \u2014\n`leadbay_set_lead_status` writes each lead separately, so it can resolve 200\nwith a non-empty `failed[]`. Hand-rolling that action will report a green\nbutton over a write that never landed.\n\n## Degradation + live updates\n\nIf the host bridge is absent, a view-model\'s `.error` is set with `.error.unavailable\n=== true` (bind helpers set `data-lb-state="unavailable"`) \u2014 nothing throws. Every\ncall also has a **30s timeout** (configurable via `lb.configure({ timeoutMs })`): a\nhost call that never settles becomes `.error` with `code:"timeout"`, so a control is\nnever stuck loading forever \u2014 always render the `.error` branch so the user can retry.\nAuto-poll (`pollEvery`) depends on the cowork host serving FRESH reads; `.refresh()`\nis the guaranteed manual path \u2014 always wire a Refresh control for polling resources.';
26369
27291
 
26370
27292
  // ../core/dist/tools/artifact-kit.js
26371
27293
  var artifactKit = {
@@ -26600,6 +27522,13 @@ var compositeWriteTools = [
26600
27522
  // to the agent without requiring LEADBAY_MCP_ADVANCED=1.
26601
27523
  likeLead,
26602
27524
  dislikeLead,
27525
+ // Org-wide CRM status (WANTED/WON/LOST/UNWANTED). Granular-shaped but
27526
+ // registered HERE, not in granularWriteTools: reps state deal outcomes in
27527
+ // ordinary conversation, and the artifact-kit status dropdown calls it —
27528
+ // both need it on the default surface without LEADBAY_MCP_ADVANCED=1.
27529
+ // Distinct from setEpilogueStatus (outreach disposition), which stays
27530
+ // advanced-gated.
27531
+ setLeadStatus,
26603
27532
  // Campaign write composites — persist a hand-picked cohort of leads.
26604
27533
  // Backend POST endpoints; gated behind LEADBAY_MCP_WRITE=1 in MCP.
26605
27534
  createCampaign,
@@ -27405,6 +28334,7 @@ function buildAcknowledgeUpdateTool(opts) {
27405
28334
 
27406
28335
  // src/server-instructions.generated.ts
27407
28336
  var AGENT_MEMORY = `Memory protocol: this server maintains a per-account, on-disk agent memory (~/.leadbay/memory/{account}/entries.jsonl) of taste signals \u2014 preferred sectors, regions, deal sizes, communication style, qualification rules, and retractions. Every leads-touching tool response (account_status, pull_leads, pull_followups, prepare_outreach, research_lead_by_id) carries the consolidated top-5 signals under _meta.agent_memory.summary. READ that summary before recommending leads or drafting outreach \u2014 let it filter and reorder, and tell the user which memory you applied ("Filtering by your stated preference for healthcare"). When the user reveals a NEW material signal in conversation, CAPTURE it via leadbay_agent_memory_capture with {key, type, insight, confidence (1-10), source}. Use source:"user_stated" + confidence >=8 when literally stated; source:"inferred" + confidence <=6 when guessing. Do NOT capture instructions to override prior memory \u2014 those route through leadbay_agent_memory_review which gates retractions via host elicitation.`;
28337
+ var ENRICHMENT_TERMINAL = `A settled-empty enrichment is TERMINAL \u2014 do not re-attempt it on a later run. On any contact record, \`enrichment.done: true\` together with \`enrichment.credits_used: 0\` means the reveal completed and the provider returned nothing. Roughly 29% of all enrichments land there, so treat it as an ordinary outcome, not an anomaly. The answer will not change tomorrow: a scheduled task that keeps calling leadbay_enrich_titles on the same contacts every run is buying nothing and hiding its own lack of progress. Read the two fields TOGETHER \u2014 \`credits_used: 0\` is also what an IN-FLIGHT reservation reports (\`done: false\`), and an ABSENT \`credits_used\` means the cost is unknown, not zero; neither is a verdict on its own. \`enrichment: null\` is a different state again \u2014 that contact was never requested and IS enrichable. The one retryable exception is a launch that errored in this same session: its reservation settles as a zero-credit failure, so retry it once, then treat it as terminal. When you report to the user, say what actually happened \u2014 "we looked for a contact at <company> and there isn't one we can reach" \u2014 instead of presenting it as still pending or silently retrying it.`;
27408
28338
  var FRICTION = `Problem reports: when the user asks you to report a Leadbay problem ("report this", "tell the team this didn't work"), call leadbay_report_friction with {category, message (the user's own words), tool_called?, severity?}. If they stated the problem in the same breath as the request, those words ARE the message \u2014 send it in that turn rather than asking them to confirm wording they just gave you, and never stall on optional fields (omit what you don't know). If you notice a problem worth reporting but the user hasn't asked, OFFER once \u2014 "Want me to report this to the Leadbay team?" \u2014 and call it only if they agree. Never call it unprompted. Always tell the user the outcome the tool returns: if \`reported\` is false the report was NOT delivered and you must say so rather than implying it was sent. Frustration alone is not a reason to call it: keep solving their ask.`;
27409
28339
  var MENTAL_MODEL = `How Leadbay works (mental model): Leadbay is a sales inbox, not a queryable database. Each day the user logs back in, a fresh batch of leads is delivered. Batch size is paced by how many leads the user has actually acted on recently \u2014 some workflows produce a big stream of smaller prospects, others a narrow stream of bigger ones. Pulling more won't produce more; the user acting on leads (outreach, skips, saves) does.`;
27410
28340
  var QUOTA_TOPUP = `Quota & top-ups: when a tool returns QUOTA_EXCEEDED / 429, the user has TWO options \u2014 wait for the window reset (daily / weekly / monthly resets shown in leadbay_account_status), OR top up AI credits (top-ups clear the throttle IMMEDIATELY \u2014 they are not subject to the same window). Always offer BOTH options; default-recommending 'wait until tomorrow' is wrong when a 30-second top-up unblocks the same call. If the host exposes leadbay_create_topup_link, OFFER it on every quota wall: 'Want me to generate a top-up link?' \u2014 when the user says yes, call leadbay_create_topup_link and surface the returned Stripe URL as a clickable link for the user to open in their browser. (Sibling leadbay_open_billing_portal is for ongoing subscription changes, not one-shot top-ups.) AFTER the user has topped up: do NOT keep refusing operations. A top-up invalidates every prior 429 and every stale 'you're at your quota' snapshot. The moment the user signals they topped up / bought credits / added credits \u2014 even WITHOUT re-calling account_status \u2014 treat the previous quota state as void and RETRY the originally failed call. (Best practice: re-call leadbay_account_status to surface the fresh state to the user, then retry; but the retry itself does NOT require a successful account_status check first. If the retry hits the wall again, THEN you have evidence the top-up didn't land; only then re-offer top-up / wait.) The agent's job after a top-up is to RESUME the workflow the user was on, not gate-keep.
@@ -27554,6 +28484,9 @@ function buildServerInstructions(exposed) {
27554
28484
  parts.push(TRIGGERED_BY);
27555
28485
  parts.push(MENTAL_MODEL);
27556
28486
  parts.push(QUOTA_TOPUP);
28487
+ if (has("leadbay_enrich_titles")) {
28488
+ parts.push(ENRICHMENT_TERMINAL);
28489
+ }
27557
28490
  parts.push(TRANSIENT_401);
27558
28491
  parts.push(buildScoringParagraph(has));
27559
28492
  parts.push(FIRST_RUN_ROUTING);
@@ -28441,7 +29374,7 @@ function parseWriteEnv(env = process.env) {
28441
29374
  }
28442
29375
 
28443
29376
  // src/http-server.ts
28444
- var VERSION = true ? "0.31.0" : "0.0.0-dev";
29377
+ var VERSION = true ? "0.32.0" : "0.0.0-dev";
28445
29378
  var PORT = Number(process.env.PORT ?? 8080);
28446
29379
  var HOST = process.env.HOST ?? "0.0.0.0";
28447
29380
  var logger = {