Skip to content

An open-source, faster Devin alternative

TypeScript

api-edge: welcome and trial emails through Loops (088)

utpal nadiger via Computera3aa3a84c5f9
diff --git a/cloudflare-workers/api-edge/migrations/0021_lifecycle_emails.sql b/cloudflare-workers/api-edge/migrations/0021_lifecycle_emails.sql
new file mode 100644
index 00000000..2fd6ed8a
--- /dev/null
+++ b/cloudflare-workers/api-edge/migrations/0021_lifecycle_emails.sql
@@ -0,0 +1,10 @@
+-- lifecycle_emails (serverless-agents-ws 088): one row per org and Loops event
+-- (`trial_low`, `trial_ended`) once it has been sent, so webhook retries, the
+-- billing clock and concurrent projections send each one at most once. The
+-- INSERT OR IGNORE that writes the row is the claim.
+CREATE TABLE IF NOT EXISTS lifecycle_emails (
+ org_id TEXT NOT NULL,
+ event TEXT NOT NULL,
+ sent_at INTEGER NOT NULL,
+ PRIMARY KEY (org_id, event)
+);
diff --git a/cloudflare-workers/api-edge/src/autumn_webhook.ts b/cloudflare-workers/api-edge/src/autumn_webhook.ts
index 3541ca43..c59b55cd 100644
--- a/cloudflare-workers/api-edge/src/autumn_webhook.ts
+++ b/cloudflare-workers/api-edge/src/autumn_webhook.ts
@@ -19,6 +19,7 @@
// events (billingWebhookEvents), never for the projection.
import { emitBillingEvent, type BillingEventName, type BillingEventsEnv } from "./billing_events";
+import { notifyTrialEvent, syncLoopsPlan, trialReason, type LoopsEnv } from "./loops";
// AutumnApiEnv is the minimal binding set for calling Autumn's REST API
// (GetCustomer / checkout). The dashboard handlers satisfy this without the
@@ -29,7 +30,7 @@ export interface AutumnApiEnv {
}
// AutumnSyncEnv adds D1 — enough to project Autumn state without dispatching.
-export interface AutumnSyncEnv extends AutumnApiEnv, BillingEventsEnv {
+export interface AutumnSyncEnv extends AutumnApiEnv, BillingEventsEnv, LoopsEnv {
OPENCOMPUTER_DB: D1Database;
}
@@ -829,7 +830,7 @@ export async function syncAutumnToD1(env: AutumnSyncEnv, orgID: string): Promise
const nowSec = Math.floor(Date.now() / 1000);
const prevRow = await env.OPENCOMPUTER_DB.prepare(
- "SELECT is_halted, halted_at, autumn_concurrency_override, usage_plan, payment_past_due_at, trial_started_at FROM orgs WHERE id = ?1",
+ "SELECT is_halted, halted_at, autumn_concurrency_override, usage_plan, payment_past_due_at, trial_started_at, billing_warning FROM orgs WHERE id = ?1",
)
.bind(orgID)
.first<{
@@ -839,6 +840,7 @@ export async function syncAutumnToD1(env: AutumnSyncEnv, orgID: string): Promise
usage_plan: UsagePlan;
payment_past_due_at: number | null;
trial_started_at: number | null;
+ billing_warning?: string | null;
}>();
const wasHalted = prevRow?.is_halted === 1;
const clock = { trialStartedAt: prevRow?.trial_started_at ?? null, paymentPastDueAt: prevRow?.payment_past_due_at ?? null };
@@ -883,6 +885,15 @@ export async function syncAutumnToD1(env: AutumnSyncEnv, orgID: string): Promise
// a concurrent projection can interleave.
if (planChange) await emitBillingEvent(env, "billing.plan_changed", { orgId: orgID, data: planChange });
+ // Lifecycle email (088), on the transition only: the first trial warning and
+ // a fresh halt on a trial limit. notifyTrialEvent also claims each event once
+ // per org, against concurrent projections that both see the transition.
+ const 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 (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/cli_auth.test.ts b/cloudflare-workers/api-edge/src/cli_auth.test.ts
index cca61fd3..9e4c9c13 100644
--- a/cloudflare-workers/api-edge/src/cli_auth.test.ts
+++ b/cloudflare-workers/api-edge/src/cli_auth.test.ts
@@ -690,6 +690,37 @@ describe("CLI device authorization edge contract", () => {
expect(typeof orgInsert?.args[8]).toBe("number");
});
+ it("sends the welcome event to Loops off the login path", async () => {
+ const db = new FakeDB([], null);
+ const fetchMock = vi.fn(async (_url: RequestInfo | URL, _init?: RequestInit) => Response.json({
+ user: { id: "new-workos-user", email: "[email protected]", first_name: "New" },
+ }));
+ vi.stubGlobal("fetch", fetchMock);
+ const pending: Promise<unknown>[] = [];
+ const resp = await worker.fetch(request("/auth/cli/device/exchange", {
+ method: "POST",
+ headers: { "content-type": "application/json", "cf-ipcountry": "US" },
+ body: JSON.stringify({ device_code: "opaque", credential_name: "oc CLI" }),
+ }), { ...testEnv(db), AUTUMN_NEW_ORGS: "true", AUTUMN_SECRET_KEY: "autumn-test", LOOPS_API_KEY: "loops-test" }, {
+ ...ctx,
+ waitUntil: (p: Promise<unknown>) => pending.push(p),
+ } as unknown as ExecutionContext);
+ expect(resp.status).toBe(200);
+ await Promise.all(pending);
+
+ const orgInsert = db.executed.find((entry) => entry.sql.includes("INSERT INTO orgs"));
+ const loops = fetchMock.mock.calls.filter(([url]) => String(url).startsWith("https://app.loops.so/"));
+ expect(loops).toHaveLength(1);
+ expect(String(loops[0][0])).toBe("https://app.loops.so/api/v1/events/send");
+ expect(JSON.parse(String(loops[0][1]?.body))).toMatchObject({
+ email: "[email protected]",
+ eventName: "signed_up",
+ firstName: "New",
+ orgId: orgInsert?.args[0],
+ plan: "base",
+ });
+ });
+
it("rejects extra exchange fields before contacting WorkOS", async () => {
const providerFetch = vi.fn();
vi.stubGlobal("fetch", providerFetch);
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index e13a67d5..94f8fb94 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -118,6 +118,7 @@ import {
COMPUTER_API_PREFIX,
} from "./computer_api";
import { emitBillingEvent, type BillingEventsEnv } from "./billing_events";
+import { sendLoopsEvent, type LoopsEnv } from "./loops";
import {
type EdgeRequestFacts,
newEdgeRequestFacts,
@@ -127,7 +128,7 @@ import { computerEnabledFor } from "./computer";
import { createdKeyForSync, revokeComputerKey, syncComputerKey } from "./computer_keys";
import { FIRST_TOUCH_COOKIE, readCookie, recordSignupAttribution, withFirstTouchCookie } from "./signup_attribution";
-export interface Env extends DashboardEnv, AgentFeedbackEnv, BillingEventsEnv {
+export interface Env extends DashboardEnv, AgentFeedbackEnv, BillingEventsEnv, LoopsEnv {
CF_ADMIN_SECRET: string;
STRIPE_WEBHOOK_SECRET: string;
EVENT_SECRET: string;
@@ -3958,6 +3959,7 @@ async function provisionWorkOSIdentity(
workosOrgID: string | undefined,
selection: IdentitySelection,
planIntent: string | null = null,
+ ctx?: ExecutionContext,
): Promise<ProvisionedIdentity> {
const nowSec = Math.floor(Date.now() / 1000);
const displayName =
@@ -4103,6 +4105,21 @@ async function provisionWorkOSIdentity(
userId: userID,
data: { plan_intent: planIntent, via: selection },
});
+ // Welcome email (088): creates the Loops contact and starts its loops.
+ // Off the login path; a Loops failure is logged, never fails the login.
+ const welcome = sendLoopsEvent(env, { email: profile.email, userId: userID }, "signed_up", {
+ idempotencyKey: `${orgID}:signed_up`,
+ eventProperties: { via: selection },
+ contactProperties: {
+ ...(profile.first_name ? { firstName: profile.first_name } : {}),
+ ...(profile.last_name ? { lastName: profile.last_name } : {}),
+ orgId: orgID,
+ plan: "base",
+ signedUpAt: new Date(nowSec * 1000).toISOString(),
+ },
+ });
+ if (ctx) ctx.waitUntil(welcome);
+ else await welcome;
}
orgRow = {
id: orgID,
@@ -4142,7 +4159,7 @@ async function provisionWorkOSIdentity(
};
}
-async function authCallback(req: Request, env: Env): Promise<Response> {
+async function authCallback(req: Request, env: Env, ctx?: ExecutionContext): Promise<Response> {
const reqURL = new URL(req.url);
const code = reqURL.searchParams.get("code");
if (!code) return json({ error: "missing code" }, 400);
@@ -4169,7 +4186,7 @@ async function authCallback(req: Request, env: Env): Promise<Response> {
// whose refresh fails with "code already exchanged". Restart the login once
// (WorkOS issues a fresh code); a second failure gets a plain retry page.
try {
- return await completeAuthCallback(req, env, reqURL, tokenBody);
+ return await completeAuthCallback(req, env, reqURL, tokenBody, ctx);
} catch (err) {
console.error("auth callback: post-exchange failure", err);
const state = parseAuthState(reqURL.searchParams.get("state"));
@@ -4216,6 +4233,7 @@ async function completeAuthCallback(
env: Env,
reqURL: URL,
tokenBody: AuthenticateResponse,
+ ctx?: ExecutionContext,
): Promise<Response> {
const profile = tokenBody.user;
// WorkOS session id (sid) for the hosted logout flow — carried in our session JWT.
@@ -4231,6 +4249,7 @@ async function completeAuthCallback(
tokenBody.organization_id ?? profile.organization_id,
"browser",
planIntent,
+ ctx,
);
if (identity.created) {
await recordSignupAttribution(env, {
@@ -4705,7 +4724,7 @@ async function authCLIExchange(req: Request, env: Env, ctx?: ExecutionContext):
let identity: ProvisionedIdentity;
try {
- identity = await provisionWorkOSIdentity(req, env, typedProfile, workosOrgID, "cli");
+ identity = await provisionWorkOSIdentity(req, env, typedProfile, workosOrgID, "cli", null, ctx);
} catch {
return finish(cliAuthError("account_provisioning_unavailable", 503), "provisioning_error");
}
@@ -5940,7 +5959,7 @@ export default {
// Browser auth flow.
if (path === "/auth/login") { if (req.method === "GET") return withFirstTouchCookie(req, await authLogin(req, env)); }
- if (path === "/auth/callback") { if (req.method === "GET") return authCallback(req, env); }
+ if (path === "/auth/callback") { if (req.method === "GET") return authCallback(req, env, ctx); }
if (path === "/auth/logout") { if (req.method === "POST") return authLogout(req, env); }
if (path === "/auth/refresh") { if (req.method === "POST") return authRefresh(req, env); }
diff --git a/cloudflare-workers/api-edge/src/loops.test.ts b/cloudflare-workers/api-edge/src/loops.test.ts
new file mode 100644
index 00000000..66ab0154
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/loops.test.ts
@@ -0,0 +1,255 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { syncAutumnToD1 } from "./autumn_webhook";
+import { isExcludedEmail, notifyTrialEvent, sendLoopsEvent, trialReason } from "./loops";
+
+const owner = { email: "[email protected]", userId: "user_1" };
+
+function mockFetch(status = 200) {
+ const calls: Array<{ url: string; method: string; headers: Record<string, string>; body: Record<string, unknown> }> = [];
+ vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {
+ calls.push({
+ url: String(input),
+ method: init?.method ?? "GET",
+ headers: init?.headers as Record<string, string>,
+ body: JSON.parse(String(init?.body)),
+ });
+ return new Response(null, { status });
+ });
+ return calls;
+}
+
+describe("Loops exclusions", () => {
+ it("skips our own domains and the configured addresses", () => {
+ expect(isExcludedEmail("[email protected]")).toBe(true);
+ expect(isExcludedEmail("[email protected]")).toBe(true);
+ expect(isExcludedEmail("[email protected]")).toBe(false);
+ expect(isExcludedEmail("[email protected]", "@example.com")).toBe(true);
+ expect(isExcludedEmail("[email protected]", "[email protected], @other.io")).toBe(false);
+ });
+
+ it("matches Gmail addresses ignoring dots and +tags", () => {
+ expect(isExcludedEmail("[email protected]", "[email protected]")).toBe(true);
+ expect(isExcludedEmail("[email protected]", "[email protected]")).toBe(false);
+ expect(isExcludedEmail("[email protected]", "[email protected]")).toBe(false);
+ });
+
+ it("names only trial reasons", () => {
+ expect(trialReason("trial_days")).toBe("days");
+ expect(trialReason("trial_minutes")).toBe("minutes");
+ expect(trialReason("trial_tokens")).toBe("tokens");
+ expect(trialReason("credits_low")).toBeNull();
+ expect(trialReason(null)).toBeNull();
+ });
+});
+
+describe("Loops client", () => {
+ afterEach(() => vi.restoreAllMocks());
+
+ it("is off without an API key", async () => {
+ const calls = mockFetch();
+ expect(await sendLoopsEvent({}, owner, "signed_up", { idempotencyKey: "org_1:signed_up" })).toBe(false);
+ expect(calls).toHaveLength(0);
+ });
+
+ it("sends the event with contact properties and an idempotency key", async () => {
+ const calls = mockFetch();
+ const ok = await sendLoopsEvent({ LOOPS_API_KEY: "loops-key" }, owner, "signed_up", {
+ idempotencyKey: "org_1:signed_up",
+ eventProperties: { via: "browser" },
+ contactProperties: { firstName: "Ada", orgId: "org_1" },
+ });
+ expect(ok).toBe(true);
+ expect(calls).toEqual([
+ {
+ url: "https://app.loops.so/api/v1/events/send",
+ method: "POST",
+ headers: {
+ authorization: "Bearer loops-key",
+ "content-type": "application/json",
+ "idempotency-key": "org_1:signed_up",
+ },
+ body: {
+ firstName: "Ada",
+ orgId: "org_1",
+ email: "[email protected]",
+ userId: "user_1",
+ eventName: "signed_up",
+ eventProperties: { via: "browser" },
+ },
+ },
+ ]);
+ });
+
+ it("does not send to internal accounts", async () => {
+ const calls = mockFetch();
+ await sendLoopsEvent({ LOOPS_API_KEY: "k" }, { email: "[email protected]", userId: "u" }, "signed_up", {
+ idempotencyKey: "o:signed_up",
+ });
+ expect(calls).toHaveLength(0);
+ });
+
+ it("reports a failure without throwing", async () => {
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ mockFetch(500);
+ expect(await sendLoopsEvent({ LOOPS_API_KEY: "k" }, owner, "trial_low", { idempotencyKey: "o:trial_low" })).toBe(
+ false,
+ );
+ vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("network"));
+ expect(await sendLoopsEvent({ LOOPS_API_KEY: "k" }, owner, "trial_low", { idempotencyKey: "o:trial_low" })).toBe(
+ false,
+ );
+ });
+});
+
+// A D1 fake holding one org, its owner and the lifecycle_emails claims.
+function fakeDb(opts: { provider?: string; email?: string; org?: Record<string, unknown> } = {}) {
+ const org: Record<string, unknown> = {
+ is_halted: 0,
+ autumn_concurrency_override: null,
+ usage_plan: "base",
+ payment_past_due_at: null,
+ trial_started_at: Math.floor(Date.now() / 1000) - 86_400,
+ billing_warning: null,
+ ...opts.org,
+ };
+ const claims = new Set<string>();
+ const db = {
+ org,
+ claims,
+ prepare(sql: string) {
+ return {
+ bind(...args: unknown[]) {
+ return {
+ first: async () => {
+ if (sql.includes("JOIN users")) {
+ return (opts.provider ?? "autumn") === "autumn"
+ ? { user_id: "user_1", email: opts.email ?? "[email protected]" }
+ : null;
+ }
+ return { ...org };
+ },
+ run: async () => {
+ if (sql.includes("INSERT OR IGNORE INTO lifecycle_emails")) {
+ const key = `${args[0]}:${args[1]}`;
+ if (claims.has(key)) return { meta: { changes: 0 } };
+ claims.add(key);
+ } else if (sql.includes("AND usage_plan = ?3")) {
+ if (org.usage_plan !== args[2]) return { meta: { changes: 0 } };
+ org.usage_plan = args[0];
+ } else if (sql.includes("SET is_halted")) {
+ org.is_halted = args[0];
+ org.halted_at = args[1];
+ org.usage_plan = args[3];
+ org.halt_reason = args[6];
+ org.billing_warning = args[7];
+ }
+ return { meta: { changes: 1 } };
+ },
+ };
+ },
+ };
+ },
+ };
+ return db as typeof db & D1Database;
+}
+
+describe("trial events", () => {
+ afterEach(() => vi.restoreAllMocks());
+
+ it("sends each trial event once per org", async () => {
+ const calls = mockFetch();
+ const db = fakeDb();
+ const env = { OPENCOMPUTER_DB: db, LOOPS_API_KEY: "k" };
+ await notifyTrialEvent(env, "org_1", "trial_low", "minutes");
+ await notifyTrialEvent(env, "org_1", "trial_low", "days");
+ await notifyTrialEvent(env, "org_1", "trial_ended", "minutes");
+ expect(calls.map((c) => [c.body.eventName, c.body.eventProperties, c.headers["idempotency-key"]])).toEqual([
+ ["trial_low", { reason: "minutes" }, "org_1:trial_low"],
+ ["trial_ended", { reason: "minutes" }, "org_1:trial_ended"],
+ ]);
+ });
+
+ it("skips legacy billing, internal owners and a missing key without claiming", async () => {
+ const calls = mockFetch();
+ for (const db of [fakeDb({ provider: "legacy" }), fakeDb({ email: "[email protected]" })]) {
+ await notifyTrialEvent({ OPENCOMPUTER_DB: db, LOOPS_API_KEY: "k" }, "org_1", "trial_low", "days");
+ expect(db.claims.size).toBe(0);
+ }
+ const db = fakeDb();
+ await notifyTrialEvent({ OPENCOMPUTER_DB: db }, "org_1", "trial_low", "days");
+ expect(db.claims.size).toBe(0);
+ expect(calls).toHaveLength(0);
+ });
+});
+
+describe("trial events from the Autumn projection", () => {
+ afterEach(() => vi.restoreAllMocks());
+
+ function mockAutumn(minutes: number, credits = 5) {
+ const loops: Array<Record<string, unknown>> = [];
+ vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {
+ if (String(input).startsWith("https://autumn.test/v1/customers/")) {
+ return Response.json({
+ id: "org_1",
+ subscriptions: [{ plan_id: "trial", add_on: false, status: "active" }],
+ balances: { credits: { remaining: credits }, work_minutes: { remaining: minutes } },
+ });
+ }
+ if (String(input).startsWith("https://app.loops.so/")) loops.push(JSON.parse(String(init?.body)));
+ return new Response(null, { status: 200 });
+ });
+ return loops;
+ }
+
+ const syncEnv = (db: D1Database) => ({
+ AUTUMN_SECRET_KEY: "autumn-secret",
+ AUTUMN_BASE_URL: "https://autumn.test/v1",
+ OPENCOMPUTER_DB: db,
+ LOOPS_API_KEY: "k",
+ });
+
+ it("sends trial_low when the first trial warning is raised, and not again", async () => {
+ const loops = mockAutumn(100);
+ const db = fakeDb();
+ await syncAutumnToD1(syncEnv(db), "org_1");
+ await syncAutumnToD1(syncEnv(db), "org_1");
+ expect(db.org.billing_warning).toBe("trial_minutes");
+ expect(loops).toEqual([expect.objectContaining({ eventName: "trial_low", eventProperties: { reason: "minutes" } })]);
+ });
+
+ it("does not resend when a standing warning changes reason", async () => {
+ const loops = mockAutumn(100, 1);
+ const db = fakeDb({ org: { billing_warning: "trial_minutes" } });
+ await syncAutumnToD1(syncEnv(db), "org_1");
+ expect(db.org.billing_warning).toBe("trial_tokens");
+ expect(loops).toEqual([]);
+ });
+
+ it("sends trial_ended when the trial halts the org, once", async () => {
+ const loops = mockAutumn(0);
+ const db = fakeDb({ org: { billing_warning: "trial_minutes" } });
+ await syncAutumnToD1(syncEnv(db), "org_1");
+ await syncAutumnToD1(syncEnv(db), "org_1");
+ expect(db.org.halt_reason).toBe("trial_minutes");
+ expect(loops).toEqual([expect.objectContaining({ eventName: "trial_ended", eventProperties: { reason: "minutes" } })]);
+ });
+
+ it("mirrors a plan change onto the contact", async () => {
+ const loops: Array<Record<string, unknown>> = [];
+ vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {
+ if (String(input).startsWith("https://autumn.test/v1/customers/")) {
+ return Response.json({
+ id: "org_1",
+ subscriptions: [{ plan_id: "pro", add_on: false, status: "active" }],
+ balances: { credits: { remaining: 20 }, work_minutes: { remaining: 3000 } },
+ });
+ }
+ if (String(input).startsWith("https://app.loops.so/")) loops.push({ url: String(input), ...JSON.parse(String(init?.body)) });
+ return new Response(null, { status: 200 });
+ });
+ await syncAutumnToD1(syncEnv(fakeDb()), "org_1");
+ expect(loops).toEqual([
+ { url: "https://app.loops.so/api/v1/contacts/update", plan: "pro", email: "[email protected]", userId: "user_1" },
+ ]);
+ });
+});
diff --git a/cloudflare-workers/api-edge/src/loops.ts b/cloudflare-workers/api-edge/src/loops.ts
new file mode 100644
index 00000000..f542e221
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/loops.ts
@@ -0,0 +1,176 @@
+// Lifecycle email through Loops (serverless-agents-ws 088). The edge only
+// creates contacts and sends events; copy, delays, conditions, unsubscribes
+// and the sending domain live in Loops, editable without a deploy.
+//
+// Events: `signed_up` (new org), `trial_low` (a trial limit is near) and
+// `trial_ended` (the trial halted the org), each with `reason` = days |
+// minutes | tokens. The contact's `plan` property follows plan changes so a
+// loop can stop once the org pays.
+//
+// Off unless LOOPS_API_KEY is set. Never throws, one bounded attempt, so a
+// login or billing path can await it. Internal accounts are skipped: our own
+// domains, plus LOOPS_EXCLUDE_EMAILS (comma-separated addresses or @domains;
+// Gmail addresses match ignoring dots and +tags).
+
+export interface LoopsEnv {
+ LOOPS_API_KEY?: string;
+ LOOPS_EXCLUDE_EMAILS?: string;
+}
+
+export type LoopsEvent = "signed_up" | "trial_low" | "trial_ended";
+
+export interface LoopsContact {
+ email: string;
+ userId: string;
+}
+
+const LOOPS_API = "https://app.loops.so/api/v1";
+const POST_TIMEOUT_MS = 2_000;
+const INTERNAL_DOMAINS = ["digger.dev", "opencomputer.dev"];
+const GMAIL_DOMAINS = new Set(["gmail.com", "googlemail.com"]);
+
+function normalizeEmail(email: string): string {
+ const lower = email.trim().toLowerCase();
+ const at = lower.lastIndexOf("@");
+ if (at < 0) return lower;
+ let local = lower.slice(0, at);
+ const domain = lower.slice(at + 1);
+ if (GMAIL_DOMAINS.has(domain)) local = local.replace(/\+.*$/, "").replaceAll(".", "");
+ return `${local}@${domain}`;
+}
+
+/** Whether an address belongs to us and must not get lifecycle email. */
+export function isExcludedEmail(email: string, extra = ""): boolean {
+ const addr = normalizeEmail(email);
+ const domain = addr.slice(addr.lastIndexOf("@") + 1);
+ const entries = [...INTERNAL_DOMAINS.map((d) => `@${d}`), ...extra.split(",")]
+ .map((e) => e.trim().toLowerCase())
+ .filter(Boolean);
+ return entries.some((e) => (e.startsWith("@") ? domain === e.slice(1) : addr === normalizeEmail(e)));
+}
+
+/** The reason a trial billing_warning or halt_reason carries, or null for any other kind. */
+export function trialReason(kind: string | null | undefined): "days" | "minutes" | "tokens" | null {
+ if (kind === "trial_days") return "days";
+ if (kind === "trial_minutes") return "minutes";
+ if (kind === "trial_tokens") return "tokens";
+ return null;
+}
+
+/**
+ * Sends one event for a contact, creating the contact if it is new. Contact
+ * properties ride along at the top level. Returns whether Loops accepted it.
+ */
+export async function sendLoopsEvent(
+ env: LoopsEnv,
+ contact: LoopsContact,
+ eventName: LoopsEvent,
+ opts: {
+ idempotencyKey: string;
+ eventProperties?: Record<string, string | number | boolean>;
+ contactProperties?: Record<string, string | number | boolean>;
+ },
+): Promise<boolean> {
+ const key = env.LOOPS_API_KEY?.trim();
+ if (!key || isExcludedEmail(contact.email, env.LOOPS_EXCLUDE_EMAILS)) return false;
+ return post(key, "/events/send", "POST", {
+ ...opts.contactProperties,
+ email: contact.email,
+ userId: contact.userId,
+ eventName,
+ ...(opts.eventProperties ? { eventProperties: opts.eventProperties } : {}),
+ }, { "idempotency-key": opts.idempotencyKey });
+}
+
+/** Updates (or creates) a contact's properties without sending an event. */
+export async function updateLoopsContact(
+ env: LoopsEnv,
+ contact: LoopsContact,
+ properties: Record<string, string | number | boolean>,
+): Promise<boolean> {
+ const key = env.LOOPS_API_KEY?.trim();
+ if (!key || isExcludedEmail(contact.email, env.LOOPS_EXCLUDE_EMAILS)) return false;
+ return post(key, "/contacts/update", "PUT", { ...properties, email: contact.email, userId: contact.userId });
+}
+
+async function post(
+ key: string,
+ path: string,
+ method: "POST" | "PUT",
+ body: Record<string, unknown>,
+ headers: Record<string, string> = {},
+): Promise<boolean> {
+ try {
+ const res = await fetch(`${LOOPS_API}${path}`, {
+ method,
+ headers: { authorization: `Bearer ${key}`, "content-type": "application/json", ...headers },
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(POST_TIMEOUT_MS),
+ });
+ await res.body?.cancel().catch(() => {});
+ // 409: the idempotency key was already used, so the event went out before.
+ if (res.ok || res.status === 409) return true;
+ // The response can echo the contact's email; log the status only.
+ console.error(`loops: ${path} failed: ${res.status}`);
+ return false;
+ } catch (err) {
+ console.error(`loops: ${path} failed: ${err instanceof Error ? err.name : "error"}`);
+ return false;
+ }
+}
+
+interface LoopsDBEnv extends LoopsEnv {
+ OPENCOMPUTER_DB: D1Database;
+}
+
+/** The org owner as a Loops contact, or null for legacy billing or an unknown owner. */
+async function orgOwner(env: LoopsDBEnv, orgID: string): Promise<LoopsContact | null> {
+ const row = await env.OPENCOMPUTER_DB.prepare(
+ `SELECT u.id AS user_id, u.email FROM orgs o JOIN users u ON u.id = o.owner_user_id
+ WHERE o.id = ?1 AND o.billing_provider = 'autumn'`,
+ )
+ .bind(orgID)
+ .first<{ user_id: string; email: string }>();
+ return row?.email ? { email: row.email, userId: row.user_id } : null;
+}
+
+/**
+ * Sends a trial event to the org owner at most once per org: the
+ * lifecycle_emails row is claimed first, so retries and concurrent
+ * projections that see the same transition do not resend. Never throws.
+ */
+export async function notifyTrialEvent(
+ env: LoopsDBEnv,
+ orgID: string,
+ eventName: "trial_low" | "trial_ended",
+ reason: "days" | "minutes" | "tokens",
+): Promise<void> {
+ if (!env.LOOPS_API_KEY?.trim()) return;
+ try {
+ const owner = await orgOwner(env, orgID);
+ if (!owner || isExcludedEmail(owner.email, env.LOOPS_EXCLUDE_EMAILS)) return;
+ const claimed = await env.OPENCOMPUTER_DB.prepare(
+ `INSERT OR IGNORE INTO lifecycle_emails (org_id, event, sent_at) VALUES (?1, ?2, ?3)`,
+ )
+ .bind(orgID, eventName, Math.floor(Date.now() / 1000))
+ .run();
+ if (claimed.meta?.changes !== 1) return;
+ await sendLoopsEvent(env, owner, eventName, {
+ idempotencyKey: `${orgID}:${eventName}`,
+ eventProperties: { reason },
+ });
+ } catch {
+ console.error(`loops: ${eventName} for ${orgID} failed`);
+ }
+}
+
+/** Mirrors the org's plan onto the owner's contact, so loops can stop once it pays. Never throws. */
+export async function syncLoopsPlan(env: LoopsDBEnv, orgID: string, plan: string): Promise<void> {
+ if (!env.LOOPS_API_KEY?.trim()) return;
+ try {
+ const owner = await orgOwner(env, orgID);
+ if (owner) await updateLoopsContact(env, owner, { plan });
+ } catch {
+ console.error(`loops: plan sync for ${orgID} failed`);
+ }
+}
diff --git a/cloudflare-workers/api-edge/wrangler.prod.toml b/cloudflare-workers/api-edge/wrangler.prod.toml
index ed60612b..400d4238 100644
--- a/cloudflare-workers/api-edge/wrangler.prod.toml
+++ b/cloudflare-workers/api-edge/wrangler.prod.toml
@@ -170,6 +170,10 @@ deleted_classes = ["VmSession"]
# LINEAR_API_KEY / LINEAR_TEAM_ID (+ optional LINEAR_PROJECT_ID var) —
# when set, each new agent-feedback report opens a
# Linear issue. Off when unset.
+# LOOPS_API_KEY — lifecycle email through Loops (src/loops.ts,
+# serverless-agents-ws 088). Off when unset.
+# LOOPS_EXCLUDE_EMAILS — comma-separated addresses or @domains that never
+# get lifecycle email (internal accounts).
# Optional vars: OPENROUTER_BASE_URL (default https://openrouter.ai/api/v1),
# OPENROUTER_MARKUP_BPS (env-default markup; per-org orgs.model_markup_bps wins).
diff --git a/cloudflare-workers/api-edge/wrangler.toml b/cloudflare-workers/api-edge/wrangler.toml
index 75bafbd2..b82fece0 100644
--- a/cloudflare-workers/api-edge/wrangler.toml
+++ b/cloudflare-workers/api-edge/wrangler.toml
@@ -180,6 +180,10 @@ deleted_classes = ["VmSession"]
# LINEAR_API_KEY / LINEAR_TEAM_ID (+ optional LINEAR_PROJECT_ID var) —
# when set, each new agent-feedback report opens a
# Linear issue. Off when unset.
+# LOOPS_API_KEY — lifecycle email through Loops (src/loops.ts,
+# serverless-agents-ws 088). Off when unset.
+# LOOPS_EXCLUDE_EMAILS — comma-separated addresses or @domains that never
+# get lifecycle email (internal accounts).
# The VM-DO exec data plane (VM_SESSIONS DO) needs NO dedicated secret: the worker
# host authenticates its /internal/vms/:id/connect dial with a per-sandbox HMAC
# over the already-shared SESSION_JWT_SECRET (minted by the CP, re-derived here).