Astra: security review, left-on-pod ledger, chosen scenarios all run, GL navigation and Create Order popup on 26D, health check (ed9256cd4029)
348eedc verified Download coworker/api/app.py from EnergyVenom/patchwise-agent-studio: direct link, hf CLI and curl.
- Browser
- Download file 11 kB
-
https://huggingface.co/spaces/EnergyVenom/patchwise-agent-studio/resolve/main/coworker/api/app.py
- Command line
-
hf download hf://spaces/EnergyVenom/patchwise-agent-studio/coworker/api/app.py
-
curl -L -o app.py https://huggingface.co/spaces/EnergyVenom/patchwise-agent-studio/resolve/main/coworker/api/app.py
11 kB
| """FastAPI app factory. Same origin: `/` = built web app (web/dist), `/api` = API, `/api/docs` = OpenAPI UI. | |
| Lifespan starts the RunManager worker and the Scheduler; crash recovery marks running runs 'interrupted'.""" | |
| from __future__ import annotations | |
| import logging | |
| from contextlib import asynccontextmanager | |
| from pathlib import Path | |
| from fastapi import APIRouter, FastAPI, Request | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.responses import FileResponse, JSONResponse | |
| from ..config import VERSION, Settings, get_settings | |
| from ..graph.services import Services, build_services | |
| from ..platform.scheduler import Scheduler | |
| from . import errors | |
| from .middleware import BodyLimit, RequestContext, setup_logging | |
| from . import a2a, mcp | |
| from .routes import admin, agent_studio, ai_monitoring, assistant, auth, channels, chat, consultant, custom_cases, gates, heals, integrations, left_on_pod, live, llm, notifications, pods, recordings, review, runs, screens, signin, tokens | |
| from .runner import RunManager | |
| log = logging.getLogger("fpt.api") | |
| def _orchestrator(svc: Services, cfg: Settings): | |
| """FPT_ORCHESTRATOR=temporal (default): Temporal client + Temporal Schedules. Falls back to the in-process LangGraph | |
| RunManager + Scheduler when Temporal is unreachable (reported by /api/ready).""" | |
| if cfg.orchestrator == "temporal": | |
| try: | |
| from ..workflows.client import TemporalRunManager, TemporalScheduler | |
| rm = TemporalRunManager(svc) | |
| if cfg.embedded_worker: | |
| from ..workflows.worker import start_embedded | |
| start_embedded(svc) | |
| return rm, TemporalScheduler(svc, rm) | |
| except Exception as e: # noqa: BLE001 | |
| log.warning("Temporal unreachable at %s (%s): falling back to the in-process LangGraph orchestrator", | |
| cfg.temporal_address, type(e).__name__) | |
| rm = RunManager(svc) | |
| rm.fallback_reason = f"temporal unreachable at {cfg.temporal_address}" | |
| return rm, Scheduler(svc, rm, cfg.scheduler_tick_s) | |
| rm = RunManager(svc) | |
| return rm, Scheduler(svc, rm, cfg.scheduler_tick_s) | |
| def create_app(svc: Services | None = None, cfg: Settings | None = None, *, background: bool = True, transport=None) -> FastAPI: | |
| cfg = cfg or (svc.cfg if svc else get_settings()) | |
| svc = svc or build_services(cfg, transport=transport) | |
| setup_logging(logfile=cfg.path("logs", "api.jsonl")) | |
| if svc.users.bootstrap_from_env(): | |
| log.info("bootstrap admin created from FPT_BOOTSTRAP_ADMIN_USER") | |
| reset = svc.users.reset_admin_from_env() | |
| if reset: # audited, and loud: the secret should be deleted now that it has been used | |
| svc.audit.append("users.admin_password_reset", actor="server-secret", summary=f"{reset}: password reset from FPT_ADMIN_PASSWORD_RESET") | |
| log.warning("administrator %s password reset from FPT_ADMIN_PASSWORD_RESET: delete that secret now", reset) | |
| run_mgr, sched = _orchestrator(svc, cfg) | |
| async def lifespan(app: FastAPI): | |
| _error_tracking() | |
| recovered = run_mgr.recover() | |
| from ..platform import assisted_signin, liveview | |
| liveview.sweep(svc) # live-view folders left behind by a crash | |
| assisted_signin.sweep(svc) # captured sessions of runs that ended while the server was down, sign-in browser folders | |
| if recovered: | |
| log.warning("marked %d run(s) interrupted after restart", len(recovered)) | |
| try: | |
| from ..platform import left_on_pod as left | |
| left.backfill_once(svc) # test documents earlier runs left on a pod, once per database | |
| except Exception: # noqa: BLE001 | |
| log.exception("left-on-pod backfill failed") | |
| from ..platform.pods import PodRegistry | |
| cut = PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit).recover_screens() | |
| if cut: | |
| log.warning("marked the screen reading of pod(s) %s interrupted after restart", cut) | |
| syncer = None | |
| if background: | |
| run_mgr.start_worker() | |
| sched.start() | |
| from ..platform import notify | |
| notify.get(svc).start() | |
| from ..platform import watchdog | |
| if (wd := watchdog.install(svc)): # operations alerts and the dated backup (both off until switched on) | |
| wd.start() | |
| app.state.watchdog = wd | |
| from ..channels import telegram as tg_channel | |
| tg_channel.start(svc, run_mgr) # the two-way bot: listens only when the bot token is set | |
| from ..platform.agent_studio import AgentStudio, Courier | |
| AgentStudio(svc).ensure_from_env() # the Fusion tool's client survives a restart without saved state | |
| courier = Courier(svc, run_mgr, watch_hours=cfg.agent_studio_watch_hours) | |
| courier.start() # callbacks to Oracle AI Agent Studio, and the release watch | |
| app.state.courier = courier | |
| from ..platform import statesync | |
| if statesync.enabled(svc): | |
| syncer = statesync.Syncer(svc, cfg.state_sync_interval_s) | |
| syncer.start() | |
| app.state.syncer = syncer | |
| log.info("state is saved to Supabase Storage every %ss when it changes", syncer.interval) | |
| yield | |
| # Shutdown: stop taking new work, let a running run stop at its next step (bounded: the host does not wait long), | |
| # then the one last save, then everything else. Saving before the run stopped kept it as "running", so it came | |
| # back interrupted after the restart. | |
| if getattr(app.state, "courier", None): | |
| app.state.courier.stop() | |
| app.state.sign_in.close_all() # an open sign-in browser closes with the server (the run keeps waiting) | |
| sched.stop() | |
| if getattr(app.state, "watchdog", None): | |
| app.state.watchdog.stop() | |
| stop_runs = getattr(run_mgr, "stop_for_shutdown", None) # the Temporal orchestrator keeps its runs itself | |
| if stop_runs and not stop_runs(cfg.shutdown_run_wait_s): | |
| log.warning("a run step was still going after %ss: saving without it (that run comes back interrupted)", | |
| cfg.shutdown_run_wait_s) | |
| if syncer: | |
| syncer.stop() # stops the saver and makes the last save | |
| run_mgr.stop() | |
| from ..platform import notify | |
| notify.get(svc).stop() | |
| from ..channels import telegram as tg_channel | |
| tg_channel.stop(svc) | |
| app = FastAPI(title="Astra API", version=VERSION, lifespan=lifespan, | |
| description="Pilot backend. Runs against the local mock app or a registered Oracle Fusion TEST pod (never production); " | |
| "every run and report names its target.", | |
| docs_url="/api/docs" if svc.cfg.api_docs else None, redoc_url=None, | |
| openapi_url="/api/openapi.json" if svc.cfg.api_docs else None) | |
| app.state.svc, app.state.runs, app.state.scheduler, app.state.inline_worker = svc, run_mgr, sched, not background | |
| from ..platform.assisted_signin import SignInSessions | |
| app.state.sign_in = SignInSessions(svc, run_mgr) # assisted sign-in browsers (routes/signin.py) | |
| run_mgr.sign_in = app.state.sign_in # a run that ends closes its own and drops its captured session | |
| errors.install(app) | |
| # a "*" origin with credentials would let any website act as a signed-in person: never honoured | |
| origins = [o for o in cfg.cors_origins if o.strip() != "*"] | |
| if len(origins) != len(cfg.cors_origins): | |
| log.warning("FPT_CORS_ORIGINS contains '*': ignored (the API sends credentials; list the origins that may call it)") | |
| app.add_middleware(BodyLimit, limit=cfg.max_body_bytes) | |
| app.add_middleware(CORSMiddleware, allow_origins=origins, allow_credentials=True, | |
| allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE"], | |
| allow_headers=["Authorization", "Content-Type", "X-CSRF-Token", "X-Request-ID", "Last-Event-ID"], | |
| expose_headers=["X-Request-ID"]) | |
| app.add_middleware(RequestContext) | |
| api = APIRouter(prefix="/api") | |
| for r in (auth.router, runs.router, gates.router, review.router, admin.router, pods.router, screens.router, consultant.router, live.router, chat.router, assistant.router, llm.router, notifications.router, channels.router, integrations.router, tokens.router, custom_cases.router, recordings.router, heals.router, left_on_pod.router, agent_studio.router, ai_monitoring.router, signin.router): | |
| api.include_router(r) | |
| app.include_router(api) | |
| app.include_router(agent_studio.oauth) # /oauth/token: the Oracle AI Agent Studio client (docs/AGENT_STUDIO.md) | |
| app.include_router(mcp.router) # /mcp: the MCP connector (personal access tokens only; docs/MCP.md) | |
| app.include_router(a2a.router) # /a2a + /.well-known/agent-card.json: the A2A agent (same tokens; docs/A2A.md) | |
| def api_404(rest: str, request: Request): | |
| return JSONResponse({"detail": f"no such endpoint /api/{rest}", "code": "NOT_FOUND", | |
| "request_id": getattr(request.state, "request_id", None)}, status_code=404) | |
| dist = Path(cfg.web_dist) | |
| def spa(path: str): | |
| if not (dist / "index.html").exists(): | |
| return JSONResponse({"detail": "web app not built: run `fpt.cmd package` or `npm --prefix web run build`", | |
| "code": "WEB_NOT_BUILT"}, status_code=404) | |
| f = (dist / path).resolve() | |
| if path and f.is_file() and f.is_relative_to(dist.resolve()): | |
| headers = {"Cache-Control": "public, max-age=31536000, immutable"} if path.startswith("assets/") else {} | |
| return FileResponse(f, headers=headers) | |
| return FileResponse(dist / "index.html", headers={"Cache-Control": "no-cache"}) | |
| return app | |
| def app_from_env() -> FastAPI: # uvicorn factory: `uvicorn coworker.api.app:app_from_env --factory` | |
| return create_app() | |
| def _error_tracking() -> None: | |
| """Optional, Sentry-compatible error tracking: on when SENTRY_DSN is set and the sentry-sdk package is installed | |
| (not a dependency of the app). Request bodies and personal data are not sent.""" | |
| import os | |
| dsn = os.environ.get("SENTRY_DSN", "") | |
| if not dsn: | |
| return | |
| try: | |
| import sentry_sdk | |
| except ImportError: | |
| log.warning("SENTRY_DSN is set but sentry-sdk is not installed; error tracking is off") | |
| return | |
| sentry_sdk.init(dsn=dsn, send_default_pii=False, max_request_body_size="never", traces_sample_rate=0.0, | |
| environment=os.environ.get("FPT_ENVIRONMENT", "production")) | |