Skip to content

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

fix(gmail): guard draft-only requests and support draft updates (#4326)

Krishna Dobhal494e7f5e6c88
diff --git a/docs/approval-levels.md b/docs/approval-levels.md
index 2d6f3b0c7c..b5e1a76af3 100644
--- a/docs/approval-levels.md
+++ b/docs/approval-levels.md
@@ -35,7 +35,7 @@ from the operator's dedicated policy.
| **Ask for approval** | Requests approval for commands and file changes, the way the provider's supervised mode does. |
| **Auto-accept edits** | Approves file edits automatically; other actions can still require approval. Offered where the provider has such a mode (Claude, Grok, Antigravity). |
| **Approve for me** | Uses the provider's automatic review on Codex, Claude, Cursor, and Grok to approve routine actions and ask about others. Providers without an equivalent fall back to asking. |
-| **Full access** | Enables the provider's permissive mode for commands, edits, and selected-computer actions, including potentially destructive or sensitive work. Residual native permission prompts are answered for you. OMB profile changes, routine actions, team setup, bot deletion, and enabled skill authoring apply without a second approval. Peer-review prompts are skipped within the bot's authorized scope. Sends through connected apps (email, messages, posts, payments) go out without the "Send on your behalf?" card or a daily allowance; apps outside the bot's connected-app scope are still refused. Work handed on with `coordinate_bots` uses the receiving bot's setting, never the sender's — except from a Chief of Staff, whose level flows down (below). Actual questions and missing credentials still need your input. |
+| **Full access** | Enables the provider's permissive mode for commands, edits, and selected-computer actions, including potentially destructive or sensitive work. Residual native permission prompts are answered for you. OMB profile changes, routine actions, team setup, bot deletion, and enabled skill authoring apply without a second approval. Peer-review prompts are skipped within the bot's authorized scope. Sends through connected apps (email, messages, posts, payments) follow the bot's Sending on your behalf setting: Ask every time requires consent, and Allow a daily amount consumes the configured cap. Apps outside the bot's connected-app scope are still refused. Work handed on with `coordinate_bots` uses the receiving bot's setting, never the sender's — except from a Chief of Staff, whose level flows down (below). Actual questions and missing credentials still need your input. |
| **Custom (`config.toml`)** | Codex only. OpenMausBot reads and reapplies the effective approval and sandbox settings from your Codex configuration. |
Full access applies the moment you pick it: no confirmation dialog, no second
diff --git a/docs/composio.md b/docs/composio.md
index 88f644b961..d175ec9eca 100644
--- a/docs/composio.md
+++ b/docs/composio.md
@@ -202,3 +202,5 @@ A bot with no grant record at all keeps the legacy behavior: every tool on every
**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.
Grants are enforced on the real tool names at call time (including batches inside the MULTI_EXECUTE meta-tool), the tool list offered to the model is filtered to the granted set, and every allow/deny writes a decision-log row. Refusals do not enumerate what else is granted. Paired phones see each bot's grants read-only in its profile (What this bot does → App tools); grants are assigned on the computer, never from a phone.
+
+Connected-app sends also follow the bot's **Permissions → Sending on your behalf** setting at every access level, including Full access. **Ask every time** requires approval for each send regardless of prompt language. **Allow a daily amount** permits automatic sends up to its cap. Reading and drafting do not consume the allowance; opaque app code execution always requires approval because its effects cannot be counted.
diff --git a/docs/verification/README.md b/docs/verification/README.md
index 0e3222533e..ad4d0d64c6 100644
--- a/docs/verification/README.md
+++ b/docs/verification/README.md
@@ -55,6 +55,7 @@ Use only mapped, tested commands:
- [MausBot, everyone's helper](mausbot.md)
- [Profile proposal and credential-card lifecycle](proposal-cards.md)
- [Full Access without duplicate approvals](full-access.md)
+- [Gmail draft creation, send approval and revision](gmail-drafts.md)
- [Exact command allowlist UI and saved rules](command-allowlist.md)
- [The safety floor: a never-list no grant can allow](safety-floor.md)
- [Peer approval denial, expiry, and cancellation](peer-approvals.md)
diff --git a/docs/verification/full-access.md b/docs/verification/full-access.md
index ef0c4bc7d5..db96e97696 100644
--- a/docs/verification/full-access.md
+++ b/docs/verification/full-access.md
@@ -41,6 +41,11 @@ of a real provider's planning quality or authentication.
- An expired turn token is refused, and Full does not authorize changes to
an existing bot outside the Chief's team scope.
+Connected-app sends follow **Sending on your behalf** at Full access:
+**Ask every time** waits for consent and **Allow a daily amount** consumes
+the configured cap. The [Gmail and outbound fixture](gmail-drafts.md) verifies
+both policies, opaque execution, delegation and changes before dispatch.
+
## Evidence and limits
The desktop smoke uses a disposable Electron utility-process server and the
diff --git a/docs/verification/gmail-drafts.md b/docs/verification/gmail-drafts.md
new file mode 100644
index 0000000000..51164ac322
--- /dev/null
+++ b/docs/verification/gmail-drafts.md
@@ -0,0 +1,49 @@
+# Gmail draft creation, send approval and revision
+
+In the bot's Permissions settings, choose **Ask every time** under
+**Sending on your behalf**. Connected-app sends require consent at every
+access level, including Full access, regardless of the prompt's language.
+An Allow applies to the pending call, not later sends. **Allow a daily amount**
+instead authorizes automatic sends up to the configured cap, including at
+Full access. Reading and drafting never consume the allowance. Opaque app
+code execution needs consent because its effects cannot be counted.
+
+Run the isolated server and bridge regressions:
+
+```sh
+pnpm exec vitest run server/trust-controls.e2e.test.ts server/connected-app-tools.e2e.test.ts server/connector-proxy.test.ts server/connector-app-tools.test.ts server/gmail-draft-policy.test.ts server/outbound-hold.test.ts
+```
+
+The trust-controls fixture launches disposable verification servers and points
+Composio at a loopback stand-in. It verifies:
+
+- Ask every time holds Gmail sends, replies, forwards, Slack sends, opaque
+ execution and mixed create/send batches at Full access. Denial leaves the
+ provider untouched; approval releases only that call.
+- Spanish, Hindi, French, Japanese and English requests need consent before
+ the first send, with no draft write or request-wording classification.
+- The daily allowance permits sends at Full access, consumes the cap, and
+ refuses further sends after it is exhausted. Explicit draft-and-send
+ requests follow the same policy. Sending a draft after a draft write also
+ uses the configured policy.
+- The draft tools create one reply draft and update its existing ID while
+ retaining the Gmail thread. Repeated creation for the same thread within
+ the originating request is refused, including after delegation and resuming.
+ Independent requests must still check existing drafts before creating one.
+- Delegated and resumed Full-access turns respect each bot's outbound policy.
+- Switching from an allowance to Ask every time while session metadata is
+ pending refuses dispatch. Fresh scope checks run before draft reservations,
+ so a scope refusal does not consume a creation attempt.
+
+The bridge tests verify read-only app grants hide draft writes and native
+updates map to GMAIL_UPDATE_DRAFT. The fixture retains its server log and a
+`.trust-controls.json` evidence file under the temporary verification evidence
+directory. Evidence records API requests, responses and provider calls; the
+disposable application data is removed on completion.
+
+These checks prove relay enforcement and draft-tool argument mapping. They do
+not verify Gmail rendering, Composio's MIME reply headers or a model's ability
+to follow natural-language drafting instructions. The relay does not classify
+request wording. A daily allowance authorizes automatic sends; use Ask every
+time when each send needs review. Draft revisions use the existing draft ID,
+not a language-based prohibition on creating drafts.
diff --git a/server/connector-app-tools.test.ts b/server/connector-app-tools.test.ts
index ce3cd52922..5527cd7a2d 100644
--- a/server/connector-app-tools.test.ts
+++ b/server/connector-app-tools.test.ts
@@ -3,14 +3,14 @@ import { describe, expect, it } from "vitest";
import { APP_TOOLS, appToolAnswer, appToolCall, appToolEntries, appToolsFor } from "./connector-app-tools.ts";
const CONNECTED = ["gmail", "googlecalendar", "github"];
-const READS = ["gmail.search_emails", "gmail.read_email", "gmail.read_email_thread", "googlecalendar.list_events", "googlecalendar.list_calendars"];
+const READS = ["gmail.search_emails", "gmail.read_email", "gmail.read_email_thread", "gmail.list_drafts", "gmail.read_draft", "googlecalendar.list_events", "googlecalendar.list_calendars"];
describe("the connected-app tools a bot gets", () => {
it("are its connected apps' tools, and only the reads of an app it may only read", () => {
expect(appToolsFor({}, CONNECTED)).toEqual(APP_TOOLS.map((tool) => tool.name));
expect(appToolsFor({ connectorScopes: { apps: { gmail: "read", googlecalendar: "read" } }, connectorTools: { gmail: { tools: "*" }, googlecalendar: { tools: "*" } } }, CONNECTED)).toEqual(READS);
expect(appToolsFor({ connectorScopes: { apps: { gmail: "write" } }, connectorTools: { gmail: { tools: "*" } } }, CONNECTED))
- .toEqual(["gmail.search_emails", "gmail.read_email", "gmail.read_email_thread", "gmail.create_draft", "gmail.send_email"]);
+ .toEqual(APP_TOOLS.filter(tool => tool.name.startsWith("gmail.")).map(tool => tool.name));
});
it("never offers an app that is not connected, not granted, or granted other tools only", () => {
@@ -24,7 +24,7 @@ describe("the connected-app tools a bot gets", () => {
describe("how an engine sees them", () => {
it("lists them under the dotted names for an engine that finds tools by their own name, and with an underscore elsewhere", () => {
expect(appToolEntries(["gmail.search_emails"], "dotted").map((entry) => entry.name)).toEqual(["gmail.search_emails"]);
- expect(appToolEntries(READS, "plain").map((entry) => entry.name)).toEqual(["gmail_search_emails", "gmail_read_email", "gmail_read_email_thread", "googlecalendar_list_events", "googlecalendar_list_calendars"]);
+ expect(appToolEntries(READS, "plain").map((entry) => entry.name)).toEqual(READS.map(name => name.replace(".", "_")));
});
it("keeps every schema one flat object, the shape every engine's converter keeps", () => {
@@ -38,6 +38,19 @@ describe("how an engine sees them", () => {
});
describe("a call to one", () => {
+ it("keeps draft identity and threading when replacing a reply", () => {
+ const input = { draft_id: "r123", to: "[email protected]", subject: "Re: Account", body: "Revised reply", thread_id: "t123" };
+ const update = appToolCall("gmail_update_draft", input);
+ expect(update?.slug).toBe("GMAIL_UPDATE_DRAFT");
+ expect(update?.frame(1)).toMatchObject({ params: { arguments: { tools: [{ tool_slug: "GMAIL_UPDATE_DRAFT", arguments: {
+ user_id: "me", draft_id: "r123", recipient_email: "[email protected]", subject: "Re: Account", body: "Revised reply", thread_id: "t123",
+ } }] } } });
+ expect(appToolCall("gmail.create_draft", input)?.frame(2)).toMatchObject({ params: { arguments: { tools: [{ tool_slug: "GMAIL_CREATE_EMAIL_DRAFT", arguments: {
+ thread_id: "t123", subject: "Re: Account", body: "Revised reply",
+ } }] } } });
+ expect(appToolsFor({ connectorTools: { gmail: { tools: ["GMAIL_CREATE_EMAIL_DRAFT"] } } }, ["gmail"])).toEqual(["gmail.create_draft"]);
+ });
+
it("runs its Composio tool through the multi-execute tool, by either name, with the arguments it takes", () => {
const call = appToolCall("gmail.search_emails", { query: "from:[email protected]", max_results: "5" });
expect(call?.slug).toBe("GMAIL_FETCH_EMAILS");
diff --git a/server/connector-app-tools.ts b/server/connector-app-tools.ts
index e039d0425d..4bcf06b6ec 100644
--- a/server/connector-app-tools.ts
+++ b/server/connector-app-tools.ts
@@ -74,14 +74,14 @@ export const APP_TOOLS: readonly AppTool[] = [
{
name: "gmail.create_draft",
slug: "GMAIL_CREATE_EMAIL_DRAFT",
- description: "Save an email as a draft in the person's Gmail without sending it. Give thread_id to draft a reply in that conversation.",
+ description: "Create a new Gmail draft without sending. For a reply, read the original thread and provide its thread_id and matching subject. Each call creates a separate draft: first check gmail.list_drafts; revise an existing draft with gmail.update_draft and its draft ID. Never use send_email or a reply/send action to save a draft.",
properties: {
to: { type: "string", description: "The recipient's address; several separated by commas." },
subject: { type: "string" },
body: { type: "string", description: "The text of the email." },
thread_id: { type: "string", description: "For a reply: the conversation's thread id." },
},
- required: ["to", "body"],
+ required: ["to", "subject", "body"],
args: (input) => {
const [first, ...rest] = addresses(input.to ?? input.recipient_email) ?? [];
return {
@@ -90,10 +90,48 @@ export const APP_TOOLS: readonly AppTool[] = [
};
},
},
+ {
+ name: "gmail.list_drafts",
+ slug: "GMAIL_LIST_DRAFTS",
+ description: "List Gmail drafts with draft IDs and message/thread IDs. Find the intended draft before creating or revising a reply. Follow nextPageToken when needed; read its full content with gmail.read_draft.",
+ properties: {
+ query: { type: "string", description: "Gmail search, for example subject:invoice." },
+ max_results: { type: "integer", minimum: 1, maximum: 100 },
+ page_token: { type: "string" },
+ },
+ args: input => ({ user_id: "me", max_results: count(input.max_results, 20, 100),
+ ...(text(input.query) ? { q: text(input.query) } : {}), ...(text(input.page_token) ? { page_token: text(input.page_token) } : {}) }),
+ },
+ {
+ name: "gmail.read_draft",
+ slug: "GMAIL_GET_DRAFT",
+ description: "Read an existing Gmail draft by draft ID, including its content and thread. A draft ID is different from a message ID. Preserve the existing recipients, subject and thread when revising.",
+ properties: { draft_id: { type: "string" } },
+ required: ["draft_id"],
+ args: input => ({ user_id: "me", draft_id: text(input.draft_id) ?? "", format: "full" }),
+ },
+ {
+ name: "gmail.update_draft",
+ slug: "GMAIL_UPDATE_DRAFT",
+ description: "Replace an existing Gmail draft in place without sending. Use its draft_id from creation or gmail.list_drafts, not a message ID. Read it first and provide the complete revised content, preserving recipients, subject and thread_id. Never create a replacement if this fails. Verify the result before claiming success.",
+ properties: {
+ draft_id: { type: "string" }, to: { type: "string" }, subject: { type: "string" }, body: { type: "string" },
+ thread_id: { type: "string" }, cc: { type: "string" }, bcc: { type: "string" }, is_html: { type: "boolean" },
+ },
+ required: ["draft_id", "to", "subject", "body"],
+ args: input => {
+ const [first, ...rest] = addresses(input.to) ?? [];
+ return { user_id: "me", draft_id: text(input.draft_id) ?? "", recipient_email: first ?? "", extra_recipients: rest,
+ subject: String(input.subject ?? ""), body: String(input.body ?? ""),
+ ...(text(input.thread_id) ? { thread_id: text(input.thread_id) } : {}),
+ ...(input.cc !== undefined ? { cc: addresses(input.cc) ?? [] } : {}),
+ ...(input.bcc !== undefined ? { bcc: addresses(input.bcc) ?? [] } : {}), is_html: input.is_html === true };
+ },
+ },
{
name: "gmail.send_email",
slug: "GMAIL_SEND_EMAIL",
- description: "Send an email from the person's Gmail.",
+ description: "Send an email immediately from the person's Gmail. This is not a draft tool. Only use when the person explicitly asks to send; for a draft use gmail.create_draft or gmail.update_draft.",
properties: {
to: { type: "string", description: "The recipient's address; several separated by commas." },
subject: { type: "string" },
diff --git a/server/gmail-draft-policy.test.ts b/server/gmail-draft-policy.test.ts
new file mode 100644
index 0000000000..0b64ddad67
--- /dev/null
+++ b/server/gmail-draft-policy.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from "vitest";
+import { reserveGmailDrafts } from "./gmail-draft-policy.ts";
+
+const create = (thread_id = "gmail-thread") => ({ slug: "GMAIL_CREATE_EMAIL_DRAFT", arguments: { thread_id } });
+
+describe("Gmail draft reservations", () => {
+ it("reserves one creation per Gmail thread, atomically across batches", () => {
+ const reserved = new Set<string>();
+ expect(reserveGmailDrafts([create(), create()], reserved)).toContain("already attempted");
+ expect(reserved.size).toBe(0);
+ expect(reserveGmailDrafts([create()], reserved)).toBeNull();
+ expect(reserveGmailDrafts([create("other"), create()], reserved)).toContain("already attempted");
+ expect(reserved.size).toBe(1);
+ expect(reserveGmailDrafts([create("other")], reserved)).toBeNull();
+ expect(reserveGmailDrafts([{ slug: "GMAIL_UPDATE_DRAFT" }], reserved)).toBeNull();
+ });
+});
diff --git a/server/gmail-draft-policy.ts b/server/gmail-draft-policy.ts
new file mode 100644
index 0000000000..c7cef44bcb
--- /dev/null
+++ b/server/gmail-draft-policy.ts
@@ -0,0 +1,17 @@
+import type { ConnectorCall } from "../shared/outbound.ts";
+
+// Security invariant: reserve before dispatch, including concurrent batches and uncertain upstream failures.
+export function reserveGmailDrafts(calls: readonly ConnectorCall[], reserved: Set<string>): string | null {
+ const keys: string[] = [];
+ for (const call of calls) {
+ if (call.slug !== "GMAIL_CREATE_EMAIL_DRAFT") continue;
+ const args = call.arguments as Record<string, unknown> | undefined;
+ const thread = args && typeof args.thread_id === "string" ? args.thread_id : "";
+ if (!thread) continue;
+ const key = JSON.stringify([args?.user_id ?? "me", thread]);
+ if (reserved.has(key) || keys.includes(key)) return "Draft creation for this Gmail thread was already attempted in this request. Read the existing drafts and update the intended draft by ID; do not create another, including after a timeout.";
+ keys.push(key);
+ }
+ for (const key of keys) reserved.add(key);
+ return null;
+}
diff --git a/server/index.ts b/server/index.ts
index 4e33e2d8ce..8104d276fa 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -1,5 +1,6 @@
// Import first: it reads a Cloud home's secrets off the launcher's pipe before any module can start a process.
import { BOOT_CLOUD_SECRETS } from "./cloud-secrets-boot.ts";
+import { reserveGmailDrafts } from "./gmail-draft-policy.ts";
import { AsyncLocalStorage } from "node:async_hooks";
import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
import { existsSync, realpathSync, rmSync } from "node:fs";
@@ -1656,6 +1657,7 @@ type InternalCapability = {
externalRuntime?: ExternalRuntimeGrant;
/** A Team Cloud member's own connected-apps bridge: their person key. */
connectorsFor?: string;
+ gmailDrafts?: Set<string>;
};
const MAX_ATTACHED_FILES_PER_TURN = 10;
const MAX_ROOM_POSTS_PER_TURN = 3;
@@ -1664,6 +1666,8 @@ const MAX_CREATED_BOT_INSTRUCTIONS = 4_000;
// Only an orphan backstop: normal terminal paths revoke a capability synchronously.
const INTERNAL_CAPABILITY_ORPHAN_MS = 30 * 24 * 60 * 60_000;
const internalCapabilities = new Map<string, InternalCapability>();
+const gmailDraftsByGeneration = new Map<string, Set<string>>();
+const gmailDraftsByNode = new Map<string, Set<string>>();
const activeInternalGenerationByThread = new Map<string, string>();
const internalGenerationByProviderTurn = new ProviderTurnGenerationRegistry();
const computerSelectionTurns = new Map<string, {
@@ -1741,6 +1745,7 @@ function mintInternalCapability(capability: Omit<InternalCapability, "orphanExpi
if (internalCapabilities.get(token)?.generation !== capability.generation) {
internalCapabilities.set(token, {
...capability,
+ ...(capability.kind === "connectors" ? { gmailDrafts: gmailDraftsForTurn(capability.threadId, capability.generation, capability.roomHandoffId) } : {}),
orphanExpiresAt: Date.now() + INTERNAL_CAPABILITY_ORPHAN_MS,
turnStartedAt: Date.now(),
});
@@ -1759,6 +1764,7 @@ function endForeignTurns(threadId: string, generation?: string): void {
}
function revokeInternalCapabilityGeneration(threadId: string, generation: string): void {
+ gmailDraftsByGeneration.delete(generation);
if (standInRoots.delete(generation)) coordinator.endTurn(generation, { ok: true, text: "" });
endForeignTurns(threadId, generation);
if (guestDrivenTurns.get(threadId) === generation) guestDrivenTurns.delete(threadId);
@@ -1953,7 +1959,34 @@ const directRequestOwners = new Map<string, {
generation: string; messageId?: string; generations: Set<string>; turnId: string | null; stopped?: boolean;
automation?: RoutineRunTrigger;
origin?: WorkOrigin; personLine?: true; kind?: TurnKind;
+ gmailDrafts?: Set<string>;
}>();
+
+function gmailDraftsForNode(id: string): Set<string> | undefined {
+ for (const cachedId of gmailDraftsByNode.keys()) {
+ const node = coordinator.node(cachedId);
+ if (!node || ENDED.has(node.status)) gmailDraftsByNode.delete(cachedId);
+ }
+ const node = coordinator.node(id);
+ if (!node) return undefined;
+ const cached = gmailDraftsByNode.get(id);
+ if (cached) return cached;
+ const owner = directRequestOwners.get(node.threadId);
+ const reserved = owner?.generations.has(id) && owner.gmailDrafts ? owner.gmailDrafts :
+ (node.parentId ? gmailDraftsForNode(node.parentId) : undefined) ?? new Set<string>();
+ gmailDraftsByNode.set(id, reserved);
+ return reserved;
+}
+
+function gmailDraftsForTurn(threadId: string, generation: string, handoffId?: string): Set<string> {
+ const cached = gmailDraftsByGeneration.get(generation);
+ if (cached) return cached;
+ const owner = directRequestOwners.get(threadId);
+ const reserved = owner?.generation === generation && owner.gmailDrafts ? owner.gmailDrafts :
+ gmailDraftsForNode(handoffId ?? generation) ?? new Set<string>();
+ gmailDraftsByGeneration.set(generation, reserved);
+ return reserved;
+}
type DirectTurnOutcome = HostTurnResult;
const directFollowupTurns = new ProviderTurnGenerationRegistry<DirectTurnOutcome>();
const directFollowupSettlers = new Map<string, { threadId: string; settle?: () => void }>();
@@ -7838,6 +7871,9 @@ async function beginTurn(
const requestOrigin = requestWorkOrigin({ trigger: opts?.automationSource, guest: guestConfined, handed: opts?.origin, continued,
line: !continuation && requestMessageId === userMessage.id ? userMessage : undefined });
directRequestOwners.set(threadId, { generation: dispatchClaimId, messageId: requestMessageId,
+ gmailDrafts: opts?.coordination ? gmailDraftsForNode(opts.coordination.id) :
+ continuation && previousRequest && !previousRequest.stopped && (!requestMessageId || previousRequest.messageId === requestMessageId)
+ ? previousRequest.gmailDrafts ?? new Set<string>() : new Set<string>(),
generations: requestGenerations, turnId: null, ...(opts?.automationSource ? { automation: opts.automationSource } : {}), origin: requestOrigin, ...(personLine || (continued && previousRequest?.personLine) ? { personLine: true as const } : {}),
kind: directTurnKind({ ...opts, peerAsk: opts?.peerAsk ?? userMessage.peerAsk }) });
const notesRefused = CLOUD_PERSONAL && cloudHomeLendingRefusal(cloudLendingTurn({ botId, threadId, generation: dispatchClaimId })) !== null;
@@ -9823,6 +9859,8 @@ async function runClaimedGroupMemberTurn(
return true;
}
const internalGeneration = beginInternalCapabilityGeneration(threadId);
+ if (orchestration?.roomHandoffId) gmailDraftsByGeneration.set(internalGeneration,
+ gmailDraftsForNode(orchestration.roomHandoffId) ?? new Set<string>());
if (operation) roomTurnStarted(internalGeneration, operation);
if (roomGuestConfined) guestDrivenTurns.set(threadId, internalGeneration);
// Only a personal Cloud's owner answering their own line in a room they alone wrote in is theirs.
@@ -14617,7 +14655,6 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
rule: verdict.rule,
});
}
- // Below Full access, a tools/call that sends something waits on a card or spends the daily allowance.
const rpc = body && typeof body === "object" && !Array.isArray(body)
? (body as { id?: unknown; method?: unknown; params?: unknown })
: null;
@@ -14650,13 +14687,9 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
}
const opaque = connectorCalls.some(call => call.slug === "COMPOSIO_PROXY_EXECUTE");
if (opaque && currentSender.connectorTools !== undefined) return refuseOutbound("OpenMausBot cannot verify this code against this bot's tool grants. Use a direct app tool.");
- // A room turn can run at a Chief's delegated level, which only the room handoff carries.
- const sendsFreely = () => roomTurnLevels.forRequest(internalCapability.threadId, internalCapability.botId,
- () => sourceApprovalMode(internalCapability.botId, internalCapability.threadId)) === "full";
- const fullAccess = outboundTool !== null && sendsFreely();
- const held: OutboundHoldAnswer = outboundTool && !fullAccess
+ const held: OutboundHoldAnswer = outboundTool
? await outboundHold.hold({
- bot: currentSender, threadId: internalCapability.threadId, tool: outboundTool, calls: outboundCalls, opaque, fullAccess,
+ bot: currentSender, threadId: internalCapability.threadId, tool: outboundTool, calls: outboundCalls, opaque,
active: () => internalCapabilityIsActive(internalCapability),
})
: { ok: true, approved: false };
@@ -14685,16 +14718,21 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
(call.kind === "unrecognized" && fresh.connectorTools !== undefined)) {
refuseDispatch("This bot's connected-app permissions changed. The call was not run.");
}
+ const reservedDrafts = internalCapability.gmailDrafts ??= new Set();
+ const nextDrafts = new Set(reservedDrafts);
+ const draftReservation = reserveGmailDrafts(connectorCalls, nextDrafts);
+ if (draftReservation) refuseDispatch(draftReservation);
if (outboundTool) {
try {
outboundHold.reserve({
bot: fresh, threadId: internalCapability.threadId, tool: outboundTool, calls: outboundCalls, opaque,
- fullAccess: fullAccess && sendsFreely(), approved: outboundApproved,
+ approved: outboundApproved,
});
} catch (error) {
refuseDispatch(error instanceof Error ? error.message : String(error));
}
}
+ for (const key of nextDrafts) reservedDrafts.add(key);
}, undefined, actor.access,
); } catch (error) {
if (dispatchRefusal) return refuseOutbound(dispatchRefusal);
diff --git a/server/outbound-hold.test.ts b/server/outbound-hold.test.ts
index 1346fca2cb..ea46b6ae3c 100644
--- a/server/outbound-hold.test.ts
+++ b/server/outbound-hold.test.ts
@@ -61,7 +61,7 @@ function setup(bot: HoldBot) {
activeGroupTurnForBot: () => null,
notify: (notification) => notified.push(notification),
};
- const input = { bot, threadId: "t1", tool: "GMAIL_SEND_EMAIL", calls, opaque: false, fullAccess: false };
+ const input = { bot, threadId: "t1", tool: "GMAIL_SEND_EMAIL", calls, opaque: false };
return { hold: createOutboundHold(deps), dataDir, appended, patches, activity, notified, outboundRequests, input };
}
@@ -147,12 +147,8 @@ describe("createOutboundHold", () => {
});
it("reserve refuses when the hold was not approved and the policy is ask", async () => {
- const { hold, dataDir, input } = setup(bot({ policy: "ask", dailyCap: 10 }));
- expect(() => hold.reserve({ ...input, fullAccess: false, approved: false })).toThrow(/outbound policy changed/);
-
- // Full access sends freely and logs it.
- expect(() => hold.reserve({ ...input, fullAccess: true, approved: false })).not.toThrow();
- await flushDecisionLog(dataDir);
- expect(readDecisions(dataDir, 10)).toMatchObject([{ decision: "auto-approved", source: "outbound", rule: "full-access" }]);
+ const { hold, input } = setup(bot({ policy: "ask", dailyCap: 10 }));
+ expect(() => hold.reserve({ ...input, approved: false })).toThrow(/outbound policy changed/);
+ expect(() => hold.reserve({ ...input, approved: true })).not.toThrow();
});
});
diff --git a/server/outbound-hold.ts b/server/outbound-hold.ts
index 29ee4d9df1..e0d24d9c7b 100644
--- a/server/outbound-hold.ts
+++ b/server/outbound-hold.ts
@@ -30,10 +30,8 @@ export interface OutboundHoldDeps {
export type OutboundHoldAnswer = { ok: true; approved: boolean } | { ok: false; text: string };
export interface OutboundHold {
- /** Below Full access, a send waits on the "Send on your behalf?" card or spends the daily allowance. */
- hold(input: { bot: OutboundHoldBot; threadId: string; tool: string; calls: ConnectorCall[]; opaque: boolean; fullAccess: boolean; active: () => boolean }): Promise<OutboundHoldAnswer>;
- /** At dispatch time: Full access logs auto-approved; "allow" reserves against the cap; otherwise the hold must have been approved. Throws the refusal text. */
- reserve(input: { bot: OutboundHoldBot; threadId: string; tool: string; calls: ConnectorCall[]; opaque: boolean; fullAccess: boolean; approved: boolean }): void;
+ hold(input: { bot: OutboundHoldBot; threadId: string; tool: string; calls: ConnectorCall[]; opaque: boolean; active: () => boolean }): Promise<OutboundHoldAnswer>;
+ reserve(input: { bot: OutboundHoldBot; threadId: string; tool: string; calls: ConnectorCall[]; opaque: boolean; approved: boolean }): void;
}
export function createOutboundHold(deps: OutboundHoldDeps): OutboundHold {
@@ -42,9 +40,8 @@ export function createOutboundHold(deps: OutboundHoldDeps): OutboundHold {
const { holdMs } = deps;
return {
- async hold({ bot: currentSender, threadId, tool: outboundTool, calls: outboundCalls, opaque, fullAccess, active }) {
+ async hold({ bot: currentSender, threadId, tool: outboundTool, calls: outboundCalls, opaque, active }) {
const refuseOutbound = (text: string): OutboundHoldAnswer => ({ ok: false, text });
- if (fullAccess) return { ok: true, approved: false };
const policy = currentSender.outbound ?? DEFAULT_OUTBOUND_POLICY;
const { app, calls, summary } = outboundCard(outboundCalls);
const capNote = (count: number) =>
@@ -113,25 +110,20 @@ export function createOutboundHold(deps: OutboundHoldDeps): OutboundHold {
}
return { ok: true, approved: false };
},
- reserve({ bot: fresh, threadId, tool: outboundTool, calls: outboundCalls, opaque, fullAccess, approved: outboundApproved }) {
+ reserve({ bot: fresh, threadId, tool: outboundTool, calls: outboundCalls, opaque, approved: outboundApproved }) {
const refuseDispatch: (text: string) => never = (text) => {
throw new Error(text);
};
- if (fullAccess) {
+ const policy = fresh.outbound ?? DEFAULT_OUTBOUND_POLICY;
+ if (policy.policy === "allow" && !opaque) {
+ let reserved: number | null;
+ try { reserved = outboundCounts.reserve(fresh.id, outboundCalls.length, policy.dailyCap); }
+ catch { refuseDispatch("The daily allowance could not be saved. Nothing was sent."); }
+ if (reserved === null) refuseDispatch("This bot has reached its daily outbound limit. Nothing was sent.");
appendDecision(DATA_DIR, { threadId, botId: fresh.id, botName: fresh.name,
- tool: outboundTool, decision: "auto-approved", source: "outbound", rule: "full-access" });
- } else {
- const policy = fresh.outbound ?? DEFAULT_OUTBOUND_POLICY;
- if (policy.policy === "allow" && !opaque) {
- let reserved: number | null;
- try { reserved = outboundCounts.reserve(fresh.id, outboundCalls.length, policy.dailyCap); }
- catch { refuseDispatch("The daily allowance could not be saved. Nothing was sent."); }
- if (reserved === null) refuseDispatch("This bot has reached its daily outbound limit. Nothing was sent.");
- appendDecision(DATA_DIR, { threadId, botId: fresh.id, botName: fresh.name,
- tool: outboundTool, decision: "auto-approved", source: "outbound", rule: `daily-allowance:${reserved}/${policy.dailyCap}` });
- } else if (!outboundApproved) {
- refuseDispatch("The outbound policy changed. Ask for approval again before sending.");
- }
+ tool: outboundTool, decision: "auto-approved", source: "outbound", rule: `daily-allowance:${reserved}/${policy.dailyCap}` });
+ } else if (!outboundApproved) {
+ refuseDispatch("The outbound policy changed. Ask for approval again before sending.");
}
},
};
diff --git a/server/system-prompt.ts b/server/system-prompt.ts
index 6db57cedc8..050b09b5e3 100644
--- a/server/system-prompt.ts
+++ b/server/system-prompt.ts
@@ -177,7 +177,7 @@ export const COMPOSIO_PROMPT =
/** The app tools a bot with these apps can call by name, on every engine. */
const APP_TOOLS_PROMPT: Record<string, { label: string; tools: string }> = {
- gmail: { label: "Gmail", tools: "gmail.search_emails, gmail.read_email and gmail.read_email_thread" },
+ gmail: { label: "Gmail", tools: "gmail.search_emails, gmail.read_email, gmail.read_email_thread, gmail.create_draft, gmail.list_drafts, gmail.read_draft and gmail.update_draft. Draft requests never authorize sending. Revisions update the existing draft ID; creation always makes another draft. If an action fails or accidentally sends, report that fact accurately; a later draft does not undo a send" },
googlecalendar: { label: "Google Calendar", tools: "googlecalendar.list_events and googlecalendar.list_calendars" },
};
diff --git a/server/trust-controls.e2e.test.ts b/server/trust-controls.e2e.test.ts
index c3127c3066..9686bb612d 100644
--- a/server/trust-controls.e2e.test.ts
+++ b/server/trust-controls.e2e.test.ts
@@ -15,6 +15,10 @@ let broker: Server;
let admin: string;
let member: string;
let fullBot: any;
+let draftBot: any;
+let draftHelper: any;
+let outboundPolicyBot: any;
+const gmailDrafts = new Map<string, Record<string, unknown>>();
let brokerOrigin = "";
const relayed: unknown[] = [];
const evidence: unknown[] = [];
@@ -31,7 +35,6 @@ const api = async (method: string, path: string, body?: unknown, token = admin)
evidence.push({ method, path, result });
return result;
};
-// Below Full access, so sends reach the outbound card and the daily allowance.
const bot = async (name: string) => {
const created = await api("POST", "/api/bots", { name });
expect(created.status, JSON.stringify(created.body)).toBe(201);
@@ -75,6 +78,17 @@ beforeAll(async () => {
}
if (req.url === "/mcp") {
relayed.push(body);
+ const tools = body.params?.arguments?.tools ?? [{ tool_slug: body.params?.name, arguments: body.params?.arguments }];
+ if (tools.every((tool: any) => ["GMAIL_CREATE_EMAIL_DRAFT", "GMAIL_UPDATE_DRAFT"].includes(tool.tool_slug))) {
+ const results = tools.map((tool: any) => {
+ const args = tool.arguments;
+ const id = tool.tool_slug === "GMAIL_CREATE_EMAIL_DRAFT" ? `draft-${gmailDrafts.size + 1}` : args.draft_id;
+ if (tool.tool_slug === "GMAIL_UPDATE_DRAFT" && !gmailDrafts.has(id)) return { tool_slug: tool.tool_slug, response: { successful: false, error: "Draft not found" } };
+ gmailDrafts.set(id, args);
+ return { tool_slug: tool.tool_slug, response: { successful: true, data: { id, message: { threadId: args.thread_id, body: args.body } } } };
+ });
+ return res.end(JSON.stringify({ jsonrpc: "2.0", id: body.id, result: { content: [{ type: "text", text: JSON.stringify({ successful: true, data: { results } }) }] } }));
+ }
if (blockRelay) {
relayEntered = true;
await new Promise<void>(resolve => { blockRelay = resolve; });
@@ -91,13 +105,25 @@ beforeAll(async () => {
const created = await fetch(fixture.info.url + "/api/bots", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ name: "Existing Full grant" }) });
expect(created.status).toBe(201);
fullBot = (await created.json() as any).bot;
+ const draftCreated = await fetch(fixture.info.url + "/api/bots", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ name: "Full Gmail draft fixture" }) });
+ expect(draftCreated.status).toBe(201);
+ draftBot = (await draftCreated.json() as any).bot;
+ const helperCreated = await fetch(fixture.info.url + "/api/bots", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ name: "Full Gmail delegate fixture" }) });
+ expect(helperCreated.status).toBe(201);
+ draftHelper = (await helperCreated.json() as any).bot;
+ const policyCreated = await fetch(fixture.info.url + "/api/bots", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ name: "Full outbound policy fixture" }) });
+ expect(policyCreated.status).toBe(201);
+ outboundPolicyBot = (await policyCreated.json() as any).bot;
await waitForExit(fixture.child, { signal: "SIGTERM" });
const botsFile = join(fixture.info.dataDir, "bots.json");
const bots = JSON.parse(readFileSync(botsFile, "utf8"));
const saved = bots.find((row: any) => row.id === fullBot.id);
- saved.approvalMode = "full";
- saved.autoApprove = false;
- for (const task of saved.tasks) { task.approvalMode = "full"; task.autoApprove = false; }
+ for (const full of [saved, ...[draftBot, draftHelper, outboundPolicyBot].map(bot => bots.find((row: any) => row.id === bot.id))]) {
+ full.approvalMode = "full";
+ full.autoApprove = false;
+ for (const task of full.tasks) { task.approvalMode = "full"; task.autoApprove = false; }
+ }
+ bots.find((row: any) => row.id === outboundPolicyBot.id).outbound = { policy: "ask", dailyCap: 100 };
writeFileSync(botsFile, JSON.stringify(bots));
const configFile = join(fixture.info.dataDir, "config.json");
const config = JSON.parse(readFileSync(configFile, "utf8"));
@@ -105,6 +131,8 @@ beforeAll(async () => {
config.composio = { apiKey: "ak_isolated_fixture", userId: "fixture-user", sessionId: "fixture-session" };
config.instances.activityFixture = { ...config.instances.claude, displayName: "Exact task activity fixture",
environment: { FAKE_CLAUDE_MODE: "hang", FAKE_CLAUDE_RELEASE: join(fixture.info.dataDir, "activity-release") } };
+ config.instances.gmailFixture = { ...config.instances.claude, displayName: "Gmail continuation fixture",
+ environment: { FAKE_CLAUDE_ROOM_PLAN: join(fixture.info.dataDir, "gmail-plan.json") } };
writeFileSync(configFile, JSON.stringify(config));
const sessions = new SessionRegistry({ file: join(fixture.info.dataDir, "sessions.json"),
emailScopes: email => email === "[email protected]" ? ["admin", "client"] : ["client"] });
@@ -152,21 +180,200 @@ it("keeps activity, shared memory and policy changes admin-only", async () => {
expect((await api("PATCH", `/api/bots/${b.id}`, { fallback: [{ instanceId: "claude", model: " " }] })).status).toBe(400);
});
-it("sends in Full without a card, and still refuses an app outside the bot's scope", async () => {
+it("honors outbound approval and the daily allowance at Full access, and still refuses apps outside scope", async () => {
const b = fullBot;
const fleet = await api("GET", "/api/bots");
expect(fleet.body.bots.find((row: any) => row.id === b.id).approvalMode).toBe("full");
const token = await mint(b.id, b.threadId);
const before = relayed.length;
- expect((await relay(token, "GMAIL_SEND_EMAIL", { to: "[email protected]" })).body.result.isError).not.toBe(true);
- expect((await relay(token, "COMPOSIO_REMOTE_WORKBENCH", { code_to_execute: "print(1)" })).body.result.isError).not.toBe(true);
+ const denied = relay(token, "GMAIL_SEND_EMAIL", { to: "[email protected]" });
+ const deniedCard = await pending(b.threadId);
+ expect(relayed).toHaveLength(before);
+ await api("POST", `/api/threads/${b.threadId}/respond`, { requestId: deniedCard.card.requestId, behavior: "deny" });
+ expect((await denied).body.result.isError).toBe(true);
+ const allowed = relay(token, "GMAIL_SEND_EMAIL", { to: "[email protected]" });
+ const allowedCard = await pending(b.threadId);
+ expect(relayed).toHaveLength(before);
+ await api("POST", `/api/threads/${b.threadId}/respond`, { requestId: allowedCard.card.requestId, behavior: "allow" });
+ expect((await allowed).body.result.isError).not.toBe(true);
+ expect(relayed).toHaveLength(before + 1);
+ await api("PATCH", `/api/bots/${b.id}`, { outbound: { policy: "allow", dailyCap: 1 } });
+ const cardCount = (await cards(b.threadId)).filter(row => row.card?.outboundRequest).length;
+ expect((await relay(token, "SLACK_SEND_MESSAGE", { channel: "fixture", text: "Allowed once" })).body.result.isError).not.toBe(true);
+ expect((await api("GET", `/api/bots/${b.id}/outbound`)).body.today).toBe(1);
+ expect((await relay(token, "GMAIL_SEND_EMAIL", { to: "[email protected]" })).body.result.isError).toBe(true);
+ expect((await cards(b.threadId)).filter(row => row.card?.outboundRequest)).toHaveLength(cardCount);
+ const opaque = relay(token, "COMPOSIO_REMOTE_WORKBENCH", { code_to_execute: "print(1)" });
+ const opaqueCard = await pending(b.threadId);
+ await api("POST", `/api/threads/${b.threadId}/respond`, { requestId: opaqueCard.card.requestId, behavior: "deny" });
+ expect((await opaque).body.result.isError).toBe(true);
expect(relayed).toHaveLength(before + 2);
- expect((await cards(b.threadId)).some((row: any) => row.card?.outboundRequest)).toBe(false);
await api("PATCH", `/api/bots/${b.id}`, { connectorScopes: { apps: { gmail: "read" } } });
expect((await relay(token, "GMAIL_SEND_EMAIL")).body.result.isError).toBe(true);
expect(relayed).toHaveLength(before + 2);
});
+it("honors Ask every time at Full access before the first send for any prompt language", async () => {
+ const b = outboundPolicyBot;
+ expect((await api("GET", "/api/bots")).body.bots.find((bot: any) => bot.id === b.id).outbound.policy).toBe("ask");
+ expect((await api("PATCH", `/api/bots/${b.id}`, { outbound: { policy: "invalid", dailyCap: 100 } })).status).toBe(400);
+ expect((await api("PATCH", `/api/bots/${b.id}`, { outbound: { policy: "allow", dailyCap: 100 } }, member)).status).toBe(403);
+ const before = relayed.length;
+ for (const text of ["Responde a Sam, no lo envíes", "Sam को जवाब लिखो, भेजना मत", "Réponds à Sam sans envoyer", "Samに返信を書いて、送信しないで", "Send the email now"]) {
+ expect((await api("POST", `/api/bots/${b.id}/messages`, { text, threadId: b.threadId })).status).toBe(202);
+ await expect.poll(async () => (await api("GET", "/api/bots")).body.bots.find((bot: any) => bot.id === b.id).busy, { timeout: 10_000 }).toBe(false);
+ const token = await mint(b.id, b.threadId);
+ const send = relay(token, "GMAIL_REPLY_TO_THREAD", { thread_id: "ask-policy", body: "Never sent without consent" });
+ const card = await pending(b.threadId);
+ expect(relayed).toHaveLength(before);
+ await api("POST", `/api/threads/${b.threadId}/respond`, { requestId: card.card.requestId, behavior: "deny" });
+ expect((await send).body.result.isError).toBe(true);
+ }
+ const token = await mint(b.id, b.threadId);
+ for (const name of ["GMAIL_SEND_EMAIL", "GMAIL_SEND_DRAFT", "GMAIL_FORWARD_MESSAGE", "SLACK_SEND_MESSAGE", "COMPOSIO_REMOTE_WORKBENCH"]) {
+ const send = relay(token, name);
+ const card = await pending(b.threadId);
+ expect(relayed).toHaveLength(before);
+ await api("POST", `/api/threads/${b.threadId}/respond`, { requestId: card.card.requestId, behavior: "deny" });
+ expect((await send).body.result.isError).toBe(true);
+ }
+ const allowed = relay(token, "GMAIL_SEND_EMAIL", { to: "[email protected]" });
+ const card = await pending(b.threadId);
+ await api("POST", `/api/threads/${b.threadId}/respond`, { requestId: card.card.requestId, behavior: "allow" });
+ expect((await allowed).body.result.isError).not.toBe(true);
+ expect(relayed).toHaveLength(before + 1);
+ const repeated = relay(token, "GMAIL_SEND_EMAIL", { to: "[email protected]" });
+ const repeatedCard = await pending(b.threadId);
+ expect(relayed).toHaveLength(before + 1);
+ await api("POST", `/api/threads/${b.threadId}/respond`, { requestId: repeatedCard.card.requestId, behavior: "deny" });
+ expect((await repeated).body.result.isError).toBe(true);
+});
+
+it("honors the daily allowance for explicit draft-and-send requests without classifying their wording", async () => {
+ const b = outboundPolicyBot;
+ expect((await api("PATCH", `/api/bots/${b.id}`, { outbound: { policy: "allow", dailyCap: 100 } })).status).toBe(200);
+ const before = relayed.length;
+ const cardCount = (await cards(b.threadId)).filter(row => row.card?.outboundRequest).length;
+ for (const text of ["Draft a reply to Sam and send it", "Edit the draft to fix the typo and send it", "Write a draft and then send it to the team"]) {
+ expect((await api("POST", `/api/bots/${b.id}/messages`, { text, threadId: b.threadId })).status).toBe(202);
+ await expect.poll(async () => (await api("GET", "/api/bots")).body.bots.find((bot: any) => bot.id === b.id).busy, { timeout: 10_000 }).toBe(false);
+ const token = await mint(b.id, b.threadId);
+ expect((await relay(token, "GMAIL_SEND_DRAFT", { draft_id: "fixture-draft" })).body.result.isError).not.toBe(true);
+ }
+ expect(relayed).toHaveLength(before + 3);
+ expect((await cards(b.threadId)).filter(row => row.card?.outboundRequest)).toHaveLength(cardCount);
+ expect((await api("PATCH", `/api/bots/${b.id}`, { outbound: { policy: "ask", dailyCap: 100 } })).status).toBe(200);
+});
+
+it("holds sends under Ask every time at Full access and revises the same Gmail draft without another creation", async () => {
+ const b = draftBot;
+ const begin = async (text: string) => {
+ const previous = (await cards(b.threadId)).filter(row => row.role === "bot" && row.kind === "text").length;
+ expect((await api("POST", `/api/bots/${b.id}/messages`, { text, threadId: b.threadId })).status).toBe(202);
+ await expect.poll(async () => (await cards(b.threadId)).filter(row => row.role === "bot" && row.kind === "text").length, { timeout: 10_000 }).toBeGreaterThan(previous);
+ await expect.poll(async () => (await api("GET", "/api/bots")).body.bots.find((row: any) => row.id === b.id).busy, { timeout: 10_000 }).toBe(false);
+ return mint(b.id, b.threadId);
+ };
+ const token = await begin("Create exactly one reply draft for MEGA. If a draft already exists, update it instead of creating another. Do not send it.");
+ const before = relayed.length;
+ const deny = async (request: Promise<any>) => {
+ const card = await pending(b.threadId);
+ expect(relayed).toHaveLength(before);
+ await api("POST", `/api/threads/${b.threadId}/respond`, { requestId: card.card.requestId, behavior: "deny" });
+ expect((await request).body.result.isError).toBe(true);
+ };
+ for (const name of ["GMAIL_SEND_EMAIL", "GMAIL_SEND_DRAFT", "GMAIL_REPLY_TO_THREAD", "GMAIL_FORWARD_MESSAGE", "COMPOSIO_REMOTE_WORKBENCH"]) {
+ await deny(relay(token, name));
+ }
+ const draft = { thread_id: "mega-thread", recipient_email: "[email protected]", subject: "Re: MEGA", body: "Original reply" };
+ const batch = (tools: any[]) => relay(token, "COMPOSIO_MULTI_EXECUTE_TOOL", { tools });
+ await deny(batch([{ tool_slug: "GMAIL_CREATE_EMAIL_DRAFT", arguments: draft }, { tool_slug: "GMAIL_SEND_EMAIL", arguments: draft }]));
+ expect(relayed).toHaveLength(before);
+ expect((await relay(token, "GMAIL_CREATE_EMAIL_DRAFT", draft)).body.result.isError).not.toBe(true);
+ expect((await relay(token, "GMAIL_CREATE_EMAIL_DRAFT", draft)).body.result.isError).toBe(true);
+ expect(gmailDrafts.size).toBe(1);
+ const draftId = [...gmailDrafts.keys()][0];
+ const revision = await begin("Update the existing MEGA reply draft. Do not create another. Do not send it.");
+ expect((await relay(revision, "GMAIL_UPDATE_DRAFT", { ...draft, draft_id: draftId, body: "Revised reply" })).body.result.isError).not.toBe(true);
+ expect(gmailDrafts.size).toBe(1);
+ expect(gmailDrafts.get(draftId)).toMatchObject({ body: "Revised reply", thread_id: "mega-thread" });
+ const reached = relayed.slice(before).flatMap((frame: any) => frame.params?.arguments?.tools ?? [{ tool_slug: frame.params?.name }]);
+ expect(reached.map((tool: any) => tool.tool_slug)).toEqual(["GMAIL_CREATE_EMAIL_DRAFT", "GMAIL_UPDATE_DRAFT"]);
+ await api("PATCH", `/api/bots/${b.id}`, { outbound: { policy: "allow", dailyCap: 100 } });
+ const cardCount = (await cards(b.threadId)).filter(row => row.card?.outboundRequest).length;
+ expect((await relay(revision, "GMAIL_SEND_DRAFT", { draft_id: draftId })).body.result.isError).not.toBe(true);
+ expect(relayed).toHaveLength(before + 3);
+ expect((await cards(b.threadId)).filter(row => row.card?.outboundRequest)).toHaveLength(cardCount);
+});
+
+it("retains Gmail draft limits through delegated work and the requester's resumed turn", async () => {
+ const b = draftBot;
+ const helper = draftHelper;
+ for (const bot of [b, helper]) {
+ expect((await api("PATCH", `/api/bots/${bot.id}`, { modelSelection: { instanceId: "gmailFixture", model: "claude-sonnet-5" }, threadId: bot.threadId, peers: [b.id, helper.id].filter(id => id !== bot.id), acknowledgePeerScope: true, outbound: { policy: "ask", dailyCap: 100 } })).status).toBe(200);
+ }
+ const draft = { thread_id: "continued-thread", recipient_email: "[email protected]", subject: "Re: Continuation", body: "Draft response" };
+ const write = { server: "composio", tool: "GMAIL_CREATE_EMAIL_DRAFT", arguments: draft };
+ const send = { server: "composio", tool: "GMAIL_REPLY_TO_THREAD", arguments: { thread_id: draft.thread_id }, expectError: true };
+ writeFileSync(join(fixture.info.dataDir, "gmail-plan.json"), JSON.stringify({
+ [b.id]: {
+ timeoutMs: 60_000,
+ steps: [write, { arguments: { bot_ids: [helper.id], message: "Check the proposed response", thread: "new" } }],
+ reply: "Waiting for a check", resumeSteps: [{ ...write, expectError: true }, send], resumeReply: "Draft remains unsent",
+ },
+ [helper.id]: { timeoutMs: 60_000, steps: [send], reply: "Checked the response" },
+ }));
+ const before = relayed.length;
+ expect((await api("POST", `/api/bots/${b.id}/messages`, { text: "Draft a reply. Do not send it. Ask your teammate to check it.", threadId: b.threadId })).status).toBe(202);
+ let delegatedThread = "";
+ await expect.poll(async () => {
+ const fresh = (await api("GET", "/api/bots")).body.bots.find((bot: any) => bot.id === helper.id);
+ delegatedThread = fresh.tasks.find((task: any) => task.busy)?.threadId ?? "";
+ return Boolean(delegatedThread);
+ }, { timeout: 15_000 }).toBe(true);
+ for (const threadId of [delegatedThread, b.threadId]) {
+ const card = await pending(threadId);
+ const tools = relayed.slice(before).filter((frame: any) => frame.method === "tools/call")
+ .flatMap((frame: any) => frame.params?.arguments?.tools ?? [{ tool_slug: frame.params?.name }]);
+ expect(tools.map((tool: any) => tool.tool_slug)).toEqual(["GMAIL_CREATE_EMAIL_DRAFT"]);
+ await api("POST", `/api/threads/${threadId}/respond`, { requestId: card.card.requestId, behavior: "deny" });
+ }
+ await expect.poll(async () => (await cards(b.threadId)).some(row => row.text === "Draft remains unsent"), { timeout: 15_000 }).toBe(true);
+ const planEvidence = readFileSync(join(fixture.info.dataDir, "gmail-plan.json.evidence.jsonl"), "utf8");
+ evidence.push({ gmailContinuation: planEvidence });
+ expect(planEvidence).toContain("already attempted");
+ expect(gmailDrafts.size).toBe(2);
+}, 90_000);
+
+it("honors Ask every time on Full-access delegated and resumed turns without relying on wording or a draft write", async () => {
+ const b = outboundPolicyBot;
+ const helper = draftHelper;
+ for (const bot of [b, helper]) {
+ expect((await api("PATCH", `/api/bots/${bot.id}`, { modelSelection: { instanceId: "gmailFixture", model: "claude-sonnet-5" }, threadId: bot.threadId, peers: [b.id, helper.id].filter(id => id !== bot.id), acknowledgePeerScope: true, outbound: { policy: "ask", dailyCap: 100 } })).status).toBe(200);
+ }
+ const send = { server: "composio", tool: "GMAIL_REPLY_TO_THREAD", arguments: { thread_id: "ask-delegation" }, expectError: true };
+ writeFileSync(join(fixture.info.dataDir, "gmail-plan.json"), JSON.stringify({
+ [b.id]: { timeoutMs: 60_000, steps: [{ arguments: { bot_ids: [helper.id], message: "Check the response", thread: "new" } }],
+ reply: "Waiting for review", resumeSteps: [send], resumeReply: "Outbound policy retained" },
+ [helper.id]: { timeoutMs: 60_000, steps: [send], reply: "Reviewed" },
+ }));
+ const before = relayed.length;
+ expect((await api("POST", `/api/bots/${b.id}/messages`, { text: "Responde a Sam, no lo envíes", threadId: b.threadId })).status).toBe(202);
+ let delegatedThread = "";
+ await expect.poll(async () => {
+ const fresh = (await api("GET", "/api/bots")).body.bots.find((bot: any) => bot.id === helper.id);
+ delegatedThread = fresh.tasks.find((task: any) => task.busy)?.threadId ?? "";
+ return Boolean(delegatedThread);
+ }, { timeout: 15_000 }).toBe(true);
+ for (const threadId of [delegatedThread, b.threadId]) {
+ const card = await pending(threadId);
+ expect(relayed.slice(before).filter((frame: any) => frame.method === "tools/call")).toEqual([]);
+ await api("POST", `/api/threads/${threadId}/respond`, { requestId: card.card.requestId, behavior: "deny" });
+ }
+ await expect.poll(async () => (await cards(b.threadId)).some(row => row.text === "Outbound policy retained"), { timeout: 15_000 }).toBe(true);
+ evidence.push({ outboundPolicyDelegation: readFileSync(join(fixture.info.dataDir, "gmail-plan.json.evidence.jsonl"), "utf8") });
+}, 90_000);
+
it("shows each outbound batch recipient and amount with explicit preview truncation before consent", async () => {
const b = await bot("Batch consent preview");
const token = await mint(b.id, b.threadId);
@@ -210,6 +417,73 @@ it.each(["scope", "turn"])("rechecks %s revocation after project-session metadat
expect(relayed).toHaveLength(before);
});
+it("does not consume a Gmail draft reservation when the fresh scope check refuses dispatch", async () => {
+ const b = await bot("Draft scope race");
+ const token = await mint(b.id, b.threadId);
+ const before = relayed.length;
+ sessionEntered = false;
+ blockSession = () => {};
+ const args = { thread_id: "scope-race", body: "Only a draft" };
+ const held = relay(token, "GMAIL_CREATE_EMAIL_DRAFT", args);
+ try {
+ await expect.poll(() => sessionEntered, { timeout: 5_000 }).toBe(true);
+ await api("PATCH", `/api/bots/${b.id}`, { connectorScopes: { apps: { gmail: "read" } } });
+ } finally {
+ blockSession?.();
+ blockSession = undefined;
+ }
+ expect((await held).body.result.isError).toBe(true);
+ expect(relayed).toHaveLength(before);
+ await api("PATCH", `/api/bots/${b.id}`, { connectorScopes: { apps: { gmail: "write" } } });
+ expect((await relay(token, "GMAIL_CREATE_EMAIL_DRAFT", args)).body.result.isError).not.toBe(true);
+ expect(relayed).toHaveLength(before + 1);
+});
+
+it("honors Ask every time enabled while a Full-access send is waiting for dispatch", async () => {
+ const b = fullBot;
+ await api("PATCH", `/api/bots/${b.id}`, { outbound: { policy: "allow", dailyCap: 100 }, connectorScopes: { apps: { gmail: "write" } } });
+ const token = await mint(b.id, b.threadId);
+ const before = relayed.length;
+ sessionEntered = false;
+ blockSession = () => {};
+ const send = relay(token, "GMAIL_SEND_EMAIL", { to: "[email protected]" });
+ try {
+ await expect.poll(() => sessionEntered, { timeout: 5_000 }).toBe(true);
+ expect((await api("PATCH", `/api/bots/${b.id}`, { outbound: { policy: "ask", dailyCap: 100 } })).status).toBe(200);
+ await expect.poll(() => JSON.parse(readFileSync(join(fixture.info.dataDir, "bots.json"), "utf8"))
+ .find((bot: any) => bot.id === b.id).outbound?.policy).toBe("ask");
+ } finally {
+ blockSession?.();
+ blockSession = undefined;
+ }
+ expect((await send).body.result.isError).toBe(true);
+ expect(relayed).toHaveLength(before);
+ const nextSend = relay(token, "GMAIL_SEND_EMAIL", { to: "[email protected]" });
+ const card = await pending(b.threadId);
+ expect(relayed).toHaveLength(before);
+ await api("POST", `/api/threads/${b.threadId}/respond`, { requestId: card.card.requestId, behavior: "deny" });
+ expect((await nextSend).body.result.isError).toBe(true);
+ expect((await api("PATCH", `/api/bots/${b.id}`, { outbound: { policy: "allow", dailyCap: 100 } })).status).toBe(200);
+ expect((await relay(token, "GMAIL_SEND_EMAIL", { to: "[email protected]" })).body.result.isError).not.toBe(true);
+ expect(relayed).toHaveLength(before + 1);
+});
+
+it("does not consume the outbound allowance when a duplicate draft refuses a mixed batch", async () => {
+ const b = fullBot;
+ const token = await mint(b.id, b.threadId);
+ const draft = { thread_id: "reservation-cap", body: "Review this" };
+ const before = relayed.length;
+ const count = (await api("GET", `/api/bots/${b.id}/outbound`)).body.today;
+ expect((await relay(token, "GMAIL_CREATE_EMAIL_DRAFT", draft)).body.result.isError).not.toBe(true);
+ const duplicate = await relay(token, "COMPOSIO_MULTI_EXECUTE_TOOL", { tools: [
+ { tool_slug: "GMAIL_CREATE_EMAIL_DRAFT", arguments: draft },
+ { tool_slug: "GMAIL_SEND_EMAIL", arguments: { to: "[email protected]" } },
+ ] });
+ expect(duplicate.body.result.isError).toBe(true);
+ expect((await api("GET", `/api/bots/${b.id}/outbound`)).body.today).toBe(count);
+ expect(relayed).toHaveLength(before + 1);
+});
+
it("reserves a daily slot before provider await, so simultaneous calls cannot overspend", async () => {
const b = await bot("Concurrent cap");
await api("PATCH", `/api/bots/${b.id}`, { outbound: { policy: "allow", dailyCap: 1 } });
diff --git a/shared/outbound.ts b/shared/outbound.ts
index d9fec95a53..66140dde30 100644
--- a/shared/outbound.ts
+++ b/shared/outbound.ts
@@ -1,8 +1,3 @@
-// Outbound actions: calls that reach a person outside the app or move money.
-// Below Full access they get their own confirmation, or spend an optional daily
-// allowance per bot; at Full access they run. A read-and-draft routine run never
-// reaches them: the relay refuses every send there. Shared by the harness (which
-// enforces it) and the app.
import { isConnectedAppsServer } from "./own-apps.ts";
export type OutboundPolicy = {
diff --git a/src/locales/en.json b/src/locales/en.json
index ecff4f23b4..7686f3f943 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -3072,7 +3072,7 @@
"permissions.approval.helpHanded": "Default for new threads, routines and work handed to it. Full access also applies at once to every existing thread. Use Refresh permissions on a thread to apply the current level to that conversation.",
"permissions.approval.applyFull": "Apply Full access to all threads",
"permissions.outbound.title": "Sending on your behalf",
- "permissions.outbound.help": "Emails, messages, posts, invites, and payments through connected apps. Reading and drafting never count. Full access sends without asking.",
+ "permissions.outbound.help": "Emails, messages, posts, invites, and payments through connected apps. Reading and drafting never count. These sending rules also apply at Full access.",
"permissions.outbound.ask": "Ask every time",
"permissions.outbound.askHint": "Every send waits for your tap.",
"permissions.outbound.allow": "Allow a daily amount",
diff --git a/src/locales/it.json b/src/locales/it.json
index 6eef48bd78..f336bdf68f 100644
--- a/src/locales/it.json
+++ b/src/locales/it.json
@@ -2636,7 +2636,6 @@
"permissions.approval.helpHanded": "Predefinito per le nuove conversazioni, le routine e il lavoro che gli viene affidato. Accesso completo si applica subito anche a ogni conversazione già presente. Usa «Aggiorna permessi» su una conversazione per applicarle il livello attuale.",
"permissions.approval.applyFull": "Applica Accesso completo a tutte le conversazioni",
"permissions.outbound.title": "Invii per tuo conto",
- "permissions.outbound.help": "Email, messaggi, post, inviti e pagamenti tramite le app collegate. La lettura e le bozze non contano mai. Accesso completo invia senza chiedere.",
"permissions.outbound.ask": "Chiedi ogni volta",
"permissions.outbound.askHint": "Ogni invio aspetta un tuo clic.",
"permissions.outbound.allow": "Consenti una quota giornaliera",
diff --git a/src/locales/ja.json b/src/locales/ja.json
index a51c146fd6..3c6fe3bc2d 100644
--- a/src/locales/ja.json
+++ b/src/locales/ja.json
@@ -2749,7 +2749,6 @@
"permissions.approval.helpHanded": "新しいスレッド、ルーティン、このボットに任された作業の既定値です。フルアクセスは、既存のすべてのスレッドにも即座に適用されます。現在のレベルを特定の会話に適用するには、そのスレッドで「権限を更新」を使用してください。",
"permissions.approval.applyFull": "すべてのスレッドにフルアクセスを適用",
"permissions.outbound.title": "代理での送信",
- "permissions.outbound.help": "接続したアプリを通じた、メール、メッセージ、投稿、招待、支払いが対象です。閲覧と下書きは含まれません。フルアクセスでは、確認なしで送信されます。",
"permissions.outbound.ask": "毎回確認する",
"permissions.outbound.askHint": "送信のたびに、あなたの操作を待ちます。",
"permissions.outbound.allow": "1日の上限まで許可",
diff --git a/src/locales/ko.json b/src/locales/ko.json
index f807037ba5..14a9767c40 100644
--- a/src/locales/ko.json
+++ b/src/locales/ko.json
@@ -2901,7 +2901,6 @@
"permissions.approval.helpHanded": "새 스레드, 루틴, 이 봇에게 맡긴 작업의 기본값이에요. 전체 접근은 기존 스레드 모두에도 바로 적용돼요. 스레드에서 권한 새로고침을 쓰면 그 대화에 현재 수준이 적용돼요.",
"permissions.approval.applyFull": "모든 스레드에 전체 접근 적용",
"permissions.outbound.title": "대신 보내기",
- "permissions.outbound.help": "연결된 앱을 통한 이메일, 메시지, 게시물, 초대, 결제예요. 읽기와 초안 작성은 포함되지 않아요. 전체 접근에서는 묻지 않고 보내요.",
"permissions.outbound.ask": "매번 묻기",
"permissions.outbound.askHint": "보낼 때마다 내가 누르기를 기다려요.",
"permissions.outbound.allow": "하루 허용량 정하기",
diff --git a/src/locales/pl.json b/src/locales/pl.json
index 8acdceec86..e99002faec 100644
--- a/src/locales/pl.json
+++ b/src/locales/pl.json
@@ -2693,7 +2693,6 @@
"permissions.approval.helpHanded": "Domyślne dla nowych wątków, rutyn i przekazanej mu pracy. Pełny dostęp obowiązuje też od razu we wszystkich istniejących wątkach. Użyj opcji Odśwież uprawnienia w wątku, aby zastosować bieżący poziom do tej rozmowy.",
"permissions.approval.applyFull": "Zastosuj pełny dostęp do wszystkich wątków",
"permissions.outbound.title": "Wysyłanie w twoim imieniu",
- "permissions.outbound.help": "E-maile, wiadomości, posty, zaproszenia i płatności przez połączone aplikacje. Czytanie i tworzenie szkiców nigdy się nie liczą. Pełny dostęp wysyła bez pytania.",
"permissions.outbound.ask": "Pytaj za każdym razem",
"permissions.outbound.askHint": "Każde wysłanie czeka na twoje kliknięcie.",
"permissions.outbound.allow": "Zezwól na dzienny limit",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 78a56dd373..7290786b5c 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -2634,7 +2634,6 @@
"permissions.approval.helpHanded": "Padrão para novas conversas, rotinas e trabalhos repassados a ele. O acesso total também se aplica imediatamente a todas as conversas existentes. Use Atualizar permissões em uma conversa para aplicar o nível atual a ela.",
"permissions.approval.applyFull": "Aplicar acesso total a todas as conversas",
"permissions.outbound.title": "Enviar em seu nome",
- "permissions.outbound.help": "E-mails, mensagens, publicações, convites e pagamentos por aplicativos conectados. Ler e redigir nunca contam. O acesso total envia sem perguntar.",
"permissions.outbound.ask": "Perguntar sempre",
"permissions.outbound.askHint": "Cada envio espera seu toque.",
"permissions.outbound.allow": "Permitir uma quantidade diária",
diff --git a/src/locales/ru.json b/src/locales/ru.json
index 20992f1e13..36f21208ea 100644
--- a/src/locales/ru.json
+++ b/src/locales/ru.json
@@ -2730,7 +2730,6 @@
"permissions.approval.helpHanded": "По умолчанию для новых тредов, сценариев и переданной боту работы. Полный доступ также сразу применяется ко всем существующим тредам. Чтобы применить текущий уровень к конкретному диалогу, используйте «Обновить права» в этом треде.",
"permissions.approval.applyFull": "Применить полный доступ ко всем тредам",
"permissions.outbound.title": "Отправка от вашего имени",
- "permissions.outbound.help": "Письма, сообщения, публикации, приглашения и платежи через подключённые приложения. Чтение и создание черновиков не учитываются. Полный доступ отправляет без запроса.",
"permissions.outbound.ask": "Спрашивать каждый раз",
"permissions.outbound.askHint": "Каждая отправка ждёт вашего подтверждения.",
"permissions.outbound.allow": "Разрешить дневной лимит",
diff --git a/src/locales/zh.json b/src/locales/zh.json
index 96446b5363..27f7877297 100644
--- a/src/locales/zh.json
+++ b/src/locales/zh.json
@@ -3026,7 +3026,6 @@
"permissions.approval.helpHanded": "新建对话、例行任务以及转交给它的工作的默认值。完全访问权限也会立即应用到所有现有对话。如需将当前层级应用到某段对话,请在对话中使用「刷新权限」。",
"permissions.approval.applyFull": "对所有对话应用完全访问权限",
"permissions.outbound.title": "代你发送内容",
- "permissions.outbound.help": "通过已连接的应用发送邮件、消息、帖子、邀请和付款。读取和起草不计入。完全访问权限会直接发送,无需询问。",
"permissions.outbound.ask": "每次都询问",
"permissions.outbound.askHint": "每次发送都需要你确认。",
"permissions.outbound.allow": "允许每日额度",