Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /als-apg_osprey /src /osprey /agent_runner /primitives.py
| """Headless agent-run primitives shared across the OSPREY package. | |
| These symbols are extracted from ``tests/e2e/sdk_helpers.py`` so they can be | |
| imported by production code (e.g. ``osprey query``) without depending on the | |
| test tree. The test module re-imports from here and deletes its own copies so | |
| there is a single source of truth. | |
| The SDK import block mirrors the pattern in ``sdk_helpers.py``: the whole | |
| module remains importable even when ``claude_agent_sdk`` is not installed; only | |
| the runtime paths that actually USE the SDK will fail in that case. | |
| """ | |
| from __future__ import annotations | |
| import asyncio | |
| import json | |
| import logging | |
| import os | |
| import time | |
| from dataclasses import dataclass, field | |
| from pathlib import Path | |
| from typing import TYPE_CHECKING, Any | |
| if TYPE_CHECKING: | |
| from claude_agent_sdk import ( | |
| ClaudeAgentOptions, | |
| ClaudeSDKClient, | |
| PermissionMode, | |
| ResultMessage, | |
| SystemMessage, | |
| ToolResultBlock, | |
| ) | |
| # SDK imports — keep module importable even when SDK is absent. | |
| try: | |
| from claude_agent_sdk import ( # type: ignore[assignment] | |
| AssistantMessage, | |
| ClaudeAgentOptions, | |
| ResultMessage, | |
| SystemMessage, | |
| TextBlock, | |
| ToolResultBlock, | |
| ToolUseBlock, | |
| UserMessage, | |
| ) | |
| HAS_SDK = True | |
| except ImportError: | |
| HAS_SDK = False | |
| from osprey.infrastructure.proxy.lifecycle import start_proxy | |
| logger = logging.getLogger(__name__) | |
| # --------------------------------------------------------------------------- | |
| # Internal support: provider / spec resolution | |
| # --------------------------------------------------------------------------- | |
| # These helpers back sdk_env() and resolve_default_model(). They are NOT part | |
| # of the public __all__ but live here because they have no other production | |
| # home yet (they were in the test tree alongside the consumers). | |
| def _apply_e2e_overrides(spec: Any) -> Any: | |
| """Apply suite-wide CBORG model-matrix overrides to a resolved spec (#259). | |
| This is the single chokepoint every routing consumer goes through | |
| (``provider_env_for_project``, ``resolve_default_model``, | |
| and ``run_sdk_query``'s default model), so forcing the spec here keeps | |
| the build env, the SDK ``model=`` argument, and the proxy base URL | |
| mutually consistent. | |
| * ``OSPREY_E2E_FORCE_MODEL`` — collapse every tier onto one model id and | |
| rewrite the tier-model env vars to match. | |
| * ``OSPREY_E2E_PROXY_BASE_URL`` — point ``ANTHROPIC_BASE_URL`` at the | |
| in-process translation proxy (set by the session fixture in | |
| tests/e2e/conftest.py for OpenAI-protocol / open models). Anthropic- | |
| protocol CBORG models (``claude-*``) leave this unset and route direct. | |
| Inert (returns the spec unchanged) when neither var is set, so normal | |
| e2e runs are unaffected. | |
| """ | |
| if spec is None: | |
| return None | |
| force_model = os.environ.get("OSPREY_E2E_FORCE_MODEL") | |
| proxy_base = os.environ.get("OSPREY_E2E_PROXY_BASE_URL") | |
| if not force_model and not proxy_base: | |
| return spec | |
| import dataclasses | |
| tier_to_model = dict(spec.tier_to_model) | |
| env_block = dict(spec.env_block) | |
| if force_model: | |
| from osprey.build.claude_code_resolver import TIER_MODEL_ENV_VARS | |
| for tier in tier_to_model: | |
| tier_to_model[tier] = force_model | |
| # Force exactly ANTHROPIC_MODEL plus the tier-model vars, derived from | |
| # the single TIER_MODEL_ENV_VARS source so this key set cannot drift | |
| # from resolve()'s env_block (the #350 failure). Only keys actually | |
| # present in env_block are rewritten. | |
| forced_keys = {"ANTHROPIC_MODEL"} | set(TIER_MODEL_ENV_VARS.values()) | |
| for key in forced_keys: | |
| if key in env_block: | |
| env_block[key] = force_model | |
| if proxy_base: | |
| env_block["ANTHROPIC_BASE_URL"] = proxy_base | |
| return dataclasses.replace(spec, tier_to_model=tier_to_model, env_block=env_block) | |
| def _secrets_dir(project_dir: Path) -> Path: | |
| """The directory whose ``.env`` holds the secrets *project_dir*'s config needs. | |
| Callers here hand over the RENDER — ``<repo>/build``, the directory holding | |
| ``config.yml``. Secrets are not in it and must not be: ``.env`` is the | |
| durable secrets zone at the repo root, deliberately outside the zone every | |
| ``osprey build`` wipes. Reading ``.env`` beside the config therefore reads | |
| nothing at all, leaving ``${VAR}`` expansion with ``os.environ`` alone — | |
| which is why a provider whose ``base_url``/``api_key`` lives only in the | |
| repo's ``.env`` resolved to a literal placeholder here while the same | |
| deployment authenticated fine under ``osprey chat``. | |
| Resolved through the helper the runtime resolves a repo root with, so a flat | |
| directory that holds its own ``config.yml`` still answers itself — the | |
| previous behaviour, kept for every caller that passes one. | |
| """ | |
| from osprey.utils.workspace import repo_root_for_config | |
| return repo_root_for_config(Path(project_dir) / "config.yml") | |
| def _resolve_project_spec(project_dir: Path, *, provider: str | None = None) -> Any: | |
| """Return the project's ``ClaudeCodeModelSpec`` or ``None``. | |
| Reads ``config.yml`` and runs the same resolver ``osprey chat`` | |
| uses, so test routing matches production exactly. Surfaces any unexpected | |
| error (missing config, YAML parse failure, resolver import failure) rather | |
| than masking it as ``None`` — with one carve-out, for the telemetry | |
| credential a deploy has not issued yet (see below). | |
| Args: | |
| project_dir: Path to an initialized OSPREY project — the render holding | |
| ``config.yml``. | |
| provider: When given, overrides ``claude_code.provider`` in the loaded | |
| config before resolving — used by cross-provider model sweeps in | |
| the benchmark runner. | |
| """ | |
| from osprey.build.claude_code_resolver import load_provider_spec | |
| from osprey.build.claude_code_telemetry import ( | |
| ObservabilityCredentialError, | |
| telemetry_creds_are_store_issued, | |
| ) | |
| # load_provider_spec reads config.yml and expands ${VAR} in provider config | |
| # (e.g. a custom provider's base_url: ${ARGO_PROD_URL}) against an | |
| # os.environ + project .env overlay before resolving. The overlay is taken | |
| # from the repo's secrets zone (see _secrets_dir), which is the same pairing | |
| # the dispatch worker and `osprey chat` read the spec with. The e2e/benchmark | |
| # override is applied last so it still wins (and is inert in production). | |
| env_dir = _secrets_dir(project_dir) | |
| try: | |
| spec = load_provider_spec(project_dir, env_dir=env_dir, provider=provider) | |
| except ObservabilityCredentialError as exc: | |
| # Keep this arm ahead of any broader one added later: it subclasses | |
| # ValueError. | |
| # | |
| # Resolving the provider resolves the telemetry block with it, so a | |
| # store-issued credential that no deploy has minted yet arrives here as | |
| # a failure to read the provider — and every agent this project spawns | |
| # would die on it, on a project whose only fault is never having been | |
| # started. Run without telemetry instead; losing an agent run's traces | |
| # is not a reason to withhold the run. Anything else — a credential an | |
| # operator has to set, or one that is simply blank — keeps raising. | |
| if not telemetry_creds_are_store_issued(exc): | |
| raise | |
| logger.warning( | |
| "Telemetry is off for this run — `osprey up` issues %s when it starts the " | |
| "telemetry store, and this project has not been started yet", | |
| ", ".join(exc.unresolved_vars), | |
| ) | |
| spec = load_provider_spec( | |
| project_dir, env_dir=env_dir, provider=provider, include_telemetry=False | |
| ) | |
| return _apply_e2e_overrides(spec) | |
| def provider_env_for_project(project_dir: Path, *, provider: str | None = None) -> dict[str, str]: | |
| """Resolve provider env vars so the SDK routes to the project's provider. | |
| Without this, the bundled Claude CLI defaults to ``api.anthropic.com`` | |
| using whatever ambient ``ANTHROPIC_API_KEY`` happens to be set — which | |
| is the wrong endpoint for cborg/als-apg projects and 404s on model | |
| aliases like ``anthropic/claude-haiku``. | |
| Args: | |
| project_dir: Path to an initialized OSPREY project. | |
| provider: When given, overrides ``claude_code.provider`` in the loaded | |
| config before resolving — used by cross-provider model sweeps in | |
| the benchmark runner. | |
| Returns: | |
| Env dict with ``ANTHROPIC_BASE_URL``, the auth-token var, the tier-model | |
| vars, and the *raw* upstream secret var (see below), populated from the | |
| configured provider. | |
| Raises: | |
| RuntimeError: When the project has no resolvable provider. | |
| Notes: | |
| Two distinct auth vars are propagated because the project has two LLM | |
| call paths: | |
| * The bundled Claude CLI / SDK authenticates via ``spec.auth_env_var`` | |
| (e.g. ``ANTHROPIC_AUTH_TOKEN`` for proxy providers). | |
| * The in-context channel-finder benchmark spawns an MCP **stdio** | |
| subprocess that inherits only a tiny safe-list (HOME, PATH, …) and | |
| then expands ``config.yml``'s ``api_key: ${SECRET}`` against its own | |
| environment. So the *raw* ``spec.auth_secret_env`` var must be carried | |
| through explicitly, or the literal ``${SECRET}`` reaches litellm and | |
| 401s. For proxy providers (cborg/als-apg) the two var names differ; | |
| for anthropic-direct they coincide. | |
| The deployment's ``.env`` — at the repo root, not beside the config | |
| being read (see :func:`_secrets_dir`) — is honoured first, so a | |
| freshly-configured key overrides a stale shell export (mirrors | |
| ``inject_provider_env``). | |
| """ | |
| spec = _resolve_project_spec(project_dir, provider=provider) | |
| if spec is None: | |
| raise RuntimeError( | |
| f"Project at {project_dir} has no resolvable provider in " | |
| "config.yml — pass provider=<als-apg|cborg|anthropic|amsc-i2|argo> " | |
| "to init_project()." | |
| ) | |
| env: dict[str, str] = dict(spec.env_block) | |
| # Overlay the deployment's .env so freshly-configured keys win over stale | |
| # shell exports; strictly a superset of reading os.environ alone. Uses the | |
| # shared overlay helper (no circular import: resolver never imports primitives), | |
| # against the repo's secrets zone rather than the render — see _secrets_dir. | |
| from osprey.build.claude_code_resolver import _env_lookup | |
| lookup: dict[str, str] = _env_lookup(_secrets_dir(project_dir)) | |
| if spec.auth_secret_env: | |
| secret = lookup.get(spec.auth_secret_env) | |
| if secret: | |
| if spec.auth_env_var: | |
| env[spec.auth_env_var] = secret | |
| # Raw secret for the MCP-subprocess ${SECRET} expansion (see Notes). | |
| env[spec.auth_secret_env] = secret | |
| # Spend attribution on a LiteLLM-fronted provider (mirrors inject_provider_env). | |
| from osprey.models.spend_attribution import apply_attribution_env | |
| apply_attribution_env(env, spec.gateway) | |
| return env | |
| # --------------------------------------------------------------------------- | |
| # Tool trace dataclass | |
| # --------------------------------------------------------------------------- | |
| class ToolTrace: | |
| """Lightweight record of a single tool call for observability.""" | |
| name: str | |
| input: dict[str, Any] | |
| result: str | None = None | |
| is_error: bool = False | |
| tool_use_id: str | None = None | |
| parent_tool_use_id: str | None = None | |
| class SDKWorkflowResult: | |
| """Aggregated result from an SDK query run.""" | |
| tool_traces: list[ToolTrace] = field(default_factory=list) | |
| text_blocks: list[str] = field(default_factory=list) | |
| system_messages: list[SystemMessage] = field(default_factory=list) | |
| result: ResultMessage | None = None | |
| # Authoritative MCP server snapshot from ``ClaudeSDKClient.get_mcp_status()`` | |
| # captured just before the prompt is sent (see ``await_mcp_ready``). Each entry | |
| # is an ``McpServerStatus`` object (SDK) or raw dict: {name, status, tools, ...}. | |
| # Empty when the runner used the one-shot ``query()`` path with no client to poll. | |
| # This is the ground-truth infra-vs-model discriminator: a failure where the | |
| # expected tool is absent here is INFRA (server never registered); present-but- | |
| # unused is MODEL. | |
| mcp_servers: list[Any] = field(default_factory=list) | |
| def tool_names(self) -> list[str]: | |
| """Ordered list of tool names that were called.""" | |
| return [t.name for t in self.tool_traces] | |
| def mcp_server_status(self) -> dict[str, str]: | |
| """``{'controls': 'connected', 'python': 'connected', ...}`` from the | |
| captured ``get_mcp_status()`` snapshot. Empty if no snapshot was taken.""" | |
| return {s.get("name", "?"): s.get("status", "unknown") for s in self.mcp_servers} | |
| def registered_tools(self) -> list[str]: | |
| """Flattened ``mcp__<server>__<tool>`` names that the MCP handshake exposed. | |
| Built from the captured snapshot, so it reflects what the model could | |
| actually call — not what it chose to call (that is ``tool_names``).""" | |
| out: list[str] = [] | |
| for s in self.mcp_servers: | |
| server = s.get("name", "") | |
| for t in s.get("tools", []) or []: | |
| tname = t.get("name") if isinstance(t, dict) else t | |
| if tname: | |
| out.append(f"mcp__{server}__{tname}") | |
| return out | |
| def tool_was_registered(self, tool: str) -> bool | None: | |
| """Was *tool* (e.g. ``mcp__controls__channel_write``) exposed by the MCP | |
| handshake? ``None`` if no snapshot is available (cannot tell).""" | |
| if not self.mcp_servers: | |
| return None | |
| return tool in self.registered_tools | |
| def repeated_tool_calls(self) -> dict[str, int]: | |
| """``{'<tool>::<input-digest>': count}`` for any call issued more than | |
| once. A high count on a delegation tool is the fingerprint of a | |
| non-convergence loop.""" | |
| from collections import Counter | |
| keys = [ | |
| f"{t.name}::{json.dumps(t.input, sort_keys=True, default=str)}" | |
| for t in self.tool_traces | |
| ] | |
| return {k: n for k, n in Counter(keys).items() if n > 1} | |
| def has_redelegation_loop(self) -> bool: | |
| """True if a subagent-spawning tool (``Agent``/``Task*``) was re-issued | |
| with identical input 3+ times — model non-convergence (a MODEL timeout), | |
| distinct from slow-but-progressing proxy latency (INFRA). Lets a | |
| ``resource_timeout`` failure be bucketed from the recorded artifact | |
| instead of guessed.""" | |
| for key, n in self.repeated_tool_calls.items(): | |
| name = key.split("::", 1)[0] | |
| if n >= 3 and (name == "Agent" or name.startswith("Task")): | |
| return True | |
| return False | |
| def cost_usd(self) -> float | None: | |
| """Total cost from the ResultMessage.""" | |
| return self.result.total_cost_usd if self.result else None | |
| def num_turns(self) -> int | None: | |
| """Number of agentic turns from the ResultMessage.""" | |
| return self.result.num_turns if self.result else None | |
| def input_tokens(self) -> int: | |
| """Total input tokens (raw + cache creation + cache read).""" | |
| usage: dict[str, Any] | None = getattr(self.result, "usage", None) | |
| if not usage: | |
| return 0 | |
| return ( | |
| int(usage.get("input_tokens", 0)) | |
| + int(usage.get("cache_creation_input_tokens", 0)) | |
| + int(usage.get("cache_read_input_tokens", 0)) | |
| ) | |
| def output_tokens(self) -> int: | |
| """Total output tokens.""" | |
| usage: dict[str, Any] | None = getattr(self.result, "usage", None) | |
| if not usage: | |
| return 0 | |
| return int(usage.get("output_tokens", 0)) | |
| def cache_read_tokens(self) -> int: | |
| """Cache-read input tokens (charged at reduced rate).""" | |
| usage: dict[str, Any] | None = getattr(self.result, "usage", None) | |
| if not usage: | |
| return 0 | |
| return int(usage.get("cache_read_input_tokens", 0)) | |
| def cache_creation_tokens(self) -> int: | |
| """Cache-creation input tokens.""" | |
| usage: dict[str, Any] | None = getattr(self.result, "usage", None) | |
| if not usage: | |
| return 0 | |
| return int(usage.get("cache_creation_input_tokens", 0)) | |
| def tools_matching(self, substring: str) -> list[ToolTrace]: | |
| """Return all tool traces whose name contains *substring*.""" | |
| return [t for t in self.tool_traces if substring in t.name] | |
| # --------------------------------------------------------------------------- | |
| # Public primitives | |
| # --------------------------------------------------------------------------- | |
| def resolve_default_model(project_dir: Path) -> str: | |
| """Resolve the haiku-tier model name for the given project. | |
| Reads ``config.yml`` and returns the provider's haiku-tier model id, | |
| falling back to the upstream Anthropic default when no spec is | |
| configured. | |
| Args: | |
| project_dir: Path to an initialized OSPREY project. | |
| Returns: | |
| Model identifier string suitable for passing to the Claude Agent SDK | |
| ``model=`` argument. | |
| """ | |
| spec = _resolve_project_spec(project_dir) | |
| if spec is not None: | |
| return str(spec.tier_to_model.get("haiku", "claude-haiku-4-5-20251001")) | |
| return "claude-haiku-4-5-20251001" | |
| def sdk_env(project_dir: Path | None = None, *, provider: str | None = None) -> dict[str, str]: | |
| """Return env overrides for the SDK subprocess. | |
| Always sets ``CLAUDECODE=""`` to bypass the nested-session guard | |
| (JavaScript treats "" as falsy). When ``project_dir`` is provided, | |
| also injects the project's resolved provider env block so the bundled | |
| CLI talks to the configured provider (cborg, als-apg, anthropic-direct) | |
| instead of falling through to ``api.anthropic.com``. | |
| Also sets ``CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1`` so subagent | |
| delegation runs **synchronously** in the foreground. Since Claude Code CLI | |
| 2.1.x, when the agent launches parallel subagents the CLI auto-backgrounds | |
| them: the ``Agent`` tool returns ``"Async agent launched successfully"``, | |
| the turn ends, and the subagent results arrive later as a | |
| ``<task-notification>`` on a *new* turn. Our SDK drain | |
| (:func:`_drain_response`) stops at the first ``ResultMessage``, so it never | |
| sees that continuation — the agent would end at "I've launched the | |
| investigations" with none of the delegated results, silently under-running | |
| every benchmark and e2e that relies on delegation. Disabling background | |
| tasks makes the ``Agent`` tool block to completion and inject the subagent | |
| output back into the same turn (``status: "completed"``), matching what an | |
| interactive session ultimately converges to. The trade-off is that parallel | |
| delegations run sequentially rather than concurrently — a wall-clock cost we | |
| accept for deterministic, complete single-drain runs. | |
| Args: | |
| project_dir: Optional path to an initialized OSPREY project. When | |
| omitted only the ``CLAUDECODE`` bypass is returned. | |
| provider: When given, overrides ``claude_code.provider`` in the loaded | |
| config before resolving — used by cross-provider model sweeps in | |
| the benchmark runner. Has no effect when ``project_dir`` is | |
| ``None``. | |
| Returns: | |
| Env dict to merge into the SDK options ``env`` field. | |
| """ | |
| env: dict[str, str] = { | |
| "CLAUDECODE": "", | |
| "CLAUDE_CODE_DISABLE_BACKGROUND_TASKS": "1", | |
| } | |
| if project_dir is not None: | |
| env.update(provider_env_for_project(project_dir, provider=provider)) | |
| return env | |
| def combined_text(result: SDKWorkflowResult) -> str: | |
| """Combine all text blocks and tool results into a single searchable string. | |
| Args: | |
| result: A completed SDK workflow result. | |
| Returns: | |
| Lower-cased concatenation of all assistant text blocks and every | |
| non-empty tool-result string, joined by spaces. | |
| """ | |
| parts = list(result.text_blocks) | |
| for trace in result.tool_traces: | |
| if trace.result: | |
| parts.append(trace.result) | |
| return " ".join(parts).lower() | |
| def _ingest_tool_result(block: ToolResultBlock, pending_tools: dict[str, ToolTrace]) -> None: | |
| """Match a ToolResultBlock to its pending ToolTrace and populate result/is_error. | |
| ToolResultBlocks arrive in ``UserMessage.content`` (per Anthropic API | |
| contract: tool_use is assistant output, tool_result is user input back to | |
| the model). They may also appear in ``AssistantMessage`` when the SDK | |
| forwards them. | |
| Args: | |
| block: The tool result block to ingest. | |
| pending_tools: Map of tool_use_id to the ToolTrace awaiting its result. | |
| """ | |
| matched = pending_tools.get(block.tool_use_id) | |
| if matched is None: | |
| return | |
| if isinstance(block.content, str): | |
| matched.result = block.content | |
| elif isinstance(block.content, list): | |
| texts = [] | |
| for item in block.content: | |
| if isinstance(item, dict) and item.get("type") == "text": | |
| texts.append(item.get("text", "")) | |
| matched.result = "\n".join(texts) if texts else str(block.content) | |
| matched.is_error = bool(block.is_error) | |
| # --------------------------------------------------------------------------- | |
| # Shared SDK wiring: option building + response draining | |
| # --------------------------------------------------------------------------- | |
| # These back both the single-turn ``run_query`` and the multi-turn | |
| # ``agent_session`` so provider routing and stream parsing are identical across | |
| # entry points — there is one place to fix a routing bug or a message-type gap. | |
| def build_agent_options( | |
| project_dir: Path, | |
| *, | |
| disallowed_tools: list[str], | |
| max_turns: int = 25, | |
| max_budget_usd: float = 2.0, | |
| model: str | None = None, | |
| permission_mode: PermissionMode = "bypassPermissions", | |
| ) -> ClaudeAgentOptions: | |
| """Build ``ClaudeAgentOptions`` routed to a project's configured provider. | |
| Resolves the model and provider env, and — for non-native (OpenAI-protocol) | |
| providers — starts the in-process translation proxy and repoints | |
| ``ANTHROPIC_BASE_URL`` at it. The proxy upstream comes from | |
| ``spec.upstream_base_url`` (the OpenAI root *with* its ``/v1``), NOT from | |
| ``env["ANTHROPIC_BASE_URL"]`` which the resolver strips of ``/v1`` for Claude | |
| Code; sourcing the upstream from the env var would forward to a ``/v1``-less | |
| ``…/chat/completions`` (issue #312). | |
| Args: | |
| project_dir: Path to an initialized OSPREY project. | |
| disallowed_tools: Tool names forbidden at the SDK level (forwarded as | |
| ``--disallowedTools``; the architectural read-only guard). | |
| max_turns: Maximum agentic turns before the SDK stops a response. | |
| max_budget_usd: Budget ceiling passed to the SDK (literal, not scaled). | |
| model: Model id; when ``None``, resolved from the project's haiku tier. | |
| permission_mode: SDK permission mode. ``"bypassPermissions"`` for the | |
| read-only headless path; ``"default"`` when an approval callback | |
| should mediate tool use. | |
| Returns: | |
| Configured ``ClaudeAgentOptions`` ready to open a ``ClaudeSDKClient``. | |
| Raises: | |
| ImportError: When ``claude_agent_sdk`` is not installed. | |
| """ | |
| if not HAS_SDK: | |
| raise ImportError( | |
| "claude_agent_sdk is required to build agent options. " | |
| "Install it with: pip install claude-agent-sdk" | |
| ) | |
| resolved_model = model if model is not None else resolve_default_model(project_dir) | |
| env = sdk_env(project_dir) | |
| spec = _resolve_project_spec(project_dir) | |
| if spec and spec.needs_proxy and spec.upstream_base_url: | |
| auth_token = env.get(spec.auth_env_var) | |
| if not auth_token: | |
| # A missing token otherwise surfaces only as an opaque proxy 401 | |
| # mid-query; warn early naming the var and provider. | |
| logger.warning( | |
| "Auth token %s missing for provider '%s' — proxied requests may " | |
| "fail to authenticate (set the provider secret in the project .env)", | |
| spec.auth_env_var, | |
| spec.provider, | |
| ) | |
| port = start_proxy(spec.upstream_base_url, auth_token) | |
| env["ANTHROPIC_BASE_URL"] = f"http://127.0.0.1:{port}" | |
| return ClaudeAgentOptions( | |
| model=resolved_model, | |
| cwd=str(project_dir), | |
| permission_mode=permission_mode, | |
| max_turns=max_turns, | |
| max_budget_usd=max_budget_usd, | |
| env=env, | |
| setting_sources=["project"], | |
| disallowed_tools=disallowed_tools, | |
| ) | |
| async def _drain_response( | |
| client: ClaudeSDKClient, | |
| workflow: SDKWorkflowResult, | |
| ) -> None: | |
| """Consume one response stream from *client* into *workflow*. | |
| Iterates ``client.receive_response()`` (which terminates after the | |
| ResultMessage) and collects assistant text, tool-call traces, tool results | |
| (which arrive in a following ``UserMessage`` per the Anthropic contract, or | |
| embedded in an ``AssistantMessage`` when the SDK forwards them), system | |
| messages, and the final ResultMessage. | |
| Args: | |
| client: An open, connected ``ClaudeSDKClient`` with a query in flight. | |
| workflow: Result accumulator; a fresh instance collects one turn, a | |
| reused instance accumulates across turns. | |
| """ | |
| # ``tool_use_id`` → ``ToolTrace`` map for matching results to their calls; | |
| # purely local to this drain, reset for each response stream. | |
| pending_tools: dict[str, ToolTrace] = {} | |
| async for message in client.receive_response(): | |
| if isinstance(message, AssistantMessage): | |
| for block in message.content: | |
| if isinstance(block, TextBlock): | |
| workflow.text_blocks.append(block.text) | |
| elif isinstance(block, ToolUseBlock): | |
| trace = ToolTrace( | |
| name=block.name, | |
| input=block.input, | |
| tool_use_id=block.id, | |
| parent_tool_use_id=message.parent_tool_use_id, | |
| ) | |
| workflow.tool_traces.append(trace) | |
| pending_tools[block.id] = trace | |
| elif isinstance(block, ToolResultBlock): | |
| _ingest_tool_result(block, pending_tools) | |
| elif isinstance(message, UserMessage): | |
| if isinstance(message.content, list): | |
| for block in message.content: | |
| if isinstance(block, ToolResultBlock): | |
| _ingest_tool_result(block, pending_tools) | |
| elif isinstance(message, SystemMessage): | |
| workflow.system_messages.append(message) | |
| elif isinstance(message, ResultMessage): | |
| workflow.result = message | |
| # --------------------------------------------------------------------------- | |
| # MCP readiness barrier + instrumentation | |
| # --------------------------------------------------------------------------- | |
| # | |
| # OSPREY MCP servers register ASYNCHRONOUSLY: each stdio subprocess imports the | |
| # framework and primes its config before it can finish the MCP handshake, so a | |
| # declared server connects ~1.5–2s after the CLI launches on an idle machine — | |
| # and the nine servers of a full deployment come up one after another, CPU-bound, | |
| # so the last one lands several seconds later still. On a loaded host (a cold | |
| # two-CPU CI runner starting several sessions at once) that tail stretches past | |
| # a naive "give it a few seconds" wait. | |
| # | |
| # The CLI fixes a session's MCP toolset when the FIRST turn is sent and does not | |
| # revisit it: a server that connects later never contributes its tools to that | |
| # session (measured — a workspace server connecting 11s after the first turn | |
| # left the agent calling its tool by exact name and being told no such tool | |
| # exists, seven turns later). So a turn fired before the servers it needs are | |
| # connected does not merely start slow; it runs the whole session without those | |
| # tools, the agent improvises, and the run is scored as a model give-up when it | |
| # was a cold start. That cannot be told apart from a genuine model give-up from | |
| # the persisted transcript, which does not record MCP status. | |
| # | |
| # Both problems are solved with the SDK's own ``ClaudeSDKClient.get_mcp_status()``: | |
| # * READINESS — poll it until every expected server is terminal (``connected``, | |
| # or ``failed`` — a server the CLI has given up on will not connect later) | |
| # before sending the prompt, so every agent gets the toolset it can get (the | |
| # harness-enforced equivalent of the CLI's ``WaitForMcpServers`` tool, | |
| # independent of whether the model thinks to call it). | |
| # * INSTRUMENTATION — hand back the final snapshot so a missing tool is provably | |
| # INFRA (server never registered) vs MODEL (tool was there, agent ignored it). | |
| # The ceiling only ever costs a run on a host where a server is still pending — | |
| # the barrier returns the moment every expected server is terminal. It is sized | |
| # for a cold, oversubscribed CI runner, not for the idle-machine ~2s, because | |
| # starting early forfeits the late servers for the whole session (see above). | |
| # Callers that spawn the CLI should hand the same figure to the CLI's own | |
| # ``MCP_TIMEOUT`` (its stdio-startup limit, 30s by default), or the CLI marks a | |
| # slow server failed before this barrier would have seen it connect. | |
| MCP_READY_TIMEOUT_S = float(os.environ.get("OSPREY_E2E_MCP_READY_TIMEOUT", "90")) | |
| _MCP_READY_TIMEOUT_S = MCP_READY_TIMEOUT_S | |
| _MCP_READY_POLL_S = 0.3 | |
| # ``get_mcp_status()`` statuses that will not change without a reconnect. The | |
| # barrier stops waiting once every expected server reports one of these. | |
| _MCP_TERMINAL_STATUSES = frozenset({"connected", "failed"}) | |
| def expected_mcp_servers(project_dir: Path) -> set[str]: | |
| """The MCP server names a project declares in ``.mcp.json`` — the set the | |
| readiness barrier waits for. Returns an empty set if the file is unreadable.""" | |
| try: | |
| cfg = json.loads((project_dir / ".mcp.json").read_text(encoding="utf-8")) | |
| except (OSError, ValueError): | |
| return set() | |
| return set(cfg.get("mcpServers", {}).keys()) | |
| async def await_mcp_ready( | |
| client: ClaudeSDKClient, | |
| expected: set[str], | |
| *, | |
| timeout_s: float = _MCP_READY_TIMEOUT_S, | |
| poll_s: float = _MCP_READY_POLL_S, | |
| ) -> list[Any]: | |
| """Poll ``get_mcp_status()`` until every server in *expected* is terminal — | |
| ``connected`` or ``failed`` — or *timeout_s* elapses, then return the final | |
| snapshot. | |
| A ``failed`` server is one the CLI has given up on (spawn error, or its own | |
| startup limit — ``MCP_TIMEOUT`` — expired); it will not connect later, so | |
| waiting for it only delays the run. It stays in the snapshot with its | |
| ``error`` so the caller can name it. | |
| Resilient to ``get_mcp_status()`` raising early in startup (before the stream | |
| is live). Never raises: on timeout it returns the last snapshot seen so the | |
| caller can record a genuine registration failure rather than masking it. | |
| """ | |
| deadline = time.monotonic() + timeout_s | |
| servers: list[Any] = [] | |
| while True: | |
| try: | |
| status = await client.get_mcp_status() | |
| servers = status.get("mcpServers", []) if isinstance(status, dict) else (status or []) | |
| except Exception: # noqa: BLE001 — status not queryable yet; keep polling | |
| servers = servers or [] | |
| if expected: | |
| terminal = {s.get("name") for s in servers if s.get("status") in _MCP_TERMINAL_STATUSES} | |
| if expected <= terminal: | |
| return servers | |
| if time.monotonic() >= deadline: | |
| return servers | |
| await asyncio.sleep(poll_s) | |
| def mcp_servers_connected(servers: list[Any]) -> set[str]: | |
| """Names of the servers a ``get_mcp_status()`` snapshot reports ``connected``.""" | |
| return {s.get("name") for s in servers if s.get("status") == "connected"} | |
| def mcp_snapshot_summary(servers: list[Any]) -> list[dict[str, Any]]: | |
| """Compact, JSON-friendly form of a ``get_mcp_status()`` snapshot. | |
| One entry per server: ``name``, ``status``, the number of ``tools`` it | |
| registered, and its ``error`` (``None`` unless the CLI reported one). This | |
| is what a run record persists so a missing tool can be read off the record | |
| as INFRA (server not connected) or MODEL (tool registered, agent ignored it). | |
| """ | |
| summary = [] | |
| for s in servers: | |
| tools = s.get("tools") or [] | |
| summary.append( | |
| { | |
| "name": s.get("name"), | |
| "status": s.get("status"), | |
| "tools": len(tools) if isinstance(tools, list) else 0, | |
| "error": s.get("error"), | |
| } | |
| ) | |
| return summary | |
Xet Storage Details
- Size:
- 33.4 kB
- Xet hash:
- ff1a610fa63d1c50b2937da3027bcd7f087fee86214535095c75a49a66afa22c
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.