Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions changelog.d/1446.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
### Security
- pydantic-ai moves from 2.35.0 to 2.54.0, with pydantic-ai-slim, pydantic-evals and pydantic-graph; the resolver also moves anthropic to 1.12.1, openai to 3.26.1 and google-genai to 2.29.0. This fixes three advisories: GHSA-4x9p-g9wm-8q7f (tool and agent run spans put content in exception events even with `include_content=False`), GHSA-fpf4-vwcp-v4hp (quadratic title extraction in `web_fetch` blocked the event loop) and GHSA-vmxc-h2x2-jmf3 (an IPv6 zone identifier got past the SSRF cloud-metadata blocklist, which devops-cli's URL pre-flight checks and connect-time egress check also use). `uv audit` passes again, and with it `uv run devops ci` and the pre-push gate (#1446).

### Changed
- `LocalDurabilityCapability` is built on pydantic-ai's public durable engine API: an `engine_spec` and a backend that runs each operation in-process. Toolsets are not wrapped, and model requests go through pydantic-ai's durable model in the same process. An `event_stream_handler` must be async, as pydantic-ai's `EventStreamHandler` type requires. pydantic-ai now rejects a second durability capability on the same agent (#1446).
- A `PydanticAgent` tool that takes a context must annotate it with pydantic-ai's `RunContext`. A tool annotated with `devops_cli.ai.agents.context.RunContext` now fails schema generation, because the private pydantic-ai hook that accepted the subclass no longer exists. Use `isinstance` to narrow to the subclass when the tool reads `loaded_capability_ids` or `tool_call_approved` (#1446).
- `calculate_usage_cost` prices through `genai_prices.calc_price` and returns its `PriceCalculation`, or None when genai-prices cannot price the model or usage. `get_active_traceparent` reads the active span through OpenTelemetry's W3C trace-context propagator (#1446).

### Removed
- `devops_cli.ai`, `devops_cli.ai.agents`, `devops_cli.ai.agents.pydantic_agent`, `devops_cli.ai.result` and `devops_cli.ai.run` no longer re-export these pydantic-ai internals: `best_effort_price` (removed from pydantic-ai), `OutputSchema`, `OutputValidator`, `TextOutputSchema`, `run_image_process_hooks`, `run_output_with_hooks`, `SyncStreamBridge` and `current_otel_traceparent` (#1446).
57 changes: 57 additions & 0 deletions docs/agent/tasks/task-1446-pydantic-ai-advisories.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Task: Upgrade pydantic-ai to 2.54.0, past three advisories that fail the devops ci audit (#1446)

**Issue**: [#1446](https://github.com/dan-petty/devops-cli/issues/1446)
**Status**: Done
**Milestone**: v0.2.29
**Priority**: priority/p0-critical
**Scope**: type/security, scope/ai, scope/security

## Description

`pyproject.toml` pinned `pydantic-ai==2.35.0`. Three advisories against that version (GHSA-4x9p-g9wm-8q7f, GHSA-fpf4-vwcp-v4hp, GHSA-vmxc-h2x2-jmf3) made `uv audit` fail on every branch, and with it `uv run devops ci` and the pre-push gate. The pin is now `pydantic-ai==2.54.0`, the latest 2.x release. `uv lock --upgrade-package` moved pydantic-ai, pydantic-ai-slim, pydantic-evals and pydantic-graph to 2.54.0. The resolver also requires anthropic 1.5.0 → 1.12.1, openai 3.13.0 → 3.26.1 and google-genai 2.23.0 → 2.29.0. No other package in the lock changes.

devops-cli imported private pydantic-ai modules, and 2.54.0 removed or changed some of them. Each private import, and what replaced it:

| Private import (2.35.0) | In 2.54.0 | Replacement |
| :--- | :--- | :--- |
| `pydantic_ai._cost.best_effort_price` (`ai/result`) | module removed | `genai_prices.calc_price`, a direct dependency already used by `ai/spend/pricing.py`. `calculate_usage_cost` returns its `PriceCalculation`, or None on `LookupError`/`ValueError`, the two errors pydantic-ai treats as "cannot price". |
| `pydantic_ai._output` (`OutputSchema`, `OutputValidator`, `TextOutputSchema`, `run_image_process_hooks`, `run_output_with_hooks`) and `pydantic_ai._sync_stream.SyncStreamBridge` (`ai/result`) | still present | Removed. Nothing in devops-cli used them; they were only re-exported from `ai`, `ai.agents`, `ai.agents.pydantic_agent` and `ai.result`. |
| `pydantic_ai._function_schema._is_call_ctx`, monkey-patched in `ai/agents/context.py` so tool schemas accepted the devops `RunContext` subclass | renamed `is_call_ctx`; the patch's `getattr` guard made it a silent no-op | Patch removed. pydantic-ai recognises only its own `RunContext` as a context annotation. `PydanticAgent`'s `load_capability` tool annotates its context with it and narrows to the devops subclass with `isinstance`, as `harness/workflow.py`'s `delegate_task` already did. |
| `pydantic_ai.durable_exec._base.BaseDurabilityCapability` and `pydantic_ai.durable_exec._runtime_toolsets.RuntimeToolsetKind` (`ai/durable.py`, `tests/test_pydantic_ai_durable.py`) | `BaseDurabilityCapability` is public in `pydantic_ai.durable_exec` and has become pydantic-ai's durable engine builder, with an abstract `get_durable_operation_backend` | `LocalDurabilityCapability` follows pydantic-ai's durable backend guide. An `engine_spec` (`DurabilityEngineSpec`: engine Local, unit step, container run, `wrapped_toolset_kinds=frozenset()`) replaces the private ClassVars. `get_durable_operation_backend` returns `_LocalOperationBackend`, a `JournalCallableOperationBackend` whose `execute` awaits the body in place. The overrides of the private `_bind_to_agent`, `_wrap_leaf_toolset` and `_dispatch_event_stream_event` are gone, because the base now owns them and the empty `wrapped_toolset_kinds` keeps toolsets unwrapped. `before_model_request` delegates to the base's, which validates the request. |
| `pydantic_ai._enqueue` (`EnqueueContent`, `PendingMessage`, `PendingMessagePriority`) (`ai/run`) | still present | Imported from `pydantic_ai.run`, where pydantic-ai documents them. That module has no `__all__`, so a `[[tool.mypy.overrides]]` entry sets `implicit_reexport` for `pydantic_ai.run` alone. mypy still reports a name the module lacks. |
| `pydantic_ai._instrumentation.current_otel_traceparent` (`ai/run`) | still present, undocumented | `get_active_traceparent` reads the active span through OpenTelemetry's `TraceContextTextMapPropagator`, and the re-export is removed. |

`ai/tools`' `DeferredToolRequests.build_results` override now takes `approvals` as a `Mapping`, because pydantic-ai widened the parameter.

**What remains private, for #1001 to retire:**
- `pydantic_ai._ssrf` in `core/validation.py` (`_PRIVATE_NETWORKS`, `is_cloud_metadata_ip`, `is_private_ip`) and `http/egress.py` (`is_cloud_metadata_ip`). pydantic-ai exposes no public SSRF classifier; only its `web_fetch` tool and model downloads use this module. Replacing it would mean choosing another SSRF library or hand-rolling the classification, which is a redesign. The shared classifier is also what keeps the URL pre-flight checks and the connect-time egress check in agreement. The 2.54.0 module contains the GHSA-vmxc-h2x2-jmf3 fix, so both checks get it. `tests/test_validation.py`'s contract test guards the names.
- `LocalDurabilityCapability.resolve_model_id_sync` reads the base's private `_models_by_id`. pydantic-ai's public equivalent is the async `resolve_model_id`.
- `CONST_OPENAI_FINISH_REASONS` and `CONST_ANTHROPIC_STOP_REASONS` in `config/constants.py` are copies of pydantic-ai's private finish-reason maps, not imports. The maps are identical in 2.54.0, and the comment now names that version.

**Behaviour that changed with the library:**
- `LocalDurabilityCapability` now passes its event stream handler to pydantic-ai, whose `EventStreamHandler` type requires an async handler. The old private override also accepted a sync handler; that support is gone.
- pydantic-ai refuses a second durability capability on one agent (`UserError`).
- A tool whose context is annotated with the devops `RunContext` subclass fails pydantic-ai's schema generation.
- The devops `RunContext` subclass and the in-house `PydanticAgent` loop that builds it are #1001's to retire.

## Acceptance Criteria

- [x] `uv audit` reports no pydantic-ai advisory, and `uv run devops ci` passes.
- [x] `pyproject.toml` and `uv.lock` agree. The lock changes only the four pydantic-ai packages and the anthropic, openai and google-genai versions the resolver requires.
- [x] `changelog.d/1446.md` records the upgrade under `### Security`, with the API changes under `### Changed` and `### Removed`. `CHANGELOG.md` and `docs/ROADMAP.md` are untouched.
- [x] The only private pydantic-ai imports left in `src` are the two `pydantic_ai._ssrf` imports listed above. There are no version checks, `ImportError` fallbacks or copied internals.
- [x] Tests change only where the API changed:
- `tests/test_pydantic_ai_durable.py` imports `BaseDurabilityCapability` from `pydantic_ai.durable_exec`.
- `test_local_durability_delivers_run_events_and_leaves_toolsets_unwrapped` replaces the test that called the private `_dispatch_event_stream_event` and `_wrap_leaf_toolset`. It runs an agent on `TestModel` and checks that the async handler receives the tool call and result events, that `get_wrapper_toolset` leaves every toolset unwrapped, and that the steps are recorded.
- The extended-options test uses `StepPersistence` as its extra capability, since a second engine is refused.
- Three test tools annotate their context with pydantic-ai's `RunContext`.
- The result and run tests drop the removed names, and `test_get_active_traceparent` pins the traceparent of a known span context and None outside a span.
- No test reaches the network, and each one finishes in under 1 s.
- [x] The knowledge base pages that named 2.35.0 (`libraries/pydantic_ai.md`, `python_packages.md`) name 2.54.0, and `uv run devops docs generate --sync-readme` leaves the generated docs unchanged.

## Deliverables

- [x] Pin and lock: `pyproject.toml`, `uv.lock`.
- [x] Code: `ai/result`, `ai/run`, `ai/durable.py`, `ai/agents/context.py`, `ai/agents/agent.py`, `ai/tools`, and the export maps in `ai/__init__.py`, `ai/agents/__init__.py` and `ai/agents/pydantic_agent.py`.
- [x] mypy override for `pydantic_ai.run` in `pyproject.toml`.
- [x] Tests, knowledge base pages, the `config/constants.py` comment, `changelog.d/1446.md`.
9 changes: 8 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ dependencies = [
"fastapi==0.142.2",
"uvicorn==0.53.0",
"tiktoken==0.14.0",
"pydantic-ai==2.35.0",
"pydantic-ai==2.54.0",
"dnspython==2.8.0",
"genai-prices==0.1.9",
"opentelemetry-exporter-otlp-proto-grpc==1.44.0",
Expand Down Expand Up @@ -121,6 +121,13 @@ strict = true
plugins = ['pydantic.mypy']
enable_error_code = ["ignore-without-code"]

# pydantic-ai documents EnqueueContent, PendingMessage and PendingMessagePriority as members of
# pydantic_ai.run (https://pydantic.dev/docs/ai/api/run/), but the module has no __all__, so
# strict mode would not count them as exported.
[[tool.mypy.overrides]]
module = "pydantic_ai.run"
implicit_reexport = true

[tool.pytest.ini_options]
asyncio_mode = "auto"
testpaths = ["tests"]
Expand Down
16 changes: 0 additions & 16 deletions src/devops_cli/ai/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -284,19 +284,12 @@ def __getattr__(name: str) -> Any: # noqa: C901
"AgentStream",
"AgentStreamEvent",
"FinalResult",
"OutputSchema",
"OutputValidator",
"OutputValidatorFunc",
"RunUsage",
"StreamedRunResult",
"StreamedRunResultSync",
"SyncStreamBridge",
"TextOutputSchema",
"best_effort_price",
"calculate_usage_cost",
"create_run_usage",
"run_image_process_hooks",
"run_output_with_hooks",
"to_agent_response",
"to_final_result",
}:
Expand Down Expand Up @@ -338,7 +331,6 @@ def __getattr__(name: str) -> Any: # noqa: C901
"PendingMessage",
"PendingMessagePriority",
"create_pending_message",
"current_otel_traceparent",
"format_run_summary",
"get_active_traceparent",
}:
Expand Down Expand Up @@ -845,10 +837,8 @@ def __getattr__(name: str) -> Any: # noqa: C901
"OutputDataT",
"OutputMode",
"OutputObjectDefinition",
"OutputSchema",
"OutputSpec",
"OutputTypeOrFunction",
"OutputValidator",
"OutputValidatorFunc",
"OverflowStore",
"PackedContext",
Expand Down Expand Up @@ -919,14 +909,12 @@ def __getattr__(name: str) -> Any: # noqa: C901
"Summarize",
"SummarizingCompaction",
"SuspendedResponseExpired",
"SyncStreamBridge",
"TavilySearchResult",
"TavilySearchTool",
"TemplateStr",
"TenacityTransport",
"TextOutput",
"TextOutputFunc",
"TextOutputSchema",
"ThinkingEffort",
"ThinkingLevel",
"ThinkingStreamProcessor",
Expand Down Expand Up @@ -978,7 +966,6 @@ def __getattr__(name: str) -> Any: # noqa: C901
"amazon_model_profile",
"anthropic_model_profile",
"approve_all_requests",
"best_effort_price",
"build_output_spec",
"bundle_ollama_models",
"calculate_usage_cost",
Expand All @@ -1004,7 +991,6 @@ def __getattr__(name: str) -> Any: # noqa: C901
"create_tool",
"create_tool_definition",
"create_tool_or_output",
"current_otel_traceparent",
"deepseek_model_profile",
"defer_loading_toolset",
"deny_all_requests",
Expand Down Expand Up @@ -1121,8 +1107,6 @@ def __getattr__(name: str) -> Any: # noqa: C901
"resolve_model_profile",
"resolve_output_mode",
"resolve_runtime_model_settings",
"run_image_process_hooks",
"run_output_with_hooks",
"scaffold_agent_instructions",
"signature_from_callable",
"signature_from_schema",
Expand Down
16 changes: 0 additions & 16 deletions src/devops_cli/ai/agents/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -454,19 +454,12 @@ def __getattr__(name: str) -> Any: # noqa: C901
if name in {
"AgentStream",
"FinalResult",
"OutputSchema",
"OutputValidator",
"OutputValidatorFunc",
"RunUsage",
"StreamedRunResult",
"StreamedRunResultSync",
"SyncStreamBridge",
"TextOutputSchema",
"best_effort_price",
"calculate_usage_cost",
"create_run_usage",
"run_image_process_hooks",
"run_output_with_hooks",
"to_agent_response",
"to_final_result",
}:
Expand Down Expand Up @@ -507,7 +500,6 @@ def __getattr__(name: str) -> Any: # noqa: C901
"PendingMessage",
"PendingMessagePriority",
"create_pending_message",
"current_otel_traceparent",
"format_run_summary",
"get_active_traceparent",
}:
Expand Down Expand Up @@ -879,10 +871,8 @@ def __getattr__(name: str) -> Any: # noqa: C901
"OutputGuardrail",
"OutputMode",
"OutputObjectDefinition",
"OutputSchema",
"OutputSpec",
"OutputTypeOrFunction",
"OutputValidator",
"OutputValidatorFunc",
"OverflowStore",
"ParallelExecutionMode",
Expand Down Expand Up @@ -969,7 +959,6 @@ def __getattr__(name: str) -> Any: # noqa: C901
"Summarize",
"SummarizingCompaction",
"SuspendedResponseExpired",
"SyncStreamBridge",
"SystemReminders",
"TavilySearchResult",
"TavilySearchTool",
Expand All @@ -979,7 +968,6 @@ def __getattr__(name: str) -> Any: # noqa: C901
"TestModel",
"TextOutput",
"TextOutputFunc",
"TextOutputSchema",
"Thinking",
"ThinkingEffort",
"ThinkingLevel",
Expand Down Expand Up @@ -1050,7 +1038,6 @@ def __getattr__(name: str) -> Any: # noqa: C901
"anthropic_model_profile",
"approval_required",
"approve_all_requests",
"best_effort_price",
"build_output_spec",
"calculate_usage_cost",
"capture_run_messages",
Expand All @@ -1076,7 +1063,6 @@ def __getattr__(name: str) -> Any: # noqa: C901
"create_tool",
"create_tool_definition",
"create_tool_or_output",
"current_otel_traceparent",
"deepseek_model_profile",
"defer_loading_toolset",
"deferred_loading",
Expand Down Expand Up @@ -1184,8 +1170,6 @@ def __getattr__(name: str) -> Any: # noqa: C901
"resolve_output_mode",
"resolve_runtime_model_settings",
"restore_media",
"run_image_process_hooks",
"run_output_with_hooks",
"signature_from_callable",
"signature_from_schema",
"signature_from_tool",
Expand Down
9 changes: 6 additions & 3 deletions src/devops_cli/ai/agents/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from devops_cli.ai.concurrency import AbstractConcurrencyLimiter, AnyConcurrencyLimit
from devops_cli.ai.function_signature import FunctionSignature

from pydantic_ai.tools import RunContext as NativeRunContext
from pydantic_ai.toolsets import AbstractToolset as PyAIAbstractToolset

from devops_cli.ai.agents.capabilities import (
Expand Down Expand Up @@ -336,15 +337,17 @@ def __init__( # noqa: C901
self._register_load_capability_tool()

def _register_load_capability_tool(self) -> None:
def load_capability(ctx: RunContext[Any], capability_id: str) -> str:
def load_capability(ctx: NativeRunContext[Any], capability_id: str) -> str:
"""Load an on-demand capability by ID, unlocking its tools, instructions, and hooks."""
matching = next(
(c for c in self.capabilities if c.id == capability_id and c.defer_loading), None
)
if not matching:
avail = [c.id for c in self.capabilities if c.defer_loading]
return f"Capability '{capability_id}' not found. Available on-demand: {avail}"
ctx.loaded_capability_ids.add(capability_id)
run_ctx = ctx if isinstance(ctx, RunContext) else None
if run_ctx is not None:
run_ctx.loaded_capability_ids.add(capability_id)
for t in matching.get_tools():
self.add_tool(t)
cap_hooks = matching.get_hooks()
Expand All @@ -354,7 +357,7 @@ def load_capability(ctx: RunContext[Any], capability_id: str) -> str:
self.hooks.before_tool_execute.extend(cap_hooks.before_tool_execute)
self.hooks.after_tool_execute.extend(cap_hooks.after_tool_execute)
self.hooks.on_tool_error.extend(cap_hooks.on_tool_error)
additions = matching.get_system_prompt_additions(ctx=ctx)
additions = matching.get_system_prompt_additions(ctx=run_ctx)
inst = (" " + " ".join(additions)) if additions else ""
return f"Capability '{capability_id}' loaded successfully.{inst}"

Expand Down
25 changes: 0 additions & 25 deletions src/devops_cli/ai/agents/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from collections.abc import Callable
from typing import Any, TypeVar, cast

import pydantic_ai._function_schema as _pydantic_fs
from pydantic import BaseModel, Field
from pydantic_ai.tools import RunContext as NativeRunContext

Expand Down Expand Up @@ -89,30 +88,6 @@ def model_copy(
return copied


# Guarded, idempotent compatibility registration for RunContext subclasses in pydantic_ai
_orig_fs_is_call_ctx = getattr(_pydantic_fs, "_is_call_ctx", None)

if _orig_fs_is_call_ctx is not None and not getattr(
_orig_fs_is_call_ctx, "_is_subclass_aware", False
):

def _subclass_aware_is_call_ctx(annotation: Any) -> bool:
if _orig_fs_is_call_ctx is not None:
try:
if _orig_fs_is_call_ctx(annotation):
return True
except Exception:
pass
origin = getattr(annotation, "__origin__", None) or annotation
try:
return isinstance(origin, type) and issubclass(origin, NativeRunContext)
except TypeError:
return False

_subclass_aware_is_call_ctx._is_subclass_aware = True # type: ignore[attr-defined]
_pydantic_fs._is_call_ctx = _subclass_aware_is_call_ctx


class AgentStepNode(BaseModel):
"""Represents a discrete step or node in the agent execution graph."""

Expand Down
Loading
Loading