Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Slack on personal Clouds: the app side (#6061)
Milind Soni19ea665585d5
diff --git a/docs/team-slack.md b/docs/team-slack.mdindex 27ef933087..d47f68a9eb 100644--- a/docs/team-slack.md+++ b/docs/team-slack.md@@ -6,8 +6,11 @@ there), which works out the team member who wrote and hands each message to thatfor that member**. This page is the Cloud's side: three routes the Admin calls, and one signed report back. The Slack bottoken never reaches this machine, and this machine never talks to Slack.-Only a Team Cloud (`OMB_CLOUD_ROLE=team`, [team-cloud.md](team-cloud.md)) has any of it. Everywhere else every route-below answers 404 with no `code`, and nothing is reported anywhere.+A Team Cloud (`OMB_CLOUD_ROLE=team`, [team-cloud.md](team-cloud.md)) has all of it. A My Cloud, one person's own+(`OMB_CLOUD_ROLE=home`), has the same routes and reports for its owner: see+[On a My Cloud](#on-a-my-cloud-one-persons-own) for what differs. Everywhere else (the desktop app, a self-hosted+server) every route below answers 404 with no `code`, and nothing is reported anywhere. Which plans may connect Slack+is the Admin's to decide: the app checks no plan.## A Slack message is the member's own request@@ -57,6 +60,26 @@ A channel's conversation is also recorded as from Slack where its sharing is (`c"slack"`). It is never the chat its bot opens to: the bot's shared chat stays the shared chat, however often Slackthreads are written in after it.+## On a My Cloud, one person's own++The Admin opens the session through the same signed pairing with no member's claim, so it is the owner's own session,+as their app's is. The three routes, their answers, the idempotent `id`, the queue, Stop and the signed reports are the+ones on this page. What differs, because there is one person and no team:++- **Who asks.** The owner: a session with full access, whichever one the Admin opened (a new session per message is the+ same person). Any other session (a guest's) answers `404 not_a_member`.+- **Both audiences are the owner's ordinary conversation.** `team` and `member` each open a conversation as the owner+ opens one in the app, and the line is their own request through the same `acceptDirectSend`. Nothing is shared+ (`conversation-shares.json` is a Team Cloud's), no audience is compared, and `conversationId` continues any+ conversation the owner can write in, whichever audience the request names. There is no `bot_private`.+- **Bots.** `GET /api/slack/team/bots` lists every bot, each `shared: true`: all are the owner's, in a channel as in a+ direct message. `{ default: true }` is the Cloud's MausBot, else the first bot.+- **Where it came from.** The titles are the same. A conversation a channel's message opened is still never the chat+ its bot opens to; with no sharing to record it in, its id is kept in `team-slack-messages.json` (`channels`), after+ its messages are dropped. A direct message's conversation is as any the owner opens, so the one they last wrote in+ is the chat the bot opens to.+- **Nobody leaves.** Nothing is forgotten for a person; the record keeps its week, month and 2,000.+## The routesEach takes the member's session, as a bearer. `server/routes/team-slack.ts`; the wire shapes are in@@ -107,8 +130,9 @@ answers; a `running` nobody answered is not. `{ done: true }` and a 404 end thethe Admin may put in its answer is not read: only a member's own session stops a run.`team-slack-messages.json` (0600) keeps each message's id, its person's key, bot, conversation, audience and state: a-week after it is over, a month at most, 2,000 at most. Never the words, the channel, the Slack user or an address. It-is left out of a workspace export.+week after it is over, a month at most, 2,000 at most. Never the words, the channel, the Slack user or an address. On+a My Cloud it also keeps the ids of the conversations a channel opened (`channels`, 2,000 at most). It is left out of+a workspace export.## Cardsdiff --git a/docs/verification/README.md b/docs/verification/README.mdindex 2b7899d5fe..846dfb102b 100644--- a/docs/verification/README.md+++ b/docs/verification/README.md@@ -227,7 +227,8 @@ route module, and stale-response isolation.The [Slack for Team Clouds fixture](team-slack.md) checks a Slack message handed over with a member's own session:a channel's shared conversation, a direct message's private chat, who may ask and stop, and the signed reports a-stand-in Admin takes. It reaches no Slack workspace and no real Admin.+stand-in Admin takes; and the same on a My Cloud, where both are the owner's ordinary conversations. It reaches no+Slack workspace and no real Admin.The [chat and settings polish fixture](chat-polish.md) exercises attachmentgalleries, opt-in video playback, persisted tool details, and responsive settingsdiff --git a/docs/verification/team-slack.md b/docs/verification/team-slack.mdindex 8cabc8015a..19e08128fe 100644--- a/docs/verification/team-slack.md+++ b/docs/verification/team-slack.md@@ -11,13 +11,15 @@ Slack's own context with the bootstrap secret, and whether the message is this t```shpnpm exec vitest run server/team-slack.test.tspnpm exec vitest run server/cloud-team-slack.e2e.test.ts+pnpm exec vitest run server/cloud-personal-slack.e2e.test.ts````server/team-slack.test.ts` holds the parts with no server: the signature against the value the Admin's own functiongives, the message's shape, what a conversation's records say of a run (`teamSlackPhase` in`server/host/team-slack-host.ts`: waiting in the queue, working, an open approval or question, settled with its finalreply, stopped, failed when the next request began first, a line answered together with a later one), the record of-messages across a restart and when someone leaves, and how each answer of the Admin's is read.+messages across a restart and when someone leaves, which conversations a channel opened on a My Cloud (kept after+their messages are dropped, and never written by a Team Cloud), and how each answer of the Admin's is read.`server/cloud-team-slack.e2e.test.ts` launches a Team Cloud (`scripts/testing/cloud-send-fixture.ts`) with an Owner, anAdmin and two Users, the synthetic Claude CLI, and five bots: one everyone can chat with, one a User owns that asks@@ -57,12 +59,40 @@ before it acts, one only its owner uses, one everyone can only view, and one a U- **When the member leaves** (`POST /api/cloud/team/member-left`), their direct message's conversation and privatelayer are gone, for them too when they join again; what the Cloud kept of their Slack messages is gone; the channel'sconversation stays.-- **Off a Team Cloud**, on a My Cloud and on a desktop's own server, all three routes answer 404 with no code.+- **Off a Cloud**, on a desktop's own server, all three routes answer 404 with no code.Their own connections and saved secrets are not driven here: a channel's conversation has the `team` audience, and`server/cloud-team-per-person.e2e.test.ts` and `server/cloud-team-member-secrets.e2e.test.ts` prove what a conversationof that audience is given.+## On a My Cloud++`server/cloud-personal-slack.e2e.test.ts` launches a My Cloud (`scripts/testing/cloud-send-fixture.ts`, no team) with+its MausBot and one more bot, the synthetic Claude CLI, and the same stand-in Admin. The Admin's session is the owner's:+the signed pairing with the label "Slack (MausBot Cloud)" and no member's claim. It proves:++- **The list** (`GET /api/slack/team/bots`) is every bot, each `shared: true`; a request with no session is refused.+- **A channel message** (`audience: "team"`) is the owner's own line in a new conversation: `202`, the reports+ `running` then `completed` with the reply, the conversation titled "Slack #sales: …" and not shared, the line not+ relayed, the engine's prompt with nothing relayed or information only, and the bot still opening to its own chat.+- **The same id again** answers as the first did, while the run works, after it ended, and from another session of the+ owner's: one line, one reply, one conversation, one `completed`.+- **A direct message** (`audience: "member"`, `{ default: true }`) is a conversation with the Cloud's MausBot titled+ "Slack DM: …"; `{ name }` ignores case; a direct message's conversation becomes the chat its bot opens to as any+ conversation the owner writes in does, and a channel's never does. A thread continues by `conversationId` with either+ audience; an id that names nothing answers `409 no_such_conversation`, a bot that does not exist `404 no_such_bot`.+- **A line written while the bot works** is taken (`202`), waits, and runs after as its own turn: both are reported+ `completed`, each with its own reply.+- **Stop** ends the owner's run and is reported `stopped`; an id never taken is 404; with no session it is refused.+- **Every report** verifies in Slack's context with the bootstrap secret and under no other context of this Cloud's.+ What the Cloud keeps holds no word of a message or an answer, no channel's name and no Slack user; it names the+ channel's conversation by id and not the direct message's, and no sharing file is written.+- **An install that is no Cloud** (the desktop's own server) answers 404 with no code on all three routes.++Not driven on a My Cloud: an approval reported as `waiting`, a final report sent again after a 503, and a guest's+session (a My Cloud revokes every session that is not its owner's at each boot). Those paths are the same code the+Team Cloud's test drives.+## What only a real Slack workspace and the real Admin proveThat Slack delivers the events, that the Admin matches a Slack user to a member and opens their session, that itsdiff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjsindex 9e427718a1..32c1ff7cb8 100644--- a/scripts/ci-scope.mjs+++ b/scripts/ci-scope.mjs@@ -77,6 +77,7 @@ export const VITEST_SUBSETS = {"server/cloud-lending-memory.e2e.test.ts","server/cloud-lending.e2e.test.ts","server/cloud-lent-mcp.e2e.test.ts",+ "server/cloud-personal-slack.e2e.test.ts","server/cloud-send-kinds.e2e.test.ts","server/cloud-send-move.e2e.test.ts","server/cloud-send-rooms.e2e.test.ts",diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.tsindex 80aa18b789..e6a08732bf 100644--- a/scripts/ci-scope.test.ts+++ b/scripts/ci-scope.test.ts@@ -217,6 +217,7 @@ describe("CI outputs", () => {"server/cloud-lending-memory.e2e.test.ts","server/cloud-lending.e2e.test.ts","server/cloud-lent-mcp.e2e.test.ts",+ "server/cloud-personal-slack.e2e.test.ts","server/cloud-send-kinds.e2e.test.ts","server/cloud-send-move.e2e.test.ts","server/cloud-send-rooms.e2e.test.ts",diff --git a/scripts/testing/cloud-send-fixture.ts b/scripts/testing/cloud-send-fixture.tsindex 29ba7694db..2ed0e80c75 100644--- a/scripts/testing/cloud-send-fixture.ts+++ b/scripts/testing/cloud-send-fixture.ts@@ -23,6 +23,7 @@ import { freePortBlock } from "../../server/testing/ports.ts";const SERVER_DIR = fileURLToPath(new URL("../../server/", import.meta.url));export const CLOUD_HOST = "omb-t-5e6d7c8b9a0f.fly.dev";+const CLOUD_MACHINE_ID = "7c1d2e3f-4a5b-4c6d-8e7f-9a0b1c2d3e4f";const EDGE = { host: CLOUD_HOST, "x-forwarded-for": "203.0.113.9", "x-forwarded-proto": "https", origin: `https://${CLOUD_HOST}` };const parse = (text: string) => { try { return JSON.parse(text); } catch { return null; } };@@ -33,6 +34,9 @@ export interface CloudSendFixture {/** The owner's own device on My Cloud, through the edge: what the window's Cloud session is. */owner: string;ownerCapability: string;+ /** What the Admin signs with and My Cloud reports with, and the machine id My Cloud reports as. */+ secret: string;+ cloudMachineId: string;edge: typeof EDGE;/** Every answer either server gave, for the no-secret check. */answers: string[];@@ -254,7 +258,7 @@ await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-cllet desktop = await startDesktop();const cloudPort = await freePortBlock([0, 1]);const cloudBase = `http://127.0.0.1:${cloudPort}`;- const startCloud = (more: NodeJS.ProcessEnv = {}) => start("cloud", { OMB_CLOUD_ROLE: "home", OMB_CLOUD_MACHINE_ID: "7c1d2e3f-4a5b-4c6d-8e7f-9a0b1c2d3e4f", OMB_CLOUD_ADMIN_URL: "https://cloud.example.test",+ const startCloud = (more: NodeJS.ProcessEnv = {}) => start("cloud", { OMB_CLOUD_ROLE: "home", OMB_CLOUD_MACHINE_ID: CLOUD_MACHINE_ID, OMB_CLOUD_ADMIN_URL: "https://cloud.example.test",OMB_CLOUD_BOOTSTRAP_SECRET: secret, OMB_PUBLIC_URL: `https://${CLOUD_HOST}`, ...(broker ? { OMB_COMPOSIO_BROKER_URL: broker.url } : {}), ...cloudEnv, ...more }, cloudPort, [], false, cloudOnePasswordToken, 0, cloudEngine, cloudSignedIn);let cloud = await startCloud();@@ -549,7 +553,7 @@ await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-cllisten();return {- root, desktopBase, cloudBase, get owner() { return owner; }, ownerCapability, edge: EDGE, answers, labels, logs: () => logs, local, onCloud, desktopInstallation,+ root, desktopBase, cloudBase, get owner() { return owner; }, ownerCapability, secret, cloudMachineId: CLOUD_MACHINE_ID, edge: EDGE, answers, labels, logs: () => logs, local, onCloud, desktopInstallation,account, journalFile, spies, teamJournalFile,get beforeTeamJournalWrite() { return fixture.beforeTeamJournalWrite; },set beforeTeamJournalWrite(hook) { fixture.beforeTeamJournalWrite = hook; },diff --git a/server/cloud-personal-slack.e2e.test.ts b/server/cloud-personal-slack.e2e.test.tsnew file mode 100644index 0000000000..972ff3218a--- /dev/null+++ b/server/cloud-personal-slack.e2e.test.ts@@ -0,0 +1,315 @@+// Slack on a personal Cloud (docs/team-slack.md): a My Cloud, with no team. The Admin's part is played here: a session+// opened for the owner through the signed pairing (label "Slack (MausBot Cloud)"), the three routes called with it,+// and a stand-in Admin that takes the Cloud's signed reports and checks them as the real one does. A channel message+// and a direct message each become an ordinary conversation of the owner's. Disposable homes and the synthetic Claude+// CLI; no Slack and no real Admin are reached.+import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";+import { readFileSync, rmSync, writeFileSync } from "node:fs";+import { createServer, type Server } from "node:http";+import type { AddressInfo } from "node:net";+import { join } from "node:path";+import { afterAll, afterEach, beforeAll, expect, it } from "vitest";++import { launchCloudSendFixture, type CloudSendFixture } from "../scripts/testing/cloud-send-fixture.ts";+import { cloudRequestSignature } from "./cloud-home.ts";+import { teamRosterSignature } from "./cloud-team-roster.ts";+import { TEAM_SLACK_FILE, TEAM_SLACK_REPORT_PATH, teamSlackSignature } from "./team-slack.ts";+import { hostTimeout } from "./testing/host-timeout.ts";++const SLACK_LABEL = "Slack (MausBot Cloud)";+const ENGINE = `const { existsSync } = process.getBuiltinModule("node:fs");+const dir = process.env.FAKE_CLAUDE_FIXTURE_DIR;+process.env.FAKE_CLAUDE_DUMP = dir + "/dump.json";+process.env.FAKE_CLAUDE_TOOL_CALLS_FILE = dir + "/tool-calls.json";+process.env.FAKE_CLAUDE_RELEASE = dir + "/release";+process.env.FAKE_CLAUDE_MARKER_REPLIES = dir + "/markers.json";`;+const HOLD = { name: "Bash", input: { command: "gh run watch 42" }, hold: true };+/** A turn's prompt can carry earlier lines of its conversation, and the engine answers the first marker it finds: later asks first. */+const ANSWERS: Record<string, string> = {+ "And the week after?": "The week after is **quiet**.",+ "Then the invoices?": "The invoices follow.",+ "What ships on Friday?": "The **invoice run** ships on Friday.",+ "Private notes please": "Noted privately.",+ "Is the report out?": "The report is out.",+ "Watch the build": "The build is green.",+};++type Report = { id: string; status: string; text?: string; conversationId?: string; bot?: { id: string; name: string }; openUrl?: string };+type Task = { threadId: string; title: string; private?: boolean; shared?: boolean; busy?: boolean };+type Bot = { id: string; name: string; threadId: string; mainThreadId?: string; busy?: boolean; defaultBot?: { person?: string }; tasks?: Task[] };+type Row = { id: string; role: string; kind: string; text?: string; relayed?: boolean; tool?: { name: string }; stoppedBy?: { name: string } };++const admin = {+ /** Every request to the report path, as the real Admin would judge it. */+ taken: [] as { report: Report; headers: Record<string, string>; raw: string }[],+ refused: 0,+ /** Message ids this Cloud's Admin handed over; any other id is not this Cloud's. */+ known: new Set<string>(),+};+let adminServer: Server, fx: CloudSendFixture;+let owner = "", ownerSlack = "";+let scout: Bot, mausbot: Bot;++const file = (name: string) => join(fx.root, "cloud", name);+const dataFile = (name: string) => join(fx.root, "cloud", ".openmausbot", name);+async function as(token: string | null, method: string, path: string, body?: unknown): Promise<{ status: number; body: any }> {+ const response = await fetch(`${fx.cloudBase}${path}`, { method, headers: { ...fx.edge, ...(token ? { authorization: `Bearer ${token}` } : {}),+ ...(body === undefined ? {} : { "content-type": "application/json" }) }, body: body === undefined ? undefined : JSON.stringify(body) });+ const text = await response.text();+ try { return { status: response.status, body: JSON.parse(text) }; } catch { return { status: response.status, body: null }; }+}+const bots = async () => (await as(owner, "GET", "/api/bots?messages=0")).body.bots as Bot[];+const botOf = async (botId: string) => (await bots()).find((bot) => bot.id === botId)!;+const taskOf = async (botId: string, threadId: string) => (await botOf(botId)).tasks?.find((task) => task.threadId === threadId);+const rows = async (threadId: string) => ((await as(owner, "GET", `/api/threads/${threadId}/messages?limit=200`)).body.messages ?? []) as Row[];+const idle = async () => (await bots()).every((bot) => !bot.busy && !(bot.tasks ?? []).some((task) => task.busy));+const statuses = (id: string) => admin.taken.filter((entry) => entry.report.id === id).map((entry) => entry.report.status);+const lastReport = (id: string) => admin.taken.findLast((entry) => entry.report.id === id)!.report;+const until = (done: () => Promise<boolean> | boolean, timeout = 60_000) => expect.poll(done, { timeout: hostTimeout(timeout), interval: 100 }).toBe(true);+const finished = (id: string, status = "completed") => until(() => statuses(id).at(-1) === status);++type Ask = { audience: "team" | "member"; bot?: { id: string } | { name: string } | { default: true }; conversationId?: string | null; text: string; id?: string; channelName?: string };+/** One Slack message as the Admin delivers it, with the session it opened for the owner. */+async function slack(token: string | null, ask: Ask) {+ const id = ask.id ?? randomUUID();+ admin.known.add(id);+ const direct = ask.audience === "member";+ const answer = await as(token, "POST", "/api/slack/team/messages", { v: 1, id, audience: ask.audience, bot: ask.bot ?? { id: scout.id }, conversationId: ask.conversationId ?? null, text: ask.text,+ slack: { workspace: "T0HOME", channel: direct ? "D0OWNER" : "C0SALES", threadTs: "1731662000.000100", messageTs: "1731662000.000100", user: "U0OWNER", ...(ask.channelName ? { channelName: ask.channelName } : {}) } });+ return { id, ...answer };+}+const stop = (token: string | null, id: string) => as(token, "POST", `/api/slack/team/messages/${id}/stop`, { v: 1 });+const dump = () => JSON.parse(readFileSync(file("dump.json"), "utf8")) as { prompt?: unknown };++beforeAll(async () => {+ adminServer = createServer((req, res) => {+ const chunks: Buffer[] = [];+ req.on("data", (chunk) => chunks.push(chunk));+ req.on("end", () => {+ const raw = Buffer.concat(chunks).toString("utf8"), headers = req.headers as Record<string, string>;+ const answer = (status: number, body: unknown) => { res.writeHead(status, { "content-type": "application/json" }); res.end(JSON.stringify(body)); };+ if (req.url !== TEAM_SLACK_REPORT_PATH || req.method !== "POST") return answer(404, { error: "not found" });+ const machine = headers["x-omb-cloud-machine"] ?? "", timestamp = headers["x-omb-cloud-timestamp"] ?? "", nonce = headers["x-omb-cloud-nonce"] ?? "";+ const presented = /^v1=([A-Za-z0-9_-]{43})$/.exec(headers["x-omb-cloud-signature"] ?? "")?.[1];+ const expected = Buffer.from(teamSlackSignature(fx.secret, machine, timestamp, nonce, raw), "base64url"), given = Buffer.from(presented ?? "", "base64url");+ if (machine !== fx.cloudMachineId || Math.abs(Date.now() / 1000 - Number(timestamp)) > 300 || !/^[A-Za-z0-9_-]{16,128}$/.test(nonce) || given.length !== expected.length || !timingSafeEqual(given, expected)) {+ admin.refused++;+ return answer(401, { error: "That request isn't signed by a Cloud." });+ }+ const report = JSON.parse(raw) as Report & { v: number };+ if (!admin.known.has(report.id)) return answer(404, { error: "There is no such message.", code: "unknown_message" });+ const over = admin.taken.some((entry) => entry.report.id === report.id && ["completed", "failed", "stopped"].includes(entry.report.status));+ admin.taken.push({ report, headers, raw });+ answer(200, over ? { ok: true, done: true } : { ok: true });+ });+ });+ await new Promise<void>((resolve) => adminServer.listen(0, "127.0.0.1", resolve));+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-slack-${randomBytes(8).toString("hex")}`, cloudEngine: ENGINE,+ cloudEnv: { OMB_BOT_BOX: "0", FIXTURE_ADMIN_STAND_IN: `http://127.0.0.1:${(adminServer.address() as AddressInfo).port}` } });+ writeFileSync(file("markers.json"), JSON.stringify(ANSWERS));+ writeFileSync(file("tool-calls.json"), "[]");+ writeFileSync(file("release"), "");+ owner = fx.owner;+ // The Admin's session for Slack: the same signed pairing as the owner's app, with no member's claim.+ const paired = await as(null, "POST", "/api/auth/pair", { code: (await fx.grant(SLACK_LABEL)).code });+ expect(paired.status, JSON.stringify(paired.body)).toBe(200);+ ownerSlack = paired.body.token;+ const created = await as(owner, "POST", "/api/bots", { name: "Scout" });+ expect(created.status, JSON.stringify(created.body)).toBe(201);+ scout = created.body.bot as Bot;+ mausbot = (await bots()).find((bot) => bot.defaultBot)!;+ expect(mausbot, "a My Cloud has its MausBot").toBeTruthy();+}, hostTimeout(180_000));++afterEach(async () => {+ writeFileSync(file("release"), "");+ writeFileSync(file("tool-calls.json"), "[]");+ await until(idle, 90_000);+}, hostTimeout(120_000));++afterAll(async () => {+ await fx?.close();+ await new Promise((resolve) => adminServer?.close(resolve));+});++let channelThread = "", directThread = "";++it("the owner's session lists every bot, each usable in a channel; no session is refused", async () => {+ const mine = await as(ownerSlack, "GET", "/api/slack/team/bots");+ expect(mine.status, JSON.stringify(mine.body)).toBe(200);+ const listed = mine.body.bots as { id: string; name: string; shared: boolean }[];+ expect(listed.find((bot) => bot.id === scout.id)).toEqual({ id: scout.id, name: "Scout", shared: true });+ expect(listed.find((bot) => bot.id === mausbot.id)).toEqual({ id: mausbot.id, name: mausbot.name, shared: true });+ for (const refused of [await as(null, "GET", "/api/slack/team/bots"), await slack(null, { audience: "team", text: "hello" })]) {+ expect(refused.status).toBe(403);+ expect(refused.body.bots ?? refused.body.accepted).toBeUndefined();+ }+});++it("a channel message is the owner's own request in an ordinary conversation, reported running then completed with the reply", async () => {+ rmSync(file("dump.json"), { force: true });+ const sent = await slack(ownerSlack, { audience: "team", text: "What ships on Friday?", channelName: "sales" });+ expect(sent.status, JSON.stringify(sent.body)).toBe(202);+ expect(sent.body).toEqual({ accepted: true, conversationId: expect.any(String), bot: { id: scout.id, name: "Scout" }, openUrl: expect.stringMatching(/^https:\/\/[^/]+\/\?thread=[\w-]+&bot=[\w-]+$/) });+ channelThread = sent.body.conversationId;+ expect(channelThread).not.toBe(scout.threadId);+ await finished(sent.id);+ expect(statuses(sent.id)).toEqual(["running", "completed"]);+ expect(lastReport(sent.id)).toEqual({ v: 1, id: sent.id, status: "completed", text: ANSWERS["What ships on Friday?"], conversationId: channelThread, bot: { id: scout.id, name: "Scout" }, openUrl: sent.body.openUrl });++ // The owner's app is sent it as any conversation of theirs, named for where it came from; nothing is shared.+ const task = await taskOf(scout.id, channelThread);+ expect(task).toMatchObject({ title: "Slack #sales: What ships on Friday?" });+ expect(task!.shared).toBeUndefined();+ // The chat the bot opens to stays that chat: a Slack channel's conversation never takes its place.+ expect((await botOf(scout.id)).mainThreadId).toBe(scout.threadId);+ const thread = await rows(channelThread);+ const line = thread.find((row) => row.role === "user")!;+ expect(line).toMatchObject({ text: "What ships on Friday?" });+ expect(line.relayed).toBeUndefined();+ expect(thread.filter((row) => row.role === "bot" && row.kind === "text").map((row) => row.text)).toEqual([ANSWERS["What ships on Friday?"]]);+ // The owner's own line with their own authority: never the relayed, information-only kind.+ const prompt = JSON.stringify(dump().prompt);+ expect(prompt).toContain("What ships on Friday?");+ expect(prompt).not.toContain("relayed");+ expect(prompt).not.toContain("information only");+}, hostTimeout(120_000));++it("the same id again starts nothing new and answers as the first did", async () => {+ const first = await slack(ownerSlack, { audience: "team", text: "Is the report out?" });+ expect(first.status, JSON.stringify(first.body)).toBe(202);+ const again = await slack(ownerSlack, { audience: "team", text: "Is the report out?", id: first.id });+ expect(again.status).toBe(202);+ expect(again.body).toEqual(first.body);+ await finished(first.id);+ // The owner's app session is the same person: the Admin may open a new session for each message.+ const afterwards = await slack(owner, { audience: "team", text: "Is the report out?", id: first.id });+ expect(afterwards.body).toEqual(first.body);+ await until(idle);+ const thread = await rows(first.body.conversationId);+ expect(thread.filter((row) => row.role === "user")).toHaveLength(1);+ expect(thread.filter((row) => row.role === "bot" && row.kind === "text")).toHaveLength(1);+ expect((await botOf(scout.id)).tasks!.map((task) => task.title).filter((title) => title.startsWith("Slack channel: Is the report out"))).toEqual(["Slack channel: Is the report out?"]);+ expect(statuses(first.id).filter((status) => status === "completed")).toHaveLength(1);+}, hostTimeout(120_000));++it("a direct message is an ordinary conversation too, with the owner's MausBot by default; either audience continues a conversation", async () => {+ const sent = await slack(ownerSlack, { audience: "member", bot: { default: true }, text: "Private notes please" });+ expect(sent.status, JSON.stringify(sent.body)).toBe(202);+ expect(sent.body.bot).toEqual({ id: mausbot.id, name: mausbot.name });+ directThread = sent.body.conversationId;+ await finished(sent.id);+ expect(lastReport(sent.id).text).toBe(ANSWERS["Private notes please"]);+ expect(await taskOf(mausbot.id, directThread)).toMatchObject({ title: "Slack DM: Private notes please" });+ expect((await rows(directThread)).find((row) => row.role === "user")).toMatchObject({ text: "Private notes please" });++ const named = await slack(ownerSlack, { audience: "member", bot: { name: "SCOUT" }, conversationId: null, text: "Is the report out?" });+ expect(named.status, JSON.stringify(named.body)).toBe(202);+ expect(named.body.bot).toEqual({ id: scout.id, name: "Scout" });+ await finished(named.id);+ // A direct message's conversation is as any the owner opens: the one they last wrote in is the chat the bot opens to.+ expect((await botOf(scout.id)).mainThreadId).toBe(named.body.conversationId);++ // There is one person and no audience to tell apart: a thread continues by its id whichever audience is named.+ const more = await slack(ownerSlack, { audience: "team", conversationId: channelThread, text: "And the week after?" });+ expect(more.status, JSON.stringify(more.body)).toBe(202);+ expect(more.body.conversationId).toBe(channelThread);+ await finished(more.id);+ expect(lastReport(more.id).text).toBe(ANSWERS["And the week after?"]);+ const crossed = await slack(ownerSlack, { audience: "member", conversationId: channelThread, text: "Then the invoices?" });+ expect(crossed.status, JSON.stringify(crossed.body)).toBe(202);+ expect(crossed.body.conversationId).toBe(channelThread);+ await finished(crossed.id);+ expect((await rows(channelThread)).filter((row) => row.role === "user").map((row) => row.text)).toEqual(["What ships on Friday?", "And the week after?", "Then the invoices?"]);++ const gone = await slack(ownerSlack, { audience: "team", conversationId: "t_does_not_exist", text: "nowhere" });+ expect(gone.status).toBe(409);+ expect(gone.body).toEqual({ error: "No such conversation.", code: "no_such_conversation" });+ const missing = await slack(ownerSlack, { audience: "team", bot: { id: "bot_that_never_was" }, text: "hello" });+ expect(missing.status).toBe(404);+ expect(missing.body).toEqual({ error: "No such bot.", code: "no_such_bot" });+ // The channel's conversation, though written in last, is still not that chat.+ expect((await botOf(scout.id)).mainThreadId).toBe(named.body.conversationId);+}, hostTimeout(180_000));++it("a line written while the bot works waits in the queue and runs after, as its own turn", async () => {+ await until(idle);+ rmSync(file("release"), { force: true });+ writeFileSync(file("tool-calls.json"), JSON.stringify([HOLD]));+ const first = await slack(ownerSlack, { audience: "team", text: "Watch the build" });+ expect(first.status, JSON.stringify(first.body)).toBe(202);+ const thread = first.body.conversationId as string;+ await until(async () => (await rows(thread)).some((row) => row.kind === "activity" && JSON.stringify(row.tool ?? {}).includes("gh run watch 42")));+ writeFileSync(file("tool-calls.json"), "[]");+ const second = await slack(ownerSlack, { audience: "team", conversationId: thread, text: "Is the report out?" });+ expect(second.status, JSON.stringify(second.body)).toBe(202);+ expect(second.body.conversationId).toBe(thread);+ expect((await rows(thread)).filter((row) => row.role === "user")).toHaveLength(1);+ expect(statuses(first.id)).toEqual(["running"]);+ writeFileSync(file("release"), "");+ await finished(first.id);+ await finished(second.id);+ expect(lastReport(first.id).text).toBe(ANSWERS["Watch the build"]);+ expect(lastReport(second.id).text).toBe(ANSWERS["Is the report out?"]);+ expect((await rows(thread)).filter((row) => row.role === "user").map((row) => row.text)).toEqual(["Watch the build", "Is the report out?"]);+}, hostTimeout(180_000));++it("Stop from Slack ends the owner's run and is reported; an id never taken is 404", async () => {+ await until(idle);+ rmSync(file("release"), { force: true });+ writeFileSync(file("tool-calls.json"), JSON.stringify([HOLD]));+ const sent = await slack(ownerSlack, { audience: "member", text: "What ships on Friday?" });+ expect(sent.status, JSON.stringify(sent.body)).toBe(202);+ const thread = sent.body.conversationId as string;+ await until(async () => (await rows(thread)).some((row) => row.kind === "activity" && JSON.stringify(row.tool ?? {}).includes("gh run watch 42")));+ writeFileSync(file("tool-calls.json"), "[]");+ expect((await taskOf(scout.id, thread))?.busy).toBe(true);+ expect((await stop(ownerSlack, randomUUID())).status).toBe(404);+ expect((await stop(null, sent.id)).status).toBe(403);+ expect(statuses(sent.id)).toEqual(["running"]);++ const stopped = await stop(ownerSlack, sent.id);+ expect(stopped.status, JSON.stringify(stopped.body)).toBe(200);+ expect(typeof stopped.body.stopped).toBe("boolean");+ await finished(sent.id, "stopped");+ await until(async () => !(await taskOf(scout.id, thread))?.busy);+ expect((await rows(thread)).filter((row) => row.role === "bot" && row.kind === "text")).toEqual([]);+ expect((await stop(ownerSlack, sent.id)).body).toEqual({ stopped: true });+}, hostTimeout(180_000));++it("every report is signed in Slack's own context with the bootstrap secret, and what is kept holds no words", async () => {+ expect(admin.refused).toBe(0);+ expect(admin.taken.length).toBeGreaterThan(10);+ for (const { headers, raw } of admin.taken) {+ const [timestamp, nonce, signature] = [headers["x-omb-cloud-timestamp"]!, headers["x-omb-cloud-nonce"]!, headers["x-omb-cloud-signature"]!];+ expect(headers["x-omb-cloud-machine"]).toBe(fx.cloudMachineId);+ expect(signature).toBe(`v1=${teamSlackSignature(fx.secret, fx.cloudMachineId, timestamp, nonce, raw)}`);+ expect(signature).not.toBe(`v1=${teamRosterSignature(fx.secret, fx.cloudMachineId, timestamp, nonce, raw)}`);+ expect(signature).not.toBe(`v1=${cloudRequestSignature(fx.secret, timestamp, nonce, "POST", TEAM_SLACK_REPORT_PATH, raw)}`);+ }+ const base = `http://127.0.0.1:${(adminServer.address() as AddressInfo).port}${TEAM_SLACK_REPORT_PATH}`;+ const { raw } = admin.taken[0]!;+ const send = (sign: (timestamp: string, nonce: string) => string) => {+ const timestamp = String(Math.floor(Date.now() / 1000)), nonce = randomBytes(18).toString("base64url");+ return fetch(base, { method: "POST", body: raw, headers: { "content-type": "application/json", "x-omb-cloud-machine": fx.cloudMachineId, "x-omb-cloud-timestamp": timestamp, "x-omb-cloud-nonce": nonce, "x-omb-cloud-signature": `v1=${sign(timestamp, nonce)}` } });+ };+ expect((await send((timestamp, nonce) => teamSlackSignature(randomBytes(32).toString("base64url"), fx.cloudMachineId, timestamp, nonce, raw))).status).toBe(401);+ expect((await send((timestamp, nonce) => teamSlackSignature(fx.secret, fx.cloudMachineId, timestamp, nonce, raw))).status).toBe(200);+ const kept = readFileSync(dataFile(TEAM_SLACK_FILE), "utf8");+ for (const words of [...Object.keys(ANSWERS), ...Object.values(ANSWERS), "C0SALES", "U0OWNER", "sales"]) expect(kept).not.toContain(words);+ // Which conversations a channel opened is kept there, by id: the conversation a direct message opened is not among them.+ const channels = (JSON.parse(kept) as { channels?: string[] }).channels ?? [];+ expect(channels).toContain(channelThread);+ expect(channels).not.toContain(directThread);+ // Nothing was shared: sharing is a Team Cloud's.+ expect(() => readFileSync(dataFile("conversation-shares.json"), "utf8")).toThrow();+}, hostTimeout(60_000));++it("an install that is no Cloud answers 404 on every route", async () => {+ for (const [method, path, body] of [["GET", "/api/slack/team/bots", undefined], ["POST", "/api/slack/team/messages", { v: 1, id: randomUUID(), audience: "team", bot: { default: true }, conversationId: null, text: "hello" }],+ ["POST", `/api/slack/team/messages/${randomUUID()}/stop`, { v: 1 }]] as const) {+ const answer = await fx.local(method, path, body);+ expect(answer.status, `${method} ${path}`).toBe(404);+ expect(answer.body.code).toBeUndefined();+ }+}, hostTimeout(60_000));diff --git a/server/cloud-team-slack.e2e.test.ts b/server/cloud-team-slack.e2e.test.tsindex 2186bbf437..f08190ebc9 100644--- a/server/cloud-team-slack.e2e.test.ts+++ b/server/cloud-team-slack.e2e.test.ts@@ -438,8 +438,8 @@ it("when a member leaves, their direct-message conversations go with their privaexpect((await rows(tom, channelThread)).filter((row) => row.role === "user").length).toBeGreaterThanOrEqual(3);}, hostTimeout(120_000));-it("off a Team Cloud every route answers 404", async () => {- for (const ask of [fx.onCloud, fx.local]) {+it("off a Cloud, on a desktop's own server, every route answers 404", async () => {+ for (const ask of [fx.local]) {for (const [method, path, body] of [["GET", "/api/slack/team/bots", undefined], ["POST", "/api/slack/team/messages", { v: 1, id: randomUUID(), audience: "team", bot: { default: true }, conversationId: null, text: "hello" }],["POST", `/api/slack/team/messages/${randomUUID()}/stop`, { v: 1 }]] as const) {const answer = await ask(method, path, body);diff --git a/server/host/team-slack-host.ts b/server/host/team-slack-host.tsindex 0c424d7087..96e4cc06a7 100644--- a/server/host/team-slack-host.ts+++ b/server/host/team-slack-host.ts@@ -3,6 +3,8 @@// of the audience the message asks for. A Slack channel thread is a conversation its writer opened and shared with the// team at once; a Slack direct message is their private chat with the bot. What the run does is read from the// conversation's own records as they change, and reported to the Admin.+// On a personal Cloud (no team) the asker is the owner's session, and a channel's and a direct message's conversation+// are both the owner's ordinary one: there is no team to share with and no audience to tell apart.// Security invariants: the session decides who asks, at their level on the bot; the audience named in the request is// checked against the conversation's own, so a channel's message never lands in a private chat and a direct message// never in a shared one; a bot the member can't chat with answers as one that doesn't exist; nothing in a report's@@ -24,7 +26,7 @@ import { cancelSteeredMessage, onSteeredQueueChange, queuedSteeredMessage, queueimport type { BotRecord, Message, Store } from "../store.ts";import {TEAM_SLACK_ANSWER_MAX, TEAM_SLACK_FINAL, TEAM_SLACK_RUNNING_EVERY_MS, createTeamSlackMessages, createTeamSlackReporter, teamSlackKey, teamSlackOver,- type TeamSlackAccepted, type TeamSlackMessage, type TeamSlackRecord, type TeamSlackReport, type TeamSlackReporter, type TeamSlackState, type TeamSlackWaiting,+ type TeamSlackAccepted, type TeamSlackMessage, type TeamSlackMessages, type TeamSlackRecord, type TeamSlackReport, type TeamSlackReporter, type TeamSlackState, type TeamSlackWaiting,} from "../team-slack.ts";import type { UsageTrigger } from "../usage-ledger.ts";import { sharedBeyondOwner } from "./member-bots.ts";@@ -41,6 +43,10 @@ interface Timer { unref?(): unknown }export interface TeamSlackHostDeps {cloudHome: Pick<CloudHomeConfig, "team" | "machineId" | "adminOrigin" | "publicOrigin" | "bootstrapSecret"> | null;dataDir: string;+ /** A personal Cloud's record of the messages taken, made by whoever also reads which conversations came from a channel. */+ messages?: TeamSlackMessages;+ /** On a personal Cloud: its owner's person key when the session is the owner's, else null. A Team Cloud never asks. */+ owner(auth: RequestAuth): string | null;store: Pick<Store, "bot" | "bots" | "botByThread" | "taskByThread" | "createTask" | "activePath" | "onChange">;visibleFor(auth: RequestAuth): Pick<VisibleSet, "bot" | "level" | "thread">;sender(auth: RequestAuth): ResolvedSender | undefined;@@ -119,17 +125,22 @@ export function teamSlackPhase(path: readonly Message[], sendId: string, live: {}export function createTeamSlackHost(deps: TeamSlackHostDeps) {- const home = deps.cloudHome?.team ? deps.cloudHome : null;+ const home = deps.cloudHome;if (!home) return null;+ const personal = !home.team;const { store } = deps;const now = deps.now ?? Date.now;const setTimer = deps.setTimer ?? ((run, ms) => setTimeout(run, ms));const later = (run: () => void, ms: number) => { setTimer(run, ms).unref?.(); };- const messages = createTeamSlackMessages({ dataDir: deps.dataDir, now });+ const messages = deps.messages ?? createTeamSlackMessages({ dataDir: deps.dataDir, now });const report = deps.reporter ?? createTeamSlackReporter({ machineId: home.machineId, adminOrigin: home.adminOrigin, secret: home.bootstrapSecret, now, log: (line) => console.log(`team slack: ${line}`) });- const member = (auth: RequestAuth): { person: string } | null =>- auth.kind === "session" && auth.session.membershipAuthority === "team" && auth.session.email ? { person: personKey(auth.session) } : null;+ const member = (auth: RequestAuth): { person: string } | null => {+ if (personal) { const person = deps.owner(auth); return person ? { person } : null; }+ return auth.kind === "session" && auth.session.membershipAuthority === "team" && auth.session.email ? { person: personKey(auth.session) } : null;+ };+ /** Whether a channel may use the bot. On a personal Cloud every bot is its owner's, in a channel as in a direct message. */+ const shared = (bot: BotRecord): boolean => personal || teamSlackShared(bot);const chattable = (auth: RequestAuth) => {const visible = deps.visibleFor(auth);return (bot: BotRecord) => !bot.hidden && visible.bot(bot.id) && atLeast(visible.level(bot.id), "chat");@@ -231,7 +242,8 @@ export function createTeamSlackHost(deps: TeamSlackHostDeps) {const text = oneLine(input.text, 40);if (input.audience === "member") return serverLine(deps.language(person), "server.teamSlack.direct", { text });const channel = input.slack?.channelName?.replace(/^#/, "");- return channel ? serverLine(deps.language(), "server.teamSlack.channel", { channel, text }) : serverLine(deps.language(), "server.teamSlack.channelUnnamed", { text });+ const language = deps.language(personal ? person : undefined);+ return channel ? serverLine(language, "server.teamSlack.channel", { channel, text }) : serverLine(language, "server.teamSlack.channelUnnamed", { text });}/** What the app's own send refused, as the Admin reads it: it tries again on 409, 423, 429 and 5xx, and tells the sender on anything else. */@@ -249,7 +261,7 @@ export function createTeamSlackHost(deps: TeamSlackHostDeps) {let bot: BotRecord | null | undefined, threadId = input.conversationId ?? undefined;if (threadId) {bot = store.botByThread(threadId);- if (!bot || !store.taskByThread(bot.id, threadId) || !visible.thread(threadId) || !canChat(bot) || deps.audienceOf(threadId) !== wanted) return NO_SUCH_CONVERSATION;+ if (!bot || !store.taskByThread(bot.id, threadId) || !visible.thread(threadId) || !canChat(bot) || (!personal && deps.audienceOf(threadId) !== wanted)) return NO_SUCH_CONVERSATION;} else if ("id" in input.bot) {bot = store.bot(input.bot.id);} else if ("name" in input.bot) {@@ -257,20 +269,20 @@ export function createTeamSlackHost(deps: TeamSlackHostDeps) {bot = store.bots.find((one) => canChat(one) && one.name.trim().toLowerCase() === name);} else {const mine = store.bots.filter(canChat);- bot = mine.find((one) => defaultBotPerson(one) !== "") ?? mine[0];+ bot = mine.find((one) => (personal ? Boolean(one.defaultBot) : defaultBotPerson(one) !== "")) ?? mine[0];}if (!bot || !canChat(bot)) return NO_SUCH_BOT;- if (input.audience === "team" && !teamSlackShared(bot)) return refusal(403, "bot_private", "That bot is private to its owner.");+ if (input.audience === "team" && !shared(bot)) return refusal(403, "bot_private", "That bot is private to its owner.");const created = threadId === undefined;if (threadId === undefined) {const task = store.createTask(bot.id, title(input, person), false, undefined, undefined, undefined, undefined, undefined, (made) => {deps.starters.set(made.threadId, person);- if (input.audience === "team") deps.shareFromSlack(made.threadId, person);+ if (input.audience === "team") { if (personal) messages.channel(made.threadId, true); else deps.shareFromSlack(made.threadId, person); }});if (!task) return refusal(503, "unavailable", "The conversation could not be opened.");threadId = task.threadId;- if (deps.audienceOf(threadId) !== wanted) {+ if (!personal && deps.audienceOf(threadId) !== wanted) {deps.discard(bot.id, threadId);return refusal(503, "unavailable", "The conversation could not be opened.");}@@ -279,7 +291,7 @@ export function createTeamSlackHost(deps: TeamSlackHostDeps) {try {receipt = await deps.send({ botId: bot.id, threadId, text: input.text, sendId: input.id, sender: deps.sender(auth), trigger: deps.trigger(auth), personPresent: true, admin: deps.actor(auth).admin, followUp: "queue" });} catch (error) {- if (created) deps.discard(bot.id, threadId);+ if (created) { deps.discard(bot.id, threadId); messages.channel(threadId, false); }return sendRefused(error);}// A line made of stop words ended the run instead of starting one, as it does in the app.@@ -297,7 +309,7 @@ export function createTeamSlackHost(deps: TeamSlackHostDeps) {/** The bots this member can chat with. */bots(auth: RequestAuth): TeamSlackAnswer {if (!member(auth)) return refusal(404, "not_a_member", "Not found.");- return { status: 200, body: { bots: store.bots.filter(chattable(auth)).map((bot) => ({ id: bot.id, name: bot.name, shared: teamSlackShared(bot) })) } };+ return { status: 200, body: { bots: store.bots.filter(chattable(auth)).map((bot) => ({ id: bot.id, name: bot.name, shared: shared(bot) })) } };},/** Starts or continues a conversation with one Slack message, once per id. */message(auth: RequestAuth, input: TeamSlackMessage): Promise<TeamSlackAnswer> {diff --git a/server/index.ts b/server/index.tsindex 0c8de4c8f9..4bdf1b28db 100644--- a/server/index.ts+++ b/server/index.ts@@ -279,7 +279,7 @@ import { botBox, startBotBoxAtBoot } from "./bot-box/boot.ts"; import { attachmeimport { createCloudSignedHost } from "./host/cloud-signed-host.ts"; import { createDeleteLeftovers, engineSessionFolders, instanceEnvironment } from "./host/delete-leftovers.ts"; import { createBotNameClash } from "./host/bot-name-clash.ts"; import { hiddenThreadRefusal, hideOthersSyncFolders } from "./host/team-private.ts"; import { createTeamMemberLeft, memoryLayerRecords } from "./host/team-member-left.ts"; import { createUploadOwners, uploadsFor } from "./host/member-uploads.ts"; import { createMemberOwnBot } from "./host/member-own-bot.ts"; import { createVisibilityHost } from "./host/visibility-host.ts"; import { createBotAccessHost, refusalFor, relayedSendRefusal } from "./host/bot-access-gate.ts"; import { createBotAccessRoutes, writeAccess } from "./routes/bot-access.ts"; import { createAccessRequests } from "./host/access-requests.ts";import { cloudPowerNow, createCloudPower, registerCloudPower, wokeFromSleep, type CloudPower } from "./cloud-power.ts"; import { createWokeNotifier } from "./cloud-woke.ts"; import { createSharedComputerRoutes } from "./routes/shared-computers.ts";import { lentCopies, noteSyncBotTurn } from "./routes/cloud-sync.ts"; import { mcpReconnectLine, retryBrokeredMcp } from "./bot-box/broker-mcp.ts";-import { type CloudOwnership } from "./cloud-owner.ts"; import { memberLoginRefusal, personalMoveRefusal } from "./cloud-team.ts"; import { createCloudTeamHost, type MemberProfile } from "./host/cloud-team-host.ts"; import { engineHomes } from "./engine-homes/engine-homes.ts"; import { audienceMember, layerId, memberAudience } from "./audience.ts"; import { createPersonRooms, createRoomReads, type OwnGroupFrames } from "./host/room-reads.ts"; import { createPersonBotOrder } from "./host/person-bot-order.ts"; import { createMeRoutes } from "./routes/me.ts"; import { createTeamPhoneRoutes } from "./routes/team-phone.ts"; import { settleCloudHome } from "./cloud-home-settle.ts"; import { CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY } from "./cloud-sharing.ts"; import { createTeamSlackHost } from "./host/team-slack-host.ts"; import { createTeamSlackRoutes } from "./routes/team-slack.ts";+import { type CloudOwnership } from "./cloud-owner.ts"; import { memberLoginRefusal, personalMoveRefusal } from "./cloud-team.ts"; import { createCloudTeamHost, type MemberProfile } from "./host/cloud-team-host.ts"; import { engineHomes } from "./engine-homes/engine-homes.ts"; import { audienceMember, layerId, memberAudience } from "./audience.ts"; import { createPersonRooms, createRoomReads, type OwnGroupFrames } from "./host/room-reads.ts"; import { createPersonBotOrder } from "./host/person-bot-order.ts"; import { createMeRoutes } from "./routes/me.ts"; import { createTeamPhoneRoutes } from "./routes/team-phone.ts"; import { settleCloudHome } from "./cloud-home-settle.ts"; import { CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY } from "./cloud-sharing.ts"; import { createTeamSlackHost } from "./host/team-slack-host.ts"; import { createTeamSlackMessages } from "./team-slack.ts"; import { createTeamSlackRoutes } from "./routes/team-slack.ts";import { createCloudMoveRoutes } from "./cloud-move-http.ts";import { RESTART_EXIT_CODE } from "./restart.ts";import { applyIncludedXMessage, holdIncludedServices, hostingCredential, researchCredential, trialCreditCredential, xCredential, xResearchStatus } from "./included-services.ts"; import { applyPhoneLinkMessage, phoneLinkPart } from "./phone-link.ts"; import { createResearchAvailability } from "./research.ts";@@ -740,7 +740,7 @@ await startBotBoxAtBoot({ dataDir: DATA_DIR, port: PORT }); // The bot box (servif (CLOUD_HOME && Object.keys(CLOUD_SECRETS).length === 0) {console.warn("cloud home: its secrets came in this process's environment, which anything running as the same user can read in /proc; start it with cloud-home-start");}-const threadStarters = new ThreadStarters(join(DATA_DIR, "thread-starters.json")); const conversationShares = createConversationShares({ dataDir: DATA_DIR, team: Boolean(CLOUD_TEAM) });+const threadStarters = new ThreadStarters(join(DATA_DIR, "thread-starters.json")); const conversationShares = createConversationShares({ dataDir: DATA_DIR, team: Boolean(CLOUD_TEAM) }); const personalSlackMessages = CLOUD_PERSONAL ? createTeamSlackMessages({ dataDir: DATA_DIR }) : null;const commandAllowlist = new CommandAllowlistStore(join(DATA_DIR, "command-allowlist.json"));// Every value saved in the Vault is scrubbed from whatever a bot or a transcript can read.const logins = new VaultStore({ dataDir: DATA_DIR, secretChanged: (item) => mcpServersHost.keyChanged(item) });@@ -8661,7 +8661,7 @@ function routineSourceOwner(run: Pick<RoutineRun, "botId" | "sourceThreadId" | "return group?.memberIds.includes(bot.id) ? { bot, group, threadId } : null;}-function mainThreadTasks(botId: string) { const tasks = store.tasks(botId), own = store.bot(botId)?.defaultBot?.person ? [...tasks].sort((a, b) => a.createdAt - b.createdAt)[0]?.threadId : undefined; return CLOUD_TEAM ? tasks.filter((task) => (teamHost.audienceOf(task.threadId) === "team" && !conversationShares.fromSlack(task.threadId)) || task.threadId === own) : CLOUD_HOME ? tasks.filter((task) => !cloudGuestOpened(task.threadId)) : tasks; }+function mainThreadTasks(botId: string) { const tasks = store.tasks(botId), own = store.bot(botId)?.defaultBot?.person ? [...tasks].sort((a, b) => a.createdAt - b.createdAt)[0]?.threadId : undefined; return CLOUD_TEAM ? tasks.filter((task) => (teamHost.audienceOf(task.threadId) === "team" && !conversationShares.fromSlack(task.threadId)) || task.threadId === own) : CLOUD_HOME ? tasks.filter((task) => !cloudGuestOpened(task.threadId) && !personalSlackMessages?.channelThread(task.threadId)) : tasks; }function botMainThread(botId: string): string | undefined {return mainThread(mainThreadTasks(botId), store.bot(botId)?.threadId, store.bot(botId)?.mainThreadChoice);}@@ -12284,7 +12284,7 @@ const taskRoutes = createTaskRoutes({revokeInternalCapabilitiesForThread,stagedSkillCleanupsForThread,rejectDeletedThreadSkillStages,-}); ROUTES.push(taskRoutes); const leaveTeam = CLOUD_TEAM ? createTeamMemberLeft({ dataDir: DATA_DIR, store, openedBy: (person) => threadStarters.threadsOf(person, 50_000), privateTo: teamHost.privateTo, sharesLeft: conversationSharing.personLeft, revokeSessions: (email) => sessions.revokeMember(email), busy: threadBusy, stop: (botId, threadId) => interruptDirectThread(botId, threadId, "The person left the team"), deleteTasks: taskRoutes.deleteTasks, stopBot: (botId) => memberOwnBot.stopWork(botId, "The person left the team"), deleteBot: memberOwnBot.remove, threadsReferencing, deleteAttachment: (name) => deleteAttachment(join(ATTACHMENTS_DIR, name)), eraseBrowsers: eraseAudienceBrowsers, forgetConnections: (person) => { connectionHealth.forgetPerson(person); personRooms.reads?.forgetPerson(person); return teamConnections.forgetPerson(person); }, forgetSecrets: (person) => { logins.forgetPerson(person); }, ...teamRoutines.leaving, forgetOnBots: (email) => forgetMember(store, email, (bot, access) => writeAccess({ store, publicGroupState, broadcast, audienceChanged }, bot, access)).length, ownerOf: (botId) => { const bot = store.bot(botId); return bot ? botOwner(bot) : null; }, record: (row) => appendAdminAction(DATA_DIR, { ...row, actor: { kind: "session", sessionId: "", label: "MausBot Cloud" } }) }) : null; const teamSlack = createTeamSlackHost({ cloudHome: CLOUD_HOME, dataDir: DATA_DIR, store, visibleFor: (auth) => visibleTo(viewerFor(auth)), sender: messageSender, trigger: usageTriggerFor, actor: runActor, audienceOf: teamHost.audienceOf, starters: threadStarters, shareFromSlack: (threadId, person) => void conversationShares.share(threadId, person, "team", Date.now(), "slack"), discard: (botId, threadId) => void taskRoutes.deleteTasks(botId, [threadId]), send: (input) => acceptDirectSend(input), busy: threadBusy, handedOn: directRootPending, request: (threadId) => directRequestOwners.get(threadId), stopRefusal: (threadId, by) => runOwners.stopRefusal(threadId, by), removeRefusal: (threadId, sender, by) => runOwners.removeRefusal(threadId, sender, by), stopThread: stopThreadForPerson, language: personLanguages.forLine }); ROUTES.push(createTeamSlackRoutes({ host: teamSlack }));+}); ROUTES.push(taskRoutes); const leaveTeam = CLOUD_TEAM ? createTeamMemberLeft({ dataDir: DATA_DIR, store, openedBy: (person) => threadStarters.threadsOf(person, 50_000), privateTo: teamHost.privateTo, sharesLeft: conversationSharing.personLeft, revokeSessions: (email) => sessions.revokeMember(email), busy: threadBusy, stop: (botId, threadId) => interruptDirectThread(botId, threadId, "The person left the team"), deleteTasks: taskRoutes.deleteTasks, stopBot: (botId) => memberOwnBot.stopWork(botId, "The person left the team"), deleteBot: memberOwnBot.remove, threadsReferencing, deleteAttachment: (name) => deleteAttachment(join(ATTACHMENTS_DIR, name)), eraseBrowsers: eraseAudienceBrowsers, forgetConnections: (person) => { connectionHealth.forgetPerson(person); personRooms.reads?.forgetPerson(person); return teamConnections.forgetPerson(person); }, forgetSecrets: (person) => { logins.forgetPerson(person); }, ...teamRoutines.leaving, forgetOnBots: (email) => forgetMember(store, email, (bot, access) => writeAccess({ store, publicGroupState, broadcast, audienceChanged }, bot, access)).length, ownerOf: (botId) => { const bot = store.bot(botId); return bot ? botOwner(bot) : null; }, record: (row) => appendAdminAction(DATA_DIR, { ...row, actor: { kind: "session", sessionId: "", label: "MausBot Cloud" } }) }) : null; const teamSlack = createTeamSlackHost({ cloudHome: CLOUD_HOME, dataDir: DATA_DIR, ...(personalSlackMessages ? { messages: personalSlackMessages } : {}), owner: (auth) => (cloudOwnerSession(auth) ? CLOUD_OWNER_KEY : null), store, visibleFor: (auth) => visibleTo(viewerFor(auth)), sender: messageSender, trigger: usageTriggerFor, actor: runActor, audienceOf: teamHost.audienceOf, starters: threadStarters, shareFromSlack: (threadId, person) => void conversationShares.share(threadId, person, "team", Date.now(), "slack"), discard: (botId, threadId) => void taskRoutes.deleteTasks(botId, [threadId]), send: (input) => acceptDirectSend(input), busy: threadBusy, handedOn: directRootPending, request: (threadId) => directRequestOwners.get(threadId), stopRefusal: (threadId, by) => runOwners.stopRefusal(threadId, by), removeRefusal: (threadId, sender, by) => runOwners.removeRefusal(threadId, sender, by), stopThread: stopThreadForPerson, language: personLanguages.forLine }); ROUTES.push(createTeamSlackRoutes({ host: teamSlack }));ROUTES.push(createTeamRoutes({store,cfg,diff --git a/server/request-auth.ts b/server/request-auth.tsindex 3c83f7d769..c137ab9d23 100644--- a/server/request-auth.ts+++ b/server/request-auth.ts@@ -492,8 +492,8 @@ export const CLIENT_ALLOW: ReadonlyArray<{ methods: readonly string[]; path: Reg// what the viewer's own bots put online, from conversations they can read; the handler deletes only what is theirs{ methods: ["GET"], path: /^\/api\/published-apps(?:\/framing)?$/ },{ methods: ["POST"], path: /^\/api\/published-apps\/delete$/ },- // Slack for Team Clouds: the Admin calls these with the member's own session, and the handler answers each as that- // member alone (routes/team-slack.ts); off a Team Cloud they answer 404+ // Slack for Clouds: the Admin calls these with the member's own session, and the handler answers each as that member+ // alone, on a personal Cloud its owner alone (routes/team-slack.ts); off a Cloud they answer 404{ methods: ["GET"], path: /^\/api\/slack\/team\/bots$/ },{ methods: ["POST"], path: /^\/api\/slack\/team\/messages(?:\/[0-9a-f-]{36}\/stop)?$/ },];diff --git a/server/routes/team-slack.ts b/server/routes/team-slack.tsindex d48ea347db..3f616757c3 100644--- a/server/routes/team-slack.ts+++ b/server/routes/team-slack.ts@@ -1,6 +1,6 @@-// Slack for Team Clouds: the three routes the Admin calls with a session it opened for the member who wrote in Slack-// (docs/team-slack.md). Only a Team Cloud has them; anywhere else each answers 404 with no code, which the Admin reads-// as a Cloud that can't take Slack messages yet.+// Slack for Clouds: the three routes the Admin calls with a session it opened for the member who wrote in Slack, or+// for a personal Cloud's owner (docs/team-slack.md). Only a Cloud has them; anywhere else each answers 404 with no+// code, which the Admin reads as a Cloud that can't take Slack messages yet.import type { ServerResponse } from "node:http";import type { TeamSlackAnswer, TeamSlackHost } from "../host/team-slack-host.ts";diff --git a/server/team-slack.test.ts b/server/team-slack.test.tsindex 6350d54de6..4ac1f4f19d 100644--- a/server/team-slack.test.ts+++ b/server/team-slack.test.ts@@ -105,6 +105,30 @@ describe("the record of Slack messages", () => {expect(again.forgetPerson("p_zyxwvutsrqponmlkjihgfe")).toEqual([LATER]);expect(JSON.parse(readFileSync(join(dataDir, TEAM_SLACK_FILE), "utf8")).messages.map((one: { id: string }) => one.id)).toEqual([ID]);});+ it("on a personal Cloud keeps which conversations a channel opened, after their messages are dropped and across a restart", () => {+ const dataDir = dir(), day = 24 * 3_600_000;+ let now = 0;+ const first = createTeamSlackMessages({ dataDir, now: () => now });+ first.channel("t_channel", true);+ first.channel("t_refused", true);+ first.channel("t_refused", false);+ first.put(record({ threadId: "t_channel", state: "completed", told: "completed" }));+ first.put(record({ id: LATER, threadId: "t_direct", audience: "member" }));+ expect([first.channelThread("t_channel"), first.channelThread("t_direct"), first.channelThread("t_refused")]).toEqual([true, false, false]);+ now = 31 * day;+ first.patch(LATER, {});+ expect(first.all()).toEqual([]);+ const again = createTeamSlackMessages({ dataDir, now: () => now });+ expect([again.channelThread("t_channel"), again.channelThread("t_direct")]).toEqual([true, false]);+ expect(readFileSync(join(dataDir, TEAM_SLACK_FILE), "utf8")).toBe('{"version":1,"messages":[],"channels":["t_channel"]}\n');+ });+ it("a Team Cloud's record names no channel conversations: its sharing does", () => {+ const dataDir = dir();+ const kept = createTeamSlackMessages({ dataDir, now: () => 2_000 });+ kept.put(record());+ expect(kept.channelThread("t_1")).toBe(false);+ expect(Object.keys(JSON.parse(readFileSync(join(dataDir, TEAM_SLACK_FILE), "utf8")))).toEqual(["version", "messages"]);+ });it("past its cap drops what is over before a run it still tracks", () => {const kept = createTeamSlackMessages({ dataDir: dir(), now: () => 1_000, max: 2 });const [first, second, third] = [ID, LATER, "8b2e3c4d-5e6f-4a7b-8c9d-2e3f4a5b6c7d"];diff --git a/server/team-slack.ts b/server/team-slack.tsindex c0b901f0ff..c8649f8bc0 100644--- a/server/team-slack.ts+++ b/server/team-slack.ts@@ -1,7 +1,8 @@-// Slack for Team Clouds, the Team Cloud's side (docs/team-slack.md). One MausBot Slack app is installed per company;-// Slack's events arrive at the Admin, which hands each message to the team's Cloud with a session it opened for the-// member who wrote it, so here the message is that member's own request. This module holds the contract's wire shapes,-// the record of the messages taken (the idempotency key and what the Admin has been told) and the signed report back.+// Slack for Clouds, the Cloud's side (docs/team-slack.md). One MausBot Slack app is installed per company or person;+// Slack's events arrive at the Admin, which hands each message to the Cloud with a session it opened for the member who+// wrote it (on a personal Cloud, for its owner), so here the message is that person's own request. This module holds+// the contract's wire shapes, the record of the messages taken (the idempotency key and what the Admin has been told)+// and the signed report back.// Security invariants: the Slack bot token never reaches this machine; nothing the Admin sends beyond the member's own// session and this contract's signature is authority; a report carries a message's id, state and final answer only.import { createHash, createHmac, randomBytes } from "node:crypto";@@ -68,7 +69,9 @@ const recordSchema = z.object({closed: z.literal(true).optional(),});export type TeamSlackRecord = z.infer<typeof recordSchema>;-const fileSchema = z.object({ version: z.literal(1), messages: z.array(recordSchema) });+const fileSchema = z.object({ version: z.literal(1), messages: z.array(recordSchema),+ /** A personal Cloud only: the conversations a Slack channel's message opened, kept after their messages are dropped. */+ channels: z.array(z.string().regex(/^[\w-]{1,128}$/)).optional() });export const teamSlackKey = (record: Pick<TeamSlackRecord, "state" | "waiting">): string => record.state === "waiting" ? `waiting:${record.waiting ?? "question"}` : record.state;/** Nothing more will be said about it: the Admin has its final state, or asked for no more. */@@ -78,9 +81,13 @@ export const teamSlackOver = (record: TeamSlackRecord): boolean => record.closedexport function createTeamSlackMessages(options: { dataDir: string; now?: () => number; max?: number }) {const file = join(options.dataDir, TEAM_SLACK_FILE), now = options.now ?? Date.now, max = options.max ?? MAX_MESSAGES;const records = new Map<string, TeamSlackRecord>();+ const channels = new Set<string>();try {const parsed = fileSchema.safeParse(JSON.parse(readFileSync(file, "utf8")));- if (parsed.success) for (const record of parsed.data.messages) records.set(record.id, record);+ if (parsed.success) {+ for (const record of parsed.data.messages) records.set(record.id, record);+ for (const threadId of parsed.data.channels ?? []) channels.add(threadId);+ }else console.warn("team slack: the record of Slack messages can't be read; starting empty");} catch (error) {if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.warn("team slack: the record of Slack messages can't be read; starting empty");@@ -91,12 +98,21 @@ export function createTeamSlackMessages(options: { dataDir: string; now?: () =>// Past the cap, what is over goes first: a run still tracked keeps its report and its Stop.for (const [id, record] of records) { if (records.size <= max) break; if (teamSlackOver(record)) records.delete(id); }while (records.size > max) records.delete(records.keys().next().value!);- try { writeFileAtomic(file, `${JSON.stringify({ version: 1, messages: [...records.values()] })}\n`, { mode: 0o600 }); }+ while (channels.size > max) channels.delete(channels.values().next().value!);+ try { writeFileAtomic(file, `${JSON.stringify({ version: 1, messages: [...records.values()], ...(channels.size ? { channels: [...channels] } : {}) })}\n`, { mode: 0o600 }); }catch (error) { console.warn(`team slack: could not save the record of Slack messages (${error instanceof Error ? error.name : "error"})`); }};return {get: (id: string): TeamSlackRecord | undefined => records.get(id),all: (): TeamSlackRecord[] => [...records.values()],+ /** A personal Cloud's conversation that a Slack channel's message opened: never the chat its bot opens to. */+ channelThread: (threadId: string): boolean => channels.has(threadId),+ /** On a personal Cloud: a Slack channel's message opened this conversation, or (`opened` false) it was not kept. */+ channel(threadId: string, opened: boolean): void {+ if (opened ? channels.has(threadId) : !channels.delete(threadId)) return;+ if (opened) channels.add(threadId);+ save();+ },put(record: TeamSlackRecord): void {records.set(record.id, record);save();diff --git a/server/workspace-backup.ts b/server/workspace-backup.tsindex 513d4d8872..4a0abf4a00 100644--- a/server/workspace-backup.ts+++ b/server/workspace-backup.ts@@ -33,7 +33,7 @@ const EXCLUDED = new Set([".backups", "tools", "browser", "agent-browser-profiles", "cache", ".cache", "tmp", ".tmp", "dist-native", "tunnel-runtime", "evidence",".openmausbot-server-child", "environment-id", "sessions.json", "tunnel-account.json","team-computers.json",- // Slack messages a Team Cloud took from the Admin (team-slack.ts): this machine's own, of no use anywhere else.+ // Slack messages a Cloud took from the Admin (team-slack.ts): this machine's own, of no use anywhere else."team-slack-messages.json","openmausbot-server.lease", "box-create-requests.lock", "messages.db-wal", "messages.db-shm","runtime.db-wal", "runtime.db-shm",