Skip to content

AI execution

Agents API

Run bounded model work from definitions you own: persona, model and defaults pinned to a Roye profile. A private session carries history between executions.

Hosted preview

Contract 1 is the default; contract 2 adds structured output. Both are pinnable. The operator enables hosting per project; this guide does not show it is enabled, or a model qualified, for yours.

Quickstart

Call only from your trusted backend, with its project key. Hosted use also needs operator enablement, an allowed priced model, funding, customer credentials and a matched API and worker rollout; check GET /v1/capabilities and readiness first, and never use a disabled or unqualified profile.

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

// Trusted backend, server-side only: the backend key never reaches a browser.
const roye = new Roye({ baseURL, token: () => process.env.ROYE_PROJECT_KEY!, projectId, environment: 'development', intents });
const definition = await roye.agents.definitions.create({
  displayName: 'support-assistant',
  persona: { instructions: 'Answer billing questions in two sentences.' },
  profile: { id: 'text-standard', revision: '1' },
  model, // a public provider/model ID the profile lists
  defaults: { maxOutputTokens: 512, temperature: 0.3 },
  idempotencyKey: 'agd-1',
});
const readiness = await definition.revision(1).readiness();
if (!readiness.eligible) throw new Error('Not ready: ' + readiness.reasons.join(', '));

Waits are bounded, and their expiry cancels nothing. The next execution starts from the settled history.

session.ts
const session = await roye.agents.sessions.create({
  definition: { id: definition.id, revision: 1 },
  idempotencyKey: 'ags-1',
});
const first = await session.executions.create({ input: { text: 'Where do I find my invoice?' }, idempotencyKey: 'agx-1' });
// wait() returns the execution view as it stands: expiry never cancels. Wait again until it is terminal.
let done = await first.wait({ waitMs: 30000 });
while (['queued', 'running', 'cancelling'].includes(done.status)) done = await first.wait({ waitMs: 30000 });
// The create result carries no output; the waited view of a completed execution does.
const answer = done.status === 'completed' ? done.outputs[0]?.content : undefined;
// The next execution starts from the first one's settled history.
const second = await session.executions.create({ input: { text: 'And for last year?' }, idempotencyKey: 'agx-2' });

pnpm --filter @roye-ai/api-examples agents runs this flow; examples/README.md lists its prerequisites.

Concepts

IDs are opaque; resources belong to one project and environment. Sessions and executions keep the immutable revision they pin.

ResourceMeaning
ProfileRoye-installed, read-only models, limits and defaults.
Definition (agd_)Persona, profile, model and defaults in digested revisions. Archivable.
Session (ags_)A private conversation on one revision, one non-terminal execution at a time.
Checkpoint (agk_)Settled history of a completed execution. Routes return metadata only.
Execution (agx_)One model call with status, usage and output. No history without a session.

The console is read-only and never sees keys, checkpoints, messages or events.

Contract 1 or 2

Contract 2 adds schema-validated JSON, session messages, and appointee and reference executions. Select it with Roye-Contract-Version: 2 or roye.agents.v2; responses echo the version. The first request of a project and environment pins its version, no header pinning 1 (SDK versions).

  • A completed contract 2 view has outputDigest, the canonical reply digest, else null.
  • Contract 2 terminalReason is open: treat an unknown value as terminal.

A definition whose first revision has outputSchema or pins json-standard is contract-2-only, and a schema cannot be added later. Contract 1 hides these and actor and reference executions from lists, and refuses them by name with contract_version_unsupported.

Contract 1 filters lists per page, so a page can be short or empty while next is set. Read until next is null.

Profiles

A cut reply stopped at maxOutputTokens. Capabilities list the JSON profiles under profileContractVersions.

ProfileContractOutput, cut reply
text-standard@11, 2Text. Completes with reason completed.
text-standard@21, 2Text. Completes with reason output_limit.
structured@12JSON. Cut or above 8 KiB: fails unvalidated with output_truncated; invalidOutput and outputDigest are null.
json-standard@12Deprecated JSON. Completes unvalidated with output_limit.
tool-result@12Deprecated JSON. Cut or oversized: fails with output_invalid.

