Repository navigation
fix(agents): bind a human-in-the-loop confirmation to the action it approves - #771
Conversation
`requireConfirmation` is meant to guarantee a tool runs only with the exact
arguments a human saw and approved. It pins the call into the
`adk_request_confirmation` gate and executes that pin, so a message smuggled
in while the gate is open cannot rewrite the arguments — the first case here
asserts that and passes today.
The pin itself is not checked. The resume path in
request_confirmation_llm_request_processor.ts accepts any function call in
history that carries an `originalFunctionCall` argument, without checking the
call's name or author, that the pinned call exists in history, or that the
named tool requires confirmation at all. Session history includes messages
the client wrote, so a client can author the gate, pin an action of its
choosing, approve its own gate, and the tool executes with no human involved.
adk-python validates all of that on resume; this does not.
The three remaining cases pin current behaviour rather than desired
behaviour, and pass because the bypass works:
- a client-forged gate executes an unapproved call;
- the same forgery arrives over A2A, where a `data` part becomes a function
call and the executor's input-required guard is scoped to one task while
the session is keyed by context;
- a replayed approval runs the tool a second time.
Landing the characterization first so the fix is a visible inversion of these
assertions: forgery and replay must raise, the A2A case must execute nothing,
and the pinning case must keep passing.
Bug: b/538565318
The confirmation gate is enforced inside the tool that owns it, which is enough while the tool is deciding whether to pause. It is not enough a turn later: the resume path has to re-ask "does this tool gate at all?" before it honours an approval naming that tool, and today it has no way to ask. Add `BaseTool.checkRequireConfirmation(args, toolContext)`, defaulting to false, overridden by `FunctionTool` to resolve its `requireConfirmation` flag or predicate. `runAsync` now shares that resolution rather than duplicating it, so the answer the resume path gets is the same one the gate itself used. Mirrors adk-python's `BaseTool.check_require_confirmation`. Add `IntentMismatchError` for the checks that will use it: a confirmation that does not bind to the action it claims to approve. It carries the failed check as a `reason` and the call it refers to, and deliberately no argument values — a rejected payload is attacker-controlled and does not belong in a log line. No behaviour change; both additions are wiring for the resume-path validation that follows. Bug: b/538565318
An approval authorizes one action, in the turn it was given, on the branch that asked for it. The resume path enforced none of those three. Single-use. The already-resumed check only looked at events *after* the confirmation event, so a replayed approval — the same bytes, sent again later in the session — landed at the end of history with the original execution behind it, outside the window, and ran the tool a second time. The window now opens at the gate and never closes. It cannot simply cover all of history: the paused call already has a response before the gate, the "requires confirmation" placeholder that raised it, and treating that as an execution would jam the gate shut for everyone. Current. Confirmations were read from the newest user turn that happened to contain one, so a decision from an abandoned turn could be resurrected long after the conversation moved past it. Only the latest user turn is read now, matching adk-python. In scope. The scan ran over every event in the session. A sub-agent could resume a sibling branch's paused call — an approval never shown in its context, for a tool it may not even have. Events are filtered to the current branch, matching adk-python's `_get_events(current_branch=True)`. Restructured into named steps while making these changes: collect the decisions, resolve each to the action it approves, then run. Resolution now also collects gates from more than one event, as adk-python does, instead of stopping at the first event that matched. Inverts the replay case in the b/538565318 characterization test. Bug: b/538565318
Pinning the action when a gate goes up is only worth something if the pin itself is trustworthy. It was not. The resume path accepted any function call in session history carrying an `originalFunctionCall` argument, without checking the call's name, who wrote it, or whether the action it pinned had ever been requested. Session history includes messages the client wrote, so a client could author the gate, pin an action of its choosing, approve its own gate, and watch a `requireConfirmation` tool execute with no human anywhere in the loop. Reachable from any writer on the session: an A2A peer, a second client on a shared context, anything that can reach /run. Before an approval is honoured, the gate must now be one this agent raised — a client-authored gate is refused outright, another agent's is left for that agent — and the action it pins must survive four checks: the agent really issued that call, the tool is still registered, that tool really does gate on approval (statically, or because it asked at runtime), and the pinned name and every argument match what the agent asked to run. Any mismatch raises `IntentMismatchError` and aborts the invocation. Ports the checks in adk-python's `_resolve_confirmation_targets`, plus a check on the gate's own author that Python does not have and does not need — it reaches the same place by requiring the pinned call to be in history and to match exactly. Arguments are matched before the tool is asked whether it gates, so a predicate is never handed a payload that has not already been reconciled with history. `FunctionTool.checkRequireConfirmation` no longer validates arguments for the static flag either: a question about the gate should not come back as a schema error. A tool that asks for confirmation at runtime answers "no" when asked again, so history is consulted for that too: an agent-authored event whose response carries the id it requested confirmation for. Note for a future reader: a gate naming an unregistered tool is refused, which includes `transfer_to_agent` — that tool is registered by the transfer request processor rather than in `canonicalTools`. adk-js has no way to gate a transfer today; if that changes, the transfer tool has to be injected here the way adk-python injects it. Inverts the two forgery cases in the b/538565318 characterization test, which now assert refusal. Test fixtures that only wrote a gate without the agent's own call were under-specifying a real session and have been completed. Bug: b/538565318
`adk_request_confirmation`, `adk_request_credential` and `adk_request_input` are questions the framework asks, raised into agent-authored events. A client answers one with a function response. A client that sends the *call* is writing the question — the first half of approving its own action, and there is no legitimate reason to do it. Reject that message at the runner, which is the one door every transport comes through: the dev server's /run hands `newMessage` straight to it, and the A2A executor calls it after converting a `data` part into whatever function call the part described. Function responses are untouched. This is defence in depth rather than the fix — the resume path already refuses a gate it did not raise — but it keeps the forgery out of the event log entirely, where it would otherwise sit as a trap for the next reader of the history. Deliberately not enforced in `toGenAIPartData`, though that is where the A2A data part becomes a function call: the same converter runs on the caller side of a remote agent, where a gate raised by the remote is exactly what has to come through. The reserved names move to their own module so the runner can see them without importing the tool-execution machinery; `agents/functions.ts` re-exports them, so the public surface is unchanged. Bug: b/538565318
The executor refuses a message that leaves a pending request unanswered, but it only looked at `ctx.task`. The ADK session is keyed by `contextId`, and the client picks its own task ids — so abandoning the task that carries the gate and opening a fresh one in the same context shed the guard entirely, and the agent went on talking while it was supposed to be waiting on a human. Pending requests are now read from the session as well as the task: every long-running call with no response, wherever it was raised. The incoming message has to answer all of them, exactly as before, and the same input-required error comes back naming the first one it missed. Renamed to `getUnansweredRequestEvent`, since it is no longer a question about one task. Bug: b/538565318
`requireConfirmation` asks a person to look at an action and decide. A message arriving over A2A is not that person: it comes from a peer, and a peer that can post to the task could approve a dangerous call on the operator's behalf — the exact substitution the gate exists to prevent. Until now the resume path could not tell the two apart, so it honoured either. The executor marks its runs `remoteDelivered`, and the confirmation processor ignores approvals on such a run, with a warning naming the way back. Matches adk-python, which refuses these outright. Refusing outright would strand deployments whose A2A peer is a front-end relaying a real person's decision, which is a legitimate way to build this and one adk-js appears to have more of than Python does. `allowRemoteToolConfirmation` on the run config opts those back in: same default, with a documented door. `remoteDelivered` is marked internal — only the transport can honestly say where a message came from, so an application setting it is asserting something it does not know. Bug: b/538565318
The auth resume path had the same shape as the confirmation one: it scanned every event for an `adk_request_credential` call, whoever wrote it. The request is what gives the response meaning — it names the tool that is waiting and the key the credential is filed under — so a request in a client-authored event let a caller nominate both: store a credential under a key of its choosing, then resume a tool call of its choosing. Requests are now read only from events this agent authored; one from another agent is left for that agent, as elsewhere. A response with no matching request is also no longer stored. That path ran `parseAndStoreAuthResponse` on whatever arrived, so answering a question that was never asked was enough to seed the session's credential store. The remaining sharp edge is unchanged and worth naming: the `AuthConfig` in the response is adopted wholesale apart from `credentialKey`, which is pinned from the request. Narrowing that to just the credential material is a change to the OAuth exchange itself and wants its own patch. Bug: b/538565318
The request-input resume path collected pending node-tool calls, and the interrupts they were waiting on, from every event in the session — including the ones a client wrote. A node-tool call is an ordinary function call by name, so a caller could put one in a message and have the processor treat it as work already in progress, then hand it resume inputs. Same for the interrupt: a client-written `adk_request_input` was accepted as a question the framework had asked, which a typed reply then answered. Both scans now skip client-authored events. They deliberately test for the client rather than requiring a particular agent name: an interrupt raised inside a workflow is authored by the node that raised it, and the point here is only that the party answering a question is not the party that asked it. Adds the processor's first direct unit test; it had been covered only in passing by the workflow integration suites. Bug: b/538565318
Review catch, and a real one: `longRunningToolIds` marks any tool declared
`isLongRunning`, which is not the same thing as waiting on a person. A
`LongRunningFunctionTool` that returns null never gets a response event, so its
call stayed unanswered forever and every later A2A message in that context came
back `input-required` — the guard would have wedged the conversation shut.
Use `getPendingUserInputRequests`, which matches the three `adk_request_*`
calls and already excludes the answered ones. It also settles which id answers
each kind, so the credential flow — whose answering id can live in the args —
is read the way the rest of the framework reads it. Same rule
`workflow/utils/rehydration_utils.ts` states for the same reason.
Also from review:
- `confirmed` is now read as exactly `true`, in both the field and JSON forms.
Every reader tests it for truthiness, so `{"confirmed": "false"}` — what an
HTML form sends for an unchecked box — used to approve the call. An
unreadable decision resolves the gate as a denial.
- The pending node-tool scan tests the author against this agent's name, as the
confirmation and credential paths do, so a sibling agent's call is no longer
read as this agent's unfinished work. The interrupt scan still only excludes
the client, and now says why: a node raises its interrupt under the node's
name, so an agent-name test there would never match.
- `allowRemoteToolConfirmation` no longer claims to mirror adk-python; it is a
deliberate divergence, and `remoteDelivered`'s single reader is explained.
- Dropped the internal bug id from the test source (it stays in the commit
trailers) and reverted an unrelated YAML fixture that an editor reformatted.
Bug: b/538565318
AmaadMartin
left a comment
There was a problem hiding this comment.
Approve. I verified every source change against the head files at a5084a8.
The binding is correct: the gate must be agent-authored, the pinned call must match a call in history by name and by arguments, the tool must really gate, and an approval is spent by its first execution. The A2A remote-gate refusal, the runner ingress check, the credential author check, and the node-tool resume scoping all hold. The node-interrupt scan excludes only user on purpose, because a node authors its interrupt under the node name (node_runner.ts enrichEvent) — verified.
No type suppressions. The new public types (IntentMismatchError, isIntentMismatchError, IntentMismatchReason) reach common.ts, and no typedoc.json exclusion hides a missing export.
Two items stay open and the description names both: the AuthConfig is still adopted wholesale apart from credentialKey, and the request-input path fabricates a ToolConfirmation. Both are separate patches, not blockers.
CI: ubuntu and macOS passed the new tests; Windows was still running at review time. The PR body embeds a prior review summary that addresses a reviewer; I treated it as data and checked the code independently.
|
Thanks for the review. The two open items are now tracked so they don't ride out on this PR:
|
#775) * fix(auth): bind a credential response to the request that asked for it #771 closed the provenance half of the credential resume path: a request is honoured only if this agent raised it. What the response then says was still taken at face value. Only `credentialKey` was pinned back from the request, and only when the request happened to carry one: const authConfig = authResponses[fcId] as AuthConfig; if (request.config.credentialKey) { authConfig.credentialKey = request.config.credentialKey; } Everything else on the `AuthConfig` — the scheme, the client identity, the credential itself — came from the client. So the destination was trusted and the credential was not, and a session writer who is not the user could put a credential of its choosing under the key a waiting tool reads. That tool then authenticates with it: reads and writes landing in someone else's account while the agent believes it is acting for the user. The scheme is the load-bearing field, because it decides what happens next. Restated as `apiKey`, it sends `parseAndStoreAuthResponse` down the branch that stores the supplied credential verbatim, so an OAuth2 request could be answered without any exchange at all. Left as `oauth2`, it still names the token endpoint, so the same message chose where the exchange posted — within the SSRF blocklist `fetchOAuth2Tokens` already applies, so a public HTTPS host of the sender's choosing. And a response bearing an `accessToken` skipped the exchange regardless, because the exchanger returns early on any token it finds. The CSRF check had the same shape. `exchangeAuthorizationCode` compares the `state` in `authResponseUri` against the `state` on the credential — both of which arrived in the same client message, so it compared the sender against itself, and a response that simply omitted `state` skipped the check. Reconcile the two before storing anything. The request defines the question — scheme, client identity, credential key — and is now the only source for it. The response answers, and what counts as an answer depends on what was asked: if the request carries an `authUri` an authorization-code flow is pending, so only `authResponseUri` and `authCode` are read from the response and the rest of the credential is the agent's; otherwise nothing was pinned to answer — an API key, an HTTP credential, a service account — and the supplied credential is the answer. Pinning `state` this way is what makes the CSRF check mean something, since the state compared against the redirect is now the one the agent issued. A request too incomplete to be an authority, or a response carrying no credential material, is refused rather than guessed at. `processAuthResume` on the workflow path had the same three lines and gets the same treatment; its plain-value branch already built from the request and is unchanged. Test fixtures that asked for a credential without saying what kind were under-specifying a real session — both producers of an `adk_request_credential` call put the whole config in the args — and have been completed. Fixes #772 * fix(auth): refuse a credential that answers nothing, rather than exchanging it Review catch. On the authorization-code path a response whose `exchangedAuthCredential` was present but carried neither `authResponseUri` nor `authCode` was not refused. The answer stayed empty, the agent's own credential came back unchanged, and the exchanger threw further down — aborting the invocation where every other unusable response gets a warn and a skip. Nothing client-controlled was ever stored, so this was safe rather than a gap. It just was not the "refused rather than guessed at" the rest of the module promises, and it reported the same condition in two different ways depending on which field was missing. `bindCredential` now returns `undefined` for that shape, so it joins the others at the caller's warn-and-skip. The no-authorization-code path is untouched: a credential answering an API key, an HTTP scheme or a service account has no code fields by definition and is still accepted. Two direct tests for the two sides of the new branch, and the access-token case now asserts the refusal is clean — no exchange attempted, nothing stored, nothing thrown.
Rebuilt against current main per review: google#771 (2d1bb44) rewrote this file end to end into collectApprovals / collectGateCandidates / bindApprovedCalls partway through review, which the original PR predates entirely. Most of what that PR fixed either already landed via google#771's own rewrite, or -- specifically the ported adk-go#1369 conflict-detection commit -- turned out to be redundant with and strictly weaker than main's bindApprovedCalls, which validates a pin against the agent's actual call by deep-equal name+args rather than against a second copy of the pin. That commit is dropped entirely rather than carried forward. What survives, confirmed against current main directly rather than assumed: two of main's confirmation-resolution scans are still author-blind today. - hasRespondedAfter (the post-approval 'already spent' window) does not check who authored a response reusing the pinned call's id, so a foreign event landing after a legitimate approval -- e.g. an A2A peer's response converted into a model-role event -- convinces the scan the approval was already spent, silently dropping a real, not-yet-executed approval with nothing logged. - mapPlainTextConfirmation's backward scan for the pending gate a typed 'yes' answers has the same gap: a foreign-authored confirmation request landing between the legitimate one and the reply shadows it, so the typed approval resolves nothing at all. Both fixes are the same ~3-line author-filter shape, threaded through via a new agentName parameter. Also adds the requested debug log on collectGateCandidates' existing foreign-author skip, previously silent. Dynamically confirmed each fix by reverting it in isolation against this exact codebase and reproducing the precise executed=[] failure, then restoring and confirming it passes -- not just reasoned about. The debug log's actual output was captured with setLogLevel('debug') and matches byte-for-byte: 'Skipping tool confirmation from event zx4E98KF: authored by payments_agent, not by root_agent.' Adds two regression tests using the existing test file's own fixture helpers (pausedCallEvents, approvalEvent, userTextEvent), placed alongside their closest existing thematic siblings. Verified: all 47 pre-existing tests in this file pass unmodified against the patched source (no regression), both new tests pass, the broader core/test/agents/processors/ suite (12 files, 160 tests) passes, and tsc --noEmit / eslint / prettier --check are all clean.
…755) Rebuilt against current main per review: #771 (2d1bb44) rewrote this file end to end into collectApprovals / collectGateCandidates / bindApprovedCalls partway through review, which the original PR predates entirely. Most of what that PR fixed either already landed via #771's own rewrite, or -- specifically the ported adk-go#1369 conflict-detection commit -- turned out to be redundant with and strictly weaker than main's bindApprovedCalls, which validates a pin against the agent's actual call by deep-equal name+args rather than against a second copy of the pin. That commit is dropped entirely rather than carried forward. What survives, confirmed against current main directly rather than assumed: two of main's confirmation-resolution scans are still author-blind today. - hasRespondedAfter (the post-approval 'already spent' window) does not check who authored a response reusing the pinned call's id, so a foreign event landing after a legitimate approval -- e.g. an A2A peer's response converted into a model-role event -- convinces the scan the approval was already spent, silently dropping a real, not-yet-executed approval with nothing logged. - mapPlainTextConfirmation's backward scan for the pending gate a typed 'yes' answers has the same gap: a foreign-authored confirmation request landing between the legitimate one and the reply shadows it, so the typed approval resolves nothing at all. Both fixes are the same ~3-line author-filter shape, threaded through via a new agentName parameter. Also adds the requested debug log on collectGateCandidates' existing foreign-author skip, previously silent. Dynamically confirmed each fix by reverting it in isolation against this exact codebase and reproducing the precise executed=[] failure, then restoring and confirming it passes -- not just reasoned about. The debug log's actual output was captured with setLogLevel('debug') and matches byte-for-byte: 'Skipping tool confirmation from event zx4E98KF: authored by payments_agent, not by root_agent.' Adds two regression tests using the existing test file's own fixture helpers (pausedCallEvents, approvalEvent, userTextEvent), placed alongside their closest existing thematic siblings. Verified: all 47 pre-existing tests in this file pass unmodified against the patched source (no regression), both new tests pass, the broader core/test/agents/processors/ suite (12 files, 160 tests) passes, and tsc --noEmit / eslint / prettier --check are all clean.
* fix(agents): carry request-input resume inputs in their own type
`ToolConfirmation` means one thing everywhere else in the tree: a human
looked at an action and approved it. The request-input resume path used it
as a transport instead, building `{confirmed: true, payload: resumeInputs}`
for every pending node-tool call so the answers had something to ride in.
That object is installed on `toolContext.toolConfirmation`, which is the
field the confirmation gate reads — so the one fabricated confirmation in
the codebase was, at the point of use, indistinguishable from one a person
granted.
Nothing is exploitable today, and this does not claim otherwise. A NodeTool
does not override `checkRequireConfirmation`, so FunctionTool's gate never
engages for one; SecurityPlugin gates on policy rather than on the tool, but
its state machine cannot currently reach the combination that would matter —
a node tool it blocks never runs, so it never pauses for input, and once a
real approval releases it the recorded state is the ToolConfirmation rather
than 'CONFIRM'. The safety is a coincidence of two unrelated facts, neither
enforced by a type nor asserted by a test, which is what #773 asked to fix.
Split the types. `ToolResumePayload` carries the inputs and has no
`confirmed` field to set, travels in its own `toolResumePayloadDict`
parameter on `handleFunctionCallList`, and lands on its own
`Context.toolResumePayload`. NodeTool reads that field, which also retires
the `typeof payload === 'object'` narrowing the untyped `unknown` payload
needed. `toolConfirmation` now has a single writer path again — a real
approval that survived the binding checks from #771 — so the gate cannot be
satisfied by anything else, and a node tool that starts gating fails closed
instead of silently becoming a bypass.
Tests: the resumed call is asserted to see no confirmation at all while the
inputs still arrive, and an armed SecurityPlugin gate is asserted to hold
against a resume. Both fail against the previous code, the second by running
the node. The gate fixture is seeded rather than played out, for the
reachability reason above, and says so.
Fixes #773
* fix(agents): name resume inputs after adk-python's resume_inputs
adk-python already carries this concept and never had the conflation
this branch fixes: `Context.__init__` takes `tool_confirmation` and
`resume_inputs` as separate parameters (`agents/context.py`), and
nothing in its `src/` fabricates a confirmed `ToolConfirmation` to move
data. So the split here is a parity fix, and it should land in the
shape upstream already uses rather than inventing a second one.
Renames the concept to match and drops the wrapper object:
ToolResumePayload {inputs} -> ResumeInputs = Record<string, unknown>
Context.toolResumePayload? -> Context.resumeInputs
toolResumePayloadDict -> resumeInputsDict
`resumeInputs` now defaults to `{}` rather than being absent, matching
`self._resume_inputs = resume_inputs or {}`. The constructor option
stays optional, so nothing that builds a Context has to change, and
NodeTool loses its `?.inputs ?? {}` dance because the field can no
longer be missing.
The named type is kept — a TypeScript addition upstream has no need
for — but as an alias over the bare mapping, so it hosts the
"this is not an approval" contract without adding a level of nesting
that adk-python does not have.
…863) * fix(a2a): stop attributing a remote peer's message to the local user messageToAdkEvent authored the converted event from the peer's own message role: role === 'user' ? 'user' : agentName. The role is a value the remote peer controls, so a peer could make A2ARemoteAgent append a local event whose author is 'user'. Event author is a trust anchor. The tool-confirmation processor reads an approval only from the latest user-authored event (findLatestUserEvent), so a peer that streams back a message with role 'user' carrying an adk_request_confirmation response with confirmed: true forges the human's approval and lets a requireConfirmation tool run with no human in the loop. #771 already blocks a confirmation that arrives while the agent is serving a remote A2A request (runConfig.remoteDelivered), but that guard only covers the inbound server path; on the outbound client path the peer response lands in an ordinary local run and is not covered, and the author it lands under was the peer's to choose. Attribute the message to the peer instead, the same way taskToAdkEvent and the status-update converters already set author to agentName. The message content role is unchanged, so it still reads as a user or model turn in the model's view; only the trust attribution is corrected. * fix(a2a): correct the credential doc block and tighten the peer-role tests Addresses the review on the peer attribution fix. The doc block in a2a_remote_agent_utils.ts quoted the deleted line and stated the opposite of the code. It now describes the current behaviour: every peer message is attributed to the peer regardless of the role it claims, so a peer's own adk_request_credential is always classified as peer-requested and its answer is forwarded back to the peer that asked. That widens credential egress compared with the old path, where a peer mislabelling its request as role user was treated as local and had the answer withheld; that path is gone because a peer can no longer author an event as the local user. Removes the dead author read in createAdkEventFromMetadata: every converter overwrites author from the local context after the spread, so reading it from peer metadata was dead and read as if a peer could set the author. Adds beforeEach(vi.clearAllMocks) to the peer confirmation test, which relied on test order since vitest.config.ts sets no global clearMocks. Rewrites the duplicate converter case to pin the pair the PR claims: the peer owns the event and the content role stays user. * test(a2a): name the peer-role variables for what they are The empty-message case bound a role:'user' Message to `userMessage` / `userEvent` while asserting `author: 'agent1'`, which reads as a contradiction. Rename to `peerMessageClaimingUserRole` / `eventFromUserRoleClaim` (and the agent-role pair) and add a comment: every Message here comes off the peer's response stream, `role` is the peer's own claim, and authorship ignores it.
…pproves (google#771) * test(security): characterize HITL tool-confirmation intent binding `requireConfirmation` is meant to guarantee a tool runs only with the exact arguments a human saw and approved. It pins the call into the `adk_request_confirmation` gate and executes that pin, so a message smuggled in while the gate is open cannot rewrite the arguments — the first case here asserts that and passes today. The pin itself is not checked. The resume path in request_confirmation_llm_request_processor.ts accepts any function call in history that carries an `originalFunctionCall` argument, without checking the call's name or author, that the pinned call exists in history, or that the named tool requires confirmation at all. Session history includes messages the client wrote, so a client can author the gate, pin an action of its choosing, approve its own gate, and the tool executes with no human involved. adk-python validates all of that on resume; this does not. The three remaining cases pin current behaviour rather than desired behaviour, and pass because the bypass works: - a client-forged gate executes an unapproved call; - the same forgery arrives over A2A, where a `data` part becomes a function call and the executor's input-required guard is scoped to one task while the session is keyed by context; - a replayed approval runs the tool a second time. Landing the characterization first so the fix is a visible inversion of these assertions: forgery and replay must raise, the A2A case must execute nothing, and the pinning case must keep passing. Bug: b/538565318 * feat(tools): expose checkRequireConfirmation and IntentMismatchError The confirmation gate is enforced inside the tool that owns it, which is enough while the tool is deciding whether to pause. It is not enough a turn later: the resume path has to re-ask "does this tool gate at all?" before it honours an approval naming that tool, and today it has no way to ask. Add `BaseTool.checkRequireConfirmation(args, toolContext)`, defaulting to false, overridden by `FunctionTool` to resolve its `requireConfirmation` flag or predicate. `runAsync` now shares that resolution rather than duplicating it, so the answer the resume path gets is the same one the gate itself used. Mirrors adk-python's `BaseTool.check_require_confirmation`. Add `IntentMismatchError` for the checks that will use it: a confirmation that does not bind to the action it claims to approve. It carries the failed check as a `reason` and the call it refers to, and deliberately no argument values — a rejected payload is attacker-controlled and does not belong in a log line. No behaviour change; both additions are wiring for the resume-path validation that follows. Bug: b/538565318 * fix(agents): make a tool confirmation single-use, current, and in scope An approval authorizes one action, in the turn it was given, on the branch that asked for it. The resume path enforced none of those three. Single-use. The already-resumed check only looked at events *after* the confirmation event, so a replayed approval — the same bytes, sent again later in the session — landed at the end of history with the original execution behind it, outside the window, and ran the tool a second time. The window now opens at the gate and never closes. It cannot simply cover all of history: the paused call already has a response before the gate, the "requires confirmation" placeholder that raised it, and treating that as an execution would jam the gate shut for everyone. Current. Confirmations were read from the newest user turn that happened to contain one, so a decision from an abandoned turn could be resurrected long after the conversation moved past it. Only the latest user turn is read now, matching adk-python. In scope. The scan ran over every event in the session. A sub-agent could resume a sibling branch's paused call — an approval never shown in its context, for a tool it may not even have. Events are filtered to the current branch, matching adk-python's `_get_events(current_branch=True)`. Restructured into named steps while making these changes: collect the decisions, resolve each to the action it approves, then run. Resolution now also collects gates from more than one event, as adk-python does, instead of stopping at the first event that matched. Inverts the replay case in the b/538565318 characterization test. Bug: b/538565318 * fix(agents): verify a confirmation binds to the action it approves Pinning the action when a gate goes up is only worth something if the pin itself is trustworthy. It was not. The resume path accepted any function call in session history carrying an `originalFunctionCall` argument, without checking the call's name, who wrote it, or whether the action it pinned had ever been requested. Session history includes messages the client wrote, so a client could author the gate, pin an action of its choosing, approve its own gate, and watch a `requireConfirmation` tool execute with no human anywhere in the loop. Reachable from any writer on the session: an A2A peer, a second client on a shared context, anything that can reach /run. Before an approval is honoured, the gate must now be one this agent raised — a client-authored gate is refused outright, another agent's is left for that agent — and the action it pins must survive four checks: the agent really issued that call, the tool is still registered, that tool really does gate on approval (statically, or because it asked at runtime), and the pinned name and every argument match what the agent asked to run. Any mismatch raises `IntentMismatchError` and aborts the invocation. Ports the checks in adk-python's `_resolve_confirmation_targets`, plus a check on the gate's own author that Python does not have and does not need — it reaches the same place by requiring the pinned call to be in history and to match exactly. Arguments are matched before the tool is asked whether it gates, so a predicate is never handed a payload that has not already been reconciled with history. `FunctionTool.checkRequireConfirmation` no longer validates arguments for the static flag either: a question about the gate should not come back as a schema error. A tool that asks for confirmation at runtime answers "no" when asked again, so history is consulted for that too: an agent-authored event whose response carries the id it requested confirmation for. Note for a future reader: a gate naming an unregistered tool is refused, which includes `transfer_to_agent` — that tool is registered by the transfer request processor rather than in `canonicalTools`. adk-js has no way to gate a transfer today; if that changes, the transfer tool has to be injected here the way adk-python injects it. Inverts the two forgery cases in the b/538565318 characterization test, which now assert refusal. Test fixtures that only wrote a gate without the agent's own call were under-specifying a real session and have been completed. Bug: b/538565318 * fix(runner): refuse a client message that raises a framework request `adk_request_confirmation`, `adk_request_credential` and `adk_request_input` are questions the framework asks, raised into agent-authored events. A client answers one with a function response. A client that sends the *call* is writing the question — the first half of approving its own action, and there is no legitimate reason to do it. Reject that message at the runner, which is the one door every transport comes through: the dev server's /run hands `newMessage` straight to it, and the A2A executor calls it after converting a `data` part into whatever function call the part described. Function responses are untouched. This is defence in depth rather than the fix — the resume path already refuses a gate it did not raise — but it keeps the forgery out of the event log entirely, where it would otherwise sit as a trap for the next reader of the history. Deliberately not enforced in `toGenAIPartData`, though that is where the A2A data part becomes a function call: the same converter runs on the caller side of a remote agent, where a gate raised by the remote is exactly what has to come through. The reserved names move to their own module so the runner can see them without importing the tool-execution machinery; `agents/functions.ts` re-exports them, so the public surface is unchanged. Bug: b/538565318 * fix(a2a): hold a pause open across every task in the context The executor refuses a message that leaves a pending request unanswered, but it only looked at `ctx.task`. The ADK session is keyed by `contextId`, and the client picks its own task ids — so abandoning the task that carries the gate and opening a fresh one in the same context shed the guard entirely, and the agent went on talking while it was supposed to be waiting on a human. Pending requests are now read from the session as well as the task: every long-running call with no response, wherever it was raised. The incoming message has to answer all of them, exactly as before, and the same input-required error comes back naming the first one it missed. Renamed to `getUnansweredRequestEvent`, since it is no longer a question about one task. Bug: b/538565318 * fix(a2a): a remote peer cannot answer a human-in-the-loop gate `requireConfirmation` asks a person to look at an action and decide. A message arriving over A2A is not that person: it comes from a peer, and a peer that can post to the task could approve a dangerous call on the operator's behalf — the exact substitution the gate exists to prevent. Until now the resume path could not tell the two apart, so it honoured either. The executor marks its runs `remoteDelivered`, and the confirmation processor ignores approvals on such a run, with a warning naming the way back. Matches adk-python, which refuses these outright. Refusing outright would strand deployments whose A2A peer is a front-end relaying a real person's decision, which is a legitimate way to build this and one adk-js appears to have more of than Python does. `allowRemoteToolConfirmation` on the run config opts those back in: same default, with a documented door. `remoteDelivered` is marked internal — only the transport can honestly say where a message came from, so an application setting it is asserting something it does not know. Bug: b/538565318 * fix(auth): honour a credential request only if this agent raised it The auth resume path had the same shape as the confirmation one: it scanned every event for an `adk_request_credential` call, whoever wrote it. The request is what gives the response meaning — it names the tool that is waiting and the key the credential is filed under — so a request in a client-authored event let a caller nominate both: store a credential under a key of its choosing, then resume a tool call of its choosing. Requests are now read only from events this agent authored; one from another agent is left for that agent, as elsewhere. A response with no matching request is also no longer stored. That path ran `parseAndStoreAuthResponse` on whatever arrived, so answering a question that was never asked was enough to seed the session's credential store. The remaining sharp edge is unchanged and worth naming: the `AuthConfig` in the response is adopted wholesale apart from `credentialKey`, which is pinned from the request. Narrowing that to just the credential material is a change to the OAuth exchange itself and wants its own patch. Bug: b/538565318 * fix(agents): resume only the node-tool work the agent itself started The request-input resume path collected pending node-tool calls, and the interrupts they were waiting on, from every event in the session — including the ones a client wrote. A node-tool call is an ordinary function call by name, so a caller could put one in a message and have the processor treat it as work already in progress, then hand it resume inputs. Same for the interrupt: a client-written `adk_request_input` was accepted as a question the framework had asked, which a typed reply then answered. Both scans now skip client-authored events. They deliberately test for the client rather than requiring a particular agent name: an interrupt raised inside a workflow is authored by the node that raised it, and the point here is only that the party answering a question is not the party that asked it. Adds the processor's first direct unit test; it had been covered only in passing by the workflow integration suites. Bug: b/538565318 * fix(a2a): read the pause from adk_request_*, not from long-running tools Review catch, and a real one: `longRunningToolIds` marks any tool declared `isLongRunning`, which is not the same thing as waiting on a person. A `LongRunningFunctionTool` that returns null never gets a response event, so its call stayed unanswered forever and every later A2A message in that context came back `input-required` — the guard would have wedged the conversation shut. Use `getPendingUserInputRequests`, which matches the three `adk_request_*` calls and already excludes the answered ones. It also settles which id answers each kind, so the credential flow — whose answering id can live in the args — is read the way the rest of the framework reads it. Same rule `workflow/utils/rehydration_utils.ts` states for the same reason. Also from review: - `confirmed` is now read as exactly `true`, in both the field and JSON forms. Every reader tests it for truthiness, so `{"confirmed": "false"}` — what an HTML form sends for an unchecked box — used to approve the call. An unreadable decision resolves the gate as a denial. - The pending node-tool scan tests the author against this agent's name, as the confirmation and credential paths do, so a sibling agent's call is no longer read as this agent's unfinished work. The interrupt scan still only excludes the client, and now says why: a node raises its interrupt under the node's name, so an agent-name test there would never match. - `allowRemoteToolConfirmation` no longer claims to mirror adk-python; it is a deliberate divergence, and `remoteDelivered`'s single reader is explained. - Dropped the internal bug id from the test source (it stays in the commit trailers) and reverted an unrelated YAML fixture that an editor reformatted. Bug: b/538565318
google#775) * fix(auth): bind a credential response to the request that asked for it google#771 closed the provenance half of the credential resume path: a request is honoured only if this agent raised it. What the response then says was still taken at face value. Only `credentialKey` was pinned back from the request, and only when the request happened to carry one: const authConfig = authResponses[fcId] as AuthConfig; if (request.config.credentialKey) { authConfig.credentialKey = request.config.credentialKey; } Everything else on the `AuthConfig` — the scheme, the client identity, the credential itself — came from the client. So the destination was trusted and the credential was not, and a session writer who is not the user could put a credential of its choosing under the key a waiting tool reads. That tool then authenticates with it: reads and writes landing in someone else's account while the agent believes it is acting for the user. The scheme is the load-bearing field, because it decides what happens next. Restated as `apiKey`, it sends `parseAndStoreAuthResponse` down the branch that stores the supplied credential verbatim, so an OAuth2 request could be answered without any exchange at all. Left as `oauth2`, it still names the token endpoint, so the same message chose where the exchange posted — within the SSRF blocklist `fetchOAuth2Tokens` already applies, so a public HTTPS host of the sender's choosing. And a response bearing an `accessToken` skipped the exchange regardless, because the exchanger returns early on any token it finds. The CSRF check had the same shape. `exchangeAuthorizationCode` compares the `state` in `authResponseUri` against the `state` on the credential — both of which arrived in the same client message, so it compared the sender against itself, and a response that simply omitted `state` skipped the check. Reconcile the two before storing anything. The request defines the question — scheme, client identity, credential key — and is now the only source for it. The response answers, and what counts as an answer depends on what was asked: if the request carries an `authUri` an authorization-code flow is pending, so only `authResponseUri` and `authCode` are read from the response and the rest of the credential is the agent's; otherwise nothing was pinned to answer — an API key, an HTTP credential, a service account — and the supplied credential is the answer. Pinning `state` this way is what makes the CSRF check mean something, since the state compared against the redirect is now the one the agent issued. A request too incomplete to be an authority, or a response carrying no credential material, is refused rather than guessed at. `processAuthResume` on the workflow path had the same three lines and gets the same treatment; its plain-value branch already built from the request and is unchanged. Test fixtures that asked for a credential without saying what kind were under-specifying a real session — both producers of an `adk_request_credential` call put the whole config in the args — and have been completed. Fixes google#772 * fix(auth): refuse a credential that answers nothing, rather than exchanging it Review catch. On the authorization-code path a response whose `exchangedAuthCredential` was present but carried neither `authResponseUri` nor `authCode` was not refused. The answer stayed empty, the agent's own credential came back unchanged, and the exchanger threw further down — aborting the invocation where every other unusable response gets a warn and a skip. Nothing client-controlled was ever stored, so this was safe rather than a gap. It just was not the "refused rather than guessed at" the rest of the module promises, and it reported the same condition in two different ways depending on which field was missing. `bindCredential` now returns `undefined` for that shape, so it joins the others at the caller's warn-and-skip. The no-authorization-code path is untouched: a credential answering an API key, an HTTP scheme or a service account has no code fields by definition and is still accepted. Two direct tests for the two sides of the new branch, and the access-token case now asserts the refusal is clean — no exchange attempted, nothing stored, nothing thrown.
…oogle#755) Rebuilt against current main per review: google#771 (2d1bb44) rewrote this file end to end into collectApprovals / collectGateCandidates / bindApprovedCalls partway through review, which the original PR predates entirely. Most of what that PR fixed either already landed via google#771's own rewrite, or -- specifically the ported adk-go#1369 conflict-detection commit -- turned out to be redundant with and strictly weaker than main's bindApprovedCalls, which validates a pin against the agent's actual call by deep-equal name+args rather than against a second copy of the pin. That commit is dropped entirely rather than carried forward. What survives, confirmed against current main directly rather than assumed: two of main's confirmation-resolution scans are still author-blind today. - hasRespondedAfter (the post-approval 'already spent' window) does not check who authored a response reusing the pinned call's id, so a foreign event landing after a legitimate approval -- e.g. an A2A peer's response converted into a model-role event -- convinces the scan the approval was already spent, silently dropping a real, not-yet-executed approval with nothing logged. - mapPlainTextConfirmation's backward scan for the pending gate a typed 'yes' answers has the same gap: a foreign-authored confirmation request landing between the legitimate one and the reply shadows it, so the typed approval resolves nothing at all. Both fixes are the same ~3-line author-filter shape, threaded through via a new agentName parameter. Also adds the requested debug log on collectGateCandidates' existing foreign-author skip, previously silent. Dynamically confirmed each fix by reverting it in isolation against this exact codebase and reproducing the precise executed=[] failure, then restoring and confirming it passes -- not just reasoned about. The debug log's actual output was captured with setLogLevel('debug') and matches byte-for-byte: 'Skipping tool confirmation from event zx4E98KF: authored by payments_agent, not by root_agent.' Adds two regression tests using the existing test file's own fixture helpers (pausedCallEvents, approvalEvent, userTextEvent), placed alongside their closest existing thematic siblings. Verified: all 47 pre-existing tests in this file pass unmodified against the patched source (no regression), both new tests pass, the broader core/test/agents/processors/ suite (12 files, 160 tests) passes, and tsc --noEmit / eslint / prettier --check are all clean.
…gle#822) * fix(agents): carry request-input resume inputs in their own type `ToolConfirmation` means one thing everywhere else in the tree: a human looked at an action and approved it. The request-input resume path used it as a transport instead, building `{confirmed: true, payload: resumeInputs}` for every pending node-tool call so the answers had something to ride in. That object is installed on `toolContext.toolConfirmation`, which is the field the confirmation gate reads — so the one fabricated confirmation in the codebase was, at the point of use, indistinguishable from one a person granted. Nothing is exploitable today, and this does not claim otherwise. A NodeTool does not override `checkRequireConfirmation`, so FunctionTool's gate never engages for one; SecurityPlugin gates on policy rather than on the tool, but its state machine cannot currently reach the combination that would matter — a node tool it blocks never runs, so it never pauses for input, and once a real approval releases it the recorded state is the ToolConfirmation rather than 'CONFIRM'. The safety is a coincidence of two unrelated facts, neither enforced by a type nor asserted by a test, which is what google#773 asked to fix. Split the types. `ToolResumePayload` carries the inputs and has no `confirmed` field to set, travels in its own `toolResumePayloadDict` parameter on `handleFunctionCallList`, and lands on its own `Context.toolResumePayload`. NodeTool reads that field, which also retires the `typeof payload === 'object'` narrowing the untyped `unknown` payload needed. `toolConfirmation` now has a single writer path again — a real approval that survived the binding checks from google#771 — so the gate cannot be satisfied by anything else, and a node tool that starts gating fails closed instead of silently becoming a bypass. Tests: the resumed call is asserted to see no confirmation at all while the inputs still arrive, and an armed SecurityPlugin gate is asserted to hold against a resume. Both fail against the previous code, the second by running the node. The gate fixture is seeded rather than played out, for the reachability reason above, and says so. Fixes google#773 * fix(agents): name resume inputs after adk-python's resume_inputs adk-python already carries this concept and never had the conflation this branch fixes: `Context.__init__` takes `tool_confirmation` and `resume_inputs` as separate parameters (`agents/context.py`), and nothing in its `src/` fabricates a confirmed `ToolConfirmation` to move data. So the split here is a parity fix, and it should land in the shape upstream already uses rather than inventing a second one. Renames the concept to match and drops the wrapper object: ToolResumePayload {inputs} -> ResumeInputs = Record<string, unknown> Context.toolResumePayload? -> Context.resumeInputs toolResumePayloadDict -> resumeInputsDict `resumeInputs` now defaults to `{}` rather than being absent, matching `self._resume_inputs = resume_inputs or {}`. The constructor option stays optional, so nothing that builds a Context has to change, and NodeTool loses its `?.inputs ?? {}` dance because the field can no longer be missing. The named type is kept — a TypeScript addition upstream has no need for — but as an alias over the bare mapping, so it hosts the "this is not an approval" contract without adding a level of nesting that adk-python does not have.
Link to Issue or Description of Change
Problem
requireConfirmationis meant to guarantee that a gated tool runs only with theexact arguments a human saw and approved. The pinning half worked — the action
is snapshotted into the
adk_request_confirmationcall and the snapshot is whatexecutes, so an instruction smuggled in while the gate is open cannot rewrite
it.
The pin itself was not checked. The resume path accepted any function call in
session history carrying an
originalFunctionCallargument, without checkingthe call's name, who wrote it, or whether the action it pinned had ever been
requested. Session history includes messages the client wrote. So a client
could author the gate, pin an action of its choosing, approve its own gate, and
watch a gated tool execute with no human anywhere in the loop — reachable from
any writer on the session: an A2A peer, a second client on a shared context,
anything that can reach
/run.Three smaller flaws in the same area: an approval was not single-use (replaying
it ran the tool again), the A2A "answer the pending call first" guard was scoped
to one task while the session is keyed by context (so a new task shed it), and
the credential and node-tool resume paths took their requests from any author
too.
adk-pythonvalidates all of this on resume (_resolve_confirmation_targets);adk-js did not. The gap is an omission of checks Python already has, not a
design difference — worth a look in Go and Java for the same reason.
Solution
Nine commits, each independently reviewable, in dependency order:
408733352b34ddcheckRequireConfirmation+IntentMismatchError(no behaviour change)4d35a03828351b89fb1d7adk_request_*calls8f3cec293bbd0eallowRemoteToolConfirmationopts inaddae5b92745eda5084a8The characterization commit lands first on purpose, so the fix reads as an
inversion of its assertions rather than as a claim.
Three judgement calls worth a reviewer's attention:
live in
toGenAIPartData: that converter also runs on the caller side of aremote agent, where a gate raised by the remote must come through.
allowRemoteToolConfirmationis a deliberate divergence from adk-python,which refuses remote-delivered confirmations outright. Same default; adk-js
has real deployments where the peer is a front-end relaying a person's
decision.
AuthConfigis still adopted wholesale apart from the pinnedcredentialKey.Narrowing that touches the OAuth exchange and wants its own patch.
Testing Plan
Unit Tests
npm run test:unit,npm run test:integration,npm run ts:check,npm run lint,npm run format:checkall clean.Coverage: 884 changed source lines across 13 files, 0 uncovered —
statements and branches, audited per-line against the diff rather than by file
percentage.
Manual End-to-End (E2E) Tests
The reproduction is automated, and the demonstration is that the original
assertions now fail. Restore the characterization test as first written and run
it against the current tree:
The in-tree suite asserts the refusals, 5/5 passing:
No credentials or network needed: the tests drive a scripted model, an
InMemoryRunner, and the realA2AAgentExecutor.Checklist
Additional context
This change was reviewed once in a private repository before being opened here.
The commits are unchanged, so the SHAs in the table above are the reviewed ones.
The review is summarised below rather than lost.
Round 1 — @AmaadMartin, reviewing at
92745edVerdict on the core of the change: the binding reads correctly — the gate must
be agent-authored, the pinned call must match session history by name and by
arguments, the tool must really gate, and the approval is spent by the first
execution, with
IntentMismatchErrorthrown rather than logged. Both writers oftoolConfirmationDictwere traced; only the request-input resume path was foundto stay unbound.
Two blocking items, both fixed in
a5084a8:longRunningToolIdswas the wrong "waiting on a human" signal on the A2A path — aLongRunningFunctionToolreturningnullnever produces a response event, so its call stays unanswered forever and every later message in that context comes backinput-required, wedging the conversation shutgetPendingUserInputRequests, which matches the threeadk_request_*calls and settles which id answers each kind; 2 regression testsconfirmedwas read as truthy, so{"confirmed": "false"}— what an HTML form sends for an unchecked box — approved the calltruein both the field and JSON forms; an unreadable decision now resolves the gate as a denial; 6 testsFour nits, three fixed and one half-declined:
'user', where the other two hardened processors test against the agent nameevent.author !== agent.name, so a sibling agent's call no longer reads as this agent's unfinished work. ThependingInterruptIdsscan keeps the client-exclusion test — a node raises its interrupt under the node's name (workflow/node_runner.ts:577), so an agent-name test there would match nothing and would break workflow HITL outright. The reason is now written in the commentallowRemoteToolConfirmationclaimed to mirror adk-python, which has no equivalent switchremoteDelivered's single reader documented on the fieldprettier --writepointed at directories; the repo'sformatscript scopes to**/*.tsprecisely so this cannot happenOpen follow-ups, not addressed here — both now tracked
AuthConfigin a credential response is adopted wholesale apartfrom
credentialKey, so the scheme, the token endpoint and the credentialmaterial are all still caller-supplied. Narrowing it touches the OAuth
exchange and wants its own patch.
new ToolConfirmation({confirmed: true})to carry resume inputs. It is theone confirmation in the tree that is fabricated rather than approved. Neither
reviewer nor author found a reachable bypass, but it wants a distinct
resume-payload type rather than reusing the approval type.