@leadbay/mcp 0.18.2 → 0.19.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.
@@ -33,10 +33,10 @@ import {
33
33
  var leadbay_daily_check_in = `
34
34
  ## MEMORY
35
35
 
36
- Before responding, glance at any \`_meta.agent_memory.summary\` returned by tool calls earlier in this session and reflect its top signals in your reasoning ("Filtering by your stated preference for healthcare"). After any material new taste signal from the user this conversation (sector, region, deal size, communication style, qualification rule, explicit retraction), call \`leadbay_agent_memory_capture\` to persist it: \`source:"user_stated"\` if literal, \`source:"inferred"\` with confidence <=6 if inferred.
36
+ Before responding, glance at any \`_meta.agent_memory.summary\` returned by tool calls earlier in this session and reflect its top signals in your reasoning ("Filtering by your stated preference for healthcare"). After any material new signal from the user this conversation (sector, region, deal size, communication style, qualification rule, explicit retraction, or recurrence / scheduling preference such as "I do this every day" or "remind me every morning"), call \`leadbay_agent_memory_capture\` to persist it: \`source:"user_stated"\` if literal, \`source:"inferred"\` with confidence <=6 if inferred.
37
37
 
38
38
 
39
- Run the Leadbay daily check-in for me. Treat this prompt the same way for any equivalent ask focused on NEW leads from the Discover wishlist: "get me leadbay leads", "best NEW leads to prospect today", "what's new today", "show me my batch", "let's prospect". For follow-up phrasings ("what should I follow up on", "leads I've already worked", "before my trip"), this is the wrong prompt \u2014 route to \`leadbay_followup_check_in\` instead. If the user's intent is ambiguous ("what should I work on?"), ASK once before picking an entry point.
39
+ Run the Leadbay daily check-in for me. Treat this prompt the same way for any equivalent ask focused on NEW leads from the Discover wishlist: "get me leadbay leads", "best NEW leads to prospect today", "what's new today", "show me my batch", "let's prospect", "run my morning check-in", "my daily routine", "I do this every day", "every morning". For follow-up phrasings ("what should I follow up on", "leads I've already worked", "before my trip"), this is the wrong prompt \u2014 route to \`leadbay_followup_check_in\` instead. **Recurrence language ("I do this every day", "every morning", "my routine") always means this prompt \u2014 it is a daily batch check-in, not a follow-up.** If the user's intent is ambiguous ("what should I work on?"), ASK once before picking an entry point.
40
40
 
41
41
  # Resilience rules for Leadbay long-running tools
42
42
 
@@ -162,13 +162,66 @@ If the batch returns fewer than 10 qualified leads, top it up: call \`leadbay_bu
162
162
 
163
163
  # PHASE 4 \u2014 DEEP DIVE (every promising lead)
164
164
 
165
+ **Skip Phase 4 if the user's request is primarily to view the batch** (e.g., "show me today's leads", "run my morning check-in", "what's in my inbox") \u2014 proceed directly to NEXT STEPS. Run Phase 4 when the user explicitly asks to research leads, names a specific company, or says "and then research" / "deep dive" / "tell me more about".
166
+
165
167
  Call \`leadbay_research_lead_by_id\` on **every** lead from your top 10 that the user might realistically prospect today (filter out clearly weak fits if any). Don't pick just one. **Call it sequentially** \u2014 one at a time, or batches of at most 3 in parallel. Do not fire 10 in parallel \u2014 it triggers transport backpressure that surfaces as \`"Tool permission stream closed"\` errors (see Rule 3 above). If a call fails, retry that single lead once; if the retry also fails, note the lead id and continue. Report Phase 4 results even if 1\u20132 leads were unresearchable.
166
168
 
167
169
  For each researched lead surface:
168
170
  - what makes it promising (1\u20132 sentences citing signals from the research)
169
171
  - the **recommended contacts** the research returns \u2014 name, title, why they're the right starting point
170
172
 
171
- Then ASK the user (don't auto-run): "Want me to enrich the contacts on these leads to acquire their emails / phone numbers?" If the user says yes, call \`leadbay_enrich_contacts\` for the relevant lead IDs (this consumes enrichment quota \u2014 that's why we ask first).
173
+ Contact enrichment is offered in the NEXT STEPS widget below \u2014 do NOT emit a separate prose question here. The widget handles the enrichment offer as one of the selectable options. If the user selects enrichment, call \`leadbay_enrich_contacts({leadId, contactId})\` ONCE PER CONTACT \u2014 the tool takes a single leadId + contactId, never a list. (For bulk title/seniority enrichment across many leads at once, use \`leadbay_enrich_titles({leadIds: [...]})\` instead.) This consumes enrichment quota.
174
+
175
+ # NEXT STEPS
176
+
177
+ **Sequential request gate:** If the user's original message contained the literal phrase "and then" (e.g., "show me X and then do Y"), and all stated actions have been completed this turn, skip the NEXT STEPS widget entirely and emit STOP directly. The user stated their full plan; they do not need a "what next?" prompt.
178
+ - Skip example: "Show me today's leads and then research the top one for me." \u2192 after research completes, go directly to STOP without any widget.
179
+ - Do NOT skip for: plain single-action requests ("show me today's leads"), recurring requests ("I do this every day"), or multi-step workflows the user didn't pre-specify.
180
+
181
+ **REQUIRED OPTIONS \u2014 triggers and position rules:**
182
+ - **Recurring language** ("every day", "every morning", "I do this every", "remind me", "automate this", "recurring"): add "Schedule 'Daily prospecting check-in' as a recurring task" and place it **first**.
183
+ - **\u22655 leads returned**: add "Build an interactive lead triage board for this batch" and place it **first** (or second if the scheduling offer above also applies).
184
+
185
+ ## NEXT STEPS \u2014 after rendering the pull_leads table
186
+
187
+ **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.
188
+
189
+ **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.
190
+
191
+ **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.
192
+ - Skip example: "Show me today's leads and then research the top one for me." \u2192 after research completes, emit STOP without the widget.
193
+ - 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.
194
+
195
+ 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):
196
+ - \`ask_user_input_v0\`: \`{questions:[{question,type:"single_select",options:["<Suggest 1>","<Suggest 2>"]}]}\`
197
+ - \`AskUserQuestion\`: \`{questions:[{question,header:"Next step",multiSelect:false,options:[{label:"<\u22645 words>",description:"<Suggest 1>"}]}]}\`
198
+
199
+ 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.
200
+
201
+ ---
202
+
203
+
204
+
205
+ Pick 2\u20133 items below based on what was actually observed in the response. The table is the source of truth for which moves are valid.
206
+
207
+ | Observation | Suggest | Calls |
208
+ |------------------------------------------------------------|--------------------------------------------------------------|--------------------------------------------------------|
209
+ | \u2265 5 leads returned (any batch) | "Build an interactive lead triage board for this batch" | emit antArtifact from data in hand (do NOT re-call leadbay_pull_leads) |
210
+ | \`has_more == true\` | "Pull the next page (page N+1 of M)" | leadbay_pull_leads(page = current + 1, lensId = pinned)|
211
+ | \u2265 3 rows have \`qualification_summary.answered == 0\` | "Deepen AI qualification on the rows without \u2756 caps" | leadbay_bulk_qualify_leads(leadIds=[\u2026]) |
212
+ | User points at a single row | "Research [Company] in depth" | leadbay_research_lead_by_id(leadId) |
213
+ | User only has a name (no leadId in context) | "Look up [Company] by name" | leadbay_research_lead_by_name_fuzzy(companyName) |
214
+ | Top row has phone AND email | "Prepare an outreach for [Contact] \u2014 call + email" | leadbay_prepare_outreach(leadId) |
215
+ | Top row has email but no phone | "Draft an outreach email for [Contact]" | leadbay_prepare_outreach(leadId) |
216
+ | Top row has phone but no email | "Show [Contact]'s call details + a 60-second opener" | leadbay_prepare_outreach(leadId) |
217
+ | Top row has contacts but no phone/email | "Order contact enrichment to surface email/phone first" | leadbay_enrich_titles(...) or leadbay_prepare_outreach(leadId, enrich:true) |
218
+ | \`computing_scores == true\` or \`computing_wishlist == true\` | "Scores are still being computed \u2014 re-pull in ~30s" | leadbay_pull_leads (retry with same lensId) |
219
+ | User wants a narrower / wider audience | "Adjust the lens filters (sector / size)" | leadbay_adjust_audience(...) |
220
+ | Phase 4 research was run (\`research_lead_by_id\` called) AND top contacts lack direct email/phone | "Enrich contacts on [Lead1], [Lead2] to get direct emails and phone numbers" | leadbay_enrich_contacts(leadId, contactId) \u2014 ONE call per contact (the tool takes a single leadId + contactId, never a list) |
221
+ If nothing in the menu applies cleanly, suggest only "pull next page" and "research a specific lead in depth" \u2014 never invent a tool that doesn't exist.
222
+
223
+
224
+ **Final ordering check (do this before rendering):** Recurring offer \u2192 option 1; triage board \u2192 option 1 (or 2 if scheduling is also required). Swap if needed.
172
225
 
173
226
  # GATE \u2014 STOP
174
227
 
@@ -415,7 +468,7 @@ Done. The map is the surface; the drafts are the action; the campaign is the per
415
468
  var leadbay_prospecting_overview = `
416
469
  ## MEMORY
417
470
 
418
- Before responding, glance at any \`_meta.agent_memory.summary\` returned by tool calls earlier in this session and reflect its top signals in your reasoning ("Filtering by your stated preference for healthcare"). After any material new taste signal from the user this conversation (sector, region, deal size, communication style, qualification rule, explicit retraction), call \`leadbay_agent_memory_capture\` to persist it: \`source:"user_stated"\` if literal, \`source:"inferred"\` with confidence <=6 if inferred.
471
+ Before responding, glance at any \`_meta.agent_memory.summary\` returned by tool calls earlier in this session and reflect its top signals in your reasoning ("Filtering by your stated preference for healthcare"). After any material new signal from the user this conversation (sector, region, deal size, communication style, qualification rule, explicit retraction, or recurrence / scheduling preference such as "I do this every day" or "remind me every morning"), call \`leadbay_agent_memory_capture\` to persist it: \`source:"user_stated"\` if literal, \`source:"inferred"\` with confidence <=6 if inferred.
419
472
 
420
473
 
421
474
  # Leadbay Prospecting \u2014 Orientation
@@ -689,7 +742,7 @@ If the response status is \`applied\`, tell me Leadbay is regenerating intellige
689
742
  var leadbay_research_a_domain = `
690
743
  ## MEMORY
691
744
 
692
- Before responding, glance at any \`_meta.agent_memory.summary\` returned by tool calls earlier in this session and reflect its top signals in your reasoning ("Filtering by your stated preference for healthcare"). After any material new taste signal from the user this conversation (sector, region, deal size, communication style, qualification rule, explicit retraction), call \`leadbay_agent_memory_capture\` to persist it: \`source:"user_stated"\` if literal, \`source:"inferred"\` with confidence <=6 if inferred.
745
+ Before responding, glance at any \`_meta.agent_memory.summary\` returned by tool calls earlier in this session and reflect its top signals in your reasoning ("Filtering by your stated preference for healthcare"). After any material new signal from the user this conversation (sector, region, deal size, communication style, qualification rule, explicit retraction, or recurrence / scheduling preference such as "I do this every day" or "remind me every morning"), call \`leadbay_agent_memory_capture\` to persist it: \`source:"user_stated"\` if literal, \`source:"inferred"\` with confidence <=6 if inferred.
693
746
 
694
747
 
695
748
  IRON LAW \u2014 NO FABRICATION. Every lead id, contact email, custom field id, mapping decision, and tool argument must trace to a value you read from the file the user attached or to an output from a leadbay_* tool call in this session. Do not invent values. Do not "fill in" a missing leadId with a name match. Do not synthesize a CRM id from a guess. If a value is missing, leave the field blank and say so.
@@ -830,7 +883,7 @@ Then ask me ONCE: "Which of these should we drop?" If I name leads to drop, excl
830
883
 
831
884
  # PHASE 3 \u2014 DECIDE THE CAMPAIGN SHAPE
832
885
 
833
- If I provided a \`rep_split\` ("one campaign per rep: John gets Tulsa, Sarah gets OKC"), partition the validated leads accordingly. If I didn't, ask ONCE: "Create one campaign for the whole batch, or split per rep / region / sector?" \u2014 surface 2-4 options via \`ask_user_input_v0\` when available, else as a bulleted list.
886
+ If I provided a \`rep_split\` ("one campaign per rep: John gets Tulsa, Sarah gets OKC"), partition the validated leads accordingly. If I didn't, ask ONCE: "Create one campaign for the whole batch, or split per rep / region / sector?" \u2014 surface 2-4 options via your host's choice widget (\`ask_user_input_v0\` or \`AskUserQuestion\`) when available, else as a bulleted list.
834
887
 
835
888
  For each campaign-shape decision, derive a name. Templates:
836
889
  - Whole batch: \`"<lens-name> \u2013 <YYYY-MM-DD>"\`
@@ -847,7 +900,7 @@ Once the campaigns are created, surface this caveat in plain prose:
847
900
 
848
901
  > Campaign visibility is currently scoped to the user who CREATED the campaign \u2014 the reps won't see these in their own MCP \`leadbay_list_campaigns\` calls. They CAN see them in the web UI at app.leadbay.ai \u2192 Campaigns. Cross-user MCP visibility would need backend work; flag this as a #3630 US3 product gap if your reps work primarily through MCP.
849
902
 
850
- End with a NEXT STEPS chip via \`ask_user_input_v0\`: "View progression on one of these now?" \u2192 routes to \`leadbay_campaign_progression\`.
903
+ End with a NEXT STEPS chip via your host's choice widget (\`ask_user_input_v0\` or \`AskUserQuestion\`): "View progression on one of these now?" \u2192 routes to \`leadbay_campaign_progression\`.
851
904
 
852
905
  # PHASE 6 \u2014 STOP
853
906
 
@@ -863,7 +916,7 @@ If the prompt's body and the tool's RENDERING appear to conflict, the tool's REN
863
916
 
864
917
  # PHASE 0 \u2014 PICK THE CAMPAIGN
865
918
 
866
- If I gave you a name or id, resolve it. Otherwise call \`leadbay_list_campaigns()\` and surface the active campaigns as a \`single_select\` via \`ask_user_input_v0\` (cap at 4 \u2014 sort by \`updated_at\` desc, archived hidden):
919
+ If I gave you a name or id, resolve it. Otherwise call \`leadbay_list_campaigns()\` and surface the active campaigns as a \`single_select\` via your host's choice widget (\`ask_user_input_v0\` or \`AskUserQuestion\`) (cap at 4 \u2014 sort by \`updated_at\` desc, archived hidden):
867
920
 
868
921
  > Which campaign do you want to work?
869
922
  > - <Name 1> \xB7 <N leads> \xB7 last touched <date>
@@ -896,7 +949,7 @@ Call \`leadbay_campaign_call_sheet({campaign_id})\`. The response carries \`summ
896
949
  \u{1F4CB} <total_leads> leads \xB7 \u{1F4DE} <leads_with_phone> with a phone \xB7 \u2709 <leads_with_email> with an email \xB7 \u{1F5FA} <leads_with_coords> with coords \xB7 \u{1F534} <leads_without_contacts> need enrichment \xB7 \u2705 <leads_already_contacted> already touched
897
950
  \`\`\`
898
951
 
899
- **Then PROPOSE the right modes via \`ask_user_input_v0\`** (2-4 options, sorted by what makes the most sense for THIS campaign's data):
952
+ **Then PROPOSE the right modes via your host's choice widget (\`ask_user_input_v0\` or \`AskUserQuestion\`)** (2-4 options, sorted by what makes the most sense for THIS campaign's data):
900
953
 
901
954
  - "\u{1F4DE} Start calling now" \u2014 IF \`ready_for_calling\`. Top option when phones are there.
902
955
  - "\u2709 Email session instead" \u2014 IF \`ready_for_emailing\` AND \`email_ratio > phone_ratio\`. Don't surface this when calling is more obvious.
@@ -958,23 +1011,9 @@ Optional: offer to review the \`leadbay_campaign_progression\` for the same camp
958
1011
  - If the user dictates an outcome that doesn't cleanly map to one of the four epilogue values, ASK ONCE before guessing.
959
1012
  `;
960
1013
  var PROMPT_META = {
961
- leadbay_daily_check_in: { "name": "leadbay_daily_check_in", "short_description": `Run the canonical daily check-in: account state, fresh batch, triage
962
- top 10, deep-dive every promising one, offer contact enrichment. The
963
- morning DISCOVERY workflow (new leads from the lens wishlist). Trigger
964
- on "leadbay leads", "best NEW leads", "what's new today", "show me the
965
- day's batch", "let's prospect". Do NOT trigger on follow-up phrasings
966
- ("what should I follow up on", "before my trip") \u2014 those go to
967
- \`leadbay_followup_check_in\`.
968
- `, "arguments": [], "expected_calls": ["leadbay_account_status", "leadbay_pull_leads", "leadbay_research_lead_by_id", "leadbay_bulk_qualify_leads", "leadbay_enrich_contacts"], "failure_modes": ["Calls leadbay_report_outreach without explicit user authorization", "Surfaces fewer than 10 leads when more are available, or fails to top up via leadbay_qualify_top_n when the batch is short", `Replaces the canonical pull_leads table layout with prose per row (the per-tool RENDERING block is the structural contract; "Today's nudges" goes above it, not in place of it)`, "Skips the nudge paragraph entirely \u2014 the table alone is fine but adding the nudge is the value-add", "Skips deep research on promising leads (Phase 4) \u2014 the agent must call leadbay_research_lead_by_id on each, not just one", "Triggers contact enrichment without asking the user first (it consumes quota)", "Skips the STOP byproduct and proposes next actions on its own", 'Fires 10 parallel leadbay_research_lead_by_id calls and treats "stream closed" errors as terminal \u2014 must serialize and retry singletons', "Re-pulls leadbay_pull_leads without passing the captured lensId, allowing a backend lens shift to discard the Phase 2 batch", 'Treats a "Request timed out" from leadbay_bulk_qualify_leads as terminal instead of retrying with wait_for_completion:false + qualify_status polling', 'Triggers on a follow-up query (e.g., "leads I should follow up with") that should have routed to `leadbay_followup_check_in` \u2014 the two entry points are different data sources (Discover wishlist vs Monitor view) per \xA71.6'] },
969
- leadbay_extend_my_lens: { "name": "leadbay_extend_my_lens", "short_description": "Add more leads to the current lens on demand \u2014 for users whose appetite\nexceeds the standard daily fill. The agent picks seeds silently from\nwhat's already on the lens, fires the extra refill, and surfaces the\nqueue confirmation. The user never reviews the seed list.\n", "arguments": [{ "name": "extra_count", "description": "How many extra leads to add. Optional. Omit to use the backend default.", "required": false }], "expected_calls": ["leadbay_account_status", "leadbay_seed_candidates", "leadbay_extend_lens", "leadbay_pull_leads"], "failure_modes": ["Surfaces the seed candidate list to the user instead of picking silently \u2014 the user asked for MORE LEADS, not a candidate review meeting", "Skips the seeded path and calls `leadbay_extend_lens` with no `seed_lead_ids`, losing the bias signal the recommender needs", "On 429, silently retries instead of surfacing the three options (smaller / wait / upgrade) via `ask_user_input_v0`", "Forgets to pre-check `LENS_EXTRA_REFILL` quota in `leadbay_account_status` and burns a wasted API call", "Skips the post-queue pull-leads suggestion, so the user doesn't see what just got added"] },
970
- leadbay_followup_check_in: { "name": "leadbay_followup_check_in", "short_description": `Run the canonical follow-up check-in: surface KNOWN leads from the
971
- Monitor view that need re-engagement today, ranked by AI urgency,
972
- with the canonical pull_followups table layout. Trigger when the
973
- user asks "follow up", "already known leads", "leads I haven't
974
- contacted", "leads in [city]", "before my trip", "this week",
975
- "this month", "what's overdue", "who should I re-engage", or
976
- anything that implies pre-existing pipeline context.
977
- `, "arguments": [], "expected_calls": ["leadbay_pull_followups", "leadbay_research_lead_by_id", "leadbay_prepare_outreach"], "failure_modes": ["Calls leadbay_pull_leads (the Discover entry point) instead of leadbay_pull_followups \u2014 these are different data sources; the Discover queue does NOT contain Monitor's known-but-cold pipeline", 'Iterates pages of leadbay_pull_leads filtering by engagement_count to "fake" a follow-up view (a real bug observed in 0.9.0 \u2014 the right move is to call pull_followups directly)', "Replaces the canonical pull_followups table layout with prose per row (the per-tool RENDERING block is the structural contract; commentary belongs above or below)", 'Skips the cross-mode pivot offer at the end ("Want to see NEW leads from your wishlist instead?" routes to leadbay_pull_leads)'] },
1014
+ leadbay_daily_check_in: { "name": "leadbay_daily_check_in", "short_description": 'Morning DISCOVERY workflow \u2014 new leads from the lens wishlist. Trigger\non "show me leads", "what\'s new today", "let\'s prospect", "run my check-in",\n"my morning check-in", "I do this every day", "every morning". Recurrence\nlanguage always means this prompt. Do NOT trigger on follow-up phrasings\n("follow up", "before my trip") \u2014 those go to `leadbay_followup_check_in`.\n', "arguments": [], "expected_calls": ["leadbay_account_status", "leadbay_pull_leads", "leadbay_research_lead_by_id", "leadbay_bulk_qualify_leads", "leadbay_enrich_contacts"], "failure_modes": ["Calls leadbay_report_outreach without explicit user authorization", "Surfaces fewer than 10 leads when more are available, or fails to top up via leadbay_qualify_top_n when the batch is short", `Replaces the canonical pull_leads table layout with prose per row (the per-tool RENDERING block is the structural contract; "Today's nudges" goes above it, not in place of it)`, "Skips the nudge paragraph entirely \u2014 the table alone is fine but adding the nudge is the value-add", `Skips deep research on promising leads (Phase 4) \u2014 the agent must call leadbay_research_lead_by_id on each when the user's intent is to research specific leads; Phase 4 is intentionally skipped for batch-view requests ("show me today's leads", "run my morning check-in") per the Phase 4 skip gate`, "Triggers contact enrichment without asking the user first (it consumes quota)", "Skips the STOP byproduct and proposes next actions on its own", 'Fires 10 parallel leadbay_research_lead_by_id calls and treats "stream closed" errors as terminal \u2014 must serialize and retry singletons', "Re-pulls leadbay_pull_leads without passing the captured lensId, allowing a backend lens shift to discard the Phase 2 batch", 'Treats a "Request timed out" from leadbay_bulk_qualify_leads as terminal instead of retrying with wait_for_completion:false + qualify_status polling', 'Triggers on a follow-up query (e.g., "leads I should follow up with") that should have routed to `leadbay_followup_check_in` \u2014 the two entry points are different data sources (Discover wishlist vs Monitor view) per \xA71.6'] },
1015
+ leadbay_extend_my_lens: { "name": "leadbay_extend_my_lens", "short_description": "Add more leads to the current lens on demand \u2014 for users whose appetite\nexceeds the standard daily fill. The agent picks seeds silently from\nwhat's already on the lens, fires the extra refill, and surfaces the\nqueue confirmation. The user never reviews the seed list.\n", "arguments": [{ "name": "extra_count", "description": "How many extra leads to add. Optional. Omit to use the backend default.", "required": false }], "expected_calls": ["leadbay_account_status", "leadbay_seed_candidates", "leadbay_extend_lens", "leadbay_pull_leads"], "failure_modes": ["Surfaces the seed candidate list to the user instead of picking silently \u2014 the user asked for MORE LEADS, not a candidate review meeting", "Skips the seeded path and calls `leadbay_extend_lens` with no `seed_lead_ids`, losing the bias signal the recommender needs", "On 429, silently retries instead of surfacing the three options (smaller / wait / upgrade) via your host's choice widget (`ask_user_input_v0` or `AskUserQuestion`)", "Forgets to pre-check `LENS_EXTRA_REFILL` quota in `leadbay_account_status` and burns a wasted API call", "Skips the post-queue pull-leads suggestion, so the user doesn't see what just got added"] },
1016
+ leadbay_followup_check_in: { "name": "leadbay_followup_check_in", "short_description": 'Follow-up check-in: surface KNOWN leads from the Monitor view needing\nre-engagement. Trigger on "follow up", "already known leads", "what\'s\noverdue", "before my trip", "who should I re-engage". Do NOT trigger on\n"show me today\'s leads", "my morning check-in", "run my check-in",\n"I do this every day", "every morning" \u2014 those go to\n`leadbay_daily_check_in`.\n', "arguments": [], "expected_calls": ["leadbay_pull_followups", "leadbay_research_lead_by_id", "leadbay_prepare_outreach"], "failure_modes": ["Calls leadbay_pull_leads (the Discover entry point) instead of leadbay_pull_followups \u2014 these are different data sources; the Discover queue does NOT contain Monitor's known-but-cold pipeline", 'Iterates pages of leadbay_pull_leads filtering by engagement_count to "fake" a follow-up view (a real bug observed in 0.9.0 \u2014 the right move is to call pull_followups directly)', "Replaces the canonical pull_followups table layout with prose per row (the per-tool RENDERING block is the structural contract; commentary belongs above or below)", 'Skips the cross-mode pivot offer at the end ("Want to see NEW leads from your wishlist instead?" routes to leadbay_pull_leads)'] },
978
1017
  leadbay_import_file: { "name": "leadbay_import_file", "short_description": "Import a user-supplied CSV/file into Leadbay through five phases with\nevidence gates \u2014 scan, derive, resolve identities, preserve & commit,\nthen optionally qualify and report. The job is to maximize how many\nrows the Leadbay system actually ingests and matches.\n", "arguments": [{ "name": "file", "description": "Path or user-visible name of the CSV/file to import. If omitted, use the file the user attached or referenced.", "required": false }, { "name": "instruction", "description": 'Additional user goal, e.g. "then qualify the leads", "preserve owner phone as a custom field", or "only import restaurants in Manhattan".', "required": false }], "expected_calls": ["leadbay_resolve_import_rows", "leadbay_list_mappable_fields", "leadbay_create_custom_field", "leadbay_import_leads", "leadbay_import_and_qualify", "leadbay_add_note", "leadbay_import_status"], "failure_modes": ["Picks LEADBAY_ID from score alone, name-only, fuzzy-name-only, root-domain-only, brand-only, postcode-only, or city-only evidence", "Drops meaningful business notes or CRM record links instead of preserving them as custom fields or lead notes", "Treats a consumer mailbox domain (gmail.com, hotmail.com, ...) as the company domain", "Skips deriving company_domain from a business email when no website column exists (this kills match rate)", "Skips the COLUMN PRESERVATION PLAN byproduct before importing", "Skips the DECISION LOG byproduct before writing LEADBAY_ID", "Returns the imported records WITHOUT writing LEADBAY_ID values back into the user's file (leaves the user no audit trail of what matched)", "Fabricates leadIds, contact emails, or mapping IDs not present in the file or a tool response"] },
979
1018
  leadbay_log_outreach: { "name": "leadbay_log_outreach", "short_description": "Log outreach (an email I sent, a call I made, a meeting I had) on a\nspecific lead. Captures verification so the SDR pipeline trusts the entry.\n", "arguments": [{ "name": "lead_id", "description": "The lead UUID. Get it from leadbay_pull_leads or leadbay_research_lead_by_id.", "required": true }, { "name": "summary", "description": "1-2 sentences describing what I did (e.g. 'Sent intro email to CTO citing recent Hornsea contract').", "required": true }], "expected_calls": ["leadbay_report_outreach"], "failure_modes": ["Calls leadbay_report_outreach without first collecting a verification source", "Fabricates a gmail_message_id or calendar_event_id (the human team treats verification as canonical)", "Records outreach to a different lead_id than the one the user supplied", "Skips the dry_run step when the user is unsure what would be sent"] },
980
1019
  leadbay_plan_tour_in_city: { "name": "leadbay_plan_tour_in_city", "short_description": "Plan a field sales tour: in one flow, surface follow-ups + fresh\nDiscover leads in the target city via `leadbay_tour_plan`, render\nto a map, draft in-area outreach via `leadbay_prepare_outreach`,\nand optionally persist the selected accounts as a named campaign\nvia `leadbay_create_campaign`. Closes #3630 US1 end-to-end.\n", "arguments": [{ "name": "city", "description": "City or region the user is visiting (e.g. 'Limoges', 'Bay Area'). Used as the geo filter for both Monitor and Discover lookups.", "required": true }, { "name": "date", "description": "When the visit is (e.g. 'May 24', 'next Thursday'). Surfaced in the outreach drafts as 'I'll be in <city> on <date>'.", "required": false }], "expected_calls": ["leadbay_tour_plan", "leadbay_research_lead_by_id", "leadbay_prepare_outreach", "leadbay_create_campaign"], "failure_modes": ["Calls leadbay_followups_map (Monitor-only) instead of leadbay_tour_plan \u2014 loses the Discover (fresh-lead) half that the user explicitly asked for", "Calls leadbay_pull_leads then drops the geo filter \u2014 returns the lens-wide wishlist instead of city-relevant fresh leads", 'Skips the campaign-persist step ("would you like to save these as a tour?") \u2014 leaves the rep with a one-shot map but no follow-up artifact', "Creates a campaign WITHOUT asking the user first \u2014 the persist step is high-intent; offer it, don't assume", "Fabricates lead_ids when seeding the campaign instead of using the ids returned by tour_plan"] },
@@ -993,9 +1032,9 @@ should I follow up on" to "I'll send via lemlist".
993
1032
  };
994
1033
  var PROMPT_CATALOG_HEADER = `This server exposes the following workflow prompts via \`prompts/list\` and \`prompts/get\`. Some MCP clients render them as slash commands; if your client does not, you (the agent) should invoke them directly via \`prompts/get\` when the user's request matches one of the triggers described below.`;
995
1034
  var PROMPT_CATALOG_BULLETS = {
996
- leadbay_daily_check_in: `- \`leadbay_daily_check_in\`: Run the canonical daily check-in: account state, fresh batch, triage top 10, deep-dive every promising one, offer contact enrichment. The morning DISCOVERY workflow (new leads from the lens wishlist). Trigger on "leadbay leads", "best NEW leads", "what's new today", "show me the day's batch", "let's prospect". Do NOT trigger on follow-up phrasings ("what should I follow up on", "before my trip") \u2014 those go to \`leadbay_followup_check_in\`.`,
1035
+ leadbay_daily_check_in: `- \`leadbay_daily_check_in\`: Morning DISCOVERY workflow \u2014 new leads from the lens wishlist. Trigger on "show me leads", "what's new today", "let's prospect", "run my check-in", "my morning check-in", "I do this every day", "every morning". Recurrence language always means this prompt. Do NOT trigger on follow-up phrasings ("follow up", "before my trip") \u2014 those go to \`leadbay_followup_check_in\`.`,
997
1036
  leadbay_extend_my_lens: `- \`leadbay_extend_my_lens\` (optional args: extra_count): Add more leads to the current lens on demand \u2014 for users whose appetite exceeds the standard daily fill. The agent picks seeds silently from what's already on the lens, fires the extra refill, and surfaces the queue confirmation. The user never reviews the seed list.`,
998
- leadbay_followup_check_in: `- \`leadbay_followup_check_in\`: Run the canonical follow-up check-in: surface KNOWN leads from the Monitor view that need re-engagement today, ranked by AI urgency, with the canonical pull_followups table layout. Trigger when the user asks "follow up", "already known leads", "leads I haven't contacted", "leads in [city]", "before my trip", "this week", "this month", "what's overdue", "who should I re-engage", or anything that implies pre-existing pipeline context.`,
1037
+ leadbay_followup_check_in: `- \`leadbay_followup_check_in\`: Follow-up check-in: surface KNOWN leads from the Monitor view needing re-engagement. Trigger on "follow up", "already known leads", "what's overdue", "before my trip", "who should I re-engage". Do NOT trigger on "show me today's leads", "my morning check-in", "run my check-in", "I do this every day", "every morning" \u2014 those go to \`leadbay_daily_check_in\`.`,
999
1038
  leadbay_import_file: `- \`leadbay_import_file\` (optional args: file, instruction): Import a user-supplied CSV/file into Leadbay through five phases with evidence gates \u2014 scan, derive, resolve identities, preserve & commit, then optionally qualify and report. The job is to maximize how many rows the Leadbay system actually ingests and matches.`,
1000
1039
  leadbay_log_outreach: `- \`leadbay_log_outreach\` (required args: lead_id, summary): Log outreach (an email I sent, a call I made, a meeting I had) on a specific lead. Captures verification so the SDR pipeline trusts the entry.`,
1001
1040
  leadbay_plan_tour_in_city: `- \`leadbay_plan_tour_in_city\` (required args: city; optional args: date): Plan a field sales tour: in one flow, surface follow-ups + fresh Discover leads in the target city via \`leadbay_tour_plan\`, render to a map, draft in-area outreach via \`leadbay_prepare_outreach\`, and optionally persist the selected accounts as a named campaign via \`leadbay_create_campaign\`. Closes #3630 US1 end-to-end.`,
@@ -6219,6 +6258,7 @@ var COMPOSITE_FILE_TOOL_NAMES = /* @__PURE__ */ new Set([
6219
6258
  "leadbay_research_lead_by_id",
6220
6259
  "leadbay_research_lead_by_name_fuzzy",
6221
6260
  "leadbay_resolve_import_rows",
6261
+ "leadbay_scan_portfolio_signals",
6222
6262
  "leadbay_seed_candidates",
6223
6263
  "leadbay_tour_plan"
6224
6264
  ]);
@@ -6458,6 +6498,45 @@ WHEN NOT TO USE: before doing the revision work; for general "mark all read" swe
6458
6498
 
6459
6499
  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\`.
6460
6500
  `;
6501
+ var leadbay_add_contact = `## WHEN TO USE
6502
+
6503
+ Trigger phrases: "add a contact to this company", "add this person to <company>", "create a contact from this LinkedIn URL", "this company has no contacts \u2014 add one", "I found someone on LinkedIn, add them to <lead>".
6504
+
6505
+ **Memory:** recall + capture via \`leadbay_agent_memory_*\` tools.
6506
+
6507
+ Do NOT use for: "import these companies / a CSV of leads and qualify them" \u2192 \`leadbay_import_and_qualify\`; "get email/phone for a contact already on the company" \u2192 \`leadbay_enrich_titles\`; "remove / delete this contact" \u2192 \`leadbay_remove_contact\`.
6508
+
6509
+ Prefer when: user wants to attach ONE known person to an already-identified company \u2014 pass the company's \`lead_id\` plus the person's name (+ optional linkedin_page/title/email/phone)
6510
+
6511
+ Examples that SHOULD invoke this tool:
6512
+ - "Acme has no suggested contacts \u2014 add Jane Doe, VP Eng, here's her LinkedIn."
6513
+ - "Add this person I found on LinkedIn to that company."
6514
+ - "Create a contact for John Smith, CFO, on this lead."
6515
+
6516
+ Examples that should NOT invoke this tool (sound similar, route elsewhere):
6517
+ - "Import these 40 domains from my CRM and qualify them."
6518
+ - "Get me the email for the contact already on this company."
6519
+ - "Remove that contact, it's the wrong person."
6520
+
6521
+ ## RENDER (quick)
6522
+
6523
+ One-line confirmation: the contact's name + title now sits on the company.
6524
+ No table. If the contact has no email/phone yet, note it can be enriched.
6525
+
6526
+ ---
6527
+
6528
+ Add a single contact (a person) to a known company \u2014 the in-conversation "create a contact" path. Use it when a rep has found someone (often just a LinkedIn URL) and wants them on an already-identified Leadbay company without leaving the chat.
6529
+
6530
+ Pass the parent company's \`lead_id\` plus the person's \`first_name\` + \`last_name\`. Everything else is optional: \`job_title\`, \`linkedin_page\`, \`email\`, \`phone_number\`.
6531
+
6532
+ Backend: \`POST /leads/{lead_id}/contacts\` \u2192 returns the created contact with its new \`id\`. This is the same direct endpoint the Leadbay web UI uses \u2014 one call, no import/qualify quota. (Distinct from \`leadbay_import_and_qualify\`, which is for importing *lists of companies*, not attaching a single person.)
6533
+
6534
+ The created contact starts unenriched \u2014 if it has no email/phone, enrich it via \`leadbay_enrich_titles\`. The undo is \`leadbay_remove_contact\` (pass the returned \`contact.id\`).
6535
+
6536
+ Returns \`{ added: true, lead_id, contact: { id, first_name, last_name, job_title, linkedin_page, email, phone_number, \u2026 } }\`.
6537
+
6538
+ Requires: LEADBAY_MCP_WRITE=1 (MCP) or exposeWrite=true (OpenClaw).
6539
+ `;
6461
6540
  var leadbay_add_leads_to_campaign = `## WHEN TO USE
6462
6541
 
6463
6542
  Trigger phrases: "add leads to <name> campaign", "attach these to <campaign>", "put these in Q2 Push", "add to existing campaign".
@@ -6631,29 +6710,23 @@ Do not enumerate the affected leads \u2014 that's the job of \`leadbay_pull_lead
6631
6710
 
6632
6711
  ---
6633
6712
 
6713
+ ---
6714
+
6634
6715
  ## NEXT STEPS \u2014 after kicking off bulk qualification
6635
6716
 
6636
- **RENDER NEXT STEPS via \`ask_user_input_v0\` when the host exposes it.**
6717
+ **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.
6637
6718
 
6638
- The (Observation, Suggest, Calls) table below is the source of truth for which moves are valid. Pick the 2\u20134 most relevant rows based on what the response actually contains, then surface them as a \`single_select\` quick-select widget:
6719
+ **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.
6639
6720
 
6640
- \`\`\`
6641
- ask_user_input_v0({
6642
- questions: [{
6643
- question: "What next?",
6644
- type: "single_select",
6645
- options: [
6646
- "<Suggest column from row 1>",
6647
- "<Suggest column from row 2>",
6648
- "<Suggest column from row 3>"
6649
- ]
6650
- }]
6651
- })
6652
- \`\`\`
6721
+ **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.
6722
+ - Skip example: "Show me today's leads and then research the top one for me." \u2192 after research completes, emit STOP without the widget.
6723
+ - 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.
6653
6724
 
6654
- When the user picks an option, you call the matching tool from the \`Calls\` column. Constraints carried over from the widget contract: 2\u20134 mutually-exclusive options per question, button-sized labels (\u22646 words), max 3 questions per call.
6725
+ 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):
6726
+ - \`ask_user_input_v0\`: \`{questions:[{question,type:"single_select",options:["<Suggest 1>","<Suggest 2>"]}]}\`
6727
+ - \`AskUserQuestion\`: \`{questions:[{question,header:"Next step",multiSelect:false,options:[{label:"<\u22645 words>",description:"<Suggest 1>"}]}]}\`
6655
6728
 
6656
- **Fallback prose mode** \u2014 when the host doesn't expose \`ask_user_input_v0\` (or it returned an error): surface the same 2\u20133 picks as a short bulleted list of "Suggest" phrasings. The table itself stays internal; never recite the whole table to the user.
6729
+ 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.
6657
6730
 
6658
6731
  ---
6659
6732
 
@@ -6785,7 +6858,7 @@ Modern chat hosts (Claude, ChatGPT) expose first-party widgets the agent can rou
6785
6858
  |---|---|---|
6786
6859
  | \`places_map_display_v0\` (Claude) | Result has \u22652 leads with \`location.city\` set, and the user's intent is geographic / "in person" / travel | \`{name: lead.company_name, address: "<city>, <country>", place_id: lead.location.place_id ?? omit, notes: <one-sentence pitch>}\` per location |
6787
6860
  | \`message_compose_v1\` (Claude) | You're about to draft outreach (email / message / call opener) | \`{kind: "email", summary_title, variants: [{label, body, subject}]}\` \u2014 2\u20133 variants, labels describe STRATEGY ("Push for alignment", "Reference the M&A signal"), not tone ("Friendly", "Formal") |
6788
- | \`ask_user_input_v0\` (Claude) | The tool's NEXT STEPS block has 2\u20134 mutually-exclusive next moves and the user hasn't already chosen | \`{questions: [{question: "What next?", type: "single_select", options: [<2-4 short button labels>]}]}\`; max 3 questions per call |
6861
+ | \`ask_user_input_v0\` (Claude chat / ChatGPT) **or** \`AskUserQuestion\` (Claude cowork / Claude Code) \u2014 whichever is in your tool set; their schemas differ, match the one you have | The tool's NEXT STEPS block has 2\u20134 mutually-exclusive next moves and the user hasn't already chosen | Per-tool schema in the server instructions + NEXT STEPS routing block. Max 3 questions. |
6789
6862
 
6790
6863
  ChatGPT exposes the same routing pattern via \`_meta.openai/outputTemplate\`. We don't ship any custom widgets ourselves \u2014 this gate is exclusively about routing into the host's first-party widgets when the data shape fits.
6791
6864
 
@@ -6877,6 +6950,8 @@ WHEN TO USE: after \`leadbay_list_campaigns\` (or when the user named a specific
6877
6950
  WHEN NOT TO USE: for cross-campaign pulse (use \`leadbay_list_campaigns\`); to drill into a lead's full timeline (use \`leadbay_get_lead_activities\` or \`leadbay_research_lead_by_id\`); to log outreach (\`leadbay_report_outreach\`).
6878
6951
 
6879
6952
  **Response**: \`{items, pagination, summary, _meta}\`. Use the \`summary\` for the one-line headline; use \`items\` for the per-lead table.
6953
+
6954
+ ---
6880
6955
  `;
6881
6956
  var leadbay_clear_selection = `Clear the user's transient selection.
6882
6957
 
@@ -7084,7 +7159,7 @@ Modern chat hosts (Claude, ChatGPT) expose first-party widgets the agent can rou
7084
7159
  |---|---|---|
7085
7160
  | \`places_map_display_v0\` (Claude) | Result has \u22652 leads with \`location.city\` set, and the user's intent is geographic / "in person" / travel | \`{name: lead.company_name, address: "<city>, <country>", place_id: lead.location.place_id ?? omit, notes: <one-sentence pitch>}\` per location |
7086
7161
  | \`message_compose_v1\` (Claude) | You're about to draft outreach (email / message / call opener) | \`{kind: "email", summary_title, variants: [{label, body, subject}]}\` \u2014 2\u20133 variants, labels describe STRATEGY ("Push for alignment", "Reference the M&A signal"), not tone ("Friendly", "Formal") |
7087
- | \`ask_user_input_v0\` (Claude) | The tool's NEXT STEPS block has 2\u20134 mutually-exclusive next moves and the user hasn't already chosen | \`{questions: [{question: "What next?", type: "single_select", options: [<2-4 short button labels>]}]}\`; max 3 questions per call |
7162
+ | \`ask_user_input_v0\` (Claude chat / ChatGPT) **or** \`AskUserQuestion\` (Claude cowork / Claude Code) \u2014 whichever is in your tool set; their schemas differ, match the one you have | The tool's NEXT STEPS block has 2\u20134 mutually-exclusive next moves and the user hasn't already chosen | Per-tool schema in the server instructions + NEXT STEPS routing block. Max 3 questions. |
7088
7163
 
7089
7164
  ChatGPT exposes the same routing pattern via \`_meta.openai/outputTemplate\`. We don't ship any custom widgets ourselves \u2014 this gate is exclusively about routing into the host's first-party widgets when the data shape fits.
7090
7165
 
@@ -7121,7 +7196,7 @@ Examples that should NOT invoke this tool (sound similar, route elsewhere):
7121
7196
 
7122
7197
  \`queued\` \u2192 \u2705 "Queued <N> extra leads on lens <id>. Pull in ~30s." Do NOT
7123
7198
  list \`accepted_seeds\`; they're internal.
7124
- \`quota_exceeded\` \u2192 render three options via \`ask_user_input_v0\` (smaller
7199
+ \`quota_exceeded\` \u2192 render three options via your host's choice widget (\`ask_user_input_v0\` or \`AskUserQuestion\`) (smaller
7125
7200
  count / wait until reset / upgrade).
7126
7201
  \`refresh_in_progress\` \u2192 "lens is filling, retry in a minute".
7127
7202
  \`no_valid_seeds\` \u2192 silently re-call \`leadbay_seed_candidates\`, retry once.
@@ -7139,7 +7214,7 @@ Queue an additive extra-refill on a lens \u2014 more leads on the same criteria,
7139
7214
  **Status envelope (translated from raw API errors so the agent routes on \`status\`).**
7140
7215
 
7141
7216
  - \`status: "queued"\` \u2014 fill is queued. \`accepted_seeds\` lists IDs that passed validation. NEXT STEP: call \`leadbay_pull_leads\` in ~30s.
7142
- - \`status: "quota_exceeded"\` \u2014 daily LENS_EXTRA_REFILL hit. Response carries \`quota: {used_today, resets_at}\` + a \`message\` to surface. **Render three options via \`ask_user_input_v0\`**: (1) smaller \`extra_count\`, (2) wait until \`resets_at\`, (3) upgrade plan (TIER1=150, TIER2=1000). Do NOT silently retry.
7217
+ - \`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.
7143
7218
  - \`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.
7144
7219
  - \`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.
7145
7220
 
@@ -7154,27 +7229,19 @@ This tool MUTATES state. The caller (agent or human-in-the-loop) is responsible
7154
7229
 
7155
7230
  ## NEXT STEPS \u2014 after \`leadbay_extend_lens\`
7156
7231
 
7157
- **RENDER NEXT STEPS via \`ask_user_input_v0\` when the host exposes it.**
7232
+ **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.
7158
7233
 
7159
- The (Observation, Suggest, Calls) table below is the source of truth for which moves are valid. Pick the 2\u20134 most relevant rows based on what the response actually contains, then surface them as a \`single_select\` quick-select widget:
7234
+ **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.
7160
7235
 
7161
- \`\`\`
7162
- ask_user_input_v0({
7163
- questions: [{
7164
- question: "What next?",
7165
- type: "single_select",
7166
- options: [
7167
- "<Suggest column from row 1>",
7168
- "<Suggest column from row 2>",
7169
- "<Suggest column from row 3>"
7170
- ]
7171
- }]
7172
- })
7173
- \`\`\`
7236
+ **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.
7237
+ - Skip example: "Show me today's leads and then research the top one for me." \u2192 after research completes, emit STOP without the widget.
7238
+ - 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.
7174
7239
 
7175
- When the user picks an option, you call the matching tool from the \`Calls\` column. Constraints carried over from the widget contract: 2\u20134 mutually-exclusive options per question, button-sized labels (\u22646 words), max 3 questions per call.
7240
+ 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):
7241
+ - \`ask_user_input_v0\`: \`{questions:[{question,type:"single_select",options:["<Suggest 1>","<Suggest 2>"]}]}\`
7242
+ - \`AskUserQuestion\`: \`{questions:[{question,header:"Next step",multiSelect:false,options:[{label:"<\u22645 words>",description:"<Suggest 1>"}]}]}\`
7176
7243
 
7177
- **Fallback prose mode** \u2014 when the host doesn't expose \`ask_user_input_v0\` (or it returned an error): surface the same 2\u20133 picks as a short bulleted list of "Suggest" phrasings. The table itself stays internal; never recite the whole table to the user.
7244
+ 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.
7178
7245
 
7179
7246
  ---
7180
7247
 
@@ -7317,7 +7384,7 @@ Never link a person's name to the company's LinkedIn page (and vice versa) \u201
7317
7384
 
7318
7385
  Open with **one short intro sentence** in chat ("Five lead visits across NYC for your trip next week \u2014 three in Midtown, plus Long Island and one in NJ.") and then invoke the widget, then the chat-side list above. **No markdown table.**
7319
7386
 
7320
- **After the widget renders, end the turn with the NEXT STEPS surface** \u2014 not with a prose question. See "GATE \u2014 PREFER BUILT-IN HOST WIDGETS" below: surface 2\u20134 mutually-exclusive moves via \`ask_user_input_v0\` if the host exposes it, else as a short bulleted list. "Want me to plot these on a map or jump to outreach for Atlas?" is exactly the prose pattern to AVOID \u2014 it's a \`single_select\` with two options.
7387
+ **After the widget renders, end the turn with the NEXT STEPS surface** \u2014 not with a prose question. See "GATE \u2014 PREFER BUILT-IN HOST WIDGETS" below: surface 2\u20134 mutually-exclusive moves via your host's choice widget (\`ask_user_input_v0\` or \`AskUserQuestion\`) if the host exposes it, else as a short bulleted list. "Want me to plot these on a map or jump to outreach for Atlas?" is exactly the prose pattern to AVOID \u2014 it's a \`single_select\` with two options.
7321
7388
 
7322
7389
  ## RENDER \u2014 fallback for hosts without \`places_map_display_v0\`
7323
7390
 
@@ -7348,7 +7415,7 @@ Modern chat hosts (Claude, ChatGPT) expose first-party widgets the agent can rou
7348
7415
  |---|---|---|
7349
7416
  | \`places_map_display_v0\` (Claude) | Result has \u22652 leads with \`location.city\` set, and the user's intent is geographic / "in person" / travel | \`{name: lead.company_name, address: "<city>, <country>", place_id: lead.location.place_id ?? omit, notes: <one-sentence pitch>}\` per location |
7350
7417
  | \`message_compose_v1\` (Claude) | You're about to draft outreach (email / message / call opener) | \`{kind: "email", summary_title, variants: [{label, body, subject}]}\` \u2014 2\u20133 variants, labels describe STRATEGY ("Push for alignment", "Reference the M&A signal"), not tone ("Friendly", "Formal") |
7351
- | \`ask_user_input_v0\` (Claude) | The tool's NEXT STEPS block has 2\u20134 mutually-exclusive next moves and the user hasn't already chosen | \`{questions: [{question: "What next?", type: "single_select", options: [<2-4 short button labels>]}]}\`; max 3 questions per call |
7418
+ | \`ask_user_input_v0\` (Claude chat / ChatGPT) **or** \`AskUserQuestion\` (Claude cowork / Claude Code) \u2014 whichever is in your tool set; their schemas differ, match the one you have | The tool's NEXT STEPS block has 2\u20134 mutually-exclusive next moves and the user hasn't already chosen | Per-tool schema in the server instructions + NEXT STEPS routing block. Max 3 questions. |
7352
7419
 
7353
7420
  ChatGPT exposes the same routing pattern via \`_meta.openai/outputTemplate\`. We don't ship any custom widgets ourselves \u2014 this gate is exclusively about routing into the host's first-party widgets when the data shape fits.
7354
7421
 
@@ -7493,27 +7560,19 @@ Defer the full list of imported leads to \`leadbay_pull_leads\` or \`leadbay_res
7493
7560
 
7494
7561
  ## NEXT STEPS \u2014 after an import
7495
7562
 
7496
- **RENDER NEXT STEPS via \`ask_user_input_v0\` when the host exposes it.**
7563
+ **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.
7497
7564
 
7498
- The (Observation, Suggest, Calls) table below is the source of truth for which moves are valid. Pick the 2\u20134 most relevant rows based on what the response actually contains, then surface them as a \`single_select\` quick-select widget:
7565
+ **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.
7499
7566
 
7500
- \`\`\`
7501
- ask_user_input_v0({
7502
- questions: [{
7503
- question: "What next?",
7504
- type: "single_select",
7505
- options: [
7506
- "<Suggest column from row 1>",
7507
- "<Suggest column from row 2>",
7508
- "<Suggest column from row 3>"
7509
- ]
7510
- }]
7511
- })
7512
- \`\`\`
7567
+ **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.
7568
+ - Skip example: "Show me today's leads and then research the top one for me." \u2192 after research completes, emit STOP without the widget.
7569
+ - 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.
7513
7570
 
7514
- When the user picks an option, you call the matching tool from the \`Calls\` column. Constraints carried over from the widget contract: 2\u20134 mutually-exclusive options per question, button-sized labels (\u22646 words), max 3 questions per call.
7571
+ 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):
7572
+ - \`ask_user_input_v0\`: \`{questions:[{question,type:"single_select",options:["<Suggest 1>","<Suggest 2>"]}]}\`
7573
+ - \`AskUserQuestion\`: \`{questions:[{question,header:"Next step",multiSelect:false,options:[{label:"<\u22645 words>",description:"<Suggest 1>"}]}]}\`
7515
7574
 
7516
- **Fallback prose mode** \u2014 when the host doesn't expose \`ask_user_input_v0\` (or it returned an error): surface the same 2\u20133 picks as a short bulleted list of "Suggest" phrasings. The table itself stays internal; never recite the whole table to the user.
7575
+ 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.
7517
7576
 
7518
7577
  ---
7519
7578
 
@@ -7566,27 +7625,19 @@ Defer the full list of imported leads to \`leadbay_pull_leads\` or \`leadbay_res
7566
7625
 
7567
7626
  ## NEXT STEPS \u2014 after an import
7568
7627
 
7569
- **RENDER NEXT STEPS via \`ask_user_input_v0\` when the host exposes it.**
7628
+ **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.
7570
7629
 
7571
- The (Observation, Suggest, Calls) table below is the source of truth for which moves are valid. Pick the 2\u20134 most relevant rows based on what the response actually contains, then surface them as a \`single_select\` quick-select widget:
7630
+ **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.
7572
7631
 
7573
- \`\`\`
7574
- ask_user_input_v0({
7575
- questions: [{
7576
- question: "What next?",
7577
- type: "single_select",
7578
- options: [
7579
- "<Suggest column from row 1>",
7580
- "<Suggest column from row 2>",
7581
- "<Suggest column from row 3>"
7582
- ]
7583
- }]
7584
- })
7585
- \`\`\`
7632
+ **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.
7633
+ - Skip example: "Show me today's leads and then research the top one for me." \u2192 after research completes, emit STOP without the widget.
7634
+ - 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.
7586
7635
 
7587
- When the user picks an option, you call the matching tool from the \`Calls\` column. Constraints carried over from the widget contract: 2\u20134 mutually-exclusive options per question, button-sized labels (\u22646 words), max 3 questions per call.
7636
+ 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):
7637
+ - \`ask_user_input_v0\`: \`{questions:[{question,type:"single_select",options:["<Suggest 1>","<Suggest 2>"]}]}\`
7638
+ - \`AskUserQuestion\`: \`{questions:[{question,header:"Next step",multiSelect:false,options:[{label:"<\u22645 words>",description:"<Suggest 1>"}]}]}\`
7588
7639
 
7589
- **Fallback prose mode** \u2014 when the host doesn't expose \`ask_user_input_v0\` (or it returned an error): surface the same 2\u20133 picks as a short bulleted list of "Suggest" phrasings. The table itself stays internal; never recite the whole table to the user.
7640
+ 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.
7590
7641
 
7591
7642
  ---
7592
7643
 
@@ -7726,6 +7777,8 @@ WHEN TO USE: the user wants the cross-campaign pulse \u2014 what cohorts are in
7726
7777
  WHEN NOT TO USE: for per-lead progression inside ONE campaign (use \`leadbay_campaign_progression\`); to create a campaign (\`leadbay_create_campaign\`); to add leads to one (\`leadbay_add_leads_to_campaign\`).
7727
7778
 
7728
7779
  **Response**: \`{campaigns: CampaignWithStats[], _meta}\`. Sort by \`updated_at desc\` when rendering \u2014 recency is the manager's natural lens.
7780
+
7781
+ ---
7729
7782
  `;
7730
7783
  var leadbay_list_lenses = `List all available Leadbay lenses (saved lead-search configurations). Each lens defines a different target market or buyer segment. The lens with \`is_last_active=true\` is used by default for lead discovery.
7731
7784
 
@@ -7852,7 +7905,7 @@ Modern chat hosts (Claude, ChatGPT) expose first-party widgets the agent can rou
7852
7905
  |---|---|---|
7853
7906
  | \`places_map_display_v0\` (Claude) | Result has \u22652 leads with \`location.city\` set, and the user's intent is geographic / "in person" / travel | \`{name: lead.company_name, address: "<city>, <country>", place_id: lead.location.place_id ?? omit, notes: <one-sentence pitch>}\` per location |
7854
7907
  | \`message_compose_v1\` (Claude) | You're about to draft outreach (email / message / call opener) | \`{kind: "email", summary_title, variants: [{label, body, subject}]}\` \u2014 2\u20133 variants, labels describe STRATEGY ("Push for alignment", "Reference the M&A signal"), not tone ("Friendly", "Formal") |
7855
- | \`ask_user_input_v0\` (Claude) | The tool's NEXT STEPS block has 2\u20134 mutually-exclusive next moves and the user hasn't already chosen | \`{questions: [{question: "What next?", type: "single_select", options: [<2-4 short button labels>]}]}\`; max 3 questions per call |
7908
+ | \`ask_user_input_v0\` (Claude chat / ChatGPT) **or** \`AskUserQuestion\` (Claude cowork / Claude Code) \u2014 whichever is in your tool set; their schemas differ, match the one you have | The tool's NEXT STEPS block has 2\u20134 mutually-exclusive next moves and the user hasn't already chosen | Per-tool schema in the server instructions + NEXT STEPS routing block. Max 3 questions. |
7856
7909
 
7857
7910
  ChatGPT exposes the same routing pattern via \`_meta.openai/outputTemplate\`. We don't ship any custom widgets ourselves \u2014 this gate is exclusively about routing into the host's first-party widgets when the data shape fits.
7858
7911
 
@@ -7891,27 +7944,19 @@ render an empty table.
7891
7944
 
7892
7945
  ## NEXT STEPS \u2014 after \`leadbay_my_lenses\`
7893
7946
 
7894
- **RENDER NEXT STEPS via \`ask_user_input_v0\` when the host exposes it.**
7947
+ **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.
7895
7948
 
7896
- The (Observation, Suggest, Calls) table below is the source of truth for which moves are valid. Pick the 2\u20134 most relevant rows based on what the response actually contains, then surface them as a \`single_select\` quick-select widget:
7949
+ **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.
7897
7950
 
7898
- \`\`\`
7899
- ask_user_input_v0({
7900
- questions: [{
7901
- question: "What next?",
7902
- type: "single_select",
7903
- options: [
7904
- "<Suggest column from row 1>",
7905
- "<Suggest column from row 2>",
7906
- "<Suggest column from row 3>"
7907
- ]
7908
- }]
7909
- })
7910
- \`\`\`
7951
+ **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.
7952
+ - Skip example: "Show me today's leads and then research the top one for me." \u2192 after research completes, emit STOP without the widget.
7953
+ - 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.
7911
7954
 
7912
- When the user picks an option, you call the matching tool from the \`Calls\` column. Constraints carried over from the widget contract: 2\u20134 mutually-exclusive options per question, button-sized labels (\u22646 words), max 3 questions per call.
7955
+ 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):
7956
+ - \`ask_user_input_v0\`: \`{questions:[{question,type:"single_select",options:["<Suggest 1>","<Suggest 2>"]}]}\`
7957
+ - \`AskUserQuestion\`: \`{questions:[{question,header:"Next step",multiSelect:false,options:[{label:"<\u22645 words>",description:"<Suggest 1>"}]}]}\`
7913
7958
 
7914
- **Fallback prose mode** \u2014 when the host doesn't expose \`ask_user_input_v0\` (or it returned an error): surface the same 2\u20133 picks as a short bulleted list of "Suggest" phrasings. The table itself stays internal; never recite the whole table to the user.
7959
+ 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.
7915
7960
 
7916
7961
  ---
7917
7962
 
@@ -7989,7 +8034,7 @@ Modern chat hosts (Claude, ChatGPT) expose first-party widgets the agent can rou
7989
8034
  |---|---|---|
7990
8035
  | \`places_map_display_v0\` (Claude) | Result has \u22652 leads with \`location.city\` set, and the user's intent is geographic / "in person" / travel | \`{name: lead.company_name, address: "<city>, <country>", place_id: lead.location.place_id ?? omit, notes: <one-sentence pitch>}\` per location |
7991
8036
  | \`message_compose_v1\` (Claude) | You're about to draft outreach (email / message / call opener) | \`{kind: "email", summary_title, variants: [{label, body, subject}]}\` \u2014 2\u20133 variants, labels describe STRATEGY ("Push for alignment", "Reference the M&A signal"), not tone ("Friendly", "Formal") |
7992
- | \`ask_user_input_v0\` (Claude) | The tool's NEXT STEPS block has 2\u20134 mutually-exclusive next moves and the user hasn't already chosen | \`{questions: [{question: "What next?", type: "single_select", options: [<2-4 short button labels>]}]}\`; max 3 questions per call |
8037
+ | \`ask_user_input_v0\` (Claude chat / ChatGPT) **or** \`AskUserQuestion\` (Claude cowork / Claude Code) \u2014 whichever is in your tool set; their schemas differ, match the one you have | The tool's NEXT STEPS block has 2\u20134 mutually-exclusive next moves and the user hasn't already chosen | Per-tool schema in the server instructions + NEXT STEPS routing block. Max 3 questions. |
7993
8038
 
7994
8039
  ChatGPT exposes the same routing pattern via \`_meta.openai/outputTemplate\`. We don't ship any custom widgets ourselves \u2014 this gate is exclusively about routing into the host's first-party widgets when the data shape fits.
7995
8040
 
@@ -8004,27 +8049,19 @@ ChatGPT exposes the same routing pattern via \`_meta.openai/outputTemplate\`. We
8004
8049
 
8005
8050
  ## NEXT STEPS \u2014 after \`leadbay_new_lens\`
8006
8051
 
8007
- **RENDER NEXT STEPS via \`ask_user_input_v0\` when the host exposes it.**
8052
+ **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.
8008
8053
 
8009
- The (Observation, Suggest, Calls) table below is the source of truth for which moves are valid. Pick the 2\u20134 most relevant rows based on what the response actually contains, then surface them as a \`single_select\` quick-select widget:
8054
+ **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.
8010
8055
 
8011
- \`\`\`
8012
- ask_user_input_v0({
8013
- questions: [{
8014
- question: "What next?",
8015
- type: "single_select",
8016
- options: [
8017
- "<Suggest column from row 1>",
8018
- "<Suggest column from row 2>",
8019
- "<Suggest column from row 3>"
8020
- ]
8021
- }]
8022
- })
8023
- \`\`\`
8056
+ **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.
8057
+ - Skip example: "Show me today's leads and then research the top one for me." \u2192 after research completes, emit STOP without the widget.
8058
+ - 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.
8024
8059
 
8025
- When the user picks an option, you call the matching tool from the \`Calls\` column. Constraints carried over from the widget contract: 2\u20134 mutually-exclusive options per question, button-sized labels (\u22646 words), max 3 questions per call.
8060
+ 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):
8061
+ - \`ask_user_input_v0\`: \`{questions:[{question,type:"single_select",options:["<Suggest 1>","<Suggest 2>"]}]}\`
8062
+ - \`AskUserQuestion\`: \`{questions:[{question,header:"Next step",multiSelect:false,options:[{label:"<\u22645 words>",description:"<Suggest 1>"}]}]}\`
8026
8063
 
8027
- **Fallback prose mode** \u2014 when the host doesn't expose \`ask_user_input_v0\` (or it returned an error): surface the same 2\u20133 picks as a short bulleted list of "Suggest" phrasings. The table itself stays internal; never recite the whole table to the user.
8064
+ 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.
8028
8065
 
8029
8066
  ---
8030
8067
 
@@ -8064,6 +8101,42 @@ WHEN NOT TO USE: from agent flow \u2014 use leadbay_answer_clarification.
8064
8101
 
8065
8102
  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\`.
8066
8103
  `;
8104
+ var leadbay_pin_contact = `## WHEN TO USE
8105
+
8106
+ Trigger phrases: "pin this contact", "mark this person as priority", "make this the main contact", "favourite this contact".
8107
+
8108
+ **Memory:** recall + capture via \`leadbay_agent_memory_*\` tools.
8109
+
8110
+ Do NOT use for: "unpin / remove the pin" \u2192 \`leadbay_unpin_contact\`; "add a contact to this company" \u2192 \`leadbay_add_contact\`; "remove / delete this contact" \u2192 \`leadbay_remove_contact\`.
8111
+
8112
+ Prefer when: user wants ONE person flagged as the priority on a company \u2014 pass that contact's own \`contact_id\`
8113
+
8114
+ Examples that SHOULD invoke this tool:
8115
+ - "Pin Jane Doe as the main contact on this company."
8116
+ - "Mark this person as the priority contact."
8117
+ - "Favourite that contact so it shows first."
8118
+
8119
+ Examples that should NOT invoke this tool (sound similar, route elsewhere):
8120
+ - "Add a contact to this company."
8121
+ - "Remove that contact, wrong person."
8122
+ - "Stop showing me this lead."
8123
+
8124
+ ## RENDER (quick)
8125
+
8126
+ One-line confirmation that the named contact (or id) is now pinned. No table.
8127
+
8128
+ ---
8129
+
8130
+ Pin a single contact on a company so it surfaces first as a priority / favourite. Use when the user wants to flag a specific person as the one to focus on.
8131
+
8132
+ Pass the contact's **own** \`contact_id\` (the \`id\` field on a contact object from \`leadbay_research_lead_by_id\` or a contacts list) \u2014 **not** the parent lead id.
8133
+
8134
+ Backend: \`POST /contacts/{contact_id}/pin\` \u2192 204. Idempotent. The inverse is \`leadbay_unpin_contact\`.
8135
+
8136
+ Returns \`{ pinned: true, contact_id, action: "pinned" }\`.
8137
+
8138
+ Requires: LEADBAY_MCP_WRITE=1 (MCP) or exposeWrite=true (OpenClaw).
8139
+ `;
8067
8140
  var leadbay_prepare_outreach = `## WHEN TO USE
8068
8141
 
8069
8142
  Trigger phrases: "draft outreach for <Contact>", "write an email to <Contact>", "outreach package for <Company>".
@@ -8093,7 +8166,7 @@ email. Do NOT paste the email body into chat prose alongside.
8093
8166
 
8094
8167
  ---
8095
8168
 
8096
- Prepare a single-lead outreach brief: the full \`lead\` block (score, \`split_ai_summary\`, \`location\`, \`size\`, \`phone_numbers\`, \`website\`, \`description\`, \`social_urls\`, \`social_presence\`), the \`recommended_contact\` (always in the post-enrichment shape \u2014 \`contact_id\`, \`first_name\`, \`last_name\`, \`job_title\`, \`email\`, \`phone_number\`, \`linkedin_page\`, \`is_org_contact\` \u2014 with nulls where data isn't yet enriched), \`additional_contacts_count\` (other contacts at this company), and an \`enrichment\` block describing async state.
8169
+ Prepare a single-lead outreach brief: the full \`lead\` block (score, \`split_ai_summary\`, \`location\`, \`size\`, \`phone_numbers\`, \`website\`, \`description\`, \`social_urls\`, \`social_presence\`), the \`recommended_contact\` (always in the post-enrichment shape \u2014 \`contact_id\`, \`first_name\`, \`last_name\`, \`job_title\`, \`email\`, \`phone_number\`, \`linkedin_page\`, \`is_org_contact\` \u2014 with nulls where data isn't yet enriched), \`additional_contacts_count\`, and an \`enrichment\` block describing async state.
8097
8170
 
8098
8171
  Optionally trigger contact enrichment in-flight with \`enrich:true\`. Enrichment is async (~60s). **Self-polling pattern (no separate tool needed):** re-call \`leadbay_prepare_outreach(leadId)\` without \`enrich\`; check \`enrichment.complete\`. When \`complete: true\`, the recommended contact now carries \`email\` and/or \`phone_number\`.
8099
8172
 
@@ -8110,46 +8183,9 @@ WHEN NOT TO USE: across many leads \u2014 use leadbay_enrich_titles for bulk; fo
8110
8183
 
8111
8184
  ## RENDER \u2014 host-native message composer is the PRIMARY surface
8112
8185
 
8113
- \`message_compose_v1\` is the canonical surface for outreach drafts on this tool. The composer gives the user inline edit + send affordances and beats any prose code-fenced draft. **If the host exposes \`message_compose_v1\`, route every draft through it.** Don't paste email body or call-opener body into chat prose alongside \u2014 the composer IS the visual.
8114
-
8115
- Above the composer, emit ONE short markdown context paragraph: the lead's score callout + sector fit + recommended-contact name (LinkedIn-markdown-linked) + bare phone/email pills. That gives the user the "why this lead" context. The composer below carries the actionable draft.
8116
-
8117
- **Single draft:**
8118
-
8119
- \`\`\`
8120
- message_compose_v1({
8121
- kind: "email",
8122
- summary_title: "Outreach to <Contact Name> at <Company>",
8123
- variants: [{
8124
- label: "Lead with the M&A signal",
8125
- subject: "<one-line subject \u2014 references the angle>",
8126
- body: "<5-8 sentence email; salesperson voice; references signal + a clear next step>"
8127
- }]
8128
- })
8129
- \`\`\`
8130
-
8131
- **Strategic options (preferred when split_ai_summary surfaces multiple angles):**
8132
-
8133
- \`\`\`
8134
- message_compose_v1({
8135
- kind: "email",
8136
- summary_title: "Three angles for <Company> outreach",
8137
- variants: [
8138
- { label: "Push for alignment", subject: "...", body: "..." },
8139
- { label: "Reference the M&A signal", subject: "...", body: "..." },
8140
- { label: "Soft intro \u2014 peer reference", subject: "...", body: "..." }
8141
- ]
8142
- })
8143
- \`\`\`
8144
-
8145
- Constraints:
8146
- - **Labels describe STRATEGY, not tone.** "Push for alignment", "Reference M&A signal", "Lead with peer reference" \u2014 not "Friendly" / "Formal" / "Aggressive".
8147
- - **2\u20133 variants when strategic options are clearly distinct.** One variant when you have a single best-angle draft.
8148
- - Subject required for \`kind: "email"\`. Phone/call openers use \`kind: "other"\` with the opener in \`body\`.
8186
+ Route every draft through \`message_compose_v1\` (Claude's email composer). Above it, emit ONE short markdown context paragraph: score callout + sector fit + linked contact name + bare phone/email pills. Do NOT paste the email body into chat prose alongside \u2014 the composer IS the visual.
8149
8187
 
8150
- The composer becomes the single visual. **Don't also paste the email body into chat prose** \u2014 that's just noise next to the composer.
8151
-
8152
- For phone-only contacts (no email enriched), use \`kind: "other"\` with a 60-second call opener.
8188
+ Variant shape: 1\u20133 entries. Labels describe **strategy** ("Push for alignment", "Reference the M&A signal", "Soft intro \u2014 peer reference"), not tone. \`kind: "email"\` requires \`subject\`; phone/call openers use \`kind: "other"\` with the opener in \`body\`.
8153
8189
 
8154
8190
  ## GATE \u2014 PREFER BUILT-IN HOST WIDGETS
8155
8191
 
@@ -8161,7 +8197,7 @@ Modern chat hosts (Claude, ChatGPT) expose first-party widgets the agent can rou
8161
8197
  |---|---|---|
8162
8198
  | \`places_map_display_v0\` (Claude) | Result has \u22652 leads with \`location.city\` set, and the user's intent is geographic / "in person" / travel | \`{name: lead.company_name, address: "<city>, <country>", place_id: lead.location.place_id ?? omit, notes: <one-sentence pitch>}\` per location |
8163
8199
  | \`message_compose_v1\` (Claude) | You're about to draft outreach (email / message / call opener) | \`{kind: "email", summary_title, variants: [{label, body, subject}]}\` \u2014 2\u20133 variants, labels describe STRATEGY ("Push for alignment", "Reference the M&A signal"), not tone ("Friendly", "Formal") |
8164
- | \`ask_user_input_v0\` (Claude) | The tool's NEXT STEPS block has 2\u20134 mutually-exclusive next moves and the user hasn't already chosen | \`{questions: [{question: "What next?", type: "single_select", options: [<2-4 short button labels>]}]}\`; max 3 questions per call |
8200
+ | \`ask_user_input_v0\` (Claude chat / ChatGPT) **or** \`AskUserQuestion\` (Claude cowork / Claude Code) \u2014 whichever is in your tool set; their schemas differ, match the one you have | The tool's NEXT STEPS block has 2\u20134 mutually-exclusive next moves and the user hasn't already chosen | Per-tool schema in the server instructions + NEXT STEPS routing block. Max 3 questions. |
8165
8201
 
8166
8202
  ChatGPT exposes the same routing pattern via \`_meta.openai/outputTemplate\`. We don't ship any custom widgets ourselves \u2014 this gate is exclusively about routing into the host's first-party widgets when the data shape fits.
8167
8203
 
@@ -8242,27 +8278,19 @@ When the response carries \`social_urls\` (the post-fix multi-platform URL block
8242
8278
 
8243
8279
  ## NEXT STEPS \u2014 after the outreach brief
8244
8280
 
8245
- **RENDER NEXT STEPS via \`ask_user_input_v0\` when the host exposes it.**
8281
+ **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.
8246
8282
 
8247
- The (Observation, Suggest, Calls) table below is the source of truth for which moves are valid. Pick the 2\u20134 most relevant rows based on what the response actually contains, then surface them as a \`single_select\` quick-select widget:
8283
+ **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.
8248
8284
 
8249
- \`\`\`
8250
- ask_user_input_v0({
8251
- questions: [{
8252
- question: "What next?",
8253
- type: "single_select",
8254
- options: [
8255
- "<Suggest column from row 1>",
8256
- "<Suggest column from row 2>",
8257
- "<Suggest column from row 3>"
8258
- ]
8259
- }]
8260
- })
8261
- \`\`\`
8285
+ **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.
8286
+ - Skip example: "Show me today's leads and then research the top one for me." \u2192 after research completes, emit STOP without the widget.
8287
+ - 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.
8262
8288
 
8263
- When the user picks an option, you call the matching tool from the \`Calls\` column. Constraints carried over from the widget contract: 2\u20134 mutually-exclusive options per question, button-sized labels (\u22646 words), max 3 questions per call.
8289
+ 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):
8290
+ - \`ask_user_input_v0\`: \`{questions:[{question,type:"single_select",options:["<Suggest 1>","<Suggest 2>"]}]}\`
8291
+ - \`AskUserQuestion\`: \`{questions:[{question,header:"Next step",multiSelect:false,options:[{label:"<\u22645 words>",description:"<Suggest 1>"}]}]}\`
8264
8292
 
8265
- **Fallback prose mode** \u2014 when the host doesn't expose \`ask_user_input_v0\` (or it returned an error): surface the same 2\u20133 picks as a short bulleted list of "Suggest" phrasings. The table itself stays internal; never recite the whole table to the user.
8293
+ 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.
8266
8294
 
8267
8295
  ---
8268
8296
 
@@ -8282,7 +8310,6 @@ Offer 2\u20133 follow-ups. Choose based on enrichment state + available channels
8282
8310
  | User reports they reached out | "Log this outreach \u2014 creates prospecting action + outcome" | leadbay_report_outreach(leadId, contact_id, ...) |
8283
8311
  | User adds context for next time | "Save a note on the contact or company" | leadbay_add_note |
8284
8312
  | After a successful exchange | "Update qualification answers based on what you learned" | leadbay_answer_clarification |
8285
-
8286
8313
  The "log outreach" step is the most-important follow-up \u2014 it closes the loop and populates history for the next \`leadbay_prepare_outreach\` call. Detect intent from natural language: "I sent the email", "she didn't pick up", "left a voicemail", "they responded yes/no", etc.
8287
8314
  `;
8288
8315
  var leadbay_preview_bulk_enrichment = `Preview a bulk-enrichment cost given a set of job titles applied to the current selection. Returns \`{selected_leads, enriched_contacts, enrichable_contacts, title_suggestions, auto_included_titles, previously_enriched_titles}\`. \`previously_enriched_titles\` is a newer field (in prod soon) \u2014 when present, the agent can recommend repeating those titles for new leads.
@@ -8333,9 +8360,9 @@ table. Detail + status priority below.
8333
8360
 
8334
8361
  Pull KNOWN leads from the user's Monitor view \u2014 the re-engagement entry point. Use when the user asks "what should I follow up on", "leads I haven't contacted", "leads in [city]", "before my trip", or any phrasing implying pre-existing pipeline context. For NEW leads from Discover, use \`leadbay_pull_leads\`.
8335
8362
 
8336
- Backend: wraps \`GET /1.5/monitor?personal=&liked=&filtered=&count=&page=\` plus, when \`set_filter\` is supplied, a preceding \`POST /1.5/monitor/filter\` to persist the filter server-side. The Monitor filter is a single \`FilterItem\` per user \u2014 refreshing the page restores it.
8363
+ Backend: wraps \`GET /1.5/monitor?personal=&liked=&filtered=&count=&page=\` plus, when \`set_filter\` is supplied, a preceding \`POST /1.5/monitor/filter\`. The Monitor filter is a single \`FilterItem\` per user \u2014 refreshing restores it.
8337
8364
 
8338
- **Filter mechanism \u2014 store-then-apply.** Pass \`set_filter: { criteria: FilterCriterion[] }\` to overwrite the server-stored filter, then the composite re-fetches with \`filtered:true\`. \`FilterCriterion\` is the backend's \`anyOf\` over 10 typed criteria: \`size\`, \`keywords\`, \`sector_ids\`, \`location_ids\`, \`custom_field\`, \`custom_field_comparison\`, \`yc\`, \`liked\`, \`last_action\` (filters by MonitorActionType enum), \`last_action_date\` (with \`last_days\` for "last N days").
8365
+ **Filter mechanism \u2014 store-then-apply.** Pass \`set_filter: { criteria: FilterCriterion[] }\` to overwrite the server-stored filter, then the composite re-fetches with \`filtered:true\`. \`FilterCriterion\` is the backend's \`anyOf\` over 10 typed criteria: \`size\`, \`keywords\`, \`sector_ids\`, \`location_ids\`, \`custom_field\`(\`_comparison\`), \`yc\`, \`liked\`, \`last_action\` (MonitorActionType enum), \`last_action_date\` (with \`last_days\`).
8339
8366
 
8340
8367
  Practical mapping from user phrasing to criterion:
8341
8368
 
@@ -8348,11 +8375,11 @@ Practical mapping from user phrasing to criterion:
8348
8375
  | "leads 50\u2013200 employees" | \`{type: "size", sizes: [{min: 50, max: 200}]}\` |
8349
8376
  | "Y Combinator companies" | \`{type: "yc"}\` |
8350
8377
 
8351
- Geo filtering needs \`admin_area_id\` resolution \u2014 backend rejects free-text in \`location_ids\`. Pass \`city: "<free-text>"\` and the composite calls \`/geo/search\` internally, picks the best match, merges its id into \`set_filter\`. Ambiguous matches return \`status: "ambiguous_locations"\` + \`location_ambiguities[]\` \u2014 pick an id and re-call with \`city_id\`. For multi-city cases, call \`leadbay_list_locations\` then pass \`set_filter.criteria\` with \`{type: "location_ids", is_excluded: false, locations: [...]}\`.
8378
+ Geo filtering needs \`admin_area_id\` resolution \u2014 backend rejects free-text in \`location_ids\`. Pass \`city: "<free-text>"\` and the composite calls \`/geo/search\` internally, picks the best match, merges its id into \`set_filter\`. Ambiguous matches return \`status: "ambiguous_locations"\` + \`location_ambiguities[]\` \u2014 pick an id and re-call with \`city_id\`.
8352
8379
 
8353
- **Place names go through \`city\`, NEVER \`keywords\`.** This includes any geographic token the user names \u2014 cities (\`"Berlin"\`, \`"NYC"\`), states / provinces / regions (\`"Texas"\`, \`"California"\`, \`"Bavaria"\`), countries (\`"France"\`, \`"United States"\`), neighborhoods (\`"Brooklyn"\`, \`"SoHo"\`). The \`/geo/search\` resolver handles all admin levels \u2014 level 4 (state) and level 2 (country) resolve just as well as level 5 (city). If you put \`"Texas"\` in \`keywords\` you get a TEXT-MATCH against company descriptions (\u22480 hits) instead of a real state filter. If a place name resolves ambiguously, surface the choices to the user \u2014 do NOT silently fall back to keyword search or to the unfiltered Monitor view. If \`keywords: ["Texas"]\` returned empty, the next call is \`city: "Texas"\`, not \`keywords: []\`.
8380
+ **Place names go through \`city\`, NEVER \`keywords\`.** Any geographic token the user names \u2014 cities (\`"Berlin"\`), states/regions (\`"Texas"\`, \`"Bavaria"\`), countries (\`"France"\`), neighborhoods (\`"Brooklyn"\`) \u2014 resolves via \`/geo/search\` (all admin levels). A place name in \`keywords\` becomes a TEXT-MATCH against company descriptions (\u22480 hits), not a real filter. If a place resolves ambiguously, surface the choices \u2014 never silently fall back to keyword search or the unfiltered view.
8354
8381
 
8355
- **Pushback exclusion.** Leads with active pushback (\`pushback_status\` set and \`pushback_until > today\`) are excluded from the response. The composite enforces this client-side; \`total_excluded_by_pushback\` in the output reports how many rows were dropped.
8382
+ **Pushback exclusion.** Leads with active pushback (\`pushback_status\` set, \`pushback_until > today\`) are excluded client-side; \`total_excluded_by_pushback\` reports how many rows were dropped.
8356
8383
 
8357
8384
  WHEN TO USE: re-engaging pipeline ("what should I follow up on", "stale leads"), filtering monitored leads by city / sector / recency / action type / liked. The canonical orchestrator is the \`leadbay_followup_check_in\` prompt.
8358
8385
 
@@ -8360,6 +8387,16 @@ WHEN NOT TO USE: for NEW leads \u2014 that's \`leadbay_pull_leads\` (Discover).
8360
8387
 
8361
8388
  **Anti-confusion guardrail.** Iterating \`pull_leads\` pages looking for \`prospecting_actions_count > 0\` or \`notes_count > 0\` rows is the wrong entry point \u2014 the two read different tables. Leads with follow-up history live in \`pull_followups\`.
8362
8389
 
8390
+ **SIGNAL HONESTY \u2014 never infer signals from freshness.** \`stale_at\`,
8391
+ \`web_fetch_in_progress\`, \`fetch_at\` are freshness markers, not signal
8392
+ indicators \u2014 signal presence is read ONLY from the actual \`signals[]\` /
8393
+ \`web_fetch.content\` entries. For "which of my leads have signal X" across a
8394
+ portfolio, call **\`leadbay_scan_portfolio_signals\`** (bulk-reads cached
8395
+ signals); don't loop \`leadbay_research_lead_by_id\` per lead or guess from
8396
+ freshness. A lead with no cached content is \`not_researched\`, not "no match";
8397
+ never report a signal verdict for a lead you never read.
8398
+
8399
+
8363
8400
  ---
8364
8401
 
8365
8402
  ## RENDERING \u2014 follow-ups table, status-badge driven
@@ -8446,27 +8483,19 @@ When the response carries \`social_urls\` (the post-fix multi-platform URL block
8446
8483
 
8447
8484
  ## NEXT STEPS \u2014 after the follow-ups table
8448
8485
 
8449
- **RENDER NEXT STEPS via \`ask_user_input_v0\` when the host exposes it.**
8486
+ **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.
8450
8487
 
8451
- The (Observation, Suggest, Calls) table below is the source of truth for which moves are valid. Pick the 2\u20134 most relevant rows based on what the response actually contains, then surface them as a \`single_select\` quick-select widget:
8488
+ **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.
8452
8489
 
8453
- \`\`\`
8454
- ask_user_input_v0({
8455
- questions: [{
8456
- question: "What next?",
8457
- type: "single_select",
8458
- options: [
8459
- "<Suggest column from row 1>",
8460
- "<Suggest column from row 2>",
8461
- "<Suggest column from row 3>"
8462
- ]
8463
- }]
8464
- })
8465
- \`\`\`
8490
+ **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.
8491
+ - Skip example: "Show me today's leads and then research the top one for me." \u2192 after research completes, emit STOP without the widget.
8492
+ - 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.
8466
8493
 
8467
- When the user picks an option, you call the matching tool from the \`Calls\` column. Constraints carried over from the widget contract: 2\u20134 mutually-exclusive options per question, button-sized labels (\u22646 words), max 3 questions per call.
8494
+ 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):
8495
+ - \`ask_user_input_v0\`: \`{questions:[{question,type:"single_select",options:["<Suggest 1>","<Suggest 2>"]}]}\`
8496
+ - \`AskUserQuestion\`: \`{questions:[{question,header:"Next step",multiSelect:false,options:[{label:"<\u22645 words>",description:"<Suggest 1>"}]}]}\`
8468
8497
 
8469
- **Fallback prose mode** \u2014 when the host doesn't expose \`ask_user_input_v0\` (or it returned an error): surface the same 2\u20133 picks as a short bulleted list of "Suggest" phrasings. The table itself stays internal; never recite the whole table to the user.
8498
+ 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.
8470
8499
 
8471
8500
  ---
8472
8501
 
@@ -8487,7 +8516,6 @@ Always include at least one filter-modification offer (users think in filters: b
8487
8516
  | User wants to defer a lead | "Snooze [Company] for 3 / 6 / 12 months" | leadbay_set_pushback({ lead_ids:[leadId], status:"3" }) |
8488
8517
  | User completed outreach mid-flow | "Log the outreach + record the outcome" | leadbay_report_outreach |
8489
8518
  | Discovery mode might fit better | "Looking for NEW leads instead? Switch to discovery." | leadbay_pull_leads |
8490
-
8491
8519
  Always offer at least one of: prep outreach, refilter, pushback. Pushback is the canonical way to honor "not now" / "next quarter" \u2014 leads with active pushback are excluded from this view until expiry.
8492
8520
  `;
8493
8521
  var leadbay_pull_leads = `## WHEN TO USE
@@ -8614,27 +8642,19 @@ When the response carries \`social_urls\` (the post-fix multi-platform URL block
8614
8642
 
8615
8643
  ## NEXT STEPS \u2014 after rendering the pull_leads table
8616
8644
 
8617
- **RENDER NEXT STEPS via \`ask_user_input_v0\` when the host exposes it.**
8645
+ **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.
8618
8646
 
8619
- The (Observation, Suggest, Calls) table below is the source of truth for which moves are valid. Pick the 2\u20134 most relevant rows based on what the response actually contains, then surface them as a \`single_select\` quick-select widget:
8647
+ **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.
8620
8648
 
8621
- \`\`\`
8622
- ask_user_input_v0({
8623
- questions: [{
8624
- question: "What next?",
8625
- type: "single_select",
8626
- options: [
8627
- "<Suggest column from row 1>",
8628
- "<Suggest column from row 2>",
8629
- "<Suggest column from row 3>"
8630
- ]
8631
- }]
8632
- })
8633
- \`\`\`
8649
+ **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.
8650
+ - Skip example: "Show me today's leads and then research the top one for me." \u2192 after research completes, emit STOP without the widget.
8651
+ - 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.
8634
8652
 
8635
- When the user picks an option, you call the matching tool from the \`Calls\` column. Constraints carried over from the widget contract: 2\u20134 mutually-exclusive options per question, button-sized labels (\u22646 words), max 3 questions per call.
8653
+ 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):
8654
+ - \`ask_user_input_v0\`: \`{questions:[{question,type:"single_select",options:["<Suggest 1>","<Suggest 2>"]}]}\`
8655
+ - \`AskUserQuestion\`: \`{questions:[{question,header:"Next step",multiSelect:false,options:[{label:"<\u22645 words>",description:"<Suggest 1>"}]}]}\`
8636
8656
 
8637
- **Fallback prose mode** \u2014 when the host doesn't expose \`ask_user_input_v0\` (or it returned an error): surface the same 2\u20133 picks as a short bulleted list of "Suggest" phrasings. The table itself stays internal; never recite the whole table to the user.
8657
+ 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.
8638
8658
 
8639
8659
  ---
8640
8660
 
@@ -8644,6 +8664,7 @@ Pick 2\u20133 items below based on what was actually observed in the response. T
8644
8664
 
8645
8665
  | Observation | Suggest | Calls |
8646
8666
  |------------------------------------------------------------|--------------------------------------------------------------|--------------------------------------------------------|
8667
+ | \u2265 5 leads returned (any batch) | "Build an interactive lead triage board for this batch" | emit antArtifact from data in hand (do NOT re-call leadbay_pull_leads) |
8647
8668
  | \`has_more == true\` | "Pull the next page (page N+1 of M)" | leadbay_pull_leads(page = current + 1, lensId = pinned)|
8648
8669
  | \u2265 3 rows have \`qualification_summary.answered == 0\` | "Deepen AI qualification on the rows without \u2756 caps" | leadbay_bulk_qualify_leads(leadIds=[\u2026]) |
8649
8670
  | User points at a single row | "Research [Company] in depth" | leadbay_research_lead_by_id(leadId) |
@@ -8654,7 +8675,7 @@ Pick 2\u20133 items below based on what was actually observed in the response. T
8654
8675
  | Top row has contacts but no phone/email | "Order contact enrichment to surface email/phone first" | leadbay_enrich_titles(...) or leadbay_prepare_outreach(leadId, enrich:true) |
8655
8676
  | \`computing_scores == true\` or \`computing_wishlist == true\` | "Scores are still being computed \u2014 re-pull in ~30s" | leadbay_pull_leads (retry with same lensId) |
8656
8677
  | User wants a narrower / wider audience | "Adjust the lens filters (sector / size)" | leadbay_adjust_audience(...) |
8657
-
8678
+ | Phase 4 research was run (\`research_lead_by_id\` called) AND top contacts lack direct email/phone | "Enrich contacts on [Lead1], [Lead2] to get direct emails and phone numbers" | leadbay_enrich_contacts(leadId, contactId) \u2014 ONE call per contact (the tool takes a single leadId + contactId, never a list) |
8658
8679
  If nothing in the menu applies cleanly, suggest only "pull next page" and "research a specific lead in depth" \u2014 never invent a tool that doesn't exist.
8659
8680
  `;
8660
8681
  var leadbay_qualify_lead = `Trigger AI qualification for a single lead (web fetch + AI rescore). The operation is asynchronous \u2014 results take ~60s. \`forceFetch:true\` re-runs even if recent data exists.
@@ -8711,6 +8732,43 @@ WHEN NOT TO USE: to answer a pending clarification \u2014 that's leadbay_answer_
8711
8732
 
8712
8733
  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\`.
8713
8734
  `;
8735
+ var leadbay_remove_contact = `## WHEN TO USE
8736
+
8737
+ Trigger phrases: "remove this contact", "delete this contact", "take this person off the company", "that contact is wrong \u2014 get rid of it", "undo the contact I just added".
8738
+
8739
+ **Memory:** recall + capture via \`leadbay_agent_memory_*\` tools.
8740
+
8741
+ Do NOT use for: "add a contact to this company" \u2192 \`leadbay_add_contact\`; "stop showing me this lead / not interested" \u2192 \`leadbay_dislike_lead\`.
8742
+
8743
+ Prefer when: user wants a specific PERSON gone from a company \u2014 pass that contact's own \`contact_id\` (from a contacts list), not the lead id
8744
+
8745
+ Examples that SHOULD invoke this tool:
8746
+ - "Remove Jane Doe from that company \u2014 I added her by mistake."
8747
+ - "Delete this contact, it's the wrong person."
8748
+ - "Undo the contact I just added to Acme."
8749
+
8750
+ Examples that should NOT invoke this tool (sound similar, route elsewhere):
8751
+ - "Stop showing me this lead."
8752
+ - "Add a contact to this company."
8753
+ - "Show me today's leads."
8754
+
8755
+ ## RENDER (quick)
8756
+
8757
+ One-line confirmation: name the contact (or id) and that it was removed
8758
+ from the company. No table.
8759
+
8760
+ ---
8761
+
8762
+ Remove a single contact from a company by archiving it. This is the **undo** for the add-a-contact path (\`leadbay_add_contact\`) \u2014 when a rep adds the wrong person, or finds a stale contact, this takes them off the company.
8763
+
8764
+ Pass the contact's **own** \`contact_id\` \u2014 the \`id\` field on a contact object returned by \`leadbay_research_lead_by_id\` or the contacts list. **Not** the parent lead id; the archive endpoint is keyed by the contact directly.
8765
+
8766
+ Backend: \`POST /contacts/{contact_id}/archive\` \u2192 204. Archive is a **soft-delete** \u2014 the contact leaves the company's active contact list (the same action the Leadbay web UI's contact "delete" fires). Idempotent: archiving an already-archived contact is a no-op.
8767
+
8768
+ Returns \`{ archived: true, contact_id, action: "archived" }\`.
8769
+
8770
+ Requires: LEADBAY_MCP_WRITE=1 (MCP) or exposeWrite=true (OpenClaw).
8771
+ `;
8714
8772
  var leadbay_remove_epilogue = `Bulk-clear the epilogue status from a set of leads.
8715
8773
 
8716
8774
  WHEN TO USE: when an outreach action was logged in error and needs to be undone.
@@ -8839,7 +8897,7 @@ Trigger phrases: "tell me about this lead", "deep dive on the lead I just picked
8839
8897
 
8840
8898
  **Memory:** recall + capture via \`leadbay_agent_memory_*\` tools.
8841
8899
 
8842
- Do NOT use for: "company name without lead id" \u2192 \`leadbay_research_lead_by_name_fuzzy\`; "draft outreach for <Contact>" \u2192 \`leadbay_prepare_outreach\`.
8900
+ Do NOT use for: "company name without lead id" \u2192 \`leadbay_research_lead_by_name_fuzzy\`; "draft outreach for <Contact>" \u2192 \`leadbay_prepare_outreach\`; "add a contact to this company" \u2192 \`leadbay_add_contact\`.
8843
8901
 
8844
8902
  Prefer when: user picked a row and you have its UUID; pass \`leadId\`
8845
8903
 
@@ -8854,42 +8912,46 @@ Examples that should NOT invoke this tool (sound similar, route elsewhere):
8854
8912
  ---
8855
8913
 
8856
8914
  Tell me everything decision-relevant about a single lead, identified by its
8857
- Leadbay UUID. Bundles the lens-scoped lead profile, the AI qualification
8858
- answers (the agent's knowledge-base food), the structured web-research signals
8859
- (with hot flags + sources), the two-tier contact set (\`enriched\` + \`org\`), the
8860
- unified \`recent_activities\` timeline, the engagement counts, and a
8861
- \`_meta.has_reachable_contact\` hint that drives NEXT STEPS. Order is
8862
- deliberate: qualification first, then signals, then firmographics, then
8863
- contacts, then recent activity.
8864
-
8865
- Scoring has two layers: the basic \`score\` (firmographic, always present,
8866
- already decent) and the AI qualification layer (\`ai_agent_lead_score\` +
8867
- per-question answers + web_fetch signals). The AI layer is pre-populated for
8868
- roughly the top 10 of each daily batch, and on-demand (via
8869
- leadbay_bulk_qualify_leads) for anything below that. Combine both layers when
8870
- judging a lead.
8871
-
8872
- The companion tool **leadbay_research_lead_by_name_fuzzy** wraps this one for
8873
- the case where the user names a company in prose without a UUID \u2014 it
8874
- fuzzy-resolves the name against the active lens's wishlist, then delegates
8875
- here. Both return the same shape; the fuzzy wrapper just adds
8876
- \`_meta.resolved_from\` and \`_meta.match_candidates\` so you can offer
8877
- disambiguation.
8915
+ Leadbay UUID. Bundles the lens-scoped profile, AI qualification answers,
8916
+ structured web-research signals (hot flags + sources), the two-tier contact set
8917
+ (\`enriched\` + \`org\`), the unified \`recent_activities\` timeline, engagement
8918
+ counts, and a \`_meta.has_reachable_contact\` hint that drives NEXT STEPS. Order
8919
+ is deliberate: qualification, signals, firmographics, contacts, recent activity.
8920
+
8921
+ Scoring has two layers: the basic \`score\` (firmographic, always present) and
8922
+ the AI qualification layer (\`ai_agent_lead_score\` + per-question answers +
8923
+ web_fetch signals). The AI layer is pre-populated for roughly the top 10 of
8924
+ each daily batch, and on-demand (via leadbay_bulk_qualify_leads) below that.
8925
+ Combine both when judging a lead.
8926
+
8927
+ The companion **leadbay_research_lead_by_name_fuzzy** wraps this one when the
8928
+ user names a company without a UUID: it fuzzy-resolves against the active
8929
+ lens's wishlist, then delegates here. Same shape, plus \`_meta.resolved_from\` /
8930
+ \`_meta.match_candidates\`.
8878
8931
 
8879
8932
  WHEN TO USE: when picking up a single lead from
8880
8933
  leadbay_pull_leads (or any list that exposed a leadId) to decide whether to
8881
8934
  act on it.
8882
8935
 
8883
8936
  WHEN NOT TO USE: across many leads at once \u2014 that's
8884
- leadbay_pull_leads' job. (This composite supersedes the lower-level
8885
- leadbay_get_lead_profile in agent flow; the granular tool stays available for
8886
- fine-grained access.)
8887
-
8888
- **Concurrency note**: this is a composite that reads many sub-resources per
8889
- call. Call it **sequentially** or in small batches (\u22643 parallel) when
8890
- researching multiple leads. Firing 10+ in parallel can saturate the transport
8891
- and produce misleading \`"Tool permission stream closed"\` errors that look like
8892
- permission failures but are really backpressure. On a transient
8937
+ leadbay_pull_leads' job (portfolio-wide signal questions go to
8938
+ leadbay_scan_portfolio_signals; see below). This composite supersedes the
8939
+ lower-level leadbay_get_lead_profile.
8940
+
8941
+ **SIGNAL HONESTY \u2014 never infer signals from freshness.** \`stale_at\`,
8942
+ \`web_fetch_in_progress\`, \`fetch_at\` are freshness markers, not signal
8943
+ indicators \u2014 signal presence is read ONLY from the actual \`signals[]\` /
8944
+ \`web_fetch.content\` entries. For "which of my leads have signal X" across a
8945
+ portfolio, call **\`leadbay_scan_portfolio_signals\`** (bulk-reads cached
8946
+ signals); don't loop \`leadbay_research_lead_by_id\` per lead or guess from
8947
+ freshness. A lead with no cached content is \`not_researched\`, not "no match";
8948
+ never report a signal verdict for a lead you never read.
8949
+
8950
+
8951
+ **Concurrency note**: this composite reads many sub-resources per call. Call
8952
+ it **sequentially or in small batches (\u22643 parallel)**. Firing 10+ in parallel
8953
+ saturates the transport and produces misleading \`"Tool permission stream
8954
+ closed"\` errors \u2014 that's backpressure, not a permission failure. On a transient
8893
8955
  stream/timeout failure, retry the same lead once before moving on.
8894
8956
 
8895
8957
  ---
@@ -8968,27 +9030,19 @@ When the response carries \`social_urls\` (the post-fix multi-platform URL block
8968
9030
 
8969
9031
  ## NEXT STEPS \u2014 after the research card
8970
9032
 
8971
- **RENDER NEXT STEPS via \`ask_user_input_v0\` when the host exposes it.**
9033
+ **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.
8972
9034
 
8973
- The (Observation, Suggest, Calls) table below is the source of truth for which moves are valid. Pick the 2\u20134 most relevant rows based on what the response actually contains, then surface them as a \`single_select\` quick-select widget:
9035
+ **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.
8974
9036
 
8975
- \`\`\`
8976
- ask_user_input_v0({
8977
- questions: [{
8978
- question: "What next?",
8979
- type: "single_select",
8980
- options: [
8981
- "<Suggest column from row 1>",
8982
- "<Suggest column from row 2>",
8983
- "<Suggest column from row 3>"
8984
- ]
8985
- }]
8986
- })
8987
- \`\`\`
9037
+ **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.
9038
+ - Skip example: "Show me today's leads and then research the top one for me." \u2192 after research completes, emit STOP without the widget.
9039
+ - 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.
8988
9040
 
8989
- When the user picks an option, you call the matching tool from the \`Calls\` column. Constraints carried over from the widget contract: 2\u20134 mutually-exclusive options per question, button-sized labels (\u22646 words), max 3 questions per call.
9041
+ 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):
9042
+ - \`ask_user_input_v0\`: \`{questions:[{question,type:"single_select",options:["<Suggest 1>","<Suggest 2>"]}]}\`
9043
+ - \`AskUserQuestion\`: \`{questions:[{question,header:"Next step",multiSelect:false,options:[{label:"<\u22645 words>",description:"<Suggest 1>"}]}]}\`
8990
9044
 
8991
- **Fallback prose mode** \u2014 when the host doesn't expose \`ask_user_input_v0\` (or it returned an error): surface the same 2\u20133 picks as a short bulleted list of "Suggest" phrasings. The table itself stays internal; never recite the whole table to the user.
9045
+ 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.
8992
9046
 
8993
9047
  ---
8994
9048
 
@@ -9033,6 +9087,7 @@ out?"\`
9033
9087
 
9034
9088
  | Observation | Suggest | Calls |
9035
9089
  |--------------------------------------------------------|----------------------------------------------------------|----------------------------------------------------------------|
9090
+ | Lead is clearly not a fit (wrong industry, too small) | "Dislike this lead" | leadbay_dislike_lead({ leadId }) |
9036
9091
  | User is done with this lead | "Back to the inbox" | leadbay_pull_leads |
9037
9092
  `;
9038
9093
  var leadbay_research_lead_by_name_fuzzy = `## WHEN TO USE
@@ -9156,27 +9211,19 @@ When the response carries \`social_urls\` (the post-fix multi-platform URL block
9156
9211
 
9157
9212
  ## NEXT STEPS \u2014 after the research card
9158
9213
 
9159
- **RENDER NEXT STEPS via \`ask_user_input_v0\` when the host exposes it.**
9214
+ **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.
9160
9215
 
9161
- The (Observation, Suggest, Calls) table below is the source of truth for which moves are valid. Pick the 2\u20134 most relevant rows based on what the response actually contains, then surface them as a \`single_select\` quick-select widget:
9216
+ **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.
9162
9217
 
9163
- \`\`\`
9164
- ask_user_input_v0({
9165
- questions: [{
9166
- question: "What next?",
9167
- type: "single_select",
9168
- options: [
9169
- "<Suggest column from row 1>",
9170
- "<Suggest column from row 2>",
9171
- "<Suggest column from row 3>"
9172
- ]
9173
- }]
9174
- })
9175
- \`\`\`
9218
+ **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.
9219
+ - Skip example: "Show me today's leads and then research the top one for me." \u2192 after research completes, emit STOP without the widget.
9220
+ - 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.
9176
9221
 
9177
- When the user picks an option, you call the matching tool from the \`Calls\` column. Constraints carried over from the widget contract: 2\u20134 mutually-exclusive options per question, button-sized labels (\u22646 words), max 3 questions per call.
9222
+ 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):
9223
+ - \`ask_user_input_v0\`: \`{questions:[{question,type:"single_select",options:["<Suggest 1>","<Suggest 2>"]}]}\`
9224
+ - \`AskUserQuestion\`: \`{questions:[{question,header:"Next step",multiSelect:false,options:[{label:"<\u22645 words>",description:"<Suggest 1>"}]}]}\`
9178
9225
 
9179
- **Fallback prose mode** \u2014 when the host doesn't expose \`ask_user_input_v0\` (or it returned an error): surface the same 2\u20133 picks as a short bulleted list of "Suggest" phrasings. The table itself stays internal; never recite the whole table to the user.
9226
+ 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.
9180
9227
 
9181
9228
  ---
9182
9229
 
@@ -9221,6 +9268,7 @@ out?"\`
9221
9268
 
9222
9269
  | Observation | Suggest | Calls |
9223
9270
  |--------------------------------------------------------|----------------------------------------------------------|----------------------------------------------------------------|
9271
+ | Lead is clearly not a fit (wrong industry, too small) | "Dislike this lead" | leadbay_dislike_lead({ leadId }) |
9224
9272
  | User is done with this lead | "Back to the inbox" | leadbay_pull_leads |
9225
9273
 
9226
9274
 
@@ -9268,6 +9316,178 @@ Below the table, a one-liner: \`"Ready: K rows \xB7 Ambiguous: A rows \xB7 Unmat
9268
9316
  | Unmatched rows but websites present | "Import anyway \u2014 Leadbay will crawl and match later" | leadbay_import_leads (status check after) |
9269
9317
  | User wants to skip rows they can't ID | "Drop unmatched rows and import the rest" | leadbay_import_leads (with filtered records) |
9270
9318
  `;
9319
+ var leadbay_scan_portfolio_signals = `## WHEN TO USE
9320
+
9321
+ 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>".
9322
+
9323
+ **Memory:** recall + capture via \`leadbay_agent_memory_*\` tools.
9324
+
9325
+ 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\`.
9326
+
9327
+ 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\`
9328
+
9329
+ Examples that SHOULD invoke this tool:
9330
+ - "Which of my leads acquired a company since 2025?"
9331
+ - "Scan my Lyon portfolio for funding signals."
9332
+ - "Find everyone in Monitor who changed CEO and build a campaign."
9333
+
9334
+ Examples that should NOT invoke this tool (sound similar, route elsewhere):
9335
+ - "Look up Acme Corp for me."
9336
+ - "Show me my follow-ups."
9337
+ - "Qualify my next 10 leads."
9338
+
9339
+ ## RENDER (quick)
9340
+
9341
+ Cohort grouped by lead: one block per matched lead (name \xB7 location +
9342
+ its matched signal entries, hot first, source-linked). Open with
9343
+ "N match <query> (M scanned)"; ALWAYS close with an honesty footer \u2014
9344
+ "scanned N \xB7 matched M \xB7 K not yet researched". Never present
9345
+ not_researched leads as "no signal". Full layout below.
9346
+
9347
+ ---
9348
+
9349
+ Scan a known portfolio for a specific web-research signal in one call. This is
9350
+ the bulk, read-only answer to "which of my leads have signal X" \u2014 the question
9351
+ that otherwise forces a per-lead \`leadbay_research_lead_by_id\` loop (one full
9352
+ profile call per lead, slow and quota-heavy).
9353
+
9354
+ **Reads CACHED signals only \u2014 does not trigger new research.** For each lead in
9355
+ scope it reads \`GET /leads/{id}/web_fetch\` (the already-computed web-research
9356
+ signals) and filters the entries against \`query\`. It issues NO web_fetch POST,
9357
+ so it does not consume AI qualification credits and does not re-crawl. Leads
9358
+ that have no cached content (never qualified, or still in progress) are
9359
+ reported in \`not_researched\` \u2014 they are **NOT** silently treated as "no
9360
+ match". Qualify them with \`leadbay_bulk_qualify_leads\`, then re-scan.
9361
+
9362
+ **Scope.** Pass \`leadIds\` for an explicit cohort, or omit it to scan the
9363
+ Monitor portfolio. Narrow the Monitor scope with \`city\` / \`set_filter\` exactly
9364
+ as \`leadbay_pull_followups\` does (store-then-apply server-side filter). The
9365
+ scan is bounded by \`max_leads\` (default 200, hard cap 300); when the portfolio
9366
+ is larger, \`truncated_at\` is set and coverage is partial \u2014 say so.
9367
+
9368
+ **Query.** \`query\` is matched case- and accent-insensitively against each
9369
+ signal entry's description, source, and section label. Comma- or
9370
+ space-separated terms are OR'd ("M&A, acquisition, rachet\xE9" matches any). Use
9371
+ \`since\` (ISO date) to keep only entries dated on/after it \u2014 entries with no
9372
+ date are kept (a missing date is not evidence the event is old).
9373
+
9374
+ **Result is campaign-ready.** \`matched[]\` carries \`lead_id\`, \`name\`,
9375
+ \`location\`, and the matching \`matched_signals[]\` (section + hot + source +
9376
+ date + description). Feed the matched \`lead_id\`s straight into
9377
+ \`leadbay_add_leads_to_campaign\` / \`leadbay_create_campaign\`.
9378
+
9379
+ On a 429 mid-scan, partial \`matched\` is returned with \`quota_exceeded: true\` \u2014
9380
+ offer the user wait-for-reset OR a top-up link (both unblock; a top-up clears
9381
+ the throttle immediately).
9382
+
9383
+ **SIGNAL HONESTY \u2014 never infer signals from freshness.** \`stale_at\`,
9384
+ \`web_fetch_in_progress\`, \`fetch_at\` are freshness markers, not signal
9385
+ indicators \u2014 signal presence is read ONLY from the actual \`signals[]\` /
9386
+ \`web_fetch.content\` entries. For "which of my leads have signal X" across a
9387
+ portfolio, call **\`leadbay_scan_portfolio_signals\`** (bulk-reads cached
9388
+ signals); don't loop \`leadbay_research_lead_by_id\` per lead or guess from
9389
+ freshness. A lead with no cached content is \`not_researched\`, not "no match";
9390
+ never report a signal verdict for a lead you never read.
9391
+
9392
+
9393
+ WHEN TO USE: when the user wants to filter a known
9394
+ portfolio by a web-research signal across many leads at once \u2014 discovering a
9395
+ cohort to act on, not inspecting a single lead.
9396
+
9397
+ WHEN NOT TO USE: for a single named company
9398
+ (leadbay_research_lead_by_name_fuzzy) or one lead by UUID
9399
+ (leadbay_research_lead_by_id); to qualify leads that have no signals yet
9400
+ (leadbay_bulk_qualify_leads); or to just list follow-ups with no signal filter
9401
+ (leadbay_pull_followups).
9402
+
9403
+ ---
9404
+
9405
+ ## RENDERING \u2014 bulk signal-scan results
9406
+
9407
+ The output is a cohort, grouped by lead. Lead with the matches, end with an
9408
+ honesty footer \u2014 never hide what wasn't scanned.
9409
+
9410
+ ### Matched leads
9411
+
9412
+ Open with a one-line headline: \`**N leads match "<query>"** (M scanned).\`
9413
+
9414
+ Then one block per \`matched[]\` lead, ordered with \`hot\` matches first. Emit
9415
+ each as a host-parseable per-lead block so the chat host's place-card
9416
+ auto-detector can render it (per the repo "feed the address auto-detector"
9417
+ convention):
9418
+
9419
+ \`\`\`
9420
+ ### <name> \xB7 <location>
9421
+
9422
+ <for each matched_signal, one bullet>
9423
+ - **<section_emoji> <section_label>** \u2014 <description> <\u{1F525} if hot> ([source](<source>), <date>)
9424
+ \`\`\`
9425
+
9426
+ - **Bold** the description of \`hot: true\` entries; leave cold entries plain.
9427
+ - Render \`source\` as a markdown link \`([source](url), date)\`; omit the date
9428
+ when null, omit the link when \`source\` is empty.
9429
+ - Cap to the 3 strongest signals per lead (hot first, then by date desc); if a
9430
+ lead has more, end its block with \`_+K more signals_\`.
9431
+ - When \`name\` is null (the scan was scoped by \`leadIds\` and the read failed to
9432
+ carry firmographics), fall back to \`### Lead <lead_id>\` \u2014 but prefer to enrich
9433
+ the name via the matched lead's own data when available.
9434
+
9435
+ ### Honesty footer (ALWAYS print)
9436
+
9437
+ A single italic line summarising coverage:
9438
+
9439
+ \`_Scanned N \xB7 matched M \xB7 K had no cached signals (not yet researched)._\`
9440
+
9441
+ - When \`not_researched\` is non-empty, this is load-bearing: state plainly that
9442
+ those K leads were NOT searched and were NOT counted as "no match". Offer to
9443
+ qualify them and re-scan (see NEXT STEPS).
9444
+ - When \`truncated_at\` is set, add: \`_Coverage partial \u2014 only the first <truncated_at>
9445
+ leads were scanned; narrow the scope or raise max_leads._\`
9446
+ - When \`quota_exceeded\` is true, add the wait-or-top-up offer.
9447
+
9448
+ **Hide:** raw \`lead_id\` in prose (use it only for the campaign call), \`_meta\`,
9449
+ empty arrays, any freshness field. NEVER present \`not_researched\` leads as
9450
+ "no signal found".
9451
+
9452
+
9453
+ ---
9454
+
9455
+ ## NEXT STEPS \u2014 after the signal scan
9456
+
9457
+ **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.
9458
+
9459
+ **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.
9460
+
9461
+ **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.
9462
+ - Skip example: "Show me today's leads and then research the top one for me." \u2192 after research completes, emit STOP without the widget.
9463
+ - 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.
9464
+
9465
+ 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):
9466
+ - \`ask_user_input_v0\`: \`{questions:[{question,type:"single_select",options:["<Suggest 1>","<Suggest 2>"]}]}\`
9467
+ - \`AskUserQuestion\`: \`{questions:[{question,header:"Next step",multiSelect:false,options:[{label:"<\u22645 words>",description:"<Suggest 1>"}]}]}\`
9468
+
9469
+ 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.
9470
+
9471
+ ---
9472
+
9473
+
9474
+
9475
+ The scan exists to BUILD A COHORT, not just to list. The default next move is
9476
+ almost always "turn the matched leads into a campaign."
9477
+
9478
+ | Observation | Suggest | Calls |
9479
+ |---------------------------------------------------|--------------------------------------------------------------|----------------------------------------------------------------------------------------|
9480
+ | \`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) |
9481
+ | \`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 |
9482
+ | Zero matches but leads were researched | "Widen the query (synonyms) or relax \`since\`" | leadbay_scan_portfolio_signals(query: "<broader terms>", since: omit-or-earlier) |
9483
+ | \`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\` |
9484
+ | One standout matched lead | "Open that lead's full brief" | leadbay_research_lead_by_id(leadId) |
9485
+ | \`quota_exceeded\` | "Wait for reset OR top up to finish the scan" | leadbay_create_topup_link |
9486
+
9487
+ NEVER report leads in \`not_researched\` as if they had no matching signal \u2014 they
9488
+ were never read. Distinguish "no signal X found" (researched, no match) from
9489
+ "not yet researched" (no data to search) every time.
9490
+ `;
9271
9491
  var leadbay_seed_candidates = `## WHEN TO USE
9272
9492
 
9273
9493
  Trigger phrases: "(internal) agent decided to extend the lens \u2014 fetch seed candidates".
@@ -9440,7 +9660,7 @@ Modern chat hosts (Claude, ChatGPT) expose first-party widgets the agent can rou
9440
9660
  |---|---|---|
9441
9661
  | \`places_map_display_v0\` (Claude) | Result has \u22652 leads with \`location.city\` set, and the user's intent is geographic / "in person" / travel | \`{name: lead.company_name, address: "<city>, <country>", place_id: lead.location.place_id ?? omit, notes: <one-sentence pitch>}\` per location |
9442
9662
  | \`message_compose_v1\` (Claude) | You're about to draft outreach (email / message / call opener) | \`{kind: "email", summary_title, variants: [{label, body, subject}]}\` \u2014 2\u20133 variants, labels describe STRATEGY ("Push for alignment", "Reference the M&A signal"), not tone ("Friendly", "Formal") |
9443
- | \`ask_user_input_v0\` (Claude) | The tool's NEXT STEPS block has 2\u20134 mutually-exclusive next moves and the user hasn't already chosen | \`{questions: [{question: "What next?", type: "single_select", options: [<2-4 short button labels>]}]}\`; max 3 questions per call |
9663
+ | \`ask_user_input_v0\` (Claude chat / ChatGPT) **or** \`AskUserQuestion\` (Claude cowork / Claude Code) \u2014 whichever is in your tool set; their schemas differ, match the one you have | The tool's NEXT STEPS block has 2\u20134 mutually-exclusive next moves and the user hasn't already chosen | Per-tool schema in the server instructions + NEXT STEPS routing block. Max 3 questions. |
9444
9664
 
9445
9665
  ChatGPT exposes the same routing pattern via \`_meta.openai/outputTemplate\`. We don't ship any custom widgets ourselves \u2014 this gate is exclusively about routing into the host's first-party widgets when the data shape fits.
9446
9666
 
@@ -9458,6 +9678,83 @@ WHEN TO USE: the user signals a *mixed* tour-planning intent \u2014 they want bo
9458
9678
  WHEN NOT TO USE: if the user only wants follow-ups (use \`leadbay_followups_map\`), only wants new leads (use \`leadbay_pull_leads\`), wants research on one specific account (\`leadbay_research_lead_by_id\`), or wants to persist the tour as a campaign artifact (chain into \`leadbay_create_campaign\` after this).
9459
9679
 
9460
9680
  **Response envelope**: \`{city, city_id, monitor_leads, discover_leads, discover_filter_note, _meta}\` on happy path; \`{status: "ambiguous_locations", location_ambiguities, ...}\` when the passed \`city\` matched multiple admin areas.
9681
+
9682
+ ---
9683
+ `;
9684
+ var leadbay_unpin_contact = `## WHEN TO USE
9685
+
9686
+ Trigger phrases: "unpin this contact", "remove the pin from this contact", "this person isn't the priority anymore", "unfavourite this contact".
9687
+
9688
+ **Memory:** recall + capture via \`leadbay_agent_memory_*\` tools.
9689
+
9690
+ Do NOT use for: "pin / mark as priority" \u2192 \`leadbay_pin_contact\`; "remove / delete this contact" \u2192 \`leadbay_remove_contact\`.
9691
+
9692
+ Prefer when: user wants to clear the pinned flag on a contact (but keep the contact) \u2014 pass that contact's own \`contact_id\`
9693
+
9694
+ Examples that SHOULD invoke this tool:
9695
+ - "Unpin Jane Doe \u2014 she's not the priority anymore."
9696
+ - "Remove the pin from that contact."
9697
+ - "Unfavourite this person."
9698
+
9699
+ Examples that should NOT invoke this tool (sound similar, route elsewhere):
9700
+ - "Pin this contact as priority."
9701
+ - "Remove that contact entirely."
9702
+ - "Add a new contact to this company."
9703
+
9704
+ ## RENDER (quick)
9705
+
9706
+ One-line confirmation that the named contact (or id) is no longer pinned.
9707
+ No table.
9708
+
9709
+ ---
9710
+
9711
+ Unpin a single contact on a company \u2014 clears its priority / favourite flag. The contact stays on the company; only the pin is removed (to remove the contact entirely, use \`leadbay_remove_contact\`).
9712
+
9713
+ Pass the contact's **own** \`contact_id\` \u2014 not the parent lead id.
9714
+
9715
+ Backend: \`POST /contacts/{contact_id}/unpin\` \u2192 204. Idempotent. The inverse is \`leadbay_pin_contact\`.
9716
+
9717
+ Returns \`{ pinned: false, contact_id, action: "unpinned" }\`.
9718
+
9719
+ Requires: LEADBAY_MCP_WRITE=1 (MCP) or exposeWrite=true (OpenClaw).
9720
+ `;
9721
+ var leadbay_update_contact = `## WHEN TO USE
9722
+
9723
+ Trigger phrases: "update this contact", "fix this contact's title", "change their email / phone / LinkedIn", "edit this person's details", "correct the contact's name".
9724
+
9725
+ **Memory:** recall + capture via \`leadbay_agent_memory_*\` tools.
9726
+
9727
+ Do NOT use for: "add a new contact to this company" \u2192 \`leadbay_add_contact\`; "remove / delete this contact" \u2192 \`leadbay_remove_contact\`; "get email/phone for a contact (enrichment)" \u2192 \`leadbay_enrich_titles\`.
9728
+
9729
+ Prefer when: user wants to change details on an EXISTING contact \u2014 pass that contact's own \`contact_id\` plus first_name + last_name (required) and the fields to change
9730
+
9731
+ Examples that SHOULD invoke this tool:
9732
+ - "Update Jane's title to SVP Engineering."
9733
+ - "Fix this contact's LinkedIn URL."
9734
+ - "Change John's email to john@acme.com."
9735
+
9736
+ Examples that should NOT invoke this tool (sound similar, route elsewhere):
9737
+ - "Add a new contact to this company."
9738
+ - "Remove that contact, wrong person."
9739
+ - "Get me the email for this contact."
9740
+
9741
+ ## RENDER (quick)
9742
+
9743
+ One-line confirmation naming the contact and what changed. No table.
9744
+
9745
+ ---
9746
+
9747
+ Edit an existing contact in place \u2014 change their \`job_title\`, \`linkedin_page\`, \`email\`, \`phone_number\`, or name.
9748
+
9749
+ Pass the contact's **own** \`contact_id\` (the \`id\` field from \`leadbay_research_lead_by_id\` or a contacts list) \u2014 **not** the parent lead id.
9750
+
9751
+ **\`first_name\` + \`last_name\` are required even on an edit.** The backend validates the full contact identity and rejects a partial body (\`invalid contact\`). So pass the contact's *current* first/last name even when you're only changing the title \u2014 read the current values via \`leadbay_research_lead_by_id\` first if you don't have them.
9752
+
9753
+ Backend: \`POST /contacts/{contact_id}/update\` (snake_case body) \u2192 200 with the updated contact. Edits in place (same id). Camel-case bodies are rejected.
9754
+
9755
+ Returns \`{ updated: true, contact_id, contact: { id, first_name, last_name, job_title, linkedin_page, email, phone_number } }\`.
9756
+
9757
+ Requires: LEADBAY_MCP_WRITE=1 (MCP) or exposeWrite=true (OpenClaw).
9461
9758
  `;
9462
9759
  var leadbay_update_lens = `Update lens metadata (name, description, mode flags). Does NOT change the audience filter \u2014 use leadbay_update_lens_filter for that.
9463
9760
 
@@ -13493,6 +13790,215 @@ var dislikeLead = {
13493
13790
  }
13494
13791
  };
13495
13792
 
13793
+ // ../core/dist/tools/add-contact.js
13794
+ var addContact = {
13795
+ name: "leadbay_add_contact",
13796
+ description: leadbay_add_contact,
13797
+ write: true,
13798
+ annotations: {
13799
+ title: "Add a contact",
13800
+ readOnlyHint: false,
13801
+ destructiveHint: false,
13802
+ idempotentHint: false,
13803
+ openWorldHint: true
13804
+ },
13805
+ inputSchema: {
13806
+ type: "object",
13807
+ properties: {
13808
+ lead_id: {
13809
+ type: "string",
13810
+ description: "UUID of the parent company (lead) to attach the contact to. The contact is created on this company."
13811
+ },
13812
+ first_name: { type: "string", description: "Contact first name." },
13813
+ last_name: { type: "string", description: "Contact last name." },
13814
+ job_title: { type: "string", description: "Contact job title (optional)." },
13815
+ linkedin_page: {
13816
+ type: "string",
13817
+ description: "Contact LinkedIn profile URL (optional)."
13818
+ },
13819
+ email: { type: "string", description: "Contact email (optional)." },
13820
+ phone_number: {
13821
+ type: "string",
13822
+ description: "Contact phone number (optional, free-form)."
13823
+ }
13824
+ },
13825
+ required: ["lead_id", "first_name", "last_name"],
13826
+ additionalProperties: false
13827
+ },
13828
+ execute: async (client, params, _ctx) => {
13829
+ const body = {
13830
+ first_name: params.first_name,
13831
+ last_name: params.last_name
13832
+ };
13833
+ if (params.job_title != null)
13834
+ body.job_title = params.job_title;
13835
+ if (params.linkedin_page != null)
13836
+ body.linkedin_page = params.linkedin_page;
13837
+ if (params.email != null)
13838
+ body.email = params.email;
13839
+ if (params.phone_number != null)
13840
+ body.phone_number = params.phone_number;
13841
+ const contact = await client.request("POST", `/leads/${params.lead_id}/contacts`, body);
13842
+ return { added: true, lead_id: params.lead_id, contact };
13843
+ }
13844
+ };
13845
+
13846
+ // ../core/dist/tools/remove-contact.js
13847
+ var removeContact = {
13848
+ name: "leadbay_remove_contact",
13849
+ description: leadbay_remove_contact,
13850
+ write: true,
13851
+ annotations: {
13852
+ title: "Remove a contact",
13853
+ readOnlyHint: false,
13854
+ // Soft-delete (archive), but it does remove the contact from the active
13855
+ // list, so flag it destructive so cautious clients can confirm.
13856
+ destructiveHint: true,
13857
+ idempotentHint: true,
13858
+ openWorldHint: true
13859
+ },
13860
+ inputSchema: {
13861
+ type: "object",
13862
+ properties: {
13863
+ contact_id: {
13864
+ type: "string",
13865
+ description: "UUID of the contact to remove (the contact's own `id`, e.g. from leadbay_research_lead_by_id's contacts list \u2014 NOT the parent lead id)."
13866
+ }
13867
+ },
13868
+ required: ["contact_id"],
13869
+ additionalProperties: false
13870
+ },
13871
+ execute: async (client, params, _ctx) => {
13872
+ await client.requestVoid("POST", `/contacts/${params.contact_id}/archive`);
13873
+ return { archived: true, contact_id: params.contact_id, action: "archived" };
13874
+ }
13875
+ };
13876
+
13877
+ // ../core/dist/tools/pin-contact.js
13878
+ var pinContact = {
13879
+ name: "leadbay_pin_contact",
13880
+ description: leadbay_pin_contact,
13881
+ write: true,
13882
+ annotations: {
13883
+ title: "Pin a contact",
13884
+ readOnlyHint: false,
13885
+ destructiveHint: false,
13886
+ idempotentHint: true,
13887
+ openWorldHint: true
13888
+ },
13889
+ inputSchema: {
13890
+ type: "object",
13891
+ properties: {
13892
+ contact_id: {
13893
+ type: "string",
13894
+ description: "UUID of the contact to pin (the contact's own `id` \u2014 NOT the parent lead id)."
13895
+ }
13896
+ },
13897
+ required: ["contact_id"],
13898
+ additionalProperties: false
13899
+ },
13900
+ execute: async (client, params, _ctx) => {
13901
+ await client.requestVoid("POST", `/contacts/${params.contact_id}/pin`);
13902
+ return { pinned: true, contact_id: params.contact_id, action: "pinned" };
13903
+ }
13904
+ };
13905
+
13906
+ // ../core/dist/tools/unpin-contact.js
13907
+ var unpinContact = {
13908
+ name: "leadbay_unpin_contact",
13909
+ description: leadbay_unpin_contact,
13910
+ write: true,
13911
+ annotations: {
13912
+ title: "Unpin a contact",
13913
+ readOnlyHint: false,
13914
+ destructiveHint: false,
13915
+ idempotentHint: true,
13916
+ openWorldHint: true
13917
+ },
13918
+ inputSchema: {
13919
+ type: "object",
13920
+ properties: {
13921
+ contact_id: {
13922
+ type: "string",
13923
+ description: "UUID of the contact to unpin (the contact's own `id` \u2014 NOT the parent lead id)."
13924
+ }
13925
+ },
13926
+ required: ["contact_id"],
13927
+ additionalProperties: false
13928
+ },
13929
+ execute: async (client, params, _ctx) => {
13930
+ await client.requestVoid("POST", `/contacts/${params.contact_id}/unpin`);
13931
+ return { pinned: false, contact_id: params.contact_id, action: "unpinned" };
13932
+ }
13933
+ };
13934
+
13935
+ // ../core/dist/tools/update-contact.js
13936
+ var updateContact = {
13937
+ name: "leadbay_update_contact",
13938
+ description: leadbay_update_contact,
13939
+ write: true,
13940
+ annotations: {
13941
+ title: "Update a contact",
13942
+ readOnlyHint: false,
13943
+ destructiveHint: false,
13944
+ idempotentHint: true,
13945
+ openWorldHint: true
13946
+ },
13947
+ inputSchema: {
13948
+ type: "object",
13949
+ properties: {
13950
+ contact_id: {
13951
+ type: "string",
13952
+ description: "UUID of the contact to edit (the contact's own `id` \u2014 NOT the parent lead id)."
13953
+ },
13954
+ first_name: {
13955
+ type: "string",
13956
+ description: "Contact first name \u2014 REQUIRED even on an edit. Pass the current value if you're not changing it."
13957
+ },
13958
+ last_name: {
13959
+ type: "string",
13960
+ description: "Contact last name \u2014 REQUIRED even on an edit. Pass the current value if you're not changing it."
13961
+ },
13962
+ // Nullable so the agent can CLEAR a field (pass null) as well as set a
13963
+ // new value. execute forwards null verbatim; the backend accepts it.
13964
+ job_title: {
13965
+ type: ["string", "null"],
13966
+ description: "Contact job title. Pass null to clear it."
13967
+ },
13968
+ linkedin_page: {
13969
+ type: ["string", "null"],
13970
+ description: "Contact LinkedIn URL. Pass null to clear it."
13971
+ },
13972
+ email: {
13973
+ type: ["string", "null"],
13974
+ description: "Contact email. Pass null to clear it."
13975
+ },
13976
+ phone_number: {
13977
+ type: ["string", "null"],
13978
+ description: "Contact phone (free-form). Pass null to clear it."
13979
+ }
13980
+ },
13981
+ required: ["contact_id", "first_name", "last_name"],
13982
+ additionalProperties: false
13983
+ },
13984
+ execute: async (client, params, _ctx) => {
13985
+ const body = {
13986
+ first_name: params.first_name,
13987
+ last_name: params.last_name
13988
+ };
13989
+ if (params.job_title !== void 0)
13990
+ body.job_title = params.job_title;
13991
+ if (params.linkedin_page !== void 0)
13992
+ body.linkedin_page = params.linkedin_page;
13993
+ if (params.email !== void 0)
13994
+ body.email = params.email;
13995
+ if (params.phone_number !== void 0)
13996
+ body.phone_number = params.phone_number;
13997
+ const contact = await client.request("POST", `/contacts/${params.contact_id}/update`, body);
13998
+ return { updated: true, contact_id: params.contact_id, contact };
13999
+ }
14000
+ };
14001
+
13496
14002
  // ../core/dist/composite/prepare-outreach.js
13497
14003
  function normalizeLinkedinPage2(v) {
13498
14004
  if (v == null)
@@ -13704,6 +14210,35 @@ function summarise(responses) {
13704
14210
  }
13705
14211
  return { answered, total, avg_qualification_boost: avg, best_response_excerpt: excerpt };
13706
14212
  }
14213
+ function buildPullLeadsNextSteps(args) {
14214
+ const { leadCount, hasMore, nextPage } = args;
14215
+ if (leadCount <= 0)
14216
+ return null;
14217
+ const options = [];
14218
+ options.push({
14219
+ label: "Triage board",
14220
+ description: "Build an interactive lead triage board to sort and filter this batch.",
14221
+ kind: "build_artifact"
14222
+ });
14223
+ options.push({
14224
+ label: "Deepen qualification",
14225
+ description: "Run deeper AI qualification on these leads.",
14226
+ kind: "qualify_deeper"
14227
+ });
14228
+ if (hasMore && nextPage != null) {
14229
+ options.push({
14230
+ label: "Next page",
14231
+ description: `Pull page ${nextPage + 1} of this lens.`,
14232
+ kind: "pull_next_page"
14233
+ });
14234
+ }
14235
+ options.push({
14236
+ label: "Refine audience",
14237
+ description: "Adjust the lens audience / filters (sector, size, prompt).",
14238
+ kind: "refine_audience"
14239
+ });
14240
+ return { question: "What do you want to do next?", options: options.slice(0, 4) };
14241
+ }
13707
14242
  var pullLeads = {
13708
14243
  name: "leadbay_pull_leads",
13709
14244
  annotations: {
@@ -13768,6 +14303,24 @@ var pullLeads = {
13768
14303
  type: "boolean",
13769
14304
  description: "True if scoring is still running."
13770
14305
  },
14306
+ next_steps: {
14307
+ type: ["object", "null"],
14308
+ description: "Ready-made NEXT STEPS for the host's choice widget. Each option has a SHORT `label` (\u22645 words, fits AskUserQuestion's label cap on Claude cowork/Claude Code) and a full `description`. For AskUserQuestion (cowork/Claude Code) pass each option as {label, description}. For ask_user_input_v0 (Claude chat/ChatGPT, string-only options) use the `description` as the option string. Use these VERBATIM, in order \u2014 do NOT re-derive, reword, or render as prose when a widget tool exists. options[0] is the artifact offer (build the lead triage board) whenever the batch is non-empty. null only when the batch is empty.",
14309
+ properties: {
14310
+ question: { type: "string" },
14311
+ options: {
14312
+ type: "array",
14313
+ items: {
14314
+ type: "object",
14315
+ properties: {
14316
+ label: { type: "string" },
14317
+ description: { type: "string" },
14318
+ kind: { type: "string" }
14319
+ }
14320
+ }
14321
+ }
14322
+ }
14323
+ },
13771
14324
  _meta: {
13772
14325
  type: "object",
13773
14326
  description: "Operator context: region + last-call latency.",
@@ -13842,6 +14395,8 @@ var pullLeads = {
13842
14395
  const currentPage = res.pagination?.page ?? page;
13843
14396
  const hasMore = currentPage < totalPages - 1;
13844
14397
  const nextPage = hasMore ? currentPage + 1 : null;
14398
+ const leadCount = res.items.length;
14399
+ const nextSteps = buildPullLeadsNextSteps({ leadCount, hasMore, nextPage });
13845
14400
  return withAgentMemoryMeta(client, {
13846
14401
  lens: { id: lensId },
13847
14402
  leads: res.items.map((lead) => ({
@@ -13853,6 +14408,7 @@ var pullLeads = {
13853
14408
  next_page: nextPage,
13854
14409
  computing_wishlist: res.computing_wishlist,
13855
14410
  computing_scores: res.computing_scores,
14411
+ next_steps: nextSteps,
13856
14412
  _meta: {
13857
14413
  region: client.region,
13858
14414
  latency_ms: client.lastMeta?.latency_ms ?? null
@@ -14893,6 +15449,40 @@ var campaignCallSheet = {
14893
15449
  }
14894
15450
  };
14895
15451
 
15452
+ // ../core/dist/composite/_web-fetch-helpers.js
15453
+ var SECTION_PRIORITY = ["profile", "signals", "clues"];
15454
+ function splitEmojiSection(key) {
15455
+ const m = key.match(/^([^\p{L}\p{N}\s]+)\s+(.+)$/u);
15456
+ if (m)
15457
+ return { emoji: m[1], label: m[2] };
15458
+ return { emoji: null, label: key };
15459
+ }
15460
+ function reshapeWebFetchContent(content) {
15461
+ if (!content)
15462
+ return [];
15463
+ const sections = [];
15464
+ for (const [key, val] of Object.entries(content)) {
15465
+ if (!Array.isArray(val))
15466
+ continue;
15467
+ const { emoji, label } = splitEmojiSection(key);
15468
+ sections.push({
15469
+ section_label: label,
15470
+ section_emoji: emoji,
15471
+ entries: val
15472
+ });
15473
+ }
15474
+ sections.sort((a, b) => {
15475
+ const ai = SECTION_PRIORITY.findIndex((p) => a.section_label.toLowerCase().includes(p));
15476
+ const bi = SECTION_PRIORITY.findIndex((p) => b.section_label.toLowerCase().includes(p));
15477
+ const aN = ai < 0 ? SECTION_PRIORITY.length : ai;
15478
+ const bN = bi < 0 ? SECTION_PRIORITY.length : bi;
15479
+ if (aN !== bN)
15480
+ return aN - bN;
15481
+ return a.section_label.localeCompare(b.section_label);
15482
+ });
15483
+ return sections;
15484
+ }
15485
+
14896
15486
  // ../core/dist/composite/research-lead-by-id.js
14897
15487
  function normalizeLinkedinPage5(v) {
14898
15488
  if (v == null)
@@ -15008,38 +15598,6 @@ _Truncated_: ${shape.truncation_hint ?? "response trimmed"}_`);
15008
15598
  }
