<!-- https://tinyactors.dev/docs/node/ -->
# @tinyactors/node API · tinyactors

Kind: reference. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml).
Voice: [Reference](https://tinyactors.dev/voices/reference.xml).

> Every class, function, interface and type of @tinyactors/node for Node.js and Bun, each with its signature and what it does.

`@tinyactors/node 0.4.0`

The types of @tinyactors/node and @tinyactors/wasm, one API (docs/api-map.md says where @tinyactors/wasm differs today). Every export has a doc comment, which an editor shows on hover; README.md and docs/guide/ teach the same API in order, with examples. Each declaration is a row of docs/api-map.md, which names the core behind it.

The declarations come in three groups, as the README orders them: the application API first, then what operating a host takes, then the wire format. Every name is exported from the package's one entry; the groups say where an item fits, not where it is imported from.

Units: time is milliseconds (but telemetry.flushInterval, in the host's clock ticks, and traceWatch's seconds); sessions are bigints (inputs also take a safe integer from 1, and typed methods' results hold numbers); bytes the host hands out are Uint8Arrays (Buffers in @tinyactors/node), copied once, yours to keep.

## Contents

- **[Values](#values)**: [`Session`](#Session), [`Value`](#Value), [`ReceivedValue`](#ReceivedValue)
- **[Errors](#errors)**: [`Status`](#Status), [`TinyactorsError`](#TinyactorsError), [`StaleError`](#StaleError), [`StateError`](#StateError), [`InvalidError`](#InvalidError), [`UnsupportedError`](#UnsupportedError)
- **[Compiling](#compiling)**: [`Source`](#Source), [`Diagnostic`](#Diagnostic), [`CompileError`](#CompileError), [`ResolveError`](#ResolveError), [`Resolver`](#Resolver), [`Compiled`](#Compiled), [`compileCharts`](#compileCharts), [`CompileOptions`](#CompileOptions), [`compileSystem`](#compileSystem), [`compileDir`](#compileDir), [`version`](#version)
- **[The clock](#the-clock)**: [`SimulatedClock`](#SimulatedClock)
- **[What handlers get](#what-handlers-get)**: [`Send`](#Send), [`AnswerOptions`](#AnswerOptions), [`LogEntry`](#LogEntry), [`Invocation`](#Invocation), [`Service`](#Service)
- **[The host's options](#the-host-s-options)**: [`HostOptions`](#HostOptions), [`Charts`](#Charts), [`IOProcessor`](#IOProcessor), [`Store`](#Store), [`MemoryStore`](#MemoryStore), [`SQLiteStore`](#SQLiteStore), [`Spawner`](#Spawner), [`Handled`](#Handled), [`QuickJSOptions`](#QuickJSOptions)
- **[Actors](#actors)**: [`Actor`](#Actor), [`SpawnOptions`](#SpawnOptions), [`SendOptions`](#SendOptions)
- **[The typed methods: their shapes, and an actor's](#the-typed-methods-their-shapes-and-an-actor-s)**: [`Params`](#Params), [`NoParams`](#NoParams), [`OnResult`](#OnResult), [`OnError`](#OnError), [`StateValue`](#StateValue), [`SessionParams`](#SessionParams), [`ActorStateResult`](#ActorStateResult), [`ActorContextResult`](#ActorContextResult), [`ActorGetResult`](#ActorGetResult), [`PendingSend`](#PendingSend)
- **[The host](#the-host)**: [`Host`](#Host)
- **[Config and sizes](#config-and-sizes)**: [`HostConfig`](#HostConfig), [`SystemConfig`](#SystemConfig), [`TelemetryConfig`](#TelemetryConfig), [`EffectiveHostConfig`](#EffectiveHostConfig)
- **[Images, segments and migration](#images-segments-and-migration)**: [`ChartRef`](#ChartRef), [`MigrateOptions`](#MigrateOptions), [`Migrated`](#Migrated), [`MigrationFailure`](#MigrationFailure), [`MigrationResult`](#MigrationResult)
- **[Inspection](#inspection)**: [`ActorListParams`](#ActorListParams), [`ActorListResult`](#ActorListResult), [`Pool`](#Pool), [`SegmentPools`](#SegmentPools), [`ChartStats`](#ChartStats), [`HostStatsResult`](#HostStatsResult)
- **[Tracing](#tracing)**: [`TraceRule`](#TraceRule), [`TraceDetail`](#TraceDetail), [`TraceConfigureParams`](#TraceConfigureParams), [`TraceWatchParams`](#TraceWatchParams), [`TraceWatchResult`](#TraceWatchResult), [`TraceUnwatchParams`](#TraceUnwatchParams), [`TraceSpansDecodeParams`](#TraceSpansDecodeParams), [`SpanEvent`](#SpanEvent), [`Span`](#Span), [`TraceSpansDecodeResult`](#TraceSpansDecodeResult), [`EmptyResult`](#EmptyResult)
- **[Values as bytes](#values-as-bytes)**: [`Encodable`](#Encodable), [`encode`](#encode), [`decode`](#decode)
- **[Addresses](#addresses)**: [`Address`](#Address)
- **[Other systems](#other-systems)**: [`SendMessage`](#SendMessage)
- **[BasicHTTP](#basichttp)**: [`HTTPField`](#HTTPField), [`HTTPPost`](#HTTPPost), [`HTTPRequest`](#HTTPRequest), [`encodeHTTPPost`](#encodeHTTPPost), [`parseHTTPRequest`](#parseHTTPRequest)
- **[An OTLP export, read back](#an-otlp-export-read-back)**: [`decodeTraces`](#decodeTraces), [`DecodedSpan`](#DecodedSpan)

<a id="the-application-api"></a>

## The application API

Charts, a Host with its processors, store and handlers, Actors: what an application writes against (README.md, from "A first program" to "Before you use it").

<a id="values"></a>

### Values

<a id="Session"></a>

#### `Session` (type)

```typescript
export type Session = bigint | number;
```

An actor's session, as an input takes it: a `bigint` from 1 to 2^64-1, or a number that is a safe integer from 1 (as a database or JSON gives one back). Anything else is a `TypeError`. The calls and views return a `bigint`; a typed method's result holds a number, so compare with `Number(session) === listed`.

<a id="Value"></a>

#### `Value` (type)

```typescript
export type Value =
  | undefined
  | null
  | boolean
  | number
  | bigint
  | string
  | Uint8Array
  | Value[]
  | { [key: string]: Value };
```

A value that crosses between your program and a chart: event data, spawn params, a typed method's result, and what `encode` and `decode` convert. Numbers that are safe integers stay integers; integers past 2^53 are `bigint`s (up to 64 bits). Plain objects only: a function, a `Map`, a `Date` or a class's instance is refused. Values are copied when they cross. Inside a value an actor's address is its text.

<a id="ReceivedValue"></a>

#### `ReceivedValue` (type)

```typescript
export type ReceivedValue = any;
```

A [`Value`](#Value) the host hands you (`send.data`, `invocation.data`, `decode`, a typed method's variables), typed `any` as `JSON.parse`'s result is: it holds whatever a chart put there, so you read its fields without narrowing first. What it holds at run time is a `Value`.

<a id="errors"></a>

### Errors

<a id="Status"></a>

#### `Status` (type)

```typescript
export type Status =
  | 'TA_ERROR_INVALID'
  | 'TA_ERROR_NO_MEMORY'
  | 'TA_ERROR_STATE'
  | 'TA_ERROR_STALE'
  | 'TA_ERROR_UNSUPPORTED'
  | 'TA_ERROR_EXECUTION'
  | 'TA_ERROR_COMMUNICATION'
  | 'TA_ERROR_ABORTED'
  | 'TA_ERROR_FATAL'
  | (string & {});
```

The reason a call was refused, as `TinyactorsError.status` names it:

- `TA_ERROR_INVALID`: an argument the host does not take (a chart it does not have, a config key, malformed bytes);
- `TA_ERROR_STALE`: something that ended or never was (a session, a view read after its handler returned, a closed compile result);
- `TA_ERROR_STATE`: not now (a snapshot from a handler, a second answer, hibernating an actor that is not at rest);
- `TA_ERROR_UNSUPPORTED`: a value outside the value table;
- `TA_ERROR_NO_MEMORY`: a pool at its largest size, or the system allocator refused.

<a id="TinyactorsError"></a>

#### `TinyactorsError` (class)

```typescript
export class TinyactorsError extends Error
```

An error the host reported. A refused call has a `status` to branch on; a typed method's error, and a refused config, have `code`, `reason` and `path`, as the host wrote them. The message is for people: do not match on it.

```typescript title="example"
try { host.send(session, 'go'); }
catch (error) { if (error instanceof StaleError) ... } // the actor ended
```

<a id="TinyactorsError.constructor"></a>

##### `TinyactorsError.constructor`

```typescript
constructor(
    message?: string,
    options?: { code?: number; reason?: string; path?: string; status?: Status },
  );
```

<a id="TinyactorsError.code"></a>

##### `TinyactorsError.code`

```typescript
readonly code: number | undefined;
```

A typed method's error: its JSON-RPC code (`-32001` for a session that does not exist, `-32602` for a param it does not take, ...).

<a id="TinyactorsError.reason"></a>

##### `TinyactorsError.reason`

```typescript
readonly reason: string | undefined;
```

A typed method's error: a word for its cause (`stale`, `type`, `unknown`, `range`, `missing`, `state`, ...).

<a id="TinyactorsError.path"></a>

##### `TinyactorsError.path`

```typescript
readonly path: string | undefined;
```

A typed method's error: the param it is about (`params.session`).

<a id="TinyactorsError.status"></a>

##### `TinyactorsError.status`

```typescript
readonly status: Status | undefined;
```

A refused call's reason.

<a id="StaleError"></a>

#### `StaleError` (class)

```typescript
export class StaleError extends TinyactorsError
```

An actor, session, view or handle that does not exist (any more): a send to a session or name that ended, a thin view read after its batch, a typed method's `stale` error. Its `status` is `'TA_ERROR_STALE'`.

<a id="StateError"></a>

#### `StateError` (class)

```typescript
export class StateError extends TinyactorsError
```

A call the host cannot make now: a closed host, a snapshot from a handler, a typed method's `state` error. Its `status` is `'TA_ERROR_STATE'`.

<a id="InvalidError"></a>

#### `InvalidError` (class)

```typescript
export class InvalidError extends TinyactorsError
```

An argument the host refused: a malformed config, image or address, a typed method's param. Its `status` is `'TA_ERROR_INVALID'`.

<a id="UnsupportedError"></a>

#### `UnsupportedError` (class)

```typescript
export class UnsupportedError extends TinyactorsError
```

A value or a feature the host does not take: a value outside the value table, a chart that cannot hibernate. Its `status` is `'TA_ERROR_UNSUPPORTED'`.

<a id="compiling"></a>

### Compiling

<a id="Source"></a>

#### `Source` (interface)

```typescript
export interface Source
```

A document to compile: its name, which error messages and `src` attributes name, and its text.

<a id="Source.name"></a>

##### `Source.name`

```typescript
name: string;
```

<a id="Source.text"></a>

##### `Source.text`

```typescript
text: string;
```

<a id="Diagnostic"></a>

#### `Diagnostic` (interface)

```typescript
export interface Diagnostic
```

One message of the compiler about a document.

<a id="Diagnostic.severity"></a>

##### `Diagnostic.severity`

```typescript
readonly severity: 'error' | 'warning' | 'note';
```

<a id="Diagnostic.code"></a>

##### `Diagnostic.code`

```typescript
readonly code: number;
```

The compiler's code for the kind of problem.

<a id="Diagnostic.file"></a>

##### `Diagnostic.file`

```typescript
readonly file: string;
```

The document's name, as its [`Source`](#Source) gave it.

<a id="Diagnostic.line"></a>

##### `Diagnostic.line`

```typescript
readonly line: number;
```

From 1.

<a id="Diagnostic.column"></a>

##### `Diagnostic.column`

```typescript
readonly column: number;
```

From 1.

<a id="Diagnostic.message"></a>

##### `Diagnostic.message`

```typescript
readonly message: string;
```

<a id="CompileError"></a>

#### `CompileError` (class)

```typescript
export class CompileError extends TinyactorsError
```

A compilation found an error, and compiled nothing. Its message is the first error as a compiler prints it, `file:line:column: error: message`; its status is `TA_ERROR_INVALID`.

<a id="CompileError.diagnostics"></a>

##### `CompileError.diagnostics`

```typescript
readonly diagnostics: readonly Diagnostic[];
```

Every diagnostic of the compilation: errors, warnings and notes.

<a id="ResolveError"></a>

#### `ResolveError` (class)

```typescript
export class ResolveError extends TinyactorsError
```

Thrown by a [`Resolver`](#Resolver) to refuse a document: the refusal becomes a compile error of the resolved file, at `line` and `column` when given, and the compile call throws a `CompileError`.

<a id="ResolveError.constructor"></a>

##### `ResolveError.constructor`

```typescript
constructor(message: string, options?: { line?: number; column?: number });
```

<a id="ResolveError.line"></a>

##### `ResolveError.line`

```typescript
readonly line: number | undefined;
```

<a id="ResolveError.column"></a>

##### `ResolveError.column`

```typescript
readonly column: number | undefined;
```

<a id="Resolver"></a>

#### `Resolver` (type)

```typescript
export type Resolver = (base: string, source: string) => string;
```

Reads a document a chart names with `src` (`<invoke src>`, `<script src>`, `<data src>`, a manifest's `<chart src>`): the text of `source`, named by the document `base`. Called during the compile call only. Throw a `ResolveError` to refuse; any other error is thrown from the compile call as it is.

```typescript title="example"
const resolver = (base, source) => readFileSync(join(root, source), 'utf8');
```

<a id="Compiled"></a>

#### `Compiled` (interface)

```typescript
export interface Compiled extends Disposable
```

What a compile call returns: the image and the compiler's warnings.

<a id="Compiled.image"></a>

##### `Compiled.image`

```typescript
readonly image: Uint8Array;
```

The compiled image, for `host.addImage`: a `Uint8Array`, copied on the first read and yours from then on (write it to a file, load it elsewhere). A first read after `close()` throws `TA_ERROR_STALE`.

<a id="Compiled.diagnostics"></a>

##### `Compiled.diagnostics`

```typescript
readonly diagnostics: readonly Diagnostic[];
```

The warnings and notes of the compilation.

<a id="Compiled.close"></a>

##### `Compiled.close`

```typescript
close(): void;
```

Frees the compiler's memory now; the garbage collector does it otherwise. Read `image` first.

<a id="Compiled.Symboldispose"></a>

##### `Compiled.Symboldispose`

```typescript
[Symbol.dispose](): void;
```

`close()`.

<a id="compileCharts"></a>

#### `compileCharts` (function)

```typescript
export function compileCharts(sources: readonly Source[], options?: CompileOptions): Compiled;
```

Compiles SCXML documents into one image. Each chart is known by its `<scxml name>`. A `src` is answered by a source of that name or by `resolver`. The first source is the boot chart, which `host.boot` spawns. Throws `CompileError` with every diagnostic. Every expression and script of an `"ecmascript"` chart is parsed by the engine, running nothing: a syntax error is a warning in `diagnostics` (`cond: SyntaxError: ...`, at its element's line and column, a script's own line), and an error with `warningsAsErrors`.

```typescript title="example"
const compiled = compileCharts([{ name: 'order.scxml', text }]);
const host = new Host(compiled, { system: 'shop' });
compiled.close();
```

<a id="CompileOptions"></a>

#### `CompileOptions` (interface)

```typescript
export interface CompileOptions
```

The options of `compileCharts`, `compileSystem` and `compileDir`.

<a id="CompileOptions.resolver"></a>

##### `CompileOptions.resolver`

```typescript
readonly resolver?: Resolver;
```

Answers each `src` the sources do not hold (`compileDir`'s default reads them from its directory).

<a id="CompileOptions.warningsAsErrors"></a>

##### `CompileOptions.warningsAsErrors`

```typescript
readonly warningsAsErrors?: boolean;
```

Every warning is an error, and the compile throws `CompileError`: the compiler's own warnings and the syntax errors of the charts' ECMAScript, which are warnings otherwise, since SCXML makes such an expression an `error.execution` when it is evaluated.

<a id="compileSystem"></a>

#### `compileSystem` (function)

```typescript
export function compileSystem(manifest: Source, options?: CompileOptions): Compiled;
```

Compiles a system manifest: a `<system>` document of `<chart name src>`s, read through `options.resolver`, and `<actor name chart>`s, which `host.boot` spawns with their names. Throws `CompileError`.

<a id="compileDir"></a>

#### `compileDir` (function)

```typescript
export function compileDir(dir: string | URL, options?: { readonly resolver?: Resolver }): Compiled;
```

Compiles every `*.scxml` file under the directory `dir` (a path or a `file:` URL) into one image: keep an application's charts and their helper files (a `.js` a chart reads with `<script src>`, a chart it invokes with `<invoke src>`) in one directory, compile it once at startup, and give the result to any number of hosts. The charts are named by their path under `dir`, sorted (the first is the image's default boot chart); a `src` is read from under `dir`, relative to the document that names it, and one whose path leaves `dir` (`..` past it, an absolute path, a symbolic link pointing outside) is refused with a `ResolveError`, so a `CompileError`; give `options.resolver` to read them yourself. A directory with no chart, or a chart file whose real path leaves it, throws `TA_ERROR_INVALID`; an error of the file system is thrown as it is. Needs `node:fs` (`TA_ERROR_UNSUPPORTED` in a page).

```typescript title="example"
const compiled = compileDir(new URL('./charts/', import.meta.url));
const host = new Host(compiled, { system: 'chat' });
compiled.close();
```

<a id="version"></a>

#### `version` (const)

```typescript
export const version: string;
```

The version of the package installed (`'0.4.0'`, or a development build's `'0.4.0-dev.20261119.3.gabc1234'`), as its package.json says. `@tinyactors/node/package.json` can be imported too.

<a id="the-clock"></a>

### The clock

<a id="SimulatedClock"></a>

#### `SimulatedClock` (class)

```typescript
export class SimulatedClock
```

A clock for tests and simulations, which moves only when you move it. Give it to a host as `options.clock`; a host on it arms no timer.

```typescript title="example"
const clock = new SimulatedClock();
const host = new Host(config, { clock });
clock.increment(30_000); // a 30-second timeout, at once
await host.idle();
```

<a id="SimulatedClock.constructor"></a>

##### `SimulatedClock.constructor`

```typescript
constructor();
```

<a id="SimulatedClock.now"></a>

##### `SimulatedClock.now`

```typescript
readonly now: number;
```

Milliseconds since the clock was made.

<a id="SimulatedClock.increment"></a>

##### `SimulatedClock.increment`

```typescript
increment(ms: number): void;
```

Moves the clock `ms` forward and schedules a turn on every host made with it; `await host.idle()` to see what ran. What is due runs once, at the new time, and a delay it starts counts from there: to see each of several deadlines, step to each.

<a id="what-handlers-get"></a>

### What handlers get

<a id="Send"></a>

#### `Send` (interface)

```typescript
export interface Send
```

One `<send>` of a chart, as an I/O processor's handler, the transport or a service's `receive` gets it. A view of the host's memory: each field is read on first access, while the handler runs; after the handler returned, a read throws `TA_ERROR_STALE`. When the handler returns a promise, every field is read before the host moves on, and the view stays valid, `answer` and `fail` included, while the host is open.

<a id="Send.host"></a>

##### `Send.host`

```typescript
readonly host: Host;
```

The host that handed it out.

<a id="Send.session"></a>

##### `Send.session`

```typescript
readonly session: bigint;
```

The sender's session.

<a id="Send.sender"></a>

##### `Send.sender`

```typescript
readonly sender: Actor;
```

The sender, as an [`Actor`](#Actor) (a new one at each read).

<a id="Send.event"></a>

##### `Send.event`

```typescript
readonly event: string;
```

The event's name.

<a id="Send.target"></a>

##### `Send.target`

```typescript
readonly target: string | Address | undefined;
```

`<send target>`: a string; an `Address` for the transport's sends; `undefined` when the send has none.

<a id="Send.sendid"></a>

##### `Send.sendid`

```typescript
readonly sendid: string | undefined;
```

`<send id>`, or the id the host generated; `undefined` when none. A generated id is unique in the sender's session only (each session's first is `send.1`): key by `session` and `sendid` together.

<a id="Send.data"></a>

##### `Send.data`

```typescript
readonly data: ReceivedValue;
```

The `<param>`s as an object, or the `<content>`'s value.

<a id="Send.type"></a>

##### `Send.type`

```typescript
readonly type: string | undefined;
```

The I/O processor's type; `undefined` for the transport and a service.

<a id="Send.origin"></a>

##### `Send.origin`

```typescript
readonly origin: Address | undefined;
```

The sender's address.

<a id="Send.traceparent"></a>

##### `Send.traceparent`

```typescript
readonly traceparent: string | undefined;
```

The sending step's trace as W3C `traceparent` text, for the header of the request you make; `undefined` when untraced.

<a id="Send.message"></a>

##### `Send.message`

```typescript
readonly message: SendMessage;
```

The outgoing half, `{ target, event, data, sendid, origin, traceparent }`: what `host.send(message)` takes on the other side, unchanged. The transport's reason to exist; present on every send. A text field the send lacks (`sendid`, `origin`, `traceparent`) is `null`, as in a Python host's message, so encoded it is absent to every binding. Its addresses are `Address`es, which `JSON.stringify` writes as their text (`toJSON`) and `encode` as tag 32.

<a id="Send.answer"></a>

##### `Send.answer`

```typescript
answer(event: string, data?: Value, options?: AnswerOptions): boolean;
```

Sends `event` back to the sender, with this send's `sendid`. It continues the send's trace unless `options.traceparent` is given (`null`: a new trace). Once: a second answer, or one after `fail()`, throws `TA_ERROR_STATE`, as does a closed host. Returns `true` when the sender gets it, `false` when the sender ended meanwhile (an answer given after the handler returned): nothing is delivered.

<a id="Send.fail"></a>

##### `Send.fail`

```typescript
fail(): boolean;
```

Gives the sender `error.communication` with this send's `sendid`: the request could not be done. Returns `true` when the sender gets it, `false` when it ended meanwhile, as `answer`.

<a id="AnswerOptions"></a>

#### `AnswerOptions` (interface)

```typescript
export interface AnswerOptions
```

The options of `send.answer`.

<a id="AnswerOptions.traceparent"></a>

##### `AnswerOptions.traceparent`

```typescript
traceparent?: string | null;
```

The answer's trace: W3C text, or `null` for a new trace. Absent: the send's.

<a id="AnswerOptions.origin"></a>

##### `AnswerOptions.origin`

```typescript
origin?: string | Address;
```

The answer's `_event.origin`.

<a id="AnswerOptions.raw"></a>

##### `AnswerOptions.raw`

```typescript
raw?: string;
```

The message as you read it, for the chart's `_event.raw`.

<a id="LogEntry"></a>

#### `LogEntry` (interface)

```typescript
export interface LogEntry
```

A `<log>` line: a view, valid while the log handler runs.

<a id="LogEntry.host"></a>

##### `LogEntry.host`

```typescript
readonly host: Host;
```

The host that handed it out.

<a id="LogEntry.session"></a>

##### `LogEntry.session`

```typescript
readonly session: bigint;
```

The actor that logged.

<a id="LogEntry.label"></a>

##### `LogEntry.label`

```typescript
readonly label: string;
```

`<log label>`; `''` when it has none.

<a id="LogEntry.text"></a>

##### `LogEntry.text`

```typescript
readonly text: string;
```

The value of `<log expr>`, as text.

<a id="Invocation"></a>

#### `Invocation` (interface)

```typescript
export interface Invocation
```

An `<invoke>` of a service your program runs, as a service handler gets it. A record: keep it and use it while the service runs.

<a id="Invocation.host"></a>

##### `Invocation.host`

```typescript
readonly host: Host;
```

The host that runs the invocation.

<a id="Invocation.session"></a>

##### `Invocation.session`

```typescript
readonly session: bigint;
```

The invoking actor.

<a id="Invocation.invokeid"></a>

##### `Invocation.invokeid`

```typescript
readonly invokeid: string;
```

The `<invoke id>`, or the id the host generated.

<a id="Invocation.type"></a>

##### `Invocation.type`

```typescript
readonly type: string;
```

`<invoke type>`.

<a id="Invocation.src"></a>

##### `Invocation.src`

```typescript
readonly src: string;
```

`<invoke src>`.

<a id="Invocation.data"></a>

##### `Invocation.data`

```typescript
readonly data: ReceivedValue;
```

The `<param>`s as an object, or the `<content>`'s value.

<a id="Invocation.traceparent"></a>

##### `Invocation.traceparent`

```typescript
readonly traceparent: string | undefined;
```

The invoking step's trace, as W3C text.

<a id="Invocation.restored"></a>

##### `Invocation.restored`

```typescript
readonly restored: boolean;
```

True when a restored host announces an invocation that was running at its snapshot: start it again, or a stand-in.

<a id="Invocation.running"></a>

##### `Invocation.running`

```typescript
readonly running: boolean;
```

False once the invocation ended (done, cancelled, failed) or the host closed.

<a id="Invocation.sendBack"></a>

##### `Invocation.sendBack`

```typescript
sendBack(event: string, data?: Value, options?: { traceparent?: string | null }): void;
```

Sends `event` to the invoker, with `_event.invokeid` set. Continues the invoke's trace unless given one (`null`: a new trace). Throws `TA_ERROR_STALE` once the invocation ended.

<a id="Invocation.done"></a>

##### `Invocation.done`

```typescript
done(data?: Value, options?: { traceparent?: string | null }): void;
```

Ends the service: the invoker gets `done.invoke.<invokeid>` with `data`, and the service is dropped without `stop`. Throws `TA_ERROR_STALE` once the invocation ended.

<a id="Service"></a>

#### `Service` (interface)

```typescript
export interface Service
```

What a service handler returns: any object, kept by the host until the invocation ends, whose methods the host calls. At `host.close()` a running service is dropped, not stopped.

<a id="Service.receive"></a>

##### `Service.receive`

```typescript
receive?(send: Send): void | Promise<void>;
```

A send of the invoker to the service (`<send target="#_<invokeid>">`, or an autoforwarded event); `send.type` is `undefined`. A throw, or a promise that rejects, is a crash: the invoker gets `error.communication` and the service is dropped.

<a id="Service.stop"></a>

##### `Service.stop`

```typescript
stop?(): void;
```

The invoker left the state, which cancels the invocation.

<a id="the-host-s-options"></a>

### The host's options

<a id="HostOptions"></a>

#### `HostOptions` (interface)

```typescript
export interface HostOptions
```

The handlers and choices of a host, `new Host(charts, options)`. A handler's error is reported after its turn: it goes to `onHandlerError` when there is one; else it rejects a waiting `host.idle()`, or is thrown as an uncaught exception. No handler takes the host: a view or record has `.host`.

<a id="HostOptions.system"></a>

##### `HostOptions.system`

```typescript
system: string;
```

Required: this system's id, part of every address it hands out (`tinyactors://<system>/...`). No two systems that talk may share one, and `'tinyactors-ask'` is the binding's (`TA_ERROR_INVALID`).

<a id="HostOptions.ioProcessors"></a>

##### `HostOptions.ioProcessors`

```typescript
ioProcessors?: { [type: string]: IOProcessor };
```

The I/O processors the charts may send to (`<send type>`): an object of each type's [`IOProcessor`](#IOProcessor), the config's `ioProcessors` in this order. Sends to another system need none: they go to `transport`.

<a id="HostOptions.config"></a>

##### `HostOptions.config`

```typescript
config?: HostConfig;
```

The rest of the host's config.

<a id="HostOptions.clock"></a>

##### `HostOptions.clock`

```typescript
clock?: SimulatedClock;
```

A `SimulatedClock`; without one the host reads the runtime's clock and arms a timer at its next deadline.

<a id="HostOptions.store"></a>

##### `HostOptions.store`

```typescript
store?: Store;
```

Where hibernated actors' blobs go: a WAKE (an event, a due delayed send, a migration for a hibernated actor) loads its blob from here and wakes it. Without a store a WAKE is dropped: the actor stays hibernated, and its events wait, until `host.wake`.

<a id="HostOptions.resident"></a>

##### `HostOptions.resident`

```typescript
resident?: number;
```

The most actors kept in memory (an integer from 1; needs `store`): after a turn that goes idle the host hibernates the actors past it into the store, the coldest first (`host.sweep`, `host.hibernate`); a migration's WAKE waits while the bound is reached, and loads as room is made. An actor not at rest, or holding what its datamodel cannot write out, stays.

<a id="HostOptions.log"></a>

##### `HostOptions.log`

```typescript
log?: (entry: LogEntry) => Handled;
```

`<log>` lines; without one they are dropped.

<a id="HostOptions.telemetry"></a>

##### `HostOptions.telemetry`

```typescript
telemetry?: (signal: 'traces' | 'logs', data: Uint8Array) => Handled;
```

Your exporter: each OTLP traces or logs request the encoder wrote (protobuf, for a collector's `/v1/traces` or `/v1/logs`), as a `Uint8Array`. Needs `telemetry` in the config; without a handler the requests are dropped. It runs in the host's turn: start the post and return. At `close()` it gets the last requests; the promises it returns then are awaited by `[Symbol.asyncDispose]`.

<a id="HostOptions.services"></a>

##### `HostOptions.services`

```typescript
services?: { [type: string]: (invocation: Invocation) => Service | void | PromiseLike<Service | void> };
```

The handler of each `<invoke type>` your program runs: it returns the service, or a promise of it. Until the promise settles the sends to the invocation wait, in order; a rejection is a failed start, and the invoker gets `error.communication`.

<a id="HostOptions.transport"></a>

##### `HostOptions.transport`

```typescript
transport?: (send: Send) => Handled;
```

Sends to another system's address. Pass `send.message` to the other side's `host.send`. Without one, each such send is failed. A reply to an `actor.ask` never reaches it.

<a id="HostOptions.onDone"></a>

##### `HostOptions.onDone`

```typescript
onDone?: (actor: Actor, donedata: ReceivedValue) => Handled;
```

Each top-level actor that reaches a final state, with its donedata (`undefined` for none).

<a id="HostOptions.onError"></a>

##### `HostOptions.onError`

```typescript
onError?: (actor: Actor, error: TinyactorsError) => Handled;
```

Each top-level actor that faulted and ended (a `TinyactorsError`, status `TA_ERROR_FATAL`).

<a id="HostOptions.onHandlerError"></a>

##### `HostOptions.onHandlerError`

```typescript
onHandlerError?: (error: unknown, effect: Send | LogEntry | Migrated | Invocation | undefined) => void;
```

A handler's error (a throw, or its promise's rejection), with the view or record it was handling (`undefined` for none; a thin view is readable while the hook runs). The send is failed as without it. Without it, the error is the turn's.

<a id="HostOptions.migrated"></a>

##### `HostOptions.migrated`

```typescript
migrated?: (migrated: Migrated) => Handled;
```

Each actor a migration moved.

<a id="HostOptions.migrationDone"></a>

##### `HostOptions.migrationDone`

```typescript
migrationDone?: (result: MigrationResult) => Handled;
```

The end of each migration.

<a id="HostOptions.datamodel"></a>

##### `HostOptions.datamodel`

```typescript
datamodel?: 'native' | 'quickjs';
```

Where chart code runs: `'native'` (the default), your own engine (`node:vm` contexts in @tinyactors/node), for trusted charts; or `'quickjs'`, the sandbox, for charts you do not trust (in @tinyactors/wasm the datamodel for a page whose policy forbids `'unsafe-eval'`).

<a id="HostOptions.quickjs"></a>

##### `HostOptions.quickjs`

```typescript
quickjs?: QuickJSOptions;
```

The sandbox's limits, with `datamodel: 'quickjs'` only (else a `TypeError`).

<a id="Charts"></a>

#### `Charts` (type)

```typescript
export type Charts = Compiled | Uint8Array | ArrayBuffer | readonly (Compiled | Uint8Array | ArrayBuffer)[];
```

What `new Host` and `Host.restore` take as charts: a compile result (its image is read), an image's bytes, or an array of them, each added in order as a segment.

<a id="IOProcessor"></a>

#### `IOProcessor` (interface)

```typescript
export interface IOProcessor
```

An I/O processor: the object that serves one `<send type>`, given as `options.ioProcessors[type]`. Its `receive` gets each send to the type, called on the object: answer or fail it there, or return a promise (every field of the send is read before the host moves on, and it may be answered when the promise gets there). A throw, or a promise that rejects before an answer, fails the send (`error.communication` for the sender) and is reported as the turn's error, or to `onHandlerError`. A plain function is a `TypeError`: switch on `send.event` in `receive`.

```typescript title="example"
const database = {
  receive(send) {
    if (send.event === 'load') send.answer('loaded', { rows: [] });
    else send.fail();
  },
};
```

<a id="IOProcessor.receive"></a>

##### `IOProcessor.receive`

```typescript
receive(send: Send): Handled;
```

<a id="IOProcessor.location"></a>

##### `IOProcessor.location`

```typescript
readonly location?: string;
```

Its location, which `_ioprocessors` shows the charts.

<a id="Store"></a>

#### `Store` (interface)

```typescript
export interface Store
```

A store of hibernated actors' blobs, given as `options.store`: the host saves an actor's blob when it hibernates it (with `options.resident`), loads it when an event, a due delayed send or a migration comes for the actor (a WAKE), then wakes the actor and deletes the blob. Each method may return a value or a promise: the host waits for a promise (and so does `idle()`); a save still pending when its actor's WAKE comes is waited for first. A `save` that throws, or whose promise rejects, wakes the actor back from its blob (it stays in memory until a later turn), a `load` that throws leaves it hibernated; both are reported as a handler's error. `MemoryStore` and `SQLiteStore` are synchronous.

<a id="Store.save"></a>

##### `Store.save`

```typescript
save(session: bigint, blob: Uint8Array): void | PromiseLike<void>;
```

<a id="Store.load"></a>

##### `Store.load`

```typescript
load(session: bigint): Uint8Array | ArrayBuffer | PromiseLike<Uint8Array | ArrayBuffer>;
```

<a id="Store.delete"></a>

##### `Store.delete`

```typescript
delete(session: bigint): void | PromiseLike<void>;
```

<a id="MemoryStore"></a>

#### `MemoryStore` (class)

```typescript
export class MemoryStore implements Store
```

A [`Store`](#Store) in a `Map`, in this process: for tests, and where the host's memory, not the process's, is what must stay small.

<a id="MemoryStore.constructor"></a>

##### `MemoryStore.constructor`

```typescript
constructor();
```

<a id="MemoryStore.blobs"></a>

##### `MemoryStore.blobs`

```typescript
readonly blobs: Map<bigint, Uint8Array>;
```

The blobs by session: what a test reads to see what was stored.

<a id="MemoryStore.save"></a>

##### `MemoryStore.save`

```typescript
save(session: bigint, blob: Uint8Array): void;
```

<a id="MemoryStore.load"></a>

##### `MemoryStore.load`

```typescript
load(session: bigint): Uint8Array;
```

The blob of `session`; a `StaleError` when there is none.

<a id="MemoryStore.delete"></a>

##### `MemoryStore.delete`

```typescript
delete(session: bigint): void;
```

<a id="SQLiteStore"></a>

#### `SQLiteStore` (class)

```typescript
export class SQLiteStore implements Store
```

A [`Store`](#Store) in an SQLite database file, one row per actor in the table `tinyactors_blobs (session, blob)`, through the runtime's own SQLite (`node:sqlite` under node, `bun:sqlite` under bun), synchronously; `':memory:'` for no file. It is a cache of the host's actors, not their durability: a host's blobs wake only in that host or one restored from its snapshot, so keep the file with the snapshot. A runtime without SQLite (a page) throws `TA_ERROR_UNSUPPORTED`.

<a id="SQLiteStore.constructor"></a>

##### `SQLiteStore.constructor`

```typescript
constructor(path: string);
```

<a id="SQLiteStore.database"></a>

##### `SQLiteStore.database`

```typescript
readonly database: any;
```

The runtime's database object, for an application that reads the table itself.

<a id="SQLiteStore.save"></a>

##### `SQLiteStore.save`

```typescript
save(session: bigint, blob: Uint8Array): void;
```

<a id="SQLiteStore.load"></a>

##### `SQLiteStore.load`

```typescript
load(session: bigint): Uint8Array;
```

The blob of `session`; a `StaleError` when there is none.

<a id="SQLiteStore.delete"></a>

##### `SQLiteStore.delete`

```typescript
delete(session: bigint): void;
```

<a id="SQLiteStore.close"></a>

##### `SQLiteStore.close`

```typescript
close(): void;
```

Closes the database; the file keeps the blobs.

<a id="Spawner"></a>

#### `Spawner` (class)

```typescript
export class Spawner implements IOProcessor
```

An I/O processor that spawns actors for charts: give it a type you name, `ioProcessors: { spawn: new Spawner() }`, and a chart sends it `{chart, name, params}` (`<send type="spawn" event="spawn">`). The new actor runs the chart's current version; the sender gets `spawned` with `{name, address}` and the send's `sendid`, or `error.communication` when the host cannot spawn it (a chart it does not have, data of another shape). A type no processor serves stays `error.execution`. It does not look names up: a name has one owner, the collection actor that spawns it and records the spawns it asked for.

<a id="Spawner.constructor"></a>

##### `Spawner.constructor`

```typescript
constructor();
```

<a id="Spawner.receive"></a>

##### `Spawner.receive`

```typescript
receive(send: Send): void;
```

<a id="Handled"></a>

#### `Handled` (type)

```typescript
export type Handled = unknown;
```

What a handler returns: nothing, or a promise (typed `unknown`, so a handler that returns another value, as `(host, send) => sent.push(send)` does, is one too; the host ignores it). A send whose handler returns a promise is read in full before the host moves on, and may be answered when the promise gets there.

<a id="QuickJSOptions"></a>

#### `QuickJSOptions` (interface)

```typescript
export interface QuickJSOptions
```

The quickjs sandbox's limits. Absent: the engine's default.

<a id="QuickJSOptions.maxOps"></a>

##### `QuickJSOptions.maxOps`

```typescript
maxOps?: number;
```

Interrupt checks one evaluation may make before it is stopped with `error.execution` (default 1,000,000, which lets a busy loop run for many seconds).

<a id="QuickJSOptions.memoryLimit"></a>

##### `QuickJSOptions.memoryLimit`

```typescript
memoryLimit?: number;
```

Bytes for the whole engine, every actor together (default 1 GiB, `2 ** 30`; `Number.MAX_SAFE_INTEGER` is as good as none). An evaluation that needs more is stopped with `error.execution`, reason `'memory'`.

<a id="QuickJSOptions.stackLimit"></a>

##### `QuickJSOptions.stackLimit`

```typescript
stackLimit?: number;
```

Bytes of native stack for JavaScript.

<a id="QuickJSOptions.realm"></a>

##### `QuickJSOptions.realm`

```typescript
realm?: 'auto' | 'isolated';
```

`'auto'` (the default): the actors of a chart that declares no top-level names share one context and its builtins; `'isolated'`: a context per actor.

<a id="actors"></a>

### Actors

<a id="Actor"></a>

#### `Actor` (class)

```typescript
export class Actor
```

An actor of a host: what `host.spawn` and `host.actor` return, and what `send.sender` and `onDone` give. A small immutable value made where the API returns one: keeping one keeps nothing alive in the host, two for one actor are `equals` (key a `Map` by `id`), and one whose actor ended refuses what needs the actor (`StaleError`). Every call that takes a session takes an Actor.

<a id="Actor.constructor"></a>

##### `Actor.constructor`

```typescript
constructor(host: Host, id: bigint);
```

An Actor of `host` for session `id`; `host.actor(id)` checks it is live.

<a id="Actor.id"></a>

##### `Actor.id`

```typescript
readonly id: bigint;
```

The actor's session: a `bigint`, core's `_sessionid`.

<a id="Actor.host"></a>

##### `Actor.host`

```typescript
readonly host: Host;
```

The host it runs in (not enumerable).

<a id="Actor.address"></a>

##### `Actor.address`

```typescript
readonly address: Address;
```

`tinyactors://<system>/#_scxml_<id>`, the full form: what another system sends to. A chart sees this actor's sends' `_event.origin` either in it or as its fragment, `#_scxml_<id>`, so compare by the fragment.

<a id="Actor.send"></a>

##### `Actor.send`

```typescript
send(event: string, data?: Value, options?: SendOptions): void;
```

`host.send(actor, event, data, options)`.

<a id="Actor.terminate"></a>

##### `Actor.terminate`

```typescript
terminate(): void;
```

Ends the actor now (`host.terminate`): no exit handlers, no done event; a hibernated one is woken to end, its blob deleted.

<a id="Actor.state"></a>

##### `Actor.state`

```typescript
state(): Promise<ActorStateResult>;
```

`host.actorState({ session: actor })`.

<a id="Actor.context"></a>

##### `Actor.context`

```typescript
context(): Promise<ActorContextResult>;
```

`host.actorContext({ session: actor })`.

<a id="Actor.get"></a>

##### `Actor.get`

```typescript
get(): Promise<ActorGetResult>;
```

`host.actorGet({ session: actor })`.

<a id="Actor.ask"></a>

##### `Actor.ask`

```typescript
ask(event: string, data?: Value, options?: { signal?: AbortSignal }): Promise<[string, ReceivedValue]>;
```

Sends `event` with `data` and resolves with the actor's reply, `[event, data]`: the chart answers with `<send targetexpr="_event.origin" event="...">`. The event's origin is an address of the host's own (system `tinyactors-ask`), so the reply comes back here and never reaches your transport. No timeout of its own: `options.signal` (an `AbortSignal`) rejects it with the signal's reason and drops it; an ask pending at `close()` never settles. A refusal at the call (an actor that ended) rejects.

<a id="Actor.done"></a>

##### `Actor.done`

```typescript
readonly done: Promise<ReceivedValue>;
```

A promise of the actor's donedata, settled when it reaches a top-level final state (rejected with the error it ended with, a fault). The same promise while it is pending; an actor that ended already rejects with `StaleError`, a closed host `StateError`, and one pending at `close()` never settles.

<a id="Actor.equals"></a>

##### `Actor.equals`

```typescript
equals(other: unknown): boolean;
```

Whether `other` is an Actor of the same host and session.

<a id="Actor.toString"></a>

##### `Actor.toString`

```typescript
toString(): string;
```

`Actor(<id>)`.

<a id="SpawnOptions"></a>

#### `SpawnOptions` (interface)

```typescript
export interface SpawnOptions
```

The options of `host.spawn`.

<a id="SpawnOptions.name"></a>

##### `SpawnOptions.name`

```typescript
name?: string;
```

The actor's name: `host.actor(name)` finds it, `_name` holds it, and its address is `tinyactors://<system>/@<name>`.

<a id="SpawnOptions.params"></a>

##### `SpawnOptions.params`

```typescript
params?: Value;
```

Initial values: each key that names a top-level `<data>` replaces that variable's initial value; keys that name none are left out.

<a id="SpawnOptions.traceparent"></a>

##### `SpawnOptions.traceparent`

```typescript
traceparent?: string;
```

The trace the actor's start continues, as W3C text.

<a id="SendOptions"></a>

#### `SendOptions` (interface)

```typescript
export interface SendOptions
```

The options of `host.send(target, event, data, options)`.

<a id="SendOptions.sendid"></a>

##### `SendOptions.sendid`

```typescript
sendid?: string;
```

The event's `_event.sendid`.

<a id="SendOptions.traceparent"></a>

##### `SendOptions.traceparent`

```typescript
traceparent?: string;
```

The trace the event continues, as W3C text; text that does not parse starts a new one.

<a id="SendOptions.origin"></a>

##### `SendOptions.origin`

```typescript
origin?: string | Address;
```

The event's `_event.origin`.

<a id="the-typed-methods-their-shapes-and-an-actor-s"></a>

### The typed methods: their shapes, and an actor's

<a id="Params"></a>

#### `Params` (type)

```typescript
export type Params = { [key: string]: Value } | undefined;
```

A typed method's params, passed to the host as given (the host checks them); `undefined` for none. Each method has its own type below.

<a id="NoParams"></a>

#### `NoParams` (type)

```typescript
export type NoParams = undefined | { readonly [key: string]: never };
```

The params of a method that takes none: `undefined` or `{}`.

<a id="OnResult"></a>

#### `OnResult` (type)

```typescript
export type OnResult<R = Value> = (result: R) => void;
```

A typed method's result handler, called once, in a later turn, with the method's result.

<a id="OnError"></a>

#### `OnError` (type)

```typescript
export type OnError = (error: TinyactorsError) => void;
```

A typed method's error handler. Without one, the error rejects a waiting `idle()` or is thrown as an uncaught exception.

<a id="StateValue"></a>

#### `StateValue` (type)

```typescript
export type StateValue = string | { readonly [state: string]: StateValue };
```

An active configuration, as xstate's `value`: an atomic state is its id (`'s'`), a compound state `{ [state]: its active child }`, a parallel state `{ [state]: { [region]: ... } }`, an atomic region `{}`.

<a id="SessionParams"></a>

#### `SessionParams` (interface)

```typescript
export interface SessionParams
```

The params of `actorState`, `actorContext` and `actorGet`.

<a id="SessionParams.session"></a>

##### `SessionParams.session`

```typescript
session: Session | Actor;
```

<a id="ActorStateResult"></a>

#### `ActorStateResult` (interface)

```typescript
export interface ActorStateResult
```

`actorState`'s result.

<a id="ActorStateResult.value"></a>

##### `ActorStateResult.value`

```typescript
readonly value: StateValue;
```

<a id="ActorStateResult.history"></a>

##### `ActorStateResult.history`

```typescript
readonly history: { readonly [history: string]: StateValue };
```

Where each history state the actor has recorded would return, by its id: its parent state as it would be entered again, in the shape of `value` (a deep history down to the atomic states it recorded; a shallow one names the child it recorded). A history state records when its parent is exited; one that has recorded nothing is absent, so this is `{}` before any exit. A hibernated actor's state is refused (`reason` `'state'`): wake it first.

<a id="ActorContextResult"></a>

#### `ActorContextResult` (interface)

```typescript
export interface ActorContextResult
```

`actorContext`'s result: each `<data>`, in the chart's order.

<a id="ActorContextResult.variables"></a>

##### `ActorContextResult.variables`

```typescript
readonly variables: { readonly [id: string]: ReceivedValue };
```

<a id="ActorGetResult"></a>

#### `ActorGetResult` (interface)

```typescript
export interface ActorGetResult
```

`actorGet`'s result.

<a id="ActorGetResult.session"></a>

##### `ActorGetResult.session`

```typescript
readonly session: number;
```

<a id="ActorGetResult.segment"></a>

##### `ActorGetResult.segment`

```typescript
readonly segment: number;
```

<a id="ActorGetResult.chart"></a>

##### `ActorGetResult.chart`

```typescript
readonly chart: string;
```

The chart's name.

<a id="ActorGetResult.parent"></a>

##### `ActorGetResult.parent`

```typescript
readonly parent: number | null;
```

The session that invoked it; `null` for a root actor.

<a id="ActorGetResult.mailbox"></a>

##### `ActorGetResult.mailbox`

```typescript
readonly mailbox: number;
```

Events waiting for it.

<a id="ActorGetResult.invocations"></a>

##### `ActorGetResult.invocations`

```typescript
readonly invocations: number;
```

Services it runs.

<a id="ActorGetResult.timers"></a>

##### `ActorGetResult.timers`

```typescript
readonly timers: readonly PendingSend[];
```

Its pending delayed sends (`<send delay>` not yet due, not cancelled), earliest first, at most 32: `timersPending` says how many it has.

<a id="ActorGetResult.timersPending"></a>

##### `ActorGetResult.timersPending`

```typescript
readonly timersPending: number;
```

How many delayed sends it has pending: more than `timers` holds when the list was cut.

<a id="PendingSend"></a>

#### `PendingSend` (interface)

```typescript
export interface PendingSend
```

A pending delayed send, in `actorGet`'s `timers`.

<a id="PendingSend.sendid"></a>

##### `PendingSend.sendid`

```typescript
readonly sendid: string | null;
```

The send's id (its `id`, or the one `idlocation` was given); `null` when it has none.

<a id="PendingSend.event"></a>

##### `PendingSend.event`

```typescript
readonly event: string;
```

The event's name.

<a id="PendingSend.due"></a>

##### `PendingSend.due`

```typescript
readonly due: number;
```

When it fires: milliseconds on the clock `host.now()` reads.

<a id="the-host"></a>

### The host

<a id="Host"></a>

#### `Host` (class)

```typescript
export class Host implements Disposable, AsyncDisposable
```

Runs actors: many charts, many images, from a handful of actors to millions, on the runtime's event loop. Inputs (`spawn`, `send`, ...) apply at once and schedule a turn; in its turns the host runs the actors and calls your handlers with what they sent out. There is no `run()`: `await host.idle()` waits until there is nothing left to do.

An open host with a pending deadline keeps the process alive, as a `setTimeout` does; `close()` ends it. With no deadline it keeps nothing alive: the process may exit with the host open and actors waiting, for an answer included.

```typescript title="example"
const compiled = compileCharts([{ name: 'order.scxml', text }]);
const host = new Host(compiled, { system: 'shop', log: (entry) => console.log(entry.text) });
compiled.close();
const order = host.spawn('order');
order.send('checkout');
await host.idle();
host.close();
```

**The application API**

<a id="Host.constructor"></a>

##### `Host.constructor`

```typescript
constructor(charts: Charts, options: HostOptions);
```

A host of system `options.system` running `charts` (each image added in order, a segment each: `addImage`), with the handlers and choices of `options`. Throws `TinyactorsError` (`TA_ERROR_INVALID`) for a config the host does not take, `TypeError` for options it does not take.

<a id="Host.system"></a>

##### `Host.system`

```typescript
readonly system: string;
```

The system id, `options.system`.

<a id="Host.closed"></a>

##### `Host.closed`

```typescript
readonly closed: boolean;
```

True once `close()` ran; every input of a closed host throws.

<a id="Host.nextDeadline"></a>

##### `Host.nextDeadline`

```typescript
readonly nextDeadline: number | undefined;
```

Milliseconds from the last idle turn to the next deadline (a delayed send, a timeout, or the telemetry encoder's flush once records are staged); `undefined` for none. An input given since that turn has not run yet, so its deadlines are not in it.

<a id="Host.spawn"></a>

##### `Host.spawn`

```typescript
spawn(chart: string | ChartRef, options?: SpawnOptions): Actor;
```

Starts an actor of `chart`, a chart's name (its current version) or a `ChartRef` (a version), and returns it. It runs in a later turn. Throws `TA_ERROR_INVALID` for a chart the host does not have.

<a id="Host.actor"></a>

##### `Host.actor`

```typescript
actor(which: Session | Actor | string | Address): Actor;
```

The live actor `which` names: a session, an Actor, the name it was spawned with (newest segment first), or an address of this system (text or an `Address`). Throws `StaleError` for no live actor, `InvalidError` for another system's address.

<a id="Host.actors"></a>

##### `Host.actors`

```typescript
actors(options?: { chart?: string }): Promise<Actor[]>;
```

Every live actor of the host (`actorList`, a page at a time), or the actors of the chart named `options.chart`.

<a id="Host.send"></a>

##### `Host.send`

```typescript
send(target: Session | Actor | string | Address, event: string, data?: Value, options?: SendOptions): void;
```

```typescript
send(message: SendMessage): void;
```

Puts `event`, with `data`, in the queue of the actor `target` names (a session or an address). Throws `TA_ERROR_STALE` for an actor that ended.

The same, from a `SendMessage` (the transport's `send.message`).

<a id="Host.terminate"></a>

##### `Host.terminate`

```typescript
terminate(session: Session | Actor): void;
```

Ends the actor. Throws `TA_ERROR_STALE` for one that already ended.

<a id="Host.idle"></a>

##### `Host.idle`

```typescript
idle(): Promise<void>;
```

Resolves at the next turn that finds nothing to do while no promise a handler returned is pending (an I/O processor's, a service's or its `receive`'s, a wake, telemetry, log, migration or typed-method handler's): the same promise to every caller until then. A handler's promise that never settles keeps it pending, and so does a handler that awaits `idle()` itself. Rejects with the turn's first error (a handler's, a typed method's without `onError`), or with `TA_ERROR_STATE` when the host is closed first; on a closed host it returns a promise rejected so. It does not wait for promises your handlers start and do not return.

<a id="Host.now"></a>

##### `Host.now`

```typescript
now(): number;
```

The host's clock in milliseconds, read now: a `SimulatedClock`'s time, or the runtime's monotonic clock, on the scale the host's deadlines and `snapshot()` use, so a restored host's goes on from its snapshot's. A journal of inputs records it beside each input, and a replay on a restored host moves its clock to each reading. It reads and advances nothing; a closed host throws `TA_ERROR_STATE`.

<a id="Host.actorState"></a>

##### `Host.actorState`

```typescript
actorState(params: SessionParams, onResult: OnResult<ActorStateResult>, onError?: OnError | null): void;
```

```typescript
actorState(params: SessionParams): Promise<ActorStateResult>;
```

An actor's active states, `{ value, history }`: a state id, or `{ parent: child }` for compound states. Params `{ session }`. `const { value } = await host.actorState({ session })`.

`actorState` given no handler: a promise of `{ value, history }`.

<a id="Host.actorContext"></a>

##### `Host.actorContext`

```typescript
actorContext(params: SessionParams, onResult: OnResult<ActorContextResult>, onError?: OnError | null): void;
```

```typescript
actorContext(params: SessionParams): Promise<ActorContextResult>;
```

An actor's variables, `{ variables }`. Params `{ session }`; refused for a hibernated actor. A variable that holds `undefined` reads `undefined`, apart from `null`; before the actor's first turn every variable is `undefined`, its spawn params included.

`actorContext` given no handler: a promise of `{ variables }`.

<a id="Host.close"></a>

##### `Host.close`

```typescript
close(): void;
```

Frees the host: the last telemetry requests go to the handler, the timer is cleared, pending typed methods and running services are dropped without being called. From a handler it waits for the end of the turn. Again: nothing.

<a id="Host.Symboldispose"></a>

##### `Host.Symboldispose`

```typescript
[Symbol.dispose](): void;
```

`close()`.

<a id="Host.SymbolasyncDispose"></a>

##### `Host.SymbolasyncDispose`

```typescript
[Symbol.asyncDispose](): Promise<void>;
```

`close()`, then the promises the telemetry handler returned at it.

**Operating a host**

<a id="Host.restore"></a>

##### `Host.restore`

```typescript
static restore(snapshot: Uint8Array | ArrayBuffer, charts: Charts, options: HostOptions): Host;
```

A new host running a snapshot `host.snapshot()` gave, with the system it was taken with (checked) and the options `new Host` takes, its `datamodel` the snapshot's; of `charts`, the images the snapshot does not hold (compared by their bytes) are added after its own. Every session stays the same, and its clock goes on from the snapshot's time, whatever clock reads it. Invocations that were running are announced again to `services`, with `invocation.restored` true. A snapshot of a build whose layout differs throws `TA_ERROR_INVALID`.

<a id="Host.ticksPerSecond"></a>

##### `Host.ticksPerSecond`

```typescript
readonly ticksPerSecond: number;
```

The host's clock rate, `system.ticksPerSecond`.

<a id="Host.quickjsHeapBytes"></a>

##### `Host.quickjsHeapBytes`

```typescript
readonly quickjsHeapBytes: number | undefined;
```

The quickjs engine's heap in bytes, every actor's together, read on each access (cheap): what `quickjs.memoryLimit` bounds. `undefined` on a native host and once closed.

<a id="Host.addImage"></a>

##### `Host.addImage`

```typescript
addImage(image: Uint8Array | ArrayBuffer): number;
```

Loads a compiled image, which it copies, and returns its segment, a number. A chart whose name the host already has gets a new version: new actors are of it, running ones stay on theirs until `migrate`. Throws `TA_ERROR_INVALID` for bytes that are not an image.

<a id="Host.chart"></a>

##### `Host.chart`

```typescript
chart(name: string): ChartRef;
```

The current version of chart `name`, for `spawn`. Throws `TA_ERROR_INVALID` when the host has no chart of that name.

<a id="Host.boot"></a>

##### `Host.boot`

```typescript
boot(segment: number): void;
```

Spawns the boot actors of the image of `segment`: a system manifest's `<actor>`s, or an actor of `compileCharts`' first chart.

<a id="Host.actorList"></a>

##### `Host.actorList`

```typescript
actorList(params: ActorListParams | undefined, onResult: OnResult<ActorListResult>, onError?: OnError | null): void;
```

```typescript
actorList(params?: ActorListParams): Promise<ActorListResult>;
```

The host's sessions a page at a time, `{ sessions, cursor }`, `cursor` `null` after the last page. Params `{ cursor?, limit? }` (1 to 512, default 256).

`actorList` given no handler: a promise of a page, `{ sessions, cursor }`.

<a id="Host.actorGet"></a>

##### `Host.actorGet`

```typescript
actorGet(params: SessionParams, onResult: OnResult<ActorGetResult>, onError?: OnError | null): void;
```

```typescript
actorGet(params: SessionParams): Promise<ActorGetResult>;
```

One actor, `{ session, segment, chart, parent, mailbox, invocations, timers, timersPending }`. Params `{ session }`.

`actorGet` given no handler: a promise of the actor.

<a id="Host.hostStats"></a>

##### `Host.hostStats`

```typescript
hostStats(params: NoParams, onResult: OnResult<HostStatsResult>, onError?: OnError | null): void;
```

```typescript
hostStats(params?: NoParams): Promise<HostStatsResult>;
```

The host's counters, `{ host, pools, charts }`: `pools` has one entry per live segment with each pool's `capacity`, `used` and `highWater`. No params: `await host.hostStats()`.

`hostStats` given no handler: a promise of the counters.

<a id="Host.hostConfig"></a>

##### `Host.hostConfig`

```typescript
hostConfig(params: NoParams, onResult: OnResult<EffectiveHostConfig>, onError?: OnError | null): void;
```

```typescript
hostConfig(params?: NoParams): Promise<EffectiveHostConfig>;
```

The config the host runs with, every default filled in. No params.

`hostConfig` given no handler: a promise of the effective config.

<a id="Host.traceConfigure"></a>

##### `Host.traceConfigure`

```typescript
traceConfigure(params: TraceConfigureParams | undefined, onResult: OnResult<EmptyResult>, onError?: OnError | null): void;
```

```typescript
traceConfigure(params?: TraceConfigureParams): Promise<EmptyResult>;
```

Sets what every actor traces: `{ detail, values, sample, records, rules }`.

`traceConfigure` given no handler: a promise of `{}`.

<a id="Host.traceWatch"></a>

##### `Host.traceWatch`

```typescript
traceWatch(params: TraceWatchParams, onResult: OnResult<TraceWatchResult>, onError?: OnError | null): void;
```

```typescript
traceWatch(params: TraceWatchParams): Promise<TraceWatchResult>;
```

Adds trace rules for a while: `{ rules, seconds }` (default 900); answers `{ id }`.

`traceWatch` given no handler: a promise of `{ id }`.

<a id="Host.traceUnwatch"></a>

##### `Host.traceUnwatch`

```typescript
traceUnwatch(params: TraceUnwatchParams, onResult: OnResult<EmptyResult>, onError?: OnError | null): void;
```

```typescript
traceUnwatch(params: TraceUnwatchParams): Promise<EmptyResult>;
```

Ends a watch early: `{ id }`.

`traceUnwatch` given no handler: a promise of `{}`.

<a id="Host.traceEnd"></a>

##### `Host.traceEnd`

```typescript
traceEnd(params: NoParams, onResult: OnResult<EmptyResult>, onError?: OnError | null): void;
```

```typescript
traceEnd(params?: NoParams): Promise<EmptyResult>;
```

Ends every open span now, marked incomplete, for the telemetry handler. Refused without `telemetry` in the config.

`traceEnd` given no handler: a promise of `{}`.

<a id="Host.traceSpansDecode"></a>

##### `Host.traceSpansDecode`

```typescript
traceSpansDecode(params: TraceSpansDecodeParams, onResult: OnResult<TraceSpansDecodeResult>, onError?: OnError | null): void;
```

```typescript
traceSpansDecode(params: TraceSpansDecodeParams): Promise<TraceSpansDecodeResult>;
```

The spans of a traces request: `{ traces }` (the bytes) answers `{ spans }`, each with `trace`, `span`, `parent`, `name`, `start`, `end`, `attributes`, ...

`traceSpansDecode` given no handler: a promise of `{ spans }`.

<a id="Host.metrics"></a>

##### `Host.metrics`

```typescript
metrics(): Uint8Array;
```

The host's counters now as an OTLP metrics request (a `Uint8Array`, for a collector's `/v1/metrics`). `TA_ERROR_STATE` without `telemetry` in the config.

<a id="Host.sweep"></a>

##### `Host.sweep`

```typescript
sweep(maxScan: number, limit: number): bigint[];
```

Finds cold actors: at most `limit` sessions that did not run since the previous sweep and can be hibernated now, looking at most at `maxScan` actors (each an integer from 0 to 2^32-1). The first sweep after an actor ran skips it.

<a id="Host.hibernate"></a>

##### `Host.hibernate`

```typescript
hibernate(session: Session | Actor): Uint8Array;
```

Takes the actor out of memory and returns its blob (a `Uint8Array`) for your store. `TA_ERROR_STATE` when it is not at rest (events waiting, a step not over, running an invoked child or service) and when it is not resident (already hibernated, its wake asked for and not given): the status does not tell the two apart. `TA_ERROR_STALE` for a session that ended or never was, `TA_ERROR_UNSUPPORTED` when a variable holds what the datamodel cannot store (the message names it); it stays where it is then.

<a id="Host.wake"></a>

##### `Host.wake`

```typescript
wake(session: Session | Actor, blob: Uint8Array | ArrayBuffer): void;
```

Puts a hibernated actor back from the blob `hibernate` gave; its waiting events run at the next turn. Only its latest blob: one of an earlier hibernation (a store that fell behind) throws `TA_ERROR_STALE`, another session's `TA_ERROR_INVALID`, and the actor stays hibernated. On a restored host a blob of a hibernation made after the snapshot is taken too.

<a id="Host.migrate"></a>

##### `Host.migrate`

```typescript
migrate(options?: MigrateOptions): number;
```

Starts moving running actors (every chart's, `chart`'s, or one `session`) to the current version of their chart, in later turns; each gets `error.platform.upgrade` with its old variables. Returns the migration's id, which `migrated` and `migrationDone` name. Throws `TA_ERROR_INVALID` for a chart the host does not have and `TA_ERROR_STALE` for a session that ended.

<a id="Host.snapshot"></a>

##### `Host.snapshot`

```typescript
snapshot(): Uint8Array;
```

The whole host as one `Uint8Array`: every segment, the images, the system id, the host's time (its clocks advanced first: the time of the call, as `now()` reads it) and the datamodel's state, for `Host.restore` on the same build of the package. Only when quiescent: from a handler, with an effect or a reply pending, or during a migration it throws `TA_ERROR_STATE`; a value outside the value table throws `TA_ERROR_UNSUPPORTED`.

**Wire format**

<a id="Host.fail"></a>

##### `Host.fail`

```typescript
fail(sender: Session | Actor | string | Address, sendid?: string): void;
```

Tells a sender that its send could not be delivered: the actor `sender` (a session or its address, the send's `origin`) gets `error.communication` with `sendid`.

<a id="Host.sendMany"></a>

##### `Host.sendMany`

```typescript
sendMany(items: readonly SendMessage[]): number;
```

Sends each of `items` in order, and returns how many were taken: the rest, from the first one refused, were not sent.

<a id="operating-a-host"></a>

## Operating a host

What an operator's tools, a deploy script or an admin endpoint use: the host's config and sizes, inspection, telemetry, hibernation by a policy of your own, images, segments and migration, snapshots (README.md, "Operating a host"). The Host's own methods for them are grouped in the class, under the same heading.

<a id="config-and-sizes"></a>

### Config and sizes

<a id="HostConfig"></a>

#### `HostConfig` (interface)

```typescript
export interface HostConfig
```

The rest of the host's config, `options.config`: plain values, checked by the host, every absent key a default (the host's, never the package's). A key the host does not take, or a value of the wrong type, throws a `TinyactorsError` (`TA_ERROR_INVALID`) at `new Host`, with the host's `reason` and the key as `path` (`system.maxActors`). The system id is `options.system` and the I/O processors `options.ioProcessors`: a `systemID` or `ioProcessors` here is a `TypeError`. `host.hostConfig()` answers the whole config with every default filled in, as [`EffectiveHostConfig`](#EffectiveHostConfig).

```typescript title="example"
const config = { system: { maxActors: 10_000 }, telemetry: { resource: { 'service.name': 'orders' } } };
```

<a id="HostConfig.system"></a>

##### `HostConfig.system`

```typescript
system?: SystemConfig;
```

The capacities of each new segment, each its first size, not a cap (a pool that fills grows its segment).

<a id="HostConfig.migrateQuantum"></a>

##### `HostConfig.migrateQuantum`

```typescript
migrateQuantum?: number;
```

Actors a migration looks at per run (default 256).

<a id="HostConfig.telemetry"></a>

##### `HostConfig.telemetry`

```typescript
telemetry?: TelemetryConfig;
```

Present: the host has an OTLP encoder, and `options.telemetry` gets its requests. Absent: none, and nothing is paid for it.

<a id="SystemConfig"></a>

#### `SystemConfig` (interface)

```typescript
export interface SystemConfig
```

Each new segment's first sizes: unsigned integers, 0 or absent for the host's default; larger values are clamped to the host's limits.

<a id="SystemConfig.maxActors"></a>

##### `SystemConfig.maxActors`

```typescript
maxActors?: number;
```

Default 64, at most 8388606.

<a id="SystemConfig.maxEvents"></a>

##### `SystemConfig.maxEvents`

```typescript
maxEvents?: number;
```

Queued events; default 256.

<a id="SystemConfig.maxTimers"></a>

##### `SystemConfig.maxTimers`

```typescript
maxTimers?: number;
```

Delayed sends and timeouts; default 64.

<a id="SystemConfig.workspaces"></a>

##### `SystemConfig.workspaces`

```typescript
workspaces?: number;
```

Actors that may be in a step at once; default 4.

<a id="SystemConfig.maxRequests"></a>

##### `SystemConfig.maxRequests`

```typescript
maxRequests?: number;
```

Default 16.

<a id="SystemConfig.outbox"></a>

##### `SystemConfig.outbox`

```typescript
outbox?: number;
```

Default 64.

<a id="SystemConfig.quantum"></a>

##### `SystemConfig.quantum`

```typescript
quantum?: number;
```

Default 1000.

<a id="SystemConfig.instanceBytes"></a>

##### `SystemConfig.instanceBytes`

```typescript
instanceBytes?: number;
```

Default 0: derived from the image and `maxActors`.

<a id="SystemConfig.stringBytes"></a>

##### `SystemConfig.stringBytes`

```typescript
stringBytes?: number;
```

Default 16384 + 16 per actor of `maxActors`.

<a id="SystemConfig.ticksPerSecond"></a>

##### `SystemConfig.ticksPerSecond`

```typescript
ticksPerSecond?: number;
```

The host's clock rate; default 1e9 (nanoseconds).

<a id="SystemConfig.traceBytes"></a>

##### `SystemConfig.traceBytes`

```typescript
traceBytes?: number;
```

The trace journal; default 131072, at least 65536.

<a id="SystemConfig.traceContexts"></a>

##### `SystemConfig.traceContexts`

```typescript
traceContexts?: number;
```

Default `maxEvents`.

<a id="SystemConfig.traceRules"></a>

##### `SystemConfig.traceRules`

```typescript
traceRules?: number;
```

Default 16, at most 255.

<a id="SystemConfig.traceSeed"></a>

##### `SystemConfig.traceSeed`

```typescript
traceSeed?: number;
```

The seed of the trace IDs: the same seed gives the same IDs. Without one, each new host draws a random seed (`crypto.getRandomValues`); set it to reproduce a test's traces.

<a id="SystemConfig.tracing"></a>

##### `SystemConfig.tracing`

```typescript
tracing?: boolean;
```

Write trace records (default true), so export or a watch can be turned on later.

<a id="TelemetryConfig"></a>

#### `TelemetryConfig` (interface)

```typescript
export interface TelemetryConfig
```

The OTLP encoder: unsigned integers, 0 or absent for its default.

<a id="TelemetryConfig.stagingBytes"></a>

##### `TelemetryConfig.stagingBytes`

```typescript
stagingBytes?: number;
```

Default 1048576, from 65536 to 1073741824.

<a id="TelemetryConfig.logBytes"></a>

##### `TelemetryConfig.logBytes`

```typescript
logBytes?: number;
```

Default a quarter of `stagingBytes`.

<a id="TelemetryConfig.openSpans"></a>

##### `TelemetryConfig.openSpans`

```typescript
openSpans?: number;
```

Default 1024.

<a id="TelemetryConfig.chunks"></a>

##### `TelemetryConfig.chunks`

```typescript
chunks?: number;
```

Default 8 per open span.

<a id="TelemetryConfig.scopes"></a>

##### `TelemetryConfig.scopes`

```typescript
scopes?: number;
```

Default 64.

<a id="TelemetryConfig.valueLimit"></a>

##### `TelemetryConfig.valueLimit`

```typescript
valueLimit?: number;
```

Default 256.

<a id="TelemetryConfig.renderBytes"></a>

##### `TelemetryConfig.renderBytes`

```typescript
renderBytes?: number;
```

Default 16384.

<a id="TelemetryConfig.resourceBytes"></a>

##### `TelemetryConfig.resourceBytes`

```typescript
resourceBytes?: number;
```

Default 4096.

<a id="TelemetryConfig.metricBytes"></a>

##### `TelemetryConfig.metricBytes`

```typescript
metricBytes?: number;
```

Default 65536.

<a id="TelemetryConfig.spanMetricCharts"></a>

##### `TelemetryConfig.spanMetricCharts`

```typescript
spanMetricCharts?: number;
```

Default 64.

<a id="TelemetryConfig.flushInterval"></a>

##### `TelemetryConfig.flushInterval`

```typescript
flushInterval?: number;
```

A request is ready this long after its first record, in the host's clock ticks; 0 or absent: only when the staging is full.

<a id="TelemetryConfig.linkParents"></a>

##### `TelemetryConfig.linkParents`

```typescript
linkParents?: boolean;
```

A macrostep is a root span linked to its cause (default false).

<a id="TelemetryConfig.values"></a>

##### `TelemetryConfig.values`

```typescript
values?: boolean;
```

Event data and assigned values in the spans (default false: they may hold personal data).

<a id="TelemetryConfig.logs"></a>

##### `TelemetryConfig.logs`

```typescript
logs?: boolean;
```

`<log>`s and failed actions as log records (default true).

<a id="TelemetryConfig.resource"></a>

##### `TelemetryConfig.resource`

```typescript
resource?: { readonly [key: string]: string };
```

Attributes on every request (`service.name`, ...), at most 32.

<a id="EffectiveHostConfig"></a>

#### `EffectiveHostConfig` (interface)

```typescript
export interface EffectiveHostConfig
```

The config a host runs with, every key present, as `hostConfig` answers it: a host made from it answers the same.

<a id="EffectiveHostConfig.systemID"></a>

##### `EffectiveHostConfig.systemID`

```typescript
readonly systemID: string;
```

<a id="EffectiveHostConfig.system"></a>

##### `EffectiveHostConfig.system`

```typescript
readonly system: Readonly<Required<SystemConfig>>;
```

<a id="EffectiveHostConfig.ioProcessors"></a>

##### `EffectiveHostConfig.ioProcessors`

```typescript
readonly ioProcessors: readonly { readonly type: string; readonly location?: string }[];
```

The I/O processors, in the order `options.ioProcessors` gave them.

<a id="EffectiveHostConfig.migrateQuantum"></a>

##### `EffectiveHostConfig.migrateQuantum`

```typescript
readonly migrateQuantum: number;
```

<a id="EffectiveHostConfig.telemetry"></a>

##### `EffectiveHostConfig.telemetry`

```typescript
readonly telemetry?: Readonly<Required<TelemetryConfig>>;
```

Only when the host has an encoder.

<a id="images-segments-and-migration"></a>

### Images, segments and migration

<a id="ChartRef"></a>

#### `ChartRef` (interface)

```typescript
export interface ChartRef
```

A chart's current version in a host, from `host.chart(name)`, for `host.spawn`.

<a id="ChartRef.segment"></a>

##### `ChartRef.segment`

```typescript
readonly segment: number;
```

The segment of the image that holds it.

<a id="ChartRef.chart"></a>

##### `ChartRef.chart`

```typescript
readonly chart: number;
```

Its index in that image.

<a id="MigrateOptions"></a>

#### `MigrateOptions` (interface)

```typescript
export interface MigrateOptions
```

The options of `host.migrate`.

<a id="MigrateOptions.chart"></a>

##### `MigrateOptions.chart`

```typescript
chart?: string;
```

A chart's name; none: every chart.

<a id="MigrateOptions.session"></a>

##### `MigrateOptions.session`

```typescript
session?: Session | Actor;
```

One actor.

<a id="MigrateOptions.wake"></a>

##### `MigrateOptions.wake`

```typescript
wake?: boolean;
```

Load the hibernated actors from the store (as `resident` allows), for the migration to move.

<a id="MigrateOptions.timeout"></a>

##### `MigrateOptions.timeout`

```typescript
timeout?: number;
```

Milliseconds of the host's clock from now, rounded up to its next tick; 0 or none: no timeout.

<a id="Migrated"></a>

#### `Migrated` (interface)

```typescript
export interface Migrated
```

An actor a migration moved: a view, valid while the handler runs.

<a id="Migrated.host"></a>

##### `Migrated.host`

```typescript
readonly host: Host;
```

The host that handed it out.

<a id="Migrated.session"></a>

##### `Migrated.session`

```typescript
readonly session: bigint;
```

<a id="Migrated.segment"></a>

##### `Migrated.segment`

```typescript
readonly segment: number;
```

The segment of its new version.

<a id="Migrated.chart"></a>

##### `Migrated.chart`

```typescript
readonly chart: string;
```

The chart's name.

<a id="Migrated.migration"></a>

##### `Migrated.migration`

```typescript
readonly migration: number;
```

The migration's id, as `host.migrate` returned it.

<a id="MigrationFailure"></a>

#### `MigrationFailure` (interface)

```typescript
export interface MigrationFailure
```

A session a migration could not move: it stays on its version. `reason` names core's status, `'TA_ERROR_UNSUPPORTED'` when its state cannot be written out (a value outside the value table).

<a id="MigrationFailure.session"></a>

##### `MigrationFailure.session`

```typescript
readonly session: bigint;
```

<a id="MigrationFailure.reason"></a>

##### `MigrationFailure.reason`

```typescript
readonly reason: string;
```

<a id="MigrationResult"></a>

#### `MigrationResult` (interface)

```typescript
export interface MigrationResult
```

A migration's end: how many actors it moved, the ones it could not move and why (they stay on their version), and the sessions its timeout left behind.

<a id="MigrationResult.migration"></a>

##### `MigrationResult.migration`

```typescript
readonly migration: number;
```

<a id="MigrationResult.migrated"></a>

##### `MigrationResult.migrated`

```typescript
readonly migrated: number;
```

<a id="MigrationResult.failed"></a>

##### `MigrationResult.failed`

```typescript
readonly failed: readonly MigrationFailure[];
```

<a id="MigrationResult.pending"></a>

##### `MigrationResult.pending`

```typescript
readonly pending: readonly bigint[];
```

<a id="inspection"></a>

### Inspection

<a id="ActorListParams"></a>

#### `ActorListParams` (interface)

```typescript
export interface ActorListParams
```

The params of `actorList`.

<a id="ActorListParams.cursor"></a>

##### `ActorListParams.cursor`

```typescript
cursor?: number;
```

From the previous page; absent: the first.

<a id="ActorListParams.limit"></a>

##### `ActorListParams.limit`

```typescript
limit?: number;
```

1 to 512, default 256.

<a id="ActorListResult"></a>

#### `ActorListResult` (interface)

```typescript
export interface ActorListResult
```

`actorList`'s result: a page of sessions.

<a id="ActorListResult.sessions"></a>

##### `ActorListResult.sessions`

```typescript
readonly sessions: readonly number[];
```

<a id="ActorListResult.cursor"></a>

##### `ActorListResult.cursor`

```typescript
readonly cursor: number | null;
```

The next page's cursor, opaque; `null` after the last page.

<a id="Pool"></a>

#### `Pool` (interface)

```typescript
export interface Pool
```

A pool of a segment: its size, what it holds, the most it held.

<a id="Pool.capacity"></a>

##### `Pool.capacity`

```typescript
readonly capacity: number;
```

<a id="Pool.used"></a>

##### `Pool.used`

```typescript
readonly used: number;
```

<a id="Pool.highWater"></a>

##### `Pool.highWater`

```typescript
readonly highWater: number;
```

<a id="SegmentPools"></a>

#### `SegmentPools` (interface)

```typescript
export interface SegmentPools
```

One live segment's pools, in `host.stats`.

<a id="SegmentPools.segment"></a>

##### `SegmentPools.segment`

```typescript
readonly segment: number;
```

The segment, as `addImage` returned it.

<a id="SegmentPools.actors"></a>

##### `SegmentPools.actors`

```typescript
readonly actors: Pool;
```

<a id="SegmentPools.events"></a>

##### `SegmentPools.events`

```typescript
readonly events: Pool;
```

<a id="SegmentPools.timers"></a>

##### `SegmentPools.timers`

```typescript
readonly timers: Pool;
```

<a id="SegmentPools.workspaces"></a>

##### `SegmentPools.workspaces`

```typescript
readonly workspaces: Pool;
```

<a id="SegmentPools.requests"></a>

##### `SegmentPools.requests`

```typescript
readonly requests: Pool;
```

<a id="SegmentPools.slabBytes"></a>

##### `SegmentPools.slabBytes`

```typescript
readonly slabBytes: Pool;
```

The slab of instances and strings, in bytes.

<a id="ChartStats"></a>

#### `ChartStats` (interface)

```typescript
export interface ChartStats
```

One chart's counters, summed over every segment, retired versions included.

<a id="ChartStats.name"></a>

##### `ChartStats.name`

```typescript
readonly name: string;
```

<a id="ChartStats.actors"></a>

##### `ChartStats.actors`

```typescript
readonly actors: number;
```

<a id="ChartStats.hibernated"></a>

##### `ChartStats.hibernated`

```typescript
readonly hibernated: number;
```

<a id="ChartStats.spawned"></a>

##### `ChartStats.spawned`

```typescript
readonly spawned: number;
```

<a id="ChartStats.ended"></a>

##### `ChartStats.ended`

```typescript
readonly ended: number;
```

<a id="ChartStats.turns"></a>

##### `ChartStats.turns`

```typescript
readonly turns: number;
```

<a id="ChartStats.macrosteps"></a>

##### `ChartStats.macrosteps`

```typescript
readonly macrosteps: number;
```

<a id="ChartStats.fuel"></a>

##### `ChartStats.fuel`

```typescript
readonly fuel: number;
```

<a id="ChartStats.errorsExecution"></a>

##### `ChartStats.errorsExecution`

```typescript
readonly errorsExecution: number;
```

<a id="ChartStats.errorsCommunication"></a>

##### `ChartStats.errorsCommunication`

```typescript
readonly errorsCommunication: number;
```

<a id="ChartStats.errorsPlatform"></a>

##### `ChartStats.errorsPlatform`

```typescript
readonly errorsPlatform: number;
```

<a id="ChartStats.faults"></a>

##### `ChartStats.faults`

```typescript
readonly faults: number;
```

<a id="HostStatsResult"></a>

#### `HostStatsResult` (interface)

```typescript
export interface HostStatsResult
```

`hostStats`'s result.

<a id="HostStatsResult.host"></a>

##### `HostStatsResult.host`

```typescript
readonly host: {
    readonly segments: number;
    readonly actors: number;
    readonly hibernated: number;
    readonly runnable: number;
    readonly migrations: number;
    /** The live segments' regions; the host's copies of the images are not
     * in it. */
    readonly regionBytes: number;
    readonly delivered: number;
    readonly routed: number;
    readonly migrated: number;
    readonly retired: number;
    readonly fuelClock: number;
  };
```

<a id="HostStatsResult.pools"></a>

##### `HostStatsResult.pools`

```typescript
readonly pools: readonly SegmentPools[];
```

One entry per live segment, in segment order.

<a id="HostStatsResult.charts"></a>

##### `HostStatsResult.charts`

```typescript
readonly charts: readonly ChartStats[];
```

<a id="tracing"></a>

### Tracing

<a id="TraceRule"></a>

#### `TraceRule` (interface)

```typescript
export interface TraceRule
```

A trace rule of `traceConfigure` and `traceWatch`: each absent field matches anything.

<a id="TraceRule.at"></a>

##### `TraceRule.at`

```typescript
at?: 'start' | 'take';
```

<a id="TraceRule.chart"></a>

##### `TraceRule.chart`

```typescript
chart?: string;
```

<a id="TraceRule.actor"></a>

##### `TraceRule.actor`

```typescript
actor?: string;
```

An actor's name; a trailing `*` makes it a prefix.

<a id="TraceRule.event"></a>

##### `TraceRule.event`

```typescript
event?: string;
```

An event descriptor, SCXML's prefix rule.

<a id="TraceRule.session"></a>

##### `TraceRule.session`

```typescript
session?: Session;
```

<a id="TraceRule.from"></a>

##### `TraceRule.from`

```typescript
from?: readonly ('host' | 'actor' | 'timer' | 'spawn' | 'sampled' | 'unsampled')[];
```

<a id="TraceRule.sample"></a>

##### `TraceRule.sample`

```typescript
sample?: 'keep' | 'sample' | 'drop' | number;
```

What a match decides (default `'keep'`); a number samples that share of trace IDs.

<a id="TraceRule.detail"></a>

##### `TraceRule.detail`

```typescript
detail?: TraceDetail;
```

<a id="TraceRule.values"></a>

##### `TraceRule.values`

```typescript
values?: boolean;
```

<a id="TraceRule.perSecond"></a>

##### `TraceRule.perSecond`

```typescript
perSecond?: number;
```

<a id="TraceRule.burst"></a>

##### `TraceRule.burst`

```typescript
burst?: number;
```

<a id="TraceDetail"></a>

#### `TraceDetail` (type)

```typescript
export type TraceDetail = 'summary' | 'decisions' | 'full' | 'off';
```

How much a trace records.

<a id="TraceConfigureParams"></a>

#### `TraceConfigureParams` (interface)

```typescript
export interface TraceConfigureParams
```

The params of `traceConfigure`, which replace the last ones.

<a id="TraceConfigureParams.detail"></a>

##### `TraceConfigureParams.detail`

```typescript
detail?: TraceDetail;
```

Default `'summary'`.

<a id="TraceConfigureParams.values"></a>

##### `TraceConfigureParams.values`

```typescript
values?: boolean;
```

Default false.

<a id="TraceConfigureParams.sample"></a>

##### `TraceConfigureParams.sample`

```typescript
sample?: number;
```

The share of new traces sampled, 0 to 1 (default 1).

<a id="TraceConfigureParams.records"></a>

##### `TraceConfigureParams.records`

```typescript
records?: boolean;
```

False writes no records; traceparents still flow (default true).

<a id="TraceConfigureParams.rules"></a>

##### `TraceConfigureParams.rules`

```typescript
rules?: readonly TraceRule[];
```

At most 32.

<a id="TraceWatchParams"></a>

#### `TraceWatchParams` (interface)

```typescript
export interface TraceWatchParams
```

The params of `traceWatch`.

<a id="TraceWatchParams.rules"></a>

##### `TraceWatchParams.rules`

```typescript
rules: readonly TraceRule[];
```

At least one.

<a id="TraceWatchParams.seconds"></a>

##### `TraceWatchParams.seconds`

```typescript
seconds?: number | null;
```

On the host's clock; `null`: no end (default 900).

<a id="TraceWatchResult"></a>

#### `TraceWatchResult` (interface)

```typescript
export interface TraceWatchResult
```

`traceWatch`'s result.

<a id="TraceWatchResult.id"></a>

##### `TraceWatchResult.id`

```typescript
readonly id: number;
```

<a id="TraceUnwatchParams"></a>

#### `TraceUnwatchParams` (interface)

```typescript
export interface TraceUnwatchParams
```

The params of `traceUnwatch`.

<a id="TraceUnwatchParams.id"></a>

##### `TraceUnwatchParams.id`

```typescript
id: number;
```

<a id="TraceSpansDecodeParams"></a>

#### `TraceSpansDecodeParams` (interface)

```typescript
export interface TraceSpansDecodeParams
```

The params of `traceSpansDecode`.

<a id="TraceSpansDecodeParams.traces"></a>

##### `TraceSpansDecodeParams.traces`

```typescript
traces: Uint8Array;
```

An OTLP traces request, as the telemetry handler gets it.

<a id="SpanEvent"></a>

#### `SpanEvent` (interface)

```typescript
export interface SpanEvent
```

A span event.

<a id="SpanEvent.name"></a>

##### `SpanEvent.name`

```typescript
readonly name: string;
```

<a id="SpanEvent.time"></a>

##### `SpanEvent.time`

```typescript
readonly time: number | bigint;
```

<a id="SpanEvent.attributes"></a>

##### `SpanEvent.attributes`

```typescript
readonly attributes: { readonly [key: string]: ReceivedValue };
```

<a id="Span"></a>

#### `Span` (interface)

```typescript
export interface Span
```

A span of `traceSpansDecode`.

<a id="Span.trace"></a>

##### `Span.trace`

```typescript
readonly trace: string;
```

Lowercase hex.

<a id="Span.span"></a>

##### `Span.span`

```typescript
readonly span: string;
```

<a id="Span.parent"></a>

##### `Span.parent`

```typescript
readonly parent: string | null;
```

`null` for a root span.

<a id="Span.name"></a>

##### `Span.name`

```typescript
readonly name: string;
```

<a id="Span.kind"></a>

##### `Span.kind`

```typescript
readonly kind: number;
```

OTLP's span kind.

<a id="Span.start"></a>

##### `Span.start`

```typescript
readonly start: number | bigint;
```

Nanoseconds since the Unix epoch (a bigint past 2^53).

<a id="Span.end"></a>

##### `Span.end`

```typescript
readonly end: number | bigint;
```

<a id="Span.status"></a>

##### `Span.status`

```typescript
readonly status: number;
```

OTLP's status code.

<a id="Span.statusMessage"></a>

##### `Span.statusMessage`

```typescript
readonly statusMessage: string;
```

<a id="Span.attributes"></a>

##### `Span.attributes`

```typescript
readonly attributes: { readonly [key: string]: ReceivedValue };
```

<a id="Span.events"></a>

##### `Span.events`

```typescript
readonly events: readonly SpanEvent[];
```

<a id="TraceSpansDecodeResult"></a>

#### `TraceSpansDecodeResult` (interface)

```typescript
export interface TraceSpansDecodeResult
```

`traceSpansDecode`'s result.

<a id="TraceSpansDecodeResult.spans"></a>

##### `TraceSpansDecodeResult.spans`

```typescript
readonly spans: readonly Span[];
```

<a id="EmptyResult"></a>

#### `EmptyResult` (type)

```typescript
export type EmptyResult = { readonly [key: string]: never };
```

The result of the methods that answer nothing: `{}`.

<a id="wire-format"></a>

## Wire format

What values, sends and addresses become when they leave the process: CBOR, a transport's messages, addresses read into their parts, SCXML's BasicHTTP, an OTLP export read back (README.md, "Wire format"). An application of one host and its own store needs none of it.

<a id="values-as-bytes"></a>

### Values as bytes

<a id="Encodable"></a>

#### `Encodable` (type)

```typescript
export type Encodable =
  | Value
  | Address
  | Encodable[]
  | { [key: string]: Encodable };
```

What `encode` writes: a [`Value`](#Value), or one holding `Address`es, which it writes as CBOR's tag 32 (an actor reference).

<a id="encode"></a>

#### `encode` (function)

```typescript
export function encode(value: Encodable): Uint8Array;
```

A value as CBOR bytes, the form to store or send it in. An `Address` is tag 32 on its text.

Throws a `TinyactorsError`: `TA_ERROR_UNSUPPORTED` for what is not a [`Value`](#Value) (a function, a symbol, a `Date`, a `Map`, a class's instance, a typed array other than `Uint8Array`), `TA_ERROR_INVALID` for what a value cannot hold (a string with a lone surrogate, a `bigint` past 64 bits, a cycle or nesting deeper than 64). A getter's exception passes through.

```typescript title="example"
const bytes = encode({ sku: 'tea', qty: 2 });
decode(bytes); // { sku: 'tea', qty: 2 }
```

<a id="decode"></a>

#### `decode` (function)

```typescript
export function decode(bytes: Uint8Array | ArrayBuffer): ReceivedValue;
```

The value of the one CBOR item that fills `bytes`: the inverse of [`encode`](#encode), tag 32 an `Address`. Throws a `TinyactorsError` (`TA_ERROR_INVALID`) for bytes that are not one such item, a `TypeError` for an argument that is not bytes.

<a id="addresses"></a>

### Addresses

<a id="Address"></a>

#### `Address` (class)

```typescript
export class Address
```

An actor's address: `tinyactors://<system>/#_scxml_<session>`, or `tinyactors://<system>/@<name>` for a named actor. Immutable. Its parts are read from the text on each access, `undefined` for a part the text lacks (any text makes an `Address`; one that is not an address has no parts).

<a id="Address.constructor"></a>

##### `Address.constructor`

```typescript
constructor(text: string);
```

<a id="Address.fromSession"></a>

##### `Address.fromSession`

```typescript
static fromSession(system: string, session: Session): Address;
```

The address of a session of system `system`.

<a id="Address.fromName"></a>

##### `Address.fromName`

```typescript
static fromName(system: string, name: string): Address;
```

The address of the actor named `name` in system `system`; the name is percent-encoded.

<a id="Address.text"></a>

##### `Address.text`

```typescript
readonly text: string;
```

<a id="Address.system"></a>

##### `Address.system`

```typescript
readonly system: string | undefined;
```

The system id.

<a id="Address.session"></a>

##### `Address.session`

```typescript
readonly session: bigint | undefined;
```

<a id="Address.name"></a>

##### `Address.name`

```typescript
readonly name: string | undefined;
```

The actor's name, decoded.

<a id="Address.toString"></a>

##### `Address.toString`

```typescript
toString(): string;
```

The text.

<a id="Address.toJSON"></a>

##### `Address.toJSON`

```typescript
toJSON(): string;
```

The text, so `JSON.stringify` writes an address as a string, which `new Address(text)` and `host.send` read back.

<a id="other-systems"></a>

### Other systems

<a id="SendMessage"></a>

#### `SendMessage` (interface)

```typescript
export interface SendMessage
```

An event for `host.send(message)` and `host.sendMany(items)`, in the shape `send.message` has. Keys it does not know are ignored.

<a id="SendMessage.target"></a>

##### `SendMessage.target`

```typescript
target: Session | Actor | string | Address;
```

A session, or an address (string or `Address`); a local address is resolved to its actor.

<a id="SendMessage.event"></a>

##### `SendMessage.event`

```typescript
event: string;
```

<a id="SendMessage.data"></a>

##### `SendMessage.data`

```typescript
data?: Value;
```

<a id="SendMessage.sendid"></a>

##### `SendMessage.sendid`

```typescript
sendid?: string | null;
```

The event's `_event.sendid`.

<a id="SendMessage.origin"></a>

##### `SendMessage.origin`

```typescript
origin?: string | Address | null;
```

The event's `_event.origin`: where an answer goes.

<a id="SendMessage.traceparent"></a>

##### `SendMessage.traceparent`

```typescript
traceparent?: string | null;
```

The trace the event continues, as W3C text; text that does not parse starts a new one.

<a id="basichttp"></a>

### BasicHTTP

<a id="HTTPField"></a>

#### `HTTPField` (interface)

```typescript
export interface HTTPField
```

A form field of a BasicHTTP message.

<a id="HTTPField.name"></a>

##### `HTTPField.name`

```typescript
name: string;
```

<a id="HTTPField.value"></a>

##### `HTTPField.value`

```typescript
value: string;
```

<a id="HTTPPost"></a>

#### `HTTPPost` (interface)

```typescript
export interface HTTPPost
```

A BasicHTTP POST, the request SCXML's HTTP processor makes for a send.

<a id="HTTPPost.url"></a>

##### `HTTPPost.url`

```typescript
url: string;
```

`http://host[:port]/path`.

<a id="HTTPPost.event"></a>

##### `HTTPPost.event`

```typescript
event?: string;
```

Written as the `_scxmleventname` field.

<a id="HTTPPost.fields"></a>

##### `HTTPPost.fields`

```typescript
fields?: readonly HTTPField[];
```

<a id="HTTPPost.body"></a>

##### `HTTPPost.body`

```typescript
body?: string;
```

The body, used when there are no fields; percent-encoded.

<a id="HTTPRequest"></a>

#### `HTTPRequest` (interface)

```typescript
export interface HTTPRequest
```

An incoming BasicHTTP request, read.

<a id="HTTPRequest.method"></a>

##### `HTTPRequest.method`

```typescript
readonly method: string;
```

<a id="HTTPRequest.target"></a>

##### `HTTPRequest.target`

```typescript
readonly target: string;
```

<a id="HTTPRequest.body"></a>

##### `HTTPRequest.body`

```typescript
readonly body: string;
```

The body as received.

<a id="HTTPRequest.event"></a>

##### `HTTPRequest.event`

```typescript
readonly event: string;
```

The `_scxmleventname` field, else `HTTP.<METHOD>`.

<a id="HTTPRequest.fields"></a>

##### `HTTPRequest.fields`

```typescript
readonly fields: readonly HTTPField[];
```

The decoded form fields, but `_scxmleventname`.

<a id="encodeHTTPPost"></a>

#### `encodeHTTPPost` (function)

```typescript
export function encodeHTTPPost(post: HTTPPost): Uint8Array;
```

The bytes of a BasicHTTP POST, to write to a socket. A URL that is not `http://host[:port]/path` throws `TA_ERROR_INVALID`.

<a id="parseHTTPRequest"></a>

#### `parseHTTPRequest` (function)

```typescript
export function parseHTTPRequest(message: Uint8Array | ArrayBuffer): HTTPRequest;
```

Reads an incoming BasicHTTP request: its event and form fields, for `host.send`. A malformed request throws `TA_ERROR_INVALID`.

<a id="an-otlp-export-read-back"></a>

### An OTLP export, read back

<a id="decodeTraces"></a>

#### `decodeTraces` (function)

```typescript
export function decodeTraces(bytes: Uint8Array | ArrayBuffer): DecodedSpan[];
```

The spans of an OTLP ExportTraceServiceRequest (the bytes a telemetry handler gets for `'traces'`, or any exporter's), read without a host: for tests and a collector of your own. Throws an `InvalidError` for bytes that are not such a request, a `TypeError` for an argument that is not bytes.

```typescript title="example"
const spans = decodeTraces(data);
console.log(spans.map((span) => `${span.name} ${span.scope.attributes['tinyactors.chart.name']}`));
```

<a id="DecodedSpan"></a>

#### `DecodedSpan` (interface)

```typescript
export interface DecodedSpan extends Span
```

A span as [`decodeTraces`](#decodeTraces) gives it: a [`Span`](#Span) and more of what the request holds.

<a id="DecodedSpan.flags"></a>

##### `DecodedSpan.flags`

```typescript
readonly flags: number;
```

OTLP's Span.flags.

<a id="DecodedSpan.links"></a>

##### `DecodedSpan.links`

```typescript
readonly links: readonly { readonly trace: string; readonly span: string; readonly attributes: { readonly [key: string]: ReceivedValue } }[];
```

<a id="DecodedSpan.resource"></a>

##### `DecodedSpan.resource`

```typescript
readonly resource: { readonly [key: string]: ReceivedValue };
```

Its resource's attributes (`service.name`, ...).

<a id="DecodedSpan.scope"></a>

##### `DecodedSpan.scope`

```typescript
readonly scope: { readonly name: string; readonly version: string; readonly attributes: { readonly [key: string]: ReceivedValue } };
```

Its instrumentation scope.
