# TypeScript API reference · Loa Arbor

Every actor type with its options and methods in tables, then the contexts your code receives, tools, the bundle, the modules a script imports, and the limits. Each entry says what it does and gives a default only where the source states one.

## How to read this page

An Arbor app is a **bundle**: the actors and agents you define, plus the declarations around them (who may join, which models, which HTTP endpoints). You build one with `bundle({...})`, and every app file ends with `export default bundle({...})`. The server finds every definition reachable from the `roots` you list and runs them.

Definitions are immutable values. `actor('name', {...})` and `agent('name', {...})` return a definition, and every method on it (`.wake()`, `.tool()`, `.hooks()` and the rest) returns a new one, so you chain them. Copy a definition with `extend()`, not with a spread. A few methods say "call once": calling them twice is an error.

In the tables, **Default** is filled in only where the source states one. A dash means the source states none, not that there is none. Durations are a Go-style string (`'300ms'`, `'5m'`, `'1h30m'`) or a number of milliseconds. `Json` means anything that survives `JSON.stringify`. Every value your code hands to Arbor to encode (what `receive`, a tool's `handler`, `before` and `after`, and a relay's `summary` return, and the body its `present` returns; the payloads of `ctx.emit`, `ctx.send`, `ctx.event`, `ctx.wake` and `ctx.spawn`; `ctx.setState`'s patch; `ctx.answer`'s value; a module call's arguments) is a `JsonResult`: the same, except an object's value may be `undefined`, and Arbor leaves that key out. A value Arbor hands you stays `Json`. Every example below is a whole app, checked against the SDK's types.

Your code runs in a sandbox with nothing ambient: no `fetch`, `setTimeout`, `console`, `require` or `process`. The `ctx` object you are handed is the whole platform API, and anything that reaches outside is a module you import from `arbor:*` (see "Modules imported by scripts"). `Date.now()` and `Math.random()` read a clock and a random source the node injects.

A few words recur. A **session** is one conversation with an app. A **root** is an actor the server starts when a session opens. A **node** is a running Arbor server. **Settings** are the operator's configuration for one environment, kept outside your code. An actor's **ledger** is the record of every step it has taken, and its **outbox** is what it has sent to the people in the session. A **fork** is a copy of a session from one of its steps, for trying a change.

The sections run from the inside out: the actor types, the contexts their code receives, tools, the bundle that holds it all, the modules scripts import, and the limits.

## Actor types

An **actor** is the basic unit: a function over its saved state and a batch of messages. The server wakes it when messages are due, calls it once with the batch, and commits what it did (the messages it consumed, what it sent, its new state) as one step. Every type below is an actor with something added. Two of them, `agent()` and `actor()`, are the ones you will use most. `relay()`, `ranger()`, `workspace` and the A2A task add a fixed behavior.

```mermaid
%% How the bundle, actors and agents relate
flowchart TB
  bundle["bundle()<br/>the app"] --> roots["roots<br/>booted at session start"]
  bundle --> session["session<br/>roles, partition, exposed"]
  roots --> actor["actor()<br/>function over state and a batch"]
  actor --> agent["agent()<br/>adds the model loop"]
  actor --> fixed["relay(), ranger(),<br/>workspace, A2A task<br/>fixed behavior"]
  agent -. ".subagents()" .-> child["child agents"]
```

### actor()

`actor(name, config?)` is plain code with no model in it. The name must be non-empty with no whitespace or `:`.

| Config | Type | Default | What it does |
|---|---|---|---|
| `state` | plain object | `{}` | The state a new actor starts with. Whatever `ctx.state` holds when `receive` returns is committed with the step, and the next batch starts from it on whichever node claims the actor. |
| `receive` | `(ctx, batch) => void or JsonResult` | none (required, here or with `.receive()`) | Called once per activation over the batch. What it returns is the actor's **projection**: whatever it wants to show of itself, stored with the step and readable without its state. Returning nothing keeps the previous projection. |
| `endsSession` | `boolean` | off | A root only. Lets the actor end its whole session from inside a turn with `ctx.endSession(outcome?)`. A non-root that sets it fails when the bundle is built. |

An actor takes no other config key: `instructions` and `tools` make an `agent()`.

The methods below each return a new definition. `Ext` in the types means the ctx accumulates what you attach, so `.receive()` is typed by everything chained before it. Give `receive` after the capabilities it uses.

| Method | What it does |
|---|---|
| `.receive(fn)` | Sets the receive function, replacing one given in the config. |
| `.wake(policy)` | Says when the server wakes the actor and with what batch. `policy` is `'chat'`, `'voice'`, a config object, or `{ policy, options }`. See the wake table below. |
| `.wiretap(source, opts?)` | Receive another definition's messages and outbox. `source` is a definition or its name. Options are in the wiretap table below. |
| `.subagents(...templates)` | The definitions this actor may spawn. Each is a definition or a template object (the template table in `agent()` below). Adds `ctx.subagents`. |
| `.labels(decl)` | Labels this actor declares. Mutable ones it may set with `ctx.setLabel`. The label spec is in "models, labels, vars and inputs" under The bundle. |
| `.clientEvents({ subtypes })` | Client events of these subtypes arrive in the batch as messages. At least one subtype. |
| `.artifacts(kinds, opts?)` | The named-artifact kinds this actor reads, and with `write` writes. Adds `ctx.artifacts`. Options are in the `agent()` section. |
| `.use(module)` | Attach a module that has no tools or hooks (tools and hooks are an agent's). The module's `extend` adds to the ctx. |
| `.participants(roles)` | The participant roles that talk to this root. Call once. |
| `.instance(mode)` | This root's route mode. Call once. |
| `.principal(p)` | Who this root acts for: `'app'` or `'opener'`. Call once. |
| `.describe(d)` | What this actor says of itself to the edges that meet it. Call once. |
| `.a2aTask(opts?)` | Makes this actor an Agent2Agent task (see `a2a()` below). Call once. Adds `ctx.task`. |

An actor has no `instructions`, `tools`, `skills`, `docs`, `context`, `prompts`, `run`, `reply` or `hooks`. Those belong to a loop, so they are an agent's.

`.wake(policy)` takes one of the presets, or a config object:

| Preset | Expands to |
|---|---|
| `'chat'` | `debounce: '300ms'`, `debounceInitial: '0ms'`, `debounceAfterTurns: 1`, `mergeMidTurn: true`, `maxSteps: 25`. A fast first reply, then a short linger so a burst of messages becomes one turn. A message that arrives mid-turn steers. |
| `'voice'` | The same with no linger (`debounce: '0ms'`, `debounceAfterTurns: 0`) and `onNewMessage: 'redirect'`. Every utterance is its own turn, and one spoken over the model's answer redirects it. |

| Wake option | Type | Default | What it does |
|---|---|---|---|
| `debounce` | `Duration` | — | How long the server lingers after a message before waking the actor, so a burst becomes one batch. |
| `debounceInitial` | `Duration` | — | The linger used instead of `debounce` while the actor has run at most `debounceAfterTurns` turns and the batch holds someone waiting for a reply (a user message or the boot). |
| `debounceAfterTurns` | `number` | — | How many turns the `debounceInitial` linger applies for. |
| `mergeMidTurn` | `boolean` | — | Lets newly due messages merge into a running turn at the next step boundary. |
| `maxSteps` | `number` | — | The most steps one turn takes. At the limit the agent makes one last call with its tools off, so the user always gets a reply. |
| `on` | `MessageKind[]` | none | Only these kinds wake the actor. The rest queue and arrive with the next waking one. A boot, a terminate and the actor's own timers always wake it. At least one kind. |
| `batch` | `{ count?, within }` | none | Fan-in: wake at `count` due messages, or when the oldest has waited `within`, whichever is first. `within` is required, because a count alone could hold messages that never fill it. |
| `onNewMessage` | `'steer'`, `'redirect'`, `'interrupt'` | `'steer'` | What a message that becomes due mid-turn does. `steer` merges it at the next step boundary. `redirect` cancels the model call in flight and makes it again with the message (a tool is never killed). It needs `mergeMidTurn`. `interrupt` cancels the turn and starts the next. While the agent has live children, `interrupt` is `steer`. |
| `maxRedirects` | `number` | 3 | How many redirects one turn may make before new messages steer. |
| `immediate` | `string[]` | none | `client_event` subtypes that wake the actor on their own, past `on` and `batch` (the debounce still applies). An answer to a held call needs no listing: it always wakes the agent at once. |

The server's default, when you declare no wake, is a 300 ms debounce after the first turn, merge mid-turn, and 25 steps. A `{ policy, options }` argument names a runtime wake policy; it is emitted but the runtime ignores it today.

`.wiretap(source, opts?)` subscribes to another definition's ledger. Pass `'*'` as the source to tap every agent of the session.

| Wiretap option | Type | Default | What it does |
|---|---|---|---|
| `descendants` | `boolean` | — | Also tap everything spawned under the source. |
| `inbound` | `MessageKind[]` | `user_msg`, `child_report` | Inbound kinds to tap when the source processes them. |
| `outbound` | `string[]` | `reply`, `child_report` | Outbound kinds to tap when the source emits them. |
| `events` | `string[]` | none | Ledger event kinds to tap (`park`, `cap_reached`, `turn_crashed`, or an extension's dotted kind). Taps arrive with `direction: 'event'`. A tap with `events` takes no defaults. |

`.instance(mode)` is one of `'singleton'` (one row, made with the session), `'participant'`, `'role'`, `` `label:${key}` `` (one row per key, made the first time it is addressed), or `'key'` (one row per key chosen when the instance is opened: an actor per ticket, order or task). Only a root has instances.

```ts
import { actor, bundle, isMessage } from '@arbor/sdk';

// Plain code, no model: counts the person's messages and answers each.
const counter = actor('counter', { state: { seen: 0 }, endsSession: true })
  .wake('chat')
  .receive((ctx, batch) => {
    for (const m of batch) {
      if (!isMessage(m, 'user_msg')) continue;
      ctx.state.seen += 1;
      if (m.body.text === 'bye') ctx.endSession({ summary: `${ctx.state.seen} messages` });
      else ctx.emit('reply', { text: `Message ${ctx.state.seen}` });
    }
    return { seen: ctx.state.seen }; // the projection: what the actor shows of itself
  });

export default bundle({ app: 'counter', roots: [counter], session: { exposed: [counter] } });
```

A second actor can listen to the first. A listener hears what another actor **emits**, never what it received. An actor reads a tap as the entry itself: the type the source emitted, with `via` set on the message.

```ts
import { actor, agent, bundle } from '@arbor/sdk';

const front = agent('front', { instructions: 'Help customers of a bookshop.' }).wake('chat');

// Hears what `front` says. An actor reads a tap as the entry itself: type `reply`, with `via` set.
const tally = actor('tally', { state: { replies: 0 } })
  .wiretap(front, { inbound: [], outbound: ['reply'] })
  .receive((ctx, batch) => {
    for (const m of batch) if (m.type === 'reply' && m.via?.made === 'definition') ctx.state.replies += 1;
    ctx.log('info', 'replies so far', { n: ctx.state.replies });
  });

export default bundle({ app: 'tally', roots: [front, tally], session: { exposed: [front] } });
```

An actor can also be instanced, bound to a person, and declare labels:

```ts
import { actor, bundle } from '@arbor/sdk';

// One seat per player, made the first time that player writes to it.
const seat = actor('seat', { state: { turns: 0 } })
  .participants(['player'])
  .instance('participant')
  .principal('opener')               // each seat acts for its own player
  .labels({ phase: { type: 'string', mutable: true } })
  .receive((ctx, batch) => {
    ctx.state.turns += batch.length;
    ctx.setLabel('phase', 'playing');
    ctx.emit('reply', { text: `Turn ${ctx.state.turns}` });
  });

export default bundle({
  app: 'seats', roots: [seat],
  session: { roles: { player: { max: 6, principal: true } }, exposed: [seat] },
});
```

### agent()

`agent(name, config?)` is an actor whose receive is the model loop. The loop builds the context window, calls the model, runs the tools it asks for, and repeats until the agent replies. Each model call and tool call is a recorded step. Use it when a model should decide what to do. The name must be non-empty with no whitespace or `:`.

| Config | Type | Default | What it does |
|---|---|---|---|
| `instructions` | `string`, `fromPrompt(id)` or `fromVar(NAME)` | none | The system instructions. Without them the agent never runs the loop and its hooks do all the work, which is an actor written the long way: use `actor()`. |
| `model` | `string` | none | A model **role** (`'fast'`, `'smart'`) declared in `bundle({ models })`. Settings map roles to real models. A bundle names roles, never endpoints or vendor model ids. A role is a lower-case letter then up to 31 of `a-z`, `0-9`, `_`, `-`. |
| `defaults` | `ModelDefaults` | none | The bundle's layer of the model configuration. Fields are in the table below. |
| `state` | plain object | `{}` | Durable state at spawn. |
| `endsSession` | `boolean` | off | A root only. Hooks get `ctx.endSession(outcome?)` and the model gets the `end_session` tool; either ends the whole session. |

| `defaults` field | Type | What it does |
|---|---|---|
| `temperature` | `number` | Sampling temperature. |
| `topP` | `number` | Nucleus sampling cutoff. |
| `maxTokens` | `number` | The output token limit. |
| `reasoning` | `'none'`, `'low'`, `'medium'`, `'high'`, `'xhigh'`, `'max'` | How much the model reasons, where the provider supports it. |
| `structured` | `'native'` or `'prompted'` | How a typed reply (`.reply()`) reaches the model: the provider's structured output, or the schema in the instructions. Unset: the API's default. |
| `options` | `Record<string, unknown>` | Provider-specific knobs, passed to the provider verbatim. |
| `model`, `api` | `string`, `'anthropic'`, `'chat'` or `'responses'` | Still read, but they name a vendor, so the linter warns (`models/endpoint-in-bundle`). Name a role with `agent(name, { model })` instead. |

Credentials and endpoints (`api_key`, `base_url`) are settings only. A bundle that carries them is rejected at publish. The model config is layered: the node's flags, then the settings' app-wide `model`, then the settings' entry for the agent's role, then these `defaults`, and finally the settings' per-agent tuning wins.

An agent has every method `actor()` has, with the same meaning: `.wake`, `.wiretap`, `.subagents`, `.labels`, `.clientEvents`, `.artifacts`, `.participants`, `.instance`, `.principal`, `.describe`, `.a2aTask`. It has no `.receive`, because its receive is the loop. These are the methods only an agent has.

| Method | What it does |
|---|---|
| `.tools(...selectors, opts?)` | Host tools the model may call, by selector (`'dns.*'`, `'billing.lookup'`, `'*'`). A selector is a name, `prefix.*`, or `*`. At least one. The last argument may be loading options (table below). |
| `.tool(def)` | One script tool the model may call, run in the sandbox. Chain it once per tool. Names must be distinct. See Tools. |
| `.subagents(...templates)` | Children this agent may spawn. The model gets `spawn`, `send`, `join`, `close` and `broadcast`. Hooks get `ctx.subagents`. Template options are in the template table below. |
| `.heard(kinds)` | Emit each inbound message of these kinds the agent consumes as a `heard` entry for no participant, so a listener bound to this agent hears what it heard. For a listener the bundle does not name. |
| `.context(opts?)` | The context window and how it folds when it overflows. Options are in the context table below. |
| `.run(opts?)` | Gives the model the `run` tool: it may answer with a short JavaScript program that calls the agent's tools. Off unless declared. Call once. Options are in the run table below. |
| `.reply(schema, opts?)` | A typed final reply. See below. Call once. |
| `.skills(entries, opts?)` | The skills this agent may load. See `skill()` below. Call once. |
| `.docs({ search, paths? })` | Search and read the reference files the bundle ships under `docs/`. Call once. |
| `.prompts(...specs)` | Prompts your code loads at run time with `loadPrompt`. Calling again adds to the list. See Prompts under The bundle. |
| `.use(module)` | Attach a module: config, tools, ctx additions and hooks. |
| `.hooks(hooks)` | Lifecycle hooks around the loop. Calling again merges by hook name. See Hooks under The contexts. |

`.subagents()` template options. Each argument is a definition, or an object with these fields:

| Field | Type | Default | What it does |
|---|---|---|---|
| `template` | definition or name | required | The child's definition. A name only works if the definition is reachable some other way. |
| `default` | `boolean` | off | The template the model's `spawn` and `ctx.subagents.spawnDefault` use when none is named. A single template is the default without saying so. |
| `when` | `string` | none | Guidance for the model on when to pick this template. It is rendered into the `spawn` tool's description. |
| `checkup` | `string` | none | Look in on children of this template this often while they run (a rolling check-up wake). |
| `peers` | `string` | none | Children of this template join this peer group. Siblings in one group may message each other. |
| `capMicros` | `number` | none | The child's spend allowance in micro-dollars (a million to the dollar). The store clamps it to the parent's headroom. |
| `closeOnReport` | `boolean` | `false` | The child closes itself right after its first report. For a one-shot template that should not linger. |

`.tools()` loading options. Past `threshold` resolved tools, the model is offered the platform tools, the `core` ones, the ones it loaded, and `tool_search`, `tool_load` and `tool_unload`:

| Option | Type | Default | What it does |
|---|---|---|---|
| `loading` | `'progressive'` or `'all'` | `'progressive'` | `'all'` offers every tool on every call. |
| `threshold` | `number` | 24 | How many resolved tools are offered whole before loading turns progressive. |
| `core` | `string[]` | none | Tools offered on every call whatever is loaded: names or selectors. |
| `maxLoaded` | `number` | 32 | The bound on the loaded set. The least recently used leaves first. |

`.context()` options:

| Option | Type | Default | What it does |
|---|---|---|---|
| `maxMemory` | `number` | 50 | Bound on the recall table. |
| `maintenance` | `string` | the agent's own policy | The model that summaries run on when the window overflows. Use a cheap one. |
| `compactAfter` | `number` | half the window | How many items beyond the window pile up before they are folded into a summary. |
| `compaction` | `boolean` | on | `false` drops what leaves the window instead of summarizing it. |
| `strategy` | `string` | `"default"` | Which context strategy folds the window: a name the node is composed with. |
| `maxInputTokens` | `number` | 0 | Token budget of one request. Past it (by the usage-anchored estimate) the window folds. 0 means item counts only. |
| `foldTo` | `number` | 0.6 | The share of `maxInputTokens` a token-triggered fold aims to leave. Between 0 (exclusive) and 1. |
| `childReportMaxChars` | `number` | 4000 | The largest child report admitted whole. A longer one becomes a placeholder plus a `report:` entry. Negative means no cap. |

Memory (the `remember`, `recall` and `forget` tools, and notes) is not a context option. It is the app's memory module, declared once in `bundle({ uses: { memory } })`. The old `remember`, `inherit` and `maxFactChars` options throw.

`.run()` options:

| Option | Type | Default | What it does |
|---|---|---|---|
| `maxCalls` | `number` | 50 | How many tool calls one program may make. At most 500. Past it the next call throws. |
| `timeout` | `Duration` | `'60s'` | The program's wall clock. At most `'10m'`. Past it the program is stopped and the call fails. |

The model writes the program as the body of an async function and calls the agent's tools as `await tools.name(args)`. Only what the program returns enters the window. Every call goes through the loop as a model call would (hooks, guardrails, approvals, the meter) and is a step of its own, so a crash resumes the program where it stood. The program reaches the tools only: no ctx, no sends, no spawns.

`.reply(schema, opts?)` declares the JSON Schema of what the agent finally says: an object schema in the node's subset, so the reply is a value your code can act on. Every model call of the turn asks for the schema, nothing streams, and a final reply that breaks it is asked again.

| Part | Type | Default | What it does |
|---|---|---|---|
| `schema` | JSON Schema, root `{ type: 'object' }` | required | What the reply must look like. The type argument, `.reply<T>(schema)`, types `result.value` in `afterTurn`. |
| `retries` | `number` | 2 | Further model calls a reply that breaks the schema may cost, 0 to 5. Past them the turn fails (`model.invalid_reply`). |

The reply is `{ text, value }`: `text` is the value's JSON, `value` the object. Hooks read `result.value` in `afterTurn` and answer with `ctx.answer(value)`; a parent's `report` hook reads the child's `value`. An actor has no model, so no `.reply()`.

`.docs({ search, paths? })`: with `search: true` the model gets `search` and `read` over the `docs/` files the bundle ships (`.md` and `.txt`, at any depth). `paths` narrows it (`'docs/rules/**'`, `'docs/faq.md'`, a directory such as `'docs/rules'`). The app must declare the artifacts module, with no kinds if it has none (`uses: { artifacts: {} }`).

`.artifacts(kinds, opts?)` lists the named-artifact kinds this definition reads, which the bundle declares in `uses.artifacts` (see `uses` under The bundle). The model gets `artifact_list`, `artifact_pin`, `artifact_unpin`, `read`, and `search` for searchable kinds. Hooks and actors get `ctx.artifacts`.

| Option | Type | Default | What it does |
|---|---|---|---|
| `write` | `string[]` | none | The listed kinds this definition may write. It adds `artifact_write`, `artifact_patch` and `artifact_delete` for the model, and `put`, `patch` and `delete` on `ctx.artifacts`. |
| `maxPins` | `number` | 2 | How many artifacts it keeps pinned in its context at once. |

Here is an agent with a role, generation settings, a child template, a context budget and a hook:

```ts
import { agent, bundle } from '@arbor/sdk';

const researcher = agent('researcher', { instructions: 'Answer one question in under 100 words.', model: 'fast' });

const front = agent('front', {
  instructions: 'You answer customers of a bookshop. Ask the researcher when you must look something up.',
  model: 'smart',
  defaults: { temperature: 0.2, maxTokens: 800 },
  state: { turns: 0 },
})
  .wake('chat')
  .subagents({ template: researcher, when: 'one independent question that needs looking up' })
  .context({ maxInputTokens: 6000 })
  .hooks({ afterTurn: (ctx) => ctx.setState((s) => ({ ...s, turns: Number(s['turns']) + 1 })) });

export default bundle({
  app: 'shop', roots: [front], session: { exposed: [front] },
  models: { fast: {}, smart: { default: 'fast' } },
});
```

`extend(def, overrides)` makes a new agent from an existing one: `name`, `instructions`, `model`, `defaults` and `state` may be overridden, and the modules and hooks are copied.

### relay()

`relay(name, config)` is an actor that re-emits each message it receives to the audience that message calls for. Use it for rooms where several people and agents talk and some messages are only for some readers: a staff-only note, a whisper to one person. It is an actor, so everything an actor has applies (`.wake`, `.labels`, `.subagents`, `.instance` and the rest). It is a root or a child alike.

| Config | Type | Default | What it does |
|---|---|---|---|
| `roles` | `string[]` | the bundle's principal role | The participant roles that take part. This is `.participants(roles)`. |
| `messages` | `Record<kind, { for? }>` | required, at least one kind | The kinds the relay takes, each with its audience. A kind is a lower-case name; the platform's own (`reply`, `user_msg`, `child_report` and so on) are refused. |
| `readers` | definitions | none | Agents or actors that hear every re-emitted entry. The bundle gives each a wiretap onto the relay. |
| `writers` | definitions | none | Agents or actors whose `ctx.send(relay, kind, body)` lands. The bundle gives each a peer edge to the relay. |
| `state` | plain object | `{}` | The state a new relay starts with. |

A kind's `for` is its audience. `{}` means everyone. `{ for: { role: 'staff' } }` is every participant holding the role. `{ for: { participant: 'to' } }` is the one participant whose id the message body's field `to` holds (a message without it reaches nobody). A list of those makes one entry per member, in order.

`.hooks(hooks)` is the relay's own method. Calling it again merges by hook name. For each message the hooks run in this order, and a hook that returns nothing leaves that message's default.

| Hook | Runs | Returns | Default |
|---|---|---|---|
| `boot(ctx, input)` | once, at the relay's boot, with the spawn's input (empty for a root) | nothing | nothing |
| `admit(ctx, m)` | per message, first | `true` takes it, `false` drops it silently | every declared kind; an undeclared one is dropped |
| `audience(ctx, m)` | next | `'everyone'`, `'nobody'`, a `{ role }`, a `{ participant }`, or a list of them | the kind's `for`, else everyone |
| `present(ctx, m)` | next | the message whose `body` is re-emitted (redact, enrich) | as it came |
| `onMessage(ctx, m)` | after the emit | nothing. Use it for state, sends, spawns, `ctx.refuse` and `ctx.accept` | nothing |
| `summary(ctx)` | when a child relay closes | what its parent receives | `{ messages, closed_at }` |

```mermaid
%% The order a relay's hooks run for each message
flowchart LR
  admit["admit<br/>keep or drop"] --> audience["audience<br/>who reads it"]
  audience --> present["present<br/>redact or enrich"]
  present --> emit["Re-emitted to the audience"]
  emit --> onMessage["onMessage<br/>state, sends, spawns"]
```

A relay message `m` has `id`, `pos` (its position in the session), `kind`, `body` (without the platform's fields), `from` (`{ participant, role }`, `{ actor, definition }` or `{ outside: true }`), `at`, and `message` (the actor message it arrived as).

A participant posts a message of a kind as a user message whose payload carries `kind`; with no `kind`, it is the relay's first declared kind. An actor sends the kind as the message type. What the relay re-emits is an outbox entry of that kind, whose body is `present`'s body plus `from`, `message_id` and `message_pos`.

```ts
import { agent, bundle, relay } from '@arbor/sdk';

const coach = agent('coach', { instructions: 'Read the lobby and suggest replies to staff.' });

const lobby = relay('lobby', {
  roles: ['customer', 'staff'],
  messages: {
    text: {},                                  // everyone
    note: { for: { role: 'staff' } },          // staff only
    whisper: { for: { participant: 'to' } },   // the participant whose id the body's `to` holds
  },
  readers: [coach],
}).hooks({ admit: (_ctx, m) => (m.body['text'] === '' ? false : undefined) });

export default bundle({
  app: 'lobby', roots: [lobby, coach],
  session: { roles: { customer: { max: 2, principal: true }, staff: { max: 3 } }, exposed: [lobby] },
});
```

### ranger()

`ranger(opts?)` is the supervisor of a session's forest of agents. It sleeps until an agent parks, crashes a turn, or hits a cap, then inspects it, writes a diagnosis, and in heal mode acts within its platform tools. It is an ordinary agent, so `ranger().hooks({...})` and the other methods still apply.

| Option | Type | Default | What it does |
|---|---|---|---|
| `name` | `string` | `'ranger'` | The definition's name. |
| `instructions` | `string` | none | Appended after a blank line to the built-in instructions: what this app's ranger should know (its failure modes, who to tell). |
| `model` | `string` | the app's model | A model role (`'smart'`), declared in `bundle({ models })`. Use a stronger model here: the ranger runs rarely and reasons over evidence. |

What the ranger may do is settings, not bundle: `app.ranger.mode` is `observe` (the default: it may read and record, with `ranger.inspect`, `ranger.diagnosis` and `ranger.note`) or `heal` (adds the acting tools). Its spend is capped by `app.ranger.cap_micros` in settings. Its notes are app-wide notes of the memory module, so the app must declare `uses: { memory: { scopes: ['app/all'] } }`, or the build refuses the bundle. Keep the ranger out of `session.exposed`: it is internal.

```ts
import { agent, bundle, ranger } from '@arbor/sdk';

const front = agent('front', { instructions: 'Help customers of a bookshop.', model: 'fast' }).wake('chat');

export default bundle({
  app: 'care',
  roots: [front, ranger({ model: 'smart', instructions: 'A parked "front" is usually the catalog tool timing out.' })],
  session: { exposed: [front] },          // the ranger stays internal
  models: { fast: {}, smart: { default: 'fast' } },
  uses: { memory: { scopes: ['app/all'] } }, // the ranger writes its notes at app/all
});
```

### workspace

`workspace` is a ready-made actor definition, not a function. It is a clone of a repository on the node, worked on by an actor that calls the coding module. List it among an agent's `.subagents()` and declare `uses: { coding: {} }`. The repositories, sandbox and approval rules are the environment's settings (`coding.*` keys), never the bundle's.

An agent that lists the workspace spawns one per repository (the model's `spawn` tool, with the alias as its task: `app`, `app@v1.2` or `local`), and gets one tool per operation, each with a `workspace` argument naming it. Code spawns it with `ctx.spawn(workspace, input, { name })`.

| Spawn input | Type | Default | What it does |
|---|---|---|---|
| `repo` | `string` | none | A repository alias the environment defines. |
| `local` | `boolean` | none | Use the dev node's own clone, in a work tree of its own. |
| `ref` | `string` | the alias's ref, else the remote's default branch | The ref to open at. |
| `branch` | `string` | `arbor/<session>/<name>` | The branch to work on. It is never the branch the workspace opens at. |

The operations, each a message kind and a tool `ws_<op>`:

| Operation | Arguments | What it does |
|---|---|---|
| `read` | `path`, `offset?`, `limit?` | Numbered lines (2000 lines or 50 KiB, with a notice for the next offset). Records the file's hash for the read-before-write rule. |
| `write` | `path`, `content` | Writes the whole file. A placeholder such as `// rest unchanged` is refused. |
| `edit` | `path`, `old_string`, `new_string`, `replace_all?`, or `path`, `edits` | Replaces text that must match once. Several edits in one file are applied in one call. |
| `patch` | `patch` | A multi-file patch. An agent on a GPT model gets this in place of `edit` and `write`. |
| `list` | `path?`, `depth?` | List a directory. |
| `outline` | `path?` | A file's or directory's definitions with their lines, to choose what to read. |
| `glob` | `pattern`, `path?`, `limit?` | Match file names. |
| `grep` | `pattern`, `path?`, `include?`, `mode?`, `limit?`, `offset?` | Search content (RE2). |
| `shell` | `command`, `cwd?`, `timeout?`, `background?` | Runs one command with `bash -c` inside the workspace's OS sandbox. Stateless, not interactive. |
| `process` | `action`, `id?`, `until?`, `pattern?`, `timeout?` | `list`, `output`, `kill`, or `wait` on a background process. |
| `browser` | per action | Browser actions, only where the environment turns them on. |
| `status` | none | The repository's state. |
| `diff` | `ref?`, `path?` | A diff. |
| `log` | `limit?` | Recent commits. |
| `commit` | `message`, `paths?` | Commit changes. |
| `checkout` | `ref` | Check out a ref. A dirty tree is committed as a checkpoint first. |
| `push` | none | Push the branch. A person approves the first push of a session. A push is refused as `conflict.git_config` when the clone's or the mirror's git configuration would steer where git goes (a `pushurl`, a `url.*.insteadOf`, a `core.sshCommand`, an `http.*` or `credential.*` key, or a remote URL that is no longer the mirror's own), before any credential is carried. |

A file may be written over or edited only when this workspace has shown its current content. An unread file answers `conflict.unread_overwrite`, and one that changed since answers `conflict.stale_read`. A workspace answers its agent's calls and never reports, so there is nothing to `join` on. It shows `arbor.coding.workspace` (`repo`, `local`, `branch`, `head`, `dirty`, `processes`) in its projection and emits each operation's fact (`coding.read`, `coding.edit`, `coding.commit`, `coding.exec` and so on). A plain actor sends the operation itself and the answer arrives as a `coding.result` message:

```ts
import { actor, bundle, isMessage, workspace } from '@arbor/sdk';

const committer = actor('committer', { state: { ws: '' } })
  .subagents(workspace)
  .receive((ctx, batch) => {
    for (const m of batch) {
      if (m.type === 'boot') ctx.state.ws = ctx.spawn(workspace, { repo: 'app' }, { name: 'repo' }).id;
      else if (isMessage(m, 'user_msg')) ctx.send(ctx.state.ws, 'commit', { message: m.body.text });
      else if (m.type === 'coding.result') ctx.emit('reply', { text: JSON.stringify(m.body) });
    }
  });

export default bundle({ app: 'committer', roots: [committer], session: { exposed: [committer] }, uses: { coding: {} } });
```

An agent gets the same through tools:

```ts
import { agent, bundle, workspace } from '@arbor/sdk';

const fixer = agent('fixer', { instructions: 'Fix the failing test in the repository `app`.' })
  .subagents(workspace)   // one workspace per repository, spawned by name
  .wake('chat');

export default bundle({
  app: 'fixer', roots: [fixer], session: { exposed: [fixer] },
  uses: { coding: {} },   // the coding module: repositories and policy are the environment's
});
```

### a2a(): the Agent2Agent pair

An app is an Agent2Agent (A2A) agent when it opts into the protocol's task lifecycle, openly, as two roots: a **context** (the conversation, one per caller) and a **task** (one instance per task). `a2a({ context, task, annotations? })` wires them. The context is any actor or agent. The task is any actor or agent that called `.a2aTask()`. An ingress of kind `a2a` refuses an app without the pair, and requires a bearer token: A2A has no way for an anonymous caller to carry a session, so an anonymous caller gets 401. Use an `http` ingress for a public surface.

| `a2a()` argument | Type | What it does |
|---|---|---|
| `context` | definition | The context root. It stays a singleton (an instanced context throws) and is not itself a task. It hears each task's start and transitions as `task_event` messages. |
| `task` | definition | The task root, which must have called `.a2aTask()`. It is made `instance('key')` with the context's roles. A task that declares other roles or another `.instance()` throws. |
| `annotations` | `Record<string, Json>` | The implementer's `a2a.*` annotations (`a2a.skills`, `a2a.provider`, `a2a.documentationUrl`, `a2a.iconUrl`), added to the context's exposed entry. |

It returns `{ context, task, roots, exposed, peers }`. Spread `roots` into `bundle({ roots })` and `exposed` into `session.exposed`. The peer edge from the task to the context is added by the bundle itself.

`.describe(d)` (on any definition, and the source of an A2A card) takes:

| Field | Type | Limit | What it does |
|---|---|---|---|
| `summary` | `string` | one line, at most 200 characters | What the definition is. |
| `description` | `string` | at most 8000 characters | A longer description. |
| `tags` | `string[]` | at most 32, each at most 64 characters | Tags. |
| `examples` | `string[]` | at most 32, each at most 2000 characters | Example requests. |

`.a2aTask(opts?)` takes these options:

| Option | Type | Default | What it does |
|---|---|---|---|
| `onReply` | `'complete'`, `'input'` or `'tool'` | `'complete'` | What an agent's final reply means. `complete` makes it the task's artifact and completes the task. `input` makes it a question (`input-required`). `tool` gives the model `complete_task` and `request_input`, and a reply with neither is asked again. An actor decides with `ctx.task` itself. |
| `replyArtifact` | `string` | none | Store a reply used as the task's artifact under this declared artifact kind. Without it, the reply is a text part that is not stored. |
| `onCancel` | `(ctx) => boolean or void` | cancel | A cancel arrived. Return `false` to refuse it (the edge answers `TaskNotCancelableError`). |

The task's state is one of `submitted`, `working`, `input-required`, `auth-required`, `completed`, `failed`, `rejected`, `canceled`. `ctx.task` is how code moves it:

| Call | Moves the task from | To |
|---|---|---|
| (the boot) | | `submitted` |
| (a held call waits on a connection) | `working` | `auth-required`, set by the platform |
| (a post arrives, or the connection is made) | `submitted`, `input-required`, `auth-required` | `working` |
| `ctx.task.needInput(message)` | `working` | `input-required` |
| `await ctx.task.complete(artifacts?)` | `working`, `input-required` | `completed`, then the actor ends |
| `ctx.task.fail(reason)` | any live state | `failed`, then the actor ends |
| `ctx.task.reject(reason)` | `submitted`, `working` | `rejected`, then the actor ends |
| `ctx.task.cancel()` | any live state | `canceled`, then the actor ends |
| `await ctx.task.artifact(artifact, opts?)` | `working` | unchanged: adds an artifact. `opts` are `append` and `lastChunk`. |

`ctx.task.state` and `ctx.task.record` read the task. Any other move throws an error with the code `a2a/illegal-transition`. An artifact is a string, `{ text, name? }`, `{ data, name? }`, or `{ kind, content, name? }` (an artifact of a kind the app declares, written through the artifacts module, so the task definition needs `.artifacts([...], { write })`).

```ts
import { a2a, actor, agent, bundle } from '@arbor/sdk';

const concierge = actor('concierge', { state: {} })      // the context: one per conversation
  .participants(['customer'])
  .describe({ summary: 'Trip concierge', tags: ['travel'] })
  .receive((ctx, batch) => {
    for (const m of batch) if (m.type === 'task_event') ctx.log('info', 'task moved', { body: m.body });
  });

const trip = agent('trip', { instructions: 'Book the trip the customer asks for.' })
  .a2aTask({ onReply: 'tool' });                          // the task: complete_task and request_input

const desk = a2a({ context: concierge, task: trip, annotations: { 'a2a.provider': { organization: 'Example' } } });

export default bundle({
  app: 'travel', roots: [...desk.roots],
  session: { roles: { customer: { max: 1, principal: true } }, exposed: [...desk.exposed] },
});
```

### skill()

`skill(name, config)` is a loadable pair: a context fragment (the skill's rules, a declared prompt) plus the tools that go with them. Progressive tool loading changes which tools the model sees. A skill changes which knowledge it sees, and brings its tools along. The skill's name is a lower-case letter then up to 31 of `a-z`, `0-9`, `_`, `-`.

| Config | Type | Default | What it does |
|---|---|---|---|
| `description` | `string` | required | What `skill_list` shows the model: what the skill is for, so it knows when to load it. |
| `prompt` | `fromPrompt(id)` | required | The skill's rules. It must be a declared prompt, and ships as `prompts/<id>.md`. |
| `tools` | `ToolDef[]` | none | The script tools the skill brings. They are offered only while it is loaded. A platform tool name throws. |

An agent lists the skills it may load with `.skills(entries, opts?)`. An entry is a skill, or `{ skill, loaded: true }` to load it at start.

| `.skills()` option | Type | Default | What it does |
|---|---|---|---|
| `maxLoaded` | `number` | 3 | How many skills may be loaded at once. Past it, `skill_load` is a tool error. |

The model gets `skill_list`, `skill_load` and `skill_unload`. A loaded skill's prompt becomes a labelled block `[skill: name]` in the dynamic tail of the window, and its tools join the agent's tools. Unloading removes both. A skill that no agent lists, and that you want declared anyway, goes in `bundle({ skills })`.

```ts
import { agent, bundle, fromPrompt, skill } from '@arbor/sdk';

const combat = skill('combat', {
  description: 'Resolving fights: initiative, attacks, harm',   // what skill_list shows the model
  prompt: fromPrompt('combat-rules'),                            // ships prompts/combat-rules.md
  tools: [{                                                      // offered only while the skill is loaded
    name: 'strike',
    description: 'Roll an attack against a target.',
    params: { type: 'object', properties: { target: { type: 'string' } }, required: ['target'] },
    handler: (args) => ({ target: String(args['target']), hit: true }),
  }],
});

const narrator = agent('narrator', { instructions: 'You run the table.' })
  .skills([{ skill: combat, loaded: true }], { maxLoaded: 2 });

export default bundle({ app: 'tale', roots: [narrator], session: { exposed: [narrator] } });
```

## The contexts

Your code gets a `ctx`. An actor's `receive` gets the **actor ctx**. An agent's hooks and tool handlers get the **hook ctx**. They overlap, but they are not the same object.

### The batch and its messages

An actor's `receive(ctx, batch)` is called with a batch of messages. Each one has these fields:

| Field | Type | What it is |
|---|---|---|
| `id` | `string` | The message's id. |
| `seq` | `number` | Its inbox sequence. 0 for a synthetic message. |
| `type` | `string` | What it is: `boot`, `terminate`, `user_msg`, `child_report`, a timer's type, or an app's own type. |
| `body` | `Json` | The payload. |
| `from` | `string` | The sending actor's address. An empty string when it came from outside. |
| `sender` | `Sender` | The principal it came from. `{ principal: 'actor', actor, definition? }`, `{ principal: 'participant', participant, role }`, or `{ principal: 'outside' }`. |
| `at` | `string` | When it was due (RFC 3339). |
| `via` | `Via` or absent | Set on a delivered entry: `made` (`'spawn'`, `'definition'` for a `.wiretap()`, or `'behavior'` for `ctx.subscribe`), `entry` (`'outbox'` or `'event'`), and optionally `pos`, `depth`, `sourceUrn`. Absent for a message someone sent. |

`isMessage(m, 'user_msg')` narrows a message by its type, so `m.body.text` is typed. The kinds with a declared body (`Payloads` in the SDK) are:

| Kind | Body |
|---|---|
| `boot` | The spawn args for a child, or `{}` for a root. |
| `user_msg` | `{ text, artifacts? }`. Who spoke is on the message's `speaker` (`{ participant, role }`), stamped by the server. |
| `child_report` | `{ text, value?, exit_reason? }`. A typed child's `value` rides beside the text. |
| `child_event` | `{ child, template, event, status, ... }`. A child's abnormal or terminal transition: `parked`, `crashed`, `stalled`, `max_steps`, `budget_exhausted` or `closed`. |
| `wiretap` | `{ source, source_urn, depth, direction, kind, pos, payload }`. How an agent's hook reads a tap. |
| `peer_msg` | `{ text }`. From a parent, a child, or a peer in the same group. |
| `wake` | `{ kind?, payload? }`. A self-addressed timer an agent set with `ctx.wake`. |
| `terminate`, `client_event` | A JSON object. |
| `note` | Any JSON. |
| `cap_reached` | `{ counter, scope, at, spent, action, ... }`. A cap's line was reached. |
| `undeliverable` | `{ reason, to, id, kind, payload }`. A message this actor sent came back because its addressee closed. |

An app can add its own kind by augmenting `Payloads` (`declare module '@arbor/sdk' { interface Payloads { ticket: { id: string } } }`). Two more helpers read a message: `isStepsCap(m)` is true for the session's steps-cap notice (save what the next session needs and end naming a successor before the grace runs out), and `isCancel(payload)` is true for the reserved `cancel` client event, which every root may receive without declaring it.

### The actor ctx

| Member | What it does |
|---|---|
| `ctx.state` | The actor's state, a plain object. Whatever it holds when `receive` returns is committed with the step. |
| `ctx.self` | This actor's address (its id). |
| `ctx.parent` | The parent's address. Undefined for a root. |
| `ctx.actor` | The actor itself: `id`, `urn`, `name`, `parentId`, `status`, and `inbox` (the inbox control as of this point in the step). |
| `ctx.principal` | Who this actor acts for: `{ kind: 'app' }` or `{ kind: 'participant', participant }`. Fixed at creation. |
| `ctx.session` | The session: `id`, `params`, `vars`, `inputs`, `labels`. |
| `ctx.participants` | The session's present participants: `id`, `role`, `name?`, `present`. A participant who left is not listed. |
| `ctx.ledger` | The actor's own ledger: `head()`, and `from(index)` or `back(index)` to read with `for await`. |
| `ctx.send(to, type, body?, opts?)` | A message to an address the actor holds: its own, its parent's, a child's, one granted to it, or a root a `peers` edge reaches (by definition or name). `opts` are `at` (an instant) or `in` (a delay). A send to an address it does not hold throws `conflict.not_addressable`. Returns the message's handle. An instanced root is reached as `'name[key]'` (one open instance) or `'name[*]'` (every open one, one message each, handle `''`). |
| `ctx.withdraw(handle)` | Takes back a message this actor sent itself that is still pending. `{ withdrawn: true }` when it left the inbox, `{ withdrawn: false }` when there was nothing to take back (received already, withdrawn already, another actor's), which is no error. |
| `ctx.instances(definition)` | The open instances of an instanced root this actor reaches by a peer edge, as `{ id, key }` in creation order. |
| `ctx.emit(type, body?, opts?)` | Emit to this actor's own outbox. Whoever listens (its parent, the clients) receives it. `opts.for` is `'everyone'`, a participant id (or `{ participant }`), or `{ role }`. |
| `ctx.call(name, fn, opts?)` | A recorded call. It runs `fn`, commits the result as a step, and returns it. When an unfinished turn is resumed, it returns the recorded result without running `fn` again. `fn` is handed `{ idempotencyKey, use }`, where `use(name)` is `ctx.use` bound to this call. `opts.meter` (`{ api_calls: 1 }`) counts against the caps before `fn` runs. Calls are matched by name in order, so give calls made together distinct names. |
| `ctx.spawn(definition, input?, opts?)` | Create a child from a definition in this bundle. Returns `{ id, name }`. Options are below. |
| `ctx.close(child)` | Close a child and its whole subtree: its address, the handle `spawn` returned, or its name. A child already closed is no error. |
| `ctx.subscribe(source, types?)` | Receive the outbox entries of `source`, of `types` (default all), from now on. `source` is an address this actor holds, or `{ actor, descendants }`. The `{ definition }`, `{ forest: true }` and `{ session: true }` sources need the session's ranger. |
| `ctx.setLabel(key, value)` | Set a session label. The key must be declared mutable by this actor's `.labels()`. |
| `ctx.endSession(outcome?)` | End the whole session with this step. Only a root declared with `endsSession: true`. The outcome is recorded (status `succeeded`, end reason `resolved` unless it says otherwise), every other live root and this actor's children are terminated. `{ successor: { params?, labels? } }` names the session that continues this one. |
| `ctx.refuse(roles?, opts?)` | Refuse the user messages of these roles while this actor stays open. A refused post comes back `conflict.inbox_refused` with `opts.message` (at most 500 characters) as its reason. No roles refuses every declared role. Returns the control as it now stands. |
| `ctx.accept(roles?)` | Take these roles' messages again, or everyone's with no roles. |
| `ctx.log(level, msg, attrs?)` | A log line: `level` is `'debug'`, `'info'`, `'warn'` or `'error'`. |
| `ctx.summary(text)` | The step's one-line summary for the console's ledger. At most 120 characters (cut), one per step, the last call winning. Plain text, and never a secret: whoever reads the ledger reads it. |
| `ctx.llm.text(prompt)` | One model call outside any loop. Record it with `ctx.call` when it must not repeat. |
| `ctx.use(module)` | A resource module the app declares in `bundle({ uses })`: `await ctx.use('counter').call('add', { by: 1 })`. A write is idempotent on the call's id. When two recorded calls overlap (a `Promise.all` of two `ctx.call`s), `ctx.use` cannot tell which one encloses the code and throws; use the call's own handle instead: `ctx.call('a', async (c) => c.use('x').call(…))`. |
| `ctx.memory` | The memory module's notes: `read`, `text`, `write`, `list`, `delete`. See `uses` under The bundle. |
| `ctx.needConnection(name)` | Ask for a declared connection ahead of any call. Resolves with its status when the holder has a live token. Otherwise a receive throws a `ConnectionNeeded` carrying the `url` the holder opens. |
| `ctx.connections.status(name)` | How a declared connection stands: `{ name, holder, connected, expired?, scopes?, expires_at? }`. Never a token. |

A capability you attach adds a member: `.artifacts()` gives `ctx.artifacts`, `.subagents()` gives `ctx.subagents`, `.a2aTask()` gives `ctx.task`.

`ctx.spawn` options:

| Option | Type | Default | What it does |
|---|---|---|---|
| `name` | `string` | `<definition>-<n>` | A short handle among this actor's children: lower-case letters, digits, `-`, `_`. |
| `summary` | `string` | none | One line saying what the child is for. |
| `addresses` | `Address[]` | none | Addresses this actor holds that the child holds too. |
| `for` | `string` | this actor's own principal | Who the child acts for: `'app'` or a present participant's id. A participant who is not present throws. |
| `wants` | `string[]` | the child's replies and its closing report | The types of the child's outbox this actor wants delivered. |
| `expose` | `boolean` | `false` (but a spawned relay is exposed unless this says `false`) | The child speaks to the clients itself: its replies and emits go to its own outbox and its tokens stream to them. |

A message to oneself, later, is a timer. `ctx.send(ctx.self, 'settled', {}, { in: '10s' })` returns a handle you keep in `ctx.state`, and a later step can `withdraw` it. A debounce is a timer withdrawn by each new message and set again:

```ts
import { actor, bundle, isMessage } from '@arbor/sdk';

// A debounce: answer once, ten quiet seconds after the last message.
const desk = actor('desk', { state: { texts: [] as string[], timer: '' } })
  .wake('chat')
  .receive(async (ctx, batch) => {
    for (const m of batch) {
      if (isMessage(m, 'user_msg')) {
        ctx.state.texts.push(m.body.text);
        if (ctx.state.timer) ctx.withdraw(ctx.state.timer);                   // the old timer is stale
        ctx.state.timer = ctx.send(ctx.self, 'settled', {}, { in: '10s' });   // a message to itself, later
      } else if (m.type === 'settled' && m.id === ctx.state.timer) {
        // recorded: a resumed turn reads the answer back instead of calling the model again
        const text = await ctx.call('summary', () => ctx.llm.text(`Summarize: ${ctx.state.texts.join(' / ')}`));
        ctx.emit('reply', { text });
        ctx.state.texts = []; ctx.state.timer = '';
      }
    }
  });
export default bundle({ app: 'desk', roots: [desk], session: { exposed: [desk] } });
```

A step that does everything at once may reach outside without recording. If the node crashes before the commit, `receive` runs again over the same batch (at-least-once). Record a call with `ctx.call` when its result is expensive, must not repeat, or must survive a crash.

### The hook ctx

Hooks and tool handlers of an agent get a different ctx. Everything on it either stages something the step commits (`emit`, `send`, `spawn`, `event`) or reads what the turn already has. What only stages an effect is synchronous. What does I/O on the node (`scratch`, `memory`, `llm`, `use`) is `async`.

| Member | What it does |
|---|---|
| `ctx.session`, `ctx.principal`, `ctx.participants` | As on the actor ctx. |
| `ctx.agent` | This agent's row: `id`, `urn`, `name`, `parentId`, `status`, `phase`, `state` (as of the start of the turn; `setState` replaces it), and `inbox`. |
| `ctx.messages` | The batch this turn is processing, typed by `m.kind`. `beforeTurn` may replace or filter it, and the loop sees the result. Hook messages use `m.kind` and `m.payload` (an actor's use `type` and `body`). |
| `ctx.answer(text or value)` | Answers the turn directly and skips the loop: `return ctx.answer('...')` from `beforeTurn` or `onModelFailure`. A typed agent answers with its value (an object), never text. |
| `ctx.emit(kind, payload, opts?)` | Hooks only. The agent speaking: an outbox event (exposed agent) or a `child_report` (child). `opts.for` addresses a participant or role. The platform's own kinds (`error`, `status`, `call_waiting`, `call_settled`, `approval_required`, `retract`, `fallback`, `tool_progress`) throw. Inside a tool handler it throws: a tool returns a result. |
| `ctx.send(to, kind, payload)` | Stage a message to an agent id, `'parent'`, or a root a peer edge reaches. From a hook it commits with the step. From a tool handler it commits with the checkpoint that journals the call. |
| `ctx.instances(definition)` | As on the actor ctx. |
| `ctx.spawn(template, args, opts?)` | Stage a child spawn from a template in this bundle. Options are `name`, `summary` and `for`. Returns `{ id, name }`. |
| `ctx.wake({ in, kind?, payload? })` | Stage a self-addressed timer. Returns its handle, as `ctx.send` does. |
| `ctx.withdraw(handle)` | Take back a pending `wake` or a send to this agent's own id. From a hook or a tool handler. |
| `ctx.terminate(childId?)` | Stage the termination of a child and everything under it (by id), or of this agent (no argument). |
| `ctx.setState(patch or fn)` | Replace durable state at commit. A patch is shallow-merged: a key it holds `undefined` is left as it is, and `null` is a value. A function maps the current state to the whole new one. |
| `ctx.transition(phase)` | Set the author-defined phase, shown in `ctx.agent.phase`. |
| `ctx.setLabel(key, value)` | Stage a label change. The key must be declared mutable by `.labels()`. |
| `ctx.cost(micros, opts?)` | What this cost, in micro-dollars. From a tool handler it attributes to the call. From a hook it is its own cost record on the step (`opts.name`, default `'hook'`). It rolls into the agent's and the session's spend. |
| `ctx.event(kind, payload)` | Record a state transition of your own extension, not a log line. `kind` is namespaced lower snake case with at least one dot (`shop.turn_done`), and `payload` is JSON of at most 64 KB. A bad one throws and nothing is staged. |
| `ctx.progress(text)` | Tool handlers only. What the call is doing, for whoever watches now. An ephemeral frame: never in the ledger. At most one frame per call per 250 ms, text cut at 200 characters. Throws from a hook. |
| `ctx.summary(text)` | As on the actor ctx. |
| `ctx.extract(facts)` | Record temporal fact triples (`subject`, `predicate`, `object`, `valid_from?`, `valid_to?`, `source?`) as a `memory_extracted` ledger event. At most 100 facts per call, each field at most 400 characters. Arbor extracts nothing on its own. |
| `ctx.outcome(result)` | State the session's result: `{ status, end_reason?, summary?, artifacts?, successor? }`. One per session. |
| `ctx.endSession(outcome?)` | As on the actor ctx. The model's way is the `end_session` tool, offered to such a root alone. |
| `ctx.refuse(roles?, opts?)`, `ctx.accept(roles?)` | As on the actor ctx. Hooks only: from a tool handler they throw. |
| `ctx.scratch` | Per-agent ephemeral space with a time to live: `get(key)`, `set(key, value, { ttl? })`, `del(key)`. Async. Not durable state. |
| `ctx.use(module)`, `ctx.memory` | As on the actor ctx. |
| `ctx.needConnection(name)`, `ctx.connections` | As on the actor ctx. In a tool handler a missing token holds the call until the person connects, then runs the handler again. In a hook it throws `ConnectionNeeded`. |
| `ctx.log(level, msg, attrs?)`, `ctx.llm.text(prompt)` | As on the actor ctx. |

The tool-handler-only members (`approved`, `idempotencyKey`, `needsApproval`, `pending`, `completionToken`) are under Tools, in Held calls. A capability you attach adds `ctx.subagents` (`.subagents()`, with `templates` and `spawnDefault(args, opts?)`), `ctx.artifacts` (`.artifacts()`) and `ctx.task` (`.a2aTask()`), and TypeScript knows: `ctx.subagents` exists only after `.subagents()`.

### Hooks

`.hooks({...})` decorates the loop and never shadows it silently. Calling it again merges by hook name. Hooks and handlers may be sync or async.

| Hook | When it runs | It receives | It may |
|---|---|---|---|
| `boot(ctx)` | The boot turn. No loop. A spawned child's boot that carries a task is also its first turn: `boot` runs, then the turn's hooks and the loop. | the hook ctx | Greet, seed state. |
| `beforeTurn(ctx)` | Before the loop. | the hook ctx | Rewrite `ctx.messages` (the loop sees the result), or `return ctx.answer(text)` to skip the loop. That is the only way to skip it. |
| `turn(ctx, next)` | Around the loop. Rare. | the hook ctx, and `next()` | Middleware. `next()` runs the default loop and returns a `TurnResult`, which the hook must return. |
| `afterTurn(ctx, result)` | After the loop, before commit. | the hook ctx, and a `TurnResult` | Edit `result.reply` (ignored when `result.streamed`), stage effects, set state. A typed agent's `result.value` may be replaced here and the text follows it. |
| `report(ctx)` | A `child_report` is in the batch, before `beforeTurn`; and one that arrives while the turn runs, at the next step boundary. | the hook ctx | Deterministic fan-out without asking the model. Mid-turn, what it stages is the step's, as a tool handler's is. |
| `terminate(ctx)` | The final turn. No loop. | the hook ctx | Extraction, outcome events. |
| `onModelFailure(ctx, failure)` | The gateway exhausted every candidate, or a typed reply ran out of retries. | the hook ctx, and a `ModelFailure` | `return ctx.answer(text)` to reply in the model's place and commit. Return nothing and the failure stands (the crash policy applies). |

The order within a turn is `report` (if a child report arrived), then `beforeTurn`, then `turn(next)`, then the loop, then `afterTurn`, and then the reply is emitted. Module hooks run before yours at each point. The first `beforeTurn` answer wins. `turn` hooks nest, with the first attached outermost. A hook that throws fails the step, and nothing it staged is committed.

```mermaid
%% The order of an agent's hooks within one turn
flowchart LR
  report["report<br/>if a child report arrived"] --> before["beforeTurn"]
  before --> turn["turn(next)<br/>wraps the loop"]
  turn --> loop["The loop<br/>model and tools"]
  loop --> after["afterTurn"]
  after --> reply["Reply emitted"]
  before -. "return ctx.answer(text)<br/>skips the loop" .-> after
```

`TurnResult` fields:

| Field | Type | What it is |
|---|---|---|
| `reply` | `string` or absent | The final text. Editable in `afterTurn` unless it already streamed. A typed agent's is the JSON of `value`, and follows it. |
| `value` | typed `T` or absent | A typed agent's reply (`.reply(schema)`). Absent for an agent whose reply is text. |
| `streamed` | `boolean` | True when the reply already streamed to the client as tokens. Edits are ignored. |
| `answered` | `boolean` | True when `beforeTurn` answered and the loop did not run. |

`ModelFailure` fields: `code` (the platform's error code, such as `unavailable`, or `limit.budget`, or `limit.rate`), `reason` (plain words), `retryable` (whether the same call may succeed later), `class?` (`transient`, `rate_limited`, `budget`, `auth`, `invalid` and so on), `provider_code?`.

```ts
import { agent, bundle } from '@arbor/sdk';

const front = agent('front', { instructions: 'Answer questions about orders, briefly.', state: { turns: 0 } })
  .wake('chat')
  .labels({ vip: { type: 'boolean', mutable: true } })
  .hooks({
    beforeTurn: (ctx) => {
      const last = ctx.messages[ctx.messages.length - 1];
      if (last?.kind === 'user_msg' && last.payload.text.trim() === 'ping') return ctx.answer('pong'); // skip the loop
      ctx.setState((s) => ({ ...s, turns: Number(s['turns']) + 1 }));
    },
    afterTurn: (ctx, result) => {
      ctx.event('shop.turn_done', { chars: result.reply?.length ?? 0 });   // a ledger event of your own
      ctx.log('info', 'turn done', { answered: result.answered });
    },
    onModelFailure: (ctx, failure) => ctx.answer(`I cannot answer now (${failure.code}). Please try again.`),
    terminate: (ctx) => ctx.log('info', 'closing', { turns: ctx.agent.state['turns'] ?? 0 }),
  });

export default bundle({ app: 'orders', roots: [front], session: { exposed: [front] } });
```

A crash is retried by the server's policy, set in settings and not in the bundle. By default the turn runs again up to 3 times (`lifetime.maxRetries`, at most 10), then the actor parks.

## Tools

A tool is something the model may call. An agent gets tools four ways: host tools by selector (`.tools()`), script tools you write (`.tool()`), tools a module brings (`.use()`), and tools a skill brings (`.skills()`). The runtime also gives every agent platform tools such as `spawn`, `send` and `remember`, depending on what you declared. Their names are reserved, so no script tool may use one: `spawn`, `send`, `join`, `close`, `broadcast`, `set_label`, `set_status`, `end_session`, `remember`, `recall`, `forget`, `tool_search`, `tool_load`, `tool_unload`, `skill_list`, `skill_load`, `skill_unload`, `search`, `read`, `doc_search` and `doc_read` (the old names of `search` and `read`), `artifact_list`, `artifact_write`, `artifact_patch`, `artifact_delete`, `artifact_pin`, `artifact_unpin`, `run`, and everything starting `ranger.`.

### The tool definition

`.tool(def)` takes a `ToolDef`. It is sugar for `.use({ name: def.name, tools: [def] })`, and the handler runs in the sandbox with the same ctx hooks get, including what earlier capabilities added.

| Field | Type | Default | What it does |
|---|---|---|---|
| `name` | `string` | required | 1 to 64 of letters, digits, `_` and `-`. A second tool of one name throws. |
| `description` | `string` | required | What the model reads. It must not be empty. |
| `params` | JSON Schema | required | The arguments. It must be an object schema, `{ type: 'object', ... }`. |
| `handler` | `(args, ctx) => JsonResult or Hold` | none | Runs the tool: the effects and the parsing. May be async. It may return a `Hold` instead of a result. A tool with no handler and no `runsOn` must have an `output` schema, which makes it a **mock tool**. |
| `output` | JSON Schema | none | The result's shape. Every result is validated against it, the handler's and every answer that stands in for it, and a result that breaks it is a tool error the model reads (`tool.invalid_output`, not retryable). Required of a mock tool. |
| `before` | `(args, ctx) => args` | none | Runs before the handler and returns the arguments it gets: defaults, normalization. It runs again whenever the call's result is settled, so it computes and keeps no state. |
| `after` | `(result, args, ctx) => JsonResult` | none | Runs after the handler, over the result once it fits `output`, and returns what the model reads. This is where the tool's state goes (`ctx.setState`, `ctx.event`). It never runs over an error. |
| `needsApproval` | `boolean` or `{ to }` | off | Every call waits for a person's yes before it runs. `to` says who answers. |
| `annotations` | `ToolAnnotations` | none | What a call does to the world. The table is below. |
| `retry` | `ToolRetry` | none (the tool runs once) | Try the call again when it fails with a retryable error. The table is below. |
| `runsOn`, `to`, `timeout` | | | A client tool. Use `clientTool()` below instead of setting these. |

The rule for what goes where: effects and parsing in the handler, state in `before` and `after`, because the handler is the unit something else may stand in for (a replay's record, a stub, a mock). A tool that sets state in its handler loses it whenever something answers in the handler's place.

A **mock tool** has `output` and no `handler`. The agent's model answers it in JSON mode, against `output`. Whether a node runs one is the environment's decision: a dev node generates the answer, and the default refuses a revision that has one.

`annotations` say what a call does, and what the server does with a call that was in flight when the node died:

| Annotation | Type | What it says |
|---|---|---|
| `readOnly` | `boolean` | The call changes nothing. It runs again after a crash, and runs live in a fork that has no record. |
| `idempotent` | `boolean` | A repeat under the same `ctx.idempotencyKey` does no more than the first call. It runs again after a crash. |
| `destructive` | `boolean` | The call does what cannot be undone. A fork never runs it. It cannot be set with `readOnly`. |
| `interrupted` | `'replay'`, `'unknown'`, `'ask'`, `'park'` | What the resume rule does with a call in flight at a crash. See below. |

With no `interrupted` setting, a `readOnly` or `idempotent` tool is `replay`, and any other tool is `unknown`. A tool with no annotations is treated as mutative.

| `interrupted` | What the turn after the crash does with the call |
|---|---|
| `replay` | Runs it again, under the same call id and `ctx.idempotencyKey`. |
| `unknown` | Does not run it. The model reads that the call was interrupted, may or may not have taken effect, and should be checked before it is repeated. |
| `ask` | Holds it as an approval. Approved runs it again under the same key, with `ctx.approved` set from the answer only when an operator or a service gave it; another answerer's yes carries nothing, and a handler written `if (!ctx.approved) return ctx.needsApproval(…)` asks again for its own audience. Denied or timed out reads `unknown`. |
| `park` | Parks the actor until an operator unparks it. The turn after reads `unknown`. |

The default needs nobody. Arbor hands every call a stable `ctx.idempotencyKey`: pass it to the service the tool changes, declare the tool `idempotent`, and a crash costs nothing. Choose `ask` or `park` only when a repeat is harmful and cannot be made safe.

`retry` takes these fields. The attempts happen inside the one recorded call, before the step commits, and the tool runs again only when the error says the same call may succeed later.

| Field | Type | Default | What it does |
|---|---|---|---|
| `attempts` | `number` | required | How many times the tool may run in all, the first included. 2 to 10. |
| `backoff.initial` | `Duration` | `'1s'` | The wait before the second attempt. |
| `backoff.factor` | `number` | 2 | How the wait grows. 1 to 10. Each wait is jittered: half of it, plus a random draw of the other half. |
| `backoff.max` | `Duration` | `'30s'` | The longest wait. At most 5 minutes. |
| `deadline` | `Duration` | `'2m'` | A limit over every attempt and wait together. At most 10 minutes. An attempt still running then is cancelled. |

A `ToolError` is how a handler says what went wrong. `new ToolError(reason, { code?, retryable? })`: `reason` is what the model reads, `code` is dot-separated lower snake case (default `tool.failed`), and `retryable` (default `false`) says the same call may succeed later. Any other thrown error is not retryable. A host module's retryable errors (an HTTP timeout or refused connection) are retried as thrown.

### Held calls

A tool call can be **held**: waiting on a person's approval, on the client, or on external work. A held call ends the turn. The client is told once with a `call_waiting` signal, and the answer wakes the agent at once. Every kind of hold times out with an error result the model can narrate around, after one hour by default.

| Member | Available in | What it does |
|---|---|---|
| `ctx.needsApproval(reason, { to? })` | tool handlers | `return ctx.needsApproval('refund over $100')` holds the call for a person's approval. On approve the handler runs again with the same arguments and `ctx.approved` set. On deny the result is an error with the note. Asking again once approved is an error. Nothing the handler staged before returning the hold lands. `to` is `'operators'`, `{ role }` or `{ participant }`. Unnamed, an app that declares participants asks the operators, and one that declares none asks anyone who may post. |
| `ctx.approved` | tool handlers | `{ by, note }` on the invocation that follows a yes, otherwise `null`. Always `null` in hooks. |
| `ctx.pending({ correlation, timeout? })` | tool handlers | `return ctx.pending({ correlation: jobId, timeout: '30m' })` holds the call for long-running work the handler started. The handler never runs again: the completion arrives as the call's result. What the handler staged before the hold (a send, a spawn, a label) lands with the step that holds it. `timeout` defaults to 1 hour. |
| `ctx.completionToken()` | tool handlers | This call's completion token, to hand to the job you start. Whoever holds it may answer the call. |
| `ctx.idempotencyKey` | tool handlers | This call's idempotency key (typed `string` in a handler, never null there): the same on every run of this call (an approval's re-invocation, a retry's attempts), another for another call. Hand it to what the handler changes outside. `null` in hooks. |

Only a handler holds. A `before` or `after` that returns a hold fails the call.

### clientTool()

`clientTool(def)` is a tool the client runs. The model sees an ordinary tool, and the platform never runs it: the call is held, the client gets the arguments, and its answer is the call's result. Attach it with `.tool(clientTool({...}))`. The client answers with `POST /v1/apps/{app}/sessions/{id}/agents/{agent}/calls/{call_id}`.

| Field | Type | Default | What it does |
|---|---|---|---|
| `name` | `string` | required | The tool's name. |
| `description` | `string` | required | What the model reads. |
| `params` | JSON Schema | required | The arguments, an object schema. |
| `to` | `'speaker'`, `{ role }`, `{ participant }` or `{ arg }` | `'speaker'` | Who answers. `'speaker'` is the person whose message woke the turn (anyone on the surface when no participant spoke). `{ arg: 'for' }` reads the participant (an id or display name) from the call's own argument of that name. A name that resolves to nobody, or to more than one, fails the call with an error the model reads. Name exactly one of `role`, `participant` or `arg`. |
| `timeout` | `Duration` | 1 hour | How long the client has before the call fails with a timeout the model reads. |
| `output` | JSON Schema | none | The answer's schema. The client's result is held to it (`tool.invalid_output` otherwise). |
| `interrupted` | `'replay'`, `'unknown'`, `'ask'`, `'park'` | `replay` | What a resume does with a call whose hold was lost with its step. `replay` holds it for the client again. |

```ts
import { agent, bundle, clientTool } from '@arbor/sdk';
const front = agent('front', { instructions: 'Book deliveries.' })
  .tool(clientTool({
    name: 'pick_delivery_slot',
    description: 'Ask the customer to pick a delivery slot.',
    params: { type: 'object', properties: { day: { type: 'string' } } },
    to: 'speaker',          // the person whose message woke the turn (the default)
    timeout: '10m',         // the call fails with a timeout the model reads
  }))
  .tool({
    name: 'start_export',
    description: 'Export the orders; the job answers when it is done.',
    params: { type: 'object' },
    handler: (_args, ctx) => {
      const token = ctx.completionToken();   // hand this to the job: its holder may answer the call
      return ctx.pending({ correlation: `export-${token.slice(0, 8)}`, timeout: '30m' });
    },
  });
export default bundle({ app: 'delivery', roots: [front], session: { exposed: [front] } });
```

### A script tool with retry

This tool is read-only, so a crash may run it again, and it retries when the service is busy. Its `output` schema holds every result to one shape:

```ts
import { agent, bundle, ToolError } from '@arbor/sdk';
import { endpoint } from 'arbor:http';
const orders = agent('orders', { instructions: 'Look orders up for customers.' }).tool({
  name: 'lookup_order',
  description: 'Look one order up by id.',
  params: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] },
  output: { type: 'object', properties: { status: { type: 'string' } }, required: ['status'] },
  annotations: { readOnly: true },                                   // a crash may run it again
  retry: { attempts: 3, backoff: { initial: '500ms', max: '4s' }, deadline: '20s' },
  handler: async (args) => {
    const res = await endpoint('orders').get(`/orders/${String(args['id'])}`);
    if (res.status === 503) throw new ToolError('the order service is busy', { retryable: true });
    return res.json as { status: string };
  },
});
export default bundle({
  app: 'orders', roots: [orders], session: { exposed: [orders] },
  http: { orders: { url: 'https://orders.example/api', methods: ['GET'] } },
});
```

### A tool that asks only when it must

Under $100 this refund just runs. Over it, the handler holds the call for a person's yes, and runs again with `ctx.approved` set:

```ts
import { agent, bundle } from '@arbor/sdk';

const orders = agent('orders', { instructions: 'Refund orders when asked.' })
  .tool({
    name: 'refund',
    description: 'Refund an order.',
    params: { type: 'object', properties: { amount: { type: 'number' } }, required: ['amount'] },
    handler: (args, ctx) => {
      if (Number(args['amount']) > 100 && !ctx.approved) return ctx.needsApproval('a refund over $100');
      return { refunded: true, by: ctx.approved?.by ?? null };
    },
  });

export default bundle({ app: 'refunds', roots: [orders], session: { exposed: [orders] } });
```

### Modules

`.use(module)` attaches anything with the `Module` shape. The built-in capabilities are modules built by the agent methods, and `schedule()` (a `schedule` tool that stages a wake) is the plain example.

| Field | Type | What it does |
|---|---|---|
| `name` | `string` | Required. Serialized as `modules[name]` in the manifest. |
| `config` | `Json` | Config the runtime reads. |
| `tools` | `ToolDef[]` | Tools the module adds. A reserved platform tool name is refused. |
| `extend` | `(ctx) => Ext` | Additive, typed hook context. Called once per activation. |
| `hooks` | `Hooks` | Composed with yours: module hooks run first, and `turn` wraps outermost. |
| `delivers` | `MessageKind[]` | Inbox kinds the module produces. Informational. |
| `refs` | definitions | Definitions the module wires to, which the bundle discovers. |
| `host` | a fixed set of names | Set only for the capabilities the runtime itself understands. Not for app code. |

A module may carry only the keys above and the hooks `boot`, `beforeTurn`, `afterTurn`, `turn`, `report`, `terminate` and `onModelFailure`. Anything else is refused when it is attached. A module attached to an actor may not bring tools or hooks.

## The bundle

`bundle(def)` declares the app. It throws on structural mistakes, so they surface at build time and not when a session is created. It returns a `Bundle` with `app`, `connections` (the declared connection names), `roots`, `exposed`, `agents`, `skills`, `agent(name)` (the definition of that name) and `manifest()` (the declarative half). Its `activate` method is for the server's loader, not for app code.

| Field | Type | Default | What it does |
|---|---|---|---|
| `app` | `string` | required | The app name. Sessions and definition URNs carry it. Non-empty, no whitespace or `:`. |
| `summary` | `string` | none | The app in one line of plain text, at most 160 characters and no line break. Without it the console's lists read the README's first sentence. |
| `roots` | definitions | required, at least one | Actors and agents booted at session start. Everything reachable from them is part of the bundle. |
| `session` | `SessionDecl` | one implicit role, `user` | How sessions are made: roles, partition, exposed roots. Below. |
| `labels` | `LabelDecl` | none | Labels the app accepts at session creation, beyond what definitions declare. |
| `vars` | `VarDecl` | none | Values settings supply. Read with `fromVar()` and `ctx.session.vars`. |
| `inputs` | `LabelDecl` | none | Inputs the caller supplies at session creation. |
| `models` | `Record<role, { description?, default? }>` | none | The model roles agents run on. Below. |
| `prompts` | `(string or PromptDecl)[]` | none | Prompts any agent loads at run time, beyond what agents declare. Every session pins all of them. |
| `skills` | `SkillDef[]` | none | Skills declared beyond the ones agents list. |
| `uses` | `BundleUses` | none | The resource modules the app uses: `memory`, `artifacts`, `connections`, `coding`, `console`. Below. |
| `peers` | `PeerDecl[]` | none | Edges between roots. Below. |
| `http` | `Record<name, HttpEndpointDecl>` | none | The outbound HTTP endpoints the app calls through `arbor:http`. Below. |
| `schedules` | `Record<name, ScheduleDecl>` | none | Posts the environment fires on a clock. Below. |

### session

| Field | Type | Default | What it does |
|---|---|---|---|
| `roles` | `Record<role, RoleDecl>` | one implicit role, `user` (max 1, principal, self) | The participant roles and their seats. |
| `partition` | input name, or `{ by, mode?, from? }` | none | The declared string input a session is filed under. Declaring it makes that input required. |
| `exposed` | root, name, or `{ root, events?, annotations? }` list | required, at least one | The roots the outside may reach, in order. A root not listed is internal: nothing that comes through an ingress posts to it or reads its outbox. The first one is where an open that names no root lands. |

A **role** is a name (a lower-case letter then up to 31 of `a-z`, `0-9`, `_`) with these fields. Settings say who holds each role (the role map); the bundle declares what the roles are.

| Role field | Type | Default | What it does |
|---|---|---|---|
| `max` | `number` | required | How many present participants may hold the role at once. A whole number, 1 or more. |
| `principal` | `boolean` | off | The role turns derive their identity from. Exactly one role is principal. |
| `join` | `'self'` or `'invite'` | `'self'` | `self`: a caller the role map admits joins by entering. `invite`: a holder of `session.grant` names the subject. |
| `may` | `string[]` | none | The actions the role is granted: a module's (`memory.read`, `artifacts.create:sheet`, `memory.*`) and the kernel's `ledger.read` and `session.upload`. An action no role is granted is open only to operators. |

A **partition** is a group of an app's sessions sharing a key: the campaign a tabletop evening belongs to, the customer account a support contact is about. Notes can be shared across one. A session is in one partition or none, set at creation and never changed. The key matches `^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$`.

| Partition field | Type | Default | What it does |
|---|---|---|---|
| `by` | `string` | required | The declared string input that holds the partition's key. |
| `mode` | `'many'`, `'one'`, `'once'` | `'many'` | `many`: any number running, every open a new session. `one`: at most one running; a second open is refused until it closes. `once`: one session ever; after it ends, an open is refused. |
| `from` | `string` | `'input'` | Where an open's value comes from. `input` can be supplied only by an operator or a service. `identity.subject`, `identity.attr:<name>` and `identity.partition` take it from the caller's identity. |

An exposed entry `{ root, events?, annotations? }`:

| Field | Type | What it does |
|---|---|---|
| `root` | definition or name | The exposed root. |
| `events` | `{ fallback?, retract?, tool_progress? }` | The platform signals its clients are shown: the model's fallback notices, its retractions, tools' progress. By default a retraction is shown, a fallback is not, and tools' progress only on a root whose gate admits operators' audiences alone. |
| `annotations` | `Record<'<consumer>.<key>', Json>` | An opaque dictionary for an edge that needs tuning the core should not understand. At most 16 KiB together. The kernel stores it and never reads it. `.describe()` is the primary path. |

### models, labels, vars and inputs

`models` maps a role name to `{ description?, default? }`. `default` names another declared role to fall back to when settings do not map this one. An unmapped role falls back to its default role, then to the app's model, then to the node's, so the bundle runs on a node that maps none. Settings map each role to a concrete model.

`labels`, `vars` and `inputs` share one spec vocabulary. The shorthand `'string'` is `{ type: 'string' }`.

| Spec field | Type | What it does |
|---|---|---|
| `type` | `'string'`, `'boolean'`, `'integer'` | Required. |
| `enum` | `string[]` | The allowed values. String specs only. |
| `pattern` | `string` | A RE2 pattern. String specs only. |
| `max_length` | `number` | Bytes on the wire. Greater than 0. |
| `mutable` | `boolean` | May change after creation (through `set_label` or `ctx.setLabel`). |
| `required` | `boolean` | Must be present at creation. |
| `default` | `string`, `number` or `boolean` | Vars only. The value when settings set none. A var with a default is optional, and one with no default is required, whatever `required` says. `required: true` beside a default throws. |
| `description` | `string` | What the declaration is for, shown to the operator. |

### uses

`uses` declares the resource modules the app uses, each with its declaration (`null` or `{}` when it takes none). A node without one of them refuses the publish. Code reaches a module with `ctx.use('<module>')`, and an agent also gets the module's tools. You grant a role its actions with `may`.

**`memory`** is the notes module. `{}` is working memory alone: every agent gets `remember`, `recall` and `forget` over its own notes. A note has two axes: **across** which sessions (`'session'`, the default; `'partition'`; `'app'`) and **among** which actors of them (`'actor'`, `'definition'`, `'subtree'`, `'all'`, the default, or a group you name). Those defaults are for a note you declare in `notes`. A key an agent remembers without declaring it is kept per session and per actor, unless `scopes` allows more.

| Field | Type | What it does |
|---|---|---|
| `groups` | `Record<name, definition[]>` | Named sets of definitions. A note declared `among: '<group>'` is seen by every agent built from a listed definition. |
| `notes` | `Record<key, { across?, among?, description? }>` | Declared keys. A declared note is pushed: its full text is in the window of every agent it reaches, and it is always written at its declared scope. `description` is one line, at most 200 characters. `actor` and `subtree` only with across `'session'`. |
| `scopes` | `string[]` | Scopes beyond `session/actor` an undeclared key may be remembered at (`['session/definition', 'app/all']`). |

`ctx.memory` has `read(key, opts?)`, `text(key, opts?)`, `write(key, text, { description?, scope?, id? })`, `list(opts?)` and `delete(key, opts?)`. A note key is 1 to 128 characters with no whitespace or `/`. Every write is idempotent on its call id.

**`artifacts`** is the named-artifact module: documents an agent pulls on demand (a character sheet, a handout). `{}` gives search and read over the shipped reference files alone.

| Kind field | Type | Default | What it does |
|---|---|---|---|
| `description` | `string` | none | What the kind is. |
| `schema` | JSON Schema | none | With a schema the kind is **structured**: one JSON value, validated on every write and changed with a JSON merge patch. The schema language is a subset (`type`, `properties`, `required`, `additionalProperties`, `items`, `enum`, `const`, `minimum`, `maximum`, `minLength`, `maxLength`, `pattern`, `minItems`, `maxItems`). |
| `mime` | `string` | `text/markdown` | Without a schema the kind holds text of this type, written whole. |
| `across` | `'session'`, `'partition'`, `'app'` | `'session'` | Which sessions see an instance. |
| `agents` | `'all'`, `'self'`, `'subtree'`, or definitions | `'all'` | Which agents of those sessions see it. |
| `search` | `'none'`, `'lexical'`, `'hybrid'` | none | Makes the kind searchable. `'hybrid'` runs lexical until embeddings land. |

A kind's name is a lower-case letter then up to 31 of `a-z`, `0-9`, `_`, `-`, and never `docs`. Every write is a new version, and `ifVersion` refuses a stale write. People get access through role grants: `artifacts.read`, `artifacts.write` and `artifacts.create`, each optionally `:<kind>`. `ctx.artifacts` has `get(kind, name, opts?)`, `list(opts?)`, `versions(kind, name)`, `put(kind, name, content, opts?)`, `patch(kind, name, patch, opts?)`, `delete(kind, name, opts?)` and `search(query, opts?)`.

**`connections`** are the per-person authorizations an app needs to reach a downstream service as someone, named by the app's own names. The tokens are the node's, kept in its secret plane and added at the egress. Code never sees one.

| Field | Type | Default | What it does |
|---|---|---|---|
| `provider` | `string` | required | The recipe it authorizes through: a shipped one (`atlassian`, `atlassian-mcp`, `github`, `google`, `microsoft`) or the environment's own by name. |
| `scopes` | `string[]` | the provider's defaults | What to ask the provider for. Declare the least the app needs. |
| `as` | `'participant'`, `'app'`, `'partition'`, or a list | `'participant'` | Who holds the authorization. A list is tried in order, and the first holder with a live token is used. |
| `role` | `string` | none | For a `partition` connection: the role whose members authorize it for their tenant. The app must be partitioned. |

`bundle()` infers the connection names as a literal union, `ConnectionName<typeof b>`. A name is a lower-case letter then up to 31 of `a-z`, `0-9`, `_`, `-`.

**`coding`** and **`console`** each take `{}` (or `null`). The coding module backs `workspace`, and its repositories and policy are the environment's `coding.*` keys. `outbound`, `schedules` and `quality` are never declared in `uses`: an ingress names an outbound target, `bundle({ schedules })` declares schedules, and quality is the operator's.

### peers

`peers` lets one root send to another. `{ from, to }` lets `from`'s row send to `to`'s. `{ between: [a, b] }` is both ways. Each end is a root of this bundle, singleton or instanced, as its definition or its name. An edge grants sending only, never spawning or closing across roots. The recipient wakes under its own wake policy and sees a message from the sender. The sender names the recipient as `name`, `'name[key]'` for one open instance, or `'name[*]'` for each.

### http

`http` declares the outbound HTTP endpoints, by name. It never holds a secret: settings give the credential and may set the URL.

| Field | Type | Default | What it does |
|---|---|---|---|
| `url` | `string` | settings give it | The base URL: `https://`, or `http://` to a literal loopback for development. |
| `description` | `string` | none | What the endpoint is for. |
| `auth` | `{ header, prefix? }`, `{ query }` or `{ connection }` | no credential | How the credential rides. `header` and `query` carry the value settings give. `{ connection }` names a declared connection whose token for the calling actor's holder is added as `Authorization: Bearer`. |
| `hosts` | `string[]` | none | Further hosts an absolute URL may name: exact, or `*.domain`. |
| `methods` | `HttpMethod[]` | all | The methods the endpoint allows (`GET`, `HEAD`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS`). |
| `idempotency` | `string` | none | The header an unsafe call (POST, PUT, PATCH, DELETE) carries a stable key in. |
| `timeout` | `Duration` | none | The endpoint's default timeout. |

### schedules

A schedule posts into the app on a clock. The bundle declares what each posts and where. The environment says when, so the code never carries a time: it arms each with `schedule.<name>.spec` (a cron expression or `every 15m`, in UTC), and a schedule with no spec does not fire.

| Field | Type | Default | What it does |
|---|---|---|---|
| `description` | `string` | none | What the schedule is for. |
| `text` | `string` | none | A user message with this text. Give this or `payload`. |
| `kind` | `'user_msg'` or `'client_event'` | `'user_msg'` | The kind of the post when you give a `payload`. |
| `payload` | object | none | The message's payload, instead of `text`. |
| `root` | definition or name | required | The root it posts to: a root of the bundle, exposed or not. |
| `partition` | `string` | the environment's setting | The partition it posts to, for a partitioned app. On an app with no partition every firing opens a new session. |

### A whole bundle

```ts
import { agent, bundle } from '@arbor/sdk';

const desk = agent('desk', { instructions: 'Help the customer.' }).wake('chat');
const digest = agent('digest', { instructions: 'Write the day\'s digest.' });

export default bundle({
  app: 'support',
  summary: 'Support desk for an online shop, with a nightly digest.',
  roots: [desk, digest],
  inputs: { customer: 'string' },
  session: {
    roles: { customer: { max: 1, principal: true }, staff: { max: 3, join: 'invite', may: ['memory.read'] } },
    partition: { by: 'customer', mode: 'one' },
    exposed: [desk],
  },
  peers: [{ from: digest, to: desk }],
  http: { billing: { url: 'https://billing.example/api', methods: ['GET'], timeout: '10s' } },
  schedules: { nightly: { text: 'write the digest', root: digest } },
  uses: { memory: { notes: { house_style: { across: 'app', description: 'how the shop talks' } } } },
});
```

### Prompts

A prompt is text kept apart from code, versioned, and **pinned into the session at creation**: a session never re-reads a prompt, so a running conversation never sees one change. The bundle declares the prompt and ships the default, and the configuration gives its value by key.

| Name | What it does |
|---|---|
| `fromPrompt(id)` | Instructions read from a pinned prompt. It ships `prompts/<id>.md` with the bundle, and that text is what every session pins unless the configuration's `prompt.<id>` gives another value (`store:<id>@stable`, `file:prompts/<name>.md`, or `{ text }`). It declares the prompt, and the build requires the file. An id is a lower-case letter then up to 63 of `a-z`, `0-9`, `_`, `-`. |
| `fromVar(NAME)` | Instructions read from a var in the session's pinned settings. `NAME` is letters, digits and underscore. Declare it in `bundle({ vars })`. |
| `.prompts(...specs)` | On an agent, or `bundle({ prompts })`: declare the prompts your code loads at run time. A spec is a bare id (a shipped file) or `{ id, source, ref? }`. |
| `loadPrompt(id, opts?)` | From `arbor:prompt`. A synchronous lookup, by declared id, of the pinned text. Call it in a hook or a tool: while the build evaluates the bundle there is no session. A prompt the session did not pin throws. |

The `prompts/` directory is built into the bundle: every `.md` file directly under it is shipped and declared as a file prompt, so `loadPrompt(id)` works for any shipped file.

```ts
import { agent, bundle, fromPrompt, fromVar } from '@arbor/sdk';
import { loadPrompt } from 'arbor:prompt';

const dm = agent('dm', { instructions: fromPrompt('dm_intro') })   // prompts/dm_intro.md, pinned per session
  .prompts('npc_voice')                                             // declared: code loads it at run time
  .hooks({
    beforeTurn: (ctx) => ctx.log('info', 'voice loaded', { chars: loadPrompt('npc_voice').length }),
  });
const clerk = agent('clerk', { instructions: fromVar('CLERK_PROMPT') }); // a var the settings supply

export default bundle({
  app: 'rpg', roots: [dm, clerk], session: { exposed: [dm] },
  vars: { CLERK_PROMPT: { type: 'string', default: 'You are a clerk.' } },
});
```

## Modules imported by scripts

Anything that reaches beyond the turn with authority (the network, secrets, a vendor API) is a host module the bundle imports from `arbor:*`. The import is the grant: the build records a bundle's imports, a session pins every one of them, and the sandbox resolves only what the session pinned. An environment may refuse a module with the settings' `capability.<module>`, in which case session creation fails at the start instead of mid-conversation.

| Module | Reaches outside | Exports |
|---|---|---|
| `arbor:crypto` | no (pure) | `sha256(data)`, `hmacSha256(key, data)`, `randomUUID()` |
| `arbor:prompt` | no (reads the session's pinned prompts) | `loadPrompt(id, { source?, ref? }?)` |
| `arbor:http` | yes | `endpoint(name)`, `request(req)`, `isHttpError(e)` |
| `arbor:node` | yes (the node's own API, in process; needs a policy) | `node`, `isNodeError(e)` |

Another module registered on the node exports what it says. Importing one the node does not have is a build error.

### arbor:http

The sandbox has no `fetch`. A bundle reaches an HTTP API through `arbor:http`, and only through the endpoints it declares in `bundle({ http })`. `endpoint('billing')` throws when the bundle declares no such endpoint.

| Call | What it does |
|---|---|
| `endpoint(name)` | Returns an object with `get`, `head`, `delete`, `options`, `post`, `put` and `patch`, each `(path, { query?, headers?, json?, body?, timeout?, maxBytes? })`. A path stays under the endpoint's URL. |
| `request({ endpoint, method, path or url, ... })` | The same call in full. An absolute `url` must be on the endpoint's origin or one of its declared `hosts`. |
| `isHttpError(e)` | True for an `HttpError`: a call refused or failed, with `code`, `reason` and `retryable`. |

The answer is plain JSON: `{ ok, status, headers, contentType, bytes, text?, json?, bodyRef?, exchange, replayed }`. A non-2xx status is an answer, not an error. A call may not set `Host`, `Content-Length`, `Connection`, `Transfer-Encoding`, `Cookie` or the credential's header.

**Each call is recorded.** In a receive or a hook it is a recorded call of its own, with no `ctx.call` around it. A turn resumed after a crash gets each recorded answer back, with `replayed: true` and nothing sent. In a tool handler the tool call is the record, and what a crash does is the tool's `annotations` (above).

```ts
import { agent, bundle } from '@arbor/sdk';
import { endpoint } from 'arbor:http';

const desk = agent('desk', { instructions: 'Check the order service when asked.' }).tool({
  name: 'order_service_status',
  description: 'Read the order service status page.',
  params: { type: 'object' },
  handler: async () => {
    const res = await endpoint('orders').get('/status', { query: { verbose: '1' } });
    return { ok: res.ok, status: res.status };   // a non-2xx status is an answer, not an error
  },
});

export default bundle({
  app: 'status', roots: [desk], session: { exposed: [desk] },
  http: { orders: { url: 'https://orders.example/api', methods: ['GET'], timeout: '10s' } },
});
```

Settings grant the module (`imports: ["arbor:http"]`) and give each endpoint its environment's values (`http.<name>.url`, `credential`, `headers`, `timeout`). A credential is a reference (`secret:<ref>` or `${VAR}`) or a literal that every read shows as `[redacted]`.

### arbor:node

`arbor:node` is Arbor's own API from actor code: a health monitor reading its stats and sessions, an assistant tuning its own settings and prompts. It calls the use cases in process, not the node's HTTP API. The import is not the grant: the environment states the policy (`capability["arbor:node"]`, with `scopes` and `apps`), and with none the module is refused. The calls are `node.stats`, `node.sessions` (`find`, `get`, `costs`, `ledger`, `terminate`), `node.settings` (`get`, `put`), `node.prompts`, `node.revisions`, `node.releases`, `node.labels`, `node.drafts`, `node.apps`, `node.nodes` and `node.sheet`. A failure is a `NodeError` (`isNodeError(e)`) with `code`, `reason`, `retryable` and `details`. Each call is recorded as an HTTP call is.

## Limits

These are the numbers the sources state. Settings change some of them; the table says which.

### Structure

| Limit | Value | Where it is checked or set |
|---|---|---|
| Tree depth | 8, with the root at 1 | At a spawn's commit (`conflict.tree_depth`). |
| Inbox length | 1000 | At the client door (`conflict.inbox_full`). |
| Children per actor | no limit | There is no per-actor children limit. |
| Spawns per turn | 8 | The model's `spawn` tool. A spawn with the same template and task as a running child answers the existing one. |
| Loaded skills | 3 | `.skills([…], { maxLoaded })`. |
| Tools offered whole | 24 | `.tools('*', { threshold })`. Past it, loading is progressive. |
| Tools loaded at once | 32 | `.tools('*', { maxLoaded })`. |
| Steps in one turn | 25 | The `'chat'` and `'voice'` presets' `maxSteps`. |
| Redirects in one turn | 3 | `.wake({ maxRedirects })`. |
| Pinned artifacts per agent | 2 (8 KB each) | `.artifacts(kinds, { maxPins })`. |
| Documents shipped under `docs/` | 2 MB in all | Checked at build and publish. |

### Run, reply and retry defaults

| Limit | Default | Bound |
|---|---|---|
| `run` calls per program | 50 | At most 500. |
| `run` wall clock | `'60s'` | At most `'10m'`. |
| Reply retries (`.reply()`) | 2 | 0 to 5. |
| Tool retry attempts | none (runs once) | 2 to 10 when declared. |
| Tool retry backoff | `initial` `'1s'`, `factor` 2, `max` `'30s'` | `factor` 1 to 10, `max` at most 5 minutes. |
| Tool retry deadline | `'2m'` | At most 10 minutes. |
| A held call's timeout (approval, client, external) | 1 hour | Set per tool with `timeout` or `ctx.pending({ timeout })`. |
| Child report admitted whole | 4000 characters | `.context({ childReportMaxChars })`. |
| Recall table | 50 | `.context({ maxMemory })`. |
| Fold target | 0.6 of `maxInputTokens` | `.context({ foldTo })`. |

### Lifetimes and retries (settings)

These are settings, not bundle options.

| Limit | Value |
|---|---|
| An actor's maximum lifetime | 6 hours (`lifetime.max`). |
| A root's idle time | unset. |
| A child's idle time | 15 minutes, unless settings give its template another. |
| Crash retries | 3 (`lifetime.maxRetries`), at most 10: the turn's failures since its last step that made progress. Then the actor parks. |
| The steps cap | none by default. When set (`app.steps: { cap, grace }`), the entry root hears `cap_reached` at the cap, and past the grace (default a tenth of the cap, at least 10 steps) every actor that commits is held. |

### Text and size bounds

| Item | Bound |
|---|---|
| `bundle({ summary })` | One line, at most 160 characters. |
| `.describe()` | `summary` at most 200 characters, `description` at most 8000, at most 32 tags (64 characters each) and 32 examples (2000 each). |
| Exposed-root annotations | 16 KiB together. |
| `ctx.summary(text)` | 120 characters (cut), one per step. |
| `ctx.event` payload | 64 KB. |
| `ctx.extract` | 100 facts per call, each field at most 400 characters. |
| `ctx.progress` | One frame per call per 250 ms, text cut at 200 characters. |
| `ctx.refuse` message | 500 characters. |
| A child's `summary` | 120 characters. A child's `name` is at most 32 characters. |
| Memory note key | 1 to 128 characters. Note `description` at most 200. |
| Artifact size | 256 KB per structured version, 2 MB per text version (settings change them per kind). |
| Artifacts per kind | 1000 live names per scope (settings change it per kind). |
| `arbor:http` bodies | 1 MiB out and 5 MiB in. |
| `arbor:http` timeout | The call's, else the endpoint's, else 10 s, at most 60 s. |
| `arbor:http` redirects | Followed on the same origin only, at most 3. |

### Names

| Name | Pattern |
|---|---|
| Definition (actor, agent, relay) | Non-empty, no whitespace or `:`. |
| Model role | A lower-case letter, then up to 31 of `a-z`, `0-9`, `_`, `-`. |
| Skill | The same as a model role. |
| Participant role | A lower-case letter, then up to 31 of `a-z`, `0-9`, `_`. |
| Tool | 1 to 64 of letters, digits, `_`, `-`. |
| Prompt id | A lower-case letter, then up to 63 of `a-z`, `0-9`, `_`, `-`. |
| Artifact kind | A lower-case letter, then up to 31 of `a-z`, `0-9`, `_`, `-`; never `docs`. |
| Connection | A lower-case letter, then up to 31 of `a-z`, `0-9`, `_`, `-`. |
| Relay kind | A lower-case letter, then up to 63 of `a-z`, `0-9`, `_`, `.`, `-`. |
| Child | Lower-case letters, digits, `-`, `_`, at most 32 characters. |

- [The building blocks](https://arbor.getloa.app/en/../blocks/): Each block as a small complete app, in the order you would learn them.
- [Examples](https://arbor.getloa.app/en/../examples/): Whole apps that use these options together.

Loa Arbor. © Richard Clayton. All rights reserved. Intended licence: FSL-1.1-MIT, at launch. Coming soon: the download opens when the repository goes public.
