Skip to content

Commit ce132b9

Browse files
DeanChensjcopybara-github
authored andcommitted
feat(workflow): pause tool nodes for tool confirmation via RequestInput
A tool that requires confirmation behaved differently inside a workflow graph than inside an LlmAgent. In an agent the call pauses until the user approves or rejects it. In a tool node, the confirmation request was recorded on `ctx.actions` where nothing handled it, and the placeholder `{'error': 'This tool call requires confirmation, ...'}` was passed downstream as the node output. The tool never ran. Tool nodes now turn both ways a tool can ask for confirmation into a single `RequestInput` (interrupt id `wf_tool_confirmation:<node_path>`, response schema `ToolConfirmation`), and the workflow waits: * Before the call, when `check_require_confirmation` returns True (for example `FunctionTool(require_confirmation=...)`). Tool nodes reuse the agent pipeline's confirmation gate (`tools/_confirmation_utils.py`), which runs after the plugin before-tool callback. On resume, an approval runs the tool once; a rejection answers with `{'error': 'This tool call is rejected.'}` without running the tool. After-tool plugin callbacks still see the rejected result. * While the call runs, when the tool calls `tool_context.request_confirmation(hint=..., payload=...)` (for example `ExecuteBashTool`). The hint becomes the request message and the payload is passed through as `confirmation_payload`. On resume, the tool reruns and decides what to do with the answer, as it does inside an agent. Both paths record the request on `ctx.actions.requested_tool_confirmations`, and the tool node converts it into the `RequestInput` in one place. On resume the answer is stored on `ctx.tool_confirmation` before any plugin tool callback runs, as an agent sets it when building the `ToolContext`, so the before-tool callback, the gate and the tool all see it, and a malformed answer is not routed to `on_tool_error_callback`. Tool nodes are created with `rerun_on_resume=True` so that confirmed calls can execute upon resume, and `_replay_interceptor.py` fast-forwards tool nodes that completed without output, both static ones and ones scheduled with `ctx.run_node()`, as well as ones that already reran after their confirmation was answered, so their side effects do not run again during workflow replay. A tool that raises after requesting confirmation has its request dropped; the error (or the `on_tool_error_callback` answer) is the call's result. Behavior change: confirm-required tools in a graph now pause for the user instead of emitting the placeholder output. Tools whose confirmation predicate returns False run immediately as before. Not in this change: * `FunctionTool`, `McpTool`, `BashTool` and `ComputerUseTool` keep their own copies of the confirmation check; they pass because `ctx.tool_confirmation` is set before the tool runs. Switching them to the shared gate can be a follow-up. * Auth requests raised by tools inside tool nodes are still unhandled. Tests: end-to-end workflow tests (resumable and non-resumable) for the pause, approval and rejection paths of both confirmation styles (including `ExecuteBashTool`), for the before-tool callback seeing the answer on resume, for a predicate that does not require confirmation, for a failed call dropping its confirmation request, and for static, dynamically scheduled and confirmed tool nodes with no output not rerunning on resume. Co-authored-by: Shangjie Chen <[email protected]> PiperOrigin-RevId: 991938956
1 parent 2daa303 commit ce132b9

6 files changed

Lines changed: 696 additions & 7 deletions

File tree

‎src/google/adk/workflow/_tool_node.py‎

Lines changed: 97 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,12 +28,42 @@
2828

2929
from ..agents.context import Context
3030
from ..events.event import Event
31+
from ..events.request_input import RequestInput
3132
from ..platform import uuid as platform_uuid
33+
from ..tools._confirmation_utils import apply_confirmation_gate
3234
from ..tools.base_tool import BaseTool
35+
from ..tools.tool_confirmation import ToolConfirmation
3336
from ..utils.content_utils import extract_text_from_content
3437
from ._base_node import BaseNode
38+
from ._errors import WorkflowDataError
3539
from ._retry_config import RetryConfig
3640

41+
_TOOL_CONFIRMATION_INTERRUPT_PREFIX = 'wf_tool_confirmation:'
42+
43+
44+
def _parse_tool_confirmation(response: Any) -> ToolConfirmation:
45+
"""Parses the user's answer to a tool confirmation request.
46+
47+
Resume validation against the `ToolConfirmation` schema yields a dict in
48+
which the fields the user left out are None, so those are dropped to fall
49+
back to the model defaults.
50+
"""
51+
if isinstance(response, ToolConfirmation):
52+
return response
53+
if not isinstance(response, dict):
54+
raise WorkflowDataError(
55+
'A tool confirmation response must be a ToolConfirmation payload, but'
56+
f' got {type(response).__name__}.'
57+
)
58+
try:
59+
return ToolConfirmation.from_response_dict(
60+
{k: v for k, v in response.items() if v is not None}
61+
)
62+
except ValueError as e:
63+
raise WorkflowDataError(
64+
f'Invalid tool confirmation response: {response!r}'
65+
) from e
66+
3767

