Repository navigation
feat(discovery): add bounded OpenRouter free canary #985
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
seonghobae
wants to merge
17
commits into
main
Choose a base branch
from
feat/openrouter-free-canary
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 4 commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
5aab180
feat(discovery): add bounded OpenRouter free canary
seonghobae f20d3d9
fix(canary): enforce free evidence lifecycle
seonghobae aa9f172
fix(canary): reconcile routable free candidates
seonghobae d60367f
fix(canary): reject special evidence paths
seonghobae 65fe3b4
fix(canary): harden retention and CLI boundaries
seonghobae 499c657
fix(canary): persist and validate live attempts
seonghobae 0ec2ade
fix(canary): serialize evidence lifecycle
seonghobae 55ccf97
fix(canary): support new evidence parents
seonghobae c4b48d0
fix(canary): surface inaccessible evidence parents
seonghobae 899e6f8
Merge remote-tracking branch 'origin/main' into fix/985-continue
claude b6a2cb3
fix(canary): remove duplicate import, correct bootstrap credential
claude 2522330
Merge branch 'main' into feat/openrouter-free-canary
opencode-agent[bot] 9804763
fix(tests): eliminate CI-only embedding batch race by waiting for ter…
claude d4c1bae
Merge branch 'main' into feat/openrouter-free-canary
claude 15e4af9
Merge branch 'main' into feat/openrouter-free-canary
opencode-agent[bot] 4488f4a
Merge remote-tracking branch 'origin/main' into codex/pr985-repair
seonghobae e527eaf
docs(discovery): isolate OpenRouter canary delta
seonghobae File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,187 @@ | ||
| """Bounded, opt-in evidence for one currently free OpenRouter model.""" | ||
|
seonghobae marked this conversation as resolved.
|
||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from dataclasses import asdict, dataclass | ||
| import json | ||
| import os | ||
| from pathlib import Path | ||
| import stat | ||
| import tempfile | ||
| import time | ||
| from typing import Any, Callable | ||
|
|
||
| from .credentials import get_credential | ||
| from .model_discovery import ( | ||
| DiscoveredModel, | ||
| PROVIDER_MODEL_SOURCES, | ||
| _deduplicate_discovered_models, | ||
| _requires_non_text_input, | ||
| agent_from_discovered, | ||
| discover_provider_models, | ||
| is_discovered_chat_candidate, | ||
| ) | ||
| from .orchestrator import ModelClient | ||
|
|
||
|
|
||
| class OpenRouterCanaryError(RuntimeError): | ||
| """Raised before transport when the canary contract is incomplete.""" | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class OpenRouterCanaryLimits: | ||
| """Explicit operator caps for the optional live request.""" | ||
|
|
||
| max_requests: int | ||
| max_output_tokens: int | ||
| timeout_seconds: int | ||
| retention_days: int | ||
|
|
||
| def validate(self) -> None: | ||
| """Reject absent, boolean, or non-positive cap values.""" | ||
| for name, value in asdict(self).items(): | ||
| if type(value) is not int or value < 1: | ||
| raise OpenRouterCanaryError(f"{name} must be a positive integer") | ||
|
|
||
|
|
||
| def _eligible(models: list[DiscoveredModel]) -> list[DiscoveredModel]: | ||
| """Return price-complete, text-chat OpenRouter rows in stable order.""" | ||
| return sorted( | ||
| ( | ||
| model | ||
| for model in models | ||
| if model.provider_name == "openrouter" | ||
| and model.prompt_price_per_1k == 0.0 | ||
| and model.completion_price_per_1k == 0.0 | ||
| and model.is_free is True | ||
| and not model.unit_prices | ||
|
seonghobae marked this conversation as resolved.
seonghobae marked this conversation as resolved.
|
||
| and model.currency_code == "USD" | ||
| and not model.evidence_only | ||
| and model.spend_admitted | ||
| and is_discovered_chat_candidate(model) | ||
|
seonghobae marked this conversation as resolved.
|
||
| and not _requires_non_text_input(model) | ||
|
seonghobae marked this conversation as resolved.
|
||
| ), | ||
| key=lambda model: model.model_id, | ||
| ) | ||
|
|
||
|
|
||
| def _write_evidence(path: Path, evidence: dict[str, Any]) -> None: | ||
| """Atomically publish one secret- and prompt-free JSON evidence document.""" | ||
| path.parent.mkdir(parents=True, exist_ok=True) | ||
| descriptor, temporary_name = tempfile.mkstemp( | ||
| prefix=f".{path.name}.", dir=path.parent | ||
| ) | ||
| try: | ||
| with os.fdopen(descriptor, "w", encoding="utf-8") as stream: | ||
| json.dump(evidence, stream, sort_keys=True) | ||
| stream.write("\n") | ||
| os.replace(temporary_name, path) | ||
| except BaseException: | ||
| try: | ||
| os.unlink(temporary_name) | ||
| except FileNotFoundError: | ||
| pass | ||
| raise | ||
|
|
||
|
|
||
| def _prepare_evidence_path(path: Path, current_time: int) -> None: | ||
| """Remove expired prior evidence and prove a secure atomic write is possible.""" | ||
| try: | ||
| mode = path.lstat().st_mode | ||
| except FileNotFoundError: | ||
| mode = None | ||
|
devin-ai-integration[bot] marked this conversation as resolved.
|
||
| if mode is not None and not stat.S_ISREG(mode): | ||
| raise OpenRouterCanaryError("evidence output must be a regular file path") | ||
| try: | ||
| prior = json.loads(path.read_text(encoding="utf-8")) | ||
|
seonghobae marked this conversation as resolved.
Outdated
|
||
| except (FileNotFoundError, OSError, UnicodeError, json.JSONDecodeError): | ||
| prior = None | ||
| if ( | ||
| isinstance(prior, dict) | ||
| and prior.get("provider") == "openrouter" | ||
| and type(prior.get("expires_at")) is int | ||
| and prior["expires_at"] <= current_time | ||
| ): | ||
| path.unlink(missing_ok=True) | ||
| path.parent.mkdir(parents=True, exist_ok=True) | ||
| descriptor, temporary_name = tempfile.mkstemp( | ||
| prefix=f".{path.name}.preflight.", dir=path.parent | ||
| ) | ||
| os.close(descriptor) | ||
| os.unlink(temporary_name) | ||
|
|
||
|
|
||
| def run_openrouter_free_canary( | ||
| *, | ||
| live: bool, | ||
| limits: OpenRouterCanaryLimits | None = None, | ||
| evidence_output: Path | None = None, | ||
| discover: Callable[..., list[DiscoveredModel]] = discover_provider_models, | ||
| client_factory: Callable[..., ModelClient] = ModelClient, | ||
| now: Callable[[], float] = time.time, | ||
| ) -> dict[str, Any]: | ||
| """Discover a current free candidate and optionally issue one bounded request.""" | ||
| source = next( | ||
| item for item in PROVIDER_MODEL_SOURCES if item.provider_name == "openrouter" | ||
| ) | ||
| if not get_credential(source.credential_name): | ||
| raise OpenRouterCanaryError( | ||
| "OPENROUTER_API_KEY is unavailable in the KV registry" | ||
| ) | ||
| if live: | ||
| if limits is None or evidence_output is None: | ||
| raise OpenRouterCanaryError( | ||
| "live mode requires all caps and an evidence output path" | ||
| ) | ||
| limits.validate() | ||
| discovered_at = int(now()) | ||
|
seonghobae marked this conversation as resolved.
Outdated
|
||
| if live: | ||
| assert evidence_output is not None | ||
| try: | ||
| _prepare_evidence_path(evidence_output, discovered_at) | ||
| except OSError as exc: | ||
| raise OpenRouterCanaryError("evidence output is not writable") from exc | ||
| candidates = _eligible( | ||
| _deduplicate_discovered_models( | ||
| discover(source, timeout=limits.timeout_seconds if limits else 10) | ||
| ) | ||
|
seonghobae marked this conversation as resolved.
|
||
| ) | ||
|
seonghobae marked this conversation as resolved.
|
||
| if not candidates: | ||
| raise OpenRouterCanaryError( | ||
| "current discovery has no unambiguous zero-price chat candidate" | ||
| ) | ||
| selected = candidates[0] | ||
| evidence: dict[str, Any] = { | ||
| "schema_version": 1, | ||
| "mode": "live" if live else "dry_run", | ||
| "provider": "openrouter", | ||
| "model_id": selected.model_id, | ||
| "discovered_at": discovered_at, | ||
| "price_evidence": { | ||
| "prompt_price_per_1k": 0.0, | ||
| "completion_price_per_1k": 0.0, | ||
| "currency_code": "USD", | ||
| }, | ||
| "request_count": 0, | ||
| } | ||
| if live: | ||
| assert limits is not None and evidence_output is not None | ||
| client = client_factory( | ||
| timeout=limits.timeout_seconds, | ||
| max_output_tokens=limits.max_output_tokens, | ||
| max_retries=0, | ||
| temperature=0.0, | ||
| ) | ||
| client.chat( | ||
| agent_from_discovered(selected), [{"role": "user", "content": "Reply OK."}] | ||
| ) | ||
|
seonghobae marked this conversation as resolved.
Outdated
seonghobae marked this conversation as resolved.
Outdated
github-actions[bot] marked this conversation as resolved.
Outdated
|
||
| evidence.update( | ||
| { | ||
| "request_count": 1, | ||
| "limits": asdict(limits), | ||
| "expires_at": discovered_at + limits.retention_days * 86400, | ||
|
seonghobae marked this conversation as resolved.
seonghobae marked this conversation as resolved.
|
||
| "outcome": "completed", | ||
| } | ||
| ) | ||
| _write_evidence(evidence_output, evidence) | ||
| return evidence | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.