feat(control-station): add AI polygon setup streaming and mission controls
This commit is contained in:
@@ -43,7 +43,7 @@ const defaultQuickActions: Record<
|
||||
missions: ["routes", null],
|
||||
data: ["recordings", "datasets"],
|
||||
system: ["modules", "integrations"],
|
||||
polygon: ["lab-archive", "local-device"],
|
||||
polygon: ["observatory", "local-device"],
|
||||
};
|
||||
|
||||
export function defaultEnvironmentSettings(): EnvironmentSettings {
|
||||
@@ -140,6 +140,10 @@ function decodeBackground(value: unknown, path: string): EnvironmentBackground {
|
||||
};
|
||||
}
|
||||
|
||||
function currentQuickAction(value: string | null): string | null {
|
||||
return value === "lab-archive" ? "observatory" : value;
|
||||
}
|
||||
|
||||
function decodePage(value: unknown, path: string): EnvironmentPage {
|
||||
const record = requireRecord(value, path);
|
||||
return {
|
||||
@@ -147,16 +151,16 @@ function decodePage(value: unknown, path: string): EnvironmentPage {
|
||||
eyebrow: requireString(record.eyebrow, `${path}.eyebrow`)!,
|
||||
title: requireString(record.title, `${path}.title`)!,
|
||||
description: requireString(record.description, `${path}.description`)!,
|
||||
primaryWorkspaceId: requireString(
|
||||
primaryWorkspaceId: currentQuickAction(requireString(
|
||||
record.primary_workspace_id,
|
||||
`${path}.primary_workspace_id`,
|
||||
true,
|
||||
),
|
||||
secondaryWorkspaceId: requireString(
|
||||
)),
|
||||
secondaryWorkspaceId: currentQuickAction(requireString(
|
||||
record.secondary_workspace_id,
|
||||
`${path}.secondary_workspace_id`,
|
||||
true,
|
||||
),
|
||||
)),
|
||||
background: decodeBackground(record.background, `${path}.background`),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -87,6 +87,10 @@ export async function fetchAIModuleCatalog(signal?: AbortSignal): Promise<AIModu
|
||||
});
|
||||
const body = await bodyOf(response);
|
||||
if (!response.ok) throw apiError(body, response.status);
|
||||
return decodeAIModuleCatalog(body);
|
||||
}
|
||||
|
||||
export function decodeAIModuleCatalog(body: unknown): AIModuleCatalog {
|
||||
const root = record(body, "каталог AI-модулей");
|
||||
exactKeys(root, ["authority", "groups", "schema_version"]);
|
||||
if (root.schema_version !== CATALOG_SCHEMA) throw new Error("Версия каталога AI-модулей изменилась.");
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
import { decodeAIModuleCatalog, type AIModuleCatalog, type AIGroupId } from "../observatory/aiComposition";
|
||||
|
||||
const API = "/api/v1/ai-polygon";
|
||||
|
||||
export interface AiSelection {
|
||||
schema_version: "missioncore.observatory-ai-composition/v1";
|
||||
selections: { group: AIGroupId; module_id: string; module_sha256: string; parameters: Readonly<Record<string, unknown>> }[];
|
||||
}
|
||||
export interface AiModules { catalog: AIModuleCatalog; selection: AiSelection }
|
||||
export async function fetchAiModules(): Promise<AiModules> {
|
||||
const value = await polygonRequest<{ catalog: unknown; selection: AiSelection }>("/ai-modules");
|
||||
return { catalog: decodeAIModuleCatalog(value.catalog), selection: value.selection };
|
||||
}
|
||||
|
||||
export interface AiWorldSettings {
|
||||
meters_per_unit: number;
|
||||
rotation_degrees: [number, number, number];
|
||||
ground_z: number;
|
||||
spawn_xy: [number, number];
|
||||
heading_degrees: number;
|
||||
camera_height_m: number;
|
||||
max_speed_mps: number;
|
||||
prepared: boolean;
|
||||
route_xy?: [number, number][];
|
||||
}
|
||||
export interface AiSource {
|
||||
name: string; author: string; license: string; source_url: string | null;
|
||||
description?: string;
|
||||
}
|
||||
export interface AiWorld extends AiSource {
|
||||
world_id: string; filename: string; byte_length: number; uploaded_bytes: number;
|
||||
status: "uploading" | "available"; sha256: string | null; splat_count: number | null;
|
||||
settings: AiWorldSettings;
|
||||
}
|
||||
export interface AiRun {
|
||||
run_id: string;
|
||||
world: AiWorld;
|
||||
request?: { composition?: AiSelection };
|
||||
state: "starting" | "ready" | "running" | "paused" | "stopping" | "completed" | "stopped" | "failed" | "disconnected";
|
||||
clock?: "lockstep" | "realtime";
|
||||
control?: "play" | "pause" | "stop";
|
||||
control_sequence?: number;
|
||||
camera?: AiCamera;
|
||||
worker?: { stream?: AiStreamEndpoint | null };
|
||||
telemetry?: AiTelemetry | null;
|
||||
samples: number;
|
||||
phase?: string;
|
||||
applied_steps?: number;
|
||||
last_applied?: null | {
|
||||
sequence: number; simulation_time_ns: number; pose_xy: [number, number];
|
||||
pose_yaw?: number | null; cycle_ms?: number | null;
|
||||
};
|
||||
message: string | null;
|
||||
last_sample: null | {
|
||||
sequence: number; simulation_time_ns: number; inference_ms: number; pose_xy: [number, number];
|
||||
decision: { speed_mps: number; yaw_rate_rps: number; reason: string;
|
||||
road_fraction: number; obstacle_count: number };
|
||||
};
|
||||
}
|
||||
export type AiCamera = "follow" | "overview" | "camera";
|
||||
export interface AiStreamEndpoint {
|
||||
server: string; signaling_port: number; media_port: number; width: number; height: number; fps: number;
|
||||
}
|
||||
export interface AiTelemetry {
|
||||
sequence: number; control_sequence: number; simulation_time_ns: number;
|
||||
rtf: number; render_fps: number; sensor_fps: number; ai_hz: number;
|
||||
inference_ms: number | null; frame_age_ms: number | null; command_age_ms: number | null;
|
||||
speed_mps: number; applied_speed_mps: number; stop_reason: string;
|
||||
ai_ready: boolean; stream_ready: boolean; camera: AiCamera;
|
||||
decision: NonNullable<AiRun["last_sample"]>["decision"] | null;
|
||||
}
|
||||
export interface AiCatalog {
|
||||
sources: AiSource[]; worlds: AiWorld[]; runs: AiRun[];
|
||||
runtime: { available: boolean; active_run: AiRun | null };
|
||||
}
|
||||
|
||||
export async function polygonRequest<T>(path: string, init: RequestInit = {}): Promise<T> {
|
||||
const response = await fetch(`${API}${path}`, { ...init, headers: {
|
||||
...(typeof init.body === "string" ? { "Content-Type": "application/json" } : {}),
|
||||
...init.headers,
|
||||
} });
|
||||
if (!response.ok) {
|
||||
const body = await response.json().catch(() => null);
|
||||
throw new Error(typeof body?.detail === "string" ? body.detail : "Не удалось выполнить запрос полигона.");
|
||||
}
|
||||
return response.json() as Promise<T>;
|
||||
}
|
||||
export const runJournalUrl = (run: AiRun) => `${API}/runs/${run.run_id}/decisions`;
|
||||
export const fetchAiCatalog = () => polygonRequest<AiCatalog>("/catalog");
|
||||
export const configureAiWorld = (world: AiWorld, settings: AiWorldSettings) =>
|
||||
polygonRequest<AiWorld>(`/worlds/${world.world_id}/settings`, {
|
||||
method: "PUT", body: JSON.stringify(settings),
|
||||
});
|
||||
export const startAiRun = (world: AiWorld, composition?: AiSelection) => polygonRequest<AiRun>("/runs", {
|
||||
method: "POST", headers: { "Idempotency-Key": crypto.randomUUID() },
|
||||
body: JSON.stringify({ world_id: world.world_id, clock: "realtime", start_paused: true, duration_seconds: 1800, composition }),
|
||||
});
|
||||
export const setAiCamera = (run: AiRun, camera: AiCamera) =>
|
||||
polygonRequest<AiRun>(`/runs/${run.run_id}/view`, { method: "PUT", body: JSON.stringify({ camera }) });
|
||||
export const controlAiRun = (run: AiRun, command: "play" | "pause" | "step" | "stop") =>
|
||||
polygonRequest<AiRun>(`/runs/${run.run_id}/${command}`, { method: "POST" });
|
||||
|
||||
export async function importAiWorld(file: File, source: AiSource, progress: (value: number) => void,
|
||||
signal: AbortSignal, resume?: AiWorld, onCreated?: (world: AiWorld) => void): Promise<AiWorld> {
|
||||
if (!file.name.toLowerCase().endsWith(".ply")) throw new Error("Выберите Gaussian PLY из экспорта сцены.");
|
||||
if (resume && (file.name !== resume.filename || file.size !== resume.byte_length)) {
|
||||
throw new Error("Для продолжения выберите тот же файл.");
|
||||
}
|
||||
let world = resume ? await polygonRequest<AiWorld>(`/worlds/${resume.world_id}`, { signal })
|
||||
: await polygonRequest<AiWorld>("/worlds", { method: "POST", signal,
|
||||
body: JSON.stringify({ ...source, description: undefined, filename: file.name,
|
||||
byte_length: file.size, source_url: source.source_url || null }) });
|
||||
onCreated?.(world);
|
||||
if (world.uploaded_bytes > 0) {
|
||||
const prefix = await polygonRequest<{ uploaded_bytes: number; chunks: { byte_length: number; sha256: string }[] }>(
|
||||
`/worlds/${world.world_id}/upload-prefix`, { signal });
|
||||
let offset = 0;
|
||||
for (const chunk of prefix.chunks) {
|
||||
signal.throwIfAborted();
|
||||
const bytes = await file.slice(offset, offset + chunk.byte_length).arrayBuffer();
|
||||
const digest = Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)))
|
||||
.map((value) => value.toString(16).padStart(2, "0")).join("");
|
||||
if (digest !== chunk.sha256) throw new Error("Этот файл отличается от начатой загрузки. Выберите исходный файл.");
|
||||
offset += chunk.byte_length;
|
||||
}
|
||||
if (offset !== prefix.uploaded_bytes || offset !== world.uploaded_bytes) {
|
||||
throw new Error("Загрузка изменилась в другом окне. Повторите продолжение импорта.");
|
||||
}
|
||||
}
|
||||
const chunkSize = 4 * 1024 ** 2;
|
||||
progress(world.uploaded_bytes / file.size);
|
||||
while (world.uploaded_bytes < file.size) {
|
||||
const offset = world.uploaded_bytes;
|
||||
world = await polygonRequest<AiWorld>(`/worlds/${world.world_id}/source`, {
|
||||
method: "PATCH", signal, headers: { "Upload-Offset": String(offset) },
|
||||
body: file.slice(offset, Math.min(file.size, offset + chunkSize)),
|
||||
});
|
||||
progress(world.uploaded_bytes / file.size);
|
||||
}
|
||||
return polygonRequest<AiWorld>(`/worlds/${world.world_id}/complete`, { method: "POST", signal });
|
||||
}
|
||||
Reference in New Issue
Block a user