Metadata-Version: 2.5
Name: dryv-api
Version: 0.1.0
Summary: Network wrapper and orchestrator for Dryv capabilities
License: Apache-2.0
Requires-Python: >=3.11
Requires-Dist: aiohttp<4,>=3.11
Requires-Dist: dryv
Requires-Dist: httpx<1,>=0.28
Requires-Dist: pyyaml<7,>=6.0
Requires-Dist: websockets<17,>=15
Description-Content-Type: text/markdown

# Dryv API

The Dryv API is the client-facing process/network boundary for Dryv. It exposes Dryv operations and coordinates client environment capabilities while keeping Engine, renderer, provider-process, and filesystem details behind explicit contracts.

The API is **not** a second semantic model. Canonical software meaning remains owned by the Dryv Runtime/Engine.

Package registry and knowledge/content routes belong to Platform and are not served by this API. The CLI reads public package metadata and archives from `DRYV_PLATFORM_URL`; Platform owns namespaces, publication, private access, docs publication, and public knowledge delivery. Dryv keeps the pack descriptor contract and local/Git pack support.

## Public client surface

```text
GET    /
POST   /v1/prepare
POST   /v1/validate
POST   /v1/plan
WS     /v1/generate

WS     /v1/authoring/{sessionId}/{buildId}
DELETE /v1/authoring/{sessionId}/{buildId}

POST   /v1/builds/{sessionId}/{buildId}/validate
POST   /v1/builds/{sessionId}/{buildId}/plan
WS     /v1/builds/{sessionId}/{buildId}/generate
```

## API-key access (implemented foundation)

The API requires an `Authorization: Bearer …`
key for every HTTP route except the public `GET` and `HEAD /health` checks; discovery requires a key. WebSockets authenticate with a first text frame
`{"type":"api.auth","key":"…"}` before the route protocol begins and return `auth.ok`
or a typed authentication failure. The auth frame is capped at 8 KiB and the handshake
times out after five seconds. At most 64 upgraded WebSocket connections may wait for
authentication at once by default; excess attempts receive HTTP 503 with `Retry-After: 1`
before upgrade. Configure this process-wide ceiling with
`DRYV_API_UNAUTHENTICATED_WEBSOCKET_HANDSHAKES` or
`--unauthenticated-websocket-handshakes`.

The Engine API has no database. Customer accounts, persistent keys and hosted usage belong to the
Dryv Platform, whose gateway calls a private Engine with one service key. A secured private Engine uses a single static key of at least 32 characters: set `DRYV_API_STATIC_KEY` or pass `--static-api-key`. This mode validates the key in constant time and keeps request-rate and generation-concurrency limits in process memory; usage is not persisted, and key rotation takes an Engine restart. Configure the Platform gateway's `ENGINE_API_KEY` to the same secret as `DRYV_API_STATIC_KEY` on the private Engine. The Engine also accepts `ENGINE_API_KEY` as an alias when using a shared gateway/Engine secret file; `DRYV_API_STATIC_KEY` takes precedence. Keep that Engine origin on a private network.

For local Engine development without authentication, leave `DRYV_API_STATIC_KEY` unset and pass `--insecure-no-auth` (or set `DRYV_API_INSECURE_NO_AUTH=1`); that mode accepts any key and must not be exposed to a network. A configured static key takes precedence over the insecure flag. Defaults are
60 authenticated requests per key per minute, two concurrent generations per key, a 64 MiB
per-key request budget plus the global HTTP/WebSocket ceiling, and a five-minute generation
timeout. Rate, concurrency and timeout defaults can be set through `DRYV_API_REQUESTS_PER_KEY_PER_MINUTE`,
`DRYV_API_CONCURRENT_GENERATIONS_PER_KEY`, and `DRYV_API_GENERATION_TIMEOUT_SECONDS`, or the
matching `serve` flags. The request-size ceiling uses the existing
`DRYV_API_MAX_REQUEST_SIZE_MB` setting. Backup/restore procedure and broad host integration remain
unfinished. API-key tests cover route authentication,
limits, generation timeout and absence of API key material from captured HTTP/WebSocket logs
in `tests/server/test_api_keys.py`. Authenticated validation also preserves Engine-owned
operation-policy diagnostics, and the route-level concurrency test verifies that a second
generation is denied while the per-key slot is occupied. Malformed/oversized auth frames and
expired/revoked-key rejection are covered there as well. The global unauthenticated WebSocket
connection limit is configurable and tested across generation, authored-build generation,
authoring, and client sessions. CLI credential integration is
covered by the Platform CLI tests, and VS Code origin-scoped SecretStorage and transport auth are
covered by the Platform VS Code extension tests (`credentials.test.ts`, `clientSessionAuth.test.ts`, and
`apiWebSocketAuth.test.ts`). Do not treat the current implementation as a complete hosted-access
feature or deploy it as one. PostgreSQL backup and restore procedures remain operator-owned and
unfinished. Discovery requires an API key, and browser
CORS stays disabled by default under the owner's 2026-11-05 decision. Authenticated client
WebSockets recheck key status every 10 seconds and close with policy code 1008 after revocation
or expiry; the approved maximum is 30 seconds.

