Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

Migrate Cyclops CS to the UniFFI SDK (#6358)

r33drichards7ac74a6ae014
diff --git a/libs/fleet/.dockerignore b/libs/fleet/.dockerignore
index 9766ae2e7a..e5b96c1847 100644
--- a/libs/fleet/.dockerignore
+++ b/libs/fleet/.dockerignore
@@ -1,5 +1,9 @@
node_modules
dist
+target
+sdk-bindings/ts-uniffi-browser/node_modules
+sdk-bindings/ts-uniffi-browser/examples/dist
+sdk-bindings/ts-uniffi-browser/ts/wasm-bindgen
.git
*.log
README.md
diff --git a/libs/fleet/Dockerfile b/libs/fleet/Dockerfile
index 14b57d29fa..cb977db2de 100644
--- a/libs/fleet/Dockerfile
+++ b/libs/fleet/Dockerfile
@@ -1,3 +1,17 @@
+FROM node:20-bookworm AS sdk-builder
+WORKDIR /workspace/cyclops-cs
+
+RUN apt-get update \
+ && apt-get install --yes --no-install-recommends build-essential curl pkg-config \
+ && rm -rf /var/lib/apt/lists/* \
+ && curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \
+ | sh -s -- -y --profile minimal --default-toolchain 1.97.0
+
+ENV PATH="/root/.cargo/bin:${PATH}"
+
+COPY . .
+RUN ./scripts/build-browser-sdk-binding.sh
+
# Build stage — produces /app/dist (Vite output).
FROM node:20-alpine AS builder
WORKDIR /app
@@ -7,13 +21,15 @@ RUN corepack enable && corepack prepare [email protected] --activate
# Install deps first (better layer caching). patches/ must be present before
# install so pnpm can apply pnpm.patchedDependencies (e.g. the @novnc BGR fix).
-COPY package.json pnpm-lock.yaml ./
+COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY patches ./patches
-RUN pnpm install --frozen-lockfile --ignore-workspace
+RUN pnpm install --frozen-lockfile
# Build.
COPY . .
-RUN pnpm build
+COPY --from=sdk-builder /workspace/cyclops-cs/sdk-bindings/ts-uniffi-browser/ts/index.web.ts ./sdk-bindings/ts-uniffi-browser/ts/index.web.ts
+COPY --from=sdk-builder /workspace/cyclops-cs/sdk-bindings/ts-uniffi-browser/ts/wasm-bindgen ./sdk-bindings/ts-uniffi-browser/ts/wasm-bindgen
+RUN pnpm build:app
# Runtime stage — nginx serves static files and proxies /api to the backend.
FROM nginx:1.27-alpine AS runtime
diff --git a/libs/fleet/backend/handlers/user_keys_test.go b/libs/fleet/backend/handlers/user_keys_test.go
index ccd640a599..fc1f9c8000 100644
--- a/libs/fleet/backend/handlers/user_keys_test.go
+++ b/libs/fleet/backend/handlers/user_keys_test.go
@@ -12,6 +12,48 @@ import (
"cyclops-cs-backend/keycloak"
)
+func TestListUserKeysSerializesEmptyScopeAsArray(t *testing.T) {
+ keycloakServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/realms/cyclops-cs/protocol/openid-connect/token":
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"access_token":"admin-token","token_type":"Bearer","expires_in":300}`))
+ case "/admin/realms/cyclops-cs/clients":
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`[{"id":"key-id","clientId":"ukey-demo","name":"demo key","attributes":{"managed_by":"cyclops-cs-backend","key_type":"user","owner_sub":"user-123","scope":""}}]`))
+ default:
+ t.Fatalf("unexpected Keycloak request: %s %s", r.Method, r.URL.Path)
+ }
+ }))
+ defer keycloakServer.Close()
+
+ h := Handlers{
+ Admin: keycloak.NewAdmin(keycloakServer.URL, "cyclops-cs", "admin-client", "admin-secret", "key-", "ukey-"),
+ }
+ r := httptest.NewRequest(http.MethodGet, "/api/user-keys", nil)
+ r = withUser(r, &auth.User{ID: "user-123"})
+ w := httptest.NewRecorder()
+
+ h.ListUserKeys(w, r)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String())
+ }
+ var response ListUserKeysResponse
+ if err := json.NewDecoder(w.Body).Decode(&response); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if len(response.Keys) != 1 {
+ t.Fatalf("keys = %d, want 1", len(response.Keys))
+ }
+ if response.Keys[0].Scope == nil {
+ t.Fatalf("scope = nil, want empty array")
+ }
+ if len(response.Keys[0].Scope) != 0 {
+ t.Fatalf("scope = %v, want empty array", response.Keys[0].Scope)
+ }
+}
+
func TestCreateUserKeyReturnsConfiguredPublicTokenURL(t *testing.T) {
var keycloakServer *httptest.Server
keycloakServer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
diff --git a/libs/fleet/backend/keycloak/admin.go b/libs/fleet/backend/keycloak/admin.go
index 159c130d65..cbdbae8813 100644
--- a/libs/fleet/backend/keycloak/admin.go
+++ b/libs/fleet/backend/keycloak/admin.go
@@ -366,7 +366,7 @@ func (a *Admin) ListUserKeyClients(ctx context.Context, ownerSub string) ([]User
if attrs["managed_by"] != "cyclops-cs-backend" || attrs["key_type"] != "user" || attrs["owner_sub"] != ownerSub {
continue
}
- var scope []string
+ scope := []string{}
if s := attrs["scope"]; s != "" {
scope = strings.Split(s, ",")
}
diff --git a/libs/fleet/biome.json b/libs/fleet/biome.json
index df3dd30a83..ad41692eae 100644
--- a/libs/fleet/biome.json
+++ b/libs/fleet/biome.json
@@ -2,14 +2,9 @@
"$schema": "https://biomejs.dev/schemas/2.4.15/schema.json",
"vcs": { "enabled": false, "clientKind": "git", "useIgnoreFile": false },
"files": {
- "includes": ["src/**", "!**/dist", "!**/node_modules", "!src/api/generated/**"]
+ "includes": ["src/**", "!**/dist", "!**/node_modules"]
},
- "overrides": [
- {
- "includes": ["src/api/generated/**"],
- "linter": { "enabled": false }
- }
- ],
+ "overrides": [],
"formatter": { "enabled": false },
"assist": { "actions": { "source": { "organizeImports": "off" } } },
"linter": {
diff --git a/libs/fleet/e2e/fixtures/mock-api.ts b/libs/fleet/e2e/fixtures/mock-api.ts
index de6c028aea..0b4852e601 100644
--- a/libs/fleet/e2e/fixtures/mock-api.ts
+++ b/libs/fleet/e2e/fixtures/mock-api.ts
@@ -100,14 +100,6 @@ export async function mockAuth(page: Page): Promise<void> {
})
})
- // Mock the /api/config endpoint (feature flags)
- await page.route("**/api/config", (route) =>
- route.fulfill({
- contentType: "application/json",
- body: JSON.stringify({ admin: false }),
- }),
- )
-
// Intercept any stray Keycloak endpoint requests
await page.route("**/realms/cyclops-cs/**", (route) =>
route.fulfill({ status: 200, contentType: "application/json", body: "{}" }),
@@ -127,7 +119,7 @@ export interface MockNamespace {
const DEFAULT_NAMESPACES: MockNamespace[] = [
{
- name: "my-workspace",
+ name: "demo-pool",
status: "Active",
createdAt: "2026-01-15T10:00:00Z",
labels: null,
@@ -257,49 +249,86 @@ export async function mockUserKeysApi(
// ---------------------------------------------------------------------------
export async function mockPoolsApi(page: Page): Promise<void> {
- // List pools: GET /api/k8s/apis/cua.ai/v1/osgymworkspacepools
- await page.route("**/api/k8s/apis/cua.ai/v1/osgymworkspacepools", async (route) => {
- if (route.request().method() === "GET") {
- await route.fulfill({
- contentType: "application/json",
- body: JSON.stringify({
- items: [
- {
- metadata: { name: "demo-pool", namespace: "my-workspace" },
- spec: { replicas: 2 },
- status: { phase: "Ready", availableCount: 2 },
- },
- ],
- }),
- })
- } else {
- await route.continue()
- }
- })
+ const pool = {
+ apiVersion: "osgym.cua.ai/v1alpha1",
+ kind: "OSGymSandboxWarmPool",
+ metadata: { name: "demo-pool", namespace: "demo-pool" },
+ spec: {
+ replicas: 2,
+ sandboxTemplateRef: { name: "demo-pool-template" },
+ },
+ status: { replicas: 2, readyReplicas: 2 },
+ }
+ const template = {
+ apiVersion: "osgym.cua.ai/v1alpha1",
+ kind: "OSGymSandboxTemplate",
+ metadata: { name: "demo-pool-template", namespace: "demo-pool" },
+ spec: {
+ vmTemplate: {
+ containerDiskImage: "test-image:latest",
+ cpuCores: 4,
+ memory: "4Gi",
+ services: [],
+ },
+ },
+ }
- // Create pool: POST /api/k8s/apis/cua.ai/v1/namespaces/*/osgymworkspacepools
await page.route(
- "**/api/k8s/apis/cua.ai/v1/namespaces/*/osgymworkspacepools",
+ "**/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/*/osgymsandboxwarmpools",
async (route) => {
- if (route.request().method() === "POST") {
+ const namespace = route.request().url().split("/namespaces/")[1].split("/")[0]
+ if (route.request().method() === "GET") {
+ await route.fulfill({
+ contentType: "application/json",
+ body: JSON.stringify({ items: namespace === "demo-pool" ? [pool] : [] }),
+ })
+ } else if (route.request().method() === "POST") {
const body = route.request().postDataJSON()
await route.fulfill({
status: 201,
contentType: "application/json",
- body: JSON.stringify({
- metadata: {
- name: body.metadata.name,
- namespace: route.request().url().split("/namespaces/")[1].split("/")[0],
- },
- spec: body.spec,
- status: { phase: "Provisioning" },
- }),
+ body: JSON.stringify({ ...body, status: { replicas: body.spec.replicas } }),
+ })
+ } else {
+ await route.continue()
+ }
+ },
+ )
+
+ await page.route(
+ "**/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/demo-pool/osgymsandboxwarmpools/demo-pool",
+ async (route) => {
+ if (route.request().method() === "GET") {
+ await route.fulfill({ contentType: "application/json", body: JSON.stringify(pool) })
+ } else if (route.request().method() === "DELETE") {
+ await route.fulfill({ status: 204, body: "" })
+ } else {
+ await route.continue()
+ }
+ },
+ )
+
+ await page.route(
+ "**/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/*/osgymsandboxtemplates",
+ async (route) => {
+ if (route.request().method() === "POST") {
+ await route.fulfill({
+ status: 201,
+ contentType: "application/json",
+ body: route.request().postData() ?? "{}",
})
} else {
await route.continue()
}
},
)
+
+ await page.route(
+ "**/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/demo-pool/osgymsandboxtemplates/demo-pool-template",
+ async (route) => {
+ await route.fulfill({ contentType: "application/json", body: JSON.stringify(template) })
+ },
+ )
}
// ---------------------------------------------------------------------------
@@ -316,14 +345,16 @@ export async function mockClaimsApi(page: Page): Promise<void> {
body: JSON.stringify({
items: [
{
+ apiVersion: "osgym.cua.ai/v1alpha1",
+ kind: "OSGymSandboxClaim",
metadata: {
name: "claim-abc123",
- namespace: "pool-demo-pool",
+ namespace: "demo-pool",
creationTimestamp: "2026-05-28T10:00:00Z",
},
spec: {
sandboxTemplateRef: { name: "demo-pool-template" },
- warmpool: "default",
+ warmpool: "demo-pool",
},
status: {
phase: "Bound",
@@ -342,9 +373,11 @@ export async function mockClaimsApi(page: Page): Promise<void> {
status: 201,
contentType: "application/json",
body: JSON.stringify({
+ apiVersion: "osgym.cua.ai/v1alpha1",
+ kind: "OSGymSandboxClaim",
metadata: {
name: body.metadata.name,
- namespace: "pool-demo-pool",
+ namespace: "demo-pool",
creationTimestamp: new Date().toISOString(),
},
spec: body.spec,
diff --git a/libs/fleet/e2e/pools.spec.ts b/libs/fleet/e2e/pools.spec.ts
index 8cb0617c21..16e04ced7f 100644
--- a/libs/fleet/e2e/pools.spec.ts
+++ b/libs/fleet/e2e/pools.spec.ts
@@ -33,7 +33,6 @@ test.describe("Pool creation", () => {
// Services section has an "Add service" button
await expect(page.getByRole("button", { name: "Add service" })).toBeVisible()
})
-
})
test.describe("Pool duplication", () => {
@@ -52,28 +51,38 @@ test.describe("Pool duplication", () => {
// Source pool with a NON-default resource spec (defaults are cpu 4,
// ram 4Gi, the ECR image, replicas 1, no services).
const sourcePool = {
- metadata: { name: "demo-pool", namespace: "my-workspace" },
+ apiVersion: "osgym.cua.ai/v1alpha1",
+ kind: "OSGymSandboxWarmPool",
+ metadata: { name: "demo-pool", namespace: "demo-pool" },
spec: {
replicas: 3,
- template: {
+ sandboxTemplateRef: { name: "demo-pool-template" },
+ },
+ status: { replicas: 3, readyReplicas: 3 },
+ }
+ const sourceTemplate = {
+ apiVersion: "osgym.cua.ai/v1alpha1",
+ kind: "OSGymSandboxTemplate",
+ metadata: { name: "demo-pool-template", namespace: "demo-pool" },
+ spec: {
+ vmTemplate: {
containerDiskImage: "custom-image:v1",
cpuCores: 8,
memory: "16Gi",
+ services: [{ name: "api", targetPort: 8080, protocol: "TCP" }],
},
- services: [{ name: "api", targetPort: 8080, protocol: "TCP" }],
},
- status: { phase: "Ready", totalCount: 3, availableCount: 3, claimedCount: 0 },
}
// listPools() iterates the user's namespaces and lists pools in each.
await page.route(
- "**/api/k8s/apis/cua.ai/v1/namespaces/*/osgymworkspacepools",
+ "**/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/*/osgymsandboxwarmpools",
async (route) => {
if (route.request().method() !== "GET") return route.continue()
const ns = route.request().url().split("/namespaces/")[1].split("/")[0]
await route.fulfill({
contentType: "application/json",
- body: JSON.stringify({ items: ns === "my-workspace" ? [sourcePool] : [] }),
+ body: JSON.stringify({ items: ns === "demo-pool" ? [sourcePool] : [] }),
})
},
)
@@ -81,7 +90,7 @@ test.describe("Pool duplication", () => {
// Single-pool GET — where a correct duplicate flow would read the full
// spec. Registered after the list route so it wins for this exact path.
await page.route(
- "**/api/k8s/apis/cua.ai/v1/namespaces/my-workspace/osgymworkspacepools/demo-pool",
+ "**/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/demo-pool/osgymsandboxwarmpools/demo-pool",
async (route) => {
await route.fulfill({
contentType: "application/json",
@@ -89,6 +98,15 @@ test.describe("Pool duplication", () => {
})
},
)
+ await page.route(
+ "**/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/demo-pool/osgymsandboxtemplates/demo-pool-template",
+ async (route) => {
+ await route.fulfill({
+ contentType: "application/json",
+ body: JSON.stringify(sourceTemplate),
+ })
+ },
+ )
await page.goto("/pools")
@@ -125,35 +143,7 @@ test.describe("Pool detail with claims", () => {
await mockPoolsApi(page)
await mockClaimsApi(page)
- // Mock the getPool endpoint for a specific pool
- await page.route(
- "**/api/k8s/apis/cua.ai/v1/namespaces/my-workspace/osgymworkspacepools/demo-pool",
- async (route) => {
- await route.fulfill({
- contentType: "application/json",
- body: JSON.stringify({
- metadata: { name: "demo-pool", namespace: "my-workspace" },
- spec: {
- replicas: 2,
- template: {
- containerDiskImage: "test-image:latest",
- cpuCores: 4,
- memory: "4Gi",
- },
- services: [],
- },
- status: {
- phase: "Ready",
- totalCount: 2,
- availableCount: 1,
- claimedCount: 1,
- },
- }),
- })
- },
- )
-
- await page.goto("/pools/my-workspace/demo-pool")
+ await page.goto("/pools/demo-pool/demo-pool")
// The pool name should be shown
await expect(page.getByRole("heading", { name: "demo-pool" })).toBeVisible()
@@ -167,7 +157,32 @@ test.describe("Pool detail with claims", () => {
).toBeVisible()
// The existing mock claim should be listed
- await expect(page.getByText("claim-abc123")).toBeVisible()
+ const claimRow = page.getByRole("row").filter({ hasText: "claim-abc123" })
+ await expect(claimRow).toBeVisible()
await expect(page.getByText("Bound")).toBeVisible()
+ await expect(claimRow.getByRole("cell").nth(3)).not.toHaveText("-")
+ })
+})
+
+test.describe("Retired navigation", () => {
+ test("does not expose removed admin and runtime surfaces", async ({ page }) => {
+ await mockAuth(page)
+ await mockNamespacesApi(page)
+ await mockPoolsApi(page)
+
+ await page.goto("/pools")
+
+ await expect(page.getByRole("link", { name: "Nodes" })).toHaveCount(0)
+ await expect(page.getByRole("link", { name: "Operator events" })).toHaveCount(0)
+ await expect(page.getByRole("link", { name: "API keys", exact: true })).toHaveCount(0)
+ await expect(page.getByRole("link", { name: "User API keys" })).toBeVisible()
+ await expect(page.getByRole("link", { name: "Settings" })).toBeVisible()
+
+ for (const route of ["/nodes", "/operator-events", "/operator-logs", "/api-keys"]) {
+ await page.goto(route)
+ await expect(
+ page.getByRole("heading", { name: /nodes|events|logs|api keys/i }),
+ ).toHaveCount(0)
+ }
})
})
diff --git a/libs/fleet/e2e/sdk-models.unit.ts b/libs/fleet/e2e/sdk-models.unit.ts
new file mode 100644
index 0000000000..effeb16161
--- /dev/null
+++ b/libs/fleet/e2e/sdk-models.unit.ts
@@ -0,0 +1,28 @@
+import { deriveWarmPoolPhase } from "../src/sdk/status.js"
+
+function assertEqual<T>(actual: T, expected: T, message: string): void {
+ if (actual !== expected) {
+ throw new Error(`${message}: expected ${String(expected)}, got ${String(actual)}`)
+ }
+}
+
+assertEqual(
+ deriveWarmPoolPhase(0, { replicas: 0, readyReplicas: 0 }),
+ "Ready",
+ "a reconciled zero-sized pool is healthy",
+)
+assertEqual(
+ deriveWarmPoolPhase(0, undefined),
+ "Provisioning",
+ "a pool without observed status is still provisioning",
+)
+assertEqual(
+ deriveWarmPoolPhase(2, { replicas: 2, readyReplicas: 1 }),
+ "Provisioning",
+ "a partially ready pool is provisioning",
+)
+assertEqual(
+ deriveWarmPoolPhase(2, { replicas: 2, readyReplicas: 2 }),
+ "Ready",
+ "a fully ready pool is healthy",
+)
diff --git a/libs/fleet/e2e/user-keys.spec.ts b/libs/fleet/e2e/user-keys.spec.ts
index d917302c46..0585084031 100644
--- a/libs/fleet/e2e/user-keys.spec.ts
+++ b/libs/fleet/e2e/user-keys.spec.ts
@@ -25,6 +25,31 @@ test.describe("User API keys", () => {
await expect(page.getByText("sa-testuser-mykey")).toBeVisible()
})
+ test("renders keys when the backend returns a null scope", async ({ page }) => {
+ await page.unroute("**/api/user-keys")
+ await page.route("**/api/user-keys", (route) =>
+ route.fulfill({
+ contentType: "application/json",
+ body: JSON.stringify({
+ keys: [
+ {
+ id: "key-1",
+ client_id: "sa-testuser-mykey",
+ name: "my-key",
+ scope: null,
+ },
+ ],
+ }),
+ }),
+ )
+
+ await page.goto("/user-keys")
+
+ await expect(page.getByText("Error: SdkError.Body")).not.toBeVisible()
+ await expect(page.getByText("my-key")).toBeVisible()
+ await expect(page.getByText("sa-testuser-mykey")).toBeVisible()
+ })
+
test("shows the create key form", async ({ page }) => {
await page.goto("/user-keys")
diff --git a/libs/fleet/package.json b/libs/fleet/package.json
index 721dc0ccba..6de3dbdf4a 100644
--- a/libs/fleet/package.json
+++ b/libs/fleet/package.json
@@ -4,21 +4,24 @@
"version": "0.0.1",
"type": "module",
"scripts": {
- "dev": "vite",
- "build": "tsc -b && vite build",
+ "sdk:browser": "./scripts/ensure-browser-sdk-binding.sh",
+ "dev": "npm run sdk:browser && vite",
+ "build": "npm run sdk:browser && npm run build:app",
+ "build:app": "tsc -b && vite build",
"preview": "vite preview",
- "typecheck": "tsc -b --noEmit",
+ "typecheck": "npm run sdk:browser && tsc -b --noEmit",
"lint": "biome check",
"lint:fix": "biome check --write",
- "test:e2e": "playwright test",
- "test:e2e:ui": "playwright test --ui",
- "gen:api": "swagger-typescript-api generate -p ./backend/docs/swagger.json -o ./src/api/generated -n cyclops-cs-backend.ts --module-name-index 1 --extract-request-body --extract-request-params --extract-response-body --extract-response-error"
+ "test:e2e": "npm run sdk:browser && playwright test",
+ "test:e2e:ui": "npm run sdk:browser && playwright test --ui",
+ "test:sdk-models": "rm -rf target/sdk-model-tests && tsc e2e/sdk-models.unit.ts src/sdk/status.ts --target ES2022 --module NodeNext --moduleResolution NodeNext --outDir target/sdk-model-tests --skipLibCheck && node target/sdk-model-tests/e2e/sdk-models.unit.js"
},
"dependencies": {
"@cloudscape-design/collection-hooks": "^1.0.93",
"@cloudscape-design/components": "^3.0.825",
"@cloudscape-design/global-styles": "^1.0.36",
"@novnc/novnc": "^1.7.0",
+ "@ubjs/core": "0.31.0-3",
"ansi-to-html": "^0.7.2",
"keycloak-js": "^25.0.6",
"react": "^18.3.1",
@@ -31,13 +34,7 @@
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^4.3.4",
- "swagger-typescript-api": "13.2.7",
"typescript": "^5.7.2",
"vite": "^5.4.11"
- },
- "pnpm": {
- "patchedDependencies": {
- "@novnc/[email protected]": "patches/@[email protected]"
- }
}
}
diff --git a/libs/fleet/playwright.config.ts b/libs/fleet/playwright.config.ts
index 9fd838cbd7..4547de7778 100644
--- a/libs/fleet/playwright.config.ts
+++ b/libs/fleet/playwright.config.ts
@@ -9,7 +9,7 @@ export default defineConfig({
headless: true,
},
webServer: {
- command: "pnpm dev",
+ command: "npm run dev",
port: 5180,
reuseExistingServer: true,
timeout: 30_000,
diff --git a/libs/fleet/pnpm-lock.yaml b/libs/fleet/pnpm-lock.yaml
index 9fde5564ed..596e36af5e 100644
--- a/libs/fleet/pnpm-lock.yaml
+++ b/libs/fleet/pnpm-lock.yaml
@@ -25,6 +25,9 @@ importers:
'@novnc/novnc':
specifier: ^1.7.0
version: 1.7.0(patch_hash=c119c00d14c51f940f1ebed4fe41ad2fe1358c63e1095baa39d11d696b66dbff)
+ '@ubjs/core':
+ specifier: 0.31.0-3
+ version: 0.31.0-3
ansi-to-html:
specifier: ^0.7.2
version: 0.7.2
@@ -56,9 +59,6 @@ importers:
'@vitejs/plugin-react':
specifier: ^4.3.4
version: 4.7.0([email protected])
- swagger-typescript-api:
- specifier: 13.2.7
- version: 13.2.7
typescript:
specifier: ^5.7.2
version: 5.9.3
@@ -208,23 +208,6 @@ packages:
cpu: [x64]
os: [win32]
- '@biomejs/[email protected]':
- resolution: {integrity: sha512-69OfQ7+09AtiCIg+k+aU3rEsGit5o/SJWCS3BeBH/2nJYdJGi0cIx+ybka8i1EK69aNcZxYO1y1iAAEmYMq1HA==}
- peerDependencies:
- '@biomejs/wasm-bundler': ^2.0.0
- '@biomejs/wasm-nodejs': ^2.0.0
- '@biomejs/wasm-web': ^2.0.0
- peerDependenciesMeta:
- '@biomejs/wasm-bundler':
- optional: true
- '@biomejs/wasm-nodejs':
- optional: true
- '@biomejs/wasm-web':
- optional: true
-
- '@biomejs/[email protected]':
- resolution: {integrity: sha512-pihpBMylewgDdGFZHRkgmc3OajuGIJPXhvfYuKCNK/CWyJMrYEFmPKs8Iq1kY0sYMmGlTbD4K2udV03KYa+r0Q==}
-
'@cloudscape-design/[email protected]':
resolution: {integrity: sha512-77khCT0cwxxEddRxfsvuZNlrlu/Qk2CNPm+tMsMTXoL1/n4mrDKQh/AA0sbnvCga7m4g9xS3kW27RfN1H9eu1Q==}
peerDependencies:
@@ -409,9 +392,6 @@ packages:
cpu: [x64]
os: [win32]
- '@exodus/[email protected]':
- resolution: {integrity: sha512-5Aap/GaRupgNx/feGBwLLTVv8OQFfv3pq2lPRzPg9R+IOBnDgghTGW7l7EuVXOvg5cc/xSAlRW8rBrjIC3Nvqw==}
-
'@formatjs/[email protected]':
resolution: {integrity: sha512-HJnTFeRM2kVFVr5gr5kH1XP6K0JcJtE7Lzvtr3FS/so5f1kpsqqqxy5JF+FRaO6H2qmcMfAUIox7AJteieRtVw==}
@@ -612,8 +592,8 @@ packages:
resolution: {integrity: sha512-z9VXpC7MWrhfWipitjNdgCauoMLRdIILQsAEV+ZesIzBq/oUlxk0m3ApZuMFCXdnS4U7KrI+l3WRUEGQ8K1QKw==}
- '@types/[email protected]':
- resolution: {integrity: sha512-T92Xav+Gf/Ik1uPW581nA+JftmjWPgskw/WBf4TJzxRG/SJ+DfNnNE+WuZ4mrXuzflQMqMkm1LSYjzYW7MB1Cg==}
+ resolution: {integrity: sha512-39XrJgUZ2VVb561sSnkXPhczNoeBsNiSRArecsV0JE7CJq69ajFkcn9/tBAUS2NpgHkLIDU+z6Ks2+1wXnboxg==}
'@vitejs/[email protected]':
resolution: {integrity: sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==}
@@ -624,22 +604,11 @@ packages:
resolution: {integrity: sha512-L1ddibQ7F3vyXR2k2fg+I8TQTPWVA6CKeDQr/h2+8CeyTp3W6EQL8xNFZRTztuP8xNOAqL3IYPqdzs31GCjDvg==}
- resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==}
- engines: {node: '>=8'}
-
- resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==}
- engines: {node: '>=8'}
-
resolution: {integrity: sha512-v6MqmEpNlxF+POuyhKkidusCHWWkaLcGRURzivcU3I9tv7k4JVhFcnukrM5Rlk2rUywdZuzYAZ+kbZqWCnfN3g==}
engines: {node: '>=8.0.0'}
hasBin: true
- resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==}
-
resolution: {integrity: sha512-Ic44hnOtFIgravCunj1ifSoQPSUrkNiJuH9Mf6jr2jjoA74icqV8wU0KuadXeOR8zuIJMOoTv0GuQjZ9ZYNMeA==}
engines: {node: '>=6.0.0'}
@@ -650,49 +619,13 @@ packages:
engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}
hasBin: true
- resolution: {integrity: sha512-cM0ApFQSBXuourJejzwv/AuPRvAxordTyParRVcHjjtXirtkzM0uK2L9TTn9s0cXZbG7E55jCivRQzoxYmRAlA==}
- peerDependencies:
- magicast: '*'
- peerDependenciesMeta:
- magicast:
- optional: true
-
- resolution: {integrity: sha512-HpX65o1Hnr9HH25ojC1YGs7HCQLq0GCOibSaWER0eNpgJ/Z1MZv2mTc7+xh6WOPxbRVcmgbv4hGU+uSQ/2xFZQ==}
-
resolution: {integrity: sha512-hVLMUZFgR4JJ6ACt1uEESvQN1/dBVqPAKY0hgrV70eN3391K6juAfTjKZLKvOMsx8PxA7gsY1/tLMMTcfFLLpw==}
- resolution: {integrity: sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==}
- engines: {node: '>= 20.19.0'}
-
- resolution: {integrity: sha512-tskPPKEs8D2KPafUypv2gxwJP8h/OaJmC82QQGGDQcHvXX43xF2VDACcJVmZ0EuSxkpO9Kc4MlrA3q0+FG58AQ==}
-
- resolution: {integrity: sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==}
- engines: {node: '>=12'}
-
resolution: {integrity: sha512-EcR6r5a8bj6pu3ycsa/E/cKVGuTgZJZdsyUYHOksG/UHIiKfjxzRxYJpyVBwYaQeOvghal9fcc4PidlgzugAQg==}
engines: {node: '>=6'}
- resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==}
- engines: {node: '>=7.0.0'}
-
- resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==}
-
- resolution: {integrity: sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ==}
-
- resolution: {integrity: sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==}
- engines: {node: ^14.18.0 || >=16.10.0}
-
resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==}
@@ -732,31 +665,15 @@ packages:
resolution: {integrity: sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==}
- resolution: {integrity: sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==}
-
- resolution: {integrity: sha512-ugFTXCtDZunbzasqBxrK93Ik/DRYsO6S/fedkWEMKqt04xZ4csmnmwGDBAb07QWNaGMAmnTIemsYZCksjATwsA==}
-
resolution: {integrity: sha512-nRCa7CK3VTrM2NmGkIy4cbK7IZlgBE/PYMn55rrXefr5xXDP0LdtfPnblFDoVdcAfslJ7or6iqAUnx0CCGIWQA==}
- resolution: {integrity: sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==}
- engines: {node: '>=12'}
-
resolution: {integrity: sha512-kOrWphBi8TOZyiJZqsgqIle0lw+tzmnQK83pV9dZUd01Nm2POECSyFQMAuarzZdYqQW7FH9RaYOuaRo3h+bQ3w==}
- resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==}
-
resolution: {integrity: sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A==}
- resolution: {integrity: sha512-SOp9Phqvqn7jtEUxPWdWfWoLmyt2VaJ6MpvP9Comy1MceMXqE6bxvaTu4iaxpYYPzhny28Lc+M87/c2cPK6lDg==}
-
resolution: {integrity: sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==}
engines: {node: '>=12'}
@@ -766,16 +683,6 @@ packages:
resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==}
engines: {node: '>=6'}
- resolution: {integrity: sha512-UVQ72Rqjy/ZKQalzV5dCCJP80GrmPrMxh6NlNf+erV6ObL0ZFkhCstWRawS85z3smdr3d2wXPsZEY7rDPfGd2g==}
- engines: {node: '>=6.0.0'}
-
- resolution: {integrity: sha512-LmDxfWXwcTArk8fUEnOfSZpHOJ6zOMUJKOtFLFqJLoKJetuQG874Uc7/Kki7zFLzYybmZhp1M7+98pfMqeX8yA==}
-
- resolution: {integrity: sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==}
-
resolution: {integrity: sha512-483XLLxTVIwWK3QTrMGRqUfUpoOs/0hbQrl2oz4J0pAcm3A3bu84wxTFqGqkJzewCLdME38xJLJAxBABfQT8sQ==}
@@ -793,38 +700,15 @@ packages:
resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==}
engines: {node: '>=6.9.0'}
- resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==}
- engines: {node: 6.* || 8.* || >= 10.*}
-
- resolution: {integrity: sha512-GvHTWcykIR/fP8cj8dMpuMMkvaeJfPvYnhq0oW+chSeIr+ldX21ifU2Ms6KBoyKZQZmVaUAAhQ2EZ68KJF8a7A==}
- hasBin: true
-
- resolution: {integrity: sha512-EC2utToWl4RKfs5zd36Mxq7nzHHBuomZboI0yYL6Y0RmBgT7Sgkq4rQ0ezFTYoIsSs7Tm9SJe+o2FcAg6GBhGA==}
-
resolution: {integrity: sha512-m3Ofv/X/tV8Y3tHXLohcuVuhWKo7BBq62cqY15etqmLxg2DZ34AGGgQDeR+SCta2+zICb1NX83af0GJmbQ1++g==}
- resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==}
- engines: {node: '>=8'}
-
- resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==}
- hasBin: true
-
resolution: {integrity: sha512-o6WSo/LUvY2uC4j7mO50a2ms7E/EAdbP0swigLV+nzHKTTaYnaLIWJ02VdXrsJX0vGedDESQnLsOekr94ryfjg==}
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
- resolution: {integrity: sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==}
- hasBin: true
-
resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==}
engines: {node: '>=6'}
@@ -842,9 +726,6 @@ packages:
resolution: {integrity: sha512-Km+dc+XfNvY6a4az5jcxTK0zPk52ns9mAxLrHj7lF3V+riVYvQujfHmhayltJDjEpSOJ4C8a57LFNNKnNnRP2g==}
- resolution: {integrity: sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==}
-
resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==}
hasBin: true
@@ -864,65 +745,16 @@ packages:
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
hasBin: true
- resolution: {integrity: sha512-v+KEsUv2ps74PaSKv0gHTxTCgMXOIfBEbaqa6w6ISIGC7ZsvHN4N9oJ8d4cmf0n5oTzQz2SLmThbQWhjd/8eKg==}
- engines: {node: ^18 || >=20}
- hasBin: true
-
- resolution: {integrity: sha512-ofRW94Ab0T4AOh5Fk8t0h8OBWrmjb0SSB20xh1H8YnPV9EJ+f5AMoYSUQ2zgJ4Iq2HAK0I2l5/Nequ8YzFS3Hg==}
- engines: {node: 4.x || >=6.0.0}
-
- resolution: {integrity: sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==}
- engines: {node: 4.x || >=6.0.0}
- peerDependencies:
- encoding: ^0.1.0
- peerDependenciesMeta:
- encoding:
- optional: true
-
- resolution: {integrity: sha512-SU00ZarexNlE4Rjdm83vglt5Y9yiQ+XI1XpflWlb7q7UTN1JUItm69xMeiQCTxtTfnzt+83T8Cx+vI2ED++VDA==}
-
resolution: {integrity: sha512-3qT/88Y3FbH/Kx4szpQQ4HzUbVrHPKTLVpVocKiLfoYvw9XSGOX2FmD2d6DrXbVYyAQTF2HeF6My8jmzx7/CRw==}
- resolution: {integrity: sha512-pJTS2+T0oGIwgjGpw7sIRU8RQMcUoKCDWFLdBqKB2BNmGpbBMH2sdqAaOXUg8OzonZHU0L7vfJu1mJFEiYDWOQ==}
-
- resolution: {integrity: sha512-KEGjPDVoU5K6swgo9hJVA/qYGlwfbFx+Kg2QB/kd7rzV5N8N5Mg6PlsoCMohVnQmo+pzJap/F610qTodKzecGQ==}
-
- resolution: {integrity: sha512-Yx5PWQNZomfEhPPOphFbZKi9W93CocQj18NlD2Pa4GWZzdZpSJvYwoiuurRI7m3SpcChrnO08hkuQDL3FGsVFQ==}
- hasBin: true
-
- resolution: {integrity: sha512-2yucenq1a9YPmeNExoUa9Qwrt9RFkjqaMAA1X+U7sbb0AqBeTIdMHky9SQQ6iN94bO5NW0W4TRYXerG+BdAvAQ==}
-
- resolution: {integrity: sha512-cu20/HE5N5HKqVygs3dt94eYJfBi0TsZvPVXDhbXQHiEityDN+RROTleefoKRKKJ9dFAF2JBkDHgvWj0sjKGmw==}
-
resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==}
engines: {node: '>=0.10.0'}
- resolution: {integrity: sha512-RdR9FQrFwNBNXAr4GixM8YaRZRJ5PUWbKYbE5eOsrwAjJW0q2REGcf79oYPsLyskQCZG1PLN+S/K1V00joZAoQ==}
-
- resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}
-
- resolution: {integrity: sha512-LjgdTytVFXeUgtHZr9WYViYSM/g8MkcTPYDlPa3cDqMirHjKiSZPYd6DoL7pK8AJQr+uWkQvCjHNdiMqsrJs+g==}
-
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
- resolution: {integrity: sha512-y+ichcgc2LrADuhLNAx8DFjVfgz91pRxfZdI3UDhxHvcVEZsenLO+7XaU5vOp0u/7V/wZ+plyuQxtrDlZJ+yeg==}
-
resolution: {integrity: sha512-9bW6zvX/m0lEbgTKJ6YppOKx8H3VOPBMOCFh2irXFOT4BbHgrx5hPjwJYLT40Lu+4qtD36qKc/Hn56StUW57IA==}
engines: {node: '>=18'}
@@ -940,9 +772,6 @@ packages:
resolution: {integrity: sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==}
- resolution: {integrity: sha512-gMDyleLWVE+i6Sgtc0QbbY6pEKqYs97NGi6isHQPqYlLemPoO8dxQ3uGi0f4NiP98c+jMW6cG1Kx9dDwfvqARQ==}
-
resolution: {integrity: sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==}
peerDependencies:
@@ -981,17 +810,6 @@ packages:
resolution: {integrity: sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==}
engines: {node: '>=0.10.0'}
- resolution: {integrity: sha512-9u/XQ1pvrQtYyMpZe7DXKv2p5CNvyVwzUB6uhLAnQwHMSgKMBR62lc7AHljaeteeHXn11XTAaLLUVZYVZyuRBQ==}
- engines: {node: '>= 20.19.0'}
-
- resolution: {integrity: sha512-OVede/NQE13xBQ+ob5CKd5KyeJYU2YInb1bmV4nRoOfquZPkAkxuOXicSe1PvqIuZZ4kD13sPKBbR7UFDmli6w==}
-
- resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==}
- engines: {node: '>=0.10.0'}
-
resolution: {integrity: sha512-pAQK9HalE84QSm4Po3EmWIZPd3FnjkShVkiMlz1iligWYkWQ7wHYd1PF/T7QZ5TVSD6uSTon5gBVMSM4JfBV+A==}
engines: {node: '>=18.0.0', npm: '>=8.0.0'}
@@ -1004,59 +822,13 @@ packages:
resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==}
hasBin: true
- resolution: {integrity: sha512-ZP36TMrK9euEuWQYBig9W55WPC7uo37qzAEmbjHz4gfyuXrEUgF8cUvQVO+w+d3OMfPvSRQJ22lSm8MQJ43LTA==}
-
- resolution: {integrity: sha512-hZ58adtulAk0gKtua7QxevgUaXTTXxIi8t41L3zo9AHvjXO1/7sdLECuHeIN2SRtYXpNkmhoUP2pdeWgricQ+Q==}
-
- resolution: {integrity: sha512-JA4hdoLnN+kebEp2Vs8eBe9g7uy0zbRo+RMcU0EsNy+R+k049Ki+N5tT5Jagst2g7EAja+euFuoXFCa8vIklfA==}
-
- resolution: {integrity: sha512-MdAsTu3n25yDbIe1NeN69G4n6mUnJGtSJHygX3+oN0ZbO3DTiATnf7XnYJdGT42JCXurTb1JI0qOBR65shvhPQ==}
-
- resolution: {integrity: sha512-oXF8tfxx5cDk8r2kYqlkUJzZpDBqVY/II2WhvU0n9Y3XYvAYRmeaf1PvvIvTgPnv4KJ+ES5M0PyDq5Jp+Ygy2g==}
-
- resolution: {integrity: sha512-ggLesLtu2xp+ZxI+ysJTmNjh2U0TsC+rQ/pfED9bUZZ4DKefP27D+7YJVVTvKsmjLpIi9jAa7itwDGkDDmt1GQ==}
-
resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
engines: {node: '>=0.10.0'}
- resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==}
- engines: {node: '>=8'}
-
- resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==}
- engines: {node: '>=8'}
-
- resolution: {integrity: sha512-rCC0NWGKr/IJhtRuPq/t37qvZHI/mH4I4sxflVM+qgVe5Z2uOCivzWaVbuioJaB61kvm5UvB7b49E+oBY0M8jA==}
-
- resolution: {integrity: sha512-rfqqoRFpZJPl477M/snMJPM90EvI8WqhuUHSF5ecC2r/w376T29+QXNJFVPsJmbFu5rBc/8m3vhArtMctjONdw==}
- engines: {node: '>=20'}
- hasBin: true
-
- resolution: {integrity: sha512-upi/0ZGkYgEcLeGieoz8gT74oWHA0E7JivX7aN9mAf+Tc7BQoRBvnIGHoPDw+f9TXTW4s6kGYCZJtauP6OYp7g==}
- hasBin: true
-
- resolution: {integrity: sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==}
-
resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
- resolution: {integrity: sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==}
- engines: {node: '>=14.17'}
- hasBin: true
-
resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==}
engines: {node: '>=14.17'}
@@ -1099,41 +871,15 @@ packages:
terser:
optional: true
- resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==}
-
resolution: {integrity: sha512-ZO3I7c7J9nwGN1PZKZeBYAsuwWEsCOZi5T68cQoVNYrzrpp5Br0Bgi0OF4l8kH/Ez7nKfxa5mSsXjsgris3+qg==}
resolution: {integrity: sha512-HjYc14IQUwDcnGICuc8tVtqAd6EFpoAQMqgrqcNtWWZB+F1b7iTq44GzwM1qvnH4upFgbhJsaNHuK93NOFheSg==}
- resolution: {integrity: sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==}
-
- resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==}
- engines: {node: '>=10'}
-
- resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==}
- engines: {node: '>=10'}
-
resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==}
- resolution: {integrity: sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA==}
- engines: {node: '>= 6'}
-
- resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==}
- engines: {node: '>=12'}
-
- resolution: {integrity: sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==}
- engines: {node: '>=12'}
-
snapshots:
@@ -1285,12 +1031,6 @@ snapshots:
'@biomejs/[email protected]':
optional: true
- '@biomejs/[email protected](@biomejs/[email protected])':
- optionalDependencies:
- '@biomejs/wasm-nodejs': 2.0.5
-
- '@biomejs/[email protected]': {}
-
'@cloudscape-design/[email protected]([email protected])':
dependencies:
'@cloudscape-design/component-toolkit': 1.0.0-beta.159([email protected])
@@ -1431,8 +1171,6 @@ snapshots:
'@esbuild/[email protected]':
optional: true
- '@exodus/[email protected]': {}
-
'@formatjs/[email protected]':
dependencies:
'@formatjs/fast-memoize': 2.2.7
@@ -1599,7 +1337,7 @@ snapshots:
'@types/prop-types': 15.7.15
csstype: 3.2.3
- '@types/[email protected]': {}
+ '@ubjs/[email protected]': {}
dependencies:
@@ -1615,18 +1353,10 @@ snapshots:
-
- dependencies:
- color-convert: 2.0.1
-
dependencies:
entities: 2.2.0
-
@@ -1637,51 +1367,10 @@ snapshots:
node-releases: 2.0.38
update-browserslist-db: 1.2.3([email protected])
- dependencies:
- chokidar: 5.0.0
- confbox: 0.2.4
- defu: 6.1.7
- dotenv: 17.4.2
- exsolve: 1.0.8
- giget: 3.2.0
- jiti: 2.7.0
- ohash: 2.0.11
- pathe: 2.0.3
- perfect-debounce: 2.1.0
- pkg-types: 2.3.1
- rc9: 3.0.1
-
-
- dependencies:
- readdirp: 5.0.0
-
- dependencies:
- consola: 3.4.2
-
- dependencies:
- string-width: 4.2.3
- strip-ansi: 6.0.1
- wrap-ansi: 7.0.0
-
- dependencies:
- color-name: 1.1.4
-
-
-
-
@@ -1711,25 +1400,15 @@ snapshots:
-
-
dependencies:
'@babel/runtime': 7.29.2
csstype: 3.2.3
-
-
-
optionalDependencies:
'@esbuild/aix-ppc64': 0.21.5
@@ -1758,12 +1437,6 @@ snapshots:
-
-
-
@@ -1774,12 +1447,6 @@ snapshots:
-
-
-
dependencies:
'@formatjs/ecma402-abstract': 2.3.6
@@ -1787,18 +1454,10 @@ snapshots:
'@formatjs/icu-messageformat-parser': 2.11.4
tslib: 2.8.1
-
-
- dependencies:
- argparse: 2.0.1
-
@@ -1810,8 +1469,6 @@ snapshots:
js-sha256: 0.11.1
jwt-decode: 4.0.0
-
dependencies:
js-tokens: 4.0.0
@@ -1828,69 +1485,12 @@ snapshots:
-
- dependencies:
- http2-client: 1.3.5
-
- dependencies:
- whatwg-url: 5.0.0
-
- dependencies:
- es6-promise: 3.3.1
-
- dependencies:
- fast-safe-stringify: 2.1.1
-
- dependencies:
- '@exodus/schemasafe': 1.3.0
- should: 13.2.3
- yaml: 1.10.3
-
- dependencies:
- node-fetch-h2: 2.3.0
- oas-kit-common: 1.0.8
- reftools: 1.1.9
- yaml: 1.10.3
- yargs: 17.7.2
-
-
- dependencies:
- call-me-maybe: 1.0.2
- oas-kit-common: 1.0.8
- oas-linter: 3.2.2
- oas-resolver: 2.5.6
- oas-schema-walker: 1.1.5
- reftools: 1.1.9
- should: 13.2.3
- yaml: 1.10.3
-
-
-
-
- dependencies:
- confbox: 0.2.4
- exsolve: 1.0.8
- pathe: 2.0.3
-
@@ -1911,11 +1511,6 @@ snapshots:
object-assign: 4.1.1
react-is: 16.13.1
- dependencies:
- defu: 6.1.7
- destr: 2.0.5
-
dependencies:
loose-envify: 1.4.0
@@ -1953,12 +1548,6 @@ snapshots:
dependencies:
loose-envify: 1.4.0
-
-
-
dependencies:
'@types/estree': 1.0.8
@@ -1996,89 +1585,10 @@ snapshots:
- dependencies:
- should-type: 1.4.0
-
- dependencies:
- should-type: 1.4.0
- should-type-adaptors: 1.1.0
-
- dependencies:
- should-type: 1.4.0
- should-util: 1.0.1
-
-
-
- dependencies:
- should-equal: 2.0.0
- should-format: 3.0.3
- should-type: 1.4.0
- should-type-adaptors: 1.1.0
- should-util: 1.0.1
-
- dependencies:
- emoji-regex: 8.0.0
- is-fullwidth-code-point: 3.0.0
- strip-ansi: 6.0.1
-
- dependencies:
- ansi-regex: 5.0.1
-
-
- dependencies:
- '@biomejs/js-api': 1.0.0(@biomejs/[email protected])
- '@biomejs/wasm-nodejs': 2.0.5
- '@types/swagger-schema-official': 2.0.25
- c12: 3.3.4
- citty: 0.1.6
- consola: 3.4.2
- eta: 2.2.0
- js-yaml: 4.1.1
- lodash: 4.18.1
- nanoid: 5.1.11
- swagger-schema-official: 2.0.0-bab6bed
- swagger2openapi: 7.0.8
- typescript: 5.8.3
- transitivePeerDependencies:
- - '@biomejs/wasm-bundler'
- - '@biomejs/wasm-web'
- - encoding
- - magicast
-
- dependencies:
- call-me-maybe: 1.0.2
- node-fetch: 2.7.0
- node-fetch-h2: 2.3.0
- node-readfiles: 0.2.0
- oas-kit-common: 1.0.8
- oas-resolver: 2.5.6
- oas-schema-walker: 1.1.5
- oas-validator: 5.0.8
- reftools: 1.1.9
- yaml: 1.10.3
- yargs: 17.7.2
- transitivePeerDependencies:
- - encoding
-
-
-
@@ -2095,37 +1605,8 @@ snapshots:
optionalDependencies:
fsevents: 2.3.3
-
- dependencies:
- tr46: 0.0.3
- webidl-conversions: 3.0.1
-
- dependencies:
- ansi-styles: 4.3.0
- string-width: 4.2.3
- strip-ansi: 6.0.1
-
-
-
-
-
- dependencies:
- cliui: 8.0.1
- escalade: 3.2.0
- get-caller-file: 2.0.5
- require-directory: 2.1.1
- string-width: 4.2.3
- y18n: 5.0.8
- yargs-parser: 21.1.1
diff --git a/libs/fleet/pnpm-workspace.yaml b/libs/fleet/pnpm-workspace.yaml
new file mode 100644
index 0000000000..2d759adc43
--- /dev/null
+++ b/libs/fleet/pnpm-workspace.yaml
@@ -0,0 +1,8 @@
+packages:
+ - .
+
+onlyBuiltDependencies:
+ - esbuild
+
+patchedDependencies:
diff --git a/libs/fleet/python-sdk/.gitignore b/libs/fleet/python-sdk/.gitignore
new file mode 100644
index 0000000000..79a2c3d73c
--- /dev/null
+++ b/libs/fleet/python-sdk/.gitignore
@@ -0,0 +1,23 @@
+__pycache__/
+build/
+dist/
+*.egg-info/
+.pytest_cache/
+
+# pyenv
+.python-version
+
+# Environments
+.env
+.venv
+
+# mypy
+.mypy_cache/
+.dmypy.json
+dmypy.json
+
+# JetBrains
+.idea/
+
+/coverage.xml
+/.coverage
diff --git a/libs/fleet/python-sdk/README.md b/libs/fleet/python-sdk/README.md
new file mode 100644
index 0000000000..8b13789179
--- /dev/null
+++ b/libs/fleet/python-sdk/README.md
@@ -0,0 +1 @@
+
diff --git a/libs/fleet/python-sdk/cua_train/__init__.py b/libs/fleet/python-sdk/cua_train/__init__.py
new file mode 100644
index 0000000000..c0b9d96bd7
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/__init__.py
@@ -0,0 +1,10 @@
+"""cua-train — Python client library for the CUA training / batch backend API."""
+
+from ._convenience import TrainClient
+from .client import AuthenticatedClient, Client
+
+__all__ = (
+ "AuthenticatedClient",
+ "Client",
+ "TrainClient",
+)
diff --git a/libs/fleet/python-sdk/cua_train/_convenience.py b/libs/fleet/python-sdk/cua_train/_convenience.py
new file mode 100644
index 0000000000..dc3422bb00
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/_convenience.py
@@ -0,0 +1,147 @@
+"""
+TrainClient — an AuthenticatedClient that also exposes every generated
+endpoint as a method, so callers write::
+
+ c = TrainClient.from_key(token_url=..., client_id=..., client_secret=...)
+ c.acquire_lanes(pool="test-pool", body=AcquireLanesRequest(n=8))
+ c.submit_label_batch(pool="test-pool", label="run-1", body=BatchSubmitRequest(...))
+ c.get_label_results(pool="test-pool", label="run-1", completed_only=True)
+
+instead of importing each generated module and calling ``.sync`` by hand.
+
+The endpoint surface is built generically: :func:`_load_operations` loops over
+every module under ``cua_train.api`` once at import and maps each operation's
+``sync`` function by name. ``TrainClient.__getattr__`` then resolves an
+unknown attribute to that function with ``client=self`` pre-bound — no
+per-endpoint code and no routing logic, so a new endpoint is callable the moment
+it is regenerated from the OpenAPI spec. ``c`` remains a drop-in
+``AuthenticatedClient`` for the low-level ``cua_train.api.*`` functions.
+"""
+
+from __future__ import annotations
+
+import functools
+import importlib
+import pkgutil
+import threading
+import time
+from collections.abc import Callable
+
+import httpx
+
+from . import api
+from .client import AuthenticatedClient
+
+
+def _load_operations() -> dict[str, Callable]:
+ """Map ``operation_name -> sync()`` for every generated endpoint module.
+
+ Walks ``cua_train/api/<tag>/<operation>.py`` (operation names are globally
+ unique, so a flat namespace is safe). Run once at import.
+ """
+ ops: dict[str, Callable] = {}
+ for tag in pkgutil.iter_modules(api.__path__):
+ if not tag.ispkg:
+ continue
+ pkg = importlib.import_module(f"{api.__name__}.{tag.name}")
+ for op in pkgutil.iter_modules(pkg.__path__):
+ module = importlib.import_module(f"{pkg.__name__}.{op.name}")
+ fn = getattr(module, "sync", None)
+ if callable(fn):
+ ops[op.name] = fn
+ return ops
+
+
+_OPERATIONS = _load_operations()
+
+
+class TrainClient(AuthenticatedClient):
+ """AuthenticatedClient with a ``client_credentials`` helper, a bearer token
+ that is refreshed transparently before it expires, and every generated
+ endpoint exposed as a method (its ``sync``, client pre-bound)."""
+
+ @classmethod
+ def from_key(
+ cls,
+ *,
+ token_url: str,
+ client_id: str,
+ client_secret: str,
+ base_url: str = "https://run.cua.ai",
+ **kwargs,
+ ) -> TrainClient:
+ """Exchange client credentials for a bearer token and return a ready client.
+
+ Args:
+ token_url: Keycloak token endpoint, e.g.
+ ``https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token``
+ client_id: Service-account client ID (starts with ``key-``).
+ client_secret: Client secret returned by ``POST /api/keys``.
+ base_url: Backend base URL (default: production, run.cua.ai).
+ **kwargs: Forwarded to :class:`AuthenticatedClient`.
+ """
+ token, ttl = cls._exchange(token_url, client_id, client_secret)
+ self = cls(base_url=base_url, token=token, **kwargs)
+ # Stash credentials so the token can be refreshed transparently.
+ self._token_url = token_url
+ self._client_id = client_id
+ self._client_secret = client_secret
+ self._token_deadline = time.monotonic() + ttl
+ self._refresh_lock = threading.Lock()
+ return self
+
+ @staticmethod
+ def _exchange(token_url: str, client_id: str, client_secret: str) -> tuple[str, float]:
+ """client_credentials exchange → (access_token, lifetime_seconds)."""
+ resp = httpx.post(
+ token_url,
+ data={
+ "grant_type": "client_credentials",
+ "client_id": client_id,
+ "client_secret": client_secret,
+ },
+ )
+ resp.raise_for_status()
+ body = resp.json()
+ return body["access_token"], float(body.get("expires_in", 300))
+
+ def _refresh_token(self) -> None:
+ """Re-mint the bearer token shortly before it expires. Transparent to
+ callers, thread-safe (double-checked under a lock), and a no-op for
+ clients not created via :meth:`from_key`."""
+ if getattr(self, "_token_url", None) is None:
+ return
+ if time.monotonic() < self._token_deadline - 30:
+ return
+ with self._refresh_lock:
+ if time.monotonic() < self._token_deadline - 30:
+ return
+ token, ttl = self._exchange(self._token_url, self._client_id, self._client_secret)
+ self.token = token
+ self._token_deadline = time.monotonic() + ttl
+ header = f"{self.prefix} {token}" if self.prefix else token
+ self._headers[self.auth_header_name] = header
+ if self._client is not None:
+ self._client.headers[self.auth_header_name] = header
+ if self._async_client is not None:
+ self._async_client.headers[self.auth_header_name] = header
+
+ def get_httpx_client(self) -> httpx.Client:
+ self._refresh_token()
+ return super().get_httpx_client()
+
+ def get_async_httpx_client(self) -> httpx.AsyncClient:
+ self._refresh_token()
+ return super().get_async_httpx_client()
+
+ def __getattr__(self, name: str) -> Callable:
+ # Only reached for attributes not found normally (slots/methods take
+ # precedence), so this never shadows real client state. Unknown names —
+ # including dunders probed by copy/pickle — raise AttributeError.
+ fn = _OPERATIONS.get(name)
+ if fn is None:
+ raise AttributeError(
+ f"{type(self).__name__!r} object has no attribute {name!r}; "
+ f"available operations: {', '.join(sorted(_OPERATIONS))}"
+ )
+ return functools.partial(fn, client=self)
diff --git a/libs/fleet/python-sdk/cua_train/api/__init__.py b/libs/fleet/python-sdk/cua_train/api/__init__.py
new file mode 100644
index 0000000000..81f9fa241b
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/api/__init__.py
@@ -0,0 +1 @@
+"""Contains methods for accessing the API"""
diff --git a/libs/fleet/python-sdk/cua_train/api/batch/__init__.py b/libs/fleet/python-sdk/cua_train/api/batch/__init__.py
new file mode 100644
index 0000000000..2d7c0b23da
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/api/batch/__init__.py
@@ -0,0 +1 @@
+"""Contains endpoint functions for accessing the API"""
diff --git a/libs/fleet/python-sdk/cua_train/api/batch/acquire_lanes.py b/libs/fleet/python-sdk/cua_train/api/batch/acquire_lanes.py
new file mode 100644
index 0000000000..453c8323b6
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/api/batch/acquire_lanes.py
@@ -0,0 +1,212 @@
+from http import HTTPStatus
+from typing import Any
+from urllib.parse import quote
+
+import httpx
+
+from ... import errors
+from ...client import AuthenticatedClient, Client
+from ...models.acquire_lanes_request import AcquireLanesRequest
+from ...models.acquire_lanes_response import AcquireLanesResponse
+from ...models.error_response import ErrorResponse
+from ...types import Response
+
+
+def _get_kwargs(
+ pool: str,
+ *,
+ body: AcquireLanesRequest,
+) -> dict[str, Any]:
+ headers: dict[str, Any] = {}
+
+ _kwargs: dict[str, Any] = {
+ "method": "post",
+ "url": "/api/batch/{pool}/lanes".format(
+ pool=quote(str(pool), safe=""),
+ ),
+ }
+
+ _kwargs["json"] = body.to_dict()
+
+ headers["Content-Type"] = "application/json"
+
+ _kwargs["headers"] = headers
+ return _kwargs
+
+
+def _parse_response(
+ *, client: AuthenticatedClient | Client, response: httpx.Response
+) -> AcquireLanesResponse | ErrorResponse | None:
+ if response.status_code == 200:
+ response_200 = AcquireLanesResponse.from_dict(response.json())
+
+ return response_200
+
+ if response.status_code == 400:
+ response_400 = ErrorResponse.from_dict(response.json())
+
+ return response_400
+
+ if response.status_code == 401:
+ response_401 = ErrorResponse.from_dict(response.json())
+
+ return response_401
+
+ if response.status_code == 503:
+ response_503 = ErrorResponse.from_dict(response.json())
+
+ return response_503
+
+ if client.raise_on_unexpected_status:
+ raise errors.UnexpectedStatus(response.status_code, response.content)
+ else:
+ return None
+
+
+def _build_response(
+ *, client: AuthenticatedClient | Client, response: httpx.Response
+) -> Response[AcquireLanesResponse | ErrorResponse]:
+ return Response(
+ status_code=HTTPStatus(response.status_code),
+ content=response.content,
+ headers=response.headers,
+ parsed=_parse_response(client=client, response=response),
+ )
+
+
+def sync_detailed(
+ pool: str,
+ *,
+ client: AuthenticatedClient | Client,
+ body: AcquireLanesRequest,
+) -> Response[AcquireLanesResponse | ErrorResponse]:
+ r"""Acquire warm VM lanes
+
+ Explicitly provisions N warm VMs (\"lanes\") and returns their vm_ids. Pass each as
+ `RunConfig.vm_id` to run actions on it (state persists across batches), and `DELETE` this route to
+ release them. All-or-nothing: a partial acquisition is rolled back, and 503 is returned if the pool
+ can't supply every lane in time.
+
+ Args:
+ pool (str):
+ body (AcquireLanesRequest):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[AcquireLanesResponse | ErrorResponse]
+ """
+
+ kwargs = _get_kwargs(
+ pool=pool,
+ body=body,
+ )
+
+ response = client.get_httpx_client().request(
+ **kwargs,
+ )
+
+ return _build_response(client=client, response=response)
+
+
+def sync(
+ pool: str,
+ *,
+ client: AuthenticatedClient | Client,
+ body: AcquireLanesRequest,
+) -> AcquireLanesResponse | ErrorResponse | None:
+ r"""Acquire warm VM lanes
+
+ Explicitly provisions N warm VMs (\"lanes\") and returns their vm_ids. Pass each as
+ `RunConfig.vm_id` to run actions on it (state persists across batches), and `DELETE` this route to
+ release them. All-or-nothing: a partial acquisition is rolled back, and 503 is returned if the pool
+ can't supply every lane in time.
+
+ Args:
+ pool (str):
+ body (AcquireLanesRequest):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ AcquireLanesResponse | ErrorResponse
+ """
+
+ return sync_detailed(
+ pool=pool,
+ client=client,
+ body=body,
+ ).parsed
+
+
+async def asyncio_detailed(
+ pool: str,
+ *,
+ client: AuthenticatedClient | Client,
+ body: AcquireLanesRequest,
+) -> Response[AcquireLanesResponse | ErrorResponse]:
+ r"""Acquire warm VM lanes
+
+ Explicitly provisions N warm VMs (\"lanes\") and returns their vm_ids. Pass each as
+ `RunConfig.vm_id` to run actions on it (state persists across batches), and `DELETE` this route to
+ release them. All-or-nothing: a partial acquisition is rolled back, and 503 is returned if the pool
+ can't supply every lane in time.
+
+ Args:
+ pool (str):
+ body (AcquireLanesRequest):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[AcquireLanesResponse | ErrorResponse]
+ """
+
+ kwargs = _get_kwargs(
+ pool=pool,
+ body=body,
+ )
+
+ response = await client.get_async_httpx_client().request(**kwargs)
+
+ return _build_response(client=client, response=response)
+
+
+async def asyncio(
+ pool: str,
+ *,
+ client: AuthenticatedClient | Client,
+ body: AcquireLanesRequest,
+) -> AcquireLanesResponse | ErrorResponse | None:
+ r"""Acquire warm VM lanes
+
+ Explicitly provisions N warm VMs (\"lanes\") and returns their vm_ids. Pass each as
+ `RunConfig.vm_id` to run actions on it (state persists across batches), and `DELETE` this route to
+ release them. All-or-nothing: a partial acquisition is rolled back, and 503 is returned if the pool
+ can't supply every lane in time.
+
+ Args:
+ pool (str):
+ body (AcquireLanesRequest):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ AcquireLanesResponse | ErrorResponse
+ """
+
+ return (
+ await asyncio_detailed(
+ pool=pool,
+ client=client,
+ body=body,
+ )
+ ).parsed
diff --git a/libs/fleet/python-sdk/cua_train/api/batch/cancel_batch.py b/libs/fleet/python-sdk/cua_train/api/batch/cancel_batch.py
new file mode 100644
index 0000000000..00110ea700
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/api/batch/cancel_batch.py
@@ -0,0 +1,196 @@
+from http import HTTPStatus
+from typing import Any
+from urllib.parse import quote
+
+import httpx
+
+from ... import errors
+from ...client import AuthenticatedClient, Client
+from ...models.cancel_batch_response import CancelBatchResponse
+from ...models.error_response import ErrorResponse
+from ...types import Response
+
+
+def _get_kwargs(
+ pool: str,
+ id: str,
+) -> dict[str, Any]:
+
+ _kwargs: dict[str, Any] = {
+ "method": "delete",
+ "url": "/api/batch/{pool}/{id}".format(
+ pool=quote(str(pool), safe=""),
+ id=quote(str(id), safe=""),
+ ),
+ }
+
+ return _kwargs
+
+
+def _parse_response(
+ *, client: AuthenticatedClient | Client, response: httpx.Response
+) -> CancelBatchResponse | ErrorResponse | None:
+ if response.status_code == 200:
+ response_200 = CancelBatchResponse.from_dict(response.json())
+
+ return response_200
+
+ if response.status_code == 401:
+ response_401 = ErrorResponse.from_dict(response.json())
+
+ return response_401
+
+ if response.status_code == 404:
+ response_404 = ErrorResponse.from_dict(response.json())
+
+ return response_404
+
+ if client.raise_on_unexpected_status:
+ raise errors.UnexpectedStatus(response.status_code, response.content)
+ else:
+ return None
+
+
+def _build_response(
+ *, client: AuthenticatedClient | Client, response: httpx.Response
+) -> Response[CancelBatchResponse | ErrorResponse]:
+ return Response(
+ status_code=HTTPStatus(response.status_code),
+ content=response.content,
+ headers=response.headers,
+ parsed=_parse_response(client=client, response=response),
+ )
+
+
+def sync_detailed(
+ pool: str,
+ id: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> Response[CancelBatchResponse | ErrorResponse]:
+ """Cancel a batch
+
+ Hard-cancels the batch — aborts in-flight /reset and /step calls
+ and stops dispatch. Idempotent on terminal batches. Returns 200
+ with the final status.
+
+ Args:
+ pool (str):
+ id (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[CancelBatchResponse | ErrorResponse]
+ """
+
+ kwargs = _get_kwargs(
+ pool=pool,
+ id=id,
+ )
+
+ response = client.get_httpx_client().request(
+ **kwargs,
+ )
+
+ return _build_response(client=client, response=response)
+
+
+def sync(
+ pool: str,
+ id: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> CancelBatchResponse | ErrorResponse | None:
+ """Cancel a batch
+
+ Hard-cancels the batch — aborts in-flight /reset and /step calls
+ and stops dispatch. Idempotent on terminal batches. Returns 200
+ with the final status.
+
+ Args:
+ pool (str):
+ id (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ CancelBatchResponse | ErrorResponse
+ """
+
+ return sync_detailed(
+ pool=pool,
+ id=id,
+ client=client,
+ ).parsed
+
+
+async def asyncio_detailed(
+ pool: str,
+ id: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> Response[CancelBatchResponse | ErrorResponse]:
+ """Cancel a batch
+
+ Hard-cancels the batch — aborts in-flight /reset and /step calls
+ and stops dispatch. Idempotent on terminal batches. Returns 200
+ with the final status.
+
+ Args:
+ pool (str):
+ id (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[CancelBatchResponse | ErrorResponse]
+ """
+
+ kwargs = _get_kwargs(
+ pool=pool,
+ id=id,
+ )
+
+ response = await client.get_async_httpx_client().request(**kwargs)
+
+ return _build_response(client=client, response=response)
+
+
+async def asyncio(
+ pool: str,
+ id: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> CancelBatchResponse | ErrorResponse | None:
+ """Cancel a batch
+
+ Hard-cancels the batch — aborts in-flight /reset and /step calls
+ and stops dispatch. Idempotent on terminal batches. Returns 200
+ with the final status.
+
+ Args:
+ pool (str):
+ id (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ CancelBatchResponse | ErrorResponse
+ """
+
+ return (
+ await asyncio_detailed(
+ pool=pool,
+ id=id,
+ client=client,
+ )
+ ).parsed
diff --git a/libs/fleet/python-sdk/cua_train/api/batch/get_batch_results.py b/libs/fleet/python-sdk/cua_train/api/batch/get_batch_results.py
new file mode 100644
index 0000000000..bb2e2b48fd
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/api/batch/get_batch_results.py
@@ -0,0 +1,202 @@
+from http import HTTPStatus
+from typing import Any
+from urllib.parse import quote
+
+import httpx
+
+from ... import errors
+from ...client import AuthenticatedClient, Client
+from ...models.batch_in_progress_response import BatchInProgressResponse
+from ...models.batch_results_response import BatchResultsResponse
+from ...models.error_response import ErrorResponse
+from ...types import Response
+
+
+def _get_kwargs(
+ pool: str,
+ id: str,
+) -> dict[str, Any]:
+
+ _kwargs: dict[str, Any] = {
+ "method": "get",
+ "url": "/api/batch/{pool}/{id}/results".format(
+ pool=quote(str(pool), safe=""),
+ id=quote(str(id), safe=""),
+ ),
+ }
+
+ return _kwargs
+
+
+def _parse_response(
+ *, client: AuthenticatedClient | Client, response: httpx.Response
+) -> BatchInProgressResponse | BatchResultsResponse | ErrorResponse | None:
+ if response.status_code == 200:
+ response_200 = BatchResultsResponse.from_dict(response.json())
+
+ return response_200
+
+ if response.status_code == 202:
+ response_202 = BatchInProgressResponse.from_dict(response.json())
+
+ return response_202
+
+ if response.status_code == 401:
+ response_401 = ErrorResponse.from_dict(response.json())
+
+ return response_401
+
+ if response.status_code == 404:
+ response_404 = ErrorResponse.from_dict(response.json())
+
+ return response_404
+
+ if client.raise_on_unexpected_status:
+ raise errors.UnexpectedStatus(response.status_code, response.content)
+ else:
+ return None
+
+
+def _build_response(
+ *, client: AuthenticatedClient | Client, response: httpx.Response
+) -> Response[BatchInProgressResponse | BatchResultsResponse | ErrorResponse]:
+ return Response(
+ status_code=HTTPStatus(response.status_code),
+ content=response.content,
+ headers=response.headers,
+ parsed=_parse_response(client=client, response=response),
+ )
+
+
+def sync_detailed(
+ pool: str,
+ id: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> Response[BatchInProgressResponse | BatchResultsResponse | ErrorResponse]:
+ """Final batch results
+
+ Returns 200 with the full results once the batch is in a terminal
+ status (completed/failed). While still running, returns 202 with a
+ `message` field.
+
+ Args:
+ pool (str):
+ id (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[BatchInProgressResponse | BatchResultsResponse | ErrorResponse]
+ """
+
+ kwargs = _get_kwargs(
+ pool=pool,
+ id=id,
+ )
+
+ response = client.get_httpx_client().request(
+ **kwargs,
+ )
+
+ return _build_response(client=client, response=response)
+
+
+def sync(
+ pool: str,
+ id: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> BatchInProgressResponse | BatchResultsResponse | ErrorResponse | None:
+ """Final batch results
+
+ Returns 200 with the full results once the batch is in a terminal
+ status (completed/failed). While still running, returns 202 with a
+ `message` field.
+
+ Args:
+ pool (str):
+ id (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ BatchInProgressResponse | BatchResultsResponse | ErrorResponse
+ """
+
+ return sync_detailed(
+ pool=pool,
+ id=id,
+ client=client,
+ ).parsed
+
+
+async def asyncio_detailed(
+ pool: str,
+ id: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> Response[BatchInProgressResponse | BatchResultsResponse | ErrorResponse]:
+ """Final batch results
+
+ Returns 200 with the full results once the batch is in a terminal
+ status (completed/failed). While still running, returns 202 with a
+ `message` field.
+
+ Args:
+ pool (str):
+ id (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[BatchInProgressResponse | BatchResultsResponse | ErrorResponse]
+ """
+
+ kwargs = _get_kwargs(
+ pool=pool,
+ id=id,
+ )
+
+ response = await client.get_async_httpx_client().request(**kwargs)
+
+ return _build_response(client=client, response=response)
+
+
+async def asyncio(
+ pool: str,
+ id: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> BatchInProgressResponse | BatchResultsResponse | ErrorResponse | None:
+ """Final batch results
+
+ Returns 200 with the full results once the batch is in a terminal
+ status (completed/failed). While still running, returns 202 with a
+ `message` field.
+
+ Args:
+ pool (str):
+ id (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ BatchInProgressResponse | BatchResultsResponse | ErrorResponse
+ """
+
+ return (
+ await asyncio_detailed(
+ pool=pool,
+ id=id,
+ client=client,
+ )
+ ).parsed
diff --git a/libs/fleet/python-sdk/cua_train/api/batch/get_batch_status.py b/libs/fleet/python-sdk/cua_train/api/batch/get_batch_status.py
new file mode 100644
index 0000000000..e4a13d4a81
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/api/batch/get_batch_status.py
@@ -0,0 +1,180 @@
+from http import HTTPStatus
+from typing import Any
+from urllib.parse import quote
+
+import httpx
+
+from ... import errors
+from ...client import AuthenticatedClient, Client
+from ...models.batch_status_response import BatchStatusResponse
+from ...models.error_response import ErrorResponse
+from ...types import Response
+
+
+def _get_kwargs(
+ pool: str,
+ id: str,
+) -> dict[str, Any]:
+
+ _kwargs: dict[str, Any] = {
+ "method": "get",
+ "url": "/api/batch/{pool}/{id}/status".format(
+ pool=quote(str(pool), safe=""),
+ id=quote(str(id), safe=""),
+ ),
+ }
+
+ return _kwargs
+
+
+def _parse_response(
+ *, client: AuthenticatedClient | Client, response: httpx.Response
+) -> BatchStatusResponse | ErrorResponse | None:
+ if response.status_code == 200:
+ response_200 = BatchStatusResponse.from_dict(response.json())
+
+ return response_200
+
+ if response.status_code == 401:
+ response_401 = ErrorResponse.from_dict(response.json())
+
+ return response_401
+
+ if response.status_code == 404:
+ response_404 = ErrorResponse.from_dict(response.json())
+
+ return response_404
+
+ if client.raise_on_unexpected_status:
+ raise errors.UnexpectedStatus(response.status_code, response.content)
+ else:
+ return None
+
+
+def _build_response(
+ *, client: AuthenticatedClient | Client, response: httpx.Response
+) -> Response[BatchStatusResponse | ErrorResponse]:
+ return Response(
+ status_code=HTTPStatus(response.status_code),
+ content=response.content,
+ headers=response.headers,
+ parsed=_parse_response(client=client, response=response),
+ )
+
+
+def sync_detailed(
+ pool: str,
+ id: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> Response[BatchStatusResponse | ErrorResponse]:
+ """Poll batch progress
+
+ Args:
+ pool (str):
+ id (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[BatchStatusResponse | ErrorResponse]
+ """
+
+ kwargs = _get_kwargs(
+ pool=pool,
+ id=id,
+ )
+
+ response = client.get_httpx_client().request(
+ **kwargs,
+ )
+
+ return _build_response(client=client, response=response)
+
+
+def sync(
+ pool: str,
+ id: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> BatchStatusResponse | ErrorResponse | None:
+ """Poll batch progress
+
+ Args:
+ pool (str):
+ id (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ BatchStatusResponse | ErrorResponse
+ """
+
+ return sync_detailed(
+ pool=pool,
+ id=id,
+ client=client,
+ ).parsed
+
+
+async def asyncio_detailed(
+ pool: str,
+ id: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> Response[BatchStatusResponse | ErrorResponse]:
+ """Poll batch progress
+
+ Args:
+ pool (str):
+ id (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[BatchStatusResponse | ErrorResponse]
+ """
+
+ kwargs = _get_kwargs(
+ pool=pool,
+ id=id,
+ )
+
+ response = await client.get_async_httpx_client().request(**kwargs)
+
+ return _build_response(client=client, response=response)
+
+
+async def asyncio(
+ pool: str,
+ id: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> BatchStatusResponse | ErrorResponse | None:
+ """Poll batch progress
+
+ Args:
+ pool (str):
+ id (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ BatchStatusResponse | ErrorResponse
+ """
+
+ return (
+ await asyncio_detailed(
+ pool=pool,
+ id=id,
+ client=client,
+ )
+ ).parsed
diff --git a/libs/fleet/python-sdk/cua_train/api/batch/release_lanes.py b/libs/fleet/python-sdk/cua_train/api/batch/release_lanes.py
new file mode 100644
index 0000000000..8c8534cf0f
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/api/batch/release_lanes.py
@@ -0,0 +1,199 @@
+from http import HTTPStatus
+from typing import Any
+from urllib.parse import quote
+
+import httpx
+
+from ... import errors
+from ...client import AuthenticatedClient, Client
+from ...models.error_response import ErrorResponse
+from ...models.release_lanes_request import ReleaseLanesRequest
+from ...models.release_lanes_response import ReleaseLanesResponse
+from ...types import Response
+
+
+def _get_kwargs(
+ pool: str,
+ *,
+ body: ReleaseLanesRequest,
+) -> dict[str, Any]:
+ headers: dict[str, Any] = {}
+
+ _kwargs: dict[str, Any] = {
+ "method": "delete",
+ "url": "/api/batch/{pool}/lanes".format(
+ pool=quote(str(pool), safe=""),
+ ),
+ }
+
+ _kwargs["json"] = body.to_dict()
+
+ headers["Content-Type"] = "application/json"
+
+ _kwargs["headers"] = headers
+ return _kwargs
+
+
+def _parse_response(
+ *, client: AuthenticatedClient | Client, response: httpx.Response
+) -> ErrorResponse | ReleaseLanesResponse | None:
+ if response.status_code == 200:
+ response_200 = ReleaseLanesResponse.from_dict(response.json())
+
+ return response_200
+
+ if response.status_code == 400:
+ response_400 = ErrorResponse.from_dict(response.json())
+
+ return response_400
+
+ if response.status_code == 401:
+ response_401 = ErrorResponse.from_dict(response.json())
+
+ return response_401
+
+ if client.raise_on_unexpected_status:
+ raise errors.UnexpectedStatus(response.status_code, response.content)
+ else:
+ return None
+
+
+def _build_response(
+ *, client: AuthenticatedClient | Client, response: httpx.Response
+) -> Response[ErrorResponse | ReleaseLanesResponse]:
+ return Response(
+ status_code=HTTPStatus(response.status_code),
+ content=response.content,
+ headers=response.headers,
+ parsed=_parse_response(client=client, response=response),
+ )
+
+
+def sync_detailed(
+ pool: str,
+ *,
+ client: AuthenticatedClient | Client,
+ body: ReleaseLanesRequest,
+) -> Response[ErrorResponse | ReleaseLanesResponse]:
+ """Release warm VM lanes
+
+ Shuts down the given VMs (lanes from `acquireLanes` or `vm_id`s returned by a `keep_warm` batch).
+ Best-effort and idempotent — unknown or already-gone ids are ignored.
+
+ Args:
+ pool (str):
+ body (ReleaseLanesRequest):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[ErrorResponse | ReleaseLanesResponse]
+ """
+
+ kwargs = _get_kwargs(
+ pool=pool,
+ body=body,
+ )
+
+ response = client.get_httpx_client().request(
+ **kwargs,
+ )
+
+ return _build_response(client=client, response=response)
+
+
+def sync(
+ pool: str,
+ *,
+ client: AuthenticatedClient | Client,
+ body: ReleaseLanesRequest,
+) -> ErrorResponse | ReleaseLanesResponse | None:
+ """Release warm VM lanes
+
+ Shuts down the given VMs (lanes from `acquireLanes` or `vm_id`s returned by a `keep_warm` batch).
+ Best-effort and idempotent — unknown or already-gone ids are ignored.
+
+ Args:
+ pool (str):
+ body (ReleaseLanesRequest):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ ErrorResponse | ReleaseLanesResponse
+ """
+
+ return sync_detailed(
+ pool=pool,
+ client=client,
+ body=body,
+ ).parsed
+
+
+async def asyncio_detailed(
+ pool: str,
+ *,
+ client: AuthenticatedClient | Client,
+ body: ReleaseLanesRequest,
+) -> Response[ErrorResponse | ReleaseLanesResponse]:
+ """Release warm VM lanes
+
+ Shuts down the given VMs (lanes from `acquireLanes` or `vm_id`s returned by a `keep_warm` batch).
+ Best-effort and idempotent — unknown or already-gone ids are ignored.
+
+ Args:
+ pool (str):
+ body (ReleaseLanesRequest):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[ErrorResponse | ReleaseLanesResponse]
+ """
+
+ kwargs = _get_kwargs(
+ pool=pool,
+ body=body,
+ )
+
+ response = await client.get_async_httpx_client().request(**kwargs)
+
+ return _build_response(client=client, response=response)
+
+
+async def asyncio(
+ pool: str,
+ *,
+ client: AuthenticatedClient | Client,
+ body: ReleaseLanesRequest,
+) -> ErrorResponse | ReleaseLanesResponse | None:
+ """Release warm VM lanes
+
+ Shuts down the given VMs (lanes from `acquireLanes` or `vm_id`s returned by a `keep_warm` batch).
+ Best-effort and idempotent — unknown or already-gone ids are ignored.
+
+ Args:
+ pool (str):
+ body (ReleaseLanesRequest):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ ErrorResponse | ReleaseLanesResponse
+ """
+
+ return (
+ await asyncio_detailed(
+ pool=pool,
+ client=client,
+ body=body,
+ )
+ ).parsed
diff --git a/libs/fleet/python-sdk/cua_train/api/batch/submit_batch.py b/libs/fleet/python-sdk/cua_train/api/batch/submit_batch.py
new file mode 100644
index 0000000000..5fe187f149
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/api/batch/submit_batch.py
@@ -0,0 +1,219 @@
+from http import HTTPStatus
+from typing import Any
+from urllib.parse import quote
+
+import httpx
+
+from ... import errors
+from ...client import AuthenticatedClient, Client
+from ...models.batch_submit_request import BatchSubmitRequest
+from ...models.batch_submit_response import BatchSubmitResponse
+from ...models.error_response import ErrorResponse
+from ...types import Response
+
+
+def _get_kwargs(
+ pool: str,
+ *,
+ body: BatchSubmitRequest,
+) -> dict[str, Any]:
+ headers: dict[str, Any] = {}
+
+ _kwargs: dict[str, Any] = {
+ "method": "post",
+ "url": "/api/batch/{pool}/submit".format(
+ pool=quote(str(pool), safe=""),
+ ),
+ }
+
+ _kwargs["json"] = body.to_dict()
+
+ headers["Content-Type"] = "application/json"
+
+ _kwargs["headers"] = headers
+ return _kwargs
+
+
+def _parse_response(
+ *, client: AuthenticatedClient | Client, response: httpx.Response
+) -> BatchSubmitResponse | ErrorResponse | None:
+ if response.status_code == 202:
+ response_202 = BatchSubmitResponse.from_dict(response.json())
+
+ return response_202
+
+ if response.status_code == 400:
+ response_400 = ErrorResponse.from_dict(response.json())
+
+ return response_400
+
+ if response.status_code == 401:
+ response_401 = ErrorResponse.from_dict(response.json())
+
+ return response_401
+
+ if client.raise_on_unexpected_status:
+ raise errors.UnexpectedStatus(response.status_code, response.content)
+ else:
+ return None
+
+
+def _build_response(
+ *, client: AuthenticatedClient | Client, response: httpx.Response
+) -> Response[BatchSubmitResponse | ErrorResponse]:
+ return Response(
+ status_code=HTTPStatus(response.status_code),
+ content=response.content,
+ headers=response.headers,
+ parsed=_parse_response(client=client, response=response),
+ )
+
+
+def sync_detailed(
+ pool: str,
+ *,
+ client: AuthenticatedClient | Client,
+ body: BatchSubmitRequest,
+) -> Response[BatchSubmitResponse | ErrorResponse]:
+ """Submit a batch of rollouts
+
+ Asynchronously queues a batch of OSGym rollouts under `{pool}`.
+ Returns immediately with a `batch_id`; poll
+ `/api/batch/{pool}/{id}/status` for progress and
+ `/api/batch/{pool}/{id}/results` for the final payload.
+
+ The pool is bound by the URL path; any `pool_name` in the body must
+ match the URL pool or the request is rejected with 400.
+
+ Args:
+ pool (str):
+ body (BatchSubmitRequest):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[BatchSubmitResponse | ErrorResponse]
+ """
+
+ kwargs = _get_kwargs(
+ pool=pool,
+ body=body,
+ )
+
+ response = client.get_httpx_client().request(
+ **kwargs,
+ )
+
+ return _build_response(client=client, response=response)
+
+
+def sync(
+ pool: str,
+ *,
+ client: AuthenticatedClient | Client,
+ body: BatchSubmitRequest,
+) -> BatchSubmitResponse | ErrorResponse | None:
+ """Submit a batch of rollouts
+
+ Asynchronously queues a batch of OSGym rollouts under `{pool}`.
+ Returns immediately with a `batch_id`; poll
+ `/api/batch/{pool}/{id}/status` for progress and
+ `/api/batch/{pool}/{id}/results` for the final payload.
+
+ The pool is bound by the URL path; any `pool_name` in the body must
+ match the URL pool or the request is rejected with 400.
+
+ Args:
+ pool (str):
+ body (BatchSubmitRequest):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ BatchSubmitResponse | ErrorResponse
+ """
+
+ return sync_detailed(
+ pool=pool,
+ client=client,
+ body=body,
+ ).parsed
+
+
+async def asyncio_detailed(
+ pool: str,
+ *,
+ client: AuthenticatedClient | Client,
+ body: BatchSubmitRequest,
+) -> Response[BatchSubmitResponse | ErrorResponse]:
+ """Submit a batch of rollouts
+
+ Asynchronously queues a batch of OSGym rollouts under `{pool}`.
+ Returns immediately with a `batch_id`; poll
+ `/api/batch/{pool}/{id}/status` for progress and
+ `/api/batch/{pool}/{id}/results` for the final payload.
+
+ The pool is bound by the URL path; any `pool_name` in the body must
+ match the URL pool or the request is rejected with 400.
+
+ Args:
+ pool (str):
+ body (BatchSubmitRequest):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[BatchSubmitResponse | ErrorResponse]
+ """
+
+ kwargs = _get_kwargs(
+ pool=pool,
+ body=body,
+ )
+
+ response = await client.get_async_httpx_client().request(**kwargs)
+
+ return _build_response(client=client, response=response)
+
+
+async def asyncio(
+ pool: str,
+ *,
+ client: AuthenticatedClient | Client,
+ body: BatchSubmitRequest,
+) -> BatchSubmitResponse | ErrorResponse | None:
+ """Submit a batch of rollouts
+
+ Asynchronously queues a batch of OSGym rollouts under `{pool}`.
+ Returns immediately with a `batch_id`; poll
+ `/api/batch/{pool}/{id}/status` for progress and
+ `/api/batch/{pool}/{id}/results` for the final payload.
+
+ The pool is bound by the URL path; any `pool_name` in the body must
+ match the URL pool or the request is rejected with 400.
+
+ Args:
+ pool (str):
+ body (BatchSubmitRequest):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ BatchSubmitResponse | ErrorResponse
+ """
+
+ return (
+ await asyncio_detailed(
+ pool=pool,
+ client=client,
+ body=body,
+ )
+ ).parsed
diff --git a/libs/fleet/python-sdk/cua_train/api/health/__init__.py b/libs/fleet/python-sdk/cua_train/api/health/__init__.py
new file mode 100644
index 0000000000..2d7c0b23da
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/api/health/__init__.py
@@ -0,0 +1 @@
+"""Contains endpoint functions for accessing the API"""
diff --git a/libs/fleet/python-sdk/cua_train/api/health/healthz.py b/libs/fleet/python-sdk/cua_train/api/health/healthz.py
new file mode 100644
index 0000000000..267c378898
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/api/health/healthz.py
@@ -0,0 +1,124 @@
+from http import HTTPStatus
+from typing import Any
+
+import httpx
+
+from ... import errors
+from ...client import AuthenticatedClient, Client
+from ...models.health_response import HealthResponse
+from ...types import Response
+
+
+def _get_kwargs() -> dict[str, Any]:
+
+ _kwargs: dict[str, Any] = {
+ "method": "get",
+ "url": "/healthz",
+ }
+
+ return _kwargs
+
+
+def _parse_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> HealthResponse | None:
+ if response.status_code == 200:
+ response_200 = HealthResponse.from_dict(response.json())
+
+ return response_200
+
+ if client.raise_on_unexpected_status:
+ raise errors.UnexpectedStatus(response.status_code, response.content)
+ else:
+ return None
+
+
+def _build_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> Response[HealthResponse]:
+ return Response(
+ status_code=HTTPStatus(response.status_code),
+ content=response.content,
+ headers=response.headers,
+ parsed=_parse_response(client=client, response=response),
+ )
+
+
+def sync_detailed(
+ *,
+ client: AuthenticatedClient | Client,
+) -> Response[HealthResponse]:
+ """Liveness/readiness probe
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[HealthResponse]
+ """
+
+ kwargs = _get_kwargs()
+
+ response = client.get_httpx_client().request(
+ **kwargs,
+ )
+
+ return _build_response(client=client, response=response)
+
+
+def sync(
+ *,
+ client: AuthenticatedClient | Client,
+) -> HealthResponse | None:
+ """Liveness/readiness probe
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ HealthResponse
+ """
+
+ return sync_detailed(
+ client=client,
+ ).parsed
+
+
+async def asyncio_detailed(
+ *,
+ client: AuthenticatedClient | Client,
+) -> Response[HealthResponse]:
+ """Liveness/readiness probe
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[HealthResponse]
+ """
+
+ kwargs = _get_kwargs()
+
+ response = await client.get_async_httpx_client().request(**kwargs)
+
+ return _build_response(client=client, response=response)
+
+
+async def asyncio(
+ *,
+ client: AuthenticatedClient | Client,
+) -> HealthResponse | None:
+ """Liveness/readiness probe
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ HealthResponse
+ """
+
+ return (
+ await asyncio_detailed(
+ client=client,
+ )
+ ).parsed
diff --git a/libs/fleet/python-sdk/cua_train/api/keys/__init__.py b/libs/fleet/python-sdk/cua_train/api/keys/__init__.py
new file mode 100644
index 0000000000..2d7c0b23da
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/api/keys/__init__.py
@@ -0,0 +1 @@
+"""Contains endpoint functions for accessing the API"""
diff --git a/libs/fleet/python-sdk/cua_train/api/keys/create_key.py b/libs/fleet/python-sdk/cua_train/api/keys/create_key.py
new file mode 100644
index 0000000000..b53a7760db
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/api/keys/create_key.py
@@ -0,0 +1,188 @@
+from http import HTTPStatus
+from typing import Any
+
+import httpx
+
+from ... import errors
+from ...client import AuthenticatedClient, Client
+from ...models.create_key_request import CreateKeyRequest
+from ...models.create_key_response import CreateKeyResponse
+from ...models.error_response import ErrorResponse
+from ...types import Response
+
+
+def _get_kwargs(
+ *,
+ body: CreateKeyRequest,
+) -> dict[str, Any]:
+ headers: dict[str, Any] = {}
+
+ _kwargs: dict[str, Any] = {
+ "method": "post",
+ "url": "/api/keys",
+ }
+
+ _kwargs["json"] = body.to_dict()
+
+ headers["Content-Type"] = "application/json"
+
+ _kwargs["headers"] = headers
+ return _kwargs
+
+
+def _parse_response(
+ *, client: AuthenticatedClient | Client, response: httpx.Response
+) -> CreateKeyResponse | ErrorResponse | None:
+ if response.status_code == 201:
+ response_201 = CreateKeyResponse.from_dict(response.json())
+
+ return response_201
+
+ if response.status_code == 400:
+ response_400 = ErrorResponse.from_dict(response.json())
+
+ return response_400
+
+ if response.status_code == 401:
+ response_401 = ErrorResponse.from_dict(response.json())
+
+ return response_401
+
+ if response.status_code == 403:
+ response_403 = ErrorResponse.from_dict(response.json())
+
+ return response_403
+
+ if client.raise_on_unexpected_status:
+ raise errors.UnexpectedStatus(response.status_code, response.content)
+ else:
+ return None
+
+
+def _build_response(
+ *, client: AuthenticatedClient | Client, response: httpx.Response
+) -> Response[CreateKeyResponse | ErrorResponse]:
+ return Response(
+ status_code=HTTPStatus(response.status_code),
+ content=response.content,
+ headers=response.headers,
+ parsed=_parse_response(client=client, response=response),
+ )
+
+
+def sync_detailed(
+ *,
+ client: AuthenticatedClient | Client,
+ body: CreateKeyRequest,
+) -> Response[CreateKeyResponse | ErrorResponse]:
+ """Create a new API key
+
+ Creates a Keycloak service-account client owned by the calling user. The returned `client_secret` is
+ shown exactly once.
+
+ Args:
+ body (CreateKeyRequest):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[CreateKeyResponse | ErrorResponse]
+ """
+
+ kwargs = _get_kwargs(
+ body=body,
+ )
+
+ response = client.get_httpx_client().request(
+ **kwargs,
+ )
+
+ return _build_response(client=client, response=response)
+
+
+def sync(
+ *,
+ client: AuthenticatedClient | Client,
+ body: CreateKeyRequest,
+) -> CreateKeyResponse | ErrorResponse | None:
+ """Create a new API key
+
+ Creates a Keycloak service-account client owned by the calling user. The returned `client_secret` is
+ shown exactly once.
+
+ Args:
+ body (CreateKeyRequest):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ CreateKeyResponse | ErrorResponse
+ """
+
+ return sync_detailed(
+ client=client,
+ body=body,
+ ).parsed
+
+
+async def asyncio_detailed(
+ *,
+ client: AuthenticatedClient | Client,
+ body: CreateKeyRequest,
+) -> Response[CreateKeyResponse | ErrorResponse]:
+ """Create a new API key
+
+ Creates a Keycloak service-account client owned by the calling user. The returned `client_secret` is
+ shown exactly once.
+
+ Args:
+ body (CreateKeyRequest):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[CreateKeyResponse | ErrorResponse]
+ """
+
+ kwargs = _get_kwargs(
+ body=body,
+ )
+
+ response = await client.get_async_httpx_client().request(**kwargs)
+
+ return _build_response(client=client, response=response)
+
+
+async def asyncio(
+ *,
+ client: AuthenticatedClient | Client,
+ body: CreateKeyRequest,
+) -> CreateKeyResponse | ErrorResponse | None:
+ """Create a new API key
+
+ Creates a Keycloak service-account client owned by the calling user. The returned `client_secret` is
+ shown exactly once.
+
+ Args:
+ body (CreateKeyRequest):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ CreateKeyResponse | ErrorResponse
+ """
+
+ return (
+ await asyncio_detailed(
+ client=client,
+ body=body,
+ )
+ ).parsed
diff --git a/libs/fleet/python-sdk/cua_train/api/keys/delete_key.py b/libs/fleet/python-sdk/cua_train/api/keys/delete_key.py
new file mode 100644
index 0000000000..05dd935582
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/api/keys/delete_key.py
@@ -0,0 +1,160 @@
+from http import HTTPStatus
+from typing import Any, cast
+from urllib.parse import quote
+
+import httpx
+
+from ... import errors
+from ...client import AuthenticatedClient, Client
+from ...models.error_response import ErrorResponse
+from ...types import Response
+
+
+def _get_kwargs(
+ id: str,
+) -> dict[str, Any]:
+
+ _kwargs: dict[str, Any] = {
+ "method": "delete",
+ "url": "/api/keys/{id}".format(
+ id=quote(str(id), safe=""),
+ ),
+ }
+
+ return _kwargs
+
+
+def _parse_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> Any | ErrorResponse | None:
+ if response.status_code == 204:
+ response_204 = cast(Any, None)
+ return response_204
+
+ if response.status_code == 401:
+ response_401 = ErrorResponse.from_dict(response.json())
+
+ return response_401
+
+ if response.status_code == 403:
+ response_403 = ErrorResponse.from_dict(response.json())
+
+ return response_403
+
+ if client.raise_on_unexpected_status:
+ raise errors.UnexpectedStatus(response.status_code, response.content)
+ else:
+ return None
+
+
+def _build_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> Response[Any | ErrorResponse]:
+ return Response(
+ status_code=HTTPStatus(response.status_code),
+ content=response.content,
+ headers=response.headers,
+ parsed=_parse_response(client=client, response=response),
+ )
+
+
+def sync_detailed(
+ id: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> Response[Any | ErrorResponse]:
+ """Revoke an API key by Keycloak client UUID
+
+ Args:
+ id (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[Any | ErrorResponse]
+ """
+
+ kwargs = _get_kwargs(
+ id=id,
+ )
+
+ response = client.get_httpx_client().request(
+ **kwargs,
+ )
+
+ return _build_response(client=client, response=response)
+
+
+def sync(
+ id: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> Any | ErrorResponse | None:
+ """Revoke an API key by Keycloak client UUID
+
+ Args:
+ id (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Any | ErrorResponse
+ """
+
+ return sync_detailed(
+ id=id,
+ client=client,
+ ).parsed
+
+
+async def asyncio_detailed(
+ id: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> Response[Any | ErrorResponse]:
+ """Revoke an API key by Keycloak client UUID
+
+ Args:
+ id (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[Any | ErrorResponse]
+ """
+
+ kwargs = _get_kwargs(
+ id=id,
+ )
+
+ response = await client.get_async_httpx_client().request(**kwargs)
+
+ return _build_response(client=client, response=response)
+
+
+async def asyncio(
+ id: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> Any | ErrorResponse | None:
+ """Revoke an API key by Keycloak client UUID
+
+ Args:
+ id (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Any | ErrorResponse
+ """
+
+ return (
+ await asyncio_detailed(
+ id=id,
+ client=client,
+ )
+ ).parsed
diff --git a/libs/fleet/python-sdk/cua_train/api/keys/list_keys.py b/libs/fleet/python-sdk/cua_train/api/keys/list_keys.py
new file mode 100644
index 0000000000..5b3936ff2f
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/api/keys/list_keys.py
@@ -0,0 +1,134 @@
+from http import HTTPStatus
+from typing import Any
+
+import httpx
+
+from ... import errors
+from ...client import AuthenticatedClient, Client
+from ...models.error_response import ErrorResponse
+from ...models.list_keys_response import ListKeysResponse
+from ...types import Response
+
+
+def _get_kwargs() -> dict[str, Any]:
+
+ _kwargs: dict[str, Any] = {
+ "method": "get",
+ "url": "/api/keys",
+ }
+
+ return _kwargs
+
+
+def _parse_response(
+ *, client: AuthenticatedClient | Client, response: httpx.Response
+) -> ErrorResponse | ListKeysResponse | None:
+ if response.status_code == 200:
+ response_200 = ListKeysResponse.from_dict(response.json())
+
+ return response_200
+
+ if response.status_code == 401:
+ response_401 = ErrorResponse.from_dict(response.json())
+
+ return response_401
+
+ if client.raise_on_unexpected_status:
+ raise errors.UnexpectedStatus(response.status_code, response.content)
+ else:
+ return None
+
+
+def _build_response(
+ *, client: AuthenticatedClient | Client, response: httpx.Response
+) -> Response[ErrorResponse | ListKeysResponse]:
+ return Response(
+ status_code=HTTPStatus(response.status_code),
+ content=response.content,
+ headers=response.headers,
+ parsed=_parse_response(client=client, response=response),
+ )
+
+
+def sync_detailed(
+ *,
+ client: AuthenticatedClient | Client,
+) -> Response[ErrorResponse | ListKeysResponse]:
+ """List the calling user's API keys
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[ErrorResponse | ListKeysResponse]
+ """
+
+ kwargs = _get_kwargs()
+
+ response = client.get_httpx_client().request(
+ **kwargs,
+ )
+
+ return _build_response(client=client, response=response)
+
+
+def sync(
+ *,
+ client: AuthenticatedClient | Client,
+) -> ErrorResponse | ListKeysResponse | None:
+ """List the calling user's API keys
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ ErrorResponse | ListKeysResponse
+ """
+
+ return sync_detailed(
+ client=client,
+ ).parsed
+
+
+async def asyncio_detailed(
+ *,
+ client: AuthenticatedClient | Client,
+) -> Response[ErrorResponse | ListKeysResponse]:
+ """List the calling user's API keys
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[ErrorResponse | ListKeysResponse]
+ """
+
+ kwargs = _get_kwargs()
+
+ response = await client.get_async_httpx_client().request(**kwargs)
+
+ return _build_response(client=client, response=response)
+
+
+async def asyncio(
+ *,
+ client: AuthenticatedClient | Client,
+) -> ErrorResponse | ListKeysResponse | None:
+ """List the calling user's API keys
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ ErrorResponse | ListKeysResponse
+ """
+
+ return (
+ await asyncio_detailed(
+ client=client,
+ )
+ ).parsed
diff --git a/libs/fleet/python-sdk/cua_train/api/label/__init__.py b/libs/fleet/python-sdk/cua_train/api/label/__init__.py
new file mode 100644
index 0000000000..2d7c0b23da
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/api/label/__init__.py
@@ -0,0 +1 @@
+"""Contains endpoint functions for accessing the API"""
diff --git a/libs/fleet/python-sdk/cua_train/api/label/cancel_label.py b/libs/fleet/python-sdk/cua_train/api/label/cancel_label.py
new file mode 100644
index 0000000000..c22be8df0f
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/api/label/cancel_label.py
@@ -0,0 +1,188 @@
+from http import HTTPStatus
+from typing import Any
+from urllib.parse import quote
+
+import httpx
+
+from ... import errors
+from ...client import AuthenticatedClient, Client
+from ...models.cancel_label_response import CancelLabelResponse
+from ...models.error_response import ErrorResponse
+from ...types import Response
+
+
+def _get_kwargs(
+ pool: str,
+ label: str,
+) -> dict[str, Any]:
+
+ _kwargs: dict[str, Any] = {
+ "method": "delete",
+ "url": "/api/label/{pool}/{label}".format(
+ pool=quote(str(pool), safe=""),
+ label=quote(str(label), safe=""),
+ ),
+ }
+
+ return _kwargs
+
+
+def _parse_response(
+ *, client: AuthenticatedClient | Client, response: httpx.Response
+) -> CancelLabelResponse | ErrorResponse | None:
+ if response.status_code == 200:
+ response_200 = CancelLabelResponse.from_dict(response.json())
+
+ return response_200
+
+ if response.status_code == 401:
+ response_401 = ErrorResponse.from_dict(response.json())
+
+ return response_401
+
+ if response.status_code == 404:
+ response_404 = ErrorResponse.from_dict(response.json())
+
+ return response_404
+
+ if client.raise_on_unexpected_status:
+ raise errors.UnexpectedStatus(response.status_code, response.content)
+ else:
+ return None
+
+
+def _build_response(
+ *, client: AuthenticatedClient | Client, response: httpx.Response
+) -> Response[CancelLabelResponse | ErrorResponse]:
+ return Response(
+ status_code=HTTPStatus(response.status_code),
+ content=response.content,
+ headers=response.headers,
+ parsed=_parse_response(client=client, response=response),
+ )
+
+
+def sync_detailed(
+ pool: str,
+ label: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> Response[CancelLabelResponse | ErrorResponse]:
+ """Cancel every non-terminal batch under a label (scoped to pool)
+
+ Cancels only batches submitted under `{pool}`; same label in other pools is untouched.
+
+ Args:
+ pool (str):
+ label (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[CancelLabelResponse | ErrorResponse]
+ """
+
+ kwargs = _get_kwargs(
+ pool=pool,
+ label=label,
+ )
+
+ response = client.get_httpx_client().request(
+ **kwargs,
+ )
+
+ return _build_response(client=client, response=response)
+
+
+def sync(
+ pool: str,
+ label: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> CancelLabelResponse | ErrorResponse | None:
+ """Cancel every non-terminal batch under a label (scoped to pool)
+
+ Cancels only batches submitted under `{pool}`; same label in other pools is untouched.
+
+ Args:
+ pool (str):
+ label (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ CancelLabelResponse | ErrorResponse
+ """
+
+ return sync_detailed(
+ pool=pool,
+ label=label,
+ client=client,
+ ).parsed
+
+
+async def asyncio_detailed(
+ pool: str,
+ label: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> Response[CancelLabelResponse | ErrorResponse]:
+ """Cancel every non-terminal batch under a label (scoped to pool)
+
+ Cancels only batches submitted under `{pool}`; same label in other pools is untouched.
+
+ Args:
+ pool (str):
+ label (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[CancelLabelResponse | ErrorResponse]
+ """
+
+ kwargs = _get_kwargs(
+ pool=pool,
+ label=label,
+ )
+
+ response = await client.get_async_httpx_client().request(**kwargs)
+
+ return _build_response(client=client, response=response)
+
+
+async def asyncio(
+ pool: str,
+ label: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> CancelLabelResponse | ErrorResponse | None:
+ """Cancel every non-terminal batch under a label (scoped to pool)
+
+ Cancels only batches submitted under `{pool}`; same label in other pools is untouched.
+
+ Args:
+ pool (str):
+ label (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ CancelLabelResponse | ErrorResponse
+ """
+
+ return (
+ await asyncio_detailed(
+ pool=pool,
+ label=label,
+ client=client,
+ )
+ ).parsed
diff --git a/libs/fleet/python-sdk/cua_train/api/label/get_label_results.py b/libs/fleet/python-sdk/cua_train/api/label/get_label_results.py
new file mode 100644
index 0000000000..9083fd115a
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/api/label/get_label_results.py
@@ -0,0 +1,227 @@
+from http import HTTPStatus
+from typing import Any
+from urllib.parse import quote
+
+import httpx
+
+from ... import errors
+from ...client import AuthenticatedClient, Client
+from ...models.error_response import ErrorResponse
+from ...models.label_in_progress_response import LabelInProgressResponse
+from ...models.label_results_response import LabelResultsResponse
+from ...types import UNSET, Response, Unset
+
+
+def _get_kwargs(
+ pool: str,
+ label: str,
+ *,
+ completed_only: bool | Unset = UNSET,
+) -> dict[str, Any]:
+
+ params: dict[str, Any] = {}
+
+ params["completed_only"] = completed_only
+
+ params = {k: v for k, v in params.items() if v is not UNSET and v is not None}
+
+ _kwargs: dict[str, Any] = {
+ "method": "get",
+ "url": "/api/label/{pool}/{label}/results".format(
+ pool=quote(str(pool), safe=""),
+ label=quote(str(label), safe=""),
+ ),
+ "params": params,
+ }
+
+ return _kwargs
+
+
+def _parse_response(
+ *, client: AuthenticatedClient | Client, response: httpx.Response
+) -> ErrorResponse | LabelInProgressResponse | LabelResultsResponse | None:
+ if response.status_code == 200:
+ response_200 = LabelResultsResponse.from_dict(response.json())
+
+ return response_200
+
+ if response.status_code == 202:
+ response_202 = LabelInProgressResponse.from_dict(response.json())
+
+ return response_202
+
+ if response.status_code == 401:
+ response_401 = ErrorResponse.from_dict(response.json())
+
+ return response_401
+
+ if response.status_code == 404:
+ response_404 = ErrorResponse.from_dict(response.json())
+
+ return response_404
+
+ if client.raise_on_unexpected_status:
+ raise errors.UnexpectedStatus(response.status_code, response.content)
+ else:
+ return None
+
+
+def _build_response(
+ *, client: AuthenticatedClient | Client, response: httpx.Response
+) -> Response[ErrorResponse | LabelInProgressResponse | LabelResultsResponse]:
+ return Response(
+ status_code=HTTPStatus(response.status_code),
+ content=response.content,
+ headers=response.headers,
+ parsed=_parse_response(client=client, response=response),
+ )
+
+
+def sync_detailed(
+ pool: str,
+ label: str,
+ *,
+ client: AuthenticatedClient | Client,
+ completed_only: bool | Unset = UNSET,
+) -> Response[ErrorResponse | LabelInProgressResponse | LabelResultsResponse]:
+ """Aggregate results for all batches under a pool+label
+
+ Default mode returns 200 only once every matched batch is completed.
+ Pass `?completed_only=true` to drain partial results (200 with the
+ filtered subset; non-completed batches are visible via status).
+ Aggregates only batches submitted under `{pool}`.
+
+ Args:
+ pool (str):
+ label (str):
+ completed_only (bool | Unset):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[ErrorResponse | LabelInProgressResponse | LabelResultsResponse]
+ """
+
+ kwargs = _get_kwargs(
+ pool=pool,
+ label=label,
+ completed_only=completed_only,
+ )
+
+ response = client.get_httpx_client().request(
+ **kwargs,
+ )
+
+ return _build_response(client=client, response=response)
+
+
+def sync(
+ pool: str,
+ label: str,
+ *,
+ client: AuthenticatedClient | Client,
+ completed_only: bool | Unset = UNSET,
+) -> ErrorResponse | LabelInProgressResponse | LabelResultsResponse | None:
+ """Aggregate results for all batches under a pool+label
+
+ Default mode returns 200 only once every matched batch is completed.
+ Pass `?completed_only=true` to drain partial results (200 with the
+ filtered subset; non-completed batches are visible via status).
+ Aggregates only batches submitted under `{pool}`.
+
+ Args:
+ pool (str):
+ label (str):
+ completed_only (bool | Unset):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ ErrorResponse | LabelInProgressResponse | LabelResultsResponse
+ """
+
+ return sync_detailed(
+ pool=pool,
+ label=label,
+ client=client,
+ completed_only=completed_only,
+ ).parsed
+
+
+async def asyncio_detailed(
+ pool: str,
+ label: str,
+ *,
+ client: AuthenticatedClient | Client,
+ completed_only: bool | Unset = UNSET,
+) -> Response[ErrorResponse | LabelInProgressResponse | LabelResultsResponse]:
+ """Aggregate results for all batches under a pool+label
+
+ Default mode returns 200 only once every matched batch is completed.
+ Pass `?completed_only=true` to drain partial results (200 with the
+ filtered subset; non-completed batches are visible via status).
+ Aggregates only batches submitted under `{pool}`.
+
+ Args:
+ pool (str):
+ label (str):
+ completed_only (bool | Unset):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[ErrorResponse | LabelInProgressResponse | LabelResultsResponse]
+ """
+
+ kwargs = _get_kwargs(
+ pool=pool,
+ label=label,
+ completed_only=completed_only,
+ )
+
+ response = await client.get_async_httpx_client().request(**kwargs)
+
+ return _build_response(client=client, response=response)
+
+
+async def asyncio(
+ pool: str,
+ label: str,
+ *,
+ client: AuthenticatedClient | Client,
+ completed_only: bool | Unset = UNSET,
+) -> ErrorResponse | LabelInProgressResponse | LabelResultsResponse | None:
+ """Aggregate results for all batches under a pool+label
+
+ Default mode returns 200 only once every matched batch is completed.
+ Pass `?completed_only=true` to drain partial results (200 with the
+ filtered subset; non-completed batches are visible via status).
+ Aggregates only batches submitted under `{pool}`.
+
+ Args:
+ pool (str):
+ label (str):
+ completed_only (bool | Unset):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ ErrorResponse | LabelInProgressResponse | LabelResultsResponse
+ """
+
+ return (
+ await asyncio_detailed(
+ pool=pool,
+ label=label,
+ client=client,
+ completed_only=completed_only,
+ )
+ ).parsed
diff --git a/libs/fleet/python-sdk/cua_train/api/label/get_label_status.py b/libs/fleet/python-sdk/cua_train/api/label/get_label_status.py
new file mode 100644
index 0000000000..815a0f9507
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/api/label/get_label_status.py
@@ -0,0 +1,192 @@
+from http import HTTPStatus
+from typing import Any
+from urllib.parse import quote
+
+import httpx
+
+from ... import errors
+from ...client import AuthenticatedClient, Client
+from ...models.error_response import ErrorResponse
+from ...models.label_status_response import LabelStatusResponse
+from ...types import Response
+
+
+def _get_kwargs(
+ pool: str,
+ label: str,
+) -> dict[str, Any]:
+
+ _kwargs: dict[str, Any] = {
+ "method": "get",
+ "url": "/api/label/{pool}/{label}/status".format(
+ pool=quote(str(pool), safe=""),
+ label=quote(str(label), safe=""),
+ ),
+ }
+
+ return _kwargs
+
+
+def _parse_response(
+ *, client: AuthenticatedClient | Client, response: httpx.Response
+) -> ErrorResponse | LabelStatusResponse | None:
+ if response.status_code == 200:
+ response_200 = LabelStatusResponse.from_dict(response.json())
+
+ return response_200
+
+ if response.status_code == 401:
+ response_401 = ErrorResponse.from_dict(response.json())
+
+ return response_401
+
+ if response.status_code == 404:
+ response_404 = ErrorResponse.from_dict(response.json())
+
+ return response_404
+
+ if client.raise_on_unexpected_status:
+ raise errors.UnexpectedStatus(response.status_code, response.content)
+ else:
+ return None
+
+
+def _build_response(
+ *, client: AuthenticatedClient | Client, response: httpx.Response
+) -> Response[ErrorResponse | LabelStatusResponse]:
+ return Response(
+ status_code=HTTPStatus(response.status_code),
+ content=response.content,
+ headers=response.headers,
+ parsed=_parse_response(client=client, response=response),
+ )
+
+
+def sync_detailed(
+ pool: str,
+ label: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> Response[ErrorResponse | LabelStatusResponse]:
+ """Aggregate status for all batches under a pool+label
+
+ Aggregates only batches submitted under `{pool}`; batches with the same label in other pools are
+ invisible.
+
+ Args:
+ pool (str):
+ label (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[ErrorResponse | LabelStatusResponse]
+ """
+
+ kwargs = _get_kwargs(
+ pool=pool,
+ label=label,
+ )
+
+ response = client.get_httpx_client().request(
+ **kwargs,
+ )
+
+ return _build_response(client=client, response=response)
+
+
+def sync(
+ pool: str,
+ label: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> ErrorResponse | LabelStatusResponse | None:
+ """Aggregate status for all batches under a pool+label
+
+ Aggregates only batches submitted under `{pool}`; batches with the same label in other pools are
+ invisible.
+
+ Args:
+ pool (str):
+ label (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ ErrorResponse | LabelStatusResponse
+ """
+
+ return sync_detailed(
+ pool=pool,
+ label=label,
+ client=client,
+ ).parsed
+
+
+async def asyncio_detailed(
+ pool: str,
+ label: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> Response[ErrorResponse | LabelStatusResponse]:
+ """Aggregate status for all batches under a pool+label
+
+ Aggregates only batches submitted under `{pool}`; batches with the same label in other pools are
+ invisible.
+
+ Args:
+ pool (str):
+ label (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[ErrorResponse | LabelStatusResponse]
+ """
+
+ kwargs = _get_kwargs(
+ pool=pool,
+ label=label,
+ )
+
+ response = await client.get_async_httpx_client().request(**kwargs)
+
+ return _build_response(client=client, response=response)
+
+
+async def asyncio(
+ pool: str,
+ label: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> ErrorResponse | LabelStatusResponse | None:
+ """Aggregate status for all batches under a pool+label
+
+ Aggregates only batches submitted under `{pool}`; batches with the same label in other pools are
+ invisible.
+
+ Args:
+ pool (str):
+ label (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ ErrorResponse | LabelStatusResponse
+ """
+
+ return (
+ await asyncio_detailed(
+ pool=pool,
+ label=label,
+ client=client,
+ )
+ ).parsed
diff --git a/libs/fleet/python-sdk/cua_train/api/label/submit_label_batch.py b/libs/fleet/python-sdk/cua_train/api/label/submit_label_batch.py
new file mode 100644
index 0000000000..3131b4242a
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/api/label/submit_label_batch.py
@@ -0,0 +1,225 @@
+from http import HTTPStatus
+from typing import Any
+from urllib.parse import quote
+
+import httpx
+
+from ... import errors
+from ...client import AuthenticatedClient, Client
+from ...models.batch_submit_request import BatchSubmitRequest
+from ...models.batch_submit_response import BatchSubmitResponse
+from ...models.error_response import ErrorResponse
+from ...types import Response
+
+
+def _get_kwargs(
+ pool: str,
+ label: str,
+ *,
+ body: BatchSubmitRequest,
+) -> dict[str, Any]:
+ headers: dict[str, Any] = {}
+
+ _kwargs: dict[str, Any] = {
+ "method": "post",
+ "url": "/api/label/{pool}/{label}/batch".format(
+ pool=quote(str(pool), safe=""),
+ label=quote(str(label), safe=""),
+ ),
+ }
+
+ _kwargs["json"] = body.to_dict()
+
+ headers["Content-Type"] = "application/json"
+
+ _kwargs["headers"] = headers
+ return _kwargs
+
+
+def _parse_response(
+ *, client: AuthenticatedClient | Client, response: httpx.Response
+) -> BatchSubmitResponse | ErrorResponse | None:
+ if response.status_code == 202:
+ response_202 = BatchSubmitResponse.from_dict(response.json())
+
+ return response_202
+
+ if response.status_code == 400:
+ response_400 = ErrorResponse.from_dict(response.json())
+
+ return response_400
+
+ if response.status_code == 401:
+ response_401 = ErrorResponse.from_dict(response.json())
+
+ return response_401
+
+ if client.raise_on_unexpected_status:
+ raise errors.UnexpectedStatus(response.status_code, response.content)
+ else:
+ return None
+
+
+def _build_response(
+ *, client: AuthenticatedClient | Client, response: httpx.Response
+) -> Response[BatchSubmitResponse | ErrorResponse]:
+ return Response(
+ status_code=HTTPStatus(response.status_code),
+ content=response.content,
+ headers=response.headers,
+ parsed=_parse_response(client=client, response=response),
+ )
+
+
+def sync_detailed(
+ pool: str,
+ label: str,
+ *,
+ client: AuthenticatedClient | Client,
+ body: BatchSubmitRequest,
+) -> Response[BatchSubmitResponse | ErrorResponse]:
+ """Submit a batch under a pool and label
+
+ Same as `/api/batch/{pool}/submit` but pins the batch's `name`
+ field to the URL label, overriding any value in the body. The
+ label is scoped to `{pool}`; aggregate routes under
+ `/api/label/{pool}/{label}/*` only see batches submitted to the
+ same pool.
+
+ Args:
+ pool (str):
+ label (str):
+ body (BatchSubmitRequest):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[BatchSubmitResponse | ErrorResponse]
+ """
+
+ kwargs = _get_kwargs(
+ pool=pool,
+ label=label,
+ body=body,
+ )
+
+ response = client.get_httpx_client().request(
+ **kwargs,
+ )
+
+ return _build_response(client=client, response=response)
+
+
+def sync(
+ pool: str,
+ label: str,
+ *,
+ client: AuthenticatedClient | Client,
+ body: BatchSubmitRequest,
+) -> BatchSubmitResponse | ErrorResponse | None:
+ """Submit a batch under a pool and label
+
+ Same as `/api/batch/{pool}/submit` but pins the batch's `name`
+ field to the URL label, overriding any value in the body. The
+ label is scoped to `{pool}`; aggregate routes under
+ `/api/label/{pool}/{label}/*` only see batches submitted to the
+ same pool.
+
+ Args:
+ pool (str):
+ label (str):
+ body (BatchSubmitRequest):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ BatchSubmitResponse | ErrorResponse
+ """
+
+ return sync_detailed(
+ pool=pool,
+ label=label,
+ client=client,
+ body=body,
+ ).parsed
+
+
+async def asyncio_detailed(
+ pool: str,
+ label: str,
+ *,
+ client: AuthenticatedClient | Client,
+ body: BatchSubmitRequest,
+) -> Response[BatchSubmitResponse | ErrorResponse]:
+ """Submit a batch under a pool and label
+
+ Same as `/api/batch/{pool}/submit` but pins the batch's `name`
+ field to the URL label, overriding any value in the body. The
+ label is scoped to `{pool}`; aggregate routes under
+ `/api/label/{pool}/{label}/*` only see batches submitted to the
+ same pool.
+
+ Args:
+ pool (str):
+ label (str):
+ body (BatchSubmitRequest):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[BatchSubmitResponse | ErrorResponse]
+ """
+
+ kwargs = _get_kwargs(
+ pool=pool,
+ label=label,
+ body=body,
+ )
+
+ response = await client.get_async_httpx_client().request(**kwargs)
+
+ return _build_response(client=client, response=response)
+
+
+async def asyncio(
+ pool: str,
+ label: str,
+ *,
+ client: AuthenticatedClient | Client,
+ body: BatchSubmitRequest,
+) -> BatchSubmitResponse | ErrorResponse | None:
+ """Submit a batch under a pool and label
+
+ Same as `/api/batch/{pool}/submit` but pins the batch's `name`
+ field to the URL label, overriding any value in the body. The
+ label is scoped to `{pool}`; aggregate routes under
+ `/api/label/{pool}/{label}/*` only see batches submitted to the
+ same pool.
+
+ Args:
+ pool (str):
+ label (str):
+ body (BatchSubmitRequest):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ BatchSubmitResponse | ErrorResponse
+ """
+
+ return (
+ await asyncio_detailed(
+ pool=pool,
+ label=label,
+ client=client,
+ body=body,
+ )
+ ).parsed
diff --git a/libs/fleet/python-sdk/cua_train/api/lanes/__init__.py b/libs/fleet/python-sdk/cua_train/api/lanes/__init__.py
new file mode 100644
index 0000000000..2d7c0b23da
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/api/lanes/__init__.py
@@ -0,0 +1 @@
+"""Contains endpoint functions for accessing the API"""
diff --git a/libs/fleet/python-sdk/cua_train/api/lanes/create_lane_lanes_post.py b/libs/fleet/python-sdk/cua_train/api/lanes/create_lane_lanes_post.py
new file mode 100644
index 0000000000..0b99cd2dc1
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/api/lanes/create_lane_lanes_post.py
@@ -0,0 +1,220 @@
+from http import HTTPStatus
+from typing import Any
+from urllib.parse import quote
+
+import httpx
+
+from ... import errors
+from ...client import AuthenticatedClient, Client
+from ...models.lane_create_request import LaneCreateRequest
+from ...models.lane_response import LaneResponse
+from ...types import Response
+
+
+def _get_kwargs(
+ pool: str,
+ *,
+ body: LaneCreateRequest,
+) -> dict[str, Any]:
+ headers: dict[str, Any] = {}
+
+ _kwargs: dict[str, Any] = {
+ "method": "post",
+ "url": "/api/gateway/{pool}/lanes".format(
+ pool=quote(str(pool), safe=""),
+ ),
+ }
+
+ _kwargs["json"] = body.to_dict()
+
+ headers["Content-Type"] = "application/json"
+
+ _kwargs["headers"] = headers
+ return _kwargs
+
+
+def _parse_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> LaneResponse | None:
+ if response.status_code == 200:
+ response_200 = LaneResponse.from_dict(response.json())
+
+ return response_200
+
+ if client.raise_on_unexpected_status:
+ raise errors.UnexpectedStatus(response.status_code, response.content)
+ else:
+ return None
+
+
+def _build_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> Response[LaneResponse]:
+ return Response(
+ status_code=HTTPStatus(response.status_code),
+ content=response.content,
+ headers=response.headers,
+ parsed=_parse_response(client=client, response=response),
+ )
+
+
+def sync_detailed(
+ pool: str,
+ *,
+ client: AuthenticatedClient | Client,
+ body: LaneCreateRequest,
+) -> Response[LaneResponse]:
+ """Create Lane
+
+ Create a lane: a fresh OSGymSandboxClaim bound to a Sandbox.
+
+ The lane id is the stable handle the customer holds. The
+ underlying claim CR's name rotates on swap; the lane id does
+ not. The initial bind is via the normal queue+CAS-PATCH flow,
+ same as /reset.
+
+ Args:
+ pool (str):
+ body (LaneCreateRequest): Body of POST /lanes.
+
+ ``ttl_seconds`` is the absolute time the claim is reserved for;
+ after that the reaper deletes it. With ``autoRenew=true`` the lane
+ auto-renew timer in pool-operator pushes this forward, so the
+ customer's effective TTL is "as long as the lane exists".
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[LaneResponse]
+ """
+
+ kwargs = _get_kwargs(
+ pool=pool,
+ body=body,
+ )
+
+ response = client.get_httpx_client().request(
+ **kwargs,
+ )
+
+ return _build_response(client=client, response=response)
+
+
+def sync(
+ pool: str,
+ *,
+ client: AuthenticatedClient | Client,
+ body: LaneCreateRequest,
+) -> LaneResponse | None:
+ """Create Lane
+
+ Create a lane: a fresh OSGymSandboxClaim bound to a Sandbox.
+
+ The lane id is the stable handle the customer holds. The
+ underlying claim CR's name rotates on swap; the lane id does
+ not. The initial bind is via the normal queue+CAS-PATCH flow,
+ same as /reset.
+
+ Args:
+ pool (str):
+ body (LaneCreateRequest): Body of POST /lanes.
+
+ ``ttl_seconds`` is the absolute time the claim is reserved for;
+ after that the reaper deletes it. With ``autoRenew=true`` the lane
+ auto-renew timer in pool-operator pushes this forward, so the
+ customer's effective TTL is "as long as the lane exists".
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ LaneResponse
+ """
+
+ return sync_detailed(
+ pool=pool,
+ client=client,
+ body=body,
+ ).parsed
+
+
+async def asyncio_detailed(
+ pool: str,
+ *,
+ client: AuthenticatedClient | Client,
+ body: LaneCreateRequest,
+) -> Response[LaneResponse]:
+ """Create Lane
+
+ Create a lane: a fresh OSGymSandboxClaim bound to a Sandbox.
+
+ The lane id is the stable handle the customer holds. The
+ underlying claim CR's name rotates on swap; the lane id does
+ not. The initial bind is via the normal queue+CAS-PATCH flow,
+ same as /reset.
+
+ Args:
+ pool (str):
+ body (LaneCreateRequest): Body of POST /lanes.
+
+ ``ttl_seconds`` is the absolute time the claim is reserved for;
+ after that the reaper deletes it. With ``autoRenew=true`` the lane
+ auto-renew timer in pool-operator pushes this forward, so the
+ customer's effective TTL is "as long as the lane exists".
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[LaneResponse]
+ """
+
+ kwargs = _get_kwargs(
+ pool=pool,
+ body=body,
+ )
+
+ response = await client.get_async_httpx_client().request(**kwargs)
+
+ return _build_response(client=client, response=response)
+
+
+async def asyncio(
+ pool: str,
+ *,
+ client: AuthenticatedClient | Client,
+ body: LaneCreateRequest,
+) -> LaneResponse | None:
+ """Create Lane
+
+ Create a lane: a fresh OSGymSandboxClaim bound to a Sandbox.
+
+ The lane id is the stable handle the customer holds. The
+ underlying claim CR's name rotates on swap; the lane id does
+ not. The initial bind is via the normal queue+CAS-PATCH flow,
+ same as /reset.
+
+ Args:
+ pool (str):
+ body (LaneCreateRequest): Body of POST /lanes.
+
+ ``ttl_seconds`` is the absolute time the claim is reserved for;
+ after that the reaper deletes it. With ``autoRenew=true`` the lane
+ auto-renew timer in pool-operator pushes this forward, so the
+ customer's effective TTL is "as long as the lane exists".
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ LaneResponse
+ """
+
+ return (
+ await asyncio_detailed(
+ pool=pool,
+ client=client,
+ body=body,
+ )
+ ).parsed
diff --git a/libs/fleet/python-sdk/cua_train/api/lanes/delete_lane_lanes_lane_id_delete.py b/libs/fleet/python-sdk/cua_train/api/lanes/delete_lane_lanes_lane_id_delete.py
new file mode 100644
index 0000000000..970656aa75
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/api/lanes/delete_lane_lanes_lane_id_delete.py
@@ -0,0 +1,173 @@
+from http import HTTPStatus
+from typing import Any
+from urllib.parse import quote
+
+import httpx
+
+from ... import errors
+from ...client import AuthenticatedClient, Client
+from ...models.lane_delete_response import LaneDeleteResponse
+from ...types import Response
+
+
+def _get_kwargs(
+ pool: str,
+ lane_id: str,
+) -> dict[str, Any]:
+
+ _kwargs: dict[str, Any] = {
+ "method": "delete",
+ "url": "/api/gateway/{pool}/lanes/{lane_id}".format(
+ pool=quote(str(pool), safe=""),
+ lane_id=quote(str(lane_id), safe=""),
+ ),
+ }
+
+ return _kwargs
+
+
+def _parse_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> LaneDeleteResponse | None:
+ if response.status_code == 200:
+ response_200 = LaneDeleteResponse.from_dict(response.json())
+
+ return response_200
+
+ if client.raise_on_unexpected_status:
+ raise errors.UnexpectedStatus(response.status_code, response.content)
+ else:
+ return None
+
+
+def _build_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> Response[LaneDeleteResponse]:
+ return Response(
+ status_code=HTTPStatus(response.status_code),
+ content=response.content,
+ headers=response.headers,
+ parsed=_parse_response(client=client, response=response),
+ )
+
+
+def sync_detailed(
+ pool: str,
+ lane_id: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> Response[LaneDeleteResponse]:
+ """Delete Lane
+
+ Release the lane's bound claim. Idempotent.
+
+ Args:
+ pool (str):
+ lane_id (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[LaneDeleteResponse]
+ """
+
+ kwargs = _get_kwargs(
+ pool=pool,
+ lane_id=lane_id,
+ )
+
+ response = client.get_httpx_client().request(
+ **kwargs,
+ )
+
+ return _build_response(client=client, response=response)
+
+
+def sync(
+ pool: str,
+ lane_id: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> LaneDeleteResponse | None:
+ """Delete Lane
+
+ Release the lane's bound claim. Idempotent.
+
+ Args:
+ pool (str):
+ lane_id (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ LaneDeleteResponse
+ """
+
+ return sync_detailed(
+ pool=pool,
+ lane_id=lane_id,
+ client=client,
+ ).parsed
+
+
+async def asyncio_detailed(
+ pool: str,
+ lane_id: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> Response[LaneDeleteResponse]:
+ """Delete Lane
+
+ Release the lane's bound claim. Idempotent.
+
+ Args:
+ pool (str):
+ lane_id (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[LaneDeleteResponse]
+ """
+
+ kwargs = _get_kwargs(
+ pool=pool,
+ lane_id=lane_id,
+ )
+
+ response = await client.get_async_httpx_client().request(**kwargs)
+
+ return _build_response(client=client, response=response)
+
+
+async def asyncio(
+ pool: str,
+ lane_id: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> LaneDeleteResponse | None:
+ """Delete Lane
+
+ Release the lane's bound claim. Idempotent.
+
+ Args:
+ pool (str):
+ lane_id (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ LaneDeleteResponse
+ """
+
+ return (
+ await asyncio_detailed(
+ pool=pool,
+ lane_id=lane_id,
+ client=client,
+ )
+ ).parsed
diff --git a/libs/fleet/python-sdk/cua_train/api/lanes/swap_lanes_lane_id_swap_post.py b/libs/fleet/python-sdk/cua_train/api/lanes/swap_lanes_lane_id_swap_post.py
new file mode 100644
index 0000000000..5373481c33
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/api/lanes/swap_lanes_lane_id_swap_post.py
@@ -0,0 +1,193 @@
+from http import HTTPStatus
+from typing import Any
+from urllib.parse import quote
+
+import httpx
+
+from ... import errors
+from ...client import AuthenticatedClient, Client
+from ...models.lane_swap_response import LaneSwapResponse
+from ...types import Response
+
+
+def _get_kwargs(
+ pool: str,
+ lane_id: str,
+) -> dict[str, Any]:
+
+ _kwargs: dict[str, Any] = {
+ "method": "post",
+ "url": "/api/gateway/{pool}/lanes/{lane_id}/swap".format(
+ pool=quote(str(pool), safe=""),
+ lane_id=quote(str(lane_id), safe=""),
+ ),
+ }
+
+ return _kwargs
+
+
+def _parse_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> LaneSwapResponse | None:
+ if response.status_code == 200:
+ response_200 = LaneSwapResponse.from_dict(response.json())
+
+ return response_200
+
+ if client.raise_on_unexpected_status:
+ raise errors.UnexpectedStatus(response.status_code, response.content)
+ else:
+ return None
+
+
+def _build_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> Response[LaneSwapResponse]:
+ return Response(
+ status_code=HTTPStatus(response.status_code),
+ content=response.content,
+ headers=response.headers,
+ parsed=_parse_response(client=client, response=response),
+ )
+
+
+def sync_detailed(
+ pool: str,
+ lane_id: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> Response[LaneSwapResponse]:
+ """Swap
+
+ New-first claim rotation for ``lane_id``.
+
+ Calls into the pure protocol body in osgym/lane_swap.py with a
+ K8s-backed SwapDeps. The lane keeps its bound VM if the swap
+ bind times out (SwapAtomicity); the new vm_id is returned on
+ success.
+
+ Args:
+ pool (str):
+ lane_id (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[LaneSwapResponse]
+ """
+
+ kwargs = _get_kwargs(
+ pool=pool,
+ lane_id=lane_id,
+ )
+
+ response = client.get_httpx_client().request(
+ **kwargs,
+ )
+
+ return _build_response(client=client, response=response)
+
+
+def sync(
+ pool: str,
+ lane_id: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> LaneSwapResponse | None:
+ """Swap
+
+ New-first claim rotation for ``lane_id``.
+
+ Calls into the pure protocol body in osgym/lane_swap.py with a
+ K8s-backed SwapDeps. The lane keeps its bound VM if the swap
+ bind times out (SwapAtomicity); the new vm_id is returned on
+ success.
+
+ Args:
+ pool (str):
+ lane_id (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ LaneSwapResponse
+ """
+
+ return sync_detailed(
+ pool=pool,
+ lane_id=lane_id,
+ client=client,
+ ).parsed
+
+
+async def asyncio_detailed(
+ pool: str,
+ lane_id: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> Response[LaneSwapResponse]:
+ """Swap
+
+ New-first claim rotation for ``lane_id``.
+
+ Calls into the pure protocol body in osgym/lane_swap.py with a
+ K8s-backed SwapDeps. The lane keeps its bound VM if the swap
+ bind times out (SwapAtomicity); the new vm_id is returned on
+ success.
+
+ Args:
+ pool (str):
+ lane_id (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[LaneSwapResponse]
+ """
+
+ kwargs = _get_kwargs(
+ pool=pool,
+ lane_id=lane_id,
+ )
+
+ response = await client.get_async_httpx_client().request(**kwargs)
+
+ return _build_response(client=client, response=response)
+
+
+async def asyncio(
+ pool: str,
+ lane_id: str,
+ *,
+ client: AuthenticatedClient | Client,
+) -> LaneSwapResponse | None:
+ """Swap
+
+ New-first claim rotation for ``lane_id``.
+
+ Calls into the pure protocol body in osgym/lane_swap.py with a
+ K8s-backed SwapDeps. The lane keeps its bound VM if the swap
+ bind times out (SwapAtomicity); the new vm_id is returned on
+ success.
+
+ Args:
+ pool (str):
+ lane_id (str):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ LaneSwapResponse
+ """
+
+ return (
+ await asyncio_detailed(
+ pool=pool,
+ lane_id=lane_id,
+ client=client,
+ )
+ ).parsed
diff --git a/libs/fleet/python-sdk/cua_train/client.py b/libs/fleet/python-sdk/cua_train/client.py
new file mode 100644
index 0000000000..1b7055ab87
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/client.py
@@ -0,0 +1,268 @@
+import ssl
+from typing import Any
+
+import httpx
+from attrs import define, evolve, field
+
+
+@define
+class Client:
+ """A class for keeping track of data related to the API
+
+ The following are accepted as keyword arguments and will be used to construct httpx Clients internally:
+
+ ``base_url``: The base URL for the API, all requests are made to a relative path to this URL
+
+ ``cookies``: A dictionary of cookies to be sent with every request
+
+ ``headers``: A dictionary of headers to be sent with every request
+
+ ``timeout``: The maximum amount of a time a request can take. API functions will raise
+ httpx.TimeoutException if this is exceeded.
+
+ ``verify_ssl``: Whether or not to verify the SSL certificate of the API server. This should be True in production,
+ but can be set to False for testing purposes.
+
+ ``follow_redirects``: Whether or not to follow redirects. Default value is False.
+
+ ``httpx_args``: A dictionary of additional arguments to be passed to the ``httpx.Client`` and ``httpx.AsyncClient`` constructor.
+
+
+ Attributes:
+ raise_on_unexpected_status: Whether or not to raise an errors.UnexpectedStatus if the API returns a
+ status code that was not documented in the source OpenAPI document. Can also be provided as a keyword
+ argument to the constructor.
+ """
+
+ raise_on_unexpected_status: bool = field(default=False, kw_only=True)
+ _base_url: str = field(alias="base_url")
+ _cookies: dict[str, str] = field(factory=dict, kw_only=True, alias="cookies")
+ _headers: dict[str, str] = field(factory=dict, kw_only=True, alias="headers")
+ _timeout: httpx.Timeout | None = field(default=None, kw_only=True, alias="timeout")
+ _verify_ssl: str | bool | ssl.SSLContext = field(default=True, kw_only=True, alias="verify_ssl")
+ _follow_redirects: bool = field(default=False, kw_only=True, alias="follow_redirects")
+ _httpx_args: dict[str, Any] = field(factory=dict, kw_only=True, alias="httpx_args")
+ _client: httpx.Client | None = field(default=None, init=False)
+ _async_client: httpx.AsyncClient | None = field(default=None, init=False)
+
+ def with_headers(self, headers: dict[str, str]) -> "Client":
+ """Get a new client matching this one with additional headers"""
+ if self._client is not None:
+ self._client.headers.update(headers)
+ if self._async_client is not None:
+ self._async_client.headers.update(headers)
+ return evolve(self, headers={**self._headers, **headers})
+
+ def with_cookies(self, cookies: dict[str, str]) -> "Client":
+ """Get a new client matching this one with additional cookies"""
+ if self._client is not None:
+ self._client.cookies.update(cookies)
+ if self._async_client is not None:
+ self._async_client.cookies.update(cookies)
+ return evolve(self, cookies={**self._cookies, **cookies})
+
+ def with_timeout(self, timeout: httpx.Timeout) -> "Client":
+ """Get a new client matching this one with a new timeout configuration"""
+ if self._client is not None:
+ self._client.timeout = timeout
+ if self._async_client is not None:
+ self._async_client.timeout = timeout
+ return evolve(self, timeout=timeout)
+
+ def set_httpx_client(self, client: httpx.Client) -> "Client":
+ """Manually set the underlying httpx.Client
+
+ **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.
+ """
+ self._client = client
+ return self
+
+ def get_httpx_client(self) -> httpx.Client:
+ """Get the underlying httpx.Client, constructing a new one if not previously set"""
+ if self._client is None:
+ self._client = httpx.Client(
+ base_url=self._base_url,
+ cookies=self._cookies,
+ headers=self._headers,
+ timeout=self._timeout,
+ verify=self._verify_ssl,
+ follow_redirects=self._follow_redirects,
+ **self._httpx_args,
+ )
+ return self._client
+
+ def __enter__(self) -> "Client":
+ """Enter a context manager for self.client—you cannot enter twice (see httpx docs)"""
+ self.get_httpx_client().__enter__()
+ return self
+
+ def __exit__(self, *args: Any, **kwargs: Any) -> None:
+ """Exit a context manager for internal httpx.Client (see httpx docs)"""
+ self.get_httpx_client().__exit__(*args, **kwargs)
+
+ def set_async_httpx_client(self, async_client: httpx.AsyncClient) -> "Client":
+ """Manually set the underlying httpx.AsyncClient
+
+ **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.
+ """
+ self._async_client = async_client
+ return self
+
+ def get_async_httpx_client(self) -> httpx.AsyncClient:
+ """Get the underlying httpx.AsyncClient, constructing a new one if not previously set"""
+ if self._async_client is None:
+ self._async_client = httpx.AsyncClient(
+ base_url=self._base_url,
+ cookies=self._cookies,
+ headers=self._headers,
+ timeout=self._timeout,
+ verify=self._verify_ssl,
+ follow_redirects=self._follow_redirects,
+ **self._httpx_args,
+ )
+ return self._async_client
+
+ async def __aenter__(self) -> "Client":
+ """Enter a context manager for underlying httpx.AsyncClient—you cannot enter twice (see httpx docs)"""
+ await self.get_async_httpx_client().__aenter__()
+ return self
+
+ async def __aexit__(self, *args: Any, **kwargs: Any) -> None:
+ """Exit a context manager for underlying httpx.AsyncClient (see httpx docs)"""
+ await self.get_async_httpx_client().__aexit__(*args, **kwargs)
+
+
+@define
+class AuthenticatedClient:
+ """A Client which has been authenticated for use on secured endpoints
+
+ The following are accepted as keyword arguments and will be used to construct httpx Clients internally:
+
+ ``base_url``: The base URL for the API, all requests are made to a relative path to this URL
+
+ ``cookies``: A dictionary of cookies to be sent with every request
+
+ ``headers``: A dictionary of headers to be sent with every request
+
+ ``timeout``: The maximum amount of a time a request can take. API functions will raise
+ httpx.TimeoutException if this is exceeded.
+
+ ``verify_ssl``: Whether or not to verify the SSL certificate of the API server. This should be True in production,
+ but can be set to False for testing purposes.
+
+ ``follow_redirects``: Whether or not to follow redirects. Default value is False.
+
+ ``httpx_args``: A dictionary of additional arguments to be passed to the ``httpx.Client`` and ``httpx.AsyncClient`` constructor.
+
+
+ Attributes:
+ raise_on_unexpected_status: Whether or not to raise an errors.UnexpectedStatus if the API returns a
+ status code that was not documented in the source OpenAPI document. Can also be provided as a keyword
+ argument to the constructor.
+ token: The token to use for authentication
+ prefix: The prefix to use for the Authorization header
+ auth_header_name: The name of the Authorization header
+ """
+
+ raise_on_unexpected_status: bool = field(default=False, kw_only=True)
+ _base_url: str = field(alias="base_url")
+ _cookies: dict[str, str] = field(factory=dict, kw_only=True, alias="cookies")
+ _headers: dict[str, str] = field(factory=dict, kw_only=True, alias="headers")
+ _timeout: httpx.Timeout | None = field(default=None, kw_only=True, alias="timeout")
+ _verify_ssl: str | bool | ssl.SSLContext = field(default=True, kw_only=True, alias="verify_ssl")
+ _follow_redirects: bool = field(default=False, kw_only=True, alias="follow_redirects")
+ _httpx_args: dict[str, Any] = field(factory=dict, kw_only=True, alias="httpx_args")
+ _client: httpx.Client | None = field(default=None, init=False)
+ _async_client: httpx.AsyncClient | None = field(default=None, init=False)
+
+ token: str
+ prefix: str = "Bearer"
+ auth_header_name: str = "Authorization"
+
+ def with_headers(self, headers: dict[str, str]) -> "AuthenticatedClient":
+ """Get a new client matching this one with additional headers"""
+ if self._client is not None:
+ self._client.headers.update(headers)
+ if self._async_client is not None:
+ self._async_client.headers.update(headers)
+ return evolve(self, headers={**self._headers, **headers})
+
+ def with_cookies(self, cookies: dict[str, str]) -> "AuthenticatedClient":
+ """Get a new client matching this one with additional cookies"""
+ if self._client is not None:
+ self._client.cookies.update(cookies)
+ if self._async_client is not None:
+ self._async_client.cookies.update(cookies)
+ return evolve(self, cookies={**self._cookies, **cookies})
+
+ def with_timeout(self, timeout: httpx.Timeout) -> "AuthenticatedClient":
+ """Get a new client matching this one with a new timeout configuration"""
+ if self._client is not None:
+ self._client.timeout = timeout
+ if self._async_client is not None:
+ self._async_client.timeout = timeout
+ return evolve(self, timeout=timeout)
+
+ def set_httpx_client(self, client: httpx.Client) -> "AuthenticatedClient":
+ """Manually set the underlying httpx.Client
+
+ **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.
+ """
+ self._client = client
+ return self
+
+ def get_httpx_client(self) -> httpx.Client:
+ """Get the underlying httpx.Client, constructing a new one if not previously set"""
+ if self._client is None:
+ self._headers[self.auth_header_name] = f"{self.prefix} {self.token}" if self.prefix else self.token
+ self._client = httpx.Client(
+ base_url=self._base_url,
+ cookies=self._cookies,
+ headers=self._headers,
+ timeout=self._timeout,
+ verify=self._verify_ssl,
+ follow_redirects=self._follow_redirects,
+ **self._httpx_args,
+ )
+ return self._client
+
+ def __enter__(self) -> "AuthenticatedClient":
+ """Enter a context manager for self.client—you cannot enter twice (see httpx docs)"""
+ self.get_httpx_client().__enter__()
+ return self
+
+ def __exit__(self, *args: Any, **kwargs: Any) -> None:
+ """Exit a context manager for internal httpx.Client (see httpx docs)"""
+ self.get_httpx_client().__exit__(*args, **kwargs)
+
+ def set_async_httpx_client(self, async_client: httpx.AsyncClient) -> "AuthenticatedClient":
+ """Manually set the underlying httpx.AsyncClient
+
+ **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.
+ """
+ self._async_client = async_client
+ return self
+
+ def get_async_httpx_client(self) -> httpx.AsyncClient:
+ """Get the underlying httpx.AsyncClient, constructing a new one if not previously set"""
+ if self._async_client is None:
+ self._headers[self.auth_header_name] = f"{self.prefix} {self.token}" if self.prefix else self.token
+ self._async_client = httpx.AsyncClient(
+ base_url=self._base_url,
+ cookies=self._cookies,
+ headers=self._headers,
+ timeout=self._timeout,
+ verify=self._verify_ssl,
+ follow_redirects=self._follow_redirects,
+ **self._httpx_args,
+ )
+ return self._async_client
+
+ async def __aenter__(self) -> "AuthenticatedClient":
+ """Enter a context manager for underlying httpx.AsyncClient—you cannot enter twice (see httpx docs)"""
+ await self.get_async_httpx_client().__aenter__()
+ return self
+
+ async def __aexit__(self, *args: Any, **kwargs: Any) -> None:
+ """Exit a context manager for underlying httpx.AsyncClient (see httpx docs)"""
+ await self.get_async_httpx_client().__aexit__(*args, **kwargs)
diff --git a/libs/fleet/python-sdk/cua_train/errors.py b/libs/fleet/python-sdk/cua_train/errors.py
new file mode 100644
index 0000000000..5f92e76aca
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/errors.py
@@ -0,0 +1,16 @@
+"""Contains shared errors types that can be raised from API functions"""
+
+
+class UnexpectedStatus(Exception):
+ """Raised by api functions when the response status an undocumented status and Client.raise_on_unexpected_status is True"""
+
+ def __init__(self, status_code: int, content: bytes):
+ self.status_code = status_code
+ self.content = content
+
+ super().__init__(
+ f"Unexpected status code: {status_code}\n\nResponse content:\n{content.decode(errors='ignore')}"
+ )
+
+
+__all__ = ["UnexpectedStatus"]
diff --git a/libs/fleet/python-sdk/cua_train/models/__init__.py b/libs/fleet/python-sdk/cua_train/models/__init__.py
new file mode 100644
index 0000000000..39cb3e01a1
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/__init__.py
@@ -0,0 +1,93 @@
+"""Contains all the data models used in inputs/outputs"""
+
+from .acquire_lanes_request import AcquireLanesRequest
+from .acquire_lanes_response import AcquireLanesResponse
+from .action import Action
+from .action_parameters import ActionParameters
+from .batch_in_progress_response import BatchInProgressResponse
+from .batch_progress import BatchProgress
+from .batch_results_response import BatchResultsResponse
+from .batch_status_response import BatchStatusResponse
+from .batch_submit_request import BatchSubmitRequest
+from .batch_submit_response import BatchSubmitResponse
+from .batch_summary import BatchSummary
+from .cancel_batch_response import CancelBatchResponse
+from .cancel_label_batch_item import CancelLabelBatchItem
+from .cancel_label_response import CancelLabelResponse
+from .create_key_request import CreateKeyRequest
+from .create_key_response import CreateKeyResponse
+from .error_response import ErrorResponse
+from .health_response import HealthResponse
+from .healthz_response import HealthzResponse
+from .key_client import KeyClient
+from .label_batch_summary import LabelBatchSummary
+from .label_in_progress_response import LabelInProgressResponse
+from .label_results_response import LabelResultsResponse
+from .label_status_response import LabelStatusResponse
+from .lane_create_request import LaneCreateRequest
+from .lane_delete_response import LaneDeleteResponse
+from .lane_response import LaneResponse
+from .lane_swap_response import LaneSwapResponse
+from .list_keys_response import ListKeysResponse
+from .pool_list_response import PoolListResponse
+from .pool_list_response_vms_item import PoolListResponseVmsItem
+from .release_lanes_request import ReleaseLanesRequest
+from .release_lanes_response import ReleaseLanesResponse
+from .reset_request import ResetRequest
+from .reset_request_task_config import ResetRequestTaskConfig
+from .reset_response import ResetResponse
+from .run_config import RunConfig
+from .run_result import RunResult
+from .screenshot_response import ScreenshotResponse
+from .shutdown_request import ShutdownRequest
+from .shutdown_response import ShutdownResponse
+from .step_request import StepRequest
+from .step_response import StepResponse
+from .timing_stats import TimingStats
+
+__all__ = (
+ "AcquireLanesRequest",
+ "AcquireLanesResponse",
+ "Action",
+ "ActionParameters",
+ "BatchInProgressResponse",
+ "BatchProgress",
+ "BatchResultsResponse",
+ "BatchStatusResponse",
+ "BatchSubmitRequest",
+ "BatchSubmitResponse",
+ "BatchSummary",
+ "CancelBatchResponse",
+ "CancelLabelBatchItem",
+ "CancelLabelResponse",
+ "CreateKeyRequest",
+ "CreateKeyResponse",
+ "ErrorResponse",
+ "HealthResponse",
+ "HealthzResponse",
+ "KeyClient",
+ "LabelBatchSummary",
+ "LabelInProgressResponse",
+ "LabelResultsResponse",
+ "LabelStatusResponse",
+ "LaneCreateRequest",
+ "LaneDeleteResponse",
+ "LaneResponse",
+ "LaneSwapResponse",
+ "ListKeysResponse",
+ "PoolListResponse",
+ "PoolListResponseVmsItem",
+ "ReleaseLanesRequest",
+ "ReleaseLanesResponse",
+ "ResetRequest",
+ "ResetRequestTaskConfig",
+ "ResetResponse",
+ "RunConfig",
+ "RunResult",
+ "ScreenshotResponse",
+ "ShutdownRequest",
+ "ShutdownResponse",
+ "StepRequest",
+ "StepResponse",
+ "TimingStats",
+)
diff --git a/libs/fleet/python-sdk/cua_train/models/acquire_lanes_request.py b/libs/fleet/python-sdk/cua_train/models/acquire_lanes_request.py
new file mode 100644
index 0000000000..0c4d559eef
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/acquire_lanes_request.py
@@ -0,0 +1,61 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+T = TypeVar("T", bound="AcquireLanesRequest")
+
+
+@_attrs_define
+class AcquireLanesRequest:
+ """
+ Attributes:
+ n (int): Number of warm VM lanes to acquire.
+ """
+
+ n: int
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ n = self.n
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update(
+ {
+ "n": n,
+ }
+ )
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ n = d.pop("n")
+
+ acquire_lanes_request = cls(
+ n=n,
+ )
+
+ acquire_lanes_request.additional_properties = d
+ return acquire_lanes_request
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/acquire_lanes_response.py b/libs/fleet/python-sdk/cua_train/models/acquire_lanes_response.py
new file mode 100644
index 0000000000..94a07a9934
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/acquire_lanes_response.py
@@ -0,0 +1,63 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, TypeVar, cast
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+T = TypeVar("T", bound="AcquireLanesResponse")
+
+
+@_attrs_define
+class AcquireLanesResponse:
+ """
+ Attributes:
+ vm_ids (list[str] | Unset): One warm VM id per acquired lane. Use as RunConfig.vm_id.
+ """
+
+ vm_ids: list[str] | Unset = UNSET
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ vm_ids: list[str] | Unset = UNSET
+ if not isinstance(self.vm_ids, Unset):
+ vm_ids = self.vm_ids
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update({})
+ if vm_ids is not UNSET:
+ field_dict["vm_ids"] = vm_ids
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ vm_ids = cast(list[str], d.pop("vm_ids", UNSET))
+
+ acquire_lanes_response = cls(
+ vm_ids=vm_ids,
+ )
+
+ acquire_lanes_response.additional_properties = d
+ return acquire_lanes_response
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/action.py b/libs/fleet/python-sdk/cua_train/models/action.py
new file mode 100644
index 0000000000..885240e29c
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/action.py
@@ -0,0 +1,85 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import TYPE_CHECKING, Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+if TYPE_CHECKING:
+ from ..models.action_parameters import ActionParameters
+
+
+T = TypeVar("T", bound="Action")
+
+
+@_attrs_define
+class Action:
+ """
+ Attributes:
+ action_type (str): OSGym action type (e.g. CLICK, TYPE, KEY). Example: CLICK.
+ parameters (ActionParameters | Unset): Action-type-specific parameters (e.g. `{x, y, button}` for CLICK).
+ """
+
+ action_type: str
+ parameters: ActionParameters | Unset = UNSET
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ action_type = self.action_type
+
+ parameters: dict[str, Any] | Unset = UNSET
+ if not isinstance(self.parameters, Unset):
+ parameters = self.parameters.to_dict()
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update(
+ {
+ "action_type": action_type,
+ }
+ )
+ if parameters is not UNSET:
+ field_dict["parameters"] = parameters
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ from ..models.action_parameters import ActionParameters
+
+ d = dict(src_dict)
+ action_type = d.pop("action_type")
+
+ _parameters = d.pop("parameters", UNSET)
+ parameters: ActionParameters | Unset
+ if isinstance(_parameters, Unset):
+ parameters = UNSET
+ else:
+ parameters = ActionParameters.from_dict(_parameters)
+
+ action = cls(
+ action_type=action_type,
+ parameters=parameters,
+ )
+
+ action.additional_properties = d
+ return action
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/action_parameters.py b/libs/fleet/python-sdk/cua_train/models/action_parameters.py
new file mode 100644
index 0000000000..be814ccb07
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/action_parameters.py
@@ -0,0 +1,47 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+T = TypeVar("T", bound="ActionParameters")
+
+
+@_attrs_define
+class ActionParameters:
+ """Action-type-specific parameters (e.g. `{x, y, button}` for CLICK)."""
+
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ action_parameters = cls()
+
+ action_parameters.additional_properties = d
+ return action_parameters
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/batch_in_progress_response.py b/libs/fleet/python-sdk/cua_train/models/batch_in_progress_response.py
new file mode 100644
index 0000000000..e5fe35fb10
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/batch_in_progress_response.py
@@ -0,0 +1,79 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+T = TypeVar("T", bound="BatchInProgressResponse")
+
+
+@_attrs_define
+class BatchInProgressResponse:
+ """
+ Attributes:
+ batch_id (str | Unset):
+ status (str | Unset):
+ message (str | Unset):
+ """
+
+ batch_id: str | Unset = UNSET
+ status: str | Unset = UNSET
+ message: str | Unset = UNSET
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ batch_id = self.batch_id
+
+ status = self.status
+
+ message = self.message
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update({})
+ if batch_id is not UNSET:
+ field_dict["batch_id"] = batch_id
+ if status is not UNSET:
+ field_dict["status"] = status
+ if message is not UNSET:
+ field_dict["message"] = message
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ batch_id = d.pop("batch_id", UNSET)
+
+ status = d.pop("status", UNSET)
+
+ message = d.pop("message", UNSET)
+
+ batch_in_progress_response = cls(
+ batch_id=batch_id,
+ status=status,
+ message=message,
+ )
+
+ batch_in_progress_response.additional_properties = d
+ return batch_in_progress_response
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/batch_progress.py b/libs/fleet/python-sdk/cua_train/models/batch_progress.py
new file mode 100644
index 0000000000..c5e3f97322
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/batch_progress.py
@@ -0,0 +1,88 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+T = TypeVar("T", bound="BatchProgress")
+
+
+@_attrs_define
+class BatchProgress:
+ """
+ Attributes:
+ completed (int | Unset):
+ total (int | Unset):
+ ok (int | Unset):
+ failed (int | Unset):
+ """
+
+ completed: int | Unset = UNSET
+ total: int | Unset = UNSET
+ ok: int | Unset = UNSET
+ failed: int | Unset = UNSET
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ completed = self.completed
+
+ total = self.total
+
+ ok = self.ok
+
+ failed = self.failed
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update({})
+ if completed is not UNSET:
+ field_dict["completed"] = completed
+ if total is not UNSET:
+ field_dict["total"] = total
+ if ok is not UNSET:
+ field_dict["ok"] = ok
+ if failed is not UNSET:
+ field_dict["failed"] = failed
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ completed = d.pop("completed", UNSET)
+
+ total = d.pop("total", UNSET)
+
+ ok = d.pop("ok", UNSET)
+
+ failed = d.pop("failed", UNSET)
+
+ batch_progress = cls(
+ completed=completed,
+ total=total,
+ ok=ok,
+ failed=failed,
+ )
+
+ batch_progress.additional_properties = d
+ return batch_progress
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/batch_results_response.py b/libs/fleet/python-sdk/cua_train/models/batch_results_response.py
new file mode 100644
index 0000000000..1d9590fbc6
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/batch_results_response.py
@@ -0,0 +1,151 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import TYPE_CHECKING, Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+if TYPE_CHECKING:
+ from ..models.batch_summary import BatchSummary
+ from ..models.run_result import RunResult
+
+
+T = TypeVar("T", bound="BatchResultsResponse")
+
+
+@_attrs_define
+class BatchResultsResponse:
+ """
+ Attributes:
+ batch_id (str | Unset):
+ name (str | Unset):
+ status (str | Unset):
+ runs (list[RunResult] | Unset):
+ s3_bucket (str | Unset):
+ s3_key (str | Unset):
+ s3_presigned_url (str | Unset):
+ summary (BatchSummary | Unset):
+ """
+
+ batch_id: str | Unset = UNSET
+ name: str | Unset = UNSET
+ status: str | Unset = UNSET
+ runs: list[RunResult] | Unset = UNSET
+ s3_bucket: str | Unset = UNSET
+ s3_key: str | Unset = UNSET
+ s3_presigned_url: str | Unset = UNSET
+ summary: BatchSummary | Unset = UNSET
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ batch_id = self.batch_id
+
+ name = self.name
+
+ status = self.status
+
+ runs: list[dict[str, Any]] | Unset = UNSET
+ if not isinstance(self.runs, Unset):
+ runs = []
+ for runs_item_data in self.runs:
+ runs_item = runs_item_data.to_dict()
+ runs.append(runs_item)
+
+ s3_bucket = self.s3_bucket
+
+ s3_key = self.s3_key
+
+ s3_presigned_url = self.s3_presigned_url
+
+ summary: dict[str, Any] | Unset = UNSET
+ if not isinstance(self.summary, Unset):
+ summary = self.summary.to_dict()
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update({})
+ if batch_id is not UNSET:
+ field_dict["batch_id"] = batch_id
+ if name is not UNSET:
+ field_dict["name"] = name
+ if status is not UNSET:
+ field_dict["status"] = status
+ if runs is not UNSET:
+ field_dict["runs"] = runs
+ if s3_bucket is not UNSET:
+ field_dict["s3_bucket"] = s3_bucket
+ if s3_key is not UNSET:
+ field_dict["s3_key"] = s3_key
+ if s3_presigned_url is not UNSET:
+ field_dict["s3_presigned_url"] = s3_presigned_url
+ if summary is not UNSET:
+ field_dict["summary"] = summary
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ from ..models.batch_summary import BatchSummary
+ from ..models.run_result import RunResult
+
+ d = dict(src_dict)
+ batch_id = d.pop("batch_id", UNSET)
+
+ name = d.pop("name", UNSET)
+
+ status = d.pop("status", UNSET)
+
+ _runs = d.pop("runs", UNSET)
+ runs: list[RunResult] | Unset = UNSET
+ if _runs is not UNSET:
+ runs = []
+ for runs_item_data in _runs:
+ runs_item = RunResult.from_dict(runs_item_data)
+
+ runs.append(runs_item)
+
+ s3_bucket = d.pop("s3_bucket", UNSET)
+
+ s3_key = d.pop("s3_key", UNSET)
+
+ s3_presigned_url = d.pop("s3_presigned_url", UNSET)
+
+ _summary = d.pop("summary", UNSET)
+ summary: BatchSummary | Unset
+ if isinstance(_summary, Unset):
+ summary = UNSET
+ else:
+ summary = BatchSummary.from_dict(_summary)
+
+ batch_results_response = cls(
+ batch_id=batch_id,
+ name=name,
+ status=status,
+ runs=runs,
+ s3_bucket=s3_bucket,
+ s3_key=s3_key,
+ s3_presigned_url=s3_presigned_url,
+ summary=summary,
+ )
+
+ batch_results_response.additional_properties = d
+ return batch_results_response
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/batch_status_response.py b/libs/fleet/python-sdk/cua_train/models/batch_status_response.py
new file mode 100644
index 0000000000..8287aea218
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/batch_status_response.py
@@ -0,0 +1,134 @@
+from __future__ import annotations
+
+import datetime
+from collections.abc import Mapping
+from typing import TYPE_CHECKING, Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+if TYPE_CHECKING:
+ from ..models.batch_progress import BatchProgress
+
+
+T = TypeVar("T", bound="BatchStatusResponse")
+
+
+@_attrs_define
+class BatchStatusResponse:
+ """
+ Attributes:
+ batch_id (str | Unset):
+ name (str | Unset):
+ status (str | Unset):
+ progress (BatchProgress | Unset):
+ created_at (datetime.datetime | Unset):
+ updated_at (datetime.datetime | Unset):
+ """
+
+ batch_id: str | Unset = UNSET
+ name: str | Unset = UNSET
+ status: str | Unset = UNSET
+ progress: BatchProgress | Unset = UNSET
+ created_at: datetime.datetime | Unset = UNSET
+ updated_at: datetime.datetime | Unset = UNSET
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ batch_id = self.batch_id
+
+ name = self.name
+
+ status = self.status
+
+ progress: dict[str, Any] | Unset = UNSET
+ if not isinstance(self.progress, Unset):
+ progress = self.progress.to_dict()
+
+ created_at: str | Unset = UNSET
+ if not isinstance(self.created_at, Unset):
+ created_at = self.created_at.isoformat()
+
+ updated_at: str | Unset = UNSET
+ if not isinstance(self.updated_at, Unset):
+ updated_at = self.updated_at.isoformat()
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update({})
+ if batch_id is not UNSET:
+ field_dict["batch_id"] = batch_id
+ if name is not UNSET:
+ field_dict["name"] = name
+ if status is not UNSET:
+ field_dict["status"] = status
+ if progress is not UNSET:
+ field_dict["progress"] = progress
+ if created_at is not UNSET:
+ field_dict["created_at"] = created_at
+ if updated_at is not UNSET:
+ field_dict["updated_at"] = updated_at
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ from ..models.batch_progress import BatchProgress
+
+ d = dict(src_dict)
+ batch_id = d.pop("batch_id", UNSET)
+
+ name = d.pop("name", UNSET)
+
+ status = d.pop("status", UNSET)
+
+ _progress = d.pop("progress", UNSET)
+ progress: BatchProgress | Unset
+ if isinstance(_progress, Unset):
+ progress = UNSET
+ else:
+ progress = BatchProgress.from_dict(_progress)
+
+ _created_at = d.pop("created_at", UNSET)
+ created_at: datetime.datetime | Unset
+ if isinstance(_created_at, Unset):
+ created_at = UNSET
+ else:
+ created_at = datetime.datetime.fromisoformat(_created_at)
+
+ _updated_at = d.pop("updated_at", UNSET)
+ updated_at: datetime.datetime | Unset
+ if isinstance(_updated_at, Unset):
+ updated_at = UNSET
+ else:
+ updated_at = datetime.datetime.fromisoformat(_updated_at)
+
+ batch_status_response = cls(
+ batch_id=batch_id,
+ name=name,
+ status=status,
+ progress=progress,
+ created_at=created_at,
+ updated_at=updated_at,
+ )
+
+ batch_status_response.additional_properties = d
+ return batch_status_response
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/batch_submit_request.py b/libs/fleet/python-sdk/cua_train/models/batch_submit_request.py
new file mode 100644
index 0000000000..37b2956ce1
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/batch_submit_request.py
@@ -0,0 +1,115 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import TYPE_CHECKING, Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+if TYPE_CHECKING:
+ from ..models.run_config import RunConfig
+
+
+T = TypeVar("T", bound="BatchSubmitRequest")
+
+
+@_attrs_define
+class BatchSubmitRequest:
+ """
+ Attributes:
+ runs (list[RunConfig]):
+ concurrency (int | Unset): Default: 10.
+ pool_name (str | Unset): Optional — must match the URL `{pool}` if provided; ignored otherwise.
+ name (str | Unset): Optional batch name. Overridden by the URL `{label}` on label routes.
+ keep_warm (bool | Unset): Leave each run's VM running when the run ends (instead of shutting it down), so a
+ follow-up batch can reattach to it via RunConfig.vm_id (read each lane's surviving id from RunResult.vm_id).
+ Best-effort: a warm VM is reaped after its claim TTL (~minutes), after which reattach falls back to a fresh VM.
+ """
+
+ runs: list[RunConfig]
+ concurrency: int | Unset = 10
+ pool_name: str | Unset = UNSET
+ name: str | Unset = UNSET
+ keep_warm: bool | Unset = UNSET
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ runs = []
+ for runs_item_data in self.runs:
+ runs_item = runs_item_data.to_dict()
+ runs.append(runs_item)
+
+ concurrency = self.concurrency
+
+ pool_name = self.pool_name
+
+ name = self.name
+
+ keep_warm = self.keep_warm
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update(
+ {
+ "runs": runs,
+ }
+ )
+ if concurrency is not UNSET:
+ field_dict["concurrency"] = concurrency
+ if pool_name is not UNSET:
+ field_dict["pool_name"] = pool_name
+ if name is not UNSET:
+ field_dict["name"] = name
+ if keep_warm is not UNSET:
+ field_dict["keep_warm"] = keep_warm
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ from ..models.run_config import RunConfig
+
+ d = dict(src_dict)
+ runs = []
+ _runs = d.pop("runs")
+ for runs_item_data in _runs:
+ runs_item = RunConfig.from_dict(runs_item_data)
+
+ runs.append(runs_item)
+
+ concurrency = d.pop("concurrency", UNSET)
+
+ pool_name = d.pop("pool_name", UNSET)
+
+ name = d.pop("name", UNSET)
+
+ keep_warm = d.pop("keep_warm", UNSET)
+
+ batch_submit_request = cls(
+ runs=runs,
+ concurrency=concurrency,
+ pool_name=pool_name,
+ name=name,
+ keep_warm=keep_warm,
+ )
+
+ batch_submit_request.additional_properties = d
+ return batch_submit_request
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/batch_submit_response.py b/libs/fleet/python-sdk/cua_train/models/batch_submit_response.py
new file mode 100644
index 0000000000..679370ff0e
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/batch_submit_response.py
@@ -0,0 +1,96 @@
+from __future__ import annotations
+
+import datetime
+from collections.abc import Mapping
+from typing import Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+T = TypeVar("T", bound="BatchSubmitResponse")
+
+
+@_attrs_define
+class BatchSubmitResponse:
+ """
+ Attributes:
+ batch_id (str | Unset):
+ name (str | Unset):
+ status (str | Unset):
+ created_at (datetime.datetime | Unset):
+ """
+
+ batch_id: str | Unset = UNSET
+ name: str | Unset = UNSET
+ status: str | Unset = UNSET
+ created_at: datetime.datetime | Unset = UNSET
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ batch_id = self.batch_id
+
+ name = self.name
+
+ status = self.status
+
+ created_at: str | Unset = UNSET
+ if not isinstance(self.created_at, Unset):
+ created_at = self.created_at.isoformat()
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update({})
+ if batch_id is not UNSET:
+ field_dict["batch_id"] = batch_id
+ if name is not UNSET:
+ field_dict["name"] = name
+ if status is not UNSET:
+ field_dict["status"] = status
+ if created_at is not UNSET:
+ field_dict["created_at"] = created_at
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ batch_id = d.pop("batch_id", UNSET)
+
+ name = d.pop("name", UNSET)
+
+ status = d.pop("status", UNSET)
+
+ _created_at = d.pop("created_at", UNSET)
+ created_at: datetime.datetime | Unset
+ if isinstance(_created_at, Unset):
+ created_at = UNSET
+ else:
+ created_at = datetime.datetime.fromisoformat(_created_at)
+
+ batch_submit_response = cls(
+ batch_id=batch_id,
+ name=name,
+ status=status,
+ created_at=created_at,
+ )
+
+ batch_submit_response.additional_properties = d
+ return batch_submit_response
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/batch_summary.py b/libs/fleet/python-sdk/cua_train/models/batch_summary.py
new file mode 100644
index 0000000000..a4113f6db9
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/batch_summary.py
@@ -0,0 +1,133 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import TYPE_CHECKING, Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+if TYPE_CHECKING:
+ from ..models.timing_stats import TimingStats
+
+
+T = TypeVar("T", bound="BatchSummary")
+
+
+@_attrs_define
+class BatchSummary:
+ """
+ Attributes:
+ n_ok (int | Unset):
+ n_fail (int | Unset):
+ total_wall_ms (int | Unset):
+ reset_stats (TimingStats | Unset):
+ step_stats (TimingStats | Unset):
+ shutdown_stats (TimingStats | Unset):
+ """
+
+ n_ok: int | Unset = UNSET
+ n_fail: int | Unset = UNSET
+ total_wall_ms: int | Unset = UNSET
+ reset_stats: TimingStats | Unset = UNSET
+ step_stats: TimingStats | Unset = UNSET
+ shutdown_stats: TimingStats | Unset = UNSET
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ n_ok = self.n_ok
+
+ n_fail = self.n_fail
+
+ total_wall_ms = self.total_wall_ms
+
+ reset_stats: dict[str, Any] | Unset = UNSET
+ if not isinstance(self.reset_stats, Unset):
+ reset_stats = self.reset_stats.to_dict()
+
+ step_stats: dict[str, Any] | Unset = UNSET
+ if not isinstance(self.step_stats, Unset):
+ step_stats = self.step_stats.to_dict()
+
+ shutdown_stats: dict[str, Any] | Unset = UNSET
+ if not isinstance(self.shutdown_stats, Unset):
+ shutdown_stats = self.shutdown_stats.to_dict()
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update({})
+ if n_ok is not UNSET:
+ field_dict["n_ok"] = n_ok
+ if n_fail is not UNSET:
+ field_dict["n_fail"] = n_fail
+ if total_wall_ms is not UNSET:
+ field_dict["total_wall_ms"] = total_wall_ms
+ if reset_stats is not UNSET:
+ field_dict["reset_stats"] = reset_stats
+ if step_stats is not UNSET:
+ field_dict["step_stats"] = step_stats
+ if shutdown_stats is not UNSET:
+ field_dict["shutdown_stats"] = shutdown_stats
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ from ..models.timing_stats import TimingStats
+
+ d = dict(src_dict)
+ n_ok = d.pop("n_ok", UNSET)
+
+ n_fail = d.pop("n_fail", UNSET)
+
+ total_wall_ms = d.pop("total_wall_ms", UNSET)
+
+ _reset_stats = d.pop("reset_stats", UNSET)
+ reset_stats: TimingStats | Unset
+ if isinstance(_reset_stats, Unset):
+ reset_stats = UNSET
+ else:
+ reset_stats = TimingStats.from_dict(_reset_stats)
+
+ _step_stats = d.pop("step_stats", UNSET)
+ step_stats: TimingStats | Unset
+ if isinstance(_step_stats, Unset):
+ step_stats = UNSET
+ else:
+ step_stats = TimingStats.from_dict(_step_stats)
+
+ _shutdown_stats = d.pop("shutdown_stats", UNSET)
+ shutdown_stats: TimingStats | Unset
+ if isinstance(_shutdown_stats, Unset):
+ shutdown_stats = UNSET
+ else:
+ shutdown_stats = TimingStats.from_dict(_shutdown_stats)
+
+ batch_summary = cls(
+ n_ok=n_ok,
+ n_fail=n_fail,
+ total_wall_ms=total_wall_ms,
+ reset_stats=reset_stats,
+ step_stats=step_stats,
+ shutdown_stats=shutdown_stats,
+ )
+
+ batch_summary.additional_properties = d
+ return batch_summary
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/cancel_batch_response.py b/libs/fleet/python-sdk/cua_train/models/cancel_batch_response.py
new file mode 100644
index 0000000000..ace0ea24ae
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/cancel_batch_response.py
@@ -0,0 +1,70 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+T = TypeVar("T", bound="CancelBatchResponse")
+
+
+@_attrs_define
+class CancelBatchResponse:
+ """
+ Attributes:
+ batch_id (str | Unset):
+ status (str | Unset):
+ """
+
+ batch_id: str | Unset = UNSET
+ status: str | Unset = UNSET
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ batch_id = self.batch_id
+
+ status = self.status
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update({})
+ if batch_id is not UNSET:
+ field_dict["batch_id"] = batch_id
+ if status is not UNSET:
+ field_dict["status"] = status
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ batch_id = d.pop("batch_id", UNSET)
+
+ status = d.pop("status", UNSET)
+
+ cancel_batch_response = cls(
+ batch_id=batch_id,
+ status=status,
+ )
+
+ cancel_batch_response.additional_properties = d
+ return cancel_batch_response
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/cancel_label_batch_item.py b/libs/fleet/python-sdk/cua_train/models/cancel_label_batch_item.py
new file mode 100644
index 0000000000..0040b5eeb4
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/cancel_label_batch_item.py
@@ -0,0 +1,70 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+T = TypeVar("T", bound="CancelLabelBatchItem")
+
+
+@_attrs_define
+class CancelLabelBatchItem:
+ """
+ Attributes:
+ batch_id (str | Unset):
+ status (str | Unset):
+ """
+
+ batch_id: str | Unset = UNSET
+ status: str | Unset = UNSET
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ batch_id = self.batch_id
+
+ status = self.status
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update({})
+ if batch_id is not UNSET:
+ field_dict["batch_id"] = batch_id
+ if status is not UNSET:
+ field_dict["status"] = status
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ batch_id = d.pop("batch_id", UNSET)
+
+ status = d.pop("status", UNSET)
+
+ cancel_label_batch_item = cls(
+ batch_id=batch_id,
+ status=status,
+ )
+
+ cancel_label_batch_item.additional_properties = d
+ return cancel_label_batch_item
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/cancel_label_response.py b/libs/fleet/python-sdk/cua_train/models/cancel_label_response.py
new file mode 100644
index 0000000000..a135405c7c
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/cancel_label_response.py
@@ -0,0 +1,115 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import TYPE_CHECKING, Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+if TYPE_CHECKING:
+ from ..models.cancel_label_batch_item import CancelLabelBatchItem
+
+
+T = TypeVar("T", bound="CancelLabelResponse")
+
+
+@_attrs_define
+class CancelLabelResponse:
+ """
+ Attributes:
+ label (str | Unset):
+ batch_count (int | Unset):
+ cancelled_count (int | Unset):
+ already_done (int | Unset):
+ batches (list[CancelLabelBatchItem] | Unset):
+ """
+
+ label: str | Unset = UNSET
+ batch_count: int | Unset = UNSET
+ cancelled_count: int | Unset = UNSET
+ already_done: int | Unset = UNSET
+ batches: list[CancelLabelBatchItem] | Unset = UNSET
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ label = self.label
+
+ batch_count = self.batch_count
+
+ cancelled_count = self.cancelled_count
+
+ already_done = self.already_done
+
+ batches: list[dict[str, Any]] | Unset = UNSET
+ if not isinstance(self.batches, Unset):
+ batches = []
+ for batches_item_data in self.batches:
+ batches_item = batches_item_data.to_dict()
+ batches.append(batches_item)
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update({})
+ if label is not UNSET:
+ field_dict["label"] = label
+ if batch_count is not UNSET:
+ field_dict["batch_count"] = batch_count
+ if cancelled_count is not UNSET:
+ field_dict["cancelled_count"] = cancelled_count
+ if already_done is not UNSET:
+ field_dict["already_done"] = already_done
+ if batches is not UNSET:
+ field_dict["batches"] = batches
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ from ..models.cancel_label_batch_item import CancelLabelBatchItem
+
+ d = dict(src_dict)
+ label = d.pop("label", UNSET)
+
+ batch_count = d.pop("batch_count", UNSET)
+
+ cancelled_count = d.pop("cancelled_count", UNSET)
+
+ already_done = d.pop("already_done", UNSET)
+
+ _batches = d.pop("batches", UNSET)
+ batches: list[CancelLabelBatchItem] | Unset = UNSET
+ if _batches is not UNSET:
+ batches = []
+ for batches_item_data in _batches:
+ batches_item = CancelLabelBatchItem.from_dict(batches_item_data)
+
+ batches.append(batches_item)
+
+ cancel_label_response = cls(
+ label=label,
+ batch_count=batch_count,
+ cancelled_count=cancelled_count,
+ already_done=already_done,
+ batches=batches,
+ )
+
+ cancel_label_response.additional_properties = d
+ return cancel_label_response
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/create_key_request.py b/libs/fleet/python-sdk/cua_train/models/create_key_request.py
new file mode 100644
index 0000000000..5a8a891095
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/create_key_request.py
@@ -0,0 +1,69 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+T = TypeVar("T", bound="CreateKeyRequest")
+
+
+@_attrs_define
+class CreateKeyRequest:
+ """
+ Attributes:
+ name (str): Example: ci-prod.
+ namespace (str): Example: test-pool.
+ """
+
+ name: str
+ namespace: str
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ name = self.name
+
+ namespace = self.namespace
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update(
+ {
+ "name": name,
+ "namespace": namespace,
+ }
+ )
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ name = d.pop("name")
+
+ namespace = d.pop("namespace")
+
+ create_key_request = cls(
+ name=name,
+ namespace=namespace,
+ )
+
+ create_key_request.additional_properties = d
+ return create_key_request
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/create_key_response.py b/libs/fleet/python-sdk/cua_train/models/create_key_response.py
new file mode 100644
index 0000000000..78b3a35ca9
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/create_key_response.py
@@ -0,0 +1,97 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+T = TypeVar("T", bound="CreateKeyResponse")
+
+
+@_attrs_define
+class CreateKeyResponse:
+ """
+ Attributes:
+ client_id (str | Unset):
+ client_secret (str | Unset):
+ name (str | Unset):
+ namespace (str | Unset):
+ token_url (str | Unset):
+ """
+
+ client_id: str | Unset = UNSET
+ client_secret: str | Unset = UNSET
+ name: str | Unset = UNSET
+ namespace: str | Unset = UNSET
+ token_url: str | Unset = UNSET
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ client_id = self.client_id
+
+ client_secret = self.client_secret
+
+ name = self.name
+
+ namespace = self.namespace
+
+ token_url = self.token_url
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update({})
+ if client_id is not UNSET:
+ field_dict["client_id"] = client_id
+ if client_secret is not UNSET:
+ field_dict["client_secret"] = client_secret
+ if name is not UNSET:
+ field_dict["name"] = name
+ if namespace is not UNSET:
+ field_dict["namespace"] = namespace
+ if token_url is not UNSET:
+ field_dict["token_url"] = token_url
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ client_id = d.pop("client_id", UNSET)
+
+ client_secret = d.pop("client_secret", UNSET)
+
+ name = d.pop("name", UNSET)
+
+ namespace = d.pop("namespace", UNSET)
+
+ token_url = d.pop("token_url", UNSET)
+
+ create_key_response = cls(
+ client_id=client_id,
+ client_secret=client_secret,
+ name=name,
+ namespace=namespace,
+ token_url=token_url,
+ )
+
+ create_key_response.additional_properties = d
+ return create_key_response
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/error_response.py b/libs/fleet/python-sdk/cua_train/models/error_response.py
new file mode 100644
index 0000000000..3cd602cb1e
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/error_response.py
@@ -0,0 +1,61 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+T = TypeVar("T", bound="ErrorResponse")
+
+
+@_attrs_define
+class ErrorResponse:
+ """
+ Attributes:
+ error (str | Unset):
+ """
+
+ error: str | Unset = UNSET
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ error = self.error
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update({})
+ if error is not UNSET:
+ field_dict["error"] = error
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ error = d.pop("error", UNSET)
+
+ error_response = cls(
+ error=error,
+ )
+
+ error_response.additional_properties = d
+ return error_response
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/health_response.py b/libs/fleet/python-sdk/cua_train/models/health_response.py
new file mode 100644
index 0000000000..8172423767
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/health_response.py
@@ -0,0 +1,61 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+T = TypeVar("T", bound="HealthResponse")
+
+
+@_attrs_define
+class HealthResponse:
+ """
+ Attributes:
+ ok (bool | Unset):
+ """
+
+ ok: bool | Unset = UNSET
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ ok = self.ok
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update({})
+ if ok is not UNSET:
+ field_dict["ok"] = ok
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ ok = d.pop("ok", UNSET)
+
+ health_response = cls(
+ ok=ok,
+ )
+
+ health_response.additional_properties = d
+ return health_response
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/healthz_response.py b/libs/fleet/python-sdk/cua_train/models/healthz_response.py
new file mode 100644
index 0000000000..b0d829863d
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/healthz_response.py
@@ -0,0 +1,61 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+T = TypeVar("T", bound="HealthzResponse")
+
+
+@_attrs_define
+class HealthzResponse:
+ """
+ Attributes:
+ status (str):
+ """
+
+ status: str
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ status = self.status
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update(
+ {
+ "status": status,
+ }
+ )
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ status = d.pop("status")
+
+ healthz_response = cls(
+ status=status,
+ )
+
+ healthz_response.additional_properties = d
+ return healthz_response
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/key_client.py b/libs/fleet/python-sdk/cua_train/models/key_client.py
new file mode 100644
index 0000000000..54bb017434
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/key_client.py
@@ -0,0 +1,97 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+T = TypeVar("T", bound="KeyClient")
+
+
+@_attrs_define
+class KeyClient:
+ """
+ Attributes:
+ id (str | Unset):
+ client_id (str | Unset):
+ name (str | Unset):
+ namespace (str | Unset):
+ owner_sub (str | Unset):
+ """
+
+ id: str | Unset = UNSET
+ client_id: str | Unset = UNSET
+ name: str | Unset = UNSET
+ namespace: str | Unset = UNSET
+ owner_sub: str | Unset = UNSET
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ id = self.id
+
+ client_id = self.client_id
+
+ name = self.name
+
+ namespace = self.namespace
+
+ owner_sub = self.owner_sub
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update({})
+ if id is not UNSET:
+ field_dict["id"] = id
+ if client_id is not UNSET:
+ field_dict["client_id"] = client_id
+ if name is not UNSET:
+ field_dict["name"] = name
+ if namespace is not UNSET:
+ field_dict["namespace"] = namespace
+ if owner_sub is not UNSET:
+ field_dict["owner_sub"] = owner_sub
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ id = d.pop("id", UNSET)
+
+ client_id = d.pop("client_id", UNSET)
+
+ name = d.pop("name", UNSET)
+
+ namespace = d.pop("namespace", UNSET)
+
+ owner_sub = d.pop("owner_sub", UNSET)
+
+ key_client = cls(
+ id=id,
+ client_id=client_id,
+ name=name,
+ namespace=namespace,
+ owner_sub=owner_sub,
+ )
+
+ key_client.additional_properties = d
+ return key_client
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/label_batch_summary.py b/libs/fleet/python-sdk/cua_train/models/label_batch_summary.py
new file mode 100644
index 0000000000..91f67ac805
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/label_batch_summary.py
@@ -0,0 +1,143 @@
+from __future__ import annotations
+
+import datetime
+from collections.abc import Mapping
+from typing import TYPE_CHECKING, Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+if TYPE_CHECKING:
+ from ..models.batch_progress import BatchProgress
+
+
+T = TypeVar("T", bound="LabelBatchSummary")
+
+
+@_attrs_define
+class LabelBatchSummary:
+ """
+ Attributes:
+ batch_id (str | Unset):
+ status (str | Unset):
+ progress (BatchProgress | Unset):
+ created_at (datetime.datetime | Unset):
+ updated_at (datetime.datetime | Unset):
+ s3_key (str | Unset):
+ s3_presigned_url (str | Unset):
+ """
+
+ batch_id: str | Unset = UNSET
+ status: str | Unset = UNSET
+ progress: BatchProgress | Unset = UNSET
+ created_at: datetime.datetime | Unset = UNSET
+ updated_at: datetime.datetime | Unset = UNSET
+ s3_key: str | Unset = UNSET
+ s3_presigned_url: str | Unset = UNSET
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ batch_id = self.batch_id
+
+ status = self.status
+
+ progress: dict[str, Any] | Unset = UNSET
+ if not isinstance(self.progress, Unset):
+ progress = self.progress.to_dict()
+
+ created_at: str | Unset = UNSET
+ if not isinstance(self.created_at, Unset):
+ created_at = self.created_at.isoformat()
+
+ updated_at: str | Unset = UNSET
+ if not isinstance(self.updated_at, Unset):
+ updated_at = self.updated_at.isoformat()
+
+ s3_key = self.s3_key
+
+ s3_presigned_url = self.s3_presigned_url
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update({})
+ if batch_id is not UNSET:
+ field_dict["batch_id"] = batch_id
+ if status is not UNSET:
+ field_dict["status"] = status
+ if progress is not UNSET:
+ field_dict["progress"] = progress
+ if created_at is not UNSET:
+ field_dict["created_at"] = created_at
+ if updated_at is not UNSET:
+ field_dict["updated_at"] = updated_at
+ if s3_key is not UNSET:
+ field_dict["s3_key"] = s3_key
+ if s3_presigned_url is not UNSET:
+ field_dict["s3_presigned_url"] = s3_presigned_url
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ from ..models.batch_progress import BatchProgress
+
+ d = dict(src_dict)
+ batch_id = d.pop("batch_id", UNSET)
+
+ status = d.pop("status", UNSET)
+
+ _progress = d.pop("progress", UNSET)
+ progress: BatchProgress | Unset
+ if isinstance(_progress, Unset):
+ progress = UNSET
+ else:
+ progress = BatchProgress.from_dict(_progress)
+
+ _created_at = d.pop("created_at", UNSET)
+ created_at: datetime.datetime | Unset
+ if isinstance(_created_at, Unset):
+ created_at = UNSET
+ else:
+ created_at = datetime.datetime.fromisoformat(_created_at)
+
+ _updated_at = d.pop("updated_at", UNSET)
+ updated_at: datetime.datetime | Unset
+ if isinstance(_updated_at, Unset):
+ updated_at = UNSET
+ else:
+ updated_at = datetime.datetime.fromisoformat(_updated_at)
+
+ s3_key = d.pop("s3_key", UNSET)
+
+ s3_presigned_url = d.pop("s3_presigned_url", UNSET)
+
+ label_batch_summary = cls(
+ batch_id=batch_id,
+ status=status,
+ progress=progress,
+ created_at=created_at,
+ updated_at=updated_at,
+ s3_key=s3_key,
+ s3_presigned_url=s3_presigned_url,
+ )
+
+ label_batch_summary.additional_properties = d
+ return label_batch_summary
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/label_in_progress_response.py b/libs/fleet/python-sdk/cua_train/models/label_in_progress_response.py
new file mode 100644
index 0000000000..aeaf99e06a
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/label_in_progress_response.py
@@ -0,0 +1,88 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+T = TypeVar("T", bound="LabelInProgressResponse")
+
+
+@_attrs_define
+class LabelInProgressResponse:
+ """
+ Attributes:
+ label (str | Unset):
+ batch_count (int | Unset):
+ all_completed (bool | Unset):
+ message (str | Unset):
+ """
+
+ label: str | Unset = UNSET
+ batch_count: int | Unset = UNSET
+ all_completed: bool | Unset = UNSET
+ message: str | Unset = UNSET
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ label = self.label
+
+ batch_count = self.batch_count
+
+ all_completed = self.all_completed
+
+ message = self.message
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update({})
+ if label is not UNSET:
+ field_dict["label"] = label
+ if batch_count is not UNSET:
+ field_dict["batch_count"] = batch_count
+ if all_completed is not UNSET:
+ field_dict["all_completed"] = all_completed
+ if message is not UNSET:
+ field_dict["message"] = message
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ label = d.pop("label", UNSET)
+
+ batch_count = d.pop("batch_count", UNSET)
+
+ all_completed = d.pop("all_completed", UNSET)
+
+ message = d.pop("message", UNSET)
+
+ label_in_progress_response = cls(
+ label=label,
+ batch_count=batch_count,
+ all_completed=all_completed,
+ message=message,
+ )
+
+ label_in_progress_response.additional_properties = d
+ return label_in_progress_response
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/label_results_response.py b/libs/fleet/python-sdk/cua_train/models/label_results_response.py
new file mode 100644
index 0000000000..0ddc78efba
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/label_results_response.py
@@ -0,0 +1,133 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import TYPE_CHECKING, Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+if TYPE_CHECKING:
+ from ..models.batch_results_response import BatchResultsResponse
+ from ..models.batch_summary import BatchSummary
+
+
+T = TypeVar("T", bound="LabelResultsResponse")
+
+
+@_attrs_define
+class LabelResultsResponse:
+ """
+ Attributes:
+ label (str | Unset):
+ batch_count (int | Unset):
+ completed_batch_count (int | Unset):
+ all_completed (bool | Unset):
+ batches (list[BatchResultsResponse] | Unset):
+ summary (BatchSummary | Unset):
+ """
+
+ label: str | Unset = UNSET
+ batch_count: int | Unset = UNSET
+ completed_batch_count: int | Unset = UNSET
+ all_completed: bool | Unset = UNSET
+ batches: list[BatchResultsResponse] | Unset = UNSET
+ summary: BatchSummary | Unset = UNSET
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ label = self.label
+
+ batch_count = self.batch_count
+
+ completed_batch_count = self.completed_batch_count
+
+ all_completed = self.all_completed
+
+ batches: list[dict[str, Any]] | Unset = UNSET
+ if not isinstance(self.batches, Unset):
+ batches = []
+ for batches_item_data in self.batches:
+ batches_item = batches_item_data.to_dict()
+ batches.append(batches_item)
+
+ summary: dict[str, Any] | Unset = UNSET
+ if not isinstance(self.summary, Unset):
+ summary = self.summary.to_dict()
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update({})
+ if label is not UNSET:
+ field_dict["label"] = label
+ if batch_count is not UNSET:
+ field_dict["batch_count"] = batch_count
+ if completed_batch_count is not UNSET:
+ field_dict["completed_batch_count"] = completed_batch_count
+ if all_completed is not UNSET:
+ field_dict["all_completed"] = all_completed
+ if batches is not UNSET:
+ field_dict["batches"] = batches
+ if summary is not UNSET:
+ field_dict["summary"] = summary
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ from ..models.batch_results_response import BatchResultsResponse
+ from ..models.batch_summary import BatchSummary
+
+ d = dict(src_dict)
+ label = d.pop("label", UNSET)
+
+ batch_count = d.pop("batch_count", UNSET)
+
+ completed_batch_count = d.pop("completed_batch_count", UNSET)
+
+ all_completed = d.pop("all_completed", UNSET)
+
+ _batches = d.pop("batches", UNSET)
+ batches: list[BatchResultsResponse] | Unset = UNSET
+ if _batches is not UNSET:
+ batches = []
+ for batches_item_data in _batches:
+ batches_item = BatchResultsResponse.from_dict(batches_item_data)
+
+ batches.append(batches_item)
+
+ _summary = d.pop("summary", UNSET)
+ summary: BatchSummary | Unset
+ if isinstance(_summary, Unset):
+ summary = UNSET
+ else:
+ summary = BatchSummary.from_dict(_summary)
+
+ label_results_response = cls(
+ label=label,
+ batch_count=batch_count,
+ completed_batch_count=completed_batch_count,
+ all_completed=all_completed,
+ batches=batches,
+ summary=summary,
+ )
+
+ label_results_response.additional_properties = d
+ return label_results_response
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/label_status_response.py b/libs/fleet/python-sdk/cua_train/models/label_status_response.py
new file mode 100644
index 0000000000..92148a1df7
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/label_status_response.py
@@ -0,0 +1,124 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import TYPE_CHECKING, Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+if TYPE_CHECKING:
+ from ..models.batch_progress import BatchProgress
+ from ..models.label_batch_summary import LabelBatchSummary
+
+
+T = TypeVar("T", bound="LabelStatusResponse")
+
+
+@_attrs_define
+class LabelStatusResponse:
+ """
+ Attributes:
+ label (str | Unset):
+ batch_count (int | Unset):
+ all_completed (bool | Unset):
+ progress (BatchProgress | Unset):
+ batches (list[LabelBatchSummary] | Unset):
+ """
+
+ label: str | Unset = UNSET
+ batch_count: int | Unset = UNSET
+ all_completed: bool | Unset = UNSET
+ progress: BatchProgress | Unset = UNSET
+ batches: list[LabelBatchSummary] | Unset = UNSET
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ label = self.label
+
+ batch_count = self.batch_count
+
+ all_completed = self.all_completed
+
+ progress: dict[str, Any] | Unset = UNSET
+ if not isinstance(self.progress, Unset):
+ progress = self.progress.to_dict()
+
+ batches: list[dict[str, Any]] | Unset = UNSET
+ if not isinstance(self.batches, Unset):
+ batches = []
+ for batches_item_data in self.batches:
+ batches_item = batches_item_data.to_dict()
+ batches.append(batches_item)
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update({})
+ if label is not UNSET:
+ field_dict["label"] = label
+ if batch_count is not UNSET:
+ field_dict["batch_count"] = batch_count
+ if all_completed is not UNSET:
+ field_dict["all_completed"] = all_completed
+ if progress is not UNSET:
+ field_dict["progress"] = progress
+ if batches is not UNSET:
+ field_dict["batches"] = batches
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ from ..models.batch_progress import BatchProgress
+ from ..models.label_batch_summary import LabelBatchSummary
+
+ d = dict(src_dict)
+ label = d.pop("label", UNSET)
+
+ batch_count = d.pop("batch_count", UNSET)
+
+ all_completed = d.pop("all_completed", UNSET)
+
+ _progress = d.pop("progress", UNSET)
+ progress: BatchProgress | Unset
+ if isinstance(_progress, Unset):
+ progress = UNSET
+ else:
+ progress = BatchProgress.from_dict(_progress)
+
+ _batches = d.pop("batches", UNSET)
+ batches: list[LabelBatchSummary] | Unset = UNSET
+ if _batches is not UNSET:
+ batches = []
+ for batches_item_data in _batches:
+ batches_item = LabelBatchSummary.from_dict(batches_item_data)
+
+ batches.append(batches_item)
+
+ label_status_response = cls(
+ label=label,
+ batch_count=batch_count,
+ all_completed=all_completed,
+ progress=progress,
+ batches=batches,
+ )
+
+ label_status_response.additional_properties = d
+ return label_status_response
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/lane_create_request.py b/libs/fleet/python-sdk/cua_train/models/lane_create_request.py
new file mode 100644
index 0000000000..cfc634808e
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/lane_create_request.py
@@ -0,0 +1,67 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+T = TypeVar("T", bound="LaneCreateRequest")
+
+
+@_attrs_define
+class LaneCreateRequest:
+ """Body of POST /lanes.
+
+ ``ttl_seconds`` is the absolute time the claim is reserved for;
+ after that the reaper deletes it. With ``autoRenew=true`` the lane
+ auto-renew timer in pool-operator pushes this forward, so the
+ customer's effective TTL is "as long as the lane exists".
+
+ Attributes:
+ ttl_seconds (int | Unset): Default: 300.
+ """
+
+ ttl_seconds: int | Unset = 300
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ ttl_seconds = self.ttl_seconds
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update({})
+ if ttl_seconds is not UNSET:
+ field_dict["ttl_seconds"] = ttl_seconds
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ ttl_seconds = d.pop("ttl_seconds", UNSET)
+
+ lane_create_request = cls(
+ ttl_seconds=ttl_seconds,
+ )
+
+ lane_create_request.additional_properties = d
+ return lane_create_request
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/lane_delete_response.py b/libs/fleet/python-sdk/cua_train/models/lane_delete_response.py
new file mode 100644
index 0000000000..cc9af25268
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/lane_delete_response.py
@@ -0,0 +1,61 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+T = TypeVar("T", bound="LaneDeleteResponse")
+
+
+@_attrs_define
+class LaneDeleteResponse:
+ """
+ Attributes:
+ lane_id (str):
+ """
+
+ lane_id: str
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ lane_id = self.lane_id
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update(
+ {
+ "lane_id": lane_id,
+ }
+ )
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ lane_id = d.pop("lane_id")
+
+ lane_delete_response = cls(
+ lane_id=lane_id,
+ )
+
+ lane_delete_response.additional_properties = d
+ return lane_delete_response
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/lane_response.py b/libs/fleet/python-sdk/cua_train/models/lane_response.py
new file mode 100644
index 0000000000..3d1b680806
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/lane_response.py
@@ -0,0 +1,91 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, TypeVar, cast
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+T = TypeVar("T", bound="LaneResponse")
+
+
+@_attrs_define
+class LaneResponse:
+ """
+ Attributes:
+ lane_id (str):
+ vm_id (str):
+ screenshot (None | str | Unset):
+ """
+
+ lane_id: str
+ vm_id: str
+ screenshot: None | str | Unset = UNSET
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ lane_id = self.lane_id
+
+ vm_id = self.vm_id
+
+ screenshot: None | str | Unset
+ if isinstance(self.screenshot, Unset):
+ screenshot = UNSET
+ else:
+ screenshot = self.screenshot
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update(
+ {
+ "lane_id": lane_id,
+ "vm_id": vm_id,
+ }
+ )
+ if screenshot is not UNSET:
+ field_dict["screenshot"] = screenshot
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ lane_id = d.pop("lane_id")
+
+ vm_id = d.pop("vm_id")
+
+ def _parse_screenshot(data: object) -> None | str | Unset:
+ if data is None:
+ return data
+ if isinstance(data, Unset):
+ return data
+ return cast(None | str | Unset, data)
+
+ screenshot = _parse_screenshot(d.pop("screenshot", UNSET))
+
+ lane_response = cls(
+ lane_id=lane_id,
+ vm_id=vm_id,
+ screenshot=screenshot,
+ )
+
+ lane_response.additional_properties = d
+ return lane_response
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/lane_swap_response.py b/libs/fleet/python-sdk/cua_train/models/lane_swap_response.py
new file mode 100644
index 0000000000..46272c5edf
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/lane_swap_response.py
@@ -0,0 +1,77 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+T = TypeVar("T", bound="LaneSwapResponse")
+
+
+@_attrs_define
+class LaneSwapResponse:
+ """
+ Attributes:
+ lane_id (str):
+ vm_id (str):
+ wait_seconds (float):
+ """
+
+ lane_id: str
+ vm_id: str
+ wait_seconds: float
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ lane_id = self.lane_id
+
+ vm_id = self.vm_id
+
+ wait_seconds = self.wait_seconds
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update(
+ {
+ "lane_id": lane_id,
+ "vm_id": vm_id,
+ "wait_seconds": wait_seconds,
+ }
+ )
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ lane_id = d.pop("lane_id")
+
+ vm_id = d.pop("vm_id")
+
+ wait_seconds = d.pop("wait_seconds")
+
+ lane_swap_response = cls(
+ lane_id=lane_id,
+ vm_id=vm_id,
+ wait_seconds=wait_seconds,
+ )
+
+ lane_swap_response.additional_properties = d
+ return lane_swap_response
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/list_keys_response.py b/libs/fleet/python-sdk/cua_train/models/list_keys_response.py
new file mode 100644
index 0000000000..97a45082fa
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/list_keys_response.py
@@ -0,0 +1,79 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import TYPE_CHECKING, Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+if TYPE_CHECKING:
+ from ..models.key_client import KeyClient
+
+
+T = TypeVar("T", bound="ListKeysResponse")
+
+
+@_attrs_define
+class ListKeysResponse:
+ """
+ Attributes:
+ keys (list[KeyClient] | Unset):
+ """
+
+ keys: list[KeyClient] | Unset = UNSET
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ keys: list[dict[str, Any]] | Unset = UNSET
+ if not isinstance(self.keys, Unset):
+ keys = []
+ for keys_item_data in self.keys:
+ keys_item = keys_item_data.to_dict()
+ keys.append(keys_item)
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update({})
+ if keys is not UNSET:
+ field_dict["keys"] = keys
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ from ..models.key_client import KeyClient
+
+ d = dict(src_dict)
+ _keys = d.pop("keys", UNSET)
+ keys: list[KeyClient] | Unset = UNSET
+ if _keys is not UNSET:
+ keys = []
+ for keys_item_data in _keys:
+ keys_item = KeyClient.from_dict(keys_item_data)
+
+ keys.append(keys_item)
+
+ list_keys_response = cls(
+ keys=keys,
+ )
+
+ list_keys_response.additional_properties = d
+ return list_keys_response
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/pool_list_response.py b/libs/fleet/python-sdk/cua_train/models/pool_list_response.py
new file mode 100644
index 0000000000..cbfb8db4c5
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/pool_list_response.py
@@ -0,0 +1,83 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import TYPE_CHECKING, Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+if TYPE_CHECKING:
+ from ..models.pool_list_response_vms_item import PoolListResponseVmsItem
+
+
+T = TypeVar("T", bound="PoolListResponse")
+
+
+@_attrs_define
+class PoolListResponse:
+ """
+ Attributes:
+ vms (list[PoolListResponseVmsItem]):
+ count (int):
+ """
+
+ vms: list[PoolListResponseVmsItem]
+ count: int
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ vms = []
+ for vms_item_data in self.vms:
+ vms_item = vms_item_data.to_dict()
+ vms.append(vms_item)
+
+ count = self.count
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update(
+ {
+ "vms": vms,
+ "count": count,
+ }
+ )
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ from ..models.pool_list_response_vms_item import PoolListResponseVmsItem
+
+ d = dict(src_dict)
+ vms = []
+ _vms = d.pop("vms")
+ for vms_item_data in _vms:
+ vms_item = PoolListResponseVmsItem.from_dict(vms_item_data)
+
+ vms.append(vms_item)
+
+ count = d.pop("count")
+
+ pool_list_response = cls(
+ vms=vms,
+ count=count,
+ )
+
+ pool_list_response.additional_properties = d
+ return pool_list_response
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/pool_list_response_vms_item.py b/libs/fleet/python-sdk/cua_train/models/pool_list_response_vms_item.py
new file mode 100644
index 0000000000..79d2871fc2
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/pool_list_response_vms_item.py
@@ -0,0 +1,47 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+T = TypeVar("T", bound="PoolListResponseVmsItem")
+
+
+@_attrs_define
+class PoolListResponseVmsItem:
+ """ """
+
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ pool_list_response_vms_item = cls()
+
+ pool_list_response_vms_item.additional_properties = d
+ return pool_list_response_vms_item
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/release_lanes_request.py b/libs/fleet/python-sdk/cua_train/models/release_lanes_request.py
new file mode 100644
index 0000000000..69ae98df1c
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/release_lanes_request.py
@@ -0,0 +1,61 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, TypeVar, cast
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+T = TypeVar("T", bound="ReleaseLanesRequest")
+
+
+@_attrs_define
+class ReleaseLanesRequest:
+ """
+ Attributes:
+ vm_ids (list[str]): VM ids to shut down (lanes to release).
+ """
+
+ vm_ids: list[str]
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ vm_ids = self.vm_ids
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update(
+ {
+ "vm_ids": vm_ids,
+ }
+ )
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ vm_ids = cast(list[str], d.pop("vm_ids"))
+
+ release_lanes_request = cls(
+ vm_ids=vm_ids,
+ )
+
+ release_lanes_request.additional_properties = d
+ return release_lanes_request
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/release_lanes_response.py b/libs/fleet/python-sdk/cua_train/models/release_lanes_response.py
new file mode 100644
index 0000000000..494ea6cc48
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/release_lanes_response.py
@@ -0,0 +1,61 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+T = TypeVar("T", bound="ReleaseLanesResponse")
+
+
+@_attrs_define
+class ReleaseLanesResponse:
+ """
+ Attributes:
+ released (int | Unset): Number of vm_ids submitted for release.
+ """
+
+ released: int | Unset = UNSET
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ released = self.released
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update({})
+ if released is not UNSET:
+ field_dict["released"] = released
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ released = d.pop("released", UNSET)
+
+ release_lanes_response = cls(
+ released=released,
+ )
+
+ release_lanes_response.additional_properties = d
+ return release_lanes_response
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/reset_request.py b/libs/fleet/python-sdk/cua_train/models/reset_request.py
new file mode 100644
index 0000000000..1d69fc2fd1
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/reset_request.py
@@ -0,0 +1,75 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import TYPE_CHECKING, Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+if TYPE_CHECKING:
+ from ..models.reset_request_task_config import ResetRequestTaskConfig
+
+
+T = TypeVar("T", bound="ResetRequest")
+
+
+@_attrs_define
+class ResetRequest:
+ """
+ Attributes:
+ task_config (ResetRequestTaskConfig):
+ timeout (int):
+ """
+
+ task_config: ResetRequestTaskConfig
+ timeout: int
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ task_config = self.task_config.to_dict()
+
+ timeout = self.timeout
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update(
+ {
+ "task_config": task_config,
+ "timeout": timeout,
+ }
+ )
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ from ..models.reset_request_task_config import ResetRequestTaskConfig
+
+ d = dict(src_dict)
+ task_config = ResetRequestTaskConfig.from_dict(d.pop("task_config"))
+
+ timeout = d.pop("timeout")
+
+ reset_request = cls(
+ task_config=task_config,
+ timeout=timeout,
+ )
+
+ reset_request.additional_properties = d
+ return reset_request
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/reset_request_task_config.py b/libs/fleet/python-sdk/cua_train/models/reset_request_task_config.py
new file mode 100644
index 0000000000..e8cc4a55c7
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/reset_request_task_config.py
@@ -0,0 +1,47 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+T = TypeVar("T", bound="ResetRequestTaskConfig")
+
+
+@_attrs_define
+class ResetRequestTaskConfig:
+ """ """
+
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ reset_request_task_config = cls()
+
+ reset_request_task_config.additional_properties = d
+ return reset_request_task_config
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/reset_response.py b/libs/fleet/python-sdk/cua_train/models/reset_response.py
new file mode 100644
index 0000000000..de7d5d14b3
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/reset_response.py
@@ -0,0 +1,77 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+T = TypeVar("T", bound="ResetResponse")
+
+
+@_attrs_define
+class ResetResponse:
+ """
+ Attributes:
+ screenshot (str):
+ problem (str):
+ vm_id (str):
+ """
+
+ screenshot: str
+ problem: str
+ vm_id: str
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ screenshot = self.screenshot
+
+ problem = self.problem
+
+ vm_id = self.vm_id
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update(
+ {
+ "screenshot": screenshot,
+ "problem": problem,
+ "vm_id": vm_id,
+ }
+ )
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ screenshot = d.pop("screenshot")
+
+ problem = d.pop("problem")
+
+ vm_id = d.pop("vm_id")
+
+ reset_response = cls(
+ screenshot=screenshot,
+ problem=problem,
+ vm_id=vm_id,
+ )
+
+ reset_response.additional_properties = d
+ return reset_response
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/run_config.py b/libs/fleet/python-sdk/cua_train/models/run_config.py
new file mode 100644
index 0000000000..16cd10739c
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/run_config.py
@@ -0,0 +1,99 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import TYPE_CHECKING, Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+if TYPE_CHECKING:
+ from ..models.action import Action
+
+
+T = TypeVar("T", bound="RunConfig")
+
+
+@_attrs_define
+class RunConfig:
+ """
+ Attributes:
+ steps (list[Action]): Ordered actions to execute on the rollout VM. A step with `action_type: "RESET"` is a
+ reserved control action: instead of being forwarded to the VM, it hard-resets the VM in place (new vm_id, clean
+ baseline desktop), so one run can execute several independent episodes on a warm instance.
+ timeout (int | Unset): Per-rollout timeout in seconds (max 24h).
+ vm_id (str | Unset): Reattach this run to an existing warm VM (instance reuse / "lane"), typically a vm_id
+ returned by a previous `keep_warm` batch, instead of acquiring a fresh one. If that claim has already expired,
+ the run transparently falls back to a fresh VM.
+ """
+
+ steps: list[Action]
+ timeout: int | Unset = UNSET
+ vm_id: str | Unset = UNSET
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ steps = []
+ for steps_item_data in self.steps:
+ steps_item = steps_item_data.to_dict()
+ steps.append(steps_item)
+
+ timeout = self.timeout
+
+ vm_id = self.vm_id
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update(
+ {
+ "steps": steps,
+ }
+ )
+ if timeout is not UNSET:
+ field_dict["timeout"] = timeout
+ if vm_id is not UNSET:
+ field_dict["vm_id"] = vm_id
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ from ..models.action import Action
+
+ d = dict(src_dict)
+ steps = []
+ _steps = d.pop("steps")
+ for steps_item_data in _steps:
+ steps_item = Action.from_dict(steps_item_data)
+
+ steps.append(steps_item)
+
+ timeout = d.pop("timeout", UNSET)
+
+ vm_id = d.pop("vm_id", UNSET)
+
+ run_config = cls(
+ steps=steps,
+ timeout=timeout,
+ vm_id=vm_id,
+ )
+
+ run_config.additional_properties = d
+ return run_config
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/run_result.py b/libs/fleet/python-sdk/cua_train/models/run_result.py
new file mode 100644
index 0000000000..ee264934a5
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/run_result.py
@@ -0,0 +1,139 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, TypeVar, cast
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+T = TypeVar("T", bound="RunResult")
+
+
+@_attrs_define
+class RunResult:
+ """
+ Attributes:
+ run_id (int | Unset):
+ vm_id (str | Unset):
+ ok (bool | Unset):
+ error (str | Unset):
+ reset_ms (int | Unset):
+ step_ms (list[int] | Unset):
+ shutdown_ms (int | Unset):
+ actions (list[str] | Unset):
+ screenshots (list[str] | Unset):
+ """
+
+ run_id: int | Unset = UNSET
+ vm_id: str | Unset = UNSET
+ ok: bool | Unset = UNSET
+ error: str | Unset = UNSET
+ reset_ms: int | Unset = UNSET
+ step_ms: list[int] | Unset = UNSET
+ shutdown_ms: int | Unset = UNSET
+ actions: list[str] | Unset = UNSET
+ screenshots: list[str] | Unset = UNSET
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ run_id = self.run_id
+
+ vm_id = self.vm_id
+
+ ok = self.ok
+
+ error = self.error
+
+ reset_ms = self.reset_ms
+
+ step_ms: list[int] | Unset = UNSET
+ if not isinstance(self.step_ms, Unset):
+ step_ms = self.step_ms
+
+ shutdown_ms = self.shutdown_ms
+
+ actions: list[str] | Unset = UNSET
+ if not isinstance(self.actions, Unset):
+ actions = self.actions
+
+ screenshots: list[str] | Unset = UNSET
+ if not isinstance(self.screenshots, Unset):
+ screenshots = self.screenshots
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update({})
+ if run_id is not UNSET:
+ field_dict["run_id"] = run_id
+ if vm_id is not UNSET:
+ field_dict["vm_id"] = vm_id
+ if ok is not UNSET:
+ field_dict["ok"] = ok
+ if error is not UNSET:
+ field_dict["error"] = error
+ if reset_ms is not UNSET:
+ field_dict["reset_ms"] = reset_ms
+ if step_ms is not UNSET:
+ field_dict["step_ms"] = step_ms
+ if shutdown_ms is not UNSET:
+ field_dict["shutdown_ms"] = shutdown_ms
+ if actions is not UNSET:
+ field_dict["actions"] = actions
+ if screenshots is not UNSET:
+ field_dict["screenshots"] = screenshots
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ run_id = d.pop("run_id", UNSET)
+
+ vm_id = d.pop("vm_id", UNSET)
+
+ ok = d.pop("ok", UNSET)
+
+ error = d.pop("error", UNSET)
+
+ reset_ms = d.pop("reset_ms", UNSET)
+
+ step_ms = cast(list[int], d.pop("step_ms", UNSET))
+
+ shutdown_ms = d.pop("shutdown_ms", UNSET)
+
+ actions = cast(list[str], d.pop("actions", UNSET))
+
+ screenshots = cast(list[str], d.pop("screenshots", UNSET))
+
+ run_result = cls(
+ run_id=run_id,
+ vm_id=vm_id,
+ ok=ok,
+ error=error,
+ reset_ms=reset_ms,
+ step_ms=step_ms,
+ shutdown_ms=shutdown_ms,
+ actions=actions,
+ screenshots=screenshots,
+ )
+
+ run_result.additional_properties = d
+ return run_result
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/screenshot_response.py b/libs/fleet/python-sdk/cua_train/models/screenshot_response.py
new file mode 100644
index 0000000000..ac733c46b3
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/screenshot_response.py
@@ -0,0 +1,69 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+T = TypeVar("T", bound="ScreenshotResponse")
+
+
+@_attrs_define
+class ScreenshotResponse:
+ """
+ Attributes:
+ screenshot (str):
+ vm_id (str):
+ """
+
+ screenshot: str
+ vm_id: str
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ screenshot = self.screenshot
+
+ vm_id = self.vm_id
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update(
+ {
+ "screenshot": screenshot,
+ "vm_id": vm_id,
+ }
+ )
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ screenshot = d.pop("screenshot")
+
+ vm_id = d.pop("vm_id")
+
+ screenshot_response = cls(
+ screenshot=screenshot,
+ vm_id=vm_id,
+ )
+
+ screenshot_response.additional_properties = d
+ return screenshot_response
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/shutdown_request.py b/libs/fleet/python-sdk/cua_train/models/shutdown_request.py
new file mode 100644
index 0000000000..41efd71c6b
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/shutdown_request.py
@@ -0,0 +1,61 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+T = TypeVar("T", bound="ShutdownRequest")
+
+
+@_attrs_define
+class ShutdownRequest:
+ """
+ Attributes:
+ vm_id (str):
+ """
+
+ vm_id: str
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ vm_id = self.vm_id
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update(
+ {
+ "vm_id": vm_id,
+ }
+ )
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ vm_id = d.pop("vm_id")
+
+ shutdown_request = cls(
+ vm_id=vm_id,
+ )
+
+ shutdown_request.additional_properties = d
+ return shutdown_request
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/shutdown_response.py b/libs/fleet/python-sdk/cua_train/models/shutdown_response.py
new file mode 100644
index 0000000000..ba86618657
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/shutdown_response.py
@@ -0,0 +1,61 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+T = TypeVar("T", bound="ShutdownResponse")
+
+
+@_attrs_define
+class ShutdownResponse:
+ """
+ Attributes:
+ vm_id (str):
+ """
+
+ vm_id: str
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ vm_id = self.vm_id
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update(
+ {
+ "vm_id": vm_id,
+ }
+ )
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ vm_id = d.pop("vm_id")
+
+ shutdown_response = cls(
+ vm_id=vm_id,
+ )
+
+ shutdown_response.additional_properties = d
+ return shutdown_response
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/step_request.py b/libs/fleet/python-sdk/cua_train/models/step_request.py
new file mode 100644
index 0000000000..ac578484c7
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/step_request.py
@@ -0,0 +1,80 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+T = TypeVar("T", bound="StepRequest")
+
+
+@_attrs_define
+class StepRequest:
+ """
+ Attributes:
+ action (str):
+ vm_id (str):
+ timeout (int | Unset): Default: 300.
+ """
+
+ action: str
+ vm_id: str
+ timeout: int | Unset = 300
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ action = self.action
+
+ vm_id = self.vm_id
+
+ timeout = self.timeout
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update(
+ {
+ "action": action,
+ "vm_id": vm_id,
+ }
+ )
+ if timeout is not UNSET:
+ field_dict["timeout"] = timeout
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ action = d.pop("action")
+
+ vm_id = d.pop("vm_id")
+
+ timeout = d.pop("timeout", UNSET)
+
+ step_request = cls(
+ action=action,
+ vm_id=vm_id,
+ timeout=timeout,
+ )
+
+ step_request.additional_properties = d
+ return step_request
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/step_response.py b/libs/fleet/python-sdk/cua_train/models/step_response.py
new file mode 100644
index 0000000000..e9a2e89dd5
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/step_response.py
@@ -0,0 +1,84 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, TypeVar, cast
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+T = TypeVar("T", bound="StepResponse")
+
+
+@_attrs_define
+class StepResponse:
+ """
+ Attributes:
+ screenshot (None | str):
+ is_finish (bool):
+ reward (float):
+ """
+
+ screenshot: None | str
+ is_finish: bool
+ reward: float
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ screenshot: None | str
+ screenshot = self.screenshot
+
+ is_finish = self.is_finish
+
+ reward = self.reward
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update(
+ {
+ "screenshot": screenshot,
+ "is_finish": is_finish,
+ "reward": reward,
+ }
+ )
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+
+ def _parse_screenshot(data: object) -> None | str:
+ if data is None:
+ return data
+ return cast(None | str, data)
+
+ screenshot = _parse_screenshot(d.pop("screenshot"))
+
+ is_finish = d.pop("is_finish")
+
+ reward = d.pop("reward")
+
+ step_response = cls(
+ screenshot=screenshot,
+ is_finish=is_finish,
+ reward=reward,
+ )
+
+ step_response.additional_properties = d
+ return step_response
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/models/timing_stats.py b/libs/fleet/python-sdk/cua_train/models/timing_stats.py
new file mode 100644
index 0000000000..6bd6ebedf6
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/models/timing_stats.py
@@ -0,0 +1,88 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, TypeVar
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+T = TypeVar("T", bound="TimingStats")
+
+
+@_attrs_define
+class TimingStats:
+ """
+ Attributes:
+ n (int | Unset):
+ min_ (int | Unset):
+ mean (float | Unset):
+ max_ (int | Unset):
+ """
+
+ n: int | Unset = UNSET
+ min_: int | Unset = UNSET
+ mean: float | Unset = UNSET
+ max_: int | Unset = UNSET
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ n = self.n
+
+ min_ = self.min_
+
+ mean = self.mean
+
+ max_ = self.max_
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update({})
+ if n is not UNSET:
+ field_dict["n"] = n
+ if min_ is not UNSET:
+ field_dict["min"] = min_
+ if mean is not UNSET:
+ field_dict["mean"] = mean
+ if max_ is not UNSET:
+ field_dict["max"] = max_
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ n = d.pop("n", UNSET)
+
+ min_ = d.pop("min", UNSET)
+
+ mean = d.pop("mean", UNSET)
+
+ max_ = d.pop("max", UNSET)
+
+ timing_stats = cls(
+ n=n,
+ min_=min_,
+ mean=mean,
+ max_=max_,
+ )
+
+ timing_stats.additional_properties = d
+ return timing_stats
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/libs/fleet/python-sdk/cua_train/py.typed b/libs/fleet/python-sdk/cua_train/py.typed
new file mode 100644
index 0000000000..1aad32711f
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/py.typed
@@ -0,0 +1 @@
+# Marker file for PEP 561
\ No newline at end of file
diff --git a/libs/fleet/python-sdk/cua_train/types.py b/libs/fleet/python-sdk/cua_train/types.py
new file mode 100644
index 0000000000..b64af09529
--- /dev/null
+++ b/libs/fleet/python-sdk/cua_train/types.py
@@ -0,0 +1,54 @@
+"""Contains some shared types for properties"""
+
+from collections.abc import Mapping, MutableMapping
+from http import HTTPStatus
+from typing import IO, BinaryIO, Generic, Literal, TypeVar
+
+from attrs import define
+
+
+class Unset:
+ def __bool__(self) -> Literal[False]:
+ return False
+
+
+UNSET: Unset = Unset()
+
+# The types that `httpx.Client(files=)` can accept, copied from that library.
+FileContent = IO[bytes] | bytes | str
+FileTypes = (
+ # (filename, file (or bytes), content_type)
+ tuple[str | None, FileContent, str | None]
+ # (filename, file (or bytes), content_type, headers)
+ | tuple[str | None, FileContent, str | None, Mapping[str, str]]
+)
+RequestFiles = list[tuple[str, FileTypes]]
+
+
+@define
+class File:
+ """Contains information for file uploads"""
+
+ payload: BinaryIO
+ file_name: str | None = None
+ mime_type: str | None = None
+
+ def to_tuple(self) -> FileTypes:
+ """Return a tuple representation that httpx will accept for multipart/form-data"""
+ return self.file_name, self.payload, self.mime_type
+
+
+T = TypeVar("T")
+
+
+@define
+class Response(Generic[T]):
+ """A response from an endpoint"""
+
+ status_code: HTTPStatus
+ content: bytes
+ headers: MutableMapping[str, str]
+ parsed: T | None
+
+
+__all__ = ["UNSET", "File", "FileTypes", "RequestFiles", "Response", "Unset"]
diff --git a/libs/fleet/python-sdk/examples/claim_and_connect.py b/libs/fleet/python-sdk/examples/claim_and_connect.py
new file mode 100644
index 0000000000..fde6771a9c
--- /dev/null
+++ b/libs/fleet/python-sdk/examples/claim_and_connect.py
@@ -0,0 +1,236 @@
+#!/usr/bin/env python3
+"""Claim a sandbox from a pool, wait for it to bind, then call one of its
+service endpoints — all through the cyclops-cs backend with a client id/secret.
+
+What it illustrates:
+ * ``TrainClient.from_key`` for the client_credentials exchange + transparent
+ token refresh, reused as a plain authenticated httpx client for endpoints
+ that are NOT in the generated SDK surface
+ * creating an ``OSGymSandboxClaim`` CR via the ``/api/k8s`` kubectl-proxy
+ (the same path the SPA uses — the pool-operator binds it to a warm sandbox)
+ * reaching the claimed sandbox through ``/api/svc/{namespace}/{service}/``
+
+Auth — use a per-USER key (``ukey-...``), not a per-pool key:
+``/api/k8s`` impersonates the token's owner so Capsule tenant RBAC applies.
+Per-user keys (POST /api/user-keys) act on behalf of their owner and can
+create claims; per-pool keys (POST /api/keys, ``key-...``) have no K8s
+identity and are rejected on the claim step.
+
+Setup::
+
+ pip install cua-train --extra-index-url https://wheels.cua.ai/simple/
+ export CUA_CLIENT_ID=ukey-xxxxxxxx # from POST /api/user-keys
+ export CUA_CLIENT_SECRET=...
+ python claim_and_connect.py --pool my-pool # first pool service
+ python claim_and_connect.py --pool my-pool --service vnc --path /healthz
+ python claim_and_connect.py --pool win --service cua-driver --mcp
+
+``--mcp`` runs the cua-driver MCP handshake (initialize → session id →
+tools/list) instead of a plain GET — proof the desktop is drivable, not
+just that something answers HTTP.
+
+The claim is released (DELETE) on exit unless ``--keep`` is passed.
+
+A sandbox released by an earlier claim is hard-reset in place and rejoins
+the pool, but its guest OS reboots — the in-guest service answers 502
+("upstream unavailable") for a few minutes after the claim binds. The
+script polls the service until it responds (``--ready-timeout``).
+
+Env knobs: CUA_CLIENT_ID, CUA_CLIENT_SECRET, CUA_TOKEN_URL, CUA_BASE_URL.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import sys
+import time
+import uuid
+
+import httpx
+
+from cua_train import TrainClient
+
+# Native CRD coordinates (osgym.cua.ai group). The pool-operator watches
+# OSGymSandboxClaims and binds each to a warm sandbox from the pool; the pool's
+# VM shape (image, size, services) lives on its OSGymSandboxTemplate.
+GROUP = "osgym.cua.ai"
+VERSION = "v1alpha1"
+CLAIM_PLURAL = "osgymsandboxclaims"
+TEMPLATE_PLURAL = "osgymsandboxtemplates"
+
+DEFAULT_TOKEN_URL = "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token"
+DEFAULT_BASE_URL = "https://run.cua.ai"
+
+
+def claims_url(pool: str, name: str | None = None) -> str:
+ base = f"/api/k8s/apis/{GROUP}/{VERSION}/namespaces/{pool}/{CLAIM_PLURAL}"
+ return f"{base}/{name}" if name else base
+
+
+def template_url(pool: str, name: str) -> str:
+ return f"/api/k8s/apis/{GROUP}/{VERSION}/namespaces/{pool}/{TEMPLATE_PLURAL}/{name}"
+
+
+def first_template_service(http: httpx.Client, pool: str) -> str:
+ """Name of the first service the pool's template declares
+ (spec.vmTemplate.services[0].name on <pool>-template)."""
+ tmpl = f"{pool}-template"
+ r = http.get(template_url(pool, tmpl))
+ r.raise_for_status()
+ vm_template = r.json().get("spec", {}).get("vmTemplate") or {}
+ services = vm_template.get("services") or []
+ if not services:
+ sys.exit(
+ f"template {tmpl!r} declares no services — pass --service or add one "
+ f"to spec.vmTemplate.services"
+ )
+ return services[0]["name"]
+
+
+def create_claim(http: httpx.Client, pool: str, name: str) -> None:
+ r = http.post(
+ claims_url(pool),
+ json={
+ "apiVersion": f"{GROUP}/{VERSION}",
+ "kind": "OSGymSandboxClaim",
+ "metadata": {"name": name},
+ # Pool name = namespace name (1:1), and each pool ships a template
+ # named "<pool>-template" — same convention the SPA uses.
+ "spec": {"sandboxTemplateRef": {"name": f"{pool}-template"}},
+ },
+ )
+ if r.status_code == 403:
+ sys.exit(
+ "403 creating claim — is this a per-pool key? Claims need a per-USER "
+ "key (client id starting with 'ukey-', from POST /api/user-keys)."
+ )
+ r.raise_for_status()
+
+
+def wait_bound(http: httpx.Client, pool: str, name: str, timeout: float) -> str:
+ """Poll the claim until status.phase == Bound; return the sandbox name."""
+ deadline = time.monotonic() + timeout
+ while True:
+ r = http.get(claims_url(pool, name))
+ r.raise_for_status()
+ status = r.json().get("status") or {}
+ phase = status.get("phase", "Pending")
+ sandbox = (status.get("sandbox") or {}).get("name")
+ if phase == "Bound" and sandbox:
+ return sandbox
+ if phase == "Failed":
+ sys.exit(f"claim {name} failed: {status}")
+ if time.monotonic() > deadline:
+ sys.exit(f"timed out after {timeout:.0f}s waiting for claim {name} (phase={phase})")
+ print(f" claim {name}: {phase} …")
+ time.sleep(2)
+
+
+def wait_service_ready(http, url: str, timeout: float) -> httpx.Response:
+ """GET url until the in-guest service answers with something other than
+ a proxy 502/503/504 (the guest OS is still booting after a reset)."""
+ deadline = time.monotonic() + timeout
+ while True:
+ resp = http().get(url)
+ if resp.status_code not in (502, 503, 504):
+ return resp
+ if time.monotonic() > deadline:
+ sys.exit(f"timed out after {timeout:.0f}s waiting for the service (last: HTTP {resp.status_code})")
+ print(f" HTTP {resp.status_code} — guest still booting …")
+ time.sleep(15)
+
+
+def mcp_handshake(http, base: str) -> None:
+ """initialize → notifications/initialized → tools/list against the
+ cua-driver Streamable HTTP MCP endpoint at {base}/mcp."""
+ url = f"{base}/mcp"
+ headers = {
+ "Content-Type": "application/json",
+ "Accept": "application/json, text/event-stream",
+ }
+ r = http().post(url, headers=headers, json={
+ "jsonrpc": "2.0", "id": 1, "method": "initialize",
+ "params": {
+ "protocolVersion": "2025-03-26",
+ "capabilities": {},
+ "clientInfo": {"name": "claim_and_connect", "version": "0.1.0"},
+ },
+ })
+ r.raise_for_status()
+ session = r.headers.get("mcp-session-id")
+ print(f"MCP initialize: HTTP {r.status_code}, session {session}")
+ if session:
+ headers["Mcp-Session-Id"] = session
+ http().post(url, headers=headers, json={"jsonrpc": "2.0", "method": "notifications/initialized"})
+ r = http().post(url, headers=headers, json={"jsonrpc": "2.0", "id": 2, "method": "tools/list"})
+ r.raise_for_status()
+ # Streamable HTTP returns SSE ("event: message\ndata: {...}"); the JSON
+ # payload is on the data: line.
+ data = next((ln[6:] for ln in r.text.splitlines() if ln.startswith("data: ")), r.text)
+ tools = [t.get("name") for t in json.loads(data).get("result", {}).get("tools", [])]
+ print(f"MCP tools ({len(tools)}): {', '.join(sorted(tools)[:12])}{', …' if len(tools) > 12 else ''}")
+
+
+def main() -> None:
+ p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ p.add_argument("--pool", required=True, help="pool name (= namespace)")
+ p.add_argument("--service", help="service name (default: first service in the pool's template)")
+ p.add_argument("--path", default="/", help="path to request on the service (default: /)")
+ p.add_argument("--claim-name", help="claim name (default: claim-<random>)")
+ p.add_argument("--timeout", type=float, default=300, help="seconds to wait for Bound (default: 300)")
+ p.add_argument("--ready-timeout", type=float, default=420,
+ help="seconds to wait for the in-guest service after binding (default: 420)")
+ p.add_argument("--mcp", action="store_true",
+ help="run the cua-driver MCP handshake (initialize + tools/list) instead of GET --path")
+ p.add_argument("--keep", action="store_true", help="keep the claim instead of releasing it on exit")
+ args = p.parse_args()
+
+ client_id = os.environ.get("CUA_CLIENT_ID")
+ client_secret = os.environ.get("CUA_CLIENT_SECRET")
+ if not client_id or not client_secret:
+ sys.exit("set CUA_CLIENT_ID and CUA_CLIENT_SECRET (per-user key, POST /api/user-keys)")
+
+ client = TrainClient.from_key(
+ token_url=os.environ.get("CUA_TOKEN_URL", DEFAULT_TOKEN_URL),
+ client_id=client_id,
+ client_secret=client_secret,
+ base_url=os.environ.get("CUA_BASE_URL", DEFAULT_BASE_URL),
+ )
+
+ # get_httpx_client() re-mints the bearer token when it is close to expiry,
+ # so fetch it per request rather than holding one reference.
+ http = client.get_httpx_client
+ claim_name = args.claim_name or f"claim-{uuid.uuid4().hex[:8]}"
+
+ service = args.service or first_template_service(http(), args.pool)
+
+ print(f"creating claim {claim_name} on pool {args.pool} (template {args.pool}-template)")
+ create_claim(http(), args.pool, claim_name)
+
+ try:
+ sandbox = wait_bound(http(), args.pool, claim_name, args.timeout)
+ # Per-sandbox K8s Services are named "<sandbox>-<service>" and exposed
+ # on port 80 by the operator; /api/svc proxies to them in-cluster.
+ svc_base = f"/api/svc/{args.pool}/{sandbox}-{service}"
+ url = f"{svc_base}/{args.path.lstrip('/')}"
+ print(f"bound to sandbox {sandbox}; GET {url}")
+
+ resp = wait_service_ready(http, url, args.ready_timeout)
+ print(f"HTTP {resp.status_code} {resp.headers.get('content-type', '')}")
+ body = resp.text
+ print(body[:2000] + ("…" if len(body) > 2000 else ""))
+
+ if args.mcp:
+ mcp_handshake(http, svc_base)
+ finally:
+ if args.keep:
+ print(f"keeping claim {claim_name} (release with: DELETE {claims_url(args.pool, claim_name)})")
+ else:
+ r = http().delete(claims_url(args.pool, claim_name))
+ print(f"released claim {claim_name} (HTTP {r.status_code})")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/libs/fleet/python-sdk/examples/create_pool_and_list_tools.py b/libs/fleet/python-sdk/examples/create_pool_and_list_tools.py
new file mode 100644
index 0000000000..614eed63b7
--- /dev/null
+++ b/libs/fleet/python-sdk/examples/create_pool_and_list_tools.py
@@ -0,0 +1,589 @@
+#!/usr/bin/env -S uv run --script
+# /// script
+# requires-python = ">=3.10"
+# dependencies = [
+# "cua-train",
+# "httpx",
+# ]
+#
+# [tool.uv]
+# extra-index-url = ["https://wheels.cua.ai/simple/"]
+# ///
+"""Create a warm sandbox pool on cyclops-cs / run.cua.ai, claim a sandbox from
+it, and list the cua-driver MCP tools it exposes — end to end, from nothing but
+a client id/secret.
+
+This is the "create it too" companion to ``claim_and_connect.py`` (which only
+claims from a pool that already exists). Here we drive the whole lifecycle and
+narrate every step so you can follow along in the console:
+
+ 1. exchange the client_credentials for a bearer token (``TrainClient.from_key``)
+ 2. create the per-user namespace (``POST /api/namespaces`` — same path the SPA
+ uses, so Capsule sets up tenant ownership + RBAC; pool name == namespace)
+ 3. create the two native CRs (``osgym.cua.ai/v1alpha1``) via the ``/api/k8s``
+ kubectl-proxy: an ``OSGymSandboxTemplate`` (``<pool>-template``) holding the
+ VM shape — image, size, and a service on the chosen port — and an
+ ``OSGymSandboxWarmPool`` (``<pool>``) that references it and warms
+ ``replicas`` VMs.
+ 4. claim a sandbox (``OSGymSandboxClaim``) and wait for it to bind
+ 5. reach the bound sandbox through ``/api/svc/{ns}/{sandbox}-{service}/`` and
+ run the cua-driver MCP handshake (initialize -> tools/list)
+
+Auth — use a per-USER key (``ukey-...``), NOT a per-pool key:
+``/api/k8s`` impersonates the token's owner so Capsule tenant RBAC applies.
+Per-user keys (POST /api/user-keys) act on behalf of their owner and can create
+namespaces, pools, and claims; per-pool keys (POST /api/keys, ``key-...``) have
+no K8s identity and are rejected on those steps.
+
+The default image is the Linux ``desktop-workspace`` — it serves the cua-driver
+computer-use MCP server over Streamable HTTP on :3000/mcp (with /healthz),
+and nothing else (no :5000 Flask server). So we set the pool's readiness probe
+to the MCP port: a warm sandbox is only advertised as "available" (and a claim
+only binds) once MCP is actually answering, which is exactly what we want
+before listing tools.
+
+Setup (zero-install with uv)::
+
+ export CUA_CLIENT_ID=ukey-xxxxxxxx # from POST /api/user-keys
+ export CUA_CLIENT_SECRET=...
+ uv run create_pool_and_list_tools.py --name my-pool
+
+…or pass credentials as flags, and/or pin everything explicitly::
+
+ uv run create_pool_and_list_tools.py \
+ --name my-pool \
+ --client-id ukey-xxxxxxxx --client-secret ... \
+ --image 296062593712.dkr.ecr.us-west-2.amazonaws.com/desktop-workspace:latest \
+ --port 3000
+
+If your uv is too old to read the inline extra-index-url, run it the explicit
+way (same as the other examples)::
+
+ uv run --with cua-train --with httpx \
+ --extra-index-url https://wheels.cua.ai/simple/ \
+ create_pool_and_list_tools.py --name my-pool
+
+The claim is released on exit (so the warm VM returns to the pool); the pool is
+kept — it is the thing you asked to create. Pass ``--keep-claim`` to hold the
+claim, or ``--delete-pool`` to tear the whole thing (warm pool + template +
+namespace) down.
+
+Env knobs: CUA_CLIENT_ID, CUA_CLIENT_SECRET, CUA_TOKEN_URL, CUA_BASE_URL.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import sys
+import time
+import uuid
+from collections.abc import Callable
+
+import httpx
+
+from cua_train import TrainClient
+
+DEFAULT_TOKEN_URL = "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token"
+DEFAULT_BASE_URL = "https://run.cua.ai"
+# NOTE: ':latest' is NOT reliably published for the Linux workspace repos — the
+# build workflow only tags 'latest' on pushes to main, and ECR lifecycle rules
+# expire old tags. A pool pointed at a missing tag never warms (the VM sits in
+# ImagePullBackOff). Pass --image with a tag you've confirmed exists, e.g.:
+# aws ecr describe-images --repository-name desktop-workspace --region us-west-2
+# (verified working at the time of writing: a desktop-workspace gym-seed tag
+# 'amazon-feature-gym-uv-seed-openshot-<sha>-base' — Linux, cua-driver MCP on :3000.)
+DEFAULT_IMAGE = "296062593712.dkr.ecr.us-west-2.amazonaws.com/desktop-workspace:latest"
+
+# A pool is two native CRs in the osgym.cua.ai group: an OSGymSandboxTemplate
+# (the VM shape, named "<pool>-template") and an OSGymSandboxWarmPool (named
+# "<pool>") that references it and keeps spec.replicas VMs warm. Claims
+# (OSGymSandboxClaim) reference the template by name.
+EXT_GROUP = "osgym.cua.ai"
+EXT_VERSION = "v1alpha1"
+TEMPLATE_PLURAL = "osgymsandboxtemplates"
+WARMPOOL_PLURAL = "osgymsandboxwarmpools"
+CLAIM_PLURAL = "osgymsandboxclaims"
+
+
+# ── URL builders (relative to base_url, e.g. https://run.cua.ai) ──────────
+
+
+def template_url(pool: str, name: str | None = None) -> str:
+ base = f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{TEMPLATE_PLURAL}"
+ return f"{base}/{name}" if name else base
+
+
+def warmpool_url(pool: str, name: str | None = None) -> str:
+ base = f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{WARMPOOL_PLURAL}"
+ return f"{base}/{name}" if name else base
+
+
+def claims_url(pool: str, name: str | None = None) -> str:
+ base = f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{CLAIM_PLURAL}"
+ return f"{base}/{name}" if name else base
+
+
+# ── Console helpers ───────────────────────────────────────────────────────
+
+
+def step(msg: str) -> None:
+ print(f"\n==> {msg}", flush=True)
+
+
+def info(msg: str) -> None:
+ print(f" {msg}", flush=True)
+
+
+def die(msg: str) -> None:
+ sys.exit(f"\nERROR: {msg}")
+
+
+# ── Lifecycle steps ───────────────────────────────────────────────────────
+
+
+def create_namespace(http: httpx.Client, name: str) -> None:
+ """Create the per-user namespace via the Capsule-backed SPA endpoint.
+
+ Pool name == namespace name (1:1). Going through /api/namespaces (rather
+ than a raw /api/k8s namespace create) is what makes Capsule stamp tenant
+ ownership + RBAC, so the impersonated pool create below is allowed. A 409
+ just means we are reusing a namespace from an earlier run.
+ """
+ r = http.post("/api/namespaces", json={"name": name})
+ if r.status_code == 409:
+ info(f"namespace {name!r} already exists — reusing it")
+ return
+ if r.status_code == 403:
+ die(
+ "403 creating namespace — is this a per-pool key? Namespaces/pools/"
+ "claims need a per-USER key (client id starting with 'ukey-', from "
+ "POST /api/user-keys)."
+ )
+ r.raise_for_status()
+ info(f"namespace {name!r} created")
+
+
+def create_template(
+ http: httpx.Client,
+ *,
+ pool: str,
+ image: str,
+ cpu: int,
+ ram: str,
+ firmware: str,
+ service_name: str,
+ port: int,
+ readiness_port: int,
+) -> None:
+ """Create the OSGymSandboxTemplate — the VM shape every sandbox in the pool
+ is stamped from, and what claims reference by name (``<pool>-template``)."""
+ vm_template: dict = {
+ "containerDiskImage": image,
+ "imagePullSecret": "ecr-credentials",
+ "cpuCores": cpu,
+ "memory": ram,
+ # Each entry becomes a per-sandbox K8s Service "<sandbox>-<name>"
+ # mapping port 80 -> targetPort on the VM.
+ "services": [
+ {"name": service_name, "targetPort": port, "protocol": "TCP"}
+ ],
+ }
+ # The SPA only sends firmware when it differs from KubeVirt's bios default.
+ if firmware != "bios":
+ vm_template["firmware"] = firmware
+ # Gate "Ready" (and therefore claim binding) on the in-guest service being
+ # bound — for desktop-workspace that's the MCP port. Without a probe the VM
+ # is advertised ready ~30s before the guest finishes booting (CUA-535).
+ # readiness_port == 0 disables the probe (KubeVirt's launcher-up default).
+ if readiness_port:
+ vm_template["probes"] = {"readinessProbe": {"tcpSocket": {"port": readiness_port}}}
+
+ tmpl = f"{pool}-template"
+ body = {
+ "apiVersion": f"{EXT_GROUP}/{EXT_VERSION}",
+ "kind": "OSGymSandboxTemplate",
+ "metadata": {"namespace": pool, "name": tmpl, "labels": {"cua.ai/pool": pool}},
+ "spec": {"vmTemplate": vm_template},
+ }
+
+ r = http.post(template_url(pool), json=body)
+ if r.status_code == 409:
+ info(f"template {tmpl!r} already exists — reusing it (VM shape unchanged)")
+ return
+ if r.status_code == 403:
+ die(
+ "403 creating template — per-pool keys cannot reach /api/k8s. Use a "
+ "per-USER key (client id starting with 'ukey-', from POST /api/user-keys)."
+ )
+ r.raise_for_status()
+ info(f"template {tmpl!r} created")
+ info(f"image: {image}")
+ info(f"size: {cpu} vCPU / {ram} / firmware={firmware}")
+ info(f"service: {service_name} -> targetPort {port} (reachable on Service port 80)")
+ info(f"readiness: {'tcpSocket :' + str(readiness_port) if readiness_port else 'launcher-up (no probe)'}")
+
+
+def create_warm_pool(http: httpx.Client, *, pool: str, replicas: int) -> None:
+ """Create the OSGymSandboxWarmPool that keeps ``replicas`` sandboxes warm
+ from ``<pool>-template``."""
+ body = {
+ "apiVersion": f"{EXT_GROUP}/{EXT_VERSION}",
+ "kind": "OSGymSandboxWarmPool",
+ "metadata": {"namespace": pool, "name": pool, "labels": {"cua.ai/pool": pool}},
+ "spec": {
+ "replicas": replicas,
+ "sandboxTemplateRef": {"name": f"{pool}-template"},
+ },
+ }
+
+ r = http.post(warmpool_url(pool), json=body)
+ if r.status_code == 409:
+ info(f"warm pool {pool!r} already exists — reusing it (replicas unchanged)")
+ return
+ if r.status_code == 403:
+ die(
+ "403 creating warm pool — per-pool keys cannot reach /api/k8s. Use a "
+ "per-USER key (client id starting with 'ukey-', from POST /api/user-keys)."
+ )
+ r.raise_for_status()
+ info(f"warm pool {pool!r} created (replicas={replicas} from {pool}-template)")
+
+
+def pool_counts(get_http: Callable[[], httpx.Client], pool: str) -> tuple[int, int]:
+ """(replicas, readyReplicas) from the warm pool status, best-effort."""
+ try:
+ r = get_http().get(warmpool_url(pool, pool))
+ r.raise_for_status()
+ st = r.json().get("status") or {}
+ return int(st.get("replicas", 0)), int(st.get("readyReplicas", 0))
+ except Exception:
+ return (0, 0)
+
+
+def wait_pool_warm(get_http: Callable[[], httpx.Client], pool: str, timeout: float, poll: float) -> None:
+ """Wait until the warm pool reports a ready VM.
+
+ This is the key to a reliable first claim: a brand-new pool has to pull the
+ (multi-GB) containerDisk image, boot the guest, and bring the in-guest
+ service up on the readiness port before a Sandbox becomes adoptable. That
+ cold start routinely exceeds the operator's 300s *claim* bind deadline
+ (claim_handlers.BIND_DEADLINE_DEFAULT_S). If we claim first, the deadline
+ burns down during the image pull and the claim Fails with
+ ``BindDeadlineExceeded`` — exactly the failure mode this avoids.
+
+ So we let the warm pool reach status.readyReplicas>=1 *before* claiming; the
+ subsequent claim then binds in seconds. Re-fetches the ``http`` accessor
+ each poll to keep the bearer token fresh over a long pull.
+ """
+ start = time.monotonic()
+ deadline = start + timeout
+ while True:
+ total, ready = pool_counts(get_http, pool)
+ if ready >= 1:
+ info(f"pool warm: {ready}/{total} VM(s) ready")
+ return
+ if time.monotonic() > deadline:
+ die(f"timed out after {timeout:.0f}s waiting for a warm VM "
+ f"({ready}/{total} ready).\n"
+ f" Most common cause: the --image tag does not exist in the registry, "
+ f"so the VM sits in ImagePullBackOff and never boots. Note that "
+ f"'desktop-workspace:latest' / 'osgym-workspace:latest' are typically "
+ f"NOT published — list real tags with:\n"
+ f" aws ecr describe-images --repository-name desktop-workspace --region us-west-2\n"
+ f" Less commonly the cold pull just needs longer — raise --warm-timeout.")
+ elapsed = int(time.monotonic() - start)
+ info(f"[{elapsed:4d}s] pool: {ready}/{total} VMs ready — warming "
+ f"(image pull + guest boot + service on the readiness port) …")
+ time.sleep(poll)
+
+
+def create_claim(http: httpx.Client, pool: str, name: str, bind_deadline: int = 0) -> None:
+ spec: dict = {"sandboxTemplateRef": {"name": f"{pool}-template"}}
+ # The pool-operator fails an unbound claim after spec.bindDeadline seconds
+ # (default 300, claim_handlers.BIND_DEADLINE_DEFAULT_S). We claim only after
+ # the pool is already warm, so binding is near-instant — but a non-zero
+ # deadline is a safety margin in case the warm VM is mid hard-reset.
+ if bind_deadline:
+ spec["bindDeadline"] = bind_deadline
+ r = http.post(
+ claims_url(pool),
+ json={
+ "apiVersion": f"{EXT_GROUP}/{EXT_VERSION}",
+ "kind": "OSGymSandboxClaim",
+ "metadata": {"name": name},
+ # Same convention the SPA uses: the pool's template is <pool>-template.
+ "spec": spec,
+ },
+ )
+ if r.status_code == 403:
+ die(
+ "403 creating claim — per-pool keys have no K8s identity. Use a "
+ "per-USER key (client id starting with 'ukey-', from POST /api/user-keys)."
+ )
+ r.raise_for_status()
+ info(f"claim {name!r} created")
+
+
+def wait_bound(get_http: Callable[[], httpx.Client], pool: str, name: str, timeout: float, poll: float) -> str:
+ """Poll the claim until status.phase == Bound; return the sandbox name.
+
+ While we wait we also surface the warm pool's ready counts, so a cold start
+ (image pull + guest boot + MCP coming up on the readiness port) is visible
+ rather than a silent hang. Re-fetches the ``http`` accessor each poll so the
+ bearer token stays fresh across a long (cold-boot) wait.
+ """
+ start = time.monotonic()
+ deadline = start + timeout
+ while True:
+ r = get_http().get(claims_url(pool, name))
+ r.raise_for_status()
+ status = r.json().get("status") or {}
+ phase = status.get("phase", "Pending")
+ sandbox = (status.get("sandbox") or {}).get("name")
+ if phase == "Bound" and sandbox:
+ return sandbox
+ if phase == "Failed":
+ die(f"claim {name} failed: {status}")
+ if time.monotonic() > deadline:
+ die(f"timed out after {timeout:.0f}s waiting for claim {name} to bind (phase={phase})")
+ total, ready = pool_counts(get_http, pool)
+ elapsed = int(time.monotonic() - start)
+ info(f"[{elapsed:4d}s] claim={phase} pool={ready}/{total} VMs ready …")
+ time.sleep(poll)
+
+
+def wait_service_ready(get_http: Callable[[], httpx.Client], url: str, timeout: float, poll: float) -> None:
+ """GET url until the in-guest service answers (not a proxy 502/503/504).
+
+ Backstop for the slim window where the sandbox is Bound but the in-guest
+ HTTP server hasn't finished accepting connections yet. Re-fetches the
+ ``http`` accessor each poll to keep the bearer token fresh.
+ """
+ start = time.monotonic()
+ deadline = start + timeout
+ while True:
+ try:
+ resp = get_http().get(url, timeout=15.0)
+ except httpx.HTTPError as e:
+ resp = None
+ reason = type(e).__name__
+ else:
+ reason = f"HTTP {resp.status_code}"
+ if resp is not None and resp.status_code not in (502, 503, 504):
+ info(f"service responding ({reason})")
+ return
+ if time.monotonic() > deadline:
+ die(f"timed out after {timeout:.0f}s waiting for the in-guest service (last: {reason})")
+ elapsed = int(time.monotonic() - start)
+ info(f"[{elapsed:4d}s] {reason} — guest still booting …")
+ time.sleep(poll)
+
+
+def list_mcp_tools(http: httpx.Client, base: str, mcp_path: str) -> None:
+ """cua-driver MCP handshake over Streamable HTTP:
+ initialize -> notifications/initialized -> tools/list, then print the tools."""
+ url = f"{base}/{mcp_path.lstrip('/')}"
+ headers = {
+ "Content-Type": "application/json",
+ # Streamable HTTP requires advertising both content types.
+ "Accept": "application/json, text/event-stream",
+ }
+
+ r = http.post(
+ url,
+ headers=headers,
+ timeout=30.0,
+ json={
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": "2025-03-26",
+ "capabilities": {},
+ "clientInfo": {"name": "create_pool_and_list_tools", "version": "0.1.0"},
+ },
+ },
+ )
+ r.raise_for_status()
+ session = r.headers.get("mcp-session-id")
+ info(f"MCP initialize: HTTP {r.status_code}" + (f", session {session}" if session else ""))
+ if session:
+ headers["Mcp-Session-Id"] = session
+
+ # Notify the server we're ready (no response expected).
+ http.post(
+ url,
+ headers=headers,
+ timeout=30.0,
+ json={"jsonrpc": "2.0", "method": "notifications/initialized"},
+ )
+
+ r = http.post(
+ url,
+ headers=headers,
+ timeout=30.0,
+ json={"jsonrpc": "2.0", "id": 2, "method": "tools/list"},
+ )
+ r.raise_for_status()
+ # Streamable HTTP returns SSE ("event: message\ndata: {...}"); the JSON
+ # payload is on the data: line. Fall back to the raw body for plain JSON.
+ data = next((ln[6:] for ln in r.text.splitlines() if ln.startswith("data: ")), r.text)
+ tools = json.loads(data).get("result", {}).get("tools", [])
+
+ print(f"\nMCP tools ({len(tools)}):", flush=True)
+ for i, t in enumerate(sorted(tools, key=lambda t: t.get("name", "")), 1):
+ name = t.get("name", "?")
+ desc = " ".join((t.get("description") or "").split())
+ if len(desc) > 70:
+ desc = desc[:67] + "…"
+ print(f" {i:3d}. {name:<24} {desc}", flush=True)
+ if not tools:
+ print(" (the server returned an empty tool list)", flush=True)
+
+
+def delete_pool(http: httpx.Client, pool: str) -> None:
+ """Delete both pool CRs (warm pool first, so it stops respawning sandboxes
+ from a template that is on its way out), then the namespace."""
+ r = http.delete(warmpool_url(pool, pool))
+ info(f"deleted warm pool {pool!r} (HTTP {r.status_code})")
+ r = http.delete(template_url(pool, f"{pool}-template"))
+ info(f"deleted template {pool}-template (HTTP {r.status_code})")
+ r = http.delete(f"/api/namespaces/{pool}")
+ info(f"deleted namespace {pool!r} (HTTP {r.status_code})")
+
+
+# ── Main ──────────────────────────────────────────────────────────────────
+
+
+def main() -> None:
+ p = argparse.ArgumentParser(
+ description="Create a pool on run.cua.ai, claim a sandbox, and list its MCP tools.",
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
+ )
+ p.add_argument("--name", required=True, help="pool name (also the namespace; lowercase/dashes)")
+ p.add_argument("--client-id", default=os.environ.get("CUA_CLIENT_ID"),
+ help="OAuth client id (per-user key 'ukey-…'); env CUA_CLIENT_ID")
+ p.add_argument("--client-secret", default=os.environ.get("CUA_CLIENT_SECRET"),
+ help="OAuth client secret; env CUA_CLIENT_SECRET")
+ p.add_argument("--image", default=DEFAULT_IMAGE, help="workspace containerDisk image")
+ p.add_argument("--port", type=int, default=3000, help="service target port on the VM (MCP)")
+ p.add_argument("--service-name", default="mcp", help="name for the per-sandbox Service")
+ p.add_argument("--mcp-path", default="/mcp", help="path the MCP server is mounted at")
+ p.add_argument("--replicas", type=int, default=1, help="pre-warmed VMs the pool keeps")
+ p.add_argument("--cpu", type=int, default=4, help="vCPU cores per VM")
+ p.add_argument("--ram", default="4Gi", help="memory per VM (K8s quantity)")
+ p.add_argument("--firmware", choices=["bios", "efi"], default="bios",
+ help="VM firmware (efi for GPT/UEFI-only images, e.g. Windows)")
+ p.add_argument("--readiness-port", type=int, default=None,
+ help="TCP readiness port (default: --port; 0 disables the probe)")
+ p.add_argument("--token-url", default=os.environ.get("CUA_TOKEN_URL", DEFAULT_TOKEN_URL),
+ help="OIDC token endpoint")
+ p.add_argument("--base-url", default=os.environ.get("CUA_BASE_URL", DEFAULT_BASE_URL),
+ help="cyclops-cs base URL")
+ p.add_argument("--claim-name", help="claim name (default: claim-<random>)")
+ p.add_argument("--warm-timeout", type=float, default=900,
+ help="seconds to wait for the pool's first warm VM before claiming "
+ "(covers the cold image pull + guest boot)")
+ p.add_argument("--bind-deadline", type=int, default=600,
+ help="claim spec.bindDeadline (operator fails an unbound claim after "
+ "this; 0 uses the operator default of 300s)")
+ p.add_argument("--bind-timeout", type=float, default=300,
+ help="seconds the script waits for the claim to bind (fast once warm)")
+ p.add_argument("--ready-timeout", type=float, default=420,
+ help="seconds to wait for the in-guest service after binding")
+ p.add_argument("--poll-interval", type=float, default=5,
+ help="seconds between status polls")
+ p.add_argument("--keep-claim", action="store_true",
+ help="keep the claim (and its VM) instead of releasing it on exit")
+ p.add_argument("--delete-pool", action="store_true",
+ help="tear down the warm pool, template AND namespace on exit (full cleanup)")
+ args = p.parse_args()
+
+ if not args.client_id or not args.client_secret:
+ die("set --client-id/--client-secret or CUA_CLIENT_ID/CUA_CLIENT_SECRET "
+ "(per-user key from POST /api/user-keys)")
+ if args.client_id.startswith("key-"):
+ die("that looks like a per-POOL key ('key-…'), which has no K8s identity. "
+ "Creating namespaces/pools/claims needs a per-USER key ('ukey-…', "
+ "from POST /api/user-keys).")
+
+ readiness_port = args.port if args.readiness_port is None else args.readiness_port
+ pool = args.name
+ claim_name = args.claim_name or f"claim-{uuid.uuid4().hex[:8]}"
+
+ step(f"Authenticating to {args.base_url} (client {args.client_id})")
+ client = TrainClient.from_key(
+ token_url=args.token_url,
+ client_id=args.client_id,
+ client_secret=args.client_secret,
+ base_url=args.base_url,
+ )
+ # get_httpx_client() re-mints the bearer token near expiry, so fetch it
+ # per request rather than holding one reference.
+ http = client.get_httpx_client
+ info("token acquired")
+
+ step(f"Creating namespace {pool!r}")
+ create_namespace(http(), pool)
+
+ step(f"Creating sandbox template {pool}-template")
+ create_template(
+ http(),
+ pool=pool,
+ image=args.image,
+ cpu=args.cpu,
+ ram=args.ram,
+ firmware=args.firmware,
+ service_name=args.service_name,
+ port=args.port,
+ readiness_port=readiness_port,
+ )
+
+ step(f"Creating warm pool {pool!r}")
+ create_warm_pool(http(), pool=pool, replicas=args.replicas)
+
+ step("Waiting for the pool's first VM to warm up (so the claim binds fast)")
+ info("(cold start = containerDisk image pull + guest boot + service on the readiness port)")
+ wait_pool_warm(http, pool, args.warm_timeout, args.poll_interval)
+
+ step(f"Claiming a sandbox from {pool!r} (claim {claim_name!r})")
+ create_claim(http(), pool, claim_name, args.bind_deadline)
+
+ try:
+ step("Waiting for the claim to bind to the warm sandbox")
+ sandbox = wait_bound(http, pool, claim_name, args.bind_timeout, args.poll_interval)
+ info(f"bound to sandbox {sandbox!r}")
+
+ # Per-sandbox Service is "<sandbox>-<service>" on port 80 -> targetPort.
+ svc_base = f"/api/svc/{pool}/{sandbox}-{args.service_name}"
+
+ step("Waiting for the in-guest MCP server to answer")
+ wait_service_ready(http, f"{svc_base}/healthz", args.ready_timeout, args.poll_interval)
+
+ step(f"Listing MCP tools at {svc_base}{args.mcp_path}")
+ list_mcp_tools(http(), svc_base, args.mcp_path)
+ finally:
+ print(flush=True)
+ if args.keep_claim:
+ step(f"Keeping claim {claim_name!r} (its VM stays out of the pool)")
+ info(f"release later with: DELETE {claims_url(pool, claim_name)}")
+ else:
+ step(f"Releasing claim {claim_name!r}")
+ r = http().delete(claims_url(pool, claim_name))
+ info(f"released (HTTP {r.status_code}) — the VM hard-resets and rejoins the pool")
+
+ if args.delete_pool:
+ step(f"Tearing down pool {pool!r}")
+ delete_pool(http(), pool)
+ else:
+ step(f"Pool {pool!r} is live")
+ info(f"claim more sandboxes: POST {claims_url(pool)} (spec.sandboxTemplateRef.name={pool}-template)")
+ info(f"delete it when done: DELETE {warmpool_url(pool, pool)}")
+ info(f" DELETE {template_url(pool, f'{pool}-template')}")
+ info(f" DELETE /api/namespaces/{pool}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/libs/fleet/python-sdk/examples/lanes_fan_out.py b/libs/fleet/python-sdk/examples/lanes_fan_out.py
new file mode 100644
index 0000000000..15b34b01f5
--- /dev/null
+++ b/libs/fleet/python-sdk/examples/lanes_fan_out.py
@@ -0,0 +1,134 @@
+#!/usr/bin/env python3
+"""Minimal uv run example: send two batches to the same lane VMs.
+
+Run:
+ uv run --with cua-train --extra-index-url https://wheels.cua.ai/simple/ \
+ lanes_fan_out.py \
+ --client-id key-xxxxxxxx \
+ --client-secret your-secret \
+ --pool test-pool-please-ignore
+"""
+
+from __future__ import annotations
+
+import argparse
+import random
+import time
+
+from cua_train import TrainClient
+from cua_train.models import (
+ AcquireLanesRequest,
+ Action,
+ ActionParameters,
+ BatchSubmitRequest,
+ ReleaseLanesRequest,
+ RunConfig,
+)
+
+
+def parse_args() -> argparse.Namespace:
+ parser = argparse.ArgumentParser(description="Submit two batches to the same lane VMs.")
+ parser.add_argument("--client-id", required=True, help="OAuth client id")
+ parser.add_argument("--client-secret", required=True, help="OAuth client secret")
+ parser.add_argument(
+ "--token-url",
+ default="https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token",
+ help="OIDC token endpoint",
+ )
+ parser.add_argument("--pool", default="test-pool-please-ignore", help="Target pool name")
+ parser.add_argument("--lanes", type=int, default=4, help="Number of lanes (VMs) to acquire")
+ parser.add_argument("--steps", type=int, default=5, help="Clicks per run")
+ parser.add_argument("--run-timeout", type=int, default=300, help="Run timeout seconds")
+ parser.add_argument("--poll-interval", type=float, default=2.0, help="Poll interval seconds")
+ return parser.parse_args()
+
+
+def random_click() -> Action:
+ return Action(
+ action_type="CLICK",
+ parameters=ActionParameters.from_dict(
+ {"x": random.randint(200, 1720), "y": random.randint(100, 980), "button": "left"}
+ ),
+ )
+
+
+def wait_for_label(client: TrainClient, pool: str, label: str, poll_interval: float) -> list:
+ res = client.get_label_results(pool=pool, label=label, completed_only=True)
+ while True:
+ runs = [r for b in res.batches for r in b.runs] if getattr(res, "batches", None) else []
+ if getattr(res, "all_completed", False) and runs:
+ return runs
+ time.sleep(poll_interval)
+ res = client.get_label_results(pool=pool, label=label, completed_only=True)
+
+
+def submit_and_wait(
+ client: TrainClient,
+ pool: str,
+ lanes: list[str],
+ label: str,
+ steps: int,
+ run_timeout: int,
+ poll_interval: float,
+) -> tuple[int, int]:
+ runs = [RunConfig(vm_id=vm_id, steps=[random_click() for _ in range(steps)], timeout=run_timeout) for vm_id in lanes]
+
+ client.submit_label_batch(
+ pool=pool,
+ label=label,
+ body=BatchSubmitRequest(
+ runs=runs,
+ concurrency=len(lanes),
+ ),
+ )
+ print(f"submitted {label} with {len(runs)} runs")
+
+ results = wait_for_label(client, pool, label, poll_interval)
+ ok = sum(1 for r in results if getattr(r, "ok", False))
+ return ok, len(results)
+
+
+def main() -> None:
+ args = parse_args()
+
+ client = TrainClient.from_key(
+ token_url=args.token_url,
+ client_id=args.client_id,
+ client_secret=args.client_secret,
+ )
+
+ lanes = client.acquire_lanes(pool=args.pool, body=AcquireLanesRequest(n=args.lanes)).vm_ids
+ print(f"acquired {len(lanes)} lanes")
+
+ try:
+ first_label = f"uv-example-{int(time.time())}-1"
+ first_ok, first_total = submit_and_wait(
+ client,
+ args.pool,
+ lanes,
+ first_label,
+ args.steps,
+ args.run_timeout,
+ args.poll_interval,
+ )
+ print(f"first batch completed: {first_ok}/{first_total} ok")
+
+ # Reuses the exact same vm_ids from the acquired lanes for a second interaction.
+ second_label = f"uv-example-{int(time.time())}-2"
+ second_ok, second_total = submit_and_wait(
+ client,
+ args.pool,
+ lanes,
+ second_label,
+ args.steps,
+ args.run_timeout,
+ args.poll_interval,
+ )
+ print(f"second batch completed: {second_ok}/{second_total} ok")
+ finally:
+ released = client.release_lanes(pool=args.pool, body=ReleaseLanesRequest(vm_ids=lanes)).released
+ print(f"released {released} lanes")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/libs/fleet/python-sdk/examples/linux-mini-swe.yaml b/libs/fleet/python-sdk/examples/linux-mini-swe.yaml
new file mode 100644
index 0000000000..b1dbf9bdec
--- /dev/null
+++ b/libs/fleet/python-sdk/examples/linux-mini-swe.yaml
@@ -0,0 +1,54 @@
+apiVersion: cua.ai/v1alpha1
+kind: AgentWindowsDoubleMCPRun
+metadata:
+ name: linux-mini-swe-demo
+
+spec:
+ pool:
+ image: 296062593712.dkr.ecr.us-west-2.amazonaws.com/desktop-workspace-duo:ci-publish-desktop-workspace-duo-main
+ cpu: 4
+ ram: 4Gi
+ firmware: bios # Linux workspace image boots on KubeVirt's default BIOS (efi is for the Windows image)
+ replicas: 2
+ minAvailable: 1
+ readinessPort: 8000
+ services:
+ - type: mcp
+ label: computer-server
+ service: server
+ port: 8000
+ mcpPath: /mcp
+ health: /status
+ - type: mcp
+ label: cua-driver
+ service: mcp
+ port: 3000
+ mcpPath: /mcp
+ health: /healthz
+ - type: auxiliary
+ label: novnc
+ service: novnc
+ port: 6080
+ claim:
+ bindDeadline: 600
+ agent:
+ model: us.anthropic.claude-sonnet-4-6
+ task: >-
+ install and launch firefox in this linux env, open
+ https://news.yahoo.com/, inspect the Yahoo News front page, and then
+ report the visible page contents in a concise final message. Do all work
+ inside this remote Windows sandbox, not on the local machine.
+ maxSteps: 60
+ keepImages: 2
+ rollout:
+ templateTimeout: 120
+ warmTimeout: 0
+ bindTimeout: 0
+ readyTimeout: 0
+ pollInterval: 10
+ teardown:
+ # keepPool:false so `--delete-pool` actually tears down (the script's
+ # if-keep/elif-delete precedence ignores --delete-pool when keepPool is
+ # true). With no teardown flags the pool is still left live for reuse.
+ keepPool: false
+ deletePool: false
diff --git a/libs/fleet/python-sdk/examples/live_demo.py b/libs/fleet/python-sdk/examples/live_demo.py
new file mode 100644
index 0000000000..417ca3cb2d
--- /dev/null
+++ b/libs/fleet/python-sdk/examples/live_demo.py
@@ -0,0 +1,460 @@
+#!/usr/bin/env python3
+"""Live demo — N lanes loop ``square -> triangle -> RESET`` forever, streamed to
+a local webserver (one live MJPEG per lane) with a metadata overlay.
+
+What it illustrates (cyclops-cs 0.2.0):
+ * explicit ``acquire_lanes`` / ``release_lanes``
+ * the SAME warm VM reused across batches — square (batch 1) then triangle
+ (batch 2) land on one desktop; the on-frame ``vm`` id stays the same
+ * in-band ``RESET`` (batch 3) hard-resets the VM — watch the ``vm`` id change
+ * the generic facade — every call is ``client.<op>(...)``, no ``.sync``
+
+Each frame carries a banner (lane, iteration, phase, step, vm id); while a batch
+is being provisioned/run you get a loading screen with an elapsed timer.
+
+Setup::
+
+ pip install cua-train --extra-index-url https://wheels.cua.ai/simple/
+ pip install pillow boto3
+ export CUA_CLIENT_ID=key-xxxxxxxx # from POST /api/keys
+ export CUA_CLIENT_SECRET=...
+ python live_demo.py # then open http://127.0.0.1:8000
+
+Run-batch screenshots come back as S3 keys, so frames are pulled from the
+results bucket (needs AWS read access). Ctrl-C releases the lanes.
+
+Env knobs: CUA_POOL, CUA_LANES (default 4), CUA_DEMO_PORT (8000),
+CUA_TOKEN_URL, CUA_RESULTS_BUCKET. Set CUA_DEMO_SELFTEST=1 to serve
+loading/placeholder frames without touching the backend (preview the UI).
+"""
+
+from __future__ import annotations
+
+import io
+import os
+import threading
+import time
+import uuid
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+import boto3
+from PIL import Image, ImageDraw, ImageFont
+
+from cua_train import TrainClient
+from cua_train.models import (
+ AcquireLanesRequest,
+ Action,
+ ActionParameters,
+ BatchSubmitRequest,
+ ErrorResponse,
+ ReleaseLanesRequest,
+ RunConfig,
+)
+
+POOL = os.environ.get("CUA_POOL", "test-pool-please-ignore")
+TOKEN_URL = os.environ.get(
+ "CUA_TOKEN_URL",
+ "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token",
+)
+RESULTS_BUCKET = os.environ.get("CUA_RESULTS_BUCKET", "cua-osgym-batch-results")
+N_LANES = int(os.environ.get("CUA_LANES", "4"))
+PORT = int(os.environ.get("CUA_DEMO_PORT", "8000"))
+SELFTEST = os.environ.get("CUA_DEMO_SELFTEST") == "1"
+
+W, H = 1920, 1080
+SCALE = 960 / W
+SW, SH = round(W * SCALE), round(H * SCALE)
+ANIM_DT = 0.06 # loading-frame redraw + stream push interval (~16 fps)
+RED, BLUE, ORANGE, GREY, INK = (255, 90, 90), (90, 150, 255), (255, 165, 50), (120, 120, 120), (190, 205, 230)
+
+SQUARE = [(480, 270), (1440, 270), (1440, 810), (480, 810), (480, 270)]
+TRIANGLE = [(960, 170), (1440, 880), (480, 880), (960, 170)]
+
+
+def _font(size):
+ try:
+ return ImageFont.load_default(size=size)
+ except TypeError: # lint-ignore: swallowed-exception — old Pillow without size=
+ return ImageFont.load_default()
+
+
+FONT, FONT_SM, FONT_BIG = _font(22), _font(16), _font(34)
+
+
+def _clicks(points):
+ return [
+ Action(action_type="CLICK", parameters=ActionParameters.from_dict({"x": x, "y": y, "button": "left"}))
+ for x, y in points
+ ]
+
+
+def _short(vm):
+ return vm.rsplit("-", 1)[-1][:8] if vm else "?"
+
+
+# ── shared latest-frame buffers (one JPEG per lane) ────────────────────────────
+_frames: list[bytes | None] = [None] * N_LANES
+# Each lane's current VM id (changes on RESET); tracked so shutdown releases the
+# live VMs rather than the now-stale ones returned by acquire_lanes.
+_cur_vms: list[str | None] = [None] * N_LANES
+_lock = threading.Lock()
+
+
+def set_frame(i, jpeg):
+ with _lock:
+ _frames[i] = jpeg
+
+
+def get_frame(i):
+ with _lock:
+ return _frames[i]
+
+
+def _jpeg(im):
+ buf = io.BytesIO()
+ im.convert("RGB").save(buf, "JPEG", quality=80)
+ return buf.getvalue()
+
+
+def banner(im, lines, accent):
+ """Top metadata strip: line 0 in the accent colour, the rest dimmed."""
+ d = ImageDraw.Draw(im, "RGBA")
+ d.rectangle([0, 0, im.width, 12 + 28 * len(lines)], fill=(0, 0, 0, 170))
+ y = 8
+ for i, ln in enumerate(lines):
+ d.text((12, y), ln, fill=tuple(accent) if i == 0 else (235, 235, 235), font=FONT if i == 0 else FONT_SM)
+ y += 28
+
+
+CYAN, MINT = (90, 165, 255), (110, 210, 160)
+
+
+def loading_frame(head, secs, status="waiting for VM…", sub="", accent=CYAN):
+ """A status screen with a spinner + elapsed timer. `status`/`accent`
+ distinguish the wait: acquiring a fresh VM vs. a batch running / waiting
+ for its results."""
+ im = Image.new("RGB", (SW, SH), (15, 17, 22))
+ d = ImageDraw.Draw(im)
+ cx, cy, r = SW // 2, SH // 2, 40
+ d.ellipse([cx - r, cy - r, cx + r, cy + r], outline=(40, 46, 58), width=6) # track
+ a = (secs * 220) % 360 # rotating head
+ d.arc([cx - r, cy - r, cx + r, cy + r], a, a + 110, fill=accent, width=6)
+ d.text((cx, cy + r + 36), f"{status} {secs:0.1f}s", fill=INK, font=FONT, anchor="mm")
+ banner(im, [head, sub], accent)
+ return _jpeg(im)
+
+
+def path_frame(base, head, sub, accent, path, upto, prior=None):
+ """A real screenshot with the click path traced + metadata banner."""
+ im = base.resize((SW, SH)).convert("RGB")
+ d = ImageDraw.Draw(im)
+ if prior: # earlier shape on this same VM, faded
+ d.line([(x * SCALE, y * SCALE) for x, y in prior], fill=GREY, width=3)
+ pts = [(x * SCALE, y * SCALE) for x, y in path[: upto + 1]]
+ if len(pts) >= 2:
+ d.line(pts, fill=accent, width=4)
+ for sx, sy in pts:
+ d.ellipse([sx - 7, sy - 7, sx + 7, sy + 7], fill=accent)
+ banner(im, [head, sub], accent)
+ return _jpeg(im)
+
+
+def reset_frame(base, head, sub):
+ im = base.resize((SW, SH)).convert("RGB")
+ banner(im, [head, sub], ORANGE)
+ return _jpeg(im)
+
+
+# ── backend helpers ────────────────────────────────────────────────────────────
+def make_client():
+ return TrainClient.from_key(
+ token_url=TOKEN_URL,
+ client_id=os.environ["CUA_CLIENT_ID"],
+ client_secret=os.environ["CUA_CLIENT_SECRET"],
+ )
+
+
+def wait_run(client, label, stop, idx, head, timeout=300):
+ """Poll for the run; meanwhile paint a loading screen with a live timer.
+ Raises on ErrorResponse (e.g. 401) so the caller can refresh the client."""
+ t0 = time.time()
+ last_poll = 0.0
+ while not stop.is_set():
+ # Redraw the spinner every frame (smooth); the VM already exists, so
+ # this is "running / waiting for results", not "waiting for a VM".
+ set_frame(
+ idx,
+ loading_frame(
+ head,
+ time.time() - t0,
+ status="running — waiting for results…",
+ sub="executing steps on the VM",
+ accent=MINT,
+ ),
+ )
+ if time.time() - last_poll >= 2:
+ last_poll = time.time()
+ try:
+ res = client.get_label_results(pool=POOL, label=label, completed_only=True)
+ except Exception as e: # transient network blip — keep waiting
+ print(f"[lane {idx}] poll {label}: {e!r}", flush=True)
+ else:
+ if isinstance(res, ErrorResponse):
+ raise RuntimeError(f"results error: {res}")
+ runs = [r for b in res.batches for r in b.runs] if getattr(res, "batches", None) else []
+ if getattr(res, "all_completed", False) and runs:
+ return runs[0]
+ if time.time() - t0 > timeout:
+ return None
+ stop.wait(ANIM_DT)
+ return None
+
+
+def run_batch(client, idx, vm, steps, stop, head):
+ label = f"demo-{idx}-{uuid.uuid4().hex[:6]}"
+ resp = client.submit_label_batch(
+ pool=POOL,
+ label=label,
+ body=BatchSubmitRequest(runs=[RunConfig(vm_id=vm, steps=steps, timeout=300)], concurrency=1, keep_warm=True),
+ )
+ if isinstance(resp, ErrorResponse):
+ raise RuntimeError(f"submit error: {resp}")
+ return wait_run(client, label, stop, idx, head)
+
+
+def play(idx, run, s3, stop, frame_fn):
+ """Stream a run's screenshots (S3 keys) into the lane buffer, one per step."""
+ shots = run.screenshots or []
+ for j, k in enumerate(shots):
+ if stop.is_set():
+ return
+ if not k:
+ continue
+ raw = s3.get_object(Bucket=RESULTS_BUCKET, Key=k)["Body"].read()
+ set_frame(idx, frame_fn(Image.open(io.BytesIO(raw)), j, len(shots)))
+ stop.wait(0.45)
+
+
+# ── per-lane worker: loop square (b1) → triangle (b2) → RESET (b3), forever ─────
+def lane_worker(idx, vm0, stop):
+ s3 = boto3.client("s3")
+ client = make_client() # TrainClient refreshes its token transparently
+ cur, it = vm0, 0
+ _cur_vms[idx] = vm0
+ while not stop.is_set():
+ try:
+ it += 1
+
+ # batch 1 — square on the current warm VM
+ r = run_batch(client, idx, cur, _clicks(SQUARE), stop, f"LANE {idx} · iter {it} · SQUARE (batch 1)")
+ if r is None:
+ continue
+ cur = r.vm_id
+ _cur_vms[idx] = cur
+ play(
+ idx,
+ r,
+ s3,
+ stop,
+ lambda im, j, n: path_frame(
+ im, f"LANE {idx} iter {it} SQUARE {j + 1}/{n}", f"batch 1 · vm …{_short(cur)}", RED, SQUARE, j
+ ),
+ )
+
+ # batch 2 — triangle on the SAME VM (reuse across batches)
+ r = run_batch(client, idx, cur, _clicks(TRIANGLE), stop, f"LANE {idx} · iter {it} · TRIANGLE (batch 2)")
+ if r is None:
+ continue
+ cur = r.vm_id
+ _cur_vms[idx] = cur
+ play(
+ idx,
+ r,
+ s3,
+ stop,
+ lambda im, j, n: path_frame(
+ im,
+ f"LANE {idx} iter {it} TRIANGLE {j + 1}/{n}",
+ f"batch 2 · vm …{_short(cur)} (same VM, reused)",
+ BLUE,
+ TRIANGLE,
+ j,
+ prior=SQUARE,
+ ),
+ )
+
+ # batch 3 — in-band RESET: hard reset → new VM
+ old = cur
+ r = run_batch(
+ client, idx, cur, [Action(action_type="RESET")], stop, f"LANE {idx} · iter {it} · RESET (batch 3)"
+ )
+ if r is None:
+ continue
+ cur = r.vm_id
+ _cur_vms[idx] = cur
+ play(
+ idx,
+ r,
+ s3,
+ stop,
+ lambda im, j, n: reset_frame(
+ im, "RESET — hard reset", f"vm …{_short(old)} → …{_short(cur)} (new VM, same lane {idx})"
+ ),
+ )
+ except Exception as e: # transient network blip — log and retry the iteration
+ print(f"[lane {idx}] iter {it} error: {e!r}; retrying", flush=True)
+ stop.wait(2)
+
+
+# ── webserver: one MJPEG stream per lane ───────────────────────────────────────
+class Handler(BaseHTTPRequestHandler):
+ def log_message(self, *_):
+ pass
+
+ def do_GET(self):
+ if self.path == "/":
+ self._page()
+ elif self.path.startswith("/lane/"):
+ try:
+ idx = int(self.path.split("/")[2])
+ except (IndexError, ValueError): # lint-ignore: swallowed-exception — bad /lane path, handled as 404
+ self.send_error(404)
+ return
+ self._stream(idx)
+ else:
+ self.send_error(404)
+
+ def _page(self):
+ cards = "".join(
+ f'<figure><figcaption>lane {i}</figcaption><img src="/lane/{i}"></figure>' for i in range(N_LANES)
+ )
+ body = f"""<!doctype html><html><head><meta charset=utf-8>
+<title>cyclops-cs — square / triangle / reset loop</title>
+<style>body{{background:#111;color:#eee;font-family:system-ui;margin:0;padding:24px;text-align:center}}
+.grid{{display:flex;flex-wrap:wrap;gap:18px;justify-content:center}}
+figure{{margin:0}} img{{width:46vw;border:1px solid #333;border-radius:8px}}
+figcaption{{margin:6px;color:#9cf}} .legend{{max-width:1000px;margin:8px auto 0;color:#bbb;line-height:1.5}}
+b{{color:#eee}}</style></head>
+<body><h2>cyclops-cs 0.2.0 — {N_LANES} lanes looping square → triangle → reset</h2>
+<p class=legend>Each tile is one <b>lane</b> = a persistent VM. Per loop it runs three batches on
+the <b>same warm VM</b>: <span style="color:#ff5a5a">square</span> (batch 1) →
+<span style="color:#5a96ff">triangle</span> (batch 2, <b>VM reused</b>) →
+<span style="color:#ffa532">RESET</span> (batch 3, <b>new VM</b> — watch the <code>vm</code> id change).
+Then it repeats.</p>
+<div class=grid>{cards}</div></body></html>""".encode()
+ self.send_response(200)
+ self.send_header("Content-Type", "text/html; charset=utf-8")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def _stream(self, idx):
+ self.send_response(200)
+ self.send_header("Content-Type", "multipart/x-mixed-replace; boundary=frame")
+ self.send_header("Cache-Control", "no-cache")
+ self.end_headers()
+ try:
+ while True:
+ frame = get_frame(idx) or loading_frame("starting…", 0.0)
+ self.wfile.write(b"--frame\r\nContent-Type: image/jpeg\r\n")
+ self.wfile.write(f"Content-Length: {len(frame)}\r\n\r\n".encode())
+ self.wfile.write(frame)
+ self.wfile.write(b"\r\n")
+ time.sleep(ANIM_DT)
+ except (BrokenPipeError, ConnectionResetError): # lint-ignore: swallowed-exception — viewer closed stream
+ pass
+
+
+def _acquire_with_timer(client, stop_anim):
+ """Acquire N lanes while painting a loading+timer screen on every tile."""
+ t0 = time.time()
+ box = {}
+
+ def anim():
+ while not stop_anim.is_set():
+ for i in range(N_LANES):
+ set_frame(
+ i,
+ loading_frame(
+ f"LANE {i} · acquiring",
+ time.time() - t0,
+ status="waiting for VM…",
+ sub="acquire_lanes — provisioning a warm VM from the pool",
+ ),
+ )
+ time.sleep(ANIM_DT)
+
+ t = threading.Thread(target=anim, daemon=True)
+ t.start()
+ try:
+ # The pool may not have N warm VMs yet (503 / ErrorResponse). Keep the
+ # "waiting for VM…" screen up and retry instead of crashing.
+ while not stop_anim.is_set():
+ res = client.acquire_lanes(pool=POOL, body=AcquireLanesRequest(n=N_LANES))
+ if isinstance(res, ErrorResponse):
+ print(f"acquire_lanes: {res}; retrying…", flush=True)
+ time.sleep(3)
+ continue
+ box["lanes"] = res.vm_ids
+ break
+ finally:
+ stop_anim.set()
+ t.join(timeout=2)
+ return box["lanes"]
+
+
+def main():
+ for i in range(N_LANES):
+ set_frame(i, loading_frame("starting…", 0.0))
+
+ server = ThreadingHTTPServer(("127.0.0.1", PORT), Handler)
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ print(f"streaming on http://127.0.0.1:{PORT} ({N_LANES} lanes)")
+
+ if SELFTEST:
+ print("SELFTEST: serving loading frames, no backend. Ctrl-C to stop.")
+ t0 = time.time()
+ try:
+ while True:
+ for i in range(N_LANES):
+ state = (
+ ("running — waiting for results…", "executing steps on the VM", MINT)
+ if (int(t0) + i) % 2
+ else ("waiting for VM…", "acquire_lanes — provisioning a warm VM", CYAN)
+ )
+ set_frame(
+ i,
+ loading_frame(
+ f"LANE {i} · selftest", time.time() - t0, status=state[0], sub=state[1], accent=state[2]
+ ),
+ )
+ time.sleep(ANIM_DT)
+ except KeyboardInterrupt: # lint-ignore: swallowed-exception — Ctrl-C stops selftest
+ return
+
+ client = make_client()
+ print(f"acquire_lanes(n={N_LANES}) …")
+ lanes = _acquire_with_timer(client, threading.Event())
+
+ stop = threading.Event()
+ workers = [threading.Thread(target=lane_worker, args=(i, lanes[i], stop), daemon=True) for i in range(N_LANES)]
+ for w in workers:
+ w.start()
+ try:
+ while any(w.is_alive() for w in workers):
+ time.sleep(1)
+ except KeyboardInterrupt: # lint-ignore: swallowed-exception — Ctrl-C, releases in finally
+ print("\nstopping …")
+ finally:
+ stop.set()
+ for w in workers:
+ w.join(timeout=10)
+ # Release the VMs the lanes currently hold (RESET changes the id each
+ # iteration), plus the originals, so nothing leaks back to the pool.
+ to_release = sorted({*lanes, *(v for v in _cur_vms if v)})
+ client.release_lanes(pool=POOL, body=ReleaseLanesRequest(vm_ids=to_release))
+ print(f"released {len(to_release)} VMs; bye.")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/libs/fleet/python-sdk/examples/provision_windows_and_drive_with_cua_sdk.py b/libs/fleet/python-sdk/examples/provision_windows_and_drive_with_cua_sdk.py
new file mode 100644
index 0000000000..02cdd4d519
--- /dev/null
+++ b/libs/fleet/python-sdk/examples/provision_windows_and_drive_with_cua_sdk.py
@@ -0,0 +1,572 @@
+#!/usr/bin/env -S uv run --script
+# /// script
+# requires-python = ">=3.12,<3.14"
+# dependencies = [
+# "cua-train",
+# "httpx",
+# # Direct-proxy support (api_base_url / api_headers) shipped in cua-computer
+# # 0.5.19 — https://github.com/trycua/cua/pull/1932
+# "cua-computer>=0.5.19",
+# ]
+#
+# [tool.uv]
+# extra-index-url = ["https://wheels.cua.ai/simple/"]
+# ///
+"""Provision a **Windows computer-server** pool on cyclops-cs / run.cua.ai, claim
+a sandbox, then drive it with the real ``cua-computer`` SDK (screenshot, screen
+size, a shell command) — and tear the whole thing back down afterward.
+
+This is the SDK companion to ``provision_windows_and_list_mcp_tools.py`` (which
+claims the same kind of sandbox but only lists its MCP tools). Both target the
+Windows ``cua-server-windows`` image, which runs ``python -m computer_server`` on
+:8000.
+
+Connecting directly through the proxy (no forwarder)
+----------------------------------------------------
+cyclops-cs exposes a sandbox only through an authenticated reverse proxy at
+``{base_url}/api/svc/{ns}/{sandbox}-{service}/...`` that wants an
+``Authorization: Bearer <token>`` header. The ``cua-computer`` SDK now supports
+pointing at exactly that kind of endpoint via two params (added in
+https://github.com/trycua/cua/pull/1932):
+
+ Computer(
+ use_host_computer_server=True,
+ os_type="windows",
+ api_base_url="https://run.cua.ai/api/svc/<ns>/<sandbox>-api",
+ api_headers={"Authorization": "Bearer <token>"},
+ )
+
+The SDK derives its REST/WebSocket URIs from ``api_base_url`` (keeping the path
+prefix) and sends ``api_headers`` on every request — so it talks to the proxy
+directly. No localhost forwarder, no subprocess.
+
+> The bearer is short-lived, so we mint a fresh one right before connecting. For
+> a long-running session you'd refresh it yourself (the proxy re-checks it per
+> request); this example's actions finish in seconds.
+
+Two modes
+---------
+* default — connect the SDK, take a screenshot + screen size + run a command,
+ print the results, then tear down.
+* ``--print-connection`` — print the ``api_base_url`` + a fresh bearer + a
+ ready-to-paste ``Computer(...)`` snippet and hold the sandbox open so you can
+ drive it from another process / your own agent. Ctrl-C tears it down.
+
+Lifecycle is otherwise identical to the MCP example: create namespace → sandbox
+template (Windows image, **efi firmware**, service on :8000) → warm pool → wait
+warm → claim → wait bound → wait ``/status`` → [drive | print] → **teardown**
+(claim + warm pool + template + namespace; this is a throwaway test scenario).
+Pass ``--keep`` to leave it up.
+
+Auth — use a per-USER key (``ukey-...``, from POST /api/user-keys), not a
+per-pool key. Windows is slow to first-boot; the defaults wait generously.
+
+Setup (zero-install with uv)::
+
+ export CUA_CLIENT_ID=ukey-xxxxxxxx
+ export CUA_CLIENT_SECRET=...
+ uv run provision_windows_and_drive_with_cua_sdk.py --name win-api-demo
+ uv run provision_windows_and_drive_with_cua_sdk.py --name win-fwd-demo --print-connection
+
+Env knobs: CUA_CLIENT_ID, CUA_CLIENT_SECRET, CUA_TOKEN_URL, CUA_BASE_URL.
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import os
+import sys
+import time
+import uuid
+from collections.abc import Callable
+
+import httpx
+
+from cua_train import TrainClient
+
+DEFAULT_TOKEN_URL = "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token"
+DEFAULT_BASE_URL = "https://run.cua.ai"
+# The Windows computer-server image: Windows Server 2022 + cua-computer-server on
+# :8000. It is a dockur-built GPT/UEFI image, so the pool MUST boot it with efi
+# firmware (see --firmware below).
+DEFAULT_IMAGE = "296062593712.dkr.ecr.us-west-2.amazonaws.com/cua-server-windows:latest"
+
+# A pool is two native CRs in the osgym.cua.ai group: an OSGymSandboxTemplate
+# (the VM shape, named "<pool>-template") and an OSGymSandboxWarmPool (named
+# "<pool>") that references it and keeps spec.replicas VMs warm. Claims
+# (OSGymSandboxClaim) reference the template by name.
+EXT_GROUP = "osgym.cua.ai"
+EXT_VERSION = "v1alpha1"
+TEMPLATE_PLURAL = "osgymsandboxtemplates"
+WARMPOOL_PLURAL = "osgymsandboxwarmpools"
+CLAIM_PLURAL = "osgymsandboxclaims"
+
+
+# ── URL builders (relative to base_url, e.g. https://run.cua.ai) ──────────
+
+
+def template_url(pool: str, name: str | None = None) -> str:
+ base = f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{TEMPLATE_PLURAL}"
+ return f"{base}/{name}" if name else base
+
+
+def warmpool_url(pool: str, name: str | None = None) -> str:
+ base = f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{WARMPOOL_PLURAL}"
+ return f"{base}/{name}" if name else base
+
+
+def claims_url(pool: str, name: str | None = None) -> str:
+ base = f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{CLAIM_PLURAL}"
+ return f"{base}/{name}" if name else base
+
+
+# ── Console helpers ───────────────────────────────────────────────────────
+
+
+def step(msg: str) -> None:
+ print(f"\n==> {msg}", flush=True)
+
+
+def info(msg: str) -> None:
+ print(f" {msg}", flush=True)
+
+
+def die(msg: str) -> None:
+ sys.exit(f"\nERROR: {msg}")
+
+
+# ── Lifecycle steps (identical to provision_windows_and_list_mcp_tools.py) ──
+
+
+def create_namespace(http: httpx.Client, name: str) -> None:
+ """Create the per-user namespace via the Capsule-backed SPA endpoint.
+
+ Pool name == namespace name (1:1). A 409 just means we are reusing a
+ namespace from an earlier run.
+ """
+ r = http.post("/api/namespaces", json={"name": name})
+ if r.status_code == 409:
+ info(f"namespace {name!r} already exists — reusing it")
+ return
+ if r.status_code == 403:
+ die(
+ "403 creating namespace — is this a per-pool key? Namespaces/pools/"
+ "claims need a per-USER key (client id starting with 'ukey-', from "
+ "POST /api/user-keys)."
+ )
+ r.raise_for_status()
+ info(f"namespace {name!r} created")
+
+
+def create_template(
+ http: httpx.Client,
+ *,
+ pool: str,
+ image: str,
+ cpu: int,
+ ram: str,
+ firmware: str,
+ service_name: str,
+ port: int,
+ readiness_port: int,
+) -> None:
+ """Create the OSGymSandboxTemplate — the VM shape every sandbox in the pool
+ is stamped from, and what claims reference by name (``<pool>-template``)."""
+ vm_template: dict = {
+ "containerDiskImage": image,
+ "imagePullSecret": "ecr-credentials",
+ "cpuCores": cpu,
+ "memory": ram,
+ "services": [
+ {"name": service_name, "targetPort": port, "protocol": "TCP"}
+ ],
+ }
+ # Windows needs efi: the VM builder then auto-applies the Hyper-V
+ # enlightenments + Windows-tuned clocks (vm_builders.vm_body, firmware=="efi").
+ if firmware != "bios":
+ vm_template["firmware"] = firmware
+ # Gate "Ready" (and claim binding) on the computer-server port being bound —
+ # without a probe the VM is advertised ready before the guest finishes
+ # booting (CUA-535). readiness_port == 0 disables the probe.
+ if readiness_port:
+ vm_template["probes"] = {"readinessProbe": {"tcpSocket": {"port": readiness_port}}}
+
+ tmpl = f"{pool}-template"
+ body = {
+ "apiVersion": f"{EXT_GROUP}/{EXT_VERSION}",
+ "kind": "OSGymSandboxTemplate",
+ "metadata": {"namespace": pool, "name": tmpl, "labels": {"cua.ai/pool": pool}},
+ "spec": {"vmTemplate": vm_template},
+ }
+
+ r = http.post(template_url(pool), json=body)
+ if r.status_code == 409:
+ info(f"template {tmpl!r} already exists — reusing it (VM shape unchanged)")
+ return
+ if r.status_code == 403:
+ die(
+ "403 creating template — per-pool keys cannot reach /api/k8s. Use a "
+ "per-USER key (client id starting with 'ukey-', from POST /api/user-keys)."
+ )
+ r.raise_for_status()
+ info(f"template {tmpl!r} created")
+ info(f"image: {image}")
+ info(f"size: {cpu} vCPU / {ram} / firmware={firmware}")
+ info(f"service: {service_name} -> targetPort {port} (reachable on Service port 80)")
+ info(f"readiness: {'tcpSocket :' + str(readiness_port) if readiness_port else 'launcher-up (no probe)'}")
+
+
+def create_warm_pool(http: httpx.Client, *, pool: str, replicas: int) -> None:
+ """Create the OSGymSandboxWarmPool that keeps ``replicas`` sandboxes warm
+ from ``<pool>-template``."""
+ body = {
+ "apiVersion": f"{EXT_GROUP}/{EXT_VERSION}",
+ "kind": "OSGymSandboxWarmPool",
+ "metadata": {"namespace": pool, "name": pool, "labels": {"cua.ai/pool": pool}},
+ "spec": {
+ "replicas": replicas,
+ "sandboxTemplateRef": {"name": f"{pool}-template"},
+ },
+ }
+
+ r = http.post(warmpool_url(pool), json=body)
+ if r.status_code == 409:
+ info(f"warm pool {pool!r} already exists — reusing it (replicas unchanged)")
+ return
+ if r.status_code == 403:
+ die(
+ "403 creating warm pool — per-pool keys cannot reach /api/k8s. Use a "
+ "per-USER key (client id starting with 'ukey-', from POST /api/user-keys)."
+ )
+ r.raise_for_status()
+ info(f"warm pool {pool!r} created (replicas={replicas} from {pool}-template)")
+
+
+def pool_counts(get_http: Callable[[], httpx.Client], pool: str) -> tuple[int, int]:
+ """(replicas, readyReplicas) from the warm pool status, best-effort."""
+ try:
+ r = get_http().get(warmpool_url(pool, pool))
+ r.raise_for_status()
+ st = r.json().get("status") or {}
+ return int(st.get("replicas", 0)), int(st.get("readyReplicas", 0))
+ except Exception:
+ return (0, 0)
+
+
+def wait_pool_warm(get_http: Callable[[], httpx.Client], pool: str, timeout: float, poll: float) -> None:
+ """Wait until the warm pool reports a ready VM before claiming.
+
+ A brand-new Windows pool's cold start (UEFI image pull + Windows Server boot
+ + the computer-server scheduled task) is *minutes* and routinely exceeds the
+ operator's 300s claim bind deadline. Letting status.readyReplicas>=1 first
+ means the subsequent claim binds in seconds. Re-fetches the ``http``
+ accessor each poll to keep the bearer token fresh over a long pull.
+ """
+ start = time.monotonic()
+ deadline = start + timeout
+ while True:
+ total, ready = pool_counts(get_http, pool)
+ if ready >= 1:
+ info(f"pool warm: {ready}/{total} VM(s) ready")
+ return
+ if time.monotonic() > deadline:
+ die(f"timed out after {timeout:.0f}s waiting for a warm VM "
+ f"({ready}/{total} ready).\n"
+ f" Most common cause: the --image tag does not exist in the registry, "
+ f"so the VM sits in ImagePullBackOff and never boots. List real tags with:\n"
+ f" aws ecr describe-images --repository-name cua-server-windows --region us-west-2\n"
+ f" Less commonly the cold Windows boot just needs longer — raise --warm-timeout.")
+ elapsed = int(time.monotonic() - start)
+ info(f"[{elapsed:4d}s] pool: {ready}/{total} VMs ready — warming "
+ f"(image pull + Windows boot + computer-server on the readiness port) …")
+ time.sleep(poll)
+
+
+def create_claim(http: httpx.Client, pool: str, name: str, bind_deadline: int = 0) -> None:
+ spec: dict = {"sandboxTemplateRef": {"name": f"{pool}-template"}}
+ if bind_deadline:
+ spec["bindDeadline"] = bind_deadline
+ r = http.post(
+ claims_url(pool),
+ json={
+ "apiVersion": f"{EXT_GROUP}/{EXT_VERSION}",
+ "kind": "OSGymSandboxClaim",
+ "metadata": {"name": name},
+ "spec": spec,
+ },
+ )
+ if r.status_code == 403:
+ die(
+ "403 creating claim — per-pool keys have no K8s identity. Use a "
+ "per-USER key (client id starting with 'ukey-', from POST /api/user-keys)."
+ )
+ r.raise_for_status()
+ info(f"claim {name!r} created")
+
+
+def wait_bound(get_http: Callable[[], httpx.Client], pool: str, name: str, timeout: float, poll: float) -> str:
+ """Poll the claim until status.phase == Bound; return the sandbox name."""
+ start = time.monotonic()
+ deadline = start + timeout
+ while True:
+ r = get_http().get(claims_url(pool, name))
+ r.raise_for_status()
+ status = r.json().get("status") or {}
+ phase = status.get("phase", "Pending")
+ sandbox = (status.get("sandbox") or {}).get("name")
+ if phase == "Bound" and sandbox:
+ return sandbox
+ if phase == "Failed":
+ die(f"claim {name} failed: {status}")
+ if time.monotonic() > deadline:
+ die(f"timed out after {timeout:.0f}s waiting for claim {name} to bind (phase={phase})")
+ total, ready = pool_counts(get_http, pool)
+ elapsed = int(time.monotonic() - start)
+ info(f"[{elapsed:4d}s] claim={phase} pool={ready}/{total} VMs ready …")
+ time.sleep(poll)
+
+
+def wait_service_ready(get_http: Callable[[], httpx.Client], url: str, timeout: float, poll: float) -> None:
+ """GET url until the in-guest service answers (not a proxy 502/503/504).
+
+ For computer-server that endpoint is ``/status``.
+ """
+ start = time.monotonic()
+ deadline = start + timeout
+ while True:
+ try:
+ resp = get_http().get(url, timeout=15.0)
+ except httpx.HTTPError as e:
+ resp = None
+ reason = type(e).__name__
+ else:
+ reason = f"HTTP {resp.status_code}"
+ if resp is not None and resp.status_code not in (502, 503, 504):
+ info(f"service responding ({reason})")
+ return
+ if time.monotonic() > deadline:
+ die(f"timed out after {timeout:.0f}s waiting for the in-guest service (last: {reason})")
+ elapsed = int(time.monotonic() - start)
+ info(f"[{elapsed:4d}s] {reason} — guest still booting …")
+ time.sleep(poll)
+
+
+def teardown(get_http: Callable[[], httpx.Client], pool: str, claim_name: str) -> None:
+ """Best-effort full cleanup: delete the claim, both pool CRs (warm pool
+ before template), then the namespace.
+
+ Idempotent — a 404 just means something was already gone.
+ """
+ for what, url in (
+ (f"claim {claim_name!r}", claims_url(pool, claim_name)),
+ (f"warm pool {pool!r}", warmpool_url(pool, pool)),
+ (f"template {pool}-template", template_url(pool, f"{pool}-template")),
+ (f"namespace {pool!r}", f"/api/namespaces/{pool}"),
+ ):
+ try:
+ r = get_http().delete(url)
+ info(f"deleted {what} (HTTP {r.status_code})")
+ except httpx.HTTPError as e:
+ info(f"could not delete {what}: {type(e).__name__}: {e}")
+
+
+def bearer(client: TrainClient) -> str:
+ """Mint/refresh and return the current bearer token value."""
+ client.get_httpx_client() # forces TrainClient._refresh_token()
+ return f"Bearer {client.token}"
+
+
+# ── Drive the box with the cua-computer SDK (directly through the proxy) ─────
+
+
+async def drive_with_sdk(api_base_url: str, auth: str, sandbox: str) -> None:
+ """Connect the cua-computer SDK straight at the cyclops-cs proxy and do a few
+ things — no forwarder (uses api_base_url + api_headers from cua#1932)."""
+ # Imported lazily so --help and arg errors don't pay the cua-computer import.
+ from computer import Computer
+
+ step(f"Connecting the cua-computer SDK directly to {api_base_url}")
+ computer = Computer(
+ use_host_computer_server=True, # connect to an existing server, do not spawn a VM
+ os_type="windows",
+ api_base_url=api_base_url,
+ api_headers={"Authorization": auth},
+ )
+ async with computer: # __aenter__ -> run() -> wait_for_ready (REST 'version' then get_screen_size)
+ size = await computer.interface.get_screen_size()
+ info(f"screen size: {size['width']}x{size['height']}")
+
+ png = await computer.interface.screenshot()
+ out = f"{sandbox}-screenshot.png"
+ with open(out, "wb") as f:
+ f.write(png)
+ info(f"screenshot: wrote {len(png)} bytes to {out}")
+
+ res = await computer.interface.run_command("echo hello-from-cua")
+ info(f"run_command rc={res.returncode} stdout={res.stdout.strip()!r}")
+
+ info("SDK actions complete")
+
+
+async def print_connection(api_base_url: str, auth: str) -> None:
+ """Print connection details and hold the sandbox open until Ctrl-C."""
+ step("Sandbox is live — point any cua-computer client straight at the proxy")
+ info(f"api_base_url: {api_base_url}")
+ info("paste into your own script / agent (the bearer below is short-lived):")
+ print(
+ "\n"
+ " from computer import Computer\n"
+ " computer = Computer(\n"
+ " use_host_computer_server=True,\n"
+ ' os_type="windows",\n'
+ f' api_base_url="{api_base_url}",\n'
+ f' api_headers={{"Authorization": "{auth}"}},\n'
+ " )\n"
+ " async with computer:\n"
+ " await computer.interface.screenshot()\n",
+ flush=True,
+ )
+ info("Ctrl-C to stop and tear everything down.")
+ await asyncio.Event().wait() # block; KeyboardInterrupt propagates to main's finally
+
+
+# ── Main ──────────────────────────────────────────────────────────────────
+
+
+async def amain() -> None:
+ p = argparse.ArgumentParser(
+ description="Provision a Windows computer-server pool on run.cua.ai, claim a sandbox, "
+ "drive it with the cua-computer SDK (directly through the proxy), then tear it down.",
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
+ )
+ p.add_argument("--name", required=True, help="pool name (also the namespace; lowercase/dashes)")
+ p.add_argument("--client-id", default=os.environ.get("CUA_CLIENT_ID"),
+ help="OAuth client id (per-user key 'ukey-…'); env CUA_CLIENT_ID")
+ p.add_argument("--client-secret", default=os.environ.get("CUA_CLIENT_SECRET"),
+ help="OAuth client secret; env CUA_CLIENT_SECRET")
+ p.add_argument("--image", default=DEFAULT_IMAGE, help="Windows workspace containerDisk image")
+ p.add_argument("--port", type=int, default=8000, help="computer-server port on the VM")
+ p.add_argument("--service-name", default="api", help="name for the per-sandbox Service")
+ p.add_argument("--replicas", type=int, default=1, help="pre-warmed VMs the pool keeps")
+ p.add_argument("--cpu", type=int, default=4, help="vCPU cores per VM")
+ p.add_argument("--ram", default="8Gi", help="memory per VM (K8s quantity; Windows wants >=8Gi)")
+ p.add_argument("--firmware", choices=["bios", "efi"], default="efi",
+ help="VM firmware (efi for the GPT/UEFI-only Windows image)")
+ p.add_argument("--readiness-port", type=int, default=None,
+ help="TCP readiness port (default: --port; 0 disables the probe)")
+ p.add_argument("--token-url", default=os.environ.get("CUA_TOKEN_URL", DEFAULT_TOKEN_URL),
+ help="OIDC token endpoint")
+ p.add_argument("--base-url", default=os.environ.get("CUA_BASE_URL", DEFAULT_BASE_URL),
+ help="cyclops-cs base URL")
+ p.add_argument("--claim-name", help="claim name (default: claim-<random>)")
+ p.add_argument("--warm-timeout", type=float, default=1200,
+ help="seconds to wait for the pool's first warm VM before claiming "
+ "(covers the cold image pull + slow Windows boot)")
+ p.add_argument("--bind-deadline", type=int, default=600,
+ help="claim spec.bindDeadline (0 uses the operator default of 300s)")
+ p.add_argument("--bind-timeout", type=float, default=300,
+ help="seconds the script waits for the claim to bind (fast once warm)")
+ p.add_argument("--ready-timeout", type=float, default=420,
+ help="seconds to wait for the in-guest service after binding")
+ p.add_argument("--poll-interval", type=float, default=5,
+ help="seconds between status polls")
+ p.add_argument("--print-connection", action="store_true",
+ help="instead of driving the SDK, print the api_base_url + a fresh bearer "
+ "+ a Computer(...) snippet and hold the sandbox open (Ctrl-C to tear down)")
+ p.add_argument("--keep", action="store_true",
+ help="skip teardown — leave the pool, namespace, and claim up for debugging")
+ args = p.parse_args()
+
+ if not args.client_id or not args.client_secret:
+ die("set --client-id/--client-secret or CUA_CLIENT_ID/CUA_CLIENT_SECRET "
+ "(per-user key from POST /api/user-keys)")
+ if args.client_id.startswith("key-"):
+ die("that looks like a per-POOL key ('key-…'), which has no K8s identity. "
+ "Creating namespaces/pools/claims needs a per-USER key ('ukey-…', "
+ "from POST /api/user-keys).")
+
+ readiness_port = args.port if args.readiness_port is None else args.readiness_port
+ pool = args.name
+ claim_name = args.claim_name or f"claim-{uuid.uuid4().hex[:8]}"
+
+ step(f"Authenticating to {args.base_url} (client {args.client_id})")
+ client = TrainClient.from_key(
+ token_url=args.token_url,
+ client_id=args.client_id,
+ client_secret=args.client_secret,
+ base_url=args.base_url,
+ )
+ http = client.get_httpx_client # callable: re-mints the bearer near expiry
+ info("token acquired")
+
+ step(f"Creating namespace {pool!r}")
+ create_namespace(http(), pool)
+
+ step(f"Creating sandbox template {pool}-template")
+ create_template(
+ http(),
+ pool=pool,
+ image=args.image,
+ cpu=args.cpu,
+ ram=args.ram,
+ firmware=args.firmware,
+ service_name=args.service_name,
+ port=args.port,
+ readiness_port=readiness_port,
+ )
+
+ step(f"Creating warm pool {pool!r}")
+ create_warm_pool(http(), pool=pool, replicas=args.replicas)
+
+ step("Waiting for the pool's first VM to warm up (so the claim binds fast)")
+ info("(cold start = containerDisk image pull + Windows boot + computer-server on the readiness port)")
+ wait_pool_warm(http, pool, args.warm_timeout, args.poll_interval)
+
+ step(f"Claiming a sandbox from {pool!r} (claim {claim_name!r})")
+ create_claim(http(), pool, claim_name, args.bind_deadline)
+
+ try:
+ step("Waiting for the claim to bind to the warm sandbox")
+ sandbox = wait_bound(http, pool, claim_name, args.bind_timeout, args.poll_interval)
+ info(f"bound to sandbox {sandbox!r}")
+
+ # Per-sandbox Service is "<sandbox>-<service>" on port 80 -> targetPort.
+ svc_path = f"/api/svc/{pool}/{sandbox}-{args.service_name}"
+
+ step("Waiting for the in-guest computer-server to answer")
+ wait_service_ready(http, f"{svc_path}/status", args.ready_timeout, args.poll_interval)
+
+ # Full https URL of the proxied computer-server + a fresh short-lived bearer.
+ api_base_url = f"{args.base_url}{svc_path}"
+ auth = bearer(client)
+
+ if args.print_connection:
+ await print_connection(api_base_url, auth)
+ else:
+ await drive_with_sdk(api_base_url, auth, sandbox)
+ except KeyboardInterrupt:
+ info("interrupted — tearing down")
+ finally:
+ print(flush=True)
+ if args.keep:
+ step(f"Keeping infra ({pool!r}) — skipping teardown (--keep)")
+ info(f"claim: {claims_url(pool, claim_name)}")
+ info(f"warm pool: {warmpool_url(pool, pool)}")
+ info(f"template: {template_url(pool, f'{pool}-template')}")
+ info(f"namespace: /api/namespaces/{pool}")
+ else:
+ step(f"Tearing down {pool!r} (claim + warm pool + template + namespace)")
+ teardown(http, pool, claim_name)
+ info("done — nothing left billing")
+
+
+def main() -> None:
+ try:
+ asyncio.run(amain())
+ except KeyboardInterrupt:
+ pass
+
+
+if __name__ == "__main__":
+ main()
diff --git a/libs/fleet/python-sdk/examples/provision_windows_and_list_mcp_tools.py b/libs/fleet/python-sdk/examples/provision_windows_and_list_mcp_tools.py
new file mode 100644
index 0000000000..7372efae36
--- /dev/null
+++ b/libs/fleet/python-sdk/examples/provision_windows_and_list_mcp_tools.py
@@ -0,0 +1,582 @@
+#!/usr/bin/env -S uv run --script
+# /// script
+# requires-python = ">=3.10"
+# dependencies = [
+# "cua-train",
+# "httpx",
+# ]
+#
+# [tool.uv]
+# extra-index-url = ["https://wheels.cua.ai/simple/"]
+# ///
+"""Provision a **Windows computer-server** pool on cyclops-cs / run.cua.ai, claim
+a sandbox from it, list the MCP tools it exposes — then tear the whole thing back
+down. End to end, from nothing but a client id/secret.
+
+This is the MCP companion to ``provision_windows_and_drive_with_cua_sdk.py``
+(which claims the same kind of sandbox but drives it with the ``cua-computer``
+SDK instead). Both target the Windows ``cua-server-windows`` image, which runs
+``python -m computer_server`` on :8000 and exposes, on that one port:
+
+ * the HTTP/WebSocket computer-use API (``/cmd``, ``/ws``, ``/status``)
+ * an MCP server over Streamable HTTP at ``/mcp``
+
+Here we only do the MCP side: the Streamable-HTTP handshake
+(``initialize`` → ``notifications/initialized`` → ``tools/list``) and print the
+advertised tools.
+
+Lifecycle (every step is narrated so you can follow along in the console):
+
+ 1. exchange the client_credentials for a bearer token (``TrainClient.from_key``)
+ 2. create the per-user namespace (``POST /api/namespaces`` — same path the SPA
+ uses, so Capsule sets up tenant ownership + RBAC; pool name == namespace)
+ 3. create the two native CRs (``osgym.cua.ai/v1alpha1``) via the ``/api/k8s``
+ kubectl-proxy: an ``OSGymSandboxTemplate`` (``<pool>-template``) with the
+ Windows image, **efi firmware**, and a service on :8000, plus an
+ ``OSGymSandboxWarmPool`` (``<pool>``) referencing it that warms the VM.
+ 4. claim a sandbox (``OSGymSandboxClaim``) and wait for it to bind
+ 5. reach the bound sandbox through ``/api/svc/{ns}/{sandbox}-{service}/`` and
+ run the computer-server MCP handshake (initialize -> tools/list)
+ 6. **tear it all down** — delete the claim, both pool CRs, and the namespace.
+ This is a throwaway test scenario, so nothing is left billing. Pass
+ ``--keep`` to leave the pool up for poking at.
+
+Auth — use a per-USER key (``ukey-...``), NOT a per-pool key:
+``/api/k8s`` impersonates the token's owner so Capsule tenant RBAC applies.
+Per-user keys (POST /api/user-keys) can create namespaces, pools, and claims;
+per-pool keys (POST /api/keys, ``key-...``) have no K8s identity and are rejected.
+
+Heads up: Windows is **slow to first-boot** (UEFI image pull + Windows Server
+boot + computer-server scheduled task coming up). The defaults wait generously;
+raise ``--warm-timeout`` if your pull is cold.
+
+Setup (zero-install with uv)::
+
+ export CUA_CLIENT_ID=ukey-xxxxxxxx # from POST /api/user-keys
+ export CUA_CLIENT_SECRET=...
+ uv run provision_windows_and_list_mcp_tools.py --name win-mcp-demo
+
+If your uv is too old to read the inline extra-index-url, run it the explicit
+way::
+
+ uv run --with cua-train --with httpx \
+ --extra-index-url https://wheels.cua.ai/simple/ \
+ provision_windows_and_list_mcp_tools.py --name win-mcp-demo
+
+Env knobs: CUA_CLIENT_ID, CUA_CLIENT_SECRET, CUA_TOKEN_URL, CUA_BASE_URL.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import sys
+import time
+import uuid
+from collections.abc import Callable
+
+import httpx
+
+from cua_train import TrainClient
+
+DEFAULT_TOKEN_URL = "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token"
+DEFAULT_BASE_URL = "https://run.cua.ai"
+# The Windows computer-server image: Windows Server 2022 + cua-computer-server on
+# :8000 (HTTP/WS API at /cmd//ws, MCP at /mcp). It is a dockur-built GPT/UEFI
+# image, so the pool MUST boot it with efi firmware (see --firmware below).
+DEFAULT_IMAGE = "296062593712.dkr.ecr.us-west-2.amazonaws.com/cua-server-windows:latest"
+
+# A pool is two native CRs in the osgym.cua.ai group: an OSGymSandboxTemplate
+# (the VM shape, named "<pool>-template") and an OSGymSandboxWarmPool (named
+# "<pool>") that references it and keeps spec.replicas VMs warm. Claims
+# (OSGymSandboxClaim) reference the template by name.
+EXT_GROUP = "osgym.cua.ai"
+EXT_VERSION = "v1alpha1"
+TEMPLATE_PLURAL = "osgymsandboxtemplates"
+WARMPOOL_PLURAL = "osgymsandboxwarmpools"
+CLAIM_PLURAL = "osgymsandboxclaims"
+
+
+# ── URL builders (relative to base_url, e.g. https://run.cua.ai) ──────────
+
+
+def template_url(pool: str, name: str | None = None) -> str:
+ base = f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{TEMPLATE_PLURAL}"
+ return f"{base}/{name}" if name else base
+
+
+def warmpool_url(pool: str, name: str | None = None) -> str:
+ base = f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{WARMPOOL_PLURAL}"
+ return f"{base}/{name}" if name else base
+
+
+def claims_url(pool: str, name: str | None = None) -> str:
+ base = f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{CLAIM_PLURAL}"
+ return f"{base}/{name}" if name else base
+
+
+# ── Console helpers ───────────────────────────────────────────────────────
+
+
+def step(msg: str) -> None:
+ print(f"\n==> {msg}", flush=True)
+
+
+def info(msg: str) -> None:
+ print(f" {msg}", flush=True)
+
+
+def die(msg: str) -> None:
+ sys.exit(f"\nERROR: {msg}")
+
+
+# ── Lifecycle steps ───────────────────────────────────────────────────────
+
+
+def create_namespace(http: httpx.Client, name: str) -> None:
+ """Create the per-user namespace via the Capsule-backed SPA endpoint.
+
+ Pool name == namespace name (1:1). Going through /api/namespaces (rather
+ than a raw /api/k8s namespace create) is what makes Capsule stamp tenant
+ ownership + RBAC, so the impersonated pool create below is allowed. A 409
+ just means we are reusing a namespace from an earlier run.
+ """
+ r = http.post("/api/namespaces", json={"name": name})
+ if r.status_code == 409:
+ info(f"namespace {name!r} already exists — reusing it")
+ return
+ if r.status_code == 403:
+ die(
+ "403 creating namespace — is this a per-pool key? Namespaces/pools/"
+ "claims need a per-USER key (client id starting with 'ukey-', from "
+ "POST /api/user-keys)."
+ )
+ r.raise_for_status()
+ info(f"namespace {name!r} created")
+
+
+def create_template(
+ http: httpx.Client,
+ *,
+ pool: str,
+ image: str,
+ cpu: int,
+ ram: str,
+ firmware: str,
+ service_name: str,
+ port: int,
+ readiness_port: int,
+) -> None:
+ """Create the OSGymSandboxTemplate — the VM shape every sandbox in the pool
+ is stamped from, and what claims reference by name (``<pool>-template``)."""
+ vm_template: dict = {
+ "containerDiskImage": image,
+ "imagePullSecret": "ecr-credentials",
+ "cpuCores": cpu,
+ "memory": ram,
+ # Each entry becomes a per-sandbox K8s Service "<sandbox>-<name>"
+ # mapping port 80 -> targetPort on the VM.
+ "services": [
+ {"name": service_name, "targetPort": port, "protocol": "TCP"}
+ ],
+ }
+ # The SPA only sends firmware when it differs from KubeVirt's bios default.
+ # Windows needs efi: the VM builder then auto-applies the Hyper-V
+ # enlightenments + Windows-tuned clocks (vm_builders.vm_body, firmware=="efi").
+ if firmware != "bios":
+ vm_template["firmware"] = firmware
+ # Gate "Ready" (and therefore claim binding) on the computer-server port
+ # being bound. Without a probe the VM is advertised ready ~30s before the
+ # guest finishes booting (CUA-535) — doubly important for slow Windows boots.
+ # readiness_port == 0 disables the probe (KubeVirt's launcher-up default).
+ if readiness_port:
+ vm_template["probes"] = {"readinessProbe": {"tcpSocket": {"port": readiness_port}}}
+
+ tmpl = f"{pool}-template"
+ body = {
+ "apiVersion": f"{EXT_GROUP}/{EXT_VERSION}",
+ "kind": "OSGymSandboxTemplate",
+ "metadata": {"namespace": pool, "name": tmpl, "labels": {"cua.ai/pool": pool}},
+ "spec": {"vmTemplate": vm_template},
+ }
+
+ r = http.post(template_url(pool), json=body)
+ if r.status_code == 409:
+ info(f"template {tmpl!r} already exists — reusing it (VM shape unchanged)")
+ return
+ if r.status_code == 403:
+ die(
+ "403 creating template — per-pool keys cannot reach /api/k8s. Use a "
+ "per-USER key (client id starting with 'ukey-', from POST /api/user-keys)."
+ )
+ r.raise_for_status()
+ info(f"template {tmpl!r} created")
+ info(f"image: {image}")
+ info(f"size: {cpu} vCPU / {ram} / firmware={firmware}")
+ info(f"service: {service_name} -> targetPort {port} (reachable on Service port 80)")
+ info(f"readiness: {'tcpSocket :' + str(readiness_port) if readiness_port else 'launcher-up (no probe)'}")
+
+
+def create_warm_pool(http: httpx.Client, *, pool: str, replicas: int) -> None:
+ """Create the OSGymSandboxWarmPool that keeps ``replicas`` sandboxes warm
+ from ``<pool>-template``."""
+ body = {
+ "apiVersion": f"{EXT_GROUP}/{EXT_VERSION}",
+ "kind": "OSGymSandboxWarmPool",
+ "metadata": {"namespace": pool, "name": pool, "labels": {"cua.ai/pool": pool}},
+ "spec": {
+ "replicas": replicas,
+ "sandboxTemplateRef": {"name": f"{pool}-template"},
+ },
+ }
+
+ r = http.post(warmpool_url(pool), json=body)
+ if r.status_code == 409:
+ info(f"warm pool {pool!r} already exists — reusing it (replicas unchanged)")
+ return
+ if r.status_code == 403:
+ die(
+ "403 creating warm pool — per-pool keys cannot reach /api/k8s. Use a "
+ "per-USER key (client id starting with 'ukey-', from POST /api/user-keys)."
+ )
+ r.raise_for_status()
+ info(f"warm pool {pool!r} created (replicas={replicas} from {pool}-template)")
+
+
+def pool_counts(get_http: Callable[[], httpx.Client], pool: str) -> tuple[int, int]:
+ """(replicas, readyReplicas) from the warm pool status, best-effort."""
+ try:
+ r = get_http().get(warmpool_url(pool, pool))
+ r.raise_for_status()
+ st = r.json().get("status") or {}
+ return int(st.get("replicas", 0)), int(st.get("readyReplicas", 0))
+ except Exception:
+ return (0, 0)
+
+
+def wait_pool_warm(get_http: Callable[[], httpx.Client], pool: str, timeout: float, poll: float) -> None:
+ """Wait until the warm pool reports a ready VM.
+
+ This is the key to a reliable first claim: a brand-new pool has to pull the
+ (multi-GB) containerDisk image, boot the guest, and bring the in-guest
+ service up on the readiness port before a Sandbox becomes adoptable. For the
+ Windows image that cold start is *minutes* (UEFI image pull + Windows Server
+ boot + the computer-server scheduled task), and routinely exceeds the
+ operator's 300s *claim* bind deadline (claim_handlers.BIND_DEADLINE_DEFAULT_S).
+ If we claim first, the deadline burns down during the image pull and the
+ claim Fails with ``BindDeadlineExceeded`` — exactly the failure mode this
+ avoids.
+
+ So we let the warm pool reach status.readyReplicas>=1 *before* claiming; the
+ subsequent claim then binds in seconds. Re-fetches the ``http`` accessor
+ each poll to keep the bearer token fresh over a long pull.
+ """
+ start = time.monotonic()
+ deadline = start + timeout
+ while True:
+ total, ready = pool_counts(get_http, pool)
+ if ready >= 1:
+ info(f"pool warm: {ready}/{total} VM(s) ready")
+ return
+ if time.monotonic() > deadline:
+ die(f"timed out after {timeout:.0f}s waiting for a warm VM "
+ f"({ready}/{total} ready).\n"
+ f" Most common cause: the --image tag does not exist in the registry, "
+ f"so the VM sits in ImagePullBackOff and never boots. List real tags with:\n"
+ f" aws ecr describe-images --repository-name cua-server-windows --region us-west-2\n"
+ f" Less commonly the cold Windows boot just needs longer — raise --warm-timeout.")
+ elapsed = int(time.monotonic() - start)
+ info(f"[{elapsed:4d}s] pool: {ready}/{total} VMs ready — warming "
+ f"(image pull + Windows boot + computer-server on the readiness port) …")
+ time.sleep(poll)
+
+
+def create_claim(http: httpx.Client, pool: str, name: str, bind_deadline: int = 0) -> None:
+ spec: dict = {"sandboxTemplateRef": {"name": f"{pool}-template"}}
+ # The pool-operator fails an unbound claim after spec.bindDeadline seconds
+ # (default 300, claim_handlers.BIND_DEADLINE_DEFAULT_S). We claim only after
+ # the pool is already warm, so binding is near-instant — but a non-zero
+ # deadline is a safety margin in case the warm VM is mid hard-reset.
+ if bind_deadline:
+ spec["bindDeadline"] = bind_deadline
+ r = http.post(
+ claims_url(pool),
+ json={
+ "apiVersion": f"{EXT_GROUP}/{EXT_VERSION}",
+ "kind": "OSGymSandboxClaim",
+ "metadata": {"name": name},
+ "spec": spec,
+ },
+ )
+ if r.status_code == 403:
+ die(
+ "403 creating claim — per-pool keys have no K8s identity. Use a "
+ "per-USER key (client id starting with 'ukey-', from POST /api/user-keys)."
+ )
+ r.raise_for_status()
+ info(f"claim {name!r} created")
+
+
+def wait_bound(get_http: Callable[[], httpx.Client], pool: str, name: str, timeout: float, poll: float) -> str:
+ """Poll the claim until status.phase == Bound; return the sandbox name.
+
+ While we wait we also surface the warm pool's ready counts, so a cold start
+ is visible rather than a silent hang. Re-fetches the ``http`` accessor each
+ poll so the bearer token stays fresh across a long (cold-boot) wait.
+ """
+ start = time.monotonic()
+ deadline = start + timeout
+ while True:
+ r = get_http().get(claims_url(pool, name))
+ r.raise_for_status()
+ status = r.json().get("status") or {}
+ phase = status.get("phase", "Pending")
+ sandbox = (status.get("sandbox") or {}).get("name")
+ if phase == "Bound" and sandbox:
+ return sandbox
+ if phase == "Failed":
+ die(f"claim {name} failed: {status}")
+ if time.monotonic() > deadline:
+ die(f"timed out after {timeout:.0f}s waiting for claim {name} to bind (phase={phase})")
+ total, ready = pool_counts(get_http, pool)
+ elapsed = int(time.monotonic() - start)
+ info(f"[{elapsed:4d}s] claim={phase} pool={ready}/{total} VMs ready …")
+ time.sleep(poll)
+
+
+def wait_service_ready(get_http: Callable[[], httpx.Client], url: str, timeout: float, poll: float) -> None:
+ """GET url until the in-guest service answers (not a proxy 502/503/504).
+
+ Backstop for the slim window where the sandbox is Bound but the in-guest
+ HTTP server hasn't finished accepting connections yet. For computer-server
+ that endpoint is ``/status``. Re-fetches the ``http`` accessor each poll to
+ keep the bearer token fresh.
+ """
+ start = time.monotonic()
+ deadline = start + timeout
+ while True:
+ try:
+ resp = get_http().get(url, timeout=15.0)
+ except httpx.HTTPError as e:
+ resp = None
+ reason = type(e).__name__
+ else:
+ reason = f"HTTP {resp.status_code}"
+ if resp is not None and resp.status_code not in (502, 503, 504):
+ info(f"service responding ({reason})")
+ return
+ if time.monotonic() > deadline:
+ die(f"timed out after {timeout:.0f}s waiting for the in-guest service (last: {reason})")
+ elapsed = int(time.monotonic() - start)
+ info(f"[{elapsed:4d}s] {reason} — guest still booting …")
+ time.sleep(poll)
+
+
+def list_mcp_tools(http: httpx.Client, base: str, mcp_path: str) -> None:
+ """computer-server MCP handshake over Streamable HTTP:
+ initialize -> notifications/initialized -> tools/list, then print the tools."""
+ url = f"{base}/{mcp_path.lstrip('/')}"
+ headers = {
+ "Content-Type": "application/json",
+ # Streamable HTTP requires advertising both content types.
+ "Accept": "application/json, text/event-stream",
+ }
+
+ r = http.post(
+ url,
+ headers=headers,
+ timeout=30.0,
+ json={
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": "2025-03-26",
+ "capabilities": {},
+ "clientInfo": {"name": "provision_windows_and_list_mcp_tools", "version": "0.1.0"},
+ },
+ },
+ )
+ r.raise_for_status()
+ session = r.headers.get("mcp-session-id")
+ info(f"MCP initialize: HTTP {r.status_code}" + (f", session {session}" if session else ""))
+ if session:
+ headers["Mcp-Session-Id"] = session
+
+ # Notify the server we're ready (no response expected).
+ http.post(
+ url,
+ headers=headers,
+ timeout=30.0,
+ json={"jsonrpc": "2.0", "method": "notifications/initialized"},
+ )
+
+ r = http.post(
+ url,
+ headers=headers,
+ timeout=30.0,
+ json={"jsonrpc": "2.0", "id": 2, "method": "tools/list"},
+ )
+ r.raise_for_status()
+ # Streamable HTTP returns SSE ("event: message\ndata: {...}"); the JSON
+ # payload is on the data: line. Fall back to the raw body for plain JSON.
+ data = next((ln[6:] for ln in r.text.splitlines() if ln.startswith("data: ")), r.text)
+ tools = json.loads(data).get("result", {}).get("tools", [])
+
+ print(f"\nMCP tools ({len(tools)}):", flush=True)
+ for i, t in enumerate(sorted(tools, key=lambda t: t.get("name", "")), 1):
+ name = t.get("name", "?")
+ desc = " ".join((t.get("description") or "").split())
+ if len(desc) > 70:
+ desc = desc[:67] + "…"
+ print(f" {i:3d}. {name:<24} {desc}", flush=True)
+ if not tools:
+ print(" (the server returned an empty tool list)", flush=True)
+
+
+def teardown(get_http: Callable[[], httpx.Client], pool: str, claim_name: str) -> None:
+ """Best-effort full cleanup: delete the claim, both pool CRs (warm pool
+ before template), then the namespace.
+
+ Idempotent — a 404 just means something was already gone. This is a test
+ scenario, so we remove everything we created and leave nothing billing.
+ """
+ for what, url in (
+ (f"claim {claim_name!r}", claims_url(pool, claim_name)),
+ (f"warm pool {pool!r}", warmpool_url(pool, pool)),
+ (f"template {pool}-template", template_url(pool, f"{pool}-template")),
+ (f"namespace {pool!r}", f"/api/namespaces/{pool}"),
+ ):
+ try:
+ r = get_http().delete(url)
+ info(f"deleted {what} (HTTP {r.status_code})")
+ except httpx.HTTPError as e:
+ info(f"could not delete {what}: {type(e).__name__}: {e}")
+
+
+# ── Main ──────────────────────────────────────────────────────────────────
+
+
+def main() -> None:
+ p = argparse.ArgumentParser(
+ description="Provision a Windows computer-server pool on run.cua.ai, claim a sandbox, "
+ "list its MCP tools, then tear it all down.",
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
+ )
+ p.add_argument("--name", required=True, help="pool name (also the namespace; lowercase/dashes)")
+ p.add_argument("--client-id", default=os.environ.get("CUA_CLIENT_ID"),
+ help="OAuth client id (per-user key 'ukey-…'); env CUA_CLIENT_ID")
+ p.add_argument("--client-secret", default=os.environ.get("CUA_CLIENT_SECRET"),
+ help="OAuth client secret; env CUA_CLIENT_SECRET")
+ p.add_argument("--image", default=DEFAULT_IMAGE, help="Windows workspace containerDisk image")
+ p.add_argument("--port", type=int, default=8000, help="computer-server port on the VM")
+ p.add_argument("--service-name", default="api", help="name for the per-sandbox Service")
+ p.add_argument("--mcp-path", default="/mcp", help="path the MCP server is mounted at")
+ p.add_argument("--replicas", type=int, default=1, help="pre-warmed VMs the pool keeps")
+ p.add_argument("--cpu", type=int, default=4, help="vCPU cores per VM")
+ p.add_argument("--ram", default="8Gi", help="memory per VM (K8s quantity; Windows wants >=8Gi)")
+ p.add_argument("--firmware", choices=["bios", "efi"], default="efi",
+ help="VM firmware (efi for the GPT/UEFI-only Windows image)")
+ p.add_argument("--readiness-port", type=int, default=None,
+ help="TCP readiness port (default: --port; 0 disables the probe)")
+ p.add_argument("--token-url", default=os.environ.get("CUA_TOKEN_URL", DEFAULT_TOKEN_URL),
+ help="OIDC token endpoint")
+ p.add_argument("--base-url", default=os.environ.get("CUA_BASE_URL", DEFAULT_BASE_URL),
+ help="cyclops-cs base URL")
+ p.add_argument("--claim-name", help="claim name (default: claim-<random>)")
+ p.add_argument("--warm-timeout", type=float, default=1200,
+ help="seconds to wait for the pool's first warm VM before claiming "
+ "(covers the cold image pull + slow Windows boot)")
+ p.add_argument("--bind-deadline", type=int, default=600,
+ help="claim spec.bindDeadline (operator fails an unbound claim after "
+ "this; 0 uses the operator default of 300s)")
+ p.add_argument("--bind-timeout", type=float, default=300,
+ help="seconds the script waits for the claim to bind (fast once warm)")
+ p.add_argument("--ready-timeout", type=float, default=420,
+ help="seconds to wait for the in-guest service after binding")
+ p.add_argument("--poll-interval", type=float, default=5,
+ help="seconds between status polls")
+ p.add_argument("--keep", action="store_true",
+ help="skip teardown — leave the pool, namespace, and claim up for debugging")
+ args = p.parse_args()
+
+ if not args.client_id or not args.client_secret:
+ die("set --client-id/--client-secret or CUA_CLIENT_ID/CUA_CLIENT_SECRET "
+ "(per-user key from POST /api/user-keys)")
+ if args.client_id.startswith("key-"):
+ die("that looks like a per-POOL key ('key-…'), which has no K8s identity. "
+ "Creating namespaces/pools/claims needs a per-USER key ('ukey-…', "
+ "from POST /api/user-keys).")
+
+ readiness_port = args.port if args.readiness_port is None else args.readiness_port
+ pool = args.name
+ claim_name = args.claim_name or f"claim-{uuid.uuid4().hex[:8]}"
+
+ step(f"Authenticating to {args.base_url} (client {args.client_id})")
+ client = TrainClient.from_key(
+ token_url=args.token_url,
+ client_id=args.client_id,
+ client_secret=args.client_secret,
+ base_url=args.base_url,
+ )
+ # get_httpx_client() re-mints the bearer token near expiry, so fetch it
+ # per request rather than holding one reference.
+ http = client.get_httpx_client
+ info("token acquired")
+
+ step(f"Creating namespace {pool!r}")
+ create_namespace(http(), pool)
+
+ step(f"Creating sandbox template {pool}-template")
+ create_template(
+ http(),
+ pool=pool,
+ image=args.image,
+ cpu=args.cpu,
+ ram=args.ram,
+ firmware=args.firmware,
+ service_name=args.service_name,
+ port=args.port,
+ readiness_port=readiness_port,
+ )
+
+ step(f"Creating warm pool {pool!r}")
+ create_warm_pool(http(), pool=pool, replicas=args.replicas)
+
+ step("Waiting for the pool's first VM to warm up (so the claim binds fast)")
+ info("(cold start = containerDisk image pull + Windows boot + computer-server on the readiness port)")
+ wait_pool_warm(http, pool, args.warm_timeout, args.poll_interval)
+
+ step(f"Claiming a sandbox from {pool!r} (claim {claim_name!r})")
+ create_claim(http(), pool, claim_name, args.bind_deadline)
+
+ try:
+ step("Waiting for the claim to bind to the warm sandbox")
+ sandbox = wait_bound(http, pool, claim_name, args.bind_timeout, args.poll_interval)
+ info(f"bound to sandbox {sandbox!r}")
+
+ # Per-sandbox Service is "<sandbox>-<service>" on port 80 -> targetPort.
+ svc_base = f"/api/svc/{pool}/{sandbox}-{args.service_name}"
+
+ step("Waiting for the in-guest computer-server to answer")
+ wait_service_ready(http, f"{svc_base}/status", args.ready_timeout, args.poll_interval)
+
+ step(f"Listing MCP tools at {svc_base}{args.mcp_path}")
+ list_mcp_tools(http(), svc_base, args.mcp_path)
+ finally:
+ print(flush=True)
+ if args.keep:
+ step(f"Keeping infra ({pool!r}) — skipping teardown (--keep)")
+ info(f"claim: {claims_url(pool, claim_name)}")
+ info(f"warm pool: {warmpool_url(pool, pool)}")
+ info(f"template: {template_url(pool, f'{pool}-template')}")
+ info(f"namespace: /api/namespaces/{pool}")
+ else:
+ step(f"Tearing down {pool!r} (claim + warm pool + template + namespace)")
+ teardown(http, pool, claim_name)
+ info("done — nothing left billing")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/libs/fleet/python-sdk/examples/requirements.txt b/libs/fleet/python-sdk/examples/requirements.txt
new file mode 100644
index 0000000000..d37fafb796
--- /dev/null
+++ b/libs/fleet/python-sdk/examples/requirements.txt
@@ -0,0 +1,6 @@
+# Extra deps for the examples (the SDK itself only needs httpx + attrs).
+# pip install cua-train --extra-index-url https://wheels.cua.ai/simple/
+# pip install -r requirements.txt
+pillow
+boto3
+pyyaml
diff --git a/libs/fleet/python-sdk/examples/sample_agent.py b/libs/fleet/python-sdk/examples/sample_agent.py
new file mode 100644
index 0000000000..b41c1b59d3
--- /dev/null
+++ b/libs/fleet/python-sdk/examples/sample_agent.py
@@ -0,0 +1,1217 @@
+#!/usr/bin/env -S uv run --script
+# /// script
+# requires-python = ">=3.10"
+# dependencies = [
+# "boto3",
+# "cua-train",
+# "httpx",
+# "pyyaml",
+# ]
+#
+# [tool.uv]
+# extra-index-url = ["https://wheels.cua.ai/simple/"]
+# ///
+"""Run **mini-swe-agent over TWO MCP servers** on a **Windows** CUA sandbox.
+
+Self-contained, single-file — run it straight with ``uv`` (no venv, no
+``pip install``); the inline script metadata pulls ``cua-train`` from the wheels
+index automatically.
+
+the sandbox runs **two** MCP servers at once:
+
+ * CUA **computer-server** — Service ``<sandbox>-server`` (VM :8000), MCP /mcp
+ * **cua-driver** — Service ``<sandbox>-mcp`` (VM :3000), MCP /mcp
+
+Lifecycle (every step narrated in the console):
+
+ 1. exchange the client_credentials for a bearer token (``TrainClient.from_key``)
+ 2. create the per-user namespace (``POST /api/namespaces`` — Capsule tenant
+ RBAC; pool name == namespace)
+ 3. create the pool's two native CRs (``osgym.cua.ai/v1alpha1``): an
+ ``OSGymSandboxTemplate`` (``<pool>-template``) with **one Service per MCP
+ server**, and an ``OSGymSandboxWarmPool`` (``<pool>``) that warms VMs from it
+ 4. wait for a warm VM, then claim a sandbox (``OSGymSandboxClaim``)
+ 5. open one MCP session per server, run the agent, release the claim
+
+Auth needs a per-USER key (``ukey-…``, from POST /api/user-keys); the LLM runs
+on **AWS Bedrock** via a direct ``boto3`` ``bedrock-runtime`` Converse call. AWS
+credentials come straight from the standard environment / default chain (env
+vars, a shared profile, SSO, or an instance role) — there is no LiteLLM layer.
+Set AWS_REGION (or pass ``--aws-region``); the model id is a Bedrock id such as
+``us.anthropic.claude-sonnet-4-6`` (a leading ``bedrock/`` is stripped).
+
+ export CUA_CLIENT_ID=ukey-xxxxxxxx
+ export CUA_CLIENT_SECRET=...
+ export AWS_REGION=us-east-1
+ export AWS_ACCESS_KEY_ID=... AWS_SECRET_ACCESS_KEY=... # or AWS_PROFILE / role
+ uv run sample_agent.py --name windows-agent-demo \
+ --model us.anthropic.claude-sonnet-4-6 \
+ --task "Open Microsoft Edge and browse to https://news.yahoo.com/."
+
+…or, if your uv is too old to read the inline extra-index-url::
+
+ uv run --with cua-train --with httpx --with boto3 \
+ --extra-index-url https://wheels.cua.ai/simple/ \
+ sample_agent.py --name windows-agent-demo --task "…"
+
+The sandbox claim is ALWAYS released on exit — success, error, or Ctrl-C. Pass
+``--keep`` to leave the *pool/namespace* up (the claim is still released),
+``--delete-pool`` to tear everything down.
+Env knobs: CUA_CLIENT_ID, CUA_CLIENT_SECRET, CUA_TOKEN_URL, CUA_BASE_URL, AGENT_MODEL,
+plus the standard AWS_* variables (AWS_REGION, AWS_ACCESS_KEY_ID, …) read by boto3.
+"""
+
+from __future__ import annotations
+
+import argparse
+import base64
+import dataclasses
+import json
+import os
+import re
+import signal
+import sys
+import time
+import uuid
+from collections.abc import Callable
+
+import boto3
+import httpx
+import yaml
+
+from cua_train import TrainClient
+
+DEFAULT_TOKEN_URL = "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token"
+DEFAULT_BASE_URL = "https://run.cua.ai"
+
+# A pool is two native CRs in the osgym.cua.ai group: an OSGymSandboxTemplate
+# (the VM shape, named "<pool>-template") and an OSGymSandboxWarmPool (named
+# "<pool>") that references it and keeps spec.replicas VMs warm. Claims
+# (OSGymSandboxClaim) reference the template by name.
+EXT_GROUP, EXT_VERSION = "osgym.cua.ai", "v1alpha1"
+TEMPLATE_PLURAL, WARMPOOL_PLURAL = "osgymsandboxtemplates", "osgymsandboxwarmpools"
+CLAIM_PLURAL = "osgymsandboxclaims"
+
+SYSTEM = (
+ "You operate a computer through the provided tools. You have access to "
+ "MULTIPLE tool servers running inside the same machine — a CUA "
+ "computer-server and a cua-driver — and their tool names are prefixed with "
+ "the server they belong to (e.g. 'computer-server__screenshot', "
+ "'cua-driver__click'). Pick whichever tool fits; they act on the same "
+ "desktop. Inspect state (take a screenshot, read a file, run a command), "
+ "then take ONE action at a time and observe the result before the next. "
+ "When the task is fully complete, reply with a final message and no tool call."
+)
+
+
+def default_run_manifest() -> dict:
+ return {
+ "apiVersion": "cua.ai/v1alpha1",
+ "kind": "AgentWindowsDoubleMCPRun",
+ "metadata": {"name": None},
+ "spec": {
+ "pool": {
+ "image": DEFAULT_IMAGE,
+ "cpu": DEFAULT_CPU,
+ "ram": DEFAULT_RAM,
+ "firmware": DEFAULT_FIRMWARE,
+ "replicas": 1,
+ "minAvailable": 1,
+ "readinessPort": None,
+ "services": [],
+ },
+ "claim": {
+ "name": None,
+ "bindDeadline": 600,
+ },
+ "agent": {
+ "model": None,
+ "task": None,
+ "maxSteps": 40,
+ "keepImages": 2,
+ },
+ "rollout": {
+ "warmTimeout": 0,
+ "bindTimeout": 0,
+ "readyTimeout": 0,
+ "pollInterval": 5,
+ },
+ "teardown": {
+ "keepPool": False,
+ "deletePool": False,
+ },
+ },
+ }
+
+
+def deep_merge(base: dict, override: dict) -> dict:
+ merged = dict(base)
+ for key, value in override.items():
+ if isinstance(value, dict) and isinstance(base.get(key), dict):
+ merged[key] = deep_merge(base[key], value)
+ else:
+ merged[key] = value
+ return merged
+
+
+def load_run_manifest(path: str | None) -> dict:
+ manifest = default_run_manifest()
+ if not path:
+ return manifest
+ with open(path, "r", encoding="utf-8") as f:
+ raw = yaml.safe_load(f) or {}
+ if not isinstance(raw, dict):
+ die(f"config {path!r} must be a YAML mapping/object")
+ manifest = deep_merge(manifest, raw)
+ kind = manifest.get("kind")
+ if kind != "AgentWindowsDoubleMCPRun":
+ die(f"config {path!r} must have kind: AgentWindowsDoubleMCPRun (got {kind!r})")
+ return manifest
+
+
+def manifest_get(manifest: dict, *path: str, default=None):
+ cur = manifest
+ for part in path:
+ if not isinstance(cur, dict):
+ return default
+ cur = cur.get(part)
+ if cur is None:
+ return default
+ return cur
+
+
+def resolve_name_template(name: str | None) -> str | None:
+ if not name:
+ return name
+ suffix = uuid.uuid4().hex[:6]
+ if "{randhex6}" in name:
+ return name.replace("{randhex6}", suffix)
+ if name.endswith("-"):
+ return f"{name}{suffix}"
+ return name
+
+
+# Default LLM: Claude on AWS Bedrock (cross-region inference profile). Override
+# with --model or AGENT_MODEL; whatever your AWS account/region has enabled.
+DEFAULT_BEDROCK_MODEL = "us.anthropic.claude-sonnet-4-6"
+MAX_OUTPUT_TOKENS = 4096
+
+
+def default_model() -> str:
+ """Bedrock model id default (AGENT_MODEL overrides)."""
+ return os.environ.get("AGENT_MODEL") or DEFAULT_BEDROCK_MODEL
+
+
+def env_first(name: str, *aliases: str) -> str | None:
+ for key in (name, *aliases):
+ value = os.environ.get(key)
+ if value:
+ return value
+ return None
+
+
+def bedrock_model_id(model: str) -> str:
+ """Strip an optional ``bedrock/`` prefix; the Converse API wants the bare id."""
+ return model[len("bedrock/"):] if model.startswith("bedrock/") else model
+
+
+def make_bedrock_client(args: argparse.Namespace):
+ """A boto3 bedrock-runtime client. Credentials and region come from the
+ standard AWS environment / default chain (env vars, shared profile, SSO,
+ instance role) — nothing LLM-specific to configure. --aws-region overrides
+ the region; AWS_REGION/AWS_DEFAULT_REGION are honoured otherwise."""
+ region = args.aws_region or env_first("AWS_REGION", "AWS_DEFAULT_REGION")
+ client = boto3.client("bedrock-runtime", region_name=region) if region else boto3.client("bedrock-runtime")
+ info(f"Bedrock client ready (region {client.meta.region_name})")
+ return client
+
+
+# OS profile (Windows)
+
+
[email protected](frozen=True)
+class McpServerSpec:
+ """One MCP server exposed by the sandbox VM.
+
+ ``label`` — short name; tool names are namespaced ``<label>__<tool>``.
+ ``service`` — per-sandbox Service suffix: ``/api/svc/{ns}/{sandbox}-{service}``.
+ ``port`` — targetPort on the VM the Service maps :80 -> .
+ ``mcp_path`` — path the MCP server is mounted at (Streamable HTTP).
+ ``health`` — a cheap GET that returns non-5xx once the guest service is up.
+ """
+
+ label: str
+ service: str
+ port: int
+ mcp_path: str = "/mcp"
+ health: str = "/healthz"
+
+
[email protected](frozen=True)
+class ServiceSpec:
+ """One non-MCP service exposed by the sandbox VM."""
+
+ label: str
+ service: str
+ port: int
+
+
+OS_NAME = "windows"
+DEFAULT_IMAGE = "296062593712.dkr.ecr.us-west-2.amazonaws.com/cua-server-windows:latest"
+# KubeVirt VM firmware (spec.vmTemplate.firmware; CRD enum [bios, efi]).
+# efi — GPT/UEFI-only guest images (the dockur-built Windows desktop-workspace);
+# the operator also flips on Hyper-V enlightenments + clock config for it.
+# bios — KubeVirt's default; what the Linux workspace images boot with.
+# The SPA/operator only send firmware when it differs from bios, so we omit it for
+# bios and let the operator default apply. Default here is efi (this script's
+# Windows lineage); per-run configs set spec.pool.firmware for non-Windows images.
+DEFAULT_FIRMWARE = "efi"
+FIRMWARE_CHOICES = ("bios", "efi")
+DEFAULT_RAM = "4Gi"
+DEFAULT_CPU = 4
+DEFAULT_WARM_TIMEOUT = 900 # cold image pull + Windows boot
+
+
+# URL builders (relative to base_url, e.g. https://run.cua.ai)
+
+
+def template_url(pool: str, name: str | None = None) -> str:
+ base = f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{TEMPLATE_PLURAL}"
+ return f"{base}/{name}" if name else base
+
+
+def warmpool_url(pool: str, name: str | None = None) -> str:
+ base = f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{WARMPOOL_PLURAL}"
+ return f"{base}/{name}" if name else base
+
+
+def claims_url(pool: str, name: str | None = None) -> str:
+ base = f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{CLAIM_PLURAL}"
+ return f"{base}/{name}" if name else base
+
+
+def load_pool_services(manifest: dict) -> tuple[tuple[McpServerSpec, ...], tuple[ServiceSpec, ...]]:
+ raw_services = manifest_get(manifest, "spec", "pool", "services")
+ if not isinstance(raw_services, list) or not raw_services:
+ die("config must define spec.pool.services as a non-empty list")
+
+ mcp_servers: list[McpServerSpec] = []
+ extra_services: list[ServiceSpec] = []
+ labels: set[str] = set()
+ names: set[str] = set()
+
+ for idx, raw in enumerate(raw_services):
+ if not isinstance(raw, dict):
+ die(f"spec.pool.services[{idx}] must be a YAML mapping/object")
+ kind = raw.get("type")
+ label = raw.get("label")
+ service = raw.get("service")
+ port = raw.get("port")
+ if kind not in {"mcp", "auxiliary"}:
+ die(f"spec.pool.services[{idx}].type must be 'mcp' or 'auxiliary'")
+ if not isinstance(label, str) or not label:
+ die(f"spec.pool.services[{idx}].label must be a non-empty string")
+ if not isinstance(service, str) or not service:
+ die(f"spec.pool.services[{idx}].service must be a non-empty string")
+ if not isinstance(port, int) or port <= 0:
+ die(f"spec.pool.services[{idx}].port must be a positive integer")
+ if label in labels:
+ die(f"duplicate spec.pool.services label: {label!r}")
+ if service in names:
+ die(f"duplicate spec.pool.services service: {service!r}")
+ labels.add(label)
+ names.add(service)
+ if kind == "mcp":
+ mcp_path = raw.get("mcpPath", "/mcp")
+ health = raw.get("health", "/healthz")
+ if not isinstance(mcp_path, str) or not mcp_path.startswith("/"):
+ die(f"spec.pool.services[{idx}].mcpPath must be an absolute path string")
+ if not isinstance(health, str) or not health.startswith("/"):
+ die(f"spec.pool.services[{idx}].health must be an absolute path string")
+ mcp_servers.append(
+ McpServerSpec(label=label, service=service, port=port, mcp_path=mcp_path, health=health)
+ )
+ else:
+ extra_services.append(ServiceSpec(label=label, service=service, port=port))
+
+ if not mcp_servers:
+ die("spec.pool.services must include at least one MCP service")
+ return tuple(mcp_servers), tuple(extra_services)
+
+
+def pool_services(
+ mcp_servers: tuple[McpServerSpec, ...],
+ extra_services: tuple[ServiceSpec, ...],
+) -> tuple[ServiceSpec, ...]:
+ base = tuple(ServiceSpec(label=s.label, service=s.service, port=s.port) for s in mcp_servers)
+ return base + extra_services
+
+
+# Status formatting helpers
+
+
+def _fmt_conditions(conditions: list[dict] | None) -> str:
+ if not conditions:
+ return "none"
+ parts = []
+ for cond in conditions:
+ ctype = cond.get("type", "?")
+ status = cond.get("status", "?")
+ reason = cond.get("reason", "?")
+ msg = " ".join(str(cond.get("message", "")).split())
+ chunk = f"{ctype}={status}/{reason}"
+ if msg:
+ chunk += f" ({msg})"
+ parts.append(chunk)
+ return "; ".join(parts)
+
+
+def pool_status(http: httpx.Client, pool: str) -> dict:
+ r = http.get(warmpool_url(pool, pool))
+ r.raise_for_status()
+ return r.json().get("status") or {}
+
+
+def claim_status(http: httpx.Client, pool: str, name: str) -> dict:
+ r = http.get(claims_url(pool, name))
+ r.raise_for_status()
+ return r.json().get("status") or {}
+
+
+def claim_obj(http: httpx.Client, pool: str, name: str) -> dict:
+ r = http.get(claims_url(pool, name))
+ r.raise_for_status()
+ return r.json()
+
+
+def pool_summary(status: dict) -> str:
+ return f"ready={int(status.get('readyReplicas', 0))}/{int(status.get('replicas', 0))}"
+
+
+def claim_summary(status: dict) -> str:
+ sandbox = (status.get("sandbox") or {}).get("name")
+ summary = f"phase={status.get('phase', 'Pending')}"
+ if sandbox:
+ summary += f" sandbox={sandbox}"
+ conds = _fmt_conditions(status.get("conditions"))
+ if conds != "none":
+ summary += f" conditions=[{conds}]"
+ return summary
+
+
+def claim_operator_progress(obj: dict) -> str | None:
+ raw = (obj.get("metadata") or {}).get("annotations", {}).get("kopf.zalando.org/on_claim_create")
+ if not raw:
+ return None
+ try:
+ data = json.loads(raw)
+ except Exception:
+ return raw
+ retries = data.get("retries")
+ message = " ".join(str(data.get("message", "")).split())
+ parts = []
+ if retries is not None:
+ parts.append(f"retries={retries}")
+ if message:
+ parts.append(message)
+ return "; ".join(parts) or None
+
+
+# Console helpers
+
+
+def step(msg: str) -> None:
+ print(f"\n==> {msg}", flush=True)
+
+
+def info(msg: str) -> None:
+ print(f" {msg}", flush=True)
+
+
+def die(msg: str) -> None:
+ sys.exit(f"\nERROR: {msg}")
+
+
+class TeeWriter:
+ def __init__(self, *streams) -> None:
+ self.streams = streams
+
+ def write(self, data: str) -> int:
+ for stream in self.streams:
+ stream.write(data)
+ return len(data)
+
+ def flush(self) -> None:
+ for stream in self.streams:
+ stream.flush()
+
+ def isatty(self) -> bool:
+ return any(getattr(stream, "isatty", lambda: False)() for stream in self.streams)
+
+
+def configure_logging(log_file: str | None) -> None:
+ if not log_file:
+ return
+ log_path = os.path.abspath(log_file)
+ os.makedirs(os.path.dirname(log_path), exist_ok=True)
+ log_stream = open(log_path, "a", encoding="utf-8", buffering=1)
+ sys.stdout = TeeWriter(sys.stdout, log_stream)
+ sys.stderr = TeeWriter(sys.stderr, log_stream)
+ info(f"logging to {log_path}")
+
+
+# Pool / claim lifecycle (mirrors create_pool_and_list_tools.py)
+
+
+def create_namespace(http: httpx.Client, name: str) -> None:
+ """Create the per-user namespace via the Capsule-backed SPA endpoint.
+
+ Pool name == namespace name (1:1). Going through /api/namespaces is what
+ makes Capsule stamp tenant ownership + RBAC, so the impersonated pool create
+ below is allowed. 409 just means we are reusing an earlier run's namespace.
+ """
+ r = http.post("/api/namespaces", json={"name": name})
+ if r.status_code == 409:
+ info(f"namespace {name!r} already exists — reusing it")
+ return
+ if r.status_code == 403:
+ die("403 creating namespace — namespaces/pools/claims need a per-USER key "
+ "(client id 'ukey-…', from POST /api/user-keys).")
+ r.raise_for_status()
+ info(f"namespace {name!r} created")
+
+
+def delete_namespace(http: httpx.Client, name: str) -> None:
+ r = http.delete(f"/api/namespaces/{name}")
+ if r.status_code in (200, 202, 204, 404):
+ info(f"namespace {name!r} delete requested (HTTP {r.status_code})")
+ return
+ if r.status_code == 403:
+ die("403 deleting namespace — the user key cannot replace this pool namespace.")
+ r.raise_for_status()
+
+
+def recreate_namespace(get_http: Callable[[], httpx.Client], name: str, poll: float) -> None:
+ delete_namespace(get_http(), name)
+ while True:
+ r = get_http().post("/api/namespaces", json={"name": name})
+ if r.status_code == 409:
+ info(f"namespace {name!r} still terminating — waiting to recreate …")
+ time.sleep(poll)
+ continue
+ if r.status_code == 403:
+ die("403 creating namespace during replacement — namespaces/pools/claims need a per-USER key.")
+ r.raise_for_status()
+ info(f"namespace {name!r} recreated")
+ return
+
+
+def desired_template_spec(
+ *,
+ image: str,
+ cpu: int,
+ ram: str,
+ firmware: str,
+ readiness_port: int | None,
+ services: tuple[ServiceSpec, ...],
+) -> dict:
+ """OSGymSandboxTemplate.spec — the VM shape, including the per-sandbox
+ Services (each becomes "<sandbox>-<name>", port 80 -> targetPort)."""
+ vm_template: dict = {
+ "containerDiskImage": image,
+ "imagePullSecret": "ecr-credentials",
+ "cpuCores": cpu,
+ "memory": ram,
+ "services": [{"name": s.service, "targetPort": s.port, "protocol": "TCP"} for s in services],
+ }
+ # Match the SPA/operator: only send firmware when it differs from the bios default.
+ if firmware != "bios":
+ vm_template["firmware"] = firmware
+ if readiness_port:
+ vm_template["probes"] = {"readinessProbe": {"tcpSocket": {"port": readiness_port}}}
+ return {"vmTemplate": vm_template}
+
+
+def desired_warm_pool_spec(*, pool: str, replicas: int) -> dict:
+ """OSGymSandboxWarmPool.spec — how many sandboxes to keep warm, and which
+ template to stamp them from."""
+ return {"replicas": replicas, "sandboxTemplateRef": {"name": f"{pool}-template"}}
+
+
+def _json_canonical(value: dict) -> str:
+ return json.dumps(value, sort_keys=True, separators=(",", ":"))
+
+
+def _flatten_json(value, prefix: str = "") -> dict[str, str]:
+ flat: dict[str, str] = {}
+ if isinstance(value, dict):
+ for key in sorted(value):
+ child = f"{prefix}.{key}" if prefix else str(key)
+ flat.update(_flatten_json(value[key], child))
+ if not value and prefix:
+ flat[prefix] = "{}"
+ elif isinstance(value, list):
+ for idx, item in enumerate(value):
+ child = f"{prefix}[{idx}]"
+ flat.update(_flatten_json(item, child))
+ if not value and prefix:
+ flat[prefix] = "[]"
+ else:
+ flat[prefix] = json.dumps(value, sort_keys=True)
+ return flat
+
+
+def log_pool_spec_diff(current_spec: dict, desired_spec: dict, what: str = "pool") -> None:
+ current_flat = _flatten_json(current_spec, "spec")
+ desired_flat = _flatten_json(desired_spec, "spec")
+ keys = sorted(set(current_flat) | set(desired_flat))
+ diffs = []
+ for key in keys:
+ current_value = current_flat.get(key, "<missing>")
+ desired_value = desired_flat.get(key, "<missing>")
+ if current_value == desired_value:
+ continue
+ diffs.append((key, current_value, desired_value))
+ if not diffs:
+ info(f"{what} spec diff: none")
+ return
+ info(f"{what} spec diff: {len(diffs)} field(s) differ")
+ for key, current_value, desired_value in diffs:
+ info(f" {key}: current={current_value} desired={desired_value}")
+
+
+def create_pool(
+ get_http: Callable[[], httpx.Client],
+ *,
+ pool: str,
+ image: str,
+ cpu: int,
+ ram: str,
+ firmware: str,
+ replicas: int,
+ readiness_port: int | None,
+ mcp_servers: tuple[McpServerSpec, ...],
+ extra_services: tuple[ServiceSpec, ...],
+ poll: float,
+ allow_replace: bool = True,
+) -> None:
+ """Create the pool's two native CRs: the OSGymSandboxTemplate
+ ``<pool>-template`` (VM shape + MCP/auxiliary services) and the
+ OSGymSandboxWarmPool ``<pool>`` that warms sandboxes from it.
+
+ Each service becomes a per-sandbox Service ``<sandbox>-<name>`` (port 80 ->
+ targetPort). The MCP services are used by the agent; auxiliary services such
+ as noVNC are exposed for debugging but are not opened as MCP sessions.
+
+ If either CR already exists with a different spec we replace the whole pool
+ namespace — simpler and more robust than patching two objects in place.
+ """
+ tmpl = f"{pool}-template"
+ template_spec = desired_template_spec(
+ image=image,
+ cpu=cpu,
+ ram=ram,
+ firmware=firmware,
+ readiness_port=readiness_port,
+ services=pool_services(mcp_servers, extra_services),
+ )
+ warm_pool_spec = desired_warm_pool_spec(pool=pool, replicas=replicas)
+
+ existing_template = post_cr(
+ get_http, template_url(pool), f"template {tmpl!r}",
+ {
+ "apiVersion": f"{EXT_GROUP}/{EXT_VERSION}",
+ "kind": "OSGymSandboxTemplate",
+ "metadata": {"namespace": pool, "name": tmpl, "labels": {"cua.ai/pool": pool}},
+ "spec": template_spec,
+ },
+ )
+ existing_warm_pool = post_cr(
+ get_http, warmpool_url(pool), f"warm pool {pool!r}",
+ {
+ "apiVersion": f"{EXT_GROUP}/{EXT_VERSION}",
+ "kind": "OSGymSandboxWarmPool",
+ "metadata": {"namespace": pool, "name": pool, "labels": {"cua.ai/pool": pool}},
+ "spec": warm_pool_spec,
+ },
+ )
+
+ drifted = False
+ for existing, desired, what in (
+ (existing_template, template_spec, f"template {tmpl!r}"),
+ (existing_warm_pool, warm_pool_spec, f"warm pool {pool!r}"),
+ ):
+ if existing is None:
+ info(f"{what} created")
+ continue
+ log_pool_spec_diff(existing, desired, what)
+ if existing == desired:
+ info(f"{what} already exists — reusing it (spec unchanged)")
+ else:
+ drifted = True
+
+ if drifted:
+ if not allow_replace:
+ die(f"pool {pool!r} still differs from desired state after replacement attempt")
+ info(f"pool {pool!r} differs from the desired spec — replacing pool namespace")
+ recreate_namespace(get_http, pool, poll)
+ return create_pool(
+ get_http,
+ pool=pool,
+ image=image,
+ cpu=cpu,
+ ram=ram,
+ firmware=firmware,
+ replicas=replicas,
+ readiness_port=readiness_port,
+ mcp_servers=mcp_servers,
+ extra_services=extra_services,
+ poll=poll,
+ allow_replace=False,
+ )
+
+ info(f"image: {image}")
+ info(f"size: {cpu} vCPU / {ram} / replicas={replicas} / firmware={firmware}")
+ for s in mcp_servers:
+ info(f"service: {s.service:<14} -> targetPort {s.port} (MCP at {s.mcp_path}, health {s.health})")
+ for s in extra_services:
+ info(f"service: {s.service:<14} -> targetPort {s.port} (auxiliary {s.label})")
+ info(f"readiness: {'disabled' if not readiness_port else f'tcpSocket :{readiness_port}'}")
+
+
+def post_cr(
+ get_http: Callable[[], httpx.Client], collection_url: str, what: str, body: dict
+) -> dict | None:
+ """POST one CR. Returns None when it was created, or the existing object's
+ spec on 409 so the caller can decide what to do about the drift."""
+ r = get_http().post(collection_url, json=body)
+ if r.status_code == 409:
+ current = get_http().get(f"{collection_url}/{body['metadata']['name']}")
+ current.raise_for_status()
+ return current.json().get("spec") or {}
+ if r.status_code == 403:
+ die(f"403 creating {what} — /api/k8s needs a per-USER key ('ukey-…', POST /api/user-keys).")
+ r.raise_for_status()
+ return None
+
+
+def pool_counts(get_http: Callable[[], httpx.Client], pool: str) -> tuple[int, int]:
+ """(replicas, readyReplicas) from the warm pool status, best-effort."""
+ try:
+ st = pool_status(get_http(), pool)
+ return int(st.get("replicas", 0)), int(st.get("readyReplicas", 0))
+ except Exception:
+ return 0, 0
+
+
+def wait_pool_warm(
+ get_http: Callable[[], httpx.Client],
+ pool: str,
+ timeout: float,
+ poll: float,
+ *,
+ replicas: int,
+ min_available: int,
+) -> None:
+ """Wait until the warm pool reports ready VMs, so the first claim binds fast.
+
+ A cold pool has to pull the multi-GB containerDisk, boot the guest, and bring
+ the readiness-port service up before a Sandbox is adoptable. Letting the pool
+ warm first keeps the claim's bindDeadline from burning down during the pull.
+ """
+ start = time.monotonic()
+ deadline = start + timeout
+ last_summary = ""
+ while True:
+ try:
+ st = pool_status(get_http(), pool)
+ total = int(st.get("replicas", 0))
+ ready = int(st.get("readyReplicas", 0))
+ summary = pool_summary(st)
+ except Exception:
+ total, ready = 0, 0
+ summary = "ready=0/0"
+ if total >= replicas and ready >= min_available:
+ info(f"pool warm: {ready}/{total} VM(s) ready")
+ return
+ if summary != last_summary:
+ info(f"pool detail: {summary}")
+ last_summary = summary
+ if timeout > 0 and time.monotonic() > deadline:
+ info(f"timed out after {timeout:.0f}s waiting for a warm VM ({ready}/{total} ready)")
+ info("continuing anyway — the claim may still bind once the VM finishes pulling/booting")
+ return
+ elapsed = int(time.monotonic() - start)
+ info(f"[{elapsed:4d}s] pool: {ready}/{total} VMs ready (target total={replicas}, "
+ f"target ready={min_available}) — warming (image pull + guest boot + service on the readiness port) …")
+ time.sleep(poll)
+
+
+def create_claim(http: httpx.Client, pool: str, name: str, bind_deadline: int) -> None:
+ spec: dict = {"sandboxTemplateRef": {"name": f"{pool}-template"}}
+ if bind_deadline:
+ spec["bindDeadline"] = bind_deadline
+ r = http.post(claims_url(pool), json={
+ "apiVersion": f"{EXT_GROUP}/{EXT_VERSION}", "kind": "OSGymSandboxClaim",
+ "metadata": {"name": name}, "spec": spec})
+ if r.status_code == 403:
+ die("403 creating claim — per-pool keys have no K8s identity. Use a per-USER key ('ukey-…').")
+ r.raise_for_status()
+ info(f"claim {name!r} created")
+
+
+def wait_bound(get_http: Callable[[], httpx.Client], pool: str, name: str, timeout: float, poll: float) -> str:
+ """Poll the claim until status.phase == Bound; return the sandbox name."""
+ start = time.monotonic()
+ deadline = start + timeout
+ last_claim = ""
+ last_pool = ""
+ last_operator = ""
+ while True:
+ claim = claim_obj(get_http(), pool, name)
+ status = claim.get("status") or {}
+ phase = status.get("phase", "Pending")
+ sandbox = (status.get("sandbox") or {}).get("name")
+ if phase == "Bound" and sandbox:
+ return sandbox
+ if phase == "Failed":
+ die(f"claim {name} failed: {status}")
+ if timeout > 0 and time.monotonic() > deadline:
+ die(f"timed out after {timeout:.0f}s waiting for claim {name} to bind (phase={phase})")
+ claim_line = claim_summary(status)
+ if claim_line != last_claim:
+ info(f"claim detail: {claim_line}")
+ last_claim = claim_line
+ operator_line = claim_operator_progress(claim)
+ if operator_line and operator_line != last_operator:
+ info(f"claim operator: {operator_line}")
+ last_operator = operator_line
+ try:
+ pst = pool_status(get_http(), pool)
+ total = int(pst.get("replicas", 0))
+ ready = int(pst.get("readyReplicas", 0))
+ pool_line = pool_summary(pst)
+ except Exception:
+ total, ready = 0, 0
+ pool_line = "ready=0/0"
+ if pool_line != last_pool:
+ info(f"pool detail: {pool_line}")
+ last_pool = pool_line
+ elapsed = int(time.monotonic() - start)
+ info(f"[{elapsed:4d}s] claim={phase} pool={ready}/{total} VMs ready …")
+ time.sleep(poll)
+
+
+def wait_service_ready(get_http: Callable[[], httpx.Client], url: str, timeout: float, poll: float) -> None:
+ """GET url until the in-guest service answers (not a proxy 502/503/504)."""
+ start = time.monotonic()
+ deadline = start + timeout
+ while True:
+ try:
+ resp = get_http().get(url, timeout=15.0)
+ except httpx.HTTPError as e:
+ resp, reason = None, type(e).__name__
+ else:
+ reason = f"HTTP {resp.status_code}"
+ if resp is not None and resp.status_code not in (502, 503, 504):
+ info(f"service responding ({reason})")
+ return
+ if timeout > 0 and time.monotonic() > deadline:
+ die(f"timed out after {timeout:.0f}s waiting for the in-guest service (last: {reason})")
+ elapsed = int(time.monotonic() - start)
+ info(f"[{elapsed:4d}s] {reason} — guest still booting …")
+ time.sleep(poll)
+
+
+# MCP (Streamable HTTP) multi-server
+
+
+def _sse_json(resp: httpx.Response) -> dict:
+ """Streamable HTTP replies are SSE ('event: message\\ndata: {...}'); the JSON
+ is on the data: line. Fall back to the raw body for plain JSON."""
+ line = next((ln[6:] for ln in resp.text.splitlines() if ln.startswith("data: ")), resp.text)
+ return json.loads(line)
+
+
+class McpConn:
+ """A live MCP session against one server of the bound sandbox."""
+
+ spec: McpServerSpec
+ svc_base: str # /api/svc/{ns}/{sandbox}-{service}
+ session_id: str | None
+ tools: list[dict] # this server's raw tools/list
+
+ @property
+ def url(self) -> str:
+ return f"{self.svc_base}{self.spec.mcp_path}"
+
+ def _headers(self) -> dict:
+ h = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream"}
+ if self.session_id:
+ h["Mcp-Session-Id"] = self.session_id
+ return h
+
+
+def mcp_open(http: httpx.Client, spec: McpServerSpec, svc_base: str, client_name: str) -> McpConn:
+ """initialize -> notifications/initialized -> tools/list for one server."""
+ url = f"{svc_base}{spec.mcp_path}"
+ headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream"}
+ init = http.post(url, headers=headers, timeout=30.0, json={
+ "jsonrpc": "2.0", "id": 1, "method": "initialize",
+ "params": {"protocolVersion": "2025-03-26", "capabilities": {},
+ "clientInfo": {"name": client_name, "version": "0.1.0"}}})
+ init.raise_for_status()
+ sid = init.headers.get("mcp-session-id")
+ if sid:
+ headers["Mcp-Session-Id"] = sid
+ http.post(url, headers=headers, timeout=30.0, json={"jsonrpc": "2.0", "method": "notifications/initialized"})
+ r = http.post(url, headers=headers, timeout=30.0, json={"jsonrpc": "2.0", "id": 2, "method": "tools/list"})
+ r.raise_for_status()
+ tools = _sse_json(r).get("result", {}).get("tools", [])
+ return McpConn(spec=spec, svc_base=svc_base, session_id=sid, tools=tools)
+
+
+_BEDROCK_IMAGE_FORMATS = {"png", "jpeg", "gif", "webp"}
+
+
+def mcp_call(http: httpx.Client, conn: McpConn, name: str, arguments: dict) -> dict:
+ """Dispatch one tools/call on a specific server. Returns text + inline images
+ (decoded to raw bytes + Bedrock image format) + isError. Raises on a
+ transport/proxy error so the caller can surface it."""
+ r = http.post(conn.url, headers=conn._headers(), timeout=600.0, json={
+ "jsonrpc": "2.0", "id": 1, "method": "tools/call",
+ "params": {"name": name, "arguments": arguments}})
+ if r.status_code in (502, 503, 504):
+ raise httpx.HTTPError(f"proxy {r.status_code}")
+ r.raise_for_status()
+ result = _sse_json(r).get("result", {})
+ text_parts, images = [], []
+ for block in result.get("content", []):
+ if block.get("type") == "text":
+ text_parts.append(block.get("text", ""))
+ elif block.get("type") == "image":
+ mime = block.get("mimeType", "image/png")
+ fmt = mime.split("/")[-1].lower()
+ fmt = "jpeg" if fmt == "jpg" else fmt
+ if fmt not in _BEDROCK_IMAGE_FORMATS:
+ fmt = "png"
+ images.append({"format": fmt, "bytes": base64.b64decode(block["data"])})
+ return {"text": "\n".join(text_parts), "images": images, "is_error": bool(result.get("isError"))}
+
+
+def _sanitize(label: str) -> str:
+ return re.sub(r"[^a-zA-Z0-9_-]", "-", label)
+
+
+def build_tool_registry(conns: list[McpConn]) -> tuple[list[dict], dict[str, tuple[McpConn, str]]]:
+ """Union every server's tools into one Bedrock Converse toolConfig tool list,
+ namespacing names as ``<server>__<tool>`` so two servers can expose the same
+ tool without colliding. Returns (llm_tools, registry) where registry maps the
+ namespaced name back to (connection, original tool name) for dispatch."""
+ llm_tools: list[dict] = []
+ registry: dict[str, tuple[McpConn, str]] = {}
+ for conn in conns:
+ prefix = _sanitize(conn.spec.label)
+ for t in conn.tools:
+ orig = t["name"]
+ llm_name = f"{prefix}__{orig}"[:64] # Bedrock caps tool names at 64
+ # Extremely unlikely, but keep names unique if truncation collides.
+ while llm_name in registry:
+ llm_name = f"{llm_name[:60]}_{len(registry)}"
+ registry[llm_name] = (conn, orig)
+ desc = f"[{conn.spec.label}] " + " ".join((t.get("description") or "").split())
+ schema = t.get("inputSchema") or {"type": "object", "properties": {}}
+ llm_tools.append({"toolSpec": {
+ "name": llm_name,
+ "description": desc or llm_name,
+ "inputSchema": {"json": schema}}})
+ return llm_tools, registry
+
+
+def _msg_has_image(m: dict) -> bool:
+ return isinstance(m.get("content"), list) and any(
+ "toolResult" in b and any("image" in c for c in b["toolResult"].get("content", []))
+ for b in m["content"])
+
+
+def _prune_images(messages: list[dict], keep: int) -> None:
+ """Drop all but the last `keep` screenshots — image tokens dominate a
+ computer-use trajectory's cost and stale frames mislead the model. Images live
+ inside toolResult content blocks; replace each with a text placeholder so the
+ toolResult stays valid (Converse requires non-empty toolResult content)."""
+ idx = [i for i, m in enumerate(messages) if _msg_has_image(m)]
+ for i in (idx[:-keep] if keep else idx):
+ for b in messages[i]["content"]:
+ tr = b.get("toolResult")
+ if not tr:
+ continue
+ tr["content"] = [
+ {"text": "[older screenshot dropped from context]"} if "image" in c else c
+ for c in tr.get("content", [])]
+
+
+# The agent loop (mini-swe-agent, multi-MCP)
+
+
+def _converse_text(content: list[dict]) -> str:
+ return "\n".join(b["text"] for b in content if "text" in b).strip()
+
+
+def run_agent(http_get: Callable[[], httpx.Client], conns: list[McpConn], bedrock, *,
+ task: str, model_id: str, max_steps: int, keep_images: int) -> str:
+ """Canonical mini-swe-agent loop over the UNION of every server's tools, driven
+ by the Bedrock Converse API (one tool turn per step)."""
+ llm_tools, registry = build_tool_registry(conns)
+ info(f"action space: {len(llm_tools)} tools across {len(conns)} MCP server(s)")
+ for conn in conns:
+ names = ", ".join(sorted(t["name"] for t in conn.tools)) or "(none)"
+ info(f" {conn.spec.label}: {names}")
+
+ system = [{"text": SYSTEM}]
+ tool_config = {"tools": llm_tools}
+ messages: list[dict] = [{"role": "user", "content": [{"text": task}]}]
+ for n in range(1, max_steps + 1):
+ resp = bedrock.converse(
+ modelId=model_id,
+ system=system,
+ messages=messages,
+ toolConfig=tool_config,
+ inferenceConfig={"temperature": 0.0, "maxTokens": MAX_OUTPUT_TOKENS},
+ )
+ out = resp["output"]["message"]
+ messages.append(out)
+ tool_uses = [b["toolUse"] for b in out["content"] if "toolUse" in b]
+ if not tool_uses:
+ step(f"agent finished after {n - 1} action(s)")
+ final = _converse_text(out["content"])
+ print(final or "(no final message)", flush=True)
+ return final or "done"
+
+ result_blocks: list[dict] = []
+ for tu in tool_uses:
+ llm_name, tuid = tu["name"], tu["toolUseId"]
+ tool_args = tu.get("input") or {}
+ entry = registry.get(llm_name)
+ if entry is None:
+ result_blocks.append({"toolResult": {"toolUseId": tuid,
+ "content": [{"text": f"unknown tool {llm_name!r}"}], "status": "error"}})
+ continue
+ conn, orig = entry
+ info(f"[step {n}] {conn.spec.label} -> {orig}({json.dumps(tool_args)[:120]})")
+ try:
+ res = mcp_call(http_get(), conn, orig, tool_args)
+ except httpx.HTTPError as e:
+ result_blocks.append({"toolResult": {"toolUseId": tuid,
+ "content": [{"text": f"tool transport error: {e}"}], "status": "error"}})
+ continue
+ content: list[dict] = []
+ if res["text"]:
+ content.append({"text": res["text"]})
+ for img in res["images"]:
+ content.append({"image": {"format": img["format"], "source": {"bytes": img["bytes"]}}})
+ if not content:
+ content.append({"text": "(no output)"})
+ result_blocks.append({"toolResult": {"toolUseId": tuid, "content": content,
+ "status": "error" if res["is_error"] else "success"}})
+ messages.append({"role": "user", "content": result_blocks})
+ _prune_images(messages, keep_images)
+ return "max_steps_exceeded"
+
+
+# Main
+
+
+def main() -> None:
+ pre = argparse.ArgumentParser(add_help=False)
+ pre.add_argument("--config")
+ pre_args, remaining = pre.parse_known_args()
+ manifest = load_run_manifest(pre_args.config)
+ mcp_servers, extra_services = load_pool_services(manifest)
+
+ p = argparse.ArgumentParser(
+ description=f"Provision a {OS_NAME} double-MCP pool on run.cua.ai, claim a sandbox, "
+ "and run mini-swe-agent against BOTH its MCP servers.",
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
+ parents=[pre],
+ )
+ cfg_name = manifest_get(manifest, "metadata", "name")
+ cfg_task = manifest_get(manifest, "spec", "agent", "task")
+ p.add_argument("--name", required=cfg_name is None, default=cfg_name,
+ help="pool name (also the namespace; lowercase/dashes). Reuse the same name across retries "
+ "to keep the same provisioning pool warm.")
+ p.add_argument("--task", required=cfg_task is None, default=cfg_task, help="the task prompt for the agent")
+ p.add_argument("--client-id", default=os.environ.get("CUA_CLIENT_ID"),
+ help="OAuth client id (per-user key 'ukey-…'); env CUA_CLIENT_ID")
+ p.add_argument("--client-secret", default=os.environ.get("CUA_CLIENT_SECRET"),
+ help="OAuth client secret; env CUA_CLIENT_SECRET")
+ p.add_argument("--model", default=manifest_get(manifest, "spec", "agent", "model", default=default_model()) or default_model(),
+ help="Bedrock model id (a leading 'bedrock/' is stripped). Uses AGENT_MODEL if set, "
+ f"else {DEFAULT_BEDROCK_MODEL}.")
+ p.add_argument("--aws-region", default=None,
+ help="AWS region for the Bedrock client. Defaults to AWS_REGION/AWS_DEFAULT_REGION "
+ "(or your ~/.aws config). Credentials always come from the AWS env / default chain.")
+ p.add_argument("--image", default=manifest_get(manifest, "spec", "pool", "image"), help="workspace containerDisk image")
+ p.add_argument("--cpu", type=int, default=manifest_get(manifest, "spec", "pool", "cpu"), help="vCPU cores per VM")
+ p.add_argument("--ram", default=manifest_get(manifest, "spec", "pool", "ram"), help="memory per VM (K8s quantity)")
+ p.add_argument("--firmware", choices=FIRMWARE_CHOICES,
+ default=manifest_get(manifest, "spec", "pool", "firmware", default=DEFAULT_FIRMWARE) or DEFAULT_FIRMWARE,
+ help="VM firmware. 'efi' for GPT/UEFI-only images (Windows desktop-workspace); "
+ "'bios' (KubeVirt default) for the Linux workspace images.")
+ p.add_argument("--replicas", type=int, default=manifest_get(manifest, "spec", "pool", "replicas"), help="pre-warmed VMs the pool keeps")
+ p.add_argument("--min-available", type=int, default=manifest_get(manifest, "spec", "pool", "minAvailable"),
+ help="minimum warm/available VMs to wait for before claiming. Set to 2+ to keep a small surplus warm.")
+ p.add_argument("--readiness-port", type=int, default=manifest_get(manifest, "spec", "pool", "readinessPort"),
+ help="TCP port used for readiness probing. Set to 0 to disable readiness probes in the pool template.")
+ p.add_argument("--max-steps", type=int, default=manifest_get(manifest, "spec", "agent", "maxSteps"), help="agent step budget")
+ p.add_argument("--keep-images", type=int, default=manifest_get(manifest, "spec", "agent", "keepImages"), help="screenshots kept in LLM context")
+ p.add_argument("--token-url", default=os.environ.get("CUA_TOKEN_URL", DEFAULT_TOKEN_URL))
+ p.add_argument("--base-url", default=os.environ.get("CUA_BASE_URL", DEFAULT_BASE_URL))
+ p.add_argument("--claim-name", default=manifest_get(manifest, "spec", "claim", "name"), help="claim name (default: claim-<random>)")
+ p.add_argument("--warm-timeout", type=float, default=manifest_get(manifest, "spec", "rollout", "warmTimeout"),
+ help="seconds to wait for warm pool capacity. 0 waits indefinitely.")
+ p.add_argument("--bind-deadline", type=int, default=manifest_get(manifest, "spec", "claim", "bindDeadline"))
+ p.add_argument("--bind-timeout", type=float, default=manifest_get(manifest, "spec", "rollout", "bindTimeout"),
+ help="seconds to wait for claim binding. 0 waits indefinitely.")
+ p.add_argument("--ready-timeout", type=float, default=manifest_get(manifest, "spec", "rollout", "readyTimeout"),
+ help="seconds to wait for each MCP server to answer after binding. 0 waits indefinitely.")
+ p.add_argument("--poll-interval", type=float, default=manifest_get(manifest, "spec", "rollout", "pollInterval"))
+ p.add_argument("--log-file", default=None,
+ help="append all console output to this file while the run is active")
+ p.add_argument("--keep", action="store_true", default=manifest_get(manifest, "spec", "teardown", "keepPool"),
+ help="skip teardown — leave the pool/namespace/claim up for debugging or for reuse on the next retry")
+ p.add_argument("--delete-pool", action="store_true", default=manifest_get(manifest, "spec", "teardown", "deletePool"),
+ help="on exit also delete the pool AND namespace (full cleanup)")
+ args = p.parse_args(remaining)
+ args.name = resolve_name_template(args.name)
+ args.claim_name = resolve_name_template(args.claim_name)
+ configure_logging(args.log_file)
+
+ if not args.client_id or not args.client_secret:
+ die("set --client-id/--client-secret or CUA_CLIENT_ID/CUA_CLIENT_SECRET "
+ "(per-user key from POST /api/user-keys)")
+ if args.client_id.startswith("key-"):
+ die("that looks like a per-POOL key ('key-…'), which has no K8s identity. "
+ "Creating namespaces/pools/claims needs a per-USER key ('ukey-…').")
+
+ model_id = bedrock_model_id(args.model)
+ bedrock = make_bedrock_client(args)
+
+ pool = args.name
+ claim_name = args.claim_name or f"claim-{uuid.uuid4().hex[:8]}"
+
+ step(f"Authenticating to {args.base_url} (client {args.client_id})")
+ client = TrainClient.from_key(token_url=args.token_url, client_id=args.client_id,
+ client_secret=args.client_secret, base_url=args.base_url)
+ http = client.get_httpx_client # call per request — re-mints the bearer near expiry
+ info("token acquired")
+
+ step(f"Creating namespace {pool!r}")
+ create_namespace(http(), pool)
+
+ step(f"Creating {OS_NAME} double-MCP pool {pool!r}")
+ readiness_port = args.readiness_port or None
+ create_pool(
+ http,
+ pool=pool,
+ image=args.image,
+ cpu=args.cpu,
+ ram=args.ram,
+ firmware=args.firmware,
+ replicas=args.replicas,
+ readiness_port=readiness_port,
+ mcp_servers=mcp_servers,
+ extra_services=extra_services,
+ poll=args.poll_interval,
+ )
+
+ step(f"Claiming a sandbox from {pool!r} (claim {claim_name!r})")
+
+ # The claim is ALWAYS released — on success, on error, or on Ctrl-C — so an
+ # interrupted or failed run never leaks a claimed VM. --keep only preserves the
+ # pool/namespace, NOT the claim. The `released` flag makes release idempotent
+ # across the SIGINT handler and the finally block.
+ released = False
+
+ def release_claim() -> None:
+ nonlocal released
+ if released:
+ return
+ released = True
+ step(f"Releasing claim {claim_name!r}")
+ try:
+ r = http().delete(claims_url(pool, claim_name))
+ info(f"released (HTTP {r.status_code}) — the VM hard-resets and rejoins the pool")
+ except httpx.HTTPError as e:
+ info(f"could not release claim: {type(e).__name__}: {e}")
+
+ def _sigint_handler(signum, frame):
+ print(flush=True)
+ step("Interrupted (Ctrl-C) — releasing claim before exit")
+ release_claim()
+ sys.exit(130)
+
+ signal.signal(signal.SIGINT, _sigint_handler)
+
+ try:
+ # Inside the try so the finally still releases even if create/bind fails midway.
+ create_claim(http(), pool, claim_name, args.bind_deadline)
+ step("Waiting for the claim to bind to the warm sandbox")
+ sandbox = wait_bound(http, pool, claim_name, args.bind_timeout, args.poll_interval)
+ info(f"bound to sandbox {sandbox!r}")
+
+ # Connect to EVERY MCP server the double image exposes. Best-effort for
+ # dev: a server that fails to connect is logged and skipped rather than
+ # aborting the whole run, so a partial action space is still usable.
+ conns: list[McpConn] = []
+ for spec in mcp_servers:
+ svc_base = f"/api/svc/{pool}/{sandbox}-{spec.service}"
+ step(f"Waiting for the {spec.label} server (svc {sandbox}-{spec.service}, health {spec.health})")
+ # wait_service_ready(http, f"{svc_base}{spec.health}", args.ready_timeout, args.poll_interval)
+ step(f"Opening MCP session: {spec.label} at {svc_base}{spec.mcp_path}")
+ try:
+ conn = mcp_open(http(), spec, svc_base, client_name=f"mini-swe-multi-mcp-{OS_NAME}")
+ except Exception as e:
+ info(f"could not connect to {spec.label} MCP server: {type(e).__name__}: {e} — skipping (best effort)")
+ continue
+ info(f"session {conn.session_id or '(stateless)'} — {len(conn.tools)} tool(s)")
+ conns.append(conn)
+
+ if not conns:
+ die("no MCP servers connected — cannot run the agent")
+
+ step(f"Running mini-swe-agent (bedrock {model_id}) against {len(conns)} MCP server(s)")
+ info(f"task: {args.task}")
+ result = run_agent(http, conns, bedrock, task=args.task, model_id=model_id,
+ max_steps=args.max_steps, keep_images=args.keep_images)
+ step(f"Agent result: {result[:200]}")
+ finally:
+ print(flush=True)
+ # Always release the claim — success, error, or interrupt — no matter what.
+ release_claim()
+ if args.keep:
+ step(f"Keeping pool/namespace {pool!r} — skipping pool teardown (--keep)")
+ info(f"claim again: POST {claims_url(pool)} (spec.sandboxTemplateRef.name={pool}-template)")
+ info(f"delete it: DELETE {warmpool_url(pool, pool)}, "
+ f"DELETE {template_url(pool, f'{pool}-template')} "
+ f"(and DELETE /api/namespaces/{pool})")
+ elif args.delete_pool:
+ step(f"Tearing down pool {pool!r} (warm pool + template + namespace)")
+ for what, url in ((f"warm pool {pool!r}", warmpool_url(pool, pool)),
+ (f"template {pool}-template", template_url(pool, f"{pool}-template")),
+ (f"namespace {pool!r}", f"/api/namespaces/{pool}")):
+ try:
+ r = http().delete(url)
+ info(f"deleted {what} (HTTP {r.status_code})")
+ except httpx.HTTPError as e:
+ info(f"could not delete {what}: {type(e).__name__}: {e}")
+ else:
+ step(f"Pool {pool!r} is live")
+ info(f"claim again: POST {claims_url(pool)} (spec.sandboxTemplateRef.name={pool}-template)")
+ info(f"delete it: DELETE {warmpool_url(pool, pool)}, "
+ f"DELETE {template_url(pool, f'{pool}-template')} "
+ f"(and DELETE /api/namespaces/{pool})")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/libs/fleet/python-sdk/examples/windows-mini-swe.yaml b/libs/fleet/python-sdk/examples/windows-mini-swe.yaml
new file mode 100644
index 0000000000..3f55ee71c7
--- /dev/null
+++ b/libs/fleet/python-sdk/examples/windows-mini-swe.yaml
@@ -0,0 +1,54 @@
+apiVersion: cua.ai/v1alpha1
+kind: AgentWindowsDoubleMCPRun
+metadata:
+ name: windows-mini-swe
+
+spec:
+ pool:
+ image: 296062593712.dkr.ecr.us-west-2.amazonaws.com/cua-server-windows:latest
+ cpu: 4
+ ram: 4Gi
+ firmware: efi # GPT/UEFI-only Windows image; operator also enables Hyper-V enlightenments for efi
+ replicas: 2
+ minAvailable: 1
+ readinessPort: 8000
+ services:
+ - type: mcp
+ label: computer-server
+ service: server
+ port: 8000
+ mcpPath: /mcp
+ health: /status
+ - type: mcp
+ label: cua-driver
+ service: mcp
+ port: 3000
+ mcpPath: /mcp
+ health: /healthz
+ - type: auxiliary
+ label: novnc
+ service: novnc
+ port: 6080
+ claim:
+ bindDeadline: 600
+ agent:
+ model: us.anthropic.claude-sonnet-4-6
+ task: >-
+ Launch Microsoft Edge in this Windows environment, open
+ https://news.yahoo.com/, inspect the Yahoo News front page, and then
+ report the visible page contents in a concise final message. Do all work
+ inside this remote Windows sandbox, not on the local machine.
+ maxSteps: 60
+ keepImages: 2
+ rollout:
+ templateTimeout: 120
+ warmTimeout: 0
+ bindTimeout: 0
+ readyTimeout: 0
+ pollInterval: 10
+ teardown:
+ # keepPool:false so `--delete-pool` actually tears down (the script's
+ # if-keep/elif-delete precedence ignores --delete-pool when keepPool is
+ # true). With no teardown flags the pool is still left live for reuse.
+ keepPool: false
+ deletePool: false
diff --git a/libs/fleet/python-sdk/openapi3.yaml b/libs/fleet/python-sdk/openapi3.yaml
new file mode 100644
index 0000000000..b4056a5e26
--- /dev/null
+++ b/libs/fleet/python-sdk/openapi3.yaml
@@ -0,0 +1,1246 @@
+openapi: 3.0.3
+info:
+ title: Cyclops CS Backend API
+ description: "Backend sidecar for the cyclops-cs SPA — Keycloak-authenticated key\n\
+ management, authenticated reverse proxies (gateway / k8s / orch), and\nthe in-process\
+ \ OSGym batch driver.\n\nThe batch driver exposes two pool-scoped surfaces:\n\
+ - `/api/batch/{pool}/...` — submit, poll, cancel a single batch by ID\n- `/api/label/{pool}/{label}/...`\
+ \ — aggregate operations across batches\n in `{pool}` that share a `name` field\
+ \ (the \"label\")\n"
+ version: '0.2'
+ contact:
+ name: API Support
+ url: https://cua.ai/support
+servers:
+- url: https://run.cua.ai
+ description: Production
+security:
+- BearerAuth: []
+paths:
+ /healthz:
+ get:
+ summary: Liveness/readiness probe
+ operationId: healthz
+ tags:
+ - health
+ security: []
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HealthResponse'
+ /api/keys:
+ get:
+ summary: List the calling user's API keys
+ operationId: listKeys
+ tags:
+ - keys
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ListKeysResponse'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ post:
+ summary: Create a new API key
+ operationId: createKey
+ description: Creates a Keycloak service-account client owned by the calling
+ user. The returned `client_secret` is shown exactly once.
+ tags:
+ - keys
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/CreateKeyRequest'
+ responses:
+ '201':
+ description: Created
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/CreateKeyResponse'
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ /api/keys/{id}:
+ delete:
+ summary: Revoke an API key by Keycloak client UUID
+ operationId: deleteKey
+ tags:
+ - keys
+ parameters:
+ - name: id
+ in: path
+ required: true
+ description: Keycloak client UUID
+ schema:
+ type: string
+ responses:
+ '204':
+ description: No Content
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ /api/batch/{pool}/submit:
+ post:
+ summary: Submit a batch of rollouts
+ operationId: submitBatch
+ description: 'Asynchronously queues a batch of OSGym rollouts under `{pool}`.
+
+ Returns immediately with a `batch_id`; poll
+
+ `/api/batch/{pool}/{id}/status` for progress and
+
+ `/api/batch/{pool}/{id}/results` for the final payload.
+
+
+ The pool is bound by the URL path; any `pool_name` in the body must
+
+ match the URL pool or the request is rejected with 400.
+
+ '
+ tags:
+ - batch
+ parameters:
+ - name: pool
+ in: path
+ required: true
+ description: Pool name (DNS-1123 label)
+ schema:
+ type: string
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/BatchSubmitRequest'
+ responses:
+ '202':
+ description: Accepted
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/BatchSubmitResponse'
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ /api/batch/{pool}/lanes:
+ post:
+ summary: Acquire warm VM lanes
+ operationId: acquireLanes
+ description: 'Explicitly provisions N warm VMs ("lanes") and returns their vm_ids.
+ Pass each as `RunConfig.vm_id` to run actions on it (state persists across
+ batches), and `DELETE` this route to release them. All-or-nothing: a partial
+ acquisition is rolled back, and 503 is returned if the pool can''t supply
+ every lane in time.'
+ tags:
+ - batch
+ parameters:
+ - name: pool
+ in: path
+ required: true
+ description: Pool name
+ schema:
+ type: string
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/AcquireLanesRequest'
+ responses:
+ '200':
+ description: Lanes acquired
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/AcquireLanesResponse'
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '503':
+ description: Pool could not supply the requested lanes
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorResponse'
+ delete:
+ summary: Release warm VM lanes
+ operationId: releaseLanes
+ description: Shuts down the given VMs (lanes from `acquireLanes` or `vm_id`s
+ returned by a `keep_warm` batch). Best-effort and idempotent — unknown or
+ already-gone ids are ignored.
+ tags:
+ - batch
+ parameters:
+ - name: pool
+ in: path
+ required: true
+ description: Pool name
+ schema:
+ type: string
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ReleaseLanesRequest'
+ responses:
+ '200':
+ description: Release accepted
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ReleaseLanesResponse'
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ /api/batch/{pool}/{id}/status:
+ get:
+ summary: Poll batch progress
+ operationId: getBatchStatus
+ tags:
+ - batch
+ parameters:
+ - name: pool
+ in: path
+ required: true
+ description: Pool name
+ schema:
+ type: string
+ - name: id
+ in: path
+ required: true
+ description: Batch ID (UUID returned by submit)
+ schema:
+ type: string
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/BatchStatusResponse'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '404':
+ $ref: '#/components/responses/NotFound'
+ /api/batch/{pool}/{id}/results:
+ get:
+ summary: Final batch results
+ operationId: getBatchResults
+ description: 'Returns 200 with the full results once the batch is in a terminal
+
+ status (completed/failed). While still running, returns 202 with a
+
+ `message` field.
+
+ '
+ tags:
+ - batch
+ parameters:
+ - name: pool
+ in: path
+ required: true
+ description: Pool name
+ schema:
+ type: string
+ - name: id
+ in: path
+ required: true
+ description: Batch ID
+ schema:
+ type: string
+ responses:
+ '200':
+ description: Completed — full results
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/BatchResultsResponse'
+ '202':
+ description: Still running
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/BatchInProgressResponse'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '404':
+ $ref: '#/components/responses/NotFound'
+ /api/batch/{pool}/{id}:
+ delete:
+ summary: Cancel a batch
+ operationId: cancelBatch
+ description: 'Hard-cancels the batch — aborts in-flight /reset and /step calls
+
+ and stops dispatch. Idempotent on terminal batches. Returns 200
+
+ with the final status.
+
+ '
+ tags:
+ - batch
+ parameters:
+ - name: pool
+ in: path
+ required: true
+ description: Pool name
+ schema:
+ type: string
+ - name: id
+ in: path
+ required: true
+ description: Batch ID
+ schema:
+ type: string
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/CancelBatchResponse'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '404':
+ $ref: '#/components/responses/NotFound'
+ /api/label/{pool}/{label}/batch:
+ post:
+ summary: Submit a batch under a pool and label
+ operationId: submitLabelBatch
+ description: 'Same as `/api/batch/{pool}/submit` but pins the batch''s `name`
+
+ field to the URL label, overriding any value in the body. The
+
+ label is scoped to `{pool}`; aggregate routes under
+
+ `/api/label/{pool}/{label}/*` only see batches submitted to the
+
+ same pool.
+
+ '
+ tags:
+ - label
+ parameters:
+ - name: pool
+ in: path
+ required: true
+ description: Pool name (DNS-1123 label)
+ schema:
+ type: string
+ - name: label
+ in: path
+ required: true
+ description: Batch label / name
+ schema:
+ type: string
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/BatchSubmitRequest'
+ responses:
+ '202':
+ description: Accepted
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/BatchSubmitResponse'
+ '400':
+ $ref: '#/components/responses/BadRequest'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ /api/label/{pool}/{label}/status:
+ get:
+ summary: Aggregate status for all batches under a pool+label
+ operationId: getLabelStatus
+ description: Aggregates only batches submitted under `{pool}`; batches with
+ the same label in other pools are invisible.
+ tags:
+ - label
+ parameters:
+ - name: pool
+ in: path
+ required: true
+ description: Pool name
+ schema:
+ type: string
+ - name: label
+ in: path
+ required: true
+ description: Batch label
+ schema:
+ type: string
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/LabelStatusResponse'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '404':
+ $ref: '#/components/responses/NotFound'
+ /api/label/{pool}/{label}/results:
+ get:
+ summary: Aggregate results for all batches under a pool+label
+ operationId: getLabelResults
+ description: 'Default mode returns 200 only once every matched batch is completed.
+
+ Pass `?completed_only=true` to drain partial results (200 with the
+
+ filtered subset; non-completed batches are visible via status).
+
+ Aggregates only batches submitted under `{pool}`.
+
+ '
+ tags:
+ - label
+ parameters:
+ - name: pool
+ in: path
+ required: true
+ description: Pool name
+ schema:
+ type: string
+ - name: label
+ in: path
+ required: true
+ description: Batch label
+ schema:
+ type: string
+ - name: completed_only
+ in: query
+ required: false
+ description: Return completed batches only (drain mode)
+ schema:
+ type: boolean
+ responses:
+ '200':
+ description: OK — all batches completed (or drain mode)
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/LabelResultsResponse'
+ '202':
+ description: Still running (non-drain mode)
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/LabelInProgressResponse'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '404':
+ $ref: '#/components/responses/NotFound'
+ /api/label/{pool}/{label}:
+ delete:
+ summary: Cancel every non-terminal batch under a label (scoped to pool)
+ operationId: cancelLabel
+ description: Cancels only batches submitted under `{pool}`; same label in other
+ pools is untouched.
+ tags:
+ - label
+ parameters:
+ - name: pool
+ in: path
+ required: true
+ description: Pool name
+ schema:
+ type: string
+ - name: label
+ in: path
+ required: true
+ description: Batch label
+ schema:
+ type: string
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/CancelLabelResponse'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '404':
+ $ref: '#/components/responses/NotFound'
+ /api/gateway/{pool}/lanes:
+ post:
+ summary: Create Lane
+ description: 'Create a lane: a fresh OSGymSandboxClaim bound to a Sandbox.
+
+
+ The lane id is the stable handle the customer holds. The
+
+ underlying claim CR''s name rotates on swap; the lane id does
+
+ not. The initial bind is via the normal queue+CAS-PATCH flow,
+
+ same as /reset.'
+ operationId: create_lane_lanes_post
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/LaneCreateRequest'
+ required: true
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/LaneResponse'
+ '503':
+ description: Bind timeout — warm pool exhausted
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/LaneErrorResponse'
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ parameters:
+ - name: pool
+ in: path
+ required: true
+ schema:
+ type: string
+ description: Pool name (DNS-1123 label)
+ tags:
+ - lanes
+ /api/gateway/{pool}/lanes/{lane_id}/swap:
+ post:
+ summary: Swap
+ description: 'New-first claim rotation for ``lane_id``.
+
+
+ Calls into the pure protocol body in osgym/lane_swap.py with a
+
+ K8s-backed SwapDeps. The lane keeps its bound VM if the swap
+
+ bind times out (SwapAtomicity); the new vm_id is returned on
+
+ success.'
+ operationId: swap_lanes__lane_id__swap_post
+ parameters:
+ - name: pool
+ in: path
+ required: true
+ schema:
+ type: string
+ description: Pool name (DNS-1123 label)
+ - name: lane_id
+ in: path
+ required: true
+ schema:
+ type: string
+ title: Lane Id
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/LaneSwapResponse'
+ '404':
+ description: Lane not found
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/LaneErrorResponse'
+ '503':
+ description: Swap bind timeout — old VM retained
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/LaneErrorResponse'
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ tags:
+ - lanes
+ /api/gateway/{pool}/lanes/{lane_id}:
+ delete:
+ summary: Delete Lane
+ description: Release the lane's bound claim. Idempotent.
+ operationId: delete_lane_lanes__lane_id__delete
+ parameters:
+ - name: pool
+ in: path
+ required: true
+ schema:
+ type: string
+ description: Pool name (DNS-1123 label)
+ - name: lane_id
+ in: path
+ required: true
+ schema:
+ type: string
+ title: Lane Id
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/LaneDeleteResponse'
+ '404':
+ description: Lane not found
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/LaneErrorResponse'
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ tags:
+ - lanes
+components:
+ securitySchemes:
+ BearerAuth:
+ type: http
+ scheme: bearer
+ description: "Keycloak access token.\n- For `/api/keys` and `/api/{k8s,orch}`:\
+ \ SPA user JWT (azp=cyclops-cs-spa).\n- For `/api/batch/{pool}/*` and `/api/label/{pool}/*`:\
+ \ service-account JWT\n minted via `client_credentials` against a per-key\
+ \ client; the token's\n `namespace` claim must equal `pool-{pool}` (OPA-enforced).\
+ \ SPA tokens\n may target any pool.\n"
+ responses:
+ BadRequest:
+ description: Bad Request
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorResponse'
+ Unauthorized:
+ description: Unauthorized
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorResponse'
+ Forbidden:
+ description: Forbidden
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorResponse'
+ NotFound:
+ description: Not Found
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorResponse'
+ schemas:
+ ErrorResponse:
+ type: object
+ properties:
+ error:
+ type: string
+ HealthResponse:
+ type: object
+ properties:
+ ok:
+ type: boolean
+ KeyClient:
+ type: object
+ properties:
+ id:
+ type: string
+ client_id:
+ type: string
+ name:
+ type: string
+ namespace:
+ type: string
+ owner_sub:
+ type: string
+ ListKeysResponse:
+ type: object
+ properties:
+ keys:
+ type: array
+ items:
+ $ref: '#/components/schemas/KeyClient'
+ CreateKeyRequest:
+ type: object
+ required:
+ - name
+ - namespace
+ properties:
+ name:
+ type: string
+ example: ci-prod
+ namespace:
+ type: string
+ example: test-pool
+ CreateKeyResponse:
+ type: object
+ properties:
+ client_id:
+ type: string
+ client_secret:
+ type: string
+ name:
+ type: string
+ namespace:
+ type: string
+ token_url:
+ type: string
+ Action:
+ type: object
+ required:
+ - action_type
+ properties:
+ action_type:
+ type: string
+ description: OSGym action type (e.g. CLICK, TYPE, KEY).
+ example: CLICK
+ parameters:
+ type: object
+ additionalProperties: true
+ description: Action-type-specific parameters (e.g. `{x, y, button}` for
+ CLICK).
+ RunConfig:
+ type: object
+ required:
+ - steps
+ properties:
+ steps:
+ type: array
+ description: 'Ordered actions to execute on the rollout VM. A step with
+ `action_type: "RESET"` is a reserved control action: instead of being
+ forwarded to the VM, it hard-resets the VM in place (new vm_id, clean
+ baseline desktop), so one run can execute several independent episodes
+ on a warm instance.'
+ items:
+ $ref: '#/components/schemas/Action'
+ maxItems: 10000
+ timeout:
+ type: integer
+ minimum: 0
+ maximum: 86400
+ description: Per-rollout timeout in seconds (max 24h).
+ vm_id:
+ type: string
+ description: Reattach this run to an existing warm VM (instance reuse /
+ "lane"), typically a vm_id returned by a previous `keep_warm` batch, instead
+ of acquiring a fresh one. If that claim has already expired, the run transparently
+ falls back to a fresh VM.
+ BatchSubmitRequest:
+ type: object
+ required:
+ - runs
+ properties:
+ runs:
+ type: array
+ items:
+ $ref: '#/components/schemas/RunConfig'
+ maxItems: 10000
+ concurrency:
+ type: integer
+ default: 10
+ minimum: 1
+ maximum: 1000
+ pool_name:
+ type: string
+ description: Optional — must match the URL `{pool}` if provided; ignored
+ otherwise.
+ name:
+ type: string
+ description: Optional batch name. Overridden by the URL `{label}` on label
+ routes.
+ maxLength: 256
+ keep_warm:
+ type: boolean
+ description: 'Leave each run''s VM running when the run ends (instead of
+ shutting it down), so a follow-up batch can reattach to it via RunConfig.vm_id
+ (read each lane''s surviving id from RunResult.vm_id). Best-effort: a
+ warm VM is reaped after its claim TTL (~minutes), after which reattach
+ falls back to a fresh VM.'
+ BatchSubmitResponse:
+ type: object
+ properties:
+ batch_id:
+ type: string
+ name:
+ type: string
+ status:
+ type: string
+ created_at:
+ type: string
+ format: date-time
+ AcquireLanesRequest:
+ type: object
+ required:
+ - n
+ properties:
+ n:
+ type: integer
+ minimum: 1
+ maximum: 1000
+ description: Number of warm VM lanes to acquire.
+ AcquireLanesResponse:
+ type: object
+ properties:
+ vm_ids:
+ type: array
+ description: One warm VM id per acquired lane. Use as RunConfig.vm_id.
+ items:
+ type: string
+ ReleaseLanesRequest:
+ type: object
+ required:
+ - vm_ids
+ properties:
+ vm_ids:
+ type: array
+ description: VM ids to shut down (lanes to release).
+ items:
+ type: string
+ ReleaseLanesResponse:
+ type: object
+ properties:
+ released:
+ type: integer
+ description: Number of vm_ids submitted for release.
+ BatchProgress:
+ type: object
+ properties:
+ completed:
+ type: integer
+ total:
+ type: integer
+ ok:
+ type: integer
+ failed:
+ type: integer
+ BatchStatusResponse:
+ type: object
+ properties:
+ batch_id:
+ type: string
+ name:
+ type: string
+ status:
+ type: string
+ progress:
+ $ref: '#/components/schemas/BatchProgress'
+ created_at:
+ type: string
+ format: date-time
+ updated_at:
+ type: string
+ format: date-time
+ BatchInProgressResponse:
+ type: object
+ properties:
+ batch_id:
+ type: string
+ status:
+ type: string
+ message:
+ type: string
+ CancelBatchResponse:
+ type: object
+ properties:
+ batch_id:
+ type: string
+ status:
+ type: string
+ TimingStats:
+ type: object
+ properties:
+ n:
+ type: integer
+ min:
+ type: integer
+ format: int64
+ mean:
+ type: number
+ format: double
+ max:
+ type: integer
+ format: int64
+ BatchSummary:
+ type: object
+ properties:
+ n_ok:
+ type: integer
+ n_fail:
+ type: integer
+ total_wall_ms:
+ type: integer
+ format: int64
+ reset_stats:
+ $ref: '#/components/schemas/TimingStats'
+ step_stats:
+ $ref: '#/components/schemas/TimingStats'
+ shutdown_stats:
+ $ref: '#/components/schemas/TimingStats'
+ RunResult:
+ type: object
+ properties:
+ run_id:
+ type: integer
+ vm_id:
+ type: string
+ ok:
+ type: boolean
+ error:
+ type: string
+ reset_ms:
+ type: integer
+ format: int64
+ step_ms:
+ type: array
+ items:
+ type: integer
+ format: int64
+ shutdown_ms:
+ type: integer
+ format: int64
+ actions:
+ type: array
+ items:
+ type: string
+ screenshots:
+ type: array
+ items:
+ type: string
+ BatchResultsResponse:
+ type: object
+ properties:
+ batch_id:
+ type: string
+ name:
+ type: string
+ status:
+ type: string
+ runs:
+ type: array
+ items:
+ $ref: '#/components/schemas/RunResult'
+ s3_bucket:
+ type: string
+ s3_key:
+ type: string
+ s3_presigned_url:
+ type: string
+ summary:
+ $ref: '#/components/schemas/BatchSummary'
+ LabelBatchSummary:
+ type: object
+ properties:
+ batch_id:
+ type: string
+ status:
+ type: string
+ progress:
+ $ref: '#/components/schemas/BatchProgress'
+ created_at:
+ type: string
+ format: date-time
+ updated_at:
+ type: string
+ format: date-time
+ s3_key:
+ type: string
+ s3_presigned_url:
+ type: string
+ LabelStatusResponse:
+ type: object
+ properties:
+ label:
+ type: string
+ batch_count:
+ type: integer
+ all_completed:
+ type: boolean
+ progress:
+ $ref: '#/components/schemas/BatchProgress'
+ batches:
+ type: array
+ items:
+ $ref: '#/components/schemas/LabelBatchSummary'
+ LabelInProgressResponse:
+ type: object
+ properties:
+ label:
+ type: string
+ batch_count:
+ type: integer
+ all_completed:
+ type: boolean
+ message:
+ type: string
+ LabelResultsResponse:
+ type: object
+ properties:
+ label:
+ type: string
+ batch_count:
+ type: integer
+ completed_batch_count:
+ type: integer
+ all_completed:
+ type: boolean
+ batches:
+ type: array
+ items:
+ $ref: '#/components/schemas/BatchResultsResponse'
+ summary:
+ $ref: '#/components/schemas/BatchSummary'
+ CancelLabelBatchItem:
+ type: object
+ properties:
+ batch_id:
+ type: string
+ status:
+ type: string
+ CancelLabelResponse:
+ type: object
+ properties:
+ label:
+ type: string
+ batch_count:
+ type: integer
+ cancelled_count:
+ type: integer
+ already_done:
+ type: integer
+ batches:
+ type: array
+ items:
+ $ref: '#/components/schemas/CancelLabelBatchItem'
+ HealthzResponse:
+ properties:
+ status:
+ type: string
+ title: Status
+ type: object
+ required:
+ - status
+ title: HealthzResponse
+ LaneCreateRequest:
+ properties:
+ ttl_seconds:
+ type: integer
+ title: Ttl Seconds
+ default: 300
+ type: object
+ title: LaneCreateRequest
+ description: 'Body of POST /lanes.
+
+
+ ``ttl_seconds`` is the absolute time the claim is reserved for;
+
+ after that the reaper deletes it. With ``autoRenew=true`` the lane
+
+ auto-renew timer in pool-operator pushes this forward, so the
+
+ customer''s effective TTL is "as long as the lane exists".'
+ LaneDeleteResponse:
+ properties:
+ lane_id:
+ type: string
+ title: Lane Id
+ type: object
+ required:
+ - lane_id
+ title: LaneDeleteResponse
+ LaneResponse:
+ properties:
+ lane_id:
+ type: string
+ title: Lane Id
+ vm_id:
+ type: string
+ title: Vm Id
+ screenshot:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Screenshot
+ type: object
+ required:
+ - lane_id
+ - vm_id
+ title: LaneResponse
+ LaneSwapResponse:
+ properties:
+ lane_id:
+ type: string
+ title: Lane Id
+ vm_id:
+ type: string
+ title: Vm Id
+ wait_seconds:
+ type: number
+ title: Wait Seconds
+ type: object
+ required:
+ - lane_id
+ - vm_id
+ - wait_seconds
+ title: LaneSwapResponse
+ PoolListResponse:
+ properties:
+ vms:
+ items:
+ additionalProperties: true
+ type: object
+ type: array
+ title: Vms
+ count:
+ type: integer
+ title: Count
+ type: object
+ required:
+ - vms
+ - count
+ title: PoolListResponse
+ ResetRequest:
+ properties:
+ task_config:
+ additionalProperties: true
+ type: object
+ title: Task Config
+ timeout:
+ type: integer
+ title: Timeout
+ type: object
+ required:
+ - task_config
+ - timeout
+ title: ResetRequest
+ ResetResponse:
+ properties:
+ screenshot:
+ type: string
+ title: Screenshot
+ problem:
+ type: string
+ title: Problem
+ vm_id:
+ type: string
+ title: Vm Id
+ type: object
+ required:
+ - screenshot
+ - problem
+ - vm_id
+ title: ResetResponse
+ ScreenshotResponse:
+ properties:
+ screenshot:
+ type: string
+ title: Screenshot
+ vm_id:
+ type: string
+ title: Vm Id
+ type: object
+ required:
+ - screenshot
+ - vm_id
+ title: ScreenshotResponse
+ ShutdownRequest:
+ properties:
+ vm_id:
+ type: string
+ title: Vm Id
+ type: object
+ required:
+ - vm_id
+ title: ShutdownRequest
+ ShutdownResponse:
+ properties:
+ vm_id:
+ type: string
+ title: Vm Id
+ type: object
+ required:
+ - vm_id
+ title: ShutdownResponse
+ StepRequest:
+ properties:
+ action:
+ type: string
+ title: Action
+ vm_id:
+ type: string
+ title: Vm Id
+ timeout:
+ type: integer
+ title: Timeout
+ default: 300
+ type: object
+ required:
+ - action
+ - vm_id
+ title: StepRequest
+ StepResponse:
+ properties:
+ screenshot:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Screenshot
+ is_finish:
+ type: boolean
+ title: Is Finish
+ reward:
+ type: number
+ title: Reward
+ type: object
+ required:
+ - screenshot
+ - is_finish
+ - reward
+ title: StepResponse
+ LaneErrorResponse:
+ properties:
+ message:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Message
+ reason:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Reason
+ lane_id:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Lane Id
+ type: object
+ title: ErrorResponse
diff --git a/libs/fleet/python-sdk/package.nix b/libs/fleet/python-sdk/package.nix
new file mode 100644
index 0000000000..ce60b8c7f6
--- /dev/null
+++ b/libs/fleet/python-sdk/package.nix
@@ -0,0 +1,140 @@
+# Nix package for the cua-train Python SDK.
+#
+# Single-step build:
+# 1. Import the osgym FastAPI app (fake backend) → dump openapi.json
+# 2. Merge lane endpoints into parent openapi3.yaml
+# 3. Regenerate api/ + models/ with openapi-python-client
+# 4. Format with ruff
+# 5. Build the wheel
+#
+# Usage:
+# nix build .#cua-train-sdk
+# pip install result/*.whl
+{
+ pkgs,
+ lib ? pkgs.lib,
+ # Build against a caller-supplied interpreter so consumers (e.g. the
+ # cua-temporal-agent worker env) can keep the package on the same Python as
+ # the rest of their closure. Defaults to 3.12 for the standalone `nix build`.
+ python ? pkgs.python312,
+}:
+
+let
+ pp = python.pkgs;
+
+ osgymSrc = builtins.path {
+ path = ../../osgym;
+ name = "osgym-src";
+ };
+
+ # Python with deps needed to import the osgym FastAPI app (fake backend)
+ # AND to run the merge script.
+ genPython = python.withPackages (
+ ps: with ps; [
+ fastapi
+ pydantic
+ uvicorn
+ aiohttp
+ prometheus-client
+ kubernetes
+ pyyaml
+ ruff
+ ]
+ );
+
+in
+pp.buildPythonPackage {
+ pname = "cua-train";
+ version = "0.1.3";
+ pyproject = true;
+
+ src = builtins.path {
+ path = ./.;
+ name = "cua-train-sdk-src";
+ filter =
+ path: type:
+ let
+ base = builtins.baseNameOf path;
+ in
+ !(
+ base == ".venv"
+ || base == "__pycache__"
+ || base == "dist"
+ || base == ".pytest_cache"
+ || lib.hasSuffix ".egg-info" base
+ );
+ };
+
+ build-system = [ pp.hatchling ];
+
+ nativeBuildInputs = [
+ genPython
+ pkgs.openapi-python-client
+ ];
+
+ dependencies = with pp; [
+ httpx
+ attrs
+ python-dateutil
+ ];
+
+ preBuild = ''
+ echo "==> Generating orchestrator OpenAPI spec"
+ PYTHONPATH="${osgymSrc}" \
+ OSGYM_POOL_BACKEND=fake \
+ OSGYM_ALLOWED_IPS=0.0.0.0/0 \
+ ${genPython}/bin/python -c "
+ import json, sys, io
+
+ # Suppress all stdout noise from osgym imports (log messages, banners)
+ real_stdout = sys.stdout
+ sys.stdout = io.StringIO()
+ try:
+ # Lanes were decoupled out of the orchestrator (osgym #4953), so the
+ # old \`from lane_endpoints import register\` no longer exists. The lane
+ # paths now live in the committed openapi3.yaml (the merge below only
+ # ADDS osgym paths, never drops the parent's), so plain app.openapi()
+ # is the correct spec source.
+ from main import app
+ spec = app.openapi()
+ finally:
+ sys.stdout = real_stdout
+
+ json.dump(spec, sys.stdout, indent=2)
+ " > /tmp/orch-spec.json
+ echo " Spec: $(wc -l < /tmp/orch-spec.json) lines"
+ test -s /tmp/orch-spec.json || { echo "FATAL: empty spec"; exit 1; }
+
+ echo "==> Merging lane endpoints"
+ cat /tmp/orch-spec.json | head -3
+ ${genPython}/bin/python scripts/merge_orchestrator_spec.py \
+ --parent openapi3.yaml \
+ --orchestrator /tmp/orch-spec.json \
+ --output openapi3.yaml
+
+ echo "==> Regenerating SDK"
+ openapi-python-client update --path openapi3.yaml || true # lint-ignore: error-masking — may fail on first run
+
+ echo "==> Formatting"
+ ${genPython}/bin/python -m ruff check --fix cua_train/ 2>/dev/null || true # lint-ignore: error-masking — best-effort autofix
+ ${genPython}/bin/python -m ruff format cua_train/
+ '';
+
+ nativeCheckInputs = with pp; [
+ pytestCheckHook
+ pytest-httpx
+ ];
+
+ # test_wheel_build stages the wheel from the repo-absolute path
+ # /cyclops-cs/python-sdk (valid in the cyclops-cs repo CI container, absent in
+ # the Nix sandbox) -> FileNotFoundError, which failed every worker image
+ # build on main. Environment-dependent, not a property of the package: skip.
+ disabledTestPaths = [ "tests/test_wheel_build.py" ];
+
+ pythonImportsCheck = [ "cua_train" ];
+
+ meta = {
+ description = "Python SDK for the CUA training / batch backend API";
+ license = lib.licenses.mit;
+ };
+}
diff --git a/libs/fleet/python-sdk/pyproject.toml b/libs/fleet/python-sdk/pyproject.toml
new file mode 100644
index 0000000000..d10daac1b6
--- /dev/null
+++ b/libs/fleet/python-sdk/pyproject.toml
@@ -0,0 +1,38 @@
+[build-system]
+requires = ["hatchling"]
+build-backend = "hatchling.build"
+
+[project]
+name = "cua-train"
+version = "0.1.6"
+description = "Python SDK for the CUA training / batch backend API — generated from OpenAPI spec."
+readme = "README.md"
+license = { text = "MIT" }
+authors = [{ name = "TryCua", email = "[email protected]" }]
+requires-python = ">=3.10"
+dependencies = [
+ "httpx>=0.23.0",
+ "attrs>=22.2.0",
+ "python-dateutil>=2.8.0",
+]
+
+[project.urls]
+Repository = "https://github.com/trycua/cloud"
+"Issue Tracker" = "https://github.com/trycua/cloud/issues"
+
+[tool.hatch.build.targets.wheel]
+packages = ["cua_train"]
+
+[project.optional-dependencies]
+dev = [
+ "build>=1.2",
+ "pytest>=7.0",
+ "pytest-httpx>=0.30.0",
+ "ruff>=0.6",
+]
+
+[tool.ruff]
+line-length = 120
+
+[tool.ruff.lint]
+select = ["F", "I", "UP"]
diff --git a/libs/fleet/python-sdk/scripts/build_wheel.py b/libs/fleet/python-sdk/scripts/build_wheel.py
new file mode 100755
index 0000000000..74a07a6fa5
--- /dev/null
+++ b/libs/fleet/python-sdk/scripts/build_wheel.py
@@ -0,0 +1,210 @@
+#!/usr/bin/env python3
+"""Build a platform wheel containing the generated Fleet Python binding."""
+
+from __future__ import annotations
+
+import argparse
+import base64
+import csv
+import hashlib
+import platform
+import shutil
+import subprocess
+import sys
+import tempfile
+import zipfile
+from pathlib import Path
+
+PACKAGE_NAME = "cua_train"
+NATIVE_PACKAGE = "fleet_sdk"
+
+
+def parse_args() -> argparse.Namespace:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--outdir", type=Path, default=Path("dist"))
+ parser.add_argument("--native-library", type=Path)
+ parser.add_argument("--platform-tag")
+ parser.add_argument("--cargo-target")
+ return parser.parse_args()
+
+
+def repository_root() -> Path:
+ return Path(__file__).resolve().parents[3]
+
+
+def native_library_name() -> str:
+ if sys.platform == "darwin":
+ return "libcyclops_sdk.dylib"
+ if sys.platform.startswith("linux"):
+ return "libcyclops_sdk.so"
+ if sys.platform.startswith("win"):
+ return "cyclops_sdk.dll"
+ raise RuntimeError(f"unsupported wheel build platform: {sys.platform}")
+
+
+def default_platform_tag() -> str:
+ machine = platform.machine().lower()
+ aliases = {"amd64": "x86_64", "aarch64": "arm64"}
+ machine = aliases.get(machine, machine)
+
+ if sys.platform.startswith("linux"):
+ linux_arches = {"x86_64": "x86_64", "arm64": "aarch64"}
+ try:
+ return f"linux_{linux_arches[machine]}"
+ except KeyError as error:
+ raise RuntimeError(f"unsupported Linux architecture: {machine}") from error
+
+ if sys.platform == "darwin":
+ macos_versions = {"x86_64": "10_13", "arm64": "11_0"}
+ try:
+ return f"macosx_{macos_versions[machine]}_{machine}"
+ except KeyError as error:
+ raise RuntimeError(f"unsupported macOS architecture: {machine}") from error
+
+ if sys.platform.startswith("win"):
+ if machine != "x86_64":
+ raise RuntimeError(f"unsupported Windows architecture: {machine}")
+ return "win_amd64"
+
+ raise RuntimeError(f"unsupported wheel build platform: {sys.platform}")
+
+
+def native_library_name_for_platform_tag(platform_tag: str) -> str:
+ if platform_tag == "win_amd64":
+ return "cyclops_sdk.dll"
+ if platform_tag.startswith("linux_"):
+ return "libcyclops_sdk.so"
+ if platform_tag.startswith("macosx_"):
+ return "libcyclops_sdk.dylib"
+ raise RuntimeError(f"unsupported wheel platform tag: {platform_tag}")
+
+
+def build_native_library(repo_root: Path, cargo_target: str | None) -> Path:
+ command = [
+ "cargo",
+ "build",
+ "--locked",
+ "--manifest-path",
+ str(repo_root / "cyclops-cs" / "Cargo.toml"),
+ "--package",
+ "cyclops-sdk",
+ "--release",
+ ]
+ if cargo_target:
+ command.extend(["--target", cargo_target])
+ subprocess.run(command, check=True)
+
+ target_directory = repo_root / "cyclops-cs" / "target"
+ if cargo_target:
+ target_directory /= cargo_target
+ library = target_directory / "release" / native_library_name()
+ if not library.is_file():
+ raise RuntimeError(f"Cargo did not produce expected native library: {library}")
+ return library
+
+
+def stage_project(repo_root: Path, stage_root: Path, library: Path, native_library: str) -> None:
+ source = repo_root / "cyclops-cs" / "python-sdk"
+ shutil.copytree(
+ source,
+ stage_root,
+ ignore=shutil.ignore_patterns("build", "dist", "*.egg-info", ".pytest_cache", "__pycache__", ".venv"),
+ )
+ shutil.copytree(repo_root / "cyclops-cs" / "sdk-bindings" / "python" / NATIVE_PACKAGE, stage_root / NATIVE_PACKAGE)
+ shutil.copy2(library, stage_root / NATIVE_PACKAGE / native_library)
+
+ pyproject = stage_root / "pyproject.toml"
+ contents = pyproject.read_text()
+ expected = 'packages = ["cua_train"]'
+ replacement = 'packages = ["cua_train", "fleet_sdk"]'
+ if expected not in contents:
+ raise RuntimeError(f"could not configure staged package list in {pyproject}")
+ pyproject.write_text(contents.replace(expected, replacement, 1))
+
+
+def record_line(filename: str, data: bytes) -> list[str]:
+ digest = base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode()
+ return [filename, f"sha256={digest}", str(len(data))]
+
+
+def retag_wheel(wheel: Path, platform_tag: str) -> Path:
+ with zipfile.ZipFile(wheel) as source:
+ entries = {
+ entry.filename: source.read(entry.filename)
+ for entry in source.infolist()
+ if not entry.filename.endswith(".dist-info/RECORD")
+ }
+
+ wheel_metadata_name = next(name for name in entries if name.endswith(".dist-info/WHEEL"))
+ wheel_metadata = entries[wheel_metadata_name].decode().splitlines()
+ updated_metadata = [
+ "Root-Is-Purelib: false" if line == "Root-Is-Purelib: true" else line
+ for line in wheel_metadata
+ if not line.startswith("Tag: ")
+ ]
+ updated_metadata.append(f"Tag: py3-none-{platform_tag}")
+ entries[wheel_metadata_name] = ("\n".join(updated_metadata) + "\n").encode()
+
+ distribution = wheel.name.split("-")[0]
+ version = wheel.name.split("-")[1]
+ retagged = wheel.with_name(f"{distribution}-{version}-py3-none-{platform_tag}.whl")
+ record_name = next(name for name in entries if name.endswith(".dist-info/WHEEL"))
+ record_name = record_name.rsplit("/", 1)[0] + "/RECORD"
+
+ with zipfile.ZipFile(retagged, "w", compression=zipfile.ZIP_DEFLATED) as target:
+ records: list[list[str]] = []
+ for name in sorted(entries):
+ data = entries[name]
+ target.writestr(name, data)
+ records.append(record_line(name, data))
+ records.append([record_name, "", ""])
+ target.writestr(record_name, csv_text(records))
+
+ wheel.unlink()
+ return retagged
+
+
+def csv_text(rows: list[list[str]]) -> str:
+ from io import StringIO
+
+ output = StringIO()
+ csv.writer(output, lineterminator="\n").writerows(rows)
+ return output.getvalue()
+
+
+def main() -> None:
+ args = parse_args()
+ repo_root = repository_root()
+ platform_tag = args.platform_tag or default_platform_tag()
+ expected_library_name = native_library_name_for_platform_tag(platform_tag)
+ library = (
+ args.native_library.resolve()
+ if args.native_library
+ else build_native_library(repo_root, args.cargo_target)
+ )
+ if not library.is_file():
+ raise RuntimeError(f"native library does not exist: {library}")
+ if library.name != expected_library_name:
+ raise RuntimeError(
+ f"native library must be named {expected_library_name} for {platform_tag}: {library}"
+ )
+
+ output = args.outdir.resolve()
+ output.mkdir(parents=True, exist_ok=True)
+ with tempfile.TemporaryDirectory(prefix="cua-train-wheel-") as temporary_directory:
+ stage_root = Path(temporary_directory) / "python-sdk"
+ stage_project(repo_root, stage_root, library, expected_library_name)
+ subprocess.run(
+ [sys.executable, "-m", "build", "--wheel", "--outdir", str(output), str(stage_root)],
+ check=True,
+ )
+
+ wheels = sorted(output.glob(f"{PACKAGE_NAME}-*.whl"))
+ if len(wheels) != 1:
+ raise RuntimeError(f"expected exactly one built wheel in {output}, found: {wheels}")
+ wheel = retag_wheel(wheels[0], platform_tag)
+ print(wheel)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/libs/fleet/python-sdk/scripts/generate.sh b/libs/fleet/python-sdk/scripts/generate.sh
new file mode 100755
index 0000000000..a960d5d9e5
--- /dev/null
+++ b/libs/fleet/python-sdk/scripts/generate.sh
@@ -0,0 +1,54 @@
+#!/usr/bin/env bash
+# Generate the cua_train SDK from the osgym orchestrator's OpenAPI spec.
+#
+# Usage:
+# ./scripts/generate.sh
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+SDK_DIR="$(dirname "$SCRIPT_DIR")"
+OSGYM_DIR="$(cd "$SDK_DIR/../../osgym" && pwd)"
+
+# Bootstrap: re-exec inside nix-shell with a proper Python environment
+if [ -z "${IN_NIX_SHELL:-}" ]; then
+ exec nix-shell --pure -E '
+ let pkgs = import <nixpkgs> {};
+ python = pkgs.python312.withPackages (ps: with ps; [
+ fastapi pydantic uvicorn aiohttp prometheus-client
+ kubernetes pyyaml ruff
+ ]);
+ in pkgs.mkShell {
+ buildInputs = [ python pkgs.openapi-python-client ];
+ shellHook = "export IN_NIX_SHELL=1";
+ }
+ ' --run "bash $0"
+fi
+
+echo "==> Step 1: Generate orchestrator OpenAPI spec"
+ORCH_SPEC=$(mktemp /tmp/osgym-openapi-XXXXXX.json)
+PYTHONPATH="$OSGYM_DIR" \
+ OSGYM_POOL_BACKEND=fake \
+ OSGYM_ALLOWED_IPS=0.0.0.0/0 \
+ python3 -c "
+import json
+from main import app
+print(json.dumps(app.openapi(), indent=2))
+" > "$ORCH_SPEC"
+echo " Wrote $ORCH_SPEC ($(wc -l < "$ORCH_SPEC") lines)"
+
+echo "==> Step 2: Merge lane endpoints into parent openapi3.yaml"
+python3 "$SCRIPT_DIR/merge_orchestrator_spec.py" \
+ --parent "$SDK_DIR/openapi3.yaml" \
+ --orchestrator "$ORCH_SPEC" \
+ --output "$SDK_DIR/openapi3.yaml"
+
+echo "==> Step 3: Regenerate Python SDK"
+cd "$SDK_DIR"
+openapi-python-client update --path openapi3.yaml || true # lint-ignore: error-masking — may fail on first run
+
+echo "==> Step 4: Format"
+python3 -m ruff check --fix cua_train/ 2>/dev/null || true # lint-ignore: error-masking — best-effort autofix
+python3 -m ruff format cua_train/
+
+rm -f "$ORCH_SPEC"
+echo "==> Done. Review changes with: git diff cyclops-cs/python-sdk/"
diff --git a/libs/fleet/python-sdk/scripts/merge_orchestrator_spec.py b/libs/fleet/python-sdk/scripts/merge_orchestrator_spec.py
new file mode 100644
index 0000000000..6a59862a7d
--- /dev/null
+++ b/libs/fleet/python-sdk/scripts/merge_orchestrator_spec.py
@@ -0,0 +1,123 @@
+#!/usr/bin/env python3
+"""Merge the osgym orchestrator's OpenAPI spec into the parent SDK spec.
+
+Rewrites orchestrator paths like /lanes → /api/gateway/{pool}/lanes
+and adds a {pool} path parameter. Merges schemas into components.
+Only merges /lanes endpoints (not /reset, /step, etc. which are
+already covered by the batch driver).
+"""
+import argparse
+import copy
+import json
+import sys
+
+import yaml
+
+
+# Paths from the orchestrator to include (prefix match)
+INCLUDE_PREFIXES = ["/lanes"]
+
+# Schemas to always skip (already in parent or not needed)
+SKIP_SCHEMAS = {"HTTPValidationError", "ValidationError"}
+
+
+def rewrite_path(path: str) -> str:
+ """Rewrite /lanes/... → /api/gateway/{pool}/lanes/..."""
+ return f"/api/gateway/{{pool}}{path}"
+
+
+def add_pool_param(operation: dict) -> None:
+ """Add {pool} path parameter to an operation if not present."""
+ params = operation.setdefault("parameters", [])
+ if any(p.get("name") == "pool" for p in params):
+ return
+ params.insert(0, {
+ "name": "pool",
+ "in": "path",
+ "required": True,
+ "schema": {"type": "string"},
+ "description": "Pool name (DNS-1123 label)",
+ })
+
+
+def fix_ref(obj, old_prefix="#/components/schemas/", renames=None):
+ """Recursively fix $ref pointers after schema renames."""
+ if isinstance(obj, dict):
+ if "$ref" in obj:
+ ref = obj["$ref"]
+ if ref.startswith(old_prefix) and renames:
+ schema_name = ref[len(old_prefix):]
+ if schema_name in renames:
+ obj["$ref"] = f"{old_prefix}{renames[schema_name]}"
+ for v in obj.values():
+ fix_ref(v, old_prefix, renames)
+ elif isinstance(obj, list):
+ for item in obj:
+ fix_ref(item, old_prefix, renames)
+
+
+def merge(parent_path: str, orch_path: str, output_path: str) -> None:
+ with open(parent_path) as f:
+ parent = yaml.safe_load(f)
+ with open(orch_path) as f:
+ orch = json.load(f)
+
+ orch_paths = orch.get("paths", {})
+ orch_schemas = orch.get("components", {}).get("schemas", {})
+
+ # Determine which schemas are referenced by included paths
+ included_paths = {}
+ for path, methods in orch_paths.items():
+ if not any(path.startswith(p) for p in INCLUDE_PREFIXES):
+ continue
+ included_paths[path] = methods
+
+ # Rename schemas with module prefixes (e.g. lane_endpoints__ErrorResponse → LaneErrorResponse)
+ renames = {}
+ for name in orch_schemas:
+ if "__" in name:
+ # lane_endpoints__ErrorResponse → LaneErrorResponse
+ new_name = name.split("__")[-1]
+ # Prefix with "Lane" if it would conflict
+ if new_name in orch_schemas and new_name != name:
+ new_name = f"Lane{new_name}"
+ renames[name] = new_name
+
+ # Add rewritten paths to parent
+ parent_paths = parent.setdefault("paths", {})
+ for path, methods in included_paths.items():
+ new_path = rewrite_path(path)
+ methods = copy.deepcopy(methods)
+ for method, operation in methods.items():
+ if isinstance(operation, dict):
+ add_pool_param(operation)
+ # Tag as "lanes" for SDK grouping
+ operation["tags"] = ["lanes"]
+ fix_ref(operation, renames=renames)
+ parent_paths[new_path] = methods
+
+ # Add schemas to parent
+ parent_schemas = parent.setdefault("components", {}).setdefault("schemas", {})
+ for name, schema in orch_schemas.items():
+ if name in SKIP_SCHEMAS:
+ continue
+ final_name = renames.get(name, name)
+ if final_name not in parent_schemas:
+ schema = copy.deepcopy(schema)
+ fix_ref(schema, renames=renames)
+ parent_schemas[final_name] = schema
+
+ with open(output_path, "w") as f:
+ yaml.dump(parent, f, default_flow_style=False, sort_keys=False, allow_unicode=True)
+
+ added = len(included_paths)
+ print(f" Merged {added} path(s), {len(orch_schemas) - len(SKIP_SCHEMAS)} schema(s)")
+
+
+if __name__ == "__main__":
+ p = argparse.ArgumentParser()
+ p.add_argument("--parent", required=True)
+ p.add_argument("--orchestrator", required=True)
+ p.add_argument("--output", required=True)
+ args = p.parse_args()
+ merge(args.parent, args.orchestrator, args.output)
diff --git a/libs/fleet/python-sdk/tests/__init__.py b/libs/fleet/python-sdk/tests/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/libs/fleet/python-sdk/tests/test_endpoints.py b/libs/fleet/python-sdk/tests/test_endpoints.py
new file mode 100644
index 0000000000..3efa39dfed
--- /dev/null
+++ b/libs/fleet/python-sdk/tests/test_endpoints.py
@@ -0,0 +1,672 @@
+"""
+Parametrized tests for every endpoint in the cyclops-cs SDK.
+
+Uses pytest-httpx to intercept httpx calls so no real server is needed.
+Each endpoint has three test categories:
+ - base: happy-path / golden response
+ - error: 4xx responses parsed into ErrorResponse
+ - generated: edge-case parameter variants
+"""
+
+import pytest
+from pytest_httpx import HTTPXMock
+
+from cua_train import TrainClient
+from cua_train.api.batch import cancel_batch, get_batch_results, get_batch_status, submit_batch
+from cua_train.api.health import healthz
+from cua_train.api.keys import create_key, delete_key, list_keys
+from cua_train.api.label import cancel_label, get_label_results, get_label_status, submit_label_batch
+from cua_train.client import AuthenticatedClient, Client
+from cua_train.models import (
+ Action,
+ ActionParameters,
+ BatchInProgressResponse,
+ BatchResultsResponse,
+ BatchStatusResponse,
+ BatchSubmitRequest,
+ BatchSubmitResponse,
+ CancelBatchResponse,
+ CancelLabelResponse,
+ CreateKeyRequest,
+ CreateKeyResponse,
+ ErrorResponse,
+ HealthResponse,
+ LabelInProgressResponse,
+ LabelResultsResponse,
+ LabelStatusResponse,
+ ListKeysResponse,
+ RunConfig,
+)
+
+BASE_URL = "https://cyclops-cs.trycua.com"
+TOKEN = "test-bearer-token"
+
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
+def anon_client() -> Client:
+ return Client(base_url=BASE_URL, raise_on_unexpected_status=True)
+
+
+def auth_client() -> AuthenticatedClient:
+ # TrainClient is a drop-in AuthenticatedClient that also exposes every
+ # generated endpoint as a method; using it here exercises both the low-level
+ # api.* calls (client=auth_client) and the generic facade (auth_client.<op>).
+ return TrainClient(base_url=BASE_URL, token=TOKEN, raise_on_unexpected_status=True)
+
+
+def test_train_client_refreshes_token(httpx_mock: HTTPXMock):
+ """from_key mints a token, then get_httpx_client() transparently re-mints it
+ once it's near expiry — no caller involvement."""
+ token_ep = "https://auth.example/realms/x/token"
+ # First exchange returns an already-stale token (expires_in=0).
+ httpx_mock.add_response(method="POST", url=token_ep, json={"access_token": "t1", "expires_in": 0})
+ c = TrainClient.from_key(token_url=token_ep, client_id="key-x", client_secret="s", base_url=BASE_URL)
+ assert c.token == "t1"
+
+ # Next use refreshes (deadline already passed) and bakes the new bearer.
+ httpx_mock.add_response(method="POST", url=token_ep, json={"access_token": "t2", "expires_in": 300})
+ client = c.get_httpx_client()
+ assert c.token == "t2"
+ assert client.headers["Authorization"] == "Bearer t2"
+
+
+# ---------------------------------------------------------------------------
+# /healthz
+# ---------------------------------------------------------------------------
+
+
+class TestHealthz:
+ def test_base_ok(self, httpx_mock: HTTPXMock, anon_client):
+ """Golden: healthz returns 200 {ok: true}."""
+ httpx_mock.add_response(
+ method="GET",
+ url=f"{BASE_URL}/healthz",
+ status_code=200,
+ json={"ok": True},
+ )
+ resp = healthz.sync_detailed(client=anon_client)
+ assert resp.status_code.value == 200
+ assert isinstance(resp.parsed, HealthResponse)
+ assert resp.parsed.ok is True
+
+ def test_base_degraded(self, httpx_mock: HTTPXMock, anon_client):
+ """Edge: ok=false still parses cleanly."""
+ httpx_mock.add_response(
+ method="GET",
+ url=f"{BASE_URL}/healthz",
+ status_code=200,
+ json={"ok": False},
+ )
+ assert healthz.sync_detailed(client=anon_client).parsed.ok is False
+
+ def test_unexpected_status(self, httpx_mock: HTTPXMock, anon_client):
+ """Error: unexpected 503 raises when raise_on_unexpected_status=True."""
+ httpx_mock.add_response(
+ method="GET", url=f"{BASE_URL}/healthz", status_code=503, json={"error": "svc unavailable"}
+ )
+ from cua_train import errors
+
+ with pytest.raises(errors.UnexpectedStatus):
+ healthz.sync_detailed(client=anon_client)
+
+
+# ---------------------------------------------------------------------------
+# /api/keys GET
+# ---------------------------------------------------------------------------
+
+
+GOLDEN_KEY = {
+ "id": "kc-uuid-1",
+ "client_id": "key-abc123",
+ "name": "ci-prod",
+ "namespace": "test-pool",
+ "owner_sub": "user-sub-1",
+}
+
+
+class TestListKeys:
+ def test_base(self, httpx_mock: HTTPXMock, auth_client):
+ httpx_mock.add_response(method="GET", url=f"{BASE_URL}/api/keys", status_code=200, json={"keys": [GOLDEN_KEY]})
+ resp = list_keys.sync_detailed(client=auth_client)
+ assert resp.status_code.value == 200
+ assert isinstance(resp.parsed, ListKeysResponse)
+ assert len(resp.parsed.keys) == 1
+ assert resp.parsed.keys[0].name == "ci-prod"
+
+ def test_empty_list(self, httpx_mock: HTTPXMock, auth_client):
+ httpx_mock.add_response(method="GET", url=f"{BASE_URL}/api/keys", status_code=200, json={"keys": []})
+ assert list_keys.sync_detailed(client=auth_client).parsed.keys == []
+
+ def test_unauthorized(self, httpx_mock: HTTPXMock, auth_client):
+ httpx_mock.add_response(
+ method="GET", url=f"{BASE_URL}/api/keys", status_code=401, json={"error": "unauthorized"}
+ )
+ resp = list_keys.sync_detailed(client=auth_client)
+ assert resp.status_code.value == 401
+ assert isinstance(resp.parsed, ErrorResponse)
+
+
+# ---------------------------------------------------------------------------
+# /api/keys POST
+# ---------------------------------------------------------------------------
+
+
+class TestCreateKey:
+ @pytest.mark.parametrize(
+ "name,namespace",
+ [
+ ("ci-prod", "test-pool"),
+ ("my-key", "default"),
+ ("key-with-dashes", "namespace-123"),
+ ],
+ )
+ def test_base(self, httpx_mock: HTTPXMock, auth_client, name, namespace):
+ httpx_mock.add_response(
+ method="POST",
+ url=f"{BASE_URL}/api/keys",
+ status_code=201,
+ json={
+ "client_id": f"key-{name}",
+ "client_secret": "super-secret",
+ "name": name,
+ "namespace": namespace,
+ "token_url": "https://auth.example.com/token",
+ },
+ )
+ resp = create_key.sync_detailed(client=auth_client, body=CreateKeyRequest(name=name, namespace=namespace))
+ assert resp.status_code.value == 201
+ assert isinstance(resp.parsed, CreateKeyResponse)
+ assert resp.parsed.client_secret == "super-secret"
+
+ def test_bad_request(self, httpx_mock: HTTPXMock, auth_client):
+ httpx_mock.add_response(
+ method="POST", url=f"{BASE_URL}/api/keys", status_code=400, json={"error": "name is required"}
+ )
+ resp = create_key.sync_detailed(client=auth_client, body=CreateKeyRequest(name="", namespace="pool"))
+ assert resp.status_code.value == 400
+ assert isinstance(resp.parsed, ErrorResponse)
+
+ def test_forbidden(self, httpx_mock: HTTPXMock, auth_client):
+ httpx_mock.add_response(
+ method="POST", url=f"{BASE_URL}/api/keys", status_code=403, json={"error": "key limit reached"}
+ )
+ resp = create_key.sync_detailed(client=auth_client, body=CreateKeyRequest(name="extra", namespace="pool"))
+ assert resp.status_code.value == 403
+
+
+# ---------------------------------------------------------------------------
+# /api/keys/{id} DELETE
+# ---------------------------------------------------------------------------
+
+
+class TestDeleteKey:
+ @pytest.mark.parametrize("key_id", ["kc-uuid-1", "kc-uuid-2", "00000000-0000-0000-0000-000000000000"])
+ def test_base(self, httpx_mock: HTTPXMock, auth_client, key_id):
+ httpx_mock.add_response(method="DELETE", url=f"{BASE_URL}/api/keys/{key_id}", status_code=204)
+ assert delete_key.sync_detailed(id=key_id, client=auth_client).status_code.value == 204
+
+ def test_forbidden(self, httpx_mock: HTTPXMock, auth_client):
+ httpx_mock.add_response(
+ method="DELETE", url=f"{BASE_URL}/api/keys/other-uuid", status_code=403, json={"error": "not your key"}
+ )
+ assert delete_key.sync_detailed(id="other-uuid", client=auth_client).status_code.value == 403
+
+
+# ---------------------------------------------------------------------------
+# /api/batch/{pool}/submit POST
+# ---------------------------------------------------------------------------
+
+
+GOLDEN_SUBMIT_RESP = {
+ "batch_id": "batch-abc",
+ "name": "my-batch",
+ "status": "queued",
+ "created_at": "2026-05-01T00:00:00Z",
+}
+GOLDEN_RUN = RunConfig(
+ steps=[Action(action_type="CLICK", parameters=ActionParameters.from_dict({"x": 1, "y": 2}))],
+ timeout=60,
+)
+
+
+class TestSubmitBatch:
+ @pytest.mark.parametrize(
+ "pool,concurrency",
+ [
+ ("test-pool", 1),
+ ("prod-pool", 10),
+ ("staging", 50),
+ ],
+ )
+ def test_base(self, httpx_mock: HTTPXMock, auth_client, pool, concurrency):
+ httpx_mock.add_response(
+ method="POST", url=f"{BASE_URL}/api/batch/{pool}/submit", status_code=202, json=GOLDEN_SUBMIT_RESP
+ )
+ resp = submit_batch.sync_detailed(
+ pool=pool, client=auth_client, body=BatchSubmitRequest(runs=[GOLDEN_RUN], concurrency=concurrency)
+ )
+ assert resp.status_code.value == 202
+ assert isinstance(resp.parsed, BatchSubmitResponse)
+ assert resp.parsed.batch_id == "batch-abc"
+
+ def test_bad_request_empty_runs(self, httpx_mock: HTTPXMock, auth_client):
+ httpx_mock.add_response(
+ method="POST",
+ url=f"{BASE_URL}/api/batch/pool/submit",
+ status_code=400,
+ json={"error": "runs must not be empty"},
+ )
+ resp = submit_batch.sync_detailed(pool="pool", client=auth_client, body=BatchSubmitRequest(runs=[]))
+ assert resp.status_code.value == 400
+ assert isinstance(resp.parsed, ErrorResponse)
+
+ def test_flat_wrapper(self, httpx_mock: HTTPXMock, auth_client):
+ httpx_mock.add_response(
+ method="POST", url=f"{BASE_URL}/api/label/test-pool/my-run/batch", status_code=202, json=GOLDEN_SUBMIT_RESP
+ )
+ result = auth_client.submit_label_batch(
+ pool="test-pool", label="my-run", body=BatchSubmitRequest(runs=[GOLDEN_RUN])
+ )
+ assert isinstance(result, BatchSubmitResponse)
+
+
+# ---------------------------------------------------------------------------
+# /api/batch/{pool}/{id}/status GET
+# ---------------------------------------------------------------------------
+
+
+GOLDEN_BATCH_STATUS = {
+ "batch_id": "batch-abc",
+ "name": "my-batch",
+ "status": "running",
+ "progress": {"completed": 3, "total": 10, "ok": 2, "failed": 1},
+ "created_at": "2026-05-01T00:00:00Z",
+ "updated_at": "2026-05-01T00:05:00Z",
+}
+
+
+class TestGetBatchStatus:
+ def test_base(self, httpx_mock: HTTPXMock, auth_client):
+ httpx_mock.add_response(
+ method="GET",
+ url=f"{BASE_URL}/api/batch/test-pool/batch-abc/status",
+ status_code=200,
+ json=GOLDEN_BATCH_STATUS,
+ )
+ resp = get_batch_status.sync_detailed(pool="test-pool", id="batch-abc", client=auth_client)
+ assert resp.status_code.value == 200
+ assert isinstance(resp.parsed, BatchStatusResponse)
+ assert resp.parsed.status == "running"
+
+ def test_not_found(self, httpx_mock: HTTPXMock, auth_client):
+ httpx_mock.add_response(
+ method="GET",
+ url=f"{BASE_URL}/api/batch/test-pool/unknown/status",
+ status_code=404,
+ json={"error": "batch not found"},
+ )
+ resp = get_batch_status.sync_detailed(pool="test-pool", id="unknown", client=auth_client)
+ assert resp.status_code.value == 404
+ assert isinstance(resp.parsed, ErrorResponse)
+
+ @pytest.mark.parametrize("status_val", ["queued", "running", "completed", "failed", "cancelled"])
+ def test_all_statuses(self, httpx_mock: HTTPXMock, auth_client, status_val):
+ body = {**GOLDEN_BATCH_STATUS, "status": status_val}
+ httpx_mock.add_response(
+ method="GET", url=f"{BASE_URL}/api/batch/pool/batch-abc/status", status_code=200, json=body
+ )
+ resp = get_batch_status.sync_detailed(pool="pool", id="batch-abc", client=auth_client)
+ assert resp.parsed.status == status_val
+
+ def test_flat_wrapper(self, httpx_mock: HTTPXMock, auth_client):
+ httpx_mock.add_response(
+ method="GET", url=f"{BASE_URL}/api/label/pool/test-label/status", status_code=200, json=GOLDEN_LABEL_STATUS
+ )
+ result = auth_client.get_label_status(pool="pool", label="test-label")
+ assert isinstance(result, LabelStatusResponse)
+
+
+# ---------------------------------------------------------------------------
+# /api/batch/{pool}/{id}/results GET
+# ---------------------------------------------------------------------------
+
+
+GOLDEN_BATCH_RESULTS = {
+ "batch_id": "batch-abc",
+ "name": "my-batch",
+ "status": "completed",
+ "runs": [
+ {
+ "run_id": 1,
+ "vm_id": "vm-1",
+ "ok": True,
+ "reset_ms": 100,
+ "step_ms": [200],
+ "shutdown_ms": 50,
+ "actions": [],
+ "screenshots": [],
+ }
+ ],
+ "s3_bucket": "my-bucket",
+ "s3_key": "results/batch-abc.json",
+ "s3_presigned_url": "https://s3.example.com/presigned",
+ "summary": {
+ "n_ok": 1,
+ "n_fail": 0,
+ "total_wall_ms": 350,
+ "reset_stats": {"n": 1, "min": 100, "mean": 100.0, "max": 100},
+ "step_stats": {"n": 1, "min": 200, "mean": 200.0, "max": 200},
+ "shutdown_stats": {"n": 1, "min": 50, "mean": 50.0, "max": 50},
+ },
+}
+
+
+class TestGetBatchResults:
+ def test_base_completed(self, httpx_mock: HTTPXMock, auth_client):
+ httpx_mock.add_response(
+ method="GET", url=f"{BASE_URL}/api/batch/pool/batch-abc/results", status_code=200, json=GOLDEN_BATCH_RESULTS
+ )
+ resp = get_batch_results.sync_detailed(pool="pool", id="batch-abc", client=auth_client)
+ assert resp.status_code.value == 200
+ assert isinstance(resp.parsed, BatchResultsResponse)
+ assert resp.parsed.status == "completed"
+
+ def test_in_progress_202(self, httpx_mock: HTTPXMock, auth_client):
+ httpx_mock.add_response(
+ method="GET",
+ url=f"{BASE_URL}/api/batch/pool/batch-abc/results",
+ status_code=202,
+ json={"batch_id": "batch-abc", "status": "running", "message": "batch still running"},
+ )
+ resp = get_batch_results.sync_detailed(pool="pool", id="batch-abc", client=auth_client)
+ assert resp.status_code.value == 202
+ assert isinstance(resp.parsed, BatchInProgressResponse)
+
+ def test_not_found(self, httpx_mock: HTTPXMock, auth_client):
+ httpx_mock.add_response(
+ method="GET", url=f"{BASE_URL}/api/batch/pool/unknown/results", status_code=404, json={"error": "not found"}
+ )
+ assert get_batch_results.sync_detailed(pool="pool", id="unknown", client=auth_client).status_code.value == 404
+
+ def test_flat_wrapper(self, httpx_mock: HTTPXMock, auth_client):
+ httpx_mock.add_response(
+ method="GET", url=f"{BASE_URL}/api/label/pool/lbl/results", status_code=200, json=GOLDEN_LABEL_RESULTS
+ )
+ result = auth_client.get_label_results(pool="pool", label="lbl")
+ assert isinstance(result, LabelResultsResponse)
+
+
+# ---------------------------------------------------------------------------
+# /api/batch/{pool}/{id} DELETE
+# ---------------------------------------------------------------------------
+
+
+class TestCancelBatch:
+ @pytest.mark.parametrize(
+ "pool,id,expected_status",
+ [
+ ("test-pool", "batch-abc", "cancelling"),
+ ("prod-pool", "batch-xyz", "completed"),
+ ("staging", "batch-999", "cancelled"),
+ ],
+ )
+ def test_base(self, httpx_mock: HTTPXMock, auth_client, pool, id, expected_status):
+ httpx_mock.add_response(
+ method="DELETE",
+ url=f"{BASE_URL}/api/batch/{pool}/{id}",
+ status_code=200,
+ json={"batch_id": id, "status": expected_status},
+ )
+ resp = cancel_batch.sync_detailed(pool=pool, id=id, client=auth_client)
+ assert resp.status_code.value == 200
+ assert isinstance(resp.parsed, CancelBatchResponse)
+ assert resp.parsed.status == expected_status
+
+ def test_not_found(self, httpx_mock: HTTPXMock, auth_client):
+ httpx_mock.add_response(
+ method="DELETE", url=f"{BASE_URL}/api/batch/pool/unknown", status_code=404, json={"error": "not found"}
+ )
+ assert cancel_batch.sync_detailed(pool="pool", id="unknown", client=auth_client).status_code.value == 404
+
+ def test_flat_wrapper(self, httpx_mock: HTTPXMock, auth_client):
+ httpx_mock.add_response(
+ method="DELETE", url=f"{BASE_URL}/api/label/pool/test-label", status_code=200, json=GOLDEN_CANCEL_LABEL
+ )
+ result = auth_client.cancel_label(pool="pool", label="test-label")
+ assert isinstance(result, CancelLabelResponse)
+
+
+# ---------------------------------------------------------------------------
+# /api/label/{pool}/{label}/batch POST
+# ---------------------------------------------------------------------------
+
+
+class TestSubmitLabelBatch:
+ @pytest.mark.parametrize(
+ "pool,label,concurrency",
+ [
+ ("test-pool", "test-label", 1),
+ ("prod-pool", "prod-run-2026-05-20", 10),
+ ("staging", "label-with-dashes", 50),
+ ],
+ )
+ def test_base(self, httpx_mock: HTTPXMock, auth_client, pool, label, concurrency):
+ resp_body = {**GOLDEN_SUBMIT_RESP, "name": label}
+ httpx_mock.add_response(
+ method="POST", url=f"{BASE_URL}/api/label/{pool}/{label}/batch", status_code=202, json=resp_body
+ )
+ resp = submit_label_batch.sync_detailed(
+ pool=pool,
+ label=label,
+ client=auth_client,
+ body=BatchSubmitRequest(runs=[GOLDEN_RUN], concurrency=concurrency),
+ )
+ assert resp.status_code.value == 202
+ assert isinstance(resp.parsed, BatchSubmitResponse)
+
+ def test_bad_request(self, httpx_mock: HTTPXMock, auth_client):
+ httpx_mock.add_response(
+ method="POST",
+ url=f"{BASE_URL}/api/label/pool/test/batch",
+ status_code=400,
+ json={"error": "runs must not be empty"},
+ )
+ resp = submit_label_batch.sync_detailed(
+ pool="pool", label="test", client=auth_client, body=BatchSubmitRequest(runs=[])
+ )
+ assert resp.status_code.value == 400
+ assert isinstance(resp.parsed, ErrorResponse)
+
+ def test_flat_wrapper(self, httpx_mock: HTTPXMock, auth_client):
+ httpx_mock.add_response(
+ method="POST", url=f"{BASE_URL}/api/label/test-pool/my-run/batch", status_code=202, json=GOLDEN_SUBMIT_RESP
+ )
+ result = auth_client.submit_label_batch(
+ pool="test-pool", label="my-run", body=BatchSubmitRequest(runs=[GOLDEN_RUN])
+ )
+ assert isinstance(result, BatchSubmitResponse)
+
+
+# ---------------------------------------------------------------------------
+# /api/label/{pool}/{label}/status GET
+# ---------------------------------------------------------------------------
+
+
+GOLDEN_LABEL_STATUS = {
+ "label": "test-label",
+ "batch_count": 2,
+ "all_completed": False,
+ "progress": {"completed": 5, "total": 10, "ok": 4, "failed": 1},
+ "batches": [
+ {
+ "batch_id": "batch-abc",
+ "status": "running",
+ "progress": {"completed": 5, "total": 10, "ok": 4, "failed": 1},
+ "created_at": "2026-05-01T00:00:00Z",
+ "updated_at": "2026-05-01T01:00:00Z",
+ }
+ ],
+}
+
+
+class TestGetLabelStatus:
+ def test_base(self, httpx_mock: HTTPXMock, auth_client):
+ httpx_mock.add_response(
+ method="GET",
+ url=f"{BASE_URL}/api/label/test-pool/test-label/status",
+ status_code=200,
+ json=GOLDEN_LABEL_STATUS,
+ )
+ resp = get_label_status.sync_detailed(pool="test-pool", label="test-label", client=auth_client)
+ assert resp.status_code.value == 200
+ assert isinstance(resp.parsed, LabelStatusResponse)
+ assert resp.parsed.all_completed is False
+
+ def test_all_completed(self, httpx_mock: HTTPXMock, auth_client):
+ body = {**GOLDEN_LABEL_STATUS, "all_completed": True}
+ httpx_mock.add_response(method="GET", url=f"{BASE_URL}/api/label/pool/done/status", status_code=200, json=body)
+ assert (
+ get_label_status.sync_detailed(pool="pool", label="done", client=auth_client).parsed.all_completed is True
+ )
+
+ def test_not_found(self, httpx_mock: HTTPXMock, auth_client):
+ httpx_mock.add_response(
+ method="GET",
+ url=f"{BASE_URL}/api/label/pool/unknown/status",
+ status_code=404,
+ json={"error": "label not found"},
+ )
+ assert get_label_status.sync_detailed(pool="pool", label="unknown", client=auth_client).status_code.value == 404
+
+ def test_flat_wrapper(self, httpx_mock: HTTPXMock, auth_client):
+ httpx_mock.add_response(
+ method="GET", url=f"{BASE_URL}/api/label/pool/lbl/status", status_code=200, json=GOLDEN_LABEL_STATUS
+ )
+ result = auth_client.get_label_status(pool="pool", label="lbl")
+ assert isinstance(result, LabelStatusResponse)
+
+
+# ---------------------------------------------------------------------------
+# /api/label/{pool}/{label}/results GET
+# ---------------------------------------------------------------------------
+
+
+GOLDEN_LABEL_RESULTS = {
+ "label": "test-label",
+ "batch_count": 1,
+ "completed_batch_count": 1,
+ "all_completed": True,
+ "batches": [GOLDEN_BATCH_RESULTS],
+ "summary": GOLDEN_BATCH_RESULTS["summary"],
+}
+
+
+class TestGetLabelResults:
+ def test_base_completed(self, httpx_mock: HTTPXMock, auth_client):
+ httpx_mock.add_response(
+ method="GET", url=f"{BASE_URL}/api/label/pool/lbl/results", status_code=200, json=GOLDEN_LABEL_RESULTS
+ )
+ resp = get_label_results.sync_detailed(pool="pool", label="lbl", client=auth_client)
+ assert resp.status_code.value == 200
+ assert isinstance(resp.parsed, LabelResultsResponse)
+ assert resp.parsed.all_completed is True
+
+ def test_drain_mode(self, httpx_mock: HTTPXMock, auth_client):
+ httpx_mock.add_response(
+ method="GET",
+ url=f"{BASE_URL}/api/label/pool/lbl/results?completed_only=true",
+ status_code=200,
+ json=GOLDEN_LABEL_RESULTS,
+ )
+ resp = get_label_results.sync_detailed(pool="pool", label="lbl", client=auth_client, completed_only=True)
+ assert resp.status_code.value == 200
+
+ def test_in_progress_202(self, httpx_mock: HTTPXMock, auth_client):
+ httpx_mock.add_response(
+ method="GET",
+ url=f"{BASE_URL}/api/label/pool/lbl/results",
+ status_code=202,
+ json={"label": "lbl", "batch_count": 1, "all_completed": False, "message": "still running"},
+ )
+ resp = get_label_results.sync_detailed(pool="pool", label="lbl", client=auth_client)
+ assert resp.status_code.value == 202
+ assert isinstance(resp.parsed, LabelInProgressResponse)
+
+ @pytest.mark.parametrize(
+ "pool,label",
+ [
+ ("test-pool", "test-label"),
+ ("prod-pool", "prod-2026"),
+ ("staging", "my-experiment"),
+ ],
+ )
+ def test_generated_pool_label(self, httpx_mock: HTTPXMock, auth_client, pool, label):
+ body = {**GOLDEN_LABEL_RESULTS, "label": label}
+ httpx_mock.add_response(
+ method="GET", url=f"{BASE_URL}/api/label/{pool}/{label}/results", status_code=200, json=body
+ )
+ resp = get_label_results.sync_detailed(pool=pool, label=label, client=auth_client)
+ assert resp.parsed.label == label
+
+ def test_flat_wrapper(self, httpx_mock: HTTPXMock, auth_client):
+ httpx_mock.add_response(
+ method="GET", url=f"{BASE_URL}/api/label/pool/lbl/results", status_code=200, json=GOLDEN_LABEL_RESULTS
+ )
+ result = auth_client.get_label_results(pool="pool", label="lbl")
+ assert isinstance(result, LabelResultsResponse)
+
+
+# ---------------------------------------------------------------------------
+# /api/label/{pool}/{label} DELETE
+# ---------------------------------------------------------------------------
+
+
+GOLDEN_CANCEL_LABEL = {
+ "label": "test-label",
+ "batch_count": 2,
+ "cancelled_count": 1,
+ "already_done": 1,
+ "batches": [
+ {"batch_id": "batch-abc", "status": "cancelling"},
+ {"batch_id": "batch-xyz", "status": "completed"},
+ ],
+}
+
+
+class TestCancelLabel:
+ @pytest.mark.parametrize(
+ "pool,label",
+ [
+ ("test-pool", "test-label"),
+ ("prod-pool", "prod-run"),
+ ("staging", "experiment-42"),
+ ],
+ )
+ def test_base(self, httpx_mock: HTTPXMock, auth_client, pool, label):
+ body = {**GOLDEN_CANCEL_LABEL, "label": label}
+ httpx_mock.add_response(method="DELETE", url=f"{BASE_URL}/api/label/{pool}/{label}", status_code=200, json=body)
+ resp = cancel_label.sync_detailed(pool=pool, label=label, client=auth_client)
+ assert resp.status_code.value == 200
+ assert isinstance(resp.parsed, CancelLabelResponse)
+
+ def test_not_found(self, httpx_mock: HTTPXMock, auth_client):
+ httpx_mock.add_response(
+ method="DELETE",
+ url=f"{BASE_URL}/api/label/pool/unknown",
+ status_code=404,
+ json={"error": "label not found"},
+ )
+ assert cancel_label.sync_detailed(pool="pool", label="unknown", client=auth_client).status_code.value == 404
+
+ def test_flat_wrapper(self, httpx_mock: HTTPXMock, auth_client):
+ httpx_mock.add_response(
+ method="DELETE", url=f"{BASE_URL}/api/label/pool/lbl", status_code=200, json=GOLDEN_CANCEL_LABEL
+ )
+ result = auth_client.cancel_label(pool="pool", label="lbl")
+ assert isinstance(result, CancelLabelResponse)
diff --git a/libs/fleet/python-sdk/tests/test_models.py b/libs/fleet/python-sdk/tests/test_models.py
new file mode 100644
index 0000000000..cb6ce7df94
--- /dev/null
+++ b/libs/fleet/python-sdk/tests/test_models.py
@@ -0,0 +1,61 @@
+"""Smoke tests — verify models and TrainClient can be imported and instantiated."""
+
+from cua_train import AuthenticatedClient, TrainClient
+from cua_train.models import (
+ Action,
+ ActionParameters,
+ BatchProgress,
+ BatchSubmitRequest,
+ LabelStatusResponse,
+ RunConfig,
+)
+
+
+def test_batch_submit_request_instantiation():
+ click = Action(action_type="CLICK", parameters=ActionParameters.from_dict({"x": 1, "y": 2}))
+ req = BatchSubmitRequest(
+ runs=[RunConfig(steps=[click], timeout=60)],
+ concurrency=2,
+ )
+ assert len(req.runs) == 1
+ assert req.runs[0].steps[0].action_type == "CLICK"
+
+
+def test_label_status_response_instantiation():
+ resp = LabelStatusResponse(
+ label="test-label",
+ batch_count=1,
+ all_completed=False,
+ progress=BatchProgress(completed=0, total=1, ok=0, failed=0),
+ batches=[],
+ )
+ assert resp.label == "test-label"
+
+
+def test_train_client_is_subclass():
+ """TrainClient must be a drop-in for AuthenticatedClient."""
+ assert issubclass(TrainClient, AuthenticatedClient)
+
+
+def test_client_exposes_generated_operations():
+ """Every generated endpoint is reachable as a method on the client
+ (its sync(), client pre-bound), with no hand-written wrapper."""
+ import pytest
+
+ c = TrainClient(base_url="https://example.invalid", token="t")
+
+ # A representative op from each tag is exposed and callable.
+ for op in (
+ "acquire_lanes",
+ "release_lanes",
+ "submit_batch",
+ "submit_label_batch",
+ "get_label_results",
+ "list_keys",
+ "healthz",
+ ):
+ assert callable(getattr(c, op)), f"client.{op} should be callable"
+
+ # Unknown attributes still raise AttributeError (so copy/pickle/etc. behave).
+ with pytest.raises(AttributeError):
+ c.definitely_not_an_endpoint
diff --git a/libs/fleet/python-sdk/tests/test_wheel_build.py b/libs/fleet/python-sdk/tests/test_wheel_build.py
new file mode 100644
index 0000000000..25dff8c70a
--- /dev/null
+++ b/libs/fleet/python-sdk/tests/test_wheel_build.py
@@ -0,0 +1,135 @@
+import csv
+import importlib.util
+import subprocess
+import sys
+import tempfile
+import unittest
+import zipfile
+from pathlib import Path
+from unittest.mock import patch
+
+
+class WheelBuildTest(unittest.TestCase):
+ def test_windows_x86_64_wheel_contains_generated_loader_dll_and_platform_tag(self):
+ project = Path(__file__).resolve().parents[1]
+ builder_path = project / "scripts" / "build_wheel.py"
+ spec = importlib.util.spec_from_file_location("build_wheel", builder_path)
+ assert spec and spec.loader
+ build_wheel = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(build_wheel)
+
+ with (
+ patch.object(build_wheel.sys, "platform", "win32"),
+ patch.object(build_wheel.platform, "machine", return_value="AMD64"),
+ ):
+ self.assertEqual("cyclops_sdk.dll", build_wheel.native_library_name())
+ self.assertEqual("win_amd64", build_wheel.default_platform_tag())
+ self.assertEqual("cyclops_sdk.dll", build_wheel.native_library_name_for_platform_tag("win_amd64"))
+
+ with tempfile.TemporaryDirectory() as temporary_directory:
+ temporary = Path(temporary_directory)
+ native_library = temporary / "cyclops_sdk.dll"
+ native_library.write_bytes(b"not a native library")
+ output = temporary / "dist"
+
+ subprocess.run(
+ [
+ sys.executable,
+ "scripts/build_wheel.py",
+ "--native-library",
+ str(native_library),
+ "--platform-tag",
+ "win_amd64",
+ "--outdir",
+ str(output),
+ ],
+ cwd=project,
+ check=True,
+ )
+
+ wheels = list(output.glob("*.whl"))
+ self.assertEqual([wheel.name for wheel in wheels], ["cua_train-0.1.6-py3-none-win_amd64.whl"])
+ with zipfile.ZipFile(wheels[0]) as archive:
+ names = archive.namelist()
+ self.assertIn("fleet_sdk/cyclops_sdk.dll", names)
+ wheel_metadata = next(name for name in names if name.endswith(".dist-info/WHEEL"))
+ self.assertIn("Root-Is-Purelib: false", archive.read(wheel_metadata).decode())
+ self.assertIn("Tag: py3-none-win_amd64", archive.read(wheel_metadata).decode())
+ record = next(name for name in names if name.endswith(".dist-info/RECORD"))
+ record_rows = list(csv.reader(archive.read(record).decode().splitlines()))
+ self.assertIn(
+ ["fleet_sdk/cyclops_sdk.dll", "sha256=U9PN3aRS1FqC5Fx0fZQjZf4JXxMTFG6yOsDsB5DOjD0", "20"],
+ record_rows,
+ )
+
+ def test_wheel_build_rejects_a_native_library_name_the_loader_cannot_find(self):
+ project = Path(__file__).resolve().parents[1]
+ with tempfile.TemporaryDirectory() as temporary_directory:
+ temporary = Path(temporary_directory)
+ native_library = temporary / "libcyclops_sdk.so"
+ native_library.write_bytes(b"not a native library")
+
+ process = subprocess.run(
+ [
+ sys.executable,
+ "scripts/build_wheel.py",
+ "--native-library",
+ str(native_library),
+ "--platform-tag",
+ "win_amd64",
+ "--outdir",
+ str(temporary / "dist"),
+ ],
+ cwd=project,
+ text=True,
+ capture_output=True,
+ )
+
+ self.assertNotEqual(0, process.returncode)
+ self.assertIn("native library must be named cyclops_sdk.dll", process.stderr)
+
+ def test_staged_wheel_contains_native_binding_and_platform_tag(self):
+ project = Path(__file__).resolve().parents[1]
+ with tempfile.TemporaryDirectory() as temporary_directory:
+ temporary = Path(temporary_directory)
+ native_library = temporary / "libcyclops_sdk.so"
+ native_library.write_bytes(b"not a native library")
+ output = temporary / "dist"
+
+ subprocess.run(
+ [
+ sys.executable,
+ "scripts/build_wheel.py",
+ "--native-library",
+ str(native_library),
+ "--platform-tag",
+ "linux_x86_64",
+ "--outdir",
+ str(output),
+ ],
+ cwd=project,
+ check=True,
+ )
+
+ wheels = list(output.glob("*.whl"))
+ self.assertEqual([wheel.name for wheel in wheels], ["cua_train-0.1.6-py3-none-linux_x86_64.whl"])
+ with zipfile.ZipFile(wheels[0]) as archive:
+ names = archive.namelist()
+ self.assertIn("fleet_sdk/__init__.py", names)
+ self.assertIn("fleet_sdk/_sdk.py", names)
+ self.assertIn("fleet_sdk/_schema.py", names)
+ self.assertIn("fleet_sdk/libcyclops_sdk.so", names)
+ self.assertIn("cua_train/__init__.py", names)
+ wheel_metadata = next(name for name in names if name.endswith(".dist-info/WHEEL"))
+ self.assertIn("Root-Is-Purelib: false", archive.read(wheel_metadata).decode())
+ self.assertIn("Tag: py3-none-linux_x86_64", archive.read(wheel_metadata).decode())
+ record = next(name for name in names if name.endswith(".dist-info/RECORD"))
+ record_rows = list(csv.reader(archive.read(record).decode().splitlines()))
+ self.assertIn(
+ ["fleet_sdk/libcyclops_sdk.so", "sha256=U9PN3aRS1FqC5Fx0fZQjZf4JXxMTFG6yOsDsB5DOjD0", "20"],
+ record_rows,
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/libs/fleet/scripts/ensure-browser-sdk-binding.sh b/libs/fleet/scripts/ensure-browser-sdk-binding.sh
new file mode 100755
index 0000000000..e6a86e1653
--- /dev/null
+++ b/libs/fleet/scripts/ensure-browser-sdk-binding.sh
@@ -0,0 +1,51 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
+cyclops_root="$repo_root/cyclops-cs"
+binding_dir="$cyclops_root/sdk-bindings/ts-uniffi-browser"
+stamp_dir="$cyclops_root/target/browser-sdk"
+stamp_file="$stamp_dir/input.sha256"
+
+artifacts=(
+ "$binding_dir/ts/index.web.ts"
+ "$binding_dir/ts/wasm-bindgen/index.js"
+ "$binding_dir/ts/wasm-bindgen/index_bg.wasm"
+)
+
+inputs_hash="$({
+ find \
+ "$cyclops_root/sdk/src" \
+ "$cyclops_root/sdk-schema/src" \
+ -type f -print0
+ printf '%s\0' \
+ "$cyclops_root/Cargo.lock" \
+ "$cyclops_root/Cargo.toml" \
+ "$cyclops_root/rust-toolchain.toml" \
+ "$cyclops_root/bindgen-cli/main.rs" \
+ "$binding_dir/package-lock.json" \
+ "$binding_dir/ubrn.config.yaml" \
+ "$binding_dir/scripts/patch-ubrn-wasm-template.mjs" \
+ "$cyclops_root/scripts/build-browser-sdk-binding.sh"
+} | sort -z | xargs -0 sha256sum | sha256sum | cut -d' ' -f1)"
+
+artifacts_ready=true
+for artifact in "${artifacts[@]}"; do
+ if [ ! -s "$artifact" ]; then
+ artifacts_ready=false
+ break
+ fi
+done
+
+stamp_matches=false
+if [ -f "$stamp_file" ] && [ "$(cat "$stamp_file")" = "$inputs_hash" ]; then
+ stamp_matches=true
+fi
+
+if [ "$artifacts_ready" = true ] && [ "$stamp_matches" = true ]; then
+ exit 0
+fi
+
+"$cyclops_root/scripts/build-browser-sdk-binding.sh"
+mkdir -p "$stamp_dir"
+printf '%s\n' "$inputs_hash" > "$stamp_file"
diff --git a/libs/fleet/scripts/generate-sdk-bindings.sh b/libs/fleet/scripts/generate-sdk-bindings.sh
index 5ccbd55c7a..432cc9d5fb 100755
--- a/libs/fleet/scripts/generate-sdk-bindings.sh
+++ b/libs/fleet/scripts/generate-sdk-bindings.sh
@@ -799,6 +799,7 @@ text = text.replace(future_runtime_anchor, future_runtime, 1)
buffer_pattern = r"(?m)^(\s*)result = FleetSdk\.rust_call_with_error\(([^,]+),:([a-z0-9_]+),(.*)\)$"
def replace_buffer(match):
indent, error_module, function, arguments = match.groups()
+ arguments = arguments.rstrip().removesuffix(",")
return (
f"{indent}result = FleetSdk.uniffi_rust_future_rust_buffer(\n"
f"{indent} {error_module},\n"
@@ -806,12 +807,13 @@ def replace_buffer(match):
f"{indent})"
)
text, buffer_replacements = re.subn(buffer_pattern, replace_buffer, text)
-if buffer_replacements != 17:
- raise SystemExit(f"expected 17 Ruby Rust-buffer future wrappers, found {buffer_replacements}")
+if buffer_replacements != 20:
+ raise SystemExit(f"expected 20 Ruby Rust-buffer future wrappers, found {buffer_replacements}")
void_pattern = r"(?m)^(\s*)FleetSdk\.rust_call_with_error\(([^,]+),:([a-z0-9_]+),(.*)\)$"
def replace_void(match):
indent, error_module, function, arguments = match.groups()
+ arguments = arguments.rstrip().removesuffix(",")
return (
f"{indent}FleetSdk.uniffi_rust_future_void(\n"
f"{indent} {error_module},\n"
@@ -819,8 +821,8 @@ def replace_void(match):
f"{indent})"
)
text, void_replacements = re.subn(void_pattern, replace_void, text)
-if void_replacements != 3:
- raise SystemExit(f"expected 3 Ruby void future wrappers, found {void_replacements}")
+if void_replacements != 4:
+ raise SystemExit(f"expected 4 Ruby void future wrappers, found {void_replacements}")
handle_map_anchor = """def self.uniffi_bytes(v)
raise TypeError, \"no implicit conversion of #{v} into String\" unless v.respond_to?(:to_str)
diff --git a/libs/fleet/scripts/test-browser-sdk-bindings.sh b/libs/fleet/scripts/test-browser-sdk-bindings.sh
index 97f1264504..87b97f0af2 100755
--- a/libs/fleet/scripts/test-browser-sdk-bindings.sh
+++ b/libs/fleet/scripts/test-browser-sdk-bindings.sh
@@ -2,11 +2,16 @@
set -euo pipefail
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
-binding_file="$repo_root/cyclops-cs/sdk-bindings/ts-uniffi-browser/ts/cyclops_sdk.ts"
+binding_file="$repo_root/cyclops-cs/sdk-bindings/ts-uniffi-browser/ts/fleet_sdk.ts"
-for symbol in AccessTokenProvider connectWithAccessTokenProvider connectWithAccessToken connectBrowserWithAccessToken; do
+for symbol in AccessTokenProvider connectWithAccessTokenProvider connectWithAccessToken connectBrowserWithAccessToken creationTimestamp listNamespaces listUserApiKeys createUserApiKey deleteUserApiKey; do
if ! grep -Fq "$symbol" "$binding_file"; then
echo "error: generated browser SDK binding is missing $symbol: $binding_file" >&2
exit 1
fi
done
+
+if grep -Fq "executeAuthenticated" "$binding_file"; then
+ echo "error: generated browser SDK binding exports executeAuthenticated: $binding_file" >&2
+ exit 1
+fi
diff --git a/libs/fleet/scripts/test-generate-sdk-bindings.sh b/libs/fleet/scripts/test-generate-sdk-bindings.sh
index a0f8a13424..2cdaa98b37 100755
--- a/libs/fleet/scripts/test-generate-sdk-bindings.sh
+++ b/libs/fleet/scripts/test-generate-sdk-bindings.sh
@@ -335,7 +335,40 @@ PYTHON_SMOKE
rm "$runtime_copy"
runtime_copy=""
"$generator" --check
+python_sdk_source="$bindings_dir/python/fleet_sdk/_sdk.py"
+kotlin_sdk_source="$bindings_dir/kotlin/ai/cua/cyclops/sdk/fleet_sdk.kt"
+swift_sdk_source="$bindings_dir/swift/CyclopsSdk.swift"
ruby_sdk_source="$bindings_dir/ruby/cyclops_sdk/sdk.rb"
+node_sdk_source="$bindings_dir/ts-uniffi/fleet_sdk.ts"
+go_sdk_source="$bindings_dir/go-uniffi/fleet_sdk/fleet_sdk.go"
+if grep -Fq -- "execute_authenticated" "$python_sdk_source"; then fail "Python bindings export execute_authenticated"; fi
+if grep -Fq -- "executeAuthenticated" "$kotlin_sdk_source"; then fail "Kotlin bindings export executeAuthenticated"; fi
+if grep -Fq -- "executeAuthenticated" "$swift_sdk_source"; then fail "Swift bindings export executeAuthenticated"; fi
+if grep -Fq -- "execute_authenticated" "$ruby_sdk_source"; then fail "Ruby bindings export execute_authenticated"; fi
+if grep -Fq -- "executeAuthenticated" "$node_sdk_source"; then fail "Node bindings export executeAuthenticated"; fi
+if grep -Fq -- "ExecuteAuthenticated" "$go_sdk_source"; then fail "Go bindings export ExecuteAuthenticated"; fi
+for method in list_namespaces list_user_api_keys create_user_api_key delete_user_api_key; do
+ grep -Fq -- "async def $method" "$python_sdk_source" || fail "Python bindings omit $method"
+done
+for method in listNamespaces listUserApiKeys createUserApiKey deleteUserApiKey; do
+ grep -Fq -- "suspend fun \`$method\`" "$kotlin_sdk_source" || fail "Kotlin bindings omit $method"
+ grep -Fq -- "func $method" "$swift_sdk_source" || fail "Swift bindings omit $method"
+done
+for method in list_namespaces list_user_api_keys create_user_api_key delete_user_api_key; do
+ grep -Fq -- "def $method" "$ruby_sdk_source" || fail "Ruby bindings omit $method"
+done
+for method in listNamespaces listUserApiKeys createUserApiKey deleteUserApiKey; do
+ grep -Fq -- "$method(" "$node_sdk_source" || fail "Node bindings omit $method"
+done
+for method in ListNamespaces ListUserApiKeys CreateUserApiKey DeleteUserApiKey; do
+ grep -Fq -- "$method(" "$go_sdk_source" || fail "Go bindings omit $method"
+done
+grep -Fq -- "creation_timestamp:typing.Optional[str]" "$python_sdk_source" || fail "Python bindings omit creation_timestamp"
+grep -Fq -- "var \`creationTimestamp\`: kotlin.String?" "$kotlin_sdk_source" || fail "Kotlin bindings omit creationTimestamp"
+grep -Fq -- "public var creationTimestamp: String?" "$swift_sdk_source" || fail "Swift bindings omit creationTimestamp"
+grep -Fq -- "attr_reader :namespace, :name, :labels, :creation_timestamp" "$ruby_sdk_source" || fail "Ruby bindings omit creation_timestamp"
+grep -Fq -- "creationTimestamp?: string" "$node_sdk_source" || fail "Node bindings omit creationTimestamp"
+grep -Fq -- "CreationTimestamp *string" "$go_sdk_source" || fail "Go bindings omit CreationTimestamp"
grep -Fq -- "@uniffi_handle_map = UniffiHandleMap.new" "$ruby_sdk_source" || fail "Ruby callback bindings do not retain native callback objects"
grep -Fq -- "module UniffiCallbackInterfaceHttpClient" "$ruby_sdk_source" || fail "Ruby callback bindings do not register an HTTP callback vtable"
grep -Fq -- "[VTableCallbackInterfaceHttpClient.by_ref]" "$ruby_sdk_source" || fail "Ruby callback vtable initializer has the wrong FFI signature"
@@ -348,6 +381,7 @@ grep -Fq -- "def self.uniffi_is_error_type?" "$ruby_sdk_source" || fail "Ruby ca
grep -Fq -- "FleetSdk.uniffi_rust_future_rust_buffer" "$ruby_sdk_source" || fail "Ruby async methods do not resolve Rust-buffer futures"
grep -Fq -- "def self.uniffi_rust_future_void" "$ruby_sdk_source" || fail "Ruby bindings do not resolve void futures"
grep -Fq -- "FleetSdk.uniffi_rust_future_void" "$ruby_sdk_source" || fail "Ruby async void methods do not resolve Rust futures"
+if grep -Fq -- ",,RustCallStatus.new" "$ruby_sdk_source"; then fail "Ruby zero-argument async methods emit a duplicate status separator"; fi
grep -Fq -- "UniFFILib.uniffi_cyclops_sdk_fn_method_cyclopsclient_create_pool(uniffi_clone_handle(),RustBuffer.alloc_from_TypeCreatePoolRequest(request),RustCallStatus.new)" "$ruby_sdk_source" || fail "Ruby async factories do not pass the generated status placeholder"
grep -Fq -- " readTypeOSGymSandboxWarmPoolSpec" "$bindings_dir/ruby/cyclops_sdk.rb" || fail "Ruby facade does not delegate schema record readers"
if grep -Fq -- "OsGym" "$ruby_sdk_source"; then
diff --git a/libs/fleet/sdk-bindings/examples/kotlin/AppControlled.kt b/libs/fleet/sdk-bindings/examples/kotlin/AppControlled.kt
index 8bd874f429..0f16336ce7 100644
--- a/libs/fleet/sdk-bindings/examples/kotlin/AppControlled.kt
+++ b/libs/fleet/sdk-bindings/examples/kotlin/AppControlled.kt
@@ -4,6 +4,17 @@ import kotlinx.coroutines.runBlocking
import java.util.Collections
private data class Expected(val method: String, val url: String, val headers: List<Pair<String, String>>, val body: ByteArray?, val status: UShort, val response: String)
+private val generatedClaimNamePattern = Regex("claim-[a-z0-9](?:[-a-z0-9]*[a-z0-9])?")
+private val claimNameFieldPattern = Regex("\"name\":\"(claim-[^\"]+)\"")
+
+private fun normalizedGeneratedClaimBody(body: ByteArray?): ByteArray? {
+ val text = body?.decodeToString() ?: return null
+ val match = claimNameFieldPattern.find(text) ?: return null
+ val name = match.groupValues[1]
+ check(name.length <= 63 && generatedClaimNamePattern.matches(name))
+ return text.replaceRange(match.groups[1]!!.range, "claim-generated").encodeToByteArray()
+}
+
private class ScriptedHttpClient : HttpClient {
private val lock = Any()
private val expected = ArrayDeque(listOf(
@@ -22,7 +33,13 @@ private class ScriptedHttpClient : HttpClient {
val item = expected.removeFirst()
check(request.method == item.method && request.url == item.url)
check(request.headers.map { it.name to it.value } == item.headers)
- check((request.body == null && item.body == null) || (request.body != null && item.body != null && request.body.contentEquals(item.body)))
+ if (request.method == "POST" && request.url.endsWith("/osgymsandboxclaims")) {
+ val actualBody = normalizedGeneratedClaimBody(request.body)
+ val expectedBody = normalizedGeneratedClaimBody(item.body)
+ check(actualBody != null && expectedBody != null && actualBody.contentEquals(expectedBody))
+ } else {
+ check((request.body == null && item.body == null) || (request.body != null && item.body != null && request.body.contentEquals(item.body)))
+ }
HttpResponse(item.status, emptyList(), item.response.encodeToByteArray())
}
fun assertExhausted() = check(expected.isEmpty())
diff --git a/libs/fleet/sdk-bindings/examples/ruby/app_controlled.rb b/libs/fleet/sdk-bindings/examples/ruby/app_controlled.rb
index c38b088840..bf6dca827b 100644
--- a/libs/fleet/sdk-bindings/examples/ruby/app_controlled.rb
+++ b/libs/fleet/sdk-bindings/examples/ruby/app_controlled.rb
@@ -5,6 +5,17 @@ require 'json'
require 'thread'
Expected = Struct.new(:method, :url, :headers, :body, :status, :response)
BASE = 'https://cyclops.invalid'; TOKEN = 'https://keycloak.invalid/token'; JSON_HEADERS = [['accept','application/json'],['content-type','application/json'],['authorization','Bearer offline-token']]
+GENERATED_CLAIM_NAME = /\Aclaim-[a-z0-9](?:[-a-z0-9]*[a-z0-9])?\z/
+
+def normalized_generated_claim_body(body)
+ return nil if body.nil?
+ value = JSON.parse(body)
+ name = value.fetch('metadata').fetch('name')
+ raise "invalid generated claim name: #{name.inspect}" unless name.bytesize <= 63 && GENERATED_CLAIM_NAME.match?(name)
+ value['metadata']['name'] = 'claim-generated'
+ JSON.generate(value).b
+end
+
def pool_json; { apiVersion:'osgym.cua.ai/v1alpha1',kind:'OSGymSandboxWarmPool',metadata:{namespace:'default',name:'default',labels:nil},spec:{replicas:1,sandboxTemplateRef:{name:'default'}},status:nil }; end
def template_json; { apiVersion:'osgym.cua.ai/v1alpha1',kind:'OSGymSandboxTemplate',metadata:{namespace:'default',name:'default',labels:nil},spec:{vmTemplate:{containerDiskImage:'registry.example/desktop:offline',services:[{name:'mcp',targetPort:8080}]}} }; end
def claim_json(bound=false); value={apiVersion:'osgym.cua.ai/v1alpha1',kind:'OSGymSandboxClaim',metadata:{namespace:'default',name:'default',labels:nil},spec:{sandboxTemplateRef:{name:'default'}},status:nil}; value[:status]={phase:'Bound',sandbox:{name:'offline-sandbox'}} if bound; value; end
@@ -19,7 +30,12 @@ class ScriptedHttpClient < FleetSdk::HttpClient
@mutex.synchronize do
[email protected] or raise 'unexpected request'
actual=[request.method,request.url,request.headers.map{|h|[h.name,h.value]},request.body]
- raise "request mismatch: #{actual.inspect}" unless actual == [item.method,item.url,item.headers,item.body]
+ expected=[item.method,item.url,item.headers,item.body]
+ if request.method == 'POST' && request.url.end_with?('/osgymsandboxclaims')
+ raise "request mismatch: #{actual.inspect}" unless actual.first(3) == expected.first(3) && normalized_generated_claim_body(request.body) == normalized_generated_claim_body(item.body)
+ else
+ raise "request mismatch: #{actual.inspect}" unless actual == expected
+ end
body=item.response.is_a?(String) ? item.response.b : JSON.generate(item.response).b
FleetSdk::HttpResponse.new(status:item.status,headers:[],body:body)
end
diff --git a/libs/fleet/sdk-bindings/go-uniffi/cyclops_sdk_schema/cyclops_sdk_schema.h b/libs/fleet/sdk-bindings/go-uniffi/cyclops_sdk_schema/cyclops_sdk_schema.h
index 69857cfd60..d34c40ac97 100644
--- a/libs/fleet/sdk-bindings/go-uniffi/cyclops_sdk_schema/cyclops_sdk_schema.h
+++ b/libs/fleet/sdk-bindings/go-uniffi/cyclops_sdk_schema/cyclops_sdk_schema.h
@@ -390,21 +390,6 @@ uint64_t uniffi_cyclops_sdk_schema_fn_constructor_preservedjson_from_json(RustBu
RustBuffer uniffi_cyclops_sdk_schema_fn_method_preservedjson_to_json(uint64_t ptr, RustCallStatus *out_status
);
#endif
-#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_SCHEMA_FN_METHOD_POOLSPEC_UNIFFI_TRAIT_EQ_EQ
-#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_SCHEMA_FN_METHOD_POOLSPEC_UNIFFI_TRAIT_EQ_EQ
-int8_t uniffi_cyclops_sdk_schema_fn_method_poolspec_uniffi_trait_eq_eq(RustBuffer ptr, RustBuffer other, RustCallStatus *out_status
-);
-#endif
-#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_SCHEMA_FN_METHOD_POOLSPEC_UNIFFI_TRAIT_EQ_NE
-#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_SCHEMA_FN_METHOD_POOLSPEC_UNIFFI_TRAIT_EQ_NE
-int8_t uniffi_cyclops_sdk_schema_fn_method_poolspec_uniffi_trait_eq_ne(RustBuffer ptr, RustBuffer other, RustCallStatus *out_status
-);
-#endif
-#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_SCHEMA_FN_METHOD_POOLSPEC_UNIFFI_TRAIT_HASH
-#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_SCHEMA_FN_METHOD_POOLSPEC_UNIFFI_TRAIT_HASH
-uint64_t uniffi_cyclops_sdk_schema_fn_method_poolspec_uniffi_trait_hash(RustBuffer ptr, RustCallStatus *out_status
-);
-#endif
#ifndef UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUSTBUFFER_ALLOC
#define UNIFFI_FFIDEF_FFI_CYCLOPS_SDK_SCHEMA_RUSTBUFFER_ALLOC
RustBuffer ffi_cyclops_sdk_schema_rustbuffer_alloc(uint64_t size, RustCallStatus *out_status
diff --git a/libs/fleet/sdk-bindings/go-uniffi/fleet_sdk/fleet_sdk.go b/libs/fleet/sdk-bindings/go-uniffi/fleet_sdk/fleet_sdk.go
index 4c12b9c626..fffef5a2b4 100644
--- a/libs/fleet/sdk-bindings/go-uniffi/fleet_sdk/fleet_sdk.go
+++ b/libs/fleet/sdk-bindings/go-uniffi/fleet_sdk/fleet_sdk.go
@@ -421,6 +421,15 @@ func uniffiCheckChecksums() {
panic("fleet_sdk: uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim: UniFFI API checksum mismatch")
}
}
+ {
+ checksum := rustCall(func(_uniffiStatus *C.RustCallStatus) C.uint16_t {
+ return C.uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_namespaces()
+ })
+ if checksum != 65288 {
+ // If this happens try cleaning and rebuilding your project
+ panic("fleet_sdk: uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_namespaces: UniFFI API checksum mismatch")
+ }
+ }
{
checksum := rustCall(func(_uniffiStatus *C.RustCallStatus) C.uint16_t {
return C.uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_pool()
@@ -538,6 +547,33 @@ func uniffiCheckChecksums() {
panic("fleet_sdk: uniffi_cyclops_sdk_checksum_method_cyclopsclient_update_template: UniFFI API checksum mismatch")
}
}
+ {
+ checksum := rustCall(func(_uniffiStatus *C.RustCallStatus) C.uint16_t {
+ return C.uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_user_api_key()
+ })
+ if checksum != 9174 {
+ // If this happens try cleaning and rebuilding your project
+ panic("fleet_sdk: uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_user_api_key: UniFFI API checksum mismatch")
+ }
+ }
+ {
+ checksum := rustCall(func(_uniffiStatus *C.RustCallStatus) C.uint16_t {
+ return C.uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_user_api_key()
+ })
+ if checksum != 1700 {
+ // If this happens try cleaning and rebuilding your project
+ panic("fleet_sdk: uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_user_api_key: UniFFI API checksum mismatch")
+ }
+ }
+ {
+ checksum := rustCall(func(_uniffiStatus *C.RustCallStatus) C.uint16_t {
+ return C.uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_user_api_keys()
+ })
+ if checksum != 5949 {
+ // If this happens try cleaning and rebuilding your project
+ panic("fleet_sdk: uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_user_api_keys: UniFFI API checksum mismatch")
+ }
+ }
{
checksum := rustCall(func(_uniffiStatus *C.RustCallStatus) C.uint16_t {
return C.uniffi_cyclops_sdk_checksum_method_accesstokenprovider_get_access_token()
@@ -1157,6 +1193,7 @@ type CyclopsClientInterface interface {
GetClaim(claim Claim) (Claim, error)
ListClaims(namespace string) ([]Claim, error)
WaitClaim(claim Claim) (Sandbox, error)
+ ListNamespaces() ([]Namespace, error)
CreatePool(request CreatePoolRequest) (Pool, error)
DeletePool(pool Pool) error
GetPool(name string) (Pool, error)
@@ -1170,6 +1207,9 @@ type CyclopsClientInterface interface {
ListTemplates(namespace string) ([]Template, error)
ReconcileTemplate(request CreateTemplateRequest) (Template, error)
UpdateTemplate(template Template) (Template, error)
+ CreateUserApiKey(request CreateUserApiKeyRequest) (NewUserApiKey, error)
+ DeleteUserApiKey(id string) error
+ ListUserApiKeys() ([]UserApiKey, error)
}
type CyclopsClient struct {
ffiObject FfiObject
@@ -1430,6 +1470,41 @@ func (_self *CyclopsClient) WaitClaim(claim Claim) (Sandbox, error) {
return res, err
}
+func (_self *CyclopsClient) ListNamespaces() ([]Namespace, error) {
+ _pointer := _self.ffiObject.incrementPointer("*CyclopsClient")
+ defer _self.ffiObject.decrementPointer()
+ res, err := uniffiRustCallAsync[*SdkError](
+ FfiConverterSdkErrorINSTANCE,
+ // completeFn
+ func(handle C.uint64_t, status *C.RustCallStatus) RustBufferI {
+ res := C.ffi_cyclops_sdk_rust_future_complete_rust_buffer(handle, status)
+ return GoRustBuffer{
+ inner: res,
+ }
+ },
+ // liftFn
+ func(ffi RustBufferI) []Namespace {
+ return FfiConverterSequenceNamespaceINSTANCE.Lift(ffi)
+ },
+ C.uniffi_cyclops_sdk_fn_method_cyclopsclient_list_namespaces(
+ _pointer),
+ // pollFn
+ func(handle C.uint64_t, continuation C.UniffiRustFutureContinuationCallback, data C.uint64_t) {
+ C.ffi_cyclops_sdk_rust_future_poll_rust_buffer(handle, continuation, data)
+ },
+ // freeFn
+ func(handle C.uint64_t) {
+ C.ffi_cyclops_sdk_rust_future_free_rust_buffer(handle)
+ },
+ )
+
+ if err == nil {
+ return res, nil
+ }
+
+ return res, err
+}
+
func (_self *CyclopsClient) CreatePool(request CreatePoolRequest) (Pool, error) {
_pointer := _self.ffiObject.incrementPointer("*CyclopsClient")
defer _self.ffiObject.decrementPointer()
@@ -1876,6 +1951,107 @@ func (_self *CyclopsClient) UpdateTemplate(template Template) (Template, error)
return res, err
}
+
+func (_self *CyclopsClient) CreateUserApiKey(request CreateUserApiKeyRequest) (NewUserApiKey, error) {
+ _pointer := _self.ffiObject.incrementPointer("*CyclopsClient")
+ defer _self.ffiObject.decrementPointer()
+ res, err := uniffiRustCallAsync[*SdkError](
+ FfiConverterSdkErrorINSTANCE,
+ // completeFn
+ func(handle C.uint64_t, status *C.RustCallStatus) RustBufferI {
+ res := C.ffi_cyclops_sdk_rust_future_complete_rust_buffer(handle, status)
+ return GoRustBuffer{
+ inner: res,
+ }
+ },
+ // liftFn
+ func(ffi RustBufferI) NewUserApiKey {
+ return FfiConverterNewUserApiKeyINSTANCE.Lift(ffi)
+ },
+ C.uniffi_cyclops_sdk_fn_method_cyclopsclient_create_user_api_key(
+ _pointer, FfiConverterCreateUserApiKeyRequestINSTANCE.Lower(request)),
+ // pollFn
+ func(handle C.uint64_t, continuation C.UniffiRustFutureContinuationCallback, data C.uint64_t) {
+ C.ffi_cyclops_sdk_rust_future_poll_rust_buffer(handle, continuation, data)
+ },
+ // freeFn
+ func(handle C.uint64_t) {
+ C.ffi_cyclops_sdk_rust_future_free_rust_buffer(handle)
+ },
+ )
+
+ if err == nil {
+ return res, nil
+ }
+
+ return res, err
+}
+
+func (_self *CyclopsClient) DeleteUserApiKey(id string) error {
+ _pointer := _self.ffiObject.incrementPointer("*CyclopsClient")
+ defer _self.ffiObject.decrementPointer()
+ _, err := uniffiRustCallAsync[*SdkError](
+ FfiConverterSdkErrorINSTANCE,
+ // completeFn
+ func(handle C.uint64_t, status *C.RustCallStatus) struct{} {
+ C.ffi_cyclops_sdk_rust_future_complete_void(handle, status)
+ return struct{}{}
+ },
+ // liftFn
+ func(_ struct{}) struct{} { return struct{}{} },
+ C.uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_user_api_key(
+ _pointer, FfiConverterStringINSTANCE.Lower(id)),
+ // pollFn
+ func(handle C.uint64_t, continuation C.UniffiRustFutureContinuationCallback, data C.uint64_t) {
+ C.ffi_cyclops_sdk_rust_future_poll_void(handle, continuation, data)
+ },
+ // freeFn
+ func(handle C.uint64_t) {
+ C.ffi_cyclops_sdk_rust_future_free_void(handle)
+ },
+ )
+
+ if err == nil {
+ return nil
+ }
+
+ return err
+}
+
+func (_self *CyclopsClient) ListUserApiKeys() ([]UserApiKey, error) {
+ _pointer := _self.ffiObject.incrementPointer("*CyclopsClient")
+ defer _self.ffiObject.decrementPointer()
+ res, err := uniffiRustCallAsync[*SdkError](
+ FfiConverterSdkErrorINSTANCE,
+ // completeFn
+ func(handle C.uint64_t, status *C.RustCallStatus) RustBufferI {
+ res := C.ffi_cyclops_sdk_rust_future_complete_rust_buffer(handle, status)
+ return GoRustBuffer{
+ inner: res,
+ }
+ },
+ // liftFn
+ func(ffi RustBufferI) []UserApiKey {
+ return FfiConverterSequenceUserApiKeyINSTANCE.Lift(ffi)
+ },
+ C.uniffi_cyclops_sdk_fn_method_cyclopsclient_list_user_api_keys(
+ _pointer),
+ // pollFn
+ func(handle C.uint64_t, continuation C.UniffiRustFutureContinuationCallback, data C.uint64_t) {
+ C.ffi_cyclops_sdk_rust_future_poll_rust_buffer(handle, continuation, data)
+ },
+ // freeFn
+ func(handle C.uint64_t) {
+ C.ffi_cyclops_sdk_rust_future_free_rust_buffer(handle)
+ },
+ )
+
+ if err == nil {
+ return res, nil
+ }
+
+ return res, err
+}
func (object *CyclopsClient) Destroy() {
runtime.SetFinalizer(object, nil)
object.ffiObject.destroy()
@@ -2396,6 +2572,50 @@ func (_ FfiDestroyerCreateTemplateRequest) Destroy(value CreateTemplateRequest)
value.Destroy()
}
+type CreateUserApiKeyRequest struct {
+ Name string
+ Scope []string
+}
+
+func (r *CreateUserApiKeyRequest) Destroy() {
+ FfiDestroyerString{}.Destroy(r.Name)
+ FfiDestroyerSequenceString{}.Destroy(r.Scope)
+}
+
+type FfiConverterCreateUserApiKeyRequest struct{}
+
+var FfiConverterCreateUserApiKeyRequestINSTANCE = FfiConverterCreateUserApiKeyRequest{}
+
+func (c FfiConverterCreateUserApiKeyRequest) Lift(rb RustBufferI) CreateUserApiKeyRequest {
+ return LiftFromRustBuffer[CreateUserApiKeyRequest](c, rb)
+}
+
+func (c FfiConverterCreateUserApiKeyRequest) Read(reader io.Reader) CreateUserApiKeyRequest {
+ return CreateUserApiKeyRequest{
+ FfiConverterStringINSTANCE.Read(reader),
+ FfiConverterSequenceStringINSTANCE.Read(reader),
+ }
+}
+
+func (c FfiConverterCreateUserApiKeyRequest) Lower(value CreateUserApiKeyRequest) C.RustBuffer {
+ return LowerIntoRustBuffer[CreateUserApiKeyRequest](c, value)
+}
+
+func (c FfiConverterCreateUserApiKeyRequest) LowerExternal(value CreateUserApiKeyRequest) ExternalCRustBuffer {
+ return RustBufferFromC(LowerIntoRustBuffer[CreateUserApiKeyRequest](c, value))
+}
+
+func (c FfiConverterCreateUserApiKeyRequest) Write(writer io.Writer, value CreateUserApiKeyRequest) {
+ FfiConverterStringINSTANCE.Write(writer, value.Name)
+ FfiConverterSequenceStringINSTANCE.Write(writer, value.Scope)
+}
+
+type FfiDestroyerCreateUserApiKeyRequest struct{}
+
+func (_ FfiDestroyerCreateUserApiKeyRequest) Destroy(value CreateUserApiKeyRequest) {
+ value.Destroy()
+}
+
type CyclopsConfiguration struct {
BaseUrl string
TokenUrl string
@@ -2660,6 +2880,114 @@ func (_ FfiDestroyerHttpResponse) Destroy(value HttpResponse) {
value.Destroy()
}
+type Namespace struct {
+ Name string
+ Status string
+ CreatedAt string
+ Labels *map[string]string
+}
+
+func (r *Namespace) Destroy() {
+ FfiDestroyerString{}.Destroy(r.Name)
+ FfiDestroyerString{}.Destroy(r.Status)
+ FfiDestroyerString{}.Destroy(r.CreatedAt)
+ FfiDestroyerOptionalMapStringString{}.Destroy(r.Labels)
+}
+
+type FfiConverterNamespace struct{}
+
+var FfiConverterNamespaceINSTANCE = FfiConverterNamespace{}
+
+func (c FfiConverterNamespace) Lift(rb RustBufferI) Namespace {
+ return LiftFromRustBuffer[Namespace](c, rb)
+}
+
+func (c FfiConverterNamespace) Read(reader io.Reader) Namespace {
+ return Namespace{
+ FfiConverterStringINSTANCE.Read(reader),
+ FfiConverterStringINSTANCE.Read(reader),
+ FfiConverterStringINSTANCE.Read(reader),
+ FfiConverterOptionalMapStringStringINSTANCE.Read(reader),
+ }
+}
+
+func (c FfiConverterNamespace) Lower(value Namespace) C.RustBuffer {
+ return LowerIntoRustBuffer[Namespace](c, value)
+}
+
+func (c FfiConverterNamespace) LowerExternal(value Namespace) ExternalCRustBuffer {
+ return RustBufferFromC(LowerIntoRustBuffer[Namespace](c, value))
+}
+
+func (c FfiConverterNamespace) Write(writer io.Writer, value Namespace) {
+ FfiConverterStringINSTANCE.Write(writer, value.Name)
+ FfiConverterStringINSTANCE.Write(writer, value.Status)
+ FfiConverterStringINSTANCE.Write(writer, value.CreatedAt)
+ FfiConverterOptionalMapStringStringINSTANCE.Write(writer, value.Labels)
+}
+
+type FfiDestroyerNamespace struct{}
+
+func (_ FfiDestroyerNamespace) Destroy(value Namespace) {
+ value.Destroy()
+}
+
+type NewUserApiKey struct {
+ ClientId string
+ ClientSecret string
+ TokenUrl string
+ Name string
+ Scope []string
+}
+
+func (r *NewUserApiKey) Destroy() {
+ FfiDestroyerString{}.Destroy(r.ClientId)
+ FfiDestroyerString{}.Destroy(r.ClientSecret)
+ FfiDestroyerString{}.Destroy(r.TokenUrl)
+ FfiDestroyerString{}.Destroy(r.Name)
+ FfiDestroyerSequenceString{}.Destroy(r.Scope)
+}
+
+type FfiConverterNewUserApiKey struct{}
+
+var FfiConverterNewUserApiKeyINSTANCE = FfiConverterNewUserApiKey{}
+
+func (c FfiConverterNewUserApiKey) Lift(rb RustBufferI) NewUserApiKey {
+ return LiftFromRustBuffer[NewUserApiKey](c, rb)
+}
+
+func (c FfiConverterNewUserApiKey) Read(reader io.Reader) NewUserApiKey {
+ return NewUserApiKey{
+ FfiConverterStringINSTANCE.Read(reader),
+ FfiConverterStringINSTANCE.Read(reader),
+ FfiConverterStringINSTANCE.Read(reader),
+ FfiConverterStringINSTANCE.Read(reader),
+ FfiConverterSequenceStringINSTANCE.Read(reader),
+ }
+}
+
+func (c FfiConverterNewUserApiKey) Lower(value NewUserApiKey) C.RustBuffer {
+ return LowerIntoRustBuffer[NewUserApiKey](c, value)
+}
+
+func (c FfiConverterNewUserApiKey) LowerExternal(value NewUserApiKey) ExternalCRustBuffer {
+ return RustBufferFromC(LowerIntoRustBuffer[NewUserApiKey](c, value))
+}
+
+func (c FfiConverterNewUserApiKey) Write(writer io.Writer, value NewUserApiKey) {
+ FfiConverterStringINSTANCE.Write(writer, value.ClientId)
+ FfiConverterStringINSTANCE.Write(writer, value.ClientSecret)
+ FfiConverterStringINSTANCE.Write(writer, value.TokenUrl)
+ FfiConverterStringINSTANCE.Write(writer, value.Name)
+ FfiConverterSequenceStringINSTANCE.Write(writer, value.Scope)
+}
+
+type FfiDestroyerNewUserApiKey struct{}
+
+func (_ FfiDestroyerNewUserApiKey) Destroy(value NewUserApiKey) {
+ value.Destroy()
+}
+
// UniFFI cannot emit aliases for external record types. Generated bindings use
// `OSGymSandboxWarmPoolStatus` and `OSGymSandboxClaimStatus` from cyclops_sdk_schema.
//
@@ -2724,15 +3052,17 @@ func (_ FfiDestroyerPool) Destroy(value Pool) {
}
type ResourceMetadata struct {
- Namespace string
- Name string
- Labels *map[string]string
+ Namespace string
+ Name string
+ Labels *map[string]string
+ CreationTimestamp *string
}
func (r *ResourceMetadata) Destroy() {
FfiDestroyerString{}.Destroy(r.Namespace)
FfiDestroyerString{}.Destroy(r.Name)
FfiDestroyerOptionalMapStringString{}.Destroy(r.Labels)
+ FfiDestroyerOptionalString{}.Destroy(r.CreationTimestamp)
}
type FfiConverterResourceMetadata struct{}
@@ -2748,6 +3078,7 @@ func (c FfiConverterResourceMetadata) Read(reader io.Reader) ResourceMetadata {
FfiConverterStringINSTANCE.Read(reader),
FfiConverterStringINSTANCE.Read(reader),
FfiConverterOptionalMapStringStringINSTANCE.Read(reader),
+ FfiConverterOptionalStringINSTANCE.Read(reader),
}
}
@@ -2763,6 +3094,7 @@ func (c FfiConverterResourceMetadata) Write(writer io.Writer, value ResourceMeta
FfiConverterStringINSTANCE.Write(writer, value.Namespace)
FfiConverterStringINSTANCE.Write(writer, value.Name)
FfiConverterOptionalMapStringStringINSTANCE.Write(writer, value.Labels)
+ FfiConverterOptionalStringINSTANCE.Write(writer, value.CreationTimestamp)
}
type FfiDestroyerResourceMetadata struct{}
@@ -2877,6 +3209,58 @@ func (_ FfiDestroyerTemplate) Destroy(value Template) {
value.Destroy()
}
+type UserApiKey struct {
+ Id string
+ ClientId string
+ Name string
+ Scope []string
+}
+
+func (r *UserApiKey) Destroy() {
+ FfiDestroyerString{}.Destroy(r.Id)
+ FfiDestroyerString{}.Destroy(r.ClientId)
+ FfiDestroyerString{}.Destroy(r.Name)
+ FfiDestroyerSequenceString{}.Destroy(r.Scope)
+}
+
+type FfiConverterUserApiKey struct{}
+
+var FfiConverterUserApiKeyINSTANCE = FfiConverterUserApiKey{}
+
+func (c FfiConverterUserApiKey) Lift(rb RustBufferI) UserApiKey {
+ return LiftFromRustBuffer[UserApiKey](c, rb)
+}
+
+func (c FfiConverterUserApiKey) Read(reader io.Reader) UserApiKey {
+ return UserApiKey{
+ FfiConverterStringINSTANCE.Read(reader),
+ FfiConverterStringINSTANCE.Read(reader),
+ FfiConverterStringINSTANCE.Read(reader),
+ FfiConverterSequenceStringINSTANCE.Read(reader),
+ }
+}
+
+func (c FfiConverterUserApiKey) Lower(value UserApiKey) C.RustBuffer {
+ return LowerIntoRustBuffer[UserApiKey](c, value)
+}
+
+func (c FfiConverterUserApiKey) LowerExternal(value UserApiKey) ExternalCRustBuffer {
+ return RustBufferFromC(LowerIntoRustBuffer[UserApiKey](c, value))
+}
+
+func (c FfiConverterUserApiKey) Write(writer io.Writer, value UserApiKey) {
+ FfiConverterStringINSTANCE.Write(writer, value.Id)
+ FfiConverterStringINSTANCE.Write(writer, value.ClientId)
+ FfiConverterStringINSTANCE.Write(writer, value.Name)
+ FfiConverterSequenceStringINSTANCE.Write(writer, value.Scope)
+}
+
+type FfiDestroyerUserApiKey struct{}
+
+func (_ FfiDestroyerUserApiKey) Destroy(value UserApiKey) {
+ value.Destroy()
+}
+
type AccessTokenProviderError struct {
err error
}
@@ -3578,6 +3962,47 @@ func (_ FfiDestroyerSdkError) Destroy(value *SdkError) {
}
}
+type FfiConverterOptionalString struct{}
+
+var FfiConverterOptionalStringINSTANCE = FfiConverterOptionalString{}
+
+func (c FfiConverterOptionalString) Lift(rb RustBufferI) *string {
+ return LiftFromRustBuffer[*string](c, rb)
+}
+
+func (_ FfiConverterOptionalString) Read(reader io.Reader) *string {
+ if readInt8(reader) == 0 {
+ return nil
+ }
+ temp := FfiConverterStringINSTANCE.Read(reader)
+ return &temp
+}
+
+func (c FfiConverterOptionalString) Lower(value *string) C.RustBuffer {
+ return LowerIntoRustBuffer[*string](c, value)
+}
+
+func (c FfiConverterOptionalString) LowerExternal(value *string) ExternalCRustBuffer {
+ return RustBufferFromC(LowerIntoRustBuffer[*string](c, value))
+}
+
+func (_ FfiConverterOptionalString) Write(writer io.Writer, value *string) {
+ if value == nil {
+ writeInt8(writer, 0)
+ } else {
+ writeInt8(writer, 1)
+ FfiConverterStringINSTANCE.Write(writer, *value)
+ }
+}
+
+type FfiDestroyerOptionalString struct{}
+
+func (_ FfiDestroyerOptionalString) Destroy(value *string) {
+ if value != nil {
+ FfiDestroyerString{}.Destroy(*value)
+ }
+}
+
type FfiConverterOptionalBytes struct{}
var FfiConverterOptionalBytesINSTANCE = FfiConverterOptionalBytes{}
@@ -3924,6 +4349,53 @@ func (FfiDestroyerSequenceHttpHeader) Destroy(sequence []HttpHeader) {
}
}
+type FfiConverterSequenceNamespace struct{}
+
+var FfiConverterSequenceNamespaceINSTANCE = FfiConverterSequenceNamespace{}
+
+func (c FfiConverterSequenceNamespace) Lift(rb RustBufferI) []Namespace {
+ return LiftFromRustBuffer[[]Namespace](c, rb)
+}
+
+func (c FfiConverterSequenceNamespace) Read(reader io.Reader) []Namespace {
+ length := readInt32(reader)
+ if length == 0 {
+ return nil
+ }
+ result := make([]Namespace, 0, length)
+ for i := int32(0); i < length; i++ {
+ result = append(result, FfiConverterNamespaceINSTANCE.Read(reader))
+ }
+ return result
+}
+
+func (c FfiConverterSequenceNamespace) Lower(value []Namespace) C.RustBuffer {
+ return LowerIntoRustBuffer[[]Namespace](c, value)
+}
+
+func (c FfiConverterSequenceNamespace) LowerExternal(value []Namespace) ExternalCRustBuffer {
+ return RustBufferFromC(LowerIntoRustBuffer[[]Namespace](c, value))
+}
+
+func (c FfiConverterSequenceNamespace) Write(writer io.Writer, value []Namespace) {
+ if len(value) > math.MaxInt32 {
+ panic("[]Namespace is too large to fit into Int32")
+ }
+
+ writeInt32(writer, int32(len(value)))
+ for _, item := range value {
+ FfiConverterNamespaceINSTANCE.Write(writer, item)
+ }
+}
+
+type FfiDestroyerSequenceNamespace struct{}
+
+func (FfiDestroyerSequenceNamespace) Destroy(sequence []Namespace) {
+ for _, value := range sequence {
+ FfiDestroyerNamespace{}.Destroy(value)
+ }
+}
+
type FfiConverterSequencePool struct{}
var FfiConverterSequencePoolINSTANCE = FfiConverterSequencePool{}
@@ -4018,6 +4490,53 @@ func (FfiDestroyerSequenceTemplate) Destroy(sequence []Template) {
}
}
+type FfiConverterSequenceUserApiKey struct{}
+
+var FfiConverterSequenceUserApiKeyINSTANCE = FfiConverterSequenceUserApiKey{}
+
+func (c FfiConverterSequenceUserApiKey) Lift(rb RustBufferI) []UserApiKey {
+ return LiftFromRustBuffer[[]UserApiKey](c, rb)
+}
+
+func (c FfiConverterSequenceUserApiKey) Read(reader io.Reader) []UserApiKey {
+ length := readInt32(reader)
+ if length == 0 {
+ return nil
+ }
+ result := make([]UserApiKey, 0, length)
+ for i := int32(0); i < length; i++ {
+ result = append(result, FfiConverterUserApiKeyINSTANCE.Read(reader))
+ }
+ return result
+}
+
+func (c FfiConverterSequenceUserApiKey) Lower(value []UserApiKey) C.RustBuffer {
+ return LowerIntoRustBuffer[[]UserApiKey](c, value)
+}
+
+func (c FfiConverterSequenceUserApiKey) LowerExternal(value []UserApiKey) ExternalCRustBuffer {
+ return RustBufferFromC(LowerIntoRustBuffer[[]UserApiKey](c, value))
+}
+
+func (c FfiConverterSequenceUserApiKey) Write(writer io.Writer, value []UserApiKey) {
+ if len(value) > math.MaxInt32 {
+ panic("[]UserApiKey is too large to fit into Int32")
+ }
+
+ writeInt32(writer, int32(len(value)))
+ for _, item := range value {
+ FfiConverterUserApiKeyINSTANCE.Write(writer, item)
+ }
+}
+
+type FfiDestroyerSequenceUserApiKey struct{}
+
+func (FfiDestroyerSequenceUserApiKey) Destroy(sequence []UserApiKey) {
+ for _, value := range sequence {
+ FfiDestroyerUserApiKey{}.Destroy(value)
+ }
+}
+
type FfiConverterMapStringString struct{}
var FfiConverterMapStringStringINSTANCE = FfiConverterMapStringString{}
diff --git a/libs/fleet/sdk-bindings/go-uniffi/fleet_sdk/fleet_sdk.h b/libs/fleet/sdk-bindings/go-uniffi/fleet_sdk/fleet_sdk.h
index 45080b8b4d..26eb4462fb 100644
--- a/libs/fleet/sdk-bindings/go-uniffi/fleet_sdk/fleet_sdk.h
+++ b/libs/fleet/sdk-bindings/go-uniffi/fleet_sdk/fleet_sdk.h
@@ -486,6 +486,11 @@ uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_list_claims(uint64_t ptr, Ru
uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_wait_claim(uint64_t ptr, RustBuffer claim
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_LIST_NAMESPACES
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_LIST_NAMESPACES
+uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_list_namespaces(uint64_t ptr
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_CREATE_POOL
#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_CREATE_POOL
uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_create_pool(uint64_t ptr, RustBuffer request
@@ -551,6 +556,21 @@ uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_reconcile_template(uint64_t
uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_update_template(uint64_t ptr, RustBuffer template
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_CREATE_USER_API_KEY
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_CREATE_USER_API_KEY
+uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_create_user_api_key(uint64_t ptr, RustBuffer request
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_DELETE_USER_API_KEY
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_DELETE_USER_API_KEY
+uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_user_api_key(uint64_t ptr, RustBuffer id
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_LIST_USER_API_KEYS
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_LIST_USER_API_KEYS
+uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_list_user_api_keys(uint64_t ptr
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_CLONE_ACCESSTOKENPROVIDER
#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_CLONE_ACCESSTOKENPROVIDER
uint64_t uniffi_cyclops_sdk_fn_clone_accesstokenprovider(uint64_t handle, RustCallStatus *out_status
@@ -894,6 +914,12 @@ uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_claims(void
#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_WAIT_CLAIM
uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_LIST_NAMESPACES
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_LIST_NAMESPACES
+uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_namespaces(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_CREATE_POOL
@@ -972,6 +998,24 @@ uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_reconcile_template(voi
#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_UPDATE_TEMPLATE
uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_update_template(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_CREATE_USER_API_KEY
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_CREATE_USER_API_KEY
+uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_user_api_key(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_DELETE_USER_API_KEY
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_DELETE_USER_API_KEY
+uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_user_api_key(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_LIST_USER_API_KEYS
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_LIST_USER_API_KEYS
+uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_user_api_keys(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_ACCESSTOKENPROVIDER_GET_ACCESS_TOKEN
diff --git a/libs/fleet/sdk-bindings/kotlin/ai/cua/cyclops/sdk/fleet_sdk.kt b/libs/fleet/sdk-bindings/kotlin/ai/cua/cyclops/sdk/fleet_sdk.kt
index 55a995c753..1874750e51 100644
--- a/libs/fleet/sdk-bindings/kotlin/ai/cua/cyclops/sdk/fleet_sdk.kt
+++ b/libs/fleet/sdk-bindings/kotlin/ai/cua/cyclops/sdk/fleet_sdk.kt
@@ -712,6 +712,8 @@ internal object IntegrityCheckingUniffiLib {
): Short
external fun uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim(
): Short
+ external fun uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_namespaces(
+ ): Short
external fun uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_pool(
): Short
external fun uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_pool(
@@ -738,6 +740,12 @@ internal object IntegrityCheckingUniffiLib {
): Short
external fun uniffi_cyclops_sdk_checksum_method_cyclopsclient_update_template(
): Short
+ external fun uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_user_api_key(
+ ): Short
+ external fun uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_user_api_key(
+ ): Short
+ external fun uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_user_api_keys(
+ ): Short
external fun uniffi_cyclops_sdk_checksum_method_accesstokenprovider_get_access_token(
): Short
external fun uniffi_cyclops_sdk_checksum_method_httpclient_execute(
@@ -807,6 +815,8 @@ external fun uniffi_cyclops_sdk_fn_method_cyclopsclient_list_claims(`ptr`: Long,
): Long
external fun uniffi_cyclops_sdk_fn_method_cyclopsclient_wait_claim(`ptr`: Long,`claim`: RustBuffer.ByValue,
): Long
+external fun uniffi_cyclops_sdk_fn_method_cyclopsclient_list_namespaces(`ptr`: Long,
+): Long
external fun uniffi_cyclops_sdk_fn_method_cyclopsclient_create_pool(`ptr`: Long,`request`: RustBuffer.ByValue,
): Long
external fun uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_pool(`ptr`: Long,`pool`: RustBuffer.ByValue,
@@ -833,6 +843,12 @@ external fun uniffi_cyclops_sdk_fn_method_cyclopsclient_reconcile_template(`ptr`
): Long
external fun uniffi_cyclops_sdk_fn_method_cyclopsclient_update_template(`ptr`: Long,`template`: RustBuffer.ByValue,
): Long
+external fun uniffi_cyclops_sdk_fn_method_cyclopsclient_create_user_api_key(`ptr`: Long,`request`: RustBuffer.ByValue,
+): Long
+external fun uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_user_api_key(`ptr`: Long,`id`: RustBuffer.ByValue,
+): Long
+external fun uniffi_cyclops_sdk_fn_method_cyclopsclient_list_user_api_keys(`ptr`: Long,
+): Long
external fun uniffi_cyclops_sdk_fn_clone_accesstokenprovider(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
): Long
external fun uniffi_cyclops_sdk_fn_free_accesstokenprovider(`handle`: Long,uniffi_out_err: UniffiRustCallStatus,
@@ -989,6 +1005,9 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {
if (lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim() != 18984.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
+ if (lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_namespaces() != 65288.toShort()) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
if (lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_pool() != 48557.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
@@ -1028,6 +1047,15 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {
if (lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_update_template() != 18704.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
+ if (lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_user_api_key() != 9174.toShort()) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
+ if (lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_user_api_key() != 1700.toShort()) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
+ if (lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_user_api_keys() != 5949.toShort()) {
+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
if (lib.uniffi_cyclops_sdk_checksum_method_accesstokenprovider_get_access_token() != 1180.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
@@ -1987,6 +2015,8 @@ public interface CyclopsClientInterface {
suspend fun `waitClaim`(`claim`: Claim): Sandbox
+ suspend fun `listNamespaces`(): List<Namespace>
+
suspend fun `createPool`(`request`: CreatePoolRequest): Pool
suspend fun `deletePool`(`pool`: Pool)
@@ -2013,6 +2043,12 @@ public interface CyclopsClientInterface {
suspend fun `updateTemplate`(`template`: Template): Template
+ suspend fun `createUserApiKey`(`request`: CreateUserApiKeyRequest): NewUserApiKey
+
+ suspend fun `deleteUserApiKey`(`id`: kotlin.String)
+
+ suspend fun `listUserApiKeys`(): List<UserApiKey>
+
companion object
}
@@ -2219,6 +2255,27 @@ open class CyclopsClient: Disposable, AutoCloseable, CyclopsClientInterface
}
+ @Throws(SdkException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `listNamespaces`() : List<Namespace> {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_list_namespaces(
+ uniffiHandle,
+
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterSequenceTypeNamespace.lift(it) },
+ // Error FFI converter
+ SdkException.ErrorHandler,
+ )
+ }
+
+
@Throws(SdkException::class)
@Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
override suspend fun `createPool`(`request`: CreatePoolRequest) : Pool {
@@ -2494,6 +2551,70 @@ open class CyclopsClient: Disposable, AutoCloseable, CyclopsClientInterface
}
+ @Throws(SdkException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `createUserApiKey`(`request`: CreateUserApiKeyRequest) : NewUserApiKey {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_create_user_api_key(
+ uniffiHandle,
+ FfiConverterTypeCreateUserApiKeyRequest.lower(`request`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterTypeNewUserApiKey.lift(it) },
+ // Error FFI converter
+ SdkException.ErrorHandler,
+ )
+ }
+
+
+ @Throws(SdkException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `deleteUserApiKey`(`id`: kotlin.String) {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_user_api_key(
+ uniffiHandle,
+ FfiConverterString.lower(`id`),
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_poll_void(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_complete_void(future, continuation) },
+ { future -> UniffiLib.ffi_cyclops_sdk_rust_future_free_void(future) },
+ // lift function
+ { Unit },
+
+ // Error FFI converter
+ SdkException.ErrorHandler,
+ )
+ }
+
+
+ @Throws(SdkException::class)
+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
+ override suspend fun `listUserApiKeys`() : List<UserApiKey> {
+ return uniffiRustCallAsync(
+ callWithHandle { uniffiHandle ->
+ UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_list_user_api_keys(
+ uniffiHandle,
+
+ )
+ },
+ { future, callback, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },
+ { future, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer(future, continuation) },
+ { future -> UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer(future) },
+ // lift function
+ { FfiConverterSequenceTypeUserApiKey.lift(it) },
+ // Error FFI converter
+ SdkException.ErrorHandler,
+ )
+ }
+
+
@@ -3366,6 +3487,44 @@ public object FfiConverterTypeCreateTemplateRequest: FfiConverterRustBuffer<Crea
+data class CreateUserApiKeyRequest (
+ var `name`: kotlin.String
+ ,
+ var `scope`: List<kotlin.String>
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeCreateUserApiKeyRequest: FfiConverterRustBuffer<CreateUserApiKeyRequest> {
+ override fun read(buf: ByteBuffer): CreateUserApiKeyRequest {
+ return CreateUserApiKeyRequest(
+ FfiConverterString.read(buf),
+ FfiConverterSequenceString.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: CreateUserApiKeyRequest) = (
+ FfiConverterString.allocationSize(value.`name`) +
+ FfiConverterSequenceString.allocationSize(value.`scope`)
+ )
+
+ override fun write(value: CreateUserApiKeyRequest, buf: ByteBuffer) {
+ FfiConverterString.write(value.`name`, buf)
+ FfiConverterSequenceString.write(value.`scope`, buf)
+ }
+}
+
+
+
data class CyclopsConfiguration (
var `baseUrl`: kotlin.String
,
@@ -3625,6 +3784,107 @@ public object FfiConverterTypeHttpResponse: FfiConverterRustBuffer<HttpResponse>
+data class Namespace (
+ var `name`: kotlin.String
+ ,
+ var `status`: kotlin.String
+ ,
+ var `createdAt`: kotlin.String
+ ,
+ var `labels`: Map<kotlin.String, kotlin.String>?
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeNamespace: FfiConverterRustBuffer<Namespace> {
+ override fun read(buf: ByteBuffer): Namespace {
+ return Namespace(
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterOptionalMapStringString.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: Namespace) = (
+ FfiConverterString.allocationSize(value.`name`) +
+ FfiConverterString.allocationSize(value.`status`) +
+ FfiConverterString.allocationSize(value.`createdAt`) +
+ FfiConverterOptionalMapStringString.allocationSize(value.`labels`)
+ )
+
+ override fun write(value: Namespace, buf: ByteBuffer) {
+ FfiConverterString.write(value.`name`, buf)
+ FfiConverterString.write(value.`status`, buf)
+ FfiConverterString.write(value.`createdAt`, buf)
+ FfiConverterOptionalMapStringString.write(value.`labels`, buf)
+ }
+}
+
+
+
+data class NewUserApiKey (
+ var `clientId`: kotlin.String
+ ,
+ var `clientSecret`: kotlin.String
+ ,
+ var `tokenUrl`: kotlin.String
+ ,
+ var `name`: kotlin.String
+ ,
+ var `scope`: List<kotlin.String>
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeNewUserApiKey: FfiConverterRustBuffer<NewUserApiKey> {
+ override fun read(buf: ByteBuffer): NewUserApiKey {
+ return NewUserApiKey(
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterSequenceString.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: NewUserApiKey) = (
+ FfiConverterString.allocationSize(value.`clientId`) +
+ FfiConverterString.allocationSize(value.`clientSecret`) +
+ FfiConverterString.allocationSize(value.`tokenUrl`) +
+ FfiConverterString.allocationSize(value.`name`) +
+ FfiConverterSequenceString.allocationSize(value.`scope`)
+ )
+
+ override fun write(value: NewUserApiKey, buf: ByteBuffer) {
+ FfiConverterString.write(value.`clientId`, buf)
+ FfiConverterString.write(value.`clientSecret`, buf)
+ FfiConverterString.write(value.`tokenUrl`, buf)
+ FfiConverterString.write(value.`name`, buf)
+ FfiConverterSequenceString.write(value.`scope`, buf)
+ }
+}
+
+
+
/**
* UniFFI cannot emit aliases for external record types. Generated bindings use
* `OSGymSandboxWarmPoolStatus` and `OSGymSandboxClaimStatus` from cyclops_sdk_schema.
@@ -3693,6 +3953,8 @@ data class ResourceMetadata (
var `name`: kotlin.String
,
var `labels`: Map<kotlin.String, kotlin.String>?
+ ,
+ var `creationTimestamp`: kotlin.String?
){
@@ -3712,19 +3974,22 @@ public object FfiConverterTypeResourceMetadata: FfiConverterRustBuffer<ResourceM
FfiConverterString.read(buf),
FfiConverterString.read(buf),
FfiConverterOptionalMapStringString.read(buf),
+ FfiConverterOptionalString.read(buf),
)
}
override fun allocationSize(value: ResourceMetadata) = (
FfiConverterString.allocationSize(value.`namespace`) +
FfiConverterString.allocationSize(value.`name`) +
- FfiConverterOptionalMapStringString.allocationSize(value.`labels`)
+ FfiConverterOptionalMapStringString.allocationSize(value.`labels`) +
+ FfiConverterOptionalString.allocationSize(value.`creationTimestamp`)
)
override fun write(value: ResourceMetadata, buf: ByteBuffer) {
FfiConverterString.write(value.`namespace`, buf)
FfiConverterString.write(value.`name`, buf)
FfiConverterOptionalMapStringString.write(value.`labels`, buf)
+ FfiConverterOptionalString.write(value.`creationTimestamp`, buf)
}
}
@@ -3830,6 +4095,54 @@ public object FfiConverterTypeTemplate: FfiConverterRustBuffer<Template> {
+data class UserApiKey (
+ var `id`: kotlin.String
+ ,
+ var `clientId`: kotlin.String
+ ,
+ var `name`: kotlin.String
+ ,
+ var `scope`: List<kotlin.String>
+
+){
+
+
+
+
+
+ companion object
+}
+
+/**
+ * @suppress
+ */
+public object FfiConverterTypeUserApiKey: FfiConverterRustBuffer<UserApiKey> {
+ override fun read(buf: ByteBuffer): UserApiKey {
+ return UserApiKey(
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterString.read(buf),
+ FfiConverterSequenceString.read(buf),
+ )
+ }
+
+ override fun allocationSize(value: UserApiKey) = (
+ FfiConverterString.allocationSize(value.`id`) +
+ FfiConverterString.allocationSize(value.`clientId`) +
+ FfiConverterString.allocationSize(value.`name`) +
+ FfiConverterSequenceString.allocationSize(value.`scope`)
+ )
+
+ override fun write(value: UserApiKey, buf: ByteBuffer) {
+ FfiConverterString.write(value.`id`, buf)
+ FfiConverterString.write(value.`clientId`, buf)
+ FfiConverterString.write(value.`name`, buf)
+ FfiConverterSequenceString.write(value.`scope`, buf)
+ }
+}
+
+
+
sealed class AccessTokenProviderException: kotlin.Exception() {
@@ -4230,6 +4543,38 @@ public object FfiConverterTypeSdkError : FfiConverterRustBuffer<SdkException> {
+/**
+ * @suppress
+ */
+public object FfiConverterOptionalString: FfiConverterRustBuffer<kotlin.String?> {
+ override fun read(buf: ByteBuffer): kotlin.String? {
+ if (buf.get().toInt() == 0) {
+ return null
+ }
+ return FfiConverterString.read(buf)
+ }
+
+ override fun allocationSize(value: kotlin.String?): ULong {
+ if (value == null) {
+ return 1UL
+ } else {
+ return 1UL + FfiConverterString.allocationSize(value)
+ }
+ }
+
+ override fun write(value: kotlin.String?, buf: ByteBuffer) {
+ if (value == null) {
+ buf.put(0)
+ } else {
+ buf.put(1)
+ FfiConverterString.write(value, buf)
+ }
+ }
+}
+
+
+
+
/**
* @suppress
*/
@@ -4474,6 +4819,34 @@ public object FfiConverterSequenceTypeHttpHeader: FfiConverterRustBuffer<List<Ht
+/**
+ * @suppress
+ */
+public object FfiConverterSequenceTypeNamespace: FfiConverterRustBuffer<List<Namespace>> {
+ override fun read(buf: ByteBuffer): List<Namespace> {
+ val len = buf.getInt()
+ return List<Namespace>(len) {
+ FfiConverterTypeNamespace.read(buf)
+ }
+ }
+
+ override fun allocationSize(value: List<Namespace>): ULong {
+ val sizeForLength = 4UL
+ val sizeForItems = value.map { FfiConverterTypeNamespace.allocationSize(it) }.sum()
+ return sizeForLength + sizeForItems
+ }
+
+ override fun write(value: List<Namespace>, buf: ByteBuffer) {
+ buf.putInt(value.size)
+ value.iterator().forEach {
+ FfiConverterTypeNamespace.write(it, buf)
+ }
+ }
+}
+
+
+
+
/**
* @suppress
*/
@@ -4530,6 +4903,34 @@ public object FfiConverterSequenceTypeTemplate: FfiConverterRustBuffer<List<Temp
+/**
+ * @suppress
+ */
+public object FfiConverterSequenceTypeUserApiKey: FfiConverterRustBuffer<List<UserApiKey>> {
+ override fun read(buf: ByteBuffer): List<UserApiKey> {
+ val len = buf.getInt()
+ return List<UserApiKey>(len) {
+ FfiConverterTypeUserApiKey.read(buf)
+ }
+ }
+
+ override fun allocationSize(value: List<UserApiKey>): ULong {
+ val sizeForLength = 4UL
+ val sizeForItems = value.map { FfiConverterTypeUserApiKey.allocationSize(it) }.sum()
+ return sizeForLength + sizeForItems
+ }
+
+ override fun write(value: List<UserApiKey>, buf: ByteBuffer) {
+ buf.putInt(value.size)
+ value.iterator().forEach {
+ FfiConverterTypeUserApiKey.write(it, buf)
+ }
+ }
+}
+
+
+
+
/**
* @suppress
*/
diff --git a/libs/fleet/sdk-bindings/kotlin/tests/TestAsyncClient.kt b/libs/fleet/sdk-bindings/kotlin/tests/TestAsyncClient.kt
index 8af0ddbfe0..2f5f449fee 100644
--- a/libs/fleet/sdk-bindings/kotlin/tests/TestAsyncClient.kt
+++ b/libs/fleet/sdk-bindings/kotlin/tests/TestAsyncClient.kt
@@ -14,6 +14,17 @@ private data class Expected(
val response: ByteArray,
)
+private val generatedClaimNamePattern = Regex("claim-[a-z0-9](?:[-a-z0-9]*[a-z0-9])?")
+private val claimNameFieldPattern = Regex("\"name\":\"(claim-[^\"]+)\"")
+
+private fun normalizedGeneratedClaimBody(body: ByteArray?): ByteArray? {
+ val text = body?.decodeToString() ?: return null
+ val match = claimNameFieldPattern.find(text) ?: return null
+ val name = match.groupValues[1]
+ check(name.length <= 63 && generatedClaimNamePattern.matches(name))
+ return text.replaceRange(match.groups[1]!!.range, "claim-generated").encodeToByteArray()
+}
+
private val jsonHeaders = listOf(
"accept" to "application/json",
"content-type" to "application/json",
@@ -68,7 +79,13 @@ private class ScriptedHttpClient(expected: List<Expected>) : HttpClient {
val item = expected.removeFirstOrNull() ?: error("unexpected request")
check(request.method == item.method && request.url == item.url)
check(request.headers.map { it.name to it.value } == item.headers)
- check((request.body == null && item.body == null) || (request.body != null && item.body != null && request.body.contentEquals(item.body)))
+ if (request.method == "POST" && request.url.endsWith("/osgymsandboxclaims")) {
+ val actualBody = normalizedGeneratedClaimBody(request.body)
+ val expectedBody = normalizedGeneratedClaimBody(item.body)
+ check(actualBody != null && expectedBody != null && actualBody.contentEquals(expectedBody))
+ } else {
+ check((request.body == null && item.body == null) || (request.body != null && item.body != null && request.body.contentEquals(item.body)))
+ }
HttpResponse(item.status, emptyList(), item.response)
}
diff --git a/libs/fleet/sdk-bindings/python/contract_fixture.py b/libs/fleet/sdk-bindings/python/contract_fixture.py
index dbcce63a3d..61f1c477d5 100644
--- a/libs/fleet/sdk-bindings/python/contract_fixture.py
+++ b/libs/fleet/sdk-bindings/python/contract_fixture.py
@@ -1,5 +1,6 @@
import asyncio
import json
+import re
from dataclasses import dataclass
from fleet_sdk import (ClaimSpec, CreateClaimRequest, CreatePoolRequest, CyclopsClient,
@@ -21,6 +22,15 @@ class Expected:
status: int
response: object
+def normalized_generated_claim_body(body):
+ if body is None:
+ return None
+ value = json.loads(body)
+ name = value['metadata']['name']
+ assert len(name.encode()) <= 63 and re.fullmatch(r'claim-[a-z0-9](?:[-a-z0-9]*[a-z0-9])?', name), name
+ value['metadata']['name'] = 'claim-generated'
+ return json.dumps(value, separators=(',', ':'), sort_keys=True).encode()
+
class ScriptedHttpClient(HttpClient):
def __init__(self, expected):
self.expected = list(expected)
@@ -32,7 +42,13 @@ class ScriptedHttpClient(HttpClient):
assert self.expected, f'unexpected request: {request.method} {request.url}'
item = self.expected.pop(0)
actual_headers = [(header.name, header.value) for header in request.headers]
- assert (request.method, request.url, actual_headers, request.body) == (item.method, item.url, item.headers, item.body)
+ actual = (request.method, request.url, actual_headers)
+ expected = (item.method, item.url, item.headers)
+ assert actual == expected, f"request mismatch:\nactual={actual!r}\nexpected={expected!r}"
+ if request.method == 'POST' and request.url.endswith('/osgymsandboxclaims'):
+ assert normalized_generated_claim_body(request.body) == normalized_generated_claim_body(item.body)
+ else:
+ assert (request.method, request.url, actual_headers, request.body) == (item.method, item.url, item.headers, item.body)
self.requests.append(request)
body = item.response if isinstance(item.response, bytes) else json.dumps(item.response, separators=(',', ':')).encode()
return HttpResponse(status=item.status, headers=[], body=body)
diff --git a/libs/fleet/sdk-bindings/python/fleet_sdk/_sdk.py b/libs/fleet/sdk-bindings/python/fleet_sdk/_sdk.py
index d7270278e9..f0e0b969e7 100644
--- a/libs/fleet/sdk-bindings/python/fleet_sdk/_sdk.py
+++ b/libs/fleet/sdk-bindings/python/fleet_sdk/_sdk.py
@@ -502,12 +502,16 @@ def _uniffi_check_api_checksums(lib):
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_template() != 13689:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_user_api_key() != 9174:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_claim() != 20460:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_pool() != 31235:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_template() != 54852:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_user_api_key() != 1700:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_claim() != 17760:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_pool() != 49450:
@@ -516,10 +520,14 @@ def _uniffi_check_api_checksums(lib):
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_claims() != 7802:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_namespaces() != 65288:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_pools() != 27984:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_templates() != 58376:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_user_api_keys() != 5949:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_reconcile_pool() != 53919:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_reconcile_template() != 36469:
@@ -941,6 +949,11 @@ _UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_create_template.argtypes =
_UniffiRustBuffer,
)
_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_create_template.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_create_user_api_key.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_create_user_api_key.restype = ctypes.c_uint64
_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_claim.argtypes = (
ctypes.c_uint64,
_UniffiRustBuffer,
@@ -956,6 +969,11 @@ _UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_template.argtypes =
_UniffiRustBuffer,
)
_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_template.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_user_api_key.argtypes = (
+ ctypes.c_uint64,
+ _UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_user_api_key.restype = ctypes.c_uint64
_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_get_claim.argtypes = (
ctypes.c_uint64,
_UniffiRustBuffer,
@@ -977,6 +995,10 @@ _UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_list_claims.argtypes = (
_UniffiRustBuffer,
)
_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_list_claims.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_list_namespaces.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_list_namespaces.restype = ctypes.c_uint64
_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_list_pools.argtypes = (
ctypes.c_uint64,
_UniffiRustBuffer,
@@ -987,6 +1009,10 @@ _UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_list_templates.argtypes =
_UniffiRustBuffer,
)
_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_list_templates.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_list_user_api_keys.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_list_user_api_keys.restype = ctypes.c_uint64
_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_reconcile_pool.argtypes = (
ctypes.c_uint64,
_UniffiRustBuffer,
@@ -1067,6 +1093,9 @@ _UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_pool.restype
_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_template.argtypes = (
)
_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_template.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_user_api_key.argtypes = (
+)
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_user_api_key.restype = ctypes.c_uint16
_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_claim.argtypes = (
)
_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_claim.restype = ctypes.c_uint16
@@ -1076,6 +1105,9 @@ _UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_pool.restype
_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_template.argtypes = (
)
_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_template.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_user_api_key.argtypes = (
+)
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_user_api_key.restype = ctypes.c_uint16
_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_claim.argtypes = (
)
_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_claim.restype = ctypes.c_uint16
@@ -1088,12 +1120,18 @@ _UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_template.restype
_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_claims.argtypes = (
)
_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_claims.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_namespaces.argtypes = (
+)
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_namespaces.restype = ctypes.c_uint16
_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_pools.argtypes = (
)
_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_pools.restype = ctypes.c_uint16
_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_templates.argtypes = (
)
_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_templates.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_user_api_keys.argtypes = (
+)
+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_user_api_keys.restype = ctypes.c_uint16
_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_reconcile_pool.argtypes = (
)
_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_reconcile_pool.restype = ctypes.c_uint16
@@ -1339,18 +1377,44 @@ class _UniffiFfiConverterOptionalMapStringString(_UniffiConverterRustBuffer):
else:
raise InternalError("Unexpected flag byte for optional type")
+class _UniffiFfiConverterOptionalString(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterString.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterString.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterString.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
@dataclass
class ResourceMetadata:
- def __init__(self, *, namespace:str, name:str, labels:typing.Optional[dict[str, str]]):
+ def __init__(self, *, namespace:str, name:str, labels:typing.Optional[dict[str, str]], creation_timestamp:typing.Optional[str]):
self.namespace = namespace
self.name = name
self.labels = labels
+ self.creation_timestamp = creation_timestamp
def __str__(self):
- return "ResourceMetadata(namespace={}, name={}, labels={})".format(self.namespace, self.name, self.labels)
+ return "ResourceMetadata(namespace={}, name={}, labels={}, creation_timestamp={})".format(self.namespace, self.name, self.labels, self.creation_timestamp)
def __eq__(self, other):
if self.namespace != other.namespace:
return False
@@ -1358,6 +1422,8 @@ class ResourceMetadata:
return False
if self.labels != other.labels:
return False
+ if self.creation_timestamp != other.creation_timestamp:
+ return False
return True
class _UniffiFfiConverterTypeResourceMetadata(_UniffiConverterRustBuffer):
@@ -1367,6 +1433,7 @@ class _UniffiFfiConverterTypeResourceMetadata(_UniffiConverterRustBuffer):
namespace=_UniffiFfiConverterString.read(buf),
name=_UniffiFfiConverterString.read(buf),
labels=_UniffiFfiConverterOptionalMapStringString.read(buf),
+ creation_timestamp=_UniffiFfiConverterOptionalString.read(buf),
)
@staticmethod
@@ -1374,12 +1441,14 @@ class _UniffiFfiConverterTypeResourceMetadata(_UniffiConverterRustBuffer):
_UniffiFfiConverterString.check_lower(value.namespace)
_UniffiFfiConverterString.check_lower(value.name)
_UniffiFfiConverterOptionalMapStringString.check_lower(value.labels)
+ _UniffiFfiConverterOptionalString.check_lower(value.creation_timestamp)
@staticmethod
def write(value, buf):
_UniffiFfiConverterString.write(value.namespace, buf)
_UniffiFfiConverterString.write(value.name, buf)
_UniffiFfiConverterOptionalMapStringString.write(value.labels, buf)
+ _UniffiFfiConverterOptionalString.write(value.creation_timestamp, buf)
@@ -1697,6 +1766,65 @@ class _UniffiFfiConverterTypeCreateTemplateRequest(_UniffiConverterRustBuffer):
_UniffiFfiConverterString.write(value.name, buf)
fleet_sdk._UniffiFfiConverterTypeOSGymSandboxTemplateSpec.write(value.spec, buf)
+class _UniffiFfiConverterSequenceString(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ for item in value:
+ _UniffiFfiConverterString.check_lower(item)
+
+ @classmethod
+ def write(cls, value, buf):
+ items = len(value)
+ buf.write_i32(items)
+ for item in value:
+ _UniffiFfiConverterString.write(item, buf)
+
+ @classmethod
+ def read(cls, buf):
+ count = buf.read_i32()
+ if count < 0:
+ raise InternalError("Unexpected negative sequence length")
+
+ return [
+ _UniffiFfiConverterString.read(buf) for i in range(count)
+ ]
+
+@dataclass
+class CreateUserApiKeyRequest:
+ def __init__(self, *, name:str, scope:typing.List[str]):
+ self.name = name
+ self.scope = scope
+
+
+
+
+ def __str__(self):
+ return "CreateUserApiKeyRequest(name={}, scope={})".format(self.name, self.scope)
+ def __eq__(self, other):
+ if self.name != other.name:
+ return False
+ if self.scope != other.scope:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeCreateUserApiKeyRequest(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return CreateUserApiKeyRequest(
+ name=_UniffiFfiConverterString.read(buf),
+ scope=_UniffiFfiConverterSequenceString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.name)
+ _UniffiFfiConverterSequenceString.check_lower(value.scope)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.name, buf)
+ _UniffiFfiConverterSequenceString.write(value.scope, buf)
+
class CyclopsCredentialsProtocol(typing.Protocol):
@@ -2123,28 +2251,107 @@ class _UniffiFfiConverterTypeHttpResponse(_UniffiConverterRustBuffer):
_UniffiFfiConverterSequenceTypeHttpHeader.write(value.headers, buf)
_UniffiFfiConverterBytes.write(value.body, buf)
-class _UniffiFfiConverterSequenceString(_UniffiConverterRustBuffer):
- @classmethod
- def check_lower(cls, value):
- for item in value:
- _UniffiFfiConverterString.check_lower(item)
+@dataclass
+class Namespace:
+ def __init__(self, *, name:str, status:str, created_at:str, labels:typing.Optional[dict[str, str]]):
+ self.name = name
+ self.status = status
+ self.created_at = created_at
+ self.labels = labels
- @classmethod
- def write(cls, value, buf):
- items = len(value)
- buf.write_i32(items)
- for item in value:
- _UniffiFfiConverterString.write(item, buf)
- @classmethod
- def read(cls, buf):
- count = buf.read_i32()
- if count < 0:
- raise InternalError("Unexpected negative sequence length")
- return [
- _UniffiFfiConverterString.read(buf) for i in range(count)
- ]
+
+ def __str__(self):
+ return "Namespace(name={}, status={}, created_at={}, labels={})".format(self.name, self.status, self.created_at, self.labels)
+ def __eq__(self, other):
+ if self.name != other.name:
+ return False
+ if self.status != other.status:
+ return False
+ if self.created_at != other.created_at:
+ return False
+ if self.labels != other.labels:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeNamespace(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return Namespace(
+ name=_UniffiFfiConverterString.read(buf),
+ status=_UniffiFfiConverterString.read(buf),
+ created_at=_UniffiFfiConverterString.read(buf),
+ labels=_UniffiFfiConverterOptionalMapStringString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.name)
+ _UniffiFfiConverterString.check_lower(value.status)
+ _UniffiFfiConverterString.check_lower(value.created_at)
+ _UniffiFfiConverterOptionalMapStringString.check_lower(value.labels)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.name, buf)
+ _UniffiFfiConverterString.write(value.status, buf)
+ _UniffiFfiConverterString.write(value.created_at, buf)
+ _UniffiFfiConverterOptionalMapStringString.write(value.labels, buf)
+
+@dataclass
+class NewUserApiKey:
+ def __init__(self, *, client_id:str, client_secret:str, token_url:str, name:str, scope:typing.List[str]):
+ self.client_id = client_id
+ self.client_secret = client_secret
+ self.token_url = token_url
+ self.name = name
+ self.scope = scope
+
+
+
+
+ def __str__(self):
+ return "NewUserApiKey(client_id={}, client_secret={}, token_url={}, name={}, scope={})".format(self.client_id, self.client_secret, self.token_url, self.name, self.scope)
+ def __eq__(self, other):
+ if self.client_id != other.client_id:
+ return False
+ if self.client_secret != other.client_secret:
+ return False
+ if self.token_url != other.token_url:
+ return False
+ if self.name != other.name:
+ return False
+ if self.scope != other.scope:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeNewUserApiKey(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return NewUserApiKey(
+ client_id=_UniffiFfiConverterString.read(buf),
+ client_secret=_UniffiFfiConverterString.read(buf),
+ token_url=_UniffiFfiConverterString.read(buf),
+ name=_UniffiFfiConverterString.read(buf),
+ scope=_UniffiFfiConverterSequenceString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.client_id)
+ _UniffiFfiConverterString.check_lower(value.client_secret)
+ _UniffiFfiConverterString.check_lower(value.token_url)
+ _UniffiFfiConverterString.check_lower(value.name)
+ _UniffiFfiConverterSequenceString.check_lower(value.scope)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.client_id, buf)
+ _UniffiFfiConverterString.write(value.client_secret, buf)
+ _UniffiFfiConverterString.write(value.token_url, buf)
+ _UniffiFfiConverterString.write(value.name, buf)
+ _UniffiFfiConverterSequenceString.write(value.scope, buf)
@dataclass
class Sandbox:
@@ -2246,6 +2453,54 @@ class _UniffiFfiConverterTypeTemplate(_UniffiConverterRustBuffer):
_UniffiFfiConverterTypeResourceMetadata.write(value.metadata, buf)
fleet_sdk._UniffiFfiConverterTypeOSGymSandboxTemplateSpec.write(value.spec, buf)
+@dataclass
+class UserApiKey:
+ def __init__(self, *, id:str, client_id:str, name:str, scope:typing.List[str]):
+ self.id = id
+ self.client_id = client_id
+ self.name = name
+ self.scope = scope
+
+
+
+
+ def __str__(self):
+ return "UserApiKey(id={}, client_id={}, name={}, scope={})".format(self.id, self.client_id, self.name, self.scope)
+ def __eq__(self, other):
+ if self.id != other.id:
+ return False
+ if self.client_id != other.client_id:
+ return False
+ if self.name != other.name:
+ return False
+ if self.scope != other.scope:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeUserApiKey(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return UserApiKey(
+ id=_UniffiFfiConverterString.read(buf),
+ client_id=_UniffiFfiConverterString.read(buf),
+ name=_UniffiFfiConverterString.read(buf),
+ scope=_UniffiFfiConverterSequenceString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.id)
+ _UniffiFfiConverterString.check_lower(value.client_id)
+ _UniffiFfiConverterString.check_lower(value.name)
+ _UniffiFfiConverterSequenceString.check_lower(value.scope)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.id, buf)
+ _UniffiFfiConverterString.write(value.client_id, buf)
+ _UniffiFfiConverterString.write(value.name, buf)
+ _UniffiFfiConverterSequenceString.write(value.scope, buf)
+
# AccessTokenProviderError
@@ -2812,6 +3067,29 @@ class _UniffiFfiConverterSequenceTypeClaim(_UniffiConverterRustBuffer):
_UniffiFfiConverterTypeClaim.read(buf) for i in range(count)
]
+class _UniffiFfiConverterSequenceTypeNamespace(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ for item in value:
+ _UniffiFfiConverterTypeNamespace.check_lower(item)
+
+ @classmethod
+ def write(cls, value, buf):
+ items = len(value)
+ buf.write_i32(items)
+ for item in value:
+ _UniffiFfiConverterTypeNamespace.write(item, buf)
+
+ @classmethod
+ def read(cls, buf):
+ count = buf.read_i32()
+ if count < 0:
+ raise InternalError("Unexpected negative sequence length")
+
+ return [
+ _UniffiFfiConverterTypeNamespace.read(buf) for i in range(count)
+ ]
+
class _UniffiFfiConverterSequenceTypePool(_UniffiConverterRustBuffer):
@classmethod
def check_lower(cls, value):
@@ -2858,6 +3136,29 @@ class _UniffiFfiConverterSequenceTypeTemplate(_UniffiConverterRustBuffer):
_UniffiFfiConverterTypeTemplate.read(buf) for i in range(count)
]
+class _UniffiFfiConverterSequenceTypeUserApiKey(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ for item in value:
+ _UniffiFfiConverterTypeUserApiKey.check_lower(item)
+
+ @classmethod
+ def write(cls, value, buf):
+ items = len(value)
+ buf.write_i32(items)
+ for item in value:
+ _UniffiFfiConverterTypeUserApiKey.write(item, buf)
+
+ @classmethod
+ def read(cls, buf):
+ count = buf.read_i32()
+ if count < 0:
+ raise InternalError("Unexpected negative sequence length")
+
+ return [
+ _UniffiFfiConverterTypeUserApiKey.read(buf) for i in range(count)
+ ]
+
class CyclopsClientProtocol(typing.Protocol):
@@ -2867,12 +3168,16 @@ class CyclopsClientProtocol(typing.Protocol):
raise NotImplementedError
async def create_template(self, request: CreateTemplateRequest) -> Template:
raise NotImplementedError
+ async def create_user_api_key(self, request: CreateUserApiKeyRequest) -> NewUserApiKey:
+ raise NotImplementedError
async def delete_claim(self, claim: Claim) -> None:
raise NotImplementedError
async def delete_pool(self, pool: Pool) -> None:
raise NotImplementedError
async def delete_template(self, template: Template) -> None:
raise NotImplementedError
+ async def delete_user_api_key(self, id: str) -> None:
+ raise NotImplementedError
async def get_claim(self, claim: Claim) -> Claim:
raise NotImplementedError
async def get_pool(self, name: str) -> Pool:
@@ -2881,10 +3186,14 @@ class CyclopsClientProtocol(typing.Protocol):
raise NotImplementedError
async def list_claims(self, namespace: str) -> typing.List[Claim]:
raise NotImplementedError
+ async def list_namespaces(self, ) -> typing.List[Namespace]:
+ raise NotImplementedError
async def list_pools(self, namespace: str) -> typing.List[Pool]:
raise NotImplementedError
async def list_templates(self, namespace: str) -> typing.List[Template]:
raise NotImplementedError
+ async def list_user_api_keys(self, ) -> typing.List[UserApiKey]:
+ raise NotImplementedError
async def reconcile_pool(self, request: CreatePoolRequest) -> Pool:
raise NotImplementedError
async def reconcile_template(self, request: CreateTemplateRequest) -> Template:
@@ -3102,6 +3411,23 @@ class CyclopsClient(CyclopsClientProtocol):
_uniffi_lift_return,
_uniffi_error_converter,
)
+ async def create_user_api_key(self, request: CreateUserApiKeyRequest) -> NewUserApiKey:
+
+ _UniffiFfiConverterTypeCreateUserApiKeyRequest.check_lower(request)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterTypeCreateUserApiKeyRequest.lower(request),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeNewUserApiKey.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeSdkError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_create_user_api_key(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
async def delete_claim(self, claim: Claim) -> None:
_UniffiFfiConverterTypeClaim.check_lower(claim)
@@ -3153,6 +3479,23 @@ class CyclopsClient(CyclopsClientProtocol):
_uniffi_lift_return,
_uniffi_error_converter,
)
+ async def delete_user_api_key(self, id: str) -> None:
+
+ _UniffiFfiConverterString.check_lower(id)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ _UniffiFfiConverterString.lower(id),
+ )
+ _uniffi_lift_return = lambda val: None
+ _uniffi_error_converter = _UniffiFfiConverterTypeSdkError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_user_api_key(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cyclops_sdk_rust_future_poll_void,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_complete_void,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_free_void,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
async def get_claim(self, claim: Claim) -> Claim:
_UniffiFfiConverterTypeClaim.check_lower(claim)
@@ -3224,6 +3567,20 @@ class CyclopsClient(CyclopsClientProtocol):
_uniffi_lift_return,
_uniffi_error_converter,
)
+ async def list_namespaces(self, ) -> typing.List[Namespace]:
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterSequenceTypeNamespace.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeSdkError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_list_namespaces(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
async def list_pools(self, namespace: str) -> typing.List[Pool]:
_UniffiFfiConverterString.check_lower(namespace)
@@ -3258,6 +3615,20 @@ class CyclopsClient(CyclopsClientProtocol):
_uniffi_lift_return,
_uniffi_error_converter,
)
+ async def list_user_api_keys(self, ) -> typing.List[UserApiKey]:
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterSequenceTypeUserApiKey.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeSdkError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_list_user_api_keys(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
async def reconcile_pool(self, request: CreatePoolRequest) -> Pool:
_UniffiFfiConverterTypeCreatePoolRequest.check_lower(request)
@@ -3573,13 +3944,17 @@ __all__ = [
"CreateClaimRequest",
"CreatePoolRequest",
"CreateTemplateRequest",
+ "CreateUserApiKeyRequest",
"CyclopsConfiguration",
"CyclopsTokenProviderConfiguration",
"HttpHeader",
"HttpRequest",
"HttpResponse",
+ "Namespace",
+ "NewUserApiKey",
"Sandbox",
"Template",
+ "UserApiKey",
"CyclopsCredentials",
"CyclopsCredentialsProtocol",
"AccessTokenProviderImpl",
diff --git a/libs/fleet/sdk-bindings/ruby/cyclops_sdk/sdk.rb b/libs/fleet/sdk-bindings/ruby/cyclops_sdk/sdk.rb
index 99e4b7b419..3f00ee29da 100644
--- a/libs/fleet/sdk-bindings/ruby/cyclops_sdk/sdk.rb
+++ b/libs/fleet/sdk-bindings/ruby/cyclops_sdk/sdk.rb
@@ -253,6 +253,26 @@ private_constant :UniffiHandleMap
end
end
+ # The Record type CreateUserApiKeyRequest.
+
+ def self.check_lower_TypeCreateUserApiKeyRequest(v)
+
+ RustBuffer.check_lower_Sequencestring(v.scope)
+ end
+
+ def self.alloc_from_TypeCreateUserApiKeyRequest(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeCreateUserApiKeyRequest(v)
+ return builder.finalize
+ end
+ end
+
+ def consumeIntoTypeCreateUserApiKeyRequest
+ consumeWithStream do |stream|
+ return stream.readTypeCreateUserApiKeyRequest
+ end
+ end
+
# The Record type CyclopsConfiguration.
def self.check_lower_TypeCyclopsConfiguration(v)
@@ -364,6 +384,51 @@ private_constant :UniffiHandleMap
end
end
+ # The Record type Namespace.
+
+ def self.check_lower_TypeNamespace(v)
+
+
+
+ RustBuffer.check_lower_OptionalMapStringString(v.labels)
+ end
+
+ def self.alloc_from_TypeNamespace(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeNamespace(v)
+ return builder.finalize
+ end
+ end
+
+ def consumeIntoTypeNamespace
+ consumeWithStream do |stream|
+ return stream.readTypeNamespace
+ end
+ end
+
+ # The Record type NewUserApiKey.
+
+ def self.check_lower_TypeNewUserApiKey(v)
+
+
+
+
+ RustBuffer.check_lower_Sequencestring(v.scope)
+ end
+
+ def self.alloc_from_TypeNewUserApiKey(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeNewUserApiKey(v)
+ return builder.finalize
+ end
+ end
+
+ def consumeIntoTypeNewUserApiKey
+ consumeWithStream do |stream|
+ return stream.readTypeNewUserApiKey
+ end
+ end
+
# The Record type Pool.
def self.check_lower_TypePool(v)
@@ -393,6 +458,7 @@ private_constant :UniffiHandleMap
RustBuffer.check_lower_OptionalMapStringString(v.labels)
+ RustBuffer.check_lower_Optionalstring(v.creation_timestamp)
end
def self.alloc_from_TypeResourceMetadata(v)
@@ -452,11 +518,54 @@ private_constant :UniffiHandleMap
end
end
+ # The Record type UserApiKey.
+
+ def self.check_lower_TypeUserApiKey(v)
+
+
+
+ RustBuffer.check_lower_Sequencestring(v.scope)
+ end
+
+ def self.alloc_from_TypeUserApiKey(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_TypeUserApiKey(v)
+ return builder.finalize
+ end
+ end
+
+ def consumeIntoTypeUserApiKey
+ consumeWithStream do |stream|
+ return stream.readTypeUserApiKey
+ end
+ end
+
+
+ # The Optional<T> type for string.
+
+ def self.check_lower_Optionalstring(v)
+ if not v.nil?
+
+ end
+ end
+
+ def self.alloc_from_Optionalstring(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_Optionalstring(v)
+ return builder.finalize()
+ end
+ end
+
+ def consumeIntoOptionalstring
+ consumeWithStream do |stream|
+ return stream.readOptionalstring
+ end
+ end
# The Optional<T> type for bytes.
@@ -626,6 +735,27 @@ private_constant :UniffiHandleMap
end
end
+ # The Sequence<T> type for TypeNamespace.
+
+ def self.check_lower_SequenceTypeNamespace(v)
+ v.each do |item|
+ RustBuffer.check_lower_TypeNamespace(item)
+ end
+ end
+
+ def self.alloc_from_SequenceTypeNamespace(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_SequenceTypeNamespace(v)
+ return builder.finalize()
+ end
+ end
+
+ def consumeIntoSequenceTypeNamespace
+ consumeWithStream do |stream|
+ return stream.readSequenceTypeNamespace
+ end
+ end
+
# The Sequence<T> type for TypePool.
def self.check_lower_SequenceTypePool(v)
@@ -668,6 +798,27 @@ private_constant :UniffiHandleMap
end
end
+ # The Sequence<T> type for TypeUserApiKey.
+
+ def self.check_lower_SequenceTypeUserApiKey(v)
+ v.each do |item|
+ RustBuffer.check_lower_TypeUserApiKey(item)
+ end
+ end
+
+ def self.alloc_from_SequenceTypeUserApiKey(v)
+ RustBuffer.allocWithBuilder do |builder|
+ builder.write_SequenceTypeUserApiKey(v)
+ return builder.finalize()
+ end
+ end
+
+ def consumeIntoSequenceTypeUserApiKey
+ consumeWithStream do |stream|
+ return stream.readSequenceTypeUserApiKey
+ end
+ end
+
# The Map<T> type for string.
def self.check_lower_MapStringString(v)
@@ -839,6 +990,15 @@ class RustBufferStream
)
end
+ # The Record type CreateUserApiKeyRequest.
+
+ def readTypeCreateUserApiKeyRequest
+ CreateUserApiKeyRequest.new(
+ name: readString,
+ scope: readSequencestring
+ )
+ end
+
# The Record type CyclopsConfiguration.
def readTypeCyclopsConfiguration
@@ -895,6 +1055,29 @@ class RustBufferStream
)
end
+ # The Record type Namespace.
+
+ def readTypeNamespace
+ Namespace.new(
+ name: readString,
+ status: readString,
+ created_at: readString,
+ labels: readOptionalMapStringString
+ )
+ end
+
+ # The Record type NewUserApiKey.
+
+ def readTypeNewUserApiKey
+ NewUserApiKey.new(
+ client_id: readString,
+ client_secret: readString,
+ token_url: readString,
+ name: readString,
+ scope: readSequencestring
+ )
+ end
+
# The Record type Pool.
def readTypePool
@@ -913,7 +1096,8 @@ class RustBufferStream
ResourceMetadata.new(
namespace: readString,
name: readString,
- labels: readOptionalMapStringString
+ labels: readOptionalMapStringString,
+ creation_timestamp: readOptionalstring
)
end
@@ -939,6 +1123,17 @@ class RustBufferStream
)
end
+ # The Record type UserApiKey.
+
+ def readTypeUserApiKey
+ UserApiKey.new(
+ id: readString,
+ client_id: readString,
+ name: readString,
+ scope: readSequencestring
+ )
+ end
+
@@ -1045,6 +1240,20 @@ class RustBufferStream
end
+ # The Optional<T> type for string.
+
+ def readOptionalstring
+ flag = unpack_from 1, 'c'
+
+ if flag == 0
+ return nil
+ elsif flag == 1
+ return readString
+ else
+ raise InternalError, 'Unexpected flag byte for Optionalstring'
+ end
+ end
+
# The Optional<T> type for bytes.
def readOptionalbytes
@@ -1163,6 +1372,22 @@ class RustBufferStream
items
end
+ # The Sequence<T> type for TypeNamespace.
+
+ def readSequenceTypeNamespace
+ count = unpack_from 4, 'l>'
+
+ raise InternalError, 'Unexpected negative sequence length' if count.negative?
+
+ items = []
+
+ count.times do
+ items.append readTypeNamespace
+ end
+
+ items
+ end
+
# The Sequence<T> type for TypePool.
def readSequenceTypePool
@@ -1195,6 +1420,22 @@ class RustBufferStream
items
end
+ # The Sequence<T> type for TypeUserApiKey.
+
+ def readSequenceTypeUserApiKey
+ count = unpack_from 4, 'l>'
+
+ raise InternalError, 'Unexpected negative sequence length' if count.negative?
+
+ items = []
+
+ count.times do
+ items.append readTypeUserApiKey
+ end
+
+ items
+ end
+
# The Map<T> type for string.
def readMapStringString
@@ -1345,6 +1586,13 @@ class RustBufferBuilder
self.write_TypeOSGymSandboxTemplateSpec(v.spec)
end
+ # The Record type CreateUserApiKeyRequest.
+
+ def write_TypeCreateUserApiKeyRequest(v)
+ self.write_String(v.name)
+ self.write_Sequencestring(v.scope)
+ end
+
# The Record type CyclopsConfiguration.
def write_TypeCyclopsConfiguration(v)
@@ -1391,6 +1639,25 @@ class RustBufferBuilder
self.write_Bytes(v.body)
end
+ # The Record type Namespace.
+
+ def write_TypeNamespace(v)
+ self.write_String(v.name)
+ self.write_String(v.status)
+ self.write_String(v.created_at)
+ self.write_OptionalMapStringString(v.labels)
+ end
+
+ # The Record type NewUserApiKey.
+
+ def write_TypeNewUserApiKey(v)
+ self.write_String(v.client_id)
+ self.write_String(v.client_secret)
+ self.write_String(v.token_url)
+ self.write_String(v.name)
+ self.write_Sequencestring(v.scope)
+ end
+
# The Record type Pool.
def write_TypePool(v)
@@ -1407,6 +1674,7 @@ class RustBufferBuilder
self.write_String(v.namespace)
self.write_String(v.name)
self.write_OptionalMapStringString(v.labels)
+ self.write_Optionalstring(v.creation_timestamp)
end
# The Record type Sandbox.
@@ -1427,11 +1695,31 @@ class RustBufferBuilder
self.write_TypeOSGymSandboxTemplateSpec(v.spec)
end
+ # The Record type UserApiKey.
+
+ def write_TypeUserApiKey(v)
+ self.write_String(v.id)
+ self.write_String(v.client_id)
+ self.write_String(v.name)
+ self.write_Sequencestring(v.scope)
+ end
+
+
+ # The Optional<T> type for string.
+
+ def write_Optionalstring(v)
+ if v.nil?
+ pack_into(1, 'c', 0)
+ else
+ pack_into(1, 'c', 1)
+ self.write_String(v)
+ end
+ end
# The Optional<T> type for bytes.
@@ -1518,6 +1806,16 @@ class RustBufferBuilder
end
end
+ # The Sequence<T> type for TypeNamespace.
+
+ def write_SequenceTypeNamespace(items)
+ pack_into(4, 'l>', items.size)
+
+ items.each do |item|
+ self.write_TypeNamespace(item)
+ end
+ end
+
# The Sequence<T> type for TypePool.
def write_SequenceTypePool(items)
@@ -1538,6 +1836,16 @@ class RustBufferBuilder
end
end
+ # The Sequence<T> type for TypeUserApiKey.
+
+ def write_SequenceTypeUserApiKey(items)
+ pack_into(4, 'l>', items.size)
+
+ items.each do |item|
+ self.write_TypeUserApiKey(item)
+ end
+ end
+
# The Map<T> type for string.
def write_MapStringString(items)
@@ -2030,6 +2338,9 @@ module UniFFILib
attach_function :uniffi_cyclops_sdk_fn_method_cyclopsclient_wait_claim,
[:uint64, RustBuffer.by_value, RustCallStatus.by_ref],
:uint64
+ attach_function :uniffi_cyclops_sdk_fn_method_cyclopsclient_list_namespaces,
+ [:uint64, RustCallStatus.by_ref],
+ :uint64
attach_function :uniffi_cyclops_sdk_fn_method_cyclopsclient_create_pool,
[:uint64, RustBuffer.by_value, RustCallStatus.by_ref],
:uint64
@@ -2069,6 +2380,15 @@ module UniFFILib
attach_function :uniffi_cyclops_sdk_fn_method_cyclopsclient_update_template,
[:uint64, RustBuffer.by_value, RustCallStatus.by_ref],
:uint64
+ attach_function :uniffi_cyclops_sdk_fn_method_cyclopsclient_create_user_api_key,
+ [:uint64, RustBuffer.by_value, RustCallStatus.by_ref],
+ :uint64
+ attach_function :uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_user_api_key,
+ [:uint64, RustBuffer.by_value, RustCallStatus.by_ref],
+ :uint64
+ attach_function :uniffi_cyclops_sdk_fn_method_cyclopsclient_list_user_api_keys,
+ [:uint64, RustCallStatus.by_ref],
+ :uint64
attach_function :uniffi_cyclops_sdk_fn_clone_accesstokenprovider,
[:uint64, RustCallStatus.by_ref],
:uint64
@@ -2157,6 +2477,9 @@ module UniFFILib
attach_function :uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim,
[RustCallStatus.by_ref],
:uint16
+ attach_function :uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_namespaces,
+ [RustCallStatus.by_ref],
+ :uint16
attach_function :uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_pool,
[RustCallStatus.by_ref],
:uint16
@@ -2196,6 +2519,15 @@ module UniFFILib
attach_function :uniffi_cyclops_sdk_checksum_method_cyclopsclient_update_template,
[RustCallStatus.by_ref],
:uint16
+ attach_function :uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_user_api_key,
+ [RustCallStatus.by_ref],
+ :uint16
+ attach_function :uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_user_api_key,
+ [RustCallStatus.by_ref],
+ :uint16
+ attach_function :uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_user_api_keys,
+ [RustCallStatus.by_ref],
+ :uint16
attach_function :uniffi_cyclops_sdk_checksum_method_accesstokenprovider_get_access_token,
[RustCallStatus.by_ref],
:uint16
@@ -2338,6 +2670,27 @@ class CreateTemplateRequest
end
end
+ # Record type CreateUserApiKeyRequest
+class CreateUserApiKeyRequest
+ attr_reader :name, :scope
+
+ def initialize(name:, scope:)
+ @name = name
+ @scope = scope
+ end
+
+ def ==(other)
+ if @name != other.name
+ return false
+ end
+ if @scope != other.scope
+ return false
+ end
+
+ true
+ end
+end
+
# Record type CyclopsConfiguration
class CyclopsConfiguration
attr_reader :base_url, :token_url, :credentials, :pool_poll_interval_ms, :pool_poll_limit, :claim_poll_interval_ms, :claim_poll_limit
@@ -2487,6 +2840,68 @@ class HttpResponse
end
end
+ # Record type Namespace
+class Namespace
+ attr_reader :name, :status, :created_at, :labels
+
+ def initialize(name:, status:, created_at:, labels:)
+ @name = name
+ @status = status
+ @created_at = created_at
+ @labels = labels
+ end
+
+ def ==(other)
+ if @name != other.name
+ return false
+ end
+ if @status != other.status
+ return false
+ end
+ if @created_at != other.created_at
+ return false
+ end
+ if @labels != other.labels
+ return false
+ end
+
+ true
+ end
+end
+
+ # Record type NewUserApiKey
+class NewUserApiKey
+ attr_reader :client_id, :client_secret, :token_url, :name, :scope
+
+ def initialize(client_id:, client_secret:, token_url:, name:, scope:)
+ @client_id = client_id
+ @client_secret = client_secret
+ @token_url = token_url
+ @name = name
+ @scope = scope
+ end
+
+ def ==(other)
+ if @client_id != other.client_id
+ return false
+ end
+ if @client_secret != other.client_secret
+ return false
+ end
+ if @token_url != other.token_url
+ return false
+ end
+ if @name != other.name
+ return false
+ end
+ if @scope != other.scope
+ return false
+ end
+
+ true
+ end
+end
+
# Record type Pool
class Pool
attr_reader :api_version, :kind, :metadata, :spec, :status
@@ -2522,12 +2937,13 @@ end
# Record type ResourceMetadata
class ResourceMetadata
- attr_reader :namespace, :name, :labels
+ attr_reader :namespace, :name, :labels, :creation_timestamp
- def initialize(namespace:, name:, labels:)
+ def initialize(namespace:, name:, labels:, creation_timestamp:)
@namespace = namespace
@name = name
@labels = labels
+ @creation_timestamp = creation_timestamp
end
def ==(other)
@@ -2540,6 +2956,9 @@ class ResourceMetadata
if @labels != other.labels
return false
end
+ if @creation_timestamp != other.creation_timestamp
+ return false
+ end
true
end
@@ -2603,6 +3022,35 @@ class Template
end
end
+ # Record type UserApiKey
+class UserApiKey
+ attr_reader :id, :client_id, :name, :scope
+
+ def initialize(id:, client_id:, name:, scope:)
+ @id = id
+ @client_id = client_id
+ @name = name
+ @scope = scope
+ end
+
+ def ==(other)
+ if @id != other.id
+ return false
+ end
+ if @client_id != other.client_id
+ return false
+ end
+ if @name != other.name
+ return false
+ end
+ if @scope != other.scope
+ return false
+ end
+
+ true
+ end
+end
+
@@ -2772,6 +3220,13 @@ end
)
return result.consumeIntoTypeSandbox
end
+ def list_namespaces()
+ result = FleetSdk.uniffi_rust_future_rust_buffer(
+ SdkError,
+ UniFFILib.uniffi_cyclops_sdk_fn_method_cyclopsclient_list_namespaces(uniffi_clone_handle(),RustCallStatus.new),
+ )
+ return result.consumeIntoSequenceTypeNamespace
+ end
def create_pool(request)
request = request
RustBuffer.check_lower_TypeCreatePoolRequest(request)
@@ -2909,6 +3364,34 @@ end
)
return result.consumeIntoTypeTemplate
end
+ def create_user_api_key(request)
+ request = request
+ RustBuffer.check_lower_TypeCreateUserApiKeyRequest(request)
+ result = FleetSdk.uniffi_rust_future_rust_buffer(
+ SdkError,
+ UniFFILib.uniffi_cyclops_sdk_fn_method_cyclopsclient_create_user_api_key(uniffi_clone_handle(),RustBuffer.alloc_from_TypeCreateUserApiKeyRequest(request),RustCallStatus.new),
+ )
+ return result.consumeIntoTypeNewUserApiKey
+ end
+ def delete_user_api_key(id)
+ id = FleetSdk::uniffi_utf8(id)
+
+ FleetSdk.uniffi_rust_future_void(
+
+ SdkError,
+
+ UniFFILib.uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_user_api_key(uniffi_clone_handle(),RustBuffer.allocFromString(id),RustCallStatus.new),
+
+ )
+ end
+
+ def list_user_api_keys()
+ result = FleetSdk.uniffi_rust_future_rust_buffer(
+ SdkError,
+ UniFFILib.uniffi_cyclops_sdk_fn_method_cyclopsclient_list_user_api_keys(uniffi_clone_handle(),RustCallStatus.new),
+ )
+ return result.consumeIntoSequenceTypeUserApiKey
+ end
end
diff --git a/libs/fleet/sdk-bindings/ruby/tests/test_async_client.rb b/libs/fleet/sdk-bindings/ruby/tests/test_async_client.rb
index 3e55918ad0..3ddbca0550 100644
--- a/libs/fleet/sdk-bindings/ruby/tests/test_async_client.rb
+++ b/libs/fleet/sdk-bindings/ruby/tests/test_async_client.rb
@@ -6,6 +6,17 @@ BASE = 'https://cyclops.invalid'
TOKEN = 'https://keycloak.invalid/token'
JSON_HEADERS = [['accept', 'application/json'], ['content-type', 'application/json'], ['authorization', 'Bearer offline-token']]
+GENERATED_CLAIM_NAME = /\Aclaim-[a-z0-9](?:[-a-z0-9]*[a-z0-9])?\z/
+
+def normalized_generated_claim_body(body)
+ return nil if body.nil?
+ value = JSON.parse(body)
+ name = value.fetch('metadata').fetch('name')
+ raise "invalid generated claim name: #{name.inspect}" unless name.bytesize <= 63 && GENERATED_CLAIM_NAME.match?(name)
+ value['metadata']['name'] = 'claim-generated'
+ JSON.generate(value).b
+end
+
def pool_json
{ apiVersion: 'osgym.cua.ai/v1alpha1', kind: 'OSGymSandboxWarmPool', metadata: { namespace: 'default', name: 'default', labels: nil }, spec: { replicas: 1, sandboxTemplateRef: { name: 'default' } }, status: nil }
end
@@ -59,7 +70,12 @@ class ScriptedHttpClient < FleetSdk::HttpClient
@mutex.synchronize do
item = @expected.shift or raise 'unexpected request'
actual = [request.method, request.url, request.headers.map { |header| [header.name, header.value] }, request.body]
- raise "request mismatch: #{actual.inspect}" unless actual == [item.method, item.url, item.headers, item.body]
+ expected = [item.method, item.url, item.headers, item.body]
+ if request.method == 'POST' && request.url.end_with?('/osgymsandboxclaims')
+ raise "request mismatch: #{actual.inspect}" unless actual.first(3) == expected.first(3) && normalized_generated_claim_body(request.body) == normalized_generated_claim_body(item.body)
+ else
+ raise "request mismatch: #{actual.inspect}" unless actual == [item.method, item.url, item.headers, item.body]
+ end
@requests << request
body = item.response.is_a?(String) ? item.response.b : JSON.generate(item.response).b
FleetSdk::HttpResponse.new(status: item.status, headers: [], body: body)
diff --git a/libs/fleet/sdk-bindings/swift/CyclopsSdk.swift b/libs/fleet/sdk-bindings/swift/CyclopsSdk.swift
index 4114f36a71..1c8d369812 100644
--- a/libs/fleet/sdk-bindings/swift/CyclopsSdk.swift
+++ b/libs/fleet/sdk-bindings/swift/CyclopsSdk.swift
@@ -782,6 +782,8 @@ public protocol CyclopsClientProtocol: AnyObject, Sendable {
func waitClaim(claim: Claim) async throws -> Sandbox
+ func listNamespaces() async throws -> [Namespace]
+
func createPool(request: CreatePoolRequest) async throws -> Pool
func deletePool(pool: Pool) async throws
@@ -808,6 +810,12 @@ public protocol CyclopsClientProtocol: AnyObject, Sendable {
func updateTemplate(template: Template) async throws -> Template
+ func createUserApiKey(request: CreateUserApiKeyRequest) async throws -> NewUserApiKey
+
+ func deleteUserApiKey(id: String) async throws
+
+ func listUserApiKeys() async throws -> [UserApiKey]
+
}
open class CyclopsClient: CyclopsClientProtocol, @unchecked Sendable {
fileprivate let handle: UInt64
@@ -1011,6 +1019,23 @@ open func waitClaim(claim: Claim)async throws -> Sandbox {
)
}
+open func listNamespaces()async throws -> [Namespace] {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cyclops_sdk_fn_method_cyclopsclient_list_namespaces(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterSequenceTypeNamespace.lift,
+ errorHandler: FfiConverterTypeSdkError_lift
+ )
+}
+
open func createPool(request: CreatePoolRequest)async throws -> Pool {
return
try await uniffiRustCallAsync(
@@ -1232,6 +1257,57 @@ open func updateTemplate(template: Template)async throws -> Template {
)
}
+open func createUserApiKey(request: CreateUserApiKeyRequest)async throws -> NewUserApiKey {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cyclops_sdk_fn_method_cyclopsclient_create_user_api_key(
+ self.uniffiCloneHandle(),
+ FfiConverterTypeCreateUserApiKeyRequest_lower(request)
+ )
+ },
+ pollFunc: ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterTypeNewUserApiKey_lift,
+ errorHandler: FfiConverterTypeSdkError_lift
+ )
+}
+
+open func deleteUserApiKey(id: String)async throws {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_user_api_key(
+ self.uniffiCloneHandle(),
+ FfiConverterString.lower(id)
+ )
+ },
+ pollFunc: ffi_cyclops_sdk_rust_future_poll_void,
+ completeFunc: ffi_cyclops_sdk_rust_future_complete_void,
+ freeFunc: ffi_cyclops_sdk_rust_future_free_void,
+ liftFunc: { $0 },
+ errorHandler: FfiConverterTypeSdkError_lift
+ )
+}
+
+open func listUserApiKeys()async throws -> [UserApiKey] {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_cyclops_sdk_fn_method_cyclopsclient_list_user_api_keys(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ completeFunc: ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ freeFunc: ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterSequenceTypeUserApiKey.lift,
+ errorHandler: FfiConverterTypeSdkError_lift
+ )
+}
+
}
@@ -1841,6 +1917,60 @@ public func FfiConverterTypeCreateTemplateRequest_lower(_ value: CreateTemplateR
}
+public struct CreateUserApiKeyRequest: Equatable, Hashable {
+ public var name: String
+ public var scope: [String]
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(name: String, scope: [String]) {
+ self.name = name
+ self.scope = scope
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension CreateUserApiKeyRequest: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeCreateUserApiKeyRequest: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> CreateUserApiKeyRequest {
+ return
+ try CreateUserApiKeyRequest(
+ name: FfiConverterString.read(from: &buf),
+ scope: FfiConverterSequenceString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: CreateUserApiKeyRequest, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.name, into: &buf)
+ FfiConverterSequenceString.write(value.scope, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeCreateUserApiKeyRequest_lift(_ buf: RustBuffer) throws -> CreateUserApiKeyRequest {
+ return try FfiConverterTypeCreateUserApiKeyRequest.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeCreateUserApiKeyRequest_lower(_ value: CreateUserApiKeyRequest) -> RustBuffer {
+ return FfiConverterTypeCreateUserApiKeyRequest.lower(value)
+}
+
+
public struct CyclopsConfiguration {
public var baseUrl: String
public var tokenUrl: String
@@ -2155,6 +2285,134 @@ public func FfiConverterTypeHttpResponse_lower(_ value: HttpResponse) -> RustBuf
}
+public struct Namespace: Equatable, Hashable {
+ public var name: String
+ public var status: String
+ public var createdAt: String
+ public var labels: [String: String]?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(name: String, status: String, createdAt: String, labels: [String: String]?) {
+ self.name = name
+ self.status = status
+ self.createdAt = createdAt
+ self.labels = labels
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension Namespace: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeNamespace: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Namespace {
+ return
+ try Namespace(
+ name: FfiConverterString.read(from: &buf),
+ status: FfiConverterString.read(from: &buf),
+ createdAt: FfiConverterString.read(from: &buf),
+ labels: FfiConverterOptionDictionaryStringString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: Namespace, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.name, into: &buf)
+ FfiConverterString.write(value.status, into: &buf)
+ FfiConverterString.write(value.createdAt, into: &buf)
+ FfiConverterOptionDictionaryStringString.write(value.labels, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeNamespace_lift(_ buf: RustBuffer) throws -> Namespace {
+ return try FfiConverterTypeNamespace.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeNamespace_lower(_ value: Namespace) -> RustBuffer {
+ return FfiConverterTypeNamespace.lower(value)
+}
+
+
+public struct NewUserApiKey: Equatable, Hashable {
+ public var clientId: String
+ public var clientSecret: String
+ public var tokenUrl: String
+ public var name: String
+ public var scope: [String]
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(clientId: String, clientSecret: String, tokenUrl: String, name: String, scope: [String]) {
+ self.clientId = clientId
+ self.clientSecret = clientSecret
+ self.tokenUrl = tokenUrl
+ self.name = name
+ self.scope = scope
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension NewUserApiKey: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeNewUserApiKey: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> NewUserApiKey {
+ return
+ try NewUserApiKey(
+ clientId: FfiConverterString.read(from: &buf),
+ clientSecret: FfiConverterString.read(from: &buf),
+ tokenUrl: FfiConverterString.read(from: &buf),
+ name: FfiConverterString.read(from: &buf),
+ scope: FfiConverterSequenceString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: NewUserApiKey, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.clientId, into: &buf)
+ FfiConverterString.write(value.clientSecret, into: &buf)
+ FfiConverterString.write(value.tokenUrl, into: &buf)
+ FfiConverterString.write(value.name, into: &buf)
+ FfiConverterSequenceString.write(value.scope, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeNewUserApiKey_lift(_ buf: RustBuffer) throws -> NewUserApiKey {
+ return try FfiConverterTypeNewUserApiKey.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeNewUserApiKey_lower(_ value: NewUserApiKey) -> RustBuffer {
+ return FfiConverterTypeNewUserApiKey.lower(value)
+}
+
+
/**
* UniFFI cannot emit aliases for external record types. Generated bindings use
* `OSGymSandboxWarmPoolStatus` and `OSGymSandboxClaimStatus` from cyclops_sdk_schema.
@@ -2234,13 +2492,15 @@ public struct ResourceMetadata: Equatable, Hashable {
public var namespace: String
public var name: String
public var labels: [String: String]?
+ public var creationTimestamp: String?
// Default memberwise initializers are never public by default, so we
// declare one manually.
- public init(namespace: String, name: String, labels: [String: String]?) {
+ public init(namespace: String, name: String, labels: [String: String]?, creationTimestamp: String?) {
self.namespace = namespace
self.name = name
self.labels = labels
+ self.creationTimestamp = creationTimestamp
}
@@ -2261,7 +2521,8 @@ public struct FfiConverterTypeResourceMetadata: FfiConverterRustBuffer {
try ResourceMetadata(
namespace: FfiConverterString.read(from: &buf),
name: FfiConverterString.read(from: &buf),
- labels: FfiConverterOptionDictionaryStringString.read(from: &buf)
+ labels: FfiConverterOptionDictionaryStringString.read(from: &buf),
+ creationTimestamp: FfiConverterOptionString.read(from: &buf)
)
}
@@ -2269,6 +2530,7 @@ public struct FfiConverterTypeResourceMetadata: FfiConverterRustBuffer {
FfiConverterString.write(value.namespace, into: &buf)
FfiConverterString.write(value.name, into: &buf)
FfiConverterOptionDictionaryStringString.write(value.labels, into: &buf)
+ FfiConverterOptionString.write(value.creationTimestamp, into: &buf)
}
}
@@ -2416,6 +2678,68 @@ public func FfiConverterTypeTemplate_lower(_ value: Template) -> RustBuffer {
}
+public struct UserApiKey: Equatable, Hashable {
+ public var id: String
+ public var clientId: String
+ public var name: String
+ public var scope: [String]
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(id: String, clientId: String, name: String, scope: [String]) {
+ self.id = id
+ self.clientId = clientId
+ self.name = name
+ self.scope = scope
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension UserApiKey: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeUserApiKey: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> UserApiKey {
+ return
+ try UserApiKey(
+ id: FfiConverterString.read(from: &buf),
+ clientId: FfiConverterString.read(from: &buf),
+ name: FfiConverterString.read(from: &buf),
+ scope: FfiConverterSequenceString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: UserApiKey, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.id, into: &buf)
+ FfiConverterString.write(value.clientId, into: &buf)
+ FfiConverterString.write(value.name, into: &buf)
+ FfiConverterSequenceString.write(value.scope, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeUserApiKey_lift(_ buf: RustBuffer) throws -> UserApiKey {
+ return try FfiConverterTypeUserApiKey.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeUserApiKey_lower(_ value: UserApiKey) -> RustBuffer {
+ return FfiConverterTypeUserApiKey.lower(value)
+}
+
+
public enum AccessTokenProviderError: Swift.Error, Equatable, Hashable, Foundation.LocalizedError {
@@ -2735,6 +3059,30 @@ public func FfiConverterTypeSdkError_lower(_ value: SdkError) -> RustBuffer {
return FfiConverterTypeSdkError.lower(value)
}
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionString: FfiConverterRustBuffer {
+ typealias SwiftType = String?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterString.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterString.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
@@ -2930,6 +3278,31 @@ fileprivate struct FfiConverterSequenceTypeHttpHeader: FfiConverterRustBuffer {
}
}
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeNamespace: FfiConverterRustBuffer {
+ typealias SwiftType = [Namespace]
+
+ public static func write(_ value: [Namespace], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeNamespace.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [Namespace] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [Namespace]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeNamespace.read(from: &buf))
+ }
+ return seq
+ }
+}
+
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
@@ -2980,6 +3353,31 @@ fileprivate struct FfiConverterSequenceTypeTemplate: FfiConverterRustBuffer {
}
}
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeUserApiKey: FfiConverterRustBuffer {
+ typealias SwiftType = [UserApiKey]
+
+ public static func write(_ value: [UserApiKey], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeUserApiKey.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [UserApiKey] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [UserApiKey]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeUserApiKey.read(from: &buf))
+ }
+ return seq
+ }
+}
+
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
@@ -3174,6 +3572,9 @@ private let initializationResult: InitializationResult = {
if (uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim() != 18984) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_namespaces() != 65288) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_pool() != 48557) {
return InitializationResult.apiChecksumMismatch
}
@@ -3213,6 +3614,15 @@ private let initializationResult: InitializationResult = {
if (uniffi_cyclops_sdk_checksum_method_cyclopsclient_update_template() != 18704) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_user_api_key() != 9174) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_user_api_key() != 1700) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_user_api_keys() != 5949) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cyclops_sdk_checksum_method_accesstokenprovider_get_access_token() != 1180) {
return InitializationResult.apiChecksumMismatch
}
diff --git a/libs/fleet/sdk-bindings/swift/CyclopsSdkFFI.h b/libs/fleet/sdk-bindings/swift/CyclopsSdkFFI.h
index 8c7cb53abe..ec6fde1d71 100644
--- a/libs/fleet/sdk-bindings/swift/CyclopsSdkFFI.h
+++ b/libs/fleet/sdk-bindings/swift/CyclopsSdkFFI.h
@@ -343,6 +343,11 @@ uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_list_claims(uint64_t ptr, Ru
uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_wait_claim(uint64_t ptr, RustBuffer claim
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_LIST_NAMESPACES
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_LIST_NAMESPACES
+uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_list_namespaces(uint64_t ptr
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_CREATE_POOL
#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_CREATE_POOL
uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_create_pool(uint64_t ptr, RustBuffer request
@@ -408,6 +413,21 @@ uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_reconcile_template(uint64_t
uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_update_template(uint64_t ptr, RustBuffer template
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_CREATE_USER_API_KEY
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_CREATE_USER_API_KEY
+uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_create_user_api_key(uint64_t ptr, RustBuffer request
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_DELETE_USER_API_KEY
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_DELETE_USER_API_KEY
+uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_user_api_key(uint64_t ptr, RustBuffer id
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_LIST_USER_API_KEYS
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_LIST_USER_API_KEYS
+uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_list_user_api_keys(uint64_t ptr
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_CLONE_ACCESSTOKENPROVIDER
#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_CLONE_ACCESSTOKENPROVIDER
uint64_t uniffi_cyclops_sdk_fn_clone_accesstokenprovider(uint64_t handle, RustCallStatus *_Nonnull out_status
@@ -751,6 +771,12 @@ uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_claims(void
#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_WAIT_CLAIM
uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_LIST_NAMESPACES
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_LIST_NAMESPACES
+uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_namespaces(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_CREATE_POOL
@@ -829,6 +855,24 @@ uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_reconcile_template(voi
#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_UPDATE_TEMPLATE
uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_update_template(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_CREATE_USER_API_KEY
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_CREATE_USER_API_KEY
+uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_user_api_key(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_DELETE_USER_API_KEY
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_DELETE_USER_API_KEY
+uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_user_api_key(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_LIST_USER_API_KEYS
+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_LIST_USER_API_KEYS
+uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_user_api_keys(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_ACCESSTOKENPROVIDER_GET_ACCESS_TOKEN
diff --git a/libs/fleet/sdk-bindings/swift/tests/TestAsyncClient.swift b/libs/fleet/sdk-bindings/swift/tests/TestAsyncClient.swift
index 3edc46e9d7..5084a4b17c 100644
--- a/libs/fleet/sdk-bindings/swift/tests/TestAsyncClient.swift
+++ b/libs/fleet/sdk-bindings/swift/tests/TestAsyncClient.swift
@@ -56,6 +56,23 @@ private func lifecycleQueue() -> [Expected] {
]
}
+private func normalizedGeneratedClaimBody(_ body: Data?) -> Data? {
+ guard let body,
+ var object = try? JSONSerialization.jsonObject(with: body) as? [String: Any],
+ var metadata = object["metadata"] as? [String: Any],
+ let name = metadata["name"] as? String,
+ name.hasPrefix("claim-") else { return nil }
+ let suffix = name.dropFirst("claim-".count)
+ guard !suffix.isEmpty,
+ suffix.first != "-",
+ suffix.last != "-",
+ name.utf8.count <= 63,
+ suffix.allSatisfy({ $0.isLowercase || $0.isNumber || $0 == "-" }) else { return nil }
+ metadata["name"] = "claim-generated"
+ object["metadata"] = metadata
+ return try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys])
+}
+
actor ScriptedHttpClient: HttpClient {
private var expected: [Expected]
private var requests: [HttpRequest] = []
@@ -69,7 +86,11 @@ actor ScriptedHttpClient: HttpClient {
let item = expected.removeFirst()
precondition(request.method == item.method && request.url == item.url)
precondition(request.headers == item.headers)
- precondition(request.body == item.body)
+ if request.method == "POST" && request.url.hasSuffix("/osgymsandboxclaims") {
+ precondition(normalizedGeneratedClaimBody(request.body) == normalizedGeneratedClaimBody(item.body))
+ } else {
+ precondition(request.body == item.body)
+ }
requests.append(request)
return HttpResponse(status: item.status, headers: [], body: item.response)
}
diff --git a/libs/fleet/sdk-bindings/ts-uniffi-browser/ts/fleet_sdk.ts b/libs/fleet/sdk-bindings/ts-uniffi-browser/ts/fleet_sdk.ts
index 391c1c784d..92e8dc1997 100644
--- a/libs/fleet/sdk-bindings/ts-uniffi-browser/ts/fleet_sdk.ts
+++ b/libs/fleet/sdk-bindings/ts-uniffi-browser/ts/fleet_sdk.ts
@@ -111,6 +111,7 @@ export type ResourceMetadata = {
namespace: string;
name: string;
labels?: Map<string, string>;
+ creationTimestamp?: string;
};
/**
@@ -138,18 +139,21 @@ const FfiConverterTypeResourceMetadata = (() => {
namespace: FfiConverterString.read(from),
name: FfiConverterString.read(from),
labels: FfiConverterOptionalMapStringString.read(from),
+ creationTimestamp: FfiConverterOptionalString.read(from),
};
}
write(value: TypeName, into: RustBuffer): void {
FfiConverterString.write(value.namespace, into);
FfiConverterString.write(value.name, into);
FfiConverterOptionalMapStringString.write(value.labels, into);
+ FfiConverterOptionalString.write(value.creationTimestamp, into);
}
allocationSize(value: TypeName): number {
return (
FfiConverterString.allocationSize(value.namespace) +
FfiConverterString.allocationSize(value.name) +
- FfiConverterOptionalMapStringString.allocationSize(value.labels)
+ FfiConverterOptionalMapStringString.allocationSize(value.labels) +
+ FfiConverterOptionalString.allocationSize(value.creationTimestamp)
);
}
}
@@ -422,6 +426,53 @@ const FfiConverterTypeCreateTemplateRequest = (() => {
return new FFIConverter();
})();
+export type CreateUserApiKeyRequest = {
+ name: string;
+ scope: Array<string>;
+};
+
+/**
+ * Generated factory for {@link CreateUserApiKeyRequest} record objects.
+ */
+export const CreateUserApiKeyRequest = (() => {
+ const defaults = () => ({});
+ const create = (() => {
+ return uniffiCreateRecord<
+ CreateUserApiKeyRequest,
+ ReturnType<typeof defaults>
+ >(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () =>
+ Object.freeze(defaults()) as Partial<CreateUserApiKeyRequest>,
+ });
+})();
+
+const FfiConverterTypeCreateUserApiKeyRequest = (() => {
+ type TypeName = CreateUserApiKeyRequest;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ name: FfiConverterString.read(from),
+ scope: FfiConverterSequenceString.read(from),
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.name, into);
+ FfiConverterSequenceString.write(value.scope, into);
+ }
+ allocationSize(value: TypeName): number {
+ return (
+ FfiConverterString.allocationSize(value.name) +
+ FfiConverterSequenceString.allocationSize(value.scope)
+ );
+ }
+ }
+ return new FFIConverter();
+})();
+
export interface CyclopsCredentialsLike {}
/**
* @deprecated Use `CyclopsCredentialsLike` instead.
@@ -820,6 +871,114 @@ const FfiConverterTypeHttpResponse = (() => {
return new FFIConverter();
})();
+export type Namespace = {
+ name: string;
+ status: string;
+ createdAt: string;
+ labels?: Map<string, string>;
+};
+
+/**
+ * Generated factory for {@link Namespace} record objects.
+ */
+export const Namespace = (() => {
+ const defaults = () => ({});
+ const create = (() => {
+ return uniffiCreateRecord<Namespace, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<Namespace>,
+ });
+})();
+
+const FfiConverterTypeNamespace = (() => {
+ type TypeName = Namespace;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ name: FfiConverterString.read(from),
+ status: FfiConverterString.read(from),
+ createdAt: FfiConverterString.read(from),
+ labels: FfiConverterOptionalMapStringString.read(from),
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.name, into);
+ FfiConverterString.write(value.status, into);
+ FfiConverterString.write(value.createdAt, into);
+ FfiConverterOptionalMapStringString.write(value.labels, into);
+ }
+ allocationSize(value: TypeName): number {
+ return (
+ FfiConverterString.allocationSize(value.name) +
+ FfiConverterString.allocationSize(value.status) +
+ FfiConverterString.allocationSize(value.createdAt) +
+ FfiConverterOptionalMapStringString.allocationSize(value.labels)
+ );
+ }
+ }
+ return new FFIConverter();
+})();
+
+export type NewUserApiKey = {
+ clientId: string;
+ clientSecret: string;
+ tokenUrl: string;
+ name: string;
+ scope: Array<string>;
+};
+
+/**
+ * Generated factory for {@link NewUserApiKey} record objects.
+ */
+export const NewUserApiKey = (() => {
+ const defaults = () => ({});
+ const create = (() => {
+ return uniffiCreateRecord<NewUserApiKey, ReturnType<typeof defaults>>(
+ defaults,
+ );
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<NewUserApiKey>,
+ });
+})();
+
+const FfiConverterTypeNewUserApiKey = (() => {
+ type TypeName = NewUserApiKey;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ clientId: FfiConverterString.read(from),
+ clientSecret: FfiConverterString.read(from),
+ tokenUrl: FfiConverterString.read(from),
+ name: FfiConverterString.read(from),
+ scope: FfiConverterSequenceString.read(from),
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.clientId, into);
+ FfiConverterString.write(value.clientSecret, into);
+ FfiConverterString.write(value.tokenUrl, into);
+ FfiConverterString.write(value.name, into);
+ FfiConverterSequenceString.write(value.scope, into);
+ }
+ allocationSize(value: TypeName): number {
+ return (
+ FfiConverterString.allocationSize(value.clientId) +
+ FfiConverterString.allocationSize(value.clientSecret) +
+ FfiConverterString.allocationSize(value.tokenUrl) +
+ FfiConverterString.allocationSize(value.name) +
+ FfiConverterSequenceString.allocationSize(value.scope)
+ );
+ }
+ }
+ return new FFIConverter();
+})();
+
export type Sandbox = {
namespace: string;
claim: string;
@@ -926,6 +1085,59 @@ const FfiConverterTypeTemplate = (() => {
return new FFIConverter();
})();
+export type UserApiKey = {
+ id: string;
+ clientId: string;
+ name: string;
+ scope: Array<string>;
+};
+
+/**
+ * Generated factory for {@link UserApiKey} record objects.
+ */
+export const UserApiKey = (() => {
+ const defaults = () => ({});
+ const create = (() => {
+ return uniffiCreateRecord<UserApiKey, ReturnType<typeof defaults>>(
+ defaults,
+ );
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<UserApiKey>,
+ });
+})();
+
+const FfiConverterTypeUserApiKey = (() => {
+ type TypeName = UserApiKey;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ id: FfiConverterString.read(from),
+ clientId: FfiConverterString.read(from),
+ name: FfiConverterString.read(from),
+ scope: FfiConverterSequenceString.read(from),
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.id, into);
+ FfiConverterString.write(value.clientId, into);
+ FfiConverterString.write(value.name, into);
+ FfiConverterSequenceString.write(value.scope, into);
+ }
+ allocationSize(value: TypeName): number {
+ return (
+ FfiConverterString.allocationSize(value.id) +
+ FfiConverterString.allocationSize(value.clientId) +
+ FfiConverterString.allocationSize(value.name) +
+ FfiConverterSequenceString.allocationSize(value.scope)
+ );
+ }
+ }
+ return new FFIConverter();
+})();
+
// Error type: AccessTokenProviderError
export enum AccessTokenProviderError_Tags {
Failed = "Failed",
@@ -1951,6 +2163,10 @@ export interface CyclopsClientLike {
request: CreateTemplateRequest,
asyncOpts_?: { signal: AbortSignal },
) /*throws*/ : Promise<Template>;
+ createUserApiKey(
+ request: CreateUserApiKeyRequest,
+ asyncOpts_?: { signal: AbortSignal },
+ ) /*throws*/ : Promise<NewUserApiKey>;
deleteClaim(
claim: Claim,
asyncOpts_?: { signal: AbortSignal },
@@ -1963,6 +2179,10 @@ export interface CyclopsClientLike {
template: Template,
asyncOpts_?: { signal: AbortSignal },
) /*throws*/ : Promise<void>;
+ deleteUserApiKey(
+ id: string,
+ asyncOpts_?: { signal: AbortSignal },
+ ) /*throws*/ : Promise<void>;
getClaim(
claim: Claim,
asyncOpts_?: { signal: AbortSignal },
@@ -1980,6 +2200,9 @@ export interface CyclopsClientLike {
namespace: string,
asyncOpts_?: { signal: AbortSignal },
) /*throws*/ : Promise<Array<Claim>>;
+ listNamespaces(asyncOpts_?: {
+ signal: AbortSignal;
+ }) /*throws*/ : Promise<Array<Namespace>>;
listPools(
namespace: string,
asyncOpts_?: { signal: AbortSignal },
@@ -1988,6 +2211,9 @@ export interface CyclopsClientLike {
namespace: string,
asyncOpts_?: { signal: AbortSignal },
) /*throws*/ : Promise<Array<Template>>;
+ listUserApiKeys(asyncOpts_?: {
+ signal: AbortSignal;
+ }) /*throws*/ : Promise<Array<UserApiKey>>;
reconcilePool(
request: CreatePoolRequest,
asyncOpts_?: { signal: AbortSignal },
@@ -2343,6 +2569,45 @@ export class CyclopsClient
);
}
+ async createUserApiKey(
+ request: CreateUserApiKeyRequest,
+ asyncOpts_?: { signal: AbortSignal },
+ ): Promise<NewUserApiKey> /*throws*/ {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().ubrn_uniffi_cyclops_sdk_fn_method_cyclopsclient_create_user_api_key(
+ uniffiTypeCyclopsClientObjectFactory.clonePointer(this),
+ FfiConverterTypeCreateUserApiKeyRequest.lower(
+ request,
+ nativeModule().rustbuffer_alloc,
+ ),
+ );
+ },
+ /*pollFunc:*/ nativeModule()
+ .ubrn_ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule()
+ .ubrn_ffi_cyclops_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule()
+ .ubrn_ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule()
+ .ubrn_ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeNewUserApiKey.lift.bind(
+ FfiConverterTypeNewUserApiKey,
+ ),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeSdkError.lift.bind(
+ FfiConverterTypeSdkError,
+ ),
+ );
+ }
+
async deleteClaim(
claim: Claim,
asyncOpts_?: { signal: AbortSignal },
@@ -2427,6 +2692,33 @@ export class CyclopsClient
);
}
+ async deleteUserApiKey(
+ id: string,
+ asyncOpts_?: { signal: AbortSignal },
+ ): Promise<void> /*throws*/ {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().ubrn_uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_user_api_key(
+ uniffiTypeCyclopsClientObjectFactory.clonePointer(this),
+ FfiConverterString.lower(id, nativeModule().rustbuffer_alloc),
+ );
+ },
+ /*pollFunc:*/ nativeModule().ubrn_ffi_cyclops_sdk_rust_future_poll_void,
+ /*cancelFunc:*/ nativeModule()
+ .ubrn_ffi_cyclops_sdk_rust_future_cancel_void,
+ /*completeFunc:*/ nativeModule()
+ .ubrn_ffi_cyclops_sdk_rust_future_complete_void,
+ /*freeFunc:*/ nativeModule().ubrn_ffi_cyclops_sdk_rust_future_free_void,
+ /*liftFunc:*/ (_v) => {},
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeSdkError.lift.bind(
+ FfiConverterTypeSdkError,
+ ),
+ );
+ }
+
async getClaim(
claim: Claim,
asyncOpts_?: { signal: AbortSignal },
@@ -2569,6 +2861,40 @@ export class CyclopsClient
);
}
+ async listNamespaces(asyncOpts_?: {
+ signal: AbortSignal;
+ }): Promise<Array<Namespace>> /*throws*/ {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().ubrn_uniffi_cyclops_sdk_fn_method_cyclopsclient_list_namespaces(
+ uniffiTypeCyclopsClientObjectFactory.clonePointer(this),
+ );
+ },
+ /*pollFunc:*/ nativeModule()
+ .ubrn_ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule()
+ .ubrn_ffi_cyclops_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule()
+ .ubrn_ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule()
+ .ubrn_ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterSequenceTypeNamespace.lift.bind(
+ FfiConverterSequenceTypeNamespace,
+ ),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeSdkError.lift.bind(
+ FfiConverterTypeSdkError,
+ ),
+ );
+ }
+
async listPools(
namespace: string,
asyncOpts_?: { signal: AbortSignal },
@@ -2641,6 +2967,40 @@ export class CyclopsClient
);
}
+ async listUserApiKeys(asyncOpts_?: {
+ signal: AbortSignal;
+ }): Promise<Array<UserApiKey>> /*throws*/ {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().ubrn_uniffi_cyclops_sdk_fn_method_cyclopsclient_list_user_api_keys(
+ uniffiTypeCyclopsClientObjectFactory.clonePointer(this),
+ );
+ },
+ /*pollFunc:*/ nativeModule()
+ .ubrn_ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule()
+ .ubrn_ffi_cyclops_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule()
+ .ubrn_ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule()
+ .ubrn_ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterSequenceTypeUserApiKey.lift.bind(
+ FfiConverterSequenceTypeUserApiKey,
+ ),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeSdkError.lift.bind(
+ FfiConverterTypeSdkError,
+ ),
+ );
+ }
+
async reconcilePool(
request: CreatePoolRequest,
asyncOpts_?: { signal: AbortSignal },
@@ -3202,6 +3562,9 @@ const FfiConverterOptionalMapStringString = new FfiConverterOptional(
FfiConverterMapStringString,
);
+// FfiConverter for string | undefined
+const FfiConverterOptionalString = new FfiConverterOptional(FfiConverterString);
+
// FfiConverter for OsGymSandboxClaimStatus | undefined
const FfiConverterOptionalTypeOSGymSandboxClaimStatus =
new FfiConverterOptional(FfiConverterTypeOSGymSandboxClaimStatus);
@@ -3215,6 +3578,9 @@ const FfiConverterOptionalTypeClaimSpec = new FfiConverterOptional(
FfiConverterTypeClaimSpec,
);
+// FfiConverter for Array<string>
+const FfiConverterSequenceString = new FfiConverterArray(FfiConverterString);
+
// FfiConverter for Array<HttpHeader>
const FfiConverterSequenceTypeHttpHeader = new FfiConverterArray(
FfiConverterTypeHttpHeader,
@@ -3225,14 +3591,16 @@ const FfiConverterOptionalBytes = new FfiConverterOptional(
FfiConverterArrayBuffer,
);
-// FfiConverter for Array<string>
-const FfiConverterSequenceString = new FfiConverterArray(FfiConverterString);
-
// FfiConverter for Array<Claim>
const FfiConverterSequenceTypeClaim = new FfiConverterArray(
FfiConverterTypeClaim,
);
+// FfiConverter for Array<Namespace>
+const FfiConverterSequenceTypeNamespace = new FfiConverterArray(
+ FfiConverterTypeNamespace,
+);
+
// FfiConverter for Array<Pool>
const FfiConverterSequenceTypePool = new FfiConverterArray(
FfiConverterTypePool,
@@ -3243,6 +3611,11 @@ const FfiConverterSequenceTypeTemplate = new FfiConverterArray(
FfiConverterTypeTemplate,
);
+// FfiConverter for Array<UserApiKey>
+const FfiConverterSequenceTypeUserApiKey = new FfiConverterArray(
+ FfiConverterTypeUserApiKey,
+);
+
/**
* This should be called before anything else.
*
@@ -3353,6 +3726,14 @@ function uniffiEnsureInitialized() {
"uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_template",
);
}
+ if (
+ nativeModule().ubrn_uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_user_api_key() !==
+ 9174
+ ) {
+ throw new UniffiInternalError.ApiChecksumMismatch(
+ "uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_user_api_key",
+ );
+ }
if (
nativeModule().ubrn_uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_claim() !==
20460
@@ -3377,6 +3758,14 @@ function uniffiEnsureInitialized() {
"uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_template",
);
}
+ if (
+ nativeModule().ubrn_uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_user_api_key() !==
+ 1700
+ ) {
+ throw new UniffiInternalError.ApiChecksumMismatch(
+ "uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_user_api_key",
+ );
+ }
if (
nativeModule().ubrn_uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_claim() !==
17760
@@ -3409,6 +3798,14 @@ function uniffiEnsureInitialized() {
"uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_claims",
);
}
+ if (
+ nativeModule().ubrn_uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_namespaces() !==
+ 65288
+ ) {
+ throw new UniffiInternalError.ApiChecksumMismatch(
+ "uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_namespaces",
+ );
+ }
if (
nativeModule().ubrn_uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_pools() !==
27984
@@ -3425,6 +3822,14 @@ function uniffiEnsureInitialized() {
"uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_templates",
);
}
+ if (
+ nativeModule().ubrn_uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_user_api_keys() !==
+ 5949
+ ) {
+ throw new UniffiInternalError.ApiChecksumMismatch(
+ "uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_user_api_keys",
+ );
+ }
if (
nativeModule().ubrn_uniffi_cyclops_sdk_checksum_method_cyclopsclient_reconcile_pool() !==
53919
@@ -3503,6 +3908,7 @@ export default Object.freeze({
FfiConverterTypeCreateClaimRequest,
FfiConverterTypeCreatePoolRequest,
FfiConverterTypeCreateTemplateRequest,
+ FfiConverterTypeCreateUserApiKeyRequest,
FfiConverterTypeCyclopsClient,
FfiConverterTypeCyclopsConfiguration,
FfiConverterTypeCyclopsCredentials,
@@ -3512,10 +3918,13 @@ export default Object.freeze({
FfiConverterTypeHttpHeader,
FfiConverterTypeHttpRequest,
FfiConverterTypeHttpResponse,
+ FfiConverterTypeNamespace,
+ FfiConverterTypeNewUserApiKey,
FfiConverterTypePool,
FfiConverterTypeResourceMetadata,
FfiConverterTypeSandbox,
FfiConverterTypeSdkError,
FfiConverterTypeTemplate,
+ FfiConverterTypeUserApiKey,
},
});
diff --git a/libs/fleet/sdk-bindings/ts-uniffi/fleet_sdk-ffi.ts b/libs/fleet/sdk-bindings/ts-uniffi/fleet_sdk-ffi.ts
index 05f781907d..9f6df1be46 100644
--- a/libs/fleet/sdk-bindings/ts-uniffi/fleet_sdk-ffi.ts
+++ b/libs/fleet/sdk-bindings/ts-uniffi/fleet_sdk-ffi.ts
@@ -368,6 +368,11 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cyclops_sdk_fn_method_cyclopsclient_create_user_api_key": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_claim": {
args: [FfiType.Handle, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -383,6 +388,11 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_user_api_key": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cyclops_sdk_fn_method_cyclopsclient_get_claim": {
args: [FfiType.Handle, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -403,6 +413,11 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cyclops_sdk_fn_method_cyclopsclient_list_namespaces": {
+ args: [FfiType.Handle],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cyclops_sdk_fn_method_cyclopsclient_list_pools": {
args: [FfiType.Handle, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -413,6 +428,11 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cyclops_sdk_fn_method_cyclopsclient_list_user_api_keys": {
+ args: [FfiType.Handle],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cyclops_sdk_fn_method_cyclopsclient_reconcile_pool": {
args: [FfiType.Handle, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -513,6 +533,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_user_api_key": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_claim": {
args: [],
ret: FfiType.UInt16,
@@ -528,6 +553,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_user_api_key": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_claim": {
args: [],
ret: FfiType.UInt16,
@@ -548,6 +578,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_namespaces": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_pools": {
args: [],
ret: FfiType.UInt16,
@@ -558,6 +593,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_user_api_keys": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cyclops_sdk_checksum_method_cyclopsclient_reconcile_pool": {
args: [],
ret: FfiType.UInt16,
@@ -740,15 +780,19 @@ interface NativeModuleInterface {
uniffi_cyclops_sdk_fn_method_cyclopsclient_create_claim(uniffiSelf: bigint, request: Uint8Array): bigint;
uniffi_cyclops_sdk_fn_method_cyclopsclient_create_pool(uniffiSelf: bigint, request: Uint8Array): bigint;
uniffi_cyclops_sdk_fn_method_cyclopsclient_create_template(uniffiSelf: bigint, request: Uint8Array): bigint;
+ uniffi_cyclops_sdk_fn_method_cyclopsclient_create_user_api_key(uniffiSelf: bigint, request: Uint8Array): bigint;
uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_claim(uniffiSelf: bigint, claim: Uint8Array): bigint;
uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_pool(uniffiSelf: bigint, pool: Uint8Array): bigint;
uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_template(uniffiSelf: bigint, template: Uint8Array): bigint;
+ uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_user_api_key(uniffiSelf: bigint, id: Uint8Array): bigint;
uniffi_cyclops_sdk_fn_method_cyclopsclient_get_claim(uniffiSelf: bigint, claim: Uint8Array): bigint;
uniffi_cyclops_sdk_fn_method_cyclopsclient_get_pool(uniffiSelf: bigint, name: Uint8Array): bigint;
uniffi_cyclops_sdk_fn_method_cyclopsclient_get_template(uniffiSelf: bigint, namespace: Uint8Array, name: Uint8Array): bigint;
uniffi_cyclops_sdk_fn_method_cyclopsclient_list_claims(uniffiSelf: bigint, namespace: Uint8Array): bigint;
+ uniffi_cyclops_sdk_fn_method_cyclopsclient_list_namespaces(uniffiSelf: bigint): bigint;
uniffi_cyclops_sdk_fn_method_cyclopsclient_list_pools(uniffiSelf: bigint, namespace: Uint8Array): bigint;
uniffi_cyclops_sdk_fn_method_cyclopsclient_list_templates(uniffiSelf: bigint, namespace: Uint8Array): bigint;
+ uniffi_cyclops_sdk_fn_method_cyclopsclient_list_user_api_keys(uniffiSelf: bigint): bigint;
uniffi_cyclops_sdk_fn_method_cyclopsclient_reconcile_pool(uniffiSelf: bigint, request: Uint8Array): bigint;
uniffi_cyclops_sdk_fn_method_cyclopsclient_reconcile_template(uniffiSelf: bigint, request: Uint8Array): bigint;
uniffi_cyclops_sdk_fn_method_cyclopsclient_service_request(uniffiSelf: bigint, sandbox: Uint8Array, service: Uint8Array, path: Uint8Array, request: Uint8Array): bigint;
@@ -769,15 +813,19 @@ interface NativeModuleInterface {
uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_claim(): number;
uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_pool(): number;
uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_template(): number;
+ uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_user_api_key(): number;
uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_claim(): number;
uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_pool(): number;
uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_template(): number;
+ uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_user_api_key(): number;
uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_claim(): number;
uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_pool(): number;
uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_template(): number;
uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_claims(): number;
+ uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_namespaces(): number;
uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_pools(): number;
uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_templates(): number;
+ uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_user_api_keys(): number;
uniffi_cyclops_sdk_checksum_method_cyclopsclient_reconcile_pool(): number;
uniffi_cyclops_sdk_checksum_method_cyclopsclient_reconcile_template(): number;
uniffi_cyclops_sdk_checksum_method_cyclopsclient_service_request(): number;
diff --git a/libs/fleet/sdk-bindings/ts-uniffi/fleet_sdk.ts b/libs/fleet/sdk-bindings/ts-uniffi/fleet_sdk.ts
index d35a3ac336..99a9627611 100644
--- a/libs/fleet/sdk-bindings/ts-uniffi/fleet_sdk.ts
+++ b/libs/fleet/sdk-bindings/ts-uniffi/fleet_sdk.ts
@@ -47,7 +47,8 @@ const FfiConverterString = uniffiCreateFfiConverterString(stringConverter);
export type ResourceMetadata = {
namespace: string,
name: string,
- labels?: Map<string, string>
+ labels?: Map<string, string>,
+ creationTimestamp?: string
}
/**
@@ -73,18 +74,21 @@ const FfiConverterTypeResourceMetadata = (() => {
return {
namespace: FfiConverterString.read(from),
name: FfiConverterString.read(from),
- labels: FfiConverterOptionalMapStringString.read(from)
+ labels: FfiConverterOptionalMapStringString.read(from),
+ creationTimestamp: FfiConverterOptionalString.read(from)
};
}
write(value: TypeName, into: RustBuffer): void {
FfiConverterString.write(value.namespace, into);
FfiConverterString.write(value.name, into);
FfiConverterOptionalMapStringString.write(value.labels, into);
+ FfiConverterOptionalString.write(value.creationTimestamp, into);
}
allocationSize(value: TypeName): number {
return FfiConverterString.allocationSize(value.namespace) +
FfiConverterString.allocationSize(value.name) +
- FfiConverterOptionalMapStringString.allocationSize(value.labels);
+ FfiConverterOptionalMapStringString.allocationSize(value.labels) +
+ FfiConverterOptionalString.allocationSize(value.creationTimestamp);
}
};
@@ -343,6 +347,49 @@ const FfiConverterTypeCreateTemplateRequest = (() => {
return new FFIConverter();
})();
+export type CreateUserApiKeyRequest = {
+ name: string,
+ scope: Array<string>
+}
+
+/**
+ * Generated factory for {@link CreateUserApiKeyRequest} record objects.
+ */
+export const CreateUserApiKeyRequest = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<CreateUserApiKeyRequest, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<CreateUserApiKeyRequest>,
+ });
+})();
+
+const FfiConverterTypeCreateUserApiKeyRequest = (() => {
+ type TypeName = CreateUserApiKeyRequest;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ name: FfiConverterString.read(from),
+ scope: FfiConverterSequenceString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.name, into);
+ FfiConverterSequenceString.write(value.scope, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.name) +
+ FfiConverterSequenceString.allocationSize(value.scope);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
export interface CyclopsCredentialsLike {
}
@@ -715,6 +762,112 @@ const FfiConverterTypeHttpResponse = (() => {
return new FFIConverter();
})();
+export type Namespace = {
+ name: string,
+ status: string,
+ createdAt: string,
+ labels?: Map<string, string>
+}
+
+/**
+ * Generated factory for {@link Namespace} record objects.
+ */
+export const Namespace = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<Namespace, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<Namespace>,
+ });
+})();
+
+const FfiConverterTypeNamespace = (() => {
+ type TypeName = Namespace;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ name: FfiConverterString.read(from),
+ status: FfiConverterString.read(from),
+ createdAt: FfiConverterString.read(from),
+ labels: FfiConverterOptionalMapStringString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.name, into);
+ FfiConverterString.write(value.status, into);
+ FfiConverterString.write(value.createdAt, into);
+ FfiConverterOptionalMapStringString.write(value.labels, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.name) +
+ FfiConverterString.allocationSize(value.status) +
+ FfiConverterString.allocationSize(value.createdAt) +
+ FfiConverterOptionalMapStringString.allocationSize(value.labels);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+export type NewUserApiKey = {
+ clientId: string,
+ clientSecret: string,
+ tokenUrl: string,
+ name: string,
+ scope: Array<string>
+}
+
+/**
+ * Generated factory for {@link NewUserApiKey} record objects.
+ */
+export const NewUserApiKey = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<NewUserApiKey, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<NewUserApiKey>,
+ });
+})();
+
+const FfiConverterTypeNewUserApiKey = (() => {
+ type TypeName = NewUserApiKey;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ clientId: FfiConverterString.read(from),
+ clientSecret: FfiConverterString.read(from),
+ tokenUrl: FfiConverterString.read(from),
+ name: FfiConverterString.read(from),
+ scope: FfiConverterSequenceString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.clientId, into);
+ FfiConverterString.write(value.clientSecret, into);
+ FfiConverterString.write(value.tokenUrl, into);
+ FfiConverterString.write(value.name, into);
+ FfiConverterSequenceString.write(value.scope, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.clientId) +
+ FfiConverterString.allocationSize(value.clientSecret) +
+ FfiConverterString.allocationSize(value.tokenUrl) +
+ FfiConverterString.allocationSize(value.name) +
+ FfiConverterSequenceString.allocationSize(value.scope);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
export type Sandbox = {
namespace: string,
claim: string,
@@ -821,6 +974,57 @@ const FfiConverterTypeTemplate = (() => {
return new FFIConverter();
})();
+export type UserApiKey = {
+ id: string,
+ clientId: string,
+ name: string,
+ scope: Array<string>
+}
+
+/**
+ * Generated factory for {@link UserApiKey} record objects.
+ */
+export const UserApiKey = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<UserApiKey, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<UserApiKey>,
+ });
+})();
+
+const FfiConverterTypeUserApiKey = (() => {
+ type TypeName = UserApiKey;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ id: FfiConverterString.read(from),
+ clientId: FfiConverterString.read(from),
+ name: FfiConverterString.read(from),
+ scope: FfiConverterSequenceString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.id, into);
+ FfiConverterString.write(value.clientId, into);
+ FfiConverterString.write(value.name, into);
+ FfiConverterSequenceString.write(value.scope, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.id) +
+ FfiConverterString.allocationSize(value.clientId) +
+ FfiConverterString.allocationSize(value.name) +
+ FfiConverterSequenceString.allocationSize(value.scope);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
// Error type: AccessTokenProviderError
export enum AccessTokenProviderError_Tags {
@@ -1803,15 +2007,19 @@ export interface CyclopsClientLike {
createClaim(request: CreateClaimRequest, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Claim>;
createPool(request: CreatePoolRequest, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Pool>;
createTemplate(request: CreateTemplateRequest, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Template>;
+ createUserApiKey(request: CreateUserApiKeyRequest, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<NewUserApiKey>;
deleteClaim(claim: Claim, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<void>;
deletePool(pool: Pool, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<void>;
deleteTemplate(template: Template, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<void>;
+ deleteUserApiKey(id: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<void>;
getClaim(claim: Claim, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Claim>;
getPool(name: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Pool>;
getTemplate(namespace: string, name: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Template>;
listClaims(namespace: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Array<Claim>>;
+ listNamespaces(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Array<Namespace>>;
listPools(namespace: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Array<Pool>>;
listTemplates(namespace: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Array<Template>>;
+ listUserApiKeys(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Array<UserApiKey>>;
reconcilePool(request: CreatePoolRequest, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Pool>;
reconcileTemplate(request: CreateTemplateRequest, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Template>;
serviceRequest(sandbox: Sandbox, service: string, path: string, request: HttpRequest, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<HttpResponse>;
@@ -2028,6 +2236,38 @@ private constructor(pointer: UniffiHandle) {
}
}
+ async createUserApiKey(request: CreateUserApiKeyRequest, asyncOpts_?: { signal: AbortSignal }): Promise<NewUserApiKey> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cyclops_sdk_fn_method_cyclopsclient_create_user_api_key(
+ uniffiTypeCyclopsClientObjectFactory.clonePointer(this),FfiConverterTypeCreateUserApiKeyRequest.lower(request, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cyclops_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeNewUserApiKey.lift.bind(FfiConverterTypeNewUserApiKey),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeSdkError.lift.bind(FfiConverterTypeSdkError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
async deleteClaim(claim: Claim, asyncOpts_?: { signal: AbortSignal }): Promise<void> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
@@ -2109,6 +2349,33 @@ private constructor(pointer: UniffiHandle) {
}
}
+ async deleteUserApiKey(id: string, asyncOpts_?: { signal: AbortSignal }): Promise<void> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cyclops_sdk_fn_method_cyclopsclient_delete_user_api_key(
+ uniffiTypeCyclopsClientObjectFactory.clonePointer(this),FfiConverterString.lower(id, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cyclops_sdk_rust_future_poll_void,
+ /*cancelFunc:*/ nativeModule().ffi_cyclops_sdk_rust_future_cancel_void,
+ /*completeFunc:*/ nativeModule().ffi_cyclops_sdk_rust_future_complete_void,
+ /*freeFunc:*/ nativeModule().ffi_cyclops_sdk_rust_future_free_void,
+ /*liftFunc:*/ (_v) => {},
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeSdkError.lift.bind(FfiConverterTypeSdkError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
async getClaim(claim: Claim, asyncOpts_?: { signal: AbortSignal }): Promise<Claim> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
@@ -2237,6 +2504,38 @@ private constructor(pointer: UniffiHandle) {
}
}
+ async listNamespaces(asyncOpts_?: { signal: AbortSignal }): Promise<Array<Namespace>> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cyclops_sdk_fn_method_cyclopsclient_list_namespaces(
+ uniffiTypeCyclopsClientObjectFactory.clonePointer(this)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cyclops_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterSequenceTypeNamespace.lift.bind(FfiConverterSequenceTypeNamespace),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeSdkError.lift.bind(FfiConverterTypeSdkError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
async listPools(namespace: string, asyncOpts_?: { signal: AbortSignal }): Promise<Array<Pool>> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
@@ -2301,6 +2600,38 @@ private constructor(pointer: UniffiHandle) {
}
}
+ async listUserApiKeys(asyncOpts_?: { signal: AbortSignal }): Promise<Array<UserApiKey>> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cyclops_sdk_fn_method_cyclopsclient_list_user_api_keys(
+ uniffiTypeCyclopsClientObjectFactory.clonePointer(this)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cyclops_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cyclops_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cyclops_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cyclops_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterSequenceTypeUserApiKey.lift.bind(FfiConverterSequenceTypeUserApiKey),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeSdkError.lift.bind(FfiConverterTypeSdkError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
async reconcilePool(request: CreatePoolRequest, asyncOpts_?: { signal: AbortSignal }): Promise<Pool> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
@@ -2778,6 +3109,9 @@ const FfiConverterMapStringString = new FfiConverterMap(FfiConverterString, FfiC
// FfiConverter for Map<string, string> | undefined
const FfiConverterOptionalMapStringString = new FfiConverterOptional(FfiConverterMapStringString);
+// FfiConverter for string | undefined
+const FfiConverterOptionalString = new FfiConverterOptional(FfiConverterString);
+
// FfiConverter for OsGymSandboxClaimStatus | undefined
const FfiConverterOptionalTypeOSGymSandboxClaimStatus = new FfiConverterOptional(FfiConverterTypeOSGymSandboxClaimStatus);
@@ -2787,24 +3121,30 @@ const FfiConverterOptionalTypeOSGymSandboxWarmPoolStatus = new FfiConverterOptio
// FfiConverter for ClaimSpec | undefined
const FfiConverterOptionalTypeClaimSpec = new FfiConverterOptional(FfiConverterTypeClaimSpec);
+// FfiConverter for Array<string>
+const FfiConverterSequenceString = new FfiConverterArray(FfiConverterString);
+
// FfiConverter for Array<HttpHeader>
const FfiConverterSequenceTypeHttpHeader = new FfiConverterArray(FfiConverterTypeHttpHeader);
// FfiConverter for ArrayBuffer | undefined
const FfiConverterOptionalBytes = new FfiConverterOptional(FfiConverterArrayBuffer);
-// FfiConverter for Array<string>
-const FfiConverterSequenceString = new FfiConverterArray(FfiConverterString);
-
// FfiConverter for Array<Claim>
const FfiConverterSequenceTypeClaim = new FfiConverterArray(FfiConverterTypeClaim);
+// FfiConverter for Array<Namespace>
+const FfiConverterSequenceTypeNamespace = new FfiConverterArray(FfiConverterTypeNamespace);
+
// FfiConverter for Array<Pool>
const FfiConverterSequenceTypePool = new FfiConverterArray(FfiConverterTypePool);
// FfiConverter for Array<Template>
const FfiConverterSequenceTypeTemplate = new FfiConverterArray(FfiConverterTypeTemplate);
+// FfiConverter for Array<UserApiKey>
+const FfiConverterSequenceTypeUserApiKey = new FfiConverterArray(FfiConverterTypeUserApiKey);
+
/**
* This should be called before anything else.
@@ -2857,6 +3197,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_template() !== 13689) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_template");
}
+ if (nativeModule().uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_user_api_key() !== 9174) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_user_api_key");
+ }
if (nativeModule().uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_claim() !== 20460) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_claim");
}
@@ -2866,6 +3209,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_template() !== 54852) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_template");
}
+ if (nativeModule().uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_user_api_key() !== 1700) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_user_api_key");
+ }
if (nativeModule().uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_claim() !== 17760) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_claim");
}
@@ -2878,12 +3224,18 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_claims() !== 7802) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_claims");
}
+ if (nativeModule().uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_namespaces() !== 65288) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_namespaces");
+ }
if (nativeModule().uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_pools() !== 27984) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_pools");
}
if (nativeModule().uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_templates() !== 58376) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_templates");
}
+ if (nativeModule().uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_user_api_keys() !== 5949) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_user_api_keys");
+ }
if (nativeModule().uniffi_cyclops_sdk_checksum_method_cyclopsclient_reconcile_pool() !== 53919) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cyclops_sdk_checksum_method_cyclopsclient_reconcile_pool");
}
@@ -2922,6 +3274,7 @@ export default Object.freeze({
FfiConverterTypeCreateClaimRequest,
FfiConverterTypeCreatePoolRequest,
FfiConverterTypeCreateTemplateRequest,
+ FfiConverterTypeCreateUserApiKeyRequest,
FfiConverterTypeCyclopsClient,
FfiConverterTypeCyclopsConfiguration,
FfiConverterTypeCyclopsCredentials,
@@ -2931,10 +3284,13 @@ export default Object.freeze({
FfiConverterTypeHttpHeader,
FfiConverterTypeHttpRequest,
FfiConverterTypeHttpResponse,
+ FfiConverterTypeNamespace,
+ FfiConverterTypeNewUserApiKey,
FfiConverterTypePool,
FfiConverterTypeResourceMetadata,
FfiConverterTypeSandbox,
FfiConverterTypeSdkError,
FfiConverterTypeTemplate,
+ FfiConverterTypeUserApiKey,
}
});
\ No newline at end of file
diff --git a/libs/fleet/sdk/src/claims.rs b/libs/fleet/sdk/src/claims.rs
index c87da704fe..9b75a359f9 100644
--- a/libs/fleet/sdk/src/claims.rs
+++ b/libs/fleet/sdk/src/claims.rs
@@ -59,6 +59,7 @@ impl CyclopsClient {
namespace: pool.metadata.namespace.clone(),
name: claim_name()?,
labels: None,
+ creation_timestamp: None,
},
spec,
status: None,
diff --git a/libs/fleet/sdk/src/client.rs b/libs/fleet/sdk/src/client.rs
index d303218bf0..fde94c9154 100644
--- a/libs/fleet/sdk/src/client.rs
+++ b/libs/fleet/sdk/src/client.rs
@@ -249,21 +249,21 @@ impl CyclopsClient {
NamespaceLifecycleGuard {}
}
- pub async fn execute_authenticated(
+ pub(crate) async fn execute_authenticated_service(
&self,
request: HttpRequest,
) -> Result<HttpResponse, SdkError> {
self.transport
- .execute_authenticated(request, AuthenticatedRequestClass::ControlPlane)
+ .execute_authenticated(request, AuthenticatedRequestClass::ServiceProxy)
.await
}
- pub(crate) async fn execute_authenticated_service(
+ pub async fn execute_authenticated(
&self,
request: HttpRequest,
) -> Result<HttpResponse, SdkError> {
self.transport
- .execute_authenticated(request, AuthenticatedRequestClass::ServiceProxy)
+ .execute_authenticated(request, AuthenticatedRequestClass::ControlPlane)
.await
}
}
diff --git a/libs/fleet/sdk/src/lib.rs b/libs/fleet/sdk/src/lib.rs
index 4649f1d300..52df2ec75b 100644
--- a/libs/fleet/sdk/src/lib.rs
+++ b/libs/fleet/sdk/src/lib.rs
@@ -1,12 +1,14 @@
mod claims;
mod client;
mod error;
+mod namespaces;
mod pools;
mod routes;
mod services;
mod templates;
mod transport;
mod types;
+mod user_keys;
pub use client::CyclopsClient;
pub use error::{
@@ -15,9 +17,10 @@ pub use error::{
pub use routes::validate_dns_label;
pub use transport::{AccessTokenProvider, HttpClient};
pub use types::{
- Claim, CreateClaimRequest, CreatePoolRequest, CreateTemplateRequest, CyclopsConfiguration,
- CyclopsCredentials, CyclopsTokenProviderConfiguration, HttpHeader, HttpRequest, HttpResponse,
- Pool, ResourceMetadata, Sandbox, Template,
+ Claim, CreateClaimRequest, CreatePoolRequest, CreateTemplateRequest, CreateUserApiKeyRequest,
+ CyclopsConfiguration, CyclopsCredentials, CyclopsTokenProviderConfiguration, HttpHeader,
+ HttpRequest, HttpResponse, Namespace, NewUserApiKey, Pool, ResourceMetadata, Sandbox, Template,
+ UserApiKey,
};
uniffi::setup_scaffolding!("fleet_sdk");
diff --git a/libs/fleet/sdk/src/namespaces.rs b/libs/fleet/sdk/src/namespaces.rs
new file mode 100644
index 0000000000..2b831a3bce
--- /dev/null
+++ b/libs/fleet/sdk/src/namespaces.rs
@@ -0,0 +1,28 @@
+use crate::{CyclopsClient, HttpHeader, HttpRequest, Namespace, SdkError, routes};
+use std::sync::Arc;
+
+const JSON_CONTENT_TYPE: &str = "application/json";
+
+#[uniffi::export]
+impl CyclopsClient {
+ pub async fn list_namespaces(self: Arc<Self>) -> Result<Vec<Namespace>, SdkError> {
+ self.send_json_crud(
+ "list namespaces",
+ json_request("GET", routes::namespace_collection(self.base_url())?),
+ &[200],
+ )
+ .await
+ }
+}
+
+fn json_request(method: &str, url: url::Url) -> HttpRequest {
+ HttpRequest {
+ method: method.into(),
+ url: url.into(),
+ headers: vec![HttpHeader {
+ name: "accept".into(),
+ value: JSON_CONTENT_TYPE.into(),
+ }],
+ body: None,
+ }
+}
diff --git a/libs/fleet/sdk/src/pools.rs b/libs/fleet/sdk/src/pools.rs
index 2e6a1b8eea..481b2ba22e 100644
--- a/libs/fleet/sdk/src/pools.rs
+++ b/libs/fleet/sdk/src/pools.rs
@@ -34,6 +34,7 @@ impl CyclopsClient {
namespace: request.namespace.clone(),
name: request.namespace,
labels: None,
+ creation_timestamp: None,
},
spec: request.spec,
status: None,
diff --git a/libs/fleet/sdk/src/routes.rs b/libs/fleet/sdk/src/routes.rs
index 3635aee997..af4f9c00ff 100644
--- a/libs/fleet/sdk/src/routes.rs
+++ b/libs/fleet/sdk/src/routes.rs
@@ -9,6 +9,7 @@ const TEMPLATE_COLLECTION_SUFFIX: &str = "/osgymsandboxtemplates";
const NAMESPACE_COLLECTION: &str = "api/namespaces";
const NAMESPACE_PREFIX: &str = "api/namespaces/";
const SERVICE_COLLECTION_PREFIX: &str = "api/svc/";
+const USER_KEY_COLLECTION: &str = "api/user-keys";
pub fn pool_collection(base: &Url, namespace: &str) -> Result<Url, SdkError> {
validate_dns_label_for("namespace", namespace)?;
@@ -61,6 +62,20 @@ pub fn namespace_item(base: &Url, namespace: &str) -> Result<Url, SdkError> {
route(base, format!("{NAMESPACE_PREFIX}{namespace}"))
}
+pub fn user_key_collection(base: &Url) -> Result<Url, SdkError> {
+ route(base, USER_KEY_COLLECTION.into())
+}
+
+pub fn user_key_item(base: &Url, id: &str) -> Result<Url, SdkError> {
+ let mut url = user_key_collection(base)?;
+ url.path_segments_mut()
+ .map_err(|_| SdkError::Configuration {
+ reason: "base_url cannot be used for user API key routes".into(),
+ })?
+ .push(id);
+ Ok(url)
+}
+
pub fn validate_dns_label(value: &str) -> Result<(), SdkError> {
validate_dns_label_for("resource name", value)
}
diff --git a/libs/fleet/sdk/src/templates.rs b/libs/fleet/sdk/src/templates.rs
index e37ba42256..cebcb6ed5c 100644
--- a/libs/fleet/sdk/src/templates.rs
+++ b/libs/fleet/sdk/src/templates.rs
@@ -27,6 +27,7 @@ impl CyclopsClient {
namespace: request.namespace,
name: request.name,
labels: None,
+ creation_timestamp: None,
},
spec: request.spec,
};
diff --git a/libs/fleet/sdk/src/types.rs b/libs/fleet/sdk/src/types.rs
index 5a0664ee00..149de2f526 100644
--- a/libs/fleet/sdk/src/types.rs
+++ b/libs/fleet/sdk/src/types.rs
@@ -2,7 +2,7 @@ use cyclops_sdk_schema::{
ClaimSpec, OSGymSandboxClaimStatus, OSGymSandboxTemplateSpec, OSGymSandboxWarmPoolSpec,
OSGymSandboxWarmPoolStatus,
};
-use serde::{Deserialize, Serialize};
+use serde::{Deserialize, Deserializer, Serialize};
use std::{collections::HashMap, fmt, sync::Arc};
#[derive(uniffi::Object)]
@@ -84,6 +84,12 @@ pub struct ResourceMetadata {
pub namespace: String,
pub name: String,
pub labels: Option<HashMap<String, String>>,
+ #[serde(
+ rename = "creationTimestamp",
+ default,
+ skip_serializing_if = "Option::is_none"
+ )]
+ pub creation_timestamp: Option<String>,
}
/// UniFFI cannot emit aliases for external record types. Generated bindings use
@@ -133,6 +139,50 @@ impl PartialEq for Claim {
}
}
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, uniffi::Record)]
+#[serde(rename_all = "camelCase")]
+pub struct Namespace {
+ pub name: String,
+ pub status: String,
+ pub created_at: String,
+ pub labels: Option<HashMap<String, String>>,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, uniffi::Record)]
+pub struct UserApiKey {
+ pub id: String,
+ #[serde(rename = "client_id")]
+ pub client_id: String,
+ pub name: String,
+ #[serde(default, deserialize_with = "deserialize_nullable_scope")]
+ pub scope: Vec<String>,
+}
+
+fn deserialize_nullable_scope<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
+where
+ D: Deserializer<'de>,
+{
+ Option::<Vec<String>>::deserialize(deserializer).map(Option::unwrap_or_default)
+}
+
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, uniffi::Record)]
+pub struct CreateUserApiKeyRequest {
+ pub name: String,
+ pub scope: Vec<String>,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, uniffi::Record)]
+pub struct NewUserApiKey {
+ #[serde(rename = "client_id")]
+ pub client_id: String,
+ #[serde(rename = "client_secret")]
+ pub client_secret: String,
+ #[serde(rename = "token_url")]
+ pub token_url: String,
+ pub name: String,
+ pub scope: Vec<String>,
+}
+
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, uniffi::Record)]
pub struct Sandbox {
pub namespace: String,
diff --git a/libs/fleet/sdk/src/user_keys.rs b/libs/fleet/sdk/src/user_keys.rs
new file mode 100644
index 0000000000..d4e710bff0
--- /dev/null
+++ b/libs/fleet/sdk/src/user_keys.rs
@@ -0,0 +1,79 @@
+use crate::{
+ CreateUserApiKeyRequest, CyclopsClient, HttpHeader, HttpRequest, NewUserApiKey, SdkError,
+ UserApiKey, routes,
+};
+use serde::Deserialize;
+use std::sync::Arc;
+
+const JSON_CONTENT_TYPE: &str = "application/json";
+
+#[derive(Deserialize)]
+struct ListUserApiKeysResponse {
+ keys: Vec<UserApiKey>,
+}
+
+#[uniffi::export]
+impl CyclopsClient {
+ pub async fn list_user_api_keys(self: Arc<Self>) -> Result<Vec<UserApiKey>, SdkError> {
+ let response: ListUserApiKeysResponse = self
+ .send_json_crud(
+ "list user API keys",
+ json_request("GET", routes::user_key_collection(self.base_url())?, None),
+ &[200],
+ )
+ .await?;
+ Ok(response.keys)
+ }
+
+ pub async fn create_user_api_key(
+ self: Arc<Self>,
+ request: CreateUserApiKeyRequest,
+ ) -> Result<NewUserApiKey, SdkError> {
+ let body = serde_json::to_vec(&request).map_err(|error| SdkError::Body {
+ reason: error.to_string(),
+ })?;
+ self.send_json_crud(
+ "create user API key",
+ json_request(
+ "POST",
+ routes::user_key_collection(self.base_url())?,
+ Some(body),
+ ),
+ &[201],
+ )
+ .await
+ }
+
+ pub async fn delete_user_api_key(self: Arc<Self>, id: String) -> Result<(), SdkError> {
+ if id.is_empty() {
+ return Err(SdkError::Configuration {
+ reason: "user API key id must not be empty".into(),
+ });
+ }
+ self.send_unit_crud(
+ "delete user API key",
+ json_request("DELETE", routes::user_key_item(self.base_url(), &id)?, None),
+ &[204],
+ )
+ .await
+ }
+}
+
+fn json_request(method: &str, url: url::Url, body: Option<Vec<u8>>) -> HttpRequest {
+ let mut headers = vec![HttpHeader {
+ name: "accept".into(),
+ value: JSON_CONTENT_TYPE.into(),
+ }];
+ if body.is_some() {
+ headers.push(HttpHeader {
+ name: "content-type".into(),
+ value: JSON_CONTENT_TYPE.into(),
+ });
+ }
+ HttpRequest {
+ method: method.into(),
+ url: url.into(),
+ headers,
+ body,
+ }
+}
diff --git a/libs/fleet/sdk/tests/account_flow.rs b/libs/fleet/sdk/tests/account_flow.rs
new file mode 100644
index 0000000000..0be66017c2
--- /dev/null
+++ b/libs/fleet/sdk/tests/account_flow.rs
@@ -0,0 +1,181 @@
+mod support;
+
+use cyclops_sdk::{
+ CreateUserApiKeyRequest, CyclopsClient, CyclopsTokenProviderConfiguration, HttpHeader,
+ HttpRequest, HttpResponse, Namespace, NewUserApiKey, SdkError, UserApiKey,
+};
+use std::{collections::HashMap, sync::Arc};
+use support::ScriptedHttpClient;
+
+const BASE_URL: &str = "https://cyclops.example:8443/root";
+
+#[tokio::test]
+async fn typed_account_apis_use_authenticated_backend_contracts() {
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(response(
+ 200,
+ br#"[{"name":"demo","status":"Active","createdAt":"2026-08-04T12:00:00Z","labels":{"team":"sdk"}}]"#,
+ )),
+ Ok(response(
+ 200,
+ br#"{"keys":[{"id":"key-id","client_id":"ukey-demo","name":"demo key","scope":["demo"]}]}"#,
+ )),
+ Ok(response(
+ 201,
+ br#"{"client_id":"ukey-ci","client_secret":"shown-once","token_url":"https://identity.example/token","name":"ci-key","scope":["demo"]}"#,
+ )),
+ Ok(response(204, b"")),
+ ]));
+ let client = client(Arc::clone(&http));
+
+ assert_eq!(
+ Arc::clone(&client).list_namespaces().await.unwrap(),
+ vec![Namespace {
+ name: "demo".into(),
+ status: "Active".into(),
+ created_at: "2026-08-04T12:00:00Z".into(),
+ labels: Some(HashMap::from([("team".into(), "sdk".into())])),
+ }]
+ );
+ assert_eq!(
+ Arc::clone(&client).list_user_api_keys().await.unwrap(),
+ vec![UserApiKey {
+ id: "key-id".into(),
+ client_id: "ukey-demo".into(),
+ name: "demo key".into(),
+ scope: vec!["demo".into()],
+ }]
+ );
+ assert_eq!(
+ Arc::clone(&client)
+ .create_user_api_key(CreateUserApiKeyRequest {
+ name: "ci-key".into(),
+ scope: vec!["demo".into()],
+ })
+ .await
+ .unwrap(),
+ NewUserApiKey {
+ client_id: "ukey-ci".into(),
+ client_secret: "shown-once".into(),
+ token_url: "https://identity.example/token".into(),
+ name: "ci-key".into(),
+ scope: vec!["demo".into()],
+ }
+ );
+ client.delete_user_api_key("key/id".into()).await.unwrap();
+
+ let requests = http.requests().await;
+ assert_eq!(requests.len(), 4);
+ assert_request(
+ &requests[0],
+ "GET",
+ "https://cyclops.example:8443/root/api/namespaces",
+ None,
+ );
+ assert_request(
+ &requests[1],
+ "GET",
+ "https://cyclops.example:8443/root/api/user-keys",
+ None,
+ );
+ assert_request(
+ &requests[2],
+ "POST",
+ "https://cyclops.example:8443/root/api/user-keys",
+ Some(br#"{"name":"ci-key","scope":["demo"]}"#),
+ );
+ assert_request(
+ &requests[3],
+ "DELETE",
+ "https://cyclops.example:8443/root/api/user-keys/key%2Fid",
+ None,
+ );
+}
+
+#[tokio::test]
+async fn list_user_api_keys_treats_null_scope_as_unrestricted() {
+ let http = Arc::new(ScriptedHttpClient::new([Ok(response(
+ 200,
+ br#"{"keys":[{"id":"key-id","client_id":"ukey-demo","name":"demo key","scope":null}]}"#,
+ ))]));
+ let client = client(Arc::clone(&http));
+
+ assert_eq!(
+ client.list_user_api_keys().await.unwrap(),
+ vec![UserApiKey {
+ id: "key-id".into(),
+ client_id: "ukey-demo".into(),
+ name: "demo key".into(),
+ scope: vec![],
+ }]
+ );
+}
+
+#[tokio::test]
+async fn typed_account_apis_validate_ids_statuses_and_json() {
+ let http = Arc::new(ScriptedHttpClient::new([
+ Ok(response(200, b"not json")),
+ Ok(response(500, b"key service unavailable")),
+ ]));
+ let client = client(Arc::clone(&http));
+
+ assert!(matches!(
+ Arc::clone(&client).list_namespaces().await.unwrap_err(),
+ SdkError::Body { .. }
+ ));
+ assert!(matches!(
+ Arc::clone(&client).list_user_api_keys().await.unwrap_err(),
+ SdkError::Status {
+ ref operation,
+ status: 500,
+ ref body,
+ } if operation == "list user API keys" && body == "key service unavailable"
+ ));
+ assert!(matches!(
+ client.delete_user_api_key(String::new()).await.unwrap_err(),
+ SdkError::Configuration { ref reason } if reason == "user API key id must not be empty"
+ ));
+ assert_eq!(http.request_count().await, 2);
+}
+
+fn client(http: Arc<ScriptedHttpClient>) -> Arc<CyclopsClient> {
+ CyclopsClient::connect_with_access_token(
+ CyclopsTokenProviderConfiguration {
+ base_url: BASE_URL.into(),
+ pool_poll_interval_ms: 1,
+ pool_poll_limit: 1,
+ claim_poll_interval_ms: 1,
+ claim_poll_limit: 1,
+ },
+ "offline-token".into(),
+ http,
+ )
+ .unwrap()
+}
+
+fn response(status: u16, body: &[u8]) -> HttpResponse {
+ HttpResponse {
+ status,
+ headers: vec![],
+ body: body.to_vec(),
+ }
+}
+
+fn assert_request(request: &HttpRequest, method: &str, url: &str, body: Option<&[u8]>) {
+ assert_eq!(request.method, method);
+ assert_eq!(request.url, url);
+ assert_eq!(request.body.as_deref(), body);
+ let mut expected_headers = vec![header("accept", "application/json")];
+ if body.is_some() {
+ expected_headers.push(header("content-type", "application/json"));
+ }
+ expected_headers.push(header("authorization", "Bearer offline-token"));
+ assert_eq!(request.headers, expected_headers);
+}
+
+fn header(name: &str, value: &str) -> HttpHeader {
+ HttpHeader {
+ name: name.into(),
+ value: value.into(),
+ }
+}
diff --git a/libs/fleet/sdk/tests/binding_generation.rs b/libs/fleet/sdk/tests/binding_generation.rs
index ee179850af..2d03f709b8 100644
--- a/libs/fleet/sdk/tests/binding_generation.rs
+++ b/libs/fleet/sdk/tests/binding_generation.rs
@@ -55,6 +55,18 @@ fn generated_bindings_hide_raw_credentials_and_claim_update() {
assert!(python.contains("def connect_with_access_token_and_native_http_client"));
assert!(python.contains("async def reconcile_pool"));
assert!(kotlin.contains("suspend fun `reconcilePool`"));
+ assert!(!python.contains("async def execute_authenticated"));
+ assert!(!kotlin.contains("suspend fun `executeAuthenticated`"));
+ assert!(python.contains("async def list_namespaces"));
+ assert!(python.contains("async def list_user_api_keys"));
+ assert!(python.contains("async def create_user_api_key"));
+ assert!(python.contains("async def delete_user_api_key"));
+ assert!(kotlin.contains("suspend fun `listNamespaces`"));
+ assert!(kotlin.contains("suspend fun `listUserApiKeys`"));
+ assert!(kotlin.contains("suspend fun `createUserApiKey`"));
+ assert!(kotlin.contains("suspend fun `deleteUserApiKey`"));
+ assert!(python.contains("creation_timestamp:typing.Optional[str]"));
+ assert!(kotlin.contains("var `creationTimestamp`: kotlin.String?"));
fs::remove_dir_all(output).unwrap();
}
diff --git a/libs/fleet/sdk/tests/claim_flow.rs b/libs/fleet/sdk/tests/claim_flow.rs
index 96c4f0621c..29da963559 100644
--- a/libs/fleet/sdk/tests/claim_flow.rs
+++ b/libs/fleet/sdk/tests/claim_flow.rs
@@ -240,6 +240,7 @@ async fn validation_and_malformed_responses_fail_without_unexpected_http() {
namespace: NAMESPACE.into(),
name: "Uppercase".into(),
labels: None,
+ creation_timestamp: None,
},
..claim("valid-claim", claim_spec("example-pool-template"), None)
};
@@ -291,6 +292,7 @@ fn pool_named(name: &str, replicas: u32) -> Pool {
namespace: name.into(),
name: name.into(),
labels: None,
+ creation_timestamp: None,
},
spec: serde_json::from_value(serde_json::json!({
"replicas": replicas,
@@ -315,6 +317,7 @@ fn template_named(name: &str, services: Option<Vec<&str>>) -> Template {
namespace: NAMESPACE.into(),
name: name.into(),
labels: None,
+ creation_timestamp: None,
},
spec: serde_json::from_value(serde_json::json!({
"vmTemplate": {
@@ -334,6 +337,7 @@ fn claim(name: &str, spec: ClaimSpec, status: Option<serde_json::Value>) -> Clai
namespace: NAMESPACE.into(),
name: name.into(),
labels: None,
+ creation_timestamp: None,
},
spec,
status: status.map(|status| serde_json::from_value(status).unwrap()),
@@ -519,6 +523,7 @@ async fn wait_claim_rejects_invalid_claim_identity_before_token_or_pool_lookup()
namespace: NAMESPACE.into(),
name: "Uppercase".into(),
labels: None,
+ creation_timestamp: None,
},
..claim("named-claim", claim_spec("example-pool-template"), None)
};
diff --git a/libs/fleet/sdk/tests/pool_flow.rs b/libs/fleet/sdk/tests/pool_flow.rs
index 0c0ff8d23e..267dfecb82 100644
--- a/libs/fleet/sdk/tests/pool_flow.rs
+++ b/libs/fleet/sdk/tests/pool_flow.rs
@@ -590,6 +590,7 @@ async fn rejects_deleting_a_pool_outside_the_namespace_owned_lifecycle() {
namespace: NAMESPACE.into(),
name: "other-pool".into(),
labels: None,
+ creation_timestamp: None,
},
..pool()
};
@@ -609,6 +610,7 @@ async fn updates_non_lifecycle_pool_resources_without_namespace_cleanup() {
namespace: NAMESPACE.into(),
name: "other-pool".into(),
labels: None,
+ creation_timestamp: None,
},
..pool()
};
@@ -758,6 +760,7 @@ fn pool_named(namespace: &str) -> Pool {
namespace: namespace.into(),
name: namespace.into(),
labels: None,
+ creation_timestamp: None,
},
spec: pool_spec(),
status: None,
diff --git a/libs/fleet/sdk/tests/public_api.rs b/libs/fleet/sdk/tests/public_api.rs
index d2fe51a72b..867f0c26d4 100644
--- a/libs/fleet/sdk/tests/public_api.rs
+++ b/libs/fleet/sdk/tests/public_api.rs
@@ -70,6 +70,7 @@ fn pool() -> Pool {
namespace: "default".into(),
name: "pool".into(),
labels: None,
+ creation_timestamp: None,
},
spec: pool_spec(),
status: None,
@@ -84,6 +85,7 @@ fn claim() -> Claim {
namespace: "default".into(),
name: "claim".into(),
labels: None,
+ creation_timestamp: None,
},
spec: claim_spec(),
status: None,
@@ -198,12 +200,32 @@ fn http_request_distinguishes_absent_and_empty_bodies() {
assert_eq!(empty.body, Some(vec![]));
}
+#[test]
+fn resource_metadata_preserves_kubernetes_creation_timestamp() {
+ let metadata: ResourceMetadata = serde_json::from_value(serde_json::json!({
+ "namespace": "default",
+ "name": "claim-1",
+ "creationTimestamp": "2026-08-04T12:34:56Z"
+ }))
+ .unwrap();
+
+ assert_eq!(
+ metadata.creation_timestamp.as_deref(),
+ Some("2026-08-04T12:34:56Z")
+ );
+ assert_eq!(
+ serde_json::to_value(metadata).unwrap()["creationTimestamp"],
+ "2026-08-04T12:34:56Z"
+ );
+}
+
#[test]
fn resources_use_canonical_schema_specs_and_statuses() {
let metadata = ResourceMetadata {
namespace: "default".into(),
name: "example".into(),
labels: None,
+ creation_timestamp: None,
};
assert_eq!(metadata.namespace, "default");
diff --git a/libs/fleet/src/App.tsx b/libs/fleet/src/App.tsx
index 040dbfebd0..67f4da3c8b 100644
--- a/libs/fleet/src/App.tsx
+++ b/libs/fleet/src/App.tsx
@@ -10,9 +10,7 @@ import {
import AppLayout from "@cloudscape-design/components/app-layout"
import Button from "@cloudscape-design/components/button"
import SideNavigation from "@cloudscape-design/components/side-navigation"
-import TopNavigation, {
- type TopNavigationProps,
-} from "@cloudscape-design/components/top-navigation"
+import TopNavigation from "@cloudscape-design/components/top-navigation"
import Flashbar, {
type FlashbarProps,
} from "@cloudscape-design/components/flashbar"
@@ -21,14 +19,9 @@ import { PoolsList } from "./pages/PoolsList"
import { ClaimDetail } from "./pages/ClaimDetail"
import { PoolDetail } from "./pages/PoolDetail"
import { PoolNew } from "./pages/PoolNew"
-import { PoolReplicaDetail } from "./pages/PoolReplicaDetail"
-import { NodesList } from "./pages/NodesList"
-import { OperatorEvents } from "./pages/OperatorEvents"
-import { ApiKeys } from "./pages/ApiKeys"
import { UserApiKeys } from "./pages/UserApiKeys"
import { Settings } from "./pages/Settings"
import { FlashContext, type FlashMsg } from "./components/FlashContext"
-import { FeatureFlagProvider, useFeatureFlags } from "./components/FeatureFlagContext"
import { logout, userInfo } from "./auth/keycloak"
const VERSION_CHECK_INTERVAL_MS = 60_000
@@ -85,7 +78,6 @@ function Shell() {
const [flashes, setFlashes] = useState<FlashbarProps.MessageDefinition[]>([])
const { stale } = useStaleCheck()
const [staleDismissed, setStaleDismissed] = useState(false)
- const { admin } = useFeatureFlags()
const user = userInfo()
const pushFlash = useCallback((msg: FlashMsg) => {
const id = crypto.randomUUID()
@@ -120,28 +112,6 @@ function Shell() {
navigate("/pools")
},
},
- ...(admin
- ? ([
- {
- type: "button",
- text: "Nodes",
- href: "#/nodes",
- onClick: e => {
- e.preventDefault()
- navigate("/nodes")
- },
- },
- {
- type: "button",
- text: "Operator events",
- href: "#/operator-events",
- onClick: e => {
- e.preventDefault()
- navigate("/operator-events")
- },
- },
- ] satisfies TopNavigationProps.Utility[])
- : []),
{
type: "menu-dropdown",
text: user.name ?? user.email ?? "Account",
@@ -169,16 +139,6 @@ function Shell() {
}}
items={[
{ type: "link", text: "Pools", href: "#/pools" },
- ...(admin
- ? [
- { type: "link" as const, text: "Nodes", href: "#/nodes" },
- {
- type: "link" as const,
- text: "Operator events",
- href: "#/operator-events",
- },
- ]
- : []),
{ type: "link", text: "User API keys", href: "#/user-keys" },
{ type: "link", text: "Settings", href: "#/settings" },
]}
@@ -220,47 +180,31 @@ function Shell() {
export function App() {
return (
<BrowserRouter>
- <FeatureFlagProvider>
- <Routes>
- <Route element={<Shell />}>
- <Route index element={<Navigate to="/pools" replace />} />
- <Route path="/pools" element={<PoolsList />} />
- <Route path="/pools/new" element={<PoolNew />} />
- {/* Templates feature removed — keep old links working. */}
- <Route
- path="/pools/templates"
- element={<Navigate to="/pools" replace />}
- />
- <Route path="/pools/:namespace/:name" element={<PoolDetail />} />
- <Route path="/nodes" element={<NodesList />} />
- <Route path="/operator-events" element={<OperatorEvents />} />
- <Route
- path="/operator-logs"
- element={<Navigate to="/operator-events" replace />}
- />
- <Route path="/api-keys" element={<ApiKeys />} />
- <Route path="/user-keys" element={<UserApiKeys />} />
- <Route path="/settings" element={<Settings />} />
- <Route
- path="/pools/:namespace/:poolName/claims/:claimName"
- element={<ClaimDetail />}
- />
- <Route
- path="/pools/:namespace/:poolName/replicas/:vmName"
- element={<PoolReplicaDetail />}
- />
- {/* Back-compat for old bookmarks. */}
- <Route path="/modules" element={<Navigate to="/pools" replace />} />
- <Route
- path="/modules/new"
- element={<Navigate to="/pools/new" replace />}
- />
- <Route path="/modules/:name" element={<RedirectModule />} />
- {/* Back-compat: old /pools/:name URLs (no namespace) redirect to list. */}
- <Route path="/pools/:name" element={<Navigate to="/pools" replace />} />
- </Route>
- </Routes>
- </FeatureFlagProvider>
+ <Routes>
+ <Route element={<Shell />}>
+ <Route index element={<Navigate to="/pools" replace />} />
+ <Route path="/pools" element={<PoolsList />} />
+ <Route path="/pools/new" element={<PoolNew />} />
+ <Route
+ path="/pools/templates"
+ element={<Navigate to="/pools" replace />}
+ />
+ <Route path="/pools/:namespace/:name" element={<PoolDetail />} />
+ <Route path="/user-keys" element={<UserApiKeys />} />
+ <Route path="/settings" element={<Settings />} />
+ <Route
+ path="/pools/:namespace/:poolName/claims/:claimName"
+ element={<ClaimDetail />}
+ />
+ <Route path="/modules" element={<Navigate to="/pools" replace />} />
+ <Route
+ path="/modules/new"
+ element={<Navigate to="/pools/new" replace />}
+ />
+ <Route path="/modules/:name" element={<RedirectModule />} />
+ <Route path="/pools/:name" element={<Navigate to="/pools" replace />} />
+ </Route>
+ </Routes>
</BrowserRouter>
)
}
diff --git a/libs/fleet/src/api/client.ts b/libs/fleet/src/api/client.ts
deleted file mode 100644
index 7c1ea77409..0000000000
--- a/libs/fleet/src/api/client.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-// Singleton instance of the generated cyclops-cs-backend Api client.
-//
-// The generated client (src/api/generated/cyclops-cs-backend.ts) is
-// produced by `pnpm gen:api` from backend/docs/swagger.json. We don't
-// hand-edit it — instead we configure it here with a securityWorker
-// that pulls a fresh Keycloak access token before every authenticated
-// request, so all SPA → backend calls share one auth pipeline.
-//
-// `baseUrl` is "" so the generated `/api/...` paths resolve against the
-// SPA's own origin (nginx routes /api/{keys,gateway,k8s,orch,swagger}
-// to the backend sidecar).
-
-import { Api } from "./generated/cyclops-cs-backend"
-import { getToken } from "../auth/keycloak"
-
-export const apiClient = new Api({
- baseUrl: "",
- securityWorker: async () => {
- const token = await getToken()
- if (!token) return {}
- return { headers: { Authorization: `Bearer ${token}` } }
- },
-})
diff --git a/libs/fleet/src/api/cyclops.ts b/libs/fleet/src/api/cyclops.ts
deleted file mode 100644
index 57931392aa..0000000000
--- a/libs/fleet/src/api/cyclops.ts
+++ /dev/null
@@ -1,759 +0,0 @@
-// © 2024 CUA - gateway proxy
-// API client for the cyclops-cs SPA. All calls go through the
-// kubectl-proxy sidecar (/k8s-api/) or the nginx orch-api proxy
-// (/orch-api/).
-
-// ── K8s API types (only the bits we use) ────────────────────────────────
-
-export interface PodContainerStatus {
- name: string
- ready?: boolean
- restartCount?: number
- state?: {
- waiting?: { reason?: string; message?: string }
- running?: { startedAt?: string }
- terminated?: {
- exitCode?: number
- reason?: string
- message?: string
- startedAt?: string
- finishedAt?: string
- }
- }
-}
-
-export interface PodSummary {
- metadata: {
- name: string
- namespace: string
- labels?: Record<string, string>
- creationTimestamp?: string
- }
- spec?: {
- nodeName?: string
- containers?: { name: string }[]
- }
- status?: {
- phase?: string
- podIP?: string
- startTime?: string
- containerStatuses?: PodContainerStatus[]
- }
-}
-
-export interface PodList {
- items: PodSummary[]
-}
-
-export interface NodeSummary {
- metadata: {
- name: string
- labels?: Record<string, string>
- creationTimestamp?: string
- }
- status?: {
- capacity?: Record<string, string>
- allocatable?: Record<string, string>
- nodeInfo?: {
- kubeletVersion?: string
- osImage?: string
- architecture?: string
- }
- conditions?: { type: string; status: string }[]
- }
- spec?: {
- taints?: { key: string; effect: string }[]
- unschedulable?: boolean
- }
-}
-
-export interface NodeList {
- items: NodeSummary[]
-}
-
-// Pool VMs only schedule onto kubevirt worker nodes. Use this to scope any
-// node listing or capacity math to the nodes that can actually host pools.
-export const POOL_WORKER_NODE_PREFIX = "kubevirt-k3s-worker-"
-export function isPoolWorkerNode(n: NodeSummary): boolean {
- return n.metadata.name.startsWith(POOL_WORKER_NODE_PREFIX)
-}
-
-export interface PodMetricsContainer {
- name: string
- usage: { cpu: string; memory: string } // e.g. "159687357n", "1450060Ki"
-}
-
-export interface PodMetrics {
- metadata: {
- name: string
- namespace: string
- timestamp?: string
- window?: string
- }
- containers: PodMetricsContainer[]
-}
-
-// One row from the osgym orchestrator's `GET /pool` (osgym/main.py).
-export interface PoolVm {
- name: string
- // KubeVirt VM `printableStatus` — observed: "Running" | "Stopped" |
- // "Provisioning" | "Starting" | "Stopping" | "Terminating" | "Unknown".
- phase: string
- claimed_by: string | null
- available: boolean
-}
-
-export interface OrchestratorPoolStatus {
- count: number
- vms: PoolVm[]
-}
-
-// One row from osgym/observability.py's `GET /events`. Backed by a Redis
-// LIST capped at 2000 entries.
-export interface OrchestratorEvent {
- ts: number // unix seconds (float)
- method: string
- path: string
- status: number
- duration_ms: number
- vm_id: string | null
-}
-
-export interface OrchestratorEventsResponse {
- events: OrchestratorEvent[]
- pool: string
- key: string
-}
-
-// Prometheus HTTP API `/api/v1/query` response shape (only the bits we use).
-export interface PromQueryResult {
- metric: Record<string, string>
- value: [number, string] // [unix_secs, sample_value_as_string]
-}
-
-export interface PromQueryResponse {
- status: "success" | "error"
- data: { resultType: "vector" | "scalar" | "matrix" | "string"; result: PromQueryResult[] }
- errorType?: string
- error?: string
-}
-
-export interface KubernetesEvent {
- metadata: {
- name: string
- namespace: string
- uid?: string
- creationTimestamp?: string
- }
- involvedObject: {
- kind: string
- name: string
- namespace?: string
- }
- reason?: string
- message?: string
- type?: string // "Normal" | "Warning"
- count?: number
- firstTimestamp?: string
- lastTimestamp?: string
- eventTime?: string
- source?: { component?: string; host?: string }
- reportingComponent?: string
- reportingInstance?: string
-}
-
-export interface KubernetesEventList {
- items: KubernetesEvent[]
-}
-
-async function fetchJson<T>(url: string, init?: RequestInit): Promise<T> {
- // Inject Authorization: Bearer ${kc.token} for backend-mediated paths
- // (everything served by the cyclops-cs sidecar).
- const authHeader: Record<string, string> = {}
- if (
- url.startsWith("/api/keys") ||
- url.startsWith("/api/user-keys") ||
- url.startsWith("/api/gateway") ||
- url.startsWith("/api/k8s") ||
- url.startsWith("/api/orch") ||
- url.startsWith("/api/namespaces")
- ) {
- const { getToken } = await import("../auth/keycloak")
- const token = await getToken()
- if (token) authHeader.Authorization = `Bearer ${token}`
- }
- const res = await fetch(url, {
- ...init,
- headers: {
- "Content-Type": "application/json",
- ...authHeader,
- ...(init?.headers ?? {}),
- },
- })
- if (!res.ok) {
- const body = await res.text().catch(() => "")
- throw new Error(`${res.status} ${res.statusText}${body ? `: ${body}` : ""}`)
- }
- // Some endpoints return empty bodies on success.
- const text = await res.text()
- return text ? (JSON.parse(text) as T) : (undefined as T)
-}
-
-// `/api/orch/<ns>/<svc>/<path>` → osgym orchestrator, via the cyclops-cs
-// backend sidecar (Keycloak SSO + OPA). Replaces the older /orch-api/
-// nginx block; fetchJson injects Authorization: Bearer ${kc.token}.
-const httpOrch = <T>(
- namespace: string,
- service: string,
- path: string,
- init?: RequestInit,
-) =>
- fetchJson<T>(
- `/api/orch/${encodeURIComponent(namespace)}/` +
- `${encodeURIComponent(service)}/${path.replace(/^\//, "")}`,
- init,
- )
-
-// `/api/k8s/<path>` → kubectl-proxy sidecar via the cyclops-cs backend
-// (Keycloak SSO + OPA). Replaces /k8s-api/. Used for arbitrary K8s API
-// reads — pod listing by label, PodMetrics, etc. The cyclops-cs
-// ClusterRole on the pod's ServiceAccount limits what's reachable.
-const httpK8s = <T>(path: string, init?: RequestInit) =>
- fetchJson<T>(`/api/k8s/${path.replace(/^\//, "")}`, init)
-
-export const api = {
- // Pool CRUD via K8s API (kubectl-proxy sidecar with impersonation).
- // The proxy adds Impersonate-User/Group headers so Capsule enforces
- // tenant RBAC — users can only operate in their own namespaces.
- // The pool-operator watches OSGymWorkspacePool CRs and creates all
- // resources (orchestrator, RBAC, namespace, etc.) automatically.
- createPool: async (name: string, values: {
- cpu: number; ram: string; ociImage: string; replicas: number;
- firmware?: "bios" | "efi";
- // runtime=macos provisions macOS sandboxes (ADMIN-ONLY; the backend
- // rejects macos pool writes from non-admins). Omitted/kubevirt = a VM pool.
- runtime?: "kubevirt" | "macos" | "gvisor";
- services?: { name: string; targetPort: number; protocol: string }[];
- probes?: { readinessProbe?: Record<string, unknown>; livenessProbe?: Record<string, unknown> };
- autoscaling?: PoolAutoscalingConfig;
- }) => {
- // Pool name = namespace name (1:1 mapping).
- // Auto-create the namespace before creating the pool. Tolerate "already
- // exists": the namespace can be left over from a previous attempt that
- // failed at the pool step (e.g. an adoption race), and create-or-reuse
- // makes pool creation retryable under the same name.
- const namespace = name
- try {
- await namespacesApi.create(namespace)
- } catch (e) {
- if (!String((e as Error).message).startsWith("409")) throw e
- }
- return httpK8s<void>(
- `apis/cua.ai/v1/namespaces/${encodeURIComponent(namespace)}/osgymworkspacepools`,
- {
- method: "POST",
- body: JSON.stringify({
- apiVersion: "cua.ai/v1",
- kind: "OSGymWorkspacePool",
- metadata: { name, labels: { "cua.ai/pool": name } },
- spec: {
- replicas: values.replicas,
- template: {
- // A pod runtime (macos / gvisor) flows verbatim through the compat
- // shim into the OSGymSandboxTemplate vmTemplate, where the operator's
- // pod_backend dispatches on runtime and applies that runtime's
- // placement defaults (RuntimeClass, nodeSelector, tolerations).
- ...(values.runtime && values.runtime !== "kubevirt"
- ? { runtime: values.runtime }
- : {}),
- containerDiskImage: values.ociImage,
- imagePullSecret: "ecr-credentials",
- cpuCores: values.cpu,
- memory: values.ram,
- ...(values.firmware && values.firmware !== "bios" ? { firmware: values.firmware } : {}),
- ...(values.probes ? { probes: values.probes } : {}),
- },
- ...(values.services?.length ? { services: values.services } : {}),
- ...(values.autoscaling ? { autoscaling: values.autoscaling } : {}),
- },
- }),
- },
- )
- },
-
- updatePoolServices: (namespace: string, name: string, services: { name: string; targetPort: number; protocol: string }[]) =>
- httpK8s<void>(
- `apis/cua.ai/v1/namespaces/${encodeURIComponent(namespace)}/osgymworkspacepools/${encodeURIComponent(name)}`,
- {
- method: "PATCH",
- headers: { "Content-Type": "application/merge-patch+json" },
- body: JSON.stringify({ spec: { services } }),
- },
- ),
-
- deletePool: (namespace: string, name: string) =>
- httpK8s<void>(
- `apis/cua.ai/v1/namespaces/${encodeURIComponent(namespace)}/osgymworkspacepools/${encodeURIComponent(name)}`,
- { method: "DELETE" },
- ),
-
- getPool: async (namespace: string, name: string): Promise<{
- name: string
- namespace: string
- replicas: number
- cpu: number
- ram: string
- ociImage: string
- firmware?: "bios" | "efi"
- services: { name: string; targetPort: number; protocol: string }[]
- probes?: { readinessProbe?: Record<string, unknown>; livenessProbe?: Record<string, unknown> }
- phase: string
- totalCount: number
- availableCount: number
- claimedCount: number
- }> => {
- const pool = await httpK8s<{
- metadata: { name: string; namespace: string }
- spec: {
- replicas: number
- template: { containerDiskImage: string; cpuCores: number; memory: string; firmware?: string; probes?: Record<string, unknown> }
- services?: { name: string; targetPort: number; protocol?: string }[]
- }
- status?: {
- phase?: string
- totalCount?: number
- availableCount?: number
- claimedCount?: number
- }
- }>(`apis/cua.ai/v1/namespaces/${encodeURIComponent(namespace)}/osgymworkspacepools/${encodeURIComponent(name)}`)
- return {
- name: pool.metadata.name,
- namespace: pool.metadata.namespace,
- replicas: pool.spec.replicas,
- cpu: pool.spec.template.cpuCores,
- ram: pool.spec.template.memory,
- ociImage: pool.spec.template.containerDiskImage,
- firmware: pool.spec.template.firmware as "bios" | "efi" | undefined,
- services: (pool.spec.services ?? []).map(s => ({
- name: s.name,
- targetPort: s.targetPort,
- protocol: s.protocol ?? "TCP",
- })),
- probes: pool.spec.template.probes as { readinessProbe?: Record<string, unknown>; livenessProbe?: Record<string, unknown> } | undefined,
- phase: pool.status?.phase ?? "Unknown",
- totalCount: pool.status?.totalCount ?? 0,
- availableCount: pool.status?.availableCount ?? 0,
- claimedCount: pool.status?.claimedCount ?? 0,
- }
- },
-
- listPools: async (): Promise<{
- name: string
- namespace: string
- replicas: number
- phase: string
- availableCount: number
- }[]> => {
- // Capsule restricts users to their own namespaces — cluster-wide list
- // is forbidden. Instead, fetch the user's namespaces and list pools
- // in each one.
- const namespaces = await namespacesApi.list()
- const pools: {
- name: string
- namespace: string
- replicas: number
- phase: string
- availableCount: number
- }[] = []
- await Promise.all(
- namespaces.map(async (ns) => {
- try {
- const list = await httpK8s<{
- items: {
- metadata: { name: string; namespace: string }
- spec: { replicas: number }
- status?: { phase?: string; availableCount?: number }
- }[]
- }>(`apis/cua.ai/v1/namespaces/${encodeURIComponent(ns.name)}/osgymworkspacepools`)
- for (const p of list.items) {
- pools.push({
- name: p.metadata.name,
- namespace: p.metadata.namespace,
- replicas: p.spec.replicas,
- phase: p.status?.phase ?? "Unknown",
- availableCount: p.status?.availableCount ?? 0,
- })
- }
- } catch {
- // Namespace may not have pool CRD access — skip
- }
- }),
- )
- return pools.sort((a, b) => a.name.localeCompare(b.name))
- },
-
- // Per-pool orchestrator (osgym FastAPI inside the pool's namespace).
- listPoolVms: (namespace: string, poolName: string) =>
- httpOrch<OrchestratorPoolStatus>(
- namespace,
- `${poolName}-orchestrator`,
- "/pool",
- ),
-
- listOrchestratorEvents: (
- namespace: string,
- poolName: string,
- limit = 200,
- ) =>
- httpOrch<OrchestratorEventsResponse>(
- namespace,
- `${poolName}-orchestrator`,
- `/events?limit=${limit}`,
- ),
-
- // Shared Prom in cyclops-cs ns; Service listens on port 80 → 9090, so
- // the existing /orch-api/<ns>/<svc>/<path> proxy hits it unchanged.
- queryProm: (promql: string) =>
- httpOrch<PromQueryResponse>(
- "cyclops-cs",
- "prometheus",
- `/api/v1/query?query=${encodeURIComponent(promql)}`,
- ),
-
- // K8s direct (via kubectl-proxy sidecar). The replica detail page uses
- // these to find the virt-launcher pod for a given VM and read its metrics.
- findLauncherPod: async (
- namespace: string,
- vmName: string,
- ): Promise<PodSummary | null> => {
- const list = await httpK8s<PodList>(
- `api/v1/namespaces/${encodeURIComponent(namespace)}/pods` +
- `?labelSelector=${encodeURIComponent(`vm.kubevirt.io/name=${vmName}`)}` +
- "&limit=1",
- )
- return list.items[0] ?? null
- },
-
- // Locate the orchestrator (osgym) pod for a pool. The orchestrator
- // Deployment sets `app=<poolName>-orchestrator` (see
- // charts/osgym-workspace-test/templates/orchestrator-deploy.yaml).
- findPoolOrchestratorPod: async (
- namespace: string,
- poolName: string,
- ): Promise<PodSummary | null> => {
- const list = await httpK8s<PodList>(
- `api/v1/namespaces/${encodeURIComponent(namespace)}/pods` +
- `?labelSelector=${encodeURIComponent(`app=${poolName}-orchestrator`)}` +
- "&limit=1",
- )
- return list.items[0] ?? null
- },
-
- // Locate the centralized pool-operator pod. Deployed cluster-wide in the
- // `osgym` namespace with label `app=osgym-pool-operator` (see
- // clusters/kopf-k3s/osgym/pool-operator.yaml).
- findPoolOperatorPod: async (): Promise<PodSummary | null> => {
- const list = await httpK8s<PodList>(
- "api/v1/namespaces/osgym/pods" +
- `?labelSelector=${encodeURIComponent("app=osgym-pool-operator")}` +
- "&limit=1",
- )
- return list.items[0] ?? null
- },
-
- listNodes: () => httpK8s<NodeList>("api/v1/nodes"),
-
- // Cluster-wide list of KubeVirt launcher pods (one per VM replica).
- // Filters by the `vm.kubevirt.io/name` label so we only return virt-launcher
- // pods, not the orchestrator or other workloads.
- listVmPods: () =>
- httpK8s<PodList>(
- `api/v1/pods?labelSelector=${encodeURIComponent("vm.kubevirt.io/name")}`,
- ),
-
- getPodMetrics: (namespace: string, podName: string) =>
- httpK8s<PodMetrics>(
- "apis/metrics.k8s.io/v1beta1/namespaces/" +
- `${encodeURIComponent(namespace)}/pods/${encodeURIComponent(podName)}`,
- ),
-
- // K8s events for OSGymWorkspacePool resources — what the pool-operator
- // emits via kopf for handler outcomes (Normal/Warning, reason, message).
- // Cluster-wide; filtered server-side by involvedObject.kind.
- listOperatorEvents: () =>
- httpK8s<KubernetesEventList>(
- `api/v1/events?fieldSelector=${encodeURIComponent("involvedObject.kind=OSGymWorkspacePool")}&limit=500`,
- ),
-
- // Stream pod logs via K8s API (follow mode). Returns the URL for
- // fetch() with ReadableStream — the caller reads lines incrementally.
- // Routed through the cyclops-cs backend sidecar (Keycloak SSO + OPA),
- // which proxies to the kubectl-proxy sidecar.
- podLogsUrl: (namespace: string, podName: string, container: string) =>
- `/api/k8s/api/v1/namespaces/${encodeURIComponent(namespace)}/pods/` +
- `${encodeURIComponent(podName)}/log?container=${encodeURIComponent(container)}` +
- "&follow=true&tailLines=200",
-
- // Restart a KubeVirt VM replica via the subresources API.
- // This is equivalent to `virtctl restart <vm>` — the VMI is
- // terminated and a new one is started from the same VM spec.
- // Requires the subresources.kubevirt.io/virtualmachines/restart ClusterRole
- // rule added in clusters/kopf-k3s/cyclops-cs/rbac.yaml.
- restartVm: (namespace: string, vmName: string) =>
- httpK8s<void>(
- `apis/subresources.kubevirt.io/v1/namespaces/` +
- `${encodeURIComponent(namespace)}/virtualmachines/` +
- `${encodeURIComponent(vmName)}/restart`,
- { method: "PUT", body: JSON.stringify({}) },
- ),
-
- // Rollout-restart the pool's orchestrator Deployment.
- // Equivalent to `kubectl rollout restart deployment/<poolName>-orchestrator`.
- // Patches spec.template.metadata.annotations with a restartedAt timestamp
- // so K8s triggers a new rollout without changing the Deployment spec.
- // Requires apps/deployments patch permission in the ClusterRole.
- restartOrchestrator: (namespace: string, poolName: string) =>
- httpK8s<void>(
- `apis/apps/v1/namespaces/${encodeURIComponent(namespace)}/` +
- `deployments/${encodeURIComponent(`${poolName}-orchestrator`)}`,
- {
- method: "PATCH",
- headers: { "Content-Type": "application/strategic-merge-patch+json" },
- body: JSON.stringify({
- spec: {
- template: {
- metadata: {
- annotations: {
- "kubectl.kubernetes.io/restartedAt": new Date().toISOString(),
- },
- },
- },
- },
- }),
- },
- ),
-}
-
-// ── Namespace types ────────────────────────────────────────────────────
-
-export interface Namespace {
- name: string
- status: string
- createdAt: string
- labels: Record<string, string> | null
-}
-
-// `/api/namespaces` — Capsule-backed per-user namespace CRUD.
-const httpNamespaces = <T>(path: string, init?: RequestInit) =>
- fetchJson<T>(`/api/namespaces${path}`, init)
-
-export const namespacesApi = {
- list: () => httpNamespaces<Namespace[]>(""),
-
- create: (name: string) =>
- httpNamespaces<Namespace>("", {
- method: "POST",
- body: JSON.stringify({ name }),
- }),
-
- remove: (name: string) =>
- httpNamespaces<void>(`/${encodeURIComponent(name)}`, {
- method: "DELETE",
- }),
-}
-
-// ── Pool config shape ──────────────────────────────────────────────────
-//
-// The object the SPA passes to api.createPool.
-
-// Optional autoscaling extension. Threaded verbatim onto the pool's
-// generated OSGymSandboxWarmPool.spec.autoscaling by the compat shim,
-// opting the pool into KEDA autoscaling on claim demand.
-export interface PoolAutoscalingConfig {
- minPoolSize?: number
- initialPoolSize?: number
- maxPoolSize?: number
-}
-
-export interface PoolTemplateConfig {
- cpu: number
- ram: string
- ociImage: string
- replicas: number
- // VM firmware: "efi" for GPT/UEFI-only images (e.g. the Windows
- // desktop-workspace); omitted/"bios" boots KubeVirt's legacy-BIOS default.
- firmware?: "bios" | "efi"
- // runtime=macos provisions macOS sandboxes (admin-only). Omitted =
- // a KubeVirt VM pool (the default for all customer pools).
- runtime?: "kubevirt" | "macos" | "gvisor"
- services?: { name: string; targetPort: number; protocol: string }[]
- probes?: {
- readinessProbe?: Record<string, unknown>
- livenessProbe?: Record<string, unknown>
- }
- autoscaling?: PoolAutoscalingConfig
-}
-
-// ── User API keys ─────────────────────────────────────────────────────
-
-export interface UserApiKey {
- id: string
- client_id: string
- name: string
- scope: string[]
-}
-
-export interface NewUserApiKey {
- client_id: string
- client_secret: string
- token_url: string
- name: string
- scope: string[]
-}
-
-export const userKeysApi = {
- list: async (): Promise<UserApiKey[]> => {
- const res = await fetchJson<{ keys: UserApiKey[] }>("/api/user-keys")
- return res.keys ?? []
- },
-
- create: async (name: string, scope?: string[]): Promise<NewUserApiKey> => {
- return fetchJson<NewUserApiKey>("/api/user-keys", {
- method: "POST",
- body: JSON.stringify({ name, scope: scope ?? [] }),
- })
- },
-
- remove: async (id: string): Promise<void> => {
- await fetchJson<void>(`/api/user-keys/${encodeURIComponent(id)}`, {
- method: "DELETE",
- })
- },
-}
-
-// ── OSGymSandboxClaim (osgym.cua.ai/v1alpha1) ────────────────────────
-
-export interface Claim {
- name: string
- namespace: string
- templateRef: string
- warmpool: string
- phase: string
- sandboxName?: string
- sandboxService?: string
- createdAt: string
-}
-
-function parseClaim(raw: any): Claim {
- const meta = raw.metadata || {}
- const spec = raw.spec || {}
- const status = raw.status || {}
- return {
- name: meta.name ?? "",
- namespace: meta.namespace ?? "",
- templateRef: (spec.sandboxTemplateRef || {}).name ?? "",
- warmpool: spec.warmpool ?? "default",
- phase: status.phase ?? "Pending",
- sandboxName: (status.sandbox || {}).name,
- sandboxService: (status.sandbox || {}).service,
- createdAt: meta.creationTimestamp ?? "",
- }
-}
-
-const CLAIM_GROUP = "osgym.cua.ai"
-const CLAIM_VERSION = "v1alpha1"
-const CLAIM_PLURAL = "osgymsandboxclaims"
-
-export const claimsApi = {
- list: async (namespace: string): Promise<Claim[]> => {
- const data = await httpK8s<{ items: any[] }>(
- `apis/${CLAIM_GROUP}/${CLAIM_VERSION}/namespaces/${encodeURIComponent(namespace)}/${CLAIM_PLURAL}`,
- )
- return (data.items || []).map(parseClaim)
- },
-
- create: async (
- namespace: string,
- name: string,
- templateRef: string,
- ): Promise<Claim> => {
- const raw = await httpK8s<any>(
- `apis/${CLAIM_GROUP}/${CLAIM_VERSION}/namespaces/${encodeURIComponent(namespace)}/${CLAIM_PLURAL}`,
- {
- method: "POST",
- body: JSON.stringify({
- apiVersion: `${CLAIM_GROUP}/${CLAIM_VERSION}`,
- kind: "OSGymSandboxClaim",
- metadata: { name },
- spec: {
- sandboxTemplateRef: { name: templateRef },
- },
- }),
- },
- )
- return parseClaim(raw)
- },
-
- get: async (namespace: string, name: string): Promise<Claim> => {
- const raw = await httpK8s<any>(
- `apis/${CLAIM_GROUP}/${CLAIM_VERSION}/namespaces/${encodeURIComponent(namespace)}/${CLAIM_PLURAL}/${encodeURIComponent(name)}`,
- )
- return parseClaim(raw)
- },
-
- remove: async (namespace: string, name: string): Promise<void> => {
- await httpK8s<void>(
- `apis/${CLAIM_GROUP}/${CLAIM_VERSION}/namespaces/${encodeURIComponent(namespace)}/${CLAIM_PLURAL}/${encodeURIComponent(name)}`,
- { method: "DELETE" },
- )
- },
-}
-
-// ── Unit parsing ────────────────────────────────────────────────────────
-//
-// metrics-server returns CPU as `<n>n` (nanocores) and memory as
-// `<n>Ki|Mi|Gi` (binary suffix). Helpers convert to floats.
-
-const MEM_SUFFIX: Record<string, number> = {
- "": 1,
- Ki: 1024,
- Mi: 1024 ** 2,
- Gi: 1024 ** 3,
- Ti: 1024 ** 4,
- // Decimal suffixes (rare) — handled defensively.
- K: 1000,
- M: 1000 ** 2,
- G: 1000 ** 3,
- T: 1000 ** 4,
-}
-
-export function parseCpuCores(v: string): number {
- // Forms seen: "159687357n", "0.250", "100m"
- if (!v) return 0
- if (v.endsWith("n")) return parseInt(v.slice(0, -1), 10) / 1e9
- if (v.endsWith("u")) return parseInt(v.slice(0, -1), 10) / 1e6
- if (v.endsWith("m")) return parseInt(v.slice(0, -1), 10) / 1000
- return parseFloat(v)
-}
-
-export function parseMemoryBytes(v: string): number {
- if (!v) return 0
- const m = v.match(/^(\d+(?:\.\d+)?)([KMGTP]i?)?$/)
- if (!m) return parseFloat(v) || 0
- const mult = MEM_SUFFIX[m[2] ?? ""] ?? 1
- return parseFloat(m[1]) * mult
-}
-
-export function sumPodUsage(metrics: PodMetrics): {
- cpuCores: number
- memBytes: number
-} {
- let cpu = 0
- let mem = 0
- for (const c of metrics.containers ?? []) {
- cpu += parseCpuCores(c.usage?.cpu ?? "0")
- mem += parseMemoryBytes(c.usage?.memory ?? "0")
- }
- return { cpuCores: cpu, memBytes: mem }
-}
-
diff --git a/libs/fleet/src/api/featureFlags.ts b/libs/fleet/src/api/featureFlags.ts
deleted file mode 100644
index 77a32d0049..0000000000
--- a/libs/fleet/src/api/featureFlags.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-// Feature flags client — fetches /api/config to get per-user flags.
-// The backend derives admin status from the OpenFeature flag
-// `/feature-flags/cyclops-cs/admin-subs` (AWS SSM Parameter Store in prod,
-// or the CYCLOPS_CS_ADMIN_SUBS env var in dev) — a JSON array of Keycloak
-// sub UUIDs. Access to infra-only resources is also enforced server-side by
-// the backend's OPA policy, not just by hiding nav here.
-
-import { getToken } from "../auth/keycloak"
-
-export interface FeatureFlags {
- /** Admin users see the full infra UI: Nodes and Operator events. */
- admin: boolean
-}
-
-const DEFAULT_FLAGS: FeatureFlags = {
- admin: false,
-}
-
-let _cache: FeatureFlags | null = null
-let _fetchPromise: Promise<FeatureFlags> | null = null
-
-export async function fetchFeatureFlags(): Promise<FeatureFlags> {
- if (_cache) return _cache
- if (_fetchPromise) return _fetchPromise
-
- _fetchPromise = (async () => {
- try {
- const token = await getToken()
- const res = await fetch("/api/config", {
- headers: {
- Authorization: token ? `Bearer ${token}` : "",
- "Content-Type": "application/json",
- },
- })
- if (!res.ok) return DEFAULT_FLAGS
- const data = (await res.json()) as FeatureFlags
- _cache = {
- admin: data.admin ?? false,
- }
- return _cache
- } catch {
- return DEFAULT_FLAGS
- } finally {
- _fetchPromise = null
- }
- })()
-
- return _fetchPromise
-}
-
-/** Invalidate the cache (e.g., after login). */
-export function invalidateFeatureFlags(): void {
- _cache = null
-}
diff --git a/libs/fleet/src/api/generated/cyclops-cs-backend.ts b/libs/fleet/src/api/generated/cyclops-cs-backend.ts
deleted file mode 100644
index 7ca6ee79e9..0000000000
--- a/libs/fleet/src/api/generated/cyclops-cs-backend.ts
+++ /dev/null
@@ -1,915 +0,0 @@
-/* eslint-disable */
-/* tslint:disable */
-// @ts-nocheck
-/*
- * ---------------------------------------------------------------
- * ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ##
- * ## ##
- * ## AUTHOR: acacode ##
- * ## SOURCE: https://github.com/acacode/swagger-typescript-api ##
- * ---------------------------------------------------------------
- */
-
-export interface HandlersConfigResponse {
- /**
- * Admin is true when the caller is in input.flags.admin_subs (OPA-evaluated).
- * Non-admins get the customer view: infra-only nav (Nodes, Operator events)
- * is hidden in the SPA and the corresponding kubectl-proxy paths are denied
- * server-side by authz.rego.
- */
- admin?: boolean;
-}
-
-export interface HandlersCreateKeyRequest {
- /** @example "ci-prod" */
- name?: string;
- /** @example "test-pool" */
- namespace?: string;
-}
-
-export interface HandlersCreateKeyResponse {
- client_id?: string;
- client_secret?: string;
- name?: string;
- namespace?: string;
- token_url?: string;
-}
-
-export interface HandlersCreateNamespaceRequest {
- /** @example "my-workspace" */
- name?: string;
-}
-
-export interface HandlersCreateUserKeyRequest {
- /** @example "my-ci-key" */
- name?: string;
- /** @example ["[\"ns1\"","\"ns2\"]"] */
- scope?: string[];
-}
-
-export interface HandlersCreateUserKeyResponse {
- client_id?: string;
- client_secret?: string;
- name?: string;
- scope?: string[];
- token_url?: string;
-}
-
-export interface HandlersErrorResponse {
- error?: string;
-}
-
-export interface HandlersHealthResponse {
- ok?: boolean;
-}
-
-export interface HandlersListKeysResponse {
- keys?: KeycloakKeyClient[];
-}
-
-export interface HandlersListUserKeysResponse {
- keys?: HandlersUserKeyResponse[];
-}
-
-export interface HandlersNamespaceResponse {
- createdAt?: string;
- labels?: Record<string, string>;
- name?: string;
- status?: string;
-}
-
-export interface HandlersUserKeyResponse {
- client_id?: string;
- id?: string;
- name?: string;
- scope?: string[];
-}
-
-export interface KeycloakKeyClient {
- client_id?: string;
- id?: string;
- name?: string;
- namespace?: string;
- owner_sub?: string;
-}
-
-export type BatchLanesCreateError = Record<string, string>;
-
-export type BatchLanesDeleteError = Record<string, string>;
-
-export type BatchSubmitCreateError = Record<string, string>;
-
-export type BatchDeleteError = Record<string, string>;
-
-export type BatchResultsListError = Record<string, string>;
-
-export type BatchStatusListError = Record<string, string>;
-
-export type ConfigListData = HandlersConfigResponse;
-
-export type ConfigListError = HandlersErrorResponse;
-
-export type GatewayDetailError = HandlersErrorResponse;
-
-export type GetK8SData = string;
-
-export type GetK8SError = HandlersErrorResponse;
-
-export type KeysListData = HandlersListKeysResponse;
-
-export type KeysListError = HandlersErrorResponse;
-
-export type KeysCreateData = HandlersCreateKeyResponse;
-
-export type KeysCreateError = HandlersErrorResponse;
-
-export type KeysDeleteData = any;
-
-export type KeysDeleteError = HandlersErrorResponse;
-
-export type LabelDeleteError = Record<string, string>;
-
-export type LabelBatchCreateError = Record<string, string>;
-
-export type LabelResultsListError = Record<string, string>;
-
-export type LabelStatusListError = Record<string, string>;
-
-export type NamespacesListData = HandlersNamespaceResponse[];
-
-export type NamespacesListError = HandlersErrorResponse;
-
-export type NamespacesCreateData = HandlersNamespaceResponse;
-
-export type NamespacesCreateError = HandlersErrorResponse;
-
-export type NamespacesDeleteData = any;
-
-export type NamespacesDeleteError = HandlersErrorResponse;
-
-export type OrchDetailData = string;
-
-export type OrchDetailError = HandlersErrorResponse;
-
-export type GetSvcData = string;
-
-export type GetSvcError = HandlersErrorResponse;
-
-export type UserKeysListData = HandlersListUserKeysResponse;
-
-export type UserKeysListError = HandlersErrorResponse;
-
-export type UserKeysCreateData = HandlersCreateUserKeyResponse;
-
-export type UserKeysCreateError = HandlersErrorResponse;
-
-export type UserKeysDeleteData = any;
-
-export type UserKeysDeleteError = HandlersErrorResponse;
-
-export type HealthzListData = HandlersHealthResponse;
-
-export type QueryParamsType = Record<string | number, any>;
-export type ResponseFormat = keyof Omit<Body, "body" | "bodyUsed">;
-
-export interface FullRequestParams extends Omit<RequestInit, "body"> {
- /** set parameter to `true` for call `securityWorker` for this request */
- secure?: boolean;
- /** request path */
- path: string;
- /** content type of request body */
- type?: ContentType;
- /** query params */
- query?: QueryParamsType;
- /** format of response (i.e. response.json() -> format: "json") */
- format?: ResponseFormat;
- /** request body */
- body?: unknown;
- /** base url */
- baseUrl?: string;
- /** request cancellation token */
- cancelToken?: CancelToken;
-}
-
-export type RequestParams = Omit<
- FullRequestParams,
- "body" | "method" | "query" | "path"
->;
-
-export interface ApiConfig<SecurityDataType = unknown> {
- baseUrl?: string;
- baseApiParams?: Omit<RequestParams, "baseUrl" | "cancelToken" | "signal">;
- securityWorker?: (
- securityData: SecurityDataType | null,
- ) => Promise<RequestParams | void> | RequestParams | void;
- customFetch?: typeof fetch;
-}
-
-export interface HttpResponse<D extends unknown, E extends unknown = unknown>
- extends Response {
- data: D;
- error: E;
-}
-
-type CancelToken = Symbol | string | number;
-
-export enum ContentType {
- Json = "application/json",
- JsonApi = "application/vnd.api+json",
- FormData = "multipart/form-data",
- UrlEncoded = "application/x-www-form-urlencoded",
- Text = "text/plain",
-}
-
-export class HttpClient<SecurityDataType = unknown> {
- public baseUrl: string = "/";
- private securityData: SecurityDataType | null = null;
- private securityWorker?: ApiConfig<SecurityDataType>["securityWorker"];
- private abortControllers = new Map<CancelToken, AbortController>();
- private customFetch = (...fetchParams: Parameters<typeof fetch>) =>
- fetch(...fetchParams);
-
- private baseApiParams: RequestParams = {
- credentials: "same-origin",
- headers: {},
- redirect: "follow",
- referrerPolicy: "no-referrer",
- };
-
- constructor(apiConfig: ApiConfig<SecurityDataType> = {}) {
- Object.assign(this, apiConfig);
- }
-
- public setSecurityData = (data: SecurityDataType | null) => {
- this.securityData = data;
- };
-
- protected encodeQueryParam(key: string, value: any) {
- const encodedKey = encodeURIComponent(key);
- return `${encodedKey}=${encodeURIComponent(typeof value === "number" ? value : `${value}`)}`;
- }
-
- protected addQueryParam(query: QueryParamsType, key: string) {
- return this.encodeQueryParam(key, query[key]);
- }
-
- protected addArrayQueryParam(query: QueryParamsType, key: string) {
- const value = query[key];
- return value.map((v: any) => this.encodeQueryParam(key, v)).join("&");
- }
-
- protected toQueryString(rawQuery?: QueryParamsType): string {
- const query = rawQuery || {};
- const keys = Object.keys(query).filter(
- (key) => "undefined" !== typeof query[key],
- );
- return keys
- .map((key) =>
- Array.isArray(query[key])
- ? this.addArrayQueryParam(query, key)
- : this.addQueryParam(query, key),
- )
- .join("&");
- }
-
- protected addQueryParams(rawQuery?: QueryParamsType): string {
- const queryString = this.toQueryString(rawQuery);
- return queryString ? `?${queryString}` : "";
- }
-
- private contentFormatters: Record<ContentType, (input: any) => any> = {
- [ContentType.Json]: (input: any) =>
- input !== null && (typeof input === "object" || typeof input === "string")
- ? JSON.stringify(input)
- : input,
- [ContentType.JsonApi]: (input: any) =>
- input !== null && (typeof input === "object" || typeof input === "string")
- ? JSON.stringify(input)
- : input,
- [ContentType.Text]: (input: any) =>
- input !== null && typeof input !== "string"
- ? JSON.stringify(input)
- : input,
- [ContentType.FormData]: (input: any) =>
- Object.keys(input || {}).reduce((formData, key) => {
- const property = input[key];
- formData.append(
- key,
- property instanceof Blob
- ? property
- : typeof property === "object" && property !== null
- ? JSON.stringify(property)
- : `${property}`,
- );
- return formData;
- }, new FormData()),
- [ContentType.UrlEncoded]: (input: any) => this.toQueryString(input),
- };
-
- protected mergeRequestParams(
- params1: RequestParams,
- params2?: RequestParams,
- ): RequestParams {
- return {
- ...this.baseApiParams,
- ...params1,
- ...(params2 || {}),
- headers: {
- ...(this.baseApiParams.headers || {}),
- ...(params1.headers || {}),
- ...((params2 && params2.headers) || {}),
- },
- };
- }
-
- protected createAbortSignal = (
- cancelToken: CancelToken,
- ): AbortSignal | undefined => {
- if (this.abortControllers.has(cancelToken)) {
- const abortController = this.abortControllers.get(cancelToken);
- if (abortController) {
- return abortController.signal;
- }
- return void 0;
- }
-
- const abortController = new AbortController();
- this.abortControllers.set(cancelToken, abortController);
- return abortController.signal;
- };
-
- public abortRequest = (cancelToken: CancelToken) => {
- const abortController = this.abortControllers.get(cancelToken);
-
- if (abortController) {
- abortController.abort();
- this.abortControllers.delete(cancelToken);
- }
- };
-
- public request = async <T = any, E = any>({
- body,
- secure,
- path,
- type,
- query,
- format,
- baseUrl,
- cancelToken,
- ...params
- }: FullRequestParams): Promise<HttpResponse<T, E>> => {
- const secureParams =
- ((typeof secure === "boolean" ? secure : this.baseApiParams.secure) &&
- this.securityWorker &&
- (await this.securityWorker(this.securityData))) ||
- {};
- const requestParams = this.mergeRequestParams(params, secureParams);
- const queryString = query && this.toQueryString(query);
- const payloadFormatter = this.contentFormatters[type || ContentType.Json];
- const responseFormat = format || requestParams.format;
-
- return this.customFetch(
- `${baseUrl || this.baseUrl || ""}${path}${queryString ? `?${queryString}` : ""}`,
- {
- ...requestParams,
- headers: {
- ...(requestParams.headers || {}),
- ...(type && type !== ContentType.FormData
- ? { "Content-Type": type }
- : {}),
- },
- signal:
- (cancelToken
- ? this.createAbortSignal(cancelToken)
- : requestParams.signal) || null,
- body:
- typeof body === "undefined" || body === null
- ? null
- : payloadFormatter(body),
- },
- ).then(async (response) => {
- const r = response.clone() as HttpResponse<T, E>;
- r.data = null as unknown as T;
- r.error = null as unknown as E;
-
- const data = !responseFormat
- ? r
- : await response[responseFormat]()
- .then((data) => {
- if (r.ok) {
- r.data = data;
- } else {
- r.error = data;
- }
- return r;
- })
- .catch((e) => {
- r.error = e;
- return r;
- });
-
- if (cancelToken) {
- this.abortControllers.delete(cancelToken);
- }
-
- if (!response.ok) throw data;
- return data;
- });
- };
-}
-
-/**
- * @title Cyclops CS Backend API
- * @version 0.1
- * @baseUrl /
- * @contact
- *
- * Backend sidecar for the cyclops-cs SPA — Keycloak-authenticated key management, service proxies (k8s / orch / svc), namespace management, and deprecated gateway / batch / label routes that now return 410 Gone. All pool operations use OSGymSandboxClaim CRs (Path B).
- */
-export class Api<
- SecurityDataType extends unknown,
-> extends HttpClient<SecurityDataType> {
- /**
- * No description
- *
- * @tags health
- * @name HealthzList
- * @summary Liveness/readiness probe
- * @request GET:/healthz
- */
- healthzList = (params: RequestParams = {}) =>
- this.request<HealthzListData, any>({
- path: `/healthz`,
- method: "GET",
- format: "json",
- ...params,
- });
-
- batch = {
- /**
- * @description Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.
- *
- * @tags batch
- * @name BatchLanesCreate
- * @summary Deprecated batch lanes route
- * @request POST:/api/batch/{pool}/lanes
- * @deprecated
- * @secure
- */
- batchLanesCreate: (pool: string, params: RequestParams = {}) =>
- this.request<any, BatchLanesCreateError>({
- path: `/api/batch/${pool}/lanes`,
- method: "POST",
- secure: true,
- ...params,
- }),
-
- /**
- * @description Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.
- *
- * @tags batch
- * @name BatchLanesDelete
- * @summary Deprecated batch lanes route
- * @request DELETE:/api/batch/{pool}/lanes
- * @deprecated
- * @secure
- */
- batchLanesDelete: (pool: string, params: RequestParams = {}) =>
- this.request<any, BatchLanesDeleteError>({
- path: `/api/batch/${pool}/lanes`,
- method: "DELETE",
- secure: true,
- ...params,
- }),
-
- /**
- * @description Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.
- *
- * @tags batch
- * @name BatchSubmitCreate
- * @summary Deprecated batch submission route
- * @request POST:/api/batch/{pool}/submit
- * @deprecated
- * @secure
- */
- batchSubmitCreate: (pool: string, params: RequestParams = {}) =>
- this.request<any, BatchSubmitCreateError>({
- path: `/api/batch/${pool}/submit`,
- method: "POST",
- secure: true,
- ...params,
- }),
-
- /**
- * @description Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.
- *
- * @tags batch
- * @name BatchDelete
- * @summary Deprecated batch delete route
- * @request DELETE:/api/batch/{pool}/{id}
- * @deprecated
- * @secure
- */
- batchDelete: (pool: string, id: string, params: RequestParams = {}) =>
- this.request<any, BatchDeleteError>({
- path: `/api/batch/${pool}/${id}`,
- method: "DELETE",
- secure: true,
- ...params,
- }),
-
- /**
- * @description Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.
- *
- * @tags batch
- * @name BatchResultsList
- * @summary Deprecated batch results route
- * @request GET:/api/batch/{pool}/{id}/results
- * @deprecated
- * @secure
- */
- batchResultsList: (pool: string, id: string, params: RequestParams = {}) =>
- this.request<any, BatchResultsListError>({
- path: `/api/batch/${pool}/${id}/results`,
- method: "GET",
- secure: true,
- ...params,
- }),
-
- /**
- * @description Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.
- *
- * @tags batch
- * @name BatchStatusList
- * @summary Deprecated batch status route
- * @request GET:/api/batch/{pool}/{id}/status
- * @deprecated
- * @secure
- */
- batchStatusList: (pool: string, id: string, params: RequestParams = {}) =>
- this.request<any, BatchStatusListError>({
- path: `/api/batch/${pool}/${id}/status`,
- method: "GET",
- secure: true,
- ...params,
- }),
- };
- config = {
- /**
- * @description Returns OPA-evaluated feature flags for the authenticated SPA user. `admin` is true when the caller's JWT sub appears in input.flags.admin_subs.
- *
- * @tags config
- * @name ConfigList
- * @summary Per-user feature flags
- * @request GET:/api/config
- * @secure
- */
- configList: (params: RequestParams = {}) =>
- this.request<ConfigListData, ConfigListError>({
- path: `/api/config`,
- method: "GET",
- secure: true,
- format: "json",
- ...params,
- }),
- };
- gateway = {
- /**
- * @description The per-pool HTTP orchestrator has been deprecated and removed. All pools now use OSGymSandboxClaim CRs exclusively (Path B). This endpoint returns 410 Gone for any request. See CUA-609.
- *
- * @tags gateway
- * @name GatewayDetail
- * @summary DEPRECATED: Per-pool orchestrator reverse-proxy (CUA-609)
- * @request GET:/api/gateway/{name}/{path}
- */
- gatewayDetail: (name: string, path?: string, params: RequestParams = {}) =>
- this.request<any, GatewayDetailError>({
- path: `/api/gateway/${name}/${path}`,
- method: "GET",
- ...params,
- }),
- };
- k8S = {
- /**
- * @description Forwards requests to http://127.0.0.1:8001 (the kubectl-proxy sidecar) so the SPA can read K8s resources via the pod ServiceAccount. SPA-only; OPA-gated. EventList responses are filtered by the caller's OPA visible_events policy via auth.K8sEventFilterMiddleware (mounted in main.go's route chain).
- *
- * @tags passthrough
- * @name GetK8S
- * @summary Authenticated proxy to the in-pod kubectl-proxy sidecar
- * @request GET:/api/k8s/{path}
- * @secure
- */
- getK8S: (path: string, params: RequestParams = {}) =>
- this.request<GetK8SData, GetK8SError>({
- path: `/api/k8s/${path}`,
- method: "GET",
- secure: true,
- ...params,
- }),
- };
- keys = {
- /**
- * No description
- *
- * @tags keys
- * @name KeysList
- * @summary List the calling user's API keys
- * @request GET:/api/keys
- * @secure
- */
- keysList: (params: RequestParams = {}) =>
- this.request<KeysListData, KeysListError>({
- path: `/api/keys`,
- method: "GET",
- secure: true,
- format: "json",
- ...params,
- }),
-
- /**
- * @description Creates a Keycloak service-account client owned by the calling user. The returned `client_secret` is shown exactly once.
- *
- * @tags keys
- * @name KeysCreate
- * @summary Create a new API key
- * @request POST:/api/keys
- * @secure
- */
- keysCreate: (body: HandlersCreateKeyRequest, params: RequestParams = {}) =>
- this.request<KeysCreateData, KeysCreateError>({
- path: `/api/keys`,
- method: "POST",
- body: body,
- secure: true,
- type: ContentType.Json,
- format: "json",
- ...params,
- }),
-
- /**
- * No description
- *
- * @tags keys
- * @name KeysDelete
- * @summary Revoke an API key by Keycloak client UUID
- * @request DELETE:/api/keys/{id}
- * @secure
- */
- keysDelete: (id: string, params: RequestParams = {}) =>
- this.request<KeysDeleteData, KeysDeleteError>({
- path: `/api/keys/${id}`,
- method: "DELETE",
- secure: true,
- ...params,
- }),
- };
- label = {
- /**
- * @description Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.
- *
- * @tags label
- * @name LabelDelete
- * @summary Deprecated label delete route
- * @request DELETE:/api/label/{pool}/{label}
- * @deprecated
- * @secure
- */
- labelDelete: (pool: string, label: string, params: RequestParams = {}) =>
- this.request<any, LabelDeleteError>({
- path: `/api/label/${pool}/${label}`,
- method: "DELETE",
- secure: true,
- ...params,
- }),
-
- /**
- * @description Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.
- *
- * @tags label
- * @name LabelBatchCreate
- * @summary Deprecated label batch route
- * @request POST:/api/label/{pool}/{label}/batch
- * @deprecated
- * @secure
- */
- labelBatchCreate: (
- pool: string,
- label: string,
- params: RequestParams = {},
- ) =>
- this.request<any, LabelBatchCreateError>({
- path: `/api/label/${pool}/${label}/batch`,
- method: "POST",
- secure: true,
- ...params,
- }),
-
- /**
- * @description Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.
- *
- * @tags label
- * @name LabelResultsList
- * @summary Deprecated label results route
- * @request GET:/api/label/{pool}/{label}/results
- * @deprecated
- * @secure
- */
- labelResultsList: (
- pool: string,
- label: string,
- params: RequestParams = {},
- ) =>
- this.request<any, LabelResultsListError>({
- path: `/api/label/${pool}/${label}/results`,
- method: "GET",
- secure: true,
- ...params,
- }),
-
- /**
- * @description Route is deprecated and unavailable. Returns 410 Gone for every request. The orchestrator-backed batch surface is retired; callers must migrate to the replacement flow.
- *
- * @tags label
- * @name LabelStatusList
- * @summary Deprecated label status route
- * @request GET:/api/label/{pool}/{label}/status
- * @deprecated
- * @secure
- */
- labelStatusList: (
- pool: string,
- label: string,
- params: RequestParams = {},
- ) =>
- this.request<any, LabelStatusListError>({
- path: `/api/label/${pool}/${label}/status`,
- method: "GET",
- secure: true,
- ...params,
- }),
- };
- namespaces = {
- /**
- * @description Returns namespaces owned by the caller's Capsule Tenant. The list is scoped by a capsule.clastix.io/tenant=<tenant> label selector built from the authenticated subject, so it stays fail-closed even when Capsule Proxy isn't filtering.
- *
- * @tags namespaces
- * @name NamespacesList
- * @summary List the calling user's namespaces
- * @request GET:/api/namespaces
- * @secure
- */
- namespacesList: (params: RequestParams = {}) =>
- this.request<NamespacesListData, NamespacesListError>({
- path: `/api/namespaces`,
- method: "GET",
- secure: true,
- format: "json",
- ...params,
- }),
-
- /**
- * @description Creates a K8s namespace via impersonation. Capsule's webhook intercepts the creation and assigns it to the user's Tenant.
- *
- * @tags namespaces
- * @name NamespacesCreate
- * @summary Create a namespace for the calling user
- * @request POST:/api/namespaces
- * @secure
- */
- namespacesCreate: (
- body: HandlersCreateNamespaceRequest,
- params: RequestParams = {},
- ) =>
- this.request<NamespacesCreateData, NamespacesCreateError>({
- path: `/api/namespaces`,
- method: "POST",
- body: body,
- secure: true,
- type: ContentType.Json,
- format: "json",
- ...params,
- }),
-
- /**
- * @description Deletes a K8s namespace via impersonation. Capsule blocks deletion if the namespace doesn't belong to the user's Tenant.
- *
- * @tags namespaces
- * @name NamespacesDelete
- * @summary Delete a namespace owned by the calling user
- * @request DELETE:/api/namespaces/{name}
- * @secure
- */
- namespacesDelete: (name: string, params: RequestParams = {}) =>
- this.request<NamespacesDeleteData, NamespacesDeleteError>({
- path: `/api/namespaces/${name}`,
- method: "DELETE",
- secure: true,
- ...params,
- }),
- };
- orch = {
- /**
- * @description Resolves <service>.<namespace>.svc.cluster.local at request time (in-cluster DNS). The caller must hold RBAC in {namespace} (verified via an impersonated RoleBinding probe); OPA additionally validates that namespace and service look like DNS-1123 labels.
- *
- * @tags passthrough
- * @name OrchDetail
- * @summary SPA-authenticated proxy to a per-namespace orchestrator service
- * @request GET:/api/orch/{namespace}/{service}/{path}
- * @secure
- */
- orchDetail: (
- namespace: string,
- service: string,
- path: string,
- params: RequestParams = {},
- ) =>
- this.request<OrchDetailData, OrchDetailError>({
- path: `/api/orch/${namespace}/${service}/${path}`,
- method: "GET",
- secure: true,
- ...params,
- }),
- };
- svc = {
- /**
- * @description Proxies to {service}.{namespace}.svc.cluster.local:80. Per-key tokens are bound to their `namespace` claim; all other principals (SPA, user keys, oauth2-proxy browser sessions) must hold RBAC in {namespace}, verified via an impersonated RoleBinding probe. Strips Authorization before forwarding.
- *
- * @tags gateway
- * @name GetSvc
- * @summary Authenticated reverse proxy to a K8s Service in a namespace the caller owns
- * @request GET:/api/svc/{namespace}/{service}/{path}
- * @secure
- */
- getSvc: (
- namespace: string,
- service: string,
- path?: string,
- params: RequestParams = {},
- ) =>
- this.request<GetSvcData, GetSvcError>({
- path: `/api/svc/${namespace}/${service}/${path}`,
- method: "GET",
- secure: true,
- ...params,
- }),
- };
- userKeys = {
- /**
- * No description
- *
- * @tags user-keys
- * @name UserKeysList
- * @summary List the calling user's API keys
- * @request GET:/api/user-keys
- * @secure
- */
- userKeysList: (params: RequestParams = {}) =>
- this.request<UserKeysListData, UserKeysListError>({
- path: `/api/user-keys`,
- method: "GET",
- secure: true,
- format: "json",
- ...params,
- }),
-
- /**
- * @description Creates a Keycloak service-account client that acts on behalf of the calling user. The client_secret is returned exactly once; it cannot be retrieved later.
- *
- * @tags user-keys
- * @name UserKeysCreate
- * @summary Create a per-user API key
- * @request POST:/api/user-keys
- * @secure
- */
- userKeysCreate: (
- body: HandlersCreateUserKeyRequest,
- params: RequestParams = {},
- ) =>
- this.request<UserKeysCreateData, UserKeysCreateError>({
- path: `/api/user-keys`,
- method: "POST",
- body: body,
- secure: true,
- type: ContentType.Json,
- format: "json",
- ...params,
- }),
-
- /**
- * No description
- *
- * @tags user-keys
- * @name UserKeysDelete
- * @summary Revoke a per-user API key
- * @request DELETE:/api/user-keys/{id}
- * @secure
- */
- userKeysDelete: (id: string, params: RequestParams = {}) =>
- this.request<UserKeysDeleteData, UserKeysDeleteError>({
- path: `/api/user-keys/${id}`,
- method: "DELETE",
- secure: true,
- ...params,
- }),
- };
-}
diff --git a/libs/fleet/src/api/keys.ts b/libs/fleet/src/api/keys.ts
deleted file mode 100644
index 7c90b4dd45..0000000000
--- a/libs/fleet/src/api/keys.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-// Thin facade over the generated cyclops-cs-backend client.
-//
-// Existing components import { ApiKey, NewApiKey, keysApi } from "./keys"
-// — keep that surface stable while delegating the actual HTTP calls to
-// the swagger-generated client (src/api/generated/cyclops-cs-backend.ts).
-// To regenerate the client after backend changes: pnpm gen:api
-
-import { apiClient } from "./client"
-import type {
- HandlersCreateKeyResponse,
- KeycloakKeyClient,
-} from "./generated/cyclops-cs-backend"
-
-export type ApiKey = Required<
- Pick<KeycloakKeyClient, "id" | "client_id" | "name" | "namespace" | "owner_sub">
->
-export type NewApiKey = Required<
- Pick<
- HandlersCreateKeyResponse,
- "client_id" | "client_secret" | "token_url" | "name" | "namespace"
- >
->
-
-export const keysApi = {
- list: async (): Promise<{ keys: ApiKey[] }> => {
- const res = await apiClient.keys.keysList()
- return { keys: (res.data.keys ?? []) as ApiKey[] }
- },
- create: async (name: string, namespace: string): Promise<NewApiKey> => {
- const res = await apiClient.keys.keysCreate({ name, namespace })
- return res.data as NewApiKey
- },
- remove: async (id: string): Promise<void> => {
- await apiClient.keys.keysDelete(id)
- },
-}
diff --git a/libs/fleet/src/components/FeatureFlagContext.tsx b/libs/fleet/src/components/FeatureFlagContext.tsx
deleted file mode 100644
index 322fcc5d33..0000000000
--- a/libs/fleet/src/components/FeatureFlagContext.tsx
+++ /dev/null
@@ -1,35 +0,0 @@
-import { createContext, useContext, useEffect, useState, type ReactNode } from "react"
-import { fetchFeatureFlags, type FeatureFlags } from "../api/featureFlags"
-
-const DEFAULT_FLAGS: FeatureFlags = { admin: false }
-
-const FeatureFlagContext = createContext<FeatureFlags>(DEFAULT_FLAGS)
-
-/**
- * Fetches /api/config once at app startup and provides the result via
- * context. All children can call useFeatureFlags() to read flags.
- */
-export function FeatureFlagProvider({ children }: { children: ReactNode }) {
- const [flags, setFlags] = useState<FeatureFlags>(DEFAULT_FLAGS)
-
- useEffect(() => {
- fetchFeatureFlags().then(setFlags).catch(() => setFlags(DEFAULT_FLAGS))
- }, [])
-
- return (
- <FeatureFlagContext.Provider value={flags}>
- {children}
- </FeatureFlagContext.Provider>
- )
-}
-
-/**
- * Returns the current user's feature flags.
- *
- * @example
- * const { admin } = useFeatureFlags()
- * if (admin) { ... }
- */
-export function useFeatureFlags(): FeatureFlags {
- return useContext(FeatureFlagContext)
-}
diff --git a/libs/fleet/src/components/LogsPanel.tsx b/libs/fleet/src/components/LogsPanel.tsx
deleted file mode 100644
index b103497a1d..0000000000
--- a/libs/fleet/src/components/LogsPanel.tsx
+++ /dev/null
@@ -1,164 +0,0 @@
-import { useEffect, useRef, useState } from "react"
-import AnsiToHtml from "ansi-to-html"
-import Box from "@cloudscape-design/components/box"
-import Button from "@cloudscape-design/components/button"
-import Container from "@cloudscape-design/components/container"
-import Header from "@cloudscape-design/components/header"
-import SpaceBetween from "@cloudscape-design/components/space-between"
-import StatusIndicator from "@cloudscape-design/components/status-indicator"
-import { api } from "../api/cyclops"
-
-const MAX_LOG_LINES = 2000
-
-// SGR-only ANSI → HTML converter shared by every line append. ansi-to-html
-// HTML-escapes its input first (escapeXML: true), so `<script>` in a log
-// line lands as `&lt;script&gt;`.
-const ANSI = new AnsiToHtml({
- fg: "#d1d5db",
- bg: "#0f1419",
- newline: false,
- escapeXML: true,
-})
-
-export function LogsPanel({
- namespace,
- podName,
- container,
- title,
- waitingText,
-}: {
- namespace?: string
- podName?: string
- container: string
- title: string
- waitingText?: string
-}) {
- const [lines, setLines] = useState<string[]>([])
- const [paused, setPaused] = useState(false)
- const [error, setError] = useState<string | null>(null)
- const preRef = useRef<HTMLPreElement>(null)
- const stickToBottomRef = useRef(true)
-
- useEffect(() => {
- setLines([])
- }, [namespace, podName, container])
-
- useEffect(() => {
- if (!namespace || !podName || paused) return
- setError(null)
- const url = api.podLogsUrl(namespace, podName, container)
- const ctrl = new AbortController()
- ;(async () => {
- try {
- const { getToken } = await import("../auth/keycloak")
- const token = await getToken()
- const headers: Record<string, string> = {}
- if (token) headers.Authorization = `Bearer ${token}`
- const res = await fetch(url, { signal: ctrl.signal, headers })
- if (!res.ok || !res.body) {
- setError(`Log stream failed: ${res.status}`)
- return
- }
- const reader = res.body.getReader()
- const decoder = new TextDecoder()
- let buffer = ""
- for (;;) {
- const { done, value } = await reader.read()
- if (done) break
- buffer += decoder.decode(value, { stream: true })
- const parts = buffer.split("\n")
- buffer = parts.pop() ?? ""
- if (parts.length > 0) {
- const htmlLines = parts.map(l => ANSI.toHtml(l))
- setLines(prev => {
- const next = [...prev, ...htmlLines]
- return next.length > MAX_LOG_LINES
- ? next.slice(next.length - MAX_LOG_LINES)
- : next
- })
- }
- }
- } catch {
- if (!ctrl.signal.aborted) {
- setError("Log stream interrupted. Click Resume to retry.")
- }
- }
- })()
- return () => ctrl.abort()
- }, [namespace, podName, container, paused])
-
- useEffect(() => {
- const el = preRef.current
- if (!el || !stickToBottomRef.current) return
- el.scrollTop = el.scrollHeight
- }, [lines])
-
- const onScroll = () => {
- const el = preRef.current
- if (!el) return
- const distanceFromBottom = el.scrollHeight - (el.scrollTop + el.clientHeight)
- stickToBottomRef.current = distanceFromBottom < 40
- }
-
- return (
- <Container
- header={
- <Header
- variant="h2"
- counter={`(${lines.length})`}
- actions={
- <SpaceBetween direction="horizontal" size="xs">
- <Button
- onClick={() => setPaused(p => !p)}
- iconName={paused ? "caret-right-filled" : "close"}
- >
- {paused ? "Resume" : "Pause"}
- </Button>
- <Button onClick={() => setLines([])}>Clear</Button>
- </SpaceBetween>
- }
- >
- {title}
- </Header>
- }
- >
- {error && (
- <Box color="text-status-warning" margin={{ bottom: "xs" }}>
- <StatusIndicator type="warning">{error}</StatusIndicator>
- </Box>
- )}
- {lines.length === 0 ? (
- <Box color="text-body-secondary" textAlign="center" padding="m">
- {!namespace || !podName
- ? (waitingText ?? "Waiting for pod…")
- : paused
- ? "Paused."
- : "Connecting…"}
- </Box>
- ) : (
- <pre
- ref={preRef}
- onScroll={onScroll}
- // ansi-to-html HTML-escapes input first (escapeXML: true), so
- // dangerouslySetInnerHTML here is safe — log payload can't
- // inject markup.
- dangerouslySetInnerHTML={{ __html: lines.join("\n") }}
- style={{
- maxHeight: 480,
- overflow: "auto",
- margin: 0,
- padding: "0.75rem",
- backgroundColor: "#0f1419",
- color: "#d1d5db",
- fontSize: 12,
- fontFamily:
- "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",
- borderRadius: 4,
- whiteSpace: "pre-wrap",
- wordBreak: "break-all",
- }}
- />
- )}
- </Container>
- )
-}
diff --git a/libs/fleet/src/components/PoolLifecycleEvents.tsx b/libs/fleet/src/components/PoolLifecycleEvents.tsx
deleted file mode 100644
index f4df1832d6..0000000000
--- a/libs/fleet/src/components/PoolLifecycleEvents.tsx
+++ /dev/null
@@ -1,264 +0,0 @@
-import { useEffect, useState } from "react"
-import Box from "@cloudscape-design/components/box"
-import Button from "@cloudscape-design/components/button"
-import Container from "@cloudscape-design/components/container"
-import Header from "@cloudscape-design/components/header"
-import StatusIndicator from "@cloudscape-design/components/status-indicator"
-import Table, { type TableProps } from "@cloudscape-design/components/table"
-import { api, type KubernetesEvent } from "../api/cyclops"
-
-// ── Shared helpers ─────────────────────────────────────────────────────────
-
-export function eventTime(e: KubernetesEvent): string {
- return e.lastTimestamp ?? e.eventTime ?? e.firstTimestamp ?? e.metadata.creationTimestamp ?? ""
-}
-
-function fmtAge(ts: string): string {
- if (!ts) return "—"
- const ms = Date.now() - new Date(ts).getTime()
- if (Number.isNaN(ms)) return "—"
- const s = Math.max(0, Math.round(ms / 1000))
- if (s < 60) return `${s}s`
- const m = Math.round(s / 60)
- if (m < 60) return `${m}m`
- const h = Math.round(m / 60)
- if (h < 48) return `${h}h`
- return `${Math.round(h / 24)}d`
-}
-
-function AgeCell({ e }: { e: KubernetesEvent }) {
- return (
- <Box variant="small" color="text-body-secondary">
- {fmtAge(eventTime(e))}
- </Box>
- )
-}
-
-function TypeCell({ e }: { e: KubernetesEvent }) {
- return e.type === "Warning" ? (
- <StatusIndicator type="warning">Warning</StatusIndicator>
- ) : (
- <StatusIndicator type="success">Normal</StatusIndicator>
- )
-}
-
-// ── Strategy interface ─────────────────────────────────────────────────────
-
-/**
- * EventViewStrategy determines what events are visible and how they render.
- * Each concrete strategy encapsulates one audience's view of lifecycle events.
- * Adding a new audience (e.g. "support tier") is a new class, not a new branch.
- */
-interface EventViewStrategy {
- /** Filter the full sorted event list to what this audience should see. */
- filter(events: KubernetesEvent[]): KubernetesEvent[]
- /** Column definitions for the Cloudscape Table. */
- columns(): TableProps.ColumnDefinition<KubernetesEvent>[]
-}
-
-// ── Customer strategy ──────────────────────────────────────────────────────
-
-// Mapping of K8s event reason → marketing-friendly display label.
-// Used purely for display translation — filtering is now done server-side
-// by OPA's visible_events rule before events reach the SPA.
-const CUSTOMER_REASON_LABELS: Record<string, string> = {
- PoolCreated: "Pool created",
- PoolUpdated: "Pool updated",
- PoolDeleted: "Pool deleted",
- PoolScaled: "Replicas changed",
- PoolReady: "Pool ready",
- PoolDegraded: "Pool degraded",
- PoolFailed: "Pool failed",
- VmStarted: "VM started",
- VmStopped: "VM stopped",
- VmFailed: "VM failed",
- VmProvisioning: "Provisioning VM",
- OrchestratorReady: "Orchestrator ready",
- OrchestratorDown: "Orchestrator restarted",
-}
-
-// Optional user-facing subtitles for actionable/notable events.
-const CUSTOMER_REASON_DESC: Record<string, string> = {
- PoolDegraded: "The pool has fewer ready replicas than requested.",
- PoolFailed: "The pool encountered an error. Check your configuration.",
- VmFailed: "A VM replica failed. It will be replaced automatically.",
- OrchestratorDown: "The orchestrator pod was replaced.",
-}
-
-class CustomerEventView implements EventViewStrategy {
- /** No client-side filtering — server already applied visible_events via OPA. */
- filter(events: KubernetesEvent[]): KubernetesEvent[] {
- return events
- }
-
- columns(): TableProps.ColumnDefinition<KubernetesEvent>[] {
- return [
- {
- id: "age",
- header: "Age",
- cell: e => <AgeCell e={e} />,
- width: 80,
- },
- {
- id: "type",
- header: "Status",
- cell: e => <TypeCell e={e} />,
- width: 120,
- },
- {
- id: "event",
- header: "Event",
- isRowHeader: true,
- cell: e => {
- const label = e.reason ? (CUSTOMER_REASON_LABELS[e.reason] ?? e.reason) : "—"
- const desc = e.reason ? CUSTOMER_REASON_DESC[e.reason] : undefined
- return (
- <Box>
- <Box variant="span">{label}</Box>
- {desc && (
- <Box variant="small" color="text-body-secondary">
- {desc}
- </Box>
- )}
- </Box>
- )
- },
- },
- ]
- }
-}
-
-// ── Admin strategy ─────────────────────────────────────────────────────────
-
-class AdminEventView implements EventViewStrategy {
- /** Admins see every event for this pool — no filtering. */
- filter(events: KubernetesEvent[]): KubernetesEvent[] {
- return events
- }
-
- columns(): TableProps.ColumnDefinition<KubernetesEvent>[] {
- return [
- {
- id: "age",
- header: "Age",
- cell: e => <AgeCell e={e} />,
- width: 80,
- },
- {
- id: "type",
- header: "Type",
- cell: e => <TypeCell e={e} />,
- width: 120,
- },
- {
- id: "reason",
- header: "Reason",
- isRowHeader: true,
- cell: e => <code>{e.reason ?? "—"}</code>,
- width: 200,
- },
- {
- id: "message",
- header: "Message",
- cell: e => <Box variant="small">{e.message ?? "—"}</Box>,
- },
- {
- id: "count",
- header: "Count",
- cell: e => e.count ?? 1,
- width: 70,
- },
- ]
- }
-}
-
-// ── Strategy factory ───────────────────────────────────────────────────────
-
-/** Returns the correct strategy for the given audience. */
-function eventViewStrategyFor(admin: boolean): EventViewStrategy {
- return admin ? new AdminEventView() : new CustomerEventView()
-}
-
-// ── Component ──────────────────────────────────────────────────────────────
-
-const REFRESH_MS = 15_000
-
-interface PoolLifecycleEventsProps {
- /** Pool name (without the pool- prefix). Used to filter events to this pool. */
- poolName: string
- /** Whether the current user has admin access. Selects the AdminEventView strategy. */
- admin?: boolean
-}
-
-/**
- * Shows Kubernetes operator events for a specific pool.
- * The rendering strategy (columns, event filter, labels) is selected
- * by `admin` via `eventViewStrategyFor` — no if-statements in render.
- */
-export function PoolLifecycleEvents({ poolName, admin = false }: PoolLifecycleEventsProps) {
- const [events, setEvents] = useState<KubernetesEvent[]>([])
- const [loading, setLoading] = useState(true)
- const [error, setError] = useState<string | null>(null)
-
- const strategy = eventViewStrategyFor(admin)
-
- const load = async () => {
- setLoading(true)
- try {
- const list = await api.listOperatorEvents()
- const poolEvents = list.items
- .filter(e => e.involvedObject.name === poolName)
- .sort((a, b) => eventTime(b).localeCompare(eventTime(a)))
- setEvents(poolEvents)
- setError(null)
- } catch (e) {
- setError(String((e as Error).message))
- } finally {
- setLoading(false)
- }
- }
-
- useEffect(() => {
- load()
- const id = window.setInterval(load, REFRESH_MS)
- return () => window.clearInterval(id)
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [poolName])
-
- const visibleEvents = strategy.filter(events)
-
- return (
- <Container
- header={
- <Header
- variant="h2"
- counter={loading ? undefined : `(${visibleEvents.length})`}
- description="Recent lifecycle events for this pool."
- actions={<Button iconName="refresh" onClick={load} disabled={loading} />}
- >
- Lifecycle events
- </Header>
- }
- >
- <Table
- variant="embedded"
- items={visibleEvents}
- loading={loading}
- loadingText="Loading events"
- trackBy={e => e.metadata.uid ?? e.metadata.name + eventTime(e)}
- columnDefinitions={strategy.columns()}
- empty={
- error ? (
- <Box color="text-status-warning" textAlign="center" padding="m">
- Could not load events.
- </Box>
- ) : (
- <Box textAlign="center" color="text-body-secondary" padding="m">
- No lifecycle events yet.
- </Box>
- )
- }
- />
- </Container>
- )
-}
diff --git a/libs/fleet/src/components/PoolStatus.tsx b/libs/fleet/src/components/PoolStatus.tsx
index e408bc2523..b5e15b1a80 100644
--- a/libs/fleet/src/components/PoolStatus.tsx
+++ b/libs/fleet/src/components/PoolStatus.tsx
@@ -1,7 +1,7 @@
import StatusIndicator, {
StatusIndicatorProps,
} from "@cloudscape-design/components/status-indicator"
-import { PoolStatus } from "../api/pools"
+import type { PoolStatus } from "../sdk/status"
const POOL_STATUS_TYPE: Record<PoolStatus["kind"], StatusIndicatorProps.Type> = {
healthy: "success",
diff --git a/libs/fleet/src/pages/ApiKeys.tsx b/libs/fleet/src/pages/ApiKeys.tsx
deleted file mode 100644
index f58e837f4a..0000000000
--- a/libs/fleet/src/pages/ApiKeys.tsx
+++ /dev/null
@@ -1,195 +0,0 @@
-// API keys management.
-//
-// Lists the calling user's keys, lets them mint new ones (showing the
-// generated client_secret exactly once), and revoke existing keys. Each
-// key is a Keycloak service-account client with a `namespace` claim
-// mapper, which gates which orchestrator the resulting JWT can reach via
-// /api/gateway/:name.
-
-import { useEffect, useState } from "react"
-import Alert from "@cloudscape-design/components/alert"
-import Box from "@cloudscape-design/components/box"
-import Button from "@cloudscape-design/components/button"
-import Container from "@cloudscape-design/components/container"
-import CopyToClipboard from "@cloudscape-design/components/copy-to-clipboard"
-import Form from "@cloudscape-design/components/form"
-import FormField from "@cloudscape-design/components/form-field"
-import Header from "@cloudscape-design/components/header"
-import Input from "@cloudscape-design/components/input"
-import Modal from "@cloudscape-design/components/modal"
-import Select, { type SelectProps } from "@cloudscape-design/components/select"
-import SpaceBetween from "@cloudscape-design/components/space-between"
-import Table from "@cloudscape-design/components/table"
-import { ApiKey, NewApiKey, keysApi } from "../api/keys"
-import { api } from "../api/cyclops"
-
-export function ApiKeys() {
- const [keys, setKeys] = useState<ApiKey[]>([])
- const [loading, setLoading] = useState(true)
- const [error, setError] = useState<string | null>(null)
- const [name, setName] = useState("")
- const [selectedNs, setSelectedNs] = useState<SelectProps.Option | null>(null)
- const [nsOptions, setNsOptions] = useState<SelectProps.Option[]>([])
- const [creating, setCreating] = useState(false)
- const [created, setCreated] = useState<NewApiKey | null>(null)
-
- const refresh = async () => {
- setLoading(true)
- try {
- const [r, pools] = await Promise.all([
- keysApi.list(),
- api.listPools(),
- ])
- setKeys(r.keys)
- const poolOpts = pools.map(p => ({
- label: `${p.name} (pool-${p.name})`,
- value: `pool-${p.name}`,
- }))
- setNsOptions(poolOpts)
- setError(null)
- } catch (e) {
- setError(String(e))
- } finally {
- setLoading(false)
- }
- }
-
- useEffect(() => {
- refresh()
- }, [])
-
- const create = async () => {
- setCreating(true)
- try {
- const k = await keysApi.create(name, selectedNs!.value!)
- setCreated(k)
- setName("")
- setSelectedNs(null)
- await refresh()
- } catch (e) {
- setError(String(e))
- } finally {
- setCreating(false)
- }
- }
-
- const remove = async (id: string) => {
- try {
- await keysApi.remove(id)
- await refresh()
- } catch (e) {
- setError(String(e))
- }
- }
-
- return (
- <SpaceBetween size="l">
- {error && (
- <Alert type="error" dismissible onDismiss={() => setError(null)}>
- {error}
- </Alert>
- )}
-
- <Container header={<Header variant="h2">Issue a new API key</Header>}>
- <Form
- actions={
- <Button
- variant="primary"
- loading={creating}
- disabled={!name || !selectedNs}
- onClick={create}
- >
- Create key
- </Button>
- }
- >
- <SpaceBetween size="m">
- <FormField label="Name" description="Free-text label for this key">
- <Input value={name} onChange={e => setName(e.detail.value)} />
- </FormField>
- <FormField
- label="Namespace"
- description="Pool namespace this key may proxy to"
- >
- <Select
- selectedOption={selectedNs}
- onChange={e => setSelectedNs(e.detail.selectedOption)}
- options={nsOptions}
- placeholder="Select a pool"
- loadingText="Loading pools..."
- statusType={loading ? "loading" : "finished"}
- empty="No pools found"
- />
- </FormField>
- </SpaceBetween>
- </Form>
- </Container>
-
- <Table
- loading={loading}
- items={keys}
- columnDefinitions={[
- { id: "client_id", header: "Client ID", cell: r => r.client_id },
- { id: "name", header: "Name", cell: r => r.name },
- { id: "namespace", header: "Namespace", cell: r => r.namespace },
- {
- id: "actions",
- header: "",
- cell: r => (
- <Button onClick={() => remove(r.id)}>Revoke</Button>
- ),
- },
- ]}
- empty={<Box textAlign="center">No keys yet.</Box>}
- header={<Header variant="h2">Existing keys</Header>}
- />
-
- {created && (
- <Modal
- visible
- header="API key created"
- onDismiss={() => setCreated(null)}
- footer={
- <Box float="right">
- <Button variant="primary" onClick={() => setCreated(null)}>
- I have copied the secret
- </Button>
- </Box>
- }
- >
- <SpaceBetween size="m">
- <Alert type="warning">
- The client secret is shown <b>once</b>. Copy it now — it
- can&rsquo;t be retrieved later. To rotate, revoke this key and
- create a new one.
- </Alert>
- <Container>
- <SpaceBetween size="m">
- <FormField label="Client ID">
- <CopyToClipboard
- variant="inline"
- textToCopy={created.client_id}
- textToDisplay={<code>{created.client_id}</code>}
- copyButtonAriaLabel="Copy Client ID"
- copySuccessText="Client ID copied"
- copyErrorText="Failed to copy"
- />
- </FormField>
- <FormField label="Client secret">
- <CopyToClipboard
- variant="inline"
- textToCopy={created.client_secret}
- textToDisplay={<code>{created.client_secret}</code>}
- copyButtonAriaLabel="Copy Client secret"
- copySuccessText="Client secret copied"
- copyErrorText="Failed to copy"
- />
- </FormField>
- </SpaceBetween>
- </Container>
- </SpaceBetween>
- </Modal>
- )}
- </SpaceBetween>
- )
-}
diff --git a/libs/fleet/src/pages/ClaimDetail.tsx b/libs/fleet/src/pages/ClaimDetail.tsx
index 2ce243007f..4083fec801 100644
--- a/libs/fleet/src/pages/ClaimDetail.tsx
+++ b/libs/fleet/src/pages/ClaimDetail.tsx
@@ -10,9 +10,11 @@ import Modal from "@cloudscape-design/components/modal"
import SpaceBetween from "@cloudscape-design/components/space-between"
import Spinner from "@cloudscape-design/components/spinner"
import StatusIndicator from "@cloudscape-design/components/status-indicator"
-import { api, claimsApi, type Claim } from "../api/cyclops"
import { useFlash } from "../components/FlashContext"
import { DesktopPane } from "../components/DesktopPane"
+import { deleteClaim, getClaim } from "../sdk/claims"
+import type { Claim } from "../sdk/models"
+import { getPool } from "../sdk/pools"
function phaseType(phase: string): "success" | "pending" | "error" | "info" {
switch (phase) {
@@ -42,8 +44,8 @@ export function ClaimDetail() {
setLoading(true)
try {
const [claimData, poolData] = await Promise.all([
- claimsApi.get(namespace, claimName),
- api.getPool(namespace, poolName),
+ getClaim(namespace, claimName),
+ getPool(namespace, poolName),
])
setClaim(claimData)
setServices(poolData.services)
@@ -70,7 +72,7 @@ export function ClaimDetail() {
if (!claim || claim.phase !== "Pending") return
const id = setInterval(async () => {
try {
- const c = await claimsApi.get(namespace, claimName)
+ const c = await getClaim(namespace, claimName)
setClaim(c)
} catch {
// Silent — next tick will retry
@@ -82,7 +84,7 @@ export function ClaimDetail() {
const release = async () => {
setReleasing(true)
try {
- await claimsApi.remove(namespace, claimName)
+ await deleteClaim(namespace, claimName)
flash.push({ type: "success", header: `Released claim ${claimName}` })
navigate(`/pools/${namespace}/${poolName}`)
} catch (e) {
diff --git a/libs/fleet/src/pages/NodesList.tsx b/libs/fleet/src/pages/NodesList.tsx
deleted file mode 100644
index 1746f9ffdb..0000000000
--- a/libs/fleet/src/pages/NodesList.tsx
+++ /dev/null
@@ -1,149 +0,0 @@
-import { useEffect, useState } from "react"
-import Box from "@cloudscape-design/components/box"
-import Button from "@cloudscape-design/components/button"
-import Header from "@cloudscape-design/components/header"
-import Table from "@cloudscape-design/components/table"
-import {
- api,
- isPoolWorkerNode,
- NodeSummary,
- parseCpuCores,
- parseMemoryBytes,
- POOL_WORKER_NODE_PREFIX,
-} from "../api/cyclops"
-import { useFlash } from "../components/FlashContext"
-
-function readyCondition(n: NodeSummary): string {
- const c = (n.status?.conditions ?? []).find(c => c.type === "Ready")
- if (!c) return "Unknown"
- return c.status === "True" ? "Ready" : "NotReady"
-}
-
-function fmtMemGi(s?: string): string {
- if (!s) return "—"
- const b = parseMemoryBytes(s)
- return `${(b / 1024 ** 3).toFixed(1)}Gi`
-}
-
-interface NodeRow {
- node: NodeSummary
- totalVms: number
-}
-
-export function NodesList() {
- const flash = useFlash()
- const [rows, setRows] = useState<NodeRow[]>([])
- const [loading, setLoading] = useState(true)
-
- const load = async () => {
- setLoading(true)
- try {
- const [nodes, pods, pools] = await Promise.all([
- api.listNodes(),
- api.listVmPods(),
- api.listPools().catch(() => []),
- ])
-
- const knownPoolNs = new Set(
- pools.map(p => `pool-${p.name}`),
- )
-
- const byNode = new Map<string, number>()
- for (const p of pods.items) {
- const node = p.spec?.nodeName
- if (!node) continue
- const ns = p.metadata.namespace
- if (!knownPoolNs.has(ns)) continue
- byNode.set(node, (byNode.get(node) ?? 0) + 1)
- }
-
- setRows(
- nodes.items.filter(isPoolWorkerNode).map(n => ({
- node: n,
- totalVms: byNode.get(n.metadata.name) ?? 0,
- })),
- )
- } catch (e) {
- flash.push({
- type: "error",
- header: "Failed to list nodes",
- content: String((e as Error).message),
- })
- } finally {
- setLoading(false)
- }
- }
- useEffect(() => {
- load()
- }, [])
-
- const totalVms = rows.reduce((s, r) => s + r.totalVms, 0)
-
- return (
- <Table
- header={
- <Header
- variant="h1"
- counter={loading ? undefined : `(${rows.length})`}
- description={
- loading
- ? undefined
- : `${totalVms} pool VM${totalVms === 1 ? "" : "s"} scheduled across ${rows.length} node${rows.length === 1 ? "" : "s"}.`
- }
- actions={
- <Button iconName="refresh" onClick={load} disabled={loading} />
- }
- >
- Nodes
- </Header>
- }
- items={rows}
- loading={loading}
- loadingText="Loading nodes"
- trackBy={r => r.node.metadata.name}
- empty={
- <Box textAlign="center" padding="m" color="text-body-secondary">
- No nodes
- </Box>
- }
- columnDefinitions={[
- {
- id: "name",
- header: "Name",
- cell: r => (
- <code title={r.node.metadata.name}>
- {r.node.metadata.name.startsWith(POOL_WORKER_NODE_PREFIX)
- ? r.node.metadata.name.slice(POOL_WORKER_NODE_PREFIX.length)
- : r.node.metadata.name}
- </code>
- ),
- sortingField: "node.metadata.name",
- isRowHeader: true,
- },
- {
- id: "status",
- header: "Status",
- cell: r => readyCondition(r.node),
- },
- {
- id: "cpu",
- header: "CPU (alloc.)",
- cell: r => {
- const c = r.node.status?.allocatable?.cpu
- return c ? parseCpuCores(c).toFixed(1) : "—"
- },
- },
- {
- id: "mem",
- header: "Memory (alloc.)",
- cell: r => fmtMemGi(r.node.status?.allocatable?.memory),
- },
- {
- id: "vms",
- header: "Pool VMs",
- cell: r => r.totalVms,
- },
- ]}
- />
- )
-}
diff --git a/libs/fleet/src/pages/OperatorEvents.tsx b/libs/fleet/src/pages/OperatorEvents.tsx
deleted file mode 100644
index d391116aa0..0000000000
--- a/libs/fleet/src/pages/OperatorEvents.tsx
+++ /dev/null
@@ -1,136 +0,0 @@
-import { useEffect, useState } from "react"
-import Box from "@cloudscape-design/components/box"
-import Button from "@cloudscape-design/components/button"
-import Header from "@cloudscape-design/components/header"
-import StatusIndicator from "@cloudscape-design/components/status-indicator"
-import Table from "@cloudscape-design/components/table"
-import { api, type KubernetesEvent } from "../api/cyclops"
-import { useFlash } from "../components/FlashContext"
-
-const REFRESH_MS = 15_000
-
-function eventTime(e: KubernetesEvent): string {
- return (
- e.lastTimestamp ??
- e.eventTime ??
- e.firstTimestamp ??
- e.metadata.creationTimestamp ??
- ""
- )
-}
-
-function fmtAge(ts: string): string {
- if (!ts) return "—"
- const ms = Date.now() - new Date(ts).getTime()
- if (Number.isNaN(ms)) return "—"
- const s = Math.max(0, Math.round(ms / 1000))
- if (s < 60) return `${s}s`
- const m = Math.round(s / 60)
- if (m < 60) return `${m}m`
- const h = Math.round(m / 60)
- if (h < 48) return `${h}h`
- return `${Math.round(h / 24)}d`
-}
-
-export function OperatorEvents() {
- const flash = useFlash()
- const [events, setEvents] = useState<KubernetesEvent[]>([])
- const [loading, setLoading] = useState(true)
-
- const load = async () => {
- setLoading(true)
- try {
- const list = await api.listOperatorEvents()
- const sorted = [...list.items].sort((a, b) =>
- eventTime(b).localeCompare(eventTime(a)),
- )
- setEvents(sorted)
- } catch (e) {
- flash.push({
- type: "error",
- header: "Failed to list events",
- content: String((e as Error).message),
- })
- } finally {
- setLoading(false)
- }
- }
-
- useEffect(() => {
- load()
- const id = window.setInterval(load, REFRESH_MS)
- return () => window.clearInterval(id)
- }, [])
-
- return (
- <Table
- header={
- <Header
- variant="h1"
- counter={loading ? undefined : `(${events.length})`}
- description="Kubernetes events emitted by the pool-operator on OSGymWorkspacePool resources."
- actions={
- <Button iconName="refresh" onClick={load} disabled={loading} />
- }
- >
- Operator events
- </Header>
- }
- items={events}
- loading={loading}
- loadingText="Loading events"
- trackBy={e => e.metadata.uid ?? e.metadata.name}
- empty={
- <Box textAlign="center" padding="m" color="text-body-secondary">
- No events
- </Box>
- }
- columnDefinitions={[
- {
- id: "age",
- header: "Age",
- cell: e => fmtAge(eventTime(e)),
- width: 90,
- },
- {
- id: "type",
- header: "Type",
- cell: e =>
- e.type === "Warning" ? (
- <StatusIndicator type="warning">Warning</StatusIndicator>
- ) : (
- <StatusIndicator type="success">Normal</StatusIndicator>
- ),
- width: 130,
- },
- {
- id: "reason",
- header: "Reason",
- cell: e => <code>{e.reason ?? "—"}</code>,
- width: 220,
- },
- {
- id: "object",
- header: "Object",
- cell: e => (
- <code title={`${e.involvedObject.kind}/${e.involvedObject.name}`}>
- {e.involvedObject.name}
- </code>
- ),
- width: 200,
- },
- {
- id: "message",
- header: "Message",
- cell: e => e.message ?? "",
- },
- {
- id: "count",
- header: "Count",
- cell: e => e.count ?? 1,
- width: 80,
- },
- ]}
- />
- )
-}
diff --git a/libs/fleet/src/pages/PoolDetail.tsx b/libs/fleet/src/pages/PoolDetail.tsx
index cef154e297..3324039b36 100644
--- a/libs/fleet/src/pages/PoolDetail.tsx
+++ b/libs/fleet/src/pages/PoolDetail.tsx
@@ -14,52 +14,27 @@ import Spinner from "@cloudscape-design/components/spinner"
import StatusIndicator from "@cloudscape-design/components/status-indicator"
import Table from "@cloudscape-design/components/table"
import Tabs from "@cloudscape-design/components/tabs"
-import { api, claimsApi, type Claim } from "../api/cyclops"
-import { derivePoolStatus, tombstonePool } from "../api/pools"
-import { useFeatureFlags } from "../components/FeatureFlagContext"
import { useFlash } from "../components/FlashContext"
import { PoolStatusPill } from "../components/PoolStatus"
-
-interface ServiceDef {
- name: string
- targetPort: number
- protocol: string
-}
-
-interface PoolData {
- name: string
- namespace: string
- replicas: number
- cpu: number
- ram: string
- ociImage: string
- services: ServiceDef[]
- probes?: { readinessProbe?: Record<string, unknown>; livenessProbe?: Record<string, unknown> }
- phase: string
- totalCount: number
- availableCount: number
- claimedCount: number
-}
+import { createClaim as createSdkClaim, deleteClaim, listClaims } from "../sdk/claims"
+import type { Claim, PoolData } from "../sdk/models"
+import { deletePool, getPool, updatePoolServices } from "../sdk/pools"
+import { derivePoolStatus, tombstonePool } from "../sdk/status"
export function PoolDetail() {
const { namespace = "", name = "" } = useParams()
const navigate = useNavigate()
const flash = useFlash()
- const { admin } = useFeatureFlags()
const [pool, setPool] = useState<PoolData | null>(null)
const [loading, setLoading] = useState(true)
const [confirmingDelete, setConfirmingDelete] = useState(false)
const [deleting, setDeleting] = useState(false)
- // Orchestrator restart state (admin-only)
- const [confirmingOrchestratorRestart, setConfirmingOrchestratorRestart] = useState(false)
- const [orchestratorRestarting, setOrchestratorRestarting] = useState(false)
-
const load = async () => {
setLoading(true)
try {
- const p = await api.getPool(namespace, name)
+ const p = await getPool(namespace, name)
setPool(p)
} catch (e) {
flash.push({
@@ -79,7 +54,7 @@ export function PoolDetail() {
const remove = async () => {
setDeleting(true)
try {
- await api.deletePool(namespace, name)
+ await deletePool(namespace, name)
tombstonePool(name)
flash.push({ type: "success", header: `Deleted ${name}` })
navigate("/pools")
@@ -93,29 +68,6 @@ export function PoolDetail() {
}
}
- const restartOrchestrator = async () => {
- if (!pool) return
- setOrchestratorRestarting(true)
- try {
- await api.restartOrchestrator(`pool-${pool.name}`, pool.name)
- flash.push({
- type: "success",
- header: `Restarting orchestrator for ${pool.name}`,
- content:
- "A rollout restart has been triggered. The orchestrator pod will be replaced momentarily.",
- })
- } catch (e) {
- flash.push({
- type: "error",
- header: "Orchestrator restart failed",
- content: String((e as Error).message),
- })
- } finally {
- setOrchestratorRestarting(false)
- setConfirmingOrchestratorRestart(false)
- }
- }
-
if (loading && !pool) {
return (
<Container header={<Header variant="h1">{name}</Header>}>
@@ -145,14 +97,6 @@ export function PoolDetail() {
>
Duplicate
</Button>
- {admin && (
- <Button
- onClick={() => setConfirmingOrchestratorRestart(true)}
- disabled={orchestratorRestarting}
- >
- Restart orchestrator
- </Button>
- )}
<Button onClick={() => setConfirmingDelete(true)}>
Delete
</Button>
@@ -163,7 +107,7 @@ export function PoolDetail() {
</Header>
}
>
- <ColumnLayout columns={admin ? 3 : 2} variant="text-grid">
+ <ColumnLayout columns={2} variant="text-grid">
<div>
<Box variant="awsui-key-label">Status</Box>
<PoolStatusPill status={status} />
@@ -172,14 +116,6 @@ export function PoolDetail() {
<Box variant="awsui-key-label">Namespace</Box>
<div>{pool.namespace}</div>
</div>
- {admin && (
- <div>
- <Box variant="awsui-key-label">Gateway</Box>
- <div>
- <code>{window.location.origin}/api/gateway/{pool.name}</code>
- </div>
- </div>
- )}
</ColumnLayout>
</Container>
@@ -219,38 +155,6 @@ export function PoolDetail() {
in <b>{pool.namespace}</b>.
</Modal>
- {admin && (
- <Modal
- visible={confirmingOrchestratorRestart}
- onDismiss={() => { if (!orchestratorRestarting) setConfirmingOrchestratorRestart(false) }}
- header={`Restart orchestrator for ${name}?`}
- footer={
- <Box float="right">
- <SpaceBetween direction="horizontal" size="xs">
- <Button
- onClick={() => setConfirmingOrchestratorRestart(false)}
- disabled={orchestratorRestarting}
- >
- Cancel
- </Button>
- <Button
- variant="primary"
- onClick={restartOrchestrator}
- loading={orchestratorRestarting}
- >
- Restart orchestrator
- </Button>
- </SpaceBetween>
- </Box>
- }
- >
- This will trigger a rolling restart of the{" "}
- <b>{name}-orchestrator</b> Deployment in{" "}
- <b>{pool.namespace}</b>. Equivalent to{" "}
- <code>kubectl rollout restart deployment/{name}-orchestrator</code>.
- In-flight requests will be drained before the old pod is terminated.
- </Modal>
- )}
</SpaceBetween>
)
}
@@ -409,7 +313,7 @@ function ServicesEditor({
targetPort: parseInt(r.targetPort, 10),
protocol: r.protocol || "TCP",
}))
- await api.updatePoolServices(pool.namespace, pool.name, services)
+ await updatePoolServices(pool.namespace, pool.name, services)
flash.push({ type: "success", header: "Services updated" })
onSaved()
} catch (e) {
@@ -521,12 +425,9 @@ function ClaimsTable({ pool }: { pool: PoolData }) {
// Pool name = namespace name (1:1 mapping).
const claimNamespace = pool.namespace
- // The compat shim names the template <pool-name>-template.
- const templateRef = `${pool.name}-template`
-
const loadClaims = useCallback(async () => {
try {
- const list = await claimsApi.list(claimNamespace)
+ const list = await listClaims(claimNamespace)
setClaims(list)
} catch {
// Silently ignore polling errors — the table will show stale data
@@ -548,9 +449,8 @@ function ClaimsTable({ pool }: { pool: PoolData }) {
const createClaim = async () => {
setCreating(true)
try {
- const id = `claim-${Math.random().toString(36).slice(2, 10)}`
- await claimsApi.create(claimNamespace, id, templateRef)
- flash.push({ type: "success", header: `Created claim ${id}` })
+ const claim = await createSdkClaim(claimNamespace, pool.name)
+ flash.push({ type: "success", header: `Created claim ${claim.name}` })
setShowCreate(false)
await loadClaims()
} catch (e) {
@@ -567,7 +467,7 @@ function ClaimsTable({ pool }: { pool: PoolData }) {
const releaseClaim = async (claimName: string) => {
setReleasing(true)
try {
- await claimsApi.remove(claimNamespace, claimName)
+ await deleteClaim(claimNamespace, claimName)
flash.push({ type: "success", header: `Released claim ${claimName}` })
setConfirmRelease(null)
await loadClaims()
diff --git a/libs/fleet/src/pages/PoolNew.tsx b/libs/fleet/src/pages/PoolNew.tsx
index 7dfa68a210..c9a1b2d71b 100644
--- a/libs/fleet/src/pages/PoolNew.tsx
+++ b/libs/fleet/src/pages/PoolNew.tsx
@@ -11,20 +11,12 @@ import Input from "@cloudscape-design/components/input"
import Select from "@cloudscape-design/components/select"
import SpaceBetween from "@cloudscape-design/components/space-between"
import Toggle from "@cloudscape-design/components/toggle"
-import { api, type PoolTemplateConfig } from "../api/cyclops"
import { useFlash } from "../components/FlashContext"
-import { useFeatureFlags } from "../components/FeatureFlagContext"
+import { createPool } from "../sdk/pools"
+import type { PoolTemplateConfig } from "../sdk/models"
const NAME_PATTERN = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/
-const RUNTIME_OPTIONS = [
- { label: "KubeVirt VM (Linux / Windows)", value: "kubevirt" },
- { label: "macOS VM", value: "macos" },
- { label: "gVisor pod (sandboxed Linux)", value: "gvisor" },
-]
-// A macOS pool's default desktop image (admin-only). Overridable in the field.
-const MACOS_DEFAULT_IMAGE = "127.0.0.1:5000/cua/macos-desktop-workspace:latest"
-
const DEFAULTS = {
cpu: 4,
ram: "4Gi",
@@ -114,15 +106,6 @@ export function PoolNew() {
const [initialPoolSize, setInitialPoolSize] = useState(String(seed.autoscaling?.initialPoolSize ?? 0))
const [maxPoolSize, setMaxPoolSize] = useState(String(seed.autoscaling?.maxPoolSize ?? 20))
const [submitting, setSubmitting] = useState(false)
- // macOS is an admin-only capability — the selector is only rendered for
- // admins, and the backend independently rejects macos pool writes from
- // non-admins (handlers/k8s.go macosPoolNeedsAdmin). Non-admins never see it.
- const { admin } = useFeatureFlags()
- const [runtime, setRuntime] = useState<"kubevirt" | "macos" | "gvisor">(seed.runtime ?? "kubevirt")
- // Pod runtimes (macos, gvisor) are gated to admins in the UI; the backend
- // independently rejects macos writes from non-admins (handlers/k8s.go).
- const isPodRuntime = admin && runtime !== "kubevirt"
- const isMacos = admin && runtime === "macos"
const nameError = useMemo(() => {
if (!name) return undefined
@@ -144,8 +127,7 @@ export function PoolNew() {
setServices(prev => prev.filter(s => s.id !== id))
}
- // Collect the current form into the config object that api.createPool
- // consumes.
+ // Collect the current form into the SDK's pool/template configuration.
const buildValues = (): PoolTemplateConfig => {
const validServices = services
.filter(s => s.name.trim() && s.targetPort)
@@ -162,21 +144,15 @@ export function PoolNew() {
} = {}
if (readPort) probes.readinessProbe = { tcpSocket: { port: readPort } }
if (livePort) probes.livenessProbe = { tcpSocket: { port: livePort } }
- // A macOS pool auto-gets a `vnc` service (unless the user added one) so its
- // desktop streams to the ClaimDetail DesktopPane over noVNC.
- const svcs = isMacos && !validServices.some(s => s.name === "vnc")
- ? [...validServices, { name: "vnc", targetPort: 6080, protocol: "TCP" }]
- : validServices
return {
cpu: parseInt(cpu, 10) || DEFAULTS.cpu,
ram: ram.trim() || DEFAULTS.ram,
// Trim pasted whitespace: K8s rejects pod images with leading/trailing
// spaces, which wedges the pool's VM in Starting forever.
- ociImage: ociImage.trim() || (isMacos ? MACOS_DEFAULT_IMAGE : DEFAULTS.ociImage),
+ ociImage: ociImage.trim() || DEFAULTS.ociImage,
firmware: firmware !== "bios" ? firmware : undefined,
- runtime: isPodRuntime ? runtime : undefined,
replicas: parseInt(replicas, 10) || DEFAULTS.replicas,
- services: svcs.length ? svcs : undefined,
+ services: validServices.length ? validServices : undefined,
probes: Object.keys(probes).length ? probes : undefined,
autoscaling: autoscalingEnabled
? {
@@ -192,7 +168,7 @@ export function PoolNew() {
if (!name || nameError) return
setSubmitting(true)
try {
- await api.createPool(name, buildValues())
+ await createPool(name, buildValues())
flash.push({ type: "success", header: `Created pool ${name}` })
// Pool name = namespace name (1:1 mapping).
navigate(`/pools/${name}/${name}`)
@@ -271,24 +247,9 @@ export function PoolNew() {
/>
</FormField>
- {admin && (
- <FormField
- label="Runtime"
- description="Admin-only. macOS provisions a macOS sandbox (streamable over noVNC) instead of a KubeVirt VM."
- >
- <Select
- selectedOption={RUNTIME_OPTIONS.find(o => o.value === runtime) ?? RUNTIME_OPTIONS[0]}
- onChange={({ detail }) => setRuntime((detail.selectedOption.value as "kubevirt" | "macos" | "gvisor") ?? "kubevirt")}
- options={RUNTIME_OPTIONS}
- />
- </FormField>
- )}
-
<FormField
label="OCI image"
- description={isMacos
- ? "macOS sandbox image ref (defaults to the macos-desktop-workspace image if left blank)."
- : "Workspace containerDisk image (and the image used by /reset-created VMs)."}
+ description="Workspace containerDisk image."
>
<Input
value={ociImage}
diff --git a/libs/fleet/src/pages/PoolReplicaDetail.tsx b/libs/fleet/src/pages/PoolReplicaDetail.tsx
deleted file mode 100644
index 23272f093e..0000000000
--- a/libs/fleet/src/pages/PoolReplicaDetail.tsx
+++ /dev/null
@@ -1,305 +0,0 @@
-import { useEffect, useMemo, useState } from "react"
-import { useNavigate, useParams } from "react-router-dom"
-import BreadcrumbGroup from "@cloudscape-design/components/breadcrumb-group"
-import Box from "@cloudscape-design/components/box"
-import Button from "@cloudscape-design/components/button"
-import ColumnLayout from "@cloudscape-design/components/column-layout"
-import Container from "@cloudscape-design/components/container"
-import Header from "@cloudscape-design/components/header"
-import Modal from "@cloudscape-design/components/modal"
-import ProgressBar from "@cloudscape-design/components/progress-bar"
-import SpaceBetween from "@cloudscape-design/components/space-between"
-import Spinner from "@cloudscape-design/components/spinner"
-import StatusIndicator from "@cloudscape-design/components/status-indicator"
-import { api, parseMemoryBytes, sumPodUsage } from "../api/cyclops"
-import type { PodMetrics, PodSummary } from "../api/cyclops"
-import { useFlash } from "../components/FlashContext"
-import { LogsPanel } from "../components/LogsPanel"
-
-const LOG_CONTAINER = "guest-console-log"
-const METRICS_INTERVAL_MS = 5000
-
-export function PoolReplicaDetail() {
- const { namespace: nsParam = "", poolName = "", vmName = "" } = useParams()
- const navigate = useNavigate()
- const flash = useFlash()
-
- const [namespace, setNamespace] = useState<string | null>(null)
- const [launcher, setLauncher] = useState<PodSummary | null>(null)
- const [launcherLoading, setLauncherLoading] = useState(true)
- const [launcherError, setLauncherError] = useState<string | null>(null)
-
- const [metrics, setMetrics] = useState<PodMetrics | null>(null)
- const [metricsError, setMetricsError] = useState<string | null>(null)
-
- // Pool's spec.cpu / spec.ram (denominators for the progress bars).
- const [cpuLimit, setCpuLimit] = useState<number | null>(null)
- const [memLimit, setMemLimit] = useState<number | null>(null)
-
- // Restart confirmation dialog state.
- const [confirmingRestart, setConfirmingRestart] = useState(false)
- const [restarting, setRestarting] = useState(false)
-
- useEffect(() => {
- if (!nsParam || !poolName) return
- api
- .getPool(nsParam, poolName)
- .then(p => {
- setNamespace(p.namespace)
- setCpuLimit(p.cpu)
- setMemLimit(parseMemoryBytes(p.ram))
- })
- .catch(e => setLauncherError(String((e as Error).message)))
- }, [nsParam, poolName])
-
- // Once we have the namespace, find the launcher pod.
- useEffect(() => {
- if (!namespace || !vmName) return
- setLauncherLoading(true)
- setLauncherError(null)
- api
- .findLauncherPod(namespace, vmName)
- .then(p => setLauncher(p))
- .catch(e => setLauncherError(String((e as Error).message)))
- .finally(() => setLauncherLoading(false))
- }, [namespace, vmName])
-
- // Poll metrics every 5s once we have a launcher pod.
- useEffect(() => {
- if (!launcher) return
- let cancelled = false
- const tick = async () => {
- try {
- const m = await api.getPodMetrics(
- launcher.metadata.namespace,
- launcher.metadata.name,
- )
- if (!cancelled) {
- setMetrics(m)
- setMetricsError(null)
- }
- } catch (e) {
- if (!cancelled) setMetricsError(String((e as Error).message))
- }
- }
- tick()
- const id = window.setInterval(tick, METRICS_INTERVAL_MS)
- return () => {
- cancelled = true
- window.clearInterval(id)
- }
- }, [launcher])
-
- const usage = useMemo(() => (metrics ? sumPodUsage(metrics) : null), [metrics])
-
- const refresh = () => {
- if (!namespace) return
- setLauncherLoading(true)
- setLauncherError(null)
- api
- .findLauncherPod(namespace, vmName)
- .then(p => setLauncher(p))
- .catch(e => setLauncherError(String((e as Error).message)))
- .finally(() => setLauncherLoading(false))
- }
-
- const restart = async () => {
- if (!namespace) return
- setRestarting(true)
- try {
- await api.restartVm(namespace, vmName)
- flash.push({
- type: "success",
- header: `Restarting ${vmName}`,
- content:
- "The VM restart has been requested. The VMI will terminate and a fresh instance will start from the same spec.",
- })
- setConfirmingRestart(false)
- // Refresh after a short delay to pick up the new launcher pod.
- setTimeout(refresh, 3000)
- } catch (e) {
- flash.push({
- type: "error",
- header: "Restart failed",
- content: String((e as Error).message),
- })
- } finally {
- setRestarting(false)
- setConfirmingRestart(false)
- }
- }
-
- return (
- <SpaceBetween size="l">
- <BreadcrumbGroup
- items={[
- { text: "Pools", href: "#/pools" },
- { text: poolName, href: `#/pools/${nsParam}/${poolName}` },
- { text: vmName, href: "#" },
- ]}
- onFollow={e => {
- if (e.detail.href === "#") return
- e.preventDefault()
- navigate(e.detail.href.replace(/^#/, ""))
- }}
- />
-
- <Container
- header={
- <Header
- variant="h1"
- actions={
- <SpaceBetween direction="horizontal" size="xs">
- <Button iconName="refresh" onClick={refresh} disabled={launcherLoading}>
- Refresh
- </Button>
- <Button
- onClick={() => setConfirmingRestart(true)}
- disabled={restarting}
- >
- Restart
- </Button>
- </SpaceBetween>
- }
- >
- {vmName}
- </Header>
- }
- >
- <ColumnLayout columns={2}>
- <div>
- <Box variant="awsui-key-label">CPU</Box>
- <MetricTile
- error={metricsError}
- loading={!metrics && !metricsError}
- value={usage?.cpuCores}
- limit={cpuLimit}
- format={fmtCores}
- />
- </div>
- <div>
- <Box variant="awsui-key-label">Memory</Box>
- <MetricTile
- error={metricsError}
- loading={!metrics && !metricsError}
- value={usage?.memBytes}
- limit={memLimit}
- format={fmtBytes}
- />
- </div>
- </ColumnLayout>
- </Container>
-
- <LogsPanel
- namespace={launcher?.metadata.namespace}
- podName={launcher?.metadata.name}
- container={LOG_CONTAINER}
- title="Logs (guest console)"
- waitingText="Waiting for launcher pod…"
- />
-
- {launcherError && !launcherLoading && !launcher && (
- <Box color="text-status-warning" textAlign="center" padding="m">
- <SpaceBetween size="xs">
- <b>Couldn't find the launcher pod</b>
- <Box variant="small">
- <code>{launcherError}</code>
- </Box>
- </SpaceBetween>
- </Box>
- )}
-
- <Modal
- visible={confirmingRestart}
- onDismiss={() => { if (!restarting) setConfirmingRestart(false) }}
- header={`Restart ${vmName}?`}
- footer={
- <Box float="right">
- <SpaceBetween direction="horizontal" size="xs">
- <Button
- onClick={() => setConfirmingRestart(false)}
- disabled={restarting}
- >
- Cancel
- </Button>
- <Button
- variant="primary"
- onClick={restart}
- loading={restarting}
- >
- Restart
- </Button>
- </SpaceBetween>
- </Box>
- }
- >
- This will restart replica <b>{vmName}</b> via the KubeVirt subresource
- API (equivalent to <code>virtctl restart {vmName}</code>). The VM's
- current instance will be terminated and a fresh one started from the
- same spec. Any in-progress session on this replica will be interrupted.
- </Modal>
- </SpaceBetween>
- )
-}
-
-// ── Metric tile ────────────────────────────────────────────────────────────
-
-function MetricTile({
- loading,
- error,
- value,
- limit,
- format,
-}: {
- loading: boolean
- error: string | null
- value: number | undefined
- limit: number | null
- format: (n: number) => string
-}) {
- if (loading) {
- return (
- <Box textAlign="center" padding="m">
- <Spinner /> Loading metrics…
- </Box>
- )
- }
- if (error) {
- return (
- <Box color="text-body-secondary" padding="m">
- <StatusIndicator type="warning">{error}</StatusIndicator>
- </Box>
- )
- }
- if (value === undefined) return null
- const denom = limit ?? 0
- const pct = denom > 0 ? Math.min(100, (value / denom) * 100) : 0
- return (
- <SpaceBetween size="xs">
- <Box variant="h2" fontSize="display-l">
- {format(value)}
- </Box>
- {limit ? (
- <ProgressBar
- value={pct}
- additionalInfo={`${format(value)} of ${format(denom)}`}
- />
- ) : (
- <Box variant="small" color="text-body-secondary">
- No limit configured.
- </Box>
- )}
- </SpaceBetween>
- )
-}
-
-function fmtCores(n: number): string {
- return `${n.toFixed(2)} cores`
-}
-
-function fmtBytes(n: number): string {
- if (n >= 1024 ** 3) return `${(n / 1024 ** 3).toFixed(2)} GiB`
- if (n >= 1024 ** 2) return `${(n / 1024 ** 2).toFixed(1)} MiB`
- if (n >= 1024) return `${(n / 1024).toFixed(0)} KiB`
- return `${n} B`
-}
diff --git a/libs/fleet/src/pages/PoolsList.tsx b/libs/fleet/src/pages/PoolsList.tsx
index a2b5a6f6a2..77e97bf46f 100644
--- a/libs/fleet/src/pages/PoolsList.tsx
+++ b/libs/fleet/src/pages/PoolsList.tsx
@@ -9,12 +9,12 @@ import Pagination from "@cloudscape-design/components/pagination"
import PropertyFilter from "@cloudscape-design/components/property-filter"
import SpaceBetween from "@cloudscape-design/components/space-between"
import Table from "@cloudscape-design/components/table"
-import { api } from "../api/cyclops"
+import { deletePool, getPool, listPools } from "../sdk/pools"
import {
derivePoolStatus,
reconcileTombstones,
tombstonePool,
-} from "../api/pools"
+} from "../sdk/status"
import { PoolStatusPill } from "../components/PoolStatus"
import { useFlash } from "../components/FlashContext"
@@ -39,7 +39,7 @@ export function PoolsList() {
const load = async () => {
setLoading(true)
try {
- const poolList = await api.listPools()
+ const poolList = await listPools()
reconcileTombstones(poolList.map(p => p.name))
setRows(
poolList.map(p => ({
@@ -65,7 +65,7 @@ export function PoolsList() {
if (selected.length === 0) return
setBusy(true)
try {
- await Promise.all(selected.map(p => api.deletePool(p.namespace, p.name)))
+ await Promise.all(selected.map(p => deletePool(p.namespace, p.name)))
for (const p of selected) tombstonePool(p.name)
flash.push({
type: "success",
@@ -93,7 +93,7 @@ export function PoolsList() {
if (!src) return
setDuplicating(true)
try {
- const full = await api.getPool(src.namespace, src.name)
+ const full = await getPool(src.namespace, src.name)
navigate("/pools/new", { state: { source: full } })
} catch (e) {
flash.push({
diff --git a/libs/fleet/src/pages/UserApiKeys.tsx b/libs/fleet/src/pages/UserApiKeys.tsx
index 4a2a6d8f7b..ebd375ec17 100644
--- a/libs/fleet/src/pages/UserApiKeys.tsx
+++ b/libs/fleet/src/pages/UserApiKeys.tsx
@@ -22,11 +22,13 @@ import Multiselect, {
import SpaceBetween from "@cloudscape-design/components/space-between"
import Table from "@cloudscape-design/components/table"
import {
- type UserApiKey,
+ createUserKey,
+ deleteUserKey,
+ listUserKeys,
type NewUserApiKey,
- userKeysApi,
- namespacesApi,
-} from "../api/cyclops"
+ type UserApiKey,
+} from "../sdk/userKeys"
+import { listNamespaces } from "../sdk/pools"
export function UserApiKeys() {
const [keys, setKeys] = useState<UserApiKey[]>([])
@@ -45,8 +47,8 @@ export function UserApiKeys() {
setLoading(true)
try {
const [userKeys, namespaces] = await Promise.all([
- userKeysApi.list(),
- namespacesApi.list().catch(() => []),
+ listUserKeys(),
+ listNamespaces().catch(() => []),
])
setKeys(userKeys)
setNsOptions(
@@ -71,7 +73,7 @@ export function UserApiKeys() {
setCreating(true)
try {
const scope = selectedScope.map(o => o.value!).filter(Boolean)
- const k = await userKeysApi.create(
+ const k = await createUserKey(
name,
scope.length > 0 ? scope : undefined,
)
@@ -88,7 +90,7 @@ export function UserApiKeys() {
const remove = async (id: string) => {
try {
- await userKeysApi.remove(id)
+ await deleteUserKey(id)
setConfirmRevoke(null)
await refresh()
} catch (e) {
@@ -146,7 +148,7 @@ export function UserApiKeys() {
items={keys}
columnDefinitions={[
{ id: "name", header: "Name", cell: r => r.name },
- { id: "client_id", header: "Client ID", cell: r => <code>{r.client_id}</code> },
+ { id: "client_id", header: "Client ID", cell: r => <code>{r.clientId}</code> },
{
id: "scope",
header: "Scope",
@@ -191,8 +193,8 @@ export function UserApiKeys() {
<FormField label="Client ID">
<CopyToClipboard
variant="inline"
- textToCopy={created.client_id}
- textToDisplay={<code>{created.client_id}</code>}
+ textToCopy={created.clientId}
+ textToDisplay={<code>{created.clientId}</code>}
copyButtonAriaLabel="Copy client ID"
copySuccessText="Client ID copied"
copyErrorText="Failed to copy"
@@ -201,8 +203,8 @@ export function UserApiKeys() {
<FormField label="Client Secret">
<CopyToClipboard
variant="inline"
- textToCopy={created.client_secret}
- textToDisplay={<code>{created.client_secret}</code>}
+ textToCopy={created.clientSecret}
+ textToDisplay={<code>{created.clientSecret}</code>}
copyButtonAriaLabel="Copy client secret"
copySuccessText="Client secret copied"
copyErrorText="Failed to copy"
diff --git a/libs/fleet/src/sdk/claims.ts b/libs/fleet/src/sdk/claims.ts
new file mode 100644
index 0000000000..e243a60924
--- /dev/null
+++ b/libs/fleet/src/sdk/claims.ts
@@ -0,0 +1,54 @@
+import type { Claim as SdkClaim, CyclopsClient } from "./generated"
+import { withClient } from "./client"
+import type { Claim } from "./models"
+
+function claimModel(claim: SdkClaim): Claim {
+ return {
+ name: claim.metadata.name,
+ namespace: claim.metadata.namespace,
+ templateRef: claim.spec.sandboxTemplateRef.name,
+ warmpool: claim.spec.warmpool ?? "default",
+ phase: claim.status?.phase ?? "Pending",
+ sandboxName: claim.status?.sandbox?.name,
+ sandboxService: claim.status?.sandbox?.service,
+ createdAt: claim.metadata.creationTimestamp ?? "",
+ }
+}
+
+async function findClaim(
+ client: CyclopsClient,
+ namespace: string,
+ name: string,
+): Promise<SdkClaim> {
+ const claim = (await client.listClaims(namespace)).find(
+ candidate => candidate.metadata.name === name,
+ )
+ if (!claim) throw new Error(`Claim ${name} was not found`)
+ return claim
+}
+
+export async function listClaims(namespace: string): Promise<Claim[]> {
+ return withClient(async client =>
+ (await client.listClaims(namespace)).map(claimModel),
+ )
+}
+
+export async function createClaim(namespace: string, poolName: string): Promise<Claim> {
+ return withClient(async client => {
+ const pool = await client.getPool(poolName)
+ if (pool.metadata.namespace !== namespace) {
+ throw new Error(`Pool ${poolName} belongs to namespace ${pool.metadata.namespace}`)
+ }
+ return claimModel(await client.createClaim({ pool }))
+ })
+}
+
+export async function getClaim(namespace: string, name: string): Promise<Claim> {
+ return withClient(async client => claimModel(await findClaim(client, namespace, name)))
+}
+
+export async function deleteClaim(namespace: string, name: string): Promise<void> {
+ await withClient(async client => {
+ await client.deleteClaim(await findClaim(client, namespace, name))
+ })
+}
diff --git a/libs/fleet/src/sdk/client.ts b/libs/fleet/src/sdk/client.ts
new file mode 100644
index 0000000000..d3d06e8dcb
--- /dev/null
+++ b/libs/fleet/src/sdk/client.ts
@@ -0,0 +1,32 @@
+import { getToken } from "../auth/keycloak"
+import { CyclopsClient, uniffiInitAsync } from "./generated"
+
+const sdkInitialization = uniffiInitAsync()
+
+function baseUrl(): string {
+ return window.location.origin
+}
+
+export async function withClient<T>(
+ operation: (client: CyclopsClient) => Promise<T>,
+): Promise<T> {
+ await sdkInitialization
+ const token = await getToken()
+ if (!token) throw new Error("Authentication token is unavailable")
+
+ const client = CyclopsClient.connectBrowserWithAccessToken(
+ {
+ baseUrl: baseUrl(),
+ poolPollIntervalMs: 5_000n,
+ poolPollLimit: 120,
+ claimPollIntervalMs: 5_000n,
+ claimPollLimit: 120,
+ },
+ token,
+ ) as CyclopsClient
+ try {
+ return await operation(client)
+ } finally {
+ client.uniffiDestroy()
+ }
+}
diff --git a/libs/fleet/src/sdk/generated.ts b/libs/fleet/src/sdk/generated.ts
new file mode 100644
index 0000000000..6cca520300
--- /dev/null
+++ b/libs/fleet/src/sdk/generated.ts
@@ -0,0 +1 @@
+export * from "../../sdk-bindings/ts-uniffi-browser/ts/index.web"
diff --git a/libs/fleet/src/sdk/models.ts b/libs/fleet/src/sdk/models.ts
new file mode 100644
index 0000000000..5c6be58a6e
--- /dev/null
+++ b/libs/fleet/src/sdk/models.ts
@@ -0,0 +1,50 @@
+export interface PoolService {
+ name: string
+ targetPort: number
+ protocol: string
+}
+
+export interface PoolAutoscalingConfig {
+ minPoolSize?: number
+ initialPoolSize?: number
+ maxPoolSize?: number
+}
+
+export interface PoolTemplateConfig {
+ cpu: number
+ ram: string
+ ociImage: string
+ replicas: number
+ firmware?: "bios" | "efi"
+ services?: PoolService[]
+ probes?: {
+ readinessProbe?: Record<string, unknown>
+ livenessProbe?: Record<string, unknown>
+ }
+ autoscaling?: PoolAutoscalingConfig
+}
+
+export interface PoolSummary {
+ name: string
+ namespace: string
+ replicas: number
+ phase: string
+ availableCount: number
+}
+
+export interface PoolData extends PoolSummary, PoolTemplateConfig {
+ services: PoolService[]
+ totalCount: number
+ claimedCount: number
+}
+
+export interface Claim {
+ name: string
+ namespace: string
+ templateRef: string
+ warmpool: string
+ phase: string
+ sandboxName?: string
+ sandboxService?: string
+ createdAt: string
+}
diff --git a/libs/fleet/src/sdk/pools.ts b/libs/fleet/src/sdk/pools.ts
new file mode 100644
index 0000000000..c672f53d59
--- /dev/null
+++ b/libs/fleet/src/sdk/pools.ts
@@ -0,0 +1,180 @@
+import {
+ Firmware,
+ PreservedJson,
+ ServiceProtocol,
+ type CyclopsClient,
+ type Namespace,
+ type Pool,
+ type Template,
+} from "./generated"
+import { withClient } from "./client"
+import { deriveWarmPoolPhase } from "./status"
+import type {
+ PoolData,
+ PoolService,
+ PoolSummary,
+ PoolTemplateConfig,
+} from "./models"
+
+function serviceProtocol(protocol: ServiceProtocol | undefined): string {
+ return protocol === ServiceProtocol.Udp ? "UDP" : "TCP"
+}
+
+function sdkProtocol(protocol: string): ServiceProtocol {
+ return protocol.toUpperCase() === "UDP"
+ ? ServiceProtocol.Udp
+ : ServiceProtocol.Tcp
+}
+
+function parseProbes(template: Template): PoolTemplateConfig["probes"] {
+ const probes = template.spec.vmTemplate.probes
+ return probes ? (JSON.parse(probes.toJson()) as PoolTemplateConfig["probes"]) : undefined
+}
+
+function poolSummary(pool: Pool): PoolSummary {
+ return {
+ name: pool.metadata.name,
+ namespace: pool.metadata.namespace,
+ replicas: pool.spec.replicas,
+ phase: deriveWarmPoolPhase(pool.spec.replicas, pool.status),
+ availableCount: pool.status?.readyReplicas ?? 0,
+ }
+}
+
+function poolData(pool: Pool, template: Template): PoolData {
+ const summary = poolSummary(pool)
+ const vm = template.spec.vmTemplate
+ const totalCount = pool.status?.replicas ?? pool.spec.replicas
+ const availableCount = pool.status?.readyReplicas ?? 0
+ return {
+ ...summary,
+ cpu: vm.cpuCores ?? 0,
+ ram: vm.memory ?? "",
+ ociImage: vm.containerDiskImage,
+ firmware: vm.firmware === Firmware.Efi ? "efi" : undefined,
+ services: (vm.services ?? []).map(service => ({
+ name: service.name,
+ targetPort: service.targetPort,
+ protocol: serviceProtocol(service.protocol),
+ })),
+ probes: parseProbes(template),
+ autoscaling: pool.spec.autoscaling,
+ totalCount,
+ availableCount,
+ claimedCount: Math.max(totalCount - availableCount, 0),
+ }
+}
+
+async function listNamespacesWith(client: CyclopsClient): Promise<Namespace[]> {
+ return client.listNamespaces()
+}
+
+export async function listNamespaces(): Promise<Namespace[]> {
+ return withClient(listNamespacesWith)
+}
+
+export async function listPools(): Promise<PoolSummary[]> {
+ return withClient(async client => {
+ const namespaces = await listNamespacesWith(client)
+ const pools = await Promise.all(
+ namespaces.map(async namespace => {
+ try {
+ return await client.listPools(namespace.name)
+ } catch {
+ return []
+ }
+ }),
+ )
+ return pools.flat().map(poolSummary).sort((a, b) => a.name.localeCompare(b.name))
+ })
+}
+
+async function getPoolWith(
+ client: CyclopsClient,
+ namespace: string,
+ name: string,
+): Promise<{ pool: Pool; template: Template }> {
+ const pool = await client.getPool(name)
+ if (pool.metadata.namespace !== namespace) {
+ throw new Error(`Pool ${name} belongs to namespace ${pool.metadata.namespace}`)
+ }
+ const template = await client.getTemplate(
+ namespace,
+ pool.spec.sandboxTemplateRef.name,
+ )
+ return { pool, template }
+}
+
+export async function getPool(namespace: string, name: string): Promise<PoolData> {
+ return withClient(async client => {
+ const resources = await getPoolWith(client, namespace, name)
+ return poolData(resources.pool, resources.template)
+ })
+}
+
+function sdkServices(services: PoolService[] | undefined) {
+ return services?.map(service => ({
+ name: service.name,
+ targetPort: service.targetPort,
+ protocol: sdkProtocol(service.protocol),
+ }))
+}
+
+export async function createPool(
+ name: string,
+ values: PoolTemplateConfig,
+): Promise<PoolData> {
+ return withClient(async client => {
+ const templateName = `${name}-template`
+ const pool = await client.createPool({
+ namespace: name,
+ spec: {
+ replicas: values.replicas,
+ sandboxTemplateRef: { name: templateName },
+ autoscaling: values.autoscaling,
+ },
+ })
+ try {
+ const template = await client.createTemplate({
+ namespace: name,
+ name: templateName,
+ spec: {
+ vmTemplate: {
+ containerDiskImage: values.ociImage,
+ imagePullSecret: "ecr-credentials",
+ cpuCores: values.cpu,
+ memory: values.ram,
+ firmware: values.firmware === "efi" ? Firmware.Efi : undefined,
+ probes: values.probes
+ ? PreservedJson.fromJson(JSON.stringify(values.probes))
+ : undefined,
+ services: sdkServices(values.services),
+ },
+ },
+ })
+ return poolData(pool, template)
+ } catch (error) {
+ await client.deletePool(pool).catch(() => undefined)
+ throw error
+ }
+ })
+}
+
+export async function updatePoolServices(
+ namespace: string,
+ name: string,
+ services: PoolService[],
+): Promise<void> {
+ await withClient(async client => {
+ const { template } = await getPoolWith(client, namespace, name)
+ template.spec.vmTemplate.services = sdkServices(services)
+ await client.updateTemplate(template)
+ })
+}
+
+export async function deletePool(namespace: string, name: string): Promise<void> {
+ await withClient(async client => {
+ const { pool } = await getPoolWith(client, namespace, name)
+ await client.deletePool(pool)
+ })
+}
diff --git a/libs/fleet/src/api/pools.ts b/libs/fleet/src/sdk/status.ts
similarity index 61%
rename from libs/fleet/src/api/pools.ts
rename to libs/fleet/src/sdk/status.ts
index 4fc3544d04..efa84125ed 100644
--- a/libs/fleet/src/api/pools.ts
+++ b/libs/fleet/src/sdk/status.ts
@@ -1,3 +1,17 @@
+export interface WarmPoolObservedStatus {
+ replicas?: number
+ readyReplicas?: number
+}
+
+export function deriveWarmPoolPhase(
+ specReplicas: number,
+ status: WarmPoolObservedStatus | undefined,
+): "Ready" | "Provisioning" {
+ if (!status) return "Provisioning"
+ const expected = status.replicas ?? specReplicas
+ return (status.readyReplicas ?? 0) >= expected ? "Ready" : "Provisioning"
+}
+
const tombstones = new Set<string>()
export function tombstonePool(name: string): void {
@@ -6,7 +20,9 @@ export function tombstonePool(name: string): void {
export function reconcileTombstones(present: Iterable<string>): void {
const names = new Set(present)
- for (const t of tombstones) if (!names.has(t)) tombstones.delete(t)
+ for (const tombstone of tombstones) {
+ if (!names.has(tombstone)) tombstones.delete(tombstone)
+ }
}
export function isTombstoned(name: string): boolean {
@@ -24,9 +40,7 @@ export function derivePoolStatus(pool: { name: string; phase: string }): PoolSta
return { kind: "terminating", label: "Terminating" }
}
const phase = (pool.phase ?? "").toLowerCase()
- if (phase === "ready") {
- return { kind: "healthy", label: "Healthy" }
- }
+ if (phase === "ready") return { kind: "healthy", label: "Healthy" }
if (phase === "provisioning") {
return { kind: "provisioning", label: "Provisioning" }
}
diff --git a/libs/fleet/src/sdk/userKeys.ts b/libs/fleet/src/sdk/userKeys.ts
new file mode 100644
index 0000000000..a3ed421512
--- /dev/null
+++ b/libs/fleet/src/sdk/userKeys.ts
@@ -0,0 +1,21 @@
+import type { NewUserApiKey, UserApiKey } from "./generated"
+import { withClient } from "./client"
+
+export type { NewUserApiKey, UserApiKey } from "./generated"
+
+export async function listUserKeys(): Promise<UserApiKey[]> {
+ return withClient(client => client.listUserApiKeys())
+}
+
+export async function createUserKey(
+ name: string,
+ scope?: string[],
+): Promise<NewUserApiKey> {
+ return withClient(client =>
+ client.createUserApiKey({ name, scope: scope ?? [] }),
+ )
+}
+
+export async function deleteUserKey(id: string): Promise<void> {
+ await withClient(client => client.deleteUserApiKey(id))
+}
diff --git a/libs/fleet/vite.config.ts b/libs/fleet/vite.config.ts
index 71c99a26c3..0c88442db0 100644
--- a/libs/fleet/vite.config.ts
+++ b/libs/fleet/vite.config.ts
@@ -9,6 +9,7 @@ const ORCH_API = process.env.ORCH_API ?? "https://cyclops-cs.tail204509.ts.net"
export default defineConfig({
plugins: [react()],
+ assetsInclude: ["**/*.wasm"],
// @novnc/novnc (1.7+) uses top-level await; es2020 (esbuild's default here)
// rejects it. es2022 is supported by all evergreen browsers the app targets.
build: { target: "es2022" },