Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(agents): owner approval for tool calls in turns someone else prompted (#7173)

Wolf Mermelstein28a784035d5b
diff --git a/.sqlx/query-0978b8f4414bcc135fc867075255ef541a9820a9902258f903edf20a064f8a6c.json b/.sqlx/query-0978b8f4414bcc135fc867075255ef541a9820a9902258f903edf20a064f8a6c.json
new file mode 100644
index 0000000000..28db1874be
--- /dev/null
+++ b/.sqlx/query-0978b8f4414bcc135fc867075255ef541a9820a9902258f903edf20a064f8a6c.json
@@ -0,0 +1,98 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH resolved AS (\n UPDATE agent_session_tool_approval\n SET status = $2, resolved_by = $3, resolved_at = now(), remembered = $5\n WHERE id = $1 AND status = 'pending'\n RETURNING *\n )\n SELECT\n resolved.id AS \"id!\",\n resolved.agent_session_id AS \"agent_session_id!\",\n resolved.turn_action_id AS \"turn_action_id!\",\n resolved.request_id AS \"request_id!\",\n resolved.owner_id AS \"owner_id!: MacroUserIdStr<'static>\",\n resolved.requested_by AS \"requested_by: MacroUserIdStr<'static>\",\n resolved.server_slug AS \"server_slug!\",\n resolved.server_name AS \"server_name!\",\n resolved.tool_name AS \"tool_name!\",\n resolved.arguments AS \"arguments!\",\n resolved.status AS \"status!\",\n resolved.resolved_by AS \"resolved_by: MacroUserIdStr<'static>\",\n resolved.remembered AS \"remembered!\"\n FROM resolved, pg_notify($4, resolved.id::text)\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id!",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "agent_session_id!",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "turn_action_id!",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "request_id!",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 4,
+ "name": "owner_id!: MacroUserIdStr<'static>",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "requested_by: MacroUserIdStr<'static>",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "server_slug!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 7,
+ "name": "server_name!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "tool_name!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 9,
+ "name": "arguments!",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 10,
+ "name": "status!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 11,
+ "name": "resolved_by: MacroUserIdStr<'static>",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 12,
+ "name": "remembered!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Text",
+ "Bool"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ false
+ ]
+ },
+ "hash": "0978b8f4414bcc135fc867075255ef541a9820a9902258f903edf20a064f8a6c"
+}
diff --git a/.sqlx/query-19fbb93823857ff16a4269cce376a2a90b88ed4c60fc2e7ee82e6af2002d1120.json b/.sqlx/query-19fbb93823857ff16a4269cce376a2a90b88ed4c60fc2e7ee82e6af2002d1120.json
new file mode 100644
index 0000000000..f68e9791e9
--- /dev/null
+++ b/.sqlx/query-19fbb93823857ff16a4269cce376a2a90b88ed4c60fc2e7ee82e6af2002d1120.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO agent_session_tool_approval (\n id, agent_session_id, turn_action_id, request_id, owner_id, requested_by,\n server_slug, server_name, tool_name, arguments, status\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Uuid",
+ "Jsonb",
+ "Text",
+ "Text",
+ "Text",
+ "Text",
+ "Text",
+ "Jsonb",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "19fbb93823857ff16a4269cce376a2a90b88ed4c60fc2e7ee82e6af2002d1120"
+}
diff --git a/.sqlx/query-3c474ee081e2218363be0fe80f4a5c0032d77d1cf8f3c98d5c8c9d3b3b11f967.json b/.sqlx/query-3c474ee081e2218363be0fe80f4a5c0032d77d1cf8f3c98d5c8c9d3b3b11f967.json
new file mode 100644
index 0000000000..7d3b303765
--- /dev/null
+++ b/.sqlx/query-3c474ee081e2218363be0fe80f4a5c0032d77d1cf8f3c98d5c8c9d3b3b11f967.json
@@ -0,0 +1,94 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n id, agent_session_id, turn_action_id, request_id,\n owner_id AS \"owner_id: MacroUserIdStr<'static>\",\n requested_by AS \"requested_by: MacroUserIdStr<'static>\",\n server_slug, server_name, tool_name, arguments, status,\n resolved_by AS \"resolved_by: MacroUserIdStr<'static>\",\n remembered\n FROM agent_session_tool_approval\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "agent_session_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "turn_action_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "request_id",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 4,
+ "name": "owner_id: MacroUserIdStr<'static>",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "requested_by: MacroUserIdStr<'static>",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "server_slug",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 7,
+ "name": "server_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "tool_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 9,
+ "name": "arguments",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 10,
+ "name": "status",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 11,
+ "name": "resolved_by: MacroUserIdStr<'static>",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 12,
+ "name": "remembered",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ false
+ ]
+ },
+ "hash": "3c474ee081e2218363be0fe80f4a5c0032d77d1cf8f3c98d5c8c9d3b3b11f967"
+}
diff --git a/.sqlx/query-4112ad1071655877a81668e95e5654d64114ca7decbf236749595bda453c62f2.json b/.sqlx/query-4112ad1071655877a81668e95e5654d64114ca7decbf236749595bda453c62f2.json
new file mode 100644
index 0000000000..1bf73c8651
--- /dev/null
+++ b/.sqlx/query-4112ad1071655877a81668e95e5654d64114ca7decbf236749595bda453c62f2.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT turn_action_id, turn_prompter AS \"turn_prompter: MacroUserIdStr<'static>\"\n FROM agent_session\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "turn_action_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "turn_prompter: MacroUserIdStr<'static>",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true,
+ true
+ ]
+ },
+ "hash": "4112ad1071655877a81668e95e5654d64114ca7decbf236749595bda453c62f2"
+}
diff --git a/.sqlx/query-5401f3b2719a9a654c053921e9f89812c2b21a38dac9127c546d4dc296d2a188.json b/.sqlx/query-5401f3b2719a9a654c053921e9f89812c2b21a38dac9127c546d4dc296d2a188.json
new file mode 100644
index 0000000000..c880096a76
--- /dev/null
+++ b/.sqlx/query-5401f3b2719a9a654c053921e9f89812c2b21a38dac9127c546d4dc296d2a188.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id FROM agent_session_tool_approval\n WHERE agent_session_id = $1 AND request_id = $2 AND status = 'pending'\n ORDER BY created_at DESC\n LIMIT 1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Jsonb"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "5401f3b2719a9a654c053921e9f89812c2b21a38dac9127c546d4dc296d2a188"
+}
diff --git a/.sqlx/query-7a07dfc37ee03d0cf8bd287e34351eed3f0baf6bb6a5c2a8f1eb960a11e527c7.json b/.sqlx/query-7a07dfc37ee03d0cf8bd287e34351eed3f0baf6bb6a5c2a8f1eb960a11e527c7.json
new file mode 100644
index 0000000000..0bb2fefc86
--- /dev/null
+++ b/.sqlx/query-7a07dfc37ee03d0cf8bd287e34351eed3f0baf6bb6a5c2a8f1eb960a11e527c7.json
@@ -0,0 +1,25 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id FROM agent_session_tool_approval\n WHERE agent_session_id = $1 AND requested_by = $2 AND server_slug = $3\n AND ($4::text IS NULL OR tool_name = $4) AND status = 'pending'\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "7a07dfc37ee03d0cf8bd287e34351eed3f0baf6bb6a5c2a8f1eb960a11e527c7"
+}
diff --git a/.sqlx/query-8f653ae1ee4210ae28103cb83980495b239df2ff6d2c3f5a4c3335ec1e9d54ab.json b/.sqlx/query-8f653ae1ee4210ae28103cb83980495b239df2ff6d2c3f5a4c3335ec1e9d54ab.json
new file mode 100644
index 0000000000..b128cebc43
--- /dev/null
+++ b/.sqlx/query-8f653ae1ee4210ae28103cb83980495b239df2ff6d2c3f5a4c3335ec1e9d54ab.json
@@ -0,0 +1,25 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT EXISTS (\n SELECT 1 FROM agent_session_tool_standing_approval\n WHERE agent_session_id = $1 AND user_id = $2 AND server_slug = $3\n AND (tool_name IS NULL OR tool_name = $4)\n ) AS \"standing!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "standing!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "8f653ae1ee4210ae28103cb83980495b239df2ff6d2c3f5a4c3335ec1e9d54ab"
+}
diff --git a/.sqlx/query-92c9ba77cddbada79f0093f80cd578c0c4df182e35cff640a58bfd7067cd1575.json b/.sqlx/query-92c9ba77cddbada79f0093f80cd578c0c4df182e35cff640a58bfd7067cd1575.json
new file mode 100644
index 0000000000..5c18a4e942
--- /dev/null
+++ b/.sqlx/query-92c9ba77cddbada79f0093f80cd578c0c4df182e35cff640a58bfd7067cd1575.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id FROM agent_session_tool_approval\n WHERE agent_session_id = $1 AND status = 'pending'\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "92c9ba77cddbada79f0093f80cd578c0c4df182e35cff640a58bfd7067cd1575"
+}
diff --git a/.sqlx/query-cbaaff046a2092289ffd1c9bed577905aa3cdaf212f867b827f6ef4a0de215f2.json b/.sqlx/query-cbaaff046a2092289ffd1c9bed577905aa3cdaf212f867b827f6ef4a0de215f2.json
new file mode 100644
index 0000000000..8a98afa9ea
--- /dev/null
+++ b/.sqlx/query-cbaaff046a2092289ffd1c9bed577905aa3cdaf212f867b827f6ef4a0de215f2.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE agent_session SET turn_action_id = $2, turn_prompter = $3 WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "cbaaff046a2092289ffd1c9bed577905aa3cdaf212f867b827f6ef4a0de215f2"
+}
diff --git a/.sqlx/query-ec910250f6dd6b38b2b7cd83aff36e74c42c99c244ce7ec8f4dbcef1cd3c0276.json b/.sqlx/query-ec910250f6dd6b38b2b7cd83aff36e74c42c99c244ce7ec8f4dbcef1cd3c0276.json
new file mode 100644
index 0000000000..250bc93b74
--- /dev/null
+++ b/.sqlx/query-ec910250f6dd6b38b2b7cd83aff36e74c42c99c244ce7ec8f4dbcef1cd3c0276.json
@@ -0,0 +1,18 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO agent_session_tool_standing_approval (\n agent_session_id, user_id, server_slug, tool_name, granted_by\n )\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (agent_session_id, user_id, server_slug, (COALESCE(tool_name, '')))\n DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "ec910250f6dd6b38b2b7cd83aff36e74c42c99c244ce7ec8f4dbcef1cd3c0276"
+}
diff --git a/Cargo.lock b/Cargo.lock
index c5964aa0eb..8165d853fa 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -274,6 +274,7 @@ dependencies = [
"macro_auth",
"macro_db_client",
"macro_user_id",
+ "macro_uuid",
"mcp_client",
"model_owner",
"pipedream_mcp",
diff --git a/apps/web/src/features/block-agent/agent-session-provider.tsx b/apps/web/src/features/block-agent/agent-session-provider.tsx
index 95cd7f4c36..744b793c37 100644
--- a/apps/web/src/features/block-agent/agent-session-provider.tsx
+++ b/apps/web/src/features/block-agent/agent-session-provider.tsx
@@ -6,6 +6,8 @@ import { isCursorBotId } from '@core/constant/cursorAgent';
import { useUserId } from '@core/context/user';
import { idToDisplayName } from '@core/user/util';
import { useAgentSessionExternalUrlQuery } from '@queries/agent-session/session';
+import { useAgentSessionSubscription } from '@queries/agent-session/subscription';
+import { answerAgentSessionToolApproval } from '@queries/agent-session/tool-approvals';
import type {
FoldedMessage,
TurnState,
@@ -27,6 +29,7 @@ import { resolveSessionId } from './context/resolve-session-id';
import { createSendNext } from './context/send-next';
import { createSteer } from './context/steer';
import { createInteractionController } from './primitives/create-interaction-controller';
+import { createToolApprovalController } from './primitives/create-tool-approval-controller';
import type { QuoteInsert } from './ui';
export function AgentSessionProvider(
@@ -113,6 +116,16 @@ export function AgentSessionProvider(
issue: live.issue,
onFailure: toast.failure,
});
+ useAgentSessionSubscription(sessionId);
+ const toolApprovals = createToolApprovalController({
+ sessionId,
+ pending: () => live.metadata()?.pendingInteractions ?? [],
+ ownerId: () => live.session()?.ownerId,
+ userId,
+ canEdit: () => live.session()?.canEdit,
+ onFailure: toast.failure,
+ answer: answerAgentSessionToolApproval,
+ });
// The transcript's "Reply to this" chip hands selected text to the
// composer through here. A plain variable, not a signal: it is only read
@@ -161,6 +174,7 @@ export function AgentSessionProvider(
sendNext,
steer,
interactions,
+ toolApprovals,
queue,
quoteSelection,
registerQuoteInsert,
diff --git a/apps/web/src/features/block-agent/component/AgentComposer.test.tsx b/apps/web/src/features/block-agent/component/AgentComposer.test.tsx
index 6337192c16..3e645bbf46 100644
--- a/apps/web/src/features/block-agent/component/AgentComposer.test.tsx
+++ b/apps/web/src/features/block-agent/component/AgentComposer.test.tsx
@@ -43,6 +43,7 @@ vi.mock('../context/AgentSessionContext', () => ({
displayName: (id: string) => id,
userId: () => 'viewer',
interactions: { pending: () => [], canAnswer: () => false },
+ toolApprovals: { pending: () => [] },
issue: mocks.issue,
selectModel: mocks.selectModel,
loadFailed: () => false,
diff --git a/apps/web/src/features/block-agent/component/AgentComposer.tsx b/apps/web/src/features/block-agent/component/AgentComposer.tsx
index c45d6975c2..82b7e06f25 100644
--- a/apps/web/src/features/block-agent/component/AgentComposer.tsx
+++ b/apps/web/src/features/block-agent/component/AgentComposer.tsx
@@ -43,6 +43,7 @@ import type { AgentModelSelectorProps } from '../ui/AgentModelSelector';
import { AgentModelMenuItem } from './AgentModelMenuItem';
import { PermissionRequest } from './PermissionRequest';
import { promptActionOf } from './prompt-action';
+import { ToolApprovalRequest } from './ToolApprovalRequest';
export function AgentComposer(props: {
/**
@@ -61,6 +62,7 @@ export function AgentComposer(props: {
displayName,
userId,
interactions,
+ toolApprovals,
issue,
loadFailed,
messages,
@@ -269,6 +271,13 @@ export function AgentComposer(props: {
</div>
)}
</For>
+ <For each={toolApprovals.pending()}>
+ {(approval) => (
+ <div class="mb-2 min-w-0">
+ <ToolApprovalRequest request={approval} />
+ </div>
+ )}
+ </For>
<Input
initialInput={initialInput}
draft={persistedDraft.draft()}
diff --git a/apps/web/src/features/block-agent/component/AgentMessage.tsx b/apps/web/src/features/block-agent/component/AgentMessage.tsx
index 2d7bb74ca5..d9638cbf53 100644
--- a/apps/web/src/features/block-agent/component/AgentMessage.tsx
+++ b/apps/web/src/features/block-agent/component/AgentMessage.tsx
@@ -39,6 +39,7 @@ import { PermissionPart } from './parts/PermissionPart';
import { PlanPart } from './parts/PlanPart';
import { type ToolUsePart, toolUsedAfter } from './parts/shared';
import { TextPart } from './parts/TextPart';
+import { ToolApprovalPart } from './parts/ToolApprovalPart';
import { ToolCallPart } from './parts/ToolCallPart';
/**
@@ -97,6 +98,9 @@ function AgentMessagePart(props: {
<Match when={props.part.kind === 'permission' && props.part}>
{(part) => <PermissionPart part={part()} />}
</Match>
+ <Match when={props.part.kind === 'tool_approval' && props.part}>
+ {(part) => <ToolApprovalPart part={part()} />}
+ </Match>
<Match when={props.part.kind === 'plan' && props.part}>
{(part) => <PlanPart part={part()} />}
</Match>
@@ -183,6 +187,7 @@ function showsWorkingLine(message: FoldedMessage): boolean {
{ kind: 'text' },
{ kind: 'thought' },
{ kind: 'permission' },
+ { kind: 'tool_approval' },
{ kind: 'elicitation' },
() => false
)
diff --git a/apps/web/src/features/block-agent/component/ToolApprovalRequest.tsx b/apps/web/src/features/block-agent/component/ToolApprovalRequest.tsx
new file mode 100644
index 0000000000..82e4c9094f
--- /dev/null
+++ b/apps/web/src/features/block-agent/component/ToolApprovalRequest.tsx
@@ -0,0 +1,48 @@
+import type { ToolApprovalAnswerDto } from '@service-agent-harness/generated/schemas';
+import { useOptionalAgentSession } from '../context/AgentSessionContext';
+import type { HeldToolApproval } from '../primitives/create-tool-approval-controller';
+import {
+ describeStandingApproval,
+ describeToolCall,
+ possessive,
+} from '../state/tool-approval-wording';
+import { ToolApprovalCard } from '../ui/ToolApprovalCard';
+
+/** A held tool call above the composer, said as what the agent wants to do. */
+export function ToolApprovalRequest(props: { request: HeldToolApproval }) {
+ const session = useOptionalAgentSession();
+ const name = (userId: string | null | undefined) =>
+ userId ? (session?.displayName(userId) ?? userId) : undefined;
+ const approvals = () => session?.toolApprovals;
+ const owner = () => name(session?.session()?.ownerId) ?? 'the session owner';
+ const server = () => ({
+ slug: props.request.serverSlug,
+ name: props.request.serverName,
+ });
+ const whose = () =>
+ approvals()?.canApprove() ? 'your' : possessive(owner());
+ const action = () =>
+ describeToolCall(server(), props.request.toolName, whose());
+ // Only a person can be remembered, not a bot acting on nobody's behalf.
+ const standing = () =>
+ props.request.requestedBy
+ ? describeStandingApproval(server(), props.request.toolName, whose())
+ : undefined;
+ const answer = (value: ToolApprovalAnswerDto) =>
+ void approvals()?.answer(props.request.approvalId, value);
+ return (
+ <ToolApprovalCard
+ action={action()}
+ standing={standing()}
+ requester={name(props.request.requestedBy)}
+ owner={owner()}
+ canApprove={approvals()?.canApprove() === true}
+ canCancel={approvals()?.canCancel() === true}
+ disabled={approvals()?.answering(props.request.approvalId)}
+ onApprove={() => answer('approve')}
+ onApproveAlways={() => answer('approve_and_remember')}
+ onDeny={() => answer('deny')}
+ onCancel={() => answer('cancel')}
+ />
+ );
+}
diff --git a/apps/web/src/features/block-agent/component/parts/ToolApprovalPart.tsx b/apps/web/src/features/block-agent/component/parts/ToolApprovalPart.tsx
new file mode 100644
index 0000000000..167b1c82b4
--- /dev/null
+++ b/apps/web/src/features/block-agent/component/parts/ToolApprovalPart.tsx
@@ -0,0 +1,63 @@
+/**
+ * A tool call held for the session owner, once answered. Pending ones live
+ * above the composer so there is only one place to answer them.
+ */
+
+import type { MessagePart } from '@service-agent-fold/generated/types';
+import { Show } from 'solid-js';
+import { match } from 'ts-pattern';
+import { useOptionalAgentSession } from '../../context/AgentSessionContext';
+import {
+ describeToolCall,
+ possessive,
+} from '../../state/tool-approval-wording';
+import { ToolCard } from '../../ui';
+
+export function ToolApprovalPart(props: {
+ part: Extract<MessagePart, { kind: 'tool_approval' }>;
+}) {
+ const session = useOptionalAgentSession();
+ const by = () => {
+ const resolvedBy = props.part.resolvedBy;
+ return resolvedBy
+ ? (session?.displayName(resolvedBy) ?? resolvedBy)
+ : undefined;
+ };
+ const owner = () => {
+ const ownerId = session?.session()?.ownerId;
+ if (!ownerId) return "the owner's";
+ return ownerId === session?.userId()
+ ? 'your'
+ : possessive(session?.displayName(ownerId) ?? ownerId);
+ };
+ // "Read your email", from "read your email".
+ const title = () => {
+ const action = describeToolCall(
+ { slug: props.part.serverSlug, name: props.part.serverName },
+ props.part.toolName,
+ owner()
+ );
+ return action.charAt(0).toUpperCase() + action.slice(1);
+ };
+ const outcome = () =>
+ match(props.part.status)
+ .with('pending', () => 'Waiting for approval')
+ .with('approved', () => {
+ const approved = props.part.remembered ? 'Always allowed' : 'Approved';
+ return by() ? `${approved} by ${by()}` : approved;
+ })
+ .with('denied', () => (by() ? `Declined by ${by()}` : 'Declined'))
+ .with('cancelled', () => (by() ? `Cancelled by ${by()}` : 'Cancelled'))
+ .with('expired', () => 'Not approved in time')
+ .exhaustive();
+
+ return (
+ <Show when={props.part.status !== 'pending'}>
+ <ToolCard
+ title={title()}
+ trailing={<span class="text-ink">{outcome()}</span>}
+ status="completed"
+ />
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx b/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
index a261d5f2c8..d59e5a3433 100644
--- a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
+++ b/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
@@ -12,6 +12,7 @@ import type {
SessionBot,
} from '@service-agent-harness/generated/schemas';
import { type Accessor, createContext, useContext } from 'solid-js';
+import type { ToolApprovalController } from '../primitives/create-tool-approval-controller';
import type { EffortSelection } from '../state/session-config';
import type { QuoteInsert } from '../ui';
import type { QueueController } from './create-queue-controller';
@@ -84,6 +85,11 @@ export type AgentSessionState = {
steer: (actionId: string) => void;
/** The live requests, and the action that answers each one. */
interactions: InteractionController;
+ /**
+ * Tool calls held until the session's owner approves them, made in turns
+ * somebody else prompted.
+ */
+ toolApprovals: ToolApprovalController;
/**
* The session's server-side action queue: prompts sent mid-turn wait
* there and dispatch one per turn end. The server is the only truth —
diff --git a/apps/web/src/features/block-agent/context/interaction.ts b/apps/web/src/features/block-agent/context/interaction.ts
index 65400e83fa..267c3c55dc 100644
--- a/apps/web/src/features/block-agent/context/interaction.ts
+++ b/apps/web/src/features/block-agent/context/interaction.ts
@@ -7,8 +7,14 @@ import type {
} from '@service-agent-harness/generated/schemas';
import type { Accessor } from 'solid-js';
-export type InteractionIdentity = Pick<
+/** Requests the agent itself asked, answered through agent actions. */
+export type AgentInteraction = Exclude<
PendingInteraction,
+ { kind: 'tool_approval' }
+>;
+
+export type InteractionIdentity = Pick<
+ AgentInteraction,
'kind' | 'requestId' | 'turn'
>;
diff --git a/apps/web/src/features/block-agent/primitives/create-interaction-controller.ts b/apps/web/src/features/block-agent/primitives/create-interaction-controller.ts
index a27e46da05..c33c9904c3 100644
--- a/apps/web/src/features/block-agent/primitives/create-interaction-controller.ts
+++ b/apps/web/src/features/block-agent/primitives/create-interaction-controller.ts
@@ -31,6 +31,7 @@ export function createInteractionController(
.pending()
.some(
(request) =>
+ request.kind !== 'tool_approval' &&
request.kind === response.kind &&
request.turn === response.turn &&
request.requestId === response.requestId
diff --git a/apps/web/src/features/block-agent/primitives/create-tool-approval-controller.test.ts b/apps/web/src/features/block-agent/primitives/create-tool-approval-controller.test.ts
new file mode 100644
index 0000000000..f3dd47a0d2
--- /dev/null
+++ b/apps/web/src/features/block-agent/primitives/create-tool-approval-controller.test.ts
@@ -0,0 +1,120 @@
+/** @vitest-environment jsdom */
+import type { PendingInteraction } from '@service-agent-fold/generated/types';
+import { err, ok } from 'neverthrow';
+import { createRoot, createSignal } from 'solid-js';
+import { describe, expect, it, vi } from 'vitest';
+import {
+ createToolApprovalController,
+ type ToolApprovalSource,
+} from './create-tool-approval-controller';
+
+const held = {
+ kind: 'tool_approval',
+ approvalId: 'approval-1',
+ turn: 0,
+ serverSlug: 'macro',
+ serverName: 'Macro',
+ toolName: 'ListEmails',
+ requestedBy: 'macro|[email protected]',
+} satisfies PendingInteraction;
+
+const permission = {
+ kind: 'permission',
+ requestId: 7,
+ turn: 0,
+ toolCall: 'tool',
+ options: [],
+} satisfies PendingInteraction;
+
+type Answer = ToolApprovalSource['answer'];
+
+function setup(viewer: string, canEdit = true) {
+ const [pending, setPending] = createSignal<PendingInteraction[]>([
+ permission,
+ held,
+ ]);
+ const answer = vi.fn<Answer>(() =>
+ Promise.resolve(ok({ status: 'approved' as const }))
+ );
+ const onFailure = vi.fn();
+ const { controller, dispose } = createRoot((dispose) => ({
+ controller: createToolApprovalController({
+ sessionId: () => 'session-a',
+ pending,
+ ownerId: () => 'macro|[email protected]',
+ userId: () => viewer,
+ canEdit: () => canEdit,
+ onFailure,
+ answer,
+ }),
+ dispose,
+ }));
+ return { controller, dispose, answer, onFailure, setPending };
+}
+
+describe('createToolApprovalController', () => {
+ it('lists only held tool calls', () => {
+ const { controller, dispose } = setup('macro|[email protected]');
+ expect(controller.pending()).toEqual([held]);
+ dispose();
+ });
+
+ it('lets the owner approve and decline', async () => {
+ const { controller, dispose, answer } = setup('macro|[email protected]');
+ expect(controller.canApprove()).toBe(true);
+ await expect(controller.answer('approval-1', 'approve')).resolves.toBe(
+ true
+ );
+ expect(answer).toHaveBeenCalledWith('session-a', 'approval-1', 'approve');
+ dispose();
+ });
+
+ it('lets an editor only cancel', async () => {
+ const { controller, dispose, answer } = setup('macro|[email protected]');
+ expect(controller.canApprove()).toBe(false);
+ expect(controller.canCancel()).toBe(true);
+ await expect(controller.answer('approval-1', 'approve')).resolves.toBe(
+ false
+ );
+ expect(answer).not.toHaveBeenCalled();
+ await expect(controller.answer('approval-1', 'cancel')).resolves.toBe(true);
+ expect(answer).toHaveBeenCalledWith('session-a', 'approval-1', 'cancel');
+ dispose();
+ });
+
+ it('lets a viewer do nothing', async () => {
+ const { controller, dispose, answer } = setup(
+ false
+ );
+ await expect(controller.answer('approval-1', 'cancel')).resolves.toBe(
+ false
+ );
+ expect(answer).not.toHaveBeenCalled();
+ dispose();
+ });
+
+ it('does not answer a call that is no longer held', async () => {
+ const { controller, dispose, answer, setPending } = setup(
+ );
+ setPending([]);
+ await expect(controller.answer('approval-1', 'deny')).resolves.toBe(false);
+ expect(answer).not.toHaveBeenCalled();
+ dispose();
+ });
+
+ it('says so when somebody answered first', async () => {
+ const { controller, dispose, answer, onFailure } = setup(
+ );
+ answer.mockResolvedValueOnce(
+ err([{ code: 'CONFLICT' as const, message: 'already resolved' }])
+ );
+ await expect(controller.answer('approval-1', 'deny')).resolves.toBe(false);
+ expect(onFailure).toHaveBeenCalledWith(
+ 'That tool call was already answered'
+ );
+ dispose();
+ });
+});
diff --git a/apps/web/src/features/block-agent/primitives/create-tool-approval-controller.ts b/apps/web/src/features/block-agent/primitives/create-tool-approval-controller.ts
new file mode 100644
index 0000000000..fd01e54076
--- /dev/null
+++ b/apps/web/src/features/block-agent/primitives/create-tool-approval-controller.ts
@@ -0,0 +1,111 @@
+import type { FetchWithTokenErrorCode } from '@core/util/fetchWithToken';
+import type { ResultError } from '@core/util/result';
+import type { PendingInteraction } from '@service-agent-fold/generated/types';
+import type {
+ AnswerToolApprovalResponse,
+ ToolApprovalAnswerDto,
+} from '@service-agent-harness/generated/schemas';
+import type { Result } from 'neverthrow';
+import type { Accessor } from 'solid-js';
+import { createStore } from 'solid-js/store';
+
+/** A tool call the egress proxy holds until the session owner approves it. */
+export type HeldToolApproval = Extract<
+ PendingInteraction,
+ { kind: 'tool_approval' }
+>;
+
+export type ToolApprovalSource = {
+ sessionId: Accessor<string | undefined>;
+ pending: Accessor<readonly PendingInteraction[]>;
+ /** The session's owner: the only one who may approve or decline. */
+ ownerId: Accessor<string | undefined>;
+ /** The viewer. */
+ userId: Accessor<string | undefined>;
+ /** Edit access, which is enough to cancel. */
+ canEdit: Accessor<boolean | undefined>;
+ onFailure: (message: string) => void;
+ /** Sends an answer to the harness. */
+ answer: (
+ sessionId: string,
+ approvalId: string,
+ answer: ToolApprovalAnswerDto
+ ) => Promise<
+ Result<AnswerToolApprovalResponse, ResultError<FetchWithTokenErrorCode>[]>
+ >;
+};
+
+export type ToolApprovalController = {
+ pending: Accessor<readonly HeldToolApproval[]>;
+ /** The viewer owns the session, so approves or declines. */
+ canApprove: Accessor<boolean>;
+ /** The viewer may give up waiting on the owner. */
+ canCancel: Accessor<boolean>;
+ answering: (approvalId: string) => boolean;
+ answer: (
+ approvalId: string,
+ answer: ToolApprovalAnswerDto
+ ) => Promise<boolean>;
+};
+
+/**
+ * Answers held tool calls. Unlike a permission, the answer is not an agent
+ * action: the call is held at the egress proxy, not by the agent, so it goes
+ * to the proxy's own endpoint and the log reports the outcome.
+ */
+export function createToolApprovalController(
+ source: ToolApprovalSource
+): ToolApprovalController {
+ const [answering, setAnswering] = createStore<
+ Record<string, true | undefined>
+ >({});
+ const pending = () =>
+ source
+ .pending()
+ .filter(
+ (request): request is HeldToolApproval =>
+ request.kind === 'tool_approval'
+ );
+ const canApprove = () => {
+ const owner = source.ownerId();
+ return owner !== undefined && owner === source.userId();
+ };
+ const canCancel = () => source.canEdit() === true;
+
+ const answer = async (
+ approvalId: string,
+ answer: ToolApprovalAnswerDto
+ ): Promise<boolean> => {
+ const sessionId = source.sessionId();
+ const allowed = answer === 'cancel' ? canCancel() : canApprove();
+ const live = pending().some((request) => request.approvalId === approvalId);
+ if (!sessionId || !allowed || !live || answering[approvalId]) return false;
+
+ setAnswering(approvalId, true);
+ try {
+ const result = await source.answer(sessionId, approvalId, answer);
+ if (result.isErr()) {
+ source.onFailure(
+ result.error.some((error) => error.code === 'CONFLICT')
+ ? 'That tool call was already answered'
+ : "Couldn't send your answer"
+ );
+ return false;
+ }
+ return true;
+ } catch {
+ source.onFailure("Couldn't send your answer");
+ return false;
+ } finally {
+ setAnswering(approvalId, undefined);
+ }
+ };
+
+ return {
+ pending,
+ canApprove,
+ canCancel,
+ answering: (approvalId) => answering[approvalId] === true,
+ answer,
+ };
+}
diff --git a/apps/web/src/features/block-agent/state/tool-approval-wording.test.ts b/apps/web/src/features/block-agent/state/tool-approval-wording.test.ts
new file mode 100644
index 0000000000..0bf4a16728
--- /dev/null
+++ b/apps/web/src/features/block-agent/state/tool-approval-wording.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from 'vitest';
+import {
+ describeStandingApproval,
+ describeToolCall,
+ possessive,
+} from './tool-approval-wording';
+
+const macro = { slug: 'macro', name: 'Macro' };
+
+describe('describeToolCall', () => {
+ it("says what one of Macro's tools does with the owner's data", () => {
+ expect(describeToolCall(macro, 'GetThread', 'your')).toBe(
+ 'read your email'
+ );
+ expect(describeToolCall(macro, 'CreateCalendarEvent', "Alice's")).toBe(
+ "add an event to Alice's calendar"
+ );
+ });
+
+ it('falls back to the tool name in words', () => {
+ expect(describeToolCall(macro, 'NewerThanThisBuild', 'your')).toBe(
+ 'use your Macro workspace (newer than this build)'
+ );
+ expect(
+ describeToolCall(
+ { slug: 'linear', name: 'Linear' },
+ 'linear-create-issue',
+ 'your'
+ )
+ ).toBe('use your Linear account (linear create issue)');
+ });
+});
+
+describe('describeStandingApproval', () => {
+ it("covers one of Macro's tools, or a whole connected app", () => {
+ expect(describeStandingApproval(macro, 'GetThread', 'your')).toBe(
+ 'read your email'
+ );
+ expect(
+ describeStandingApproval(
+ { slug: 'linear', name: 'Linear' },
+ 'linear-create-issue',
+ 'your'
+ )
+ ).toBe('use your Linear account');
+ });
+});
+
+describe('possessive', () => {
+ it('adds an apostrophe s, or just an apostrophe after an s', () => {
+ expect(possessive('Alice Seed')).toBe("Alice Seed's");
+ expect(possessive('James')).toBe("James'");
+ });
+});
diff --git a/apps/web/src/features/block-agent/state/tool-approval-wording.ts b/apps/web/src/features/block-agent/state/tool-approval-wording.ts
new file mode 100644
index 0000000000..75239d131e
--- /dev/null
+++ b/apps/web/src/features/block-agent/state/tool-approval-wording.ts
@@ -0,0 +1,175 @@
+/**
+ * What a held tool call wants to do, in words a person reads at a glance:
+ * "read your email", not `ListInboxes {"limit": 5}`. `whose` is the
+ * possessive of the owner whose access the call spends ("your", "Alice's").
+ */
+
+import type { ToolName as MacroToolName } from '@service-cognition/generated/tools/tool';
+
+type Wording = (whose: string) => string;
+
+/**
+ * Every Macro tool, so a new one does not type-check until it is worded.
+ * `null` for the tools that use nobody's access and so are never held.
+ */
+const MACRO_TOOLS: Record<MacroToolName, Wording | null> = {
+ BashCodeExecution: (whose) => `run code with ${whose} access`,
+ BulkSetEntityPropertyOptions: (whose) =>
+ `change property options in ${whose} workspace`,
+ CalculateSpreadsheet: (whose) => `calculate in ${whose} spreadsheets`,
+ CommentOnDocument: (whose) => `comment on ${whose} documents`,
+ ConfigureAgent: (whose) => `change ${whose} agents`,
+ ConfigureBot: (whose) => `change ${whose} bots`,
+ ContentSearch: (whose) => `search ${whose} workspace`,
+ CreateBot: (whose) => `create a bot in ${whose} workspace`,
+ CreateCalendarEvent: (whose) => `add an event to ${whose} calendar`,
+ CreateChannel: (whose) => `create a channel from ${whose} account`,
+ CreateConfirmedCalendarEvent: (whose) => `add an event to ${whose} calendar`,
+ CreateDocument: (whose) => `create a document in ${whose} workspace`,
+ CreateImportEntity: (whose) => `import into ${whose} workspace`,
+ CreateInitiative: (whose) => `create an initiative in ${whose} workspace`,
+ CreateProject: (whose) => `create a project in ${whose} workspace`,
+ CreateReminder: (whose) => `add a reminder for ${whose} account`,
+ CreateRoutine: (whose) => `create a routine for ${whose} account`,
+ CreateTag: (whose) => `create a tag in ${whose} workspace`,
+ DeleteBot: (whose) => `delete ${whose} bots`,
+ DeleteCalendarEvent: (whose) => `delete an event from ${whose} calendar`,
+ DeleteDatabaseView: (whose) => `delete a view from ${whose} databases`,
+ DeleteImportEntity: (whose) => `delete an import from ${whose} workspace`,
+ DeleteInitiative: (whose) => `delete ${whose} initiatives`,
+ DeleteReminder: (whose) => `delete ${whose} reminders`,
+ DeleteTag: (whose) => `delete tags in ${whose} workspace`,
+ DescribeDatabase: (whose) => `read ${whose} databases`,
+ DisplayResults: (whose) => `show results from ${whose} workspace`,
+ DispatchCodingAgent: (whose) => `start a coding agent with ${whose} access`,
+ EditDocument: (whose) => `edit ${whose} documents`,
+ EditPresentation: (whose) => `edit ${whose} presentations`,
+ EditSpreadsheet: (whose) => `edit ${whose} spreadsheets`,
+ EditTag: (whose) => `edit tags in ${whose} workspace`,
+ EditWordDocument: (whose) => `edit ${whose} documents`,
+ GenerateImage: (whose) => `generate an image with ${whose} account`,
+ GetBotWebhooks: (whose) => `read ${whose} bot webhooks`,
+ GetCompany: (whose) => `look up companies in ${whose} workspace`,
+ GetEntityProperties: (whose) => `read properties in ${whose} workspace`,
+ GetThread: (whose) => `read ${whose} email`,
+ ImportNotionPage: (whose) => `import a Notion page into ${whose} workspace`,
+ IssueBotCredential: (whose) => `issue credentials for ${whose} bots`,
+ ListAgents: (whose) => `list ${whose} agents`,
+ ListBots: (whose) => `list ${whose} bots`,
+ ListCalendarEvents: (whose) => `read ${whose} calendar`,
+ ListCalendars: (whose) => `read ${whose} calendar`,
+ ListCodingAgents: (whose) => `list ${whose} coding agents`,
+ ListCompanies: (whose) => `look up companies in ${whose} workspace`,
+ ListDatabases: (whose) => `list ${whose} databases`,
+ ListEntities: (whose) => `list ${whose} files and tasks`,
+ ListImportEntities: (whose) => `list imports in ${whose} workspace`,
+ ListInboxes: (whose) => `look through ${whose} email`,
+ ListInitiatives: (whose) => `list ${whose} initiatives`,
+ ListLabels: (whose) => `read ${whose} email labels`,
+ ListNotifications: (whose) => `read ${whose} notifications`,
+ ListReminders: (whose) => `read ${whose} reminders`,
+ ListRoutines: (whose) => `list ${whose} routines`,
+ ListSkills: (whose) => `list ${whose} skills`,
+ ListTags: (whose) => `list tags in ${whose} workspace`,
+ ListTeamMembers: (whose) => `look up ${whose} teammates`,
+ LoadTools: null,
+ ManageBotChannelAccess: (whose) =>
+ `change which channels ${whose} bots can use`,
+ ManageChannelParticipants: (whose) => `change who is in ${whose} channels`,
+ MarkNotificationsDone: (whose) => `mark ${whose} notifications done`,
+ MarkNotificationsSeen: (whose) => `mark ${whose} notifications seen`,
+ MoveToProject: (whose) => `reorganize ${whose} projects`,
+ NameSearch: (whose) => `search ${whose} workspace`,
+ QueryDatabase: (whose) => `query ${whose} databases`,
+ ReadActivity: (whose) => `read ${whose} recent activity`,
+ ReadCallRecord: (whose) => `read ${whose} call recordings`,
+ ReadChannelMessageContext: (whose) => `read ${whose} channel messages`,
+ ReadChannelMessages: (whose) => `read ${whose} channel messages`,
+ ReadChannelThread: (whose) => `read ${whose} channel messages`,
+ ReadChat: (whose) => `read ${whose} chats`,
+ ReadContent: (whose) => `read ${whose} documents`,
+ ReadDesign: (whose) => `read ${whose} designs`,
+ ReadInitiative: (whose) => `read ${whose} initiatives`,
+ ReadInitiativeActivity: (whose) => `read activity on ${whose} initiatives`,
+ ReadMetadata: (whose) => `look up details in ${whose} workspace`,
+ ReadPresentation: (whose) => `read ${whose} presentations`,
+ ReadProject: (whose) => `read ${whose} projects`,
+ ReadRoutine: (whose) => `read ${whose} routines`,
+ ReadSkill: (whose) => `read ${whose} skills`,
+ ReadSpreadsheet: (whose) => `read ${whose} spreadsheets`,
+ ReadThread: (whose) => `read ${whose} email`,
+ ReadWordDocument: (whose) => `read ${whose} documents`,
+ RenameChannel: (whose) => `rename ${whose} channels`,
+ RenameDocument: (whose) => `rename ${whose} documents`,
+ ResolveDocumentComment: (whose) => `resolve comments on ${whose} documents`,
+ SaveDatabaseQuery: (whose) => `save a query in ${whose} databases`,
+ SaveDatabaseView: (whose) => `save a view in ${whose} databases`,
+ SearchSkills: (whose) => `search ${whose} skills`,
+ SearchTools: null,
+ SelfKnowledge: null,
+ SendChannelMessage: (whose) => `post a message from ${whose} account`,
+ SendConfirmedEmail: (whose) => `send email from ${whose} account`,
+ SendEmail: (whose) => `send email from ${whose} account`,
+ SetEntityProperty: (whose) => `set properties in ${whose} workspace`,
+ SetSenderPolicy: (whose) => `change ${whose} email sender rules`,
+ Subagent: (whose) => `start a helper agent with ${whose} access`,
+ TextEditorCodeExecution: (whose) => `edit files with ${whose} access`,
+ UpdateCalendarEvent: (whose) => `change an event on ${whose} calendar`,
+ UpdateInitiative: (whose) => `change ${whose} initiatives`,
+ UpdateInitiativeSharing: (whose) => `change who can see ${whose} initiatives`,
+ UpdateReminder: (whose) => `change ${whose} reminders`,
+ UpdateRoutine: (whose) => `change ${whose} routines`,
+ UpdateThreadLabels: (whose) => `relabel ${whose} email`,
+ UploadFile: (whose) => `upload a file to ${whose} workspace`,
+ WebFetch: null,
+ WebSearch: null,
+};
+
+function isMacroTool(tool: string): tool is MacroToolName {
+ return Object.hasOwn(MACRO_TOOLS, tool);
+}
+
+/** `ListEntities` → `list entities`, `linear-create-issue` → `linear create issue`. */
+function toolWords(tool: string): string {
+ return tool
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
+ .replace(/[-_]+/g, ' ')
+ .trim()
+ .toLowerCase();
+}
+
+/** The verb phrase for a held call, e.g. `read your email`. */
+export function describeToolCall(
+ server: { slug: string; name: string },
+ tool: string,
+ whose: string
+): string {
+ if (server.slug !== 'macro') {
+ return `use ${whose} ${server.name} account (${toolWords(tool)})`;
+ }
+ // A tool newer than this build, or one never held, reads by its name.
+ const wording = isMacroTool(tool) ? MACRO_TOOLS[tool] : null;
+ return wording
+ ? wording(whose)
+ : `use ${whose} Macro workspace (${toolWords(tool)})`;
+}
+
+/**
+ * What approving a call for good covers, as a verb phrase: the same tool on
+ * Macro, whose one server reaches all of the owner's data, or the whole
+ * connected app.
+ */
+export function describeStandingApproval(
+ server: { slug: string; name: string },
+ tool: string,
+ whose: string
+): string {
+ return server.slug === 'macro'
+ ? describeToolCall(server, tool, whose)
+ : `use ${whose} ${server.name} account`;
+}
+
+/** `Alice Seed` → `Alice Seed's`; a name ending in s takes a bare apostrophe. */
+export function possessive(name: string): string {
+ return name.endsWith('s') ? `${name}'` : `${name}'s`;
+}
diff --git a/apps/web/src/features/block-agent/ui/ToolApprovalCard.test.tsx b/apps/web/src/features/block-agent/ui/ToolApprovalCard.test.tsx
new file mode 100644
index 0000000000..017e03705e
--- /dev/null
+++ b/apps/web/src/features/block-agent/ui/ToolApprovalCard.test.tsx
@@ -0,0 +1,79 @@
+/** @vitest-environment jsdom */
+
+import { cleanup, fireEvent, render } from '@solidjs/testing-library';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import {
+ ToolApprovalCard,
+ type ToolApprovalCardProps,
+} from './ToolApprovalCard';
+
+afterEach(cleanup);
+
+function card(overrides: Partial<ToolApprovalCardProps>) {
+ const handlers = {
+ onApprove: vi.fn(),
+ onApproveAlways: vi.fn(),
+ onDeny: vi.fn(),
+ onCancel: vi.fn(),
+ };
+ const view = render(() => (
+ <ToolApprovalCard
+ action="read your email"
+ requester="[email protected]"
+ canApprove={false}
+ canCancel={false}
+ {...handlers}
+ {...overrides}
+ />
+ ));
+ return { ...view, ...handlers };
+}
+
+describe('ToolApprovalCard', () => {
+ it('asks the owner to approve or decline, saying what the agent wants and who asked', () => {
+ const { getByText, onApprove, onDeny } = card({ canApprove: true });
+ expect(getByText('Approval needed')).toBeTruthy();
+ expect(
+ getByText('[email protected] asked the agent to read your email.')
+ ).toBeTruthy();
+ fireEvent.click(getByText('Approve'));
+ fireEvent.click(getByText('Decline'));
+ expect(onApprove).toHaveBeenCalledOnce();
+ expect(onDeny).toHaveBeenCalledOnce();
+ });
+
+ it('lets the owner approve for good, saying what that covers', () => {
+ const { getByText, onApproveAlways } = card({
+ canApprove: true,
+ standing: 'use your Linear account',
+ });
+ expect(
+ getByText(
+ 'Always allow lets [email protected] use your Linear account in this session without asking you.'
+ )
+ ).toBeTruthy();
+ fireEvent.click(getByText('Always allow'));
+ expect(onApproveAlways).toHaveBeenCalledOnce();
+ });
+
+ it('offers no standing approval when there is nobody to remember', () => {
+ const { queryByText } = card({ canApprove: true });
+ expect(queryByText('Always allow')).toBeNull();
+ });
+
+ it('shows everyone else who it waits for, with a way out for editors', () => {
+ const { getByText, queryByText, onCancel } = card({ canCancel: true });
+ expect(getByText('Waiting for [email protected] to approve')).toBeTruthy();
+ expect(queryByText('Approve')).toBeNull();
+ expect(queryByText('Always allow')).toBeNull();
+ fireEvent.click(getByText('Cancel'));
+ expect(onCancel).toHaveBeenCalledOnce();
+ });
+
+ it('leaves a viewer nothing to press', () => {
+ const { queryByText } = card({});
+ expect(queryByText('Cancel')).toBeNull();
+ expect(queryByText('Approve')).toBeNull();
+ });
+});
diff --git a/apps/web/src/features/block-agent/ui/ToolApprovalCard.tsx b/apps/web/src/features/block-agent/ui/ToolApprovalCard.tsx
new file mode 100644
index 0000000000..d2d0496c88
--- /dev/null
+++ b/apps/web/src/features/block-agent/ui/ToolApprovalCard.tsx
@@ -0,0 +1,114 @@
+import ShieldCheck from '@phosphor/shield-check.svg';
+import { Button } from '@ui';
+import { Show } from 'solid-js';
+
+export type ToolApprovalCardProps = {
+ /** What the agent wants to do, e.g. `read your email`. */
+ action: string;
+ /**
+ * What approving for good would let the requester do without asking, e.g.
+ * `use your Linear account`. Absent when it cannot be offered.
+ */
+ standing?: string;
+ /** Who prompted the turn; absent for a bot on nobody's behalf. */
+ requester?: string;
+ /** The session's owner, whose access the call spends. */
+ owner: string;
+ /** The viewer is the owner. */
+ canApprove: boolean;
+ /** The viewer may give up waiting on the owner. */
+ canCancel: boolean;
+ /** An answer is on the wire. */
+ disabled?: boolean;
+ onApprove: () => void;
+ onApproveAlways: () => void;
+ onDeny: () => void;
+ onCancel: () => void;
+};
+
+/**
+ * A tool call held for the session owner: approve or decline for them,
+ * "waiting for the owner" with a way out for everyone else.
+ */
+export function ToolApprovalCard(props: ToolApprovalCardProps) {
+ const asker = () => props.requester ?? 'A bot';
+ return (
+ <section
+ aria-label="Tool approval request"
+ class="min-w-0 overflow-hidden rounded-xl border border-edge-muted bg-panel text-ink"
+ >
+ <div class="flex items-start gap-3 px-4 pt-4">
+ <div class="flex size-8 shrink-0 items-center justify-center rounded-lg bg-accent-bg text-accent">
+ <ShieldCheck class="size-4" />
+ </div>
+ <div class="min-w-0 flex-1">
+ <div class="text-sm font-medium">
+ {props.canApprove
+ ? 'Approval needed'
+ : `Waiting for ${props.owner} to approve`}
+ </div>
+ <p class="mt-0.5 text-sm leading-5 text-ink-muted [overflow-wrap:anywhere]">
+ {asker()} asked the agent to {props.action}.
+ </p>
+ <Show when={props.canApprove && props.standing}>
+ {(standing) => (
+ <p class="mt-1 text-xs leading-4 text-ink-muted [overflow-wrap:anywhere]">
+ Always allow lets {asker()} {standing()} in this session without
+ asking you.
+ </p>
+ )}
+ </Show>
+ </div>
+ </div>
+ <div class="flex min-w-0 flex-wrap items-center justify-end gap-2 p-3">
+ <Show
+ when={props.canApprove}
+ fallback={
+ <Show when={props.canCancel}>
+ <Button
+ type="button"
+ size="md"
+ variant="outline"
+ disabled={props.disabled}
+ onClick={() => props.onCancel()}
+ >
+ Cancel
+ </Button>
+ </Show>
+ }
+ >
+ <Button
+ type="button"
+ size="md"
+ variant="ghost"
+ class="mr-auto"
+ disabled={props.disabled}
+ onClick={() => props.onDeny()}
+ >
+ Decline
+ </Button>
+ <Show when={props.standing}>
+ <Button
+ type="button"
+ size="md"
+ variant="outline"
+ disabled={props.disabled}
+ onClick={() => props.onApproveAlways()}
+ >
+ Always allow
+ </Button>
+ </Show>
+ <Button
+ type="button"
+ size="md"
+ variant="strong"
+ disabled={props.disabled}
+ onClick={() => props.onApprove()}
+ >
+ Approve
+ </Button>
+ </Show>
+ </div>
+ </section>
+ );
+}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts
index 7c99159d3d..d96a6c646d 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts
@@ -70,6 +70,8 @@ vi.mock('@core/user', () => ({
getDisplayName: (id: string) =>
id === 'macro|[email protected]' ? 'Alice Owner' : '',
}));
+let viewer = 'macro|[email protected]';
+vi.mock('@core/context/user', () => ({ useUserId: () => () => viewer }));
vi.mock('@core/component/Toast/Toast', () => ({
toast: { failure: vi.fn(), success: vi.fn() },
}));
@@ -649,6 +651,52 @@ describe('createMagicChipModel', () => {
dispose();
});
+ it('says what a held tool call wants, as yours to the owner', async () => {
+ live.snapshot = {
+ messages: [prompt, openResponse],
+ metadata: {
+ pendingInteractions: [
+ {
+ kind: 'tool_approval',
+ approvalId: 'a1',
+ turn: 0,
+ serverSlug: 'macro',
+ serverName: 'Macro',
+ toolName: 'GetThread',
+ requestedBy: 'macro|[email protected]',
+ },
+ ],
+ } as unknown as SessionMetadata,
+ };
+ serviceClient.get.mockResolvedValue({
+ isOk: () => true,
+ isErr: () => false,
+ value: {
+ status: { kind: 'disconnected' },
+ ownerId: 'macro|[email protected]',
+ canEdit: true,
+ },
+ });
+ const action = async () => {
+ let presentation!: ReturnType<
+ typeof createMagicChipModel
+ >['presentation'];
+ const dispose = createRoot((rootDispose) => {
+ presentation = createModel(props).presentation;
+ return rootDispose;
+ });
+ await settle();
+ const shown = presentation();
+ dispose();
+ return shown.kind === 'asking' ? shown.asking.action : undefined;
+ };
+
+ expect(await action()).toBe('Wants to read your email');
+ viewer = 'macro|[email protected]';
+ expect(await action()).toBe("Wants to read the owner's email");
+ viewer = 'macro|[email protected]';
+ });
+
it("a question from a later turn is not this chip's, and the live metadata moves it", async () => {
live.snapshot = {
messages: [prompt, openResponse],
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts
index 04870e38c4..1083fff7e8 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts
@@ -10,8 +10,10 @@ import {
} from '@app/features/block-agent/component/parts/shared';
import type { InteractionController } from '@app/features/block-agent/context/interaction';
import { createInteractionController } from '@app/features/block-agent/primitives/create-interaction-controller';
+import { describeToolCall } from '@app/features/block-agent/state/tool-approval-wording';
import { AgentSession } from '@core/agent-session/AgentSession';
import { toast } from '@core/component/Toast/Toast';
+import { useUserId } from '@core/context/user';
import {
MAGIC_CHIP_STATUSES,
type MagicChipData,
@@ -115,6 +117,7 @@ export function createMagicChipModel(props: MagicChipData): {
const session = () =>
queryReadyGate(sessionQuery) ? sessionQuery.data : undefined;
const canEdit = () => session()?.canEdit;
+ const userId = useUserId();
const persistedStatus = () => {
const status = session()?.status;
return (status ? magicChipStatus(status) : undefined) ?? props.status;
@@ -184,6 +187,19 @@ export function createMagicChipModel(props: MagicChipData): {
const asking = (): MagicChipInteraction | undefined => {
const request = pendingForTurn()[0];
if (!request) return undefined;
+ // A held tool call is answered in the session, where its arguments are.
+ if (request.kind === 'tool_approval') {
+ return {
+ request,
+ canAnswer: false,
+ answering: false,
+ action: `Wants to ${describeToolCall(
+ { slug: request.serverSlug, name: request.serverName },
+ request.toolName,
+ session()?.ownerId === userId() ? 'your' : "the owner's"
+ )}`,
+ };
+ }
const tool = messages()
.find(
(message) =>
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.ts
index 2d70408fa3..5a30a9c4c3 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.ts
@@ -204,6 +204,22 @@ function partActivity(part: MessagePart): MagicChipActivity {
label: 'Permission unavailable',
busy: false,
}))
+ .with({ kind: 'tool_approval', status: 'pending' }, () => ({
+ label: 'Waiting for approval',
+ busy: false,
+ tone: 'attention' as const,
+ }))
+ .with({ kind: 'tool_approval', status: 'approved' }, () => ({
+ label: 'Resuming work',
+ busy: true,
+ }))
+ .with(
+ {
+ kind: 'tool_approval',
+ status: P.union('denied', 'cancelled', 'expired'),
+ },
+ () => ({ label: 'Tool call not approved', busy: true })
+ )
.with({ kind: 'control', control: { kind: 'set_model' } }, (part) => ({
label: 'Model changed',
detail: modelLabel(part.control.model),
@@ -465,9 +481,11 @@ export function presentationStatus(
.with({ kind: 'asking' }, ({ asking }) => ({
label: asking.answering
? 'Sending answer'
- : asking.canAnswer
- ? 'Waiting for you'
- : 'Waiting for an editor',
+ : asking.request.kind === 'tool_approval'
+ ? 'Waiting for approval'
+ : asking.canAnswer
+ ? 'Waiting for you'
+ : 'Waiting for an editor',
busy: false,
}))
.with({ kind: 'settled' }, () => ({ label: 'Done', busy: false }))
diff --git a/apps/web/src/lib/queries/agent-session/subscription.ts b/apps/web/src/lib/queries/agent-session/subscription.ts
new file mode 100644
index 0000000000..1affdc7069
--- /dev/null
+++ b/apps/web/src/lib/queries/agent-session/subscription.ts
@@ -0,0 +1,16 @@
+import { useEntitySubscription } from '@service-connection/client';
+import type { Accessor } from 'solid-js';
+
+/**
+ * Tell the gateway this viewer watches `sessionId`, so its live frames reach
+ * them. The owner hears every frame regardless; anyone else would otherwise
+ * see nothing live unless they also had the parent channel open.
+ */
+export function useAgentSessionSubscription(
+ sessionId: Accessor<string | undefined>
+) {
+ useEntitySubscription(() => {
+ const id = sessionId();
+ return id ? { entity_type: 'agent_session', entity_id: id } : undefined;
+ });
+}
diff --git a/apps/web/src/lib/queries/agent-session/tool-approvals.ts b/apps/web/src/lib/queries/agent-session/tool-approvals.ts
new file mode 100644
index 0000000000..0d01caab4e
--- /dev/null
+++ b/apps/web/src/lib/queries/agent-session/tool-approvals.ts
@@ -0,0 +1,20 @@
+import { agentHarnessServiceClient } from '@service-agent-harness/client';
+import type { ToolApprovalAnswerDto } from '@service-agent-harness/generated/schemas';
+
+/**
+ * Answer a tool call held for the session owner. Not a cached mutation: the
+ * outcome reaches every viewer through the session's log, and the caller
+ * branches on the result's error codes (an already-answered call is a
+ * conflict, not a failure).
+ */
+export function answerAgentSessionToolApproval(
+ sessionId: string,
+ approvalId: string,
+ answer: ToolApprovalAnswerDto
+) {
+ return agentHarnessServiceClient.answerToolApproval(
+ sessionId,
+ approvalId,
+ answer
+ );
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts b/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts
index a13dfd4d7b..8817afcb17 100644
--- a/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts
+++ b/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts
@@ -620,6 +620,34 @@ export type MessagePart =
/** How the request has resolved so far. */
outcome: PermissionOutcome;
}
+ /**
+ * An MCP tool call the egress proxy is holding, or held, until the
+ * session's owner approved it: made in a turn somebody else prompted.
+ */
+ | {
+ kind: 'tool_approval';
+ /** The approval an answer names. */
+ approvalId: string;
+ /** `macro`, or the connected app's slug. */
+ serverSlug: string;
+ /** What a person calls the server the tool is on. */
+ serverName: string;
+ /** The tool called. */
+ toolName: string;
+ /** What it was called with. */
+ arguments: unknown;
+ /** Who prompted the turn; absent for a bot on nobody's behalf. */
+ requestedBy: string | null;
+ /** Where it stands. */
+ status: ToolApprovalStatus;
+ /** Who resolved it, when a person did. */
+ resolvedBy: string | null;
+ /**
+ * Approved for good: the person who asked may make the calls it
+ * covers without the owner being asked again.
+ */
+ remembered: boolean;
+ }
/** A user-issued control operation on the session. */
| {
kind: 'control';
@@ -722,7 +750,14 @@ export type PendingInteraction =
/** A form, URL consent, or user tool review. */
| ({
kind: 'elicitation';
- } & PendingElicitation);
+ } & PendingElicitation)
+ /**
+ * An MCP tool call held until the session's owner approves it. Only
+ * the owner may approve or decline; anyone with edit access may cancel.
+ */
+ | ({
+ kind: 'tool_approval';
+ } & PendingToolApproval);
/** A permission request the current connection can still answer. */
export type PendingPermission = {
@@ -736,6 +771,22 @@ export type PendingPermission = {
options: PermissionOption[];
};
+/** A held MCP tool call the owner can still answer. */
+export type PendingToolApproval = {
+ /** The approval an answer names. */
+ approvalId: string;
+ /** The turn the call was made in. */
+ turn: number;
+ /** `macro`, or the connected app's slug. */
+ serverSlug: string;
+ /** What a person calls the server the tool is on. */
+ serverName: string;
+ /** The tool called. */
+ toolName: string;
+ /** Who prompted the turn; absent for a bot on nobody's behalf. */
+ requestedBy: string | null;
+};
+
/** One choice offered for a permission request. */
export type PermissionOption = {
/** The id to report back when this option is chosen. */
@@ -1003,6 +1054,19 @@ export type SubagentResult = {
stats: ToolStats | null;
};
+/** Where a held call stands. */
+export type ToolApprovalStatus =
+ /** Held until the owner answers. */
+ | 'pending'
+ /** The owner approved it; the call went through. */
+ | 'approved'
+ /** The owner refused it; the call did not run. */
+ | 'denied'
+ /** Someone with edit access, the agent, or the session gave up on it. */
+ | 'cancelled'
+ /** Nobody answered in time. */
+ | 'expired';
+
/**
* What a tool call actually did.
*
@@ -1285,7 +1349,10 @@ export type TurnState =
| 'running'
/** A stop was issued against the open turn and no stop reason has arrived. */
| 'stopping'
- /** The open turn is waiting on a permission or elicitation response. */
+ /**
+ * The open turn is waiting on a permission, elicitation, or tool
+ * approval response.
+ */
| 'blocked'
/** The runtime reported `disconnected`; whatever was open is not moving. */
| 'disconnected';
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/client.ts b/apps/web/src/lib/service-clients/service-agent-harness/client.ts
index c34b438428..ac616f1c23 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/client.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/client.ts
@@ -9,6 +9,7 @@ import type {
AgentSessionLogResponse,
AgentSessionQueueResponse,
AgentSessionResponse,
+ AnswerToolApprovalResponse,
ControlRequest,
ControlResponse,
CreateAgentSessionRequest,
@@ -23,6 +24,7 @@ import type {
SandboxSizeBody,
SessionPullRequestsResponse,
SharePermissionV2,
+ ToolApprovalAnswerDto,
UpdateSharePermissionRequestV2,
} from './generated/schemas';
@@ -342,6 +344,26 @@ export const agentHarnessServiceClient = {
);
},
+ /**
+ * Answer a tool call the agent made in a turn somebody other than the
+ * owner prompted. Approve and deny are the owner's; cancel is anyone's
+ * with edit access. 409 once somebody already answered.
+ */
+ answerToolApproval(
+ sessionId: string,
+ approvalId: string,
+ answer: ToolApprovalAnswerDto
+ ) {
+ return fetchWithToken<AnswerToolApprovalResponse>(
+ `${agentHarnessHost}/agent-sessions/${sessionId}/tool-approvals/${approvalId}`,
+ {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ answer }),
+ }
+ );
+ },
+
setSessionSandboxSize(sessionId: string, size: SandboxSize) {
return fetchWithToken<SandboxSizeBody>(
`${agentHarnessHost}/agent-sessions/${sessionId}/sandbox-size`,
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts
index 7f3c13dd89..7f89554690 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts
@@ -13,6 +13,8 @@ import type {
AgentSessionQueueResponse,
AgentSessionResponse,
AiAdmissionErrorBody,
+ AnswerToolApprovalRequest,
+ AnswerToolApprovalResponse,
CompleteRequest,
ControlRequest,
ControlResponse,
@@ -2038,6 +2040,100 @@ export const putAgentSessionSandboxSize = async (
} as putAgentSessionSandboxSizeResponse;
};
+/**
+ * @summary Answer a tool call the agent made in a turn somebody other than the
+session's owner prompted. Approve and deny are the owner's; cancel is
+anyone's with edit access.
+ */
+export type answerAgentSessionToolApprovalResponse200 = {
+ data: AnswerToolApprovalResponse;
+ status: 200;
+};
+
+export type answerAgentSessionToolApprovalResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type answerAgentSessionToolApprovalResponse403 = {
+ data: string;
+ status: 403;
+};
+
+export type answerAgentSessionToolApprovalResponse404 = {
+ data: string;
+ status: 404;
+};
+
+export type answerAgentSessionToolApprovalResponse409 = {
+ data: string;
+ status: 409;
+};
+
+export type answerAgentSessionToolApprovalResponse422 = {
+ data: string;
+ status: 422;
+};
+
+export type answerAgentSessionToolApprovalResponse500 = {
+ data: string;
+ status: 500;
+};
+
+export type answerAgentSessionToolApprovalResponseSuccess =
+ answerAgentSessionToolApprovalResponse200 & {
+ headers: Headers;
+ };
+export type answerAgentSessionToolApprovalResponseError = (
+ | answerAgentSessionToolApprovalResponse401
+ | answerAgentSessionToolApprovalResponse403
+ | answerAgentSessionToolApprovalResponse404
+ | answerAgentSessionToolApprovalResponse409
+ | answerAgentSessionToolApprovalResponse422
+ | answerAgentSessionToolApprovalResponse500
+) & {
+ headers: Headers;
+};
+
+export type answerAgentSessionToolApprovalResponse =
+ | answerAgentSessionToolApprovalResponseSuccess
+ | answerAgentSessionToolApprovalResponseError;
+
+export const getAnswerAgentSessionToolApprovalUrl = (
+ sessionId: string,
+ approvalId: string
+) => {
+ return `/agent-sessions/${sessionId}/tool-approvals/${approvalId}`;
+};
+
+export const answerAgentSessionToolApproval = async (
+ sessionId: string,
+ approvalId: string,
+ answerToolApprovalRequest: AnswerToolApprovalRequest,
+ options?: RequestInit
+): Promise<answerAgentSessionToolApprovalResponse> => {
+ const res = await fetch(
+ getAnswerAgentSessionToolApprovalUrl(sessionId, approvalId),
+ {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(answerToolApprovalRequest),
+ }
+ );
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: answerAgentSessionToolApprovalResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as answerAgentSessionToolApprovalResponse;
+};
+
/**
* @summary Read connection status for the authenticated user only.
*/
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/answerToolApprovalRequest.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/answerToolApprovalRequest.ts
new file mode 100644
index 0000000000..1191e4b456
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/answerToolApprovalRequest.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ToolApprovalAnswerDto } from './toolApprovalAnswerDto';
+
+/**
+ * Request body for answering a held tool call.
+ */
+export interface AnswerToolApprovalRequest {
+ /** The answer. */
+ answer: ToolApprovalAnswerDto;
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/answerToolApprovalResponse.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/answerToolApprovalResponse.ts
new file mode 100644
index 0000000000..97fb4aa49c
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/answerToolApprovalResponse.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ToolApprovalStatusDto } from './toolApprovalStatusDto';
+
+/**
+ * Response body for answering a held tool call.
+ */
+export interface AnswerToolApprovalResponse {
+ /** Where the call stands now. */
+ status: ToolApprovalStatusDto;
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
index 17c1f00e5d..ed8e087241 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
@@ -85,6 +85,8 @@ export * from './agentSessionResponseThreadParent';
export * from './agentSetConfigOptionAction';
export * from './agentSetModelAction';
export * from './aiAdmissionErrorBody';
+export * from './answerToolApprovalRequest';
+export * from './answerToolApprovalResponse';
export * from './botId';
export * from './capabilityHarnessDto';
export * from './captureAttemptDto';
@@ -207,6 +209,8 @@ export * from './sharePermissionV2LinkShareAccessLevel';
export * from './sharePermissionV2TeamShareAccessLevel';
export * from './startResponse';
export * from './statusResponse';
+export * from './toolApprovalAnswerDto';
+export * from './toolApprovalStatusDto';
export * from './unlinkAgentSessionPullRequestParams';
export * from './updateChannelSharePermission';
export * from './updateChannelSharePermissionAccessLevel';
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/toolApprovalAnswerDto.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/toolApprovalAnswerDto.ts
new file mode 100644
index 0000000000..7cabf34853
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/toolApprovalAnswerDto.ts
@@ -0,0 +1,20 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * How a person answers a held tool call.
+ */
+export type ToolApprovalAnswerDto =
+ (typeof ToolApprovalAnswerDto)[keyof typeof ToolApprovalAnswerDto];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const ToolApprovalAnswerDto = {
+ approve: 'approve',
+ approve_and_remember: 'approve_and_remember',
+ deny: 'deny',
+ cancel: 'cancel',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/toolApprovalStatusDto.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/toolApprovalStatusDto.ts
new file mode 100644
index 0000000000..e6c9b131a9
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/toolApprovalStatusDto.ts
@@ -0,0 +1,21 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Where a held tool call stands once answered.
+ */
+export type ToolApprovalStatusDto =
+ (typeof ToolApprovalStatusDto)[keyof typeof ToolApprovalStatusDto];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const ToolApprovalStatusDto = {
+ pending: 'pending',
+ approved: 'approved',
+ denied: 'denied',
+ cancelled: 'cancelled',
+ expired: 'expired',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
index cc3da35a63..739bea72b5 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
+++ b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
@@ -1825,6 +1825,117 @@
}
}
},
+ "/agent-sessions/{session_id}/tool-approvals/{approval_id}": {
+ "post": {
+ "tags": ["agent-sessions"],
+ "summary": "Answer a tool call the agent made in a turn somebody other than the\nsession's owner prompted. Approve and deny are the owner's; cancel is\nanyone's with edit access.",
+ "operationId": "answer_agent_session_tool_approval",
+ "parameters": [
+ {
+ "name": "session_id",
+ "in": "path",
+ "description": "ID of the agent session",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ },
+ {
+ "name": "approval_id",
+ "in": "path",
+ "description": "ID of the held tool call",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AnswerToolApprovalRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AnswerToolApprovalResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "Not the owner, for approve or deny; or no edit access",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "409": {
+ "description": "Already resolved",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Approve for good, for a call no person asked for",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/claude-auth": {
"get": {
"tags": ["claude-auth"],
@@ -2705,6 +2816,28 @@
}
}
},
+ "AnswerToolApprovalRequest": {
+ "type": "object",
+ "description": "Request body for answering a held tool call.",
+ "required": ["answer"],
+ "properties": {
+ "answer": {
+ "$ref": "#/components/schemas/ToolApprovalAnswerDto",
+ "description": "The answer."
+ }
+ }
+ },
+ "AnswerToolApprovalResponse": {
+ "type": "object",
+ "description": "Response body for answering a held tool call.",
+ "required": ["status"],
+ "properties": {
+ "status": {
+ "$ref": "#/components/schemas/ToolApprovalStatusDto",
+ "description": "Where the call stands now."
+ }
+ }
+ },
"BotId": {
"type": "string"
},
@@ -3799,6 +3932,16 @@
}
}
},
+ "ToolApprovalAnswerDto": {
+ "type": "string",
+ "description": "How a person answers a held tool call.",
+ "enum": ["approve", "approve_and_remember", "deny", "cancel"]
+ },
+ "ToolApprovalStatusDto": {
+ "type": "string",
+ "description": "Where a held tool call stands once answered.",
+ "enum": ["pending", "approved", "denied", "cancelled", "expired"]
+ },
"UpdateChannelSharePermission": {
"type": "object",
"required": ["operation", "channelId"],
diff --git a/crates/agent_egress/Cargo.toml b/crates/agent_egress/Cargo.toml
index dc07bddc36..08ada31c73 100644
--- a/crates/agent_egress/Cargo.toml
+++ b/crates/agent_egress/Cargo.toml
@@ -16,6 +16,8 @@ axum = { workspace = true }
axum-extra = { workspace = true, features = ["typed-header"] }
base64 = { workspace = true }
bytes = { workspace = true }
+# Holding a tool call for the owner: the stream it answers with.
+futures = { workspace = true }
chrono = { workspace = true }
# The installation records that say whose installation an installation is, and
# the team memberships that decide whether the session's owner is one of them.
@@ -39,6 +41,7 @@ macro_user_id = { path = "../macro_user_id" }
# encrypted grants, and the refresh that keeps a grant live. Port and domain
# service only; the Postgres adapter is the composition root's to build.
mcp_client = { path = "../mcp_client" }
+macro_uuid = { path = "../macro_uuid" }
model_owner = { path = "../model_owner" }
# The rows saying which apps an owner connected, and the client that turns one
# into Pipedream's MCP endpoint plus the headers scoping a call to it.
@@ -51,6 +54,8 @@ serde_json = { workspace = true }
sqlx = { workspace = true }
sha2 = { workspace = true }
thiserror = { workspace = true }
+# The hold's keepalive timer, and the channel its stream is fed through.
+tokio = { workspace = true, features = ["rt", "sync", "time", "macros"] }
tracing = { workspace = true }
url = { workspace = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
diff --git a/crates/agent_egress/src/domain/approval.rs b/crates/agent_egress/src/domain/approval.rs
new file mode 100644
index 0000000000..4761f91f0d
--- /dev/null
+++ b/crates/agent_egress/src/domain/approval.rs
@@ -0,0 +1,796 @@
+//! Holding an MCP tool call until the session's owner approves it.
+//!
+//! A session spends its owner's credentials whoever prompts it. When somebody
+//! else prompted the running turn, every `tools/call` it makes is held here:
+//! recorded as a pending approval, announced where the session's viewers see
+//! it (and to the owner as a notification), and answered only once the owner
+//! approves, declines, someone with edit access cancels, or nobody answers in
+//! time.
+//!
+//! The hold is an event stream on the call's own HTTP response. Its first
+//! bytes go out at once, and a progress notification follows every
+//! [`KEEPALIVE_EVERY`], which is what keeps an MCP client that resets its
+//! request timeout on progress (opencode does) waiting for as long as the
+//! owner takes. A client that sent no progress token gets comments instead,
+//! and a shorter limit: nothing says it will wait longer than the transport
+//! does.
+//!
+//! The approval row is the whole truth. Whoever resolves it - the owner's
+//! answer on any replica, the hold's own deadline, the agent cancelling its
+//! request, the turn ending - does so by updating a still-pending row, so
+//! exactly one resolution wins, and the hold wakes on the store's signal to
+//! read which.
+
+use std::pin::Pin;
+use std::sync::Arc;
+use std::time::Duration;
+
+use agent_runtime_protocol::domain::tool_approval::ToolApprovalStatus;
+use bytes::Bytes;
+use macro_user_id::user_id::MacroUserIdStr;
+use tokio::sync::mpsc;
+
+use crate::domain::error::EgressError;
+use crate::domain::model::{AgentSessionId, ProxyRequest, ProxyResponse, TurnPrompter};
+use crate::domain::ports::{
+ ToolApprovalAnnouncer, ToolApprovalSignals, ToolApprovalStore, ToolApprovalSubscription,
+};
+
+mod model;
+mod stream;
+#[cfg(test)]
+mod test;
+
+pub use model::{
+ ApprovalAnswer, StandingApproval, ToolApproval, ToolApprovalError, ToolApprovalId, ToolsCall,
+};
+use stream::{json_response, pass_through, sse_message, stream_response, tool_error};
+
+/// How often a held call's stream says it is still alive.
+pub const KEEPALIVE_EVERY: Duration = Duration::from_secs(15);
+
+/// How long a call is held for a client that resets its timeout on
+/// progress, and in-process, where the turn counts the hold as waiting on a
+/// person rather than as silence.
+pub const HOLD_LIMIT_WITH_PROGRESS: Duration = Duration::from_secs(30 * 60);
+
+/// How long a call is held for an MCP client that sent no progress token:
+/// nothing says it will wait longer than a transport usually does.
+pub const HOLD_LIMIT: Duration = Duration::from_secs(4 * 60);
+
+/// The server slug Macro's own tools are held under.
+pub const MACRO_SERVER_SLUG: &str = "macro";
+
+/// Macro's tools that use nobody's access: looking things up on the public
+/// web, and Macro's help about itself. Everything else on Macro's server
+/// reads or changes the owner's own data, and every connected app is the
+/// owner's own account.
+const MACRO_TOOLS_WITHOUT_OWNER_ACCESS: [&str; 3] = ["WebSearch", "WebFetch", "SelfKnowledge"];
+
+/// Whether calling `tool` on `server_slug` spends the owner's access, and so
+/// waits for them in a turn somebody else prompted.
+#[must_use]
+pub fn spends_owner_access(server_slug: &str, tool: &str) -> bool {
+ server_slug != MACRO_SERVER_SLUG || !MACRO_TOOLS_WITHOUT_OWNER_ACCESS.contains(&tool)
+}
+
+/// Sends an approved call upstream. Built by the proxy over its own
+/// forwarder, so the hold never learns how.
+pub type ForwardOnce = Box<
+ dyn FnOnce(
+ ProxyRequest,
+ ) -> Pin<Box<dyn Future<Output = Result<ProxyResponse, EgressError>> + Send>>
+ + Send,
+>;
+
+/// A `tools/call` the proxy is holding, with everything it takes to put it
+/// through once approved.
+pub struct HeldCall {
+ /// The session whose agent made it.
+ pub session: AgentSessionId,
+ /// The owner whose approval it waits on.
+ pub owner: MacroUserIdStr<'static>,
+ /// Who prompted the turn it was made in.
+ pub prompter: TurnPrompter,
+ /// `macro`, or the connected app's slug.
+ pub server_slug: String,
+ /// What a person calls the server.
+ pub server_name: String,
+ /// The call.
+ pub call: ToolsCall,
+ /// The request, already addressed and stamped for the upstream.
+ pub request: ProxyRequest,
+ /// How to send it.
+ pub forward: ForwardOnce,
+}
+
+/// Holds calls for the owner's approval.
+pub trait OwnerApprovals: Send + Sync + 'static {
+ /// Answer `call`: at once with a stream that ends in the call's own
+ /// result once it is approved, or in a result saying why it did not run.
+ fn hold(
+ &self,
+ call: HeldCall,
+ ) -> impl Future<Output = Result<ProxyResponse, EgressError>> + Send;
+
+ /// The agent withdrew its request `request_id` (`notifications/cancelled`):
+ /// stop holding it, if it is held.
+ fn withdraw(
+ &self,
+ session: AgentSessionId,
+ request_id: &serde_json::Value,
+ ) -> impl Future<Output = Result<(), EgressError>> + Send;
+}
+
+impl<Approvals: OwnerApprovals> OwnerApprovals for Arc<Approvals> {
+ fn hold(
+ &self,
+ call: HeldCall,
+ ) -> impl Future<Output = Result<ProxyResponse, EgressError>> + Send {
+ (**self).hold(call)
+ }
+
+ fn withdraw(
+ &self,
+ session: AgentSessionId,
+ request_id: &serde_json::Value,
+ ) -> impl Future<Output = Result<(), EgressError>> + Send {
+ (**self).withdraw(session, request_id)
+ }
+}
+
+/// For a proxy with no way to ask the owner: every held call is refused, in
+/// words the model can relay. Fails closed, so a deployment that forgot to
+/// wire approvals cannot spend the owner's access on somebody else's behalf.
+#[derive(Clone, Copy, Debug, Default)]
+pub struct RefuseHeldCalls;
+
+impl OwnerApprovals for RefuseHeldCalls {
+ async fn hold(&self, call: HeldCall) -> Result<ProxyResponse, EgressError> {
+ let text = format!(
+ "{tool} did not run. Someone other than {owner}, whose access this session uses, \
+ prompted this turn, and tool calls in such a turn need {owner} to approve them, \
+ which is not possible here. Tell the person who asked, and do not try to do the \
+ same thing another way.",
+ tool = call.call.name,
+ owner = call.owner.email_str(),
+ );
+ Ok(json_response(&tool_error(&call.call.id, &text)))
+ }
+
+ async fn withdraw(
+ &self,
+ _session: AgentSessionId,
+ _request_id: &serde_json::Value,
+ ) -> Result<(), EgressError> {
+ Ok(())
+ }
+}
+
+/// The approval flow over its store, its wake-ups, and whoever it announces
+/// to. Cheap to clone; clones share everything.
+pub struct ToolApprovalService<Store, Signals, Announcer> {
+ inner: Arc<Inner<Store, Signals, Announcer>>,
+}
+
+impl<Store, Signals, Announcer> Clone for ToolApprovalService<Store, Signals, Announcer> {
+ fn clone(&self) -> Self {
+ Self {
+ inner: Arc::clone(&self.inner),
+ }
+ }
+}
+
+struct Inner<Store, Signals, Announcer> {
+ store: Store,
+ signals: Signals,
+ announcer: Announcer,
+ timing: HoldTiming,
+}
+
+/// How long a hold lasts and how often it speaks. Constants in production;
+/// shortened in tests.
+#[derive(Clone, Copy, Debug)]
+pub struct HoldTiming {
+ /// See [`KEEPALIVE_EVERY`].
+ pub keepalive_every: Duration,
+ /// See [`HOLD_LIMIT_WITH_PROGRESS`].
+ pub limit_with_progress: Duration,
+ /// See [`HOLD_LIMIT`].
+ pub limit: Duration,
+}
+
+impl Default for HoldTiming {
+ fn default() -> Self {
+ Self {
+ keepalive_every: KEEPALIVE_EVERY,
+ limit_with_progress: HOLD_LIMIT_WITH_PROGRESS,
+ limit: HOLD_LIMIT,
+ }
+ }
+}
+
+impl<Store, Signals, Announcer> ToolApprovalService<Store, Signals, Announcer>
+where
+ Store: ToolApprovalStore,
+ Signals: ToolApprovalSignals,
+ Announcer: ToolApprovalAnnouncer,
+{
+ /// Build the flow over its adapters.
+ pub fn new(store: Store, signals: Signals, announcer: Announcer) -> Self {
+ Self::with_timing(store, signals, announcer, HoldTiming::default())
+ }
+
+ /// [`Self::new`], holding for other durations.
+ pub fn with_timing(
+ store: Store,
+ signals: Signals,
+ announcer: Announcer,
+ timing: HoldTiming,
+ ) -> Self {
+ Self {
+ inner: Arc::new(Inner {
+ store,
+ signals,
+ announcer,
+ timing,
+ }),
+ }
+ }
+}
+
+/// A tool call made in-process - the in-memory runtime's own Macro tools -
+/// with nothing to stream a hold into.
+#[derive(Clone, Debug)]
+pub struct InProcessCall {
+ /// The session whose agent made it.
+ pub session: AgentSessionId,
+ /// The owner whose approval it waits on.
+ pub owner: MacroUserIdStr<'static>,
+ /// Who prompted the turn it was made in.
+ pub prompter: TurnPrompter,
+ /// `macro`, or the connected app's slug.
+ pub server_slug: String,
+ /// What a person calls the server.
+ pub server_name: String,
+ /// The tool called.
+ pub tool_name: String,
+ /// What it was called with.
+ pub arguments: serde_json::Value,
+}
+
+impl<Store, Signals, Announcer> ToolApprovalService<Store, Signals, Announcer>
+where
+ Store: ToolApprovalStore,
+ Signals: ToolApprovalSignals,
+ Announcer: ToolApprovalAnnouncer,
+{
+ /// Hold `call` until it is resolved, and say how. Dropping the future
+ /// cancels the hold, which is how a stopped turn gives up on it.
+ pub async fn hold_in_process(
+ &self,
+ call: InProcessCall,
+ ) -> Result<ToolApprovalStatus, EgressError> {
+ if self
+ .inner
+ .is_standing(
+ call.session,
+ &call.prompter,
+ &call.server_slug,
+ &call.tool_name,
+ )
+ .await?
+ {
+ return Ok(ToolApprovalStatus::Approved);
+ }
+ let prompter = call.prompter.clone();
+ let approval = ToolApproval {
+ id: ToolApprovalId::mint(),
+ session: call.session,
+ turn_action_id: call.prompter.action_id,
+ // No JSON-RPC request to name; unique so nothing withdraws it.
+ request_id: serde_json::Value::String(macro_uuid::generate_uuid_v7().to_string()),
+ owner: call.owner.clone(),
+ requested_by: call.prompter.user.clone(),
+ server_slug: call.server_slug,
+ server_name: call.server_name,
+ tool_name: call.tool_name,
+ arguments: call.arguments,
+ status: ToolApprovalStatus::Pending,
+ resolved_by: None,
+ remembered: false,
+ };
+ self.inner.store.insert(&approval).await?;
+ if self.inner.settled_by_standing(&approval, &prompter).await? {
+ return Ok(ToolApprovalStatus::Approved);
+ }
+ tracing::info!(
+ approval = %approval.id,
+ session = %approval.session,
+ tool = %approval.tool_name,
+ "holding an in-process tool call for the owner's approval"
+ );
+ self.inner.announcer.requested(&approval, &call.owner).await;
+
+ let guard = CancelOnDrop {
+ inner: Some(Arc::clone(&self.inner)),
+ id: approval.id,
+ };
+ let resolved = self
+ .inner
+ .await_resolution(&approval, None, call.owner.email_str(), None)
+ .await;
+ guard.disarm();
+ Ok(resolved?.status)
+ }
+}
+
+/// Cancels a held call whose waiter went away before it was resolved.
+struct CancelOnDrop<Store, Signals, Announcer>
+where
+ Store: ToolApprovalStore,
+ Signals: ToolApprovalSignals,
+ Announcer: ToolApprovalAnnouncer,
+{
+ inner: Option<Arc<Inner<Store, Signals, Announcer>>>,
+ id: ToolApprovalId,
+}
+
+impl<Store, Signals, Announcer> CancelOnDrop<Store, Signals, Announcer>
+where
+ Store: ToolApprovalStore,
+ Signals: ToolApprovalSignals,
+ Announcer: ToolApprovalAnnouncer,
+{
+ fn disarm(mut self) {
+ self.inner = None;
+ }
+}
+
+impl<Store, Signals, Announcer> Drop for CancelOnDrop<Store, Signals, Announcer>
+where
+ Store: ToolApprovalStore,
+ Signals: ToolApprovalSignals,
+ Announcer: ToolApprovalAnnouncer,
+{
+ fn drop(&mut self) {
+ if let Some(inner) = self.inner.take() {
+ let id = self.id;
+ tokio::spawn(async move {
+ if let Err(error) = inner.resolve(id, ToolApprovalStatus::Cancelled, None).await {
+ tracing::warn!(error = ?error, approval = %id, "could not cancel an abandoned tool call");
+ }
+ });
+ }
+ }
+}
+
+/// Answering held calls: what the session view's buttons reach.
+pub trait ToolApprovalAnswers: Send + Sync + 'static {
+ /// A person's answer to the held call `id` in `session`. The caller has
+ /// already checked `by` may edit the session.
+ ///
+ /// Only the owner recorded on the approval approves or declines: the
+ /// call spends their access. Anyone with edit access may cancel, which is
+ /// how a turn gets unstuck while the owner is away.
+ fn answer(
+ &self,
+ session: AgentSessionId,
+ id: ToolApprovalId,
+ answer: ApprovalAnswer,
+ by: &MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<ToolApproval, ToolApprovalError>> + Send;
+
+ /// Stop holding every call `session` is waiting on: its turn ended, it
+ /// stopped, or it is being deleted.
+ fn release_session(
+ &self,
+ session: AgentSessionId,
+ ) -> impl Future<Output = Result<(), EgressError>> + Send;
+}
+
+impl<Answers: ToolApprovalAnswers> ToolApprovalAnswers for Arc<Answers> {
+ fn answer(
+ &self,
+ session: AgentSessionId,
+ id: ToolApprovalId,
+ answer: ApprovalAnswer,
+ by: &MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<ToolApproval, ToolApprovalError>> + Send {
+ (**self).answer(session, id, answer, by)
+ }
+
+ fn release_session(
+ &self,
+ session: AgentSessionId,
+ ) -> impl Future<Output = Result<(), EgressError>> + Send {
+ (**self).release_session(session)
+ }
+}
+
+impl<Store, Signals, Announcer> ToolApprovalAnswers
+ for ToolApprovalService<Store, Signals, Announcer>
+where
+ Store: ToolApprovalStore,
+ Signals: ToolApprovalSignals,
+ Announcer: ToolApprovalAnnouncer,
+{
+ async fn answer(
+ &self,
+ session: AgentSessionId,
+ id: ToolApprovalId,
+ answer: ApprovalAnswer,
+ by: &MacroUserIdStr<'static>,
+ ) -> Result<ToolApproval, ToolApprovalError> {
+ let approval = self
+ .inner
+ .store
+ .get(id)
+ .await?
+ .filter(|approval| approval.session == session)
+ .ok_or(ToolApprovalError::NotFound)?;
+ if answer != ApprovalAnswer::Cancel && *by != approval.owner {
+ return Err(ToolApprovalError::NotOwner);
+ }
+ if !approval.status.is_pending() {
+ return Err(ToolApprovalError::NotPending);
+ }
+ if answer == ApprovalAnswer::ApproveAndRemember {
+ return self.inner.approve_for_good(&approval, by).await;
+ }
+ self.inner
+ .resolve(id, answer.status(), Some(by))
+ .await?
+ .ok_or(ToolApprovalError::NotPending)
+ }
+
+ async fn release_session(&self, session: AgentSessionId) -> Result<(), EgressError> {
+ for id in self.inner.store.pending_for_session(session).await? {
+ self.inner
+ .resolve(id, ToolApprovalStatus::Cancelled, None)
+ .await?;
+ }
+ Ok(())
+ }
+}
+
+impl<Store, Signals, Announcer> Inner<Store, Signals, Announcer>
+where
+ Store: ToolApprovalStore,
+ Signals: ToolApprovalSignals,
+ Announcer: ToolApprovalAnnouncer,
+{
+ /// Resolve `id` if it is still pending, and announce the resolution.
+ /// `None` when somebody else resolved it first.
+ async fn resolve(
+ &self,
+ id: ToolApprovalId,
+ status: ToolApprovalStatus,
+ by: Option<&MacroUserIdStr<'static>>,
+ ) -> Result<Option<ToolApproval>, EgressError> {
+ self.settle(id, status, by, false).await
+ }
+
+ /// [`Self::resolve`], recording whether it was approved for good.
+ async fn settle(
+ &self,
+ id: ToolApprovalId,
+ status: ToolApprovalStatus,
+ by: Option<&MacroUserIdStr<'static>>,
+ remembered: bool,
+ ) -> Result<Option<ToolApproval>, EgressError> {
+ let resolved = self.store.resolve(id, status, by, remembered).await?;
+ if let Some(approval) = &resolved {
+ tracing::info!(
+ approval = %approval.id,
+ session = %approval.session,
+ status = approval.status.as_str(),
+ "resolved a held tool call"
+ );
+ self.announcer.resolved(approval).await;
+ }
+ Ok(resolved)
+ }
+
+ /// Whether a standing approval lets whoever prompted the turn make this
+ /// call without asking. Never for a bot on nobody's behalf.
+ async fn is_standing(
+ &self,
+ session: AgentSessionId,
+ prompter: &TurnPrompter,
+ server_slug: &str,
+ tool: &str,
+ ) -> Result<bool, EgressError> {
+ match &prompter.user {
+ Some(user) => {
+ self.store
+ .is_standing(session, user, server_slug, tool)
+ .await
+ }
+ None => Ok(false),
+ }
+ }
+
+ /// Checks again once `approval` is recorded and before anyone is told:
+ /// a standing approval given between the first check and the insert
+ /// either finds the row among those it covers, or is seen here, which
+ /// approves it quietly. Whether it was.
+ async fn settled_by_standing(
+ &self,
+ approval: &ToolApproval,
+ prompter: &TurnPrompter,
+ ) -> Result<bool, EgressError> {
+ if !self
+ .is_standing(
+ approval.session,
+ prompter,
+ &approval.server_slug,
+ &approval.tool_name,
+ )
+ .await?
+ {
+ return Ok(false);
+ }
+ self.store
+ .resolve(approval.id, ToolApprovalStatus::Approved, None, true)
+ .await?;
+ Ok(true)
+ }
+
+ /// Approve `approval` for good: remember what it covers, approve it, and
+ /// approve whatever else the same person is already waiting on that it
+ /// covers, so one answer settles them all.
+ async fn approve_for_good(
+ &self,
+ approval: &ToolApproval,
+ by: &MacroUserIdStr<'static>,
+ ) -> Result<ToolApproval, ToolApprovalError> {
+ let standing =
+ StandingApproval::covering(approval, by).ok_or(ToolApprovalError::NobodyToRemember)?;
+ self.store.remember(&standing).await?;
+ let approved = self
+ .settle(approval.id, ToolApprovalStatus::Approved, Some(by), true)
+ .await?
+ .ok_or(ToolApprovalError::NotPending)?;
+ for covered in self.store.pending_covered_by(&standing).await? {
+ self.settle(covered, ToolApprovalStatus::Approved, Some(by), true)
+ .await?;
+ }
+ Ok(approved)
+ }
+
+ /// Wait until `id` is no longer pending, keeping the client alive on
+ /// `keepalive`, and resolve it as expired at the limit or cancelled when
+ /// the client goes away first. The approval as it was resolved.
+ async fn await_resolution(
+ &self,
+ approval: &ToolApproval,
+ progress_token: Option<&serde_json::Value>,
+ owner: &str,
+ events: Option<&mpsc::Sender<Bytes>>,
+ ) -> Result<ToolApproval, EgressError> {
+ let mut subscription = self.signals.subscribe(approval.id);
+ let limit = if progress_token.is_some() || events.is_none() {
+ self.timing.limit_with_progress
+ } else {
+ self.timing.limit
+ };
+ let deadline = tokio::time::Instant::now() + limit;
+ let mut ticks = 0_u64;
+ loop {
+ // Read after subscribing, so a resolution between the two is
+ // seen here rather than missed.
+ let Some(current) = self.store.get(approval.id).await? else {
+ // Deleted with its session: nobody is left to answer.
+ return Ok(ToolApproval {
+ status: ToolApprovalStatus::Cancelled,
+ ..approval.clone()
+ });
+ };
+ if !current.status.is_pending() {
+ return Ok(current);
+ }
+ let now = tokio::time::Instant::now();
+ if now >= deadline {
+ if let Some(expired) = self
+ .resolve(approval.id, ToolApprovalStatus::Expired, None)
+ .await?
+ {
+ return Ok(expired);
+ }
+ continue;
+ }
+ let tick = (now + self.timing.keepalive_every).min(deadline);
+ let closed = async {
+ match events {
+ Some(events) => events.closed().await,
+ // An in-process caller stops waiting by dropping the
+ // future, which its own guard answers.
+ None => std::future::pending().await,
+ }
+ };
+ tokio::select! {
+ () = subscription.changed() => {}
+ () = closed => {
+ tracing::info!(approval = %approval.id, "the client stopped waiting on a held tool call");
+ if let Some(cancelled) = self
+ .resolve(approval.id, ToolApprovalStatus::Cancelled, None)
+ .await?
+ {
+ return Ok(cancelled);
+ }
+ }
+ () = tokio::time::sleep_until(tick) => {
+ let Some(events) = events else {
+ continue;
+ };
+ ticks += 1;
+ let keepalive = match progress_token {
+ Some(token) => sse_message(&serde_json::json!({
+ "jsonrpc": "2.0",
+ "method": "notifications/progress",
+ "params": {
+ "progressToken": token,
+ "progress": ticks,
+ "message": format!("Waiting for {owner} to approve {}", approval.tool_name),
+ },
+ })),
+ None => Bytes::from_static(b": waiting for the session owner\n\n"),
+ };
+ // A closed stream is noticed on the next pass.
+ let _ = events.send(keepalive).await;
+ }
+ }
+ }
+ }
+
+ /// The whole hold, run beside the response it streams into.
+ async fn run_hold(
+ self: Arc<Self>,
+ call: HeldCall,
+ approval: ToolApproval,
+ events: mpsc::Sender<Bytes>,
+ ) {
+ let owner = call.owner.email_str().to_owned();
+ let tool = approval.tool_name.clone();
+ let id = call.call.id.clone();
+ let resolved = match self
+ .await_resolution(
+ &approval,
+ call.call.progress_token.as_ref(),
+ &owner,
+ Some(&events),
+ )
+ .await
+ {
+ Ok(resolved) => resolved,
+ Err(error) => {
+ tracing::error!(error = ?error, approval = %approval.id, "a held tool call could not be resolved");
+ let text = format!(
+ "{tool} did not run: waiting for {owner} to approve it failed. Tell the person \
+ who asked, and do not try to do the same thing another way."
+ );
+ let _ = events.send(sse_message(&tool_error(&id, &text))).await;
+ return;
+ }
+ };
+
+ match refusal(resolved.status, &owner, &tool) {
+ None => {
+ pass_through(
+ call.forward,
+ call.request,
+ &id,
+ &approval.server_name,
+ &events,
+ )
+ .await;
+ }
+ Some(text) => {
+ let _ = events.send(sse_message(&tool_error(&id, &text))).await;
+ }
+ }
+ }
+}
+
+impl<Store, Signals, Announcer> OwnerApprovals for ToolApprovalService<Store, Signals, Announcer>
+where
+ Store: ToolApprovalStore,
+ Signals: ToolApprovalSignals,
+ Announcer: ToolApprovalAnnouncer,
+{
+ async fn hold(&self, call: HeldCall) -> Result<ProxyResponse, EgressError> {
+ if self
+ .inner
+ .is_standing(
+ call.session,
+ &call.prompter,
+ &call.server_slug,
+ &call.call.name,
+ )
+ .await?
+ {
+ return (call.forward)(call.request).await;
+ }
+ let approval = ToolApproval {
+ id: ToolApprovalId::mint(),
+ session: call.session,
+ turn_action_id: call.prompter.action_id,
+ request_id: call.call.id.clone(),
+ owner: call.owner.clone(),
+ requested_by: call.prompter.user.clone(),
+ server_slug: call.server_slug.clone(),
+ server_name: call.server_name.clone(),
+ tool_name: call.call.name.clone(),
+ arguments: call.call.arguments.clone(),
+ status: ToolApprovalStatus::Pending,
+ resolved_by: None,
+ remembered: false,
+ };
+ self.inner.store.insert(&approval).await?;
+ if self
+ .inner
+ .settled_by_standing(&approval, &call.prompter)
+ .await?
+ {
+ return (call.forward)(call.request).await;
+ }
+ tracing::info!(
+ approval = %approval.id,
+ session = %approval.session,
+ tool = %approval.tool_name,
+ server = %approval.server_slug,
+ "holding a tool call for the owner's approval"
+ );
+ self.inner.announcer.requested(&approval, &call.owner).await;
+
+ let (events, received) = mpsc::channel::<Bytes>(8);
+ // Something goes out at once: a client that sees headers and no
+ // bytes may give up before the first keepalive.
+ let _ = events
+ .send(Bytes::from_static(b": waiting for the session owner\n\n"))
+ .await;
+ tokio::spawn(Arc::clone(&self.inner).run_hold(call, approval, events));
+ Ok(stream_response(received))
+ }
+
+ async fn withdraw(
+ &self,
+ session: AgentSessionId,
+ request_id: &serde_json::Value,
+ ) -> Result<(), EgressError> {
+ if let Some(id) = self
+ .inner
+ .store
+ .pending_for_request(session, request_id)
+ .await?
+ {
+ self.inner
+ .resolve(id, ToolApprovalStatus::Cancelled, None)
+ .await?;
+ }
+ Ok(())
+ }
+}
+
+/// What the model is told instead of the tool's answer, for every outcome
+/// but approval. The wording is ours, plus the owner's email and the tool's
+/// name.
+#[must_use]
+pub fn refusal(status: ToolApprovalStatus, owner: &str, tool: &str) -> Option<String> {
+ match status {
+ ToolApprovalStatus::Approved => None,
+ ToolApprovalStatus::Denied => Some(format!(
+ "{owner} declined this call, so {tool} did not run. Tell the person who asked \
+ that {owner} declined it, and do not try to do the same thing another way."
+ )),
+ ToolApprovalStatus::Cancelled => Some(format!(
+ "This call was cancelled before {owner} approved it, so {tool} did not run. \
+ Tell the person who asked, and do not try to do the same thing another way."
+ )),
+ ToolApprovalStatus::Expired | ToolApprovalStatus::Pending => Some(format!(
+ "{owner} did not approve this call in time, so {tool} did not run. Tell the \
+ person who asked that it needs {owner} to approve it, and stop."
+ )),
+ }
+}
diff --git a/crates/agent_egress/src/domain/approval/model.rs b/crates/agent_egress/src/domain/approval/model.rs
new file mode 100644
index 0000000000..dfc23af1c3
--- /dev/null
+++ b/crates/agent_egress/src/domain/approval/model.rs
@@ -0,0 +1,235 @@
+//! What a held call is, and what a person answers it with.
+
+use std::fmt;
+
+use agent_runtime_protocol::domain::action::AgentActionId;
+use agent_runtime_protocol::domain::tool_approval::{ToolApprovalNotice, ToolApprovalStatus};
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+
+use super::MACRO_SERVER_SLUG;
+use crate::domain::error::EgressError;
+use crate::domain::model::AgentSessionId;
+
+/// Identifies one held call.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub struct ToolApprovalId(Uuid);
+
+impl ToolApprovalId {
+ /// A fresh id, time-ordered.
+ #[must_use]
+ pub fn mint() -> Self {
+ Self(macro_uuid::generate_uuid_v7())
+ }
+
+ /// Wrap a stored id.
+ #[must_use]
+ pub fn from_uuid(id: Uuid) -> Self {
+ Self(id)
+ }
+
+ /// The id as stored.
+ #[must_use]
+ pub fn as_uuid(&self) -> Uuid {
+ self.0
+ }
+}
+
+impl fmt::Display for ToolApprovalId {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ self.0.fmt(formatter)
+ }
+}
+
+/// One held call and where it stands.
+#[derive(Clone, Debug, PartialEq)]
+pub struct ToolApproval {
+ /// Its id.
+ pub id: ToolApprovalId,
+ /// The session whose agent made the call.
+ pub session: AgentSessionId,
+ /// The turn it was made in.
+ pub turn_action_id: AgentActionId,
+ /// The call's JSON-RPC id.
+ pub request_id: serde_json::Value,
+ /// The owner whose access the call spends; the only one who may approve
+ /// or decline it.
+ pub owner: MacroUserIdStr<'static>,
+ /// Who prompted the turn; `None` for a bot on nobody's behalf.
+ pub requested_by: Option<MacroUserIdStr<'static>>,
+ /// `macro`, or the connected app's slug.
+ pub server_slug: String,
+ /// What a person calls the server.
+ pub server_name: String,
+ /// The tool called.
+ pub tool_name: String,
+ /// What it was called with.
+ pub arguments: serde_json::Value,
+ /// Where it stands.
+ pub status: ToolApprovalStatus,
+ /// Who resolved it, when a person did.
+ pub resolved_by: Option<MacroUserIdStr<'static>>,
+ /// Approved for good: the person who asked may make the calls it covers
+ /// without the owner being asked again.
+ pub remembered: bool,
+}
+
+impl ToolApproval {
+ /// The frame the session's log records for this state.
+ #[must_use]
+ pub fn notice(&self) -> ToolApprovalNotice {
+ ToolApprovalNotice {
+ approval_id: self.id.to_string(),
+ server_slug: self.server_slug.clone(),
+ server_name: self.server_name.clone(),
+ tool_name: self.tool_name.clone(),
+ arguments: self.arguments.clone(),
+ requested_by: self
+ .requested_by
+ .as_ref()
+ .map(|user| user.as_ref().to_owned()),
+ status: self.status,
+ resolved_by: self
+ .resolved_by
+ .as_ref()
+ .map(|user| user.as_ref().to_owned()),
+ remembered: self.remembered,
+ }
+ }
+}
+
+/// The owner's "approve, and don't ask me again": one person may make the
+/// calls it covers in one session without the owner being asked each time.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct StandingApproval {
+ /// The session it holds in, for as long as the session lasts.
+ pub session: AgentSessionId,
+ /// Who may make the calls.
+ pub user: MacroUserIdStr<'static>,
+ /// `macro`, or the connected app's slug.
+ pub server_slug: String,
+ /// The one tool covered on Macro's server, which reaches all of the
+ /// owner's data; `None` covers a whole connected app.
+ pub tool_name: Option<String>,
+ /// The owner who said so.
+ pub granted_by: MacroUserIdStr<'static>,
+}
+
+impl StandingApproval {
+ /// What approving `approval` for good covers: the same tool on Macro,
+ /// the whole app otherwise. `None` when no person asked, since there is
+ /// nobody to remember.
+ #[must_use]
+ pub fn covering(approval: &ToolApproval, granted_by: &MacroUserIdStr<'static>) -> Option<Self> {
+ Some(Self {
+ session: approval.session,
+ user: approval.requested_by.clone()?,
+ server_slug: approval.server_slug.clone(),
+ tool_name: (approval.server_slug == MACRO_SERVER_SLUG)
+ .then(|| approval.tool_name.clone()),
+ granted_by: granted_by.clone(),
+ })
+ }
+
+ /// Whether it covers `user` calling `tool` on `server_slug` in `session`.
+ #[must_use]
+ pub fn covers(
+ &self,
+ session: AgentSessionId,
+ user: &MacroUserIdStr<'static>,
+ server_slug: &str,
+ tool: &str,
+ ) -> bool {
+ self.session == session
+ && self.user == *user
+ && self.server_slug == server_slug
+ && self
+ .tool_name
+ .as_deref()
+ .is_none_or(|covered| covered == tool)
+ }
+}
+
+/// What a person answers a held call with.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ApprovalAnswer {
+ /// Let it run.
+ Approve,
+ /// Let it run, and let the same person make the calls it covers in this
+ /// session without asking again.
+ ApproveAndRemember,
+ /// Refuse it.
+ Deny,
+ /// Give up waiting on the owner.
+ Cancel,
+}
+
+impl ApprovalAnswer {
+ pub(super) fn status(self) -> ToolApprovalStatus {
+ match self {
+ Self::Approve | Self::ApproveAndRemember => ToolApprovalStatus::Approved,
+ Self::Deny => ToolApprovalStatus::Denied,
+ Self::Cancel => ToolApprovalStatus::Cancelled,
+ }
+ }
+}
+
+/// Why an answer was refused.
+#[derive(Debug, thiserror::Error)]
+pub enum ToolApprovalError {
+ /// No such approval in this session.
+ #[error("no such tool approval")]
+ NotFound,
+ /// Somebody resolved it first.
+ #[error("the tool approval was already resolved")]
+ NotPending,
+ /// Only the owner may approve or decline.
+ #[error("only the session owner may approve or decline a tool call")]
+ NotOwner,
+ /// A call no person asked for cannot be approved for good.
+ #[error("a call a bot made on nobody's behalf cannot be approved for good")]
+ NobodyToRemember,
+ /// The store failed.
+ #[error(transparent)]
+ Egress(#[from] EgressError),
+}
+
+/// The parts of a `tools/call` the hold reads.
+#[derive(Clone, Debug, PartialEq)]
+pub struct ToolsCall {
+ /// The JSON-RPC id the answer echoes.
+ pub id: serde_json::Value,
+ /// The tool's name.
+ pub name: String,
+ /// Its arguments.
+ pub arguments: serde_json::Value,
+ /// The progress token the client asked to be kept alive under.
+ pub progress_token: Option<serde_json::Value>,
+}
+
+impl ToolsCall {
+ /// Read a `tools/call` request body; `None` for anything else.
+ #[must_use]
+ pub fn parse(body: &[u8]) -> Option<Self> {
+ let value: serde_json::Value = serde_json::from_slice(body).ok()?;
+ if value.get("method")?.as_str()? != crate::domain::model::TOOLS_CALL_METHOD {
+ return None;
+ }
+ let id = value.get("id").filter(|id| !id.is_null())?.clone();
+ let params = value.get("params")?;
+ Some(Self {
+ id,
+ name: params.get("name")?.as_str()?.to_owned(),
+ arguments: params
+ .get("arguments")
+ .cloned()
+ .unwrap_or(serde_json::Value::Null),
+ progress_token: params
+ .get("_meta")
+ .and_then(|meta| meta.get("progressToken"))
+ .filter(|token| !token.is_null())
+ .cloned(),
+ })
+ }
+}
diff --git a/crates/agent_egress/src/domain/approval/stream.rs b/crates/agent_egress/src/domain/approval/stream.rs
new file mode 100644
index 0000000000..fe107db5c2
--- /dev/null
+++ b/crates/agent_egress/src/domain/approval/stream.rs
@@ -0,0 +1,128 @@
+//! The held call's own HTTP response: an event stream that keeps the client
+//! waiting, then carries the tool's answer or why it did not run.
+
+use bytes::Bytes;
+use http::header::{CACHE_CONTROL, CONTENT_TYPE};
+use http::{HeaderValue, StatusCode};
+use http_body_util::{BodyExt, StreamBody};
+use tokio::sync::mpsc;
+
+use super::ForwardOnce;
+use crate::domain::model::{BoxError, ProxyRequest, ProxyResponse};
+
+/// Send the approved call upstream and relay its answer into the stream.
+pub(super) async fn pass_through(
+ forward: ForwardOnce,
+ request: ProxyRequest,
+ id: &serde_json::Value,
+ server_name: &str,
+ events: &mpsc::Sender<Bytes>,
+) {
+ let response = match forward(request).await {
+ Ok(response) => response,
+ Err(error) => {
+ tracing::warn!(error = ?error, "an approved tool call could not reach its upstream");
+ let text = format!("The call was approved, but {server_name} could not be reached.");
+ let _ = events.send(sse_message(&tool_error(id, &text))).await;
+ return;
+ }
+ };
+ if !response.status().is_success() {
+ let text = format!(
+ "The call was approved, but {server_name} answered with HTTP {}.",
+ response.status().as_u16()
+ );
+ let _ = events.send(sse_message(&tool_error(id, &text))).await;
+ return;
+ }
+ let is_event_stream = response
+ .headers()
+ .get(CONTENT_TYPE)
+ .and_then(|value| value.to_str().ok())
+ .is_some_and(|value| value.starts_with("text/event-stream"));
+ let mut body = response.into_body();
+ if is_event_stream {
+ // Already events: relay them as they come.
+ while let Some(frame) = body.frame().await {
+ match frame {
+ Ok(frame) => {
+ if let Ok(data) = frame.into_data()
+ && events.send(data).await.is_err()
+ {
+ return;
+ }
+ }
+ Err(error) => {
+ tracing::warn!(error = %error, "an approved tool call's stream broke");
+ return;
+ }
+ }
+ }
+ return;
+ }
+ let bytes = match body.collect().await {
+ Ok(collected) => collected.to_bytes(),
+ Err(error) => {
+ tracing::warn!(error = %error, "an approved tool call's answer could not be read");
+ return;
+ }
+ };
+ let message = match serde_json::from_slice::<serde_json::Value>(&bytes) {
+ Ok(message) => sse_message(&message),
+ Err(_) => sse_message(&tool_error(
+ id,
+ &format!(
+ "The call was approved, but {server_name} answered with something that is not JSON."
+ ),
+ )),
+ };
+ let _ = events.send(message).await;
+}
+
+/// A tool result the model reads as the tool's own failed answer.
+pub(super) fn tool_error(id: &serde_json::Value, text: &str) -> serde_json::Value {
+ serde_json::json!({
+ "jsonrpc": "2.0",
+ "id": id,
+ "result": {
+ "isError": true,
+ "content": [{ "type": "text", "text": text }],
+ },
+ })
+}
+
+/// One JSON-RPC message as a server-sent event.
+pub(super) fn sse_message(message: &serde_json::Value) -> Bytes {
+ let mut event = b"event: message\ndata: ".to_vec();
+ event.extend(serde_json::to_vec(message).expect("a JSON value serializes"));
+ event.extend(b"\n\n");
+ Bytes::from(event)
+}
+
+pub(super) fn json_response(message: &serde_json::Value) -> ProxyResponse {
+ let bytes = Bytes::from(serde_json::to_vec(message).expect("a JSON value serializes"));
+ let mut response = http::Response::new(
+ http_body_util::Full::new(bytes)
+ .map_err(|never| match never {})
+ .boxed_unsync(),
+ );
+ response
+ .headers_mut()
+ .insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
+ response
+}
+
+pub(super) fn stream_response(received: mpsc::Receiver<Bytes>) -> ProxyResponse {
+ let frames = futures::stream::unfold(received, |mut received| async move {
+ received
+ .recv()
+ .await
+ .map(|bytes| (Ok::<_, BoxError>(http_body::Frame::data(bytes)), received))
+ });
+ let mut response = http::Response::new(StreamBody::new(frames).boxed_unsync());
+ *response.status_mut() = StatusCode::OK;
+ let headers = response.headers_mut();
+ headers.insert(CONTENT_TYPE, HeaderValue::from_static("text/event-stream"));
+ headers.insert(CACHE_CONTROL, HeaderValue::from_static("no-cache"));
+ response
+}
diff --git a/crates/agent_egress/src/domain/approval/test.rs b/crates/agent_egress/src/domain/approval/test.rs
new file mode 100644
index 0000000000..440f7718e1
--- /dev/null
+++ b/crates/agent_egress/src/domain/approval/test.rs
@@ -0,0 +1,720 @@
+use std::sync::Mutex;
+
+use agent_runtime_protocol::domain::action::AgentActionId;
+use http::header::CONTENT_TYPE;
+use http_body_util::{BodyExt, Full};
+use tokio::sync::oneshot;
+
+use super::*;
+use crate::outbound::tool_approvals::{InMemoryToolApprovalStore, InProcessToolApprovalSignals};
+
+type MemoryStore = InMemoryToolApprovalStore;
+
+trait OnlyApproval {
+ fn only(&self) -> ToolApproval;
+}
+
+impl OnlyApproval for MemoryStore {
+ fn only(&self) -> ToolApproval {
+ let all = self.all();
+ assert_eq!(all.len(), 1, "exactly one call was held");
+ all.into_iter().next().unwrap()
+ }
+}
+
+/// One announcement: the state, and the owner when it was a request.
+type Heard = (ToolApprovalStatus, Option<String>);
+
+/// What the announcer heard, in order.
+#[derive(Clone, Default)]
+struct RecordingAnnouncer {
+ heard: Arc<Mutex<Vec<Heard>>>,
+ /// Woken once per call that starts waiting.
+ requested: Arc<tokio::sync::Notify>,
+}
+
+impl RecordingAnnouncer {
+ fn heard(&self) -> Vec<Heard> {
+ self.heard.lock().unwrap().clone()
+ }
+}
+
+impl ToolApprovalAnnouncer for RecordingAnnouncer {
+ async fn requested(&self, approval: &ToolApproval, owner: &MacroUserIdStr<'static>) {
+ self.heard
+ .lock()
+ .unwrap()
+ .push((approval.status, Some(owner.as_ref().to_owned())));
+ self.requested.notify_one();
+ }
+
+ async fn resolved(&self, approval: &ToolApproval) {
+ self.heard.lock().unwrap().push((approval.status, None));
+ }
+}
+
+type Service = ToolApprovalService<MemoryStore, InProcessToolApprovalSignals, RecordingAnnouncer>;
+
+fn service_with(timing: HoldTiming) -> (Service, MemoryStore, RecordingAnnouncer) {
+ let store = MemoryStore::default();
+ let announcer = RecordingAnnouncer::default();
+ let service =
+ ToolApprovalService::with_timing(store.clone(), store.signals(), announcer.clone(), timing);
+ (service, store, announcer)
+}
+
+fn service() -> (Service, MemoryStore, RecordingAnnouncer) {
+ service_with(HoldTiming::default())
+}
+
+fn owner() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").unwrap()
+}
+
+fn asker() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").unwrap()
+}
+
+fn tools_call(progress_token: Option<serde_json::Value>) -> ToolsCall {
+ ToolsCall {
+ id: serde_json::json!(7),
+ name: "ListEmails".to_owned(),
+ arguments: serde_json::json!({ "limit": 5 }),
+ progress_token,
+ }
+}
+
+/// A held call whose forward, once approved, answers with `answer` and
+/// reports the request it was handed.
+fn held(
+ session: AgentSessionId,
+ call: ToolsCall,
+ answer: serde_json::Value,
+) -> (HeldCall, oneshot::Receiver<ProxyRequest>) {
+ let (forwarded, received) = oneshot::channel();
+ let request = http::Request::builder()
+ .method("POST")
+ .uri("https://upstream.example/mcp")
+ .body(
+ Full::new(Bytes::from_static(b"{}"))
+ .map_err(|never| match never {})
+ .boxed_unsync(),
+ )
+ .unwrap();
+ let held = HeldCall {
+ session,
+ owner: owner(),
+ prompter: TurnPrompter {
+ action_id: AgentActionId::mint(),
+ user: Some(asker()),
+ },
+ server_slug: "macro".to_owned(),
+ server_name: "Macro".to_owned(),
+ call,
+ request,
+ forward: Box::new(move |request| {
+ Box::pin(async move {
+ let _ = forwarded.send(request);
+ Ok(json_response(&answer))
+ })
+ }),
+ };
+ (held, received)
+}
+
+/// The next event the held call's stream sends, as text.
+async fn next_event(body: &mut crate::domain::model::ProxyBody) -> String {
+ let frame = body
+ .frame()
+ .await
+ .expect("the stream sends another event")
+ .expect("the stream does not fail");
+ String::from_utf8(frame.into_data().unwrap().to_vec()).unwrap()
+}
+
+/// The JSON-RPC message an event carries.
+fn message(event: &str) -> serde_json::Value {
+ let data = event
+ .strip_prefix("event: message\ndata: ")
+ .and_then(|rest| rest.strip_suffix("\n\n"))
+ .unwrap_or_else(|| panic!("not a message event: {event:?}"));
+ serde_json::from_str(data).unwrap()
+}
+
+fn result_text(message: &serde_json::Value) -> &str {
+ message["result"]["content"][0]["text"].as_str().unwrap()
+}
+
+#[tokio::test]
+async fn an_approved_call_goes_through_and_its_answer_comes_back_on_the_stream() {
+ let (service, store, announcer) = service();
+ let session = AgentSessionId::new();
+ let upstream = serde_json::json!({ "jsonrpc": "2.0", "id": 7, "result": { "content": [] } });
+ let (call, forwarded) = held(session, tools_call(None), upstream.clone());
+
+ let response = service.hold(call).await.unwrap();
+ assert_eq!(
+ response.headers()[CONTENT_TYPE],
+ "text/event-stream",
+ "held calls answer as a stream"
+ );
+ let mut body = response.into_body();
+ assert!(
+ next_event(&mut body).await.starts_with(':'),
+ "bytes go out at once"
+ );
+
+ let pending = store.only();
+ assert_eq!(pending.status, ToolApprovalStatus::Pending);
+ assert_eq!(pending.owner, owner());
+ assert_eq!(pending.requested_by, Some(asker()));
+ assert_eq!(pending.tool_name, "ListEmails");
+ assert_eq!(pending.request_id, serde_json::json!(7));
+
+ let approved = service
+ .answer(session, pending.id, ApprovalAnswer::Approve, &owner())
+ .await
+ .unwrap();
+ assert_eq!(approved.resolved_by, Some(owner()));
+
+ assert_eq!(message(&next_event(&mut body).await), upstream);
+ assert_eq!(
+ forwarded.await.unwrap().uri(),
+ "https://upstream.example/mcp"
+ );
+ assert_eq!(
+ announcer.heard(),
+ [
+ (
+ ToolApprovalStatus::Pending,
+ Some(owner().as_ref().to_owned())
+ ),
+ (ToolApprovalStatus::Approved, None),
+ ]
+ );
+}
+
+#[tokio::test]
+async fn a_declined_call_never_runs_and_says_who_declined() {
+ let (service, store, _announcer) = service();
+ let session = AgentSessionId::new();
+ let (call, forwarded) = held(session, tools_call(None), serde_json::json!({}));
+ let mut body = service.hold(call).await.unwrap().into_body();
+ next_event(&mut body).await;
+
+ service
+ .answer(session, store.only().id, ApprovalAnswer::Deny, &owner())
+ .await
+ .unwrap();
+
+ let answer = message(&next_event(&mut body).await);
+ assert_eq!(answer["id"], 7);
+ assert_eq!(answer["result"]["isError"], true);
+ assert!(result_text(&answer).starts_with("[email protected] declined this call"));
+ assert!(forwarded.await.is_err(), "nothing went upstream");
+}
+
+#[tokio::test]
+async fn only_the_owner_approves_but_an_editor_may_cancel() {
+ let (service, store, _announcer) = service();
+ let session = AgentSessionId::new();
+ let (call, _forwarded) = held(session, tools_call(None), serde_json::json!({}));
+ let mut body = service.hold(call).await.unwrap().into_body();
+ next_event(&mut body).await;
+ let id = store.only().id;
+
+ for answer in [ApprovalAnswer::Approve, ApprovalAnswer::Deny] {
+ assert!(matches!(
+ service.answer(session, id, answer, &asker()).await,
+ Err(ToolApprovalError::NotOwner)
+ ));
+ }
+ assert!(
+ matches!(
+ service
+ .answer(AgentSessionId::new(), id, ApprovalAnswer::Cancel, &asker())
+ .await,
+ Err(ToolApprovalError::NotFound)
+ ),
+ "an approval is only answerable through its own session"
+ );
+
+ service
+ .answer(session, id, ApprovalAnswer::Cancel, &asker())
+ .await
+ .unwrap();
+ let answer = message(&next_event(&mut body).await);
+ assert!(result_text(&answer).starts_with("This call was cancelled"));
+ assert!(
+ matches!(
+ service
+ .answer(session, id, ApprovalAnswer::Approve, &owner())
+ .await,
+ Err(ToolApprovalError::NotPending)
+ ),
+ "the first resolution is the only one"
+ );
+}
+
+#[tokio::test]
+async fn a_call_nobody_answers_expires_and_says_so() {
+ let (service, store, announcer) = service_with(HoldTiming {
+ keepalive_every: Duration::from_millis(5),
+ limit_with_progress: Duration::from_secs(60),
+ limit: Duration::from_millis(30),
+ });
+ let session = AgentSessionId::new();
+ let (call, _forwarded) = held(session, tools_call(None), serde_json::json!({}));
+ let mut body = service.hold(call).await.unwrap().into_body();
+
+ let answer = loop {
+ let event = next_event(&mut body).await;
+ if !event.starts_with(':') {
+ break message(&event);
+ }
+ };
+ assert!(result_text(&answer).starts_with("[email protected] did not approve this call in time"));
+ assert_eq!(store.only().status, ToolApprovalStatus::Expired);
+ assert_eq!(
+ announcer.heard().last(),
+ Some(&(ToolApprovalStatus::Expired, None))
+ );
+}
+
+#[tokio::test]
+async fn a_client_that_asked_for_progress_is_kept_alive_with_it() {
+ let (service, store, _announcer) = service_with(HoldTiming {
+ keepalive_every: Duration::from_millis(5),
+ limit_with_progress: Duration::from_secs(60),
+ limit: Duration::from_millis(1),
+ });
+ let session = AgentSessionId::new();
+ let (call, _forwarded) = held(
+ session,
+ tools_call(Some(serde_json::json!("token-1"))),
+ serde_json::json!({}),
+ );
+ let mut body = service.hold(call).await.unwrap().into_body();
+ next_event(&mut body).await;
+
+ let progress = message(&next_event(&mut body).await);
+ assert_eq!(progress["method"], "notifications/progress");
+ assert_eq!(progress["params"]["progressToken"], "token-1");
+ assert_eq!(progress["params"]["progress"], 1);
+ let progress = message(&next_event(&mut body).await);
+ assert_eq!(
+ progress["params"]["progress"], 2,
+ "progress only ever grows"
+ );
+ assert_eq!(
+ store.only().status,
+ ToolApprovalStatus::Pending,
+ "the shorter limit is for clients that asked for no progress"
+ );
+}
+
+#[tokio::test]
+async fn a_client_that_hangs_up_cancels_its_call() {
+ let (service, store, announcer) = service();
+ let session = AgentSessionId::new();
+ let (call, _forwarded) = held(session, tools_call(None), serde_json::json!({}));
+ drop(service.hold(call).await.unwrap());
+
+ let id = store.only().id;
+ let mut subscription = store.signals().subscribe(id);
+ if store.only().status.is_pending() {
+ subscription.changed().await;
+ }
+ assert_eq!(store.only().status, ToolApprovalStatus::Cancelled);
+ assert_eq!(
+ announcer.heard().last(),
+ Some(&(ToolApprovalStatus::Cancelled, None))
+ );
+}
+
+#[tokio::test]
+async fn the_agent_withdrawing_its_request_cancels_the_hold() {
+ let (service, store, _announcer) = service();
+ let session = AgentSessionId::new();
+ let (call, _forwarded) = held(session, tools_call(None), serde_json::json!({}));
+ let mut body = service.hold(call).await.unwrap().into_body();
+ next_event(&mut body).await;
+
+ service
+ .withdraw(AgentSessionId::new(), &serde_json::json!(7))
+ .await
+ .unwrap();
+ assert!(
+ store.only().status.is_pending(),
+ "another session's id is not this one"
+ );
+
+ service
+ .withdraw(session, &serde_json::json!(7))
+ .await
+ .unwrap();
+ assert!(
+ result_text(&message(&next_event(&mut body).await)).starts_with("This call was cancelled")
+ );
+}
+
+#[tokio::test]
+async fn ending_the_session_releases_every_held_call() {
+ let (service, _store, _announcer) = service();
+ let session = AgentSessionId::new();
+ let (call, _forwarded) = held(session, tools_call(None), serde_json::json!({}));
+ let mut body = service.hold(call).await.unwrap().into_body();
+ next_event(&mut body).await;
+
+ service.release_session(session).await.unwrap();
+ assert!(
+ result_text(&message(&next_event(&mut body).await)).starts_with("This call was cancelled")
+ );
+}
+
+#[tokio::test]
+async fn without_a_way_to_ask_every_held_call_is_refused() {
+ let (call, forwarded) = held(
+ AgentSessionId::new(),
+ tools_call(None),
+ serde_json::json!({}),
+ );
+ let response = RefuseHeldCalls.hold(call).await.unwrap();
+ let body = response.into_body().collect().await.unwrap().to_bytes();
+ let answer: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(answer["id"], 7);
+ assert_eq!(answer["result"]["isError"], true);
+ assert!(result_text(&answer).starts_with("ListEmails did not run."));
+ assert!(forwarded.await.is_err());
+}
+
+#[test]
+fn a_tools_call_is_read_with_its_progress_token() {
+ let call = ToolsCall::parse(
+ br#"{"jsonrpc":"2.0","id":"a","method":"tools/call","params":{"name":"Search","arguments":{"q":"x"},"_meta":{"progressToken":3}}}"#,
+ )
+ .unwrap();
+ assert_eq!(
+ call,
+ ToolsCall {
+ id: serde_json::json!("a"),
+ name: "Search".to_owned(),
+ arguments: serde_json::json!({ "q": "x" }),
+ progress_token: Some(serde_json::json!(3)),
+ }
+ );
+ assert_eq!(
+ ToolsCall::parse(br#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#),
+ None
+ );
+ assert_eq!(
+ ToolsCall::parse(br#"{"jsonrpc":"2.0","method":"tools/call","params":{"name":"x"}}"#),
+ None,
+ "a notification has no answer to hold"
+ );
+}
+
+fn in_process(session: AgentSessionId) -> InProcessCall {
+ InProcessCall {
+ session,
+ owner: owner(),
+ prompter: TurnPrompter {
+ action_id: AgentActionId::mint(),
+ user: Some(asker()),
+ },
+ server_slug: "macro".to_owned(),
+ server_name: "Macro".to_owned(),
+ tool_name: "ListEmails".to_owned(),
+ arguments: serde_json::json!({}),
+ }
+}
+
+#[tokio::test]
+async fn an_in_process_call_waits_for_the_owner_and_says_how_it_ended() {
+ let (service, store, announcer) = service();
+ let session = AgentSessionId::new();
+ let waiting = tokio::spawn({
+ let service = service.clone();
+ async move { service.hold_in_process(in_process(session)).await }
+ });
+ // Held once the owner has been told; answer then.
+ announcer.requested.notified().await;
+ let id = store.only().id;
+ service
+ .answer(session, id, ApprovalAnswer::Deny, &owner())
+ .await
+ .unwrap();
+ assert_eq!(waiting.await.unwrap().unwrap(), ToolApprovalStatus::Denied);
+ assert_eq!(announcer.heard()[0].0, ToolApprovalStatus::Pending);
+}
+
+#[tokio::test]
+async fn abandoning_an_in_process_call_cancels_it() {
+ let (service, store, _announcer) = service();
+ let session = AgentSessionId::new();
+ {
+ let hold = service.hold_in_process(in_process(session));
+ tokio::pin!(hold);
+ // Poll once so the call is recorded, then drop it.
+ let _ = futures::poll!(&mut hold);
+ }
+ let id = store.only().id;
+ let mut subscription = store.signals().subscribe(id);
+ if store.only().status.is_pending() {
+ subscription.changed().await;
+ }
+ assert_eq!(store.only().status, ToolApprovalStatus::Cancelled);
+}
+
+#[test]
+fn only_approval_lets_a_call_run() {
+ assert_eq!(refusal(ToolApprovalStatus::Approved, "[email protected]", "T"), None);
+ for status in [
+ ToolApprovalStatus::Denied,
+ ToolApprovalStatus::Cancelled,
+ ToolApprovalStatus::Expired,
+ ] {
+ assert!(
+ refusal(status, "[email protected]", "T")
+ .unwrap()
+ .contains("T did not run")
+ );
+ }
+}
+
+#[test]
+fn only_public_lookups_on_macro_skip_the_owner() {
+ assert!(!spends_owner_access(MACRO_SERVER_SLUG, "WebSearch"));
+ assert!(!spends_owner_access(MACRO_SERVER_SLUG, "WebFetch"));
+ assert!(spends_owner_access(MACRO_SERVER_SLUG, "ListEmails"));
+ assert!(spends_owner_access(MACRO_SERVER_SLUG, "ReadContent"));
+ assert!(
+ spends_owner_access("linear", "WebSearch"),
+ "a connected app is always the owner's own account"
+ );
+}
+
+/// Hold `call` in-process on a task, and the approval it is waiting on once
+/// the owner has been told.
+async fn waiting_in_process(
+ service: &Service,
+ store: &MemoryStore,
+ announcer: &RecordingAnnouncer,
+ call: InProcessCall,
+) -> (
+ tokio::task::JoinHandle<Result<ToolApprovalStatus, EgressError>>,
+ ToolApprovalId,
+) {
+ let before: Vec<ToolApprovalId> = store.all().iter().map(|approval| approval.id).collect();
+ let waiting = tokio::spawn({
+ let service = service.clone();
+ async move { service.hold_in_process(call).await }
+ });
+ announcer.requested.notified().await;
+ let id = store
+ .all()
+ .into_iter()
+ .find(|approval| !before.contains(&approval.id))
+ .expect("the call was held")
+ .id;
+ (waiting, id)
+}
+
+#[tokio::test]
+async fn approving_for_good_lets_that_person_use_that_macro_tool_without_asking_again() {
+ let (service, store, announcer) = service();
+ let session = AgentSessionId::new();
+ let (waiting, id) = waiting_in_process(&service, &store, &announcer, in_process(session)).await;
+
+ let approved = service
+ .answer(session, id, ApprovalAnswer::ApproveAndRemember, &owner())
+ .await
+ .unwrap();
+ assert_eq!(approved.status, ToolApprovalStatus::Approved);
+ assert!(approved.remembered, "the log says it was approved for good");
+ assert_eq!(
+ waiting.await.unwrap().unwrap(),
+ ToolApprovalStatus::Approved
+ );
+
+ assert_eq!(
+ service.hold_in_process(in_process(session)).await.unwrap(),
+ ToolApprovalStatus::Approved,
+ "the same person calling the same tool runs at once"
+ );
+ assert_eq!(store.all().len(), 1, "and nothing was held for it");
+ assert_eq!(
+ announcer.heard(),
+ [
+ (
+ ToolApprovalStatus::Pending,
+ Some(owner().as_ref().to_owned())
+ ),
+ (ToolApprovalStatus::Approved, None),
+ ],
+ "nobody was asked about the second call"
+ );
+}
+
+#[tokio::test]
+async fn approving_one_macro_tool_for_good_still_asks_about_anything_else() {
+ let (service, store, announcer) = service();
+ let session = AgentSessionId::new();
+ let (waiting, id) = waiting_in_process(&service, &store, &announcer, in_process(session)).await;
+ service
+ .answer(session, id, ApprovalAnswer::ApproveAndRemember, &owner())
+ .await
+ .unwrap();
+ waiting.await.unwrap().unwrap();
+
+ let other_tool = InProcessCall {
+ tool_name: "SendEmail".to_owned(),
+ ..in_process(session)
+ };
+ let (other_tool, _) = waiting_in_process(&service, &store, &announcer, other_tool).await;
+ other_tool.abort();
+
+ let someone_else = InProcessCall {
+ prompter: TurnPrompter {
+ action_id: AgentActionId::mint(),
+ user: Some(MacroUserIdStr::try_from_email("[email protected]").unwrap()),
+ },
+ ..in_process(session)
+ };
+ let (someone_else, _) = waiting_in_process(&service, &store, &announcer, someone_else).await;
+ someone_else.abort();
+
+ let (another_session, _) = waiting_in_process(
+ &service,
+ &store,
+ &announcer,
+ in_process(AgentSessionId::new()),
+ )
+ .await;
+ another_session.abort();
+
+ assert_eq!(store.all().len(), 4, "each of those was held");
+}
+
+#[tokio::test]
+async fn approving_a_connected_app_for_good_covers_all_of_its_tools() {
+ let (service, store, _announcer) = service();
+ let session = AgentSessionId::new();
+ let linear = |call: ToolsCall| {
+ let (held, forwarded) = held(session, call, serde_json::json!({ "jsonrpc": "2.0" }));
+ (
+ HeldCall {
+ server_slug: "linear".to_owned(),
+ server_name: "Linear".to_owned(),
+ ..held
+ },
+ forwarded,
+ )
+ };
+ let (first, _) = linear(tools_call(None));
+ let mut body = service.hold(first).await.unwrap().into_body();
+ next_event(&mut body).await;
+ service
+ .answer(
+ session,
+ store.only().id,
+ ApprovalAnswer::ApproveAndRemember,
+ &owner(),
+ )
+ .await
+ .unwrap();
+
+ let (second, forwarded) = linear(ToolsCall {
+ name: "create_issue".to_owned(),
+ ..tools_call(None)
+ });
+ let response = service.hold(second).await.unwrap();
+ assert_ne!(
+ response
+ .headers()
+ .get(CONTENT_TYPE)
+ .map(|value| value.as_bytes()),
+ Some(b"text/event-stream".as_slice()),
+ "the call is not held"
+ );
+ forwarded.await.expect("it went straight upstream");
+ assert_eq!(store.all().len(), 1, "and nothing was recorded for it");
+}
+
+#[tokio::test]
+async fn approving_for_good_also_approves_what_that_person_is_already_waiting_on() {
+ let (service, store, announcer) = service();
+ let session = AgentSessionId::new();
+ let (first, first_id) =
+ waiting_in_process(&service, &store, &announcer, in_process(session)).await;
+ let (second, _) = waiting_in_process(&service, &store, &announcer, in_process(session)).await;
+ let other_tool = InProcessCall {
+ tool_name: "SendEmail".to_owned(),
+ ..in_process(session)
+ };
+ let (other_tool, other_id) = waiting_in_process(&service, &store, &announcer, other_tool).await;
+
+ service
+ .answer(
+ session,
+ first_id,
+ ApprovalAnswer::ApproveAndRemember,
+ &owner(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(first.await.unwrap().unwrap(), ToolApprovalStatus::Approved);
+ assert_eq!(
+ tokio::time::timeout(Duration::from_secs(5), second)
+ .await
+ .expect("the second call to the same tool did not need its own click")
+ .unwrap()
+ .unwrap(),
+ ToolApprovalStatus::Approved
+ );
+ assert_eq!(
+ store.get(other_id).await.unwrap().unwrap().status,
+ ToolApprovalStatus::Pending,
+ "a call it does not cover still waits"
+ );
+ other_tool.abort();
+}
+
+#[tokio::test]
+async fn only_the_owner_approves_for_good_and_never_for_a_bot() {
+ let (service, store, announcer) = service();
+ let session = AgentSessionId::new();
+ let (waiting, id) = waiting_in_process(&service, &store, &announcer, in_process(session)).await;
+ assert!(matches!(
+ service
+ .answer(session, id, ApprovalAnswer::ApproveAndRemember, &asker())
+ .await,
+ Err(ToolApprovalError::NotOwner)
+ ));
+ waiting.abort();
+
+ let from_a_bot = InProcessCall {
+ prompter: TurnPrompter {
+ action_id: AgentActionId::mint(),
+ user: None,
+ },
+ ..in_process(session)
+ };
+ let (waiting, id) = waiting_in_process(&service, &store, &announcer, from_a_bot).await;
+ assert!(
+ matches!(
+ service
+ .answer(session, id, ApprovalAnswer::ApproveAndRemember, &owner())
+ .await,
+ Err(ToolApprovalError::NobodyToRemember)
+ ),
+ "there is no person to remember"
+ );
+ assert_eq!(
+ store.get(id).await.unwrap().unwrap().status,
+ ToolApprovalStatus::Pending,
+ "and the call still waits for a plain answer"
+ );
+ waiting.abort();
+}
diff --git a/crates/agent_egress/src/domain/mod.rs b/crates/agent_egress/src/domain/mod.rs
index bb31ddf103..8b5eddaeb1 100644
--- a/crates/agent_egress/src/domain/mod.rs
+++ b/crates/agent_egress/src/domain/mod.rs
@@ -1,5 +1,7 @@
//! The domain: what a session may reach, and with whose credentials.
+/// Holding an MCP tool call until the session's owner approves it.
+pub mod approval;
/// Failures a proxied call can end in.
pub mod error;
/// Vocabulary: grants, slugs, targets, and the transport-neutral request and
diff --git a/crates/agent_egress/src/domain/model.rs b/crates/agent_egress/src/domain/model.rs
index 8ac3b78d87..37d2904188 100644
--- a/crates/agent_egress/src/domain/model.rs
+++ b/crates/agent_egress/src/domain/model.rs
@@ -28,6 +28,7 @@ use url::Url;
use crate::domain::error::EgressError;
pub use agent_fold::domain::log::AgentSessionId;
+pub use agent_session::domain::model::TurnPrompter;
#[cfg(test)]
mod test;
@@ -240,9 +241,21 @@ pub struct SessionGrant {
pub repo: Option<RepoSlug>,
/// The apps the agent listed for this session, for naming only.
pub mcp_servers: Vec<McpServerListing>,
+ /// Who prompted the turn the session is running; `None` before its
+ /// first dispatch.
+ pub prompter: Option<TurnPrompter>,
}
impl SessionGrant {
+ /// The prompter of a turn whose MCP tool calls must wait for the
+ /// owner's approval: anyone but the owner, a bot on nobody's behalf
+ /// included. `None` when the owner prompted it, or nobody has yet.
+ pub fn held_prompter(&self) -> Option<&TurnPrompter> {
+ self.prompter
+ .as_ref()
+ .filter(|prompter| prompter.user.as_ref() != Some(&self.owner))
+ }
+
/// What to call `slug` when speaking to the model: the agent's own name
/// for it when the agent listed it, otherwise the slug made readable
/// (`google_sheets` → `Google Sheets`).
diff --git a/crates/agent_egress/src/domain/ports.rs b/crates/agent_egress/src/domain/ports.rs
index 2e4f4d65c2..5b888b5129 100644
--- a/crates/agent_egress/src/domain/ports.rs
+++ b/crates/agent_egress/src/domain/ports.rs
@@ -7,10 +7,13 @@
//! last touches a socket, which is what lets the decisions above it be tested
//! exhaustively without one.
+use agent_runtime_protocol::domain::tool_approval::ToolApprovalStatus;
+
+use crate::domain::approval::{StandingApproval, ToolApproval, ToolApprovalId};
use crate::domain::error::EgressError;
use crate::domain::model::{
- McpDestination, McpResolution, ProxyRequest, ProxyResponse, RepoSlug, SessionGrant,
- SessionToken, UpstreamCall,
+ AgentSessionId, McpDestination, McpResolution, ProxyRequest, ProxyResponse, RepoSlug,
+ SessionGrant, SessionToken, UpstreamCall,
};
use macro_user_id::user_id::MacroUserIdStr;
@@ -87,3 +90,102 @@ pub trait Forwarder: Send + Sync {
request: ProxyRequest,
) -> impl Future<Output = Result<ProxyResponse, EgressError>> + Send;
}
+
+/// Where held tool calls are recorded.
+///
+/// Every resolution is conditional on the row still being pending, which is
+/// what makes the first resolution the only one: an owner's answer racing
+/// the hold's own deadline on another replica cannot both land.
+pub trait ToolApprovalStore: Send + Sync + 'static {
+ /// Record a newly held call.
+ fn insert(
+ &self,
+ approval: &ToolApproval,
+ ) -> impl Future<Output = Result<(), EgressError>> + Send;
+
+ /// Resolve `id` if it is still pending, and wake whoever waits on it.
+ /// `remembered` records an approval given for good. `None` when it was
+ /// not pending or does not exist.
+ fn resolve(
+ &self,
+ id: ToolApprovalId,
+ status: ToolApprovalStatus,
+ resolved_by: Option<&MacroUserIdStr<'static>>,
+ remembered: bool,
+ ) -> impl Future<Output = Result<Option<ToolApproval>, EgressError>> + Send;
+
+ /// The approval `id`, whatever its state.
+ fn get(
+ &self,
+ id: ToolApprovalId,
+ ) -> impl Future<Output = Result<Option<ToolApproval>, EgressError>> + Send;
+
+ /// The pending approval holding `session`'s JSON-RPC request `request_id`.
+ fn pending_for_request(
+ &self,
+ session: AgentSessionId,
+ request_id: &serde_json::Value,
+ ) -> impl Future<Output = Result<Option<ToolApprovalId>, EgressError>> + Send;
+
+ /// Every approval `session` has pending.
+ fn pending_for_session(
+ &self,
+ session: AgentSessionId,
+ ) -> impl Future<Output = Result<Vec<ToolApprovalId>, EgressError>> + Send;
+
+ /// Record an approval given for good. Recording the same one twice is
+ /// not an error.
+ fn remember(
+ &self,
+ standing: &StandingApproval,
+ ) -> impl Future<Output = Result<(), EgressError>> + Send;
+
+ /// Whether a standing approval lets `user` call `tool` on `server_slug`
+ /// in `session` without asking.
+ fn is_standing(
+ &self,
+ session: AgentSessionId,
+ user: &MacroUserIdStr<'static>,
+ server_slug: &str,
+ tool: &str,
+ ) -> impl Future<Output = Result<bool, EgressError>> + Send;
+
+ /// Every pending approval `standing` covers.
+ fn pending_covered_by(
+ &self,
+ standing: &StandingApproval,
+ ) -> impl Future<Output = Result<Vec<ToolApprovalId>, EgressError>> + Send;
+}
+
+/// Wakes a hold when its approval may have been resolved, wherever that
+/// happened.
+pub trait ToolApprovalSignals: Send + Sync + 'static {
+ /// A waiter on one approval.
+ type Subscription: ToolApprovalSubscription;
+
+ /// Start listening for `id`. Registered by the time this returns, so a
+ /// resolution after it is never missed.
+ fn subscribe(&self, id: ToolApprovalId) -> Self::Subscription;
+}
+
+/// A waiter on one approval.
+pub trait ToolApprovalSubscription: Send + 'static {
+ /// Resolves when the approval may have changed. Wakes can be spurious,
+ /// and a waiter re-reads the store either way.
+ fn changed(&mut self) -> impl Future<Output = ()> + Send;
+}
+
+/// Tells people about held calls: the session's viewers see each state in
+/// its log, and the owner is notified when one starts waiting on them.
+/// Best-effort; a failure is the adapter's to log.
+pub trait ToolApprovalAnnouncer: Send + Sync + 'static {
+ /// A call started waiting on `owner`.
+ fn requested(
+ &self,
+ approval: &ToolApproval,
+ owner: &MacroUserIdStr<'static>,
+ ) -> impl Future<Output = ()> + Send;
+
+ /// A held call was resolved.
+ fn resolved(&self, approval: &ToolApproval) -> impl Future<Output = ()> + Send;
+}
diff --git a/crates/agent_egress/src/domain/service.rs b/crates/agent_egress/src/domain/service.rs
index 0175706afc..711acbed34 100644
--- a/crates/agent_egress/src/domain/service.rs
+++ b/crates/agent_egress/src/domain/service.rs
@@ -1,9 +1,14 @@
//! The service itself: verify, resolve, stamp, forward.
+use std::sync::Arc;
+
use http::header::AUTHORIZATION;
use http::{Method, Uri};
use http_body_util::{BodyExt, Full};
+use crate::domain::approval::{
+ HeldCall, MACRO_SERVER_SLUG, OwnerApprovals, RefuseHeldCalls, ToolsCall, spends_owner_access,
+};
use crate::domain::error::EgressError;
use crate::domain::model::{
EgressTarget, MAX_MCP_REQUEST_BYTES, McpDestination, McpResolution, ProxyRequest,
@@ -30,13 +35,17 @@ pub trait EgressService: Send + Sync {
) -> impl Future<Output = Result<ProxyResponse, EgressError>> + Send;
}
-/// The service, over its four ports.
-pub struct EgressServiceImpl<Sessions, Credentials, Tokens, Forward> {
+/// The service, over its ports.
+///
+/// Held tool calls are refused until [`Self::with_owner_approvals`] says how
+/// to ask the owner, so a proxy wired without approvals fails closed.
+pub struct EgressServiceImpl<Sessions, Credentials, Tokens, Forward, Approvals = RefuseHeldCalls> {
sessions: Sessions,
credentials: Credentials,
tokens: Tokens,
- forward: Forward,
+ forward: Arc<Forward>,
preview_mcp: Option<(url::Url, bool)>,
+ approvals: Approvals,
}
impl<Sessions, Credentials, Tokens, Forward>
@@ -74,19 +83,41 @@ where
sessions,
credentials,
tokens,
- forward,
+ forward: Arc::new(forward),
preview_mcp: None,
+ approvals: RefuseHeldCalls,
+ }
+ }
+}
+
+impl<Sessions, Credentials, Tokens, Forward, Approvals>
+ EgressServiceImpl<Sessions, Credentials, Tokens, Forward, Approvals>
+{
+ /// Hold the tool calls of turns somebody other than the owner prompted
+ /// with `approvals`.
+ pub fn with_owner_approvals<Next>(
+ self,
+ approvals: Next,
+ ) -> EgressServiceImpl<Sessions, Credentials, Tokens, Forward, Next> {
+ EgressServiceImpl {
+ sessions: self.sessions,
+ credentials: self.credentials,
+ tokens: self.tokens,
+ forward: self.forward,
+ preview_mcp: self.preview_mcp,
+ approvals,
}
}
}
-impl<Sessions, Credentials, Tokens, Forward> EgressService
- for EgressServiceImpl<Sessions, Credentials, Tokens, Forward>
+impl<Sessions, Credentials, Tokens, Forward, Approvals> EgressService
+ for EgressServiceImpl<Sessions, Credentials, Tokens, Forward, Approvals>
where
Sessions: SessionAuthority,
Credentials: McpCredentials,
Tokens: GithubTokens,
- Forward: Forwarder,
+ Forward: Forwarder + 'static,
+ Approvals: OwnerApprovals,
{
#[tracing::instrument(skip_all, err, fields(
destination = ?target,
@@ -253,6 +284,63 @@ where
request.headers_mut().insert(name.clone(), value.clone());
}
+ // A turn somebody other than the owner prompted spends the owner's
+ // access only with their say-so, one tool call at a time. Checked
+ // last, so the held request is already addressed and stamped, and an
+ // app the owner has not connected was answered above without asking
+ // anyone - nothing would run.
+ if let (EgressTarget::McpServer(destination), Some(prompter)) =
+ (&target, grant.held_prompter())
+ && !matches!(destination, McpDestination::Preview)
+ && *request.method() == Method::POST
+ {
+ let (parts, bytes) = read_mcp_body(request).await?;
+ let (server_slug, server_name) = match destination {
+ // Session-scoped previews spend nobody's access; exempt above.
+ McpDestination::Macro | McpDestination::Preview => {
+ (MACRO_SERVER_SLUG.to_owned(), "Macro".to_owned())
+ }
+ McpDestination::Connected(slug) => {
+ (slug.as_str().to_owned(), grant.display_name(slug))
+ }
+ // Known only by the hash of its URL here; nothing on the path
+ // carries the name the owner gave it.
+ McpDestination::Custom(key) => {
+ (format!("custom-{key}"), "custom MCP server".to_owned())
+ }
+ };
+ if let Some(call) = ToolsCall::parse(&bytes)
+ .filter(|call| spends_owner_access(&server_slug, &call.name))
+ {
+ let forward = Arc::clone(&self.forward);
+ return self
+ .approvals
+ .hold(HeldCall {
+ session: grant.session,
+ owner: grant.owner.clone(),
+ prompter: prompter.clone(),
+ server_slug,
+ server_name,
+ call,
+ request: ProxyRequest::from_parts(parts, full_body(bytes)),
+ forward: Box::new(move |request| {
+ Box::pin(async move {
+ let mut response = forward.forward(request).await?;
+ sanitize_response_headers(response.headers_mut());
+ Ok(response)
+ })
+ }),
+ })
+ .await;
+ }
+ // The agent giving up on a call it is waiting on: the hold has to
+ // hear it too, or the owner is asked about a call nobody wants.
+ if let Some(request_id) = cancelled_request_id(&bytes) {
+ self.approvals.withdraw(grant.session, &request_id).await?;
+ }
+ request = ProxyRequest::from_parts(parts, full_body(bytes));
+ }
+
// A GET on an MCP target opens the server's event stream. Those are
// the requests a client reopens in a loop when the upstream keeps
// closing them, so its body is watched to its end - the one place the
@@ -314,13 +402,8 @@ enum Unconnected {
/// upstream's place.
type Answer = Box<dyn FnOnce(serde_json::Value) -> ProxyResponse + Send>;
-impl<Sessions, Credentials, Tokens, Forward>
- EgressServiceImpl<Sessions, Credentials, Tokens, Forward>
-where
- Sessions: SessionAuthority,
- Credentials: McpCredentials,
- Tokens: GithubTokens,
- Forward: Forwarder,
+impl<Sessions, Credentials, Tokens, Forward, Approvals>
+ EgressServiceImpl<Sessions, Credentials, Tokens, Forward, Approvals>
{
/// A server the owner has no live grant for: forward everything except
/// `tools/call`.
@@ -339,22 +422,7 @@ where
if *request.method() != Method::POST {
return Ok(Unconnected::Forward(request));
}
- let (parts, mut body) = request.into_parts();
- let mut bytes = Vec::new();
- while let Some(frame) = body.frame().await {
- let frame = frame.map_err(|error| {
- EgressError::Internal(rootcause::report!(
- "could not read an MCP request body: {error}"
- ))
- })?;
- if let Ok(data) = frame.into_data() {
- if bytes.len() + data.len() > MAX_MCP_REQUEST_BYTES {
- return Err(EgressError::RequestTooLarge);
- }
- bytes.extend_from_slice(&data);
- }
- }
- let bytes = bytes::Bytes::from(bytes);
+ let (parts, bytes) = read_mcp_body(request).await?;
if let Some(call) = peek_json_rpc(&bytes)
&& call.method == TOOLS_CALL_METHOD
@@ -364,9 +432,49 @@ where
Ok(Unconnected::Forward(ProxyRequest::from_parts(
parts,
- Full::new(bytes)
- .map_err(|never| match never {})
- .boxed_unsync(),
+ full_body(bytes),
)))
}
}
+
+/// Read an MCP request body the proxy has to look inside, up to
+/// [`MAX_MCP_REQUEST_BYTES`].
+async fn read_mcp_body(
+ request: ProxyRequest,
+) -> Result<(http::request::Parts, bytes::Bytes), EgressError> {
+ let (parts, mut body) = request.into_parts();
+ let mut bytes = Vec::new();
+ while let Some(frame) = body.frame().await {
+ let frame = frame.map_err(|error| {
+ EgressError::Internal(rootcause::report!(
+ "could not read an MCP request body: {error}"
+ ))
+ })?;
+ if let Ok(data) = frame.into_data() {
+ if bytes.len() + data.len() > MAX_MCP_REQUEST_BYTES {
+ return Err(EgressError::RequestTooLarge);
+ }
+ bytes.extend_from_slice(&data);
+ }
+ }
+ Ok((parts, bytes::Bytes::from(bytes)))
+}
+
+fn full_body(bytes: bytes::Bytes) -> crate::domain::model::ProxyBody {
+ Full::new(bytes)
+ .map_err(|never| match never {})
+ .boxed_unsync()
+}
+
+/// The request id a `notifications/cancelled` names.
+fn cancelled_request_id(body: &[u8]) -> Option<serde_json::Value> {
+ let value: serde_json::Value = serde_json::from_slice(body).ok()?;
+ if value.get("method")?.as_str()? != "notifications/cancelled" {
+ return None;
+ }
+ value
+ .get("params")?
+ .get("requestId")
+ .filter(|id| !id.is_null())
+ .cloned()
+}
diff --git a/crates/agent_egress/src/domain/service/test.rs b/crates/agent_egress/src/domain/service/test.rs
index 7137550fc0..e9b79635ce 100644
--- a/crates/agent_egress/src/domain/service/test.rs
+++ b/crates/agent_egress/src/domain/service/test.rs
@@ -53,6 +53,7 @@ impl StubSessions {
owner: owner(),
repo: Some(session_repo()),
mcp_servers: servers,
+ prompter: None,
}))
}
@@ -886,6 +887,7 @@ async fn a_session_owned_outside_macro_gets_nothing() {
owner: MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id"),
repo: Some(session_repo()),
mcp_servers: Vec::new(),
+ prompter: None,
})),
SpyCredentials::knowing(),
SpyGithubTokens::default(),
@@ -1194,6 +1196,7 @@ async fn a_session_without_a_repository_can_use_mcp_but_cannot_mint_git_credenti
owner: owner(),
repo: None,
mcp_servers: Vec::new(),
+ prompter: None,
})),
SpyCredentials::knowing(),
SpyGithubTokens::default(),
@@ -1267,6 +1270,7 @@ async fn non_staff_session_owners_can_share_previews_without_workspace_or_git_ac
session: AgentSessionId::new(),
owner: MacroUserIdStr::try_from_email("[email protected]").unwrap(),
repo: None,
+ prompter: None,
mcp_servers: Vec::new(),
})),
SpyCredentials::knowing(),
@@ -1309,3 +1313,257 @@ async fn non_staff_session_owners_can_share_previews_without_workspace_or_git_ac
assert!(service.credentials.asked.lock().unwrap().is_empty());
assert!(service.tokens.asked.lock().unwrap().is_empty());
}
+
+fn asker() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id")
+}
+
+/// A grant whose running turn `prompter` prompted.
+fn prompted_by(prompter: Option<MacroUserIdStr<'static>>) -> StubSessions {
+ let StubSessions(Ok(mut grant)) =
+ StubSessions::granting_with(selected(&[("datadog", "Datadog")]))
+ else {
+ unreachable!("granting grants");
+ };
+ grant.prompter = Some(crate::domain::model::TurnPrompter {
+ action_id: agent_runtime_protocol::domain::action::AgentActionId::mint(),
+ user: prompter,
+ });
+ StubSessions(Ok(grant))
+}
+
+/// Records what it was asked to hold or withdraw, and answers a hold with a
+/// marker status so a test can tell the hold answered.
+#[derive(Default)]
+struct RecordingApprovals {
+ held: Mutex<
+ Vec<(
+ String,
+ String,
+ crate::domain::approval::ToolsCall,
+ http::request::Parts,
+ )>,
+ >,
+ withdrawn: Mutex<Vec<serde_json::Value>>,
+}
+
+impl OwnerApprovals for RecordingApprovals {
+ async fn hold(&self, call: HeldCall) -> Result<ProxyResponse, EgressError> {
+ let (parts, _body) = call.request.into_parts();
+ self.held
+ .lock()
+ .unwrap()
+ .push((call.server_slug, call.server_name, call.call, parts));
+ let mut response = http::Response::new(empty_body());
+ *response.status_mut() = StatusCode::IM_USED;
+ Ok(response)
+ }
+
+ async fn withdraw(
+ &self,
+ _session: AgentSessionId,
+ request_id: &serde_json::Value,
+ ) -> Result<(), EgressError> {
+ self.withdrawn.lock().unwrap().push(request_id.clone());
+ Ok(())
+ }
+}
+
+const TOOLS_CALL: &str = r#"{"jsonrpc":"2.0","id":9,"method":"tools/call","params":{"name":"search","arguments":{"q":"x"}}}"#;
+
+fn gated(
+ sessions: StubSessions,
+ credentials: SpyCredentials,
+) -> EgressServiceImpl<
+ StubSessions,
+ SpyCredentials,
+ SpyGithubTokens,
+ SpyForwarder,
+ RecordingApprovals,
+> {
+ EgressServiceImpl::new(
+ sessions,
+ credentials,
+ SpyGithubTokens::default(),
+ SpyForwarder::answering(&[]),
+ )
+ .with_owner_approvals(RecordingApprovals::default())
+}
+
+/// The owner's own turn spends their access without asking anyone.
+#[tokio::test]
+async fn a_tool_call_in_a_turn_the_owner_prompted_goes_straight_through() {
+ let service = gated(prompted_by(Some(owner())), SpyCredentials::knowing());
+ let response = service
+ .proxy(
+ &SessionToken::new("token"),
+ datadog(),
+ json_request(TOOLS_CALL),
+ )
+ .await
+ .expect("proxied");
+ assert_eq!(response.status(), StatusCode::ACCEPTED);
+ assert!(service.forward.was_called());
+ assert!(service.approvals.held.lock().unwrap().is_empty());
+}
+
+/// Somebody else's turn holds the call, already addressed and stamped with
+/// the owner's credential, and nothing reaches the upstream yet.
+#[tokio::test]
+async fn a_tool_call_in_a_turn_somebody_else_prompted_is_held_for_the_owner() {
+ let service = gated(prompted_by(Some(asker())), SpyCredentials::knowing());
+ let response = service
+ .proxy(
+ &SessionToken::new("token"),
+ datadog(),
+ json_request(TOOLS_CALL),
+ )
+ .await
+ .expect("held");
+ assert_eq!(response.status(), StatusCode::IM_USED, "the hold answered");
+ assert!(!service.forward.was_called());
+
+ let held = service.approvals.held.lock().unwrap();
+ let [(slug, name, call, parts)] = held.as_slice() else {
+ panic!("one call was held");
+ };
+ assert_eq!((slug.as_str(), name.as_str()), ("datadog", "Datadog"));
+ assert_eq!(call.name, "search");
+ assert_eq!(call.id, serde_json::json!(9));
+ assert_eq!(parts.uri, "https://mcp.example.com/mcp");
+ assert!(
+ parts.headers.contains_key(AUTHORIZATION),
+ "stamped before holding, so approval only has to send it"
+ );
+}
+
+/// A bot acting on nobody's behalf is not the owner either.
+#[tokio::test]
+async fn a_tool_call_in_a_turn_a_bot_prompted_is_held_too() {
+ let service = gated(prompted_by(None), SpyCredentials::knowing());
+ service
+ .proxy(
+ &SessionToken::new("token"),
+ datadog(),
+ json_request(TOOLS_CALL),
+ )
+ .await
+ .expect("held");
+ assert_eq!(service.approvals.held.lock().unwrap().len(), 1);
+}
+
+/// Macro's own server is gated like any connected app, under its own name.
+#[tokio::test]
+async fn a_tool_call_to_macros_own_server_is_held_under_its_name() {
+ let service = gated(prompted_by(Some(asker())), SpyCredentials::knowing());
+ service
+ .proxy(
+ &SessionToken::new("token"),
+ EgressTarget::McpServer(McpDestination::Macro),
+ json_request(TOOLS_CALL),
+ )
+ .await
+ .expect("held");
+ let held = service.approvals.held.lock().unwrap();
+ assert_eq!((held[0].0.as_str(), held[0].1.as_str()), ("macro", "Macro"));
+}
+
+/// Only `tools/call` runs anything; the handshake and listing still flow so
+/// the agent sees its tools.
+#[tokio::test]
+async fn listing_tools_in_a_gated_turn_is_not_held() {
+ let service = gated(prompted_by(Some(asker())), SpyCredentials::knowing());
+ service
+ .proxy(
+ &SessionToken::new("token"),
+ datadog(),
+ json_request(r#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#),
+ )
+ .await
+ .expect("proxied");
+ assert!(service.forward.was_called());
+ assert!(service.approvals.held.lock().unwrap().is_empty());
+}
+
+/// The agent giving up on a held request reaches the hold, and the
+/// notification still goes upstream.
+#[tokio::test]
+async fn a_cancelled_request_is_withdrawn_from_the_hold_and_forwarded() {
+ let service = gated(prompted_by(Some(asker())), SpyCredentials::knowing());
+ service
+ .proxy(
+ &SessionToken::new("token"),
+ datadog(),
+ json_request(
+ r#"{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":9}}"#,
+ ),
+ )
+ .await
+ .expect("proxied");
+ assert_eq!(
+ *service.approvals.withdrawn.lock().unwrap(),
+ [serde_json::json!(9)]
+ );
+ assert!(service.forward.was_called());
+}
+
+/// Nothing would run for an app the owner has not connected, so nobody is
+/// asked: the not-connected answer comes back as before.
+#[tokio::test]
+async fn an_unconnected_app_in_a_gated_turn_is_answered_without_asking() {
+ let service = gated(prompted_by(Some(asker())), SpyCredentials::unconnected());
+ let response = service
+ .proxy(
+ &SessionToken::new("token"),
+ datadog(),
+ json_request(TOOLS_CALL),
+ )
+ .await
+ .expect("answered");
+ let body = body_json(response).await;
+ assert_eq!(body["result"]["isError"], true);
+ assert!(service.approvals.held.lock().unwrap().is_empty());
+ assert!(!service.forward.was_called());
+}
+
+/// A proxy built without approvals fails closed.
+#[tokio::test]
+async fn without_approvals_a_gated_tool_call_is_refused() {
+ let service = EgressServiceImpl::new(
+ prompted_by(Some(asker())),
+ SpyCredentials::knowing(),
+ SpyGithubTokens::default(),
+ SpyForwarder::answering(&[]),
+ );
+ let response = service
+ .proxy(
+ &SessionToken::new("token"),
+ datadog(),
+ json_request(TOOLS_CALL),
+ )
+ .await
+ .expect("answered");
+ let body = body_json(response).await;
+ assert_eq!(body["id"], 9);
+ assert_eq!(body["result"]["isError"], true);
+ assert!(!service.forward.was_called());
+}
+
+/// Looking something up on the public web spends nobody's access, so even a
+/// turn somebody else prompted searches without asking.
+#[tokio::test]
+async fn a_public_web_search_in_a_gated_turn_goes_straight_through() {
+ let service = gated(prompted_by(Some(asker())), SpyCredentials::knowing());
+ service
+ .proxy(
+ &SessionToken::new("token"),
+ EgressTarget::McpServer(McpDestination::Macro),
+ json_request(
+ r#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"WebSearch","arguments":{"input":"rust"}}}"#,
+ ),
+ )
+ .await
+ .expect("proxied");
+ assert!(service.forward.was_called());
+ assert!(service.approvals.held.lock().unwrap().is_empty());
+}
diff --git a/crates/agent_egress/src/lib.rs b/crates/agent_egress/src/lib.rs
index eceb68924c..4fb14818a2 100644
--- a/crates/agent_egress/src/lib.rs
+++ b/crates/agent_egress/src/lib.rs
@@ -58,4 +58,4 @@ pub mod inbound;
/// Adapters this crate reaches the rest of the world through.
pub mod outbound;
-pub use domain::{error, model, ports, service};
+pub use domain::{approval, error, model, ports, service};
diff --git a/crates/agent_egress/src/outbound/mod.rs b/crates/agent_egress/src/outbound/mod.rs
index ea79c5da99..54a3f2f0c9 100644
--- a/crates/agent_egress/src/outbound/mod.rs
+++ b/crates/agent_egress/src/outbound/mod.rs
@@ -17,3 +17,6 @@ pub mod session_authority;
/// Executing an already-addressed, already-stamped request.
pub mod forwarder;
+
+/// Held tool calls in Postgres, and the NOTIFY that wakes their holds.
+pub mod tool_approvals;
diff --git a/crates/agent_egress/src/outbound/session_authority.rs b/crates/agent_egress/src/outbound/session_authority.rs
index c612a07a4a..cdc561204b 100644
--- a/crates/agent_egress/src/outbound/session_authority.rs
+++ b/crates/agent_egress/src/outbound/session_authority.rs
@@ -105,11 +105,25 @@ where
})
.collect();
+ // Read beside the row rather than off it: the harness writes it at
+ // every dispatch, and a call is judged by who prompted the turn
+ // running now.
+ let prompter = self
+ .sessions
+ .turn_prompter(session.id)
+ .await
+ .map_err(|error| {
+ EgressError::Internal(rootcause::report!(
+ "could not read who prompted the turn: {error}"
+ ))
+ })?;
+
Ok(SessionGrant {
session: session.id,
owner,
repo,
mcp_servers,
+ prompter,
})
}
}
diff --git a/crates/agent_egress/src/outbound/tool_approvals.rs b/crates/agent_egress/src/outbound/tool_approvals.rs
new file mode 100644
index 0000000000..58258f8626
--- /dev/null
+++ b/crates/agent_egress/src/outbound/tool_approvals.rs
@@ -0,0 +1,533 @@
+//! Held tool calls in Postgres, and the NOTIFY that wakes their holds.
+//!
+//! A resolution is an `UPDATE ... WHERE status = 'pending'` that notifies in
+//! the same statement, so the row and the wake-up cannot disagree: a hold on
+//! any replica hears about a resolution made on any other, and re-reads the
+//! row to learn what it was.
+
+use std::sync::Arc;
+
+use agent_runtime_protocol::domain::action::AgentActionId;
+use agent_runtime_protocol::domain::tool_approval::ToolApprovalStatus;
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+use sqlx::PgPool;
+use sqlx::postgres::PgListener;
+use tokio::sync::broadcast;
+
+use crate::domain::approval::{StandingApproval, ToolApproval, ToolApprovalId};
+use crate::domain::error::EgressError;
+use crate::domain::model::AgentSessionId;
+use crate::domain::ports::{ToolApprovalSignals, ToolApprovalStore, ToolApprovalSubscription};
+
+/// The channel resolutions are announced on; the payload is the approval id.
+pub const TOOL_APPROVAL_CHANNEL: &str = "agent_session_tool_approval";
+
+fn storage(error: impl std::fmt::Display) -> EgressError {
+ EgressError::Internal(rootcause::report!("tool approval storage failed: {error}"))
+}
+
+struct Row {
+ id: Uuid,
+ agent_session_id: Uuid,
+ turn_action_id: Uuid,
+ request_id: serde_json::Value,
+ owner_id: MacroUserIdStr<'static>,
+ requested_by: Option<MacroUserIdStr<'static>>,
+ server_slug: String,
+ server_name: String,
+ tool_name: String,
+ arguments: serde_json::Value,
+ status: String,
+ resolved_by: Option<MacroUserIdStr<'static>>,
+ remembered: bool,
+}
+
+impl Row {
+ fn into_approval(self) -> Result<ToolApproval, EgressError> {
+ Ok(ToolApproval {
+ id: ToolApprovalId::from_uuid(self.id),
+ session: AgentSessionId::new_from_uuid(self.agent_session_id),
+ turn_action_id: AgentActionId::from_uuid(self.turn_action_id),
+ request_id: self.request_id,
+ owner: self.owner_id,
+ requested_by: self.requested_by,
+ server_slug: self.server_slug,
+ server_name: self.server_name,
+ tool_name: self.tool_name,
+ arguments: self.arguments,
+ status: ToolApprovalStatus::parse(&self.status)
+ .ok_or_else(|| storage(format!("unknown status {:?}", self.status)))?,
+ resolved_by: self.resolved_by,
+ remembered: self.remembered,
+ })
+ }
+}
+
+/// [`ToolApprovalStore`] over the `agent_session_tool_approval` table.
+#[derive(Clone)]
+pub struct PgToolApprovalStore {
+ pool: PgPool,
+}
+
+impl PgToolApprovalStore {
+ /// Build the store over `pool`.
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+
+impl ToolApprovalStore for PgToolApprovalStore {
+ async fn insert(&self, approval: &ToolApproval) -> Result<(), EgressError> {
+ sqlx::query!(
+ r#"
+ INSERT INTO agent_session_tool_approval (
+ id, agent_session_id, turn_action_id, request_id, owner_id, requested_by,
+ server_slug, server_name, tool_name, arguments, status
+ )
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
+ "#,
+ approval.id.as_uuid(),
+ approval.session.as_uuid(),
+ approval.turn_action_id.as_uuid(),
+ approval.request_id,
+ approval.owner.as_ref(),
+ approval.requested_by.as_ref().map(|user| user.as_ref()),
+ approval.server_slug,
+ approval.server_name,
+ approval.tool_name,
+ approval.arguments,
+ approval.status.as_str(),
+ )
+ .execute(&self.pool)
+ .await
+ .map_err(storage)?;
+ Ok(())
+ }
+
+ async fn resolve(
+ &self,
+ id: ToolApprovalId,
+ status: ToolApprovalStatus,
+ resolved_by: Option<&MacroUserIdStr<'static>>,
+ remembered: bool,
+ ) -> Result<Option<ToolApproval>, EgressError> {
+ let row = sqlx::query_as!(
+ Row,
+ r#"
+ WITH resolved AS (
+ UPDATE agent_session_tool_approval
+ SET status = $2, resolved_by = $3, resolved_at = now(), remembered = $5
+ WHERE id = $1 AND status = 'pending'
+ RETURNING *
+ )
+ SELECT
+ resolved.id AS "id!",
+ resolved.agent_session_id AS "agent_session_id!",
+ resolved.turn_action_id AS "turn_action_id!",
+ resolved.request_id AS "request_id!",
+ resolved.owner_id AS "owner_id!: MacroUserIdStr<'static>",
+ resolved.requested_by AS "requested_by: MacroUserIdStr<'static>",
+ resolved.server_slug AS "server_slug!",
+ resolved.server_name AS "server_name!",
+ resolved.tool_name AS "tool_name!",
+ resolved.arguments AS "arguments!",
+ resolved.status AS "status!",
+ resolved.resolved_by AS "resolved_by: MacroUserIdStr<'static>",
+ resolved.remembered AS "remembered!"
+ FROM resolved, pg_notify($4, resolved.id::text)
+ "#,
+ id.as_uuid(),
+ status.as_str(),
+ resolved_by.map(|user| user.as_ref()),
+ TOOL_APPROVAL_CHANNEL,
+ remembered,
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .map_err(storage)?;
+ row.map(Row::into_approval).transpose()
+ }
+
+ async fn get(&self, id: ToolApprovalId) -> Result<Option<ToolApproval>, EgressError> {
+ let row = sqlx::query_as!(
+ Row,
+ r#"
+ SELECT
+ id, agent_session_id, turn_action_id, request_id,
+ owner_id AS "owner_id: MacroUserIdStr<'static>",
+ requested_by AS "requested_by: MacroUserIdStr<'static>",
+ server_slug, server_name, tool_name, arguments, status,
+ resolved_by AS "resolved_by: MacroUserIdStr<'static>",
+ remembered
+ FROM agent_session_tool_approval
+ WHERE id = $1
+ "#,
+ id.as_uuid(),
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .map_err(storage)?;
+ row.map(Row::into_approval).transpose()
+ }
+
+ async fn pending_for_request(
+ &self,
+ session: AgentSessionId,
+ request_id: &serde_json::Value,
+ ) -> Result<Option<ToolApprovalId>, EgressError> {
+ let id = sqlx::query_scalar!(
+ r#"
+ SELECT id FROM agent_session_tool_approval
+ WHERE agent_session_id = $1 AND request_id = $2 AND status = 'pending'
+ ORDER BY created_at DESC
+ LIMIT 1
+ "#,
+ session.as_uuid(),
+ request_id,
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .map_err(storage)?;
+ Ok(id.map(ToolApprovalId::from_uuid))
+ }
+
+ async fn pending_for_session(
+ &self,
+ session: AgentSessionId,
+ ) -> Result<Vec<ToolApprovalId>, EgressError> {
+ let ids = sqlx::query_scalar!(
+ r#"
+ SELECT id FROM agent_session_tool_approval
+ WHERE agent_session_id = $1 AND status = 'pending'
+ "#,
+ session.as_uuid(),
+ )
+ .fetch_all(&self.pool)
+ .await
+ .map_err(storage)?;
+ Ok(ids.into_iter().map(ToolApprovalId::from_uuid).collect())
+ }
+
+ async fn remember(&self, standing: &StandingApproval) -> Result<(), EgressError> {
+ sqlx::query!(
+ r#"
+ INSERT INTO agent_session_tool_standing_approval (
+ agent_session_id, user_id, server_slug, tool_name, granted_by
+ )
+ VALUES ($1, $2, $3, $4, $5)
+ ON CONFLICT (agent_session_id, user_id, server_slug, (COALESCE(tool_name, '')))
+ DO NOTHING
+ "#,
+ standing.session.as_uuid(),
+ standing.user.as_ref(),
+ standing.server_slug,
+ standing.tool_name,
+ standing.granted_by.as_ref(),
+ )
+ .execute(&self.pool)
+ .await
+ .map_err(storage)?;
+ Ok(())
+ }
+
+ async fn is_standing(
+ &self,
+ session: AgentSessionId,
+ user: &MacroUserIdStr<'static>,
+ server_slug: &str,
+ tool: &str,
+ ) -> Result<bool, EgressError> {
+ let standing = sqlx::query_scalar!(
+ r#"
+ SELECT EXISTS (
+ SELECT 1 FROM agent_session_tool_standing_approval
+ WHERE agent_session_id = $1 AND user_id = $2 AND server_slug = $3
+ AND (tool_name IS NULL OR tool_name = $4)
+ ) AS "standing!"
+ "#,
+ session.as_uuid(),
+ user.as_ref(),
+ server_slug,
+ tool,
+ )
+ .fetch_one(&self.pool)
+ .await
+ .map_err(storage)?;
+ Ok(standing)
+ }
+
+ async fn pending_covered_by(
+ &self,
+ standing: &StandingApproval,
+ ) -> Result<Vec<ToolApprovalId>, EgressError> {
+ let ids = sqlx::query_scalar!(
+ r#"
+ SELECT id FROM agent_session_tool_approval
+ WHERE agent_session_id = $1 AND requested_by = $2 AND server_slug = $3
+ AND ($4::text IS NULL OR tool_name = $4) AND status = 'pending'
+ "#,
+ standing.session.as_uuid(),
+ standing.user.as_ref(),
+ standing.server_slug,
+ standing.tool_name,
+ )
+ .fetch_all(&self.pool)
+ .await
+ .map_err(storage)?;
+ Ok(ids.into_iter().map(ToolApprovalId::from_uuid).collect())
+ }
+}
+
+/// [`ToolApprovalSignals`] over `LISTEN`, fanned out in process.
+///
+/// One listener connection per process, whatever the number of holds. A
+/// dropped connection loses the notifications sent while it was down, which
+/// costs a hold no more than its next keepalive: it re-reads the row then.
+#[derive(Clone)]
+pub struct PgToolApprovalSignals {
+ resolved: broadcast::Sender<Uuid>,
+}
+
+impl PgToolApprovalSignals {
+ /// Start listening. The listener runs until the process exits.
+ pub fn spawn(pool: PgPool) -> Self {
+ let (resolved, _) = broadcast::channel(256);
+ let sender = resolved.clone();
+ tokio::spawn(async move {
+ loop {
+ if let Err(error) = listen(&pool, &sender).await {
+ tracing::warn!(error = %error, "tool approval listener failed; reconnecting");
+ }
+ tokio::time::sleep(std::time::Duration::from_secs(1)).await;
+ }
+ });
+ Self { resolved }
+ }
+}
+
+async fn listen(pool: &PgPool, resolved: &broadcast::Sender<Uuid>) -> Result<(), sqlx::Error> {
+ let mut listener = PgListener::connect_with(pool).await?;
+ listener.listen(TOOL_APPROVAL_CHANNEL).await?;
+ loop {
+ let notification = listener.recv().await?;
+ if let Ok(id) = notification.payload().parse::<Uuid>() {
+ // Nobody listening is not an error: no hold is waiting.
+ let _ = resolved.send(id);
+ }
+ }
+}
+
+impl ToolApprovalSignals for PgToolApprovalSignals {
+ type Subscription = BroadcastSubscription;
+
+ fn subscribe(&self, id: ToolApprovalId) -> BroadcastSubscription {
+ BroadcastSubscription {
+ id: id.as_uuid(),
+ receiver: self.resolved.subscribe(),
+ }
+ }
+}
+
+/// A waiter on one approval id among every resolution the process hears.
+pub struct BroadcastSubscription {
+ id: Uuid,
+ receiver: broadcast::Receiver<Uuid>,
+}
+
+impl ToolApprovalSubscription for BroadcastSubscription {
+ async fn changed(&mut self) {
+ loop {
+ match self.receiver.recv().await {
+ Ok(id) if id == self.id => return,
+ Ok(_) => {}
+ // Missed some: this one may be among them.
+ Err(broadcast::error::RecvError::Lagged(_)) => return,
+ // The listener is gone; the hold's keepalive re-reads.
+ Err(broadcast::error::RecvError::Closed) => {
+ std::future::pending::<()>().await;
+ }
+ }
+ }
+ }
+}
+
+/// Signals within one process, for tests and single-process tooling.
+#[derive(Clone, Default)]
+pub struct InProcessToolApprovalSignals {
+ resolved: Arc<std::sync::OnceLock<broadcast::Sender<Uuid>>>,
+}
+
+impl InProcessToolApprovalSignals {
+ fn sender(&self) -> &broadcast::Sender<Uuid> {
+ self.resolved.get_or_init(|| broadcast::channel(256).0)
+ }
+
+ /// Wake whoever waits on `id`.
+ pub fn notify(&self, id: ToolApprovalId) {
+ let _ = self.sender().send(id.as_uuid());
+ }
+}
+
+impl ToolApprovalSignals for InProcessToolApprovalSignals {
+ type Subscription = BroadcastSubscription;
+
+ fn subscribe(&self, id: ToolApprovalId) -> BroadcastSubscription {
+ BroadcastSubscription {
+ id: id.as_uuid(),
+ receiver: self.sender().subscribe(),
+ }
+ }
+}
+
+/// [`ToolApprovalStore`] in memory, waking its own signals: tests and
+/// single-process tooling. Clones share one store.
+#[derive(Clone, Default)]
+pub struct InMemoryToolApprovalStore {
+ rows: Arc<std::sync::Mutex<std::collections::HashMap<ToolApprovalId, ToolApproval>>>,
+ standing: Arc<std::sync::Mutex<Vec<StandingApproval>>>,
+ signals: InProcessToolApprovalSignals,
+}
+
+impl InMemoryToolApprovalStore {
+ /// An empty store.
+ #[must_use]
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// The signals its resolutions wake.
+ #[must_use]
+ pub fn signals(&self) -> InProcessToolApprovalSignals {
+ self.signals.clone()
+ }
+
+ /// Every approval, in no particular order.
+ #[must_use]
+ pub fn all(&self) -> Vec<ToolApproval> {
+ self.rows
+ .lock()
+ .expect("tool approvals poisoned")
+ .values()
+ .cloned()
+ .collect()
+ }
+}
+
+impl ToolApprovalStore for InMemoryToolApprovalStore {
+ async fn insert(&self, approval: &ToolApproval) -> Result<(), EgressError> {
+ self.rows
+ .lock()
+ .expect("tool approvals poisoned")
+ .insert(approval.id, approval.clone());
+ Ok(())
+ }
+
+ async fn resolve(
+ &self,
+ id: ToolApprovalId,
+ status: ToolApprovalStatus,
+ resolved_by: Option<&MacroUserIdStr<'static>>,
+ remembered: bool,
+ ) -> Result<Option<ToolApproval>, EgressError> {
+ let resolved = {
+ let mut rows = self.rows.lock().expect("tool approvals poisoned");
+ let Some(row) = rows.get_mut(&id).filter(|row| row.status.is_pending()) else {
+ return Ok(None);
+ };
+ row.status = status;
+ row.resolved_by = resolved_by.cloned();
+ row.remembered = remembered;
+ row.clone()
+ };
+ self.signals.notify(id);
+ Ok(Some(resolved))
+ }
+
+ async fn get(&self, id: ToolApprovalId) -> Result<Option<ToolApproval>, EgressError> {
+ Ok(self
+ .rows
+ .lock()
+ .expect("tool approvals poisoned")
+ .get(&id)
+ .cloned())
+ }
+
+ async fn pending_for_request(
+ &self,
+ session: AgentSessionId,
+ request_id: &serde_json::Value,
+ ) -> Result<Option<ToolApprovalId>, EgressError> {
+ Ok(self
+ .rows
+ .lock()
+ .expect("tool approvals poisoned")
+ .values()
+ .find(|row| {
+ row.session == session && row.request_id == *request_id && row.status.is_pending()
+ })
+ .map(|row| row.id))
+ }
+
+ async fn pending_for_session(
+ &self,
+ session: AgentSessionId,
+ ) -> Result<Vec<ToolApprovalId>, EgressError> {
+ Ok(self
+ .rows
+ .lock()
+ .expect("tool approvals poisoned")
+ .values()
+ .filter(|row| row.session == session && row.status.is_pending())
+ .map(|row| row.id)
+ .collect())
+ }
+
+ async fn remember(&self, standing: &StandingApproval) -> Result<(), EgressError> {
+ let mut all = self.standing.lock().expect("standing approvals poisoned");
+ let same = |held: &StandingApproval| {
+ held.session == standing.session
+ && held.user == standing.user
+ && held.server_slug == standing.server_slug
+ && held.tool_name == standing.tool_name
+ };
+ if !all.iter().any(same) {
+ all.push(standing.clone());
+ }
+ Ok(())
+ }
+
+ async fn is_standing(
+ &self,
+ session: AgentSessionId,
+ user: &MacroUserIdStr<'static>,
+ server_slug: &str,
+ tool: &str,
+ ) -> Result<bool, EgressError> {
+ Ok(self
+ .standing
+ .lock()
+ .expect("standing approvals poisoned")
+ .iter()
+ .any(|standing| standing.covers(session, user, server_slug, tool)))
+ }
+
+ async fn pending_covered_by(
+ &self,
+ standing: &StandingApproval,
+ ) -> Result<Vec<ToolApprovalId>, EgressError> {
+ Ok(self
+ .rows
+ .lock()
+ .expect("tool approvals poisoned")
+ .values()
+ .filter(|row| {
+ row.status.is_pending()
+ && row.requested_by.as_ref().is_some_and(|user| {
+ standing.covers(row.session, user, &row.server_slug, &row.tool_name)
+ })
+ })
+ .map(|row| row.id)
+ .collect())
+ }
+}
diff --git a/crates/agent_harness/container/SYSTEM.md b/crates/agent_harness/container/SYSTEM.md
index 312a97bb10..fe98f3a7c7 100644
--- a/crates/agent_harness/container/SYSTEM.md
+++ b/crates/agent_harness/container/SYSTEM.md
@@ -10,3 +10,4 @@ General rules:
- Inspect existing code before making changes.
- Keep changes focused on the user's request.
- Run relevant formatting, checks, and tests before reporting completion.
+- Every prompt opens with a private context block naming the session's owner, whose access you act with, and who sent the prompt. Follow its note on what a prompt from someone else may do.
diff --git a/crates/agent_harness/src/domain/model.rs b/crates/agent_harness/src/domain/model.rs
index 9b8d4ed479..f01e10709c 100644
--- a/crates/agent_harness/src/domain/model.rs
+++ b/crates/agent_harness/src/domain/model.rs
@@ -450,6 +450,18 @@ pub struct MarkedPassage {
pub surrounding_text: String,
}
+/// Whose access a session runs with, and who sent the prompt being composed.
+///
+/// Named to the agent on every prompt so it can tell the session's owner
+/// from anyone else who may drive it.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct PromptPeople {
+ /// The session's owner.
+ pub owner: MacroUserIdStr<'static>,
+ /// The prompt's sender; absent when a bot sent it on nobody's behalf.
+ pub sender: Option<MacroUserIdStr<'static>>,
+}
+
/// What the conversation an agent was summoned from contributes to its prompt.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ConversationContext {
diff --git a/crates/agent_harness/src/domain/notifications.rs b/crates/agent_harness/src/domain/notifications.rs
index e677d29605..629f46c3a5 100644
--- a/crates/agent_harness/src/domain/notifications.rs
+++ b/crates/agent_harness/src/domain/notifications.rs
@@ -224,6 +224,39 @@ fn plan_waiting(waiting: &WaitingForInputMetadata, is_coding: bool) -> Vec<Plann
})]
}
+/// A tool call held for the owner's approval: only the owner hears, since
+/// only they can answer it. Filed as the waiting-for-input kind - the owner
+/// is being asked something, and every surface already opens the session
+/// from it - under an id of its own, so one held call is one notification
+/// however many turns ask.
+#[must_use]
+pub fn plan_tool_approval(
+ identity: &SessionIdentity,
+ approval_id: Uuid,
+ requested_by: Option<&MacroUserIdStr<'static>>,
+ server_name: &str,
+ tool_name: &str,
+) -> PlannedNotification {
+ let (entity, secondary_entity) = entities(identity);
+ let asker = requested_by.map_or_else(
+ || "A bot".to_owned(),
+ |user| macro_user_id::email::ReadEmailParts::local_part(&user.email_part()).to_owned(),
+ );
+ PlannedNotification::WaitingForInput(Notify {
+ notification_id: tool_approval_notification_id(identity.session_id.as_uuid(), approval_id),
+ entity,
+ secondary_entity,
+ recipients: vec![identity.owner_id.clone()],
+ metadata: AgentSessionWaitingForInputMetadata {
+ session: session_ref(identity, None),
+ turn: 0,
+ question: format!(
+ "{asker} asked it to use {server_name} {tool_name} with your access. Approve or decline it."
+ ),
+ },
+ })
+}
+
fn plan_mentioned(mentioned: &SessionMentionedMetadata) -> Vec<PlannedNotification> {
if mentioned.mentioned.is_empty() {
return Vec::new();
@@ -329,3 +362,9 @@ pub fn mentioned_notification_id(session_id: Uuid, action_id: Uuid) -> Uuid {
AgentSessionMentionedMetadata::TYPE_NAME
))
}
+
+/// The id of the approval notification for one held tool call.
+#[must_use]
+pub fn tool_approval_notification_id(session_id: Uuid, approval_id: Uuid) -> Uuid {
+ derived_id(&format!("{session_id}:{approval_id}:tool_approval"))
+}
diff --git a/crates/agent_harness/src/domain/notifications/test.rs b/crates/agent_harness/src/domain/notifications/test.rs
index f438578754..c5b1309c8d 100644
--- a/crates/agent_harness/src/domain/notifications/test.rs
+++ b/crates/agent_harness/src/domain/notifications/test.rs
@@ -401,3 +401,45 @@ fn a_notify_becomes_a_realtime_and_push_request_with_its_own_id() {
);
assert_eq!(value["req"]["notification"]["tag"], "agent_session_settled");
}
+
+#[test]
+fn a_held_tool_call_tells_only_the_owner() {
+ let approval = Uuid::from_u128(0xA99);
+ let PlannedNotification::WaitingForInput(notify) = plan_tool_approval(
+ &identity(),
+ approval,
+ Some(&user("[email protected]")),
+ "Macro",
+ "ListEmails",
+ ) else {
+ panic!("filed as waiting for input");
+ };
+ assert_eq!(notify.recipients, [owner()], "only the owner can answer");
+ assert_eq!(
+ notify.metadata.question,
+ "alice asked it to use Macro ListEmails with your access. Approve or decline it."
+ );
+ assert_eq!(
+ notify.notification_id,
+ tool_approval_notification_id(SESSION, approval)
+ );
+ assert_ne!(
+ notify.notification_id,
+ tool_approval_notification_id(SESSION, Uuid::from_u128(0xA98)),
+ "each held call is its own notification"
+ );
+}
+
+#[test]
+fn a_held_tool_call_a_bot_asked_for_says_so() {
+ let PlannedNotification::WaitingForInput(notify) = plan_tool_approval(
+ &identity(),
+ Uuid::from_u128(1),
+ None,
+ "Linear",
+ "create_issue",
+ ) else {
+ panic!("filed as waiting for input");
+ };
+ assert!(notify.metadata.question.starts_with("A bot asked it"));
+}
diff --git a/crates/agent_harness/src/domain/ports.rs b/crates/agent_harness/src/domain/ports.rs
index a865faddb5..9ad3271df3 100644
--- a/crates/agent_harness/src/domain/ports.rs
+++ b/crates/agent_harness/src/domain/ports.rs
@@ -183,12 +183,14 @@ pub trait MessagePromptContext: Send + Sync + 'static {
/// Composes an agent prompt from raw markdown and trusted session context.
pub trait AgentPromptComposer: Send + Sync + 'static {
/// Return the markdown that should be delivered to the agent runtime.
- /// Empty context sanitizes a prompt without adding a private context node.
+ /// With no instructions, people, or context, the prompt is sanitized
+ /// without adding a private context node.
fn compose(
&self,
prompt_markdown: &str,
instructions: Option<&str>,
parent: Option<&messages::domain::models::MessageParent>,
+ people: Option<&super::model::PromptPeople>,
context: Option<&ConversationContext>,
) -> impl Future<Output = Result<String>> + Send;
}
diff --git a/crates/agent_harness/src/domain/service.rs b/crates/agent_harness/src/domain/service.rs
index 3ee75dba14..48155dcfea 100644
--- a/crates/agent_harness/src/domain/service.rs
+++ b/crates/agent_harness/src/domain/service.rs
@@ -50,8 +50,8 @@ use tracing::instrument::WithSubscriber as _;
use crate::domain::error::{HarnessError, Result};
use crate::domain::model::{
AgentKind, AnnounceOrigin, AnnouncePrompt, CommandOutcome, DeclinedMention, DeliverAction,
- HarnessCommand, HarnessDefaults, OpenSession, ReplyOutcome, ResolvedReply, SessionAnnouncement,
- SpawnContainer, is_macro_staff,
+ HarnessCommand, HarnessDefaults, OpenSession, PromptPeople, ReplyOutcome, ResolvedReply,
+ SessionAnnouncement, SpawnContainer, is_macro_staff,
};
use crate::domain::pending::PendingCommands;
use crate::domain::ports::{
diff --git a/crates/agent_harness/src/domain/service/deliver.rs b/crates/agent_harness/src/domain/service/deliver.rs
index 74f09120e5..25536a6349 100644
--- a/crates/agent_harness/src/domain/service/deliver.rs
+++ b/crates/agent_harness/src/domain/service/deliver.rs
@@ -172,16 +172,19 @@ where
let AgentAction::Prompt(prompt) = action else {
return Ok(());
};
+ let session = self.sessions.get_session(session_id).await?;
+ // Every prompt names the owner and its sender, so the agent can tell
+ // a request from the person whose access it spends from anyone
+ // else's. A session owned by a bot or team has no person to name.
+ let people = session.owner_id.as_user().map(|owner| PromptPeople {
+ owner: owner.clone(),
+ sender: actor.cloned(),
+ });
let raw_prompt = prompt.prompt.clone();
- let session = if first_turn {
- Some(self.sessions.get_session(session_id).await?)
- } else {
- None
- };
- let instructions = session
- .as_ref()
+ let instructions = Some(&session)
.filter(|session| {
- AgentKind::for_session(session.bot_id, &session.harness).folds_instructions()
+ first_turn
+ && AgentKind::for_session(session.bot_id, &session.harness).folds_instructions()
})
.and_then(|session| session.instructions.as_deref())
.filter(|instructions| !instructions.trim().is_empty());
@@ -198,6 +201,7 @@ where
announce
.filter(|origin| !origin.reuse_origin_message)
.map(|origin| &origin.parent),
+ people.as_ref(),
context.as_ref(),
)
.await?;
diff --git a/crates/agent_harness/src/domain/service/queue.rs b/crates/agent_harness/src/domain/service/queue.rs
index b63954b977..b25bd073c8 100644
--- a/crates/agent_harness/src/domain/service/queue.rs
+++ b/crates/agent_harness/src/domain/service/queue.rs
@@ -8,7 +8,7 @@ use agent_session::domain::events::{
SessionSettledMetadata, SessionStoppedMetadata, TurnEndedMetadata, TurnStartedMetadata,
WaitingForInputMetadata,
};
-use agent_session::domain::model::StoredQueuedAction;
+use agent_session::domain::model::{StoredQueuedAction, TurnPrompter};
use super::*;
@@ -1006,6 +1006,25 @@ where
}
}
+ // Recorded before delivery, since the runtime may call a tool the
+ // moment the prompt lands: the egress proxy judges every call by who
+ // prompted the turn it belongs to, and it may be serving the call on
+ // another replica.
+ if let Err(error) = self
+ .sessions
+ .set_turn_prompter(
+ session_id,
+ &TurnPrompter {
+ action_id: entry.action_id,
+ user: entry.actor.clone(),
+ },
+ )
+ .await
+ {
+ self.requeue_claimed(session_id, entry).await?;
+ return Err(error.into());
+ }
+
let command = DeliverAction {
id: entry.action_id,
action: composed,
diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rs
index 2b55800ac3..532c0cb21a 100644
--- a/crates/agent_harness/src/domain/service/test.rs
+++ b/crates/agent_harness/src/domain/service/test.rs
@@ -49,8 +49,8 @@ use crate::domain::error::HarnessError;
use crate::domain::model::{
AgentKind, AgentRuntimeConfig, AnnounceOrigin, CommandOutcome, CommentAnchor, ContextMessage,
ContextThread, ConversationContext, DeclinedMention, DeliverAction, HarnessCommand,
- HarnessDefaults, MentionOrigin, OpenSession, SessionBlocker, SessionDefaults, SessionOrigin,
- SessionRepository, SpawnContainer,
+ HarnessDefaults, MentionOrigin, OpenSession, PromptPeople, SessionBlocker, SessionDefaults,
+ SessionOrigin, SessionRepository, SpawnContainer,
};
use crate::domain::ports::{
AgentPromptComposer, ContainerManager as _, MessagePromptContext, NoPeers,
@@ -209,6 +209,7 @@ type PromptCompositionCall = (String, Option<String>, Option<ConversationContext
struct PromptComposerMock {
calls: Arc<Mutex<Vec<PromptCompositionCall>>>,
parents: Arc<Mutex<Vec<Option<MessageParent>>>>,
+ people: Arc<Mutex<Vec<Option<PromptPeople>>>>,
failure: Arc<Mutex<Option<String>>>,
}
@@ -223,6 +224,10 @@ impl PromptComposerMock {
fn calls(&self) -> Vec<PromptCompositionCall> {
self.calls.lock().unwrap().clone()
}
+
+ fn people(&self) -> Vec<Option<PromptPeople>> {
+ self.people.lock().unwrap().clone()
+ }
}
impl AgentPromptComposer for PromptComposerMock {
@@ -231,9 +236,11 @@ impl AgentPromptComposer for PromptComposerMock {
prompt_markdown: &str,
instructions: Option<&str>,
parent: Option<&MessageParent>,
+ people: Option<&PromptPeople>,
context: Option<&ConversationContext>,
) -> crate::domain::error::Result<String> {
self.parents.lock().unwrap().push(parent.cloned());
+ self.people.lock().unwrap().push(people.cloned());
self.calls.lock().unwrap().push((
prompt_markdown.to_owned(),
instructions.map(str::to_owned),
@@ -1244,7 +1251,7 @@ async fn open_announces_while_the_container_is_still_booting() {
#[tokio::test]
async fn forward_to_a_live_session_reuses_the_transport() {
let composer = PromptComposerMock::default();
- let ((service, _repo, containers, announcer, _runtimes), mut turns) =
+ let ((service, repo, containers, announcer, _runtimes), mut turns) =
harness_with_signals(PromptContextMock::default(), composer.clone());
let id = AgentSessionId::new();
let container = live_session(&service, &containers, id).await;
@@ -1269,6 +1276,28 @@ async fn forward_to_a_live_session_reuses_the_transport() {
Some(ConversationContext::default())
))
);
+ assert_eq!(
+ composer.people(),
+ [
+ Some(PromptPeople {
+ owner: sender(),
+ sender: Some(sender()),
+ }),
+ Some(PromptPeople {
+ owner: sender(),
+ sender: Some(staff_sender()),
+ }),
+ ],
+ "every prompt names the owner and who sent it"
+ );
+ assert_eq!(
+ repo.turn_prompter(id)
+ .await
+ .unwrap()
+ .and_then(|prompter| prompter.user),
+ Some(staff_sender()),
+ "the dispatched turn's prompter is durable before the runtime can act on it"
+ );
assert_eq!(
prompts(&container.agent())[1],
vec![ContentBlock::from(context_prompt(
diff --git a/crates/agent_harness/src/inbound/mod.rs b/crates/agent_harness/src/inbound/mod.rs
index 2af4433602..728a1211c7 100644
--- a/crates/agent_harness/src/inbound/mod.rs
+++ b/crates/agent_harness/src/inbound/mod.rs
@@ -11,3 +11,5 @@ pub mod model_load;
/// Authenticated repository and branch listing.
pub mod repositories;
pub mod runtime_gateway;
+/// Answering tool calls held for the session owner's approval.
+pub mod tool_approvals;
diff --git a/crates/agent_harness/src/inbound/tool_approvals.rs b/crates/agent_harness/src/inbound/tool_approvals.rs
new file mode 100644
index 0000000000..9061bf05d6
--- /dev/null
+++ b/crates/agent_harness/src/inbound/tool_approvals.rs
@@ -0,0 +1,257 @@
+//! Answering a tool call the egress proxy holds for the session's owner,
+//! mounted under `/agent-sessions`.
+//!
+//! The caller needs edit access to the session, checked by the extractor
+//! before the handler runs; beyond that, only the owner the approval names
+//! may approve or decline, which the domain decides. Anyone with edit access
+//! may cancel, so a turn is never stuck on an owner who is away.
+
+use std::sync::Arc;
+
+use agent_egress::domain::approval::{
+ ApprovalAnswer, ToolApprovalAnswers, ToolApprovalError, ToolApprovalId,
+};
+use agent_egress::domain::model::AgentSessionId;
+use agent_runtime_protocol::domain::tool_approval::ToolApprovalStatus;
+use axum::Router;
+use axum::extract::{FromRef, Json, Path, State};
+use axum::http::StatusCode;
+use axum::response::{IntoResponse, Response};
+use axum::routing::post;
+use entity_access::domain::models::EditAccessLevel;
+use entity_access::domain::ports::EntityAccessService;
+use entity_access::inbound::axum_extractors::AgentSessionAccessLevelExtractor;
+use macro_authorization::{MacroAuthorizationService, MacroAuthorizationState};
+use macro_uuid::Uuid;
+use serde::{Deserialize, Serialize};
+use utoipa::ToSchema;
+
+#[cfg(test)]
+mod test;
+
+/// How a person answers a held tool call.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum ToolApprovalAnswerDto {
+ /// Let it run. Owner only.
+ Approve,
+ /// Let it run, and let the same person make the calls it covers in this
+ /// session without asking again: the same tool on Macro, every tool of a
+ /// connected app. Owner only.
+ ApproveAndRemember,
+ /// Refuse it. Owner only.
+ Deny,
+ /// Stop waiting on the owner. Anyone with edit access.
+ Cancel,
+}
+
+impl From<ToolApprovalAnswerDto> for ApprovalAnswer {
+ fn from(answer: ToolApprovalAnswerDto) -> Self {
+ match answer {
+ ToolApprovalAnswerDto::Approve => Self::Approve,
+ ToolApprovalAnswerDto::ApproveAndRemember => Self::ApproveAndRemember,
+ ToolApprovalAnswerDto::Deny => Self::Deny,
+ ToolApprovalAnswerDto::Cancel => Self::Cancel,
+ }
+ }
+}
+
+/// Request body for answering a held tool call.
+#[derive(Debug, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct AnswerToolApprovalRequest {
+ /// The answer.
+ pub answer: ToolApprovalAnswerDto,
+}
+
+/// Where a held tool call stands once answered.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum ToolApprovalStatusDto {
+ /// Still waiting. Never the answer to an answer; listed for completeness.
+ Pending,
+ /// Approved; the call went through.
+ Approved,
+ /// Declined; the call did not run.
+ Denied,
+ /// Cancelled; the call did not run.
+ Cancelled,
+ /// Nobody answered in time.
+ Expired,
+}
+
+impl From<ToolApprovalStatus> for ToolApprovalStatusDto {
+ fn from(status: ToolApprovalStatus) -> Self {
+ match status {
+ ToolApprovalStatus::Pending => Self::Pending,
+ ToolApprovalStatus::Approved => Self::Approved,
+ ToolApprovalStatus::Denied => Self::Denied,
+ ToolApprovalStatus::Cancelled => Self::Cancelled,
+ ToolApprovalStatus::Expired => Self::Expired,
+ }
+ }
+}
+
+/// Response body for answering a held tool call.
+#[derive(Debug, Serialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct AnswerToolApprovalResponse {
+ /// Where the call stands now.
+ pub status: ToolApprovalStatusDto,
+}
+
+/// Router state: the answers, plus what the access extractor resolves grants
+/// and identity through.
+pub struct ToolApprovalsRouterState<Approvals, Access, Auth> {
+ approvals: Arc<Approvals>,
+ entity_access: Arc<Access>,
+ authorization: MacroAuthorizationState<Auth>,
+}
+
+impl<Approvals, Access, Auth> ToolApprovalsRouterState<Approvals, Access, Auth> {
+ /// Build the state.
+ pub fn new(
+ approvals: Arc<Approvals>,
+ entity_access: Arc<Access>,
+ authorization: MacroAuthorizationState<Auth>,
+ ) -> Self {
+ Self {
+ approvals,
+ entity_access,
+ authorization,
+ }
+ }
+}
+
+impl<Approvals, Access, Auth> Clone for ToolApprovalsRouterState<Approvals, Access, Auth> {
+ fn clone(&self) -> Self {
+ Self {
+ approvals: Arc::clone(&self.approvals),
+ entity_access: Arc::clone(&self.entity_access),
+ authorization: self.authorization.clone(),
+ }
+ }
+}
+
+impl<Approvals, Access, Auth> FromRef<ToolApprovalsRouterState<Approvals, Access, Auth>>
+ for MacroAuthorizationState<Auth>
+{
+ fn from_ref(state: &ToolApprovalsRouterState<Approvals, Access, Auth>) -> Self {
+ state.authorization.clone()
+ }
+}
+
+impl<Approvals, Access, Auth> FromRef<ToolApprovalsRouterState<Approvals, Access, Auth>>
+ for Arc<Access>
+{
+ fn from_ref(state: &ToolApprovalsRouterState<Approvals, Access, Auth>) -> Self {
+ Arc::clone(&state.entity_access)
+ }
+}
+
+/// Build the router. Mount it under `/agent-sessions`.
+pub fn tool_approvals_router<Approvals, Access, Auth, S>(
+ state: ToolApprovalsRouterState<Approvals, Access, Auth>,
+) -> Router<S>
+where
+ Approvals: ToolApprovalAnswers,
+ Access: EntityAccessService,
+ Auth: MacroAuthorizationService,
+ S: Clone + Send + Sync + 'static,
+{
+ Router::new()
+ .route(
+ "/{session_id}/tool-approvals/{approval_id}",
+ post(answer_tool_approval_handler::<Approvals, Access, Auth>),
+ )
+ .with_state(state)
+}
+
+/// Why an answer was refused, on the wire.
+#[derive(Debug)]
+pub struct ToolApprovalApiError(ToolApprovalError);
+
+impl IntoResponse for ToolApprovalApiError {
+ fn into_response(self) -> Response {
+ match self.0 {
+ ToolApprovalError::NotFound => {
+ (StatusCode::NOT_FOUND, "no such tool approval").into_response()
+ }
+ ToolApprovalError::NotPending => (
+ StatusCode::CONFLICT,
+ "the tool approval was already resolved",
+ )
+ .into_response(),
+ ToolApprovalError::NotOwner => (
+ StatusCode::FORBIDDEN,
+ "only the session owner may approve or decline",
+ )
+ .into_response(),
+ ToolApprovalError::NobodyToRemember => (
+ StatusCode::UNPROCESSABLE_ENTITY,
+ "a call a bot made on nobody's behalf cannot be approved for good",
+ )
+ .into_response(),
+ ToolApprovalError::Egress(error) => {
+ tracing::error!(error = ?error, "answering a tool approval failed");
+ (StatusCode::INTERNAL_SERVER_ERROR, "internal error").into_response()
+ }
+ }
+ }
+}
+
+#[utoipa::path(
+ post,
+ path = "/agent-sessions/{session_id}/tool-approvals/{approval_id}",
+ tag = "agent-sessions",
+ operation_id = "answer_agent_session_tool_approval",
+ params(
+ ("session_id" = Uuid, Path, description = "ID of the agent session"),
+ ("approval_id" = Uuid, Path, description = "ID of the held tool call"),
+ ),
+ request_body = AnswerToolApprovalRequest,
+ responses(
+ (status = 200, body = AnswerToolApprovalResponse),
+ (status = 401, body = String),
+ (status = 403, body = String, description = "Not the owner, for approve or deny; or no edit access"),
+ (status = 404, body = String),
+ (status = 409, body = String, description = "Already resolved"),
+ (status = 422, body = String, description = "Approve for good, for a call no person asked for"),
+ (status = 500, body = String),
+ )
+)]
+/// Answer a tool call the agent made in a turn somebody other than the
+/// session's owner prompted. Approve and deny are the owner's; cancel is
+/// anyone's with edit access.
+#[tracing::instrument(skip_all, fields(%session_id, %approval_id), err(Debug))]
+pub async fn answer_tool_approval_handler<Approvals, Access, Auth>(
+ access: AgentSessionAccessLevelExtractor<EditAccessLevel, Access, Auth>,
+ State(state): State<ToolApprovalsRouterState<Approvals, Access, Auth>>,
+ Path((session_id, approval_id)): Path<(Uuid, Uuid)>,
+ Json(request): Json<AnswerToolApprovalRequest>,
+) -> Result<Json<AnswerToolApprovalResponse>, Response>
+where
+ Approvals: ToolApprovalAnswers,
+ Access: EntityAccessService,
+ Auth: MacroAuthorizationService,
+{
+ // A person answers: a bot has no say over whose access is spent.
+ let by = access
+ .entity_access_receipt
+ .get_authenticated_user()
+ .map_err(|_| (StatusCode::FORBIDDEN, "a person must answer").into_response())?
+ .clone();
+ let approval = state
+ .approvals
+ .answer(
+ AgentSessionId::new_from_uuid(session_id),
+ ToolApprovalId::from_uuid(approval_id),
+ request.answer.into(),
+ &by,
+ )
+ .await
+ .map_err(|error| ToolApprovalApiError(error).into_response())?;
+ Ok(Json(AnswerToolApprovalResponse {
+ status: approval.status.into(),
+ }))
+}
diff --git a/crates/agent_harness/src/inbound/tool_approvals/test.rs b/crates/agent_harness/src/inbound/tool_approvals/test.rs
new file mode 100644
index 0000000000..2a2141edb5
--- /dev/null
+++ b/crates/agent_harness/src/inbound/tool_approvals/test.rs
@@ -0,0 +1,33 @@
+use super::*;
+
+#[test]
+fn refusals_answer_with_the_status_the_buttons_branch_on() {
+ let status = |error| ToolApprovalApiError(error).into_response().status();
+ assert_eq!(status(ToolApprovalError::NotFound), StatusCode::NOT_FOUND);
+ assert_eq!(status(ToolApprovalError::NotPending), StatusCode::CONFLICT);
+ assert_eq!(status(ToolApprovalError::NotOwner), StatusCode::FORBIDDEN);
+ assert_eq!(
+ status(ToolApprovalError::NobodyToRemember),
+ StatusCode::UNPROCESSABLE_ENTITY
+ );
+}
+
+#[test]
+fn the_wire_speaks_snake_case() {
+ let request: AnswerToolApprovalRequest =
+ serde_json::from_value(serde_json::json!({ "answer": "deny" })).unwrap();
+ assert_eq!(ApprovalAnswer::from(request.answer), ApprovalAnswer::Deny);
+ let request: AnswerToolApprovalRequest =
+ serde_json::from_value(serde_json::json!({ "answer": "approve_and_remember" })).unwrap();
+ assert_eq!(
+ ApprovalAnswer::from(request.answer),
+ ApprovalAnswer::ApproveAndRemember
+ );
+ let response = AnswerToolApprovalResponse {
+ status: ToolApprovalStatus::Cancelled.into(),
+ };
+ assert_eq!(
+ serde_json::to_value(response).unwrap(),
+ serde_json::json!({ "status": "cancelled" })
+ );
+}
diff --git a/crates/agent_harness/src/outbound/agent_prompt_composer.rs b/crates/agent_harness/src/outbound/agent_prompt_composer.rs
index 9746bbd3d3..55f630f1b2 100644
--- a/crates/agent_harness/src/outbound/agent_prompt_composer.rs
+++ b/crates/agent_harness/src/outbound/agent_prompt_composer.rs
@@ -2,13 +2,14 @@
use lexical_client::LexicalClient;
use lexical_client::parse_markdown::{
- AgentContext, AgentContextAnchor, AgentContextMessage, AgentContextReplyTarget,
- AgentContextThread,
+ AgentContext, AgentContextAnchor, AgentContextMessage, AgentContextPeople, AgentContextPerson,
+ AgentContextReplyTarget, AgentContextThread,
};
+use macro_user_id::user_id::MacroUserIdStr;
use crate::domain::error::{HarnessError, Result};
use crate::domain::model::{
- CommentAnchor, ContextMessage, ContextThread, ConversationContext, ReplyTarget,
+ CommentAnchor, ContextMessage, ContextThread, ConversationContext, PromptPeople, ReplyTarget,
};
use crate::domain::ports::AgentPromptComposer;
@@ -30,8 +31,13 @@ impl AgentPromptComposer for LexicalAgentPromptComposer {
prompt_markdown: &str,
instructions: Option<&str>,
parent: Option<&messages::domain::models::MessageParent>,
+ people: Option<&PromptPeople>,
context: Option<&ConversationContext>,
) -> Result<String> {
+ let people = people.map(|people| AgentContextPeople {
+ owner: person(&people.owner),
+ sender: people.sender.as_ref().map(person),
+ });
let context = context.map(|context| AgentContext {
anchor: context.anchor.as_ref().map(anchor),
reply_target: context.reply_target.as_ref().map(reply_target),
@@ -41,12 +47,26 @@ impl AgentPromptComposer for LexicalAgentPromptComposer {
});
self.lexical
- .compose_agent_context(prompt_markdown, instructions, parent, context.as_ref())
+ .compose_agent_context(
+ prompt_markdown,
+ instructions,
+ parent,
+ people.as_ref(),
+ context.as_ref(),
+ )
.await
.map_err(|error| HarnessError::PromptComposition(rootcause::report!(error).into()))
}
}
+/// A user as the context names them: by email, the way message authors are.
+fn person<'a>(user: &'a MacroUserIdStr<'static>) -> AgentContextPerson<'a> {
+ AgentContextPerson {
+ id: user.as_ref(),
+ name: user.email_str(),
+ }
+}
+
fn anchor(anchor: &CommentAnchor) -> AgentContextAnchor<'_> {
match anchor {
CommentAnchor::Spreadsheet {
diff --git a/crates/agent_harness/src/outbound/agent_prompt_composer/test.rs b/crates/agent_harness/src/outbound/agent_prompt_composer/test.rs
index 1745003480..151f6b6568 100644
--- a/crates/agent_harness/src/outbound/agent_prompt_composer/test.rs
+++ b/crates/agent_harness/src/outbound/agent_prompt_composer/test.rs
@@ -1,6 +1,6 @@
use super::*;
use crate::domain::model::{
- CommentAnchor, ContextMessage, ContextThread, MarkedPassage, ReplyTarget,
+ CommentAnchor, ContextMessage, ContextThread, MarkedPassage, PromptPeople, ReplyTarget,
};
use axum::{Json, Router, routing::post};
use macro_uuid::Uuid;
@@ -22,7 +22,7 @@ async fn composition_preserves_lexical_output_without_tool_instructions() {
for context in [None, Some(&ConversationContext::default())] {
let prompt = composer
- .compose("Raw prompt", None, None, context)
+ .compose("Raw prompt", None, None, None, context)
.await
.unwrap();
assert_eq!(prompt, "Sanitized prompt and context");
@@ -60,6 +60,7 @@ async fn the_comment_anchor_reaches_the_lexical_service_beside_the_history() {
"Raw prompt",
Some("Never force-push."),
None,
+ None,
Some(&ConversationContext {
anchor: Some(CommentAnchor::Mark {
mark_id: "mark-1".to_owned(),
@@ -91,6 +92,7 @@ async fn the_comment_anchor_reaches_the_lexical_service_beside_the_history() {
"Raw prompt",
None,
None,
+ None,
Some(&ConversationContext {
anchor: Some(CommentAnchor::Mark {
mark_id: "mark-2".to_owned(),
@@ -116,6 +118,7 @@ async fn the_comment_anchor_reaches_the_lexical_service_beside_the_history() {
"Raw prompt",
None,
None,
+ None,
Some(&ConversationContext {
anchor: Some(anchor),
..ConversationContext::default()
@@ -220,7 +223,7 @@ async fn the_thread_channel_and_reply_target_reach_the_lexical_service() {
let context = context(target);
async move {
composer
- .compose("Raw prompt", None, None, Some(&context))
+ .compose("Raw prompt", None, None, None, Some(&context))
.await
.unwrap();
received.lock().unwrap().clone().unwrap()
@@ -265,3 +268,70 @@ async fn the_thread_channel_and_reply_target_reach_the_lexical_service() {
assert_eq!(body["replyTarget"], serde_json::json!({ "kind": "none" }));
server.abort();
}
+
+/// Owner and sender cross the same boundary and are named by email, like
+/// message authors; a prompt with no person behind it sends no sender.
+#[tokio::test]
+async fn the_owner_and_sender_reach_the_lexical_service() {
+ let received: Arc<Mutex<Option<serde_json::Value>>> = Arc::default();
+ let seen = received.clone();
+ let app = Router::new().route(
+ "/agent-context",
+ post(move |Json(body): Json<serde_json::Value>| {
+ let seen = seen.clone();
+ async move {
+ *seen.lock().unwrap() = Some(body);
+ Json(serde_json::json!({ "markdown": "composed" }))
+ }
+ }),
+ );
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+ let composer = LexicalAgentPromptComposer::new(LexicalClient::new(
+ "test".into(),
+ format!("http://{address}"),
+ ));
+ let owner = MacroUserIdStr::try_from_email("[email protected]").unwrap();
+ let sender = MacroUserIdStr::try_from_email("[email protected]").unwrap();
+
+ composer
+ .compose(
+ "Raw prompt",
+ None,
+ None,
+ Some(&PromptPeople {
+ owner: owner.clone(),
+ sender: Some(sender),
+ }),
+ None,
+ )
+ .await
+ .unwrap();
+ let body = received.lock().unwrap().clone().unwrap();
+ assert_eq!(
+ body["owner"],
+ serde_json::json!({ "id": "macro|[email protected]", "name": "[email protected]" })
+ );
+ assert_eq!(
+ body["sender"],
+ serde_json::json!({ "id": "macro|[email protected]", "name": "[email protected]" })
+ );
+
+ composer
+ .compose(
+ "Raw prompt",
+ None,
+ None,
+ Some(&PromptPeople {
+ owner,
+ sender: None,
+ }),
+ None,
+ )
+ .await
+ .unwrap();
+ let body = received.lock().unwrap().clone().unwrap();
+ assert!(body.get("sender").is_none());
+ server.abort();
+}
diff --git a/crates/agent_harness/src/outbound/cursor/manager/test.rs b/crates/agent_harness/src/outbound/cursor/manager/test.rs
index 9662bd21ce..351bb7b5c7 100644
--- a/crates/agent_harness/src/outbound/cursor/manager/test.rs
+++ b/crates/agent_harness/src/outbound/cursor/manager/test.rs
@@ -157,6 +157,21 @@ impl AgentSessionRepo for StubSessions {
unimplemented!("this adapter does not rotate credentials")
}
+ async fn set_turn_prompter(
+ &self,
+ _id: AgentSessionId,
+ _prompter: &agent_session::domain::model::TurnPrompter,
+ ) -> SessionResult<()> {
+ unimplemented!("this adapter does not dispatch turns")
+ }
+
+ async fn turn_prompter(
+ &self,
+ _id: AgentSessionId,
+ ) -> SessionResult<Option<agent_session::domain::model::TurnPrompter>> {
+ unimplemented!("this adapter does not dispatch turns")
+ }
+
async fn set_repo_url(
&self,
id: AgentSessionId,
diff --git a/crates/agent_harness/src/outbound/mod.rs b/crates/agent_harness/src/outbound/mod.rs
index f0fa284d4d..173e837509 100644
--- a/crates/agent_harness/src/outbound/mod.rs
+++ b/crates/agent_harness/src/outbound/mod.rs
@@ -20,6 +20,7 @@ pub(crate) mod provision;
pub mod routing;
pub mod runtime_registry;
pub mod sidecar;
+pub mod tool_approvals;
/// Provider-neutral in-process ACP transport.
pub mod acp_pipe;
diff --git a/crates/agent_harness/src/outbound/routing/test.rs b/crates/agent_harness/src/outbound/routing/test.rs
index 6d0dff65b6..d479f76178 100644
--- a/crates/agent_harness/src/outbound/routing/test.rs
+++ b/crates/agent_harness/src/outbound/routing/test.rs
@@ -213,6 +213,21 @@ impl AgentSessionRepo for FixedBotSessions {
unimplemented!("this adapter does not rotate credentials")
}
+ async fn set_turn_prompter(
+ &self,
+ _id: AgentSessionId,
+ _prompter: &agent_session::domain::model::TurnPrompter,
+ ) -> SessionResult<()> {
+ unimplemented!("this adapter does not dispatch turns")
+ }
+
+ async fn turn_prompter(
+ &self,
+ _id: AgentSessionId,
+ ) -> SessionResult<Option<agent_session::domain::model::TurnPrompter>> {
+ unimplemented!("this adapter does not dispatch turns")
+ }
+
async fn set_repo_url(
&self,
_id: AgentSessionId,
diff --git a/crates/agent_harness/src/outbound/tool_approvals.rs b/crates/agent_harness/src/outbound/tool_approvals.rs
new file mode 100644
index 0000000000..69dbd61134
--- /dev/null
+++ b/crates/agent_harness/src/outbound/tool_approvals.rs
@@ -0,0 +1,148 @@
+//! Telling people about tool calls the egress proxy holds for the owner.
+//!
+//! Each state of a held call becomes a frame in the session's log, which is
+//! what the session view renders and answers from; a call that starts
+//! waiting also notifies the owner, the only person who can approve it.
+//! Both are best-effort: the hold stands on its approval row either way.
+//!
+//! Also here: releasing a session's held calls when its turn ends, stops, or
+//! the session is deleted, by listening to the same lifecycle facts the
+//! harness publishes.
+
+use std::pin::Pin;
+use std::sync::Arc;
+
+use agent_egress::domain::approval::{ToolApproval, ToolApprovalAnswers};
+use agent_egress::domain::ports::ToolApprovalAnnouncer;
+use agent_session::domain::events::AgentSessionLifecycleEvent;
+use agent_session::domain::lifecycle::session_identity;
+use agent_session::domain::ports::AgentSessionLifecyclePublisher;
+use agent_session::domain::service::AgentSessionService;
+use macro_user_id::user_id::MacroUserIdStr;
+
+use crate::domain::notifications::plan_tool_approval;
+use crate::domain::ports::AgentSessionNotifier;
+
+#[cfg(test)]
+mod test;
+
+/// [`ToolApprovalAnnouncer`] over the session's log and the notifier.
+pub struct SessionToolApprovalAnnouncer<Sessions, Notifier> {
+ sessions: Sessions,
+ notifier: Notifier,
+}
+
+impl<Sessions, Notifier> SessionToolApprovalAnnouncer<Sessions, Notifier> {
+ /// Announce through `sessions`' log and `notifier`.
+ pub fn new(sessions: Sessions, notifier: Notifier) -> Self {
+ Self { sessions, notifier }
+ }
+}
+
+impl<Sessions, Notifier> SessionToolApprovalAnnouncer<Sessions, Notifier>
+where
+ Sessions: AgentSessionService,
+ Notifier: AgentSessionNotifier,
+{
+ async fn record(&self, approval: &ToolApproval) {
+ if let Err(error) = self
+ .sessions
+ .record_frame(approval.session, approval.notice().to_server_message())
+ .await
+ {
+ tracing::error!(
+ error = ?error,
+ session = %approval.session,
+ approval = %approval.id,
+ "could not record a held tool call in the session log"
+ );
+ }
+ }
+
+ async fn notify_owner(&self, approval: &ToolApproval) -> anyhow::Result<()> {
+ let session = self.sessions.get_session(approval.session).await?;
+ let (bot, participants) = tokio::try_join!(
+ self.sessions.session_bot(session.bot_id),
+ self.sessions.session_participants(session.id),
+ )?;
+ let identity = session_identity(&session, &bot, participants)?;
+ self.notifier
+ .notify(plan_tool_approval(
+ &identity,
+ approval.id.as_uuid(),
+ approval.requested_by.as_ref(),
+ &approval.server_name,
+ &approval.tool_name,
+ ))
+ .await;
+ Ok(())
+ }
+}
+
+impl<Sessions, Notifier> ToolApprovalAnnouncer for SessionToolApprovalAnnouncer<Sessions, Notifier>
+where
+ Sessions: AgentSessionService,
+ Notifier: AgentSessionNotifier,
+{
+ async fn requested(&self, approval: &ToolApproval, _owner: &MacroUserIdStr<'static>) {
+ self.record(approval).await;
+ if let Err(error) = self.notify_owner(approval).await {
+ tracing::warn!(
+ error = ?error,
+ session = %approval.session,
+ approval = %approval.id,
+ "could not notify the owner of a held tool call"
+ );
+ }
+ }
+
+ async fn resolved(&self, approval: &ToolApproval) {
+ self.record(approval).await;
+ }
+}
+
+/// Publishes lifecycle facts through `inner`, releasing a session's held
+/// tool calls first when its turn ends, it stops, or it is deleted: none of
+/// those leaves anybody waiting on the answer.
+pub struct ReleaseHeldCallsOnTurnEnd<Inner, Approvals> {
+ inner: Inner,
+ approvals: Arc<Approvals>,
+}
+
+impl<Inner, Approvals> ReleaseHeldCallsOnTurnEnd<Inner, Approvals> {
+ /// Wrap `inner`, releasing through `approvals`.
+ pub fn new(inner: Inner, approvals: Arc<Approvals>) -> Self {
+ Self { inner, approvals }
+ }
+}
+
+impl<Inner, Approvals> AgentSessionLifecyclePublisher
+ for ReleaseHeldCallsOnTurnEnd<Inner, Approvals>
+where
+ Inner: AgentSessionLifecyclePublisher,
+ Approvals: ToolApprovalAnswers,
+{
+ fn publish(
+ &self,
+ event: AgentSessionLifecycleEvent,
+ ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
+ Box::pin(async move {
+ let ended = match &event {
+ AgentSessionLifecycleEvent::TurnEnded(ended) => Some(ended.identity.session_id),
+ AgentSessionLifecycleEvent::Stopped(stopped) => Some(stopped.identity.session_id),
+ AgentSessionLifecycleEvent::Deleted(deleted) => Some(deleted.identity.session_id),
+ _ => None,
+ };
+ if let Some(session) = ended
+ && let Err(error) = self.approvals.release_session(session).await
+ {
+ tracing::warn!(
+ error = ?error,
+ %session,
+ "could not release a session's held tool calls"
+ );
+ }
+ self.inner.publish(event).await;
+ })
+ }
+}
diff --git a/crates/agent_harness/src/outbound/tool_approvals/test.rs b/crates/agent_harness/src/outbound/tool_approvals/test.rs
new file mode 100644
index 0000000000..12d647b43b
--- /dev/null
+++ b/crates/agent_harness/src/outbound/tool_approvals/test.rs
@@ -0,0 +1,170 @@
+use std::sync::Mutex;
+
+use agent_client_protocol::RawJsonRpcMessage;
+use agent_egress::domain::approval::{ApprovalAnswer, ToolApprovalError, ToolApprovalId};
+use agent_egress::domain::error::EgressError;
+use agent_egress::domain::model::AgentSessionId;
+use agent_runtime_protocol::domain::action::AgentActionId;
+use agent_runtime_protocol::domain::schema::v0::{AcpMessage, ToServerMessage};
+use agent_runtime_protocol::domain::tool_approval::{ToolApprovalNotice, ToolApprovalStatus};
+use agent_session::domain::error::AgentSessionError;
+use agent_session::domain::events::{
+ SessionDeletedMetadata, SessionIdentity, SessionRenamedMetadata, SessionStoppedMetadata,
+};
+use agent_session::domain::service::MockAgentSessionService;
+use agent_session::testing::RecordingLifecyclePublisher;
+use bot_id::BotId;
+use macro_uuid::Uuid;
+
+use super::*;
+use crate::domain::notifications::PlannedNotification;
+
+#[derive(Default)]
+struct RecordingReleases(Mutex<Vec<AgentSessionId>>);
+
+impl ToolApprovalAnswers for RecordingReleases {
+ async fn answer(
+ &self,
+ _session: AgentSessionId,
+ _id: ToolApprovalId,
+ _answer: ApprovalAnswer,
+ _by: &MacroUserIdStr<'static>,
+ ) -> Result<ToolApproval, ToolApprovalError> {
+ unimplemented!("releases only")
+ }
+
+ async fn release_session(&self, session: AgentSessionId) -> Result<(), EgressError> {
+ self.0.lock().unwrap().push(session);
+ Ok(())
+ }
+}
+
+fn identity(session: AgentSessionId) -> SessionIdentity {
+ SessionIdentity {
+ session_id: session,
+ session_name: "Session".to_owned(),
+ bot_id: BotId::new_from_uuid(Uuid::from_u128(1)),
+ bot_name: "Macro".to_owned(),
+ owner_id: MacroUserIdStr::try_from_email("[email protected]").unwrap(),
+ origin: None,
+ audience: Vec::new(),
+ }
+}
+
+#[tokio::test]
+async fn stopping_or_deleting_a_session_releases_its_held_calls_before_publishing() {
+ let releases = Arc::new(RecordingReleases::default());
+ let published = RecordingLifecyclePublisher::new();
+ let publisher = ReleaseHeldCallsOnTurnEnd::new(published.clone(), Arc::clone(&releases));
+ let stopped = AgentSessionId::new();
+ let deleted = AgentSessionId::new();
+ let renamed = AgentSessionId::new();
+
+ publisher
+ .publish(AgentSessionLifecycleEvent::Stopped(
+ SessionStoppedMetadata {
+ identity: identity(stopped),
+ reason: "closed".to_owned(),
+ turn_in_flight: None,
+ },
+ ))
+ .await;
+ publisher
+ .publish(AgentSessionLifecycleEvent::Deleted(
+ SessionDeletedMetadata {
+ identity: identity(deleted),
+ },
+ ))
+ .await;
+ publisher
+ .publish(AgentSessionLifecycleEvent::Renamed(
+ SessionRenamedMetadata {
+ identity: identity(renamed),
+ },
+ ))
+ .await;
+
+ assert_eq!(*releases.0.lock().unwrap(), [stopped, deleted]);
+ assert_eq!(published.published().len(), 3, "every fact still goes out");
+}
+
+#[derive(Clone, Default)]
+struct RecordingNotifier(Arc<Mutex<Vec<PlannedNotification>>>);
+
+impl AgentSessionNotifier for RecordingNotifier {
+ fn notify(
+ &self,
+ notification: PlannedNotification,
+ ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
+ self.0.lock().unwrap().push(notification);
+ Box::pin(async {})
+ }
+}
+
+fn approval(session: AgentSessionId, status: ToolApprovalStatus) -> ToolApproval {
+ ToolApproval {
+ id: ToolApprovalId::mint(),
+ session,
+ turn_action_id: AgentActionId::mint(),
+ request_id: serde_json::json!(1),
+ owner: MacroUserIdStr::try_from_email("[email protected]").unwrap(),
+ requested_by: Some(MacroUserIdStr::try_from_email("[email protected]").unwrap()),
+ server_slug: "macro".to_owned(),
+ server_name: "Macro".to_owned(),
+ tool_name: "ListEmails".to_owned(),
+ arguments: serde_json::json!({}),
+ status,
+ resolved_by: None,
+ remembered: false,
+ }
+}
+
+fn notice_of(message: &ToServerMessage) -> ToolApprovalNotice {
+ let ToServerMessage::Acp(AcpMessage(RawJsonRpcMessage::Notification(frame))) = message else {
+ panic!("a notice is a notification");
+ };
+ ToolApprovalNotice::from_notification(&frame.method, frame.params.as_ref()).unwrap()
+}
+
+#[tokio::test]
+async fn every_state_of_a_held_call_is_recorded_in_the_session_log() {
+ let session = AgentSessionId::new();
+ let recorded: Arc<Mutex<Vec<ToolApprovalNotice>>> = Arc::default();
+ let mut sessions = MockAgentSessionService::new();
+ let frames = Arc::clone(&recorded);
+ sessions
+ .expect_record_frame()
+ .times(2)
+ .returning(move |id, message| {
+ assert_eq!(id, session);
+ frames.lock().unwrap().push(notice_of(&message));
+ Box::pin(async { Ok(()) })
+ });
+ // The owner's notification reads the session; a lookup that fails
+ // costs the notification and nothing else.
+ sessions
+ .expect_get_session()
+ .returning(move |_| Box::pin(async move { Err(AgentSessionError::Disconnected(session)) }));
+ let notifier = RecordingNotifier::default();
+ let announcer = SessionToolApprovalAnnouncer::new(sessions, notifier.clone());
+
+ let pending = approval(session, ToolApprovalStatus::Pending);
+ announcer.requested(&pending, &pending.owner).await;
+ announcer
+ .resolved(&ToolApproval {
+ status: ToolApprovalStatus::Approved,
+ ..pending.clone()
+ })
+ .await;
+
+ let recorded = recorded.lock().unwrap();
+ assert_eq!(
+ recorded
+ .iter()
+ .map(|notice| notice.status)
+ .collect::<Vec<_>>(),
+ [ToolApprovalStatus::Pending, ToolApprovalStatus::Approved]
+ );
+ assert_eq!(recorded[0].approval_id, pending.id.to_string());
+ assert!(notifier.0.lock().unwrap().is_empty());
+}
diff --git a/crates/agent_inmem/src/domain/agent.rs b/crates/agent_inmem/src/domain/agent.rs
index 25914e2f67..2f4b35f832 100644
--- a/crates/agent_inmem/src/domain/agent.rs
+++ b/crates/agent_inmem/src/domain/agent.rs
@@ -9,7 +9,7 @@
//! [`RuntimeAttachment::solo`]: agent_session::domain::connection::RuntimeAttachment::solo
use std::collections::HashSet;
-use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
+use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
@@ -44,7 +44,7 @@ use tokio_util::sync::CancellationToken;
use tracing::Instrument as _;
use crate::domain::admission::admit_turn;
-use crate::domain::engine::{AgentIdentity, TurnEngine, TurnRequest};
+use crate::domain::engine::{AgentIdentity, AwaitingUser, TurnEngine, TurnRequest};
use crate::domain::mcp::{DynMcpToolConnector, dialable_servers};
use crate::domain::model_options::REASONING_EFFORT_CONFIG_ID;
use crate::domain::session::{HistoryEntry, SessionStore, UserPrompt, messages_for_turn};
@@ -280,33 +280,6 @@ impl AgentState {
}
}
-/// How many questions a turn currently has out to the user. Shared between
-/// the turn's requester, which counts each question it is waiting on, and the
-/// turn loop, which reads it to tell "waiting on the user" from "hung".
-#[derive(Default)]
-struct AwaitingUser(AtomicUsize);
-
-impl AwaitingUser {
- fn is_waiting(&self) -> bool {
- self.0.load(Ordering::Acquire) > 0
- }
-
- /// Count one outstanding question until the guard drops - on an answer,
- /// an error, or the asking future being cancelled.
- fn begin(&self) -> AwaitingGuard<'_> {
- self.0.fetch_add(1, Ordering::AcqRel);
- AwaitingGuard(self)
- }
-}
-
-struct AwaitingGuard<'a>(&'a AwaitingUser);
-
-impl Drop for AwaitingGuard<'_> {
- fn drop(&mut self) {
- self.0.0.fetch_sub(1, Ordering::AcqRel);
- }
-}
-
/// ACP-backed user-input port for one connected session: the one place this
/// agent sends `elicitation/create`, whether a tool is asking a question
/// (`AskUser`, [`UserInputRequester`]) or a user tool wants its call reviewed
@@ -790,6 +763,8 @@ async fn run_turn(
let awaiting = Arc::new(AwaitingUser::default());
let requester = user_input_requester(state, connection, acp_session_id.clone(), &awaiting);
let mut parts = state.engine.run_turn(TurnRequest {
+ session_id: state.session_id,
+ awaiting: Arc::clone(&awaiting),
owner: state.owner.clone(),
model,
reasoning_effort,
diff --git a/crates/agent_inmem/src/domain/agent/test.rs b/crates/agent_inmem/src/domain/agent/test.rs
index 4fddfd56b3..f0c37d838f 100644
--- a/crates/agent_inmem/src/domain/agent/test.rs
+++ b/crates/agent_inmem/src/domain/agent/test.rs
@@ -1462,6 +1462,48 @@ async fn a_silent_turn_with_no_question_out_is_stopped_by_the_idle_timeout() {
);
}
+/// An engine whose turn waits on a person for twice the idle timeout - the
+/// way a tool call held for the owner does - and then answers.
+struct OwnerWaitingEngine;
+
+impl TurnEngine for OwnerWaitingEngine {
+ fn supported_models(&self) -> &[&str] {
+ crate::testing::TEST_MODELS
+ }
+
+ fn run_turn(
+ &self,
+ request: TurnRequest,
+ ) -> tokio::sync::mpsc::Receiver<Result<StreamPart, agent::AgentError>> {
+ let (parts, receiver) = tokio::sync::mpsc::channel(1);
+ tokio::spawn(async move {
+ {
+ let _waiting = request.awaiting.begin();
+ tokio::time::sleep(TURN_IDLE_TIMEOUT * 2).await;
+ }
+ let _ = parts.send(Ok(StreamPart::Content("approved".into()))).await;
+ });
+ receiver
+ }
+}
+
+/// Waiting on the owner to approve a tool call is not the turn hanging.
+#[tokio::test(start_paused = true)]
+async fn a_turn_waiting_on_the_owner_outlasts_the_idle_timeout() {
+ let (notifications, _config_options, response) =
+ with_agent(Arc::new(OwnerWaitingEngine), async |connection, session| {
+ connection
+ .send_request(text_prompt(&session, "read my email"))
+ .block_task()
+ .await
+ .expect("the turn should complete")
+ })
+ .await;
+
+ assert_eq!(response.stop_reason, StopReason::EndTurn);
+ assert_eq!(spoken(&notifications), "approved");
+}
+
#[tokio::test]
async fn ask_without_form_support_explains_instead_of_asking() {
let engine = Arc::new(ScriptedEngine::new(vec![]));
diff --git a/crates/agent_inmem/src/domain/engine.rs b/crates/agent_inmem/src/domain/engine.rs
index abe2991ebf..4fe138c4a1 100644
--- a/crates/agent_inmem/src/domain/engine.rs
+++ b/crates/agent_inmem/src/domain/engine.rs
@@ -1,6 +1,7 @@
//! The seam between the ACP surface and the agentic loop that serves it.
use std::sync::Arc;
+use std::sync::atomic::{AtomicUsize, Ordering};
use agent::ReasoningEffort;
use agent::types::ChatMessage;
@@ -33,6 +34,11 @@ pub struct AgentIdentity {
/// Everything one conversational turn needs.
pub struct TurnRequest {
+ /// The session the turn belongs to.
+ pub session_id: agent_session::domain::model::AgentSessionId,
+ /// Counts what the turn is waiting on a person for - a question, or a
+ /// tool call held for the owner - so the idle timeout leaves it be.
+ pub awaiting: Arc<AwaitingUser>,
/// The session's owner, whom the turn acts on behalf of: tools run with
/// their identity and token usage is recorded against them. Both need a
/// person, which the engine asks of this rather than assumes.
@@ -68,6 +74,37 @@ pub struct TurnRequest {
pub reviewer: Option<Arc<dyn UserToolReviewer>>,
}
+/// How many things a turn currently waits on a person for. Shared between
+/// whatever is waiting (a question to the user, a tool call held for the
+/// owner), which counts itself in, and the turn loop, which reads it to tell
+/// "waiting on someone" from "hung".
+#[derive(Debug, Default)]
+pub struct AwaitingUser(AtomicUsize);
+
+impl AwaitingUser {
+ /// Whether anything is being waited on.
+ #[must_use]
+ pub fn is_waiting(&self) -> bool {
+ self.0.load(Ordering::Acquire) > 0
+ }
+
+ /// Count one wait until the guard drops - on an answer, an error, or the
+ /// waiting future being cancelled.
+ pub fn begin(&self) -> AwaitingGuard<'_> {
+ self.0.fetch_add(1, Ordering::AcqRel);
+ AwaitingGuard(self)
+ }
+}
+
+/// One wait, counted until dropped.
+pub struct AwaitingGuard<'a>(&'a AwaitingUser);
+
+impl Drop for AwaitingGuard<'_> {
+ fn drop(&mut self) {
+ self.0.0.fetch_sub(1, Ordering::AcqRel);
+ }
+}
+
/// Runs one conversational turn and streams its parts back.
///
/// The trait is the testing seam: the ACP surface is exercised against a
diff --git a/crates/agent_inmem/src/domain/mod.rs b/crates/agent_inmem/src/domain/mod.rs
index ca8b506117..3dbfbc3115 100644
--- a/crates/agent_inmem/src/domain/mod.rs
+++ b/crates/agent_inmem/src/domain/mod.rs
@@ -11,4 +11,6 @@ pub mod model_options;
pub mod models;
pub mod replay;
pub mod session;
+/// Whether one of Macro's own tools may run in this turn.
+pub mod tool_gate;
pub mod user_input;
diff --git a/crates/agent_inmem/src/domain/tool_gate.rs b/crates/agent_inmem/src/domain/tool_gate.rs
new file mode 100644
index 0000000000..cac7937bdf
--- /dev/null
+++ b/crates/agent_inmem/src/domain/tool_gate.rs
@@ -0,0 +1,47 @@
+//! Whether one of Macro's own tools may run in this turn.
+//!
+//! The sandboxed runtimes reach Macro's tools through the egress proxy, which
+//! holds a turn's calls for the owner when somebody else prompted it. This
+//! runtime runs those tools in-process, so it asks the same question here,
+//! before each call. Connected apps still go through the proxy and are not
+//! asked twice.
+
+use std::pin::Pin;
+
+use agent_session::domain::model::AgentSessionId;
+
+/// What became of the question.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum NativeToolVerdict {
+ /// Run the tool.
+ Run,
+ /// Do not; this is what the model is told instead.
+ Refuse(String),
+}
+
+/// Decides, and when need be waits for the owner, before a native tool runs.
+/// Object-safe so the engine holds it erased.
+pub trait NativeToolGate: Send + Sync + 'static {
+ /// May `session` run `tool` with `arguments` now?
+ fn check<'a>(
+ &'a self,
+ session: AgentSessionId,
+ tool: &'a str,
+ arguments: &'a serde_json::Value,
+ ) -> Pin<Box<dyn Future<Output = NativeToolVerdict> + Send + 'a>>;
+}
+
+/// Lets every call through: tests, and tooling with no owner to ask.
+#[derive(Clone, Copy, Debug, Default)]
+pub struct UngatedNativeTools;
+
+impl NativeToolGate for UngatedNativeTools {
+ fn check<'a>(
+ &'a self,
+ _session: AgentSessionId,
+ _tool: &'a str,
+ _arguments: &'a serde_json::Value,
+ ) -> Pin<Box<dyn Future<Output = NativeToolVerdict> + Send + 'a>> {
+ Box::pin(async { NativeToolVerdict::Run })
+ }
+}
diff --git a/crates/agent_inmem/src/outbound/approval_gate.rs b/crates/agent_inmem/src/outbound/approval_gate.rs
new file mode 100644
index 0000000000..5994816f26
--- /dev/null
+++ b/crates/agent_inmem/src/outbound/approval_gate.rs
@@ -0,0 +1,112 @@
+//! [`NativeToolGate`] over the egress proxy's approvals.
+//!
+//! The same rule and the same record as a sandbox's MCP calls: a turn
+//! somebody other than the owner prompted waits on the owner for each of
+//! Macro's own tools, and the hold shows in the session like any other.
+
+use std::pin::Pin;
+use std::sync::Arc;
+
+use agent_egress::domain::approval::{
+ InProcessCall, MACRO_SERVER_SLUG, ToolApprovalService, refusal, spends_owner_access,
+};
+use agent_egress::domain::ports::{ToolApprovalAnnouncer, ToolApprovalSignals, ToolApprovalStore};
+use agent_session::domain::model::AgentSessionId;
+use agent_session::domain::ports::AgentSessionRepo;
+
+use crate::domain::tool_gate::{NativeToolGate, NativeToolVerdict};
+
+#[cfg(test)]
+mod test;
+
+/// What the model hears when the gate itself could not decide.
+const UNDECIDED: &str = "This tool did not run: whether it may run in this turn could not be \
+ checked. Tell the person who asked, and do not try to do the same thing another way.";
+
+/// Holds native tool calls for the owner in turns somebody else prompted.
+pub struct OwnerApprovalGate<Sessions, Store, Signals, Announcer> {
+ sessions: Sessions,
+ approvals: Arc<ToolApprovalService<Store, Signals, Announcer>>,
+}
+
+impl<Sessions, Store, Signals, Announcer> OwnerApprovalGate<Sessions, Store, Signals, Announcer> {
+ /// Gate over `sessions`' rows and `approvals`.
+ pub fn new(
+ sessions: Sessions,
+ approvals: Arc<ToolApprovalService<Store, Signals, Announcer>>,
+ ) -> Self {
+ Self {
+ sessions,
+ approvals,
+ }
+ }
+}
+
+impl<Sessions, Store, Signals, Announcer> OwnerApprovalGate<Sessions, Store, Signals, Announcer>
+where
+ Sessions: AgentSessionRepo,
+ Store: ToolApprovalStore,
+ Signals: ToolApprovalSignals,
+ Announcer: ToolApprovalAnnouncer,
+{
+ async fn decide(
+ &self,
+ session: AgentSessionId,
+ tool: &str,
+ arguments: &serde_json::Value,
+ ) -> anyhow::Result<NativeToolVerdict> {
+ if !spends_owner_access(MACRO_SERVER_SLUG, tool) {
+ return Ok(NativeToolVerdict::Run);
+ }
+ let row = self.sessions.get(session).await?;
+ let Some(owner) = row.owner_id.as_user().cloned() else {
+ return Ok(NativeToolVerdict::Refuse(UNDECIDED.to_owned()));
+ };
+ let prompter = self.sessions.turn_prompter(session).await?;
+ let Some(prompter) = prompter.filter(|prompter| prompter.user.as_ref() != Some(&owner))
+ else {
+ return Ok(NativeToolVerdict::Run);
+ };
+ let status = self
+ .approvals
+ .hold_in_process(InProcessCall {
+ session,
+ owner: owner.clone(),
+ prompter,
+ server_slug: MACRO_SERVER_SLUG.to_owned(),
+ server_name: "Macro".to_owned(),
+ tool_name: tool.to_owned(),
+ arguments: arguments.clone(),
+ })
+ .await?;
+ Ok(match refusal(status, owner.email_str(), tool) {
+ None => NativeToolVerdict::Run,
+ Some(text) => NativeToolVerdict::Refuse(text),
+ })
+ }
+}
+
+impl<Sessions, Store, Signals, Announcer> NativeToolGate
+ for OwnerApprovalGate<Sessions, Store, Signals, Announcer>
+where
+ Sessions: AgentSessionRepo,
+ Store: ToolApprovalStore,
+ Signals: ToolApprovalSignals,
+ Announcer: ToolApprovalAnnouncer,
+{
+ fn check<'a>(
+ &'a self,
+ session: AgentSessionId,
+ tool: &'a str,
+ arguments: &'a serde_json::Value,
+ ) -> Pin<Box<dyn Future<Output = NativeToolVerdict> + Send + 'a>> {
+ Box::pin(async move {
+ self.decide(session, tool, arguments)
+ .await
+ .unwrap_or_else(|error| {
+ tracing::error!(error = ?error, %session, tool, "could not gate a native tool call");
+ NativeToolVerdict::Refuse(UNDECIDED.to_owned())
+ })
+ })
+ }
+}
diff --git a/crates/agent_inmem/src/outbound/approval_gate/test.rs b/crates/agent_inmem/src/outbound/approval_gate/test.rs
new file mode 100644
index 0000000000..dbaa7a3d2d
--- /dev/null
+++ b/crates/agent_inmem/src/outbound/approval_gate/test.rs
@@ -0,0 +1,155 @@
+use std::sync::Mutex;
+
+use agent_egress::domain::approval::{ApprovalAnswer, ToolApproval, ToolApprovalAnswers};
+use agent_egress::outbound::tool_approvals::{
+ InMemoryToolApprovalStore, InProcessToolApprovalSignals,
+};
+use agent_runtime_protocol::domain::action::AgentActionId;
+use agent_runtime_protocol::domain::tool_approval::ToolApprovalStatus;
+use agent_session::domain::model::TurnPrompter;
+use agent_session::testing::{InMemoryAgentSessionRepo, test_agent_session};
+use macro_user_id::user_id::MacroUserIdStr;
+
+use super::*;
+
+#[derive(Clone, Default)]
+struct Heard {
+ requested: Arc<tokio::sync::Notify>,
+ statuses: Arc<Mutex<Vec<ToolApprovalStatus>>>,
+}
+
+impl ToolApprovalAnnouncer for Heard {
+ async fn requested(&self, approval: &ToolApproval, _owner: &MacroUserIdStr<'static>) {
+ self.statuses.lock().unwrap().push(approval.status);
+ self.requested.notify_one();
+ }
+
+ async fn resolved(&self, approval: &ToolApproval) {
+ self.statuses.lock().unwrap().push(approval.status);
+ }
+}
+
+type Approvals =
+ ToolApprovalService<InMemoryToolApprovalStore, InProcessToolApprovalSignals, Heard>;
+
+fn owner() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").unwrap()
+}
+
+struct Rig {
+ gate: OwnerApprovalGate<
+ InMemoryAgentSessionRepo,
+ InMemoryToolApprovalStore,
+ InProcessToolApprovalSignals,
+ Heard,
+ >,
+ sessions: InMemoryAgentSessionRepo,
+ approvals: Arc<Approvals>,
+ store: InMemoryToolApprovalStore,
+ heard: Heard,
+ session: AgentSessionId,
+}
+
+fn rig() -> Rig {
+ let sessions = InMemoryAgentSessionRepo::new();
+ let session = AgentSessionId::new();
+ sessions.insert_session(test_agent_session(session));
+ let store = InMemoryToolApprovalStore::new();
+ let heard = Heard::default();
+ let approvals = Arc::new(ToolApprovalService::new(
+ store.clone(),
+ store.signals(),
+ heard.clone(),
+ ));
+ Rig {
+ gate: OwnerApprovalGate::new(sessions.clone(), Arc::clone(&approvals)),
+ sessions,
+ approvals,
+ store,
+ heard,
+ session,
+ }
+}
+
+async fn prompted_by(rig: &Rig, user: Option<MacroUserIdStr<'static>>) {
+ rig.sessions
+ .set_turn_prompter(
+ rig.session,
+ &TurnPrompter {
+ action_id: AgentActionId::mint(),
+ user,
+ },
+ )
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn the_owners_own_turn_runs_without_asking() {
+ let rig = rig();
+ prompted_by(&rig, Some(owner())).await;
+ let verdict = rig
+ .gate
+ .check(rig.session, "ListEmails", &serde_json::json!({}))
+ .await;
+ assert_eq!(verdict, NativeToolVerdict::Run);
+ assert!(rig.store.all().is_empty());
+}
+
+#[tokio::test]
+async fn somebody_elses_turn_runs_only_once_the_owner_approves() {
+ let rig = rig();
+ prompted_by(
+ &rig,
+ Some(MacroUserIdStr::try_from_email("[email protected]").unwrap()),
+ )
+ .await;
+ let arguments = serde_json::json!({ "limit": 3 });
+ let check = rig.gate.check(rig.session, "ListEmails", &arguments);
+ let answer = async {
+ rig.heard.requested.notified().await;
+ let held = rig.store.all().remove(0);
+ assert_eq!(held.tool_name, "ListEmails");
+ assert_eq!(held.server_slug, "macro");
+ assert_eq!(held.arguments, serde_json::json!({ "limit": 3 }));
+ rig.approvals
+ .answer(rig.session, held.id, ApprovalAnswer::Approve, &owner())
+ .await
+ .unwrap();
+ };
+ let (verdict, ()) = tokio::join!(check, answer);
+ assert_eq!(verdict, NativeToolVerdict::Run);
+}
+
+#[tokio::test]
+async fn a_declined_call_is_refused_in_words_the_model_can_relay() {
+ let rig = rig();
+ prompted_by(&rig, None).await;
+ let arguments = serde_json::json!({});
+ let check = rig.gate.check(rig.session, "SendEmail", &arguments);
+ let answer = async {
+ rig.heard.requested.notified().await;
+ let held = rig.store.all().remove(0);
+ rig.approvals
+ .answer(rig.session, held.id, ApprovalAnswer::Deny, &owner())
+ .await
+ .unwrap();
+ };
+ let (verdict, ()) = tokio::join!(check, answer);
+ let NativeToolVerdict::Refuse(reason) = verdict else {
+ panic!("a declined call does not run");
+ };
+ assert!(reason.starts_with("[email protected] declined this call, so SendEmail did not run."));
+}
+
+#[tokio::test]
+async fn a_public_web_search_runs_without_asking_even_for_somebody_else() {
+ let rig = rig();
+ prompted_by(&rig, None).await;
+ let verdict = rig
+ .gate
+ .check(rig.session, "WebSearch", &serde_json::json!({}))
+ .await;
+ assert_eq!(verdict, NativeToolVerdict::Run);
+ assert!(rig.store.all().is_empty());
+}
diff --git a/crates/agent_inmem/src/outbound/local_attachments/test.rs b/crates/agent_inmem/src/outbound/local_attachments/test.rs
index a541dc635f..6ce415c6ed 100644
--- a/crates/agent_inmem/src/outbound/local_attachments/test.rs
+++ b/crates/agent_inmem/src/outbound/local_attachments/test.rs
@@ -145,6 +145,8 @@ fn message(uri: &str) -> ChatMessage {
fn request(messages: Vec<ChatMessage>) -> TurnRequest {
TurnRequest {
+ session_id: agent_session::domain::model::AgentSessionId::new(),
+ awaiting: std::sync::Arc::default(),
owner: Owner::from_principal_str("macro|[email protected]").expect("user"),
model: "test-model".to_owned(),
reasoning_effort: agent::ReasoningEffort::default(),
diff --git a/crates/agent_inmem/src/outbound/mod.rs b/crates/agent_inmem/src/outbound/mod.rs
index feaeefb7d9..bd2a63b8ac 100644
--- a/crates/agent_inmem/src/outbound/mod.rs
+++ b/crates/agent_inmem/src/outbound/mod.rs
@@ -1,6 +1,8 @@
//! Outbound adapters for session logging and agent management.
pub mod acp_mcp;
+/// Holding Macro's own tools for the owner, through the egress approvals.
+pub mod approval_gate;
pub mod egress_mcp;
pub mod local_attachments;
pub mod log_frames;
diff --git a/crates/agent_inmem/src/rig_engine.rs b/crates/agent_inmem/src/rig_engine.rs
index 072f266b46..5e13ded792 100644
--- a/crates/agent_inmem/src/rig_engine.rs
+++ b/crates/agent_inmem/src/rig_engine.rs
@@ -39,6 +39,7 @@ use tokio::sync::mpsc;
use tracing::Instrument as _;
use crate::domain::engine::{AgentIdentity, TurnEngine, TurnRequest};
+use crate::domain::tool_gate::{NativeToolGate, NativeToolVerdict, UngatedNativeTools};
use crate::inbound::ask_user::{AskUser, AskUserContext};
#[cfg(test)]
@@ -54,14 +55,89 @@ const PART_BUFFER: usize = 256;
pub struct RigTurnEngine {
db: PgPool,
tool_context: ToolServiceContext,
+ gate: Arc<dyn NativeToolGate>,
}
impl RigTurnEngine {
/// An engine whose tools run against `tool_context` and whose user
- /// memory comes from `db`.
+ /// memory comes from `db`. Every native tool runs ungated until
+ /// [`Self::with_gate`] says otherwise.
#[must_use]
pub fn new(db: PgPool, tool_context: ToolServiceContext) -> Self {
- Self { db, tool_context }
+ Self {
+ db,
+ tool_context,
+ gate: Arc::new(UngatedNativeTools),
+ }
+ }
+
+ /// Ask `gate` before each of Macro's own tools runs.
+ #[must_use]
+ pub fn with_gate(mut self, gate: Arc<dyn NativeToolGate>) -> Self {
+ self.gate = gate;
+ self
+ }
+}
+
+/// Native tools never gated: asking the user something, and finding or
+/// loading a connected app's tools, spend nobody's access.
+const UNGATED_NATIVE_TOOLS: [&str; 3] = ["AskUser", "SearchTools", "LoadTools"];
+
+/// A turn's tools, each call to one of Macro's own asked of the gate first.
+/// Remote MCP tools are left to the egress proxy, which gates them already.
+struct GatedToolSet<Context> {
+ tools: Arc<dyn AiToolSet<Context> + Send + Sync>,
+ gate: Arc<dyn NativeToolGate>,
+ session: agent_session::domain::model::AgentSessionId,
+ awaiting: Arc<crate::domain::engine::AwaitingUser>,
+}
+
+impl<Context> AiToolSet<Context> for GatedToolSet<Context>
+where
+ Context: Send + Sync + 'static,
+{
+ fn dispatch_tool_call<'a>(
+ &'a self,
+ context: Context,
+ request_context: ai_toolset::RequestContext,
+ tool_name: &'a str,
+ json: &'a serde_json::Value,
+ ) -> ai_toolset::ToolCallFuture<'a> {
+ Box::pin(async move {
+ if !UNGATED_NATIVE_TOOLS.contains(&tool_name)
+ && !tool_name.starts_with(mcp_select::MANGLED_PREFIX)
+ && let NativeToolVerdict::Refuse(reason) = {
+ // A call held for the owner is the turn waiting on a
+ // person, not hanging: the idle timeout leaves it be.
+ let _waiting = self.awaiting.begin();
+ self.gate.check(self.session, tool_name, json).await
+ }
+ {
+ return Ok(Err(ai_toolset::ToolCallError {
+ internal_error: anyhow::anyhow!("{tool_name} was not approved"),
+ description: reason,
+ }));
+ }
+ self.tools
+ .dispatch_tool_call(context, request_context, tool_name, json)
+ .await
+ })
+ }
+
+ fn request_schemas(&self) -> Option<Vec<ai_toolset::RequestSchema>> {
+ self.tools.request_schemas()
+ }
+
+ fn searchable_catalog(&self) -> Vec<ai_toolset::SearchableTool> {
+ self.tools.searchable_catalog()
+ }
+
+ fn searchable_toolset_names(&self) -> Vec<String> {
+ self.tools.searchable_toolset_names()
+ }
+
+ fn routing_description<'a>(&'a self, tool_name: &'a str) -> Option<ai_toolset::ToolInfo> {
+ self.tools.routing_description(tool_name)
}
}
@@ -104,10 +180,11 @@ impl TurnEngine for RigTurnEngine {
let (parts, receiver) = mpsc::channel(PART_BUFFER);
let db = self.db.clone();
let tool_context = self.tool_context.clone();
+ let gate = Arc::clone(&self.gate);
let metering = agent::MeteringContext::current();
tokio::spawn(
agent::MeteringContext::carry(metering, async move {
- if let Err(error) = drive_turn(db, tool_context, request, &parts).await {
+ if let Err(error) = drive_turn(db, tool_context, gate, request, &parts).await {
let _ = parts.send(Err(error)).await;
}
})
@@ -120,10 +197,13 @@ impl TurnEngine for RigTurnEngine {
async fn drive_turn(
db: PgPool,
base_context: ToolServiceContext,
+ gate: Arc<dyn NativeToolGate>,
request: TurnRequest,
parts: &mpsc::Sender<Result<StreamPart, AgentError>>,
) -> Result<(), AgentError> {
let TurnRequest {
+ session_id,
+ awaiting,
owner,
model,
reasoning_effort,
@@ -204,12 +284,22 @@ async fn drive_turn(
cancel.clone(),
));
}
+ // Macro's own tools spend the owner's access in-process, so they ask the
+ // gate a turn somebody else prompted must pass - the one the egress
+ // proxy applies to every MCP server. Remote MCP tools already pass
+ // through that proxy and are not asked twice.
// Keep remote MCP tools alongside the native and AskUser tools. The
// finisher above reviews only Macro's native user tools.
let toolset: Arc<dyn AiToolSet<_> + Send + Sync> = match mcp_tools {
Some(mcp) => Arc::new(mcp_select::CombinedToolSet::new(toolset, mcp)),
None => toolset,
};
+ let toolset: Arc<dyn AiToolSet<_> + Send + Sync> = Arc::new(GatedToolSet {
+ tools: toolset,
+ gate,
+ session: session_id,
+ awaiting,
+ });
let session = agent_loop
.session(toolset, Arc::new(tool_context), &system_prompt, usage_ctx)
.await;
diff --git a/crates/agent_runtime_protocol/src/domain/mod.rs b/crates/agent_runtime_protocol/src/domain/mod.rs
index e95b69d8e8..2664077bd3 100644
--- a/crates/agent_runtime_protocol/src/domain/mod.rs
+++ b/crates/agent_runtime_protocol/src/domain/mod.rs
@@ -12,6 +12,8 @@ pub mod connection;
pub mod ports;
/// Versioned protocol message types.
pub mod schema;
+/// The log frame an MCP tool call held for the owner's approval leaves.
+pub mod tool_approval;
/// Agent-neutral reconstructed turn lifecycle.
pub mod turn;
diff --git a/crates/agent_runtime_protocol/src/domain/tool_approval.rs b/crates/agent_runtime_protocol/src/domain/tool_approval.rs
new file mode 100644
index 0000000000..2cca0785da
--- /dev/null
+++ b/crates/agent_runtime_protocol/src/domain/tool_approval.rs
@@ -0,0 +1,131 @@
+//! The log frame an MCP tool call held for the owner's approval leaves.
+//!
+//! The egress proxy holds a `tools/call` made during a turn somebody other
+//! than the session's owner prompted, until the owner approves it. The proxy
+//! is not the agent and not the session actor, so what it records is an ACP
+//! extension notification (`_macro/...`, which ACP reserves for exactly this)
+//! logged in the runtime's direction: it is about the runtime's own traffic,
+//! and every existing reader of the log already accepts any JSON-RPC frame
+//! there and ignores methods it does not know.
+//!
+//! One frame per state: `pending` when the call is held, then one terminal
+//! frame when it is resolved. The fold pairs them by `approvalId`.
+
+use agent_client_protocol::{RawJsonRpcMessage, RawJsonRpcParams};
+use serde::{Deserialize, Serialize};
+use specta::Type;
+
+use super::schema::v0::{AcpMessage, ToServerMessage};
+
+#[cfg(test)]
+mod test;
+
+/// The extension method the frame is logged under.
+pub const TOOL_APPROVAL_METHOD: &str = "_macro/tool_approval";
+
+/// Where a held call stands.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
+#[serde(rename_all = "snake_case")]
+pub enum ToolApprovalStatus {
+ /// Held until the owner answers.
+ Pending,
+ /// The owner approved it; the call went through.
+ Approved,
+ /// The owner refused it; the call did not run.
+ Denied,
+ /// Someone with edit access, the agent, or the session gave up on it.
+ Cancelled,
+ /// Nobody answered in time.
+ Expired,
+}
+
+impl ToolApprovalStatus {
+ /// The stored and wire spelling.
+ #[must_use]
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::Pending => "pending",
+ Self::Approved => "approved",
+ Self::Denied => "denied",
+ Self::Cancelled => "cancelled",
+ Self::Expired => "expired",
+ }
+ }
+
+ /// Read a stored spelling back.
+ #[must_use]
+ pub fn parse(value: &str) -> Option<Self> {
+ Some(match value {
+ "pending" => Self::Pending,
+ "approved" => Self::Approved,
+ "denied" => Self::Denied,
+ "cancelled" => Self::Cancelled,
+ "expired" => Self::Expired,
+ _ => return None,
+ })
+ }
+
+ /// Whether the call is still waiting on an answer.
+ #[must_use]
+ pub fn is_pending(self) -> bool {
+ self == Self::Pending
+ }
+}
+
+/// One held call, as the log records it.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct ToolApprovalNotice {
+ /// The approval's id, shared by its pending and terminal frames.
+ pub approval_id: String,
+ /// `macro` for Macro's own server, otherwise the connected app's slug.
+ pub server_slug: String,
+ /// What a person calls the server.
+ pub server_name: String,
+ /// The tool the agent called.
+ pub tool_name: String,
+ /// The arguments it called the tool with.
+ #[specta(type = specta_typescript::Unknown)]
+ pub arguments: serde_json::Value,
+ /// Who prompted the turn; absent when a bot acted on nobody's behalf.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub requested_by: Option<String>,
+ /// Where it stands.
+ pub status: ToolApprovalStatus,
+ /// Who resolved it, when a person did.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub resolved_by: Option<String>,
+ /// Approved for good: the person who asked may make the calls it covers
+ /// in this session without the owner being asked again.
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub remembered: bool,
+}
+
+impl ToolApprovalNotice {
+ /// The frame to log.
+ ///
+ /// # Panics
+ ///
+ /// Never: the notice is plain data and always serializes.
+ #[must_use]
+ pub fn to_server_message(&self) -> ToServerMessage {
+ let params = serde_json::to_value(self).expect("a notice serializes");
+ let frame = RawJsonRpcMessage::notification(TOOL_APPROVAL_METHOD.to_owned(), params)
+ .expect("an object is valid notification params");
+ ToServerMessage::Acp(AcpMessage(frame))
+ }
+
+ /// Read a notice off a logged notification, if it is one.
+ #[must_use]
+ pub fn from_notification(method: &str, params: Option<&RawJsonRpcParams>) -> Option<Self> {
+ if method != TOOL_APPROVAL_METHOD {
+ return None;
+ }
+ match params? {
+ RawJsonRpcParams::Object(map) => {
+ serde_json::from_value(serde_json::Value::Object(map.clone())).ok()
+ }
+ RawJsonRpcParams::Array(_) => None,
+ }
+ }
+}
diff --git a/crates/agent_runtime_protocol/src/domain/tool_approval/test.rs b/crates/agent_runtime_protocol/src/domain/tool_approval/test.rs
new file mode 100644
index 0000000000..190cb35295
--- /dev/null
+++ b/crates/agent_runtime_protocol/src/domain/tool_approval/test.rs
@@ -0,0 +1,63 @@
+use agent_client_protocol::RawJsonRpcMessage;
+
+use super::*;
+
+fn notice(status: ToolApprovalStatus) -> ToolApprovalNotice {
+ ToolApprovalNotice {
+ approval_id: "0192f7a0-0000-7000-8000-000000000001".to_owned(),
+ server_slug: "macro".to_owned(),
+ server_name: "Macro".to_owned(),
+ tool_name: "ListEmails".to_owned(),
+ arguments: serde_json::json!({ "limit": 5 }),
+ requested_by: Some("macro|[email protected]".to_owned()),
+ status,
+ resolved_by: None,
+ remembered: false,
+ }
+}
+
+#[test]
+fn a_notice_round_trips_through_its_logged_frame() {
+ let original = notice(ToolApprovalStatus::Pending);
+ let ToServerMessage::Acp(AcpMessage(RawJsonRpcMessage::Notification(frame))) =
+ original.to_server_message()
+ else {
+ panic!("a notice is logged as a notification");
+ };
+ assert_eq!(&*frame.method, TOOL_APPROVAL_METHOD);
+ assert_eq!(
+ ToolApprovalNotice::from_notification(&frame.method, frame.params.as_ref()),
+ Some(original)
+ );
+}
+
+#[test]
+fn the_wire_shape_is_camel_case_with_snake_case_statuses() {
+ let value = serde_json::to_value(notice(ToolApprovalStatus::Expired)).unwrap();
+ assert_eq!(value["approvalId"], "0192f7a0-0000-7000-8000-000000000001");
+ assert_eq!(value["toolName"], "ListEmails");
+ assert_eq!(value["status"], "expired");
+ assert!(value.get("resolvedBy").is_none());
+}
+
+#[test]
+fn other_methods_are_not_notices() {
+ assert_eq!(
+ ToolApprovalNotice::from_notification("session/update", None),
+ None
+ );
+}
+
+#[test]
+fn statuses_parse_their_own_spelling() {
+ for status in [
+ ToolApprovalStatus::Pending,
+ ToolApprovalStatus::Approved,
+ ToolApprovalStatus::Denied,
+ ToolApprovalStatus::Cancelled,
+ ToolApprovalStatus::Expired,
+ ] {
+ assert_eq!(ToolApprovalStatus::parse(status.as_str()), Some(status));
+ }
+ assert_eq!(ToolApprovalStatus::parse("maybe"), None);
+}
diff --git a/crates/agent_session/src/domain/model.rs b/crates/agent_session/src/domain/model.rs
index 5408102427..0c586837e8 100644
--- a/crates/agent_session/src/domain/model.rs
+++ b/crates/agent_session/src/domain/model.rs
@@ -368,6 +368,19 @@ pub struct SessionBot {
pub avatar_url: Option<String>,
}
+/// Who prompted the turn a session is running, or last ran.
+///
+/// Written at dispatch, before the runtime can act on the prompt, so the
+/// egress proxy - which may be on any replica - can tell a turn the owner
+/// prompted from one somebody else did.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct TurnPrompter {
+ /// The action that opened the turn.
+ pub action_id: agent_runtime_protocol::domain::action::AgentActionId,
+ /// The user who prompted it, absent when a bot acted on nobody's behalf.
+ pub user: Option<MacroUserIdStr<'static>>,
+}
+
/// One waiting action as the session store records it.
///
/// The harness keeps an in-memory working copy beside the live actor; this
diff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rs
index f220d410f5..ca8be2556a 100644
--- a/crates/agent_session/src/domain/ports.rs
+++ b/crates/agent_session/src/domain/ports.rs
@@ -396,6 +396,20 @@ pub trait AgentSessionRepo: Send + Sync + 'static {
hash: &str,
) -> impl Future<Output = Result<()>> + Send;
+ /// Record who prompted the turn `id` is about to run.
+ fn set_turn_prompter(
+ &self,
+ id: AgentSessionId,
+ prompter: &TurnPrompter,
+ ) -> impl Future<Output = Result<()>> + Send;
+
+ /// Who prompted the turn `id` is running or last ran; `None` before its
+ /// first dispatch.
+ fn turn_prompter(
+ &self,
+ id: AgentSessionId,
+ ) -> impl Future<Output = Result<Option<TurnPrompter>>> + Send;
+
/// The session a sandbox's egress token stands for, if any still does.
///
/// `egress_token_hash` is the SHA-256 hex of the token as presented, never
diff --git a/crates/agent_session/src/domain/routines/status.rs b/crates/agent_session/src/domain/routines/status.rs
index c0d1842a00..b0df46f2bb 100644
--- a/crates/agent_session/src/domain/routines/status.rs
+++ b/crates/agent_session/src/domain/routines/status.rs
@@ -49,7 +49,11 @@ pub(super) fn action_status(
for pending in &fold.inner().metadata().pending_interactions {
if pending.turn() == prompt.id.0 {
let reason = match pending {
- PendingInteraction::Permission(_) => RoutinePendingReason::Permission,
+ // A held tool call waits on the owner's say-so, which a
+ // routine can no more give than a permission.
+ PendingInteraction::Permission(_) | PendingInteraction::ToolApproval(_) => {
+ RoutinePendingReason::Permission
+ }
PendingInteraction::Elicitation(_) => RoutinePendingReason::Elicitation,
};
return RoutineActionStatus::Pending(reason);
diff --git a/crates/agent_session/src/domain/routines/status/test.rs b/crates/agent_session/src/domain/routines/status/test.rs
index 0fd9871e9f..ef1691c012 100644
--- a/crates/agent_session/src/domain/routines/status/test.rs
+++ b/crates/agent_session/src/domain/routines/status/test.rs
@@ -151,6 +151,13 @@ fn pending_human_interactions_are_nonterminal() {
}}),
RoutinePendingReason::Elicitation,
),
+ (
+ json!({"method": "_macro/tool_approval", "params": {
+ "approvalId": "a1", "serverSlug": "macro", "serverName": "Macro",
+ "toolName": "WebSearch", "arguments": {}, "status": "pending"
+ }}),
+ RoutinePendingReason::Permission,
+ ),
] {
assert_eq!(
action_status(
diff --git a/crates/agent_session/src/domain/service.rs b/crates/agent_session/src/domain/service.rs
index fa450627cb..650b538b07 100644
--- a/crates/agent_session/src/domain/service.rs
+++ b/crates/agent_session/src/domain/service.rs
@@ -55,7 +55,6 @@ use bots::domain::models::BotId;
use super::connection::RuntimeAttachment;
use super::error::{AgentSessionError, Result};
use super::lifecycle::session_identity;
-use super::model::SessionBot;
use super::model::{
AgentSession, AgentSessionId, AgentSessionLog, AgentSessionPreview, AgentSessionRenamed,
AuthorKind, ClaimOutcome, CreateAgentSessionParams, LogAppended, MAX_AGENT_SESSION_NAME_CHARS,
@@ -63,6 +62,7 @@ use super::model::{
SessionManagement, SessionPreviewCandidate, StoredAgentSessionLog, StoredQueuedAction,
ThreadSession, cursor_run_checkpoint,
};
+use super::model::{SessionBot, TurnPrompter};
use super::ports::{
AgentConnector, AgentSessionLifecyclePublisher, AgentSessionLogRepo, AgentSessionLogWriter,
AgentSessionNameGenerator, AgentSessionQueueChanged, AgentSessionRealtime, AgentSessionRepo,
@@ -158,6 +158,23 @@ pub trait AgentSessionService: Send + Sync + 'static {
/// Get a persisted agent session by id.
fn get_session(&self, id: AgentSessionId) -> impl Future<Output = Result<AgentSession>> + Send;
+ /// Append a frame observed on the runtime's behalf by something other
+ /// than its session actor - the egress proxy's tool approvals - and push
+ /// it to the session's viewers. Any replica may call this; the frame is
+ /// ordered by when it is stored.
+ fn record_frame(
+ &self,
+ id: AgentSessionId,
+ message: ToServerMessage,
+ ) -> impl Future<Output = Result<()>> + Send;
+
+ /// Record who prompted the turn `id` is about to run, before it runs.
+ fn set_turn_prompter(
+ &self,
+ id: AgentSessionId,
+ prompter: &TurnPrompter,
+ ) -> impl Future<Output = Result<()>> + Send;
+
/// What `viewer` may see of each of `ids`, for rendering chips.
///
/// Duplicate ids are collapsed, so the answer has one entry per distinct
@@ -737,6 +754,10 @@ where
self.repo.get(id).await
}
+ async fn set_turn_prompter(&self, id: AgentSessionId, prompter: &TurnPrompter) -> Result<()> {
+ self.repo.set_turn_prompter(id, prompter).await
+ }
+
async fn preview_sessions(
&self,
viewer: &MacroUserIdStr<'static>,
@@ -881,6 +902,29 @@ where
.map(|_| ())
}
+ #[tracing::instrument(
+ name = "agent.session.record_frame",
+ err,
+ skip(self, message),
+ fields(agent.session.id = %id),
+ )]
+ async fn record_frame(&self, id: AgentSessionId, message: ToServerMessage) -> Result<()> {
+ let mut logs = LiveSessionLogWriter::new(self.repo.clone(), self.realtime.clone());
+ // Flushed at once: an unclaimed writer publishes to viewers only on
+ // flush, and nothing else will flush this one.
+ tokio::time::timeout(SESSION_PERSIST_TIMEOUT, async {
+ logs.append(AgentSessionLog {
+ agent_session_id: id,
+ user_id: None,
+ content: Message::ToServer(message),
+ })
+ .await?;
+ logs.flush().await
+ })
+ .await
+ .unwrap_or(Err(AgentSessionError::LogTimedOut(id)))
+ }
+
async fn attach_session<Connector>(
&self,
id: AgentSessionId,
@@ -1606,6 +1650,14 @@ where
self.repo.set_egress_token_hash(id, hash).await
}
+ async fn set_turn_prompter(&self, id: AgentSessionId, prompter: &TurnPrompter) -> Result<()> {
+ self.repo.set_turn_prompter(id, prompter).await
+ }
+
+ async fn turn_prompter(&self, id: AgentSessionId) -> Result<Option<TurnPrompter>> {
+ self.repo.turn_prompter(id).await
+ }
+
async fn find_by_egress_token_hash(
&self,
egress_token_hash: &str,
diff --git a/crates/agent_session/src/domain/service/test.rs b/crates/agent_session/src/domain/service/test.rs
index 3b1dab74d9..41b8e84979 100644
--- a/crates/agent_session/src/domain/service/test.rs
+++ b/crates/agent_session/src/domain/service/test.rs
@@ -619,6 +619,21 @@ impl AgentSessionRepo for BlockingPromptLogs {
self.repo.set_egress_token_hash(id, hash).await
}
+ async fn set_turn_prompter(
+ &self,
+ id: AgentSessionId,
+ prompter: &crate::domain::model::TurnPrompter,
+ ) -> Result<()> {
+ self.repo.set_turn_prompter(id, prompter).await
+ }
+
+ async fn turn_prompter(
+ &self,
+ id: AgentSessionId,
+ ) -> Result<Option<crate::domain::model::TurnPrompter>> {
+ self.repo.turn_prompter(id).await
+ }
+
async fn set_repo_url(&self, id: AgentSessionId, repo_url: Option<String>) -> Result<()> {
self.repo.set_repo_url(id, repo_url).await
}
@@ -1369,6 +1384,51 @@ async fn marking_disconnected_persists_and_publishes_the_event() {
assert_eq!(realtime.published().len(), 1);
}
+/// A frame recorded out of band - a held tool call - reaches the session's
+/// viewers straight away, not on some later flush nobody will make.
+#[tokio::test]
+async fn a_recorded_frame_is_stored_and_published_at_once() {
+ let repo = InMemoryAgentSessionRepo::new();
+ let session = test_session();
+ repo.insert_session(test_agent_session(session));
+ let realtime = RecordingRealtime::new();
+ let service = AgentSessionServiceImpl::new(
+ repo.clone(),
+ FoldedMessageService::new(repo.clone()),
+ realtime.clone(),
+ NoOpAgentSessionNameGenerator,
+ Arc::new(NoOpTurnObserver),
+ Arc::new(NoopLifecyclePublisher),
+ ReplicaId::mint(),
+ );
+ let notice = agent_runtime_protocol::domain::tool_approval::ToolApprovalNotice {
+ approval_id: "a1".to_owned(),
+ server_slug: "macro".to_owned(),
+ server_name: "Macro".to_owned(),
+ tool_name: "WebSearch".to_owned(),
+ arguments: serde_json::json!({}),
+ requested_by: None,
+ status: agent_runtime_protocol::domain::tool_approval::ToolApprovalStatus::Pending,
+ resolved_by: None,
+ remembered: false,
+ };
+
+ service
+ .record_frame(session, notice.to_server_message())
+ .await
+ .expect("the frame is recorded");
+
+ let stored = AgentSessionLogRepo::list_by_session(&repo, session)
+ .await
+ .expect("stored log can be read");
+ assert_eq!(stored.len(), 1);
+ assert_eq!(
+ realtime.published().len(),
+ 1,
+ "viewers hear it without a flush"
+ );
+}
+
#[tokio::test(start_paused = true)]
async fn marking_disconnected_is_bounded_when_persistence_hangs() {
let repo = InMemoryAgentSessionRepo::new();
diff --git a/crates/agent_session/src/outbound/postgres.rs b/crates/agent_session/src/outbound/postgres.rs
index 308ab3c842..ff2c510e4d 100644
--- a/crates/agent_session/src/outbound/postgres.rs
+++ b/crates/agent_session/src/outbound/postgres.rs
@@ -22,7 +22,7 @@ use crate::domain::model::{
ClaimOutcome, CreateAgentSessionParams, ExternalSession, LeaseView, ManagerFence, Message,
ReplicaAddress, ReplicaId, SandboxSize, SessionBot, SessionClaim, SessionManager,
SessionPreviewCandidate, SessionStatus, StoredAgentSessionLog, StoredQueuedAction,
- ThreadSession, cursor_run_checkpoint, session_owner_user,
+ ThreadSession, TurnPrompter, cursor_run_checkpoint, session_owner_user,
};
use crate::domain::ports::{
AgentSessionLogRepo, AgentSessionRepo, ExternalSessionRepo, REPLICA_STALE_AFTER,
@@ -793,6 +793,41 @@ impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {
Ok(())
}
+ async fn set_turn_prompter(&self, id: AgentSessionId, prompter: &TurnPrompter) -> Result<()> {
+ sqlx::query!(
+ "UPDATE agent_session SET turn_action_id = $2, turn_prompter = $3 WHERE id = $1",
+ id.as_uuid(),
+ prompter.action_id.as_uuid(),
+ prompter.user.as_ref().map(|user| user.as_ref()),
+ )
+ .execute(&self.pool)
+ .await
+ .context("failed to record the turn prompter")?;
+ Ok(())
+ }
+
+ async fn turn_prompter(&self, id: AgentSessionId) -> Result<Option<TurnPrompter>> {
+ let row = sqlx::query!(
+ r#"
+ SELECT turn_action_id, turn_prompter AS "turn_prompter: MacroUserIdStr<'static>"
+ FROM agent_session
+ WHERE id = $1
+ "#,
+ id.as_uuid(),
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .context("failed to read the turn prompter")?;
+ Ok(row.and_then(|row| {
+ row.turn_action_id.map(|action_id| TurnPrompter {
+ action_id: agent_runtime_protocol::domain::action::AgentActionId::from_uuid(
+ action_id,
+ ),
+ user: row.turn_prompter,
+ })
+ }))
+ }
+
async fn set_repo_url(&self, id: AgentSessionId, repo_url: Option<String>) -> Result<()> {
let result = sqlx::query!(
r#"
diff --git a/crates/agent_session/src/testing.rs b/crates/agent_session/src/testing.rs
index 7f4d751b25..1624910cf5 100644
--- a/crates/agent_session/src/testing.rs
+++ b/crates/agent_session/src/testing.rs
@@ -11,7 +11,7 @@ use crate::domain::model::{
ClaimOutcome, CreateAgentSessionParams, DEFAULT_AGENT_SESSION_NAME, LeaseView, LogAppended,
ManagerFence, ReplicaAddress, ReplicaId, SandboxSize, SessionBot, SessionClaim, SessionManager,
SessionPreviewCandidate, SessionStatus, StoredAgentSessionLog, StoredQueuedAction,
- ThreadSession,
+ ThreadSession, TurnPrompter,
};
use crate::domain::ports::{
AgentSessionLifecyclePublisher, AgentSessionLogRepo, AgentSessionRealtime, AgentSessionRepo,
@@ -83,6 +83,8 @@ pub struct InMemoryAgentSessionRepo {
leases: Arc<Mutex<HashMap<AgentSessionId, Lease>>>,
/// Session -> waiting actions, mirroring `agent_session_queue`.
queues: Arc<Mutex<HashMap<AgentSessionId, Vec<StoredQueuedAction>>>>,
+ /// Session -> who prompted its turn, mirroring the `turn_*` columns.
+ turn_prompters: Arc<Mutex<HashMap<AgentSessionId, TurnPrompter>>>,
}
impl InMemoryAgentSessionRepo {
@@ -361,6 +363,24 @@ impl AgentSessionRepo for InMemoryAgentSessionRepo {
Ok(())
}
+ async fn set_turn_prompter(&self, id: AgentSessionId, prompter: &TurnPrompter) -> Result<()> {
+ self.get(id).await?;
+ self.turn_prompters
+ .lock()
+ .expect("turn prompters poisoned")
+ .insert(id, prompter.clone());
+ Ok(())
+ }
+
+ async fn turn_prompter(&self, id: AgentSessionId) -> Result<Option<TurnPrompter>> {
+ Ok(self
+ .turn_prompters
+ .lock()
+ .expect("turn prompters poisoned")
+ .get(&id)
+ .cloned())
+ }
+
async fn set_repo_url(&self, id: AgentSessionId, repo_url: Option<String>) -> Result<()> {
let mut sessions = self
.sessions
diff --git a/crates/folds/agent_fold/src/bin/fold_jsonl.rs b/crates/folds/agent_fold/src/bin/fold_jsonl.rs
index 1f13dffa03..2a8ff8d154 100644
--- a/crates/folds/agent_fold/src/bin/fold_jsonl.rs
+++ b/crates/folds/agent_fold/src/bin/fold_jsonl.rs
@@ -263,6 +263,25 @@ fn render_part(part: &MessagePart) -> String {
outcome,
..
} => out.push_str(&render_permission(tool_call, options, outcome)),
+ MessagePart::ToolApproval {
+ server_name,
+ tool_name,
+ requested_by,
+ status,
+ resolved_by,
+ ..
+ } => {
+ let _ = writeln!(
+ out,
+ "[tool approval] {server_name} {tool_name} for {}: {}{}",
+ requested_by.as_deref().unwrap_or("a bot"),
+ status.as_str(),
+ resolved_by
+ .as_deref()
+ .map(|by| format!(" by {by}"))
+ .unwrap_or_default()
+ );
+ }
MessagePart::Control { control, outcome } => {
let label = match control {
Control::SetModel { model } => format!("model changed to {model}"),
diff --git a/crates/folds/agent_fold/src/domain/fold.rs b/crates/folds/agent_fold/src/domain/fold.rs
index 7c5d27cd02..ae58fa6c13 100644
--- a/crates/folds/agent_fold/src/domain/fold.rs
+++ b/crates/folds/agent_fold/src/domain/fold.rs
@@ -81,6 +81,7 @@ mod replay;
mod state;
/// Delegated agents and the calls nested under them.
mod subagent;
+mod tool_approval;
/// Tool calls and their patches.
mod tool_call;
/// Opening, closing, and failing turns.
diff --git a/crates/folds/agent_fold/src/domain/fold/state.rs b/crates/folds/agent_fold/src/domain/fold/state.rs
index 5349b01693..c96590bc29 100644
--- a/crates/folds/agent_fold/src/domain/fold/state.rs
+++ b/crates/folds/agent_fold/src/domain/fold/state.rs
@@ -15,6 +15,7 @@ use agent_client_protocol::schema::v1::{
use agent_client_protocol::{JsonRpcMessage, RawJsonRpcMessage, RawJsonRpcParams};
use agent_runtime_protocol::domain::action::AgentAction;
use agent_runtime_protocol::domain::schema::v0::{SystemEvent, ToRuntimeMessage, ToServerMessage};
+use agent_runtime_protocol::domain::tool_approval::TOOL_APPROVAL_METHOD;
use serde::Deserialize;
use super::convert::{content_block_text, param, user_content_part};
@@ -117,6 +118,8 @@ pub(super) struct FoldState {
pub(super) turns_opened: u32,
/// Outstanding permission requests, by the id of the request that asked.
pub(super) pending_permissions: HashMap<RequestId, ToolPath>,
+ /// Tool calls the egress proxy is holding for the owner, by approval id.
+ pub(super) pending_tool_approvals: HashMap<String, ToolPath>,
/// Outstanding `elicitation/create`s, by the id of the request that
/// asked: where the question's part sits, so its answer can find it.
/// Session-wide like [`Self::tool_positions`], since the part may have
@@ -351,6 +354,15 @@ impl FoldState {
None => Vec::new(),
}
}
+ // A tool call held for the owner, or how it was resolved.
+ RawJsonRpcMessage::Notification(notification)
+ if notification.method.as_ref() == TOOL_APPROVAL_METHOD =>
+ {
+ self.apply_tool_approval(&notification.method, notification.params.as_ref())
+ .map_or_else(Vec::new, |(message, metadata)| {
+ Self::message_and_metadata(message, metadata)
+ })
+ }
// The agent reporting that a URL interaction finished.
RawJsonRpcMessage::Notification(notification)
if CompleteElicitationNotification::matches_method(&notification.method) =>
@@ -506,6 +518,7 @@ impl FoldState {
/// Forget live requests at a connection boundary, preserving the transcript.
fn forget_interactions(&mut self) -> bool {
self.pending_permissions.clear();
+ self.pending_tool_approvals.clear();
self.pending_elicitations.clear();
self.completable_elicitations.clear();
let changed = !self.metadata.pending_interactions.is_empty();
diff --git a/crates/folds/agent_fold/src/domain/fold/tool_approval.rs b/crates/folds/agent_fold/src/domain/fold/tool_approval.rs
new file mode 100644
index 0000000000..2a49850677
--- /dev/null
+++ b/crates/folds/agent_fold/src/domain/fold/tool_approval.rs
@@ -0,0 +1,87 @@
+//! MCP tool calls held for the session owner's approval.
+//!
+//! The egress proxy logs a `pending` notice when it holds a call and one
+//! terminal notice when the hold ends. The pending one adds a part to the
+//! open turn and an interaction the owner can answer; the terminal one
+//! settles both.
+
+use agent_client_protocol::RawJsonRpcParams;
+use agent_runtime_protocol::domain::tool_approval::ToolApprovalNotice;
+
+use crate::domain::model::{MessagePart, PendingInteraction, PendingToolApproval};
+
+use super::state::{Changed, FoldState, ToolPath};
+
+impl FoldState {
+ /// Handle a `_macro/tool_approval` notice.
+ pub(super) fn apply_tool_approval(
+ &mut self,
+ method: &str,
+ params: Option<&RawJsonRpcParams>,
+ ) -> Option<(Changed, bool)> {
+ let notice = ToolApprovalNotice::from_notification(method, params)?;
+ if notice.status.is_pending() {
+ self.hold_tool_approval(notice)
+ } else {
+ self.settle_tool_approval(notice)
+ }
+ }
+
+ fn hold_tool_approval(&mut self, notice: ToolApprovalNotice) -> Option<(Changed, bool)> {
+ // Held calls belong to a running turn; one arriving after its turn
+ // closed has nothing left to block.
+ self.turn.as_ref()?;
+ let (changed, position) = self.push_agent_part(MessagePart::ToolApproval {
+ approval_id: notice.approval_id.clone(),
+ server_slug: notice.server_slug.clone(),
+ server_name: notice.server_name.clone(),
+ tool_name: notice.tool_name.clone(),
+ arguments: notice.arguments,
+ requested_by: notice.requested_by.clone(),
+ status: notice.status,
+ resolved_by: None,
+ remembered: false,
+ })?;
+ self.pending_tool_approvals.insert(
+ notice.approval_id.clone(),
+ ToolPath {
+ message: changed.message,
+ path: vec![position],
+ },
+ );
+ self.metadata
+ .pending_interactions
+ .push(PendingInteraction::ToolApproval(PendingToolApproval {
+ approval_id: notice.approval_id,
+ turn: self.messages[changed.message].id.0,
+ server_slug: notice.server_slug,
+ server_name: notice.server_name,
+ tool_name: notice.tool_name,
+ requested_by: notice.requested_by,
+ }));
+ Some((changed, true))
+ }
+
+ fn settle_tool_approval(&mut self, notice: ToolApprovalNotice) -> Option<(Changed, bool)> {
+ let at = self.pending_tool_approvals.remove(&notice.approval_id)?;
+ if let Some(MessagePart::ToolApproval {
+ status,
+ resolved_by,
+ remembered,
+ ..
+ }) = self.part_at_mut(&at)
+ {
+ *status = notice.status;
+ resolved_by.clone_from(&notice.resolved_by);
+ *remembered = notice.remembered;
+ }
+ let before = self.metadata.pending_interactions.len();
+ self.metadata.pending_interactions.retain(|pending| {
+ !matches!(pending, PendingInteraction::ToolApproval(held) if held.approval_id == notice.approval_id)
+ });
+ Some((
+ Changed::updated(at.message),
+ before != self.metadata.pending_interactions.len(),
+ ))
+ }
+}
diff --git a/crates/folds/agent_fold/src/domain/model.rs b/crates/folds/agent_fold/src/domain/model.rs
index d0ac208829..519f4fc2ba 100644
--- a/crates/folds/agent_fold/src/domain/model.rs
+++ b/crates/folds/agent_fold/src/domain/model.rs
@@ -50,7 +50,7 @@ pub use elicitation::{
ElicitationSchema, PendingElicitation,
};
pub use event::{FoldEvent, OwnedFoldEvent};
-pub use interaction::{PendingInteraction, PendingPermission};
+pub use interaction::{PendingInteraction, PendingPermission, PendingToolApproval};
pub use metadata::{AvailableCommand, Harness, ModelOption, SessionMetadata, TurnState};
pub use part::{Control, ControlOutcome, MessagePart, StopReason};
pub use permission::{PermissionOption, PermissionOptionKind, PermissionOutcome};
diff --git a/crates/folds/agent_fold/src/domain/model/interaction.rs b/crates/folds/agent_fold/src/domain/model/interaction.rs
index baef7f5cf2..f682f7b7d6 100644
--- a/crates/folds/agent_fold/src/domain/model/interaction.rs
+++ b/crates/folds/agent_fold/src/domain/model/interaction.rs
@@ -13,6 +13,9 @@ pub enum PendingInteraction {
Permission(PendingPermission),
/// A form, URL consent, or user tool review.
Elicitation(PendingElicitation),
+ /// An MCP tool call held until the session's owner approves it. Only
+ /// the owner may approve or decline; anyone with edit access may cancel.
+ ToolApproval(PendingToolApproval),
}
impl PendingInteraction {
@@ -22,6 +25,7 @@ impl PendingInteraction {
match self {
Self::Permission(pending) => pending.turn,
Self::Elicitation(pending) => pending.turn,
+ Self::ToolApproval(pending) => pending.turn,
}
}
}
@@ -39,3 +43,21 @@ pub struct PendingPermission {
/// The options the agent offered.
pub options: Vec<PermissionOption>,
}
+
+/// A held MCP tool call the owner can still answer.
+#[derive(Debug, Clone, PartialEq, Serialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct PendingToolApproval {
+ /// The approval an answer names.
+ pub approval_id: String,
+ /// The turn the call was made in.
+ pub turn: u32,
+ /// `macro`, or the connected app's slug.
+ pub server_slug: String,
+ /// What a person calls the server the tool is on.
+ pub server_name: String,
+ /// The tool called.
+ pub tool_name: String,
+ /// Who prompted the turn; absent for a bot on nobody's behalf.
+ pub requested_by: Option<String>,
+}
diff --git a/crates/folds/agent_fold/src/domain/model/metadata.rs b/crates/folds/agent_fold/src/domain/model/metadata.rs
index 8061f43f75..00042e37ac 100644
--- a/crates/folds/agent_fold/src/domain/model/metadata.rs
+++ b/crates/folds/agent_fold/src/domain/model/metadata.rs
@@ -86,7 +86,7 @@ impl SessionMetadata {
.iter()
.find_map(|pending| match pending {
PendingInteraction::Elicitation(question) => Some(question),
- PendingInteraction::Permission(_) => None,
+ PendingInteraction::Permission(_) | PendingInteraction::ToolApproval(_) => None,
})
}
}
@@ -106,7 +106,8 @@ pub enum TurnState {
Running,
/// A stop was issued against the open turn and no stop reason has arrived.
Stopping,
- /// The open turn is waiting on a permission or elicitation response.
+ /// The open turn is waiting on a permission, elicitation, or tool
+ /// approval response.
Blocked,
/// The runtime reported `disconnected`; whatever was open is not moving.
Disconnected,
diff --git a/crates/folds/agent_fold/src/domain/model/part.rs b/crates/folds/agent_fold/src/domain/model/part.rs
index 2ce6c7b515..0732b70afd 100644
--- a/crates/folds/agent_fold/src/domain/model/part.rs
+++ b/crates/folds/agent_fold/src/domain/model/part.rs
@@ -13,6 +13,7 @@ use super::permission::{PermissionOption, PermissionOutcome};
use super::plan::PlanEntry;
use super::tool::{ToolDetail, ToolName, ToolStatus};
use super::user_tool::UserToolOutcome;
+use agent_runtime_protocol::domain::tool_approval::ToolApprovalStatus;
use agent_runtime_protocol::domain::turn::FailureNotice;
/// A unit of renderable content.
@@ -72,6 +73,36 @@ pub enum MessagePart {
/// How the request has resolved so far.
outcome: PermissionOutcome,
},
+ /// An MCP tool call the egress proxy is holding, or held, until the
+ /// session's owner approved it: made in a turn somebody else prompted.
+ ToolApproval {
+ /// The approval an answer names.
+ #[serde(rename = "approvalId")]
+ approval_id: String,
+ /// `macro`, or the connected app's slug.
+ #[serde(rename = "serverSlug")]
+ server_slug: String,
+ /// What a person calls the server the tool is on.
+ #[serde(rename = "serverName")]
+ server_name: String,
+ /// The tool called.
+ #[serde(rename = "toolName")]
+ tool_name: String,
+ /// What it was called with.
+ #[specta(type = specta_typescript::Unknown)]
+ arguments: serde_json::Value,
+ /// Who prompted the turn; absent for a bot on nobody's behalf.
+ #[serde(rename = "requestedBy")]
+ requested_by: Option<String>,
+ /// Where it stands.
+ status: ToolApprovalStatus,
+ /// Who resolved it, when a person did.
+ #[serde(rename = "resolvedBy")]
+ resolved_by: Option<String>,
+ /// Approved for good: the person who asked may make the calls it
+ /// covers without the owner being asked again.
+ remembered: bool,
+ },
/// A user-issued control operation on the session.
Control {
/// The requested operation.
diff --git a/crates/folds/agent_fold/src/domain/model/search.rs b/crates/folds/agent_fold/src/domain/model/search.rs
index 0bd9f483fa..037398a046 100644
--- a/crates/folds/agent_fold/src/domain/model/search.rs
+++ b/crates/folds/agent_fold/src/domain/model/search.rs
@@ -81,6 +81,14 @@ impl SearchText {
self.push(&option.name);
}
}
+ MessagePart::ToolApproval {
+ server_name,
+ tool_name,
+ ..
+ } => {
+ self.push(server_name);
+ self.push(tool_name);
+ }
MessagePart::Control { control, outcome } => {
match control {
Control::SetModel { model } => self.push(model),
diff --git a/crates/folds/agent_fold/src/domain/test/interactions.rs b/crates/folds/agent_fold/src/domain/test/interactions.rs
index b2868105a8..0a3f8e431a 100644
--- a/crates/folds/agent_fold/src/domain/test/interactions.rs
+++ b/crates/folds/agent_fold/src/domain/test/interactions.rs
@@ -1,5 +1,6 @@
//! Shared live-request lifecycle, preserving each protocol's answer shape.
+use agent_runtime_protocol::domain::tool_approval::ToolApprovalStatus;
use serde_json::{Value, json};
use super::util::parse_log;
@@ -171,3 +172,127 @@ fn ending_stopping_and_disconnecting_clear_both_live_requests() {
);
}
}
+
+fn tool_approval(status: &str, resolved_by: Option<&str>) -> Value {
+ let mut params = json!({
+ "approvalId": "a1", "serverSlug": "macro", "serverName": "Macro",
+ "toolName": "ListEmails", "arguments": {"limit": 5},
+ "requestedBy": "macro|[email protected]", "status": status,
+ });
+ if let Some(by) = resolved_by {
+ params["resolvedBy"] = json!(by);
+ }
+ json!({"method": "_macro/tool_approval", "params": params})
+}
+
+fn approval_part(machine: &FoldMachineImpl) -> MessagePart {
+ machine
+ .messages()
+ .iter()
+ .flat_map(|message| message.parts.iter())
+ .find(|part| matches!(part, MessagePart::ToolApproval { .. }))
+ .cloned()
+ .expect("the held call is in the transcript")
+}
+
+#[test]
+fn a_held_tool_call_blocks_the_turn_until_it_is_resolved() {
+ let mut machine = FoldMachineImpl::new();
+ prompt(&mut machine, "p");
+ assert!(push(
+ &mut machine,
+ "to_server",
+ tool_approval("pending", None)
+ ));
+ assert_eq!(machine.metadata().turn, TurnState::Blocked);
+ let [PendingInteraction::ToolApproval(pending)] =
+ machine.metadata().pending_interactions.as_slice()
+ else {
+ panic!("one held call is pending");
+ };
+ assert_eq!(pending.approval_id, "a1");
+ assert_eq!(pending.tool_name, "ListEmails");
+ assert_eq!(
+ pending.requested_by.as_deref(),
+ Some("macro|[email protected]")
+ );
+
+ assert!(push(
+ &mut machine,
+ "to_server",
+ tool_approval("approved", Some("macro|[email protected]"))
+ ));
+ assert!(machine.metadata().pending_interactions.is_empty());
+ assert_eq!(machine.metadata().turn, TurnState::Running);
+ assert!(matches!(
+ approval_part(&machine),
+ MessagePart::ToolApproval { status: ToolApprovalStatus::Approved, resolved_by: Some(by), .. }
+ if by == "macro|[email protected]"
+ ));
+}
+
+#[test]
+fn a_held_tool_call_approved_for_good_says_so() {
+ let mut machine = FoldMachineImpl::new();
+ prompt(&mut machine, "p");
+ push(&mut machine, "to_server", tool_approval("pending", None));
+ assert!(matches!(
+ approval_part(&machine),
+ MessagePart::ToolApproval {
+ remembered: false,
+ ..
+ }
+ ));
+
+ let mut approved = tool_approval("approved", Some("macro|[email protected]"));
+ approved["params"]["remembered"] = json!(true);
+ assert!(push(&mut machine, "to_server", approved));
+ assert!(matches!(
+ approval_part(&machine),
+ MessagePart::ToolApproval {
+ status: ToolApprovalStatus::Approved,
+ remembered: true,
+ ..
+ }
+ ));
+}
+
+#[test]
+fn a_held_tool_call_outside_a_turn_or_resolved_twice_changes_nothing() {
+ let mut machine = FoldMachineImpl::new();
+ assert!(!push(
+ &mut machine,
+ "to_server",
+ tool_approval("pending", None)
+ ));
+ assert!(machine.messages().is_empty());
+
+ prompt(&mut machine, "p");
+ push(&mut machine, "to_server", tool_approval("pending", None));
+ push(&mut machine, "to_server", tool_approval("denied", None));
+ assert!(!push(
+ &mut machine,
+ "to_server",
+ tool_approval("expired", None)
+ ));
+ assert!(matches!(
+ approval_part(&machine),
+ MessagePart::ToolApproval {
+ status: ToolApprovalStatus::Denied,
+ ..
+ }
+ ));
+}
+
+#[test]
+fn stopping_the_turn_hides_a_held_tool_call() {
+ let mut machine = FoldMachineImpl::new();
+ prompt(&mut machine, "p");
+ push(&mut machine, "to_server", tool_approval("pending", None));
+ push(
+ &mut machine,
+ "to_runtime",
+ json!({"method": "session/cancel", "params": {"sessionId": "s"}}),
+ );
+ assert!(machine.metadata().pending_interactions.is_empty());
+}
diff --git a/crates/lexical_client/src/parse_markdown.rs b/crates/lexical_client/src/parse_markdown.rs
index 279c65f5c6..e8b3bd834c 100644
--- a/crates/lexical_client/src/parse_markdown.rs
+++ b/crates/lexical_client/src/parse_markdown.rs
@@ -312,6 +312,25 @@ pub enum AgentContextReplyTarget<'a> {
None,
}
+/// A person an agent session acts for or hears from.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
+pub struct AgentContextPerson<'a> {
+ /// Their Macro user id.
+ pub id: &'a str,
+ /// How a reader names them.
+ pub name: &'a str,
+}
+
+/// Whose access an agent session runs with, and who sent the prompt.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
+pub struct AgentContextPeople<'a> {
+ /// The session's owner.
+ pub owner: AgentContextPerson<'a>,
+ /// The prompt's sender; absent when a bot sent it on nobody's behalf.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub sender: Option<AgentContextPerson<'a>>,
+}
+
/// The conversation an agent prompt was posted in.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "camelCase")]
@@ -389,6 +408,8 @@ struct AgentContextRequest<'a> {
#[serde(skip_serializing_if = "Option::is_none")]
parent: Option<&'a MessageParent>,
#[serde(flatten, skip_serializing_if = "Option::is_none")]
+ people: Option<&'a AgentContextPeople<'a>>,
+ #[serde(flatten, skip_serializing_if = "Option::is_none")]
context: Option<&'a AgentContext<'a>>,
}
@@ -718,6 +739,7 @@ impl LexicalClient {
prompt_markdown: &str,
instructions: Option<&str>,
parent: Option<&MessageParent>,
+ people: Option<&AgentContextPeople<'_>>,
context: Option<&AgentContext<'_>>,
) -> Result<String> {
let url = format!("{}/agent-context", self.url);
@@ -728,6 +750,7 @@ impl LexicalClient {
prompt_markdown,
instructions,
parent,
+ people,
context,
})
.send()
diff --git a/crates/macro_db_client/migrations/20261005203905_agent_session_tool_approval.sql b/crates/macro_db_client/migrations/20261005203905_agent_session_tool_approval.sql
new file mode 100644
index 0000000000..9552dde8e8
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261005203905_agent_session_tool_approval.sql
@@ -0,0 +1,47 @@
+-- Who prompted the turn a session is running, and the MCP tool calls that
+-- turn is waiting on the owner to approve.
+--
+-- A session spends its owner's credentials whoever prompts it, so a turn
+-- somebody else prompted holds each MCP `tools/call` at the egress proxy
+-- until the owner answers. The proxy may run on any replica, and the harness
+-- replica managing the session keeps its in-flight turn in memory, so the
+-- prompter is written here at dispatch, before the runtime can make a call.
+-- Overwritten by the next dispatch, never cleared: a late call from a turn
+-- that already ended is still judged by who prompted it.
+ALTER TABLE agent_session
+ ADD COLUMN turn_action_id UUID,
+ -- NULL with a turn_action_id: a bot prompted on nobody's behalf.
+ ADD COLUMN turn_prompter TEXT;
+
+-- One held tool call. The row is the source of truth for the hold: the proxy
+-- waits on it (woken by NOTIFY on `agent_session_tool_approval`), and exactly
+-- one resolution wins, because every resolution is an update of a still
+-- pending row.
+CREATE TABLE agent_session_tool_approval (
+ id UUID PRIMARY KEY,
+ agent_session_id UUID NOT NULL REFERENCES agent_session (id) ON DELETE CASCADE,
+ -- The turn the call was made in.
+ turn_action_id UUID NOT NULL,
+ -- The held call's JSON-RPC id, so the agent's own cancellation of that
+ -- request can find it.
+ request_id JSONB NOT NULL,
+ -- The owner whose access the call spends, and the only one who may
+ -- approve or decline it.
+ owner_id TEXT NOT NULL,
+ -- Who prompted that turn; NULL for a bot acting on nobody's behalf.
+ requested_by TEXT,
+ -- `macro` for Macro's own server, otherwise the connected app's slug.
+ server_slug TEXT NOT NULL,
+ server_name TEXT NOT NULL,
+ tool_name TEXT NOT NULL,
+ arguments JSONB NOT NULL,
+ status TEXT NOT NULL DEFAULT 'pending'
+ CHECK (status IN ('pending', 'approved', 'denied', 'cancelled', 'expired')),
+ resolved_by TEXT,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ resolved_at TIMESTAMPTZ
+);
+
+CREATE INDEX agent_session_tool_approval_pending
+ ON agent_session_tool_approval (agent_session_id)
+ WHERE status = 'pending';
diff --git a/crates/macro_db_client/migrations/20261005203907_agent_session_tool_standing_approval.sql b/crates/macro_db_client/migrations/20261005203907_agent_session_tool_standing_approval.sql
new file mode 100644
index 0000000000..9e5d9be507
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261005203907_agent_session_tool_standing_approval.sql
@@ -0,0 +1,27 @@
+-- "Approve, and don't ask me again": the owner lets one person make a kind
+-- of tool call in one session without being asked each time.
+--
+-- On Macro's own server a standing approval covers one tool, because that one
+-- server reaches all of the owner's data. A connected app is covered whole.
+-- It lasts as long as the session.
+CREATE TABLE agent_session_tool_standing_approval (
+ agent_session_id UUID NOT NULL REFERENCES agent_session (id) ON DELETE CASCADE,
+ -- Who may now make the calls without asking.
+ user_id TEXT NOT NULL,
+ -- `macro` for Macro's own server, otherwise the connected app's slug.
+ server_slug TEXT NOT NULL,
+ -- The one tool covered on Macro's server; NULL for a whole connected app.
+ tool_name TEXT,
+ -- The owner who said so.
+ granted_by TEXT NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+CREATE UNIQUE INDEX agent_session_tool_standing_approval_scope
+ ON agent_session_tool_standing_approval (
+ agent_session_id, user_id, server_slug, (COALESCE(tool_name, ''))
+ );
+
+-- Whether an approval was given for good, so the session's log can say so.
+ALTER TABLE agent_session_tool_approval
+ ADD COLUMN remembered BOOLEAN NOT NULL DEFAULT false;
diff --git a/crates/mcp_select/src/lib.rs b/crates/mcp_select/src/lib.rs
index 401eb3008f..06218bc0f9 100644
--- a/crates/mcp_select/src/lib.rs
+++ b/crates/mcp_select/src/lib.rs
@@ -27,7 +27,7 @@ use std::sync::Arc;
mod test;
/// Mangled MCP tool names start with this prefix on both stacks.
-const MANGLED_PREFIX: &str = "mcp__";
+pub const MANGLED_PREFIX: &str = "mcp__";
/// A connector identified in both stacks: the Pipedream app slugs and the
/// native server URL that back the same product (e.g. `linear` /
diff --git a/crates/prompt/src/agent_session.rs b/crates/prompt/src/agent_session.rs
index 4e5161c41e..42b1f03b28 100644
--- a/crates/prompt/src/agent_session.rs
+++ b/crates/prompt/src/agent_session.rs
@@ -11,6 +11,7 @@ static INSTRUCTIONS: &str = r##"You are a Macro agent working inside an agent se
- When you reference a Macro document, channel, chat, project, task, email thread, calendar event, person, date/time, agent session, or other mentionable chip, emit the matching XML mention tag (see the mentioning rules). Those tags render as clickable chips in the session and in the channel thread. Do not use plain Markdown links or bare names for Macro items.
- You have no shell and no filesystem. Everything you can do, you do through the tools you are given.
- Work autonomously: nobody can approve intermediate questions mid-turn, so make reasonable assumptions, state them briefly, and proceed.
+- Every prompt opens with a private context block naming the session's owner, whose access you act with, and who sent the prompt. Follow its note on what a prompt from someone else may do.
"##;
static INTENT: &str = "The model behaves as a fast product assistant inside an agent session: \
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index 4caee3b1c2..d254a075d3 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -756,6 +756,28 @@ who has prompted or answered the session also receive an `agent_session_waiting_
notification (inbox, browser, and iOS push) when the question is asked; it stays until
marked done.
+## Tool calls waiting for the session owner
+
+An agent session always runs with its owner's access. When someone else prompts it (a
+second person replying in the session's channel thread, or a bot), every tool call that
+uses that access - Macro's own tools on the owner's email, calendar, documents and so on,
+and any connected app - waits for the owner to approve it. Public lookups (`WebSearch`,
+`WebFetch`, `SelfKnowledge`) and the owner's own turns are never held. The session view
+shows a card over the composer that says what the agent wants to do, e.g. `Dave Seed asked
+the agent to read your email.` The owner sees `Approval needed` with `Decline` /
+`Always allow` / `Approve`; everyone else sees `Waiting for <owner> to approve` (`…to read
+Alice Seed's email`) and, with edit access, a `Cancel` button for when the owner is away.
+`Always allow` approves the call and stops asking about the same person's calls for the
+rest of the session: the same tool on Macro (the card says `Always allow lets Dave Seed
+read your email in this session without asking you.`), every tool of a connected app. It
+also approves that person's other waiting calls it covers, and is not offered for a bot.
+The owner also gets an `agent_session_waiting_for_input` notification. Once answered the
+transcript shows the same action (`Read your email`) with `Approved by …`, `Always allowed
+by …`, `Declined by …`, `Cancelled`, or `Not approved in time` (30 minutes for the
+in-process agent; sandboxed ones wait as long when their MCP client accepts progress, about
+four minutes otherwise). A declined or cancelled call does not run and the agent says so. The Magic Chip
+reads `Waiting for approval`. The agent's hidden context names the owner and the prompter.
+
## In channels
Mention `@Macro` in any channel message. Without the `enable-chat-v3-agents` rollout it is
diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.md
index 27ada2b200..006b7aec75 100644
--- a/docs/AGENT_GUIDE/channels.md
+++ b/docs/AGENT_GUIDE/channels.md
@@ -260,6 +260,8 @@ A late webhook does not require reloading the page.
When the agent requests permission or input, the Magic Chip displays the waiting
status for its anchored turn. Open the session to answer; editors and owners can
respond there. The chip follows the agent's next activity after the answer.
+A tool call held for the owner's approval (a turn somebody other than the owner
+prompted) reads `Waiting for approval`; only the owner approves it, in the session.
Coding agents use `macro_internal.set_pull_request` to register an existing or
new GitHub PR with their session. Macro Internal MCP is hosted by the harness
diff --git a/packages/lexical-core/tests/agent-context.test.ts b/packages/lexical-core/tests/agent-context.test.ts
index 36a7382de3..40de25efaf 100644
--- a/packages/lexical-core/tests/agent-context.test.ts
+++ b/packages/lexical-core/tests/agent-context.test.ts
@@ -359,6 +359,59 @@ describe('composeAgentContextPrompt', () => {
expect(text?.match(/<\/thread>/g)).toHaveLength(1);
});
+ it('names the owner and says an owner prompt is theirs', () => {
+ const owner = { id: 'macro|[email protected]', name: '[email protected]' };
+ expect(
+ composedContext({ promptMarkdown: 'hi', owner, sender: owner })
+ ).toBe(
+ [
+ '<session owner="[email protected]" owner_id="macro|[email protected]">',
+ ' <prompted_by name="[email protected]" id="macro|[email protected]" is_owner="true"/>',
+ ' <note>[email protected] owns this session and sent this prompt.</note>',
+ '</session>',
+ ].join('\n')
+ );
+ });
+
+ it('tells the agent a non-owner prompt cannot spend the owner access', () => {
+ const text = composedContext({
+ promptMarkdown: 'read my email',
+ parent: { type: 'channel', id: 'channel-1' },
+ owner: { id: 'macro|[email protected]', name: '[email protected]' },
+ sender: { id: 'macro|[email protected]', name: '[email protected]' },
+ });
+ expect(text).toMatch(/^<session owner="[email protected]"/);
+ expect(text).toContain(
+ '<prompted_by name="[email protected]" id="macro|[email protected]" is_owner="false"/>'
+ );
+ expect(text).toContain(
+ '[email protected] sent this prompt, but [email protected] owns this session.'
+ );
+ expect(text).toContain(
+ 'Every tool call that uses that access waits for [email protected] to approve it, so use the tools the request needs and let [email protected] decide'
+ );
+ expect(text).toContain('<conversation type="channel" id="channel-1">');
+ });
+
+ it('treats a prompt with no person behind it as not the owner', () => {
+ const text = composedContext({
+ promptMarkdown: 'run',
+ owner: { id: 'macro|[email protected]', name: '[email protected]' },
+ });
+ expect(text).toContain('<prompted_by is_owner="false"/>');
+ expect(text).toContain('but [email protected] owns this session');
+ });
+
+ it('escapes owner and sender names', () => {
+ const text = composedContext({
+ promptMarkdown: 'x',
+ owner: { id: 'o', name: 'o"<' },
+ sender: { id: 's', name: '</session>' },
+ });
+ expect(text).toContain('owner="o&quot;&lt;"');
+ expect(text?.match(/<\/session>/g)).toHaveLength(1);
+ });
+
it('does not add context when there is none', () => {
expect(
composeAgentContextPrompt({ promptMarkdown: 'original', channel: [] })
diff --git a/packages/lexical-core/utils/agent-context.ts b/packages/lexical-core/utils/agent-context.ts
index b05415510e..dd6731d994 100644
--- a/packages/lexical-core/utils/agent-context.ts
+++ b/packages/lexical-core/utils/agent-context.ts
@@ -88,11 +88,22 @@ export type AgentContextAnchor =
| PdfPinCommentAnchor
| { type: 'spreadsheet'; sheetId: string; sheetName: string; range: string };
+/** A person the session acts for or hears from. */
+export type AgentContextPerson = {
+ id: string;
+ /** Readable name. */
+ name: string;
+};
+
/** Input used to compose an agent prompt with private conversation context. */
export type AgentContextPrompt = {
promptMarkdown: string;
/** Trusted session instructions supplied by the agent harness. */
instructions?: string;
+ /** Whose access the session runs with. Supplied by the harness. */
+ owner?: AgentContextPerson;
+ /** Who sent the prompt; absent when a bot sent it on nobody's behalf. */
+ sender?: AgentContextPerson;
/** Supplied by the message service, never by the prompt's author. */
parent?: AgentContextParent;
anchor?: AgentContextAnchor;
@@ -339,7 +350,7 @@ function channelNode(
* outright. A flat history leaves the agent to guess which of several bugs
* "please fix" means.
*/
-function renderConversation(input: AgentContextPrompt): string | undefined {
+function renderConversation(input: AgentContextPrompt): FxpNode | undefined {
const channel = input.channel ?? [];
const children: FxpNode[] = [
...(input.parent
@@ -361,14 +372,54 @@ function renderConversation(input: AgentContextPrompt): string | undefined {
: []),
];
if (children.length === 0) return undefined;
- return buildXml([
- el(
- 'conversation',
- children,
- present({ type: input.parent?.type, id: input.parent?.id })
- ),
- // The builder opens with a newline when formatting.
- ]).trimStart();
+ return el(
+ 'conversation',
+ children,
+ present({ type: input.parent?.type, id: input.parent?.id })
+ );
+}
+
+/**
+ * Name who the session acts for and who is asking. The agent runs with the
+ * owner's access, so a prompt from anyone else must not be able to spend it
+ * on things only the owner should see or do.
+ */
+function sessionNode(
+ owner: AgentContextPerson,
+ sender: AgentContextPerson | undefined
+): FxpNode {
+ const isOwner = sender?.id === owner.id;
+ const prompter = sender?.name ?? 'A bot acting for nobody';
+ const policy = isOwner
+ ? `${owner.name} owns this session and sent this prompt.`
+ : `${prompter} sent this prompt, but ${owner.name} owns this session. You act with the access of ${owner.name} - their email, calendar, documents, and connected apps. Every tool call that uses that access waits for ${owner.name} to approve it, so use the tools the request needs and let ${owner.name} decide. Do not refuse on ${owner.name}'s behalf: the approval request is how they say yes or no. Looking things up on the public web needs no approval. Do not repeat anything private to ${owner.name} that you saw in earlier turns. If a call is declined or not approved, say so and do not look for another way to do it.`;
+ return el(
+ 'session',
+ [
+ el(
+ 'prompted_by',
+ [],
+ present({
+ name: sender?.name,
+ id: sender?.id,
+ is_owner: isOwner ? 'true' : 'false',
+ })
+ ),
+ note(policy),
+ ],
+ { owner: owner.name, owner_id: owner.id }
+ );
+}
+
+function renderContext(input: AgentContextPrompt): string | undefined {
+ const conversation = renderConversation(input);
+ const nodes = [
+ ...(input.owner ? [sessionNode(input.owner, input.sender)] : []),
+ ...(conversation ? [conversation] : []),
+ ];
+ if (nodes.length === 0) return undefined;
+ // The builder opens with a newline when formatting.
+ return buildXml(nodes).trimStart();
}
function renderInstructions(
@@ -410,7 +461,7 @@ export function composeAgentContextPrompt(input: AgentContextPrompt): string {
() => {
const sections = [
renderInstructions(input.instructions),
- renderConversation(input),
+ renderContext(input),
].filter((section) => section !== undefined);
if (sections.length === 0) return;
diff --git a/packages/sdk/generated/agent-harness/index.ts b/packages/sdk/generated/agent-harness/index.ts
index c1ba714096..034081a792 100644
--- a/packages/sdk/generated/agent-harness/index.ts
+++ b/packages/sdk/generated/agent-harness/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AccessLevel, AgentAction, AgentActionId, AgentConfigKindDto, AgentConfigOptionDto, AgentConfigSelectOptionDto, AgentModelDto, AgentModelsStatusDto, AgentPermissionAction, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryBranchesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSessionsForPullRequestData, AgentSessionsForPullRequestError, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponse, AgentSessionsForPullRequestResponses, AgentSetConfigOptionAction, AgentSetModelAction, AiAdmissionErrorBody, BotId, CapabilityHarnessDto, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ChannelSharePermission, ClientOptions, CompleteData, CompleteErrors, CompleteRequest, CompleteResponse, CompleteResponses, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateSessionThread, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponse, DisconnectResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponse, DiscoverAgentCapabilitiesHandlerResponses, DiscoverAgentCapabilitiesRequest, DiscoverAgentCapabilitiesResponse, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmptyRequest, ExternalSessionResponse, FileChangeKindDto, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesError, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchError, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponse, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponse, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsError, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponse, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, GitRefDto, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestError, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponse, LinkAgentSessionPullRequestResponses, LinkShare, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponse, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsError, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponse, ListAgentSessionPullRequestsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, ModelHarnessDto, PermissionAnswer, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PullRequestLinkSource, PullRequestSessionsResponse, PullRequestUrl, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QueuedActionDto, RefreshAgentSessionChangesData, RefreshAgentSessionChangesError, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponse, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, SandboxSize, SandboxSizeBody, SessionBot, SessionPullRequestLink, SessionPullRequestsResponse, SessionStatusDto, SetAgentSessionArchivedData, SetAgentSessionArchivedError, SetAgentSessionArchivedErrors, SetAgentSessionArchivedRequest, SetAgentSessionArchivedResponse, SetAgentSessionArchivedResponses, SharePermissionV2, StartData, StartErrors, StartResponse, StartResponse2, StartResponses, StatusData, StatusErrors, StatusResponse, StatusResponse2, StatusResponses, SteerQueuedActionData, SteerQueuedActionError, SteerQueuedActionErrors, SteerQueuedActionResponse, SteerQueuedActionResponses, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestError, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponse, UnlinkAgentSessionPullRequestResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsError, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponse, UpdateAgentSessionPermissionsResponses, UpdateChannelSharePermission, UpdateOperation, UpdateSharePermissionRequestV2, WithAgentSessionId } from './types.gen';
+export type { AccessLevel, AgentAction, AgentActionId, AgentConfigKindDto, AgentConfigOptionDto, AgentConfigSelectOptionDto, AgentModelDto, AgentModelsStatusDto, AgentPermissionAction, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryBranchesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSessionsForPullRequestData, AgentSessionsForPullRequestError, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponse, AgentSessionsForPullRequestResponses, AgentSetConfigOptionAction, AgentSetModelAction, AiAdmissionErrorBody, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalError, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponse, AnswerAgentSessionToolApprovalResponses, AnswerToolApprovalRequest, AnswerToolApprovalResponse, BotId, CapabilityHarnessDto, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ChannelSharePermission, ClientOptions, CompleteData, CompleteErrors, CompleteRequest, CompleteResponse, CompleteResponses, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateSessionThread, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponse, DisconnectResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponse, DiscoverAgentCapabilitiesHandlerResponses, DiscoverAgentCapabilitiesRequest, DiscoverAgentCapabilitiesResponse, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmptyRequest, ExternalSessionResponse, FileChangeKindDto, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesError, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchError, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponse, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponse, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsError, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponse, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, GitRefDto, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestError, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponse, LinkAgentSessionPullRequestResponses, LinkShare, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponse, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsError, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponse, ListAgentSessionPullRequestsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, ModelHarnessDto, PermissionAnswer, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PullRequestLinkSource, PullRequestSessionsResponse, PullRequestUrl, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QueuedActionDto, RefreshAgentSessionChangesData, RefreshAgentSessionChangesError, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponse, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, SandboxSize, SandboxSizeBody, SessionBot, SessionPullRequestLink, SessionPullRequestsResponse, SessionStatusDto, SetAgentSessionArchivedData, SetAgentSessionArchivedError, SetAgentSessionArchivedErrors, SetAgentSessionArchivedRequest, SetAgentSessionArchivedResponse, SetAgentSessionArchivedResponses, SharePermissionV2, StartData, StartErrors, StartResponse, StartResponse2, StartResponses, StatusData, StatusErrors, StatusResponse, StatusResponse2, StatusResponses, SteerQueuedActionData, SteerQueuedActionError, SteerQueuedActionErrors, SteerQueuedActionResponse, SteerQueuedActionResponses, ToolApprovalAnswerDto, ToolApprovalStatusDto, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestError, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponse, UnlinkAgentSessionPullRequestResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsError, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponse, UpdateAgentSessionPermissionsResponses, UpdateChannelSharePermission, UpdateOperation, UpdateSharePermissionRequestV2, WithAgentSessionId } from './types.gen';
diff --git a/packages/sdk/generated/agent-harness/sdk.gen.ts b/packages/sdk/generated/agent-harness/sdk.gen.ts
index 6c0aa24551..34beadddaf 100644
--- a/packages/sdk/generated/agent-harness/sdk.gen.ts
+++ b/packages/sdk/generated/agent-harness/sdk.gen.ts
@@ -2,7 +2,7 @@
import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';
import { client } from './client.gen';
-import type { AgentSessionsForPullRequestData, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponses, CompleteData, CompleteErrors, CompleteResponses, ControlAgentSessionData, ControlAgentSessionErrors, ControlAgentSessionResponses, CreateAgentSessionData, CreateAgentSessionErrors, CreateAgentSessionResponses, DeleteAgentSessionData, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponses, EditQueuedActionData, EditQueuedActionErrors, EditQueuedActionResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogErrors, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueErrors, GetAgentSessionQueueResponses, GetAgentSessionResponses, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponses, PreviewAgentSessionsData, PreviewAgentSessionsErrors, PreviewAgentSessionsResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponses, RefreshAgentSessionChangesData, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionErrors, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionErrors, RenameAgentSessionResponses, SetAgentSessionArchivedData, SetAgentSessionArchivedErrors, SetAgentSessionArchivedResponses, StartData, StartErrors, StartResponses, StatusData, StatusErrors, StatusResponses, SteerQueuedActionData, SteerQueuedActionErrors, SteerQueuedActionResponses, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponses } from './types.gen';
+import type { AgentSessionsForPullRequestData, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponses, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponses, CompleteData, CompleteErrors, CompleteResponses, ControlAgentSessionData, ControlAgentSessionErrors, ControlAgentSessionResponses, CreateAgentSessionData, CreateAgentSessionErrors, CreateAgentSessionResponses, DeleteAgentSessionData, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponses, EditQueuedActionData, EditQueuedActionErrors, EditQueuedActionResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogErrors, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueErrors, GetAgentSessionQueueResponses, GetAgentSessionResponses, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponses, PreviewAgentSessionsData, PreviewAgentSessionsErrors, PreviewAgentSessionsResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponses, RefreshAgentSessionChangesData, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionErrors, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionErrors, RenameAgentSessionResponses, SetAgentSessionArchivedData, SetAgentSessionArchivedErrors, SetAgentSessionArchivedResponses, StartData, StartErrors, StartResponses, StatusData, StatusErrors, StatusResponses, SteerQueuedActionData, SteerQueuedActionErrors, SteerQueuedActionResponses, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/**
@@ -384,6 +384,22 @@ export class Sdk extends HeyApiClient {
});
}
+ /**
+ * Answer a tool call the agent made in a turn somebody other than the
+ * session's owner prompted. Approve and deny are the owner's; cancel is
+ * anyone's with edit access.
+ */
+ public answerAgentSessionToolApproval<ThrowOnError extends boolean = false>(options: Options<AnswerAgentSessionToolApprovalData, ThrowOnError>): RequestResult<AnswerAgentSessionToolApprovalResponses, AnswerAgentSessionToolApprovalErrors, ThrowOnError> {
+ return (options.client ?? this.client).post<AnswerAgentSessionToolApprovalResponses, AnswerAgentSessionToolApprovalErrors, ThrowOnError>({
+ url: '/agent-sessions/{session_id}/tool-approvals/{approval_id}',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
/**
* Forget only the authenticated user's grant and cancel pending consent.
*/
diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.ts
index 2898097152..8e5709417a 100644
--- a/packages/sdk/generated/agent-harness/types.gen.ts
+++ b/packages/sdk/generated/agent-harness/types.gen.ts
@@ -511,6 +511,26 @@ export type AiAdmissionErrorBody = {
error: string;
};
+/**
+ * Request body for answering a held tool call.
+ */
+export type AnswerToolApprovalRequest = {
+ /**
+ * The answer.
+ */
+ answer: ToolApprovalAnswerDto;
+};
+
+/**
+ * Response body for answering a held tool call.
+ */
+export type AnswerToolApprovalResponse = {
+ /**
+ * Where the call stands now.
+ */
+ status: ToolApprovalStatusDto;
+};
+
export type BotId = string;
/**
@@ -1370,6 +1390,16 @@ export type StatusResponse = {
ephemeral: boolean;
};
+/**
+ * How a person answers a held tool call.
+ */
+export type ToolApprovalAnswerDto = 'approve' | 'approve_and_remember' | 'deny' | 'cancel';
+
+/**
+ * Where a held tool call stands once answered.
+ */
+export type ToolApprovalStatusDto = 'pending' | 'approved' | 'denied' | 'cancelled' | 'expired';
+
export type UpdateChannelSharePermission = {
accessLevel?: null | AccessLevel;
/**
@@ -2221,6 +2251,48 @@ export type PutAgentSessionSandboxSizeResponses = {
export type PutAgentSessionSandboxSizeResponse = PutAgentSessionSandboxSizeResponses[keyof PutAgentSessionSandboxSizeResponses];
+export type AnswerAgentSessionToolApprovalData = {
+ body: AnswerToolApprovalRequest;
+ path: {
+ /**
+ * ID of the agent session
+ */
+ session_id: string;
+ /**
+ * ID of the held tool call
+ */
+ approval_id: string;
+ };
+ query?: never;
+ url: '/agent-sessions/{session_id}/tool-approvals/{approval_id}';
+};
+
+export type AnswerAgentSessionToolApprovalErrors = {
+ 401: string;
+ /**
+ * Not the owner, for approve or deny; or no edit access
+ */
+ 403: string;
+ 404: string;
+ /**
+ * Already resolved
+ */
+ 409: string;
+ /**
+ * Approve for good, for a call no person asked for
+ */
+ 422: string;
+ 500: string;
+};
+
+export type AnswerAgentSessionToolApprovalError = AnswerAgentSessionToolApprovalErrors[keyof AnswerAgentSessionToolApprovalErrors];
+
+export type AnswerAgentSessionToolApprovalResponses = {
+ 200: AnswerToolApprovalResponse;
+};
+
+export type AnswerAgentSessionToolApprovalResponse = AnswerAgentSessionToolApprovalResponses[keyof AnswerAgentSessionToolApprovalResponses];
+
export type DisconnectData = {
body: EmptyRequest;
path?: never;
diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.json
index cc3da35a63..739bea72b5 100644
--- a/packages/sdk/specs/agent-harness.json
+++ b/packages/sdk/specs/agent-harness.json
@@ -1825,6 +1825,117 @@
}
}
},
+ "/agent-sessions/{session_id}/tool-approvals/{approval_id}": {
+ "post": {
+ "tags": ["agent-sessions"],
+ "summary": "Answer a tool call the agent made in a turn somebody other than the\nsession's owner prompted. Approve and deny are the owner's; cancel is\nanyone's with edit access.",
+ "operationId": "answer_agent_session_tool_approval",
+ "parameters": [
+ {
+ "name": "session_id",
+ "in": "path",
+ "description": "ID of the agent session",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ },
+ {
+ "name": "approval_id",
+ "in": "path",
+ "description": "ID of the held tool call",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AnswerToolApprovalRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AnswerToolApprovalResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "Not the owner, for approve or deny; or no edit access",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "409": {
+ "description": "Already resolved",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Approve for good, for a call no person asked for",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/claude-auth": {
"get": {
"tags": ["claude-auth"],
@@ -2705,6 +2816,28 @@
}
}
},
+ "AnswerToolApprovalRequest": {
+ "type": "object",
+ "description": "Request body for answering a held tool call.",
+ "required": ["answer"],
+ "properties": {
+ "answer": {
+ "$ref": "#/components/schemas/ToolApprovalAnswerDto",
+ "description": "The answer."
+ }
+ }
+ },
+ "AnswerToolApprovalResponse": {
+ "type": "object",
+ "description": "Response body for answering a held tool call.",
+ "required": ["status"],
+ "properties": {
+ "status": {
+ "$ref": "#/components/schemas/ToolApprovalStatusDto",
+ "description": "Where the call stands now."
+ }
+ }
+ },
"BotId": {
"type": "string"
},
@@ -3799,6 +3932,16 @@
}
}
},
+ "ToolApprovalAnswerDto": {
+ "type": "string",
+ "description": "How a person answers a held tool call.",
+ "enum": ["approve", "approve_and_remember", "deny", "cancel"]
+ },
+ "ToolApprovalStatusDto": {
+ "type": "string",
+ "description": "Where a held tool call stands once answered.",
+ "enum": ["pending", "approved", "denied", "cancelled", "expired"]
+ },
"UpdateChannelSharePermission": {
"type": "object",
"required": ["operation", "channelId"],
diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.ts
index c31e40c371..8916a21130 100644
--- a/packages/sdk/src/coverage/skipped.ts
+++ b/packages/sdk/src/coverage/skipped.ts
@@ -36,6 +36,7 @@ export const agentHarnessExcluded = [
] as const satisfies readonly (keyof AgentHarnessSdk)[];
export const agentHarnessBacklog = [
+ 'answerAgentSessionToolApproval',
'getAgentSessionPermissions',
'updateAgentSessionPermissions',
] as const satisfies readonly (keyof AgentHarnessSdk)[];
diff --git a/services/agent_harness_service/src/api.rs b/services/agent_harness_service/src/api.rs
index 2cf7d00271..7157a9ae6f 100644
--- a/services/agent_harness_service/src/api.rs
+++ b/services/agent_harness_service/src/api.rs
@@ -75,6 +75,7 @@ pub struct ApiStates<T, R, Opener, Bots, Requests, Access, Auth, Models, Changes
coding_agents: Router,
capabilities: Router,
pull_requests: Router,
+ tool_approvals: Router,
changes: AgentChangesRouterState<Changes, Access, Auth>,
}
@@ -104,6 +105,7 @@ impl<T, R, Opener, Bots, Requests, Access, Auth, Models, Changes>
coding_agents: Router::new(),
capabilities: Router::new(),
pull_requests: Router::new(),
+ tool_approvals: Router::new(),
changes,
}
}
@@ -143,6 +145,12 @@ impl<T, R, Opener, Bots, Requests, Access, Auth, Models, Changes>
self.pull_requests = router;
self
}
+
+ /// Attach the routes answering tool calls held for the owner's approval.
+ pub fn with_tool_approvals(mut self, router: Router) -> Self {
+ self.tool_approvals = router;
+ self
+ }
}
/// Serve session egress and Macro Internal MCP on the existing egress listener.
@@ -244,6 +252,7 @@ where
.merge(agent_session_create_router(states.create))
.merge(states.sharing)
.merge(states.pull_requests)
+ .merge(states.tool_approvals)
.merge(agent_changes_router(states.changes));
Router::new()
.nest("/agent-sessions", agent_sessions)
diff --git a/services/agent_harness_service/src/api/swagger.rs b/services/agent_harness_service/src/api/swagger.rs
index 6fc103f4c9..26b4147621 100644
--- a/services/agent_harness_service/src/api/swagger.rs
+++ b/services/agent_harness_service/src/api/swagger.rs
@@ -13,6 +13,10 @@ use agent_harness::inbound::model_load::{
use agent_harness::inbound::repositories::{
self, AgentRepositoriesResponse, AgentRepositoryBranchesResponse, AgentRepositoryDto,
};
+use agent_harness::inbound::tool_approvals::{
+ self, AnswerToolApprovalRequest, AnswerToolApprovalResponse, ToolApprovalAnswerDto,
+ ToolApprovalStatusDto,
+};
use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId, PromptAttachment};
use agent_session::domain::model::{SandboxSize, SessionBot};
use agent_session::domain::pull_request_links::{PullRequestLinkSource, SessionPullRequestLink};
@@ -84,6 +88,7 @@ impl Modify for SecurityAddon {
changes_router::get_agent_session_changes_handler,
changes_router::get_agent_session_changes_patch_handler,
changes_router::refresh_agent_session_changes_handler,
+ tool_approvals::answer_tool_approval_handler,
),
components(schemas(
claude_auth::StatusResponse,
@@ -140,6 +145,10 @@ impl Modify for SecurityAddon {
CaptureOutcomeDto,
ChangesetSourceDto,
FileChangeKindDto,
+ AnswerToolApprovalRequest,
+ AnswerToolApprovalResponse,
+ ToolApprovalAnswerDto,
+ ToolApprovalStatusDto,
)),
tags(
(name = "agent-sessions", description = "Agent sessions"),
diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rs
index 18f7eff248..9187da8f01 100644
--- a/services/agent_harness_service/src/main.rs
+++ b/services/agent_harness_service/src/main.rs
@@ -33,6 +33,7 @@ use agent_changes::domain::service::{AgentChangesService, CaptureOnTurnEnd};
use agent_changes::inbound::axum_router::AgentChangesRouterState;
use agent_changes::outbound::postgres::PgChangesetRepo;
use agent_changes::outbound::s3::S3ChangesetBlobStore;
+use agent_egress::domain::approval::ToolApprovalService;
use agent_egress::domain::service::EgressServiceImpl;
use agent_egress::outbound::custom_mcp::WithCustomMcp;
use agent_egress::outbound::forwarder::ReqwestForwarder;
@@ -40,6 +41,7 @@ use agent_egress::outbound::github_tokens::GithubAppTokens;
use agent_egress::outbound::macro_mcp::{MacroApiTokenSigner, WithMacroMcp};
use agent_egress::outbound::mcp_credentials::PipedreamMcpCredentials;
use agent_egress::outbound::session_authority::StoredTokenSessionAuthority;
+use agent_egress::outbound::tool_approvals::{PgToolApprovalSignals, PgToolApprovalStore};
use agent_fold::domain::service::FoldedMessageService;
use agent_harness::domain::model::{
AgentKind, AgentRuntimeConfig, HarnessCommand, HarnessDefaults, SessionDefaults,
@@ -54,6 +56,7 @@ use agent_harness::domain::trigger_router::{
use agent_harness::inbound::model_load::AgentModelsRouterState;
use agent_harness::inbound::repositories::AgentRepositoriesRouterState;
use agent_harness::inbound::runtime_gateway::RuntimeGatewayState;
+use agent_harness::inbound::tool_approvals::{ToolApprovalsRouterState, tool_approvals_router};
use agent_harness::outbound::agent_prompt_composer::LexicalAgentPromptComposer;
use agent_harness::outbound::channel_announcer::MessageAnnouncer;
use agent_harness::outbound::channel_prompt_context::MessagePromptContextAdapter;
@@ -72,6 +75,9 @@ use agent_harness::outbound::notifications::IngressAgentSessionNotifier;
use agent_harness::outbound::prompt_mentions::{LexicalPromptMentions, PgSessionAccess};
use agent_harness::outbound::routing::RoutedContainerManager;
use agent_harness::outbound::runtime_registry::{HarnessKeyedConnections, RuntimeRegistry};
+use agent_harness::outbound::tool_approvals::{
+ ReleaseHeldCallsOnTurnEnd, SessionToolApprovalAnnouncer,
+};
use agent_inmem::domain::engine::TurnEngine;
use agent_inmem::outbound::acp_mcp::AcpMcpConnector;
use agent_inmem::outbound::egress_mcp::EgressMcpClient;
@@ -436,6 +442,18 @@ async fn run() -> anyhow::Result<()> {
// The egress proxy: one binary today, its own listener from the start.
// Shared with the in-memory runtime, which calls it directly rather than
// through that listener.
+ // Tool calls in a turn somebody other than the owner prompted wait here
+ // for the owner. The rows and their NOTIFY wake a hold on whichever
+ // replica serves it; each state lands in the session's log for its
+ // viewers, and a call that starts waiting notifies the owner.
+ let tool_approvals = Arc::new(ToolApprovalService::new(
+ PgToolApprovalStore::new(pool.clone()),
+ PgToolApprovalSignals::spawn(pool.clone()),
+ SessionToolApprovalAnnouncer::new(
+ sessions.clone(),
+ IngressAgentSessionNotifier::new(Arc::clone(&notifications)),
+ ),
+ ));
let egress = Arc::new(
EgressServiceImpl::new(
StoredTokenSessionAuthority::new(PgAgentSessionRepo::new(
@@ -459,7 +477,8 @@ async fn run() -> anyhow::Result<()> {
macro_service_urls::PreviewGatewayUrl::new()?
))?,
matches!(config.environment, Environment::Local),
- )?,
+ )?
+ .with_owner_approvals(Arc::clone(&tool_approvals)),
);
// The proxy's public address, read once: the provisioner builds the
@@ -483,8 +502,16 @@ async fn run() -> anyhow::Result<()> {
)
.await
.context("failed to build the in-memory agent tool context")?;
- let inmem_model_engine: Arc<dyn TurnEngine> =
- Arc::new(RigTurnEngine::new(pool.clone(), tool_context));
+ // Macro's own tools run in-process here rather than through the egress
+ // proxy, so they are held for the owner by the same approvals.
+ let inmem_model_engine: Arc<dyn TurnEngine> = Arc::new(
+ RigTurnEngine::new(pool.clone(), tool_context).with_gate(Arc::new(
+ agent_inmem::outbound::approval_gate::OwnerApprovalGate::new(
+ session_repo.clone(),
+ Arc::clone(&tool_approvals),
+ ),
+ )),
+ );
// A model provider cannot fetch images from a private local-stack hostname.
// Resolve its static-file links through the existing attachment service,
// including links replayed from earlier turns, before calling the model.
@@ -963,7 +990,12 @@ async fn run() -> anyhow::Result<()> {
PgPermissionPolicySource::new(PgBotsRepo::new(pool.clone())),
PgCodingAgentSource::new(PgBotsRepo::new(pool.clone())),
defaults,
- Arc::clone(&lifecycle_publisher),
+ // A turn that ends, stops, or is deleted leaves no one waiting on
+ // its held tool calls.
+ ReleaseHeldCallsOnTurnEnd::new(
+ Arc::clone(&lifecycle_publisher),
+ Arc::clone(&tool_approvals),
+ ),
pending_commands,
prompt_mentions,
// Finished / asking / mentioned reach people through the same
@@ -1214,10 +1246,15 @@ async fn run() -> anyhow::Result<()> {
let sharing = agent_session::inbound::axum_router::sharing::agent_session_sharing_router(
AgentSessionRouterState::new(
agent_session::domain::sharing::SessionSharingService::new(session_repo.clone()),
- entity_access,
+ entity_access.clone(),
MacroAuthorizationState::new(Arc::new(authorization_service.clone())),
),
);
+ let tool_approval_answers = tool_approvals_router(ToolApprovalsRouterState::new(
+ tool_approvals,
+ entity_access.clone(),
+ MacroAuthorizationState::new(Arc::new(authorization_service.clone())),
+ ));
let http = tokio::spawn(async move {
if let Err(error) = api::setup_and_serve(
api::ApiStates::new(
@@ -1234,7 +1271,8 @@ async fn run() -> anyhow::Result<()> {
.with_routine_sessions(routine_sessions)
.with_coding_agents(coding_agents)
.with_capabilities(capabilities)
- .with_pull_requests(pull_requests),
+ .with_pull_requests(pull_requests)
+ .with_tool_approvals(tool_approval_answers),
http_runtime_commands_readiness,
http_port,
shutdown_signal(),
diff --git a/services/lexical-service/src/endpoints/agent-context.ts b/services/lexical-service/src/endpoints/agent-context.ts
index 7002b30a46..69392e0a84 100644
--- a/services/lexical-service/src/endpoints/agent-context.ts
+++ b/services/lexical-service/src/endpoints/agent-context.ts
@@ -73,9 +73,16 @@ const replyTarget = z.discriminatedUnion('kind', [
}),
]);
+const person = z.object({
+ id: z.string().min(1),
+ name: z.string(),
+});
+
const agentContextRequest = z.object({
promptMarkdown: z.string(),
instructions: z.string().optional(),
+ owner: person.optional(),
+ sender: person.optional(),
parent: messageParent.optional(),
anchor: commentAnchor.optional(),
replyTarget: replyTarget.optional(),
@@ -92,7 +99,7 @@ export class AgentContextEndpoint extends OpenAPIRoute {
schema = {
summary: 'Compose an agent prompt with conversation context',
description:
- 'Builds internal markdown containing trusted session instructions and the conversation the prompt was posted in - its thread, the channel around it, what it replies to, and the comment anchor it sits on - followed by the user prompt.',
+ 'Builds internal markdown naming the session owner and the prompt sender, and containing trusted session instructions and the conversation the prompt was posted in - its thread, the channel around it, what it replies to, and the comment anchor it sits on - followed by the user prompt.',
request: {
body: {
content: {