# Receivers and Deferred Calls

> UForm for JavaScript

The same verbs run on the calling thread with no receiver, and block on an executor through `on`:

```javascript
const here = model.textEncode(["a small red panda"], arena);
const there = model.on(executor).textEncode(["a small red panda"], arena);
```

`import * as uform from 'uform';`

`import { ModelOn } from 'uform';`

`import { ModelDeferredOn } from 'uform';`

`import { TrainerDeferredOn } from 'uform';`

`import { Deferred } from 'uform';`

## ProgressCallback

Hears a long call's advance; answering `false` stops it with `cancelled`.

```typescript
type ProgressCallback = (completed: number, total: number) => boolean | void
```

## Mood

What an executor does with its threads or streams once it goes idle.

```typescript
enum Mood
```

- `Parked` = `&quot;parked&quot;`: Idle threads sleep; the next call pays a wake-up.
- `Spinning` = `&quot;spinning&quot;`: Idle threads stay hot, trading power for the next call's latency.

## Answer

How a receiver hands back what its verbs answer: as is, or as a [`Deferred`](https://www.unum.cloud/docs/uform/javascript/errors.md#Deferred) of it.

```typescript
type Answer<Receiving, Answered> = Receiving extends "deferred" ? Deferred<Answered> : Answered
```

## ModelOn

The verbs of one model, blocking on one executor: `model.on(executor)`.

```typescript
class ModelOn extends ModelVerbs<"blocking">
```

Every call starts after every earlier submission to that executor, and returns with its outputs written.

## ModelOn

Made by `model.on(executor)`, never directly.

```typescript
new ModelOn(
    compiled: CompiledModel,
    executor: Executor | undefined,
)
```

## *

Reports the model's geometry and placement in one call.

```typescript
describe(): Answer<Receiving, ModelDescription>
```

Calls `uform_model_describe`.

## text*

Encodes texts through one forward; every UTF-8 byte is a token.

```typescript
textEncode(
    texts: readonly (string | Uint8Array)[] | Tape<Uint8Array>,
    arena: Arena,
    config: EncodeConfig = {},
): Answer<Receiving, Encoded>
```

Calls `uform_text_encode`.

- `texts`: Strings, UTF-8 bytes already encoded, or a tape of them.
- `arena`: The memory the outputs land in, rewound by the call.
- `config`: The surfaces, their scalar, and a progress handler.

## text*

Scores each item's legal choices through one forward, a softmax over them alone at the item's group's calibrated inverse temperature; a model without the byte decoder reports `unsupported`.

```typescript
textChoose(
    texts: readonly (string | Uint8Array)[] | Tape<Uint8Array>,
    choices: readonly (string | Uint8Array)[] | Tape<Uint8Array>,
    arena: Arena,
    config: ChooseConfig = {},
): Answer<Receiving, Chosen>
```

Calls `uform_text_choose`.

- `texts`: The states, each ending where its choice goes.
- `choices`: Each item's legal choices, one byte each, like "yn".
- `arena`: The memory the probabilities land in, rewound by the call.
- `config`: The question types and a progress handler.

## image*

Decodes and encodes JPEG, PNG or WebP files; the browser build reports `unsupported`.

```typescript
imageEncode(
    images: readonly Uint8Array[] | Tape<Uint8Array>,
    arena: Arena,
    config: EncodeConfig = {},
): Answer<Receiving, Encoded>
```

Calls `uform_image_encode`.

- `images`: One encoded file per item, or a tape of them.
- `arena`: The memory the outputs land in, rewound by the call.
- `config`: The surfaces, their scalar, and a progress handler.

## imageEncode*

Encodes decoded images, resized on the executor's side.

```typescript
imageEncodePixels(
    images: readonly Pixels[],
    arena: Arena,
    config: EncodeConfig = {},
): Answer<Receiving, Encoded>
```

Calls `uform_image_encode_pixels`.

- `images`: `ImageData`, or RGB or RGBA bytes with their width and height.
- `arena`: The memory the outputs land in, rewound by the call.
- `config`: The surfaces, their scalar, and a progress handler.

## video*

Decodes and encodes MP4 or WebM clips; the browser build reports `unsupported`.

```typescript
videoEncode(
    videos: readonly Uint8Array[] | Tape<Uint8Array>,
    arena: Arena,
    config: EncodeConfig = {},
): Answer<Receiving, Encoded>
```

Calls `uform_video_encode`.

- `videos`: One encoded file per item, or a tape of them.
- `arena`: The memory the outputs land in, rewound by the call.
- `config`: The surfaces, their scalar, and a progress handler.

## audio*

Decodes and encodes WAV, FLAC, MP3 or Opus files; the browser build reports `unsupported`.

```typescript
audioEncode(
    recordings: readonly Uint8Array[] | Tape<Uint8Array>,
    arena: Arena,
    config: EncodeConfig = {},
): Answer<Receiving, Encoded>
```

Calls `uform_audio_encode`.

- `recordings`: One encoded file per item, or a tape of them.
- `arena`: The memory the outputs land in, rewound by the call.
- `config`: The surfaces, their scalar, and a progress handler.

## audioEncode*

Encodes decoded mono recordings, resampled to the model's rate where `sampleRate` differs.

```typescript
audioEncodeSamples(
    recordings: readonly Float32Array[] | Tape<Float32Array>,
    sampleRate: number,
    arena: Arena,
    config: EncodeConfig = {},
): Answer<Receiving, Encoded>
```

Calls `uform_audio_encode_samples`.

- `recordings`: One run of samples per item, or a tape of them.
- `sampleRate`: Samples per second shared by every recording.
- `arena`: The memory the outputs land in, rewound by the call.
- `config`: The surfaces, their scalar, and a progress handler.

## executor

The executor the verbs run on; absent runs them on the calling thread.

```typescript
readonly executor: Executor | undefined
```

## ModelDeferredOn

The verbs of one model, submitted to one executor and answered as [`Deferred`](https://www.unum.cloud/docs/uform/javascript/errors.md#Deferred) calls: `model.deferred(executor)`.

```typescript
class ModelDeferredOn extends ModelVerbs<"deferred">
```

A verb borrows its arena until final, and waits into the same views a blocking call answers.

## ModelDeferredOn

Made by `model.deferred(executor)`, never directly.

```typescript
new ModelDeferredOn(compiled: CompiledModel, executor: Executor)
```

## executor

The executor the verbs run on; absent runs them on the calling thread.

```typescript
readonly executor: Executor | undefined
```

## TrainerDeferredOn

The trainer's verbs, submitted to its executor and answered as Deferred (`*`) calls: `trainer.deferred()`.

```typescript
class TrainerDeferredOn extends TrainerVerbs<"deferred">
```

## TrainerDeferredOn

Made by `trainer.deferred()`, never directly.

```typescript
new TrainerDeferredOn(
    compiled: CompiledTrainer,
    executor: Executor,
)
```

## step

Applies one optimizer step over this process's items and every peer's.

```typescript
step(
    batch: TrainerBatch,
    config: TrainerStepConfig = {},
): Answer<Receiving, Stepped>
```

Calls `uform_trainer_step`.

- `batch`: This process's items, their modalities, bags and relations.
- `config`: Where the scored embeddings land.

## save

Writes the weights and the step as a safetensors checkpoint; only process zero writes.

```typescript
save(path: string): Answer<Receiving, void>
```

Calls `uform_trainer_save`.

- `path`: The destination, written whole and renamed into place.

## Deferred

A call submitted by a deferred receiver, final once its executor finishes it.

```typescript
class Deferred<T> implements PromiseLike<T>, Disposable
```

It keeps everything the library reads or writes alive until then - the outcome, the inputs, the
outputs and every handle it names - so none of them is collected under the call. [`status`](#status) polls
without blocking, [`wait`](#wait) blocks and answers, and `await` runs that wait on the libuv pool; both
answer the same cached result, or throw the same failure, however often they are asked. On the
WebAssembly backend the call is final once submitted.

```
const encoded = await call; // or: call.wait()
```

## Deferred

Made by a verb of a deferred receiver, never directly.

```typescript
new Deferred(call: CompiledDeferred, answer: (raw: never) => T)
```

## wait

Blocks the calling thread until the call is final, then answers its result or throws its failure.

```typescript
wait(): T
```

Calls `uform_outcome_wait`.

## then

Waits off the calling thread, which is what `await` reaches for.

```typescript
then<Fulfilled = T, Rejected = never>(
    onFulfilled?: ((value: T) => Fulfilled | PromiseLike<Fulfilled>) | null,
    onRejected?: ((reason: unknown) => Rejected | PromiseLike<Rejected>) | null,
): Promise<Fulfilled | Rejected>
```

Calls `uform_outcome_wait` on the libuv pool.

## status

[`Status.Deferred`](https://www.unum.cloud/docs/uform/javascript/errors.md#Deferred) until the call is final, then [`Status.Success`](https://www.unum.cloud/docs/uform/javascript/errors.md#Success) or its failure.

```typescript
readonly status: Status
```

Calls `uform_outcome_status`.

