Skip to main content

Agent K

Agent K sources prospects and delivers them into the tenant's CRM — GoHighLevel or HubSpot, the tenant's pick when both are connected (see HubSpot) — or, with no CRM, emails them from the tenant's own mailbox (see Routing & the tenant mailbox). Two hand-off modes (ai_agent_k.mode):

  • push (Mode A, default) — contact + custom fields + why-now note + trigger tags; the tenant's own GHL workflows send the sequences.
  • send (Mode B) — Agent K also composes and sends the 3-touch email sequence itself (AgentKSequenceJob), through GHL Conversations or the tenant mailbox (ai_agent_k.send_via).

On top of that, rules (event/score-triggered workflows) and bulk runs place calls, texts, emails and LinkedIn invites against Agent K leads — see Automations. Backend owns the pipeline and tenant (sell-side) wallet billing; ms-ai does drafting-adjacent LLM work (ICP parsing, previews, replies, stop-intent) and records platform cost.

Availability: every company. The super-admin beta flag (company.agent_k_beta_enabled, PUT /company/:_id/agent-k-beta) was removed 2026-09-25 (f1d39fb38); the tenant's ai_agent_k.enabled is the only switch for jobs, services, the inbound hand-off and rules. Switching on still needs a funded wallet (the settings screen blocks the toggle at $0; POST /company/agent-k/onboarding-enable returns 402 on an empty wallet and grants nothing — it's client setup's wallet check). scripts/grandfather-agent-k-auto-push.js keeps its old beta filter on purpose.

feeders queue & pacing
inbound KnockID (realtime, ─────────► (bypasses queue → push)
PersonResolverService)
AgentKOutboundJob (hourly): ─┐
agent_k_provider=apollo: │
Apify SoS + Apollo search │
(fresh + deep lanes) │
→ people/match reveal ├─► agent_k_prospects ─► AgentKTrickleJob
+ PredictLeads why-now │ (pending/drafted/ (5 min tick, working
agent_k_provider=origami: │ skipped ledger) hours only, jittered
one Origami search/day │ 6–20 min gap, burst ≤3,
(+ fetch-more) │ daily cap)
neither gates on a why-now ─┘ │ lead_found rule event
AgentKReactivationJob (hourly, │ in-app + phone push
dormant GHL contacts) │
tenant CSV import ─► agent_k_prospects (source 'import') │
─► AgentKImportJob (every minute, ≤20/list/tick, │
no pacing, no daily limit) ─────────────────────────► │
review feed (auto_push=false, default)
manual "Push to LeadConnector" ── or auto_push=true
│
AgentKPushService.pushLead → GHL contact
kk_token + kk_why_now fields · why-now note
`nextlevel *` trigger tags (tag failure = push failure)
│
mode 'push': tenant's GHL workflows send …?kk={{contact.kk_token}}
mode 'send': Agent K drafts touch 1–3; auto-send grid decides who sends
│
POST /user-session/kk-click ─► identity stitch + `nextlevel returned-to-site`
+ email_click rule event

Feeders​

