diff --git a/prompts/handler.md b/prompts/handler.md index 5524076a5..254876c0e 100644 --- a/prompts/handler.md +++ b/prompts/handler.md @@ -7,14 +7,14 @@ Stage-specific behavior: - QUALIFYING: Understand their needs. Ask BANT questions naturally (not like a checklist). - PRESENTING: Share relevant details about how we help. Use specific examples. - NEGOTIATING: Address concerns directly. Be transparent about pricing/terms. -- CLOSING: Propose a meeting with specific times. Make it easy to say yes. +- CLOSING: Move to the next step using the NEXT STEP guidance below. Make it easy to say yes. Guidelines: 1. MATCH THEIR ENERGY — if they're casual, be casual. If they're formal, be formal. 2. FAST — keep responses short. They already know who you are from the original email. 3. ANSWER FIRST — if they asked a question, answer it immediately. Don't dodge. 4. NO DESPERATION — never say "just checking in" or "just following up" or "I'd love to..." -5. BE SPECIFIC — when suggesting a meeting, propose 2-3 specific times. +5. BE SPECIFIC — when you propose a meeting, use the NEXT STEP times or link exactly. Never invent a time, link, or duration it doesn't give. 6. KNOW WHEN TO STOP — if they say no, thank them and move on. One "no" is enough. Never argue with a no, never "circle back" after a no. 7. OBJECTION = OPPORTUNITY — address concerns with empathy, then redirect to value. 8. NEVER FABRICATE — no invented customers, statistics, discounts, or capabilities. If you don't know, say you'll find out. @@ -22,7 +22,7 @@ Guidelines: 10. NO AI TELLS — no em dashes, no "great question", no bullet points, no exclamation marks, no "I completely understand your concern". Write like a busy human on their phone. Intent-specific guidance: -- INTERESTED: Move toward a meeting within 1-2 messages. Don't oversell. +- INTERESTED: Move toward the next step within 1-2 messages. Don't oversell. - OBJECTION: Acknowledge the concern, provide one proof point, ask one question. - QUESTION: Answer clearly, tie back to their specific situation. - WRONG PERSON: Thank them warmly, ask for a name or warm intro. Make it easy. @@ -30,6 +30,9 @@ Intent-specific guidance: - UNSUBSCRIBE / OPT-OUT: You NEVER reply, never try to save the deal, never ask why. Opt-outs are honored immediately and permanently. This is non-negotiable. - ANGRY / LEGAL / COMPLIANCE (mentions of lawyers, spam reports, harassment, GDPR, CAN-SPAM): You NEVER reply. These are escalated to a human. Do not attempt to smooth it over yourself. +Next step for this reply: +{{booking}} + Output rules: - Write ONLY the email body. No subject line, no "Body:" label, no signature block, no markdown. - Keep it under the word limit you were given. Shorter is always better. diff --git a/sellbird/agents/handler.py b/sellbird/agents/handler.py index 158f6c6cb..48a358eb9 100644 --- a/sellbird/agents/handler.py +++ b/sellbird/agents/handler.py @@ -13,6 +13,7 @@ import unicodedata from datetime import datetime, timezone +from sellbird.booking import booking_instruction from sellbird.brain import Brain, BrainUnavailable from sellbird.config import ( DEFAULT_OPT_OUT_LINE, SellbirdConfig, EnvConfig, compliance_of, legacy_sending_held, @@ -25,6 +26,7 @@ NATIVE_PROVIDERS, get_mail_provider, strip_quoted_reply, ) from sellbird.models.conversation import Conversation, Message +from sellbird.send_window import recipient_zone from sellbird.state import COLLEAGUE_REPLIED, REVIEW_NEXT_REPLY_KEY, StateManager from sellbird.sending_mode import sync_sending_mode from sellbird.startups import startup_facts @@ -1252,11 +1254,32 @@ async def _generate_response( objection_context = f"\nSuggested approach for this objection: {response}" break - prompt = self.brain.load_prompt("handler", stage=convo.stage) + # Only an interested prospect (or a thread already closing) should be + # moved to the configured next step. Everything else gets an answer, + # not a pitch. + if intent == "interested" or convo.stage == "closing": + try: + zone = await recipient_zone(self.state, prospect, self.config) + except Exception as e: + logger.warning(f"Handler: couldn't resolve the recipient's time zone: {e}") + zone = "" + booking = booking_instruction( + self.config, datetime.now(timezone.utc), zone, + ) + else: + booking = ( + "Do not offer a meeting, a call, a trial, or a booking link. " + "Answer their message and follow the intent guidance above." + ) + + prompt = self.brain.load_prompt("handler", stage=convo.stage, booking=booking) if not prompt: prompt = f"""You are {self.config.persona.name}, {self.config.persona.role} at {self.config.persona.company}. Your tone is: {self.config.persona.tone} -Product: {self.config.product.name} — {self.config.product.description}""" +Product: {self.config.product.name} — {self.config.product.description} + +NEXT STEP +{booking}""" # Inject objection handling + sales methodology skills if self.skills: @@ -1291,9 +1314,9 @@ async def _generate_response( if intent == "interested": prompt += """ - Acknowledges their interest warmly -- Suggests a specific next step (brief call or meeting) +- Moves to the next step exactly as the NEXT STEP guidance says - Keeps it short (under 80 words) -- Includes a clear CTA with flexibility on timing""" +- Includes one clear CTA""" elif intent == "objection": prompt += """ - Addresses the concern directly and empathetically diff --git a/sellbird/booking.py b/sellbird/booking.py new file mode 100644 index 000000000..198f9954a --- /dev/null +++ b/sellbird/booking.py @@ -0,0 +1,180 @@ +"""What the reply should offer, from the ``product.offer`` you configured. + +``sellbird.yaml`` asks what happens when someone is interested: book a call +with your calendar link, suggest concrete times, ask for their preference, +start a trial, or just keep the conversation going. Until now only +``booking_url`` was read (the pre-send gate allows it); the rest was dead +config and every reply was told to "propose 2-3 specific times" whether or +not that fit the offer. + +``booking_instruction`` turns the offer into instruction for the model. It +is never the email body itself: the caller puts the returned paragraph in +the handler prompt. +""" + +from datetime import datetime, time, timedelta +from urllib.parse import urlparse + +import pytz + +from sellbird.config import operator_timezone, send_window_of + +DEFAULT_START = time(9, 0) +DEFAULT_END = time(17, 0) +SUGGESTED_TIMES = 3 +LOOKAHEAD_DAYS = 14 + + +def _parse_clock(value, fallback: time) -> time: + try: + return time.fromisoformat(str(value)) + except (TypeError, ValueError): + return fallback + + +def _hours(config) -> tuple[time, time]: + """The send window's hours, or sensible office hours when none is set. + + A reply is not held to the window, but a time inside it is a time the + prospect is more likely to answer.""" + window = send_window_of(config) + if window is None: + return DEFAULT_START, DEFAULT_END + start = _parse_clock(window.start, DEFAULT_START) + end = _parse_clock(window.end, DEFAULT_END) + return (start, end) if start < end else (DEFAULT_START, DEFAULT_END) + + +def _slot_times(config) -> list[time]: + """One or two clock times inside the window, spread across the day.""" + start, end = _hours(config) + start_min = start.hour * 60 + start.minute + end_min = end.hour * 60 + end.minute + span = end_min - start_min + if span >= 120: + minutes = [start_min + 60, end_min - 60] + elif span >= 60: + minutes = [start_min + 30, end_min - 30] + else: + minutes = [start_min] + out = [] + for value in minutes: + slot = time(value // 60, value % 60) + if slot not in out and start <= slot < end: + out.append(slot) + return out or [start] + + +def _local(now: datetime, zone: str) -> datetime: + """``now`` on the recipient's clock. A naive ``now`` is taken as wall + time in ``zone``, so tests and callers that already resolved the zone + don't need to build an aware datetime.""" + if not zone: + return now + try: + tz = pytz.timezone(zone) + except pytz.UnknownTimeZoneError: + return now + if now.tzinfo is None: + return tz.localize(now) + return now.astimezone(tz) + + +def _format(day: datetime, at: time) -> str: + # No %-d / %-I: those are not portable to Windows. + clock = at.strftime("%I:%M %p") + if clock.startswith("0"): + clock = clock[1:] + return f"{day:%A}, {day:%B} {day.day} at {clock}" + + +def _suggested_times(config, now: datetime) -> list[str]: + """Two or three upcoming weekday slots, starting tomorrow.""" + window = send_window_of(config) + weekdays_only = window.weekdays_only if window is not None else True + times = _slot_times(config) + day = now + slots = [] + for offset in range(1, LOOKAHEAD_DAYS + 1): + candidate = day + timedelta(days=offset) + if weekdays_only and candidate.weekday() >= 5: + continue + slots.append(_format(candidate, times[len(slots) % len(times)])) + if len(slots) == SUGGESTED_TIMES: + break + return slots + + +def _join(items: list[str]) -> str: + if len(items) <= 1: + return items[0] if items else "" + if len(items) == 2: + return f"{items[0]} or {items[1]}" + return ", ".join(items[:-1]) + f", or {items[-1]}" + + +def _valid_url(value: str) -> str: + url = str(value or "").strip() + parsed = urlparse(url) + if parsed.scheme not in ("http", "https") or not parsed.netloc: + return "" + return url + + +def _meeting(config) -> str: + offer = getattr(getattr(config, "product", None), "offer", None) + duration = str(getattr(offer, "meeting_duration", "") or "15 minutes").strip() + owner = str(getattr(offer, "meeting_owner", "") or "").strip() + if owner: + return f"The call is {duration} with {owner}." + return f"The call is {duration}." + + +def _time_instruction(config, now: datetime, zone: str, zone_known: bool) -> str: + slots = _suggested_times(config, now) + if not slots: + return ("Ask what time works for them in the next week. Do not invent " + "a specific time. " + _meeting(config)) + where = (f"These are already in the recipient's local time ({zone}); write " + "them as given." if zone_known else + "Write these times as given and do not name a time zone.") + return (f"Propose these times: {_join(slots)}. {where} Offer no other " + "time. " + _meeting(config)) + + +def booking_instruction(config, now: datetime, zone: str = "") -> str: + """Instruction for the next step this reply should offer. + + ``zone`` is the recipient's IANA time zone, when Sellbird knows it. With + no zone the dates are worked out on the operator's clock and the text + avoids naming one.""" + offer = getattr(getattr(config, "product", None), "offer", None) + goal = str(getattr(offer, "goal", "") or "book_call") + entry = str(getattr(offer, "entry", "") or "").strip() + + if goal == "get_reply": + return ("Keep this reply conversational: answer them and ask one " + "question about their situation. Do not propose a call, a " + "meeting, a trial, or a link.") + + if goal == "start_trial" and entry: + return (f"Offer this as the next step: {entry}. Keep it to one sentence " + "and one action, and do not ask for a call or invent a " + "different trial.") + + zone = str(zone or "").strip() + local = _local(now, zone or operator_timezone(config)) + zone_known = bool(zone) and zone in pytz.all_timezones_set + + method = str(getattr(offer, "booking_method", "") or "calendar_link") + url = _valid_url(getattr(offer, "booking_url", "")) + if method == "calendar_link" and url: + return (f"Offer this booking link: {url}\n" + f"Let them pick a time on that page. Do not invent times or " + f"offer to compare calendars yourself. {_meeting(config)}") + if method == "ask_preference": + return ("Ask what time works for them in the next week. Do not invent " + "specific times or paste a link. " + _meeting(config)) + # ``suggest_times``, and the default ``calendar_link`` with no usable + # URL: a link that can't be sent is worse than a real time. + return _time_instruction(config, now=local, zone=zone, zone_known=zone_known) diff --git a/tests/test_booking.py b/tests/test_booking.py new file mode 100644 index 000000000..dc0fe5ba7 --- /dev/null +++ b/tests/test_booking.py @@ -0,0 +1,243 @@ +"""The offer in ``product.offer`` shapes what a reply proposes. + +The config asked for a goal and a booking method all along, but only the +booking URL was read (by the send gate). Every reply was told to suggest +2-3 times, so a Calendly link never appeared and a trial never got offered. +These tests pin the instruction the model receives; no email is sent. + +The clock is pinned, so the dates are stable in every time zone the tests +run in. +""" + +from datetime import datetime, timezone +from types import SimpleNamespace + +import pytest +import pytest_asyncio + +from sellbird import brain as brain_mod +from sellbird.booking import booking_instruction +from sellbird.config import SendWindowConfig +from sellbird.models.conversation import Conversation, Message +from sellbird.models.prospect import Prospect +from sellbird.state import StateManager +from tests.test_outbox_native import Cfg, Env +from tests.test_prompt_injection import RecordingBrain + +# A Monday afternoon, so "tomorrow" is unambiguous. +NOW = datetime(2026, 11, 2, 14, 0, tzinfo=timezone.utc) + + +def _cfg(**offer) -> SimpleNamespace: + fields = dict( + goal="book_call", booking_method="calendar_link", booking_url="", + entry="", meeting_duration="15 minutes", meeting_owner="", + ) + fields.update(offer) + return SimpleNamespace( + product=SimpleNamespace(offer=SimpleNamespace(**fields)), + channels=SimpleNamespace(email=SimpleNamespace( + send_window=SendWindowConfig(start="09:00", end="17:00"), + )), + usage=SimpleNamespace(quiet_hours=SimpleNamespace(timezone="America/New_York")), + ) + + +# ── calendar link ── + + +def test_a_configured_calendar_link_is_offered_verbatim(): + text = booking_instruction( + _cfg(booking_url="https://cal.com/sellbird/15", meeting_owner="Sam"), + NOW, + ) + assert "https://cal.com/sellbird/15" in text + assert "Sam" in text + assert "15 minutes" in text + assert "Propose these times" not in text + assert "Do not invent times" in text + + +def test_a_link_that_cannot_be_sent_falls_back_to_real_times(): + text = booking_instruction(_cfg(booking_url="javascript:alert(1)"), NOW) + assert "javascript" not in text + assert "Propose these times:" in text + + +def test_the_default_offer_suggests_times_when_no_link_is_set(): + """A fresh sellbird.yaml defaults to calendar_link with an empty URL. + That must not leave the reply with nothing to offer.""" + text = booking_instruction(_cfg(), NOW) + assert "Propose these times:" in text + assert "Tuesday, November 3" in text + + +# ── suggested times ── + + +def test_suggested_times_start_after_today_and_skip_the_weekend(): + text = booking_instruction(_cfg(booking_method="suggest_times"), NOW) + assert "Tuesday, November 3" in text + assert "Wednesday, November 4" in text + assert "Thursday, November 5" in text + assert "Monday, November 2" not in text + assert "Saturday" not in text and "Sunday" not in text + + +def test_a_friday_only_offers_the_next_week(): + friday = datetime(2026, 11, 6, 14, 0, tzinfo=timezone.utc) + text = booking_instruction(_cfg(booking_method="suggest_times"), friday) + assert "Monday, November 9" in text + assert "Saturday" not in text and "Sunday" not in text + + +def test_the_window_hours_bound_the_suggested_times(): + config = _cfg(booking_method="suggest_times") + config.channels.email.send_window = SendWindowConfig(start="07:30", end="09:30") + text = booking_instruction(config, NOW) + assert "8:30 AM" in text + assert "10:00 AM" not in text + + +def test_the_recipients_zone_moves_the_date(): + """23:30 UTC is already Tuesday in Tokyo, so tomorrow is Wednesday.""" + late = datetime(2026, 11, 2, 23, 30, tzinfo=timezone.utc) + text = booking_instruction(_cfg(booking_method="suggest_times"), late, "Asia/Tokyo") + assert "Wednesday, November 4" in text + assert "Asia/Tokyo" in text + assert "Tuesday, November 3" not in text + + +def test_without_a_zone_the_operator_clock_decides_but_no_zone_is_named(): + # 02:00 UTC Tuesday is still Monday evening in New York, so tomorrow is + # Tuesday there. + late = datetime(2026, 11, 3, 2, 0, tzinfo=timezone.utc) + text = booking_instruction(_cfg(booking_method="suggest_times"), late, "") + assert "Tuesday, November 3" in text + assert "America/New_York" not in text + assert "time zone" in text + + +def test_an_unknown_zone_is_ignored_rather_than_printed(): + text = booking_instruction(_cfg(booking_method="suggest_times"), NOW, "Mars/Olympus") + assert "Mars/Olympus" not in text + assert "Propose these times:" in text + + +# ── other goals and methods ── + + +def test_asking_preference_does_not_invent_a_time(): + text = booking_instruction(_cfg(booking_method="ask_preference"), NOW) + assert "what time works for them" in text + assert "AM" not in text and "PM" not in text + assert "15 minutes" in text + + +def test_start_trial_offers_the_entry_offer(): + text = booking_instruction(_cfg(goal="start_trial", entry="a free audit"), NOW) + assert "a free audit" in text + assert "one action" in text + + +def test_start_trial_without_an_entry_still_offers_a_next_step(): + text = booking_instruction(_cfg(goal="start_trial", booking_method="suggest_times"), NOW) + assert "Propose these times:" in text + + +def test_get_reply_does_not_push_a_meeting(): + text = booking_instruction( + _cfg(goal="get_reply", booking_url="https://cal.com/sellbird/15"), NOW, + ) + assert "Do not propose a call" in text + assert "https://cal.com/sellbird/15" not in text + + +# ── the reply prompt ── + + +class PromptBrain(RecordingBrain): + """Records the prompt, but loads the real prompt file so the handler's + ``{{booking}}`` and ``{{stage}}`` are checked, not a stub.""" + + def load_prompt(self, name, **kwargs): + template = (brain_mod.PROMPTS_DIR / f"{name}.md").read_text(encoding="utf-8") + for key, value in kwargs.items(): + template = template.replace(f"{{{{{key}}}}}", str(value)) + return template + + +class OfferCfg(Cfg): + class product(Cfg.product): + class offer: + goal = "book_call" + booking_method = "calendar_link" + booking_url = "https://cal.example/sellbird/15" + entry = "" + meeting_duration = "20 minutes" + meeting_owner = "Sam" + + +@pytest_asyncio.fixture +async def state(tmp_path): + s = StateManager(str(tmp_path / "booking.db")) + await s.init_db() + return s + + +async def _handler(state, config=None): + from sellbird.agents.handler import Handler + + brain = PromptBrain(text_reply="Happy to. Tuesday works?") + handler = Handler(brain=brain, state=state, config=config or OfferCfg(), env=Env()) + return handler, brain + + +async def _prospect(state): + pid = await state.add_prospect(Prospect( + first_name="Jo", last_name="Q", title="CTO", company="Q Co", + email="jo@q.example", email_status="verified", + )) + return await state.get_prospect(pid) + + +def _convo(prospect, stage="engaged"): + return Conversation( + id="c", prospect_id=prospect.id, stage=stage, + thread=[Message(sender="prospect", content="Let's talk.")], + ) + + +@pytest.mark.asyncio +async def test_an_interested_reply_gets_the_configured_booking_link(state): + handler, brain = await _handler(state) + prospect = await _prospect(state) + await handler._generate_response( + "interested", "Let's talk.", prospect, _convo(prospect), + ) + prompt = brain.prompts[0] + assert "https://cal.example/sellbird/15" in prompt + assert "20 minutes" in prompt and "Sam" in prompt + assert "{{" not in prompt + + +@pytest.mark.asyncio +async def test_a_question_does_not_get_a_pitch(state): + handler, brain = await _handler(state) + prospect = await _prospect(state) + await handler._generate_response( + "question", "What does it cost?", prospect, _convo(prospect, stage="engaged"), + ) + prompt = brain.prompts[0] + assert "Do not offer a meeting, a call, a trial, or a booking link" in prompt + assert "https://cal.example/sellbird/15" not in prompt + + +@pytest.mark.asyncio +async def test_a_closing_thread_gets_the_next_step_whatever_the_intent(state): + handler, brain = await _handler(state) + prospect = await _prospect(state) + await handler._generate_response( + "question", "Send the details.", prospect, _convo(prospect, stage="closing"), + ) + assert "https://cal.example/sellbird/15" in brain.prompts[0]