Skip to content

Commit 438b88f

Browse files
Merge pull request #31 from OpenRouterTeam/devin/1794512255-approval-parsed-args
fix(approval): evaluate require_approval predicates on schema-parsed arguments
2 parents a5251c4 + 0b0aa7c commit 438b88f

6 files changed

Lines changed: 274 additions & 10 deletions

File tree

‎.github/workflows/publish.yaml‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -108,9 +108,15 @@ jobs:
108108
https://github.com/OpenRouterTeam/typescript-agent.git /tmp/upstream-check
109109
git -C /tmp/upstream-check fetch -q --tags origin
110110
111-
TAG="@openrouter/agent@${VERSION}"
111+
# Downstream-only patch releases: versions upstream never published,
112+
# each mapped to the upstream release its tree is ported from.
113+
case "$VERSION" in
114+
0.8.1) BASE_VERSION="0.8.0" ;;
115+
*) BASE_VERSION="$VERSION" ;;
116+
esac
117+
TAG="@openrouter/agent@${BASE_VERSION}"
112118
if ! git -C /tmp/upstream-check rev-parse -q --verify "refs/tags/$TAG" >/dev/null; then
113-
echo "::error::Upstream has no release tag $TAG. This package's version tracks the ported @openrouter/agent version, so publishing $VERSION means upstream released it. Wait for the upstream release, or correct the version."
119+
echo "::error::Upstream has no release tag $TAG. This package's version tracks the ported @openrouter/agent version, so publishing $VERSION means upstream released $BASE_VERSION. Wait for the upstream release, or correct the version."
114120
exit 1
115121
fi
116122

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ name = "openrouter-agent-sdk"
88
# says plainly which upstream version it is a port of. The verifier enforces the
99
# match against upstream's package.json during a sync. See the Package Version
1010
# section of .upstreamer/upstreamer.md.
11-
version = "0.8.0"
11+
version = "0.8.1"
1212
description = "Python port of @openrouter/agent: OpenRouter tool orchestration, streaming, state, and format compatibility."
1313
readme = "README.md"
1414
requires-python = ">=3.10"

‎src/openrouter_agent/conversation_state.py‎

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,11 @@
55
import time
66
import uuid
77
from dataclasses import replace
8-
from typing import Any, Dict, List, Mapping, Optional, Sequence
8+
from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple
99

