npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@context-server/sdk

v0.1.0

Published

Context SDK

Downloads

92

Readme

@context/sdk

TypeScript/JavaScript client for the Context API.

  • ✅ Node 18+ (built-in fetch, ESM/CJS)
  • ✅ First-class TypeScript types
  • ✅ Works in browsers (uses fetch/FormData)
  • ✅ Simple, promise-based API

Installation

# npm
npm i @context/sdk

# pnpm
pnpm add @context/sdk

# yarn
yarn add @context/sdk

Node version: 18 or newer.


Quick start

import { Context } from '@context/sdk'

const context = new Context({
  apiKey: process.env.CONTEXT_API_KEY!, // required
  // baseUrl is optional; see "Configuration"
  // baseUrl: 'http://localhost:4600',
})

const server = await context.getServer('ctx.ai')

const chat = await server.startChat('Hello 👋')
console.log(chat.answer)

await chat.send('Tell me more.')
console.log(chat.answer)

The SDK throws on non-2xx responses. Wrap calls in try/catch if you want to handle errors explicitly.


Configuration

new Context({
  apiKey: string;          // required
  baseUrl?: string;        // optional
})

Base URL tips

  • If you’re talking to a local Developer API:
    new Context({ apiKey: '…', baseUrl: 'http://localhost:4600' })
  • Or use an env var (recommended):
    export DEVELOPER_API_URL=http://localhost:4600
    export NO_PROXY=localhost,127.0.0.1,::1   # avoids proxies hijacking localhost
  • In the SDK, baseUrl can default to production; passing baseUrl or setting DEVELOPER_API_URL overrides it.

ESM, CJS & TypeScript

ESM / TypeScript (preferred)

import { Context } from '@context/sdk'

CommonJS

const { Context } = require('@context/sdk')

If your runner compiles to CJS, avoid top-level await (wrap in an async IIFE).


Servers

const server = await context.getServer('ctx.ai')

Chat

// Start a chat
const chat = await server.startChat('What is your expertise?')
console.log(chat.answer)

// Continue the chat
await chat.send('And what can you help me with today?')
console.log(chat.answer)

Knowledge Base (Documents)

Add a document (text)

const doc = await server.knowledge.add({
  name: 'Product Overview',
  content: 'Our product helps teams collaborate…',
  collection: 'public', // or 'private'
})

console.log('Document ID:', doc.id)
console.log('Status:', doc.status)
console.log('Is processing?', doc.isProcessing)

Upload a file (Node)

import fs from 'node:fs'

// Buffer or Readable stream are both supported
const uploaded = await server.knowledge.add({
  name: 'my-document.pdf',
  file: fs.readFileSync('./my-document.pdf'), // or fs.createReadStream(...)
  collection: 'public',
})

console.log(uploaded.id, uploaded.status)

Upload a file (browser)

const input = document.querySelector('input[type="file"]') as HTMLInputElement
const file = input.files?.[0]
if (!file) throw new Error('Pick a file first')

await server.knowledge.add({
  name: file.name,
  file, // File/Blob
  collection: 'public',
})

Refresh & access documents

// Refresh the cache from the server
await server.knowledge.load()

// Snapshot of all docs (from local cache)
const all = server.knowledge.documents
console.log('Total:', all.length)

// Get by ID (from cache)
const one = server.knowledge.get('doc-id-123')
if (one) {
  console.log(one.name, one.status)
}

// Find by name (from cache)
const found = server.knowledge.find('Product Overview')
console.log('Found?', !!found)

Filter by status / counts

const pending = server.knowledge.getByStatus('pending')
const running = server.knowledge.getByStatus('running')
const completed = server.knowledge.getByStatus('completed')
const failed = server.knowledge.getByStatus('failed')

console.log('Counts:', {
  pending: pending.length,
  running: running.length,
  completed: completed.length,
  failed: failed.length,
})

console.log('Total docs:', server.knowledge.count)

Track processing until done (polling example)

const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))

let doc = await server.knowledge.add({
  name: 'Large Report',
  content: 'Long content…',
  collection: 'public',
})

// Poll until terminal state
while (!doc.isComplete && !doc.isFailed) {
  await sleep(2000)
  await server.knowledge.load() // refresh cache from server
  const refreshed = server.knowledge.get(doc.id)
  if (!refreshed) throw new Error('Document disappeared from cache')
  doc = refreshed
  console.log('Status:', doc.status)
}

if (doc.isComplete) console.log('✓ Processing complete!')
else console.log('✗ Processing failed')

Delete documents

// By ID
await server.knowledge.del('doc-id-123')

// By Document instance
const doc = server.knowledge.get('doc-id-456')
if (doc) await server.knowledge.del(doc)

// Many at once
await server.knowledge.deleteMany(['id1', 'id2', 'id3'])

API surface (selected)

Context

  • constructor(options: { apiKey: string; baseUrl?: string })
  • getServer(name: string): Promise<Server>

Server

  • startChat(prompt: string): Promise<Chat>
  • knowledge: Knowledge

Knowledge

  • add(options: { name: string; content?: string; file?: File|Buffer; sourceUrl?: string; collection?: 'public'|'private' }): Promise<Document>
  • del(documentOrId: string | Document): Promise<void>
  • deleteMany(ids: string[]): Promise<void>
  • load(): Promise<Document[]>
  • get(documentId: string): Document | undefined
  • find(name: string): Document | undefined
  • getByStatus(s: 'pending' | 'running' | 'completed' | 'failed'): Document[]
  • documents: Document[] (getter, cache snapshot)
  • count: number (getter)

Document

  • Properties: id, name, status, sourceType, collectionType, task?
  • Helpers: isProcessing, isComplete, isFailed
  • Methods: update(options: { name?: string; content?: string }): Promise<void>

Chat

  • Properties: answer (last assistant message)
  • Methods: send(message: string): Promise<void>

Note: Some fields can be snake_case from the API; the SDK normalizes them to camelCase on the Document/Server objects.


Error handling

The SDK throws an Error on non-2xx responses and on network failures:

try {
  const server = await context.getServer('ctx.ai')
  const chat = await server.startChat('Hello')
  console.log(chat.answer)
} catch (err) {
  console.error('Request failed:', err instanceof Error ? err.message : String(err))
}

If you want a result-style helper:

async function result<T>(fn: () => Promise<T>) {
  try {
    return { ok: true as const, data: await fn() }
  } catch (e) {
    return { ok: false as const, error: e as Error }
  }
}

Browser notes

  • Use <input type="file"> to obtain a File object; the SDK will POST multipart/form-data.
  • Ensure your API has CORS headers allowing the origin where your app runs.

Local development tips

  • Use baseUrl: 'http://localhost:4600' or set DEVELOPER_API_URL.
  • If you run behind corporate proxies, set:
    export NO_PROXY=localhost,127.0.0.1,::1

License

MIT © Context