The API uses Engine-owned contracts from `dryv.contracts.engine`, `dryv.contracts.engine.environment`, and the Runtime-owned authoring ingestion implementation. It does not define competing validation, planning, or Runtime IR semantics.

## Virtual project boundary

Clients provide project resources as a typed virtual workspace. A virtual path is data, not permission for the API or Engine to access a caller filesystem.

```text
EngineProject
├── entrypoint: dryv.yaml
└── workspace
    └── files
        ├── dryv.yaml
        ├── dryv.py
        ├── dryv.author.yaml  # current internal author-provider resource
        ├── packs/types/dryv.pack.yaml
        └── packs/types/templates/schema.j2
```

The client may gather project resources from a local filesystem, browser editor, archive, connected workspace, or another source. `dryv.author.yaml` is author-provider metadata, not a second semantic model. The current authoring preparation flow may carry it as a virtual workspace resource; the intended user-facing project configuration remains `dryv.yaml`, while provider manifests live with authoring implementations under `plugins/authoring/<language>/`. Transport code converts supplied resources into the canonical `VirtualWorkspace` contract.

The Engine starts at `entrypoint` and interprets Dryv relationships itself. The API does not parse pack semantics, select templates, or decide what authored declarations mean.

## Discovery

`GET /` returns:

- API protocol/version;
- the observed URL of the running API server;
- API orchestration capabilities;
- Engine operations;
- supported Dryv document versions;
- supported virtual workspace file kinds;
- supported Environment Protocol versions;
- supported Authoring Protocol versions;
- supported Runtime IR versions;
- the Template Servers currently connected by the API.

Each connected Template Server entry exposes operational discovery data only:

```text
kind
name
version
protocol_version
ready
url
websocket_url
session_url
capabilities
```

Local descriptor paths and process launch commands are intentionally not exposed to API clients.

The default runnable API eagerly connects its configured Jinja and Handlebars Template Servers during startup. Template Server configuration comes from server manifests; the source checkout uses `source/engine/python/api/dryv.server.yaml`. See `.tasks/docs/reference/servers.md`. This makes the root discovery response describe real live connections rather than merely configured names, and makes connection failures visible before generation starts.

This lets a client reject incompatible compositions before doing work and inspect which renderer services are actually available.

## Prepare and Environment Protocol

`POST /v1/prepare` asks the Engine what the selected Dryv project requires from the caller environment.

For authored sources this can produce requirements such as:

```text
package.inspect
package.install
provider.ensure
resource.read
```

The client executes those machine-local operations only if it advertises the capability and, where required, the user approves the mutation. Results return as typed environment facts. The Engine consumes those facts and either asks for another requirement, blocks with diagnostics, or returns a ready `AuthoringExecutionPlan`.

The API coordinates this exchange; it does not install packages or infer language-specific execution rules itself.

## Authoring stream

Once preparation returns an authoring execution plan, the client launches the resolved compiler/provider and streams its Dryv Authoring Protocol JSONL frames to:

```text
WS /v1/authoring/{sessionId}/{buildId}
```

The API forwards bounded frames to Runtime-owned ingestion. Runtime validates:

- provider/protocol negotiation;
- Runtime IR version negotiation;
- session correlation;
- begin/batch/end ordering;
- batch sequence numbers;
- typed canonical record payloads;
- duplicate canonical identities;
- final item count;
- deterministic semantic SHA-256 digest;
- final canonical Runtime IR semantic validation.

Only after a valid explicit `end` barrier does the API report `authoring.completed`.

Completed authored builds are retained in a bounded in-process Runtime store until consumed or explicitly discarded. Clients can release an unused build with:

```text
DELETE /v1/authoring/{sessionId}/{buildId}
```

## Continuing an authored build

Canonical Runtime IR does **not** travel back through the CLI after authoring.

For a completed build, the client calls the build-specific form of the normal Engine operation:

```text
POST /v1/builds/{sessionId}/{buildId}/validate
POST /v1/builds/{sessionId}/{buildId}/plan
WS   /v1/builds/{sessionId}/{buildId}/generate
```

The request still contains the original `EngineProject`. The API uses the build correlation only to retrieve the completed typed `DryvIR`, then asks the Engine-owned authoring materializer to create an equivalent in-memory project view:

