Data
Knowledge API
Keep a team's versioned documents, decisions and attributed claims, and retrieve access-checked context with source references for your own model call. It uses no company and no Roye inference, so any model works.
Knowledge contract 1 runs on the local service only, with a lexical index. It is not hosted or published and may change. A request without Roye-Contract-Version gets contract 1, which is never pinned.
Quickstart
A trusted backend creates a space, a collection and a member per agent, grants the collection and issues each member process its own token once. Never put the backend key in a member process.
import { Roye } from '@roye-ai/client';
// Trusted backend, server-side only: the backend key never reaches a member process or a browser.
const roye = new Roye({ baseURL, token: () => process.env.ROYE_PROJECT_KEY!, projectId, environment: 'development', intents });
const space = await roye.knowledge.spaces.create({ displayName: 'product-team', idempotencyKey: 'ksp-1' });
const decisions = await space.collections.create({ displayName: 'decisions', idempotencyKey: 'kcl-dec' });
const planner = await space.members.create({ kind: 'agent', displayName: 'planner', idempotencyKey: 'kmb-planner' });
await space.collections.get(decisions.id).grants.set({
grants: { [planner.id]: ['read', 'contribute'] },
expectedRevision: decisions.view.revision,
idempotencyKey: 'grants-1',
});
const issued = await space.members.get(planner.id).tokens.issue({ scopes: ['read', 'write'], idempotencyKey: 'ktk-planner-1' });
// Hand issued.secret (rkt_...) with space.id, planner.id and the collection ID to the planner process.A member process needs only its own token and outbound HTTPS. One member commits documents and decisions, and another retrieves context for its own model call.
import { RoyeKnowledgeMember } from '@roye-ai/client';
// Member process: its own token, outbound HTTPS only.
const kb = new RoyeKnowledgeMember({
baseURL,
token: () => process.env.PLANNER_TOKEN!,
spaceId,
memberId,
intents, // may be shared: each client resumes only the intents its own principal recorded
});
const doc = await kb.documents.create({
collectionId,
title: 'Pricing brief',
contentType: 'text/markdown',
content: '...',
idempotencyKey: 'doc-1',
});
// Reference context for your own model call; never instructions. The SDK supplies the retrieval key.
const context = await kb.retrieve({ query: 'launch region', bounds: { maxItems: 8, maxContextChars: 12000 } });Concepts
Every resource belongs to one project and environment. IDs are opaque, so do not parse their prefixes. A committed revision of a document or decision is immutable, and the previous one becomes superseded.
| Resource | Meaning |
|---|---|
Space (ksp_) | Collections, members and records of one project and environment. |
Collection (kcl_) | Records with grants: which members may read, contribute or curate them. |
Member (kmb_) | An agent, service or human identity. Its label grants nothing. |
Member token (ktk_) | A short-lived credential for one member process, with read and write scopes. |
Document (kdc_) | Titled text, Markdown or JSON with tags, attributes, immutable numbered revisions and exact historical reads. |
Decision (kdr_) | Moves from open to decided. A later decision can supersede it. |
Claim (kcm_) | A statement with an author and required sources. Knowledge does not assert that it is true. |
Retrieval (kqr_) | The bounded, access-checked result of one query, kept for later reads. |
Job (kjb_) | Background processing of a revision, such as indexing, with bounded attempts. |
A revision a company's operating principal committed for a member has committedVia: operating_principal and a provenance with the Agents output digest and the output field used ($ for the whole text output). Only the backend key sees the execution ID and the Work task the document delivers.
Credentials
| Credential | Held by | Can |
|---|---|---|
| Backend project key | Your trusted backend (roye.knowledge) | Every route, including reads, writes and retrieval for a member's view. |
Member token (rkt_…) | One member process (RoyeKnowledgeMember) | Read, write and retrieve within its own grants and scopes. It never manages. |
| Developer sign-in | The console | Read spaces, collections, members, token metadata, document and decision lists, jobs and usage. Never a backend key, member token or document content, but decision lists return full records. |
A token secret is returned only in the first issue response.
Retrieval
- Each item has a source reference (type, ID, revision, collection, content digest, locator, author and, for a document, its passage), an excerpt, a relevance score and the role
reference_context. - Retrieved content is reference context, never instructions: it cannot change grants, budgets or what your application decides.
- Ranking happens in the index before the candidate cut. Every index read is limited to the collections the caller can read, so nothing it cannot read is read, ranked or counted. Records that can never be returned, such as superseded revisions, are skipped before the cut. Index reads stop at the candidate target, 48 pages or 4,000 rows, and
consistency.scanLimitReachedistruewhenever they stopped with matching rows unread, so the ranking is approximate. - Candidates come from the index, then Knowledge re-reads each record and the caller's grants, so a stale index never returns deleted, withdrawn or unreadable content.
- A replay or later read is filtered again: newly unreadable items show as
withheld, deleted or withdrawn ones as outcomes without excerpts.
Each item's freshness is one of:
| Freshness | Meaning |
|---|---|
current | Every readable source it relies on is still current. |
source_superseded | A cited revision is no longer current, or a decision revision or target was superseded, withdrawn or retracted. |
source_deleted | A cited source was deleted. This outranks source_superseded. |
Passages and offsets
A document revision holds up to 1 MiB of normalized text. Retrieval splits it into passages of about 400 to 1,200 UTF-16 code units, and a document item is one passage. maxItems counts passages, so one document can contribute several items. Offsets count UTF-16 code units in the normalized content of the exact revision: slice it from start to end to get the passage or the excerpt.
| Field | Meaning |
|---|---|
passage.id | Stable for its document, revision and position. |
passage.ordinal | Position of the passage in the revision, from 0. |
passage.start, passage.end | Offsets of the passage in the revision content. |
locator.start, locator.end | Offsets of the excerpt in the same content. The excerpt lies inside its passage. |
Tags and attributes
A revision takes up to 16 attributes. A key is a lower-case ASCII identifier of up to 40 characters, and a value is an NFC string of up to 256 characters, a finite number or a boolean. A new revision keeps the previous tags and attributes unless it sets them. Tags are Unicode letters, marks and digits in NFC and lower case, up to 64 characters, with _, ., : and - allowed after the first character, so a Korean tag such as 배송 is valid.
The tags filter matches a document with any listed tag. filters.attributes takes up to 8 keys and every condition must hold. A document without the attribute or with a value of another type never matches, and decisions and claims never match an attribute filter.
| Condition | Matches when |
|---|---|
eq | The attribute equals the string, number or boolean. |
in | The attribute equals one of up to 10 listed values. |
gt, gte, lt, lte | The attribute is inside the range. All bounds are numbers, or all are strings compared in UTF-16 code-unit order. |
Index profiles and space policy
A space fixes its index profile and revision at creation with policy.indexProfile and policy.indexProfileRevision. lexical revision 1 indexes word tokens. Revision 2, the default for new spaces, also strips Korean postpositions, so a query for 배송은 matches 배송. It removes compounds such as 에는 whole and a postposition after a word in another script (API는 matches API), and keeps common nouns whose last syllable is also a postposition, such as 고양이, whole. Existing spaces keep revision 1, and a reindex request names the space's revision.
Policy values are open. The Knowledge module's acceptedValues in GET /v1/capabilities lists the values this deployment accepts and each default, and any other value is refused with unsupported_capability. Keep a value your client does not know, such as an older space's policy, as it is.
| Policy field | Accepted in the local preview | Default |
|---|---|---|
policy.indexProfile | lexical | lexical |
policy.indexProfileRevision | 1, 2 | 2 |
policy.extraction | off | off |
policy.supersededRetention | unlimited | unlimited |
Contract 1 changed in place on 2026-10-27 to add passages, attributes, ranking in the index and profile revision 2, and limitsRevision became knowledge-2. Index data written before then is not read, so recreate any local space indexed earlier.
Example: filter a product catalog
A catalog keeps one document per product with tags and attributes. The first request creates one, and the second retrieves passages from in-stock products priced from 20 to under 50. A help center uses the same fields with attributes such as product and locale.
# 1. A product document with tags and attributes (member token with write scope, or the backend key).
POST /v1/knowledge/spaces/{ksp}/collections/{kcl}/documents
{ "idempotencyKey": "doc-kettle-1", "title": "Electric kettle 1.7 L", "contentType": "text/markdown",
"content": "# Electric kettle 1.7 L\n\nA brushed steel kettle with a 1.7 litre capacity, a concealed 2,200 W element and a removable limescale filter. The handle stays cool and the lid opens with one press.\n\n## Boil time\n\nA full kettle boils in about four minutes; one cup boils in under a minute. Automatic shut-off ends the boil and stops a dry kettle from heating.\n\n## Care\n\nDescale monthly in hard-water areas. Wipe the body with a damp cloth; never immerse the base.",
"tags": ["kitchen", "주방"], "attributes": { "category": "kettle", "price": 39.5, "in_stock": true } }
# 2. Passages from in-stock products priced from 20 to under 50, with excerpts of at most 160 characters.
POST /v1/knowledge/spaces/{ksp}/retrieve
{ "idempotencyKey": "ret-kettle-1", "query": "boil time",
"filters": { "tags": ["kitchen"], "attributes": { "price": { "gte": 20, "lt": 50 }, "in_stock": { "eq": true } } },
"bounds": { "maxItems": 5, "maxContextChars": 8000, "maxExcerptChars": 160 } }
# 201 { "items": [ { "role": "reference_context", "outcome": "available", "type": "document", "id": "kdc_…", "revision": 1,
# "excerpt": "l and the lid opens with one press.\n\n## Boil time\n\nA full kettle boils in about four minutes; one cup boils in under a minute. Automatic shut-off ends the boil ",
# "locator": { "start": 157, "end": 317 }, "passage": { "id": "kps_…", "ordinal": 0, "start": 0, "end": 457 },
# "freshness": "current", "score": 25.034, … } ],
# "consistency": { "unindexedInScope": 0, "indexFailedInScope": 0, "scanLimitReached": false, … }, "truncated": false }
# The excerpt is a fixed-width window around the first match, so it may start or end inside a word.
# 3. Check the excerpt against the exact revision: content.slice(157, 317) is the excerpt, slice(0, 457) the passage.
GET /v1/knowledge/spaces/{ksp}/documents/kdc_…/revisions/1Endpoints
Routes are under /v1/knowledge, and … is /spaces/{ksp}. Mutations take an idempotencyKey in the body, and POST on a space, collection or member ID updates it. The backend key works on every route. Member tokens need scope write to write and read to read, and backend-only routes refuse them with 403 forbidden before any lookup.
| Resource | Routes | Member token |
|---|---|---|
| Spaces | POST, GET /spaces, GET, POST /spaces/{ksp}, POST …/{suspend,resume,delete} | No |
| Collections | POST …/collections, POST …/collections/{kcl}[/{grants,delete}], GET …/collections[/{kcl}] | Collections it can read |
| Members | POST …/members, POST …/members/{kmb}[/{suspend,resume,retire}], GET …/members[/{kmb}] | Reads the member directory |
| Member tokens | POST, GET …/members/{kmb}/tokens, GET …/members/{kmb}/tokens/{ktk}, POST …/tokens/{ktk}/revoke | No. Token metadata never holds a secret. |
| Document writes | POST …/collections/{kcl}/documents, POST …/documents/{kdc}/{revisions,supersede,delete}, POST …/documents/{kdc}/revisions/{n}/{withdraw,delete} | With contribute or curate |
| Document reads | GET …/collections/{kcl}/documents, GET …/documents/{kdc}[?asOf=], GET …/documents/{kdc}/revisions[/{n}] | With read |
| Decisions | POST, GET …/collections/{kcl}/decisions, GET …/decisions/{kdr}[?asOf=], POST …/decisions/{kdr}/{revisions,supersede,withdraw,delete}, GET …/decisions?responsibleMemberId= | With the needed grant. Not the space-wide GET …/decisions. |
| Claims | POST, GET …/collections/{kcl}/claims, GET …/claims/{kcm}, POST …/claims/{kcm}/{retract,contradicts,delete} | With the needed grant |
| Retrieval | POST …/retrieve, GET …/retrievals/{kqr} | Yes |
| Reindex, jobs | POST …/reindex, GET …/jobs[/{kjb}] | Jobs only, on documents it can read |
| Events | GET …/events?cursor= | Events in collections it can read |
| Usage | GET …/usage | No |
Limits
Preview values until measured costs set them, enforced with typed errors.
| Limit | Value |
|---|---|
| Documents | 1 MiB of normalized text/plain, text/markdown or application/json per revision, in a request body up to 3 MiB. Title up to 200 characters, 16 tags of 64 characters and 32 sources. |
| Attributes | 16 per revision, keys up to 40 characters and string values up to 256. Per retrieval 8 attribute filters with up to 10 values in a set. |
| Passages | About 400 to 1,200 UTF-16 code units each. |
| Revisions | 64 per document or decision. |
| Retrieval | Query up to 2,048 characters, of which the first 16 distinct terms rank (fewer when the readable collections need several reads per term). Per retrieval up to 50 items (passages), 64,000 context and 4,000 excerpt characters. |
| Index reads | Per retrieval 48 index pages and 4,000 index rows, and up to 100 candidates rescored. |
| Space size | 100 collections and 1,000 members. |
| Member tokens | 1 hour by default, at most 24 hours. |
| Pages | 64 items. |
| Retention | Retrieval excerpts 24 hours, retrieval records 30 days, events 7 days. |
Not in this preview: hosted service, handoff manifests, promotion, exports, semantic retrieval, the event stream, company bindings, caps and rate limits, and any charge.
Errors
| Code | HTTP | What to do |
|---|---|---|
invalid_request, payload_limit, bounds_exceeded | 400, 413 | Fix the input or reduce the bounds. |
unsupported_capability | 400 | Use an advertised capability. asOf works on exact reads, not on retrieval. |
unauthorized, credential_expired, credential_revoked | 401 | Get a new member token from the backend. |
forbidden, not_found | 403, 404 | The credential lacks the scope or grant, and there is no privileged fallback. not_found hides whether a resource exists. |
space_not_active, member_suspended | 409 | Resume the space or member. |
index_pending, index_failed | 409 | Only with requireIndexed: true; reads by ID never wait. Retry index_pending after retryAfterMs, and reindex from the backend after index_failed. |
invalid_source, stale_reference | 409 | Re-read the referenced record and cite an existing readable revision. |
revision_conflict, invalid_successor | 409 | Commit again on the latest baseRevision with a new key, or pick a successor that is not final and makes no cycle. |
idempotency_conflict | 409 | The key was used with other input. Recover the original. |
quota_exceeded | 429 | A count limit is reached: collections or members per space, revisions per record, or records one transition changes. |
retrieval_expired, cursor_expired | 410 | Past retention. Read the current records again. |
unavailable | 503 | Retry with the same key and input. |
Recovery
Save each idempotencyKey with its input before sending, and never retry an uncertain call with a new key. After a lost response, recover the original by its key through POST /v1/operations/recover with the credential that performed it. The SDK generates each retrieval's key, so a retry is not counted twice.
| Situation | What happens and what to do |
|---|---|
| Lost write response | The same key replays the original. Write results carry metadata only, so a replay returns nothing a later grant change would withhold. |
| Lost token issue response | The replay has secretStatus not_replayable and no secret. Revoke that token by its ID and issue a new one with a new key. |
| Lost retrieval response | The same key returns the same retrieval, filtered again against current access. After the replay window only references and usage remain. |
Usage
knowledge.processed records bytes once per content digest when indexing first derives its data, and knowledge.retrieval records each completed retrieval once, scaled by its declared context bound. Both are measurement records: no price, cap or invoice applies in this preview.
Runnable example
apps/roye-api-examples/src/knowledge runs a backend and separate member processes from grants to deletion; run pnpm --filter @roye-ai/api-examples knowledge after the prerequisites in examples/README.md.