Skip to content

TypeScript SDK Reference

Official TypeScript SDK for Identity OS with full type safety and async-first design.

Installation

npm install @identity-os/sdk
# or
yarn add @identity-os/sdk

Quick Start

import { IdentityOS, Mode } from "@identity-os/sdk";

// Initialize client
const client = new IdentityOS({
  apiKey: "idos_sk_xxx"
});

// Create instance
const instance = await client.instances.create({
  name: "Aria"
});

// Process observation
const result = await client.engine.process(instance.id, {
  modeTarget: Mode.EXPLORATION,
  signalStrength: 0.8,
  confidence: 0.9
});

// Read contract
console.log(result.contract.allowedActions);

Client Initialization

Standard

import { IdentityOS } from "@identity-os/sdk";

const client = new IdentityOS({
  apiKey: "idos_sk_xxx"
});

Custom Base URL (Local Docker)

const client = new IdentityOS({
  apiKey: "",  // Not needed for local
  baseUrl: "http://localhost:8000/v1"
});

With Options

const client = new IdentityOS({
  apiKey: "idos_sk_xxx",
  baseUrl: "https://api.identity-os.dev/v1",
  timeout: 30000,  // milliseconds
  retries: 3
});

Instances

Create

const instance = await client.instances.create({
  name: "Aria",
  description: "Research assistant",
  initialConfig: {
    modeStrengths: {
      perception: 0.50,
      exploration: 0.50,
      order: 0.50,
      assertion: 0.50,
      connection: 0.50,
      identity: 0.50,
      stressResponse: 0.50
    },
    energyLevel: 0.8
  }
});

console.log(instance.id);       // inst_9f190826e20c49ea
console.log(instance.name);     // Aria
console.log(instance.createdAt);

List

// Get first page
const page = await client.instances.list({
  limit: 50,
  offset: 0
});

console.log(`Total: ${page.pagination.total}`);

// Iterate through pages
let offset = 0;
while (true) {
  const batch = await client.instances.list({
    limit: 100,
    offset
  });

  for (const inst of batch.data) {
    console.log(inst.name);
  }

  if (!batch.pagination.hasMore) break;
  offset += 100;
}

Get

const instance = await client.instances.get("inst_9f190826e20c49ea");

console.log(`Cycles: ${instance.cycleCount}`);
console.log(`Energy: ${instance.energyLevel}`);

Update

const updated = await client.instances.update("inst_9f190826e20c49ea", {
  name: "Aria v2",
  description: "Senior research assistant"
});

Delete

await client.instances.delete("inst_9f190826e20c49ea");

Engine

Process

import { Mode } from "@identity-os/sdk";

const result = await client.engine.process(
  "inst_xxx",
  {
    modeTarget: Mode.EXPLORATION,
    signalStrength: 0.8,
    confidence: 0.9,
    context: { task: "research" }
  }
);

// Access results
const { contract, snapshot, drift } = result;

console.log(`Allowed: ${contract.allowedActions}`);
console.log(`Stress: ${contract.stressState}`);
console.log(`Energy: ${contract.energyLevel}`);
console.log(`Dominant modes: ${contract.dominantModes}`);

Batch Process

const result = await client.engine.processBatch(
  "inst_xxx",
  {
    observations: [
      { modeTarget: Mode.EXPLORATION, signalStrength: 0.8 },
      { modeTarget: Mode.ORDER, signalStrength: 0.7 },
      { modeTarget: Mode.ASSERTION, signalStrength: 0.6 }
    ],
    includeIntermediate: false
  }
);

console.log(`Processed ${result.processedCount} observations`);
console.log(`Final contract: ${JSON.stringify(result.contract)}`);

Get Snapshot

const snapshot = await client.engine.getSnapshot("inst_xxx");

console.log(`Cycle: ${snapshot.cycle}`);
console.log(`Modes: ${JSON.stringify(snapshot.modeStrengths)}`);
console.log(`Stress: ${snapshot.stressState}`);
console.log(`Energy: ${snapshot.energyLevel}`);
console.log(`Stability: ${snapshot.stabilityIndex}`);

Get Contract

const contract = await client.engine.getContract("inst_xxx");

if (contract.allowedActions.includes("execute")) {
  console.log("Can execute");
}

