Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Team Cloud: Slack for Team Clouds, the Cloud's side (phase 2) (#6012)
Milind Soni5646315c4086
diff --git a/docs/team-cloud.md b/docs/team-cloud.mdindex b3ba93d9e7..e15cfc4efc 100644--- a/docs/team-cloud.md+++ b/docs/team-cloud.md@@ -98,6 +98,11 @@ keeps people apart on it. The bot box ([bot-box.md](bot-box.md)) is what makes t*Paired devices* lists the phones those codes opened as *device · member* (`GET /api/team/phones`): a member sees theirown, the Super admin and Admins every member's. **Remove** (`DELETE /api/team/phones/<id>`, the same rule) signs thatphone out at once and closes its open streams; the app windows the Admin signs in are not listed there.+- **Slack.** With the team's Slack connected on MausBot Cloud, a message to `@MausBot` in a channel, or a direct+ message, is its writer's own request here: the Admin hands it over with a session it opened for that member, so their+ level on the bot, their run and their right to stop it hold as in the app. A channel thread is a conversation shared+ with the team; a direct message is their private chat. It is never the relayed, information-only kind of line. See+ [team-slack.md](team-slack.md).- **Asleep only when nobody needs it, kept across restarts.** On a plan that sleeps, a Team Cloud answers the Admin'ssleep request as any home does ([Sleeping homes](cloud-pro.md#sleeping-homes-the-power-read-and-the-sleep-handshake)):not while any member used it in the last minutes, a turn or routine runs, or work one bot handed another is stilldiff --git a/docs/team-slack.md b/docs/team-slack.mdnew file mode 100644index 0000000000..27ef933087--- /dev/null+++ b/docs/team-slack.md@@ -0,0 +1,127 @@+# Slack for Team Clouds: the Team Cloud's side++People in a company's Slack write `@MausBot` in a channel, or message it directly, and the team's bots answer there. One+MausBot Slack app is installed per company. Slack's events arrive at the Admin (openmaus-cloud, `docs/team-slack.md`+there), which works out the team member who wrote and hands each message to that team's Cloud **with a session it opened+for that member**. This page is the Cloud's side: three routes the Admin calls, and one signed report back. The Slack bot+token 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 Slack message is the member's own request++The Admin opens the session through the signed pairing with the member's claim (label `Slack (MausBot Cloud)`), exactly+as each person's app is paired. So the request is that member's, at their role, and every check is the app's own:++- The line is sent the way their composer sends it (`acceptDirectSend`, `server/host/team-slack-host.ts`): their name+ on it, their person key as its sender, `[From Priya (person) · message · their own request]` where several people+ write. It is never the relayed, information-only kind (`onBehalfOf` on the guarded route), which acts for nobody.+- Their level on the bot decides ([team-cloud.md](team-cloud.md#who-can-use-a-bot)). A bot they can't chat with (No+ access, Can view, or someone else's own MausBot) answers exactly as an id no bot has.+- They own the run ([team-cloud.md](team-cloud.md#whoever-asked-owns-the-run)): in a shared conversation someone+ else's line waits its turn, and only they, or an Owner or Admin, stop it.+- A line written while the conversation's bot works waits in the queue, as a message sent with "queue" does in the+ app, and runs after as its own turn; it is never steered into the running turn. Lines of one person that waited+ together are answered by one turn, as in the app: the last is reported with the reply, the earlier ones as completed+ with no text.+- A reply in Slack is a new line. It never answers a card: approvals and questions are answered in MausBot.++## The audience is the Cloud's to enforce++The request names an audience; the Cloud checks it against the conversation and never takes the Admin's word further.++| `audience` | From | The conversation |+|---|---|---|+| `team` | a Slack channel thread | A conversation the member opens and shares with the team at once: audience `team`, on the Team side for everyone who sees the bot. Its turns read the bot's team notes and the team's connected apps only, never the member's private layer, About you, own connections or own secrets. |+| `member` | a Slack direct message | The member's private chat with that bot, `member:<person>`: theirs alone, as any conversation they open in the app. No other member and no admin reads it. |++- A bot private to its owner, and a member's own MausBot, is refused for the `team` audience (`bot_private`): nobody+ else could read the conversation, so it would not be a shared one.+- `conversationId` continues a conversation only when the member reads it, can chat with its bot, and its audience is+ the one the request names. A channel's message never lands in a private chat, a direct message never in a shared+ conversation, and nobody's direct message in someone else's: each answers `no_such_conversation`, as an id that does+ not exist.+- A shared conversation started from Slack is like one its member shared from the app: it stays the team's when they+ leave. Their direct-message conversations are their private chats, and go with them+ ([team-cloud.md](team-cloud.md#the-pairing-claim-contract-v1)); what this machine kept of their Slack messages goes too.++## Where it came from++A conversation started from Slack is named for it, in the language of the person it is for: *"Slack #sales: What ships+on Friday?"* for a channel whose name the Admin sent (`slack.channelName`, optional), *"Slack channel: …"* without one,+*"Slack DM: …"* for a direct message. It is an ordinary title: its person can rename it. It is listed under Just me or+Team by the same answer as every conversation.++A channel's conversation is also recorded as from Slack where its sharing is (`conversation-shares.json`, `from:+"slack"`). It is never the chat its bot opens to: the bot's shared chat stays the shared chat, however often Slack+threads are written in after it.++## The routes++Each takes the member's session, as a bearer. `server/routes/team-slack.ts`; the wire shapes are in+`server/team-slack.ts`.++- `GET /api/slack/team/bots` → `{ "bots": [{ "id", "name", "shared" }] }`: the bots this member can chat with.+ `shared` is false for a bot only its owner uses and for their own MausBot. There is no `avatarUrl`: a bot's picture+ is served to signed-in members only (`/api/attachments/…`), so there is no address Slack could fetch.+- `POST /api/slack/team/messages` with `{ v: 1, id, audience, bot, conversationId, text, slack }`. `id` is the+ idempotency key: the same id again answers as the first did and starts nothing. `bot` is `{ id }`, `{ name }` (among+ the bots the member can chat with, ignoring case) or `{ default: true }` (their own MausBot, else the first bot they+ can chat with). It answers `202 { accepted: true, conversationId, bot: { id, name }, openUrl }`; `openUrl` is this+ Cloud's own address with `?thread=…&bot=…`, which the web app opens to that conversation.+- `POST /api/slack/team/messages/<id>/stop`: Stop, pressed in Slack by this member. `200 { stopped }`, `403` when it is+ not theirs to stop (the run goes on), `404` for an id this Cloud never took.++| Answer | When |+|---|---|+| `404 { code: "no_such_bot" }` | No such bot, or one this member can't chat with: the same body for both |+| `403 { code: "bot_private" }` | The `team` audience and a bot private to its owner |+| `409 { code: "no_such_conversation" }` | `conversationId` names nothing this member may continue with this audience |+| `409`, `423`, `429`, `5xx` with the app's own `code` | The send was refused for now, in the app's words (`no_ai`, `spend_cap`, …): the Admin tries again |+| `422` with the app's own `code` | The send was refused for good (a team rule, a typed stop that is not theirs) |+| `400 { code: "bad_request" }` | Not the contract's message |+| `403 { code: "not_yours" }` | The id is one another member's message already has |+| `404 { code: "not_a_member" }` | The session carries no member's claim |++## Reporting back++`POST <Admin>/api/cloud/machines/slack`, signed with the bootstrap secret in a context of its own+(`teamSlackSignature`, `omb-team-slack-v1`), like the roster check: `{ v: 1, id, status, conversationId, bot, openUrl }`+with `text` on `completed`, `waiting` on `waiting` and `error` on `failed`.++What a message's run is doing is read from the conversation's own records each time they change, never polled and+never taken from a model's words (`teamSlackPhase`): the request's own marks (`requestPending`, `requestCancelled`),+the cards after it, and whether the conversation works.++| `status` | When |+|---|---|+| `running` | The message was taken; again when a card is answered, and every 10 minutes while it works |+| `waiting` | A card after the request waits on a person: `approval`, or `question` for a question, a sign-in, a password or an app to connect. Once per wait |+| `completed` | The request settled. `text` is the turn's final reply, as Markdown |+| `failed` | The run ended without an answer, the next request began before this one settled, or the server restarted under it. `error` is always `failed` |+| `stopped` | Its request was stopped (from Slack or in the app), its waiting line was removed, or its conversation was deleted |++A final report, and a `waiting`, is sent again (5 s, 15 s, a minute, then every 5 minutes, for 6 hours) until the Admin+answers; a `running` nobody answered is not. `{ done: true }` and a 404 end the reports for that message. The `stop`+the 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.++## Cards++A card is asked where it always is. In a shared conversation it is in the conversation, where whoever asked, the bot's+owner or an admin answers it, and a copy reaches the inbox of the bot's owner+([team-cloud.md](team-cloud.md#one-inbox-per-person)); in a direct message's conversation it stays there, the member's+own. Either way the report is `waiting` and the Admin's link opens the conversation. A question a finished turn left+open is part of its reply: the report is `completed`.++## Not in this version++A picture for Slack (no public address exists), partial text for streaming, files, a reply in Slack answering a card,+and telling `model` and `limit` apart in a `failed`. A card asked by another bot the work was handed to waits in its+person's inbox, and Slack keeps showing the run as working.++See [Verifying Slack for Team Clouds](verification/team-slack.md).diff --git a/docs/verification/README.md b/docs/verification/README.mdindex 11f37211f5..2b7899d5fe 100644--- a/docs/verification/README.md+++ b/docs/verification/README.md@@ -225,6 +225,10 @@ The [hosted Slack management fixture](hosted-slack-management.md) checks theagent settings link to Admin: hosted-only availability, the member-readableroute 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.+The [chat and settings polish fixture](chat-polish.md) exercises attachmentgalleries, opt-in video playback, persisted tool details, and responsive settingsthrough the real renderer in an isolated fake-engine workspace.diff --git a/docs/verification/team-slack.md b/docs/verification/team-slack.mdnew file mode 100644index 0000000000..8cabc8015a--- /dev/null+++ b/docs/verification/team-slack.md@@ -0,0 +1,71 @@+# Verifying Slack for Team Clouds++Read [the verification entry point](README.md) first. What this is and what each route answers is in+[Slack for Team Clouds: the Team Cloud's side](../team-slack.md).++Nothing here reaches Slack or the real Admin. The Admin's part is played by the test: it pairs each member with the+Admin's signed claim (label "Slack (MausBot Cloud)"), calls the three routes with that session, and runs a stand-in+Admin that takes the Cloud's signed reports and judges each as the real one does (machine, clock, nonce, the signature in+Slack's own context with the bootstrap secret, and whether the message is this team's).++```sh+pnpm exec vitest run server/team-slack.test.ts+pnpm exec vitest run server/cloud-team-slack.e2e.test.ts+```++`server/team-slack.test.ts` holds the parts with no server: the signature against the value the Admin's own function+gives, 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 final+reply, 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.++`server/cloud-team-slack.e2e.test.ts` launches a Team Cloud (`scripts/testing/cloud-send-fixture.ts`) with an Owner, an+Admin and two Users, the synthetic Claude CLI, and five bots: one everyone can chat with, one a User owns that asks+before it acts, one only its owner uses, one everyone can only view, and one a User made for themselves. It proves:++- **A channel message** (`POST /api/slack/team/messages`, `audience: "team"`) is its writer's own line in a new+ conversation shared with the team: `202` with the conversation, the bot and an https link; the reports are `running`+ then `completed` with the reply; every other member and the Owner are sent the conversation, shared and not private,+ titled "Slack #sales: …"; the line carries its writer's name; and the engine's prompt says *their own request*, with+ nothing relayed or information only.+- **The same id again** answers as the first did, while the run works and after it ended: one line, one reply, one+ conversation, one `completed`. Another member presenting that id gets 403.+- **A thread continues** by `conversationId`, for its writer and for another member who writes next, each line under+ its own name; with the other audience, or an id that names nothing, it answers `409 no_such_conversation`.+- **A direct message** (`audience: "member"`, the bot named with other capitals) is a private chat titled "Slack DM:+ …": its member reads it, and the other User, the Owner and the Admin get 404 reading it, are not sent it, and get 404+ writing in it. A channel's message, another User's direct message and the Owner's can't be put into it.+- **A final report the Admin did not take** (a 503) is sent again until it does, once.+- **Which bot**: `GET /api/slack/team/bots` lists the bots the member can chat with, each `shared` or not and none with+ a picture, never one they can't chat with; the Owner's list has the bot only its owner uses and not the User's own+ MausBot. `{ default: true }` is the member's own MausBot; `{ name }` ignores case.+- **Private and unreachable bots**: a bot only its owner uses, a User's own bot and their MausBot answer `403+ bot_private` for a channel. A bot the member can't see, one they can only view and a name nobody has all answer+ exactly what an id no bot has answers, for both audiences, and no conversation is made.+- **The audience holds**: with a marker in the member's About you and another in their private notes for the bot, a+ direct message's turn is given both, and a channel's turn (a new conversation and a continued one) is given neither,+ nor the path of their private layer.+- **An approval** asked through the bot's permission socket is reported `waiting` with `approval`, once; the card is in+ the conversation and in the member's inbox under Needs you (`GET /api/inbox`); answered in MausBot, the reports go on+ `running` then `completed`.+- **Stop** (`POST /api/slack/team/messages/<id>/stop`): another User gets 403 in the app's words and the run goes on;+ an id never taken is 404; its writer's Stop ends it, the report is `stopped`, and the conversation says who stopped.+- **Every report** verifies in Slack's context with the bootstrap secret and under no other context of this Cloud's+ (the roster check's, the Admin's own request signature); the stand-in refuses the roster context and another secret.+ What the Cloud keeps (`team-slack-messages.json`) holds no word of a message or an answer, no channel, no Slack user+ and no address.+- **When the member leaves** (`POST /api/cloud/team/member-left`), their direct message's conversation and private+ layer are gone, for them too when they join again; what the Cloud kept of their Slack messages is gone; the channel's+ conversation stays.+- **Off a Team Cloud**, on a My Cloud and 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 conversation+of that audience is given.++## What only a real Slack workspace and the real Admin prove++That Slack delivers the events, that the Admin matches a Slack user to a member and opens their session, that its+retries carry the same id, that its words for each answer and report read well in a thread, and that a Cloud asleep is+woken for a message. The Admin's own tests in openmaus-cloud run it against a fake Cloud that follows the same+contract; no run has joined the real two.diff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjsindex 714e545137..9e427718a1 100644--- a/scripts/ci-scope.mjs+++ b/scripts/ci-scope.mjs@@ -108,6 +108,7 @@ export const VITEST_SUBSETS = {"server/cloud-team-private-default.e2e.test.ts","server/cloud-team-private.e2e.test.ts","server/cloud-team-profile.e2e.test.ts",+ "server/cloud-team-slack.e2e.test.ts","server/cloud-team-published-apps.e2e.test.ts","server/cloud-team-requests.e2e.test.ts","server/cloud-team-routines.e2e.test.ts",diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.tsindex 4353a46f7f..80aa18b789 100644--- a/scripts/ci-scope.test.ts+++ b/scripts/ci-scope.test.ts@@ -248,6 +248,7 @@ describe("CI outputs", () => {"server/cloud-team-private-default.e2e.test.ts","server/cloud-team-private.e2e.test.ts","server/cloud-team-profile.e2e.test.ts",+ "server/cloud-team-slack.e2e.test.ts","server/cloud-team-published-apps.e2e.test.ts","server/cloud-team-requests.e2e.test.ts","server/cloud-team-routines.e2e.test.ts",diff --git a/scripts/testing/cloud-send-fixture.ts b/scripts/testing/cloud-send-fixture.tsindex 48e272980b..29ba7694db 100644--- a/scripts/testing/cloud-send-fixture.ts+++ b/scripts/testing/cloud-send-fixture.ts@@ -124,6 +124,9 @@ export interface CloudTeamFixture {home: string;id: string;name: string;+ /** What the Admin signs with and this Cloud reports with, and the machine id it reports as. */+ secret: string;+ machineId: string;/** The Admin's signed pairing for one member, as the Admin hands it to the app: a one-time code, not redeemed. */grant(member: TeamMember): Promise<{ origin: string; code: string; expiresAt: number }>;/** The Admin's signed pairing for one member, redeemed into a bearer. `body` replaces the member and team claims@@ -140,6 +143,8 @@ export interface CloudTeamFixture {relaunch(env?: NodeJS.ProcessEnv): Promise<void>;}+const TEAM_MACHINE_ID = "0d9e8f7a-6b5c-4d3e-9f8a-7b6c5d4e3f2a";+function fakeOnePassword(at: string, token: string): string {const sdk = join(at, "node_modules", "@1password", "sdk");mkdirSync(sdk, { recursive: true });@@ -294,7 +299,7 @@ await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-clsymlinkSync(join(SERVER_DIR, "..", "node_modules", scope), join(root, "team", "native", "node_modules", scope), "junction");}const startTeam = (more: NodeJS.ProcessEnv = {}) => start("team", { OMB_CLOUD_ROLE: "team", OMB_CLOUD_TEAM_ID: team.id, OMB_CLOUD_TEAM_NAME: team.name,- OMB_CLOUD_MACHINE_ID: "0d9e8f7a-6b5c-4d3e-9f8a-7b6c5d4e3f2a", OMB_CLOUD_ADMIN_URL: "https://cloud.example.test", OMB_CLOUD_BOOTSTRAP_SECRET: secret,+ OMB_CLOUD_MACHINE_ID: TEAM_MACHINE_ID, OMB_CLOUD_ADMIN_URL: "https://cloud.example.test", OMB_CLOUD_BOOTSTRAP_SECRET: secret,OMB_PUBLIC_URL: `https://${CLOUD_HOST}`, OMB_TEST_INTERNAL_CAPABILITY_KEY: CAPABILITY_KEY, ...(broker ? { OMB_COMPOSIO_BROKER_URL: broker.url } : {}), ...team.env, ...more },teamPort, stopOverIpc ? ["--import", stopOnMessage] : [], stopOverIpc, onePasswordToken, 0, team.engine ?? "", true);let teamServer = await startTeam();@@ -320,7 +325,7 @@ await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-clif (renamed.status !== 200) throw new Error(`could not name the team's Chief: ${renamed.status} ${JSON.stringify(renamed.body)}`);};teamFixture = {- base: teamBase, home: join(root, "team"), id: team.id, name: team.name,+ base: teamBase, home: join(root, "team"), id: team.id, name: team.name, secret, machineId: TEAM_MACHINE_ID,async grant(member) {const body = JSON.stringify({ label: "OpenMausBot app (Team Cloud)", ttlSeconds: 300, team: { id: team.id, name: team.name }, member });const timestamp = String(Math.floor(Date.now() / 1000)), nonce = randomBytes(16).toString("base64url");diff --git a/server/cloud-team-slack.e2e.test.ts b/server/cloud-team-slack.e2e.test.tsnew file mode 100644index 0000000000..2186bbf437--- /dev/null+++ b/server/cloud-team-slack.e2e.test.ts@@ -0,0 +1,450 @@+// Slack for Team Clouds on a real Team Cloud (docs/team-slack.md). The Admin's part is played here: a session opened+// for each member 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 becomes+// a shared conversation its writer asked in; a direct message their private chat; the app's own rules decide who may+// ask, read and stop. Disposable homes and the synthetic Claude CLI; no Slack and no real Admin are reached.+import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { createServer, type Server } from "node:http";+import { connect, type AddressInfo, type Socket } from "node:net";+import { join } from "node:path";+import { afterAll, afterEach, beforeAll, expect, it } from "vitest";++import { launchCloudSendFixture, type CloudSendFixture, type CloudTeamFixture } from "../scripts/testing/cloud-send-fixture.ts";+import { cloudRequestSignature } from "./cloud-home.ts";+import { teamRosterSignature } from "./cloud-team-roster.ts";+import { personKey } from "./person-key.ts";+import { TEAM_SLACK_FILE, TEAM_SLACK_REPORT_PATH, teamSlackSignature } from "./team-slack.ts";+import { hostTimeout } from "./testing/host-timeout.ts";++const ADA = { email: "[email protected]", role: "owner" as const };+const ARI = { email: "[email protected]", role: "admin" as const };+const PRIYA = { email: "[email protected]", role: "member" as const };+const TOM = { email: "[email protected]", role: "member" as const };+const priyaKey = personKey({ id: "", email: PRIYA.email });+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";+if (existsSync(dir + "/hang-mode")) process.env.FAKE_CLAUDE_MODE = "hang";`;+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**.",+ "What ships on Friday?": "The **invoice run** ships on Friday.",+ "Tom here: who is on call?": "Sam is on call.",+ "What is my badge code?": "I can't share badge codes here.",+ "Remind me what I like": "You like short answers.",+ "Draft my week": "Your week is drafted.",+ "Private notes please": "Noted privately.",+ "Is the report out?": "The report is out.",+};+const ABOUT = "ABOUT-PRIYA-7731 prefers oolong", BADGE = "BADGE-PRIYA-4471";++type Report = { id: string; status: string; text?: string; waiting?: string; error?: string; conversationId?: string; bot?: { id: string; name: string; avatarUrl?: string }; openUrl?: string };+type Task = { threadId: string; title: string; private?: boolean; shared?: boolean; busy?: boolean };+type Bot = { id: string; name: string; threadId: string; busy?: boolean; defaultBot?: { person?: string }; tasks?: Task[] };+type Row = { id: string; role: string; kind: string; text?: string; sender?: { name: string }; card?: { requestId?: string; answered?: string }; 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 team's Admin handed over; any other id is not this team's. */+ known: new Set<string>(),+ /** How many final reports the stand-in answers 503 before it takes one. */+ failFinal: 0,+};+let adminServer: Server, fx: CloudSendFixture, team: CloudTeamFixture;+let ada = "", ari = "", priya = "", tom = "", adaSlack = "", priyaSlack = "", tomSlack = "";+let scout: Bot, reporter: Bot, vault: Bot, payroll: Bot, notes: Bot, priyaOwn: Bot;+const sockets: Socket[] = [];++const file = (name: string) => join(team.home, name);+const dataFile = (...rest: string[]) => join(team.home, ".openmausbot", ...rest);+const bots = async (token: string) => (await team.as(token, "GET", "/api/bots?messages=0")).body.bots as Bot[];+const taskOf = async (token: string, botId: string, threadId: string) => (await bots(token)).find((bot) => bot.id === botId)?.tasks?.find((task) => task.threadId === threadId);+const rows = async (token: string, threadId: string) => ((await team.as(token, "GET", `/api/threads/${threadId}/messages?limit=200`)).body.messages ?? []) as Row[];+const idle = async () => (await bots(ada)).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 its writer. */+async function slack(token: string, ask: Ask) {+ const id = ask.id ?? randomUUID();+ admin.known.add(id);+ const direct = ask.audience === "member";+ const answer = await team.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: "T0ACME", channel: direct ? "D0PRIYA" : "C0SALES", threadTs: "1731662000.000100", messageTs: "1731662000.000100", user: "U0PRIYA", ...(ask.channelName ? { channelName: ask.channelName } : {}) } });+ return { id, ...answer };+}+const stop = (token: string, id: string) => team.as(token, "POST", `/api/slack/team/messages/${id}/stop`, { v: 1 });+const dump = () => JSON.parse(readFileSync(file("dump.json"), "utf8")) as { prompt?: unknown; systemPrompt?: string; mcpConfig?: { mcpServers?: { ogb?: { args?: string[] } } } };++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(team.secret, machine, timestamp, nonce, raw), "base64url"), given = Buffer.from(presented ?? "", "base64url");+ if (machine !== team.machineId || 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 Team 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" });+ if (admin.failFinal > 0 && ["completed", "failed", "stopped"].includes(report.status)) { admin.failFinal--; return answer(503, { error: "busy" }); }+ 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")}`, team: { id: "team-acme-slack", name: "Acme", engine: ENGINE,+ env: { OMB_BOT_BOX: "0", FIXTURE_ADMIN_STAND_IN: `http://127.0.0.1:${(adminServer.address() as AddressInfo).port}` } } });+ team = fx.team!;+ writeFileSync(file("markers.json"), JSON.stringify(ANSWERS));+ writeFileSync(file("tool-calls.json"), "[]");+ writeFileSync(file("release"), "");+ ada = (await team.pair(ADA)).token!;+ ari = (await team.pair(ARI)).token!;+ priya = (await team.pair(PRIYA)).token!;+ tom = (await team.pair(TOM)).token!;+ for (const [token, name] of [[ada, "Ada"], [priya, "Priya"], [tom, "Tom"]]) expect((await team.as(token, "PUT", "/api/me", { name })).status).toBe(200);+ adaSlack = (await team.pair(ADA, { label: SLACK_LABEL })).token!;+ priyaSlack = (await team.pair(PRIYA, { label: SLACK_LABEL })).token!;+ tomSlack = (await team.pair(TOM, { label: SLACK_LABEL })).token!;+ const create = async (token: string, body: Record<string, unknown>) => {+ const created = await team.as(token, "POST", "/api/bots", body);+ expect(created.status, JSON.stringify(created.body)).toBe(201);+ return created.body.bot as Bot;+ };+ scout = await create(ada, { name: "Scout", visibility: "everyone" });+ reporter = await create(ada, { name: "Reporter", visibility: "everyone", reportsTo: PRIYA.email });+ expect((await team.as(ada, "PATCH", `/api/bots/${reporter.id}`, { approvalMode: "ask" })).status).toBe(200);+ vault = await create(ada, { name: "Vault" });+ payroll = await create(ada, { name: "Payroll", visibility: "everyone" });+ expect((await team.as(ada, "PUT", `/api/bots/${payroll.id}/access`, { everyone: "view", people: {} })).status).toBe(200);+ notes = await create(priya, { name: "Notes" });+ priyaOwn = (await bots(priya)).find((bot) => bot.defaultBot?.person === PRIYA.email)!;+ expect(priyaOwn, "every member has a MausBot of their own").toBeTruthy();+}, hostTimeout(180_000));++afterEach(async () => {+ writeFileSync(file("release"), "");+ writeFileSync(file("tool-calls.json"), "[]");+ rmSync(file("hang-mode"), { force: true });+ await until(idle, 90_000);+}, hostTimeout(120_000));++afterAll(async () => {+ for (const socket of sockets) socket.destroy();+ await fx?.close();+ await new Promise((resolve) => adminServer?.close(resolve));+});++let channelThread = "", directThread = "";++it("a channel message is its writer's own request in a shared conversation, reported running then completed with the reply", async () => {+ rmSync(file("dump.json"), { force: true });+ const sent = await slack(priyaSlack, { 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 });++ // Everyone the bot is shared with reads it, on the Team side, named for where it came from.+ for (const token of [priya, tom, ada]) {+ const task = await taskOf(token, scout.id, channelThread);+ expect(task).toMatchObject({ title: "Slack #sales: What ships on Friday?", shared: true });+ expect(task!.private).toBeUndefined();+ }+ // The bot's own shared chat stays the chat it opens to: a Slack thread never takes its place.+ expect(((await bots(tom)).find((bot) => bot.id === scout.id) as Bot & { mainThreadId?: string }).mainThreadId).toBe(scout.threadId);+ const line = (await rows(tom, channelThread)).find((row) => row.role === "user")!;+ expect(line).toMatchObject({ text: "What ships on Friday?", sender: { name: "Priya" } });+ // Her own line with her own authority: never the relayed, information-only kind.+ const prompt = JSON.stringify(dump().prompt);+ expect(prompt).toContain("[From Priya (person) · message · their own request]");+ 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(priyaSlack, { audience: "team", text: "Is the report out?" });+ expect(first.status, JSON.stringify(first.body)).toBe(202);+ const again = await slack(priyaSlack, { 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);+ const afterwards = await slack(priyaSlack, { audience: "team", text: "Is the report out?", id: first.id });+ expect(afterwards.body).toEqual(first.body);+ await until(idle);+ const thread = await rows(priya, 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 bots(priya)).find((bot) => bot.id === 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);+ // Someone else presenting her message's id gets nothing of it.+ expect((await slack(tomSlack, { audience: "team", text: "Is the report out?", id: first.id })).status).toBe(403);+}, hostTimeout(120_000));++it("a thread continues its conversation by id, for whoever writes next, and only with the conversation's own audience", async () => {+ const more = await slack(priyaSlack, { audience: "team", conversationId: channelThread, bot: { id: scout.id }, 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 toms = await slack(tomSlack, { audience: "team", conversationId: channelThread, text: "Tom here: who is on call?" });+ expect(toms.status, JSON.stringify(toms.body)).toBe(202);+ await finished(toms.id);+ expect((await rows(ada, channelThread)).filter((row) => row.role === "user").map((row) => row.sender?.name)).toEqual(["Priya", "Priya", "Tom"]);++ const gone = { error: "No such conversation.", code: "no_such_conversation" };+ for (const refused of [+ await slack(priyaSlack, { audience: "member", conversationId: channelThread, text: "into my private chat" }),+ await slack(priyaSlack, { audience: "team", conversationId: "t_does_not_exist", text: "nowhere" }),+ ]) {+ expect(refused.status).toBe(409);+ expect(refused.body).toEqual(gone);+ }+}, hostTimeout(120_000));++it("a direct message is the member's private chat: only they read it, an admin and another member get 404", async () => {+ const sent = await slack(priyaSlack, { audience: "member", bot: { name: "scout" }, text: "Private notes please" });+ expect(sent.status, JSON.stringify(sent.body)).toBe(202);+ expect(sent.body.bot).toEqual({ id: scout.id, name: "Scout" });+ directThread = sent.body.conversationId;+ await finished(sent.id);+ expect(lastReport(sent.id).text).toBe(ANSWERS["Private notes please"]);+ expect(await taskOf(priya, scout.id, directThread)).toMatchObject({ title: "Slack DM: Private notes please", private: true });+ expect((await team.as(priya, "GET", `/api/threads/${directThread}/messages?limit=50`)).status).toBe(200);+ for (const token of [tom, ada, ari]) {+ const read = await team.as(token, "GET", `/api/threads/${directThread}/messages?limit=50`);+ expect(read.status, JSON.stringify(read.body)).toBe(404);+ expect(await taskOf(token, scout.id, directThread)).toBeUndefined();+ expect((await team.as(token, "POST", `/api/bots/${scout.id}/messages`, { text: "let me in", threadId: directThread })).status).toBe(404);+ }+ // Neither a channel's message nor anyone else's direct message can be put into it.+ const gone = { error: "No such conversation.", code: "no_such_conversation" };+ for (const refused of [+ await slack(priyaSlack, { audience: "team", conversationId: directThread, text: "from a channel" }),+ await slack(tomSlack, { audience: "member", conversationId: directThread, text: "from Tom" }),+ await slack(adaSlack, { audience: "member", conversationId: directThread, text: "from the owner" }),+ ]) {+ expect(refused.status).toBe(409);+ expect(refused.body).toEqual(gone);+ }+ expect((await rows(priya, directThread)).filter((row) => row.role === "user")).toHaveLength(1);+}, hostTimeout(120_000));++it("a final report the Admin did not take is sent again until it does", async () => {+ admin.failFinal = 1;+ const sent = await slack(priyaSlack, { audience: "member", conversationId: directThread, text: "Draft my week" });+ expect(sent.status, JSON.stringify(sent.body)).toBe(202);+ await finished(sent.id, "completed");+ expect(admin.failFinal).toBe(0);+ expect(statuses(sent.id)).toEqual(["running", "completed"]);+}, hostTimeout(120_000));++it("the bot is the one named, +Name ignoring case, or the member's default; the list is the bots they can chat with", async () => {+ const mine = await team.as(priyaSlack, "GET", "/api/slack/team/bots");+ expect(mine.status).toBe(200);+ const listed = mine.body.bots as { id: string; name: string; shared: boolean; avatarUrl?: string }[];+ const sharedOf = Object.fromEntries(listed.map((bot) => [bot.id, bot.shared]));+ expect([sharedOf[scout.id], sharedOf[reporter.id], sharedOf[notes.id], sharedOf[priyaOwn.id]]).toEqual([true, true, false, false]);+ expect(listed.find((bot) => bot.id === scout.id)).toEqual({ id: scout.id, name: "Scout", shared: true });+ expect(listed.map((bot) => bot.id)).not.toContain(vault.id);+ expect(listed.map((bot) => bot.id)).not.toContain(payroll.id);+ expect(listed.every((bot) => !("avatarUrl" in bot))).toBe(true);+ const owners = (await team.as(adaSlack, "GET", "/api/slack/team/bots")).body.bots as { id: string; name: string; shared: boolean }[];+ expect(owners.find((bot) => bot.id === vault.id)).toEqual({ id: vault.id, name: "Vault", shared: false });+ expect(owners.map((bot) => bot.id)).not.toContain(priyaOwn.id);++ const byDefault = await slack(priyaSlack, { audience: "member", bot: { default: true }, text: "Remind me what I like" });+ expect(byDefault.status, JSON.stringify(byDefault.body)).toBe(202);+ expect(byDefault.body.bot.id).toBe(priyaOwn.id);+ await finished(byDefault.id);+ const named = await slack(priyaSlack, { audience: "member", bot: { name: "NOTES" }, text: "Draft my week" });+ expect(named.status, JSON.stringify(named.body)).toBe(202);+ expect(named.body.bot).toEqual({ id: notes.id, name: "Notes" });+ await finished(named.id);+}, hostTimeout(120_000));++it("a bot private to its owner is refused in a channel; a bot the member can't chat with answers exactly as one that doesn't exist", async () => {+ for (const [token, bot] of [[adaSlack, { id: vault.id }], [priyaSlack, { id: notes.id }], [priyaSlack, { name: "Notes" }], [priyaSlack, { id: priyaOwn.id }]] as const) {+ const refused = await slack(token, { audience: "team", bot, text: "in a channel" });+ expect(refused.status, JSON.stringify(refused.body)).toBe(403);+ expect(refused.body).toEqual({ error: "That bot is private to its owner.", code: "bot_private" });+ }+ const missing = await slack(priyaSlack, { 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" });+ for (const audience of ["team", "member"] as const) {+ for (const bot of [{ id: vault.id }, { name: "Vault" }, { id: payroll.id }, { name: "Payroll" }, { name: "Nobody" }]) {+ const refused = await slack(priyaSlack, { audience, bot, text: "hello" });+ expect(refused.status, JSON.stringify(refused.body)).toBe(missing.status);+ expect(refused.body).toEqual(missing.body);+ }+ }+ for (const bot of [vault, payroll]) expect((await bots(ada)).find((one) => one.id === bot.id)!.tasks ?? []).toHaveLength(1);+}, hostTimeout(120_000));++it("a channel's conversation never reads the member's private notes or About you; their direct message does", async () => {+ expect((await team.as(priya, "PUT", "/api/me", { aboutMe: ABOUT })).status).toBe(200);+ const layer = dataFile("workspaces", `${scout.id}--member-${priyaKey}`);+ mkdirSync(join(layer, "memory"), { recursive: true });+ writeFileSync(join(layer, "MEMORY.md"), `# Memory\n\n- Priya's badge code is ${BADGE}\n`);+ const seen = async (ask: Ask) => {+ await until(idle);+ rmSync(file("dump.json"), { force: true });+ const sent = await slack(priyaSlack, ask);+ expect(sent.status, JSON.stringify(sent.body)).toBe(202);+ await finished(sent.id);+ await until(() => existsSync(file("dump.json")));+ return JSON.stringify(dump());+ };+ const direct = await seen({ audience: "member", conversationId: directThread, text: "Remind me what I like" });+ expect(direct).toContain(ABOUT);+ expect(direct).toContain(BADGE);+ for (const ask of [{ audience: "team", conversationId: channelThread, text: "What is my badge code?" }, { audience: "team", text: "What is my badge code?" }] as const) {+ const shared = await seen(ask);+ expect(shared).not.toContain(ABOUT);+ expect(shared).not.toContain(BADGE);+ expect(shared).not.toContain(`--member-${priyaKey}`);+ }+}, hostTimeout(180_000));++it("an approval is reported as waiting, sits in the member's inbox and conversation, and is answered only in MausBot", async () => {+ await until(idle);+ writeFileSync(file("hang-mode"), "");+ rmSync(file("release"), { force: true });+ rmSync(file("dump.json"), { force: true });+ const text = `Clean the build ${randomUUID()}`;+ const sent = await slack(priyaSlack, { audience: "team", bot: { id: reporter.id }, text });+ expect(sent.status, JSON.stringify(sent.body)).toBe(202);+ const thread = sent.body.conversationId as string;+ let socketPath: string | undefined;+ await until(() => {+ try {+ const turn = dump();+ if (JSON.stringify(turn.prompt).includes(text)) socketPath = turn.mcpConfig?.mcpServers?.ogb?.args?.[1];+ } catch { /* not written yet */ }+ return socketPath !== undefined;+ }, 30_000);+ rmSync(file("hang-mode"), { force: true });+ const socket = connect(socketPath!);+ sockets.push(socket);+ socket.on("error", () => {});+ await new Promise<void>((resolve, reject) => { socket.once("connect", resolve); socket.once("error", reject); });+ const requestId = randomUUID();+ socket.write(`${JSON.stringify({ t: "ask", id: requestId, tool: "Bash", input: { command: "rm -rf ./build" } })}\n`);++ await until(() => statuses(sent.id).at(-1) === "waiting");+ expect(lastReport(sent.id)).toMatchObject({ status: "waiting", waiting: "approval", conversationId: thread });+ expect((await rows(priya, thread)).some((row) => row.card?.requestId === requestId)).toBe(true);+ const inbox = async () => ((await team.as(priya, "GET", "/api/inbox")).body.rows ?? []) as { card?: { requestId?: string; answered?: string }; tab?: string }[];+ await until(async () => (await inbox()).some((row) => row.card?.requestId === requestId && row.tab === "needs-you"));+ // Slack's only other route, Stop, is not an answer; the card stays open until she answers it in MausBot.+ expect(statuses(sent.id).filter((status) => status === "waiting")).toHaveLength(1);+ const allowed = await team.as(priya, "POST", `/api/threads/${thread}/respond`, { requestId, behavior: "allow" });+ expect(allowed.status, JSON.stringify(allowed.body)).toBe(200);+ await until(() => statuses(sent.id).at(-1) === "running");+ writeFileSync(file("release"), "");+ await finished(sent.id);+ expect(statuses(sent.id)).toEqual(["running", "waiting", "running", "completed"]);+}, hostTimeout(180_000));++it("Stop from Slack is the asker's: another member is refused and the run goes on; the asker's stops it and is reported", async () => {+ await until(idle);+ rmSync(file("release"), { force: true });+ writeFileSync(file("tool-calls.json"), JSON.stringify([HOLD]));+ const sent = await slack(priyaSlack, { audience: "team", 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(priya, thread)).some((row) => row.kind === "activity" && JSON.stringify(row.tool ?? {}).includes("gh run watch 42")));+ writeFileSync(file("tool-calls.json"), "[]");++ const toms = await stop(tomSlack, sent.id);+ expect(toms.status, JSON.stringify(toms.body)).toBe(403);+ expect(toms.body).toMatchObject({ code: "stop_not_yours", error: "Only Priya or an admin can stop this." });+ expect((await taskOf(ada, scout.id, thread))?.busy).toBe(true);+ expect(statuses(sent.id)).toEqual(["running"]);+ expect((await stop(priyaSlack, randomUUID())).status).toBe(404);++ const hers = await stop(priyaSlack, sent.id);+ expect(hers.status, JSON.stringify(hers.body)).toBe(200);+ expect(typeof hers.body.stopped).toBe("boolean");+ await finished(sent.id, "stopped");+ await until(async () => !(await taskOf(ada, scout.id, thread))?.busy);+ expect((await rows(tom, thread)).findLast((row) => row.kind === "activity" && row.stoppedBy)?.stoppedBy?.name).toBe("Priya");+ expect((await stop(priyaSlack, sent.id)).body).toEqual({ stopped: true });+}, hostTimeout(180_000));++it("every report is signed in Slack's own context with the bootstrap secret, and nothing else passes for one", 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(team.machineId);+ expect(signature).toBe(`v1=${teamSlackSignature(team.secret, team.machineId, timestamp, nonce, raw)}`);+ expect(signature).not.toBe(`v1=${teamRosterSignature(team.secret, team.machineId, timestamp, nonce, raw)}`);+ expect(signature).not.toBe(`v1=${cloudRequestSignature(team.secret, timestamp, nonce, "POST", TEAM_SLACK_REPORT_PATH, raw)}`);+ }+ // The stand-in refuses what the real Admin refuses: another context's signature, and another secret's.+ 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": team.machineId, "x-omb-cloud-timestamp": timestamp, "x-omb-cloud-nonce": nonce, "x-omb-cloud-signature": `v1=${sign(timestamp, nonce)}` } });+ };+ expect((await send((timestamp, nonce) => teamRosterSignature(team.secret, team.machineId, timestamp, nonce, raw))).status).toBe(401);+ expect((await send((timestamp, nonce) => teamSlackSignature(randomBytes(32).toString("base64url"), team.machineId, timestamp, nonce, raw))).status).toBe(401);+ expect((await send((timestamp, nonce) => teamSlackSignature(team.secret, team.machineId, timestamp, nonce, raw))).status).toBe(200);+ // What this Cloud keeps of Slack's messages is ids and state, never their words.+ const kept = readFileSync(dataFile(TEAM_SLACK_FILE), "utf8");+ for (const words of [...Object.keys(ANSWERS), ...Object.values(ANSWERS), "C0SALES", "U0PRIYA", PRIYA.email]) expect(kept).not.toContain(words);+}, hostTimeout(60_000));++it("when a member leaves, their direct-message conversations go with their private chats; the channel's stay", async () => {+ await until(idle);+ const before = JSON.parse(readFileSync(dataFile(TEAM_SLACK_FILE), "utf8")) as { messages: { person: string; threadId: string }[] };+ expect(before.messages.some((message) => message.person === priyaKey && message.threadId === directThread)).toBe(true);+ const left = await team.signed("POST", "/api/cloud/team/member-left", { email: PRIYA.email });+ expect(left.status, JSON.stringify(left.body)).toBe(200);+ expect(left.body.chats).toBeGreaterThanOrEqual(2);+ expect((await team.as(priyaSlack, "GET", "/api/slack/team/bots")).status).toBe(401);+ const after = JSON.parse(readFileSync(dataFile(TEAM_SLACK_FILE), "utf8")) as { messages: { person: string }[] };+ expect(after.messages.filter((message) => message.person === priyaKey)).toEqual([]);+ // Joining again restores nothing: the direct message's conversation is gone for her too.+ const back = (await team.pair(PRIYA, { label: SLACK_LABEL })).token!;+ expect((await team.as(back, "GET", `/api/threads/${directThread}/messages?limit=50`)).status).toBe(404);+ expect((await slack(back, { audience: "member", conversationId: directThread, text: "still there?" })).body.code).toBe("no_such_conversation");+ expect(existsSync(dataFile("workspaces", `${scout.id}--member-${priyaKey}`))).toBe(false);+ expect((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]) {+ 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);+ expect(answer.status, `${method} ${path}`).toBe(404);+ expect(answer.body.code).toBeUndefined();+ }+ }+}, hostTimeout(60_000));diff --git a/server/host/conversation-shares.test.ts b/server/host/conversation-shares.test.tsindex 3b9c3315e6..85e5a283a3 100644--- a/server/host/conversation-shares.test.ts+++ b/server/host/conversation-shares.test.ts@@ -31,6 +31,16 @@ describe("conversation shares", () => {expect(createConversationShares({ dataDir: dir, team: true }).audienceOf("t1"), "kept across a restart").toBe("team");});+ it("remembers a conversation its person opened from a Slack channel, across a restart", () => {+ const shares = createConversationShares({ dataDir: dir, team: true });+ shares.share("t1", rui, "team", 100, "slack");+ shares.share("t2", rui, "team", 100);+ const again = createConversationShares({ dataDir: dir, team: true });+ expect([again.fromSlack("t1"), again.fromSlack("t2"), again.fromSlack("t3")]).toEqual([true, false, false]);+ expect(again.audienceOf("t1")).toBe("team");+ expect(createConversationShares({ dataDir: dir, team: false }).fromSlack("t1")).toBe(false);+ });+it("is nothing off a team", () => {createConversationShares({ dataDir: dir, team: true }).share("t1", rui, marta);const off = createConversationShares({ dataDir: dir, team: false });diff --git a/server/host/conversation-shares.ts b/server/host/conversation-shares.tsindex 55e4d85244..be3c592024 100644--- a/server/host/conversation-shares.ts+++ b/server/host/conversation-shares.ts@@ -16,7 +16,9 @@ export const CONVERSATION_SHARES_FILE = "conversation-shares.json";const MAX_SHARES = 50_000;const person = z.string().regex(/^p_[\w-]{22}$/);-const shareSchema = z.object({ owner: person, with: z.union([z.literal("team"), person]), at: z.number(), before: z.object({ with: person, at: z.number() }).optional() });+const shareSchema = z.object({ owner: person, with: z.union([z.literal("team"), person]), at: z.number(), before: z.object({ with: person, at: z.number() }).optional(),+ /** Its person opened it from a Slack channel, shared with the team from its first line (host/team-slack-host.ts). */+ from: z.literal("slack").optional() });const fileSchema = z.record(z.string().regex(/^[\w-]{1,128}$/), shareSchema);export type ConversationShare = z.infer<typeof shareSchema>;@@ -59,6 +61,10 @@ export function createConversationShares(deps: { dataDir: string; team: booleanif (!share) return null;return share.with === "team" ? "team" : memberAudience(shareKey(threadId));},+ /** A Slack channel's conversation: the team's, and never the chat its bot opens to. */+ fromSlack(threadId: string): boolean {+ return deps.team && shares[threadId]?.from === "slack";+ },/** Who reads a conversation shared with one person: its owner and that person. Null for any other conversation. */readers(threadId: string): readonly string[] | null {const share = deps.team ? shares[threadId] : undefined;@@ -84,10 +90,10 @@ export function createConversationShares(deps: { dataDir: string; team: booleanif (!share || entry.at >= share.at || person === share.owner) return true;return Boolean(share.before && person === share.before.with && entry.at >= share.before.at);},- share(threadId: string, owner: string, to: "team" | string, at = Date.now()): ConversationShare {+ share(threadId: string, owner: string, to: "team" | string, at = Date.now(), from?: "slack"): ConversationShare {const earlier = shares[threadId];const before = earlier && earlier.with !== "team" ? { with: earlier.with, at: earlier.at } : undefined;- const share = shareSchema.parse({ owner, with: to, at, ...(before ? { before } : {}) });+ const share = shareSchema.parse({ owner, with: to, at, ...(before ? { before } : {}), ...(from ? { from } : {}) });shares[threadId] = share;save();return share;diff --git a/server/host/team-slack-host.ts b/server/host/team-slack-host.tsnew file mode 100644index 0000000000..0c424d7087--- /dev/null+++ b/server/host/team-slack-host.ts@@ -0,0 +1,349 @@+// Slack for Team Clouds on the Team Cloud (docs/team-slack.md, server/team-slack.ts): a message the Admin hands over+// with the member's own session becomes that member's own line, sent the way their composer sends it, in a conversation+// 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.+// 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+// answer stops or starts anything.+import { isPersistentQuestionCard } from "../../shared/ask-question.ts";+import { atLeast } from "../../shared/bot-access.ts";+import { defaultBotPerson } from "../../shared/default-bot.ts";+import type { ResolvedSender } from "../../shared/wire.ts";+import { memberAudience, type Audience } from "../audience.ts";+import type { VisibleSet } from "../bot-visibility.ts";+import type { CloudHomeConfig } from "../cloud-home.ts";+import type { DirectSendInput, DirectSendReceipt } from "../direct-send.ts";+import { requestNeedsInput } from "../guarded-requests.ts";+import { personKey } from "../person-key.ts";+import type { RequestAuth } from "../request-auth.ts";+import { isStopCommand } from "../room-holds.ts";+import { serverLine } from "../server-lines.ts";+import { cancelSteeredMessage, onSteeredQueueChange, queuedSteeredMessage, queuedSteerSender } from "../steer-queue.ts";+import 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,+} from "../team-slack.ts";+import type { UsageTrigger } from "../usage-ledger.ts";+import { sharedBeyondOwner } from "./member-bots.ts";+import type { Actor } from "./run-owner.ts";+import { oneLine } from "./text-clip.ts";++/** A run that reads as ended without an answer is failed only once it has read so for this long: a turn's end, a+ * restart on another engine and a queued line's start each leave the conversation idle for a moment. */+export const TEAM_SLACK_SETTLE_MS = 8_000;+const RETRY_MS = [5_000, 15_000, 60_000, 5 * 60_000], RETRY_FOR_MS = 6 * 3_600_000;++interface Timer { unref?(): unknown }++export interface TeamSlackHostDeps {+ cloudHome: Pick<CloudHomeConfig, "team" | "machineId" | "adminOrigin" | "publicOrigin" | "bootstrapSecret"> | null;+ dataDir: string;+ store: Pick<Store, "bot" | "bots" | "botByThread" | "taskByThread" | "createTask" | "activePath" | "onChange">;+ visibleFor(auth: RequestAuth): Pick<VisibleSet, "bot" | "level" | "thread">;+ sender(auth: RequestAuth): ResolvedSender | undefined;+ trigger(auth: RequestAuth): UsageTrigger;+ actor(auth: RequestAuth): Actor;+ audienceOf(threadId: string): Audience;+ starters: { set(threadId: string, person: string): void };+ /** Shares a conversation its person just opened with the team, as one from Slack. */+ shareFromSlack(threadId: string, person: string): void;+ /** The app's own deletion of a conversation. */+ discard(botId: string, threadId: string): void;+ /** The composer's own send (index.ts acceptDirectSend). */+ send(input: DirectSendInput): Promise<DirectSendReceipt>;+ busy(botId: string, threadId: string): boolean;+ /** Work this conversation handed to other bots is still moving. */+ handedOn(threadId: string): boolean;+ /** The request this conversation's run answers. */+ request(threadId: string): { messageId?: string } | undefined;+ stopRefusal(threadId: string, by: Actor): string | null;+ removeRefusal(threadId: string, sender: ResolvedSender | undefined, by: Actor): string | null;+ stopThread(botId: string, threadId: string, by?: ResolvedSender): Promise<void>;+ language(person?: string): string | undefined;+ reporter?: TeamSlackReporter;+ now?: () => number;+ setTimer?: (run: () => void, ms: number) => Timer;+}++export interface TeamSlackAnswer { status: number; body: Record<string, unknown> }++type Phase = { state: TeamSlackState; waiting?: TeamSlackWaiting; text?: string } | "unsettled";++const refusal = (status: number, code: string, error: string): TeamSlackAnswer => ({ status, body: { error, code } });+const NO_SUCH_BOT = refusal(404, "no_such_bot", "No such bot.");+const NO_SUCH_CONVERSATION = refusal(409, "no_such_conversation", "No such conversation.");++/** Usable where everyone the team shares the bot with reads along: never a member's own MausBot, never a bot only its owner uses. */+export const teamSlackShared = (bot: BotRecord): boolean => !defaultBotPerson(bot) && sharedBeyondOwner(bot);++const openCard = (message: Message): boolean => Boolean(message.card?.requestId && !message.card.answered && !message.card.dismissed && !message.card.expired);+const isRequest = (message: Message): boolean => message.requestPending !== undefined || message.requestCancelled === true;++/** The member's line and the request it runs under: that line, or the one it joined (one person's lines that waited+ * together are answered by one turn, the last of them its request). */+export function teamSlackLines(path: readonly Message[], sendId: string): { at: number; request: number } | null {+ const at = path.findIndex((message) => message.role === "user" && message.sendId === sendId);+ if (at < 0) return null;+ let request = at;+ if (path[at]!.steered) {+ while (request >= 0 && !(path[request]!.role === "user" && isRequest(path[request]!))) request--;+ } else {+ while (!isRequest(path[request]!) && path[request + 1]?.role === "user" && !path[request + 1]!.steered) request++;+ }+ return { at, request: request >= 0 && isRequest(path[request]!) ? request : -1 };+}++/** What the conversation's records say of one Slack message's run. */+export function teamSlackPhase(path: readonly Message[], sendId: string, live: { queued: boolean; busy: boolean; handedOn: boolean }): Phase {+ if (live.queued) return { state: "running" };+ const lines = teamSlackLines(path, sendId);+ if (!lines) return { state: "stopped" };+ if (lines.request < 0) return live.busy ? { state: "running" } : "unsettled";+ const line = path[lines.request]!;+ if (line.requestCancelled) return { state: "stopped" };+ const after = path.slice(lines.request + 1);+ const next = after.findIndex((message) => message.role === "user" && !message.steered);+ const run = next < 0 ? after : after.slice(0, next);+ if (line.requestPending === false) {+ const reply = lines.request === lines.at ? run.findLast((message) => message.role === "bot" && message.kind === "text" && message.turnTerminal) : undefined;+ return { state: "completed", ...(reply?.text ? { text: reply.text } : {}) };+ }+ if (next >= 0) return { state: "failed" };+ // A question outlives the turn that asked it, so it holds this run only while that turn is still blocked on it.+ const card = run.find((message) => requestNeedsInput(message) || (live.busy && openCard(message)));+ if (card) return { state: "waiting", waiting: card.card?.requestId && !isPersistentQuestionCard(card.card) ? "approval" : "question" };+ return live.busy || live.handedOn ? { state: "running" } : "unsettled";+}++export function createTeamSlackHost(deps: TeamSlackHostDeps) {+ const home = deps.cloudHome?.team ? deps.cloudHome : null;+ if (!home) return null;+ 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 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 chattable = (auth: RequestAuth) => {+ const visible = deps.visibleFor(auth);+ return (bot: BotRecord) => !bot.hidden && visible.bot(bot.id) && atLeast(visible.level(bot.id), "chat");+ };+ const openUrl = (record: Pick<TeamSlackRecord, "botId" | "threadId">) => `${home.publicOrigin}/?thread=${encodeURIComponent(record.threadId)}&bot=${encodeURIComponent(record.botId)}`;+ const accepted = (record: TeamSlackRecord): TeamSlackAccepted => ({ accepted: true, conversationId: record.threadId, bot: { id: record.botId, name: record.botName }, openUrl: openUrl(record) });++ const sending = new Set<string>(), unsettledSince = new Map<string, number>(), retries = new Map<string, { tries: number; since: number }>();+ /** Each settled run's final reply, in memory until the Admin has it: the conversation may move on before a retry. */+ const replies = new Map<string, string>();+ const open = () => messages.all().filter((record) => !teamSlackOver(record));++ const phaseOf = (record: TeamSlackRecord): Phase => {+ if (!store.taskByThread(record.botId, record.threadId)) return { state: "stopped" };+ return teamSlackPhase(store.activePath(record.threadId), record.id, {+ queued: queuedSteeredMessage(record.botId, record.threadId, record.id) !== null,+ busy: deps.busy(record.botId, record.threadId), handedOn: deps.handedOn(record.threadId),+ });+ };++ async function flush(id: string): Promise<void> {+ if (sending.has(id)) return;+ sending.add(id);+ try {+ for (;;) {+ const record = messages.get(id);+ if (!record || teamSlackOver(record) || record.told === teamSlackKey(record)) return;+ const key = teamSlackKey(record), final = TEAM_SLACK_FINAL.has(record.state);+ const phase = record.state === "completed" && !replies.has(id) ? phaseOf(record) : null;+ const text = replies.get(id) ?? (phase && phase !== "unsettled" ? phase.text : undefined);+ const body: TeamSlackReport = {+ id, status: record.state, conversationId: record.threadId, bot: { id: record.botId, name: record.botName }, openUrl: openUrl(record),+ ...(record.state === "waiting" ? { waiting: record.waiting ?? "question" } : {}),+ ...(record.state === "failed" ? { error: "failed" as const } : {}),+ ...(record.state === "completed" && text ? { text: text.slice(0, TEAM_SLACK_ANSWER_MAX) } : {}),+ };+ const outcome = await report(body);+ const current = messages.get(id);+ if (!current) return;+ if (outcome === "over") { replies.delete(id); messages.patch(id, { closed: true }); return; }+ if (outcome === "told") { retries.delete(id); if (final) replies.delete(id); messages.patch(id, { told: key }); continue; }+ if (teamSlackKey(current) !== key) continue;+ // A report the Admin won't take as it is, or a `running` nobody answered, is not said again; the next state is.+ if (outcome === "refused" || (!final && current.state === "running")) { if (final) { replies.delete(id); messages.patch(id, { closed: true }); } return; }+ const tried = retries.get(id) ?? { tries: 0, since: now() };+ if (now() - tried.since > RETRY_FOR_MS) { retries.delete(id); replies.delete(id); messages.patch(id, { closed: true }); return; }+ retries.set(id, { tries: tried.tries + 1, since: tried.since });+ later(() => void flush(id), RETRY_MS[Math.min(tried.tries, RETRY_MS.length - 1)]!);+ return;+ }+ } finally {+ sending.delete(id);+ }+ }++ function settle(id: string): void {+ const record = messages.get(id);+ if (!record || teamSlackOver(record) || TEAM_SLACK_FINAL.has(record.state)) return;+ let phase = phaseOf(record);+ if (phase === "unsettled") {+ const since = unsettledSince.get(id) ?? now();+ unsettledSince.set(id, since);+ if (now() - since < TEAM_SLACK_SETTLE_MS) { later(() => settle(id), TEAM_SLACK_SETTLE_MS - (now() - since) + 50); return; }+ phase = { state: "failed" };+ }+ unsettledSince.delete(id);+ if (phase.state === record.state && phase.waiting === record.waiting) return;+ if (phase.state === "completed" && phase.text) replies.set(id, phase.text);+ messages.patch(id, { state: phase.state, waiting: phase.waiting });+ void flush(id);+ }++ /** After the change's own fold has finished: a turn's end frees the conversation before it settles the request. */+ const pending = new Set<string>();+ const soon = (records: readonly TeamSlackRecord[]) => {+ for (const record of records) {+ if (pending.has(record.id)) continue;+ pending.add(record.id);+ setImmediate(() => { pending.delete(record.id); settle(record.id); });+ }+ };+ store.onChange((change) => {+ if (change.type === "message" || change.type === "message.patch" || change.type === "thread" || change.type === "thread.deleted") soon(open().filter((record) => record.threadId === change.threadId));+ else if (change.type === "bot" || change.type === "bot.deleted") soon(open().filter((record) => record.botId === change.botId));+ });+ onSteeredQueueChange(() => soon(open()));+ const beat = () => {+ for (const record of open()) {+ if (record.state === "running" && record.told === "running") messages.patch(record.id, { told: undefined });+ void flush(record.id);+ }+ later(beat, TEAM_SLACK_RUNNING_EVERY_MS);+ };+ later(beat, TEAM_SLACK_RUNNING_EVERY_MS);+ // What was open when this server last stopped: its run ended with the process, and what the Admin wasn't told is said now.+ later(() => { for (const record of open()) { settle(record.id); void flush(record.id); } }, 1_000);++ function title(input: TeamSlackMessage, person: string): string {+ 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 });+ }++ /** 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. */+ function sendRefused(error: unknown): TeamSlackAnswer {+ const thrown = error as { status?: unknown; code?: unknown; body?: { error?: unknown; code?: unknown }; message?: unknown } | null;+ const status = typeof thrown?.status === "number" ? thrown.status : 500;+ const code = typeof thrown?.body?.code === "string" ? thrown.body.code : typeof thrown?.code === "string" ? thrown.code : "refused";+ const words = typeof thrown?.body?.error === "string" ? thrown.body.error : typeof thrown?.message === "string" ? thrown.message : "The message could not be sent.";+ return refusal(status === 409 || status === 423 || status === 429 || status >= 500 ? status : 422, code, words);+ }++ async function take(auth: RequestAuth, person: string, input: TeamSlackMessage): Promise<TeamSlackAnswer> {+ const canChat = chattable(auth), visible = deps.visibleFor(auth);+ const wanted: Audience = input.audience === "team" ? "team" : memberAudience(person);+ 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;+ } else if ("id" in input.bot) {+ bot = store.bot(input.bot.id);+ } else if ("name" in input.bot) {+ const name = input.bot.name.toLowerCase();+ 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];+ }+ 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.");++ 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 (!task) return refusal(503, "unavailable", "The conversation could not be opened.");+ threadId = task.threadId;+ if (deps.audienceOf(threadId) !== wanted) {+ deps.discard(bot.id, threadId);+ return refusal(503, "unavailable", "The conversation could not be opened.");+ }+ }+ let receipt: DirectSendReceipt;+ 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);+ return sendRefused(error);+ }+ // A line made of stop words ended the run instead of starting one, as it does in the app.+ const stopWords = !("queued" in receipt) && !receipt.steered && isStopCommand(input.text, bot.name) && deps.request(threadId)?.messageId !== receipt.message.id;+ const record: TeamSlackRecord = { id: input.id, person, botId: bot.id, botName: bot.name, threadId, audience: input.audience, at: now(), state: stopWords ? "stopped" : "running" };+ messages.put(record);+ void flush(record.id);+ soon([record]);+ return { status: 202, body: { ...accepted(record) } };+ }++ const taking = new Map<string, { person: string; answer: Promise<TeamSlackAnswer> }>();++ return {+ /** 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) })) } };+ },+ /** Starts or continues a conversation with one Slack message, once per id. */+ message(auth: RequestAuth, input: TeamSlackMessage): Promise<TeamSlackAnswer> {+ const who = member(auth);+ if (!who) return Promise.resolve(refusal(404, "not_a_member", "Not found."));+ const notYours = refusal(403, "not_yours", "That message is someone else's.");+ const known = messages.get(input.id);+ if (known) return Promise.resolve(known.person === who.person ? { status: 202, body: { ...accepted(known) } } : notYours);+ const running = taking.get(input.id);+ if (running) return running.person === who.person ? running.answer : Promise.resolve(notYours);+ const answer = take(auth, who.person, input).finally(() => taking.delete(input.id));+ taking.set(input.id, { person: who.person, answer });+ return answer;+ },+ /** Stop, pressed in Slack by this member: theirs to stop by the app's own rule, or refused. */+ async stop(auth: RequestAuth, id: string): Promise<TeamSlackAnswer> {+ const who = member(auth);+ if (!who) return refusal(404, "not_a_member", "Not found.");+ const record = messages.get(id);+ if (!record) return refusal(404, "no_such_message", "No such message.");+ if (TEAM_SLACK_FINAL.has(record.state)) return { status: 200, body: { stopped: true } };+ const by = deps.actor(auth), visible = deps.visibleFor(auth);+ const notTheirs = refusal(403, "stop_not_yours", "Only the person who asked can stop this.");+ if (!visible.thread(record.threadId) || !atLeast(visible.level(record.botId), "chat")) return notTheirs;+ const waiting = queuedSteeredMessage(record.botId, record.threadId, id);+ if (waiting) {+ if (deps.removeRefusal(record.threadId, queuedSteerSender(record.botId, record.threadId, waiting.id)?.sender, by)) return notTheirs;+ cancelSteeredMessage(record.botId, waiting.id, record.threadId);+ settle(id);+ return { status: 200, body: { stopped: true } };+ }+ const path = store.activePath(record.threadId), lines = teamSlackLines(path, id), phase = phaseOf(record);+ if (phase !== "unsettled" && TEAM_SLACK_FINAL.has(phase.state)) { settle(id); return { status: 200, body: { stopped: true } }; }+ // Another request runs in this conversation now: this one is not what Stop would end.+ if (!lines || lines.request < 0 || deps.request(record.threadId)?.messageId !== path[lines.request]!.id) return { status: 200, body: { stopped: false } };+ const refused = deps.stopRefusal(record.threadId, by);+ if (refused) return refusal(403, "stop_not_yours", refused);+ await deps.stopThread(record.botId, record.threadId, deps.sender(auth));+ settle(id);+ return { status: 200, body: { stopped: messages.get(id)?.state === "stopped" } };+ },+ /** A member left the team: what this kept of their Slack messages goes; their direct-message conversations go with their private chats. */+ memberLeft(person: string): void {+ for (const id of messages.forgetPerson(person)) { unsettledSince.delete(id); retries.delete(id); replies.delete(id); }+ },+ };+}++export type TeamSlackHost = NonNullable<ReturnType<typeof createTeamSlackHost>>;diff --git a/server/index.ts b/server/index.tsindex 994b08c5fc..ba50e85191 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 { 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 { 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";@@ -2848,7 +2848,7 @@ const phones = createPhones({active: (turn) => internalCapabilityIsActive(turn as InternalCapability),});const cloudPlanTier = createCloudPlanTier({ dataDir: DATA_DIR, cloudHome: Boolean(CLOUD_HOME), changed: () => broadcast({ kind: "config", ...configStatus() }) }); const starterAwake = createStarterAwake({ dataDir: DATA_DIR, starter: () => cloudPlanTier.starter(), bots: () => store.bots, changed: () => broadcast({ kind: "config", ...configStatus() }) }); const starterCaps = createStarterCaps({ starter: () => cloudPlanTier.starter(), awake: starterAwake, waitsOnOthers: (threadId) => coordinator.outstandingFor(threadId).length > 0, laneOwned: (threadId) => burst.laneOwned(threadId), botName: (botId) => store.bot(botId)?.name, pausedLine: (language, limit) => serverLine(language, "server.botPaused", { limit }), refused: () => broadcast({ kind: "config", ...configStatus() }) }); engineMemory.useCap(starterCaps.engine); const botHolds = createBotHolds({ dataDir: DATA_DIR, bots: () => store.bots, line: (language, key, params) => serverLine(language, key, params), changed: () => broadcast({ kind: "config", ...configStatus() }) }); let cloudPower: CloudPower | null = null; // The sleep handshake of a plan that sleeps (server/cloud-power.ts), made just before the server listens.-const teamWelcome = createTeamWelcomeStore(DATA_DIR); const { cloudHealth, cloudSigned } = createCloudSignedHost({ cloudHome: CLOUD_HOME, sessions, power: () => cloudPower, box: () => botBox.report(), teamAdmin: teamAdminHost(), policyChanged: nudgeCloudTeamPolicy, invited: (email, by) => teamWelcome.invited(personKey({ id: "", email }), by), memberBrowserOff: () => managedPolicy.remoteAccessRefusal() !== undefined, plan: (cancelled) => routineHolds?.plan(cancelled), planTier: (tier) => cloudPlanTier.set(tier), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { botApi.manager.revokeMintedBy(personKey({ id: "", email })); teamOwners.left(email); teamMessages.inbox.forget(personKey({ id: "", email })); forgetSetupPresser(store, personKey({ id: "", email })); devsReports.forget(personKey({ id: "", email })); return result; }) : Promise.reject(new Error("not a team")), health: { store, bus, dataDir: DATA_DIR, eventsDir: EVENTS_DIR, version: serverVersion(), image: process.env.OMB_CLOUD_IMAGE,+const teamWelcome = createTeamWelcomeStore(DATA_DIR); const { cloudHealth, cloudSigned } = createCloudSignedHost({ cloudHome: CLOUD_HOME, sessions, power: () => cloudPower, box: () => botBox.report(), teamAdmin: teamAdminHost(), policyChanged: nudgeCloudTeamPolicy, invited: (email, by) => teamWelcome.invited(personKey({ id: "", email }), by), memberBrowserOff: () => managedPolicy.remoteAccessRefusal() !== undefined, plan: (cancelled) => routineHolds?.plan(cancelled), planTier: (tier) => cloudPlanTier.set(tier), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { botApi.manager.revokeMintedBy(personKey({ id: "", email })); teamOwners.left(email); teamMessages.inbox.forget(personKey({ id: "", email })); forgetSetupPresser(store, personKey({ id: "", email })); devsReports.forget(personKey({ id: "", email })); teamSlack?.memberLeft(personKey({ id: "", email })); return result; }) : Promise.reject(new Error("not a team")), health: { store, bus, dataDir: DATA_DIR, eventsDir: EVENTS_DIR, version: serverVersion(), image: process.env.OMB_CLOUD_IMAGE,engines: () => registry.instances().map((instance) => ({ instanceId: instance.instanceId, driverKind: instance.driverKind, snapshot: registry.knownSnapshot(instance.instanceId) })),connectors: () => emailHost.health(composio.configured(cfg) ? composio.connectedServices(cfg) : null),browser: () => ({ available: browserReady(undefined), installing: Boolean(browserEngineInstall), interrupted: browserRuntime.interruptedCount() }), firstHour: () => firstHourHooks.health(), ...(engineMemory.enabled ? { room: () => engineMemory.dayPressure() } : {}) } });@@ -8660,7 +8660,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" || 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)) : 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;+}); 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(createTeamRoutes({store,cfg,diff --git a/server/request-auth.ts b/server/request-auth.tsindex 8097e14335..3c83f7d769 100644--- a/server/request-auth.ts+++ b/server/request-auth.ts@@ -492,6 +492,10 @@ 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+ { methods: ["GET"], path: /^\/api\/slack\/team\/bots$/ },+ { methods: ["POST"], path: /^\/api\/slack\/team\/messages(?:\/[0-9a-f-]{36}\/stop)?$/ },];export function requiredScope(method: string, path: string, features: { sharedComputers?: boolean } = {}): Scope {diff --git a/server/routes/team-slack.ts b/server/routes/team-slack.tsnew file mode 100644index 0000000000..d48ea347db--- /dev/null+++ b/server/routes/team-slack.ts@@ -0,0 +1,37 @@+// 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.+import type { ServerResponse } from "node:http";++import type { TeamSlackAnswer, TeamSlackHost } from "../host/team-slack-host.ts";+import { teamSlackMessageSchema } from "../team-slack.ts";+import { PASS, type RouteHandler } from "./table.ts";++const STOP = /^\/api\/slack\/team\/messages\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/stop$/;++/** The contract's `bot` and `bots` are not the app's bot records, so they skip the filter every JSON body sent to a+ * member passes through, which would add the app's own fields to them. */+function answerWith(res: ServerResponse, answer: TeamSlackAnswer): void {+ res.writeHead(answer.status, { "content-type": "application/json", "cache-control": "no-store" });+ res.end(JSON.stringify(answer.body));+}++export function createTeamSlackRoutes(deps: { host: TeamSlackHost | null }): RouteHandler {+ return async ({ req, res, path, method, auth, json, readBody }) => {+ if (!path.startsWith("/api/slack/team/")) return PASS;+ const { host } = deps;+ if (!host) return json(res, 404, { error: "not found" });+ if (path === "/api/slack/team/bots" && method === "GET") return answerWith(res, host.bots(auth));+ if (path === "/api/slack/team/messages" && method === "POST") {+ const parsed = teamSlackMessageSchema.safeParse(await readBody(req));+ if (!parsed.success) return json(res, 400, { error: "Send a message as docs/team-slack.md says.", code: "bad_request" });+ return answerWith(res, await host.message(auth, parsed.data));+ }+ const stop = method === "POST" ? STOP.exec(path) : null;+ if (stop) {+ await readBody(req);+ return answerWith(res, await host.stop(auth, stop[1]!));+ }+ return json(res, 404, { error: "not found" });+ };+}diff --git a/server/team-slack.test.ts b/server/team-slack.test.tsnew file mode 100644index 0000000000..6350d54de6--- /dev/null+++ b/server/team-slack.test.ts@@ -0,0 +1,160 @@+import { mkdtempSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { teamSlackPhase } from "./host/team-slack-host.ts";+import type { Message } from "./store.ts";+import { TEAM_SLACK_FILE, TEAM_SLACK_REPORT_PATH, createTeamSlackMessages, createTeamSlackReporter, teamSlackMessageSchema, teamSlackOver, teamSlackSignature, type TeamSlackRecord, type TeamSlackReport } from "./team-slack.ts";++const ID = "6f0c1a2b-3c4d-4e5f-8a9b-0c1d2e3f4a5b", LATER = "7a1d2b3c-4d5e-4f6a-9b0c-1d2e3f4a5b6c";+let seq = 0;+const row = (fields: Partial<Message>): Message => ({ id: `m${++seq}`, at: seq, role: "user", kind: "text", text: "", ...fields } as Message);+const reply = (text: string, fields: Partial<Message> = {}) => row({ role: "bot", text, turnTerminal: true, ...fields });+const idle = { queued: false, busy: false, handedOn: false }, busy = { ...idle, busy: true };+const dirs: string[] = [];+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });++describe("teamSlackSignature", () => {+ it("signs as the Admin checks: the Slack context, the machine, the time, the nonce and the body's hash", () => {+ // The value openmaus-cloud's teamSlackSignature gives for the same input.+ expect(teamSlackSignature("s3cret-s3cret", "machine-1", "1731662000", "nonce-nonce-nonce", '{"v":1}')).toBe("Ajtt5Il9oDl9T2EOM8ebLe5iTiDiES4oheQp2ZwcUTk");+ });+});++describe("teamSlackMessageSchema", () => {+ const message = { v: 1, id: ID, audience: "team", bot: { id: "bot_1" }, conversationId: null, text: "hello",+ slack: { workspace: "T1", channel: "C1", threadTs: "1731662000.000100", messageTs: "1731662000.000100", user: "U1" } };+ it("takes the contract's message, each way of naming the bot, and a channel's name", () => {+ expect(teamSlackMessageSchema.safeParse(message).success).toBe(true);+ for (const bot of [{ name: "Quotes" }, { default: true }]) expect(teamSlackMessageSchema.safeParse({ ...message, bot }).success).toBe(true);+ expect(teamSlackMessageSchema.safeParse({ ...message, slack: { ...message.slack, channelName: "sales" } }).success).toBe(true);+ });+ it("refuses another version, an id that is no uuid, an unknown audience and a bot named two ways", () => {+ for (const wrong of [{ v: 2 }, { id: "not-a-uuid" }, { audience: "room" }, { bot: { id: "bot_1", name: "Quotes" } }, { bot: { default: false } }, { text: "" }, { conversationId: "../etc" }]) {+ expect(teamSlackMessageSchema.safeParse({ ...message, ...wrong }).success, JSON.stringify(wrong)).toBe(false);+ }+ });+});++describe("teamSlackPhase", () => {+ it("is running while its line waits in the queue or its turn works, and unsettled when nothing yet says", () => {+ expect(teamSlackPhase([], ID, { ...idle, queued: true })).toEqual({ state: "running" });+ const path = [row({ sendId: ID, requestPending: true })];+ expect(teamSlackPhase(path, ID, busy)).toEqual({ state: "running" });+ expect(teamSlackPhase(path, ID, { ...idle, handedOn: true })).toEqual({ state: "running" });+ expect(teamSlackPhase(path, ID, idle)).toBe("unsettled");+ expect(teamSlackPhase([row({ sendId: ID })], ID, idle)).toBe("unsettled");+ });+ it("is completed with the turn's final reply once the request settled", () => {+ const path = [row({ sendId: ID, requestPending: false }), row({ role: "bot", text: "Looking…" }), reply("**Done**, it shipped.")];+ expect(teamSlackPhase(path, ID, idle)).toEqual({ state: "completed", text: "**Done**, it shipped." });+ });+ it("waits on an open approval or question, and no longer once it is answered", () => {+ const card = (fields: Record<string, unknown>) => row({ role: "bot", kind: "options", card: { title: "Run it?", subtitle: "", options: ["Allow"], requestId: "r1", ...fields } } as Partial<Message>);+ const line = row({ sendId: ID, requestPending: true }), approval = { requestType: "permission", tool: "Bash" }, question = { requestType: "question" };+ expect(teamSlackPhase([line, card(approval)], ID, busy)).toEqual({ state: "waiting", waiting: "approval" });+ expect(teamSlackPhase([line, card(question)], ID, busy)).toEqual({ state: "waiting", waiting: "question" });+ expect(teamSlackPhase([line, card({ ...approval, answered: "Allow" })], ID, busy)).toEqual({ state: "running" });+ // A question its turn left open is part of the reply, not a wait: the request settled.+ expect(teamSlackPhase([{ ...line, requestPending: false }, card(question), reply("Which one?")], ID, idle)).toEqual({ state: "completed", text: "Which one?" });+ expect(teamSlackPhase([line, card(question)], ID, idle)).toBe("unsettled");+ });+ it("is stopped when its request was cancelled, or its line is gone from the conversation", () => {+ expect(teamSlackPhase([row({ sendId: ID, requestPending: true, requestCancelled: true })], ID, busy)).toEqual({ state: "stopped" });+ expect(teamSlackPhase([row({ sendId: LATER, requestPending: true })], ID, busy)).toEqual({ state: "stopped" });+ });+ it("is failed when the next request began before this one settled", () => {+ const path = [row({ sendId: ID, requestPending: true }), row({ role: "bot", kind: "activity" }), row({ sendId: LATER, requestPending: true })];+ expect(teamSlackPhase(path, ID, busy)).toEqual({ state: "failed" });+ expect(teamSlackPhase(path, LATER, busy)).toEqual({ state: "running" });+ });+ it("a line that waited with a later one of the same person is answered by that one's turn, which carries the reply", () => {+ const path = [row({ sendId: ID }), row({ sendId: LATER, requestPending: false }), reply("Both answered.")];+ expect(teamSlackPhase(path, ID, idle)).toEqual({ state: "completed" });+ expect(teamSlackPhase(path, LATER, idle)).toEqual({ state: "completed", text: "Both answered." });+ });+ it("a line steered into a running request follows that request", () => {+ const path = [row({ sendId: LATER, requestPending: true }), row({ role: "bot", kind: "activity" }), row({ sendId: ID, steered: true })];+ expect(teamSlackPhase(path, ID, busy)).toEqual({ state: "running" });+ path[0] = { ...path[0]!, requestPending: false };+ expect(teamSlackPhase([...path, reply("Done.")], ID, idle)).toEqual({ state: "completed" });+ });+});++describe("the record of Slack messages", () => {+ it("is left out of a workspace export, by the name it is saved under", () => {+ expect(TEAM_SLACK_FILE).toBe("team-slack-messages.json");+ expect(readFileSync(new URL("./workspace-backup.ts", import.meta.url), "utf8")).toContain(`"${TEAM_SLACK_FILE}",`);+ });++ const record = (fields: Partial<TeamSlackRecord> = {}): TeamSlackRecord => ({ id: ID, person: "p_0123456789abcdefghijkl", botId: "bot_1", botName: "Quotes", threadId: "t_1", audience: "team", at: 1_000, state: "running", ...fields });+ const dir = () => { const made = mkdtempSync(join(tmpdir(), "team-slack-home-unit-")); dirs.push(made); return made; };+ it("survives a restart, is over once the Admin has the final state, and forgets a person who left", () => {+ const dataDir = dir();+ const first = createTeamSlackMessages({ dataDir, now: () => 2_000 });+ first.put(record());+ first.put(record({ id: LATER, person: "p_zyxwvutsrqponmlkjihgfe", audience: "member" }));+ const again = createTeamSlackMessages({ dataDir, now: () => 3_000 });+ expect(again.all().map((one) => one.id)).toEqual([ID, LATER]);+ expect(teamSlackOver(again.get(ID)!)).toBe(false);+ again.patch(ID, { state: "completed" });+ expect(teamSlackOver(again.get(ID)!)).toBe(false);+ again.patch(ID, { told: "completed" });+ expect(teamSlackOver(again.get(ID)!)).toBe(true);+ 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("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"];+ kept.put(record({ id: first }));+ kept.put(record({ id: second, state: "completed", told: "completed" }));+ kept.put(record({ id: third }));+ expect(kept.all().map((one) => one.id)).toEqual([first, third]);+ kept.put(record({ id: second }));+ expect(kept.all().map((one) => one.id)).toEqual([third, second]);+ });+ it("drops what is over after a week and anything after a month", () => {+ const dataDir = dir(), day = 24 * 3_600_000;+ let now = 0;+ const kept = createTeamSlackMessages({ dataDir, now: () => now });+ kept.put(record({ at: 0, state: "completed", told: "completed" }));+ kept.put(record({ id: LATER, at: 0 }));+ now = 8 * day;+ kept.patch(LATER, {});+ expect(kept.all().map((one) => one.id)).toEqual([LATER]);+ now = 31 * day;+ kept.patch(LATER, {});+ expect(kept.all()).toEqual([]);+ });+});++describe("createTeamSlackReporter", () => {+ const report: TeamSlackReport = { id: ID, status: "completed", text: "Done.", conversationId: "t_1", bot: { id: "bot_1", name: "Quotes" }, openUrl: "https://acme.example.test/?thread=t_1&bot=bot_1" };+ const reporter = (answer: () => Response | Promise<Response>, seen: { url: string; init: RequestInit }[] = []) => createTeamSlackReporter({ machineId: "machine-1", adminOrigin: "https://cloud.example.test", secret: "s3cret-s3cret", now: () => 1_731_662_000_000,+ fetchImpl: (async (url: string, init: RequestInit) => { seen.push({ url, init }); return answer(); }) as typeof fetch });+ const json = (status: number, body: unknown) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });++ it("posts the contract's body to the Admin's report path, signed over exactly those bytes", async () => {+ const seen: { url: string; init: RequestInit }[] = [];+ expect(await reporter(() => json(200, { ok: true }), seen)(report)).toBe("told");+ const { url, init } = seen[0]!, headers = init.headers as Record<string, string>;+ expect(url).toBe(`https://cloud.example.test${TEAM_SLACK_REPORT_PATH}`);+ expect(JSON.parse(String(init.body))).toEqual({ v: 1, ...report });+ expect(headers["x-omb-cloud-machine"]).toBe("machine-1");+ expect(headers["x-omb-cloud-timestamp"]).toBe("1731662000");+ expect(headers["x-omb-cloud-nonce"]).toMatch(/^[A-Za-z0-9_-]{16,128}$/);+ expect(headers["x-omb-cloud-signature"]).toBe(`v1=${teamSlackSignature("s3cret-s3cret", "machine-1", "1731662000", headers["x-omb-cloud-nonce"]!, String(init.body))}`);+ expect(init.redirect).toBe("error");+ });+ it("reads the Admin's answers: over, later, refused; a Stop it mentions is never acted on", async () => {+ expect(await reporter(() => json(200, { ok: true, done: true }))(report)).toBe("over");+ expect(await reporter(() => json(200, { ok: true, stop: true }))(report)).toBe("told");+ expect(await reporter(() => json(404, { code: "unknown_message" }))(report)).toBe("over");+ for (const status of [429, 500, 503]) expect(await reporter(() => json(status, {}))(report)).toBe("later");+ expect(await reporter(() => { throw new TypeError("fetch failed"); })(report)).toBe("later");+ expect(await reporter(() => new Response("<html>", { status: 200 }))(report)).toBe("later");+ for (const status of [400, 401, 409]) expect(await reporter(() => json(status, {}))(report)).toBe("refused");+ });+});diff --git a/server/team-slack.ts b/server/team-slack.tsnew file mode 100644index 0000000000..c0b901f0ff--- /dev/null+++ b/server/team-slack.ts@@ -0,0 +1,169 @@+// 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.+// 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";+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { z } from "zod";++import { writeFileAtomic } from "./atomic.ts";++/** On the Admin; must match openmaus-cloud's TEAM_SLACK_REPORT_PATH. */+export const TEAM_SLACK_REPORT_PATH = "/api/cloud/machines/slack";+export const TEAM_SLACK_FILE = "team-slack-messages.json";+/** The Admin's own limit on a final answer. */+export const TEAM_SLACK_ANSWER_MAX = 200_000;+export const TEAM_SLACK_RUNNING_EVERY_MS = 10 * 60_000;+const MAX_MESSAGES = 2_000, KEEP_FINISHED_MS = 7 * 24 * 3_600_000, KEEP_ANY_MS = 30 * 24 * 3_600_000;+const FETCH_TIMEOUT_MS = 15_000, ANSWER_MAX_BYTES = 16 * 1024;++/** Must match openmaus-cloud's teamSlackSignature: a context of its own, so no other signed request reads as a report. */+export function teamSlackSignature(secret: string, machineId: string, timestamp: string, nonce: string, body: string): string {+ const bodyHash = createHash("sha256").update(body).digest("base64url");+ return createHmac("sha256", secret).update(`omb-team-slack-v1\n${machineId}\n${timestamp}\n${nonce}\n${bodyHash}`).digest("base64url");+}++const slackId = z.string().regex(/^[A-Z0-9]{1,32}$/), slackTs = z.string().regex(/^\d{1,12}\.\d{1,9}$/);+// oxlint-disable-next-line no-control-regex+const plainName = z.string().trim().min(1).max(80).regex(/^[^\x00-\x1f\x7f]+$/);++/** POST /api/slack/team/messages. `slack` says where the message was written, for the conversation's title only: it is+ * never authority. `channelName` is additive: the Admin may send the channel's name, shown as "#name". */+export const teamSlackMessageSchema = z.object({+ v: z.literal(1),+ id: z.uuid(),+ audience: z.enum(["team", "member"]),+ bot: z.union([z.object({ id: z.string().regex(/^[\w-]{1,200}$/) }).strict(), z.object({ name: plainName }).strict(), z.object({ default: z.literal(true) }).strict()]),+ conversationId: z.string().regex(/^[\w-]{1,128}$/).nullable(),+ text: z.string().min(1).max(12_000),+ slack: z.object({ workspace: slackId, channel: slackId, threadTs: slackTs, messageTs: slackTs, user: slackId, channelName: plainName.optional() }).optional(),+});+export type TeamSlackMessage = z.infer<typeof teamSlackMessageSchema>;++/** A bot as this Cloud names it for Slack. No picture: a bot's picture is served to signed-in members only. */+export interface TeamSlackBot { id: string; name: string }+export interface TeamSlackAccepted { accepted: true; conversationId: string; bot: TeamSlackBot; openUrl: string }++export type TeamSlackState = "running" | "waiting" | "completed" | "failed" | "stopped";+export type TeamSlackWaiting = "approval" | "question";+export const TEAM_SLACK_FINAL: ReadonlySet<TeamSlackState> = new Set(["completed", "failed", "stopped"]);++const personSchema = z.string().regex(/^p_[\w-]{22}$/);+const recordSchema = z.object({+ id: z.uuid(),+ person: personSchema,+ botId: z.string(),+ botName: z.string(),+ threadId: z.string(),+ audience: z.enum(["team", "member"]),+ at: z.number(),+ state: z.enum(["running", "waiting", "completed", "failed", "stopped"]),+ waiting: z.enum(["approval", "question"]).optional(),+ /** The last state the Admin answered for; a message is over here once this is its final state. */+ told: z.string().optional(),+ /** The Admin no longer wants reports for it (already over there, or not this team's). */+ closed: z.literal(true).optional(),+});+export type TeamSlackRecord = z.infer<typeof recordSchema>;+const fileSchema = z.object({ version: z.literal(1), messages: z.array(recordSchema) });++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. */+export const teamSlackOver = (record: TeamSlackRecord): boolean => record.closed === true || (TEAM_SLACK_FINAL.has(record.state) && record.told === record.state);++/** The messages taken from Slack: ids and state, never their words. */+export 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>();+ 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);+ 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");+ }+ const save = () => {+ const at = now();+ for (const [id, record] of records) if (at - record.at > KEEP_ANY_MS || (teamSlackOver(record) && at - record.at > KEEP_FINISHED_MS)) records.delete(id);+ // 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 }); }+ 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()],+ put(record: TeamSlackRecord): void {+ records.set(record.id, record);+ save();+ },+ patch(id: string, change: Partial<TeamSlackRecord>): TeamSlackRecord | undefined {+ const record = records.get(id);+ if (!record) return undefined;+ Object.assign(record, change);+ save();+ return record;+ },+ /** Everything of one person's, when they leave the team. */+ forgetPerson(person: string): string[] {+ const gone = [...records.values()].filter((record) => record.person === person).map((record) => record.id);+ for (const id of gone) records.delete(id);+ if (gone.length) save();+ return gone;+ },+ };+}+export type TeamSlackMessages = ReturnType<typeof createTeamSlackMessages>;++export interface TeamSlackReport {+ id: string;+ status: TeamSlackState;+ text?: string;+ waiting?: TeamSlackWaiting;+ error?: "model" | "limit" | "failed";+ conversationId: string;+ bot: TeamSlackBot;+ openUrl: string;+}+/** `told`: the Admin has it. `over`: the Admin wants no more about this message. `later`: no answer, or one that asks to+ * wait. `refused`: the Admin will not take this report as it is, so sending it again changes nothing. */+export type TeamSlackReportOutcome = "told" | "over" | "later" | "refused";++const answerSchema = z.object({ ok: z.literal(true), done: z.boolean().optional() });++/** One signed report to the Admin, as the roster check signs its own. It never rejects, and logs no id, word or address. */+export function createTeamSlackReporter(options: { machineId: string; adminOrigin: string; secret: string; fetchImpl?: typeof fetch; now?: () => number; log?: (line: string) => void }) {+ const now = options.now ?? Date.now, log = options.log ?? (() => {});+ return async (report: TeamSlackReport): Promise<TeamSlackReportOutcome> => {+ const fetcher = options.fetchImpl ?? globalThis.fetch;+ const body = JSON.stringify({ v: 1, ...report });+ const timestamp = String(Math.floor(now() / 1000)), nonce = randomBytes(18).toString("base64url");+ let response: Response;+ try {+ response = await fetcher(`${options.adminOrigin}${TEAM_SLACK_REPORT_PATH}`, { method: "POST", redirect: "error", cache: "no-store", body, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), headers: {+ accept: "application/json", "content-type": "application/json", "x-omb-cloud-machine": options.machineId, "x-omb-cloud-timestamp": timestamp, "x-omb-cloud-nonce": nonce,+ "x-omb-cloud-signature": `v1=${teamSlackSignature(options.secret, options.machineId, timestamp, nonce, body)}`,+ } });+ } catch (error) {+ log(`the Admin can't be reached for a Slack report (${error instanceof Error ? error.name : "error"})`);+ return "later";+ }+ const text = await response.text().catch(() => "");+ // Security: the answer's `stop` is never read. Only a member's own session stops a run (the Stop route).+ if (response.status === 404) return "over";+ if (response.status === 429 || response.status >= 500) return "later";+ if (response.status !== 200) {+ log(`the Admin refused a Slack report (HTTP ${response.status})`);+ return "refused";+ }+ let answer: z.ZodSafeParseResult<z.infer<typeof answerSchema>>;+ try { answer = text.length > ANSWER_MAX_BYTES ? answerSchema.safeParse(null) : answerSchema.safeParse(JSON.parse(text)); } catch { answer = answerSchema.safeParse(null); }+ if (!answer.success) return "later";+ return answer.data.done ? "over" : "told";+ };+}+export type TeamSlackReporter = ReturnType<typeof createTeamSlackReporter>;diff --git a/server/workspace-backup.ts b/server/workspace-backup.tsindex 29ca6a9d31..a397329755 100644--- a/server/workspace-backup.ts+++ b/server/workspace-backup.ts@@ -33,6 +33,8 @@ 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.+ "team-slack-messages.json","openmausbot-server.lease", "box-create-requests.lock", "messages.db-wal", "messages.db-shm","runtime.db-wal", "runtime.db-shm","decider-log",diff --git a/src/locales/de.json b/src/locales/de.jsonindex 2ee96f2002..ea4e52a668 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -332,6 +332,9 @@"server.share.wrote": "{name} hat in „{title}“ geschrieben. Öffne die Unterhaltung, um zu antworten.","server.share.answeredTitle": "{bot} hat {name} in „{title}“ geantwortet","server.share.answered": "{bot} hat {name} in „{title}“ geantwortet. Öffne die Unterhaltung, um weiterzumachen.",+ "server.teamSlack.direct": "Slack-Direktnachricht: {text}",+ "server.teamSlack.channel": "Slack #{channel}: {text}",+ "server.teamSlack.channelUnnamed": "Slack-Kanal: {text}","server.teammates.personAssistantAnswered": "Die Assistenz von {name} hat geantwortet","server.teammates.told": "{name} Bescheid gegeben","server.noAi.member": "{owner} muss eine KI verbinden, bevor Bots antworten können. Ich habe Bescheid gegeben.",diff --git a/src/locales/en.json b/src/locales/en.jsonindex b039eb520f..af765bf9e1 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -478,6 +478,9 @@"server.share.wrote": "{name} wrote in “{title}”. Open it to answer.","server.share.answeredTitle": "{bot} answered {name} in “{title}”","server.share.answered": "{bot} answered {name} in “{title}”. Open it to carry on.",+ "server.teamSlack.direct": "Slack DM: {text}",+ "server.teamSlack.channel": "Slack #{channel}: {text}",+ "server.teamSlack.channelUnnamed": "Slack channel: {text}","server.teammates.personAssistantAnswered": "{name}'s assistant answered","server.teammates.told": "Told {name}","server.noAi.member": "{owner} needs to connect an AI before bots can answer. I've told them.",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex b23cf93af5..da216e5d0f 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -461,6 +461,9 @@"server.share.wrote": "{name} escreveu em “{title}”. Abra a conversa para responder.","server.share.answeredTitle": "{bot} respondeu a {name} em “{title}”","server.share.answered": "{bot} respondeu a {name} em “{title}”. Abra a conversa para continuar.",+ "server.teamSlack.direct": "Mensagem direta do Slack: {text}",+ "server.teamSlack.channel": "Slack #{channel}: {text}",+ "server.teamSlack.channelUnnamed": "Canal do Slack: {text}","server.teammates.personAssistantAnswered": "O assistente de {name} respondeu","server.teammates.told": "Avisou {name}","server.noAi.member": "{owner} precisa conectar uma IA para os bots poderem responder. Já avisei.",diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.jsonindex f1d211c58d..3230206f5d 100644--- a/src/locales/source-hashes.json+++ b/src/locales/source-hashes.json@@ -3427,6 +3427,9 @@"server.share.wrote": "7672ad3a723e9f3a97a7570db7c388644185cfd1c78a5582743d1900fd50ccf1","server.share.answeredTitle": "475334e117f72b6000a657501681debdd73d31128177856fda6a5c48999c94ef","server.share.answered": "b9baf8feb4ac3ea7b8277d116c8c5ea89fe86cbb997143892121ca28259581ec",+ "server.teamSlack.direct": "373ba43ec0c11e5d29530d434a32d074462c54e2674c2112b88ead9db5f39ccb",+ "server.teamSlack.channel": "278ba4330c539df0ef4c273e6585467ecc3981d17ca5289dc105567041674de6",+ "server.teamSlack.channelUnnamed": "bec8ce235c21024fd80e2e4cdb41eaff6b45fbe13b44ff0660047d131ce3d624","settings.learnMore": "1445799c033a2d17e2bad5d8610879e71ff0d73a8a3c2b932b43ad0449dac3a1","phone.pair.installLine": "c38bd5e91a296019b3909f24bed64290e6adbef39480d48eb1af18e5f8fa90ea","phone.code.notCamera": "94977df418d83e1fd94e4d9ed0b8452bcf97bfc9a6a88a42576855f3c32e7481",@@ -36276,6 +36279,9 @@"server.share.wrote": "7672ad3a723e9f3a97a7570db7c388644185cfd1c78a5582743d1900fd50ccf1","server.share.answeredTitle": "475334e117f72b6000a657501681debdd73d31128177856fda6a5c48999c94ef","server.share.answered": "b9baf8feb4ac3ea7b8277d116c8c5ea89fe86cbb997143892121ca28259581ec",+ "server.teamSlack.direct": "373ba43ec0c11e5d29530d434a32d074462c54e2674c2112b88ead9db5f39ccb",+ "server.teamSlack.channel": "278ba4330c539df0ef4c273e6585467ecc3981d17ca5289dc105567041674de6",+ "server.teamSlack.channelUnnamed": "bec8ce235c21024fd80e2e4cdb41eaff6b45fbe13b44ff0660047d131ce3d624","teamMemorySave.saved": "16dcefaa40a168bc07ccea0eb693f0d461e06c3f4204c36418aca8f06b4eb04e","settings.learnMore": "1445799c033a2d17e2bad5d8610879e71ff0d73a8a3c2b932b43ad0449dac3a1","phone.pair.installLine": "c38bd5e91a296019b3909f24bed64290e6adbef39480d48eb1af18e5f8fa90ea",