Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

## Unreleased

- **Breaking change (tool authorization): a Context Runtime tenant no longer starts without an authorization plane.** Every integration tenant and the module fleet resolves an authorizer at construction (`context_runtime/tools/authz.py`): an explicit `authorizer=`, else a plane installed process-wide with `context_runtime.tools.set_default_authorizer(...)` (what `agentic_os.app_gate.install_gate` does), else an explicitly declared local authority — `local_trust=True` with a written `local_trust_reason`, or `CR_LOCAL_AUTHORITY="<why this process is trusted>"`. None of the three raises `RegistryConfigurationError` at construction instead of denying every call later; `CR_LOCAL_AUTHORITY=1` is refused, because a value that carries no reason is how an allow-all switch reaches a production manifest. This follows agent-harness #33 (a registry with no authorizer denies everything) and #34 (a tool with no declared risk class is permitted by no grant).
- **Behaviour change (risk classes are declared, never inferred).** `mount_mcp(..., actions={...}, default_action="write")` and `AgentConsole.tool(..., action=...)` take the class from the integrator; `readOnlyHint`/`title` pass through as annotations and relax the **approval** gate only. An MCP server is not allowed to grade its own risk. `AgentConsole.validate()` is the start-up check that refuses to serve a console with no plane.
- **Behaviour change (the module fleet):** standing a module up with no plane no longer kills the process — `Fleet.up()` follows `AgentConsole`'s rule (`on_missing="deny_later"`), because the embedding application installs its gate a moment after import and a container that never answers `/health` is worse than one that denies. It warns once, and every tool call stays denied (`missing_authorizer`) until a plane exists. **`/status` looks identical either way** — that is what the warning is for.
- **Behaviour change (fleet actions of discovered modules):** a `CATALOG` action without a recorded class is still a start-up error, because this file wrote those names. An action inferred from a module the registry discovered at run time (e.g. `sidekick.coder`) is now registered **unclassified** — matched by no grant, so denied — with one warning naming it. Before this it was impossible to run a custom module at all, and guessing `read` for an unread action is the failure this migration removes.
- **Pin:** `agent-harness` `6b8ba3a` → `7e422f541f` (fail-closed authorizer decisions + `ToolSpec.action`). `Dockerfile`, `deploy/geo-demo/Dockerfile.aks` and `deploy/proxmox-demo/Dockerfile.contextruntime` move with it; `tests/test_container.py` / `tests/test_geo_image.py` fail if they drift apart.

- **Fix (Windows):** `JsonlExporter` appends each trace through `locked_append` (inter-process and in-process lock, one write, explicit newline, no per-trace `fsync`). A bare `open(path, "a")` loses lines when writers overlap on Windows, where the C runtime appends as seek-then-write. `locked_append` gains `durable=False`. The exporter waits at most 1 s for the lock; if it cannot get it the trace is dropped and one warning is logged per exporter. A test fails on any new lock-free append writer in the repository's Python code. **Visible differences:** a `<name>.jsonl.lock` sidecar file (0600) is created next to the trace file; in a read-only directory, or one holding a sidecar owned by another user, `export` now raises `PermissionError` where the bare append worked (the runtime and `MultiExporter` swallow exporter errors, so the trace is lost; one warning is logged); on Windows each line now ends in LF, where text-mode append wrote CRLF, so a trace file written by an older version and then appended to can mix the two (`splitlines()` and `json.loads` accept both).

Native Windows and macOS portability of the core library. Details and the verification status of each item: [docs/native-portability.md](docs/native-portability.md).
Expand Down
4 changes: 2 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ RUN pip install --no-cache-dir "fastapi>=0.110" "uvicorn>=0.29" "httpx>=0.27" "p
# application does not import without it. Pinned to the same commit as pyproject.toml, from the commit's
# source archive (no git in this image) and verified against the archive's sha256.
# tests/test_container.py checks that this commit equals the one in pyproject.toml.
ARG AGENT_HARNESS_COMMIT=6b8ba3a596a5e2caf0fdf009f2af013517591662
ARG AGENT_HARNESS_SHA256=d67eadb33c161df00b70bad4f20c80f43d2f477031dce3259ee5d465c8844a47
ARG AGENT_HARNESS_COMMIT=1259d1b338e80414b32b863bcc97a0db93db8cd2
ARG AGENT_HARNESS_SHA256=5e7ac02ec1fdb6e00aba7d7871db870d08f5b89084c4464173354a4ef036e04c
RUN pip install --no-cache-dir "agent-harness @ https://github.com/redevops-io/agent-harness/archive/${AGENT_HARNESS_COMMIT}.tar.gz#sha256=${AGENT_HARNESS_SHA256}"
ENV PYTHONPATH=/app