15009
15599
  return out.join("\n");
15010
15600
  }
15011
- var SECTION_PRIORITY = ["profile", "signals", "clues"];
15012
- function splitEmojiSection(key) {
15013
- const m = key.match(/^([^\p{L}\p{N}\s]+)\s+(.+)$/u);
15014
- if (m)
15015
- return { emoji: m[1], label: m[2] };
15016
- return { emoji: null, label: key };
15017
- }
15018
- function reshapeWebFetchContent(content) {
15019
- if (!content)
15020
- return [];
15021
- const sections = [];
15022
- for (const [key, val] of Object.entries(content)) {
15023
- if (!Array.isArray(val))
15024
- continue;
15025
- const { emoji, label } = splitEmojiSection(key);
15026
- sections.push({
15027
- section_label: label,
15028
- section_emoji: emoji,
15029
- entries: val
15030
- });
15031
- }
15032
- sections.sort((a, b) => {
15033
- const ai = SECTION_PRIORITY.findIndex((p) => a.section_label.toLowerCase().includes(p));
15034
- const bi = SECTION_PRIORITY.findIndex((p) => b.section_label.toLowerCase().includes(p));
15035
- const aN = ai < 0 ? SECTION_PRIORITY.length : ai;
15036
- const bN = bi < 0 ? SECTION_PRIORITY.length : bi;
15037
- if (aN !== bN)
15038
- return aN - bN;
15039
- return a.section_label.localeCompare(b.section_label);
15040
- });
15041
- return sections;
15042
- }
15043
15601
  function isReachable(c) {
15044
15602
  if (!c)
15045
15603
  return false;
@@ -15602,6 +16160,316 @@ var accountHistory = {
15602
16160
  }
15603
16161
  };
