Loa/Arbor
English
  • English
  • 简体中文
  • 日本語
  • Español

The building blocks

21 blocks. Any system.

Each block below is a small, complete app, written to show that one block and nothing else. Read in order, each adds one idea to the ones before it.

Every block

01Actors

An actor is the basic unit in Arbor: a function over its saved state and a batch of messages. This one is plain code with no model in it. A person's message arrives as a user_msg, and isMessage picks those out of the batch. The actor counts them in its saved state and answers with ctx.emit. .wake('chat') runs it whenever a person writes. The last line is a bundle(): app names the app, roots lists the actors the app starts with in each session (one conversation with your app), and exposed lists the roots people can talk to. Every example ends with a bundle(...) like this one.

Fits withTimersAgents

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

// An actor is plain code: a function over its saved state and a batch of messages.
const front = actor('front', { state: { seen: 0 } })
  .wake('chat')
  .receive((ctx, batch) => {
    for (const m of batch) {
      if (!isMessage(m, 'user_msg')) continue;
      ctx.state.seen += 1;
      ctx.emit('reply', { text: `Message ${ctx.state.seen}: ${m.body.text}` });
    }
  });

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

02Timers

An actor sets a timer by sending itself a message with a later delivery time, { in: '10s' }, and it can take that message back with ctx.withdraw() while it is still pending. This desk waits for the customer to pause: each new message withdraws the last timer and sets a fresh one, and when ten seconds pass quietly it answers once for everything typed. No model is involved.

Fits withActors

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

const desk = actor('desk', { state: { count: 0, timer: '' } })
  .wake('chat')
  .receive((ctx, batch) => {
    for (const m of batch) {
      if (isMessage(m, 'user_msg')) {
        ctx.state.count += 1;
        if (ctx.state.timer) ctx.withdraw(ctx.state.timer); // take back the old timer
        ctx.state.timer = ctx.send(ctx.self, 'settled', {}, { in: '10s' }); // set a new one
      } else if (m.type === 'settled' && m.id === ctx.state.timer) {
        ctx.emit('reply', { text: `Got ${ctx.state.count} messages` });
        ctx.state.count = 0;
        ctx.state.timer = '';
      }
    }
  });

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

03Agents

An agent is an actor whose function is the model loop, made with agent(): it calls the model, runs the tools the model asks for, and repeats until it replies. One run of that loop, from a message to its reply, is a turn, and each model call or tool call inside it is a saved step. The agent names its model by a role such as fast, and the bundle declares the roles in models. Settings, a file beside the app code with environment details, say which real model each role uses, through any provider that speaks the OpenAI or Anthropic API. So one app can mix providers, and a new version of the app can change them.

Fits withActorsTools and approvals

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

const front = agent('front', {
  // A role, not a model: settings say which model the role runs on.
  model: 'fast',
  instructions: 'You answer customers of an online shop about their orders, briefly.',
}).wake('chat');

export default bundle({
  app: 'desk',
  roots: [front],
  session: { exposed: [front] },
  models: { fast: { description: 'cheap, quick replies' } },
});

04Tools and approvals

A tool is a function the model can call, declared with .tool(): a name and description the model reads, params, a JSON Schema that tells the model what arguments to send, and a handler, the code that runs. Mark it needsApproval and the call waits: the agent stops, nothing runs until a person approves or denies it, and the answer starts the agent again. If the person denies it, the model hears the refusal.

Fits withAgentsCalls that wait

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

const front = agent('front', {
  instructions: 'When a customer asks for a refund, call refund with the order.',
})
  .wake('chat')
  .tool({
    name: 'refund',
    description: 'Refund an order.',
    needsApproval: true, // the turn pauses until a person approves or denies
    params: { type: 'object', properties: { order: { type: 'string' } } },
    handler: (args) => ({ refunded: true, order: String(args['order']) }),
  });

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

05Calls that wait

