Skip to content

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.

client.ts
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.

HandleRuns inGuide
roye.roundtable.runsBackendRoundtable
roye.agentsBackendAgents
roye.evaluationsBackendEvaluations
roye.communication, RoyeActorBackend, each processorCommunication
roye.knowledge, RoyeKnowledgeMemberBackend, each member processKnowledge
roye.work, RoyeWorkParticipantBackend, each worker and reviewer processWork
roye.companies, with read-only operating sessionsBackendCompany Workspace
roye.automationBackendAutomation
roye.actions, RoyeActionsInvoker, RoyeActionsApproverBackend, an assistant's process, your approval UIActions
roye.agreementsBackendAgreements
roye.billingBackendFunding and usage
roye.projectLifecycleBackendProject exit and export
roye.operations, roye.intents, roye.capabilities(), roye.preflight(), roye.contractPins()BackendThis 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.

OperationRouteResult
CreatePOST /v1/keys201 with the secret once (secretStatus: 'returned'). scopes: null means every API.
RotatePOST /v1/keys/{keyId}/rotate201 successor and previous. Copies name, scopes, environment and createdBy; sets rotatedBy.
RevokePOST /v1/keys/{keyId}/revoke200, the same on repeat. Revoke each key of a chain by its ID.
ListGET /v1/keys?cursor=&limit=200 { items, next } by ID.
GetGET /v1/keys/{keyId}200 key view, never a secret. Other projects' or environments' keys are 404 not_found.
create-key.sh
# 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.
rotate-key.sh
# 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" }
revoke-key.sh
# 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

ScopeRoutes 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 keyGET /v1/capabilities, /v1/operations/... and GET /v1/contracts/pins
The pinned module's scopePUT /v1/contracts/pins/{module}
  • Scopes are fixed for a key's life and copied on rotation. null grants all, and keys older than scopes read as null. Outside its scopes a key gets 403 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, agents or actions), and so does the project key a schedule or event trigger runs as.
  • An operating session started with a companies or automation key 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 201 with Roye-Replayed: true and secretStatus: 'not_replayable', without the secret.
  • Lost create: POST /v1/operations/recover with { module: 'platform', kind: 'keys.create', idempotencyKey }, revoke the key in result.resource, and create a new one under a new idempotencyKey.
  • Lost rotation: recover with { module: 'platform', kind: 'keys.rotate', target: { keyId }, idempotencyKey }, using the rotated key's ID and the original idempotencyKey. Then rotate the successor in result.resource with overlapMs: 0 under a new idempotencyKey.

Key holders, rotation overlap, refusal codes and legacy routes are in the key lifecycle reference.

Contract versions and pins

RoutesVersion served
Agents, Evaluations, Work, Companies, Automation, Agreements, Communication, Knowledge, ActionsRoye-Contract-Version, or the environment's pin without it.
/v1/runs, /v1/runtime, /v1/capabilities, /v1/operations, /v1/contractsAlways 1. A requested version is ignored.
Billing, project lifecycleAlways 1. Others get contract_version_unsupported.
/v1/roundtable/runs, Company manager routesAlways 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 is contract_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.
RequestResult
GET /v1/contracts/pinsPer 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).

pins.http
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 }
pins.ts
// 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.

CategoryExample codesNext action
invalid_inputinvalid_request, payload_limitFix the input.
unsupportedunsupported_capability, contract_version_unsupportedPick a supported version or capability.
invalid_bindingstale_reference, stale_bindingRe-read, then retry with fresh references.
deniedunauthorized, forbidden, not_foundObtain authority.
revokedcredential_expired, credential_revoked, authority_revokedObtain authority.
not_readynot_ready, company_not_activeRe-read or repair.
exhaustedbudget_exhausted, quota_exceeded, concurrency_exhausted, rate_limitedRaise the limit or retry later.
expired_historycursor_expired, history_expired, operation_replay_expiredRestart from a snapshot or recover.
pending_originaloperation_pendingObserve the original.
conflictidempotency_conflict, revision_conflict, invalid_transitionRecover or re-read.
transientunavailableRetry 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.

errors.ts
// { "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.

RuleBehavior
KeyOpaque. No credentials or personal data.
ScopeProject, environment, module, kind and target.
Same key, same inputReplays the original with Roye-Replayed: true. No second run or charge.
Same key, other input409 idempotency_conflict with the original operationId.
Lost responseResend 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.

recover.ts
// 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 run

Observation

  • events() pages a run's contiguous events until execution settles or maxDurationMs passes. wait() returns when execution settles or its bound expires. until can end it sooner, never later.
  • Usage can stay pending after that. Re-read the same original within a separate bound, then keep any pending or unknown explicit. Unknown is never zero.
  • Aborting stops only the observation, and closing the client cancels no run.
  • Publish only committed outputs, and read executionSettled and meteringSettled separately.
observe.ts
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.

preflight.ts
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

LimitValue
idempotencyKey1 to 80 of A-Z, a-z, 0-9, _, -.
Replay window7 days.
Client retries5 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, expiresAt1 to 120 characters; null or 1 to 32 scopes; future, at most 90 days ahead.
Rotation overlapMs0 to 604,800,000 ms (7 days).
Key list limit1 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 using retryable, nextAction and retryAfterMs, with the same key, input and scope. The SDK retries rate_limited but not concurrency_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 IntentStore on 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 as unconfirmed and are returned.
  • EphemeralIntentStore is for tests only.
  • A key reused with other input or contract version fails with idempotency_conflict before sending, keeping the original. Resending a stored request older than the replay window gets operation_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.
intents.ts
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 as creator_removed and gets 404 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.

WhenOld keyWork it admitted or recorded
During the overlapWorks 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 rotationRefused.Keeps running.
The overlap ends, or the old key's own expiry came firstcredential_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 unrotatedRefused.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 overlapWorks until the overlap ends.Withdrawn when the overlap ends.

Refusals and legacy routes

KeyClean routes`/v1/runs`, `/v1/runtime`, legacy routes
Revoked401 credential_revoked401 unauthorized
Expired, overlap included401 credential_expired401 unauthorized
Unknown, or wrong secret401 unauthorized, no state revealed401 unauthorized
Exited project (digests removed)401 unauthorized401 unauthorized
  • The legacy key routes POST and GET /v1/projects/{projectId}/{environment}/keys and DELETE /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 have null name and scopes and heldBy: 'creator'. New integrations use /v1/keys.
  • Key routes answer Roye-Contract-Version: 1, and key operations appear in GET /v1/operations. lastUsedAt is accurate to five minutes and null until 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.

PathHow
Your template, as definedResolve 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, editedThe same, after your app changes fields it owns, such as role instructions, owner acceptance or binding display names.
Direct compositionCreate 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.
composition.ts
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 1Contract 2
POST /v1/runs { requestId, definition }POST /v1/roundtable/runs { idempotencyKey, definition }
definition.apiVersion, definition.runtimeVersiondefinition.profile { id: 'roundtable-text', revision: '1' }
View requestId, definitionDigestoperation { operationId, idempotencyKey, inputDigest }
View runtimeVersion, runtimeRevisionprofile, serviceRevision
usage[].providerId, generationId, upstreamCostusage[].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/runtimeGET /v1/capabilities
  • /v1/runs keeps its contract 1 schemas and Roye-Contract-Version: 1. Its usage reports upstreamCost unknown with usd null, providerId roye and no generationId, 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.
migration.ts
// 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,
});