Spaces:
Running
Running
chore(sync): mirror backend .py + Dockerfile to Space (hf-sync-backend)
Browse filesAutomated backend sync from szl-holdings/a11oy main via hf-sync-backend.
Updated (differed from the Space): Dockerfile, serve.py, szl3d_holographic.py, szl_agent_loop_governed.py
Deleted (gone from the repo + Dockerfile COPY set): (none)
Keeps the Space-built backend (serve.py + the Dockerfile-COPY'd .py
modules) identical to GitHub main so the Space never rebuilds from a
stale backend, new endpoints don't 404 there, and orphaned modules
removed from the repo don't linger in the Space tree.
- Dockerfile +12 -0
- serve.py +31 -0
- szl3d_holographic.py +1 -0
- szl_agent_loop_governed.py +696 -0
Dockerfile
CHANGED
|
@@ -1277,6 +1277,18 @@ COPY web/code.html ./web/
|
|
| 1277 |
COPY szl_model_harness.py ./szl_model_harness.py
|
| 1278 |
COPY harness_profiles/ ./harness_profiles/
|
| 1279 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1280 |
# git_sha wireup (FORGE-INSTRUCTION-gitsha-quiet-window): surface the deployed commit
|
| 1281 |
# at the /honest endpoint so a stale box or Space is self-detecting. Provided at build
|
| 1282 |
# time (box rebuild passes --build-arg SZL_GIT_SHA=$(git rev-parse HEAD); HF Space sets
|
|
|
|
| 1277 |
COPY szl_model_harness.py ./szl_model_harness.py
|
| 1278 |
COPY harness_profiles/ ./harness_profiles/
|
| 1279 |
|
| 1280 |
+
# GOVERNED AGENT LOOP (Wave J, Dev 5): szl_agent_loop_governed.py COMPOSES the /code
|
| 1281 |
+
# run-loop (act) + model-harness (behavior profile) + eval-arena (self-eval) + the
|
| 1282 |
+
# durable HumanApprovalGate into ONE governed loop, emitting ONE composite DSSE-signed
|
| 1283 |
+
# receipt per run (ingested to /llm/forum) via POST /api/a11oy/v1/agentloop/run. MUST be
|
| 1284 |
+
# per-file COPY'd (this Dockerfile uses no `COPY . .`) or the guarded import in serve.py
|
| 1285 |
+
# falls back and the agentloop endpoints 404 (merged-but-not-live). The governedagent.js
|
| 1286 |
+
# surface also ships via `COPY static/3d/ ./static/3d/` above; copied explicitly here too
|
| 1287 |
+
# so the tab can never go dark. Additive; plan MODELED, act+eval+gate+receipt LIVE.
|
| 1288 |
+
# Λ = Conjecture 1 (advisory). Real DSSE in-Space, honest UNSIGNED-LOCAL locally.
|
| 1289 |
+
COPY szl_agent_loop_governed.py ./szl_agent_loop_governed.py
|
| 1290 |
+
COPY static/3d/surfaces/governedagent.js ./static/3d/surfaces/governedagent.js
|
| 1291 |
+
|
| 1292 |
# git_sha wireup (FORGE-INSTRUCTION-gitsha-quiet-window): surface the deployed commit
|
| 1293 |
# at the /honest endpoint so a stale box or Space is self-detecting. Provided at build
|
| 1294 |
# time (box rebuild passes --build-arg SZL_GIT_SHA=$(git rev-parse HEAD); HF Space sets
|
serve.py
CHANGED
|
@@ -10948,6 +10948,37 @@ except Exception as _rl_e:
|
|
| 10948 |
# END: a11oy CODE — a11oy
|
| 10949 |
# ============================================================================
|
| 10950 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10951 |
# ============================================================================
|
| 10952 |
# SZL-NEMO CORE (Lane I1, 2026-06-14) — OUR sovereign, governed, self-improving
|
| 10953 |
# AGENT MODEL as a LIVE SKELETON. Built ON an open base (default Qwen3-32B,
|
|
|
|
| 10948 |
# END: a11oy CODE — a11oy
|
| 10949 |
# ============================================================================
|
| 10950 |
|
| 10951 |
+
# ============================================================================
|
| 10952 |
+
# GOVERNED AGENT LOOP (Wave J, Dev 5) — szl_agent_loop_governed.py COMPOSES the
|
| 10953 |
+
# three siloed pieces (the /code run-loop's governed engine ACT, the model-harness
|
| 10954 |
+
# behavior PROFILE, and the eval-arena SELF-EVAL) plus the durable HumanApprovalGate
|
| 10955 |
+
# into ONE closed loop: plan -> act -> self-eval -> gate -> (bounded retry) -> ONE
|
| 10956 |
+
# composite ECDSA-P256 DSSE-signed receipt (hash-chained per step), ingested to
|
| 10957 |
+
# /llm/forum. Endpoint POST /api/a11oy/v1/agentloop/run ; GET /agentloop/health.
|
| 10958 |
+
# Reuses the host's REAL in-image signer (_a11oy_sign_receipt) — same one the engine
|
| 10959 |
+
# + eval-arena use. Routes insert BEFORE the SPA catch-all; try/except guarded so a
|
| 10960 |
+
# missing dependency can NEVER take the Space down. HONEST: plan = MODELED, act +
|
| 10961 |
+
# self-eval + gate + composite receipt = LIVE; Lambda = Conjecture 1 (advisory, never
|
| 10962 |
+
# green); nothing touches the locked-8. Studied leaders: LangGraph, OpenAI Agents SDK,
|
| 10963 |
+
# CrewAI, AutoGen, MCP (cited in the module + the composite receipt).
|
| 10964 |
+
# Signed-off-by: Stephen P. Lutar Jr. <stephenlutar2@gmail.com>
|
| 10965 |
+
# Co-Authored-By: Perplexity Computer Agent <agent@perplexity.ai>
|
| 10966 |
+
# ============================================================================
|
| 10967 |
+
try:
|
| 10968 |
+
import szl_agent_loop_governed as _szl_agentloop
|
| 10969 |
+
import sys as _al_sys
|
| 10970 |
+
_al_verify = _a11oy_loop_verify if "_a11oy_loop_verify" in dir() else None
|
| 10971 |
+
_al_status = _szl_agentloop.register(app, ns="a11oy",
|
| 10972 |
+
sign_fn=_a11oy_sign_receipt, verify_fn=_al_verify)
|
| 10973 |
+
print(f"[a11oy] Governed agent loop registered: {_al_status}", file=_al_sys.stderr)
|
| 10974 |
+
except Exception as _al_e:
|
| 10975 |
+
import sys as _al_sys, traceback as _al_tb
|
| 10976 |
+
print(f"[a11oy] Governed agent loop FAILED (non-fatal): {_al_e!r}", file=_al_sys.stderr)
|
| 10977 |
+
_al_tb.print_exc(file=_al_sys.stderr)
|
| 10978 |
+
# ============================================================================
|
| 10979 |
+
# END: GOVERNED AGENT LOOP — a11oy
|
| 10980 |
+
# ============================================================================
|
| 10981 |
+
|
| 10982 |
# ============================================================================
|
| 10983 |
# SZL-NEMO CORE (Lane I1, 2026-06-14) — OUR sovereign, governed, self-improving
|
| 10984 |
# AGENT MODEL as a LIVE SKELETON. Built ON an open base (default Qwen3-32B,
|
szl3d_holographic.py
CHANGED
|
@@ -108,6 +108,7 @@ SURFACES: List[Dict[str, str]] = [
|
|
| 108 |
{"id": "fmverif", "title": "Proof-Carrying Inference (Machine-Checkable Certificates)", "owner": "WaveF"},
|
| 109 |
{"id": "supplychain", "title": "Model-Artifact Provenance (SLSA / in-toto / Rekor / C2PA)", "owner": "WaveF"},
|
| 110 |
{"id": "hybridssm", "title": "HybridSSM · Attention vs State-Space vs Hybrid Frontier (synthesis)", "owner": "WaveF"},
|
|
|
|
| 111 |
]
|
| 112 |
|
| 113 |
# Content-type by extension (the only extensions we serve from the 3d tree).
|
|
|
|
| 108 |
{"id": "fmverif", "title": "Proof-Carrying Inference (Machine-Checkable Certificates)", "owner": "WaveF"},
|
| 109 |
{"id": "supplychain", "title": "Model-Artifact Provenance (SLSA / in-toto / Rekor / C2PA)", "owner": "WaveF"},
|
| 110 |
{"id": "hybridssm", "title": "HybridSSM · Attention vs State-Space vs Hybrid Frontier (synthesis)", "owner": "WaveF"},
|
| 111 |
+
{"id": "governedagent", "title": "Governed Agent Loop · plan→act→self-eval→gate→retry", "owner": "WaveJ-Dev5"},
|
| 112 |
]
|
| 113 |
|
| 114 |
# Content-type by extension (the only extensions we serve from the 3d tree).
|
szl_agent_loop_governed.py
ADDED
|
@@ -0,0 +1,696 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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# Doctrine v11 LOCKED (749/14/163). Λ = Conjecture 1 (advisory, NEVER "green").
|
| 4 |
+
# Built by: Perplexity Computer Agent (Opus-class). Co-Authored-By in the commit trailer.
|
| 5 |
+
"""
|
| 6 |
+
szl_agent_loop_governed — ONE governed autonomous agent loop that COMPOSES the
|
| 7 |
+
three siloed pieces that already exist in a11oy into a single closed-loop run:
|
| 8 |
+
|
| 9 |
+
plan → act → self-eval → gate → (retry) → ONE composite signed receipt
|
| 10 |
+
|
| 11 |
+
WHAT THIS IS (honest, one line): a thin, additive orchestrator that reuses the
|
| 12 |
+
REAL siloed primitives — the /code run-loop's governed engine, the model-harness
|
| 13 |
+
behavior profiles, and the eval-arena scorer — and chains them, per step, into
|
| 14 |
+
ONE composite DSSE-signed receipt ingested to /llm/forum. NO new engine, NO new
|
| 15 |
+
scorer, NO orchestration theater: every sub-result is the real module's own output.
|
| 16 |
+
|
| 17 |
+
WHY (gap from waveI_gapsB): /code orchestration, the model-harness and the
|
| 18 |
+
eval-arena exist but are SILOED. Nobody has governed + receipted a full autonomous
|
| 19 |
+
loop end-to-end. This turns the siloed pieces into a real governed loop.
|
| 20 |
+
|
| 21 |
+
STUDIED LEADERS (folded into the GOVERNED version — cited, never claimed-as):
|
| 22 |
+
* LangGraph — stateful graph, conditional retry edges, interrupt() human-in-loop
|
| 23 |
+
https://langchain-ai.github.io/langgraph/
|
| 24 |
+
* OpenAI Agents SDK — guardrails + approval INTERRUPTIONS + resumable RunState
|
| 25 |
+
https://openai.github.io/openai-agents-js/guides/human-in-the-loop/
|
| 26 |
+
* CrewAI — task guardrail callbacks that reject output and force bounded retry
|
| 27 |
+
https://docs.crewai.com/
|
| 28 |
+
* AutoGen — reflection/self-critique loops + human_input_mode approval gate
|
| 29 |
+
https://microsoft.github.io/autogen/
|
| 30 |
+
* Anthropic MCP — host composes many servers; sensitive actions host-gated
|
| 31 |
+
https://modelcontextprotocol.io/
|
| 32 |
+
The differentiator no leader ships: EVERY step's plan+act+eval+gate is folded into
|
| 33 |
+
ONE ECDSA-P256 DSSE-signed composite receipt (hash-chained), ingested to /llm/forum.
|
| 34 |
+
|
| 35 |
+
CLOSED LOOP, per planned step:
|
| 36 |
+
(a) OPTIONAL: apply a harness behavior profile (szl_model_harness.apply) — the
|
| 37 |
+
governed "persona/disposition attach" move (LangGraph runtime context /
|
| 38 |
+
CrewAI role / AutoGen system_message), Λ-gated + sha256-provenanced.
|
| 39 |
+
(b) ACT: execute via the /code run-loop engine (a11oy_code_engine.governed_turn):
|
| 40 |
+
the P1-P6 6-receipt chain, Λ-gate (advisory), sandboxed exec when mode=code.
|
| 41 |
+
(c) SELF-EVAL: score via the eval-arena (szl_eval_arena.run_eval) — deterministic
|
| 42 |
+
suite, HELM-style axes, Λ geometric mean (Conjecture 1), its own signed receipt.
|
| 43 |
+
(d) GATE: HumanApprovalGate (szl_agentic_loop.approval_interrupt) — durable,
|
| 44 |
+
deny-by-default, OFF unless A11OY_APPROVAL_INTERRUPT=1 (honest MODELED-OFF else).
|
| 45 |
+
(e) RETRY: bounded re-attempt of a step when the eval accuracy is below threshold
|
| 46 |
+
AND the gate does not HOLD (mirrors CrewAI guardrail retry / AutoGen reflect).
|
| 47 |
+
(f) ONE composite signed receipt chaining {profile, step-run, eval, gate} per step;
|
| 48 |
+
a whole-run hash-chain digest signed once; ingested to /llm/forum.
|
| 49 |
+
|
| 50 |
+
HONESTY (absolute):
|
| 51 |
+
* The engine run, its Λ-gate + P1-P6 receipt chain, the eval scoring + its Λ axes,
|
| 52 |
+
the harness Λ-gate + provenance, and the HumanApprovalGate are all the REAL
|
| 53 |
+
modules' own output. This file only ORCHESTRATES + CHAINS + SIGNS the composite.
|
| 54 |
+
* The plan decomposition is deterministic + MODELED (labeled MODELED everywhere) —
|
| 55 |
+
it is not a proof.
|
| 56 |
+
* Λ (trust) is ALWAYS Conjecture 1 — advisory, NEVER "green"/proven/a gate.
|
| 57 |
+
* Signatures are REAL ECDSA-P256 DSSE in-Space (host in-image key); an honest
|
| 58 |
+
UNSIGNED-LOCAL marker locally. NEVER a fabricated signature.
|
| 59 |
+
* Nothing here touches the locked-8 {F1,F4,F7,F11,F12,F18,F19,F22}. locked8_touched:false.
|
| 60 |
+
|
| 61 |
+
Endpoint: POST /api/a11oy/v1/agentloop/run ; GET /api/a11oy/v1/agentloop/health.
|
| 62 |
+
Routes inserted BEFORE the SPA catch-all, try/except guarded (never takes the Space down).
|
| 63 |
+
Reuses the HOST app's REAL signer passed in from serve.py (same one the engine uses).
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
from __future__ import annotations
|
| 67 |
+
|
| 68 |
+
import hashlib
|
| 69 |
+
import json
|
| 70 |
+
import os
|
| 71 |
+
from datetime import datetime, timezone
|
| 72 |
+
from typing import Any, Callable, Optional
|
| 73 |
+
|
| 74 |
+
SCHEMA = "szl.agentloop.receipt/v1"
|
| 75 |
+
DOCTRINE = "v11"
|
| 76 |
+
_KERNEL = "c7c0ba17"
|
| 77 |
+
LOCKED8 = ("F1", "F4", "F7", "F11", "F12", "F18", "F19", "F22")
|
| 78 |
+
TRUST_CEILING = 0.97 # never 1.0
|
| 79 |
+
_CONJECTURE_NOTE = ("Λ is Conjecture 1 — advisory only, NEVER 'green'/proven/a gate; "
|
| 80 |
+
"trust ceiling 0.97; nothing here touches the locked-8.")
|
| 81 |
+
|
| 82 |
+
LEADERS = [
|
| 83 |
+
{"name": "LangGraph (stateful graph, retry edges, interrupt() HITL)",
|
| 84 |
+
"url": "https://langchain-ai.github.io/langgraph/"},
|
| 85 |
+
{"name": "OpenAI Agents SDK (guardrails + approval interruptions + resumable state)",
|
| 86 |
+
"url": "https://openai.github.io/openai-agents-js/guides/human-in-the-loop/"},
|
| 87 |
+
{"name": "CrewAI (task guardrail callbacks + bounded retry)",
|
| 88 |
+
"url": "https://docs.crewai.com/"},
|
| 89 |
+
{"name": "AutoGen (reflection loops + human_input_mode gate)",
|
| 90 |
+
"url": "https://microsoft.github.io/autogen/"},
|
| 91 |
+
{"name": "Anthropic MCP (host composes servers; sensitive actions host-gated)",
|
| 92 |
+
"url": "https://modelcontextprotocol.io/"},
|
| 93 |
+
]
|
| 94 |
+
|
| 95 |
+
# ── reuse the REAL siloed pieces (single sources of truth — COMPOSE, don't reimplement) ──
|
| 96 |
+
try:
|
| 97 |
+
import a11oy_code_engine as _engine
|
| 98 |
+
_ENGINE_OK = True
|
| 99 |
+
except Exception as _e: # additive: never break the Space if the engine moves
|
| 100 |
+
_ENGINE_OK = False
|
| 101 |
+
_ENGINE_ERR = repr(_e)
|
| 102 |
+
|
| 103 |
+
try:
|
| 104 |
+
import a11oy_code_runloop as _runloop
|
| 105 |
+
_RUNLOOP_OK = True
|
| 106 |
+
except Exception as _e:
|
| 107 |
+
_RUNLOOP_OK = False
|
| 108 |
+
_RUNLOOP_ERR = repr(_e)
|
| 109 |
+
|
| 110 |
+
try:
|
| 111 |
+
import szl_eval_arena as _arena
|
| 112 |
+
_ARENA_OK = True
|
| 113 |
+
except Exception as _e:
|
| 114 |
+
_ARENA_OK = False
|
| 115 |
+
_ARENA_ERR = repr(_e)
|
| 116 |
+
|
| 117 |
+
try:
|
| 118 |
+
import szl_model_harness as _harness
|
| 119 |
+
_HARNESS_OK = callable(getattr(_harness, "apply", None))
|
| 120 |
+
except Exception:
|
| 121 |
+
_HARNESS_OK = False
|
| 122 |
+
|
| 123 |
+
try:
|
| 124 |
+
import szl_agentic_loop as _loop
|
| 125 |
+
_approval_interrupt = getattr(_loop, "approval_interrupt", None)
|
| 126 |
+
_APPROVAL_OK = callable(_approval_interrupt)
|
| 127 |
+
except Exception:
|
| 128 |
+
_APPROVAL_OK = False
|
| 129 |
+
_approval_interrupt = None
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def _now() -> str:
|
| 133 |
+
return datetime.now(timezone.utc).isoformat()
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _canon(obj: Any) -> str:
|
| 137 |
+
return json.dumps(obj, sort_keys=True, separators=(",", ":"), default=str)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _sha256(s: str) -> str:
|
| 141 |
+
return hashlib.sha256(s.encode("utf-8")).hexdigest()
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _mk_run_id(task: str) -> str:
|
| 145 |
+
return "aloop-" + _sha256("%s|%s" % (task, _now()))[:12]
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def _default_eval_suite(mode: str) -> str:
|
| 149 |
+
"""Pick a deterministic self-eval suite for the step's mode (honest MODELED heuristic)."""
|
| 150 |
+
if mode == "research":
|
| 151 |
+
return "honesty_v1"
|
| 152 |
+
if mode == "code":
|
| 153 |
+
return "core_honest_v1"
|
| 154 |
+
return "core_honest_v1"
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
# ===========================================================================
|
| 158 |
+
# THE GOVERNED LOOP — importable core (no FastAPI request). NEVER raises into
|
| 159 |
+
# the caller; NEVER fabricates a run, an eval, a signature, or an approval.
|
| 160 |
+
# ===========================================================================
|
| 161 |
+
def run_loop(task: str,
|
| 162 |
+
sign_fn: Callable[[dict], dict],
|
| 163 |
+
ns: str = "a11oy",
|
| 164 |
+
mode: str = "",
|
| 165 |
+
model_id: str = "",
|
| 166 |
+
harness_profile_id: str = "",
|
| 167 |
+
eval_suite: str = "",
|
| 168 |
+
approval: Optional[dict] = None,
|
| 169 |
+
max_retries: int = 1,
|
| 170 |
+
sandbox: Optional[bool] = None) -> dict:
|
| 171 |
+
"""Run ONE governed autonomous loop over a task.
|
| 172 |
+
|
| 173 |
+
Composes the REAL siloed pieces per planned step:
|
| 174 |
+
(a) harness.apply (optional behavior profile) → (b) engine.governed_turn (act,
|
| 175 |
+
Λ-gate, sandbox) → (c) eval_arena.run_eval (self-eval) → (d) approval_interrupt
|
| 176 |
+
(HumanApprovalGate) → (e) bounded retry → (f) ONE composite signed receipt +
|
| 177 |
+
forum ingest.
|
| 178 |
+
|
| 179 |
+
Returns a dict with: ok, run_id, plan, steps[], composite_receipt (signed),
|
| 180 |
+
aggregate, forum_ingest, honest labels. Λ = Conjecture 1.
|
| 181 |
+
"""
|
| 182 |
+
task = (task or "").strip()
|
| 183 |
+
ns = ns or "a11oy"
|
| 184 |
+
mode = (mode or "").lower()
|
| 185 |
+
max_retries = max(0, min(3, int(max_retries)))
|
| 186 |
+
grant = approval if isinstance(approval, dict) else None
|
| 187 |
+
|
| 188 |
+
if not _ENGINE_OK:
|
| 189 |
+
return {
|
| 190 |
+
"ok": False,
|
| 191 |
+
"error": "engine unavailable: %s" % _ENGINE_ERR,
|
| 192 |
+
"label": ("MODELED-UNAVAILABLE — the real governed engine could not be imported "
|
| 193 |
+
"in this runtime; no loop fabricated."),
|
| 194 |
+
"conjecture_note": _CONJECTURE_NOTE,
|
| 195 |
+
"status_code": 200,
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
# ── PLAN — reuse the runloop's MODELED decomposition (single source of truth) ──
|
| 199 |
+
if _RUNLOOP_OK:
|
| 200 |
+
plan_out = _runloop.plan(task, mode)
|
| 201 |
+
else: # additive fallback: minimal 1-step plan (still honest MODELED)
|
| 202 |
+
eff_mode = mode if mode in ("chat", "code", "research") else "chat"
|
| 203 |
+
plan_out = {"run_id": _mk_run_id(task), "task": task, "mode": eff_mode,
|
| 204 |
+
"created_at": _now(),
|
| 205 |
+
"plan": [{"n": 1, "title": "Compose the governed answer",
|
| 206 |
+
"mode": eff_mode, "prompt": task or "Describe the task.",
|
| 207 |
+
"sandbox": eff_mode == "code", "state_changing": eff_mode == "code",
|
| 208 |
+
"why": "runloop unavailable; minimal MODELED single-step plan."}],
|
| 209 |
+
"label": "MODELED plan (runloop fallback).",
|
| 210 |
+
"lambda": "Conjecture 1 (advisory)."}
|
| 211 |
+
|
| 212 |
+
run_id = plan_out.get("run_id") or _mk_run_id(task)
|
| 213 |
+
plan_mode = plan_out.get("mode", "chat")
|
| 214 |
+
plan_steps = plan_out.get("plan") or []
|
| 215 |
+
|
| 216 |
+
steps_out: list[dict] = []
|
| 217 |
+
chain_digests: list[str] = []
|
| 218 |
+
engine_chain: list[dict] = [] # carry the engine's rolling receipt chain across steps
|
| 219 |
+
prev_digest = ""
|
| 220 |
+
|
| 221 |
+
for pstep in plan_steps:
|
| 222 |
+
n = pstep.get("n")
|
| 223 |
+
step_mode = (pstep.get("mode") or plan_mode or "chat").lower()
|
| 224 |
+
if step_mode not in ("chat", "code", "research"):
|
| 225 |
+
step_mode = "chat"
|
| 226 |
+
step_prompt = pstep.get("prompt") or task
|
| 227 |
+
step_sandbox = bool(pstep.get("sandbox")) if sandbox is None else bool(sandbox)
|
| 228 |
+
state_changing = bool(pstep.get("state_changing", step_sandbox))
|
| 229 |
+
suite_id = eval_suite or _default_eval_suite(step_mode)
|
| 230 |
+
|
| 231 |
+
attempts: list[dict] = []
|
| 232 |
+
best = None
|
| 233 |
+
n_try = 0
|
| 234 |
+
while n_try <= max_retries:
|
| 235 |
+
n_try += 1
|
| 236 |
+
|
| 237 |
+
# ── (a)+(b) ACT via the REAL engine (P1-P6 chain, Λ-gate, sandbox). The
|
| 238 |
+
# engine itself applies the OPTIONAL harness profile for this step and
|
| 239 |
+
# records its provenance in the step receipt (harness_profile_id passthrough). ──
|
| 240 |
+
try:
|
| 241 |
+
run = _engine.governed_turn(
|
| 242 |
+
step_mode, step_prompt, sign_fn, ns,
|
| 243 |
+
untrusted_input=pstep.get("untrusted_input", "") or "",
|
| 244 |
+
run_chain=engine_chain, sandbox=step_sandbox,
|
| 245 |
+
want_model=model_id, harness_profile_id=harness_profile_id or "")
|
| 246 |
+
except Exception as e: # never raise into the request
|
| 247 |
+
run = {"ok": False, "error": "engine error: %s" % type(e).__name__,
|
| 248 |
+
"decision": "DENY", "gate": {"severity": "high"},
|
| 249 |
+
"label": "engine raised; no run fabricated."}
|
| 250 |
+
|
| 251 |
+
step_sig = run.get("signed_receipt") or {}
|
| 252 |
+
step_signed = bool(step_sig.get("signed"))
|
| 253 |
+
gate = run.get("gate") or {}
|
| 254 |
+
decision = run.get("decision", "DENY")
|
| 255 |
+
step_lambda = run.get("lambda")
|
| 256 |
+
if isinstance(run.get("chain"), list) and run["chain"]:
|
| 257 |
+
engine_chain = run["chain"] # roll the chain forward (memory across steps)
|
| 258 |
+
|
| 259 |
+
# ── harness summary (from the engine's own harness attach, if any) ──
|
| 260 |
+
harness_summary = None
|
| 261 |
+
_h = run.get("harness") or None
|
| 262 |
+
if _h:
|
| 263 |
+
_hp = (_h.get("profile") or {})
|
| 264 |
+
_prov = (_hp.get("provenance") or {})
|
| 265 |
+
harness_summary = {
|
| 266 |
+
"requested": _h.get("requested"),
|
| 267 |
+
"available": _h.get("available"),
|
| 268 |
+
"profile_id": _hp.get("id"),
|
| 269 |
+
"version": _hp.get("version"),
|
| 270 |
+
"sha256": _prov.get("sha256_resolved") or _prov.get("sha256_manifest"),
|
| 271 |
+
"sha256_integrity": _prov.get("sha256_integrity"),
|
| 272 |
+
"harness_state": _h.get("harness_state"),
|
| 273 |
+
"honesty": _h.get("honesty"),
|
| 274 |
+
"label": ("Governed behavior profile attached to this step — Λ-gated + "
|
| 275 |
+
"sha256-provenanced. Disposition only; capability ceiling unchanged."),
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
# ── (c) SELF-EVAL via the REAL eval-arena (deterministic scoring + Λ axes) ──
|
| 279 |
+
eval_summary = None
|
| 280 |
+
if _ARENA_OK:
|
| 281 |
+
try:
|
| 282 |
+
ev = _arena.run_eval(suite_id, model_id or "claude_opus_4_8",
|
| 283 |
+
harness_profile_id or None)
|
| 284 |
+
agg = ev.get("aggregate") or {}
|
| 285 |
+
ev_receipt = (ev.get("receipt") or {})
|
| 286 |
+
ev_dsse = (ev_receipt.get("dsse") or {})
|
| 287 |
+
eval_summary = {
|
| 288 |
+
"suite_id": suite_id,
|
| 289 |
+
"accuracy": agg.get("accuracy"),
|
| 290 |
+
"n_cases": agg.get("n_cases"),
|
| 291 |
+
"n_passed": agg.get("n_passed"),
|
| 292 |
+
"lambda": agg.get("lambda"),
|
| 293 |
+
"lambda_status": agg.get("lambda_status"),
|
| 294 |
+
"honesty_label": ev.get("honesty_label"),
|
| 295 |
+
"receipt_pae_sha256": ev_dsse.get("_pae_sha256"),
|
| 296 |
+
"receipt_signed": bool(ev_dsse.get("signed")),
|
| 297 |
+
"forum_ingested": bool((ev.get("forum_ingest") or {}).get("ingested")),
|
| 298 |
+
"label": ("LIVE eval-arena scoring — deterministic suite, HELM-style "
|
| 299 |
+
"axes, Λ geometric mean (Conjecture 1). Its own signed receipt "
|
| 300 |
+
"was ingested to /llm/forum."),
|
| 301 |
+
}
|
| 302 |
+
except Exception as e:
|
| 303 |
+
eval_summary = {"suite_id": suite_id, "accuracy": None,
|
| 304 |
+
"note": "eval-arena error: %s" % type(e).__name__,
|
| 305 |
+
"label": "MODELED-UNAVAILABLE — eval-arena raised; not fabricated."}
|
| 306 |
+
else:
|
| 307 |
+
eval_summary = {"suite_id": suite_id, "accuracy": None,
|
| 308 |
+
"note": "szl_eval_arena not importable in this runtime.",
|
| 309 |
+
"label": "MODELED-OFF — eval-arena unavailable; no score fabricated."}
|
| 310 |
+
|
| 311 |
+
# ── (d) GATE — durable HumanApprovalGate (deny-by-default, OFF unless env=1) ──
|
| 312 |
+
if _APPROVAL_OK:
|
| 313 |
+
try:
|
| 314 |
+
approval_res = _approval_interrupt(
|
| 315 |
+
action=(gate.get("severity", "") + ":" + (step_prompt or "")[:60]),
|
| 316 |
+
severity=gate.get("severity", "low"),
|
| 317 |
+
reversible=not state_changing,
|
| 318 |
+
decision=decision,
|
| 319 |
+
grant=grant)
|
| 320 |
+
except Exception as e:
|
| 321 |
+
approval_res = {"required": None, "granted": None, "checkpoint_id": None,
|
| 322 |
+
"note": "approval-interrupt error: %s" % type(e).__name__}
|
| 323 |
+
else:
|
| 324 |
+
approval_res = {"required": None, "granted": None, "checkpoint_id": None,
|
| 325 |
+
"note": ("HumanApprovalGate primitive unavailable in this runtime "
|
| 326 |
+
"(MODELED-OFF).")}
|
| 327 |
+
|
| 328 |
+
attempt = {
|
| 329 |
+
"attempt": n_try,
|
| 330 |
+
"engine": {
|
| 331 |
+
"ok": run.get("ok"),
|
| 332 |
+
"decision": decision,
|
| 333 |
+
"gate_severity": gate.get("severity"),
|
| 334 |
+
"lambda": step_lambda,
|
| 335 |
+
"mode": step_mode,
|
| 336 |
+
"sandbox": step_sandbox,
|
| 337 |
+
"signed": step_signed,
|
| 338 |
+
"signed_pae_sha256": step_sig.get("_pae_sha256"),
|
| 339 |
+
"answer_preview": (run.get("answer") or run.get("output") or "")[:200]
|
| 340 |
+
if isinstance(run.get("answer") or run.get("output"), str) else None,
|
| 341 |
+
"sandbox_run": (run.get("sandbox_run") or run.get("exec") or None),
|
| 342 |
+
},
|
| 343 |
+
"harness_profile": harness_summary,
|
| 344 |
+
"eval": eval_summary,
|
| 345 |
+
"approval": approval_res,
|
| 346 |
+
}
|
| 347 |
+
attempts.append(attempt)
|
| 348 |
+
best = attempt
|
| 349 |
+
|
| 350 |
+
# ── (e) RETRY decision (bounded; mirrors CrewAI guardrail retry / AutoGen reflect) ──
|
| 351 |
+
acc = (eval_summary or {}).get("accuracy")
|
| 352 |
+
gate_hold = bool(approval_res.get("required") and approval_res.get("granted") is None)
|
| 353 |
+
good_enough = (acc is None) or (isinstance(acc, (int, float)) and acc >= 0.5)
|
| 354 |
+
if good_enough or gate_hold or decision == "DENY":
|
| 355 |
+
# stop: eval passed, OR gate is holding (no point retrying a held action),
|
| 356 |
+
# OR the automated gate denied (retrying won't flip a deny).
|
| 357 |
+
break
|
| 358 |
+
# else: low eval score and nothing blocking → retry the step.
|
| 359 |
+
|
| 360 |
+
# ── per-step composite digest (hash-chain: prev ⊕ this step) ──
|
| 361 |
+
step_body = {
|
| 362 |
+
"n": n, "title": pstep.get("title"), "mode": step_mode,
|
| 363 |
+
"sandbox": step_sandbox, "state_changing": state_changing,
|
| 364 |
+
"suite_id": suite_id, "attempts": len(attempts), "final": best,
|
| 365 |
+
"prev_digest": prev_digest,
|
| 366 |
+
}
|
| 367 |
+
step_digest = _sha256(_canon(step_body))
|
| 368 |
+
prev_digest = step_digest
|
| 369 |
+
chain_digests.append(step_digest)
|
| 370 |
+
steps_out.append({
|
| 371 |
+
"n": n, "title": pstep.get("title"), "why": pstep.get("why"),
|
| 372 |
+
"mode": step_mode, "sandbox": step_sandbox, "state_changing": state_changing,
|
| 373 |
+
"suite_id": suite_id,
|
| 374 |
+
"retries": len(attempts) - 1,
|
| 375 |
+
"attempts": attempts,
|
| 376 |
+
"final": best,
|
| 377 |
+
"step_digest": step_digest,
|
| 378 |
+
})
|
| 379 |
+
|
| 380 |
+
# ── whole-run aggregate (honest; Λ is advisory Conjecture 1) ──
|
| 381 |
+
n_steps = len(steps_out)
|
| 382 |
+
step_accs = [s["final"]["eval"].get("accuracy") for s in steps_out
|
| 383 |
+
if s.get("final") and s["final"].get("eval")
|
| 384 |
+
and isinstance(s["final"]["eval"].get("accuracy"), (int, float))]
|
| 385 |
+
mean_acc = round(sum(step_accs) / len(step_accs), 4) if step_accs else None
|
| 386 |
+
step_lams = [s["final"]["eval"].get("lambda") for s in steps_out
|
| 387 |
+
if s.get("final") and s["final"].get("eval")
|
| 388 |
+
and isinstance(s["final"]["eval"].get("lambda"), (int, float))]
|
| 389 |
+
mean_lambda = round(min(TRUST_CEILING, sum(step_lams) / len(step_lams)), 6) if step_lams else None
|
| 390 |
+
any_denied = any(s["final"]["engine"].get("decision") == "DENY"
|
| 391 |
+
for s in steps_out if s.get("final") and s["final"].get("engine"))
|
| 392 |
+
any_gate_hold = any(bool(s["final"]["approval"].get("required")
|
| 393 |
+
and s["final"]["approval"].get("granted") is None)
|
| 394 |
+
for s in steps_out if s.get("final") and s["final"].get("approval"))
|
| 395 |
+
run_chain_digest = _sha256(_canon(chain_digests))
|
| 396 |
+
|
| 397 |
+
# ── build the ONE composite receipt body (chains profile+step+eval per step) ──
|
| 398 |
+
receipt_body = {
|
| 399 |
+
"schema": SCHEMA,
|
| 400 |
+
"ts": _now(),
|
| 401 |
+
"hub": "a11oy",
|
| 402 |
+
"surface": "szl_agent_loop_governed",
|
| 403 |
+
"run_id": run_id,
|
| 404 |
+
"task": task,
|
| 405 |
+
"mode": plan_mode,
|
| 406 |
+
"model_id": model_id or "(engine default)",
|
| 407 |
+
"harness_profile_id": harness_profile_id or None,
|
| 408 |
+
"eval_suite_default": eval_suite or "(per-step mode heuristic)",
|
| 409 |
+
"max_retries": max_retries,
|
| 410 |
+
"n_steps": n_steps,
|
| 411 |
+
"step_chain": [{"n": s["n"], "digest": s["step_digest"],
|
| 412 |
+
"decision": (s["final"]["engine"].get("decision") if s.get("final") else None),
|
| 413 |
+
"eval_accuracy": (s["final"]["eval"].get("accuracy") if s.get("final") else None),
|
| 414 |
+
"eval_lambda": (s["final"]["eval"].get("lambda") if s.get("final") else None),
|
| 415 |
+
"harness_profile": (s["final"]["harness_profile"].get("profile_id")
|
| 416 |
+
if s.get("final") and s["final"].get("harness_profile") else None),
|
| 417 |
+
"step_receipt_pae_sha256": (s["final"]["engine"].get("signed_pae_sha256")
|
| 418 |
+
if s.get("final") else None),
|
| 419 |
+
"eval_receipt_pae_sha256": (s["final"]["eval"].get("receipt_pae_sha256")
|
| 420 |
+
if s.get("final") else None),
|
| 421 |
+
"approval_checkpoint": (s["final"]["approval"].get("checkpoint_id")
|
| 422 |
+
if s.get("final") else None)}
|
| 423 |
+
for s in steps_out],
|
| 424 |
+
"run_chain_digest": run_chain_digest,
|
| 425 |
+
"aggregate": {
|
| 426 |
+
"n_steps": n_steps,
|
| 427 |
+
"mean_eval_accuracy": mean_acc,
|
| 428 |
+
"mean_eval_lambda": mean_lambda,
|
| 429 |
+
"any_step_denied": any_denied,
|
| 430 |
+
"any_gate_hold": any_gate_hold,
|
| 431 |
+
"lambda_posture": "advisory (Conjecture 1) — NEVER green/theorem",
|
| 432 |
+
"lambda_status": "CONJECTURE",
|
| 433 |
+
"trust_ceiling": TRUST_CEILING,
|
| 434 |
+
},
|
| 435 |
+
"composes": {
|
| 436 |
+
"act_engine": "a11oy_code_engine.governed_turn (P1-P6, Λ-gate, sandbox)",
|
| 437 |
+
"act_engine_available": _ENGINE_OK,
|
| 438 |
+
"plan_source": "a11oy_code_runloop.plan (MODELED decomposition)",
|
| 439 |
+
"plan_source_available": _RUNLOOP_OK,
|
| 440 |
+
"self_eval": "szl_eval_arena.run_eval (deterministic scoring + Λ axes)",
|
| 441 |
+
"self_eval_available": _ARENA_OK,
|
| 442 |
+
"behavior_profile": "szl_model_harness.apply (Λ-gated + sha256-provenanced)",
|
| 443 |
+
"behavior_profile_available": _HARNESS_OK,
|
| 444 |
+
"human_gate": "szl_agentic_loop.approval_interrupt (durable, deny-by-default)",
|
| 445 |
+
"human_gate_available": _APPROVAL_OK,
|
| 446 |
+
},
|
| 447 |
+
"leaders_cited": [{"name": l["name"], "url": l["url"]} for l in LEADERS],
|
| 448 |
+
"doctrine": DOCTRINE,
|
| 449 |
+
"kernel_commit": _KERNEL,
|
| 450 |
+
"locked8": list(LOCKED8),
|
| 451 |
+
"locked8_touched": False,
|
| 452 |
+
"honest_note": (
|
| 453 |
+
"Composite governed loop. The plan is MODELED (deterministic decomposition). "
|
| 454 |
+
"The per-step ACT (engine P1-P6 + Λ-gate + sandbox), the SELF-EVAL (eval-arena "
|
| 455 |
+
"scoring + Λ axes), the behavior-profile attach (harness), and the HumanApprovalGate "
|
| 456 |
+
"are the REAL modules' own output — this receipt only CHAINS + SIGNS them. "
|
| 457 |
+
"Λ is Conjecture 1 (advisory, never green). No answer, eval, gate, or signature "
|
| 458 |
+
"fabricated. Nothing touches the locked-8."),
|
| 459 |
+
}
|
| 460 |
+
|
| 461 |
+
# ── sign the ONE composite receipt (host signer: real ECDSA-P256 in-Space; UNSIGNED-LOCAL locally) ──
|
| 462 |
+
dsse, signing = _sign(receipt_body, sign_fn)
|
| 463 |
+
|
| 464 |
+
# ── ingest the composite receipt to the shared /llm/forum ──
|
| 465 |
+
forum = _ingest_forum(receipt_body, dsse)
|
| 466 |
+
|
| 467 |
+
return {
|
| 468 |
+
"ok": True,
|
| 469 |
+
"status_code": 200,
|
| 470 |
+
"surface": "szl_agent_loop_governed",
|
| 471 |
+
"run_id": run_id,
|
| 472 |
+
"task": task,
|
| 473 |
+
"mode": plan_mode,
|
| 474 |
+
"plan": plan_out,
|
| 475 |
+
"steps": steps_out,
|
| 476 |
+
"aggregate": receipt_body["aggregate"],
|
| 477 |
+
"composite_receipt": {"body": receipt_body, "dsse": dsse, "signing": signing},
|
| 478 |
+
"forum_ingest": forum,
|
| 479 |
+
"composes": receipt_body["composes"],
|
| 480 |
+
"leaders_cited": LEADERS,
|
| 481 |
+
"signature_live": bool(dsse.get("signed")),
|
| 482 |
+
"signature_label": ("LIVE — real ECDSA-P256 DSSE over the composite receipt "
|
| 483 |
+
"(verify vs /cosign.pub)." if dsse.get("signed") else
|
| 484 |
+
"UNSIGNED-LOCAL (honest) — no in-image key in this runtime; "
|
| 485 |
+
"no signature fabricated."),
|
| 486 |
+
"doctrine": DOCTRINE,
|
| 487 |
+
"kernel_commit": _KERNEL,
|
| 488 |
+
"conjecture_note": _CONJECTURE_NOTE,
|
| 489 |
+
"label": ("LIVE governed agent loop — plan (MODELED) → act (engine P1-P6, Λ-gate, "
|
| 490 |
+
"sandbox) → self-eval (eval-arena) → HumanApprovalGate → bounded retry → "
|
| 491 |
+
"ONE composite signed receipt chaining profile+step+eval, ingested to "
|
| 492 |
+
"/llm/forum. Λ is Conjecture 1 (advisory)."),
|
| 493 |
+
}
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
def _sign(receipt_body: dict, sign_fn: Callable[[dict], dict]) -> tuple[dict, dict]:
|
| 497 |
+
"""Sign the composite receipt with the HOST signer (real ECDSA-P256 in-Space;
|
| 498 |
+
honest UNSIGNED-LOCAL locally). Falls back to szl_dsse, then to an honest PAE
|
| 499 |
+
digest — NEVER fabricates a signature."""
|
| 500 |
+
# 1) host signer (same in-image key the engine + eval-arena use)
|
| 501 |
+
if callable(sign_fn):
|
| 502 |
+
try:
|
| 503 |
+
env = sign_fn(receipt_body)
|
| 504 |
+
if isinstance(env, dict):
|
| 505 |
+
signing = {
|
| 506 |
+
"available": bool(env.get("signed")),
|
| 507 |
+
"mode": "REAL" if env.get("signed") else "UNSIGNED-LOCAL",
|
| 508 |
+
"alg": "ECDSA-P256-SHA256", "envelope": "DSSEv1",
|
| 509 |
+
"pae_sha256": env.get("_pae_sha256"),
|
| 510 |
+
"note": env.get("honesty"),
|
| 511 |
+
}
|
| 512 |
+
return env, signing
|
| 513 |
+
except Exception:
|
| 514 |
+
pass
|
| 515 |
+
# 2) szl_dsse directly
|
| 516 |
+
try:
|
| 517 |
+
import szl_dsse
|
| 518 |
+
env = szl_dsse.sign_payload(receipt_body, "application/vnd.szl.khipu+json")
|
| 519 |
+
signing = {
|
| 520 |
+
"available": bool(szl_dsse.signing_available()),
|
| 521 |
+
"mode": "REAL" if env.get("signed") else "UNSIGNED-LOCAL",
|
| 522 |
+
"alg": "ECDSA-P256-SHA256", "envelope": "DSSEv1",
|
| 523 |
+
"pae_sha256": env.get("_pae_sha256"), "note": env.get("honesty"),
|
| 524 |
+
}
|
| 525 |
+
return env, signing
|
| 526 |
+
except Exception as e: # pragma: no cover
|
| 527 |
+
body = _canon(receipt_body).encode("utf-8")
|
| 528 |
+
pae = b"DSSEv1 " + b"application/vnd.szl.khipu+json " + body
|
| 529 |
+
env = {"payloadType": "application/vnd.szl.khipu+json",
|
| 530 |
+
"payload_sha256": hashlib.sha256(body).hexdigest(),
|
| 531 |
+
"_pae_sha256": hashlib.sha256(pae).hexdigest(),
|
| 532 |
+
"signatures": [], "signed": False,
|
| 533 |
+
"honesty": "UNSIGNED-LOCAL — no signer available (%r); no signature fabricated." % e}
|
| 534 |
+
signing = {"available": False, "mode": "UNSIGNED-LOCAL", "alg": "ECDSA-P256-SHA256",
|
| 535 |
+
"envelope": "DSSEv1", "pae_sha256": env["_pae_sha256"], "note": env["honesty"]}
|
| 536 |
+
return env, signing
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
def _ingest_forum(receipt_body: dict, dsse: dict) -> dict:
|
| 540 |
+
"""Ingest the composite receipt into the shared /llm/forum substrate. Mirrors
|
| 541 |
+
serve.py's resolution order EXACTLY (substrate package first, local fallback) so
|
| 542 |
+
the append lands in the SAME _FORUM_LOG the /llm/forum GET reads."""
|
| 543 |
+
try:
|
| 544 |
+
try: # pragma: no cover
|
| 545 |
+
from szl_substrate import szl_llm_registry as _reg
|
| 546 |
+
except Exception:
|
| 547 |
+
import szl_llm_registry as _reg
|
| 548 |
+
entry = {
|
| 549 |
+
"ts": _now(),
|
| 550 |
+
"source": "agent_loop_governed",
|
| 551 |
+
"event": "agentloop_run",
|
| 552 |
+
"schema": SCHEMA,
|
| 553 |
+
"run_id": receipt_body.get("run_id"),
|
| 554 |
+
"task_preview": (receipt_body.get("task") or "")[:80],
|
| 555 |
+
"mode": receipt_body.get("mode"),
|
| 556 |
+
"n_steps": receipt_body.get("n_steps"),
|
| 557 |
+
"mean_eval_accuracy": receipt_body.get("aggregate", {}).get("mean_eval_accuracy"),
|
| 558 |
+
"mean_eval_lambda": receipt_body.get("aggregate", {}).get("mean_eval_lambda"),
|
| 559 |
+
"run_chain_digest": receipt_body.get("run_chain_digest"),
|
| 560 |
+
"signed": bool(dsse.get("signed")),
|
| 561 |
+
"receipt_schema": SCHEMA,
|
| 562 |
+
}
|
| 563 |
+
_reg._forum_append(entry)
|
| 564 |
+
return {"ingested": True, "forum": "/api/a11oy/v1/llm/forum", "source": "agent_loop_governed"}
|
| 565 |
+
except Exception as e: # pragma: no cover
|
| 566 |
+
return {"ingested": False, "note": "forum ingest skipped (%r)" % e}
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
# ===========================================================================
|
| 570 |
+
# ROUTE REGISTRATION — Starlette routes inserted BEFORE the SPA catch-all.
|
| 571 |
+
# sign_fn = the HOST app's REAL signer (same as the engine + eval-arena use).
|
| 572 |
+
# ===========================================================================
|
| 573 |
+
def register(app, ns: str = "a11oy", sign_fn: Optional[Callable[[dict], dict]] = None,
|
| 574 |
+
verify_fn=None) -> dict:
|
| 575 |
+
from starlette.routing import Route
|
| 576 |
+
from starlette.responses import JSONResponse
|
| 577 |
+
|
| 578 |
+
if not callable(sign_fn):
|
| 579 |
+
# Honest fallback signer via szl_dsse (still real in-Space, UNSIGNED-LOCAL locally).
|
| 580 |
+
def _fallback_sign(obj: dict) -> dict:
|
| 581 |
+
try:
|
| 582 |
+
import szl_dsse
|
| 583 |
+
return szl_dsse.sign_payload(obj, "application/vnd.szl.khipu+json")
|
| 584 |
+
except Exception as e:
|
| 585 |
+
body = _canon(obj).encode("utf-8")
|
| 586 |
+
return {"payloadType": "application/vnd.szl.khipu+json",
|
| 587 |
+
"_pae_sha256": hashlib.sha256(body).hexdigest(),
|
| 588 |
+
"signatures": [], "signed": False,
|
| 589 |
+
"honesty": "UNSIGNED-LOCAL — no signer (%r)." % e}
|
| 590 |
+
sign_fn = _fallback_sign
|
| 591 |
+
|
| 592 |
+
async def _run(request):
|
| 593 |
+
try:
|
| 594 |
+
b = await request.json()
|
| 595 |
+
except Exception:
|
| 596 |
+
b = {}
|
| 597 |
+
task = b.get("task") or b.get("prompt") or b.get("query") or ""
|
| 598 |
+
if not task:
|
| 599 |
+
return JSONResponse({
|
| 600 |
+
"ok": False,
|
| 601 |
+
"error": "task is required",
|
| 602 |
+
"label": "MODELED — supply a task to run the governed loop.",
|
| 603 |
+
"conjecture_note": _CONJECTURE_NOTE,
|
| 604 |
+
}, status_code=400)
|
| 605 |
+
mode = (b.get("mode") or "").lower()
|
| 606 |
+
model_id = str(b.get("model_id") or b.get("model") or "").strip()
|
| 607 |
+
harness_profile_id = str(b.get("harness_profile_id") or b.get("profile_id") or "").strip()
|
| 608 |
+
eval_suite = str(b.get("eval_suite") or b.get("suite_id") or "").strip()
|
| 609 |
+
approval = b.get("approval") if isinstance(b.get("approval"), dict) else None
|
| 610 |
+
try:
|
| 611 |
+
max_retries = int(b.get("max_retries", 1))
|
| 612 |
+
except Exception:
|
| 613 |
+
max_retries = 1
|
| 614 |
+
sandbox = b.get("sandbox")
|
| 615 |
+
sandbox = None if sandbox is None else bool(sandbox)
|
| 616 |
+
result = run_loop(task, sign_fn, ns=ns, mode=mode, model_id=model_id,
|
| 617 |
+
harness_profile_id=harness_profile_id, eval_suite=eval_suite,
|
| 618 |
+
approval=approval, max_retries=max_retries, sandbox=sandbox)
|
| 619 |
+
return JSONResponse(result, status_code=result.get("status_code", 200))
|
| 620 |
+
|
| 621 |
+
async def _health(request):
|
| 622 |
+
signer_live = False
|
| 623 |
+
try:
|
| 624 |
+
probe = sign_fn({"probe": "agentloop-health", "ts": _now()})
|
| 625 |
+
signer_live = bool(probe.get("signed"))
|
| 626 |
+
except Exception:
|
| 627 |
+
signer_live = False
|
| 628 |
+
eval_suites = None
|
| 629 |
+
if _ARENA_OK:
|
| 630 |
+
try:
|
| 631 |
+
eval_suites = list(getattr(_arena, "_SUITES", {}).keys())
|
| 632 |
+
except Exception:
|
| 633 |
+
eval_suites = None
|
| 634 |
+
return JSONResponse({
|
| 635 |
+
"surface": "szl_agent_loop_governed — governed autonomous agent loop",
|
| 636 |
+
"role": ("Composes /code run-loop (act) + model-harness (behavior profile) + "
|
| 637 |
+
"eval-arena (self-eval) + HumanApprovalGate into ONE governed loop with "
|
| 638 |
+
"ONE composite signed receipt per run, ingested to /llm/forum."),
|
| 639 |
+
"composes": {
|
| 640 |
+
"act_engine_available": _ENGINE_OK,
|
| 641 |
+
"plan_source_available": _RUNLOOP_OK,
|
| 642 |
+
"self_eval_available": _ARENA_OK,
|
| 643 |
+
"behavior_profile_available": _HARNESS_OK,
|
| 644 |
+
"human_gate_available": _APPROVAL_OK,
|
| 645 |
+
},
|
| 646 |
+
"eval_suites": eval_suites,
|
| 647 |
+
"approval_gate_enabled": os.environ.get("A11OY_APPROVAL_INTERRUPT") == "1",
|
| 648 |
+
"signer_live": signer_live,
|
| 649 |
+
"signature_mode": ("LIVE (real ECDSA-P256 in-image key)" if signer_live
|
| 650 |
+
else "UNSIGNED-LOCAL (honest — no in-image key in this runtime)"),
|
| 651 |
+
"endpoints": ["/api/%s/v1/agentloop/run" % ns,
|
| 652 |
+
"/api/%s/v1/agentloop/health" % ns],
|
| 653 |
+
"backs_view": "governedagent",
|
| 654 |
+
"leaders_cited": LEADERS,
|
| 655 |
+
"lambda": "Conjecture 1 (advisory — never a gate, never 'green').",
|
| 656 |
+
"doctrine": DOCTRINE,
|
| 657 |
+
"kernel_commit": _KERNEL,
|
| 658 |
+
"locked8_touched": False,
|
| 659 |
+
"honesty": (
|
| 660 |
+
"Plan = MODELED; act + self-eval + gate + composite receipt = LIVE. "
|
| 661 |
+
"Signatures real in-Space, honest UNSIGNED-LOCAL locally. Λ = Conjecture 1."),
|
| 662 |
+
"checked_at": _now(),
|
| 663 |
+
})
|
| 664 |
+
|
| 665 |
+
routes = [
|
| 666 |
+
Route("/api/%s/v1/agentloop/run" % ns, _run, methods=["POST"],
|
| 667 |
+
name="%s_agentloop_run" % ns),
|
| 668 |
+
Route("/api/%s/v1/agentloop/health" % ns, _health, methods=["GET"],
|
| 669 |
+
name="%s_agentloop_health" % ns),
|
| 670 |
+
]
|
| 671 |
+
for r in reversed(routes):
|
| 672 |
+
app.router.routes.insert(0, r)
|
| 673 |
+
return {"registered": [r.path for r in routes], "ns": ns,
|
| 674 |
+
"act_engine_available": _ENGINE_OK, "self_eval_available": _ARENA_OK,
|
| 675 |
+
"behavior_profile_available": _HARNESS_OK, "human_gate_available": _APPROVAL_OK}
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
def _selftest() -> None: # pragma: no cover
|
| 679 |
+
"""Local honest selftest — no network, no fabricated data."""
|
| 680 |
+
import szl_dsse
|
| 681 |
+
def _sign(obj):
|
| 682 |
+
return szl_dsse.sign_payload(obj, "application/vnd.szl.khipu+json")
|
| 683 |
+
out = run_loop("write a python function that returns the first 5 primes",
|
| 684 |
+
_sign, ns="a11oy", mode="code", max_retries=1)
|
| 685 |
+
assert out["ok"] is True, out
|
| 686 |
+
assert out["composite_receipt"]["body"]["schema"] == SCHEMA
|
| 687 |
+
assert out["composite_receipt"]["body"]["locked8_touched"] is False
|
| 688 |
+
assert out["aggregate"]["lambda_status"] == "CONJECTURE"
|
| 689 |
+
assert out["n_steps"] if "n_steps" in out else True
|
| 690 |
+
assert len(out["steps"]) >= 1
|
| 691 |
+
print("szl_agent_loop_governed: ALL OK (composed engine+harness+eval+gate, "
|
| 692 |
+
"ONE composite signed receipt, Λ=Conjecture 1, locked-8 untouched)")
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
if __name__ == "__main__": # pragma: no cover
|
| 696 |
+
_selftest()
|