Preserve installed operator workspace before consolidation

Local preservation snapshot, not a new deployment or simulation acceptance.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-08 09:59:51 +03:00
parent 97614742bb
commit d0e5f90952
368 changed files with 129172 additions and 1856 deletions
+162 -11
View File
@@ -10,9 +10,15 @@ from fastapi.responses import FileResponse
from k1link.observatory.recorded_jobs import ObservatoryRecordedJobQueue
from k1link.simulation.ai_polygon.composition import compose, registry
from k1link.simulation.ai_polygon.contracts import (
InferencePreview,
LocalPlanCreate,
PlanLibraryUpdate,
PlanningCommand,
PlanSave,
RealtimeSnapshot,
RunApplied,
RunCreate,
RunLibraryUpdate,
RunProgress,
RunSample,
ViewControl,
@@ -23,6 +29,8 @@ from k1link.simulation.ai_polygon.contracts import (
WorldCreate,
WorldSettings,
)
from k1link.simulation.ai_polygon.editor_cache import EditorCache
from k1link.simulation.ai_polygon.robots import robot_catalog, select_robot
from k1link.simulation.ai_polygon.runs import RunStore
from k1link.simulation.ai_polygon.worlds import CHUNK_BYTES, SOURCES, WorldStore
@@ -32,8 +40,12 @@ def build_ai_polygon_router(
) -> APIRouter:
worlds = WorldStore(data_dir)
runs = RunStore(worlds, queue)
editor = EditorCache(data_dir, worlds)
router = APIRouter(prefix="/api/v1/ai-polygon", tags=["ai-polygon"])
adapters = Path(__file__).resolve().parents[3] / "simulation/ai-polygon"
from k1link.web.ai_profile_api import build_ai_profile_router
router.include_router(build_ai_profile_router(data_dir / "ai-polygon/ai-profiles", adapters))
def invoke(fn, *args):
try:
@@ -52,14 +64,37 @@ def build_ai_polygon_router(
@router.get("/catalog")
def catalog():
runtime = runs.status()
locations = worlds.list()
if "project-sog" not in (runtime.get("worker") or {}).get("scene_formats", []):
locations = [
{
**w,
"inference_ready": False,
"inference_message": "Для inference этой локации требуется обновление Worker.",
}
if w.get("local_scene")
else w
for w in locations
]
return {
"schema_version": "missioncore.ai-polygon-catalog/v1",
"sources": SOURCES,
"worlds": worlds.list(),
"runtime": runs.status(),
"runs": runs.list()[:30],
"robots": robot_catalog(adapters),
"worlds": locations,
"runtime": runtime,
"runs": runs.library.visible(runs.list(), "run_id")[:30],
"plans": runs.plans.visible_list(),
}
@router.get("/worker/worlds/{world_id}/project-assets")
def project_assets(world_id: str, authorization: str | None = Header(default=None)):
authenticate(authorization)
world = invoke(worlds.get, world_id)
if not world.get("local_scene"):
raise HTTPException(400, "Локация не является Gaussian-проектом.")
return invoke(worlds.projects.package, world)
@router.post("/worlds", status_code=201)
def create_world(body: WorldCreate):
return invoke(worlds.create, body)
@@ -107,12 +142,67 @@ def build_ai_polygon_router(
},
)
@router.post("/worlds/{world_id}/editor-cache")
def prepare_editor(world_id: str):
return invoke(editor.request, world_id)
@router.get("/editor-cache/{key}")
def editor_status(key: str):
return invoke(editor.get, key)
@router.get("/editor-cache/{key}/{name}")
def editor_asset(key: str, name: str):
path, digest = invoke(editor.asset, key, name)
return FileResponse(
path,
headers={
"ETag": f'"{digest}"',
"Cache-Control": "private, max-age=31536000, immutable",
},
)
@router.post("/plans", status_code=201)
def local_plan(body: LocalPlanCreate):
with runs.lock:
cached = invoke(editor.get, body.cache_key)
world = invoke(worlds.get, cached["world"]["world_id"])
if cached["status"] != "ready" or editor.identity(world) != cached["identity"]:
raise HTTPException(409, "Локация изменилась. Откройте планирование заново.")
robot = invoke(select_robot, body.robot_id, body.robot_sha256)
context = {"world": world, "robot": robot, "run_id": None}
return invoke(
lambda: runs.plans.create(
context,
body.name,
[p.model_dump() for p in body.points],
body.sequence,
draft_id=body.draft_id,
cache_key=body.cache_key,
editor_collider_sha256=cached["files"]["collision.glb"]["sha256"],
)
)
@router.patch("/plans/{plan_id}")
def update_plan(plan_id: str, body: PlanLibraryUpdate):
return invoke(runs.update_library, "plans", plan_id, body.model_dump(exclude_none=True))
@router.patch("/runs/{run_id}")
def update_run(run_id: str, body: RunLibraryUpdate):
return invoke(runs.update_library, "runs", run_id, body.model_dump())
@router.post("/runs", status_code=201)
def start(body: RunCreate, idempotency_key: str = Header(alias="Idempotency-Key")):
if editor.pending():
raise HTTPException(409, "Дождитесь загрузки локальной сцены.")
if body.clock == "realtime":
graph = invoke(compose, adapters, body.composition)
body = body.model_copy(update={"composition": graph.selection_document()})
return invoke(runs.start, body, idempotency_key)
return invoke(
lambda: runs.start(
body, idempotency_key,
composition_sha256=graph.sha256 if body.clock == "realtime" else None,
)
)
@router.get("/ai-modules")
def modules():
@@ -129,10 +219,6 @@ def build_ai_polygon_router(
runs.status()
return invoke(runs.get, run_id)
@router.post("/runs/{run_id}/{command}")
def control(run_id: str, command: Literal["pause", "play", "step", "stop"]):
return invoke(runs.control, run_id, command)
@router.get("/runs/{run_id}/frames/{sequence}.jpg")
def frame(run_id: str, sequence: int):
row = invoke(runs.get, run_id)
@@ -144,9 +230,37 @@ def build_ai_polygon_router(
headers={"Cache-Control": "private, max-age=31536000, immutable"},
)
@router.get("/runs/{run_id}/inference-preview")
def inference_preview(run_id: str, response: Response):
response.headers["Cache-Control"] = "no-store"
return invoke(runs.inference_preview, run_id)
@router.post("/worker/runs/{run_id}/inference-preview")
def publish_inference_preview(
run_id: str,
body: InferencePreview,
instance_id: str = Header(alias="Worker-Instance"),
authorization: str | None = Header(default=None),
):
authenticate(authorization)
return invoke(runs.inference_preview, run_id, instance_id, body)
@router.put("/runs/{run_id}/view")
def view(run_id: str, body: ViewControl):
return invoke(runs.view, run_id, body.camera)
row = invoke(runs.view, run_id, body.camera, body.navigation)
return {"accepted": body.navigation.sequence} if body.navigation else row
@router.put("/runs/{run_id}/planning")
def planning(run_id: str, body: PlanningCommand):
return invoke(runs.planning_command, run_id, body)
@router.post("/runs/{run_id}/plan")
def save_plan(run_id: str, body: PlanSave):
return invoke(runs.save_plan, run_id, body)
@router.post("/runs/{run_id}/{command}")
def control(run_id: str, command: Literal["pause", "play", "step", "stop"]):
return invoke(runs.control, run_id, command)
@router.get("/runs/{run_id}/decisions")
def decisions(run_id: str):
@@ -181,7 +295,42 @@ def build_ai_polygon_router(
@router.post("/worker/poll")
def poll(body: WorkerPoll, authorization: str | None = Header(default=None)):
authenticate(authorization)
return invoke(runs.poll, body.instance_id, body.run_id)
value = invoke(runs.poll, body.instance_id, body.run_id)
if value["action"] == "idle":
pending = editor.pending()
if pending:
if runs.queue is None:
return value
try:
runs.queue.reserve_simulation("aicache-" + pending["key"])
except RuntimeError:
return value
return {"action": "editor-cache", "cache": pending}
return value
@router.post("/worker/editor-cache/{key}")
async def upload_editor(
key: str,
request: Request,
authorization: str | None = Header(default=None),
instance_id: str = Header(alias="Worker-Instance"),
):
authenticate(authorization)
invoke(runs.heartbeat, instance_id)
raw = bytearray()
async for block in request.stream():
raw.extend(block)
if len(raw) > 1024 * 1024:
raise HTTPException(413, "Editor transfer chunk too large")
import json
body = json.loads(raw)
if body.get("action") == "release":
invoke(editor.get, key)
if runs.queue is not None:
invoke(runs.queue.release_simulation, "aicache-" + key)
return {"released": True}
return invoke(editor.update, key, body)
@router.post("/worker/runs/{run_id}/progress")
def progress(
@@ -216,7 +365,9 @@ def build_ai_polygon_router(
@router.post("/worker/runs/{run_id}/finish")
def finish(run_id: str, body: WorkerResult, authorization: str | None = Header(default=None)):
authenticate(authorization)
return invoke(runs.finish, run_id, body.instance_id, body.outcome, body.message)
return invoke(
runs.finish, run_id, body.instance_id, body.outcome, body.message, body.report
)
@router.post("/worker/runs/{run_id}/applied")
def applied(
+49
View File
@@ -0,0 +1,49 @@
"""AI preset library; no authority to launch or modify a running simulation."""
from fastapi import APIRouter, HTTPException
from pydantic import Field
from k1link.simulation.ai_polygon.ai_profiles import AiProfileStore
from k1link.simulation.ai_polygon.contracts import Contract
class ProfileCreate(Contract):
name: str = Field(min_length=1, max_length=120)
composition: dict
class ProfileUpdate(Contract):
expected_revision: int = Field(ge=1)
name: str | None = Field(default=None, min_length=1, max_length=120)
composition: dict | None = None
removed: bool = False
def build_ai_profile_router(root, adapters):
store = AiProfileStore(root, adapters)
router = APIRouter(prefix="/ai-profiles")
def invoke(fn, *args, **kwargs):
try:
return fn(*args, **kwargs)
except FileNotFoundError as exc:
raise HTTPException(404, "Профиль AI не найден.") from exc
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
except RuntimeError as exc:
raise HTTPException(409, str(exc)) from exc
@router.get("")
def profiles():
return invoke(store.list)
@router.post("", status_code=201)
def create(body: ProfileCreate):
return invoke(store.save, body.name, body.composition)
@router.patch("/{identity}")
def update(identity: str, body: ProfileUpdate):
return invoke(store.save, body.name, body.composition, identity=identity,
expected_revision=body.expected_revision, removed=body.removed)
return router