10-
from ._utils import dump, json_dumps, maybe_await
10+
from pydantic import BaseModel
11+
12+
from ._utils import dump, json_dumps, maybe_await, validate_schema
1113
from .tool_types import (
1214
ConversationState,
1315
ParsedToolCall,
@@ -189,14 +191,29 @@ def append_to_messages(current: Any, new_items: Sequence[Any]) -> List[Any]:
189191
return [*normalize_input_to_array(current), *list(new_items)]
190192

191193

194+
def _parse_tool_arguments(tool: Tool, arguments: Any) -> Tuple[bool, Any]:
195+
"""Parse arguments with the schema `execute` validates through, so approval
196+
predicates and `execute` see the same defaults and coercions."""
197+
if isinstance(arguments, str):
198+
return False, arguments
199+
try:
200+
parsed = validate_schema(get_tool_function(tool).get("input_schema"), arguments)
201+
except Exception:
202+
return False, arguments
203+
if isinstance(parsed, BaseModel):
204+
parsed = parsed.model_dump()
205+
return True, parsed
206+
207+
192208
async def tool_requires_approval(
193209
tool_call: ParsedToolCall,
194210
tools: Sequence[Tool],
195211
context: Mapping[str, Any],
196212
call_level_check: Any = None,
197213
) -> bool:
198-
if call_level_check is not None:
199-
return bool(await maybe_await(call_level_check(tool_call, context)))
214+
"""Call-level checks get a copy of the call with parsed arguments when parsing
215+
succeeds. Tool-level predicates get the parsed arguments; invalid or
216+
non-mapping arguments fail closed (require approval)."""
200217
matching = next(
201218
(
202219
candidate
@@ -205,11 +222,21 @@ async def tool_requires_approval(
205222
),
206223
None,
207224
)
225+
if call_level_check is not None:
226+
if matching is None:
227+
return bool(await maybe_await(call_level_check(tool_call, context)))
228+
ok, parsed = _parse_tool_arguments(matching, tool_call.arguments)
229+
if not ok:
230+
return bool(await maybe_await(call_level_check(tool_call, context)))
231+
return bool(await maybe_await(call_level_check(replace(tool_call, arguments=parsed), context)))
208232
if not matching:
209233
return False
210234
requirement = get_tool_function(matching).get("require_approval")
211235
if callable(requirement):
212-
return bool(await maybe_await(requirement(tool_call.arguments, context)))
236+
ok, parsed = _parse_tool_arguments(matching, tool_call.arguments)
237+
if not ok or not isinstance(parsed, Mapping):
238+
return True
239+
return bool(await maybe_await(requirement(parsed, context)))
213240
return bool(requirement)
214241

215242

Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,225 @@
1+
"""Approval predicates see the same schema-parsed arguments `execute` gets,
2+
and schema-invalid arguments fail closed. Subset of upstream
3+
`tests/unit/approval-gate-regressions.test.ts`.
4+
"""
5+
6+
from __future__ import annotations
7+
8+
import dataclasses
9+
from typing import Any, Dict, List, Tuple
10+
11+
import pytest
12+
from pydantic import BaseModel, field_validator
13+
14+
from openrouter_agent import tool
15+
from openrouter_agent.conversation_state import tool_requires_approval
16+
from openrouter_agent.tool_executor import execute_regular_tool
17+
from openrouter_agent.tool_types import ParsedToolCall, Tool
18+
19+
CONTEXT: Dict[str, Any] = {"number_of_turns": 1}
20+
21+
22+
class Recorder:
23+
"""Counts invocations and records arguments; returns a fixed value.
24+
25+
A class (not `lambda: calls.append(...) or value`) so the return value is
26+
explicit and mypy-clean -- see tests/unit/test_tool_execution_once.py.
27+
"""
28+
29+
def __init__(self, value: Any = None) -> None:
30+
self.value = value
31+
self.calls: List[Tuple[Any, ...]] = []
32+
33+
def __call__(self, *args: Any) -> Any:
34+
self.calls.append(args)
35+
return self.value
36+
37+
@property
38+
def count(self) -> int:
39+
return len(self.calls)
40+
41+
42+
def _dumped_first_args(recorder: Recorder) -> List[Any]:
43+
return [call[0].model_dump() if isinstance(call[0], BaseModel) else call[0] for call in recorder.calls]
44+
45+
46+
# ---------------------------------------------------------------------------
47+
# Bug 1: the approval predicate must see the SAME arguments `execute` gets.
48+
# ---------------------------------------------------------------------------
49+
50+
51+
class DangerousDefaultArgs(BaseModel):
52+
dangerous: bool = True
53+
54+
55+
class AmountArgs(BaseModel):
56+
amount: int
57+
58+
59+
class DestructiveDefaultArgs(BaseModel):
60+
destructive: bool = True
61+
62+
63+
class TargetArgs(BaseModel):
64+
target: str
65+
66+
67+
class OkOutput(BaseModel):
68+
ok: bool
69+
70+
71+
async def test_applies_input_schema_defaults_before_function_require_approval() -> None:
72+
predicate = Recorder()
73+
74+
def require(params: Any, ctx: Any) -> bool:
75+
predicate(params, ctx)
76+
return params["dangerous"] is True
77+
78+
conditional = tool(
79+
name="conditional_action",
80+
input_schema=DangerousDefaultArgs,
81+
require_approval=require,
82+
execute=lambda params, ctx: {},
83+
)
84+
85+
# The model emitted `{}`; the schema default makes `dangerous` True by the
86+
# time execute runs, so the predicate must see it True too.
87+
requires = await tool_requires_approval(
88+
ParsedToolCall(id="1", name="conditional_action", arguments={}), [conditional], CONTEXT
89+
)
90+
91+
# Pydantic models are model_dump()'d for the predicate (conversation_state.py
92+
# _parse_tool_arguments): the predicate contract is a mapping, as upstream.
93+
assert [call[0] for call in predicate.calls] == [{"dangerous": True}]
94+
assert requires is True
95+
96+
97+
async def test_applies_input_schema_coercions_before_function_require_approval() -> None:
98+
predicate = Recorder()
99+
100+
def require(params: Any, ctx: Any) -> bool:
101+
predicate(params, ctx)
102+
return bool(params["amount"] > 100)
103+
104+
transfer = tool(
105+
name="transfer",
106+
input_schema=AmountArgs,
107+
require_approval=require,
108+
execute=lambda params, ctx: {},
109+
)
110+
111+
# String amount is coerced (Pydantic lax mode stands in for z.coerce), so
112+
# the comparison is numeric, not lexicographic.
113+
requires = await tool_requires_approval(
114+
ParsedToolCall(id="2", name="transfer", arguments={"amount": "500"}), [transfer], CONTEXT
115+
)
116+
117+
assert [call[0] for call in predicate.calls] == [{"amount": 500}]
118+
assert requires is True
119+
120+
121+
async def test_applies_schema_defaults_for_call_level_checks_without_mutating_call() -> None:
122+
defaulted = tool(
123+
name="call_level_defaulted_action",
124+
input_schema=DestructiveDefaultArgs,
125+
execute=lambda params, ctx: {},
126+
)
127+
tool_call = ParsedToolCall(id="call-level-default", name="call_level_defaulted_action", arguments={})
128+
call_level_check = Recorder(True)
129+
130+
requires = await tool_requires_approval(tool_call, [defaulted], CONTEXT, call_level_check)
131+
132+
assert call_level_check.calls == [(dataclasses.replace(tool_call, arguments={"destructive": True}), CONTEXT)]
133+
assert tool_call.arguments == {}
134+
assert requires is True
135+
136+
137+
@pytest.mark.parametrize("decision", [False, True])
138+
async def test_honors_call_level_check_when_arguments_fail_schema_validation(decision: bool) -> None:
139+
strict = tool(name="call_level_invalid_action", input_schema=TargetArgs, execute=lambda params, ctx: {})
140+
invalid_call = ParsedToolCall(id=f"call-level-invalid-{decision}", name="call_level_invalid_action", arguments={})
141+
call_level_check = Recorder(decision)
142+
143+
assert await tool_requires_approval(invalid_call, [strict], CONTEXT, call_level_check) is decision
144+
# Parsing failed, so the call-level check receives the raw call.
145+
assert call_level_check.calls == [(invalid_call, CONTEXT)]
146+
147+
148+
async def test_parses_original_wire_arguments_once_for_predicate_and_once_for_execution() -> None:
149+
transform_calls = {"n": 0}
150+
151+
class TransformedArgs(BaseModel):
152+
value: str
153+
154+
@field_validator("value")
155+
@classmethod
156+
def _suffix(cls, value: str) -> str:
157+
transform_calls["n"] += 1
158+
return f"{value}:{transform_calls['n']}"
159+
160+
predicate = Recorder(False)
161+
execute = Recorder({})
162+
transformed = tool(
163+
name="transformed_action",
164+
input_schema=TransformedArgs,
165+
require_approval=predicate,
166+
execute=execute,
167+
)
168+
tool_call = ParsedToolCall(id="non-idempotent-transform", name="transformed_action", arguments={"value": "wire"})
169+
170+
assert await tool_requires_approval(tool_call, [transformed], CONTEXT) is False
171+
await execute_regular_tool(transformed, tool_call, CONTEXT)
172+
173+
assert predicate.calls == [({"value": "wire:1"}, CONTEXT)]
174+
assert _dumped_first_args(execute) == [{"value": "wire:2"}]
175+
assert transform_calls["n"] == 2
176+
assert tool_call.arguments == {"value": "wire"}
177+
178+
179+
async def test_fails_closed_when_arguments_fail_schema_validation() -> None:
180+
predicate = Recorder(False)
181+
strict = tool(name="strict_action", input_schema=TargetArgs, require_approval=predicate, execute=lambda p, c: {})
182+
183+
requires = await tool_requires_approval(
184+
ParsedToolCall(id="3", name="strict_action", arguments={}), [strict], CONTEXT
185+
)
186+
187+
assert requires is True
188+
assert predicate.count == 0
189+
190+
191+
async def test_still_fails_closed_when_schema_parses_to_non_object_value() -> None:
192+
predicate = Recorder(False)
193+
weird = tool(name="weird_action", input_schema=TargetArgs, require_approval=predicate, execute=lambda p, c: {})
194+
# Mirrors upstream swapping in a schema whose parse succeeds with a
195+
# non-record payload: a callable schema is honored by validate_schema.
196+
weird["function"]["input_schema"] = lambda value: ["not", "a", "record"]
197+
198+
requires = await tool_requires_approval(
199+
ParsedToolCall(id="4", name="weird_action", arguments={"target": "x"}), [weird], CONTEXT
200+
)
201+
202+
assert requires is True
203+
assert predicate.count == 0
204+
205+
206+
async def test_still_fails_closed_on_schema_invalid_arguments_for_manual_tools() -> None:
207+
predicate = Recorder(False)
208+
# A manual tool: no execute / on_tool_called. The host runs it as-is, so a
209+
# malformed call must not be waved past the gate.
210+
manual_tool: Tool = {
211+
"type": "function",
212+
"function": {"name": "manual_action", "input_schema": TargetArgs, "require_approval": predicate},
213+
}
214+
215+
requires = await tool_requires_approval(
216+
ParsedToolCall(id="5", name="manual_action", arguments={}), [manual_tool], CONTEXT
217+
)
218+
219+
assert requires is True
220+
assert predicate.count == 0
221+
222+
223+
# ---------------------------------------------------------------------------
224+
# Approval vs. PreToolUse-mutated arguments.
225+
# ---------------------------------------------------------------------------

‎upstreamer-changelog.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
# openrouter-agent-sdk Changelog
22

3+
## 0.8.1 — approval fix
4+
5+
Downstream-only fix on top of the 0.8.0 port; no new upstream work.
6+
7+
- **Security:** callable `require_approval` predicates and call-level approval checks now see the arguments after `input_schema` parsing (coercions and defaults applied), the same values `execute` receives. Arguments that fail parsing require approval. Before this, a value such as the string `"true"` could pass a strict predicate and then run as boolean `True`.
8+
39
## 0.8.0 — first PyPI release
410

511
First published release. The version is `0.8.0`, not `0.0.1`, because this

‎uv.lock‎

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)