Context0 Service User Guide
This document describes how to use the six core capabilities of Context0: Memory management, Knowledge Base management, Session management, Context Assembly, Memory Promotion, and Workspace management.
Preparations
Before reading, make sure you have completed the onboarding (seeQuick Start). The following examples use:
export API_KEY="<YOUR_API_KEY>" # Data Plane USER Key
export HOST="https://<your-endpoint>"Operations involving the Control Plane (members, Keys, promotion review, etc.) requireOwner Key, marked in examples as$OWNER_KEY.
Memory Management
Memory is the long-term memory capability provided by Context0 for Agents, compatible with the Mem0 protocol.
Memory Hierarchy (L1 Facts / L0 Entities / Rules)
After a conversation is ingested, Context0 progressively distills it into three layers of Memory:
Ingest ──► L2 Raw Conversation ──LLM Extraction──► L1 Atomic Facts ──Entity Recognition──► L0 Entity Profiles
(Immutable, traceable) (Single fact, with timeliness) (Structured entity card)Level | Content | Description |
L2 | Raw conversation text | Immutable, used for traceability and real-time recall fallback. |
L1 | Atomic facts | Single fact, such as "the project uses TypeScript", with |
L0 | Entity profiles | Structured entity cards, supporting five types: person / project / technology / organization / concept. |
Timeliness of L1 facts (
validity):Value
Meaning
permanentPermanent (e.g., name, core preferences).
durablePersistent (e.g., technology choices).
temporalTime-sensitive (e.g., "focusing on performance optimization this week").
Rules (distillation rules): You cancustomize rules for "what to extract from conversations and how to extract it", to control the distillation behavior. Additionally, throughPinyou can fix key memories as high-priority entries that do not decay over time.
Writing Memories (Automatic vs Manual)
Automatic write (recommended): Use the
ingestendpoint to ingest conversations. The server asynchronously extracts memories without blocking the conversation.curl -X POST "$HOST/v1/context/ingest" \ -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \ -d '{ "session_id": "sess_789", "user_id": "user_001", "messages": [ {"role": "user", "content": "The project prefers TypeScript, with Prisma as the ORM"}, {"role": "assistant", "content": "Got it, tech stack selection noted"} ] }'NoteWhen using the CLI plugin, the plugin calls
POST /v3/memories/addby default at the end of each valid turn, and the backend asynchronously distills long-term memories. No manual action is required.Manual write: Call
/v1/memoriesdirectly to extract atomic facts from a conversation:curl -X POST "$HOST/v1/memories" \ -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \ -d '{ "messages": [ {"role": "user", "content": "NextAuth is chosen for authentication"} ], "user_id": "user_001", "metadata": {"source": "manual"} }'(Recommended) V3 Memory Add:
POST /v3/memories/addis a Box-wrapped memory write endpoint. The request parameters are the same as/v1/memories, and the response includes deduplication information:curl -X POST "$HOST/v3/memories/add" \ -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \ -d '{ "messages": [{"role": "user", "content": "The project uses Vite for builds"}], "user_id": "user_001" }'Response
{"code": 0, "msg": "ok", "data": {"memory_id": "mem_1_2_abc", "event_id": 789, "created": true}}Field
Description
memory_idMemory ID
event_idThe event ID corresponding to the write (
created=falsewhen deduplication matches an existing memory)createdtrueCreated /falseDeduplication matched an existing memoryNoteThe CLI plugin uses this endpoint by default for writing memories.
Search Memories
Search memories by semantic similarity, using a two-way recall of vector kNN + BM25 lexical matching, fused with RRF to return top-k results. Three versions are available with increasing capabilities:
Path | L1 facts | L2 source text | Response format |
| Yes | No | Bare JSON array |
| Yes | Yes (enabled by default) | Bare JSON array |
| Yes | Yes |
|
Example
curl -X POST "$HOST/v2/memories/search" \
-H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
-d '{
"query": "tech stack selection",
"user_id": "user_001",
"limit": 10
}'Parameter Description
Field | Required | Description |
| Yes | Query text |
| No | Restricts to a specific user. USER Key is automatically bound to itself |
| No | Number of results [1,200], default 10 (alias |
| No | Additional filters, supporting time ranges: |
| No |
|
| No | Similarity threshold [0,1], no filtering by default (alias |
V3 search filters map parameter passing(Mem0 v1.1 SDK compatible): In the V3 endpoint
POST /v3/memories/search, entity parameters such asuser_id/agent_id/run_idshould be placed inside thefiltersmap, for example:{"query": "tech stack", "filters": {"user_id": "user_001"}, "limit": 10}.Top-level parameters with the same names (such as
user_idin V1/V2) are still accepted in V3 routes, but using thefiltersis recommended to align with the Mem0 v1.1 SDK.
Memory Operations (View / Update / Delete / Pin / Invalidate)
Operation | Method and Path | |||||||||||||||
List |
Example: optional parameter | |||||||||||||||
Details |
Example | |||||||||||||||
Update |
Example | |||||||||||||||
Delete |
Example: | |||||||||||||||
Pin / Unpin |
Example: | |||||||||||||||
Invalidate |
Example: | |||||||||||||||
History |
Example | |||||||||||||||
Statistics |
| |||||||||||||||
Clear (irreversible) |
Note Used in reset scenarios, irreversible. Both query and body must include Example Parameter Description
Response Example | |||||||||||||||
Feedback |
Note
Example Parameter Description
Response Example | |||||||||||||||
L2 source text |
Returns the original conversation messages (L2 level) that produced this L1 fact, for auditing or debugging purposes. Example Response Example | |||||||||||||||
V3 List |
Mem0 v1.1 SDK compatible, with entity filtering via request body and paginated envelope response support. Example
Response Example(bare JSON, no Box wrapper): | |||||||||||||||
L0 Entity Card Editing |
Partially updates an entity profile (only the provided fields are overwritten). Example
|
Custom Distillation Rules
Distillation rules (distill-prompt) control "what to extract from conversations and how to extract it", and can be configured per member without requiring OWNER permissions.
custom_prompt ≤ 8192 characters, defines only what to extract / how to extract, without changing the output JSON structure. OWNERs can use the Control Plane /ops/distill-prompt to set workspace-level default rules or rules for specific members.
Priority chain:
custom_instructions in ingest request>Member-level rules>Workspace default rules>Built-in defaults.Set member-level rules:
curl -X PUT "$HOST/v1/memories/distill-prompt" \ -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \ -d '{ "custom_prompt": "Focus on extracting tech stack selections and architecture decisions, ignore casual chat", "enabled": true }'Query current rules:
curl "$HOST/v1/memories/distill-prompt" -H "X-API-Key: $API_KEY"Delete rules(falls back to workspace default or built-in):
curl -X DELETE "$HOST/v1/memories/distill-prompt" -H "X-API-Key: $API_KEY"
Knowledge Base Management
Knowledge Base supports uploading documents with automatic parsing, chunking, vectorization, and indexing, and provides RAG retrieval with vector + BM25 + rerank fusion.
Create Knowledge Base
The response returns the Knowledge Base id(numeric type), which is used for subsequent uploads and searches.
curl -X POST "$HOST/v1/knowledge/bases" \
-H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
-d '{
"name": "Project Documentation Library",
"description": "Internal technical documentation and policies",
"visibility": "workspace"
}'Field | Required | Description |
| Yes | Name, ≤128 characters. |
| No | Description, ≤1024 characters. |
| No |
|
| No | Whether to enable knowledge graph indexing, default |
Manage Knowledge Bases
List Knowledge Bases:
curl "$HOST/v1/knowledge/bases?page=0&page_size=20" -H "X-API-Key: $API_KEY"Get a single knowledge base details:
curl "$HOST/v1/knowledge/bases/1" -H "X-API-Key: $API_KEY"Response:
{ "code": 0, "data": { "id": 1, "name": "Project Document Library", "description": "Internal technical documentation and policies", "visibility": "workspace", "document_count": 42, "graph_enabled": false, "created_at": "2026-07-01T00:00:00Z", "updated_at": "2026-08-15T12:00:00Z" } }Delete a knowledge base:
curl -X DELETE "$HOST/v1/knowledge/bases/1" -H "X-API-Key: $API_KEY"NoteOWNER can delete any knowledge base. USER can only delete private knowledge bases they created. Deletion cascades to all documents and indexes under the knowledge base.
Upload Documents (Formats + Limits + Three Methods)
Supported file formats
Documents: PDF, Markdown, Word, Excel, PPT, RTF, EPUB.
Images: PNG, JPG, etc. (Vision model automatically generates descriptions).
Audio: Common audio formats (automatic transcription).
Limits and mechanisms
Processing is asynchronous after upload. The API synchronously returns the document ID and
ingest_status, with status transitioning throughpending→indexed(failure results infailed+last_error).Idempotent deduplication: Re-uploading the same byte stream returns the existing document ID without duplicate ingestion.
After processing completes,
chunk_countis updated with the actual chunk count.
Upload methods
Multipart file upload
Knowledge base idis specified in the request path.
curl -X POST "$HOST/v1/knowledge/bases/1/documents/upload" \
-H "X-API-Key: $API_KEY" \
-F "file=@/path/to/runbook.pdf" \
-F "title=Deployment Runbook" \
-F "external_id=runbook-v2" \
-F "folder_path=/ops"When Markdown contains images, upload them together via the images field:
curl -X POST "$HOST/v1/knowledge/bases/1/documents/upload" \
-H "X-API-Key: $API_KEY" \
-F "file=@/path/to/guide.md" \
-F "title=Operations Guide" \
-F "images=@/path/to/screenshot1.png" \
-F "images=@/path/to/diagram.jpg"JSON text content submission
Suitable for programmatic synchronization. Supports chunking by external_id upsert.
curl -X POST "$HOST/v1/knowledge/documents" \
-H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
-d '{
"knowledge_base_id": 1,
"title": "Synced Document",
"external_id": "feishu-doc-001",
"content": "# Document Content\n..."
}'Console upload
On the Knowledge Base page in the console, select the target knowledge base, drag and drop or select files to upload, and visually monitor ingestion progress.
Manage documents
List documents:
curl "$HOST/v1/knowledge/bases/1/documents?page=0&size=20" -H "X-API-Key: $API_KEY"Get a single document details(including processing status):
curl "$HOST/v1/knowledge/documents/101" -H "X-API-Key: $API_KEY"Response:
{ "code": 0, "data": { "id": 101, "knowledge_base_id": 1, "title": "Deployment Runbook", "external_id": "runbook-v2", "ingest_status": "indexed", "chunk_count": 24, "source_type": "upload", "created_at": "2026-08-01T00:00:00Z", "updated_at": "2026-08-01T00:05:00Z" } }Noteingest_statusPossible values:pending→indexed(success) /failed(failure, includeslast_error).Delete a document:
curl -X DELETE "$HOST/v1/knowledge/documents/101" -H "X-API-Key: $API_KEY"NoteDeletion requires
editoror higher permissions. Corresponding chunk indexes are cleaned up synchronously.
Knowledge Recall
RAG retrieval: Vector + BM25 hybrid recall with reranking, returning matched chunks.
Example
curl -X POST "$HOST/v1/knowledge/search" \
-H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
-d '{
"query": "Docker deployment process",
"kb_ids": [1],
"top_k": 10
}'Parameter Description
Field | Required | Description |
| Yes | Query text. |
| Required for USER Key | Array of knowledge base IDs to search (note: plural form; singular |
| No | Number of results to return. Default 10, range [1, 100]. |
| No | BM25 vs. vector hybrid weight [0.0, 1.0]. |
| No | Whether to enable LLM query rewriting. |
Response example (partial)
{
"code": 0,
"data": [
{
"chunk_id": "chunk_42",
"document_id": "101",
"title": "Deployment Runbook",
"snippet": "Deployment process: 1. Prepare .env ... 2. Run ./deploy.sh ...",
"score": 0.91,
"rerank_score": 0.88
}
]
}The matched text is in the snippet field (not content), and the file name is in title.
Knowledge Review
When quality review is enabled, newly ingested document chunks are automatically scored, and low-scoring chunks enter the manual review queue.
Enable review:
curl -X PUT "$HOST/v1/knowledge/bases/1/settings" \ -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \ -d '{"review_enabled": true}'View review queue:
curl "$HOST/v1/knowledge/bases/1/reviews?status=pending_human&page=0&size=20" \ -H "X-API-Key: $API_KEY"Submit review decision(
ACCEPT_ORIGINAL/REJECT/RETRY):curl -X POST "$HOST/v1/knowledge/reviews/decision" \ -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \ -d '{"review_id": 42, "decision": "ACCEPT_ORIGINAL"}'Decision
Description
ACCEPT_ORIGINALApprove and activate the chunk
REJECTReject; the chunk remains non-retrievable
RETRYRe-score
NoteReview requires deployment-level workers to be enabled and the workspace feature toggle to be turned on; otherwise, it returns
FEATURE_DISABLED.
Wiki Knowledge Distillation
Wiki distillation refines knowledge base documents through LLM into structured Wiki pages (entities / concepts / summaries), complementing RAG — RAG returns chunk-level snippets, while Wiki returns page-level structured knowledge.
Enable Wiki distillation(Owner Key, Control Plane):
NoteOnce enabled, newly uploaded documents automatically trigger distillation. Existing documents are not retroactively processed; they can be manually triggered by re-distilling.
curl -X PUT "$HOST/ops/knowledge/wiki/config?kb_id=1" \ -H "X-API-Key: $OWNER_KEY" -H "Content-Type: application/json" \ -d '{ "wiki_enabled": true, "wiki_config": "{\"synthesis_model\":\"qwen-max\",\"extraction_granularity\":\"standard\"}" }'Search Wiki pages(Data Plane, BM25 retrieval):
curl -X POST "$HOST/v1/knowledge/wiki/search" \ -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \ -d '{ "query": "Kubernetes deployment process", "knowledge_base_ids": [1], "top_k": 5 }'Read full page content:
curl "$HOST/v1/knowledge/wiki/pages/42" -H "X-API-Key: $API_KEY"Wiki page types:
Type
Description
summaryDocument-level summary (one per document)
entityEntity (person / technology / product, etc.); multiple documents can contribute to the same entity
conceptConcept (method / principle / pattern, etc.)
indexWiki home page, automatically maintained by the system
Skill Catalog
The Skill Catalog allows Agents to dynamically discover available Skills at runtime and assemble them into context via the assemble endpoint. Skills support L0/L1/L2 progressive disclosure: L0 metadata → L1 summary → L2 full content.
Typical Agent flow: via search discover relevant Skills → retrieve content → assemble into context for execution. The assemble endpoint can also automatically include matching Skill content.
List skills:
Notepagestarts at 0;page_sizerange [1, 100], default 20.curl "$HOST/v1/skills?page=0&page_size=20" -H "X-API-Key: $API_KEY"Response example:
{ "code": 0, "data": { "content": [ { "id": 1, "name": "deploy-helper", "description": "Automated deployment process guide", "tags": ["devops", "docker"], "updated_at": "2026-08-10T00:00:00Z" } ], "totalElements": 5, "totalPages": 1 } }Search skills(semantic retrieval):
curl -X POST "$HOST/v1/skills/search" \ -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \ -d '{ "query": "Docker deployment", "top_k": 5, "tags": ["devops"] }'Parameter description:
Field
Required
Description
queryYes
Query text
top_kNo
Number of results to return. Default 10.
tagsNo
Filter by tags
Response example:
{ "code": 0, "data": [ {"id": 1, "name": "deploy-helper", "score": 0.92, "description": "Automated deployment process guide"} ] }Get full skill content(L2):
curl "$HOST/v1/skills/1/content" -H "X-API-Key: $API_KEY"Response example:
{ "code": 0, "data": { "id": 1, "name": "deploy-helper", "content": "# Deploy Helper\n\n## When to Use\n...\n## Steps\n..." } }
Session Management
A session is a container for short-term context. The complete Agent workflow = create session → append messages → assemble → close session. Each message has an auto-incrementing seq sequence number, supporting incremental fetching and reverse pagination.
Session operations quick reference
Operation | Method and Path |
Create |
|
List |
|
Details |
|
Update |
|
Append message |
|
Message list |
|
Close |
|
Delete |
|
Statistics |
|
Inheritance chain |
|
Create a session
Use external_id as the business-side session identifier (idempotent). Under the same user_id , repeated calls with the same external_id return the existing session.
curl -X POST "$HOST/v1/sessions" \
-H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
-d '{"external_id": "sess-2026-08-19-001", "agent_id": "coding-agent", "title": "Deployment Discussion", "user_id": "user_001"}'Request parameters
Field | Required | Description |
| Yes | External session identifier, ≤128 characters, idempotent under the same user. |
| No | Agent identifier, used to filter sessions by Agent. |
| No | Title, ≤256 characters. |
| No | End user identifier; automatically bound for USER Key. |
| No | Thread key for cross-session context inheritance. |
| No | Parent session |
Response Example
created=true indicates a new session. Under the same external_id , repeated calls return the existing session with created=false(idempotent).
{
"code": 0,
"data": {
"session": {
"id": 42,
"external_id": "sess-2026-08-19-001",
"agent_id": "coding-agent",
"title": "Deployment Discussion",
"status": "open",
"user_id": "user_001",
"message_count": 0,
"total_tokens": 0,
"created_at": "2026-08-19T10:00:00Z",
"updated_at": "2026-08-19T10:00:00Z"
},
"created": true
}
}List sessions
curl "$HOST/v1/sessions?page=0&page_size=20&status=open" \
-H "X-API-Key: $API_KEY"Request parameters
Parameters | Description |
| Page number (0-indexed), default 0. |
| Page size [1, 200], default 20. |
| Filter by Agent. |
| Filter by status: |
Pagination metadata is returned via response headers:X-Total-Count / X-Page / X-Page-Size / X-Has-More.
Get session details
curl "$HOST/v1/sessions/sess-2026-08-19-001" -H "X-API-Key: $API_KEY"Path parameter {id} can be the session's external_id or the database id. The response is the same as the create endpoint's session object.
Append messages to a session
curl -X POST "$HOST/v1/sessions/sess-2026-08-19-001/messages" \
-H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
-d '{"messages": [{"role": "user", "content": "How to deploy with Docker?"}, {"role": "assistant", "content": "We recommend using docker compose ..."}]}'Response Example
{
"code": 0,
"data": [
{"id": 101, "role": "user", "content": "How to deploy with Docker?", "seq": 1, "token_count": 12},
{"id": 102, "role": "assistant", "content": "We recommend using docker compose ...", "seq": 2, "token_count": 45}
]
}role Supports user / assistant / system / tool, where tool must be accompanied by tool_name.
Get session message list
curl "$HOST/v1/sessions/sess-2026-08-19-001/messages?since_seq=0&limit=50" \
-H "X-API-Key: $API_KEY"Request parameters
Parameters | Description |
| Incremental fetch: Returns seq > since_seq 's messages. |
| Reverse fetch: Returns seq < before_seq 's messages. |
| Sort order: |
| Number of results to return [1, 200], default 50. |
Response Example
{
"code": 0,
"msg": "ok",
"data": {
"items": [
{"id": 101, "role": "user", "content": "How to deploy with Docker?", "seq": 1, "token_count": 12},
{"id": 102, "role": "assistant", "content": "We recommend using docker compose ...", "seq": 2, "token_count": 45}
],
"total": 2
},
"trace_id": "550e8400-e29b-41d4-a716-446655440000"
}Close a session
curl -X PUT "$HOST/v1/sessions/sess-2026-08-19-001/close" \
-H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
-d '{"generate_summary": true}'Response Example
{
"code": 0,
"data": {
"id": 42,
"external_id": "sess-2026-08-19-001",
"status": "closed",
"closed_at": "2026-08-19T10:30:00Z"
}
}generate_summary=true(default) automatically generates a handoff summary for subsequent session inheritance. After closing, messages cannot be appended but remain readable.
Context Assembly
Context assembly is the most frequently called API for Agent invocations: it recalls relevant memories and knowledge based on the query, selects the best content within the token budget, and outputs a structured prompt_blocks, ready to be inserted directly into the system prompt.
Basic usage
curl -X POST "$HOST/v1/context/assemble" \
-H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
-d '{
"session_id": "sess_789",
"user_id": "user_001",
"query": "How to deploy the application?",
"token_budget": 4000,
"recall": {"top_k": 8}
}'session_id and user_id must have at least one filled in (otherwise workspace-wide recall is prohibited).query An empty query triggers zero-query cold start.
Recall configuration
Field | Description |
| Output token budget [1, 32000], default 32000. Never exceeds the budget. |
| Number of results to recall [1, 50]. |
| Minimum similarity threshold [0, 1], default 0.3. |
| Assembly scope: |
| Boolean to force-enable or disable a single dimension (takes effect after scope). |
| List of knowledge base IDs to recall from. |
| Budget allocation ratios: |
context_scope Presets:
Value | Included dimensions | Typical scenario |
| System instructions + recent messages + memories + knowledge base. | General conversation |
| System instructions + recent messages. | Completion / formatting and other lightweight calls |
| System instructions + recent messages + memory. | Scenario without knowledge base |
| System instructions + recent messages + knowledge base. | RAG Q&A |
Response structure
Concatenate prompt_blocks 's content into the system prompt in order. The backend selects by importance within the budget and never exceeds it. token_budget.
{
"code": 0,
"data": {
"prompt_blocks": [
{"role": "system", "tag": "user_profile", "content": "User prefers TypeScript + Prisma", "tokens": 30, "sources": []},
{"role": "system", "tag": "knowledge", "content": "Deployment process: 1. Prepare .env ...", "tokens": 120, "sources": ["runbook.pdf"]},
{"role": "user", "tag": "recent_messages", "content": "User: I want to deploy with Docker ...", "tokens": 80, "sources": []}
],
"token_used": 255,
"token_budget": 4000,
"trace_id": "550e8400-...",
"stats": {"recall_total": 12, "recall_kept": 8, "took_ms": 142}
}
}Compact Context
Proactively trigger incremental summary compression for long conversations, folding the earliest active messages into leaf summaries to reduce the total message count while preserving semantics.
curl -X POST "$HOST/v1/context/compact" \
-H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
-d '{
"session_id": "sess-2026-08-19-001",
"keep_recent_n": 50,
"chunk_size": 20
}'Parameter Description
Field | Required | Description |
| Yes | The external_id of the conversation |
| No | Number of recent active messages to retain. Default: 50, range: [1,500] |
| No | Number of messages to fold per call. Default: 20, range: [5,200] |
Response Example
{
"code": 0,
"data": {
"session_id": "sess-2026-08-19-001",
"compacted_message_count": 20,
"summary_token_count": 180,
"active_message_count": 50
}
}Make multiple calls for multi-leaf incremental compression, rather than compressing all old messages into a single summary at once.keep_recent_n Default 50 [1,500],chunk_size Default 20 [5,200].
Flush Context
Persist short-term context as long-term memory after a conversation ends. Flush first performs a compact, then sets the conversation status to flushed, and triggers a memory distillation event.
curl -X POST "$HOST/v1/context/flush" \
-H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
-d '{
"session_id": "sess-2026-08-19-001",
"compact_first": true,
"keep_recent_n": 20
}'Parameter Description
Field | Required | Description |
| Yes | The external_id of the conversation |
| No | Whether to compact before flush. Default: |
| No | Number of recent messages to retain during compact. Default: 20 |
Response Example
{
"code": 0,
"data": {
"session_id": "sess-2026-08-19-001",
"status": "flushed",
"flushed_at": "2026-08-19T10:35:00Z",
"evolve_event_id": 1001
}
}compact + flush + assemble are the three core operations of the context lifecycle: assemble reads, compact compresses, and flush persists.
Idempotency: flushing an already flushed conversation returns the existing status instead of an error.
Context Lifecycle
POST /v1/context/lifecycle By action drive the conversation state machine:
action=start: Create or open a conversation and return the first-screen assembled PromptBlock (equivalent to a combined
POST /v1/sessions+POST /v1/context/assemblecall).-- start -- Create conversation + first-screen assembly curl -X POST "$HOST/v1/context/lifecycle" \ -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \ -d '{ "action": "start", "session": {"external_id": "sess-2026-08-20-001", "user_id": "user_001", "agent_id": "coding-agent"}, "query": "Continue our previous discussion", "token_budget": 4096 }'action=end: Close the conversation and return closing statistics (equivalent to a
PUT /v1/sessions/{id}/close+POST /v1/context/flushcall).-- end -- Close conversation + flush curl -X POST "$HOST/v1/context/lifecycle" \ -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \ -d '{"action": "end", "session_id": "sess-2026-08-20-001", "user_id": "user_001"}'
Parameter Description
Field | Required | Description |
| Yes |
|
| Required for start | New session metadata ( |
| Required for end | Session ID |
| No |
|
| No |
|
| No |
|
action=start Response structure is the same as assemble, including prompt_blocks / token_used / stats; action=end Returns message_count / total_tokens / event_id.
Dialectic Analysis
POST /v1/context/dialectic Perform multi-perspective dialectic analysis on context recall results, outputting structured evidence and judgments. Requires session_id or user_id , at least one must be provided.
Example
curl -X POST "$HOST/v1/context/dialectic" \
-H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
-d '{
"query": "What are the pros and cons of Rust's ownership model?",
"user_id": "user_001",
"depth": "standard",
"top_k": 5
}'Parameter Description
Field | Required | Description |
| Yes | Query text |
| Condition | and |
| Condition | and |
| No | Analysis depth: |
| No | Return top-k [1,20], default 5 |
In the response, prompt_blocks has the same structure as assemble, with additional hits_count(recall hit count) and latency_ms(elapsed time).
Memory Promotion
Memory Promotion bridges the memory system and the knowledge base system: it automatically discovers high-value memory clusters, has an Agent synthesize Markdown knowledge documents, routes them through human review, and ingests them as knowledge base documents, forming a closed-loop evolution from "memory to knowledge."
Feature description
The state transitions of a Promotion:
generate (manual) / auto-nomination
|
v
generating --synthesis success--> pending_review --approve--> approved (ingested)
| |
synthesis failed reject
v v
generation_failed rejectedStatus | Meaning |
| Enqueued; the Agent is retrieving evidence and synthesizing the document. |
| Synthesis complete; awaiting human review. |
| Successfully ingested; knowledge base document created. |
| Review rejected. |
| Synthesis failed. |
Must be enabled on the deployment side context.promotion.enabled=true(disabled by default). When enabled, the system periodically auto-discovers hot memory clusters and creates promotion tickets; it can also be initiated manually.
Procedure
The following examples use theOwner Key. The Data Plane (initiate / query) also supports USER Keys (operating on own members only).
Manually initiate a promotion (async enqueue):
curl -X POST "$HOST/ops/promotion/generate" \ -H "X-API-Key: $OWNER_KEY" -H "Content-Type: application/json" \ -d '{"topic": "Project deployment process", "target_member_id": 10}'Poll the list and wait for the status to change to
pending_review:curl "$HOST/ops/promotion/list?status=pending_review&page=0&pageSize=20" \ -H "X-API-Key: $OWNER_KEY"View details to confirm the content and doubts:
curl "$HOST/ops/promotion/detail?promotionId=101" -H "X-API-Key: $OWNER_KEY"(Optional) Resolve doubts: If the Agent encounters conflicting evidence during synthesis, it lists pending doubts in the
doubtsfield. Providingresolutionstriggers re-synthesis:curl -X POST "$HOST/ops/promotion/resolve-doubts" \ -H "X-API-Key: $OWNER_KEY" -H "Content-Type: application/json" \ -d '{ "promotion_id": 101, "resolutions": [{"doubt_title": "Deployment environment", "chosen_value": "prod"}] }'Approve and write to the knowledge base:
curl -X POST "$HOST/ops/promotion/approve" \ -H "X-API-Key: $OWNER_KEY" -H "Content-Type: application/json" \ -d '{"promotion_id": 101, "knowledge_base_id": 5}'orReject:
curl -X POST "$HOST/ops/promotion/reject" \ -H "X-API-Key: $OWNER_KEY" -H "Content-Type: application/json" \ -d '{"promotion_id": 101, "reason": "Content duplicates existing knowledge base entries"}'
After approval, a Markdown document is created in the target knowledge base (source=memory_promotion). The above review operations can also be completed visually on the Memory Promotion page in the console.
Workspace management
Workspace management operations use theOwner Keyand can be completed visually in the console or via API calls.
Owner Key vs Admin Key's Control Plane responsibilities:
Owner KeyHandles single-Workspace-level management (member management, Key management, Wiki configuration, promotion review, and other
/ops/...endpoints)Admin KeyHandles platform-level global management (creating Workspaces, issuing/revokingOwner Keyand other global endpoints). Do not mix them.
Members and permissions
List members:
curl "$HOST/ops/workspaces/members?workspaceId=1" -H "X-API-Key: $OWNER_KEY"Create a member:
curl -X POST "$HOST/ops/workspaces/members" \ -H "X-API-Key: $OWNER_KEY" -H "Content-Type: application/json" \ -d '{"workspace_id": 1, "user_id": "agent_tech", "name": "Tech Agent", "role": "member"}'NoteRole enum values (lowercase):
owner,admin,viewer,member.ownerhas full workspace permissions;membercan only access own memory.Other APIs:
Update:
PATCH /ops/workspaces/membersDelete:
DELETE /ops/workspaces/members
API Key management
Issue a USER Key for a member:
curl -X POST "$HOST/ops/workspaces/members/keys" \ -H "X-API-Key: $OWNER_KEY" -H "Content-Type: application/json" \ -d '{"workspace_id": 1, "member_id": 10, "key_type": "USER"}'Response example:
Warningplain_keyis returned only once; save it immediately. You can revoke it at any time if suspicious activity is detected, and a stolen Key becomes invalid immediately.{"id": 42, "key_prefix": "ctx_9f3a", "key_type": "USER", "plain_key": "ctx_user_xxx..."}List Keys (excluding plaintext values):
curl "$HOST/ops/workspaces/members/keys?workspaceId=1" -H "X-API-Key: $OWNER_KEY"Revoke a Key(revoked Keys become invalid cluster-wide within 30 seconds):
curl -X POST "$HOST/ops/workspaces/members/keys/revoke" \ -H "X-API-Key: $OWNER_KEY" -H "Content-Type: application/json" \ -d '{"workspace_id": 1, "id": 42}'
Usage monitoring
Memory statistics:
curl "$HOST/v1/memories/stats?user_id=user_001" -H "X-API-Key: $API_KEY"Workspace overview(Owner Key):
curl "$HOST/ops/overview/summary" -H "X-API-Key: $OWNER_KEY"Response Example
{ "memory_total": 12800, "active_sessions": 42, "queue_depth": 3, "token_saved_estimate": 1250000 }Token usage and quotas:
# Monthly usage snapshot curl "$HOST/ops/quota/usage" -H "X-API-Key: $OWNER_KEY" # Current quota (dimension: workspace / member) curl "$HOST/ops/quota/current?dimension=workspace" -H "X-API-Key: $OWNER_KEY"NoteUsage, token economics, and API call trends can also be viewed as charts on the Usage page in the console.
Audit logs
Every API call records workspace_id + member_id + action + path + result, retained for 30 days by default.
Retrieve audit logs:
curl "$HOST/v1/audit/logs?action=MEMORY_ADD&result=success&from=2026-07-01T00:00:00Z&size=20" \ -H "X-API-Key: $OWNER_KEY"Response example (partial):
{ "id": 9001, "workspace_id": 1, "action": "MEMORY_ADD", "subject_type": "user", "subject_id": "10", "result": "success", "path": "/v1/memories", "created_at": "2026-07-01T10:01:00Z" }Statistics by dimension:
curl "$HOST/v1/audit/stats?group_by=action" -H "X-API-Key: $OWNER_KEY"NoteUse the following to get single-record details:
GET /v1/audit/logs/{id}. Audit logs can also be searched on the Audit page in the console by action / result / time range.
Related documentation
For complete API field reference, see the API Reference.