3868
class _ToolNode(BaseNode):
3969
"""A node that wraps an ADK Tool."""
@@ -52,7 +82,8 @@ def __init__(
5282
super().__init__(
5383
tool=tool,
5484
name=name or tool.name,
55-
rerun_on_resume=False,
85+
# Tool nodes rerun on resume so that calls paused for confirmation execute.
86+
rerun_on_resume=True,
5687
retry_config=retry_config,
5788
timeout=timeout,
5889
)
@@ -115,11 +146,16 @@ async def _run_impl(
115146
args[param_name] = ctx.state[param_name]
116147

117148
response = await self._run_tool_with_plugin_callbacks(ctx=ctx, args=args)
149+
if isinstance(response, RequestInput):
150+
yield response
151+
return
118152

119153
# State and artifact deltas recorded on ctx.actions by the tool are
120154
# attached to emitted events by the node runner.
121155
if response is not None:
122156
yield Event(output=response)
157+
else:
158+
yield Event()
123159

124160
async def _run_tool_with_plugin_callbacks(
125161
self, *, ctx: Context, args: dict[str, Any]
@@ -131,15 +167,33 @@ async def _run_tool_with_plugin_callbacks(
131167
callback may answer a failed call, and an after-tool callback may replace
132168
the result. Agent-level tool callbacks do not apply because no agent owns
133169
a tool node.
170+
171+
Like the agent pipeline, the user's answer to a confirmation request is on
172+
`ctx.tool_confirmation` before any callback runs, and the confirmation gate
173+
runs after the before-tool callback. A call waiting for confirmation
174+
returns the `RequestInput` to send the user and skips the after-tool
175+
callback; a rejected call answers with an error that the after-tool
176+
callback still sees.
134177
"""
178+
# Set before the callbacks so they see the answer, and outside the tool
179+
# error handling so a malformed answer is not reported as a tool failure.
180+
self._apply_confirmation_resume(ctx=ctx)
135181
plugin_manager = ctx.get_invocation_context().plugin_manager
136182
response = await plugin_manager.run_before_tool_callback(
137183
tool=self.tool, tool_args=args, tool_context=ctx
138184
)
139185
if response is None:
140186
try:
141-
response = await self.tool.run_async(args=args, tool_context=ctx)
187+
response = await apply_confirmation_gate(self.tool, args, ctx)
188+
if response is None:
189+
response = await self.tool.run_async(args=args, tool_context=ctx)
190+
request = self._take_requested_confirmation(ctx=ctx, args=args)
191+
if request is not None:
192+
return request
142193
except Exception as error:
194+
# The failure is the call's result, so a confirmation the tool asked
195+
# for before raising is dropped rather than left pending.
196+
ctx.actions.requested_tool_confirmations.pop(ctx.function_call_id, None)
143197
response = await plugin_manager.run_on_tool_error_callback(
144198
tool=self.tool, tool_args=args, tool_context=ctx, error=error
145199
)
@@ -152,3 +206,44 @@ async def _run_tool_with_plugin_callbacks(
152206
if altered_response is not None:
153207
response = altered_response
154208
return response
209+
210+
def _apply_confirmation_resume(self, *, ctx: Context) -> None:
211+
"""Stores the user's answer to this node's confirmation request.
212+
213+
The answer is set on `ctx.tool_confirmation`, so the confirmation gate and
214+
the tool see it the same way they do inside an agent.
215+
"""
216+
response = ctx.resume_inputs.get(self._confirmation_interrupt_id(ctx))
217+
if response is not None:
218+
ctx.tool_confirmation = _parse_tool_confirmation(response)
219+
220+
def _take_requested_confirmation(
221+
self, *, ctx: Context, args: dict[str, Any]
222+
) -> RequestInput | None:
223+
"""Turns a confirmation requested for this call into a `RequestInput`.
224+
225+
The request comes from the confirmation gate or from the tool calling
226+
`tool_context.request_confirmation()`. Once the user answers, the node is
227+
rerun with `ctx.tool_confirmation` set.
228+
"""
229+
if not ctx.function_call_id:
230+
return None
231+
requested = ctx.actions.requested_tool_confirmations.pop(
232+
ctx.function_call_id, None
233+
)
234+
if requested is None:
235+
return None
236+
payload: dict[str, Any] = {'tool_name': self.tool.name, 'args': args}
237+
if requested.payload is not None:
238+
payload['confirmation_payload'] = requested.payload
239+
return RequestInput(
240+
interrupt_id=self._confirmation_interrupt_id(ctx),
241+
message=requested.hint
242+
or f'Please approve or reject the tool call {self.tool.name}().',
243+
payload=payload,
244+
response_schema=ToolConfirmation,
245+
)
246+
247+
def _confirmation_interrupt_id(self, ctx: Context) -> str:
248+
"""Returns the interrupt id of this node run's confirmation request."""
249+
return f'{_TOOL_CONFIRMATION_INTERRUPT_PREFIX}{ctx.node_path}'

‎src/google/adk/workflow/utils/_rehydration_utils.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,15 @@ class _ChildScanState:
8585
resolved_responses: dict[str, Any] = field(default_factory=dict)
8686
"""Responses keyed by interrupt id, for the ids in ``resolved_ids``."""
8787

88+
finished_after_resume: bool = False
89+
"""Whether the child finished without asking again after its last answer.
90+
91+
A user response to one of the child's interrupts clears it, and the child's
92+
next direct event sets it unless that event raises an interrupt. It tells a
93+
child that reran with its answers and finished without output apart from one
94+
that has not rerun yet.
95+
"""
96+
8897

8998
def _wrap_response(value: Any) -> dict[str, Any]:
9099
"""Wraps a value into a dict suitable for FunctionResponse.response.
@@ -320,6 +329,7 @@ def get_owner_key(event_path_builder: _NodePathBuilder) -> str | None:
320329
# not rerun never gets to pick an edge again.
321330
scan_states[owner].output = None
322331
scan_states[owner].resolved_responses[fr.id] = response_data
332+
scan_states[owner].finished_after_resume = False
323333

324334
if event.branch:
325335
# Match the branch's run ids exactly. A substring test on the raw
@@ -339,6 +349,7 @@ def get_owner_key(event_path_builder: _NodePathBuilder) -> str | None:
339349
# Same reason as the direct branch: the node paused mid-run
340350
# to ask this, so what it emitted earlier is not its result.
341351
o_state.output = None
352+
o_state.finished_after_resume = False
342353
continue
343354

344355
# 2. Match events under base_path
@@ -430,6 +441,9 @@ def get_owner_key(event_path_builder: _NodePathBuilder) -> str | None:
430441
if schema_json:
431442
schemas_by_id[interrupt_id] = schema_json
432443

444+
if is_direct:
445+
child.finished_after_resume = not interrupt_ids_to_process
446+
433447
return scan_states
434448

435449

‎src/google/adk/workflow/utils/_replay_interceptor.py‎

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ def check_interception(
6161
current_run: DynamicNodeRun | None = None,
6262
) -> InterceptionResult:
6363
"""Determine if a node execution should be intercepted based on history."""
64+
from .._tool_node import _ToolNode # pylint: disable=g-import-not-at-top
6465
from .._workflow import Workflow # pylint: disable=g-import-not-at-top
6566

6667
# Case 1: Same-turn completed or waiting interception (dynamic nodes only).
@@ -127,22 +128,35 @@ def check_interception(
127128
elif recovered.interrupt_ids:
128129
# Case 5: Cross-turn all prior interrupts are resolved, but no output yet.
129130
# Extract responses directly if the node does not support rerun; otherwise
130-
# rerun natively with resolved responses to produce output.
131+
# rerun natively with resolved responses to produce output, unless a tool
132+
# node already reran with them.
131133
if not node.rerun_on_resume:
132134
child_resume_inputs = recovered.resolved_responses
133135
if len(child_resume_inputs) == 1:
134136
output = list(child_resume_inputs.values())[0]
135137
else:
136138
output = dict(child_resume_inputs)
139+
elif isinstance(node, _ToolNode) and recovered.finished_after_resume:
140+
# The tool node reran with the user's answers and its tool returned
141+
# None. Fast-forward it, as in case 6, so the tool's side effects do
142+
# not run again.
143+
should_run = False
137144
else:
138145
should_run = True
139146
resume_inputs = recovered.resolved_responses
140147

141148
else:
142149
# Case 6: Cross-turn no events, or events contain no output, route, or interrupts.
143-
# Rerun wait_for_output nodes and rerun_on_resume nodes with no prior output
144-
# so they can guide nested children or resume execution; otherwise fall through.
145-
if node.wait_for_output or node.rerun_on_resume:
150+
if isinstance(node, _ToolNode):
151+
# A tool node emits a single terminal event (its output, an empty event
152+
# for a None result, a confirmation request, or an error), so recorded
153+
# history with none of the above means it returned None. Fast-forward
154+
# it whether it is static or scheduled dynamically, so the tool's side
155+
# effects do not run again on resume.
156+
should_run = False
157+
elif node.wait_for_output or node.rerun_on_resume:
158+
# Rerun wait_for_output nodes and rerun_on_resume nodes with no prior
159+
# output so they can guide nested children or resume execution.
146160
should_run = True
147161
resume_inputs = recovered.resolved_responses
148162
else:

‎tests/unittests/tools/test_confirmation_utils.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
"""Tests for the shared tool confirmation gate.
15+
"""Tests for the shared tool confirmation helpers.
1616
1717
Verifies that the gate holds back a call that needs confirmation, records the
1818
confirmation request, and lets approved or unguarded calls through.

0 commit comments

Comments
 (0)