# SciFlow AI API Guide

This guide is written for AI agents and API clients that need to discover and use the SciFlow control-plane APIs safely.

## Discovery

Use the gateway discovery document first:

- Gateway API docs: `/api-docs`
- Agent discovery: `/llms.txt`
- Service index: `/api-docs.json`

Each service also exposes its own OpenAPI document at `/openapi.json`. Through the gateway, use these service-scoped specs:

| Service | Gateway OpenAPI URL | Responsibility |
| --- | --- | --- |
| orchestrator | `/sciflow/orchestrator/openapi.json` | Templates, instance requests, instances, jobs, logs, inventory, and Flux reconciliation. |
| policy | `/sciflow/policy/openapi.json` | User profile, SSH keys, env vars, orgs, quota, admission, storage, platform settings, and support tickets. |
| images | `/sciflow/images/openapi.json` | Image records, image commits, image persistence, registry verification, and image operation state. |
| operations | `/sciflow/operations/openapi.json` | Image worker job queue visibility, worker manifests, and worker job refresh. |
| reporting | `/sciflow/reporting/openapi.json` | Billing settings, GPU pricing, usage summaries, and reporting status. |

Prefer the OpenAPI documents for exact paths, schemas, required fields, response bodies, and enum values. Use this guide for workflow and safety context that does not fit cleanly in a schema.

## Authentication

SciFlow expects requests to arrive behind the platform auth layer. Browser clients normally rely on forwarded auth headers and cookies. API clients may use bearer tokens where the deployment enables token introspection.

Do not invent identity headers. If an endpoint returns `401` or `403`, stop and ask the user to authenticate or grant access rather than retrying with guessed credentials.

## API Scope

Paths under `/api/v2` are user-facing or admin-facing product APIs. Paths under `/api/internal` are service-to-service APIs and should not be called by a general user agent unless the user explicitly asks for internal diagnostics or maintenance.

When routing through the gateway, prefer the service prefixes shown in the discovery document. When calling a service directly, use the raw paths from that service's OpenAPI document.

## Safety Rules

Treat these operations as read-only and safe to call after normal auth:

- `GET` list, get, status, inventory, usage, and log endpoints.
- Admission-check endpoints that only validate a proposed request.

Ask for explicit user confirmation before calling endpoints that mutate state:

- `POST`, `PUT`, or `DELETE` endpoints unless the user has already given a clear instruction for that exact action.
- Instance lifecycle actions such as start, stop, and delete.
- Image commit, persist, transition, registry verification, and worker refresh operations.
- Quota, org membership, platform config, SMTP, registry, invitation, and Authentik token updates.
- Flux reconciliation updates.

Never call internal transition endpoints speculatively. They can advance durable state machines. GPU quota release is handled automatically through Kueue Workload lifecycle.

## Common Workflows

### Inspect Current User And Org Context

1. Call `policy` `GET /api/v2/me`.
2. Call `policy` `GET /api/v2/orgs/current` or list orgs if the user needs to choose an org.
3. Use the selected org identifier when APIs expose org-scoped query parameters.

### Launch Or Validate An Instance Request

1. List templates with `orchestrator` template endpoints.
2. Inspect template versions before choosing launch parameters.
3. Use the validation endpoint before creating a real instance request when the user is exploring options.
4. Create the instance request only after the user confirms the template, org, resource shape, and overrides.
5. Poll the request and resulting instance until the state reaches a terminal or runnable state.

### Inspect Instance Logs

1. List or get the instance through `orchestrator`.
2. Use the instance log endpoints for runtime logs.
3. Use platform log search only when the user asks for broader diagnostics.

### Inspect Workload Admission And Placement

1. Get the instance, job, or training run to confirm that it is visible to the caller.
2. Call `orchestrator` `GET /api/v2/workloads/{workload_kind}/{workload_id}/status` with `instance`, `job`, or `training`.
3. Treat `admission` as the Kueue quota decision and `scheduling` as the Volcano or Kubernetes placement decision.
4. Do not infer a numeric queue position; Kueue reports admission state and reasons, not a stable rank.

### Commit Or Persist Images

1. Read the source instance and current image operation state first.
2. Check for active operations before creating a new commit.
3. Create the image commit only after the user confirms the target image reference.
4. Poll `images` image-operation endpoints for durable operation status.
5. Use `operations` worker job endpoints only when diagnosing the background execution path.

### Diagnose Worker Jobs

1. Start from `images` image operation status.
2. Use `operations` queue status and worker job lookup for execution details.
3. Refresh worker job state only after confirming it is safe to query Kubernetes-backed execution status.

### Billing And Usage

1. Use `reporting` status endpoints first to verify sync health.
2. Use usage summary endpoints for read-only reporting.
3. Ask for confirmation before changing billing settings or GPU type prices.

## Error Handling

Use status codes and response schemas from the OpenAPI documents. In general:

- `400` means the request shape or business input is invalid. Correct the payload; do not retry unchanged.
- `401` means authentication is missing. Ask the user to authenticate.
- `403` means authorization is missing. Do not retry with a different scope unless the user explicitly changes context.
- `404` means the resource does not exist or is not visible to the caller.
- `409` means a state conflict, such as an already-active operation or stale transition.
- `503` means a dependency is unavailable. Retry only if the user wants to wait or diagnose service health.

For long-running operations, prefer polling the durable operation or request resource over retrying the original mutation.

## Agent Output Expectations

When reporting API actions back to the user, include:

- The service and operation called.
- The resource identifiers returned by the API.
- Whether the action was read-only or mutating.
- Any follow-up polling or confirmation needed.