Execution lifecycle

Statuses only move forward. waiting never occurs: no profile has waits.

  • queued: admitted and reserved, or expired at its deadline without reaching a provider.
  • running: a worker holds it. Cancelling moves it to cancelling; the dispatched call settles on its original record.
  • completed: output and next checkpoint committed.
  • failed, cancelled: no output, and the session is free again. See terminalReason.

Cancelling a queued execution is immediate and releases its reservation; a terminal one is returned unchanged.

cancel.ts
// Cancel by ID from anywhere; a queued execution is cancelled at once, a running one moves to cancelling.
await roye.agents.executions.get(second.id).cancel({ idempotencyKey: 'agx-2-cancel' });

Terminal reasons

Check the reason, not only the status, before parsing a completed reply.

ReasonWhen
completed, execution_timeout, caller_cancelled, session_deletedOutput committed; activeTimeoutMs exceeded; you cancelled; the session was deleted.
execution_failedThe call failed, or the base checkpoint was unreadable first.
output_limitfailed: output above 8 KiB. completed: a cut reply.
worker_lostWorker lost after dispatch; usage unknown and held.
deadlineQueued 24 hours without a worker.
authority_revokedAuthority lost at commit (cancelled without a request) or before an appointee's call.
principal_ended, company_archived, stale_work_claimAppointment, company or Work reference lost before the call. Not billed.
output_invalid, output_truncatedJSON rejected. See structured output.

Structured output

Send structured@1, a listed model and an outputSchema. A new revision asks for native JSON with your schema on openai/… models and anthropic/claude-haiku-4.5, and for a forced function call on other anthropic/… models; no field selects it, and no other model is offered. An anthropic/claude-haiku-4.5 revision created while Roye used a forced function call for it keeps that call. To move to native JSON, create a new definition revision, then run new sessions and session-less executions on it. An existing session keeps the revision it was created on, and so its mechanism.

structured.ts
// Contract 2: roye.agents.v2 sends Roye-Contract-Version: 2 on every request. Contract 1 stays the default on roye.agents.
const extractor = await roye.agents.v2.definitions.create({
  persona: { instructions: 'Extract the vendor, the total and the purchase-order number, if there is one.' },
  profile: { id: 'structured', revision: '1' },
  model, // an anthropic/ or openai/ model the profile lists; Roye picks how to ask it for JSON
  outputSchema: {
    type: 'object',
    required: ['vendor', 'total', 'purchaseOrder'],
    properties: {
      vendor: { type: 'string', maxLength: 200 },
      total: { type: 'number', minimum: 0 },
      purchaseOrder: { type: ['string', 'null'] }, // null when the invoice has none
    },
    additionalProperties: false,
  },
  idempotencyKey: 'agd-invoice-1',
});
const run = await roye.agents.v2.executions.create({
  definition: { id: extractor.id, revision: 1 },
  input: { text: invoiceText, outputFormat: 'json' },
  idempotencyKey: 'agx-invoice-1',
});
let view = await run.wait({ waitMs: 30000 });
while (['queued', 'running', 'cancelling'].includes(view.status)) view = await run.wait({ waitMs: 30000 });
if (view.terminalReason === 'completed') console.log(JSON.parse(view.outputs[0].content));
else if (view.terminalReason === 'output_invalid') console.warn(view.invalidOutput?.error); // the rejected text is in invalidOutput.text
else if (view.terminalReason === 'output_truncated') console.warn('The reply was cut or too long; nothing was committed.');

The subset is type (one or more names, null included), enum, const, required, properties, items, additionalProperties: false, minLength/maxLength, minItems/maxItems, minimum/maximum and oneOf with a const discriminator: 16 KiB, digested only when present. The root is an object with properties, every node is typed, and a nullable field is type: [T, "null"] whose enum holds null and another value. pattern (check it after parsing), a nullable root, other type arrays, a bad nullable enum, object or array enum values and null in a non-nullable enum are unsupported_capability.

ReplyResult
ValidOne call, no retry. Output and checkpoint committed.
Invalidoutput_invalid. invalidOutput holds the text and first failing JSON pointer and rule until the session is erased. Usage kept.
Cut or above 8 KiBoutput_truncated. Events end execution.failed, execution.settled; native JSON execution.text may carry provisional, never-committed text.

