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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@dex-ai/context

v0.7.17

Published

Index-and-pointer context management — indexes all tool outputs into FTS5 knowledge base for zero-loss compression. Provides ctx_search for on-demand retrieval. Zero config.

Readme

@dex-ai/context

Context management extension for Dex — tracks token usage, provides a visual /context command, enforces context budgets, and guides the LLM to avoid flooding the context window.

What It Does

Context Usage

■ ■ ■ ■ ■ ■ ■ ■ ■ ■      Total Usage    102k ( 51.1%)
■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■ ■ ■ ■ ■ ■ ■ ■ □ □      ■ System Prompt   1k (  0.7%)
□ □ □ □ □ □ □ □ □ □      ■ System Tools    2k (  0.9%)
□ □ □ □ □ □ □ □ □ □      ■ Tool Results   96k ( 48.1%)
                           ■ Messages        3k (  1.5%)
                           □ Available      98k ( 48.9%)

Features

  1. Real-time context tracking — estimates token usage across categories (system prompt, tools, messages, tool calls/results, images, files, reasoning) using fast heuristics calibrated against cl100k_base.

  2. /context command — visual grid + percentage breakdown showing exactly where context is being consumed, with color-coded categories.

  3. Threshold warnings — automatically injects guidance to the LLM when context usage exceeds configurable thresholds (default: warn at 75%, critical at 90%).

  4. Context-awareness skill — teaches the LLM patterns for keeping outputs small (targeted reads, search-before-read, output truncation).

  5. Tool output tracking — records per-tool output sizes to identify the biggest context consumers.

Usage

import { contextExtension } from "@dex-ai/context";
import { Agent } from "@dex-ai/sdk";

const agent = await Agent.create({
  provider: "anthropic",
  model: "claude-sonnet-4-20250514",
  extensions: [
    providerExt,
    contextExtension(), // sensible defaults
  ],
});

With Options

contextExtension({
  maxTokens: 128_000, // override context window (auto-detected from model)
  warnAt: 70, // warn threshold (default: 75%)
  criticalAt: 85, // critical threshold (default: 90%)
  injectGuidance: true, // inject context-awareness skill (default: true)
  trackToolOutputs: true, // track per-tool output sizes (default: true)
  largeOutputThreshold: 4_000, // tokens above which an output is "large"
});

/context Command Integration

The extension stores accessor functions in AgentContext.state that the host (CLI/TUI) can invoke:

// In your host/CLI command handler:
const getFormatted = agent.context.state.get(
  "context:getFormatted",
) as () => string;
const getPlain = agent.context.state.get("context:getPlain") as () => string;
const getSnapshot = agent.context.state.get(
  "context:getSnapshot",
) as () => ContextSnapshot;

// For TUI rendering (ANSI color codes):
console.log(getFormatted());

// For plain text (no ANSI):
console.log(getPlain());

// For programmatic access:
const snapshot = getSnapshot();
console.log(
  `${snapshot.usagePercent}% used, ${snapshot.availableTokens} remaining`,
);

How It Works

Token Estimation

Uses character-based heuristics calibrated for modern tokenizers:

  • English text: ~4 chars per token
  • Code: ~3.5 chars per token
  • JSON/structured: ~3 chars per token
  • Images: Anthropic tile-based estimation

This is intentionally approximate (±10%). Real token counts come from the provider's usage response and are used to calibrate the estimates.

Category Tracking

| Category | What's counted | | ------------- | ---------------------------------------------------- | | System Prompt | System messages + injected skills | | System Tools | Tool definitions (name + description + JSON Schema) | | Tool Calls | Assistant tool invocations (name + serialized input) | | Tool Results | Tool outputs (text, JSON, rich content) | | Messages | User + assistant text messages | | Images | Image content (resolution-based estimation) | | Files | File attachments (size-based estimation) | | Reasoning | Chain-of-thought / extended thinking |

Threshold Behavior

When context usage exceeds a threshold, the extension injects a concise system message into the next model request:

  • Warning (75%): "⚠️ Context usage: 76%. Be concise. Avoid large reads/outputs."
  • Critical (90%): "🚨 Context nearly full: 91% used. Complete the current task as concisely as possible."

These are injected once per threshold crossing (not on every model call).

Context-Awareness Skill

When injectGuidance: true (default), a skill is added to the system prompt teaching the LLM:

  • Prefer targeted reads (line ranges) over full file reads
  • Use search before read to find relevant sections
  • Truncate bash output with head/tail/grep
  • Avoid redundant re-reads of files already in context
  • Be more concise when context is running low

Comparison with context-mode

| Feature | context-mode | @dex-ai/context | | ------------------- | ---------------------- | ------------------------------------------------- | | Token tracking | ❌ (defers to host) | ✅ Built-in estimation | | Visual display | ❌ | ✅ Grid + categories | | Hard-blocks tools | ✅ (blocks curl/fetch) | ❌ (guidance-based) | | Sandboxed execution | ✅ (separate process) | ❌ (not needed — Dex tools already handle this) | | FTS5 knowledge base | ✅ (SQLite) | ❌ (out of scope — use @dex-ai/knowledge) | | Session persistence | ✅ (SessionDB) | ❌ (out of scope — use @dex-ai/session-extension) | | Native dependencies | better-sqlite3 | None | | Weight | 3.6 MB | ~15 KB |

Philosophy difference: context-mode hard-blocks certain tool calls to prevent context flooding. @dex-ai/context takes a guidance approach — it teaches the LLM good patterns and warns when budgets are exceeded, but trusts the model to make the right choice. This works better with modern models that can follow instructions.

API

contextExtension(opts?): Extension

Factory function — creates the extension.

estimateTokens(text: string): number

Estimate token count for a string.

formatContextUsage(snapshot: ContextSnapshot): string

Format a snapshot with ANSI colors for terminal display.

formatContextUsagePlain(snapshot: ContextSnapshot): string

Format a snapshot as plain text (no colors).

Types

interface ContextSnapshot {
  timestamp: number;
  totalTokens: number;
  maxTokens: number;
  usagePercent: number;
  categories: CategoryUsage[];
  availableTokens: number;
}

interface CategoryUsage {
  category: ContextCategory;
  tokens: number;
  percent: number;
}

type ContextCategory =
  | "system-prompt"
  | "system-tools"
  | "messages"
  | "tool-calls"
  | "tool-results"
  | "images"
  | "files"
  | "reasoning";

Development

bun install
bun run typecheck
bun test

License

MIT