Get started
Roye SDK
@roye-ai/client is a thin TypeScript client over Roye's public HTTP contracts. It executes nothing and holds no authority: Roye services validate, record and run every operation.
@roye-ai/client 1.0.0 and @roye-ai/contracts are unpublished private workspace packages. They and the key routes are verified on the local stack only. Hosted behavior is unverified.
Quickstart
Create a backend project key in the console and keep it on your server, never in browser code.
import { Roye } from '@roye-ai/client';
// Server-side only: a backend project key never belongs in browser code.
const roye = new Roye({
baseURL: 'http://127.0.0.1:4101',
token: () => process.env.ROYE_PROJECT_KEY!,
projectId: process.env.ROYE_PROJECT_ID!,
environment: 'development',
intents: durableIntentStore, // optional; see "Durable intents"
});Every keyed call needs an idempotencyKey stored with its input, or an injected intent store.
Modules
Handles call the same public routes as direct HTTP and add no capability. Each guide says where its API runs today.
| Handle | Runs in | Guide |
|---|---|---|
roye.roundtable.runs | Backend | Roundtable |
roye.agents | Backend | Agents |
roye.evaluations | Backend | Evaluations |
roye.communication, RoyeActor | Backend, each processor | Communication |
roye.knowledge, RoyeKnowledgeMember | Backend, each member process | Knowledge |
roye.work, RoyeWorkParticipant | Backend, each worker and reviewer process | Work |
roye.companies, with read-only operating sessions | Backend | Company Workspace |
roye.automation | Backend | Automation |
roye.actions, RoyeActionsInvoker, RoyeActionsApprover | Backend, an assistant's process, your approval UI | Actions |
roye.agreements | Backend | Agreements |
roye.billing | Backend | Funding and usage |
roye.projectLifecycle | Backend | Project exit and export |
roye.operations, roye.intents, roye.capabilities(), roye.preflight(), roye.contractPins() | Backend | This guide |
Project keys
A project key (ryk_...) lets your backend call Roye for one project and environment. Manage keys in the console, or with a current project member's developer sign-in token plus X-Roye-Project and X-Roye-Environment. A ryk_ key gets 403 forbidden on these routes.
| Operation | Route | Result |
|---|---|---|
| Create | POST /v1/keys | 201 with the secret once (secretStatus: 'returned'). scopes: null means every API. |
| Rotate | POST /v1/keys/{keyId}/rotate | 201 successor and previous. Copies name, scopes, environment and createdBy; sets rotatedBy. |
| Revoke | POST /v1/keys/{keyId}/revoke | 200, the same on repeat. Revoke each key of a chain by its ID. |
| List | GET /v1/keys?cursor=&limit= | 200 { items, next } by ID. |
| Get | GET /v1/keys/{keyId} | 200 key view, never a secret. Other projects' or environments' keys are 404 not_found. |
# Key routes take a project member's developer sign-in token, never a ryk_ key.
EXPIRES_AT=$(( ($(date +%s) + 30 * 86400) * 1000 )) # 30 days ahead, in milliseconds
curl -X POST "$ROYE_API_URL/v1/keys" \
-H "Authorization: Bearer $ROYE_DEVELOPER_TOKEN" \
-H "X-Roye-Project: $ROYE_PROJECT_ID" \
-H "X-Roye-Environment: production" \
-H "Content-Type: application/json" \
--data @- <<JSON
{ "idempotencyKey": "billing-worker-key-1", "name": "Billing worker", "scopes": ["billing"], "expiresAt": $EXPIRES_AT }
JSON
# 201 { "key": { "id": "KEY_ID", "prefix": "ryk_...", "state": "active", ... },
# "secret": "ryk_KEY_ID.SECRET", "secretStatus": "returned" }
# Put the secret in your secret manager now. A replay returns secretStatus "not_replayable" and no secret.# The old key keeps working for one hour, the successor until EXPIRES_AT.
curl -X POST "$ROYE_API_URL/v1/keys/$KEY_ID/rotate" \
-H "Authorization: Bearer $ROYE_DEVELOPER_TOKEN" \
-H "X-Roye-Project: $ROYE_PROJECT_ID" \
-H "X-Roye-Environment: production" \
-H "Content-Type: application/json" \
--data @- <<JSON
{ "idempotencyKey": "billing-worker-rotate-1", "overlapMs": 3600000, "expiresAt": $EXPIRES_AT }
JSON
# 201 { "key": { "rotatedFrom": "KEY_ID", ... }, "previous": { "state": "overlapping", ... },
# "secret": "ryk_NEW_KEY_ID.SECRET", "secretStatus": "returned" }# Ends the key at once. Repeating the request returns the same view.
curl -X POST "$ROYE_API_URL/v1/keys/$KEY_ID/revoke" \
-H "Authorization: Bearer $ROYE_DEVELOPER_TOKEN" \
-H "X-Roye-Project: $ROYE_PROJECT_ID" \
-H "X-Roye-Environment: production" \
-H "Content-Type: application/json" \
-d '{}'Scopes
| Scope | Routes it opens |
|---|---|
roundtable | /v1/roundtable/..., /v1/runs/... and /v1/runtime |
agents, evaluations, communication, knowledge, work, companies, automation, actions, agreements | /v1/{scope}/.... actions includes approvals and approver tokens. |
billing | /v1/billing/... and /v1/projects/{projectId}/{environment}/billing/preview |
| Any key | GET /v1/capabilities, /v1/operations/... and GET /v1/contracts/pins |
| The pinned module's scope | PUT /v1/contracts/pins/{module} |
- Scopes are fixed for a key's life and copied on rotation.
nullgrants all, and keys older than scopes read asnull. Outside its scopes a key gets403 forbidden. - Scopes gate HTTP entry only, with one exception. A key that starts an Automation run, creates or resumes a trigger, or resumes a run also grants the scope of every module the steps use (
communication,agentsoractions), and so does the project key a schedule or event trigger runs as. - An operating session started with a
companiesorautomationkey acts as the key's creator. It follows the creator's membership: it survives the key's revocation, expiry or rotation and ends when the creator leaves.
Secrets and lost responses
- The secret is only in the first response; Roye keeps its SHA-256 digest. A same-key replay is
201withRoye-Replayed: trueandsecretStatus: 'not_replayable', without the secret. - Lost create:
POST /v1/operations/recoverwith{ module: 'platform', kind: 'keys.create', idempotencyKey }, revoke the key inresult.resource, and create a new one under a newidempotencyKey. - Lost rotation: recover with
{ module: 'platform', kind: 'keys.rotate', target: { keyId }, idempotencyKey }, using the rotated key's ID and the originalidempotencyKey. Then rotate the successor inresult.resourcewithoverlapMs: 0under a newidempotencyKey.
Key holders, rotation overlap, refusal codes and legacy routes are in the key lifecycle reference.
Contract versions and pins
| Routes | Version served |
|---|---|
| Agents, Evaluations, Work, Companies, Automation, Agreements, Communication, Knowledge, Actions | Roye-Contract-Version, or the environment's pin without it. |
/v1/runs, /v1/runtime, /v1/capabilities, /v1/operations, /v1/contracts | Always 1. A requested version is ignored. |
| Billing, project lifecycle | Always 1. Others get contract_version_unsupported. |
/v1/roundtable/runs, Company manager routes | Always 2. Others get contract_version_unsupported. Company manager routes also require the header. |
- A module's first request pins the version it names, or the default. A project credential can also set the pin. A request that names a version always gets it.
- Previews (
pinnable: false) are never pinned: today Communication, Knowledge, Work, Companies, Automation, Actions, Agreements and Evaluations. Without a header they get the default, and pinning one iscontract_version_unsupported. - Responses state their version in
Roye-Contract-Version, except a header-selected route's refusal before it selects one, such as a failed sign-in.
| Request | Result |
|---|---|
GET /v1/contracts/pins | Per served header-selected module: module, pinnedVersion, pinnedAt, both null until pinned and always for previews. Reading never pins. |
PUT /v1/contracts/pins/{module} { idempotencyKey, version } | Moves the pin. The same key and version replay with Roye-Replayed: true, never for a revoked or expired credential. Recover with module platform, kind contracts.pins.set, target { module }. |
Pin errors: 409 idempotency_conflict (same key, other version), 410 operation_replay_expired, 400 contract_version_unsupported, 400 invalid_request (bad body or any query), 413 payload_limit (over 132,096 bytes), 404 not_found (unlisted module), 403 forbidden (actor, member, participant or invoker credential).
GET /v1/contracts/pins
Authorization: Bearer <project credential>
X-Roye-Project: <projectId>
X-Roye-Environment: production
// 200, Roye-Contract-Version: 1. Null means no pin yet; reading never pins.
{ "apiVersion": "1", "scope": { "projectId": "<projectId>", "environment": "production" },
"pins": [{ "module": "agents", "pinnedVersion": null, "pinnedAt": null }] }
PUT /v1/contracts/pins/agents
Content-Type: application/json
{ "idempotencyKey": "pin-agents-2", "version": 2 }
// 200, Roye-Contract-Version: 1. Requests to /v1/agents without a header now get contract 2.
{ "module": "agents", "pinnedVersion": 2, "pinnedAt": 1782451200000 }// The SDK only reads pins; it always sends its own version.
const pins = await roye.contractPins();Errors
Every refusal is a RoyeApiError with the shared envelope. Branch on category, a closed list. Codes may grow, and unknown ones are preserved.
| Category | Example codes | Next action |
|---|---|---|
invalid_input | invalid_request, payload_limit | Fix the input. |
unsupported | unsupported_capability, contract_version_unsupported | Pick a supported version or capability. |
invalid_binding | stale_reference, stale_binding | Re-read, then retry with fresh references. |
denied | unauthorized, forbidden, not_found | Obtain authority. |
revoked | credential_expired, credential_revoked, authority_revoked | Obtain authority. |
not_ready | not_ready, company_not_active | Re-read or repair. |
exhausted | budget_exhausted, quota_exceeded, concurrency_exhausted, rate_limited | Raise the limit or retry later. |
expired_history | cursor_expired, history_expired, operation_replay_expired | Restart from a snapshot or recover. |
pending_original | operation_pending | Observe the original. |
conflict | idempotency_conflict, revision_conflict, invalid_transition | Recover or re-read. |
transient | unavailable | Retry the same request. |
The client retries only transient failures and rate_limited, with the same key and input. A timeout cancels no server work and leaves the original recoverable. Management requests recheck credential expiry before acting.
// { "apiVersion": "1", "error": { "code": "idempotency_conflict", "category": "conflict",
// "message": "...", "retryable": false, "nextAction": "recover_operation", "operationId": "op_..." } }
import { RoyeApiError } from '@roye-ai/client';
try {
await roye.roundtable.runs.create({ definition, idempotencyKey });
} catch (error) {
if (!(error instanceof RoyeApiError)) throw error;
if (error.category === 'conflict')
return roye.operations.recover({ module: 'roundtable', kind: 'runs.create', idempotencyKey });
if (error.category === 'exhausted') return retrySameIntentLater(error.retryAfterMs);
throw error; // error.code, error.nextAction, error.operationId, error.retryable
}Idempotency and recovery
Store each keyed mutation's idempotencyKey with its input before sending. Roye records an operation only on commit, so a refusal before commit (validation, authority, budget) leaves the key free.
| Rule | Behavior |
|---|---|
| Key | Opaque. No credentials or personal data. |
| Scope | Project, environment, module, kind and target. |
| Same key, same input | Replays the original with Roye-Replayed: true. No second run or charge. |
| Same key, other input | 409 idempotency_conflict with the original operationId. |
| Lost response | Resend the same request, or recover by module, kind and key. |
Recovery is a POST, keeping keys out of URLs and logs. operations.get(operationId), operations.list({ module, kind, state, cursor, limit }) and the console read the same records.
// Store the key with the input before the first attempt; reuse both on every retry.
const run = await roye.roundtable.runs.create({ definition, idempotencyKey: saved.key });
run.replayed; // true when Roye replayed the original admission
// After a lost response: find the original operation without creating anything.
const operation = await roye.operations.recover({
module: 'roundtable',
kind: 'runs.create',
idempotencyKey: saved.key,
});
operation.state; // pending | succeeded | failed | cancelled
operation.result?.resource.id; // the original runObservation
events()pages a run's contiguous events until execution settles ormaxDurationMspasses.wait()returns when execution settles or its bound expires.untilcan end it sooner, never later.- Usage can stay pending after that. Re-read the same original within a separate bound, then keep any
pendingorunknownexplicit. Unknown is never zero. - Aborting stops only the observation, and closing the client cancels no run.
- Publish only committed outputs, and read
executionSettledandmeteringSettledseparately.
const handle = roye.roundtable.runs.get(savedRunId);
const controller = new AbortController(); // aborting stops observing, never the run
for await (const event of handle.events({ after: savedCursor, signal: controller.signal })) {
saveCursor(event.cursor);
if (event.payload.type === 'commit') publish(event.payload.outputs);
}
let view = await handle.wait({ waitMs: 30000 }); // ends when execution settles, not metering
const deadline = Date.now() + 30000;
while (!view.meteringSettled && Date.now() < deadline &&
!view.usage.some((row) => row.provenance === 'unknown') &&
(view.managed?.accounting === 'reserved' || view.usage.some((row) => row.costStatus === 'pending'))) {
await new Promise((resolve) => setTimeout(resolve, 500));
view = await handle.get(); // read the original run; never admit a replacement
}
console.log({ usage: view.usage, meteringSettled: view.meteringSettled });
// After the bound, pending stays pending; unknown stays unknown. Reconnect for later evidence.Capabilities and preflight
roye.capabilities() (GET /v1/capabilities) lists each module's kind, availability, contract versions with status and route, pinnedVersion and capabilities. kind is api for a general API and product for a Roye product built on the APIs, such as Company; it was added without changing anything else, and an absent kind means api. It is free and pins nothing. preflight() returns every unmet requirement, so your app can stop instead of substituting output.
const capabilities = await roye.capabilities();
const check = await roye.preflight({
modules: { roundtable: { version: 2, capabilities: ['runs.create', 'runs.events'] } },
});
if (!check.ok) throw new Error(check.unmet.map((item) => item.message).join('\n'));Limits
| Limit | Value |
|---|---|
idempotencyKey | 1 to 80 of A-Z, a-z, 0-9, _, -. |
| Replay window | 7 days. |
| Client retries | 5 attempts within 2 minutes by default, stalls and response bodies included. |
wait() | 30 seconds at most. |
events() | maxDurationMs of 15 minutes at most. |
Key name, scopes, expiresAt | 1 to 120 characters; null or 1 to 32 scopes; future, at most 90 days ahead. |
Rotation overlapMs | 0 to 604,800,000 ms (7 days). |
Key list limit | 1 to 100, default 25. |
The key routes are not rate-limited.
Concurrent requests
- Agents executions and Roundtable runs return an accepted handle, and Roye keeps delivering the original if your backend disconnects. One Agents session runs one turn at a time: observe it to the end before the next.
- On
429, back off with jitter usingretryable,nextActionandretryAfterMs, with the same key, input and scope. The SDK retriesrate_limitedbut notconcurrency_exhausted.
Scheduled hosted qualification is pending. Production throughput and tenant fairness are unqualified.
Usage
The SDK adds no meter or fee; each module records its own usage. Capability reads, same-key replays and key routes are free, and key routes record no usage.
Durable intents
- Without an intent store, pass an explicit
idempotencyKey. The client never invents one. - With an
IntentStoreon durable storage, the client persists each intent before sending. After a restart,intents.resume()recovers unresolved intents by key and resends one only if nothing committed and it is within the replay window. Older ones settle asunconfirmedand are returned. EphemeralIntentStoreis for tests only.- A key reused with other input or contract version fails with
idempotency_conflictbefore sending, keeping the original. Resending a stored request older than the replay window getsoperation_replay_expired: recover the original instead. - Retries keep the original age and a nondecreasing attempt counter, which is recovery metadata, not a send count or billing measure.
- Your store must enforce this binding atomically across concurrent writers. Read-then-overwrite is not enough.
import { Roye, type IntentStore } from '@roye-ai/client';
const intents: IntentStore = {
put: persistOriginalIntent, // app function: atomically insert/verify; preserve age and attempt counter
get: (ref) => db.intents.find(ref),
unresolved: () => db.intents.unresolved(), // AsyncIterable of unsettled intents
settle: (ref, outcome) => db.intents.settle(ref, outcome),
};
const roye = new Roye({ ...options, intents });
await roye.roundtable.runs.create({ definition }); // key generated and persisted first
// After a restart:
for (const result of await roye.intents.resume())
if (result.outcome?.state === 'unconfirmed') reviewManually(result.intent);Key lifecycle reference
Who holds a key
heldBy: 'project': created or rotated through/v1/keys. Ends on expiry, overlap end, revocation or project exit, not when its creator (createdBy) leaves.heldBy: 'creator': older and legacy-route keys. While the creator is not a member of both the project and the organization, it reads ascreator_removedand gets404 not_found, until the creator is added back.- Any member may rotate another member's key and gets a secret acting as that member, operating grants included. Only the organization owner rotates the owner's keys; others get
403 forbidden.
Rotation overlap
The old key's expiresAt becomes the earlier of its own expiry and now plus overlapMs. To retire it, let the overlap run out instead of revoking it. Rotate the successor next: rotating an overlapping, revoked, expired or creator_removed key is 409 invalid_transition and records no operation.
| When | Old key | Work it admitted or recorded |
|---|---|---|
| During the overlap | Works as overlapping. | Agents executions, Roundtable runs, Automation triggers and runs and Company setups keep running, owned by the project. |
| A creator-held key's creator leaves after the rotation | Refused. | Keeps running. |
| The overlap ends, or the old key's own expiry came first | credential_expired. | Follows the chain's newest key. |
| The recorded key is revoked (even after rotation), the newest key is revoked or expires, or the recorded key expired unrotated | Refused. | Withdrawn: queued Agents executions and Roundtable runs fail with execution_failed, running ones are cancelled, Automation shows grant_withdrawn. |
| The successor is revoked during the overlap | Works until the overlap ends. | Withdrawn when the overlap ends. |
Refusals and legacy routes
| Key | Clean routes | `/v1/runs`, `/v1/runtime`, legacy routes |
|---|---|---|
| Revoked | 401 credential_revoked | 401 unauthorized |
| Expired, overlap included | 401 credential_expired | 401 unauthorized |
| Unknown, or wrong secret | 401 unauthorized, no state revealed | 401 unauthorized |
| Exited project (digests removed) | 401 unauthorized | 401 unauthorized |
- The legacy key routes
POSTandGET /v1/projects/{projectId}/{environment}/keysandDELETE /v1/projects/{projectId}/{environment}/keys/{keyId}take the sign-in token and serve the same keys, so a key works on both paths. Their keys havenullnameandscopesandheldBy: 'creator'. New integrations use/v1/keys. - Key routes answer
Roye-Contract-Version: 1, and key operations appear inGET /v1/operations.lastUsedAtis accurate to five minutes andnulluntil first use.
Company composition paths
Three paths create the same kind of company (launch sequence). Afterwards operation.revisePolicy changes only the policy and keeps attached IDs, Communication usage and the budget.
| Path | How |
|---|---|
| Your template, as defined | Resolve the template your app keeps into the explicit create, with charter, bindings that create each module resource, budget and policy, then call companies.v2.create, or companies.v2.launch to staff and start it too. |
| Your template, edited | The same, after your app changes fields it owns, such as role instructions, owner acceptance or binding display names. |
| Direct composition | Create the workspace, space and board, then companies.v2.create with a charter, policy, budget and an attach binding for each. You keep them, and deleting the company releases them. |
const companies = roye.companies.v2;
// Paths 1 and 2: your own template, kept in your app. Resolve it there, with any overrides, into an explicit policy.
const policy = resolvePolicy(myTemplate, { limitCredits: 2000, instructions: { writer: 'Write short, plain notes.' } });
const company = await companies.create({
idempotencyKey: saved.key, // stored with the input before the first attempt
displayName,
charter: { purpose: brief },
bindings: [
{ module: 'communication', create: { displayName: 'Communication' } },
{ module: 'knowledge', create: { displayName: 'Knowledge' } },
{ module: 'work', create: { displayName: 'Work board' } },
],
budget: { limitCredits: 2000 },
policy, // its budget.reserveCredits must stay below the limit
});
// Path 3: compose the pieces yourself, then attach them. Deleting the company releases them.
const direct = await companies.create({
idempotencyKey: saved.directKey,
displayName,
charter: { purpose: brief },
bindings: [
{ module: 'communication', attach: { id: workspace.id } },
{ module: 'knowledge', attach: { id: space.id } },
{ module: 'work', attach: { id: board.id } },
],
budget: { limitCredits: 2000 },
policy,
});
// Setup completion bumps the company revision, so wait for ready and read the current one first.
await direct.ready({ waitMs: 20000 });
const { revision } = await direct.get();
// Attached IDs, workspace usage and the budget view are unchanged by a policy revision.
await direct.operation.revisePolicy({ expectedRevision: revision, policy: { ...policy, ownerAcceptance: true } });Migrating from contract 1 to contract 2
Roundtable contract 1 is deprecated. Contract 2 at /v1/roundtable/runs shares its operation namespace, so stored requestId values sent as idempotencyKey address the same runs. Switch to Roye from @roye-ai/client with types from @roye-ai/contracts/roundtable, map the fields below and branch on error category.
| Contract 1 | Contract 2 |
|---|---|
POST /v1/runs { requestId, definition } | POST /v1/roundtable/runs { idempotencyKey, definition } |
definition.apiVersion, definition.runtimeVersion | definition.profile { id: 'roundtable-text', revision: '1' } |
View requestId, definitionDigest | operation { operationId, idempotencyKey, inputDigest } |
View runtimeVersion, runtimeRevision | profile, serviceRevision |
usage[].providerId, generationId, upstreamCost | usage[].costStatus (pending, reported, unknown). Neither contract exposes supplier identity or cost. |
Events { apiVersion, runId, cursor, at, payload } | Adds eventId, module, type, source, causalOperationId. Cursors stay contiguous. |
Error { code, message, retryable } | Shared envelope with category, nextAction, operationId |
GET /v1/runtime | GET /v1/capabilities |
/v1/runskeeps its contract 1 schemas andRoye-Contract-Version: 1. Its usage reportsupstreamCostunknownwithusdnull,providerIdroyeand nogenerationId, so read charges from the billing usage view.- A key resolves across the two contracts only for a definition valid under both with the same meaning, so a larger contract 2 definition never matches a contract 1 run.
// Contract 1, legacy route /v1/runs
await legacyClient.submit({ apiVersion, runtimeVersion, ...rest }, requestId);
// Contract 2, /v1/roundtable/runs: the same stored key addresses the same run
await roye.roundtable.runs.create({
definition: { ...rest, profile: { id: 'roundtable-text', revision: '1' } },
idempotencyKey: requestId,
});