From 96d71ec32119513e7c7c514cbca094c937c67608 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 06:59:50 -0500 Subject: [PATCH 01/10] feat(runtime): governed agent core re-engineered from Microsoft Agent Framework (Phase 1) Add osiris_cli.runtime: typed messages, chat clients (wrapping the existing providers, plus Anthropic), tools with JSON schemas from type hints, agent / chat / function middleware pipelines, sessions with a hash-chained file history, and per-run spans with optional OpenTelemetry export. Every agent runs inside a governance stack built from existing OSIRIS code: task_context run records in $OSIRIS_HOME/tasks/task_runs.jsonl and budgets, intent_router risk tiers (CRITICAL blocked, HIGH needs a grant), the evidence firewall, governance_scope, the SYS-025 AST firewall, workspace confinement, the AGENTS.md credential-name rule, approvals, and exec_policy/exec_kernel for commands. Governance can be omitted only when osiris_cli/policy/ runtime_policy.json says governance_required is false. Adapted from microsoft/agent-framework@567e4d458b59b83ac9b19088a43a2853094c6df1 (MIT). Per-file headers, THIRD_PARTY_NOTICES.md, the license text shipped in the wheel, and osiris_cli/runtime/PORT_MAP.md record what was taken and changed. task_context.KINDS gains "agent" so runtime runs are recorded as their own kind. Full suite, Python 3.12: main 5efbc72 = 1 failed / 3518 passed / 136 skipped; this branch = 1 failed / 3614 passed / 137 skipped (same pre-existing failure, test_bt2t003_deterministic_regeneration_and_sha256sums). Runtime and task_context tests also pass on Python 3.9 and 3.10. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FYXiwQpjjWVfi7MNQgjVHJ --- THIRD_PARTY_NOTICES.md | 41 ++ osiris_cli/policy/runtime_policy.json | 19 + .../runtime/LICENSE-agent-framework.txt | 24 + osiris_cli/runtime/PORT_MAP.md | 57 ++ osiris_cli/runtime/__init__.py | 84 +++ osiris_cli/runtime/_agents.py | 280 ++++++++++ osiris_cli/runtime/_clients.py | 284 ++++++++++ osiris_cli/runtime/_governance.py | 496 ++++++++++++++++++ osiris_cli/runtime/_middleware.py | 242 +++++++++ osiris_cli/runtime/_sessions.py | 157 ++++++ osiris_cli/runtime/_telemetry.py | 186 +++++++ osiris_cli/runtime/_tools.py | 285 ++++++++++ osiris_cli/runtime/_types.py | 342 ++++++++++++ osiris_cli/runtime/demo.py | 102 ++++ osiris_cli/runtime/testing.py | 58 ++ osiris_cli/task_context.py | 2 +- pyproject.toml | 2 +- tests/runtime_support.py | 33 ++ tests/test_runtime_agent.py | 225 ++++++++ tests/test_runtime_clients.py | 201 +++++++ tests/test_runtime_governance.py | 318 +++++++++++ tests/test_runtime_middleware.py | 164 ++++++ tests/test_runtime_sessions_telemetry.py | 130 +++++ tests/test_runtime_tools.py | 151 ++++++ 24 files changed, 3881 insertions(+), 2 deletions(-) create mode 100644 THIRD_PARTY_NOTICES.md create mode 100644 osiris_cli/policy/runtime_policy.json create mode 100644 osiris_cli/runtime/LICENSE-agent-framework.txt create mode 100644 osiris_cli/runtime/PORT_MAP.md create mode 100644 osiris_cli/runtime/__init__.py create mode 100644 osiris_cli/runtime/_agents.py create mode 100644 osiris_cli/runtime/_clients.py create mode 100644 osiris_cli/runtime/_governance.py create mode 100644 osiris_cli/runtime/_middleware.py create mode 100644 osiris_cli/runtime/_sessions.py create mode 100644 osiris_cli/runtime/_telemetry.py create mode 100644 osiris_cli/runtime/_tools.py create mode 100644 osiris_cli/runtime/_types.py create mode 100644 osiris_cli/runtime/demo.py create mode 100644 osiris_cli/runtime/testing.py create mode 100644 tests/runtime_support.py create mode 100644 tests/test_runtime_agent.py create mode 100644 tests/test_runtime_clients.py create mode 100644 tests/test_runtime_governance.py create mode 100644 tests/test_runtime_middleware.py create mode 100644 tests/test_runtime_sessions_telemetry.py create mode 100644 tests/test_runtime_tools.py diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md new file mode 100644 index 00000000..69948c63 --- /dev/null +++ b/THIRD_PARTY_NOTICES.md @@ -0,0 +1,41 @@ +# Third-party notices + +osiris-cli is licensed under the OSIRIS Source-Available Dual License (see `LICENSE`). The +components below include material from third parties under their own licenses. Those licenses +continue to apply to that material. + +## Microsoft Agent Framework + +- Source: https://github.com/microsoft/agent-framework +- Commit: `567e4d458b59b83ac9b19088a43a2853094c6df1` (2026-12-04) +- Used in: `osiris_cli/runtime/` (files whose header says "Portions adapted from + microsoft/agent-framework"). `osiris_cli/runtime/PORT_MAP.md` lists each file, the source file + it adapts, and what changed. +- License: MIT + +``` +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE +``` + +"Microsoft" and "Agent Framework" are used here only to identify the source of the adapted +material. osiris-cli is not affiliated with or endorsed by Microsoft. diff --git a/osiris_cli/policy/runtime_policy.json b/osiris_cli/policy/runtime_policy.json new file mode 100644 index 00000000..de8e6ae6 --- /dev/null +++ b/osiris_cli/policy/runtime_policy.json @@ -0,0 +1,19 @@ +{ + "schema": "osiris.runtime-policy.v1", + "governance_required": true, + "blocked_risk_tiers": ["CRITICAL"], + "grant_required_risk_tiers": ["HIGH"], + "credential_name_patterns": [ + ".env", + ".env.*", + "apikey.json", + "*credentials*", + "*secret*", + "*token*", + "id_rsa*", + "id_ed25519*", + "*.pem", + "*.key", + ".netrc" + ] +} diff --git a/osiris_cli/runtime/LICENSE-agent-framework.txt b/osiris_cli/runtime/LICENSE-agent-framework.txt new file mode 100644 index 00000000..3a251e08 --- /dev/null +++ b/osiris_cli/runtime/LICENSE-agent-framework.txt @@ -0,0 +1,24 @@ +Portions of osiris_cli/runtime are adapted from microsoft/agent-framework +(commit 567e4d458b59b83ac9b19088a43a2853094c6df1), used under the following license. + +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/osiris_cli/runtime/PORT_MAP.md b/osiris_cli/runtime/PORT_MAP.md new file mode 100644 index 00000000..54137666 --- /dev/null +++ b/osiris_cli/runtime/PORT_MAP.md @@ -0,0 +1,57 @@ +# osiris_cli.runtime port map + +Phase 1 of re-engineering Microsoft Agent Framework (MAF) into osiris-cli. + +- **Source:** `microsoft/agent-framework` at `567e4d458b59b83ac9b19088a43a2853094c6df1` (2026-12-04), MIT. License text: `THIRD_PARTY_NOTICES.md` in the repo and `LICENSE-agent-framework.txt` in this package (shipped in the wheel). +- **Method:** each MAF module was read, then rebuilt here as a smaller module that keeps its design and semantics. This is a re-implementation guided by the source, not a line-for-line copy. Files that adapt MAF code carry a header naming the source file. +- **Size:** MAF's Python core is about 86,000 lines. This runtime is about 2,400 lines of code and 1,400 lines of tests. + +## Files + +| OSIRIS file | MAF source (python/packages/…) | What was taken | What changed | +|---|---|---|---| +| `_types.py` | `core/agent_framework/_types.py` | Message, Content, UsageDetails, ChatResponse, AgentResponse and their streaming updates | Five content kinds only (text, function call, function result, error, usage). Plain dataclasses with canonical JSON and SHA-256 helpers for ledger digests. No multimodal, annotation, hosted-tool or continuation types. | +| `_middleware.py` | `core/agent_framework/_middleware.py` | Agent, function and chat contexts; three base classes; `MiddlewareTermination`; `MiddlewareFailure`; decorator helpers; index-based pipeline execution | Unrecognized middleware raises `TypeError` (MAF logs and skips it, which would fail open). Every context carries a `RunState` shared by the run's three pipelines. No stream hooks or result gates. | +| `_tools.py` | `core/agent_framework/_tools.py` | `FunctionTool`, `@tool`, `approval_mode`, schema-checked arguments, `FunctionInvocationConfiguration` (here `InvocationConfig`) | Schema from type hints without pydantic, checked by `providers.schema_guard` and offered through `providers.tool_shim`. Adds the `effects`, `path_params`, `write_params` and `code_params` declarations that governance enforces. | +| `_clients.py` | `core/agent_framework/_clients.py`, `anthropic/` | Chat-client protocol (complete and streamed response); Anthropic message and tool-use mapping | `ProviderChatClient` wraps the existing `osiris_cli.providers` instead of replacing them. Malformed tool calls fail closed. The Anthropic client needs an explicit model id and never reads a key itself. | +| `_agents.py` | `core/agent_framework/_agents.py`, `_tools.py` | `Agent.run` / `run_stream` around three pipelines; the function-invocation loop and its limits; error wording; settling a batch when the loop stops | Tool calls run sequentially. Approvals are decided in the run by a handler (no stored approvals to replay). `run_stream` is buffered until governance passes the run. Arguments are validated before middleware sees a call. | +| `_sessions.py` | `core/agent_framework/_sessions.py` | `AgentSession`, `HistoryProvider`, `ContextProvider` | `FileHistoryProvider` writes hash-chained JSONL and refuses an edited history. It is opt-in, in a directory the caller names; it holds conversation state, never run provenance. | +| `_telemetry.py` | `core/agent_framework/observability.py` | OpenTelemetry GenAI attribute names; one span per agent run, model call and tool call | Spans are always recorded in-process; OpenTelemetry is used only when installed. The span summary (with a timing-free SHA-256) goes into the task ledger's `task_close`. | +| `_governance.py` | — (OSIRIS only) | — | Binds the hooks to existing OSIRIS governance: `task_context` (ledger, budget), `intent_router` (risk tier), `evidence_firewall`, `governance_scope`, `ast_firewall` (SYS-025), `exec_policy` + `exec_kernel`. | +| `testing.py`, `demo.py` | — (OSIRIS only) | — | Scripted chat client; end-to-end demo with an Ollama preflight before any ledger write. | + +Tests: `tests/test_runtime_{middleware,tools,agent,clients,governance,sessions_telemetry}.py`. The cases mirrored from MAF's `core/tests` name the source test file in their module docstring. + +## Governance order (outermost first) + +- **Agent:** RunRecord → Telemetry → IntentGate → EvidenceFirewall → *caller's agent middleware* → core loop +- **Chat:** Telemetry → Budget → Provenance → *caller's chat middleware* → client +- **Function:** Telemetry → *caller's function middleware* → ToolPolicy → tool + +ToolPolicy is innermost, so it checks the arguments that will actually run. The stack can be left out only when `osiris_cli/policy/runtime_policy.json` says `"governance_required": false`. That file sits in a governance-protected directory. + +## Not ported in Phase 1 + +| MAF area | Why not now | +|---|---| +| Workflows (`_workflows/`, about 12k lines) and `orchestrations` | Phase 2 | +| MCP client and server (`_mcp.py`, `hosting-mcp`) | Phase 3 | +| Compaction strategies (`_compaction.py`) | Phase 3 (`osiris.runtime.context` has a bounded broker already) | +| Information-flow security labels (`security.py`) | Phase 4 | +| Harness: tool-approval rules, judge loop, todo, background agents, file access, memory | Phase 3 | +| Evaluation (`_evaluation.py`) | Phase 3, writing into the claims register | +| Skills (`_skills.py`) | osiris-cli has `skills_runtime.py`; compare before porting anything | +| A2A, AG-UI, Responses hosting, DevUI, declarative YAML | Phase 4 (`.dna` to declarative specs) | +| Vector stores and memory backends | Later | +| Azure, Foundry, Purview, Copilot Studio, Bedrock, the other vendor packages; .NET; Go | Out of scope | +| Concurrent tool calls, unbuffered streaming, stored-approval replay, hosted tools, multimodal content | Deliberately left out (see deviations above) | + +## Relation to `osiris.runtime` + +osiris-cli also has `osiris/runtime/`, about 1,500 lines of opt-in primitives: contracts, a policy decision, a SQLite session store, a scheduler, workspace tools, an isolation backend, and an MCP registration registry. It has no model-client layer, middleware or agent loop, and its only user outside tests is `osiris_launcher.py` (capability status). + +This package does not import or change it. The two overlap on policy hooks, traces, context compaction and session storage. Before merge, decide whether to keep both, rename this package, or fold `osiris.runtime`'s primitives into these hooks in Phase 2. + +## Change outside the package + +`osiris_cli/task_context.py`: `KINDS` gains `"agent"` so runtime runs are recorded under their own kind instead of being mislabelled `code`. `new_context` still floors the cost class at `workspace_write` and the tier at `MEDIUM` for every kind. That is conservative for read-only agents, and the ledger reason text reads "a agent task proposes local changes" even when it doesn't. diff --git a/osiris_cli/runtime/__init__.py b/osiris_cli/runtime/__init__.py new file mode 100644 index 00000000..5b91874c --- /dev/null +++ b/osiris_cli/runtime/__init__.py @@ -0,0 +1,84 @@ +"""OSIRIS runtime: governed agents, tools, middleware, sessions and telemetry. + +Re-engineered from Microsoft Agent Framework (MIT; see THIRD_PARTY_NOTICES.md and PORT_MAP.md) with +OSIRIS's governance built in: every agent runs inside the governance stack in ``_governance``, its +runs are recorded in the canonical task ledger, and its tool calls are checked by the existing +exec policy, governance scope and SYS-025 AST firewall. + +Quick start:: + + from osiris_cli.runtime import Agent, GovernanceConfig, ProviderChatClient, tool + from osiris_cli.providers.ollama_compat import OllamaCompatibilityProvider + + @tool(effects=("read",), path_params=("path",)) + def count_lines(path: str) -> int: + '''Count the lines in a workspace file.''' + with open(path, encoding="utf-8") as f: + return sum(1 for _ in f) + + agent = Agent(ProviderChatClient(OllamaCompatibilityProvider(model="qwen2.5-coder:7b")), + tools=[count_lines], governance=GovernanceConfig(workspace_root=".")) + print(agent.run_sync("How many lines are in README.md?").text) +""" + +from ._agents import Agent +from ._clients import AnthropicChatClient, ChatClient, ChatClientError, ProviderChatClient +from ._governance import ( + ApprovalRequest, + GovernanceConfig, + GovernancePolicyError, + GovernanceRequiredError, + GovernanceStack, + PolicyRefusal, + load_runtime_policy, + make_exec_tool, +) +from ._middleware import ( + AgentContext, + AgentMiddleware, + ChatContext, + ChatMiddleware, + FunctionInvocationContext, + FunctionMiddleware, + MiddlewareFailure, + MiddlewareTermination, + RunState, + agent_middleware, + chat_middleware, + function_middleware, +) +from ._sessions import ( + AgentSession, + ContextAdditions, + ContextProvider, + FileHistoryProvider, + HistoryIntegrityError, + HistoryProvider, + InMemoryHistoryProvider, +) +from ._telemetry import SpanRecorder +from ._tools import FunctionTool, InvocationConfig, ToolArgumentError, ToolError, tool +from ._types import ( + AgentResponse, + AgentResponseUpdate, + ChatResponse, + ChatResponseUpdate, + Content, + Message, + UsageDetails, +) + +SOURCE_FRAMEWORK = "microsoft/agent-framework" +SOURCE_COMMIT = "567e4d458b59b83ac9b19088a43a2853094c6df1" + +__all__ = [ + "Agent", "AgentContext", "AgentMiddleware", "AgentResponse", "AgentResponseUpdate", "AgentSession", + "AnthropicChatClient", "ApprovalRequest", "ChatClient", "ChatClientError", "ChatContext", "ChatMiddleware", + "ChatResponse", "ChatResponseUpdate", "Content", "ContextAdditions", "ContextProvider", "FileHistoryProvider", + "FunctionInvocationContext", "FunctionMiddleware", "FunctionTool", "GovernanceConfig", "GovernancePolicyError", + "GovernanceRequiredError", "GovernanceStack", "HistoryIntegrityError", "HistoryProvider", + "InMemoryHistoryProvider", "InvocationConfig", "Message", "MiddlewareFailure", "MiddlewareTermination", + "PolicyRefusal", "ProviderChatClient", "RunState", "SOURCE_COMMIT", "SOURCE_FRAMEWORK", "SpanRecorder", + "ToolArgumentError", "ToolError", "UsageDetails", "agent_middleware", "chat_middleware", "function_middleware", + "load_runtime_policy", "make_exec_tool", "tool", +] diff --git a/osiris_cli/runtime/_agents.py b/osiris_cli/runtime/_agents.py new file mode 100644 index 00000000..251ff011 --- /dev/null +++ b/osiris_cli/runtime/_agents.py @@ -0,0 +1,280 @@ +# Portions adapted from microsoft/agent-framework@567e4d458b59b83ac9b19088a43a2853094c6df1 +# python/packages/core/agent_framework/_agents.py (Agent.run / run_stream around three middleware +# pipelines, session history and context providers) and _tools.py (the function-invocation loop: +# round-trip, call-count, wall-time and consecutive-error limits, unknown-call handling, error +# results without exception detail by default, settling a batch when the loop stops). +# MIT License, Copyright (c) Microsoft Corporation. See THIRD_PARTY_NOTICES.md and PORT_MAP.md. +"""The agent: a model, tools, and the governed loop between them. + +``Agent.run`` builds one ``RunState`` and runs the agent pipeline (governance first, then the +caller's agent middleware) around the core loop. Each model call goes through the chat pipeline; +each tool call through the function pipeline, whose innermost link is the governance tool policy. + +Deliberate differences from the source: + +* Tool calls in one model response run sequentially, in the model's order, so the ledger and the + budget see one deterministic sequence. +* Approval is decided in the run by the governance ``approval_handler`` (no handler, no approval) + instead of by returning approval requests to the caller; there is no stored approval to replay. +* ``run_stream`` is buffered: updates are released only after every agent middleware, including + the evidence firewall, has passed the run. The source's unbuffered mode lets a stream reach the + consumer before result gates run. +""" + +from __future__ import annotations + +import asyncio +import time +import uuid +from typing import Any, AsyncIterator, Dict, List, Mapping, Optional, Sequence, Union + +from ._clients import ChatClient +from ._governance import ( + GovernanceConfig, + GovernanceRequiredError, + GovernanceStack, + PolicyRefusal, + governance_disabled_allowed, +) +from ._middleware import ( + KIND_AGENT, + KIND_CHAT, + KIND_FUNCTION, + AgentContext, + ChatContext, + FunctionInvocationContext, + MiddlewareFailure, + MiddlewarePipeline, + MiddlewareTermination, + RunState, + middleware_kind, +) +from ._sessions import AgentSession, ContextProvider, HistoryProvider +from ._telemetry import SpanRecorder, otel_tracer +from ._tools import FunctionTool, InvocationConfig, ToolArgumentError, normalize_tools +from ._types import ( + FINISH_STOP, + ROLE_SYSTEM, + ROLE_TOOL, + AgentResponse, + AgentResponseUpdate, + ChatResponse, + Content, + Message, + MessageInput, + UsageDetails, + normalize_messages, +) + +_NOT_EXECUTED = "Not executed: the run stopped before this call." + + +class Agent: + """A governed agent. + + ``governance`` is a ``GovernanceConfig`` (or a prebuilt ``GovernanceStack``); left out, a default + read-only configuration is used. ``governance=False`` is accepted only when the runtime policy + has ``"governance_required": false``. ``middleware`` mixes agent, chat and function middleware; + each item goes to its own pipeline, inside the governance stack.""" + + def __init__(self, client: ChatClient, *, name: str = "osiris-agent", instructions: str = "", + tools: Sequence[Any] = (), middleware: Sequence[Any] = (), + governance: Union[None, bool, GovernanceConfig, GovernanceStack] = None, + context_providers: Sequence[ContextProvider] = (), invocation: Optional[InvocationConfig] = None, + options: Optional[Mapping[str, Any]] = None, agent_id: Optional[str] = None) -> None: + if not isinstance(client, ChatClient): + raise TypeError("client must be a ChatClient") + self.client = client + self.name = name + self.id = agent_id or uuid.uuid4().hex + self.instructions = instructions + self.tools: List[FunctionTool] = normalize_tools(tools) + self._tool_map: Dict[str, FunctionTool] = {t.name: t for t in self.tools} + self.context_providers = list(context_providers) + self.invocation = invocation or InvocationConfig() + self.options: Dict[str, Any] = dict(options or {}) + if governance is False: + if not governance_disabled_allowed(): + raise GovernanceRequiredError("the runtime policy requires governance; " + "edit osiris_cli/policy/runtime_policy.json to change that") + self.governance: Optional[GovernanceStack] = None + elif governance is None or governance is True: + self.governance = GovernanceStack.build(GovernanceConfig()) + elif isinstance(governance, GovernanceConfig): + self.governance = GovernanceStack.build(governance) + elif isinstance(governance, GovernanceStack): + self.governance = governance + else: + raise TypeError("governance must be a GovernanceConfig, a GovernanceStack, None, or False") + user: Dict[str, List[Any]] = {KIND_AGENT: [], KIND_CHAT: [], KIND_FUNCTION: []} + for item in middleware: + user[middleware_kind(item)].append(item) + g = self.governance + self._agent_pipeline = MiddlewarePipeline(KIND_AGENT, (g.agent if g else []) + user[KIND_AGENT]) + self._chat_pipeline = MiddlewarePipeline(KIND_CHAT, (g.chat if g else []) + user[KIND_CHAT]) + self._function_pipeline = MiddlewarePipeline( + KIND_FUNCTION, (g.function_outer if g else []) + user[KIND_FUNCTION] + (g.function_inner if g else [])) + + def __repr__(self) -> str: + return f"Agent({self.name!r}, tools={[t.name for t in self.tools]}, governed={self.governance is not None})" + + @property + def pipelines(self) -> Dict[str, List[str]]: + """Middleware names per pipeline, outermost first.""" + return {"agent": self._agent_pipeline.names, "chat": self._chat_pipeline.names, + "function": self._function_pipeline.names} + + def new_session(self, session_id: Optional[str] = None, *, + history: Optional[HistoryProvider] = None) -> AgentSession: + return AgentSession(session_id, history=history) + + async def run(self, messages: MessageInput = None, *, session: Optional[AgentSession] = None, + options: Optional[Mapping[str, Any]] = None) -> AgentResponse: + return await self._run(messages, session=session, options=options, stream=False) + + async def run_stream(self, messages: MessageInput = None, *, session: Optional[AgentSession] = None, + options: Optional[Mapping[str, Any]] = None) -> AsyncIterator[AgentResponseUpdate]: + """Buffered streaming: one update per new message, released after governance passed the run.""" + response = await self._run(messages, session=session, options=options, stream=True) + for message in response.messages: + yield AgentResponseUpdate(contents=list(message.contents), role=message.role, agent_name=self.name, + message_id=message.message_id, run_id=response.run_id) + + def run_sync(self, messages: MessageInput = None, *, session: Optional[AgentSession] = None, + options: Optional[Mapping[str, Any]] = None) -> AgentResponse: + """``run`` for synchronous callers such as the REPL. Not usable inside a running event loop.""" + try: + asyncio.get_running_loop() + except RuntimeError: + return asyncio.run(self.run(messages, session=session, options=options)) + raise RuntimeError("run_sync() was called inside a running event loop; await run() instead") + + async def _run(self, messages: MessageInput, *, session: Optional[AgentSession], + options: Optional[Mapping[str, Any]], stream: bool) -> AgentResponse: + run = RunState(run_id=uuid.uuid4().hex, agent_name=self.name, recorder=SpanRecorder(otel_tracer())) + context = AgentContext(agent=self, messages=normalize_messages(messages), run=run, session=session, + options={**self.options, **dict(options or {})}, stream=stream) + result = await self._agent_pipeline.execute(context, self._run_core) + if not isinstance(result, AgentResponse): + result = AgentResponse(agent_name=self.name, run_id=run.run_id, status=run.status or "BLOCKED") + result.run_id = run.run_id + result.governance = {**run.governance, **result.governance} + result.telemetry = run.recorder.to_dicts() + return result + + async def _run_core(self, context: AgentContext) -> AgentResponse: + session: Optional[AgentSession] = context.session + history = await session.history.get_messages(session.session_id) if session is not None else [] + instructions = [self.instructions] if self.instructions else [] + extra: List[Message] = [] + for provider in self.context_providers: + additions = await provider.before_run(session, context.messages) + instructions.extend(i for i in additions.instructions if i) + extra.extend(additions.messages) + conversation: List[Message] = ([Message.system("\n\n".join(instructions))] if instructions else []) \ + + [m for m in history if m.role != ROLE_SYSTEM] + extra + list(context.messages) + new_messages: List[Message] = [] + usage = UsageDetails() + finish = FINISH_STOP + model_id = "" + cfg = self.invocation + started = time.monotonic() + calls_made = 0 + consecutive_errors = 0 + offer_tools = bool(self.tools) + tool_rounds = 0 + while True: + tools = self.tools if offer_tools else [] + chat = ChatContext(client=self.client, messages=conversation, run=context.run, options=context.options, + tools=tools, session=session) + response = await self._chat_pipeline.execute(chat, self._call_client) + if not isinstance(response, ChatResponse): + break # chat middleware ended the run (for example, the step budget) + usage = usage + response.usage + finish, model_id = response.finish_reason, response.model_id or model_id + conversation.extend(response.messages) + new_messages.extend(response.messages) + calls = response.function_calls + if not calls or not offer_tools: + break + tool_rounds += 1 + results, stopped, errors, calls_made = await self._invoke_batch(context, calls, calls_made) + consecutive_errors = consecutive_errors + errors if errors == len(results) else 0 + tool_message = Message(ROLE_TOOL, results) + conversation.append(tool_message) + new_messages.append(tool_message) + if stopped: + break + if tool_rounds >= cfg.max_iterations or consecutive_errors >= cfg.max_consecutive_errors \ + or (cfg.max_function_calls is not None and calls_made >= cfg.max_function_calls) \ + or (cfg.max_duration_seconds is not None and time.monotonic() - started >= cfg.max_duration_seconds): + offer_tools = False # one more model call, without tools, for a plain answer + if session is not None: + await session.history.add_messages(session.session_id, list(context.messages) + new_messages) + response_out = AgentResponse(messages=new_messages, agent_name=self.name, run_id=context.run.run_id, + usage=usage, finish_reason=finish, model_id=model_id, + status=context.run.status or "SUCCESS") + for provider in self.context_providers: + await provider.after_run(session, context.messages, response_out) + return response_out + + async def _call_client(self, chat: ChatContext) -> ChatResponse: + return await chat.client.get_response(chat.messages, tools=chat.tools, options=chat.options) + + async def _invoke_batch(self, context: AgentContext, calls: List[Content], calls_made: int): + """Run one response's tool calls in order. Returns (results, stopped, error_count, calls_made). + When the run stops mid-batch every remaining call still gets a result, so history never holds + a call without an answer.""" + cfg = self.invocation + results: List[Content] = [] + errors = 0 + stopped = False + for index, call in enumerate(calls): + if stopped or (cfg.max_function_calls is not None and calls_made >= cfg.max_function_calls): + results.append(Content.from_function_result(call.call_id, name=call.name, exception=_NOT_EXECUTED + if stopped else "Not executed: the tool-call limit was reached.")) + errors += 1 + continue + tool = self._tool_map.get(call.name) + if tool is None: + if cfg.terminate_on_unknown_calls: + raise MiddlewareFailure(f"the model called an unknown tool {call.name!r}") + results.append(Content.from_function_result( + call.call_id, name=call.name, exception=f'Error: Requested function "{call.name}" not found.')) + errors += 1 + continue + calls_made += 1 + try: + # Validate before middleware sees the call (no approval prompt for a malformed call); + # FunctionTool.invoke validates again whatever middleware passes on. + arguments = tool.validate_arguments(call.arguments) + invocation = FunctionInvocationContext(function=tool, arguments=arguments, run=context.run, + call_id=call.call_id, session=context.session) + value = await self._function_pipeline.execute(invocation, self._invoke_tool) + except MiddlewareTermination as termination: + stopped = True + value = termination.result if termination.result is not None else PolicyRefusal(str(termination), tool.name) + except MiddlewareFailure: + raise + except ToolArgumentError as exc: + detail = f" Exception: {exc}" if cfg.include_detailed_errors else "" + results.append(Content.from_function_result(call.call_id, name=tool.name, + exception=f"Error: Argument parsing failed.{detail}")) + errors += 1 + continue + except Exception as exc: + detail = f" Exception: {type(exc).__name__}: {exc}" if cfg.include_detailed_errors else "" + results.append(Content.from_function_result(call.call_id, name=tool.name, + exception=f"Error: Function failed.{detail}")) + errors += 1 + continue + if isinstance(value, PolicyRefusal): + results.append(Content.from_function_result(call.call_id, name=tool.name, + exception=f"Refused by policy: {value.refusal_reason}")) + errors += 1 + else: + results.append(Content.from_function_result(call.call_id, value, name=tool.name)) + return results, stopped, errors, calls_made + + async def _invoke_tool(self, invocation: FunctionInvocationContext) -> Any: + return await invocation.function.invoke(invocation.arguments) diff --git a/osiris_cli/runtime/_clients.py b/osiris_cli/runtime/_clients.py new file mode 100644 index 00000000..9b19da3f --- /dev/null +++ b/osiris_cli/runtime/_clients.py @@ -0,0 +1,284 @@ +# Portions adapted from microsoft/agent-framework@567e4d458b59b83ac9b19088a43a2853094c6df1 +# python/packages/core/agent_framework/_clients.py (the chat-client protocol: one async call for a +# whole response and one for streamed updates) and python/packages/anthropic (message and tool-use +# mapping for the Anthropic Messages API). MIT License, Copyright (c) Microsoft Corporation. +# See THIRD_PARTY_NOTICES.md and PORT_MAP.md. +"""Chat clients: the runtime's view of a model. + +``ProviderChatClient`` wraps any existing ``osiris_cli.providers`` provider (Ollama, +OpenAI-compatible, Gemini compatibility, Gemma) instead of replacing it: messages and tools are +translated to the provider's ``ProviderRequest`` and tool wire format by ``tool_shim``, and tool +calls coming back are normalized by ``tool_shim.normalize`` (malformed ones fail closed). +``AnthropicChatClient`` talks to the Anthropic Messages API through the official ``anthropic`` +package when it is installed; nothing here reads or prints an API key. +""" + +from __future__ import annotations + +import asyncio +from abc import ABC, abstractmethod +from typing import Any, AsyncIterator, Dict, List, Mapping, Optional, Sequence, Tuple + +from osiris_cli.providers.base import FinishReason, ProviderRequest +from osiris_cli.providers.base import Message as ProviderMessage +from osiris_cli.providers.tool_shim import ToolCallError, normalize, wire_tools + +from ._types import ( + FINISH_ERROR, + FINISH_LENGTH, + FINISH_STOP, + FINISH_TOOL_CALLS, + ROLE_ASSISTANT, + ROLE_SYSTEM, + ROLE_TOOL, + ROLE_USER, + ChatResponse, + ChatResponseUpdate, + Content, + Message, + UsageDetails, + canonical_json, +) + + +class ChatClientError(RuntimeError): + """The model call failed or returned something that cannot be trusted.""" + + +class ChatClient(ABC): + """A model. ``provider_name`` and ``model_id`` feed telemetry and provenance.""" + + provider_name: str = "unknown" + model_id: str = "" + + @abstractmethod + async def get_response(self, messages: Sequence[Message], *, tools: Sequence[Any] = (), + options: Optional[Mapping[str, Any]] = None) -> ChatResponse: + """One complete model response to ``messages``, offering ``tools`` (FunctionTools).""" + + async def get_streaming_response(self, messages: Sequence[Message], *, tools: Sequence[Any] = (), + options: Optional[Mapping[str, Any]] = None) -> AsyncIterator[ChatResponseUpdate]: + """Streamed updates. Clients without native streaming yield their whole response once.""" + response = await self.get_response(messages, tools=tools, options=options) + for message in response.messages: + yield ChatResponseUpdate(contents=list(message.contents), role=message.role, + model_id=response.model_id, finish_reason=response.finish_reason) + + +_FINISH_FROM_PROVIDER = { + FinishReason.STOP: FINISH_STOP, FinishReason.LENGTH: FINISH_LENGTH, FinishReason.TOOL_CALL: FINISH_TOOL_CALLS, +} + + +def split_system(messages: Sequence[Message]) -> Tuple[str, List[Message]]: + """System messages joined into one instruction text, and the rest in order.""" + system = "\n\n".join(m.text for m in messages if m.role == ROLE_SYSTEM and m.text) + return system, [m for m in messages if m.role != ROLE_SYSTEM] + + +class ProviderChatClient(ChatClient): + """Adapts a ``BaseModelProvider`` to the chat-client protocol. + + ``flavor`` is the tool wire format: ``"ollama"`` for the Ollama provider (whose ``chat`` method + carries tools), ``"openai"`` for OpenAI-compatible servers. Provider calls are blocking, so they + run in a worker thread.""" + + def __init__(self, provider: Any, *, model: Optional[str] = None, flavor: Optional[str] = None, + temperature: float = 0.2, max_tokens: int = 1024, timeout: float = 60.0) -> None: + self.provider = provider + self.flavor = flavor or ("ollama" if type(provider).__name__.lower().startswith("ollama") else "openai") + if self.flavor not in ("ollama", "openai"): + raise ValueError("flavor must be 'ollama' or 'openai'") + self.model_id = model or getattr(provider, "model", "") or getattr(provider, "selected_model", "") or "" + self.provider_name = getattr(provider, "name", "") or type(provider).__name__ + self.temperature = temperature + self.max_tokens = max_tokens + self.timeout = timeout + + def _wire_call(self, call: Content) -> Dict[str, Any]: + args: Any = call.arguments if self.flavor == "ollama" else canonical_json(call.arguments) + return {"id": call.call_id, "type": "function", "function": {"name": call.name, "arguments": args}} + + def to_request(self, messages: Sequence[Message], tools: Sequence[Any] = (), + options: Optional[Mapping[str, Any]] = None) -> ProviderRequest: + opts = dict(options or {}) + system, rest = split_system(messages) + out: List[ProviderMessage] = [] + for m in rest: + if m.role == ROLE_TOOL: + for r in m.function_results: + meta = {"tool_call_id": r.call_id} + if r.name: + meta["name"] = r.name + out.append(ProviderMessage("tool", r.result_text(), meta)) + continue + meta: Dict[str, Any] = {} + if m.role == ROLE_ASSISTANT and m.function_calls: + meta["tool_calls"] = [self._wire_call(c) for c in m.function_calls] + out.append(ProviderMessage(m.role, m.text, meta)) + specs = [t.spec for t in tools] + return ProviderRequest( + messages=out, system=system, model=opts.get("model") or self.model_id or None, + temperature=float(opts.get("temperature", self.temperature)), + max_tokens=int(opts.get("max_tokens", self.max_tokens)), + tools=wire_tools(self.flavor, specs) if specs else None, timeout=float(opts.get("timeout", self.timeout)), + ) + + def _call(self): + chat = getattr(self.provider, "chat", None) + return chat if callable(chat) else self.provider.generate + + async def get_response(self, messages: Sequence[Message], *, tools: Sequence[Any] = (), + options: Optional[Mapping[str, Any]] = None) -> ChatResponse: + request = self.to_request(messages, tools, options) + response = await asyncio.to_thread(self._call(), request) + if response.error or not response.is_success: + raise ChatClientError(f"{self.provider_name}: {response.error or response.finish_reason.value}") + try: + calls = normalize(response.tool_calls, self.flavor) + except ToolCallError as exc: + raise ChatClientError(f"{self.provider_name}: malformed tool call ({exc})") from None + contents: List[Content] = [] + if response.content: + contents.append(Content.from_text(response.content)) + contents.extend(Content.from_function_call(c.id, c.name, c.arguments) for c in calls) + usage = UsageDetails(response.prompt_eval_count or None, response.eval_count or None) + finish = FINISH_TOOL_CALLS if calls else _FINISH_FROM_PROVIDER.get(response.finish_reason, FINISH_ERROR) + return ChatResponse([Message(ROLE_ASSISTANT, contents)], model_id=response.model or self.model_id, + finish_reason=finish, usage=usage, response_id=response.request_id) + + async def get_streaming_response(self, messages: Sequence[Message], *, tools: Sequence[Any] = (), + options: Optional[Mapping[str, Any]] = None) -> AsyncIterator[ChatResponseUpdate]: + """Text chunks as the provider produces them. Streaming carries text only; the tool loop + uses ``get_response``.""" + request = self.to_request(messages, tools, options) + request.stream = True + stream_fn = getattr(self.provider, "stream_chat", None) if request.messages else None + if not callable(stream_fn): + stream_fn = self.provider.stream + loop = asyncio.get_running_loop() + queue: "asyncio.Queue[Any]" = asyncio.Queue() + done = object() + + def produce() -> None: + try: + for chunk in stream_fn(request): + loop.call_soon_threadsafe(queue.put_nowait, chunk) + except Exception as exc: # surfaced to the consumer below + loop.call_soon_threadsafe(queue.put_nowait, exc) + finally: + loop.call_soon_threadsafe(queue.put_nowait, done) + + worker = loop.run_in_executor(None, produce) + try: + while True: + item = await queue.get() + if item is done: + break + if isinstance(item, Exception): + raise ChatClientError(f"{self.provider_name}: stream failed ({item})") from item + finish = _FINISH_FROM_PROVIDER.get(item.finish_reason) if item.finish_reason else None + if item.finish_reason is not None and finish is None: + raise ChatClientError(f"{self.provider_name}: stream ended with {item.finish_reason.value}") + yield ChatResponseUpdate(contents=[Content.from_text(item.text)] if item.text else [], + model_id=self.model_id, finish_reason=finish) + finally: + await worker + + +_ANTHROPIC_STOP = {"end_turn": FINISH_STOP, "stop_sequence": FINISH_STOP, "tool_use": FINISH_TOOL_CALLS, + "max_tokens": FINISH_LENGTH} + + +def _field(obj: Any, name: str, default: Any = None) -> Any: + if isinstance(obj, Mapping): + return obj.get(name, default) + return getattr(obj, name, default) + + +class AnthropicChatClient(ChatClient): + """The Anthropic Messages API. ``model`` is required: no model id is assumed. Pass ``client`` + (an ``anthropic.Anthropic`` or any object with the same ``messages.create``) to inject one; + otherwise the ``anthropic`` package is imported on first use.""" + + provider_name = "anthropic" + + def __init__(self, model: str, *, client: Any = None, max_tokens: int = 1024, + temperature: Optional[float] = None) -> None: + if not model: + raise ValueError("AnthropicChatClient needs an explicit model id") + self.model_id = model + self._client = client + self.max_tokens = max_tokens + self.temperature = temperature + + def _sdk(self) -> Any: + if self._client is None: + try: + import anthropic # type: ignore[import-not-found] + except ImportError as exc: + raise ChatClientError("the 'anthropic' package is not installed") from exc + self._client = anthropic.Anthropic() + return self._client + + def to_request(self, messages: Sequence[Message], tools: Sequence[Any] = (), + options: Optional[Mapping[str, Any]] = None) -> Dict[str, Any]: + opts = dict(options or {}) + system, rest = split_system(messages) + wire: List[Dict[str, Any]] = [] + for m in rest: + if m.role == ROLE_TOOL: + role = ROLE_USER + blocks = [{"type": "tool_result", "tool_use_id": r.call_id, "content": r.result_text(), + **({"is_error": True} if r.exception else {})} for r in m.function_results] + else: + role = m.role + blocks = [{"type": "text", "text": m.text}] if m.text else [] + if m.role == ROLE_ASSISTANT: + blocks += [{"type": "tool_use", "id": c.call_id, "name": c.name, "input": c.arguments} + for c in m.function_calls] + if not blocks: + continue + if wire and wire[-1]["role"] == role: + wire[-1]["content"].extend(blocks) + else: + wire.append({"role": role, "content": blocks}) + request: Dict[str, Any] = {"model": opts.get("model") or self.model_id, + "max_tokens": int(opts.get("max_tokens", self.max_tokens)), "messages": wire} + if system: + request["system"] = system + temperature = opts.get("temperature", self.temperature) + if temperature is not None: + request["temperature"] = float(temperature) + if tools: + request["tools"] = [{"name": t.name, "description": t.description, "input_schema": t.parameters} + for t in tools] + return request + + async def get_response(self, messages: Sequence[Message], *, tools: Sequence[Any] = (), + options: Optional[Mapping[str, Any]] = None) -> ChatResponse: + request = self.to_request(messages, tools, options) + sdk = self._sdk() + try: + response = await asyncio.to_thread(sdk.messages.create, **request) + except ChatClientError: + raise + except Exception as exc: + raise ChatClientError(f"anthropic: {type(exc).__name__}") from exc + contents: List[Content] = [] + for block in _field(response, "content", []) or []: + kind = _field(block, "type") + if kind == "text": + contents.append(Content.from_text(_field(block, "text", ""))) + elif kind == "tool_use": + arguments = _field(block, "input", {}) or {} + if not isinstance(arguments, Mapping): + raise ChatClientError("anthropic: tool_use input is not an object") + contents.append(Content.from_function_call(_field(block, "id"), _field(block, "name"), dict(arguments))) + usage_obj = _field(response, "usage") + usage = UsageDetails(_field(usage_obj, "input_tokens"), _field(usage_obj, "output_tokens")) \ + if usage_obj is not None else UsageDetails() + stop = _field(response, "stop_reason") or "end_turn" + finish = _ANTHROPIC_STOP.get(stop, FINISH_ERROR) + return ChatResponse([Message(ROLE_ASSISTANT, contents)], model_id=_field(response, "model", "") or self.model_id, + finish_reason=finish, usage=usage, response_id=_field(response, "id", "") or "") diff --git a/osiris_cli/runtime/_governance.py b/osiris_cli/runtime/_governance.py new file mode 100644 index 00000000..8d22d119 --- /dev/null +++ b/osiris_cli/runtime/_governance.py @@ -0,0 +1,496 @@ +"""The governance stack every runtime agent runs inside. + +This module is OSIRIS's own; it has no counterpart in the source framework. It binds the runtime's +middleware hooks to the governance code osiris-cli already has, without changing that code: + +======================== ========== ============================================================== +Middleware Hook Existing OSIRIS code it applies +======================== ========== ============================================================== +RunRecordMiddleware agent ``task_context``: intake context, ``task_open``/``task_close`` + in ``$OSIRIS_HOME/tasks/task_runs.jsonl``, the BudgetMeter +IntentGateMiddleware agent ``intent_router.assess`` (via the context's risk tier) and the + runtime policy's blocked / grant-required tiers +EvidenceFirewallMid... agent ``orchestration.evidence_firewall.check_report`` on the answer +BudgetChatMiddleware chat ``BudgetMeter.begin_step`` / ``charge_tokens`` +ProvenanceChatMiddleware chat requested vs. actual model, prompt and response SHA-256 +ToolPolicyMiddleware function run permissions, workspace confinement, credential-name rule, + ``orchestration.governance_scope`` for writes, + ``orchestration.ast_firewall`` (SYS-025) for code arguments, + approval for ``always_require`` tools, ``BudgetMeter`` +======================== ========== ============================================================== + +The stack is installed first on every agent. It can be left out only when +``osiris_cli/policy/runtime_policy.json`` says ``"governance_required": false``; no constructor +argument or flag overrides that. Every decision is fail-closed: a missing ledger, meter or policy +aborts the run with ``MiddlewareFailure`` rather than running ungoverned. +""" + +from __future__ import annotations + +import asyncio +import dataclasses +import fnmatch +import inspect +import json +import os +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Awaitable, Callable, Dict, List, Mapping, Optional, Union + +from osiris_cli import task_context +from osiris_cli.orchestration import ast_firewall, governance_scope +from osiris_cli.orchestration.evidence_firewall import check_report + +from ._middleware import ( + AgentContext, + AgentMiddleware, + CallNext, + ChatContext, + ChatMiddleware, + FunctionInvocationContext, + FunctionMiddleware, + MiddlewareFailure, + MiddlewareTermination, +) +from ._telemetry import ( + TelemetryAgentMiddleware, + TelemetryChatMiddleware, + TelemetryFunctionMiddleware, +) +from ._tools import APPROVAL_ALWAYS, FunctionTool +from ._types import ( + ROLE_ASSISTANT, + ROLE_USER, + AgentResponse, + ChatResponse, + Content, + Message, + sha256_json, +) + +POLICY_SCHEMA = "osiris.runtime-policy.v1" +DEFAULT_POLICY_PATH = Path(__file__).resolve().parent.parent / "policy" / "runtime_policy.json" +GOVERNANCE_AUTHOR = "osiris.governance" + + +class GovernancePolicyError(RuntimeError): + """The runtime policy is missing or malformed. Treated as a refusal to run.""" + + +class GovernanceRequiredError(RuntimeError): + """An agent was built without governance while the runtime policy requires it.""" + + +def load_runtime_policy(path: Optional[Union[str, "os.PathLike[str]"]] = None) -> Dict[str, Any]: + p = Path(path) if path is not None else DEFAULT_POLICY_PATH + try: + with open(p, encoding="utf-8") as f: + policy = json.load(f) + except (OSError, ValueError) as exc: + raise GovernancePolicyError(f"runtime policy {p} cannot be read ({exc})") from None + if not isinstance(policy, dict) or policy.get("schema") != POLICY_SCHEMA: + raise GovernancePolicyError(f"runtime policy {p} is not a {POLICY_SCHEMA} document") + for key, kind in (("governance_required", bool), ("blocked_risk_tiers", list), + ("grant_required_risk_tiers", list), ("credential_name_patterns", list)): + if not isinstance(policy.get(key), kind): + raise GovernancePolicyError(f"runtime policy {p}: '{key}' must be a {kind.__name__}") + unknown = [t for t in policy["blocked_risk_tiers"] + policy["grant_required_risk_tiers"] + if t not in task_context.RISK_TIERS] + if unknown: + raise GovernancePolicyError(f"runtime policy {p}: unknown risk tiers {unknown}") + return policy + + +def osiris_home() -> Path: + """``$OSIRIS_HOME``, else ``~/.osiris``, resolved.""" + return Path(os.environ.get("OSIRIS_HOME") or (Path.home() / ".osiris")).resolve() + + +@dataclass +class ApprovalRequest: + """Something a human must approve: a run at a grant-required risk tier, a tool marked + ``always_require``, or a command ``exec_policy`` classifies ASK.""" + + kind: str + summary: str + details: Dict[str, Any] = field(default_factory=dict) + + +ApprovalHandler = Callable[[ApprovalRequest], Union[bool, Awaitable[bool]]] + + +async def ask_approval(handler: Optional[ApprovalHandler], request: ApprovalRequest) -> bool: + """True only if a handler exists and returns exactly ``True``. No handler means no approval.""" + if handler is None: + return False + answer = handler(request) + if inspect.isawaitable(answer): + answer = await answer + return answer is True + + +@dataclass +class PolicyRefusal: + """The result of a tool call the governance stack refused. The tool loop turns it into a + function result whose error text the model sees.""" + + refusal_reason: str + tool: str + + +@dataclass +class GovernanceConfig: + """What one agent's runs may do, and where they are recorded. + + Permissions are a ceiling the operator sets in code or on the command line, never derived from + the prompt. ``workspace_root`` defaults to the current directory; ``ledger_path`` and + ``exchange_log`` default to the canonical files under ``$OSIRIS_HOME``. ``budget`` lowers the + risk tier's caps (``max_steps``, ``max_tool_calls``, ...) and can never raise them.""" + + workspace_root: Optional[str] = None + propose_writes: bool = False + run_commands: bool = False + external_actions: bool = False + hardware_actions: bool = False + approval_handler: Optional[ApprovalHandler] = None + ledger_path: Optional[str] = None + exchange_log: Optional[str] = None + kind: str = "agent" + budget: Dict[str, Any] = field(default_factory=dict) + policy_path: Optional[str] = None + assess: Optional[Callable[[str], Any]] = None + + def root(self) -> Path: + return Path(self.workspace_root or os.getcwd()).resolve() + + def resolved_ledger_path(self) -> str: + return self.ledger_path or str(osiris_home() / "tasks" / "task_runs.jsonl") + + def resolved_exchange_log(self) -> str: + return self.exchange_log or str(osiris_home() / "living" / "exchanges.jsonl") + + def permissions(self) -> task_context.Permissions: + base = task_context.permissions(read=True, propose_writes=self.propose_writes, run_commands=self.run_commands) + return dataclasses.replace(base, external_actions=self.external_actions, hardware_actions=self.hardware_actions) + + +def _refusal_response(context: AgentContext, reason: str) -> AgentResponse: + message = Message(ROLE_ASSISTANT, [Content.from_text(f"Refused by OSIRIS governance: {reason}")], + author_name=GOVERNANCE_AUTHOR) + return AgentResponse(messages=[message], agent_name=context.run.agent_name, run_id=context.run.run_id, + status="BLOCKED", governance={"refusal": reason}) + + +def _require(context: Any, key: str, who: str) -> Any: + value = context.run.metadata.get(key) + if value is None: + raise MiddlewareFailure(f"{who} needs '{key}' from RunRecordMiddleware; refusing to run ungoverned") + return value + + +class RunRecordMiddleware(AgentMiddleware): + """L0 intake and L8 ledger: mint the task context, write ``task_open`` before anything runs and + ``task_close`` after, whatever happens. No ledger record, no run.""" + + def __init__(self, config: GovernanceConfig) -> None: + self.config = config + + async def process(self, context: AgentContext, call_next: CallNext) -> None: + text = "\n".join(m.text for m in context.messages if m.role == ROLE_USER and m.text) or "(no user text)" + perms = self.config.permissions() + try: + tctx = task_context.new_context(text, kind=self.config.kind, perms=perms, + exchange_log=self.config.resolved_exchange_log(), + assess=self.config.assess, **self.config.budget) + except (task_context.TaskContextError, TypeError, ValueError) as exc: + raise MiddlewareFailure(f"BLOCKED (context_invalid): {exc}") from exc + ledger = task_context.TaskLedger(self.config.resolved_ledger_path()) + try: + ledger.open(tctx) + except task_context.TaskLedgerError as exc: + raise MiddlewareFailure(f"BLOCKED (ledger_unavailable): {exc}") from exc + meter = tctx.meter() + run = context.run + run.run_id = tctx.run_id + run.metadata["task_context"] = tctx + run.metadata["meter"] = meter + run.governance["run_record"] = {"run_id": tctx.run_id, "kind": tctx.kind, "risk_tier": tctx.risk_tier, + "cost_class": tctx.cost_class, "risk_reasons": list(tctx.risk_reasons), + "context_sha256": tctx.context_sha256, + "ledger": self.config.resolved_ledger_path()} + blocked = task_context.require(tctx, propose_writes=perms.propose_writes, run_commands=perms.run_commands) + status = "ERROR" + try: + if blocked is not None: + run.stop, run.status = blocked, blocked.status + context.result = _refusal_response(context, str(blocked)) + status = blocked.status + else: + try: + await call_next() + except MiddlewareTermination as termination: + # Graceful stop further in (a refused intent, a budget stop): record it, keep its result. + if context.result is None: + context.result = termination.result + # Only a stop that actually ended the run (set by the budget or tool-policy + # middleware) marks it STOPPED_BUDGET; a run that finished its answer is not relabelled. + result = context.result + if run.status: + status = run.status + elif run.stop is not None: + status = run.stop.status + elif isinstance(result, AgentResponse): + status = result.status + else: + status = "BLOCKED" + finally: + usage = dict(meter.usage()) + usage["telemetry"] = run.recorder.summary() + usage["governance"] = { + "evidence_decision": run.governance.get("evidence_decision"), + "refusals": len(run.governance.get("refusals", [])), + "tool_calls_allowed": len(run.governance.get("tool_calls", [])), + "model_calls": len(run.governance.get("provenance", [])), + } + try: + ledger.close(tctx, status, stop=run.stop, usage=usage, detail=f"agent {run.agent_name}") + except task_context.TaskLedgerError as exc: + run.governance["ledger_close_error"] = str(exc) + raise MiddlewareFailure(f"task_close could not be written: {exc}") from exc + if isinstance(context.result, AgentResponse): + context.result.status = status + context.result.run_id = tctx.run_id + + +class IntentGateMiddleware(AgentMiddleware): + """L1: refuse runs at a blocked risk tier; ask for a grant at a grant-required tier.""" + + def __init__(self, config: GovernanceConfig, policy: Mapping[str, Any]) -> None: + self.config = config + self.policy = policy + + async def process(self, context: AgentContext, call_next: CallNext) -> None: + tctx = _require(context, "task_context", "IntentGateMiddleware") + tier = tctx.risk_tier + reason = "" + if tier in self.policy["blocked_risk_tiers"]: + reason = f"risk tier {tier} is blocked by the runtime policy" + elif tier in self.policy["grant_required_risk_tiers"]: + granted = await ask_approval(self.config.approval_handler, ApprovalRequest( + "risk_tier", f"run '{context.run.agent_name}' at risk tier {tier}", + {"risk_reasons": list(tctx.risk_reasons), "cost_class": tctx.cost_class})) + context.run.note("grants", {"kind": "risk_tier", "tier": tier, "granted": granted}) + if not granted: + reason = f"risk tier {tier} needs a human grant and none was given" + if reason: + context.run.status = "BLOCKED" + context.run.note("refusals", {"gate": "intent", "reason": reason, + "risk_reasons": list(tctx.risk_reasons)}) + raise MiddlewareTermination(reason, result=_refusal_response(context, reason)) + await call_next() + + +class EvidenceFirewallMiddleware(AgentMiddleware): + """L3: run the answer through the evidence firewall. Non-ACCEPT decisions are flagged on the + response (``governance['evidence']``), never silently dropped.""" + + async def process(self, context: AgentContext, call_next: CallNext) -> None: + await call_next() + result = context.result + if not isinstance(result, AgentResponse) or not result.text: + return + firewall = check_report(result.text, evidence=context.run.metadata.get("execution_evidence"), + artifacts=context.run.metadata.get("evidence_artifacts")) + decision = firewall.decision + result.governance["evidence"] = {"decision": decision, + "findings": [dataclasses.asdict(f) for f in firewall.findings]} + context.run.governance["evidence_decision"] = decision + + +class BudgetChatMiddleware(ChatMiddleware): + """Each model call is a step against the task budget; reported tokens are charged after it.""" + + async def process(self, context: ChatContext, call_next: CallNext) -> None: + meter = _require(context, "meter", "BudgetChatMiddleware") + stop = meter.begin_step() + if stop is not None: + context.run.stop, context.run.status = stop, stop.status + context.run.note("stops", str(stop)) + raise MiddlewareTermination(str(stop)) + await call_next() + if isinstance(context.result, ChatResponse): + meter.charge_tokens(context.result.usage.total_token_count, text=context.result.text) + + +class ProvenanceChatMiddleware(ChatMiddleware): + """Record which model was asked, which answered, and digests of what went in and came out.""" + + async def process(self, context: ChatContext, call_next: CallNext) -> None: + requested = context.options.get("model") or getattr(context.client, "model_id", "") or "" + entry: Dict[str, Any] = {"requested_model": requested, + "prompt_sha256": sha256_json([m.content_dict() for m in context.messages]), + "tools_offered": [t.name for t in context.tools]} + try: + await call_next() + finally: + result = context.result + if isinstance(result, ChatResponse): + entry["actual_model"] = result.model_id + entry["response_sha256"] = sha256_json(result.to_dict()) + entry["model_mismatch"] = bool(requested and result.model_id and requested != result.model_id) + context.run.note("provenance", entry) + + +class ToolPolicyMiddleware(FunctionMiddleware): + """The innermost function middleware: it checks exactly the arguments that will run. + + Order: task budget, effects against the run's permissions, path arguments (workspace + confinement, credential names, governance-protected write targets), code arguments (SYS-025 AST + firewall), then approval for ``always_require`` tools. A refusal does not run the tool; the model + is told why and may continue.""" + + def __init__(self, config: GovernanceConfig, policy: Mapping[str, Any]) -> None: + self.config = config + self.patterns = [p.lower() for p in policy["credential_name_patterns"]] + + def path_problem(self, value: Any, write: bool) -> str: + if not isinstance(value, str) or not value or "\x00" in value: + return "path argument is not a usable string" + root = self.config.root() + candidate = Path(value) + resolved = (candidate if candidate.is_absolute() else root / candidate).resolve() + try: + relative = resolved.relative_to(root) + except ValueError: + return f"'{value}' resolves outside the workspace {root}" + for part in relative.parts: + if any(fnmatch.fnmatch(part.lower(), pat) for pat in self.patterns): + return f"'{value}' names a credential-shaped file ({part}); it is never read or written" + if write: + protected = governance_scope.protected_reason(str(resolved), roots=[str(root)]) + if protected: + return f"write refused: {protected}" + return "" + + def _refuse(self, context: FunctionInvocationContext, reason: str) -> None: + context.result = PolicyRefusal(reason, context.function.name) + context.run.note("refusals", {"gate": "tool", "tool": context.function.name, + "call_id": context.call_id, "reason": reason}) + + async def process(self, context: FunctionInvocationContext, call_next: CallNext) -> None: + tool: FunctionTool = context.function + tctx = _require(context, "task_context", "ToolPolicyMiddleware") + meter = _require(context, "meter", "ToolPolicyMiddleware") + stop = meter.begin_tool_call() + if stop is not None: + context.run.stop, context.run.status = stop, stop.status + context.run.note("stops", str(stop)) + raise MiddlewareTermination(str(stop), result=PolicyRefusal(str(stop), tool.name)) + perms = tctx.permissions + allowed = {"write": perms.propose_writes, "exec": perms.run_commands, "network": perms.external_actions, + "hardware": perms.hardware_actions} + for effect in tool.effects: + if effect in allowed and not allowed[effect]: + meter.note(False) + return self._refuse(context, f"effect '{effect}' is not permitted for this run") + for name in tool.path_params + tool.write_params: + if name in context.arguments and context.arguments[name] is not None: + problem = self.path_problem(context.arguments[name], write=name in tool.write_params) + if problem: + meter.note(False) + return self._refuse(context, problem) + for name in tool.code_params: + source = context.arguments.get(name) + if source is None: + continue + clean, violations = ast_firewall.check(source) if isinstance(source, str) else (False, []) + if not clean: + found = ", ".join(f"{v.kind} {v.name} (line {v.line})" for v in violations[:5]) or "does not parse" + meter.note(False) + return self._refuse(context, f"SYS-025 AST firewall refused '{name}': {found}") + if tool.approval_mode == APPROVAL_ALWAYS: + granted = await ask_approval(self.config.approval_handler, ApprovalRequest( + "tool", f"call tool '{tool.name}'", + {"arguments": dict(context.arguments), "effects": list(tool.effects)})) + context.run.note("grants", {"kind": "tool", "tool": tool.name, "granted": granted}) + if not granted: + meter.note(False) + return self._refuse(context, f"tool '{tool.name}' requires approval and none was given") + context.run.note("tool_calls", {"tool": tool.name, "call_id": context.call_id, + "arguments_sha256": sha256_json(context.arguments)}) + try: + await call_next() + except Exception: + meter.note(False) + raise + meter.note(True) + + +@dataclass +class GovernanceStack: + """The middleware the governance stack contributes to each pipeline. ``function_inner`` runs + after any user function middleware, so it checks the arguments that will actually execute.""" + + agent: List[Any] + chat: List[Any] + function_outer: List[Any] + function_inner: List[Any] + config: GovernanceConfig + policy: Dict[str, Any] + + @classmethod + def build(cls, config: Optional[GovernanceConfig] = None) -> "GovernanceStack": + config = config or GovernanceConfig() + policy = load_runtime_policy(config.policy_path) + return cls( + agent=[RunRecordMiddleware(config), TelemetryAgentMiddleware(), IntentGateMiddleware(config, policy), + EvidenceFirewallMiddleware()], + chat=[TelemetryChatMiddleware(), BudgetChatMiddleware(), ProvenanceChatMiddleware()], + function_outer=[TelemetryFunctionMiddleware()], + function_inner=[ToolPolicyMiddleware(config, policy)], + config=config, policy=policy, + ) + + +def governance_disabled_allowed(policy_path: Optional[str] = None) -> bool: + return not load_runtime_policy(policy_path)["governance_required"] + + +def make_exec_tool(config: GovernanceConfig, *, journal_path: Optional[str] = None, + timeout_s: Optional[float] = None) -> FunctionTool: + """A ``run_command`` tool whose every call goes through ``exec_policy`` and ``exec_kernel``: + classification (ALLOW / ASK / DENY), ``shell=False``, a scrubbed environment and one receipt in + the exec journal. ASK is put to the governance approval handler; DENY never spawns.""" + from osiris_cli import exec_kernel + from osiris_cli.exec_policy import CommandRequest + + def confirm_in_thread(loop: asyncio.AbstractEventLoop) -> Callable[[str, Any], bool]: + def confirm(summary: str, classification: Any) -> bool: + request = ApprovalRequest("command", summary, {"tier": classification.tier, + "reasons": list(classification.reasons)}) + future = asyncio.run_coroutine_threadsafe(ask_approval(config.approval_handler, request), loop) + return future.result() + return confirm + + async def run_command(argv: List[str]) -> Dict[str, Any]: + """Run one program (argv list, no shell) inside the workspace and return its exit code and output.""" + if not argv or not all(isinstance(a, str) and a for a in argv): + raise ValueError("argv must be a non-empty list of non-empty strings") + root = str(config.root()) + request = CommandRequest(argv=tuple(argv), cwd=root, origin="model", timeout_s=timeout_s, root=root) + journal = exec_kernel.ExecJournal(Path(journal_path) if journal_path else exec_kernel.default_journal_path()) + loop = asyncio.get_running_loop() + result = await asyncio.to_thread(exec_kernel.run, request, confirm_in_thread(loop), journal) + return {"decision": result.decision, "exit_code": result.exit_code, "stdout": result.stdout_view, + "stderr": result.stderr_view, "timed_out": result.timed_out, "receipt_id": result.receipt_id, + "reasons": list(result.reasons)} + + return FunctionTool(run_command, name="run_command", effects=("exec",)) + + +__all__ = [ + "ApprovalHandler", "ApprovalRequest", "BudgetChatMiddleware", "EvidenceFirewallMiddleware", "GovernanceConfig", + "GovernancePolicyError", "GovernanceRequiredError", "GovernanceStack", "IntentGateMiddleware", "PolicyRefusal", + "ProvenanceChatMiddleware", "RunRecordMiddleware", "ToolPolicyMiddleware", "ask_approval", + "governance_disabled_allowed", "load_runtime_policy", "make_exec_tool", "osiris_home", +] diff --git a/osiris_cli/runtime/_middleware.py b/osiris_cli/runtime/_middleware.py new file mode 100644 index 00000000..d2e2c8f3 --- /dev/null +++ b/osiris_cli/runtime/_middleware.py @@ -0,0 +1,242 @@ +# Portions adapted from microsoft/agent-framework@567e4d458b59b83ac9b19088a43a2853094c6df1 +# python/packages/core/agent_framework/_middleware.py (AgentContext, FunctionInvocationContext, +# ChatContext, the three middleware base classes, MiddlewareTermination, MiddlewareFailure, the +# decorator helpers and the index-based pipeline execution). MIT License, Copyright (c) Microsoft +# Corporation. See THIRD_PARTY_NOTICES.md and PORT_MAP.md. +"""Middleware for the three places a run can be intercepted. + +* Agent middleware wraps a whole run (``AgentContext``). +* Chat middleware wraps every model call (``ChatContext``). +* Function middleware wraps every tool call (``FunctionInvocationContext``). + +Each middleware implements ``async process(context, call_next)``: work before ``await call_next()`` +runs on the way in, work after it on the way out, and not calling it at all short-circuits the +chain. Two control-flow exceptions differ on purpose: + +* ``MiddlewareTermination`` stops gracefully. Agent and chat pipelines return its ``result`` (if + any); in the tool loop it ends the run after recording the result. +* ``MiddlewareFailure`` aborts fail-closed. It is never turned into a tool result for the model; it + propagates to whoever called ``Agent.run``. + +Differences from the source, all deliberate: a pipeline refuses (``TypeError``) any object that is +neither middleware of its kind nor a callable marked for its kind, where the source logs a warning +and skips it, because skipped governance middleware would fail open; and every context carries the +run's ``RunState`` so the three pipelines of one run share a meter, a span recorder and a record of +what governance decided. +""" + +from __future__ import annotations + +import inspect +from abc import ABC, abstractmethod +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, List, Mapping, Optional, Sequence + +if TYPE_CHECKING: # pragma: no cover - imported for annotations only + from ._telemetry import SpanRecorder + +CallNext = Callable[[], Awaitable[None]] +_KIND_ATTR = "_osiris_middleware_kind" +KIND_AGENT = "agent" +KIND_FUNCTION = "function" +KIND_CHAT = "chat" + + +class MiddlewareException(Exception): + """Base class for middleware control flow.""" + + +class MiddlewareTermination(MiddlewareException): + """Stop the chain gracefully, optionally substituting ``result``.""" + + def __init__(self, message: str = "Middleware terminated execution.", *, result: Any = None) -> None: + super().__init__(message) + self.result = result + + +class MiddlewareFailure(MiddlewareException): + """Abort the run fail-closed. Never converted into a tool result; reaches ``Agent.run``'s caller. + + Middleware must not catch this exception: swallowing it turns a fail-closed abort back into a + running, possibly unguarded, loop.""" + + +@dataclass +class RunState: + """What the three pipelines of one run share.""" + + run_id: str + agent_name: str + recorder: "SpanRecorder" + metadata: Dict[str, Any] = field(default_factory=dict) + governance: Dict[str, Any] = field(default_factory=dict) + status: Optional[str] = None + stop: Any = None + + def note(self, key: str, value: Any) -> None: + """Append ``value`` to the list ``governance[key]``: what governance decided, in order.""" + self.governance.setdefault(key, []).append(value) + + +class AgentContext: + """Context for agent middleware. ``result`` is the ``AgentResponse`` once ``call_next`` returns; + setting it before returning replaces the run's result.""" + + def __init__(self, *, agent: Any, messages: List[Any], run: RunState, session: Any = None, + options: Optional[Mapping[str, Any]] = None, stream: bool = False, + metadata: Optional[Mapping[str, Any]] = None, result: Any = None) -> None: + self.agent = agent + self.messages = messages + self.run = run + self.session = session + self.options: Dict[str, Any] = dict(options or {}) + self.stream = stream + self.metadata: Dict[str, Any] = dict(metadata or {}) + self.result = result + + +class FunctionInvocationContext: + """Context for function middleware. ``function`` is the ``FunctionTool`` about to run and + ``arguments`` the model's arguments, which middleware may replace before ``call_next``.""" + + def __init__(self, *, function: Any, arguments: Mapping[str, Any], run: RunState, call_id: str = "", + session: Any = None, metadata: Optional[Mapping[str, Any]] = None, result: Any = None) -> None: + self.function = function + self.arguments: Dict[str, Any] = dict(arguments) + self.run = run + self.call_id = call_id + self.session = session + self.metadata: Dict[str, Any] = dict(metadata or {}) + self.result = result + + +class ChatContext: + """Context for chat middleware. ``result`` is the ``ChatResponse`` once ``call_next`` returns.""" + + def __init__(self, *, client: Any, messages: Sequence[Any], run: RunState, + options: Optional[Mapping[str, Any]] = None, tools: Sequence[Any] = (), session: Any = None, + metadata: Optional[Mapping[str, Any]] = None, result: Any = None) -> None: + self.client = client + self.messages = list(messages) + self.run = run + self.options: Dict[str, Any] = dict(options or {}) + self.tools = list(tools) + self.session = session + self.metadata: Dict[str, Any] = dict(metadata or {}) + self.result = result + + +class AgentMiddleware(ABC): + @abstractmethod + async def process(self, context: AgentContext, call_next: CallNext) -> None: + """Do work around ``await call_next()``; raise MiddlewareTermination to stop gracefully.""" + + +class FunctionMiddleware(ABC): + @abstractmethod + async def process(self, context: FunctionInvocationContext, call_next: CallNext) -> None: + """Do work around ``await call_next()``; raise MiddlewareTermination to end the tool loop.""" + + +class ChatMiddleware(ABC): + @abstractmethod + async def process(self, context: ChatContext, call_next: CallNext) -> None: + """Do work around ``await call_next()``; raise MiddlewareTermination to skip the model call.""" + + +def _mark(func: Callable[..., Any], kind: str) -> Callable[..., Any]: + if not inspect.iscoroutinefunction(func): + raise TypeError(f"{kind} middleware {getattr(func, '__name__', func)!r} must be an async function") + setattr(func, _KIND_ATTR, kind) + return func + + +def agent_middleware(func: Callable[..., Any]) -> Callable[..., Any]: + """Mark ``async def f(context, call_next)`` as agent middleware.""" + return _mark(func, KIND_AGENT) + + +def function_middleware(func: Callable[..., Any]) -> Callable[..., Any]: + """Mark ``async def f(context, call_next)`` as function middleware.""" + return _mark(func, KIND_FUNCTION) + + +def chat_middleware(func: Callable[..., Any]) -> Callable[..., Any]: + """Mark ``async def f(context, call_next)`` as chat middleware.""" + return _mark(func, KIND_CHAT) + + +_BASES = {KIND_AGENT: AgentMiddleware, KIND_FUNCTION: FunctionMiddleware, KIND_CHAT: ChatMiddleware} + + +def middleware_kind(item: Any) -> str: + """Which pipeline ``item`` belongs to. Raises TypeError for anything unrecognized.""" + for kind, base in _BASES.items(): + if isinstance(item, base): + return kind + kind = getattr(item, _KIND_ATTR, None) + if kind in _BASES and callable(item): + return kind + raise TypeError(f"{item!r} is not middleware: subclass AgentMiddleware, FunctionMiddleware or " + "ChatMiddleware, or decorate an async function with agent_middleware, " + "function_middleware or chat_middleware") + + +class _CallableMiddleware: + def __init__(self, func: Callable[..., Awaitable[None]]) -> None: + self.func = func + self.__name__ = getattr(func, "__name__", "middleware") + + async def process(self, context: Any, call_next: CallNext) -> None: + await self.func(context, call_next) + + +class MiddlewarePipeline: + """Runs middleware of one kind in order, then ``final_handler``.""" + + def __init__(self, kind: str, middleware: Sequence[Any] = ()) -> None: + if kind not in _BASES: + raise ValueError(f"unknown middleware kind {kind!r}") + self.kind = kind + self._middleware: List[Any] = [] + for item in middleware: + found = middleware_kind(item) + if found != kind: + raise TypeError(f"{item!r} is {found} middleware, not {kind} middleware") + self._middleware.append(item if isinstance(item, _BASES[kind]) else _CallableMiddleware(item)) + + def __len__(self) -> int: + return len(self._middleware) + + @property + def names(self) -> List[str]: + return [getattr(m, "__name__", type(m).__name__) if isinstance(m, _CallableMiddleware) + else type(m).__name__ for m in self._middleware] + + async def execute(self, context: Any, final_handler: Callable[[Any], Any]) -> Any: + """Run the chain. Agent and chat pipelines absorb MiddlewareTermination (keeping a result + set on the context, else using the termination's); the function pipeline lets it propagate + so the tool loop can end the run.""" + + def make(index: int) -> CallNext: + if index >= len(self._middleware): + async def final() -> None: + value = final_handler(context) + if inspect.isawaitable(value): + value = await value + context.result = value + return final + + async def current() -> None: + await self._middleware[index].process(context, make(index + 1)) + return current + + if self.kind == KIND_FUNCTION: + await make(0)() + return context.result + try: + await make(0)() + except MiddlewareTermination as termination: + if context.result is None: + context.result = termination.result + return context.result diff --git a/osiris_cli/runtime/_sessions.py b/osiris_cli/runtime/_sessions.py new file mode 100644 index 00000000..b0ffffd1 --- /dev/null +++ b/osiris_cli/runtime/_sessions.py @@ -0,0 +1,157 @@ +# Portions adapted from microsoft/agent-framework@567e4d458b59b83ac9b19088a43a2853094c6df1 +# python/packages/core/agent_framework/_sessions.py (AgentSession, HistoryProvider and +# ContextProvider: conversation state that outlives one run, and hooks that add context before a +# run and observe it after). MIT License, Copyright (c) Microsoft Corporation. +# See THIRD_PARTY_NOTICES.md and PORT_MAP.md. +"""Sessions: conversation history across runs, and providers of extra context. + +``FileHistoryProvider`` keeps each session as an append-only, SHA-256 hash-chained JSONL file in a +directory the caller names. It holds conversation state only. Run provenance stays in the canonical +task ledger (``$OSIRIS_HOME/tasks/task_runs.jsonl``); this module never writes under +``$OSIRIS_HOME`` unless told to. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +import threading +import uuid +from abc import ABC, abstractmethod +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Dict, List, Optional, Sequence, Union + +from ._types import Message, canonical_json + +SESSION_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$") +HISTORY_SCHEMA = "osiris.runtime.history.v1" +_GENESIS = "0" * 64 + + +class HistoryIntegrityError(RuntimeError): + """A session history file does not verify; it is not used.""" + + +class HistoryProvider(ABC): + @abstractmethod + async def get_messages(self, session_id: str) -> List[Message]: + """Every message stored for ``session_id``, oldest first.""" + + @abstractmethod + async def add_messages(self, session_id: str, messages: Sequence[Message]) -> int: + """Append ``messages``; return how many were stored.""" + + +class InMemoryHistoryProvider(HistoryProvider): + def __init__(self) -> None: + self._store: Dict[str, List[Message]] = {} + + async def get_messages(self, session_id: str) -> List[Message]: + return list(self._store.get(session_id, [])) + + async def add_messages(self, session_id: str, messages: Sequence[Message]) -> int: + self._store.setdefault(session_id, []).extend(messages) + return len(messages) + + +class FileHistoryProvider(HistoryProvider): + """One hash-chained JSONL file per session under ``directory``. + + Each line is ``{"schema", "seq", "prev", "message", "hash"}`` with + ``hash = sha256(prev + canonical_json(message))``. Reading verifies the whole chain and raises + ``HistoryIntegrityError`` on any break, so an edited history is never fed to a model.""" + + def __init__(self, directory: Union[str, "os.PathLike[str]"]) -> None: + self.directory = Path(directory).resolve() + self._lock = threading.Lock() + + def path_for(self, session_id: str) -> Path: + if not SESSION_ID_RE.match(session_id): + raise ValueError(f"session id {session_id!r} must match {SESSION_ID_RE.pattern}") + return self.directory / f"{session_id}.jsonl" + + def _read(self, session_id: str) -> List[Dict[str, Any]]: + path = self.path_for(session_id) + if not path.exists(): + return [] + entries: List[Dict[str, Any]] = [] + prev = _GENESIS + with open(path, encoding="utf-8") as f: + for n, line in enumerate(f): + if not line.strip(): + continue + try: + entry = json.loads(line) + except ValueError as exc: + raise HistoryIntegrityError(f"{path}: line {n + 1} is not JSON ({exc})") from None + expected = hashlib.sha256((prev + canonical_json(entry.get("message"))).encode("utf-8")).hexdigest() + if entry.get("schema") != HISTORY_SCHEMA or entry.get("seq") != len(entries) \ + or entry.get("prev") != prev or entry.get("hash") != expected: + raise HistoryIntegrityError(f"{path}: chain breaks at line {n + 1}") + entries.append(entry) + prev = expected + return entries + + def _get(self, session_id: str) -> List[Message]: + return [Message.from_dict(e["message"]) for e in self._read(session_id)] + + def _add(self, session_id: str, messages: Sequence[Message]) -> int: + with self._lock: + entries = self._read(session_id) + prev = entries[-1]["hash"] if entries else _GENESIS + seq = len(entries) + self.directory.mkdir(parents=True, exist_ok=True) + with open(self.path_for(session_id), "a", encoding="utf-8", newline="\n") as f: + for m in messages: + body = m.to_dict() + digest = hashlib.sha256((prev + canonical_json(body)).encode("utf-8")).hexdigest() + f.write(json.dumps({"schema": HISTORY_SCHEMA, "seq": seq, "prev": prev, "message": body, + "hash": digest}, sort_keys=True, ensure_ascii=False) + "\n") + prev, seq = digest, seq + 1 + f.flush() + os.fsync(f.fileno()) + return len(messages) + + async def get_messages(self, session_id: str) -> List[Message]: + return self._get(session_id) + + async def add_messages(self, session_id: str, messages: Sequence[Message]) -> int: + return self._add(session_id, messages) + + +@dataclass +class ContextAdditions: + """What a context provider adds to one run: system instructions and/or messages placed before + the caller's input.""" + + instructions: List[str] = field(default_factory=list) + messages: List[Message] = field(default_factory=list) + + +class ContextProvider(ABC): + @abstractmethod + async def before_run(self, session: Optional["AgentSession"], messages: Sequence[Message]) -> ContextAdditions: + """Context to add before the model sees ``messages``.""" + + @abstractmethod + async def after_run(self, session: Optional["AgentSession"], request: Sequence[Message], + response: Any) -> int: + """Observe a finished run; return how many items were recorded (0 when nothing was).""" + + +class AgentSession: + """Conversation state shared by successive runs: an id, a history provider and a state dict.""" + + def __init__(self, session_id: Optional[str] = None, *, history: Optional[HistoryProvider] = None, + state: Optional[Dict[str, Any]] = None) -> None: + self.session_id = session_id or uuid.uuid4().hex + if not SESSION_ID_RE.match(self.session_id): + raise ValueError(f"session id {self.session_id!r} must match {SESSION_ID_RE.pattern}") + self.history: HistoryProvider = history or InMemoryHistoryProvider() + self.state: Dict[str, Any] = dict(state or {}) + + def __repr__(self) -> str: + return f"AgentSession({self.session_id!r}, history={type(self.history).__name__})" diff --git a/osiris_cli/runtime/_telemetry.py b/osiris_cli/runtime/_telemetry.py new file mode 100644 index 00000000..c4372c71 --- /dev/null +++ b/osiris_cli/runtime/_telemetry.py @@ -0,0 +1,186 @@ +# Portions adapted from microsoft/agent-framework@567e4d458b59b83ac9b19088a43a2853094c6df1 +# python/packages/core/agent_framework/observability.py (OtelAttr: the OpenTelemetry GenAI +# semantic-convention attribute names, and one span per agent run, model call and tool call). +# MIT License, Copyright (c) Microsoft Corporation. See THIRD_PARTY_NOTICES.md and PORT_MAP.md. +"""Spans for agent runs, model calls and tool calls. + +Every run records its spans in a ``SpanRecorder`` whether or not OpenTelemetry is installed. When +the ``opentelemetry`` API is importable, the same spans are also emitted through it, so any OTel +exporter can collect them. The recorder's ``summary`` (counts, tokens, models, errors, and a +SHA-256 digest over the spans with timings left out) is what the run record writes into the task +ledger's ``task_close`` entry; the ledger never gets a second, competing span store. +""" + +from __future__ import annotations + +import contextlib +import time +from dataclasses import dataclass, field +from typing import Any, Dict, Iterator, List, Optional + +from ._middleware import ( + AgentContext, + AgentMiddleware, + CallNext, + ChatContext, + ChatMiddleware, + FunctionInvocationContext, + FunctionMiddleware, +) +from ._types import AgentResponse, ChatResponse, sha256_json + +# OpenTelemetry GenAI semantic-convention attributes (names as in the source's OtelAttr). +OPERATION = "gen_ai.operation.name" +PROVIDER_NAME = "gen_ai.provider.name" +REQUEST_MODEL = "gen_ai.request.model" +RESPONSE_MODEL = "gen_ai.response.model" +FINISH_REASONS = "gen_ai.response.finish_reasons" +INPUT_TOKENS = "gen_ai.usage.input_tokens" +OUTPUT_TOKENS = "gen_ai.usage.output_tokens" +TOOL_NAME = "gen_ai.tool.name" +TOOL_CALL_ID = "gen_ai.tool.call.id" +AGENT_NAME = "gen_ai.agent.name" +AGENT_ID = "gen_ai.agent.id" +CONVERSATION_ID = "gen_ai.conversation.id" + +OP_INVOKE_AGENT = "invoke_agent" +OP_CHAT = "chat" +OP_EXECUTE_TOOL = "execute_tool" + +TRACER_NAME = "osiris.runtime" + + +def otel_tracer() -> Any: + """The OpenTelemetry tracer for the runtime, or None when the API is not installed.""" + try: + from opentelemetry import trace # type: ignore[import-not-found] + except ImportError: + return None + return trace.get_tracer(TRACER_NAME) + + +@dataclass +class SpanRecord: + name: str + operation: str + attributes: Dict[str, Any] = field(default_factory=dict) + start_ns: int = 0 + end_ns: int = 0 + status: str = "OK" + error: str = "" + + @property + def duration_ms(self) -> float: + return (self.end_ns - self.start_ns) / 1e6 if self.end_ns else 0.0 + + def to_dict(self) -> Dict[str, Any]: + return {"name": self.name, "operation": self.operation, "attributes": dict(self.attributes), + "status": self.status, "error": self.error, "duration_ms": round(self.duration_ms, 3)} + + def digest_body(self) -> Dict[str, Any]: + """The span without timings: identical runs give identical digests.""" + return {"name": self.name, "operation": self.operation, "attributes": dict(sorted(self.attributes.items())), + "status": self.status, "error": self.error} + + +class SpanRecorder: + """Collects the spans of one run, and mirrors them to OpenTelemetry when a tracer is given.""" + + def __init__(self, tracer: Any = None) -> None: + self.tracer = tracer + self.spans: List[SpanRecord] = [] + + @contextlib.contextmanager + def span(self, name: str, operation: str, attributes: Optional[Dict[str, Any]] = None) -> Iterator[SpanRecord]: + record = SpanRecord(name, operation, {OPERATION: operation, **(attributes or {})}, start_ns=time.monotonic_ns()) + otel_cm = self.tracer.start_as_current_span(name) if self.tracer is not None else contextlib.nullcontext() + with otel_cm as otel_span: + try: + yield record + except BaseException as exc: + record.status = "ERROR" + record.error = type(exc).__name__ + if otel_span is not None: + otel_span.record_exception(exc) + raise + finally: + record.end_ns = time.monotonic_ns() + self.spans.append(record) + if otel_span is not None: + for key, value in record.attributes.items(): + if isinstance(value, (str, bool, int, float)): + otel_span.set_attribute(key, value) + elif isinstance(value, (list, tuple)) and all(isinstance(v, str) for v in value): + otel_span.set_attribute(key, list(value)) + if record.status == "ERROR": + from opentelemetry.trace import Status, StatusCode # type: ignore[import-not-found] + otel_span.set_status(Status(StatusCode.ERROR, record.error)) + + def to_dicts(self) -> List[Dict[str, Any]]: + return [s.to_dict() for s in self.spans] + + def digest(self) -> str: + return sha256_json([s.digest_body() for s in self.spans]) + + def summary(self) -> Dict[str, Any]: + counts: Dict[str, int] = {} + input_tokens = output_tokens = 0 + models = set() + for s in self.spans: + counts[s.operation] = counts.get(s.operation, 0) + 1 + if s.operation == OP_CHAT: + input_tokens += int(s.attributes.get(INPUT_TOKENS) or 0) + output_tokens += int(s.attributes.get(OUTPUT_TOKENS) or 0) + if s.attributes.get(RESPONSE_MODEL): + models.add(str(s.attributes[RESPONSE_MODEL])) + return {"spans": len(self.spans), "by_operation": dict(sorted(counts.items())), + "errors": sum(1 for s in self.spans if s.status == "ERROR"), + "input_tokens": input_tokens, "output_tokens": output_tokens, + "response_models": sorted(models), "sha256": self.digest()} + + +def _usage_attributes(usage: Any, record: SpanRecord) -> None: + if usage is None: + return + if usage.input_token_count is not None: + record.attributes[INPUT_TOKENS] = usage.input_token_count + if usage.output_token_count is not None: + record.attributes[OUTPUT_TOKENS] = usage.output_token_count + + +class TelemetryAgentMiddleware(AgentMiddleware): + async def process(self, context: AgentContext, call_next: CallNext) -> None: + attrs = {AGENT_NAME: context.run.agent_name, AGENT_ID: getattr(context.agent, "id", ""), + "osiris.run_id": context.run.run_id} + if context.session is not None: + attrs[CONVERSATION_ID] = context.session.session_id + with context.run.recorder.span(f"{OP_INVOKE_AGENT} {context.run.agent_name}", OP_INVOKE_AGENT, attrs) as rec: + await call_next() + result = context.result + if isinstance(result, AgentResponse): + _usage_attributes(result.usage, rec) + rec.attributes["osiris.status"] = result.status + + +class TelemetryChatMiddleware(ChatMiddleware): + async def process(self, context: ChatContext, call_next: CallNext) -> None: + requested = context.options.get("model") or getattr(context.client, "model_id", "") or "" + attrs = {PROVIDER_NAME: getattr(context.client, "provider_name", "") or "", REQUEST_MODEL: requested} + with context.run.recorder.span(f"{OP_CHAT} {requested}".strip(), OP_CHAT, attrs) as rec: + await call_next() + result = context.result + if isinstance(result, ChatResponse): + _usage_attributes(result.usage, rec) + rec.attributes[RESPONSE_MODEL] = result.model_id + rec.attributes[FINISH_REASONS] = [result.finish_reason] + + +class TelemetryFunctionMiddleware(FunctionMiddleware): + async def process(self, context: FunctionInvocationContext, call_next: CallNext) -> None: + name = context.function.name + attrs = {TOOL_NAME: name, TOOL_CALL_ID: context.call_id} + with context.run.recorder.span(f"{OP_EXECUTE_TOOL} {name}", OP_EXECUTE_TOOL, attrs) as rec: + await call_next() + refusal = getattr(context.result, "refusal_reason", "") + if refusal: + rec.attributes["osiris.refused"] = True diff --git a/osiris_cli/runtime/_tools.py b/osiris_cli/runtime/_tools.py new file mode 100644 index 00000000..6c67e271 --- /dev/null +++ b/osiris_cli/runtime/_tools.py @@ -0,0 +1,285 @@ +# Portions adapted from microsoft/agent-framework@567e4d458b59b83ac9b19088a43a2853094c6df1 +# python/packages/core/agent_framework/_tools.py (FunctionTool, the @tool decorator, approval_mode, +# schema-checked arguments and FunctionInvocationConfiguration). MIT License, Copyright (c) +# Microsoft Corporation. See THIRD_PARTY_NOTICES.md and PORT_MAP.md. +"""Tools a model may call. + +``@tool`` turns a typed Python function into a ``FunctionTool``: the JSON schema comes from the type +hints (no pydantic), is checked by ``osiris_cli.providers.schema_guard`` so no keyword is silently +ignored, and is offered to providers through ``osiris_cli.providers.tool_shim``. Every call's +arguments are validated against that schema before the function runs. + +OSIRIS additions to the source's tool model, which the governance stack enforces: + +* ``effects`` declares what the tool does: ``none``, ``read``, ``write``, ``exec``, ``network`` or + ``hardware``. A run's permissions decide which effects it may use. +* ``path_params`` / ``write_params`` name the arguments that are file paths (read or written), so + their values can be confined to the workspace, kept off credential files and, for writes, off + governance-protected files. +* ``code_params`` name arguments that carry Python source, which must pass the SYS-025 AST firewall. +""" + +from __future__ import annotations + +import asyncio +import enum +import inspect +import typing +from dataclasses import dataclass +from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple + +from osiris_cli.providers.schema_guard import check_schema, validate +from osiris_cli.providers.tool_shim import TOOL_NAME_RE, ToolSpec + +APPROVAL_NEVER = "never_require" +APPROVAL_ALWAYS = "always_require" +APPROVAL_MODES = (APPROVAL_NEVER, APPROVAL_ALWAYS) + +EFFECTS = ("none", "read", "write", "exec", "network", "hardware") + + +class ToolError(Exception): + """A tool was declared or called incorrectly.""" + + +class ToolArgumentError(ToolError): + """The model's arguments failed the tool's schema. The message is safe to show the model.""" + + +@dataclass +class InvocationConfig: + """Limits on the tool loop of one run (the source's FunctionInvocationConfiguration). + + ``max_iterations`` caps model round-trips that may call tools; ``max_function_calls`` caps tool + executions across the run; ``max_duration_seconds`` caps the loop's wall time. When a limit or + ``max_consecutive_errors`` is reached the loop stops offering tools and asks the model for a + plain answer. The task budget from ``task_context`` applies on top of these. + ``include_detailed_errors`` is off by default because exception text can carry secrets.""" + + max_iterations: int = 10 + max_function_calls: Optional[int] = None + max_duration_seconds: Optional[float] = None + max_consecutive_errors: int = 3 + terminate_on_unknown_calls: bool = False + include_detailed_errors: bool = False + + def __post_init__(self) -> None: + if self.max_iterations < 1: + raise ValueError("max_iterations must be at least 1") + if self.max_function_calls is not None and self.max_function_calls < 0: + raise ValueError("max_function_calls cannot be negative") + if self.max_duration_seconds is not None and self.max_duration_seconds <= 0: + raise ValueError("max_duration_seconds must be positive") + if self.max_consecutive_errors < 1: + raise ValueError("max_consecutive_errors must be at least 1") + + +_PRIMITIVES = {str: "string", int: "integer", float: "number", bool: "boolean"} +_ARRAYS = (list, tuple, set, frozenset) + + +def _strip_optional(tp: Any) -> Tuple[Any, bool]: + origin = typing.get_origin(tp) + if origin is typing.Union: + args = typing.get_args(tp) + non_none = [a for a in args if a is not type(None)] + if len(non_none) < len(args): + if len(non_none) == 1: + return non_none[0], True + return typing.Union[tuple(non_none)], True + return tp, False + + +def type_to_schema(tp: Any) -> Dict[str, Any]: + """JSON schema for a type hint. Raises TypeError for a hint it cannot express exactly.""" + origin = typing.get_origin(tp) + args = typing.get_args(tp) + if origin is typing.Annotated: + schema = type_to_schema(args[0]) + for meta in args[1:]: + if isinstance(meta, str): + schema["description"] = meta + elif isinstance(meta, Mapping): + schema.update(meta) + return schema + base, optional = _strip_optional(tp) + if optional: + schema = type_to_schema(base) + if isinstance(schema.get("type"), str): + schema["type"] = [schema["type"], "null"] + elif "anyOf" in schema: + schema["anyOf"] = list(schema["anyOf"]) + [{"type": "null"}] + else: + schema["nullable"] = True + if "enum" in schema and None not in schema["enum"]: + schema["enum"] = list(schema["enum"]) + [None] + return schema + if origin is typing.Union: + return {"anyOf": [type_to_schema(a) for a in args]} + if origin is typing.Literal: + values = list(args) + kinds = {type(v) for v in values} + schema = {"enum": values} + if len(kinds) == 1 and next(iter(kinds)) in _PRIMITIVES: + schema["type"] = _PRIMITIVES[next(iter(kinds))] + return schema + if tp is Any: + return {} + if tp is type(None): + return {"type": "null"} + if isinstance(tp, type) and issubclass(tp, enum.Enum): + values = [m.value for m in tp] + kinds = {type(v) for v in values} + schema = {"enum": values} + if len(kinds) == 1 and next(iter(kinds)) in _PRIMITIVES: + schema["type"] = _PRIMITIVES[next(iter(kinds))] + return schema + if tp in _PRIMITIVES: + return {"type": _PRIMITIVES[tp]} + container = origin or tp + if container in _ARRAYS or (isinstance(container, type) and container.__module__ == "collections.abc" + and container.__name__ in ("Sequence", "MutableSequence", "Set")): + schema = {"type": "array"} + if container is tuple and args and not (len(args) == 2 and args[1] is Ellipsis): + # tuple[X, X] is a fixed-length array; tuple[X, Y] has no exact JSON-schema form here + if len(set(args)) > 1: + raise TypeError(f"heterogeneous tuple {tp!r} cannot be expressed as a JSON array schema") + schema["minItems"] = schema["maxItems"] = len(args) + if args: + schema["items"] = type_to_schema(args[0]) + if container in (set, frozenset) or getattr(container, "__name__", "") == "Set": + schema["uniqueItems"] = True + return schema + if container is dict or (isinstance(container, type) and container.__module__ == "collections.abc" + and container.__name__ in ("Mapping", "MutableMapping")): + if args and args[0] is not str: + raise TypeError(f"{tp!r}: JSON object keys are strings") + schema = {"type": "object"} + if len(args) == 2 and args[1] is not Any: + schema["additionalProperties"] = type_to_schema(args[1]) + return schema + raise TypeError(f"unsupported tool parameter type {tp!r}") + + +def _description(func: Callable[..., Any]) -> str: + doc = inspect.getdoc(func) or "" + return doc.split("\n\n", 1)[0].strip() + + +def schema_from_signature(func: Callable[..., Any]) -> Dict[str, Any]: + """Object schema for ``func``'s parameters. Every parameter needs a type hint; *args and + **kwargs are refused, so the schema says exactly what the function accepts.""" + signature = inspect.signature(func) + hints = typing.get_type_hints(func, include_extras=True) + properties: Dict[str, Any] = {} + required: List[str] = [] + for name, param in signature.parameters.items(): + if param.kind in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD): + raise TypeError(f"tool {func.__name__!r}: *args/**kwargs cannot be described to a model") + if param.kind is inspect.Parameter.POSITIONAL_ONLY: + raise TypeError(f"tool {func.__name__!r}: positional-only parameter {name!r} cannot be passed by name") + if name not in hints: + raise TypeError(f"tool {func.__name__!r}: parameter {name!r} has no type hint") + schema = type_to_schema(hints[name]) + if param.default is inspect.Parameter.empty: + required.append(name) + elif isinstance(param.default, (str, int, float, bool)) or param.default is None: + schema["default"] = param.default + properties[name] = schema + out: Dict[str, Any] = {"type": "object", "properties": properties, "additionalProperties": False} + if required: + out["required"] = required + check_schema(out, f"#/tools/{func.__name__}") + return out + + +class FunctionTool: + """A function the model may call, with its schema, approval mode and declared effects.""" + + def __init__(self, func: Callable[..., Any], *, name: Optional[str] = None, description: Optional[str] = None, + approval_mode: str = APPROVAL_NEVER, effects: Sequence[str] = ("none",), + path_params: Sequence[str] = (), write_params: Sequence[str] = (), + code_params: Sequence[str] = (), parameters: Optional[Mapping[str, Any]] = None) -> None: + if not callable(func): + raise ToolError("a tool wraps a callable") + self.func = func + self.name = name or func.__name__ + if not TOOL_NAME_RE.match(self.name): + raise ToolError(f"tool name {self.name!r} must match {TOOL_NAME_RE.pattern}") + self.description = (description if description is not None else _description(func)).strip() + if not self.description: + raise ToolError(f"tool {self.name!r} needs a description (a docstring or description=)") + if approval_mode not in APPROVAL_MODES: + raise ToolError(f"approval_mode must be one of {APPROVAL_MODES}") + self.approval_mode = approval_mode + self.effects = tuple(effects) + unknown = [e for e in self.effects if e not in EFFECTS] + if unknown or not self.effects: + raise ToolError(f"tool {self.name!r}: effects {unknown or '()'} not in {EFFECTS}") + self.parameters: Dict[str, Any] = dict(parameters) if parameters is not None else schema_from_signature(func) + check_schema(self.parameters, f"#/tools/{self.name}") + self.path_params = tuple(path_params) + self.write_params = tuple(write_params) + self.code_params = tuple(code_params) + props = self.parameters.get("properties", {}) + for label, names in (("path_params", self.path_params), ("write_params", self.write_params), + ("code_params", self.code_params)): + for p in names: + if p not in props: + raise ToolError(f"tool {self.name!r}: {label} names {p!r}, which is not a parameter") + if props[p].get("type") not in ("string", ["string", "null"]): + raise ToolError(f"tool {self.name!r}: {label} entry {p!r} must be a string parameter") + if self.write_params and "write" not in self.effects: + raise ToolError(f"tool {self.name!r} writes {list(self.write_params)} but does not declare the 'write' effect") + self.spec = ToolSpec(self.name, self.description, self.parameters) + + def __repr__(self) -> str: + return f"FunctionTool({self.name!r}, effects={self.effects}, approval_mode={self.approval_mode!r})" + + def validate_arguments(self, arguments: Mapping[str, Any]) -> Dict[str, Any]: + if not isinstance(arguments, Mapping): + raise ToolArgumentError(f"{self.name}: arguments must be an object") + args = dict(arguments) + errors = validate(args, self.parameters) + if errors: + raise ToolArgumentError(f"{self.name}: " + "; ".join(errors)) + return args + + async def invoke(self, arguments: Mapping[str, Any]) -> Any: + """Validate ``arguments`` and run the function; a sync function runs in a worker thread.""" + args = self.validate_arguments(arguments) + if inspect.iscoroutinefunction(self.func): + return await self.func(**args) + return await asyncio.to_thread(self.func, **args) + + +def tool(func: Optional[Callable[..., Any]] = None, **options: Any) -> Any: + """Decorate a typed function as a ``FunctionTool``, with or without options:: + + @tool + def add(a: int, b: int) -> int: + '''Add two integers.''' + + @tool(effects=("read",), path_params=("path",)) + def count_lines(path: str) -> int: + '''Count the lines in a workspace file.''' + """ + if func is not None: + return FunctionTool(func, **options) + + def wrap(f: Callable[..., Any]) -> FunctionTool: + return FunctionTool(f, **options) + return wrap + + +def normalize_tools(tools: Sequence[Any]) -> List[FunctionTool]: + """FunctionTools and plain functions -> FunctionTools with unique names.""" + out: List[FunctionTool] = [] + seen = set() + for t in tools: + ft = t if isinstance(t, FunctionTool) else FunctionTool(t) + if ft.name in seen: + raise ToolError(f"two tools are named {ft.name!r}") + seen.add(ft.name) + out.append(ft) + return out diff --git a/osiris_cli/runtime/_types.py b/osiris_cli/runtime/_types.py new file mode 100644 index 00000000..3d6c0b97 --- /dev/null +++ b/osiris_cli/runtime/_types.py @@ -0,0 +1,342 @@ +# Portions adapted from microsoft/agent-framework@567e4d458b59b83ac9b19088a43a2853094c6df1 +# python/packages/core/agent_framework/_types.py (Message, Content, UsageDetails, ChatResponse, +# AgentResponse and their streaming updates). MIT License, Copyright (c) Microsoft Corporation. +# See THIRD_PARTY_NOTICES.md and PORT_MAP.md. +"""Typed messages and content for the OSIRIS runtime. + +A conversation is a list of ``Message`` objects; each message holds ``Content`` items of one of five +kinds: text, a model's function call, a function result, an error, or token usage. Everything is a +plain dataclass that serializes to canonical JSON, so a prompt or a response can be hashed into a +ledger entry byte-for-byte the same on Node Alpha and Node Beta. +""" + +from __future__ import annotations + +import hashlib +import json +import uuid +from dataclasses import dataclass, field +from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Union + +ROLE_SYSTEM = "system" +ROLE_USER = "user" +ROLE_ASSISTANT = "assistant" +ROLE_TOOL = "tool" +ROLES = (ROLE_SYSTEM, ROLE_USER, ROLE_ASSISTANT, ROLE_TOOL) + +CONTENT_TEXT = "text" +CONTENT_FUNCTION_CALL = "function_call" +CONTENT_FUNCTION_RESULT = "function_result" +CONTENT_ERROR = "error" +CONTENT_USAGE = "usage" +CONTENT_TYPES = (CONTENT_TEXT, CONTENT_FUNCTION_CALL, CONTENT_FUNCTION_RESULT, CONTENT_ERROR, CONTENT_USAGE) + +FINISH_STOP = "stop" +FINISH_LENGTH = "length" +FINISH_TOOL_CALLS = "tool_calls" +FINISH_ERROR = "error" +FINISH_REASONS = (FINISH_STOP, FINISH_LENGTH, FINISH_TOOL_CALLS, FINISH_ERROR) + + +def canonical_json(value: Any) -> str: + """Sorted keys, no spaces, UTF-8 kept: the bytes every digest in the runtime is taken over.""" + return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=_jsonable) + + +def sha256_json(value: Any) -> str: + return hashlib.sha256(canonical_json(value).encode("utf-8")).hexdigest() + + +def _jsonable(value: Any) -> Any: + """Fallback for values json cannot encode: dataclasses with ``to_dict``, then their repr.""" + to_dict = getattr(value, "to_dict", None) + if callable(to_dict): + return to_dict() + if isinstance(value, (set, frozenset)): + return sorted(_jsonable(v) if not isinstance(v, (str, int, float, bool)) else v for v in value) + return repr(value) + + +@dataclass +class UsageDetails: + """Token counts reported by a model. ``None`` means the provider did not report that count.""" + + input_token_count: Optional[int] = None + output_token_count: Optional[int] = None + + @property + def total_token_count(self) -> Optional[int]: + if self.input_token_count is None and self.output_token_count is None: + return self.input_token_count + return (self.input_token_count or 0) + (self.output_token_count or 0) + + def __add__(self, other: "UsageDetails") -> "UsageDetails": + def add(a: Optional[int], b: Optional[int]) -> Optional[int]: + if a is None and b is None: + return a + return (a or 0) + (b or 0) + + return UsageDetails(add(self.input_token_count, other.input_token_count), + add(self.output_token_count, other.output_token_count)) + + def to_dict(self) -> Dict[str, Any]: + return {"input_token_count": self.input_token_count, "output_token_count": self.output_token_count, + "total_token_count": self.total_token_count} + + +@dataclass +class Content: + """One item inside a message. + + ``exception`` on a function result carries the refusal or failure text the model is allowed to + see. A Python traceback never goes here: the tool loop only fills it with exception text when + ``InvocationConfig.include_detailed_errors`` is set. + """ + + type: str + text: str = "" + call_id: str = "" + name: str = "" + arguments: Dict[str, Any] = field(default_factory=dict) + result: Any = None + exception: str = "" + usage: Optional[UsageDetails] = None + additional_properties: Dict[str, Any] = field(default_factory=dict) + + def __post_init__(self) -> None: + if self.type not in CONTENT_TYPES: + raise ValueError(f"unknown content type {self.type!r}; expected one of {CONTENT_TYPES}") + if self.type in (CONTENT_FUNCTION_CALL, CONTENT_FUNCTION_RESULT) and not self.call_id: + raise ValueError(f"{self.type} content needs a call_id") + if self.type == CONTENT_FUNCTION_CALL and not self.name: + raise ValueError("function_call content needs a name") + if not isinstance(self.arguments, dict): + raise ValueError("function call arguments must be a dict") + + @classmethod + def from_text(cls, text: str) -> "Content": + return cls(CONTENT_TEXT, text=text) + + @classmethod + def from_function_call(cls, call_id: str, name: str, arguments: Optional[Mapping[str, Any]] = None) -> "Content": + return cls(CONTENT_FUNCTION_CALL, call_id=call_id, name=name, arguments=dict(arguments or {})) + + @classmethod + def from_function_result(cls, call_id: str, result: Any = None, *, name: str = "", + exception: str = "") -> "Content": + return cls(CONTENT_FUNCTION_RESULT, call_id=call_id, name=name, result=result, exception=exception) + + @classmethod + def from_error(cls, message: str) -> "Content": + return cls(CONTENT_ERROR, text=message) + + @classmethod + def from_usage(cls, usage: UsageDetails) -> "Content": + return cls(CONTENT_USAGE, usage=usage) + + @property + def is_error_result(self) -> bool: + return self.type == CONTENT_FUNCTION_RESULT and bool(self.exception) + + def result_text(self) -> str: + """What a provider is sent for a function result: the refusal/error text, or the result.""" + if self.exception: + return self.exception + if isinstance(self.result, str): + return self.result + return canonical_json(self.result) + + def to_dict(self) -> Dict[str, Any]: + out: Dict[str, Any] = {"type": self.type} + if self.text: + out["text"] = self.text + if self.call_id: + out["call_id"] = self.call_id + if self.name: + out["name"] = self.name + if self.type == CONTENT_FUNCTION_CALL: + out["arguments"] = self.arguments + if self.type == CONTENT_FUNCTION_RESULT: + out["result"] = self.result + if self.exception: + out["exception"] = self.exception + if self.usage is not None: + out["usage"] = self.usage.to_dict() + if self.additional_properties: + out["additional_properties"] = self.additional_properties + return out + + @classmethod + def from_dict(cls, data: Mapping[str, Any]) -> "Content": + usage = data.get("usage") + return cls( + type=data["type"], text=data.get("text", ""), call_id=data.get("call_id", ""), + name=data.get("name", ""), arguments=dict(data.get("arguments") or {}), result=data.get("result"), + exception=data.get("exception", ""), + usage=UsageDetails(usage.get("input_token_count"), usage.get("output_token_count")) if usage else None, + additional_properties=dict(data.get("additional_properties") or {}), + ) + + +@dataclass +class Message: + role: str + contents: List[Content] = field(default_factory=list) + author_name: str = "" + message_id: str = field(default_factory=lambda: uuid.uuid4().hex) + additional_properties: Dict[str, Any] = field(default_factory=dict) + + def __post_init__(self) -> None: + if self.role not in ROLES: + raise ValueError(f"unknown role {self.role!r}; expected one of {ROLES}") + if isinstance(self.contents, str): + self.contents = [Content.from_text(self.contents)] + for c in self.contents: + if not isinstance(c, Content): + raise TypeError(f"message contents must be Content, got {type(c).__name__}") + + @classmethod + def system(cls, text: str) -> "Message": + return cls(ROLE_SYSTEM, [Content.from_text(text)]) + + @classmethod + def user(cls, text: str) -> "Message": + return cls(ROLE_USER, [Content.from_text(text)]) + + @classmethod + def assistant(cls, text: str) -> "Message": + return cls(ROLE_ASSISTANT, [Content.from_text(text)]) + + @property + def text(self) -> str: + return "".join(c.text for c in self.contents if c.type == CONTENT_TEXT) + + @property + def function_calls(self) -> List[Content]: + return [c for c in self.contents if c.type == CONTENT_FUNCTION_CALL] + + @property + def function_results(self) -> List[Content]: + return [c for c in self.contents if c.type == CONTENT_FUNCTION_RESULT] + + def to_dict(self) -> Dict[str, Any]: + out: Dict[str, Any] = {"role": self.role, "contents": [c.to_dict() for c in self.contents], + "message_id": self.message_id} + if self.author_name: + out["author_name"] = self.author_name + if self.additional_properties: + out["additional_properties"] = self.additional_properties + return out + + def content_dict(self) -> Dict[str, Any]: + """What the message says, without its random id: the form that prompt digests use.""" + return {"role": self.role, "contents": [c.to_dict() for c in self.contents]} + + @classmethod + def from_dict(cls, data: Mapping[str, Any]) -> "Message": + return cls(role=data["role"], contents=[Content.from_dict(c) for c in data.get("contents", [])], + author_name=data.get("author_name", ""), message_id=data.get("message_id") or uuid.uuid4().hex, + additional_properties=dict(data.get("additional_properties") or {})) + + +MessageInput = Union[None, str, Message, Sequence[Union[str, Message]]] + + +def normalize_messages(messages: MessageInput) -> List[Message]: + """A string, a message, or a list of either -> a fresh list of messages (strings are user turns).""" + if messages is None: + return [] + if isinstance(messages, (str, Message)): + messages = [messages] + out: List[Message] = [] + for m in messages: + if isinstance(m, str): + out.append(Message.user(m)) + elif isinstance(m, Message): + out.append(m) + else: + raise TypeError(f"expected str or Message, got {type(m).__name__}") + return out + + +def _assistant_text(messages: Iterable[Message]) -> str: + return "\n".join(m.text for m in messages if m.role == ROLE_ASSISTANT and m.text) + + +@dataclass +class ChatResponse: + """One model call's answer.""" + + messages: List[Message] = field(default_factory=list) + model_id: str = "" + finish_reason: str = FINISH_STOP + usage: UsageDetails = field(default_factory=UsageDetails) + response_id: str = "" + + @property + def text(self) -> str: + return _assistant_text(self.messages) + + @property + def function_calls(self) -> List[Content]: + return [c for m in self.messages for c in m.function_calls] + + def to_dict(self) -> Dict[str, Any]: + return {"messages": [m.content_dict() for m in self.messages], "model_id": self.model_id, + "finish_reason": self.finish_reason, "usage": self.usage.to_dict()} + + +@dataclass +class ChatResponseUpdate: + """One streamed chunk of a model call.""" + + contents: List[Content] = field(default_factory=list) + role: str = ROLE_ASSISTANT + model_id: str = "" + finish_reason: Optional[str] = None + + @property + def text(self) -> str: + return "".join(c.text for c in self.contents if c.type == CONTENT_TEXT) + + +@dataclass +class AgentResponse: + """What one agent run produced. + + ``status`` is the run's terminal state as written to the task ledger (SUCCESS, BLOCKED, + STOPPED_BUDGET or ERROR). ``governance`` holds what the governance stack decided about the run + (evidence firewall decision, refusals, provenance); ``telemetry`` holds the run's spans. + """ + + messages: List[Message] = field(default_factory=list) + agent_name: str = "" + run_id: str = "" + usage: UsageDetails = field(default_factory=UsageDetails) + finish_reason: str = FINISH_STOP + model_id: str = "" + status: str = "SUCCESS" + governance: Dict[str, Any] = field(default_factory=dict) + telemetry: List[Dict[str, Any]] = field(default_factory=list) + + @property + def text(self) -> str: + return _assistant_text(self.messages) + + def to_dict(self) -> Dict[str, Any]: + return {"messages": [m.to_dict() for m in self.messages], "agent_name": self.agent_name, + "run_id": self.run_id, "usage": self.usage.to_dict(), "finish_reason": self.finish_reason, + "model_id": self.model_id, "status": self.status, "governance": self.governance} + + +@dataclass +class AgentResponseUpdate: + contents: List[Content] = field(default_factory=list) + role: str = ROLE_ASSISTANT + agent_name: str = "" + message_id: str = "" + run_id: str = "" + + @property + def text(self) -> str: + return "".join(c.text for c in self.contents if c.type == CONTENT_TEXT) diff --git a/osiris_cli/runtime/demo.py b/osiris_cli/runtime/demo.py new file mode 100644 index 00000000..1955b38b --- /dev/null +++ b/osiris_cli/runtime/demo.py @@ -0,0 +1,102 @@ +"""A governed agent with one tool, end to end. + + python -m osiris_cli.runtime.demo --fake # scripted model, no Ollama needed + python -m osiris_cli.runtime.demo --model qwen2.5-coder:7b + +The agent may call ``count_lines`` (a read-only tool confined to the workspace) to answer how many +lines a file has. With a real model the demo first checks that Ollama is reachable and the model is +installed; nothing is written to the task ledger unless that check passes. It prints the answer, +the run's status, what governance decided, and whether the task ledger still verifies. +""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path +from typing import Any, List, Optional, Sequence + +from . import Agent, GovernanceConfig, ProviderChatClient, tool +from ._types import ( + FINISH_TOOL_CALLS, + ROLE_ASSISTANT, + ROLE_TOOL, + ChatResponse, + Content, + Message, + UsageDetails, +) +from .testing import FakeChatClient + + +def make_count_lines(root: Path): + @tool(effects=("read",), path_params=("path",)) + def count_lines(path: str) -> int: + """Count the lines in a text file in the workspace (path relative to the workspace).""" + with open(root / path, encoding="utf-8", errors="replace") as f: + return sum(1 for _ in f) + return count_lines + + +def fake_model(target: str) -> FakeChatClient: + def first(messages: Sequence[Message], tools: Sequence[Any], options: Any) -> ChatResponse: + call = Content.from_function_call("call_1", "count_lines", {"path": target}) + return ChatResponse([Message(ROLE_ASSISTANT, [call])], model_id="fake-model", + finish_reason=FINISH_TOOL_CALLS, usage=UsageDetails(40, 12)) + + def second(messages: Sequence[Message], tools: Sequence[Any], options: Any) -> ChatResponse: + results = [c for m in messages if m.role == ROLE_TOOL for c in m.function_results] + last = results[-1] + text = (f"{target} has {last.result} lines." if not last.exception + else f"I could not count the lines: {last.exception}") + return ChatResponse([Message.assistant(text)], model_id="fake-model", usage=UsageDetails(60, 9)) + + return FakeChatClient([first, second], model_id="fake-model") + + +def ollama_model(model: str, host: Optional[str]) -> ProviderChatClient: + from osiris_cli.providers.ollama_compat import OllamaCompatibilityProvider + + provider = OllamaCompatibilityProvider(host=host, model=model, timeout=180.0) + installed = provider.installed_model_names() + if not installed: + raise SystemExit(f"Ollama is not reachable at {provider.host}; start it (ollama serve) and retry.") + if model not in installed: + raise SystemExit(f"Model {model!r} is not installed in Ollama (installed: {', '.join(installed)}); " + f"run: ollama pull {model}") + return ProviderChatClient(provider, model=model, flavor="ollama", timeout=180.0) + + +def main(argv: Optional[List[str]] = None) -> int: + parser = argparse.ArgumentParser(prog="python -m osiris_cli.runtime.demo", description=__doc__.split("\n\n")[0]) + parser.add_argument("--fake", action="store_true", help="use a scripted model instead of Ollama") + parser.add_argument("--model", default="qwen2.5-coder:7b", help="Ollama model tag (default: %(default)s)") + parser.add_argument("--host", default=None, help="Ollama base URL (default: $OLLAMA_HOST or localhost)") + parser.add_argument("--workspace", default=".", help="workspace root the tool may read (default: cwd)") + parser.add_argument("--file", default="README.md", help="file to ask about (default: %(default)s)") + args = parser.parse_args(argv) + + root = Path(args.workspace).resolve() + client = fake_model(args.file) if args.fake else ollama_model(args.model, args.host) + config = GovernanceConfig(workspace_root=str(root)) + agent = Agent(client, name="runtime-demo", tools=[make_count_lines(root)], governance=config, + instructions="Answer with the count_lines tool; never guess a number.") + response = agent.run_sync(f"How many lines are in {args.file}? Use the count_lines tool.") + + from osiris_cli.task_context import TaskLedger + verification = TaskLedger(config.resolved_ledger_path()).verify() + print(response.text or "(no answer)") + print(json.dumps({ + "status": response.status, "run_id": response.run_id, "model": response.model_id, + "evidence": response.governance.get("evidence", {}).get("decision"), + "refusals": response.governance.get("refusals", []), + "spans": [f"{s['operation']}:{s['status']}" for s in response.telemetry], + "ledger": config.resolved_ledger_path(), + "ledger_intact": verification.get("intact"), + }, indent=2)) + return 0 if response.status == "SUCCESS" and verification.get("intact") else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/osiris_cli/runtime/testing.py b/osiris_cli/runtime/testing.py new file mode 100644 index 00000000..0986cfa2 --- /dev/null +++ b/osiris_cli/runtime/testing.py @@ -0,0 +1,58 @@ +"""A scripted chat client for tests and offline demos. No network, no model.""" + +from __future__ import annotations + +from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Union + +from ._clients import ChatClient +from ._types import ( + FINISH_STOP, + FINISH_TOOL_CALLS, + ROLE_ASSISTANT, + ChatResponse, + Content, + Message, + UsageDetails, +) + +Responder = Callable[[Sequence[Message], Sequence[Any], Mapping[str, Any]], ChatResponse] +Script = Union[ChatResponse, str, Responder] + + +def text_response(text: str, *, model_id: str = "fake-model", usage: Optional[UsageDetails] = None) -> ChatResponse: + return ChatResponse([Message(ROLE_ASSISTANT, [Content.from_text(text)])], model_id=model_id, + finish_reason=FINISH_STOP, usage=usage or UsageDetails(10, 5)) + + +def call_response(name: str, arguments: Optional[Mapping[str, Any]] = None, *, call_id: str = "call_1", + model_id: str = "fake-model", text: str = "") -> ChatResponse: + contents = [Content.from_text(text)] if text else [] + contents.append(Content.from_function_call(call_id, name, dict(arguments or {}))) + return ChatResponse([Message(ROLE_ASSISTANT, contents)], model_id=model_id, finish_reason=FINISH_TOOL_CALLS, + usage=UsageDetails(10, 5)) + + +class FakeChatClient(ChatClient): + """Returns scripted responses in order. A script item may be a ``ChatResponse``, a string (a + text answer) or a function ``(messages, tools, options) -> ChatResponse``. Every call is kept in + ``calls`` so tests can check what the model was sent.""" + + provider_name = "fake" + + def __init__(self, script: Sequence[Script], *, model_id: str = "fake-model", repeat_last: bool = False) -> None: + self.script = list(script) + self.model_id = model_id + self.repeat_last = repeat_last + self.calls: List[Dict[str, Any]] = [] + + async def get_response(self, messages: Sequence[Message], *, tools: Sequence[Any] = (), + options: Optional[Mapping[str, Any]] = None) -> ChatResponse: + self.calls.append({"messages": list(messages), "tools": [t.name for t in tools], "options": dict(options or {})}) + if not self.script: + raise AssertionError("FakeChatClient ran out of scripted responses") + item = self.script[0] if (self.repeat_last and len(self.script) == 1) else self.script.pop(0) + if isinstance(item, ChatResponse): + return item + if isinstance(item, str): + return text_response(item, model_id=self.model_id) + return item(messages, tools, dict(options or {})) diff --git a/osiris_cli/task_context.py b/osiris_cli/task_context.py index 71b41d66..49ca8415 100644 --- a/osiris_cli/task_context.py +++ b/osiris_cli/task_context.py @@ -51,7 +51,7 @@ RISK_TIERS = ("LOW", "MEDIUM", "HIGH", "CRITICAL") COST_CLASSES = ("read_only", "workspace_write", "external_action", "hardware_action") -KINDS = ("code", "sprint_story", "capsule") +KINDS = ("code", "sprint_story", "capsule", "agent") # agent: an osiris_cli.runtime Agent run READ_TOOLS = ("grep_code", "list_dir", "read_file") WRITE_TOOL = "write_file" diff --git a/pyproject.toml b/pyproject.toml index a408fb86..d01e825a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -194,7 +194,7 @@ namespaces = true # bench_tasks has no __init__.py: a .py there would change o [tool.setuptools.package-data] # the benchmark task definitions are data the console and osiris_bench read from /bench_tasks bench_tasks = ["*/*", "*/*/*"] -osiris_cli = ["policy/*.json"] +osiris_cli = ["policy/*.json", "runtime/LICENSE-agent-framework.txt"] [tool.ruff] target-version = "py39" diff --git a/tests/runtime_support.py b/tests/runtime_support.py new file mode 100644 index 00000000..18b72008 --- /dev/null +++ b/tests/runtime_support.py @@ -0,0 +1,33 @@ +"""Shared helpers for the osiris_cli.runtime tests: a workspace, a private ledger and a governance +config that never touches the real $OSIRIS_HOME.""" + +from __future__ import annotations + +import asyncio +from pathlib import Path +from typing import Any + +from osiris_cli.runtime import GovernanceConfig +from osiris_cli.task_context import TaskLedger + + +def run(coro: Any) -> Any: + return asyncio.run(coro) + + +def governed(tmp_path: Path, **overrides: Any) -> GovernanceConfig: + """A GovernanceConfig whose workspace, task ledger and exchange log all live under tmp_path.""" + workspace = tmp_path / "ws" + workspace.mkdir(exist_ok=True) + fields = dict(workspace_root=str(workspace), ledger_path=str(tmp_path / "home" / "tasks" / "task_runs.jsonl"), + exchange_log=str(tmp_path / "home" / "living" / "exchanges.jsonl")) + fields.update(overrides) + return GovernanceConfig(**fields) + + +def ledger(config: GovernanceConfig) -> TaskLedger: + return TaskLedger(config.resolved_ledger_path()) + + +def entries(config: GovernanceConfig) -> list: + return list(ledger(config).entries()) diff --git a/tests/test_runtime_agent.py b/tests/test_runtime_agent.py new file mode 100644 index 00000000..199d84b2 --- /dev/null +++ b/tests/test_runtime_agent.py @@ -0,0 +1,225 @@ +"""The governed agent and its tool loop in osiris_cli.runtime. + +Loop limits and error wording mirror microsoft/agent-framework@567e4d4 +python/packages/core/tests/core/test_function_invocation_logic.py (max iterations forcing a final +answer without tools, unknown functions, consecutive-error limits, and error results without +exception detail unless include_detailed_errors is set).""" + +from __future__ import annotations + +import pytest + +from osiris_cli.runtime import ( + Agent, + AgentMiddleware, + ContextAdditions, + ContextProvider, + InvocationConfig, + Message, + MiddlewareFailure, + MiddlewareTermination, + agent_middleware, + chat_middleware, + function_middleware, + tool, +) +from osiris_cli.runtime.testing import FakeChatClient, call_response, text_response +from tests.runtime_support import entries, governed, run + + +@tool +def add(a: int, b: int) -> int: + """Add two integers.""" + return a + b + + +@tool +def explode(reason: str) -> str: + """Always fails.""" + raise RuntimeError(f"secret detail: {reason}") + + +def _results(response): + return [c for m in response.messages for c in m.function_results] + + +def test_tool_call_then_answer(tmp_path): + client = FakeChatClient([call_response("add", {"a": 2, "b": 3}), + lambda msgs, tools, opts: text_response(f"sum={msgs[-1].function_results[0].result}")]) + agent = Agent(client, tools=[add], governance=governed(tmp_path), instructions="Be exact.") + response = run(agent.run("add 2 and 3")) + assert response.text == "sum=5" + assert response.status == "SUCCESS" + assert [m.role for m in response.messages] == ["assistant", "tool", "assistant"] + assert client.calls[0]["messages"][0].role == "system" and client.calls[0]["tools"] == ["add"] + assert response.usage.total_token_count == 30 + + +def test_unknown_function_returns_an_error_result(tmp_path): + client = FakeChatClient([call_response("nope", {}), "done"]) + response = run(Agent(client, tools=[add], governance=governed(tmp_path)).run("x")) + assert _results(response)[0].exception == 'Error: Requested function "nope" not found.' + assert response.text == "done" + + +def test_unknown_function_can_terminate_the_run(tmp_path): + client = FakeChatClient([call_response("nope", {})]) + agent = Agent(client, tools=[add], governance=governed(tmp_path), + invocation=InvocationConfig(terminate_on_unknown_calls=True)) + with pytest.raises(MiddlewareFailure): + run(agent.run("x")) + assert [e["kind"] for e in entries(agent.governance.config)] == ["task_open", "task_close"] + assert entries(agent.governance.config)[-1]["status"] == "ERROR" + + +def test_errors_hide_exception_detail_by_default(tmp_path): + client = FakeChatClient([call_response("explode", {"reason": "x"}), "ok"]) + response = run(Agent(client, tools=[explode], governance=governed(tmp_path)).run("x")) + assert _results(response)[0].exception == "Error: Function failed." + + +def test_detailed_errors_when_enabled(tmp_path): + client = FakeChatClient([call_response("explode", {"reason": "x"}), "ok"]) + agent = Agent(client, tools=[explode], governance=governed(tmp_path), + invocation=InvocationConfig(include_detailed_errors=True)) + assert "secret detail: x" in _results(run(agent.run("x")))[0].exception + + +def test_argument_errors_are_reported_without_running_the_tool(tmp_path): + client = FakeChatClient([call_response("add", {"a": "two", "b": 3}), "ok"]) + response = run(Agent(client, tools=[add], governance=governed(tmp_path)).run("x")) + assert _results(response)[0].exception == "Error: Argument parsing failed." + assert response.governance.get("tool_calls") is None # never reached the tool policy + + +def test_max_iterations_forces_a_final_answer_without_tools(tmp_path): + client = FakeChatClient([call_response("add", {"a": 1, "b": 1}, call_id=f"c{i}") for i in range(2)] + ["final"]) + agent = Agent(client, tools=[add], governance=governed(tmp_path), invocation=InvocationConfig(max_iterations=2)) + response = run(agent.run("loop")) + assert response.text == "final" + assert [c["tools"] for c in client.calls] == [["add"], ["add"], []] + + +def test_consecutive_errors_stop_offering_tools(tmp_path): + client = FakeChatClient([call_response("explode", {"reason": str(i)}, call_id=f"c{i}") for i in range(2)] + ["gave up"]) + agent = Agent(client, tools=[explode], governance=governed(tmp_path), + invocation=InvocationConfig(max_consecutive_errors=2)) + assert run(agent.run("x")).text == "gave up" + assert client.calls[-1]["tools"] == [] + + +def test_function_call_limit_answers_remaining_calls(tmp_path): + from osiris_cli.runtime import ChatResponse, Content + from osiris_cli.runtime._types import ROLE_ASSISTANT + two_calls = ChatResponse([Message(ROLE_ASSISTANT, [Content.from_function_call("c1", "add", {"a": 1, "b": 2}), + Content.from_function_call("c2", "add", {"a": 3, "b": 4})])], + model_id="fake-model", finish_reason="tool_calls") + client = FakeChatClient([two_calls, "done"]) + agent = Agent(client, tools=[add], governance=governed(tmp_path), invocation=InvocationConfig(max_function_calls=1)) + results = _results(run(agent.run("x"))) + assert results[0].result == 3 + assert results[1].exception == "Not executed: the tool-call limit was reached." + + +def test_function_middleware_termination_settles_the_batch(tmp_path): + from osiris_cli.runtime import ChatResponse, Content + from osiris_cli.runtime._types import ROLE_ASSISTANT + + @function_middleware + async def stop_first(context, call_next): + raise MiddlewareTermination(result="halted") + + batch = ChatResponse([Message(ROLE_ASSISTANT, [Content.from_function_call("c1", "add", {"a": 1, "b": 2}), + Content.from_function_call("c2", "add", {"a": 3, "b": 4})])], + model_id="fake-model", finish_reason="tool_calls") + client = FakeChatClient([batch]) + response = run(Agent(client, tools=[add], middleware=[stop_first], governance=governed(tmp_path)).run("x")) + results = _results(response) + assert results[0].result == "halted" + assert results[1].exception.startswith("Not executed") + assert len(client.calls) == 1 + + +def test_user_agent_middleware_runs_inside_governance(tmp_path): + seen = [] + + class Tag(AgentMiddleware): + async def process(self, context, call_next): + seen.append(context.run.metadata.get("task_context") is not None) + await call_next() + context.result.governance["tagged"] = True + + agent = Agent(FakeChatClient(["hi"]), middleware=[Tag()], governance=governed(tmp_path)) + assert agent.pipelines["agent"][0] == "RunRecordMiddleware" and agent.pipelines["agent"][-1] == "Tag" + response = run(agent.run("hello")) + assert seen == [True] and response.governance["tagged"] is True + + +def test_chat_middleware_termination_ends_the_run(tmp_path): + @chat_middleware + async def no_model(context, call_next): + raise MiddlewareTermination("no model today") + + client = FakeChatClient(["never"]) + response = run(Agent(client, middleware=[no_model], governance=governed(tmp_path)).run("x")) + assert response.messages == [] and client.calls == [] + + +def test_session_history_carries_across_runs(tmp_path): + client = FakeChatClient(["first answer", "second answer"]) + agent = Agent(client, governance=governed(tmp_path)) + session = agent.new_session() + run(agent.run("one", session=session)) + run(agent.run("two", session=session)) + second = [m.text for m in client.calls[1]["messages"]] + assert second == ["one", "first answer", "two"] + + +def test_context_providers_add_instructions_and_observe_runs(tmp_path): + observed = [] + + class Notes(ContextProvider): + async def before_run(self, session, messages): + return ContextAdditions(instructions=["Notes: the sky is blue."], messages=[Message.user("(context)")]) + + async def after_run(self, session, request, response): + observed.append(response.text) + return 1 + + client = FakeChatClient(["ok"]) + run(Agent(client, instructions="Base.", context_providers=[Notes()], governance=governed(tmp_path)).run("q")) + sent = client.calls[0]["messages"] + assert sent[0].text == "Base.\n\nNotes: the sky is blue." and sent[1].text == "(context)" + assert observed == ["ok"] + + +def test_run_stream_is_buffered_until_governance_passes(tmp_path): + order = [] + + @agent_middleware + async def gate(context, call_next): + await call_next() + order.append("gate-passed") + + agent = Agent(FakeChatClient(["streamed"]), middleware=[gate], governance=governed(tmp_path)) + + async def consume(): + out = [] + async for update in agent.run_stream("x"): + order.append("update") + out.append(update.text) + return out + + assert run(consume()) == ["streamed"] + assert order == ["gate-passed", "update"] + + +def test_run_sync_refuses_inside_a_running_loop(tmp_path): + agent = Agent(FakeChatClient(["x"]), governance=governed(tmp_path)) + + async def inside(): + agent.run_sync("x") + + with pytest.raises(RuntimeError): + run(inside()) + assert agent.run_sync("hello").text == "x" diff --git a/tests/test_runtime_clients.py b/tests/test_runtime_clients.py new file mode 100644 index 00000000..fac00dbe --- /dev/null +++ b/tests/test_runtime_clients.py @@ -0,0 +1,201 @@ +"""Chat clients of osiris_cli.runtime: the wrapper over existing OSIRIS providers and the Anthropic +Messages API client. No network: providers and the SDK are replaced with in-process fakes.""" + +from __future__ import annotations + +import json +from types import SimpleNamespace + +import pytest + +from osiris_cli.providers.base import ( + BaseModelProvider, + FinishReason, + HealthStatus, + ProviderCapabilities, + ProviderHealth, + ProviderResponse, + ProviderStreamChunk, +) +from osiris_cli.runtime import ( + AnthropicChatClient, + ChatClientError, + Content, + Message, + ProviderChatClient, + tool, +) +from osiris_cli.runtime._types import ROLE_ASSISTANT, ROLE_TOOL +from tests.runtime_support import run + + +@tool +def lookup(key: str) -> str: + """Look a key up.""" + return key + + +class FakeProvider(BaseModelProvider): + """Records each request and answers from a script of ProviderResponses.""" + + def __init__(self, responses, chunks=()): + self.responses = list(responses) + self.chunks = list(chunks) + self.requests = [] + self.model = "fake-provider-model" + + def generate(self, request): + self.requests.append(request) + return self.responses.pop(0) + + def stream(self, request): + self.requests.append(request) + for chunk in self.chunks: + yield chunk + + def health(self): + return ProviderHealth(HealthStatus.HEALTHY, True, "fake") + + def capabilities(self): + return ProviderCapabilities("fake", supports_tool_calling=True) + + +def _conversation(): + return [Message.system("Be brief."), Message.user("find k"), + Message(ROLE_ASSISTANT, [Content.from_function_call("call_7", "lookup", {"key": "k"})]), + Message(ROLE_TOOL, [Content.from_function_result("call_7", {"v": 1}, name="lookup")])] + + +def test_provider_request_carries_system_tools_and_tool_turns(): + provider = FakeProvider([ProviderResponse("done", "m1", "fake", "r1", eval_count=4, prompt_eval_count=9)]) + client = ProviderChatClient(provider, flavor="openai") + response = run(client.get_response(_conversation(), tools=[lookup])) + request = provider.requests[0] + assert request.system == "Be brief." + assert [m.role for m in request.messages] == ["user", "assistant", "tool"] + wire_call = request.messages[1].metadata["tool_calls"][0] + assert wire_call["function"]["name"] == "lookup" and json.loads(wire_call["function"]["arguments"]) == {"key": "k"} + assert request.messages[2].metadata == {"tool_call_id": "call_7", "name": "lookup"} + assert json.loads(request.messages[2].content) == {"v": 1} + assert request.tools[0]["function"]["name"] == "lookup" + assert response.text == "done" and response.usage.total_token_count == 13 and response.model_id == "m1" + + +def test_ollama_flavor_sends_dict_arguments(): + provider = FakeProvider([ProviderResponse("ok", "m", "fake", "r")]) + run(ProviderChatClient(provider, flavor="ollama").get_response(_conversation())) + assert provider.requests[0].messages[1].metadata["tool_calls"][0]["function"]["arguments"] == {"key": "k"} + + +def test_provider_tool_calls_are_normalized(): + raw = [{"id": "c1", "type": "function", "function": {"name": "lookup", "arguments": '{"key": "z"}'}}] + provider = FakeProvider([ProviderResponse("", "m", "fake", "r", finish_reason=FinishReason.TOOL_CALL, tool_calls=raw)]) + response = run(ProviderChatClient(provider, flavor="openai").get_response([Message.user("x")], tools=[lookup])) + call = response.function_calls[0] + assert (call.call_id, call.name, call.arguments) == ("c1", "lookup", {"key": "z"}) + assert response.finish_reason == "tool_calls" + + +@pytest.mark.parametrize("bad", [ + ProviderResponse("", "m", "fake", "r", error="model not found"), + ProviderResponse("", "m", "fake", "r", finish_reason=FinishReason.TIMEOUT), + ProviderResponse("", "m", "fake", "r", tool_calls=[{"function": {"arguments": "{}"}}]), # no name +]) +def test_provider_failures_and_malformed_calls_fail_closed(bad): + with pytest.raises(ChatClientError): + run(ProviderChatClient(FakeProvider([bad]), flavor="openai").get_response([Message.user("x")])) + + +def test_provider_streaming_yields_text_chunks(): + chunks = [ProviderStreamChunk("Hel"), ProviderStreamChunk("lo"), + ProviderStreamChunk("", is_final=True, finish_reason=FinishReason.STOP)] + client = ProviderChatClient(FakeProvider([], chunks), flavor="openai") + + async def collect(): + return [u async for u in client.get_streaming_response([Message.user("hi")])] + + updates = run(collect()) + assert "".join(u.text for u in updates) == "Hello" and updates[-1].finish_reason == "stop" + + +def test_provider_stream_errors_surface(): + class Broken(FakeProvider): + def stream(self, request): + yield ProviderStreamChunk("x") + raise OSError("socket closed") + + client = ProviderChatClient(Broken([]), flavor="openai") + + async def collect(): + return [u async for u in client.get_streaming_response([Message.user("hi")])] + + with pytest.raises(ChatClientError): + run(collect()) + + +class FakeAnthropic: + def __init__(self, reply): + self.reply = reply + self.requests = [] + self.messages = self + + def create(self, **request): + self.requests.append(request) + return self.reply + + +def test_anthropic_request_shape(): + sdk = FakeAnthropic(SimpleNamespace(content=[], stop_reason="end_turn", model="m", id="msg_1", usage=None)) + client = AnthropicChatClient("model-under-test", client=sdk, max_tokens=256) + run(client.get_response(_conversation(), tools=[lookup], options={"temperature": 0})) + request = sdk.requests[0] + assert request["model"] == "model-under-test" and request["max_tokens"] == 256 and request["temperature"] == 0.0 + assert request["system"] == "Be brief." + assert [m["role"] for m in request["messages"]] == ["user", "assistant", "user"] + assert request["messages"][1]["content"] == [{"type": "tool_use", "id": "call_7", "name": "lookup", + "input": {"key": "k"}}] + result = request["messages"][2]["content"][0] + assert result["type"] == "tool_result" and result["tool_use_id"] == "call_7" and "is_error" not in result + assert request["tools"][0]["input_schema"]["properties"]["key"] == {"type": "string"} + + +def test_anthropic_response_parsing(): + reply = SimpleNamespace( + content=[SimpleNamespace(type="text", text="Checking."), + SimpleNamespace(type="tool_use", id="toolu_1", name="lookup", input={"key": "q"})], + stop_reason="tool_use", model="served-model", id="msg_2", + usage=SimpleNamespace(input_tokens=11, output_tokens=7)) + response = run(AnthropicChatClient("asked-model", client=FakeAnthropic(reply)).get_response([Message.user("x")])) + assert response.text == "Checking." and response.finish_reason == "tool_calls" + assert response.function_calls[0].arguments == {"key": "q"} + assert response.model_id == "served-model" and response.usage.total_token_count == 18 + + +def test_anthropic_errors_and_missing_model(): + with pytest.raises(ValueError): + AnthropicChatClient("") + + class Failing(FakeAnthropic): + def create(self, **request): + raise RuntimeError("401 with key FAKE-KEY-MATERIAL") + + with pytest.raises(ChatClientError) as info: + run(AnthropicChatClient("m", client=Failing(None)).get_response([Message.user("x")])) + assert "FAKE-KEY-MATERIAL" not in str(info.value) + + +def test_error_results_are_sent_as_errors_to_anthropic(): + sdk = FakeAnthropic(SimpleNamespace(content=[], stop_reason="end_turn", model="m", id="x", usage=None)) + conversation = [Message.user("x"), + Message(ROLE_ASSISTANT, [Content.from_function_call("c", "lookup", {"key": "k"})]), + Message(ROLE_TOOL, [Content.from_function_result("c", name="lookup", exception="Refused by policy: no")])] + run(AnthropicChatClient("m", client=sdk).get_response(conversation)) + block = sdk.requests[0]["messages"][-1]["content"][0] + assert block["is_error"] is True and block["content"] == "Refused by policy: no" + + +def test_ollama_provider_model_is_used_for_provenance(): + from osiris_cli.providers.ollama_compat import OllamaCompatibilityProvider + + client = ProviderChatClient(OllamaCompatibilityProvider(host="http://127.0.0.1:9", model="qwen2.5-coder:7b")) + assert client.flavor == "ollama" and client.model_id == "qwen2.5-coder:7b" diff --git a/tests/test_runtime_governance.py b/tests/test_runtime_governance.py new file mode 100644 index 00000000..5d589461 --- /dev/null +++ b/tests/test_runtime_governance.py @@ -0,0 +1,318 @@ +"""The governance stack of osiris_cli.runtime: every run is recorded in the task ledger, and risk +tiers, tool effects, paths, code, approvals and budgets are enforced fail-closed.""" + +from __future__ import annotations + +import json +from types import SimpleNamespace + +import pytest + +from osiris_cli.runtime import ( + Agent, + GovernanceConfig, + GovernancePolicyError, + GovernanceRequiredError, + MiddlewareFailure, + _governance, + make_exec_tool, + tool, +) +from osiris_cli.runtime.testing import FakeChatClient, call_response, text_response +from tests.runtime_support import entries, governed, ledger, run + + +def _forced(tier): + """An intent assessment fixed at ``tier`` (the real one comes from intent_router.assess).""" + return lambda text: SimpleNamespace(cls="question", cost_class="read_only", tier=tier, reasons=(f"forced {tier}",)) + + +def _results(response): + return [c for m in response.messages for c in m.function_results] + + +@tool(effects=("read",), path_params=("path",)) +def read_text(path: str) -> str: + """Read a workspace file.""" + return "contents" + + +def test_every_run_is_opened_and_closed_in_the_task_ledger(tmp_path): + config = governed(tmp_path) + response = run(Agent(FakeChatClient(["fine"]), governance=config).run("what is 2+2")) + opened, closed = entries(config) + assert (opened["kind"], closed["kind"]) == ("task_open", "task_close") + assert opened["run_id"] == closed["run_id"] == response.run_id + assert opened["context"]["kind"] == "agent" + assert closed["status"] == "SUCCESS" + telemetry = closed["usage"]["telemetry"] + assert telemetry["by_operation"] == {"chat": 1, "invoke_agent": 1} and len(telemetry["sha256"]) == 64 + assert ledger(config).verify()["intact"] is True + + +def test_default_ledger_and_exchange_log_follow_osiris_home(tmp_path, monkeypatch): + monkeypatch.setenv("OSIRIS_HOME", str(tmp_path / "custom_home")) + config = GovernanceConfig() + assert config.resolved_ledger_path() == str((tmp_path / "custom_home" / "tasks" / "task_runs.jsonl").resolve()) + assert config.resolved_exchange_log().endswith("living/exchanges.jsonl") + + +def test_ledger_unavailable_means_no_run(tmp_path): + (tmp_path / "blocker").mkdir() + config = governed(tmp_path, ledger_path=str(tmp_path / "blocker")) # a directory cannot be appended to + client = FakeChatClient(["never"]) + with pytest.raises(MiddlewareFailure): + run(Agent(client, governance=config).run("hello")) + assert client.calls == [] + + +def test_high_risk_run_without_a_grant_is_blocked(tmp_path): + config = governed(tmp_path) + client = FakeChatClient(["never"]) + response = run(Agent(client, governance=config).run("delete all files in the repo and push to main")) + assert response.status == "BLOCKED" and client.calls == [] + assert response.text.startswith("Refused by OSIRIS governance: risk tier HIGH") + assert entries(config)[-1]["status"] == "BLOCKED" + + +def test_high_risk_run_with_a_grant_proceeds_and_records_it(tmp_path): + asked = [] + + def approve(request): + asked.append(request.kind) + return True + + config = governed(tmp_path, approval_handler=approve) + response = run(Agent(FakeChatClient(["planned"]), governance=config).run("delete all files in the repo and push to main")) + assert response.status == "SUCCESS" and asked == ["risk_tier"] + assert response.governance["grants"][0] == {"kind": "risk_tier", "tier": "HIGH", "granted": True} + + +def test_blocked_tier_is_refused_even_with_an_approver(tmp_path): + config = governed(tmp_path, approval_handler=lambda r: True, assess=_forced("CRITICAL")) + client = FakeChatClient(["never"]) + response = run(Agent(client, governance=config).run("anything")) + assert response.status == "BLOCKED" and client.calls == [] + + +def test_effects_beyond_the_runs_permissions_are_refused(tmp_path): + ran = [] + + @tool(effects=("write",), write_params=("path",)) + def write_file(path: str, text: str) -> int: + """Write text to a workspace file.""" + ran.append(path) + return len(text) + + client = FakeChatClient([call_response("write_file", {"path": "a.txt", "text": "x"}), "ok"]) + response = run(Agent(client, tools=[write_file], governance=governed(tmp_path)).run("write a.txt")) + assert _results(response)[0].exception == "Refused by policy: effect 'write' is not permitted for this run" + assert ran == [] and response.governance["refusals"][0]["gate"] == "tool" + + +@pytest.mark.parametrize("path, fragment", [ + ("../outside.txt", "outside the workspace"), + ("/etc/hostname", "outside the workspace"), + (".env", "credential-shaped"), + ("keys/id_rsa", "credential-shaped"), + ("deploy/token_store.json", "credential-shaped"), +]) +def test_path_arguments_are_confined(tmp_path, path, fragment): + client = FakeChatClient([call_response("read_text", {"path": path}), "ok"]) + response = run(Agent(client, tools=[read_text], governance=governed(tmp_path)).run("read it")) + assert fragment in _results(response)[0].exception + + +def test_symlink_escape_is_refused(tmp_path): + config = governed(tmp_path) + (tmp_path / "secret_dir").mkdir() + (tmp_path / "ws" / "link").symlink_to(tmp_path / "secret_dir") + client = FakeChatClient([call_response("read_text", {"path": "link/data.txt"}), "ok"]) + response = run(Agent(client, tools=[read_text], governance=config).run("read it")) + assert "outside the workspace" in _results(response)[0].exception + + +def test_writes_to_governance_files_are_refused(tmp_path): + @tool(effects=("write",), write_params=("path",)) + def write_file(path: str, text: str) -> int: + """Write text to a workspace file.""" + return len(text) + + config = governed(tmp_path, propose_writes=True) + for target in ("AGENTS.md", "osiris_cli/policy/runtime_policy.json"): + client = FakeChatClient([call_response("write_file", {"path": target, "text": "x"}), "ok"]) + response = run(Agent(client, tools=[write_file], governance=config).run("edit the file")) + assert "governance" in _results(response)[0].exception + ok = run(Agent(FakeChatClient([call_response("write_file", {"path": "notes.md", "text": "hi"}), "ok"]), + tools=[write_file], governance=config).run("write notes")) + assert _results(ok)[0].result == 2 + + +def test_code_arguments_must_pass_the_ast_firewall(tmp_path): + @tool(code_params=("source",)) + def check_source(source: str) -> int: + """Count the lines of a Python snippet.""" + return len(source.splitlines()) + + config = governed(tmp_path) + bad = run(Agent(FakeChatClient([call_response("check_source", {"source": "import os\nos.system('id')"}), "ok"]), + tools=[check_source], governance=config).run("check")) + assert "SYS-025 AST firewall" in _results(bad)[0].exception + good = run(Agent(FakeChatClient([call_response("check_source", {"source": "x = 1\ny = 2"}), "ok"]), + tools=[check_source], governance=config).run("check")) + assert _results(good)[0].result == 2 + + +@pytest.mark.parametrize("handler, granted", [ + (None, False), + (lambda request: True, True), + (lambda request: "yes", False), # only exactly True approves +]) +def test_always_require_tools_need_an_exact_approval(tmp_path, handler, granted): + @tool(approval_mode="always_require") + def launch(target: str) -> str: + """Launch something.""" + return f"launched {target}" + + client = FakeChatClient([call_response("launch", {"target": "x"}), "ok"]) + response = run(Agent(client, tools=[launch], governance=governed(tmp_path, approval_handler=handler)).run("go")) + result = _results(response)[0] + assert (result.result == "launched x") is granted + if not granted: + assert "requires approval" in result.exception + + +def test_async_approval_handlers_are_awaited(tmp_path): + @tool(approval_mode="always_require") + def launch(target: str) -> str: + """Launch something.""" + return "launched" + + async def approve(request): + return request.kind == "tool" + + client = FakeChatClient([call_response("launch", {"target": "x"}), "ok"]) + response = run(Agent(client, tools=[launch], governance=governed(tmp_path, approval_handler=approve)).run("go")) + assert _results(response)[0].result == "launched" + + +def test_step_budget_stops_the_run(tmp_path): + config = governed(tmp_path, budget={"max_steps": 1}) + client = FakeChatClient([call_response("read_text", {"path": "a.txt"}), "never reached"]) + response = run(Agent(client, tools=[read_text], governance=config).run("read a.txt")) + assert response.status == "STOPPED_BUDGET" and len(client.calls) == 1 + closed = entries(config)[-1] + assert closed["status"] == "STOPPED_BUDGET" and closed["stop_reason"] == "max_steps" + + +def test_tool_call_budget_stops_the_run(tmp_path): + config = governed(tmp_path, budget={"max_tool_calls": 1}) + client = FakeChatClient([call_response("read_text", {"path": "a.txt"}, call_id="c1"), + call_response("read_text", {"path": "b.txt"}, call_id="c2"), "never"]) + response = run(Agent(client, tools=[read_text], governance=config).run("read two files")) + assert response.status == "STOPPED_BUDGET" + assert entries(config)[-1]["stop_reason"] == "max_tool_calls" + + +def test_unsupported_claims_are_flagged_not_dropped(tmp_path): + response = run(Agent(FakeChatClient(["All 12 tests pass."]), governance=governed(tmp_path)).run("status?")) + assert response.text == "All 12 tests pass." + assert response.governance["evidence"]["decision"] == "QUARANTINE" + assert entries(governed(tmp_path))[-1]["usage"]["governance"]["evidence_decision"] == "QUARANTINE" + + +def test_provenance_records_requested_and_actual_model(tmp_path): + client = FakeChatClient([lambda m, t, o: text_response("hi", model_id="other-model")], model_id="asked-model") + response = run(Agent(client, governance=governed(tmp_path)).run("hello")) + entry = response.governance["provenance"][0] + assert entry["requested_model"] == "asked-model" and entry["actual_model"] == "other-model" + assert entry["model_mismatch"] is True and len(entry["prompt_sha256"]) == 64 + + +def test_user_function_middleware_cannot_slip_arguments_past_the_policy(tmp_path): + from osiris_cli.runtime import function_middleware + + @function_middleware + async def tamper(context, call_next): + context.arguments["path"] = "../escape.txt" + await call_next() + + client = FakeChatClient([call_response("read_text", {"path": "fine.txt"}), "ok"]) + agent = Agent(client, tools=[read_text], middleware=[tamper], governance=governed(tmp_path)) + assert agent.pipelines["function"][-1] == "ToolPolicyMiddleware" + assert "outside the workspace" in _results(run(agent.run("read")))[0].exception + + +def test_governance_cannot_be_switched_off_while_policy_requires_it(tmp_path, monkeypatch): + with pytest.raises(GovernanceRequiredError): + Agent(FakeChatClient(["x"]), governance=False) + relaxed = tmp_path / "relaxed.json" + policy = json.loads(_governance.DEFAULT_POLICY_PATH.read_text(encoding="utf-8")) + relaxed.write_text(json.dumps(dict(policy, governance_required=False)), encoding="utf-8") + monkeypatch.setattr(_governance, "DEFAULT_POLICY_PATH", relaxed) + agent = Agent(FakeChatClient(["x"]), governance=False) + assert agent.governance is None and agent.pipelines["agent"] == [] + + +@pytest.mark.parametrize("change", [ + {"schema": "something-else"}, + {"blocked_risk_tiers": ["APOCALYPTIC"]}, + {"governance_required": "yes"}, +]) +def test_a_malformed_policy_refuses_to_build(tmp_path, change): + bad = tmp_path / "policy.json" + policy = json.loads(_governance.DEFAULT_POLICY_PATH.read_text(encoding="utf-8")) + bad.write_text(json.dumps(dict(policy, **change)), encoding="utf-8") + with pytest.raises(GovernancePolicyError): + Agent(FakeChatClient(["x"]), governance=governed(tmp_path, policy_path=str(bad))) + + +def test_shipped_policy_is_valid_and_strict(): + policy = _governance.load_runtime_policy() + assert policy["governance_required"] is True + assert "CRITICAL" in policy["blocked_risk_tiers"] and "HIGH" in policy["grant_required_risk_tiers"] + + +def test_run_command_needs_the_exec_permission(tmp_path): + config = governed(tmp_path) + runner = make_exec_tool(config, journal_path=str(tmp_path / "exec_journal.jsonl")) + client = FakeChatClient([call_response("run_command", {"argv": ["ls"]}), "ok"]) + response = run(Agent(client, tools=[runner], governance=config).run("list files")) + assert "effect 'exec' is not permitted" in _results(response)[0].exception + + +def test_run_command_goes_through_exec_policy_and_its_journal(tmp_path): + config = governed(tmp_path, run_commands=True) + journal = tmp_path / "exec_journal.jsonl" + runner = make_exec_tool(config, journal_path=str(journal)) + client = FakeChatClient([call_response("run_command", {"argv": ["git", "push", "origin", "main"]}, call_id="c1"), + call_response("run_command", {"argv": ["ls"]}, call_id="c2"), "ok"]) + (tmp_path / "ws" / "visible.txt").write_text("x", encoding="utf-8") + response = run(Agent(client, tools=[runner], governance=config).run("list the files")) + denied, listed = [r.result for r in _results(response)] + assert denied["decision"] == "DENY" and denied["exit_code"] is None + assert listed["decision"] == "ALLOW" and "visible.txt" in listed["stdout"] + lines = [json.loads(line) for line in journal.read_text(encoding="utf-8").splitlines() if line.strip()] + assert len(lines) == 2 + + +def test_demo_runs_offline_and_leaves_a_verified_ledger(tmp_path, monkeypatch, capsys): + from osiris_cli.runtime import demo + + monkeypatch.setenv("OSIRIS_HOME", str(tmp_path / "home")) + workspace = tmp_path / "ws" + workspace.mkdir() + (workspace / "poem.txt").write_text("one\ntwo\nthree\n", encoding="utf-8") + assert demo.main(["--fake", "--workspace", str(workspace), "--file", "poem.txt"]) == 0 + out = capsys.readouterr().out + assert out.startswith("poem.txt has 3 lines.") + assert '"ledger_intact": true' in out + + +def test_demo_refuses_a_file_outside_the_workspace(tmp_path, monkeypatch, capsys): + from osiris_cli.runtime import demo + + monkeypatch.setenv("OSIRIS_HOME", str(tmp_path / "home")) + (tmp_path / "ws").mkdir() + assert demo.main(["--fake", "--workspace", str(tmp_path / "ws"), "--file", "../secret.txt"]) == 0 + assert "outside the workspace" in capsys.readouterr().out diff --git a/tests/test_runtime_middleware.py b/tests/test_runtime_middleware.py new file mode 100644 index 00000000..59c048fc --- /dev/null +++ b/tests/test_runtime_middleware.py @@ -0,0 +1,164 @@ +"""Middleware pipelines of osiris_cli.runtime. + +Several cases mirror tests in microsoft/agent-framework@567e4d4 +python/packages/core/tests/core/test_middleware.py and test_middleware_context_result.py (execution +order, termination before and after call_next, a result set on the context taking precedence over +the termination's, and type mismatches being refused).""" + +from __future__ import annotations + +import pytest + +from osiris_cli.runtime import ( + AgentMiddleware, + ChatMiddleware, + FunctionMiddleware, + MiddlewareFailure, + MiddlewareTermination, + agent_middleware, + chat_middleware, + function_middleware, +) +from osiris_cli.runtime._middleware import ( + KIND_AGENT, + KIND_CHAT, + KIND_FUNCTION, + AgentContext, + FunctionInvocationContext, + MiddlewarePipeline, + RunState, + middleware_kind, +) +from osiris_cli.runtime._telemetry import SpanRecorder +from tests.runtime_support import run + + +def _run_state() -> RunState: + return RunState(run_id="r1", agent_name="t", recorder=SpanRecorder()) + + +def _agent_context() -> AgentContext: + return AgentContext(agent=None, messages=[], run=_run_state()) + + +def test_execution_order_is_outer_to_inner_and_back(): + order = [] + + class Recorder(AgentMiddleware): + def __init__(self, tag): + self.tag = tag + + async def process(self, context, call_next): + order.append(f"{self.tag}:in") + await call_next() + order.append(f"{self.tag}:out") + + pipeline = MiddlewarePipeline(KIND_AGENT, [Recorder("a"), Recorder("b")]) + + def final(ctx): + order.append("final") + return "done" + + assert run(pipeline.execute(_agent_context(), final)) == "done" + assert order == ["a:in", "b:in", "final", "b:out", "a:out"] + + +def test_termination_before_call_next_skips_inner_and_final(): + reached = [] + + @agent_middleware + async def stop(context, call_next): + raise MiddlewareTermination(result="stopped") + + @agent_middleware + async def inner(context, call_next): + reached.append("inner") + await call_next() + + pipeline = MiddlewarePipeline(KIND_AGENT, [stop, inner]) + assert run(pipeline.execute(_agent_context(), lambda ctx: reached.append("final"))) == "stopped" + assert reached == [] + + +def test_termination_after_call_next_keeps_the_real_result(): + @agent_middleware + async def late_stop(context, call_next): + await call_next() + raise MiddlewareTermination(result="ignored") + + pipeline = MiddlewarePipeline(KIND_AGENT, [late_stop]) + assert run(pipeline.execute(_agent_context(), lambda ctx: "real")) == "real" + + +def test_context_result_takes_precedence_over_termination_result(): + @agent_middleware + async def stop(context, call_next): + context.result = "from-context" + raise MiddlewareTermination(result="from-termination") + + pipeline = MiddlewarePipeline(KIND_AGENT, [stop]) + assert run(pipeline.execute(_agent_context(), lambda ctx: "final")) == "from-context" + + +def test_middleware_can_override_the_result_after_call_next(): + class Override(AgentMiddleware): + async def process(self, context, call_next): + await call_next() + context.result = context.result.upper() + + assert run(MiddlewarePipeline(KIND_AGENT, [Override()]).execute(_agent_context(), lambda c: "x")) == "X" + + +def test_function_pipeline_propagates_termination_to_the_tool_loop(): + @function_middleware + async def stop(context, call_next): + raise MiddlewareTermination(result="partial") + + ctx = FunctionInvocationContext(function=None, arguments={}, run=_run_state()) + with pytest.raises(MiddlewareTermination) as info: + run(MiddlewarePipeline(KIND_FUNCTION, [stop]).execute(ctx, lambda c: "x")) + assert info.value.result == "partial" + + +def test_failure_propagates_from_every_pipeline(): + @chat_middleware + async def fail(context, call_next): + raise MiddlewareFailure("abort") + + with pytest.raises(MiddlewareFailure): + run(MiddlewarePipeline(KIND_CHAT, [fail]).execute(_agent_context(), lambda c: "x")) + + +def test_unmarked_callable_and_wrong_kind_are_refused(): + async def plain(context, call_next): + await call_next() + + with pytest.raises(TypeError): + MiddlewarePipeline(KIND_AGENT, [plain]) + + class Chat(ChatMiddleware): + async def process(self, context, call_next): + await call_next() + + with pytest.raises(TypeError): + MiddlewarePipeline(KIND_FUNCTION, [Chat()]) + with pytest.raises(TypeError): + middleware_kind(object()) + + +def test_decorators_require_async_functions(): + with pytest.raises(TypeError): + agent_middleware(lambda context, call_next: None) + + +def test_kinds_resolve_for_classes_and_decorated_functions(): + class F(FunctionMiddleware): + async def process(self, context, call_next): + await call_next() + + @chat_middleware + async def c(context, call_next): + await call_next() + + assert middleware_kind(F()) == KIND_FUNCTION + assert middleware_kind(c) == KIND_CHAT diff --git a/tests/test_runtime_sessions_telemetry.py b/tests/test_runtime_sessions_telemetry.py new file mode 100644 index 00000000..560f4e3f --- /dev/null +++ b/tests/test_runtime_sessions_telemetry.py @@ -0,0 +1,130 @@ +"""Session history storage and run telemetry in osiris_cli.runtime.""" + +from __future__ import annotations + +import json + +import pytest + +from osiris_cli.runtime import ( + Agent, + AgentSession, + Content, + FileHistoryProvider, + HistoryIntegrityError, + Message, + SpanRecorder, + tool, +) +from osiris_cli.runtime._telemetry import ( + INPUT_TOKENS, + OP_CHAT, + OP_EXECUTE_TOOL, + OP_INVOKE_AGENT, + TOOL_NAME, +) +from osiris_cli.runtime._types import ROLE_ASSISTANT, canonical_json, sha256_json +from osiris_cli.runtime.testing import FakeChatClient, call_response +from tests.runtime_support import governed, run + + +def test_file_history_round_trips_and_chains(tmp_path): + store = FileHistoryProvider(tmp_path / "sessions") + messages = [Message.user("hi"), Message(ROLE_ASSISTANT, [Content.from_function_call("c1", "f", {"a": 1})])] + assert run(store.add_messages("s1", messages)) == 2 + run(store.add_messages("s1", [Message.assistant("done")])) + back = run(store.get_messages("s1")) + assert [m.to_dict() for m in back] == [m.to_dict() for m in messages + [back[-1]]] + lines = (tmp_path / "sessions" / "s1.jsonl").read_text(encoding="utf-8").splitlines() + assert [json.loads(line)["seq"] for line in lines] == [0, 1, 2] + assert json.loads(lines[1])["prev"] == json.loads(lines[0])["hash"] + + +def test_edited_history_is_refused(tmp_path): + store = FileHistoryProvider(tmp_path) + run(store.add_messages("s1", [Message.user("original")])) + path = tmp_path / "s1.jsonl" + path.write_text(path.read_text(encoding="utf-8").replace("original", "edited"), encoding="utf-8") + with pytest.raises(HistoryIntegrityError): + run(store.get_messages("s1")) + + +@pytest.mark.parametrize("bad", ["../escape", "a/b", "", "x" * 65]) +def test_session_ids_cannot_escape_the_directory(tmp_path, bad): + with pytest.raises(ValueError): + FileHistoryProvider(tmp_path).path_for(bad) + with pytest.raises(ValueError): + AgentSession(bad or "bad id") + + +def test_agent_with_file_history(tmp_path): + client = FakeChatClient(["one", "two"]) + agent = Agent(client, governance=governed(tmp_path)) + session = agent.new_session("demo", history=FileHistoryProvider(tmp_path / "hist")) + run(agent.run("first", session=session)) + run(agent.run("second", session=session)) + assert [m.text for m in client.calls[1]["messages"]] == ["first", "one", "second"] + + +def test_spans_cover_agent_chat_and_tool_with_genai_attributes(tmp_path): + @tool + def ping(n: int) -> int: + """Return n.""" + return n + + agent = Agent(FakeChatClient([call_response("ping", {"n": 1}), "pong"]), tools=[ping], governance=governed(tmp_path), + name="spanner") + response = run(agent.run("ping")) + ops = [s["operation"] for s in response.telemetry] + assert ops == [OP_CHAT, OP_EXECUTE_TOOL, OP_CHAT, OP_INVOKE_AGENT] + chat = response.telemetry[0]["attributes"] + assert chat[INPUT_TOKENS] == 10 and chat["gen_ai.response.model"] == "fake-model" + assert response.telemetry[1]["attributes"][TOOL_NAME] == "ping" + agent_span = response.telemetry[-1]["attributes"] + assert agent_span["gen_ai.agent.name"] == "spanner" and agent_span["osiris.run_id"] == response.run_id + + +def test_span_digest_ignores_timings_but_not_content(): + def record(attr): + recorder = SpanRecorder() + with recorder.span("chat m", OP_CHAT, {"k": attr}): + sum(range(1000)) + return recorder + + assert record("a").digest() == record("a").digest() + assert record("a").digest() != record("b").digest() + + +def test_failed_spans_are_marked(): + recorder = SpanRecorder() + with pytest.raises(ValueError): + with recorder.span("x", OP_CHAT): + raise ValueError("boom") + assert recorder.spans[0].status == "ERROR" and recorder.spans[0].error == "ValueError" + assert recorder.summary()["errors"] == 1 + + +def test_canonical_json_is_stable(): + assert canonical_json({"b": 1, "a": "é"}) == '{"a":"é","b":1}' + assert sha256_json({"a": 1}) == sha256_json({"a": 1}) + + +def test_opentelemetry_export_when_installed(tmp_path): + sdk_trace = pytest.importorskip("opentelemetry.sdk.trace", reason="opentelemetry-sdk is an optional extra") + from opentelemetry.sdk.trace.export import SimpleSpanProcessor + from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter + + provider = sdk_trace.TracerProvider() + exporter = InMemorySpanExporter() + provider.add_span_processor(SimpleSpanProcessor(exporter)) + recorder = SpanRecorder(tracer=provider.get_tracer("osiris.runtime")) + with recorder.span("chat m", OP_CHAT, {"gen_ai.request.model": "m", "list": ["a", "b"]}): + pass + with pytest.raises(RuntimeError): + with recorder.span("execute_tool t", OP_EXECUTE_TOOL): + raise RuntimeError("tool broke") + finished = exporter.get_finished_spans() + assert [s.name for s in finished] == ["chat m", "execute_tool t"] + assert finished[0].attributes["gen_ai.operation.name"] == "chat" + assert finished[0].attributes["gen_ai.request.model"] == "m" + assert finished[1].status.status_code.name == "ERROR" diff --git a/tests/test_runtime_tools.py b/tests/test_runtime_tools.py new file mode 100644 index 00000000..7bb045ee --- /dev/null +++ b/tests/test_runtime_tools.py @@ -0,0 +1,151 @@ +"""Tool schemas, argument validation and invocation in osiris_cli.runtime.""" + +from __future__ import annotations + +import enum +from typing import Annotated, Any, Dict, List, Literal, Optional, Sequence, Tuple + +import pytest + +from osiris_cli.providers.schema_guard import SchemaError +from osiris_cli.providers.tool_shim import to_gemini, to_openai +from osiris_cli.runtime import FunctionTool, InvocationConfig, ToolArgumentError, ToolError, tool +from osiris_cli.runtime._tools import normalize_tools, type_to_schema +from tests.runtime_support import run + + +class Color(enum.Enum): + RED = "red" + BLUE = "blue" + + +def test_schema_from_type_hints(): + @tool + def search(query: Annotated[str, "what to look for"], limit: int = 5, tags: Optional[List[str]] = None, + mode: Literal["fast", "exact"] = "fast", color: Color = Color.RED, weights: Dict[str, float] = None, + strict: bool = False) -> str: + """Search the notes.""" + return query + + p = search.parameters + assert p["type"] == "object" and p["additionalProperties"] is False + assert p["required"] == ["query"] + assert p["properties"]["query"] == {"type": "string", "description": "what to look for"} + assert p["properties"]["limit"] == {"type": "integer", "default": 5} + assert p["properties"]["tags"]["type"] == ["array", "null"] + assert p["properties"]["tags"]["items"] == {"type": "string"} + assert p["properties"]["mode"]["enum"] == ["fast", "exact"] + assert p["properties"]["color"]["enum"] == ["red", "blue"] + assert p["properties"]["weights"]["additionalProperties"] == {"type": "number"} + assert p["properties"]["strict"] == {"type": "boolean", "default": False} + assert search.description == "Search the notes." + assert to_openai([search.spec])[0]["function"]["name"] == "search" + assert to_gemini([search.spec])[0]["functionDeclarations"][0]["parameters"]["type"] == "OBJECT" + + +def test_tuples_and_sequences(): + assert type_to_schema(Tuple[int, int]) == {"type": "array", "minItems": 2, "maxItems": 2, "items": {"type": "integer"}} + assert type_to_schema(Tuple[str, ...]) == {"type": "array", "items": {"type": "string"}} + assert type_to_schema(Sequence[float]) == {"type": "array", "items": {"type": "number"}} + with pytest.raises(TypeError): + type_to_schema(Tuple[int, str]) + + +def test_optional_literal_allows_none(): + schema = type_to_schema(Optional[Literal["a", "b"]]) + assert schema["type"] == ["string", "null"] and None in schema["enum"] + + +@pytest.mark.parametrize("bad", ["no_hint", "var_args", "no_doc", "bad_name"]) +def test_tools_that_cannot_be_described_exactly_are_refused(bad): + def no_hint(x): + """Has no hint.""" + return x + + def var_args(*xs: int) -> int: + """Varargs.""" + return 0 + + def no_doc(x: int) -> int: + return x + + with pytest.raises((TypeError, ToolError, SchemaError)): + if bad == "no_hint": + FunctionTool(no_hint) + elif bad == "var_args": + FunctionTool(var_args) + elif bad == "no_doc": + FunctionTool(no_doc) + else: + FunctionTool(no_doc, name="bad name!", description="x") + + +def test_declarations_must_be_consistent(): + def write_file(path: str, text: str) -> int: + """Write text to a file.""" + return len(text) + + with pytest.raises(ToolError): + FunctionTool(write_file, write_params=("path",)) # writes without the 'write' effect + with pytest.raises(ToolError): + FunctionTool(write_file, effects=("write",), write_params=("missing",)) + with pytest.raises(ToolError): + FunctionTool(write_file, effects=("teleport",)) + with pytest.raises(ToolError): + FunctionTool(write_file, approval_mode="sometimes") + ok = FunctionTool(write_file, effects=("write",), write_params=("path",), approval_mode="always_require") + assert ok.effects == ("write",) and ok.write_params == ("path",) + + +def test_arguments_are_validated_before_the_function_runs(): + calls = [] + + @tool + def add(a: int, b: int) -> int: + """Add two integers.""" + calls.append((a, b)) + return a + b + + assert run(add.invoke({"a": 2, "b": 3})) == 5 + with pytest.raises(ToolArgumentError): + run(add.invoke({"a": "2", "b": 3})) + with pytest.raises(ToolArgumentError): + run(add.invoke({"a": 1})) + with pytest.raises(ToolArgumentError): + run(add.invoke({"a": 1, "b": 2, "c": 3})) + assert calls == [(2, 3)] + + +def test_async_tools_are_awaited(): + @tool + async def echo(text: str) -> str: + """Echo the text.""" + return text * 2 + + assert run(echo.invoke({"text": "ab"})) == "abab" + + +def test_duplicate_tool_names_are_refused(): + def a(x: int) -> int: + """A.""" + return x + + with pytest.raises(ToolError): + normalize_tools([a, FunctionTool(a)]) + + +def test_invocation_config_limits_must_be_sane(): + with pytest.raises(ValueError): + InvocationConfig(max_iterations=0) + with pytest.raises(ValueError): + InvocationConfig(max_duration_seconds=0) + assert InvocationConfig().include_detailed_errors is False + + +def test_explicit_parameters_are_schema_checked(): + def f(**kwargs: Any) -> int: + """Anything.""" + return 0 + + with pytest.raises(SchemaError): + FunctionTool(f, parameters={"type": "object", "properties": {"x": {"type": "string", "format": "date"}}}) From b2d398540f96561dbb2e9df06e8fcfa9849be8e6 Mon Sep 17 00:00:00 2001 From: devin davis Date: Sat, 5 Dec 2026 10:37:38 -0500 Subject: [PATCH 02/10] Add pattern for matching environment files Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- osiris_cli/policy/runtime_policy.json | 1 + 1 file changed, 1 insertion(+) diff --git a/osiris_cli/policy/runtime_policy.json b/osiris_cli/policy/runtime_policy.json index de8e6ae6..b6e7a5d7 100644 --- a/osiris_cli/policy/runtime_policy.json +++ b/osiris_cli/policy/runtime_policy.json @@ -6,6 +6,7 @@ "credential_name_patterns": [ ".env", ".env.*", + "*.env", "apikey.json", "*credentials*", "*secret*", From 1bc30ab4dc2e6c2cf3bbfd9dd1b808258541e346 Mon Sep 17 00:00:00 2001 From: devin davis Date: Sat, 5 Dec 2026 10:38:53 -0500 Subject: [PATCH 03/10] Add provenance to governance data structure Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- osiris_cli/runtime/_governance.py | 1 + 1 file changed, 1 insertion(+) diff --git a/osiris_cli/runtime/_governance.py b/osiris_cli/runtime/_governance.py index 8d22d119..19f0365c 100644 --- a/osiris_cli/runtime/_governance.py +++ b/osiris_cli/runtime/_governance.py @@ -251,6 +251,7 @@ async def process(self, context: AgentContext, call_next: CallNext) -> None: "refusals": len(run.governance.get("refusals", [])), "tool_calls_allowed": len(run.governance.get("tool_calls", [])), "model_calls": len(run.governance.get("provenance", [])), + "provenance": list(run.governance.get("provenance", [])), } try: ledger.close(tctx, status, stop=run.stop, usage=usage, detail=f"agent {run.agent_name}") From 86956f8529ceceea2f5ed97b2a7e932547589de2 Mon Sep 17 00:00:00 2001 From: devin davis Date: Sat, 5 Dec 2026 10:39:02 -0500 Subject: [PATCH 04/10] Refactor governance assignment in _agents.py Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- osiris_cli/runtime/_agents.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/osiris_cli/runtime/_agents.py b/osiris_cli/runtime/_agents.py index 251ff011..fb459237 100644 --- a/osiris_cli/runtime/_agents.py +++ b/osiris_cli/runtime/_agents.py @@ -103,7 +103,7 @@ def __init__(self, client: ChatClient, *, name: str = "osiris-agent", instructio elif isinstance(governance, GovernanceConfig): self.governance = GovernanceStack.build(governance) elif isinstance(governance, GovernanceStack): - self.governance = governance + self.governance = GovernanceStack.build(governance.config) else: raise TypeError("governance must be a GovernanceConfig, a GovernanceStack, None, or False") user: Dict[str, List[Any]] = {KIND_AGENT: [], KIND_CHAT: [], KIND_FUNCTION: []} From 7434932bfd6221d285095512537bfce2d4a2a923 Mon Sep 17 00:00:00 2001 From: devin davis Date: Sat, 5 Dec 2026 10:39:11 -0500 Subject: [PATCH 05/10] Refactor governance evidence processing logic Refactor governance processing to handle exceptions and ensure evidence is not dropped. Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- osiris_cli/runtime/_governance.py | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/osiris_cli/runtime/_governance.py b/osiris_cli/runtime/_governance.py index 19f0365c..025b72a5 100644 --- a/osiris_cli/runtime/_governance.py +++ b/osiris_cli/runtime/_governance.py @@ -296,16 +296,21 @@ class EvidenceFirewallMiddleware(AgentMiddleware): response (``governance['evidence']``), never silently dropped.""" async def process(self, context: AgentContext, call_next: CallNext) -> None: - await call_next() - result = context.result - if not isinstance(result, AgentResponse) or not result.text: - return - firewall = check_report(result.text, evidence=context.run.metadata.get("execution_evidence"), - artifacts=context.run.metadata.get("evidence_artifacts")) - decision = firewall.decision - result.governance["evidence"] = {"decision": decision, - "findings": [dataclasses.asdict(f) for f in firewall.findings]} - context.run.governance["evidence_decision"] = decision + try: + await call_next() + except MiddlewareTermination as termination: + if context.result is None: + context.result = termination.result + raise + finally: + result = context.result + if isinstance(result, AgentResponse) and result.text: + firewall = check_report(result.text, evidence=context.run.metadata.get("execution_evidence"), + artifacts=context.run.metadata.get("evidence_artifacts")) + decision = firewall.decision + result.governance["evidence"] = {"decision": decision, + "findings": [dataclasses.asdict(f) for f in firewall.findings]} + context.run.governance["evidence_decision"] = decision class BudgetChatMiddleware(ChatMiddleware): From 8462006599227ce60e6c3df243c9614de2613127 Mon Sep 17 00:00:00 2001 From: devin davis Date: Sat, 5 Dec 2026 10:39:24 -0500 Subject: [PATCH 06/10] Handle missing parameters by assigning defaults Set default values for missing parameters in context arguments. Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- osiris_cli/runtime/_governance.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/osiris_cli/runtime/_governance.py b/osiris_cli/runtime/_governance.py index 025b72a5..f0ad849a 100644 --- a/osiris_cli/runtime/_governance.py +++ b/osiris_cli/runtime/_governance.py @@ -385,6 +385,12 @@ def _refuse(self, context: FunctionInvocationContext, reason: str) -> None: async def process(self, context: FunctionInvocationContext, call_next: CallNext) -> None: tool: FunctionTool = context.function + parameters = inspect.signature(tool.func).parameters + for name in tool.path_params + tool.write_params + tool.code_params: + parameter = parameters.get(name) + if name not in context.arguments and parameter is not None \ + and parameter.default is not inspect.Parameter.empty: + context.arguments[name] = parameter.default tctx = _require(context, "task_context", "ToolPolicyMiddleware") meter = _require(context, "meter", "ToolPolicyMiddleware") stop = meter.begin_tool_call() From 1179a26ccaafeaaacf4c107fc37ec168789c8aed Mon Sep 17 00:00:00 2001 From: devin davis Date: Sat, 5 Dec 2026 10:39:40 -0500 Subject: [PATCH 07/10] Allow write effects to bypass approval mode Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- osiris_cli/runtime/_governance.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/osiris_cli/runtime/_governance.py b/osiris_cli/runtime/_governance.py index f0ad849a..c235e5be 100644 --- a/osiris_cli/runtime/_governance.py +++ b/osiris_cli/runtime/_governance.py @@ -420,7 +420,7 @@ async def process(self, context: FunctionInvocationContext, call_next: CallNext) found = ", ".join(f"{v.kind} {v.name} (line {v.line})" for v in violations[:5]) or "does not parse" meter.note(False) return self._refuse(context, f"SYS-025 AST firewall refused '{name}': {found}") - if tool.approval_mode == APPROVAL_ALWAYS: + if tool.approval_mode == APPROVAL_ALWAYS or "write" in tool.effects: granted = await ask_approval(self.config.approval_handler, ApprovalRequest( "tool", f"call tool '{tool.name}'", {"arguments": dict(context.arguments), "effects": list(tool.effects)})) From 05854d4ca8c8c1ba30bd2f92f7552fa87e3d0e44 Mon Sep 17 00:00:00 2001 From: devin davis Date: Sat, 5 Dec 2026 10:39:49 -0500 Subject: [PATCH 08/10] Validate session history path resolution Ensure session history path is within the directory. Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- osiris_cli/runtime/_sessions.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/osiris_cli/runtime/_sessions.py b/osiris_cli/runtime/_sessions.py index b0ffffd1..fd6073ef 100644 --- a/osiris_cli/runtime/_sessions.py +++ b/osiris_cli/runtime/_sessions.py @@ -71,7 +71,10 @@ def __init__(self, directory: Union[str, "os.PathLike[str]"]) -> None: def path_for(self, session_id: str) -> Path: if not SESSION_ID_RE.match(session_id): raise ValueError(f"session id {session_id!r} must match {SESSION_ID_RE.pattern}") - return self.directory / f"{session_id}.jsonl" + path = (self.directory / f"{session_id}.jsonl").resolve() + if not path.is_relative_to(self.directory): + raise ValueError("session history path resolves outside its directory") + return path def _read(self, session_id: str) -> List[Dict[str, Any]]: path = self.path_for(session_id) From e480967fe94b677a8440b33e42db3155503eb99f Mon Sep 17 00:00:00 2001 From: devin davis Date: Sat, 5 Dec 2026 10:40:14 -0500 Subject: [PATCH 09/10] Enhance span context manager for exception handling Modify telemetry span context manager to handle exceptions more gracefully by adding an event instead of recording the exception directly. Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- osiris_cli/runtime/_telemetry.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/osiris_cli/runtime/_telemetry.py b/osiris_cli/runtime/_telemetry.py index c4372c71..0de850b5 100644 --- a/osiris_cli/runtime/_telemetry.py +++ b/osiris_cli/runtime/_telemetry.py @@ -93,7 +93,9 @@ def __init__(self, tracer: Any = None) -> None: @contextlib.contextmanager def span(self, name: str, operation: str, attributes: Optional[Dict[str, Any]] = None) -> Iterator[SpanRecord]: record = SpanRecord(name, operation, {OPERATION: operation, **(attributes or {})}, start_ns=time.monotonic_ns()) - otel_cm = self.tracer.start_as_current_span(name) if self.tracer is not None else contextlib.nullcontext() + otel_cm = self.tracer.start_as_current_span( + name, record_exception=False, set_status_on_exception=False + ) if self.tracer is not None else contextlib.nullcontext() with otel_cm as otel_span: try: yield record @@ -101,7 +103,7 @@ def span(self, name: str, operation: str, attributes: Optional[Dict[str, Any]] = record.status = "ERROR" record.error = type(exc).__name__ if otel_span is not None: - otel_span.record_exception(exc) + otel_span.add_event("exception", {"exception.type": record.error}) raise finally: record.end_ns = time.monotonic_ns() From 514e982a8b4839dfcb687d9db7bb7fcf160a5038 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 10:49:54 -0500 Subject: [PATCH 10/10] test(runtime): writes need the operator's approval (follow-up to 1179a26) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1179a26 ("Allow write effects to bypass approval mode") does the opposite of its title: every tool with the "write" effect now needs an exact approval, even when the run permits writes. That matches AGENTS.md §1.5 (workspace writes require explicit operator authorization), so the rule stays. It broke test_writes_to_governance_files_are_refused, which wrote notes.md with no approval handler. - The test now grants approval explicitly and also asserts that governance files are refused before anyone is asked, so an approval cannot unlock them. - New parametrized test: with no handler, a False handler or a non-True value, a permitted write is refused for lack of approval. - ToolPolicyMiddleware's docstring states the write rule. Removing the write rule makes 4 of these tests fail. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FYXiwQpjjWVfi7MNQgjVHJ --- osiris_cli/runtime/_governance.py | 5 +++-- tests/test_runtime_governance.py | 25 ++++++++++++++++++++++++- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/osiris_cli/runtime/_governance.py b/osiris_cli/runtime/_governance.py index c235e5be..067eedad 100644 --- a/osiris_cli/runtime/_governance.py +++ b/osiris_cli/runtime/_governance.py @@ -352,8 +352,9 @@ class ToolPolicyMiddleware(FunctionMiddleware): Order: task budget, effects against the run's permissions, path arguments (workspace confinement, credential names, governance-protected write targets), code arguments (SYS-025 AST - firewall), then approval for ``always_require`` tools. A refusal does not run the tool; the model - is told why and may continue.""" + firewall), then approval for ``always_require`` tools and for every tool with the ``write`` + effect (``propose_writes`` permits writes; each write still needs the operator's approval). A + refusal does not run the tool; the model is told why and may continue.""" def __init__(self, config: GovernanceConfig, policy: Mapping[str, Any]) -> None: self.config = config diff --git a/tests/test_runtime_governance.py b/tests/test_runtime_governance.py index 5d589461..0d3030b2 100644 --- a/tests/test_runtime_governance.py +++ b/tests/test_runtime_governance.py @@ -138,14 +138,37 @@ def write_file(path: str, text: str) -> int: """Write text to a workspace file.""" return len(text) - config = governed(tmp_path, propose_writes=True) + asked = [] + + def approve(request): + asked.append(request) + return True + + # The operator would approve, yet governance files are refused before anyone is asked. + config = governed(tmp_path, propose_writes=True, approval_handler=approve) for target in ("AGENTS.md", "osiris_cli/policy/runtime_policy.json"): client = FakeChatClient([call_response("write_file", {"path": target, "text": "x"}), "ok"]) response = run(Agent(client, tools=[write_file], governance=config).run("edit the file")) assert "governance" in _results(response)[0].exception + assert asked == [] ok = run(Agent(FakeChatClient([call_response("write_file", {"path": "notes.md", "text": "hi"}), "ok"]), tools=[write_file], governance=config).run("write notes")) assert _results(ok)[0].result == 2 + assert [request.kind for request in asked] == ["tool"] + + +@pytest.mark.parametrize("handler", [None, lambda request: False, lambda request: "yes"]) +def test_writes_need_an_exact_approval_even_when_writes_are_permitted(tmp_path, handler): + @tool(effects=("write",), write_params=("path",)) + def write_file(path: str, text: str) -> int: + """Write text to a workspace file.""" + return len(text) + + config = governed(tmp_path, propose_writes=True, approval_handler=handler) + client = FakeChatClient([call_response("write_file", {"path": "notes.md", "text": "hi"}), "ok"]) + result = _results(run(Agent(client, tools=[write_file], governance=config).run("write notes")))[0] + assert result.result is None + assert "requires approval" in result.exception def test_code_arguments_must_pass_the_ast_firewall(tmp_path):