> Canonical guide: https://developers.foxlight.ai/build/sdk/reference/application/
> Contract snapshots: Skulk 2.0.0 (b0af39c79b6b7102b2478062904f1d7cc8619975); SDK 1.0.1 (fe6e0f8737ae343769b8cfc0a67ab112b9efac52). Check the installed runtime when versions differ.

# application API

SDK 1.0.1. This reference describes the supported authoring interface.

## `StreamMode`

```python
type StreamMode = Literal['server_streaming', 'client_streaming', 'bidirectional']
```

## `CallErrorCode`

```python
type CallErrorCode = Literal['invalid_payload', 'provider_error', 'timeout', 'denied', 'outcome_unknown', 'cancelled']
```

## `StreamOutputKind`

```python
type StreamOutputKind = Literal['chunk', 'completed', 'failed', 'cancelled']
```

## `ApplicationStartup`

Read-only application settings projected from native-admitted startup.

Protected handshake material is not part of this public projection.
Configuration, serving address and stable app identities are supplied by the
host; they are not inferred from an account or from incoming requests.

### `ApplicationStartup.credentials`

Read declared inputs off-loop, observing rotation on each read.

The reader cannot write, select another backend or resolve undeclared
inputs. Missing required inputs or damaged storage raise a sanitized
CredentialUnavailable; an unconfigured optional input returns None.

```python
def credentials(self) -> CredentialReader:
    ...
```

### `ApplicationStartup.node_id`

Return this actual installed application's persistent identity.

```python
def node_id(self) -> str:
    ...
```

### `ApplicationStartup.host_id`

Return its actual owner identity, independently of Core transport.

```python
def host_id(self) -> str:
    ...
```

### `ApplicationStartup.serve_host`

Return the optional host-selected address; absence means loopback only.

```python
def serve_host(self) -> str | None:
    ...
```

### `ApplicationStartup.configuration`

Return an owned copy of already admitted application settings.

```python
def configuration(self) -> dict[str, JsonValue] | None:
    ...
```

### `ApplicationStartup.operation_bounds`

Return immutable shared limits projected after native manifest admission.

```python
def operation_bounds(self) -> OperationBounds | None:
    ...
```

### `ApplicationStartup.endpoint`

Copy one exact startup-bound descriptor, without granting caller rights.

```python
def endpoint(self, capability_id: str, version: str) -> CapabilityEndpoint:
    ...
```

## `ApplicationSetup`

```python
type ApplicationSetup = Callable[[ApplicationStartup], AbstractAsyncContextManager[None]]
```

## `CallContext`

An immutable copy of host-admitted metadata, not a bearer or a grant.

Obtain this only from an invocation. Exporting or parsing the metadata cannot
activate another call. The host separately rechecks current authority.

### `CallContext.export`

Return an owned projection; modifying it cannot change the admitted call.

```python
def export(self) -> dict[str, JsonValue]:
    ...
```

## `CapabilityEndpoint`

An exact descriptor and installed destination, never an execution grant.

Obtain descriptors through the application's discovery/configuration surface.
The host independently verifies the actual signed destination, original caller
and current policy at dispatch. Readiness is not a permission snapshot.

### `CapabilityEndpoint.from_descriptor`

Copy a descriptor admitted by the explicit compiled portable/2 reader.

```python
def from_descriptor(cls, node_id: str, descriptor: dict[str, JsonValue]) -> CapabilityEndpoint:
    ...
```

### `CapabilityEndpoint.descriptor`

Return an owned descriptor copy, including its exact version and mode.

```python
def descriptor(self) -> dict[str, JsonValue]:
    ...
```

### `CapabilityEndpoint.canonical_descriptor`

Return exact admitted descriptor bytes without implying signed custody.

```python
def canonical_descriptor(self) -> bytes:
    ...
```

### `CapabilityEndpoint.capability_id`

Return the exact declared capability ID from the admitted descriptor.

```python
def capability_id(self) -> str:
    ...
```

### `CapabilityEndpoint.version`

Return the exact declared version without selecting a compatible version.

```python
def version(self) -> str:
    ...
```

### `CapabilityEndpoint.descriptor_revision`

Return the issued portable/2 digest of these immutable descriptor bytes.

```python
def descriptor_revision(self) -> str:
    ...
```

### Fields

```python
node_id: str
```

| Field | Description | Declared defaults and constraints |
| --- | --- | --- |
| `node_id` | — | — |

## `CallReply`

