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
| Feeder | Trigger | Files |
|---|---|---|
| Inbound KnockID | realtime on verified identify — PersonResolverService._fireAgentKInbound → ms-ai POST /internal/knox/agent-k/inbound | app/services/PersonResolverService.js, ms-ai/src/agent-k/ |
| Outbound net-new | AgentKOutboundJob (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 below | app/jobs/AgentKOutboundJob.js, app/services/AgentKOutboundService.js, app/lib/apifySos.js, app/lib/origami.js |
| CRM reactivation | AgentKReactivationJob (hourly; once/day per tenant), requires re_engage.revive_crm + GHL | app/jobs/AgentKReactivationJob.js, app/services/ReactivationService.js |
| Tenant import | CSV upload → AgentKImportJob (every minute) — see Lead imports | app/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 storespayload.why_now: nulland nothing is claimed on push. Rows skippedno_why_nowin 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 needspredictleads.api_key(else skippedpredictleads_not_configured). - Two resumable lanes (
221174607) — each scan reads up toLANE_PAGES(4) pages per lane: fresh (companies matchingorganization_job_posted_at_rangesince the last completed fresh sweep began; first windowFRESH_FIRST_DAYS30), then deep (the whole match set, wrapping at Apollo's 500 pages / 50k results). Cursor inai_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 hitno_new_matcheswithin a week. - Never pay for Apollo errors (
de933c66c) — teasers withhas_email: falseare skipped before the paid reveal;_revealPersonthrows on an Apollo 4xx before charging, and the scan stops without ledgering anyone (hunt reasonapollo_reveal_failed, retried next scan) instead of burning them asno_contact. - Every scan is a hunt (provider
apollo) — see Hunts.
Gates on every outbound lead:
- ICP country (
1cedc4b1e, ms-aib57f49be8) —parse-icpnow returns a validated ISO-2icp_filter.country(the model asks rather than defaulting to US; locations must name their country).statesFromLocationsonly yields SoS states when the country is US (bare "WA" was read as Washington for an AU tenant);_revealPersonreturns the person's country andsameCountry()gates discovery,draftFilinganddraftProspect. A non-US ICP logsno_us_states_in_icpfor the SoS feeder (the inbox explains it). Apollo_resolveOwnernow sends filters as query params — a JSON body is ignored byapi_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 asdropped),icp_filter.keyword_offdrops the one-wordq_keywords.last_scan.outbound.reasonnow comes from discovery —no_new_matcheswhen nobody new matched (the inbox links to calibration);no_us_states_in_icpis no longer reported. - Already in CRM (
a5979f042) — an outbound prospect that resolves to an existing GHL contact is skippedalready_in_crm(reactivation owns those). Inbound is exempt. - Crash ≠ burn (
93c5a4ece) — a thrown error in the hand-off leaves the prospectpendingfor a later tick (bounded byMAX_ATTEMPTS) instead ofskipped, 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) —draftLeadandAgentKSequenceJobcheckre_engage.revive_crmtoo, so turning it off stops queued reactivation leads and touches 2–3. - ICP pivot clears the queue (
fececcda4, narrowed byde97d5d27) —AgentKOutboundService.clearQueueIfIcpPivoted(company, before, after)runs on every ICP write (settings save inCompanyController, Nox ICP adjust/revert inNoxAgentKController, calibration confirm before 👍 leads queue). Only whenicpPivoted(): 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-heldoutbound_discoveryrows goskipped/icp_changed(never deleted — ledger). Unlike a tenant'scleared, 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 migrationPOST /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, runningjob_id,reject_sample,signal_sample,past_list_idsnewest first,dead_list_ids).briefFromIcpuses 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),_origamiDiscoveryruns_apolloDiscoveryfor that hunt (resultfallback: '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 passesexclude_list_ids= the newest 20 past lists (current list, every recorded hunt's, thenorigami.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 todead_list_idsfor 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 backexhausted) clearsorigami.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;origamiVerdictskips onlynot_qualifiedandwrong_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, orrequeue_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 nokk_why_now, why-now note orsignal:tag reaches GHL. ms-aidraft-outbounddescribes a signal-less lead as "looks like the kind of business we work with" (b5dc8fafd);draftProspectkeeps thehiringdefault for PredictLeads prospects only. - Row parsing — v3 doesn't document the row format;
leadFromRowreads defensively. The signal arrives as one structured research cell ("signal-type": { value: { signal_type, signal_date, why_now } }), whichflattenreads after real columns. A Job'srow_idsinclude Origami's own rejects (~21–24 of 25) — excluded/deduplicated rows or rows without the verified email are countednot_qualified, notno_contact. - New-business owners — a single-lead search per filing, polled across trickle ticks, abandoned after 6h.
- Billing —
origamiwallet step per queued lead (_enqueuereports only real inserts, so re-finding a known lead charges nothing) or owner found; Origami's real credit spend lands inprovider_usageasagent_k_origami. - Hunts — every Origami Job (daily, manual, calibration) is an
agent_k_huntsrow; 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-diagnosticsshows 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.AgentKHuntServicereads 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_idapollo:<company>:<ms>;row_idsare Apollo person ids and the detail reads people back from the prospect ledger (skips keep the revealed card). A scan that never searches is recordedskippedwith 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 carryreasonwallet_exhausted/apollo_reveal_failed/no_new_matcheswhen relevant;search_failed(no page read) anderror(thrown — never leftsearching) arefailed.remainingisnullwhen 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 iticp_changed),requeued_later,rejected_before, andturned_awaycarrying the release step'sskip_reason(already_in_crm,suppressed,tag_failed, old-ruleno_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). Afailedhunt shows a details card to every user (1065f252, first super-admin-only in38d532fa): Reason code, Error, Job id, Started, Stopped (+ minutes), withorigami|apollo|predictleadsreplaced 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-icpwith a drafticp_filter: Apollo match count, a sample,droppedtitles/locations past the 25 cap, and wideningsuggestions(region"Search all of …",keyword"Match any industry wording",size"Any company size", each with its total and a filter patch). Never wallet-charged. FrontendIcpReachMeter.vueon 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: oneopensession per company,abandonedafter 7 days idle or on a new start;rounds[]withfilter,statusrunning/done/failed,progress,checks,leads[]withfit_score/verdictup|down /reasons,cost_usd;messages[]chat). Routes/knox/agent-k/icp-calibration—GET(current + price + typical duration),POSTstart,GET /:id,POST /:id/{round,feedback,refine,confirm}.- Round = 5 people (
ROUND_SIZE), requiresfilter.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/matchreveal (charged per reveal, ≤12/round =MAX_REVEALS, 4 pages;has_email: falseteasers 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, stepcalibration), 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× theapollo_matchprice, 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 itserroron the calibration hunt. - Every finished/failed round posts
roundSummaryto 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 (rewrittenbrief+ change bullets). Proposes only; the country is never changed (ms-ai discards it and, since7d4f9693f, 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) andicp_calibrated_at, afterclearQueueIfIcpPivotedagainst the previous filter. 👍 leads are queuedpendingwith or without a why-now (fb5365a62; the response'swaiting_for_signaland the frontend's "added once they show a buying signal" line are gone,c962a270); Origami ones carryorigami_billedso queueing doesn't charge again. 👎 leads are ledgeredskipped/icp_rejectedso 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'sno_new_matchesline). Editing chips after calibrating drops the savedbrief.
- Round = 5 people (
- 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 wholeai_agent_kreverted ICP/Outreach edits. - AI paused (
2992bb9dc) —parse-icpforwards 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_pushdefault false: released leads wait in the feed for a manual push;truepushes automatically. - Pacing read —
GET /knox/agent-k/pacinganswers with the trickle's own decision: queued, released today, next release window, and which of off / closed / capped / empty / cooling holds it (AgentKTrickleJob.nextOpennames when a closed account opens). Super-admin gated: per-companyagent_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. FrontendAgentKPacing.vue("Next lead in ~8 min", "Resumes …"). - Notifications — each release batch sends one
agent-k-leadnotification (NotificationHelper.NOTIFICATION_TYPES.AGENT_K_LEAD) carryinglead_action_idfor the lead it names first. It's tier 2 push too (c455bdc67) — daily push cap, quiet hours and the user'sagent_knotification pref apply. Frontendcomponents/AgentKLeadToast.vue(own soundagent-k-lead.mp3, "Open lead" / "View leads", no timeout) + desktop notification.AgentKDailyPushJobstill sends the once/day throughput push. - The trickle also fires the
lead_foundrule event. - Clearing the queue —
GET/DELETE /knox/agent-k/leads/review[?source=](settings danger zone) deletes Agent K's ownreview-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 markedskipped/cleared, never deleted (9a6972905) — they are the dedupe ledger, and deleting them let a later hunt find, queue and bill the same people again._enqueuenow 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 atawaiting_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 tagnextlevel 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 nonotes),consent { by, at, text }(server-stampedCONSENT_TEXT),statusrunning | paused | cancelled | done,rejectedcounts by reason,total. Rows live inagent_k_prospectswithsource: 'import',import_id,external_id= email orphone:<digits>; prospectstatusgainedpaused. - Check (
AgentKImportService.check, local only — no CRM calls):shape()per row (invalid_email,invalid_phone7–15 digits,no_contact),duplicate_in_file,already_imported(any earlier import),do_not_contact(do_not_contactsby email/phone),needs_emailwhen routing ismailbox(a no-CRM lead is keyed on its email).MAX_ROWS5,000 (400 above). - Release —
AgentKImportJob(schedular, every minute,runningimports, ≤MAX_PER_TICK20 pending rows per list per tick for fairness) →AgentKImportService.release→pushLeadwithsource: 'import'andcontext.import { id, name, tag, known, skip_existing }; settles rows withAgentKTrickleJob.settle(retry/attempts like the trickle), marks the importdonewhen nothing is pending/paused. No working hours, no pacing, no daily limit: the trickle,_queueRoomandreleasedToday()all excludesource: 'import'. Emails still obeydaily_send_cap. - Push rules — imports are cold (
COLD_SOURCES= outbound, reactivation, import;pushLeadnow stampscontext.sourceon every path, so deferred / auto-push leads are no longer read as warm). Existing CRM contacts are skippedalready_in_crmunlessskip_existing: false. Aknownlist 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 withprogress { queued, started, skipped, skip_reasons });PATCH /knox/agent-k/imports/:id{ action: pause|resume|cancel }(cancel skips the restcancelled). - Lead query —
agentKLeadQuerytakessource(outbound|reactivation|knockid|import) andimport_id. - Frontend —
views/agentk/AgentKImportDialog.vue(Upload → Match columns → Review → Start;leadImport.js: RFC 4180 parser with,/;/tab detection, header aliasguessMapping, 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_levelis a strict subdoc — cache keys must be schema'd or writes drop silently).kk_token/kk_why_noware fixed;linkedin_url/job_titlenames are tenant-configurable viaai_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 = nokk_why_now, no note, nosignal:tag. - Tags are the workflow trigger — all prefixed
nextlevel(with space):nextlevel agent-k-lead,nextlevel signal:<type>,nextlevel source:<src>, plusnextlevel returned-to-sitewritten 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.crmauto | ghl | hubspot | none—auto= first connected (GHL, then HubSpot) viacrm.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), elsenull(nothing to deliver to — theagentKBlockerbanner).- sender (
senderFor) —mailboxprovider → alwaysmailbox. Otherwisenullunlessmode === 'send'; GHL withsend_via === 'mailbox'→mailboxif usable, elsenull(push only); GHL otherwise →ghl; HubSpot →mailboxif usable, elsenull.send_viaauto | crm | mailbox(UI savescrm/mailbox; anything butmailbox= GHL). AgentKPushService.pushLeadtreatssendMode = !!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 withuse_for.agent_k ≠ false) feedsAgentKSequenceJob/AgentKAutoSendJob; feeders queryconnectedQuery(['ghl', 'hubspot', 'mailbox']).- No-CRM ids —
crmContact.mailboxId(email)=mbx_<base64url(lowercased email)>;crm_links[0].provider = 'mailbox',ghl_contact_idblank.isMailbox/mailboxEmaildecode. No contact create, fields, note or tags (_deliverreturns ok); "already in CRM" can't apply. A lead parkedpending_pushfor a CRM can't be pushed once routing saysmailbox(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 latersend_viachange doesn't split a thread. Only an explicitcrm_links[0].providernames a record's CRM — legacyghl_contact_idrows 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, publicGET|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 replymeta.message_idwhen newer). Never falls back to platform mail — a failure throwsCouldn't send from your mailbox: …. - Replies —
MailboxReplyJob(schedular, every 5 min) →MailboxService.pollReplies; only mail from addresses matchingmailboxRouting.leadQueryreacheshandleInboundReply; bounces (mailer-daemon/postmaster,Final-Recipient) suppress (reason: 'bounced') and dismiss open drafts. Unsubscribe link →addSuppression(unsubscribed).
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_modeguide | verbatim(defaultguide). AgentKSequenceJob(hourly) — touch 1 drafts at push time; touches 2–3 draft ~3–4d / ~4–5d after an unanswered send (GAPS_MS,PER_COMPANY_CAP20/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 returnsmode: 'push'with an empty ladder. - Reply suppression + stop-intent — inbound reply dismisses pending
drafts (
handleInboundReply, treatspushedas outreach);_classifyStopIntent→ ms-aiPOST /internal/knox/agent-k/classify-reply(fails openstop=false;AGENT_K_STOP_MODELoverride — 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 toevents[]({ at, reason, source, evidence }, Mixed evidence): reply text + matched keyword ordetected_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/suppressionsexcludesevents. - Trail —
GET /knox/suppressions/:id/trail→{ entry, audit, outreach, lifecycle, recovered }:audit_logsfor the record; outreach = NoxActions bycontext.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 noeventsand sourcereply/blank callsNoxGhlActionService.recoverSuppressionEvidence: finds the CRM contact (outreach ids, else by email/phone), readsadapter.incomingMessages(new onGhlAdapter+HubspotAdapter) up to 5 min after the block, keeps SMS/email/WhatsApp, newest 3, each flagged withstopKeyword(andquoted_keywordwhen the word is only in quoted text).missing:not_in_crm | unsupported_crm | crm_error. - False-DNC fix (
b56f031bd) — GHLInboundMessageonly enters the reply loop for SMS/Email/WhatsAppmessageType(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 seesfreshReply. - 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"): removesnot_a_replyandquoted_onlyentries; 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 inNoxGhlActionServiceandAgentKActionRunner;NoxGhlActionService.autoSendDecisionis the one caller and recordssend_rule/sent_byon the NoxAction (send receipt). Inline auto-send drafts (rebook, draft-batch) go throughAgentKPushService._autoSend, so the send cap counts every autonomous email.- Push mode forces email to ask/ask (
9099919e5) —policyOfreads the email row as ask outsidemode: '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'needsautomation.cold_ack({ by, at, text }, server-stamped; text in the words the tenant saw, agency name included) viaaccept_cold_ackon 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_holdrecords why an automatic email waits (quiet_hourswith the recipient's 9am,daily_send_capuntil 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._recipientTimezonenow resolves: CRM contacttimezone→context.recipient_tz(stamped on touch 1 from enrichment vialib/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'stimezone._autoSendcalls_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 stayask. - 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 bycheckOutboundAllowed, numbers survive off);spacing {enabled, minutes 45}(nox_funnel.actions.spacing,bab1fcebf) replaced the hard-coded 45-min gap — read by the gate andScheduledNoxActionJobdeferral. All editable on the Agent K Sending tab;normalizeAutomationfiles them innox_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 withouttrigger.type;GeneralHelper.updateLeadScore→AgentKRuleService.onScoreChange).engaged{ engagement_threshold 1–100 }(80c338d85) — a visit's engagement score crossing N, viaonEngagementfromPOST /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 since80c338d85website leads from the inbound / engaged paths),funnel_stage_changed{ from, to }(fired fromFunnelStageServiceon every real move). email_no_visit{ emails, days }—AgentKEmailNoVisitJob(schedular, hourly) fires oncedayshave 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 adeliveredlifecycle stage (GhlNativeEventHelper), only while the company has such a rule. Lookback is one day pastdays— 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 optionoptions.when = 'call_unanswered': the SMS task depends on the call task;ScheduledNoxActionJobsends 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 isai_call→if call_answered→no: sms. - Rules and bulk runs send as set up (
eb1f402f6) — their steps go out viaautomationAllowed/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 (overridecooldown). A step saved "always asks" and a rule'scold_limitstill hold. Reaching cold leads needs consent on record: saving such a rule or starting such a bulk run records it viaaccept_cold_ack, else 409cold_consent_required(bulk dry runs reportconsent_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/testexplains (never sends);POST …/runevaluates with explain off (super-adminagent_k_lab_enabled), dropping this rule's cooldown claim (automation_claims) on that lead first. - Queue — rule/bulk call and text tasks are
ScheduledNoxActions withcreated_from: rule | bulk;GET /knox/actions/scheduled?created_from=rule,bulkfeeds 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 appendkkto any URL on the tenant's own host (AgentKActionRunner.trackLinks); AI emails loadwebsite_urlso a link is minted even with no send link. - Frontend editor (
54e5d664, Vue Flow removed; nowviews/automations/WorkflowEditor.vue+workflow/) — GHL-style top-down builder (trigger cards + "Add New Trigger", "+" on every line viaworkflow/AddStepButton.vue, If / Else → Yes/No columns inWorkflowBranch.vue, END, "Go to" for joined paths, searchableActionPicker.vuefromworkflow.jsLIBRARY, side panelStepSettings.vue); tabs Builder / Settings (conditions + editablelimits) / 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 incommon/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/pendingbuilds every tab, channel and signal count in one$facetover index keys (feedCounts), covered by{ company_id, status, agent, kind, ghl_lead, signal_type, created_at, updated_at }.ghl_lead(set in_defer) replacespush_payloadnull checks — a Mixed blob can't be indexed; backfilled at boot with timestamps off (delete the boot backfill once it has run). - Search —
qon 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}, plusGET /knox/actions/:id/sessionsand/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 indexedvisitor_profilesread after grouping sessions, not a$lookupper session (49ac05d90, ~6.5× faster). Sessions are found with one indexedfindper 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$oraggregate read every session the company had (8.3s of 8.5s on/knox/actions/pendingin prod). - Thread —
GET /knox/actions/:id/threadmerges 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'scall:<sid>accounting rows (58a17b805). Designed template emails (full HTML documents) render in a sandboxedcomponents/EmailFrame.vueiframe — 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-callacceptsnow: true;POST /knox/actions/preview-smsreturns the exact text the SMS agent would send (policy inlib/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 atAgentKLeadVisitService.FILTER_MAX_LEADS), one row per person —personKey= CRM contact id → email → phone digits →_id, becauseAgentKPushServicere-pushes a contact after the 72h cooldown. Row = newest push + best visit summary + mergedcall_log/call_outcome/led_to_meeting+ AI calls/texts (reach) +journey(firstpushed/sent/clicked/replied/bookedper contact fromlead_lifecycle_events).deliveredcounts 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 failedno_identity. - Visit dates = session start or analysed end, never
updated_at(the 2026-09-05 crm_links backfill bumped it), except while live; summaries carryvisit_atsfor per-period counts; top pages fold tracking params, anchors and trailing slashes. lifecycle-summary?keys=1returns which contacts each stage counted (tile drill-downs);report-details?journeys=0skips the per-lead journey table.POST /knox/actions/:id/call-outcome(logCall) —OUTCOMES:no_answer,voicemailkeep the lead open;interested,booked(setsled_to_meeting),not_interested,wrong_personclose it (call_outcome). The last two alsoaddSuppression(reason: 'manual',source: 'call_outcome') and tag the CRM contactnextlevel call:not-interested/nextlevel call:wrong-person. CRM note + tag are best-effort.- Frontend
AgentKLeads.vue(period picker + tiles) wrapsAgentKLeadList.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 fromkeys. 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 —
PersonResolverServiceskips Agent K inbound for self-reach-out identifications (SELF_REACHOUT_SOURCES: form, chat_form, chat, call, inbound_call, booking) whileskip_self_reachoutsis on (dee9adfc0added chat forms, calls and bookings). POST /user-session/kk-click(UserSessionController@kkClick): bot filter (client flag → scanner-UA regex → IP check) → token lookup →PersonResolverService.resolvestitches the identity onto the session → writesnextlevel returned-to-site→ funnellink_click/web_visitsignals →email_clickrule event → widget auto-engage of the returning lead (cooldownknox.visitor_watch.auto_engage_cooldown_hours). On the session's first click (!email_click_at) it also dispatches thenew_user_identifiedwebhook with the token's contact (source: 'kk_token',751f071bb) —new_sessionfires 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()inapp/lib/trafficSource.js(dee9adfc0), used by both the per-visitpageArrivalSourceand the kk-click stamp:mapping.sourcewins; a legacy source-less token isagent_konly if Agent K worked that contact (aNoxActionwithagent: 'agent_k'), elseghl_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 skipsghl_backfill/manyreachmints — 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-backfillstampskk_tokenonto existing GHL contacts (field must exist; progress atai_agent_k.kk_backfill, socketkk-backfill-progress);KkTokenSyncJobreuses 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, becausePersonResolverServicewrites 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(), neverpending_push; new profilesoutbound_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
NoxActionkindlinkedinin 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 hitcannot_resend_yetfast.channels.linkedin.invite_note(default true) — false sends every invite plain;POST /knox/actions/:id/sendtakeswithout_noteper send (every send restates the choice, so a normal retry carries the note again); sequences recordconnect_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 onaction.context.send_error. - Usage —
GET /knox/agent-k/linkedin/usage: tier from/users/me, pending invites from/users/invite/sentunioned with Agent K's sends (7-day, 30-day notes, today's cap). Unmetered; a failed page reportscomplete: false. FrontendLinkedInInviteUsage.vue. - Monthly seat billing —
AgentKLinkedInRenewalJob(hourly, idempotent per period) clocked bychannels.linkedin.next_charge_at; due + covered → silentunipile_renewalcharge; due + short → immediate disconnect + email; due tomorrow + short →renewal_warned_atis 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-renewalfires the sweep on demand (the one-shotbackfill-agent-k-linkedin-renewalwas deleted in44820dc7e).
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. Origamilead_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_logsagainstremaining_purchased_ai_credits(1 credit = $0.01), after a successful provider response (lookups: per attempt), idempotent onidempotency_key. Linesource=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 settingai_spend_guardoff/watch/on) has the company paused foragent_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$inconprovider_usageper (company, provider, day); Origami rows carry realcredits.AgentKUsageEmitJob(hourly) forwards closed-day rows (emitted != true,company_id != 'platform') to ms-aiPOST /api/cost-tracking/internal/provider-usage, idempotent onexternal_id agentk:<co>:<provider>:<day>.- ms-ai prices via
src/cost-tracking/agent-k-provider-pricing.ts(USD/call, JSON env overrideAGENT_K_PROVIDER_USD) into ausage_charge→ thetoken-usagesum →AITokensCreditJob. See Cost Tracking.
Learning & steering
- Skip-demotion (
ms-ai/src/agent-k/agent-k-learning.service.ts): asignal_typewith ≥5 outcomes and ≥60% skips is demoted unless it ever converted. Fed byGET /internal/knox/agent-k/signal-stats. knox_agent_k_weightsNox 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.dayin company tz, once per ISO week viadigest_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: reasonmanual,1777b3b7b). - Company:
PUT /company/:_id/agent-k-{provider,pacing,lab},POST /company/agent-k/onboarding-enable. - Admin (
adminAgentKRoutes.js, after the44820dc7ecleanup):hunt-now,hunt-diagnostics,calibration-stats,clear-off-icp-queue, and the shared job pollGET /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 sincea11831fe;?view=reports|hotrewrite to?view=leads); sidebar item under Conversations (shown whileai_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.vueincl. Source / List, selection + bulk bar, Import leads / Imports (N), + Test lead),AgentKImportDialog.vue,AgentKImports.vue,AgentKLead.vue,AgentKContact.vue(AgentKRevealRow.vue, AI call / Text viaScheduleCallDialog),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.vuebehind "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 adata-settinghas 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 liverouteSummaryline): HubSpot tenants see thekk_tagsworkflow / task setup and the HubSpot property mapping instead of LeadConnector's. Setup wizard: same component withsetup(5 steps), route/settings/ai/agents/agent-k/setup, and embedded in client setup as stepcs_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.