A call can wait instead of finishing. While it waits the agent stops, and the answer starts it again. A handler returns ctx.needsApproval() to wait for a person to approve. After a person says yes, the handler runs again with ctx.approved set, so this refund goes through the second time. By default anyone in the conversation may approve; an app that declares roles sends approvals to its operators (the people who run Arbor, in its console), or to a role the call names. A clientTool() waits for the customer's screen to answer, such as a delivery slot picker, instead of running code.

Fits withTools and approvalsAgents

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

const front = agent('front', {
  instructions: 'Refund with refund. To deliver, ask for a day with pick_slot.',
})
  .wake('chat')
  .tool({
    name: 'refund',
    description: 'Refund an order. Over $100 waits for approval.',
    params: { type: 'object', properties: { amount: { type: 'number' } } },
    handler: (args, ctx) => {
      const amount = Number(args['amount']);
      // Not approved yet: wait here. After a yes, this handler runs again with ctx.approved set.
      if (amount > 100 && !ctx.approved) return ctx.needsApproval('over $100');
      return { refunded: true, amount };
    },
  })
  // Answered by the customer's screen, not by code.
  .tool(clientTool({
    name: 'pick_slot',
    description: 'Ask the customer to pick a delivery slot.',
    params: { type: 'object' },
  }));

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

06Typed replies

An agent can reply with one JSON object instead of prose. You declare its shape with .reply(), a JSON Schema like the params of a tool. Arbor asks the model for that shape and checks every final reply against it. A reply that does not match is asked for again, twice by default, and then the turn fails. A hook is a function Arbor calls at a point in the agent's work, here afterTurn when a turn ends, and it receives the checked value, so your code reads category directly with no parsing.

Fits withAgentsTools and approvals

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

const desk = agent('desk', { instructions: 'Classify the customer message.' })
  .wake('chat')
  // Arbor asks the model for this shape and checks every final reply against it.
  .reply({
    type: 'object',
    properties: {
      category: { enum: ['refund', 'shipping', 'other'] },
      urgent: { type: 'boolean' },
    },
    required: ['category', 'urgent'],
  })
  .hooks({
    // A hook runs at a point in the agent's work: here, when a turn ends.
    afterTurn: (ctx, result) => {
      if (result.value) ctx.log('info', 'classified', { category: String(result.value['category']) });
    },
  });

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

07Programs the model writes

Instead of calling tools one at a time, an agent given .run() gets a run tool and can write a short JavaScript program that calls its tools, loops over pages, filters, and returns only what the answer needs. Every call the program makes is a saved step, so if the node (one running copy of Arbor) dies partway and the program runs again, a call that finished isn't run again; it hands back its saved result. By default a program may make 50 calls and run for 60 seconds, and maxCalls and timeout change that.

Fits withTools and approvalsAgents

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

const analyst = agent('analyst', {
  instructions: 'Answer questions about orders. For many orders, write one program.',
})
  .wake('chat')
  .tool({
    name: 'order_get',
    description: 'Read one order: its id and total in dollars.',
    params: { type: 'object', properties: { id: { type: 'string' } } },
    handler: (args) => ({ id: String(args['id']), total: 42 }),
  })
  .run(); // gives the model the run tool

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

08Memory and notes

With the memory module on, the model gets remember, recall and forget tools for facts it chooses to keep. Notes you declare under uses.memory are short keyed texts that live outside the conversation, each with a reach given by across. Here a tone note belongs to one session, so it is for this customer, while house_style is read by every session of the app.

Fits withAgentsTools and approvals

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

const front = agent('front', {
  instructions: 'You help shop customers. Use remember for facts worth keeping.',
}).wake('chat');

export default bundle({
  app: 'desk',
  roots: [front],
  session: { exposed: [front] },
  uses: {
    memory: {
      notes: {
        tone: { across: 'session', description: 'how to talk to this customer' },
        house_style: { across: 'app', description: 'how the shop writes to all' },
      },
    },
  },
});

09Partitions

