Skip to content

Collaboration and automation

Communication API

Give independently hosted agents, services and people an address, a durable inbox and request and reply. No model or Roye inference is involved, and a processor only needs outbound HTTPS.

Local preview

Communication contract 1 runs on the local service only. It is not hosted or published and may change. A request without Roye-Contract-Version gets contract 1.

Quickstart

A trusted backend creates a workspace and two actors, then gives each processor its own connection secret once. The requester sends a request, and the responder can claim it from its inbox later, even if it was offline.

backend.ts
import { Roye } from '@roye-ai/client';

// Trusted backend, server-side only: the backend key never reaches a processor or a browser.
const roye = new Roye({ baseURL, token: () => process.env.ROYE_PROJECT_KEY!, projectId, environment: 'development', intents });

const ws = await roye.communication.workspaces.create({ displayName: 'support-agents' });
const triage = await ws.actors.create({ kind: 'agent', displayName: 'triage' });
const reviewer = await ws.actors.create({ kind: 'agent', displayName: 'reviewer' });

const forTriage = await triage.connections.issue({ scopes: ['send', 'receive'] });
const forReviewer = await reviewer.connections.issue({ scopes: ['receive', 'reply'] });
// Hand forTriage.secret with ws.id, triage.id and reviewer.id to the triage processor,
// and forReviewer.secret with ws.id and reviewer.id to the reviewer.

Each processor uses its own connection. The requester sends a work request and waits a bounded time for the reply.

triage.ts
import { RoyeActor } from '@roye-ai/client';

const triage = new RoyeActor({
  baseURL,
  connection: () => process.env.ROYE_ACTOR_CONNECTION!,
  workspaceId,
  actorId: process.env.ROYE_ACTOR_ID!,
  intents, // may be shared: each client resumes only the intents it recorded
});

const request = await triage.requests.create({
  recipientActorId: reviewerId,
  type: 'ticket.review.v1',
  contentType: 'application/json',
  content: { ticketId: 't-42' },
});
const latest = await request.wait({ waitMs: 30000 }); // still 'open' on expiry; nothing is cancelled

The responder claims deliveries under a lease, replies to requests and completes other messages.

reviewer.ts
const reviewer = new RoyeActor({ baseURL, connection: () => process.env.ROYE_ACTOR_CONNECTION!, workspaceId, actorId: process.env.ROYE_ACTOR_ID!, intents });

const batch = await reviewer.inbox.claim({ leaseMs: 60000, waitMs: 20000 }); // fresh claimKey per call
for (const item of batch.items) {
  if (alreadyHandled(item.delivery.id)) continue; // deduplicate your own effects by delivery ID
  if (item.message.kind === 'work_request')
    await item.reply({ type: 'ticket.verdict.v1', contentType: 'application/json', content: { verdict: 'ok' } });
  else await item.complete({ disposition: 'completed' });
}

Concepts

Every resource belongs to one project and environment. IDs are opaque, so do not parse their prefixes.

ResourceMeaning
WorkspaceThe actors, messages and records of one project and environment.
ActorAn addressable identity (agent, service or person) with its own inbox. Its name grants nothing.
ConnectionA short-lived actor credential for one processor, scoped to send, receive, reply or history.read.
MessageAn immutable envelope. The sender comes from the connection, not from the body.
DeliveryOne logical delivery to one recipient, with its delivery, claim and processing facts.
RequestA work_request that receives at most one reply. request is accepted as an input alias.
ThreadMessages that name the same threadId, listed in accept order.

Credentials

CredentialHeld byCan
Backend project keyYour trusted backend (roye.communication)Manage workspaces, actors and connections, read records and usage, cancel, hand off. It acts as an actor only to send as a service actor its rotation chain declared.
Actor connection secret (rac_…)One processor (RoyeActor)Send, request, read and claim its inbox, complete and reply within its scopes. It cannot issue or widen connections.
Developer sign-inThe consoleRead workspaces, actors, deliveries and usage. Never a backend key or actor secret.

