From c9cb5ffb7b0e16b34ea2f50602edd7fe6b85060d Mon Sep 17 00:00:00 2001 From: "openrouter-port-bot[bot]" <312657780+openrouter-port-bot[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:07:15 +0000 Subject: [PATCH] port: sync with @openrouter/agent upstream --- .upstreamer/eval-report.md | 650 +++++++++++------- README.md | 12 +- src/openrouter_agent/call_model.py | 33 + src/openrouter_agent/chat_compat.py | 24 + src/openrouter_agent/conversation_state.py | 1 + src/openrouter_agent/hooks_emit.py | 7 + src/openrouter_agent/hooks_types.py | 4 +- src/openrouter_agent/model_result.py | 648 ++++++++++++++--- src/openrouter_agent/next_turn_params.py | 20 +- src/openrouter_agent/stream_transformers.py | 35 + src/openrouter_agent/tool.py | 57 +- src/openrouter_agent/tool_context.py | 31 +- src/openrouter_agent/tool_executor.py | 44 +- src/openrouter_agent/tool_types.py | 8 + tests/_fixtures.py | 14 +- tests/unit/test_approval_gate_regressions.py | 507 ++++++++++++++ tests/unit/test_call_model.py | 11 + tests/unit/test_call_model_active_tools.py | 77 +++ tests/unit/test_compat.py | 65 ++ tests/unit/test_duplicate_call_ids.py | 10 +- tests/unit/test_final_response_validation.py | 75 ++ tests/unit/test_get_usage.py | 203 ++++++ tests/unit/test_hooks_contract_fixes.py | 108 +++ tests/unit/test_manual_tool_wire_schema.py | 114 +++ .../unit/test_max_output_tokens_truncation.py | 138 ++++ tests/unit/test_next_turn_params.py | 58 ++ tests/unit/test_next_turn_tool_choice_loop.py | 154 +++++ tests/unit/test_server_tool.py | 65 ++ tests/unit/test_shared_context.py | 97 +++ tests/unit/test_stop_when_before_approval.py | 99 +++ tests/unit/test_to_model_output_parity.py | 147 ++++ tests/unit/test_tool_choice_relaxation.py | 262 +++++++ tests/unit/test_tool_executor_return.py | 127 ++++ tests/unit/test_tool_factory_and_executor.py | 5 +- upstreamer-changelog.md | 50 ++ 35 files changed, 3589 insertions(+), 371 deletions(-) create mode 100644 tests/unit/test_call_model_active_tools.py create mode 100644 tests/unit/test_final_response_validation.py create mode 100644 tests/unit/test_get_usage.py create mode 100644 tests/unit/test_hooks_contract_fixes.py create mode 100644 tests/unit/test_manual_tool_wire_schema.py create mode 100644 tests/unit/test_max_output_tokens_truncation.py create mode 100644 tests/unit/test_next_turn_params.py create mode 100644 tests/unit/test_next_turn_tool_choice_loop.py create mode 100644 tests/unit/test_server_tool.py create mode 100644 tests/unit/test_shared_context.py create mode 100644 tests/unit/test_stop_when_before_approval.py create mode 100644 tests/unit/test_to_model_output_parity.py create mode 100644 tests/unit/test_tool_choice_relaxation.py create mode 100644 tests/unit/test_tool_executor_return.py diff --git a/.upstreamer/eval-report.md b/.upstreamer/eval-report.md index 95e04b6..7e5d0f1 100644 --- a/.upstreamer/eval-report.md +++ b/.upstreamer/eval-report.md @@ -1,267 +1,383 @@ -PASS WITH WARNINGS - -# Port Parity Eval — Python (`@openrouter/agent` 0.7.2 → 0.8.0), second pass - -Fresh re-review against upstream commit `680bceb4598f228d3e2ec58e2416e4335cdff059`, -delta baseline `adc7939f4b7ed85b1a060d13433b8be6063cff73`, scoped to `packages/agent/`. -This is a second-pass review after a prior FAIL with three findings. All three -are verified fixed below by reading the code directly (not by trusting the -converter's summary), and a broader sweep of the rest of the delta and the -eval's Required Qualities turned up no new material gap — only pre-existing, -cosmetic items. - -## Verdict rationale - -All three prior findings are genuinely fixed, confirmed by tracing execution -and by breaking the fix and watching the test fail. No required public API -symbol is missing, no load-bearing loop / state / approval-ordering / hooks -behavior regressed, and the declared version (`0.8.0`) matches what's -actually ported. Remaining items are documentation/coverage gaps that don't -change behavior — hence WARNINGS, not FAIL. - -## Finding 1 (prior FAIL #1) — Stop hook `force_resume` zero-cost retry: FIXED, verified - -`src/openrouter_agent/model_result.py:677-694`, inside `_run()`: - -```python -while stop_conditions and await is_stop_condition_met(stop_conditions, self._steps): - stop_decision = await self._run_stop_hook(force_resume_count, current_request) - if stop_decision == "resume": - force_resume_count += 1 - continue - session_end_reason = "max_turns" - stopped_by_stop_when = True - break -``` - -- `is_stop_condition_met` (`stop_conditions.py`) is a pure function over - `self._steps` (already-collected `StepResult`s) — it does not call `_send` - or `_send_and_track`. The `continue` re-enters the `while` and re-evaluates - this pure check against the *same* steps; no request is sent on the - "resume" path. This is a faithful match of upstream's - `model-result.ts:3050-3068` (`shouldStopExecution()` / `runStopHook()` / - `continue`), confirmed by reading both side by side. -- `tests/unit/test_model_result_hooks.py::test_stop_hook_force_resume_is_a_zero_cost_retry_no_extra_model_request` - genuinely pins this: the mock `QueuedResponses` has exactly one queued - response, and asserts `len(client.beta.responses.requests) == 1` after a - run in which the Stop hook is invoked twice (once forcing resume, once - not). If the "resume" branch sent a real request, the mock's second - `pop(0)` would raise `IndexError` on the empty list. -- I verified this is a real regression guard, not an accidental pass: I - temporarily replaced the `continue` branch with a version that calls - `await self._send_and_track(...)` (simulating the old bug), reran the test, - and both `test_stop_hook_force_resume_is_a_zero_cost_retry_no_extra_model_request` - and `test_stop_hook_force_resume_then_falls_through_to_normal_tool_round` - failed immediately with `IndexError: pop from empty list`. Reverted - afterward; `git diff --stat` confirms the file is back to its pre-sabotage - state and the tests pass again. -- Minor cosmetic nit: the second test's docstring says the halted round's - tool calls "execute via the normal round path (not the final-directive - coercion)" — tracing the code, they actually go through the *same* - final-directive-coercion branch (`stopped_by_stop_when` → `resolvable_pending` - execute → `tool_choice: "none"` follow-up), which is also what upstream does - (`model-result.ts:3205+`). The assertions themselves (text output, request - count) are correct; only the prose comment is a little misleading. Not a - behavioral gap. - -## Finding 2 (prior FAIL #2) — MCP tool-branding surface: FIXED, verified - -- `tool.py:57-64` — `mark_mcp()` returns `{**tool_to_mark, "_mcp": True}`, a - new dict; the underlying `"function"` value is not copied (shallow), same - as upstream's `{...toolToMark, _mcp: true}`. Confirmed non-mutating via - `tests/unit/test_mcp_tool_branding.py::test_mark_mcp_is_non_mutating_and_is_mcp_tool_detects_the_brand` - (`base is not branded`, `branded["function"] is base["function"]`). -- `tool_types.py:264-270` — `McpBranded` alias and `is_mcp_tool()` structural - check (`tool.get("_mcp") is True`), matching upstream's `isMcpTool`. -- `tool_executor.py` — `source = "mcp" if is_mcp_tool(tool) else "client"` is - computed and threaded through all three execute paths - (`execute_regular_tool`, `execute_generator_tool`, `execute_hitl_tool`, - lines 62/86/151) and returned in every result dict (success and error - branches). -- `model_result.py:825, 852` — the `tool.result` / `tool_result` stream event - carries `"source"`, preferring the executor-computed `result.get("source", ...)` - and falling back to `is_mcp_tool(tool)` for the parse-error path where no - executor result exists. -- `test_mcp_tool_branding.py::test_mcp_branded_tool_result_carries_source_mcp_in_tool_result_event` - and `test_regular_client_tool_result_carries_source_client` both drive - `call_model(...)` end-to-end through a mocked Responses API and assert - `source` on the actual `tool_result` event from `get_tool_stream()` — this - is genuine parity coverage, not a unit-level stub check. - -## Finding 3 (prior FAIL #3) — Over-exported hook internals: FIXED, verified - -- `src/openrouter_agent/__init__.py` — grepped the import block and `__all__`: - `BUILT_IN_HOOKS`, `BUILT_IN_HOOK_NAMES`, `matches_tool`, `resolve_hooks`, - `execute_handler_chain` appear nowhere in either. -- No wildcard (`import *`) re-export exists anywhere in `__init__.py` that - could smuggle these back in. `resolve_hooks` is used internally by - `call_model.py` via `from .hooks_resolve import resolve_hooks` but is never - re-exported from the package `__init__`. -- `.upstreamer/scripts/verify.sh`'s `REQUIRED_SYMBOLS` list was inspected — - it does not reference any of the five removed names, so the mechanical - verifier's required-symbol check is unaffected by the removal. -- This matches upstream's own `index.ts`, which explicitly documents (in a - code comment added in this exact delta) that `matchesTool`, `resolveHooks`, - `BUILT_IN_HOOKS`, and raw schema objects are deliberately not exported. - -## Finding 4 (prior FAIL #4) — Thin hook test coverage: FIXED, verified - -Read all four new tests in `tests/unit/test_model_result_hooks.py` in full: - -- `test_user_prompt_submit_can_reject_a_string_prompt` — asserts the raised - `ValueError` message and, critically, `len(client.beta.responses.requests) == 0`, - proving the model was never called after rejection (not just that an - exception was raised somewhere). -- `test_user_prompt_submit_can_mutate_a_string_prompt` — asserts the - *actually-sent* request's `input[0]["content"]` contains the mutated text, - reading `client.beta.responses.requests[0]`, i.e., proving the mutation - reached the wire request, not just the hook's return value. -- `test_user_prompt_submit_mutates_last_user_message_in_array_input` — same, - for array-shaped `input`, asserting `sent_input[-1]["content"]`. -- `test_pre_tool_use_mutated_input_actually_reaches_tool_execute` — the tool's - `execute` callback records its received `params` into a list; the test - asserts the *tool implementation actually observed* the hook's - `mutated_input`. I traced the plumbing: `HookEntry` mutation config - (`hooks_types.py:117`, `mutations={"mutated_input": "tool_input"}`) maps the - hook's `mutated_input` return key onto `final_payload["tool_input"]`, which - `model_result.py:492-493` reads via `pre.final_payload.get("tool_input")` - and substitutes into `effective_call.arguments` before `execute_tool()` is - called. This is a genuine end-to-end proof, not an API-surface check. - -All four exercise actual behavior with concrete, falsifiable assertions -(request contents, request counts, executed-tool arguments) — not "call and -check nothing crashed." - -## Full battery re-run - -- `bash .upstreamer/scripts/verify.sh` → `PASS: 0 failures` (uv sync, ruff - check, ruff format, mypy, pytest tests/unit, all 31 required public-API - symbols present, version `0.8.0` matches upstream `package.json`, no - leaked TS artifacts, all repo-owned files present). -- `uv run pytest tests/unit tests/e2e -q` → `102 passed` (e2e tests skip - cleanly without `OPENROUTER_API_KEY`, per contract). - -## Broader sweep beyond the four claimed fixes - -Re-read the full upstream delta file list -(`git -C tmp/upstreamer/upstream diff --name-status adc7939..680bceb -- packages/agent/`) -and spot-checked every source file not already covered above: - -- **`conversation-state.ts` (versioned serialization, upstream #66)** — fully - present and correct in `conversation_state.py`: `CONVERSATION_STATE_VERSION`, - `InvalidStateError`, `UnsupportedStateVersionError`, - `serialize_conversation_state` / `deserialize_conversation_state` with the - same version-check-before-structural-validation ordering, same required - fields (`id`, `messages`, `status`), same "absence of `version` means v1" - policy. Covered by `tests/unit/test_conversation_state_serialization.py`. -- **`call-model.ts` / `async-params.ts`** — `strict_final_response` and - `hooks` (via `resolve_hooks`) are both threaded through `call_model.py` and - `async_params.py`'s reserved-key list, matching upstream's added fields. -- **`tool.ts` / `tool-types.ts` (the other ~85% of their diffs)** — almost - entirely TypeScript generic-variance engineering (`TContext` → `TCtx` / - `ContextFromSchema`, `bivarianceHack` method-syntax tricks so concretely - typed tools stay assignable to the wide `Tool` union). Zero runtime - behavior attached; correctly not chased in Python per Idiomatic Divergence - #4 ("Typing is looser... do not contort the runtime to chase a type-level - feature"). -- **`reusable-stream.ts`** — adds a `get isComplete()` getter. Not part of - the Required Public API list and not load-bearing (it's a cache-hit - optimization signal); not found ported 1:1 in `reusable_stream.py`, but - this is pre-existing from before this delta's scope and cosmetic (no - behavioral test depends on it upstream either). -- **`tool-orchestrator.ts` (`executeToolLoop`)** — upstream added a `source` - field here too, but this function is dead code in upstream itself: it is - not exported from `index.ts` and not imported by any other upstream - source file (only mentioned in a code *comment* in one test). The port's - `tool_orchestrator.py` has always been (since the original 0.7.2 port, not - this delta) a thin re-export shim (`ModelResult`, `execute_tool`, - `partition_tool_calls`) rather than a translation of `executeToolLoop`, so - there's no `source`-field gap to fix — the shim never had the field to - begin with, and the real tool-execution path (`model_result.py` + - `tool_executor.py`) does have `source` correctly threaded (see Finding 2). - Not a new gap; pre-existing and inconsequential since the dead code isn't - reachable either upstream or downstream. -- **Hooks system files** (`hooks-emit.ts`, `hooks-manager.ts`, - `hooks-matchers.ts`, `hooks-resolve.ts`, `hooks-schemas.ts`, - `hooks-types.ts`) — all six have Python counterparts - (`hooks_emit.py`, `hooks_manager.py`, `hooks_matchers.py`, - `hooks_resolve.py`, `hooks_schemas.py`, `hooks_types.py`). Spot-checked - `hooks_matchers.py` against `hooks-matchers.ts` line by line: `None`/wildcard, - exact string, compiled regex, and predicate-callable branches all match - (Python's `re.Pattern` has no `lastIndex`-style statefulness, so the - upstream comment about resetting `RegExp.lastIndex` has no Python - equivalent bug to guard against — correctly omitted, not a gap). - Session-id-per-emit threading (`hooks_manager.py:51-60`) is present and - tested (`test_hooks_manager.py::test_session_id_threads_per_emit_for_shared_manager`). -- **SessionEnd/drain on no-tools error paths** — behaviorally verified via a - throwaway script: a transport that raises on `send_async` for a *no-tools* - `call_model` still fires `SessionStart` then `SessionEnd` with - `reason: "error"` before the exception propagates (the `try/except/finally` - wrapping the entire `_run()` body guarantees this uniformly for tool and - no-tool paths alike). This is correct but has no dedicated committed test - pinning it — a pre-existing coverage gap, not a regression from this delta. -- **"Tool executes exactly once per round" regression** (upstream's - `tool-execution-once.test.ts`, guarding against a historical bug where - `handleApprovalCheck` pre-executed auto-approve tools and the main loop - re-executed them) — verified behaviorally via a throwaway script with a - mixed auto-tool + approval-gated-tool round and a `PermissionRequest` - `"allow"` decision: each tool's `execute` fired exactly once. Correct, but - there's no dedicated Python test file pinning this specific historical - regression by name — again a coverage gap, not a behavioral gap. -- **Approval/HITL resume ordering** (`function_call` before - `function_call_output`) — already covered by pre-existing - `test_parity_requirements.py::test_approval_pause_persists_tool_call_turn_and_resume_orders_output_after_call` - and `test_hitl_pause_persists_tool_call_turn_and_resume_orders_output_after_call`, - and by the new `test_manual_tool_pending_state.py::test_mixed_auto_and_manual_round_persists_auto_output_and_pauses_manual` - for the specific "auto output recorded before the pause" mixed-round case - this delta's contract calls out. No regression found. - -## Documentation gap (new finding, cosmetic) - -`upstreamer-changelog.md` was not updated for this 0.7.2 → 0.8.0 sync. It -still reads "Latest Sync ... against the current `@openrouter/agent` 0.7.2 -surface" and has no entry for the hooks system (upstream #7/#67, explicitly -called "the 0.8.0 headline" in the contract), MCP tool branding, versioned -conversation-state serialization (upstream #66), the `allow_final_response` -default-on `tool_choice: "none"` behavior change (upstream #68), or -`awaiting_client_tools` (upstream #64) — all of which *are* correctly -reflected in `README.md` (diff confirms new "Lifecycle Hooks" section, -updated Stop Conditions section, and a new manual-tools paragraph). The -contract's Output Shape section lists `upstreamer-changelog.md` alongside -`README.md` as this repo's own product surface / user-facing port notes; -leaving it stale after a headline feature release is a real (if purely -documentation-level) gap. Does not affect behavior, the public API, or any -Required Quality in eval.md — hence a warning, not a blocker. - -## Idiomatic Divergences section check - -The Stop-hook zero-cost-retry semantics are not a divergence — the port now -matches upstream's exact `runStopHook`/`shouldStopExecution` loop structure -(see Finding 1), so nothing needs to be added to -`.upstreamer/upstreamer.md`'s Idiomatic Divergences section for it. No other -undocumented divergence was found in this sweep; the existing six divergences -(Pydantic v2, async-first, generator tools, looser typing, Python-native -cancellation, structural protocols for `BeforeCreateRequestContext`) still -accurately describe the only permanent deltas from upstream. - -## Summary - -- Public API completeness: PASS (31/31 required symbols, plus the full - hooks/MCP-branding/versioned-state surface added in this delta). -- Version honesty: PASS (`0.8.0` == upstream `package.json` at target commit). -- Load-bearing loop: PASS, including the fixed Stop-hook zero-cost retry. -- Streaming / State / Approval-HITL ordering / Hooks / Compatibility helpers: - PASS, no regressions found beyond the four already-fixed items. -- Repo-owned files: PASS (LICENSE, README.md, pyproject.toml, scripts/upstream - all present and not clobbered). -- Warnings: `upstreamer-changelog.md` stale (documentation only); a few - historical-regression behaviors (SessionEnd-on-error, exactly-once tool - execution) are behaviorally correct but lack dedicated pinning tests; one - test docstring (`test_stop_hook_force_resume_then_falls_through_to_normal_tool_round`) - slightly mischaracterizes which code path runs, though its assertions are - correct; `reusable_stream.py` lacks upstream's new `is_complete` property - (non-load-bearing). - -**Verdict: PASS WITH WARNINGS.** All three prior FAIL findings are -substantively and verifiably fixed — not just superficially patched. The -remaining items are documentation or coverage nits with no behavioral impact. +FAIL + +# Port Parity Eval: `@openrouter/agent` 0.8.0 → 1.3.0 (680bceb → 0fe4cb1) + +Reviewer: an independent fresh-context re-grade, following `.upstreamer/eval.md` and the contract in `.upstreamer/upstreamer.md`. It re-checks the tree after the converter's first fix attempt for the defects the previous eval listed. + +Under review: the uncommitted working tree. +- 13 `src/` files are modified, 14 test files are new, and 6 test-side files are modified (4 unit test files plus `tests/_fixtures.py`). +- `pyproject.toml` still has `version = "0.8.2"`. +- `state.yaml` still points at `680bceb`. + +Line references are to the current working tree. + +## 1. Verdict rationale + +**FAIL** (unchanged from the previous eval). Each of the following is a FAIL condition under `eval.md` on its own. + +1. **The version claim cannot be made honest.** + - The target `0fe4cb1` is tagged `@openrouter/agent@1.3.0`, so the verifier wants `version = 1.3.0`. + - The port only reflects a subset of the 0.9.0–1.3.0 patch fixes. These are missing: + - the headline 0.9.0 features: #90 async/unified `run()` tools and #73/#89 doom-loop; + - the 0.10.0 tool-set (#31); + - the 0.11.0 replay compaction (#109); + - run-level `signal`; + - the MCP subpath. + - Claiming 1.3.0 would overstate the port by three minor versions, and claiming even 0.9.0 would also overstate it. + - The earliest delta commit (`78c562e`, doom-loop #73) is not ported. So no upstream commit after 680bceb is fully covered, and `state.yaml` cannot truthfully move forward. + - The verifier still fails on version drift: `pyproject.toml=0.8.2, upstream @openrouter/agent=1.3.0`. +2. **The approval ordering still differs from upstream's two-phase gate (#94, shipped in 0.11.0, inside this delta). D1 is not fixed.** + - On a fresh run the port runs `PreToolUse` before approval classification for every call, including calls it then holds for a human (`model_result.py:780-816`, called from `_resolve_approval_gate` :825). + - The predicate and `PermissionRequest` see the mutated arguments. + - The pending call is persisted with the mutated arguments and `pre_tool_use_applied=True`. + - The D2/D3 fixes only take effect on pending calls without that flag. On a fresh run with hooks, that means legacy states only. Because D1 is unfixed, the D3 rejection fix now also causes a new hook divergence on the common path (R1, §8). +3. **Large load-bearing upstream features are missing.** These change loop, state (`awaiting_async_tools`, persisted `doomLoop` state) and hooks behaviour: + - async tools, the unified lifecycle, the `task` tool, steering, `tool.agent()` subagents, and per-tool timeouts and concurrency; + - doom-loop detection; + - run-level cancellation; + - tool-sets; + - stream-replay compaction. +4. **Test parity.** 51 upstream unit test files have no Python counterpart. Many cover the tool loop, state, approval/HITL, hooks, or streaming (§4). + +The patch-level fixes that were ported are mostly faithful and reasonably tested (§2). Mechanical checks are green except for the version: +- ruff and mypy pass; +- 254 unit tests pass; +- the coverage floor of 83% is met; +- all 31 required symbols are exported. + +## 2. Per-change parity table + +| Upstream change | Status | Evidence (port) | Notes | +|---|---|---|---| +| #131 decision dedupe / conflict throw | Ported | `ModelResult.__init__` `_approved_ids`/`_rejected_ids` via `dict.fromkeys`, plus a conflict `ValueError` | Message matches upstream wording, with snake_case names. | +| #131 decision-less resume stays paused; partial decisions stay paused; getters raise the pause error | Ported | `_load_state` :337, `_stays_paused_without_decisions` :372, `_paused_error` :399, `_build_resume_request` returns `None` :1478-1484, `get_response` :1637, inspection getters use `_ensure_task` | Logic matches upstream. The resume gate is `pending_tool_calls and has_decisions` (:1009), not upstream's `status in (awaiting_approval, awaiting_hitl) and has_decisions` (low-severity edge for `awaiting_client_tools` states). | +| #94 two-phase approval gate | **Divergent (partially improved)** | Initial gate: `_prepare_tool_calls_for_approval` :780-816, `_resolve_approval_gate` :818-861. Post-approval: `_prepare_after_initial_approval` :1496-1542, `_mutated_input_requires_approval` :1544-1558, `_emit_prepared_failure` :1560-1574 | The post-approval phase now mirrors upstream (D2 and D3 fixed). The initial phase is still single-phase (D1 not fixed). | +| #143 stopWhen before approval on the first response (`allow_final_response=False`) | Ported | `model_result.py:~1104-1135` | Siblings are saved as `"Tool execution skipped: stop condition met"` (:1125). | +| #155 toModelOutput with parsed input, including the resume path | Ported | `_parsed_tool_input` :907, `_apply_to_model_output` :916, `_unsent_model_output` :929, used in `_build_resume_request` :1450 | | +| #153 nextTurnParams only for successful calls, using the effective (mutated) input | Ported | tool-round path in `model_result.py` | | +| #114 nextTurnParams may set `tool_choice`; the context always carries the key | Ported | `next_turn_params.py:8-28` | | +| #161 context setters store parsed values and validate the merged context | Ported | `tool_context.py:56-74`, :136-144 | | +| #160 an aborted blocking hook chain fails closed | Ported | `hooks_emit.py:71-79` | Matches the upstream diff. | +| #125 max_output_tokens truncation: no tool calls executed | Ported | `stream_transformers.py:41-77` | | +| #100 forced toolChoice relaxation, including across resumes and the persisted key | Partially ported | `_relax_forced_tool_choice` :123, `_forced_tool_choice_key` :144, `_send_and_track` :289, `ConversationState.consumed_forced_tool_choice_key` | Static choices match upstream. The dynamic (async-param) `tool_choice` re-arm cannot be reached because async params are resolved once (`_resolve_initial_request` :363). Upstream re-resolves them on every turn. | +| #97 `getUsage` | Partially ported | `get_usage` :1831-1852, `_snapshot_session_usage` :547 | D4 is not fixed: `get_usage()` drives the loop on approval-resumed runs. | +| #99 strict passthrough | Ported | `tool.py`, `tool_executor.py` | | +| #118 / #146 `wireInputSchema` | Ported (agent side) | `tool.py` (`wire_input_schema`, `mark_mcp`), `tool_executor.py` | Runtime raise for non-manual tools; undocumented divergence (D7). | +| #148 MCP annotations | Partially ported (brand only) | `mark_mcp(annotations=…)` | No `McpToolAnnotations` and no `createMCPTools`. Depends on the MCP scope (§5). | +| #93 fromChatMessages tool calls | Ported | `chat_compat.py:30-53` | | +| #110 preliminaryResults dropped | Ported | `tool_executor.py`, tool.result events | | +| #91 toolCall threaded into the execute context | Ported | `tool_executor.py` `to_function_call_item` | | +| #95 validateFinalResponse messages | Ported | `_validate_final_response` :484 | 7 of 17 upstream cases ported. | +| #31 `activeTools` | Ported | `call_model.py:35-38` | 6 of 9 upstream cases. The rest need tool-sets. | +| #31 `createToolSet` / tool-set | **Missing** | none | | +| #162 duplicate client tool names | Ported (earlier run) | `tool_types.py`, `ModelResult.__init__` | | +| #120 user agent | Ported (earlier run) | `openrouter.py` | Contract divergence 7. | +| #90 async tools / unified `run()` / lifecycles / `task` tool / steering / `tool.agent()` / per-tool cancellation and timeouts / concurrency | **Missing** | No registry, task tool, lifecycle, or `awaiting_async_tools` status | `call_model` now refuses `async_tools`, `tool_timeout_ms`, `tool_concurrency` (D6). | +| #73 / #89 doom-loop detection, escalation, fan-out | **Missing** | none | `call_model` now refuses `doom_loop`. | +| Run-level `signal` cancellation | **Missing** | Only `ModelResult.cancel()` (:1854) | `call_model` now refuses `signal`. | +| #109 / #116 stream replay compaction (`streamReplay`) | **Missing** | Unbounded `ModelResult._events` | `call_model` now refuses `stream_replay`. | +| #102 / #140 / #146 / #148 MCP under `packages/agent/src/mcp` | **Missing** (scope ambiguous, §5) | none | 25 upstream source files, 16 test files. | +| #158 SDK upgrade to 1.5.85 | N/A | The pinned SDK is a Python SDK | | + +## 3. Concrete findings (status after fix attempt 1) + +**D1. NOT FIXED. The approval gate runs PreToolUse before the human decision.** + +`model_result.py:780-816` (`_prepare_tool_calls_for_approval`) is still called first from `_resolve_approval_gate` :825. + +Upstream (`handleApprovalCheck` / `resolveApprovalPhases`, model-result.ts 3199-3410): +- `partitionToolCalls` and `PermissionRequest` run on the raw arguments. +- `PreToolUse` runs only for initial survivors, via `prepareAfterInitialApproval`. +- A held call is persisted with its original arguments and without `preToolUseApplied`. + +Port: +- `PreToolUse` fires for every call first. +- The predicate and `PermissionRequest` see the mutated arguments. +- Every held call is persisted with `pre_tool_use_applied=True`. + +Re-verified: a fresh run with a non-mutating `PreToolUse` hook on a `require_approval=True` tool fires `PreToolUse` once before the pause and persists `pre_tool_use_applied=[True]`. Upstream fires 0 times and stores no flag. + +`test_pre_tool_use_mutation_is_approved_once_and_persists_across_resume` still pins the port's single-phase shape. The upstream block "approval uses the post-PreToolUse arguments that execute would receive" (approval-gate-regressions.test.ts 444-1088) is still not ported. + +**D2. FIXED. Re-gating after a resume-time mutation is limited to input-dependent checks.** + +`_mutated_input_requires_approval` (`model_result.py:1544-1558`) mirrors upstream `mutatedInputRequiresApproval` (2795-2818): +- If a callable call-level `require_approval` exists, it is evaluated on the mutated call. +- Otherwise only a function-valued tool-level `require_approval` is evaluated. +- A blanket `True` returns `False`. + +Verified by reproduction: on a legacy pending call (no flag), a resume with `approve_tool_calls=["c1"]` and a mutating `PreToolUse` behaves as upstream: +- the tool executes once, with `{"v": "mutated"}`; +- `PreToolUse` fires once; +- `PostToolUse` sees the mutated input; +- one follow-up request is sent and the status ends `complete`. + +The function-valued path still pauses again with the mutated arguments and `pre_tool_use_applied=True`, which matches upstream `secondGatePausedIds`. + +Small difference: upstream returns `false` when `options.tools` is absent even if a call-level function exists. That branch cannot be reached in the port, because the approved call's tool has already been found. + +New test `test_blanket_require_approval_runs_the_approved_call_after_a_pre_tool_use_mutation` (`tests/unit/test_approval_gate_regressions.py:683`) asserts three things: the call executed exactly once with the mutated value, exactly one request was sent, and the status is `complete`. That is real parity coverage. It does not assert the `PreToolUse` count. I checked that manually: it is 1. + +**D3. FIXED (post-approval path). See R1 for the interaction with D1.** + +| Case | Port | Upstream | Result | +|---|---|---|---| +| Invalid mutation | `_prepare_after_initial_approval` :1526-1532 parses the mutation with `_parse_tool_arguments` and requires a mapping. On failure it blocks with `PreToolUse produced invalid input for ""` and emits `PostToolUseFailure`. | `validatePreparedMutation` / `blockPreparedToolCall` (2835-2872) | Matches | +| PermissionRequest deny on the mutated call | :1538-1541 emits `PostToolUseFailure` with the deny reason (default `Denied by PermissionRequest hook`). | `prepareAfterInitialApproval` 2902-2904 | Matches | +| Reject a call with `pre_tool_use_applied` | :1454-1462 emits `PostToolUseFailure` with "Rejected by user", then records the rejected result. | 6212-6222 | Matches | + +Verified by reproduction: +- Function-valued gate, then a mutation, then a `PermissionRequest` deny with reason "nope": the call does not execute, the model output is `{"error":"nope"}`, and exactly one `PostToolUseFailure` fires, with error `nope`. +- An invalid mutation `{"v": 123}` produces the upstream error output and exactly one failure hook. + +Tests: +- `test_a_mutation_that_fails_the_input_schema_is_blocked_on_resume` (:707) asserts the exact output list and the exact failure list. +- `test_rejecting_a_prepared_call_closes_its_lifecycle_with_post_tool_use_failure` (:732) asserts the exact `(tool_name, error)` list and the exact output. +- **Gap:** no test covers the `PermissionRequest` deny → `PostToolUseFailure` path. It was verified only by my reproduction. + +**D4. NOT FIXED. `get_usage()` drives the tool loop on an approval-resumed run.** + +`model_result.py:1848-1852` still awaits `_ensure_task()`. Upstream `getUsage` (7761-7787) counts only the resume dispatch and leaves the loop unadvanced. The upstream cases "does not advance an approval-resumed run when read before the loop" and "counts a STREAMING resume generation without advancing the loop" are not ported. + +**D5. PARTIALLY FIXED.** + +Fixed: +- The resume turn context is now `{"number_of_turns": 1}` (:1408). Verified: an approved tool's execute context receives `number_of_turns == 1`. No test pins this. +- The decision-resume rejection reason is now `"Rejected by user"` (:1458), matching upstream 6217. `create_rejected_result`'s default `"Tool call rejected by user"` (`conversation_state.py:265`) matches upstream's `createRejectedResult` default (conversation-state.ts:424), so it is correct as is. + +Not fixed: +- The decision-resume path still emits `SessionStart` (:974) and runs `UserPromptSubmit` on the input (:979-981). Upstream's resume path skips both. +- The resume gate still keys on `pending_tool_calls` rather than status (:1009). + +**D6. FIXED.** + +`call_model.py:14-29` raises `NotImplementedError` before any request for non-`None` `doom_loop`, `signal`, `tool_timeout_ms`, `tool_concurrency`, `async_tools`, or `stream_replay`. `test_unsupported_upstream_options_are_refused_instead_of_sent` (`tests/unit/test_call_model.py:114-119`) checks every key and asserts `client.requests == []`. + +Minor warning: `doom_loop=False` is also refused. Upstream `resolveDoomLoopOption(false)` means "disabled" (doom-loop.ts:392), which is exactly the port's behaviour, so accepting `False` would be the more faithful choice. + +**D7. NOT FIXED. Undocumented divergences** (should go in the compatibility notes): +- `tool()` raises at runtime on `wire_input_schema` for non-manual tools. Upstream enforces this only at the type level. +- The `ConversationState` key `consumed_forced_tool_choice_key` is snake_case. +- `get_usage` warns instead of raising. +- `NotImplementedError` is raised for the unported engine options (D6). + +**Test quality of the new tests.** +- Shared fixtures are used throughout (`QueuedClient`, `make_response`, `tool_call_response`, `MemoryStateAccessor`, the `recording` helper). +- Request-count and exactly-once assertions are exact. There is no `asyncio.sleep` and no hand-rolled client. +- `assert x is not None` lines are only used for narrowing. +- Case coverage is still thin compared with upstream: + + | File | Port | Upstream | + |---|---|---| + | approval-gate-regressions | 23 | 43 | + | final-response-validation | 7 | 17 | + | get-usage | 8 | 13 | + | hooks-contract-fixes | 6 | 16 | + | next-turn-params | 3 | 12 | + | server-tool | 5 | 16 | + | shared-context | 4 | 16 | + | call-model-active-tools | 6 | 9 | + +- The three new approval tests use a hand-built legacy state. Two get it by pausing without hooks; the reject test sets `pre_tool_use_applied=True` by hand. This exercises the upstream post-approval code paths, but not the fresh-run shape upstream produces. + +**CI / repo-owned files.** +- `--cov-fail-under=83` in `.github/workflows/ci.yaml` is unchanged. +- `.github/`, `LICENSE`, `pyproject.toml` identity and version, and `state.yaml` are untouched. + +## 4. Lists + +### Fixable defects in the ported subset (still open) + +1. **D1** `model_result.py:780-861`: implement the two-phase gate. + - Partition and emit `PermissionRequest` on the raw arguments. + - Run `PreToolUse` only for initial survivors, via `_prepare_after_initial_approval`. + - Persist human-held calls with their original arguments and no flag. + - Port upstream tests 444-1088, and fix `test_pre_tool_use_mutation_is_approved_once_and_persists_across_resume`. + - This also resolves R1. +2. **D4** `model_result.py:1831-1852`: on a decision-resume run, `get_usage()` must count only the resume dispatch and must not advance the loop. Port the two upstream get-usage cases. +3. **D5 (remainder)**: + - Skip `SessionStart` and `UserPromptSubmit` on the decision-resume path (:972-981). + - Gate the resume on `status in ("awaiting_approval", "awaiting_hitl")` (:1009). + - Add a test pinning `number_of_turns == 1` on resume. +4. **D3 test gap**: add a test for a `PermissionRequest` deny on a mutated call → exactly one `PostToolUseFailure`. +5. **D6 nit**: accept `doom_loop=False`. +6. **D7**: record the divergences listed above in `upstreamer-changelog.md` / Parity Notes. + +### Unported upstream features (gaps) + +- **#90 async tools:** + - the unified `run()` interface and the `background`/`deferred` lifecycles; + - `AsyncToolRegistry`; + - the `task` tool (check/steer/result/cancel), steering, and `tool.agent()` subagents; + - per-tool `timeout_ms`/`max_concurrency`, plus `Semaphore`/`acquireAll`; + - the `awaiting_async_tools` status, `resumeToolResults`, and `getAsyncTasks`. +- **#73 / #89 doom-loop:** `DoomLoopMonitor`, the escalation ladder, fan-out detection, remediation/steer, persisted `doomLoop` state, `getDoomLoopVerdict`, and the `DoomLoopDetected` hook. +- Run-level `signal`, `tool_timeout_ms`, and `tool_concurrency`. +- **#31 tool-set:** `createToolSet`, `inferTools`/`.resolve()`, and snapshot metadata stripping. +- **#109 / #116 stream replay compaction** (`streamReplay`). +- Per-turn async-param re-resolution. Upstream's dynamic `tool_choice` re-arm depends on it. +- The `packages/agent/src/mcp` subpath (`createMCPTools`, `rehydrateMCPTools`, cache, elicitation, resource tools, `McpToolAnnotations`). Scope is ambiguous, see §5. + +### Unported upstream test files (from `verify.sh` / `comm -23`, 51 files) + +| Upstream test | Invariant | Severity | +|---|---|---| +| doom-loop, doom-loop-escalation, doom-loop-fanout, doom-loop-integration, doom-loop-public-api, doom-loop-remediation | repeated-call detection, escalation, stop verdict across resumes | FAIL (loop/state/hooks) | +| async-tool-background, async-tool-deferred, async-tool-registry, task-tool-actions, task-tool-integration, steering, agent-tool | async lifecycle, task check-ins, deferred resume, subagents | FAIL (loop/state) | +| run-cancellation, tool-cancellation, tool-orchestrator | cancellation/timeouts, concurrency, execution order | FAIL (loop) | +| tool-check | task-tool check semantics | FAIL (loop) | +| model-result-replay-compaction, replay-buffer-compaction, reusable-stream | multi-consumer replay correctness and memory bounds | FAIL (streaming) | +| tool-set | activeTools/tool-set resolution | warning→FAIL (request shape) | +| hitl-tool | HITL pause/resume, context threading | FAIL (approval/HITL) | +| hooks-emit, hooks-emit-adversarial, hooks-manager-adversarial, hooks-matchers-adversarial, hooks-resolve(+adversarial), hooks-types-adversarial, hooks-void-schema, hooks-post-model-call, hooks-session-lifecycle | hook chain semantics, PostModelCall, SessionEnd | FAIL (hooks); partly covered by `test_hooks_manager.py` / `test_model_result_hooks.py` | +| conversation-state, stop-conditions, turn-context, user-input-persistence | state helpers, stop predicates, turn context, input persistence | FAIL (state/loop) | +| manual-tool-calls-adversarial, get-items-stream-manual-tools, build-tool-call-stream, model-result-stream-detection, tool-name-events, tool-event-broadcaster | manual-tool edge cases, item/stream surfaces | FAIL (streaming) | +| tool-context, schema-sanitization, create-tool, tool-type-compat | context store, schema sanitization, tool factory | warning | +| openrouter | client wrapper (user agent, hooks) | warning (partly in `test_user_agent.py`) | +| claude-type-guards, assistant-message-images | compat guards/images | warning | +| package-boundaries, startup-import-closure | TS packaging/import graph | warning (largely N/A for Python) | +| mcp/* (16 files) | MCP subpath | depends on the scope decision | +| `*.test-d.ts` (type-level) | type inference | warning (contract divergence 4) | + +## 5. Contract ambiguity: MCP scope + +The contract says "Port only `packages/agent/`" and that `packages/mcp/` is not ported. Upstream #102 moved MCP into `packages/agent/src/mcp` and exports it as `@openrouter/agent/mcp`, and #140, #146 and #148 landed there. + +- **Read literally**, MCP is now in scope. +- **Read by intent** ("do not begin porting MCP as a side effect of a sync"), it is out of scope. + +The converter treated it as out of scope, which is defensible, but the decision is not recorded anywhere. The contract needs an explicit amendment either way. This does not change the verdict. + +## 6. Version honesty + +- The target `0fe4cb1` is tagged `@openrouter/agent@1.3.0`, and the verifier reports the tree as level with the tag. +- **Claiming 1.3.0 would overstate the port.** It is missing the 0.9.0 async tools and doom-loop, the 0.10.0 tool-set, and the 0.11.0 replay compaction. PyPI versions cannot be reused. +- The highest truthful claim is **0.8.x**: upstream 0.8.0 plus Python backports of selected later patch fixes. Those are #91, #93, #95, #97 (partial), #99, #100 (partial), #110, #114, #118, #125, #131, #143, #146 (agent side), #153, #155, #160, #161, #162, and the post-approval part of #94. +- `state.yaml` must stay at `680bceb`. The earliest delta commit (`78c562e`, #73) is not ported. + +## 7. Recommended human action + +1. **Do not advance `state.yaml`, and do not set `version = 1.3.0`.** Do not publish from this tree. +2. Have the converter fix D1 next. D1 is the root cause of the remaining approval divergence and of R1. Then fix D4 and the rest of D5, and port the matching upstream approval-gate-regressions and get-usage cases. +3. Decide the sync strategy for the large features (#90, #73/#89, #31, #109, run-level `signal`): + - port each in its own focused run; or + - amend the contract to make them documented deferrals, with a version policy (for example, stay on 0.8.x and record the backports in `upstreamer-changelog.md`). +4. Amend the contract's Scope section on `packages/agent/src/mcp`. +5. Add the naming mappings once confirmed: + + | TypeScript | Python | + |---|---| + | `getUsage` | `get_usage` | + | `activeTools` | `active_tools` | + | `wireInputSchema` | `wire_input_schema` | + | `consumedForcedToolChoiceKey` | `consumed_forced_tool_choice_key` | + | `toFunctionCallItem` | `to_function_call_item` | + | `isTruncatedAtMaxOutputTokens` | `is_truncated_at_max_output_tokens` | + | `responseHasToolCalls` | `response_has_tool_calls` | + | `mutatedInputRequiresApproval` | `_mutated_input_requires_approval` (private) | + | `emitPreparedFailure` | `_emit_prepared_failure` (private) | + +## 8. Re-run after fix attempt 1 + +**Commands run** +- `uv run pytest tests/unit -q`: 254 passed. There is one asyncio `ResourceWarning` for an unclosed event loop, which is not a failure. +- `.upstreamer/scripts/verify.sh`: every check passes except one, `version drift: pyproject.toml=0.8.2, upstream @openrouter/agent=1.3.0`. Passing checks are uv sync, lockfile, ruff check, ruff format, mypy, pytest with the 83% coverage floor, 31/31 required symbols, the release-tag level check, no TS artifacts, and repo-owned files present. It also lists the 51 unported upstream test files. + +**Fix verification.** I read the code against upstream `prepareAfterInitialApproval` (2874-2908), `mutatedInputRequiresApproval` (2795-2818), `validatePreparedMutation` (2854-2872), `blockPreparedToolCall` (2835-2852), `emitPreparedFailure` (2820-2833) and `processApprovalDecisions` (6086-6260). I also ran reproductions. + +| Defect | Claimed | Verified status | +|---|---|---| +| D2 | blanket `True` no longer re-gates | **Fixed.** Executes once with the mutated input and completes. The function-valued path still re-pauses, as upstream does. | +| D3 | invalid-mutation block, deny/reject PostToolUseFailure, "Rejected by user" | **Fixed** on the post-approval path. All three emit exactly one `PostToolUseFailure` with upstream's reason strings. No test covers the deny path. | +| D5 | number_of_turns 1 on resume | **Partially fixed.** `number_of_turns` is 1 (verified, but no test pins it) and the reason string is fixed. `SessionStart`/`UserPromptSubmit` still run on resume, and the gate still keys on `pending_tool_calls` rather than status. | +| D6 | refuse unported engine options | **Fixed.** Tested for all six keys with no request sent. Nit: `doom_loop=False` is refused. | +| D1, D4, D7 | not attempted | **Not fixed.** Confirmed still present. | + +**Regression found** + +**R1.** `PostToolUseFailure("Rejected by user")` now fires on ordinary fresh-run rejections when hooks are configured (`model_result.py:1459-1461`). +- **Cause:** D1 persists every held call with `pre_tool_use_applied=True` (:814). The new D3 rejection branch therefore fires for the common case. +- **Reproduction:** a hooks-enabled fresh run on a `require_approval=True` tool pauses with the flag set. Resuming with `reject_tool_calls=["c1"]` emits `PostToolUseFailure` once, with error `Rejected by user`. Upstream emits it zero times, because held calls never ran `PreToolUse` and so carry no flag. +- **Assessment:** this is internally consistent with the port's own (divergent) lifecycle, since `PreToolUse` did run. It is still a new observable hook difference from upstream in the common path; before this fix attempt the port matched upstream here. +- **Fix:** fixing D1 removes it. +- **Test gap:** `test_rejecting_a_prepared_call_closes_its_lifecycle_with_post_tool_use_failure` sets the flag by hand, so it does not exercise this path. + +No other regressions found. All previously passing tests still pass, and the updated resume rejection text did not break any existing assertion. + +**Verdict after re-run: FAIL.** D1 (approval/hooks ordering) and D4 are still open, the large features and their test files are still missing, and the version claim still cannot be made honest. + +## 9. Converter fix attempt 2, and the bankruptcy decision + +The converter wrote this section after the re-run in §8. It is not part of the +independent review. + +**Fix attempt 2 (R1).** The `PostToolUseFailure("Rejected by user")` emit on +the reject path has been removed (`_build_resume_request`, comment at the +rejection loop). Ordinary rejections again fire no hook, matching upstream on +that path. A test pins this: +`test_rejecting_a_held_call_emits_no_post_tool_use_failure`. Upstream emits the +hook for calls whose PreToolUse ran after an initial approval. That emit goes +back in once D1, the two-phase gate, is ported. Attempt 2 also added +`test_a_permission_request_deny_on_mutated_arguments_blocks_and_reports_failure`, +covering the D3 deny case §8 said had no test. After attempt 2 the verifier +fails only on version drift, and all 255 unit tests pass at 86% coverage +against the 83% floor. + +**Bankruptcy.** The eval still returns **FAIL**, and no fix inside this run's +scope can change that. + +- **Unported features.** The remaining FAIL conditions are entire upstream + features: + - async/unified `run()` tools, the `task` tool, steering and `tool.agent()` + subagents (#90) + - doom-loop detection with cross-port fingerprint vectors (#73, #89) + - run-level `signal` cancellation and per-tool timeouts and concurrency + - tool sets (#31) + - stream replay compaction (#109, #116) + - per-turn re-resolution of async request params + - the upstream two-phase approval gate (D1) + + Together these are roughly 10k lines of upstream source, most of it + interleaved in the 7.8k-line `model-result.ts`, plus about 25k lines of + upstream tests. This is not a focused fix. +- **Version.** The verifier requires `version = 1.3.0`. Declaring it would + overstate the port, which the contract forbids ("Never set it past what was + actually ported"). So the version stays `0.8.2` and the verifier's version + check fails on purpose. +- **Nothing to advance to.** The earliest commit in the delta (`78c562e`, + doom-loop) is unported. No intermediate upstream commit is fully covered, so + `state.yaml` cannot advance at all. + +`.upstreamer/state.yaml` therefore stays at +`680bceb4598f228d3e2ec58e2416e4335cdff059`, and the next run retries the same +delta. + +**What this run does leave in the tree.** These are verified, tested +backports of the upstream patch-level fixes listed as Ported in §2: +- #131 approval-decision validation and paused resumes +- #143, #155, #153, #114, #161, #160, #125 +- #100 for static choices +- #97, with D4 open +- #99, #118 and #146 on the agent side +- #93, #110, #91, #95, #31 `active_tools` + +The verifier is green apart from the version check. The next run should treat +these as already present and reconcile them, not redo them. + +**Recommended human action.** +1. Do not publish from this tree. `0.8.2` plus backports is not any upstream + release. +2. Split the sync into staged runs. Two ways to do it: + - Add a contract option to target an intermediate upstream commit or tag, + for example port `@openrouter/agent@0.9.0` (async tools and doom loop) + first. + - Run it as several human-reviewed PRs, one per feature family: (a) the D1 + two-phase approval gate and the per-turn async-param re-resolution; + (b) run-level cancellation and timeouts; (c) doom-loop, against + `tests/vectors/doom-loop-fingerprints.json`; (d) async tools, task tool, + steering and `tool.agent()`; (e) tool sets; (f) replay compaction. +3. Decide the MCP scope (§5). Upstream moved MCP into `packages/agent/src/mcp`, + while the contract excludes `packages/mcp`. Porting it would also add an + MCP Python SDK dependency, which is a substrate change. +4. Once features are in, set `version` to the highest upstream version whose + features are all present, and only then advance `state.yaml`. diff --git a/README.md b/README.md index e0372b2..c80b177 100644 --- a/README.md +++ b/README.md @@ -115,12 +115,14 @@ analysis = tool( ) ``` -Manual tools are advertised to the model but not auto-executed. +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`. ```python confirm = tool(name="confirm_action", input_schema=ConfirmInput, execute=False) ``` +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). + HITL tools use `on_tool_called`; returning a value auto-resolves, returning `None` pauses with pending tool calls in state. ```python @@ -144,6 +146,8 @@ web = server_tool({"type": "web_search_2025_08_26", "max_results": 5}) 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. +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. + 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`. 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( ) ``` +## Usage + +`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. + ## Lifecycle Hooks 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 - `max_cost(dollars)` - `finish_reason_is(reason)` +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. + 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. ## Format Compatibility diff --git a/src/openrouter_agent/call_model.py b/src/openrouter_agent/call_model.py index daad651..aad66a0 100644 --- a/src/openrouter_agent/call_model.py +++ b/src/openrouter_agent/call_model.py @@ -5,13 +5,46 @@ from .hooks_resolve import resolve_hooks from .model_result import ModelResult from .tool_executor import convert_tools_to_api_format +from .tool_types import get_tool_function, is_server_tool + + +#: Upstream `callModel` options whose features this port does not implement +#: yet. Refused instead of being forwarded to the Responses API, where they +#: would be sent as unknown request fields or silently ignored. +UNSUPPORTED_CALL_MODEL_OPTIONS = ( + "doom_loop", + "signal", + "tool_timeout_ms", + "tool_concurrency", + "async_tools", + "stream_replay", +) def call_model(client: Any, request: Mapping[str, Any], options: Optional[Mapping[str, Any]] = None) -> ModelResult: + unsupported = [key for key in UNSUPPORTED_CALL_MODEL_OPTIONS if request.get(key) is not None] + if unsupported: + raise NotImplementedError( + f"call_model option(s) not supported by this Python port yet: {', '.join(unsupported)}" + ) tools = request.get("tools") + # Narrow tools to the active subset (if provided) before API conversion and + # before they are registered for execution, so the model cannot call + # filtered tools and the executor does not carry orphaned definitions. + # Server tools are always kept. + active_tools = request.get("active_tools") + if active_tools is not None and tools is not None: + active_set = set(active_tools) + tools = [t for t in tools if is_server_tool(t) or get_tool_function(t).get("name") in active_set] + # A filtered-to-empty (or explicitly empty) tools list omits the outbound + # `tools` key entirely instead of sending `tools: []`, which several + # providers reject; the engine treats it as its no-tools state. + if tools is not None and len(tools) == 0: + tools = None final_request = dict(request) for key in ( "tools", + "active_tools", "stop_when", "state", "require_approval", diff --git a/src/openrouter_agent/chat_compat.py b/src/openrouter_agent/chat_compat.py index 8861494..a30335e 100644 --- a/src/openrouter_agent/chat_compat.py +++ b/src/openrouter_agent/chat_compat.py @@ -27,6 +27,30 @@ def from_chat_messages(messages: Sequence[Mapping[str, Any]]) -> List[Dict[str, "output": _content_to_string(msg.get("content")), } ) + elif role == "assistant": + content = _content_to_string(msg.get("content")) + tool_calls = msg.get("tool_calls") or msg.get("toolCalls") or [] + # Skip the message item only when there is no content AND there are + # tool calls to emit in its place. A content-less assistant message + # with no tool calls still round-trips as an empty message. + if content or not tool_calls: + output.append({"type": "message", "role": role, "content": content}) + # One function_call item per tool call. The chat format's + # `function.arguments` is already a JSON string, so it is + # forwarded as-is. + for call in tool_calls: + function = get_field(call, "function", {}) or {} + call_id = get_field(call, "id") + output.append( + { + "type": "function_call", + "callId": call_id, + "id": call_id, + "name": get_field(function, "name"), + "arguments": get_field(function, "arguments"), + "status": "completed", + } + ) else: output.append({"type": "message", "role": role, "content": _content_to_string(msg.get("content"))}) return output diff --git a/src/openrouter_agent/conversation_state.py b/src/openrouter_agent/conversation_state.py index 2cce4d8..42fac25 100644 --- a/src/openrouter_agent/conversation_state.py +++ b/src/openrouter_agent/conversation_state.py @@ -184,6 +184,7 @@ def deserialize_conversation_state(raw_json: str) -> ConversationState: partial_response=partial_response, interrupted_by=parsed.get("interrupted_by"), version=CONVERSATION_STATE_VERSION, + consumed_forced_tool_choice_key=parsed.get("consumed_forced_tool_choice_key"), ) diff --git a/src/openrouter_agent/hooks_emit.py b/src/openrouter_agent/hooks_emit.py index 4391677..fc19ff2 100644 --- a/src/openrouter_agent/hooks_emit.py +++ b/src/openrouter_agent/hooks_emit.py @@ -68,7 +68,14 @@ async def execute_handler_chain( behavior = HOOK_BEHAVIOR.get(hook_name) for index, entry in enumerate(entries): + # Checked before each handler so synchronous chains stop promptly. if context.cancel_event.is_set(): + # A hook that can block (PreToolUse, UserPromptSubmit) fails + # closed: the handlers left unrun may include the guard that + # would have blocked, so an aborted chain must not read as an + # approval. + if behavior and behavior.block_field: + blocked = True break gate = _evaluate_entry_gate(entry, current_payload, index, options) diff --git a/src/openrouter_agent/hooks_types.py b/src/openrouter_agent/hooks_types.py index 953af4c..b9a0666 100644 --- a/src/openrouter_agent/hooks_types.py +++ b/src/openrouter_agent/hooks_types.py @@ -94,7 +94,9 @@ class EmitResult: pending: List["asyncio.Task[None]"] = field(default_factory=list) #: The payload after all mutation piping has been applied. final_payload: Dict[str, Any] = field(default_factory=dict) - #: True if any handler triggered a block/reject short-circuit. + #: True if any handler triggered a block/reject short-circuit, or if the + #: chain of a blocking hook (PreToolUse, UserPromptSubmit) was aborted + #: before every handler ran. blocked: bool = False #: True if any handler's result actually piped a mutation into the payload. mutated: bool = False diff --git a/src/openrouter_agent/model_result.py b/src/openrouter_agent/model_result.py index 37e11bd..14160ca 100644 --- a/src/openrouter_agent/model_result.py +++ b/src/openrouter_agent/model_result.py @@ -7,7 +7,7 @@ import warnings from typing import Any, AsyncIterator, Dict, List, Mapping, Optional, Sequence, Tuple -from ._utils import dump, get_field, is_async_iterable, json_dumps, maybe_await, sdk_request_kwargs +from ._utils import dump, get_field, is_async_iterable, json_dumps, maybe_await, sdk_request_kwargs, validate_schema from .async_params import resolve_async_functions from .conversation_state import ( append_to_messages, @@ -15,7 +15,9 @@ create_rejected_result, create_unsent_result, generate_conversation_id, + _parse_tool_arguments, partition_tool_calls, + tool_requires_approval, unsent_results_to_api_format, update_state, ) @@ -96,6 +98,61 @@ def _is_user_string_message(value: Any) -> bool: return isinstance(value, Mapping) and value.get("role") == "user" and isinstance(value.get("content"), str) +def _describe_non_record(value: Any) -> str: + """Name a value's type the way upstream's `describeNonRecord` does, so + diagnostics read the same across ports.""" + if value is None: + return "null" + if isinstance(value, (list, tuple)): + return "array" + if isinstance(value, bool): + return "boolean" + if isinstance(value, (int, float)): + return "number" + if isinstance(value, str): + return "string" + return "object" + + +#: Most pending call IDs listed in a "conversation is paused" error. A state +#: can hold any number of pending calls; the message stays readable and the +#: full list is available from `get_pending_tool_calls()`. +_MAX_PENDING_IDS_IN_ERROR = 10 + + +def _relax_forced_tool_choice(tool_choice: Any) -> Any: + """Relax a tool choice that *forces* a tool call, for follow-up turns after + a tool round has executed (upstream DEV-785). + + - `"required"` -> `"auto"` + - a specific-tool object (`{"type": "function", "name": ...}`, ...) -> `"auto"` + - `allowed_tools` with `mode: "required"` -> same set with `mode: "auto"` + (the constraint on *which* tools may be used still applies; only the + force-a-call part is spent) + - `"auto"`, `"none"`, `allowed_tools` with `mode: "auto"`, and `None` pass + through unchanged. + """ + if tool_choice is None or isinstance(tool_choice, str): + return "auto" if tool_choice == "required" else tool_choice + if get_field(tool_choice, "type") == "allowed_tools": + if get_field(tool_choice, "mode") == "required": + return {**dict(dump(tool_choice)), "mode": "auto"} + return tool_choice + return "auto" + + +def _forced_tool_choice_key(tool_choice: Any) -> Optional[str]: + """Stable identity for a concrete forced choice; `None` means tools are not + forced.""" + if tool_choice is None or isinstance(tool_choice, str): + forced = tool_choice == "required" + else: + forced = get_field(tool_choice, "type") != "allowed_tools" or get_field(tool_choice, "mode") == "required" + if not forced: + return None + return json.dumps(dump(tool_choice), sort_keys=True, separators=(",", ":"), default=str) + + def _find_latest_user_string_index(items: Sequence[Any]) -> int: for index in range(len(items) - 1, -1, -1): if _is_user_string_message(items[index]): @@ -121,6 +178,7 @@ def __init__(self, options: Mapping[str, Any]) -> None: self._hooks = self.options.get("hooks") self._session_id = "" self._resuming_from_client_tools = False + self._initial_request: Optional[Dict[str, Any]] = None self._session_start_emitted = False self._session_end_emitted = False self._all_tool_rounds = 0 @@ -138,6 +196,27 @@ def __init__(self, options: Mapping[str, Any]) -> None: "state" ): raise ValueError("approve_tool_calls and reject_tool_calls require a state accessor") + # De-duplicate decisions so a call ID listed twice cannot execute an + # approval-gated tool twice, and refuse contradictory input outright: + # an ID that is both approved and rejected has no safe interpretation. + self._approved_ids: List[str] = list(dict.fromkeys(self.options.get("approve_tool_calls") or [])) + self._rejected_ids: List[str] = list(dict.fromkeys(self.options.get("reject_tool_calls") or [])) + rejected_set = set(self._rejected_ids) + conflicting = [call_id for call_id in self._approved_ids if call_id in rejected_set] + if conflicting: + raise ValueError( + f"Tool call IDs cannot be both approved and rejected: {', '.join(conflicting)}. " + "Pass each pending call ID in exactly one of approve_tool_calls or reject_tool_calls." + ) + #: Set when a paused conversation was resumed without the decision it + #: owes: the run sends nothing and every getter reports the pause. + self._paused_without_decisions = False + #: Forced tool_choice consumed in this logical run (see + #: `_relax_forced_tool_choice`); persisted so resumes stay relaxed. + self._consumed_forced_key: Optional[str] = None + + def _has_decisions(self) -> bool: + return bool(self._approved_ids or self._rejected_ids) # -- transport ----------------------------------------------------------- @@ -207,10 +286,39 @@ async def _coerce_response(self, value: Any) -> Any: return completed or {"id": "response_from_events", "output": []} return value - async def _send_and_track(self, request: Mapping[str, Any], turn_type: str, turn_number: int) -> Any: - """Send a request, coerce its response, and emit PostModelCall for it.""" + async def _send_and_track( + self, + request: Mapping[str, Any], + turn_type: str, + turn_number: int, + *, + caller_tool_choice: bool = True, + ) -> Any: + """Send a request, coerce its response, and emit PostModelCall for it. + + With `caller_tool_choice` (every dispatch except engine-owned + overrides such as the forced-final `tool_choice: "none"` turn), the + caller-configured `tool_choice` goes through the forced-choice policy: + once a forced choice (`"required"`, a specific tool, or + `allowed_tools` with `mode: "required"`) has produced a tool call in + this logical run, it is relaxed to `"auto"` on later turns so the model + can answer in text instead of calling tools until the step budget runs + out. A choice is consumed only when the response that carried it + called a tool; an unforced choice re-arms it. + """ started = time.monotonic() + configured_key: Optional[str] = None + if caller_tool_choice and "tool_choice" in request: + configured = request.get("tool_choice") + configured_key = _forced_tool_choice_key(configured) + if configured_key is not None and configured_key == self._consumed_forced_key: + request = {**dict(request), "tool_choice": _relax_forced_tool_choice(configured)} response = await self._coerce_response(await self._send(request)) + if caller_tool_choice: + if configured_key is None: + self._consumed_forced_key = None + elif configured_key != self._consumed_forced_key and extract_tool_calls_from_response(response): + self._consumed_forced_key = configured_key await self._emit_post_model_call(response, started, turn_type, turn_number) return response @@ -231,16 +339,103 @@ async def _load_state(self) -> None: if accessor is None: return loaded = await maybe_await(accessor.load()) + if loaded is not None: + self._consumed_forced_key = loaded.consumed_forced_tool_choice_key self._resuming_from_client_tools = bool(loaded is not None and loaded.status == "awaiting_client_tools") self._state = loaded or create_initial_state() + if ( + loaded is not None + and loaded.status in ("awaiting_approval", "awaiting_hitl") + and not self._has_decisions() + and await self._stays_paused_without_decisions(loaded) + ): + # Paused for a human decision but none was supplied: stay paused. + # Falling through would flip the status to "in_progress" and send + # a fresh model request, advancing the conversation past calls + # that still owe a decision. Every response/stream getter surfaces + # this as an explicit "awaiting ..." error (see `_paused_error`). + self._paused_without_decisions = True + return if not self._resuming_from_client_tools: self._state = update_state(self._state, {"status": "in_progress"}) await maybe_await(accessor.save(self._state)) + async def _resolve_initial_request(self) -> Dict[str, Any]: + """Resolve the turn-0 request exactly once. Caller-supplied async + parameter functions (including a function-valued `input`) must not run + twice when the paused-resume check needs the resolved input before the + normal initialization path does.""" + if self._initial_request is None: + self._initial_request = await resolve_async_functions(self.options["request"], {"number_of_turns": 0}) + return self._initial_request + + async def _stays_paused_without_decisions(self, loaded: Any) -> bool: + """Whether a state loaded as `awaiting_approval` / `awaiting_hitl` stays + paused when the caller supplied no approve/reject decisions. + + - No pending calls: nothing is owed a decision, so continue with a + normal request instead of stranding the conversation. + - `awaiting_approval`: always paused. Only a recorded approve/reject + decision releases an approval gate; a caller-supplied + `function_call_output` for the gated call does not. + - `awaiting_hitl`: paused unless `input` carries a + `function_call_output` for a pending call -- the documented way to + resume a HITL tool (it goes through `on_response_received`). + """ + pending_ids = {call.id for call in (loaded.pending_tool_calls or [])} + if not pending_ids: + return False + if loaded.status != "awaiting_hitl": + return True + input_value = (await self._resolve_initial_request()).get("input") + if not isinstance(input_value, list): + return True + return not any( + get_field(item, "type") == "function_call_output" + and (get_field(item, "callId") or get_field(item, "call_id")) in pending_ids + for item in input_value + ) + + def _paused_error(self) -> Optional[Exception]: + """Describe the pause when the conversation is waiting on the caller + (`awaiting_approval` / `awaiting_hitl`), or `None` when it is not.""" + state = self._state + status = getattr(state, "status", None) + if status not in ("awaiting_approval", "awaiting_hitl"): + return None + pending_ids = [call.id for call in (state.pending_tool_calls or [])] + shown = ", ".join(pending_ids[:_MAX_PENDING_IDS_IN_ERROR]) + hidden = len(pending_ids) - _MAX_PENDING_IDS_IN_ERROR + id_list = f"{shown}, ... ({hidden} more)" if hidden > 0 else shown + if status == "awaiting_approval": + what = "awaiting approval" + how_to_resume = "Resume with approve_tool_calls and/or reject_tool_calls for the pending calls." + else: + what = "awaiting HITL input" + how_to_resume = ( + "Resume by passing a function_call_output for a pending call ID in input, " + "or with approve_tool_calls / reject_tool_calls (approving re-runs on_tool_called)." + ) + input_value = self.options["request"].get("input") + input_supplied = callable(input_value) or bool(input_value) + message = ( + f"Conversation is {what} (status '{status}'); no response is available. " + f"Pending tool call IDs: {id_list}. {how_to_resume} " + "Use requires_approval() or get_pending_tool_calls() to inspect a paused conversation." + ) + if input_supplied: + message += " The input supplied with this call was not sent to the model and was not saved to state." + return RuntimeError(message) + async def _save_state(self, **updates: Any) -> None: accessor = self.options.get("state") if accessor is None or self._state is None: return + if updates.get("status") == "complete": + # A later conversational turn is a new logical run and may force + # its first tool call again. + self._consumed_forced_key = None + updates["consumed_forced_tool_choice_key"] = self._consumed_forced_key self._state = update_state(self._state, updates) await maybe_await(accessor.save(self._state)) @@ -263,7 +458,7 @@ async def _save_response_to_state(self, response: Any) -> None: # the only copy if that request failed. updates["pending_tool_calls"] = None updates["status"] = "in_progress" - self._resuming_from_client_tools = False + self._resuming_from_client_tools = False await self._save_state(**updates) async def _save_tool_outputs_to_state(self, outputs: Sequence[Any]) -> None: @@ -287,14 +482,31 @@ async def _persist_client_tools_pause(self, response: Any, unresolved_calls: Seq await self._save_state(pending_tool_calls=list(unresolved_calls), status="awaiting_client_tools") def _validate_final_response(self, response: Any, allow_empty_output: bool = False) -> None: + """Validate the final response has required fields. + + Message prefixes (`Invalid final response: missing required fields`, + `Invalid final response: empty or invalid output`) are load-bearing -- + callers and tests match on them. Detail is appended after an em dash; + never reword the prefixes. This is a pure array-length check, so a + `function_call`-only output passes. + """ response_id = get_field(response, "id") output = get_field(response, "output") if not response_id or output is None: - raise ValueError("Invalid final response: missing required fields") + missing = [name for name, absent in (("id", not response_id), ("output", output is None)) if absent] + raise ValueError(f"Invalid final response: missing required fields: {', '.join(missing)}") if not isinstance(output, list) or len(output) == 0: if allow_empty_output: return - raise ValueError("Invalid final response: empty or invalid output") + if isinstance(output, list): + detail = ( + f'output array is empty (length 0) for response "{response_id}". The model returned no ' + "output items. This can happen when the provider returns an empty final turn; see the " + "strict_final_response/allow_final_response options" + ) + else: + detail = f'output is not an array (got {_describe_non_record(output)}) for response "{response_id}"' + raise ValueError(f"Invalid final response: empty or invalid output — {detail}") # -- hooks ----------------------------------------------------------- @@ -326,25 +538,34 @@ async def _emit_session_end(self, reason: str) -> None: self._session_end_emitted = True payload: Dict[str, Any] = {"reason": reason} if self._session_usage["model_calls"] > 0: - total_usage = { - "model_calls": self._session_usage["model_calls"], - "input_tokens": self._session_usage["input_tokens"], - "output_tokens": self._session_usage["output_tokens"], - "total_tokens": self._session_usage["total_tokens"], - "cached_tokens": self._session_usage["cached_tokens"], - "reasoning_tokens": self._session_usage["reasoning_tokens"], - } - if self._session_usage["has_cost"]: - total_usage["cost"] = self._session_usage["cost"] - payload["total_usage"] = total_usage + payload["total_usage"] = self._snapshot_session_usage() try: await self._hooks.emit("SessionEnd", payload, session_id=self._session_id) except Exception as error: # noqa: BLE001 - teardown must never mask the real error warnings.warn(f"[SessionEnd] error during session teardown: {error}", stacklevel=2) + def _snapshot_session_usage(self) -> Dict[str, Any]: + """Materialize the running session aggregate. `cost` is present only + when at least one response reported it (a summed `0` from cost-less + responses would read as "free" rather than "unknown"). Single source + of truth for both `SessionEnd.total_usage` and `get_usage()`, so the + two cannot drift.""" + totals: Dict[str, Any] = { + "model_calls": self._session_usage["model_calls"], + "input_tokens": self._session_usage["input_tokens"], + "output_tokens": self._session_usage["output_tokens"], + "total_tokens": self._session_usage["total_tokens"], + "cached_tokens": self._session_usage["cached_tokens"], + "reasoning_tokens": self._session_usage["reasoning_tokens"], + } + if self._session_usage["has_cost"]: + totals["cost"] = self._session_usage["cost"] + return totals + async def _emit_post_model_call(self, response: Any, started_at: float, turn_type: str, turn_number: int) -> None: - if not self._hooks: - return + # Accumulation runs unconditionally -- before the hooks short-circuit -- + # because `get_usage()` surfaces these totals to callers who configured + # no hooks at all. Only the hook emit is gated on a HooksManager. usage = _extract_model_call_usage(get_field(response, "usage")) self._session_usage["model_calls"] += 1 if usage: @@ -356,6 +577,8 @@ async def _emit_post_model_call(self, response: Any, started_at: float, turn_typ if usage.get("cost") is not None: self._session_usage["cost"] += usage["cost"] self._session_usage["has_cost"] = True + if not self._hooks: + return payload = { "session_id": self._session_id, "response_id": get_field(response, "id", ""), @@ -649,7 +872,7 @@ async def _execute_calls_to_unsent_results( tool = self._find_tool(call.name, tools) if not tool or not is_auto_resolvable_tool(tool): continue - outcome = await self._run_tool_with_hooks(tool, call, {**turn_context, "tool_call": call}) + outcome = await self._run_tool_with_hooks(tool, call, turn_context) if outcome["type"] == "parse_error": results.append(create_rejected_result(call.id, call.name, outcome["error_message"])) elif outcome["type"] == "hook_blocked": @@ -662,7 +885,11 @@ async def _execute_calls_to_unsent_results( else: effective_call = outcome["call"] results.append( - create_unsent_result(effective_call.id, effective_call.name, outcome["result"].get("result")) + create_unsent_result( + effective_call.id, + effective_call.name, + await self._unsent_model_output(effective_call, tool, outcome["result"].get("result")), + ) ) return results @@ -677,21 +904,46 @@ async def _record_preliminary(self, call_id: str, value: Any) -> None: } ) + def _parsed_tool_input(self, tool: Tool, call: ParsedToolCall) -> Any: + """`call.arguments` is the JSON-parsed wire payload. Parse it with the + tool's `input_schema` so `to_model_output` sees the same input + `execute` got; fall back to the raw arguments when parsing fails.""" + try: + return validate_schema(get_tool_function(tool).get("input_schema"), call.arguments) + except Exception: + return call.arguments + + async def _apply_to_model_output(self, call: ParsedToolCall, tool: Tool, value: Any) -> Tuple[bool, str, Any]: + """Run the tool's `to_model_output` mapper, if any. Returns + `(applied, type, value)` where `type` is `"content"` or `"json"`.""" + converter = get_tool_function(tool).get("to_model_output") + if not converter: + return False, "", None + converted = await maybe_await(converter({"output": value, "input": self._parsed_tool_input(tool, call)})) + if isinstance(converted, Mapping) and converted.get("type") == "content": + return True, "content", converted.get("value", []) + if isinstance(converted, Mapping) and converted.get("type") == "json": + return True, "json", converted.get("value") + return False, "", None + + async def _unsent_model_output(self, call: ParsedToolCall, tool: Tool, output: Any) -> Any: + """Unsent results are serialized by `unsent_results_to_api_format`, + which does not know about `to_model_output`. Apply it here so resumed + and approved calls send the model the same output as the main loop.""" + applied, _kind, value = await self._apply_to_model_output(call, tool, output) + return value if applied else output + async def _tool_result_to_output( self, call: ParsedToolCall, tool: Tool, result: Mapping[str, Any] ) -> Dict[str, Any]: if result.get("error") is not None: output: Any = json_dumps({"error": str(result["error"])}) else: - converter = get_tool_function(tool).get("to_model_output") - if converter: - converted = await maybe_await(converter({"output": result.get("result"), "input": call.arguments})) - if isinstance(converted, Mapping) and converted.get("type") == "content": - output = converted.get("value", []) - elif isinstance(converted, Mapping) and converted.get("type") == "json": - output = json_dumps(converted.get("value")) - else: - output = json_dumps(result.get("result")) + applied, kind, value = await self._apply_to_model_output(call, tool, result.get("result")) + if applied and kind == "content": + output = value + elif applied: + output = json_dumps(value) else: output = json_dumps(result.get("result")) return {"type": "function_call_output", "id": f"output_{call.id}", "callId": call.id, "output": output} @@ -711,12 +963,16 @@ async def _run(self) -> Any: hooks = self._hooks try: await self._load_state() + if self._paused_without_decisions: + # No request, no state write, no SessionStart: the getters + # report the pause (see `_paused_error`). + return None self._session_id = self._state.id if self._state is not None else generate_conversation_id() tools: Sequence[Tool] = self.options.get("tools") or [] await self._emit_session_start(tools) - request = await resolve_async_functions(self.options["request"], {"number_of_turns": 0}) + request = dict(await self._resolve_initial_request()) request["stream"] = True base_input = request.get("input") @@ -745,22 +1001,22 @@ async def _run(self) -> Any: fresh_input = hooked_array[len(historical_function_calls) :] if self._state is not None: request["input"] = append_to_messages(historical_input, fresh_input) - if not ( - self._state.pending_tool_calls - and (self.options.get("approve_tool_calls") or self.options.get("reject_tool_calls")) - ): + if not (self._state.pending_tool_calls and self._has_decisions()): self._fresh_items_for_state = list(fresh_input) elif fresh_input: request["input"] = fresh_input current_request = request is_resume_turn = self._resuming_from_client_tools - if ( - self._state is not None - and self._state.pending_tool_calls - and (self.options.get("approve_tool_calls") or self.options.get("reject_tool_calls")) - ): - current_request = await self._build_resume_request(request) + if self._state is not None and self._state.pending_tool_calls and self._has_decisions(): + resume_request = await self._build_resume_request(request) + if resume_request is None: + # Decisions covered only some of the pending calls (or an + # approved call needs re-approval after a PreToolUse + # mutation, or an approved HITL call paused again): the + # conversation stays paused and no request is sent. + return None + current_request = resume_request is_resume_turn = True final_response = None @@ -786,7 +1042,14 @@ async def _run(self) -> Any: turn_type = "tool_round" pending_final_directive = False - response = await self._send_and_track(current_request, turn_type, turn_number) + response = await self._send_and_track( + current_request, + turn_type, + turn_number, + # The forced-final turn's tool_choice "none" is an + # engine-owned override, not the caller's policy. + caller_tool_choice=turn_type != "final", + ) await self._append_event( { "type": "turn.end", @@ -838,6 +1101,38 @@ async def _run(self) -> Any: allow_final_response = self.options.get("allow_final_response") final_response_enabled = allow_final_response is not False resolvable_pending = [c for c in calls if self._call_is_auto_resolvable(c, tools)] + if not final_response_enabled and turn_number == 0 and resolvable_pending: + # With allow_final_response=False a met stop_when means + # no tool from this response runs. The first response + # still goes through the approval check (upstream + # evaluates it before the loop), but pausing for a gated + # call must not execute its auto-approved siblings: they + # are saved as skipped results so the paused turn stays + # well-formed for the resume request. + self._assert_unique_call_ids(calls, tools) + turn_context = {"number_of_turns": turn_number + 1, "turn_request": current_request} + requires_approval, executable_calls, gate_results = await self._resolve_approval_gate( + calls, tools, turn_context + ) + if requires_approval: + if self.options.get("state") is None: + names = ", ".join(call.name for call in requires_approval) + raise ValueError( + f"Tool(s) require approval but no state accessor is configured: {names}" + ) + resolved_gate_ids = {result.call_id for result in gate_results} + gate_results.extend( + create_rejected_result(call.id, call.name, "Tool execution skipped: stop condition met") + for call in executable_calls + if call.id not in resolved_gate_ids + ) + await self._save_state( + pending_tool_calls=requires_approval, + unsent_tool_results=gate_results or None, + status="awaiting_approval", + ) + self._final_response = final_response + return final_response if final_response_enabled and resolvable_pending: self._assert_unique_call_ids(calls, tools) turn_context = {"number_of_turns": turn_number + 1, "turn_request": current_request} @@ -863,6 +1158,7 @@ async def _run(self) -> Any: final_outputs: List[Any] = unsent_results_to_api_format(gate_results) resolved_gate_ids = {result.call_id for result in gate_results} + final_executed_calls: List[ParsedToolCall] = [] for call in executable_calls: if call.id in resolved_gate_ids: continue @@ -876,6 +1172,8 @@ async def _run(self) -> Any: else: result = outcome["result"] if result is not None: + if result.get("error") is None: + final_executed_calls.append(outcome["call"]) output = await self._tool_result_to_output( outcome["call"], matching_tool, result ) @@ -898,6 +1196,14 @@ async def _run(self) -> Any: } ) await self._save_tool_outputs_to_state(final_outputs) + # Apply nextTurnParams from the calls that actually ran + # so they affect the final text-coercion request + # (mirrors the in-loop behavior). + final_params = await execute_next_turn_params_functions( + final_executed_calls, tools, current_request + ) + if final_params: + current_request = apply_next_turn_params_to_request(current_request, final_params) current_request = self._build_final_request( current_request, response, final_outputs, allow_final_response ) @@ -937,11 +1243,9 @@ async def _run(self) -> Any: tool = self._find_tool(call.name, tools) if not tool or not is_auto_resolvable_tool(tool): continue - turn_context = { - "number_of_turns": turn_number + 1, - "tool_call": call, - "turn_request": current_request, - } + # `tool_call` is threaded into the execute context by the + # executor from the call it actually runs (wire shape). + turn_context = {"number_of_turns": turn_number + 1, "turn_request": current_request} outcome = await self._run_tool_with_hooks(tool, call, turn_context) if outcome["type"] == "parse_error": await self._append_event( @@ -980,14 +1284,18 @@ async def _run(self) -> Any: "result": {"error": str(result["error"])} if result.get("error") is not None else result.get("result"), - "preliminaryResults": result.get("preliminary_results"), - "preliminary_results": result.get("preliminary_results"), "timestamp": _now_ms(), } ) output = await self._tool_result_to_output(effective_call, tool, result) outputs.append(output) - executed_calls.append(effective_call) + if result.get("error") is None: + # Only calls whose tool body ran and returned without + # error may drive nextTurnParams, with the input the + # tool actually ran on (including a PreToolUse + # mutation). Blocked, invalid, or failed calls must + # not change the next request. + executed_calls.append(effective_call) self._tool_outputs.append(output) await self._append_event({"type": "tool.call_output", "output": output, "timestamp": _now_ms()}) step.tool_results.append(result) @@ -1074,36 +1382,110 @@ def _assert_unique_call_ids(self, calls: Sequence[ParsedToolCall], tools: Sequen ) seen.add(call.id) - async def _build_resume_request(self, request: Mapping[str, Any]) -> Dict[str, Any]: + async def _build_resume_request(self, request: Mapping[str, Any]) -> Optional[Dict[str, Any]]: + """Apply approve/reject decisions to the persisted pending calls. + + Returns the resume request, or `None` when the conversation stays + paused: a pending call received no decision, an approved call whose + PreToolUse-mutated arguments need their own approval is pending + again, or an approved HITL call paused again. + """ self._fresh_items_for_state = [] - approved = set(self.options.get("approve_tool_calls") or []) - rejected = set(self.options.get("reject_tool_calls") or []) - outputs: List[Any] = [] - if self._state is not None and self._state.unsent_tool_results: - outputs.extend(unsent_results_to_api_format(self._state.unsent_tool_results)) - pending: List[ParsedToolCall] = self._state.pending_tool_calls if self._state is not None else [] - unsent_ids = [result.call_id for result in (self._state.unsent_tool_results or [])] if self._state else [] - seen_ids: set[str] = set(unsent_ids) - for call in pending or []: + tools: Sequence[Tool] = self.options.get("tools") or [] + unsent: List[UnsentToolResult] = list(self._state.unsent_tool_results or []) if self._state else [] + pending: List[ParsedToolCall] = list(self._state.pending_tool_calls or []) if self._state is not None else [] + seen_ids: set[str] = {result.call_id for result in unsent} + for call in pending: if call.id in seen_ids: raise ValueError( f'Saved state has more than one tool call with call_id "{call.id}"; ' "refusing to resume because approvals are matched to calls by call_id." ) seen_ids.add(call.id) - for call in pending or []: - tool = self._find_tool(call.name, self.options.get("tools") or []) - if call.id in rejected: - outputs.append(self._rejected_output(call.id, "Tool call rejected by user")) - elif call.id in approved and tool and is_auto_resolvable_tool(tool): - turn_context = {"number_of_turns": 0} - outcome = await self._run_tool_with_hooks(tool, call, turn_context) - if outcome["type"] == "parse_error": - outputs.append(self._rejected_output(call.id, outcome["error_message"])) - elif outcome["type"] == "hook_blocked": - outputs.append(self._rejected_output(call.id, outcome["reason"])) - elif outcome["result"] is not None: - outputs.append(await self._tool_result_to_output(outcome["call"], tool, outcome["result"])) + + # numberOfTurns is 1-indexed after the initial request (upstream + # `allToolExecutionRounds.length + 1` on a fresh run). + turn_context: Dict[str, Any] = {"number_of_turns": 1} + hitl_paused_ids: set[str] = set() + second_gate: Dict[str, ParsedToolCall] = {} + # Each decision list is de-duplicated in __init__, so an approved + # call executes at most once per resume. + for call_id in self._approved_ids: + found = next((candidate for candidate in pending if candidate.id == call_id), None) + if found is None: + continue + call = found + tool = self._find_tool(call.name, tools) + if not tool or not is_auto_resolvable_tool(tool): + unsent.append(create_rejected_result(call.id, call.name, "Tool not found or not executable")) + continue + + if self._hooks and call.pre_tool_use_applied is not True and not isinstance(call.arguments, str): + prepared = await self._prepare_after_initial_approval(call, tool, tools, turn_context) + if prepared[0] == "blocked": + unsent.append(create_rejected_result(call.id, call.name, prepared[1])) + continue + if prepared[0] == "pending": + second_gate[call.id] = prepared[2] + continue + call = prepared[2] + + outcome = await self._run_tool_with_hooks(tool, call, turn_context) + if outcome["type"] == "parse_error": + unsent.append(create_rejected_result(call.id, call.name, outcome["error_message"])) + elif outcome["type"] == "hook_blocked": + unsent.append(create_rejected_result(call.id, call.name, outcome["reason"])) + elif outcome["result"] is None: + # HITL tool paused on approval -- keep the call visible via + # pending_tool_calls (status becomes awaiting_hitl below). + hitl_paused_ids.add(call.id) + elif outcome["result"].get("error") is not None: + unsent.append(create_rejected_result(call.id, call.name, str(outcome["result"]["error"]))) + else: + effective_call = outcome["call"] + unsent.append( + create_unsent_result( + call.id, + call.name, + await self._unsent_model_output(effective_call, tool, outcome["result"].get("result")), + ) + ) + + for call_id in self._rejected_ids: + rejected = next((candidate for candidate in pending if candidate.id == call_id), None) + if rejected is None: + continue + # Upstream also emits PostToolUseFailure here for calls whose + # PreToolUse ran after an initial approval. This port still runs + # PreToolUse *before* the approval gate (the upstream two-phase + # gate is not ported yet), so `pre_tool_use_applied` is set on + # every held call and emitting here would fire the hook where + # upstream does not. Left out until the two-phase gate lands. + unsent.append(create_rejected_result(rejected.id, rejected.name, "Rejected by user")) + + processed = { + call_id + for call_id in [*self._approved_ids, *self._rejected_ids] + if call_id not in hitl_paused_ids and call_id not in second_gate + } + remaining = [second_gate.get(call.id, call) for call in pending if call.id not in processed] + unresolved_approvals = [call for call in remaining if call.id not in hitl_paused_ids] + if unresolved_approvals: + next_status = "awaiting_approval" + elif hitl_paused_ids: + next_status = "awaiting_hitl" + else: + next_status = "in_progress" + + if next_status != "in_progress": + await self._save_state( + pending_tool_calls=remaining or None, + unsent_tool_results=unsent or None, + status=next_status, + ) + return None + + outputs = unsent_results_to_api_format(unsent) updated_messages = append_to_messages(self._state.messages, outputs) if self._state is not None else outputs await self._save_state( messages=updated_messages, @@ -1113,6 +1495,86 @@ async def _build_resume_request(self, request: Mapping[str, Any]) -> Dict[str, A ) return {**dict(request), "input": updated_messages, "stream": True} + async def _prepare_after_initial_approval( + self, + call: ParsedToolCall, + tool: Tool, + tools: Sequence[Tool], + turn_context: Mapping[str, Any], + ) -> Tuple[str, str, ParsedToolCall]: + """Run PreToolUse for an approved call that has not been through it. + + The human approved the arguments they saw. If PreToolUse rewrites + them, the rewritten call needs its own approval check: returns + `("ready", "", call)` to execute, `("blocked", reason, call)` to reject, + or `("pending", "", mutated_call)` to pause again on the mutated + arguments (marked `pre_tool_use_applied` so the hook does not run a + second time on the next resume). + """ + assert self._hooks is not None + original_input = call.arguments if isinstance(call.arguments, dict) else {} + pre = await self._hooks.emit( + "PreToolUse", + {"tool_name": call.name, "tool_input": original_input}, + tool_name=call.name, + session_id=self._session_id, + ) + if pre.blocked: + block = next((result.get("block") for result in pre.results if result.get("block")), None) + return "blocked", block if isinstance(block, str) else "Blocked by PreToolUse hook", call + if not pre.mutated: + return "ready", "", dataclasses.replace(call, pre_tool_use_applied=True) + mutated = dataclasses.replace(call, arguments=pre.final_payload.get("tool_input"), pre_tool_use_applied=True) + # A mutation that no longer satisfies the schema is refused rather + # than executed or re-queued (upstream `validatePreparedMutation`). + ok, parsed = _parse_tool_arguments(tool, mutated.arguments) + if not ok or not isinstance(parsed, Mapping): + invalid = f'PreToolUse produced invalid input for "{call.name}"' + await self._emit_prepared_failure(mutated, invalid) + return "blocked", invalid, mutated + if not await self._mutated_input_requires_approval(mutated, tools, turn_context): + return "ready", "", mutated + decision, reason = await self._emit_permission_request(mutated, tools) + if decision == "allow": + return "ready", "", mutated + if decision == "deny": + denial = reason or "Denied by PermissionRequest hook" + await self._emit_prepared_failure(mutated, denial) + return "blocked", denial, mutated + return "pending", "", mutated + + async def _mutated_input_requires_approval( + self, call: ParsedToolCall, tools: Sequence[Tool], turn_context: Mapping[str, Any] + ) -> bool: + """Re-check approval for PreToolUse-mutated arguments. Only + input-dependent checks can change their answer: a call-level + `require_approval` function, or a function-valued tool-level + `require_approval`. A blanket `require_approval=True` was already + satisfied by the human's approval, so the mutated call runs.""" + call_level = self.options.get("require_approval") + if callable(call_level): + return await tool_requires_approval(call, tools, turn_context, call_level) + tool = self._find_tool(call.name, tools) + if tool is None or not callable(get_tool_function(tool).get("require_approval")): + return False + return await tool_requires_approval(call, tools, turn_context) + + async def _emit_prepared_failure(self, call: ParsedToolCall, reason: str) -> None: + """PostToolUseFailure for a call that went through PreToolUse but will + not execute (invalid mutation, PermissionRequest deny, user reject).""" + if not self._hooks: + return + await self._hooks.emit( + "PostToolUseFailure", + { + "tool_name": call.name, + "tool_input": call.arguments if isinstance(call.arguments, dict) else {}, + "error": reason, + }, + tool_name=call.name, + session_id=self._session_id, + ) + async def _iter_events_live(self) -> AsyncIterator[Any]: self._ensure_task() index = 0 @@ -1170,12 +1632,15 @@ async def _retry_current_request(self, current_request: Mapping[str, Any], turn_ if new_request.get("tools") is not None: new_request["tool_choice"] = "none" new_request["stream"] = True - return await self._send_and_track(new_request, "retry", turn_number) + return await self._send_and_track(new_request, "retry", turn_number, caller_tool_choice=False) # -- public streaming/result surface ------------------------------------ async def get_response(self) -> Any: - return await self._ensure_task() + response = await self._ensure_task() + if response is None: + raise self._paused_error() or RuntimeError("Response not available") + return response async def get_text(self) -> str: response = await self.get_response() @@ -1229,8 +1694,6 @@ async def get_tool_stream(self) -> AsyncIterator[Dict[str, Any]]: "tool_call_id": get_field(event, "tool_call_id", get_field(event, "toolCallId")), "source": get_field(event, "source", "client"), "result": get_field(event, "result"), - "preliminaryResults": get_field(event, "preliminaryResults"), - "preliminary_results": get_field(event, "preliminary_results"), } elif typ == "tool.call_output": yield {"type": "tool_call_output", "output": get_field(event, "output")} @@ -1347,7 +1810,9 @@ async def get_full_chat_stream(self) -> AsyncIterator[Dict[str, Any]]: yield {"type": "message.complete", "response": await self.get_response()} async def requires_approval(self) -> bool: - await self.get_response() + # Inspection APIs keep working on a paused conversation, so they wait + # for the run without going through get_response()'s pause error. + await self._ensure_task() state = self._state return bool( state @@ -1358,13 +1823,36 @@ async def requires_approval(self) -> bool: ) async def get_pending_tool_calls(self) -> List[ParsedToolCall]: - await self.get_response() + await self._ensure_task() return list(self._state.pending_tool_calls or []) if self._state else [] async def get_state(self) -> Any: - await self.get_response() + await self._ensure_task() return self._state + async def get_usage(self) -> Dict[str, Any]: + """Aggregate token/cost usage across every model call this run made. + + `get_response()` resolves to the *final* round's response, so in a + multi-round tool loop its `usage` block covers only that generation. + This sums the initial request, each tool-round follow-up, the + empty-final retry, the `allow_final_response` final turn, and + approval-resume requests. Same shape as the `SessionEnd` hook's + `total_usage`: `model_calls`, `input_tokens`, `output_tokens`, + `total_tokens`, `cached_tokens`, `reasoning_tokens`, and `cost` only + when the server reported it. + + Waits for the run to finish, but never raises: a failed or paused run + still consumed tokens, so it returns the totals accrued so far (and + warns with the swallowed cause). Await `get_response()` to observe the + failure itself. + """ + try: + await self._ensure_task() + except Exception as error: # noqa: BLE001 - documented never-raises accessor + warnings.warn(f"[get_usage] run failed; reporting totals accrued so far: {error}", stacklevel=2) + return self._snapshot_session_usage() + def cancel(self) -> None: if self._run_task is not None: self._run_task.cancel() diff --git a/src/openrouter_agent/next_turn_params.py b/src/openrouter_agent/next_turn_params.py index 2c670e5..af91285 100644 --- a/src/openrouter_agent/next_turn_params.py +++ b/src/openrouter_agent/next_turn_params.py @@ -5,11 +5,27 @@ from ._utils import maybe_await from .tool_types import ParsedToolCall, Tool, get_tool_function, is_client_tool -NEXT_TURN_KEYS = ("input", "model", "models", "temperature", "max_output_tokens", "top_p", "top_k", "instructions") +NEXT_TURN_KEYS = ( + "input", + "tool_choice", + "model", + "models", + "temperature", + "max_output_tokens", + "top_p", + "top_k", + "instructions", +) def build_next_turn_params_context(request: Mapping[str, Any]) -> Dict[str, Any]: - return {key: request.get(key) for key in NEXT_TURN_KEYS if key in request} + context = {key: request.get(key) for key in NEXT_TURN_KEYS if key in request} + # Always present (possibly None), like upstream: a tool computing the next + # `tool_choice` reads the current one to widen it rather than rebuild it -- + # changing which tools are reachable without touching `tools`, so the + # provider's prompt-cache prefix survives. + context.setdefault("tool_choice", request.get("tool_choice")) + return context async def execute_next_turn_params_functions( diff --git a/src/openrouter_agent/stream_transformers.py b/src/openrouter_agent/stream_transformers.py index a57341e..9ecb548 100644 --- a/src/openrouter_agent/stream_transformers.py +++ b/src/openrouter_agent/stream_transformers.py @@ -38,8 +38,43 @@ def extract_responses_message_from_response(response: Any) -> Any: raise ValueError("Response does not contain a message output item") +def is_truncated_at_max_output_tokens(response: Any) -> bool: + """Whether the provider stopped this response at `max_output_tokens`. + + The `function_call` items on such a response are an unfinished batch: the + model asked for the set together, and the last one carries whatever + argument prefix fit in the budget. Executing the complete ones would hand + the model a result set with a silent hole, and spend side effects on a turn + that truncates the same way on the same budget, so none of them run. The + caller sees every item and `incomplete_details`, and resumes once the budget + is raised. + """ + if get_field(response, "status") != "incomplete": + return False + details = get_field(response, "incomplete_details", None) + if details is None: + details = get_field(response, "incompleteDetails", None) + return get_field(details, "reason") == "max_output_tokens" + + +def response_has_tool_calls(response: Any) -> bool: + """Whether a response carries tool calls the loop should execute. A response + truncated at `max_output_tokens` has none, even when its output carries a + cut-off `function_call` item.""" + if is_truncated_at_max_output_tokens(response): + return False + return any(get_field(item, "type") == "function_call" for item in _output_items(response)) + + def extract_tool_calls_from_response(response: Any) -> List[ParsedToolCall]: + """Extract every tool call from a completed response. + + A response truncated at `max_output_tokens` yields no tool calls: see + `is_truncated_at_max_output_tokens`. + """ calls: List[ParsedToolCall] = [] + if is_truncated_at_max_output_tokens(response): + return calls for item in _output_items(response): if get_field(item, "type") != "function_call": continue diff --git a/src/openrouter_agent/tool.py b/src/openrouter_agent/tool.py index 4bd894b..1d0ae3c 100644 --- a/src/openrouter_agent/tool.py +++ b/src/openrouter_agent/tool.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import Any, Dict, Optional +from typing import Any, Dict, Mapping, Optional from .tool_types import SHARED_CONTEXT_KEY, ToolType @@ -19,7 +19,21 @@ def tool( on_tool_called: Any = None, on_response_received: Any = None, to_model_output: Any = None, + strict: Optional[bool] = None, + wire_input_schema: Optional[Mapping[str, Any]] = None, ) -> Dict[str, Any]: + """Build a client tool. + + `strict` is serialized onto the wire tool definition so providers can + enforce structured-outputs-style schema adherence on tool-call arguments + (OpenAI-style strict mode requires every object property in `required`; + use `Optional[...]` without a default for conceptually optional values). + `None` leaves the provider default. + + `wire_input_schema` (manual tools only, `execute=False`) is a caller-owned + JSON Schema serialized to the model instead of one generated from + `input_schema`, which still describes the call's arguments. + """ if name == SHARED_CONTEXT_KEY: raise ValueError('Tool name "shared" is reserved for shared context. Choose a different name.') fn: Dict[str, Any] = {"name": name, "input_schema": input_schema} @@ -37,6 +51,14 @@ def tool( fn["require_approval"] = require_approval if to_model_output is not None: fn["to_model_output"] = to_model_output + if strict is not None: + fn["strict"] = strict + if wire_input_schema is not None: + if execute is not False or on_tool_called is not None: + # Upstream restricts this at the type level (`wireInputSchema?: + # never` on executable configs); Python enforces it at runtime. + raise ValueError(f'Tool "{name}": wire_input_schema is only supported on manual tools (execute=False).') + fn["wire_input_schema"] = wire_input_schema if on_tool_called is not None: if output_schema is None: raise ValueError(f'HITL tool "{name}" must declare an output_schema.') @@ -54,11 +76,34 @@ def server_tool(config: Dict[str, Any]) -> Dict[str, Any]: return {"_brand": "server-tool", "config": dict(config)} -def mark_mcp(tool_to_mark: Dict[str, Any]) -> Dict[str, Any]: +def mark_mcp( + tool_to_mark: Dict[str, Any], + *, + annotations: Optional[Mapping[str, Any]] = None, + wire_input_schema: Optional[Mapping[str, Any]] = None, +) -> Dict[str, Any]: """Add the additive MCP brand to an already-built client tool (see `is_mcp_tool`). Non-mutating: returns a shallow copy carrying `_mcp`, so - the tool's runtime behavior and wire shape are unchanged -- only the - `is_mcp_tool` check now identifies it as MCP-originated. Used by - `@openrouter/mcp`-equivalent integrations to mark wrapped remote tools. + the tool's runtime behavior is unchanged -- only the `is_mcp_tool` check + now identifies it as MCP-originated. Used by `@openrouter/mcp`-equivalent + integrations to mark wrapped remote tools. + + `annotations` records the server's `tools/list` annotations + (`readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`, + `title`) on the branded tool so a consumer can read them back. + `wire_input_schema` is the server's own JSON Schema for the tool's + arguments; it is serialized to the model in place of one regenerated from + `input_schema`, which keeps validating the call. """ - return {**tool_to_mark, "_mcp": True} + marked: Dict[str, Any] = {**tool_to_mark, "_mcp": True} + if annotations is not None: + marked["annotations"] = annotations + # A non-object root is not a usable tool schema; the generated object + # schema is serialized instead. + if ( + wire_input_schema is not None + and wire_input_schema.get("type") == "object" + and isinstance(marked.get("function"), Mapping) + ): + marked["function"] = {**marked["function"], "wire_input_schema": wire_input_schema} + return marked diff --git a/src/openrouter_agent/tool_context.py b/src/openrouter_agent/tool_context.py index 3b8d152..0f93eac 100644 --- a/src/openrouter_agent/tool_context.py +++ b/src/openrouter_agent/tool_context.py @@ -53,6 +53,27 @@ def _filter_schema_keys(schema: Any, value: Mapping[str, Any]) -> Dict[str, Any] return dict(value) +def _parse_partial_against_schema( + schema: Any, partial: Mapping[str, Any], existing: Mapping[str, Any] +) -> Dict[str, Any]: + """Filter a partial context update to the schema's known keys and return + the schema's *parsed* value for each updated key, so field transforms, + defaults and coercions apply to the stored value. The merged result + (existing values plus the update) is validated as a whole first, so + model-level validators are enforced before anything is stored. Raises on + invalid input; the caller leaves the stored context unchanged.""" + filtered = _filter_schema_keys(schema, partial) + if schema is None: + return filtered + validated = validate_schema(schema, {**dict(existing), **filtered}) + if hasattr(validated, "model_dump"): + dumped = validated.model_dump() + return {key: dumped[key] for key in filtered if key in dumped} + if isinstance(validated, Mapping): + return {key: validated[key] for key in filtered if key in validated} + return filtered + + class LiveContext(MappingABC): def __init__(self, getter: Callable[[], Dict[str, Any]]) -> None: self._getter = getter @@ -113,12 +134,14 @@ def shared() -> Dict[str, Any]: return store.get_tool_context(SHARED_CONTEXT_KEY) def set_context(partial: Mapping[str, Any]) -> None: - filtered = _filter_schema_keys(fn.get("context_schema"), partial) - store.merge_tool_context(name, filtered) + parsed = _parse_partial_against_schema(fn.get("context_schema"), partial, store.get_tool_context(name)) + store.merge_tool_context(name, parsed) def set_shared_context(partial: Mapping[str, Any]) -> None: - filtered = _filter_schema_keys(shared_context_schema, partial) - store.merge_tool_context(SHARED_CONTEXT_KEY, filtered) + parsed = _parse_partial_against_schema( + shared_context_schema, partial, store.get_tool_context(SHARED_CONTEXT_KEY) + ) + store.merge_tool_context(SHARED_CONTEXT_KEY, parsed) base.update( { diff --git a/src/openrouter_agent/tool_executor.py b/src/openrouter_agent/tool_executor.py index 93617a9..0d7bf7b 100644 --- a/src/openrouter_agent/tool_executor.py +++ b/src/openrouter_agent/tool_executor.py @@ -16,6 +16,25 @@ ) +def to_function_call_item(tool_call: ParsedToolCall) -> Dict[str, Any]: + """Convert an executor-shaped `ParsedToolCall` (whose `id` is the wire + `call_id` and whose `arguments` are already parsed) back into the + wire-shaped `function_call` item. `arguments` is always re-serialized, so + it is semantically equal to the wire arguments but not guaranteed + byte-identical.""" + try: + arguments = json_dumps(tool_call.arguments) + except (TypeError, ValueError): + arguments = "{}" + return { + "type": "function_call", + "id": tool_call.id, + "callId": tool_call.id, + "name": tool_call.name, + "arguments": arguments, + } + + def convert_zod_to_json_schema(schema: Any) -> Dict[str, Any]: return schema_to_json_schema(schema) @@ -44,10 +63,21 @@ def convert_tools_to_api_format(tools: Sequence[Tool]) -> List[Dict[str, Any]]: converted.append(dict(config) if isinstance(config, Mapping) else {}) continue fn = get_tool_function(item) + wire_schema = fn.get("wire_input_schema") + # A caller-owned (manual tool) or server-supplied (MCP) JSON Schema is + # sent verbatim -- sanitized of `~`-prefixed keys, as a copy -- instead + # of one regenerated from `input_schema`. + if wire_schema is not None: + parameters = sanitize_json_schema(wire_schema) + else: + parameters = schema_to_json_schema(fn.get("input_schema")) api: Dict[str, Any] = { "type": "function", "name": fn.get("name"), - "parameters": schema_to_json_schema(fn.get("input_schema")), + # Passed through instead of hardcoded: `None` (null) leaves the + # provider default, `True`/`False` are sent as declared. + "strict": fn.get("strict"), + "parameters": parameters, } if fn.get("description") is not None: api["description"] = fn["description"] @@ -84,7 +114,9 @@ async def execute_generator_tool( ) -> Dict[str, Any]: fn = get_tool_function(tool) source = "mcp" if is_mcp_tool(tool) else "client" - preliminary: List[Any] = [] + # Yields are broadcast live via `on_preliminary_result`; they are not + # accumulated onto the result (upstream 1.0.0 dropped + # `preliminaryResults` to stop per-call memory growth). try: args = validate_schema(fn.get("input_schema"), tool_call.arguments) produced = fn["execute"](args, context) @@ -99,7 +131,6 @@ async def execute_generator_tool( has_pending_output = False async def emit_preliminary(event: Any) -> None: - preliminary.append(event) if on_preliminary_result is not None: await maybe_await(on_preliminary_result(tool_call.id, event)) @@ -138,7 +169,6 @@ async def emit_preliminary(event: Any) -> None: "tool_name": tool_call.name, "source": source, "result": final, - "preliminary_results": preliminary, } except Exception as exc: return { @@ -146,7 +176,6 @@ async def emit_preliminary(event: Any) -> None: "tool_name": tool_call.name, "source": source, "result": None, - "preliminary_results": preliminary, "error": exc, } @@ -183,6 +212,11 @@ async def execute_tool( ) -> Optional[Dict[str, Any]]: if not is_client_tool(tool): return None + # `tool_call` is part of the tool-facing context contract. A caller-provided + # one wins; otherwise thread the executed call, converted back to the + # wire-shaped `function_call` item, so every execution path carries it. + if turn_context is None or turn_context.get("tool_call") is None: + turn_context = {**dict(turn_context or {}), "tool_call": to_function_call_item(tool_call)} context = build_tool_execute_context(tool, turn_context, context_store, shared_context_schema) if is_hitl_tool(tool): return await execute_hitl_tool(tool, tool_call, context) diff --git a/src/openrouter_agent/tool_types.py b/src/openrouter_agent/tool_types.py index 8199c6c..0fcaaf2 100644 --- a/src/openrouter_agent/tool_types.py +++ b/src/openrouter_agent/tool_types.py @@ -59,6 +59,11 @@ class ConversationState: #: Optional so legacy (pre-version-field) states remain constructible; #: absence is treated as version 1 by `deserialize_conversation_state`. version: Optional[int] = None + #: Identity of a caller-forced `tool_choice` that already produced a tool + #: call in this logical run, so resumed follow-ups keep it relaxed to + #: `"auto"` (upstream `consumedForcedToolChoiceKey`). Additive within + #: state version 1; cleared when the run completes. + consumed_forced_tool_choice_key: Optional[str] = None @dataclass(frozen=True) @@ -133,6 +138,8 @@ class ToolExecutionResult(TypedDict, total=False): #: locally-defined tools. See `is_mcp_tool` / `mark_mcp`. source: Literal["client", "mcp"] result: object + #: Kept for type compatibility; no longer populated (yields are broadcast + #: live as `tool.preliminary_result` events instead). preliminary_results: List[object] error: BaseException @@ -163,6 +170,7 @@ class ToolResultEvent(TypedDict, total=False): #: otherwise. See `is_mcp_tool` / `mark_mcp`. source: Literal["client", "mcp"] result: object + #: Kept for type compatibility; the runtime no longer copies every yield here. preliminaryResults: List[object] preliminary_results: List[object] timestamp: int diff --git a/tests/_fixtures.py b/tests/_fixtures.py index dd1f3c1..22a3f05 100644 --- a/tests/_fixtures.py +++ b/tests/_fixtures.py @@ -25,7 +25,7 @@ from __future__ import annotations import re -from typing import Any, Dict, List, Mapping, Optional +from typing import Any, Callable, Dict, List, Mapping, Optional from openrouter_agent.tool_types import ConversationState @@ -123,6 +123,18 @@ def usage_block(**overrides: Any) -> Dict[str, Any]: return base +def recording(log: List[Any], result: Any, pick: Optional[Callable[[Any], Any]] = None) -> Callable[[Any, Any], Any]: + """An `execute` (or hook handler) that records each call's first argument -- + or `pick(arg)` -- into `log` and returns `result`. Lets a test assert an + exact call count/sequence without a hand-written closure per tool.""" + + def run(params: Any, _context: Any) -> Any: + log.append(pick(params) if pick is not None else params) + return result + + return run + + class QueuedResponses: """Fake `client.beta.responses` returning queued payloads in order. diff --git a/tests/unit/test_approval_gate_regressions.py b/tests/unit/test_approval_gate_regressions.py index ece1393..d1a64ab 100644 --- a/tests/unit/test_approval_gate_regressions.py +++ b/tests/unit/test_approval_gate_regressions.py @@ -2,8 +2,11 @@ from __future__ import annotations +import dataclasses +import json from typing import Any, List, Mapping +import pytest from pydantic import BaseModel from openrouter_agent import HookEntry, HookName, HooksManager, call_model, step_count_is, tool @@ -291,3 +294,507 @@ def needs_approval(params: Any, _context: Any) -> bool: assert predicate_calls == [] assert state.stored is not None and state.stored.status == "awaiting_approval" + + +# --------------------------------------------------------------------------- +# Approval decisions are validated before anything runs, and a paused +# conversation resumed without decisions stays paused (upstream #131, +# typescript-sdk#517/#518). +# --------------------------------------------------------------------------- + + +class _GatedInput(BaseModel): + v: str + + +def _function_call_outputs(request: Mapping[str, Any]) -> List[Any]: + # Outgoing items use snake_case `call_id`, not upstream's `callId`: + # ModelResult._send normalizes at the transport boundary + # (model_result.py `_send`). + return [ + item for item in request["input"] if isinstance(item, Mapping) and item.get("type") == "function_call_output" + ] + + +async def _pause_on_gated_calls(call_ids: List[str]) -> Any: + executed: List[Any] = [] + + def execute(params: _GatedInput, _context: Any) -> Any: + executed.append(params.v) + return {"ok": True} + + gated = tool(name="gated", input_schema=_GatedInput, output_schema=dict, require_approval=True, execute=execute) + state = MemoryStateAccessor() + await call_model( + QueuedClient( + [make_response("resp_pause", [function_call_item(cid, "gated", '{"v":"x"}') for cid in call_ids])] + ), + {"model": "test-model", "input": "run the gated action", "tools": [gated], "state": state}, + ).get_response() + assert state.stored is not None and state.stored.status == "awaiting_approval" + assert executed == [] + return gated, state, executed + + +async def test_executes_an_approved_call_once_when_its_id_is_listed_twice() -> None: + gated, state, executed = await _pause_on_gated_calls(["call_1"]) + client = QueuedClient([text_response("resp_done", "Done.")]) + + text = await call_model( + client, + { + "model": "test-model", + "input": [], + "tools": [gated], + "state": state, + "approve_tool_calls": ["call_1", "call_1"], + }, + ).get_text() + + assert text == "Done." + assert executed == ["x"] + assert [item["call_id"] for item in _function_call_outputs(client.requests[0])] == ["call_1"] + + +async def test_records_a_rejection_once_when_its_id_is_listed_twice() -> None: + gated, state, executed = await _pause_on_gated_calls(["call_1"]) + client = QueuedClient([text_response("resp_done", "Done.")]) + + await call_model( + client, + { + "model": "test-model", + "input": [], + "tools": [gated], + "state": state, + "reject_tool_calls": ["call_1", "call_1"], + }, + ).get_response() + + assert executed == [] + assert [item["call_id"] for item in _function_call_outputs(client.requests[0])] == ["call_1"] + + +async def test_refuses_an_id_that_is_both_approved_and_rejected_before_anything_runs() -> None: + gated, state, executed = await _pause_on_gated_calls(["call_1", "call_2"]) + before = state.stored + saves_before = len(state.saved) + client = QueuedClient([]) + + with pytest.raises(ValueError, match="both approved and rejected: call_2"): + call_model( + client, + { + "model": "test-model", + "input": [], + "tools": [gated], + "state": state, + "approve_tool_calls": ["call_1", "call_2"], + "reject_tool_calls": ["call_2"], + }, + ) + + assert executed == [] + assert client.requests == [] + assert state.stored is before + assert len(state.saved) == saves_before + + +async def test_stays_awaiting_approval_and_sends_no_request_when_resumed_without_decisions() -> None: + gated, state, executed = await _pause_on_gated_calls(["call_1"]) + before = state.stored + saves_before = len(state.saved) + client = QueuedClient([]) + + result = call_model( + client, {"model": "test-model", "input": "run the gated action", "tools": [gated], "state": state} + ) + + with pytest.raises(RuntimeError, match="awaiting approval.*call_1"): + await result.get_response() + with pytest.raises(RuntimeError, match="awaiting approval"): + await result.get_text() + assert await result.requires_approval() is True + assert [call.id for call in await result.get_pending_tool_calls()] == ["call_1"] + assert client.requests == [] + assert executed == [] + assert state.stored is before + assert len(state.saved) == saves_before + + # The pause still resolves normally once a decision is supplied. + await call_model( + QueuedClient([text_response("resp_done", "Done.")]), + {"model": "test-model", "input": [], "tools": [gated], "state": state, "approve_tool_calls": ["call_1"]}, + ).get_response() + assert executed == ["x"] + assert state.stored is not None and state.stored.status == "complete" + + +async def test_reports_the_pause_when_decisions_cover_only_some_pending_calls() -> None: + gated, state, executed = await _pause_on_gated_calls(["call_1", "call_2"]) + client = QueuedClient([]) + + result = call_model( + client, {"model": "test-model", "input": [], "tools": [gated], "state": state, "approve_tool_calls": ["call_1"]} + ) + + with pytest.raises(RuntimeError, match="awaiting approval.*call_2"): + await result.get_response() + assert executed == ["x"] + assert client.requests == [] + assert state.stored is not None and state.stored.status == "awaiting_approval" + assert [call.id for call in state.stored.pending_tool_calls or []] == ["call_2"] + # The executed call's output is kept for the eventual resume request. + assert [r.call_id for r in state.stored.unsent_tool_results or []] == ["call_1"] + + +class _Answer(BaseModel): + answer: str + + +async def _pause_on_hitl_call() -> Any: + called: List[Any] = [] + received: List[Any] = [] + + def on_tool_called(params: _GatedInput, _context: Any) -> Any: + called.append(params.v) + return None + + def on_response_received(raw: Any, _context: Any) -> Any: + received.append(raw) + return {"answer": str(raw["answer"]).upper()} + + review = tool( + name="gated", + input_schema=_GatedInput, + output_schema=_Answer, + on_tool_called=on_tool_called, + on_response_received=on_response_received, + ) + state = MemoryStateAccessor() + await call_model( + QueuedClient([tool_call_response("resp_hitl", "gated", call_id="call_hitl", arguments='{"v":"x"}')]), + {"model": "test-model", "input": "review", "tools": [review], "state": state}, + ).get_response() + assert state.stored is not None and state.stored.status == "awaiting_hitl" + assert called == ["x"] + return review, state, called, received + + +def _caller_output(call_id: str, output: Any) -> dict: + return {"type": "function_call_output", "id": f"output_{call_id}", "callId": call_id, "output": json.dumps(output)} + + +async def test_stays_awaiting_hitl_and_sends_no_request_when_resumed_without_decisions() -> None: + review, state, called, received = await _pause_on_hitl_call() + before = state.stored + + for input_value in ["a new user message", [_caller_output("call_other", {"answer": "yes"})]]: + client = QueuedClient([]) + result = call_model(client, {"model": "test-model", "input": input_value, "tools": [review], "state": state}) + with pytest.raises( + RuntimeError, + match="awaiting HITL input.*call_hitl.*function_call_output.*input supplied with this call was not sent", + ): + await result.get_response() + assert client.requests == [] + + assert called == ["x"] + assert received == [] + assert state.stored is before + + +async def test_resumes_awaiting_hitl_when_input_carries_a_function_call_output_for_the_paused_call() -> None: + review, state, called, received = await _pause_on_hitl_call() + client = QueuedClient([text_response("resp_done", "Done.")]) + + text = await call_model( + client, + { + "model": "test-model", + "input": [_caller_output("call_hitl", {"answer": "yes"})], + "tools": [review], + "state": state, + }, + ).get_text() + + assert text == "Done." + assert received == [{"answer": "yes"}] + assert called == ["x"] # the paused call was not re-run + assert len(client.requests) == 1 + outputs = _function_call_outputs(client.requests[0]) + assert [(o["call_id"], o["output"]) for o in outputs] == [("call_hitl", '{"answer":"YES"}')] + assert state.stored is not None and state.stored.status == "complete" + + +async def test_resolves_a_function_valued_input_once_when_it_resumes_awaiting_hitl() -> None: + review, state, _called, received = await _pause_on_hitl_call() + calls: List[Any] = [] + + def input_fn(_ctx: Any) -> Any: + calls.append(_ctx) + return [_caller_output("call_hitl", {"answer": "yes"})] + + text = await call_model( + QueuedClient([text_response("resp_done", "Done.")]), + {"model": "test-model", "input": input_fn, "tools": [review], "state": state}, + ).get_text() + + assert text == "Done." + assert len(calls) == 1 + assert len(received) == 1 + + +async def test_stays_awaiting_approval_when_input_carries_a_function_call_output_for_the_gated_call() -> None: + gated, state, executed = await _pause_on_gated_calls(["call_1"]) + before = state.stored + client = QueuedClient([]) + + result = call_model( + client, + {"model": "test-model", "input": [_caller_output("call_1", {"ok": True})], "tools": [gated], "state": state}, + ) + + with pytest.raises(RuntimeError, match="awaiting approval.*call_1.*input supplied with this call was not sent"): + await result.get_response() + assert client.requests == [] + assert executed == [] + assert state.stored is before + + +async def test_rejects_every_response_and_stream_getter_with_the_awaiting_error_on_a_paused_resume() -> None: + gated, state, _executed = await _pause_on_gated_calls(["call_1"]) + client = QueuedClient([]) + result = call_model(client, {"model": "test-model", "input": [], "tools": [gated], "state": state}) + + async def first(stream: Any) -> Any: + return await stream.__anext__() + + consumers = { + "get_response": lambda: result.get_response(), + "get_text": lambda: result.get_text(), + "get_tool_calls": lambda: result.get_tool_calls(), + "get_text_stream": lambda: first(result.get_text_stream()), + "get_reasoning_stream": lambda: first(result.get_reasoning_stream()), + "get_full_responses_stream": lambda: first(result.get_full_responses_stream()), + "get_items_stream": lambda: first(result.get_items_stream()), + "get_new_messages_stream": lambda: first(result.get_new_messages_stream()), + "get_tool_stream": lambda: first(result.get_tool_stream()), + "get_tool_calls_stream": lambda: first(result.get_tool_calls_stream()), + } + for name, consume in consumers.items(): + with pytest.raises(RuntimeError, match="awaiting approval.*call_1"): + await consume() + assert client.requests == [], name + + assert await result.requires_approval() is True + assert [call.id for call in await result.get_pending_tool_calls()] == ["call_1"] + assert (await result.get_state()).status == "awaiting_approval" + + +async def test_continues_a_paused_state_whose_pending_tool_calls_is_empty() -> None: + cases: List[Any] = [("awaiting_approval", []), ("awaiting_approval", None), ("awaiting_hitl", [])] + for status, pending in cases: + gated, state, executed = await _pause_on_gated_calls(["call_1"]) + assert state.stored is not None + state.stored = dataclasses.replace(state.stored, status=status, pending_tool_calls=pending) + client = QueuedClient([text_response("resp_done", "Done.")]) + + text = await call_model( + client, {"model": "test-model", "input": [], "tools": [gated], "state": state} + ).get_text() + + assert text == "Done." + assert len(client.requests) == 1 + assert executed == [] + assert state.stored.status == "complete" + + +async def test_caps_the_pending_ids_listed_in_the_awaiting_error_and_omits_the_input_note_without_input() -> None: + gated, state, _executed = await _pause_on_gated_calls([f"call_{i + 1}" for i in range(25)]) + result = call_model(QueuedClient([]), {"model": "test-model", "input": [], "tools": [gated], "state": state}) + + with pytest.raises(RuntimeError) as caught: + await result.get_response() + + message = str(caught.value) + assert "call_1, call_2," in message + assert "call_10, ... (15 more)" in message + assert "call_11" not in message + assert "was not sent" not in message + + +async def test_a_duplicated_id_cannot_bypass_re_approval_after_a_pre_tool_use_mutation() -> None: + executed: List[Any] = [] + + def execute(params: _GatedInput, _context: Any) -> Any: + executed.append(params.v) + return {"ok": True} + + gated = tool( + name="gated", + input_schema=_GatedInput, + output_schema=dict, + require_approval=lambda _params, _ctx: True, + execute=execute, + ) + state = MemoryStateAccessor() + await call_model( + QueuedClient([tool_call_response("resp_pause", "gated", call_id="call_1", arguments='{"v":"reviewed"}')]), + {"model": "test-model", "input": "go", "tools": [gated], "state": state}, + ).get_response() + assert state.stored is not None and state.stored.status == "awaiting_approval" + + hooks = HooksManager() + hooks.on(HookName.PreToolUse.value, HookEntry(handler=lambda _p, _c: {"mutated_input": {"v": "mutated"}})) + client = QueuedClient([]) + result = call_model( + client, + { + "model": "test-model", + "input": [], + "tools": [gated], + "hooks": hooks, + "state": state, + "approve_tool_calls": ["call_1", "call_1"], + }, + ) + + # The human approved {"v": "reviewed"}; the mutated arguments need their + # own approval, so nothing executes and the call is pending again. + with pytest.raises(RuntimeError, match="awaiting approval.*call_1"): + await result.get_response() + assert executed == [] + assert client.requests == [] + assert state.stored.status == "awaiting_approval" + pending = state.stored.pending_tool_calls or [] + assert [(c.id, c.name, c.arguments, c.pre_tool_use_applied) for c in pending] == [ + ("call_1", "gated", {"v": "mutated"}, True) + ] + + +def _mutating_hooks(mutated: Any, failures: List[Any]) -> HooksManager: + hooks = HooksManager() + hooks.on(HookName.PreToolUse.value, HookEntry(handler=lambda _p, _c: {"mutated_input": mutated})) + hooks.on(HookName.PostToolUseFailure.value, HookEntry(handler=lambda payload, _c: failures.append(payload))) + return hooks + + +async def test_blanket_require_approval_runs_the_approved_call_after_a_pre_tool_use_mutation() -> None: + # Only input-dependent checks are re-run on mutated arguments: a blanket + # `require_approval=True` was satisfied by the human's approval. + gated, state, executed = await _pause_on_gated_calls(["call_1"]) + client = QueuedClient([text_response("resp_done", "Done.")]) + + text = await call_model( + client, + { + "model": "test-model", + "input": [], + "tools": [gated], + "hooks": _mutating_hooks({"v": "mutated"}, []), + "state": state, + "approve_tool_calls": ["call_1"], + }, + ).get_text() + + assert text == "Done." + assert executed == ["mutated"] + assert len(client.requests) == 1 + assert state.stored is not None and state.stored.status == "complete" + + +async def test_a_mutation_that_fails_the_input_schema_is_blocked_on_resume() -> None: + gated, state, executed = await _pause_on_gated_calls(["call_1"]) + failures: List[Any] = [] + client = QueuedClient([text_response("resp_done", "Done.")]) + + await call_model( + client, + { + "model": "test-model", + "input": [], + "tools": [gated], + "hooks": _mutating_hooks({"v": 123}, failures), + "state": state, + "approve_tool_calls": ["call_1"], + }, + ).get_text() + + assert executed == [] + outputs = _function_call_outputs(client.requests[0]) + assert [(o["call_id"], json.loads(o["output"])) for o in outputs] == [ + ("call_1", {"error": 'PreToolUse produced invalid input for "gated"'}) + ] + assert [f["error"] for f in failures] == ['PreToolUse produced invalid input for "gated"'] + + +async def test_rejecting_a_held_call_emits_no_post_tool_use_failure() -> None: + # Upstream emits nothing on an ordinary reject of a call held at the + # initial gate (PreToolUse never ran for it there). + gated, state, executed = await _pause_on_gated_calls(["call_1"]) + failures: List[Any] = [] + hooks = HooksManager() + hooks.on(HookName.PostToolUseFailure.value, HookEntry(handler=lambda payload, _c: failures.append(payload))) + client = QueuedClient([text_response("resp_done", "Done.")]) + + await call_model( + client, + { + "model": "test-model", + "input": [], + "tools": [gated], + "hooks": hooks, + "state": state, + "reject_tool_calls": ["call_1"], + }, + ).get_text() + + assert executed == [] + assert failures == [] + outputs = _function_call_outputs(client.requests[0]) + assert [json.loads(o["output"]) for o in outputs] == [{"error": "Rejected by user"}] + + +async def test_a_permission_request_deny_on_mutated_arguments_blocks_and_reports_failure() -> None: + executed: List[Any] = [] + + def execute(params: _GatedInput, _context: Any) -> Any: + executed.append(params.v) + return {"ok": True} + + gated = tool( + name="gated", + input_schema=_GatedInput, + output_schema=dict, + require_approval=lambda params, _ctx: params["v"] != "safe", + execute=execute, + ) + state = MemoryStateAccessor() + await call_model( + QueuedClient([tool_call_response("resp_pause", "gated", call_id="call_1", arguments='{"v":"x"}')]), + {"model": "test-model", "input": "go", "tools": [gated], "state": state}, + ).get_response() + assert state.stored is not None and state.stored.status == "awaiting_approval" + + failures: List[Any] = [] + hooks = _mutating_hooks({"v": "dangerous"}, failures) + hooks.on(HookName.PermissionRequest.value, HookEntry(handler=lambda _p, _c: {"decision": "deny", "reason": "no"})) + client = QueuedClient([text_response("resp_done", "Done.")]) + + await call_model( + client, + { + "model": "test-model", + "input": [], + "tools": [gated], + "hooks": hooks, + "state": state, + "approve_tool_calls": ["call_1"], + }, + ).get_text() + + assert executed == [] + assert [(f["tool_name"], f["error"]) for f in failures] == [("gated", "no")] + outputs = _function_call_outputs(client.requests[0]) + assert [json.loads(o["output"]) for o in outputs] == [{"error": "no"}] diff --git a/tests/unit/test_call_model.py b/tests/unit/test_call_model.py index 83be11a..ac5175c 100644 --- a/tests/unit/test_call_model.py +++ b/tests/unit/test_call_model.py @@ -2,7 +2,10 @@ from typing import Any, Dict, List +import pytest + from openrouter_agent import call_model, step_count_is, tool +from openrouter_agent.call_model import UNSUPPORTED_CALL_MODEL_OPTIONS from tests._fixtures import MemoryStateAccessor, QueuedClient, text_response, tool_call_response, usage_block @@ -106,3 +109,11 @@ async def test_user_input_persists_with_response_in_state() -> None: assert accessor.stored.status == "complete" assert accessor.stored.messages[0] == {"role": "user", "content": "hello"} assert accessor.stored.messages[-1]["type"] == "message" + + +async def test_unsupported_upstream_options_are_refused_instead_of_sent() -> None: + for key in UNSUPPORTED_CALL_MODEL_OPTIONS: + client = QueuedClient([]) + with pytest.raises(NotImplementedError, match=key): + call_model(client, {"model": "m", "input": "hi", key: True}) + assert client.requests == [] diff --git a/tests/unit/test_call_model_active_tools.py b/tests/unit/test_call_model_active_tools.py new file mode 100644 index 0000000..fe66c49 --- /dev/null +++ b/tests/unit/test_call_model_active_tools.py @@ -0,0 +1,77 @@ +"""Ported from upstream tests/unit/call-model-active-tools.test.ts (the +`activeTools` option from #31). The tool-set snapshot and async `task` helper +cases are not ported: this port has no tool-set module or async tools yet.""" + +from __future__ import annotations + +from typing import Any, List + +from openrouter_agent import call_model, server_tool, tool +from tests._fixtures import QueuedClient, text_response, tool_call_response, recording + +_a = tool(name="a", input_schema=dict, execute=lambda _p, _c: {"ok": "a"}) +_b = tool(name="b", input_schema=dict, execute=lambda _p, _c: {"ok": "b"}) +_search = server_tool({"type": "web_search"}) + + +def _sent_names(client: QueuedClient) -> List[Any]: + return [t.get("name", t.get("type")) for t in client.requests[0].get("tools") or []] + + +async def test_sends_only_active_tools_when_active_tools_is_provided() -> None: + client = QueuedClient([text_response("r1", "hi")]) + + await call_model( + client, {"model": "m", "input": "hi", "tools": [_a, _b, _search], "active_tools": ["b"]} + ).get_text() + + # Server tools are always kept; the option never reaches the wire. + assert _sent_names(client) == ["b", "web_search"] + assert "active_tools" not in client.requests[0] + + +async def test_silently_ignores_unknown_active_tools_names() -> None: + client = QueuedClient([text_response("r1", "hi")]) + + await call_model(client, {"model": "m", "input": "hi", "tools": [_a, _b], "active_tools": ["a", "nope"]}).get_text() + + assert _sent_names(client) == ["a"] + + +async def test_sends_all_tools_when_active_tools_is_omitted() -> None: + client = QueuedClient([text_response("r1", "hi")]) + + await call_model(client, {"model": "m", "input": "hi", "tools": [_a, _b]}).get_text() + + assert _sent_names(client) == ["a", "b"] + + +async def test_omits_the_tools_key_when_tools_is_explicitly_empty() -> None: + client = QueuedClient([text_response("r1", "hi")]) + + await call_model(client, {"model": "m", "input": "hi", "tools": []}).get_text() + + assert "tools" not in client.requests[0] + + +async def test_omits_the_tools_key_when_active_tools_filters_out_every_tool() -> None: + client = QueuedClient([text_response("r1", "hi")]) + + await call_model(client, {"model": "m", "input": "hi", "tools": [_a, _b], "active_tools": []}).get_text() + + assert "tools" not in client.requests[0] + + +async def test_a_filtered_out_tool_is_not_executed_when_the_model_calls_it() -> None: + executed: List[str] = [] + a = tool(name="a", input_schema=dict, execute=recording(executed, {}, lambda _p: "a")) + b = tool(name="b", input_schema=dict, execute=recording(executed, {}, lambda _p: "b")) + client = QueuedClient([tool_call_response("r1", "a"), text_response("r2", "done")]) + + result = call_model(client, {"model": "m", "input": "hi", "tools": [a, b], "active_tools": ["b"]}) + await result.get_response() + + # The executor does not carry the filtered definition, so the call is + # surfaced as unresolved instead of being run. + assert executed == [] + assert len(client.requests) == 1 diff --git a/tests/unit/test_compat.py b/tests/unit/test_compat.py index 2a192b4..c43a3cb 100644 --- a/tests/unit/test_compat.py +++ b/tests/unit/test_compat.py @@ -79,3 +79,68 @@ async def events(): assert calls[0].id == "call_1" assert calls[0].name == "lookup" assert calls[0].arguments == {"q": "x"} + + +# Ported from upstream src/lib/chat-compat.test.ts (#11, #41): assistant tool +# calls become function_call items instead of being dropped. + + +def test_from_chat_messages_emits_function_call_items_for_assistant_tool_calls() -> None: + converted = from_chat_messages( + [ + { + "role": "assistant", + "content": None, + "tool_calls": [ + { + "id": "call_1", + "type": "function", + "function": {"name": "get_weather", "arguments": '{"city":"Austin"}'}, + } + ], + }, + {"role": "tool", "tool_call_id": "call_1", "content": '{"temp":30}'}, + ] + ) + + # The content-less assistant message is replaced by its tool call; the + # already-serialized arguments are forwarded as-is. + assert converted == [ + { + "type": "function_call", + "callId": "call_1", + "id": "call_1", + "name": "get_weather", + "arguments": '{"city":"Austin"}', + "status": "completed", + }, + {"type": "function_call_output", "callId": "call_1", "output": '{"temp":30}'}, + ] + + +def test_from_chat_messages_keeps_text_and_tool_calls_in_order() -> None: + converted = from_chat_messages( + [ + { + "role": "assistant", + "content": "Let me check.", + "toolCalls": [ + {"id": "call_a", "type": "function", "function": {"name": "a", "arguments": "{}"}}, + {"id": "call_b", "type": "function", "function": {"name": "b", "arguments": '{"x":1}'}}, + ], + } + ] + ) + + assert [(item["type"], item.get("callId")) for item in converted] == [ + ("message", None), + ("function_call", "call_a"), + ("function_call", "call_b"), + ] + assert converted[0]["content"] == "Let me check." + + +def test_from_chat_messages_keeps_an_empty_assistant_message_without_tool_calls() -> None: + assert from_chat_messages([{"role": "assistant", "content": None}]) == [ + {"type": "message", "role": "assistant", "content": ""} + ] diff --git a/tests/unit/test_duplicate_call_ids.py b/tests/unit/test_duplicate_call_ids.py index 003642d..cee7311 100644 --- a/tests/unit/test_duplicate_call_ids.py +++ b/tests/unit/test_duplicate_call_ids.py @@ -60,11 +60,17 @@ async def test_distinct_ids_still_run_only_the_approved_call() -> None: assert state.stored is not None assert [c.id for c in state.stored.pending_tool_calls or []] == ["call_a", "call_b"] - await call_model( + resumed = call_model( client, {"model": "m", "input": "continue", "tools": tools, "state": state, "approve_tool_calls": ["call_a"]} - ).get_response() + ) + # Upstream 1.2.0 (#131): decisions covering only some pending calls leave + # the conversation paused on the undecided one instead of dropping it. + with pytest.raises(RuntimeError, match="awaiting approval.*call_b"): + await resumed.get_response() assert executed == ["read_config"] + assert len(client.requests) == 1 + assert [c.id for c in state.stored.pending_tool_calls or []] == ["call_b"] async def test_auto_executed_batch_with_duplicate_ids_runs_nothing() -> None: diff --git a/tests/unit/test_final_response_validation.py b/tests/unit/test_final_response_validation.py new file mode 100644 index 0000000..a47f9ca --- /dev/null +++ b/tests/unit/test_final_response_validation.py @@ -0,0 +1,75 @@ +"""Ported from upstream tests/unit/final-response-validation.test.ts (#95). + +Diagnostics only: the historical message prefixes are preserved and detail is +appended. Like upstream, these call the (pure) validator directly. +""" + +from __future__ import annotations + +from typing import Any, Dict + +import pytest + +from openrouter_agent import call_model +from openrouter_agent.model_result import ModelResult +from tests._fixtures import QueuedClient, function_call_item, make_response, message_item + + +def _validator() -> Any: + return ModelResult( + {"client": QueuedClient([]), "request": {"model": "m", "input": "hello"}} + )._validate_final_response + + +def _response(**overrides: Any) -> Dict[str, Any]: + response: Dict[str, Any] = {"id": "resp_1", "object": "response", "model": "m", "status": "completed", "output": []} + response.update(overrides) + return response + + +def _message(response: Any, allow_empty: bool = False) -> str: + with pytest.raises(ValueError) as caught: + _validator()(response, allow_empty) + return str(caught.value) + + +def test_reports_the_empty_array_its_length_and_the_response_id() -> None: + message = _message(_response()) + + assert message.startswith("Invalid final response: empty or invalid output") + assert 'output array is empty (length 0) for response "resp_1"' in message + assert "strict_final_response/allow_final_response" in message + assert "The model returned no output items" in message + assert "\n" not in message + + +def test_does_not_raise_when_empty_output_is_explicitly_allowed() -> None: + _validator()(_response(), True) + + +def test_names_the_offending_runtime_type_for_a_non_array_output() -> None: + assert 'output is not an array (got string) for response "resp_1"' in _message(_response(output="oops")) + object_message = _message(_response(output={"type": "message"})) + assert "(got object)" in object_message + assert "is empty" not in object_message + + +def test_non_array_output_is_still_tolerated_under_allow_empty_output() -> None: + _validator()(_response(output="oops"), True) + + +def test_names_the_missing_required_fields() -> None: + assert _message(_response(id=None)) == "Invalid final response: missing required fields: id" + assert _message(_response(output=None)) == "Invalid final response: missing required fields: output" + assert _message({}) == "Invalid final response: missing required fields: id, output" + assert _message(None) == "Invalid final response: missing required fields: id, output" + + +def test_accepts_a_tool_call_only_output_and_a_normal_message_output() -> None: + _validator()(make_response("r1", [function_call_item("call_1", "t")])) + _validator()(make_response("r2", [message_item("hi")])) + + +async def test_an_empty_final_turn_with_no_tool_rounds_raises_the_diagnostic_through_call_model() -> None: + with pytest.raises(ValueError, match=r'output array is empty \(length 0\) for response "r_empty"'): + await call_model(QueuedClient([make_response("r_empty", [])]), {"model": "m", "input": "hi"}).get_response() diff --git a/tests/unit/test_get_usage.py b/tests/unit/test_get_usage.py new file mode 100644 index 0000000..d2137ff --- /dev/null +++ b/tests/unit/test_get_usage.py @@ -0,0 +1,203 @@ +"""Ported from upstream tests/unit/get-usage.test.ts (#97). + +`ModelResult.get_usage()` aggregates token/cost usage across every model call a +run made, independent of the hook system, and never raises. + +Not ported: the streaming-resume and `get_items_stream` interleaving cases, +which exercise upstream's lazy stream initialization; this port drives the +whole loop in one task, so every getter waits for the same completion. +""" + +from __future__ import annotations + +import warnings +from typing import Any, Dict, List + +from openrouter_agent import HookEntry, HookName, HooksManager, call_model, tool +from tests._fixtures import MemoryStateAccessor, QueuedClient, text_response, tool_call_response + + +def _usage(**overrides: Any) -> Dict[str, Any]: + base: Dict[str, Any] = { + "input_tokens": 100, + "output_tokens": 50, + "total_tokens": 150, + "input_tokens_details": {"cached_tokens": 25}, + "output_tokens_details": {"reasoning_tokens": 10}, + "cost": 0.002, + } + base.update(overrides) + return base + + +_echo = tool(name="echo", input_schema=dict, execute=lambda _p, _c: {"ok": True}) + + +async def test_sums_usage_across_every_round_of_a_multi_round_tool_loop() -> None: + client = QueuedClient( + [ + tool_call_response("r1", "echo", usage=_usage()), + text_response( + "r2", + "done", + usage=_usage( + input_tokens=200, + output_tokens=100, + total_tokens=300, + cost=0.003, + input_tokens_details={"cached_tokens": 25}, + ), + ), + ] + ) + result = call_model(client, {"model": "test-model", "input": "hi", "tools": [_echo]}) + + final = await result.get_response() + usage = await result.get_usage() + + assert usage == { + "model_calls": 2, + "input_tokens": 300, + "output_tokens": 150, + "total_tokens": 450, + "cached_tokens": 50, + "reasoning_tokens": 20, + "cost": 0.005, + } + # The gap this closes: the final response alone reports only round 2. + assert final["usage"]["total_tokens"] == 300 + + +async def test_awaits_run_completion_when_called_without_awaiting_get_response_first() -> None: + client = QueuedClient( + [tool_call_response("r1", "echo", usage=_usage()), text_response("r2", "done", usage=_usage())] + ) + result = call_model(client, {"model": "test-model", "input": "hi", "tools": [_echo]}) + + usage = await result.get_usage() + + assert usage["model_calls"] == 2 + assert usage["total_tokens"] == 300 + + +async def test_accumulates_with_no_hooks_configured() -> None: + result = call_model( + QueuedClient([text_response("r1", "hi", usage=_usage())]), {"model": "test-model", "input": "hi"} + ) + await result.get_text() + + assert await result.get_usage() == { + "model_calls": 1, + "input_tokens": 100, + "output_tokens": 50, + "total_tokens": 150, + "cached_tokens": 25, + "reasoning_tokens": 10, + "cost": 0.002, + } + + +async def test_agrees_with_the_session_end_total_usage_hook_payload() -> None: + session_end: List[Any] = [] + hooks = HooksManager() + hooks.on(HookName.SessionEnd.value, HookEntry(handler=lambda payload, _ctx: session_end.append(payload))) + client = QueuedClient( + [tool_call_response("r1", "echo", usage=_usage()), text_response("r2", "done", usage=_usage())] + ) + result = call_model(client, {"model": "test-model", "input": "hi", "tools": [_echo], "hooks": hooks}) + + usage = await result.get_usage() + + assert len(session_end) == 1 + assert session_end[0]["total_usage"] == usage + + +async def test_counts_usage_less_responses_in_model_calls_and_omits_cost() -> None: + result = call_model(QueuedClient([text_response("r1", "hi")]), {"model": "test-model", "input": "hi"}) + await result.get_text() + + assert await result.get_usage() == { + "model_calls": 1, + "input_tokens": 0, + "output_tokens": 0, + "total_tokens": 0, + "cached_tokens": 0, + "reasoning_tokens": 0, + } + + +async def test_returns_zeroed_totals_when_no_model_call_completed_warning_with_the_cause() -> None: + # Error injection on the shared fake client (no bespoke client class). + client = QueuedClient([]) + + async def fail(**_kwargs: Any) -> Any: + raise RuntimeError("api down") + + client.responses.send_async = fail # type: ignore[method-assign] + result = call_model(client, {"model": "test-model", "input": "hi"}) + + try: + await result.get_text() + except RuntimeError as error: + assert str(error) == "api down" + else: # pragma: no cover - the run must fail + raise AssertionError("expected the run to fail") + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + usage = await result.get_usage() + + assert usage["model_calls"] == 0 + assert usage["total_tokens"] == 0 + assert "cost" not in usage + # Never-raises must not mean silent. + assert [str(w.message) for w in caught] == ["[get_usage] run failed; reporting totals accrued so far: api down"] + + +async def test_reports_only_the_model_calls_that_completed_before_an_approval_pause() -> None: + risky = tool(name="risky", input_schema=dict, execute=lambda _p, _c: {"ok": True}, require_approval=True) + state = MemoryStateAccessor() + client = QueuedClient([tool_call_response("r1", "risky", usage=_usage())]) + result = call_model(client, {"model": "test-model", "input": "do it", "tools": [risky], "state": state}) + + await result.get_pending_tool_calls() + first = await result.get_usage() + second = await result.get_usage() + + assert state.stored is not None and state.stored.status == "awaiting_approval" + assert len(client.requests) == 1 + assert ( + first + == second + == { + "model_calls": 1, + "input_tokens": 100, + "output_tokens": 50, + "total_tokens": 150, + "cached_tokens": 25, + "reasoning_tokens": 10, + "cost": 0.002, + } + ) + + +async def test_scopes_totals_per_model_result_across_an_approval_resume() -> None: + risky = tool(name="risky", input_schema=dict, execute=lambda _p, _c: {"ok": True}, require_approval=True) + state = MemoryStateAccessor() + first = call_model( + QueuedClient([tool_call_response("r1", "risky", call_id="call_r", usage=_usage())]), + {"model": "test-model", "input": "do it", "tools": [risky], "state": state}, + ) + await first.get_pending_tool_calls() + + resumed = call_model( + QueuedClient([text_response("r2", "done", usage=_usage(total_tokens=7, cost=0.001))]), + {"model": "test-model", "input": [], "tools": [risky], "state": state, "approve_tool_calls": ["call_r"]}, + ) + assert await resumed.get_text() == "done" + + assert (await first.get_usage())["model_calls"] == 1 + usage = await resumed.get_usage() + assert usage["model_calls"] == 1 + assert usage["total_tokens"] == 7 + assert usage["cost"] == 0.001 diff --git a/tests/unit/test_hooks_contract_fixes.py b/tests/unit/test_hooks_contract_fixes.py new file mode 100644 index 0000000..46b908b --- /dev/null +++ b/tests/unit/test_hooks_contract_fixes.py @@ -0,0 +1,108 @@ +"""Ported from upstream tests/unit/hooks-contract-fixes.test.ts, "blocking hooks +fail closed when the chain is aborted" (#160). + +If a PreToolUse / UserPromptSubmit chain stops early because it was aborted, +the emit result reports `blocked=True`, so handlers that never ran (e.g. a +later deny guard) cannot be skipped into an approval. + +Not ported: the fake-timer variant where a detached `async_timeout_ms` expiry +aborts the chain. It needs wall-clock interleaving between the timeout and a +slow handler; the abort path it reaches (`cancel_event`) is the one +`abort_inflight()` drives below. +""" + +from __future__ import annotations + +import asyncio +from typing import Any, List + +import pytest + +from openrouter_agent import HookEntry, HookName, HooksManager, call_model, tool +from openrouter_agent.hooks_types import AsyncOutput +from tests._fixtures import QueuedClient, text_response, tool_call_response, recording + + +async def test_reports_pre_tool_use_as_blocked_when_abort_inflight_fires_mid_chain() -> None: + manager = HooksManager() + guard_calls: List[Any] = [] + manager.on(HookName.PreToolUse.value, HookEntry(handler=lambda _p, _c: manager.abort_inflight())) + manager.on( + HookName.PreToolUse.value, + HookEntry(handler=recording(guard_calls, {"block": "policy forbids this call"})), + ) + + result = await manager.emit("PreToolUse", {"tool_name": "t", "tool_input": {}}, tool_name="t") + + assert guard_calls == [] + assert result.blocked is True + + +async def test_reports_user_prompt_submit_as_blocked_when_aborted_mid_chain() -> None: + manager = HooksManager() + manager.on(HookName.UserPromptSubmit.value, HookEntry(handler=lambda _p, _c: manager.abort_inflight())) + manager.on(HookName.UserPromptSubmit.value, HookEntry(handler=lambda _p, _c: {"reject": "nope"})) + + result = await manager.emit("UserPromptSubmit", {"prompt": "hi"}) + + assert result.blocked is True + + +async def test_still_runs_every_pre_tool_use_handler_when_detached_work_settles_in_time() -> None: + manager = HooksManager() + guard_calls: List[Any] = [] + done = asyncio.get_running_loop().create_future() + done.set_result(None) + manager.on(HookName.PreToolUse.value, HookEntry(handler=lambda _p, _c: AsyncOutput(work=done, async_timeout_ms=10))) + manager.on(HookName.PreToolUse.value, HookEntry(handler=recording(guard_calls, None, lambda _p: 1))) + + result = await manager.emit("PreToolUse", {"tool_name": "t", "tool_input": {}}, tool_name="t") + await manager.drain() + + assert guard_calls == [1] + assert result.blocked is False + + +async def test_does_not_mark_non_blocking_hooks_as_blocked_when_aborted() -> None: + manager = HooksManager() + manager.on(HookName.PostToolUse.value, HookEntry(handler=lambda _p, _c: manager.abort_inflight())) + manager.on(HookName.PostToolUse.value, HookEntry(handler=lambda _p, _c: None)) + + result = await manager.emit( + "PostToolUse", + {"tool_name": "t", "tool_input": {}, "tool_output": None, "duration_ms": 1}, + tool_name="t", + ) + + assert result.blocked is False + + +async def test_an_aborted_pre_tool_use_chain_blocks_the_tool_call_in_the_loop() -> None: + executed: List[Any] = [] + hooks = HooksManager() + hooks.on(HookName.PreToolUse.value, HookEntry(handler=lambda _p, _c: hooks.abort_inflight())) + # A later guard that never runs: the chain must not read as an approval. + hooks.on(HookName.PreToolUse.value, HookEntry(handler=lambda _p, _c: None)) + danger = tool(name="danger", input_schema=dict, execute=recording(executed, {"ok": True})) + client = QueuedClient([tool_call_response("r1", "danger", call_id="call_1"), text_response("r2", "done")]) + + await call_model(client, {"model": "m", "input": "go", "tools": [danger], "hooks": hooks}).get_text() + + assert executed == [] + outputs = [ + item + for item in client.requests[1]["input"] + if isinstance(item, dict) and item.get("type") == "function_call_output" + ] + assert [(o["call_id"], o["output"]) for o in outputs] == [("call_1", '{"error":"Blocked by PreToolUse hook"}')] + + +async def test_an_aborted_user_prompt_submit_chain_rejects_the_prompt() -> None: + hooks = HooksManager() + hooks.on(HookName.UserPromptSubmit.value, HookEntry(handler=lambda _p, _c: hooks.abort_inflight())) + hooks.on(HookName.UserPromptSubmit.value, HookEntry(handler=lambda _p, _c: None)) + client = QueuedClient([]) + + with pytest.raises(ValueError, match="Prompt rejected by hook"): + await call_model(client, {"model": "m", "input": "hi", "hooks": hooks}).get_text() + assert client.requests == [] diff --git a/tests/unit/test_manual_tool_wire_schema.py b/tests/unit/test_manual_tool_wire_schema.py new file mode 100644 index 0000000..2ae6a10 --- /dev/null +++ b/tests/unit/test_manual_tool_wire_schema.py @@ -0,0 +1,114 @@ +"""Ported from upstream tests/unit/manual-tool-wire-schema.test.ts (#118) plus +the MCP wire-schema rule from #146 (`mark_mcp(..., wire_input_schema=...)`).""" + +from __future__ import annotations + +import copy + +import pytest +from pydantic import BaseModel + +from openrouter_agent import tool +from openrouter_agent.tool import mark_mcp +from openrouter_agent.tool_executor import convert_tools_to_api_format + + +class _Choice(BaseModel): + choice: str + + +class _Value(BaseModel): + value: str + + +def test_serializes_any_of_and_one_of_while_sanitizing_tilde_prefixed_keys() -> None: + wire_input_schema = { + "type": "object", + "~rootMetadata": "remove me", + "properties": { + "choice": { + "~propertyMetadata": "remove me", + "anyOf": [{"type": "string"}, {"type": "number"}], + "oneOf": [{"const": "first"}, {"const": "second"}], + } + }, + "required": ["choice"], + } + manual = tool( + name="choose_value", + description="Choose a value", + input_schema=_Choice, + wire_input_schema=wire_input_schema, + execute=False, + strict=True, + ) + + emitted = convert_tools_to_api_format([manual])[0] + + assert emitted["type"] == "function" + assert emitted["name"] == "choose_value" + assert emitted["description"] == "Choose a value" + assert emitted["strict"] is True + assert emitted["parameters"] == { + "type": "object", + "properties": { + "choice": { + "anyOf": [{"type": "string"}, {"type": "number"}], + "oneOf": [{"const": "first"}, {"const": "second"}], + } + }, + "required": ["choice"], + } + + +def test_does_not_mutate_the_caller_owned_schema_and_emits_a_copy() -> None: + wire_input_schema = { + "type": "object", + "~rootMetadata": True, + "properties": {"value": {"type": "string", "~nestedMetadata": True}}, + } + original = copy.deepcopy(wire_input_schema) + manual = tool(name="copy_schema", input_schema=_Value, wire_input_schema=wire_input_schema, execute=False) + + emitted = convert_tools_to_api_format([manual])[0] + + assert wire_input_schema == original + assert emitted["parameters"] is not wire_input_schema + + +def test_falls_back_to_the_generated_schema_without_wire_input_schema() -> None: + emitted = convert_tools_to_api_format([tool(name="fallback_schema", input_schema=_Value, execute=False)])[0] + + assert emitted["parameters"]["type"] == "object" + assert emitted["parameters"]["properties"]["value"]["type"] == "string" + + +def test_wire_input_schema_is_rejected_on_executable_tools() -> None: + # Upstream rejects this at the type level (`wireInputSchema?: never`). + with pytest.raises(ValueError, match="only supported on manual tools"): + tool(name="exec", input_schema=_Value, wire_input_schema={"type": "object"}, execute=lambda p, _c: p) + + +def test_mark_mcp_sends_the_servers_own_object_schema() -> None: + server_schema = { + "type": "object", + "properties": {"when": {"type": "string", "format": "date-time"}}, + "required": ["when"], + } + wrapped = tool(name="schedule", input_schema=dict, execute=lambda p, _c: p) + + marked = mark_mcp(wrapped, wire_input_schema=server_schema, annotations={"readOnlyHint": True}) + + assert convert_tools_to_api_format([marked])[0]["parameters"] == server_schema + assert marked["annotations"] == {"readOnlyHint": True} + # Non-mutating: the unbranded tool keeps its generated schema. + assert "wire_input_schema" not in wrapped["function"] + + +def test_mark_mcp_keeps_the_generated_schema_for_a_non_object_root() -> None: + wrapped = tool(name="weird", input_schema=_Value, execute=lambda p, _c: p) + + marked = mark_mcp(wrapped, wire_input_schema={"type": "string"}) + + assert convert_tools_to_api_format([marked])[0]["parameters"]["type"] == "object" + assert "annotations" not in marked diff --git a/tests/unit/test_max_output_tokens_truncation.py b/tests/unit/test_max_output_tokens_truncation.py new file mode 100644 index 0000000..48441ed --- /dev/null +++ b/tests/unit/test_max_output_tokens_truncation.py @@ -0,0 +1,138 @@ +"""Ported from upstream tests/unit/max-output-tokens-truncation.test.ts (#125). + +A response the provider stopped at `max_output_tokens` is an unfinished batch: +none of its function calls run -- not even the ones completed before the +cut-off -- and the loop does not re-request on the exhausted budget. +""" + +from __future__ import annotations + +import json +from typing import Any, Dict, List, Optional + +from pydantic import BaseModel + +from openrouter_agent import call_model, step_count_is, tool +from openrouter_agent.stream_transformers import extract_tool_calls_from_response, response_has_tool_calls +from tests._fixtures import QueuedClient, make_response, recording + + +def _truncated(output: Optional[List[Dict[str, Any]]] = None) -> Dict[str, Any]: + items = output or [ + { + "type": "function_call", + "id": "fc_shell", + "callId": "call_shell", + "name": "run_shell", + "arguments": '{"commands":["echo hel', + "status": "incomplete", + } + ] + return make_response( + "resp_truncated", items, status="incomplete", incompleteDetails={"reason": "max_output_tokens"} + ) + + +def _truncated_batch() -> Dict[str, Any]: + weather = [ + { + "type": "function_call", + "id": f"fc_weather_{index}", + "callId": f"call_weather_{index}", + "name": "get_weather", + "arguments": json.dumps({"city": city}), + "status": "completed", + } + for index, city in enumerate(["Paris", "London", "Tokyo"]) + ] + shell = { + "type": "function_call", + "id": "fc_shell", + "callId": "call_shell", + "name": "run_shell", + "arguments": '{"commands":', + "status": "incomplete", + } + return _truncated([*weather, shell]) + + +class _Shell(BaseModel): + commands: List[str] + + +class _City(BaseModel): + city: str + + +def test_extracts_no_tool_calls_from_a_response_truncated_at_max_output_tokens() -> None: + response = _truncated() + + assert response_has_tool_calls(response) is False + assert extract_tool_calls_from_response(response) == [] + + +def test_a_completed_response_still_reports_its_tool_calls() -> None: + response = make_response( + "resp_ok", + [{"type": "function_call", "id": "fc", "callId": "call_1", "name": "run_shell", "arguments": "{}"}], + ) + + assert response_has_tool_calls(response) is True + assert [c.id for c in extract_tool_calls_from_response(response)] == ["call_1"] + + +async def test_finalizes_on_the_truncated_turn_without_executing_or_requesting_again() -> None: + executed: List[Any] = [] + shell = tool( + name="run_shell", + description="Run shell commands.", + input_schema=_Shell, + execute=recording(executed, {"ok": True}), + ) + client = QueuedClient([_truncated()]) + + response = await call_model( + client, + {"model": "test-model", "input": "Run echo hello.", "stop_when": step_count_is(3), "tools": [shell]}, + ).get_response() + + assert executed == [] + assert len(client.requests) == 1 + assert response["id"] == "resp_truncated" + assert response["status"] == "incomplete" + + +async def test_does_not_execute_the_calls_that_completed_before_the_cut_off_either() -> None: + executed: List[Any] = [] + weather = tool( + name="get_weather", + input_schema=_City, + execute=recording(executed, {"temperature": 22}), + ) + shell = tool( + name="run_shell", + input_schema=_Shell, + execute=recording(executed, {"ok": True}), + ) + client = QueuedClient([_truncated_batch()]) + + response = await call_model( + client, + { + "model": "test-model", + "input": "Weather in three cities, then run echo hello.", + "stop_when": step_count_is(3), + "tools": [weather, shell], + }, + ).get_response() + + assert executed == [] + assert len(client.requests) == 1 + assert response["status"] == "incomplete" + # The caller gets the whole turn, cut-off item included, to resume from. + assert [item["callId"] for item in response["output"]] == [ + "call_weather_0", + "call_weather_1", + "call_weather_2", + "call_shell", + ] diff --git a/tests/unit/test_next_turn_params.py b/tests/unit/test_next_turn_params.py new file mode 100644 index 0000000..b9ab1ec --- /dev/null +++ b/tests/unit/test_next_turn_params.py @@ -0,0 +1,58 @@ +"""Ported from upstream tests/unit/next-turn-params.test.ts and +src/lib/next-turn-params.test.ts (the `toolChoice` key, #114).""" + +from __future__ import annotations + +from typing import Any, List + +from openrouter_agent import tool +from openrouter_agent.next_turn_params import ( + apply_next_turn_params_to_request, + build_next_turn_params_context, + execute_next_turn_params_functions, +) +from openrouter_agent.tool_types import ParsedToolCall + + +def test_context_carries_the_current_tool_choice() -> None: + choice = {"type": "allowed_tools", "mode": "auto", "tools": [{"type": "function", "name": "a"}]} + + context = build_next_turn_params_context({"model": "m", "input": [], "tool_choice": choice}) + + assert context["tool_choice"] == choice + assert context["model"] == "m" + + +def test_context_always_has_a_tool_choice_key() -> None: + context = build_next_turn_params_context({"model": "m"}) + + assert "tool_choice" in context + assert context["tool_choice"] is None + + +async def test_a_tool_can_compute_the_next_tool_choice_from_the_current_one() -> None: + seen: List[Any] = [] + + def widen(params: Any, context: Any) -> Any: + seen.append(context["tool_choice"]) + names = [t["name"] for t in context["tool_choice"]["tools"]] + return { + "type": "allowed_tools", + "mode": "auto", + "tools": [{"type": "function", "name": n} for n in [*names, params["add"]]], + } + + search = tool(name="search", input_schema=dict, execute=lambda _p, _c: {}, next_turn_params={"tool_choice": widen}) + request = { + "model": "m", + "tool_choice": {"type": "allowed_tools", "mode": "auto", "tools": [{"type": "function", "name": "search"}]}, + } + + computed = await execute_next_turn_params_functions( + [ParsedToolCall(id="c1", name="search", arguments={"add": "weather"})], [search], request + ) + updated = apply_next_turn_params_to_request(request, computed) + + assert seen == [request["tool_choice"]] + assert [t["name"] for t in updated["tool_choice"]["tools"]] == ["search", "weather"] + assert updated["model"] == "m" diff --git a/tests/unit/test_next_turn_tool_choice_loop.py b/tests/unit/test_next_turn_tool_choice_loop.py new file mode 100644 index 0000000..c844a52 --- /dev/null +++ b/tests/unit/test_next_turn_tool_choice_loop.py @@ -0,0 +1,154 @@ +"""Ported from upstream tests/unit/next-turn-tool-choice-loop.test.ts (#114, #153). + +`next_turn_params` may set `tool_choice` -- the hook a tool-search tool uses +to widen an `allowed_tools` choice without touching `tools` -- and it runs only +for calls whose tool body ran and returned without error, with the input the +tool actually ran on. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Literal + +from pydantic import BaseModel + +from openrouter_agent import HookEntry, HookName, HooksManager, call_model, tool +from tests._fixtures import QueuedClient, text_response, tool_call_response, recording + + +def _allowed(names: List[str]) -> Dict[str, Any]: + return {"type": "allowed_tools", "mode": "auto", "tools": [{"type": "function", "name": n} for n in names]} + + +class _Pattern(BaseModel): + pattern: str + + +class _Empty(BaseModel): + pass + + +_WIDENED = ["tool_search", "get_weather"] +_get_weather = tool(name="get_weather", input_schema=_Empty, execute=lambda _p, _c: {"ok": True}) + + +def _search_tool(next_calls: List[Any], **overrides: Any) -> Dict[str, Any]: + def next_choice(params: Any, context: Any) -> Any: + next_calls.append((params, context.get("tool_choice"))) + return _allowed(_WIDENED) + + kwargs: Dict[str, Any] = { + "name": "tool_search", + "input_schema": _Pattern, + "execute": lambda _p, _c: {"found": _WIDENED}, + "next_turn_params": {"tool_choice": next_choice}, + } + kwargs.update(overrides) + return tool(**kwargs) + + +async def _run(search: Dict[str, Any], **extra: Any) -> QueuedClient: + client = QueuedClient( + [ + tool_call_response("resp_tool", "tool_search", call_id="call_1", arguments='{"pattern":"weather"}'), + text_response("resp_text", "done"), + ] + ) + await call_model( + client, + { + "model": "test-model", + "input": "hi", + "tools": [search, _get_weather], + "tool_choice": _allowed(["tool_search"]), + **extra, + }, + ).get_text() + return client + + +async def test_reaches_the_dispatched_follow_up_request() -> None: + next_calls: List[Any] = [] + client = await _run(_search_tool(next_calls)) + + choices = [r.get("tool_choice") for r in client.requests] + assert choices == [_allowed(["tool_search"]), _allowed(_WIDENED)] + # The tool reads the current choice to widen it rather than rebuild it. + assert len(next_calls) == 1 + assert next_calls[0][1] == _allowed(["tool_search"]) + + +async def test_leaves_the_tools_array_untouched_while_the_choice_widens() -> None: + client = await _run(_search_tool([])) + + names = [[t["name"] for t in r["tools"]] for r in client.requests] + # Identical across turns: widening must not change the request prefix, or + # the provider's prompt cache is lost. + assert names[1] == names[0] + + +async def test_does_not_disturb_tool_choice_when_no_tool_computes_one() -> None: + plain = tool(name="tool_search", input_schema=_Pattern, execute=lambda _p, _c: {"ok": True}) + client = await _run(plain) + + assert [r.get("tool_choice") for r in client.requests] == [_allowed(["tool_search"])] * 2 + + +async def test_does_not_widen_tool_choice_when_pre_tool_use_blocks_the_call() -> None: + executed: List[Any] = [] + next_calls: List[Any] = [] + hooks = HooksManager() + hooks.on( + HookName.PreToolUse.value, + HookEntry(matcher="tool_search", handler=lambda _p, _c: {"block": "blocked by policy"}), + ) + search = _search_tool(next_calls, execute=recording(executed, {"found": _WIDENED})) + + client = await _run(search, hooks=hooks) + + assert executed == [] + assert next_calls == [] + assert client.requests[1]["tool_choice"] == _allowed(["tool_search"]) + + +async def test_does_not_widen_tool_choice_when_the_arguments_fail_input_schema() -> None: + class _News(BaseModel): + pattern: Literal["news"] + + executed: List[Any] = [] + next_calls: List[Any] = [] + search = _search_tool(next_calls, input_schema=_News, execute=recording(executed, {})) + + client = await _run(search) + + assert executed == [] + assert next_calls == [] + assert client.requests[1]["tool_choice"] == _allowed(["tool_search"]) + + +async def test_does_not_widen_tool_choice_when_execute_throws() -> None: + def boom(_p: Any, _c: Any) -> Any: + raise RuntimeError("search backend unavailable") + + next_calls: List[Any] = [] + client = await _run(_search_tool(next_calls, execute=boom)) + + assert next_calls == [] + assert client.requests[1]["tool_choice"] == _allowed(["tool_search"]) + + +async def test_passes_the_pre_tool_use_mutated_input_that_the_tool_ran_on() -> None: + ran_on: List[Any] = [] + next_calls: List[Any] = [] + hooks = HooksManager() + hooks.on( + HookName.PreToolUse.value, + HookEntry(matcher="tool_search", handler=lambda _p, _c: {"mutated_input": {"pattern": "mutated"}}), + ) + search = _search_tool(next_calls, execute=recording(ran_on, {"found": _WIDENED}, lambda p: p.pattern)) + + client = await _run(search, hooks=hooks) + + assert ran_on == ["mutated"] + assert [params for params, _choice in next_calls] == [{"pattern": "mutated"}] + assert client.requests[1]["tool_choice"] == _allowed(_WIDENED) diff --git a/tests/unit/test_server_tool.py b/tests/unit/test_server_tool.py new file mode 100644 index 0000000..9072d98 --- /dev/null +++ b/tests/unit/test_server_tool.py @@ -0,0 +1,65 @@ +"""Ported from upstream tests/unit/server-tool.test.ts, the `strict` +serialization cases (#99). The run-lifecycle and `tool.agent()` variants are +not ported: this port has no unified `run` tools or subagent tools yet.""" + +from __future__ import annotations + +from pydantic import BaseModel + +from openrouter_agent import call_model, server_tool, tool +from openrouter_agent.tool_executor import convert_tools_to_api_format +from tests._fixtures import QueuedClient, text_response + + +class _Msg(BaseModel): + msg: str + + +def test_serializes_strict_true_from_the_tool_definition() -> None: + strict_tool = tool(name="echo", input_schema=_Msg, strict=True, execute=lambda p, _c: p.msg) + + api = convert_tools_to_api_format([strict_tool]) + + assert api[0]["type"] == "function" + assert api[0]["name"] == "echo" + assert api[0]["strict"] is True + + +def test_serializes_strict_false_as_false_instead_of_null() -> None: + api = convert_tools_to_api_format([tool(name="echo", input_schema=_Msg, strict=False, execute=lambda p, _c: p.msg)]) + + assert api[0]["strict"] is False + + +def test_defaults_strict_to_null_when_not_declared() -> None: + api = convert_tools_to_api_format([tool(name="echo", input_schema=_Msg, execute=lambda p, _c: p.msg)]) + + assert "strict" in api[0] + assert api[0]["strict"] is None + + +def test_server_tools_pass_their_config_through_unchanged() -> None: + api = convert_tools_to_api_format( + [ + tool(name="echo", input_schema=_Msg, strict=True, execute=lambda p, _c: p.msg), + server_tool({"type": "web_search"}), + ] + ) + + assert [entry.get("name", entry["type"]) for entry in api] == ["echo", "web_search"] + assert api[1] == {"type": "web_search"} + + +async def test_strict_reaches_the_wire_request() -> None: + client = QueuedClient([text_response("r1", "hi")]) + + await call_model( + client, + { + "model": "m", + "input": "hi", + "tools": [tool(name="echo", input_schema=_Msg, strict=True, execute=lambda p, _c: p.msg)], + }, + ).get_text() + + assert client.requests[0]["tools"][0]["strict"] is True diff --git a/tests/unit/test_shared_context.py b/tests/unit/test_shared_context.py new file mode 100644 index 0000000..fda6b36 --- /dev/null +++ b/tests/unit/test_shared_context.py @@ -0,0 +1,97 @@ +"""Ported from upstream tests/unit/shared-context.test.ts, region "context +setters store schema-validated values" (#161). + +`set_context` / `set_shared_context` store the schema's parsed output for each +updated field and validate the merged context against the full schema before +storing it, so model-level validators are enforced at write time. An update +that fails validation raises and leaves the stored context unchanged. +""" + +from __future__ import annotations + +from typing import Literal + +import pytest +from pydantic import BaseModel, ValidationError, field_validator, model_validator + +from openrouter_agent import ToolContextStore, tool +from openrouter_agent.tool_context import build_tool_execute_context +from openrouter_agent.tool_types import SHARED_CONTEXT_KEY + +_TURN = {"number_of_turns": 1} + + +def _my_tool(context_schema: object = None) -> dict: + return tool(name="my_tool", input_schema=dict, execute=lambda _p, _c: None, context_schema=context_schema) + + +def test_set_shared_context_stores_the_parsed_output_of_field_transforms() -> None: + class Shared(BaseModel): + level: int + + @field_validator("level") + @classmethod + def _clamp(cls, value: int) -> int: + return min(value, 0) + + store = ToolContextStore({SHARED_CONTEXT_KEY: {"level": 0}}) + ctx = build_tool_execute_context(_my_tool(), _TURN, store, Shared) + + ctx["set_shared_context"]({"level": 1}) + + assert dict(ctx["shared"]) == {"level": 0} + + +def test_set_context_stores_the_parsed_output_of_field_transforms() -> None: + class Local(BaseModel): + mode: str + + @field_validator("mode") + @classmethod + def _normalize(cls, value: str) -> str: + return value.strip().lower() + + store = ToolContextStore({"my_tool": {"mode": "read"}}) + ctx = build_tool_execute_context(_my_tool(Local), _TURN, store) + + ctx["set_context"]({"mode": " WRITE "}) + + assert dict(ctx["local"]) == {"mode": "write"} + + +def test_set_shared_context_rejects_an_update_that_breaks_a_model_level_validator() -> None: + class Shared(BaseModel): + role: Literal["guest", "staff"] + access: Literal["read", "write"] + + @model_validator(mode="after") + def _staff_only_write(self) -> "Shared": + if self.access == "write" and self.role != "staff": + raise ValueError("write access requires staff") + return self + + initial = {"role": "guest", "access": "read"} + store = ToolContextStore({SHARED_CONTEXT_KEY: initial}) + ctx = build_tool_execute_context(_my_tool(), _TURN, store, Shared) + + with pytest.raises(ValidationError): + ctx["set_shared_context"]({"access": "write"}) + assert dict(ctx["shared"]) == initial + + ctx["set_shared_context"]({"role": "staff"}) + ctx["set_shared_context"]({"access": "write"}) + assert dict(ctx["shared"]) == {"role": "staff", "access": "write"} + + +def test_unknown_keys_are_dropped_and_only_updated_fields_are_stored() -> None: + class Local(BaseModel): + mode: str = "read" + retries: int = 3 + + store = ToolContextStore({"my_tool": {}}) + ctx = build_tool_execute_context(_my_tool(Local), _TURN, store) + + ctx["set_context"]({"mode": "write", "unknown": True}) + + # Defaults for fields the update did not touch are not written back. + assert dict(ctx["local"]) == {"mode": "write"} diff --git a/tests/unit/test_stop_when_before_approval.py b/tests/unit/test_stop_when_before_approval.py new file mode 100644 index 0000000..41a7ebb --- /dev/null +++ b/tests/unit/test_stop_when_before_approval.py @@ -0,0 +1,99 @@ +"""Ported from upstream tests/unit/stop-when-before-approval.test.ts (#143). + +With `allow_final_response=False` and `stop_when` already met on the first +response, pausing for an approval-gated call must not execute its auto-approved +siblings; they are saved as skipped results instead. +""" + +from __future__ import annotations + +from typing import Any, List, Tuple + +from pydantic import BaseModel + +from openrouter_agent import call_model, tool +from tests._fixtures import MemoryStateAccessor, QueuedClient, function_call_item, make_response + + +class _Input(BaseModel): + v: str + + +def _tools() -> Tuple[List[Any], List[str], List[str]]: + auto_calls: List[str] = [] + gated_calls: List[str] = [] + + def auto_execute(params: _Input, _ctx: Any) -> Any: + auto_calls.append(params.v) + return {"ok": True} + + def gated_execute(params: _Input, _ctx: Any) -> Any: + gated_calls.append(params.v) + return {"ok": True} + + auto = tool(name="auto", input_schema=_Input, output_schema=dict, execute=auto_execute) + gated = tool(name="gated", input_schema=_Input, output_schema=dict, require_approval=True, execute=gated_execute) + return [auto, gated], auto_calls, gated_calls + + +def _response() -> Any: + return make_response( + "resp_1", + [function_call_item("call_auto", "auto", '{"v":"x"}'), function_call_item("call_gated", "gated", '{"v":"x"}')], + ) + + +async def test_does_not_run_an_auto_executable_sibling_when_stop_when_is_already_met() -> None: + tools, auto_calls, gated_calls = _tools() + state = MemoryStateAccessor() + client = QueuedClient([_response()]) + + result = call_model( + client, + { + "model": "test-model", + "input": "go", + "tools": tools, + "state": state, + "stop_when": lambda _ctx: True, + "allow_final_response": False, + }, + ) + await result.get_response() + + assert auto_calls == [] + assert gated_calls == [] + assert len(client.requests) == 1 + saved = state.stored + assert saved is not None + assert saved.status == "awaiting_approval" + assert [c.id for c in saved.pending_tool_calls or []] == ["call_gated"] + # The skipped sibling still gets a matching output for the resume request. + assert [(r.call_id, r.name, r.output, r.error) for r in saved.unsent_tool_results or []] == [ + ("call_auto", "auto", None, "Tool execution skipped: stop condition met") + ] + assert await result.requires_approval() is True + + +async def test_still_runs_the_auto_executable_sibling_when_stop_when_is_not_met() -> None: + tools, auto_calls, _gated_calls = _tools() + state = MemoryStateAccessor() + + await call_model( + QueuedClient([_response()]), + { + "model": "test-model", + "input": "go", + "tools": tools, + "state": state, + "stop_when": lambda _ctx: False, + "allow_final_response": False, + }, + ).get_response() + + assert auto_calls == ["x"] + saved = state.stored + assert saved is not None + assert saved.status == "awaiting_approval" + assert [c.id for c in saved.pending_tool_calls or []] == ["call_gated"] + assert [r.call_id for r in saved.unsent_tool_results or []] == ["call_auto"] diff --git a/tests/unit/test_to_model_output_parity.py b/tests/unit/test_to_model_output_parity.py new file mode 100644 index 0000000..d437738 --- /dev/null +++ b/tests/unit/test_to_model_output_parity.py @@ -0,0 +1,147 @@ +"""Ported from upstream tests/unit/to-model-output-parity.test.ts (#155). + +`to_model_output` receives the tool input after `input_schema` parsing (the +same value `execute` gets), and it runs for results produced on the +approval-resume path too. +""" + +from __future__ import annotations + +import json +from typing import Any, List, Mapping + +from pydantic import BaseModel, field_validator + +from openrouter_agent import call_model, tool +from tests._fixtures import ( + recording, + MemoryStateAccessor, + QueuedClient, + function_call_item, + make_response, + text_response, + tool_call_response, +) + +SECRET = "sk-live-secret" +MASK = "[redacted]" + + +class _Lookup(BaseModel): + access: str + verbose: bool = False + + @field_validator("access") + @classmethod + def _lower(cls, value: str) -> str: + return value.lower() + + +def _sent_tool_outputs(client: QueuedClient) -> List[Any]: + # Outgoing items use snake_case `call_id` (ModelResult._send normalizes at + # the transport boundary); only the `output` payload matters here. + return [ + item["output"] + for request in client.requests + for item in request["input"] + if isinstance(item, Mapping) and item.get("type") == "function_call_output" + ] + + +async def test_passes_input_schema_normalized_arguments_to_to_model_output() -> None: + execute_inputs: List[Any] = [] + mapper_inputs: List[Any] = [] + + def execute(params: _Lookup, _ctx: Any) -> Any: + execute_inputs.append(params) + return {"secret": SECRET} + + def to_model_output(payload: Mapping[str, Any]) -> Any: + mapper_inputs.append(payload["input"]) + text = MASK if payload["input"].access == "private" else payload["output"]["secret"] + return {"type": "content", "value": [{"type": "input_text", "text": text}]} + + lookup = tool(name="lookup", input_schema=_Lookup, execute=execute, to_model_output=to_model_output) + client = QueuedClient( + [ + tool_call_response("resp_1", "lookup", call_id="call_1", arguments='{"access":"PRIVATE"}'), + text_response("resp_2", "done"), + ] + ) + + await call_model(client, {"model": "test-model", "input": "look", "tools": [lookup]}).get_response() + + parsed = _Lookup(access="private", verbose=False) + assert execute_inputs == [parsed] + # The mapper sees the same parsed value execute got, not the raw wire args. + assert mapper_inputs == [parsed] + assert SECRET not in json.dumps(_sent_tool_outputs(client)) + + +async def test_maps_the_output_of_an_approved_call_before_sending_it_to_the_model() -> None: + mapper_calls: List[Any] = [] + executed: List[Any] = [] + + def to_model_output(payload: Mapping[str, Any]) -> Any: + mapper_calls.append(payload) + return {"type": "content", "value": [{"type": "input_text", "text": MASK}]} + + lookup = tool( + name="lookup", + input_schema=_Lookup, + require_approval=True, + execute=recording(executed, {"secret": SECRET}), + to_model_output=to_model_output, + ) + state = MemoryStateAccessor() + await call_model( + QueuedClient([tool_call_response("resp_1", "lookup", call_id="call_1", arguments='{"access":"PRIVATE"}')]), + {"model": "test-model", "input": "look", "tools": [lookup], "state": state}, + ).get_response() + assert state.stored is not None and state.stored.status == "awaiting_approval" + assert executed == [] + + client = QueuedClient([text_response("resp_2", "done")]) + await call_model( + client, + {"model": "test-model", "input": [], "tools": [lookup], "state": state, "approve_tool_calls": ["call_1"]}, + ).get_response() + + assert len(executed) == 1 + assert len(mapper_calls) == 1 + assert mapper_calls[0]["input"] == _Lookup(access="private") + assert mapper_calls[0]["output"] == {"secret": SECRET} + outputs = _sent_tool_outputs(client) + assert outputs == [[{"type": "input_text", "text": MASK}]] + assert SECRET not in json.dumps(outputs) + + +async def test_maps_auto_executed_siblings_persisted_before_an_approval_pause() -> None: + # Unsent results recorded before a pause go through the same mapper, so + # the resume request carries the mapped output, not the raw result. + lookup = tool( + name="lookup", + input_schema=_Lookup, + execute=lambda _params, _ctx: {"secret": SECRET}, + to_model_output=lambda _payload: {"type": "content", "value": [{"type": "input_text", "text": MASK}]}, + ) + gated = tool(name="gated", input_schema=dict, require_approval=True, execute=lambda _p, _c: {"ok": True}) + state = MemoryStateAccessor() + await call_model( + QueuedClient( + [ + make_response( + "resp_1", + [ + function_call_item("call_lookup", "lookup", '{"access":"x"}'), + function_call_item("call_gated", "gated", "{}"), + ], + ) + ] + ), + {"model": "test-model", "input": "go", "tools": [lookup, gated], "state": state}, + ).get_response() + assert state.stored is not None + assert [(r.call_id, r.output) for r in state.stored.unsent_tool_results or []] == [ + ("call_lookup", [{"type": "input_text", "text": MASK}]) + ] diff --git a/tests/unit/test_tool_choice_relaxation.py b/tests/unit/test_tool_choice_relaxation.py new file mode 100644 index 0000000..025425f --- /dev/null +++ b/tests/unit/test_tool_choice_relaxation.py @@ -0,0 +1,262 @@ +"""Ported from upstream tests/unit/tool-choice-relaxation.test.ts (#100, DEV-785). + +A caller-forced `tool_choice` (`"required"`, a specific tool, or +`allowed_tools` with `mode: "required"`) is relaxed to `"auto"` once it has +produced a tool call, including follow-ups resumed after an approval or a +manual client-tool pause, so the model can answer in text instead of calling +tools until the step budget runs out. + +Not ported: the two "re-arms a dynamic forced choice" cases. This port resolves +function-valued request parameters once, at turn 0, rather than per turn (a +pre-existing divergence), so a choice whose value changes between turns cannot +be expressed through `call_model` here. +""" + +from __future__ import annotations + +import json +from typing import Any, Dict, List + +from pydantic import BaseModel + +from openrouter_agent import call_model, step_count_is, tool +from tests._fixtures import MemoryStateAccessor, QueuedClient, text_response, tool_call_response + + +class _City(BaseModel): + location: str + + +def _weather(**overrides: Any) -> Dict[str, Any]: + kwargs: Dict[str, Any] = { + "name": "get_weather", + "description": "Get weather", + "input_schema": _City, + "execute": lambda _params, _ctx: {"temperature": 22}, + } + kwargs.update(overrides) + return tool(**kwargs) + + +def _call(response_id: str, call_id: str) -> Dict[str, Any]: + return tool_call_response(response_id, "get_weather", call_id=call_id, arguments='{"location":"Tokyo"}') + + +def _choices(client: QueuedClient) -> List[Any]: + return [request.get("tool_choice") for request in client.requests] + + +async def test_relaxes_required_to_auto_after_a_successful_tool_round() -> None: + client = QueuedClient([_call("resp_1", "call_1"), text_response("resp_2", "It is 22 degrees.")]) + + text = await call_model( + client, + { + "model": "test-model", + "input": "What is the weather in Tokyo?", + "tools": [_weather()], + "tool_choice": "required", + "stop_when": step_count_is(5), + }, + ).get_text() + + assert text == "It is 22 degrees." + assert _choices(client) == ["required", "auto"] + # Tools stay available so the model may call another tool OR answer. + assert client.requests[1]["tools"] + + +async def test_relaxes_a_forced_specific_tool_choice_after_a_successful_tool_round() -> None: + client = QueuedClient([_call("resp_1", "call_1"), text_response("resp_2", "Done.")]) + + await call_model( + client, + { + "model": "test-model", + "input": "weather?", + "tools": [_weather()], + "tool_choice": {"type": "function", "name": "get_weather"}, + "stop_when": step_count_is(5), + }, + ).get_text() + + assert _choices(client) == [{"type": "function", "name": "get_weather"}, "auto"] + + +async def test_relaxes_allowed_tools_required_mode_to_auto_keeping_the_tool_set() -> None: + allowed = [{"type": "function", "name": "get_weather"}] + client = QueuedClient([_call("resp_1", "call_1"), text_response("resp_2", "Done.")]) + + await call_model( + client, + { + "model": "test-model", + "input": "weather?", + "tools": [_weather()], + "tool_choice": {"type": "allowed_tools", "mode": "required", "tools": allowed}, + "stop_when": step_count_is(5), + }, + ).get_text() + + assert client.requests[1]["tool_choice"] == {"type": "allowed_tools", "mode": "auto", "tools": allowed} + + +async def test_keeps_auto_unchanged_on_follow_up_turns() -> None: + client = QueuedClient([_call("resp_1", "call_1"), text_response("resp_2", "Done.")]) + + await call_model( + client, + { + "model": "test-model", + "input": "weather?", + "tools": [_weather()], + "tool_choice": "auto", + "stop_when": step_count_is(5), + }, + ).get_text() + + assert _choices(client) == ["auto", "auto"] + + +async def test_still_forces_the_final_no_tools_turn_when_the_budget_is_exhausted() -> None: + client = QueuedClient( + [_call("resp_1", "call_1"), _call("resp_2", "call_2"), text_response("resp_3", "Final summary.")] + ) + + text = await call_model( + client, + { + "model": "test-model", + "input": "weather?", + "tools": [_weather()], + "tool_choice": "required", + "stop_when": step_count_is(2), + "allow_final_response": True, + }, + ).get_text() + + assert text == "Final summary." + assert _choices(client) == ["required", "auto", "none"] + + +async def test_keeps_an_unchanged_consumed_choice_relaxed_across_multiple_follow_up_turns() -> None: + client = QueuedClient( + [_call("resp_1", "call_1"), _call("resp_2", "call_2"), text_response("resp_3", "Final summary.")] + ) + + text = await call_model( + client, + { + "model": "test-model", + "input": "weather?", + "tools": [_weather()], + "tool_choice": "required", + "stop_when": step_count_is(5), + }, + ).get_text() + + assert text == "Final summary." + assert _choices(client) == ["required", "auto", "auto"] + + +async def test_a_forced_choice_is_not_consumed_by_a_response_without_tool_calls() -> None: + # A choice is consumed only when the response that carried it called a + # tool; a text-only answer leaves nothing to relax. + state = MemoryStateAccessor() + await call_model( + QueuedClient([text_response("resp_1", "no tools")]), + {"model": "test-model", "input": "hi", "tools": [_weather()], "tool_choice": "required", "state": state}, + ).get_text() + + assert state.stored is not None + assert state.stored.consumed_forced_tool_choice_key is None + + +async def test_persists_satisfaction_across_approval_resume_and_resets_it_after_completion() -> None: + approval_weather = _weather(require_approval=True) + state = MemoryStateAccessor() + first = QueuedClient([_call("resp_1", "call_1")]) + + await call_model( + first, + { + "model": "test-model", + "input": "What is the weather in Tokyo?", + "tools": [approval_weather], + "tool_choice": "required", + "state": state, + }, + ).get_response() + + assert _choices(first) == ["required"] + assert state.stored is not None + assert state.stored.status == "awaiting_approval" + # Same canonical key upstream persists (JCS of the choice). + assert state.stored.consumed_forced_tool_choice_key == json.dumps("required") + + resumed = QueuedClient([text_response("resp_2", "It is 22 degrees.")]) + text = await call_model( + resumed, + { + "model": "test-model", + "input": [], + "tools": [approval_weather], + "tool_choice": "required", + "state": state, + "approve_tool_calls": ["call_1"], + }, + ).get_text() + + assert text == "It is 22 degrees." + assert _choices(resumed) == ["auto"] + assert state.stored.status == "complete" + assert state.stored.consumed_forced_tool_choice_key is None + + fresh = QueuedClient([_call("resp_3", "call_2")]) + await call_model( + fresh, + { + "model": "test-model", + "input": "Start a new weather request.", + "tools": [approval_weather], + "tool_choice": "required", + "state": state, + }, + ).get_response() + + assert _choices(fresh) == ["required"] + + +async def test_relaxes_the_first_model_request_after_a_manual_client_tool_resume() -> None: + manual_weather = tool(name="get_weather", input_schema=_City, execute=False) + state = MemoryStateAccessor() + + await call_model( + QueuedClient([_call("resp_1", "call_1")]), + { + "model": "test-model", + "input": "What is the weather in Tokyo?", + "tools": [manual_weather], + "tool_choice": "required", + "state": state, + }, + ).get_response() + + assert state.stored is not None + assert state.stored.status == "awaiting_client_tools" + assert state.stored.consumed_forced_tool_choice_key == json.dumps("required") + + resumed = QueuedClient([text_response("resp_2", "It is 22 degrees.")]) + text = await call_model( + resumed, + { + "model": "test-model", + "input": [{"type": "function_call_output", "callId": "call_1", "output": json.dumps({"temperature": 22})}], + "tools": [manual_weather], + "tool_choice": "required", + "state": state, + }, + ).get_text() + + assert text == "It is 22 degrees." + assert _choices(resumed) == ["auto"] diff --git a/tests/unit/test_tool_executor_return.py b/tests/unit/test_tool_executor_return.py new file mode 100644 index 0000000..05037c2 --- /dev/null +++ b/tests/unit/test_tool_executor_return.py @@ -0,0 +1,127 @@ +"""Ported from upstream tests/unit/tool-executor-return.test.ts (generator +return capture after #110 dropped `preliminaryResults`) and the +execute-context `toolCall` threading from hitl-tool.test.ts (#91).""" + +from __future__ import annotations + +import json +from typing import Any, List + +from pydantic import BaseModel + +from openrouter_agent import call_model, tool +from openrouter_agent.tool_executor import execute_tool +from openrouter_agent.tool_types import ParsedToolCall +from tests._fixtures import MemoryStateAccessor, QueuedClient, text_response, tool_call_response + + +class _In(BaseModel): + input: str + + +class _Out(BaseModel): + result: str + + +class _Event(BaseModel): + status: str + + +async def test_generator_yields_are_broadcast_live_but_not_accumulated_on_the_result() -> None: + async def execute(params: _In, _ctx: Any) -> Any: + yield {"status": "working"} + yield {"status": "almost done"} + yield {"result": f"Done: {params.input}"} + + generator = tool(name="gen", input_schema=_In, event_schema=_Event, output_schema=_Out, execute=execute) + live: List[Any] = [] + + result = await execute_tool( + generator, + ParsedToolCall(id="call_1", name="gen", arguments={"input": "test"}), + on_preliminary_result=lambda call_id, value: live.append((call_id, value.status)), + ) + + assert result is not None + assert "error" not in result + assert live == [("call_1", "working"), ("call_1", "almost done")] + assert "preliminary_results" not in result + assert result["result"] == _Out(result="Done: test") + + +async def test_tool_result_event_does_not_carry_the_yield_history() -> None: + async def execute(_params: Any, _ctx: Any) -> Any: + yield {"status": "working"} + yield {"result": "done"} + + generator = tool(name="gen", input_schema=dict, event_schema=_Event, output_schema=_Out, execute=execute) + client = QueuedClient([tool_call_response("r1", "gen", call_id="call_g"), text_response("r2", "ok")]) + result = call_model(client, {"model": "m", "input": "go", "tools": [generator]}) + + events = [event async for event in result.get_full_responses_stream()] + + preliminary = [e for e in events if e.get("type") == "tool.preliminary_result"] + results = [e for e in events if e.get("type") == "tool.result"] + assert len(preliminary) == 1 + assert len(results) == 1 + assert "preliminaryResults" not in results[0] + assert "preliminary_results" not in results[0] + + +async def test_execute_context_carries_the_executed_tool_call_in_wire_shape() -> None: + seen: List[Any] = [] + + def execute(_params: Any, ctx: Any) -> Any: + seen.append(ctx["tool_call"]) + return {"ok": True} + + echo = tool(name="echo", input_schema=dict, execute=execute) + client = QueuedClient( + [tool_call_response("r1", "echo", call_id="call_e", arguments='{"x":1}'), text_response("r2", "ok")] + ) + + await call_model(client, {"model": "m", "input": "go", "tools": [echo]}).get_text() + + assert len(seen) == 1 + assert seen[0]["type"] == "function_call" + assert seen[0]["callId"] == "call_e" + assert seen[0]["id"] == "call_e" + assert seen[0]["name"] == "echo" + assert json.loads(seen[0]["arguments"]) == {"x": 1} + + +async def test_execute_context_carries_the_tool_call_on_the_approval_resume_path() -> None: + seen: List[Any] = [] + + def execute(_params: Any, ctx: Any) -> Any: + seen.append(ctx["tool_call"]) + return {"ok": True} + + gated = tool(name="gated", input_schema=dict, execute=execute, require_approval=True) + state = MemoryStateAccessor() + await call_model( + QueuedClient([tool_call_response("r1", "gated", call_id="call_g", arguments='{"v":2}')]), + {"model": "m", "input": "go", "tools": [gated], "state": state}, + ).get_response() + + await call_model( + QueuedClient([text_response("r2", "ok")]), + {"model": "m", "input": [], "tools": [gated], "state": state, "approve_tool_calls": ["call_g"]}, + ).get_text() + + assert [(c["callId"], json.loads(c["arguments"])) for c in seen] == [("call_g", {"v": 2})] + + +async def test_a_caller_provided_tool_call_wins() -> None: + seen: List[Any] = [] + + def execute(_params: Any, ctx: Any) -> Any: + seen.append(ctx["tool_call"]) + return {} + + echo = tool(name="echo", input_schema=dict, execute=execute) + provided = {"type": "function_call", "callId": "call_x", "name": "echo", "arguments": "{}", "status": "completed"} + + await execute_tool(echo, ParsedToolCall(id="call_x", name="echo", arguments={}), {"tool_call": provided}) + + assert seen == [provided] diff --git a/tests/unit/test_tool_factory_and_executor.py b/tests/unit/test_tool_factory_and_executor.py index 0903f61..b5c16a1 100644 --- a/tests/unit/test_tool_factory_and_executor.py +++ b/tests/unit/test_tool_factory_and_executor.py @@ -77,7 +77,8 @@ async def execute(params: Input, ctx): assert prelim == [("call_2", {"progress": 0.5})] assert result is not None assert result["result"].doubled == 8 - assert result["preliminary_results"] == [{"progress": 0.5}] + # Upstream 1.0.0 stopped accumulating yields onto the result. + assert "preliminary_results" not in result async def test_generator_tool_with_dict_event_schema_keeps_earlier_output_shaped_yields_preliminary() -> None: @@ -101,7 +102,7 @@ async def execute(params, ctx): assert "error" not in result assert result["result"].data == "final" assert prelim == [("call_4", {"phase": "progress", "data": "progress-only"})] - assert result["preliminary_results"] == [{"phase": "progress", "data": "progress-only"}] + assert "preliminary_results" not in result async def test_generator_tool_with_overlapping_dict_schemas_keeps_last_yield_as_output() -> None: diff --git a/upstreamer-changelog.md b/upstreamer-changelog.md index 6ba3704..a6c5398 100644 --- a/upstreamer-changelog.md +++ b/upstreamer-changelog.md @@ -1,5 +1,55 @@ # openrouter-agent-sdk Changelog +## Unreleased — partial backport of later `@openrouter/agent` fixes + +Not released. The package version stays `0.8.2`. This adds selected fixes and small features from upstream `@openrouter/agent` 0.9.0–1.3.0 on top of the 0.8.0 port. Upstream's larger 0.9.0+ features are **not** included yet: async/background/deferred tools, the `task` tool, steering and subagent tools, doom-loop detection, run-level cancellation and tool timeouts, tool sets, stream replay compaction, and the MCP integration. + +### Approval and resume + +- **Behavior change:** `approve_tool_calls` / `reject_tool_calls` drop duplicate IDs, so an approved call runs only once. An ID that appears in both lists raises `ValueError` before anything runs. +- **Behavior change:** resuming an `awaiting_approval` conversation without decisions now leaves it paused. Previously it sent a new model request. No request is sent and the supplied `input` is not saved. The same applies when decisions cover only some of the pending calls: the undecided calls stay pending. `awaiting_hitl` still resumes when `input` carries a `function_call_output` for a pending call. +- While a conversation stays paused, `get_response()`, `get_text()`, `get_tool_calls()` and the stream getters raise an error that names the pause and lists up to 10 pending call IDs. `requires_approval()`, `get_pending_tool_calls()` and `get_state()` still work. +- **Behavior change:** an approved HITL call whose `on_tool_called` returns `None` again stays pending, with status `awaiting_hitl`. Previously it was dropped. +- **Behavior change:** approving a call that no longer has an executable tool now records a "Tool not found or not executable" error output. Previously the call was dropped. +- When a `PreToolUse` hook rewrites an approved call's arguments on resume: + - Input-dependent approval checks run again on the new arguments. These are a callable `require_approval`, either on the tool or on the request. A plain `require_approval=True` does not ask again. + - Rewritten arguments that fail `input_schema` are blocked and reported through `PostToolUseFailure`. +- **Behavior change:** the rejection message is now `"Rejected by user"`, matching upstream. +- With `allow_final_response=False` and a `stop_when` already met on the first response, pausing for an approval-gated call no longer runs that call's auto-approved siblings. They are saved as skipped results. + +### Tool loop + +- A response cut off at `max_output_tokens` no longer runs any of its tool calls, including the ones that completed before the cut-off. The run ends with that `incomplete` response. +- **Behavior change:** a forced `tool_choice` is relaxed to `"auto"` once it has produced a tool call. This covers `"required"`, a specific tool, or `allowed_tools` with `mode: "required"`. The relaxed state survives approval and client-tool resumes: it is stored in the new `ConversationState.consumed_forced_tool_choice_key` field, which is additive within state version 1. It resets when the run completes. +- `next_turn_params` can now set `tool_choice`, and its context always includes the current `tool_choice`. +- **Behavior change:** `next_turn_params` now runs only for calls whose tool ran and returned without error, and receives the input the tool actually ran on. +- `to_model_output` now receives the parsed input, the same value `execute` gets. It also runs for results produced during approval resumes and for results saved before an approval pause. +- Tool execute contexts now always carry `tool_call` as a wire-shaped `function_call` item. Before this, the main loop passed a `ParsedToolCall` there, and the resume and final-turn paths passed nothing. +- **Behavior change:** generator tools no longer collect `preliminary_results` on the result or the `tool.result` event. Yields are still streamed live as `tool.preliminary_result` events. +- Final-response validation errors now say what is wrong (empty output array with the response ID, wrong output type, or which required fields are missing). The original message prefixes are unchanged. + +### New API + +- `ModelResult.get_usage()` returns token and cost totals across every model call in the run. It never raises; a failed or paused run returns what it accrued so far. +- `call_model(..., active_tools=[...])` sends and runs only the named client tools; server tools are always kept. An empty tool list leaves `tools` out of the request. +- `tool(..., strict=True | False)` is sent on the wire tool definition. When `strict` is not set, the tool definition now carries `"strict": null`. +- `tool(..., wire_input_schema={...})` lets a manual tool send its own JSON Schema to the model. +- `mark_mcp(tool, annotations=..., wire_input_schema=...)` records an MCP server's tool annotations and sends the server's own object schema to the model. +- `from_chat_messages` now turns assistant `tool_calls` into `function_call` items instead of dropping them. + +### Context and hooks + +- **Behavior change:** `set_context` / `set_shared_context` now store the schema's parsed value for each field they update. The merged context is validated first, so model-level validators apply. An invalid update raises and leaves the stored context unchanged. +- Blocking hooks fail closed: a `PreToolUse` or `UserPromptSubmit` chain that is aborted before every handler has run now counts as blocked. + +### Compatibility notes + +- `call_model` raises `NotImplementedError` for upstream options this port does not support yet (`doom_loop`, `signal`, `tool_timeout_ms`, `tool_concurrency`, `async_tools`, `stream_replay`). Previously they were forwarded to the API. +- `tool()` raises `ValueError` if `wire_input_schema` is passed to a tool that is not manual. Upstream enforces this only in its type definitions. +- `get_usage()` reports a failed run with a Python warning (upstream logs to the console). On an approval-resumed run it waits for the whole resumed loop. Upstream counts only the resume request there. +- Function-valued request parameters (for example a callable `tool_choice`) are still resolved once per run, not per turn. A dynamic forced `tool_choice` therefore does not re-arm between turns as it does upstream. +- `PreToolUse` still runs before the approval check on a fresh run. Upstream now asks for approval on the model's original arguments and runs `PreToolUse` afterwards. + ## 0.8.2 — stop-condition approval fix Downstream-only fix on top of the 0.8.0 port; no new upstream work.