console.log(`Decision tempo: ${contract.decisionStyle.tempo}`);
console.log(`Risk tolerance: ${contract.decisionStyle.risk}`);

Get History

const history = await client.engine.getHistory("inst_xxx", {
  limit: 100
});

for (const obs of history.data) {
  console.log(`Cycle ${obs.cycle}: ${obs.modeTarget}`);
}

Get Drift

const driftEvents = await client.engine.getDrift("inst_xxx");

for (const event of driftEvents.data) {
  console.log(`Cycle ${event.cycle}: ${event.driftLevel}`);
  if (event.rolledBack) {
    console.log("  → Auto-rolled back");
  }
}

Reset

// Reset to initial state
await client.engine.reset("inst_xxx", { resetTo: "initial" });

// Reset to last stable snapshot
await client.engine.reset("inst_xxx", { resetTo: "lastSnapshot" });

Personas

List

const personas = await client.personas.list();

for (const persona of personas.data) {
  console.log(`${persona.name}: ${persona.archetype}`);
}

Get

const persona = await client.personas.get("persona_analytical");

console.log(`Name: ${persona.name}`);
console.log(`Values: ${persona.coreValues}`);
console.log(`Mode profile: ${JSON.stringify(persona.modeProfile)}`);
console.log(`Preferred actions: ${persona.preferredActions}`);

Testing

Get Questions

const questions = await client.test.getQuestions({ version: "v1" });

for (const q of questions.data.questions) {
  console.log(`${q.id}: ${q.text}`);
  for (const opt of q.options) {
    console.log(`  - ${opt.text}`);
  }
}

Submit Test

const result = await client.test.submit({
  instanceId: "inst_xxx",
  responses: [
    { questionId: "q1", selectedOptionId: "q1_b" },
    { questionId: "q2", selectedOptionId: "q2_d" }
  ]
});

console.log(`Matched personas: ${result.matchedPersonas}`);
console.log(`Mode profile: ${JSON.stringify(result.modeProfile)}`);
console.log(`Contract: ${JSON.stringify(result.contract)}`);

Or create new instance:

const result = await client.test.submit({
  createInstance: true,
  instanceName: "NewAgent",
  responses: [...]
});

console.log(`Created: ${result.instanceId}`);

Types

Enums

import { Mode, StressState } from "@identity-os/sdk";

// Modes
Mode.PERCEPTION
Mode.EXPLORATION
Mode.ORDER
Mode.ASSERTION
Mode.CONNECTION
Mode.IDENTITY
Mode.STRESS_RESPONSE

// Stress states
StressState.LOW
StressState.MED
StressState.HIGH
StressState.OVER

Key Interfaces

import {
  Instance,
  IdentitySnapshot,
  ExecutionContract,
  ProcessResult,
  Persona,
  TestResult
} from "@identity-os/sdk";

// All interfaces have full TypeScript support
// IDE autocompletion available
// Full type safety

Error Handling

import {
  IdentityOSError,
  AuthenticationError,
  NotFoundError
} from "@identity-os/sdk";

try {
  const instance = await client.instances.get("invalid_id");
} catch (error) {
  if (error instanceof NotFoundError) {
    console.log("Instance not found");
  } else if (error instanceof AuthenticationError) {
    console.log("Invalid API key");
  } else if (error instanceof IdentityOSError) {
    console.log(`API error: ${error.message}`);
  }
}

Async/Await

All SDK methods are async and return Promises:

// Using async/await
async function example() {
  const instance = await client.instances.create({ name: "Bot" });
  const result = await client.engine.process(instance.id, {
    modeTarget: Mode.EXPLORATION,
    signalStrength: 0.8
  });
  return result;
}

// Using .then()
client.instances.create({ name: "Bot" })
  .then(instance => client.engine.process(instance.id, { ... }))
  .then(result => console.log(result))
  .catch(error => console.error(error));

// Using Promise.all() for parallel operations
const results = await Promise.all([
  client.instances.get("inst_1"),
  client.instances.get("inst_2"),
  client.instances.get("inst_3")
]);

Bulk Operations

// Create multiple instances
const instances = await Promise.all(
  Array.from({ length: 10 }, (_, i) =>
    client.instances.create({
      name: `Agent-${i}`,
      description: "Bulk created"
    })
  )
);