FeederTriggerFiles
Inbound KnockIDrealtime on verified identify — PersonResolverService._fireAgentKInbound → ms-ai POST /internal/knox/agent-k/inboundapp/services/PersonResolverService.js, ms-ai/src/agent-k/
Outbound net-newAgentKOutboundJob (hourly tick; once per local day per tenant, due from 2h before today's working_hours opening — 7am with no schedule / closed day — via the ai_agent_k.last_outbound_scan_day claim, now a local date that only moves forward, c49a13efd). Provider per company.agent_k_provider — see belowapp/jobs/AgentKOutboundJob.js, app/services/AgentKOutboundService.js, app/lib/apifySos.js, app/lib/origami.js
CRM reactivationAgentKReactivationJob (hourly; once/day per tenant), requires re_engage.revive_crm + GHLapp/jobs/AgentKReactivationJob.js, app/services/ReactivationService.js
Tenant importCSV upload → AgentKImportJob (every minute) — see Lead importsapp/services/AgentKImportService.js, app/jobs/AgentKImportJob.js

Inbound (knockid), reactivation, and imports marked known are re-engage leads (lib/reEngage.isReEngage; frontend mirror isReEngageLead in AgentKInbox.vue). Since 40bb7fccc / frontend 855a7c67 they render in the separate Re-engage inbox (/re-engage/inbox, AgentKInbox with lane="reengage") and follow the Re-engage page's settings (ai_agent_k.re_engage.*, incl. max_per_day, writing, use_history, send_via; the Agent K settings save no longer sends re_engage). The Agent K Feed (lane="prospect") holds outbound + cold imports only; a ?lead= link to the other lane redirects there.

Apollo + PredictLeads (agent_k_provider: 'apollo', default): Apify SoS filings (per-state actors in app/configs/apify.js; the shared pull runs as company_id: 'platform') + Apollo mixed_people/api_search → people/match reveal (1 credit, ≤15/scan) + PredictLeads signals. Signals are always-on (watch_for.* no longer gates lookups; the settings Signals tab is read-only copy).

  • No why-now gate (fb5365a62, 2026-10-30) — like Origami, a revealed person who passes the domain/country checks is queued with or without a signal; no signal stores payload.why_now: null and nothing is claimed on push. Rows skipped no_why_now in the last 30 days are re-queued first on each scan (signal re-checked; re-revealed only when the old skip kept no email — same per-person wallet key, never billed twice). Calibration 👍 leads queue the same way. New-business registrations carry their filing as the why-now. A scan still needs predictleads.api_key (else skipped predictleads_not_configured).
  • Two resumable lanes (221174607) — each scan reads up to LANE_PAGES (4) pages per lane: fresh (companies matching organization_job_posted_at_range since the last completed fresh sweep began; first window FRESH_FIRST_DAYS 30), then deep (the whole match set, wrapping at Apollo's 500 pages / 50k results). Cursor in ai_agent_k.apollo (Mixed: query, fresh {since,page,started}, deep {page}), reset when the query string changes. Before this every scan restarted at page 1 and tenants hit no_new_matches within a week.
  • Never pay for Apollo errors (de933c66c) — teasers with has_email: false are skipped before the paid reveal; _revealPerson throws on an Apollo 4xx before charging, and the scan stops without ledgering anyone (hunt reason apollo_reveal_failed, retried next scan) instead of burning them as no_contact.
  • Every scan is a hunt (provider apollo) — see Hunts.

Gates on every outbound lead:

  • ICP country (1cedc4b1e, ms-ai b57f49be8) — parse-icp now returns a validated ISO-2 icp_filter.country (the model asks rather than defaulting to US; locations must name their country). statesFromLocations only yields SoS states when the country is US (bare "WA" was read as Washington for an AU tenant); _revealPerson returns the person's country and sameCountry() gates discovery, draftFiling and draftProspect. A non-US ICP logs no_us_states_in_icp for the SoS feeder (the inbox explains it). Apollo _resolveOwner now sends filters as query params — a JSON body is ignored by api_search, which then returns the whole unfiltered DB. Self-check: node app/lib/test_agentKGeo.js. Scan and the reach preview share one query builder (0b0ccee43): every location/title is sent (≤25, was first 5/10; the rest come back as dropped), icp_filter.keyword_off drops the one-word q_keywords. last_scan.outbound.reason now comes from discovery — no_new_matches when nobody new matched (the inbox links to calibration); no_us_states_in_icp is no longer reported.
  • Already in CRM (a5979f042) — an outbound prospect that resolves to an existing GHL contact is skipped already_in_crm (reactivation owns those). Inbound is exempt.
  • Crash ≠ burn (93c5a4ece) — a thrown error in the hand-off leaves the prospect pending for a later tick (bounded by MAX_ATTEMPTS) instead of skipped, which used to put the email in the dedupe ledger forever. Own reasons (no contact, suppressed, recently contacted) still burn at once.
  • Revival off stops in-flight (68df164f6) — draftLead and AgentKSequenceJob check re_engage.revive_crm too, so turning it off stops queued reactivation leads and touches 2–3.
  • ICP pivot clears the queue (fececcda4, narrowed by de97d5d27) — AgentKOutboundService.clearQueueIfIcpPivoted(company, before, after) runs on every ICP write (settings save in CompanyController, Nox ICP adjust/revert in NoxAgentKController, calibration confirm before 👍 leads queue). Only when icpPivoted(): both filters have industries/keywords and the new set shares no phrase with the old one. Titles, size, locations, country (checked per lead at release anyway) and ±1 industry keep the queue — paid leads the new search would only re-find, and Origami never returns. Pending and why-now-held outbound_discovery rows go skipped / icp_changed (never deleted — ledger). Unlike a tenant's cleared, a hunt on the new ICP that re-finds one re-queues it (Apollo without a second reveal, Origami via _reevaluateSkip). Seen in prod: dental leads sent under a real-estate ICP. Admin migration POST /admin/agent-k/clear-off-icp-queue ({ apply?, company_id? }, background job, "Clear leads queued under an old ideal customer" card) applies the same rule retroactively: clears waiting leads created before the first hunt on the current ICP, only where an earlier hunt ran on a pivoted one.

Each feeder writes scan telemetry to ai_agent_k.last_scan (at/queued/reason — "never silent"). last_scan defaults to null and a dotted $set can't write into null — that crashed AgentKOutboundJob before any daily hunt ran (bab1fcebf). All writes go through CompanyModel.setAgentKLastScan (pipeline merge, null-safe); one company's write can't abort the run.

Origami (agent_k_provider: 'origami')​

Super-admin switch per company (PUT /company/:_id/agent-k-provider, admin company detail). Replaces Apollo + PredictLeads for Agent K only — Nox visitor enrichment keeps Apollo. Env ORIGAMI_API_KEY (+ optional ORIGAMI_BASE_URL, ORIGAMI_DISCOVERY_TIMEOUT_MS, ORIGAMI_OWNER_TIMEOUT_MS) in both backend and schedular configmaps. Self-check: node app/lib/test_origami.js.

  • Discovery — one Origami search a day built from the ICP brief, continued with fetch-more while the brief is unchanged (nobody found twice). State in ai_agent_k.origami (Mixed: brief, search_id, list_id, running job_id, reject_sample, signal_sample, past_list_ids newest first, dead_list_ids). briefFromIcp uses a calibrated written brief (icp_filter.brief + country gate + rated examples) when there is one; without one the wording is byte-identical to before, so existing searches keep resuming.
  • Out of credits → Apollo (5d54b5f86) — when Origami rejects a search with a 402 or a *CREDIT* error code (origami.outOfCredits; v3 doesn't document it), _origamiDiscovery runs _apolloDiscovery for that hunt (result fallback: 'apollo', standard why-now gate and per-search billing), and a new-business owner lookup falls back to _resolveOwner. Other Origami errors behave as before.
  • Collection (c49a13efd) — AgentKOrigamiCollectJob (schedular, every 5 min; moved out of the hourly job) collects finished searches, so a hunt lands in minutes. Every write that closes a search is conditional on it still being the current one — collector and hunt can't clobber the next search's state.
  • Exclusions (c49a13efd) — a fresh search passes exclude_list_ids = the newest 20 past lists (current list, every recorded hunt's, then origami.past_list_ids; part of the idempotency key). If Origami rejects one, the lists are checked (free reads) and only those it no longer has go to dead_list_ids for good; the rest keep excluding. Before this a prod hunt re-found 23 of 24 people.
  • Failed ≠ resumed (79d4d2353) — collecting a job that didn't succeed (or came back exhausted) clears origami.search_id, so the next hunt starts a fresh search instead of fetch-more on a search that only repeats its failure.
  • No why-now gate (d30b9cf54, 2026-09-25) — the brief asks for the signal columns but doesn't filter on them; origamiVerdict skips only not_qualified and wrong_country. A row Origami scored 0 (failed a required check) is never queued or billed, even with an email (c49a13efd; 9 were historically — see the refund migration below).
  • Re-found skips (3f2b1d087) — a hunt that re-finds someone turned away at discovery (why-now, failed checks, wrong country) re-queues and bills them if they pass today's rules, else records today's reason; cleared and released leads keep their verdict. agent_k_prospects.requeued_by (job id, or requeue_migration) lets the Hunts screen credit the re-queueing hunt. A lead keeps its signal only when recent (≤90 days); otherwise it carries none, so no kk_why_now, why-now note or signal: tag reaches GHL. ms-ai draft-outbound describes a signal-less lead as "looks like the kind of business we work with" (b5dc8fafd); draftProspect keeps the hiring default for PredictLeads prospects only.
  • Row parsing — v3 doesn't document the row format; leadFromRow reads defensively. The signal arrives as one structured research cell ("signal-type": { value: { signal_type, signal_date, why_now } }), which flatten reads after real columns. A Job's row_ids include Origami's own rejects (~21–24 of 25) — excluded/deduplicated rows or rows without the verified email are counted not_qualified, not no_contact.
  • New-business owners — a single-lead search per filing, polled across trickle ticks, abandoned after 6h.
  • Billing — origami wallet step per queued lead (_enqueue reports only real inserts, so re-finding a known lead charges nothing) or owner found; Origami's real credit spend lands in provider_usage as agent_k_origami.
  • Hunts — every Origami Job (daily, manual, calibration) is an agent_k_hunts row; see Hunts.
  • Migrations — the one-shot Origami cards (requeue-origami-leads, seed-origami-lists, refund-rejected-origami-leads) and the older Agent K backfills were deleted on 2026-11-16 (44820dc7e) after they had run. requeued_by: 'requeue_migration' rows from the first still exist.
  • Diagnostics — POST /admin/agent-k/hunt-diagnostics shows brief + search state (+ calibration sessions); zero results name their reasons ("25 rows: 24 not qualified, …").

Hunt now — POST /knox/agent-k/hunt runs the outbound hunt immediately (fresh Origami search each time), returns at once, 2-minute claim on ai_agent_k.manual_hunt_at against double clicks (NoxActionUserController.claimHunt), then watches its own search every 30s for up to 20 min. Gated on agent_k_pacing_visible; the button lives in the pacing panel. Admin Hunt now (d1be6730d) — POST /admin/agent-k/hunt-now { company_id } (super-admin, Agent K Maintenance card) runs the same hunt for any company without the flag, whatever the hour; 202 at once, 429 inside the 2-minute claim; result lands in hunt diagnostics → last_scan.outbound.

Hunts (agent_k_hunts)​

AgentKHuntModel (a70f562b4; Apollo since 221174607): one row per search, provider origami | apollo, manual, calibration, resumed, brief + icp, requested, status searching | done | failed | skipped, reason, error (b0af3800f — the raw provider/exception message, ≤2000 chars: jobError(job) for Origami, the search error or stack for Apollo, "still <status> after N min" for timeouts), repeats, row_ids, credits, charged_usd (Apollo: sum of the wallet charges tagged with the hunt — every Apollo/PredictLeads charge carries hunt_id meta), remaining, exhausted, stats checked/qualified/queued/already_found/not_qualified/wrong_country.

  • Origami — written at start and at collect; timeouts / lost searches → failed. AgentKHuntService reads the Job's rows live (free) and classifies each person — rejected by which required check (is_* false or an empty lookup, with reasoning/confidence/evidence) or, if passed, queued / found before / outside the country / turned away before / not added — from the prospect ledger, so the screen matches what was queued and billed.
  • Apollo — job_id apollo:<company>:<ms>; row_ids are Apollo person ids and the detail reads people back from the prospect ledger (skips keep the revealed card). A scan that never searches is recorded skipped with its reason (queue_full, wallet_empty, no_icp_filter, predictleads_not_configured, apollo_not_configured); identical consecutive skips fold into one row (repeats). Done hunts carry reason wallet_exhausted / apollo_reveal_failed / no_new_matches when relevant; search_failed (no page read) and error (thrown — never left searching) are failed. remaining is null when the deep lane wasn't reached (was a false "about 0 more people"); released people count as checked.
  • Outcomes — passed-but-not-fed outcomes are honest, never a guessed reason (d50f21bb3, 9a6972905, d030cb76e): not_in_queue (no ledger row), cleared (this hunt queued it, then the danger zone cleared it or an ICP pivot marked it icp_changed), requeued_later, rejected_before, and turned_away carrying the release step's skip_reason (already_in_crm, suppressed, tag_failed, old-rule no_why_now/signal_failed, …). These render under All only, never as rejections.
  • GET /knox/agent-k/hunts, GET /knox/agent-k/hunts/:id (tenant-scoped).
  • Frontend views/agentk/AgentKHunts.vue + huntDiagnosis.js (SKIP_REASONS, OUTCOME_LABELS, HUNT_STOP_REASONS, plain-English findings). The Hunts tab renders for every company (a11831fe; was origami-only). A failed hunt shows a details card to every user (1065f252, first super-admin-only in 38d532fa): Reason code, Error, Job id, Started, Stopped (+ minutes), with origami|apollo|predictleads replaced by "provider" (noVendor). Skipped rows read e.g. "Queue already full · 3 times, last …".

ICP reach preview & calibration​

  • Reach preview (0b0ccee43) — POST /knox/agent-k/preview-icp with a draft icp_filter: Apollo match count, a sample, dropped titles/locations past the 25 cap, and widening suggestions (region "Search all of …", keyword "Match any industry wording", size "Any company size", each with its total and a filter patch). Never wallet-charged. Frontend IcpReachMeter.vue on the Ideal customer card (red <50, amber <300, green; hides the keyword lever + limit warning for origami companies).
  • Calibration (1a1581e07, b9b8925b4, bbe2a6763) — AgentKIcpCalibrationService + agent_k_icp_sessions (AgentKIcpSessionModel: one open session per company, abandoned after 7 days idle or on a new start; rounds[] with filter, status running/done/failed, progress, checks, leads[] with fit_score / verdict up|down / reasons, cost_usd; messages[] chat). Routes /knox/agent-k/icp-calibration — GET (current + price + typical duration), POST start, GET /:id, POST /:id/{round,feedback,refine,confirm}.
    • Round = 5 people (ROUND_SIZE), requires filter.country (no_country), wallet must cover 5 of the data step, atomic against a double start (round_running), runs in the background. Apollo: search → people/match reveal (charged per reveal, ≤12/round = MAX_REVEALS, 4 pages; has_email: false teasers skipped before paying; an Apollo 4xx stops the round uncharged and unledgered — progress.failed, "you weren't charged" in chat and on the round card, de933c66c). Origami: a 5-lead search collected on poll, charged once per job (_chargeOrigamiJob, step calibration), recorded as a calibration hunt so daily searches exclude its list; 30-min timeout. Polls record Origami's phase + progress {done,total} and read the rows found so far (free; excluded/duplicate/failed-check rows left out). Cost = wallet drop over the round. Price quote (GET → price): Apollo = MAX_REVEALS × the apollo_match price, to 4 decimals (was 5 × rounded to the cent — always "$0.01"), shown as "up to $X"; Origami = 5 × the per-lead estimate, shown as "~$X". A failed Origami job records its error on the calibration hunt.
    • Every finished/failed round posts roundSummary to the chat (checked, to rate, dropped by reason; an empty search says so).
    • Refine → ms-ai POST /internal/knox/agent-k/refine-icp (45s): Apollo = filter mode (revised filter + changes), Origami = description mode (rewritten brief + change bullets). Proposes only; the country is never changed (ms-ai discards it and, since 7d4f9693f, says to use the "Country you sell in" picker). Failure → refine_failed.
    • Confirm saves ai_agent_k.icp_filter (+ examples.good/bad, ≤5 each, which Origami briefs include) and icp_calibrated_at, after clearQueueIfIcpPivoted against the previous filter. 👍 leads are queued pending with or without a why-now (fb5365a62; the response's waiting_for_signal and the frontend's "added once they show a buying signal" line are gone, c962a270); Origami ones carry origami_billed so queueing doesn't charge again. 👎 leads are ledgered skipped / icp_rejected so no hunt finds or bills them again.
    • Admin: GET /admin/agent-k/calibration-stats (sessions, rounds, up rate, avg rounds to confirm; Maintenance card).
    • Frontend views/settings/ai/agents/AgentK/IcpCalibrationModal.vue + calibration/{IcpPanel,BriefPanel,RoundBody,LeadCard,AgentChat}.vue: 3 panes (ICP with undo | rounds, Y/N keys | chat), steps Find → Rate → Adjust → Save, country picker first (49c68bed — offers the locations' countries, blocks Find until set, offers to drop foreign locations); paid actions live only in the footer ("Use the suggestion & find 5 more" / "Find 5 more without it"). Opened from the reach meter or ?tab=icp&calibrate=1 (the inbox's no_new_matches line). Editing chips after calibrating drops the saved brief.
  • ICP read on save (frontend 5d1a4458) — a parsed filter records the text it was parsed from (icp_filter.parsed_from; legacy unmarked filters are re-read once). A failed read blocks the save when the description changed (it used to save new text over the old filter, which then counted as read and the stale chips came back on every refresh); Save is disabled while a read runs. The agents-card switch and the inbox auto-push toggle now send only the key they change — echoing the store's whole ai_agent_k reverted ICP/Outreach edits.
  • AI paused (2992bb9dc) — parse-icp forwards ms-ai's 402 body (AI paused, empty wallet) instead of a generic 502, so the UI shows the top-up message.

Queue & pacing​

agent_k_prospects (app/models/AgentKProspectModel.js) — status pending | drafted | skipped, unique (company, source, external_id) doubles as the dedupe ledger. AgentKTrickleJob (every 5 min) releases only inside the company's working hours (working_hours + timezone), with a jittered 6–20 min gap, burst 1–3, ranked by AgentKSourceWeightService.scoreProspect. Daily cap = ai_agent_k.daily_limit (default 10), counted from lead_lifecycle_events with stage pushed + legacy drafted since local midnight. Imported rows (source: 'import') are invisible to the trickle, the queue bound and the daily count — AgentKImportJob releases them.

  • Review feed — ai_agent_k.auto_push default false: released leads wait in the feed for a manual push; true pushes automatically.
  • Pacing read — GET /knox/agent-k/pacing answers with the trickle's own decision: queued, released today, next release window, and which of off / closed / capped / empty / cooling holds it (AgentKTrickleJob.nextOpen names when a closed account opens). Super-admin gated: per-company agent_k_pacing_visible (default false, PUT /company/:_id/agent-k-pacing, "Agent K queue status" toggle on admin company detail); the endpoint refuses when off. Frontend AgentKPacing.vue ("Next lead in ~8 min", "Resumes …").
  • Notifications — each release batch sends one agent-k-lead notification (NotificationHelper.NOTIFICATION_TYPES.AGENT_K_LEAD) carrying lead_action_id for the lead it names first. It's tier 2 push too (c455bdc67) — daily push cap, quiet hours and the user's agent_k notification pref apply. Frontend components/AgentKLeadToast.vue (own sound agent-k-lead.mp3, "Open lead" / "View leads", no timeout) + desktop notification. AgentKDailyPushJob still sends the once/day throughput push.
  • The trickle also fires the lead_found rule event.
  • Clearing the queue — GET/DELETE /knox/agent-k/leads/review[?source=] (settings danger zone) deletes Agent K's own review-bucket NoxActions and, per source (outbound | reactivation | knockid), clears the prospects queued behind them (inbound has no queue, so it skips the queue rather than clearing others'). Queued prospects are marked skipped / cleared, never deleted (9a6972905) — they are the dedupe ledger, and deleting them let a later hunt find, queue and bill the same people again. _enqueue now logs a non-duplicate write failure instead of counting it "already found". Deleting refunds credits reserved by rule lookups on those leads and removes LinkedIn enrollments stuck at awaiting_connect_approval (the enrollment upsert keys on (company, linkedin_url), so a stranded one blocked re-enrolment forever).

Lead imports (CSV)​

7fca67e5e / frontend 372f8340; released immediately since 38d317780 / b38f66b2 (the per-list per_day pace and its UI were dropped). A tenant uploads their own list; each row becomes an Agent K lead through the normal pushLead path (CRM or mailbox, email sequence, lead_found rules, costs).

  • Model agent_k_imports (AgentKImportModel): name, file_name, tag (slug → CRM tag nextlevel list:<tag>), known (past customers / enquiries → re-engage draft and the Re-engage lane), skip_existing (default true), reason (fallback why-now when a row has no notes), consent { by, at, text } (server-stamped CONSENT_TEXT), status running | paused | cancelled | done, rejected counts by reason, total. Rows live in agent_k_prospects with source: 'import', import_id, external_id = email or phone:<digits>; prospect status gained paused.
  • Check (AgentKImportService.check, local only — no CRM calls): shape() per row (invalid_email, invalid_phone 7–15 digits, no_contact), duplicate_in_file, already_imported (any earlier import), do_not_contact (do_not_contacts by email/phone), needs_email when routing is mailbox (a no-CRM lead is keyed on its email). MAX_ROWS 5,000 (400 above).
  • Release — AgentKImportJob (schedular, every minute, running imports, ≤MAX_PER_TICK 20 pending rows per list per tick for fairness) → AgentKImportService.release → pushLead with source: 'import' and context.import { id, name, tag, known, skip_existing }; settles rows with AgentKTrickleJob.settle (retry/attempts like the trickle), marks the import done when nothing is pending/paused. No working hours, no pacing, no daily limit: the trickle, _queueRoom and releasedToday() all exclude source: 'import'. Emails still obey daily_send_cap.
  • Push rules — imports are cold (COLD_SOURCES = outbound, reactivation, import; pushLead now stamps context.source on every path, so deferred / auto-push leads are no longer read as warm). Existing CRM contacts are skipped already_in_crm unless skip_existing: false. A known list drafts as re-engage with "Why you're writing to them: …" and the Re-engage writing settings.
  • Endpoints (agentKAutomationRoutes.js, AgentKAutomationController): POST /knox/agent-k/imports/preview { rows } → { ready, rejected[{row,reason}] } (writes nothing); POST /knox/agent-k/imports { rows, name, file_name, known, skip_existing, reason, consent: true } (400 unless Agent K is on); GET /knox/agent-k/imports (≤100, each with progress { queued, started, skipped, skip_reasons }); PATCH /knox/agent-k/imports/:id { action: pause|resume|cancel } (cancel skips the rest cancelled).
  • Lead query — agentKLeadQuery takes source (outbound|reactivation|knockid|import) and import_id.
  • Frontend — views/agentk/AgentKImportDialog.vue (Upload → Match columns → Review → Start; leadImport.js: RFC 4180 parser with ,/;/tab detection, header alias guessMapping, sample CSV, rejected-rows CSV with formula-injection escaping, REASONS), AgentKImports.vue (list, progress, Pause / Resume / Cancel the rest, Show leads). Rail button "Import leads" / "Imports (N)" (prospect lane, Agent K on), "Imported" chip, Filters → Source / List, contact pane "Imported by you".

GHL push (app/services/AgentKPushService.js)​

pushLead() order: suppression check (NoxGhlActionService, 72h per-contact cooldown) → create the contact untagged → mint kk_token and write it in its own field write (a rejected enrichment field can't drop it) → other custom fields → why-now note (Agent K — why now: …, agency-renamed) → trigger tags → (HubSpot task delivery) → NoxActionModel status pushed + pushed_at (stamped on every push path) + lifecycle + funnel enterFunnel. Tagging only after the token is written (8f0fe2436) means the tenant's workflow never fires with a blank {{contact.kk_token}}. pushLead copies the owner's email/phone/name into context.person, where automation steps read them (80c338d85; website leads used to carry a name only).

GHL contact creation is gated on approval — no contact exists in GHL until the lead is pushed (manually, or auto with auto_push).

  • Custom fields write by field ID — resolved once per name and cached in go_high_level.kk_field_ids (Mixed map; go_high_level is a strict subdoc — cache keys must be schema'd or writes drop silently). kk_token / kk_why_now are fixed; linkedin_url / job_title names are tenant-configurable via ai_agent_k.ghl_fields (blank = skip; UI now under Integrations → LeadConnector). Native GHL fields (company/website/city/state/ country) fill directly. Field and note writes are best-effort. No signal = no kk_why_now, no note, no signal: tag.
  • Tags are the workflow trigger — all prefixed nextlevel (with space): nextlevel agent-k-lead, nextlevel signal:<type>, nextlevel source:<src>, plus nextlevel returned-to-site written on kk-click. A tag write failure fails the push (reason: 'tag_failed'); everything else is best-effort. Tags are never renamed by the agency Agent K name.

HubSpot as Agent K's CRM​

15fda18a9 / a71bf7577 / 24c614a4a (push mode only). _crmFor = crm.resolveProvider(company, { capability: 'tags' }) — GHL when connected, else HubSpot, one per company; lead rows record crm_provider, kk_tokens keep hubspot_contact_id. Feeders, reactivation, push button, kk-token sync, rules/bulk, reveal writes and the lead thread go through the CRM port. HubSpot "tags" are the kk_tags contact property (per-contact Redis lock); fields map to fixed KK properties (kk_token, kk_why_now, kk_source, kk_signal, kk_linkedin_url, jobtitle), not ai_agent_k.ghl_fields. ai_agent_k.crm_delivery workflow | task (default workflow): task creates a HubSpot task per pushed lead (why-now + personal ?kk= link) and a task failure fails the push (task_failed) like a tag failure. HubSpot has no 1:1 send API, so Mode B on HubSpot sends only via the tenant mailbox (mailboxRouting.senderFor); without a usable mailbox it's push mode and the frontend hides the send option. Lookup failures retry instead of creating duplicates. Full integration: HubSpot.

Routing & the tenant mailbox​

35a5dd8dc (backend) / 605109b6 (frontend). The tenant chooses; nothing is auto-swapped. lib/mailboxRouting.route(company) → { provider, sender }, mirrored by frontend agentKRoute in src/common/helpers/agentK.js (keep them in step):

  • ai_agent_k.crm auto | ghl | hubspot | none — auto = first connected (GHL, then HubSpot) via crm.resolveProvider(…, { capability: 'tags', requested }). A chosen CRM that's disconnected is NOT swapped for another one. none (or no CRM connected) → provider: 'mailbox' when the mailbox is usable (usableFor(box, 'agent_k'): email set, status ≠ error, use_for.agent_k ≠ false), else null (nothing to deliver to — the agentKBlocker banner).
  • sender (senderFor) — mailbox provider → always mailbox. Otherwise null unless mode === 'send'; GHL with send_via === 'mailbox' → mailbox if usable, else null (push only); GHL otherwise → ghl; HubSpot → mailbox if usable, else null. send_via auto | crm | mailbox (UI saves crm / mailbox; anything but mailbox = GHL).
  • AgentKPushService.pushLead treats sendMode = !!sender — a mailbox tenant never parks leads for review (_defer), it drafts and the auto-send grid decides. SENDING_COMPANIES (mode: 'send' OR a mailbox with use_for.agent_k ≠ false) feeds AgentKSequenceJob / AgentKAutoSendJob; feeders query connectedQuery(['ghl', 'hubspot', 'mailbox']).
  • No-CRM ids — crmContact.mailboxId(email) = mbx_<base64url(lowercased email)>; crm_links[0].provider = 'mailbox', ghl_contact_id blank. isMailbox / mailboxEmail decode. No contact create, fields, note or tags (_deliver returns ok); "already in CRM" can't apply. A lead parked pending_push for a CRM can't be pushed once routing says mailbox (crm_changed / crm_not_connected).
  • Per-sequence pin — touch 1 sent from the mailbox stamps context.send_via: 'mailbox'; viaMailbox(action) (mbx id OR that stamp) routes every later touch, so a later send_via change doesn't split a thread. Only an explicit crm_links[0].provider names a record's CRM — legacy ghl_contact_id rows use the company default.
  • Send — NoxGhlActionService._sendViaMailbox: email only; recipient = decoded mbx address or the CRM contact's email; appends an Unsubscribe footer + List-Unsubscribe / List-Unsubscribe-Post: One-Click (RFC 8058, public GET|POST /mailbox/unsubscribe, HMAC-signed, never expires — GET only renders a button because scanners prefetch); threads onto the last sent email (Re: + In-Reply-To/References, answering the lead's own reply meta.message_id when newer). Never falls back to platform mail — a failure throws Couldn't send from your mailbox: ….
  • Replies — MailboxReplyJob (schedular, every 5 min) → MailboxService.pollReplies; only mail from addresses matching mailboxRouting.leadQuery reaches handleInboundReply; bounces (mailer-daemon/postmaster, Final-Recipient) suppress (reason: 'bounced') and dismiss open drafts. Unsubscribe link → addSuppression (unsubscribed).
Deploy

Agent K mailbox sends and MailboxReplyJob run in the schedular, which decrypts the SecretCrypto password — SECRET_ENCRYPTION_KEY must be identical in the backend and schedular secrets (schedular secret.sops.yaml got it 2026-10-16). A mismatch makes credentials() return null (warn log "SECRET_ENCRYPTION_KEY differs?") and every mailbox send fails.

Smoke test: scripts/smoke-agent-k-mailbox.js (GreenMail). Mailbox module details: Tenant Mailbox.

Mode B — Agent K sends (ai_agent_k.mode = 'send')​

  • Inputs (ai_agent_k.send.*): offering, link_url ([LINK] marks placement), touches.{t1,t2,t3} overrides, touch_mode guide | verbatim (default guide).
  • AgentKSequenceJob (hourly) — touch 1 drafts at push time; touches 2–3 draft ~3–4d / ~4–5d after an unanswered send (GAPS_MS, PER_COMPANY_CAP 20/tick). No copy from ms-ai = touch skipped.
  • Daily send cap — ai_agent_k.daily_send_cap (default 40, UI 10–150), counted from the tenant's midnight (agentKRules.dayStart, DST-safe).
  • Sequence read — GET /knox/actions/sequence?ghl_contact_id=; Mode A returns mode: 'push' with an empty ladder.
  • Reply suppression + stop-intent — inbound reply dismisses pending drafts (handleInboundReply, treats pushed as outreach); _classifyStopIntent → ms-ai POST /internal/knox/agent-k/classify-reply (fails open stop=false; AGENT_K_STOP_MODEL override — seed a cost price row first). See Do-not-contact for what counts.

Do-not-contact trail​

do_not_contacts (DoNotContactModel): reason one of unsubscribed, dnd, bounced, manual, complaint; source one of reply, unsubscribe_link, mailbox, call_outcome, manual.

  • Evidence (756321ada) — every writer appends to events[] ({ at, reason, source, evidence }, Mixed evidence): reply text + matched keyword or detected_by: 'ai', channel, subject, contact id, had_outreach; unsubscribe click (one_click, IP, UA); mailbox bounce (from, subject); call outcome (outcome, by, note); manual (by = user email). GET /knox/suppressions excludes events.
  • Trail — GET /knox/suppressions/:id/trail → { entry, audit, outreach, lifecycle, recovered }: audit_logs for the record; outreach = NoxActions by context.person.email / to_phone (≤50 — an unindexed company-scoped scan, on demand only); lifecycle events by the outreach's CRM ids.
  • Recovered evidence (595f3cc2b) — an entry with no events and source reply/blank calls NoxGhlActionService.recoverSuppressionEvidence: finds the CRM contact (outreach ids, else by email/phone), reads adapter.incomingMessages (new on GhlAdapter + HubspotAdapter) up to 5 min after the block, keeps SMS/email/WhatsApp, newest 3, each flagged with stopKeyword (and quoted_keyword when the word is only in quoted text). missing: not_in_crm | unsupported_crm | crm_error.
  • False-DNC fix (b56f031bd) — GHL InboundMessage only enters the reply loop for SMS/Email/WhatsApp messageType (live chat, calls and activity rows — including our own chat/call mirrors — were read as email replies and AI-classified as opt-outs). stopKeyword = anyStopKeyword(freshReply(t)): strong words (unsubscribe / opt out / remove me) anywhere, bare "stop" only in ≤40 chars, both only in the text above any quoted/forwarded block; the AI classifier also only sees freshReply.
  • Re-check migration — POST /admin/maintenance/recheck-dnc-replies { apply?, companyId? } (background job, lib/recheckDncReplies.js; Admin → Integrations Maintenance "Re-check Agent K do-not-contact entries"): removes not_a_reply and quoted_only entries; keeps real opt-outs, AI-classified ones (needs_review) and unverifiable ones.
  • Frontend: Do-not-contact tab "Why?" → SuppressionTrailModal.vue (time-ordered evidence + outreach + lifecycle + audit; recovered messages as "Likely trigger" / "Other message").

Language (de172c75a, ms-ai 7f17d411a)​

Agent K writes in company.language (Settings → Organization → Language; NoxGhlActionService.companyLanguage, default en; en-* = English, no translation call). effectiveAgentKTemplate passes it to the ms-ai drafter (subject + body; [LINK], signature and JSON keys kept); suggested replies and preview get it too. Short fixed copy goes through NoxGhlActionService.localize → ms-ai POST /internal/knox/agent-k/localize (10s; faithfulness rule, optional max_chars, context; any failure or implausible output returns the original): the LinkedIn connect note and first DM at draft time (dedupe stays on the English note) and the why-now before the CRM push (WHY_NOW_CONTEXT keeps it third person). The mailbox unsubscribe footer comes from a fixed UNSUBSCRIBE_TEXT map covering the three Organization language options (en, sv, ar; anything else falls back to English). The same commit makes blank call-agent languages inherit the organization language (see the call-agent docs).

Auto-send grid (app/lib/agentKAutomationPolicy.js)​

ai_agent_k.automation.auto_send = { email|sms|call|linkedin: { warm: ask|auto, cold: ask|visit|auto } } (9c119c4ed) is the answer to "does this go out without asking?". cold = found by outbound or reactivation (COLD_SOURCES); a cold lead is "engaged" (visit) once they've been on the site themselves. null = fold from the legacy fields (sending_mode, automation.sms_approval, automation.cold_policy), never more automatic; the frontend mirror is views/settings/ai/agents/AgentK/autoSend.js — keep them in step.

  • sendAllowed() replaces the per-path checks in NoxGhlActionService and AgentKActionRunner; NoxGhlActionService.autoSendDecision is the one caller and records send_rule / sent_by on the NoxAction (send receipt). Inline auto-send drafts (rebook, draft-batch) go through AgentKPushService._autoSend, so the send cap counts every autonomous email.
  • Push mode forces email to ask/ask (9099919e5) — policyOf reads the email row as ask outside mode: 'send' (saved value kept for a switch back), so no rule/bulk email sends next to the tenant's GHL workflow sequence.
  • UI is Emails + LinkedIn invites only (Settings → Agent K → Sending); sms/call cells still exist but rules and bulk runs no longer consult the grid (eb1f402f6, below).
  • Cold consent — any cold: 'auto' needs automation.cold_ack ({ by, at, text }, server-stamped; text in the words the tenant saw, agency name included) via accept_cold_ack on the settings save.
  • AgentKAutoSendJob (schedular, every 15 min) re-tries recent email drafts the grid now allows — quiet hours over, cap reset, the prospect visited — within a 3-day window. nox_actions.send_hold records why an automatic email waits (quiet_hours with the recipient's 9am, daily_send_cap until tenant midnight, awaiting_visit), cleared when nothing holds it; the feed renders "Sends 4:00 PM / tomorrow / after a visit".
  • Recipient timezone (48b6d30ce) — Agent K-created CRM contacts carry no timezone, so the quiet-hours check used to fail open and emails went out at the recipient's night. AgentKPushService._recipientTimezone now resolves: CRM contact timezone → context.recipient_tz (stamped on touch 1 from enrichment via lib/zoneForLocation.js — country, plus region for multi-zone countries like US/CA/AU — and carried on later touches) → the contact's own state/country → the tenant's timezone. _autoSend calls _isQuietHours(…, { failClosed: true }): no zone at all = held.
  • LinkedIn row (e74e64765) — applies to Agent K's own invites as drafted; the 15-min sweep sends waiting ones (14 days) within the daily cap, never while the acceptance breaker is tripped. Legacy accounts stay ask.
  • Shared guards (company knox.*, shared with Nox): quiet_hours {start_hour 9, end_hour 18} in the recipient's tz; frequency_cap {enabled, max_sends 2, window_days 7} (off switch honoured by checkOutboundAllowed, numbers survive off); spacing {enabled, minutes 45} (nox_funnel.actions.spacing, bab1fcebf) replaced the hard-coded 45-min gap — read by the gate and ScheduledNoxActionJob deferral. All editable on the Agent K Sending tab; normalizeAutomation files them in nox_funnel.actions.

Automations (rules + bulk runs)​

Controller app/controllers/AgentKAutomationController.js, routes app/routes/agentKAutomationRoutes.js; services AgentKRuleService (evaluate/fire), AgentKAutomationService (chains, waits), AgentKActionRunner (steps), AgentKBulkService. Every decision (fired, skipped + reason, per step) is logged to automation_events and fed into Nox Activity. Frontend: the Automations page (/automations, sidebar Build group; views/automations/Automations.vue, AutomationLogs.vue) — moved out of the Agent K page (debc0405) and later out of Agent K settings; see Automations for the page and this window's triggers/steps, and Campaigns for campaigns, which run on the same engine.

Rules (automation_rules, app/lib/agentKRules.js)​

trigger { type, score_threshold, only_live, page_contains }
conditions { sources[], signals[], require_crm, not_contacted_days, funnel_stages[], min_score }
graph { nodes[], edges[] } (lib/agentKGraph) — or legacy linear `steps`
limits { per_day 20, daily_credit_budget 500, cooldown_days 30 } (no longer on the form)
cold_limit { call, sms, email, linkedin } — only ever stricter than the company
enabled + dry_run (UI: Off / Dry run / Live; a new rule saved Off keeps dry_run true)
counters today's fires + credits, reserved atomically at the tenant's midnight
paused_reason / paused_at self-pause (budget, failures) with a notification

ai_agent_k.automation.rules_paused is the kill switch ("Pause all rules"). Rules only count visits the lead made — never an enrichment-guessed contact or an unverified person.

One draft per repeat visitor (fb5365a62) — website-visit rules key a visitor without a trusted person by session email (email:<addr>), not per session (each return used to re-run every rule and draft again). When a run creates the CRM contact, the cooldown claim is copied to that contact id, and the email step re-checks AgentKAutomationService.stoppedFor on a contact matched late (booked / replied still stops it).

Triggers​

A rule has triggers[] (≤MAX_TRIGGERS 5, 4658caa97; trigger = triggers[0] for old readers, triggersOf() folds legacy rules) — any one starts it, once per lead per re-entry period; matching triggers are tried in order, so a first_visit that isn't one gives way to a page_view.

  • score_crossed (default for old rules without trigger.type; GeneralHelper.updateLeadScore → AgentKRuleService.onScoreChange).
  • engaged { engagement_threshold 1–100 } (80c338d85) — a visit's engagement score crossing N, via onEngagement from POST /internal/knox/visit-engagement (below).
  • Event triggers via AgentKRuleService.onEvent (e5b045f2f): first_visit (once per lead), visited (the page view that starts a visit — none in the last 30 min — or an Agent K email click), email_click (kk-click), page_view (socket page view, page_contains), form_submitted (form endpoint), lead_found (trickle, and since 80c338d85 website leads from the inbound / engaged paths), funnel_stage_changed { from, to } (fired from FunnelStageService on every real move).
  • email_no_visit { emails, days } — AgentKEmailNoVisitJob (schedular, hourly) fires once days have passed since a lead's Nth email (Agent K's own send, or LC Email delivering one) with no visit since the first. LC Email "delivered" events for Agent K leads are recorded as a delivered lifecycle stage (GhlNativeEventHelper), only while the company has such a rule. Lookback is one day past days — a schedular down a whole day misses leads.

conditions.min_score is optional on event triggers. Rules are cached one minute only to decide whether any could match; candidates are re-read before acting, so switching off/auto-pause stops at once. Page-view repeats stay out of the log (cooldown silent, other skips once a day).

Workflows (app/lib/agentKGraph.js, e74e64765)​

graph { nodes: [node], edges: [{ from, to, branch }] }
node { id, type: action|wait|if, action?, options, approval?, position }
edge from 'start' or a node id; branch 'next', or 'yes'/'no' from an if

Validated: no cycles, all connected, ≤MAX_NODES 40, waits ≤30 days, a call_answered check only after a call. Actions: reveal_phone, reveal_linkedin, ai_call, sms, email, linkedin_connect, engage, push, tag (CRM tags), notify (team notification opening the lead), and manyreach (4658caa97, AgentKActionRunner._manyreach): adds the lead to options.campaign_id (name kept in options.campaign_name) via ManyReachService.prospect() with an agent_k-source kk token and the tenant's campaign links. No approval queue — a lead the grid/cold limits wouldn't let be emailed unasked is skipped cold_limit; also skips no_email, manyreach_not_connected, the email gate (DND/suppression), and fails manyreach_key_rejected on 401/406. Checks (IF_CONDITIONS): came_back, replied, clicked, booked (since the last wait), call_answered, has_phone/email/linkedin, in_crm, score_at_least. Old linear rules run and open as straight lines; bulk runs use the same engine.

  • A run parks on the lead with its own copy of the workflow (context.pending_chains) — waits, lookups, not-yet-known checks. AgentKRuleWaitJob (every minute) resumes due waits; chains waiting on a lookup resume when it settles (several may wait).
  • Budget reserves the costliest path (maxPathCost) and refunds what the run never reached; a lookup squares its reservation against real cost.
  • Text if unanswered (5f8916e2d) — legacy linear option options.when = 'call_unanswered': the SMS task depends on the call task; ScheduledNoxActionJob sends it only on no-answer/busy/voicemail, cancels on answer, waits while the dial is in flight, and a conversation counts as answered only after a 2-min window for voicemail analysis. A waiting task is rescheduled to its dependency's time. In graphs this is ai_call → if call_answered → no: sms.
  • Rules and bulk runs send as set up (eb1f402f6) — their steps go out via automationAllowed / autoSendDecision({ automation }) → send_rule: 'agent_k_automation', bypassing the grid. Quiet hours, DND, suppression, frequency cap and daily send cap still apply; the spacing gap doesn't (override cooldown). A step saved "always asks" and a rule's cold_limit still hold. Reaching cold leads needs consent on record: saving such a rule or starting such a bulk run records it via accept_cold_ack, else 409 cold_consent_required (bulk dry runs report consent_needed).
  • Agents without a number — a call/text step whose agent has no phone is skipped at queue time (sms_agent_no_number / call_agent_no_number; a cached "no" is re-asked first); the editor warns up front.
  • Test — POST /knox/agent-k/rules/:id/test explains (never sends); POST …/run evaluates with explain off (super-admin agent_k_lab_enabled), dropping this rule's cooldown claim (automation_claims) on that lead first.
  • Queue — rule/bulk call and text tasks are ScheduledNoxActions with created_from: rule | bulk; GET /knox/actions/scheduled?created_from=rule,bulk feeds the Agent K page's queue panel (useApprovalsPanel.js, ScheduledTaskList.vue); approvals live there, not on the Nox Activity screen.
  • Email links carry the token (8f0fe2436) — template emails (_fromTemplate) turn {{link}} / [LINK] into the minted tracked link and append kk to any URL on the tenant's own host (AgentKActionRunner.trackLinks); AI emails load website_url so a link is minted even with no send link.
  • Frontend editor (54e5d664, Vue Flow removed; now views/automations/WorkflowEditor.vue + workflow/) — GHL-style top-down builder (trigger cards + "Add New Trigger", "+" on every line via workflow/AddStepButton.vue, If / Else → Yes/No columns in WorkflowBranch.vue, END, "Go to" for joined paths, searchable ActionPicker.vue from workflow.js LIBRARY, side panel StepSettings.vue); tabs Builder / Settings (conditions + editable limits) / Execution logs (the rule's automation log); status Draft / Test / Published = enabled/dry_run. Save is blocked client-side for a trailing wait or an empty If / Else; a server error opens the step or trigger. Labels in common/helpers/agentK.js (AUTOMATION_STEPS, IF_CONDITIONS, RULE_TRIGGERS, MAX_TRIGGERS, workflowLine).

Bulk runs (agent_k_bulk_jobs)​

POST /knox/agent-k/bulk over leads picked by id or by the inbox filters (visit score, visited/live, has phone/LinkedIn/email, CRM state), capped at AgentKBulkService.MAX 500, dry-run preview first, one run per company, survives per-lead errors and restarts (GET /knox/agent-k/bulk/current, /bulk/:id). POST /knox/agent-k/bulk/eligible returns per action how many of the selection it applies to and the main reason for the rest (same ineligible() rules as the dry run).

Test bench (super-admin agent_k_lab_enabled)​

PUT /company/:_id/agent-k-lab. POST/DELETE /knox/agent-k/test-lead[/:id] (AgentKTestLeadService) builds a lead from typed contact details with a stub visit; POST /knox/agent-k/test-lead/:id/score moves the visit's score and runs score rules for real, awaited, returning each rule's outcome. Rows carry context.test_lead; reports exclude them by contact and by visit.

Highly engaged visitors (80c338d85)​

ms-sessions (c3d05dd) posts POST /internal/knox/visit-engagement { company_id, user_session_id, from, to } when a visit's engagement score rises (NoxActionController.visitEngagement; deploy backend before ms-sessions). AgentKPushService.pushEngagedVisitor: needs ai_agent_k.enabled + re_engage.engaged_visitor (default off), the score crossing re_engage.min_engagement (default 70, UI 10–100), a non-bot session with verified_person_id (never a guess), and releasedToday() < daily_limit (drafted + pushed lifecycle events since midnight). Then pushLead with source knockid, signal deep_engagement (tag nextlevel signal:deep-engagement), why-now "Spending real time exploring your site" — still deferred to the review feed unless auto_push. Fires lead_found and the engaged rule trigger.

Lead inbox (/knox/actions/*)​

  • Counts (fff591b31) — GET /knox/actions/pending builds every tab, channel and signal count in one $facet over index keys (feedCounts), covered by { company_id, status, agent, kind, ghl_lead, signal_type, created_at, updated_at }. ghl_lead (set in _defer) replaces push_payload null checks — a Mixed blob can't be indexed; backfilled at boot with timestamps off (delete the boot backfill once it has run).
  • Search — q on the shared lead query (app/lib/agentKLeadQuery.js), case-insensitive, regex-escaped; ?id= opens one lead.
  • Visits (AgentKLeadVisitService) — sessions by GHL contact or person; list rows get {count, best score, live ids}, plus GET /knox/actions/:id/sessions and /knox/actions/visits (socket refresh). A visit's score is the ms-sessions engagement score; the lead score rides alongside (top_lead_score, per visit) because rules trigger on it (5afa428b7). Scores come from one indexed visitor_profiles read after grouping sessions, not a $lookup per session (49ac05d90, ~6.5× faster). Sessions are found with one indexed find per link (contact / verified person / email-click person / own session), run in parallel and attributed in code with the same trust rules (5e3a0f0d3) — the old single $or aggregate read every session the company had (8.3s of 8.5s on /knox/actions/pending in prod).
  • Thread — GET /knox/actions/:id/thread merges the CRM conversation with our agent texts, AI calls and scheduled/failed tasks, matched by lead id and phone (leads not in the CRM yet). Calls a GHL workflow placed have no task — found via the contact's call:<sid> accounting rows (58a17b805). Designed template emails (full HTML documents) render in a sandboxed components/EmailFrame.vue iframe — sanitised, scripts and the kk token stripped, own stylesheet kept, subject on top (49595ac5); plain/simple HTML keeps the bubble. The thread label uses the lead's own CRM.
  • Named calls/texts (3b92783da) — tasks carry the lead's company; the SMS webhook passes recipient name + lead id so the Chats conversation is named and linked; SMS sessions are created inactive; blank merge fields drop their lead-in. Frontend: Calls "Agent K lead" chip, Chats "Texted by Agent K · Open the lead".
  • Call / text a lead — schedule-call accepts now: true; POST /knox/actions/preview-sms returns the exact text the SMS agent would send (policy in lib/smsAgentPolicy).

Leads tab — call list (AgentKHotLeadService)​

8174a356f, 8dfdd172c, 0fc876a62, eb09c13fd; frontend 909177ab, 97db788a, ab047b59, f87131d2.

  • GET /knox/agent-k/leads → list(company_id, { everyone: true }): every delivered lead (buckets().DELIVERED, capped at AgentKLeadVisitService.FILTER_MAX_LEADS), one row per person — personKey = CRM contact id → email → phone digits → _id, because AgentKPushService re-pushes a contact after the 72h cooldown. Row = newest push + best visit summary + merged call_log / call_outcome / led_to_meeting + AI calls/texts (reach) + journey (first pushed / sent / clicked / replied / booked per contact from lead_lifecycle_events). delivered counts people. GET /knox/actions/hot-leads (visited only) is kept for the old frontend — remove once the Leads tab is deployed.
  • Legacy pre-push rows (context: {}) get a person at read time (lib/agentKLeadPerson.fillMissingPeople: profile by CRM contact, else the lead's own trusted session) — also used by the inbox list and reveal lookups, which otherwise failed no_identity.
  • Visit dates = session start or analysed end, never updated_at (the 2026-09-05 crm_links backfill bumped it), except while live; summaries carry visit_ats for per-period counts; top pages fold tracking params, anchors and trailing slashes.
  • lifecycle-summary?keys=1 returns which contacts each stage counted (tile drill-downs); report-details?journeys=0 skips the per-lead journey table.
  • POST /knox/actions/:id/call-outcome (logCall) — OUTCOMES: no_answer, voicemail keep the lead open; interested, booked (sets led_to_meeting), not_interested, wrong_person close it (call_outcome). The last two also addSuppression (reason: 'manual', source: 'call_outcome') and tag the CRM contact nextlevel call:not-interested / nextlevel call:wrong-person. CRM note + tag are best-effort.
  • Frontend AgentKLeads.vue (period picker + tiles) wraps AgentKLeadList.vue (To call / Called / All leads, chips, sorts, CSV export, drawer with Why call now / Journey / Log the call). "To call" = hotLeadTabs: top_score ≥ HOT_SCORE (70), no closing outcome, visited ≤ CALL_WINDOW_DAYS (30). Delivered / Visited tiles count from the rows; Found / Emailed / Replied / Booked from keys. Local seed: scripts/seed-agent-k-leads.js (--clean).

On-demand lookups (AgentKRevealService)​

POST/GET /knox/actions/:id/reveal/:field (phone | linkedin): Apollo people/match (phone via webhook POST /agent-k/apollo-phone/:id/:token, LinkedIn inline) or an Origami single-lead search, per agent_k_provider. Charged per attempt, found or not (wallet must cover one first; idempotent on the attempt id) as wallet steps phone_reveal / linkedin_reveal. Found values are written to the GHL contact with crm_synced recorded; POST /knox/actions/:id/sync/:field retries a failed write. Apollo errors are retryable, never a saved "not found". Timeout TIMEOUT_MS 30 min. AgentKRevealSweepJob (every 5 min) settles lookups nobody is watching — collects finished Origami searches, times out Apollo webhooks — so waiting rule chains resume.

kk_token & click stitching​

  • kk_tokens (app/models/KkTokenModel.js) — one token per (company, GHL contact), or per email for external campaigns; denormalized email/phone/name so click resolution needs no GHL call. Every GHL template link appends ?kk={{contact.kk_token}} — the token lives on the contact.
  • Inbound gate — PersonResolverService skips Agent K inbound for self-reach-out identifications (SELF_REACHOUT_SOURCES: form, chat_form, chat, call, inbound_call, booking) while skip_self_reachouts is on (dee9adfc0 added chat forms, calls and bookings).
  • POST /user-session/kk-click (UserSessionController@kkClick): bot filter (client flag → scanner-UA regex → IP check) → token lookup → PersonResolverService.resolve stitches the identity onto the session → writes nextlevel returned-to-site → funnel link_click/web_visit signals → email_click rule event → widget auto-engage of the returning lead (cooldown knox.visitor_watch.auto_engage_cooldown_hours). On the session's first click (!email_click_at) it also dispatches the new_user_identified webhook with the token's contact (source: 'kk_token', 751f071bb) — new_session fires before the stitch and never carried it, so ManyReach-token tenants on their own CRM got nothing.
  • Attribution: a kk visit is credited to whoever minted the token — one rule, kkTokenSource() in app/lib/trafficSource.js (dee9adfc0), used by both the per-visit pageArrivalSource and the kk-click stamp: mapping.source wins; a legacy source-less token is agent_k only if Agent K worked that contact (a NoxAction with agent: 'agent_k'), else ghl_backfill; contact-less = manyreach; an unknown token falls through to UTM/referrer. (The page path used to credit Agent K for any source-less token, so a tenant's own CRM email read "Agent K Outreach".) The nightly funnel seed skips ghl_backfill/manyreach mints — the token backfill stamps the tenant's whole contact list, which had labelled every contact "Agent K" (see Nox Funnel).
  • Backfill: POST/GET /knox/agent-k/kk-backfill stamps kk_token onto existing GHL contacts (field must exist; progress at ai_agent_k.kk_backfill, socket kk-backfill-progress); KkTokenSyncJob reuses it — see Identity Graph › kk_token coverage.
  • Click → contact stitch: looks in session CRM stamp, PersonProfile by (person_id, company_id), and the email-click recipient, because PersonResolverService writes the click's contact onto the profile and never stamps the session back. Delivered leads join the identity graph on every delivered path (PersonResolver.recordContact(), never pending_push; new profiles outbound_only).

Campaign tokens & ManyReach​

For external senders: POST /knox/agent-k/campaign-tokens mints kk_tokens rows per email (no GHL contact). ManyReach push (app/services/ManyReachService.js; routes POST /knox/agent-k/manyreach/{connect,token-field,links,push,disconnect}, GET …/campaigns) writes the token into a ManyReach custom field (ai_agent_k.manyreach.token_field, default custom20); manyreach.links[] ({field,url,name}) pushes full pre-tokenized URLs per prospect — works around ManyReach's editor URL-encoding {{ }} inside hrefs; a link keeps its field for life. Rows are built by ManyReachService.prospect(), shared with the workflow manyreach step. The API key lives in the credential vault (provider manyreach, 43ae39ef8), not on the company. UI: ManyReach card on the integrations screen. See ManyReach.

LinkedIn (Unipile)​

app/services/AgentKLinkedInService.js + AgentKLinkedInJob (every 30 min); sequences in agent_k_linkedin_sequences. Tenant's account id in ai_agent_k.channels.linkedin.account_id, connected via Unipile hosted auth (POST /unipile/hosted-auth). Warm-up like → 12–48h → connect request (ai_agent_k.automation.linkedin_mode warm_up | immediate). Caps enforced at send, not draft: 20 connects / 50 likes / 50 DMs per account/day; acceptance breaker pauses connects under 25% acceptance over ≥10 invites in 7 days. Webhooks only, never polling (POST /unipile/webhook).

  • Approval vs auto-send — connect requests are NoxAction kind linkedin in the review queue unless the grid's LinkedIn row allows them; manual send of an invite no longer needs GHL. Rule/bulk invites keep their own approval.
  • Invites without a note (074561b7b) — LinkedIn caps noted invites far lower (free: ~5/month vs ~150/week), so notes hit cannot_resend_yet fast. channels.linkedin.invite_note (default true) — false sends every invite plain; POST /knox/actions/:id/send takes without_note per send (every send restates the choice, so a normal retry carries the note again); sequences record connect_with_note. Refusals map on Unipile's error type (cannot_resend_yet/limit_exceeded, already_*, too_many_requests) before the text match; raw refusal kept on action.context.send_error.
  • Usage — GET /knox/agent-k/linkedin/usage: tier from /users/me, pending invites from /users/invite/sent unioned with Agent K's sends (7-day, 30-day notes, today's cap). Unmetered; a failed page reports complete: false. Frontend LinkedInInviteUsage.vue.
  • Monthly seat billing — AgentKLinkedInRenewalJob (hourly, idempotent per period) clocked by channels.linkedin.next_charge_at; due + covered → silent unipile_renewal charge; due + short → immediate disconnect + email; due tomorrow + short → renewal_warned_at is stamped once per cycle but the "renews tomorrow" email is no longer sent (78b06c863, not wanted; the template is unused). Ops: POST /migrations/run-agent-k-linkedin-renewal fires the sweep on demand (the one-shot backfill-agent-k-linkedin-renewal was deleted in 44820dc7e).

Billing — tenant SELL side (backend wallet)​

ms-ai records the platform's COST; what the tenant pays is debited backend-side from the wallet at call time. AgentKWalletService + lib/agentKPricing.js, settings row agent_k_provider_pricing (Admin → Agent K, /admin/agent-k), 60s in-process cache. Tenants never see plans or markup — the pricing endpoint returns only per-action prices.

  • Credit providers (620e6682d) — Apollo and Origami: admin enters the pack (plan_usd, plan_credits) and credits per action (lead_search, contact_reveal, phone_lookup, linkedin_lookup; defaults Apollo 1/1/1/1, Origami 8/5/8/5) plus a markup. Where the provider reports what a call spent, that wins. Origami lead_search = one queued prospect.
  • Flat steps — predictleads (prospect with a signal), apify (filing), unipile (account connected / monthly), unipile_action (like / invite / DM — totalled daily from AI credits, not the wallet).
  • USD → credits keeps 4 decimals (a $0.014 lookup used to be quoted 1 credit and charged 1.4). Defaults 0 = free; a settings read failure bills free.
  • Debits — ai_credit_logs against remaining_purchased_ai_credits (1 credit = $0.01), after a successful provider response (lookups: per attempt), idempotent on idempotency_key. Line source = agent_k_<step>: apollo_search, apollo_match, predictleads, apify_sos, origami, phone_reveal, linkedin_reveal, unipile_connect, unipile_renewal — see Wallet.
  • Gates — hasBalance() before a scan; canAfford(provider) before single known-price actions (LinkedIn connect). Both return false while the AI spend guard (lib/aiSpendGuard, super-admin setting ai_spend_guard off/watch/on) has the company paused for agent_k; in watch mode every paid provider step is reported, even one priced $0 to the tenant (78b06c863).
  • Frontend: PricingTable.vue (hides the PredictLeads row and says "per lead found, with or without a why-now" for origami companies), PricingModal.vue.

Provider usage → platform COST (backend meters, ms-ai prices)​

  • trackProviderUsage() (app/lib/providerUsage.js) — fire-and-forget $inc on provider_usage per (company, provider, day); Origami rows carry real credits.
  • AgentKUsageEmitJob (hourly) forwards closed-day rows (emitted != true, company_id != 'platform') to ms-ai POST /api/cost-tracking/internal/provider-usage, idempotent on external_id agentk:<co>:<provider>:<day>.
  • ms-ai prices via src/cost-tracking/agent-k-provider-pricing.ts (USD/call, JSON env override AGENT_K_PROVIDER_USD) into a usage_charge → the token-usage sum → AITokensCreditJob. See Cost Tracking.

Learning & steering​

  • Skip-demotion (ms-ai/src/agent-k/agent-k-learning.service.ts): a signal_type with ≥5 outcomes and ≥60% skips is demoted unless it ever converted. Fed by GET /internal/knox/agent-k/signal-stats.
  • knox_agent_k_weights Nox tool → POST /internal/knox/actions/agent-k-weights → ai_agent_k.source_weight_overrides (0.25–3), rank-only.
  • AgentKWeeklyDigestJob (hourly tick; ai_agent_k.digest.day in company tz, once per ISO week via digest_last_sent_week), agency-branded.

Agency rename (agency.agent_k_name)​

f963b8b58 / frontend 182b3c1d / ms-ai ded448b83. Agency field agent_k_name (blank = "Agent K", trimmed, 40 chars), saved from agency settings ("Prospecting Agent Name"), returned with the branding payloads next to nox_name. lib/agentKName.js (agentKNameFor, rebrandAgentK*) applies it to every notification + push (NotificationHelper.sendNotification), every company email subject/body (MailService.send), CRM writes (contact sync, lead-source note, visit activity notes, push notes), failed-send errors, wallet/setup messages, brief notes, Nox's feature list and the stored cold consent. Inserted literally (no $-patterns). ms-ai gets agentKName in the admin context (chat prompt section, voice per-call line — no ElevenLabs re-sync) and rebrandNamesDeep renames tool labels and the brief. Frontend useAppBranding().agentKName (domain → agency → "Agent K"); rebrandNoxDeep swaps "Agent K" and "Nox" in one pass. GHL tags and data keys are never renamed. The page moved to /prospecting (route name agent-k unchanged, /agent-k alias kept; both blocked when paused).

Flags & config​

Company (super-admin, admin company detail): agent_k_provider (apollo | origami), agent_k_pacing_visible (queue-status chip + Hunt now), agent_k_lab_enabled (test bench + Run for real) — all default off/apollo. Tenant config under ai_agent_k.*: enabled, mode, crm (auto | ghl | hubspot | none), send_via (auto | crm | mailbox), auto_push, crm_delivery (workflow | task, HubSpot), send.{offering,link_url,touches,touch_mode}, daily_send_cap, icp_description/icp_filter (incl. country, keyword_off, brief, examples, parsed_from), icp_calibrated_at, last_scan (Mixed, write via setAgentKLastScan), origami (Mixed), apollo (Mixed lane cursor), manual_hunt_at, watch_for.* (unused by lookups), re_engage.* (incl. dormant_days, engaged_visitor, min_engagement, max_per_day, writing, use_history, send_via — edited on the Re-engage page), skip_self_reachouts, daily_limit, ghl_fields, manyreach.* (no api_key — it lives in the credential vault), template.*, channels.linkedin.{enabled,account_id,warm_up,personalize,invite_note,connected_at,next_charge_at,renewal_warned_at}, automation.{auto_send,cold_ack,linkedin_mode,rules_paused} (+ legacy sms_approval, cold_policy), legacy sending_mode, source_weight_overrides, digest.*.

Endpoints & surfaces​

  • Tenant (app/routes/noxActionRoutes.js): /knox/agent-k/parse-icp, preview-icp, icp-calibration[/:id[/round|/feedback|/refine|/confirm]], suggest-reply, preview-message, lifecycle-summary (?keys=1), report-details (?journeys=0), leads, dormant-count, pacing, hunt, hunts[/:id], test-lead[/:id[/score]], linkedin/{connect-link,disconnect,usage}, kk-backfill, campaign-tokens, manyreach/*, reactivate; plus /knox/actions/* (pending, sequence, schedule-call, preview-sms, scheduled[…], visits, hot-leads (legacy), :id/{send,dismiss,push,reveal/:field,sync/:field,sessions,thread,call-outcome}). Automations (agentKAutomationRoutes.js): /knox/agent-k/{rules[/:id[/resume|/test|/run]],bulk[/eligible|/current|/:id],automation-events,leads/review}; imports[/preview|/:id]; admin /admin/agent-k/automation-events. Suppressions: GET/POST /knox/suppressions, GET /knox/suppressions/:id/trail, DELETE /knox/suppressions/:id (add by hand: reason manual, 1777b3b7b).
  • Company: PUT /company/:_id/agent-k-{provider,pacing,lab}, POST /company/agent-k/onboarding-enable.
  • Admin (adminAgentKRoutes.js, after the 44820dc7e cleanup): hunt-now, hunt-diagnostics, calibration-stats, clear-off-icp-queue, and the shared job poll GET /admin/agent-k/jobs/:job_id (was per-migration URLs — deploy backend with the frontend). POST /admin/maintenance/recheck-dnc-replies (adminMaintenanceRoutes.js).
  • Internal → backend (internalKnoxRoutes.js): POST /internal/knox/visit-engagement (ms-sessions), POST /internal/knox/agent-k/push, GET …/agent-k/signal-stats, GET …/provider-usage, POST …/actions/agent-k-weights.
  • ms-ai (src/agent-k/agent-k.controller.ts): POST /internal/knox/agent-k/{inbound,suggest-reply,localize,classify-reply,draft-reengage,draft-outbound,preview-message,parse-icp,refine-icp} (agent-k-icp.service.ts — parse and refine share filter coercion and usage recording).
  • Frontend page /prospecting (views/agentk/Index.vue): tabs Feed / Leads / Hunts (every company since a11831fe; ?view=reports|hot rewrite to ?view=leads); sidebar item under Conversations (shown while ai_agent_k.enabled), next to Re-engage (/re-engage/inbox); page bar = today chips, queue chip ("N queued · M need your approval" → queue panel), AgentKPacing (flag-gated), Configure; blocker banner (agentKBlocker). Feed = AgentKInbox.vue (kept alive, lane="prospect") — AgentKRail.vue (tabs, Channel/Why-now selects, search, AgentKFilterPanel.vue incl. Source / List, selection + bulk bar, Import leads / Imports (N), + Test lead), AgentKImportDialog.vue, AgentKImports.vue, AgentKLead.vue, AgentKContact.vue (AgentKRevealRow.vue, AI call / Text via ScheduleCallDialog), AgentKVisits.vue, AgentKThread.vue, AgentKBulkDialog.vue, AgentKTestLeadDialog.vue.
  • Settings views/settings/ai/agents/AgentK/index.vue — 9 tabs: Overview (status, OverviewIntro, pricing, digest, danger zone), Signals (SignalsTab.vue, read-only), Ideal customer, Your traffic (a summary card linking to the Re-engage page, "Stay out of the way…", daily limit), Outreach, Channels, Delivery, Sending (AutoSendGrid.vue, LinkedIn mode; rules, quiet hours and send limits are on the Automations page), Do-not-contact (SuppressionTrailModal.vue behind "Why?"). One <Form> spans the rest (v-show, never v-if). Tab in ?tab=, field deep-links via ?highlight= + HIGHLIGHT_TABS (a test fails when a data-setting has no entry). A highlight is one-shot — leaving its tab drops it from the URL, so it no longer beats ?tab= on reload (ca0271fc; the page's Configure link opens settings plainly). Copy is CRM-aware (agentKRoute() / agentKSender() / CRM_LABEL; Outreach adds the Deliver leads to: CRM choice and Send the emails: GHL-vs-mailbox choice plus a live routeSummary line): HubSpot tenants see the kk_tags workflow / task setup and the HubSpot property mapping instead of LeadConnector's. Setup wizard: same component with setup (5 steps), route /settings/ai/agents/agent-k/setup, and embedded in client setup as step cs_agent_k (views/client-setup/steps/AgentKStep.vue: connect GHL first, then the wizard; GHL install returns to the step).
  • Admin: company detail toggles (provider, queue status, test bench); pricing /admin/agent-k; Agent K Maintenance /admin/agent-k/maintenance (AgentKMaintenance.vue: Hunt diagnostics, Hunt now, ICP calibration usage, "Clear leads queued under an old ideal customer"); Admin → Integrations Maintenance has "Re-check Agent K do-not-contact entries".

Living plan: AGENT_K_PLAN.md (repo root, untracked) — code is authoritative where they disagree.