JSPM

@egox/client

1.1.0
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 173
  • Score
    100M100P100Q61266F
  • License MIT

Official EgoX client SDK for Node.js - LLM orchestration made easy

Package Exports

  • @egox/client
  • @egox/client/express

Readme

@egox/client

Official EgoX Client SDK for Node.js - LLM orchestration made easy.

Installation

npm install @egox/client

Quick Start

import { EgoX } from '@egox/client';

const egox = new EgoX({
  apiKey: process.env.EGOX_API_KEY,    // egox_live_xxx or egox_test_xxx
  tenantId: process.env.EGOX_TENANT_ID,
});

const response = await egox.ask({
  message: 'What is the refund policy?',
});

console.log(response.answer);
console.log(`Tokens used: ${response.usage.totalTokens}`);

Features

  • Simple API - One method to interact with your AI assistant
  • Streaming - Token-by-token SSE via callback (askStream) or for-await (askStreamIter)
  • Trusted-header passthrough - Per-request headers field flows into EgoX's per-tool forwardHeaders allowlist
  • TypeScript First - Full type definitions included
  • Automatic Retries - Built-in retry logic with exponential backoff
  • Webhook Verification - Secure your tool endpoints with signature validation
  • Express Middleware - Drop-in middleware for webhook verification

Configuration

const egox = new EgoX({
  apiKey: 'egox_live_xxx',      // Required - Your EgoX API key
  tenantId: 'your-tenant-id',   // Required - Your tenant/project ID
  baseUrl: 'https://api.egox.io', // Optional - API base URL
  timeout: 30000,               // Optional - Request timeout (ms)
  retries: 2,                   // Optional - Number of retry attempts
});

Sending Messages

Basic Message

const response = await egox.ask({
  message: 'Hello, how can you help me?',
});

With Conversation Threading

// Start a new conversation
const first = await egox.ask({
  message: 'What is your return policy?',
  externalUserId: 'user-123', // Your user's ID
});

// Continue the conversation
const second = await egox.ask({
  message: 'What about electronics?',
  threadId: first.threadId, // Continue same thread
  externalUserId: 'user-123',
});

With Auth Token Forwarding

// Forward your user's auth token to your tools
const response = await egox.ask({
  message: 'Check my order status',
  authToken: 'user-jwt-token', // Forwarded to your tool endpoints
});

With Custom Metadata

const response = await egox.ask({
  message: 'Process refund for my order',
  metadata: {
    orderId: 'order-456',
    customerId: 'cust-789',
    internalTenantId: 'tenant-abc', // For multi-tenant setups
  },
});

With Per-Request Headers (forwardHeaders passthrough)

Pass extra HTTP headers on a single /ask call. EgoX captures every inbound header and forwards any name listed in the target tool's forwardHeaders allowlist verbatim to that tool's endpoint. Use this for trusted, server-set context — locale, app version, the authenticated user/tenant id when proxying through a gateway, A/B bucket, etc.

// Server-side (e.g. inside a GraphQL resolver) — caller already authenticated
const response = await egox.ask({
  message: 'Show my recent orders',
  externalUserId: ctx.user.id,
  headers: {
    'x-user-id':   ctx.user.id,        // trusted: injected from session
    'x-tenant-id': ctx.user.tenantId,  // (your app's tenant, not EgoX's)
    'x-locale':    ctx.user.locale,
    'x-app-version': req.get('x-app-version') ?? 'unknown',
  },
});

For these to actually reach the upstream tool, configure the tool's forwardHeaders allowlist in the EgoX console (or via MCP) to include the names you're sending.

SDK-reserved names are silently stripped: Authorization, Content-Type, Accept, X-API-Key, X-Tenant-Id, X-Request-Id, plus HTTP framing headers (Host, Content-Length, Transfer-Encoding, Connection). Use authToken instead of Authorization. The exhaustive list is exported as SDK_RESERVED_HEADERS if you want to validate ahead of time.

Streaming

EgoX streams events as it thinks, retrieves knowledge, calls tools, and generates text. Two consumption styles, pick whichever fits the call site.

Callback style (askStream)

await egox.askStream(
  {
    message: 'Walk me through resetting my password.',
    headers: { 'x-locale': 'en-US' },
  },
  {
    onEvent: (event) => {
      if (event.type === 'delta') process.stdout.write(event.content);
      if (event.type === 'tool.calling') console.log('\n→', event.name);
      if (event.type === 'done') console.log('\n[done]', event.usage);
    },
  },
);