15604
16162
 
16163
+ // ../core/dist/composite/scan-portfolio-signals.js
16164
+ var DEFAULT_MAX_LEADS = 200;
16165
+ var HARD_MAX_LEADS = 300;
16166
+ var MONITOR_PAGE_SIZE = 200;
16167
+ function fold(s) {
16168
+ return s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().trim();
16169
+ }
16170
+ function parseQueryTerms(query) {
16171
+ return query.split(/[,\s]+/).map((t) => fold(t)).filter((t) => t.length > 0);
16172
+ }
16173
+ function shortLocation(loc) {
16174
+ if (loc == null)
16175
+ return null;
16176
+ if (typeof loc === "string")
16177
+ return loc.trim() || null;
16178
+ if (typeof loc === "object") {
16179
+ const o = loc;
16180
+ const clean = (v) => {
16181
+ const s = typeof v === "string" ? v.trim() : "";
16182
+ return s && s.toUpperCase() !== "N/A" ? s : "";
16183
+ };
16184
+ const city = clean(o.city);
16185
+ const state = clean(o.state);
16186
+ if (city && state)
16187
+ return `${city}, ${state}`;
16188
+ if (city)
16189
+ return city;
16190
+ if (typeof o.full === "string" && o.full.trim())
16191
+ return o.full.trim();
16192
+ }
16193
+ return null;
16194
+ }
16195
+ function mergeLocationIds2(filter, ids) {
16196
+ const criteria = filter?.criteria ? [...filter.criteria] : [];
16197
+ const idx = criteria.findIndex((c) => c?.type === "location_ids" && c?.is_excluded === false);
16198
+ if (idx >= 0) {
16199
+ const cur = criteria[idx];
16200
+ const existing = Array.isArray(cur.locations) ? cur.locations : [];
16201
+ const merged = Array.from(/* @__PURE__ */ new Set([...existing, ...ids]));
16202
+ criteria[idx] = { ...cur, locations: merged };
16203
+ } else {
16204
+ criteria.push({ type: "location_ids", is_excluded: false, locations: ids });
16205
+ }
16206
+ return { criteria };
16207
+ }
16208
+ function entryMatches(entry, sectionLabel, terms) {
16209
+ if (terms.length === 0)
16210
+ return false;
16211
+ const haystack = fold([entry.description ?? "", entry.source ?? "", sectionLabel].join("  "));
16212
+ return terms.some((t) => haystack.includes(t));
16213
+ }
16214
+ function passesSince(entry, sinceMs) {
16215
+ if (sinceMs == null)
16216
+ return true;
16217
+ if (!entry.date)
16218
+ return true;
16219
+ const ts = Date.parse(entry.date);
16220
+ if (Number.isNaN(ts))
16221
+ return true;
16222
+ return ts >= sinceMs;
16223
+ }
16224
+ var scanPortfolioSignals = {
16225
+ name: "leadbay_scan_portfolio_signals",
16226
+ annotations: {
16227
+ title: "Scan a portfolio for a web-research signal in bulk",
16228
+ readOnlyHint: true,
16229
+ destructiveHint: false,
16230
+ idempotentHint: true,
16231
+ openWorldHint: true
16232
+ },
16233
+ description: leadbay_scan_portfolio_signals,
16234
+ inputSchema: {
16235
+ type: "object",
16236
+ properties: {
16237
+ query: {
16238
+ type: "string",
16239
+ description: "Signal terms to match (case- and accent-insensitive). Comma- or space-separated terms are OR'd, e.g. 'M&A, acquisition, rachet\xE9'. Matched against each signal entry's description, source, and section label."
16240
+ },
16241
+ leadIds: {
16242
+ type: "array",
16243
+ items: { type: "string" },
16244
+ description: "Explicit lead UUIDs to scan (skips Monitor pagination). Use when you already hold a cohort of ids."
16245
+ },
16246
+ city: {
16247
+ type: "string",
16248
+ description: "Free-text city / region to scope the Monitor portfolio before scanning (resolved via /geo/search, same as leadbay_pull_followups). Ignored when `leadIds` is given."
16249
+ },
16250
+ city_id: {
16251
+ type: "string",
16252
+ description: "Pre-resolved admin_area id (numeric string). Bypasses the resolver. Ignored when `leadIds` is given."
16253
+ },
16254
+ set_filter: {
16255
+ type: "object",
16256
+ description: "Optional Monitor FilterItem ({criteria: FilterCriterion[]}) to scope the portfolio before scanning. Persisted server-side then applied, mirroring leadbay_pull_followups. Ignored when `leadIds` is given.",
16257
+ properties: {
16258
+ criteria: { type: "array", items: { type: "object" } }
16259
+ }
16260
+ },
16261
+ since: {
16262
+ type: "string",
16263
+ description: "ISO date (e.g. '2025-01-01'). When set, only signal entries dated on/after it are returned. Entries with no date are kept (absence of a date is not evidence the event is old)."
16264
+ },
16265
+ max_leads: {
16266
+ type: "number",
16267
+ description: `Cap on leads scanned (default ${DEFAULT_MAX_LEADS}, hard max ${HARD_MAX_LEADS}). When the portfolio exceeds this, the scan is truncated and truncated_at is set.`
16268
+ }
16269
+ },
16270
+ required: ["query"],
16271
+ additionalProperties: false
16272
+ },
16273
+ outputSchema: {
16274
+ type: "object",
16275
+ properties: {
16276
+ matched: {
16277
+ type: "array",
16278
+ description: "Leads with \u22651 signal entry matching the query. Each: {lead_id, name, location, matched_signals:[{section_label, section_emoji, hot, source, date, description}]}. Campaign-ready \u2014 feed lead_ids straight into leadbay_add_leads_to_campaign.",
16279
+ items: { type: "object" }
16280
+ },
16281
+ not_researched: {
16282
+ type: "array",
16283
+ description: "Leads scanned that had NO cached signal content (web_fetch.content null or still in progress). These are NOT 'no match' \u2014 they were never researched. Qualify them (leadbay_bulk_qualify_leads) then re-scan. Each: {lead_id, name}.",
16284
+ items: { type: "object" }
16285
+ },
16286
+ scanned_count: {
16287
+ type: "number",
16288
+ description: "Total leads read in this scan (matched + non-matching + not_researched)."
16289
+ },
16290
+ matched_count: { type: "number", description: "Length of `matched`." },
16291
+ truncated_at: {
16292
+ type: "number",
16293
+ description: "Present only when the portfolio exceeded `max_leads`; equals the cap applied. Coverage is partial \u2014 narrow the scope (city / set_filter) or raise max_leads."
16294
+ },
16295
+ quota_exceeded: {
16296
+ type: "boolean",
16297
+ description: "True if a 429 was hit mid-scan. Partial `matched` is still returned. Offer wait-for-reset OR top-up."
16298
+ },
16299
+ status: {
16300
+ type: "string",
16301
+ description: "`ambiguous_locations` when a passed `city` matched multiple admin_areas; pick an id from `location_ambiguities` and re-call with `city_id`. Absent on the happy path."
16302
+ },
16303
+ location_ambiguities: {
16304
+ type: "array",
16305
+ description: "Only present when status === 'ambiguous_locations'.",
16306
+ items: { type: "object" }
16307
+ },
16308
+ _meta: {
16309
+ type: "object",
16310
+ properties: {
16311
+ region: { type: "string" },
16312
+ agent_memory: { type: "object" }
16313
+ }
16314
+ }
16315
+ },
16316
+ required: ["matched", "not_researched", "scanned_count", "matched_count", "quota_exceeded"]
16317
+ },
16318
+ execute: async (client, params, ctx) => {
16319
+ const terms = parseQueryTerms(params.query ?? "");
16320
+ const maxLeads = Math.min(params.max_leads ?? DEFAULT_MAX_LEADS, HARD_MAX_LEADS);
16321
+ const sinceParsed = params.since ? Date.parse(params.since) : NaN;
16322
+ const sinceValid = Number.isNaN(sinceParsed) ? null : sinceParsed;
16323
+ let portfolio;
16324
+ let truncatedAt;
16325
+ let quotaExceeded = false;
16326
+ if (params.leadIds && params.leadIds.length > 0) {
16327
+ const sliced = params.leadIds.slice(0, maxLeads);
16328
+ if (params.leadIds.length > maxLeads)
16329
+ truncatedAt = maxLeads;
16330
+ portfolio = sliced.map((id) => ({ id, name: null, location: null }));
16331
+ } else {
16332
+ let effectiveSetFilter = params.set_filter;
16333
+ const geoTexts = [];
16334
+ if (params.city)
16335
+ geoTexts.push(params.city);
16336
+ if (params.city_id)
16337
+ geoTexts.push(params.city_id);
16338
+ if (geoTexts.length > 0) {
16339
+ const { resolved, ambiguities } = await resolveLocations(client, geoTexts);
16340
+ if (ambiguities.length > 0) {
16341
+ return withAgentMemoryMeta(client, {
16342
+ status: "ambiguous_locations",
16343
+ location_ambiguities: ambiguities,
16344
+ matched: [],
16345
+ not_researched: [],
16346
+ scanned_count: 0,
16347
+ matched_count: 0,
16348
+ quota_exceeded: false,
16349
+ _meta: { region: client.region }
16350
+ }, ctx);
16351
+ }
16352
+ if (resolved.length > 0) {
16353
+ effectiveSetFilter = mergeLocationIds2(effectiveSetFilter, resolved);
16354
+ }
16355
+ }
16356
+ let filterStored = false;
16357
+ if (effectiveSetFilter) {
16358
+ try {
16359
+ await client.requestVoid("POST", "/monitor/filter", effectiveSetFilter);
16360
+ filterStored = true;
16361
+ } catch (err) {
16362
+ if (err?.code === "QUOTA_EXCEEDED")
16363
+ quotaExceeded = true;
16364
+ ctx?.logger?.warn?.(`scan_portfolio_signals: POST /monitor/filter failed (${err?.code ?? err?.message ?? err}); scanning UNfiltered to avoid trusting a stale server-side filter`);
16365
+ }
16366
+ }
16367
+ portfolio = [];
16368
+ let page = 0;
16369
+ while (portfolio.length < maxLeads) {
16370
+ const qs = new URLSearchParams({
16371
+ personal: "false",
16372
+ liked: "false",
16373
+ filtered: String(filterStored),
16374
+ count: String(MONITOR_PAGE_SIZE),
16375
+ page: String(page)
16376
+ }).toString();
16377
+ let monitor;
16378
+ try {
16379
+ monitor = await client.request("GET", `/monitor?${qs}`);
16380
+ } catch (err) {
16381
+ if (err?.code === "QUOTA_EXCEEDED") {
16382
+ quotaExceeded = true;
16383
+ break;
16384
+ }
16385
+ throw err;
16386
+ }
16387
+ const rawLeads = Array.isArray(monitor.items) ? monitor.items : Array.isArray(monitor.leads) ? monitor.leads : Array.isArray(monitor) ? monitor : [];
16388
+ if (rawLeads.length === 0)
16389
+ break;
16390
+ for (const lead of rawLeads) {
16391
+ if (portfolio.length >= maxLeads)
16392
+ break;
16393
+ portfolio.push({
16394
+ id: lead.id,
16395
+ name: lead.name ?? null,
16396
+ location: shortLocation(lead.location)
16397
+ });
16398
+ }
16399
+ const pages = monitor.pagination?.pages;
16400
+ if (typeof pages === "number" && page >= pages - 1)
16401
+ break;
16402
+ if (rawLeads.length < MONITOR_PAGE_SIZE)
16403
+ break;
16404
+ page += 1;
16405
+ }
16406
+ if (portfolio.length >= maxLeads)
16407
+ truncatedAt = maxLeads;
16408
+ }
16409
+ const matched = [];
16410
+ const notResearched = [];
16411
+ const reads = await Promise.all(portfolio.map(async (lead) => {
16412
+ try {
16413
+ const wf = await client.request("GET", `/leads/${lead.id}/web_fetch`);
16414
+ return { lead, wf, error: null };
16415
+ } catch (error) {
16416
+ return { lead, wf: null, error };
16417
+ }
16418
+ }));
16419
+ for (const r of reads) {
16420
+ const { lead, wf, error } = r;
16421
+ if (error) {
16422
+ if (error?.code === "QUOTA_EXCEEDED")
16423
+ quotaExceeded = true;
16424
+ notResearched.push({ lead_id: lead.id, name: lead.name });
16425
+ continue;
16426
+ }
16427
+ const hasContent = wf && wf.content != null && wf.in_progress !== true && Object.keys(wf.content).length > 0;
16428
+ if (!hasContent) {
16429
+ notResearched.push({ lead_id: lead.id, name: lead.name });
16430
+ continue;
16431
+ }
16432
+ const sections = reshapeWebFetchContent(wf.content);
16433
+ const matchedSignals = [];
16434
+ for (const sec of sections) {
16435
+ for (const entry of sec.entries) {
16436
+ if (!entryMatches(entry, sec.section_label, terms))
16437
+ continue;
16438
+ if (!passesSince(entry, sinceValid))
16439
+ continue;
16440
+ matchedSignals.push({
16441
+ section_label: sec.section_label,
16442
+ section_emoji: sec.section_emoji,
16443
+ hot: entry.hot === true,
16444
+ source: entry.source ?? "",
16445
+ date: entry.date ?? null,
16446
+ description: entry.description ?? ""
16447
+ });
16448
+ }
16449
+ }
16450
+ if (matchedSignals.length > 0) {
16451
+ matched.push({
16452
+ lead_id: lead.id,
16453
+ name: lead.name,
16454
+ location: lead.location,
16455
+ matched_signals: matchedSignals
16456
+ });
16457
+ }
16458
+ }
16459
+ const out = {
16460
+ matched,
16461
+ not_researched: notResearched,
16462
+ scanned_count: portfolio.length,
16463
+ matched_count: matched.length,
16464
+ quota_exceeded: quotaExceeded,
16465
+ _meta: { region: client.region }
16466
+ };
16467
+ if (truncatedAt !== void 0)
16468
+ out.truncated_at = truncatedAt;
16469
+ return withAgentMemoryMeta(client, out, ctx);
16470
+ }
16471
+ };
16472
+
15605
16473
  // ../core/dist/composite/recall-ordered-titles.js
