The platform for continuously improving AI agents.
Fix SDK correctness, credential handling, and tracing privacy (#309)
Tyler-Edwards79e30098cb0f
diff --git a/frontend/public/setup.md b/frontend/public/setup.mdindex 092e3376..c0de66d3 100644--- a/frontend/public/setup.md+++ b/frontend/public/setup.md@@ -81,7 +81,7 @@ Overmind has the following features- Python: use the Overmind SDK. `get_instrumentation_plan`, apply each `required_decorator` verbatim.- Any other language with OpenTelemetry already enabled: no SDK and no plan. Add Overmind as one more OTLP/HTTP protobuf exporter beside the existing ones, never replacing them:- - Endpoint `https://api.overmindlab.ai/api/v1/traces`, header `x-api-key: <project key>`.+ - Endpoint `<selected-api-base-url>/api/v1/traces`, header `x-api-key: <project key>`. Use the API reported by the connected catalogue and bound to that project key. The hosted API is `https://api.overmindlab.ai`; other deployments use their configured API URL.- Resource attribute `overmind.capability.id` (the only key that binds spans to a capability).- Span attributes: `overmind.span.type=entry_point` and `overmind.unit_kind=run` on the root span of a run, `overmind.delivery=true` on the span carrying the result, `conversation.id` on every span of a multi-turn exchange.- No OpenTelemetry in a non-Python codebase: report telemetry as not set up. Do not introduce OpenTelemetry for the user.diff --git a/overmind/CHANGELOG.md b/overmind/CHANGELOG.mdindex 0ebe6fc0..ec7ced54 100644--- a/overmind/CHANGELOG.md+++ b/overmind/CHANGELOG.md@@ -8,6 +8,17 @@ entries here cover the SDK surface.### Fixed+- Bind saved SDK credentials to their API endpoint. `init()` disables tracing+ with a warning when they meet another endpoint, and raises in strict mode.+- Preserve tool calls in SDK chat responses. `CompletionMessage.content` is+ `None` when the model returns only tool calls.+- Restore SDK compatibility with Python 3.10.+- Exclude freeform CLI arguments from analytics.+- Redact secret fields in traced dataclass values.+- Restore the outer conversation after an SDK run.+- Scope turn reuse to capability identity.+- Preserve captured tool call identity and arguments.+- Preserve constructor aliases in OpenRouter rewrites.- `convert_json_to_toml` keeps the scan's `modes` and `llm_utilities` (in thecapability card, utilities under their `called_by` parent) and its`decision_logic` and `policy_markdown`; `overmind sync` sends and round-tripsdiff --git a/overmind/overmind/__init__.py b/overmind/overmind/__init__.pyindex 5332daaa..453dd8c0 100644--- a/overmind/overmind/__init__.py+++ b/overmind/overmind/__init__.py@@ -10,7 +10,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Any-__version__ = "0.1.119"+__version__ = "0.1.120"from .client import Client, ModelDeleted, OvermindInferenceErrordiff --git a/overmind/overmind/analytics.py b/overmind/overmind/analytics.pyindex 1ef3a399..098e80b5 100644--- a/overmind/overmind/analytics.py+++ b/overmind/overmind/analytics.py@@ -20,7 +20,6 @@ import jsonimport loggingimport osimport platform-import reimport sysimport threadingimport uuid@@ -44,15 +43,6 @@ _TIMEOUT_S = 2.0_ANALYTICS_ID_PATH = Path.home() / ".overmind" / "analytics_id"_IDENTITY_CACHE_PATH = Path.home() / ".overmind" / "analytics_identity"-_SECRET_FLAGS = frozenset({- "--api-key",- "--token",- "--password",- "--secret",- "--authorization",- "-k", # common short form for keys in some CLIs-})-# Caller-supplied property names never forwarded to PostHog._BLOCKED_PROP_KEYS = frozenset({"api_key",@@ -163,19 +153,12 @@ def _resolve_api_credentials(api_key: str | None = None,base_url: str | None = None,) -> tuple[str, str] | None:- """Return ``(api_key, base_url)`` from args / env / overmind.toml, or None."""- key = (api_key or "").strip()- url = (base_url or "").strip()- if not key or not url:- # Lazy: overmind.sync pulls the Typer CLI stack into library imports.- from overmind.sync import DEFAULT_BASE_URL, resolve_api_key, resolve_api_url-+ try:cfg = config.load(config.DEFAULT_PATH) if config.DEFAULT_PATH.exists() else None- key = key or (resolve_api_key("", cfg) or "").strip()- url = url or resolve_api_url("", cfg) or DEFAULT_BASE_URL- if not key or not url:+ key, url = config.resolve_api_credentials(api_key or "", base_url or "", cfg)+ except (OSError, ValueError):return None- return key, url.rstrip("/")+ return (key, url) if key else Nonedef _fetch_me(api_key: str, base_url: str) -> dict[str, Any] | None:@@ -283,115 +266,22 @@ def _common_properties() -> dict[str, Any]:# --- CLI argv parsing and redaction ----def _looks_like_secret(value: str) -> bool:- if len(value) < 16:- return False- if value.lower().startswith(("om_", "sk-", "phc_", "pk_", "rk_")):- return True- # Long opaque tokens.- return bool(re.fullmatch(r"[A-Za-z0-9_\-]{32,}", value))---def _argv_parts(argv: list[str] | None = None) -> list[str]:- """Normalise argv so installs via ``python -m`` / console script look alike."""- raw = list(argv if argv is not None else sys.argv)- if not raw:- return []- if (- raw[0].endswith(".py")- or "python" in Path(raw[0]).name.lower()- or Path(raw[0]).name in {"overmind", "overmind.exe"}- ):- return ["overmind", *raw[1:]]- return [Path(raw[0]).name, *raw[1:]]---def _redact_parts(parts: list[str]) -> list[str]:- out: list[str] = []- redact_next = False- for part in parts:- if redact_next:- out.append("[redacted]")- redact_next = False- continue- flag = part.lower().split("=", 1)[0]- if flag in _SECRET_FLAGS:- if "=" in part:- out.append(f"{part.split('=', 1)[0]}=[redacted]")- else:- out.append(part)- redact_next = True- continue- if _looks_like_secret(part):- out.append("[redacted]")- continue- out.append(part)- return out---def _redact_argv(argv: list[str] | None = None) -> str:- """Return the invoked CLI line with secret flag values redacted."""- return " ".join(_redact_parts(_argv_parts(argv)))---def _looks_like_path(token: str) -> bool:- if "/" in token or "\\" in token:- return True- # Positional file-like args (keep subcommands like ``upload``).- return bool(re.search(r"\.[A-Za-z0-9]{1,8}$", token))--def cli_command_from_argv(argv: list[str] | None = None) -> str:- """Subcommand path from argv: leading non-flag tokens that are not paths.+ # Walk registered commands only: positional text can resemble a command name.+ from typer.main import get_command- ``overmind dataset upload ./data.jsonl --json`` → ``dataset upload``.- """- raw = list(argv if argv is not None else sys.argv)- tokens: list[str] = []- for part in raw[1:]: # drop the program name- if part.startswith("-") or _looks_like_path(part):- break- tokens.append(part)- return " ".join(tokens)---def cli_flags_and_args(- argv: list[str] | None = None,-) -> tuple[dict[str, str | bool], list[str]]:- """Parse redacted flags and positionals after the nested command path.+ from overmind.__main__ import app # Lazy to avoid the CLI/analytics import cycle.- ``overmind init --ide cursor --env production`` →- ``({"ide": "cursor", "env": "production"}, [])``.-- ``overmind dataset upload data.jsonl --json`` →- ``({"json": True}, ["data.jsonl"])``.- """raw = list(argv if argv is not None else sys.argv)- parts = _redact_parts(_argv_parts(raw))- if not parts:- return {}, []- path = cli_command_from_argv(["overmind", *raw[1:]])- rest = parts[1 + len(path.split()) :]- flags: dict[str, str | bool] = {}- args: list[str] = []- i = 0- while i < len(rest):- tok = rest[i]- if not tok.startswith("-"):- args.append(tok)- i += 1- continue- key = tok.lstrip("-").split("=", 1)[0]- if "=" in tok:- flags[key] = tok.split("=", 1)[1]- i += 1- elif i + 1 < len(rest) and not rest[i + 1].startswith("-"):- flags[key] = rest[i + 1]- i += 2- else:- flags[key] = True- i += 1- return flags, args+ command = get_command(app)+ path = []+ for part in raw[1:]:+ child = getattr(command, "commands", {}).get(part)+ if child is None:+ break+ path.append(part)+ command = child+ return " ".join(path)# --- Public event API ---@@ -416,22 +306,15 @@ def track_cli_invocation(exit_code: int = 0,duration_ms: int = 0,) -> None:- """Emit ``cli.invoked``; ``command`` kwarg is the nested path only.-- Properties: ``command`` = full redacted argv, ``command_path`` = nested- path, ``flags`` / ``args`` = parsed options and positionals. Flushes so- process teardown does not drop the event. Never raises.- """+ """Emit command identity and outcome without arguments or option values."""if not enabled():returntry:ensure_identified()- flags, args = cli_flags_and_args()props = {- "command": _redact_argv(),- "command_path": (command or "").strip() or cli_command_from_argv(),- "flags": flags,- "args": args,+ "command_path": cli_command_from_argv(["overmind", *command.split()])+ if command+ else cli_command_from_argv(),"exit_code": int(exit_code or 0),"duration_ms": max(0, int(duration_ms)),"success": int(exit_code or 0) == 0,diff --git a/overmind/overmind/client.py b/overmind/overmind/client.pyindex 50b723ed..1e1ac7ba 100644--- a/overmind/overmind/client.py+++ b/overmind/overmind/client.py@@ -48,13 +48,14 @@ from typing import Anyimport requests-DEFAULT_BASE_URL = "https://api.overmindlab.ai"+from overmind.config import DEFAULT_BASE_URL@dataclassclass CompletionMessage:role: str- content: str+ content: str | None+ tool_calls: list[dict[str, Any]] | None = None@dataclass@@ -85,6 +86,7 @@ class ChatCompletion:class Delta:role: str | None = Nonecontent: str | None = None+ tool_calls: list[dict[str, Any]] | None = None@dataclass@@ -136,7 +138,8 @@ def _parse_chat_completion(data: dict) -> ChatCompletion:index=c.get("index", i),message=CompletionMessage(role=c["message"]["role"],- content=c["message"].get("content") or "",+ content=c["message"].get("content"),+ tool_calls=c["message"].get("tool_calls"),),finish_reason=c.get("finish_reason"),)@@ -169,6 +172,7 @@ def _parse_chunk(data: dict) -> ChatCompletionChunk:delta=Delta(role=c.get("delta", {}).get("role"),content=c.get("delta", {}).get("content"),+ tool_calls=c.get("delta", {}).get("tool_calls"),),finish_reason=c.get("finish_reason"),)diff --git a/overmind/overmind/config.py b/overmind/overmind/config.pyindex 67a19bcb..843daf5e 100644--- a/overmind/overmind/config.py+++ b/overmind/overmind/config.py@@ -10,7 +10,13 @@ from dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any+try:+ import tomllib+except ImportError:+ import tomli as tomllib+DEFAULT_PATH = Path("overmind.toml")+DEFAULT_BASE_URL = "https://api.overmindlab.ai"CREDENTIALS_PATH = Path(".overmind") / "credentials.toml"@@ -73,7 +79,7 @@ class Capability:@dataclassclass Config:api_key: str = ""- base_url: str = "https://api.overmindlab.ai"+ base_url: str = DEFAULT_BASE_URLproject_id: str = ""project_name: str = ""repo_summary: str = ""@@ -149,6 +155,42 @@ class Config:self.capabilities = caps+def _expand_key(value: str) -> str:+ return os.environ.get(value[4:], "") if value.startswith("env:") else value+++def resolve_api_key(cli_key: str, config: Config | None) -> str:+ if cli_key:+ return cli_key+ toml_key = _expand_key(config.api_key if config else "")+ if config and config.project_id and toml_key:+ return toml_key+ return os.environ.get("OVERMIND_API_KEY", "") or toml_key+++def resolve_api_url(cli_url: str, config: Config | None) -> str:+ if cli_url:+ return cli_url.rstrip("/")+ env = os.environ.get("OVERMIND_API_URL")+ if env:+ return env.rstrip("/")+ if config and config.base_url:+ return config.base_url.rstrip("/")+ return DEFAULT_BASE_URL+++def resolve_api_credentials(api_key: str, api_url: str, config: Config | None) -> tuple[str, str]:+ key = resolve_api_key(api_key, config)+ url = resolve_api_url(api_url, config)+ bound_key = _expand_key(config.api_key if config else "")+ if bound_key and key == bound_key and url != config.base_url.rstrip("/"):+ raise ValueError(+ "Repository credentials belong to a different API. "+ "Use the repository's saved endpoint or an explicit matching connection. No request was sent."+ )+ return key, url++class SecretFileError(RuntimeError):pass@@ -238,8 +280,6 @@ def _metric_from_dict(raw: dict) -> EvalMetric:def _load_toml(path: Path) -> dict:- import tomllib-with path.open("rb") as fh:return tomllib.load(fh)@@ -255,7 +295,7 @@ def saved_project_api_key(path: Path = DEFAULT_PATH) -> str:raw = _load_toml(path)secrets = _load_toml(secret_path)project_id = str(raw.get("project-id") or raw.get("project_id") or "")- base_url = str(raw.get("base-url") or raw.get("base_url") or "https://api.overmindlab.ai")+ base_url = str(raw.get("base-url") or raw.get("base_url") or DEFAULT_BASE_URL)if (project_idand str(secrets.get("project-id") or "") == project_id@@ -277,7 +317,7 @@ def _strip_none(value: Any) -> Any:def load(path: Path = DEFAULT_PATH) -> Config:raw = _load_toml(path)project_id = str(raw.get("project-id") or raw.get("project_id") or "")- base_url = str(raw.get("base-url") or raw.get("base_url") or "https://api.overmindlab.ai")+ base_url = str(raw.get("base-url") or raw.get("base_url") or DEFAULT_BASE_URL)caps_raw = raw.get("capabilities") or {}caps: dict[str, Capability] = {}for slug, body in caps_raw.items():diff --git a/overmind/overmind/connector_cmd.py b/overmind/overmind/connector_cmd.pyindex 972f1cbc..33cbbf6c 100644--- a/overmind/overmind/connector_cmd.py+++ b/overmind/overmind/connector_cmd.py@@ -13,8 +13,7 @@ import requestsimport typerfrom rich.console import Console-from overmind.config import DEFAULT_PATH, Config, load-from overmind.sync import resolve_api_key, resolve_api_url+from overmind.config import DEFAULT_PATH, Config, load, resolve_api_credentialsCREDENTIALS_PATH = "/api/connector-credentials/"DEFAULT_TIMEOUT = 60@@ -187,13 +186,12 @@ def add(f"Unsupported connector type {connector_type!r}. Use one of: {', '.join(SUPPORTED_TYPES)}.")config = load(path) if path.exists() else Config()- key = resolve_api_key(api_key, config)+ key, url = resolve_api_credentials(api_key, api_url, config)if not key:raise ConnectorAddError("Missing API key. Pass --api-key or set OVERMIND_API_KEY.")project = project_id.strip() or config.project_id.strip()if not project:raise ConnectorAddError("Missing project-id. Pass --project-id or add project-id to overmind.toml.")- url = resolve_api_url(api_url, config)host = base_url.strip() or (os.environ.get("LANGFUSE_HOST", "").strip() if kind == "langfuse" else "")provider_key, provider_secret = _provider_credentials(kind)result = add_connector(diff --git a/overmind/overmind/layer_cmd.py b/overmind/overmind/layer_cmd.pyindex 65a68e5d..69651f37 100644--- a/overmind/overmind/layer_cmd.py+++ b/overmind/overmind/layer_cmd.py@@ -6,7 +6,7 @@ import jsonimport reimport timeimport uuid-from datetime import UTC, datetime, timedelta+from datetime import datetime, timedelta, timezonefrom pathlib import Pathfrom typing import Annotated, Any@@ -14,8 +14,7 @@ import requestsimport typerfrom rich.console import Console-from overmind.config import DEFAULT_PATH, Config, load-from overmind.sync import resolve_api_key, resolve_api_url+from overmind.config import DEFAULT_PATH, Config, load, resolve_api_credentialsconsole = Console()@@ -75,7 +74,7 @@ def _parse_iso(value: str, *, what: str) -> datetime:except ValueError as exc:raise LayerError(f"{what} must be an ISO timestamp or a duration like 7d.") from excif parsed.tzinfo is None:- parsed = parsed.replace(tzinfo=UTC)+ parsed = parsed.replace(tzinfo=timezone.utc)return parsed@@ -253,7 +252,7 @@ def run_backtest(eval_set = capability.get("active_eval_set")if not eval_set:raise LayerError("The capability has no eval set.")- stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")+ stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")created = client.post("/api/datasets/",{@@ -325,7 +324,7 @@ def run_finetune(eval_set = capability.get("active_eval_set")if not eval_set:raise LayerError("The capability has no eval set.")- stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")+ stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")created = client.post("/api/datasets/split/",{@@ -380,12 +379,15 @@ def run_finetune(def _client(api_key: str, api_url: str, path) -> tuple[Client, Config]:config = load(path) if path.exists() else Config()- key = resolve_api_key(api_key, config)+ try:+ key, url = resolve_api_credentials(api_key, api_url, config)+ except ValueError as exc:+ raise LayerError(str(exc)) from excif not key:raise LayerError("Missing API key. Pass --api-key or set OVERMIND_API_KEY.")session = requests.Session()session.headers["X-Api-Key"] = key- return Client(session, resolve_api_url(api_url, config)), config+ return Client(session, url), configdef _common(@@ -403,7 +405,7 @@ def _common(if not project:raise LayerError("Missing project-id. Pass --project-id or add project-id to overmind.toml.")capability_id, slug = resolve_capability(config, capability)- now = datetime.now(UTC)+ now = datetime.now(timezone.utc)start = parse_since(since, now=now)end = parse_until(until)if end is not None and end < start:diff --git a/overmind/overmind/lifecycle.py b/overmind/overmind/lifecycle.pyindex 87750e69..537906d5 100644--- a/overmind/overmind/lifecycle.py+++ b/overmind/overmind/lifecycle.py@@ -25,7 +25,7 @@ from overmind.tracing import (deliver,env_identity,flush_traces,- set_conversation_id,+ session,start_span,)from overmind.tracing import capability as _capability_scope@@ -83,13 +83,14 @@ def _run_scope(if tags:attributes.update(tags)try:- with scope:- if conversation_id:- set_conversation_id(str(conversation_id))- with start_span(name, span_type=SpanType.ENTRY_POINT, unit="run", attributes=attributes or None) as span:- if intent:- _intent(str(intent))- yield RunHandle(span)+ with (+ scope,+ session(str(conversation_id)) if conversation_id else nullcontext(),+ start_span(name, span_type=SpanType.ENTRY_POINT, unit="run", attributes=attributes or None) as span,+ ):+ if intent:+ _intent(str(intent))+ yield RunHandle(span)finally:# After the boundary span ends, so this run's turn spans (closed by the# run span's own on_end) export in the flush. Never end_all(): anotherdiff --git a/overmind/overmind/openrouter_rewrite.py b/overmind/overmind/openrouter_rewrite.pyindex 8e53b120..5db37bb3 100644--- a/overmind/overmind/openrouter_rewrite.py+++ b/overmind/overmind/openrouter_rewrite.py@@ -137,22 +137,18 @@ def _openai_ctor_source(node: ast.Call, *, name: str) -> str:return f"{name}({', '.join([*positional, *parts])})"-def _has_import(tree: ast.AST, module: str, name: str | None = None) -> bool:- for node in ast.walk(tree):- if isinstance(node, ast.Import):- if any(a.name == module or a.name.startswith(module + ".") for a in node.names):- return True- elif isinstance(node, ast.ImportFrom) and node.module == module:- if name is None:- return True- if any(a.name == name for a in node.names):- return True- return False+def _has_import(tree: ast.AST, module: str, name: str) -> bool:+ return any(+ isinstance(node, ast.ImportFrom)+ and node.module == module+ and any(a.name == name and a.asname in (None, name) for a in node.names)+ for node in ast.walk(tree)+ )def _has_name_import_os(tree: ast.AST) -> bool:for node in ast.walk(tree):- if isinstance(node, ast.Import) and any(a.name == "os" or a.name.startswith("os.") for a in node.names):+ if isinstance(node, ast.Import) and any(a.name == "os" and a.asname in (None, "os") for a in node.names):return Truereturn False@@ -196,15 +192,14 @@ def _import_insert_pos(src: str) -> int:return pos-def _insert_imports(src: str, *, need_os: bool, need_openai: bool, async_client: bool) -> str:- if not need_os and not need_openai:+def _insert_imports(src: str, *, need_os: bool, openai_names: set[str]) -> str:+ if not need_os and not openai_names:return srclines: list[str] = []if need_os:lines.append("import os")- if need_openai:- name = "AsyncOpenAI" if async_client else "OpenAI"- lines.append(f"from openai import {name}")+ if openai_names:+ lines.append(f"from openai import {', '.join(sorted(openai_names))}")block = "\n".join(lines) + "\n"pos = _import_insert_pos(src)return src[:pos] + block + src[pos:]@@ -221,8 +216,7 @@ def _rewrite_python(path: Path, src: str) -> tuple[str, list[str], bool]:starts = _line_starts(src)replacements: list[tuple[int, int, str]] = []need_os = False- need_openai = False- used_async = False+ openai_names: set[str] = set()rewrote_anthropic = Falsefor node in ast.walk(tree):@@ -241,10 +235,9 @@ def _rewrite_python(path: Path, src: str) -> tuple[str, list[str], bool]:if name in _ANTHROPIC_CTORS:ctor_name = "AsyncOpenAI" if name.startswith("Async") else "OpenAI"- used_async = used_async or ctor_name.startswith("Async")+ openai_names.add(ctor_name)replacements.append((start, end, _openai_ctor_source(node, name=ctor_name)))need_os = True- need_openai = Truerewrote_anthropic = Truecontinue@@ -252,7 +245,7 @@ def _rewrite_python(path: Path, src: str) -> tuple[str, list[str], bool]:base = _kw(node, "base_url")if base is not None and _already_openrouter(base.value):continue- replacements.append((start, end, _openai_ctor_source(node, name=name)))+ replacements.append((start, end, _openai_ctor_source(node, name=ast.unparse(node.func))))need_os = Truecontinue@@ -325,10 +318,8 @@ def _rewrite_python(path: Path, src: str) -> tuple[str, list[str], bool]:leftover.append(f"{path}: rewrite produced invalid Python")return src, leftover, Falseinject_os = need_os and not _has_name_import_os(tree_after)- inject_openai = need_openai and not (- _has_import(tree_after, "openai", "OpenAI") or _has_import(tree_after, "openai", "AsyncOpenAI")- )- new_src = _insert_imports(new_src, need_os=inject_os, need_openai=inject_openai, async_client=used_async)+ missing_names = {name for name in openai_names if not _has_import(tree_after, "openai", name)}+ new_src = _insert_imports(new_src, need_os=inject_os, openai_names=missing_names)return new_src, leftover, new_src != srcdiff --git a/overmind/overmind/optimizer_cmd.py b/overmind/overmind/optimizer_cmd.pyindex bdaae940..e631b5cc 100644--- a/overmind/overmind/optimizer_cmd.py+++ b/overmind/overmind/optimizer_cmd.py@@ -25,9 +25,9 @@ from rich.panel import Panelfrom rich.table import Tableimport overmind.config as config_mod+from overmind.config import resolve_api_credentialsfrom overmind.optimizer import OptimiseLoop, attach_optimise, start_optimisefrom overmind.optimizer_api import OptimizerAPI-from overmind.sync import resolve_api_keyOPTIMISE_HELP = "Generate candidates locally; the server scores them."@@ -52,11 +52,14 @@ def _load_config() -> config_mod.Config:def _make_api(cfg: config_mod.Config) -> OptimizerAPI:- api_key = resolve_api_key("", cfg)+ try:+ api_key, base_url = resolve_api_credentials("", "", cfg)+ except ValueError as exc:+ console.print(f"[red]{exc}[/]")+ raise typer.Exit(1) from excif not api_key:console.print("[red]No API key. Run `overmind sync` or set OVERMIND_API_KEY.[/]")raise typer.Exit(1)- base_url = os.getenv("OVERMIND_API_URL") or cfg.base_urlreturn OptimizerAPI(base_url, api_key)diff --git a/overmind/overmind/sync.py b/overmind/overmind/sync.pyindex c4bf8d73..c368b405 100644--- a/overmind/overmind/sync.py+++ b/overmind/overmind/sync.py@@ -14,7 +14,6 @@ before pushing. Project-scoped keys still require an explicit ``project-id``.from __future__ import annotations-import osimport refrom pathlib import Pathfrom typing import Annotated, Any, Literal@@ -34,13 +33,13 @@ from overmind.config import (ensure_project_name,load,protect_secret_file,+ resolve_api_credentials,)SYNC_PATH = "/api/v1/sync"PROJECTS_PATH = "/api/projects/"API_KEYS_PATH = "/api/auth/api-keys/"API_KEY_CURRENT_PATH = "/api/auth/api-keys/current/"-DEFAULT_BASE_URL = "https://api.overmindlab.ai"console = Console()@@ -181,43 +180,11 @@ def ensure_project_id(config: Config, path: Path, api_key: str, base_url: str) -return config, True-def resolve_api_key(cli_key: str, config: Config | None) -> str:- if cli_key:- return cli_key- if config and config.project_id and config.api_key:- return config.api_key- env_key = os.environ.get("OVERMIND_API_KEY", "")- if env_key:- return env_key- toml_key = (config.api_key if config else "") or ""- if toml_key.startswith("env:"):- toml_key = os.environ.get(toml_key[4:], "")- return toml_key---def resolve_api_url(cli_url: str, config: Config | None) -> str:- if cli_url:- return cli_url.rstrip("/")- env = os.environ.get("OVERMIND_API_URL")- if env:- return env.rstrip("/")- if config and config.base_url:- return config.base_url.rstrip("/")- return DEFAULT_BASE_URL--def _sync_connection(api_key: str, api_url: str, config: Config) -> tuple[str, str]:- key = resolve_api_key(api_key, config)- url = resolve_api_url(api_url, config)- bound_key = config.api_key- if bound_key.startswith("env:"):- bound_key = os.environ.get(bound_key[4:], "")- if bound_key and key == bound_key and url != config.base_url.rstrip("/"):- raise SyncError(- "Repository credentials belong to a different API. "- "Use the repository's saved endpoint or an explicit matching connection. No request was sent."- )- return key, url+ try:+ return resolve_api_credentials(api_key, api_url, config)+ except ValueError as exc:+ raise SyncError(str(exc)) from excdef run_up(path: Path, api_key: str, api_url: str) -> Config:diff --git a/overmind/overmind/tracing.py b/overmind/overmind/tracing.pyindex d30ff96e..f852c150 100644--- a/overmind/overmind/tracing.py+++ b/overmind/overmind/tracing.py@@ -36,7 +36,7 @@ from opentelemetry.semconv_ai import SpanAttributesfrom opentelemetry.trace import Status, StatusCodefrom overmind import attrs-from overmind.config import DEFAULT_PATH, Config, load, saved_project_api_key+from overmind.config import DEFAULT_PATH, Config, load, resolve_api_credentialsfrom overmind.genai_usage import canonical_usage_updateslogger = logging.getLogger(__name__)@@ -53,8 +53,6 @@ _init_lock = threading.Lock()# "tracing disabled" line on every run — log it once per process, then DEBUG._keyless_logged = False-DEFAULT_BASE_URL = os.getenv("OVERMIND_API_URL", "https://api.overmindlab.ai")-def _local_config() -> Config | None:try:@@ -68,16 +66,10 @@ def get_api_settings(base_url: str | None = None,) -> tuple[str, str]:local_config = _local_config()- saved_key = saved_project_api_key(DEFAULT_PATH) if local_config else ""- overmind_api_key = (- overmind_api_key or saved_key or os.getenv("OVERMIND_API_KEY") or (local_config.api_key if local_config else "")- )- if not overmind_api_key:+ key, url = resolve_api_credentials(overmind_api_key or "", base_url or "", local_config)+ if not key:raise RuntimeError("Missing Overmind API key. Run `overmind sync` or set OVERMIND_API_KEY.")- resolved_url = (- base_url or os.getenv("OVERMIND_API_URL") or (local_config.base_url if local_config else DEFAULT_BASE_URL)- )- return overmind_api_key, resolved_url.rstrip("/")+ return key, url# Guards against cyclic / mock-heavy inputs that recurse forever.@@ -127,7 +119,12 @@ def _normalize_for_json(obj: Any, *, _depth: int = 0) -> Any:if isinstance(obj, (int, float, bool, type(None))):return objif dataclasses.is_dataclass(obj) and not isinstance(obj, type):- return {f.name: _normalize_for_json(getattr(obj, f.name), _depth=_depth + 1) for f in dataclasses.fields(obj)}+ return {+ f.name: "<redacted>"+ if _is_secret_key(f.name)+ else _normalize_for_json(getattr(obj, f.name), _depth=_depth + 1)+ for f in dataclasses.fields(obj)+ }if _should_skip_value(obj):return f"<{type(obj).__name__}>"if isinstance(obj, dict):@@ -222,10 +219,7 @@ def normalize_messages(messages: Any) -> list[dict[str, Any]]:tool_call_id = getattr(message, "tool_call_id", None)entry: dict[str, Any] = {"role": _MESSAGE_ROLE_MAP.get(role, role), "content": _message_text(content)}if tool_calls:- entry["tool_calls"] = [- {"name": tc.get("name"), "args": tc.get("args")} if isinstance(tc, dict) else str(tc)- for tc in tool_calls- ]+ entry["tool_calls"] = _normalize_for_json(tool_calls)if tool_call_id:entry["tool_call_id"] = str(tool_call_id)out.append(entry)@@ -788,13 +782,17 @@ def init(return Truelocal_config = _local_config()- saved_key = saved_project_api_key(DEFAULT_PATH) if local_config else ""- overmind_api_key = (- overmind_api_key- or saved_key- or os.getenv("OVERMIND_API_KEY")- or (local_config.api_key if local_config else "")- )+ try:+ overmind_api_key, overmind_base_url = resolve_api_credentials(+ overmind_api_key or "", overmind_base_url or "", local_config+ )+ except ValueError as exc:+ if _strict_mode:+ _track_sdk_init("strict-fail", providers=providers, capability_id=capability_id)+ raise RuntimeError(f"Overmind tracing disabled: {exc}") from exc+ logger.warning("Overmind tracing disabled: %s", exc)+ _track_sdk_init("endpoint-mismatch", providers=providers, capability_id=capability_id)+ return Falseif not overmind_api_key:msg = "Overmind tracing disabled: no project credential. Run `overmind sync` or set OVERMIND_API_KEY."if _strict_mode:@@ -804,11 +802,6 @@ def init(_keyless_logged = True_track_sdk_init("keyless", providers=providers, capability_id=capability_id)return False- overmind_base_url = (- overmind_base_url- or os.getenv("OVERMIND_API_URL")- or (local_config.base_url if local_config else DEFAULT_BASE_URL)- ).rstrip("/")project_id = project_id or (local_config.project_id if local_config else None)environment = (@@ -1066,8 +1059,12 @@ def capability(name: str | None = None, *, id: str | None = None) -> _Capabilityreturn _CapabilityScope(name, id)+def _capability_identity() -> str:+ return str(get_value(attrs.CAPABILITY_ID) or get_value(attrs.CAPABILITY_NAME) or "")++class _TurnRegistry:- """Open turn-unit spans keyed by (trace_id, behaviour key).+ """Open turn-unit spans keyed by (trace_id, capability, behaviour key).A behaviour's activity is non-contiguous in loop-shaped agents (debaterounds interleave with other phases), so its turn span outlives each task@@ -1076,21 +1073,22 @@ class _TurnRegistry:def __init__(self) -> None:self._lock = threading.Lock()- self._spans: dict[tuple[int, str], trace.Span] = {}- self._last_activity_ns: dict[tuple[int, str], int] = {}+ self._spans: dict[tuple[int, str, str], trace.Span] = {}+ self._last_activity_ns: dict[tuple[int, str, str], int] = {}def get_or_start(self, key: str) -> trace.Span:ambient = trace.get_current_span().get_span_context()+ identity = _capability_identity()evicted: list[tuple[trace.Span, int | None]] = []with self._lock:- if ambient.is_valid and (span := self._spans.pop((ambient.trace_id, key), None)) is not None:+ if ambient.is_valid and (span := self._spans.pop((ambient.trace_id, identity, key), None)) is not None:# Re-insert so eviction takes the least recently used entry.- self._spans[(ambient.trace_id, key)] = span+ self._spans[(ambient.trace_id, identity, key)] = spanreturn spanspan = get_tracer().start_span(key, attributes=_declared_attributes(SpanType.FUNCTION, None, "turn", behaviour_key=key))- self._spans[(span.get_span_context().trace_id, key)] = span+ self._spans[(span.get_span_context().trace_id, identity, key)] = span# Without a run boundary nothing ever ends these; cap like the# evidence registry so a long-lived process cannot leak live spans.while len(self._spans) > _MAX_TRACKED_TRACES:@@ -1101,7 +1099,8 @@ class _TurnRegistry:return spandef touch(self, span: trace.Span, key: str) -> None:- entry = (span.get_span_context().trace_id, key)+ identity = _capability_identity()+ entry = (span.get_span_context().trace_id, identity, key)with self._lock:# Only a still-tracked span records activity — a touch after# eviction must not resurrect the bookkeeping for an ended span.@@ -1115,7 +1114,7 @@ class _TurnRegistry:def end_all(self) -> None:self._end(lambda entry: True)- def _end(self, match: Callable[[tuple[int, str]], bool]) -> None:+ def _end(self, match: Callable[[tuple[int, str, str]], bool]) -> None:with self._lock:entries = [entry for entry in self._spans if match(entry)]ended = [(self._spans.pop(entry), self._last_activity_ns.pop(entry, None)) for entry in entries]diff --git a/overmind/overmind/transfer_connection.py b/overmind/overmind/transfer_connection.pyindex eddc5ab3..92674a98 100644--- a/overmind/overmind/transfer_connection.py+++ b/overmind/overmind/transfer_connection.py@@ -11,8 +11,7 @@ try:except ImportError:import tomli as tomllib-from overmind.config import Config-from overmind.sync import resolve_api_key, resolve_api_url+from overmind.config import Config, resolve_api_credentialsclass TransferError(Exception):@@ -235,17 +234,8 @@ def check_connection(*, api_key, api_url, project_id, session=None):def resolve_transfer_connection(api_key: str, api_url: str, config: Config | None) -> tuple[str, str]:- key = resolve_api_key(api_key, config)+ key, base = resolve_api_credentials(api_key, api_url, config)if key:- base = resolve_api_url(api_url, config)- bound_key = config.api_key if config else ""- if bound_key.startswith("env:"):- bound_key = os.environ.get(bound_key[4:], "")- if bound_key and key == bound_key and base != config.base_url.rstrip("/"):- raise ValueError(- "Repository credentials belong to a different API; select a matching connection "- "instead of overriding only its address. No request was sent."- )return key, baseroot = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config")diff --git a/overmind/pyproject.toml b/overmind/pyproject.tomlindex 2c9b3dd6..57d4f257 100644--- a/overmind/pyproject.toml+++ b/overmind/pyproject.toml@@ -46,7 +46,7 @@ license = { text = "MIT" }name = "overmind"readme = "README.md"requires-python = ">=3.10,<4" # todo; remove the upper bound-version = "0.1.119"+version = "0.1.120"[project.urls]"Agent setup" = "https://console.overmindlab.ai/setup.md"diff --git a/overmind/tests/test_analytics.py b/overmind/tests/test_analytics.pyindex 91ea9437..62183124 100644--- a/overmind/tests/test_analytics.py+++ b/overmind/tests/test_analytics.py@@ -140,46 +140,23 @@ def test_capture_swallows_client_errors(monkeypatch, posthog_client):analytics.capture("sdk_init", outcome="keyless")-def test_redact_argv_strips_secrets():- line = analytics._redact_argv([- "overmind",- "sync",- "--api-key",- "om_super_secret_value_123456",- "--project-id",- "proj_abc",- ])- assert line == "overmind sync --api-key [redacted] --project-id proj_abc"- assert "om_super_secret" not in line--@pytest.mark.parametrize(- "argv,flags,args",+ "argv,expected",[- (- ["overmind", "init", "--ide", "cursor", "--env", "production"],- {"ide": "cursor", "env": "production"},- [],- ),- (- ["overmind", "dataset", "upload", "data.jsonl", "--json"],- {"json": True},- ["data.jsonl"],- ),- (- ["overmind", "sync", "--api-key", "om_super_secret_value_123456"],- {"api-key": "[redacted]"},- [],- ),- (- ["overmind", "init", "--ide=cursor"],- {"ide": "cursor"},- [],- ),+ (["overmind", "init", "--brief", "private business plan"], "init"),+ (["overmind", "dataset", "upload", "/private/customers.jsonl", "--json"], "dataset upload"),+ (["overmind", "connector", "add", "private-provider"], "connector add"),+ (["overmind", "unknown-private-text"], ""),],)-def test_cli_flags_and_args(argv, flags, args):- assert analytics.cli_flags_and_args(argv) == (flags, args)+def test_cli_tracks_registered_commands_only(monkeypatch, posthog_client, argv, expected):+ monkeypatch.setattr(sys, "argv", argv)+ monkeypatch.delenv("OVERMIND_API_KEY", raising=False)+ assert analytics.cli_command_from_argv() == expected+ analytics.track_cli_invocation()+ properties = posthog_client.capture.call_args.kwargs["properties"]+ assert properties["command_path"] == expected+ assert not {"command", "flags", "args"} & properties.keys()def test_ensure_identified_caches_per_key(monkeypatch, tmp_path, posthog_client):diff --git a/overmind/tests/test_client.py b/overmind/tests/test_client.pyindex 0dc14839..1f5729c9 100644--- a/overmind/tests/test_client.py+++ b/overmind/tests/test_client.py@@ -287,3 +287,25 @@ class TestModelsDelete:c._session.delete = MagicMock(side_effect=requests.exceptions.ConnectionError("refused"))with pytest.raises(OvermindInferenceError, match="Failed to delete model"):c.models.delete("ft-test")++[email protected]("stream", [False, True])+def test_completion_preserves_tool_calls_and_arguments(monkeypatch, stream):+ calls = [{"id": "call-1", "type": "function", "function": {"name": "lookup", "arguments": '{"id":42}'}}]+ part = {"role": "assistant", "content": None, "tool_calls": calls}+ data = {"id": "response", "choices": [{"index": 0, "delta" if stream else "message": part}]}+ response = (+ _sse_response([f"data: {json.dumps(data)}", "data: [DONE]"]) if stream else _mock_response(json_data=data)+ )+ sent = []++ def post(_session, _url, **kwargs):+ sent.append(kwargs["json"])+ return response++ monkeypatch.setattr(requests.Session, "post", post)+ result = _make_client().chat.completions.create(model="m", messages=[], stream=stream, tools=[{"type": "function"}])+ message = list(result)[0].choices[0].delta if stream else result.choices[0].message+ assert message.tool_calls == calls+ assert message.content is None+ assert sent[0]["tools"] == [{"type": "function"}]diff --git a/overmind/tests/test_config_toml.py b/overmind/tests/test_config_toml.pyindex 75a491e6..858532ff 100644--- a/overmind/tests/test_config_toml.py+++ b/overmind/tests/test_config_toml.py@@ -12,7 +12,9 @@ from overmind.config import (dump,load,protect_secret_file,+ resolve_api_credentials,)+from overmind.tracing import get_api_settingsfrom overmind.utils import convert_json_to_tomlpytestmark = pytest.mark.covers("privacy")@@ -219,3 +221,40 @@ def test_secret_file_still_works_without_git(tmp_path: Path):protect_secret_file(secret, repo_root=tmp_path)assert (tmp_path / ".overmind" / ".gitignore").read_text() == "*\n"++[email protected]("privacy")[email protected]("override", ["argument", "environment"])+ "base_url", ["https://api.overmindlab.ai", "https://overmind.example.org", "http://localhost:8000"]+)+def test_saved_key_cannot_follow_an_endpoint_override(tmp_path, monkeypatch, override, base_url):+ monkeypatch.chdir(tmp_path)+ monkeypatch.delenv("OVERMIND_API_URL", raising=False)+ cfg = Config(api_key="bound-secret", base_url=base_url, project_id="project")+ dump(cfg, Path("overmind.toml"))+ assert resolve_api_credentials("", "", cfg) == ("bound-secret", base_url)+ assert get_api_settings() == ("bound-secret", base_url)+ url = "https://different.example"+ if override == "environment":+ monkeypatch.setenv("OVERMIND_API_URL", url)+ url = ""+ with pytest.raises(ValueError, match="different API"):+ resolve_api_credentials("", url, cfg)+ with pytest.raises(ValueError, match="different API"):+ get_api_settings(base_url=url)+ assert resolve_api_credentials("explicit-other-key", url, cfg) == (+ "explicit-other-key",+ "https://different.example",+ )++[email protected]("authentication")+def test_project_key_reference_resolves_before_the_account_key(monkeypatch):+ cfg = Config(api_key="env:PROJECT_KEY", base_url="https://api.example", project_id="project")+ monkeypatch.setenv("OVERMIND_API_KEY", "account-key")+ monkeypatch.delenv("OVERMIND_API_URL", raising=False)+ monkeypatch.setenv("PROJECT_KEY", "project-key")+ assert resolve_api_credentials("", "", cfg) == ("project-key", "https://api.example")+ monkeypatch.delenv("PROJECT_KEY")+ assert resolve_api_credentials("", "", cfg) == ("account-key", "https://api.example")diff --git a/overmind/tests/test_layer_cmd.py b/overmind/tests/test_layer_cmd.pyindex 19e3309a..a128fc59 100644--- a/overmind/tests/test_layer_cmd.py+++ b/overmind/tests/test_layer_cmd.py@@ -1,7 +1,7 @@from __future__ import annotationsimport json-from datetime import UTC, datetime+from datetime import datetime, timezoneimport pytestfrom typer.testing import CliRunner@@ -136,7 +136,7 @@ def test_backtest_scores_each_model_and_exits_on_regression():capability_id="cap",capability_slug="support",models=["openai/gpt-5-mini", "anthropic/claude-sonnet-4.5"],- since=datetime(2026, 1, 1, tzinfo=UTC),+ since=datetime(2026, 1, 1, tzinfo=timezone.utc),until=None,limit=200,from_model="",@@ -168,7 +168,7 @@ def test_backtest_fails_when_a_metric_does_not_score():capability_id="cap",capability_slug="support",models=["openai/gpt-5-mini"],- since=datetime(2026, 1, 1, tzinfo=UTC),+ since=datetime(2026, 1, 1, tzinfo=timezone.utc),until=None,limit=10,from_model="",@@ -186,7 +186,7 @@ def test_unknown_model_does_not_create_a_dataset():capability_id="cap",capability_slug="support",models=["openai/gpt-5-mini"],- since=datetime(2026, 1, 1, tzinfo=UTC),+ since=datetime(2026, 1, 1, tzinfo=timezone.utc),until=None,limit=10,from_model="",@@ -218,7 +218,7 @@ def test_finetune_starts_one_job_per_model_in_one_group():capability_id="cap",capability_slug="support",models=["Qwen/Qwen2.5-7B-Instruct", "meta-llama/Llama-3.1-8B-Instruct"],- since=datetime(2026, 1, 1, tzinfo=UTC),+ since=datetime(2026, 1, 1, tzinfo=timezone.utc),until=None,limit=200,from_model="",@@ -257,7 +257,7 @@ def test_a_later_finetune_failure_reports_the_jobs_already_queued():capability_id="cap",capability_slug="support",models=["Qwen/Qwen2.5-7B-Instruct", "meta-llama/Llama-3.1-8B-Instruct"],- since=datetime(2026, 1, 1, tzinfo=UTC),+ since=datetime(2026, 1, 1, tzinfo=timezone.utc),until=None,limit=20,from_model="",@@ -283,7 +283,7 @@ def test_backtest_times_out_while_the_run_is_still_going():capability_id="cap",capability_slug="support",models=["openai/gpt-5-mini"],- since=datetime(2026, 1, 1, tzinfo=UTC),+ since=datetime(2026, 1, 1, tzinfo=timezone.utc),until=None,limit=10,from_model="",@@ -296,3 +296,16 @@ def test_cli_requires_models():result = CliRunner().invoke(app, ["backtest"])assert result.exit_code == 1assert "models" in result.output.lower()+++def test_cli_reports_a_saved_key_meeting_another_endpoint(tmp_path, monkeypatch):+ from overmind.config import dump++ monkeypatch.chdir(tmp_path)+ dump(Config(api_key="saved-key", base_url="https://api.example", project_id="p"), tmp_path / "overmind.toml")+ monkeypatch.setenv("OVERMIND_API_URL", "https://other.example")+ monkeypatch.delenv("OVERMIND_API_KEY", raising=False)+ result = CliRunner().invoke(app, ["backtest", "--models", "openai/gpt-5-mini", "--capability", "cap"])+ assert result.exit_code == 1+ assert "different API" in result.output+ assert result.exception is None or isinstance(result.exception, SystemExit)diff --git a/overmind/tests/test_lifecycle.py b/overmind/tests/test_lifecycle.pyindex 33ed7212..1a182e25 100644--- a/overmind/tests/test_lifecycle.py+++ b/overmind/tests/test_lifecycle.py@@ -8,6 +8,7 @@ from __future__ import annotationsimport asyncioimport contextvars+import dataclassesimport pytestfrom opentelemetry.sdk.trace import TracerProvider@@ -285,3 +286,41 @@ def test_bare_run_decoration_raises():@rundef main() -> None: ...+++def test_run_restores_outer_conversation(exporter):+ with tracing.session("outer"):+ with run("first", conversation_id="customer-1"):+ pass+ with run("second"):+ pass+ assert _by_name(exporter, "first").attributes["conversation.id"] == "customer-1"+ assert _by_name(exporter, "second").attributes["conversation.id"] == "outer"+++def test_turns_with_same_behavior_are_separate_per_capability(exporter):+ with run("root"):+ for identity in ["cap-a", "cap-b", "cap-a"]:+ with tracing.capability(id=identity), task("answer", unit="turn"):+ pass+ turns = [s for s in exporter.get_finished_spans() if s.name == "answer"]+ assert len(turns) == 2+ assert {s.attributes[attrs.CAPABILITY_ID] for s in turns} == {"cap-a", "cap-b"}++[email protected]("privacy")+def test_run_redacts_nested_dataclass_fields(exporter):+ @dataclasses.dataclass+ class Credentials:+ password: str+ count: int++ @run("secret-result")+ def operation():+ return {"result": Credentials(password="never-export-this", count=3)}++ operation()+ output = _by_name(exporter, "secret-result").attributes["outputs"]+ assert "never-export-this" not in output+ assert "redacted" in output+ assert "3" in outputdiff --git a/overmind/tests/test_openrouter_rewrite.py b/overmind/tests/test_openrouter_rewrite.pynew file mode 100644index 00000000..5c98e734--- /dev/null+++ b/overmind/tests/test_openrouter_rewrite.py@@ -0,0 +1,36 @@+from __future__ import annotations++import re+import sys+from types import SimpleNamespace++import pytest++from overmind.openrouter_rewrite import rewrite_repo++pytestmark = pytest.mark.covers("cli-contract")+++ "source",+ [+ "import openai\nclient = openai.OpenAI()\n",+ "import openai as provider\nclient = provider.AsyncOpenAI()\n",+ "from anthropic import Anthropic, AsyncAnthropic\na = Anthropic()\nb = AsyncAnthropic()\n",+ "from openai import AsyncOpenAI\nfrom anthropic import Anthropic\na = Anthropic()\nb = AsyncOpenAI()\n",+ "try:\n from openai import OpenAI\nexcept ImportError:\n OpenAI = None\nfrom anthropic import Anthropic\na = Anthropic()\n",+ ],+)+def test_rewritten_constructors_resolve_all_client_names(tmp_path, monkeypatch, source):+ monkeypatch.setenv("OPENROUTER_API_KEY", "test-key")+ monkeypatch.setitem(sys.modules, "anthropic", SimpleNamespace(Anthropic=None, AsyncAnthropic=None))+ path = tmp_path / "agent.py"+ path.write_text(source)+ report = rewrite_repo(tmp_path)+ assert report.leftover == []+ imported = [n.strip() for g in re.findall(r"from openai import ([\w, ]+)", path.read_text()) for n in g.split(",")]+ assert len(imported) == len(set(imported))+ namespace = {}+ exec(compile(path.read_text(), str(path), "exec"), namespace)+ clients = [namespace[name] for name in ("client", "a", "b") if name in namespace]+ assert all(str(client.base_url) == "https://openrouter.ai/api/v1/" for client in clients)diff --git a/overmind/tests/test_resumable_transfer.py b/overmind/tests/test_resumable_transfer.pyindex 1619697b..0be4334d 100644--- a/overmind/tests/test_resumable_transfer.py+++ b/overmind/tests/test_resumable_transfer.py@@ -1,6 +1,12 @@import hashlibimport jsonimport time+from pathlib import Path++try:+ import tomllib+except ImportError:+ import tomli as tomllibimport pytestimport requests@@ -370,10 +376,6 @@ def test_readiness_preserves_auth_permission_and_redirect_failures(monkeypatch,@pytest.mark.covers("authentication")def test_global_setup_uses_one_connection_without_pinning_a_project(tmp_path, monkeypatch):- from pathlib import Path-- import tomllib-monkeypatch.setattr(Path, "home", lambda: tmp_path)monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "config"))monkeypatch.setenv("OVERMIND_API_KEY", "secret-key")diff --git a/overmind/tests/test_sdk.py b/overmind/tests/test_sdk.pyindex 215c5b8c..2a69b256 100644--- a/overmind/tests/test_sdk.py+++ b/overmind/tests/test_sdk.py@@ -124,6 +124,27 @@ def test_init_uses_synced_local_credential(no_api_key, mock_opentelemetry, tmp_p)[email protected]("authentication")[email protected]("strict", [False, True])+def test_init_disables_tracing_when_the_saved_key_meets_another_endpoint(+ no_api_key, mock_opentelemetry, tmp_path, monkeypatch, strict+):+ from overmind import tracing+ from overmind.config import Config, dump++ monkeypatch.chdir(tmp_path)+ dump(Config(api_key="ovr_project_key", base_url="https://api.example", project_id="p"), tmp_path / "overmind.toml")+ monkeypatch.setenv("OVERMIND_API_URL", "https://other.example")+ monkeypatch.setattr(tracing, "_strict_mode", strict)++ if strict:+ with pytest.raises(RuntimeError, match="different API"):+ tracing.init()+ else:+ assert tracing.init() is False+ mock_opentelemetry["exporter"].assert_not_called()++def test_observe_calls_through_when_uninitialised(no_api_key):from overmind import tracingdiff --git a/overmind/tests/test_sync_ensure_project.py b/overmind/tests/test_sync_ensure_project.pyindex 41d280af..b460d08c 100644--- a/overmind/tests/test_sync_ensure_project.py+++ b/overmind/tests/test_sync_ensure_project.py@@ -8,14 +8,13 @@ from unittest.mock import MagicMock, patchimport pytest-from overmind.config import Config, dump, load+from overmind.config import Config, dump, load, resolve_api_keyfrom overmind.init_cmd import SUPPORTED_IDES, claude_config_path, write_mcp_configfrom overmind.sync import (SyncError,_api_key_scope,_slugify,ensure_project_id,- resolve_api_key,run_down,run_up,)diff --git a/overmind/tests/test_tracing_serialize.py b/overmind/tests/test_tracing_serialize.pyindex 362e8037..50cb8219 100644--- a/overmind/tests/test_tracing_serialize.py+++ b/overmind/tests/test_tracing_serialize.py@@ -18,8 +18,9 @@ import jsonfrom pathlib import PurePathimport pytest+from openai.types.chat.chat_completion_message import ChatCompletionMessage-from overmind.tracing import _coerce_to_otel_attribute, _normalize_for_json+from overmind.tracing import _coerce_to_otel_attribute, _normalize_for_json, normalize_messagespytestmark = pytest.mark.covers("sdk-wire")@@ -163,3 +164,14 @@ class TestCoerceToOtelAttribute:out = _coerce_to_otel_attribute([1, "a"])assert isinstance(out, str)assert json.loads(out) == [1, "a"]++[email protected]("object_form", [False, True])+def test_messages_keep_tool_call_identity_and_arguments(object_form):+ calls = [{"id": "call-1", "type": "function", "function": {"name": "lookup", "arguments": '{"id":42}'}}]+ message = {"role": "assistant", "content": "Looking up", "tool_calls": calls}+ if object_form:+ message = ChatCompletionMessage(**message)+ [result] = normalize_messages([message])+ assert result["tool_calls"] == calls+ assert result["content"] == "Looking up"diff --git a/overmind/uv.lock b/overmind/uv.lockindex 392c80cb..46be0eb8 100644--- a/overmind/uv.lock+++ b/overmind/uv.lock@@ -923,7 +923,7 @@ wheels = [[[package]]name = "overmind"-version = "0.1.119"+version = "0.1.120"source = { editable = "." }dependencies = [{ name = "packaging" },diff --git a/scripts/check_test_seams.py b/scripts/check_test_seams.pyindex ca81f0ac..8607d1aa 100644--- a/scripts/check_test_seams.py+++ b/scripts/check_test_seams.py@@ -60,8 +60,7 @@ def _working() -> dict[str, str]:"--others","--exclude-standard","--",- "tests",- "frontend/src",+ *ROOTS,)return {path: Path(path).read_text(encoding="utf-8")diff --git a/tests/coverage_map.py b/tests/coverage_map.pyindex cf37b8b8..5938c627 100644--- a/tests/coverage_map.py+++ b/tests/coverage_map.py@@ -8,10 +8,10 @@ computation with real edge cases.from __future__ import annotationsfrom dataclasses import dataclass-from enum import StrEnum+from enum import Enum-class Severity(StrEnum):+class Severity(str, Enum): # noqa: UP042 — shared with the Python 3.10 SDK suite.# A security breach, a wrong charge, or lost or changed data.CRITICAL = "S1"# A vertical, or the platform, stops for every customer.@@ -21,13 +21,19 @@ class Severity(StrEnum):# A heuristic or a presentation detail is wrong.LOW = "S4"+ def __str__(self):+ return self.value-class Kind(StrEnum):++class Kind(str, Enum): # noqa: UP042 — shared with the Python 3.10 SDK suite.PROMISE = "promise"INVARIANT = "invariant"CONTRACT = "contract"LOGIC = "logic"+ def __str__(self):+ return self.value+@dataclass(frozen=True)class Entry: