File size: 24,166 Bytes
fe0ff58 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 | #!/usr/bin/env python3
"""Privileged Monolith MCP Daemon (`root:root`, `0700` vault & call_ledger isolation).
Exposes ONLY the MCP JSON-RPC boundary (`/run/ztp/ztp_mcp.sock` or TCP host:port)
to unprivileged (`uid=1000`) rollout agents while enforcing:
- Split call budgets (`max_discovery_calls` vs `max_sim_calls`)
- Batch-sweep macro disabling (`find_flip`, `design_run`, `validate_series`)
- Engineering Datasheet Discovery Mode (`form='short'` + safe metadata, withholding internal ODEs)
- SHA-384 chained `call_ledger.jsonl` with full `call_spec` & emitted seals (root-only)
- Dynamic plugin dispatch (`StatefulPlantPlugin`) for `CLC` & `FLT` tasks
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import signal
import socketserver
import sys
import threading
import time
from typing import Any
CORE_DIR = os.path.dirname(os.path.abspath(__file__))
LAB_ROOT = os.path.dirname(CORE_DIR)
if LAB_ROOT not in sys.path:
sys.path.insert(0, LAB_ROOT)
from core.pack_registry import get_task_bundle, load_task_plant_plugin, load_task_vault # noqa: E402
from core.verifier_core import ( # noqa: E402
compute_ledger_entry_hash,
extract_model_id_from_call,
extract_seals_from_answer,
)
from core.vault_bins import resolve_pack_engine # noqa: E402
from core.ztp_client import McpStdioClient # noqa: E402
DISCOVERY_TOOLS = {
"list_cards",
"describe_card",
"list_solvers",
"describe_solver",
"find_model",
"verify_tape",
"verify_solution",
"verify_step",
"verify_receipt",
"verify_dataset",
"cite",
}
SIM_TOOLS = {
"compute_step",
"run_trajectory",
"solve",
}
EXEMPT_TOOLS = {"budget_status"}
DISABLED_BATCH_TOOLS = {"run_dataset", "find_flip", "design_run", "validate_series"}
TOOL_ALIASES = {
"get_card": "describe_card",
"get_solver": "describe_solver",
"step_environment": "step_env",
}
PROOF_FIELD_NAMES = {"field_sha384", "seal_parts", "solution_seal", "seal_rule", "receipt_sha384"}
def _strip_proof_fields(obj: Any) -> Any:
if isinstance(obj, dict):
return {
k: _strip_proof_fields(v)
for k, v in obj.items()
if not (k.endswith("_hex") or k in PROOF_FIELD_NAMES)
}
if isinstance(obj, list):
return [_strip_proof_fields(v) for v in obj]
return obj
def strip_proof_fields_text(text: str) -> str:
"""Drop hash and bit-pattern fields from a JSON answer; non-JSON text passes through."""
try:
parsed = json.loads(text)
except ValueError:
return text
return json.dumps(_strip_proof_fields(parsed), separators=(",", ":"))
class MonolithDaemon:
"""Thread-safe privileged MCP router & ledger writer for one rollout container."""
def __init__(
self,
*,
task_id: str,
pack_name: str = "flagship_monolith_30",
pack_dir: str | None = None,
vault_dir: str | None = None,
ledger_path: str,
engine_bin: str | None = None,
max_discovery_calls: int | None = None,
max_sim_calls: int | None = None,
wall_timeout_s: float = 3600.0,
):
self.task_id = task_id
self.bundle = get_task_bundle(task_id=task_id, pack_name=pack_name, pack_dir=pack_dir)
self.task_spec = self.bundle["task_spec"]
budget = self.task_spec.get("budget") or {}
self.max_discovery_calls = int(
max_discovery_calls if max_discovery_calls is not None else budget.get("max_discovery_calls", 120)
)
self.max_sim_calls = int(
max_sim_calls if max_sim_calls is not None else budget.get("max_sim_calls", 40)
)
self.wall_timeout_s = float(wall_timeout_s)
self.started_monotonic: float | None = None
self.ledger_path = ledger_path
ledger_dir = os.path.dirname(os.path.abspath(ledger_path))
if not os.path.isdir(ledger_dir):
os.makedirs(ledger_dir, mode=0o700, exist_ok=True)
# The ledger exists from the first instant, even if the agent never calls a tool:
# a missing ledger at grading time then always means a broken pipe, never "no calls".
fd = os.open(ledger_path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
os.close(fd)
if engine_bin is None:
engine_bin = resolve_pack_engine(pack_name=pack_name, pack_dir=pack_dir)
self.vault = load_task_vault(task_id=task_id, vault_dir=vault_dir, pack_dir=self.bundle["pack_dir"])
# Per-task agent surface (`task.json` `agent_surface`). A task whose grader needs no
# hashes from the agent can switch off free recompute tools and drop proof fields
# from what the agent reads. The ledger always hashes the engine's full answer.
surface = dict(self.task_spec.get("agent_surface") or {})
self._task_disabled_tools = {str(t) for t in (surface.get("disabled_tools") or [])}
self._strip_proof_fields = bool(surface.get("strip_proof_fields"))
self._lock = threading.Lock()
self.seq = 0
self.discovery_used = 0
self.sim_used = 0
self.prev_sha384 = "0" * 96
self._load_existing_ledger()
self._client = McpStdioClient(engine_bin=engine_bin)
self._engine_tools = [t for t in self._client.list_tools() if t.get("name") not in DISABLED_BATCH_TOOLS]
self._plugin = load_task_plant_plugin(
task_id=task_id,
task_dir=self.bundle["task_dir"],
task_spec=self.task_spec,
engine_client=self._client,
vault=self.vault,
)
def _load_existing_ledger(self) -> None:
if not os.path.isfile(self.ledger_path):
return
with open(self.ledger_path, "r", encoding="utf-8") as fh:
for line in fh:
s = line.strip()
if not s:
continue
rec = json.loads(s)
self.seq = int(rec.get("seq", self.seq))
self.discovery_used = int(rec.get("discovery_used", self.discovery_used))
self.sim_used = int(rec.get("sim_used", self.sim_used))
self.prev_sha384 = str(rec.get("entry_sha384", self.prev_sha384))
def close(self) -> None:
if self._plugin is not None:
self._plugin.close()
self._client.close()
def _append_ledger(
self,
*,
tool: str,
category: str,
args: dict[str, Any],
raw_text: str,
is_error: bool,
budget_rejected: bool = False,
disabled_tool: bool = False,
call_spec: dict[str, Any] | None = None,
extracted_seals: list[str] | None = None,
step_call_records: list[dict[str, Any]] | None = None,
plugin_event: dict[str, Any] | None = None,
) -> None:
self.seq += 1
args_bytes = json.dumps(args, sort_keys=True, separators=(",", ":")).encode("utf-8")
ans_hash = hashlib.sha384(raw_text.encode("utf-8")).hexdigest()
body: dict[str, Any] = {
"seq": self.seq,
"ts_unix": round(time.time(), 6),
"task_id": self.task_id,
"tool": tool,
"category": category,
"discovery_used": self.discovery_used,
"max_discovery_calls": self.max_discovery_calls,
"sim_used": self.sim_used,
"max_sim_calls": self.max_sim_calls,
"budget_rejected": budget_rejected,
"disabled_tool": disabled_tool,
"is_error": is_error,
"args_sha384": hashlib.sha384(args_bytes).hexdigest(),
"answer_sha384": ans_hash,
"call_spec": call_spec,
"extracted_seals": extracted_seals or [],
"step_call_records": step_call_records or [],
"plugin_event": plugin_event,
"prev_sha384": self.prev_sha384,
}
entry_hash = compute_ledger_entry_hash(body)
full_entry = dict(body, entry_sha384=entry_hash)
self.prev_sha384 = entry_hash
with open(self.ledger_path, "a", encoding="utf-8") as fh:
fh.write(json.dumps(full_entry, separators=(",", ":")) + "\n")
try:
os.chmod(self.ledger_path, 0o600)
except OSError:
pass
def list_exposed_tools(self) -> list[dict[str, Any]]:
tools: list[dict[str, Any]] = [
{
"name": "budget_status",
"description": "Return remaining read-only discovery budget and simulation call budget (exempt from call caps).",
"inputSchema": {"type": "object", "properties": {}},
}
]
if self._plugin is not None:
tools.extend(self._plugin.tool_definitions())
tools.extend(self._engine_tools)
return [t for t in tools if t.get("name") not in self._task_disabled_tools]
def _serve_datasheet_discovery(self, tool_name: str, args: dict[str, Any]) -> tuple[str, bool]:
if tool_name == "describe_card":
short_args = {"domain": args.get("domain", ""), "card": args.get("card", ""), "form": "short"}
short_ans, raw_short, is_err = self._client.call_json("describe_card", short_args)
if is_err or not isinstance(short_ans, dict):
return raw_short, is_err
full_ans, _, full_err = self._client.call_json(
"describe_card",
{"domain": args.get("domain", ""), "card": args.get("card", ""), "form": "full"},
)
out = dict(short_ans)
out.pop("full_form", None)
out["form"] = "datasheet"
if not full_err and isinstance(full_ans, dict):
for k in ("advisory_flags", "validation", "frame_slots", "frame_rule"):
if k in full_ans:
out[k] = full_ans[k]
return json.dumps(out, separators=(",", ":")), False
short_args = {"solver": args.get("solver", ""), "form": "short"}
short_ans, raw_short, is_err = self._client.call_json("describe_solver", short_args)
if is_err or not isinstance(short_ans, dict):
return raw_short, is_err
full_ans, _, full_err = self._client.call_json(
"describe_solver",
{"solver": args.get("solver", ""), "form": "full"},
)
out = dict(short_ans)
out.pop("full_form", None)
out["form"] = "datasheet"
if not full_err and isinstance(full_ans, dict):
for k in ("couplings", "validation"):
if k in full_ans:
out[k] = full_ans[k]
return json.dumps(out, separators=(",", ":")), False
def _budget_snapshot(self) -> dict[str, Any]:
elapsed = round(time.monotonic() - self.started_monotonic, 2) if self.started_monotonic is not None else 0.0
snap: dict[str, Any] = {
"ok": True,
"task_id": self.task_id,
"discovery_calls_used": self.discovery_used,
"discovery_calls_remaining": max(0, self.max_discovery_calls - self.discovery_used),
"max_discovery_calls": self.max_discovery_calls,
"sim_calls_used": self.sim_used,
"sim_calls_remaining": max(0, self.max_sim_calls - self.sim_used),
"max_sim_calls": self.max_sim_calls,
"wall_seconds_elapsed": elapsed,
"wall_seconds_remaining": round(max(0.0, self.wall_timeout_s - elapsed), 2),
}
if self._plugin is not None:
snap.update(self._plugin.budget_extras())
return snap
def _reject_budget(self, tool_name: str, category: str, args: dict[str, Any], message: str) -> dict[str, Any]:
err_txt = json.dumps({"ok": False, "error": message, "budget": self._budget_snapshot()}, separators=(",", ":"))
self._append_ledger(
tool=tool_name,
category=category,
args=args,
raw_text=err_txt,
is_error=True,
budget_rejected=True,
)
return {"ok": True, "text": err_txt, "isError": True}
def handle_tool_call(self, raw_tool_name: str, args: dict[str, Any]) -> dict[str, Any]:
"""Route one agent tool call. The ledger records the full answer; the agent may get a leaner one."""
res = self._handle_tool_call_full(raw_tool_name, args)
if self._strip_proof_fields and isinstance(res.get("text"), str):
res = dict(res, text=strip_proof_fields_text(res["text"]))
return res
def _handle_tool_call_full(self, raw_tool_name: str, args: dict[str, Any]) -> dict[str, Any]:
with self._lock:
tool_name = TOOL_ALIASES.get(raw_tool_name, raw_tool_name)
if tool_name in self._task_disabled_tools:
err_txt = json.dumps(
{"ok": False, "error": f"Tool {tool_name!r} is not available in this task."},
separators=(",", ":"),
)
self._append_ledger(
tool=tool_name,
category="disabled_task",
args=args,
raw_text=err_txt,
is_error=True,
budget_rejected=True,
disabled_tool=True,
)
return {"ok": True, "text": err_txt, "isError": True}
if tool_name in DISABLED_BATCH_TOOLS:
err_txt = json.dumps(
{
"ok": False,
"error": (
f"Batch sweep macro {tool_name!r} is disabled. "
f"Use targeted single-run calls (`run_trajectory`, `compute_step`, `solve`) "
f"within max_sim_calls={self.max_sim_calls}."
),
},
separators=(",", ":"),
)
self._append_ledger(
tool=tool_name,
category="disabled_batch",
args=args,
raw_text=err_txt,
is_error=True,
budget_rejected=True,
disabled_tool=True,
)
return {"ok": True, "text": err_txt, "isError": True}
if tool_name == "budget_status":
txt = json.dumps(self._budget_snapshot(), separators=(",", ":"))
self._append_ledger(tool=tool_name, category="exempt", args=args, raw_text=txt, is_error=False)
return {"ok": True, "text": txt, "isError": False}
if self.started_monotonic is None:
self.started_monotonic = time.monotonic()
if (time.monotonic() - self.started_monotonic) > self.wall_timeout_s:
return self._reject_budget(
tool_name, "timeout", args, f"Task wall timeout {self.wall_timeout_s}s exceeded."
)
# 1. Dynamic Plugin Tool Route (CLC / FLT)
if self._plugin is not None:
p_cat = self._plugin.tool_category(tool_name)
if p_cat is not None:
if p_cat == "discovery":
if self.discovery_used >= self.max_discovery_calls:
return self._reject_budget(
tool_name, "discovery", args, f"Discovery call budget exhausted ({self.max_discovery_calls})."
)
self.discovery_used += 1
elif p_cat == "sim":
if self.sim_used >= self.max_sim_calls:
return self._reject_budget(
tool_name, "sim", args, f"Simulation call budget exhausted ({self.max_sim_calls})."
)
self.sim_used += 1
res = self._plugin.handle_tool(tool_name, args)
txt = str(res.get("text", "{}"))
is_err = bool(res.get("isError", False))
step_recs_raw = res.get("step_call_records") or []
norm_step_recs: list[dict[str, Any]] = []
for sr in step_recs_raw:
raw_sr = str(sr.get("raw_text") or "")
parsed_sr = json.loads(raw_sr) if raw_sr else {}
sr_args = dict(sr.get("args") or {})
sr_tool = str(sr.get("tool") or "")
mid = str(sr.get("model_id") or extract_model_id_from_call(sr_tool, sr_args, parsed_sr))
norm_step_recs.append(
{
"call_spec": {"tool": sr_tool, "model_id": mid, "args": sr_args},
"answer_sha384": hashlib.sha384(raw_sr.encode("utf-8")).hexdigest() if raw_sr else "",
"extracted_seals": extract_seals_from_answer(parsed_sr),
}
)
self._append_ledger(
tool=tool_name,
category=p_cat,
args=args,
raw_text=txt,
is_error=is_err,
step_call_records=norm_step_recs,
plugin_event=res.get("plugin_event"),
)
return {"ok": True, "text": txt, "isError": is_err}
# 2. Standard Engine Discovery vs Simulation Route
if tool_name in DISCOVERY_TOOLS:
category = "discovery"
if self.discovery_used >= self.max_discovery_calls:
return self._reject_budget(
tool_name, category, args, f"Discovery call budget exhausted ({self.max_discovery_calls})."
)
self.discovery_used += 1
if tool_name in ("describe_card", "describe_solver"):
raw_text, is_err = self._serve_datasheet_discovery(tool_name, args)
else:
raw_text, is_err = self._client.call_raw(tool_name, args)
self._append_ledger(tool=tool_name, category=category, args=args, raw_text=raw_text, is_error=is_err)
return {"ok": True, "text": raw_text, "isError": is_err}
if tool_name in SIM_TOOLS:
category = "sim"
if self.sim_used >= self.max_sim_calls:
return self._reject_budget(
tool_name, category, args, f"Simulation call budget exhausted ({self.max_sim_calls})."
)
self.sim_used += 1
parsed, raw_text, is_err = self._client.call_json(tool_name, args)
mid = extract_model_id_from_call(tool_name, args, parsed)
extracted = extract_seals_from_answer(parsed) if not is_err else []
self._append_ledger(
tool=tool_name,
category=category,
args=args,
raw_text=raw_text,
is_error=is_err,
call_spec={"tool": tool_name, "model_id": mid, "args": args},
extracted_seals=extracted,
)
return {"ok": True, "text": raw_text, "isError": is_err}
# Fallback unknown tool
err_txt = json.dumps({"ok": False, "error": f"Unknown tool: {raw_tool_name!r}"}, separators=(",", ":"))
self._append_ledger(tool=tool_name, category="unknown", args=args, raw_text=err_txt, is_error=True)
return {"ok": True, "text": err_txt, "isError": True}
class _RpcHandler(socketserver.StreamRequestHandler):
daemon: MonolithDaemon
def handle(self) -> None:
line = self.rfile.readline()
if not line:
return
try:
req = json.loads(line.decode("utf-8"))
method = req.get("method", "")
params = req.get("params") or {}
if method == "tools/list":
resp = {"ok": True, "tools": self.daemon.list_exposed_tools()}
elif method == "tools/call":
resp = self.daemon.handle_tool_call(str(params.get("name", "")), params.get("arguments") or {})
elif method == "ping":
resp = {"ok": True, "task_id": self.daemon.task_id}
else:
resp = {"ok": False, "error": f"Unknown daemon RPC method {method!r}"}
except Exception as exc:
resp = {"ok": False, "error": f"Daemon internal exception: {exc}"}
self.wfile.write((json.dumps(resp, separators=(",", ":")) + "\n").encode("utf-8"))
self.wfile.flush()
class ThreadedUnixServer(socketserver.ThreadingMixIn, socketserver.UnixStreamServer):
daemon_threads = True
class ThreadedTcpServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
allow_reuse_address = True
daemon_threads = True
def serve_daemon(
*,
task_id: str,
socket_endpoint: str,
ledger_path: str,
pack_name: str = "flagship_monolith_30",
pack_dir: str | None = None,
vault_dir: str | None = None,
engine_bin: str | None = None,
max_discovery_calls: int | None = None,
max_sim_calls: int | None = None,
wall_timeout_s: float = 3600.0,
) -> None:
daemon_obj = MonolithDaemon(
task_id=task_id,
pack_name=pack_name,
pack_dir=pack_dir,
vault_dir=vault_dir,
ledger_path=ledger_path,
engine_bin=engine_bin,
max_discovery_calls=max_discovery_calls,
max_sim_calls=max_sim_calls,
wall_timeout_s=wall_timeout_s,
)
class BoundHandler(_RpcHandler):
daemon = daemon_obj
if ":" in socket_endpoint and not socket_endpoint.startswith("/") and not socket_endpoint.startswith("."):
host, port_s = socket_endpoint.rsplit(":", 1)
server: socketserver.BaseServer = ThreadedTcpServer((host, int(port_s)), BoundHandler)
else:
os.makedirs(os.path.dirname(os.path.abspath(socket_endpoint)), exist_ok=True)
if os.path.exists(socket_endpoint):
os.unlink(socket_endpoint)
server = ThreadedUnixServer(socket_endpoint, BoundHandler)
os.chmod(socket_endpoint, 0o666)
def _stop(_sig: int, _frame: Any) -> None:
threading.Thread(target=server.shutdown, daemon=True).start()
signal.signal(signal.SIGTERM, _stop)
signal.signal(signal.SIGINT, _stop)
try:
server.serve_forever()
finally:
daemon_obj.close()
if not (":" in socket_endpoint and not socket_endpoint.startswith("/")):
try:
os.unlink(socket_endpoint)
except OSError:
pass
def main() -> int:
parser = argparse.ArgumentParser(description="Genesis Lab Monolith Privileged Daemon")
parser.add_argument("--task-id", required=True)
parser.add_argument("--pack", default="flagship_monolith_30")
parser.add_argument("--pack-dir", default=None)
parser.add_argument("--socket", default="/run/ztp/ztp_mcp.sock")
parser.add_argument("--vault-dir", default=None)
parser.add_argument("--ledger", default="/root/ztp_vault/call_ledger.jsonl")
parser.add_argument("--engine", default=None)
parser.add_argument("--max-discovery-calls", type=int, default=None)
parser.add_argument("--max-sim-calls", type=int, default=None)
parser.add_argument("--wall-timeout-s", type=float, default=3600.0)
args = parser.parse_args()
serve_daemon(
task_id=args.task_id,
socket_endpoint=args.socket,
ledger_path=args.ledger,
pack_name=args.pack,
pack_dir=args.pack_dir,
vault_dir=args.vault_dir,
engine_bin=args.engine,
max_discovery_calls=args.max_discovery_calls,
max_sim_calls=args.max_sim_calls,
wall_timeout_s=args.wall_timeout_s,
)
return 0
if __name__ == "__main__":
raise SystemExit(main())
|