Deprecated profiles

json-standard@1 and tool-result@1 are deprecated for new definitions; use structured@1. This refusal is frozen contract 2's one non-additive change.

  • A project with no revision on the profile in any environment gets profile_not_ready naming deprecated on create or revise.
  • A project holding one, even only in development, keeps creating revisions on it everywhere.
  • Existing definitions, sessions, executions and same-key retries are unchanged; capabilities list both.

The tool-result profile

  • Accept only status and reason completed with one JSON object. outputDigest is agentsOutputDigest(parsedObject); the input digest is inputDigest({text, outputFormat: json}).
  • A missing, multiple, wrong-name, mixed, malformed, oversized or cut result is output_invalid. invalidOutput.error is text without provider content: branch on terminalReason, and never log it or private input.
tool-result.ts
// Deprecated for new definitions: this create succeeds only where the project already holds a tool-result revision in any environment.
// Persist this intent and key on your backend before the first request.
const definition = await roye.agents.v2.definitions.create({
  idempotencyKey: 'invoice-definition-original',
  persona: { instructions: 'Extract the invoice total and currency.' },
  profile: { id: 'tool-result', revision: '1' },
  model, // Must appear in this project's profile models and pass revision readiness.
  outputSchema: {
    type: 'object',
    properties: { total: { type: 'number', minimum: 0 }, currency: { type: 'string', enum: ['USD', 'EUR'] } },
    required: ['total', 'currency'], additionalProperties: false,
  },
  defaults: { maxOutputTokens: 1024, temperature: 0 },
});
const execution = await roye.agents.v2.executions.create({
  idempotencyKey: 'invoice-execution-original',
  definition: { id: definition.id, revision: 1 },
  input: { text: invoiceText, outputFormat: 'json' },
});
const view = await execution.wait({ waitMs: 30000 });
// A pending view stays on this same original. Wait again rather than creating another execution.
if (view.status === 'completed' && view.terminalReason === 'completed') {
  const result = JSON.parse(view.outputs[0].content);
  // agentsOutputDigest(result) must equal view.outputDigest.
}
// Billing uses its own contract 1 header; this SDK method selects it.
const bill = await roye.billing.usage.getAgentExecution(execution.id);
// Compare heldMicros/chargedMicros/releasedMicros with execution and metering settlement.

Session messages

Contract 2 GET /v1/agents/sessions/SESSION_ID/messages returns the settled conversation, oldest first: one user and one assistant { role, content, createdAt } per completed execution, createdAt being admission time. It leaves out messages older than 30 days and returns at most 256 KiB, unpaged.

checkpointId is null before the first completion and after deletion; contentErased is true once the session is deleting, deleted or purged. No key, no usage. A query parameter is invalid_request, contract 1 gets contract_version_unsupported, the company operating principal 403 forbidden.

Session messages
GET /v1/agents/sessions/ags_…/messages
Authorization: Bearer <management key>
X-Roye-Project: <projectId>
X-Roye-Environment: development
Roye-Contract-Version: 2

# 200, Roye-Contract-Version: 2
# { "checkpointId": "agk_…", "contentErased": false,
#   "messages": [
#     { "role": "user", "content": "I cannot sign in since the update.", "createdAt": 1793000000000 },
#     { "role": "assistant", "content": "{\"category\":\"login\",\"escalationReason\":null}", "createdAt": 1793000000000 },
#     … ] }
# After the session is deleted: { "checkpointId": null, "contentErased": true, "messages": [] }

Appointee executions

A Company contract 2 appointee runs turns as its own actor: contract 2 POST /v1/agents/executions with principal { kind: actor, appointmentId }, session-less on the appointment's definition revision. Optional definition and appointmentRevision must be current.

Appointee execution
POST /v1/agents/executions
Authorization: Bearer <management key>
X-Roye-Project: <projectId>
X-Roye-Environment: development
Roye-Contract-Version: 2
Content-Type: application/json