A connection secret is returned only in the first issue response. Its lifetime is 1 hour by default and at most 24 hours.

Send from your backend as a service actor

A backend that notifies agents needs no connection. Create a service actor once with backendSender: true, using the backend key that will send. The actor records the first key of that key's rotation chain, so that key and every key you rotate to send as it; another key, a developer sign-in or an actor connection cannot. The declaration never changes; for another sender, create another actor.

Each send names the actor in senderActorId, on POST …/messages or POST …/requests. The message records senderKeyId, the exact key that sent it, with senderConnectionId: null. A backend send is project-scoped: recover it by its idempotency key with any backend key of the project, including a key rotated after the send.

CaseWhat happens
A sender that is not a service actor of the sending key's rotation chain, a developer sign-in, or a backend send without senderActorId403 forbidden; nothing is sent.
A suspended service actor409 actor_suspended. Resume the actor, then send again with the same idempotency key.
backendSender on an actor whose kind is not service400 invalid_request
backendSender declared with a developer sign-in403 forbidden. Declare it with the backend key that will send.
A backend key without the communication scope403 forbidden before the request is read.
Another rotation chain or a developer sign-in repeating a service actor's idempotency key and body403 forbidden, never the original send. Only keys of the declaring chain replay it.
notifier.ts
// Declare once, with the backend key that will send. Every key of its rotation chain sends as this actor.
const notifier = await ws.actors.create({ kind: 'service', displayName: 'notifier', backendSender: true });

// One key, one call, up to 64 recipients: one delivery per recipient, in recipient order.
const notice = await ws.messages.send({
  senderActorId: notifier.id,
  recipientActorIds: onCallActorIds,
  type: 'incident.notice.v1',
  contentType: 'text/plain',
  content: 'Incident 42 is open.',
  threadId: 'incident-42',
});
// notice.message.senderKeyId is the key that sent it; senderConnectionId is null.

// The service actor can also ask one actor and read the outcome through the request.
const ack = await ws.requests.create({
  senderActorId: notifier.id,
  recipientActorId: onCallActorIds[0],
  type: 'incident.ack.v1',
  contentType: 'text/plain',
  content: 'Acknowledge?',
});
const outcome = await ack.wait({ waitMs: 30000 });

One send to many recipients

recipientActorIds takes 1 to 64 distinct actors of the workspace. One send commits the message, one delivery per recipient, one usage unit per delivery and one message.accepted event together, or nothing at all. The response lists the deliveries in the order you named the recipients.

CaseWhat happens
Duplicate recipients or more than 64400 invalid_request; nothing is sent.
A retired recipient409 recipient_inactive with that actor in resource; nobody receives the message.
Lost responseRetry with the same idempotency key, or recover by that key. The original message and deliveries return, and nothing is delivered twice.
Each recipientIts own delivery with its own claim and processing facts, so one agent's processing never affects another's.
RequestsExactly one responder: send a notice to many and a request to one.

Delivery states

Accepted, delivered, claimed and processed are separate facts. Delivery is at least once until expiry.

StateMeaning
acceptedThe send committed this delivery to the recipient's durable inbox.
deliveredSent to the recipient's connection at least once. Redelivery is normal.
claimedOne connection holds a lease with a fence. Only that fence can complete, reply, extend or release.
processedThe claim holder recorded completed or rejected. Not proof of an external effect.
needs_handoffThe recipient retired. The backend can hand the delivery to another actor.
handed_off, expired, withdrawnFinal: handed off, expired or out of claim attempts, or closed with its request or workspace.

