Repository navigation
feat(runtime): governed agent core re-engineered from Microsoft Agent… - #107
Conversation
… 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@567e4d4 (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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FYXiwQpjjWVfi7MNQgjVHJ
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved critical findings permit governance bypasses, unapproved writes, out-of-workspace file access, credential exposure, and sensitive telemetry leaks.
18 open issues
Credential guard allows .env files · New Prebuilt governance stacks can bypass required middleware · New Middleware termination can skip the output audit · New Protected-path checks ignore the original symlink name · New Default argument values bypass policy checks · New The max_writes limit is not enforced · New Tool calls use unchecked relative paths · New Write tools execute without explicit approval · New Session symlinks can escape the history directory · New Session file locking is not shared across providers · New Telemetry exports unsanitized tool exceptions · New Duration limits are checked too late · New Tool wrapper misclassifies Gemini providers · New External and hardware permissions always fail validation · New Task ledger omits detailed provenance records · New Claims grounding is missing before model invocation · New Provenance is captured before middleware modifies requests · New JSON arguments are not converted to annotated Python types · New
What changed in this PR
Introduces a Phase 1 agent runtime adapted from Microsoft Agent Framework, integrating OSIRIS governance, providers, and task records.
Changes:
- Adds typed messages, tool execution, middleware, sessions, and telemetry.
- Connects runtime execution to policy checks, approvals, budgets, and task ledgers.
- Adds offline tests, a demo, and third-party attribution.
| File | Description |
|---|---|
| THIRD_PARTY_NOTICES.md | Documents upstream attribution and licensing. |
| tests/test_runtime_tools.py | Tests schemas and tool invocation. |
| tests/test_runtime_sessions_telemetry.py | Tests history integrity and spans. |
| tests/test_runtime_middleware.py | Tests middleware ordering and termination. |
| tests/test_runtime_governance.py | Tests governance checks and recording. |
| tests/test_runtime_clients.py | Tests provider and Anthropic mappings. |
| tests/test_runtime_agent.py | Tests agent loops and limits. |
| tests/runtime_support.py | Supplies isolated test helpers. |
| pyproject.toml | Packages the upstream license. |
| osiris_cli/task_context.py | Adds the agent task kind. |
| osiris_cli/runtime/testing.py | Adds a scripted offline client. |
| osiris_cli/runtime/PORT_MAP.md | Records adaptation scope and differences. |
| osiris_cli/runtime/LICENSE-agent-framework.txt | Includes the upstream MIT license. |
| osiris_cli/runtime/demo.py | Demonstrates a governed file-reading tool. |
| osiris_cli/runtime/_types.py | Defines messages, responses, and serialization. |
| osiris_cli/runtime/_tools.py | Defines tool schemas and invocation. |
| osiris_cli/runtime/_telemetry.py | Records spans and optional OpenTelemetry export. |
| osiris_cli/runtime/_sessions.py | Adds session history and context providers. |
| osiris_cli/runtime/_middleware.py | Implements three middleware pipelines. |
| osiris_cli/runtime/_governance.py | Integrates policy, budgets, approvals, and ledgers. |
| osiris_cli/runtime/_clients.py | Adapts existing providers and Anthropic. |
| osiris_cli/runtime/_agents.py | Implements governed agent execution. |
| osiris_cli/runtime/__init__.py | Exposes the runtime API. |
| osiris_cli/policy/runtime_policy.json | Defines default governance restrictions. |
Review effort: Balanced
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
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>
Set default values for missing parameters in context arguments. Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Ensure session history path is within the directory. Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
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>
) 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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FYXiwQpjjWVfi7MNQgjVHJ
quantum-osiris
left a comment
There was a problem hiding this comment.
Reviewed at 514e982 against roadmap v0.5 F1.1–F1.3.
- Post-handoff commits: 1179a26 (despite its title) tightens policy — every
write-effect tool now needs operator approval; 514e982 adds the tests.*.envcredential pattern, session-path confinement (05854d4), default-argument policy checks (8462006) and evidence firewall on termination (7434932) all look correct. - Fail-closed: runtime policy load raises on missing/malformed policy;
governance=Falserequires editingruntime_policy.json, which is itself a refused write target. - Additive: new
osiris_cli.runtimepackage;osiris.runtimeconsumers untouched, so the ownership/migration decision (roadmap R11) stays open as follow-up. - Local: 99 passed, 1 skipped (runtime tests, Python 3.14.4). CI green on 3.9–3.12.
- Nit (non-blocking): in EvidenceFirewallMiddleware the
finallyrunscheck_reporteven when an unrelated exception propagates; an error insidecheck_reportwould mask the original.
🤖 Generated with Claude Code
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved critical findings allow workspace and protected-file policy bypasses, secret leakage through exception traces, and concurrent session-history corruption.
26 open issues
Suppress secret-bearing exception chains · New Assess effective context before model or tool execution · New Drain or stop background execution before closing a run · New Block rejected answers before publishing or saving them · New Apply protected-write checks to write-effect path arguments · New Require source payloads for governed Python writes · New Make shipped policy restrictions a mandatory floor · New Scope command approvals to the current governed run · New Confine or refuse commands with unchecked file access · New Provide an approving handler in the write-policy test · New Apply budget and provenance hooks to every client call · New Preflight Ollama before opening the task ledger · New Mark runs unsuccessful when middleware returns no response · New Abort on model error finish reasons · New Settle tool calls returned when tools are disabled · New Count each error-containing round toward the failure limit · New Record runtime turns in the canonical exchange log · New Apply the claims firewall before model and tool execution · New Account for tool attempts before lookup and validation · New Reject missing or unsupported Anthropic stop reasons · New
And 6 more that still need to be addressed.
18 resolved since last review
Telemetry exports unsanitized tool exceptions Session file locking is not shared across providers Session symlinks can escape the history directory Write tools execute without explicit approval Tool calls use unchecked relative paths The max_writes limit is not enforced Default argument values bypass policy checks Protected-path checks ignore the original symlink name Middleware termination can skip the output audit Prebuilt governance stacks can bypass required middleware Credential guard allows .env files JSON arguments are not converted to annotated Python types Provenance is captured before middleware modifies requests Claims grounding is missing before model invocation Task ledger omits detailed provenance records External and hardware permissions always fail validation Tool wrapper misclassifies Gemini providers Duration limits are checked too late
Review effort: Max
| except ChatClientError: | ||
| raise | ||
| except Exception as exc: | ||
| raise ChatClientError(f"anthropic: {type(exc).__name__}") from exc |
| 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)" |
| "provenance": list(run.governance.get("provenance", [])), | ||
| } | ||
| try: | ||
| ledger.close(tctx, status, stop=run.stop, usage=usage, detail=f"agent {run.agent_name}") |
| decision = firewall.decision | ||
| result.governance["evidence"] = {"decision": decision, | ||
| "findings": [dataclasses.asdict(f) for f in firewall.findings]} | ||
| context.run.governance["evidence_decision"] = decision |
| 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) |
| 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) |
|
|
||
|
|
| 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()) |
| 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) |
| except BaseException as exc: | ||
| record.status = "ERROR" | ||
| record.error = type(exc).__name__ | ||
| if otel_span is not None: | ||
| otel_span.add_event("exception", {"exception.type": record.error}) | ||
| raise |


… 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@567e4d4 (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.
Claude-Session: https://claude.ai/code/session_01FYXiwQpjjWVfi7MNQgjVHJ