CognitiveX Docs

SDK

The @cognitivx/sdk TypeScript client for the CognitiveX / iCog API — recall, remember, talk, and account management with typed namespaces.

@cognitivx/sdk is a typed TypeScript client for the CognitiveX / iCog API at https://api.cognitivx.io. It is a thin, fully typed wrapper over fetch: each endpoint is a small function that returns a typed Promise, grouped into namespaces (memory, auth, billing, and so on). There is no class to instantiate. You configure one shared client, then call namespace functions.

The same package powers the CognitiveX web surfaces, so the types you import are the types the product runs on.

Looking for the command line? That is a separate package, @cognitivx/cli (binary cogx, version 1.2.0). See the CLI guide.

Install

pnpm add @cognitivx/sdk

Initialise

For server-side or programmatic use, configure the client once with an API key. The key is sent as Authorization: Bearer <key> on every request, and the browser cookie refresh flow is disabled (there is no .cognitivx.io cookie outside the browser).

import { configureApiClient } from '@cognitivx/sdk';

configureApiClient({
  apiKey: process.env.ICOG_API_KEY, // an `icog_...` key
});

Create keys at developers.cognitivx.io/keys. A key is shown only once; keep it server-side.

configureApiClient accepts:

OptionTypeDefaultDescription
apiKeystring | nullunsetPersonal API key. Sent as a Bearer token; disables cookie refresh. null clears it.
orgIdstring | nullunsetActive organization id, sent as X-Org-ID on every request. null clears it.
baseUrlstringhttps://api.cognitivx.ioOverride the API origin (for staging or a self-hosted instance).
fetchImpltypeof fetchglobal fetchCustom fetch implementation (e.g. for a runtime without a global).

In the browser, you do not pass an apiKey. The web app authenticates with an HttpOnly refresh cookie set by api.cognitivx.io, and the client transparently refreshes the access token on a 401 and replays the request once. With an API key configured, that refresh is skipped and a 401 surfaces directly.

Your first round trip

Write a memory, then read it back. Every namespace function returns a typed result you can await directly.

import { configureApiClient, memory } from '@cognitivx/sdk';

configureApiClient({ apiKey: process.env.ICOG_API_KEY });

// Store a fact. memory_type is one of: semantic, episodic, procedural, foundational.
const { memory_id } = await memory.remember({
  content: 'The user prefers dark mode and TypeScript.',
  memory_type: 'semantic',
});

// Read it back with semantic search.
const { memories, count } = await memory.recall({
  query: 'user preferences',
  limit: 5,
});

console.log(count, memories[0]?.text);
# Remember
curl -X POST https://api.cognitivx.io/api/remember \
  -H "Authorization: Bearer $ICOG_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"content":"The user prefers dark mode and TypeScript.","memory_type":"semantic"}'

# Recall
curl -X POST https://api.cognitivx.io/api/recall \
  -H "Authorization: Bearer $ICOG_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"query":"user preferences","limit":5}'

A recall response looks like:

{
  "count": 1,
  "memories": [
    {
      "id": "f3c1...",
      "text": "The user prefers dark mode and TypeScript.",
      "memory_type": "semantic",
      "age_days": 0,
      "created_at": "2026-06-16T09:12:44Z",
      "occurred_at": null,
      "occurred_at_end": null,
      "occurred_precision": null,
      "similarity": 0.83,
      "temporal_context": null
    }
  ]
}

remember and update require the awakened tier or above. recall and talk work on any tier. See billing for how to read the current tier.

Error handling

