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.
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.
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.
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.
| Resource | Meaning |
|---|---|
| Profile | Roye-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, elsenull. - Contract 2
terminalReasonis 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.
| Profile | Contract | Output, cut reply |
|---|---|---|
text-standard@1 | 1, 2 | Text. Completes with reason completed. |
text-standard@2 | 1, 2 | Text. Completes with reason output_limit. |
structured@1 | 2 | JSON. Cut or above 8 KiB: fails unvalidated with output_truncated; invalidOutput and outputDigest are null. |
json-standard@1 | 2 | Deprecated JSON. Completes unvalidated with output_limit. |
tool-result@1 | 2 | Deprecated 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, orexpiredat its deadline without reaching a provider.running: a worker holds it. Cancelling moves it tocancelling; the dispatched call settles on its original record.completed: output and next checkpoint committed.failed,cancelled: no output, and the session is free again. SeeterminalReason.
Cancelling a queued execution is immediate and releases its reservation; a terminal one is returned unchanged.
// 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.
| Reason | When |
|---|---|
completed, execution_timeout, caller_cancelled, session_deleted | Output committed; activeTimeoutMs exceeded; you cancelled; the session was deleted. |
execution_failed | The call failed, or the base checkpoint was unreadable first. |
output_limit | failed: output above 8 KiB. completed: a cut reply. |
worker_lost | Worker lost after dispatch; usage unknown and held. |
deadline | Queued 24 hours without a worker. |
authority_revoked | Authority lost at commit (cancelled without a request) or before an appointee's call. |
principal_ended, company_archived, stale_work_claim | Appointment, company or Work reference lost before the call. Not billed. |
output_invalid, output_truncated | JSON 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.
// 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.
| Reply | Result |
|---|---|
| Valid | One call, no retry. Output and checkpoint committed. |
| Invalid | output_invalid. invalidOutput holds the text and first failing JSON pointer and rule until the session is erased. Usage kept. |
| Cut or above 8 KiB | output_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_readynamingdeprecatedon 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
completedwith one JSON object.outputDigestisagentsOutputDigest(parsedObject); the input digest isinputDigest({text, outputFormat: json}). - A missing, multiple, wrong-name, mixed, malformed, oversized or cut result is
output_invalid.invalidOutput.erroris text without provider content: branch onterminalReason, and never log it or private input.
// 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.
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.
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.// 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, orcontrollerwithsessionIdandadmittedControlRevision),appointmentId,appointmentRevision.
| Answer | Cause |
|---|---|
409 appointment_not_ready | Suspended, ended, no definition yet, or blocked. |
409 company_not_active | Provisioning, archived or deleting. |
409 stale_binding | Stale definition or appointmentRevision. |
409 definition_archived | The appointment's definition is archived. |
400 unsupported_capability | A customer-hosted appointee, or an actor on a session execution. |
400 invalid_request | A 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.
workclaim{ taskId, assignmentId, claimId, fence }: an active, unexpired claim admissible in Work. An actor's claim is on its company's board, held for itself.workreview{ taskId, submissionId }: a submission pending review on that task. The operating principal cites the turn'soutputDigestwhen deciding.automation(session, cycle,ade_entry, ordinal): only from that Automation session's operating principal; your backend gets403 forbidden.communication{ workspaceId, requestId }: an actor answer turn for an open Communication request addressed to its appointment, else403 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.
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}.# 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.// 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.
| Resource | Routes |
|---|---|
| Profiles | GET /profiles, GET /profiles/{profile}/revisions/{revision} |
| Definitions | POST /definitions, GET /definitions[/{definition}], POST …/archive, …/unarchive |
| Revisions | POST /definitions/{definition}/revisions, GET …/revisions[/{revision}], GET …/{revision}/readiness |
| Sessions | POST /sessions, GET /sessions[/{session}], …/checkpoints, …/messages (contract 2), POST …/close, …/delete |
| Executions | POST /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.
| Limit | Value |
|---|---|
| Payloads | Persona 32 KiB, input 64 KiB, output 8 KiB, schema 16 KiB. |
| Model settings | Output tokens up to 2,048 (default 1,024), temperature 0 to 1 (0.7), timeout 1 to 120 s (60). |
| Session history | 256 KiB with the new input and the 8 KiB output allowance, else payload_limit. Never truncated. |
| Definitions | 1,000 per project and environment, 100 revisions each (quota_exceeded). Name 120 characters, 16 labels. |
| Time, pages | Queued 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.
| Code | HTTP | What to do |
|---|---|---|
invalid_request, payload_limit, unsupported_capability, contract_version_unsupported | 400, 413 | Fix the input; use an advertised profile, model, keyword or version. |
unauthorized, forbidden, not_found | 401, 403, 404 | No authority, or not in this project and environment. |
profile_not_ready, definition_archived, budget_exhausted, concurrency_exhausted, quota_exceeded | 409, 429 | Nothing recorded. Fix readiness, unarchive, or retry later with the same key; a quota needs a raise. |
session_busy, revision_conflict, idempotency_conflict | 409 | Wait 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, unavailable | 409, 503 | Read 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.
| Situation | What to do |
|---|---|
| Lost create or cancel response | Resend with the same key. The result has no output, so read the execution. |
worker_lost | No 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,meteringSettledandaccountingseparately. Each original call records model, token evidence andcostStatus;unknownis never zero. - For a funded hosted execution,
GET /v1/billing/usage/agents/EXECUTION_ID(billing contract 1, SDKbilling.usage.getAgentExecution(id)) returnsstate,maximumMicros,heldMicros,chargedMicros,releasedMicrosand 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.