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

specos-agent-kit

v1.4.0

Published

Provider-agnostic multi-tenant AI agent runtime, crash-resilient async worker queue, and pluggable atomic token ledger & sliding-window rate limiter

Readme

specos-agent-kit

Multi-tenant hybrid Gemini agent runtime, crash-resilient async worker queue, and pluggable atomic token ledger & sliding-window rate limiter.

Features

  • Pluggable AI Provider (HybridAgentRuntime + AIProvider): Wrap any AI (OpenAI, Anthropic, Ollama, custom HTTP models, or built-in GeminiProvider which lazily imports @google/genai). Enforces AbortSignal + timeoutMs timeouts and falls back deterministically when offline or on provider error.
  • Crash-Resilient Worker Queue (AgentQueueService): Bounded concurrency, exponential-backoff maxRetries / retryBaseDelayMs, lifecycle hooks (onJobCompleted, onJobFailed), recoverJobs() for restarting stranded jobs from an external JobStore, and async-capable JobStore (InMemoryJobStore by default).
  • Atomic Token Ledger & Sliding-Window Rate Limiter (TokenLedgerService): True sliding-window timestamp log (RateLimitStore) and atomic tryDebit(...) quota enforcement (LedgerStore) with InMemoryRateLimitStore and InMemoryLedgerStore defaults.
  • Integrated Orchestrator (AgentOrchestrator): Wires checkRateLimit -> atomic debitTokens -> enqueueJob in one call.

Quick Start

import {
  AgentOrchestrator,
  AgentQueueService,
  HybridAgentRuntime,
  TokenLedgerService,
} from 'specos-agent-kit';

const runtime = new HybridAgentRuntime({ timeoutMs: 15000 });
runtime.registerTask('summarize', {
  buildPrompt: (ctx) => ({
    systemInstruction: `Summarize for ${ctx.tenantName} in ${ctx.locale}. Return JSON.`,
    prompt: JSON.stringify(ctx.payload),
  }),
  fallback: (ctx) => ({
    result: { summary: `Offline summary for ${ctx.tenantName}` },
    tokens: 150,
  }),
});

const queue = new AgentQueueService({
  runtime,
  concurrency: 5,
  maxRetries: 2,
  retryBaseDelayMs: 50,
  onJobCompleted: async (job) => {
    console.log('Completed', job.id, job.tokensUsed);
  },
});

const ledger = new TokenLedgerService({ windowMs: 60_000, maxLedgerEntries: 10_000 });
const orchestrator = new AgentOrchestrator({ ledger, queue });

const result = await orchestrator.dispatch({
  tenantId: 'tenant-1',
  tenantSlug: 'acme',
  tenantName: 'Acme Corp',
  locale: 'en',
  taskKey: 'summarize',
  payload: { text: 'Hello' },
  estimatedTokens: 200,
  budgetMonthly: 100_000,
});

if (result.accepted) {
  console.log('Queued job:', result.job.id);
}

// On startup with an external JobStore, recover any stranded QUEUED or stale PROCESSING jobs:
await queue.recoverJobs({ staleProcessingMs: 60_000 });

Plugging in Any AI Provider (AIProvider)

import { HybridAgentRuntime, type AIProvider } from 'specos-agent-kit';

const openaiProvider: AIProvider = {
  name: 'openai',
  async generate({ model, systemInstruction, prompt, signal }) {
    const res = await fetch('https://api.openai.com/v1/chat/completions', {
      method: 'POST',
      signal,
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
      },
      body: JSON.stringify({
        model,
        response_format: { type: 'json_object' },
        messages: [
          { role: 'system', content: systemInstruction },
          { role: 'user', content: prompt },
        ],
      }),
    });
    const data = await res.json();
    return {
      text: data.choices[0].message.content,
      tokensUsed: data.usage?.total_tokens,
    };
  },
};

const runtime = new HybridAgentRuntime({
  provider: openaiProvider,
  defaultModel: 'gpt-4o-mini',
});

Production Store Adapters (Reference Examples)

Postgres LedgerStore (atomic tryDebit)

import type { LedgerStore } from 'specos-agent-kit';

export class PostgresLedgerStore implements LedgerStore {
  constructor(private readonly db: { query: (sql: string, params: any[]) => Promise<{ rows: any[] }> }) {}

  async tryDebit(tenantId: string, taskKey: string, tokensToDebit: number, budgetMonthly: number, entryId: string) {
    const res = await this.db.query(
      `UPDATE tenant_quotas
       SET consumed = consumed + $2
       WHERE tenant_id = $1 AND consumed + $2 <= $3
       RETURNING consumed`,
      [tenantId, tokensToDebit, budgetMonthly]
    );
    if (res.rows.length === 0) {
      const current = await this.getConsumed(tenantId);
      return { success: false, newConsumed: current, remaining: Math.max(0, budgetMonthly - current), error: 'Budget exceeded' };
    }
    const newConsumed = res.rows[0].consumed;
    await this.db.query(
      `INSERT INTO token_ledger (id, tenant_id, task_key, tokens_debited, balance_remaining) VALUES ($1, $2, $3, $4, $5)`,
      [entryId, tenantId, taskKey, tokensToDebit, budgetMonthly - newConsumed]
    );
    return { success: true, newConsumed, remaining: budgetMonthly - newConsumed };
  }

  async getConsumed(tenantId: string) {
    const res = await this.db.query(`SELECT consumed FROM tenant_quotas WHERE tenant_id = $1`, [tenantId]);
    return res.rows[0]?.consumed ?? 0;
  }

  async listByTenant(tenantId: string) {
    const res = await this.db.query(`SELECT * FROM token_ledger WHERE tenant_id = $1 ORDER BY timestamp DESC`, [tenantId]);
    return res.rows;
  }
}

Redis RateLimitStore (sliding-window sorted set)

import type { RateLimitStore } from 'specos-agent-kit';

export class RedisRateLimitStore implements RateLimitStore {
  constructor(private readonly redis: { eval: (script: string, keys: string[], args: (string | number)[]) => Promise<[number, number]> }) {}

  async checkAndRecord(tenantId: string, maxPerWindow: number, windowMs: number, now: number) {
    if (maxPerWindow <= 0) return { allowed: false, remaining: 0, resetAtMs: now + windowMs };
    const lua = `
      redis.call('ZREMRANGEBYSCORE', KEYS[1], 0, ARGV[1])
      local count = redis.call('ZCARD', KEYS[1])
      if count >= tonumber(ARGV[2]) then return {0, 0} end
      redis.call('ZADD', KEYS[1], ARGV[3], ARGV[3] .. '-' .. math.random())
      redis.call('PEXPIRE', KEYS[1], ARGV[4])
      return {1, tonumber(ARGV[2]) - count - 1}
    `;
    const [allowed, remaining] = await this.redis.eval(lua, [`rl:${tenantId}`], [now - windowMs, maxPerWindow, now, windowMs]);
    return { allowed: allowed === 1, remaining, resetAtMs: now + windowMs };
  }
}