Expand Down
41 changes: 35 additions & 6 deletions context_runtime/control_plane/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,8 +199,13 @@ def _build() -> Fleet:
CORSMiddleware, allow_origins=[o.strip() for o in _cors if o.strip()],
allow_methods=["GET", "POST", "OPTIONS"], allow_headers=["*"],
)
# Building the fleet is the authorization gate: a privileged fleet that cannot name a plane to ask raises here,
# so the container exits instead of serving a dashboard over a fleet whose every call is denied. A fleet
# declared diagnostic (CR_EXECUTION_MODE=diagnostic, with a written reason) comes up and is built without an
# execution path — no tenants, so /up, /dispatch and /agent/run have nothing to fall back to.
fleet = _build()
fleet.up() # (b) stand up every module as a Context Runtime tenant → deployed
if fleet.privileged:
fleet.up() # (b) stand up every module as a Context Runtime tenant → deployed
# Hermes 0.17 inbound chatops gateway — daemon thread, started only if a channel
# is configured (closed by default; honors AGENTIC_OS_GATEWAY_ALLOW / _OPEN).
_gateway = channels.Gateway(fleet)
Expand Down Expand Up @@ -490,8 +495,32 @@ def dashboard() -> str:

@app.get("/health")
def health() -> dict:
"""Liveness only. The one unauthenticated route; it discloses nothing about the deployment."""
return {"status": "ok"}
"""Liveness, plus the one fact that stops a deny-only instance being read as a working one.

It used to answer ``{"status": "ok"}`` and nothing else, on the grounds that a public route should
disclose nothing about the deployment. That held until the fleet could stand up with no authorization plane
and keep answering this endpoint while every tool call came back denied — the dashboard's green tick was
then indistinguishable from the outage it was supposed to detect. Two booleans are disclosed, both derived
from this process's own start-up decision: no paths, no tenants, no configuration, no module names.
"""
return {"status": "ok", "mode": "diagnostic" if not fleet.privileged else "execute",
"privileged_execution": fleet.privileged}


def require_execution() -> None:
"""Refuse, before the handler runs, on the routes that would make a diagnostic instance execute.

The handlers would fail anyway — there are no tenants — but a 500 from inside ``fleet.up()`` reads like a
crash, and this state is not a crash: it is a deployment that said what it is. 503 says so, and says what
to change.
"""
if not fleet.privileged:
raise HTTPException(503, "this control plane is running in the diagnostic mode (no authorization plane "
"was installed, so privileged execution is not available in it). To run "
"actions, start the execution instance: install a plane with "
"context_runtime.tools.set_default_authorizer(...) before the control plane "
"imports, or declare local authority with CR_LOCAL_AUTHORITY=\"why this "
"process may act as the operator\".")


@app.get("/modules", response_model=list[ModuleList])
Expand All @@ -505,7 +534,7 @@ def status() -> list[dict]:
return [asdict(s) for s in fleet.status()]


@app.post("/up", dependencies=[Depends(require_api_key)])
@app.post("/up", dependencies=[Depends(require_api_key), Depends(require_execution)])
def up(names: list[str] | None = None) -> list[dict]:
return [asdict(s) for s in fleet.up(*(names or []))]

Expand Down Expand Up @@ -539,7 +568,7 @@ class DispatchRequest(BaseModel):
background: bool = False


@app.post("/dispatch", dependencies=[Depends(require_api_key)])
@app.post("/dispatch", dependencies=[Depends(require_api_key), Depends(require_execution)])
def dispatch(req: DispatchRequest) -> dict:
"""Run one agent action through the fleet (router-picked model).

Expand Down Expand Up @@ -988,7 +1017,7 @@ class RunRequest(BaseModel):
question: str


@app.post("/agent/run", dependencies=[Depends(require_api_key)])
@app.post("/agent/run", dependencies=[Depends(require_api_key), Depends(require_execution)])
def agent_run(req: RunRequest) -> dict:
"""Plan a module's answer through its Context Runtime tenant (no side effects)."""
try:
Expand Down
48 changes: 47 additions & 1 deletion context_runtime/control_plane/fleet.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from __future__ import annotations