// Process multiple observations in batch
const result = await client.engine.processBatch(instances[0].id, {
  observations: [
    { modeTarget: Mode.EXPLORATION, signalStrength: 0.8 },
    { modeTarget: Mode.ORDER, signalStrength: 0.7 },
    { modeTarget: Mode.ASSERTION, signalStrength: 0.6 }
  ]
});

// List all with pagination
const allInstances: Instance[] = [];
let offset = 0;
while (true) {
  const batch = await client.instances.list({
    limit: 100,
    offset
  });
  allInstances.push(...batch.data);
  if (!batch.pagination.hasMore) break;
  offset += 100;
}

Environment Variables

# Can also use environment variables
export IDENTITY_OS_API_KEY="idos_sk_xxx"
export IDENTITY_OS_BASE_URL="https://api.identity-os.dev/v1"

Then:

const client = new IdentityOS();  // Reads from env vars

Logging

const client = new IdentityOS({
  apiKey: "idos_sk_xxx",
  debug: true  // Enable debug logging
});

// Log requests and responses
// Set process.env.DEBUG="identity-os:*" for verbose output

Common Patterns

Pattern: Monitor Agent Health

async function monitorAgent(instanceId: string) {
  const snapshot = await client.engine.getSnapshot(instanceId);
  const contract = await client.engine.getContract(instanceId);

  return {
    stress: snapshot.stressState,
    energy: snapshot.energyLevel,
    stability: snapshot.stabilityIndex,
    cycles: snapshot.cycleCount,
    allowedActions: contract.allowedActions,
    decisionStyle: contract.decisionStyle
  };
}

const health = await monitorAgent("inst_xxx");
console.log(health);

Pattern: Adaptive Decision Making

async function decideWithConstraints(
  options: string[],
  instanceId: string
): Promise<string> {
  const contract = await client.engine.getContract(instanceId);

  // Filter by allowed actions
  const available = options.filter(
    o => contract.allowedActions.includes(o)
  );

  if (available.length === 0) {
    return "defer";  // Safe fallback
  }

  // Apply decision style
  if (contract.decisionStyle.tempo === "decisive") {
    return available[0];  // First option
  } else {
    return bestOption(available);  // Best option
  }
}

const choice = await decideWithConstraints(
  ["explore", "execute", "defer"],
  "inst_xxx"
);

Pattern: React Component with Contract

import React, { useState, useEffect } from "react";
import { IdentityOS, ExecutionContract } from "@identity-os/sdk";

function AgentComponent({ instanceId }: { instanceId: string }) {
  const [contract, setContract] = useState<ExecutionContract | null>(null);
  const [loading, setLoading] = useState(true);
  const client = new IdentityOS({ apiKey: process.env.REACT_APP_API_KEY });

  useEffect(() => {
    async function load() {
      const c = await client.engine.getContract(instanceId);
      setContract(c);
      setLoading(false);
    }
    load();
  }, [instanceId]);

  if (loading) return <div>Loading...</div>;
  if (!contract) return <div>Error</div>;

  return (
    <div>
      <h2>Agent Status</h2>
      <p>Stress: {contract.stressState}</p>
      <p>Energy: {(contract.energyLevel * 100).toFixed(0)}%</p>
      <ul>
        {contract.allowedActions.map(action => (
          <li key={action}>{action}</li>
        ))}
      </ul>
    </div>
  );
}

export default AgentComponent;

Rate Limiting

import { RateLimitError } from "@identity-os/sdk";

async function processWithRetry(
  fn: () => Promise<any>,
  maxRetries = 3
): Promise<any> {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn();
    } catch (error) {
      if (error instanceof RateLimitError) {
        const waitMs = error.retryAfter * 1000;
        console.log(`Rate limited, waiting ${waitMs}ms`);
        await new Promise(resolve => setTimeout(resolve, waitMs));
      } else {
        throw error;
      }
    }
  }
}

// Usage
const result = await processWithRetry(() =>
  client.engine.process("inst_xxx", { ... })
);

TypeScript Configuration

Ensure your tsconfig.json includes:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "lib": ["ES2020"],
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  }
}

Reference