feat(maf): add secure roundtable workflow runtime
This commit is contained in:
1 parent
e690475e6e
commit
bd4131b4e2
52 files changed
+10315
-96
No files matched your search
@@ -328,13 +328,41 @@ async def langgraph_runtime(app: FastAPI) -> AsyncGenerator[None, None]:
|
||||
maf_admin_diag = (
|
||||
bool(getattr(maf_cfg, "admin_diagnostic_access", True)) if maf_cfg is not None else True
|
||||
)
|
||||
# P0-4: when MAF is switched on, its full safety stack must be in
|
||||
# place (write_guard mounted + provider complete + bridge resolvable
|
||||
# + MAF_ACTION_SECRET_KEY set). If any prerequisite is missing the
|
||||
# feature is forced OFF (clearly logged) — never "MAF on, approval
|
||||
# guard not mounted". Reads stay open for admin history review.
|
||||
if maf_enabled:
|
||||
from app.maf_roundtable.service import (
|
||||
MafConfigurationError,
|
||||
validate_maf_prerequisites,
|
||||
)
|
||||
|
||||
try:
|
||||
validate_maf_prerequisites()
|
||||
except MafConfigurationError as cfg_exc:
|
||||
logger.error(
|
||||
"[maf-roundtable] enabled but prerequisites unmet — "
|
||||
"forcing the feature OFF: %s",
|
||||
cfg_exc,
|
||||
)
|
||||
maf_enabled = False
|
||||
if app.state.maf_roundtable_store is not None:
|
||||
app.state.maf_roundtable_service = MafRoundtableService(
|
||||
app.state.maf_roundtable_store,
|
||||
enabled=maf_enabled,
|
||||
admin_diagnostic_access=maf_admin_diag,
|
||||
config=maf_cfg,
|
||||
agent_store=getattr(app.state, "agent_store", None),
|
||||
app_config=config,
|
||||
)
|
||||
# Wire the WriteGuard bridge so the harness middleware can reach
|
||||
# the service when intercepting external-write tool calls.
|
||||
if app.state.maf_roundtable_service is not None:
|
||||
from app.maf_roundtable.write_guard_bridge import register_write_guard_service
|
||||
|
||||
register_write_guard_service(app.state.maf_roundtable_service)
|
||||
else:
|
||||
app.state.maf_roundtable_service = None
|
||||
except Exception: # noqa: BLE001 — experimental feature must never abort startup
|
||||
|
||||
@@ -198,12 +198,31 @@ async def delete_session(request: Request, session_id: str) -> dict[str, Any]:
|
||||
async def create_run(request: Request, session_id: str, body: CreateRunRequest) -> RunResponse:
|
||||
svc = _require_service(request)
|
||||
user_id, is_admin = _user_ctx(request)
|
||||
|
||||
# Check MAF SDK availability BEFORE creating the run — so the user gets a
|
||||
# clean 503 rather than a run that will immediately fail.
|
||||
from app.maf_roundtable.dispatcher import MafSdkNotAvailableError, get_dispatcher
|
||||
|
||||
dispatcher = get_dispatcher(request.app)
|
||||
try:
|
||||
dispatcher.check_sdk_available()
|
||||
except MafSdkNotAvailableError as exc:
|
||||
raise HTTPException(status_code=503, detail=str(exc)) from exc
|
||||
|
||||
try:
|
||||
run = await svc.create_run(
|
||||
session_id=session_id, user_id=user_id, workflow_version=body.workflow_version, is_admin=is_admin
|
||||
)
|
||||
except (MafDisabledError, MafForbiddenError, MafNotFoundError, MafConflictError) as exc:
|
||||
raise _map_service_error(exc) from exc
|
||||
|
||||
# Launch the workflow in the background. The run is already persisted as
|
||||
# "pending"; the dispatcher transitions it to "running" then completes/fails it.
|
||||
# Auto-dispatch can be disabled (e.g. in tests) via app.state.maf_auto_dispatch=False.
|
||||
if getattr(request.app.state, "maf_auto_dispatch", True):
|
||||
session = await svc.get_session(session_id=session_id, user_id=user_id, is_admin=is_admin)
|
||||
await dispatcher.dispatch(session, run, user_id=user_id or "default")
|
||||
|
||||
return RunResponse(**run)
|
||||
|
||||
|
||||
@@ -233,11 +252,43 @@ async def get_run(request: Request, run_id: str) -> RunResponse:
|
||||
async def cancel_run(request: Request, run_id: str) -> RunResponse:
|
||||
svc = _require_service(request)
|
||||
user_id, is_admin = _user_ctx(request)
|
||||
|
||||
# Phase 1: atomically set run+session to cancelling (not yet cancelled).
|
||||
try:
|
||||
run = await svc.cancel_run(run_id=run_id, user_id=user_id, is_admin=is_admin)
|
||||
await svc.start_cancel(run_id=run_id, user_id=user_id, is_admin=is_admin)
|
||||
except (MafDisabledError, MafForbiddenError, MafNotFoundError) as exc:
|
||||
raise _map_service_error(exc) from exc
|
||||
return RunResponse(**run)
|
||||
|
||||
# Phase 2: cascade cancel to the background task + DeerFlow sub-runs.
|
||||
from app.maf_roundtable.dispatcher import get_dispatcher
|
||||
|
||||
dispatcher = get_dispatcher(request.app)
|
||||
result = await dispatcher.cancel(run_id)
|
||||
|
||||
# Phase 3: finalize based on the structured cancel result.
|
||||
# - all_cancelled → finalize to ``cancelled`` (terminal).
|
||||
# - some sub-runs failed/still active → mark ``cancel_failed`` (non-terminal)
|
||||
# so the failure is visible and retryable. A failed cancel must NEVER
|
||||
# masquerade as cancelled.
|
||||
try:
|
||||
if result.get("all_cancelled"):
|
||||
final_run = await svc.finalize_cancel(run_id=run_id, user_id=user_id, is_admin=is_admin)
|
||||
else:
|
||||
failed = result.get("failed_run_ids") or []
|
||||
still_active = result.get("still_active_run_ids") or []
|
||||
detail = []
|
||||
if failed:
|
||||
detail.append(f"{len(failed)} sub-run(s) failed to cancel")
|
||||
if still_active:
|
||||
detail.append(f"{len(still_active)} sub-run(s) had no DeerFlow run id")
|
||||
reason = "; ".join(detail) or "cancel cascade incomplete"
|
||||
final_run = await svc.mark_cancel_failed(
|
||||
run_id=run_id, user_id=user_id, is_admin=is_admin, reason=reason
|
||||
)
|
||||
except (MafDisabledError, MafForbiddenError, MafNotFoundError) as exc:
|
||||
raise _map_service_error(exc) from exc
|
||||
|
||||
return RunResponse(**final_run)
|
||||
|
||||
|
||||
# ── events ─────────────────────────────────────────────────────────────────
|
||||
@@ -310,4 +361,25 @@ async def decide_approval(request: Request, approval_id: str, body: ApprovalDeci
|
||||
)
|
||||
except (MafDisabledError, MafForbiddenError, MafNotFoundError, MafConflictError) as exc:
|
||||
raise _map_service_error(exc) from exc
|
||||
|
||||
# P1: after a successful approval decision, resume the workflow from its
|
||||
# checkpoint. Only the owner can resume (decide_approval already enforced
|
||||
# owner-only write). The resume loads the checkpoint, restores
|
||||
# RoundtableState.from_dict(), and executes the approved action (at-most-once).
|
||||
run_id = approval.get("run_id")
|
||||
if run_id and body.decision in ("approved", "rejected"):
|
||||
from app.maf_roundtable.dispatcher import get_dispatcher
|
||||
|
||||
dispatcher = get_dispatcher(request.app)
|
||||
try:
|
||||
await dispatcher.resume(run_id, user_id=user_id or "default")
|
||||
except Exception:
|
||||
# Resume failure should not fail the approval response itself —
|
||||
# the approval is already persisted. Log for observability.
|
||||
import logging
|
||||
|
||||
logging.getLogger(__name__).exception(
|
||||
"MAF resume failed for run %s after approval %s", run_id, approval_id
|
||||
)
|
||||
|
||||
return ApprovalResponse(**approval)
|
||||
Reference in new issue
Block a user