import threading
import warnings
from dataclasses import dataclass

from pathlib import Path
Expand All @@ -19,6 +20,12 @@
from ..integrations.modules import CATALOG, ModuleSpec, ModuleTenant
from ..platform_services import ensure_private_dir, state_dir
from ..runtime.runtime import ContextRuntime
from ..tools.authz import (
DIAGNOSTIC,
PrivilegedExecutionUnavailable,
execution_mode,
require_plane,
)
from .context import Approval, Context
from .registry import Module, Registry

Expand All @@ -32,17 +39,37 @@
}


#: Recorded once per process so /health can say what this fleet was allowed to become. It is a start-up fact,
#: which is exactly why it is no longer a warning: see ``require_plane``.
_MODE: tuple[str, str] | None = None


def mode() -> tuple[str, str]:
"""``("execute", "")`` or ``("diagnostic", reason)`` for this fleet — decided once, at construction.

The control plane is a privileged execution service: it stands up tenants whose tools block IPs, file
tickets and bill customers. It therefore refuses to come up at all with nothing to ask, and the only
instance of it that may boot without a plane is one where execution has been taken out of the build —
no tenants, no dispatch, nothing for a missing grant to be about.
"""
return _MODE if _MODE is not None else execution_mode(context="module fleet")


def spec_for(m: Module) -> ModuleSpec:
"""A CATALOG tenant spec if we have one; otherwise a generic spec from the registry."""
key = _ALIAS.get(m.name)
if key and key in CATALOG:
return CATALOG[key]
if m.name in CATALOG:
return CATALOG[m.name]
# Not a CATALOG row: the action names come from a module the registry discovered at run time, so
# this file cannot vouch for what they do. They are registered unclassified (denied) rather than
# assumed safe — see integrations/modules.py::_action_tool.
return ModuleSpec(
name=m.name.replace("-", "_"), core="", pain=m.pain,
sources=("primary", "secondary", "context"), metric="task_success",
actions=tuple(a.replace("-", "_") for a in m.approval_required) or tuple(m.agents[:1]),
curated_actions=False,
)


Expand All @@ -56,8 +83,16 @@ class ModuleStatus:

class Fleet:
def __init__(self, registry: Registry, router=None, context: Context | None = None,
workdir=None, runtime: ContextRuntime | None = None, home: str | None = None):
workdir=None, runtime: ContextRuntime | None = None, home: str | None = None,
privileged: bool | None = None):
global _MODE
self.registry = registry
# Decided once, here, before anything can run: a privileged fleet refuses construction without a plane
# (``require_plane``), a diagnostic one comes up and is handed nothing to execute with.
_MODE = execution_mode(context="module fleet")
self.privileged = (_MODE[0] != DIAGNOSTIC) if privileged is None else privileged
if self.privileged:
require_plane(context="module fleet")
self.router = router # kept for app compatibility; unused
self.home = Path(home) if home else state_dir() # persistence root (the /data volume in a container)
self.context = context or Context(ensure_private_dir(self.home))
Expand All @@ -75,6 +110,12 @@ def _names(self) -> list[str]:

# --- lifecycle ---
def up(self, *names: str) -> list[ModuleStatus]:
if not self.privileged:
raise PrivilegedExecutionUnavailable(
"this fleet is diagnostic: it does not stand modules up. It exists to show a fleet that has no "
"execution path — no tenants, no tool registry, nothing a missing grant could be about — and "
"standing one up would be the moment it silently became an execution service again. Run the "
"execution instance for that.")
out = []
for n in (names or self._names()):
m = self.registry.get(n)
Expand Down Expand Up @@ -103,6 +144,11 @@ def status(self) -> list[ModuleStatus]:
# --- dispatch (now a Context Runtime plan, not a raw model call) ---
def dispatch(self, module_name: str, agent: str, action: str, prompt: str,
capability: str = "reason", background: bool = False) -> Approval | dict:
if not self.privileged:
raise PrivilegedExecutionUnavailable(
f"dispatch({module_name}/{action}) is refused: this fleet is diagnostic, so it has no tenants "
f"and no tool path behind them. A diagnostic instance answers questions about a fleet; it does "
f"not act as one.")
m = self.registry.get(module_name)
if agent not in m.agents:
raise ValueError(f"module {module_name} has no agent {agent!r} (agents: {m.agents})")
Expand Down
Loading
Loading