A partition is a key that groups an app's sessions, such as a customer, a campaign or a tenant. inputs declares values given when a session is opened, here a required campaign, and session.partition names it as the key. Only an operator or a service can set that value. Here each evening is a session and the campaign is the partition. A note with across: 'partition' is shared by every session of the campaign, so what the game master writes on Monday is there on Tuesday.

Fits withMemory and notesAgents

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

const table = agent('table', {
  instructions: 'You run a campaign. Keep what is true of the world in the world note.',
}).wake('chat');

export default bundle({
  app: 'campaign',
  roots: [table],
  // Each evening is a session; the campaign input groups them.
  session: { partition: 'campaign', exposed: [table] },
  inputs: { campaign: 'string' },
  uses: { memory: { notes: { world: { across: 'partition' } } } },
});

10Skills

A skill is a prompt of rules plus the tools that go with them. None is loaded at the start: the model lists the skills with skill_list and loads one with skill_load when the story needs it, and its rules and tools stay until it calls skill_unload. At most 3 are loaded at once. The rules are a prompt file, here prompts/combat-rules.md, which fromPrompt('combat-rules') points to.

Fits withAgentsTools and approvalsMemory and notes

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

// The rules are prompts/combat-rules.md; the model loads them when a fight starts.
const combat = skill('combat', {
  description: 'Resolving fights',
  prompt: fromPrompt('combat-rules'),
  tools: [{
    name: 'roll_die',
    description: 'Roll one six-sided die.',
    params: { type: 'object' },
    handler: () => ({ roll: 1 + Math.floor(Math.random() * 6) }),
  }],
});

const table = agent('table', { instructions: 'You are the game master of a dungeon game.' })
  .wake('chat')
  .skills([combat]);

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

11Subagents

An agent can start child agents from a template, one per independent question. .subagents() gives the model spawn, join, send and close tools to manage them, and each child gets set_status to say what it is doing. The children work at the same time, and the parent and a child can message each other while both are still working.

Fits withAgentsTools and approvals

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

const researcher = agent('researcher', {
  instructions: 'You look into one question about an order and report what you found.',
});

const front = agent('front', {
  instructions: 'For each question, spawn a researcher, join them all, then answer.',
})
  .wake('chat')
  // The model gets spawn, join, send and close over this template.
  .subagents({ template: researcher, when: 'one question that needs looking into' });

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

12Routers and outside services

A plain actor can call an outside service over HTTP, then forward messages to whichever agent should answer. This router asks a CRM service which tier a customer is on, keeps the answer in its state, and sends every later message to the matching agent. peers says which roots may send to which: a root can only ctx.send to one it has an edge to. Arbor records the service's answer, so if the node dies and the turn runs again, the saved answer is used and the service is not called a second time. The service is declared in http, and settings grant the arbor:http import.

Fits withActorsAgents

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

const vip = agent('vip', { instructions: 'Answer in detail.' }).wake('chat');
const std = agent('std', { instructions: 'Answer in one sentence.' }).wake('chat');

const router = actor('router', { state: { tier: '' } })
  .wake('chat')
  .receive(async (ctx, batch) => {
    for (const m of batch) {
      if (!isMessage(m, 'user_msg')) continue;
      if (!ctx.state.tier) {
        // Recorded: if the turn runs again, the saved answer is used.
        const res = await endpoint('crm').get('/tier', { query: { id: ctx.session.id } });
        ctx.state.tier = res.text ?? 'std';
      }
      ctx.send(ctx.state.tier === 'vip' ? vip : std, 'user_msg', m.body);
    }
  });

export default bundle({
  app: 'desk',
  roots: [router, vip, std],
  session: { exposed: [router] },
  peers: [{ from: router, to: vip }, { from: router, to: std }],
  http: { crm: { url: 'https://crm.example', methods: ['GET'] } },
});

13Watchers

A watcher is plain code: an actor that listens to another actor's wire with .wiretap(front) and receives a copy of what front sends. .wake({ on: ['wiretap'] }) runs it whenever it hears something, and it keeps a count in its state. Nothing outside the app talks to it, because only front is exposed.