```text
original dryv.yaml
source.type = author
        +
completed typed DryvIR
        ↓ Engine-owned materialization
virtual dryv.yaml
source.type = ir
source.path = .dryv/runtime/<build>.ir.json
        +
virtual canonical IR resource
        ↓
same Engine validate / plan / generate operation
```

This transformation never mutates the caller filesystem. It exists only for the downstream Engine operation.

The architectural rule is:

```text
CLI coordinates execution.
API correlates process/network state.
Runtime owns canonical IR and the author→IR continuation.
The same Engine operation owns validation, planning, and generation afterward.
```

There is no separate authored-generation engine and no API-owned semantic interpretation.

A completed build is consumed by a downstream operation. A client that wants a separate operation can perform another deterministic authoring build, which also avoids keeping canonical semantic state indefinitely in the API process.

## Validate

`POST /v1/validate` accepts the canonical `ValidateRequest` shape for an already Runtime-IR-backed project.

```json
{
  "contract_version": "dryv.engine/v1alpha1",
  "operation": "validate",
  "request_id": "validate-100",
  "project": {
    "entrypoint": "dryv.yaml",
    "workspace": {
      "files": [
        {
          "kind": "text",
          "path": "dryv.yaml",
          "content": "version: dryv/v1alpha1\nsource:\n  type: ir\n  path: dryv.ir.yaml\n"
        },
        {
          "kind": "text",
          "path": "dryv.ir.yaml",
          "content": "version: dryv.ir/v1alpha1\nkey: example\ninfo:\n  title: Example\n  version: v1\n"
        }
      ]
    }
  }
}
```

For authored projects the same request shape is sent to the build-specific validate route after authoring completes.

## Plan

`POST /v1/plan` returns `PlanResult`. Planned artifacts carry explicit pack/artifact identity, role, action, project-relative path, dependency paths, and trace references. Planning does not mutate a filesystem.

The build-specific plan route performs the same operation after Runtime materializes the completed authored IR.

## Generate

Connect to `WS /v1/generate` or the build-specific generation route and send one `generation.start` message containing the canonical `GenerateRequest`.

The API streams typed events:

```text
generation.started
generation.diagnostic
artifact.started
artifact.chunk
artifact.completed
generation.completed
```

`artifact.started` declares the stable artifact `id` and whether the artifact is `text`, `binary`, or `delete`. The `id` is the Engine planner artifact identity; it matches `PlannedArtifact.id` and `GenerationTrace.artifacts[].artifact`. Text chunks use `encoding: "text"`. Binary chunks are base64 encoded only at the API transport boundary and use `encoding: "base64"`; the Engine contract itself keeps binary content as `bytes`.

The CLI decodes binary chunks before comparing or writing project output, so base64 transport data is never written as source bytes accidentally.

A failed Engine operation terminates semantically with `generation.failed`. The client decides whether returned artifacts are previewed, buffered, or applied.

## Internal boundary

```text
client / dryv CLI
  ↓ Environment + API protocols
Dryv API
  ↓ Engine-owned typed contracts
Engine / Runtime
  ↓
Canonical Runtime IR
  ↓
pack selection / planning / rendering
```

For authored input an additional process boundary exists before the canonical IR stage:

```text
project Author SDK code
  ↓ project language runtime
Author Compiler / Provider
  ↓ dryv.authoring/v1alpha1
API stream bridge
  ↓
Runtime authoring ingestion
  ↓
Canonical DryvIR
```

The API does not import author SDK declarations, compiler internals, template-language semantics, or caller filesystem APIs.

## Python embedding

Applications that already have an `EnginePort` implementation can host the API directly:

```python
from dryv_api.server import create_app

app = create_app(engine)
```

When the API itself owns a `TemplateRendererAdapter`, pass it explicitly so application startup/cleanup and root discovery track the live Template Server connections:

```python
app = create_app(engine, template_renderer=renderer)
```

## Runnable process

The package installs:

```text
dryv-api serve --engine-factory python.module:create_engine
```

The factory must return an object satisfying `EnginePort`.

The server defaults to `127.0.0.1:8750`; `--host` and `--port` can override that process binding. `--template-server` accepts a server manifest; repeat it to combine manifests. Startup output lists the API URL, discovery URL, and connected Template Server HTTP/WebSocket URLs.

## Typed boundary rule

Known API, Environment, Engine, Authoring, and Template Server discovery messages are typed contracts. Raw JSON exists only at transport/parser boundaries, where it is immediately validated or passed to the Runtime-owned protocol ingestor.

The client-facing API exposes Template Server operational identity and connection endpoints for discovery, but not renderer internals, local descriptor paths, launch commands, template-language semantics, or hidden project mutation behavior.