Request and reply

  • A request stays open until the current responder replies once, declines by completing the delivery as rejected, the requester or backend cancels it, or it expires.
  • A reply commits at most once. The same reply replays and a different one gets reply_conflict.
  • Completing a request delivery as completed is refused with reply_required; reply instead.
  • wait() long-polls for at most 30 seconds. On expiry it returns the same open request and cancels nothing. It still sees a reply committed before the wait.
  • Responses and events always name the kind work_request. As an input, request is an alias: POST …/messages with kind: "request" and exactly one recipient is the same operation as POST …/requests, with the same digest, so one key replays across both. One key names one send: the same key for the other kind, on either route, or with another body gets 409 idempotency_conflict.

Lists and filters

Management lists page oldest first with an opaque next cursor and at most 64 items, 25 by default. Filters match exact values. Before a state filter applies, due expiries and lease ends settle, and a row that settled out of the filter is left out, so every returned row matches its filters. A page may hold fewer items than limit while next is still set: keep following next until it is null. One call settles at most 256 due records first; when more are due, a later call settles the next ones, so repeat a filtered traversal after a large backlog.

RouteFiltersReturns
GET …/messageskind (message, request, work_request, reply), senderActorIdMessage summaries without content or references. Read one message for both.
GET …/requestsstate, requesterActorId, responderActorId (the current responder)Requests in their current state
GET …/deliveriesstate, recipientActorId, messageIdDelivery views with claim and processing facts
GET …/threadsNoneThreads, oldest first
GET …/threads/{threadId}/messagesNoneThat thread's message summaries in accept order
lists.ts
// Which on-call agents claimed the notice?
const claimed = await ws.deliveries.list({ messageId: notice.message.id, state: 'claimed', limit: 64 });

// Open requests waiting on one responder, oldest first; follow next until it is null.
let cursor: string | undefined;
do {
  const page = await ws.requests.list({ state: 'open', responderActorId: reviewerId, cursor });
  for (const request of page.items) remind(request);
  cursor = page.next ?? undefined;
} while (cursor);

// Summaries carry no content or references; read one message for both.
const sent = await ws.messages.list({ senderActorId: notifier.id, kind: 'message' });
const first = await ws.messages.get(sent.items[0].id);

Threads

A threadId is your own identifier, such as incident-42. The first message that names it creates a thread record with its first message ID and creation time. Later messages read the record but never write it, so concurrent sends never contend on a thread. A reply carries its request's threadId. Like a message's type, threadId is a label, not content: content retention erases neither the messages' threadId nor the thread record.

threads.ts
const threads = await ws.threads.list(); // oldest first, each with its firstMessageId
const history = await ws.threads.messages('incident-42', { limit: 25 }); // accept order, no content or references

Endpoints

Routes are under /v1/communication, and … is /workspaces/{ws}. Mutations take an idempotencyKey in the body, and POST on an actor ID updates it. A backend key on an actor route, or a connection on a management route, gets 403 forbidden.

OperationRouteCredential
WorkspacesPOST, GET /workspaces, GET /workspaces/{ws}, POST …/{suspend,resume,delete}Backend key
ActorsPOST, GET …/actors, GET, POST …/actors/{act}, POST …/actors/{act}/{suspend,resume,retire}Backend key. Connections can list and read the directory.
ConnectionsPOST, GET …/actors/{act}/connections, GET …/actors/{act}/connections/{acn}, POST …/connections/{acn}/revokeBackend key
MessagesPOST …/messages, GET …/messages, GET …/messages/{msg}Send: send connection, or a backend key as its declared service actor. List: backend key. Read: participant with history.read, or backend key
RequestsPOST …/requests, GET …/requests/{req}?waitMs=, POST …/requests/{req}/cancelCreate: send connection, or a backend key as its declared service actor. List (GET …/requests): backend key. Read: requester, current responder or backend key. Cancel: requester (send) or backend key
Deliveries and threadsGET …/deliveries, GET …/threads, GET …/threads/{threadId}/messagesBackend key
ReplyPOST …/requests/{req}/replyCurrent responder with reply and its fence
Inbox, claimGET …/inbox, POST …/inbox/claim, POST …/deliveries/{dlv}/claimreceive connection
DeliveryGET …/deliveries/{dlv}Recipient (receive), sender, or backend key
Claimed deliveryPOST …/deliveries/{dlv}/{lease,release,complete}Claim holder
HandoffPOST …/deliveries/{dlv}/handoff, GET …/actors/{act}/handoff-itemsBackend key
EventsGET …/events?cursor=Backend key, or a connection for its own feed
UsageGET …/usageBackend key

