diff --git a/.upstreamer/eval-report.md b/.upstreamer/eval-report.md index 95e04b6..2b2e9b5 100644 --- a/.upstreamer/eval-report.md +++ b/.upstreamer/eval-report.md @@ -1,267 +1,194 @@ -PASS WITH WARNINGS +FAIL -# Port Parity Eval — Python (`@openrouter/agent` 0.7.2 → 0.8.0), second pass +# Port Parity Eval — openrouter-agent-sdk vs @openrouter/agent @ b195a8b (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. +- Target upstream commit: `b195a8bfb64b63179188b3e4f0ddc1526c3bf67a`. `packages/agent/package.json` = `1.3.1`. The commit is level with the `@openrouter/agent@1.3.1` tag. +- Last ported commit (`.upstreamer/state.yaml`): `680bceb` (`@openrouter/agent@0.8.0`). +- Upstream delta under `packages/agent`: 63 commits and 151 files (+52k / −0.9k lines), spanning releases 0.9.0 → 1.3.1. +- Converter's work reviewed: the uncommitted working tree. That is 9 modified source/README files, plus 8 new untracked `tests/unit/test_*.py` files and the deleted `tests/unit/test_forced_tool_choice_one_shot.py`. +- Reviewer: independent, fresh context. I wrote only this file. Scratch reproductions live in `tmp/upstreamer/opencode/`. ## 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.** The converter's slice of work is correct. The prior pass's defect, where forced `tool_choice` was not persisted across resumes, is now fixed and matches upstream. The repository as a whole is still not a port of `@openrouter/agent` at the target commit, for four reasons: + +1. **The version check fails, and advancing state would be dishonest.** `pyproject.toml` says `0.8.3`, but upstream is `1.3.1`. `verify.sh` fails with `version drift: pyproject.toml=0.8.3, upstream @openrouter/agent=1.3.1`. `0.8.3` is also not an upstream release (upstream went 0.8.0 → 0.9.0). Bumping to 1.3.1 would overstate the port. Leaving 0.8.3 while advancing `state.yaml` to `b195a8b` would record a port level that does not exist. Under eval.md, either choice is a FAIL. +2. **Most upstream features from 0.9.0 through 1.3.1 are absent.** These include doom-loop detection, tool sets, async/background/deferred tools, subagents, steering, cancellation and timeouts, `activeTools`, the manual-tool wire schema, and MCP under `packages/agent/src/mcp`. Several of these touch the tool loop. +3. **There are behavioral parity gaps in approval/HITL ordering and loop stop semantics.** I reproduced each one (details below). +4. **58 upstream unit test files have no Python counterpart.** Many of them cover the tool loop, state, approval/HITL, hooks, and streaming. + +## Mechanical verification + +`.upstreamer/scripts/verify.sh`: +- PASS: uv sync, lockfile, ruff check/format, mypy (src + tests), pytest + coverage floor 83%, all 31 required symbols exported, no TS artifacts, repo-owned files present. +- **FAIL:** version drift (0.8.3 vs 1.3.1). +- NOTE: 58 upstream test files have no `tests/unit` counterpart. + +`uv run pytest tests/unit -q`: 287 passed, 1 xfailed (strict xfail: `test_still_forces_the_final_no_tools_turn_when_the_budget_is_exhausted`, see gap B3). + +Repo-owned files are intact: +- The coverage floor is unchanged at `--cov-fail-under=83` in `.github/workflows/ci.yaml`. +- `.github/`, LICENSE, the package name/identity and the user-agent token (`openrouter-agent-sdk`) are untouched. + +## Converter's ported items verified + +| # | Upstream | Port change | Result | +|---|---|---|---| +| 1 | a629cf1 / #97 `getUsage()` | `ModelResult.get_usage` (`model_result.py:1675`) | Correct. `test_get_usage.py` uses the shared fixtures. Upstream's streaming-resume case is not portable because the port has no parked-stream resume path. | +| 2 | 3028554 / #99 function-tool `strict` | `tool(strict=...)` (`tool.py`), `convert_tools_to_api_format` always emits `strict` (`None` when unset) (`tool_executor.py:62`) | Correct. Matches `tool-executor.ts:132` (`strict: tool.function.strict ?? null`). | +| 3 | 5a7ed03 / #95 `validateFinalResponse` messages | `_validate_final_response` | Correct (`test_final_response_validation.py`). | +| 4 | dacf4d1 / #11, #41 `fromChatMessages` emits `function_call` items | `chat_compat.from_chat_messages` | Correct. The message is skipped only when content is empty and tool calls exist. Accepts `tool_calls` and `toolCalls`, and dumps SDK models. | +| 5 | 69aae63, 703e236, 37a2aa0: no tool execution from non-`completed` responses | `stream_transformers._is_response_completed`, `response_has_tool_calls`, `extract_tool_calls_from_response` | Correct. Matches `stream-transformers.ts:819`. `test_max_output_tokens_truncation.py` ports 3 of 3 cases. The upstream file `non-completed-response-tool-calls.test.ts` maps to the port's differently named `test_non_completed_response_tools.py`, so the 1:1 name mapping is broken there. | +| 6 | 844845f: stopWhen checked before auto-approved siblings | `_pause_for_approval_skipping_siblings` | Mostly correct. Minor structural difference: the path is only entered when `resolvable_pending` is non-empty, whereas upstream calls the approval check unconditionally. | +| 7 | 66d7232 / #114 `nextTurnParams` may set `toolChoice` | `NEXT_TURN_KEYS` gains `tool_choice`; a computed choice becomes the configured policy (`model_result.py:1248-1253`) | Correct for in-run behavior (`test_next_turn_tool_choice_loop.py`). | +| 8 | 0efdbb0 / #100 (DEV-785) forced `toolChoice` relaxation, plus consumed-key persistence | `_is_forced_tool_choice`, `_relax_forced_tool_choice`, `_forced_tool_choice_key`, `_effective_tool_choice`, `_commit_tool_choice_dispatch`, `_apply_tool_choice_policy`, `ConversationState.consumed_forced_tool_choice_key` | **Now correct** (see next section). | + +Test quality of the new files: +- No hand-rolled clients. All new files use `QueuedClient`, `make_response` and `MemoryStateAccessor` from `tests/_fixtures.py`. +- `assert ... is not None` appears only as narrowing before real assertions. +- Tool-choice assertions check the full per-request sequence (for example `["required", "auto", "auto"]`), not just membership. +- Execution counts are asserted exactly (`executed == [{"location": "Tokyo"}]`). + +## Status of the prior pass's defect: FIXED + +The prior defect was that forced tool_choice relaxation state was not persisted across approval and client-tool resumes. + +Code read: +- `ConversationState.consumed_forced_tool_choice_key` (`tool_types.py:66`) mirrors upstream `consumedForcedToolChoiceKey` (`tool-types.ts:1952`). +- `_save_state` stamps the key on every save and clears it when `status == "complete"` (`model_result.py:381-391`). This mirrors upstream's persist block (`model-result.ts:5899-5910`) and `markStateComplete → resetForcedToolChoicePolicy`. +- `_load_state` reloads the key unless the loaded state is `complete` (`model_result.py:374-377`). This mirrors `model-result.ts:6074`. +- `deserialize_conversation_state` reads the key; `serialize_conversation_state` writes it via `asdict`. +- Commit timing: `_commit_tool_choice_dispatch` runs immediately after tool calls are extracted and before `_save_response_to_state` or any approval/HITL/client pause (`model_result.py:1021-1022`). This mirrors upstream's `commitToolChoiceDispatch` before pause. +- Engine overrides do not consume the choice. A `"none"` final turn or retry never commits, because the dispatched choice is compared against the policy-derived effective choice. This mirrors `beginToolChoiceDispatch`. +- A different forced value re-arms, because its key differs from the consumed key. + +Reproduction (`tmp/upstreamer/opencode/repro.py`): +- **Setup:** a specific-tool forced choice and a `require_approval` tool. The state passed through `serialize` → `deserialize` before the resume. +- **Pause:** the state stored the key `{"name":"get_weather","type":"function"}`. +- **Resume request:** sent `tool_choice: "auto"`. Afterwards the state was `complete` with the key cleared. +- **New run:** the next fresh conversational turn forced again. +- **Re-arm:** a resume with a different forced value (`"required"`) sent `"required"`. + +All of these match upstream. The ported upstream cases (approval resume plus reset, and manual client-tool resume) pass. A serialization round-trip test was added. + +Remaining minor deviations (warning-level, not defects): +- **Clear-on-unforced timing.** Upstream clears the consumed key on any dispatched unforced turn (`commitToolChoiceDispatch` with `type: 'clear'` ignores `hasToolCalls`). The port only commits when the response has calls. The only observable case is a no-calls response, which ends the run and clears the key anyway, so there is no behavioral impact. +- **Null key in serialized output.** The serialized state always contains `"consumed_forced_tool_choice_key": null`, whereas upstream deletes the property. This is cosmetic, and the state is not cross-language. +- **Uncovered upstream cases.** Three upstream `tool-choice-relaxation` cases are not ported, because the underlying features are missing (gaps B4 and B5): + - "re-arms when a dynamic forced choice resolves to a different semantic value" + - "re-arms the same dynamic forced choice after an unforced turn" + - "clears consumed choice state when an interrupted run becomes a fresh request" + +## Major absent upstream features (severity) + +### A. Whole features missing at the target (0.9.0 → 1.3.1) + +| Upstream | Port | Severity | +|---|---|---| +| Doom-loop detection, escalation, fan-out, remediation and public API (`lib/doom-loop.ts`, #73, #89; `doomLoop` option, `doom_loop` SessionEnd reason, state snapshot) | absent (`grep doom` finds nothing) | **FAIL**: loop, state, hooks | +| Unified `run()` tools, async lifecycles, task check-ins and steering, `tool.agent()` subagents (e8d7d6d / #90: `agent-tool.ts`, `async-tool-registry.ts`, `tool-task.ts`, `tool-concurrency.ts`, `inner-loop/resume-tool-results.ts`) | absent | **FAIL**: loop, state | +| Tool sets and `activeTools` (8d2ed61, 787cbf8: `tool-set.ts`, `tool-set-types.ts`) | absent | FAIL: affects the tool loop request shape | +| Tool timeouts and cancellation across background grace, approval resume and MCP wrappers (bd1c358 / #178: `toolTimeoutMs`, `signal`) | absent | FAIL: loop, approval resume | +| `tool-check.ts` | absent | Major | +| Manual-tool wire input schema (4dce84e) | absent | Major | +| Replay-buffer compaction and backlog release (17418f7, 250e64e) | not ported or verified | Major: streaming memory | +| MCP moved into `packages/agent/src/mcp` (787cbf8, 907beec, db16748, 733b6fe; 17 upstream `tests/unit/mcp/*` files) | absent | **Scope decision needed.** The contract excludes `packages/mcp/` but says "port only `packages/agent/`", and MCP now lives inside `packages/agent/`. The contract must be amended either way. Until then, this is an unreported gap. | + +### B. Behavioral parity gaps in existing features (reproduced) + +- **B1. Approval: partial decisions drop undecided calls.** Repro: `tmp/upstreamer/opencode/repro2.py`. Two approval-gated calls `a` and `b` were pending, and the run resumed with `approve_tool_calls=["a"]`. + - The port's `_build_resume_request` (`model_result.py:1347-1383`) sets `pending_tool_calls=None` and `status="in_progress"`, then sends a model request. That request has no output for `b`. The run completed with `b` silently discarded. + - Upstream keeps `b` in `remainingPending` with status `awaiting_approval` (`model-result.ts:~6455-6475`). This logic was already present at 680bceb. + - Severity: **FAIL** (approval/HITL ordering). +- **B2. Approval: decision validation from 1601bff and 1008d7e is not ported.** + - The same call ID in both `approve_tool_calls` and `reject_tool_calls` is accepted silently. Upstream throws "cannot be both approved and rejected". + - Approval IDs are not de-duplicated. + - A decision-less resume of an `awaiting_approval` state sends a new model request and completes. Upstream stays paused, and `getResponse` / `getText` reject with an explicit "awaiting approval" error. + - Severity: **FAIL** (approval/HITL). +- **B3. `stop_when` is counted over responses, not executed tool rounds.** This is the port's own strict xfail in `test_tool_choice_relaxation.py`. Upstream `shouldStopExecution` evaluates over `allToolExecutionRounds`, so `step_count_is(1)` allows one tool round. The port stops one round earlier. Severity: **FAIL** (load-bearing loop and stop conditions). It is documented in the xfail but not in the contract's divergences. +- **B4. Async/dynamic request params are resolved only at turn 0.** `model_result.py:932` calls `resolve_async_functions(..., {"number_of_turns": 0})` once. Upstream calls `resolveAsyncFunctionsForTurn` per turn (and did at 680bceb too). Dynamic `tool_choice`, `model` and similar callables never see later turns. Severity: Major (loop). This is pre-existing. +- **B5. No interruption support.** Upstream's `checkForInterruption` polls `interruptedBy` on the state accessor and saves `status: 'interrupted'` with `partialResponse`. The port never reads `interrupted_by` in `model_result.py`. Severity: Major (state). This is pre-existing. + +## Unported upstream test files (58), by severity + +Mapping is `foo-bar.test.ts` → `test_foo_bar.py`. Some tests exist under different names; those are noted. + +**FAIL-worthy (loop, state, approval/HITL, hooks, streaming):** +- Doom-loop: `doom_loop`, `doom_loop_escalation`, `doom_loop_fanout`, `doom_loop_integration`, `doom_loop_public_api`, `doom_loop_remediation`. +- Async tools and tasks: `async_tool_background`, `async_tool_deferred`, `async_tool_registry`, `agent_tool`, `task_tool_actions`, `task_tool_integration`, `steering`. +- Cancellation: `run_cancellation`, `tool_cancellation`. +- Tool sets: `call_model_active_tools`, `tool_set`. +- HITL and manual tools: `hitl_tool`, `manual_tool_calls_adversarial`, `get_items_stream_manual_tools`, `user_input_persistence`. +- Hooks: `hooks_contract_fixes`, `hooks_post_model_call`, `hooks_session_lifecycle`, `hooks_emit`, `hooks_emit_adversarial`, `hooks_resolve`, `hooks_resolve_adversarial`, `hooks_manager_adversarial`, `hooks_matchers_adversarial`, `hooks_types_adversarial`, `hooks_void_schema`. +- State and loop: `conversation_state`, `stop_conditions`, `next_turn_params`, `tool_orchestrator`, `tool_executor_return`, `turn_context`. +- Upstream `non_completed_response_tool_calls` exists only as the port's `test_non_completed_response_tools.py` (name mismatch). +- Streaming: `model_result_stream_detection`, `model_result_replay_compaction`, `replay_buffer_compaction`, `reusable_stream`, `tool_event_broadcaster`, `build_tool_call_stream`, `tool_name_events`. + +Several of these may be partially covered by differently named port files (for example `test_parity_requirements.py`, `test_lifecycle_hook_enforcement.py`, `test_hooks_abort_fail_closed.py`). They are not 1:1, so coverage cannot be confirmed per case. + +**Major:** `tool_check`, `manual_tool_wire_schema`, `tool_context`, `shared_context`, `schema_sanitization`, `create_tool`, `assistant_message_images`, `openrouter`. + +**Warning (type-level, packaging or cosmetic):** `claude_type_guards`, `tool_type_compat`, `package_boundaries`, `startup_import_closure`. + +**Scope decision pending:** the 17 files under `tests/unit/mcp/`. + +Also not mapped: upstream co-located tests `src/lib/anthropic-compat.test.ts`, `src/lib/chat-compat.test.ts` (partly covered by the new `test_chat_compat.py`) and `src/lib/next-turn-params.test.ts`. + +## Recommended human next action + +1. **Do not advance `.upstreamer/state.yaml` to `b195a8b`.** The converter's working-tree changes are sound and can be committed as a partial sync. Keep `version = "0.8.3"` and keep `upstream_commit` at `680bceb`, or at the highest upstream commit whose delta is fully ported and tested. +2. **Fix the approval/HITL gaps next.** These are B1 (partial decisions keep remaining calls pending) and B2 (approve/reject conflict error, ID de-duplication, decision-less resume stays paused and getters reject). They are FAIL-class and small. Port the matching cases from `approval-gate-regressions.test.ts` and `hitl-tool.test.ts`. +3. **Resolve B3.** Make `stop_when` count executed tool rounds, then remove the strict xfail. If it is kept, document it as a divergence. +4. **Decide the MCP scope and amend `upstreamer.md`.** Upstream moved MCP into `packages/agent/src/mcp`. +5. **Plan the 0.9.0 → 1.3.1 feature port as staged runs, one per upstream release.** Covers doom-loop, unified run/async tools/steering/subagents, tool sets/activeTools, cancellation/timeouts, per-turn async params and interruption. Port the corresponding test files in each run, and advance state per stage only after an eval passes. + +--- + +# Converter bankruptcy declaration (run targeting b195a8b) + +**Outcome: the parity eval FAILED. `.upstreamer/state.yaml` was NOT advanced; it stays at `680bceb4598f228d3e2ec58e2416e4335cdff059`. The next run retries the same delta.** + +## Why the gap can't be closed in this run + +The delta `680bceb..b195a8b` covers `@openrouter/agent` 0.8.0 → 1.3.1: 63 agent commits across 11 upstream releases, about 13.1k inserted lines in `packages/agent/src` outside MCP, and about 33.8k lines of tests. It brings in whole subsystems this port lacks: +- unified `run()` tools, background/deferred async tools, task check-ins, steering and `tool.agent()` subagents (`resume-tool-results`, `async-tool-registry`, `tool-task`, `tool-check`, `agent-tool`, `tool-concurrency`); +- doom-loop detection (`doom-loop.ts`, 1.7k lines plus fingerprint vectors); +- tool sets and `activeTools`; +- run cancellation and tool timeouts; +- replay-buffer compaction. + +`model-result.ts` grew by about 5k lines. Porting all of that faithfully, with tests, in one reviewable change is not possible inside the contract. The skill says a big unreviewable diff counts as a failed port. Setting `pyproject.toml` to `1.3.1` without those subsystems would overstate what was ported, so the version stays `0.8.3`. As a result the verifier's version-drift check fails, as it should. + +## Attempts + +1. **Attempt 1: bounded partial port.** Ported eight self-contained upstream behaviors, each with tests ported from upstream: + - `get_usage` (#97) + - tool `strict` (#99) + - final-response diagnostics (#95) + - `from_chat_messages` `function_call` items (#11/#41) + - no tool calls from non-completed responses (#125/#177) + - forced `tool_choice` relaxation (#100) + - `next_turn_params.tool_choice` (#114) + - stop_when-before-approval siblings (844845f) + + Eval pass 1: FAIL. It found one defect in this work: the consumed forced-choice key was not persisted across resumes. +2. **Attempt 2: fixed that defect.** Added `ConversationState.consumed_forced_tool_choice_key`. It is persisted on every save, cleared on completion, restored on resume, and round-trips through serialization. Ported the two matching upstream resume cases. Eval pass 2: the defect is confirmed fixed and all eight items verified, but still FAIL because of the missing subsystems above. +3. **No third attempt.** Only a full port of the missing subsystems would close the remaining gap. That is not a focused fix. + +## Recommended human action + +1. Review and merge the working-tree changes as a partial sync. Keep version `0.8.3` and `state.yaml` at `680bceb`. **Do not publish this as 1.x.** +2. **Settle the MCP scope in `.upstreamer/upstreamer.md`.** Upstream moved MCP into `packages/agent/src/mcp`, exported as the `@openrouter/agent/mcp` subpath with an optional `@modelcontextprotocol/client` peer dependency. That makes it literally inside "`packages/agent/` only" but against the intent of the `packages/mcp` exclusion. This run did not port it. +3. **Stage the port.** Point `scripts/upstream` at intermediate upstream release tags (`@openrouter/agent@0.9.0`, then each 1.x release in turn) instead of HEAD, so each run's delta is reviewable. Suggested order: + 1. approval-decision validation and decision-less resume (1601bff, 1008d7e) + 2. stop_when round counting + 3. unified run/async tools (e8d7d6d) + 4. cancellation and timeouts (bd1c358) + 5. tool sets (8d2ed61, 787cbf8) + 6. doom-loop (78c562e, 75271c3) + 7. replay compaction (17418f7, 250e64e) + 8. manual-tool wire schema (4dce84e) +4. **Fix the pre-existing gaps this run surfaced.** They are present at 0.8.0 too and were missed by the previous eval: + - `stop_when` counts every response rather than executed tool rounds, so `step_count_is(n)` stops one round early. It is pinned by a strict `xfail` in `tests/unit/test_tool_choice_relaxation.py`. + - Async request params are resolved only on turn 0. + - With `allow_final_response=False` and a met stop condition on the first response, manual-only calls end the run as `complete` instead of pausing as `awaiting_client_tools`. diff --git a/README.md b/README.md index e0372b2..2ce8649 100644 --- a/README.md +++ b/README.md @@ -88,8 +88,12 @@ async for event in result.get_tool_stream(): async for call in result.get_tool_calls_stream(): print(call.name, call.arguments) + +usage = await result.get_usage() # totals across every model call in the run ``` +`get_response()` returns only the **final** round's response, so in a multi-round tool loop its `usage` covers one generation. `get_usage()` returns the aggregate across every model call the run made (`model_calls`, `input_tokens`, `output_tokens`, `total_tokens`, `cached_tokens`, `reasoning_tokens`, and `cost` when reported) — the same numbers as the `SessionEnd` hook's `total_usage`, with no hooks required. It never raises for a failed run, so it is safe in a `finally` block. + ## Tool Variants Regular tools execute automatically when the model emits a matching `function_call`. @@ -115,6 +119,8 @@ analysis = tool( ) ``` +Pass `strict=True` (or `False`) to forward provider strict-schema adherence onto the wire tool definition; omit it to keep the provider default. OpenAI-style strict mode requires every declared property to be listed as required. + Manual tools are advertised to the model but not auto-executed. ```python @@ -191,9 +197,13 @@ The built-ins mirror the TypeScript package and OR together when provided as a l 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. +A forced `tool_choice` (`"required"`, a specific tool, or `allowed_tools` with `mode: "required"`) applies until a response made under it calls a tool; follow-up turns then send the relaxed form (`"auto"`, or the same `allowed_tools` set with `mode: "auto"`) so the model can answer in text. A tool can set the next turn's choice via `next_turn_params={"tool_choice": fn}` (for example to widen an `allowed_tools` set without changing `tools`, which keeps the prompt-cache prefix intact). + +Tool calls are only executed from responses whose status is `completed`; a response cut off at `max_output_tokens` (status `incomplete`) ends the run with none of its calls executed. + ## Format Compatibility -Use `from_claude_messages` / `to_claude_message` for Anthropic-style messages and `from_chat_messages` / `to_chat_message` for OpenAI Chat-style messages. Content that cannot be represented directly is carried as `unsupported_content` instead of being silently discarded. +Use `from_claude_messages` / `to_claude_message` for Anthropic-style messages and `from_chat_messages` / `to_chat_message` for OpenAI Chat-style messages (assistant `tool_calls` become `function_call` items, so replayed tool-calling history keeps each output paired with its call). Content that cannot be represented directly is carried as `unsupported_content` instead of being silently discarded. ## Development diff --git a/src/openrouter_agent/chat_compat.py b/src/openrouter_agent/chat_compat.py index 8861494..341b14b 100644 --- a/src/openrouter_agent/chat_compat.py +++ b/src/openrouter_agent/chat_compat.py @@ -3,7 +3,7 @@ import json from typing import Any, Dict, List, Mapping, Sequence -from ._utils import get_field +from ._utils import dump, get_field from .stream_transformers import extract_responses_message_from_response @@ -15,9 +15,17 @@ def _content_to_string(content: Any) -> str: return json.dumps(content, separators=(",", ":")) -def from_chat_messages(messages: Sequence[Mapping[str, Any]]) -> List[Dict[str, Any]]: +def _chat_tool_calls(msg: Mapping[str, Any]) -> List[Any]: + tool_calls = msg.get("tool_calls") + if tool_calls is None: + tool_calls = msg.get("toolCalls") + return list(tool_calls or []) + + +def from_chat_messages(messages: Sequence[Any]) -> List[Dict[str, Any]]: output: List[Dict[str, Any]] = [] - for msg in messages: + for raw in messages: + msg = raw if isinstance(raw, Mapping) else dump(raw) role = msg.get("role") if role == "tool": output.append( @@ -27,8 +35,32 @@ def from_chat_messages(messages: Sequence[Mapping[str, Any]]) -> List[Dict[str, "output": _content_to_string(msg.get("content")), } ) - else: - output.append({"type": "message", "role": role, "content": _content_to_string(msg.get("content"))}) + continue + if role == "assistant": + content = _content_to_string(msg.get("content")) + tool_calls = _chat_tool_calls(msg) + # Skip the message item only when there is no content AND tool + # calls take 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. Chat-format `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", + } + ) + continue + 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 212f36b..7ad40e9 100644 --- a/src/openrouter_agent/conversation_state.py +++ b/src/openrouter_agent/conversation_state.py @@ -168,6 +168,8 @@ def deserialize_conversation_state(raw_json: str) -> ConversationState: if parsed.get("unsent_tool_results") is not None: unsent_tool_results = [UnsentToolResult(**item) for item in parsed["unsent_tool_results"]] + consumed_key = parsed.get("consumed_forced_tool_choice_key") + partial_response = None if parsed.get("partial_response") is not None: partial_response = PartialResponse(**parsed["partial_response"]) @@ -184,6 +186,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=consumed_key if isinstance(consumed_key, str) else None, ) diff --git a/src/openrouter_agent/model_result.py b/src/openrouter_agent/model_result.py index 345291c..861bbb9 100644 --- a/src/openrouter_agent/model_result.py +++ b/src/openrouter_agent/model_result.py @@ -104,6 +104,22 @@ def _extract_model_call_usage(usage: Any) -> Optional[Dict[str, Any]]: return result +def _describe_non_record(value: Any) -> str: + """Name a value's runtime type using upstream's JS vocabulary + (`null`, `array`, `string`, `number`, `boolean`, `object`).""" + if value is None: + return "null" + if isinstance(value, (list, tuple)): + return "array" + if isinstance(value, str): + return "string" + if isinstance(value, bool): + return "boolean" + if isinstance(value, (int, float)): + return "number" + return "object" + + def _tool_input_for_hooks(tool: Tool, arguments: Any) -> Dict[str, Any]: parsed = parsed_tool_input(tool, arguments) if isinstance(parsed, Mapping): @@ -171,31 +187,51 @@ def _replace_user_message_prompt(item: Any, mutated_prompt: str) -> Any: return item -def _is_specific_forced_tool_choice(tool_choice: Any) -> bool: - """Return True when `tool_choice` pins a specific tool (e.g. a named function). +def _request_tool_choice(request: Mapping[str, Any]) -> Any: + if "tool_choice" in request: + return request["tool_choice"] + return request.get("toolChoice") + + +def _is_forced_tool_choice(tool_choice: Any) -> bool: + """Whether a caller-configured tool choice requires this turn to call a tool. - String modes (`"auto"`, `"none"`, `"required"`) and `allowed_tools` allowlists - constrain tool usage without forcing the same tool on every follow-up turn. + `"required"`, a specific-tool choice (`{"type": "function", "name": ...}`, + `{"type": "web_search_preview"}`, ...), and `allowed_tools` with + `mode: "required"` force a call; `"auto"`, `"none"`, `allowed_tools` with + `mode: "auto"`, and an absent choice do not. """ if tool_choice is None or isinstance(tool_choice, str): - return False - choice_type = get_field(tool_choice, "type") - if choice_type == "allowed_tools": - return False - if isinstance(choice_type, str) and choice_type: - return True - name = get_field(tool_choice, "name") - if isinstance(name, str) and name: - return True - return get_field(tool_choice, "function") is not None + return tool_choice == "required" + if get_field(tool_choice, "type") == "allowed_tools": + return get_field(tool_choice, "mode") == "required" + return True + +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). -def _clear_forced_tool_choice(request: Mapping[str, Any]) -> Dict[str, Any]: - cleaned = dict(request) - for key in ("tool_choice", "toolChoice"): - if key in cleaned and _is_specific_forced_tool_choice(cleaned[key]): - cleaned.pop(key, None) - return cleaned + - `"required"` -> `"auto"` + - a specific-tool choice -> `"auto"` + - `allowed_tools` with `mode: "required"` -> the same set with `mode: "auto"` + (the constraint on *which* tools may be used still applies) + - unforced choices 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": + return ( + _update_field(tool_choice, "mode", "auto") if get_field(tool_choice, "mode") == "required" else tool_choice + ) + return "auto" + + +def _forced_tool_choice_key(tool_choice: Any) -> Optional[str]: + """Stable identity for a forced choice; None means tools are not forced.""" + if not _is_forced_tool_choice(tool_choice): + return None + return json.dumps(dump(tool_choice), sort_keys=True, separators=(",", ":"), default=str) class ModelResult: @@ -219,6 +255,12 @@ def __init__(self, options: Mapping[str, Any]) -> None: self._session_start_emitted = False self._session_end_emitted = False self._all_tool_rounds = 0 + # Forced caller tool choice policy (upstream DEV-785 / #114): a forced + # choice is one-shot -- once a response dispatched under it called a + # tool, follow-up turns get the relaxed form until the configured + # choice changes (e.g. via next_turn_params). + self._configured_tool_choice: Any = None + self._consumed_forced_tool_choice_key: Optional[str] = None self._session_usage: Dict[str, Any] = { "model_calls": 0, "input_tokens": 0, @@ -328,6 +370,10 @@ async def _load_state(self) -> None: loaded = await maybe_await(accessor.load()) self._resuming_from_client_tools = bool(loaded is not None and loaded.status == "awaiting_client_tools") self._state = loaded or create_initial_state() + # A completed conversation starts a new logical run that may force its + # first tool call again; a paused one keeps its consumed forced choice. + if loaded is not None and loaded.status != "complete": + self._consumed_forced_tool_choice_key = loaded.consumed_forced_tool_choice_key if not self._resuming_from_client_tools: self._state = update_state(self._state, {"status": "in_progress"}) await maybe_await(accessor.save(self._state)) @@ -336,7 +382,13 @@ async def _save_state(self, **updates: Any) -> None: accessor = self.options.get("state") if accessor is None or self._state is None: return - self._state = update_state(self._state, updates) + if updates.get("status") == "complete": + # Terminal exit: a later conversational turn may force again. + self._consumed_forced_tool_choice_key = None + self._state = update_state( + self._state, + {**updates, "consumed_forced_tool_choice_key": self._consumed_forced_tool_choice_key}, + ) await maybe_await(accessor.save(self._state)) def _response_output_items(self, response: Any) -> List[Any]: @@ -382,14 +434,38 @@ 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. + + The message prefixes (`Invalid final response: missing required + fields`, `Invalid final response: empty or invalid output`) are + load-bearing -- callers match on them. Detail naming the actual defect + is appended after them; 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") + # Mirrors upstream's JS truthiness check: a falsy scalar output counts as + # missing, while an empty list/dict is present (and handled below). + output_missing = output is None or (not isinstance(output, (list, Mapping)) and not output) + if not response_id or output_missing: + missing: List[str] = [] + if not response_id: + missing.append("id") + if output_missing: + missing.append("output") + 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 \u2014 {detail}") # -- hooks ----------------------------------------------------------- @@ -421,25 +497,37 @@ 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 as a fresh + `SessionUsageTotals` dict. `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 the + public `get_usage()` accessor, 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: @@ -451,6 +539,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", ""), @@ -876,14 +966,21 @@ async def _run(self) -> Any: elif fresh_input: request["input"] = fresh_input - current_request = request + self._configured_tool_choice = _request_tool_choice(request) + # A forced choice consumed before a pause stays relaxed on the + # resumed run's first request (persisted in state). + current_request = ( + self._apply_tool_choice_policy(request) + if self._consumed_forced_tool_choice_key is not None + else 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) + current_request = await self._build_resume_request(current_request) is_resume_turn = True final_response = None @@ -920,9 +1017,9 @@ async def _run(self) -> Any: ) if self.options.get("on_turn_end"): await maybe_await(self.options["on_turn_end"]({"number_of_turns": turn_number}, response)) - calls = ( - extract_tool_calls_from_response(response) if get_field(response, "status") == "completed" else [] - ) + calls = extract_tool_calls_from_response(response) + if calls: + self._commit_tool_choice_dispatch(current_request) self._tool_calls.extend(calls) final_response = response await self._save_response_to_state(response) @@ -963,6 +1060,15 @@ 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: + # Upstream runs the approval check on the first response + # even when stop_when is already met: an approval-gated + # call still pauses, but with allow_final_response=False + # its auto-executable siblings must NOT run -- they are + # recorded as skipped so the resume turn stays well-formed. + if await self._pause_for_approval_skipping_siblings(calls, tools, current_request): + 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} @@ -1138,17 +1244,14 @@ async def _run(self) -> Any: self._all_tool_rounds += 1 force_resume_count = 0 next_params = await execute_next_turn_params_functions(executed_calls, tools, current_request) - preserve_tool_choice = False if next_params: if "tool_choice" in next_params or "toolChoice" in next_params: - current_request = { - k: v for k, v in current_request.items() if k not in {"tool_choice", "toolChoice"} - } - preserve_tool_choice = True + # A tool-computed tool_choice becomes the new caller-level + # policy, not a one-turn override (upstream #114). + camel_choice = next_params.pop("toolChoice", None) + self._configured_tool_choice = next_params.pop("tool_choice", camel_choice) current_request = apply_next_turn_params_to_request(current_request, next_params) - current_request = self._build_followup_request( - current_request, response, outputs, preserve_tool_choice=preserve_tool_choice - ) + current_request = self._build_followup_request(current_request, response, outputs) else: raise RuntimeError("call_model exceeded the 20-turn safety limit") @@ -1186,6 +1289,38 @@ async def _run(self) -> Any: self._run_done = True self._condition.notify_all() + async def _pause_for_approval_skipping_siblings( + self, calls: Sequence[ParsedToolCall], tools: Sequence[Tool], current_request: Mapping[str, Any] + ) -> bool: + """Pause at the approval gate without executing any call. + + Returns True when the turn paused as `awaiting_approval`; False when no + call needs approval (the caller then ends the run as a stop_when exit). + """ + self._assert_unique_call_ids(calls, tools) + turn_context = {"number_of_turns": 1, "turn_request": current_request} + requires_approval, executable_calls, gate_results = await self._resolve_approval_gate( + calls, tools, turn_context + ) + if not requires_approval: + return False + 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_ids = {result.call_id for result in gate_results} + skipped = [ + create_rejected_result(call.id, call.name, "Tool execution skipped: stop condition met") + for call in executable_calls + if call.id not in resolved_ids + ] + unsent = [*skipped, *gate_results] + await self._save_state( + pending_tool_calls=list(requires_approval), + unsent_tool_results=unsent or None, + status="awaiting_approval", + ) + return True + def _call_is_auto_resolvable(self, call: ParsedToolCall, tools: Sequence[Tool]) -> bool: tool = self._find_tool(call.name, tools) return bool(tool and is_auto_resolvable_tool(tool)) @@ -1270,19 +1405,50 @@ def _build_followup_request( request: Mapping[str, Any], response: Any, outputs: Sequence[Any], - *, - preserve_tool_choice: bool = False, ) -> Dict[str, Any]: output_items = get_field(response, "output", []) or [] if not isinstance(output_items, list): output_items = [output_items] - base_request = dict(request) if preserve_tool_choice else _clear_forced_tool_choice(request) + base_request = self._apply_tool_choice_policy(request) return { **base_request, "input": [*normalize_input_to_array(request.get("input")), *output_items, *outputs], "stream": True, } + def _effective_tool_choice(self) -> Any: + configured = self._configured_tool_choice + key = _forced_tool_choice_key(configured) + if key is not None and key == self._consumed_forced_tool_choice_key: + return _relax_forced_tool_choice(configured) + return configured + + def _commit_tool_choice_dispatch(self, dispatched_request: Mapping[str, Any]) -> None: + """A response that called a tool was materialized: if it was dispatched + under the caller's (policy-derived) choice, a forced choice is now + consumed and an unforced one clears the consumed key. Engine overrides + (`"none"` on the final turn / retry) never commit caller state.""" + dispatched = _request_tool_choice(dispatched_request) + if json.dumps(dump(dispatched), sort_keys=True, default=str) != json.dumps( + dump(self._effective_tool_choice()), sort_keys=True, default=str + ): + return + self._consumed_forced_tool_choice_key = _forced_tool_choice_key(self._configured_tool_choice) + + def _apply_tool_choice_policy(self, request: Mapping[str, Any]) -> Dict[str, Any]: + """Derive the caller-configured tool choice for a follow-up turn. + + A forced choice that was already consumed this run is relaxed (see + `_relax_forced_tool_choice`); a different forced value re-arms. Engine + overrides (`"none"` for the final turn / empty-final retry) are applied + after this and still win. + """ + updated = {k: v for k, v in request.items() if k not in {"tool_choice", "toolChoice"}} + effective = self._effective_tool_choice() + if effective is not None: + updated["tool_choice"] = effective + return updated + def _build_final_request( self, request: Mapping[str, Any], response: Any, outputs: Sequence[Any], allow_final_response: Any ) -> Dict[str, Any]: @@ -1506,6 +1672,40 @@ async def get_state(self) -> Any: await self.get_response() return self._state + async def get_usage(self) -> Dict[str, Any]: + """Aggregate token/cost usage across **every** model call this run made. + + Covers the initial request, each tool-round follow-up, the empty-final + retry, the `allow_final_response` final turn, and approval-resume + requests. Same `SessionUsageTotals` shape (and the same numbers) as the + `SessionEnd` hook's `total_usage`: `model_calls`, `input_tokens`, + `output_tokens`, `total_tokens`, `cached_tokens`, `reasoning_tokens`, + plus `cost` only when the server reported cost for at least one call. + + `get_response()` returns only the **final** round's response, so in a + multi-round tool loop the earlier generations' tokens are otherwise + unreachable without a hook. This gates on run completion like + `get_response()`. On a run that paused (approval / HITL / client tools) + or failed, it returns the totals accrued so far -- `model_calls: 0` + with zeroed tokens when no model call completed. + + Unlike `get_response()`, this never raises for a failed run: cost + accounting usually runs in a `finally`/`except` where a second raise + would mask the original error. Await `get_response()` to observe the + failure itself. + """ + try: + await self._ensure_task() + except asyncio.CancelledError: + # Only swallow the run task's own cancellation; cancellation of the + # caller must still propagate. + if self._run_task is None or not self._run_task.cancelled(): + raise + warnings.warn("[get_usage] run was cancelled; reporting totals accrued so far", stacklevel=2) + except Exception as error: # noqa: BLE001 - "never raises" contract, see docstring + 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 2dad6ed..2b511a4 100644 --- a/src/openrouter_agent/next_turn_params.py +++ b/src/openrouter_agent/next_turn_params.py @@ -6,11 +6,24 @@ from .conversation_state import parsed_tool_input 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} + if "tool_choice" not in context and "toolChoice" in request: + context["tool_choice"] = request.get("toolChoice") + 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..06770b7 100644 --- a/src/openrouter_agent/stream_transformers.py +++ b/src/openrouter_agent/stream_transformers.py @@ -38,8 +38,32 @@ def extract_responses_message_from_response(response: Any) -> Any: raise ValueError("Response does not contain a message output item") +def _is_response_completed(response: Any) -> bool: + """Only a `completed` response carries tool calls the model actually made. + + An `incomplete` response (e.g. stopped at `max_output_tokens`) holds an + unfinished batch -- the last call's arguments are a fragment, and running + the complete prefix would leave the model a result set with a silent hole + -- so none of its calls are extracted. `failed`/`in_progress`/... likewise. + """ + return get_field(response, "status") == "completed" + + +def response_has_tool_calls(response: Any) -> bool: + if not _is_response_completed(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 parsed tool calls from a completed response. + + Any response whose status is not `"completed"` yields no tool calls (see + `_is_response_completed`). + """ calls: List[ParsedToolCall] = [] + if not _is_response_completed(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..3d80b70 100644 --- a/src/openrouter_agent/tool.py +++ b/src/openrouter_agent/tool.py @@ -19,6 +19,7 @@ def tool( on_tool_called: Any = None, on_response_received: Any = None, to_model_output: Any = None, + strict: Optional[bool] = None, ) -> Dict[str, Any]: if name == SHARED_CONTEXT_KEY: raise ValueError('Tool name "shared" is reserved for shared context. Choose a different name.') @@ -37,6 +38,12 @@ 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: + # Provider strict-schema adherence for this tool's generated arguments + # (OpenAI structured-outputs style). Forwarded onto the wire tool + # definition unchanged; omit to leave the provider default. Strict mode + # requires every declared property to be listed in `required`. + fn["strict"] = strict if on_tool_called is not None: if output_schema is None: raise ValueError(f'HITL tool "{name}" must declare an output_schema.') diff --git a/src/openrouter_agent/tool_executor.py b/src/openrouter_agent/tool_executor.py index 7102c42..a977cde 100644 --- a/src/openrouter_agent/tool_executor.py +++ b/src/openrouter_agent/tool_executor.py @@ -59,6 +59,8 @@ def convert_tools_to_api_format(tools: Sequence[Tool]) -> List[Dict[str, Any]]: } if fn.get("description") is not None: api["description"] = fn["description"] + # Mirrors upstream: always present, `None` (null) leaves the provider default. + api["strict"] = fn.get("strict") converted.append(api) return converted diff --git a/src/openrouter_agent/tool_types.py b/src/openrouter_agent/tool_types.py index 8199c6c..2ee1a35 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 + #: Canonical key of the forced `tool_choice` most recently consumed by the + #: active logical run. Persisted across approval, HITL, and client-tool + #: pauses so an unchanged forced choice stays relaxed after resume while a + #: different forced value re-arms. Cleared when the run completes. + consumed_forced_tool_choice_key: Optional[str] = None @dataclass(frozen=True) diff --git a/tests/unit/test_chat_compat.py b/tests/unit/test_chat_compat.py new file mode 100644 index 0000000..d4db95b --- /dev/null +++ b/tests/unit/test_chat_compat.py @@ -0,0 +1,160 @@ +"""Port of upstream src/lib/chat-compat.test.ts -- assistant tool-call conversion (#11, #41). + +Divergence (pre-existing, kept): this port's message items carry an explicit +`"type": "message"`; upstream emits bare `{role, content}` easy-input messages. +Both are valid Responses API input items. +""" + +from __future__ import annotations + +from typing import Any, Dict, List + +from openrouter_agent import call_model, from_chat_messages, tool +from tests._fixtures import QueuedClient, text_response + + +def test_emits_function_call_for_assistant_with_null_content_and_one_tool_call() -> None: + result = from_chat_messages( + [ + {"role": "user", "content": "What is the weather in Paris?"}, + { + "role": "assistant", + "content": None, + "tool_calls": [ + { + "id": "call_123", + "type": "function", + "function": {"name": "get_weather", "arguments": '{"location":"Paris"}'}, + } + ], + }, + {"role": "tool", "content": "Sunny, 22C", "tool_call_id": "call_123"}, + ] + ) + + assert result == [ + {"type": "message", "role": "user", "content": "What is the weather in Paris?"}, + { + "type": "function_call", + "callId": "call_123", + "id": "call_123", + "name": "get_weather", + "arguments": '{"location":"Paris"}', + "status": "completed", + }, + {"type": "function_call_output", "callId": "call_123", "output": "Sunny, 22C"}, + ] + + +def test_emits_message_and_function_call_when_assistant_has_text_and_tool_calls() -> None: + result = from_chat_messages( + [ + { + "role": "assistant", + "content": "Let me check the weather for you.", + # camelCase key (upstream's SDK shape) is accepted too. + "toolCalls": [ + { + "id": "call_456", + "type": "function", + "function": {"name": "get_weather", "arguments": '{"location":"London"}'}, + } + ], + } + ] + ) + + assert result == [ + {"type": "message", "role": "assistant", "content": "Let me check the weather for you."}, + { + "type": "function_call", + "callId": "call_456", + "id": "call_456", + "name": "get_weather", + "arguments": '{"location":"London"}', + "status": "completed", + }, + ] + + +def test_emits_one_function_call_per_parallel_tool_call_in_order() -> None: + result = from_chat_messages( + [ + { + "role": "assistant", + "content": None, + "tool_calls": [ + {"id": "call_a", "type": "function", "function": {"name": "get_weather", "arguments": "{}"}}, + {"id": "call_b", "type": "function", "function": {"name": "get_time", "arguments": '{"tz":"UTC"}'}}, + ], + } + ] + ) + + assert [(item["type"], item["callId"], item["name"]) for item in result] == [ + ("function_call", "call_a", "get_weather"), + ("function_call", "call_b", "get_time"), + ] + + +def test_does_not_restringify_already_serialized_arguments() -> None: + result = from_chat_messages( + [ + { + "role": "assistant", + "content": None, + "tool_calls": [ + {"id": "call_raw", "type": "function", "function": {"name": "noop", "arguments": '{"a":1}'}} + ], + } + ] + ) + + assert len(result) == 1 + assert result[0]["arguments"] == '{"a":1}' + + +def test_content_less_assistant_without_tool_calls_still_round_trips_as_empty_message() -> None: + assert from_chat_messages([{"role": "assistant", "content": None}]) == [ + {"type": "message", "role": "assistant", "content": ""} + ] + + +async def test_replayed_chat_history_sends_function_call_before_its_output() -> None: + """The point of #11: replaying a tool-calling chat history through call_model + must not orphan the function_call_output from its function_call.""" + client = QueuedClient([text_response("r1", "It was sunny.")]) + executed: List[Dict[str, Any]] = [] + history = from_chat_messages( + [ + {"role": "user", "content": "Weather in Paris?"}, + { + "role": "assistant", + "content": None, + "tool_calls": [ + {"id": "call_1", "type": "function", "function": {"name": "get_weather", "arguments": "{}"}} + ], + }, + {"role": "tool", "content": "Sunny", "tool_call_id": "call_1"}, + {"role": "user", "content": "And so?"}, + ] + ) + + result = call_model( + client, + { + "model": "test-model", + "input": history, + "tools": [tool(name="get_weather", input_schema=dict, execute=lambda p, _c: executed.append(p))], + }, + ) + + assert await result.get_text() == "It was sunny." + assert executed == [] + assert len(client.requests) == 1 + sent = client.requests[0]["input"] + types = [item.get("type") for item in sent] + assert types == ["message", "function_call", "function_call_output", "message"] + # Transport boundary normalizes callId -> call_id (model_result.py `_send`). + assert sent[1]["call_id"] == "call_1" + assert sent[2]["call_id"] == "call_1" diff --git a/tests/unit/test_final_response_validation.py b/tests/unit/test_final_response_validation.py new file mode 100644 index 0000000..9d98c46 --- /dev/null +++ b/tests/unit/test_final_response_validation.py @@ -0,0 +1,113 @@ +"""Port of upstream tests/unit/final-response-validation.test.ts (#45, #95). + +The validator is a pure array-length check; these pin the diagnostics so the +message names the actual defect. Like upstream, the validator is driven +directly because the not-an-array / missing-field shapes are unreachable +through `call_model` -- no request is ever dispatched. +""" + +from __future__ import annotations + +import re +from typing import Any, Callable + +import pytest + +from openrouter_agent import ModelResult +from tests._fixtures import QueuedClient, function_call_item, make_response, message_item + +Validator = Callable[..., None] + + +def _validator() -> Validator: + result = ModelResult({"client": QueuedClient([]), "request": {"model": "test-model", "input": "hello"}}) + return result._validate_final_response + + +def _response(**overrides: Any) -> Any: + response = make_response("resp_1", []) + for key, value in overrides.items(): + if value is _MISSING: + response.pop(key, None) + else: + response[key] = value + return response + + +_MISSING = object() + + +class TestEmptyOutputArray: + def test_reports_the_empty_array_its_length_and_the_response_id(self) -> None: + with pytest.raises(ValueError, match=r'output array is empty \(length 0\) for response "resp_empty"'): + _validator()(_response(id="resp_empty", output=[])) + + def test_points_at_the_strict_and_allow_final_response_options(self) -> None: + with pytest.raises(ValueError, match=r"strict_final_response/allow_final_response"): + _validator()(_response(output=[])) + + def test_explains_that_the_provider_returned_no_output_items(self) -> None: + with pytest.raises(ValueError, match=r"The model returned no output items"): + _validator()(_response(output=[])) + + def test_keeps_the_historical_message_prefix(self) -> None: + with pytest.raises(ValueError, match=r"^Invalid final response: empty or invalid output"): + _validator()(_response(output=[])) + + def test_stays_a_single_line(self) -> None: + with pytest.raises(ValueError) as excinfo: + _validator()(_response(output=[])) + message = str(excinfo.value) + assert message != "" + assert "\n" not in message + + def test_does_not_raise_when_empty_output_is_explicitly_allowed(self) -> None: + _validator()(_response(output=[]), True) + + +class TestOutputPresentButNotAnArray: + @pytest.mark.parametrize( + ("output", "type_name"), + [("not an array", "string"), ({"type": "message"}, "object"), (42, "number")], + ) + def test_names_the_offending_runtime_type(self, output: Any, type_name: str) -> None: + with pytest.raises(ValueError) as excinfo: + _validator()(_response(output=output)) + message = str(excinfo.value) + assert re.search(rf"output is not an array \(got {type_name}\)", message) + # Does NOT claim the array is empty for a non-array output. + assert "output array is empty" not in message + + def test_is_still_tolerated_under_allow_empty_output(self) -> None: + # Pre-existing upstream behavior, pinned so a future logic fix is deliberate. + _validator()(_response(output="not an array"), True) + + +class TestMissingRequiredFields: + def test_names_id_when_only_the_id_is_missing(self) -> None: + with pytest.raises(ValueError, match=r"missing required fields: id$"): + _validator()(_response(id=_MISSING, output=[{"type": "message"}])) + + def test_names_output_when_only_output_is_missing(self) -> None: + with pytest.raises(ValueError, match=r"missing required fields: output$"): + _validator()(_response(output=_MISSING)) + + def test_names_both_fields_when_both_are_missing(self) -> None: + with pytest.raises(ValueError, match=r"missing required fields: id, output$"): + _validator()(_response(id=_MISSING, output=_MISSING)) + + def test_treats_a_none_response_as_missing_both_fields(self) -> None: + with pytest.raises(ValueError, match=r"missing required fields: id, output$"): + _validator()(None) + + def test_keeps_the_historical_message_prefix(self) -> None: + with pytest.raises(ValueError, match=r"^Invalid final response: missing required fields"): + _validator()(_response(output=_MISSING)) + + +class TestValidOutputs: + def test_accepts_a_tool_call_only_output(self) -> None: + _validator()(_response(output=[function_call_item("call_1", "do_thing")])) + + def test_accepts_a_normal_message_output(self) -> None: + _validator()(_response(output=[message_item("hi")])) diff --git a/tests/unit/test_forced_tool_choice_one_shot.py b/tests/unit/test_forced_tool_choice_one_shot.py deleted file mode 100644 index 0d8b740..0000000 --- a/tests/unit/test_forced_tool_choice_one_shot.py +++ /dev/null @@ -1,127 +0,0 @@ -"""Specific forced tool_choice is one-shot on follow-up turns unless re-set via next_turn_params.""" - -from __future__ import annotations - -from typing import Any, Dict, List - -import pytest -from openrouter.components import OpenAIResponsesToolChoiceFunction - -from openrouter_agent import call_model, tool -from tests._fixtures import QueuedClient, text_response, tool_call_response - - -def _tool(name: str, executed: List[str], next_turn_params: Dict[str, Any] | None = None) -> Any: - def execute(params: Dict[str, Any], _ctx: Any) -> Dict[str, Any]: - executed.append(name) - return {"ran": name} - - options: Dict[str, Any] = {"name": name, "input_schema": dict, "execute": execute} - if next_turn_params is not None: - options["next_turn_params"] = next_turn_params - return tool(**options) - - -@pytest.mark.parametrize( - ("key", "forced_choice"), - [ - ("tool_choice", {"type": "function", "name": "charge_card"}), - ("toolChoice", {"type": "function", "name": "charge_card"}), - ("tool_choice", {"type": "function", "function": {"name": "charge_card"}}), - ("tool_choice", OpenAIResponsesToolChoiceFunction(type="function", name="charge_card")), - ("tool_choice", {"type": "web_search_preview"}), - ], -) -async def test_specific_forced_tool_choice_is_cleared_on_followup_turn(key: str, forced_choice: Any) -> None: - executed: List[str] = [] - client = QueuedClient( - [ - tool_call_response("r1", "charge_card", call_id="call_1", arguments="{}"), - text_response("r2", "charged once"), - ] - ) - - result = call_model( - client, - { - "model": "test/model", - "input": "charge", - "tools": [_tool("charge_card", executed)], - key: forced_choice, - }, - ) - - assert await result.get_text() == "charged once" - assert executed == ["charge_card"] - assert len(client.requests) == 2 - assert client.requests[0]["tool_choice"] == forced_choice - assert "tool_choice" not in client.requests[1] - - -async def test_next_turn_params_can_explicitly_set_forced_tool_choice_for_next_turn() -> None: - executed: List[str] = [] - step_two_choice = {"type": "function", "name": "step_two"} - step_one = _tool( - "step_one", - executed, - next_turn_params={"tool_choice": lambda _args, _ctx: step_two_choice}, - ) - step_two = _tool("step_two", executed) - - client = QueuedClient( - [ - tool_call_response("r1", "step_one", call_id="call_1", arguments="{}"), - tool_call_response("r2", "step_two", call_id="call_2", arguments="{}"), - text_response("r3", "all done"), - ] - ) - - result = call_model( - client, - { - "model": "test/model", - "input": "run two steps", - "tools": [step_one, step_two], - "toolChoice": {"type": "function", "name": "step_one"}, - }, - ) - - assert await result.get_text() == "all done" - assert executed == ["step_one", "step_two"] - assert len(client.requests) == 3 - assert client.requests[0]["tool_choice"] == {"type": "function", "name": "step_one"} - assert client.requests[1]["tool_choice"] == step_two_choice - assert "tool_choice" not in client.requests[2] - - -@pytest.mark.parametrize( - "preserved_choice", - [ - "auto", - "required", - {"type": "allowed_tools", "mode": "auto", "tools": [{"type": "function", "name": "lookup"}]}, - ], -) -async def test_non_specific_tool_choice_is_preserved_on_followup_turn(preserved_choice: Any) -> None: - executed: List[str] = [] - client = QueuedClient( - [ - tool_call_response("r1", "lookup", call_id="call_1", arguments="{}"), - text_response("r2", "found"), - ] - ) - - result = call_model( - client, - { - "model": "test/model", - "input": "look up", - "tools": [_tool("lookup", executed)], - "tool_choice": preserved_choice, - }, - ) - - assert await result.get_text() == "found" - assert len(client.requests) == 2 - assert client.requests[0]["tool_choice"] == preserved_choice - assert client.requests[1]["tool_choice"] == preserved_choice diff --git a/tests/unit/test_get_usage.py b/tests/unit/test_get_usage.py new file mode 100644 index 0000000..e6c10ac --- /dev/null +++ b/tests/unit/test_get_usage.py @@ -0,0 +1,288 @@ +"""Port of upstream tests/unit/get-usage.test.ts (#97). + +`get_usage()` aggregates token/cost usage over every model call a run made, +works without hooks, agrees with `SessionEnd.total_usage`, and never raises +for a failed run. + +Compatibility note (documented divergence): upstream's `getUsage()` on an +approval-*resumed* run counts the resume generation but does not drive further +tool rounds. In this port every getter drives the single `_run` task to its +end, so `get_usage()` on a resumed run reports the totals of the whole resumed +run. The two upstream cases pinning that carve-out ("does not advance an +approval-resumed run when read before the loop", "counts a STREAMING resume +generation without advancing the loop") are therefore not ported. +""" + +from __future__ import annotations + +from typing import Any, Dict, List + +import pytest + +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, + "input_tokens_details": {"cached_tokens": 25}, + "output_tokens": 50, + "output_tokens_details": {"reasoning_tokens": 10}, + "total_tokens": 150, + "cost": 0.002, + } + base.update(overrides) + return base + + +_ROUND_TWO_USAGE = _usage(input_tokens=200, output_tokens=100, total_tokens=300, cost=0.003) + +_TWO_ROUND_TOTALS = { + "model_calls": 2, + "input_tokens": 300, + "output_tokens": 150, + "total_tokens": 450, + "cached_tokens": 50, + "reasoning_tokens": 20, + "cost": 0.005, +} + +_ONE_CALL_TOTALS = { + "model_calls": 1, + "input_tokens": 100, + "output_tokens": 50, + "total_tokens": 150, + "cached_tokens": 25, + "reasoning_tokens": 10, + "cost": 0.002, +} + + +def _echo_tool() -> Any: + return tool(name="echo", input_schema=dict, execute=lambda _params, _ctx: {"ok": True}) + + +def _approval_tool(executed: List[Any]) -> Any: + def execute(params: Any, _ctx: Any) -> Dict[str, Any]: + executed.append(params) + return {"done": True} + + return tool(name="risky", input_schema=dict, execute=execute, require_approval=True) + + +def _assert_totals(actual: Dict[str, Any], expected: Dict[str, Any]) -> None: + assert set(actual) == set(expected) + for key, value in expected.items(): + assert actual[key] == pytest.approx(value), key + + +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", "hello back", usage=_ROUND_TWO_USAGE), + ] + ) + result = call_model(client, {"model": "test-model", "input": "hi", "tools": [_echo_tool()]}) + + final_response = await result.get_response() + _assert_totals(await result.get_usage(), _TWO_ROUND_TOTALS) + # The gap this closes: the final response alone reports only round 2. + assert final_response["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", "hello back", usage=_usage())] + ) + result = call_model(client, {"model": "test-model", "input": "hi", "tools": [_echo_tool()]}) + + usage = await result.get_usage() + + assert usage["model_calls"] == 2 + assert usage["total_tokens"] == 300 + assert len(client.requests) == 2 + + +async def test_accumulates_with_no_hooks_configured() -> None: + client = QueuedClient([text_response("r1", "hello back", usage=_usage())]) + result = call_model(client, {"model": "test-model", "input": "hi"}) + await result.get_text() + + _assert_totals(await result.get_usage(), _ONE_CALL_TOTALS) + + +async def test_reports_complete_totals_after_consuming_get_items_stream_on_a_tool_loop() -> None: + client = QueuedClient( + [tool_call_response("r1", "echo", usage=_usage()), text_response("r2", "hello back", usage=_ROUND_TWO_USAGE)] + ) + result = call_model(client, {"model": "test-model", "input": "hi", "tools": [_echo_tool()]}) + + async for _item in result.get_items_stream(): + pass + + _assert_totals(await result.get_usage(), _TWO_ROUND_TOTALS) + + +async def test_reports_complete_totals_after_consuming_the_no_tools_get_items_stream() -> None: + client = QueuedClient([text_response("r1", "hello back", usage=_usage())]) + result = call_model(client, {"model": "test-model", "input": "hi"}) + + async for _item in result.get_items_stream(): + pass + + usage = await result.get_usage() + assert usage["model_calls"] == 1 + assert usage["total_tokens"] == 150 + + +async def test_agrees_with_the_session_end_total_usage_hook_payload() -> None: + client = QueuedClient( + [tool_call_response("r1", "echo", usage=_usage()), text_response("r2", "hello back", usage=_usage())] + ) + hooks = HooksManager() + ends: List[Dict[str, Any]] = [] + hooks.on(HookName.SessionEnd.value, HookEntry(handler=lambda payload, _ctx: ends.append(payload))) + + result = call_model(client, {"model": "test-model", "input": "hi", "tools": [_echo_tool()], "hooks": hooks}) + await result.get_text() + + assert len(ends) == 1 + assert await result.get_usage() == ends[0]["total_usage"] + + +async def test_counts_usage_less_responses_in_model_calls_and_omits_cost() -> None: + client = QueuedClient([text_response("r1", "hello back")]) + result = call_model(client, {"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( + monkeypatch: pytest.MonkeyPatch, +) -> None: + client = QueuedClient([]) + + async def fail(**_kwargs: Any) -> Any: + raise RuntimeError("api down") + + monkeypatch.setattr(client.responses, "send_async", fail) + result = call_model(client, {"model": "test-model", "input": "hi"}) + + with pytest.raises(RuntimeError, match="api down"): + await result.get_text() + + # Never-raises must not mean silent: the swallowed cause is surfaced. + with pytest.warns(UserWarning, match=r"\[get_usage\] run failed; reporting totals accrued so far: api down"): + usage = await result.get_usage() + assert usage == { + "model_calls": 0, + "input_tokens": 0, + "output_tokens": 0, + "total_tokens": 0, + "cached_tokens": 0, + "reasoning_tokens": 0, + } + + +async def test_failed_run_after_one_call_reports_totals_accrued_so_far() -> None: + # Second request finds no queued response -> the run raises mid-loop. + client = QueuedClient([tool_call_response("r1", "echo", usage=_usage())]) + result = call_model(client, {"model": "test-model", "input": "hi", "tools": [_echo_tool()]}) + + with pytest.warns(UserWarning, match=r"\[get_usage\] run failed"): + usage = await result.get_usage() + + _assert_totals(usage, _ONE_CALL_TOTALS) + with pytest.raises(AssertionError, match="unexpected extra turn"): + await result.get_response() + + +class TestPausedAtAwaitingApproval: + async def test_reports_only_the_model_calls_that_completed_before_the_pause(self) -> None: + executed: List[Any] = [] + state = MemoryStateAccessor() + client = QueuedClient([tool_call_response("r1", "risky", usage=_usage())]) + result = call_model( + client, + {"model": "test-model", "input": "do the risky thing", "tools": [_approval_tool(executed)], "state": state}, + ) + + await result.get_pending_tool_calls() + + assert state.stored is not None + assert state.stored.status == "awaiting_approval" + assert len(client.requests) == 1 + assert executed == [] + _assert_totals(await result.get_usage(), _ONE_CALL_TOTALS) + + async def test_is_idempotent_while_paused_and_drives_no_further_model_requests(self) -> None: + state = MemoryStateAccessor() + # A further scripted response is queued so an accidental dispatch would + # show up as both a request-count bump and inflated totals. + client = QueuedClient( + [ + tool_call_response("r1", "risky", usage=_usage()), + text_response("should-not-be-consumed", "nope", usage=_usage()), + ] + ) + result = call_model( + client, + {"model": "test-model", "input": "do the risky thing", "tools": [_approval_tool([])], "state": state}, + ) + await result.get_pending_tool_calls() + + first = await result.get_usage() + assert first["model_calls"] == 1 + assert await result.get_usage() == first + assert len(client.requests) == 1 + + async def test_scopes_totals_per_model_result_across_an_approval_resume(self) -> None: + executed: List[Any] = [] + state = MemoryStateAccessor() + client = QueuedClient( + [ + tool_call_response("r1", "risky", usage=_usage()), + text_response("r2", "done", usage=_ROUND_TWO_USAGE), + ] + ) + first = call_model( + client, + {"model": "test-model", "input": "do the risky thing", "tools": [_approval_tool(executed)], "state": state}, + ) + await first.get_pending_tool_calls() + assert state.stored is not None + paused_call_id = (state.stored.pending_tool_calls or [])[0].id + + resumed = call_model( + client, + { + "model": "test-model", + "tools": [_approval_tool(executed)], + "state": state, + "approve_tool_calls": [paused_call_id], + }, + ) + await resumed.get_response() + + assert len(executed) == 1 + assert len(client.requests) == 2 + # Per-ModelResult, not per-conversation: a caller summing across + # resumes adds rather than double-counts. + resumed_usage = await resumed.get_usage() + assert resumed_usage["model_calls"] == 1 + assert resumed_usage["total_tokens"] == 300 + assert resumed_usage["cost"] == pytest.approx(0.003) + first_usage = await first.get_usage() + assert first_usage["model_calls"] == 1 + assert first_usage["total_tokens"] == 150 + assert first_usage["cost"] == pytest.approx(0.002) 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..b6d2c2d --- /dev/null +++ b/tests/unit/test_max_output_tokens_truncation.py @@ -0,0 +1,111 @@ +"""Port of upstream tests/unit/max-output-tokens-truncation.test.ts. + +A turn 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 request again on the same exhausted budget. +""" + +from __future__ import annotations + +import json +from typing import Any, Dict, List + +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 + +_TRUNCATED_SHELL_CALL = { + "type": "function_call", + "id": "fc_1", + "callId": "call_1", + "name": "run_shell", + "arguments": '{"commands":', + "status": "incomplete", +} + + +def _truncated_response(output: List[Dict[str, Any]]) -> Dict[str, Any]: + return make_response( + "resp_truncated", + output, + status="incomplete", + incompleteDetails={"reason": "max_output_tokens"}, + usage={"input_tokens": 4529, "output_tokens": 3002, "total_tokens": 7531}, + ) + + +def _truncated_batch_response() -> Dict[str, Any]: + weather_calls = [ + { + "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"]) + ] + return _truncated_response([*weather_calls, {**_TRUNCATED_SHELL_CALL, "id": "fc_shell", "callId": "call_shell"}]) + + +def _recording_tool(name: str, executed: List[Any]) -> Any: + def execute(params: Any, _ctx: Any) -> Dict[str, Any]: + executed.append(params) + return {"ok": True} + + return tool(name=name, input_schema=dict, execute=execute) + + +def test_extracts_no_tool_calls_from_a_truncated_response() -> None: + response = _truncated_response([_TRUNCATED_SHELL_CALL]) + + assert response_has_tool_calls(response) is False + assert extract_tool_calls_from_response(response) == [] + + +async def test_finalizes_on_the_truncated_turn_without_executing_or_requesting_again() -> None: + executed: List[Any] = [] + # One queued response: a second request would fail the fixture loudly. + client = QueuedClient([_truncated_response([_TRUNCATED_SHELL_CALL])]) + + response = await call_model( + client, + { + "model": "test-model", + "input": "Run echo hello.", + "stop_when": step_count_is(3), + "tools": [_recording_tool("run_shell", executed)], + }, + ).get_response() + + assert executed == [] + assert len(client.requests) == 1 + assert response["id"] == "resp_truncated" + assert response["status"] == "incomplete" + + +async def test_does_not_execute_calls_completed_before_the_cutoff_either() -> None: + executed: List[Any] = [] + client = QueuedClient([_truncated_batch_response()]) + + response = await call_model( + client, + { + "model": "test-model", + "input": "Weather in three cities, then run echo hello.", + "stop_when": step_count_is(3), + "tools": [_recording_tool("get_weather", executed), _recording_tool("run_shell", executed)], + }, + ).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_tool_choice_loop.py b/tests/unit/test_next_turn_tool_choice_loop.py new file mode 100644 index 0000000..24086f9 --- /dev/null +++ b/tests/unit/test_next_turn_tool_choice_loop.py @@ -0,0 +1,217 @@ +"""Port of upstream tests/unit/next-turn-tool-choice-loop.test.ts (#114, #153). + +`next_turn_params.tool_choice` driven through the real `call_model` loop and +asserted against the DISPATCHED request: a tool-search tool keeps every tool +declared up front and widens an `allowed_tools` choice as it discovers what the +model needs, leaving `tools` byte-identical so the prompt-cache prefix holds. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional + +from pydantic import BaseModel + +from openrouter_agent import HookEntry, call_model, tool +from tests._fixtures import QueuedClient, text_response, tool_call_response + + +def _allowed(names: List[str]) -> Dict[str, Any]: + return {"type": "allowed_tools", "mode": "auto", "tools": [{"type": "function", "name": n} for n in names]} + + +class SearchInput(BaseModel): + pattern: str + + +_WIDENED = ["tool_search", "get_weather"] + +_get_weather = tool(name="get_weather", input_schema=dict, execute=lambda _p, _c: {"ok": True}) + + +def _client() -> QueuedClient: + return QueuedClient( + [ + tool_call_response("resp_tool", "tool_search", call_id="call_1", arguments='{"pattern":"weather"}'), + text_response("resp_text", "done"), + ] + ) + + +def _recording_widener(computed: List[Any]) -> Any: + def widen(params: Any, _ctx: Any) -> Dict[str, Any]: + computed.append(params) + return _allowed(_WIDENED) + + return widen + + +def _choices(client: QueuedClient) -> List[Any]: + return [request.get("tool_choice") for request in client.requests] + + +async def _run(search_tool: Any, client: QueuedClient, hooks: Optional[Dict[str, Any]] = None) -> List[Any]: + request: Dict[str, Any] = { + "model": "test-model", + "input": "hi", + "tools": [search_tool, _get_weather], + "tool_choice": _allowed(["tool_search"]), + } + if hooks is not None: + request["hooks"] = hooks + await call_model(client, request).get_text() + return _choices(client) + + +class TestNextTurnToolChoiceThroughTheLoop: + async def test_reaches_the_dispatched_followup_request(self) -> None: + client = _client() + search = tool( + name="tool_search", + input_schema=SearchInput, + execute=lambda _p, _c: {"found": _WIDENED}, + next_turn_params={"tool_choice": lambda _params, _ctx: _allowed(_WIDENED)}, + ) + + choices = await _run(search, client) + + assert choices == [_allowed(["tool_search"]), _allowed(_WIDENED)] + + async def test_leaves_the_tools_array_untouched_while_the_choice_widens(self) -> None: + client = _client() + search = tool( + name="tool_search", + input_schema=SearchInput, + execute=lambda _p, _c: {"found": _WIDENED}, + next_turn_params={"tool_choice": lambda _params, _ctx: _allowed(_WIDENED)}, + ) + + await _run(search, client) + + assert len(client.requests) == 2 + tool_names = [[entry["name"] for entry in request["tools"]] for request in client.requests] + assert tool_names[0] == ["tool_search", "get_weather"] + assert tool_names[1] == tool_names[0] + assert client.requests[1]["tools"] == client.requests[0]["tools"] + + async def test_does_not_disturb_tool_choice_when_no_tool_computes_one(self) -> None: + client = _client() + plain = tool(name="tool_search", input_schema=SearchInput, execute=lambda _p, _c: {"ok": True}) + + choices = await _run(plain, client) + + assert choices == [_allowed(["tool_search"]), _allowed(["tool_search"])] + + async def test_context_exposes_the_current_tool_choice(self) -> None: + client = _client() + seen: List[Any] = [] + + def compute(_params: Any, ctx: Dict[str, Any]) -> Dict[str, Any]: + seen.append(ctx.get("tool_choice")) + return _allowed(_WIDENED) + + search = tool( + name="tool_search", + input_schema=SearchInput, + execute=lambda _p, _c: {"found": _WIDENED}, + next_turn_params={"tool_choice": compute}, + ) + + await _run(search, client) + + assert seen == [_allowed(["tool_search"])] + + +class TestNextTurnParamsOnlyForSucceededCalls: + async def test_does_not_widen_when_pre_tool_use_blocks_the_call(self) -> None: + executed: List[Any] = [] + computed: List[Any] = [] + client = _client() + search = tool( + name="tool_search", + input_schema=SearchInput, + execute=lambda p, _c: executed.append(p), + next_turn_params={"tool_choice": _recording_widener(computed)}, + ) + + choices = await _run( + search, + client, + hooks={ + "PreToolUse": [HookEntry(matcher="tool_search", handler=lambda _p, _c: {"block": "blocked by policy"})] + }, + ) + + assert executed == [] + assert computed == [] + assert choices == [_allowed(["tool_search"]), _allowed(["tool_search"])] + + async def test_does_not_widen_when_the_arguments_fail_input_schema(self) -> None: + class NewsOnly(BaseModel): + pattern: int + + executed: List[Any] = [] + computed: List[Any] = [] + client = _client() + search = tool( + name="tool_search", + input_schema=NewsOnly, + execute=lambda p, _c: executed.append(p), + next_turn_params={"tool_choice": _recording_widener(computed)}, + ) + + choices = await _run(search, client) + + assert executed == [] + assert computed == [] + assert choices == [_allowed(["tool_search"]), _allowed(["tool_search"])] + + async def test_does_not_widen_when_execute_raises(self) -> None: + computed: List[Any] = [] + + def fail(_p: Any, _c: Any) -> Any: + raise RuntimeError("search backend unavailable") + + client = _client() + search = tool( + name="tool_search", + input_schema=SearchInput, + execute=fail, + next_turn_params={"tool_choice": _recording_widener(computed)}, + ) + + choices = await _run(search, client) + + assert computed == [] + assert choices == [_allowed(["tool_search"]), _allowed(["tool_search"])] + + async def test_passes_the_pre_tool_use_mutated_input_that_the_tool_ran_on(self) -> None: + ran_on: List[str] = [] + client = _client() + + def execute(params: SearchInput, _ctx: Any) -> Dict[str, Any]: + ran_on.append(params.pattern) + return {"found": [params.pattern]} + + search = tool( + name="tool_search", + input_schema=SearchInput, + execute=execute, + next_turn_params={"tool_choice": lambda params, _c: _allowed(["tool_search", params["pattern"]])}, + ) + + choices = await _run( + search, + client, + hooks={ + "PreToolUse": [ + HookEntry( + matcher="tool_search", + handler=lambda _p, _c: {"mutated_input": {"pattern": "get_weather"}}, + ) + ] + }, + ) + + assert ran_on == ["get_weather"] + assert choices == [_allowed(["tool_search"]), _allowed(["tool_search", "get_weather"])] diff --git a/tests/unit/test_server_tool.py b/tests/unit/test_server_tool.py new file mode 100644 index 0000000..4964ca1 --- /dev/null +++ b/tests/unit/test_server_tool.py @@ -0,0 +1,94 @@ +"""Port of upstream tests/unit/server-tool.test.ts -- serialization cases. + +Not ported here: the stable tool-set `id` on `server_tool()` (`server:`, +override, empty-id rejection) belongs to upstream's tool-set feature (#31/#102), +which this port does not have yet; the agent-tool / unified-run-tool `strict` +cases depend on `tool.agent()` / unified `run` tools, likewise not ported. The +`@ts-expect-error` cases are type-level only. +""" + +from __future__ import annotations + +from typing import Any, Dict + +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 openrouter_agent.tool_types import is_client_tool, is_server_tool +from tests._fixtures import QueuedClient, text_response + + +class EchoInput(BaseModel): + msg: str + + +def _echo(**extra: Any) -> Dict[str, Any]: + return tool(name="echo", input_schema=EchoInput, execute=lambda params, _ctx: params.msg, **extra) + + +def test_server_tool_is_branded_and_carries_the_config_through() -> None: + t = server_tool({"type": "web_search_2025_08_26", "engine": "exa", "max_results": 10}) + + assert t["_brand"] == "server-tool" + assert t["config"]["type"] == "web_search_2025_08_26" + assert is_server_tool(t) is True + assert is_client_tool(t) is False + + +def test_passes_server_tool_configs_through_verbatim() -> None: + api = convert_tools_to_api_format( + [ + server_tool({"type": "openrouter:datetime"}), + server_tool({"type": "web_search_2025_08_26", "engine": "native"}), + ] + ) + + assert api == [{"type": "openrouter:datetime"}, {"type": "web_search_2025_08_26", "engine": "native"}] + + +def test_shapes_client_tools_into_the_function_call_api_format() -> None: + api = convert_tools_to_api_format([_echo()]) + + assert len(api) == 1 + assert api[0]["type"] == "function" + assert api[0]["name"] == "echo" + assert api[0]["parameters"]["properties"]["msg"]["type"] == "string" + + +def test_serializes_strict_true_from_the_tool_definition() -> None: + api = convert_tools_to_api_format([_echo(strict=True)]) + + 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([_echo(strict=False)]) + + assert api[0]["strict"] is False + + +def test_defaults_strict_to_null_when_not_declared() -> None: + api = convert_tools_to_api_format([_echo()]) + + assert "strict" in api[0] + assert api[0]["strict"] is None + + +def test_mixes_client_and_server_tools_in_one_array_in_order() -> None: + api = convert_tools_to_api_format([_echo(), server_tool({"type": "image_generation", "size": "1024x1024"})]) + + assert [entry["type"] for entry in api] == ["function", "image_generation"] + assert api[0]["name"] == "echo" + assert api[1]["size"] == "1024x1024" + + +async def test_strict_reaches_the_dispatched_request() -> None: + client = QueuedClient([text_response("r1", "ok")]) + + await call_model(client, {"model": "test-model", "input": "hi", "tools": [_echo(strict=True)]}).get_text() + + assert len(client.requests) == 1 + assert [entry["strict"] for entry in client.requests[0]["tools"]] == [True] 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..8d04273 --- /dev/null +++ b/tests/unit/test_stop_when_before_approval.py @@ -0,0 +1,118 @@ +"""Port of upstream tests/unit/stop-when-before-approval.test.ts (844845f). + +With `allow_final_response=False`, a `stop_when` already met on the first +response means no tool from that response runs. Pausing for an approval-gated +call must therefore not execute its auto-approved sibling; the sibling is saved +as a skipped result so the resume request still has a matching output. +""" + +from __future__ import annotations + +from typing import Any, List + +from pydantic import BaseModel + +from openrouter_agent import call_model, tool +from tests._fixtures import MemoryStateAccessor, QueuedClient, function_call_item, make_response + + +class VInput(BaseModel): + v: str + + +class OkOutput(BaseModel): + ok: bool + + +def _tools(auto_calls: List[Any], gated_calls: List[Any]) -> List[Any]: + def auto_execute(params: Any, _ctx: Any) -> Any: + auto_calls.append(params) + return {"ok": True} + + def gated_execute(params: Any, _ctx: Any) -> Any: + gated_calls.append(params) + return {"ok": True} + + return [ + tool(name="auto", input_schema=VInput, output_schema=OkOutput, execute=auto_execute), + tool( + name="gated", + input_schema=VInput, + output_schema=OkOutput, + execute=gated_execute, + require_approval=True, + ), + ] + + +def _client() -> QueuedClient: + return QueuedClient( + [ + make_response( + "resp_1", + [ + function_call_item("call_auto", "auto", '{"v":"a"}'), + function_call_item("call_gated", "gated", '{"v":"g"}'), + ], + ) + ] + ) + + +async def test_does_not_run_an_auto_sibling_of_an_approval_gated_call_when_stop_when_is_met() -> None: + auto_calls: List[Any] = [] + gated_calls: List[Any] = [] + state = MemoryStateAccessor() + client = _client() + + result = call_model( + client, + { + "model": "test-model", + "input": "go", + "tools": _tools(auto_calls, gated_calls), + "state": state, + "stop_when": lambda _options: 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 [call.id for call 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_sibling_when_stop_when_is_not_met() -> None: + auto_calls: List[Any] = [] + state = MemoryStateAccessor() + client = _client() + + result = call_model( + client, + { + "model": "test-model", + "input": "go", + "tools": _tools(auto_calls, []), + "state": state, + "stop_when": lambda _options: False, + "allow_final_response": False, + }, + ) + await result.get_response() + + assert len(auto_calls) == 1 + saved = state.stored + assert saved is not None + assert saved.status == "awaiting_approval" + assert [call.id for call 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_tool_choice_relaxation.py b/tests/unit/test_tool_choice_relaxation.py new file mode 100644 index 0000000..92a9809 --- /dev/null +++ b/tests/unit/test_tool_choice_relaxation.py @@ -0,0 +1,324 @@ +"""Port of upstream tests/unit/tool-choice-relaxation.test.ts (DEV-785, #100). + +A forced tool choice (`"required"`, a specific tool, or `allowed_tools` with +`mode: "required"`) is one-shot: once a response dispatched under it called a +tool, follow-up turns get the relaxed form (`"auto"`, or `allowed_tools` with +`mode: "auto"`) so the model can answer in text instead of being looped +through tool calls until the step budget runs out. A tool-computed +`tool_choice` from `next_turn_params` becomes the new configured choice and +re-arms (#114). +""" + +from __future__ import annotations + +import dataclasses +from typing import Any, Dict, List + +import pytest +from openrouter.components import OpenAIResponsesToolChoiceFunction + +from openrouter_agent import ( + call_model, + create_initial_state, + deserialize_conversation_state, + serialize_conversation_state, + step_count_is, + tool, +) +from tests._fixtures import MemoryStateAccessor, QueuedClient, text_response, tool_call_response + + +def _weather_tool(executed: List[Dict[str, Any]]) -> Any: + def execute(params: Dict[str, Any], _ctx: Any) -> Dict[str, Any]: + executed.append(params) + return {"temperature": 22} + + return tool(name="get_weather", input_schema=dict, execute=execute) + + +def _weather_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"}') + + +async def test_relaxes_required_to_auto_after_a_successful_tool_round() -> None: + executed: List[Dict[str, Any]] = [] + client = QueuedClient([_weather_call("resp_1", "call_1"), text_response("resp_text", "It is 22 degrees.")]) + + text = await call_model( + client, + { + "model": "test-model", + "input": "What is the weather in Tokyo?", + "tools": [_weather_tool(executed)], + "tool_choice": "required", + "stop_when": step_count_is(5), + }, + ).get_text() + + assert text == "It is 22 degrees." + assert len(client.requests) == 2 + assert executed == [{"location": "Tokyo"}] + # Initial turn: the caller's forced choice reaches the wire intact. + assert client.requests[0]["tool_choice"] == "required" + # Follow-up: relaxed to "auto" with tools still present, so the model may + # call another tool OR answer in text. + assert client.requests[1]["tool_choice"] == "auto" + assert client.requests[1]["tools"] == client.requests[0]["tools"] + + +@pytest.mark.parametrize( + ("key", "forced_choice"), + [ + ("tool_choice", {"type": "function", "name": "get_weather"}), + ("toolChoice", {"type": "function", "name": "get_weather"}), + ("tool_choice", {"type": "function", "function": {"name": "get_weather"}}), + ("tool_choice", OpenAIResponsesToolChoiceFunction(type="function", name="get_weather")), + ("tool_choice", {"type": "web_search_preview"}), + ], +) +async def test_relaxes_a_forced_specific_tool_choice_after_a_successful_tool_round( + key: str, forced_choice: Any +) -> None: + executed: List[Dict[str, Any]] = [] + client = QueuedClient([_weather_call("resp_1", "call_1"), text_response("resp_text", "Done.")]) + + text = await call_model( + client, + { + "model": "test-model", + "input": "What is the weather in Tokyo?", + "tools": [_weather_tool(executed)], + key: forced_choice, + "stop_when": step_count_is(5), + }, + ).get_text() + + assert text == "Done." + assert len(executed) == 1 + assert len(client.requests) == 2 + assert client.requests[0]["tool_choice"] == forced_choice + assert client.requests[1]["tool_choice"] == "auto" + + +async def test_relaxes_allowed_tools_mode_required_to_auto_keeping_the_tool_set() -> None: + allowed_tools = [{"type": "function", "name": "get_weather"}] + client = QueuedClient([_weather_call("resp_1", "call_1"), text_response("resp_text", "Done.")]) + + text = await call_model( + client, + { + "model": "test-model", + "input": "What is the weather in Tokyo?", + "tools": [_weather_tool([])], + "tool_choice": {"type": "allowed_tools", "mode": "required", "tools": allowed_tools}, + "stop_when": step_count_is(5), + }, + ).get_text() + + assert text == "Done." + assert client.requests[1]["tool_choice"] == {"type": "allowed_tools", "mode": "auto", "tools": allowed_tools} + + +@pytest.mark.parametrize( + "preserved_choice", + [ + "auto", + {"type": "allowed_tools", "mode": "auto", "tools": [{"type": "function", "name": "get_weather"}]}, + ], +) +async def test_keeps_unforced_tool_choice_unchanged_on_followup_turns(preserved_choice: Any) -> None: + client = QueuedClient([_weather_call("resp_1", "call_1"), text_response("resp_text", "Done.")]) + + await call_model( + client, + { + "model": "test-model", + "input": "What is the weather in Tokyo?", + "tools": [_weather_tool([])], + "tool_choice": preserved_choice, + "stop_when": step_count_is(5), + }, + ).get_text() + + assert len(client.requests) == 2 + assert client.requests[0]["tool_choice"] == preserved_choice + assert client.requests[1]["tool_choice"] == preserved_choice + + +@pytest.mark.xfail( + strict=True, + reason=( + "Pre-existing parity gap (not part of the tool-choice change): upstream evaluates stop_when " + "against executed tool rounds (model-result.ts shouldStopExecution over allToolExecutionRounds), " + "so step_count_is(1) allows one tool round; this port counts every response in self._steps, " + "so it stops one round earlier and the second request is already the forced final turn." + ), +) +async def test_still_forces_the_final_no_tools_turn_when_the_budget_is_exhausted() -> None: + # The relaxed "auto" follow-up returns another tool call and step_count_is(1) + # halts the loop there -- the run must still end via the forced final turn. + client = QueuedClient( + [ + _weather_call("resp_1", "call_1"), + _weather_call("resp_2", "call_2"), + text_response("resp_text", "Final summary."), + ] + ) + + text = await call_model( + client, + { + "model": "test-model", + "input": "What is the weather in Tokyo?", + "tools": [_weather_tool([])], + "tool_choice": "required", + "stop_when": step_count_is(1), + "allow_final_response": True, + }, + ).get_text() + + assert text == "Final summary." + assert len(client.requests) == 3 + assert client.requests[1]["tool_choice"] == "auto" + assert client.requests[2]["tool_choice"] == "none" + + +async def test_keeps_an_unchanged_consumed_choice_relaxed_across_multiple_followups() -> None: + client = QueuedClient( + [ + _weather_call("resp_1", "call_1"), + _weather_call("resp_2", "call_2"), + text_response("resp_text", "Final summary."), + ] + ) + + text = await call_model( + client, + { + "model": "test-model", + "input": "What is the weather in Tokyo?", + "tools": [_weather_tool([])], + "tool_choice": "required", + "stop_when": step_count_is(5), + }, + ).get_text() + + assert text == "Final summary." + assert [request["tool_choice"] for request in client.requests] == ["required", "auto", "auto"] + + +async def test_next_turn_params_tool_choice_rearms_a_different_forced_value() -> None: + """A tool-computed forced choice is the new configured policy: it applies to + the next turn, then is itself consumed and relaxed (upstream #114 + #100).""" + executed: List[str] = [] + step_two_choice = {"type": "function", "name": "step_two"} + + def make(name: str, **extra: Any) -> Any: + def execute(_params: Dict[str, Any], _ctx: Any) -> Dict[str, Any]: + executed.append(name) + return {"ran": name} + + return tool(name=name, input_schema=dict, execute=execute, **extra) + + client = QueuedClient( + [ + tool_call_response("r1", "step_one", call_id="call_1"), + tool_call_response("r2", "step_two", call_id="call_2"), + text_response("r3", "all done"), + ] + ) + + result = call_model( + client, + { + "model": "test/model", + "input": "run two steps", + "tools": [ + make("step_one", next_turn_params={"tool_choice": lambda _args, _ctx: step_two_choice}), + make("step_two"), + ], + "toolChoice": {"type": "function", "name": "step_one"}, + }, + ) + + assert await result.get_text() == "all done" + assert executed == ["step_one", "step_two"] + assert [request["tool_choice"] for request in client.requests] == [ + {"type": "function", "name": "step_one"}, + step_two_choice, + "auto", + ] + + +async def test_persists_satisfaction_across_approval_resume_and_resets_after_completion() -> None: + executed: List[Dict[str, Any]] = [] + + def execute(params: Dict[str, Any], _ctx: Any) -> Dict[str, Any]: + executed.append(params) + return {"temperature": 22} + + approval_weather = tool(name="get_weather", input_schema=dict, execute=execute, require_approval=True) + state = MemoryStateAccessor() + client = QueuedClient( + [ + _weather_call("resp_1", "call_1"), + text_response("resp_text", "It is 22 degrees."), + _weather_call("resp_2", "call_2"), + ] + ) + base = {"model": "test-model", "tools": [approval_weather], "tool_choice": "required", "state": state} + + await call_model(client, {**base, "input": "What is the weather in Tokyo?"}).get_response() + + assert client.requests[0]["tool_choice"] == "required" + assert state.stored is not None + assert state.stored.status == "awaiting_approval" + # Same canonical form as upstream's RFC 8785 key for a string choice. + assert state.stored.consumed_forced_tool_choice_key == '"required"' + + resumed_text = await call_model(client, {**base, "input": [], "approve_tool_calls": ["call_1"]}).get_text() + + assert resumed_text == "It is 22 degrees." + assert executed == [{"location": "Tokyo"}] + assert client.requests[1]["tool_choice"] == "auto" + assert state.stored.status == "complete" + assert state.stored.consumed_forced_tool_choice_key is None + + # A new conversational turn is a new logical run: it may force again. + await call_model(client, {**base, "input": "Start a new weather request."}).get_response() + + assert len(client.requests) == 3 + assert client.requests[2]["tool_choice"] == "required" + + +async def test_relaxes_the_first_model_request_after_a_manual_client_tool_resume() -> None: + manual_weather = tool(name="get_weather", input_schema=dict, execute=False) + state = MemoryStateAccessor() + client = QueuedClient([_weather_call("resp_1", "call_1"), text_response("resp_text", "It is 22 degrees.")]) + base = {"model": "test-model", "tools": [manual_weather], "tool_choice": "required", "state": state} + + await call_model(client, {**base, "input": "What is the weather in Tokyo?"}).get_response() + + assert state.stored is not None + assert state.stored.status == "awaiting_client_tools" + assert state.stored.consumed_forced_tool_choice_key == '"required"' + + resumed_text = await call_model( + client, + { + **base, + "input": [{"type": "function_call_output", "callId": "call_1", "output": '{"temperature":22}'}], + }, + ).get_text() + + assert resumed_text == "It is 22 degrees." + assert len(client.requests) == 2 + assert client.requests[1]["tool_choice"] == "auto" + + +def test_consumed_key_round_trips_through_serialization() -> None: + state = dataclasses.replace(create_initial_state(), consumed_forced_tool_choice_key='"required"') + + restored = deserialize_conversation_state(serialize_conversation_state(state)) + + assert restored.consumed_forced_tool_choice_key == '"required"' diff --git a/upstreamer-changelog.md b/upstreamer-changelog.md index da07f6e..183c3f1 100644 --- a/upstreamer-changelog.md +++ b/upstreamer-changelog.md @@ -1,5 +1,23 @@ # openrouter-agent-sdk Changelog +## Unreleased: partial sync toward `@openrouter/agent` 1.x + +This brings in part of the upstream 0.9 to 1.3 work. The package is still a 0.8.x port; the larger 1.x features (unified/async tools, doom-loop detection, tool sets, cancellation and timeouts, MCP) are not ported yet. + +- **New `ModelResult.get_usage()`.** Returns token and cost totals summed over every model call in a run: the initial request, each tool round, the final-response turn, the empty-final retry, and approval resumes. The fields are `model_calls`, `input_tokens`, `output_tokens`, `total_tokens`, `cached_tokens` and `reasoning_tokens`, plus `cost` when the server reports it. It works without hooks and matches `SessionEnd.total_usage`. It never raises for a failed or cancelled run; it warns and returns what was accrued. +- **New `strict=` option on `tool(...)`.** Forwards provider strict-schema adherence onto the wire tool definition. Tools that don't set it now send `strict: null`, which leaves the provider default. +- **Behavior change: forced `tool_choice` is now relaxed instead of dropped.** This applies to `"required"`, a specific tool, and `allowed_tools` with `mode: "required"`. Once a response made under the forced choice calls a tool, follow-up turns send `"auto"`, or the same `allowed_tools` set with `mode: "auto"`. + - Previously a specific-tool choice was removed from follow-up requests and `"required"` was kept on every turn. `"required"` could loop the model through tool calls until the step budget ran out. + - The relaxed state survives approval, HITL and client-tool pauses through a new optional `ConversationState.consumed_forced_tool_choice_key` field, which round-trips through `serialize_conversation_state`. It resets when the conversation completes, so a new turn may force again. +- **`next_turn_params` can now set `tool_choice`.** A tool-computed `tool_choice` becomes the configured choice for the rest of the run, for example to widen an `allowed_tools` set without changing `tools` and losing the prompt-cache prefix. The next-turn context now includes the current `tool_choice`. +- **Fix: `from_chat_messages` now emits a `function_call` item for each assistant `tool_calls` entry.** Arguments are forwarded as-is, and `tool_calls` and `toolCalls` are both accepted. Before this, a replayed tool-calling chat history lost its calls and left the tool outputs orphaned. +- **Fix: approval pause with a met `stop_when` no longer runs sibling tools.** When `allow_final_response=False` and a `stop_when` condition is already met on the first response, a call that needs approval pauses as `awaiting_approval` without running its auto-approved siblings. Those siblings are recorded as skipped (`"Tool execution skipped: stop condition met"`) so the resume request stays well-formed. +- **`extract_tool_calls_from_response` only returns calls from `completed` responses.** It returns nothing for any other status, for example a response cut off at `max_output_tokens`. A new `response_has_tool_calls` helper follows the same rule. +- **Clearer final-response errors.** "Invalid final response" errors now name the actual defect: which required fields are missing, an empty output array (with the response id), or a non-array output type. The existing message prefixes are unchanged. +- **Compatibility notes:** + - On an approval-resumed run, `get_usage()` drives the run to completion like every other getter. Upstream's version reports without advancing further tool rounds. + - Known gap: `stop_when` conditions are evaluated against every model response rather than against executed tool rounds, so `step_count_is(n)` stops one round earlier than upstream. + ## 0.8.3 — tool execution, schema, and lifecycle-hook hardening Downstream-only fixes on top of the 0.8.0 port; no new upstream work.