Skip to content

Commit c9cb5ff

Browse files
port: sync with @openrouter/agent upstream
1 parent d52c22c commit c9cb5ff

35 files changed

Lines changed: 3589 additions & 371 deletions

‎.upstreamer/eval-report.md‎

Lines changed: 383 additions & 267 deletions
Large diffs are not rendered by default.

‎README.md‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,12 +115,14 @@ analysis = tool(
115115
)
116116
```
117117

118-
Manual tools are advertised to the model but not auto-executed.
118+
Manual tools are advertised to the model but not auto-executed. A manual tool may pass `wire_input_schema=` to send its own JSON Schema to the model instead of one generated from `input_schema`.
119119

120120
```python
121121
confirm = tool(name="confirm_action", input_schema=ConfirmInput, execute=False)
122122
```
123123

124+
Any client tool accepts `strict=True` / `strict=False` to request provider-enforced schema adherence on tool-call arguments; it is sent on the wire tool definition (omitted means `null`, the provider default). Pass `active_tools=[...names]` to `call_model` to send and execute only a subset of `tools` (server tools are always kept).
125+
124126
HITL tools use `on_tool_called`; returning a value auto-resolves, returning `None` pauses with pending tool calls in state.
125127

126128
```python
@@ -144,6 +146,8 @@ web = server_tool({"type": "web_search_2025_08_26", "max_results": 5})
144146

145147
Use `require_approval` on a tool or `require_approval` on the request to pause sensitive calls before execution. Approval resume requires a state accessor with async `load()` and `save()` methods.
146148

149+
Resume with `approve_tool_calls` / `reject_tool_calls`. Duplicate IDs are ignored (each approved call runs once), and an ID in both lists raises before anything runs. A paused conversation stays paused until every pending call has a decision: resuming without decisions (or with decisions for only some calls) sends no model request, and `get_response()`, `get_text()`, `get_tool_calls()` and the stream getters raise an error naming the pause and the pending call IDs, while `requires_approval()`, `get_pending_tool_calls()` and `get_state()` keep working. An `awaiting_hitl` conversation also resumes when `input` carries a `function_call_output` for a pending call.
150+
147151
Manual tools (`execute=False`, no `on_tool_called`) pause the loop with status `"awaiting_client_tools"` when the model calls them, instead of silently dropping the call. Read the unresolved calls via `get_pending_tool_calls()` / `get_state()`, execute them yourself, and continue by calling `call_model` again with `function_call_output` items in `input`.
148152