Async-iterator style (askStreamIter)

Designed for GraphQL Subscription resolvers and any place where for await is more natural than registering a callback. Breaking out of the loop aborts the underlying SSE connection.

for await (const ev of egox.askStreamIter({
  message: 'Walk me through resetting my password.',
  headers: { 'x-locale': 'en-US' },
})) {
  switch (ev.type) {
    case 'delta':       yield { token: ev.content };           break;
    case 'tool.calling': yield { toolStart: ev.name };          break;
    case 'done':        yield { final: ev };                    return;
    case 'error':       throw new Error(ev.message);
  }
}

Pass an AbortSignal for external cancellation (e.g. WebSocket close, HTTP request aborted by the client):

const ctrl = new AbortController();
req.on('close', () => ctrl.abort());

for await (const ev of egox.askStreamIter(req.body, { signal: ctrl.signal })) {
  // ...
}

Response Object

interface AskResponse {
  threadId: string;              // Conversation thread ID
  answer: string;                // AI's response text
  intent: 'vanilla' | 'rag' | 'tools' | 'rag_tools';
  toolUsed: string | null;       // Tool name if one was called
  ragChunksUsed: number;         // Number of knowledge chunks used
  usage: {
    promptTokens: number;
    completionTokens: number;
    totalTokens: number;
  };
  model: string;                 // Model used (e.g., 'gpt-4.1')
}

Webhook Signature Verification

When EgoX calls your tool endpoints, it signs the request. Verify these signatures to ensure requests are authentic.

Using Express Middleware

import express from 'express';
import { createEgoXMiddleware } from '@egox/client/express';

const app = express();
app.use(express.json());

// Create middleware with your webhook secret
const verifyEgoX = createEgoXMiddleware({
  secret: process.env.EGOX_WEBHOOK_SECRET,
  tolerance: 300, // Optional: max age in seconds (default: 5 min)
});

// Apply to your tool routes
app.post('/api/tools/check-order', verifyEgoX, (req, res) => {
  // Request is verified - access metadata
  console.log(req.egox?.requestId);  // EgoX request ID
  console.log(req.egox?.tenantId);   // Tenant ID
  
  // Your tool logic...
  res.json({ status: 'Order shipped' });
});

Manual Verification

import { verifySignature, validateSignature } from '@egox/client';

// Option 1: Throws on invalid signature
try {
  verifySignature({
    signature: req.headers['x-egox-signature'],
    timestamp: req.headers['x-egox-timestamp'],
    body: JSON.stringify(req.body),
    secret: process.env.EGOX_WEBHOOK_SECRET,
  });
  // Signature is valid
} catch (error) {
  // Signature is invalid
  return res.status(401).json({ error: 'Invalid signature' });
}

// Option 2: Returns boolean
const isValid = validateSignature({
  signature: req.headers['x-egox-signature'],
  timestamp: req.headers['x-egox-timestamp'],
  body: JSON.stringify(req.body),
  secret: process.env.EGOX_WEBHOOK_SECRET,
});

Error Handling

import {
  EgoXError,
  AuthenticationError,
  ValidationError,
  NetworkError,
  TimeoutError,
  RateLimitError,
} from '@egox/client';

try {
  const response = await egox.ask({ message: 'Hello' });
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.log('Invalid API key');
  } else if (error instanceof ValidationError) {
    console.log('Invalid request:', error.message);
  } else if (error instanceof RateLimitError) {
    console.log(`Rate limited. Retry after ${error.retryAfter}s`);
  } else if (error instanceof TimeoutError) {
    console.log('Request timed out');
  } else if (error instanceof NetworkError) {
    console.log('Network error:', error.message);
  } else if (error instanceof EgoXError) {
    console.log(`API error: ${error.code} - ${error.message}`);
  }
}

Health Check

const isHealthy = await egox.ping();
if (!isHealthy) {
  console.log('EgoX API is not reachable');
}

Headers Sent by EgoX

When EgoX calls your tool endpoints, it includes these headers:

Header Description
X-EgoX-Signature HMAC-SHA256 signature (sha256=...)
X-EgoX-Timestamp Unix timestamp of the request
X-EgoX-Request-Id Unique request ID for debugging
X-EgoX-Tenant-Id Your tenant/project ID

TypeScript

Full TypeScript support with exported types:

import type {
  EgoXConfig,
  AskRequest,
  AskResponse,
  SignatureParams,
  ExpressMiddlewareOptions,
} from '@egox/client';

License

MIT