thumbgate 1.40.12 → 1.40.14
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/.claude-plugin/plugin.json +1 -1
- package/.well-known/mcp/server-card.json +1 -1
- package/adapters/claude/.mcp.json +3 -3
- package/adapters/forge/forge.yaml +3 -3
- package/adapters/future-agi/.mcp.json +1 -1
- package/adapters/future-agi/config.toml +1 -1
- package/adapters/future-agi/opencode.json +1 -1
- package/adapters/herdr/herdr-plugin.toml +2 -2
- package/adapters/mcp/server-stdio.js +18 -5
- package/adapters/opencode/opencode.json +1 -1
- package/bin/cli.js +6 -7
- package/config/unit-costs.json +47 -0
- package/package.json +16 -9
- package/public/admin.html +58 -3
- package/public/index.html +2 -2
- package/public/install.html +8 -8
- package/public/learn.html +8 -0
- package/public/numbers.html +2 -2
- package/public/project-switcher.js +10 -3
- package/scripts/activation-tracker.js +106 -5
- package/scripts/check-update.js +116 -1
- package/scripts/cli-feedback.js +8 -7
- package/scripts/cost-meter.js +161 -0
- package/scripts/first-block-upsell.js +30 -6
- package/scripts/mailer/resend-mailer.js +2 -0
- package/scripts/owner-admin.js +136 -13
- package/scripts/owner-alerts.js +6 -1
- package/scripts/owner-telemetry.js +22 -2
- package/scripts/pr-manager.js +156 -41
- package/scripts/project-identity.js +6 -1
- package/scripts/statusline-human-counts.js +52 -7
- package/scripts/unit-economics.js +138 -0
- package/server.json +2 -2
- package/src/api/server.js +43 -3
- package/src/mcp-writeguard.js +2 -2
|
@@ -3,7 +3,12 @@
|
|
|
3
3
|
/**
|
|
4
4
|
* One plain upgrade line right after a user's FIRST real block, then at most once per 7 days.
|
|
5
5
|
*
|
|
6
|
-
* Shape: "ThumbGate just stopped <what>. Pro adds <feature> - thumbgate.ai/
|
|
6
|
+
* Shape: "ThumbGate just stopped <what>. Pro adds <feature> - https://thumbgate.ai/checkout/pro?utm_source=cli&..."
|
|
7
|
+
*
|
|
8
|
+
* The link carries a scheme so terminals make it clickable, and it opens the checkout page (one click
|
|
9
|
+
* to Stripe) instead of /pricing (two). Each showing sends a `first_block_upsell_shown` ping so the
|
|
10
|
+
* activated -> shown -> checkout funnel has a denominator.
|
|
11
|
+
* See docs/decisions/2026-11-24-revenue-funnel-activation.md.
|
|
7
12
|
*
|
|
8
13
|
* Channel: a PreToolUse hook is never a TTY (stdin and stdout are pipes), so the line is not printed.
|
|
9
14
|
* It rides in the hook JSON's top-level `systemMessage`, which the host shows to the person and
|
|
@@ -19,7 +24,13 @@ const fs = require('node:fs');
|
|
|
19
24
|
const path = require('node:path');
|
|
20
25
|
|
|
21
26
|
const COOLDOWN_MS = 7 * 24 * 60 * 60 * 1000;
|
|
22
|
-
const
|
|
27
|
+
const UPSELL_BASE_URL = 'https://thumbgate.ai/checkout/pro';
|
|
28
|
+
const PRICING_URL = `${UPSELL_BASE_URL}?utm_source=cli&utm_medium=first_block&utm_campaign=first_block_upsell`;
|
|
29
|
+
|
|
30
|
+
function upsellUrl(gateId) {
|
|
31
|
+
const safeGate = String(gateId || '').toLowerCase().replace(/[^a-z0-9-]/g, '').slice(0, 40);
|
|
32
|
+
return safeGate && STOPPED_PHRASES[safeGate] ? `${PRICING_URL}&utm_content=${safeGate}` : PRICING_URL;
|
|
33
|
+
}
|
|
23
34
|
const STATE_FILE = 'first-block-upsell.json';
|
|
24
35
|
const CI_VARS = ['CI', 'GITHUB_ACTIONS', 'TRAVIS', 'CIRCLECI', 'JENKINS_URL', 'GITLAB_CI', 'CODEBUILD_BUILD_ID'];
|
|
25
36
|
|
|
@@ -47,7 +58,7 @@ function proFeature() {
|
|
|
47
58
|
}
|
|
48
59
|
|
|
49
60
|
function buildLine(gateId) {
|
|
50
|
-
return `ThumbGate just stopped ${stoppedPhrase(gateId)}. Pro adds ${proFeature()} - ${
|
|
61
|
+
return `ThumbGate just stopped ${stoppedPhrase(gateId)}. Pro adds ${proFeature()} - ${upsellUrl(gateId)}`;
|
|
51
62
|
}
|
|
52
63
|
|
|
53
64
|
// A paying, licensed, creator or owner install never sees the line. The 7-day trial is NOT exempt:
|
|
@@ -80,7 +91,19 @@ function readState(file) {
|
|
|
80
91
|
* Decide whether to show the line for a real block, and record it when shown.
|
|
81
92
|
* @returns {{ show: boolean, line?: string, reason?: string }}
|
|
82
93
|
*/
|
|
83
|
-
|
|
94
|
+
// Fire-and-forget ping when the line is shown. Never in tests unless a tracker is injected.
|
|
95
|
+
function defaultTrack(eventType, metadata, env) {
|
|
96
|
+
if (env.NODE_TEST_CONTEXT || env.NODE_ENV === 'test' || process.env.NODE_TEST_CONTEXT) return;
|
|
97
|
+
if (env.THUMBGATE_NO_TELEMETRY === '1' || env.DO_NOT_TRACK === '1') return;
|
|
98
|
+
try { require('./cli-telemetry').trackEvent(eventType, metadata); } catch { /* best-effort */ }
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function shown(gate, shownCount, track, env) {
|
|
102
|
+
try { track('first_block_upsell_shown', { gateId: gate ? String(gate).slice(0, 120) : null, shownCount }, env); } catch { /* best-effort */ }
|
|
103
|
+
return { show: true, line: buildLine(gate) };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function maybeUpsell({ gate, env = process.env, now = Date.now(), stateDir, exempt = defaultExempt, track = defaultTrack } = {}) {
|
|
84
107
|
try {
|
|
85
108
|
if (env.THUMBGATE_NO_UPSELL === '1') return { show: false, reason: 'opt-out' };
|
|
86
109
|
if (CI_VARS.some((name) => env[name])) return { show: false, reason: 'ci' };
|
|
@@ -102,7 +125,7 @@ function maybeUpsell({ gate, env = process.env, now = Date.now(), stateDir, exem
|
|
|
102
125
|
} catch (err) {
|
|
103
126
|
return { show: false, reason: err && err.code === 'EEXIST' ? 'claimed-elsewhere' : 'state-unwritable' };
|
|
104
127
|
}
|
|
105
|
-
return
|
|
128
|
+
return shown(gate, 1, track, env);
|
|
106
129
|
}
|
|
107
130
|
|
|
108
131
|
if (state.corrupt) {
|
|
@@ -126,7 +149,7 @@ function maybeUpsell({ gate, env = process.env, now = Date.now(), stateDir, exem
|
|
|
126
149
|
} catch {
|
|
127
150
|
return { show: false, reason: 'state-unwritable' };
|
|
128
151
|
}
|
|
129
|
-
return
|
|
152
|
+
return shown(gate, next.shownCount, track, env);
|
|
130
153
|
} catch {
|
|
131
154
|
return { show: false, reason: 'error' };
|
|
132
155
|
}
|
|
@@ -177,6 +200,7 @@ module.exports = {
|
|
|
177
200
|
COOLDOWN_MS,
|
|
178
201
|
PRICING_URL,
|
|
179
202
|
STATE_FILE,
|
|
203
|
+
upsellUrl,
|
|
180
204
|
STOPPED_PHRASES,
|
|
181
205
|
stoppedPhrase,
|
|
182
206
|
buildLine,
|
|
@@ -277,6 +277,8 @@ async function sendEmail({ to, subject, html, text, from, replyTo, idempotencyKe
|
|
|
277
277
|
console.warn(`[mailer] Resend returned ${res.status}:`, bodyText);
|
|
278
278
|
return { sent: false, reason: 'api_error', status: res.status, body: bodyJson || bodyText };
|
|
279
279
|
}
|
|
280
|
+
// Daily send count for the owner console's delivery cost. A count only: nothing about the message is kept.
|
|
281
|
+
try { require('../cost-meter').recordEmailSend(); } catch { /* best-effort */ }
|
|
280
282
|
return buildSendSuccess({ bodyJson, status: res.status, senderFallback: sender.senderFallback });
|
|
281
283
|
} catch (err) {
|
|
282
284
|
// eslint-disable-next-line no-console
|
package/scripts/owner-admin.js
CHANGED
|
@@ -9,12 +9,14 @@ const ownerTelemetry = require('./owner-telemetry');
|
|
|
9
9
|
const opsLog = require('./ops-log');
|
|
10
10
|
const opsReport = require('./ops-report');
|
|
11
11
|
const ownerAlerts = require('./owner-alerts');
|
|
12
|
+
const costMeter = require('./cost-meter');
|
|
13
|
+
const unitEconomics = require('./unit-economics');
|
|
12
14
|
|
|
13
15
|
const JSON_LIMIT = 8 * 1024 * 1024;
|
|
14
16
|
const LOG_LIMIT = 16 * 1024 * 1024;
|
|
15
17
|
const RESPONSE_LIMIT = 1024 * 1024;
|
|
16
18
|
const RESOURCES = Object.freeze({ customers: 'cus', subscriptions: 'sub', payments: 'ch', refunds: 're', products: 'prod', prices: 'price', 'subscription-items': 'si' });
|
|
17
|
-
const SECTIONS = new Set(['overview', 'money', 'data', 'analytics', 'observability', 'summary', 'alerts']);
|
|
19
|
+
const SECTIONS = new Set(['overview', 'money', 'data', 'analytics', 'observability', 'summary', 'alerts', 'economics']);
|
|
18
20
|
const MONEY_CACHE_MS = 60000;
|
|
19
21
|
let moneyCache = null;
|
|
20
22
|
const PRIVATE_HEADERS = Object.freeze({ 'Cache-Control': 'private, no-store', Vary: 'Cookie', 'X-Robots-Tag': 'noindex, nofollow', 'Referrer-Policy': 'no-referrer', 'X-Content-Type-Options': 'nosniff' });
|
|
@@ -530,7 +532,9 @@ const thumbgateSession = (row) => /thumbgate/i.test(String(row.success_url || ''
|
|
|
530
532
|
// Why a Stripe source failed, in words a person can act on. Never a bare "Unknown".
|
|
531
533
|
function stripeReason(error) {
|
|
532
534
|
if (/STRIPE_SECRET_KEY is missing/i.test(String(error?.message || ''))) return 'Stripe key missing';
|
|
533
|
-
|
|
535
|
+
// The request's own timeout is set to the time left before the shared deadline, so it can fire first: that is the
|
|
536
|
+
// same "no answer in time", not an outage.
|
|
537
|
+
if (error?.code === 'collection_timeout' || error?.code === 'ETIMEDOUT' || /timed? ?out/i.test(String(error?.message || ''))) return 'Stripe did not answer in time';
|
|
534
538
|
if (error?.code === 'provider_busy') return 'Stripe is busy, refresh in a moment';
|
|
535
539
|
return 'Stripe unavailable';
|
|
536
540
|
}
|
|
@@ -542,6 +546,53 @@ const telemetryReason = (error) => (error?.code === 'collection_timeout' ? 'tele
|
|
|
542
546
|
|
|
543
547
|
const trafficFields = (read) => ({ visitors: read.traffic.visitors, realVisitors: read.traffic.realVisitors, botOrInternalVisitors: read.traffic.botOrInternalVisitors, pageViewers: read.traffic.pageViewers, checkoutStartsByType: read.traffic.checkoutStartsByType, sessions: read.traffic.sessions, pageViews: read.traffic.pageViews, ctaClicks: read.traffic.ctaClicks, checkoutStarts: read.traffic.checkoutStarts, checkoutPaidConfirmations: read.traffic.checkoutPaidConfirmations });
|
|
544
548
|
|
|
549
|
+
const attemptSync = (work) => { try { return work(); } catch { return { status: 'unavailable', reason: 'The key store could not be read.' }; } };
|
|
550
|
+
|
|
551
|
+
// Payment to access: every purchase that still grants access should have a ThumbGate key that works, and every working paid
|
|
552
|
+
// key should trace to a payment. Counts only; no customer id or address leaves this function.
|
|
553
|
+
// - `entitled` is who should hold access now: credit-pack buyers (one year) and active subscribers. Service orders and
|
|
554
|
+
// canceled subscriptions grant no key, so they are not expected to have one.
|
|
555
|
+
// - A key works the way billing.validateApiKey() decides: active, and not a credit pack with no credits left. A used-up
|
|
556
|
+
// credit pack was provisioned, so it is counted apart (`exhaustedCreditKeys`), never as a provisioning failure.
|
|
557
|
+
// - A working paid key with no Stripe match is listed for review, not called wrong: GitHub Marketplace, PayPal and manual
|
|
558
|
+
// grants also make keys.
|
|
559
|
+
const isTrialOrFree = (meta) => /free|trial/i.test(String(meta.plan || '') + ' ' + String(meta.tier || '') + ' ' + String(meta.source || ''));
|
|
560
|
+
const creditsExhausted = (meta) => meta.remainingCredits !== undefined && meta.remainingCredits !== null && meta.remainingCredits <= 0;
|
|
561
|
+
function paymentAccessCheck({ entitled, failing, store, complete = true }) {
|
|
562
|
+
const active = Object.values(store?.keys || {}).filter((meta) => meta && meta.active === true);
|
|
563
|
+
const working = active.filter((meta) => !creditsExhausted(meta));
|
|
564
|
+
const owners = (list) => {
|
|
565
|
+
const out = new Set();
|
|
566
|
+
for (const meta of list) {
|
|
567
|
+
if (meta.customerId) out.add(String(meta.customerId));
|
|
568
|
+
if (meta.customerEmail) out.add(String(meta.customerEmail).toLowerCase());
|
|
569
|
+
}
|
|
570
|
+
return out;
|
|
571
|
+
};
|
|
572
|
+
const provisioned = owners(active);
|
|
573
|
+
const withAccess = owners(working);
|
|
574
|
+
const has = (set, who) => set.has(String(who)) || set.has(String(who).toLowerCase());
|
|
575
|
+
const paidKeys = working.filter((meta) => !isTrialOrFree(meta));
|
|
576
|
+
const paidWithoutAccess = [...entitled].filter((who) => !has(provisioned, who)).length;
|
|
577
|
+
const accessWithoutStripePayment = paidKeys.filter((meta) => !entitled.has(String(meta.customerId || '')) && !entitled.has(String(meta.customerEmail || '').toLowerCase())).length;
|
|
578
|
+
const failingIds = Array.isArray(failing) ? failing.map((row) => row.customer).filter(Boolean) : null;
|
|
579
|
+
const failedPaymentWithAccess = failingIds ? failingIds.filter((who) => has(withAccess, who)).length : null;
|
|
580
|
+
const problems = paidWithoutAccess + (failedPaymentWithAccess || 0);
|
|
581
|
+
return {
|
|
582
|
+
status: problems ? 'needs_review' : accessWithoutStripePayment ? 'review' : 'ok',
|
|
583
|
+
complete: complete && failingIds !== null,
|
|
584
|
+
entitledCustomers: entitled.size,
|
|
585
|
+
activeKeys: working.length,
|
|
586
|
+
activePaidKeys: paidKeys.length,
|
|
587
|
+
activeTrialOrFreeKeys: working.length - paidKeys.length,
|
|
588
|
+
exhaustedCreditKeys: active.length - working.length,
|
|
589
|
+
paidWithoutAccess,
|
|
590
|
+
accessWithoutStripePayment,
|
|
591
|
+
failedPaymentSubscriptions: failingIds ? failingIds.length : null,
|
|
592
|
+
failedPaymentWithAccess,
|
|
593
|
+
};
|
|
594
|
+
}
|
|
595
|
+
|
|
545
596
|
// Money board. Each block fails alone: its fields are null and a plain-words reason is returned beside them.
|
|
546
597
|
// Stripe answers paying customers, revenue and checkouts; our own page-view telemetry answers visitors.
|
|
547
598
|
async function collectMoney(deps, signal) {
|
|
@@ -579,7 +630,7 @@ async function collectMoney(deps, signal) {
|
|
|
579
630
|
const paidAndProLane = (async () => {
|
|
580
631
|
const paidResult = await withLastGood('paid', async () => {
|
|
581
632
|
const result = await listIt((params, options) => stripe().checkout.sessions.list(params, options),
|
|
582
|
-
{ status: 'complete', created: { gte: nowSeconds - 365 * 86400 }, expand: ['data.payment_intent.latest_charge'] },
|
|
633
|
+
{ status: 'complete', created: { gte: nowSeconds - 365 * 86400 }, expand: ['data.payment_intent.latest_charge.balance_transaction'] },
|
|
583
634
|
(row) => row.status === 'complete' && thumbgateSession(row), 10);
|
|
584
635
|
// Paid and not refunded in full, owner and test purchases excluded. A partial refund comes off the revenue.
|
|
585
636
|
const charge = (row) => (object(row.payment_intent) && object(row.payment_intent.latest_charge) ? row.payment_intent.latest_charge : null);
|
|
@@ -594,15 +645,27 @@ async function collectMoney(deps, signal) {
|
|
|
594
645
|
const who = id(row.customer) || String(row.customer_details?.email || row.customer_email || row.id).toLowerCase();
|
|
595
646
|
if (!counted.has(who)) { counted.add(who); channel(channelOf(row)).paidCustomers += 1; }
|
|
596
647
|
}
|
|
648
|
+
// Stripe's own fee on each 30-day checkout, read from the charge's balance transaction when Stripe returns it.
|
|
649
|
+
const fees = { reportedFees: {}, unreportedCharges: 0, unreportedAmount: {}, subscriptionFirstCharges: {} };
|
|
597
650
|
for (const row of paid) {
|
|
598
651
|
if (!(row.created >= nowSeconds - 30 * 86400) || !Number.isSafeInteger(row.amount_total) || !/^[a-z]{3}$/i.test(row.currency || '')) continue;
|
|
599
652
|
const code = row.currency.toUpperCase();
|
|
600
653
|
const refunded = Number.isSafeInteger(charge(row)?.amount_refunded) ? charge(row).amount_refunded : 0;
|
|
601
654
|
revenue[code] = (revenue[code] || 0) + row.amount_total - refunded;
|
|
655
|
+
const fee = charge(row)?.balance_transaction?.fee;
|
|
656
|
+
if (Number.isSafeInteger(fee)) {
|
|
657
|
+
const feeCode = String(charge(row).balance_transaction.currency || row.currency).toUpperCase();
|
|
658
|
+
fees.reportedFees[feeCode] = (fees.reportedFees[feeCode] || 0) + fee;
|
|
659
|
+
} else { fees.unreportedCharges += 1; fees.unreportedAmount[code] = (fees.unreportedAmount[code] || 0) + row.amount_total; }
|
|
660
|
+
if (row.mode === 'subscription') fees.subscriptionFirstCharges[code] = (fees.subscriptionFirstCharges[code] || 0) + row.amount_total;
|
|
602
661
|
const byChannel = channel(channelOf(row)).revenue30d;
|
|
603
662
|
byChannel[code] = (byChannel[code] || 0) + row.amount_total - refunded;
|
|
604
663
|
}
|
|
605
|
-
|
|
664
|
+
// Credit-pack buyers keep access for the pack's life; a subscription checkout's access is checked against active
|
|
665
|
+
// subscriptions instead, and a service order grants no key.
|
|
666
|
+
const grant = deps.resolveCheckoutProvisioningGrant || billing._resolveCheckoutProvisioningGrant;
|
|
667
|
+
const creditPackCustomers = new Set(paid.filter((row) => grant(row).kind === 'credit_pack').map((row) => id(row.customer) || String(row.customer_details?.email || row.customer_email || row.id).toLowerCase()));
|
|
668
|
+
return { customers, creditPackCustomers, revenue, channels, fees, complete: result.complete };
|
|
606
669
|
});
|
|
607
670
|
const proResult = await withLastGood('subscriptions', async () => {
|
|
608
671
|
const result = await listIt((params, options) => stripe().subscriptions.list(params, options), { status: 'active', expand: ['data.customer'] }, () => true, 5);
|
|
@@ -630,7 +693,15 @@ async function collectMoney(deps, signal) {
|
|
|
630
693
|
}
|
|
631
694
|
const cancelled = await listIt((params, options) => stripe().subscriptions.list(params, options), { status: 'canceled', expand: ['data.customer'] },
|
|
632
695
|
(row) => Number(row.canceled_at || row.ended_at) >= since30 && !isOwnerEmail(row.customer?.email), 5);
|
|
633
|
-
|
|
696
|
+
// Failed payments: subscriptions Stripe could not charge. Their customer ids feed the payment-to-access check.
|
|
697
|
+
const failing = [];
|
|
698
|
+
let failingComplete = true;
|
|
699
|
+
for (const status of ['past_due', 'unpaid']) {
|
|
700
|
+
const listed = await listIt((params, options) => stripe().subscriptions.list(params, options), { status }, (row) => row.status === status, 2);
|
|
701
|
+
failingComplete &&= listed.complete;
|
|
702
|
+
for (const row of listed.rows) failing.push({ status, customer: id(row.customer) });
|
|
703
|
+
}
|
|
704
|
+
return { renewals, renewalCount: invoices.rows.length, churned: cancelled.rows.length, churnedMrr: monthlyRecurring(cancelled.rows).mrr, failing, complete: invoices.complete && cancelled.complete && failingComplete };
|
|
634
705
|
});
|
|
635
706
|
let paidAndPro; let sessionRun; let trafficRun; let summaryRun; let recurringRun;
|
|
636
707
|
try {
|
|
@@ -685,6 +756,12 @@ async function collectMoney(deps, signal) {
|
|
|
685
756
|
internal: counts.excluded.internal,
|
|
686
757
|
} : null);
|
|
687
758
|
const bothStripe = paid && proRun.value;
|
|
759
|
+
const access = bothStripe ? attemptSync(() => paymentAccessCheck({
|
|
760
|
+
entitled: new Set([...(paid.creditPackCustomers || []), ...proRun.value.customers]),
|
|
761
|
+
failing: recurringRun.ok ? recurringRun.value.failing : null,
|
|
762
|
+
store: (deps.loadKeyStore || billing.loadKeyStore)(),
|
|
763
|
+
complete: paid.complete && proRun.value.complete,
|
|
764
|
+
})) : null;
|
|
688
765
|
// The checkout panel: sessions with no bot check on record come first, then people, bots and owner only for sessions
|
|
689
766
|
// created after the bot check began, then the gap between the site's own start events and Stripe's sessions.
|
|
690
767
|
const checkoutBotCheck = (counts, traffic) => {
|
|
@@ -741,6 +818,7 @@ async function collectMoney(deps, signal) {
|
|
|
741
818
|
renewalInvoices: recurringRun.value.renewalCount,
|
|
742
819
|
churnedSubscriptions: recurringRun.value.churned,
|
|
743
820
|
churnedMrr: recurringRun.value.churnedMrr,
|
|
821
|
+
failedPaymentSubscriptions: recurringRun.value.failing.length,
|
|
744
822
|
churnRate: proRun.value && proRun.value.count + recurringRun.value.churned > 0 ? Math.round((recurringRun.value.churned / (proRun.value.count + recurringRun.value.churned)) * 1000) / 1000 : null,
|
|
745
823
|
complete: recurringRun.value.complete,
|
|
746
824
|
} : null,
|
|
@@ -754,6 +832,8 @@ async function collectMoney(deps, signal) {
|
|
|
754
832
|
weekOverWeek: trafficReason ? null : (trafficRead.weeks || null),
|
|
755
833
|
activeProBasis: proRun.value ? (proRun.value.complete ? 'stripe_active_subscriptions_excluding_owner' : 'stripe_active_subscriptions_first_100_only') : 'unavailable',
|
|
756
834
|
revenueLast30Days: paid ? paid.revenue : null,
|
|
835
|
+
paymentFees30d: paid ? paid.fees : null,
|
|
836
|
+
paymentAccess: access,
|
|
757
837
|
revenueBasis: 'stripe_paid_checkouts_after_refunds',
|
|
758
838
|
checkouts7d: sessionBuckets(sessions?.d7),
|
|
759
839
|
checkouts30d: sessionBuckets(sessions?.d30),
|
|
@@ -820,6 +900,24 @@ async function collectAnalytics(deps, signal) {
|
|
|
820
900
|
return envelope('telemetry_tail_and_billing_summary_30d', data, warnings);
|
|
821
901
|
}
|
|
822
902
|
|
|
903
|
+
// Unit economics: delivery cost per active install and per paying customer, contribution per plan, payment-to-access.
|
|
904
|
+
function economicsFrom(money, deps) {
|
|
905
|
+
const meter = (deps.readCostMeter || ((options) => costMeter.readWindow(options)))({ feedbackDir: deps.feedbackDir, days: 30 });
|
|
906
|
+
return unitEconomics.computeUnitEconomics({ money, usage: money?.usage30d || null, meter, costs: deps.unitCosts || unitEconomics.loadUnitCosts() });
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
async function collectEconomics(deps, signal) {
|
|
910
|
+
const moneyRun = await attempt(() => collectMoney(deps, signal), () => 'Money collection failed');
|
|
911
|
+
const money = moneyRun.ok ? moneyRun.value.data : null;
|
|
912
|
+
const data = economicsFrom(money, deps);
|
|
913
|
+
data.paymentAccess = money?.paymentAccess || null;
|
|
914
|
+
data.firstValue = money?.usage30d ? { activeInstalls30d: money.usage30d.activeInstalls30d, initsInWindow: money.usage30d.initsInWindow, firstValueInstalls: money.usage30d.firstValueInstalls ?? null, timeToFirstValue: money.usage30d.timeToFirstValue || null } : null;
|
|
915
|
+
const warnings = [];
|
|
916
|
+
if (!money) warnings.push('money_unavailable');
|
|
917
|
+
if (data.status !== 'ok') warnings.push('costs_partial');
|
|
918
|
+
return envelope('unit_economics_30d', data, warnings);
|
|
919
|
+
}
|
|
920
|
+
|
|
823
921
|
// One metric of the read-only summary: its value, where it came from, when that source was read, and one of these states:
|
|
824
922
|
// ok a number from a source that answered in full
|
|
825
923
|
// verified_zero a zero from a source that answered in full
|
|
@@ -880,6 +978,14 @@ async function collectSummary(deps, signal) {
|
|
|
880
978
|
add('money.signups_by_source', 'Signups by source', money.leadsBySource?.signups ?? null, leadOpts);
|
|
881
979
|
add('money.workflow_sprint_leads', 'Setup Sprint leads', money.leadsBySource?.workflowSprint ?? null, leadOpts);
|
|
882
980
|
add('money.newsletter', 'Newsletter signups', money.leadsBySource?.newsletter ?? null, leadOpts);
|
|
981
|
+
add('money.payment_access', 'Payment to access check: entitled customers (active subscription or credit pack) without a key, working paid keys without a Stripe payment, failed payments still holding a working key', money.paymentAccess || null, stripeOpts('paid', why.payingCustomers));
|
|
982
|
+
const econ = economicsFrom(money, deps);
|
|
983
|
+
const econOpts = { source: 'cost_meter_and_stripe', collectedAt: refreshed, partial: econ.status !== 'ok', reason: econ.reasons?.hosting || null };
|
|
984
|
+
add('economics.delivery_cost_30d_usd', 'Cost to deliver the service, past 30 days, US dollars (hosting, email, payment fees, fixed)', econ.delivery?.totalUsd ?? null, econOpts);
|
|
985
|
+
add('economics.cost_per_active_install_usd', 'Hosting, email and fixed cost per active CLI install, past 30 days, US dollars', econ.perActiveInstallUsd ?? null, { ...econOpts, reason: econ.reasons?.activeInstalls || econOpts.reason });
|
|
986
|
+
add('economics.cost_per_paying_customer_usd', 'Delivery cost per paying customer, past 30 days, US dollars', econ.perPayingCustomerUsd ?? null, { ...econOpts, reason: econ.reasons?.payingCustomers || econOpts.reason });
|
|
987
|
+
add('economics.contribution_30d', 'Revenue minus delivery cost, past 30 days, US dollars', econ.contribution || null, econOpts);
|
|
988
|
+
add('economics.plans', 'Contribution per sale for each plan, US dollars', econ.plans || null, econOpts);
|
|
883
989
|
}
|
|
884
990
|
const traffic = analytics?.trafficMetrics || money?.traffic30d || null;
|
|
885
991
|
const trafficField = (key, label, name) => add(key, label, traffic ? traffic[name] ?? null : null, trafficOpts);
|
|
@@ -895,6 +1001,8 @@ async function collectSummary(deps, signal) {
|
|
|
895
1001
|
usageField('usage.active_installs_30d', 'CLI installs active in the past 30 days (owner and CI excluded)', 'activeInstalls30d');
|
|
896
1002
|
usageField('usage.activated_installs_30d', 'Active installs that captured feedback (30 days)', 'activatedInstalls');
|
|
897
1003
|
usageField('usage.returning_installs_30d', 'Active installs seen on 2 or more days (30 days)', 'returningInstalls');
|
|
1004
|
+
usageField('usage.first_value_installs_30d', 'Installs whose first real gate block arrived in the past 30 days', 'firstValueInstalls');
|
|
1005
|
+
usageField('usage.time_to_first_value', 'Minutes from install to first real gate block (median and 75th percentile)', 'timeToFirstValue');
|
|
898
1006
|
add('usage.install_cohorts_8w', 'Weekly CLI install cohorts and how many came back each later week (8 weeks)', analytics?.cohorts?.cohorts ?? null, { ...trafficOpts, partial: analytics?.cohorts?.partial === true });
|
|
899
1007
|
if (money) add('money.channels', 'Checkout starts (30 days), paying customers (first paid checkout, 1 year) and revenue (30 days) by channel', money.channels, stripeOpts('paid', why.revenue));
|
|
900
1008
|
add('traffic.week_over_week', 'Past 7 days against the 7 days before', analytics?.weekOverWeek || money?.weekOverWeek || null, trafficOpts);
|
|
@@ -911,7 +1019,9 @@ async function collectSummary(deps, signal) {
|
|
|
911
1019
|
|
|
912
1020
|
// A permanent, stated gap is listed apart so the overall state reflects sources that failed, not a feature not built yet.
|
|
913
1021
|
const knownGaps = [];
|
|
914
|
-
|
|
1022
|
+
// Unit economics are estimates at list rates and start empty until the cost meter has samples, so they never decide the
|
|
1023
|
+
// summary's overall state; each one carries its own status.
|
|
1024
|
+
const states = Object.entries(fields).filter(([key]) => !knownGaps.includes(key) && !key.startsWith('economics.')).map(([, entry]) => entry.status);
|
|
915
1025
|
const bad = states.filter((state) => state === 'unavailable').length;
|
|
916
1026
|
const overall = !money && !analytics ? 'unavailable' : states.every((state) => state === 'ok' || state === 'verified_zero') ? 'ok' : 'partial';
|
|
917
1027
|
return envelope('owner_console_summary', { generatedAt: refreshed, readOnly: true, windows: { checkouts: '7d and 30d', traffic: '30d', revenue: '30d' }, freshness: { displayRefreshedAt: refreshed, stripeCollectedAt: fresh.checkouts?.collectedAt || null, telemetryCollectedAt: fresh.traffic?.collectedAt || null, leadsCollectedAt: fresh.leads?.collectedAt || null, telemetryCacheSeconds: Math.round((deps.telemetryCacheMs ?? TELEMETRY_CACHE_MS) / 1000), billingSummaryCacheSeconds: Math.round(SUMMARY_TTL_MS / 1000) }, fields, knownGaps, unavailableFields: bad }, [], overall);
|
|
@@ -960,7 +1070,7 @@ function postOwnerWebhook(platform, webhookUrl, title, message) {
|
|
|
960
1070
|
}
|
|
961
1071
|
|
|
962
1072
|
// Checks the alerts every 15 minutes and sends the new ones to the channels above. Does nothing when none is set.
|
|
963
|
-
function startAlertDelivery(makeDeps, { intervalMs = 15 * 60 * 1000, send } = {}) {
|
|
1073
|
+
function startAlertDelivery(makeDeps, { intervalMs = 15 * 60 * 1000, firstCheckMs = 60000, send } = {}) {
|
|
964
1074
|
const channels = alertChannels();
|
|
965
1075
|
if (!channels.length && !send) return null;
|
|
966
1076
|
const url = String(process.env.THUMBGATE_OWNER_ALERT_WEBHOOK || '').trim();
|
|
@@ -969,21 +1079,33 @@ function startAlertDelivery(makeDeps, { intervalMs = 15 * 60 * 1000, send } = {}
|
|
|
969
1079
|
if (channels.includes('webhook')) await postOwnerWebhook(platform, url, title, message).catch(() => null);
|
|
970
1080
|
if (channels.includes('email')) {
|
|
971
1081
|
const to = require('./bot-detection').getOwnerEmails();
|
|
972
|
-
|
|
1082
|
+
const sent = to.length ? await require('./mailer/resend-mailer').sendEmail({ to: String(to[0]), subject: title, text: message }).catch(() => null) : null;
|
|
1083
|
+
console.log('[owner-alerts] email ' + (sent && sent.sent !== false ? 'sent' : 'not sent (' + (sent?.reason || (to.length ? 'error' : 'no_owner_address')) + ')'));
|
|
973
1084
|
}
|
|
974
1085
|
});
|
|
975
|
-
|
|
1086
|
+
console.log('[owner-alerts] delivery on: ' + (channels.join(', ') || 'custom'));
|
|
1087
|
+
// State lives on the volume (owner-alert-delivery.json), so a deploy or restart never re-sends an alert that is
|
|
1088
|
+
// still firing. The first check ever also sends one confirmation, so the channel is proven before a real alert needs it.
|
|
1089
|
+
const readState = (deps) => { const read = readObject(deps.feedbackDir, 'owner-alert-delivery.json'); return read.state === 'ok' ? read.value : null; };
|
|
1090
|
+
const writeState = (deps, state) => fs.writeFileSync(path.join(deps.feedbackDir, 'owner-alert-delivery.json'), JSON.stringify(state));
|
|
976
1091
|
const run = async () => {
|
|
977
1092
|
try {
|
|
978
|
-
const
|
|
979
|
-
const
|
|
1093
|
+
const deps = makeDeps();
|
|
1094
|
+
const result = await collectAlerts(deps, AbortSignal.timeout(30000));
|
|
1095
|
+
const firing = result.data.alerts.filter(ownerAlerts.isDeliverable);
|
|
1096
|
+
const state = readState(deps);
|
|
1097
|
+
const before = new Set(Array.isArray(state?.firing) ? state.firing : []);
|
|
1098
|
+
const added = firing.filter((alert) => !before.has(alert.id));
|
|
1099
|
+
writeState(deps, { confirmedAt: state?.confirmedAt || new Date().toISOString(), channels, firing: firing.map((alert) => alert.id), checkedAt: new Date().toISOString() });
|
|
1100
|
+
if (!state?.confirmedAt) await deliver({ title: 'ThumbGate: alert delivery is on', message: 'This is the one-time test that owner alerts reach you. New alerts from thumbgate.ai/admin will arrive here, each once, checked every 15 minutes. Firing right now: ' + firing.length + '.\nhttps://thumbgate.ai/admin' });
|
|
1101
|
+
console.log('[owner-alerts] checked: ' + firing.length + ' firing, ' + added.length + ' new');
|
|
980
1102
|
if (!added.length) return;
|
|
981
1103
|
await deliver(ownerAlerts.formatAlertMessage(added));
|
|
982
1104
|
} catch { /* an alert check never takes the server down */ }
|
|
983
1105
|
};
|
|
984
1106
|
const timer = setInterval(run, intervalMs);
|
|
985
1107
|
timer.unref?.();
|
|
986
|
-
setTimeout(run,
|
|
1108
|
+
setTimeout(run, firstCheckMs).unref?.();
|
|
987
1109
|
return timer;
|
|
988
1110
|
}
|
|
989
1111
|
|
|
@@ -1002,6 +1124,7 @@ async function collectAdminSection(route, deps, externalSignal) {
|
|
|
1002
1124
|
if (route.section === 'money') return collectMoney(deps, controller.signal);
|
|
1003
1125
|
if (route.section === 'summary') return collectSummary(deps, controller.signal);
|
|
1004
1126
|
if (route.section === 'alerts') return collectAlerts(deps, controller.signal);
|
|
1127
|
+
if (route.section === 'economics') return collectEconomics(deps, controller.signal);
|
|
1005
1128
|
if (route.section === 'stripe') return collectStripe(route, deps, controller.signal);
|
|
1006
1129
|
if (route.section === 'data') return collectData(route, deps, controller.signal);
|
|
1007
1130
|
if (route.section === 'observability') return collectObservability(deps, controller.signal);
|
|
@@ -1015,4 +1138,4 @@ async function collectAdminSection(route, deps, externalSignal) {
|
|
|
1015
1138
|
}
|
|
1016
1139
|
}
|
|
1017
1140
|
|
|
1018
|
-
module.exports = { PRIVATE_HEADERS, RESPONSE_LIMIT, monthlyRecurring, collectAlerts, startAlertDelivery,adminPath, parseAdminRoute, readOwnerIdentity, readSessionState, collectMoney, collectAnalytics, collectSummary, summaryParts, collectAdminSection, createRuntimeObservations, githubCommitTitle, collectObservability, projectAnalytics, projectStripe, readObject, countRecords, guardPath };
|
|
1141
|
+
module.exports = { paymentAccessCheck, PRIVATE_HEADERS, RESPONSE_LIMIT, monthlyRecurring, collectAlerts, startAlertDelivery,adminPath, parseAdminRoute, readOwnerIdentity, readSessionState, collectMoney, collectAnalytics, collectSummary, summaryParts, collectAdminSection, createRuntimeObservations, githubCommitTitle, collectObservability, projectAnalytics, projectStripe, readObject, countRecords, guardPath };
|
package/scripts/owner-alerts.js
CHANGED
|
@@ -76,4 +76,9 @@ function createAlertTracker() {
|
|
|
76
76
|
};
|
|
77
77
|
}
|
|
78
78
|
|
|
79
|
-
|
|
79
|
+
// These alerts compare raw event counts that still include our own agents, tests and bots, and installs counted by
|
|
80
|
+
// anonymous id. They stay on the admin page, but are never sent by email or webhook until the counts are filtered.
|
|
81
|
+
const UNFILTERED_COUNT_ALERTS = new Set(['visitors_drop', 'checkout_drop', 'installs_drop', 'activation_low']);
|
|
82
|
+
const isDeliverable = (alert) => alert.level !== 'info' && !UNFILTERED_COUNT_ALERTS.has(alert.id);
|
|
83
|
+
|
|
84
|
+
module.exports = { evaluateAlerts, formatAlertMessage, createAlertTracker, UNFILTERED_COUNT_ALERTS, isDeliverable };
|
|
@@ -107,6 +107,10 @@ const isCli = (entry) => (entry.clientType || entry.client) === 'cli';
|
|
|
107
107
|
const isOwnOrCiInstall = (entry) => isFlagged(entry) || ['owner', 'ci'].includes(String(entry.visitorType || '').toLowerCase());
|
|
108
108
|
// An install counts as activated once it has captured a piece of feedback: that is the first moment ThumbGate does its job.
|
|
109
109
|
const ACTIVATION_EVENT = 'cli_capture';
|
|
110
|
+
// The first value event: a gate really fired and blocked a tool call in the user's own workflow. The CLI sends it once per
|
|
111
|
+
// install with the minutes since install, so time to first value comes from the same ping.
|
|
112
|
+
const FIRST_VALUE_EVENT = 'first_blocked_tool_call';
|
|
113
|
+
const quantile = (sorted, q) => (sorted.length ? sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))] : null);
|
|
110
114
|
const topCounts = (counts, limit = 10) => Object.fromEntries(Object.entries(counts).sort((a, b) => b[1] - a[1]).slice(0, limit));
|
|
111
115
|
|
|
112
116
|
// Visitors, sessions, page views, CTA clicks, checkout starts and paid confirmations, in total and per UTC day.
|
|
@@ -148,10 +152,18 @@ async function readTrafficWindow(options) {
|
|
|
148
152
|
const day = dayOf(time);
|
|
149
153
|
day.activeInstalls.add(install);
|
|
150
154
|
if (week) weeks[week].activeInstalls.add(install);
|
|
151
|
-
const seen = installs.get(install) || { days: new Set(), lastMs: 0, inited: false, activated: false, version: null, platform: null };
|
|
155
|
+
const seen = installs.get(install) || { days: new Set(), lastMs: 0, inited: false, activated: false, firstValue: false, firstValueMinutes: null, version: null, platform: null };
|
|
152
156
|
seen.days.add(day.date);
|
|
153
157
|
seen.inited ||= type === 'cli_init';
|
|
154
158
|
seen.activated ||= type === ACTIVATION_EVENT;
|
|
159
|
+
if (type === FIRST_VALUE_EVENT) {
|
|
160
|
+
seen.firstValue = true;
|
|
161
|
+
// null or a blank means the CLI could not read its install marker: the install still reached first value, but its
|
|
162
|
+
// duration is unknown, so it stays out of the percentiles (Number(null) would count it as zero minutes).
|
|
163
|
+
const raw = entry.minutesSinceInstall;
|
|
164
|
+
const minutes = raw === null || raw === undefined || raw === '' || typeof raw === 'boolean' ? NaN : Number(raw);
|
|
165
|
+
if (Number.isFinite(minutes) && minutes >= 0 && (seen.firstValueMinutes === null || minutes < seen.firstValueMinutes)) seen.firstValueMinutes = minutes;
|
|
166
|
+
}
|
|
155
167
|
if (time >= seen.lastMs) { seen.lastMs = time; seen.version = entry.version || entry.pkgVersion || seen.version; seen.platform = entry.platform || seen.platform; }
|
|
156
168
|
installs.set(install, seen);
|
|
157
169
|
return;
|
|
@@ -180,12 +192,14 @@ async function readTrafficWindow(options) {
|
|
|
180
192
|
const daily = [...days.values()].sort((a, b) => a.date.localeCompare(b.date)).map((day) => ({ date: day.date, visitors: day.visitors.size, pageViewers: day.pageViewers.size, sessions: day.sessions.size, activeInstalls: day.activeInstalls.size, pageViews: day.pageViews, ctaClicks: day.ctaClicks, checkoutStarts: day.checkoutStarts, checkoutPaidConfirmations: day.checkoutPaidConfirmations }));
|
|
181
193
|
const byVersion = {};
|
|
182
194
|
const byPlatform = {};
|
|
183
|
-
let newInstalls = 0; let activated = 0; let returning = 0; let active7 = 0;
|
|
195
|
+
let newInstalls = 0; let activated = 0; let returning = 0; let active7 = 0; let firstValue = 0;
|
|
196
|
+
const firstValueMinutes = [];
|
|
184
197
|
for (const seen of installs.values()) {
|
|
185
198
|
byVersion[seen.version || 'unknown'] = (byVersion[seen.version || 'unknown'] || 0) + 1;
|
|
186
199
|
byPlatform[seen.platform || 'unknown'] = (byPlatform[seen.platform || 'unknown'] || 0) + 1;
|
|
187
200
|
if (seen.inited) newInstalls += 1;
|
|
188
201
|
if (seen.activated) activated += 1;
|
|
202
|
+
if (seen.firstValue) { firstValue += 1; if (seen.firstValueMinutes !== null) firstValueMinutes.push(seen.firstValueMinutes); }
|
|
189
203
|
if (seen.days.size >= 2) returning += 1;
|
|
190
204
|
if (seen.lastMs >= nowMs - 7 * DAY_MS) active7 += 1;
|
|
191
205
|
}
|
|
@@ -199,6 +213,12 @@ async function readTrafficWindow(options) {
|
|
|
199
213
|
initsInWindow: newInstalls,
|
|
200
214
|
activatedInstalls: activated,
|
|
201
215
|
returningInstalls: returning,
|
|
216
|
+
// Installs whose first real gate block arrived in the window, and how long after install it came.
|
|
217
|
+
firstValueInstalls: firstValue,
|
|
218
|
+
timeToFirstValue: (() => {
|
|
219
|
+
const sorted = firstValueMinutes.sort((a, b) => a - b);
|
|
220
|
+
return { installs: sorted.length, medianMinutes: quantile(sorted, 0.5), p75Minutes: quantile(sorted, 0.75) };
|
|
221
|
+
})(),
|
|
202
222
|
excludedInstalls: excludedInstalls.size,
|
|
203
223
|
eventsByType: topCounts(cliEvents, 20),
|
|
204
224
|
byVersion: topCounts(byVersion),
|