Skip to content

An open-source, faster Devin alternative

TypeScript

api-edge: Slack Connect channel and invite for every signup

utpal nadiger via Computer31a33749a32e
diff --git a/cloudflare-workers/api-edge/migrations/0021_slack_connect_invites.sql b/cloudflare-workers/api-edge/migrations/0021_slack_connect_invites.sql
new file mode 100644
index 00000000..2a0266c0
--- /dev/null
+++ b/cloudflare-workers/api-edge/migrations/0021_slack_connect_invites.sql
@@ -0,0 +1,17 @@
+-- slack_connect_invites (serverless-agents-ws 089): one Slack Connect invite per
+-- signup, sent by the edge cron (src/slack_connect.ts). A row is the claim that
+-- this user is handled: the cron never invites a user who has one. Work-email
+-- signups from the same domain share one channel; free-email signups get their own.
+CREATE TABLE IF NOT EXISTS slack_connect_invites (
+ user_id TEXT PRIMARY KEY,
+ email TEXT NOT NULL,
+ channel_name TEXT NOT NULL,
+ channel_id TEXT, -- set once the channel exists
+ status TEXT NOT NULL, -- pending | invited | skipped | failed
+ attempts INTEGER NOT NULL DEFAULT 0,
+ last_error TEXT,
+ invite_id TEXT, -- Slack's invite id
+ created_at INTEGER NOT NULL,
+ invited_at INTEGER
+);
+CREATE INDEX IF NOT EXISTS idx_slack_connect_invites_channel_name ON slack_connect_invites(channel_name);
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index e13a67d5..267caf64 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -72,6 +72,7 @@ import {
} from "./autumn_webhook";
import { runAutumnMeter } from "./autumn_meter";
import { runBillingClock } from "./billing_clock";
+import { runSlackConnectInvites } from "./slack_connect";
import { disableManagedBilling, enableManagedBilling } from "./model_billing";
import { runModelMeter, syncModelCaps } from "./model_meter";
import {
@@ -184,6 +185,12 @@ export interface Env extends DashboardEnv, AgentFeedbackEnv, BillingEventsEnv {
// as the API key so /v3 sandboxes are owned by + billed to the customer org.
// Unset → the feature is inert (JWT keys rejected). See dashboard.ts.
OC_PROVISION_SECRET?: string;
+ // Slack Connect per signup (slack_connect.ts): dormant unless the bot token
+ // and SINCE (unix seconds) are set.
+ SLACK_CONNECT_BOT_TOKEN?: string;
+ SLACK_CONNECT_SINCE?: string;
+ SLACK_CONNECT_TEAM_USER_IDS?: string;
+ SLACK_CONNECT_BATCH?: string;
// Token / model-usage billing (token-billing.md). The edge holds ONE OpenRouter
// secret — a management/provisioning key — and mints per-org inference keys.
OPENROUTER_PROVISIONING_KEY: string;
@@ -6370,6 +6377,11 @@ export default {
ctx.waitUntil(
runPoolKeepWarm(env).catch((err) => console.error("pool-keepwarm: run failed", err)),
);
+ // Slack Connect invite per signup, regardless of billing config. Dormant
+ // unless SLACK_CONNECT_BOT_TOKEN is set. See slack_connect.ts.
+ ctx.waitUntil(
+ runSlackConnectInvites(env, Date.now()).catch((err) => console.error("slack-connect: 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_connect.test.ts b/cloudflare-workers/api-edge/src/slack_connect.test.ts
new file mode 100644
index 00000000..250934e6
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/slack_connect.test.ts
@@ -0,0 +1,218 @@
+import { describe, expect, it } from "vitest";
+import { channelNameFor, isInternalEmail, runSlackConnectInvites, type SlackConnectEnv } from "./slack_connect";
+
+// The cron's SQL runs against the real schema: the snapshot,
+// then every migration statement it does not already contain, in node:sqlite (see agent_feedback.test.ts for why
+// the builtins are reached this way).
+interface SqliteStatement {
+ get(...params: unknown[]): unknown;
+ all(...params: unknown[]): unknown[];
+ run(...params: unknown[]): unknown;
+}
+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;
+ return this;
+ }
+ private args(): unknown[] {
+ return this.params.map((v) => (v === undefined ? null : v));
+ }
+ async first<T>(): Promise<T | null> {
+ return (this.db.prepare(this.sql).get(...this.args()) as T | undefined) ?? null;
+ }
+ async all<T>(): Promise<{ results: T[] }> {
+ return { results: this.db.prepare(this.sql).all(...this.args()) as T[] };
+ }
+ async run(): Promise<{ success: true; meta: object }> {
+ this.db.prepare(this.sql).run(...this.args());
+ return { success: true, meta: {} };
+ }
+}
+
+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;
+}
+
+function d1(db: DatabaseSync): D1Database {
+ return { prepare: (sql: string) => new Stmt(db, sql) } as unknown as D1Database;
+}
+
+const NOW = Date.UTC(2026, 9, 27, 12, 0, 0);
+const SINCE = NOW / 1000 - 3600;
+
+// A fake Slack: records every call; `errors` maps a method to the error it returns.
+function fakeSlack(errors: Record<string, string | string[]> = {}, taken: string[] = []) {
+ const calls: { method: string; params: Record<string, string> }[] = [];
+ let n = 0;
+ const fetchImpl = (async (url: string, init: RequestInit) => {
+ const method = url.split("/api/")[1];
+ const params = Object.fromEntries(new URLSearchParams(String(init.body)));
+ calls.push({ method, params });
+ const e = errors[method];
+ const err = Array.isArray(e) ? e.shift() : e;
+ if (err === "429") return new Response("", { status: 429 });
+ if (err) return Response.json({ ok: false, error: err });
+ if (method === "conversations.create") {
+ if (taken.includes(params.name)) return Response.json({ ok: false, error: "name_taken" });
+ taken.push(params.name);
+ return Response.json({ ok: true, channel: { id: `C${++n}`, name: params.name } });
+ }
+ if (method === "conversations.inviteShared") return Response.json({ ok: true, invite_id: `I${n}` });
+ return Response.json({ ok: true });
+ }) as unknown as typeof fetch;
+ return { calls, fetchImpl, methods: () => calls.map((c) => c.method) };
+}
+
+function setup(users: [string, string, number?][]) {
+ const db = schemaDB();
+ for (const [id, email, created] of users) {
+ db.prepare("INSERT INTO users (id, email, created_at) VALUES (?, ?, ?)").run(id, email, created ?? SINCE + 60);
+ }
+ const env: SlackConnectEnv = {
+ OPENCOMPUTER_DB: d1(db),
+ SLACK_CONNECT_BOT_TOKEN: "xoxb-test",
+ SLACK_CONNECT_SINCE: String(SINCE),
+ SLACK_CONNECT_TEAM_USER_IDS: "U1,U2,U3",
+ };
+ const rows = () =>
+ db.prepare("SELECT user_id, channel_name, channel_id, status, attempts, last_error FROM slack_connect_invites ORDER BY user_id").all() as {
+ user_id: string; channel_name: string; channel_id: string | null; status: string; attempts: number; last_error: string | null;
+ }[];
+ return { db, env, rows };
+}
+
+describe("channel names", () => {
+ it("names work email by company and free email by address", () => {
+ expect(channelNameFor("[email protected]")).toBe("opencomputer-acme");
+ expect(channelNameFor("[email protected]")).toBe("opencomputer-acme");
+ expect(channelNameFor("[email protected]")).toBe("opencomputer-jane-doe");
+ expect(channelNameFor(`${"x".repeat(100)}@gmail.com`).length).toBeLessThanOrEqual(77);
+ });
+
+ it("knows internal accounts", () => {
+ expect(isInternalEmail("[email protected]")).toBe(true);
+ expect(isInternalEmail("[email protected]")).toBe(true);
+ expect(isInternalEmail("[email protected]")).toBe(false);
+ });
+});
+
+describe("runSlackConnectInvites", () => {
+ it("does nothing without a token or a start time", async () => {
+ const { env, rows } = setup([["u1", "[email protected]"]]);
+ const slack = fakeSlack();
+ await runSlackConnectInvites({ ...env, SLACK_CONNECT_BOT_TOKEN: undefined }, NOW, slack.fetchImpl);
+ await runSlackConnectInvites({ ...env, SLACK_CONNECT_SINCE: undefined }, NOW, slack.fetchImpl);
+ expect(slack.calls).toEqual([]);
+ expect(rows()).toEqual([]);
+ });
+
+ it("creates a channel, adds the team, invites the signup once", async () => {
+ const { env, rows } = setup([["u1", "[email protected]"], ["old", "[email protected]", SINCE - 1]]);
+ const slack = fakeSlack();
+ expect(await runSlackConnectInvites(env, NOW, slack.fetchImpl)).toMatchObject({ invited: 1 });
+ expect(slack.calls).toEqual([
+ { method: "conversations.create", params: { name: "opencomputer-acme", is_private: "false" } },
+ { method: "conversations.invite", params: { channel: "C1", users: "U1,U2,U3", force: "true" } },
+ { method: "conversations.inviteShared", params: { channel: "C1", emails: "[email protected]" } },
+ ]);
+ expect(rows()).toMatchObject([{ user_id: "u1", channel_id: "C1", status: "invited" }]);
+
+ await runSlackConnectInvites(env, NOW + 300_000, slack.fetchImpl);
+ expect(slack.calls).toHaveLength(3);
+ });
+
+ it("puts colleagues in one channel and free-email users in their own", async () => {
+ const { env, rows } = setup([
+ ["u1", "[email protected]", SINCE + 1],
+ ["u2", "[email protected]", SINCE + 2],
+ ["u3", "[email protected]", SINCE + 3],
+ ]);
+ const slack = fakeSlack();
+ await runSlackConnectInvites(env, NOW, slack.fetchImpl);
+ // Three creates: acme, then [email protected]'s opencomputer-acme (taken) and opencomputer-acme-2.
+ expect(slack.methods().filter((m) => m === "conversations.create")).toHaveLength(3);
+ expect(rows().map((r) => [r.user_id, r.channel_name, r.channel_id])).toEqual([
+ ["u1", "opencomputer-acme", "C1"],
+ ["u2", "opencomputer-acme", "C1"],
+ ["u3", "opencomputer-acme-2", "C2"],
+ ]);
+ });
+
+ it("suffixes a taken name instead of joining someone else's channel", async () => {
+ const { env, rows } = setup([["u1", "[email protected]"]]);
+ const slack = fakeSlack({}, ["opencomputer-jane"]);
+ await runSlackConnectInvites(env, NOW, slack.fetchImpl);
+ expect(rows()).toMatchObject([{ channel_name: "opencomputer-jane-2", channel_id: "C1", status: "invited" }]);
+ });
+
+ it("skips internal accounts without calling Slack", async () => {
+ const { env, rows } = setup([["u1", "[email protected]"]]);
+ const slack = fakeSlack();
+ await runSlackConnectInvites(env, NOW, slack.fetchImpl);
+ expect(slack.calls).toEqual([]);
+ expect(rows()).toMatchObject([{ status: "skipped" }]);
+ });
+
+ it("retries a failed invite on the next tick without a second channel", async () => {
+ const { env, rows } = setup([["u1", "[email protected]"]]);
+ const slack = fakeSlack({ "conversations.inviteShared": ["internal_error"] });
+ await runSlackConnectInvites(env, NOW, slack.fetchImpl);
+ expect(rows()).toMatchObject([{ status: "pending", attempts: 1, channel_id: "C1", last_error: "internal_error" }]);
+ await runSlackConnectInvites(env, NOW, slack.fetchImpl);
+ expect(slack.methods()).toEqual([
+ "conversations.create", "conversations.invite", "conversations.inviteShared", "conversations.inviteShared",
+ ]);
+ expect(rows()).toMatchObject([{ status: "invited", last_error: null }]);
+ });
+
+ it("gives up at once on a permanent error, and after five tries otherwise", async () => {
+ const { env, rows } = setup([["u1", "[email protected]", SINCE + 1], ["u2", "[email protected]", SINCE + 2]]);
+ const slack = fakeSlack({ "conversations.inviteShared": ["not_paid", ...Array(10).fill("internal_error")] });
+ for (let i = 0; i < 6; i++) await runSlackConnectInvites(env, NOW, slack.fetchImpl);
+ expect(rows()).toMatchObject([
+ { user_id: "u1", status: "failed", attempts: 1 },
+ { user_id: "u2", status: "failed", attempts: 5 },
+ ]);
+ });
+
+ it("stops the tick on a rate limit and resumes later", async () => {
+ const { env, rows } = setup([["u1", "[email protected]", SINCE + 1], ["u2", "[email protected]", SINCE + 2]]);
+ const slack = fakeSlack({ "conversations.create": ["429"] });
+ await runSlackConnectInvites(env, NOW, slack.fetchImpl);
+ expect(slack.methods()).toEqual(["conversations.create"]);
+ await runSlackConnectInvites(env, NOW, slack.fetchImpl);
+ expect(rows()).toMatchObject([{ status: "invited" }, { status: "invited" }]);
+ });
+
+ it("respects the batch size", async () => {
+ const { env, rows } = setup([["u1", "[email protected]", SINCE + 1], ["u2", "[email protected]", SINCE + 2]]);
+ await runSlackConnectInvites({ ...env, SLACK_CONNECT_BATCH: "1" }, NOW, fakeSlack().fetchImpl);
+ expect(rows().map((r) => r.user_id)).toEqual(["u1"]);
+ });
+});
diff --git a/cloudflare-workers/api-edge/src/slack_connect.ts b/cloudflare-workers/api-edge/src/slack_connect.ts
new file mode 100644
index 00000000..5a893064
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/slack_connect.ts
@@ -0,0 +1,244 @@
+// Slack Connect per signup (serverless-agents-ws 089). Each new user gets a
+// shared channel with the team in our Slack workspace: the cron creates
+// #opencomputer-<company> (one per work-email domain, one per user for free
+// email), adds the team, and sends a Slack Connect invite to the user's email.
+//
+// Runs on the */5 cron, never in the login path. A row in slack_connect_invites
+// is the claim that a user is handled, so a re-run does nothing; a Slack error
+// leaves the row pending and the next tick retries, up to MAX_ATTEMPTS.
+// Dormant unless SLACK_CONNECT_BOT_TOKEN and SLACK_CONNECT_SINCE are set; SINCE
+// keeps the first deploy from inviting every user who signed up before it.
+
+export interface SlackConnectEnv {
+ OPENCOMPUTER_DB: D1Database;
+ SLACK_CONNECT_BOT_TOKEN?: string;
+ SLACK_CONNECT_SINCE?: string; // unix seconds; only users created at or after it
+ SLACK_CONNECT_TEAM_USER_IDS?: string; // comma-separated Slack user ids added to every channel
+ SLACK_CONNECT_BATCH?: string; // users per tick, default 10
+}
+
+const CHANNEL_PREFIX = "opencomputer-";
+const MAX_ATTEMPTS = 5;
+const DEFAULT_BATCH = 10;
+
+const INTERNAL_DOMAINS = new Set(["digger.dev", "opencomputer.dev"]);
+// Team members' personal Gmail accounts, as in oc-usage-chart's is_internal_email.
+const INTERNAL_GMAIL_LOCALS = new Set(["izalutski", "zij2005", "moehabib9"]);
+
+// Mailbox providers: their users share a domain but not a company, so each gets
+// a channel of their own named after the address.
+const FREE_EMAIL_DOMAINS = new Set([
+ "gmail.com", "googlemail.com", "outlook.com", "hotmail.com", "live.com", "msn.com",
+ "yahoo.com", "ymail.com", "icloud.com", "me.com", "mac.com", "aol.com",
+ "proton.me", "protonmail.com", "pm.me", "gmx.com", "gmx.de", "web.de", "mail.com",
+ "yandex.com", "yandex.ru", "qq.com", "163.com", "126.com", "zoho.com", "fastmail.com",
+ "hey.com", "tutanota.com",
+]);
+
+// Slack errors that will not change on retry: give up on the user at once.
+const PERMANENT_ERRORS = new Set([
+ "invalid_email", "restricted_action", "not_allowed_token_type", "not_paid",
+ "team_not_found", "user_is_restricted", "invite_not_allowed",
+]);
+
+export function isInternalEmail(email: string): boolean {
+ const [local, domain] = splitEmail(email);
+ if (INTERNAL_DOMAINS.has(domain)) return true;
+ if (domain === "gmail.com" || domain === "googlemail.com") {
+ return INTERNAL_GMAIL_LOCALS.has(local.replace(/\+.*$/, "").replace(/\./g, ""));
+ }
+ return false;
+}
+
+export function isFreeEmail(email: string): boolean {
+ return FREE_EMAIL_DOMAINS.has(splitEmail(email)[1]);
+}
+
+// #opencomputer-acme for [email protected]; #opencomputer-jane-doe for
+// [email protected]. Slack channel names: lowercase, digits, - and _, at most
+// 80 characters; room is left for a -N suffix on a name collision.
+export function channelNameFor(email: string): string {
+ const [local, domain] = splitEmail(email);
+ let base: string;
+ if (FREE_EMAIL_DOMAINS.has(domain)) {
+ base = local.replace(/\+.*$/, "");
+ } else {
+ const labels = domain.split(".");
+ labels.pop();
+ if (labels.length > 1 && /^(co|com|org|net|ac|gov|edu)$/.test(labels[labels.length - 1])) labels.pop();
+ base = labels[labels.length - 1] ?? domain;
+ }
+ const slug = base.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
+ return CHANNEL_PREFIX + (slug || "user").slice(0, 80 - CHANNEL_PREFIX.length - 3);
+}
+
+function splitEmail(email: string): [string, string] {
+ const e = email.trim().toLowerCase();
+ const at = e.lastIndexOf("@");
+ return at < 0 ? [e, ""] : [e.slice(0, at), e.slice(at + 1)];
+}
+
+class SlackRateLimited extends Error {}
+
+type SlackResponse = { ok: boolean; error?: string; [k: string]: unknown };
+
+async function slackCall(
+ env: SlackConnectEnv,
+ fetchImpl: typeof fetch,
+ method: string,
+ params: Record<string, string>,
+): Promise<SlackResponse> {
+ const resp = await fetchImpl(`https://slack.com/api/${method}`, {
+ method: "POST",
+ headers: {
+ authorization: `Bearer ${env.SLACK_CONNECT_BOT_TOKEN}`,
+ "content-type": "application/x-www-form-urlencoded",
+ },
+ body: new URLSearchParams(params).toString(),
+ });
+ if (resp.status === 429) throw new SlackRateLimited(method);
+ if (!resp.ok) return { ok: false, error: `http_${resp.status}` };
+ return (await resp.json()) as SlackResponse;
+}
+
+interface Candidate {
+ user_id: string;
+ email: string;
+ created_at: number;
+ channel_name: string | null;
+ channel_id: string | null;
+ attempts: number | null;
+}
+
+export async function runSlackConnectInvites(
+ env: SlackConnectEnv,
+ nowMs: number,
+ fetchImpl: typeof fetch = fetch,
+): Promise<{ invited: number; skipped: number; failed: number; pending: number }> {
+ const counts = { invited: 0, skipped: 0, failed: 0, pending: 0 };
+ const since = Number(env.SLACK_CONNECT_SINCE);
+ if (!env.SLACK_CONNECT_BOT_TOKEN || !Number.isFinite(since) || since <= 0) return counts;
+ const batch = Number(env.SLACK_CONNECT_BATCH) || DEFAULT_BATCH;
+ const nowSec = Math.floor(nowMs / 1000);
+
+ const { results } = await env.OPENCOMPUTER_DB.prepare(
+ `SELECT u.id AS user_id, u.email, u.created_at, s.channel_name, s.channel_id, s.attempts
+ FROM users u
+ LEFT JOIN slack_connect_invites s ON s.user_id = u.id
+ WHERE u.created_at >= ?1 AND (s.user_id IS NULL OR s.status = 'pending')
+ ORDER BY u.created_at ASC
+ LIMIT ?2`,
+ )
+ .bind(since, batch)
+ .all<Candidate>();
+
+ for (const c of results ?? []) {
+ try {
+ const status = await inviteOne(env, fetchImpl, c, nowSec);
+ counts[status]++;
+ } catch (err) {
+ if (err instanceof SlackRateLimited) {
+ console.warn(`slack-connect: rate limited on ${err.message}; resuming next tick`);
+ counts.pending++;
+ break;
+ }
+ throw err;
+ }
+ }
+ if (counts.invited + counts.failed > 0) console.log("slack-connect:", JSON.stringify(counts));
+ return counts;
+}
+
+async function inviteOne(
+ env: SlackConnectEnv,
+ fetchImpl: typeof fetch,
+ c: Candidate,
+ nowSec: number,
+): Promise<"invited" | "skipped" | "failed" | "pending"> {
+ if (c.channel_name === null) {
+ const internal = isInternalEmail(c.email);
+ await env.OPENCOMPUTER_DB.prepare(
+ `INSERT INTO slack_connect_invites (user_id, email, channel_name, status, attempts, created_at)
+ VALUES (?1, ?2, ?3, ?4, 0, ?5) ON CONFLICT(user_id) DO NOTHING`,
+ )
+ .bind(c.user_id, c.email, channelNameFor(c.email), internal ? "skipped" : "pending", nowSec)
+ .run();
+ if (internal) return "skipped";
+ c.channel_name = channelNameFor(c.email);
+ c.attempts = 0;
+ }
+
+ const fail = async (error: string): Promise<"failed" | "pending"> => {
+ const attempts = (c.attempts ?? 0) + 1;
+ const status = PERMANENT_ERRORS.has(error) || attempts >= MAX_ATTEMPTS ? "failed" : "pending";
+ await env.OPENCOMPUTER_DB.prepare(
+ `UPDATE slack_connect_invites SET attempts = ?2, last_error = ?3, status = ?4 WHERE user_id = ?1`,
+ )
+ .bind(c.user_id, attempts, error, status)
+ .run();
+ console.warn(`slack-connect: ${c.user_id} ${error} (attempt ${attempts}, ${status})`);
+ return status;
+ };
+
+ let channelID = c.channel_id;
+ if (!channelID && !isFreeEmail(c.email)) {
+ // A colleague's channel: everyone at a work domain shares one.
+ const shared = await env.OPENCOMPUTER_DB.prepare(
+ `SELECT channel_id FROM slack_connect_invites
+ WHERE lower(substr(email, instr(email, '@') + 1)) = ?1 AND channel_id IS NOT NULL
+ LIMIT 1`,
+ )
+ .bind(splitEmail(c.email)[1])
+ .first<{ channel_id: string }>();
+ channelID = shared?.channel_id ?? null;
+ if (channelID) {
+ await env.OPENCOMPUTER_DB.prepare(`UPDATE slack_connect_invites SET channel_id = ?2 WHERE user_id = ?1`)
+ .bind(c.user_id, channelID)
+ .run();
+ }
+ }
+ if (!channelID) {
+ // A taken name (another free-email user with the same local part, or a
+ // channel made by hand) gets a -2..-9 suffix rather than reusing a stranger's channel.
+ let name = c.channel_name;
+ for (let n = 2; ; n++) {
+ const r = await slackCall(env, fetchImpl, "conversations.create", { name, is_private: "false" });
+ if (r.ok) {
+ channelID = (r.channel as { id: string }).id;
+ break;
+ }
+ if (r.error !== "name_taken" || n > 9) return fail(r.error ?? "create_failed");
+ name = `${c.channel_name}-${n}`;
+ }
+ c.channel_name = name;
+ await env.OPENCOMPUTER_DB.prepare(`UPDATE slack_connect_invites SET channel_id = ?2, channel_name = ?3 WHERE user_id = ?1`)
+ .bind(c.user_id, channelID, name)
+ .run();
+
+ const team = (env.SLACK_CONNECT_TEAM_USER_IDS ?? "").split(",").map((s) => s.trim()).filter(Boolean);
+ if (team.length > 0) {
+ // Not fatal: the invite still goes out, and the team can join by hand.
+ const r = await slackCall(env, fetchImpl, "conversations.invite", {
+ channel: channelID,
+ users: team.join(","),
+ force: "true",
+ });
+ if (!r.ok && r.error !== "already_in_channel") {
+ console.warn(`slack-connect: adding team to ${channelID} failed: ${r.error}`);
+ }
+ }
+ }
+
+ const r = await slackCall(env, fetchImpl, "conversations.inviteShared", {
+ channel: channelID,
+ emails: c.email,
+ });
+ if (!r.ok) return fail(r.error ?? "invite_failed");
+ await env.OPENCOMPUTER_DB.prepare(
+ `UPDATE slack_connect_invites SET status = 'invited', invite_id = ?2, invited_at = ?3, last_error = NULL
+ WHERE user_id = ?1`,
+ )
+ .bind(c.user_id, typeof r.invite_id === "string" ? r.invite_id : null, nowSec)
+ .run();
+ return "invited";
+}