@leadbay/mcp 0.33.4 → 0.34.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3150,6 +3150,15 @@ var LeadbayClient = class _LeadbayClient {
3150
3150
  this._region = region ?? _LeadbayClient.regionFromBaseUrl(baseUrl);
3151
3151
  }
3152
3152
  }
3153
+ /**
3154
+ * Whether this client may compose text that promotes a purchase. Default
3155
+ * true. The MCP server sets it false for a host whose directory forbids
3156
+ * promoting upgrades (see BuildServerOptions.includeCommerce); the only
3157
+ * effect is that the QUOTA_EXCEEDED hint drops its two selling sentences.
3158
+ * Set per client, and the hosted server builds one client per session, so
3159
+ * this never leaks across tenants.
3160
+ */
3161
+ commerce = true;
3153
3162
  get baseUrl() {
3154
3163
  return this._baseUrl;
3155
3164
  }
@@ -3469,7 +3478,12 @@ var LeadbayClient = class _LeadbayClient {
3469
3478
  // agent can generate the URL itself instead of asking the user to
3470
3479
  // navigate to a website. Once the user has topped up, the previous
3471
3480
  // 429 is stale — retry the failed call.
3472
- `${hintBase}, OR top up AI credits \u2014 top-ups clear the throttle immediately. Offer the user to generate a Stripe checkout URL via leadbay_create_topup_link, OR direct them to app.leadbay.ai \u2192 Billing. Check leadbay_account_status / leadbay_get_quota to see which resource window (daily/weekly/monthly) was hit. Once the user has topped up, the previous QUOTA_EXCEEDED is stale \u2014 re-call leadbay_account_status to refresh, then RETRY the original operation.`,
3481
+ //
3482
+ // The two selling sentences are dropped when `commerce` is off — this
3483
+ // hint is text the agent reads out, and a host may forbid promoting a
3484
+ // purchase. Nothing is reworded; the rest of the hint is unchanged, and
3485
+ // "the user topped up (elsewhere), so retry" survives either way.
3486
+ `${hintBase}` + (this.commerce ? `, OR top up AI credits \u2014 top-ups clear the throttle immediately. Offer the user to generate a Stripe checkout URL via leadbay_create_topup_link, OR direct them to app.leadbay.ai \u2192 Billing. ` : `. `) + `Check leadbay_account_status / leadbay_get_quota to see which resource window (daily/weekly/monthly) was hit. Once the user has topped up, the previous QUOTA_EXCEEDED is stale \u2014 re-call leadbay_account_status to refresh, then RETRY the original operation.`,
3473
3487
  endpoint,
3474
3488
  retryAfter,
3475
3489
  status
@@ -8451,6 +8465,345 @@ WHEN NOT TO USE: from agent flow \u2014 use leadbay_adjust_audience, which handl
8451
8465
 
8452
8466
  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\`.
8453
8467
  `;
8468
+ var NO_COMMERCE_TOOL_DESCRIPTIONS = {
8469
+ leadbay_account_status: `## WHEN TO USE
8470
+
8471
+ Trigger phrases: "what's my account status", "how much quota do I have", "what lens am I on", "I topped up / I bought credits / I added credits".
8472
+
8473
+ Do NOT use for: "show me leads" \u2192 \`leadbay_pull_leads\`.
8474
+
8475
+ Prefer when: meta question about account, quota, active lens, or top-up recovery
8476
+
8477
+ Examples that SHOULD invoke this tool:
8478
+ - "What's my account status?"
8479
+ - "How much quota do I have left this week?"
8480
+
8481
+ Examples that should NOT invoke this tool (sound similar, route elsewhere):
8482
+ - "Show me today's leads."
8483
+ - "What should I follow up on?"
8484
+
8485
+ ## RENDER (quick)
8486
+
8487
+ Report user + org, AND quota whenever readable \u2014 include quota even on a plain
8488
+ "what account?" ask. NEVER mention the lens unless asked (use
8489
+ \`last_requested_lens_name\`, never the id). SILENT on quota ONLY when
8490
+ \`quota_error\` set, \`unlimited_credits\` true, or quota null. Else render
8491
+ Daily/Weekly/Monthly from \`quota.user\` (fall back to \`quota.org\` if \`user\`
8492
+ absent) as \`$used / $cap (N% used) \xB7 resets\` (or a resource-count table when
8493
+ \`spend[]\` empty). Never say raw "credits".
8494
+
8495
+ ---
8496
+
8497
+ Show the user's account state \u2014 admin rights, language, last-active lens, quota usage across daily/weekly/monthly windows, and whether the org's intelligence is mid-regeneration. **Show quota the way the web app does \u2014 a percentage-used + dollar-spend gauge per window, never raw "credits".** Each window in \`quota.<group>.spend[]\` carries \`current_units\` / \`max_units\` in dollar_cents (% used = the ratio, $ = \`/100\`); the \`quota.<group>.resources[]\` list gives the per-resource usage breakdown (\`count\`, plus \`max_units\` when a per-resource cap exists). **Pre-check the \`LENS_EXTRA_REFILL\` resource here before calling \`leadbay_extend_lens\`** \u2014 look in **\`quota.org.resources[]\`** first (admins), and fall back to **\`quota.user.resources[]\`** when \`quota.org\` is absent (non-admin callers only get the \`user\` group), matching the resource type **case-insensitively** (it may arrive as \`LENS_EXTRA_REFILL\` or \`lens_extra_refill\`). Its full requested batch must fit into the remaining daily quota or the call is rejected outright. Quota windows also hint at the user's consumption pace: heavy recent activity (ai_rescore / web_fetch near their window limits) is a signal that Leadbay will deliver a larger fresh batch next time the user logs back in, since batch size is paced by real consumption.
8498
+
8499
+ **After a user tops up, do NOT keep refusing \u2014 RETRY.** If the user signals they topped up / bought credits / added credits, the previous QUOTA_EXCEEDED is invalidated the moment the Stripe webhook lands. RE-CALL \`leadbay_account_status\` to pick up the new state AND retry the originally failed call. The retry itself does not require a successful account_status check first \u2014 a topped-up user has cleared the throttle whether or not your cached snapshot reflects it yet. **A stale quota snapshot is never a reason to gate-keep a topped-up user.**
8500
+
8501
+ **\`notifications\` block.** The response now includes a top-level \`notifications\` array listing background work the user (or agent) initiated that has since completed (\`bulk_enrich\`, \`bulk_qualify\`, \`import\`). These are signals to revise prior agent outputs the just-finished work might have made stale \u2014 they're NOT a pending-task list for the user. After revising (or confirming nothing is affected), call \`leadbay_acknowledge_notification(notification_id)\`. Full handling protocol below.
8502
+
8503
+ ## GATE \u2014 INSPECT \`_meta.notifications\` ON EVERY RESPONSE
8504
+
8505
+ Some Leadbay tool responses include a \`_meta.notifications\` array listing **background work the user (or you) initiated that has since completed**. The three relevant kinds:
8506
+
8507
+ | Kind | What just finished |
8508
+ |---|---|
8509
+ | \`bulk_enrich\` | A bulk contact-enrichment job (emails / phone numbers attached to leads' contacts). |
8510
+ | \`bulk_qualify\` | A bulk lead-qualification job (web-fetch + AI rescore, producing \`ai_agent_lead_score\` and qualification answers). |
8511
+ | \`import\` | A CSV / CRM file import (rows resolved to leads in the user's pipeline). |
8512
+
8513
+ **Your job when you see an entry: revise prior outputs the just-finished work might have made stale.** This is NOT a pending-task list. It's a "your earlier answer used data that has now changed" signal.
8514
+
8515
+ | Kind | Outputs you've produced that may now be stale \u2014 refresh them |
8516
+ |---|---|
8517
+ | \`bulk_enrich\` | Outreach drafts mentioning these leads' contacts; contact lists; recommended-lead lists citing \`contact_count\`; NEXT STEPS that asked the user to wait for emails / phones. Re-fetch via \`leadbay_get_contacts(leadId)\` for the affected leads. |
8518
+ | \`bulk_qualify\` | Lead rankings / shortlists you produced without \`ai_agent_lead_score\`; "today's leads"; followup maps; prepare-outreach picks. Re-pull via \`leadbay_pull_leads\` / \`leadbay_research_lead_by_id\`. |
8519
+ | \`import\` | "Available leads" claims; pulls from the affected lens that ran before the import landed; followup planning that needed the imported set. Re-pull via \`leadbay_pull_leads\` / \`leadbay_pull_followups\`. |
8520
+
8521
+ **After revising (or after confirming no prior output is affected):** call \`leadbay_acknowledge_notification(notification_id)\` so the entry stops resurfacing on every tool response. Ack-and-move-on is correct even when nothing was stale \u2014 that's how the inbox stays focused on what's actually pending.
8522
+
8523
+ **Do NOT** interpret these entries as "things waiting for the user." The user expects you to handle them silently. They are signals to YOU \u2014 agent \u2014 that prior outputs need a refresh.
8524
+
8525
+ **Poll a job you launched THIS turn; don't poll one from a PREVIOUS turn.** The rule splits by *when* the work was kicked off:
8526
+
8527
+ - **Previous turn / before an MCP restart, and the user has NOT asked about it** \u2014 don't poll for it in the background. Simply continue the conversation; the next time you call any tool, the completed-work entry appears in \`_meta.notifications\` (also on \`leadbay_account_status.notifications\`). This is the ambient push path \u2014 leave it to do its job. **But if the user explicitly asks for status or to "wait for it to finish"** (e.g. a multi-turn flow where a job was launched in a prior turn and this turn says "wait for enrichment to finish, then \u2026"), DO poll its status tool now until done, exactly as for a this-turn job below \u2014 the ambient push only surfaces *completed* work, so it can't answer a live "is it done / wait for it" request while the job is still running.
8528
+ - **This turn (you just launched it)** \u2014 the DEFAULT is: do NOT end your turn on the "launched" ack; stay active and poll the job's status tool in a loop until it reports done, then report the finished result yourself, rather than spinning forever or deferring the result to a later turn. (Two exceptions, detailed below: the user explicitly asked NOT to wait / to run it in the background; or it's a large qualification/import that's async by design \u2014 in those cases hand back the handle instead of looping.) Each status tool has its OWN terminal signal \u2014 poll until:
8529
+ - \`leadbay_bulk_enrich_status\` \u2192 \`all_done:true\` \u2014 OR \`overall_progress.done\` holds steady across several SPACED polls (~15\u201330s apart) over at least ~90s\u20132 min of elapsed time (some contacts are unresolvable, so \`all_done\` can stay false forever). Don't call a plateau from the first few back-to-back reads \u2014 early on \`done\` sits flat while the backend spins up. Once the plateau is real, report what resolved and name what didn't.
8530
+ - \`leadbay_qualify_status\` \u2192 \`still_running\` is empty: every launched lead has finished or failed. (\`in_progress\` also reads \`false\` on the fast path, but it can be \`null\` on the legacy/fallback read \u2014 so treat an empty \`still_running\` as terminal on its own; only require \`in_progress:false\` when that field is actually present.) LIKE imports, large qualification runs are async by design: \`leadbay_bulk_qualify_leads\` defaults to \`wait_for_completion:false\` for \`count > 5\` or chained workflows because blocking can time out, and \`leadbay_qualify_status\` may take minutes/hours. So don't force a long polling loop on a big run \u2014 return the handle/progress and let completion arrive via \`_meta.notifications\` \u2014 UNLESS the user explicitly asked to wait, or it's a small run that finishes quickly. A small \`wait_for_completion:true\` run you can poll to \`still_running\` empty inline.
8531
+ - \`leadbay_import_status\` \u2192 \`status:"complete"\` (or \`"failed"\`). BUT imports are the exception to the stay-active loop: a large \`leadbay_import_leads({wait_for_completion:false})\` is meant to return a handle and resolve over minutes, and the tool does ONE refresh pass per call. Don't block the conversation looping on it \u2014 surface the returned progress/handle and let the completion arrive via \`_meta.notifications\` \u2014 UNLESS the user explicitly asked you to wait for the import, or it's a small import that finishes quickly.
8532
+
8533
+ Enrichment polls to completion in-turn BY DEFAULT \u2014 the exception is when the user explicitly said to start it in the background / not wait ("kick it off, I'll check later"), in which case hand back the bulk_id and let completion arrive via \`_meta.notifications\` (only when a notification id exists; if none was returned, tell the user to ask again / that you'll poll later, since nothing will auto-surface). For qualification and imports, poll inline only for small/quick runs or when the user explicitly asked you to wait; otherwise return the handle and let \`_meta.notifications\` deliver it. Either way, the user should never have to ask "is it done yet?" for work you kicked off in the same turn \u2014 you either report it or hand back a clear in-progress handle.
8534
+
8535
+ Also surfaced as a top-level \`notifications\` array on \`leadbay_account_status\` \u2014 same shape, same handling.
8536
+
8537
+
8538
+ ---
8539
+
8540
+ ## RENDERING \u2014 quota windows (percentage + $, like the frontend)
8541
+
8542
+ Mirror the Leadbay web quota widget: three windows side by side \u2014 **Daily**,
8543
+ **Weekly**, **Monthly** \u2014 each headlined by a **% used** gauge and a **$ spend /
8544
+ $ cap** figure, with a per-resource usage breakdown underneath. **Never speak in
8545
+ raw "credits"** for quota \u2014 the unit is a percentage and a dollar spend.
8546
+
8547
+ **Include the quota whenever it is readable** \u2014 as part of the default account
8548
+ answer, even when the user only asked "what account am I connected to?". The
8549
+ sole reason to omit it is the silence gate below (unreadable quota, or an
8550
+ unlimited account); it is NOT gated on the user explicitly asking for quota.
8551
+
8552
+ **Silence gate (check FIRST).** Render NOTHING about quota when any of these
8553
+ holds \u2014 do not mention quota at all, do not say "unreadable", never tell the user
8554
+ to reconnect:
8555
+ - \`quota\` is null, OR \`quota_error\` is set (a 401/403 backend quirk for plan-less
8556
+ orgs \u2014 the same token read user/org fine), OR
8557
+ - \`organization.unlimited_credits\` is true (internal/unlimited account \u2014 stay
8558
+ silent on quota; never announce "unlimited").
8559
+
8560
+ **Pick the group (for DISPLAY only).** Prefer \`quota.user\` (present for every
8561
+ caller). Use \`quota.org\` only when \`quota.user\` is absent (admins receive both \u2014
8562
+ still show the caller's own \`user\` view). Call the chosen group \`<group>\` below.
8563
+
8564
+ **Exception \u2014 lens-refill pre-checks read the refill row, ORG-first.** This
8565
+ user-preference is for the display gauge ONLY. When you pre-check the
8566
+ \`LENS_EXTRA_REFILL\` resource before \`leadbay_extend_lens\`, look for the row in
8567
+ **\`quota.org.resources[]\` first** (admins get the org group, and the refill
8568
+ quota is org-scoped there); when \`quota.org\` is absent \u2014 non-admin callers only
8569
+ receive the \`user\` group \u2014 fall back to **\`quota.user.resources[]\`**. Match the
8570
+ resource type case-insensitively (\`LENS_EXTRA_REFILL\` / \`lens_extra_refill\`).
8571
+ Skipping the \`user\` fallback for non-admins would make the row invisible even
8572
+ when the quota data exists, so the agent burns the write and hits the very 429
8573
+ this pre-check exists to avoid.
8574
+
8575
+ **Per window (fixed order: daily \u2192 weekly \u2192 monthly).** Match entries by
8576
+ \`window_type\` (\`"daily"\` / \`"weekly"\` / \`"monthly"\`).
8577
+
8578
+ **Headline \u2014 when \`<group>.spend[]\` has an entry for the window (the % gauge):**
8579
+ - \`pct = round(current_units / max_units \xD7 100)\` (both are dollar_cents).
8580
+ - \`$used = (current_units / 100).toFixed(2)\`, \`$cap = (max_units / 100).toFixed(2)\`.
8581
+ - 10-segment bar in a SINGLE inline-code span (backticks give it contrast):
8582
+ \`filled = round(pct / 10)\` clamped 0..10; \`bar = "\u25B0"\xD7filled + "\u25B1"\xD7(10 \u2212 filled)\`.
8583
+ Use ONLY \`\u25B0\`/\`\u25B1\` \u2014 do NOT use the \`\u2756\` glyph (that identity belongs to lead
8584
+ discovery, not quota).
8585
+ - Line: **\`<Window>\`** \`\` \`\u25B0\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\` \`\` \`<pct>% used \xB7 $<used> / $<cap> \xB7 resets <resets_at, relative>\`.
8586
+ e.g. \`**Daily** \` + \`\` \`\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1\` \`\` + \` 7% used \xB7 $0.84 / $12.00 \xB7 resets in ~7 h\`.
8587
+
8588
+ **Fallback \u2014 when \`<group>.spend[]\` is empty** (internal / free orgs have no
8589
+ OVERALL_SPEND quota): no gauge. Render the per-window resource breakdown as a
8590
+ compact table instead \u2014 one row per resource in \`<group>.resources[]\` for that
8591
+ window: the friendly label + \`count\` (append \`/ <max_units>\` only when
8592
+ \`max_units\` is a number). This is the pre-existing behavior, preserved.
8593
+
8594
+ **Resource labels (look up case-insensitively \u2014 lower-case \`resource_type\`
8595
+ first).** Localize to \`user.language\` (FR canonical shown; English in parens):
8596
+ - \`llm_completion\` \u2192 **G\xE9n\xE9rations par IA** (AI generations)
8597
+ - \`ai_rescore\` \u2192 **Leads qualifi\xE9s** (qualified leads)
8598
+ - \`web_fetch\` \u2192 **Informations web** (web insights)
8599
+ - \`contact_enrichment_phone\` \u2192 **T\xE9l\xE9phones enrichis** (phones enriched)
8600
+ - \`contact_enrichment_email\` \u2192 **E-mails enrichis** (emails enriched)
8601
+
8602
+ Skip any resource type not in this map silently \u2014 never dump the raw
8603
+ \`resource_type\` string at the user.
8604
+
8605
+ **\`resets_at\`.** Show as a relative countdown ("resets in ~7 h", "resets in 3
8606
+ days"), computed against now \u2014 mirroring the widget's "r\xE9initialis\xE9 dans X". The
8607
+ raw value is an ISO-8601 timestamp.
8608
+
8609
+ **Top-up (optional, subordinate).** When \`quota.topup\` is present, you MAY add one
8610
+ small line below the windows: \`Top-up: $<remaining_cents/100> of $<total_credit_cents/100> left\`.
8611
+ Keep it secondary \u2014 the three window gauges are the headline. Omit when null.
8612
+
8613
+ **Legend** (once, below): \`\` \`\u25B0\` used \xB7 \`\u25B1\` remaining \`\`.
8614
+
8615
+
8616
+ ---
8617
+
8618
+ WHEN TO USE: at the start of a session to know what the agent can/can't do, after a 429 to explain to the user which resource window was exhausted and when it resets, and after the user signals a top-up so the agent can resume the interrupted workflow.
8619
+
8620
+ WHEN NOT TO USE: as a pre-flight gate before bulk ops \u2014 operations themselves return 429; this tool is for context, not gating. And: a recent quota snapshot showing "exhausted" is NOT a reason to refuse a write call when the user has just topped up \u2014 re-call this tool first, then proceed.
8621
+ `,
8622
+ leadbay_scan_portfolio_signals: `## WHEN TO USE
8623
+
8624
+ Trigger phrases: "which of my leads <did X>", "find leads that <raised / acquired / hired / moved / changed CEO>", "scan my portfolio for <signal>", "identify all the ones that <event> since <date>", "who in Monitor has a <funding / M&A / hiring> signal", "build a campaign from leads with <signal>".
8625
+
8626
+ Do NOT use for: "research one named company" \u2192 \`leadbay_research_lead_by_name_fuzzy\`; "everything about lead <UUID>" \u2192 \`leadbay_research_lead_by_id\`; "qualify my next N leads (they aren't researched yet)" \u2192 \`leadbay_bulk_qualify_leads\`; "just list my follow-ups" \u2192 \`leadbay_pull_followups\`.
8627
+
8628
+ Prefer when: user wants to FILTER a known portfolio by a web-research signal in bulk \u2014 pass \`query\`, optionally \`since\`, \`city\`/\`set_filter\`, or \`leadIds\`; NEVER a country name in \`city\` \u2014 a whole-country ask means NO geo filter
8629
+
8630
+ Examples that SHOULD invoke this tool:
8631
+ - "Which of my leads acquired a company since 2025?"
8632
+ - "Scan my Lyon portfolio for funding signals."
8633
+ - "Find everyone in Monitor who changed CEO and build a campaign."
8634
+
8635
+ Examples that should NOT invoke this tool (sound similar, route elsewhere):
8636
+ - "Look up Acme Corp for me."
8637
+ - "Show me my follow-ups."
8638
+ - "Qualify my next 10 leads."
8639
+
8640
+ ## RENDER (quick)
8641
+
8642
+ Cohort grouped by lead: one block per matched lead (name \xB7 location +
8643
+ its matched signal entries, hot first, source-linked). Open with
8644
+ "N match <query> (M scanned)"; ALWAYS close with an honesty footer \u2014
8645
+ "scanned N \xB7 matched M \xB7 K not yet researched". Never present
8646
+ not_researched leads as "no signal". Full layout below.
8647
+
8648
+ ---
8649
+
8650
+ Scan a known portfolio for a specific web-research signal in one call. This is
8651
+ the bulk, read-only answer to "which of my leads have signal X" \u2014 the question
8652
+ that otherwise forces a per-lead \`leadbay_research_lead_by_id\` loop (one full
8653
+ profile call per lead, slow and quota-heavy).
8654
+
8655
+ **Reads CACHED signals only \u2014 does not trigger new research.** For each lead in
8656
+ scope it reads \`GET /leads/{id}/web_fetch\` (the already-computed web-research
8657
+ signals) and filters the entries against \`query\`. It issues NO web_fetch POST,
8658
+ so it does not consume AI qualification credits and does not re-crawl. Leads
8659
+ that have no cached content (never qualified, or still in progress) are
8660
+ reported in \`not_researched\` \u2014 they are **NOT** silently treated as "no
8661
+ match". Qualify them with \`leadbay_bulk_qualify_leads\`, then re-scan.
8662
+
8663
+ **Scope.** Pass \`leadIds\` for an explicit cohort, or omit it to scan the
8664
+ Monitor portfolio. Narrow the Monitor scope with \`city\` / \`set_filter\` exactly
8665
+ as \`leadbay_pull_followups\` does (store-then-apply server-side filter).
8666
+
8667
+ **One workspace = one country \u2014 a country name is NEVER a location filter.** The admin-area index holds no country nodes, so \`"France"\` matches the *commune of Francs* and \`"United States"\` matches *Statesboro*: the call is silently fenced to one village and every conclusion from it is wrong. City AND country named? Keep the city, drop the country.
8668
+
8669
+ **On \`code: "COUNTRY_LEVEL_LOCATION"\` read \`country_locations[].axis\` and \`[].kind\` \u2014 the recovery differs per case and they are NOT interchangeable, and do NOT retry with another spelling or a nearby city.**
8670
+
8671
+ \`axis: "include"\`:
8672
+
8673
+ - \`home_country\`, or "nationwide" / "everywhere" \u2192 drop that ONE value. Omit the geo argument (\`city\` / \`locations\` / \`location_ids\`) only if nothing else was on it \u2014 then the result covers the whole workspace. If other values remain, keep them and describe the result as those places.
8674
+ - \`foreign_country\` ("leads in France" on a US workspace) \u2192 **unsupported, not unfiltered.** Do NOT re-run without the argument: whole-workspace results are US leads and answer nothing about France. Say the workspace holds only its own country's companies.
8675
+ - \`supranational\` ("EU", "EMEA") \u2192 name what the workspace covers, then offer the whole-workspace view as an explicit choice rather than assuming it.
8676
+ - \`country_indeterminate\` (custom/staging backend) \u2192 its country is unknown, so claim nothing about what it holds.
8677
+
8678
+ \`axis: "exclude"\` reverses all of that \u2014 **never "omit the argument"**, which returns the very companies the user asked to remove. Excluding this workspace's own country would empty it; excluding any other country is a harmless no-op. Either way drop the value and ask what to carve out instead.
8679
+
8680
+ On a lens-WRITING tool (\`new_lens\`, \`adjust_audience\`, \`update_lens_filter\`) write NOTHING, with no re-call in any form: when the country was the only scope; for ANY \`foreign_country\` or \`supranational\` INCLUDE however much else came with it \u2014 the sectors and sizes were QUALIFYING that territory, not a second request, so writing them alone saves a real audience for a territory nobody asked about; and for ANY non-\`foreign_country\` \`exclude\` hit, likewise \u2014 dropping it and writing the rest inverts the ask.
8681
+
8682
+ **Never infer WHICH country this workspace serves from the user's wording** \u2014 "the whole US" does not make it one. Read \`_meta.region\` on any tool result \u2014 it outranks any recalled memory; on \`custom\`, claim nothing.
8683
+
8684
+ Place names never go in \`keywords\`, \`sectors\` or \`refine_prompt\` \u2014 text matches, not geo filters.
8685
+ The
8686
+ scan is bounded by \`max_leads\` (default 200, hard cap 300); when the portfolio
8687
+ is larger, \`truncated_at\` is set and coverage is partial \u2014 say so.
8688
+
8689
+ **Query.** \`query\` is matched case- and accent-insensitively against each
8690
+ signal entry's description, source, and section label. Comma- or
8691
+ space-separated terms are OR'd ("M&A, acquisition, rachet\xE9" matches any). Use
8692
+ \`since\` (ISO date) to keep only entries dated on/after it \u2014 entries with no
8693
+ date are kept (a missing date is not evidence the event is old).
8694
+
8695
+ **Result is campaign-ready.** \`matched[]\` carries \`lead_id\`, \`name\`,
8696
+ \`location\`, and the matching \`matched_signals[]\` (section + hot + source +
8697
+ date + description). Feed the matched \`lead_id\`s straight into
8698
+ \`leadbay_add_leads_to_campaign\` / \`leadbay_create_campaign\`.
8699
+
8700
+ **SIGNAL HONESTY \u2014 never infer signals from freshness.** \`stale_at\`,
8701
+ \`web_fetch_in_progress\`, \`fetch_at\` are freshness markers, not signal
8702
+ indicators \u2014 signal presence is read ONLY from the actual \`signals[]\` /
8703
+ \`web_fetch.content\` entries. For "which of my leads have signal X" across a
8704
+ portfolio, call **\`leadbay_scan_portfolio_signals\`** (bulk-reads cached
8705
+ signals); don't loop \`leadbay_research_lead_by_id\` per lead or guess from
8706
+ freshness. A lead with no cached content is \`not_researched\`, not "no match";
8707
+ never report a signal verdict for a lead you never read.
8708
+
8709
+
8710
+ WHEN TO USE: when the user wants to filter a known
8711
+ portfolio by a web-research signal across many leads at once \u2014 discovering a
8712
+ cohort to act on, not inspecting a single lead.
8713
+
8714
+ WHEN NOT TO USE: for a single named company
8715
+ (leadbay_research_lead_by_name_fuzzy) or one lead by UUID
8716
+ (leadbay_research_lead_by_id); to qualify leads that have no signals yet
8717
+ (leadbay_bulk_qualify_leads); or to just list follow-ups with no signal filter
8718
+ (leadbay_pull_followups).
8719
+
8720
+ ---
8721
+
8722
+ ## RENDERING \u2014 bulk signal-scan results
8723
+
8724
+ The output is a cohort, grouped by lead. Lead with the matches, end with an
8725
+ honesty footer \u2014 never hide what wasn't scanned.
8726
+
8727
+ ### Matched leads
8728
+
8729
+ Open with a one-line headline: \`**N leads match "<query>"** (M scanned).\`
8730
+
8731
+ Then one block per \`matched[]\` lead, ordered with \`hot\` matches first. Emit
8732
+ each as a host-parseable per-lead block so the chat host's place-card
8733
+ auto-detector can render it (per the repo "feed the address auto-detector"
8734
+ convention):
8735
+
8736
+ \`\`\`
8737
+ ### <name> \xB7 <location>
8738
+
8739
+ <for each matched_signal, one bullet>
8740
+ - **<section_emoji> <section_label>** \u2014 <description> <\u{1F525} if hot> ([source](<source>), <date>)
8741
+ \`\`\`
8742
+
8743
+ - **Bold** the description of \`hot: true\` entries; leave cold entries plain.
8744
+ - Render \`source\` as a markdown link \`([source](url), date)\`; omit the date
8745
+ when null, omit the link when \`source\` is empty.
8746
+ - Cap to the 3 strongest signals per lead (hot first, then by date desc); if a
8747
+ lead has more, end its block with \`_+K more signals_\`.
8748
+ - When \`name\` is null (the scan was scoped by \`leadIds\` and the read failed to
8749
+ carry firmographics), fall back to \`### Lead <lead_id>\` \u2014 but prefer to enrich
8750
+ the name via the matched lead's own data when available.
8751
+
8752
+ ### Honesty footer (ALWAYS print)
8753
+
8754
+ A single italic line summarising coverage:
8755
+
8756
+ \`_Scanned N \xB7 matched M \xB7 K had no cached signals (not yet researched)._\`
8757
+
8758
+ - When \`not_researched\` is non-empty, this is load-bearing: state plainly that
8759
+ those K leads were NOT searched and were NOT counted as "no match". Offer to
8760
+ qualify them and re-scan (see NEXT STEPS).
8761
+ - When \`truncated_at\` is set, add: \`_Coverage partial \u2014 only the first <truncated_at>
8762
+ leads were scanned; narrow the scope or raise max_leads._\`
8763
+
8764
+ **Hide:** raw \`lead_id\` in prose (use it only for the campaign call), \`_meta\`,
8765
+ empty arrays, any freshness field. NEVER present \`not_researched\` leads as
8766
+ "no signal found".
8767
+
8768
+
8769
+ ---
8770
+
8771
+ ## NEXT STEPS \u2014 after the signal scan
8772
+
8773
+ **ALWAYS render NEXT STEPS via your host's next-step widget.** Use whichever is in your tool set \u2014 the NAME and SCHEMA differ: **\`ask_user_input_v0\`** (Claude chat / ChatGPT) takes plain-string options with \`type:"single_select"\`; **\`AskUserQuestion\`** (Claude cowork / Claude Code) takes object options \`{label, description}\` plus a required short \`header\` (\u226412 chars) and \`multiSelect\`, NO \`type\` field, and never add an "Other" option (the host adds it). Match the schema to the tool you actually have \u2014 the wrong schema fails silently and you fall back to prose. Prose bullets are the fallback ONLY when NEITHER widget exists. Any turn that would end with a choice must be the widget \u2014 the widget IS the question.
8774
+
8775
+ **If the tool result carries a \`next_steps\` object, that is the source of truth \u2014 use it directly.** Each option has a short \`.label\` (\u22645 words) and a full \`.description\`. Map \`next_steps.options[]\` into your host widget VERBATIM and in order: for \`AskUserQuestion\` (cowork / Claude Code) pass each as \`{label, description}\`; for \`ask_user_input_v0\` (Claude chat / ChatGPT, string options only) pass each option's \`.description\` as the string (it's the full sentence). Do NOT reword, reorder, drop, or prose-ify them \u2014 they're built deterministically by the server so the offer (incl. the artifact option at position 0) fires every time. Fall back to the table below only when there is NO \`next_steps\` field.
8776
+
8777
+ **One exception \u2014 skip the widget** when the user's original message contained a complete sequential instruction chain ("show me X and then do Y") AND all stated steps have been completed. In that case, end with STOP directly \u2014 the user stated their full plan and does not need a "what next?" prompt.
8778
+ - Skip example: "Show me today's leads and then research the top one for me." \u2192 after research completes, emit STOP without the widget.
8779
+ - Do NOT skip for: plain requests ("show me today's leads", "run my check-in"), recurring-language requests ("I do this every day"), or requests where only one action was stated.
8780
+
8781
+ Pick 2\u20134 rows from the (Observation, Suggest, Calls) table below most relevant to the response, then call your host's widget with ITS schema (per the schema rules above \u2014 wrong schema fails silently):
8782
+ - \`ask_user_input_v0\`: \`{questions:[{question,type:"single_select",options:["<Suggest 1>","<Suggest 2>"]}]}\`
8783
+ - \`AskUserQuestion\`: \`{questions:[{question,header:"Next step",multiSelect:false,options:[{label:"<\u22645 words>",description:"<Suggest 1>"}]}]}\`
8784
+
8785
+ User picks \u2192 call the matching \`Calls\` tool. Constraints: 2\u20134 mutually-exclusive options, AskUserQuestion labels \u22645 words (full text in \`description\`), max 3 questions. Table stays internal; never recite it.
8786
+
8787
+ ---
8788
+
8789
+
8790
+
8791
+ The scan exists to BUILD A COHORT, not just to list. The default next move is
8792
+ almost always "turn the matched leads into a campaign."
8793
+
8794
+ | Observation | Suggest | Calls |
8795
+ |---------------------------------------------------|--------------------------------------------------------------|----------------------------------------------------------------------------------------|
8796
+ | \`matched\` non-empty (top of menu) | "Build a campaign from the N matched leads" | leadbay_create_campaign / leadbay_add_leads_to_campaign(matched lead_ids) |
8797
+ | \`not_researched\` non-empty | "K leads aren't researched yet \u2014 qualify them, then re-scan" | leadbay_bulk_qualify_leads(not_researched lead_ids) \u2192 re-run leadbay_scan_portfolio_signals |
8798
+ | Zero matches but leads were researched | "Widen the query (synonyms) or relax \`since\`" | leadbay_scan_portfolio_signals(query: "<broader terms>", since: omit-or-earlier) |
8799
+ | \`truncated_at\` set | "Scan only covered N \u2014 narrow scope or raise the cap" | leadbay_scan_portfolio_signals({city / set_filter}) or raise \`max_leads\` |
8800
+ | One standout matched lead | "Open that lead's full brief" | leadbay_research_lead_by_id(leadId) |
8801
+
8802
+ NEVER report leads in \`not_researched\` as if they had no matching signal \u2014 they
8803
+ were never read. Distinguish "no signal X found" (researched, no match) from
8804
+ "not yet researched" (no data to search) every time.
8805
+ `
8806
+ };
8454
8807
 
8455
8808
  // ../core/dist/tools/login.js
8456
8809
  var login = {
@@ -23745,9 +24098,8 @@ function buildAcknowledgeUpdateTool(opts) {
23745
24098
  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.`;
23746
24099
  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.`;
23747
24100
  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.`;
23748
- 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.
23749
-
23750
- Show the refreshed quota AFTER a paid action has actually COMPLETED: when leadbay_bulk_enrich_status reports the job done \u2014 all_done, OR a plateau you've decided is terminal (overall_progress.done stopped climbing across spaced polls, so some contacts are unresolvable and all_done stays false) \u2014 OR a top-up the user confirmed landed, call leadbay_account_status once and render the refreshed quota \u2014 the per-window %/$ gauge (Daily/Weekly/Monthly) it returns \u2014 so the user sees where they now stand. Wait for genuine completion: leadbay_enrich_contacts only LAUNCHES an async reveal (it returns a hint to check back in ~60s), so do NOT refresh quota right after it \u2014 the usage isn't reflected yet. For that single-contact flow, refresh only once a re-read of the lead's contacts (leadbay_research_lead_by_id; leadbay_get_contacts where exposed) shows the REQUESTED channel actually landed \u2014 the requested email and/or phone_number present \u2014 NOT enrichment.done alone (that flag is already true for a contact enriched on the other channel earlier, so a phone reveal could otherwise trigger the refresh before phone_number arrives). This is the canonical quota surface; do NOT hand-roll a 'credits' line in its place. Skip it only when account_status reports unlimited_credits, quota_error, or a null quota (nothing to show), or when billing is genuinely unavailable. Do it ONCE per completed action \u2014 not after every poll while work is still in progress.`;
24101
+ var QUOTA_REFRESH = `Show the refreshed quota AFTER a paid action has actually COMPLETED: when leadbay_bulk_enrich_status reports the job done \u2014 all_done, OR a plateau you've decided is terminal (overall_progress.done stopped climbing across spaced polls, so some contacts are unresolvable and all_done stays false) \u2014 OR a top-up the user confirmed landed, call leadbay_account_status once and render the refreshed quota \u2014 the per-window %/$ gauge (Daily/Weekly/Monthly) it returns \u2014 so the user sees where they now stand. Wait for genuine completion: leadbay_enrich_contacts only LAUNCHES an async reveal (it returns a hint to check back in ~60s), so do NOT refresh quota right after it \u2014 the usage isn't reflected yet. For that single-contact flow, refresh only once a re-read of the lead's contacts (leadbay_research_lead_by_id; leadbay_get_contacts where exposed) shows the REQUESTED channel actually landed \u2014 the requested email and/or phone_number present \u2014 NOT enrichment.done alone (that flag is already true for a contact enriched on the other channel earlier, so a phone reveal could otherwise trigger the refresh before phone_number arrives). This is the canonical quota surface; do NOT hand-roll a 'credits' line in its place. Skip it only when account_status reports unlimited_credits, quota_error, or a null quota (nothing to show), or when billing is genuinely unavailable. Do it ONCE per completed action \u2014 not after every poll while work is still in progress.`;
24102
+ 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.`;
23751
24103
  var TRANSIENT_401 = `Transient 401s (DO NOT narrate as an auth problem): Leadbay bearer tokens do NOT expire on a timer, and the client already auto-retried this call once before surfacing it. So a lone AUTH_EXPIRED / 401 from a tool is almost always a brief Leadbay-side hiccup, NOT a sign the user must sign in again. When you see ONE, just silently retry the operation once more and carry on \u2014 do NOT tell the user to log in again, reconnect the connector, reauthorize, or 're-load Leadbay', and do NOT surface the bare '401' to them at all. Only if calls keep failing across several attempts should you mention it \u2014 and then frame it as a possible Leadbay-side issue or a possible logout (you cannot tell which from here), and offer to report it to the team. Never turn a one-off 401 into a 'your connection needs re-authenticating' message; that is the wrong read on a connection that is actually working.`;
23752
24104
  var TRIGGERED_BY = `Trigger provenance (MANDATORY): every Leadbay composite-tool call MUST carry a non-empty \`_triggered_by\` argument \u2014 the verbatim slice of the user's most recent message that this call is acting upon. Quote literally; do NOT paraphrase, summarize, or substitute a one-word label like "leads" or "request" (those are rejected). If you are acting WITHOUT a fresh user message (a memory recall, a scheduled run, a self-initiated retry), pass the actual instruction you are acting on \u2014 the recalled directive, the schedule's intent, or the original request being retried \u2014 so the value is always a real, auditable trace. Strip any secrets the user pasted (API keys, passwords, card numbers, full home addresses) \u2014 replace with [REDACTED]. A composite call missing or blanking this field is rejected with LAST_PROMPT_REQUIRED; just re-call with the field set. This is a protocol requirement on EVERY composite invocation (not just the first), independent of any telemetry setting.`;
23753
24105
  var VERIFICATION = `After every email, call, message, or meeting with a lead's contact, you MUST call leadbay_report_outreach with verification={source, ref} (gmail_message_id from the Gmail send, calendar_event_id from a booking, or user_confirmed='<the user's literal confirmation>'). Skipping or fabricating verification poisons the human team's pipeline.`;
@@ -23891,7 +24243,10 @@ function buildServerInstructions(exposed) {
23891
24243
  }
23892
24244
  parts.push(TRIGGERED_BY);
23893
24245
  parts.push(MENTAL_MODEL);
23894
- parts.push(QUOTA_TOPUP);
24246
+ if (has("leadbay_create_topup_link")) {
24247
+ parts.push(QUOTA_TOPUP);
24248
+ }
24249
+ parts.push(QUOTA_REFRESH);
23895
24250
  if (has("leadbay_enrich_titles")) {
23896
24251
  parts.push(ENRICHMENT_TERMINAL);
23897
24252
  }
@@ -23911,6 +24266,10 @@ function buildServerInstructions(exposed) {
23911
24266
  parts.push(BUILTIN_WIDGETS_PARAGRAPH);
23912
24267
  return parts.join("\n\n");
23913
24268
  }
24269
+ var COMMERCE_TOOL_NAMES = /* @__PURE__ */ new Set([
24270
+ "leadbay_create_topup_link",
24271
+ "leadbay_open_billing_portal"
24272
+ ]);
23914
24273
  function formatErrorForLLM(err) {
23915
24274
  if (err && typeof err === "object" && err.error === true) {
23916
24275
  const parts = [`${err.message}.`, err.hint];
@@ -23960,6 +24319,40 @@ function extractTriggeredBy(args) {
23960
24319
  const trimmed = raw.length > 500 ? `${raw.slice(0, 500)}\u2026` : raw;
23961
24320
  return { triggered_by: trimmed, cleaned };
23962
24321
  }
24322
+ function findShapeMismatch(tool, args) {
24323
+ const schema = tool.inputSchema;
24324
+ if (!schema || schema.type !== "object") return void 0;
24325
+ const props = schema.properties;
24326
+ if (!props || typeof props !== "object") return void 0;
24327
+ for (const [key, spec] of Object.entries(props)) {
24328
+ if (key === TRIGGERED_BY_FIELD || !spec || typeof spec !== "object") continue;
24329
+ const declared = spec.type;
24330
+ if (declared !== "array" && declared !== "object") continue;
24331
+ const value = args[key];
24332
+ if (value === void 0 || value === null) continue;
24333
+ const isArray = Array.isArray(value);
24334
+ const got = isArray ? "array" : typeof value;
24335
+ if (declared === "array" && !isArray) {
24336
+ const items = spec.items;
24337
+ const of = typeof items?.type === "string" ? ` of ${items.type}s` : "";
24338
+ return {
24339
+ error: true,
24340
+ code: "BAD_INPUT",
24341
+ message: `${key} must be a JSON array (got ${got})`,
24342
+ hint: `Re-call with ${key} as a JSON array${of}, e.g. ${key}: ["\u2026"]. Do not JSON-stringify the array.`
24343
+ };
24344
+ }
24345
+ if (declared === "object" && (typeof value !== "object" || isArray)) {
24346
+ return {
24347
+ error: true,
24348
+ code: "BAD_INPUT",
24349
+ message: `${key} must be a JSON object (got ${got})`,
24350
+ hint: `Re-call with ${key} as a JSON object, e.g. ${key}: {\u2026}.`
24351
+ };
24352
+ }
24353
+ }
24354
+ return void 0;
24355
+ }
23963
24356
  function toolsListPayload(tools2) {
23964
24357
  return tools2.map((t) => {
23965
24358
  const out = {
@@ -23998,16 +24391,19 @@ function buildServer(client, opts = {}) {
23998
24391
  if (opts.extraTools) {
23999
24392
  exposedTools.push(...opts.extraTools);
24000
24393
  }
24394
+ const includeCommerce = opts.includeCommerce !== false;
24395
+ client.commerce = includeCommerce;
24001
24396
  const toolByName = /* @__PURE__ */ new Map();
24002
24397
  for (const t of exposedTools) {
24003
- if (!toolByName.has(t.name) && t.name !== "leadbay_login") {
24004
- toolByName.set(
24005
- t.name,
24006
- withTriggeredByMeta(t, {
24007
- mandatory: COMPOSITE_FILE_TOOL_NAMES.has(t.name)
24008
- })
24009
- );
24010
- }
24398
+ if (toolByName.has(t.name) || t.name === "leadbay_login") continue;
24399
+ if (!includeCommerce && COMMERCE_TOOL_NAMES.has(t.name)) continue;
24400
+ const noCommerce = includeCommerce ? void 0 : NO_COMMERCE_TOOL_DESCRIPTIONS[t.name];
24401
+ toolByName.set(
24402
+ t.name,
24403
+ withTriggeredByMeta(noCommerce ? { ...t, description: noCommerce } : t, {
24404
+ mandatory: COMPOSITE_FILE_TOOL_NAMES.has(t.name)
24405
+ })
24406
+ );
24011
24407
  }
24012
24408
  const exposedNames = new Set(toolByName.keys());
24013
24409
  const server = new Server(
@@ -24337,7 +24733,8 @@ ${url}
24337
24733
  isError: true
24338
24734
  };
24339
24735
  }
24340
- const result = await runWithRequestSignal(extra.signal, () => tool.execute(client, args, {
24736
+ const shapeError = findShapeMismatch(tool, args);
24737
+ const result = shapeError ?? await runWithRequestSignal(extra.signal, () => tool.execute(client, args, {
24341
24738
  logger: opts.logger,
24342
24739
  bulkTracker: opts.bulkTracker,
24343
24740
  notificationsInbox: opts.notificationsInbox,
@@ -24768,7 +25165,7 @@ function parseWriteEnv(env = process.env) {
24768
25165
  }
24769
25166
 
24770
25167
  // src/http-server.ts
24771
- var VERSION = true ? "0.33.4" : "0.0.0-dev";
25168
+ var VERSION = true ? "0.34.1" : "0.0.0-dev";
24772
25169
  var PORT = Number(process.env.PORT ?? 8080);
24773
25170
  var HOST = process.env.HOST ?? "0.0.0.0";
24774
25171
  var logger = {
@@ -24888,19 +25285,22 @@ function extractBearer(authHeader) {
24888
25285
  const m = /^Bearer\s+(.+)$/i.exec(authHeader);
24889
25286
  return m ? m[1].trim() : void 0;
24890
25287
  }
24891
- function buildServerFromClient(client, requestTelemetry) {
25288
+ var COMMERCE_FREE_PATHS = /* @__PURE__ */ new Set(["/chatgpt/mcp"]);
25289
+ function buildServerFromClient(client, requestTelemetry, resourcePath) {
24892
25290
  const includeWrite = parseWriteEnv();
24893
25291
  const includeAdvanced = process.env.LEADBAY_MCP_ADVANCED === "1";
24894
25292
  return buildServer(client, {
24895
25293
  version: VERSION,
24896
25294
  includeWrite,
24897
25295
  includeAdvanced,
25296
+ includeCommerce: !COMMERCE_FREE_PATHS.has(resourcePath),
24898
25297
  logger,
24899
25298
  telemetry: requestTelemetry
24900
25299
  });
24901
25300
  }
25301
+ var OPENAI_APPS_CHALLENGE = process.env.OPENAI_APPS_CHALLENGE ?? "vsJ51IZ_3AqM10YZxXQFmB29IGIMDOZGbpbEgRIT4r4";
24902
25302
  var PRM_PREFIX = "/.well-known/oauth-protected-resource";
24903
- var RESOURCE_PATHS = ["/mcp", "/sse", "/fr/mcp", "/fr/sse"];
25303
+ var RESOURCE_PATHS = ["/mcp", "/sse", "/fr/mcp", "/fr/sse", "/chatgpt/mcp"];
24904
25304
  function requestOrigin(c) {
24905
25305
  const url = new URL(c.req.url);
24906
25306
  const proto = c.req.header("x-forwarded-proto") ?? url.protocol.replace(/:$/, "");
@@ -24946,6 +25346,10 @@ function sendChallenge(c, resourcePath, authState) {
24946
25346
  }
24947
25347
  var app = new Hono();
24948
25348
  app.get("/healthz", (c) => c.json({ ok: true, version: VERSION }));
25349
+ app.get(
25350
+ "/.well-known/openai-apps-challenge",
25351
+ (c) => c.text(OPENAI_APPS_CHALLENGE, 200, { "Cache-Control": "no-store" })
25352
+ );
24949
25353
  app.get(PRM_PREFIX, (c) => servePrm(c, "/mcp"));
24950
25354
  app.get(`${PRM_PREFIX}/*`, (c) => {
24951
25355
  const suffix = c.req.path.slice(PRM_PREFIX.length);
@@ -24964,6 +25368,7 @@ app.options("*", (c) => {
24964
25368
  var MCP_BODY_LIMIT = bodyLimit({ maxSize: 1 * 1024 * 1024 });
24965
25369
  app.use("/mcp", MCP_BODY_LIMIT);
24966
25370
  app.use("/fr/mcp", MCP_BODY_LIMIT);
25371
+ app.use("/chatgpt/mcp", MCP_BODY_LIMIT);
24967
25372
  app.use("/messages", MCP_BODY_LIMIT);
24968
25373
  async function handleStreamable(c, resourcePath) {
24969
25374
  const foreign = rejectForeignOrigin(c);
@@ -24976,7 +25381,8 @@ async function handleStreamable(c, resourcePath) {
24976
25381
  }
24977
25382
  const server = buildServerFromClient(
24978
25383
  resolved.client,
24979
- await telemetryHandleForRequest(resolved.client)
25384
+ await telemetryHandleForRequest(resolved.client),
25385
+ resourcePath
24980
25386
  );
24981
25387
  const transport = new StreamableHTTPServerTransport({
24982
25388
  sessionIdGenerator: void 0,
@@ -25016,6 +25422,7 @@ async function handleStreamable(c, resourcePath) {
25016
25422
  }
25017
25423
  app.all("/mcp", (c) => handleStreamable(c, "/mcp"));
25018
25424
  app.all("/fr/mcp", (c) => handleStreamable(c, "/fr/mcp"));
25425
+ app.all("/chatgpt/mcp", (c) => handleStreamable(c, "/chatgpt/mcp"));
25019
25426
  async function handleSse(c, resourcePath) {
25020
25427
  const foreign = rejectForeignOrigin(c);
25021
25428
  if (foreign) return foreign;
@@ -25063,7 +25470,8 @@ async function handleSse(c, resourcePath) {
25063
25470
  sessionOptedOut: session.suppressed,
25064
25471
  fallbackEnabled: !session.suppressed
25065
25472
  })
25066
- )
25473
+ ),
25474
+ resourcePath
25067
25475
  );
25068
25476
  await server.connect(transport);
25069
25477
  const sessionId = transport.sessionId;