Limits

Preview values until measured costs set them, enforced with typed errors.

LimitValue
Content64 KiB, application/json or text/plain. Up to 16 references, which grant no access.
Recipients1 to 64 distinct actors per message. A request has exactly one responder.
Message expiry7 days by default, at most 30 days.
Lease5 seconds to 15 minutes, 60 seconds by default. At most 1 hour held in total and 10 claims per delivery.
Waits and pagesLong polls up to 30 seconds, up to 64 items per page.
RetentionHistory 30 days, events 7 days.

Not in this preview: hosted service, streams, export, Company links, caps, rate limits and any charge.

Errors

CodeHTTPWhat to do
invalid_request, payload_limit400, 413Fix the input. Do not retry it unchanged.
unauthorized, credential_expired, credential_revoked401Get a new connection from the trusted backend.
forbidden, not_found403, 404The credential lacks authority for this resource.
actor_suspended, workspace_not_active, needs_handoff409Resume, reactivate or hand off.
recipient_inactive, stale_reference409The recipient or handoff successor is retired or not eligible. Choose another.
idempotency_conflict409The key was used with other input. Recover the original.
revision_conflict, invalid_transition409Re-read and act on the current state. A lease extension that cannot move the end forward is invalid_transition.
stale_claim, reply_conflict, request_closed, reply_required409Re-read the delivery or request. Do not repeat effects.
quota_exceeded429A retire, workspace suspend or delete would change over 400 open records at once. Reduce them first.
cursor_expired, history_expired410Read state snapshots (claimable inbox, request and delivery states), then continue from a fresh cursor. The SDK raises ObservationGap.
unavailable503Retry with the same key and input.

Recovery

Save the idempotency key with its input before sending, or inject a durable intent store, and never retry an uncertain send with a new key. intents.resume() handles only its own backend's or actor's intents, so processes can share one store.

SituationWhat happens and what to do
Lost send or request responseThe same key replays the original. After a restart, intents.resume() recovers it by key without a second request.
Lost connection issue responseThe replay has secretStatus not_replayable and no secret. Revoke that connection and issue a new one with a new key.
Lost claim responseEach claim call has its own claimKey, so the replay returns the same deliveries and fences without another claim.
Processor crashed while claimingAfter the lease ends the delivery returns with a higher fence, and the old fence can no longer complete or reply.
Duplicate deliveries or eventsAt least once is normal. Deduplicate effects by delivery ID and events by event ID, and re-read state before acting.
recovery.ts
// After a restart: recover this actor's unresolved intents by their original keys.
for (const result of await triage.intents.resume())
  if (result.outcome?.resource?.type === 'request') resumeWaiting(result.outcome.resource.id);

// Event feeds are at least once: deduplicate by eventId and persist each event's cursor.
try {
  for await (const event of triage.events.observe({ cursor: savedCursor, maxDurationMs: 60000 })) save(event);
} catch (error) {
  if (error instanceof ObservationGap) await readSnapshots(error.snapshot); // then continue from a fresh cursor
  else throw error;
}

Usage

Each logical delivery, one per recipient, records one usage unit, however often it is sent or claimed. Units are measurement records, and nothing is charged in the preview.

Runnable example

apps/roye-api-examples runs a backend and two processors through an offline period, a crash and a lost response; run pnpm --filter @roye-ai/api-examples communication after the prerequisites in examples/README.md.