Any non-2xx response throws an ApiError. It carries the HTTP status, a human-readable message (taken from the API's detail or message field), and the raw parsed body so you can inspect structured error payloads.

import { configureApiClient, memory, ApiError } from '@cognitivx/sdk';

configureApiClient({ apiKey: process.env.ICOG_API_KEY });

try {
  await memory.remember({ content: 'A new fact.', memory_type: 'semantic' });
} catch (err) {
  if (err instanceof ApiError) {
    if (err.status === 401) {
      // Missing or invalid API key.
    } else if (err.status === 402 || err.status === 403) {
      // Tier or quota gate (e.g. remember requires `awakened`+).
      console.error(err.message, err.body);
    } else {
      throw err;
    }
  } else {
    throw err; // network or non-HTTP failure
  }
}

ApiError shape:

PropertyTypeDescription
statusnumberHTTP status code of the failed response.
messagestringThe API's detail/message, or Request failed: <status>.
bodyunknownThe raw parsed response body (JSON object or text).

Common statuses you will handle across endpoints:

StatusWhen
401Missing, malformed, or revoked key (no Bearer token / invalid icog_...).
402 / 403Tier or capability gate (e.g. remember below awakened, admin-only org actions).
404The addressed resource (memory id, org, device, invite) does not exist.
422Request body failed validation (missing field, wrong type, out of range).
429Rate or quota limit reached.

Namespaces

Import any namespace by name. Each is a flat group of functions over one part of the API.

NamespaceMounted atWhat it covers
memory/apiThe cognitive surface: recall, remember, forget, update, learn, talk, reflect.
memories/api/memoriesCRUD and search over stored memories: list, get, search, remove, counts.
auth/api/authBrowser session flows: signup, signin, signout, password reset, OAuth, handoff.
me/api/auth/meget() the current authenticated user.
profile/api/profileget / update the user profile (display name, avatar).
keys/api/auth/api-keysPersonal API keys: list, create, revoke.
billing/api/billingTier, subscription, credits, PAYG balance and spend cap, checkout/portal.
usage/api/me/cognitionCognition observability: summary, timeline, engineState, precisionTrend.
senses/api/sensesThe multi-device registry (Mac, iPhone, Android): list, register, update, heartbeat, revoke.
orgs/api/orgsOrganizations: members, invites, org API keys, seats, billing, logo.

Below, the most-used namespaces are documented with method, path, parameters, and examples. The full per-function reference (every signature, interface, and field) is generated from source under Generated reference.

memory

The cognitive value surface: write to and read from your persistent memory, and converse with iCog directly. Auth: Authorization: Bearer <key> (or X-API-Key: <key>).

memory.remember

Store a new memory. POST /api/remember. Requires the awakened tier or above.

FieldTypeRequiredDescription
contentstringyesThe text to store.
memory_typestringnosemantic, episodic, procedural, or foundational.
agent_slugstringnoAttribute the memory to a named agent.
deepbooleannoRun deeper integration on write (slower, richer).
const { memory_id } = await memory.remember({
  content: 'Shipped the org-memory feature on 2026-06-14.',
  memory_type: 'episodic',
});

Response: { "memory_id": "f3c1..." }

memory.recall

Semantic search over your memories. POST /api/recall. Works on any tier.

FieldTypeRequiredDescription
querystringyesWhat to search for.
limitnumbernoMax results to return.
memory_typestringnoRestrict to one memory type.
temporalstringnoA temporal filter (e.g. a natural-language time window).
deepbooleannoRun a deeper, more thorough recall.
agent_slugstringnoScope recall to memories attributed to one agent.
const { memories, count } = await memory.recall({
  query: 'what did I ship last week',
  limit: 10,
});

Response: { memories: MemoryResult[], count: number } (see the JSON example above).

memory.talk

Converse with iCog directly. It recalls context and replies as a cognitive peer. POST /api/talk. A streaming variant exists at POST /api/talk/stream (SSE).

FieldTypeRequiredDescription
messagestringyesYour message to iCog.
current_taskstringnoYour declared topic. Pass it so iCog grounds in the right context.
agent_slugstringnoSpeak as / scope to a named agent.
scope_modestringnoControls how broadly iCog draws context.
const reply = await memory.talk({
  message: 'Should I retry on 5xx or fall back to a zero vector?',
  current_task: 'fixing intermittent 500s on remember',
});
console.log(reply.response, reply.context_used);

Response: { response: string, context_used: number, identity_proposal: object | null }

Other memory functions

FunctionMethod + pathPurpose
memory.forget(memoryId)POST /api/forgetSoft-delete a memory by id.
memory.update(memoryId, content)POST /api/updateReplace a memory's content (forget + re-embed). awakened+.
memory.learn(outcome, metadata?)POST /api/learnRecord a learning signal for iCog to integrate.
memory.reflect()GET /api/reflectiCog's self-assessment: consciousness level, memory count, narrative.

Errors: 401 (bad key), 402/403 (remember/update below awakened), 404 (forget/update on a missing id), 422 (validation).

memories

CRUD and search over stored memories, with pagination. Useful for building memory browsers and admin views.

FunctionMethod + pathPurpose
memories.list(params?)GET /api/memoriesList stored memories. Params: memory_type, limit, offset, sort (recent | relevance).
memories.get(memoryId)GET /api/memories/:idFetch a single stored memory.
memories.search(params)POST /api/memories/searchHybrid keyword + semantic search. Params: query, memory_type?, limit?.
memories.remove(memoryId)DELETE /api/memories/:idSoft-delete a stored memory.
memories.counts()GET /api/memories/countsMemory counts by type.
import { memories } from '@cognitivx/sdk';

const { memories: rows, total, has_more } = await memories.list({
  memory_type: 'episodic',
  limit: 20,
  sort: 'recent',
});

list and search return { memories: StoredMemory[], total: number, has_more: boolean }.

Errors: 401 (bad key), 404 (get/remove on a missing id), 422 (bad params).

keys

Personal API keys for programmatic and MCP access. Mounted at /api/auth/api-keys.

FunctionMethod + pathPurpose
keys.list()GET /api/auth/api-keysList your keys. The full key is never returned after creation.
keys.create(body)POST /api/auth/api-keysCreate a key. The full icog_... value is returned once, in key.
keys.revoke(id)DELETE /api/auth/api-keys/:idRevoke a key by id.
import { keys } from '@cognitivx/sdk';

const created = await keys.create({ name: 'ci-runner' });
console.log(created.key); // shown only once — store it now

create is the only call that returns the full key, in the key field. After that, only the key_prefix is visible. If you lose it, revoke and create a new one.

Errors: 401 (bad session/key), 404 (revoke on a missing id).

billing

Tier, subscription, credit balance, and pay-as-you-go (PAYG) controls. Mounted at /api/billing.

FunctionMethod + pathPurpose
billing.me()GET /api/billing/meCurrent tier, subscription, PAYG balance.
billing.balance()GET /api/billing/balanceCredit balance, low-balance / depleted flags.
billing.usage()GET /api/billing/usageThis month's usage counters and recall-credit breakdown.
billing.usageHistory(days?)GET /api/billing/usage-historyDaily usage history (default 30 days).
billing.tiers()GET /api/billing/tiersTier catalog / configuration.
billing.memoryCapacity()GET /api/billing/memory-capacityMemory capacity status.
billing.createCheckout(body)POST /api/billing/create-checkoutStart a Stripe Checkout for a subscription.
billing.createPortal()POST /api/billing/create-portalOpen the Stripe billing portal.
billing.changeInterval(body)POST /api/billing/change-intervalSwitch a subscription between monthly and annual.
billing.topup(body)POST /api/billing/topupOne-time PAYG top-up ($5–$500). Returns a client_secret.
billing.switchToPayg(body?)POST /api/billing/switch-to-paygCancel the subscription and move to PAYG.
billing.paygEstimate()GET /api/billing/payg-estimateEstimate PAYG cost vs. the current tier.
billing.getPaygCap()GET /api/billing/payg-capRead the self-set monthly PAYG spend cap.
billing.setPaygCap(body)PUT /api/billing/payg-capSet (or clear, with null) the monthly PAYG cap.
billing.paygTransactions(limit?)GET /api/billing/payg-transactionsRecent PAYG ledger transactions (default 30).
billing.verifyCheckout(body)POST /api/billing/verify-checkoutConfirm a completed Checkout activated the subscription.
import { billing } from '@cognitivx/sdk';

const status = await billing.me();
console.log(status.tier, status.payg_balance_usd);

billing.me() returns:

{
  "tier": "awakened",
  "subscription_status": "active",
  "trial_ends_at": null,
  "renewal_date": "2026-07-01",
  "subscription_interval": "monthly",
  "payg_eligible": true,
  "payg_balance_usd": 12.40,
  "payg_transactions_30d": 8
}

Errors: 401 (bad session/key), 402/403 (action not allowed on the current plan), 422 (e.g. top-up amount out of the $5–$500 range).

usage

Cognition observability — a read-only window onto the engine activity behind your memory. Mounted at /api/me/cognition.

FunctionMethod + pathPurpose
usage.summary()GET /api/me/cognition/summarySnapshot of cognitive-engine activity.
usage.timeline(days?)GET /api/me/cognition/timelinePer-engine event counts over the last days (1–30, default 7).
usage.engineState()GET /api/me/cognition/engine-stateWhich engines are enabled, and why.
usage.precisionTrend()GET /api/me/cognition/precision-trendPrecision / recall / F1 trend across recent evaluations.
import { usage } from '@cognitivx/sdk';

const recent = await usage.timeline(14);

Errors: 401 (bad key), 422 (days out of the 1–30 range).

senses

The multi-device registry: the Macs, phones, and other clients ("senses") attached to one account. Mounted at /api/senses.

FunctionMethod + pathPurpose
senses.list()GET /api/senses/devicesList this account's registered devices.
senses.register(body)POST /api/senses/devicesRegister or re-pair a device. Returns a one-time device_token.
senses.update(id, body)PATCH /api/senses/devices/:idRename a device or change its capabilities / metadata.
senses.heartbeat(id, status?)POST /api/senses/devices/:id/heartbeatPresence ping (90s online window) carrying small telemetry.
senses.revoke(id)DELETE /api/senses/devices/:idRevoke a device and invalidate its token.
import { senses } from '@cognitivx/sdk';

const device = await senses.register({
  device_type: 'mac',
  device_name: 'Parsa MacBook',
  device_uid: 'a-stable-per-install-id',
  capabilities: ['presence', 'voice'],
});
console.log(device.device_token); // shown only once — persist it

device_type is one of mac, iphone, android, ipad, web, watch. capabilities is a subset of presence, voice, location, motion, notifications, screen.

The device_token is returned only by register. Persist it on the device; it authenticates that device's later calls. If lost, revoke and re-register.

Errors: 401 (bad key), 404 (update/heartbeat/revoke on a missing id), 422 (bad device_type or capabilities).

orgs

Organizations — multi-user teams with isolated, shared memory. Mounted at /api/orgs. Most write actions require admin or owner role.

To scope recall / remember and other org-aware endpoints to an org's shared memory, set the active org. It is sent as the X-Org-ID header on every request.

import { configureApiClient, apiClient, orgs, memory } from '@cognitivx/sdk';

configureApiClient({ apiKey: process.env.ICOG_API_KEY });

// Set the active org for subsequent calls (X-Org-ID header).
apiClient.setActiveOrg('org_123'); // or: configureApiClient({ orgId: 'org_123' })

await memory.remember({ content: 'Team decision: ship behind a flag.', memory_type: 'semantic' });

apiClient.setActiveOrg(null); // back to personal memory

Selected functions:

FunctionMethod + pathRolePurpose
orgs.list()GET /api/orgsmemberOrgs you belong to (with your role, seats_used).
orgs.create(body)POST /api/orgs—Create an org (you become owner).
orgs.get(id)GET /api/orgs/:idmemberFetch one org.
orgs.update(id, body)PUT /api/orgs/:idadmin+Rename / change slug.
orgs.remove(id)DELETE /api/orgs/:idownerDelete an org.
orgs.listMembers(id)GET /api/orgs/:id/membersmemberList members.
orgs.invite(id, body)POST /api/orgs/:id/invitesadmin+Invite by email; returns invite_url.
orgs.acceptInvite(body)POST /api/orgs/invites/accept—Accept an invite by token.
orgs.listKeys(id) / createKey / revokeKey/api/orgs/:id/keysadmin+Org API keys (full key shown once, in key).
orgs.getSeats(id)GET /api/orgs/:id/seatsmemberSeat usage and billing summary.
orgs.createCheckout(id, body)POST /api/orgs/:id/checkoutownerStripe Checkout for seats.
orgs.getPricing()GET /api/orgs/pricingpublicPer-seat pricing.

The full set (member role updates, invite revocation, seat changes, GitHub authorize, logo upload/remove) is in the generated reference.

Errors: 401 (bad key), 403 (role too low for an admin/owner action), 404 (org / member / invite not found), 422 (validation).

Low-level client

Every namespace function calls apiClient under the hood. You can use it directly for endpoints not yet wrapped, or to set auth and org context.

MethodPurpose
apiClient.get/post/put/patch/delete<T>(path, ...)Issue a typed request to any path.
apiClient.setAccessToken(token)Set the in-memory access token (browser session flows).
apiClient.getAccessToken()Read the current access token.
apiClient.setActiveOrg(orgId)Set / clear the X-Org-ID header for org-scoped calls.
apiClient.getActiveOrg()Read the active org id.
apiClient.refresh()Manually refresh the access token from the browser cookie.
import { apiClient } from '@cognitivx/sdk';

// Call any endpoint, typed.
const me = await apiClient.get<{ id: string; email: string }>('/api/auth/me');

Next steps