# 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, workload and image-commit 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-operation coordinator queue health. |
| 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.

SciFlow's built-in agent API tools expose this documentation through `sciflow_get_guide`, `sciflow_search_operations`, and `sciflow_get_operation`. Use those tools instead of guessing a path or request shape. `sciflow_http` can call documented public operations. Reads run without approval. Mutations pause for durable user approval when the Codex approval policy is On Request and run immediately when it is Never. The permission profile independently controls filesystem and network access.

The agent session is already bound to one organization. Discovery results expose that organization as `session_org_id`, and `sciflow_http` injects it into documented `org_id` query parameters and top-level JSON request-body fields. Do not ask the user to look up or paste an organization UUID.

## 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.

Treat these endpoints as mutations. Call the tool directly; SciFlow's executor performs the approval pause when required:

- `POST`, `PUT`, `PATCH`, or `DELETE` endpoints.
- Instance lifecycle actions such as start, stop, and delete.
- Image commit, persist, transition, and registry verification operations.
- Quota, org membership, platform config, SMTP, registry, invitation, and Authentik token updates.
- Flux reconciliation updates.

The approval policy defines the mutation prompt boundary. With On Request, every mutation presents its documented operation, method, path, and affected scope for approval. With Never, mutations execute without pausing but remain constrained to documented public paths, the authenticated user, and the session organization.

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 visible templates with `orchestrator` as soon as the user asks to launch or spawn an instance. This read requires no approval. The tool supplies the bound session organization as a catalog context, so the response contains visible global templates plus templates scoped to the chat organization.
2. Match a template the user named. For an underspecified launch, use the first visible template with a default version, matching the web launch form; ask only if no usable template exists or the user's requirements do not resolve to one template. Never ask the user for a template hash ID; retain the selected default version's `hash_id` for the API call.
3. Treat the template list as the authoritative set of launchable templates. Never infer that a template is currently available from historical instance or request snapshots; those records may refer to deleted or private templates the caller cannot launch.
4. Inspect template versions, compute shapes, and visible images before choosing launch parameters. Loading the image catalog on every launch makes newly published builds available without requiring the user to provide a registry reference. Use the selected visible template's default version and the first active compute shape when the user did not request overrides, matching the web launch form; do not copy stale resource values from workload history.
5. Use the template version image by default. When the user requests a named image, build date, or the latest matching image, select an active published image record and pass its exact `id` as `image_id`. Never invent or pass a raw registry reference as the override. The template still supplies ports, optional apps, environment, and startup configuration.
6. Use the validation endpoint before creating a real instance request when the user is exploring options.
7. An explicit request to launch, spawn, or create an instance is sufficient intent to begin this workflow. Once a template and compute shape are resolved, call the mutation directly; do not ask for duplicate confirmation in chat. The session approval policy handles any required confirmation.
8. 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.

### Execute Commands In An Instance

1. Read the selected template's README and inspect the current image record when one is available. Image records expose advisory `runtime_hints`; do not infer runtime paths from an image name.
2. Treat every runtime hint as unverified image metadata. Prefer a hinted absolute executable when it exists, and otherwise discover the executable from `PATH`.
3. For Python package operations, invoke the hinted Python executable with `-m pip`. Shell activation is unnecessary for non-interactive exec requests.
4. A changed `current_image` may carry different hints than the original template image. Prefer metadata for `current_image` over historical template documentation.

### Inspect And Chart Telemetry

1. Resolve whether the request targets one workload, the current user's labeled series, or the whole organization before choosing the instance, job, training, or organization telemetry operation.
2. Compare the requested window with the first and last returned timestamp for every series. Report uncovered portions as missing telemetry; never treat missing samples as zero.
3. Keep series with different resource IDs separate even if their display names match. If the user asks for an aggregate, state the aggregation explicitly.
4. Chart only returned timestamps. Do not extend lines across missing intervals, and do not claim a response was truncated unless the tool reports truncation.
5. Summarize zero utilization as zero only over the interval actually covered by samples.

### Display Grafana Panels

1. Call `GET /api/v2/platform/grafana/panels`; it is the authoritative catalog of panels provisioned from Grafana dashboard ConfigMaps and is already filtered to the session owner's permissions.
2. Use `query` to match dashboard titles, tags, panel titles, and visualization types. Use `offset` when `total` exceeds the number of returned panels.
3. Pass the selected panel's `embed_url` unchanged to `render_iframe`. Never invent dashboard UIDs, panel IDs, or Grafana URLs.
4. If no matching panel is returned, explain that none is available to the owner. Never work around the catalog with a remembered or constructed Grafana URL.

### 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. Follow the linked image-commit job through `orchestrator` when diagnosing background execution.

### Diagnose Worker Jobs

1. Start from `images` image operation status and its `worker_job_id`.
2. Get the job through `orchestrator` for execution state and logs.
3. Use `operations` queue status only to diagnose coordinator health.

### 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.
