Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Each person's own apps work in work they started: delegated tasks and group chats (#3915)

Milind Soni459e96b4b727
diff --git a/docs/composio.md b/docs/composio.md
index f734ac5581..88f644b961 100644
--- a/docs/composio.md
+++ b/docs/composio.md
@@ -197,7 +197,7 @@ A bot with no grant record at all keeps the legacy behavior: every tool on every
**Imported bots land with no grants.** Shareable packages and team imports never carry grants — an imported bot starts with connected apps off, and any grants it later gets are chosen by the importing workspace. Grants also never appear in exports; only the workspace's own private team backup keeps them.
-**A Chief's new bots start with the Chief's apps.** A bot a Chief of Staff creates (`create_bot`, or a team setup) starts with a copy of the Chief's own connected apps, tools, read or write levels and MCP servers at that moment, never more, and the workspace's default access level. It has the Chief's owner and exactly the Chief's audience; on a Team Cloud, an app each person connects still works only in each person's own private chat, with their own connection. A bot a person creates keeps the defaults above.
+**A Chief's new bots start with the Chief's apps.** A bot a Chief of Staff creates (`create_bot`, or a team setup) starts with a copy of the Chief's own connected apps, tools, read or write levels and MCP servers at that moment, never more, and the workspace's default access level. It has the Chief's owner and exactly the Chief's audience; on a Team Cloud, an app each person connects still works only for the person whose own request the work is, with their own connection. A bot a person creates keeps the defaults above.
**Gmail and Google Calendar by name.** Besides Composio's search-and-run tools, a bot with Gmail or Google Calendar connected and granted gets plain tools for the common reads and writes, the same on every engine: `gmail.search_emails`, `gmail.read_email`, `gmail.read_email_thread`, `gmail.create_draft`, `gmail.send_email`, `googlecalendar.list_events` and `googlecalendar.list_calendars` (writes only where the bot may write). Claude Code finds them by those names (`select:gmail.search_emails`); other engines show them as `gmail_search_emails` behind their own prefix. Each one runs its Composio tool through the multi-execute tool, so its grant, read or write level and approval rules are that tool's. A routine written on one engine keeps working when its bot moves to another.
diff --git a/docs/team-cloud.md b/docs/team-cloud.md
index 23c6416121..72c60b8767 100644
--- a/docs/team-cloud.md
+++ b/docs/team-cloud.md
@@ -43,7 +43,7 @@ keeps people apart on it. The bot box ([bot-box.md](bot-box.md)) is what makes t
(below), never off the team.
- **Connected apps.** The team's connections (Composio, HighLevel, MCP sign-ins, an AI key an Admin saved) belong to the
Team Cloud and serve every member's turn through the broker. An Admin can instead make an app or an MCP server *each
- person's own* (below): then every member connects their own, and only their own private chats use it. A person's
+ person's own* (below): then every member connects their own, and only work their own message started uses it. A person's
connections from elsewhere have no way in: a share code, a moved MCP sign-in or a HighLevel connection is refused with
*"Personal connections never enter Acme. Ask an admin to connect it for Acme."* A login from a sign-in card is saved by
an Admin only, for the whole team.
@@ -109,18 +109,24 @@ Every app (a Composio toolkit) and MCP server has a scope. `team`, the default a
is, is one connection an Admin makes and every turn uses. `person` is one connection per member, made by that member on
their team page in MausBot Cloud (the Admin's Cloud page calls the routes below as them).
-- **Who gets a member's own connection.** Only a turn in that member's private chat (`member:<person>`) that their own
- message started (the request proven for that turn, as lent computers use). Never a group chat, the bot's main chat,
- another member's chat (no Admin can write in theirs), a routine, a webhook, or work handed on from another conversation.
+- **Who gets a member's own connection.** Only a turn that acts for them (server/host/acting-person.ts), read from the
+ harness's records: their own message started it, in their private chat, a group chat or the bot's main chat; or it is
+ work handed on (delegated, assigned, consulted, or a thread a bot opened for it) by a turn that acted for them, recorded
+ as it is handed on (`handed-people.json`, so a restart keeps it). A turn stops acting for anyone once another person's
+ words join it after it began (a line of theirs, queued or sent into it, or their answer to one of its cards), and never
+ acts for anyone in another member's private chat (no Admin can write in theirs). A routine, a webhook and a bot's own
+ work act for nobody. Each step that uses one says whose ("using Ada's Gmail").
- **Apps.** A member's own apps are their own installation on the connected-apps service (their own Composio user),
registered the first time they press Connect. Their turn gets a second bridge, `own_apps`, beside the team's
`composio`; the relay checks every frame again: the team's bridge refuses a `person` app (and code that calls apps
while the team's own installation still holds one), a member's bridge refuses a team app and anything outside their
own turn. A connection card for a `person` app is never shown: the bot gets one plain line to say, *"Connect your
- Gmail here: <their team page>"*, or that it works only in each person's private chat.
+ Gmail here: <their team page>"*; in work that acts for nobody, that the person can ask themselves, or an admin can
+ connect it for the whole team on the team's Apps page. Either way the bot doesn't try it another way (the browser or
+ another tool).
- **MCP servers.** Only a server reached by its address can be `person`. A `person` server's team credential is never
- attached to any turn; a member's own turn gets the server with their own key (in the header the Admin's key used, else
- `Authorization: Bearer`) or their own sign-in. Both are pinned to the server's address: re-pointed, they aren't sent.
+ attached to any turn; a turn that acts for a member gets the server with their own key (in the header the Admin's key
+ used, else `Authorization: Bearer`) or their own sign-in; one not mounted is named to the bot with why and the fix. Both are pinned to the server's address: re-pointed, they aren't sent.
Removing the server forgets every member's key and sign-in for it.
- **Storage.** `team-connection-scopes.json` (no secret, carried by backups) and `people-connections/` (0700; each
member's installation token, keys and sign-ins, 0600), which no backup carries and no bot box binds. Nothing a route
diff --git a/server/cloud-team-connections.e2e.test.ts b/server/cloud-team-connections.e2e.test.ts
index 3e084f6ccd..774b54dd45 100644
--- a/server/cloud-team-connections.e2e.test.ts
+++ b/server/cloud-team-connections.e2e.test.ts
@@ -1,7 +1,8 @@
// A real Team Cloud (OMB_CLOUD_ROLE=team) with the fake connected-apps service and fake MCP servers: connections the team
-// makes once, and connections each person makes for themselves. Ada's own Gmail and mail key reach only her private chat,
-// only for her own requests: never a group chat, the bot's main chat, Cleo's chat or an admin writing in hers; and no admin
-// read ever holds them. The engine is the synthetic Claude CLI, calling the connected-apps bridges it was launched with.
+// makes once, and connections each person makes for themselves. Ada's own Gmail and mail key reach only work her own
+// message started: her private chat, her own line in a group chat, and the work those hand on to other bots. Never
+// anyone else's request or the work it hands on, Cleo's chat or an admin; and no admin read ever holds them. The engine
+// is the synthetic Claude CLI, calling the connected-apps bridges it was launched with.
import { randomBytes } from "node:crypto";
import { existsSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
import { get } from "node:http";
@@ -171,9 +172,11 @@ it("gives Ada's own Gmail and mail to her private chat, for her own request, and
expect(seen.systemPrompt).toContain("Gmail is [email protected]'s own: use it through the own_apps tools");
expect(gmailCallsBy(adaUser)).toBe(before + 1);
expect(gmailCallsBy(teamUser)).toBe(teamBefore);
+ // The step says whose Gmail it used.
+ expect(seen.thread).toContain(`"whose":{"person":"${ADA.email}","app":"Gmail"}`);
// The team's bridge refuses her Gmail and points at her own.
const team_ = await turn(ada, adaThread, "Use the team's Gmail.", { calls: [gmailCall("composio")] });
- expect(team_.thread).toContain("Gmail here is this person's own: use it through the own_apps tools");
+ expect(team_.thread).toContain(`Gmail here is ${ADA.email}'s own: use it through the own_apps tools`);
expect(gmailCallsBy(teamUser)).toBe(teamBefore);
// Each bridge keeps its own bearer from turn to turn, so her conversation's engine stays warm.
const bearer = (dumped: Dump, server: string) => (dumped.mcpConfig.mcpServers[server] as { env: Record<string, string> }).env.OMB_CONNECTOR_TOKEN;
@@ -182,14 +185,20 @@ it("gives Ada's own Gmail and mail to her private chat, for her own request, and
expect(bearer(seen, "own_apps")).not.toBe(bearer(seen, "composio"));
}, hostTimeout(120_000));
-it("never lets her Gmail or mail into a group chat, the main chat, Cleo's chat or an admin's turn", async () => {
+it("gives her own Gmail and mail to her own line in a group chat, and never to anyone else's turn", async () => {
const before = gmailCallsBy(adaUser), teamBefore = gmailCallsBy(teamUser);
- const room = await turn(ada, roomThread, "@Scout check my inbox", { room: roomId, calls: [gmailCall("composio")] });
- expect(room.servers).not.toContain("own_apps");
- expect(room.servers).not.toContain("mail");
- expect(room.config).not.toContain(ADA_KEY);
- expect(room.thread).toContain("Gmail is connected by each person in Acme and works only in that person's own private chat");
- expect(room.systemPrompt).toContain("work only in that person's own private chat with you");
+ const room = await turn(ada, roomThread, "@Scout check my inbox", { room: roomId, calls: [gmailCall("own_apps")] });
+ expect(room.servers).toEqual(expect.arrayContaining(["own_apps", "mail"]));
+ expect(room.config).toContain(ADA_KEY);
+ expect(room.systemPrompt).toContain(`They are used only for ${ADA.email}'s request`);
+ expect(room.thread).toContain(`"whose":{"person":"${ADA.email}","app":"Gmail"}`);
+ expect(gmailCallsBy(adaUser), "her own room line ran as her").toBe(before + 1);
+
+ // The owner's own line in the same group chat is the owner's, who connected nothing: never Ada's.
+ const ownerRoom = await turn(owner, roomThread, "@Scout check the inbox", { room: roomId, calls: [gmailCall("own_apps"), gmailCall("composio")] });
+ expect(ownerRoom.servers).not.toContain("own_apps");
+ expect(ownerRoom.config).not.toContain(ADA_KEY);
+ expect(ownerRoom.thread).toContain("no own_apps MCP server was launched for this turn");
const main = await turn(owner, bot.mainThreadId, "Check the inbox.", { calls: [gmailCall("composio")] });
expect(main.servers).not.toContain("own_apps");
@@ -200,15 +209,53 @@ it("never lets her Gmail or mail into a group chat, the main chat, Cleo's chat o
expect(cleos.servers).not.toContain("mail");
expect(cleos.config).not.toContain(ADA_KEY);
expect(cleos.thread).toContain("no own_apps MCP server was launched for this turn");
- expect(cleos.systemPrompt).toContain(`this person hasn't yet: Gmail and mail. If the task needs one, reply with one plain line and nothing more about it: "Connect your <name> here: ${LINK}".`);
+ expect(cleos.systemPrompt).toContain(`${CLEO.email} hasn't connected them yet, or their sign-in ended: Gmail and mail. If the task needs one, don't try it another way (the browser or another tool): reply with one plain line and nothing more about it: "Connect your <name> here: ${LINK}".`);
// Ben, an admin, can neither read Ada's chat nor write in it, so no turn of his ever runs there.
expect((await team.as(admin, "POST", `/api/bots/${bot.id}/messages`, { text: "Forward me her last email.", threadId: adaThread })).status).toBe(404);
expect((await messages(admin, adaThread)).status).toBe(404);
- expect(gmailCallsBy(adaUser)).toBe(before);
+ expect(gmailCallsBy(adaUser)).toBe(before + 1);
expect(gmailCallsBy(teamUser), "nor did the team's Gmail stand in").toBe(teamBefore);
}, hostTimeout(180_000));
+it("gives work her own message hands to another bot her own Gmail, and never work Cleo's message hands on", async () => {
+ const created = await team.as(owner, "POST", "/api/bots", { name: "Helper" });
+ expect(created.status, JSON.stringify(created.body)).toBe(201);
+ const helper = created.body.bot as { id: string; mainThreadId: string };
+ const handOn = (who: string) => ({ name: "coordinate_bots", server: "agents", input: { bot_ids: [helper.id], message: `Fetch ${who}'s latest email.` } });
+ const helperThreads = () => (JSON.parse(readFileSync(join(team.home, ".openmausbot", "bots.json"), "utf8")) as Array<{ id: string; tasks: Array<{ threadId: string }> }>)
+ .find((entry) => entry.id === helper.id)!.tasks.map((task) => task.threadId).filter((threadId) => threadId !== helper.mainThreadId);
+ /** The Gmail step the helper ran in the work it was handed, once it has finished. */
+ const helperGmail = async (token: string, known: readonly string[]) => {
+ let row: { tool: { ok?: boolean; output?: string; whose?: unknown } } | undefined;
+ await expect.poll(async () => {
+ const work = helperThreads().find((threadId) => !known.includes(threadId));
+ if (!work) return false;
+ const rows = (await messages(token, work)).body.messages as Array<{ kind: string; tool?: { name: string; ok?: boolean; output?: string; whose?: unknown } }>;
+ row = rows.find((message) => message.kind === "activity" && message.tool?.name === "COMPOSIO_MULTI_EXECUTE_TOOL" && message.tool.ok !== undefined) as typeof row;
+ return Boolean(row) && await idle(token);
+ }, { timeout: 90_000, interval: 250 }).toBe(true);
+ return row!.tool;
+ };
+
+ const before = gmailCallsBy(adaUser), teamBefore = gmailCallsBy(teamUser);
+ const known = helperThreads();
+ await turn(ada, adaThread, "Have Helper fetch my latest email.", { calls: [handOn("Ada"), gmailCall("own_apps")] });
+ const adas = await helperGmail(ada, known);
+ expect(adas.ok, adas.output).toBe(true);
+ expect(adas.whose, "the step says whose").toEqual({ person: ADA.email, app: "Gmail" });
+ expect(gmailCallsBy(adaUser), "her bot and the helper both ran as her").toBeGreaterThanOrEqual(before + 2);
+
+ const adaCalls = gmailCallsBy(adaUser), seen = helperThreads();
+ await turn(cleo, cleoThread, "Have Helper fetch my latest email.", { calls: [handOn("Cleo"), gmailCall("own_apps")] });
+ const cleos = await helperGmail(cleo, seen);
+ expect(cleos.ok).toBe(false);
+ expect(cleos.output, "Cleo connected nothing, and Ada's is never hers").toContain("no own_apps MCP server was launched for this turn");
+ expect(cleos.whose).toBeUndefined();
+ expect(gmailCallsBy(adaUser)).toBe(adaCalls);
+ expect(gmailCallsBy(teamUser), "nor did the team's Gmail stand in").toBe(teamBefore);
+}, hostTimeout(240_000));
+
it("tells the bot one plain line with the link when a person's app isn't connected, never a card", async () => {
const seen = await turn(cleo, cleoThread, "Connect my Gmail.", { calls: [{ name: "COMPOSIO_MANAGE_CONNECTIONS", server: "composio", input: { toolkits: ["gmail"] } }] });
expect(seen.thread).toContain(`Connect your Gmail here: ${LINK}`);
diff --git a/server/host/acting-person.test.ts b/server/host/acting-person.test.ts
new file mode 100644
index 0000000000..259d14c945
--- /dev/null
+++ b/server/host/acting-person.test.ts
@@ -0,0 +1,178 @@
+import { mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+
+import { OUTSIDE, workOriginSchema, type WorkOrigin } from "../peer-provenance.ts";
+import { personKey } from "../person-key.ts";
+import { createActingPeople, HandedPeople, onlyTheirs, withPerson, type ActingLine, type DirectRequest, type RoomRun } from "./acting-person.ts";
+
+const ADA = personKey({ id: "", email: "[email protected]" });
+const BEN = personKey({ id: "", email: "[email protected]" });
+const said = (id: string, at: number, person: string | undefined, more: Partial<ActingLine> = {}): ActingLine =>
+ ({ id, at, role: "user", ...(person ? { sender: { id: person } } : {}), ...more });
+const botLine = (id: string, at: number): ActingLine => ({ id, at, role: "bot" });
+const ask = (id: string, at: number): ActingLine => ({ id, at, role: "user", peerAsk: { botId: "chief" } });
+const userOrigin = (person?: string): WorkOrigin => ({ kind: "user", request: "File the notes in Notion", ...(person ? { person } : {}) });
+
+function world(options: { threads?: Record<string, ActingLine[]>; rooms?: string[]; direct?: Record<string, DirectRequest>; runs?: Record<string, RoomRun> } = {}) {
+ const dir = mkdtempSync(join(tmpdir(), "omb-acting-person-"));
+ const handed = new HandedPeople(join(dir, "handed-people.json"));
+ const people = createActingPeople({
+ store: { groupByThread: (threadId) => (options.rooms ?? []).includes(threadId) || undefined, messagesFor: (threadId) => options.threads?.[threadId] ?? [] },
+ direct: (threadId) => options.direct?.[threadId],
+ roomRun: (generation) => options.runs?.[generation],
+ handed,
+ });
+ return { people, handed, dir };
+}
+const request = (generation: string, more: Partial<DirectRequest> = {}): DirectRequest => ({ generation, generations: new Set([generation]), ...more });
+
+describe("a turn started by a person's own line acts for them", () => {
+ it("in any one-on-one conversation, for that turn generation only, until it is stopped", () => {
+ const thread = [said("m1", 10, ADA), botLine("b1", 11)];
+ const { people } = world({ threads: { t: thread }, direct: { t: request("g1", { messageId: "m1" }) } });
+ expect(people.requester("t", "g1")).toBe(ADA);
+ expect(people.requester("t"), "the latest generation when none is named").toBe(ADA);
+ expect(people.requester("t", "g0"), "another generation proves nothing").toBeNull();
+ expect(world({ threads: { t: thread }, direct: { t: request("g1", { messageId: "m1", stopped: true }) } }).people.requester("t", "g1")).toBeNull();
+ });
+
+ it("never for a routine, a bot's message or a line nobody can be named for", () => {
+ expect(world({ threads: { t: [said("m1", 10, ADA)] }, direct: { t: request("g1", { messageId: "m1", automation: "schedule" }) } }).people.requester("t", "g1"), "a routine's run").toBeNull();
+ expect(world({ threads: { t: [ask("m1", 10)] }, direct: { t: request("g1", { messageId: "m1" }) } }).people.requester("t", "g1"), "a bot's line").toBeNull();
+ expect(world({ threads: { t: [said("m1", 10, undefined)] }, direct: { t: request("g1", { messageId: "m1" }) } }).people.requester("t", "g1")).toBeNull();
+ expect(world({ threads: { t: [said("m1", 10, "not-a-person-key")] }, direct: { t: request("g1", { messageId: "m1" }) } }).people.requester("t", "g1")).toBeNull();
+ });
+
+ it("stops acting for them once someone else's words join it: a line sent in, or an answer to one of its cards", () => {
+ const base = [said("m0", 5, BEN), said("m1", 10, ADA), botLine("b1", 11)];
+ const direct = { t: request("g1", { messageId: "m1" }) };
+ expect(world({ threads: { t: base }, direct }).people.requester("t", "g1"), "what was said before her request is context, not a join").toBe(ADA);
+ expect(world({ threads: { t: [...base, said("s1", 12, ADA, { steered: true })] }, direct }).people.requester("t", "g1"), "her own follow-up").toBe(ADA);
+ expect(world({ threads: { t: [...base, said("s1", 12, BEN, { steered: true })] }, direct }).people.requester("t", "g1"), "Ben's line sent into her turn").toBeNull();
+ expect(world({ threads: { t: [...base, said("s1", 12, undefined, { steered: true })] }, direct }).people.requester("t", "g1"), "a line from someone the server can't name").toBeNull();
+ const card = (person: string) => ({ id: "c1", at: 12, role: "bot", card: { answered: "yes", answeredBy: { kind: "session", person } } });
+ expect(world({ threads: { t: [...base, card(ADA)] }, direct }).people.requester("t", "g1")).toBe(ADA);
+ expect(world({ threads: { t: [...base, card(BEN)] }, direct }).people.requester("t", "g1"), "Ben answered her turn's card").toBeNull();
+ const dismissed = { id: "c2", at: 12, role: "bot", card: { dismissed: true, answeredBy: { kind: "session", person: BEN } } };
+ expect(world({ threads: { t: [...base, dismissed] }, direct }).people.requester("t", "g1"), "a card the harness settled carries nobody's words").toBe(ADA);
+ });
+});
+
+describe("a room run acts for the person whose room line began it", () => {
+ const room = { rooms: ["room"] };
+ it("for the run's own turn generations, and never once the run is stopped", () => {
+ const thread = [said("m0", 5, BEN), said("m1", 10, ADA)];
+ expect(world({ ...room, threads: { room: thread }, runs: { g1: { requestMessageId: "m1", cancelled: false } } }).people.requester("room", "g1")).toBe(ADA);
+ expect(world({ ...room, threads: { room: thread }, runs: { g1: { requestMessageId: "m1", cancelled: false } } }).people.requester("room", "g2")).toBeNull();
+ expect(world({ ...room, threads: { room: thread }, runs: { g1: { requestMessageId: "m1", cancelled: false } } }).people.requester("room"), "a room needs its turn generation").toBeNull();
+ expect(world({ ...room, threads: { room: thread }, runs: { g1: { requestMessageId: "m1", cancelled: true } } }).people.requester("room", "g1")).toBeNull();
+ expect(world({ ...room, threads: { room: [...thread, said("m2", 20, BEN)] }, runs: { g1: { requestMessageId: "m2", cancelled: false } } }).people.requester("room", "g1"), "Ben's own room line is Ben's").toBe(BEN);
+ expect(world({ ...room, threads: { room: thread }, runs: { g1: { requestMessageId: "m0", cancelled: false } } }).people.requester("room", "g1"), "Ada wrote in the room after Ben's line began his run").toBeNull();
+ });
+
+ it("joins queued lines only when every one is theirs", () => {
+ const own = [said("q1", 10, ADA, { queueId: "a" }), said("q2", 11, ADA, { queueId: "b" })];
+ const mixed = [said("q1", 10, BEN, { queueId: "a" }), said("q2", 11, ADA, { queueId: "b" })];
+ const run: RoomRun = { requestMessageId: "q2", cancelled: false, queuedQueueIds: ["a", "b"] };
+ expect(world({ ...room, threads: { room: own }, runs: { g1: run } }).people.requester("room", "g1")).toBe(ADA);
+ expect(world({ ...room, threads: { room: mixed }, runs: { g1: run } }).people.requester("room", "g1"), "Ben's queued line ran in the same turn").toBeNull();
+ });
+
+ it("acts for the person handed-on work was handed on for, until someone else writes in the room", () => {
+ const run: RoomRun = { cancelled: false, handedFor: { person: ADA, since: 20 } };
+ expect(world({ ...room, threads: { room: [said("m0", 5, BEN), ask("a1", 20)] }, runs: { g1: run } }).people.requester("room", "g1")).toBe(ADA);
+ expect(world({ ...room, threads: { room: [ask("a1", 20), said("m2", 21, BEN)] }, runs: { g1: run } }).people.requester("room", "g1")).toBeNull();
+ expect(world({ ...room, threads: { room: [] }, runs: { g1: { cancelled: false } } }).people.requester("room", "g1"), "a room run nobody started").toBeNull();
+ });
+});
+
+describe("work handed on acts for whoever the turn that handed it on acted for", () => {
+ it("records it once as the work is handed on, and the receiving turn acts for them", () => {
+ const { people } = world({ threads: { ada: [said("m1", 10, ADA)] }, direct: { ada: request("root-1", { messageId: "m1" }) } });
+ people.handOn({ threadId: "ada", generation: "root-1" }, { id: "node-1", rootId: "root-1" });
+ expect(people.handedOrigin(userOrigin(), "node-1")).toEqual(userOrigin(ADA));
+ expect(people.handedOrigin(userOrigin(BEN), "root-1"), "the turn that handed it on is kept too, for a restart").toEqual(userOrigin(ADA));
+ expect(people.handedOrigin(OUTSIDE, "node-1"), "outside work never carries a person").toEqual(OUTSIDE);
+ expect(people.handedOrigin(userOrigin(BEN), "node-unknown"), "work nobody recorded acts for nobody").toEqual(userOrigin());
+ expect(people.handedRun("node-1")).toEqual({ person: ADA, since: expect.any(Number) });
+ });
+
+ it("a delegated turn acts for its person only while nobody else has written in its conversation", () => {
+ const direct = { work: request("g2", { messageId: "a1", origin: userOrigin(ADA) }) };
+ expect(world({ threads: { work: [ask("a1", 20), botLine("b1", 21)] }, direct }).people.requester("work", "g2")).toBe(ADA);
+ expect(world({ threads: { work: [said("x", 1, BEN), ask("a1", 20)] }, direct }).people.requester("work", "g2"), "Ben wrote in this work thread").toBeNull();
+ expect(world({ threads: { work: [ask("a1", 20)] }, direct: { work: request("g2", { messageId: "a1", origin: userOrigin() }) } }).people.requester("work", "g2"), "handed on for nobody").toBeNull();
+ expect(world({ threads: { work: [ask("a1", 20)] }, direct: { work: request("g2", { messageId: "a1", origin: OUTSIDE }) } }).people.requester("work", "g2")).toBeNull();
+ });
+
+ it("never lets Ben's chain hand on Ada: each piece of work keeps the person of the turn that handed it on", () => {
+ const { people } = world({
+ threads: { ada: [said("m1", 10, ADA)], ben: [said("m2", 11, BEN)], routine: [said("r1", 12, undefined)] },
+ direct: { ada: request("ga", { messageId: "m1" }), ben: request("gb", { messageId: "m2" }), routine: request("gr", { messageId: "r1", automation: "schedule" }) },
+ });
+ people.handOn({ threadId: "ada", generation: "ga" }, { id: "from-ada", rootId: "ga" });
+ people.handOn({ threadId: "ben", generation: "gb" }, { id: "from-ben", rootId: "gb" });
+ people.handOn({ threadId: "routine", generation: "gr" }, { id: "from-routine", rootId: "gr" });
+ people.handOn({ threadId: "ben", generation: "gb" }, { id: "from-ada", rootId: "ga" });
+ expect(people.handedRun("from-ada")?.person, "recorded once: a later hand-on of the same work changes nothing").toBe(ADA);
+ expect(people.handedRun("from-ben")?.person).toBe(BEN);
+ expect(people.handedRun("from-routine"), "a routine's work acts for nobody").toBeUndefined();
+ });
+});
+
+describe("the record of handed-on work", () => {
+ it("survives a restart, in a file only the server reads", () => {
+ const { handed, dir } = world();
+ handed.record("node-1", ADA);
+ const file = join(dir, "handed-people.json");
+ if (process.platform !== "win32") expect(statSync(file).mode & 0o777).toBe(0o600);
+ expect(new HandedPeople(file).get("node-1")?.person).toBe(ADA);
+ expect(readFileSync(file, "utf8")).not.toContain("[email protected]");
+ });
+
+ it("holds nobody when its file is damaged, and refuses ids and people it can't read", () => {
+ const { dir } = world();
+ const file = join(dir, "handed-people.json");
+ writeFileSync(file, JSON.stringify({ v: 1, work: { "node-1": { person: "someone", at: 1 } } }));
+ expect(new HandedPeople(file).get("node-1")).toBeUndefined();
+ writeFileSync(file, "{not json");
+ const handed = new HandedPeople(file);
+ handed.record("../escape", ADA);
+ handed.record("node-2", "p_short");
+ handed.record("node-3", null);
+ expect([handed.get("../escape"), handed.get("node-2"), handed.get("node-3")]).toEqual([undefined, undefined, undefined]);
+ });
+
+ it("forgets work handed on more than thirty days ago", () => {
+ const dir = mkdtempSync(join(tmpdir(), "omb-acting-person-"));
+ let now = 1_000;
+ const handed = new HandedPeople(join(dir, "handed-people.json"), () => now);
+ handed.record("old", ADA);
+ now += 31 * 24 * 60 * 60_000;
+ handed.record("new", BEN);
+ expect(handed.get("old")).toBeUndefined();
+ expect(handed.get("new")?.person).toBe(BEN);
+ });
+});
+
+describe("the person on a handed-on origin", () => {
+ it("is set only on a person's own request, and only to a person's key", () => {
+ expect(withPerson(userOrigin(), ADA)).toEqual(userOrigin(ADA));
+ expect(withPerson(userOrigin(ADA), null)).toEqual(userOrigin());
+ expect(withPerson(userOrigin(), "someone")).toEqual(userOrigin());
+ expect(withPerson(OUTSIDE, ADA)).toEqual(OUTSIDE);
+ });
+
+ it("is kept when a queued handed-on message is read back, and dropped when it is not a person's key", () => {
+ expect(workOriginSchema.parse(userOrigin(ADA))).toEqual(userOrigin(ADA));
+ expect(workOriginSchema.safeParse({ ...userOrigin(), person: "../ada" }).success).toBe(false);
+ });
+
+ it("counts only words that came after the request", () => {
+ const thread = [said("m0", 5, BEN), said("m1", 10, ADA), said("m2", 15, BEN)];
+ expect(onlyTheirs(thread, ADA, 10)).toBe(false);
+ expect(onlyTheirs(thread.slice(0, 2), ADA, 10)).toBe(true);
+ });
+});
diff --git a/server/host/acting-person.ts b/server/host/acting-person.ts
new file mode 100644
index 0000000000..f206d95041
--- /dev/null
+++ b/server/host/acting-person.ts
@@ -0,0 +1,158 @@
+// Who a turn acts for on a Team Cloud: the person whose own words provably began its work, so it may use that person's
+// own apps and MCP servers (server/host/team-connections-host.ts decides with it). Read only from the harness's records,
+// never from model text:
+// - their own line started this turn in a one-on-one conversation, or began the run a room member answers (a run that
+// joined several queued lines, only when every one of them is theirs);
+// - work handed on (delegated, assigned or consulted work, or a thread a bot opened for it) acts for whoever the turn
+// that handed it on acted for at that moment, kept with the handed-on work so a restart keeps it.
+// A turn acts for nobody once another person's words joined it after it began: a line of theirs in the conversation, or
+// their answer to one of its cards. A routine, a webhook, an outside app and a bot's own work act for nobody.
+import { readFileSync } from "node:fs";
+import { z } from "zod";
+
+import { writeFileAtomic } from "../atomic.ts";
+import { answeredByPerson } from "../cloud-lending.ts";
+import type { WorkOrigin } from "../peer-provenance.ts";
+
+export const HANDED_PEOPLE_FILE = "handed-people.json";
+
+const PERSON = /^p_[\w-]{22}$/;
+const WORK = /^[\w-]{1,128}$/;
+/** As long as the coordinator keeps finished work, and no more entries than a busy team hands on in that time. */
+const KEEP_MS = 30 * 24 * 60 * 60_000;
+const MAX_ENTRIES = 20_000;
+
+type Card = { answered?: string; answeredText?: string; dismissed?: boolean; autoApplied?: boolean; answeredBy?: { kind: string; person?: string } };
+export type ActingLine = {
+ id: string; at: number; role: string; peerAsk?: unknown; steered?: boolean; queueId?: string; sender?: { id?: string }; card?: Card;
+};
+/** A one-on-one conversation's latest request (index.ts directRequestOwners). */
+export type DirectRequest = {
+ generation: string; generations: ReadonlySet<string>; messageId?: string; stopped?: boolean; automation?: unknown; origin?: WorkOrigin;
+};
+/** Handed-on work a room member does: whom it acts for, and since when the room's words count against it. */
+export type HandedRun = { person: string; since: number };
+/** A room run (index.ts GroupTurnOperation, server/host/cloud-lending-turns.ts): the person's line it answers, the queued
+ * lines it joined, or the handed-on work it does. */
+export type RoomRun = { requestMessageId?: string; cancelled: boolean; queuedQueueIds?: readonly string[]; handedFor?: HandedRun };
+
+const fileSchema = z.object({
+ v: z.literal(1),
+ work: z.record(z.string().regex(WORK), z.object({ person: z.string().regex(PERSON), at: z.number().int().nonnegative() })),
+});
+
+/** Whom each piece of handed-on work acts for, recorded once as it is handed on. A missing or damaged file holds nobody:
+ * it never grants anything by being absent. */
+export class HandedPeople {
+ readonly #file: string;
+ readonly #now: () => number;
+ readonly #work = new Map<string, { person: string; at: number }>();
+
+ constructor(file: string, now: () => number = Date.now) {
+ this.#file = file;
+ this.#now = now;
+ try {
+ const parsed = fileSchema.safeParse(JSON.parse(readFileSync(file, "utf8")));
+ if (parsed.success) for (const [id, entry] of Object.entries(parsed.data.work)) this.#work.set(id, entry);
+ } catch {
+ // none yet, or unreadable: nobody
+ }
+ }
+
+ /** Work handed on by a turn that acted for `person`; once, so handing the same work on again changes nothing. */
+ record(workId: string, person: string | null): void {
+ if (!person || !PERSON.test(person) || !WORK.test(workId) || this.#work.has(workId)) return;
+ const now = this.#now();
+ this.#work.set(workId, { person, at: now });
+ for (const [id, entry] of this.#work) if (now - entry.at > KEEP_MS) this.#work.delete(id);
+ while (this.#work.size > MAX_ENTRIES) this.#work.delete(this.#work.keys().next().value!);
+ try {
+ writeFileAtomic(this.#file, `${JSON.stringify({ v: 1, work: Object.fromEntries(this.#work) })}\n`, { mode: 0o600 });
+ } catch (error) {
+ console.warn(`handed-on work: could not save ${this.#file}: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ }
+
+ get(workId: string): { person: string; at: number } | undefined {
+ return this.#work.get(workId);
+ }
+}
+
+/** A person's own line: theirs as the server recorded it, never a bot's relayed one. */
+const linePerson = (line: ActingLine | undefined): string | undefined =>
+ line?.role === "user" && !line.peerAsk && line.sender?.id && PERSON.test(line.sender.id) ? line.sender.id : undefined;
+
+/** No one else's words joined the work since `since`: no line of another person's (and no line sent into a running turn
+ * by someone the server can't name), and no answer of theirs to a card. */
+export function onlyTheirs(thread: readonly ActingLine[], person: string, since: number): boolean {
+ return !thread.some((line) => line.at >= since && (
+ (line.role === "user" && !line.peerAsk && (line.sender?.id ? line.sender.id !== person : line.steered === true))
+ || (answeredByPerson(line.card) && line.card!.answeredBy?.kind === "session" && line.card!.answeredBy.person !== person)));
+}
+
+/** A handed-on origin names the person the work acts for, and only a person's own request can. */
+export function withPerson(origin: WorkOrigin, person: string | null | undefined): WorkOrigin {
+ if (origin.kind !== "user") return origin;
+ const { person: _previous, ...rest } = origin;
+ return person && PERSON.test(person) ? { ...rest, person } : rest;
+}
+
+export interface ActingPeopleDeps {
+ store: { groupByThread(threadId: string): unknown; messagesFor(threadId: string): readonly ActingLine[] };
+ direct(threadId: string): DirectRequest | undefined;
+ roomRun(generation: string): RoomRun | undefined;
+ handed: HandedPeople;
+}
+
+export function createActingPeople(deps: ActingPeopleDeps) {
+ /** The person this turn generation acts for (the conversation's latest when none is named), or null. */
+ const requester = (threadId: string, generation?: string): string | null => {
+ const thread = deps.store.messagesFor(threadId);
+ if (deps.store.groupByThread(threadId)) {
+ const run = generation === undefined ? undefined : deps.roomRun(generation);
+ if (!run || run.cancelled) return null;
+ if (run.requestMessageId) {
+ const line = thread.find((message) => message.id === run.requestMessageId);
+ const person = linePerson(line);
+ if (!line || !person) return null;
+ const joined = new Set(run.queuedQueueIds ?? []);
+ const since = thread.reduce((first, message) => (message.queueId !== undefined && joined.has(message.queueId) ? Math.min(first, message.at) : first), line.at);
+ return onlyTheirs(thread, person, since) ? person : null;
+ }
+ const handed = run.handedFor;
+ return handed && onlyTheirs(thread, handed.person, handed.since) ? handed.person : null;
+ }
+ const request = deps.direct(threadId);
+ const turn = generation ?? request?.generation;
+ if (!request || !turn || request.stopped || !request.generations.has(turn) || request.automation !== undefined) return null;
+ if (request.messageId) {
+ const line = thread.find((message) => message.id === request.messageId);
+ const person = linePerson(line);
+ if (line && person) return onlyTheirs(thread, person, line.at) ? person : null;
+ }
+ // Work handed on into a conversation of its own: nobody else may have written in it at all.
+ const handed = request.origin?.kind === "user" ? request.origin.person : undefined;
+ return handed && onlyTheirs(thread, handed, 0) ? handed : null;
+ };
+ return {
+ requester,
+ /** Work this turn hands on now acts for whoever this turn acts for; the first hand-on of a turn that started its
+ * work is kept for that turn too, so it still acts for them if a restart runs it again. */
+ handOn(turn: { threadId: string; generation: string }, work: { id: string; rootId: string }): void {
+ const person = requester(turn.threadId, turn.generation);
+ deps.handed.record(work.id, person);
+ if (work.rootId === turn.generation) deps.handed.record(work.rootId, person);
+ },
+ /** A handed-on origin with the person its work was handed on for, if any. */
+ handedOrigin(origin: WorkOrigin, workId: string): WorkOrigin {
+ return withPerson(origin, deps.handed.get(workId)?.person);
+ },
+ /** What a room member doing handed-on work acts for: the room's words since it was handed on count against it. */
+ handedRun(workId: string): HandedRun | undefined {
+ const entry = deps.handed.get(workId);
+ return entry ? { person: entry.person, since: entry.at } : undefined;
+ },
+ };
+}
+
+export type ActingPeople = ReturnType<typeof createActingPeople>;
diff --git a/server/host/cloud-lending-turns.ts b/server/host/cloud-lending-turns.ts
index 5af577835e..fe70812b12 100644
--- a/server/host/cloud-lending-turns.ts
+++ b/server/host/cloud-lending-turns.ts
@@ -6,10 +6,9 @@ import { unstamped } from "../cloud-owner-lines.ts";
import { deviceWord } from "../lent-computers.ts";
import type { Routine, RoutineManager, RoutineRun } from "../routines.ts";
import type { Message, Store } from "../store.ts";
+import type { RoomRun } from "./acting-person.ts";
type Turn = { botId: string; threadId: string; generation: string };
-/** A room run: the person's line it answers, if one started it, and whether it was stopped. */
-type RoomRun = { requestMessageId?: string; cancelled: boolean };
export interface CloudLendingTurnsDeps {
store: Pick<Store, "groupByThread" | "messagesFor" | "taskByThread">;
@@ -101,5 +100,7 @@ export function createCloudLendingTurns(deps: CloudLendingTurnsDeps) {
roomTurnStarted(generation: string, run: RoomRun): void { roomTurnOperations.set(generation, run); },
/** The run ended: none of its turn generations act for anyone any more. */
roomTurnEnded(run: RoomRun): void { for (const [generation, owner] of roomTurnOperations) if (owner === run) roomTurnOperations.delete(generation); },
+ /** The run a room member turn generation belongs to, while it lasts (server/host/acting-person.ts reads whom it acts for). */
+ roomRun: (generation: string): RoomRun | undefined => roomTurnOperations.get(generation),
};
}
diff --git a/server/host/team-connections-host.test.ts b/server/host/team-connections-host.test.ts
index 38b2bb3c56..c82d1f03ea 100644
--- a/server/host/team-connections-host.test.ts
+++ b/server/host/team-connections-host.test.ts
@@ -17,13 +17,15 @@ const ADA = personKey({ id: "", email: "[email protected]" });
const BEN = personKey({ id: "", email: "[email protected]" });
const CLEO = personKey({ id: "", email: "[email protected]" });
const ADA_ACCESS = { url: "https://broker.test", token: "a".repeat(64) };
+const CLEO_ACCESS = { url: "https://broker.test", token: "c".repeat(64) };
-/** Ada's private chat (she or Ben, an admin, may write in it), Cleo's, a group chat and the bot's main chat. */
-const AUDIENCES: Record<string, Audience> = { "ada-chat": `member:${ADA}`, "cleo-chat": `member:${CLEO}`, "room-chat": "room:launch", "main-chat": "team" };
+/** Ada's private chat, Cleo's, a group chat, the bot's main chat and a thread a bot opened for work handed on. Who each
+ * turn acts for is acting-person.ts's answer (the `requester`); "" is a turn that acts for nobody, as a routine's. */
+const AUDIENCES: Record<string, Audience> = { "ada-chat": `member:${ADA}`, "cleo-chat": `member:${CLEO}`, "room-chat": "room:launch", "main-chat": "team", "work-chat": "team" };
function setup(options: { team?: boolean; requester?: Record<string, string>; servers?: Record<string, unknown> } = {}) {
const dataDir = mkdtempSync(join(tmpdir(), "omb-team-connections-"));
- const requester = { "ada-chat": ADA, "cleo-chat": CLEO, "room-chat": ADA, "main-chat": ADA, ...options.requester };
+ const requester = { "ada-chat": ADA, "cleo-chat": CLEO, "room-chat": ADA, "main-chat": ADA, "work-chat": ADA, ...options.requester };
const cfg = { mcpServers: options.servers ?? {
mail: { type: "http", url: "https://mail.example/mcp", headers: { Authorization: "Bearer team-mail-key" }, enabled: true },
console: { type: "http", url: "https://console.example/mcp", headers: { Authorization: "Bearer team-console-key" }, enabled: true },
@@ -32,8 +34,8 @@ function setup(options: { team?: boolean; requester?: Record<string, string>; se
const composio = {
configured: () => true,
mcpIntegration: vi.fn(async (_cfg: AppConfig, context: { commsToken: string; as?: unknown }) => ({ command: "node", args: ["bridge"], env: { TOKEN: context.commsToken, AS: context.as ? "own" : "team" } })),
- connectedServices: vi.fn(async (_cfg: AppConfig, as?: { token: string }) => (as?.token === ADA_ACCESS.token
- ? { gmail: { connected: true, pending: false, status: "ACTIVE", accounts: [{ id: "ca_1", status: "ACTIVE", alias: "[email protected]" }] } } : {})),
+ connectedServices: vi.fn(async (_cfg: AppConfig, as?: { token: string }) => (as?.token === ADA_ACCESS.token || as?.token === CLEO_ACCESS.token
+ ? { gmail: { connected: true, pending: false, status: "ACTIVE", accounts: [{ id: "ca_1", status: "ACTIVE", alias: "[email protected]" }] } } : {})),
connectedServiceSlugs: vi.fn(async () => ["google_search_console"] as readonly string[]),
authorizeService: vi.fn(),
removeService: vi.fn(),
@@ -56,14 +58,19 @@ function setup(options: { team?: boolean; requester?: Record<string, string>; se
return { host, dataDir, minted, composio };
}
-/** Ada has her own installation, and her own key for the mail server; Gmail and mail are each person's. */
-function adaConnected(host: ReturnType<typeof setup>["host"], dataDir: string) {
+/** Ada has her own installation, and her own key for the mail server; Gmail and mail are each person's. With `cleo`, Cleo
+ * has her own installation and key too. */
+function adaConnected(host: ReturnType<typeof setup>["host"], dataDir: string, options: { cleo?: boolean } = {}) {
host.scopes.set("app", "gmail", "person");
host.scopes.set("mcp", "mail", "person");
const file = join(dataDir, "people-connections", "apps.json");
host.people.putKey(ADA, "[email protected]", "mail", { url: "https://mail.example/mcp", header: "Authorization", value: "Bearer ada-own-mail-key" });
+ if (options.cleo) host.people.putKey(CLEO, "[email protected]", "mail", { url: "https://mail.example/mcp", header: "Authorization", value: "Bearer cleo-own-mail-key" });
// As ensureAppsAccess saves it after the service registered her.
- (host.people as unknown as { write(name: string, value: unknown): void }).write("apps.json", { v: 1, brokerUrl: ADA_ACCESS.url, people: { [ADA]: { email: "[email protected]", installationId: "inst-ada", token: ADA_ACCESS.token } } });
+ (host.people as unknown as { write(name: string, value: unknown): void }).write("apps.json", { v: 1, brokerUrl: ADA_ACCESS.url, people: {
+ [ADA]: { email: "[email protected]", installationId: "inst-ada", token: ADA_ACCESS.token },
+ ...(options.cleo ? { [CLEO]: { email: "[email protected]", installationId: "inst-cleo", token: CLEO_ACCESS.token } } : {}),
+ } });
return file;
}
@@ -75,52 +82,86 @@ describe("whose connection a turn may use", () => {
expect(host.personApps()).toEqual([]);
});
- it("is a member only in her private chat, and only for her own message", () => {
- const { host } = setup({ requester: { "ada-chat": ADA } });
+ it("is the person the turn acts for, wherever their own request began it, never in another member's private chat", () => {
+ const { host } = setup({ requester: { "room-chat": ADA, "main-chat": BEN, "work-chat": CLEO } });
expect(host.turnPerson("ada-chat")).toBe(ADA);
- expect(host.turnPerson("room-chat"), "a group chat is nobody's own").toBeNull();
- expect(host.turnPerson("main-chat"), "the bot's main chat is the team's").toBeNull();
+ expect(host.turnPerson("room-chat"), "her own line in a group chat").toBe(ADA);
+ expect(host.turnPerson("main-chat"), "his own line in the bot's main chat").toBe(BEN);
+ expect(host.turnPerson("work-chat"), "work handed on from her request").toBe(CLEO);
expect(host.turnPerson("cleo-chat")).toBe(CLEO);
const admin = setup({ requester: { "ada-chat": BEN } }).host;
- expect(admin.turnPerson("ada-chat"), "an admin writing in Ada's chat is not Ada").toBeNull();
- const routine = setup({ requester: { "ada-chat": "" } }).host;
- expect(routine.turnPerson("ada-chat"), "a routine or a webhook proves nobody").toBeNull();
+ expect(admin.turnPerson("ada-chat"), "Ben's request never acts for anyone in Ada's private chat").toBeNull();
+ const routine = setup({ requester: { "ada-chat": "", "room-chat": "", "work-chat": "" } }).host;
+ for (const thread of ["ada-chat", "room-chat", "work-chat"]) expect(routine.turnPerson(thread), `a routine or a webhook acts for nobody (${thread})`).toBeNull();
expect(setup({ team: false }).host.turnPerson("ada-chat"), "off a team nothing is anyone's").toBeNull();
});
});
describe("apps each person connects", () => {
- it("mounts a member's own bridge only in her own turn, minted for her", async () => {
- const { host, dataDir, minted } = setup();
+ it("mounts a member's own bridge in every turn that acts for her, minted for her, and in no other", async () => {
+ const { host, dataDir, minted } = setup({ requester: { "main-chat": CLEO } });
adaConnected(host, dataDir);
const own = await host.appsIntegrations({ id: "scout", name: "Scout" }, "ada-chat", "gen-1");
expect(own.composio?.env.AS).toBe("team");
expect(own.composioOwn?.env.AS).toBe("own");
expect(minted.map((entry) => entry.connectorsFor)).toEqual([undefined, ADA]);
- for (const thread of ["room-chat", "main-chat", "cleo-chat"]) {
+ for (const thread of ["room-chat", "work-chat"]) {
+ minted.length = 0;
+ const hers = await host.appsIntegrations({ id: "scout", name: "Scout" }, thread, "gen-1");
+ expect(hers.composioOwn?.env.AS, `${thread}: her own request`).toBe("own");
+ expect(minted.map((entry) => entry.connectorsFor), thread).toEqual([undefined, ADA]);
+ }
+ for (const thread of ["main-chat", "cleo-chat"]) {
const elsewhere = await host.appsIntegrations({ id: "scout", name: "Scout" }, thread, "gen-1");
expect(elsewhere.composio, thread).toBeDefined();
- expect(elsewhere.composioOwn, thread).toBeUndefined();
+ expect(elsewhere.composioOwn, `${thread}: Cleo's request, and Cleo connected nothing`).toBeUndefined();
}
const admin = setup({ requester: { "ada-chat": BEN } });
adaConnected(admin.host, admin.dataDir);
expect((await admin.host.appsIntegrations({ id: "scout", name: "Scout" }, "ada-chat", "gen-1")).composioOwn).toBeUndefined();
});
- it("relays a member's own bridge to her installation, and refuses it once the turn isn't hers", () => {
- const { host, dataDir } = setup();
+ it("never gives one person's work another's: Ada's room line and the work it hands on get only Ada's, Cleo's only Cleo's", async () => {
+ const { host, dataDir, minted, composio } = setup({ requester: { "room-chat": ADA, "work-chat": CLEO } });
+ adaConnected(host, dataDir, { cleo: true });
+ await host.appsIntegrations({ id: "scout", name: "Scout" }, "room-chat", "gen-room");
+ await host.appsIntegrations({ id: "helper", name: "Helper" }, "work-chat", "gen-work");
+ expect(minted.filter((entry) => entry.connectorsFor).map((entry) => [entry.threadId, entry.connectorsFor])).toEqual([["room-chat", ADA], ["work-chat", CLEO]]);
+ const owns = composio.mcpIntegration.mock.calls.map(([, context]) => context as typeof context & { threadId: string }).filter((context) => context.as);
+ expect(owns.map((context) => [context.threadId, context.as])).toEqual([["room-chat", ADA_ACCESS], ["work-chat", CLEO_ACCESS]]);
+ // A bridge minted for one person is refused in a turn that acts for the other, on every call.
+ expect(host.relayActor({ threadId: "room-chat", generation: "gen-room", connectorsFor: ADA })).toEqual({ access: ADA_ACCESS });
+ expect(host.relayActor({ threadId: "room-chat", generation: "gen-room", connectorsFor: CLEO }).refusal).toMatch(/[email protected]'s own apps, and this turn no longer acts for [email protected]/);
+ expect(host.relayActor({ threadId: "work-chat", generation: "gen-work", connectorsFor: ADA }).refusal).toMatch(/[email protected]'s own apps/);
+ expect(host.relayActor({ threadId: "cleo-chat", generation: "g", connectorsFor: ADA }).refusal, "her bridge in Cleo's private chat").toMatch(/[email protected]'s own apps/);
+ // Each turn's MCP servers carry only its own person's key.
+ const room = JSON.stringify(await host.turnMcp(BOT, "room-chat", "gen-room")), work = JSON.stringify(await host.turnMcp(BOT, "work-chat", "gen-work"));
+ expect(room).toContain("ada-own-mail-key");
+ expect(room).not.toContain("cleo-own-mail-key");
+ expect(work).toContain("cleo-own-mail-key");
+ expect(work).not.toContain("ada-own-mail-key");
+ });
+
+ it("relays a member's own bridge to her installation, and refuses it once the turn doesn't act for her", () => {
+ const { host, dataDir } = setup({ requester: { "room-chat": "" } });
adaConnected(host, dataDir);
expect(host.relayActor({ threadId: "ada-chat", generation: "g", connectorsFor: ADA })).toEqual({ access: ADA_ACCESS });
expect(host.relayActor({ threadId: "ada-chat", generation: "g" })).toEqual({});
- expect(host.relayActor({ threadId: "cleo-chat", generation: "g", connectorsFor: ADA }).refusal).toMatch(/one person's own apps/);
- expect(host.relayActor({ threadId: "room-chat", generation: "g", connectorsFor: ADA }).refusal).toMatch(/one person's own apps/);
+ const refused = host.relayActor({ threadId: "cleo-chat", generation: "g", connectorsFor: ADA }).refusal;
+ expect(refused).toMatch(/[email protected]'s own apps, and this turn no longer acts for [email protected]: it was stopped, or someone else wrote in it since/);
+ expect(refused, "never worked around").toContain("Don't try it another way (the browser or another tool).");
+ expect(host.relayActor({ threadId: "room-chat", generation: "g", connectorsFor: ADA }).refusal).toMatch(/no longer acts for [email protected]/);
const admin = setup({ requester: { "ada-chat": BEN } });
adaConnected(admin.host, admin.dataDir);
- expect(admin.host.relayActor({ threadId: "ada-chat", generation: "g", connectorsFor: ADA }).refusal).toMatch(/one person's own apps/);
+ expect(admin.host.relayActor({ threadId: "ada-chat", generation: "g", connectorsFor: ADA }).refusal).toMatch(/no longer acts for/);
+ // Her installation went (she disconnected, or left): one line with where to connect again.
+ const gone = setup();
+ gone.host.scopes.set("app", "gmail", "person");
+ expect(gone.host.relayActor({ threadId: "ada-chat", generation: "g", connectorsFor: ADA }).refusal).toMatch(/own apps aren't connected here any more.*"Connect your apps again here: https:\/\/cloud.example.test\/cloud\/team\/team-acme-1"/);
});
it("gives a bot a Chief made the Chief's grants, never a connection: each turn still gets only its own person's", async () => {
- const { host, dataDir, composio } = setup();
+ const { host, dataDir, composio } = setup({ requester: { "main-chat": CLEO } });
adaConnected(host, dataDir);
const inherited = appsFromCreator({ createdBy: "[email protected]", connectorTools: { gmail: { tools: "*" } } }, { createdBy: "[email protected]" });
const made = { id: "scout-helper", name: "Scout's helper", ...inherited };
@@ -132,10 +173,15 @@ describe("apps each person connects", () => {
});
it("refuses a person's app through the team's bridge, and a team app through her own", async () => {
- const { host, dataDir } = setup();
+ const { host, dataDir } = setup({ requester: { "main-chat": "" } });
adaConnected(host, dataDir);
- const team = { threadId: "room-chat", generation: "g" };
- expect(await host.callRefusal(team, [{ slug: "GMAIL_FETCH_EMAILS" }])).toMatch(/Gmail is connected by each person in Acme and works only in that person's own private chat/);
+ const team = { threadId: "main-chat", generation: "g" };
+ const nobody = await host.callRefusal(team, [{ slug: "GMAIL_FETCH_EMAILS" }]);
+ expect(nobody).toMatch(/Gmail is each person's own in Acme, and this work doesn't act for one person/);
+ expect(nobody, "the fix, in one line, never \"open a private chat\"").toContain("\"Gmail is each person's own, so I can't use it here. Ask me yourself and I'll use yours, or an admin can connect Gmail for the whole team: https://cloud.example.test/cloud/team/team-acme-1/apps.\"");
+ expect(nobody).toContain("Don't try it another way (the browser or another tool).");
+ expect(nobody).not.toMatch(/private chat/);
+ expect(await host.callRefusal({ threadId: "room-chat", generation: "g" }, [{ slug: "GMAIL_FETCH_EMAILS" }]), "her own room line: hers, through her bridge").toMatch(/Gmail here is [email protected]'s own: use it through the own_apps tools/);
expect(await host.callRefusal(team, [{ slug: "SLACK_SEND_MESSAGE" }]), "a team app passes").toBeNull();
expect(await host.callRefusal({ threadId: "ada-chat", generation: "g" }, [{ slug: "GMAIL_SEND_EMAIL" }])).toMatch(/through the own_apps tools/);
expect(await host.callRefusal({ threadId: "ada-chat", generation: "g", connectorsFor: ADA }, [{ slug: "GMAIL_SEND_EMAIL" }])).toBeNull();
@@ -152,10 +198,11 @@ describe("apps each person connects", () => {
});
it("answers a connection card for a person's app with the one plain line, never a card", () => {
- const { host } = setup();
+ const { host } = setup({ requester: { "main-chat": "" } });
host.scopes.set("app", "gmail", "person");
expect(host.connectRefusal({ threadId: "ada-chat", generation: "g" }, ["gmail"])).toContain("\"Connect your Gmail here: https://cloud.example.test/cloud/team/team-acme-1\"");
- expect(host.connectRefusal({ threadId: "room-chat", generation: "g" }, ["gmail"])).toMatch(/can't be used here/);
+ expect(host.connectRefusal({ threadId: "room-chat", generation: "g" }, ["gmail"]), "her own room line: where to connect hers").toContain("\"Connect your Gmail here: https://cloud.example.test/cloud/team/team-acme-1\"");
+ expect(host.connectRefusal({ threadId: "main-chat", generation: "g" }, ["gmail"])).toMatch(/this work doesn't act for one person/);
expect(host.connectRefusal({ threadId: "room-chat", generation: "g" }, ["slack"]), "a team app keeps its card").toBeNull();
expect(host.connectRefusal({ threadId: "ada-chat", generation: "g", connectorsFor: ADA }, ["slack"])).toMatch(/ask an admin/);
expect(setup({ team: false }).host.connectRefusal({ threadId: "ada-chat", generation: "g" }, ["gmail"])).toBeNull();
@@ -165,13 +212,15 @@ describe("apps each person connects", () => {
const BOT = { id: "bot-1", name: "Bot" };
describe("MCP servers each person connects", () => {
- it("gives a member's own turn her key, never the team's, and no other turn either", async () => {
- const { host, dataDir } = setup();
+ it("gives a turn that acts for her her key, never the team's, and no other turn either", async () => {
+ const { host, dataDir } = setup({ requester: { "main-chat": "" } });
adaConnected(host, dataDir);
const own = await host.turnMcp(BOT, "ada-chat", "g");
expect(own.mail).toEqual({ type: "http", url: "https://mail.example/mcp", headers: { Authorization: "Bearer ada-own-mail-key" } });
expect(own.console, "the team's server is the team's, with its key").toEqual({ type: "http", url: "https://console.example/mcp", headers: { Authorization: "Bearer team-console-key" } });
- for (const thread of ["room-chat", "main-chat", "cleo-chat"]) {
+ expect((await host.turnMcp(BOT, "room-chat", "g")).mail, "her own room line").toEqual(own.mail);
+ expect((await host.turnMcp(BOT, "work-chat", "g")).mail, "work handed on from her request").toEqual(own.mail);
+ for (const thread of ["main-chat", "cleo-chat"]) {
const elsewhere = await host.turnMcp(BOT, thread, "g");
expect(elsewhere.mail, thread).toBeUndefined();
expect(JSON.stringify(elsewhere), thread).not.toContain("ada-own-mail-key");
@@ -206,18 +255,45 @@ describe("MCP servers each person connects", () => {
});
describe("what the bot and the admins are told", () => {
- it("tells her own turn what is hers and how to connect the rest; elsewhere, that it works only in each person's chat", () => {
- const { host, dataDir } = setup();
+ it("tells a turn that acts for her what is hers and how to connect the rest; one that acts for nobody, why and what to do", () => {
+ const { host, dataDir } = setup({ requester: { "main-chat": "" } });
adaConnected(host, dataDir);
host.scopes.set("app", "outlook", "person");
- const own = host.prompt("ada-chat", { composioOwn: {}, custom: { mail: {} } });
+ const own = host.prompt("room-chat", "g", { composioOwn: {}, custom: { mail: {} } });
expect(own).toContain("Gmail and Outlook are [email protected]'s own: use them through the own_apps tools");
expect(own).toContain("The MCP server mail acts as [email protected]'s own account.");
- const missing = host.prompt("ada-chat", { custom: {} });
- expect(missing).toContain("Each person connects these for themselves, and this person hasn't yet: Gmail, Outlook and mail.");
+ expect(own, "in a group chat, never for anyone else's request").toContain("They are used only for [email protected]'s request: if someone else asks for something from them, say they are [email protected]'s.");
+ const missing = host.prompt("ada-chat", "g", { custom: {} });
+ expect(missing).toContain("Each person connects these for themselves, and [email protected] hasn't connected them yet, or their sign-in ended: Gmail, Outlook and mail.");
expect(missing).toContain("\"Connect your <name> here: https://cloud.example.test/cloud/team/team-acme-1\"");
- expect(host.prompt("room-chat", {})).toContain("work only in that person's own private chat with you");
- expect(setup().host.prompt("room-chat", {}), "nothing each person's: nothing said").toBe("");
+ expect(missing).toContain("don't try it another way (the browser or another tool)");
+ const nobody = host.prompt("main-chat", "g", {});
+ expect(nobody).toContain("Gmail, Outlook and mail are each person's own in Acme: they work for the person whose own message started the work");
+ expect(nobody).toContain("Ask me yourself and I'll use yours, or an admin can connect <name> for the whole team: https://cloud.example.test/cloud/team/team-acme-1/apps.");
+ expect(nobody).not.toMatch(/private chat/);
+ expect(setup().host.prompt("room-chat", "g", {}), "nothing each person's: nothing said").toBe("");
+ });
+
+ it("says whose own account a step used: a person's app through her bridge, or a person's server, in a turn that acts for her", () => {
+ const { host, dataDir } = setup({ requester: { "main-chat": "" } });
+ adaConnected(host, dataDir);
+ const named = (tool: string, input?: unknown, thread = "room-chat") => host.toolWhose(thread, "g", tool, input);
+ expect(named("mcp__own_apps__GMAIL_FETCH_EMAILS")).toEqual({ whose: { person: "[email protected]", app: "Gmail" } });
+ expect(named("mcp__own_apps__COMPOSIO_MULTI_EXECUTE_TOOL", JSON.stringify({ tools: [{ tool_slug: "GMAIL_SEND_EMAIL" }] })), "a meta-tool names its app tools").toEqual({ whose: { person: "[email protected]", app: "Gmail" } });
+ expect(named("GMAIL_FETCH_EMAILS"), "an engine that names the tool alone").toEqual({ whose: { person: "[email protected]", app: "Gmail" } });
+ expect(named("gmail.fetch_emails"), "an app tool").toEqual({ whose: { person: "[email protected]", app: "Gmail" } });
+ expect(named("mcp__mail__read_inbox"), "her own MCP server").toEqual({ whose: { person: "[email protected]", app: "mail" } });
+ expect(named("mcp__console__query"), "the team's server").toEqual({});
+ expect(named("mcp__composio__SLACK_SEND_MESSAGE"), "a team app").toEqual({});
+ expect(named("mcp__own_apps__GMAIL_FETCH_EMAILS", undefined, "main-chat"), "a turn that acts for nobody").toEqual({});
+ expect(host.toolWhose("room-chat", undefined, "mcp__own_apps__GMAIL_FETCH_EMAILS"), "no turn running").toEqual({});
+ const cleos = setup({ requester: { "work-chat": CLEO } });
+ adaConnected(cleos.host, cleos.dataDir);
+ expect(cleos.host.toolWhose("work-chat", "g", "mcp__own_apps__GMAIL_FETCH_EMAILS"), "Cleo connected nothing of hers").toEqual({});
+ expect(cleos.host.toolWhose("work-chat", "g", "mcp__mail__read_inbox")).toEqual({});
+ const named2 = setup({ requester: { "room-chat": ADA } });
+ adaConnected(named2.host, named2.dataDir);
+ expect(named2.host.toolWhose("room-chat", "g", "mcp__own_apps__GMAIL_FETCH_EMAILS")).toEqual({ whose: { person: "[email protected]", app: "Gmail" } });
});
it("says who connected what for the admin read, by address, never a secret", async () => {
diff --git a/server/host/team-connections-host.ts b/server/host/team-connections-host.ts
index e8c6f5d32b..a3bc2f4777 100644
--- a/server/host/team-connections-host.ts
+++ b/server/host/team-connections-host.ts
@@ -1,8 +1,9 @@
// Whose connection a turn on a Team Cloud may use. The team's connections serve every turn; a `person` app or MCP server
-// is offered to a turn only when the turn is that member's own: its conversation is their private chat (`member:<person>`)
-// and their own message started it.
-// Security: nothing else ever gets a member's connection: not a group chat, the bot's main chat, another member's chat,
-// an admin writing in theirs, a routine or a webhook. The relay checks it again on every call. Off a team nothing changes.
+// is offered to a turn only for the person it acts for (server/host/acting-person.ts): their own message started its work,
+// in their private chat, a group chat or the bot's main chat, or the work was handed on from a turn that acted for them.
+// Security: nothing else ever gets a member's connection: not another person's request or the work it hands on, not a
+// turn someone else wrote into, not another member's private chat, a routine or a webhook. The relay checks it again on
+// every call. Off a team nothing changes.
import { createHash } from "node:crypto";
import { join } from "node:path";
@@ -31,8 +32,10 @@ export interface TeamConnectionsHostDeps {
adminOrigin: string | null;
harnessUrl: string;
audienceOf(threadId: string): Audience;
- /** The person whose own message provably started this turn generation (the latest one when none is named), or null. */
+ /** The person this turn generation acts for (the latest one when none is named), or null: server/host/acting-person.ts. */
requester(threadId: string, generation?: string): string | null;
+ /** What a person is called in a bot's words: the name they chose, else their address. */
+ personName?(person: string): string | undefined;
/** A `connectors` capability for this turn; `connectorsFor` makes it the member's own bridge's. */
mint(capability: { botId: string; threadId: string; generation: string; connectorsFor?: string }): string;
mcpOAuth: McpOAuthManager;
@@ -93,32 +96,47 @@ export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {
const without = <T,>(servers: Record<string, T>, names: readonly string[]) =>
Object.fromEntries(Object.entries(servers).filter(([name]) => !names.includes(name)));
- /** The member a turn may act for: their private chat, started by their own message. */
+ /** The member a turn acts for, so it may use their own connections: never in another member's private chat. */
const turnPerson = (threadId: string, generation?: string): string | null => {
if (!team) return null;
- const person = audienceMember(deps.audienceOf(threadId));
- return person && deps.requester(threadId, generation) === person ? person : null;
+ const person = deps.requester(threadId, generation);
+ const member = audienceMember(deps.audienceOf(threadId));
+ return person && (member === null || member === person) ? person : null;
};
+ const nameOf = (person: string): string => deps.personName?.(person) || people.emailOf(person) || "this person";
+ const teamName = () => team?.name ?? "the team";
+ /** An admin's page for who connects each app, where one can be connected for the whole team. */
+ const appsPage = () => { const where = link(); return where ? `${where}/apps` : null; };
+ const noWorkaround = "Nothing was run. Don't try it another way (the browser or another tool).";
const lines = {
- connect: (name: string) => {
+ connect: (name: string, who: string) => {
const where = link();
- return `${name} is connected by each person in ${team?.name ?? "the team"}, and this person hasn't connected theirs. Reply with this one line and nothing more about it: `
+ return `${name} is connected by each person in ${teamName()}, and ${who} hasn't connected theirs. ${noWorkaround} Reply with this one line and nothing more about it: `
+ (where ? `"Connect your ${name} here: ${where}"` : `"Connect your own ${name} on your team's page in MausBot Cloud."`);
},
- elsewhere: (name: string) => `${name} is connected by each person in ${team?.name ?? "the team"} and works only in that person's own private chat with this bot, `
- + "for their own requests. It can't be used here: say so in one plain line. Nothing was run.",
- ownOnly: "These are one person's own apps: they work only in that person's private chat, for their own requests. Nothing was run.",
+ /** No one person's own request is behind this work: say so, and how to get it done. */
+ nobody: (name: string) => {
+ const where = appsPage();
+ return `${name} is each person's own in ${teamName()}, and this work doesn't act for one person (a routine, an outside app or a bot started it, or more than one person wrote in it), so no one's ${name} can be used. ${noWorkaround} Reply with this one line and nothing more about it: `
+ + `"${name} is each person's own, so I can't use it here. Ask me yourself and I'll use yours${where ? `, or an admin can connect ${name} for the whole team: ${where}` : ""}."`;
+ },
+ ownOnly: (who: string) => `These are ${who}'s own apps, and this turn no longer acts for ${who}: it was stopped, or someone else wrote in it since. ${noWorkaround} Say so in one plain line: ${who} can ask again.`,
+ ownGone: (who: string) => {
+ const where = link();
+ return `${who}'s own apps aren't connected here any more. ${noWorkaround} Reply with this one line and nothing more about it: `
+ + (where ? `"Connect your apps again here: ${where}"` : `"Connect your apps again on your team's page in MausBot Cloud."`);
+ },
teamApp: (name: string) => `${name} is ${team?.name ?? "the team"}'s, connected once for everyone: use it through the composio tools, not ${OWN_APPS_SERVER}. Nothing was run.`,
teamCard: (name: string) => `${name} is ${team?.name ?? "the team"}'s, connected once for everyone by an admin: ask an admin to connect it. Nothing was shown.`,
opaque: (names: string[]) => `Code that calls apps can't run here while ${list(names)} ${names.length === 1 ? "is" : "are"} connected by each person. Call the app's tools directly.`,
};
- /** What a `person` app the team's bridge was asked for says: in the member's own turn, where theirs is; elsewhere, no. */
+ /** What a `person` app the team's bridge was asked for says: in a turn that acts for someone, where theirs is; else no. */
const personAppLine = (app: string, threadId: string, generation?: string): string => {
const person = turnPerson(threadId, generation);
- if (!person) return lines.elsewhere(appLabel(app));
- return people.appsAccess(person) ? `${appLabel(app)} here is this person's own: use it through the ${OWN_APPS_SERVER} tools. Nothing was run.` : lines.connect(appLabel(app));
+ if (!person) return lines.nobody(appLabel(app));
+ return people.appsAccess(person) ? `${appLabel(app)} here is ${nameOf(person)}'s own: use it through the ${OWN_APPS_SERVER} tools. Nothing was run.` : lines.connect(appLabel(app), nameOf(person));
};
const personSpec = async (person: string, name: string, spec: Extract<McpServerSpec, { url: string }>): Promise<McpServerSpec | null> => {
@@ -145,8 +163,8 @@ export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {
if (deps.composio.configured(deps.cfg())) void appsConnected();
},
- /** The connected-apps bridges of a turn: the team's, and in a member's own turn their own beside it. `names`: how the
- * engine spells the app tools' names. */
+ /** The connected-apps bridges of a turn: the team's, and in a turn that acts for a member their own beside it.
+ * `names`: how the engine spells the app tools' names. */
async appsIntegrations(bot: Bot, threadId: string, generation: string, names: "dotted" | "plain" = "plain"): Promise<{ composio?: Integration; composioOwn?: Integration }> {
const cfg = deps.cfg();
const out: { composio?: Integration; composioOwn?: Integration } = {};
@@ -163,12 +181,13 @@ export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {
},
/** Whose installation a relayed frame goes to: the team's (none named), or the member's own after checking the turn
- * is still theirs. A refusal is the plain line the bot gets back. */
+ * still acts for them. A refusal is the plain line the bot gets back. */
relayActor(capability: { threadId: string; generation: string; connectorsFor?: string }): { access?: BrokerAccess; refusal?: string } {
- if (!capability.connectorsFor) return {};
- if (turnPerson(capability.threadId, capability.generation) !== capability.connectorsFor) return { refusal: lines.ownOnly };
- const access = people.appsAccess(capability.connectorsFor);
- return access ? { access } : { refusal: lines.ownOnly };
+ const own = capability.connectorsFor;
+ if (!own) return {};
+ if (turnPerson(capability.threadId, capability.generation) !== own) return { refusal: lines.ownOnly(nameOf(own)) };
+ const access = people.appsAccess(own);
+ return access ? { access } : { refusal: lines.ownGone(nameOf(own)) };
},
/** The app calls a frame would run, checked against the scopes: a `person` app never through the team's bridge, a
@@ -200,14 +219,17 @@ export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {
const apps = personApps();
for (const slug of slugs) {
const app = apps.includes(slug) ? slug : null;
- if (capability.connectorsFor) return app ? lines.connect(appLabel(app)) : lines.teamCard(appLabel(slug));
- if (app) return turnPerson(capability.threadId, capability.generation) ? lines.connect(appLabel(app)) : lines.elsewhere(appLabel(app));
+ if (capability.connectorsFor) return app ? lines.connect(appLabel(app), nameOf(capability.connectorsFor)) : lines.teamCard(appLabel(slug));
+ if (app) {
+ const person = turnPerson(capability.threadId, capability.generation);
+ return person ? lines.connect(appLabel(app), nameOf(person)) : lines.nobody(appLabel(app));
+ }
}
return null;
},
- /** A turn's MCP servers: the team's (never a `person` server's team credential), plus, in a member's own turn, the
- * `person` servers they connected, with their own key or sign-in. */
+ /** A turn's MCP servers: the team's (never a `person` server's team credential), plus, in a turn that acts for a
+ * member, the `person` servers they connected, with their own key or sign-in. What isn't mounted, prompt() says. */
async turnMcp(bot: McpBot, threadId: string, generation: string): Promise<Record<string, McpServerSpec>> {
const all = deps.botMcp(bot), names = personMcp();
const out = await withMcpSignIn(without(all, names), deps.mcpOAuth);
@@ -227,26 +249,55 @@ export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {
return withoutPendingSignIn(without(deps.botMcp(bot), personMcp()), deps.mcpOAuth);
},
- /** What the bot is told: in a member's own turn, what is theirs and how to connect what isn't; elsewhere, that these
- * work only in each person's private chat. Empty off a team or with no `person` connection. */
- prompt(threadId: string, mounted: { composioOwn?: unknown; custom?: Record<string, unknown> }): string {
+ /** What the bot is told: in a turn that acts for a member, what is theirs and how to connect what isn't; in one that
+ * acts for nobody, why none of these can be used and what the person can do. Empty off a team or with no `person`
+ * connection. */
+ prompt(threadId: string, generation: string | undefined, mounted: { composioOwn?: unknown; custom?: Record<string, unknown> }): string {
const apps = personApps(), servers = personMcp();
if (!team || (!apps.length && !servers.length)) return "";
const names = [...apps.map(appLabel), ...servers];
- const person = turnPerson(threadId);
+ const person = turnPerson(threadId, generation);
if (!person) {
- return ` ${list(names)} ${names.length === 1 ? "is" : "are"} connected by each person in ${team.name} and work only in that person's own private chat with you, `
- + "for their own requests. If asked to use one here, say in one plain line that it works only in each person's private chat.";
+ const where = appsPage();
+ return ` ${list(names)} ${names.length === 1 ? "is" : "are"} each person's own in ${team.name}: ${names.length === 1 ? "it works" : "they work"} for the person whose own message started the work, and this work doesn't act for one person (a routine, an outside app or a bot started it, or more than one person wrote in it). `
+ + `If the task needs one, don't try it another way (the browser or another tool): reply with one plain line and nothing more about it: "<name> is each person's own, so I can't use it here. Ask me yourself and I'll use yours${where ? `, or an admin can connect <name> for the whole team: ${where}` : ""}."`;
}
- const who = people.emailOf(person) ?? "this person";
- const whose = who === "this person" ? "this person's" : `${who}'s`;
+ const who = nameOf(person);
+ const whose = `${who}'s`;
const ownApps = mounted.composioOwn ? apps : [];
const ownServers = servers.filter((name) => Object.hasOwn(mounted.custom ?? {}, name));
const missing = [...(mounted.composioOwn ? [] : apps.map(appLabel)), ...servers.filter((name) => !ownServers.includes(name))];
const where = link();
+ const only = `They are used only for ${who}'s request: if someone else asks for something from them, say they are ${whose}.`;
return (ownApps.length ? ` ${list(ownApps.map(appLabel))} ${ownApps.length === 1 ? "is" : "are"} ${whose} own: use ${ownApps.length === 1 ? "it" : "them"} through the ${OWN_APPS_SERVER} tools, which act as their own accounts; ${team.name}'s shared apps stay under composio.` : "")
+ (ownServers.length ? ` The MCP ${ownServers.length === 1 ? "server" : "servers"} ${list(ownServers)} act${ownServers.length === 1 ? "s" : ""} as ${whose} own account.` : "")
- + (missing.length ? ` Each person connects these for themselves, and this person hasn't yet: ${list(missing)}. If the task needs one, reply with one plain line and nothing more about it: "Connect your <name> here: ${where ?? "your team's page in MausBot Cloud"}".` : "");
+ + (ownApps.length || ownServers.length ? ` ${only}` : "")
+ + (missing.length ? ` Each person connects these for themselves, and ${who} hasn't connected ${missing.length === 1 ? "it" : "them"} yet, or their sign-in ended: ${list(missing)}. If the task needs one, don't try it another way (the browser or another tool): reply with one plain line and nothing more about it: "Connect your <name> here: ${where ?? "your team's page in MausBot Cloud"}".` : "");
+ },
+
+ /** Whose own account a tool call uses, for its step ("using Ada's Notion"): a `person` app through their own bridge,
+ * or a `person` MCP server, in a turn that acts for them. Empty for anything else. */
+ toolWhose(threadId: string, generation: string | undefined, tool: string, input?: unknown): { whose?: { person: string; app: string } } {
+ const apps = personApps(), servers = personMcp();
+ if (!team || !generation || (!apps.length && !servers.length)) return {};
+ const named = /^mcp__(.+?)__(.+)$/.exec(tool);
+ const server = named?.[1], bare = named?.[2] ?? tool;
+ let app: string | null = null, theirs: (person: string) => boolean = () => false;
+ if (server !== undefined && servers.includes(server)) {
+ const spec = teamServer(server);
+ const url = spec && isRemoteMcpServer(spec) ? spec.url : null;
+ app = server;
+ theirs = (person) => Boolean(url && (people.key(person, server, url) || people.oauth(person).authState(server, url) === "signed-in"));
+ } else if (server === undefined || server === OWN_APPS_SERVER) {
+ // A meta-tool names the app tools it runs in its input; an app tool names its app first.
+ const called = typeof input === "string" ? input : input === undefined ? "" : JSON.stringify(input);
+ const slugs = [bare.replace(/\./g, "_"), ...[...called.matchAll(/"tool_slug"\s*:\s*"([A-Za-z0-9_]+)"/g)].map((match) => match[1]!)];
+ const slug = slugs.map((candidate) => personAppOf(candidate, apps)).find(Boolean);
+ app = slug ? appLabel(slug) : null;
+ theirs = (person) => people.appsAccess(person) !== null;
+ }
+ const person = app ? turnPerson(threadId, generation) : null;
+ return app && person && theirs(person) ? { whose: { person: nameOf(person), app } } : {};
},
/** An MCP server was removed: every person's key and sign-in for it go, and it is the team's again if re-added. */
diff --git a/server/index.ts b/server/index.ts
index d8939e1212..8709654002 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -628,7 +628,7 @@ import { createPersonReplies } from "./person-replies.ts";
import { personKey, relayedPersonKey } from "./person-key.ts";
import { createTeamOwners, type AskViewer } from "./host/team-owners.ts"; import { createTeamMessages } from "./host/team-messages.ts"; import { relayedTurn } from "./host/relayed-turn.ts"; import { createPersonCalendar } from "./host/person-calendar.ts";
import { createDevsReports } from "./host/devs-reports.ts"; import { bugReportEndpoint, devsReportSender } from "./devs-report-send.ts"; import { captureRecentLog } from "./recent-log.ts";
-import { createCardRequester, linePersonKey } from "./host/thread-person.ts";
+import { createCardRequester, linePersonKey } from "./host/thread-person.ts"; import { createActingPeople, HANDED_PEOPLE_FILE, HandedPeople, type HandedRun, withPerson } from "./host/acting-person.ts";
import { createThreadRoutes } from "./routes/threads.ts";
import { createWebhookRoutes } from "./routes/webhooks.ts";
import { withScopeHint } from "./connector-scope-hint.ts";
@@ -1421,7 +1421,7 @@ const mcpOAuth = new McpOAuthManager({
});
// Connector tool grants only filter tools/list; the relay's verdict decides each call.
const teamConnections = createTeamConnectionsHost({ team: CLOUD_TEAM, dataDir: DATA_DIR, cfg: () => cfg, adminOrigin: CLOUD_HOME?.adminOrigin ?? null, harnessUrl: `http://127.0.0.1:${PORT}`, audienceOf: teamHost.audienceOf,
- requester: (threadId, generation) => { const owner = directRequestOwners.get(threadId); return provenRequestPerson(owner, generation ?? owner?.generation ?? "", (id) => linePersonKey(store.messagesFor(threadId).find((message) => message.id === id))); },
+ requester: (threadId, generation) => actingPeople.requester(threadId, generation), personName: (person) => teamHost.personName(person),
mint: (capability) => mintInternalCapability({ ...capability, depth: 0, kind: "connectors", skillAuthoring: false, createdBots: 0, openedThreads: 0 }), mcpOAuth, isSessionLive: (id) => sessions.isLive(id),
botMcp: (bot) => mcpServersHost.mounted(bot), brokerUrl: () => (CLOUD_TEAM ? cloudConnectedAppsBrokerUrl() || null : null), composio }); teamConnections.primeApps();
// OpenCode reads provider keys (ANTHROPIC_API_KEY, OPENAI_API_KEY, …) from its environment. Wired before the first catalog probe below.
@@ -2862,11 +2862,12 @@ const store = new Store(
() => appLanguage() ?? Intl.DateTimeFormat().resolvedOptions().locale,
() => sharedMembership() ? undefined : cfg.profile?.name,
);
-const { cloudLendingTurn, cloudLendingRefusalNotice, cloudLendingRefusal, cloudThreadStarters, cloudLendingView, cloudReportFromOthers, roomTurnStarted, roomTurnEnded } = createCloudLendingTurns({
+const { cloudLendingTurn, cloudLendingRefusalNotice, cloudLendingRefusal, cloudThreadStarters, cloudLendingView, cloudReportFromOthers, roomTurnStarted, roomTurnEnded, roomRun } = createCloudLendingTurns({
store, cloudHome: CLOUD_HOME !== null, directRequest: (threadId) => directRequestOwners.get(threadId), threadStarter: (threadId) => threadStarters.get(threadId),
ownerPerson: cloudProvenOwnerPerson, cardAnswerer: cloudCardAnswerer, activeRoutineRun: activeRoutineRunForThread, ownerStartedRun: (runId) => ownerStartedRoutineRuns.has(runId),
routineRunIsOwners: cloudRoutineRunIsOwners, routines: () => routines, routineAuthors: cloudRoutineAuthors, lentPlatform: () => sharedComputers.known(CLOUD_HOME_LENDER)[0]?.platform,
memoryChangedBySomeoneElse: (botId) => lendingMemory?.reconcile(botId, foreignTurnRunning(botId), { cached: true }).changedBySomeoneElse === true });
+const actingPeople = createActingPeople({ store, direct: (threadId) => directRequestOwners.get(threadId), roomRun, handed: new HandedPeople(join(DATA_DIR, HANDED_PEOPLE_FILE)) });
const { stopThreadForPerson, stopOnTypedCommand, noteTeammatesLeftRunning } = createPersonStop({
store, routines: () => routines, handoffs: () => handoffs, interruptDirectThread, clearUnattended,
stopGoal: (threadId) => oneOnOneGoals.stop(threadId), markStopped: (threadId) => personStops.stop(threadId, liveTurns.running(threadId), directTurnDispatchClaims.has(threadId)),
@@ -3576,8 +3577,8 @@ type GroupTurnOperation = {
providerHandshakePending: boolean;
queuedQueueIds?: string[];
line?: RoomRoundLine;
- /** The person's room line this run answers: its member turns, mentions included, act for whoever wrote it. */
- requestMessageId?: string;
+ /** The person's room line this run answers (its member turns, mentions included, act for whoever wrote it), or the handed-on work it does. */
+ requestMessageId?: string; handedFor?: HandedRun;
goalRun?: LiveGoalRun;
};
@@ -3867,7 +3868,7 @@ function noteQueuedBehindPerson(node: HandoffView): void {
function runRoomNode(node: HandoffView, group: GroupRecord, bot: BotRecord, signal: AbortSignal, parent: HandoffView | undefined,
turn: (operation: GroupTurnOperation, result: GroupTurnOrchestration["result"], coordination: NonNullable<GroupTurnOrchestration["coordination"]>) => Promise<unknown>,
): Promise<HostTurnResult> {
- const operation = beginGroupTurnOperation(group.id, node.threadId, [bot.id]);
+ const operation = Object.assign(beginGroupTurnOperation(group.id, node.threadId, [bot.id]), { handedFor: actingPeople.handedRun(node.id) });
return new Promise<HostTurnResult>(resolve => {
let done = false;
const finish = (outcome: HostTurnResult) => {
@@ -3932,7 +3933,7 @@ function runRootTurn(node: HandoffView, bot: BotRecord, signal: AbortSignal, com
void startTurn(bot.id, composed.text, {
threadId: node.threadId, cardContinuation: true,
...(ownRequest?.messageId ? { requestMessageId: ownRequest.messageId } : {}),
- ...(ownRequest ? {} : { origin: node.origin ?? OUTSIDE }),
+ ...(ownRequest ? {} : { origin: actingPeople.handedOrigin(node.origin ?? OUTSIDE, node.id) }),
unattended: isUnattended(bot.id, node.threadId),
coordination: { id: node.id, resumed: false, settle: finish },
onDispatchError: error => finish({ ok: false, text: error }),
@@ -4113,7 +4114,7 @@ const coordinator: Coordinator = createCoordinator({
threadId: node.threadId, cardContinuation: true, commsDepth: MAX_COMMS_DEPTH,
requestMessageId: directRequestOwners.get(node.threadId)?.generations.has(node.rootId)
? directRequestOwners.get(node.threadId)?.messageId : undefined,
- origin: coordinator.node(node.rootId)?.origin ?? OUTSIDE,
+ origin: actingPeople.handedOrigin(coordinator.node(node.rootId)?.origin ?? OUTSIDE, node.id),
unattended: isUnattended(bot.id, node.threadId),
coordination: { id: node.id, resumed, settle: finish },
onDispatchError: error => finish({ ok: false, text: error }),
@@ -6550,7 +6551,7 @@ bus.subscribe((event: RuntimeEvent) => {
const message = pushMessage({
role: "bot",
kind: "activity",
- tool: { name, spoken: narrateTool(name) ?? undefined, ...(event.step ? { step: event.step } : {}), summary: event.summary, input: event.input === undefined ? undefined : scrubHeldSecrets(event.input), itemId: event.itemId ?? event.eventId },
+ tool: { name, spoken: narrateTool(name) ?? undefined, ...(event.step ? { step: event.step } : {}), summary: event.summary, input: event.input === undefined ? undefined : scrubHeldSecrets(event.input), itemId: event.itemId ?? event.eventId, ...teamConnections.toolWhose(event.threadId, activeInternalGenerationByThread.get(event.threadId), name, event.input) },
turnId: liveTurnId,
});
if (event.itemId) toolMessageByItem.set(`${event.threadId}:${event.itemId}`, message.id);
@@ -8502,7 +8503,7 @@ async function startTurn(
{ id: "plan", label: "Surface", text: surfacePrompt({ computer: mountedComputer, browser: Boolean(integrations.browser) }, { pinned: plan.pinned, note: plan.note + vpsUnavailableNote + vmUpdateNote + (computerSkipped && plan.computer !== "off" ? computerSkippedNote(redactSecretsInText(computerSkipped)) : ""), canSelect: computerSelectionTurns.has(threadId), cloudHome: Boolean(CLOUD_HOME), botOpened: plan.botOpened }) },
{ id: "cloud-home", label: "My Cloud", text: CLOUD_HOME ? cloudHomePrompt(Boolean(integrations.agents) && lendingEnabled(), syncedFolders(DATA_DIR), sharedComputers.known(CLOUD_HOME_LENDER)) + firstHourHooks.prompt(bot.id, threadId) : "" },
{ id: "composio", label: "Connected apps", text: integrations.composio ? composioSystemPrompt(liveBot?.connectorTools ?? bot.connectorTools) + describeConnectorScopes((liveBot ?? bot).connectorScopes) : "" },
- { id: "mcp", label: "MCP servers", text: customMcpPrompt(Object.keys(integrations.custom ?? {}), mcpServersHost.off(bot)) }, { id: "to-connect", label: "Connections to make", text: cloudConnections.prompt(liveBot ?? bot) + teamConnections.prompt(threadId, integrations) },
+ { id: "mcp", label: "MCP servers", text: customMcpPrompt(Object.keys(integrations.custom ?? {}), mcpServersHost.off(bot)) }, { id: "to-connect", label: "Connections to make", text: cloudConnections.prompt(liveBot ?? bot) + teamConnections.prompt(threadId, dispatchClaimId, integrations) },
{ id: "browser", label: "Browser", text: integrations.browser ? browserPromptFor(bot, Boolean(integrations.agents)) : "" },
{ id: "data", label: "Data", text: integrations.data ? BUILT_IN_DATA_SYSTEM_PROMPT : "" },
{ id: "highlevel", label: "HighLevel", text: integrations.highlevel ? highlevelHost.prompt(liveBot ?? bot) : "" },
@@ -10310,7 +10311,7 @@ async function runClaimedGroupMemberTurn(
{ id: "user-profile", label: "About the user", text: userProfileSystemPrompt(teamHost.profileFor(threadId, cfg.profile)) }, { id: "people", label: "People", text: teamMessages.prompt(bot.id, threadId, Boolean(integrations.agents)) },
{ id: "files", label: "File locations", text: workspace ? workspaceLocationsPrompt(bot.id, cwd, readyBot.cwd, { attachFile: Boolean(integrations.agents) && !CLOUD_HOME && !HOSTED_WORKSPACE }) : "" },
{ id: "shell", label: "Long-running commands", text: workspace ? longCommandsPrompt(roomComputerPromptKind) : "" },
- { id: "mcp", label: "MCP servers", text: customMcpPrompt(Object.keys(integrations.custom ?? {}), mcpServersHost.off(bot)) + teamConnections.prompt(threadId, integrations) },
+ { id: "mcp", label: "MCP servers", text: customMcpPrompt(Object.keys(integrations.custom ?? {}), mcpServersHost.off(bot)) + teamConnections.prompt(threadId, internalGeneration, integrations) },
{ id: "computer", label: "Computer", text: computerPrompt(roomComputerPromptKind) },
{ id: "team-computer", label: "Team computer", text: teamComputerPrompt(roomTeamComputer) },
{ id: "plan", label: "Surface", text: surfacePrompt({ computer: roomTeamComputer ? "cloud" : roomVmTarget ? "vm" : surfaceOfComputerKind(roomComputerKind), browser: Boolean(integrations.browser) }, { note: roomPlan.note, cloudHome: Boolean(CLOUD_HOME) }) },
@@ -13959,7 +13960,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
mode, reply, thread: lane ? "new" : call.thread, approvalGranted, rework: call.rework, ...(lane ? {} : { requestBatchKey }),
...(call.doneWhen ? { doneWhen: call.doneWhen } : {}),
});
- usageTrace.link(node.id, node.parentId, { threadId: internalCapability.threadId, turnId: liveTurnByThread.get(internalCapability.threadId) ?? "" });
+ usageTrace.link(node.id, node.parentId, { threadId: internalCapability.threadId, turnId: liveTurnByThread.get(internalCapability.threadId) ?? "" }); if (!duplicate) actingPeople.handOn(internalCapability, node);
if (duplicate && createdThread) store.deleteTask(target.botId, createdThread);
else if (createdThread) {
threadStarters.set(createdThread, openerFrom(address.threadId));
@@ -14309,7 +14310,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
store.appendMessage(fromThreadId, chip);
// Mark the bot's own words, so a later turn never mistakes the request for the person's.
const opening = `[Thread you opened yourself${sourceTitle ? ` from #${sourceTitle}` : ""}. The request below is your own words, not the person's: do the work here and end with a clear result they can read.]\n\n${message}`;
- const outcome = await startOrQueueOpenedThread(from.id, task.threadId, opening, isUnattended(from.id, fromThreadId), turnOrigin(internalCapability));
+ const outcome = await startOrQueueOpenedThread(from.id, task.threadId, opening, isUnattended(from.id, fromThreadId), withPerson(turnOrigin(internalCapability), actingPeople.requester(internalCapability.threadId, internalCapability.generation)));
return json(res, 201, {
threadId: task.threadId,
title: task.title,
diff --git a/server/peer-provenance.ts b/server/peer-provenance.ts
index cac203dda7..69a9f6e48b 100644
--- a/server/peer-provenance.ts
+++ b/server/peer-provenance.ts
@@ -8,9 +8,10 @@ import { peerName } from "./peer-roster.ts";
const REQUEST_QUOTE_MAX = 400;
-/** From the harness's records, never from model text; work handed on keeps the origin it came from. */
+/** From the harness's records, never from model text; work handed on keeps the origin it came from. `person`: on work
+ * handed on, whom it acts for (server/host/acting-person.ts), so it may use that person's own apps. */
export const workOriginSchema = z.discriminatedUnion("kind", [
- z.object({ kind: z.literal("user"), request: z.string().min(1).max(REQUEST_QUOTE_MAX) }),
+ z.object({ kind: z.literal("user"), request: z.string().min(1).max(REQUEST_QUOTE_MAX), person: z.string().regex(/^p_[\w-]{22}$/).optional() }),
z.object({ kind: z.literal("outside") }),
]);
export type WorkOrigin = z.infer<typeof workOriginSchema>;
diff --git a/shared/wire.ts b/shared/wire.ts
index 833447cb1d..9fe45098e5 100644
--- a/shared/wire.ts
+++ b/shared/wire.ts
@@ -498,8 +498,8 @@ export interface WireMessage extends HelperIntroField, SetupCardFields, WaitLine
/** activity messages: tool name + outcome. */
tool?: {
name: string; ok?: boolean; spoken?: string; setup?: boolean; terminal?: boolean; summary?: string; input?: string; output?: string;
- /** What the call works on, as its live status said it: the chip's and the "Now" card's specific words. */
- step?: import("./turn-progress.ts").LiveStep;
+ /** What the call works on, as its live status said it: the chip's and the "Now" card's specific words. `whose`: the person whose own app or MCP server the call used. */
+ step?: import("./turn-progress.ts").LiveStep; whose?: { person: string; app: string };
/** error rows: the installed Claude Code is too old for the model, and
* the UI can offer to update it in place. notice rows: `rescue`, a turn that heard nothing from its AI for a while. */
claudeUpdate?: boolean; rescue?: import("./first-reply-rescue.ts").FirstReplyRescue;
diff --git a/src/lib/now-steps.test.ts b/src/lib/now-steps.test.ts
index 8229eb9377..eb633db2b3 100644
--- a/src/lib/now-steps.test.ts
+++ b/src/lib/now-steps.test.ts
@@ -45,6 +45,13 @@ describe("the Now card's steps", () => {
expect(stepLabel({ name: "Grep", ok: true }, "done")).toBe("Searched files");
expect(stepLabel({ name: "mcp__agents__ask_bot", ok: true }, "done")).toBe("Asking a teammate");
});
+
+ it("says whose own app a step used, running or done", () => {
+ const whose = { person: "Ada", app: "Notion" };
+ expect(stepLabel({ name: "mcp__own_apps__NOTION_SEARCH", ok: true, whose }, "done")).toMatch(/ · using Ada's Notion$/);
+ expect(stepLabel({ name: "mcp__own_apps__NOTION_SEARCH", whose }, "now")).toMatch(/ · using Ada's Notion$/);
+ expect(stepLabel({ name: "mcp__own_apps__NOTION_SEARCH", ok: true }, "done")).not.toContain("using");
+ });
});
describe("a long step's sign of life", () => {
diff --git a/src/lib/now-steps.ts b/src/lib/now-steps.ts
index 090b9633ba..2616d773e3 100644
--- a/src/lib/now-steps.ts
+++ b/src/lib/now-steps.ts
@@ -4,6 +4,7 @@ import type { LiveStatus } from "@/state/turn-status";
import type { StepQuiet } from "../../shared/turn-progress";
import { t } from "./i18n";
import { toolActivityPhrases, turnNowPhrases } from "./live-activity";
+import { withWhose } from "./tool-step-label";
export type NowStepState = "done" | "failed" | "now";
@@ -36,6 +37,10 @@ const DONE_PLAIN: Partial<Record<string, LocaleKey>> = {
type StepTool = NonNullable<Message["tool"]>;
export function stepLabel(tool: StepTool, state: NowStepState): string {
+ return withWhose(stepWords(tool, state), tool);
+}
+
+function stepWords(tool: StepTool, state: NowStepState): string {
const now = toolActivityPhrases(tool);
if (state === "now") return now.phrases[0]!;
const named = tool.step && DONE_NAMED[tool.step.activity];
diff --git a/src/lib/tool-step-label.test.ts b/src/lib/tool-step-label.test.ts
index e5e47dcbbf..8e4fee22d9 100644
--- a/src/lib/tool-step-label.test.ts
+++ b/src/lib/tool-step-label.test.ts
@@ -28,6 +28,13 @@ describe("toolStepLabel", () => {
expect(toolStepLabel({ name: "ls -la /Users/sam/project", summary: "ls -la /Users/sam/project" })).toBe("Run a command");
});
+ it("says whose own account a step used, after what it did", () => {
+ const whose = { person: "Ada", app: "Notion" };
+ expect(toolStepLabel({ name: "mcp__own_apps__NOTION_SEARCH_NOTION_PAGE", whose })).toBe(`${toolStepLabel({ name: "mcp__own_apps__NOTION_SEARCH_NOTION_PAGE" })} · using Ada's Notion`);
+ expect(toolStepLabel({ name: "mcp__mail__read_inbox", whose: { person: "Ada", app: "mail" } })).toBe("Read inbox · using Ada's mail");
+ expect(toolStepLabel({ name: "Bash", summary: "ls", whose })).toBe("Run a command · using Ada's Notion");
+ });
+
it("keeps a line the server already wrote in words", () => {
expect(toolStepLabel({ name: "Messaged @Ada" })).toBe("Messaged @Ada");
expect(toolStepLabel({ name: "Send failed — the sending bot no longer exists" })).toBe("Send failed — the sending bot no longer exists");
diff --git a/src/lib/tool-step-label.ts b/src/lib/tool-step-label.ts
index 9e2879e277..1442f68a62 100644
--- a/src/lib/tool-step-label.ts
+++ b/src/lib/tool-step-label.ts
@@ -3,7 +3,7 @@ import { t } from "@/lib/i18n";
import type { LocaleKey } from "@/locales";
import type { Message } from "@/state/store";
-type StepTool = Pick<NonNullable<Message["tool"]>, "name" | "summary">;
+type StepTool = Pick<NonNullable<Message["tool"]>, "name" | "summary" | "whose">;
const STEP_KEYS: Record<string, LocaleKey> = {
bash: "toolStep.runCommand",
@@ -59,7 +59,16 @@ function sentence(words: string): string {
return flat ? flat[0]!.toLocaleUpperCase() + flat.slice(1) : flat;
}
+/** Whose own app or MCP server a step used, after its label: "Fetch emails · using Ada's Gmail". */
+export function withWhose(label: string, tool: Pick<StepTool, "whose">): string {
+ return tool.whose ? `${label} · ${t("toolStep.usingWhose", { person: tool.whose.person, app: tool.whose.app })}` : label;
+}
+
export function toolStepLabel(tool: StepTool): string {
+ return withWhose(stepWords(tool), tool);
+}
+
+function stepWords(tool: StepTool): string {
const { name } = tool;
// Codex and ACP title a command's chip with the command line; only a command carries a summary.
if (tool.summary) return t("toolStep.runCommand");
diff --git a/src/locales/en.json b/src/locales/en.json
index f79b602319..7b2c80b248 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -503,6 +503,7 @@
"toolStep.manageAutomations": "Manage automations",
"toolStep.checkAutomations": "Check automations",
"toolStep.useTool": "Use a tool",
+ "toolStep.usingWhose": "using {person}'s {app}",
"attach.gallery": "Attachments",
"attach.gallerySingle": "1 attachment",
"attach.galleryCount": "{count} attachments",
diff --git a/src/state/store.tsx b/src/state/store.tsx
index 50266a9403..f86cedc66c 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -141,7 +141,7 @@ export interface Message extends Pick<import("../../shared/wire").WireMessage, "
goalRun?: GroupGoalRunCardData;
call?: import("../../shared/wire").LiveCallRecord;
channelMode?: "chat" | "goal";
- tool?: { name: string; ok?: boolean; spoken?: string; setup?: boolean; claudeUpdate?: boolean; place?: PlaceRow; limitResetsAt?: number; summary?: string; input?: string; output?: string ; itemId?: string; outputPath?: string; fullResult?: boolean; rescue?: import("../../shared/first-reply-rescue").FirstReplyRescue; step?: import("../../shared/turn-progress").LiveStep };
+ tool?: { name: string; ok?: boolean; spoken?: string; setup?: boolean; claudeUpdate?: boolean; place?: PlaceRow; limitResetsAt?: number; summary?: string; input?: string; output?: string ; itemId?: string; outputPath?: string; fullResult?: boolean; rescue?: import("../../shared/first-reply-rescue").FirstReplyRescue; step?: import("../../shared/turn-progress").LiveStep; whose?: { person: string; app: string } };
steered?: boolean;
via?: "api" | "call";
callId?: string;