An open-source, faster Devin alternative
TypeScript
api-edge: signup and revenue alerts in #signups (work 090)
utpal nadiger via Computer01ca911a76b5
diff --git a/cloudflare-workers/api-edge/migrations/0023_slack_alerts.sql b/cloudflare-workers/api-edge/migrations/0023_slack_alerts.sqlnew file mode 100644index 00000000..ba5d0c4a--- /dev/null+++ b/cloudflare-workers/api-edge/migrations/0023_slack_alerts.sql@@ -0,0 +1,13 @@+-- slack_alerts (serverless-agents-ws 090): one row per customer alert posted to+-- our own Slack (#signups), so webhook retries, concurrent projections and cron+-- re-runs post each one once. The INSERT OR IGNORE that writes the row is the+-- claim; a failed post deletes it so a later run can try again. `key` tells+-- repeatable events apart (an invitation id, a plan move and its day); events+-- that happen once per org use ''.+CREATE TABLE IF NOT EXISTS slack_alerts (+ org_id TEXT NOT NULL,+ event TEXT NOT NULL,+ key TEXT NOT NULL,+ sent_at INTEGER NOT NULL,+ PRIMARY KEY (org_id, event, key)+);diff --git a/cloudflare-workers/api-edge/src/autumn_webhook.ts b/cloudflare-workers/api-edge/src/autumn_webhook.tsindex c59b55cd..bd266415 100644--- a/cloudflare-workers/api-edge/src/autumn_webhook.ts+++ b/cloudflare-workers/api-edge/src/autumn_webhook.ts@@ -20,6 +20,7 @@import { emitBillingEvent, type BillingEventName, type BillingEventsEnv } from "./billing_events";import { notifyTrialEvent, syncLoopsPlan, trialReason, type LoopsEnv } from "./loops";+import { sendSlackAlert, trialEndedAlert } from "./slack_alerts";// AutumnApiEnv is the minimal binding set for calling Autumn's REST API// (GetCustomer / checkout). The dashboard handlers satisfy this without the@@ -891,7 +892,10 @@ export async function syncAutumnToD1(env: AutumnSyncEnv, orgID: string): Promiseconst lowReason = trialReason(warning);if (lowReason && !trialReason(prevRow?.billing_warning)) await notifyTrialEvent(env, orgID, "trial_low", lowReason);const endReason = trialReason(reason);- if (endReason && !wasHalted) await notifyTrialEvent(env, orgID, "trial_ended", endReason);+ if (endReason && !wasHalted) {+ await notifyTrialEvent(env, orgID, "trial_ended", endReason);+ await sendSlackAlert(env, trialEndedAlert(orgID, endReason));+ }if (planChange) await syncLoopsPlan(env, orgID, usagePlan);return { customer: cust, creditsRemaining, maxConcurrent, halted, haltReason: reason, warning, wasHalted, usagePlan };diff --git a/cloudflare-workers/api-edge/src/billing_events.ts b/cloudflare-workers/api-edge/src/billing_events.tsindex 82311357..71d4555e 100644--- a/cloudflare-workers/api-edge/src/billing_events.ts+++ b/cloudflare-workers/api-edge/src/billing_events.ts@@ -8,11 +8,13 @@// never retries; one attempt per sink, bounded, so a billing path can await it.//// Data policy (work 054): ids and scalars only, never emails or amounts tied-// to a card.+// to a card. The same call also feeds our own Slack (slack_alerts.ts, work+// 090), which looks the owner's email up for that message only.import { edgeTelemetryEnabled, tbTime, uuidv7, type EdgeTelemetryEnv } from "./computer_telemetry";+import { slackAlertForBillingEvent, type SlackAlertsEnv } from "./slack_alerts";-export interface BillingEventsEnv extends EdgeTelemetryEnv {+export interface BillingEventsEnv extends EdgeTelemetryEnv, SlackAlertsEnv {POSTHOG_PROJECT_TOKEN?: string;POSTHOG_HOST?: string;}@@ -112,6 +114,7 @@ export async function emitBillingEvent(),);}+ sends.push(slackAlertForBillingEvent(env, name, event.orgId, event.data));} catch {// Telemetry never fails the billing path.}diff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.tsindex 9d9627e1..f609e958 100644--- a/cloudflare-workers/api-edge/src/dashboard.ts+++ b/cloudflare-workers/api-edge/src/dashboard.ts@@ -46,6 +46,7 @@ import { computerEnabledFor } from "./computer";import { enableManagedBilling } from "./model_billing";import { paywallContext } from "./billing_onramp";import { insufficientManagedAgentCredits } from "./managed_agent_credit_gate";+import { sendSlackAlert, teammateInvitedAlert } from "./slack_alerts";export interface DashboardEnv extends BillingEventsEnv {/** Computer rollout (work 052): see computerEnabledFor in computer.ts. */@@ -602,6 +603,7 @@ async function handleSendInvitation(req: Request, env: DashboardEnv, caller: Cal`INSERT INTO invitations (id, org_id, email, role, invited_by, workos_invitation_id, status, expires_at, created_at)VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'pending', ?7, ?8)`,).bind(id, caller.orgID, email, role, caller.userID, workosInviteID, now + 7 * 86400, now).run();+ await sendSlackAlert(env, teammateInvitedAlert(caller.orgID, email));return json({ id, email, role, status: "pending", workos_invitation_id: workosInviteID, expires_at: now + 7 * 86400 }, 201);}diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex b8e8a6f3..53e8fe8c 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -73,6 +73,7 @@ import {import { runAutumnMeter } from "./autumn_meter";import { runBillingClock } from "./billing_clock";import { runSlackConnectInvites } from "./slack_connect";+import { runActivationAlerts } from "./slack_alerts";import { disableManagedBilling, enableManagedBilling } from "./model_billing";import { runModelMeter, syncModelCaps } from "./model_meter";import {@@ -6402,6 +6403,11 @@ export default {ctx.waitUntil(runSlackConnectInvites(env, Date.now()).catch((err) => console.error("slack-connect: run failed", err)),);+ // First agent session per org into #signups (work 090). Dormant unless+ // SERVERLESS_AGENTS_DB, SLACK_CONNECT_TOKEN and a channel are set.+ ctx.waitUntil(+ runActivationAlerts(env, Date.now()).catch((err) => console.error("slack-alerts: activation run failed", err)),+ );if (!env.AUTUMN_SECRET_KEY) return;ctx.waitUntil(runAutumnMeter(env, Date.now()).catch((err) => console.error("autumn-meter: run failed", err)),diff --git a/cloudflare-workers/api-edge/src/slack_alerts.test.ts b/cloudflare-workers/api-edge/src/slack_alerts.test.tsnew file mode 100644index 00000000..59d5bbb4--- /dev/null+++ b/cloudflare-workers/api-edge/src/slack_alerts.test.ts@@ -0,0 +1,267 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { emitBillingEvent } from "./billing_events";+import {+ alertChannel,+ alertForBillingEvent,+ runActivationAlerts,+ sendSlackAlert,+ teammateInvitedAlert,+ trialEndedAlert,+ type Alert,+} from "./slack_alerts";++// The SQL runs against the real schema (snapshot plus migrations) in node:sqlite,+// as in slack_connect.test.ts; this shim also reports meta.changes, which the+// claim depends on.+interface SqliteStatement {+ get(...params: unknown[]): unknown;+ all(...params: unknown[]): unknown[];+ run(...params: unknown[]): { changes: number | bigint };+}+interface DatabaseSync {+ exec(sql: string): void;+ prepare(sql: string): SqliteStatement;+}+declare const process: { cwd(): string; getBuiltinModule(id: string): unknown };+const { DatabaseSync } = process.getBuiltinModule("node:sqlite") as { DatabaseSync: new (path: string) => DatabaseSync };+const fs = process.getBuiltinModule("node:fs") as {+ readFileSync(path: string, enc: "utf8"): string;+ readdirSync(path: string): string[];+};++class Stmt {+ private params: unknown[] = [];+ constructor(private db: DatabaseSync, private sql: string) {}+ bind(...p: unknown[]): this {+ this.params = p.map((v) => (v === undefined ? null : v));+ return this;+ }+ async first<T>(): Promise<T | null> {+ return (this.db.prepare(this.sql).get(...this.params) as T | undefined) ?? null;+ }+ async all<T>(): Promise<{ results: T[] }> {+ return { results: this.db.prepare(this.sql).all(...this.params) as T[] };+ }+ async run(): Promise<{ success: true; meta: { changes: number } }> {+ const r = this.db.prepare(this.sql).run(...this.params);+ return { success: true, meta: { changes: Number(r.changes) } };+ }+}++function d1(db: DatabaseSync): D1Database {+ return { prepare: (sql: string) => new Stmt(db, sql) } as unknown as D1Database;+}++function schemaDB(): DatabaseSync {+ const db = new DatabaseSync(":memory:");+ const root = process.cwd();+ db.exec(fs.readFileSync(`${root}/schema-snapshots/current_schema.sql`, "utf8"));+ for (const file of fs.readdirSync(`${root}/migrations`).filter((f) => f.endsWith(".sql")).sort()) {+ const sql = fs.readFileSync(`${root}/migrations/${file}`, "utf8").replace(/^\s*--.*$/gm, "");+ for (const statement of sql.split(/;\s*$/m).filter((s) => s.trim())) {+ try {+ db.exec(statement);+ } catch (err) {+ if (!/already exists|duplicate column/.test(String(err))) throw err;+ }+ }+ }+ return db;+}++// blue's migrations 0001 + 0004.+function sessionsDB(): DatabaseSync {+ const db = new DatabaseSync(":memory:");+ db.exec(`CREATE TABLE session_creations (+ session_id TEXT PRIMARY KEY, account_id TEXT NOT NULL, source TEXT NOT NULL, created_at TEXT NOT NULL,+ countable INTEGER NOT NULL DEFAULT 1, exclusion_reason TEXT, outcome_at TEXT)`);+ return db;+}++const NOW = Date.parse("2026-10-28T12:00:00Z");+let seq = 0;++function addOrg(+ db: DatabaseSync,+ email: string,+ opts: { name?: string; plan?: string; attribution?: Record<string, string> } = {},+): string {+ const n = ++seq;+ const userID = `user-${n}`;+ const orgID = `org-${n}`;+ db.prepare(`INSERT INTO users (id, email, created_at) VALUES (?, ?, 0)`).run(userID, email);+ db.prepare(+ `INSERT INTO orgs (id, name, slug, plan, home_cell, owner_user_id, created_at, updated_at, usage_plan)+ VALUES (?, ?, ?, 'free', 'c', ?, 0, 0, ?)`,+ ).run(orgID, opts.name ?? `${email}'s workspace`, `slug-${n}`, userID, opts.plan ?? "base");+ if (opts.attribution) {+ const a = { channel: "unknown", client: "web", ...opts.attribution };+ const cols = Object.keys(a);+ db.prepare(+ `INSERT INTO signup_attribution (user_id, created_at, ${cols.join(", ")}) VALUES (?, 0, ${cols.map(() => "?").join(", ")})`,+ ).run(userID, ...Object.values(a));+ }+ return orgID;+}++function slack(fail = false) {+ const posts: Array<{ channel: string; text: string }> = [];+ const fetchImpl = (async (_url: string, init: RequestInit) => {+ const body = JSON.parse(String(init.body));+ if (fail) return new Response(JSON.stringify({ ok: false, error: "not_in_channel" }), { status: 200 });+ posts.push({ channel: body.channel, text: body.text });+ return new Response(JSON.stringify({ ok: true }), { status: 200 });+ }) as unknown as typeof fetch;+ return { posts, fetchImpl };+}++function env(db: DatabaseSync, extra: Record<string, unknown> = {}) {+ return { OPENCOMPUTER_DB: d1(db), SLACK_CONNECT_TOKEN: "xoxb-test", SIGNUPS_SLACK_CHANNEL: "#signups", ...extra };+}++describe("billing-event alerts", () => {+ it("posts a work-email trial start once, with its attribution", async () => {+ const db = schemaDB();+ const org = addOrg(db, "[email protected]", {+ name: "Acme",+ attribution: {+ channel: "google_ads",+ utm_campaign: "launch-oct",+ auth_method: "GitHubOAuth",+ plan_intent: "pro",+ },+ });+ const { posts, fetchImpl } = slack();+ const alert = alertForBillingEvent({}, "billing.trial_started", org, {}, NOW)!;+ expect(await sendSlackAlert(env(db), alert, fetchImpl, NOW)).toBe(true);+ // A replayed webhook or a concurrent projection posts nothing.+ expect(await sendSlackAlert(env(db), alert, fetchImpl, NOW)).toBe(false);+ expect(posts).toEqual([+ {+ channel: "#signups",+ text: "🟢 [email protected] started a trial · Acme · Google Ads / launch-oct · GitHub login · clicked Pro",+ },+ ]);+ });++ it("skips free-email trial starts and every internal account", async () => {+ const db = schemaDB();+ const { posts, fetchImpl } = slack();+ const free = addOrg(db, "[email protected]");+ const staff = addOrg(db, "[email protected]");+ const staffGmail = addOrg(db, "[email protected]");+ for (const org of [free, staff, staffGmail]) {+ await sendSlackAlert(env(db), alertForBillingEvent({}, "billing.trial_started", org, {}, NOW)!, fetchImpl, NOW);+ }+ await sendSlackAlert(env(db), trialEndedAlert(staff, "days"), fetchImpl, NOW);+ expect(posts).toEqual([]);+ // A free-email account still alerts on everything after the trial start.+ await sendSlackAlert(env(db), trialEndedAlert(free, "minutes"), fetchImpl, NOW);+ expect(posts.map((p) => p.text)).toEqual(["⏹️ [email protected] ended their trial unpaid · trial · out of work minutes"]);+ });++ it("renders each revenue event", async () => {+ const db = schemaDB();+ const org = addOrg(db, "[email protected]", { name: "Globex", plan: "pro", attribution: { channel: "referral", referrer: "https://news.ycombinator.com/item" } });+ const { posts, fetchImpl } = slack();+ const events: Array<[string, Record<string, string | number | boolean | null>]> = [+ ["billing.plan_changed", { from: "base", to: "pro", kind: "trial_converted" }],+ ["billing.plan_changed", { from: "pro", to: "max", kind: "upgrade" }],+ ["billing.plan_changed", { from: "max", to: "pro", kind: "downgrade" }],+ ["billing.plan_changed", { from: "pro", to: "base", kind: "cancel" }],+ ["billing.plan_changed", { from: "pro", to: "base", kind: "lapsed" }],+ ["billing.payment_failed", { plan: "pro" }],+ ["billing.payment_recovered", { plan: "pro" }],+ ["billing.payment_failed", { plan: "top_up", reason: "card_declined" }],+ ["billing.credits_purchased", { amount: 99, auto: false }],+ ["billing.credits_purchased", { amount: 250, auto: true }],+ ["billing.work_minutes_recorded", { minutes: 3 }],+ ];+ for (const [name, data] of events) {+ const alert = alertForBillingEvent({}, name, org, data, NOW);+ if (alert) await sendSlackAlert(env(db), alert, fetchImpl, NOW);+ }+ await sendSlackAlert(env(db), teammateInvitedAlert(org, "[email protected]"), fetchImpl, NOW);+ await sendSlackAlert(env(db), teammateInvitedAlert(org, "[email protected]"), fetchImpl, NOW);+ const ctx = "Globex · Pro · Referral (news.ycombinator.com)";+ expect(posts.map((p) => p.text)).toEqual([+ `💰 [email protected] converted to Pro · ${ctx}`,+ `📈 [email protected] upgraded Pro → Max · ${ctx}`,+ `📉 [email protected] downgraded Max → Pro · ${ctx}`,+ `📉 [email protected] cancelled Pro · ${ctx}`,+ // Same transition and day as the cancel: one post.+ `🔴 [email protected] had a payment fail · ${ctx}`,+ `✅ [email protected] recovered a failed payment · ${ctx}`,+ `🔴 [email protected] had an auto top-up payment fail · ${ctx} · card_declined`,+ `💳 [email protected] bought $250 of credits (auto top-up) · ${ctx}`,+ `👥 [email protected] invited [email protected] · ${ctx}`,+ ]);+ });++ it("routes a kind to its own channel", () => {+ const e = { SIGNUPS_SLACK_CHANNEL: "#signups", SLACK_ALERT_CHANNELS: "payment_failed=C0REV, converted = C0REV" };+ expect(alertChannel(e, "payment_failed")).toBe("C0REV");+ expect(alertChannel(e, "converted")).toBe("C0REV");+ expect(alertChannel(e, "trial_started")).toBe("#signups");+ expect(alertChannel({}, "trial_started")).toBeNull();+ });++ it("releases the claim when Slack refuses, so a retry posts", async () => {+ const db = schemaDB();+ const org = addOrg(db, "[email protected]");+ const alert: Alert = trialEndedAlert(org, "tokens");+ expect(await sendSlackAlert(env(db), alert, slack(true).fetchImpl, NOW)).toBe(false);+ const { posts, fetchImpl } = slack();+ expect(await sendSlackAlert(env(db), alert, fetchImpl, NOW)).toBe(true);+ expect(posts).toHaveLength(1);+ });++ it("is dormant without a token or channel", async () => {+ const db = schemaDB();+ const org = addOrg(db, "[email protected]");+ const { posts, fetchImpl } = slack();+ await sendSlackAlert(env(db, { SLACK_CONNECT_TOKEN: undefined }), trialEndedAlert(org, "days"), fetchImpl, NOW);+ await sendSlackAlert(env(db, { SIGNUPS_SLACK_CHANNEL: undefined }), trialEndedAlert(org, "days"), fetchImpl, NOW);+ expect(posts).toEqual([]);+ });+});++describe("emitBillingEvent", () => {+ afterEach(() => vi.unstubAllGlobals());++ it("feeds the Slack sink alongside the analytics sinks", async () => {+ const db = schemaDB();+ const org = addOrg(db, "[email protected]", { name: "Hooli" });+ const { posts, fetchImpl } = slack();+ vi.stubGlobal("fetch", fetchImpl);+ await emitBillingEvent(env(db), "billing.trial_started", { orgId: org, userId: "u", data: { via: "web" } });+ expect(posts.map((p) => p.text)).toEqual(["🟢 [email protected] started a trial · Hooli"]);+ });+});++describe("activation alerts", () => {+ it("posts each org's first agent session once, never an older customer's", async () => {+ const db = schemaDB();+ const sessions = sessionsDB();+ const fresh = addOrg(db, "[email protected]");+ const old = addOrg(db, "[email protected]");+ const staff = addOrg(db, "[email protected]");+ const add = sessions.prepare(`INSERT INTO session_creations (session_id, account_id, source, created_at, countable) VALUES (?, ?, ?, ?, ?)`);+ add.run("s0", fresh, "api", "2026-10-28T11:40:00.000Z", 0); // not countable: does not activate+ add.run("s1", fresh, "playground", "2026-10-28T11:50:00.000Z", 1);+ add.run("s2", fresh, "api", "2026-10-28T11:55:00.000Z", 1);+ add.run("s3", old, "api", "2026-10-20T09:00:00.000Z", 1);+ add.run("s4", old, "schedule", "2026-10-28T11:58:00.000Z", 1);+ add.run("s5", staff, "api", "2026-10-28T11:58:00.000Z", 1);+ const { posts, fetchImpl } = slack();+ const e = env(db, { SERVERLESS_AGENTS_DB: d1(sessions) });+ expect(await runActivationAlerts(e, NOW, fetchImpl)).toBe(1);+ expect(await runActivationAlerts(e, NOW + 300_000, fetchImpl)).toBe(0);+ expect(posts.map((p) => p.text)).toEqual(["🚀 [email protected] ran their first agent session · trial · via playground"]);+ });++ it("is dormant without the session index", async () => {+ const db = schemaDB();+ expect(await runActivationAlerts(env(db), NOW, slack().fetchImpl)).toBe(0);+ });+});diff --git a/cloudflare-workers/api-edge/src/slack_alerts.ts b/cloudflare-workers/api-edge/src/slack_alerts.tsnew file mode 100644index 00000000..903005ce--- /dev/null+++ b/cloudflare-workers/api-edge/src/slack_alerts.ts@@ -0,0 +1,361 @@+// Customer alerts in our own Slack (serverless-agents-ws 090): trial starts,+// first agent session, conversions, trial ends, payment trouble, plan moves,+// large credit purchases and teammate invites, one line each in #signups.+//+// Posted by the OpenComputer Slack app (089's SLACK_CONNECT_TOKEN, with+// chat:write and a member of the channel). SIGNUPS_SLACK_CHANNEL is the default+// destination; SLACK_ALERT_CHANNELS overrides it per alert kind+// (`payment_failed=C123,converted=C123`), so revenue alerts can move to their+// own channel without a deploy. Dormant unless the token and a channel are set.+//+// Unlike the billing events (work 054) the message carries the owner's email:+// it is looked up here, for Slack only. Internal accounts never alert;+// free-email accounts skip trial_started and first show up when they activate.+// Both lists are slack_connect.ts's, shared with 089.+//+// Each alert is claimed once in slack_alerts before it is posted. One bounded+// attempt; never throws, so a billing or login path can await it.++import { isFreeEmail, isInternalEmail } from "./slack_connect";++// The settings; OPENCOMPUTER_DB comes from the caller's env (AlertsDBEnv), kept+// out of here so env interfaces that require it can still extend this one.+export interface SlackAlertsEnv {+ // The managed-agent session index (blue's session_creations), read-only.+ SERVERLESS_AGENTS_DB?: D1Database;+ SLACK_CONNECT_TOKEN?: string;+ SIGNUPS_SLACK_CHANNEL?: string;+ SLACK_ALERT_CHANNELS?: string;+ SLACK_ALERT_CREDITS_MIN?: string; // dollars (1 credit = $1); default 100+}++type AlertsDBEnv = SlackAlertsEnv & { OPENCOMPUTER_DB?: D1Database };++export type AlertKind =+ | "trial_started"+ | "activated"+ | "converted"+ | "upgraded"+ | "downgraded"+ | "trial_ended"+ | "payment_failed"+ | "payment_recovered"+ | "credits_purchased"+ | "teammate_invited";++export interface Alert {+ kind: AlertKind;+ orgId: string;+ // Tells repeated alerts of one kind apart; '' for once per org.+ key: string;+ // What happened, after the email: "started a trial".+ what: string;+ // Extra context parts, after the org's own.+ extra?: string[];+}++// One emoji per kind, so the channel scans by color.+const EMOJI: Record<AlertKind, string> = {+ trial_started: "🟢",+ activated: "🚀",+ converted: "💰",+ upgraded: "📈",+ downgraded: "📉",+ trial_ended: "⏹️",+ payment_failed: "🔴",+ payment_recovered: "✅",+ credits_purchased: "💳",+ teammate_invited: "👥",+};++const POST_TIMEOUT_MS = 2_000;+const DEFAULT_CREDITS_MIN = 100;+// Activation looks back this far each */5 tick, so a failed post or a missed+// tick is retried; the slack_alerts claim keeps it to one post.+const ACTIVATION_LOOKBACK_SEC = 3_600;+const MAX_ACTIVATIONS_PER_RUN = 20;++const PLAN_LABEL: Record<string, string> = { base: "trial", pro: "Pro", max: "Max", top_up: "auto top-up" };+const CHANNEL_LABEL: Record<string, string> = {+ google_ads: "Google Ads",+ other_paid: "Paid ads",+ organic_search: "Organic search",+ social: "Social",+ referral: "Referral",+ direct: "Direct",+};+const AUTH_LABEL: Record<string, string> = {+ GoogleOAuth: "Google login",+ GitHubOAuth: "GitHub login",+ MicrosoftOAuth: "Microsoft login",+ Password: "password login",+ MagicAuth: "magic link",+ SSO: "SSO",+};+const TRIAL_END_REASON: Record<string, string> = {+ days: "3 days up",+ minutes: "out of work minutes",+ tokens: "out of model tokens",+};++function planLabel(plan: unknown): string {+ return PLAN_LABEL[String(plan)] ?? String(plan);+}++function today(nowMs: number): string {+ return new Date(nowMs).toISOString().slice(0, 10);+}++/**+ * The alert for one billing event, or null when it is not one we post. Plan+ * moves are claimed per transition and day: the projection's compare-and-set+ * already emits each move once, the key only absorbs a replay.+ */+export function alertForBillingEvent(+ env: SlackAlertsEnv,+ name: string,+ orgId: string,+ data: Record<string, string | number | boolean | null>,+ nowMs = Date.now(),+): Alert | null {+ const day = today(nowMs);+ switch (name) {+ case "billing.trial_started":+ return { kind: "trial_started", orgId, key: "", what: "started a trial" };+ case "billing.plan_changed": {+ const from = planLabel(data.from);+ const to = planLabel(data.to);+ const key = `${data.from}:${data.to}:${day}`;+ switch (data.kind) {+ case "trial_converted":+ return { kind: "converted", orgId, key, what: `converted to ${to}` };+ case "upgrade":+ return { kind: "upgraded", orgId, key, what: `upgraded ${from} → ${to}` };+ case "downgrade":+ return { kind: "downgraded", orgId, key, what: `downgraded ${from} → ${to}` };+ case "cancel":+ return { kind: "downgraded", orgId, key, what: `cancelled ${from}` };+ case "lapsed":+ return { kind: "downgraded", orgId, key, what: `lapsed off ${from} after a failed payment` };+ default:+ return null;+ }+ }+ case "billing.payment_failed":+ return {+ kind: "payment_failed",+ orgId,+ key: `${data.plan}:${day}`,+ what: data.plan === "top_up" ? "had an auto top-up payment fail" : "had a payment fail",+ extra: data.reason ? [String(data.reason)] : [],+ };+ case "billing.payment_recovered":+ return { kind: "payment_recovered", orgId, key: `${data.plan}:${day}`, what: "recovered a failed payment" };+ case "billing.credits_purchased": {+ const amount = Number(data.amount);+ const min = Number(env.SLACK_ALERT_CREDITS_MIN) || DEFAULT_CREDITS_MIN;+ if (!Number.isFinite(amount) || amount < min) return null;+ return {+ kind: "credits_purchased",+ orgId,+ key: `${amount}:${data.auto ? "auto" : "manual"}:${Math.floor(nowMs / 60_000)}`,+ what: `bought $${amount} of credits${data.auto ? " (auto top-up)" : ""}`,+ };+ }+ default:+ return null;+ }+}++export function trialEndedAlert(orgId: string, reason: "days" | "minutes" | "tokens"): Alert {+ return { kind: "trial_ended", orgId, key: "", what: "ended their trial unpaid", extra: [TRIAL_END_REASON[reason]] };+}++// Keyed by the invitee, so a revoke and re-invite does not post twice.+export function teammateInvitedAlert(orgId: string, inviteeEmail: string): Alert {+ return { kind: "teammate_invited", orgId, key: inviteeEmail, what: `invited ${inviteeEmail}` };+}++/** The channel an alert kind posts to, or null when alerts are off. */+export function alertChannel(env: SlackAlertsEnv, kind: AlertKind): string | null {+ for (const entry of (env.SLACK_ALERT_CHANNELS ?? "").split(",")) {+ const [k, channel] = entry.split("=").map((s) => s.trim());+ if (k === kind && channel) return channel;+ }+ return env.SIGNUPS_SLACK_CHANNEL?.trim() || null;+}++interface OrgContext {+ email: string;+ org_name: string;+ usage_plan: string | null;+ channel: string | null;+ utm_campaign: string | null;+ referrer: string | null;+ client: string | null;+ auth_method: string | null;+ plan_intent: string | null;+}++async function orgContext(db: D1Database, orgId: string): Promise<OrgContext | null> {+ return db+ .prepare(+ `SELECT u.email, o.name AS org_name, o.usage_plan, a.channel, a.utm_campaign, a.referrer,+ a.client, a.auth_method, a.plan_intent+ FROM orgs o+ JOIN users u ON u.id = o.owner_user_id+ LEFT JOIN signup_attribution a ON a.user_id = u.id+ WHERE o.id = ?1`,+ )+ .bind(orgId)+ .first<OrgContext>();+}++/** The Slack line: `🟢 [email protected] started a trial · Acme · Google Ads / launch-oct · …`. */+export function alertText(alert: Alert, c: OrgContext): string {+ const parts: string[] = [];+ // A personal org keeps the signup default, which only repeats the email.+ if (c.org_name && c.org_name !== `${c.email}'s workspace`) parts.push(c.org_name);+ if (alert.kind !== "trial_started" && c.usage_plan) parts.push(planLabel(c.usage_plan));+ const source = sourceLabel(c);+ if (source) parts.push(source);+ if (alert.kind === "trial_started") {+ if (c.client === "cli") parts.push("CLI");+ if (c.auth_method) parts.push(AUTH_LABEL[c.auth_method] ?? c.auth_method);+ if (c.plan_intent) parts.push(`clicked ${planLabel(c.plan_intent)}`);+ }+ parts.push(...(alert.extra ?? []));+ return [`${EMOJI[alert.kind]} ${c.email} ${alert.what}`, ...parts].join(" · ");+}++function sourceLabel(c: OrgContext): string | null {+ if (!c.channel || c.channel === "unknown") return null;+ let label = CHANNEL_LABEL[c.channel] ?? c.channel;+ if (c.channel === "referral" && c.referrer) {+ try {+ label += ` (${new URL(c.referrer.includes("://") ? c.referrer : `https://${c.referrer}`).hostname})`;+ } catch {+ // A referrer that is not a URL adds nothing.+ }+ }+ return c.utm_campaign ? `${label} / ${c.utm_campaign}` : label;+}++/**+ * Posts one alert unless it is filtered or already sent. Returns whether it+ * posted. Never throws.+ */+export async function sendSlackAlert(+ env: AlertsDBEnv,+ alert: Alert,+ fetchImpl: typeof fetch = fetch,+ nowMs = Date.now(),+): Promise<boolean> {+ const db = env.OPENCOMPUTER_DB;+ const token = env.SLACK_CONNECT_TOKEN?.trim();+ const channel = alertChannel(env, alert.kind);+ if (!db || !token || !channel) return false;+ try {+ const c = await orgContext(db, alert.orgId);+ if (!c?.email || isInternalEmail(c.email)) return false;+ if (alert.kind === "trial_started" && isFreeEmail(c.email)) return false;++ const claimed = await db+ .prepare(`INSERT OR IGNORE INTO slack_alerts (org_id, event, key, sent_at) VALUES (?1, ?2, ?3, ?4)`)+ .bind(alert.orgId, alert.kind, alert.key, Math.floor(nowMs / 1000))+ .run();+ if (claimed.meta?.changes !== 1) return false;++ let error: string | null = null;+ try {+ const res = await fetchImpl("https://slack.com/api/chat.postMessage", {+ method: "POST",+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json; charset=utf-8" },+ body: JSON.stringify({ channel, text: alertText(alert, c), unfurl_links: false, unfurl_media: false }),+ signal: AbortSignal.timeout(POST_TIMEOUT_MS),+ });+ const body = res.ok ? ((await res.json()) as { ok?: boolean; error?: string }) : null;+ if (!body?.ok) error = body?.error ?? `http_${res.status}`;+ } catch (err) {+ error = err instanceof Error ? err.name : "error";+ }+ if (error) {+ // Release the claim: the cron retries activation; a webhook-driven alert+ // is posted by a later replay, if any.+ await db+ .prepare(`DELETE FROM slack_alerts WHERE org_id = ?1 AND event = ?2 AND key = ?3`)+ .bind(alert.orgId, alert.kind, alert.key)+ .run();+ console.error(`slack-alerts: ${alert.kind} for ${alert.orgId} failed: ${error}`);+ return false;+ }+ return true;+ } catch {+ console.error(`slack-alerts: ${alert.kind} for ${alert.orgId} failed`);+ return false;+ }+}++/** The billing-event sink: called from emitBillingEvent for every event. Never throws. */+export async function slackAlertForBillingEvent(+ env: AlertsDBEnv,+ name: string,+ orgId: string,+ data: Record<string, string | number | boolean | null>,+): Promise<void> {+ if (!env.SLACK_CONNECT_TOKEN) return;+ const alert = alertForBillingEvent(env, name, orgId, data);+ if (alert) await sendSlackAlert(env, alert);+}++/**+ * Activation: an org's first countable managed-agent session. session_creations+ * has no emit point the edge sees, so the 5-minute cron finds orgs whose first+ * session falls inside the lookback; an org with an older session never+ * matches, so the first deploy does not alert on existing customers.+ */+export async function runActivationAlerts(+ env: AlertsDBEnv,+ nowMs: number,+ fetchImpl: typeof fetch = fetch,+): Promise<number> {+ const sessions = env.SERVERLESS_AGENTS_DB;+ const db = env.OPENCOMPUTER_DB;+ if (!sessions || !db || !env.SLACK_CONNECT_TOKEN || !alertChannel(env, "activated")) return 0;+ const sinceSec = Math.floor(nowMs / 1000) - ACTIVATION_LOOKBACK_SEC;+ const since = new Date(sinceSec * 1000).toISOString();+ // SQLite returns the bare `source` from the row that holds the MIN.+ const { results } = await sessions+ .prepare(+ `SELECT account_id, source, MIN(created_at) AS first_at+ FROM session_creations+ WHERE COALESCE(countable, 1) = 1+ AND account_id IN (+ SELECT DISTINCT account_id FROM session_creations+ WHERE created_at >= ?1 AND COALESCE(countable, 1) = 1)+ GROUP BY account_id+ HAVING MIN(created_at) >= ?1+ ORDER BY first_at`,+ )+ .bind(since)+ .all<{ account_id: string; source: string; first_at: string }>();+ // Orgs already announced inside the window (sessions cannot be joined across+ // databases), so the batch goes to new ones.+ const sent = await db+ .prepare(`SELECT org_id FROM slack_alerts WHERE event = 'activated' AND sent_at >= ?1`)+ .bind(sinceSec)+ .all<{ org_id: string }>();+ const done = new Set((sent.results ?? []).map((r) => r.org_id));+ let posted = 0;+ for (const r of (results ?? []).filter((r) => !done.has(r.account_id)).slice(0, MAX_ACTIVATIONS_PER_RUN)) {+ const alert: Alert = {+ kind: "activated",+ orgId: r.account_id,+ key: "",+ what: "ran their first agent session",+ extra: r.source ? [`via ${r.source}`] : [],+ };+ if (await sendSlackAlert(env, alert, fetchImpl, nowMs)) posted++;+ }+ return posted;+}diff --git a/cloudflare-workers/api-edge/wrangler.prod.toml b/cloudflare-workers/api-edge/wrangler.prod.tomlindex 464b1fdb..a4c5ed23 100644--- a/cloudflare-workers/api-edge/wrangler.prod.toml+++ b/cloudflare-workers/api-edge/wrangler.prod.toml@@ -45,6 +45,14 @@ database_name = "opencomputer-prod"database_id = "8329e0f0-100d-445a-bf89-95c065f15dbb"migrations_dir = "migrations"+# blue's managed-agent session index (session_creations), read by the activation+# alert (src/slack_alerts.ts, work 090). Read-only here: its schema and+# migrations belong to blue, so no migrations_dir.+[[d1_databases]]+binding = "SERVERLESS_AGENTS_DB"+database_name = "serverless-agents"+database_id = "dae08738-fc29-4ad3-acd1-138944aabc9e"+[[kv_namespaces]]binding = "SESSIONS_KV"id = "b496f905ce634f94b6ac1d4f619825e0"@@ -194,6 +202,11 @@ COMPUTER_ENABLED_ORGS = "be0cf06f-ef75-400a-851c-bfd1507a666e"# SLACK_CONNECT_TOKEN secret is set.SLACK_CONNECT_SINCE = "1793145600"SLACK_CONNECT_TEAM_USER_IDS = "U06G42NTEK1,U06GFN8DJ7P,U06H7D98X40"+# Customer alerts (slack_alerts.ts, work 090), posted by the same Slack app+# (needs chat:write and membership of the channel). SLACK_ALERT_CHANNELS+# (`kind=channel,...`) moves a kind elsewhere, e.g. revenue alerts; credit+# purchases alert from SLACK_ALERT_CREDITS_MIN dollars (default 100).+SIGNUPS_SLACK_CHANNEL = "#signups"# PoolStock sizing. SHARDS × TARGET must stay ≤ the cell's MicroVM pool# (OPENSANDBOX_MICROVM_POOL_TARGET on the CP) or every shard sits permanently# below low-water, restocks on every claim, and competes for a supply that can