149153
For durable cross-process storage, serialize state with `serialize_conversation_state` / `deserialize_conversation_state` rather than storing raw dataclass fields. The wire format is versioned (`CONVERSATION_STATE_VERSION`); a version mismatch raises `UnsupportedStateVersionError` and malformed JSON raises `InvalidStateError`, so a store can never silently misinterpret a future shape.
@@ -163,6 +167,10 @@ result = call_model(
163167
)
164168
```
165169

170+
## Usage
171+
172+
`get_response()` returns the *final* round's response, so its `usage` covers one generation. `await result.get_usage()` returns totals across every model call the run made (`model_calls`, `input_tokens`, `output_tokens`, `total_tokens`, `cached_tokens`, `reasoning_tokens`, and `cost` when reported). It waits for the run and never raises: a failed or paused run returns what was accrued so far.
173+
166174
## Lifecycle Hooks
167175

168176
Pass a `HooksManager` (or an inline `{hook_name: [HookEntry(...)]}` dict of built-in hooks) via `hooks=` to observe or intervene in a run: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `UserPromptSubmit`, `Stop`, `PermissionRequest`, `SessionStart`, `SessionEnd`, and `PostModelCall`. Handlers receive a validated payload dict and a `LifecycleHookContext` (`session_id`, `hook_name`, `cancel_event`).
@@ -189,6 +197,8 @@ The built-ins mirror the TypeScript package and OR together when provided as a l
189197
- `max_cost(dollars)`
190198
- `finish_reason_is(reason)`
191199

200+
A forced `tool_choice` (`"required"`, a specific tool, or `allowed_tools` with `mode: "required"`) is relaxed to `"auto"` once it has produced a tool call in a run (including across approval and client-tool resumes), so the model can answer in text instead of calling tools until the step budget runs out. A tool's `next_turn_params` may set `tool_choice` for the next turn (for example, to widen an `allowed_tools` set without touching `tools`); `next_turn_params` only runs for calls whose tool body ran and returned without error. A response truncated at `max_output_tokens` executes none of its tool calls; the run ends with that `incomplete` response.
201+
192202
When a stop condition fires while the model is still emitting tool calls, `call_model` makes one more turn with `tool_choice="none"` by default (tools stay in the request so the prompt-cache prefix survives) so the run ends with a natural-language answer. `allow_final_response` tunes this: `True` or omitted appends `DEFAULT_FINAL_RESPONSE_DIRECTIVE` as a user message, a non-empty string replaces the wording, `""` appends nothing, and `False` disables the extra turn entirely.
193203

194204
## Format Compatibility

‎src/openrouter_agent/call_model.py‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,46 @@
55
from .hooks_resolve import resolve_hooks
66
from .model_result import ModelResult
77
from .tool_executor import convert_tools_to_api_format
8+
from .tool_types import get_tool_function, is_server_tool
9+
10+
11+
#: Upstream `callModel` options whose features this port does not implement
12+
#: yet. Refused instead of being forwarded to the Responses API, where they
13+
#: would be sent as unknown request fields or silently ignored.
14+
UNSUPPORTED_CALL_MODEL_OPTIONS = (
15+
"doom_loop",
16+
"signal",
17+
"tool_timeout_ms",
18+
"tool_concurrency",
19+
"async_tools",
20+
"stream_replay",
21+
)
822

923

1024
def call_model(client: Any, request: Mapping[str, Any], options: Optional[Mapping[str, Any]] = None) -> ModelResult:
25+
unsupported = [key for key in UNSUPPORTED_CALL_MODEL_OPTIONS if request.get(key) is not None]
26+
if unsupported:
27+
raise NotImplementedError(
28+
f"call_model option(s) not supported by this Python port yet: {', '.join(unsupported)}"
29+
)
1130
tools = request.get("tools")
31+
# Narrow tools to the active subset (if provided) before API conversion and
32+
# before they are registered for execution, so the model cannot call
33+
# filtered tools and the executor does not carry orphaned definitions.
34+
# Server tools are always kept.
35+
active_tools = request.get("active_tools")
36+
if active_tools is not None and tools is not None:
37+
active_set = set(active_tools)
38+
tools = [t for t in tools if is_server_tool(t) or get_tool_function(t).get("name") in active_set]
39+
# A filtered-to-empty (or explicitly empty) tools list omits the outbound
40+
# `tools` key entirely instead of sending `tools: []`, which several
41+
# providers reject; the engine treats it as its no-tools state.
42+
if tools is not None and len(tools) == 0:
43+
tools = None
1244
final_request = dict(request)
1345
for key in (
1446
"tools",
47+
"active_tools",
1548
"stop_when",
1649
"state",
1750
"require_approval",

‎src/openrouter_agent/chat_compat.py‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,30 @@ def from_chat_messages(messages: Sequence[Mapping[str, Any]]) -> List[Dict[str,
2727
"output": _content_to_string(msg.get("content")),
2828
}
2929
)
30+
elif role == "assistant":
31+
content = _content_to_string(msg.get("content"))
32+
tool_calls = msg.get("tool_calls") or msg.get("toolCalls") or []
33+
# Skip the message item only when there is no content AND there are
34+
# tool calls to emit in its place. A content-less assistant message
35+
# with no tool calls still round-trips as an empty message.
36+
if content or not tool_calls:
37+
output.append({"type": "message", "role": role, "content": content})
38+
# One function_call item per tool call. The chat format's
39+
# `function.arguments` is already a JSON string, so it is
40+
# forwarded as-is.
41+
for call in tool_calls:
42+
function = get_field(call, "function", {}) or {}
43+
call_id = get_field(call, "id")
44+
output.append(
45+
{
46+
"type": "function_call",
47+
"callId": call_id,
48+
"id": call_id,
49+
"name": get_field(function, "name"),
50+
"arguments": get_field(function, "arguments"),
51+
"status": "completed",
52+
}
53+
)
3054
else:
3155
output.append({"type": "message", "role": role, "content": _content_to_string(msg.get("content"))})
3256
return output

‎src/openrouter_agent/conversation_state.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,7 @@ def deserialize_conversation_state(raw_json: str) -> ConversationState:
184184
partial_response=partial_response,
185185
interrupted_by=parsed.get("interrupted_by"),
186186
version=CONVERSATION_STATE_VERSION,
187+
consumed_forced_tool_choice_key=parsed.get("consumed_forced_tool_choice_key"),
187188
)
188189

189190

‎src/openrouter_agent/hooks_emit.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,14 @@ async def execute_handler_chain(
6868
behavior = HOOK_BEHAVIOR.get(hook_name)
6969

7070
for index, entry in enumerate(entries):
71+
# Checked before each handler so synchronous chains stop promptly.
7172
if context.cancel_event.is_set():
73+
# A hook that can block (PreToolUse, UserPromptSubmit) fails
74+
# closed: the handlers left unrun may include the guard that
75+
# would have blocked, so an aborted chain must not read as an
76+
# approval.
77+
if behavior and behavior.block_field:
78+
blocked = True
7279
break
7380

7481
gate = _evaluate_entry_gate(entry, current_payload, index, options)

‎src/openrouter_agent/hooks_types.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,9 @@ class EmitResult:
9494
pending: List["asyncio.Task[None]"] = field(default_factory=list)
9595
#: The payload after all mutation piping has been applied.
9696
final_payload: Dict[str, Any] = field(default_factory=dict)
97-
#: True if any handler triggered a block/reject short-circuit.
97+
#: True if any handler triggered a block/reject short-circuit, or if the
98+
#: chain of a blocking hook (PreToolUse, UserPromptSubmit) was aborted
99+
#: before every handler ran.
98100
blocked: bool = False
99101
#: True if any handler's result actually piped a mutation into the payload.
100102
mutated: bool = False

0 commit comments

Comments
 (0)