A successful unary response with exact bytes and an owned JSON projection.

### `CallReply.payload`

Return a fresh object; mutations do not change the original response.

```python
def payload(self) -> dict[str, JsonValue]:
    ...
```

### Fields

```python
raw_payload: bytes
```

| Field | Description | Declared defaults and constraints |
| --- | --- | --- |
| `raw_payload` | — | — |

## `CapabilityCallError`

A bounded host error; contains no backend diagnostics or request content.

### `CapabilityCallError.__init__`

Retain only a closed error code, without inferring retry permission.

```python
def __init__(self, code: CallErrorCode) -> None:
    ...
```

## `CallStreamFrame`

One admitted output with exact canonical metadata and separate raw media.

Projections are owned copies; neither metadata nor media is an execution
grant. Terminal frames are exposed only after media/control finalization.

### `CallStreamFrame.projection`

Return an owned metadata copy without changing the admitted bytes.

```python
def projection(self) -> dict[str, JsonValue]:
    ...
```

### `CallStreamFrame.kind`

Return the compiled-admitted chunk or terminal kind.

```python
def kind(self) -> StreamOutputKind:
    ...
```

### `CallStreamFrame.payload`

Return an owned optional JSON result alongside separate media.

```python
def payload(self) -> dict[str, JsonValue] | None:
    ...
```

### Fields

```python
raw_projection: bytes
media: bytes
```

| Field | Description | Declared defaults and constraints |
| --- | --- | --- |
| `raw_projection` | — | — |
| `media` | — | — |

## `CallStream`

One invocation-owned child stream with independently half-closed input.

Obtain this through `async with invocation.stream(...)`. Read to its end;
early close retires the parent because calls/2 has no child-cancel message.
One read and one write may run together, without local queues or replay.

### `CallStream.__init__`

Take an already acquired host-granted channel for this actual parent.

```python
def __init__(self, owner: _Delegations, pending: _PendingDelegation, channel: _CallerStream, descriptor: dict[str, JsonValue], media_call_id: str) -> None:
    ...
```

### `CallStream.open`

Bind SDK-owned media and initialize input; authors use Invocation.stream.

Register custody before the first await so cancellation cannot orphan
a channel whose initial input transition is still being written.

```python
async def open(cls, owner: _Delegations, pending: _PendingDelegation, channel: _CallerStream, descriptor: dict[str, JsonValue], media_call_id: str) -> CallStream:
    ...
```

### `CallStream.mode`

Return the exact descriptor mode accepted by the host.

```python
def mode(self) -> StreamMode:
    ...
```

### `CallStream.finished`

Report local media/end and host control finalization together.

```python
def finished(self) -> bool:
    ...
```

### `CallStream.retire`

Fence operations synchronously and own native teardown until awaited.

```python
def retire(self) -> None:
    ...
```

### `CallStream.close`

Await native teardown; unfinished work also retires its parent.

```python
async def close(self) -> None:
    ...
```

### `CallStream.send`

Send one schema-admitted chunk with separate bounded binary media.

Local structural/schema refusal sends nothing and consumes no sequence.
An interrupted actual write retires the parent and cannot be replayed.

```python
async def send(self, payload: dict[str, JsonValue] | None=None, *, media_metadata: dict[str, JsonValue] | None=None, media: bytes=b'') -> None:
    ...
```

### `CallStream.complete_input`

Half-close caller input while provider output remains independently open.

```python
async def complete_input(self) -> None:
    ...
```

### `CallStream.next_output`

Read one output; terminal success waits for end and delegate_finished.

```python
async def next_output(self) -> CallStreamFrame | None:
    ...
```

## `Invocation`

One startup-bound request with exact bytes and original caller context.

### `Invocation.discover`

Observe destinations within this invocation's original caller permissions.

The host intersects fresh observations with this parent's narrowed scope
and current authorization. Metadata grants no permission. Join discovery
before returning or starting a child call; cancellation drains the query
and retires the parent. There is no bearer substitution, cache or retry.
Older hosts or native cohorts explicitly report unsupported.

```python
async def discover(self) -> CapabilityDirectory:
    ...
```

### `Invocation.version`

Return the exact signed capability version admitted for this invocation.

```python
def version(self) -> str:
    ...
```

### `Invocation.enter_resource`

Enter a handler resource whose SDK-owned exit resists cancellation.

Register during the active handler, and drain application-owned tasks
before returning. Registered exits run before result/terminal completion.
This does not protect arbitrary cleanup hidden inside a backend function.