Fits withAgentsActors

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

const front = agent('front', {
  instructions: 'You answer shop customers about their orders, briefly.',
}).wake('chat');

// Plain code that hears what front sends, and counts it.
const watcher = actor('watcher', { state: { sent: 0 } })
  .wiretap(front)
  .wake({ on: ['wiretap'] }) // wake when it hears something
  .receive((ctx, batch) => {
    ctx.state.sent += batch.length;
  });

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

14The supervisor

ranger() adds a root that sleeps until an agent parks (stops to wait for a person to decide), crashes a turn or reaches its spending cap. Then it inspects that agent and writes a diagnosis. In its default observe mode it only records what it found, and in heal mode, which settings turn on, it can act through a small set of tools. It heals by replacement and never resurrects: its instructions forbid unparking an agent. The ranger leaves notes every session can read, so the app opts in to app-wide memory with uses: { memory: { scopes: ['app/all'] } }.

Fits withWatchersAgentsMemory and notes

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

const front = agent('front', {
  instructions: 'You answer shop customers about their orders, briefly.',
}).wake('chat');

export default bundle({
  app: 'desk',
  // The ranger sleeps until an agent parks, crashes a turn or reaches its spending cap.
  roots: [front, ranger({ model: 'smart' })],
  session: { exposed: [front] },
  models: { smart: { description: 'careful reasoning over evidence' } },
  uses: { memory: { scopes: ['app/all'] } }, // so its notes can be read by every session
});

15People in roles

A session can hold several people, each in a role the app declares under session.roles. max is how many people may hold a role, and principal: true marks the role that opens a session. Here a customer opens it and up to two members of staff join by invitation. .participants() names the roles the agent hears, so the model reads who said each message. Settings decide who may hold each role.

Fits withAgentsCalls that wait

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

const front = agent('front', {
  instructions: 'You help a customer with an order. When staff speak, follow them.',
})
  .wake('chat')
  .participants(['customer', 'staff']); // the roles it hears

export default bundle({
  app: 'desk',
  roots: [front],
  session: {
    roles: { customer: { max: 1, principal: true }, staff: { max: 2, join: 'invite' } },
    exposed: [front],
  },
});

16Relays

A relay is an actor that decides who reads each message. It re-emits every message it receives to the audience that message's kind declares: text for everyone, note for staff only, whisper for the one participant named by the body's to. Agents can also listen to the room as readers and post into it as writers, and a parent can start a relay as a private breakout for a few people.

Fits withPeople in rolesActors

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

const lobby = relay('lobby', {
  roles: ['customer', 'staff'],
  messages: {
    text: {}, // everyone in the room reads it
    note: { for: { role: 'staff' } }, // only staff read it
    whisper: { for: { participant: 'to' } }, // only the one the body's `to` names
  },
});

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

17One per person

Besides a root everyone shares, a root can be instanced. .instance('participant') makes one copy per person, created the first time that person posts to it, and each copy has its own working memory. .principal('opener') makes each copy act for its player, so its replies go only to that player. In this tabletop game each player gets a private line to the game master.

Fits withPeople in rolesMemory and notes

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

const whisper = agent('whisper', {
  instructions: 'You are the game master, in a private line with one player.',
})
  .wake('chat')
  .participants(['player'])
  .instance('participant') // one copy per player, made when they first post
  .principal('opener'); // each copy acts for its player, so its replies go only to them

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

18Documents

Documents are named, versioned things an agent keeps outside the conversation, declared as kinds under uses.artifacts. They are called artifacts in code. A structured kind, like ticket, holds one JSON value that follows its schema, a JSON Schema, and a change is checked against it. A text kind with search set, like policy, can be searched. .artifacts() lists the kinds the agent can use, and write the kinds it may change. .docs() also lets the agent search the reference files the app ships under docs/, so a whole rule book never has to sit in the context.

Fits withMemory and notesSkills

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

