oneshot-gtm-server 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.mjs +1591 -96
- package/dist/bin.mjs.map +1 -1
- package/dist/web/assets/{Badge-i7nNYr-O.js → Badge-CizqG39K.js} +1 -1
- package/dist/web/assets/{Button-CwgZt1tQ.js → Button-BG5_XuBU.js} +1 -1
- package/dist/web/assets/{EmptyNote-uIusooGk.js → EmptyNote-Ca39ndrq.js} +1 -1
- package/dist/web/assets/{Field-Lu8BfWg7.js → Field-CoH_-bpd.js} +1 -1
- package/dist/web/assets/{Modal-CDPz1CPv.js → Modal-BawkhTwU.js} +1 -1
- package/dist/web/assets/{Pii-CybNyYoN.js → Pii-DjW0BXTT.js} +1 -1
- package/dist/web/assets/{Skeleton-BnehflEF.js → Skeleton-241HZuI6.js} +1 -1
- package/dist/web/assets/{StrategistPanel-BT7pkEha.js → StrategistPanel-v1hVTYB2.js} +3 -3
- package/dist/web/assets/add-prospect-DNooR5hw.js +1 -0
- package/dist/web/assets/arrow-right-DqfFKNit.js +1 -0
- package/dist/web/assets/cadences-myfA9fpX.js +1 -0
- package/dist/web/assets/chevron-down-6zIAL5Jw.js +1 -0
- package/dist/web/assets/chevron-right-B5g68HIS.js +1 -0
- package/dist/web/assets/dist-CePbZ9YI.js +1 -0
- package/dist/web/assets/inbox-wOfHfUdK.js +1 -0
- package/dist/web/assets/index-CN82REiV.css +2 -0
- package/dist/web/assets/index-Cv9fu2Ox.js +54 -0
- package/dist/web/assets/loader-circle-B6ORQpaf.js +1 -0
- package/dist/web/assets/{measure-DICeV6u0.js → measure-B1xSpOF1.js} +1 -1
- package/dist/web/assets/plays-B3vCcieV.js +1 -0
- package/dist/web/assets/queue-CpMpZP2Y.js +1 -0
- package/dist/web/assets/{receipts-jmGYoC8d.js → receipts-Dr7Gdn6t.js} +1 -1
- package/dist/web/assets/{refresh-cw-BAYQiC3W.js → refresh-cw-CU2BZQWg.js} +1 -1
- package/dist/web/assets/removable-nvTWDYcH.js +1 -0
- package/dist/web/assets/rotate-cw-CLLKYNJm.js +1 -0
- package/dist/web/assets/routes-D5OSAalN.js +1 -0
- package/dist/web/assets/run._playName-B56qmIWT.js +4 -0
- package/dist/web/assets/setup-Csw0ToIu.js +1 -0
- package/dist/web/assets/src-DN5GR1Qu.js +1 -0
- package/dist/web/assets/x-CNSXZou1.js +1 -0
- package/dist/web/index.html +5 -3
- package/package.json +1 -1
- package/dist/web/assets/cadences-L6OtcR2U.js +0 -1
- package/dist/web/assets/chevron-down-Fqh8xk_J.js +0 -1
- package/dist/web/assets/chevron-right-Ct1AtbHw.js +0 -1
- package/dist/web/assets/dist-yPYNbuB_.js +0 -1
- package/dist/web/assets/inbox-D6vK3Uh_.js +0 -1
- package/dist/web/assets/index-C7_9mwYD.js +0 -54
- package/dist/web/assets/index-c7S5-cnw.css +0 -2
- package/dist/web/assets/loader-circle-Bg1u7Pc8.js +0 -1
- package/dist/web/assets/plays-FzKWoHW7.js +0 -1
- package/dist/web/assets/queue-BUHMLlyN.js +0 -1
- package/dist/web/assets/rotate-cw-BZauKIGY.js +0 -1
- package/dist/web/assets/routes-D9btIJMO.js +0 -1
- package/dist/web/assets/run._playName-BEHDsQ6-.js +0 -4
- package/dist/web/assets/setup-BaujTJR0.js +0 -1
- package/dist/web/assets/src-DDEaweyX.js +0 -1
- package/dist/web/assets/x-C-34Mo7s.js +0 -1
- /package/dist/web/assets/{summarizeRun-J5570T9r.js → summarizeRun-CIN4tTJL.js} +0 -0
package/dist/bin.mjs
CHANGED
|
@@ -72,6 +72,21 @@ function loadConfig() {
|
|
|
72
72
|
} catch {}
|
|
73
73
|
return cfg;
|
|
74
74
|
}
|
|
75
|
+
let cachedConfig = null;
|
|
76
|
+
/**
|
|
77
|
+
* Process-memoized `loadConfig` for hot, read-only callers like the telemetry
|
|
78
|
+
* send path (`reportTelemetryEvent`), which otherwise does a `readFileSync` on
|
|
79
|
+
* every emit — once per fired trigger in the server's scheduler loop. The cache
|
|
80
|
+
* is busted by `saveConfig`, so an in-process write (e.g. the dashboard's
|
|
81
|
+
* `config telemetry off`) is reflected on the next read. A config edit from a
|
|
82
|
+
* *separate* process (CLI `config telemetry off`) propagates to a long-running
|
|
83
|
+
* server on its next own write or on restart; the `ONESHOT_GTM_TELEMETRY=0` env
|
|
84
|
+
* kill switch (checked live, uncached, in `shouldSendTelemetry`) is the
|
|
85
|
+
* immediate override for that case.
|
|
86
|
+
*/
|
|
87
|
+
function loadConfigCached() {
|
|
88
|
+
return cachedConfig ??= loadConfig();
|
|
89
|
+
}
|
|
75
90
|
/**
|
|
76
91
|
* Pure helper for the clientId bootstrap path — extracted so it can be
|
|
77
92
|
* unit-tested without touching the user's real config file. Mints a fresh
|
|
@@ -107,6 +122,7 @@ function saveConfig(cfg) {
|
|
|
107
122
|
ensureConfigDir();
|
|
108
123
|
if (!existsSync(dirname(CONFIG_PATH))) mkdirSync(dirname(CONFIG_PATH), { recursive: true });
|
|
109
124
|
writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2));
|
|
125
|
+
cachedConfig = null;
|
|
110
126
|
}
|
|
111
127
|
function secretsPath() {
|
|
112
128
|
return SECRETS_PATH;
|
|
@@ -469,6 +485,42 @@ var Ledger = class {
|
|
|
469
485
|
this.db.exec(`
|
|
470
486
|
CREATE INDEX IF NOT EXISTS idx_receipts_goal
|
|
471
487
|
ON receipts(goal_id) WHERE goal_id IS NOT NULL;
|
|
488
|
+
`);
|
|
489
|
+
this.db.exec(`
|
|
490
|
+
CREATE TABLE IF NOT EXISTS bounces (
|
|
491
|
+
message_id TEXT NOT NULL,
|
|
492
|
+
recipient TEXT NOT NULL,
|
|
493
|
+
identity_id TEXT,
|
|
494
|
+
kind TEXT NOT NULL,
|
|
495
|
+
status_code TEXT,
|
|
496
|
+
diagnostic TEXT,
|
|
497
|
+
prospect_id INTEGER,
|
|
498
|
+
bounced_at TEXT NOT NULL,
|
|
499
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
500
|
+
PRIMARY KEY (message_id, recipient)
|
|
501
|
+
);
|
|
502
|
+
-- doctor's per-identity rate over a trailing window.
|
|
503
|
+
CREATE INDEX IF NOT EXISTS idx_bounces_identity ON bounces(identity_id, bounced_at);
|
|
504
|
+
-- suppressionFor, on the send pre-flight path — must be an index seek.
|
|
505
|
+
CREATE INDEX IF NOT EXISTS idx_bounces_recipient ON bounces(recipient, kind);
|
|
506
|
+
`);
|
|
507
|
+
this.db.exec(`
|
|
508
|
+
CREATE TABLE IF NOT EXISTS canary_results (
|
|
509
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
510
|
+
from_identity TEXT NOT NULL,
|
|
511
|
+
to_identity TEXT NOT NULL,
|
|
512
|
+
placement TEXT NOT NULL,
|
|
513
|
+
labels_json TEXT,
|
|
514
|
+
spf TEXT NOT NULL,
|
|
515
|
+
dkim TEXT NOT NULL,
|
|
516
|
+
dmarc TEXT NOT NULL,
|
|
517
|
+
subject TEXT,
|
|
518
|
+
source_play TEXT,
|
|
519
|
+
same_domain INTEGER NOT NULL DEFAULT 0,
|
|
520
|
+
latency_ms INTEGER,
|
|
521
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
522
|
+
);
|
|
523
|
+
CREATE INDEX IF NOT EXISTS idx_canary_created ON canary_results(created_at DESC);
|
|
472
524
|
`);
|
|
473
525
|
}
|
|
474
526
|
/**
|
|
@@ -858,6 +910,99 @@ var Ledger = class {
|
|
|
858
910
|
return this.db.query(`SELECT MIN(created_at) AS first FROM receipts
|
|
859
911
|
WHERE call_type = 'email.send' AND sender_identity = ?`).get(identityId).first;
|
|
860
912
|
}
|
|
913
|
+
/**
|
|
914
|
+
* Record one delivery failure. INSERT OR IGNORE against the (message_id,
|
|
915
|
+
* recipient) PK: the sweep re-reads a 30-day window on every tick, so the
|
|
916
|
+
* same DSN is re-seen dozens of times and must only ever count once.
|
|
917
|
+
* Returns true when this was a NEW bounce — callers use that to decide
|
|
918
|
+
* whether to act on the cadence (stopping it repeatedly is harmless, but
|
|
919
|
+
* re-tagging receipts and logging on every tick is not).
|
|
920
|
+
*/
|
|
921
|
+
recordBounce(input) {
|
|
922
|
+
return this.db.prepare(`INSERT OR IGNORE INTO bounces
|
|
923
|
+
(message_id, recipient, identity_id, kind, status_code, diagnostic, prospect_id, bounced_at)
|
|
924
|
+
VALUES(?, ?, ?, ?, ?, ?, ?, ?)`).run(input.messageId, canonEmail(input.recipient), input.identityId, input.kind, input.statusCode, input.diagnostic?.slice(0, 300) ?? null, input.prospectId, input.bouncedAt).changes > 0;
|
|
925
|
+
}
|
|
926
|
+
/**
|
|
927
|
+
* The hard bounce that suppresses this address, or null if it's still
|
|
928
|
+
* sendable. HARD ONLY — a `block` is the receiving server refusing a message
|
|
929
|
+
* on policy, not a statement that the mailbox is dead, so suppressing on it
|
|
930
|
+
* would permanently burn valid prospects over one spam-filter verdict.
|
|
931
|
+
* Soft bounces are transient by definition.
|
|
932
|
+
*/
|
|
933
|
+
suppressionFor(email) {
|
|
934
|
+
return this.db.query(`SELECT * FROM bounces WHERE recipient = ? AND kind = 'hard'
|
|
935
|
+
ORDER BY bounced_at DESC LIMIT 1`).get(canonEmail(email)) ?? null;
|
|
936
|
+
}
|
|
937
|
+
/** Bounce counts per sending identity since `sinceIso` — the doctor check's numerator. */
|
|
938
|
+
bounceStatsByIdentity(opts) {
|
|
939
|
+
const rows = this.db.query(`SELECT identity_id, kind, COUNT(*) AS n FROM bounces
|
|
940
|
+
WHERE bounced_at >= ? AND identity_id IS NOT NULL
|
|
941
|
+
GROUP BY identity_id, kind`).all(opts.sinceIso);
|
|
942
|
+
const out = /* @__PURE__ */ new Map();
|
|
943
|
+
for (const r of rows) {
|
|
944
|
+
let entry = out.get(r.identity_id);
|
|
945
|
+
if (!entry) {
|
|
946
|
+
entry = {
|
|
947
|
+
hard: 0,
|
|
948
|
+
block: 0,
|
|
949
|
+
soft: 0
|
|
950
|
+
};
|
|
951
|
+
out.set(r.identity_id, entry);
|
|
952
|
+
}
|
|
953
|
+
entry[r.kind] = r.n;
|
|
954
|
+
}
|
|
955
|
+
return out;
|
|
956
|
+
}
|
|
957
|
+
/** Most recent bounces for display (doctor detail lines, debugging). */
|
|
958
|
+
listRecentBounces(opts = {}) {
|
|
959
|
+
return this.db.query(`SELECT * FROM bounces ORDER BY bounced_at DESC LIMIT ?`).all(opts.limit ?? 20);
|
|
960
|
+
}
|
|
961
|
+
recordCanaryResult(input) {
|
|
962
|
+
const result = this.db.prepare(`INSERT INTO canary_results
|
|
963
|
+
(from_identity, to_identity, placement, labels_json, spf, dkim, dmarc,
|
|
964
|
+
subject, source_play, same_domain, latency_ms)
|
|
965
|
+
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(input.fromIdentity, input.toIdentity, input.placement, JSON.stringify(input.labelIds), input.auth.spf, input.auth.dkim, input.auth.dmarc, input.subject, input.sourcePlay, input.sameDomain ? 1 : 0, input.latencyMs);
|
|
966
|
+
return Number(result.lastInsertRowid);
|
|
967
|
+
}
|
|
968
|
+
/** Newest placement test, or null if one has never been run. */
|
|
969
|
+
latestCanaryResult() {
|
|
970
|
+
return this.db.query(`SELECT * FROM canary_results ORDER BY created_at DESC, id DESC LIMIT 1`).get() ?? null;
|
|
971
|
+
}
|
|
972
|
+
/**
|
|
973
|
+
* Subject + body of the most recent email this tool actually SENT, for the
|
|
974
|
+
* placement canary to replay. Spam filters judge content, so testing with
|
|
975
|
+
* invented copy would measure nothing that transfers to real outreach.
|
|
976
|
+
* Reads the persisted draft off the sequence_events row (metadata_json
|
|
977
|
+
* carries {subject, body} for sent email steps).
|
|
978
|
+
*/
|
|
979
|
+
latestSentEmailCopy(opts = {}) {
|
|
980
|
+
const rows = this.db.query(`SELECT play_name, metadata_json FROM sequence_events
|
|
981
|
+
WHERE status IN ('sent', 'delivered', 'replied')
|
|
982
|
+
AND channel = 'email' AND metadata_json IS NOT NULL
|
|
983
|
+
AND json_valid(metadata_json)
|
|
984
|
+
AND json_extract(metadata_json, '$.subject') IS NOT NULL
|
|
985
|
+
AND trim(coalesce(json_extract(metadata_json, '$.body'), '')) != ''
|
|
986
|
+
${opts.playName ? "AND play_name = ?" : ""}
|
|
987
|
+
-- id DESC breaks ties: created_at is second-precision, and a cadence
|
|
988
|
+
-- batch writes several rows within one second, leaving their relative
|
|
989
|
+
-- order otherwise unspecified.
|
|
990
|
+
ORDER BY created_at DESC, id DESC LIMIT 25`).all(...opts.playName ? [opts.playName] : []);
|
|
991
|
+
for (const row of rows) {
|
|
992
|
+
let meta;
|
|
993
|
+
try {
|
|
994
|
+
meta = JSON.parse(row.metadata_json);
|
|
995
|
+
} catch {
|
|
996
|
+
continue;
|
|
997
|
+
}
|
|
998
|
+
if (typeof meta.subject === "string" && typeof meta.body === "string" && meta.body.trim()) return {
|
|
999
|
+
subject: meta.subject,
|
|
1000
|
+
body: meta.body,
|
|
1001
|
+
playName: row.play_name
|
|
1002
|
+
};
|
|
1003
|
+
}
|
|
1004
|
+
return null;
|
|
1005
|
+
}
|
|
861
1006
|
getReceipt(id) {
|
|
862
1007
|
return this.db.query("SELECT * FROM receipts WHERE id = ?").get(id) ?? null;
|
|
863
1008
|
}
|
|
@@ -1277,6 +1422,11 @@ var Ledger = class {
|
|
|
1277
1422
|
where.push("status = ?");
|
|
1278
1423
|
args.push(opts.status);
|
|
1279
1424
|
}
|
|
1425
|
+
if (opts.ids) {
|
|
1426
|
+
if (opts.ids.length === 0) return [];
|
|
1427
|
+
where.push(`id IN (${opts.ids.map(() => "?").join(",")})`);
|
|
1428
|
+
args.push(...opts.ids);
|
|
1429
|
+
}
|
|
1280
1430
|
const sql = `
|
|
1281
1431
|
SELECT * FROM target_queue
|
|
1282
1432
|
${where.length ? `WHERE ${where.join(" AND ")}` : ""}
|
|
@@ -1419,6 +1569,18 @@ var Ledger = class {
|
|
|
1419
1569
|
for (const r of rows) out[r.status] = r.n;
|
|
1420
1570
|
return out;
|
|
1421
1571
|
}
|
|
1572
|
+
/**
|
|
1573
|
+
* Approved-row count per play, across the whole queue. Deliberately ignores
|
|
1574
|
+
* any status/play filter the caller is showing: /queue's drain button needs
|
|
1575
|
+
* to know a play has drainable rows even when the visible page is filtered
|
|
1576
|
+
* to `pending`. Plays with zero approved rows are absent from the map.
|
|
1577
|
+
*/
|
|
1578
|
+
approvedCountsByPlay() {
|
|
1579
|
+
const rows = this.db.query("SELECT play_name, COUNT(*) AS n FROM target_queue WHERE status = 'approved' GROUP BY play_name").all();
|
|
1580
|
+
const out = {};
|
|
1581
|
+
for (const r of rows) out[r.play_name] = r.n;
|
|
1582
|
+
return out;
|
|
1583
|
+
}
|
|
1422
1584
|
createRun(input) {
|
|
1423
1585
|
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1424
1586
|
const result = this.db.prepare(`INSERT INTO runs(play_name, dry_run, status, started_at, target_count, targets_json)
|
|
@@ -1665,6 +1827,26 @@ var Ledger = class {
|
|
|
1665
1827
|
});
|
|
1666
1828
|
this.db.prepare(`UPDATE target_queue SET last_draft_json = ?, last_drafted_at = ? WHERE id = ?`).run(json, draftedAtIso, input.id);
|
|
1667
1829
|
}
|
|
1830
|
+
/**
|
|
1831
|
+
* Overwrite a queue row's `payload_json` (the per-target JSON the play
|
|
1832
|
+
* drafts from). Used by the manual add-prospect flow: the row is enqueued
|
|
1833
|
+
* immediately as a placeholder, then — once the async dossier research
|
|
1834
|
+
* completes — its payload is rewritten to the full ProfileIntroTarget
|
|
1835
|
+
* (identity + dossier + angle) so `/queue` regenerate re-drafts from the
|
|
1836
|
+
* researched dossier instead of paying for research again.
|
|
1837
|
+
*/
|
|
1838
|
+
updateQueuePayload(input) {
|
|
1839
|
+
this.db.prepare(`UPDATE target_queue SET payload_json = ? WHERE id = ?`).run(JSON.stringify(input.payload), input.id);
|
|
1840
|
+
}
|
|
1841
|
+
/**
|
|
1842
|
+
* Set a queue row's `notes` without touching its status. Used by the manual
|
|
1843
|
+
* add-prospect flow to update the transient "researching profile…" note to
|
|
1844
|
+
* a "no email found" flag (or a research-failed message) once the async job
|
|
1845
|
+
* settles. Pass an empty string to clear it.
|
|
1846
|
+
*/
|
|
1847
|
+
setQueueNotes(input) {
|
|
1848
|
+
this.db.prepare(`UPDATE target_queue SET notes = ? WHERE id = ?`).run(input.notes === "" ? null : input.notes, input.id);
|
|
1849
|
+
}
|
|
1668
1850
|
close() {
|
|
1669
1851
|
this.db.close();
|
|
1670
1852
|
}
|
|
@@ -1987,6 +2169,198 @@ async function listGmailReplies(opts, account) {
|
|
|
1987
2169
|
agent_id: "gmail"
|
|
1988
2170
|
};
|
|
1989
2171
|
}
|
|
2172
|
+
/** Matches an RFC 3463 enhanced status code ("5.1.1"). */
|
|
2173
|
+
const ENHANCED_STATUS_RE = /\b([45]\.\d{1,3}\.\d{1,3})\b/;
|
|
2174
|
+
/** Matches a bare 3-digit SMTP reply code, for servers that omit the enhanced one. */
|
|
2175
|
+
const SMTP_CODE_RE = /\b([45]\d\d)\b/;
|
|
2176
|
+
/**
|
|
2177
|
+
* Diagnostics that mean "we refused this message" rather than "this address
|
|
2178
|
+
* doesn't exist". Catches servers that reject on policy with a plain 550 and
|
|
2179
|
+
* no 5.7.x enhanced code, which would otherwise be miscounted as a dead
|
|
2180
|
+
* address (and wrongly suppress a perfectly valid prospect).
|
|
2181
|
+
*/
|
|
2182
|
+
const POLICY_DIAGNOSTIC_RE = /\b(spam|blocked|blocklist|blacklist|policy|reputation|unsolicited|bulk|rejected due to|spamhaus|barracuda|greylist)/i;
|
|
2183
|
+
/**
|
|
2184
|
+
* Canonical DSN envelope senders. Used only as a fallback to the message's
|
|
2185
|
+
* actual From address — kept narrow deliberately: a broad pattern (no-reply@,
|
|
2186
|
+
* donotreply@…) would also discard a genuine failed recipient at one of those
|
|
2187
|
+
* addresses, and then the hard bounce would never be recorded or suppressed.
|
|
2188
|
+
*/
|
|
2189
|
+
const DAEMON_ADDRESS_RE = /^(mailer-daemon|postmaster)@/i;
|
|
2190
|
+
/**
|
|
2191
|
+
* Quantifiers are bounded to RFC 5321's limits (local-part 64, labels 63)
|
|
2192
|
+
* rather than left open. An unbounded `[...]+@` over a body that never contains
|
|
2193
|
+
* `@` backtracks from every start position — and DSN bodies are attacker-
|
|
2194
|
+
* influenced, since anyone can send mail with a mailer-daemon From. See also
|
|
2195
|
+
* PROSE_SCAN_LIMIT.
|
|
2196
|
+
*/
|
|
2197
|
+
const EMAIL_RE = /[\w.!#$%&'*+/=?^`{|}~-]{1,64}@[\w-]{1,63}(?:\.[\w-]{1,63}){1,8}/g;
|
|
2198
|
+
/**
|
|
2199
|
+
* Prose scanned by the fallback parser, in characters. A real DSN states the
|
|
2200
|
+
* failure in its first few lines; the rest is the quoted original message.
|
|
2201
|
+
* Capping bounds the regex work on hostile input.
|
|
2202
|
+
*/
|
|
2203
|
+
const PROSE_SCAN_LIMIT = 8e3;
|
|
2204
|
+
/**
|
|
2205
|
+
* Severity for a delivery failure. `statusCode` is the enhanced RFC 3463 code
|
|
2206
|
+
* when the DSN provided one; `diagnostic` is the remote server's text. Policy
|
|
2207
|
+
* rejections are separated from address failures because only the latter
|
|
2208
|
+
* justifies suppressing the address — see BounceKind.
|
|
2209
|
+
*/
|
|
2210
|
+
function classifyBounce(statusCode, diagnostic) {
|
|
2211
|
+
const code = statusCode ?? diagnostic?.match(ENHANCED_STATUS_RE)?.[1] ?? null;
|
|
2212
|
+
const policy = diagnostic != null && POLICY_DIAGNOSTIC_RE.test(diagnostic);
|
|
2213
|
+
if (code) {
|
|
2214
|
+
if (code.startsWith("4.")) return "soft";
|
|
2215
|
+
if (code.startsWith("5.7.")) return "block";
|
|
2216
|
+
if (code.startsWith("5.")) return policy ? "block" : "hard";
|
|
2217
|
+
}
|
|
2218
|
+
const smtp = diagnostic?.match(SMTP_CODE_RE)?.[1];
|
|
2219
|
+
if (smtp?.startsWith("4")) return "soft";
|
|
2220
|
+
if (smtp?.startsWith("5")) return policy ? "block" : "hard";
|
|
2221
|
+
return "soft";
|
|
2222
|
+
}
|
|
2223
|
+
/** Depth-first search for the first part of a given MIME type. */
|
|
2224
|
+
function findPart(part, mimeType) {
|
|
2225
|
+
if (!part) return void 0;
|
|
2226
|
+
if (part.mimeType === mimeType) return part;
|
|
2227
|
+
for (const child of part.parts ?? []) {
|
|
2228
|
+
const hit = findPart(child, mimeType);
|
|
2229
|
+
if (hit) return hit;
|
|
2230
|
+
}
|
|
2231
|
+
}
|
|
2232
|
+
/**
|
|
2233
|
+
* Unfold RFC 5322 continuation lines (a line beginning with whitespace belongs
|
|
2234
|
+
* to the previous one). Diagnostic-Code routinely wraps across several lines,
|
|
2235
|
+
* and reading only the first would truncate the SMTP response mid-sentence.
|
|
2236
|
+
*/
|
|
2237
|
+
function unfold(text) {
|
|
2238
|
+
const out = [];
|
|
2239
|
+
for (const raw of text.split(/\r?\n/)) if (/^[ \t]/.test(raw) && out.length > 0) out[out.length - 1] += ` ${raw.trim()}`;
|
|
2240
|
+
else out.push(raw);
|
|
2241
|
+
return out;
|
|
2242
|
+
}
|
|
2243
|
+
function fieldValue(lines, name) {
|
|
2244
|
+
const prefix = `${name.toLowerCase()}:`;
|
|
2245
|
+
for (const line of lines) if (line.toLowerCase().startsWith(prefix)) return line.slice(prefix.length).trim();
|
|
2246
|
+
return null;
|
|
2247
|
+
}
|
|
2248
|
+
/** "rfc822; jane@x.com" / "<jane@x.com>" → "jane@x.com". */
|
|
2249
|
+
function stripAddressType(value) {
|
|
2250
|
+
return (value.includes(";") ? value.slice(value.indexOf(";") + 1) : value).trim().replace(/^<|>$/g, "").trim().toLowerCase();
|
|
2251
|
+
}
|
|
2252
|
+
/**
|
|
2253
|
+
* Pull every failed recipient out of a DSN. Returns [] for ordinary mail, which
|
|
2254
|
+
* is what makes a deliberately broad Gmail query safe — the parser, not the
|
|
2255
|
+
* query, decides what counts as a bounce.
|
|
2256
|
+
*
|
|
2257
|
+
* Prefers the structured `message/delivery-status` report (locale-independent,
|
|
2258
|
+
* one block per recipient). Falls back to scraping the human-readable part for
|
|
2259
|
+
* senders that don't emit a conforming report.
|
|
2260
|
+
*/
|
|
2261
|
+
function parseBounce(msg) {
|
|
2262
|
+
const report = findPart(msg.payload, "message/delivery-status");
|
|
2263
|
+
if (report?.body?.data) {
|
|
2264
|
+
const text = Buffer.from(report.body.data, "base64url").toString("utf8");
|
|
2265
|
+
const out = [];
|
|
2266
|
+
for (const block of text.split(/\r?\n\s*\r?\n/)) {
|
|
2267
|
+
const lines = unfold(block);
|
|
2268
|
+
const finalRecipient = fieldValue(lines, "Final-Recipient") ?? fieldValue(lines, "Original-Recipient");
|
|
2269
|
+
if (!finalRecipient) continue;
|
|
2270
|
+
const recipient = stripAddressType(finalRecipient);
|
|
2271
|
+
if (!recipient.includes("@")) continue;
|
|
2272
|
+
const status = fieldValue(lines, "Status");
|
|
2273
|
+
const statusCode = status?.match(ENHANCED_STATUS_RE)?.[1] ?? null;
|
|
2274
|
+
const diagnostic = fieldValue(lines, "Diagnostic-Code");
|
|
2275
|
+
const action = fieldValue(lines, "Action")?.toLowerCase() ?? "";
|
|
2276
|
+
if (action && !action.startsWith("failed") && !action.startsWith("delayed")) continue;
|
|
2277
|
+
if (status?.trim().startsWith("2.")) continue;
|
|
2278
|
+
out.push({
|
|
2279
|
+
recipient,
|
|
2280
|
+
kind: classifyBounce(statusCode, diagnostic),
|
|
2281
|
+
statusCode,
|
|
2282
|
+
diagnostic: diagnostic?.slice(0, 300) ?? null
|
|
2283
|
+
});
|
|
2284
|
+
}
|
|
2285
|
+
if (out.length > 0) return out;
|
|
2286
|
+
}
|
|
2287
|
+
const from = msg.payload?.headers?.find((h) => h.name.toLowerCase() === "from")?.value ?? "";
|
|
2288
|
+
const subject = msg.payload?.headers?.find((h) => h.name.toLowerCase() === "subject")?.value ?? "";
|
|
2289
|
+
const senderAddress = from.match(EMAIL_RE)?.[0]?.toLowerCase() ?? null;
|
|
2290
|
+
if (!(senderAddress != null && DAEMON_ADDRESS_RE.test(senderAddress) || /(delivery (status notification|failure|has failed)|undelivered mail|returned to sender|address not found)/i.test(subject))) return [];
|
|
2291
|
+
/**
|
|
2292
|
+
* The DSN's own sender is never the address that failed. Matched by exact
|
|
2293
|
+
* address first, falling back to the canonical daemon pattern — a broader
|
|
2294
|
+
* pattern would discard a real failed recipient at, say,
|
|
2295
|
+
* `no-reply@customer.example` and the bounce would go unrecorded.
|
|
2296
|
+
*/
|
|
2297
|
+
const isSender = (addr) => addr === senderAddress || DAEMON_ADDRESS_RE.test(addr);
|
|
2298
|
+
const body = extractPlainText(msg.payload).slice(0, PROSE_SCAN_LIMIT);
|
|
2299
|
+
if (!body) return [];
|
|
2300
|
+
const statusCode = body.match(ENHANCED_STATUS_RE)?.[1] ?? null;
|
|
2301
|
+
if (!statusCode && !SMTP_CODE_RE.test(body)) return [];
|
|
2302
|
+
const ORIGINATOR_LINE = /^\s*(from|sender|reply-to|return-path|x-original-from)\s*:/i;
|
|
2303
|
+
const RECIPIENT_CUE = /^\s*(to|final-recipient|original-recipient)\s*:|(recipient|delivered to|deliver to|failed for|wasn't delivered to|was not delivered to)/i;
|
|
2304
|
+
const CODED_LINE = 3;
|
|
2305
|
+
let recipient = null;
|
|
2306
|
+
let bestScore = 0;
|
|
2307
|
+
outer: for (const line of body.split(/\r?\n/)) {
|
|
2308
|
+
if (ORIGINATOR_LINE.test(line)) continue;
|
|
2309
|
+
const score = ENHANCED_STATUS_RE.test(line) || SMTP_CODE_RE.test(line) ? CODED_LINE : RECIPIENT_CUE.test(line) ? 2 : 1;
|
|
2310
|
+
if (score <= bestScore) continue;
|
|
2311
|
+
for (const addr of line.match(EMAIL_RE) ?? []) {
|
|
2312
|
+
const lower = addr.toLowerCase();
|
|
2313
|
+
if (isSender(lower)) continue;
|
|
2314
|
+
recipient = lower;
|
|
2315
|
+
bestScore = score;
|
|
2316
|
+
if (score === CODED_LINE) break outer;
|
|
2317
|
+
break;
|
|
2318
|
+
}
|
|
2319
|
+
}
|
|
2320
|
+
if (!recipient) return [];
|
|
2321
|
+
const normalized = body.replace(/\s+/g, " ").trim();
|
|
2322
|
+
return [{
|
|
2323
|
+
recipient,
|
|
2324
|
+
kind: classifyBounce(statusCode, normalized),
|
|
2325
|
+
statusCode,
|
|
2326
|
+
diagnostic: normalized.slice(0, 300)
|
|
2327
|
+
}];
|
|
2328
|
+
}
|
|
2329
|
+
/**
|
|
2330
|
+
* Delivery failures reported to this mailbox. The query is a coarse net (DSN
|
|
2331
|
+
* senders and subjects vary by MTA); `parseBounce` discards anything that isn't
|
|
2332
|
+
* actually a delivery report, so over-matching costs a wasted fetch, not a
|
|
2333
|
+
* false bounce. No `in:inbox` — a DSN the founder archived still counts — and
|
|
2334
|
+
* no `-from:me`, which would drop self-relayed reports.
|
|
2335
|
+
*
|
|
2336
|
+
* Paginated: a heavy sender can exceed one page of DSNs inside the window, and
|
|
2337
|
+
* stopping at the first page would leave those recipients unsuppressed while
|
|
2338
|
+
* reporting a falsely low bounce rate — a silent undercount, the worst failure
|
|
2339
|
+
* mode for a check whose whole job is to notice trouble.
|
|
2340
|
+
*/
|
|
2341
|
+
async function listGmailBounces(opts, account) {
|
|
2342
|
+
const query = `(from:mailer-daemon OR from:postmaster OR subject:"Delivery Status Notification" OR subject:"Undelivered Mail Returned to Sender" OR subject:"Delivery Failure") ${opts?.since ? `after:${Math.floor(new Date(opts.since).getTime() / 1e3)}` : "newer_than:30d"}`;
|
|
2343
|
+
const limit = opts?.limit ?? 500;
|
|
2344
|
+
const ids = [];
|
|
2345
|
+
let pageToken;
|
|
2346
|
+
do {
|
|
2347
|
+
const list = await gmailJson(`/messages?${new URLSearchParams({
|
|
2348
|
+
q: query,
|
|
2349
|
+
maxResults: String(Math.min(100, limit - ids.length)),
|
|
2350
|
+
...pageToken ? { pageToken } : {}
|
|
2351
|
+
})}`, void 0, account);
|
|
2352
|
+
for (const m of list.messages ?? []) ids.push(m.id);
|
|
2353
|
+
pageToken = list.nextPageToken;
|
|
2354
|
+
} while (pageToken && ids.length < limit);
|
|
2355
|
+
return (await parallelMap(ids, 4, async (id) => {
|
|
2356
|
+
const msg = await gmailJson(`/messages/${id}?format=full`, void 0, account);
|
|
2357
|
+
const bouncedAt = new Date(Number(msg.internalDate)).toISOString();
|
|
2358
|
+
return parseBounce(msg).map((b) => Object.assign(b, {
|
|
2359
|
+
messageId: msg.id,
|
|
2360
|
+
bouncedAt
|
|
2361
|
+
}));
|
|
2362
|
+
})).flat();
|
|
2363
|
+
}
|
|
1990
2364
|
//#endregion
|
|
1991
2365
|
//#region ../../packages/core/src/identities.ts
|
|
1992
2366
|
const LEGACY_ONESHOT_ID = "legacy-oneshot";
|
|
@@ -2182,6 +2556,18 @@ function isSendDeferred(err) {
|
|
|
2182
2556
|
return err instanceof Error && err.name === "SendDeferredError";
|
|
2183
2557
|
}
|
|
2184
2558
|
/**
|
|
2559
|
+
* Thrown by sendEmail (pre-flight, before any network or LLM spend) when the
|
|
2560
|
+
* recipient has previously HARD bounced. Unlike SendDeferredError this is
|
|
2561
|
+
* permanent — callers must not leave the work queued for a retry, because no
|
|
2562
|
+
* retry can ever succeed. Name-based for the same cross-module reason.
|
|
2563
|
+
*/
|
|
2564
|
+
var SuppressedRecipientError = class extends Error {
|
|
2565
|
+
constructor(message) {
|
|
2566
|
+
super(message);
|
|
2567
|
+
this.name = "SuppressedRecipientError";
|
|
2568
|
+
}
|
|
2569
|
+
};
|
|
2570
|
+
/**
|
|
2185
2571
|
* True when an error is a TRANSIENT platform/transport failure (the OneShot
|
|
2186
2572
|
* backend or the network briefly broke) rather than a genuine negative result
|
|
2187
2573
|
* (email not found, undeliverable, no enrichment data). Callers must NOT treat
|
|
@@ -2212,6 +2598,10 @@ function todayStartSqliteUtc(now = /* @__PURE__ */ new Date()) {
|
|
|
2212
2598
|
localMidnight.setHours(0, 0, 0, 0);
|
|
2213
2599
|
return toSqliteUtc(localMidnight);
|
|
2214
2600
|
}
|
|
2601
|
+
/** `days` ago in the SQLite UTC format receipts.created_at stores — trailing-window queries (doctor's bounce rate). */
|
|
2602
|
+
function daysAgoSqliteUtc(days, now = /* @__PURE__ */ new Date()) {
|
|
2603
|
+
return toSqliteUtc(/* @__PURE__ */ new Date(now.getTime() - days * 24 * 3600 * 1e3));
|
|
2604
|
+
}
|
|
2215
2605
|
const MS_PER_WEEK = 168 * 3600 * 1e3;
|
|
2216
2606
|
const DEFAULT_WARMUP_MAX = 50;
|
|
2217
2607
|
/**
|
|
@@ -2464,6 +2854,29 @@ async function listSendingDomains() {
|
|
|
2464
2854
|
}
|
|
2465
2855
|
}
|
|
2466
2856
|
/**
|
|
2857
|
+
* Resume a paused sending domain in the wallet's pool (SDK `resumeDomain`).
|
|
2858
|
+
* Unlike `listSendingDomains`, errors PROPAGATE — this is an explicit operator
|
|
2859
|
+
* action, so a transient/auth failure must be surfaced (and retried), never
|
|
2860
|
+
* swallowed into a false "done". Returns the domain's new pool status.
|
|
2861
|
+
*/
|
|
2862
|
+
async function resumeSendingDomain(domain) {
|
|
2863
|
+
const result = await (await getAgent()).resumeDomain(domain.trim().toLowerCase());
|
|
2864
|
+
logEvent("domains.resume", {
|
|
2865
|
+
domain: domain.trim().toLowerCase(),
|
|
2866
|
+
status: result.pool_status
|
|
2867
|
+
});
|
|
2868
|
+
return result;
|
|
2869
|
+
}
|
|
2870
|
+
/** Pause a sending domain in the wallet's pool (SDK `pauseDomain`). Errors propagate (see resumeSendingDomain). */
|
|
2871
|
+
async function pauseSendingDomain(domain) {
|
|
2872
|
+
const result = await (await getAgent()).pauseDomain(domain.trim().toLowerCase());
|
|
2873
|
+
logEvent("domains.pause", {
|
|
2874
|
+
domain: domain.trim().toLowerCase(),
|
|
2875
|
+
status: result.pool_status
|
|
2876
|
+
});
|
|
2877
|
+
return result;
|
|
2878
|
+
}
|
|
2879
|
+
/**
|
|
2467
2880
|
* Derive the From localpart from the founder's name (first token, lowercased,
|
|
2468
2881
|
* non-alphanumerics stripped) so sends read e.g. `jerry@yourdomain`. Falls back
|
|
2469
2882
|
* to `agent` when the name yields nothing usable. ("Jane Doe" → "jane".)
|
|
@@ -2539,6 +2952,8 @@ async function sendEmailViaGmail(input, ctx, identity) {
|
|
|
2539
2952
|
};
|
|
2540
2953
|
}
|
|
2541
2954
|
async function sendEmail(input, ctx) {
|
|
2955
|
+
const suppression = getLedger().suppressionFor(input.to);
|
|
2956
|
+
if (suppression) throw new SuppressedRecipientError(`${input.to} hard-bounced${suppression.status_code ? ` (${suppression.status_code})` : ""} on ${suppression.bounced_at.slice(0, 10)} — not sending`);
|
|
2542
2957
|
const identity = resolveSenderIdentity(input.to);
|
|
2543
2958
|
if (identity.provider === "gmail") return sendEmailViaGmail(input, ctx, identity);
|
|
2544
2959
|
const agent = await getAgent();
|
|
@@ -2856,6 +3271,41 @@ async function listInbox(opts) {
|
|
|
2856
3271
|
agent_id: ok.map((r) => r.agent_id).join("+")
|
|
2857
3272
|
};
|
|
2858
3273
|
}
|
|
3274
|
+
/**
|
|
3275
|
+
* Delivery failures across the whole sender pool. Gmail identities only: a DSN
|
|
3276
|
+
* comes back to the envelope sender, and for OneShot sends that return path
|
|
3277
|
+
* belongs to the platform, not to us — nothing surfaces in its inbox API.
|
|
3278
|
+
*
|
|
3279
|
+
* Attribution is free and exact: the mailbox that RECEIVED the bounce is the
|
|
3280
|
+
* mailbox that sent the message, so no join back through sender_assignments is
|
|
3281
|
+
* needed to know whose reputation this counts against.
|
|
3282
|
+
*
|
|
3283
|
+
* Per-source try/catch like listInbox — one revoked Gmail token must not blind
|
|
3284
|
+
* bounce detection for every other identity. Unlike listInbox this NEVER throws
|
|
3285
|
+
* on total failure: it runs on a background sweep where the only sane response
|
|
3286
|
+
* to "no sources answered" is to report nothing and retry next tick.
|
|
3287
|
+
*/
|
|
3288
|
+
async function listBounces(opts) {
|
|
3289
|
+
return (await parallelMap(resolveIdentities(loadConfig()).filter((i) => i.provider === "gmail"), 3, async (identity) => {
|
|
3290
|
+
const account = gmailAccountFor(identity);
|
|
3291
|
+
if (!account) {
|
|
3292
|
+
logEvent("bounce.source_skipped", {
|
|
3293
|
+
source: identity.id,
|
|
3294
|
+
reason: "no_token"
|
|
3295
|
+
}, "warn");
|
|
3296
|
+
return [];
|
|
3297
|
+
}
|
|
3298
|
+
try {
|
|
3299
|
+
return (await withDeadline(listGmailBounces(opts, account), INBOX_SOURCE_TIMEOUT_MS, `bounce source '${identity.id}'`)).map((b) => Object.assign(b, { identityId: identity.id }));
|
|
3300
|
+
} catch (err) {
|
|
3301
|
+
logEvent("bounce.source_failed", {
|
|
3302
|
+
source: identity.id,
|
|
3303
|
+
message_120: (err.message ?? "").slice(0, 120)
|
|
3304
|
+
}, "warn");
|
|
3305
|
+
return [];
|
|
3306
|
+
}
|
|
3307
|
+
})).flat();
|
|
3308
|
+
}
|
|
2859
3309
|
async function sendSms(input, ctx) {
|
|
2860
3310
|
const agent = await getAgent();
|
|
2861
3311
|
const opts = {
|
|
@@ -3136,6 +3586,126 @@ async function waitForSendsToDrain(opts) {
|
|
|
3136
3586
|
};
|
|
3137
3587
|
}
|
|
3138
3588
|
//#endregion
|
|
3589
|
+
//#region ../../packages/core/src/telemetry.ts
|
|
3590
|
+
/**
|
|
3591
|
+
* Default first-party ingest endpoint — a stable custom domain we own, so the
|
|
3592
|
+
* backend can move without re-shipping the client and no hosting details leak
|
|
3593
|
+
* into the OSS source. Operators can override per-run with
|
|
3594
|
+
* ONESHOT_GTM_TELEMETRY_URL; set it to "" to make telemetry a hard no-op.
|
|
3595
|
+
*/
|
|
3596
|
+
const DEFAULT_TELEMETRY_URL = "https://telemetry.oneshotagent.com/v1/cli";
|
|
3597
|
+
const TELEMETRY_TIMEOUT_MS = 1e3;
|
|
3598
|
+
/**
|
|
3599
|
+
* Resolve the ingest URL. `ONESHOT_GTM_TELEMETRY_URL` overrides the default so
|
|
3600
|
+
* the receiver can be exercised locally / against staging. An *explicitly
|
|
3601
|
+
* empty* override (`ONESHOT_GTM_TELEMETRY_URL=""`) resolves to `""` — a hard
|
|
3602
|
+
* no-op (see reportCommand's `if (!url) return`) — honoring the documented kill
|
|
3603
|
+
* path. Only an absent var falls back to the default endpoint.
|
|
3604
|
+
*/
|
|
3605
|
+
function telemetryUrl(env = process.env) {
|
|
3606
|
+
const raw = env["ONESHOT_GTM_TELEMETRY_URL"];
|
|
3607
|
+
if (raw === void 0) return DEFAULT_TELEMETRY_URL;
|
|
3608
|
+
return raw.trim();
|
|
3609
|
+
}
|
|
3610
|
+
/**
|
|
3611
|
+
* Pure gate. Returns false — meaning "construct nothing, send nothing" — when
|
|
3612
|
+
* either the persisted flag is off or the env kill switch is set. Env wins so
|
|
3613
|
+
* a single shell-session export reliably silences telemetry regardless of
|
|
3614
|
+
* what's on disk.
|
|
3615
|
+
*/
|
|
3616
|
+
function shouldSendTelemetry(cfg, env = process.env) {
|
|
3617
|
+
const raw = env["ONESHOT_GTM_TELEMETRY"]?.trim().toLowerCase();
|
|
3618
|
+
if (raw === "0" || raw === "false" || raw === "off" || raw === "no") return false;
|
|
3619
|
+
return cfg.telemetryEnabled !== false;
|
|
3620
|
+
}
|
|
3621
|
+
/**
|
|
3622
|
+
* Pure builder — no I/O, no clock, no globals. The caller supplies every
|
|
3623
|
+
* value so tests can pin them (mirrors `buildEventLine`). Strips nothing:
|
|
3624
|
+
* the field set IS the whitelist, so anything not listed simply can't be
|
|
3625
|
+
* carried.
|
|
3626
|
+
*/
|
|
3627
|
+
function buildTelemetryPayload(input) {
|
|
3628
|
+
return {
|
|
3629
|
+
command: input.command,
|
|
3630
|
+
flags: input.flags,
|
|
3631
|
+
outcome: input.outcome,
|
|
3632
|
+
duration_ms: Math.max(0, Math.round(input.durationMs)),
|
|
3633
|
+
version: input.version,
|
|
3634
|
+
os: input.platform,
|
|
3635
|
+
bun_version: input.bunVersion,
|
|
3636
|
+
anonymous_machine_id: input.clientId,
|
|
3637
|
+
llm_provider: input.llmProvider
|
|
3638
|
+
};
|
|
3639
|
+
}
|
|
3640
|
+
/**
|
|
3641
|
+
* Fire-and-forget POST. Resolves either way — a network error, a non-2xx, or
|
|
3642
|
+
* the timeout all resolve to undefined. Bounded by an AbortController so a
|
|
3643
|
+
* hung endpoint can't delay CLI exit beyond TELEMETRY_TIMEOUT_MS.
|
|
3644
|
+
*/
|
|
3645
|
+
async function reportCommand(payload, url = telemetryUrl()) {
|
|
3646
|
+
if (!url) return;
|
|
3647
|
+
const controller = new AbortController();
|
|
3648
|
+
const timer = setTimeout(() => controller.abort(), TELEMETRY_TIMEOUT_MS);
|
|
3649
|
+
try {
|
|
3650
|
+
await fetch(url, {
|
|
3651
|
+
method: "POST",
|
|
3652
|
+
headers: { "content-type": "application/json" },
|
|
3653
|
+
body: JSON.stringify(payload),
|
|
3654
|
+
signal: controller.signal
|
|
3655
|
+
});
|
|
3656
|
+
} catch {} finally {
|
|
3657
|
+
clearTimeout(timer);
|
|
3658
|
+
}
|
|
3659
|
+
}
|
|
3660
|
+
/**
|
|
3661
|
+
* The single send path shared by every emitter (CLI dispatch, server
|
|
3662
|
+
* executions). Resolves the endpoint + opt-out gate, reads the anonymous
|
|
3663
|
+
* install id / provider from config, stamps host fields (os, bun), and fires.
|
|
3664
|
+
* Best-effort: never throws, never blocks the caller. Centralizing this keeps
|
|
3665
|
+
* the CLI and server channels from drifting as the payload evolves.
|
|
3666
|
+
*/
|
|
3667
|
+
async function reportTelemetryEvent(input, env = process.env) {
|
|
3668
|
+
try {
|
|
3669
|
+
const url = telemetryUrl(env);
|
|
3670
|
+
if (!url) return;
|
|
3671
|
+
const cfg = loadConfigCached();
|
|
3672
|
+
if (!shouldSendTelemetry(cfg, env)) return;
|
|
3673
|
+
await reportCommand(buildTelemetryPayload({
|
|
3674
|
+
command: input.command,
|
|
3675
|
+
flags: input.flags,
|
|
3676
|
+
outcome: input.outcome,
|
|
3677
|
+
durationMs: input.durationMs,
|
|
3678
|
+
version: input.version,
|
|
3679
|
+
clientId: cfg.clientId,
|
|
3680
|
+
llmProvider: cfg.llmProvider,
|
|
3681
|
+
platform: process.platform,
|
|
3682
|
+
bunVersion: typeof Bun !== "undefined" ? Bun.version : ""
|
|
3683
|
+
}), url);
|
|
3684
|
+
} catch {}
|
|
3685
|
+
}
|
|
3686
|
+
//#endregion
|
|
3687
|
+
//#region ../../packages/core/src/version.ts
|
|
3688
|
+
/**
|
|
3689
|
+
* Read the `version` from the caller's package.json so `--version` output and
|
|
3690
|
+
* the telemetry `version` field can't drift from the published release.
|
|
3691
|
+
*
|
|
3692
|
+
* Pass `import.meta.url`. The assumption — true for both current callers
|
|
3693
|
+
* (`apps/cli/src/index.ts`, `apps/server/src/telemetry.ts`) — is that the
|
|
3694
|
+
* calling file sits one directory under its package root, so `../package.json`
|
|
3695
|
+
* relative to the file's directory is the package manifest. Any failure
|
|
3696
|
+
* (unexpected layout, unreadable file, missing field) falls back to "0.0.0"
|
|
3697
|
+
* rather than throwing.
|
|
3698
|
+
*/
|
|
3699
|
+
function readPackageVersion(metaUrl) {
|
|
3700
|
+
try {
|
|
3701
|
+
const here = dirname(fileURLToPath(metaUrl));
|
|
3702
|
+
const pkg = JSON.parse(readFileSync(join(here, "..", "package.json"), "utf8"));
|
|
3703
|
+
return typeof pkg.version === "string" ? pkg.version : "0.0.0";
|
|
3704
|
+
} catch {
|
|
3705
|
+
return "0.0.0";
|
|
3706
|
+
}
|
|
3707
|
+
}
|
|
3708
|
+
//#endregion
|
|
3139
3709
|
//#region src/api/health.ts
|
|
3140
3710
|
/**
|
|
3141
3711
|
* Liveness + in-flight-send count. Exposes the same in-memory `activeSendCount()`
|
|
@@ -3567,6 +4137,41 @@ function errorDraft(message) {
|
|
|
3567
4137
|
};
|
|
3568
4138
|
}
|
|
3569
4139
|
/**
|
|
4140
|
+
* Record WHY a single target failed, next to every `errorDraft` call site.
|
|
4141
|
+
*
|
|
4142
|
+
* What reaches the queue row (and the founder's screen) is errorDraft's 80-char
|
|
4143
|
+
* slice of `err.message` — for an SDK ToolError that's the generic "Tool
|
|
4144
|
+
* request failed", true and useless. The status code and response body carry
|
|
4145
|
+
* the actual reason (`403 domain_not_owned`, the last time one was captured).
|
|
4146
|
+
* Without this, a drain could fail every send and leave nothing in
|
|
4147
|
+
* events.jsonl to diagnose from.
|
|
4148
|
+
*
|
|
4149
|
+
* Mirrors the whole-run handler in apps/server/src/api/run.ts, which already
|
|
4150
|
+
* logs these fields; per-target failures were the gap.
|
|
4151
|
+
*/
|
|
4152
|
+
function logTargetError(input) {
|
|
4153
|
+
const e = input.err;
|
|
4154
|
+
try {
|
|
4155
|
+
logTargetErrorUnsafe(e, input);
|
|
4156
|
+
} catch {}
|
|
4157
|
+
}
|
|
4158
|
+
/** Coerce an unknown thrown field to a string — never assume `.slice()` exists. */
|
|
4159
|
+
function text(v) {
|
|
4160
|
+
return typeof v === "string" ? v : v == null ? "" : String(v);
|
|
4161
|
+
}
|
|
4162
|
+
function logTargetErrorUnsafe(e, input) {
|
|
4163
|
+
const causeMsg = e?.cause instanceof Error ? text(e.cause.message) : e?.cause ? text(e.cause) : null;
|
|
4164
|
+
logEvent("play.target_error", {
|
|
4165
|
+
play: input.playName,
|
|
4166
|
+
...typeof input.to === "string" && input.to.includes("@") ? { to_domain: input.to.split("@")[1] } : {},
|
|
4167
|
+
message_200: text(e?.message).slice(0, 200),
|
|
4168
|
+
status_code: typeof e?.statusCode === "number" ? e.statusCode : null,
|
|
4169
|
+
response_body_400: typeof e?.responseBody === "string" ? e.responseBody.slice(0, 400) : null,
|
|
4170
|
+
cause_200: causeMsg ? causeMsg.slice(0, 200) : null,
|
|
4171
|
+
stack_300: text(e?.stack).slice(0, 300)
|
|
4172
|
+
}, "error");
|
|
4173
|
+
}
|
|
4174
|
+
/**
|
|
3570
4175
|
* Deterministic, semantics-preserving cleanups that the LLM occasionally
|
|
3571
4176
|
* slips through despite the humanizer rules being in its system prompt.
|
|
3572
4177
|
* Applied silently inside `draftEmailFromPrompt` so these four flags never
|
|
@@ -4004,6 +4609,85 @@ async function pollInboxReplies() {
|
|
|
4004
4609
|
return out;
|
|
4005
4610
|
}
|
|
4006
4611
|
/**
|
|
4612
|
+
* Poll the mailbox for DSNs and act on them. Sibling to pollInboxReplies:
|
|
4613
|
+
* read-only except for the bounce row and the resulting cadence stop, so it's
|
|
4614
|
+
* safe on a background timer as well as inside advanceCadence.
|
|
4615
|
+
*
|
|
4616
|
+
* Without a background caller the tool learns an address is dead only by
|
|
4617
|
+
* failing to get a reply — meanwhile the sequence keeps emailing it, paying
|
|
4618
|
+
* per send, and each refusal costs sending reputation.
|
|
4619
|
+
*/
|
|
4620
|
+
async function pollInboxBounces() {
|
|
4621
|
+
const ledger = getLedger();
|
|
4622
|
+
const out = {
|
|
4623
|
+
polled: 0,
|
|
4624
|
+
recorded: 0,
|
|
4625
|
+
cadencesStopped: 0,
|
|
4626
|
+
details: []
|
|
4627
|
+
};
|
|
4628
|
+
const bounces = await listBounces();
|
|
4629
|
+
out.polled = bounces.length;
|
|
4630
|
+
for (const b of bounces) {
|
|
4631
|
+
const prospect = ledger.findProspectByEmail(b.recipient);
|
|
4632
|
+
if (!ledger.recordBounce({
|
|
4633
|
+
messageId: b.messageId,
|
|
4634
|
+
recipient: b.recipient,
|
|
4635
|
+
identityId: b.identityId,
|
|
4636
|
+
kind: b.kind,
|
|
4637
|
+
statusCode: b.statusCode,
|
|
4638
|
+
diagnostic: b.diagnostic,
|
|
4639
|
+
prospectId: prospect?.id ?? null,
|
|
4640
|
+
bouncedAt: b.bouncedAt
|
|
4641
|
+
})) continue;
|
|
4642
|
+
out.recorded++;
|
|
4643
|
+
if (b.kind === "soft") continue;
|
|
4644
|
+
if (!prospect) {
|
|
4645
|
+
out.details.push({
|
|
4646
|
+
recipient: b.recipient,
|
|
4647
|
+
kind: b.kind,
|
|
4648
|
+
statusCode: b.statusCode,
|
|
4649
|
+
playName: null
|
|
4650
|
+
});
|
|
4651
|
+
continue;
|
|
4652
|
+
}
|
|
4653
|
+
for (const cad of ledger.listCadencesForProspect(prospect.id)) {
|
|
4654
|
+
ledger.recordSequenceEvent({
|
|
4655
|
+
prospectId: prospect.id,
|
|
4656
|
+
playName: cad.play_name,
|
|
4657
|
+
stepIndex: cad.current_step,
|
|
4658
|
+
channel: "email",
|
|
4659
|
+
status: "bounced",
|
|
4660
|
+
metadata: {
|
|
4661
|
+
kind: b.kind,
|
|
4662
|
+
statusCode: b.statusCode,
|
|
4663
|
+
diagnostic: b.diagnostic,
|
|
4664
|
+
identityId: b.identityId
|
|
4665
|
+
}
|
|
4666
|
+
});
|
|
4667
|
+
if (b.kind === "hard" && cad.status === "active") {
|
|
4668
|
+
ledger.setCadenceStatus({
|
|
4669
|
+
prospectId: prospect.id,
|
|
4670
|
+
playName: cad.play_name,
|
|
4671
|
+
status: "bounced"
|
|
4672
|
+
});
|
|
4673
|
+
out.cadencesStopped++;
|
|
4674
|
+
}
|
|
4675
|
+
out.details.push({
|
|
4676
|
+
recipient: b.recipient,
|
|
4677
|
+
kind: b.kind,
|
|
4678
|
+
statusCode: b.statusCode,
|
|
4679
|
+
playName: cad.play_name
|
|
4680
|
+
});
|
|
4681
|
+
}
|
|
4682
|
+
}
|
|
4683
|
+
if (out.recorded > 0) logEvent("bounce.poll.done", {
|
|
4684
|
+
polled: out.polled,
|
|
4685
|
+
recorded: out.recorded,
|
|
4686
|
+
cadences_stopped: out.cadencesStopped
|
|
4687
|
+
});
|
|
4688
|
+
return out;
|
|
4689
|
+
}
|
|
4690
|
+
/**
|
|
4007
4691
|
* Per-prospect cadence step runner. Single source of truth for both the
|
|
4008
4692
|
* batch `advanceCadence` (CLI) and the per-row /cadences UI (preview + send).
|
|
4009
4693
|
* Caller decides dryRun (no send) or persistedPayload (send a previously
|
|
@@ -4027,6 +4711,22 @@ async function runCadenceStepForProspect(opts) {
|
|
|
4027
4711
|
receiptIds: [],
|
|
4028
4712
|
note: `cadence is ${cadence.status}`
|
|
4029
4713
|
};
|
|
4714
|
+
if (cadence.prospect_email) {
|
|
4715
|
+
const suppression = ledger.suppressionFor(cadence.prospect_email);
|
|
4716
|
+
if (suppression) {
|
|
4717
|
+
ledger.setCadenceStatus({
|
|
4718
|
+
prospectId: opts.prospectId,
|
|
4719
|
+
playName: opts.playName,
|
|
4720
|
+
status: "bounced"
|
|
4721
|
+
});
|
|
4722
|
+
return {
|
|
4723
|
+
action: "skipped",
|
|
4724
|
+
payload: null,
|
|
4725
|
+
receiptIds: [],
|
|
4726
|
+
note: `suppressed: hard-bounced${suppression.status_code ? ` ${suppression.status_code}` : ""}`
|
|
4727
|
+
};
|
|
4728
|
+
}
|
|
4729
|
+
}
|
|
4030
4730
|
const seq = effectiveSequence(opts.playName);
|
|
4031
4731
|
if (!seq) return {
|
|
4032
4732
|
action: "skipped",
|
|
@@ -4598,6 +5298,11 @@ async function runEmailPlay(def, opts) {
|
|
|
4598
5298
|
};
|
|
4599
5299
|
} catch (err) {
|
|
4600
5300
|
if (isSendDeferred(err)) throw err;
|
|
5301
|
+
logTargetError({
|
|
5302
|
+
playName: def.playName,
|
|
5303
|
+
to: def.toEmail(target),
|
|
5304
|
+
err
|
|
5305
|
+
});
|
|
4601
5306
|
return {
|
|
4602
5307
|
target,
|
|
4603
5308
|
...errorDraft(err?.message),
|
|
@@ -4705,18 +5410,18 @@ async function draftInboxReply(input) {
|
|
|
4705
5410
|
}
|
|
4706
5411
|
//#endregion
|
|
4707
5412
|
//#region ../../packages/plays/src/accelerator-batch.ts
|
|
4708
|
-
const PLAY_NAME$
|
|
5413
|
+
const PLAY_NAME$26 = "accelerator-batch";
|
|
4709
5414
|
function runAcceleratorBatch(opts) {
|
|
4710
5415
|
const senderCohortFor = (t) => (t.senderCohort?.trim() || opts.senderCohort || "").trim();
|
|
4711
5416
|
const offerFor = (t) => t.freeForCohortOffer ?? opts.freeForCohortOffer;
|
|
4712
5417
|
return runEmailPlay({
|
|
4713
|
-
playName: PLAY_NAME$
|
|
5418
|
+
playName: PLAY_NAME$26,
|
|
4714
5419
|
promptName: "accelerator-batch-email",
|
|
4715
5420
|
maxBodyWords: 150,
|
|
4716
5421
|
enrollCadence: true,
|
|
4717
5422
|
toEmail: (t) => t.email,
|
|
4718
5423
|
prepare: (t, dryRun) => standardEnrich({
|
|
4719
|
-
playName: PLAY_NAME$
|
|
5424
|
+
playName: PLAY_NAME$26,
|
|
4720
5425
|
enrichInput: {
|
|
4721
5426
|
...t.email ? { email: t.email } : {},
|
|
4722
5427
|
...t.linkedinUrl ? { linkedinUrl: t.linkedinUrl } : {},
|
|
@@ -4751,14 +5456,14 @@ function runAcceleratorBatch(opts) {
|
|
|
4751
5456
|
}, opts);
|
|
4752
5457
|
}
|
|
4753
5458
|
registerSequence({
|
|
4754
|
-
playName: PLAY_NAME$
|
|
5459
|
+
playName: PLAY_NAME$26,
|
|
4755
5460
|
steps: [{
|
|
4756
5461
|
dayOffset: 5,
|
|
4757
5462
|
channel: "email",
|
|
4758
5463
|
breakOnReply: true,
|
|
4759
5464
|
label: "single follow-up + breakup",
|
|
4760
5465
|
builder: buildFollowUpEmail({
|
|
4761
|
-
playName: PLAY_NAME$
|
|
5466
|
+
playName: PLAY_NAME$26,
|
|
4762
5467
|
promptName: "breakup-email",
|
|
4763
5468
|
contextLines: [`PLAY: accelerator-batch. The accelerator-batch motion is one-touch + one breakup; this is the final note. Lean very short.`]
|
|
4764
5469
|
})
|
|
@@ -4766,7 +5471,7 @@ registerSequence({
|
|
|
4766
5471
|
});
|
|
4767
5472
|
//#endregion
|
|
4768
5473
|
//#region ../../packages/plays/src/breakup-revive.ts
|
|
4769
|
-
const PLAY_NAME$
|
|
5474
|
+
const PLAY_NAME$25 = "breakup-revive";
|
|
4770
5475
|
async function runBreakupRevive(opts) {
|
|
4771
5476
|
const cfg = loadConfig();
|
|
4772
5477
|
if (!cfg.founderName || !cfg.productOneLiner) throw new Error("founder profile incomplete. Run: oneshot-gtm config founder");
|
|
@@ -4787,7 +5492,7 @@ async function runBreakupRevive(opts) {
|
|
|
4787
5492
|
});
|
|
4788
5493
|
const flags = lintEmail(draft.subject, draft.body, 80);
|
|
4789
5494
|
const send = await sendDraftedEmail({
|
|
4790
|
-
playName: PLAY_NAME$
|
|
5495
|
+
playName: PLAY_NAME$25,
|
|
4791
5496
|
to: t.email,
|
|
4792
5497
|
draft,
|
|
4793
5498
|
flags,
|
|
@@ -4818,6 +5523,11 @@ async function runBreakupRevive(opts) {
|
|
|
4818
5523
|
});
|
|
4819
5524
|
} catch (err) {
|
|
4820
5525
|
if (isSendDeferred(err)) throw err;
|
|
5526
|
+
logTargetError({
|
|
5527
|
+
playName: PLAY_NAME$25,
|
|
5528
|
+
to: t.email,
|
|
5529
|
+
err
|
|
5530
|
+
});
|
|
4821
5531
|
const stub = errorDraft(err?.message);
|
|
4822
5532
|
drafted.push({
|
|
4823
5533
|
prospectEmail: t.email,
|
|
@@ -4850,10 +5560,10 @@ function ledgerScanTargets(opts) {
|
|
|
4850
5560
|
}
|
|
4851
5561
|
//#endregion
|
|
4852
5562
|
//#region ../../packages/plays/src/competitor-switch.ts
|
|
4853
|
-
const PLAY_NAME$
|
|
5563
|
+
const PLAY_NAME$24 = "competitor-switch";
|
|
4854
5564
|
function runCompetitorSwitch(opts) {
|
|
4855
5565
|
return runEmailPlay({
|
|
4856
|
-
playName: PLAY_NAME$
|
|
5566
|
+
playName: PLAY_NAME$24,
|
|
4857
5567
|
promptName: "competitor-switch-email",
|
|
4858
5568
|
maxBodyWords: 150,
|
|
4859
5569
|
enrollCadence: true,
|
|
@@ -4865,7 +5575,7 @@ function runCompetitorSwitch(opts) {
|
|
|
4865
5575
|
...t.email ? { email: t.email } : {},
|
|
4866
5576
|
name: t.name,
|
|
4867
5577
|
companyDomain: emailDomain(t.email)
|
|
4868
|
-
}, { playName: PLAY_NAME$
|
|
5578
|
+
}, { playName: PLAY_NAME$24 });
|
|
4869
5579
|
if (enr.receiptId) receiptIds.push(enr.receiptId);
|
|
4870
5580
|
const enrichmentFailed = enr.result.status === "failed";
|
|
4871
5581
|
const dossier = JSON.stringify(enr.result, null, 2).slice(0, 3500);
|
|
@@ -4890,7 +5600,7 @@ function runCompetitorSwitch(opts) {
|
|
|
4890
5600
|
}
|
|
4891
5601
|
},
|
|
4892
5602
|
maxSteps: 12
|
|
4893
|
-
}, { playName: PLAY_NAME$
|
|
5603
|
+
}, { playName: PLAY_NAME$24 });
|
|
4894
5604
|
receiptIds.push(browse.receiptId);
|
|
4895
5605
|
scrapedEvidence = typeof browse.result.output === "string" ? browse.result.output : JSON.stringify(browse.result.output ?? {});
|
|
4896
5606
|
}
|
|
@@ -4929,14 +5639,14 @@ function runCompetitorSwitch(opts) {
|
|
|
4929
5639
|
}, opts);
|
|
4930
5640
|
}
|
|
4931
5641
|
registerSequence({
|
|
4932
|
-
playName: PLAY_NAME$
|
|
5642
|
+
playName: PLAY_NAME$24,
|
|
4933
5643
|
steps: [{
|
|
4934
5644
|
dayOffset: 3,
|
|
4935
5645
|
channel: "email",
|
|
4936
5646
|
breakOnReply: true,
|
|
4937
5647
|
label: "value follow-up",
|
|
4938
5648
|
builder: buildFollowUpEmail({
|
|
4939
|
-
playName: PLAY_NAME$
|
|
5649
|
+
playName: PLAY_NAME$24,
|
|
4940
5650
|
promptName: "competitor-switch-followup",
|
|
4941
5651
|
contextLines: [`PLAY: competitor-switch. Day-3 value follow-up after the migration-honesty pitch.`]
|
|
4942
5652
|
})
|
|
@@ -4946,7 +5656,7 @@ registerSequence({
|
|
|
4946
5656
|
breakOnReply: true,
|
|
4947
5657
|
label: "breakup",
|
|
4948
5658
|
builder: buildFollowUpEmail({
|
|
4949
|
-
playName: PLAY_NAME$
|
|
5659
|
+
playName: PLAY_NAME$24,
|
|
4950
5660
|
promptName: "breakup-email",
|
|
4951
5661
|
contextLines: [`PLAY: competitor-switch. Final breakup after the migration-honesty pitch.`]
|
|
4952
5662
|
})
|
|
@@ -4954,11 +5664,11 @@ registerSequence({
|
|
|
4954
5664
|
});
|
|
4955
5665
|
//#endregion
|
|
4956
5666
|
//#region ../../packages/plays/src/hiring-signal.ts
|
|
4957
|
-
const PLAY_NAME$
|
|
5667
|
+
const PLAY_NAME$23 = "hiring-signal";
|
|
4958
5668
|
const NO_HOOK = "(no specific job post phrase scraped)";
|
|
4959
5669
|
function runHiringSignal(opts) {
|
|
4960
5670
|
return runEmailPlay({
|
|
4961
|
-
playName: PLAY_NAME$
|
|
5671
|
+
playName: PLAY_NAME$23,
|
|
4962
5672
|
promptName: "hiring-signal-email",
|
|
4963
5673
|
maxBodyWords: 150,
|
|
4964
5674
|
enrollCadence: true,
|
|
@@ -4973,12 +5683,12 @@ function runHiringSignal(opts) {
|
|
|
4973
5683
|
const search = await webSearch({
|
|
4974
5684
|
query: `${t.company} careers ${t.jobTitle} site:lever.co OR site:greenhouse.io OR site:workable.com OR site:ashbyhq.com`,
|
|
4975
5685
|
maxResults: 5
|
|
4976
|
-
}, { playName: PLAY_NAME$
|
|
5686
|
+
}, { playName: PLAY_NAME$23 });
|
|
4977
5687
|
receiptIds.push(search.receiptId);
|
|
4978
5688
|
jobUrl = search.result.results[0]?.url;
|
|
4979
5689
|
}
|
|
4980
5690
|
if (jobUrl) {
|
|
4981
|
-
const read = await webRead({ url: jobUrl }, { playName: PLAY_NAME$
|
|
5691
|
+
const read = await webRead({ url: jobUrl }, { playName: PLAY_NAME$23 });
|
|
4982
5692
|
receiptIds.push(read.receiptId);
|
|
4983
5693
|
const md = read.result.markdown ?? "";
|
|
4984
5694
|
jobPostHook = (md.match(/(?:About the role|Responsibilities|Requirements|What you[' ]?ll do)[^\n]*\n+([\s\S]{40,300})/i)?.[1] ?? md.slice(0, 400)).replace(/\s+/g, " ").trim();
|
|
@@ -5013,14 +5723,14 @@ function runHiringSignal(opts) {
|
|
|
5013
5723
|
}, opts);
|
|
5014
5724
|
}
|
|
5015
5725
|
registerSequence({
|
|
5016
|
-
playName: PLAY_NAME$
|
|
5726
|
+
playName: PLAY_NAME$23,
|
|
5017
5727
|
steps: [{
|
|
5018
5728
|
dayOffset: 3,
|
|
5019
5729
|
channel: "email",
|
|
5020
5730
|
breakOnReply: true,
|
|
5021
5731
|
label: "value follow-up",
|
|
5022
5732
|
builder: buildFollowUpEmail({
|
|
5023
|
-
playName: PLAY_NAME$
|
|
5733
|
+
playName: PLAY_NAME$23,
|
|
5024
5734
|
promptName: "hiring-signal-followup",
|
|
5025
5735
|
contextLines: [`PLAY: hiring-signal. Day-3 value follow-up about the open role.`]
|
|
5026
5736
|
})
|
|
@@ -5030,7 +5740,7 @@ registerSequence({
|
|
|
5030
5740
|
breakOnReply: true,
|
|
5031
5741
|
label: "breakup",
|
|
5032
5742
|
builder: buildFollowUpEmail({
|
|
5033
|
-
playName: PLAY_NAME$
|
|
5743
|
+
playName: PLAY_NAME$23,
|
|
5034
5744
|
promptName: "breakup-email",
|
|
5035
5745
|
contextLines: [`PLAY: hiring-signal. Final breakup.`]
|
|
5036
5746
|
})
|
|
@@ -5038,15 +5748,15 @@ registerSequence({
|
|
|
5038
5748
|
});
|
|
5039
5749
|
//#endregion
|
|
5040
5750
|
//#region ../../packages/plays/src/job-change.ts
|
|
5041
|
-
const PLAY_NAME$
|
|
5751
|
+
const PLAY_NAME$22 = "job-change";
|
|
5042
5752
|
const jobChangeDef = {
|
|
5043
|
-
playName: PLAY_NAME$
|
|
5753
|
+
playName: PLAY_NAME$22,
|
|
5044
5754
|
promptName: "job-change-email",
|
|
5045
5755
|
maxBodyWords: 150,
|
|
5046
5756
|
enrollCadence: true,
|
|
5047
5757
|
toEmail: (t) => t.email,
|
|
5048
5758
|
prepare: (t, dryRun) => standardEnrich({
|
|
5049
|
-
playName: PLAY_NAME$
|
|
5759
|
+
playName: PLAY_NAME$22,
|
|
5050
5760
|
enrichInput: {
|
|
5051
5761
|
...t.email ? { email: t.email } : {},
|
|
5052
5762
|
...t.linkedinUrl ? { linkedinUrl: t.linkedinUrl } : {},
|
|
@@ -5080,14 +5790,14 @@ function runJobChange(opts) {
|
|
|
5080
5790
|
return runEmailPlay(jobChangeDef, opts);
|
|
5081
5791
|
}
|
|
5082
5792
|
registerSequence({
|
|
5083
|
-
playName: PLAY_NAME$
|
|
5793
|
+
playName: PLAY_NAME$22,
|
|
5084
5794
|
steps: [{
|
|
5085
5795
|
dayOffset: 5,
|
|
5086
5796
|
channel: "email",
|
|
5087
5797
|
breakOnReply: true,
|
|
5088
5798
|
label: "value follow-up",
|
|
5089
5799
|
builder: buildFollowUpEmail({
|
|
5090
|
-
playName: PLAY_NAME$
|
|
5800
|
+
playName: PLAY_NAME$22,
|
|
5091
5801
|
promptName: "job-change-followup",
|
|
5092
5802
|
contextLines: [`CONTEXT: prospect recently joined a new role; first email went unanswered ~5 days ago.`]
|
|
5093
5803
|
})
|
|
@@ -5097,7 +5807,7 @@ registerSequence({
|
|
|
5097
5807
|
breakOnReply: true,
|
|
5098
5808
|
label: "breakup",
|
|
5099
5809
|
builder: buildFollowUpEmail({
|
|
5100
|
-
playName: PLAY_NAME$
|
|
5810
|
+
playName: PLAY_NAME$22,
|
|
5101
5811
|
promptName: "breakup-email",
|
|
5102
5812
|
contextLines: [`PLAY: job-change. Sender is closing the file.`]
|
|
5103
5813
|
})
|
|
@@ -5105,7 +5815,7 @@ registerSequence({
|
|
|
5105
5815
|
});
|
|
5106
5816
|
//#endregion
|
|
5107
5817
|
//#region ../../packages/plays/src/luma-events.ts
|
|
5108
|
-
const PLAY_NAME$
|
|
5818
|
+
const PLAY_NAME$21 = "luma-events";
|
|
5109
5819
|
/**
|
|
5110
5820
|
* Past this many days, a passed event's guest-list signal is stale: we still
|
|
5111
5821
|
* draft a (retrospective) email but hold it behind a `stale-event` flag for
|
|
@@ -5178,12 +5888,12 @@ function describeEventDate(iso) {
|
|
|
5178
5888
|
};
|
|
5179
5889
|
}
|
|
5180
5890
|
const lumaEventsDef = {
|
|
5181
|
-
playName: PLAY_NAME$
|
|
5891
|
+
playName: PLAY_NAME$21,
|
|
5182
5892
|
promptName: "luma-events-email",
|
|
5183
5893
|
maxBodyWords: 150,
|
|
5184
5894
|
toEmail: (t) => t.email,
|
|
5185
5895
|
prepare: (t) => standardEnrich({
|
|
5186
|
-
playName: PLAY_NAME$
|
|
5896
|
+
playName: PLAY_NAME$21,
|
|
5187
5897
|
enrichInput: {
|
|
5188
5898
|
...t.email ? { email: t.email } : {},
|
|
5189
5899
|
name: t.name,
|
|
@@ -5230,10 +5940,10 @@ function runLumaEvents(opts) {
|
|
|
5230
5940
|
}
|
|
5231
5941
|
//#endregion
|
|
5232
5942
|
//#region ../../packages/plays/src/podcast-guest.ts
|
|
5233
|
-
const PLAY_NAME$
|
|
5943
|
+
const PLAY_NAME$20 = "podcast-guest";
|
|
5234
5944
|
function runPodcastGuest(opts) {
|
|
5235
5945
|
return runEmailPlay({
|
|
5236
|
-
playName: PLAY_NAME$
|
|
5946
|
+
playName: PLAY_NAME$20,
|
|
5237
5947
|
promptName: "podcast-guest-email",
|
|
5238
5948
|
maxBodyWords: 150,
|
|
5239
5949
|
enrollCadence: true,
|
|
@@ -5245,7 +5955,7 @@ function runPodcastGuest(opts) {
|
|
|
5245
5955
|
const s = await webSearch({
|
|
5246
5956
|
query: `${t.name} ${t.podcast} "${t.episodeTitle}" notes OR transcript`,
|
|
5247
5957
|
maxResults: 3
|
|
5248
|
-
}, { playName: PLAY_NAME$
|
|
5958
|
+
}, { playName: PLAY_NAME$20 });
|
|
5249
5959
|
receiptIds.push(s.receiptId);
|
|
5250
5960
|
dossier = s.result.results.slice(0, 2).map((r) => `- ${r.title}: ${r.description}`).join("\n");
|
|
5251
5961
|
}
|
|
@@ -5279,20 +5989,20 @@ function runPodcastGuest(opts) {
|
|
|
5279
5989
|
}, opts);
|
|
5280
5990
|
}
|
|
5281
5991
|
registerSequence({
|
|
5282
|
-
playName: PLAY_NAME$
|
|
5992
|
+
playName: PLAY_NAME$20,
|
|
5283
5993
|
steps: []
|
|
5284
5994
|
});
|
|
5285
5995
|
//#endregion
|
|
5286
5996
|
//#region ../../packages/plays/src/post-funding.ts
|
|
5287
|
-
const PLAY_NAME$
|
|
5997
|
+
const PLAY_NAME$19 = "post-funding";
|
|
5288
5998
|
const postFundingDef = {
|
|
5289
|
-
playName: PLAY_NAME$
|
|
5999
|
+
playName: PLAY_NAME$19,
|
|
5290
6000
|
promptName: "post-funding-email",
|
|
5291
6001
|
maxBodyWords: 150,
|
|
5292
6002
|
enrollCadence: true,
|
|
5293
6003
|
toEmail: (t) => t.email,
|
|
5294
6004
|
prepare: (t, dryRun) => standardEnrich({
|
|
5295
|
-
playName: PLAY_NAME$
|
|
6005
|
+
playName: PLAY_NAME$19,
|
|
5296
6006
|
enrichInput: {
|
|
5297
6007
|
...t.email ? { email: t.email } : {},
|
|
5298
6008
|
...t.linkedinUrl ? { linkedinUrl: t.linkedinUrl } : {},
|
|
@@ -5328,14 +6038,14 @@ function runPostFunding(opts) {
|
|
|
5328
6038
|
return runEmailPlay(postFundingDef, opts);
|
|
5329
6039
|
}
|
|
5330
6040
|
registerSequence({
|
|
5331
|
-
playName: PLAY_NAME$
|
|
6041
|
+
playName: PLAY_NAME$19,
|
|
5332
6042
|
steps: [{
|
|
5333
6043
|
dayOffset: 9,
|
|
5334
6044
|
channel: "email",
|
|
5335
6045
|
breakOnReply: true,
|
|
5336
6046
|
label: "case-study follow-up",
|
|
5337
6047
|
builder: buildFollowUpEmail({
|
|
5338
|
-
playName: PLAY_NAME$
|
|
6048
|
+
playName: PLAY_NAME$19,
|
|
5339
6049
|
promptName: "post-funding-followup",
|
|
5340
6050
|
contextLines: [`CONTEXT: prospect's company recently raised; first email sent ~9 days ago, no reply.`]
|
|
5341
6051
|
})
|
|
@@ -5345,23 +6055,103 @@ registerSequence({
|
|
|
5345
6055
|
breakOnReply: true,
|
|
5346
6056
|
label: "breakup",
|
|
5347
6057
|
builder: buildFollowUpEmail({
|
|
5348
|
-
playName: PLAY_NAME$
|
|
6058
|
+
playName: PLAY_NAME$19,
|
|
5349
6059
|
promptName: "breakup-email",
|
|
5350
6060
|
contextLines: [`PLAY: post-funding.`]
|
|
5351
6061
|
})
|
|
5352
6062
|
}]
|
|
5353
6063
|
});
|
|
5354
6064
|
//#endregion
|
|
6065
|
+
//#region ../../packages/plays/src/profile-intro.ts
|
|
6066
|
+
const PLAY_NAME$18 = "profile-intro";
|
|
6067
|
+
const profileIntroDef = {
|
|
6068
|
+
playName: PLAY_NAME$18,
|
|
6069
|
+
promptName: "profile-intro-email",
|
|
6070
|
+
maxBodyWords: 100,
|
|
6071
|
+
enrollCadence: true,
|
|
6072
|
+
toEmail: (t) => t.email ?? "",
|
|
6073
|
+
prepare: (t, _dryRun) => t.dossier != null ? Promise.resolve({
|
|
6074
|
+
receiptIds: [],
|
|
6075
|
+
dossier: t.dossier
|
|
6076
|
+
}) : standardEnrich({
|
|
6077
|
+
playName: PLAY_NAME$18,
|
|
6078
|
+
enrichInput: {
|
|
6079
|
+
...t.email ? { email: t.email } : {},
|
|
6080
|
+
...t.linkedinUrl ? { linkedinUrl: t.linkedinUrl } : {},
|
|
6081
|
+
name: t.name
|
|
6082
|
+
},
|
|
6083
|
+
enrichSlice: 5e3
|
|
6084
|
+
}),
|
|
6085
|
+
buildInputBlock: (t, prep, cfg) => [
|
|
6086
|
+
`FOUNDER: ${cfg.founderName}`,
|
|
6087
|
+
`PRODUCT: ${cfg.productOneLiner}`,
|
|
6088
|
+
...cfg.icpOneLiner ? [`ICP: ${cfg.icpOneLiner}`] : [],
|
|
6089
|
+
`PROSPECT: ${t.name}`,
|
|
6090
|
+
`COMPANY: ${t.company ?? "(unknown)"}`,
|
|
6091
|
+
`ANGLE: ${t.angle ?? "(none detected — keep it honest and narrow)"}`,
|
|
6092
|
+
`DOSSIER:\n${prep.dossier || "(no dossier; rely on the angle only)"}`
|
|
6093
|
+
].join("\n"),
|
|
6094
|
+
prospectMeta: (t) => ({
|
|
6095
|
+
name: t.name,
|
|
6096
|
+
email: t.email ?? null,
|
|
6097
|
+
company: t.company ?? null,
|
|
6098
|
+
linkedin_url: t.linkedinUrl ?? t.twitterUrl ?? t.githubUrl ?? null,
|
|
6099
|
+
phone: t.phone ?? null,
|
|
6100
|
+
source: "manual"
|
|
6101
|
+
})
|
|
6102
|
+
};
|
|
6103
|
+
function runProfileIntro(opts) {
|
|
6104
|
+
return runEmailPlay(profileIntroDef, opts);
|
|
6105
|
+
}
|
|
6106
|
+
registerSequence({
|
|
6107
|
+
playName: PLAY_NAME$18,
|
|
6108
|
+
steps: [
|
|
6109
|
+
{
|
|
6110
|
+
dayOffset: 4,
|
|
6111
|
+
channel: "email",
|
|
6112
|
+
breakOnReply: true,
|
|
6113
|
+
label: "value follow-up",
|
|
6114
|
+
builder: buildFollowUpEmail({
|
|
6115
|
+
playName: PLAY_NAME$18,
|
|
6116
|
+
promptName: "profile-intro-followup",
|
|
6117
|
+
contextLines: [`CONTEXT: cold intro from their profile went unanswered ~4 days ago.`]
|
|
6118
|
+
})
|
|
6119
|
+
},
|
|
6120
|
+
{
|
|
6121
|
+
dayOffset: 5,
|
|
6122
|
+
channel: "email",
|
|
6123
|
+
breakOnReply: true,
|
|
6124
|
+
label: "value follow-up",
|
|
6125
|
+
builder: buildFollowUpEmail({
|
|
6126
|
+
playName: PLAY_NAME$18,
|
|
6127
|
+
promptName: "profile-intro-followup",
|
|
6128
|
+
contextLines: [`CONTEXT: second touch; still no reply. Keep it shorter than the first ping.`]
|
|
6129
|
+
})
|
|
6130
|
+
},
|
|
6131
|
+
{
|
|
6132
|
+
dayOffset: 9,
|
|
6133
|
+
channel: "email",
|
|
6134
|
+
breakOnReply: true,
|
|
6135
|
+
label: "breakup",
|
|
6136
|
+
builder: buildFollowUpEmail({
|
|
6137
|
+
playName: PLAY_NAME$18,
|
|
6138
|
+
promptName: "breakup-email",
|
|
6139
|
+
contextLines: [`PLAY: profile-intro. Sender is closing the file.`]
|
|
6140
|
+
})
|
|
6141
|
+
}
|
|
6142
|
+
]
|
|
6143
|
+
});
|
|
6144
|
+
//#endregion
|
|
5355
6145
|
//#region ../../packages/plays/src/repo-interest.ts
|
|
5356
|
-
const PLAY_NAME$
|
|
6146
|
+
const PLAY_NAME$17 = "repo-interest";
|
|
5357
6147
|
const repoInterestDef = {
|
|
5358
|
-
playName: PLAY_NAME$
|
|
6148
|
+
playName: PLAY_NAME$17,
|
|
5359
6149
|
promptName: "repo-interest-email",
|
|
5360
6150
|
maxBodyWords: 150,
|
|
5361
6151
|
enrollCadence: true,
|
|
5362
6152
|
toEmail: (t) => t.email,
|
|
5363
6153
|
prepare: (t) => standardEnrich({
|
|
5364
|
-
playName: PLAY_NAME$
|
|
6154
|
+
playName: PLAY_NAME$17,
|
|
5365
6155
|
enrichInput: {
|
|
5366
6156
|
...t.email ? { email: t.email } : {},
|
|
5367
6157
|
name: t.name,
|
|
@@ -5393,14 +6183,14 @@ function runRepoInterest(opts) {
|
|
|
5393
6183
|
return runEmailPlay(repoInterestDef, opts);
|
|
5394
6184
|
}
|
|
5395
6185
|
registerSequence({
|
|
5396
|
-
playName: PLAY_NAME$
|
|
6186
|
+
playName: PLAY_NAME$17,
|
|
5397
6187
|
steps: [{
|
|
5398
6188
|
dayOffset: 3,
|
|
5399
6189
|
channel: "email",
|
|
5400
6190
|
breakOnReply: true,
|
|
5401
6191
|
label: "value follow-up",
|
|
5402
6192
|
builder: buildFollowUpEmail({
|
|
5403
|
-
playName: PLAY_NAME$
|
|
6193
|
+
playName: PLAY_NAME$17,
|
|
5404
6194
|
promptName: "repo-interest-followup",
|
|
5405
6195
|
contextLines: [`PLAY: repo-interest. Day-3 soft nudge after the peer-to-peer intro about a repo they starred.`]
|
|
5406
6196
|
})
|
|
@@ -5408,14 +6198,14 @@ registerSequence({
|
|
|
5408
6198
|
});
|
|
5409
6199
|
//#endregion
|
|
5410
6200
|
//#region ../../packages/plays/src/show-hn.ts
|
|
5411
|
-
const PLAY_NAME$
|
|
6201
|
+
const PLAY_NAME$16 = "show-hn";
|
|
5412
6202
|
const showHnDef = {
|
|
5413
|
-
playName: PLAY_NAME$
|
|
6203
|
+
playName: PLAY_NAME$16,
|
|
5414
6204
|
promptName: "show-hn-email",
|
|
5415
6205
|
maxBodyWords: 150,
|
|
5416
6206
|
toEmail: (t) => t.founderEmail,
|
|
5417
6207
|
prepare: (t, dryRun) => standardEnrich({
|
|
5418
|
-
playName: PLAY_NAME$
|
|
6208
|
+
playName: PLAY_NAME$16,
|
|
5419
6209
|
enrichInput: {
|
|
5420
6210
|
email: t.founderEmail,
|
|
5421
6211
|
name: t.founderName
|
|
@@ -5453,15 +6243,15 @@ function extractCompany(title) {
|
|
|
5453
6243
|
}
|
|
5454
6244
|
//#endregion
|
|
5455
6245
|
//#region ../../packages/plays/src/stack-consolidation.ts
|
|
5456
|
-
const PLAY_NAME$
|
|
6246
|
+
const PLAY_NAME$15 = "stack-consolidation";
|
|
5457
6247
|
const stackConsolidationDef = {
|
|
5458
|
-
playName: PLAY_NAME$
|
|
6248
|
+
playName: PLAY_NAME$15,
|
|
5459
6249
|
promptName: "stack-consolidation-email",
|
|
5460
6250
|
maxBodyWords: 150,
|
|
5461
6251
|
enrollCadence: true,
|
|
5462
6252
|
toEmail: (t) => t.email,
|
|
5463
6253
|
prepare: (t) => standardEnrich({
|
|
5464
|
-
playName: PLAY_NAME$
|
|
6254
|
+
playName: PLAY_NAME$15,
|
|
5465
6255
|
enrichInput: {
|
|
5466
6256
|
...t.email ? { email: t.email } : {},
|
|
5467
6257
|
name: t.name,
|
|
@@ -5494,14 +6284,14 @@ function runStackConsolidation(opts) {
|
|
|
5494
6284
|
return runEmailPlay(stackConsolidationDef, opts);
|
|
5495
6285
|
}
|
|
5496
6286
|
registerSequence({
|
|
5497
|
-
playName: PLAY_NAME$
|
|
6287
|
+
playName: PLAY_NAME$15,
|
|
5498
6288
|
steps: [{
|
|
5499
6289
|
dayOffset: 3,
|
|
5500
6290
|
channel: "email",
|
|
5501
6291
|
breakOnReply: true,
|
|
5502
6292
|
label: "value follow-up",
|
|
5503
6293
|
builder: buildFollowUpEmail({
|
|
5504
|
-
playName: PLAY_NAME$
|
|
6294
|
+
playName: PLAY_NAME$15,
|
|
5505
6295
|
promptName: "stack-consolidation-followup",
|
|
5506
6296
|
contextLines: [`PLAY: stack-consolidation. Day-3 value follow-up after the consolidation-honesty pitch.`]
|
|
5507
6297
|
})
|
|
@@ -5511,7 +6301,7 @@ registerSequence({
|
|
|
5511
6301
|
breakOnReply: true,
|
|
5512
6302
|
label: "breakup",
|
|
5513
6303
|
builder: buildFollowUpEmail({
|
|
5514
|
-
playName: PLAY_NAME$
|
|
6304
|
+
playName: PLAY_NAME$15,
|
|
5515
6305
|
promptName: "breakup-email",
|
|
5516
6306
|
contextLines: [`PLAY: stack-consolidation. Final breakup after the consolidation-honesty pitch.`]
|
|
5517
6307
|
})
|
|
@@ -5573,6 +6363,11 @@ const PLAYS = {
|
|
|
5573
6363
|
targets: o.targets,
|
|
5574
6364
|
...progressOpt(o)
|
|
5575
6365
|
}) },
|
|
6366
|
+
"profile-intro": { run: (o) => runProfileIntro({
|
|
6367
|
+
dryRun: o.dryRun,
|
|
6368
|
+
targets: o.targets,
|
|
6369
|
+
...progressOpt(o)
|
|
6370
|
+
}) },
|
|
5576
6371
|
"breakup-revive": { run: (o) => runBreakupRevive({
|
|
5577
6372
|
dryRun: o.dryRun,
|
|
5578
6373
|
targets: o.targets
|
|
@@ -5582,6 +6377,199 @@ function isSupportedPlay(name) {
|
|
|
5582
6377
|
return Object.prototype.hasOwnProperty.call(PLAYS, name);
|
|
5583
6378
|
}
|
|
5584
6379
|
//#endregion
|
|
6380
|
+
//#region ../../packages/plays/src/add-prospect.ts
|
|
6381
|
+
const PLAY_NAME$14 = "profile-intro";
|
|
6382
|
+
/** Transient note on a placeholder row while its background research runs. */
|
|
6383
|
+
const RESEARCHING_NOTE = "researching profile…";
|
|
6384
|
+
/**
|
|
6385
|
+
* Validate a pasted profile URL and classify the platform. Throws on an
|
|
6386
|
+
* unparseable URL or an unsupported host — `deepResearchPerson` chases
|
|
6387
|
+
* LinkedIn / X-Twitter / GitHub social URLs, so we gate to those.
|
|
6388
|
+
*/
|
|
6389
|
+
function parseProfileUrl(raw) {
|
|
6390
|
+
const trimmed = (raw ?? "").trim();
|
|
6391
|
+
let u;
|
|
6392
|
+
try {
|
|
6393
|
+
u = new URL(trimmed);
|
|
6394
|
+
} catch {
|
|
6395
|
+
throw new Error("not a valid URL — paste a full LinkedIn or X/Twitter profile link");
|
|
6396
|
+
}
|
|
6397
|
+
if (u.protocol !== "http:" && u.protocol !== "https:") throw new Error("URL must be http(s)");
|
|
6398
|
+
const host = u.hostname.toLowerCase().replace(/^www\./, "");
|
|
6399
|
+
const hostMatches = (domain) => host === domain || host.endsWith(`.${domain}`);
|
|
6400
|
+
let platform;
|
|
6401
|
+
if (hostMatches("linkedin.com")) platform = "linkedin";
|
|
6402
|
+
else if (hostMatches("x.com") || hostMatches("twitter.com")) platform = "twitter";
|
|
6403
|
+
else if (hostMatches("github.com")) platform = "github";
|
|
6404
|
+
else throw new Error("unsupported URL — use a LinkedIn, X/Twitter, or GitHub profile");
|
|
6405
|
+
const path = u.pathname.toLowerCase().replace(/\/+$/, "");
|
|
6406
|
+
return {
|
|
6407
|
+
platform,
|
|
6408
|
+
url: trimmed,
|
|
6409
|
+
dedupeKey: `${host}${path}`
|
|
6410
|
+
};
|
|
6411
|
+
}
|
|
6412
|
+
/**
|
|
6413
|
+
* Fast, synchronous step of the manual add-prospect flow: validate the URL and
|
|
6414
|
+
* enqueue a placeholder `profile-intro` queue row immediately (so it shows on
|
|
6415
|
+
* /queue right away), returning its id. The heavy dossier research + draft runs
|
|
6416
|
+
* separately in `runProspectResearch`. Returns `{ duplicate:true }` when this
|
|
6417
|
+
* profile is already queued for this play.
|
|
6418
|
+
*/
|
|
6419
|
+
function createProspectResearchJob(input) {
|
|
6420
|
+
const parsed = parseProfileUrl(input.url);
|
|
6421
|
+
const ledger = getLedger();
|
|
6422
|
+
const payload = {
|
|
6423
|
+
url: parsed.url,
|
|
6424
|
+
platform: parsed.platform,
|
|
6425
|
+
...input.emailOverride ? { emailOverride: input.emailOverride } : {}
|
|
6426
|
+
};
|
|
6427
|
+
const id = ledger.enqueueTarget({
|
|
6428
|
+
playName: PLAY_NAME$14,
|
|
6429
|
+
payload,
|
|
6430
|
+
dedupeKey: parsed.dedupeKey,
|
|
6431
|
+
source: "manual",
|
|
6432
|
+
notes: RESEARCHING_NOTE
|
|
6433
|
+
});
|
|
6434
|
+
if (id != null) return { queueId: id };
|
|
6435
|
+
const existing = ledger.getQueueRowByDedupe(PLAY_NAME$14, parsed.dedupeKey);
|
|
6436
|
+
if (existing && existing.last_draft_json == null && existing.send_started_at == null && existing.status !== "sent") {
|
|
6437
|
+
ledger.setQueueStatus({
|
|
6438
|
+
id: existing.id,
|
|
6439
|
+
status: "pending"
|
|
6440
|
+
});
|
|
6441
|
+
ledger.updateQueuePayload({
|
|
6442
|
+
id: existing.id,
|
|
6443
|
+
payload
|
|
6444
|
+
});
|
|
6445
|
+
ledger.setQueueNotes({
|
|
6446
|
+
id: existing.id,
|
|
6447
|
+
notes: RESEARCHING_NOTE
|
|
6448
|
+
});
|
|
6449
|
+
return { queueId: existing.id };
|
|
6450
|
+
}
|
|
6451
|
+
return { duplicate: true };
|
|
6452
|
+
}
|
|
6453
|
+
function str(v) {
|
|
6454
|
+
return typeof v === "string" && v.trim() !== "" ? v.trim() : null;
|
|
6455
|
+
}
|
|
6456
|
+
/**
|
|
6457
|
+
* Async step: research the profile via the OneShot SDK (`deepResearchPerson`,
|
|
6458
|
+
* which accepts any social URL — LinkedIn / X / GitHub — and returns a
|
|
6459
|
+
* multi-source dossier incl. work/personal emails), have the LLM extract
|
|
6460
|
+
* identity + an ICP-grounded angle, draft the intro via the profile-intro play
|
|
6461
|
+
* (dry-run, no send), then persist the full target + draft onto the queue row.
|
|
6462
|
+
* Never throws — failures are written to the row's notes so the founder sees
|
|
6463
|
+
* what happened. Safe to call as `void runProspectResearch(id)`.
|
|
6464
|
+
*/
|
|
6465
|
+
async function runProspectResearch(queueId) {
|
|
6466
|
+
const ledger = getLedger();
|
|
6467
|
+
try {
|
|
6468
|
+
const row = ledger.getQueueRow(queueId);
|
|
6469
|
+
if (!row) return;
|
|
6470
|
+
let payload;
|
|
6471
|
+
try {
|
|
6472
|
+
payload = JSON.parse(row.payload_json);
|
|
6473
|
+
} catch {
|
|
6474
|
+
ledger.setQueueNotes({
|
|
6475
|
+
id: queueId,
|
|
6476
|
+
notes: "research failed: corrupt job payload"
|
|
6477
|
+
});
|
|
6478
|
+
return;
|
|
6479
|
+
}
|
|
6480
|
+
const research = await deepResearchPerson({
|
|
6481
|
+
socialMediaUrl: payload.url,
|
|
6482
|
+
...payload.emailOverride ? { email: payload.emailOverride } : {}
|
|
6483
|
+
}, {
|
|
6484
|
+
playName: PLAY_NAME$14,
|
|
6485
|
+
decisionContext: {
|
|
6486
|
+
source: "add-prospect",
|
|
6487
|
+
url: payload.url
|
|
6488
|
+
}
|
|
6489
|
+
});
|
|
6490
|
+
const enrichment = research.result?.result?.enrichment ?? {};
|
|
6491
|
+
const articles = research.result?.result?.articles;
|
|
6492
|
+
if (!(Object.keys(enrichment).length > 0 || Array.isArray(articles) && articles.length > 0)) {
|
|
6493
|
+
ledger.setQueueNotes({
|
|
6494
|
+
id: queueId,
|
|
6495
|
+
notes: "couldn't research this profile — verify the URL is a public LinkedIn/X profile"
|
|
6496
|
+
});
|
|
6497
|
+
return;
|
|
6498
|
+
}
|
|
6499
|
+
const dossier = JSON.stringify(research.result?.result ?? research.result, null, 2).slice(0, 6e3);
|
|
6500
|
+
const cfg = loadConfig();
|
|
6501
|
+
const extractSystem = loadPrompt("profile-extract");
|
|
6502
|
+
const extractUser = [
|
|
6503
|
+
`ICP: ${cfg.icpOneLiner ?? "(not set)"}`,
|
|
6504
|
+
`PRODUCT: ${cfg.productOneLiner ?? "(not set)"}`,
|
|
6505
|
+
`DOSSIER:\n${dossier}`
|
|
6506
|
+
].join("\n");
|
|
6507
|
+
const extracted = tryParseJsonObject((await complete({
|
|
6508
|
+
messages: [{
|
|
6509
|
+
role: "system",
|
|
6510
|
+
content: extractSystem
|
|
6511
|
+
}, {
|
|
6512
|
+
role: "user",
|
|
6513
|
+
content: extractUser
|
|
6514
|
+
}],
|
|
6515
|
+
temperature: .3,
|
|
6516
|
+
maxTokens: 500
|
|
6517
|
+
})).content, {});
|
|
6518
|
+
const altEmails = Array.isArray(enrichment["altemails"]) ? enrichment["altemails"].map(str).filter((x) => x != null) : [];
|
|
6519
|
+
const email = str(payload.emailOverride) ?? str(extracted.email) ?? str(enrichment["best_work_email"]) ?? str(enrichment["best_personal_email"]) ?? altEmails[0] ?? null;
|
|
6520
|
+
const urlField = payload.platform === "twitter" ? { twitterUrl: payload.url } : payload.platform === "github" ? { githubUrl: payload.url } : { linkedinUrl: payload.url };
|
|
6521
|
+
const target = {
|
|
6522
|
+
name: str(extracted.name) ?? str(enrichment["displayname"]) ?? "(unknown)",
|
|
6523
|
+
email,
|
|
6524
|
+
company: str(extracted.company),
|
|
6525
|
+
angle: str(extracted.angle),
|
|
6526
|
+
dossier,
|
|
6527
|
+
...urlField
|
|
6528
|
+
};
|
|
6529
|
+
const { drafted } = await runProfileIntro({
|
|
6530
|
+
dryRun: true,
|
|
6531
|
+
targets: [target]
|
|
6532
|
+
});
|
|
6533
|
+
const draft = drafted[0];
|
|
6534
|
+
const errorFlag = draft?.flags.find((f) => f.startsWith("error:"));
|
|
6535
|
+
if (!draft || errorFlag || draft.subject.trim() === "" || draft.body.trim() === "") {
|
|
6536
|
+
ledger.setQueueNotes({
|
|
6537
|
+
id: queueId,
|
|
6538
|
+
notes: (errorFlag ? `draft failed: ${errorFlag}` : "draft came back empty — re-add to retry").slice(0, 200)
|
|
6539
|
+
});
|
|
6540
|
+
return;
|
|
6541
|
+
}
|
|
6542
|
+
const fresh = ledger.getQueueRow(queueId);
|
|
6543
|
+
if (!fresh || fresh.status !== "pending" && fresh.status !== "approved" || fresh.send_started_at != null) return;
|
|
6544
|
+
ledger.updateQueuePayload({
|
|
6545
|
+
id: queueId,
|
|
6546
|
+
payload: target
|
|
6547
|
+
});
|
|
6548
|
+
ledger.setQueueDraft({
|
|
6549
|
+
id: queueId,
|
|
6550
|
+
draft: {
|
|
6551
|
+
subject: draft.subject,
|
|
6552
|
+
body: draft.body,
|
|
6553
|
+
flags: draft.flags,
|
|
6554
|
+
sent: false,
|
|
6555
|
+
receiptIds: [],
|
|
6556
|
+
dryRun: true
|
|
6557
|
+
}
|
|
6558
|
+
});
|
|
6559
|
+
ledger.setQueueNotes({
|
|
6560
|
+
id: queueId,
|
|
6561
|
+
notes: email ? "" : "no email found — add an email before sending"
|
|
6562
|
+
});
|
|
6563
|
+
} catch (err) {
|
|
6564
|
+
try {
|
|
6565
|
+
ledger.setQueueNotes({
|
|
6566
|
+
id: queueId,
|
|
6567
|
+
notes: `research failed: ${err?.message ?? "unknown error"}`.slice(0, 200)
|
|
6568
|
+
});
|
|
6569
|
+
} catch {}
|
|
6570
|
+
}
|
|
6571
|
+
}
|
|
6572
|
+
//#endregion
|
|
5585
6573
|
//#region ../../packages/plays/src/demo-no-show.ts
|
|
5586
6574
|
const PLAY_NAME$13 = "demo-no-show";
|
|
5587
6575
|
registerSequence({
|
|
@@ -5599,6 +6587,45 @@ registerSequence({
|
|
|
5599
6587
|
}]
|
|
5600
6588
|
});
|
|
5601
6589
|
//#endregion
|
|
6590
|
+
//#region src/telemetry.ts
|
|
6591
|
+
/**
|
|
6592
|
+
* Server-side telemetry — the dashboard analogue of the CLI's per-command
|
|
6593
|
+
* event (see apps/cli/src/index.ts `sendTelemetry`). The server executes the
|
|
6594
|
+
* same kinds of work (plays, cadence sends, queue drains, scheduled triggers)
|
|
6595
|
+
* but never passes through the CLI's `runOrFail`, so it reports here instead.
|
|
6596
|
+
*
|
|
6597
|
+
* Delegates the gate + payload + send to `reportTelemetryEvent` in core (the
|
|
6598
|
+
* shared path the CLI also uses); this wrapper only supplies the server's own
|
|
6599
|
+
* `version` and an empty-flags default. Two deliberate differences from the
|
|
6600
|
+
* CLI path:
|
|
6601
|
+
*
|
|
6602
|
+
* 1. `outcome` is passed in explicitly rather than read from the
|
|
6603
|
+
* `markTelemetryOutcome` global — that singleton is unsafe in a concurrent
|
|
6604
|
+
* server where many executions overlap.
|
|
6605
|
+
* 2. `command` is prefixed `server.` so the events table can separate CLI
|
|
6606
|
+
* and server channels (filter on a `server.` prefix).
|
|
6607
|
+
*
|
|
6608
|
+
* Best-effort and non-blocking: `reportTelemetryEvent` never throws and has its
|
|
6609
|
+
* own timeout, so a telemetry failure can't affect a request or the scheduler.
|
|
6610
|
+
*/
|
|
6611
|
+
let serverVersion;
|
|
6612
|
+
/**
|
|
6613
|
+
* Emit one anonymous telemetry event for a server-initiated execution.
|
|
6614
|
+
* `command` should already carry the `server.` prefix (e.g. `server.run.show-hn`).
|
|
6615
|
+
*/
|
|
6616
|
+
async function reportServerExecution(command, opts) {
|
|
6617
|
+
try {
|
|
6618
|
+
serverVersion ??= readPackageVersion(import.meta.url);
|
|
6619
|
+
await reportTelemetryEvent({
|
|
6620
|
+
command,
|
|
6621
|
+
flags: opts.flags ?? [],
|
|
6622
|
+
outcome: opts.outcome,
|
|
6623
|
+
durationMs: opts.durationMs,
|
|
6624
|
+
version: serverVersion
|
|
6625
|
+
});
|
|
6626
|
+
} catch {}
|
|
6627
|
+
}
|
|
6628
|
+
//#endregion
|
|
5602
6629
|
//#region src/api/cadences.ts
|
|
5603
6630
|
/**
|
|
5604
6631
|
* In-flight cadence sends are tracked on the cadence_state row's
|
|
@@ -5722,9 +6749,10 @@ function tallyCounts(rows) {
|
|
|
5722
6749
|
breakup: 0,
|
|
5723
6750
|
completed: 0,
|
|
5724
6751
|
paused: 0,
|
|
6752
|
+
bounced: 0,
|
|
5725
6753
|
overdue: 0
|
|
5726
6754
|
};
|
|
5727
|
-
for (const r of rows) if (r.status === "active" || r.status === "replied" || r.status === "breakup" || r.status === "completed" || r.status === "paused") {
|
|
6755
|
+
for (const r of rows) if (r.status === "active" || r.status === "replied" || r.status === "breakup" || r.status === "completed" || r.status === "paused" || r.status === "bounced") {
|
|
5728
6756
|
counts[r.status]++;
|
|
5729
6757
|
if (r.status === "active" && r.next_due_at && new Date(r.next_due_at).getTime() <= now) counts.overdue++;
|
|
5730
6758
|
}
|
|
@@ -5800,10 +6828,19 @@ async function sendCadenceStepRoute(req, params) {
|
|
|
5800
6828
|
startedAtIso: nowIso,
|
|
5801
6829
|
staleCutoffIso
|
|
5802
6830
|
})) return jsonResponse({ error: "already sending — wait for the in-flight send to complete" }, 409, req);
|
|
6831
|
+
const sendStartedAt = performance.now();
|
|
5803
6832
|
(async () => {
|
|
5804
6833
|
try {
|
|
5805
6834
|
await sendCadenceStep(parsed);
|
|
6835
|
+
reportServerExecution("server.cadence.send", {
|
|
6836
|
+
outcome: "ok",
|
|
6837
|
+
durationMs: performance.now() - sendStartedAt
|
|
6838
|
+
});
|
|
5806
6839
|
} catch (err) {
|
|
6840
|
+
reportServerExecution("server.cadence.send", {
|
|
6841
|
+
outcome: "error",
|
|
6842
|
+
durationMs: performance.now() - sendStartedAt
|
|
6843
|
+
});
|
|
5807
6844
|
logEvent("cadence.send.failed", {
|
|
5808
6845
|
prospect_id: parsed.prospectId,
|
|
5809
6846
|
play_name: parsed.playName,
|
|
@@ -5856,6 +6893,7 @@ async function sendCadenceBatchRoute(req) {
|
|
|
5856
6893
|
staleCutoffIso
|
|
5857
6894
|
})) claimed.push(item);
|
|
5858
6895
|
if (claimed.length === 0) return jsonResponse({ error: "no claimable rows — all selected are already sending" }, 409, req);
|
|
6896
|
+
const batchStartedAt = performance.now();
|
|
5859
6897
|
(async () => {
|
|
5860
6898
|
try {
|
|
5861
6899
|
await sendCadenceStepBatch(claimed, (item) => {
|
|
@@ -5863,7 +6901,15 @@ async function sendCadenceBatchRoute(req) {
|
|
|
5863
6901
|
ledger.clearCadenceSendingMarker(item);
|
|
5864
6902
|
} catch {}
|
|
5865
6903
|
});
|
|
6904
|
+
reportServerExecution("server.cadence.batch", {
|
|
6905
|
+
outcome: "ok",
|
|
6906
|
+
durationMs: performance.now() - batchStartedAt
|
|
6907
|
+
});
|
|
5866
6908
|
} catch (err) {
|
|
6909
|
+
reportServerExecution("server.cadence.batch", {
|
|
6910
|
+
outcome: "error",
|
|
6911
|
+
durationMs: performance.now() - batchStartedAt
|
|
6912
|
+
});
|
|
5867
6913
|
for (const item of claimed) try {
|
|
5868
6914
|
ledger.clearCadenceSendingMarker(item);
|
|
5869
6915
|
} catch {}
|
|
@@ -5954,6 +7000,47 @@ function blockingFlags(flags) {
|
|
|
5954
7000
|
return flags.filter((f) => !SOFT_REVIEW_FLAGS.includes(f));
|
|
5955
7001
|
}
|
|
5956
7002
|
/**
|
|
7003
|
+
* Plays the SSE `/api/run/:playName` endpoint can dispatch — i.e. the ones
|
|
7004
|
+
* drivable from the dashboard rather than the CLI. Canonical: the server's run
|
|
7005
|
+
* gate, /queue's drain button and the Plays page all read THIS, because three
|
|
7006
|
+
* hand-copied mirrors of the list had already drifted apart (the queue's copy
|
|
7007
|
+
* was missing luma-events, the Plays page's was missing competitor-switch).
|
|
7008
|
+
*
|
|
7009
|
+
* Adding a play here also requires a form schema in the web app's
|
|
7010
|
+
* `lib/playSchemas.ts`; a test pins the two together.
|
|
7011
|
+
*/
|
|
7012
|
+
const RUNNABLE_PLAYS = [
|
|
7013
|
+
"show-hn",
|
|
7014
|
+
"job-change",
|
|
7015
|
+
"post-funding",
|
|
7016
|
+
"accelerator-batch",
|
|
7017
|
+
"hiring-signal",
|
|
7018
|
+
"podcast-guest",
|
|
7019
|
+
"competitor-switch",
|
|
7020
|
+
"stack-consolidation",
|
|
7021
|
+
"repo-interest",
|
|
7022
|
+
"luma-events"
|
|
7023
|
+
];
|
|
7024
|
+
/**
|
|
7025
|
+
* Parse a `?ids=1,2,3` queue-row pick (the "drain selected" path).
|
|
7026
|
+
*
|
|
7027
|
+
* Returns `undefined` only when the parameter is ABSENT. A present-but-unusable
|
|
7028
|
+
* value (`?ids=`, `?ids=abc`) returns `[]` — an explicit empty pick — because
|
|
7029
|
+
* collapsing it to "absent" would silently downgrade a scoped drain into an
|
|
7030
|
+
* unscoped one and hydrate rows the founder never selected, which they could
|
|
7031
|
+
* then send. Tokens must be whole decimal integers: `123abc` is rejected
|
|
7032
|
+
* outright rather than parsed as `123`, which would load an unintended row.
|
|
7033
|
+
* Capped at 500 to match the list endpoint's own limit.
|
|
7034
|
+
*/
|
|
7035
|
+
function parseQueueIds(raw) {
|
|
7036
|
+
if (raw == null) return void 0;
|
|
7037
|
+
return raw.split(",").map((s) => s.trim()).filter((s) => /^\d+$/.test(s)).map((s) => Number.parseInt(s, 10)).filter((n) => Number.isSafeInteger(n) && n > 0).slice(0, 500);
|
|
7038
|
+
}
|
|
7039
|
+
const RUNNABLE_PLAY_SET = new Set(RUNNABLE_PLAYS);
|
|
7040
|
+
function isRunnablePlay(playName) {
|
|
7041
|
+
return RUNNABLE_PLAY_SET.has(playName);
|
|
7042
|
+
}
|
|
7043
|
+
/**
|
|
5957
7044
|
* Stable key for an inbox thread, shared by the server (persistence) and the
|
|
5958
7045
|
* web composer (send payload) so both sides agree. Gmail rows carry a
|
|
5959
7046
|
* thread_id; OneShot rows fall back to the email id (best-effort — OneShot has
|
|
@@ -6244,6 +7331,10 @@ const PLAY_CATALOG = [
|
|
|
6244
7331
|
{
|
|
6245
7332
|
name: "breakup-revive",
|
|
6246
7333
|
cli: "oneshot-gtm motion breakup-revive --min-days 60 --max-days 90"
|
|
7334
|
+
},
|
|
7335
|
+
{
|
|
7336
|
+
name: "profile-intro",
|
|
7337
|
+
cli: "added from the dashboard: Add Prospect → paste a LinkedIn or X/Twitter URL"
|
|
6247
7338
|
}
|
|
6248
7339
|
];
|
|
6249
7340
|
/** Relative per-step dayOffsets → cumulative days from the day-0 initial send. */
|
|
@@ -10607,6 +11698,32 @@ function parseStarRow(raw) {
|
|
|
10607
11698
|
starredAt
|
|
10608
11699
|
};
|
|
10609
11700
|
}
|
|
11701
|
+
/**
|
|
11702
|
+
* Parse one `/repos/{repo}/events` row into a Stargazer when it's a
|
|
11703
|
+
* `WatchEvent` (= a star; `created_at` is the star time). Non-star events and
|
|
11704
|
+
* malformed rows return null.
|
|
11705
|
+
*/
|
|
11706
|
+
function parseWatchEvent(raw) {
|
|
11707
|
+
if (!raw || typeof raw !== "object") return null;
|
|
11708
|
+
const r = raw;
|
|
11709
|
+
if (r["type"] !== "WatchEvent") return null;
|
|
11710
|
+
const createdAt = typeof r["created_at"] === "string" ? r["created_at"] : null;
|
|
11711
|
+
const actor = r["actor"];
|
|
11712
|
+
if (!createdAt || !actor || typeof actor !== "object") return null;
|
|
11713
|
+
const login = typeof actor["login"] === "string" ? actor["login"] : null;
|
|
11714
|
+
if (!login) return null;
|
|
11715
|
+
return {
|
|
11716
|
+
login,
|
|
11717
|
+
userUrl: `https://github.com/${login}`,
|
|
11718
|
+
starredAt: createdAt
|
|
11719
|
+
};
|
|
11720
|
+
}
|
|
11721
|
+
/** Read a GitHub event row's `created_at` (any event type), else null. */
|
|
11722
|
+
function eventCreatedAt(raw) {
|
|
11723
|
+
if (!raw || typeof raw !== "object") return null;
|
|
11724
|
+
const v = raw["created_at"];
|
|
11725
|
+
return typeof v === "string" ? v : null;
|
|
11726
|
+
}
|
|
10610
11727
|
/** Read the `page=N>; rel="last"` page number from a GitHub `Link` header. */
|
|
10611
11728
|
function parseLastPage(link) {
|
|
10612
11729
|
if (!link) return 1;
|
|
@@ -10614,6 +11731,88 @@ function parseLastPage(link) {
|
|
|
10614
11731
|
return m ? Math.max(1, Number.parseInt(m[1] ?? "1", 10)) : 1;
|
|
10615
11732
|
}
|
|
10616
11733
|
/**
|
|
11734
|
+
* Fallback path: recent stargazers via the public repo *events* feed.
|
|
11735
|
+
*
|
|
11736
|
+
* Since July 2026 GitHub restricts `/stargazers` to repo admins/collaborators
|
|
11737
|
+
* (401 unauth, 403/404 authed) — but `WatchEvent`s still flow through
|
|
11738
|
+
* `/repos/{repo}/events`, which stays public. The feed is newest-first and
|
|
11739
|
+
* keeps at most ~90 days / 300 events per repo, so we walk forward up to
|
|
11740
|
+
* 3 pages of 100 and stop once a page's oldest event predates the window
|
|
11741
|
+
* (every later page is older still). Busy repos can wash stars out of the
|
|
11742
|
+
* 300-event cap between poll ticks — a scheduler that ticks at least daily
|
|
11743
|
+
* keeps the gap negligible for the repo sizes we watch.
|
|
11744
|
+
*/
|
|
11745
|
+
async function recentStargazersViaEvents(repo, opts) {
|
|
11746
|
+
const headers = githubHeaders();
|
|
11747
|
+
const base = `https://api.github.com/repos/${repo}/events?per_page=100`;
|
|
11748
|
+
const out = [];
|
|
11749
|
+
let newestSeen = null;
|
|
11750
|
+
const dedupe = () => {
|
|
11751
|
+
const seen = /* @__PURE__ */ new Set();
|
|
11752
|
+
return out.filter((s) => {
|
|
11753
|
+
const key = s.login.toLowerCase();
|
|
11754
|
+
if (seen.has(key)) return false;
|
|
11755
|
+
seen.add(key);
|
|
11756
|
+
return true;
|
|
11757
|
+
});
|
|
11758
|
+
};
|
|
11759
|
+
try {
|
|
11760
|
+
for (let page = 1; page <= 3; page++) {
|
|
11761
|
+
const res = await fetch(`${base}&page=${page}`, { headers });
|
|
11762
|
+
if (!res.ok) {
|
|
11763
|
+
logEvent("github.stargazers", {
|
|
11764
|
+
repo,
|
|
11765
|
+
ok: false,
|
|
11766
|
+
mode: "events",
|
|
11767
|
+
status: res.status,
|
|
11768
|
+
page
|
|
11769
|
+
}, "warn");
|
|
11770
|
+
return {
|
|
11771
|
+
stargazers: dedupe(),
|
|
11772
|
+
newestSeen,
|
|
11773
|
+
error: `events status ${res.status}`
|
|
11774
|
+
};
|
|
11775
|
+
}
|
|
11776
|
+
const rows = await res.json() ?? [];
|
|
11777
|
+
let oldestOnPage = null;
|
|
11778
|
+
for (const raw of rows) {
|
|
11779
|
+
const at = eventCreatedAt(raw);
|
|
11780
|
+
if (at && (!oldestOnPage || at < oldestOnPage)) oldestOnPage = at;
|
|
11781
|
+
const s = parseWatchEvent(raw);
|
|
11782
|
+
if (!s) continue;
|
|
11783
|
+
if (!newestSeen || s.starredAt > newestSeen) newestSeen = s.starredAt;
|
|
11784
|
+
if (s.starredAt >= opts.sinceIso) out.push(s);
|
|
11785
|
+
}
|
|
11786
|
+
if (rows.length < 100) break;
|
|
11787
|
+
if (oldestOnPage && oldestOnPage < opts.sinceIso) break;
|
|
11788
|
+
}
|
|
11789
|
+
const stargazers = dedupe();
|
|
11790
|
+
logEvent("github.stargazers", {
|
|
11791
|
+
repo,
|
|
11792
|
+
ok: true,
|
|
11793
|
+
mode: "events",
|
|
11794
|
+
fresh: stargazers.length
|
|
11795
|
+
});
|
|
11796
|
+
return {
|
|
11797
|
+
stargazers,
|
|
11798
|
+
newestSeen
|
|
11799
|
+
};
|
|
11800
|
+
} catch (err) {
|
|
11801
|
+
const message = (err.message ?? "").slice(0, 120);
|
|
11802
|
+
logEvent("github.stargazers", {
|
|
11803
|
+
repo,
|
|
11804
|
+
ok: false,
|
|
11805
|
+
mode: "events",
|
|
11806
|
+
message_120: message
|
|
11807
|
+
}, "warn");
|
|
11808
|
+
return {
|
|
11809
|
+
stargazers: dedupe(),
|
|
11810
|
+
newestSeen,
|
|
11811
|
+
error: message
|
|
11812
|
+
};
|
|
11813
|
+
}
|
|
11814
|
+
}
|
|
11815
|
+
/**
|
|
10617
11816
|
* Recent stargazers of a public repo. GitHub returns stargazers oldest-first,
|
|
10618
11817
|
* so the newest stars live on the LAST page — we read the `Link: rel="last"`
|
|
10619
11818
|
* page number, then page backward (newest → older), collecting stars with
|
|
@@ -10624,6 +11823,11 @@ function parseLastPage(link) {
|
|
|
10624
11823
|
* surfaces as `error` (it usually means a rate-limit mid-walk) rather than
|
|
10625
11824
|
* silently masquerading as "no recent stars".
|
|
10626
11825
|
*
|
|
11826
|
+
* Since July 2026 the list endpoint only answers for repos the token owner
|
|
11827
|
+
* admins/collaborates on; a 401/403/404 on the first page falls back to the
|
|
11828
|
+
* public events feed (recentStargazersViaEvents). Own repos keep the richer
|
|
11829
|
+
* full-history walk.
|
|
11830
|
+
*
|
|
10627
11831
|
* Requires `GITHUB_TOKEN` for any real volume (5,000 req/hr core); without it
|
|
10628
11832
|
* GitHub rate-limits hard at 60/hr — which a backward walk through a big repo
|
|
10629
11833
|
* hits fast.
|
|
@@ -10654,6 +11858,11 @@ async function recentStargazers(repo, opts) {
|
|
|
10654
11858
|
ok: false,
|
|
10655
11859
|
status: firstRes.status
|
|
10656
11860
|
}, "warn");
|
|
11861
|
+
if ([
|
|
11862
|
+
401,
|
|
11863
|
+
403,
|
|
11864
|
+
404
|
|
11865
|
+
].includes(firstRes.status)) return recentStargazersViaEvents(repo, { sinceIso: opts.sinceIso });
|
|
10657
11866
|
return {
|
|
10658
11867
|
stargazers: [],
|
|
10659
11868
|
newestSeen: null,
|
|
@@ -10783,7 +11992,7 @@ async function runGitHubStarsFinder(opts) {
|
|
|
10783
11992
|
if (candidates.length === 0) {
|
|
10784
11993
|
if (firstError) result.halted = `github fetch failed (${firstError}) — set GITHUB_TOKEN for higher rate limits`;
|
|
10785
11994
|
else if (newestSeen) result.halted = `no stars in last ${sinceDays}d — newest was ${Math.floor((Date.now() - new Date(newestSeen).getTime()) / 864e5)}d ago; widen sinceDays`;
|
|
10786
|
-
else result.halted = "no stargazers found (check repo names /
|
|
11995
|
+
else result.halted = "no stargazers found (check repo names — third-party repos only surface stars still in the public events feed, ~90d/300 events)";
|
|
10787
11996
|
logEvent("finder.done", {
|
|
10788
11997
|
name: PLAY_NAME$1,
|
|
10789
11998
|
candidates: 0,
|
|
@@ -12666,13 +13875,14 @@ async function runDueTriggers() {
|
|
|
12666
13875
|
});
|
|
12667
13876
|
try {
|
|
12668
13877
|
const result = await spec.run(config);
|
|
13878
|
+
const durationMs = Date.now() - startedAt;
|
|
12669
13879
|
ledger.updateTriggerLastPoll({
|
|
12670
13880
|
name: spec.name,
|
|
12671
13881
|
summary: result
|
|
12672
13882
|
});
|
|
12673
13883
|
logEvent("trigger.run.done", {
|
|
12674
13884
|
name: spec.name,
|
|
12675
|
-
duration_ms:
|
|
13885
|
+
duration_ms: durationMs,
|
|
12676
13886
|
candidates: result.candidates,
|
|
12677
13887
|
enqueued: result.enqueued,
|
|
12678
13888
|
dropped_icp: result.droppedIcp,
|
|
@@ -12685,9 +13895,11 @@ async function runDueTriggers() {
|
|
|
12685
13895
|
name: spec.name,
|
|
12686
13896
|
fired: true,
|
|
12687
13897
|
result,
|
|
13898
|
+
duration_ms: durationMs,
|
|
12688
13899
|
nextDueInMs: intervalMs
|
|
12689
13900
|
});
|
|
12690
13901
|
} catch (err) {
|
|
13902
|
+
const durationMs = Date.now() - startedAt;
|
|
12691
13903
|
const message = err.message ?? "unknown error";
|
|
12692
13904
|
ledger.updateTriggerLastPoll({
|
|
12693
13905
|
name: spec.name,
|
|
@@ -12698,13 +13910,14 @@ async function runDueTriggers() {
|
|
|
12698
13910
|
});
|
|
12699
13911
|
logEvent("trigger.run.error", {
|
|
12700
13912
|
name: spec.name,
|
|
12701
|
-
duration_ms:
|
|
13913
|
+
duration_ms: durationMs,
|
|
12702
13914
|
message_120: message.slice(0, 120)
|
|
12703
13915
|
}, "error");
|
|
12704
13916
|
outcomes.push({
|
|
12705
13917
|
name: spec.name,
|
|
12706
13918
|
fired: true,
|
|
12707
13919
|
error: message,
|
|
13920
|
+
duration_ms: durationMs,
|
|
12708
13921
|
nextDueInMs: intervalMs
|
|
12709
13922
|
});
|
|
12710
13923
|
}
|
|
@@ -13080,6 +14293,135 @@ function humanInterval(ms) {
|
|
|
13080
14293
|
}
|
|
13081
14294
|
//#endregion
|
|
13082
14295
|
//#region ../../packages/doctor/src/check.ts
|
|
14296
|
+
/** Trailing window for the bounce rate — long enough to accumulate signal at founder-scale volume. */
|
|
14297
|
+
const BOUNCE_WINDOW_DAYS = 30;
|
|
14298
|
+
/**
|
|
14299
|
+
* Sends required before a rate is reported at all. At low volume the rate is
|
|
14300
|
+
* mostly noise: one bad address out of three sends is 33%, which would scream
|
|
14301
|
+
* about a perfectly healthy mailbox.
|
|
14302
|
+
*/
|
|
14303
|
+
const MIN_SENDS_TO_JUDGE = 20;
|
|
14304
|
+
/** Industry rule of thumb: sustained hard bounces above ~2% start costing reputation, ~5% is where providers act. */
|
|
14305
|
+
const HARD_WARN_RATE = .02;
|
|
14306
|
+
const HARD_FAIL_RATE = .05;
|
|
14307
|
+
/**
|
|
14308
|
+
* Extra days of SENDS included in the denominator beyond the bounce window.
|
|
14309
|
+
*
|
|
14310
|
+
* The two sides are timestamped by different events: a bounce is dated when the
|
|
14311
|
+
* DSN arrived, a send when it went out. Using an identical window would count a
|
|
14312
|
+
* DSN that landed just inside it while excluding the send that caused it —
|
|
14313
|
+
* inflating the rate, on a check that can report `fail`. A DSN almost always
|
|
14314
|
+
* arrives within minutes and effectively always within two days, so widening
|
|
14315
|
+
* only the denominator makes the ratio honest. It biases the rate very slightly
|
|
14316
|
+
* LOW, which is the right direction for an error that would otherwise cry wolf.
|
|
14317
|
+
*/
|
|
14318
|
+
const SEND_WINDOW_GRACE_DAYS = 2;
|
|
14319
|
+
/**
|
|
14320
|
+
* Per-identity delivery health from harvested DSNs. Two numbers, deliberately
|
|
14321
|
+
* not averaged together:
|
|
14322
|
+
* - hard-bounce RATE — list quality. Noisy at low volume, hence the sample gate.
|
|
14323
|
+
* - policy-block COUNT — reputation. Reported from the first occurrence, because
|
|
14324
|
+
* a single "blocked as spam" is a real signal about the sending domain and
|
|
14325
|
+
* would vanish if divided into a percentage.
|
|
14326
|
+
*/
|
|
14327
|
+
function deliverabilityChecks() {
|
|
14328
|
+
const results = [];
|
|
14329
|
+
try {
|
|
14330
|
+
const ledger = getLedger();
|
|
14331
|
+
const identities = resolveIdentities(loadConfig());
|
|
14332
|
+
const since = /* @__PURE__ */ new Date(Date.now() - BOUNCE_WINDOW_DAYS * 24 * 3600 * 1e3);
|
|
14333
|
+
const stats = ledger.bounceStatsByIdentity({ sinceIso: since.toISOString() });
|
|
14334
|
+
const blind = identities.filter((i) => i.provider === "oneshot");
|
|
14335
|
+
if (blind.length > 0) results.push({
|
|
14336
|
+
name: "deliverability",
|
|
14337
|
+
severity: "warn",
|
|
14338
|
+
message: `${blind.length} OneShot identit${blind.length === 1 ? "y" : "ies"} not covered — bounce detection reads DSNs from Gmail mailboxes only`
|
|
14339
|
+
});
|
|
14340
|
+
if (stats.size === 0) {
|
|
14341
|
+
const gmailCount = identities.length - blind.length;
|
|
14342
|
+
results.push({
|
|
14343
|
+
name: "deliverability",
|
|
14344
|
+
severity: "ok",
|
|
14345
|
+
message: gmailCount === 0 ? `no Gmail identity to monitor — no bounce data available` : `no delivery failures recorded in the last ${BOUNCE_WINDOW_DAYS}d`
|
|
14346
|
+
});
|
|
14347
|
+
return results;
|
|
14348
|
+
}
|
|
14349
|
+
for (const identity of identities) {
|
|
14350
|
+
if (identity.provider === "oneshot") continue;
|
|
14351
|
+
const s = stats.get(identity.id);
|
|
14352
|
+
const sent = ledger.countEmailSendsSince(identity.id, daysAgoSqliteUtc(BOUNCE_WINDOW_DAYS + SEND_WINDOW_GRACE_DAYS));
|
|
14353
|
+
const label = identity.address ?? identity.sendingDomain ?? identity.id;
|
|
14354
|
+
if (!s) {
|
|
14355
|
+
results.push({
|
|
14356
|
+
name: "deliverability",
|
|
14357
|
+
severity: "ok",
|
|
14358
|
+
message: sent === 0 ? `${label} no sends in the last ${BOUNCE_WINDOW_DAYS}d` : `${label} 0 bounced of ${sent} sent (${BOUNCE_WINDOW_DAYS}d)`
|
|
14359
|
+
});
|
|
14360
|
+
continue;
|
|
14361
|
+
}
|
|
14362
|
+
const blockNote = s.block > 0 ? ` — ${s.block} spam-block${s.block === 1 ? "" : "s"}, check content/volume` : "";
|
|
14363
|
+
if (sent < MIN_SENDS_TO_JUDGE) {
|
|
14364
|
+
results.push({
|
|
14365
|
+
name: "deliverability",
|
|
14366
|
+
severity: s.block > 0 ? "warn" : "ok",
|
|
14367
|
+
message: `${label} ${s.hard} hard / ${s.block} blocked of ${sent} sent (${BOUNCE_WINDOW_DAYS}d) — too few sends to rate${blockNote}`
|
|
14368
|
+
});
|
|
14369
|
+
continue;
|
|
14370
|
+
}
|
|
14371
|
+
const rate = s.hard / sent;
|
|
14372
|
+
const pct = `${(rate * 100).toFixed(1)}%`;
|
|
14373
|
+
const severity = rate > HARD_FAIL_RATE ? "fail" : rate > HARD_WARN_RATE || s.block > 0 ? "warn" : "ok";
|
|
14374
|
+
results.push({
|
|
14375
|
+
name: "deliverability",
|
|
14376
|
+
severity,
|
|
14377
|
+
message: `${label} ${pct} bounced (${s.hard}/${sent}, ${BOUNCE_WINDOW_DAYS}d)${blockNote}`,
|
|
14378
|
+
...severity === "ok" ? {} : { hint: rate > HARD_WARN_RATE ? "verify emails before sending — hard bounces are dead addresses" : "spam-blocks are a reputation signal, not a bad address" }
|
|
14379
|
+
});
|
|
14380
|
+
}
|
|
14381
|
+
} catch (err) {
|
|
14382
|
+
results.push({
|
|
14383
|
+
name: "deliverability",
|
|
14384
|
+
severity: "warn",
|
|
14385
|
+
message: `could not evaluate: ${err.message}`
|
|
14386
|
+
});
|
|
14387
|
+
}
|
|
14388
|
+
return results;
|
|
14389
|
+
}
|
|
14390
|
+
/** A placement result older than this is reported as stale — reputation moves. */
|
|
14391
|
+
const CANARY_STALE_DAYS = 14;
|
|
14392
|
+
/**
|
|
14393
|
+
* REPORTS the last inbox-placement canary; never runs one. doctor is expected
|
|
14394
|
+
* to be safe to run at any time, and a canary sends real mail — firing one per
|
|
14395
|
+
* doctor invocation would both spend sending reputation and, by repeatedly
|
|
14396
|
+
* mailing the same seed address, train its filter until the test always passed.
|
|
14397
|
+
*/
|
|
14398
|
+
function placementCheck() {
|
|
14399
|
+
try {
|
|
14400
|
+
const last = getLedger().latestCanaryResult();
|
|
14401
|
+
if (!last) return {
|
|
14402
|
+
name: "inbox placement",
|
|
14403
|
+
severity: "ok",
|
|
14404
|
+
message: "never tested",
|
|
14405
|
+
hint: "run: bun run cli -- gmail placement (needs a second authorized Gmail account)"
|
|
14406
|
+
};
|
|
14407
|
+
const ageDays = Math.floor((Date.now() - (/* @__PURE__ */ new Date(`${last.created_at.replace(" ", "T")}Z`)).getTime()) / 864e5);
|
|
14408
|
+
const age = Number.isFinite(ageDays) ? `${ageDays}d ago` : "unknown age";
|
|
14409
|
+
const auth = `spf=${last.spf} dkim=${last.dkim} dmarc=${last.dmarc}`;
|
|
14410
|
+
const caveat = last.same_domain ? " · same-domain, not a real-world verdict" : "";
|
|
14411
|
+
return {
|
|
14412
|
+
name: "inbox placement",
|
|
14413
|
+
severity: last.placement === "spam" ? "fail" : last.placement === "promotions" || last.placement === "tab" || last.placement === "not_delivered" || last.same_domain === 1 || ageDays > CANARY_STALE_DAYS ? "warn" : "ok",
|
|
14414
|
+
message: `${last.placement} (${age}) · ${auth}${caveat}`,
|
|
14415
|
+
...ageDays > CANARY_STALE_DAYS ? { hint: `last tested ${age} — re-run: bun run cli -- gmail placement` } : {}
|
|
14416
|
+
};
|
|
14417
|
+
} catch (err) {
|
|
14418
|
+
return {
|
|
14419
|
+
name: "inbox placement",
|
|
14420
|
+
severity: "warn",
|
|
14421
|
+
message: `could not evaluate: ${err.message}`
|
|
14422
|
+
};
|
|
14423
|
+
}
|
|
14424
|
+
}
|
|
13083
14425
|
async function runDoctor() {
|
|
13084
14426
|
const cfg = loadConfig();
|
|
13085
14427
|
const results = [];
|
|
@@ -13197,7 +14539,7 @@ async function runDoctor() {
|
|
|
13197
14539
|
name,
|
|
13198
14540
|
severity: "warn",
|
|
13199
14541
|
message: `${localpart}${domain} is ${entry.status} in the pool · ${usage}`,
|
|
13200
|
-
hint:
|
|
14542
|
+
hint: `Resume it on /setup (Sender → Provisioned domains) or run: oneshot-gtm domains resume ${domain}`
|
|
13201
14543
|
});
|
|
13202
14544
|
else {
|
|
13203
14545
|
const warmth = entry?.status === "warming" ? ` · warming${entry.warmupScore != null ? ` (score ${entry.warmupScore})` : ""} — pinned sends skip server warm-up, client cap throttles` : "";
|
|
@@ -13216,6 +14558,8 @@ async function runDoctor() {
|
|
|
13216
14558
|
message: `could not evaluate: ${err.message}`
|
|
13217
14559
|
});
|
|
13218
14560
|
}
|
|
14561
|
+
results.push(...deliverabilityChecks());
|
|
14562
|
+
results.push(placementCheck());
|
|
13219
14563
|
if (oneshotEnvReady()) try {
|
|
13220
14564
|
const bal = await getBalance();
|
|
13221
14565
|
results.push({
|
|
@@ -13246,6 +14590,51 @@ async function doctor(req) {
|
|
|
13246
14590
|
}) }, 200, req);
|
|
13247
14591
|
}
|
|
13248
14592
|
//#endregion
|
|
14593
|
+
//#region src/api/domains.ts
|
|
14594
|
+
/**
|
|
14595
|
+
* Resume / pause a wallet-owned sending domain in the OneShot pool. The /setup
|
|
14596
|
+
* UI calls these to act on a paused domain (the doctor flags one); the CLI
|
|
14597
|
+
* (`oneshot-gtm domains resume/pause`) hits the same core wrappers.
|
|
14598
|
+
*
|
|
14599
|
+
* Errors are surfaced verbatim (incl. the platform HTTP status) rather than
|
|
14600
|
+
* swallowed — a paused domain that won't resume because OneShot is returning
|
|
14601
|
+
* 500s is exactly what the founder needs to see, not a silent no-op.
|
|
14602
|
+
*/
|
|
14603
|
+
async function domainActionRoute(req, action) {
|
|
14604
|
+
let body;
|
|
14605
|
+
try {
|
|
14606
|
+
body = await req.json();
|
|
14607
|
+
} catch {
|
|
14608
|
+
return jsonResponse({ error: "invalid JSON body" }, 400, req);
|
|
14609
|
+
}
|
|
14610
|
+
if (typeof body.domain !== "string" || body.domain.trim().length === 0) return jsonResponse({ error: "domain (string) required" }, 400, req);
|
|
14611
|
+
const domain = body.domain.trim().toLowerCase();
|
|
14612
|
+
try {
|
|
14613
|
+
const result = action === "resume" ? await resumeSendingDomain(domain) : await pauseSendingDomain(domain);
|
|
14614
|
+
return jsonResponse({
|
|
14615
|
+
domain: result.domain,
|
|
14616
|
+
poolStatus: result.pool_status
|
|
14617
|
+
}, 200, req);
|
|
14618
|
+
} catch (err) {
|
|
14619
|
+
const e = err;
|
|
14620
|
+
logEvent(`domains.${action}_failed`, {
|
|
14621
|
+
domain,
|
|
14622
|
+
status_code: typeof e?.statusCode === "number" ? e.statusCode : null
|
|
14623
|
+
}, "warn");
|
|
14624
|
+
const sc = typeof e?.statusCode === "number" ? e.statusCode : null;
|
|
14625
|
+
const msg = e?.message ?? `${action} failed`;
|
|
14626
|
+
const detail = sc != null ? ` (OneShot HTTP ${sc})` : "";
|
|
14627
|
+
const httpStatus = sc != null && sc >= 400 && sc < 500 ? sc : 502;
|
|
14628
|
+
return jsonResponse({ error: `${msg}${detail}` }, httpStatus, req);
|
|
14629
|
+
}
|
|
14630
|
+
}
|
|
14631
|
+
function resumeDomainRoute(req) {
|
|
14632
|
+
return domainActionRoute(req, "resume");
|
|
14633
|
+
}
|
|
14634
|
+
function pauseDomainRoute(req) {
|
|
14635
|
+
return domainActionRoute(req, "pause");
|
|
14636
|
+
}
|
|
14637
|
+
//#endregion
|
|
13249
14638
|
//#region src/api/_play-dispatch.ts
|
|
13250
14639
|
function toDraftedView(d) {
|
|
13251
14640
|
return {
|
|
@@ -13281,21 +14670,9 @@ async function dispatchPlay(playName, body, onProgress) {
|
|
|
13281
14670
|
}
|
|
13282
14671
|
//#endregion
|
|
13283
14672
|
//#region src/api/run.ts
|
|
13284
|
-
const SUPPORTED = new Set([
|
|
13285
|
-
"show-hn",
|
|
13286
|
-
"job-change",
|
|
13287
|
-
"post-funding",
|
|
13288
|
-
"accelerator-batch",
|
|
13289
|
-
"hiring-signal",
|
|
13290
|
-
"podcast-guest",
|
|
13291
|
-
"competitor-switch",
|
|
13292
|
-
"stack-consolidation",
|
|
13293
|
-
"repo-interest",
|
|
13294
|
-
"luma-events"
|
|
13295
|
-
]);
|
|
13296
14673
|
async function runPlay(req, params) {
|
|
13297
14674
|
const playName = params["playName"] ?? "";
|
|
13298
|
-
if (!
|
|
14675
|
+
if (!isRunnablePlay(playName)) return jsonResponse({ error: `play '${playName}' is not exposed in the UI; use the CLI` }, 400, req);
|
|
13299
14676
|
let body;
|
|
13300
14677
|
try {
|
|
13301
14678
|
body = await req.json();
|
|
@@ -13312,6 +14689,9 @@ async function runPlay(req, params) {
|
|
|
13312
14689
|
const stream = new ReadableStream({ async start(controller) {
|
|
13313
14690
|
const encoder = new TextEncoder();
|
|
13314
14691
|
const ledger = getLedger();
|
|
14692
|
+
const t0 = performance.now();
|
|
14693
|
+
let runOutcome = "ok";
|
|
14694
|
+
let fromQueue = false;
|
|
13315
14695
|
const send = (event) => {
|
|
13316
14696
|
try {
|
|
13317
14697
|
ledger.appendRunEvent({
|
|
@@ -13337,7 +14717,7 @@ async function runPlay(req, params) {
|
|
|
13337
14717
|
if (email && key) emailToDedupeKey.set(email, key);
|
|
13338
14718
|
});
|
|
13339
14719
|
const inputCount = body.targets.length;
|
|
13340
|
-
|
|
14720
|
+
fromQueue = Array.isArray(body.dedupeKeys) && body.dedupeKeys.length === body.targets.length;
|
|
13341
14721
|
let verify;
|
|
13342
14722
|
if (fromQueue) verify = {
|
|
13343
14723
|
verified: body.targets,
|
|
@@ -13414,6 +14794,7 @@ async function runPlay(req, params) {
|
|
|
13414
14794
|
emailToDedupeKey
|
|
13415
14795
|
});
|
|
13416
14796
|
} catch (err) {
|
|
14797
|
+
runOutcome = "error";
|
|
13417
14798
|
const e = err;
|
|
13418
14799
|
const causeMsg = e?.cause instanceof Error ? e.cause.message : e?.cause ? String(e.cause) : null;
|
|
13419
14800
|
logEvent("run.pipeline_error", {
|
|
@@ -13451,6 +14832,14 @@ async function runPlay(req, params) {
|
|
|
13451
14832
|
try {
|
|
13452
14833
|
controller.close();
|
|
13453
14834
|
} catch {}
|
|
14835
|
+
const flags = [];
|
|
14836
|
+
if (body.dryRun) flags.push("dry-run");
|
|
14837
|
+
if (fromQueue) flags.push("from-queue");
|
|
14838
|
+
reportServerExecution(`server.run.${playName}`, {
|
|
14839
|
+
outcome: runOutcome,
|
|
14840
|
+
durationMs: performance.now() - t0,
|
|
14841
|
+
flags
|
|
14842
|
+
});
|
|
13454
14843
|
}
|
|
13455
14844
|
} });
|
|
13456
14845
|
const origin = req.headers.get("origin") ?? "";
|
|
@@ -13589,16 +14978,19 @@ function listQueueRoute(req) {
|
|
|
13589
14978
|
const url = new URL(req.url);
|
|
13590
14979
|
const playName = url.searchParams.get("play") ?? void 0;
|
|
13591
14980
|
const status = url.searchParams.get("status") ?? void 0;
|
|
14981
|
+
const ids = parseQueueIds(url.searchParams.get("ids"));
|
|
13592
14982
|
const limit = Math.min(500, Number.parseInt(url.searchParams.get("limit") ?? "200", 10) || 200);
|
|
13593
14983
|
const ledger = getLedger();
|
|
13594
|
-
const filterArgs = { limit };
|
|
14984
|
+
const filterArgs = { limit: ids ? Math.max(limit, ids.length) : limit };
|
|
13595
14985
|
if (playName) filterArgs.playName = playName;
|
|
13596
14986
|
if (status) filterArgs.status = status;
|
|
14987
|
+
if (ids) filterArgs.ids = ids;
|
|
13597
14988
|
const rows = ledger.listQueue(filterArgs);
|
|
13598
14989
|
const counts = ledger.queueCounts();
|
|
13599
14990
|
return jsonResponse({
|
|
13600
14991
|
rows: rows.map(toView$1),
|
|
13601
|
-
counts
|
|
14992
|
+
counts,
|
|
14993
|
+
approvedByPlay: ledger.approvedCountsByPlay()
|
|
13602
14994
|
}, 200, req);
|
|
13603
14995
|
}
|
|
13604
14996
|
async function approveQueueRoute(req, params) {
|
|
@@ -13646,18 +15038,31 @@ async function drainQueueRoute(req) {
|
|
|
13646
15038
|
return jsonResponse({ error: "invalid JSON body" }, 400, req);
|
|
13647
15039
|
}
|
|
13648
15040
|
if (!body.playName) return jsonResponse({ error: "playName required" }, 400, req);
|
|
13649
|
-
const
|
|
13650
|
-
|
|
13651
|
-
|
|
13652
|
-
|
|
13653
|
-
|
|
13654
|
-
|
|
13655
|
-
|
|
13656
|
-
|
|
13657
|
-
|
|
13658
|
-
|
|
13659
|
-
|
|
13660
|
-
|
|
15041
|
+
const t0 = performance.now();
|
|
15042
|
+
let outcome = "ok";
|
|
15043
|
+
try {
|
|
15044
|
+
const result = await drainQueue({
|
|
15045
|
+
playName: body.playName,
|
|
15046
|
+
limit: body.limit ?? 10,
|
|
15047
|
+
dryRun: !!body.dryRun,
|
|
15048
|
+
...body.senderCohort ? { senderCohort: body.senderCohort } : {},
|
|
15049
|
+
...body.freeForCohortOffer ? { freeForCohortOffer: body.freeForCohortOffer } : {}
|
|
15050
|
+
});
|
|
15051
|
+
return jsonResponse({
|
|
15052
|
+
drained: result.drained,
|
|
15053
|
+
sent: result.sent,
|
|
15054
|
+
errors: result.errors
|
|
15055
|
+
}, 200, req);
|
|
15056
|
+
} catch (err) {
|
|
15057
|
+
outcome = "error";
|
|
15058
|
+
throw err;
|
|
15059
|
+
} finally {
|
|
15060
|
+
reportServerExecution("server.queue.drain", {
|
|
15061
|
+
outcome,
|
|
15062
|
+
durationMs: performance.now() - t0,
|
|
15063
|
+
flags: body.dryRun ? ["dry-run"] : []
|
|
15064
|
+
});
|
|
15065
|
+
}
|
|
13661
15066
|
}
|
|
13662
15067
|
/**
|
|
13663
15068
|
* Re-draft a single queue row in PREVIEW mode and overwrite its persisted
|
|
@@ -13764,6 +15169,14 @@ async function sendDraftRoute(req, params) {
|
|
|
13764
15169
|
const str = (k) => typeof payload[k] === "string" ? payload[k] : null;
|
|
13765
15170
|
const email = str("email") ?? str("founderEmail");
|
|
13766
15171
|
if (!email) return jsonResponse({ error: "row has no recipient email" }, 400, req);
|
|
15172
|
+
const t0 = performance.now();
|
|
15173
|
+
const done = (outcome, res) => {
|
|
15174
|
+
reportServerExecution("server.queue.send", {
|
|
15175
|
+
outcome,
|
|
15176
|
+
durationMs: performance.now() - t0
|
|
15177
|
+
});
|
|
15178
|
+
return res;
|
|
15179
|
+
};
|
|
13767
15180
|
const sendFlags = [];
|
|
13768
15181
|
let result;
|
|
13769
15182
|
try {
|
|
@@ -13779,7 +15192,7 @@ async function sendDraftRoute(req, params) {
|
|
|
13779
15192
|
name: str("name") ?? str("founderName"),
|
|
13780
15193
|
email,
|
|
13781
15194
|
company: str("company"),
|
|
13782
|
-
linkedin_url: str("linkedinUrl"),
|
|
15195
|
+
linkedin_url: str("linkedinUrl") ?? str("twitterUrl") ?? str("githubUrl"),
|
|
13783
15196
|
phone: str("phone"),
|
|
13784
15197
|
source: row.play_name
|
|
13785
15198
|
},
|
|
@@ -13789,11 +15202,16 @@ async function sendDraftRoute(req, params) {
|
|
|
13789
15202
|
try {
|
|
13790
15203
|
ledger.clearQueueSendingMarker(id);
|
|
13791
15204
|
} catch {}
|
|
13792
|
-
if (isSendDeferred(err)) return jsonResponse({
|
|
15205
|
+
if (isSendDeferred(err)) return done("ok", jsonResponse({
|
|
13793
15206
|
error: err.message,
|
|
13794
15207
|
deferred: true
|
|
13795
|
-
}, 429, req);
|
|
13796
|
-
|
|
15208
|
+
}, 429, req));
|
|
15209
|
+
logTargetError({
|
|
15210
|
+
playName: row.play_name,
|
|
15211
|
+
to: email,
|
|
15212
|
+
err
|
|
15213
|
+
});
|
|
15214
|
+
return done("error", jsonResponse({ error: err.message ?? "send failed" }, 400, req));
|
|
13797
15215
|
}
|
|
13798
15216
|
if (!result.sent) {
|
|
13799
15217
|
try {
|
|
@@ -13807,13 +15225,13 @@ async function sendDraftRoute(req, params) {
|
|
|
13807
15225
|
status: "rejected",
|
|
13808
15226
|
notes: `auto: ${reason} — not re-sent`
|
|
13809
15227
|
});
|
|
13810
|
-
return jsonResponse({
|
|
15228
|
+
return done("ok", jsonResponse({
|
|
13811
15229
|
error: `${reason} — not re-sent`,
|
|
13812
15230
|
skipped: true,
|
|
13813
15231
|
reason: dedup
|
|
13814
|
-
}, 409, req);
|
|
15232
|
+
}, 409, req));
|
|
13815
15233
|
}
|
|
13816
|
-
return jsonResponse({ error: "send did not complete" }, 500, req);
|
|
15234
|
+
return done("error", jsonResponse({ error: "send did not complete" }, 500, req));
|
|
13817
15235
|
}
|
|
13818
15236
|
const prospect = ledger.findProspectByEmail(email);
|
|
13819
15237
|
if (prospect) enrollInCadence({
|
|
@@ -13835,10 +15253,10 @@ async function sendDraftRoute(req, params) {
|
|
|
13835
15253
|
dryRun: false
|
|
13836
15254
|
}
|
|
13837
15255
|
});
|
|
13838
|
-
return jsonResponse({
|
|
15256
|
+
return done("ok", jsonResponse({
|
|
13839
15257
|
sent: true,
|
|
13840
15258
|
receiptIds: result.receiptIds
|
|
13841
|
-
}, 200, req);
|
|
15259
|
+
}, 200, req));
|
|
13842
15260
|
}
|
|
13843
15261
|
//#endregion
|
|
13844
15262
|
//#region src/api/triggers.ts
|
|
@@ -13980,6 +15398,44 @@ function runTriggerRoute(req, params) {
|
|
|
13980
15398
|
}, 202, req);
|
|
13981
15399
|
}
|
|
13982
15400
|
//#endregion
|
|
15401
|
+
//#region src/api/prospects.ts
|
|
15402
|
+
/**
|
|
15403
|
+
* POST /api/prospects/add — manual add-prospect from a profile URL.
|
|
15404
|
+
*
|
|
15405
|
+
* Validates + enqueues a placeholder `profile-intro` queue row synchronously,
|
|
15406
|
+
* then kicks off the ~2-5 min dossier research + draft in the background
|
|
15407
|
+
* (`void runProspectResearch`) and returns 202 immediately. The drafted row
|
|
15408
|
+
* fills in on `/queue` (which polls) when research completes.
|
|
15409
|
+
*/
|
|
15410
|
+
async function addProspectRoute(req) {
|
|
15411
|
+
let body;
|
|
15412
|
+
try {
|
|
15413
|
+
body = await req.json();
|
|
15414
|
+
} catch {
|
|
15415
|
+
return jsonResponse({ error: "invalid JSON body" }, 400, req);
|
|
15416
|
+
}
|
|
15417
|
+
if (!body || typeof body.url !== "string" || body.url.trim() === "") return jsonResponse({ error: "url required" }, 400, req);
|
|
15418
|
+
const email = typeof body.email === "string" && body.email.trim() !== "" ? body.email.trim() : void 0;
|
|
15419
|
+
let job;
|
|
15420
|
+
try {
|
|
15421
|
+
job = createProspectResearchJob({
|
|
15422
|
+
url: body.url,
|
|
15423
|
+
...email ? { emailOverride: email } : {}
|
|
15424
|
+
});
|
|
15425
|
+
} catch (err) {
|
|
15426
|
+
return jsonResponse({ error: err.message }, 400, req);
|
|
15427
|
+
}
|
|
15428
|
+
if ("duplicate" in job) return jsonResponse({
|
|
15429
|
+
queued: false,
|
|
15430
|
+
duplicate: true
|
|
15431
|
+
}, 200, req);
|
|
15432
|
+
runProspectResearch(job.queueId);
|
|
15433
|
+
return jsonResponse({
|
|
15434
|
+
queued: true,
|
|
15435
|
+
queueId: job.queueId
|
|
15436
|
+
}, 202, req);
|
|
15437
|
+
}
|
|
15438
|
+
//#endregion
|
|
13983
15439
|
//#region src/server.ts
|
|
13984
15440
|
function route(method, pattern, handler) {
|
|
13985
15441
|
const paramNames = [];
|
|
@@ -14018,6 +15474,8 @@ const routes = [
|
|
|
14018
15474
|
route("POST", "/api/measure/outcome", recordOutcome),
|
|
14019
15475
|
route("GET", "/api/setup", getSetupStatus),
|
|
14020
15476
|
route("POST", "/api/setup", setup),
|
|
15477
|
+
route("POST", "/api/domains/resume", resumeDomainRoute),
|
|
15478
|
+
route("POST", "/api/domains/pause", pauseDomainRoute),
|
|
14021
15479
|
route("GET", "/api/gmail/auth/start", startGmailAuthRoute),
|
|
14022
15480
|
route("GET", "/api/gmail/auth/callback", gmailAuthCallbackRoute),
|
|
14023
15481
|
route("POST", "/api/setup/derive-icp", deriveIcpRoute),
|
|
@@ -14025,6 +15483,7 @@ const routes = [
|
|
|
14025
15483
|
route("GET", "/api/doctor", doctor),
|
|
14026
15484
|
route("POST", "/api/run/:playName", runPlay),
|
|
14027
15485
|
route("GET", "/api/runs/:id", getRunRoute),
|
|
15486
|
+
route("POST", "/api/prospects/add", addProspectRoute),
|
|
14028
15487
|
route("GET", "/api/queue", listQueueRoute),
|
|
14029
15488
|
route("POST", "/api/queue/approve-all", approveAllRoute),
|
|
14030
15489
|
route("POST", "/api/queue/drain", drainQueueRoute),
|
|
@@ -14154,23 +15613,58 @@ function jsonResponse(body, status = 200, req) {
|
|
|
14154
15613
|
}
|
|
14155
15614
|
//#endregion
|
|
14156
15615
|
//#region src/scheduler.ts
|
|
15616
|
+
/**
|
|
15617
|
+
* Map a fired trigger's outcome to a telemetry outcome. A thrown error is an
|
|
15618
|
+
* error; so is a finder that returned but `halted` early (e.g. cost cap, all
|
|
15619
|
+
* cohorts empty) — that's a degraded run, not a clean success, and lumping it
|
|
15620
|
+
* into "ok" would understate the real failure rate. Exported for unit tests.
|
|
15621
|
+
*/
|
|
15622
|
+
function triggerOutcome(o) {
|
|
15623
|
+
return o.error || o.result?.halted ? "error" : "ok";
|
|
15624
|
+
}
|
|
14157
15625
|
const FIRST_TICK_DELAY_MS = 5e3;
|
|
14158
15626
|
const ERROR_BACKOFF_MS = 6e4;
|
|
14159
15627
|
const REPLY_POLL_MAX_MS = 5 * 6e4;
|
|
15628
|
+
/**
|
|
15629
|
+
* Bounces are swept far less often than replies. A reply is time-sensitive —
|
|
15630
|
+
* every minute it goes unnoticed is a minute the cadence might send again. A
|
|
15631
|
+
* bounce has already happened and the sweep re-reads a 30-day window, so
|
|
15632
|
+
* running it at reply cadence would re-fetch and re-parse the same DSNs a
|
|
15633
|
+
* couple of hundred times a day for no new information.
|
|
15634
|
+
*/
|
|
15635
|
+
const BOUNCE_POLL_INTERVAL_MS = 30 * 6e4;
|
|
14160
15636
|
function startScheduler() {
|
|
14161
15637
|
let cancelled = false;
|
|
14162
15638
|
let timer = null;
|
|
15639
|
+
let lastBouncePollAt = 0;
|
|
14163
15640
|
const tick = async () => {
|
|
14164
15641
|
if (cancelled) return;
|
|
14165
15642
|
try {
|
|
14166
15643
|
const outcomes = await runDueTriggers();
|
|
14167
15644
|
const fired = outcomes.filter((o) => o.fired).length;
|
|
15645
|
+
for (const o of outcomes) {
|
|
15646
|
+
if (!o.fired) continue;
|
|
15647
|
+
reportServerExecution(`server.trigger.${o.name}`, {
|
|
15648
|
+
outcome: triggerOutcome(o),
|
|
15649
|
+
durationMs: o.duration_ms ?? 0,
|
|
15650
|
+
flags: ["scheduled"]
|
|
15651
|
+
});
|
|
15652
|
+
}
|
|
14168
15653
|
let repliesDetected = 0;
|
|
14169
15654
|
try {
|
|
14170
15655
|
repliesDetected = (await pollInboxReplies()).repliesDetected;
|
|
14171
15656
|
} catch (err) {
|
|
14172
15657
|
logEvent("scheduler.reply_poll.failed", { message_120: (err.message ?? "").slice(0, 120) }, "warn");
|
|
14173
15658
|
}
|
|
15659
|
+
let bouncesRecorded = 0;
|
|
15660
|
+
if (Date.now() - lastBouncePollAt >= BOUNCE_POLL_INTERVAL_MS) {
|
|
15661
|
+
lastBouncePollAt = Date.now();
|
|
15662
|
+
try {
|
|
15663
|
+
bouncesRecorded = (await pollInboxBounces()).recorded;
|
|
15664
|
+
} catch (err) {
|
|
15665
|
+
logEvent("scheduler.bounce_poll.failed", { message_120: (err.message ?? "").slice(0, 120) }, "warn");
|
|
15666
|
+
}
|
|
15667
|
+
}
|
|
14174
15668
|
try {
|
|
14175
15669
|
await runPendingRetries();
|
|
14176
15670
|
} catch (err) {
|
|
@@ -14179,6 +15673,7 @@ function startScheduler() {
|
|
|
14179
15673
|
logEvent("scheduler.tick.done", {
|
|
14180
15674
|
fired,
|
|
14181
15675
|
repliesDetected,
|
|
15676
|
+
bouncesRecorded,
|
|
14182
15677
|
source: "server"
|
|
14183
15678
|
});
|
|
14184
15679
|
if (cancelled) return;
|