diff --git a/.changeset/33690-ai-action-confirmation-hand-off.md b/.changeset/33690-ai-action-confirmation-hand-off.md new file mode 100644 index 00000000000..67b1c094de1 --- /dev/null +++ b/.changeset/33690-ai-action-confirmation-hand-off.md @@ -0,0 +1,28 @@ +--- +'@objectstack/runtime': minor +'@objectstack/mcp': minor +--- + +feat(runtime,mcp)!: an action declaring `ai.requiresConfirmation: true` never runs on the MCP caller's own `confirm: true` — `run_action` and `resume_run` hand it to the person in the app + +Clause-②: no (narrowing) +Metadata-protocol: semantic +Skills-docs: follow-up #34210 + + + +**BREAKING** for an MCP client, an agent or a script that runs an action declaring `ai.requiresConfirmation: true` through the `run_action` or `resume_run` tool by sending `confirm: true` itself. Ruled by the account owner on the safety fix: the caller's own `confirm: true` never counts on such a call; the person it runs as confirms it in the app. + +This release implements the hand-off and refusal steps of the amended confirmation contract (`AI_ACTION_CONFIRMATION_CAPABILITY`, `@objectstack/spec/contracts`). The MCP doors do not elicit in the client yet: every declared-gated call takes the hand-off, whatever the client advertised. + +- After every admission gate, the subject load and the caller-scope subject verdict included, a declared-gated call is handed to the host's pending-confirmation service (`IActionConfirmationService`, registered under `ACTION_CONFIRMATION_SERVICE` = `'ai.actionConfirmation'`) through its `submit` member, and the call is answered with `status: 'pending_confirmation'`, the service's `pendingId`, a plain message, `actionName` and `objectName`. That answer is the tool's successful result. Nothing runs, and no `action_invocation` row is written. A `resume_run` hand-off carries its run (`run: { runId, values }`) and the run stays paused; approving it is the host's, as is what happens after. +- A host that registers no such service (the open-source build ships none) refuses the call `428 ACTION_CONFIRMATION_REQUIRED` with `details.reason: 'no_confirmation_service'`, with or without `confirm: true`. The person performs the action in the app. +- A service that answers no `pendingId` is a fault: the call fails and nothing runs. +- An AI service account acting for itself is refused whatever it sends, as before (ADR-0151 D3 rule 3). Its refusal now carries `details.reason: 'service_account'` at every action door, REST `/actions` and a host's door included. +- Unchanged: REST `/actions` stays outside the gate for a person; a host's door (`dispatchAction`) under the `ai` posture still reads `confirm`; the MCP `delete_record` and `delete_records` gates still read `confirm: true`. The `confirm` member stays accepted on `run_action` and `resume_run` and is not read. + +What changes for a caller: + +- FROM confirm with the person yourself, then send `confirm: true` on `run_action` / `resume_run` TO relay the pending answer's message and let the person approve it in the app; do not retry the call. +- FROM a script or agent that runs a gated action unattended with `confirm: true` TO a pending answer the person decides in the app, or the `no_confirmation_service` refusal on a host without the service. Where the action is safe unattended, its author declares `ai.requiresConfirmation: false`. +- A host that wants its people to approve these calls registers an `IActionConfirmationService` under `ACTION_CONFIRMATION_SERVICE`. diff --git a/examples/app-todo/test/mcp-actions.test.ts b/examples/app-todo/test/mcp-actions.test.ts index 08e51a7e2f8..5aed6e4aa9d 100644 --- a/examples/app-todo/test/mcp-actions.test.ts +++ b/examples/app-todo/test/mcp-actions.test.ts @@ -227,7 +227,7 @@ describe('app-todo business actions over MCP (CE runtime, no service-ai)', () => // bridge never sees the runtime gate. Here the member travels from a real // JSON-RPC `tools/call`, through both of those layers, into the real gate — // and the record afterwards says whether anything ran. - it('step 7: ai.requiresConfirmation is ENFORCED, and satisfiable', async () => { + it('step 7: ai.requiresConfirmation is ENFORCED, and the caller\'s confirm: true never satisfies it', async () => { // Same app, but todo_complete_task now declares the author's gate. const gatedConfirmObjects = withTaskAction(mergedObjects, 'todo_complete_task', (a) => ({ ...a, @@ -241,23 +241,21 @@ describe('app-todo business actions over MCP (CE runtime, no service-ai)', () => const gatedId = await seedTask('Needs a human'); - // 7a — WITHOUT the member: refused, with the declared code, and NOTHING ran. - const refused = await callMcp(confirmBridge, toolsCall(12, 'run_action', { actionName: 'todo_complete_task', recordId: gatedId })); - expect(refused.result?.isError).toBe(true); - const refusedEnvelope = JSON.parse(refused.result?.content?.[0]?.text ?? '{}'); - expect(refusedEnvelope?.error?.code).toBe('ACTION_CONFIRMATION_REQUIRED'); - expect(refusedEnvelope?.error?.status).toBe(428); - expect(refusedEnvelope?.error?.details?.actionName).toBe('todo_complete_task'); - expect(refusedEnvelope?.error?.details?.confirmationMember).toBe('confirm'); - expect(await statusOf(gatedId)).toBe('not_started'); - - // 7b — WITH the member: the identical call succeeds and the handler runs. - // This is the leg that proves the member is not stripped: before the door - // grew it, this call was refused exactly like 7a and the action was - // permanently un-invokable. - const confirmed = await callMcp(confirmBridge, toolsCall(13, 'run_action', { actionName: 'todo_complete_task', recordId: gatedId, confirm: true })); - expect(confirmed.result?.isError, confirmed.result?.content?.[0]?.text).not.toBe(true); - expect(await statusOf(gatedId)).toBe('completed'); + // 7a/7b — [#33690] WITH the member and WITHOUT it alike: this app registers + // no pending-confirmation service, so the call is refused with the + // declared code and `details.reason: 'no_confirmation_service'`, and + // NOTHING ran. Before the amended contract 7b (with `confirm: true`) ran + // the handler; the member now travels the whole path and confers nothing. + for (const [id, extra] of [[12, {}], [13, { confirm: true }]] as const) { + const refused = await callMcp(confirmBridge, toolsCall(id, 'run_action', { actionName: 'todo_complete_task', recordId: gatedId, ...extra })); + expect(refused.result?.isError).toBe(true); + const refusedEnvelope = JSON.parse(refused.result?.content?.[0]?.text ?? '{}'); + expect(refusedEnvelope?.error?.code).toBe('ACTION_CONFIRMATION_REQUIRED'); + expect(refusedEnvelope?.error?.status).toBe(428); + expect(refusedEnvelope?.error?.details?.actionName).toBe('todo_complete_task'); + expect(refusedEnvelope?.error?.details?.reason).toBe('no_confirmation_service'); + expect(await statusOf(gatedId)).toBe('not_started'); + } // 7c — the heuristic must NOT gate: todo_delete_completed is `variant:'danger'` // and the listing calls it requiresConfirmation, but its author declared diff --git a/packages/mcp/src/mcp-action-confirmation-handoff-33690.test.ts b/packages/mcp/src/mcp-action-confirmation-handoff-33690.test.ts new file mode 100644 index 00000000000..73f58b3664f --- /dev/null +++ b/packages/mcp/src/mcp-action-confirmation-handoff-33690.test.ts @@ -0,0 +1,134 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#33690] The `run_action` and `resume_run` tools relay the amended + * confirmation contract's two answers through the real MCP door + * (`MCPServerRuntime.handleHttpRequest`, JSON-RPC `tools/call`): + * + * - a hand-off (`ActionConfirmationPending`, `status: 'pending_confirmation'`) + * is the call's SUCCESSFUL answer: not an error result, the pending id and + * message intact, so an agent tells its person where to approve; + * - the `no_confirmation_service` refusal keeps the registered envelope + * (`428 ACTION_CONFIRMATION_REQUIRED`) with `details.reason`. + * + * The bridge is a double standing in for the runtime door, whose hand-off is + * pinned in `packages/runtime/src/action-confirmation-handoff-33690.test.ts`; + * this package asserts the tool's half (relay, envelope) without depending on + * `@objectstack/runtime`, which deliberately does not depend back. + */ + +import { describe, it, expect } from 'vitest'; + +import { AI_ACTION_CONFIRMATION_MEMBER, type ActionConfirmationPending } from '@objectstack/spec/contracts'; + +import { MCPServerRuntime } from './mcp-server-runtime.js'; +import type { McpDataBridge, McpActionBridge } from './mcp-http-tools.js'; + +const GATED = 'archive_account'; + +const pendingOf = (n: number): ActionConfirmationPending => ({ + status: 'pending_confirmation', + pendingId: `pa_${n}`, + message: `Action '${GATED}' on 'account' declares ai.requiresConfirmation: true, so a person confirms it. Pending confirmation: pa_${n}.`, + actionName: GATED, + objectName: 'account', +}); + +const NO_SERVICE = () => Object.assign( + new Error(`Action '${GATED}' on 'account' declares ai.requiresConfirmation: true, so a person confirms it — nothing was run.`), + { + code: 'ACTION_CONFIRMATION_REQUIRED', + status: 428, + details: { actionName: GATED, objectName: 'account', confirmationMember: AI_ACTION_CONFIRMATION_MEMBER, reason: 'no_confirmation_service' }, + }, +); + +function makeBridge(mode: 'service' | 'none'): McpDataBridge & McpActionBridge & { calls: any[] } { + const calls: any[] = []; + let n = 0; + const answer = async () => { + if (mode === 'none') throw NO_SERVICE(); + return pendingOf(++n); + }; + return { + calls, + async listObjects() { return []; }, + async describeObject() { return null; }, + async query() { return { records: [] }; }, + async get() { return null; }, + async create() { return {}; }, + async update() { return {}; }, + async remove() { return {}; }, + async listActions() { + return [{ name: GATED, objectName: 'account', type: 'script', requiresRecord: true, requiresConfirmation: true }]; + }, + async runAction(name: string, input: any) { + calls.push(['runAction', name, input]); + return answer(); + }, + async resumeRun(runId: string, input: any) { + calls.push(['resumeRun', runId, input]); + return answer(); + }, + }; +} + +function mcpRequest(body: unknown): Request { + return new Request('http://localhost/api/v1/mcp', { + method: 'POST', + headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, + body: JSON.stringify(body), + }); +} + +const toolsCall = (id: number, name: string, args: Record) => ({ + jsonrpc: '2.0', id, method: 'tools/call', params: { name, arguments: args }, +}); + +async function call(bridge: McpDataBridge & McpActionBridge, body: unknown): Promise { + const runtime = new MCPServerRuntime({ name: 'objectstack-test', version: '9.9.9' }); + const res = await runtime.handleHttpRequest(mcpRequest(body), { bridge, parsedBody: body }); + return res.json(); +} + +describe('[#33690] run_action and resume_run relay a hand-off as the call\'s successful answer', () => { + it('run_action: each confirm: true call answers pending_confirmation with its own pending id, never an error', async () => { + const bridge = makeBridge('service'); + for (let i = 1; i <= 3; i++) { + const json = await call(bridge, toolsCall(i, 'run_action', { actionName: GATED, recordId: 'a1', [AI_ACTION_CONFIRMATION_MEMBER]: true })); + expect(json.result.isError).toBeFalsy(); + expect(JSON.parse(json.result.content[0].text)).toEqual(pendingOf(i)); + } + }); + + it('resume_run: the hand-off is relayed the same way', async () => { + const bridge = makeBridge('service'); + const json = await call(bridge, toolsCall(1, 'resume_run', { runId: 'run_1', values: { reason: 'x' }, [AI_ACTION_CONFIRMATION_MEMBER]: true })); + expect(json.result.isError).toBeFalsy(); + expect(JSON.parse(json.result.content[0].text)).toEqual(pendingOf(1)); + expect(bridge.calls[0]).toEqual(['resumeRun', 'run_1', { values: { reason: 'x' }, [AI_ACTION_CONFIRMATION_MEMBER]: true }]); + }); + + it('no service: the refusal keeps the registered envelope and carries details.reason', async () => { + for (const [tool, args] of [ + ['run_action', { actionName: GATED, recordId: 'a1', [AI_ACTION_CONFIRMATION_MEMBER]: true }], + ['resume_run', { runId: 'run_1', [AI_ACTION_CONFIRMATION_MEMBER]: true }], + ] as const) { + const json = await call(makeBridge('none'), toolsCall(1, tool, args)); + expect(json.result.isError, tool).toBe(true); + const envelope = JSON.parse(json.result.content[0].text); + expect({ code: envelope.error.code, status: envelope.error.status }, tool).toEqual({ code: 'ACTION_CONFIRMATION_REQUIRED', status: 428 }); + expect(envelope.error.details, tool).toEqual({ + actionName: GATED, objectName: 'account', confirmationMember: AI_ACTION_CONFIRMATION_MEMBER, reason: 'no_confirmation_service', + }); + } + }); + + it('the member stays accepted on both tools, so a call carrying it is not refused for it', async () => { + const json = await call(makeBridge('service'), { jsonrpc: '2.0', id: 1, method: 'tools/list' }); + for (const name of ['run_action', 'resume_run']) { + const tool = json.result.tools.find((t: any) => t.name === name); + expect(tool?.inputSchema.properties[AI_ACTION_CONFIRMATION_MEMBER]?.type, name).toBe('boolean'); + } + }); +}); diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index ba573d098ad..0a178bb2360 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -431,6 +431,10 @@ export interface McpActionBridge { * as the caller, loads the subject record under RLS when row-context, then * dispatches through the framework action runner. Throws on * denial / not-found / handler failure so the tool surfaces a tool-error. + * [#33690] An action declaring `ai.requiresConfirmation: true` is not run: + * the host hands it to the person and resolves to the contract's + * `ActionConfirmationPending` (`status: 'pending_confirmation'`), which the + * tool relays as its successful result; the request's `confirm` is not read. */ runAction( name: string, @@ -469,7 +473,9 @@ export interface McpActionBridge { * caller, and the run is parked on a screen. Resolves to `runAction`'s * envelope (`{ ok, action, objectName, recordId?, result }`). A run that * pauses on its next screen comes back paused again. Throws on refusal, with - * the ADR-0112 `code` / `status` on the thrown value. + * the ADR-0112 `code` / `status` on the thrown value. [#33690] A resume of a + * gated action resolves to `ActionConfirmationPending` instead, as + * {@link runAction} does, and the run stays parked. * * OPTIONAL, like {@link McpDataBridge.aggregate}. A host that cannot resume * runs omits it, and `resume_run` is then not registered. @@ -3364,10 +3370,16 @@ export function registerActionTools( 'this can mutate data or trigger flows. Invocation is gated (author AI opt-in + your capabilities), ' + 'but the action body itself runs as trusted application code with the app\'s full data authority. ' + 'Supply recordId for actions that operate on a specific record, and params for any declared inputs. ' + - 'An action the author gated (list_actions reports requiresConfirmation) is REFUSED unless you also ' + - 'send confirm: true — ask the human first, then retry; nothing runs on a refused call. ' + - // [ADR-0151 D3 rule 3] `actionConfirmationRefusal` (runtime) never reads - // the member for an AI service account, so no retry is taught to one. + // [#33690] The amended confirmation contract: the caller's `confirm` + // never counts on an action whose author declared + // `ai.requiresConfirmation: true`; the person is asked in the app. + 'An action its author declared ai.requiresConfirmation: true never runs on this call, and confirm: true ' + + 'does not change that: the call is handed to the person you act for, who approves or rejects it in ' + + 'the app, and you are answered status "pending_confirmation" with a pendingId and a message to pass on. ' + + 'Nothing has run then; do not retry, tell the user to approve it. Where the server cannot hand it off, ' + + 'the call is refused ACTION_CONFIRMATION_REQUIRED (details.reason "no_confirmation_service"): the user ' + + 'performs the action in the app. ' + + // [ADR-0151 D3 rule 3] An AI service account is refused, never handed off. 'Under an AI service account\'s own key (an agent acting for itself, for no person) the call is ' + 'refused whatever it sends and nothing runs: hand the action to a person, or its author declares ' + 'ai.requiresConfirmation: false when it is safe unattended. ' + @@ -3446,11 +3458,9 @@ export function registerActionTools( .boolean() .optional() .describe( - 'Set to true to confirm a call the app author gated with ai.requiresConfirmation ' - + '(list_actions reports requiresConfirmation for each action). Assert this only when ' - + 'the human in the loop has approved THIS call; without it a gated action is refused ' - + 'and nothing runs. Under an AI service account\'s own key it is not read: the call is ' - + 'refused whatever it sends.', + 'Not read by this tool: an action its author declared ai.requiresConfirmation: true is handed ' + + 'to the person to approve in the app whatever this member says, and any other action runs ' + + 'without it. Accepted so that a call carrying it is not refused for it.', ), }, ), @@ -3545,9 +3555,12 @@ export function registerActionTools( 'pauses again on its NEXT screen with a new screen to fill (call resume_run again for it). Only ' + 'the user whose call started the run can resume it, and it is gated exactly as run_action is ' + '(author AI opt-in, your capabilities, your read access to the record). The rest of the flow runs ' + - 'the app\'s business logic and can mutate data. When list_actions reports requiresConfirmation for ' + - 'the action that started the run, send confirm: true (ask the human first); without it the call ' + - 'is refused and the run stays paused. Under an AI service account\'s own key the call is refused ' + + 'the app\'s business logic and can mutate data. When the action that started the run was declared ' + + 'ai.requiresConfirmation: true, the run does not continue on this call and confirm: true does not ' + + 'change that: it is handed to the person you act for, who approves or rejects it in the app, and you ' + + 'are answered status "pending_confirmation" with a pendingId; the run stays paused until they ' + + 'approve. Where the server cannot hand it off, the call is refused ACTION_CONFIRMATION_REQUIRED and ' + + 'the run stays paused. Under an AI service account\'s own key the call is refused ' + 'whatever it sends and the run stays paused: hand it to a person. A run that fails answers as ' + 'run_action does: tell the user the reason in the second text block, never the flow and node chain ' + 'in the error message.', @@ -3589,11 +3602,9 @@ export function registerActionTools( .boolean() .optional() .describe( - 'Set to true to confirm resuming a run of an action the app author gated with ' - + 'ai.requiresConfirmation (list_actions reports requiresConfirmation). Assert this only when ' - + 'the human in the loop has approved THIS call; without it the call is refused and the run ' - + 'stays paused. Under an AI service account\'s own key it is not read: the call is refused ' - + 'whatever it sends.', + 'Not read by this tool: a resume of a run whose action was declared ai.requiresConfirmation: ' + + 'true is handed to the person to approve in the app whatever this member says. Accepted so ' + + 'that a call carrying it is not refused for it.', ), }, ), diff --git a/packages/mcp/src/mcp-resume-run-tool.test.ts b/packages/mcp/src/mcp-resume-run-tool.test.ts index 60f7c959ca1..07caae9e20c 100644 --- a/packages/mcp/src/mcp-resume-run-tool.test.ts +++ b/packages/mcp/src/mcp-resume-run-tool.test.ts @@ -96,9 +96,10 @@ describe('MCP resume_run — where it is registered', () => { expect(tool.description, name).toContain('confirm: true'); expect(tool.description, name).toContain("Under an AI service account's own key"); expect(tool.description, name).toContain('refused whatever it sends'); - expect(tool.inputSchema.properties.confirm.description, name).toContain( - "Under an AI service account's own key it is not read", - ); + // [#33690] The member is not read by either tool for anyone now: a + // declared-gated call is handed to the person, whatever it says. + expect(tool.inputSchema.properties.confirm.description, name).toContain('Not read by this tool'); + expect(tool.description, name).toContain('pending_confirmation'); } expect(tools.run_action.description).toContain('ai.requiresConfirmation: false when it is safe unattended'); }); diff --git a/packages/qa/dogfood/test/action-confirmation-handoff-33690.dogfood.test.ts b/packages/qa/dogfood/test/action-confirmation-handoff-33690.dogfood.test.ts new file mode 100644 index 00000000000..f01fda14bdc --- /dev/null +++ b/packages/qa/dogfood/test/action-confirmation-handoff-33690.dogfood.test.ts @@ -0,0 +1,176 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [#33690] The amended confirmation contract at the live MCP door: an action +// whose author declared `ai.requiresConfirmation: true` never runs on the +// caller's own `confirm: true`. The call is handed to the host's +// pending-confirmation service (`IActionConfirmationService`, registered under +// `ACTION_CONFIRMATION_SERVICE`) and answered `status: 'pending_confirmation'` +// with the service's pending id. +// +// Real stack, real `SecurityPlugin`, real MCP plugin, over the Streamable HTTP +// transport as a signed-in person. The host's service is a plugin double that +// records each hand-off and runs nothing, standing in for a host's own (the +// open build ships none; a stack without one refuses with +// `details.reason: 'no_confirmation_service'`, pinned at the doors in +// `approval-decide-over-mcp.dogfood.test.ts` and +// `mcp-system-object-action-exposure.dogfood.test.ts`). +// +// ⭐ the same `run_action` call carrying `confirm: true`, sent N times, +// writes the record 0 times and is held N times, each with its own +// pending id, each hand-off recorded for the person the call ran as; +// ⭐ CONTROL: the same update through an action that declares no +// confirmation runs at once, and nobody is asked. + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { type VerifyStack } from '@objectstack/verify'; +import { bootStack } from '@objectstack/verify'; +import { MCPServerPlugin } from '@objectstack/mcp'; +import { defineStack } from '@objectstack/spec'; +import { ObjectSchema, Field } from '@objectstack/spec/data'; +import { PermissionSetSchema, type PermissionSet } from '@objectstack/spec/security'; +import { ACTION_CONFIRMATION_SERVICE, AI_ACTION_CONFIRMATION_MEMBER } from '@objectstack/spec/contracts'; +import { SecurityPlugin, securityDefaultPermissionSets } from '@objectstack/plugin-security'; +import { catalogPermissionSet } from './catalog-permission-set.js'; + +const OBJECT = 'achoff_ticket'; +const GATED = 'achoff_close_ticket'; +const PLAIN = 'achoff_flag_ticket'; +const PERSON = 'achoff-person@verify.test'; +const SYS = { context: { isSystem: true } } as const; +const N = 3; +const rowsOf = (r: any): any[] => (Array.isArray(r) ? r : Array.isArray(r?.records) ? r.records : Array.isArray(r?.value) ? r.value : []); + +const ticket = ObjectSchema.create({ + name: OBJECT, + label: 'Ticket', + pluralLabel: 'Tickets', + fields: { + name: Field.text({ label: 'Name', required: true }), + status: Field.text({ label: 'Status' }), + }, + actions: [ + { + name: GATED, label: 'Close Ticket', objectName: OBJECT, operation: 'update', patch: { status: 'closed' }, + ai: { exposed: true, description: 'Close the ticket for good, so no further work is taken on it.', requiresConfirmation: true }, + }, + { + name: PLAIN, label: 'Flag Ticket', objectName: OBJECT, operation: 'update', patch: { status: 'flagged' }, + ai: { exposed: true, description: 'Flag the ticket so a person looks at it during the next review.' }, + }, + ], +} as never); + +const stackConfig = defineStack({ + manifest: { + id: 'com.dogfood.action-confirmation-handoff', + namespace: 'achoff', + version: '0.0.0', + type: 'app', + name: 'Action Confirmation Hand-off Fixture', + description: 'One object with a confirmation-gated declarative update, run over MCP.', + }, + objects: [ticket], +}); + +const baselineSet: PermissionSet = PermissionSetSchema.parse({ + name: 'achoff_baseline', + label: 'Action Confirmation Hand-off Baseline — CRUD on the fixture object', + objects: { [OBJECT]: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: false } }, +}); + +/** The host's pending-confirmation service double: records the hand-off, runs nothing. */ +const handOffs: Array<{ handOff: any; userId: unknown }> = []; +const confirmationServicePlugin = { + name: 'com.dogfood.action-confirmation-service', + version: '1.0.0', + init: async (ctx: any) => { + ctx.registerService(ACTION_CONFIRMATION_SERVICE, { + submit: async (handOff: unknown, ec: any) => { + handOffs.push({ handOff, userId: ec?.userId }); + return { pendingId: `pa_${handOffs.length}` }; + }, + }); + }, +}; + +describe('[#33690] a confirmation-gated action over MCP is handed to the person, never run on the caller\'s confirm', () => { + let stack: VerifyStack; + let ql: any; + let person: string; + let personId: string; + + const tool = async (name: string, args: Record) => { + const res = await stack.api('/mcp', { + method: 'POST', + headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream', Authorization: `Bearer ${person}` }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }), + }); + expect(res.status).toBe(200); + const rpc: any = await res.json(); + expect(rpc.error, JSON.stringify(rpc.error)).toBeUndefined(); + const text = String(rpc.result?.content?.[0]?.text ?? ''); + let payload: any; + try { payload = JSON.parse(text); } catch { payload = { message: text }; } + return { isError: rpc.result?.isError === true, payload, text }; + }; + const statusOf = async (id: string) => + rowsOf(await ql.find(OBJECT, { where: { id }, context: SYS.context }))[0]?.status; + const openTicket = async (name: string): Promise => { + const res = await stack.apiAs(person, 'POST', `/data/${OBJECT}`, { name, status: 'open' }); + expect(res.status, await res.clone().text()).toBe(201); + const created = (await res.json()) as { id?: string; record?: { id?: string } }; + return String(created.id ?? created.record?.id ?? ''); + }; + + beforeAll(async () => { + stack = await bootStack(stackConfig as unknown as Parameters[0], { + security: new SecurityPlugin({ + defaultPermissionSets: [...securityDefaultPermissionSets, baselineSet], + fallbackPermissionSet: baselineSet.name, + }), + extraPlugins: [confirmationServicePlugin as never, new MCPServerPlugin()], + }); + ql = await stack.kernel.getServiceAsync('objectql'); + await stack.signIn(); + person = await stack.signUp(PERSON); + personId = String((await ql.findOne('sys_user', { where: { email: PERSON }, context: SYS.context }))?.id ?? ''); + expect(personId).not.toBe(''); + expect(await catalogPermissionSet(ql, baselineSet.name), `${baselineSet.name} is served by the catalog`).toBeTruthy(); + await ql.insert('sys_user_permission_set', { user_id: personId, permission_set: baselineSet.name }, SYS); + }, 300_000); + + afterAll(async () => { + await stack?.stop?.(); + }); + + it(`⭐ the same call with confirm: true, sent ${N} times, writes 0 times and is held ${N} times with a pending id`, async () => { + const id = await openTicket('gated'); + const before = handOffs.length; + for (let i = 1; i <= N; i++) { + const answer = await tool('run_action', { + actionName: GATED, objectName: OBJECT, recordId: id, [AI_ACTION_CONFIRMATION_MEMBER]: true, + }); + expect(answer.isError, answer.text).toBe(false); + expect(answer.payload).toMatchObject({ + status: 'pending_confirmation', pendingId: `pa_${before + i}`, actionName: GATED, objectName: OBJECT, + }); + expect(String(answer.payload.message)).toContain(answer.payload.pendingId); + } + expect(await statusOf(id), 'a confirmed call wrote the record').toBe('open'); + const recorded = handOffs.slice(before); + expect(recorded).toHaveLength(N); + for (const { handOff, userId } of recorded) { + expect(handOff).toMatchObject({ actionName: GATED, objectName: OBJECT, recordId: id, door: 'mcp' }); + expect(userId, 'the hand-off is recorded for the person the call ran as').toBe(personId); + } + }, 120_000); + + it('CONTROL: an action that declares no confirmation runs at once, and nobody is asked', async () => { + const id = await openTicket('plain'); + const before = handOffs.length; + const answer = await tool('run_action', { actionName: PLAIN, objectName: OBJECT, recordId: id }); + expect(answer.isError, answer.text).toBe(false); + expect(await statusOf(id)).toBe('flagged'); + expect(handOffs.length).toBe(before); + }, 120_000); +}); diff --git a/packages/qa/dogfood/test/approval-decide-over-mcp.dogfood.test.ts b/packages/qa/dogfood/test/approval-decide-over-mcp.dogfood.test.ts index 68247cfaa72..f1ad7ad3e27 100644 --- a/packages/qa/dogfood/test/approval-decide-over-mcp.dogfood.test.ts +++ b/packages/qa/dogfood/test/approval-decide-over-mcp.dogfood.test.ts @@ -28,21 +28,17 @@ // ⭐ an AI service account acting for itself (ADR-0151, its own API key, on // no slate) is refused, and the request stays pending: the account // confirmation rule (ADR-0151 D3 rule 3) answers first, `428` -// `ACTION_CONFIRMATION_REQUIRED` whatever the call sends, `confirm: true` -// included — an account does not confirm an action for itself, so the -// action is handed to a person; -// ⭐ the approver is refused `428` until the call carries `confirm: true`; -// ⭐ confirmed, the approver's call decides: the request is approved and -// the decision is recorded once, as the approver's; -// ⭐ [#32993] the submitter's recall is refused `428` until confirmed, then -// withdraws the pending request, recorded once as the submitter's; -// ⭐ [#32993] a caller who is not the submitter (the approver) is refused -// recall in `approval_recall_not_submitter`'s words, and the request -// stays pending; -// ⭐ [#32993] on a request sent back for revision, the submitter edits the -// record and resubmits over MCP (confirmed): round 2 opens a pending -// request; unconfirmed, or from the approver, nothing moves. -// +// `ACTION_CONFIRMATION_REQUIRED` with `details.reason: 'service_account'` +// whatever the call sends, `confirm: true` included; +// ⭐ [#33690] every other caller's decision, recall, send-back and resubmit +// runs nothing over MCP, confirmed or not: the actions declare +// `ai.requiresConfirmation: true`, so the caller's own `confirm: true` +// never counts, and this stack registers no pending-confirmation service, +// so each call is refused `428`, `details.reason: +// 'no_confirmation_service'`, and the request stays pending. Before the +// amended contract a confirmed call decided here; a person now decides in +// the app (a host's pending-confirmation service hands the call to them). + // The read half of the card (an approver listing their pending requests over // MCP) is not here: the MCP object tools refuse every `sys_*` object, so this // file finds each request id as the system. @@ -57,7 +53,6 @@ import { defineStack, defineFlow } from '@objectstack/spec'; import { ObjectSchema, Field } from '@objectstack/spec/data'; import { PermissionSetSchema, type PermissionSet } from '@objectstack/spec/security'; import { AI_ACTION_CONFIRMATION_MEMBER } from '@objectstack/spec/contracts'; -import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system'; import { SecurityPlugin, securityDefaultPermissionSets } from '@objectstack/plugin-security'; import { catalogPermissionSet } from './catalog-permission-set.js'; @@ -73,7 +68,6 @@ const STRANGER = 'apmcp-stranger@verify.test'; const DECISIONS = ['approval_approve', 'approval_reassign', 'approval_reject', 'approval_send_back']; // [#32993] The submitter's recall and resubmit, exposed beside the decisions. const EXPOSED = [...DECISIONS, 'approval_recall', 'approval_resubmit'].sort(); -const RECALL_REFUSAL = BUILTIN_OPERATION_MESSAGES.en!.approval_recall_not_submitter!; const leave = ObjectSchema.create({ name: OBJECT, @@ -138,8 +132,6 @@ describe('an approver\'s agent decides a pending approval request over MCP (#324 let submitter: string; let approver: string; let stranger: string; - let approverId: string; - let submitterId: string; let accountKey: string; const idOf = async (email: string): Promise => @@ -217,10 +209,6 @@ describe('an approver\'s agent decides a pending approval request over MCP (#324 expect(await catalogPermissionSet(ql, baselineSet.name), `${baselineSet.name} is served by the catalog`).toBeTruthy(); await ql.insert('sys_user_permission_set', { user_id: await idOf(email), permission_set: baselineSet.name }, SYS); } - approverId = await idOf(APPROVER); - expect(approverId).not.toBe(''); - submitterId = await idOf(SUBMITTER); - expect(submitterId).not.toBe(''); // An AI service account acting for itself (ADR-0151): registered by the // administrator, its key minted for it, on no slate. @@ -253,104 +241,68 @@ describe('an approver\'s agent decides a pending approval request over MCP (#324 } }); + /** + * [#33690] What every decision call over MCP answers now: the decide, + * recall, resubmit and send-back actions declare `ai.requiresConfirmation: + * true`, so the caller's own `confirm: true` never runs them; this stack + * registers no pending-confirmation service, so the call is refused at + * confirmation, after the request row is read and before it is forwarded. + */ + const expectRefusedAtConfirmation = (answer: { isError: boolean; payload: any; text: string }, reason: string) => { + expect(answer.isError, answer.text).toBe(true); + expect(answer.payload?.error?.code, answer.text).toBe('ACTION_CONFIRMATION_REQUIRED'); + expect(answer.payload?.error?.status, answer.text).toBe(428); + expect(answer.payload?.error?.details?.reason, answer.text).toBe(reason); + }; + it('⭐ a member on no slate is refused, confirmed or not, and the request stays pending', async () => { const requestId = await openRequest('stranger'); - const answer = await approve({ bearer: stranger }, requestId, true); - expect(answer.isError, answer.text).toBe(true); - // The service's own answer: a request the caller takes no part in is - // answered as missing (existence non-disclosure), never decided. - expect(answer.payload?.error?.code, answer.text).toBe('REQUEST_NOT_FOUND'); + for (const confirm of [true, false]) { + // [#33690] Refused at confirmation now, never forwarded: the service's + // own `REQUEST_NOT_FOUND` is no longer reached over MCP. + expectRefusedAtConfirmation(await approve({ bearer: stranger }, requestId, confirm), 'no_confirmation_service'); + } await expectUndecided(requestId, 'a member on no slate'); }); it('⭐ the submitter is refused, and the request stays pending', async () => { const requestId = await openRequest('submitter'); - const answer = await approve({ bearer: submitter }, requestId, true); - expect(answer.isError, answer.text).toBe(true); - expect(answer.payload?.error?.code, answer.text).toBe('FORBIDDEN'); - expect(answer.text).toContain('is not a pending approver'); + expectRefusedAtConfirmation(await approve({ bearer: submitter }, requestId, true), 'no_confirmation_service'); await expectUndecided(requestId, 'the submitter'); }); it('⭐ an AI service account acting for itself is refused, and the request stays pending', async () => { const requestId = await openRequest('account'); - const answer = await approve({ key: accountKey }, requestId, true); - expect(answer.isError, answer.text).toBe(true); // The account confirmation rule answers first (ADR-0151 D3 rule 3): an AI // service account does not confirm an action for itself, so the decision // action, which declares `ai.requiresConfirmation`, is refused at admission - // whatever the call carries, before the request is looked up. - expect(answer.payload?.error?.code, answer.text).toBe('ACTION_CONFIRMATION_REQUIRED'); - expect(answer.payload?.error?.status, answer.text).toBe(428); + // whatever the call carries, before the request is looked up; [#33690] + // the refusal names `reason: 'service_account'`. + expectRefusedAtConfirmation(await approve({ key: accountKey }, requestId, true), 'service_account'); await expectUndecided(requestId, 'an AI service account'); }); - it('⭐ the approver is refused until the call is confirmed, then decides, recorded once as the approver\'s', async () => { + it('⭐ [#33690] the approver\'s call decides nothing, confirmed or not: refused at confirmation, the request stays pending', async () => { const requestId = await openRequest('approver'); - const unconfirmed = await approve({ bearer: approver }, requestId, false); - expect(unconfirmed.isError, unconfirmed.text).toBe(true); - expect(unconfirmed.text).toContain('ACTION_CONFIRMATION_REQUIRED'); - await expectUndecided(requestId, 'an unconfirmed call'); - - const confirmed = await approve({ bearer: approver }, requestId, true); - expect(confirmed.isError, confirmed.text).toBe(false); - expect((await requestRow(requestId)).status).toBe('approved'); - expect((await decisionsOn(requestId)).map((r) => [r.action, r.actor_id])).toEqual([['approve', approverId]]); + for (const confirm of [false, true]) { + expectRefusedAtConfirmation(await approve({ bearer: approver }, requestId, confirm), 'no_confirmation_service'); + await expectUndecided(requestId, `an approver's call (confirm: ${confirm})`); + } }); - it('⭐ [#32993] the submitter\'s recall is refused until confirmed, then withdraws the pending request, recorded once as the submitter\'s', async () => { + it('⭐ [#33690] the submitter\'s recall, resubmit and the approver\'s send-back run nothing over MCP, confirmed or not', async () => { const requestId = await openRequest('recall'); - const unconfirmed = await act({ bearer: submitter }, 'approval_recall', requestId, false, 'fixing the lines'); - expect(unconfirmed.isError, unconfirmed.text).toBe(true); - expect(unconfirmed.text).toContain('ACTION_CONFIRMATION_REQUIRED'); - await expectUndecided(requestId, 'an unconfirmed recall'); - - const confirmed = await act({ bearer: submitter }, 'approval_recall', requestId, true, 'fixing the lines'); - expect(confirmed.isError, confirmed.text).toBe(false); - expect((await requestRow(requestId)).status).toBe('recalled'); - expect((await decisionsOn(requestId)).map((r) => [r.action, r.actor_id])).toEqual([['recall', submitterId]]); - }); - - it('⭐ [#32993] a caller who is not the submitter is refused recall in the service\'s own words, and the request stays pending', async () => { - const requestId = await openRequest('recall-not-submitter'); - const answer = await act({ bearer: approver }, 'approval_recall', requestId, true, 'not mine to recall'); - expect(answer.isError, answer.text).toBe(true); - expect(answer.payload?.error?.code, answer.text).toBe('FORBIDDEN'); - expect(answer.text).toContain(RECALL_REFUSAL); - await expectUndecided(requestId, 'a recall by the approver'); - }); - - it('⭐ [#32993] on a request sent back for revision, the submitter edits the record and resubmits over MCP: round 2 opens a pending request', async () => { - const requestId = await openRequest('resubmit'); - const recordId = String((await requestRow(requestId)).record_id); - const sentBack = await act({ bearer: approver }, 'approval_send_back', requestId, true, 'fix the dates'); - expect(sentBack.isError, sentBack.text).toBe(false); - expect((await requestRow(requestId)).status).toBe('returned'); - - const edited = await stack.apiAs(submitter, 'PATCH', `/data/${OBJECT}/${recordId}`, { name: 'resubmit (dates fixed)' }); - expect(edited.status, await edited.clone().text()).toBe(200); - - const pendingOn = async () => - rowsOf(await ql.find(REQUEST, { where: { object_name: OBJECT, record_id: recordId, status: 'pending' }, context: SYS.context })); - - // Unconfirmed, or from anyone but the submitter, nothing moves. - const unconfirmed = await act({ bearer: submitter }, 'approval_resubmit', requestId, false, 'dates fixed'); - expect(unconfirmed.isError, unconfirmed.text).toBe(true); - expect(unconfirmed.text).toContain('ACTION_CONFIRMATION_REQUIRED'); - const byApprover = await act({ bearer: approver }, 'approval_resubmit', requestId, true, 'not mine'); - expect(byApprover.isError, byApprover.text).toBe(true); - expect(byApprover.payload?.error?.code, byApprover.text).toBe('FORBIDDEN'); - expect((await requestRow(requestId)).status).toBe('returned'); - expect(await pendingOn(), 'no round 2 before the submitter\'s confirmed resubmit').toEqual([]); - - const confirmed = await act({ bearer: submitter }, 'approval_resubmit', requestId, true, 'dates fixed'); - expect(confirmed.isError, confirmed.text).toBe(false); - const round2 = await pendingOn(); - expect(round2, 'the resubmit opened round 2').toHaveLength(1); - expect(round2[0].id).not.toBe(requestId); - // One row each, in no stored order (the read is unsorted). - expect((await decisionsOn(requestId)).map((r) => `${r.action}:${r.actor_id}`).sort()).toEqual( - [`resubmit:${submitterId}`, `revise:${approverId}`].sort(), - ); + for (const confirm of [false, true]) { + expectRefusedAtConfirmation( + await act({ bearer: submitter }, 'approval_recall', requestId, confirm, 'fixing the lines'), 'no_confirmation_service', + ); + expectRefusedAtConfirmation( + await act({ bearer: approver }, 'approval_send_back', requestId, confirm, 'fix the dates'), 'no_confirmation_service', + ); + expectRefusedAtConfirmation( + await act({ bearer: submitter }, 'approval_resubmit', requestId, confirm, 'dates fixed'), 'no_confirmation_service', + ); + } + await expectUndecided(requestId, 'recall, send-back and resubmit over MCP'); }); }); diff --git a/packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts b/packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts index 94d90599b92..7a12213dc75 100644 --- a/packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts +++ b/packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts @@ -37,8 +37,10 @@ // ⭐ the object is listed and described; no write tool opens it, and // `sys_approval_action` stays refused; // ⭐ the query tool's text names the "pending for me" filter shape; -// ⭐ end to end: the submitter files over MCP, the approver lists, approves -// with confirmation, and the record's flow resumes and stamps it. +// ⭐ end to end: the submitter files over MCP, the approver lists; [#33690] +// the approver's approve carrying `confirm: true` decides nothing (the +// caller's own confirm never counts on a declared-gated action, and this +// stack has no pending-confirmation service), so the request stays pending. import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { type VerifyStack } from '@objectstack/verify'; @@ -444,7 +446,7 @@ describe('an approver\'s agent lists the approvals waiting on them over MCP (#32 expect(query?.description).toContain('pending_approvers'); }); - it('⭐ end to end: the approver lists what waits on them, approves one with confirmation, and the flow resumes', async () => { + it('⭐ end to end: the approver lists what waits on them; [#33690] a confirmed approve over MCP decides nothing, and the request stays waiting', async () => { const before = rowsOf((await pendingForMe({ bearer: approver })).payload); const target = before.find((r) => String(r.record_id) === first.recordId); expect(target, 'the approver sees the request in their pending list').toBeTruthy(); @@ -456,14 +458,15 @@ describe('an approver\'s agent lists the approvals waiting on them over MCP (#32 params: { comment: 'approved over MCP' }, [AI_ACTION_CONFIRMATION_MEMBER]: true, }); - expect(decided.isError, decided.text).toBe(false); - - expect((await requestRow(first.requestId)).status).toBe('approved'); - // The run resumed past the approval node down its approve edge, whose - // next node stamps the record. - const record = rowsOf(await ql.find(OVERTIME, { where: { id: first.recordId }, context: SYS.context }))[0]; - expect(record?.outcome, JSON.stringify(record)).toBe('approved'); + // [#33690] `approval_approve` declares `ai.requiresConfirmation: true`, so + // the caller's own `confirm: true` never runs it; this stack registers no + // pending-confirmation service, so the call is refused at confirmation. + // Before the amended contract it approved and the flow resumed. + expect(decided.isError, decided.text).toBe(true); + expect(decided.payload?.error?.code, decided.text).toBe('ACTION_CONFIRMATION_REQUIRED'); + expect(decided.payload?.error?.details?.reason, decided.text).toBe('no_confirmation_service'); + expect((await requestRow(first.requestId)).status).toBe('pending'); - expect(await pendingIds({ bearer: approver })).toEqual([second.requestId]); + expect((await pendingIds({ bearer: approver })).sort()).toEqual([first.requestId, second.requestId].sort()); }); }); diff --git a/packages/qa/dogfood/test/mcp-delete-record-confirmation.dogfood.test.ts b/packages/qa/dogfood/test/mcp-delete-record-confirmation.dogfood.test.ts index 350e098226a..3e9925204a0 100644 --- a/packages/qa/dogfood/test/mcp-delete-record-confirmation.dogfood.test.ts +++ b/packages/qa/dogfood/test/mcp-delete-record-confirmation.dogfood.test.ts @@ -111,8 +111,13 @@ describe('MCP delete_record takes run_action\'s confirmation gate; REST DELETE s expect(Object.keys(d)).toEqual(Object.keys(a)); expect(d.details.confirmationMember).toBe(a.details.confirmationMember); // The action is object-less, so its details carry no `objectName`; every - // key it does carry, the delete refusal carries too. - expect(Object.keys(d.details)).toEqual(expect.arrayContaining(Object.keys(a.details))); + // key it does carry, the delete refusal carries too, save `reason`: + // [#33690] `run_action` hands a gated call to the person and, with no + // pending-confirmation service, says so in `details.reason`, while the + // delete gate still reads `confirm: true` and names no reason. + expect(a.details.reason).toBe('no_confirmation_service'); + expect(d.details).not.toHaveProperty('reason'); + expect(Object.keys(d.details)).toEqual(expect.arrayContaining(Object.keys(a.details).filter((k) => k !== 'reason'))); expect(await readStatus(id)).toBe(200); }, 60_000); diff --git a/packages/qa/dogfood/test/mcp-system-object-action-exposure.dogfood.test.ts b/packages/qa/dogfood/test/mcp-system-object-action-exposure.dogfood.test.ts index b155b05e5ce..a8ba1e57a3f 100644 --- a/packages/qa/dogfood/test/mcp-system-object-action-exposure.dogfood.test.ts +++ b/packages/qa/dogfood/test/mcp-system-object-action-exposure.dogfood.test.ts @@ -280,13 +280,17 @@ describe('[#27681, #27900] sys_user identity actions over MCP: what each bucket\ expect(await isBanned(targetUserId)).toBe(false); }, 120_000); - it('the confirmed administrator call runs through every gate and bans the user', async () => { - const ran = await tool(admin, 'run_action', { + it('[#33690] the administrator\'s call carrying confirm: true clears every gate and still bans nobody: the caller\'s confirm never counts', async () => { + // Before the amended confirmation contract this call banned the user. The + // stack registers no pending-confirmation service, so the call is refused + // at confirmation, after every other gate, and nothing is forwarded. + const refused = await tool(admin, 'run_action', { actionName: 'ban_user', objectName: 'sys_user', recordId: targetUserId, params: { banReason: 'dogfood' }, confirm: true, }); - expect(ran.isError, ran.text).toBe(false); - expect(ran.payload).toMatchObject({ ok: true, action: 'ban_user', objectName: 'sys_user', recordId: targetUserId }); - expect(await isBanned(targetUserId)).toBe(true); + expect(refused.isError, refused.text).toBe(true); + expect(refused.payload?.error).toMatchObject({ code: 'ACTION_CONFIRMATION_REQUIRED', status: 428 }); + expect(refused.payload?.error?.details?.reason, refused.text).toBe('no_confirmation_service'); + expect(await isBanned(targetUserId)).toBe(false); }, 120_000); // ── The OAuth-connected agent: one case per bucket ─────────────────────── @@ -351,20 +355,19 @@ describe('[#27681, #27900] sys_user identity actions over MCP: what each bucket\ expect(messageOf(scoped)).toContain('system object "sys_user" is not exposed via MCP'); }, 120_000); - it('C: the agent\'s unconfirmed ban_user is refused 428 before any forward; confirmed, it is served as the agent (#28367) and bans the user', async () => { - const unconfirmed = await tool(agent, 'run_action', { - actionName: 'ban_user', objectName: 'sys_user', recordId: agentTargetUserId, params: { banReason: 'agent' }, - }); - expect(unconfirmed.isError).toBe(true); - expect(unconfirmed.payload?.error).toMatchObject({ code: 'ACTION_CONFIRMATION_REQUIRED', status: 428 }); - expect(await isBanned(agentTargetUserId)).toBe(false); - - const confirmed = await tool(agent, 'run_action', { - actionName: 'ban_user', objectName: 'sys_user', recordId: agentTargetUserId, params: { banReason: 'agent' }, confirm: true, - }); - expect(confirmed.isError, confirmed.text).toBe(false); - expect(confirmed.payload).toMatchObject({ ok: true, action: 'ban_user', objectName: 'sys_user', recordId: agentTargetUserId }); - expect(await isBanned(agentTargetUserId)).toBe(true); + it('C: [#33690] the agent\'s ban_user is refused 428 before any forward, with confirm: true and without it, and bans nobody', async () => { + // Before the amended confirmation contract the confirmed call was served as + // the agent (#28367) and banned the user. The agent's own `confirm: true` + // never counts now, and the stack registers no pending-confirmation service. + for (const extra of [{}, { confirm: true }]) { + const refused = await tool(agent, 'run_action', { + actionName: 'ban_user', objectName: 'sys_user', recordId: agentTargetUserId, params: { banReason: 'agent' }, ...extra, + }); + expect(refused.isError, refused.text).toBe(true); + expect(refused.payload?.error).toMatchObject({ code: 'ACTION_CONFIRMATION_REQUIRED', status: 428 }); + expect(refused.payload?.error?.details?.reason, refused.text).toBe('no_confirmation_service'); + expect(await isBanned(agentTargetUserId)).toBe(false); + } }, 120_000); it('H: impersonate_user is absent from the agent\'s listing and refused by name', async () => { diff --git a/packages/runtime/src/action-confirmation-gate.test.ts b/packages/runtime/src/action-confirmation-gate.test.ts index e6894981314..54723c1482a 100644 --- a/packages/runtime/src/action-confirmation-gate.test.ts +++ b/packages/runtime/src/action-confirmation-gate.test.ts @@ -123,8 +123,14 @@ const runViaMcp = (h: ReturnType, name: string, input: Record { - it('refuses with the ADR-0112 envelope, dispatches nothing, and reads no record', async () => { +// [#33690] The MCP door no longer reads the member on a gated action: under +// the amended contract it hands the call to the person through the host's +// pending-confirmation service, and with none registered (this harness +// registers none) it refuses `reason: 'no_confirmation_service'`. The cases +// below flipped from "runs once the member rides" to "refused either way"; +// the hand-off itself is pinned in `action-confirmation-handoff-33690.test.ts`. +describe('the AI-facing door refuses a call on a gated action, whatever it carries (#15942, #33690)', () => { + it('refuses with the ADR-0112 envelope and dispatches nothing', async () => { const h = boot(); const thrown: any = await runViaMcp(h, GATED.name, { recordId: 'lead_1' }).catch((e) => e); @@ -133,54 +139,50 @@ describe('the AI-facing door refuses an unconfirmed call on a gated action (#159 expect(thrown.code).toBe(ACTION_CONFIRMATION_REQUIRED_CODE); expect(thrown.code).toBe('ACTION_CONFIRMATION_REQUIRED'); expect(thrown.status).toBe(428); - // The machine-readable retry, so a refused agent never re-parses prose. + // The machine-readable half: which case of the amended contract refused it. expect(thrown.details).toEqual({ actionName: GATED.name, objectName: OBJECT, confirmationMember: AI_ACTION_CONFIRMATION_MEMBER, + reason: 'no_confirmation_service', }); - // The prose still names both, for the human reading a transcript. expect(String(thrown.message)).toContain(GATED.name); - expect(String(thrown.message)).toContain(AI_ACTION_CONFIRMATION_MEMBER); - // Nothing ran, and nothing was read: the gate sits ahead of both. + // Nothing ran. The subject IS read now: the person is asked only after + // every admission gate, the subject load and its verdict included. expect(h.executeAction).not.toHaveBeenCalled(); - expect(h.callData).not.toHaveBeenCalled(); }); - it('runs the SAME call once the member rides on the request', async () => { + it('[#33690] the SAME call with the member rides is refused too: the caller\'s confirm never counts', async () => { const h = boot(); - const result: any = await runViaMcp(h, GATED.name, { + const thrown: any = await runViaMcp(h, GATED.name, { recordId: 'lead_1', [AI_ACTION_CONFIRMATION_MEMBER]: true, - }); + }).catch((e) => e); - expect(result?.ok).toBe(true); - expect(h.executeAction).toHaveBeenCalledTimes(1); + expect({ code: thrown?.code, status: thrown?.status }).toEqual({ code: 'ACTION_CONFIRMATION_REQUIRED', status: 428 }); + expect(thrown?.details?.reason).toBe('no_confirmation_service'); + expect(h.executeAction).not.toHaveBeenCalled(); }); - it('gates a FLOW action too — ahead of the type branch, so no run is created', async () => { + it('gates a FLOW action too — no run is created, with the member or without it', async () => { const h = boot(); - const thrown: any = await runViaMcp(h, GATED_FLOW.name, {}).catch((e) => e); - - expect(thrown.code).toBe('ACTION_CONFIRMATION_REQUIRED'); - expect(thrown.status).toBe(428); + for (const input of [{}, { [AI_ACTION_CONFIRMATION_MEMBER]: true }]) { + const thrown: any = await runViaMcp(h, GATED_FLOW.name, input).catch((e) => e); + expect(thrown.code).toBe('ACTION_CONFIRMATION_REQUIRED'); + expect(thrown.status).toBe(428); + } expect(h.execute).not.toHaveBeenCalled(); - // Control: the same action DOES dispatch once confirmed, so the - // assertion above is about the gate and not about a flow that never - // could have run in this harness. - await runViaMcp(h, GATED_FLOW.name, { [AI_ACTION_CONFIRMATION_MEMBER]: true }); - expect(h.execute).toHaveBeenCalledTimes(1); }); - it('admits ONLY the boolean `true` — a truthy string and `false` are not attestations', async () => { - for (const value of ['true', 1, {}, false, null]) { + it('refuses whatever the member\'s value — none of them runs it', async () => { + for (const value of ['true', 1, {}, false, null, true]) { const h = boot(); const thrown: any = await runViaMcp(h, GATED.name, { [AI_ACTION_CONFIRMATION_MEMBER]: value, }).catch((e) => e); - expect(thrown.code, `\`${JSON.stringify(value)}\` must not confirm`).toBe( + expect(thrown.code, `\`${JSON.stringify(value)}\` must not run it`).toBe( 'ACTION_CONFIRMATION_REQUIRED', ); expect(h.executeAction).not.toHaveBeenCalled(); @@ -269,10 +271,13 @@ describe('[ADR-0151 D3 rule 3] an AI service account does not confirm an action }); expect(refusal?.code).toBe('ACTION_CONFIRMATION_REQUIRED'); expect(refusal?.status).toBe(428); + // [#33690] The amended contract's rule 6: the account's refusal + // names its case at every door. expect(refusal?.details).toEqual({ actionName: GATED.name, objectName: OBJECT, confirmationMember: AI_ACTION_CONFIRMATION_MEMBER, + reason: 'service_account', }); } }); diff --git a/packages/runtime/src/action-confirmation-handoff-33690.test.ts b/packages/runtime/src/action-confirmation-handoff-33690.test.ts new file mode 100644 index 00000000000..a27e7ef4bc9 --- /dev/null +++ b/packages/runtime/src/action-confirmation-handoff-33690.test.ts @@ -0,0 +1,373 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#33690] The MCP `run_action` and `resume_run` doors under the amended + * confirmation contract (`AI_ACTION_CONFIRMATION_CAPABILITY`, + * `@objectstack/spec/contracts`; ADR-0011, the note on confirmation). + * + * On an action whose author declared `ai.requiresConfirmation: true`, the + * caller's own `confirm: true` never runs it. The call is handed to the + * host's pending-confirmation service (`IActionConfirmationService`, + * registered under `ACTION_CONFIRMATION_SERVICE`) and answered + * `status: 'pending_confirmation'` with the service's pending id; with no + * service registered it is refused `428 ACTION_CONFIRMATION_REQUIRED`, + * `details.reason: 'no_confirmation_service'`. An AI service account keeps its + * ADR-0151 D3 rule 3 refusal (`reason: 'service_account'`), and is never + * handed off. + * + * The real bridge (`buildMcpBridge`, through `HttpDispatcher`) is driven + * against a kernel double, so every pin reads what the door made the engine + * and the service double do, not only what it answered. The acceptance is + * the card's: the same request sent with `confirm: true` N times executes 0 + * times, and every attempt is held with a pending id. + */ + +// Paid at collection, not inside a case's clock (check:test-source-alias). +import '@objectstack/metadata'; +import { describe, it, expect, vi } from 'vitest'; + +import { ACTION_CONFIRMATION_SERVICE, AI_ACTION_CONFIRMATION_MEMBER } from '@objectstack/spec/contracts'; + +import { HttpDispatcher } from './http-dispatcher.js'; +import { actionConfirmationRefusal } from './action-execution.js'; +import { dispatchAction } from './action-dispatch.js'; + +const OBJECT = 'crm_lead'; + +/** Author-gated script action. */ +const GATED = { + name: 'archive_lead', label: 'Archive Lead', objectName: OBJECT, type: 'script', target: 'archive_lead_impl', + params: [{ name: 'note', type: 'text' }], + ai: { exposed: true, description: 'Archive a lead.', requiresConfirmation: true }, +}; +/** Author-gated flow action whose flow opens on a screen. */ +const GATED_FLOW = { + name: 'close_lead', label: 'Close Lead', objectName: OBJECT, type: 'flow', target: 'close_lead', + ai: { exposed: true, description: 'Close this lead for good.', requiresConfirmation: true }, +}; +/** Author-gated declarative update. */ +const GATED_UPDATE = { + name: 'mark_lost', label: 'Mark Lost', objectName: OBJECT, operation: 'update', patch: { status: 'lost' }, + ai: { exposed: true, description: 'Mark a lead lost.', requiresConfirmation: true }, +}; +/** Ungated (and destructive-looking): the heuristic gates nothing. */ +const PLAIN = { + name: 'touch_lead', label: 'Touch Lead', objectName: OBJECT, type: 'script', target: 'touch_lead_impl', mode: 'delete', + ai: { exposed: true, description: 'Touch a lead.' }, +}; + +const SCREEN = { nodeId: 'screen_1', title: 'Reason', fields: [{ name: 'reason', label: 'Reason', type: 'text', required: true }] }; + +const PERSON = { userId: 'u1', systemPermissions: [] as string[] }; +const DELEGATED = { userId: 'u1', principalKind: 'agent', onBehalfOf: { userId: 'u1', principalKind: 'human' }, systemPermissions: [] as string[] }; +const ACCOUNT = { userId: 'bot_1', principalKind: 'agent', systemPermissions: [] as string[] }; + +/** The host's pending-confirmation service double: records every hand-off, runs nothing. */ +function makeConfirmationService() { + let n = 0; + return { submit: vi.fn(async (_handOff: unknown, _ec: unknown) => ({ pendingId: `pa_${++n}` })) }; +} + +function makeHarness(opts: { service?: unknown } = {}) { + const leads = [ + { id: 'lead_1', owner: 'u1', name: 'Ada', status: 'open' }, + { id: 'lead_2', owner: 'u2', name: 'Grace', status: 'open' }, + ]; + const runs = new Map(); + let r = 0; + const automation = { + getFlow: vi.fn(async (name: string) => ({ name })), + execute: vi.fn(async (flowName: string, ctx: any) => { + const runId = `run_${++r}`; + runs.set(runId, { flowName, userId: ctx?.userId, recordId: ctx?.record?.id, status: 'paused' }); + return { success: true, status: 'paused', runId, durationMs: 1, screen: SCREEN }; + }), + getRun: vi.fn(async (runId: string) => { + const run = runs.get(runId); + return run ? { + id: runId, flowName: run.flowName, status: run.status, startedAt: '2026-11-15T00:00:00.000Z', + trigger: { type: 'manual', userId: run.userId, object: OBJECT, recordId: run.recordId }, steps: [], + } : null; + }), + getSuspendedScreen: vi.fn(async (runId: string) => (runs.get(runId)?.status === 'paused' ? SCREEN : null)), + resume: vi.fn(async (runId: string) => { + const run = runs.get(runId)!; + run.status = 'completed'; + return { success: true, status: 'completed', output: {}, durationMs: 1 }; + }), + }; + const object = { name: OBJECT, label: 'Lead', fields: { status: { type: 'text' }, name: { type: 'text' } }, actions: [GATED, GATED_FLOW, GATED_UPDATE, PLAIN] }; + const ql: any = { + executeAction: vi.fn(async () => ({ ran: 'script' })), + registry: { getObject: () => object, getItem: () => undefined }, + getSchema: () => object, + listRegisteredActions: () => [ + { objectName: OBJECT, actionName: 'archive_lead_impl' }, + { objectName: OBJECT, actionName: 'touch_lead_impl' }, + ], + // Row-level security: a caller reads only its own leads. + find: vi.fn(async (_o: string, q: any) => { + const caller = q?.context?.userId; + return leads.filter((l) => l.owner === caller && (q?.where?.id === undefined || l.id === q.where.id)); + }), + // No write verb: nothing here may write. A declarative update that + // reached the write would throw on the missing `update`, and the pins + // read that no write was attempted. + update: undefined, + }; + const metadata: any = { + load: vi.fn(async () => null), + loadDiagnosed: vi.fn(async () => ({ data: null, degraded: false, errors: [] })), + loadMany: vi.fn(async () => []), + listObjects: vi.fn(async () => [object]), + getObject: vi.fn(async () => object), + }; + const services: Record = { + objectql: ql, data: ql, metadata, automation, + ...(opts.service ? { [ACTION_CONFIRMATION_SERVICE]: opts.service } : {}), + }; + const resolve = (name: string) => services[name] ?? null; + const kernel: any = { getService: resolve, getServiceAsync: async (name: string) => resolve(name), context: { getService: resolve } }; + const dispatcher = new HttpDispatcher(kernel); + const bridgeAs = (executionContext: Record) => + (dispatcher as any).buildMcpBridge({ request: {}, environmentId: 'platform', executionContext }); + const viaRest = async (ec: unknown, action: string, recordId: string, body: unknown = {}) => { + const res: any = await dispatcher.handleActions(`/${OBJECT}/${action}/${recordId}`, 'POST', body, { + request: {}, environmentId: 'platform', executionContext: ec, + } as any); + return res.response as { status: number; body: any }; + }; + const viaHost = (ec: unknown, action: string, extra: Record = {}) => + dispatchAction(kernel, { executionContext: ec as any, environmentId: 'platform', objectName: OBJECT, actionName: action, ...extra } as any); + return { ql, automation, runs, bridgeAs, viaRest, viaHost }; +} + +async function refusalOf(p: Promise): Promise<{ code: unknown; status: unknown; message: string; details?: any }> { + try { + await p; + } catch (err: any) { + return { code: err?.code, status: err?.status, message: String(err?.message), details: err?.details }; + } + throw new Error('expected the call to be refused, and it resolved'); +} + +const N = 5; + +describe('[#33690] run_action: a declared-gated action is handed to the person, never run on the caller\'s confirm', () => { + it(`the same request with confirm: true, sent ${N} times, executes 0 times and is held ${N} times with a pending id`, async () => { + const service = makeConfirmationService(); + const h = makeHarness({ service }); + const bridge = h.bridgeAs(PERSON); + + const answers: any[] = []; + for (let i = 0; i < N; i++) { + answers.push(await bridge.runAction(GATED.name, { + recordId: 'lead_1', params: { note: 'stale' }, [AI_ACTION_CONFIRMATION_MEMBER]: true, + })); + } + + expect(h.ql.executeAction).not.toHaveBeenCalled(); + expect(service.submit).toHaveBeenCalledTimes(N); + expect(answers.map((a) => a.pendingId)).toEqual(Array.from({ length: N }, (_, i) => `pa_${i + 1}`)); + for (const answer of answers) { + expect(answer).toMatchObject({ status: 'pending_confirmation', actionName: GATED.name, objectName: OBJECT }); + expect(typeof answer.message).toBe('string'); + expect(answer.message).toContain(answer.pendingId); + // A success, not a refusal, and nothing of the run_action envelope. + expect(answer).not.toHaveProperty('ok'); + expect(answer).not.toHaveProperty('result'); + } + // The hand-off is the contract's shape: the call, for the person it runs as. + const [handOff, ec] = service.submit.mock.calls[0] as [any, any]; + expect(handOff).toEqual({ + actionName: GATED.name, objectName: OBJECT, recordId: 'lead_1', params: { note: 'stale' }, door: 'mcp', + }); + expect(ec.userId).toBe('u1'); + }); + + it('holds the call with the member and without it alike: the member is not read', async () => { + for (const extra of [{}, { [AI_ACTION_CONFIRMATION_MEMBER]: false }, { [AI_ACTION_CONFIRMATION_MEMBER]: true }]) { + const service = makeConfirmationService(); + const h = makeHarness({ service }); + const answer = await h.bridgeAs(PERSON).runAction(GATED.name, { recordId: 'lead_1', ...extra }); + expect(answer, JSON.stringify(extra)).toMatchObject({ status: 'pending_confirmation', pendingId: 'pa_1' }); + expect(h.ql.executeAction).not.toHaveBeenCalled(); + } + }); + + it('a delegated agent (acting for a person) is handed off too, for that person', async () => { + const service = makeConfirmationService(); + const h = makeHarness({ service }); + const answer = await h.bridgeAs(DELEGATED).runAction(GATED.name, { recordId: 'lead_1', [AI_ACTION_CONFIRMATION_MEMBER]: true }); + expect(answer).toMatchObject({ status: 'pending_confirmation' }); + expect(h.ql.executeAction).not.toHaveBeenCalled(); + expect((service.submit.mock.calls[0] as any[])[1].onBehalfOf.userId).toBe('u1'); + }); + + it('a gated FLOW action starts no run, and a gated declarative update writes nothing', async () => { + const service = makeConfirmationService(); + const h = makeHarness({ service }); + const bridge = h.bridgeAs(PERSON); + + const flow = await bridge.runAction(GATED_FLOW.name, { recordId: 'lead_1', [AI_ACTION_CONFIRMATION_MEMBER]: true }); + expect(flow).toMatchObject({ status: 'pending_confirmation', actionName: GATED_FLOW.name }); + expect(h.automation.execute).not.toHaveBeenCalled(); + + const update = await bridge.runAction(GATED_UPDATE.name, { recordId: 'lead_1', [AI_ACTION_CONFIRMATION_MEMBER]: true }); + expect(update).toMatchObject({ status: 'pending_confirmation', actionName: GATED_UPDATE.name }); + }); + + it('a record the caller cannot read is refused 404 before anyone is asked: no hand-off, nothing run', async () => { + const service = makeConfirmationService(); + const h = makeHarness({ service }); + + const refused = await refusalOf(h.bridgeAs(PERSON).runAction(GATED.name, { recordId: 'lead_2', [AI_ACTION_CONFIRMATION_MEMBER]: true })); + + expect({ code: refused.code, status: refused.status }).toEqual({ code: 'RECORD_NOT_FOUND', status: 404 }); + expect(service.submit).not.toHaveBeenCalled(); + expect(h.ql.executeAction).not.toHaveBeenCalled(); + }); + + it('no service registered: refused 428 ACTION_CONFIRMATION_REQUIRED, reason no_confirmation_service, with the member and without it', async () => { + for (const extra of [{ [AI_ACTION_CONFIRMATION_MEMBER]: true }, {}]) { + const h = makeHarness(); + const refused = await refusalOf(h.bridgeAs(PERSON).runAction(GATED.name, { recordId: 'lead_1', ...extra })); + expect({ code: refused.code, status: refused.status }, JSON.stringify(extra)).toEqual({ + code: 'ACTION_CONFIRMATION_REQUIRED', status: 428, + }); + expect(refused.details).toEqual({ + actionName: GATED.name, objectName: OBJECT, confirmationMember: AI_ACTION_CONFIRMATION_MEMBER, + reason: 'no_confirmation_service', + }); + // No retry is prescribed: no request this caller sends runs it here. + expect(refused.message).not.toContain(`'${AI_ACTION_CONFIRMATION_MEMBER}': true`); + expect(refused.message).toContain('in the app'); + expect(h.ql.executeAction).not.toHaveBeenCalled(); + } + }); + + it('a service that answers no pending id is a fault, never a hand-off: thrown, and nothing run', async () => { + const service = { submit: vi.fn(async () => ({})) }; + const h = makeHarness({ service }); + const thrown: any = await h.bridgeAs(PERSON).runAction(GATED.name, { recordId: 'lead_1', [AI_ACTION_CONFIRMATION_MEMBER]: true }).catch((e: unknown) => e); + expect(thrown).toBeInstanceOf(Error); + expect(String(thrown.message)).toContain('pendingId'); + expect(h.ql.executeAction).not.toHaveBeenCalled(); + }); + + it('[ADR-0151 D3 rule 3] an AI service account is refused, never handed off: reason service_account, with the member and without it', async () => { + for (const extra of [{ [AI_ACTION_CONFIRMATION_MEMBER]: true }, {}]) { + const service = makeConfirmationService(); + const h = makeHarness({ service }); + const refused = await refusalOf(h.bridgeAs(ACCOUNT).runAction(GATED.name, { recordId: 'lead_1', ...extra })); + expect({ code: refused.code, status: refused.status }).toEqual({ code: 'ACTION_CONFIRMATION_REQUIRED', status: 428 }); + expect(refused.details).toEqual({ + actionName: GATED.name, objectName: OBJECT, confirmationMember: AI_ACTION_CONFIRMATION_MEMBER, + reason: 'service_account', + }); + expect(refused.message).toContain('An AI service account does not confirm an action for itself'); + expect(service.submit).not.toHaveBeenCalled(); + expect(h.ql.executeAction).not.toHaveBeenCalled(); + // Refused before the subject load, as before: nothing was read. + expect(h.ql.find).not.toHaveBeenCalled(); + } + }); + + it('CONTROL: an action that declares no confirmation runs at once, and nobody is asked', async () => { + const service = makeConfirmationService(); + const h = makeHarness({ service }); + const answer = await h.bridgeAs(PERSON).runAction(PLAIN.name, { recordId: 'lead_1' }); + expect(answer).toMatchObject({ ok: true, action: PLAIN.name }); + expect(h.ql.executeAction).toHaveBeenCalledTimes(1); + expect(service.submit).not.toHaveBeenCalled(); + }); +}); + +describe('[#33690] resume_run: a resume of a gated action is handed off carrying its run', () => { + async function pausedRun(h: ReturnType): Promise { + // Started as the run_action door would have before the hand-off existed: + // the engine's run, owned by `u1`, paused on its screen. + const started: any = await h.automation.execute(GATED_FLOW.target, { userId: 'u1', object: OBJECT, record: { id: 'lead_1' } }); + h.automation.execute.mockClear(); + return started.runId; + } + + it(`confirm: true sent ${N} times resumes 0 times; each call is held with a pending id carrying its run and values`, async () => { + const service = makeConfirmationService(); + const h = makeHarness({ service }); + const runId = await pausedRun(h); + + for (let i = 0; i < N; i++) { + const answer = await h.bridgeAs(PERSON).resumeRun(runId, { values: { reason: 'dup' }, [AI_ACTION_CONFIRMATION_MEMBER]: true }); + expect(answer).toMatchObject({ status: 'pending_confirmation', pendingId: `pa_${i + 1}`, actionName: GATED_FLOW.name, objectName: OBJECT }); + } + + expect(h.automation.resume).not.toHaveBeenCalled(); + expect(h.runs.get(runId)?.status).toBe('paused'); + expect(service.submit).toHaveBeenCalledTimes(N); + // The parked run rides the hand-off, so approving it resumes THAT run. + expect((service.submit.mock.calls[0] as any[])[0]).toEqual({ + actionName: GATED_FLOW.name, objectName: OBJECT, recordId: 'lead_1', params: {}, door: 'mcp', + run: { runId, values: { reason: 'dup' } }, + }); + }); + + it('no service registered: refused 428, reason no_confirmation_service, and the run stays paused', async () => { + const h = makeHarness(); + const runId = await pausedRun(h); + const refused = await refusalOf(h.bridgeAs(PERSON).resumeRun(runId, { values: { reason: 'x' }, [AI_ACTION_CONFIRMATION_MEMBER]: true })); + expect({ code: refused.code, status: refused.status }).toEqual({ code: 'ACTION_CONFIRMATION_REQUIRED', status: 428 }); + expect(refused.details).toMatchObject({ actionName: GATED_FLOW.name, objectName: OBJECT, reason: 'no_confirmation_service' }); + expect(h.automation.resume).not.toHaveBeenCalled(); + expect(h.runs.get(runId)?.status).toBe('paused'); + }); + + it('[ADR-0151 D3 rule 3] an AI service account\'s resume is refused, reason service_account, never handed off', async () => { + const service = makeConfirmationService(); + const h = makeHarness({ service }); + const started: any = await h.automation.execute(GATED_FLOW.target, { userId: 'bot_1', object: OBJECT, record: { id: 'lead_1' } }); + const refused = await refusalOf(h.bridgeAs(ACCOUNT).resumeRun(started.runId, { values: { reason: 'x' }, [AI_ACTION_CONFIRMATION_MEMBER]: true })); + expect({ code: refused.code, status: refused.status }).toEqual({ code: 'ACTION_CONFIRMATION_REQUIRED', status: 428 }); + expect(refused.details).toMatchObject({ reason: 'service_account' }); + expect(service.submit).not.toHaveBeenCalled(); + expect(h.automation.resume).not.toHaveBeenCalled(); + }); +}); + +describe('[#33690] CONTROL: the doors outside the amendment keep the member gate', () => { + it('REST /actions stays outside the gate for a person: the gated action runs, and nobody is asked', async () => { + const service = makeConfirmationService(); + const h = makeHarness({ service }); + const res = await h.viaRest(PERSON, GATED.name, 'lead_1'); + expect(res.status).toBe(200); + expect(h.ql.executeAction).toHaveBeenCalledTimes(1); + expect(service.submit).not.toHaveBeenCalled(); + }); + + it('a host door under the `ai` posture still reads the member: refused without it, run with it, never handed off', async () => { + const service = makeConfirmationService(); + const h = makeHarness({ service }); + const refused: any = await h.viaHost(PERSON, GATED.name, { recordId: 'lead_1', posture: 'ai' }); + expect({ status: refused.status, code: refused.body?.error?.code }).toEqual({ status: 428, code: 'ACTION_CONFIRMATION_REQUIRED' }); + expect(h.ql.executeAction).not.toHaveBeenCalled(); + const ran: any = await h.viaHost(PERSON, GATED.name, { recordId: 'lead_1', posture: 'ai', confirm: true }); + expect(ran.status).toBe(200); + expect(h.ql.executeAction).toHaveBeenCalledTimes(1); + expect(service.submit).not.toHaveBeenCalled(); + }); + + it('[ADR-0151 D3 rule 3] REST /actions refuses an AI service account, now naming reason service_account', async () => { + const h = makeHarness({ service: makeConfirmationService() }); + const res = await h.viaRest(ACCOUNT, GATED.name, 'lead_1', { [AI_ACTION_CONFIRMATION_MEMBER]: true }); + expect({ status: res.status, code: res.body?.error?.code }).toEqual({ status: 428, code: 'ACTION_CONFIRMATION_REQUIRED' }); + expect(res.body?.error?.details).toMatchObject({ reason: 'service_account' }); + expect(h.ql.executeAction).not.toHaveBeenCalled(); + }); + + it('the member gate a host door asks still admits a person\'s confirm: true and refuses without it (no reason)', () => { + expect(actionConfirmationRefusal({} as any, GATED, { [AI_ACTION_CONFIRMATION_MEMBER]: true }, OBJECT, PERSON)).toBeUndefined(); + const refused = actionConfirmationRefusal({} as any, GATED, {}, OBJECT, PERSON); + expect({ code: refused?.code, status: refused?.status }).toEqual({ code: 'ACTION_CONFIRMATION_REQUIRED', status: 428 }); + expect(refused?.details).not.toHaveProperty('reason'); + }); +}); diff --git a/packages/runtime/src/action-dispatch.test.ts b/packages/runtime/src/action-dispatch.test.ts index 6c4eec5616c..04fda9ced28 100644 --- a/packages/runtime/src/action-dispatch.test.ts +++ b/packages/runtime/src/action-dispatch.test.ts @@ -832,7 +832,7 @@ describe('[ADR-0151 D3 rule 3] an AI service account does not confirm an action const rig = makeRig([confirmed]); const mcp: any = await rig.viaMcp(ACCOUNT_EC, 'confirmed', input); expect({ status: mcp.status, code: mcp.code }, JSON.stringify(input)).toEqual({ status: 428, code: CODE }); - expect(mcp.details).toEqual({ actionName: 'confirmed', objectName: OBJECT, confirmationMember: 'confirm' }); + expect(mcp.details).toEqual({ actionName: 'confirmed', objectName: OBJECT, confirmationMember: 'confirm', reason: 'service_account' }); expect(String(mcp.message)).not.toMatch(/retry/i); expect(rig.ran()).toBe(0); expect(rig.reads()).toBe(0); @@ -857,13 +857,17 @@ describe('[ADR-0151 D3 rule 3] an AI service account does not confirm an action } }); - it('CONTROL: a person runs with the confirmation member at MCP, and runs with or without it at REST', async () => { - const mcp = makeRig([confirmed]); - expect((await mcp.viaMcp(MEMBER_EC, 'confirmed', { confirm: true })).status).toBe(200); - expect(mcp.ran()).toBe(1); - const refused: any = await makeRig([confirmed]).viaMcp(MEMBER_EC, 'confirmed'); - expect({ status: refused.status, code: refused.code }).toEqual({ status: 428, code: CODE }); - expect(String(refused.message)).toMatch(/retry/i); + // [#33690] At MCP a person's own `confirm: true` never counts: the call is + // handed to the host's pending-confirmation service, and this rig has none. + it('CONTROL: a person is held at MCP with the confirmation member and without it, and runs with or without it at REST', async () => { + for (const input of [{}, { confirm: true }]) { + const mcp = makeRig([confirmed]); + const refused: any = await mcp.viaMcp(MEMBER_EC, 'confirmed', input); + expect({ status: refused.status, code: refused.code, reason: refused.details?.reason }, JSON.stringify(input)) + .toEqual({ status: 428, code: CODE, reason: 'no_confirmation_service' }); + expect(String(refused.message)).not.toMatch(/retry/i); + expect(mcp.ran()).toBe(0); + } for (const body of [{}, { confirm: true }]) { const rest = makeRig([confirmed]); expect((await rest.viaRest(MEMBER_EC, 'confirmed', { body })).status).toBe(200); @@ -876,15 +880,17 @@ describe('[ADR-0151 D3 rule 3] an AI service account does not confirm an action expect(read.reads()).toBeGreaterThan(0); }); - it('CONTROL: a delegated agent behaves as before at both doors', async () => { + it('CONTROL: a delegated agent runs at REST and is held for its person at MCP, the confirmation member or not', async () => { const rest = makeRig([confirmed]); expect((await rest.viaRest(DELEGATED_EC, 'confirmed')).status).toBe(200); expect(rest.ran()).toBe(1); - const refused: any = await makeRig([confirmed]).viaMcp(DELEGATED_EC, 'confirmed'); - expect({ status: refused.status, code: refused.code }).toEqual({ status: 428, code: CODE }); - const mcp = makeRig([confirmed]); - expect((await mcp.viaMcp(DELEGATED_EC, 'confirmed', { confirm: true })).status).toBe(200); - expect(mcp.ran()).toBe(1); + for (const input of [{}, { confirm: true }]) { + const mcp = makeRig([confirmed]); + const refused: any = await mcp.viaMcp(DELEGATED_EC, 'confirmed', input); + expect({ status: refused.status, code: refused.code, reason: refused.details?.reason }, JSON.stringify(input)) + .toEqual({ status: 428, code: CODE, reason: 'no_confirmation_service' }); + expect(mcp.ran()).toBe(0); + } }); it('CONTROL: an account runs an action that declares no confirmation, or `false`, at REST, MCP and a host door', async () => { diff --git a/packages/runtime/src/action-dispatch.ts b/packages/runtime/src/action-dispatch.ts index 2a6a718c3e2..ee9e4978020 100644 --- a/packages/runtime/src/action-dispatch.ts +++ b/packages/runtime/src/action-dispatch.ts @@ -59,7 +59,7 @@ import { import { readNamespacePositionSegment } from '@objectstack/spec/kernel'; import { actionsDoorAnswerOf, earnedAnswerOf, staleSummaryAnswerLines, type SummaryRecomputeRefusal } from '@objectstack/types'; import { standardErrorCodeForHttpStatus } from '@objectstack/spec/api'; -import type { AIActionConfirmation } from '@objectstack/spec/contracts'; +import type { AIActionConfirmation, ActionConfirmationPending } from '@objectstack/spec/contracts'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import * as actionExec from './action-execution.js'; import type { ActionExecutionDeps } from './action-execution.js'; @@ -149,6 +149,18 @@ export interface ResolvedActionCall { recordIdFromPath?: string; /** The AI-door confirmation member, read under the `ai` posture only. */ confirmation?: AIActionConfirmation; + /** + * [#33690] Present at an AI door that hands a declared-gated call to the + * person it runs as (the MCP `run_action` tool) instead of reading + * {@link confirmation}: under the amended contract the caller's `confirm` + * never counts there. An AI service account is refused as before; every + * other caller's gated call is handed off once every gate, the subject + * load and its verdict included, has passed ({@link ResolvedActionRun}'s + * `handedOff`), and nothing dispatches. `door` and `namespace` are the + * hand-off's own members (`ActionConfirmationHandOff`). A door without it + * (REST, a host's door) keeps the member gate. + */ + confirmationHandOff?: { door: string; namespace?: string }; /** * [ADR-0106 D1] This door's answer for a name nothing declares, where it * is not the sequence's own undeclared `404` ({@link undeclaredActionRefusal}): @@ -230,6 +242,8 @@ export interface AdmittedActionCall { /** What {@link runResolvedAction} answers. */ export type ResolvedActionRun = | { refused: ActionRefusal } + /** [#33690] Handed to the person it runs as; nothing ran and no row is written. */ + | { handedOff: ActionConfirmationPending } | { admitted: AdmittedActionCall; outcome: ActionDispatchOutcome }; /** @@ -263,6 +277,7 @@ export async function runResolvedAction( ): Promise { const admission = await admitResolvedAction(deps, requestContext, call); if ('refused' in admission) return admission; + if (admission.handOff) return handOffAdmittedAction(deps, requestContext, call, admission); const outcome = await dispatchAdmittedAction(deps, requestContext, call, admission); return { admitted: { actionDef: admission.actionDef, objectName: call.objectName, actionName: call.actionName, recordId: admission.recordId }, @@ -276,6 +291,55 @@ interface Admission { recordId: any; params: Record; subject: actionExec.ActionSubjectRecordLoad; + /** [#33690] The call is handed to the person, never dispatched ({@link ResolvedActionCall.confirmationHandOff}). */ + handOff: boolean; +} + +/** + * [#33690] The hand-off of an admitted, declared-gated call at a door that + * hands off: the caller-scope subject verdict as the arm would read it, then + * the host's pending-confirmation service (or the `no_confirmation_service` + * refusal). Nothing dispatches, and no invocation row is written: the call + * did not run. A verdict refusal is the arm's own, rendered as a refusal. + */ +async function handOffAdmittedAction( + deps: ActionExecutionDeps, + requestContext: HttpProtocolContext, + call: ResolvedActionCall, + admission: Admission, +): Promise { + const { objectName, wiring } = call; + const { actionDef, recordId, params, subject } = admission; + const subjectRecordId = recordId === undefined || recordId === null || recordId === '' ? undefined : String(recordId); + try { + await actionExec.refuseDeniedSubjectBeforeHandOff(deps, requestContext, actionDef, { + objectName, recordId: subjectRecordId, subject, ec: wiring.ec, envId: wiring.envId, + }); + } catch (error) { + const thrown = error as Error & { code?: unknown; status?: unknown }; + if (typeof thrown?.status !== 'number' || typeof thrown?.code !== 'string') throw error; + return { refused: { message: thrown.message, status: thrown.status, details: { code: thrown.code } } }; + } + const handOff = call.confirmationHandOff!; + const answer = await actionExec.handOffActionConfirmation(deps, requestContext, wiring.envId, { + actionName: typeof actionDef?.name === 'string' && actionDef.name ? actionDef.name : call.actionName, + ...(actionExec.isObjectLessActionKey(objectName) ? {} : { objectName }), + ...(handOff.namespace !== undefined ? { namespace: handOff.namespace } : {}), + ...(subjectRecordId !== undefined ? { recordId: subjectRecordId } : {}), + params, + door: handOff.door, + }, wiring.ec); + if ('refused' in answer) { + const { refused } = answer; + return { + refused: { + message: refused.message, + status: refused.status, + details: { code: refused.code, ...(refused.details as unknown as Record) }, + }, + }; + } + return { handedOff: answer.pending }; } async function admitResolvedAction( @@ -457,7 +521,22 @@ async function admitResolvedAction( // rule 3] Asked under BOTH postures for an AI service account, which never // confirms an action for itself; under `ai` only for everyone else, so REST // stays outside the gate for a person and a delegated agent. - if (posture === 'ai' || actionExec.isAiServiceAccountCaller(wiring.ec)) { + // + // [#33690] At a door that hands off (MCP `run_action`) the member is not + // read: an account is refused here as before, and every other caller's + // gated call is handed to the person after the subject load below. + let handOff = false; + if (call.confirmationHandOff && posture === 'ai') { + const step = actionExec.aiDoorConfirmation(deps, actionDef, objectName, wiring.ec); + if (step.kind === 'refuse') { + return refuse({ + message: step.refusal.message, + status: step.refusal.status, + details: { code: step.refusal.code, ...(step.refusal.details as unknown as Record) }, + }); + } + handOff = step.kind === 'hand-off'; + } else if (posture === 'ai' || actionExec.isAiServiceAccountCaller(wiring.ec)) { const confirmationRefusal = actionExec.actionConfirmationRefusal( deps, actionDef, call.confirmation ?? {}, objectName, wiring.ec, ); @@ -475,7 +554,7 @@ async function admitResolvedAction( // CALLER's own scope delivered the row (commit f19475c0a). const subject = await actionExec.loadActionSubjectRecord(objectName, recordId, () => wiring.callData('get', { object: objectName, id: recordId }, wiring.driver, wiring.envId, wiring.ec)); - return { actionDef, actionType, recordId, params, subject }; + return { actionDef, actionType, recordId, params, subject, handOff }; } /** @@ -748,6 +827,10 @@ export async function runResolvedActionAsRest( ): Promise { const run = await runResolvedAction(deps, requestContext, call); if ('refused' in run) return { handled: true, response: restRefusalResponse(deps, run.refused) }; + // [#33690] Only a door that sets `confirmationHandOff` (MCP `run_action`) + // hands off; a REST-rendered call never does. Answered as the success it + // is, should a door ever set it here, and like a refusal it writes no row. + if ('handedOff' in run) return { handled: true, response: deps.success(run.handedOff) }; const { response } = restAnswerOf(deps, run.admitted, run.outcome); // [#27908] THE INVOCATION ROW: one row for every call that cleared the // gates, whatever the arm answered. A call a gate refused writes none. diff --git a/packages/runtime/src/action-execution.ts b/packages/runtime/src/action-execution.ts index af67ac7d72a..fa5e3071e0d 100644 --- a/packages/runtime/src/action-execution.ts +++ b/packages/runtime/src/action-execution.ts @@ -30,9 +30,14 @@ import { renderOperationMessage } from '@objectstack/spec/system'; // retries have to agree on it, and two doors each writing their own 'confirm' // is how one contract becomes two dialects (Prime Directive #12). import { + ACTION_CONFIRMATION_SERVICE, AI_ACTION_CONFIRMATION_MEMBER, type AIActionConfirmation, + type ActionConfirmationHandOff, + type ActionConfirmationPending, + type ActionConfirmationRefusalReason, type ActionConfirmationRequiredDetails, + type IActionConfirmationService, } from '@objectstack/spec/contracts'; import { checkApiExposure, type ApiExposureDecision, type ObjectApiDef } from './api-exposure.js'; // [#22823] The ONE walk every door that hands a caller's filter to the engine @@ -3018,9 +3023,13 @@ export function actionLooksDestructive(_deps: ActionExecutionDeps, action: any): * REST `/actions` and a host door on `rest` refuse it too, and the MCP * `resume_run` door asks it for every candidate action. * - * For every other caller, the doors that enforce the author's AI opt-in — - * today {@link invokeBusinessAction}, reached from the MCP `run_action` tool, - * and `resume_run`. REST `/actions` (`domains/actions.ts`) is NOT + * For every other caller, a door that enforces the author's AI opt-in and + * still reads the member: today a host's door under the `ai` posture + * (`dispatchAction`, `action-dispatch.ts`). [#33690] The MCP `run_action` + * ({@link invokeBusinessAction}) and `resume_run` doors no longer read it: + * under the amended contract they hand a declared-gated call to the person + * ({@link aiDoorConfirmation}, {@link handOffActionConfirmation}) and the + * caller's `confirm` never counts. REST `/actions` (`domains/actions.ts`) is NOT * `ai.exposed`-gated and sits OUTSIDE this gate for a person and for a * delegated agent. Widening that set is its own decision, not a thing to infer * from this comment. @@ -3079,30 +3088,200 @@ export function actionConfirmationRefusal( if (!account && request?.[AI_ACTION_CONFIRMATION_MEMBER] === true) return undefined; const actionName = String(action?.name ?? ''); + const declared = `Action '${actionName}'${confirmationSubjectOn(objectName)} declares ai.requiresConfirmation: true — nothing was run. `; + // For an account the message states the rule and prescribes no retry: + // nothing the account adds to the request runs this action. Its refusal + // carries `reason: 'service_account'` at every door (the amended + // contract, rule 6); a person's member refusal carries none, which is how + // a caller tells a member gate from the amended doors. + return account + ? confirmationRefusalOf( + actionName, objectName, + declared + 'An AI service account does not confirm an action for itself: a person runs this action.', + 'service_account', + ) + : confirmationRefusalOf( + actionName, objectName, + declared + + `Confirm with the human in the loop, then retry this call with ` + + `'${AI_ACTION_CONFIRMATION_MEMBER}': true on the request.`, + ); +} + +/** ` on ''`, or nothing for an object-less action: the refusals' and the hand-off's shared phrase. */ +function confirmationSubjectOn(objectName: string | undefined): string { + return objectName ? ` on '${objectName}'` : ''; +} + +/** The registered `ACTION_CONFIRMATION_REQUIRED` envelope, `reason` set only when given. */ +function confirmationRefusalOf( + actionName: string, + objectName: string | undefined, + message: string, + reason?: ActionConfirmationRefusalReason, +): ActionConfirmationRefusal { const details: ActionConfirmationRequiredDetails = { actionName, ...(objectName ? { objectName } : {}), // Echoed off the constant so a refused caller reads the member's // spelling from the refusal instead of hard-coding it from docs. confirmationMember: AI_ACTION_CONFIRMATION_MEMBER, + ...(reason !== undefined ? { reason } : {}), }; - const on = objectName ? ` on '${objectName}'` : ''; - const declared = `Action '${actionName}'${on} declares ai.requiresConfirmation: true — nothing was run. `; + return { code: ACTION_CONFIRMATION_REQUIRED_CODE, status: ACTION_CONFIRMATION_REQUIRED_STATUS, message, details }; +} + +/** + * [#33690] The confirmation step of the MCP `run_action` and `resume_run` + * doors under the amended contract (`AI_ACTION_CONFIRMATION_CAPABILITY`, + * `@objectstack/spec/contracts`; ADR-0011, the note on confirmation): what + * the door does with a call on `action` from `caller`. + * + * - `admit`: the author declared no gate (`ai.requiresConfirmation` is not + * `true` — the DECLARED flag, as {@link actionConfirmationRefusal} reads + * it), so the call runs as any admitted call does. + * - `refuse`: an AI service account (ADR-0151 D3 rule 3), refused whatever + * it sends, `reason: 'service_account'`, exactly as the member gate + * refuses it. It is never handed off: no person stands behind it. + * - `hand-off`: every other caller. The call is handed to the person it runs + * as ({@link handOffActionConfirmation}) once every other admission gate + * has passed, and nothing runs here. + * + * ⛔ The request is not a parameter, on purpose: the caller's + * `confirm` (`AI_ACTION_CONFIRMATION_MEMBER`) never counts on such a call, + * and a function that cannot read the member cannot be satisfied by it. The + * caller's own `confirm: true` was an unverifiable claim an agent made for its + * person; this door asks the person instead. + */ +export type AiDoorConfirmation = + | { kind: 'admit' } + | { kind: 'refuse'; refusal: ActionConfirmationRefusal } + | { kind: 'hand-off' }; + +export function aiDoorConfirmation( + deps: ActionExecutionDeps, + action: any, + objectName: string | undefined, + caller: unknown, +): AiDoorConfirmation { + if (action?.ai?.requiresConfirmation !== true) return { kind: 'admit' }; + if (isAiServiceAccountCaller(caller)) { + // The member gate's own account refusal: it does not read the request + // for an account, so `undefined` loses nothing. + return { kind: 'refuse', refusal: actionConfirmationRefusal(deps, action, undefined, objectName, caller)! }; + } + return { kind: 'hand-off' }; +} + +/** + * [#33690] The host's pending-confirmation service, registered under + * `ACTION_CONFIRMATION_SERVICE` (`'ai.actionConfirmation'`), or `null` when + * this kernel registers none — the open build ships none, so a bare + * deployment answers `null`. Resolved per call, where it is used: a host + * registers it in its own plugin, and a resolution at startup would record a + * verdict the boot can still contradict. A registration without a `submit` + * member, or a resolution that throws, reads as none: the door then refuses, + * so nothing ever runs for want of the service. + */ +export async function resolveActionConfirmationService( + deps: ActionExecutionDeps, + requestContext: HttpProtocolContext, + envId?: string, +): Promise { + try { + const svc = await deps.resolveService(requestContext, ACTION_CONFIRMATION_SERVICE, envId); + return svc && typeof svc.submit === 'function' ? (svc as IActionConfirmationService) : null; + } catch { + return null; + } +} + +/** + * [#33690] Hand a declared-gated call off to the person it runs as (step 2 of + * the amended contract), or refuse it when the host has no service to hand it + * to (step 3). Runs nothing either way. + * + * - A registered service: `submit(handOff, ec)` records the call for the + * person and notifies them; the door answers `ActionConfirmationPending` + * (`status: 'pending_confirmation'`, the service's `pendingId`, a plain + * message). A hand-off is not a refusal, it is the call's successful answer. + * What happens next — approval in the app, the action running as the + * approver with every gate re-checked, a rejection, a lapse — is the + * host's (`IActionConfirmationService`). + * - None: `428 ACTION_CONFIRMATION_REQUIRED`, `details.reason: + * 'no_confirmation_service'`. The message names the one route that works on + * this server — performing the action in the app — and no retry: no request + * this caller can send runs the action here. + * + * A service that answers no `pendingId` is a broken host, never a hand-off + * that happened: thrown, so the caller is not told a person was asked. + */ +export async function handOffActionConfirmation( + deps: ActionExecutionDeps, + requestContext: HttpProtocolContext, + envId: string | undefined, + handOff: ActionConfirmationHandOff, + ec: any, +): Promise<{ pending: ActionConfirmationPending } | { refused: ActionConfirmationRefusal }> { + const on = confirmationSubjectOn(handOff.objectName); + const declared = `Action '${handOff.actionName}'${on} declares ai.requiresConfirmation: true, so a person confirms it`; + const service = await resolveActionConfirmationService(deps, requestContext, envId); + if (!service) { + return { + refused: confirmationRefusalOf( + handOff.actionName, handOff.objectName, + `${declared} — nothing was run. This server has no pending-confirmation service to ask them through, ` + + `and a confirmation sent on the request does not count. Perform the action in the app instead.`, + 'no_confirmation_service', + ), + }; + } + const submitted = await service.submit(handOff, ec as ExecutionContext); + const pendingId = submitted?.pendingId; + if (typeof pendingId !== 'string' || pendingId === '') { + throw new Error( + `The pending-confirmation service (${ACTION_CONFIRMATION_SERVICE}) answered no pendingId for action ` + + `'${handOff.actionName}'${on}; nothing was run and no confirmation can be tracked.`, + ); + } return { - code: ACTION_CONFIRMATION_REQUIRED_CODE, - status: ACTION_CONFIRMATION_REQUIRED_STATUS, - // For an account the message states the rule and prescribes no retry: - // nothing the account adds to the request runs this action. - message: account - ? declared - + 'An AI service account does not confirm an action for itself: a person runs this action.' - : declared - + `Confirm with the human in the loop, then retry this call with ` - + `'${AI_ACTION_CONFIRMATION_MEMBER}': true on the request.`, - details, + pending: { + status: 'pending_confirmation', + pendingId, + message: + `${declared}. Nothing has run yet: a confirmation request was sent to the person this call runs as, ` + + `who approves or rejects it in the app. It runs only if they approve it, as them. ` + + `Pending confirmation: ${pendingId}.`, + actionName: handOff.actionName, + ...(handOff.objectName ? { objectName: handOff.objectName } : {}), + }, }; } +/** + * [#33690] The caller-scope subject verdict, as the dispatch arm that would + * run `action` reads it, asked BEFORE a hand-off (the amended contract, step + * 2: every admission gate has passed, the subject load and its verdict + * included, so nobody is asked to confirm a call that is refused anyway). A + * declarative update asks its object-level update refusal first (#30848), as + * its arm does; every other arm asks {@link refuseDeniedSubjectLoadBeforeDispatch}. + * Throws the refusal the arm would throw; reads nothing new. + */ +export async function refuseDeniedSubjectBeforeHandOff( + deps: ActionExecutionDeps, + requestContext: HttpProtocolContext, + action: any, + wiring: { objectName: string; recordId: string | undefined; subject: ActionSubjectRecordLoad; ec: any; envId?: string }, +): Promise { + const { objectName, recordId, subject, ec, envId } = wiring; + if (isDeclarativeUpdateAction(action)) { + if (subject.recordLoadDenied) await refuseUngrantedDeclarativeUpdate(deps, requestContext, objectName, ec, envId); + refuseDeniedSubjectLoad(objectName, recordId, subject); + return; + } + refuseDeniedSubjectLoadBeforeDispatch(action, objectName, recordId, subject); +} + export function summarizeAction( deps: ActionExecutionDeps, action: any, obj: any, objectName: string, flow?: any, objectOf?: ActionParamObjectLookup, ): any { @@ -4719,7 +4898,10 @@ export async function invokeBusinessAction(deps: ActionExecutionDeps, ? { unknownName: addressedUnknownNameRefusal(name, input?.objectName, qualifier) } : askedObject ? {} : { unknownName: refusalOfThrown(objectlessNameNotFoundError(name)) }), body: { params, ...(recordId !== undefined ? { recordId } : {}) }, - confirmation: input, + // [#33690] This door hands a declared-gated call to the person it runs + // as: the caller's `confirm` is not passed on, because it never counts + // there (the amended contract, `AI_ACTION_CONFIRMATION_CAPABILITY`). + confirmationHandOff: { door: 'mcp', ...(namespace !== undefined ? { namespace } : {}) }, ql: engine, wiring: { ec, envId, driver, callData, @@ -4727,6 +4909,10 @@ export async function invokeBusinessAction(deps: ActionExecutionDeps, }, }); if ('refused' in run) throw refusalThrownByBridge(run.refused); + // [#33690] Handed to the person: the successful answer, nothing ran, and + // no invocation row is written (the call did not run; the host's pending + // item is its record, and an approved run writes its own row). + if ('handedOff' in run) return run.handedOff; // [#27908 — ruling 6513869839 on #27681, parameter 3] THE INVOCATION ROW. // Every call that cleared the gates writes one `action_invocation` row, diff --git a/packages/runtime/src/domains/api-action-forward.test.ts b/packages/runtime/src/domains/api-action-forward.test.ts index 62a24417339..9bd20e54022 100644 --- a/packages/runtime/src/domains/api-action-forward.test.ts +++ b/packages/runtime/src/domains/api-action-forward.test.ts @@ -1051,6 +1051,15 @@ describe('[#28943] an API-key caller is never offered a `sys_api_key` write as r }; const CASE_OBJECT = { name: 'crm_case', actions: [CLOSE_CASE] }; const bootWithKeys = (opts: Parameters[0] = {}) => boot({ ...opts, extraObjects: [API_KEY_OBJECT, CASE_OBJECT] }); + /** + * [#33690] The same forward with no confirmation declared: the MCP door + * hands a declared-gated action to the person before anything is forwarded, + * so the forward's own guard is reached at MCP only on this twin. + */ + const UNGATED_API_KEY_OBJECT = { + name: 'sys_api_key', actions: [{ ...REVOKE_API_KEY, ai: { ...REVOKE_API_KEY.ai, requiresConfirmation: false } }], + }; + const bootUngatedKeys = (opts: Parameters[0] = {}) => boot({ ...opts, extraObjects: [UNGATED_API_KEY_OBJECT, CASE_OBJECT] }); const KEY_CTX = (): HttpProtocolContext => { const ctx: any = CTX({ 'x-api-key': 'osk_member_key' }); @@ -1097,11 +1106,17 @@ describe('[#28943] an API-key caller is never offered a `sys_api_key` write as r const h = bootWithKeys(); const listed = await listFor(h, KEY_CTX()); - const thrown = await runViaMcp(h, KEY_CTX(), 'sys_api_key', REVOKE_API_KEY.name, 'key_1').catch((e) => e); + // [#33690] Declared-gated: held for the person before the forward, so no guard is reached. + const held = await runViaMcp(h, KEY_CTX(), 'sys_api_key', REVOKE_API_KEY.name, 'key_1').catch((e) => e); + expect(held).toMatchObject({ code: 'ACTION_CONFIRMATION_REQUIRED', status: 428, details: { reason: 'no_confirmation_service' } }); + + const ungated = bootUngatedKeys(); + const thrown = await runViaMcp(ungated, KEY_CTX(), 'sys_api_key', REVOKE_API_KEY.name, 'key_1').catch((e) => e); expect(thrown).toBeInstanceOf(Error); expect((thrown as any).status).toBe(403); expect((thrown as any).code).toBe(listed[REVOKE_API_KEY.name].unavailable.code); expect(String(thrown.message)).toBe(listed[REVOKE_API_KEY.name].unavailable.reason); + expect(ungated.request).not.toHaveBeenCalled(); const res = await h.dispatcher.handleActions(`/sys_api_key/${REVOKE_API_KEY.name}`, 'POST', { recordId: 'key_1' }, KEY_CTX()); expect(statusOf(res)).toBe(403); @@ -1118,12 +1133,18 @@ describe('[#28943] an API-key caller is never offered a `sys_api_key` write as r expect(listed[REVOKE_API_KEY.name]).toBeDefined(); expect(listed[REVOKE_API_KEY.name].unavailable).toBeUndefined(); - const result: any = await runViaMcp(h, SESSION_CTX(), 'sys_api_key', REVOKE_API_KEY.name, 'key_1'); + // [#33690] Declared-gated: the caller's `confirm: true` does not run it at MCP. + const held = await runViaMcp(h, SESSION_CTX(), 'sys_api_key', REVOKE_API_KEY.name, 'key_1').catch((e) => e); + expect(held).toMatchObject({ code: 'ACTION_CONFIRMATION_REQUIRED', status: 428, details: { reason: 'no_confirmation_service' } }); + expect(h.injected).toHaveLength(0); + + const u = bootUngatedKeys({ answer: { body: { success: true, data: { id: 'key_1', revoked: true } } } }); + const result: any = await runViaMcp(u, SESSION_CTX(), 'sys_api_key', REVOKE_API_KEY.name, 'key_1'); expect(result.ok).toBe(true); - expect(h.injected).toHaveLength(1); - expect(h.injected[0].url).toBe('http://app.example.test/api/v1/data/sys_api_key/key_1'); - expect(h.injected[0].init.method).toBe('PATCH'); - expect(JSON.parse(String(h.injected[0].init.body))).toMatchObject({ revoked: true }); + expect(u.injected).toHaveLength(1); + expect(u.injected[0].url).toBe('http://app.example.test/api/v1/data/sys_api_key/key_1'); + expect(u.injected[0].init.method).toBe('PATCH'); + expect(JSON.parse(String(u.injected[0].init.body))).toMatchObject({ revoked: true }); }); it('control: the same data-door write on an object no rule guards stays runnable under an API key', async () => { diff --git a/packages/runtime/src/domains/mcp.ts b/packages/runtime/src/domains/mcp.ts index 8b51baf8536..0be1c84eed3 100644 --- a/packages/runtime/src/domains/mcp.ts +++ b/packages/runtime/src/domains/mcp.ts @@ -1366,6 +1366,8 @@ export function buildMcpBridge( // the MCP door grew the member in the same change that enforces it, and // a bridge that quietly rebuilt `{ objectName, recordId, params }` was // the second of the two strip layers that made the member unreachable. + // [#33690] The door no longer reads it: a declared-gated call is handed + // to the person it runs as (`invokeBusinessAction`), whatever it carries. runAction: async ( name: string, // [ADR-0150 D5] `namespace` rides through like `confirm`: the whole @@ -1874,11 +1876,11 @@ function notResumableRunMessage(runId: string): string { * candidate that passes admits the call. If none passes, the first * candidate's refusal is served. If there is no candidate at all, the run * was not started by a flow action, and the call is refused 403. - * The confirmation gate applies here too because the flow's writes happen - * after the screen, so on resume. A run started with `confirm: true` still - * needs `confirm: true` to resume. An AI service account never confirms - * an action for itself (ADR-0151 D3 rule 3), so its resume of a gated - * action is refused whatever it sends. + * The confirmation step applies here too because the flow's writes happen + * after the screen, so on resume. [#33690] Under the amended contract the + * caller's `confirm` never counts: a resume of a gated action is handed to + * the person (after steps 4 and 5, below), carrying its run, and an AI + * service account is refused whatever it sends (ADR-0151 D3 rule 3). * 4. **The subject record, read again as the caller.** This is #16370's rule, * with the same two shared functions: `loadActionSubjectRecord` and * `refuseDeniedSubjectLoad`. A record the caller could read when the run @@ -1898,6 +1900,10 @@ function notResumableRunMessage(runId: string): string { * recordId?, result }`. `result` is the engine's own answer, so a run that * pauses on its NEXT screen comes back as `status: 'paused'` with a `runId` * and a `screen`, and a multi-screen wizard is walked by calling this again. + * [#33690] A resume of a gated action answers `ActionConfirmationPending` + * instead (or the `no_confirmation_service` refusal): the run stays parked, + * and approving the hand-off resumes THAT run with these values, as the + * approver, who must be its owner. No invocation row is written for it. */ export async function resumeActionRun( deps: DomainHandlerDeps, @@ -1980,6 +1986,7 @@ export async function resumeActionRun( || flowHolderForCaller(activationEngine?.registry, action.target, packageId) === runPackage) && (runObject === undefined ? actionExec.isObjectLessActionKey(objectName) : objectName === runObject)); let admitted: { action: any; objectName: string } | undefined; + let handOff = false; let firstRefusal: Error | undefined; // [ADR-0106 D1] A candidate this caller is not shown does not exist for // them, as `run_action` answers it: it admits nothing and is no refusal. @@ -1994,12 +2001,13 @@ export async function resumeActionRun( }); if (projected.kind === 'fault') throw actionRunFieldVisibilityRefusal(projected.object); if (projected.kind === 'withhold') continue; - const refusal = resumeAdmissionRefusal(deps, candidate, ec, input, activationEngine); - if (!refusal) { + const admission = resumeAdmissionRefusal(deps, candidate, ec, activationEngine); + if (!(admission instanceof Error)) { admitted = candidate; + handOff = admission.handOff; break; } - firstRefusal ??= refusal; + firstRefusal ??= admission; } if (!admitted) { throw firstRefusal ?? resumeDoorError( @@ -2013,6 +2021,28 @@ export async function resumeActionRun( const { action, objectName } = admitted; const recordId = typeof trigger?.recordId === 'string' && trigger.recordId !== '' ? trigger.recordId : undefined; + // [#33690] A gated action's resume is handed to the person, after steps 4 + // and 5 so nobody is asked to confirm a resume refused anyway: nothing + // resumes, the run stays parked, and no invocation row is written. + if (handOff) { + await refuseUnresumableAdmittedRun(deps, automation, runId, { objectName, recordId, driver, envId, ec, callData }); + const answer = await actionExec.handOffActionConfirmation(deps, context, envId, { + actionName: typeof action?.name === 'string' && action.name ? action.name : String(flowName), + ...(actionExec.isObjectLessActionKey(objectName) ? {} : { objectName }), + ...(recordId !== undefined ? { recordId } : {}), + params: {}, + door: 'mcp', + run: { runId, values: values ?? {} }, + }, ec); + if ('refused' in answer) { + throw resumeDoorError(deps, answer.refused.message, answer.refused.status, { + code: answer.refused.code, + ...answer.refused.details, + }); + } + return answer.pending; + } + // [#27908 — ruling 6513869839 on #27681, parameter 3] THE INVOCATION ROW, // as `run_action` writes it: the call cleared steps 1–3, so from here on // one `action_invocation` row is written whether the resume answers or is @@ -2063,7 +2093,37 @@ async function continueAdmittedRun( callData: (action: string, params: any, dataDriver?: any, scopeId?: string, ec?: any) => Promise; }, ): Promise { - const { action, objectName, recordId, driver, envId, ec, callData } = admitted; + const { action, objectName, recordId } = admitted; + await refuseUnresumableAdmittedRun(deps, automation, runId, admitted); + + // ── 6. resume, answered through the table the REST door uses ───────────── + const signal: { variables?: Record } = {}; + if (values !== undefined) signal.variables = values; + const result = await automation.resume(runId, signal); + const refusal = await classifyResumeResult(deps, automation, runId, result); + if (refusal) throw resumeDoorError(deps, refusal.message, refusal.status, refusal.details, refusal.extra); + return { ok: true, action: action.name, objectName, ...(recordId ? { recordId } : {}), result: result ?? null }; +} + +/** + * `resume_run` steps 4–5 for an admitted run: the subject record read again + * as the caller, and the screen-pause check. Throws the refusal; reads + * nothing else. Asked before a resume and before a hand-off (#33690) alike. + */ +async function refuseUnresumableAdmittedRun( + deps: DomainHandlerDeps, + automation: any, + runId: string, + admitted: { + objectName: string; + recordId: string | undefined; + driver: any; + envId?: string; + ec: any; + callData: (action: string, params: any, dataDriver?: any, scopeId?: string, ec?: any) => Promise; + }, +): Promise { + const { objectName, recordId, driver, envId, ec, callData } = admitted; // ── 4. the subject record, read again in the caller's own scope ────────── const subject = await actionExec.loadActionSubjectRecord(objectName, recordId, () => @@ -2080,22 +2140,14 @@ async function continueAdmittedRun( 409, ); } - - // ── 6. resume, answered through the table the REST door uses ───────────── - const signal: { variables?: Record } = {}; - if (values !== undefined) signal.variables = values; - const result = await automation.resume(runId, signal); - const refusal = await classifyResumeResult(deps, automation, runId, result); - if (refusal) throw resumeDoorError(deps, refusal.message, refusal.status, refusal.details, refusal.extra); - return { ok: true, action: action.name, objectName, ...(recordId ? { recordId } : {}), result: result ?? null }; } /** * [#15705] `run_action`'s admission gates, in `run_action`'s order, for ONE - * candidate action. Answers the refusal, or `undefined` when the candidate - * admits the call. Each gate uses the shared helper `invokeBusinessAction` - * uses, so the reasons cannot drift apart. The system-object, exposure and - * permission refusals are thrown as plain errors there. Here they carry + * candidate action. Answers the refusal, or the admission (whether the call + * is handed to the person, #33690) when the candidate admits the call. Each + * gate uses the shared helper `invokeBusinessAction` uses, so the reasons + * cannot drift apart. The system-object, exposure and permission refusals are thrown as plain errors there. Here they carry * `PERMISSION_DENIED` / 403 (the code and status REST `/actions` answers for * the permission gate), because a refusal on a new door should be * machine-readable. @@ -2104,9 +2156,8 @@ function resumeAdmissionRefusal( deps: DomainHandlerDeps, candidate: { action: any; objectName: string }, ec: any, - request: AIActionConfirmation, activationEngine: any, -): Error | undefined { +): Error | { handOff: boolean } { const { action, objectName } = candidate; const systemObject = actionExec.systemObjectActionExposureError(deps, action, objectName); if (systemObject) return resumeDoorError(deps, systemObject, 403); @@ -2118,12 +2169,14 @@ function resumeAdmissionRefusal( if (disabled) return resumeDoorError(deps, disabled.message, disabled.status, { code: disabled.code }); // [ADR-0151 D3 rule 3] The caller's envelope rides along: an AI service // account never confirms for itself, so it is refused whatever it sends. - const confirmation = actionExec.actionConfirmationRefusal(deps, action, request, objectName, ec); - if (confirmation) { - return resumeDoorError(deps, confirmation.message, confirmation.status, { - code: confirmation.code, - ...confirmation.details, + // [#33690] The request is not read: a gated resume by anyone else is + // handed to the person, never admitted on the caller's `confirm`. + const confirmation = actionExec.aiDoorConfirmation(deps, action, objectName, ec); + if (confirmation.kind === 'refuse') { + return resumeDoorError(deps, confirmation.refusal.message, confirmation.refusal.status, { + code: confirmation.refusal.code, + ...confirmation.refusal.details, }); } - return undefined; + return { handOff: confirmation.kind === 'hand-off' }; } diff --git a/packages/runtime/src/mcp-resume-run.test.ts b/packages/runtime/src/mcp-resume-run.test.ts index 00b93e678bc..2ae673a4244 100644 --- a/packages/runtime/src/mcp-resume-run.test.ts +++ b/packages/runtime/src/mcp-resume-run.test.ts @@ -453,16 +453,20 @@ describe('MCP resumeRun — (b) a caller who may not resume is refused before th expect(h.engine.resume).not.toHaveBeenCalled(); }); - it('a confirmation-gated action without confirm: ACTION_CONFIRMATION_REQUIRED / 428; with it, the run completes', async () => { + it('[#33690] a confirmation-gated action: ACTION_CONFIRMATION_REQUIRED / 428 with confirm and without it (no pending-confirmation service here), and the run stays paused', async () => { const h = makeHarness(); - const runId = await startPaused(h, CONFIRMED.name, 'u1', { confirm: true }); - const refused = await refusalOf(h.bridgeFor('u1').resumeRun(runId, { values: { subject: 'x' } })); - expect(refused).toMatchObject({ code: 'ACTION_CONFIRMATION_REQUIRED', status: 428 }); - expect(refused.details).toEqual({ actionName: 'close_lead', objectName: OBJECT, confirmationMember: 'confirm' }); + // Started as the engine would have it: `run_action` itself hands a + // gated call off now, so it starts no run to resume. + const started: any = await h.engine.execute(CONFIRMED.target, { userId: 'u1', object: OBJECT, record: { id: 'lead_1' } }); + for (const input of [{ values: { subject: 'x' } }, { values: { subject: 'x' }, confirm: true }]) { + const refused = await refusalOf(h.bridgeFor('u1').resumeRun(started.runId, input)); + expect(refused, JSON.stringify(input)).toMatchObject({ code: 'ACTION_CONFIRMATION_REQUIRED', status: 428 }); + expect(refused.details).toEqual({ + actionName: 'close_lead', objectName: OBJECT, confirmationMember: 'confirm', reason: 'no_confirmation_service', + }); + } expect(h.engine.resume).not.toHaveBeenCalled(); - - await h.bridgeFor('u1').resumeRun(runId, { values: { subject: 'x' }, confirm: true }); - expect(h.engine.tasks).toHaveLength(1); + expect(h.engine.tasks).toHaveLength(0); }); it('a run paused on something other than a screen: 409, and the engine is not asked', async () => { @@ -488,7 +492,9 @@ describe('[ADR-0151 D3 rule 3] MCP resumeRun — an AI service account does not for (const input of [{ values: { subject: 'x' }, confirm: true }, { values: { subject: 'x' } }]) { const refused = await refusalOf(h.bridgeAs(ACCOUNT_EC).resumeRun(started.runId, input)); expect(refused, JSON.stringify(input)).toMatchObject({ code: 'ACTION_CONFIRMATION_REQUIRED', status: 428 }); - expect(refused.details).toEqual({ actionName: CONFIRMED.name, objectName: OBJECT, confirmationMember: 'confirm' }); + expect(refused.details).toEqual({ + actionName: CONFIRMED.name, objectName: OBJECT, confirmationMember: 'confirm', reason: 'service_account', + }); expect(refused.message).not.toMatch(/retry/i); } expect(h.engine.resume).not.toHaveBeenCalled(); @@ -508,13 +514,15 @@ describe('[ADR-0151 D3 rule 3] MCP resumeRun — an AI service account does not expect(h.invocations).toHaveLength(1); }); - it('CONTROL: a delegated agent resumes a gated action as before — refused without the member, completed with it', async () => { + it('[#33690] a delegated agent is not an account: its gated resume reaches the hand-off step (no service here: reason no_confirmation_service), with the member and without it', async () => { const h = makeHarness(); const started: any = await h.engine.execute(CONFIRMED.target, { userId: 'u1', object: OBJECT, record: { id: 'lead_1' } }); - const refused = await refusalOf(h.bridgeAs(DELEGATED_EC).resumeRun(started.runId, { values: { subject: 'x' } })); - expect(refused).toMatchObject({ code: 'ACTION_CONFIRMATION_REQUIRED', status: 428 }); - await h.bridgeAs(DELEGATED_EC).resumeRun(started.runId, { values: { subject: 'x' }, confirm: true }); - expect(h.engine.tasks).toHaveLength(1); + for (const input of [{ values: { subject: 'x' } }, { values: { subject: 'x' }, confirm: true }]) { + const refused = await refusalOf(h.bridgeAs(DELEGATED_EC).resumeRun(started.runId, input)); + expect(refused).toMatchObject({ code: 'ACTION_CONFIRMATION_REQUIRED', status: 428 }); + expect(refused.details?.reason).toBe('no_confirmation_service'); + } + expect(h.engine.tasks).toHaveLength(0); }); }); diff --git a/packages/runtime/src/mcp-system-object-action-exposure.test.ts b/packages/runtime/src/mcp-system-object-action-exposure.test.ts index 44d26602bbe..37bc7950d5b 100644 --- a/packages/runtime/src/mcp-system-object-action-exposure.test.ts +++ b/packages/runtime/src/mcp-system-object-action-exposure.test.ts @@ -29,6 +29,8 @@ */ import { describe, it, expect, vi } from 'vitest'; +// Paid at collection, not inside a clocked case: the dispatcher's reach dynamic-imports it (check:test-source-alias). +import '@objectstack/metadata'; import { AI_ACTION_CONFIRMATION_MEMBER } from '@objectstack/spec/contracts'; import { STORED_METADATA_BODY_OBJECTS } from '@objectstack/spec/kernel'; @@ -205,19 +207,21 @@ describe('[#27681] run_action: the flagged sys_* action runs through every gate expect(executeAction).not.toHaveBeenCalled(); }); - it('the HITL confirmation gate refuses an unconfirmed destructive call (428), and runs the confirmed one', async () => { + // [#33690] The caller's own `confirm: true` never counts: with no + // pending-confirmation service the call is refused either way. + it('the HITL confirmation gate refuses a destructive call (428) with the confirmation member and without it', async () => { const { bridge, executeAction } = harness(); - const err = await refusalOf(bridge.runAction('probe_purge', { objectName: SYS_OBJECT, recordId: 'acct_1' })); - expect(err).toMatchObject({ - code: ACTION_CONFIRMATION_REQUIRED_CODE, - status: ACTION_CONFIRMATION_REQUIRED_STATUS, - details: { actionName: 'probe_purge', objectName: SYS_OBJECT, confirmationMember: AI_ACTION_CONFIRMATION_MEMBER }, - }); + for (const extra of [{}, { [AI_ACTION_CONFIRMATION_MEMBER]: true }]) { + const err = await refusalOf(bridge.runAction('probe_purge', { objectName: SYS_OBJECT, recordId: 'acct_1', ...extra })); + expect(err, JSON.stringify(extra)).toMatchObject({ + code: ACTION_CONFIRMATION_REQUIRED_CODE, + status: ACTION_CONFIRMATION_REQUIRED_STATUS, + details: { + actionName: 'probe_purge', objectName: SYS_OBJECT, confirmationMember: AI_ACTION_CONFIRMATION_MEMBER, + reason: 'no_confirmation_service', + }, + }); + } expect(executeAction).not.toHaveBeenCalled(); - - await expect(bridge.runAction('probe_purge', { - objectName: SYS_OBJECT, recordId: 'acct_1', [AI_ACTION_CONFIRMATION_MEMBER]: true, - })).resolves.toMatchObject({ ok: true, action: 'probe_purge' }); - expect(executeAction).toHaveBeenCalledTimes(1); }); }); diff --git a/packages/runtime/src/platform-admin-action-gate.test.ts b/packages/runtime/src/platform-admin-action-gate.test.ts index 3f40430a781..8c02de395f0 100644 --- a/packages/runtime/src/platform-admin-action-gate.test.ts +++ b/packages/runtime/src/platform-admin-action-gate.test.ts @@ -375,9 +375,26 @@ describe('[ruling E] list_actions marks an organization action the caller\'s mem } }); - // Green before the mark existed too: the mark changes no run. + // Green before the mark existed too: the mark changes no run. [#33690] An + // action declaring `ai.requiresConfirmation: true` never runs on the MCP + // caller's own `confirm: true`: with no pending-confirmation service it is + // refused before anything is forwarded, for the admin as for the member. it('CONTROL: run_action is unchanged: the member\'s call is forwarded and refused by the endpoint (the marked code); the admin\'s is forwarded and served', async () => { - for (const key of [...SET_A, ...SET_B]) { + const gated = [...SET_A, ...SET_B].filter((key) => declarationOf(key).ai?.requiresConfirmation === true); + for (const key of gated) { + const [objectName, name] = key.split('.'); + for (const [who, ctx] of [['member', MEMBER_P()], ['admin', ADMIN_P()]] as const) { + const boot = bootIdentity(who === 'member'); + const thrown = await refusalOf(boot.dispatcher.buildMcpBridge(ctx).runAction(name!, { + objectName, recordId: 'rec_1', params: paramsFor(key), confirm: true, + })); + expect(thrown, `${who}: ${key}`).toMatchObject({ + code: 'ACTION_CONFIRMATION_REQUIRED', status: 428, details: { reason: 'no_confirmation_service' }, + }); + expect(boot.request, `${who}: ${key}`).not.toHaveBeenCalled(); + } + } + for (const key of [...SET_A, ...SET_B].filter((k) => !gated.includes(k))) { const [objectName, name] = key.split('.'); const member = bootIdentity(true); const thrown = await refusalOf(member.dispatcher.buildMcpBridge(MEMBER_P()).runAction(name!, {