{
  "idempotencyKey": "agx-plan-1",
  "principal": { "kind": "actor", "appointmentId": "<appointmentId>" },
  "input": { "text": "Draft the launch plan." }
}

# 202, Roye-Contract-Version: 2
# { "id": "agx_…", "status": "queued",
#   "principal": { "kind": "actor", "actorId": "pac_…", "appointment": { "appointmentId": "apt_…", "revision": 1 } }, … }
# Poll GET /v1/agents/executions/{id}?waitMs=30000 with Roye-Contract-Version: 2 until it is terminal.
appointee.ts
// The SDK sends the same request and adds only local checks and intent bookkeeping.
const run = await roye.agents.v2.executions.create({
  principal: { kind: 'actor', appointmentId },
  input: { text: 'Draft the launch plan.' },
  idempotencyKey: 'agx-plan-1',
});
  • Admission, the worker's claim and a pre-call check require a hired, ready appointee in an open company; otherwise it fails before the call, unbilled.
  • A same-key retry returns the original even after the appointee changed; a new key is checked again. Recover with kind executions.create, an empty target and the original key.
  • Turns use the project allowance and also reserve under any company budget, where unknown usage stays held, never zero (Company workspace).
  • Views show references.company, derived by the service and never sent: companyWorkspaceId, origin (deliberate, or controller with sessionId and admittedControlRevision), appointmentId, appointmentRevision.
AnswerCause
409 appointment_not_readySuspended, ended, no definition yet, or blocked.
409 company_not_activeProvisioning, archived or deleting.
409 stale_bindingStale definition or appointmentRevision.
409 definition_archivedThe appointment's definition is archived.
400 unsupported_capabilityA customer-hosted appointee, or an actor on a session execution.
400 invalid_requestA malformed principal, or one under contract 1.

References

Contract 2 references name the Work, Automation or Communication record an execution works under. They are immutable and digested: other references under one key are idempotency_conflict, the same ones return the original even after the claim ended, and views show {} when none.

  • work claim { taskId, assignmentId, claimId, fence }: an active, unexpired claim admissible in Work. An actor's claim is on its company's board, held for itself.
  • work review { taskId, submissionId }: a submission pending review on that task. The operating principal cites the turn's outputDigest when deciding.
  • automation (session, cycle, ade_ entry, ordinal): only from that Automation session's operating principal; your backend gets 403 forbidden.
  • communication { workspaceId, requestId }: an actor answer turn for an open Communication request addressed to its appointment, else 403 forbidden.

A claim or submission that is not current, or not the actor's, is 409 stale_work_claim. The worker rechecks at claim and before the call and fails a lost one as stale_work_claim, unbilled.

Work claim reference
POST /v1/agents/executions
Authorization: Bearer <management key>
X-Roye-Project: <projectId>
X-Roye-Environment: development
Roye-Contract-Version: 2
Content-Type: application/json

{
  "idempotencyKey": "agx-outline-1",
  "definition": { "id": "<definitionId>", "revision": 1 },
  "references": { "work": { "taskId": "wts_…", "assignmentId": "was_…", "claimId": "wcl_…", "fence": 1 } },
  "input": { "text": "Draft the outline." }
}

# 202, Roye-Contract-Version: 2
# { "id": "agx_…", "status": "queued", "references": { "work": { "taskId": "wts_…", … } }, … }
# 409 stale_work_claim: the claim is no longer current; read it with GET /v1/work/claims/{claimId}.
Review turn
# A review turn names the submission it reviews instead of a claim (the reviewer appointee's actor).
POST /v1/agents/executions
Roye-Contract-Version: 2
Content-Type: application/json

{
  "idempotencyKey": "agx-review-1",
  "principal": { "kind": "actor", "appointmentId": "<reviewer appointmentId>" },
  "references": { "work": { "taskId": "wts_…", "submissionId": "wsb_…" } },
  "input": { "text": "Review the draft against the criteria." }
}