```python
async def enter_resource[Resource](self, context: AbstractAsyncContextManager[Resource]) -> Resource:
    ...
```

### `Invocation.call`

Await one exact unary destination under this active original caller.

Raw bytes retain their identity; objects are encoded once. The host
rechecks permission and narrows deadlines. At most one child is pending
per parent, with no queue, retry, fallback or implicit generation timeout.
Cancelling/abandoning a pending child retires the parent; drain calls
before returning. This method grants no authority to exported contexts.

```python
async def call(self, destination: CapabilityEndpoint, payload: dict[str, JsonValue] | bytes, *, deadline_unix_ms: int | None=None) -> CallReply:
    ...
```

### `Invocation.stream`

Open an exact streaming destination under this original active caller.

Use an async context manager and consume output through its terminal.
The signed descriptor fixes server/client/bidirectional mode. The host
issues the media grant and rechecks authority; no metadata is a grant.
Input half-close leaves output open. Early abandonment retires the parent.

```python
def stream(self, destination: CapabilityEndpoint, payload: dict[str, JsonValue] | bytes, *, deadline_unix_ms: int | None=None) -> AbstractAsyncContextManager[CallStream]:
    ...
```

### Fields

```python
call_id: str
capability_id: str
payload: dict[str, JsonValue]
raw_payload: bytes
context: CallContext
```

| Field | Description | Declared defaults and constraints |
| --- | --- | --- |
| `call_id` | — | — |
| `capability_id` | — | — |
| `payload` | — | — |
| `raw_payload` | — | — |
| `context` | — | — |

## `InputFrame`

One native-admitted input projection and separate bounded binary media.

Blob declarations are metadata only. This SDK never resolves a path, URL or
blob reference supplied by a caller.

### Fields

```python
projection: dict[str, JsonValue]
media: bytes
```

| Field | Description | Declared defaults and constraints |
| --- | --- | --- |
| `projection` | — | — |
| `media` | — | — |

## `OutputFrame`

One proposed stream output; the compiled channel admits its full shape.

Supply exactly one terminal after any chunks. Terminal delivery waits for
iterator cleanup and the native end acknowledgment. Media metadata is the
portable inline/blob projection, with inline bytes supplied separately.

### Fields

```python
kind: Literal['chunk', 'completed', 'failed', 'cancelled']
payload: dict[str, JsonValue] | None
media_metadata: dict[str, JsonValue] | None
media: bytes
error: str | None
```

| Field | Description | Declared defaults and constraints |
| --- | --- | --- |
| `kind` | — | — |
| `payload` | — | — |
| `media_metadata` | — | — |
| `media` | — | — |
| `error` | — | default=null |

## `UnaryHandler`

```python
type UnaryHandler = Callable[[Invocation], Awaitable[dict[str, JsonValue]]]
```

## `StreamHandler`

```python
type StreamHandler = Callable[[Invocation, AsyncIterator[InputFrame]], AsyncGenerator[OutputFrame]]
```

## `SurfaceReports`

```python
type SurfaceReports = Callable[[], list[dict[str, JsonValue]]]
```

## `CapabilityApp`

Run explicit native unary/stream handlers with one protected control reader.

Register handlers before serving. Health uses cached synchronous callbacks,
independent of active inference. An application supplies behavior; the host
retains admission, policy, process ownership and destination selection.

### `CapabilityApp.__init__`

Configure cheap cached health observations; neither callback performs I/O.

```python
def __init__(self, *, setup: ApplicationSetup=..., ready: Callable[[], bool]=..., surfaces: SurfaceReports=...) -> None:
    ...
```

### `CapabilityApp.unary`

Register unary behavior; specify versions for multi-version IDs.

```python
def unary(self, capability_id: str, handler: UnaryHandler, *, version: str | None=None) -> None:
    ...
```

### `CapabilityApp.stream`

Register stream behavior with optional exact version selection.

```python
def stream(self, capability_id: str, handler: StreamHandler, *, version: str | None=None) -> None:
    ...
```

### `CapabilityApp.serve`

Consume the private startup descriptor and own all handlers until shutdown.

The signed manifest must name exactly the registered handlers. Only the
explicit native managed/calls/transport cohort is accepted. Cancellation,
malformed channels and shutdown drain handlers before closing control.
No uncertain request is replayed or reconnected.

```python
async def serve(self, configuration_descriptor: int) -> None:
    ...
```