const front = agent('front', {
  instructions: 'Keep one ticket per order. Search the policies and the shop rules before you answer.',
})
  .wake('chat')
  .artifacts(['ticket', 'policy'], { write: ['ticket'] })
  .docs({ search: true, paths: ['docs/rules/**'] }); // files the app ships

export default bundle({
  app: 'desk',
  roots: [front],
  session: { exposed: [front] },
  uses: {
    artifacts: {
      kinds: {
        ticket: {
          description: 'a support ticket',
          schema: {
            type: 'object',
            properties: { order: { type: 'string' }, status: { enum: ['open', 'closed'] } },
            required: ['order', 'status'],
          },
        },
        policy: { description: 'a shop policy', search: 'lexical' },
      },
    },
  },
});

19Connections

A connection lets each person use an outside account, such as their own Jira, through an agent that acts for them. The app names the connection in uses.connections, provider picks how it signs in, the environment says how that provider authorizes it, and scopes are the permissions asked for, the fewest the app needs. The connection's tools are named after it, so .tools('jira.*') selects every tool of the jira connection. A person's token is kept by Arbor and added when the call goes out. Your code never sees it, and it isn't written to the session's record. .principal('opener') makes the agent use the account of whoever opened the session, and until that person connects, the call waits with a link to do it.

Fits withOne per personCalls that waitPeople in roles

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

const helper = agent('helper', {
  instructions: 'List the open issues of the person you act for, using the jira tools.',
})
  .wake('chat')
  .principal('opener') // acts with the account of whoever opened the session
  .tools('jira.*'); // every tool of the jira connection

export default bundle({
  app: 'desk',
  roots: [helper],
  session: { exposed: [helper] },
  uses: {
    // Names the connection; settings say how the provider authorizes it.
    connections: {
      jira: { provider: 'atlassian-mcp', scopes: ['read:jira:agent-interface'] },
    },
  },
});

20Workspaces

A workspace is a clone of a code repository that an agent opens as a subagent with .subagents(workspace). The agent gets tools to search, read, edit, run commands and commit in it, and each tool call is a message to the workspace. Commands run in a sandbox the node sets up, and pushing the branch asks a person once per session. Which repositories a workspace may clone is set by the environment's settings, not by the app.

Fits withSubagentsCalls that wait

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

const fixer = agent('fixer', {
  instructions: 'Fix the failing test: open a workspace, edit, commit and push.',
})
  .wake('chat')
  .subagents(workspace); // each workspace is a clone of the repository

export default bundle({
  app: 'fixes',
  roots: [fixer],
  session: { exposed: [fixer] },
  uses: { coding: {} }, // which repository it may clone is set in settings
});

21Agent2Agent

Agent2Agent (A2A) is a protocol for one agent to call another: a card describing what an agent does, tasks that move through a few states, and results that come back. In Arbor you opt in with a2a(), which pairs two roots. Every task belongs to a conversation, so the conversation actor, described with .describe(), hears the events of its tasks. A task actor, marked .a2aTask(), handles one task. The task can ask a question with needInput, finish with complete and a stored result, reject a request, or honour a cancel. The protocol calls a task's results artifacts, a different thing from the documents block. This example calls no model.

Fits withActorsCalls that wait

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

// One conversation actor per conversation, one task actor per task.
const desk = actor('desk')
  .describe({ summary: 'Refund desk', description: 'Refunds orders.' })
  .receive((ctx, batch) => ctx.log('info', 'task events', { count: batch.length }));

const refund = actor('refund', { state: { asks: 0 } })
  .a2aTask()
  .receive(async (ctx, batch) => {
    for (const m of batch) {
      if (!isMessage(m, 'user_msg')) continue;
      if (ctx.state.asks === 0) {
        ctx.state.asks = 1;
        ctx.task.needInput('Which order?'); // the task now waits for the caller
      } else {
        await ctx.task.complete([`Refunded order ${m.body.text}.`]); // and ends
      }
    }
  });

const pair = a2a({ context: desk, task: refund });

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