# Once completed: { "id": "agx_…", "status": "completed", "outputDigest": "<64 hex characters>", … }
# 409 stale_work_claim: the submission is not pending review on that task.
references.ts
// The SDK sends the same request.
const run = await roye.agents.v2.executions.create({
  definition: { id: definitionId, revision: 1 },
  references: { work: { taskId, assignmentId, claimId, fence } },
  input: { text: 'Draft the outline.' },
  idempotencyKey: 'agx-outline-1',
});
  • 400 unsupported_capability: no Work or Communication read in this composition, or an Automation workflow run.
  • 400 invalid_request: contract 1, malformed, a non-ade_ entryId, Communication on a non-actor execution, or a closed request.

Endpoints

Routes are under /v1/agents. Mutations take an idempotencyKey; revise, archive, unarchive, close and delete also take expectedRevision. Lists return a page and a cursor.

ResourceRoutes
ProfilesGET /profiles, GET /profiles/{profile}/revisions/{revision}
DefinitionsPOST /definitions, GET /definitions[/{definition}], POST …/archive, …/unarchive
RevisionsPOST /definitions/{definition}/revisions, GET …/revisions[/{revision}], GET …/{revision}/readiness
SessionsPOST /sessions, GET /sessions[/{session}], …/checkpoints, …/messages (contract 2), POST …/close, …/delete
ExecutionsPOST /sessions/{session}/executions or POST /executions, GET /executions[/{execution}][?waitMs=], …/events, POST …/cancel

Deleting a session hides its content at once, exports included. Cleanup continues; usage and accounting records remain.

Limits

Preview values until measured costs set them. Project policy can be stricter.

LimitValue
PayloadsPersona 32 KiB, input 64 KiB, output 8 KiB, schema 16 KiB.
Model settingsOutput tokens up to 2,048 (default 1,024), temperature 0 to 1 (0.7), timeout 1 to 120 s (60).
Session history256 KiB with the new input and the 8 KiB output allowance, else payload_limit. Never truncated.
Definitions1,000 per project and environment, 100 revisions each (quota_exceeded). Name 120 characters, 16 labels.
Time, pagesQueued deadline 24 hours, waitMs up to 30 s, pages up to 64 (default 25), replay 7 days.

Not available: customer-callable tools, waits, context references, arbitrary code, automatic repair calls, streaming argument events.

Errors

Errors use the shared envelope. Terminal reasons are outcomes, not errors.

CodeHTTPWhat to do
invalid_request, payload_limit, unsupported_capability, contract_version_unsupported400, 413Fix the input; use an advertised profile, model, keyword or version.
unauthorized, forbidden, not_found401, 403, 404No authority, or not in this project and environment.
profile_not_ready, definition_archived, budget_exhausted, concurrency_exhausted, quota_exceeded409, 429Nothing recorded. Fix readiness, unarchive, or retry later with the same key; a quota needs a raise.
session_busy, revision_conflict, idempotency_conflict409Wait for or cancel the current execution, also before closing. Resend revision conflicts with a new key; recover idempotency conflicts.
stale_binding, stale_work_claim, appointment_not_ready, company_not_active, unavailable409, 503Read the appointment, claim or company again. Retry unavailable with the same key and input.

Recovery

Persist each idempotencyKey with its input before sending. After a lost response, resend with the same key or call POST /v1/operations/recover (module agents, the kind, the key). A new key admits and bills a second execution.

SituationWhat to do
Lost create or cancel responseResend with the same key. The result has no output, so read the execution.
worker_lostNo call is repeated. A new key is new work, not a retry.

Roye settles checkpoints, overdue queued work and interrupted deletion with no client. Reconnecting observes and starts no replacement; losing observation cancels nothing.

Usage

Admission reserves the full declared bound and a concurrency slot before any record exists. Reads, waits, events and replays never charge.

  • Read executionSettled, meteringSettled and accounting separately. Each original call records model, token evidence and costStatus; unknown is never zero.
  • For a funded hosted execution, GET /v1/billing/usage/agents/EXECUTION_ID (billing contract 1, SDK billing.usage.getAgentExecution(id)) returns state, maximumMicros, heldMicros, chargedMicros, releasedMicros and frozen pricing.
  • An invalid result can be charged. Cancellation keeps dispatched usage and proves neither refund nor physical termination. A customer waiver neither settles supplier liability nor proves the provider call ended.