diff --git a/osiris_cli/orchestration/council.py b/osiris_cli/orchestration/council.py index 440a6fa3..f4b77fab 100644 --- a/osiris_cli/orchestration/council.py +++ b/osiris_cli/orchestration/council.py @@ -21,6 +21,9 @@ ``osiris_cli.gemini_gateway``. Each role's route record (requested and resolved model, runtime, whether the request left the device, every candidate tried) is returned and receipted. +The roles run as a workflow (``osiris_cli.runtime``): AURA -> AIDEN -> IRIS -> OSIRIS, where a +role whose model call fails sends the task straight to OSIRIS. ``council_workflow`` builds it. + "OSIRIS decides" means the workflow disposition of a proposal, nothing more. No decision here authorizes execution; anything that acts goes through the separate approval gates. """ @@ -31,8 +34,19 @@ import os import re import secrets +from dataclasses import dataclass, field from typing import Any, Callable, Dict, List, Optional, Tuple +from ..runtime._workflows import ( + COMPLETED, + Case, + Default, + Executor, + Workflow, + WorkflowBuilder, + WorkflowContext, + handler, +) from ..trio_authz import Receipts from .evidence_firewall import check_report @@ -168,128 +182,188 @@ def decide(firewall: Dict[str, str], verdict: Optional[str], *, verdict_conflict return "REVISION_REQUESTED", "AIDEN gave no verdict line" -def run_task(objective: Any, context: Any = None, *, receipts_path: str, model_fn: Optional[ModelFn] = None, - claims: Optional[List[str]] = None, allow_cloud: Any = False) -> Dict[str, Any]: - if not isinstance(objective, str) or not objective.strip(): - raise CouncilError("objective must be a non-empty string") - objective = objective.strip() - if len(objective) > MAX_OBJECTIVE: - raise CouncilError(f"objective is longer than {MAX_OBJECTIVE} characters") - if context is None: - context = "" - if not isinstance(context, str) or len(context) > MAX_CONTEXT: - raise CouncilError(f"context must be a string of at most {MAX_CONTEXT} characters") - context = context.strip() - if not isinstance(allow_cloud, bool): - raise CouncilError("allow_cloud must be true or false") +@dataclass +class _CouncilTask: + """One task as it moves through the council workflow (AURA -> AIDEN -> IRIS -> OSIRIS).""" + + task_id: str + objective: str + context: str + claims: List[str] + allow_cloud: bool + model_fn: ModelFn + base: str + events: List[Dict[str, Any]] = field(default_factory=list) + outputs: Dict[str, Dict[str, Any]] = field(default_factory=dict) + firewall: Dict[str, str] = field(default_factory=dict) + failure: Optional[str] = None + failed_routes: Dict[str, Any] = field(default_factory=dict) - model_fn = model_fn or routed_model_fn(allow_cloud) - claims = claim_lines() if claims is None else claims - task_id = "task-" + secrets.token_hex(6) - events: List[Dict[str, Any]] = [] + def emit(self, actor: str, event: str, detail: str) -> None: + self.events.append({"seq": len(self.events) + 1, "actor": actor, "event": event, "detail": detail}) - def emit(actor: str, event: str, detail: str) -> None: - events.append({"seq": len(events) + 1, "actor": actor, "event": event, "detail": detail}) + def prompt(self, role: str) -> str: + if role == "AURA": + return self.base + if role == "AIDEN": + return f"{self.base}\n\nAURA's proposal:\n{self.outputs['AURA']['text']}" + return (f"{self.base}\n\nAURA's proposal:\n{self.outputs['AURA']['text']}\n\n" + f"AIDEN's review:\n{self.outputs['AIDEN']['text']}") - emit("OSIRIS", "TASK_ACCEPTED", f"{task_id}: objective {_sha(objective)[:16]}, {len(claims)} claims in context, " - f"cloud {'allowed' if allow_cloud else 'not allowed'}") - outputs: Dict[str, Dict[str, Any]] = {} - firewall: Dict[str, str] = {} - failure: Optional[str] = None - failed_routes: Dict[str, Any] = {} - base = f"Objective:\n{objective}" + (f"\n\nContext from the workspace:\n{context}" if context else "") - prompts = { - "AURA": lambda: base, - "AIDEN": lambda: f"{base}\n\nAURA's proposal:\n{outputs['AURA']['text']}", - "IRIS": lambda: (f"{base}\n\nAURA's proposal:\n{outputs['AURA']['text']}\n\n" - f"AIDEN's review:\n{outputs['AIDEN']['text']}"), - } - stage = {"AURA": "PROPOSAL", "AIDEN": "REVIEW", "IRIS": "BRIEF"} +_STAGE = {"AURA": "PROPOSAL", "AIDEN": "REVIEW", "IRIS": "BRIEF"} - for role in ROLES: + +class _RoleExecutor(Executor): + """One role's model call, output checks and firewall pass. A failure goes straight to OSIRIS.""" + + def __init__(self, role: str) -> None: + self.role = role + super().__init__(role) + + @handler(input=_CouncilTask) + async def take(self, task: _CouncilTask, ctx: WorkflowContext) -> None: + self._run_role(task) + await ctx.send_message(task) + + def _fail(self, task: _CouncilTask, failure: str, route: Dict[str, Any]) -> None: + task.failure = failure + task.failed_routes[self.role] = route + task.emit("OSIRIS", "MODEL_UNAVAILABLE", failure) + + def _run_role(self, task: _CouncilTask) -> None: + role = self.role route: Optional[Dict[str, Any]] = None try: - reply = model_fn(role, _system(role, claims), prompts[role]()) + reply = task.model_fn(role, _system(role, task.claims), task.prompt(role)) if not isinstance(reply, (tuple, list)) or len(reply) < 2: - failure = f"{role}: malformed model reply ({type(reply).__name__})" - failed_routes[role] = {"status": "MALFORMED_REPLY", "type": type(reply).__name__} - emit("OSIRIS", "MODEL_UNAVAILABLE", failure) - break + return self._fail(task, f"{role}: malformed model reply ({type(reply).__name__})", + {"status": "MALFORMED_REPLY", "type": type(reply).__name__}) text, provider = reply[0], reply[1] route = reply[2] if len(reply) > 2 and isinstance(reply[2], dict) else None except Exception as e: # noqa: BLE001 - any model failure ends the task; no key material is in e - failure = f"{role}: {type(e).__name__}: {str(e)[:400]}" - failed_routes[role] = getattr(e, "route", None) or {"status": "EXCEPTION", "error": type(e).__name__} - emit("OSIRIS", "MODEL_UNAVAILABLE", failure) - break + return self._fail(task, f"{role}: {type(e).__name__}: {str(e)[:400]}", + getattr(e, "route", None) or {"status": "EXCEPTION", "error": type(e).__name__}) if not isinstance(text, str): - failure = f"{role}: the model call returned {type(text).__name__}, not text" - failed_routes[role] = route or {"status": "MALFORMED_OUTPUT", "type": type(text).__name__} - emit("OSIRIS", "MODEL_UNAVAILABLE", failure) - break + return self._fail(task, f"{role}: the model call returned {type(text).__name__}, not text", + route or {"status": "MALFORMED_OUTPUT", "type": type(text).__name__}) text = (text or "").strip()[:MAX_OUTPUT] if not text: - failure = f"{role}: the model returned no text" - failed_routes[role] = route or {"status": "EMPTY_OUTPUT"} - emit("OSIRIS", "MODEL_UNAVAILABLE", failure) - break + return self._fail(task, f"{role}: the model returned no text", route or {"status": "EMPTY_OUTPUT"}) if _is_mock_output(provider, route, text): - failure = f"{role}: mock model output refused; cannot masquerade as live model output" - failed_routes[role] = route or {"status": "MOCK_OUTPUT_REFUSED", "provider": str(provider)[:80]} - emit("OSIRIS", "MODEL_UNAVAILABLE", failure) - break + return self._fail(task, f"{role}: mock model output refused; cannot masquerade as live model output", + route or {"status": "MOCK_OUTPUT_REFUSED", "provider": str(provider)[:80]}) result = check_report(text) - firewall[role] = result.decision + task.firewall[role] = result.decision findings = [{"kind": f.kind, "verdict": f.verdict, "reason": f.reason, "sentence": f.sentence[:240]} for f in result.findings] - outputs[role] = {"role": role, "text": text, "provider": str(provider)[:80], "text_sha256": _sha(text), - "firewall": result.decision, "findings": findings, "route": route} + task.outputs[role] = {"role": role, "text": text, "provider": str(provider)[:80], "text_sha256": _sha(text), + "firewall": result.decision, "findings": findings, "route": route} where = "" if route is None else (" (left this device)" if route.get("left_device") else " (on this device)") - emit(role, stage[role], f"{len(text)} characters via {str(provider)[:80]}{where}") - emit("OSIRIS", "FIREWALL_" + result.decision, f"{role}: {len(findings)} finding(s)") + task.emit(role, _STAGE[role], f"{len(text)} characters via {str(provider)[:80]}{where}") + task.emit("OSIRIS", "FIREWALL_" + result.decision, f"{role}: {len(findings)} finding(s)") + - verdict, verdict_conflicted, all_verdicts = parse_aiden_verdict(outputs["AIDEN"]["text"]) if "AIDEN" in outputs else (None, False, []) - if failure: - decision, reason = "FAILED", failure +class _DecisionExecutor(Executor): + """OSIRIS: derive the decision, write the receipt, yield the task result.""" + + def __init__(self, receipts_path: str) -> None: + self.receipts_path = receipts_path + super().__init__("OSIRIS") + + @handler(input=_CouncilTask) + async def decide_task(self, task: _CouncilTask, ctx: WorkflowContext) -> None: + await ctx.yield_output(_finish(task, self.receipts_path)) + + +def _finish(task: _CouncilTask, receipts_path: str) -> Dict[str, Any]: + outputs = task.outputs + verdict, verdict_conflicted, all_verdicts = parse_aiden_verdict(outputs["AIDEN"]["text"]) \ + if "AIDEN" in outputs else (None, False, []) + if task.failure: + decision, reason = "FAILED", task.failure else: detail = f"conflicting ({', '.join(all_verdicts)}) -> {verdict}" if verdict_conflicted else (verdict or "none given") - emit("AIDEN", "VERDICT", detail) - decision, reason = decide(firewall, verdict, verdict_conflicted=verdict_conflicted) - emit("OSIRIS", "DECISION_" + decision, reason) + task.emit("AIDEN", "VERDICT", detail) + decision, reason = decide(task.firewall, verdict, verdict_conflicted=verdict_conflicted) + task.emit("OSIRIS", "DECISION_" + decision, reason) try: os.makedirs(os.path.dirname(os.path.abspath(receipts_path)), mode=0o700, exist_ok=True) row = Receipts(receipts_path).append(RECEIPT_KIND, { - "task_id": task_id, "objective_sha256": _sha(objective), "context_sha256": _sha(context), + "task_id": task.task_id, "objective_sha256": _sha(task.objective), "context_sha256": _sha(task.context), "evidence_class": EVIDENCE_CLASS, "decision": decision, "reason": reason, "aiden_verdict": verdict, - "allow_cloud": allow_cloud, + "allow_cloud": task.allow_cloud, "roles": [{"role": r, "provider": outputs[r]["provider"], "text_sha256": outputs[r]["text_sha256"], "firewall": outputs[r]["firewall"], "findings": len(outputs[r]["findings"]), "route": outputs[r]["route"]} for r in ROLES if r in outputs], - "failed_routes": failed_routes, - "events": len(events) + 1, "executed": False, + "failed_routes": task.failed_routes, + "events": len(task.events) + 1, "executed": False, }) chain_valid = Receipts.verify(receipts_path) except Exception as e: # noqa: BLE001 - an unreceipted task is not reported as a result raise ReceiptError(f"the task receipt could not be written ({type(e).__name__}); no result is reported") from e - emit("OSIRIS", "RECEIPT_RECORDED", f"{RECEIPT_KIND} {row['hash'][:16]}") + task.emit("OSIRIS", "RECEIPT_RECORDED", f"{RECEIPT_KIND} {row['hash'][:16]}") return { - "schema": "osiris-agent-task/v1", "task_id": task_id, "objective": objective, + "schema": "osiris-agent-task/v1", "task_id": task.task_id, "objective": task.objective, "evidence_class": EVIDENCE_CLASS, "orchestrator": "osiris_cli.orchestration.council", - "decision": decision, "reason": reason, "aiden_verdict": verdict, "allow_cloud": allow_cloud, - "failed_routes": failed_routes, + "decision": decision, "reason": reason, "aiden_verdict": verdict, "allow_cloud": task.allow_cloud, + "failed_routes": task.failed_routes, "authority": {"execution": "NONE", "executed": False, "note": "Model text is not an approval or evidence. The operator decides what happens next."}, "agents": [outputs[r] for r in ROLES if r in outputs], - "events": events, + "events": task.events, "receipt": {"kind": row["kind"], "hash": row["hash"], "prev": row["prev"], "chain_valid": chain_valid}, } +def _failed(task: Any) -> bool: + return task.failure is not None + + +def council_workflow(receipts_path: str) -> Workflow: + """The council as a workflow: AURA -> AIDEN -> IRIS -> OSIRIS, where a role that fails sends + the task straight to OSIRIS. A new workflow per task: executors keep no state between tasks.""" + aura, aiden, iris = (_RoleExecutor(r) for r in ROLES) + osiris = _DecisionExecutor(receipts_path) + return (WorkflowBuilder(name="council", start_executor=aura) + .add_switch_case_edge_group(aura, [Case(_failed, osiris), Default(aiden)]) + .add_switch_case_edge_group(aiden, [Case(_failed, osiris), Default(iris)]) + .add_edge(iris, osiris) + .build()) + + +def run_task(objective: Any, context: Any = None, *, receipts_path: str, model_fn: Optional[ModelFn] = None, + claims: Optional[List[str]] = None, allow_cloud: Any = False) -> Dict[str, Any]: + if not isinstance(objective, str) or not objective.strip(): + raise CouncilError("objective must be a non-empty string") + objective = objective.strip() + if len(objective) > MAX_OBJECTIVE: + raise CouncilError(f"objective is longer than {MAX_OBJECTIVE} characters") + if context is None: + context = "" + if not isinstance(context, str) or len(context) > MAX_CONTEXT: + raise CouncilError(f"context must be a string of at most {MAX_CONTEXT} characters") + context = context.strip() + if not isinstance(allow_cloud, bool): + raise CouncilError("allow_cloud must be true or false") + + model_fn = model_fn or routed_model_fn(allow_cloud) + claims = claim_lines() if claims is None else claims + task = _CouncilTask(task_id="task-" + secrets.token_hex(6), objective=objective, context=context, claims=claims, + allow_cloud=allow_cloud, model_fn=model_fn, + base=f"Objective:\n{objective}" + (f"\n\nContext from the workspace:\n{context}" if context else "")) + task.emit("OSIRIS", "TASK_ACCEPTED", f"{task.task_id}: objective {_sha(objective)[:16]}, {len(claims)} claims in context, " + f"cloud {'allowed' if allow_cloud else 'not allowed'}") + result = council_workflow(receipts_path).run_sync(task) + if result.status != COMPLETED or len(result.outputs) != 1: + raise CouncilError(f"the council workflow ended {result.status}: {result.reason}") + return result.outputs[0] + + def task_receipts(receipts_path: str) -> Dict[str, Any]: import json rows: List[Dict[str, Any]] = [] diff --git a/osiris_cli/orchestration/trio.py b/osiris_cli/orchestration/trio.py index ff68d64f..bfa3578a 100644 --- a/osiris_cli/orchestration/trio.py +++ b/osiris_cli/orchestration/trio.py @@ -10,6 +10,8 @@ * The best outcome is PENDING_HUMAN_APPROVAL. Nothing here applies, merges or promotes. * Candidates stay UNMEASURED until the runner has measured them; rejected and quarantined candidates are kept (patch + evidence) under the run directory. + * The four steps run as a workflow (``osiris_cli.runtime``): baseline -> research -> developer + -> critic. ``trio_workflow`` builds it; ``run_trio`` keeps the run record and receipt chain. """ from __future__ import annotations @@ -28,6 +30,7 @@ from pathlib import Path from typing import Callable, Dict, List, Optional, Set, Tuple +from ..runtime._workflows import Executor, Workflow, WorkflowBuilder, WorkflowContext, handler from .agent_spec import (AgentRun, AgentSpec, AgentState, BudgetExceeded, RunBudget, digest, new_run_id) from .controller import GovernanceController @@ -401,68 +404,111 @@ def verify_chain(path: str) -> bool: return True -def run_trio(repo: str, propose_fn: ProposeFn, out_dir: str, *, timeout: float = 60.0, - budget: Optional[RunBudget] = None, - supplementary_fn: Optional[Callable[[str], str]] = None, sandboxed: bool = False) -> TrioResult: - """Run the slice. ``repo`` is only read. ``out_dir`` receives the run record (and must not be - inside ``repo``); the receipt chain there is its own file, not the live genome ledger.""" - if sandboxed: - from osiris_cli import sandbox - if not sandbox.available(): - raise sandbox.SandboxUnavailable("sandboxed run requested but no namespace sandbox is available") - repo, out_dir = os.path.realpath(repo), os.path.realpath(out_dir) - if out_dir == repo or out_dir.startswith(repo + os.sep): - raise ValueError("out_dir must be outside the repo under test") - run_id = new_run_id() - run_dir = os.path.join(out_dir, run_id) - os.makedirs(run_dir) - budget = budget or RunBudget() - repo_before = tree_digest(repo) - res = TrioResult(run_id, "FAILED", "UNMEASURED", run_dir) - runs: List[AgentRun] = [] - work = tempfile.mkdtemp(prefix="osiris_trio_") - chain = os.path.join(out_dir, "receipts.jsonl") - try: - # frozen baseline - base_sb = make_sandbox(repo, work) - res.baseline, base_pass, base_fail = run_pytest(base_sb, timeout, sandboxed) - if res.baseline.green: - res.outcome, res.reasons = "NO_DEFECT", ["baseline suite is already green"] - return res - - r = AgentRun(RESEARCH, run_id, budget) - - runs.append(r) - r.start({"repo_digest": repo_before}) - findings = research(base_sb, res.baseline, base_fail) - r.finish(asdict(findings)) - if not findings.sources: - res.outcome, res.reasons = "FAILED", ["research found no implicated source file"] - return res - - d = AgentRun(DEVELOPER, run_id, budget) - - runs.append(d) +@dataclass +class _TrioState: + """One run as it moves through the trio workflow (baseline -> research -> developer -> critic).""" + + repo: str + propose_fn: ProposeFn + timeout: float + budget: RunBudget + supplementary_fn: Optional[Callable[[str], str]] + sandboxed: bool + run_id: str + run_dir: str + work: str + repo_before: str + res: TrioResult + runs: List[AgentRun] = field(default_factory=list) + base_sb: str = "" + base_pass: Set[str] = field(default_factory=set) + base_fail: Set[str] = field(default_factory=set) + findings: Optional[ResearchFindings] = None + out: Optional[DeveloperOutput] = None + diffs: Dict[str, str] = field(default_factory=dict) + refused: List[str] = field(default_factory=list) + + +class _BaselineStep(Executor): + """Freeze the unpatched run. A green baseline ends the run as NO_DEFECT.""" + + def __init__(self) -> None: + super().__init__("baseline") + + @handler(input=_TrioState) + async def step(self, st: _TrioState, ctx: WorkflowContext) -> None: + st.base_sb = make_sandbox(st.repo, st.work) + st.res.baseline, st.base_pass, st.base_fail = run_pytest(st.base_sb, st.timeout, st.sandboxed) + if st.res.baseline.green: + st.res.outcome, st.res.reasons = "NO_DEFECT", ["baseline suite is already green"] + return + await ctx.send_message(st) + + +class _ResearchStep(Executor): + def __init__(self) -> None: + super().__init__("research") + + @handler(input=_TrioState) + async def step(self, st: _TrioState, ctx: WorkflowContext) -> None: + r = AgentRun(RESEARCH, st.run_id, st.budget) + + st.runs.append(r) + r.start({"repo_digest": st.repo_before}) + st.findings = research(st.base_sb, st.res.baseline, st.base_fail) + r.finish(asdict(st.findings)) + if not st.findings.sources: + st.res.outcome, st.res.reasons = "FAILED", ["research found no implicated source file"] + return + await ctx.send_message(st) + + +class _DeveloperStep(Executor): + def __init__(self) -> None: + super().__init__("developer") + + @handler(input=_TrioState) + async def step(self, st: _TrioState, ctx: WorkflowContext) -> None: + findings, res = st.findings, st.res + assert findings is not None + d = AgentRun(DEVELOPER, st.run_id, st.budget) + + st.runs.append(d) d.start(asdict(findings)) - dev_sb = make_sandbox(repo, work) - out = propose_fn(findings, dev_sb) + dev_sb = make_sandbox(st.repo, st.work) + out = st.propose_fn(findings, dev_sb) diffs, refused = apply_to_sandbox(dev_sb, out) d.finish({"files": sorted(out.patched_files), "report": out.report}) res.findings, res.proposed_files, res.refused = findings, dict(out.patched_files), refused res.patched_files = {k: v for k, v in out.patched_files.items() if k in diffs} res.dev_report = out.report - Path(run_dir, "candidate.json").write_text(json.dumps( + Path(st.run_dir, "candidate.json").write_text(json.dumps( {"proposed_files": out.patched_files, "accepted": sorted(diffs), "refused": refused, "report": out.report}, indent=2, sort_keys=True)) for rel, df in diffs.items(): - Path(run_dir, "candidate_" + rel.replace("/", "__") + ".diff").write_text(df) + Path(st.run_dir, "candidate_" + rel.replace("/", "__") + ".diff").write_text(df) + st.out, st.diffs, st.refused = out, diffs, refused + await ctx.send_message(st) - c = AgentRun(CRITIC, run_id, budget) - runs.append(c) - c.start({"diffs": digest(diffs), "refused": refused}) +class _CriticStep(Executor): + """Re-derive the verdict from fresh runs plus the diff; set the outcome.""" + + def __init__(self) -> None: + super().__init__("critic") + + @handler(input=_TrioState) + async def step(self, st: _TrioState, ctx: WorkflowContext) -> None: + res, out = st.res, st.out + assert out is not None and st.findings is not None + d = st.runs[-1] + c = AgentRun(CRITIC, st.run_id, st.budget) + + st.runs.append(c) + c.start({"diffs": digest(st.diffs), "refused": st.refused}) verdict, res.candidate, fw = critic_review( - repo, diffs, out.patched_files, refused, findings, base_pass, out.report, timeout, work, supplementary_fn, sandboxed) + st.repo, st.diffs, out.patched_files, st.refused, st.findings, st.base_pass, out.report, st.timeout, + st.work, st.supplementary_fn, st.sandboxed) res.critic, res.firewall, res.candidate_status = verdict, fw, "MEASURED" c.finish({"approve": verdict.approve, "reasons": verdict.reasons}) @@ -480,9 +526,43 @@ def run_trio(repo: str, propose_fn: ProposeFn, out_dir: str, *, timeout: float = d.to(AgentState.REJECTED, "; ".join(res.reasons)[:300]) elif res.outcome == "QUARANTINED": d.to(AgentState.QUARANTINED, "; ".join(res.reasons)[:300]) + + +def trio_workflow() -> Workflow: + """The trio as a workflow: baseline -> research -> developer -> critic. A step that ends the + run early (green baseline, nothing implicated) sends nothing on. A new workflow per run.""" + steps = [_BaselineStep(), _ResearchStep(), _DeveloperStep(), _CriticStep()] + return WorkflowBuilder(name="trio", start_executor=steps[0]).add_chain(steps).build() + + +def run_trio(repo: str, propose_fn: ProposeFn, out_dir: str, *, timeout: float = 60.0, + budget: Optional[RunBudget] = None, + supplementary_fn: Optional[Callable[[str], str]] = None, sandboxed: bool = False) -> TrioResult: + """Run the slice. ``repo`` is only read. ``out_dir`` receives the run record (and must not be + inside ``repo``); the receipt chain there is its own file, not the live genome ledger.""" + if sandboxed: + from osiris_cli import sandbox + if not sandbox.available(): + raise sandbox.SandboxUnavailable("sandboxed run requested but no namespace sandbox is available") + repo, out_dir = os.path.realpath(repo), os.path.realpath(out_dir) + if out_dir == repo or out_dir.startswith(repo + os.sep): + raise ValueError("out_dir must be outside the repo under test") + run_id = new_run_id() + run_dir = os.path.join(out_dir, run_id) + os.makedirs(run_dir) + budget = budget or RunBudget() + repo_before = tree_digest(repo) + res = TrioResult(run_id, "FAILED", "UNMEASURED", run_dir) + work = tempfile.mkdtemp(prefix="osiris_trio_") + chain = os.path.join(out_dir, "receipts.jsonl") + st = _TrioState(repo, propose_fn, timeout, budget, supplementary_fn, sandboxed, run_id, run_dir, work, + repo_before, res) + try: + trio_workflow().run_sync(st) except BudgetExceeded as e: res.outcome, res.reasons = "FAILED", [f"budget: {e}"] finally: + runs = st.runs repo_after = tree_digest(repo) if repo_after != repo_before: # would be a bug in this module; fail loudly res.outcome, res.reasons = "FAILED", res.reasons + ["REPO MODIFIED DURING RUN"] diff --git a/osiris_cli/runtime/PORT_MAP.md b/osiris_cli/runtime/PORT_MAP.md index 54137666..df33821d 100644 --- a/osiris_cli/runtime/PORT_MAP.md +++ b/osiris_cli/runtime/PORT_MAP.md @@ -1,10 +1,10 @@ # osiris_cli.runtime port map -Phase 1 of re-engineering Microsoft Agent Framework (MAF) into osiris-cli. +Phases 1 and 2 of re-engineering Microsoft Agent Framework (MAF) into osiris-cli. Phase 1: the governed agent core. Phase 2: workflows, checkpoints and multi-agent orchestrations, with the trio and the council moved onto them. - **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. +- **Size:** MAF's Python core is about 86,000 lines, of which workflows are about 17,000, and its orchestrations package about 6,400. This runtime is about 2,600 lines of code after Phase 1 and about 4,700 after Phase 2. ## Files @@ -19,8 +19,11 @@ Phase 1 of re-engineering Microsoft Agent Framework (MAF) into osiris-cli. | `_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. | +| `_workflows.py` (Phase 2) | `core/agent_framework/_workflows/` (`_executor.py`, `_function_executor.py`, `_workflow_context.py`, `_edge.py`, `_edge_runner.py`, `_workflow_builder.py`, `_runner.py`, `_workflow.py`, `_events.py`) | Executors with typed `@handler`s and `@response_handler`; `WorkflowBuilder` (`add_edge` with conditions, fan-out with selection, fan-in, switch-case, `add_chain`); Pregel supersteps with state committed at superstep boundaries; `request_info` and `run(responses=...)`; streaming; run states | Per-superstep results are applied in executor registration order, so runs are deterministic (streaming is per superstep). A superstep limit ends the run as `STOPPED` with messages kept, not an exception. Executor exceptions are re-raised unchanged. Responses must have exactly the requested type (no `1` for `True`). No build-time edge type check. Optional run governance: task ledger record (`kind` `workflow`), intent gate on the input, one budget step per superstep, evidence firewall on text outputs. | +| `_checkpoints.py` (Phase 2) | `core/agent_framework/_workflows/_checkpoint.py`, `_checkpoint_encoding.py` | The checkpoint record (workflow name, graph signature, messages, state, executor and edge state, pending requests, previous checkpoint); storage interface; in-memory and file storage; refusing a checkpoint from another graph | No pickle. MAF encodes non-JSON values with pickle behind an allowlist it calls "not a security boundary". Here only JSON values and types registered with `register_checkpoint_type` are written or rebuilt; anything else refuses to checkpoint. File storage is a hash-chained JSONL per workflow name; the checkpoint id is the record hash and a tampered file is refused. | +| `_orchestrations.py` (Phase 2) | `core/agent_framework/_workflows/_agent_executor.py`; `orchestrations/agent_framework_orchestrations/` (`_sequential.py`, `_concurrent.py`, `_group_chat.py`, `_handoff.py`, `_magentic.py`) | `AgentExecutor`; Sequential; Concurrent with the default aggregator; group chat; handoff tools that end the agent's turn; Magentic task ledger, progress ledger, stall and reset counts | Builders are governed by default (same rule as `Agent`). Group chat: the speaker is chosen by a code `selector`. Handoff: tools only for the routes declared, checked again with `max_handoffs` before the next agent runs; handoff calls are removed from the conversation passed on. Magentic: the progress ledger is parsed strictly; an invalid ledger or unknown speaker counts as a stall; a limit ends the run with no final answer. | -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. +Tests: `tests/test_runtime_{middleware,tools,agent,clients,governance,sessions_telemetry}.py` (Phase 1); `tests/test_runtime_{workflows,orchestrations}.py` and `tests/test_council_trio_workflows.py` (Phase 2). The cases mirrored from MAF's `core/tests` name the source test file in their module docstring. ## Governance order (outermost first) @@ -30,11 +33,19 @@ Tests: `tests/test_runtime_{middleware,tools,agent,clients,governance,sessions_t 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 +## Workflow-level governance (Phase 2) + +A workflow run given a `GovernanceConfig` opens a `workflow` task before any executor runs, refuses input at a blocked risk tier (and asks for a grant at a grant-required one), charges one budget step per superstep, and closes the task with the run's status, superstep count, graph signature, checkpoint head and the evidence firewall's decision on each text output. The five orchestration builders do this by default. Agents inside a workflow are governed by their own stack regardless, so an orchestration run leaves one `workflow` task and one `agent` task per agent turn. Hand-built workflows of plain executors run without a task record unless given a config. + +## Trio and council (Phase 2) + +`orchestration/trio.py` and `orchestration/council.py` now run on the engine (`trio_workflow()`: baseline → research → developer → critic; `council_workflow()`: AURA → AIDEN → IRIS → OSIRIS, where a failing role goes straight to OSIRIS through a switch-case edge). `run_trio` and `run_task` keep their signatures, receipts and results. Their existing test files pass unchanged. 27 recorded scenarios (12 council outcomes, 3 invalid inputs, a receipt failure, the receipt rows, 8 trio outcomes, a green repo and an out-dir refusal) give identical results on `main` and after the move, apart from receipt hashes, which contain a timestamp. They do not open task-ledger records (they did not before); bringing them under L0's task ledger is a separate decision, because their tests do not isolate `$OSIRIS_HOME`. + +## Not ported yet | MAF area | Why not now | |---|---| -| Workflows (`_workflows/`, about 12k lines) and `orchestrations` | Phase 2 | +| Workflow-as-agent, sub-workflows (`WorkflowExecutor`), declarative and functional workflow APIs, visualization, checkpoint storage backends other than memory and file | Later; not needed by trio, council or the five patterns | | 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 | @@ -50,8 +61,8 @@ ToolPolicy is innermost, so it checks the arguments that will actually run. The 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. +This package does not import or change it. The two overlap on policy hooks, traces, context compaction, session storage and now scheduling and checkpoints (`osiris.runtime.persistence` keeps checkpoints in SQLite). Phase 2 did not touch it; the ownership decision is still open. ## 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. +`osiris_cli/task_context.py`: `KINDS` gains `"agent"` (Phase 1) and `"workflow"` (Phase 2) 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 index 5b91874c..e80ffa01 100644 --- a/osiris_cli/runtime/__init__.py +++ b/osiris_cli/runtime/__init__.py @@ -1,4 +1,5 @@ -"""OSIRIS runtime: governed agents, tools, middleware, sessions and telemetry. +"""OSIRIS runtime: governed agents, tools, middleware, sessions, telemetry, workflows and +multi-agent orchestrations. 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 @@ -22,6 +23,16 @@ def count_lines(path: str) -> int: """ from ._agents import Agent +from ._checkpoints import ( + CheckpointEncodingError, + CheckpointError, + CheckpointIntegrityError, + CheckpointStorage, + FileCheckpointStorage, + InMemoryCheckpointStorage, + WorkflowCheckpoint, + register_checkpoint_type, +) from ._clients import AnthropicChatClient, ChatClient, ChatClientError, ProviderChatClient from ._governance import ( ApprovalRequest, @@ -47,6 +58,21 @@ def count_lines(path: str) -> int: chat_middleware, function_middleware, ) +from ._orchestrations import ( + AgentExecutor, + AgentResult, + ConcurrentBuilder, + GroupChatBuilder, + GroupChatState, + HandoffBuilder, + HandoffUserInputRequest, + MagenticBuilder, + MagenticResult, + SequentialBuilder, + default_aggregate, + parse_progress_ledger, + round_robin, +) from ._sessions import ( AgentSession, ContextAdditions, @@ -67,6 +93,30 @@ def count_lines(path: str) -> int: Message, UsageDetails, ) +from ._workflows import ( + BLOCKED, + CANCELLED, + COMPLETED, + FAILED, + IDLE_WITH_PENDING_REQUESTS, + STOPPED, + Case, + Default, + Executor, + FunctionExecutor, + RequestInfo, + Workflow, + WorkflowBuilder, + WorkflowContext, + WorkflowError, + WorkflowEvent, + WorkflowGovernanceError, + WorkflowRunResult, + executor, + handler, + response_handler, + run_blocking, +) SOURCE_FRAMEWORK = "microsoft/agent-framework" SOURCE_COMMIT = "567e4d458b59b83ac9b19088a43a2853094c6df1" @@ -81,4 +131,13 @@ def count_lines(path: str) -> int: "PolicyRefusal", "ProviderChatClient", "RunState", "SOURCE_COMMIT", "SOURCE_FRAMEWORK", "SpanRecorder", "ToolArgumentError", "ToolError", "UsageDetails", "agent_middleware", "chat_middleware", "function_middleware", "load_runtime_policy", "make_exec_tool", "tool", + # Phase 2: workflows, checkpoints, orchestrations + "AgentExecutor", "AgentResult", "BLOCKED", "CANCELLED", "COMPLETED", "Case", "CheckpointEncodingError", + "CheckpointError", "CheckpointIntegrityError", "CheckpointStorage", "ConcurrentBuilder", "Default", "Executor", + "FAILED", "FileCheckpointStorage", "FunctionExecutor", "GroupChatBuilder", "GroupChatState", "HandoffBuilder", + "HandoffUserInputRequest", "IDLE_WITH_PENDING_REQUESTS", "InMemoryCheckpointStorage", "MagenticBuilder", + "MagenticResult", "RequestInfo", "STOPPED", "SequentialBuilder", "Workflow", "WorkflowBuilder", + "WorkflowCheckpoint", "WorkflowContext", "WorkflowError", "WorkflowEvent", "WorkflowGovernanceError", + "WorkflowRunResult", "default_aggregate", "executor", "handler", "parse_progress_ledger", + "register_checkpoint_type", "response_handler", "round_robin", "run_blocking", ] diff --git a/osiris_cli/runtime/_agents.py b/osiris_cli/runtime/_agents.py index fb459237..31f9d326 100644 --- a/osiris_cli/runtime/_agents.py +++ b/osiris_cli/runtime/_agents.py @@ -106,6 +106,7 @@ def __init__(self, client: ChatClient, *, name: str = "osiris-agent", instructio self.governance = GovernanceStack.build(governance.config) else: raise TypeError("governance must be a GovernanceConfig, a GovernanceStack, None, or False") + self._user_middleware: List[Any] = list(middleware) user: Dict[str, List[Any]] = {KIND_AGENT: [], KIND_CHAT: [], KIND_FUNCTION: []} for item in middleware: user[middleware_kind(item)].append(item) @@ -118,6 +119,17 @@ def __init__(self, client: ChatClient, *, name: str = "osiris-agent", instructio def __repr__(self) -> str: return f"Agent({self.name!r}, tools={[t.name for t in self.tools]}, governed={self.governance is not None})" + def clone(self, *, name: Optional[str] = None, extra_tools: Sequence[Any] = (), + extra_middleware: Sequence[Any] = ()) -> "Agent": + """A new agent with this one's client, instructions, governance configuration, settings and + middleware, plus ``extra_tools`` and ``extra_middleware`` (placed after this agent's own, + still inside the governance stack). Orchestrations use it to add handoff tools.""" + return Agent(self.client, name=name or self.name, instructions=self.instructions, + tools=list(self.tools) + list(extra_tools), + middleware=list(self._user_middleware) + list(extra_middleware), + governance=self.governance.config if self.governance is not None else False, + context_providers=self.context_providers, invocation=self.invocation, options=self.options) + @property def pipelines(self) -> Dict[str, List[str]]: """Middleware names per pipeline, outermost first.""" diff --git a/osiris_cli/runtime/_checkpoints.py b/osiris_cli/runtime/_checkpoints.py new file mode 100644 index 00000000..25c84aaf --- /dev/null +++ b/osiris_cli/runtime/_checkpoints.py @@ -0,0 +1,345 @@ +# Portions adapted from microsoft/agent-framework@567e4d458b59b83ac9b19088a43a2853094c6df1 +# python/packages/core/agent_framework/_workflows/_checkpoint.py (the checkpoint record: workflow +# name, graph signature, messages, state, pending requests, previous checkpoint; the storage +# interface: save / load / list / latest; in-memory and file storage). +# MIT License, Copyright (c) Microsoft Corporation. See THIRD_PARTY_NOTICES.md and PORT_MAP.md. +"""Workflow checkpoints: what a paused or interrupted workflow run needs to continue. + +Deliberate differences from the source: + +* No pickle. The source encodes non-JSON values with pickle (``_checkpoint_encoding.py``) and + narrows what may be rebuilt with an allowlist it calls "not a security boundary". Here a value + is written only if it is JSON (``None``, bool, int, finite float, str, list, tuple, dict with + str keys) or an instance of a type registered with ``register_checkpoint_type``; anything else + refuses to checkpoint. Reading rebuilds only registered types, so a checkpoint file cannot make + this process construct an arbitrary class. +* ``FileCheckpointStorage`` keeps one hash-chained JSONL file per workflow name. A checkpoint's id + is its record hash, and reading a file verifies the whole chain first, so an edited or + truncated-in-the-middle file is refused instead of resumed. +""" + +from __future__ import annotations + +import dataclasses +import hashlib +import json +import math +import os +import re +import time +from abc import ABC, abstractmethod +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Callable, Dict, List, Optional, Tuple, Type + +from ._types import AgentResponse, Content, Message, UsageDetails, canonical_json + +CHECKPOINT_SCHEMA = "osiris.workflow.checkpoint.v1" +GENESIS = "0" * 64 +_NAME_RE = re.compile(r"^[A-Za-z0-9_.-]{1,64}$") + + +class CheckpointError(RuntimeError): + """A checkpoint could not be written, found or trusted.""" + + +class CheckpointEncodingError(CheckpointError): + """A value in the workflow's state is not JSON and its type is not registered.""" + + +class CheckpointIntegrityError(CheckpointError): + """A checkpoint file's hash chain does not verify.""" + + +# ── encoding ──────────────────────────────────────────────────────────────────────────────── + +Encoder = Callable[[Any], Any] +Decoder = Callable[[Any], Any] +_REGISTRY: Dict[str, Tuple[type, Encoder, Decoder]] = {} +_BY_TYPE: Dict[type, str] = {} +_BUILTIN_RESPONSE_TYPES: Dict[str, type] = {"bool": bool, "int": int, "float": float, "str": str, + "dict": dict, "list": list} + + +def _type_name(cls: type) -> str: + return f"{cls.__module__}:{cls.__qualname__}" + + +def register_checkpoint_type(cls: type, *, encode: Optional[Encoder] = None, decode: Optional[Decoder] = None, + name: Optional[str] = None) -> type: + """Allow instances of ``cls`` in checkpoints. A dataclass needs no functions: its fields are + encoded in turn and passed back to its constructor. Other classes need ``encode`` (instance -> + encodable value) and ``decode`` (that value -> instance). Usable as a class decorator.""" + key = name or _type_name(cls) + if encode is None or decode is None: + if not dataclasses.is_dataclass(cls): + raise TypeError(f"{cls.__qualname__} is not a dataclass; give encode and decode functions") + names = [f.name for f in dataclasses.fields(cls) if f.init] + + def encode(value: Any, _names: List[str] = names) -> Any: + return {n: getattr(value, n) for n in _names} + + def decode(value: Any, _cls: type = cls) -> Any: + return _cls(**value) + existing = _REGISTRY.get(key) + if existing is not None and existing[0] is not cls: + raise TypeError(f"checkpoint type name {key!r} is already registered for another class") + _REGISTRY[key] = (cls, encode, decode) + _BY_TYPE[cls] = key + return cls + + +def encode_value(value: Any) -> Any: + """Encode ``value`` for a checkpoint, or raise CheckpointEncodingError.""" + if value is None or isinstance(value, (bool, str)): + return value + if isinstance(value, int): + return value + if isinstance(value, float): + if not math.isfinite(value): + raise CheckpointEncodingError("a non-finite float cannot be checkpointed") + return value + if isinstance(value, list): + return [encode_value(v) for v in value] + if isinstance(value, tuple) and type(value) is tuple: + return {"$tuple": [encode_value(v) for v in value]} + if isinstance(value, dict) and type(value) is dict: + if not all(isinstance(k, str) for k in value): + raise CheckpointEncodingError("only dicts with str keys can be checkpointed") + return {"$dict": {k: encode_value(v) for k, v in value.items()}} + key = _BY_TYPE.get(type(value)) + if key is None: + raise CheckpointEncodingError( + f"{type(value).__module__}.{type(value).__qualname__} is not registered for checkpoints " + "(osiris_cli.runtime.register_checkpoint_type)") + return {"$type": key, "$value": encode_value(_REGISTRY[key][1](value))} + + +def decode_value(data: Any) -> Any: + """Rebuild a value written by ``encode_value``. Only registered types are constructed.""" + if data is None or isinstance(data, (bool, int, float, str)): + return data + if isinstance(data, list): + return [decode_value(v) for v in data] + if isinstance(data, dict): + if set(data) == {"$tuple"}: + return tuple(decode_value(v) for v in data["$tuple"]) + if set(data) == {"$dict"} and isinstance(data["$dict"], dict): + return {k: decode_value(v) for k, v in data["$dict"].items()} + if set(data) == {"$type", "$value"}: + entry = _REGISTRY.get(data["$type"]) + if entry is None: + raise CheckpointEncodingError(f"checkpoint names an unregistered type {data['$type']!r}") + return entry[2](decode_value(data["$value"])) + raise CheckpointEncodingError(f"malformed checkpoint value: {str(data)[:80]}") + + +def encode_response_type(cls: type) -> str: + for name, builtin in _BUILTIN_RESPONSE_TYPES.items(): + if cls is builtin: + return name + key = _BY_TYPE.get(cls) + if key is None: + raise CheckpointEncodingError(f"response type {cls.__qualname__} is not registered for checkpoints") + return key + + +def decode_response_type(name: str) -> type: + if name in _BUILTIN_RESPONSE_TYPES: + return _BUILTIN_RESPONSE_TYPES[name] + entry = _REGISTRY.get(name) + if entry is None: + raise CheckpointEncodingError(f"checkpoint names an unregistered response type {name!r}") + return entry[0] + + +register_checkpoint_type(Content, encode=lambda c: c.to_dict(), decode=lambda d: Content.from_dict(d), + name="osiris.runtime:Content") +register_checkpoint_type(Message, encode=lambda m: m.to_dict(), decode=lambda d: Message.from_dict(d), + name="osiris.runtime:Message") +register_checkpoint_type(UsageDetails, name="osiris.runtime:UsageDetails") + + +def _encode_agent_response(r: AgentResponse) -> Dict[str, Any]: + return {"messages": list(r.messages), "agent_name": r.agent_name, "run_id": r.run_id, "usage": r.usage, + "finish_reason": r.finish_reason, "model_id": r.model_id, "status": r.status, + "governance": json.loads(canonical_json(r.governance))} + + +def _decode_agent_response(d: Dict[str, Any]) -> AgentResponse: + return AgentResponse(messages=d["messages"], agent_name=d["agent_name"], run_id=d["run_id"], usage=d["usage"], + finish_reason=d["finish_reason"], model_id=d["model_id"], status=d["status"], + governance=d["governance"]) + + +register_checkpoint_type(AgentResponse, encode=_encode_agent_response, decode=_decode_agent_response, + name="osiris.runtime:AgentResponse") + + +# ── the record ────────────────────────────────────────────────────────────────────────────── + +@dataclass +class WorkflowCheckpoint: + """Everything a run needs to continue after superstep ``superstep``. Values are encoded. + + ``checkpoint_id`` is set by the storage when saved (for file storage, the record hash); + ``previous_checkpoint_id`` is the checkpoint this run continued from, if any.""" + + workflow_name: str + graph_signature: str + run_id: str + superstep: int + messages: List[Dict[str, Any]] = field(default_factory=list) + state: Dict[str, Any] = field(default_factory=dict) + executor_states: Dict[str, Any] = field(default_factory=dict) + edge_state: Dict[str, Any] = field(default_factory=dict) + pending_requests: List[Dict[str, Any]] = field(default_factory=list) + previous_checkpoint_id: Optional[str] = None + checkpoint_id: str = "" + created_at: str = "" + + def body(self) -> Dict[str, Any]: + out = dataclasses.asdict(self) + out.pop("checkpoint_id") + return out + + @classmethod + def from_body(cls, body: Dict[str, Any], checkpoint_id: str) -> "WorkflowCheckpoint": + names = {f.name for f in dataclasses.fields(cls)} - {"checkpoint_id"} + if set(body) != names: + raise CheckpointIntegrityError(f"checkpoint {checkpoint_id[:16]} has unexpected fields") + return cls(checkpoint_id=checkpoint_id, **body) + + +class CheckpointStorage(ABC): + @abstractmethod + def save(self, checkpoint: WorkflowCheckpoint) -> str: + """Store ``checkpoint``; return and set its id.""" + + @abstractmethod + def load(self, checkpoint_id: str) -> WorkflowCheckpoint: + """The checkpoint with this id, or CheckpointError.""" + + @abstractmethod + def list_checkpoints(self, workflow_name: str) -> List[WorkflowCheckpoint]: + """This workflow's checkpoints, oldest first.""" + + def latest(self, workflow_name: str, run_id: Optional[str] = None) -> Optional[WorkflowCheckpoint]: + found = [c for c in self.list_checkpoints(workflow_name) if run_id is None or c.run_id == run_id] + return found[-1] if found else None + + +def _stamp(checkpoint: WorkflowCheckpoint) -> None: + if not checkpoint.created_at: + checkpoint.created_at = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) + + +class InMemoryCheckpointStorage(CheckpointStorage): + """For tests and runs that only need to survive within one process.""" + + def __init__(self) -> None: + self._items: List[WorkflowCheckpoint] = [] + + def save(self, checkpoint: WorkflowCheckpoint) -> str: + _stamp(checkpoint) + body = checkpoint.body() + checkpoint.checkpoint_id = hashlib.sha256( + (str(len(self._items)) + canonical_json(body)).encode("utf-8")).hexdigest() + self._items.append(WorkflowCheckpoint.from_body(json.loads(canonical_json(body)), checkpoint.checkpoint_id)) + return checkpoint.checkpoint_id + + def load(self, checkpoint_id: str) -> WorkflowCheckpoint: + for item in self._items: + if item.checkpoint_id == checkpoint_id: + return WorkflowCheckpoint.from_body(json.loads(canonical_json(item.body())), checkpoint_id) + raise CheckpointError(f"no checkpoint {checkpoint_id[:16]}") + + def list_checkpoints(self, workflow_name: str) -> List[WorkflowCheckpoint]: + return [WorkflowCheckpoint.from_body(json.loads(canonical_json(c.body())), c.checkpoint_id) + for c in self._items if c.workflow_name == workflow_name] + + +class FileCheckpointStorage(CheckpointStorage): + """One hash-chained JSONL file per workflow name in ``directory`` (created if missing). + + Each line is ``{"schema", "seq", "prev", "checkpoint", "hash"}`` with + ``hash = sha256(prev + canonical_json(checkpoint))``; the hash is the checkpoint id. The caller + chooses the directory: checkpoints are resumable run state, not a second evidence ledger.""" + + def __init__(self, directory: "os.PathLike[str] | str") -> None: + self.directory = Path(directory).resolve() + self.directory.mkdir(parents=True, exist_ok=True) + + def _path(self, workflow_name: str) -> Path: + if not _NAME_RE.match(workflow_name): + raise CheckpointError(f"workflow name {workflow_name!r} is not usable as a checkpoint file name") + path = (self.directory / f"{workflow_name}.jsonl").resolve() + if path.parent != self.directory: + raise CheckpointError("checkpoint file would fall outside the checkpoint directory") + return path + + @staticmethod + def _read(path: Path) -> List[Tuple[Dict[str, Any], str]]: + out: List[Tuple[Dict[str, Any], str]] = [] + if not path.exists(): + return out + prev = GENESIS + with open(path, encoding="utf-8") as fh: + for seq, line in enumerate(fh): + if not line.strip(): + continue + try: + record = json.loads(line) + except ValueError as exc: + raise CheckpointIntegrityError(f"{path.name} line {seq + 1} is not JSON") from exc + body = record.get("checkpoint") + expected = hashlib.sha256((prev + canonical_json(body)).encode("utf-8")).hexdigest() + if record.get("schema") != CHECKPOINT_SCHEMA or record.get("seq") != seq \ + or record.get("prev") != prev or record.get("hash") != expected: + raise CheckpointIntegrityError(f"{path.name} line {seq + 1} breaks the checkpoint hash chain") + out.append((body, expected)) + prev = expected + return out + + def save(self, checkpoint: WorkflowCheckpoint) -> str: + _stamp(checkpoint) + path = self._path(checkpoint.workflow_name) + existing = self._read(path) + prev = existing[-1][1] if existing else GENESIS + body = json.loads(canonical_json(checkpoint.body())) + digest = hashlib.sha256((prev + canonical_json(body)).encode("utf-8")).hexdigest() + record = {"schema": CHECKPOINT_SCHEMA, "seq": len(existing), "prev": prev, "checkpoint": body, "hash": digest} + with open(path, "a", encoding="utf-8", newline="\n") as fh: + fh.write(json.dumps(record, sort_keys=True, ensure_ascii=False, separators=(",", ":")) + "\n") + fh.flush() + os.fsync(fh.fileno()) + checkpoint.checkpoint_id = digest + return digest + + def load(self, checkpoint_id: str) -> WorkflowCheckpoint: + for path in sorted(self.directory.glob("*.jsonl")): + for body, digest in self._read(path): + if digest == checkpoint_id: + return WorkflowCheckpoint.from_body(body, digest) + raise CheckpointError(f"no checkpoint {checkpoint_id[:16]} in {self.directory}") + + def list_checkpoints(self, workflow_name: str) -> List[WorkflowCheckpoint]: + return [WorkflowCheckpoint.from_body(body, digest) for body, digest in self._read(self._path(workflow_name))] + + def verify(self, workflow_name: str) -> int: + """Number of checkpoints in this workflow's file; raises CheckpointIntegrityError if tampered.""" + return len(self._read(self._path(workflow_name))) + + +def registered_type_names() -> List[str]: + return sorted(_REGISTRY) + + +def response_type_ok(value: Any, expected: Type[Any]) -> bool: + """``isinstance`` without bool passing for int/float, so an approval cannot arrive as ``1`` + and a number cannot arrive as ``True``.""" + if expected is bool: + return value is True or value is False + if isinstance(value, bool): + return False + return isinstance(value, expected) diff --git a/osiris_cli/runtime/_orchestrations.py b/osiris_cli/runtime/_orchestrations.py new file mode 100644 index 00000000..e74fd91f --- /dev/null +++ b/osiris_cli/runtime/_orchestrations.py @@ -0,0 +1,662 @@ +# Portions adapted from microsoft/agent-framework@567e4d458b59b83ac9b19088a43a2853094c6df1 +# python/packages/core/agent_framework/_workflows/_agent_executor.py (an agent as an executor that +# passes the full conversation on) and python/packages/orchestrations/agent_framework_orchestrations/ +# (_sequential.py, _concurrent.py, _group_chat.py, _handoff.py, _magentic.py: the five patterns, the +# concurrent default aggregator, handoff tools that end the agent's turn, the Magentic task ledger +# and progress ledger with stall and reset counts). +# MIT License, Copyright (c) Microsoft Corporation. See THIRD_PARTY_NOTICES.md and PORT_MAP.md. +"""Multi-agent patterns built on the workflow engine. + +Every pattern's workflow is governed by default: a run opens and closes a ``workflow`` task in the +canonical task ledger, and each agent turn inside it is a governed agent run of its own. + +Deliberate differences from the source, all about who decides: + +* Group chat: the next speaker is chosen by a function you write (``selector``). The source's + default manager can be a model; here a selector that names someone outside the group fails the + run. +* Handoff: an agent gets a ``handoff_to_`` tool only for the targets ``routes`` allows it. + Calling one is a request; code checks it against ``routes`` and ``max_handoffs`` before the next + agent runs. The handoff call and its result are removed from the conversation passed on. +* Magentic: the manager model proposes the plan and, each round, a progress ledger as JSON. Code + parses it strictly, checks that ``next_speaker`` is in the team, counts stalls (an invalid or + unparseable ledger counts as one), and stops at ``max_rounds`` or when stalls exceed + ``max_stalls`` after ``max_resets`` re-plans. When a limit ends the run, no final answer is + requested: the result says why it stopped and has no answer. +""" + +from __future__ import annotations + +import json +import re +from dataclasses import dataclass, field +from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Union + +from ._agents import Agent +from ._checkpoints import CheckpointStorage, register_checkpoint_type +from ._governance import ( + GovernanceConfig, + GovernanceRequiredError, + PolicyRefusal, + governance_disabled_allowed, +) +from ._middleware import FunctionInvocationContext, FunctionMiddleware, MiddlewareTermination +from ._tools import FunctionTool +from ._types import ( + CONTENT_FUNCTION_CALL, + CONTENT_FUNCTION_RESULT, + ROLE_ASSISTANT, + ROLE_USER, + AgentResponse, + Content, + Message, +) +from ._workflows import ( + DEFAULT_MAX_SUPERSTEPS, + Executor, + FunctionExecutor, + Workflow, + WorkflowBuilder, + WorkflowContext, + WorkflowError, + handler, + response_handler, +) + +_NAME_RE = re.compile(r"^[A-Za-z0-9_-]{1,48}$") +ConversationInput = Union[str, Message, List[Message]] + + +def conversation_of(value: Any) -> List[Message]: + """A conversation from a workflow input or an agent result.""" + if isinstance(value, AgentResult): + return list(value.conversation) + if isinstance(value, str): + return [Message.user(value)] + if isinstance(value, Message): + return [value] + if isinstance(value, list) and all(isinstance(m, Message) for m in value): + return list(value) + raise WorkflowError(f"cannot make a conversation from {type(value).__name__}") + + +def resolve_governance(governance: Any) -> Optional[GovernanceConfig]: + """Builders' rule, the same as ``Agent``'s: None means a default ``GovernanceConfig``; False is + accepted only when the runtime policy has ``"governance_required": false``.""" + if governance is None or governance is True: + return GovernanceConfig() + 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") + return None + if isinstance(governance, GovernanceConfig): + return governance + raise TypeError("governance must be a GovernanceConfig, None, or False") + + +# ── an agent as an executor ───────────────────────────────────────────────────────────────── + +@register_checkpoint_type +@dataclass +class AgentResult: + """What an ``AgentExecutor`` passes on: the agent's response and the whole conversation so far.""" + + executor_id: str + response: AgentResponse + conversation: List[Message] = field(default_factory=list) + + @property + def text(self) -> str: + return self.response.text + + +class AgentExecutor(Executor): + """Runs a governed ``Agent`` on the conversation it receives (a string, a message, a list of + messages, or an ``AgentResult``) and sends an ``AgentResult`` on; with no outgoing edge it + yields the result as a workflow output instead.""" + + def __init__(self, agent: Agent, *, id: Optional[str] = None, output: bool = False) -> None: # noqa: A002 + if not isinstance(agent, Agent): + raise TypeError("AgentExecutor wraps an Agent") + self.agent = agent + self.output = output + super().__init__(id or agent.name) + + async def run_turn(self, conversation: List[Message]) -> AgentResult: + response = await self.agent.run(conversation) + _label(response.messages, self.agent.name) + return AgentResult(self.id, response, list(conversation) + list(response.messages)) + + @handler(input=Union[str, Message, List[Message], AgentResult]) + async def on_input(self, message: Any, ctx: WorkflowContext) -> None: + result = await self.run_turn(conversation_of(message)) + if self.output or not ctx.has_outgoing_edges(): + await ctx.yield_output(result) + if ctx.has_outgoing_edges(): + await ctx.send_message(result) + + +def _label(messages: List[Message], name: str) -> None: + """Name the agent on its assistant messages, so a shared conversation shows who said what.""" + for m in messages: + if m.role == ROLE_ASSISTANT and not m.author_name: + m.author_name = name + + +def _participant(item: Any) -> Executor: + if isinstance(item, Executor): + return item + if isinstance(item, Agent): + return AgentExecutor(item) + raise TypeError(f"a participant is an Agent or an Executor, not {type(item).__name__}") + + +def _unique(executors: Sequence[Executor], reserved: Sequence[str]) -> None: + ids = [e.id for e in executors] + if len(ids) < 1: + raise WorkflowError("an orchestration needs at least one participant") + if len(set(ids)) != len(ids): + raise WorkflowError(f"participant names must be unique: {ids}") + clash = set(ids) & set(reserved) + if clash: + raise WorkflowError(f"participant names {sorted(clash)} are reserved by the orchestration") + + +class _Builder: + def __init__(self, name: str, governance: Any, checkpoint_storage: Optional[CheckpointStorage], + max_supersteps: int) -> None: + self.name = name + self.governance = resolve_governance(governance) + self.checkpoint_storage = checkpoint_storage + self.max_supersteps = max_supersteps + + def _builder(self, start: Executor) -> WorkflowBuilder: + return WorkflowBuilder(name=self.name, start_executor=start, max_supersteps=self.max_supersteps, + checkpoint_storage=self.checkpoint_storage, governance=self.governance) + + +# ── sequential ────────────────────────────────────────────────────────────────────────────── + +class SequentialBuilder(_Builder): + """Each participant gets the conversation so far and adds its reply; the output is the full + conversation (``List[Message]``). An ``Executor`` participant receives an ``AgentResult`` (or + the input conversation, if first) and must send an ``AgentResult`` or a message list on.""" + + def __init__(self, participants: Sequence[Any], *, name: str = "sequential", governance: Any = None, + checkpoint_storage: Optional[CheckpointStorage] = None, + max_supersteps: int = DEFAULT_MAX_SUPERSTEPS) -> None: + super().__init__(name, governance, checkpoint_storage, max_supersteps) + self.participants = [_participant(p) for p in participants] + _unique(self.participants, ("input", "output")) + + def build(self) -> Workflow: + async def take_input(message: Any, ctx: WorkflowContext) -> None: + await ctx.send_message(conversation_of(message)) + + async def give_output(message: Any, ctx: WorkflowContext) -> None: + await ctx.yield_output(conversation_of(message)) + + start = FunctionExecutor(take_input, "input", input=ConversationInput) + end = FunctionExecutor(give_output, "output", input=Union[AgentResult, List[Message]]) + return self._builder(start).add_chain([start, *self.participants, end]).build() + + +# ── concurrent ────────────────────────────────────────────────────────────────────────────── + +Aggregator = Callable[[List[AgentResult]], Any] + + +def default_aggregate(results: List[AgentResult]) -> List[Message]: + """The input's user messages, then each participant's last assistant message, in participant + order.""" + if not results: + return [] + first = results[0].conversation[: len(results[0].conversation) - len(results[0].response.messages)] + out = [m for m in first if m.role == ROLE_USER] + for r in results: + replies = [m for m in r.response.messages if m.role == ROLE_ASSISTANT and m.text] + if replies: + out.append(replies[-1]) + return out + + +class ConcurrentBuilder(_Builder): + """Every participant gets the same input at once; when all have answered, ``aggregator`` + (code, sync or async) combines their ``AgentResult``s, in participant order, into the output.""" + + def __init__(self, participants: Sequence[Any], *, aggregator: Optional[Aggregator] = None, + name: str = "concurrent", governance: Any = None, + checkpoint_storage: Optional[CheckpointStorage] = None, + max_supersteps: int = DEFAULT_MAX_SUPERSTEPS) -> None: + super().__init__(name, governance, checkpoint_storage, max_supersteps) + self.participants = [_participant(p) for p in participants] + _unique(self.participants, ("dispatch", "aggregate")) + if len(self.participants) < 2: + raise WorkflowError("a concurrent orchestration needs at least two participants") + self.aggregator = aggregator or default_aggregate + + def build(self) -> Workflow: + aggregator = self.aggregator + + async def dispatch(message: Any, ctx: WorkflowContext) -> None: + await ctx.send_message(conversation_of(message)) + + async def aggregate(results: List[AgentResult], ctx: WorkflowContext) -> None: + value = aggregator(list(results)) + if hasattr(value, "__await__"): + value = await value + await ctx.yield_output(value) + + start = FunctionExecutor(dispatch, "dispatch", input=ConversationInput) + end = FunctionExecutor(aggregate, "aggregate", input=List[AgentResult]) + return (self._builder(start).add_fan_out_edges(start, self.participants) + .add_fan_in_edges(self.participants, end).build()) + + +# ── group chat ────────────────────────────────────────────────────────────────────────────── + +@dataclass +class GroupChatState: + conversation: List[Message] + round: int + participants: List[str] + last_speaker: Optional[str] + + +Selector = Callable[[GroupChatState], Optional[str]] + + +class _GroupChatManager(Executor): + state_fields = ("conversation", "round", "last_speaker") + + def __init__(self, participants: List[str], selector: Selector, max_rounds: int, + termination: Optional[Callable[[GroupChatState], bool]]) -> None: + super().__init__("group_chat_manager") + self.participants = participants + self.selector = selector + self.max_rounds = max_rounds + self.termination = termination + self.conversation: List[Message] = [] + self.round = 0 + self.last_speaker: Optional[str] = None + + @handler(input=ConversationInput) + async def start(self, message: Any, ctx: WorkflowContext) -> None: + self.conversation = conversation_of(message) + await self._next(ctx) + + @handler(input=AgentResult) + async def heard(self, result: AgentResult, ctx: WorkflowContext) -> None: + self.conversation.extend(result.response.messages) + await self._next(ctx) + + async def _finish(self, ctx: WorkflowContext, reason: str) -> None: + await ctx.add_event("group_chat_finished", {"reason": reason, "rounds": self.round}) + await ctx.yield_output(list(self.conversation)) + + async def _next(self, ctx: WorkflowContext) -> None: + state = GroupChatState(list(self.conversation), self.round, list(self.participants), self.last_speaker) + if self.round >= self.max_rounds: + return await self._finish(ctx, f"max_rounds ({self.max_rounds}) reached") + if self.termination is not None and self.termination(state): + return await self._finish(ctx, "termination condition met") + speaker = self.selector(state) + if speaker is None: + return await self._finish(ctx, "selector ended the chat") + if speaker not in self.participants: + raise WorkflowError(f"the group-chat selector chose {speaker!r}, who is not in the group {self.participants}") + self.round += 1 + self.last_speaker = speaker + await ctx.add_event("speaker_selected", {"speaker": speaker, "round": self.round}) + await ctx.send_message(list(self.conversation), target_id=speaker) + + +def round_robin(state: GroupChatState) -> str: + """A selector: participants in order, repeating.""" + return state.participants[state.round % len(state.participants)] + + +class GroupChatBuilder(_Builder): + """Agents take turns on one shared conversation. ``selector(state)`` (code) names the next + speaker or returns None to end; ``termination(state)`` may also end it; ``max_rounds`` caps it. + The output is the conversation.""" + + def __init__(self, participants: Sequence[Any], *, selector: Selector = round_robin, max_rounds: int = 10, + termination: Optional[Callable[[GroupChatState], bool]] = None, name: str = "group_chat", + governance: Any = None, checkpoint_storage: Optional[CheckpointStorage] = None, + max_supersteps: int = DEFAULT_MAX_SUPERSTEPS) -> None: + super().__init__(name, governance, checkpoint_storage, max_supersteps) + if not isinstance(max_rounds, int) or max_rounds < 1: + raise ValueError("max_rounds must be a positive integer") + self.participants = [_participant(p) for p in participants] + _unique(self.participants, ("group_chat_manager",)) + self.selector, self.max_rounds, self.termination = selector, max_rounds, termination + + def build(self) -> Workflow: + manager = _GroupChatManager([p.id for p in self.participants], self.selector, self.max_rounds, + self.termination) + b = self._builder(manager) + for p in self.participants: + b.add_edge(manager, p).add_edge(p, manager) + return b.build() + + +# ── handoff ───────────────────────────────────────────────────────────────────────────────── + +HANDOFF_PREFIX = "handoff_to_" + + +@register_checkpoint_type +@dataclass +class HandoffTurn: + conversation: List[Message] + handoffs: int = 0 + + +@register_checkpoint_type +@dataclass +class HandoffUserInputRequest: + """Asked when ``interactive`` and an agent answered without handing off.""" + + agent: str + conversation: List[Message] + + +def _strip_handoffs(messages: List[Message]) -> List[Message]: + out = [] + for m in messages: + kept = [c for c in m.contents + if not (c.type in (CONTENT_FUNCTION_CALL, CONTENT_FUNCTION_RESULT) and c.name.startswith(HANDOFF_PREFIX))] + if kept: + out.append(Message(m.role, kept, author_name=m.author_name, message_id=m.message_id, + additional_properties=dict(m.additional_properties))) + return out + + +class _HandoffStop(FunctionMiddleware): + """After a handoff tool has passed the tool policy and run, end the agent's turn.""" + + def __init__(self, owner: "_HandoffParticipant") -> None: + self.owner = owner + + async def process(self, context: FunctionInvocationContext, call_next: Any) -> None: + await call_next() + name = context.function.name + if name.startswith(HANDOFF_PREFIX) and not isinstance(context.result, PolicyRefusal): + self.owner.requested.append(name[len(HANDOFF_PREFIX):]) + raise MiddlewareTermination(f"handoff requested: {name}", result=context.result) + + +def _handoff_tool(target: str) -> FunctionTool: + def handoff(reason: str = "") -> str: + return f"Handoff to {target} requested." + return FunctionTool(handoff, name=f"{HANDOFF_PREFIX}{target}", + description=f"Hand the conversation to {target}. Use only when {target} should take over.") + + +class _HandoffParticipant(Executor): + def __init__(self, agent: Agent, allowed: List[str], max_handoffs: int, interactive: bool) -> None: + self.allowed = allowed + self.max_handoffs = max_handoffs + self.interactive = interactive + self.requested: List[str] = [] # filled by _HandoffStop during one turn + self.agent = agent.clone(extra_tools=[_handoff_tool(t) for t in allowed], extra_middleware=[_HandoffStop(self)]) + super().__init__(agent.name) + + async def _turn(self, turn: HandoffTurn, ctx: WorkflowContext) -> None: + self.requested = [] + response = await self.agent.run(turn.conversation) + _label(response.messages, self.id) + conversation = list(turn.conversation) + _strip_handoffs(list(response.messages)) + if self.requested: + target = self.requested[-1] + if target not in self.allowed: # tools are only given for allowed targets; checked again + raise WorkflowError(f"{self.id!r} asked to hand off to {target!r}, which routes do not allow") + if turn.handoffs >= self.max_handoffs: + await ctx.add_event("handoff_refused", {"from": self.id, "to": target, + "reason": f"max_handoffs ({self.max_handoffs}) reached"}) + await ctx.yield_output(conversation) + return + await ctx.add_event("handoff", {"from": self.id, "to": target, "handoffs": turn.handoffs + 1}) + await ctx.send_message(HandoffTurn(conversation, turn.handoffs + 1), target_id=target) + return + if self.interactive: + await ctx.request_info(HandoffUserInputRequest(self.id, conversation), str) + return + await ctx.yield_output(conversation) + + @handler(input=HandoffTurn) + async def on_turn(self, turn: HandoffTurn, ctx: WorkflowContext) -> None: + await self._turn(turn, ctx) + + @response_handler + async def on_user_input(self, request: HandoffUserInputRequest, reply: str, ctx: WorkflowContext) -> None: + conversation = list(request.conversation) + [Message.user(reply)] + await self._turn(HandoffTurn(conversation, 0), ctx) + + +class HandoffBuilder(_Builder): + """Agents pass the conversation to each other. ``routes`` maps an agent's name to the names it + may hand off to; only those get a ``handoff_to_`` tool. The run starts at ``start`` and + ends when an agent answers without handing off (or, with ``interactive=True``, asks the caller + for the next user message through ``request_info``). Output: the conversation.""" + + def __init__(self, participants: Sequence[Agent], *, start: str, routes: Mapping[str, Sequence[str]], + max_handoffs: int = 8, interactive: bool = False, name: str = "handoff", governance: Any = None, + checkpoint_storage: Optional[CheckpointStorage] = None, + max_supersteps: int = DEFAULT_MAX_SUPERSTEPS) -> None: + super().__init__(name, governance, checkpoint_storage, max_supersteps) + agents = list(participants) + if not all(isinstance(a, Agent) for a in agents): + raise TypeError("handoff participants must be Agents") + names = [a.name for a in agents] + bad = [n for n in names if not _NAME_RE.match(n)] + if bad: + raise WorkflowError(f"handoff agent names must match {_NAME_RE.pattern}: {bad}") + if len(set(names)) != len(names) or "input" in names: + raise WorkflowError(f"handoff agent names must be unique and not 'input': {names}") + if start not in names: + raise WorkflowError(f"start agent {start!r} is not a participant") + for src, targets in routes.items(): + if src not in names: + raise WorkflowError(f"routes name an unknown agent {src!r}") + for t in targets: + if t not in names or t == src: + raise WorkflowError(f"route {src!r} -> {t!r} is not to another participant") + if not isinstance(max_handoffs, int) or max_handoffs < 0: + raise ValueError("max_handoffs must be a non-negative integer") + self.agents, self.start, self.max_handoffs, self.interactive = agents, start, max_handoffs, interactive + self.routes = {n: list(dict.fromkeys(routes.get(n, ()))) for n in names} + + def build(self) -> Workflow: + parts = {a.name: _HandoffParticipant(a, self.routes[a.name], self.max_handoffs, self.interactive) + for a in self.agents} + + async def take_input(message: Any, ctx: WorkflowContext) -> None: + await ctx.send_message(HandoffTurn(conversation_of(message), 0)) + + start = FunctionExecutor(take_input, "input", input=ConversationInput) + b = self._builder(start).add_edge(start, parts[self.start]) + for src, targets in self.routes.items(): + for t in targets: + b.add_edge(parts[src], parts[t]) + for p in parts.values(): + b.add_executor(p) + return b.build() + + +# ── Magentic ──────────────────────────────────────────────────────────────────────────────── + +_PLAN = ("You coordinate a team on a task. The team: {team}.\n\nTask:\n{task}\n\n" + "Write (1) the facts given in the task, (2) facts to look up, (3) a short step-by-step plan that names " + "which team member does each step. This is a plan, not a result.") +_REPLAN = ("The team stalled. Task:\n{task}\n\nPrevious plan:\n{plan}\n\nConversation so far:\n{transcript}\n\n" + "Write a revised plan that avoids what went wrong.") +_PROGRESS = ("Task:\n{task}\n\nPlan:\n{plan}\n\nTeam: {team}\n\nConversation so far:\n{transcript}\n\n" + "Answer with one JSON object and nothing else:\n" + '{{"is_request_satisfied": {{"answer": true|false, "reason": "..."}}, ' + '"is_in_loop": {{"answer": true|false, "reason": "..."}}, ' + '"is_progress_being_made": {{"answer": true|false, "reason": "..."}}, ' + '"next_speaker": {{"answer": "", "reason": "..."}}, ' + '"instruction_or_question": {{"answer": "...", "reason": "..."}}}}') +_FINAL = ("Task:\n{task}\n\nConversation:\n{transcript}\n\nWrite the final answer to the task from what the team " + "produced. Do not claim anything was executed, tested or measured unless the conversation shows it.") + + +@register_checkpoint_type +@dataclass +class MagenticResult: + """``status``: completed, round_limit or stalled. ``answer`` is empty unless completed.""" + + status: str + answer: str + rounds: int + stalls: int + resets: int + conversation: List[Message] = field(default_factory=list) + + @property + def text(self) -> str: + return self.answer + + +_LEDGER_KEYS = {"is_request_satisfied": bool, "is_in_loop": bool, "is_progress_being_made": bool, + "next_speaker": str, "instruction_or_question": str} + + +def parse_progress_ledger(text: str) -> Optional[Dict[str, Any]]: + """The manager's progress ledger as ``{key: answer}``, or None if it is not exactly the + expected JSON shape (the first ``{`` to the last ``}`` must parse; every key present with an + ``answer`` of the right type).""" + start, end = text.find("{"), text.rfind("}") + if start < 0 or end <= start: + return None + try: + data = json.loads(text[start:end + 1]) + except ValueError: + return None + if not isinstance(data, dict): + return None + out: Dict[str, Any] = {} + for key, kind in _LEDGER_KEYS.items(): + item = data.get(key) + if not isinstance(item, dict) or "answer" not in item: + return None + answer = item["answer"] + if kind is bool and answer is not True and answer is not False: + return None + if kind is str and not isinstance(answer, str): + return None + out[key] = answer + return out + + +class _MagenticManager(Executor): + state_fields = ("task", "plan", "conversation", "rounds", "stalls", "resets") + + def __init__(self, manager: Agent, team: List[str], max_rounds: int, max_stalls: int, max_resets: int) -> None: + super().__init__("magentic_manager") + self.manager = manager + self.team = team + self.max_rounds, self.max_stalls, self.max_resets = max_rounds, max_stalls, max_resets + self.task, self.plan = "", "" + self.conversation: List[Message] = [] + self.rounds = self.stalls = self.resets = 0 + + def _transcript(self) -> str: + return "\n\n".join(f"[{m.author_name or m.role}] {m.text}" for m in self.conversation if m.text)[-12000:] + + async def _ask(self, prompt: str) -> str: + response = await self.manager.run(prompt) + if response.status != "SUCCESS": + raise WorkflowError(f"the Magentic manager's run ended {response.status}") + return response.text + + @handler(input=ConversationInput) + async def start(self, message: Any, ctx: WorkflowContext) -> None: + self.conversation = conversation_of(message) + self.task = "\n".join(m.text for m in self.conversation if m.role == ROLE_USER and m.text) + self.plan = await self._ask(_PLAN.format(team=", ".join(self.team), task=self.task)) + await ctx.add_event("magentic_plan", {"plan_chars": len(self.plan)}) + await self._next(ctx) + + @handler(input=AgentResult) + async def heard(self, result: AgentResult, ctx: WorkflowContext) -> None: + self.conversation.extend(result.response.messages) + await self._next(ctx) + + async def _stop(self, ctx: WorkflowContext, status: str, answer: str = "") -> None: + await ctx.add_event("magentic_finished", {"status": status, "rounds": self.rounds, "stalls": self.stalls, + "resets": self.resets}) + await ctx.yield_output(MagenticResult(status, answer, self.rounds, self.stalls, self.resets, + list(self.conversation))) + + async def _next(self, ctx: WorkflowContext) -> None: + while True: + if self.rounds >= self.max_rounds: + return await self._stop(ctx, "round_limit") + text = await self._ask(_PROGRESS.format(task=self.task, plan=self.plan, team=", ".join(self.team), + transcript=self._transcript())) + ledger = parse_progress_ledger(text) + problem = "" + if ledger is None: + problem = "the progress ledger was not the expected JSON" + elif ledger["is_request_satisfied"]: + answer = await self._ask(_FINAL.format(task=self.task, transcript=self._transcript())) + return await self._stop(ctx, "completed", answer) + elif ledger["next_speaker"] not in self.team: + problem = f"next_speaker {ledger['next_speaker']!r} is not in the team" + elif not ledger["instruction_or_question"].strip(): + problem = "the instruction was empty" + if problem or ledger is None or ledger["is_in_loop"] or not ledger["is_progress_being_made"]: + self.stalls += 1 + await ctx.add_event("magentic_stall", {"stalls": self.stalls, "problem": problem}) + else: + self.stalls = max(0, self.stalls - 1) + if self.stalls > self.max_stalls: + if self.resets >= self.max_resets: + return await self._stop(ctx, "stalled") + self.resets += 1 + self.stalls = 0 + self.plan = await self._ask(_REPLAN.format(task=self.task, plan=self.plan, + transcript=self._transcript())) + await ctx.add_event("magentic_replan", {"resets": self.resets}) + continue + if problem: + continue + assert ledger is not None + speaker, instruction = ledger["next_speaker"], ledger["instruction_or_question"] + self.rounds += 1 + note = Message(ROLE_USER, [Content.from_text(instruction)], author_name="magentic_manager") + self.conversation.append(note) + await ctx.add_event("speaker_selected", {"speaker": speaker, "round": self.rounds}) + await ctx.send_message(list(self.conversation), target_id=speaker) + return + + +class MagenticBuilder(_Builder): + """A manager model plans and, each round, proposes who acts next and what they should do; + code checks every proposal (see the module notes). Output: a ``MagenticResult``.""" + + def __init__(self, participants: Sequence[Any], *, manager: Agent, max_rounds: int = 10, max_stalls: int = 3, + max_resets: int = 2, name: str = "magentic", governance: Any = None, + checkpoint_storage: Optional[CheckpointStorage] = None, + max_supersteps: int = DEFAULT_MAX_SUPERSTEPS) -> None: + super().__init__(name, governance, checkpoint_storage, max_supersteps) + if not isinstance(manager, Agent): + raise TypeError("the Magentic manager is an Agent") + for label, value, low in (("max_rounds", max_rounds, 1), ("max_stalls", max_stalls, 0), + ("max_resets", max_resets, 0)): + if not isinstance(value, int) or value < low: + raise ValueError(f"{label} must be an integer >= {low}") + self.participants = [_participant(p) for p in participants] + _unique(self.participants, ("magentic_manager",)) + self.manager, self.limits = manager, (max_rounds, max_stalls, max_resets) + + def build(self) -> Workflow: + mgr = _MagenticManager(self.manager, [p.id for p in self.participants], *self.limits) + b = self._builder(mgr) + for p in self.participants: + b.add_edge(mgr, p).add_edge(p, mgr) + return b.build() diff --git a/osiris_cli/runtime/_workflows.py b/osiris_cli/runtime/_workflows.py new file mode 100644 index 00000000..9a996bd5 --- /dev/null +++ b/osiris_cli/runtime/_workflows.py @@ -0,0 +1,1098 @@ +# Portions adapted from microsoft/agent-framework@567e4d458b59b83ac9b19088a43a2853094c6df1 +# python/packages/core/agent_framework/_workflows/: _executor.py (executors with typed handlers), +# _function_executor.py, _workflow_context.py (send_message / yield_output / request_info / +# shared state), _edge.py and _edge_runner.py (direct, conditional, fan-out, fan-in and +# switch-case edge groups), _workflow_builder.py (builder API and validation), _runner.py (Pregel +# supersteps, state committed at superstep boundaries, a checkpoint after each superstep), +# _workflow.py (run / streaming / responses / checkpoint restore), _events.py (run states). +# MIT License, Copyright (c) Microsoft Corporation. See THIRD_PARTY_NOTICES.md and PORT_MAP.md. +"""Workflows: executors joined by edges, run in supersteps. + +An executor receives a message, does its work, and may send messages along its outgoing edges, +yield outputs, or ask for outside input (``request_info``). Messages sent in one superstep are +delivered in the next. A run ends when no message is pending: ``COMPLETED``, or +``IDLE_WITH_PENDING_REQUESTS`` when an executor is waiting for a response. Running again with +``responses`` (or from a checkpoint) continues it. + +Deliberate differences from the source: + +* Determinism. Executors with messages in a superstep run concurrently, but what they send, + yield, write to shared state, and the events they raise are applied in executor registration + order at the end of the superstep, so a run's messages, outputs and events do not depend on + which coroutine finished first. Streaming is therefore per superstep, not per event. +* A superstep limit reached with messages still pending ends the run as ``STOPPED`` with the + messages kept (and checkpointed), instead of raising. +* An executor exception ends the run as ``FAILED`` and is re-raised unchanged, so callers can + catch the error types they already handle. +* Responses to ``request_info`` must have exactly the requested type (``True``/``False`` for + bool; a bool is not accepted where an int or float is asked for). +* Governance: a run given a ``GovernanceConfig`` (the orchestration builders give one by default) + opens and closes a ``workflow`` task in the canonical task ledger, applies the intent gate to the + input, charges one budget step per superstep, and runs text outputs through the evidence + firewall. Agents inside a workflow are always governed by their own stack. Hand-built + workflows of plain executors run without a task record unless given one. +* No build-time check that an edge's message types match the target's handlers; a message no + handler accepts fails the run when delivered. +""" + +from __future__ import annotations + +import asyncio +import collections.abc +import concurrent.futures +import copy +import hashlib +import inspect +import json +import typing +import uuid +from abc import ABC, abstractmethod +from dataclasses import dataclass, field +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Dict, + List, + Mapping, + Optional, + Sequence, + Tuple, + Union, +) + +from ._checkpoints import ( + CheckpointError, + CheckpointStorage, + WorkflowCheckpoint, + decode_response_type, + decode_value, + encode_response_type, + encode_value, + response_type_ok, +) +from ._telemetry import SpanRecorder, otel_tracer +from ._types import AgentResponse, Message, canonical_json + +COMPLETED = "COMPLETED" +IDLE_WITH_PENDING_REQUESTS = "IDLE_WITH_PENDING_REQUESTS" +STOPPED = "STOPPED" +FAILED = "FAILED" +CANCELLED = "CANCELLED" +BLOCKED = "BLOCKED" +RUN_STATES = (COMPLETED, IDLE_WITH_PENDING_REQUESTS, STOPPED, FAILED, CANCELLED, BLOCKED) + +DEFAULT_MAX_SUPERSTEPS = 100 +OP_INVOKE_WORKFLOW = "invoke_workflow" +OP_EXECUTOR = "executor_process" + +_LEDGER_STATUS = {COMPLETED: "SUCCESS", IDLE_WITH_PENDING_REQUESTS: "PENDING_INPUT", STOPPED: "STOPPED_LIMIT", + FAILED: "ERROR", CANCELLED: "CANCELLED", BLOCKED: "BLOCKED"} + + +class WorkflowError(RuntimeError): + """The workflow is malformed, or a run did something its graph does not allow.""" + + +class WorkflowGovernanceError(WorkflowError): + """A governed run could not be recorded; it does not start.""" + + +# ── handlers and executors ────────────────────────────────────────────────────────────────── + +_HANDLER = "_osiris_workflow_handler" +_RESPONSE_HANDLER = "_osiris_workflow_response_handler" + + +def handler(func: Optional[Callable[..., Any]] = None, *, input: Any = None) -> Any: # noqa: A002 - mirrors the source's keyword + """Mark ``async def method(self, message: T, ctx: WorkflowContext)`` as a message handler. + The message type comes from the annotation, or from ``input=`` when the annotation cannot be + resolved (for example a class defined inside a function).""" + def mark(f: Callable[..., Any]) -> Callable[..., Any]: + if not inspect.iscoroutinefunction(f): + raise TypeError(f"handler {f.__qualname__} must be an async function") + setattr(f, _HANDLER, {"input": input}) + return f + return mark(func) if func is not None else mark + + +def response_handler(func: Callable[..., Any]) -> Callable[..., Any]: + """Mark ``async def method(self, request, response, ctx)``: receives the responses to this + executor's ``request_info`` calls.""" + if not inspect.iscoroutinefunction(func): + raise TypeError(f"response handler {func.__qualname__} must be an async function") + setattr(func, _RESPONSE_HANDLER, True) + return func + + +def _accepts(tp: Any, value: Any) -> bool: + if tp is Any or tp is object: + return True + origin = typing.get_origin(tp) + args = typing.get_args(tp) + if origin is Union: + return any(_accepts(a, value) for a in args) + if origin in (list, collections.abc.Sequence): + if not isinstance(value, list): + return False + return not args or all(_accepts(args[0], v) for v in value) + if origin in (dict, collections.abc.Mapping): + return isinstance(value, dict) + if origin is tuple: + return isinstance(value, tuple) + if isinstance(origin, type): + return isinstance(value, origin) + if isinstance(tp, type): + return isinstance(value, tp) + return False + + +def _type_label(tp: Any) -> str: + return getattr(tp, "__qualname__", None) or str(tp).replace("typing.", "") + + +class Executor: + """A unit of work in a workflow. Subclass it and mark methods with ``@handler``. + + List per-run attributes in ``state_fields``: they are saved in checkpoints, restored on resume, + and put back to their first values when a new run starts. Override ``snapshot_state`` / + ``restore_state`` / ``reset`` only for state that does not fit that pattern.""" + + state_fields: Tuple[str, ...] = () + + def __init__(self, id: str) -> None: # noqa: A002 - mirrors the source's parameter name + if not isinstance(id, str) or not id.strip(): + raise ValueError("executor id must be a non-empty string") + self.id = id + self._handlers: List[Tuple[Any, Callable[..., Awaitable[Any]]]] = [] + self._response: Optional[Callable[..., Awaitable[Any]]] = None + self._state_defaults: Optional[Dict[str, Any]] = None + found: Dict[str, Any] = {} + for klass in reversed(type(self).__mro__): + for name, attr in vars(klass).items(): + if getattr(attr, _HANDLER, None) is not None or getattr(attr, _RESPONSE_HANDLER, False): + found[name] = attr + elif name in found: + del found[name] # overridden by a plain method + for name, attr in found.items(): + meta = getattr(attr, _HANDLER, None) + if meta is not None: + tp = meta["input"] if meta["input"] is not None else self._hint(attr) + self._handlers.append((tp, getattr(self, name))) + else: + if self._response is not None: + raise WorkflowError(f"executor {id!r} has more than one response handler") + self._response = getattr(self, name) + + @staticmethod + def _hint(func: Callable[..., Any]) -> Any: + params = [p for p in inspect.signature(func).parameters.values() if p.name != "self"] + if len(params) != 2: + raise TypeError(f"handler {func.__qualname__} must take (self, message, ctx)") + try: + hints = typing.get_type_hints(func) + except Exception as exc: + raise TypeError(f"cannot resolve the message type of {func.__qualname__} ({exc}); " + "pass it explicitly: @handler(input=...)") from None + return hints.get(params[0].name, Any) + + @property + def input_types(self) -> List[str]: + return [_type_label(tp) for tp, _ in self._handlers] + + def handler_for(self, message: Any) -> Optional[Callable[..., Awaitable[Any]]]: + for tp, fn in self._handlers: + if _accepts(tp, message): + return fn + return None + + def reset(self) -> None: + """Called before a new run (not a resumed one): each ``state_fields`` attribute goes back + to the value it had the first time a run started.""" + for name, value in self._defaults().items(): + setattr(self, name, copy.deepcopy(value)) + + def _defaults(self) -> Dict[str, Any]: + """The ``state_fields`` values before the first run or restore changed them.""" + if self._state_defaults is None: + self._state_defaults = {n: copy.deepcopy(getattr(self, n)) for n in self.state_fields} + return self._state_defaults + + def snapshot_state(self) -> Any: + return {n: getattr(self, n) for n in self.state_fields} + + def restore_state(self, state: Any) -> None: + """Rebuild per-run state from ``snapshot_state``'s value.""" + self._defaults() + unknown = set(state or {}) - set(self.state_fields) + if unknown: + raise WorkflowError(f"checkpoint state for {self.id!r} names unknown fields {sorted(unknown)}") + for name, value in (state or {}).items(): + setattr(self, name, value) + + def __repr__(self) -> str: + return f"{type(self).__name__}({self.id!r})" + + +class FunctionExecutor(Executor): + """An executor made from one function ``(message, ctx)``, sync or async.""" + + def __init__(self, func: Callable[..., Any], id: Optional[str] = None, *, input: Any = None) -> None: # noqa: A002 + self._func = func + tp = input if input is not None else self._hint_fn(func) + super().__init__(id or func.__name__) + self._handlers = [(tp, self._call)] + + @staticmethod + def _hint_fn(func: Callable[..., Any]) -> Any: + params = list(inspect.signature(func).parameters.values()) + if len(params) != 2: + raise TypeError(f"{getattr(func, '__qualname__', func)} must take (message, ctx)") + try: + hints = typing.get_type_hints(func) + except Exception as exc: + raise TypeError(f"cannot resolve the message type of {func.__qualname__} ({exc}); " + "pass it explicitly: executor(input=...)") from None + return hints.get(params[0].name, Any) + + async def _call(self, message: Any, ctx: "WorkflowContext") -> None: + result = self._func(message, ctx) + if inspect.isawaitable(result): + await result + + +def executor(func: Optional[Callable[..., Any]] = None, *, id: Optional[str] = None, input: Any = None) -> Any: # noqa: A002 + """Decorator form of ``FunctionExecutor``.""" + def wrap(f: Callable[..., Any]) -> FunctionExecutor: + return FunctionExecutor(f, id, input=input) + return wrap(func) if func is not None else wrap + + +# ── events, requests, results ─────────────────────────────────────────────────────────────── + +@dataclass +class WorkflowEvent: + """``type`` is one of: started, superstep_started, executor_invoked, executor_completed, + executor_failed, output, request_info, custom, checkpoint, superstep_completed, status, failed.""" + + type: str + data: Any = None + executor_id: Optional[str] = None + superstep: int = 0 + + +@dataclass +class RequestInfo: + request_id: str + executor_id: str + data: Any + response_type: type + + +@dataclass +class WorkflowRunResult: + run_id: str + status: str + outputs: List[Any] = field(default_factory=list) + events: List[WorkflowEvent] = field(default_factory=list) + pending_requests: List[RequestInfo] = field(default_factory=list) + checkpoint_id: Optional[str] = None + reason: str = "" + governance: Dict[str, Any] = field(default_factory=dict) + telemetry: List[Dict[str, Any]] = field(default_factory=list) + + def get_outputs(self) -> List[Any]: + return list(self.outputs) + + def get_request_info_events(self) -> List[WorkflowEvent]: + return [e for e in self.events if e.type == "request_info"] + + +@dataclass +class _Envelope: + source: str + target: str + payload: Any + + +# ── edges ─────────────────────────────────────────────────────────────────────────────────── + +def _fn_name(fn: Optional[Callable[..., Any]]) -> Optional[str]: + if fn is None: + return None + return f"{getattr(fn, '__module__', '?')}.{getattr(fn, '__qualname__', type(fn).__name__)}" + + +@dataclass +class Case: + """A switch-case branch: the first case whose ``condition(message)`` is true receives it.""" + + condition: Callable[[Any], bool] + target: Any + + +@dataclass +class Default: + """The switch-case branch taken when no case matched.""" + + target: Any + + +class _Edge(ABC): + sources: Tuple[str, ...] = () + targets: Tuple[str, ...] = () + + @abstractmethod + def describe(self) -> Dict[str, Any]: + """The edge as data, for the graph signature.""" + + +@dataclass +class _Direct(_Edge): + source: str + target: str + condition: Optional[Callable[[Any], bool]] = None + + def __post_init__(self) -> None: + self.sources, self.targets = (self.source,), (self.target,) + + def route(self, message: Any) -> List[str]: + return [self.target] if self.condition is None or self.condition(message) else [] + + def describe(self) -> Dict[str, Any]: + return {"kind": "direct", "source": self.source, "target": self.target, "condition": _fn_name(self.condition)} + + +@dataclass +class _FanOut(_Edge): + source: str + fan_targets: Tuple[str, ...] + selection: Optional[Callable[[Any, List[str]], Sequence[str]]] = None + + def __post_init__(self) -> None: + self.sources, self.targets = (self.source,), tuple(self.fan_targets) + + def route(self, message: Any) -> List[str]: + if self.selection is None: + return list(self.fan_targets) + chosen = list(self.selection(message, list(self.fan_targets))) + unknown = [t for t in chosen if t not in self.fan_targets] + if unknown: + raise WorkflowError(f"fan-out selection from {self.source!r} chose targets outside the group: {unknown}") + return [t for t in self.fan_targets if t in chosen] + + def describe(self) -> Dict[str, Any]: + return {"kind": "fan_out", "source": self.source, "targets": list(self.fan_targets), + "selection": _fn_name(self.selection)} + + +@dataclass +class _Switch(_Edge): + source: str + cases: List[Tuple[Optional[Callable[[Any], bool]], str]] + + def __post_init__(self) -> None: + self.sources, self.targets = (self.source,), tuple(t for _, t in self.cases) + + def route(self, message: Any) -> List[str]: + for condition, target in self.cases: + if condition is None or condition(message): + return [target] + return [] + + def describe(self) -> Dict[str, Any]: + return {"kind": "switch", "source": self.source, + "cases": [{"condition": _fn_name(c) if c else "default", "target": t} for c, t in self.cases]} + + +@dataclass +class _FanIn(_Edge): + fan_sources: Tuple[str, ...] + target: str + + def __post_init__(self) -> None: + self.sources, self.targets = tuple(self.fan_sources), (self.target,) + + def describe(self) -> Dict[str, Any]: + return {"kind": "fan_in", "sources": list(self.fan_sources), "target": self.target} + + +# ── builder ───────────────────────────────────────────────────────────────────────────────── + +ExecutorLike = Any # an Executor, or an Agent (wrapped in an AgentExecutor) + + +class WorkflowBuilder: + """Assemble a workflow. Executors may be given as ``Executor`` instances or as ``Agent``s + (wrapped in an ``AgentExecutor`` named after the agent).""" + + def __init__(self, *, name: str = "workflow", start_executor: Optional[ExecutorLike] = None, + max_supersteps: int = DEFAULT_MAX_SUPERSTEPS, + checkpoint_storage: Optional[CheckpointStorage] = None, + governance: Any = None) -> None: + if not isinstance(max_supersteps, int) or max_supersteps < 1: + raise ValueError("max_supersteps must be a positive integer") + self.name = name + self._executors: Dict[str, Executor] = {} + self._edges: List[_Edge] = [] + self._start: Optional[str] = None + self._max_supersteps = max_supersteps + self._checkpoint_storage = checkpoint_storage + self._governance = governance + self._wrapped: Dict[int, Executor] = {} + if start_executor is not None: + self.set_start_executor(start_executor) + + def _add(self, item: ExecutorLike) -> str: + ex = self._as_executor(item) + known = self._executors.get(ex.id) + if known is not None and known is not ex: + raise WorkflowError(f"two different executors share the id {ex.id!r}") + self._executors[ex.id] = ex + return ex.id + + def _as_executor(self, item: ExecutorLike) -> Executor: + if isinstance(item, Executor): + return item + from ._agents import Agent + if isinstance(item, Agent): + wrapped = self._wrapped.get(id(item)) + if wrapped is None: + from ._orchestrations import AgentExecutor + wrapped = AgentExecutor(item) + self._wrapped[id(item)] = wrapped + return wrapped + raise TypeError(f"expected an Executor or an Agent, got {type(item).__name__}") + + def set_start_executor(self, item: ExecutorLike) -> "WorkflowBuilder": + self._start = self._add(item) + return self + + def add_executor(self, item: ExecutorLike) -> "WorkflowBuilder": + self._add(item) + return self + + def add_edge(self, source: ExecutorLike, target: ExecutorLike, + condition: Optional[Callable[[Any], bool]] = None) -> "WorkflowBuilder": + self._edges.append(_Direct(self._add(source), self._add(target), condition)) + return self + + def add_fan_out_edges(self, source: ExecutorLike, targets: Sequence[ExecutorLike], + selection_func: Optional[Callable[[Any, List[str]], Sequence[str]]] = None) -> "WorkflowBuilder": + ids = tuple(self._add(t) for t in targets) + if len(ids) < 2 or len(set(ids)) != len(ids): + raise WorkflowError("a fan-out needs at least two distinct targets") + self._edges.append(_FanOut(self._add(source), ids, selection_func)) + return self + + def add_fan_in_edges(self, sources: Sequence[ExecutorLike], target: ExecutorLike) -> "WorkflowBuilder": + ids = tuple(self._add(s) for s in sources) + if len(ids) < 2 or len(set(ids)) != len(ids): + raise WorkflowError("a fan-in needs at least two distinct sources") + self._edges.append(_FanIn(ids, self._add(target))) + return self + + def add_switch_case_edge_group(self, source: ExecutorLike, cases: Sequence[Union[Case, Default]]) -> "WorkflowBuilder": + built: List[Tuple[Optional[Callable[[Any], bool]], str]] = [] + defaults = 0 + for case in cases: + if isinstance(case, Default): + defaults += 1 + built.append((None, self._add(case.target))) + elif isinstance(case, Case): + if defaults: + raise WorkflowError("the Default case must come last") + built.append((case.condition, self._add(case.target))) + else: + raise TypeError("cases must be Case or Default") + if defaults > 1 or not built: + raise WorkflowError("a switch needs at least one case and at most one Default") + self._edges.append(_Switch(self._add(source), built)) + return self + + def add_chain(self, items: Sequence[ExecutorLike]) -> "WorkflowBuilder": + ids = [self._add(i) for i in items] + for a, b in zip(ids, ids[1:]): + self._edges.append(_Direct(a, b)) + return self + + def build(self) -> "Workflow": + if self._start is None: + raise WorkflowError("no start executor: call set_start_executor()") + for ex in self._executors.values(): + if not ex._handlers and not (ex.id == self._start and ex._response): + raise WorkflowError(f"executor {ex.id!r} has no message handler") + reach = {self._start} + changed = True + while changed: + changed = False + for edge in self._edges: + if set(edge.sources) & reach and not set(edge.targets) <= reach: + if isinstance(edge, _FanIn) and not set(edge.sources) <= reach: + continue + reach |= set(edge.targets) + changed = True + unreachable = sorted(set(self._executors) - reach) + if unreachable: + raise WorkflowError(f"executors not reachable from the start executor: {unreachable}") + fan_in_targets = [e.target for e in self._edges if isinstance(e, _FanIn)] + if len(set(fan_in_targets)) != len(fan_in_targets): + raise WorkflowError("an executor can be the target of only one fan-in group") + return Workflow(self.name, dict(self._executors), self._start, list(self._edges), + max_supersteps=self._max_supersteps, checkpoint_storage=self._checkpoint_storage, + governance=self._governance) + + +# ── the context an executor sees ──────────────────────────────────────────────────────────── + +class WorkflowContext: + """Given to a handler for one invocation. Sends, outputs, events and state writes are + collected and applied at the end of the superstep.""" + + def __init__(self, run: "_Run", executor_id: str, source_ids: List[str]) -> None: + self._run = run + self.executor_id = executor_id + self.source_executor_ids = source_ids + self.superstep = run.superstep + self.sent: List[Tuple[Any, Optional[str]]] = [] + self.outputs: List[Any] = [] + self.events: List[WorkflowEvent] = [] + self.requests: List[RequestInfo] = [] + self.state_writes: Dict[str, Any] = {} + + @property + def run_id(self) -> str: + return self._run.run_id + + async def send_message(self, message: Any, target_id: Optional[str] = None) -> None: + self.sent.append((message, target_id)) + + async def yield_output(self, output: Any) -> None: + self.outputs.append(output) + + async def add_event(self, name: str, data: Any = None) -> None: + self.events.append(WorkflowEvent("custom", {"name": name, "data": data}, self.executor_id, self.superstep)) + + async def request_info(self, request_data: Any, response_type: type, *, request_id: Optional[str] = None) -> str: + if not isinstance(response_type, type): + raise TypeError("response_type must be a type") + if self._run.workflow._executors[self.executor_id]._response is None: + raise WorkflowError(f"executor {self.executor_id!r} asked for input but has no @response_handler") + rid = request_id or uuid.uuid4().hex + self.requests.append(RequestInfo(rid, self.executor_id, request_data, response_type)) + return rid + + def has_outgoing_edges(self) -> bool: + return bool(self._run.workflow._outgoing.get(self.executor_id)) + + def get_state(self, key: str, default: Any = None) -> Any: + if key in self.state_writes: + return self.state_writes[key] + return self._run.state.get(key, default) + + def set_state(self, key: str, value: Any) -> None: + self.state_writes[key] = value + + +# ── governance of a run ───────────────────────────────────────────────────────────────────── + +def _input_text(value: Any) -> str: + if isinstance(value, str): + return value + if isinstance(value, Message): + return value.text + if isinstance(value, list) and value and all(isinstance(m, Message) for m in value): + return "\n".join(m.text for m in value if m.role == "user" and m.text) or "\n".join(m.text for m in value) + try: + return canonical_json(value)[:4000] + except (TypeError, ValueError): + return f"({type(value).__name__} input)" + + +def output_text(value: Any) -> Optional[str]: + """The text of an output the evidence firewall should read, if it has one.""" + if isinstance(value, str): + return value + if isinstance(value, (Message, AgentResponse)): + return value.text + if isinstance(value, list) and value and all(isinstance(m, Message) for m in value): + last = [m for m in value if m.role == "assistant" and m.text] + return last[-1].text if last else None + text = getattr(value, "text", None) + return text if isinstance(text, str) else None + + +class _Governor: + def __init__(self, config: Any, workflow_name: str) -> None: + from ._governance import GovernanceConfig, load_runtime_policy + if not isinstance(config, GovernanceConfig): + raise TypeError("governance must be a GovernanceConfig") + self.config = config + self.policy = load_runtime_policy(config.policy_path) + self.name = workflow_name + self.tctx: Any = None + self.meter: Any = None + self.ledger: Any = None + self.stop: Any = None + self.opened = False # True once task_open is in the ledger; only then is task_close written + self.record: Dict[str, Any] = {} + + async def open(self, text: str) -> Optional[str]: + """Record the run; return a refusal reason or None. Raises if it cannot be recorded.""" + from osiris_cli import task_context + + from ._governance import ApprovalRequest, ask_approval + perms = self.config.permissions() + try: + self.tctx = task_context.new_context(text or "(no input text)", kind="workflow", 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 WorkflowGovernanceError(f"BLOCKED (context_invalid): {exc}") from exc + self.ledger = task_context.TaskLedger(self.config.resolved_ledger_path()) + try: + self.ledger.open(self.tctx) + except task_context.TaskLedgerError as exc: + raise WorkflowGovernanceError(f"BLOCKED (ledger_unavailable): {exc}") from exc + self.opened = True + self.meter = self.tctx.meter() + self.record = {"run_id": self.tctx.run_id, "kind": "workflow", "risk_tier": self.tctx.risk_tier, + "risk_reasons": list(self.tctx.risk_reasons), "ledger": self.config.resolved_ledger_path()} + blocked = task_context.require(self.tctx, propose_writes=perms.propose_writes, run_commands=perms.run_commands) + if blocked is not None: + self.stop = blocked + return str(blocked) + tier = self.tctx.risk_tier + if tier in self.policy["blocked_risk_tiers"]: + return f"risk tier {tier} is blocked by the runtime policy" + if tier in self.policy["grant_required_risk_tiers"]: + granted = await ask_approval(self.config.approval_handler, ApprovalRequest( + "risk_tier", f"run workflow '{self.name}' at risk tier {tier}", + {"risk_reasons": list(self.tctx.risk_reasons), "cost_class": self.tctx.cost_class})) + self.record["grant"] = {"tier": tier, "granted": granted} + if not granted: + return f"risk tier {tier} needs a human grant and none was given" + return None + + def step(self) -> Optional[str]: + stop = self.meter.begin_step() + if stop is not None: + self.stop = stop + return str(stop) + return None + + def close(self, status: str, usage_extra: Dict[str, Any], detail: str) -> None: + from osiris_cli import task_context + usage = dict(self.meter.usage()) if self.meter is not None else {} + usage.update(usage_extra) + ledger_status = self.stop.status if (self.stop is not None and status in (STOPPED, BLOCKED)) \ + else _LEDGER_STATUS[status] + try: + self.ledger.close(self.tctx, ledger_status, stop=self.stop, usage=usage, detail=detail) + except task_context.TaskLedgerError as exc: + raise WorkflowGovernanceError(f"task_close could not be written: {exc}") from exc + self.record["status"] = ledger_status + + +# ── the workflow and its runs ─────────────────────────────────────────────────────────────── + +class Workflow: + """A built workflow. One run at a time per instance.""" + + def __init__(self, name: str, executors: Dict[str, Executor], start: str, edges: List[_Edge], *, + max_supersteps: int, checkpoint_storage: Optional[CheckpointStorage], governance: Any) -> None: + self.name = name + self._executors = executors + self._order = list(executors) + self.start_executor_id = start + self._edges = edges + self.max_supersteps = max_supersteps + self.checkpoint_storage = checkpoint_storage + self.governance = governance + self._outgoing: Dict[str, List[_Edge]] = {} + self._edge_index: Dict[int, int] = {id(e): i for i, e in enumerate(edges)} + for edge in edges: + for s in edge.sources: + self._outgoing.setdefault(s, []).append(edge) + self._running = False + self._suspended: Optional[Dict[str, Any]] = None + + @property + def executor_ids(self) -> List[str]: + return list(self._order) + + def get_executor(self, executor_id: str) -> Executor: + return self._executors[executor_id] + + def describe(self) -> Dict[str, Any]: + return {"name": self.name, "start": self.start_executor_id, + "executors": [{"id": i, "type": type(self._executors[i]).__qualname__} for i in self._order], + "edges": [e.describe() for e in self._edges]} + + @property + def graph_signature(self) -> str: + return hashlib.sha256(canonical_json(self.describe()).encode("utf-8")).hexdigest() + + async def run(self, message: Any = None, *, responses: Optional[Mapping[str, Any]] = None, + checkpoint_id: Optional[str] = None, checkpoint_storage: Optional[CheckpointStorage] = None, + governance: Any = None) -> WorkflowRunResult: + """Start a run with ``message``; or continue one: ``responses`` answers pending requests + (of the last run of this instance, or of the checkpoint), ``checkpoint_id`` restores a + checkpoint first. ``governance`` overrides the workflow's governance for this run.""" + run = self._prepare(message, responses, checkpoint_id, checkpoint_storage, governance) + return await run.execute(None) + + async def run_stream(self, message: Any = None, *, responses: Optional[Mapping[str, Any]] = None, + checkpoint_id: Optional[str] = None, checkpoint_storage: Optional[CheckpointStorage] = None, + governance: Any = None) -> AsyncIterator[WorkflowEvent]: + """Events as each superstep completes; the last event is ``status``.""" + run = self._prepare(message, responses, checkpoint_id, checkpoint_storage, governance) + queue: "asyncio.Queue[Optional[WorkflowEvent]]" = asyncio.Queue() + task = asyncio.ensure_future(run.execute(queue)) + try: + while True: + event = await queue.get() + if event is None: + break + yield event + await task + finally: + if not task.done(): + task.cancel() + + def run_sync(self, message: Any = None, **kwargs: Any) -> WorkflowRunResult: + """``run`` for synchronous callers. Inside a running event loop it runs on a helper thread.""" + return run_blocking(self.run(message, **kwargs)) + + def _prepare(self, message: Any, responses: Optional[Mapping[str, Any]], checkpoint_id: Optional[str], + checkpoint_storage: Optional[CheckpointStorage], governance: Any) -> "_Run": + if self._running: + raise WorkflowError(f"workflow {self.name!r} is already running") + if message is not None and (responses or checkpoint_id): + raise WorkflowError("give a message to start a run, or responses/checkpoint_id to continue one, not both") + if message is None and not responses and not checkpoint_id: + raise WorkflowError("a new run needs a message") + storage = checkpoint_storage or self.checkpoint_storage + if checkpoint_id and storage is None: + raise WorkflowError("checkpoint_id needs checkpoint_storage") + return _Run(self, message, dict(responses or {}), checkpoint_id, storage, + self.governance if governance is None else governance) + + +def run_blocking(coro: Awaitable[Any]) -> Any: + """Run a coroutine to completion from synchronous code, even when called inside a running + event loop (then on a helper thread with its own loop).""" + try: + asyncio.get_running_loop() + except RuntimeError: + return asyncio.run(coro) # type: ignore[arg-type] + with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool: + return pool.submit(asyncio.run, coro).result() + + +class _Run: + def __init__(self, workflow: Workflow, message: Any, responses: Dict[str, Any], checkpoint_id: Optional[str], + storage: Optional[CheckpointStorage], governance: Any) -> None: + self.workflow = workflow + self.message = message + self.responses = responses + self.checkpoint_id = checkpoint_id + self.storage = storage + self.governance_config = governance + self.run_id = uuid.uuid4().hex + self.superstep = 0 + self.state: Dict[str, Any] = {} + self.pending: List[_Envelope] = [] + self.fan_in: Dict[int, Dict[str, List[Any]]] = {} + self.requests: Dict[str, RequestInfo] = {} + self.result = WorkflowRunResult(self.run_id, FAILED) + self.recorder = SpanRecorder(otel_tracer()) + self.queue: Optional["asyncio.Queue[Optional[WorkflowEvent]]"] = None + self.last_checkpoint: Optional[str] = None + self.invocations = 0 + self.started_work = False # False: the run was refused before changing anything + + # events --------------------------------------------------------------------------------- + def emit(self, event: WorkflowEvent) -> None: + self.result.events.append(event) + if self.queue is not None: + self.queue.put_nowait(event) + + # state restore / save ------------------------------------------------------------------- + def _restore_suspended(self) -> None: + snap = self.workflow._suspended + if snap is None: + raise WorkflowError(f"workflow {self.workflow.name!r} has no pending requests to respond to") + self.state, self.fan_in = dict(snap["state"]), {k: {s: list(v) for s, v in b.items()} for k, b in snap["fan_in"].items()} + self.requests, self.superstep = dict(snap["requests"]), snap["superstep"] + self.last_checkpoint = snap.get("checkpoint_id") + + def _restore_checkpoint(self) -> None: + assert self.storage is not None and self.checkpoint_id is not None + cp = self.storage.load(self.checkpoint_id) + if cp.workflow_name != self.workflow.name or cp.graph_signature != self.workflow.graph_signature: + raise CheckpointError("the checkpoint belongs to a different workflow or graph; refusing to restore it") + self.superstep = cp.superstep + self.state = decode_value(cp.state) + self.pending = [_Envelope(m["source"], m["target"], decode_value(m["payload"])) for m in cp.messages] + self.fan_in = {int(k): {s: decode_value(v) for s, v in buf.items()} for k, buf in cp.edge_state.items()} + self.requests = {} + for r in cp.pending_requests: + self.requests[r["request_id"]] = RequestInfo(r["request_id"], r["executor_id"], decode_value(r["data"]), + decode_response_type(r["response_type"])) + for ex_id, st in cp.executor_states.items(): + if ex_id not in self.workflow._executors: + raise CheckpointError(f"checkpoint has state for an unknown executor {ex_id!r}") + self.workflow._executors[ex_id].restore_state(decode_value(st)) + self.last_checkpoint = cp.checkpoint_id + + def _checkpoint(self) -> None: + if self.storage is None: + return + cp = WorkflowCheckpoint( + workflow_name=self.workflow.name, graph_signature=self.workflow.graph_signature, run_id=self.run_id, + superstep=self.superstep, + messages=[{"source": e.source, "target": e.target, "payload": encode_value(e.payload)} for e in self.pending], + state=encode_value(self.state), + executor_states={i: encode_value(self.workflow._executors[i].snapshot_state()) for i in self.workflow._order}, + edge_state={str(k): {s: encode_value(v) for s, v in buf.items()} for k, buf in self.fan_in.items()}, + pending_requests=[{"request_id": r.request_id, "executor_id": r.executor_id, "data": encode_value(r.data), + "response_type": encode_response_type(r.response_type)} for r in self.requests.values()], + previous_checkpoint_id=self.last_checkpoint) + self.last_checkpoint = self.storage.save(cp) + self.emit(WorkflowEvent("checkpoint", {"checkpoint_id": self.last_checkpoint}, None, self.superstep)) + + # routing -------------------------------------------------------------------------------- + def _route(self, source: str, message: Any, target_id: Optional[str]) -> None: + edges = self.workflow._outgoing.get(source, []) + if not edges: + raise WorkflowError(f"executor {source!r} sent a message but has no outgoing edges") + if target_id is not None and not any(target_id in e.targets for e in edges): + raise WorkflowError(f"executor {source!r} has no edge to {target_id!r}") + for edge in edges: + if isinstance(edge, _FanIn): + if target_id is not None and target_id != edge.target: + continue + key = self.workflow._edge_index[id(edge)] + buf = self.fan_in.setdefault(key, {s: [] for s in edge.fan_sources}) + buf[source].append(message) + if all(buf[s] for s in edge.fan_sources): + self.pending.append(_Envelope(source, edge.target, [buf[s].pop(0) for s in edge.fan_sources])) + continue + targets = edge.route(message) # type: ignore[attr-defined] + for t in targets: + if target_id is None or t == target_id: + self.pending.append(_Envelope(source, t, message)) + + # the superstep loop --------------------------------------------------------------------- + async def _invoke(self, ex: Executor, work: List[Tuple[str, Any]]) -> Tuple[WorkflowContext, Optional[BaseException]]: + ctx = WorkflowContext(self, ex.id, sorted({src for src, _ in work if src and src != "$response"})) + try: + with self.recorder.span(f"{OP_EXECUTOR} {ex.id}", OP_EXECUTOR, + {"osiris.workflow.executor_id": ex.id, "osiris.workflow.superstep": self.superstep}): + for source, item in work: + ctx.source_executor_ids = [source] if source and source != "$response" else [] + if source == "$response": + request, response = item + await ex._response(request.data, response, ctx) # type: ignore[misc] + continue + fn = ex.handler_for(item) + if fn is None: + raise WorkflowError(f"executor {ex.id!r} has no handler for {type(item).__name__} " + f"(it accepts {ex.input_types})") + await fn(item, ctx) + return ctx, None + except asyncio.CancelledError: + raise + except BaseException as exc: # noqa: BLE001 - re-raised by execute() after recording + return ctx, exc + + async def _superstep(self, deliveries: Dict[str, List[Tuple[str, Any]]]) -> None: + self.superstep += 1 + self.emit(WorkflowEvent("superstep_started", None, None, self.superstep)) + order = [i for i in self.workflow._order if i in deliveries] + for i in order: + self.emit(WorkflowEvent("executor_invoked", {"messages": len(deliveries[i])}, i, self.superstep)) + self.invocations += len(order) + results = await asyncio.gather(*(self._invoke(self.workflow._executors[i], deliveries[i]) for i in order)) + failure: Optional[Tuple[str, BaseException]] = None + for i, (ctx, exc) in zip(order, results): + if exc is not None: + self.emit(WorkflowEvent("executor_failed", {"error": type(exc).__name__}, i, self.superstep)) + failure = failure or (i, exc) + continue + for event in ctx.events: + self.emit(event) + for output in ctx.outputs: + self.result.outputs.append(output) + self.emit(WorkflowEvent("output", output, i, self.superstep)) + for request in ctx.requests: + if request.request_id in self.requests: + failure = failure or (i, WorkflowError(f"duplicate request id {request.request_id!r}")) + continue + self.requests[request.request_id] = request + self.emit(WorkflowEvent("request_info", request, i, self.superstep)) + self.state.update(ctx.state_writes) + for message, target in ctx.sent: + try: + self._route(i, message, target) + except WorkflowError as exc: + failure = failure or (i, exc) + self.emit(WorkflowEvent("executor_completed", {"sent": len(ctx.sent), "outputs": len(ctx.outputs)}, + i, self.superstep)) + if failure is not None: + raise _ExecutorFailure(*failure) + self.emit(WorkflowEvent("superstep_completed", None, None, self.superstep)) + + def _hold(self, deliveries: Dict[str, List[Tuple[str, Any]]]) -> None: + """Stopping before ``deliveries`` ran: keep their messages pending and their responses' + requests open (the response itself must be sent again).""" + for target, items in deliveries.items(): + for source, payload in items: + if source == "$response": + request = payload[0] + self.requests[request.request_id] = request + else: + self.pending.append(_Envelope(source, target, payload)) + + def _take_deliveries(self) -> Dict[str, List[Tuple[str, Any]]]: + deliveries: Dict[str, List[Tuple[str, Any]]] = {} + for env in self.pending: + deliveries.setdefault(env.target, []).append((env.source, env.payload)) + self.pending = [] + return deliveries + + async def execute(self, queue: Optional["asyncio.Queue[Optional[WorkflowEvent]]"]) -> WorkflowRunResult: + wf = self.workflow + self.queue = queue + wf._running = True + governor: Optional[_Governor] = None + status, reason, error = FAILED, "", None # type: Tuple[str, str, Optional[BaseException]] + try: + with self.recorder.span(f"{OP_INVOKE_WORKFLOW} {wf.name}", OP_INVOKE_WORKFLOW, + {"osiris.workflow.name": wf.name}): + if self.governance_config is not None and self.governance_config is not False: + governor = _Governor(self.governance_config, wf.name) + text = _input_text(self.message) if self.message is not None else \ + f"resume workflow {wf.name} (checkpoint {str(self.checkpoint_id)[:16]})" + refusal = await governor.open(text) + self.run_id = self.result.run_id = governor.tctx.run_id + if refusal: + status, reason = BLOCKED, refusal + return self.result + self.emit(WorkflowEvent("started", {"run_id": self.run_id, "workflow": wf.name}, None, self.superstep)) + deliveries: Dict[str, List[Tuple[str, Any]]] = {} + if self.message is not None: + wf._suspended = None + for ex in wf._executors.values(): + ex.reset() + start = wf._executors[wf.start_executor_id] + if start.handler_for(self.message) is None: + raise WorkflowError(f"start executor {start.id!r} cannot take {type(self.message).__name__} " + f"(it accepts {start.input_types})") + self.pending = [_Envelope("", wf.start_executor_id, self.message)] + self.started_work = True + self._checkpoint() + else: + if self.checkpoint_id: + self._restore_checkpoint() + else: + self._restore_suspended() + for rid, response in self.responses.items(): # check every response before using any + request = self.requests.get(rid) + if request is None: + raise WorkflowError(f"no pending request {rid!r}") + if not response_type_ok(response, request.response_type): + raise WorkflowError(f"response to {rid!r} must be {request.response_type.__name__}, " + f"got {type(response).__name__}") + for rid, response in self.responses.items(): + request = self.requests.pop(rid) + deliveries.setdefault(request.executor_id, []).append(("$response", (request, response))) + self.started_work = True + deliveries_pending = deliveries or self._take_deliveries() + while deliveries_pending: + if self.superstep >= wf.max_supersteps: + self._hold(deliveries_pending) + status, reason = STOPPED, f"superstep limit ({wf.max_supersteps}) reached with messages pending" + self._checkpoint() + return self.result + if governor is not None: + stop = governor.step() + if stop: + self._hold(deliveries_pending) + status, reason = STOPPED, stop + self._checkpoint() + return self.result + await self._superstep(deliveries_pending) + self._checkpoint() + deliveries_pending = self._take_deliveries() + status = IDLE_WITH_PENDING_REQUESTS if self.requests else COMPLETED + return self.result + except _ExecutorFailure as failure: + status, reason, error = FAILED, f"executor {failure.executor_id!r} failed: {type(failure.error).__name__}", \ + failure.error + raise failure.error from None + except asyncio.CancelledError: + status, reason = CANCELLED, "the run was cancelled" + raise + except BaseException as exc: + status, reason, error = FAILED, f"{type(exc).__name__}: {str(exc)[:200]}", exc + raise + finally: + wf._running = False + self._finish(status, reason, error, governor) + + def _finish(self, status: str, reason: str, error: Optional[BaseException], governor: Optional[_Governor]) -> None: + try: + self._close(status, reason, error, governor) + finally: + if self.queue is not None: + self.queue.put_nowait(None) + + def _close(self, status: str, reason: str, error: Optional[BaseException], governor: Optional[_Governor]) -> None: + wf = self.workflow + res = self.result + res.status, res.reason, res.run_id = status, reason, self.run_id + res.pending_requests = list(self.requests.values()) + res.checkpoint_id = self.last_checkpoint + if status == IDLE_WITH_PENDING_REQUESTS: + wf._suspended = {"state": self.state, "fan_in": self.fan_in, "requests": dict(self.requests), + "superstep": self.superstep, "checkpoint_id": self.last_checkpoint} + elif self.started_work: + wf._suspended = None # a refused call (bad response, governance) leaves a paused run paused + if governor is not None and governor.opened: + from osiris_cli.orchestration.evidence_firewall import check_report + evidence = [] + for event in res.events: + if event.type == "output": + text = output_text(event.data) + if text: + report = check_report(text) + evidence.append({"executor_id": event.executor_id, "decision": report.decision, + "findings": len(report.findings)}) + res.governance = {"run_record": governor.record, "evidence": evidence} + if error is not None: + res.governance["error"] = type(error).__name__ + if status == BLOCKED: + res.governance["refusal"] = reason + usage = {"workflow": {"name": wf.name, "graph_signature": wf.graph_signature, "supersteps": self.superstep, + "executor_invocations": self.invocations, "outputs": len(res.outputs), + "pending_requests": len(res.pending_requests), + "checkpoint_head": self.last_checkpoint, "evidence": evidence, + "outputs_sha256": hashlib.sha256(json.dumps( + [output_text(o) or type(o).__name__ for o in res.outputs]).encode()).hexdigest()}, + "telemetry": self.recorder.summary()} + try: + governor.close(status, usage, f"workflow {wf.name}: {reason}"[:500]) + finally: + res.governance["run_record"] = governor.record + res.telemetry = self.recorder.to_dicts() + self.emit(WorkflowEvent("status", {"status": status, "reason": reason}, None, self.superstep)) + + +class _ExecutorFailure(Exception): + def __init__(self, executor_id: str, error: BaseException) -> None: + super().__init__(executor_id) + self.executor_id = executor_id + self.error = error diff --git a/osiris_cli/task_context.py b/osiris_cli/task_context.py index 49ca8415..e7c65aa8 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", "agent") # agent: an osiris_cli.runtime Agent run +KINDS = ("code", "sprint_story", "capsule", "agent", "workflow") # agent / workflow: osiris_cli.runtime runs READ_TOOLS = ("grep_code", "list_dir", "read_file") WRITE_TOOL = "write_file" diff --git a/tests/test_council_trio_workflows.py b/tests/test_council_trio_workflows.py new file mode 100644 index 00000000..a992266e --- /dev/null +++ b/tests/test_council_trio_workflows.py @@ -0,0 +1,84 @@ +"""The council and the trio run on the osiris_cli.runtime workflow engine. + +Their own suites (test_council.py, test_governed_trio.py, test_trio_command.py, test_trio_authz.py) +are unchanged and are the behavioural check. These tests pin the workflow shapes and the council's +event sequences as they were before the move (recorded from main at 588d624).""" + +from osiris_cli.orchestration import council +from osiris_cli.orchestration.trio import DeveloperOutput, run_trio, trio_workflow + +GOOD = {"AURA": "Proposal: compile the Bell organism and simulate it. Risk: none known.", + "AIDEN": "No receipt is named yet.\nVERDICT: PROCEED", + "IRIS": "AURA proposes a simulator run; AIDEN wants a receipt. Next: approve the simulator run."} + + +def model(texts): + def fn(role, system, prompt): + out = texts[role] + if isinstance(out, Exception): + raise out + return out if isinstance(out, tuple) else (out, "fake:model") + return fn + + +def sequence(result): + return [(e["actor"], e["event"]) for e in result["events"]] + + +def test_council_workflow_shape(): + wf = council.council_workflow("/unused/receipts.jsonl") + shape = wf.describe() + assert [e["id"] for e in shape["executors"]] == ["AURA", "OSIRIS", "AIDEN", "IRIS"] + assert shape["start"] == "AURA" + kinds = [(e["kind"], e["source"]) for e in shape["edges"]] + assert kinds == [("switch", "AURA"), ("switch", "AIDEN"), ("direct", "IRIS")] + assert [c["target"] for c in shape["edges"][0]["cases"]] == ["OSIRIS", "AIDEN"] + + +def test_council_event_sequences_match_the_loop_it_replaced(tmp_path): + receipts = str(tmp_path / "agents.jsonl") + ok = council.run_task("Establish a Bell baseline", "ctx text", receipts_path=receipts, model_fn=model(GOOD), + claims=["THETA_LOCK: REFUTED"]) + assert sequence(ok) == [("OSIRIS", "TASK_ACCEPTED"), ("AURA", "PROPOSAL"), ("OSIRIS", "FIREWALL_ACCEPT"), + ("AIDEN", "REVIEW"), ("OSIRIS", "FIREWALL_ACCEPT"), ("IRIS", "BRIEF"), + ("OSIRIS", "FIREWALL_ACCEPT"), ("AIDEN", "VERDICT"), + ("OSIRIS", "DECISION_PENDING_HUMAN_APPROVAL"), ("OSIRIS", "RECEIPT_RECORDED")] + calls = [] + + def tracking(role, system, prompt): + calls.append(role) + return model(dict(GOOD, AIDEN=RuntimeError("down")))(role, system, prompt) + + failed = council.run_task("Establish a Bell baseline", receipts_path=receipts, model_fn=tracking, claims=[]) + assert calls == ["AURA", "AIDEN"] # IRIS never runs after AIDEN fails + assert sequence(failed) == [("OSIRIS", "TASK_ACCEPTED"), ("AURA", "PROPOSAL"), ("OSIRIS", "FIREWALL_ACCEPT"), + ("OSIRIS", "MODEL_UNAVAILABLE"), ("OSIRIS", "DECISION_FAILED"), + ("OSIRIS", "RECEIPT_RECORDED")] + mocked = council.run_task("Establish a Bell baseline", receipts_path=receipts, + model_fn=model(dict(GOOD, IRIS=("[gemma:mock] deterministic mock response", "ollama"))), + claims=[]) + assert sequence(mocked)[-4:] == [("OSIRIS", "FIREWALL_ACCEPT"), ("OSIRIS", "MODEL_UNAVAILABLE"), + ("OSIRIS", "DECISION_FAILED"), ("OSIRIS", "RECEIPT_RECORDED")] + + +def test_council_writes_no_task_ledger_entry(tmp_path, monkeypatch): + monkeypatch.setenv("OSIRIS_HOME", str(tmp_path / "home")) + council.run_task("Establish a Bell baseline", receipts_path=str(tmp_path / "a.jsonl"), model_fn=model(GOOD), + claims=[]) + assert not (tmp_path / "home" / "tasks").exists() # its receipts chain is its record, as before + + +def test_trio_workflow_shape_and_early_exit(tmp_path): + shape = trio_workflow().describe() + assert [e["id"] for e in shape["executors"]] == ["baseline", "research", "developer", "critic"] + assert [(e["source"], e["target"]) for e in shape["edges"]] == [("baseline", "research"), + ("research", "developer"), + ("developer", "critic")] + repo = tmp_path / "repo" + repo.mkdir() + (repo / "calc.py").write_text("def mean(xs):\n return sum(xs) / len(xs)\n") + (repo / "test_calc.py").write_text("from calc import mean\n\ndef test_mean():\n assert mean([2, 4]) == 3\n") + called = [] + res = run_trio(str(repo), lambda f, sb: called.append(1) or DeveloperOutput({}, ""), str(tmp_path / "out"), + timeout=60) + assert res.outcome == "NO_DEFECT" and called == [] and res.receipts == [] diff --git a/tests/test_runtime_orchestrations.py b/tests/test_runtime_orchestrations.py new file mode 100644 index 00000000..06f56bed --- /dev/null +++ b/tests/test_runtime_orchestrations.py @@ -0,0 +1,211 @@ +"""osiris_cli.runtime orchestrations: sequential, concurrent, group chat, handoff, Magentic. + +The patterns mirror microsoft/agent-framework's orchestrations package; the tests for who decides +(code-chosen speakers, declared handoff routes, strictly parsed Magentic ledgers, no final answer +on a limit) are OSIRIS's own.""" + +import json +from typing import Any, List + +import pytest + +from osiris_cli.runtime import ( + COMPLETED, + IDLE_WITH_PENDING_REQUESTS, + Agent, + AgentResult, + ConcurrentBuilder, + GovernanceConfig, + GovernanceRequiredError, + GroupChatBuilder, + HandoffBuilder, + HandoffUserInputRequest, + InMemoryCheckpointStorage, + MagenticBuilder, + MagenticResult, + Message, + SequentialBuilder, + WorkflowError, + parse_progress_ledger, + round_robin, +) +from osiris_cli.runtime.testing import FakeChatClient, call_response +from osiris_cli.task_context import TaskLedger +from tests.runtime_support import entries, governed + + +def agent(tmp_path, name: str, script: List[Any]) -> Agent: + return Agent(FakeChatClient(script), name=name, governance=governed(tmp_path)) + + +def texts(conversation: List[Message]) -> List[tuple]: + return [(m.author_name or m.role, m.text) for m in conversation] + + +def workflow_runs(config: GovernanceConfig) -> List[dict]: + return [e for e in entries(config) if e["kind"] == "task_open" and e["context"]["kind"] == "workflow"] + + +def test_builders_are_governed_by_default_and_cannot_switch_it_off(): + builder = SequentialBuilder([Agent(FakeChatClient(["x"]), name="a", governance=GovernanceConfig())]) + assert isinstance(builder.governance, GovernanceConfig) + with pytest.raises(GovernanceRequiredError): + SequentialBuilder([Agent(FakeChatClient(["x"]), name="a")], governance=False) + + +def test_sequential_passes_the_conversation_and_records_every_run(tmp_path): + config = governed(tmp_path) + writer, editor = agent(tmp_path, "writer", ["first draft"]), agent(tmp_path, "editor", ["edited draft"]) + result = SequentialBuilder([writer, editor], governance=config).build().run_sync("write a note") + assert result.status == COMPLETED + assert texts(result.outputs[0]) == [("user", "write a note"), ("writer", "first draft"), ("editor", "edited draft")] + assert [m.text for m in editor.client.calls[0]["messages"]] == ["write a note", "first draft"] + opens = [e for e in entries(config) if e["kind"] == "task_open"] + assert sorted(e["context"]["kind"] for e in opens) == ["agent", "agent", "workflow"] + assert TaskLedger(config.resolved_ledger_path()).verify()["intact"] + + +def test_concurrent_fans_out_the_same_input_and_aggregates_in_order(tmp_path): + a, b = agent(tmp_path, "a", ["answer A"]), agent(tmp_path, "b", ["answer B"]) + result = ConcurrentBuilder([a, b], governance=governed(tmp_path)).build().run_sync("question") + assert texts(result.outputs[0]) == [("user", "question"), ("a", "answer A"), ("b", "answer B")] + assert [m.text for m in a.client.calls[0]["messages"]] == [m.text for m in b.client.calls[0]["messages"]] + + async def count(results: List[AgentResult]) -> dict: + return {r.executor_id: r.text for r in results} + + c, d = agent(tmp_path, "c", ["C"]), agent(tmp_path, "d", ["D"]) + custom = ConcurrentBuilder([c, d], aggregator=count, governance=governed(tmp_path)).build().run_sync("q") + assert custom.outputs == [{"c": "C", "d": "D"}] + + +def test_group_chat_speakers_are_chosen_by_code(tmp_path): + x, y = agent(tmp_path, "x", ["x1", "x2"]), agent(tmp_path, "y", ["y1"]) + result = GroupChatBuilder([x, y], selector=round_robin, max_rounds=3, + governance=governed(tmp_path)).build().run_sync("debate") + assert [t for _, t in texts(result.outputs[0])] == ["debate", "x1", "y1", "x2"] + finished = [e.data for e in result.events if e.type == "custom" and e.data["name"] == "group_chat_finished"] + assert finished[0]["data"]["reason"] == "max_rounds (3) reached" + + def until_agreed(state: Any): + return None if any("agreed" in m.text for m in state.conversation) else "x" + + x2 = agent(tmp_path, "x", ["thinking", "agreed"]) + ended = GroupChatBuilder([x2, agent(tmp_path, "y", [])], selector=until_agreed, + governance=governed(tmp_path)).build().run_sync("go") + assert [t for _, t in texts(ended.outputs[0])] == ["go", "thinking", "agreed"] + + with pytest.raises(WorkflowError, match="not in the group"): + GroupChatBuilder([agent(tmp_path, "x", ["?"])], selector=lambda s: "mallory", + governance=governed(tmp_path)).build().run_sync("go") + + +def test_handoff_offers_only_allowed_routes_and_strips_the_handoff_call(tmp_path): + triage = agent(tmp_path, "triage", [call_response("handoff_to_billing", {"reason": "invoice"}, call_id="h1")]) + billing = agent(tmp_path, "billing", ["Your invoice was resent."]) + refunds = agent(tmp_path, "refunds", ["unused"]) + wf = HandoffBuilder([triage, billing, refunds], start="triage", + routes={"triage": ["billing", "refunds"], "billing": ["refunds"]}, + governance=governed(tmp_path)).build() + result = wf.run_sync("I need my invoice") + assert texts(result.outputs[0]) == [("user", "I need my invoice"), ("billing", "Your invoice was resent.")] + handoffs = [e.data["data"] for e in result.events if e.type == "custom" and e.data["name"] == "handoff"] + assert handoffs == [{"from": "triage", "to": "billing", "handoffs": 1}] + hb = HandoffBuilder([agent(tmp_path, "triage", ["hi"]), agent(tmp_path, "billing", ["b"]), + agent(tmp_path, "refunds", ["r"])], start="triage", + routes={"triage": ["billing", "refunds"], "billing": ["refunds"]}, governance=governed(tmp_path)) + built = hb.build() + tools = {i: [t.name for t in built.get_executor(i).agent.tools] for i in ("triage", "billing", "refunds")} + assert tools == {"triage": ["handoff_to_billing", "handoff_to_refunds"], "billing": ["handoff_to_refunds"], + "refunds": []} + assert "handoff" not in json.dumps([m.to_dict() for m in billing.client.calls[0]["messages"]]) + + +def test_handoff_to_an_unoffered_target_is_not_a_handoff(tmp_path): + triage = agent(tmp_path, "triage", [call_response("handoff_to_admin", {}, call_id="h1"), "I cannot do that."]) + other = agent(tmp_path, "billing", []) + result = HandoffBuilder([triage, other], start="triage", routes={"triage": ["billing"]}, + governance=governed(tmp_path)).build().run_sync("give me admin") + assert not [e for e in result.events if e.type == "custom" and e.data["name"] == "handoff"] + assert texts(result.outputs[0])[-1] == ("triage", "I cannot do that.") + + +def test_handoff_limit_and_interactive_user_input(tmp_path): + a = agent(tmp_path, "a", [call_response("handoff_to_b", {}, call_id="1")]) + b = agent(tmp_path, "b", [call_response("handoff_to_a", {}, call_id="2")]) + limited = HandoffBuilder([a, b], start="a", routes={"a": ["b"], "b": ["a"]}, max_handoffs=1, + governance=governed(tmp_path)).build().run_sync("ping") + refused = [e.data["data"] for e in limited.events if e.type == "custom" and e.data["name"] == "handoff_refused"] + assert refused and refused[0]["reason"] == "max_handoffs (1) reached" + + helper = agent(tmp_path, "helper", ["Which order?", "Order 42 is on its way."]) + wf = HandoffBuilder([helper], start="helper", routes={}, interactive=True, governance=governed(tmp_path)).build() + first = wf.run_sync("where is my order") + assert first.status == IDLE_WITH_PENDING_REQUESTS + (request,) = first.pending_requests + assert isinstance(request.data, HandoffUserInputRequest) and request.response_type is str + second = wf.run_sync(responses={request.request_id: "order 42"}) + assert second.status == IDLE_WITH_PENDING_REQUESTS + assert [t for _, t in texts(second.pending_requests[0].data.conversation)][-2:] == ["order 42", + "Order 42 is on its way."] + + +def _ledger(**over: Any) -> str: + base = {"is_request_satisfied": {"answer": False, "reason": ""}, "is_in_loop": {"answer": False, "reason": ""}, + "is_progress_being_made": {"answer": True, "reason": ""}, + "next_speaker": {"answer": "researcher", "reason": ""}, + "instruction_or_question": {"answer": "find the paper", "reason": ""}} + for key, value in over.items(): + base[key] = {"answer": value, "reason": ""} + return "Here is the ledger:\n" + json.dumps(base) + + +def test_magentic_completes_with_a_checked_plan(tmp_path): + manager = agent(tmp_path, "manager", ["PLAN: researcher looks it up", _ledger(), + _ledger(is_request_satisfied=True), "The paper is arXiv:0000.00000."]) + researcher = agent(tmp_path, "researcher", ["Found arXiv:0000.00000."]) + config = governed(tmp_path) + result = MagenticBuilder([researcher], manager=manager, governance=config).build().run_sync("find the paper") + (out,) = result.outputs + assert isinstance(out, MagenticResult) and out.status == "completed" and out.rounds == 1 + assert out.answer == "The paper is arXiv:0000.00000." + instruction = researcher.client.calls[0]["messages"][-1] + assert (instruction.role, instruction.author_name, instruction.text) == ("user", "magentic_manager", "find the paper") + assert result.governance["evidence"][0]["executor_id"] == "magentic_manager" + assert len(workflow_runs(config)) == 1 + + +def test_magentic_invalid_proposals_stall_and_limits_give_no_answer(tmp_path): + bad = ["not json", _ledger(next_speaker="mallory"), _ledger(is_in_loop=True)] + manager = agent(tmp_path, "manager", ["plan", *bad, "replan", "still not json", "{}", "[]"]) + result = MagenticBuilder([agent(tmp_path, "researcher", [])], manager=manager, max_stalls=2, max_resets=1, + governance=governed(tmp_path)).build().run_sync("task") + out = result.outputs[0] + assert (out.status, out.answer, out.rounds, out.resets) == ("stalled", "", 0, 1) + stalls = [e.data["data"]["problem"] for e in result.events if e.type == "custom" and e.data["name"] == "magentic_stall"] + assert stalls[:3] == ["the progress ledger was not the expected JSON", "next_speaker 'mallory' is not in the team", ""] + + manager2 = agent(tmp_path, "manager", ["plan", _ledger(), _ledger()]) + capped = MagenticBuilder([agent(tmp_path, "researcher", ["r1", "r2"])], manager=manager2, max_rounds=2, + governance=governed(tmp_path)).build().run_sync("task") + assert (capped.outputs[0].status, capped.outputs[0].answer, capped.outputs[0].rounds) == ("round_limit", "", 2) + + +def test_progress_ledger_parsing_is_strict(): + assert parse_progress_ledger(_ledger())["next_speaker"] == "researcher" + assert parse_progress_ledger(_ledger(is_in_loop="no")) is None # a string is not a bool + assert parse_progress_ledger('{"is_request_satisfied": {"answer": true}}') is None + assert parse_progress_ledger("no json at all") is None + + +def test_group_chat_resumes_from_a_checkpoint_with_new_agent_objects(tmp_path): + storage = InMemoryCheckpointStorage() + + def build(x_script: List[str], y_script: List[str]): + return GroupChatBuilder([agent(tmp_path, "x", x_script), agent(tmp_path, "y", y_script)], max_rounds=2, + name="chat", checkpoint_storage=storage, governance=governed(tmp_path)).build() + + full = build(["x1"], ["y1"]).run_sync("start") + after_first_turn = [c for c in storage.list_checkpoints("chat") if c.run_id == full.run_id][2] + resumed = build([], ["y1 again"]).run_sync(checkpoint_id=after_first_turn.checkpoint_id) + assert [t for _, t in texts(resumed.outputs[0])] == ["start", "x1", "y1 again"] diff --git a/tests/test_runtime_workflows.py b/tests/test_runtime_workflows.py new file mode 100644 index 00000000..0bcd2fcc --- /dev/null +++ b/tests/test_runtime_workflows.py @@ -0,0 +1,404 @@ +"""osiris_cli.runtime workflows: the engine (edges, supersteps, requests, checkpoints, governance). + +Several tests mirror behaviours of microsoft/agent-framework's workflow tests (fan-out/fan-in, +switch-case, request/response resume, checkpoint restore, graph-signature check); the +governance, determinism and no-pickle tests are OSIRIS's own.""" + +import asyncio +import dataclasses +import json +from typing import Any, List + +import pytest + +from osiris_cli.runtime import ( + BLOCKED, + COMPLETED, + IDLE_WITH_PENDING_REQUESTS, + STOPPED, + Case, + CheckpointEncodingError, + CheckpointError, + CheckpointIntegrityError, + Default, + Executor, + FileCheckpointStorage, + InMemoryCheckpointStorage, + WorkflowBuilder, + WorkflowContext, + WorkflowError, + WorkflowGovernanceError, + executor, + handler, + register_checkpoint_type, + response_handler, +) +from osiris_cli.runtime._checkpoints import decode_value, encode_value +from osiris_cli.task_context import TaskLedger +from tests.runtime_support import entries, governed, run + + +class Upper(Executor): + @handler + async def go(self, text: str, ctx: WorkflowContext) -> None: + await ctx.send_message(text.upper()) + + +class Relay(Executor): + @handler + async def go(self, text: str, ctx: WorkflowContext) -> None: + await ctx.send_message(text) + + +class Length(Executor): + @handler + async def go(self, text: str, ctx: WorkflowContext) -> None: + await ctx.send_message(len(text)) + + +class Reverse(Executor): + @handler + async def go(self, text: str, ctx: WorkflowContext) -> None: + await ctx.send_message(text[::-1]) + + +class Collect(Executor): + @handler + async def go(self, items: list, ctx: WorkflowContext) -> None: + await ctx.yield_output(items) + + @handler + async def one(self, item: str, ctx: WorkflowContext) -> None: + await ctx.yield_output(item) + + +@dataclasses.dataclass +class Approval: + action: str + + +register_checkpoint_type(Approval) + + +class Ask(Executor): + @handler + async def go(self, text: str, ctx: WorkflowContext) -> None: + await ctx.request_info(Approval(text), bool) + + @response_handler + async def answered(self, request: Approval, response: bool, ctx: WorkflowContext) -> None: + await ctx.yield_output(f"{request.action}: {'approved' if response else 'refused'}") + + +def test_chain_fan_out_and_fan_in_deliver_in_participant_order(): + up, relay, length, rev, out = Upper("up"), Relay("relay"), Length("length"), Reverse("rev"), Collect("out") + wf = (WorkflowBuilder(name="fan", start_executor=up).add_edge(up, relay) + .add_fan_out_edges(relay, [length, rev]).add_fan_in_edges([length, rev], out).build()) + result = wf.run_sync("hello") + assert result.status == COMPLETED + assert result.outputs == [[5, "OLLEH"]] # fan-in order is the source order, not finish order + assert [e.superstep for e in result.events if e.type == "superstep_completed"] == [1, 2, 3, 4] + + +def test_conditional_and_switch_case_edges_route_by_message(): + @executor(id="classify") + async def classify(text: str, ctx: WorkflowContext) -> None: + await ctx.send_message(text) + + short, long_, other = Collect("short"), Collect("long"), Collect("other") + wf = (WorkflowBuilder(name="switch", start_executor=classify) + .add_switch_case_edge_group(classify, [Case(lambda t: len(t) < 4, short), Case(lambda t: len(t) < 8, long_), + Default(other)]).build()) + for text, where in (("hi", "short"), ("hello", "long"), ("a long message", "other")): + result = wf.run_sync(text) + assert [(e.executor_id, e.data) for e in result.events if e.type == "output"] == [(where, text)] + + gate = Relay("gate") + sink = Collect("sink") + wf2 = WorkflowBuilder(name="cond", start_executor=gate).add_edge(gate, sink, condition=lambda t: "ok" in t).build() + assert wf2.run_sync("ok then").outputs == ["ok then"] + assert wf2.run_sync("nope").outputs == [] # the condition dropped it; the run still completes + + +def test_concurrent_executors_apply_results_in_registration_order(): + class Slow(Executor): + def __init__(self, id: str, delay: float) -> None: + super().__init__(id) + self.delay = delay + + @handler + async def go(self, text: str, ctx: WorkflowContext) -> None: + await asyncio.sleep(self.delay) + ctx.set_state("last", self.id) + await ctx.yield_output(self.id) + + start = Relay("start") + a, b = Slow("a", 0.05), Slow("b", 0.0) # b finishes first + wf = WorkflowBuilder(name="order", start_executor=start).add_fan_out_edges(start, [a, b]).build() + result = wf.run_sync("go") + assert result.outputs == ["a", "b"] + assert [e.executor_id for e in result.events if e.type == "executor_completed"][-2:] == ["a", "b"] + + +def test_build_validation(): + with pytest.raises(WorkflowError, match="no start executor"): + WorkflowBuilder().build() + lonely = Relay("lonely") + with pytest.raises(WorkflowError, match="not reachable"): + WorkflowBuilder(start_executor=Relay("s")).add_executor(lonely).build() + with pytest.raises(WorkflowError, match="share the id"): + WorkflowBuilder(start_executor=Relay("x")).add_edge(Relay("x"), Collect("y")) + with pytest.raises(WorkflowError, match="at least two"): + WorkflowBuilder(start_executor=Relay("s")).add_fan_out_edges(Relay("s"), [Collect("y")]) + with pytest.raises(TypeError, match="async"): + class Bad(Executor): + @handler + def go(self, text: str, ctx: WorkflowContext) -> None: + return None + + +def test_runtime_routing_errors_fail_the_run_and_reraise(): + class Wrong(Executor): + @handler + async def go(self, text: str, ctx: WorkflowContext) -> None: + await ctx.send_message(text, target_id="nowhere") + + class Boom(Executor): + @handler + async def go(self, text: str, ctx: WorkflowContext) -> None: + raise KeyError("boom") + + wrong = Wrong("wrong") + wf = WorkflowBuilder(start_executor=wrong).add_edge(wrong, Collect("c")).build() + with pytest.raises(WorkflowError, match="no edge to 'nowhere'"): + wf.run_sync("x") + with pytest.raises(KeyError): # the executor's own exception, unchanged + WorkflowBuilder(start_executor=Boom("boom")).build().run_sync("x") + start = Relay("start") + wf3 = WorkflowBuilder(start_executor=start).add_edge(start, Collect("c")).build() + with pytest.raises(WorkflowError, match="cannot take int"): + wf3.run_sync(5) + + +def test_superstep_limit_stops_with_messages_kept(): + class Loop(Executor): + @handler + async def go(self, n: int, ctx: WorkflowContext) -> None: + await ctx.send_message(n + 1) + + a, b = Loop("a"), Loop("b") + wf = WorkflowBuilder(start_executor=a, max_supersteps=5).add_edge(a, b).add_edge(b, a).build() + result = wf.run_sync(0) + assert result.status == STOPPED and "superstep limit (5)" in result.reason + + +def test_request_info_pauses_and_responses_resume_with_exact_types(): + wf = WorkflowBuilder(name="ask", start_executor=Ask("ask")).build() + first = wf.run_sync("deploy") + assert first.status == IDLE_WITH_PENDING_REQUESTS + (request,) = first.pending_requests + assert request.data == Approval("deploy") and request.response_type is bool + for bad in (1, "yes", None): # only True/False answer a bool request + with pytest.raises(WorkflowError, match="must be bool"): + wf.run_sync(responses={request.request_id: bad}) + with pytest.raises(WorkflowError, match="no pending request"): + wf.run_sync(responses={"other": True}) + done = wf.run_sync(responses={request.request_id: True}) # still pending after the refusals + assert done.status == COMPLETED and done.outputs == ["deploy: approved"] + with pytest.raises(WorkflowError, match="no pending requests"): + wf.run_sync(responses={request.request_id: True}) + + +def test_file_checkpoints_resume_a_paused_run_in_a_new_process_shape(tmp_path): + storage = FileCheckpointStorage(tmp_path / "cp") + first = WorkflowBuilder(name="ask", start_executor=Ask("ask"), checkpoint_storage=storage).build().run_sync("merge") + rid = first.pending_requests[0].request_id + fresh = WorkflowBuilder(name="ask", start_executor=Ask("ask"), checkpoint_storage=storage).build() + resumed = fresh.run_sync(checkpoint_id=first.checkpoint_id, responses={rid: False}) + assert resumed.outputs == ["merge: refused"] + checkpoints = storage.list_checkpoints("ask") + assert storage.verify("ask") == len(checkpoints) >= 3 + assert checkpoints[-1].previous_checkpoint_id is not None + + +def test_checkpoint_from_another_graph_is_refused(tmp_path): + storage = InMemoryCheckpointStorage() + first = WorkflowBuilder(name="ask", start_executor=Ask("ask"), checkpoint_storage=storage).build().run_sync("x") + other_start = Ask("ask") + other = (WorkflowBuilder(name="ask", start_executor=other_start, checkpoint_storage=storage) + .add_edge(other_start, Collect("extra")).build()) + with pytest.raises(CheckpointError, match="different workflow or graph"): + other.run_sync(checkpoint_id=first.checkpoint_id) + + +def test_tampered_checkpoint_file_is_refused(tmp_path): + storage = FileCheckpointStorage(tmp_path / "cp") + first = WorkflowBuilder(name="ask", start_executor=Ask("ask"), checkpoint_storage=storage).build().run_sync("x") + path = tmp_path / "cp" / "ask.jsonl" + lines = path.read_text(encoding="utf-8").splitlines() + record = json.loads(lines[0]) + record["checkpoint"]["superstep"] = 99 + lines[0] = json.dumps(record) + path.write_text("\n".join(lines) + "\n", encoding="utf-8") + with pytest.raises(CheckpointIntegrityError): + storage.load(first.checkpoint_id) + + +def test_checkpoint_encoding_refuses_unregistered_types_and_never_imports(): + class Unregistered: + pass + + with pytest.raises(CheckpointEncodingError, match="not registered"): + encode_value({"x": Unregistered()}) + with pytest.raises(CheckpointEncodingError): + encode_value(float("nan")) + with pytest.raises(CheckpointEncodingError, match="unregistered type"): + decode_value({"$type": "os:system", "$value": "echo pwned"}) + value = {"a": (1, "two"), "b": [Approval("x")], "c": None} + assert decode_value(json.loads(json.dumps(encode_value(value)))) == value + + class Holds(Executor): + @handler + async def go(self, text: str, ctx: WorkflowContext) -> None: + ctx.set_state("thing", Unregistered()) + await ctx.yield_output(text) + + wf = WorkflowBuilder(start_executor=Holds("holds"), checkpoint_storage=InMemoryCheckpointStorage()).build() + with pytest.raises(CheckpointEncodingError): + wf.run_sync("x") + + +def test_shared_state_is_committed_at_the_superstep_boundary(): + class Writer(Executor): + @handler + async def go(self, text: str, ctx: WorkflowContext) -> None: + ctx.set_state("seen", text) + assert ctx.get_state("seen") == text # the writer sees its own write at once + await ctx.send_message(text) + + class Reader(Executor): + @handler + async def go(self, text: str, ctx: WorkflowContext) -> None: + await ctx.yield_output(ctx.get_state("seen")) + + w, r = Writer("w"), Reader("r") + assert WorkflowBuilder(start_executor=w).add_edge(w, r).build().run_sync("v").outputs == ["v"] + + +def test_run_stream_yields_events_and_ends_with_status(): + up = Upper("up") + wf = WorkflowBuilder(start_executor=up).add_edge(up, Collect("out")).build() + + async def consume() -> List[Any]: + return [e async for e in wf.run_stream("abc")] + + events = run(consume()) + assert events[0].type == "started" and events[-1].type == "status" + assert events[-1].data["status"] == COMPLETED + assert [e.data for e in events if e.type == "output"] == ["ABC"] + + +def test_run_sync_works_inside_a_running_event_loop(): + up = Upper("up") + wf = WorkflowBuilder(start_executor=up).add_edge(up, Collect("out")).build() + + async def inside() -> Any: + return wf.run_sync("abc") + + assert run(inside()).outputs == ["ABC"] + + +# ── governance ────────────────────────────────────────────────────────────────────────────── + +def test_governed_run_is_opened_and_closed_in_the_task_ledger(tmp_path): + config = governed(tmp_path) + up = Upper("up") + wf = WorkflowBuilder(name="gov", start_executor=up, governance=config).add_edge(up, Collect("out")).build() + result = wf.run_sync("summarise the notes") + assert result.status == COMPLETED + opened, closed = entries(config) + assert opened["kind"] == "task_open" and opened["context"]["kind"] == "workflow" + assert closed["status"] == "SUCCESS" and closed["run_id"] == result.run_id + usage = closed["usage"]["workflow"] + assert usage["name"] == "gov" and usage["supersteps"] == 2 and usage["graph_signature"] == wf.graph_signature + assert result.governance["evidence"] == [{"executor_id": "out", "decision": "ACCEPT", "findings": 0}] + assert TaskLedger(config.resolved_ledger_path()).verify()["intact"] + + +def test_governed_run_blocks_critical_input_before_any_executor(tmp_path): + seen = [] + + @executor(id="never") + async def never(text: str, ctx: WorkflowContext) -> None: + seen.append(text) + + config = governed(tmp_path) + wf = WorkflowBuilder(start_executor=never, governance=config).build() + result = wf.run_sync("rm -rf / on the production server and push --force to main") + assert result.status == BLOCKED and seen == [] + assert entries(config)[-1]["status"] == "BLOCKED" + + +def test_governed_run_needs_its_ledger(tmp_path): + (tmp_path / "not_a_dir").write_text("a file where the ledger's directory should be") + config = governed(tmp_path, ledger_path=str(tmp_path / "not_a_dir" / "task_runs.jsonl")) + wf = WorkflowBuilder(start_executor=Upper("up"), governance=config).build() + with pytest.raises(WorkflowGovernanceError, match="ledger_unavailable"): + wf.run_sync("hello") + + +def test_governed_run_charges_one_budget_step_per_superstep(tmp_path): + class Loop(Executor): + @handler + async def go(self, n: int, ctx: WorkflowContext) -> None: + await ctx.send_message(n + 1) + + config = governed(tmp_path, budget={"max_steps": 3}) + a, b = Loop("a"), Loop("b") + wf = WorkflowBuilder(start_executor=a, governance=config).add_edge(a, b).add_edge(b, a).build() + result = wf.run_sync(0) + assert result.status == STOPPED + assert entries(config)[-1]["status"] == "STOPPED_BUDGET" + assert entries(config)[-1]["usage"]["workflow"]["supersteps"] == 3 + + +def test_text_outputs_go_through_the_evidence_firewall(tmp_path): + @executor(id="claims") + async def claims(text: str, ctx: WorkflowContext) -> None: + await ctx.yield_output("All tests passed and the fidelity was measured at 0.999.") + + config = governed(tmp_path) + result = WorkflowBuilder(start_executor=claims, governance=config).build().run_sync("report") + (finding,) = result.governance["evidence"] + assert finding["decision"] != "ACCEPT" + assert result.outputs == ["All tests passed and the fidelity was measured at 0.999."] # flagged, not dropped + + +def test_state_fields_are_checkpointed_restored_and_reset_per_run(): + class Counter(Executor): + state_fields = ("count",) + + def __init__(self, id: str) -> None: + super().__init__(id) + self.count = 0 + + @handler + async def go(self, text: str, ctx: WorkflowContext) -> None: + self.count += 1 + await ctx.request_info(Approval(f"{text} #{self.count}"), bool) + + @response_handler + async def done(self, request: Approval, ok: bool, ctx: WorkflowContext) -> None: + await ctx.yield_output(request.action) + + storage = InMemoryCheckpointStorage() + first = WorkflowBuilder(name="count", start_executor=Counter("c"), checkpoint_storage=storage).build() + paused = first.run_sync("a") + assert paused.pending_requests[0].data == Approval("a #1") + fresh_executor = Counter("c") + fresh = WorkflowBuilder(name="count", start_executor=fresh_executor, checkpoint_storage=storage).build() + rid = paused.pending_requests[0].request_id + assert fresh.run_sync(checkpoint_id=paused.checkpoint_id, responses={rid: True}).outputs == ["a #1"] + assert fresh_executor.count == 1 # restored from the checkpoint + again = fresh.run_sync("b") # a new run starts from the first value again + assert again.pending_requests[0].data == Approval("b #1")