15606
16474
  var recallOrderedTitles = {
15607
16475
  name: "leadbay_recall_ordered_titles",
@@ -19961,6 +20829,10 @@ var compositeReadTools = [
19961
20829
  // reprioritize-a-neglected-account workflow (#3630 GAP C) must work in a
19962
20830
  // default deployment without LEADBAY_MCP_ADVANCED=1.
19963
20831
  accountHistory,
20832
+ // Bulk portfolio signal scan — read-only, no quota burn. The single-call
20833
+ // answer to "which of my leads have signal X" that previously forced a
20834
+ // per-lead research_lead_by_id loop (issue #3704).
20835
+ scanPortfolioSignals,
19964
20836
  recallOrderedTitles,
19965
20837
  accountStatus,
19966
20838
  bulkEnrichStatus,
@@ -20010,6 +20882,18 @@ var compositeWriteTools = [
20010
20882
  reportOutreach,
20011
20883
  importLeads,
20012
20884
  importAndQualify,
20885
+ // Contact management (product#3703) — each is a single-call relay, so
20886
+ // granular-shaped and living in tools/; registered HERE (not granular-gated)
20887
+ // so reps can manage contacts in-conversation without LEADBAY_MCP_ADVANCED.
20888
+ // Same pattern as likeLead/dislikeLead below. Endpoints (all direct, the
20889
+ // ones the web UI uses — NOT the import pipeline, which 401s on some
20890
+ // accounts): add → POST /leads/{id}/contacts; remove → archive;
20891
+ // pin/unpin → /pin|/unpin; update → /update (snake_case, first/last required).
20892
+ addContact,
20893
+ removeContact,
20894
+ pinContact,
20895
+ unpinContact,
20896
+ updateContact,
20013
20897
  // createCustomField is granular-shaped but file-import prompts depend on it
20014
20898
  // to preserve source-system links without requiring advanced-tool exposure.
20015
20899
  createCustomField,
@@ -20140,7 +21024,7 @@ async function readResource(uri, client) {
20140
21024
  }
20141
21025
 
20142
21026
  // src/host-widgets.ts
20143
- var BUILTIN_WIDGETS_PARAGRAPH = 'Prefer host-native widgets over inline markdown when the data shape fits. Three to know: (1) `places_map_display_v0` \u2014 for \u22652 locations / map / travel intent. Pass `{name, address, latitude, longitude, notes}` per location; the host enriches via Google Places. (2) `message_compose_v1` \u2014 for any outreach draft (email / message / call opener). Pass 2\u20133 strategic variants with goal-oriented labels ("Push for alignment", "Reference M&A signal") \u2014 NOT tone labels. (3) `ask_user_input_v0` \u2014 for the NEXT STEPS questions every Leadbay tool emits. Pass `single_select` with 2\u20134 mutually-exclusive options from the tool\'s NEXT STEPS table. When the host doesn\'t expose the named widget, fall back to the per-tool markdown RENDERING block. The directive is host-conditional; the fallback is automatic.';
21027
+ var BUILTIN_WIDGETS_PARAGRAPH = 'Prefer host-native widgets over inline markdown when the data shape fits. Three to know: (1) `places_map_display_v0` \u2014 for \u22652 locations / map / travel intent. Pass `{name, address, latitude, longitude, notes}` per location; the host enriches via Google Places. (2) `message_compose_v1` \u2014 for any outreach draft (email / message / call opener). Pass 2\u20133 strategic variants with goal-oriented labels ("Push for alignment", "Reference M&A signal") \u2014 NOT tone labels. (3) The next-step / choice widget \u2014 for the NEXT STEPS questions every Leadbay tool emits. Its NAME AND SCHEMA differ by host; use whichever is in your tool set: (a) `ask_user_input_v0` (Claude chat / ChatGPT) \u2014 options are PLAIN STRINGS with `type: "single_select"`, e.g. `{questions:[{question:"What next?",type:"single_select",options:["Build a triage board","Pull next page"]}]}`. (b) `AskUserQuestion` (Claude cowork / Claude Code) \u2014 options are OBJECTS `{label, description}`, plus a required short `header` (\u226412 chars) and a `multiSelect` boolean, and NO `type` field; do not add an "Other" option (the host adds it). e.g. `{questions:[{question:"What next?",header:"Next step",multiSelect:false,options:[{label:"Triage board",description:"Build an interactive board to sort this batch."},{label:"Next page",description:"Pull page 2."}]}]}`. Match the schema to the tool you actually have \u2014 using the string-schema for AskUserQuestion (or vice-versa) makes the call fail and you silently fall back to prose. When the host exposes NEITHER widget, fall back to the per-tool markdown RENDERING block.\n\nWIDGET IS MANDATORY WHEN AVAILABLE: if EITHER `ask_user_input_v0` OR `AskUserQuestion` is present in your tool set, you MUST emit your NEXT STEPS / scheduling / artifact offer by CALLING that widget tool (with its correct schema above) \u2014 do NOT write the options out as a prose question ("Want me to run this every morning?", "Should I build a board?"). Prose for these offers is the FALLBACK reserved ONLY for hosts that expose neither widget. When the widget exists, presenting the same choices as prose instead of calling it is a defect: the user loses the click-to-select surface. So whenever you have a recurring-task offer, an artifact offer, or a 2\u20134 option next-step menu AND a widget tool is available \u2192 call it, every time.';
20144
21028
 
20145
21029
  // src/telemetry.ts
20146
21030
  import { PostHog } from "posthog-node";
@@ -20489,6 +21373,41 @@ var QUOTA_TOPUP = `Quota & top-ups: when a tool returns QUOTA_EXCEEDED / 429, th
20489
21373
  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.`;
20490
21374
 
20491
21375
  // src/server.ts
21376
+ var ARTIFACT_PROPOSAL_PARAGRAPH = 'Artifact proposals: after any result the user would scan, compare, plan against, or return to \u2014 or any multi-item result \u2014 DEFAULT TO offering an artifact. Treat the offer as expected, not optional: a multi-item lead batch, a side-by-side comparison, or a research record the user will revisit each SHOULD get an artifact offer unless it clearly falls in the Skip list below. When in doubt, offer. WIDGET IS MANDATORY WHEN AVAILABLE: if your host\'s choice widget is in your tool set \u2014 `ask_user_input_v0` (Claude chat / ChatGPT) OR `AskUserQuestion` (Claude cowork / Claude Code) \u2014 you MUST make the offer by CALLING that widget tool \u2014 never as a prose line ("Want me to build an interactive lead triage board?"). Prose is the fallback ONLY for hosts that expose neither widget. Presenting the offer as prose when a widget exists is a defect \u2014 the user loses the click-to-select surface.\n\nTwo tracks:\n1. A NEXT STEPS menu is already firing (the choice widget with 2\u20134 options): include the artifact offer as one of the slots. It counts toward the 2\u20134 budget \u2014 replace the lowest-priority option when already at 4.\n2. No NEXT STEPS menu is firing: fire a standalone yes/no question by CALLING your host\'s choice widget with ITS schema (see the host-widget section: `ask_user_input_v0` takes string options; `AskUserQuestion` takes {label, description} objects with a `header` and `multiSelect`). The question is "Want me to build a [concrete artifact name] for this?" with yes/no options. Use the schema that matches the widget tool you actually have.\n\nName the artifact concretely from the result you just returned: "Build an interactive lead triage board", "Build a research one-pager for Acme Corp", "Build a side-by-side outreach variant comparison". Never use generic labels.\n\nOn selection of yes/build: build the artifact from data already in hand \u2014 do NOT re-call the tool. Emit with the antArtifact tag: type="text/html" for interactive boards/tables, type="application/vnd.ant.react" for React components, type="text/markdown" for one-pagers.\n\nSkip for: single-action confirmations (like/dislike, report_outreach), mid-flow steps, results a host widget already covers (places_map_display_v0, message_compose_v1).';
21377
+ var SCHEDULED_TASK_PARAGRAPH = `Scheduled task proposals: check the user's LITERAL words. NEVER fire based on the workflow or prompt type \u2014 only on what the user ACTUALLY TYPED.
21378
+
21379
+ NEVER fire for these examples (no recurring language in user message):
21380
+ - 'Show me today\\'s leads.' \u2192 NO
21381
+ - 'What are my leads today?' \u2192 NO
21382
+ - 'Pull my best new prospects.' \u2192 NO
21383
+ - 'Show me my batch.' \u2192 NO
21384
+ - 'Run my morning check-in.' (no recurring qualifier) \u2192 NO
21385
+
21386
+ ONLY fire when the user's message contains explicit recurring language:
21387
+ - 'I do this every day' \u2192 YES
21388
+ - 'every morning' \u2192 YES
21389
+ - 'remind me every week' \u2192 YES
21390
+ - 'automate this' \u2192 YES
21391
+ - 'set this up as recurring' \u2192 YES
21392
+
21393
+ WIDGET IS MANDATORY WHEN AVAILABLE: if your host's choice widget is in your tool set \u2014 \`ask_user_input_v0\` (Claude chat / ChatGPT) OR \`AskUserQuestion\` (Claude cowork / Claude Code) \u2014 you MUST make the scheduling offer by CALLING that widget tool \u2014 never as a prose line ("Want me to run this every morning?"). Prose is the fallback ONLY for hosts that expose neither widget; presenting the offer as prose when a widget exists is a defect.
21394
+
21395
+ Render EVERY question below by CALLING your host's choice widget with ITS schema (see the host-widget section: \`ask_user_input_v0\` takes string options; \`AskUserQuestion\` takes {label, description} objects with a \`header\` and \`multiSelect\`). Use the schema that matches the widget tool you actually have \u2014 never the other one.
21396
+
21397
+ Two tracks \u2014 same as artifact proposals:
21398
+ 1. A NEXT STEPS menu is already firing: add "Schedule [Task Name] as a recurring task" as one slot (counts toward the 2\u20134 budget \u2014 replace the lowest-priority option when already at 4).
21399
+ 2. No NEXT STEPS menu is firing: fire a standalone yes/no question "Want me to schedule this as a recurring task?" (options: yes / no thanks).
21400
+
21401
+ If the user selects yes, continue with a multi-step flow, one widget call per step:
21402
+ Step 1 \u2014 frequency: "How often?" \u2192 Every day / Every weekday / Weekly / Custom.
21403
+ Step 2a \u2014 if "Every day" or "Every weekday": "What time?" \u2192 Morning (8am) / Midday (12pm) / Afternoon (5pm) / Custom.
21404
+ Step 2b \u2014 if "Weekly": "Which day?" \u2192 Monday / Wednesday / Friday / Custom.
21405
+ Step 2c \u2014 if "Custom" at any step: ask for a free-text description and interpret it to determine the schedule.
21406
+ After the schedule is confirmed: judge whether the scheduled run should also produce an artifact. If yes, offer "Should each run also build an artifact (e.g. a fresh lead board)?" \u2192 yes / no.
21407
+
21408
+ Name the task concretely from context: "Daily prospecting check-in", "Weekly follow-up sweep", "Monday morning lead review". Never use generic labels.
21409
+
21410
+ Skip for: single-action confirmations, mid-flow steps, one-off lookups with no recurrence signal.`;
20492
21411
  function buildScoringParagraph(has) {
20493
21412
  const base = "Two scoring layers: every lead has a basic `score` (firmographic \u2014 already decent, usually correlates with AI). Roughly the top 10 of each batch are also AI-qualified (targeted web research + qualification questions \u2192 `ai_agent_lead_score`, surfaced as `qualification_summary` on leadbay_pull_leads). Leads past the top ~10 are not worse \u2014 the system is saving resources.";
20494
21413
  const deepenTools = [];
@@ -20603,6 +21522,8 @@ function buildServerInstructions(exposed) {
20603
21522
  if (has("leadbay_agent_memory_capture")) {
20604
21523
  parts.push(AGENT_MEMORY);
20605
21524
  }
21525
+ parts.push(ARTIFACT_PROPOSAL_PARAGRAPH);
21526
+ parts.push(SCHEDULED_TASK_PARAGRAPH);
20606
21527
  parts.push(BUILTIN_WIDGETS_PARAGRAPH);
20607
21528
  return parts.join("\n\n");
20608
21529
  }
@@ -21254,7 +22175,7 @@ function parseWriteEnv(env = process.env) {
21254
22175
  }
21255
22176
 
21256
22177
  // src/http-server.ts
21257
- var VERSION = true ? "0.18.2" : "0.0.0-dev";
22178
+ var VERSION = true ? "0.19.1" : "0.0.0-dev";
21258
22179
  var PORT = Number(process.env.PORT ?? 8080);
21259
22180
  var HOST = process.env.HOST ?? "0.0.0.0";
21260
22181
  var sseSessions = /* @__PURE__ */ new Map();