@thenoo/agentkit
v0.1.0
Published
Edge-safe, FinOps-first Agent SDK for The Noo ecosystem
Maintainers
Readme
@thenoo/agentkit
Edge-safe, FinOps-first Agent SDK for TypeScript
Build AI agents with transparent cost tracking, typed tool definitions, and pluggable memory providers. Works across Node.js, Deno, Cloudflare Workers, Vercel Edge, and AWS Lambda@Edge.
Quick Start • API Docs • Examples • Roadmap
📚 Documentation
- API Reference - Complete TypeDoc-generated API documentation
- v0.2.0 Release Notes - Latest release summary
- Changelog - Version history
- Examples - Working code examples
- Community - Contributing guidelines & discussions
- GitHub Issues - Bug reports & feature requests
🎉 What's New in v0.2.0
🚨 Breaking Changes (Deprecations)
Budget utilities moved to @thenoo/finops
The budget() function and BudgetManager class are now deprecated in @thenoo/agentkit and will be removed in v1.0.0.
Migration:
- import { budget, BudgetManager } from '@thenoo/agentkit';
+ import { createBudgetManager, BudgetManager } from '@thenoo/finops';
- const mgr = budget({ usd: 10 });
+ const mgr = createBudgetManager({ usd: 10 });🆕 New Packages
- @thenoo/finops - Dedicated FinOps package with multi-session support and event system
- @thenoo/adapter-openai - OpenAI integration with automatic cost tracking via
withFinOps() - @thenoo/cli - CLI scaffolder (
npx @thenoo/cli init) with templates and IDE presets
✨ New Features
- FinOps Context - Multi-session cost tracking with
createFinOpsContext() - Adapter Wrapping -
withFinOps()for automatic cost tracking and budget enforcement - Model Degradation - Automatic downgrade to cheaper models on budget breach
- CLI Templates - Minimal, Dashboard, and Serverless project templates
- IDE Integration - Presets for Cursor, GitHub Copilot, and VS Code
📦 Compatibility
- Backward-compatible shim maintains existing API
- Console warnings guide migration path
- All existing v0.1.0 projects continue to work
✨ Features
- 🔒 Type-Safe Tools - Zod schemas for input/output validation
- 💰 FinOps Built-In - Real-time budget tracking with configurable guardrails
- 🌍 Edge-Safe - No Node.js APIs; runs in any JavaScript runtime
- 🔌 Provider-Neutral - Works with Azure, OpenAI, local models, or custom LLMs
- 📊 Observable - Structured events ready for OpenTelemetry
- 🧩 Modular - Compose tools, memory, and budget policies
📦 Installation
# npm
npm install @thenoo/agentkit zod
# pnpm
pnpm add @thenoo/agentkit zod
# yarn
yarn add @thenoo/agentkit zodRequirements:
- Node.js ≥18 (or Deno, Cloudflare Workers, etc.)
- TypeScript ≥5.0 (recommended)
⚠️ Deprecation Notice
Budget utilities have moved to
@thenoo/finopsThe
budget()function andBudgetManagerclass are now deprecated in@thenoo/agentkitand will be removed in v1.0.0.Migration:
- import { budget, BudgetManager } from '@thenoo/agentkit'; + import { createBudgetManager, BudgetManager } from '@thenoo/finops'; - const mgr = budget({ usd: 10 }); + const mgr = createBudgetManager({ usd: 10 });See the
@thenoo/finopsdocumentation for the full API and adapter integration examples.
🚀 Quick Start
Hello Agent
import { z } from 'zod';
import { createAgent, tool } from '@thenoo/agentkit';
// 1. Define a tool with typed input/output
const calculator = tool({
name: 'calculator',
description: 'Perform basic arithmetic',
input: z.object({
operation: z.enum(['add', 'subtract', 'multiply', 'divide']),
a: z.number(),
b: z.number(),
}),
output: z.object({ result: z.number() }),
run: async ({ operation, a, b }) => {
const ops = {
add: a + b,
subtract: a - b,
multiply: a * b,
divide: a / b,
};
return { result: ops[operation] };
},
});
// 2. Create an agent with tools
const agent = createAgent({
name: 'MathAgent',
tools: [calculator],
});
// 3. Run the agent
const result = await agent.run('calculate 15 + 27');
console.log(result.output); // "The result is 42"With Budget Guardrails
import { createAgent, tool, budget } from '@thenoo/agentkit';
const agent = createAgent({
name: 'BudgetAgent',
tools: [myTool],
budget: budget({
usd: 5.0, // Max $5 per session
perRequestCents: 50, // Max 50¢ per request
onExceed: 'halt', // Stop execution on budget breach
}),
});
// Listen for cost alerts
agent.on('cost:alert', (event) => {
console.error('Budget exceeded!', event.payload);
});
const result = await agent.run('expensive operation');
console.log('Cost:', result.budgetState.totalUsd);💰 FinOps: Budget Management
Real-Time Cost Tracking
import { createAgent, budget } from '@thenoo/agentkit';
const budgetManager = budget({
usd: 10, // $10 session limit
perRequestCents: 100, // $1 per-request limit
onExceed: 'halt', // Policy: halt | truncate | degrade_model
});
const agent = createAgent({
name: 'CostAwareAgent',
budget: budgetManager,
});
// Check budget before expensive operations
if (budgetManager.wouldExceed(estimatedTokens, costPerMToken)) {
console.warn('Operation would exceed budget');
}
// Monitor costs in real-time
agent.on('cost:update', (event) => {
const { totalUsd, requestCount, lastRequestCents } = event.payload;
console.log(`Request ${requestCount}: $${lastRequestCents.toFixed(4)} (total: $${totalUsd.toFixed(2)})`);
});
// Handle budget alerts
agent.on('cost:alert', (event) => {
const { totalUsd, limitUsd, policy } = event.payload;
if (policy === 'halt') {
throw new Error(`Budget exceeded: $${totalUsd} > $${limitUsd}`);
}
});Budget Policies
| Policy | Behavior |
|--------|----------|
| halt | Stop execution immediately and throw an error |
| truncate | Continue with truncated context (reduce token usage) |
| degrade_model | Switch to cheaper model (requires adapter support) |
🔧 Tools: Type-Safe Functions
Creating Tools
import { z } from 'zod';
import { tool } from '@thenoo/agentkit';
const searchTool = tool({
name: 'webSearch',
description: 'Search the web for information',
input: z.object({
query: z.string().min(1),
limit: z.number().int().positive().optional().default(5),
}),
output: z.object({
results: z.array(z.object({
title: z.string(),
url: z.string().url(),
snippet: z.string(),
})),
}),
run: async ({ query, limit }) => {
// Integrate with your search API
const response = await fetch(`https://api.search.com?q=${query}&limit=${limit}`);
return await response.json();
},
});Tool Registry
import { createRegistry, AnyTool } from '@thenoo/agentkit';
const registry = createRegistry([searchTool, calculatorTool, databaseTool]);
// Get a tool by name
const tool = registry.get('webSearch');
// List all tools
console.log('Available tools:', registry.names());
// Execute a tool with validation
import { executeTool } from '@thenoo/agentkit';
const result = await executeTool(tool, { query: 'AI agents' });🧠 Memory: Pluggable Storage
In-Memory Provider (Development)
import { memory } from '@thenoo/agentkit';
const mem = memory<string>();
await mem.set('user:123', 'Alice', { role: 'admin' });
const record = await mem.get('user:123');
console.log(record?.content); // 'Alice'
const recent = await mem.list(10); // Last 10 recordsVector Store (Semantic Search)
import { vectorStore } from '@thenoo/agentkit';
const store = vectorStore<string>();
await store.set('doc1', 'Machine learning basics');
await store.setVector('doc1', [0.1, 0.5, 0.9]); // Embedding
const results = await store.search([0.15, 0.48, 0.92], 5);
results.forEach(({ content, score }) => {
console.log(`${content} (similarity: ${score})`);
});Custom Adapters
Implement MemoryProvider<T> or VectorStore<T> for:
- Azure Cosmos DB
- PostgreSQL with pgvector
- Redis
- Pinecone, Weaviate, Qdrant
📊 Events & Observability
Event Types
agent.on('agent:start', (event) => {
console.log('Agent started:', event.payload.prompt);
});
agent.on('tool:call', (event) => {
console.log('Tool called:', event.payload.tool);
});
agent.on('tool:result', (event) => {
console.log('Tool result:', event.payload.output);
});
agent.on('cost:update', (event) => {
console.log('Cost update:', event.payload.totalUsd);
});
agent.on('agent:complete', (event) => {
const { output, iterations, budgetState, durationMs } = event.payload;
console.log(`Completed in ${durationMs}ms with ${iterations} iterations`);
});
agent.on('agent:error', (event) => {
console.error('Agent error:', event.payload.error);
});OpenTelemetry Integration (Future)
const agent = createAgent({
name: 'TracedAgent',
tracing: true, // Emits trace:span events
});
// Integrate with @opentelemetry/api
// Implementation coming in v0.2.0🌍 Edge Runtime Compatibility
@thenoo/agentkit is edge-safe - no Node.js-specific APIs (fs, path, crypto, etc.).
Tested on:
- ✅ Node.js 18+
- ✅ Deno
- ✅ Cloudflare Workers
- ✅ Vercel Edge Functions
- ✅ AWS Lambda@Edge
- ✅ Bun
Example: Vercel Edge Function
// pages/api/agent.ts
import { createAgent, tool } from '@thenoo/agentkit';
export const config = { runtime: 'edge' };
const agent = createAgent({
name: 'EdgeAgent',
tools: [/* your tools */],
});
export default async function handler(req: Request) {
const { prompt } = await req.json();
const result = await agent.run(prompt);
return new Response(JSON.stringify(result), {
headers: { 'Content-Type': 'application/json' },
});
}🏗️ Architecture
┌─────────────────────────────────────────┐
│ Agent (Orchestrator) │
│ ┌──────────────────────────────────┐ │
│ │ Tool Registry │ │
│ │ • Validation (Zod) │ │
│ │ • Execution │ │
│ │ • Error handling │ │
│ └──────────────────────────────────┘ │
│ │
│ ┌──────────────────────────────────┐ │
│ │ Budget Manager │ │
│ │ • Token tracking │ │
│ │ • Cost calculation │ │
│ │ • Policy enforcement │ │
│ └──────────────────────────────────┘ │
│ │
│ ┌──────────────────────────────────┐ │
│ │ Memory Provider │ │
│ │ • Key-value storage │ │
│ │ • Vector search (optional) │ │
│ │ • Pluggable backends │ │
│ └──────────────────────────────────┘ │
│ │
│ ┌──────────────────────────────────┐ │
│ │ Event Bus │ │
│ │ • Structured events │ │
│ │ • OpenTelemetry-ready │ │
│ └──────────────────────────────────┘ │
└─────────────────────────────────────────┘Design Principles:
- Core is runtime-agnostic (edge-safe)
- Adapters live in separate packages
- FinOps tracking is opt-in but encouraged
- Memory and tools are pluggable
📖 API Reference
Full API documentation is available in the docs/api/ directory, generated with TypeDoc.
Core Exports
Agent Creation
createAgent(config)- Factory for agent instancesAgentclass - Main execution engine
Tools
tool({ name, input, output, run })- Create typed toolsexecuteTool(tool, input)- Execute with validationToolRegistry- Manage tool collectionsAnyTool- Type for heterogeneous tool arrays
Budget
budget(config)- Create budget managerBudgetManager- Track costs, enforce limitsestimateTokens(text)- Rough token countcalculateTokens(input, output)- Total usage
Memory
memory<T>()- In-memory providervectorStore<T>()- Stub vector searchInMemoryProvider<T>- Simple storageStubVectorStore<T>- Mock semantic search
Types
Tool<TInput, TOutput>- Generic tool interfaceAgentConfig,AgentResult,ToolCallBudgetPolicy,BudgetConfig,BudgetStateMemoryRecord,MemoryProvider,VectorStore
Utilities
mask(value, reveal?)- Redact secrets from logsschemas- Runtime Zod schemas
🧪 Testing
# Run tests
pnpm test
# Watch mode
pnpm test:watch
# Coverage (requires ≥90%)
pnpm test:coverageTest Coverage:
- 68 tests across 6 suites
- Budget: 21 tests (including guardrails)
- Tools: 16 tests (validation, registry, execution)
- Memory: 11 tests (CRUD, vector search)
- Agent: 11 tests (orchestration, events)
- Types: 9 tests (mask utility, schemas)
🚢 Publishing
# Dry-run validation
npm pack --dry-run
# Build
pnpm build
# Publish to npm
npm publish --access publicPackage Size:
- Tarball: 15.6 KB
- Unpacked: 53.5 KB
- Minified + Gzipped: ~5.2 KB
🛠️ Development
# Clone repo
git clone https://github.com/ZacheryKuykendall/noo.git
cd noo
# Install dependencies
pnpm install
# Work on agentkit
cd packages/agentkit
pnpm dev # Tests in watch mode
pnpm build # Compile to dist/
pnpm docs # Generate API docs
# Run example
cd ../../examples/hello-agent
pnpm start🗺️ Roadmap
v0.2.0 (Next)
- [ ] Real LLM adapters (
@thenoo/adapter-openai,@thenoo/adapter-azure) - [ ] Extract
@thenoo/finopsmiddleware package - [ ] Production vector store adapters (Cosmos DB, pgvector)
- [ ] Streaming support for agent responses
v1.0.0 (Future)
- [ ] Multi-agent orchestration
- [ ] OpenTelemetry tracing implementation
- [ ] Advanced budget policies (
degrade_model,truncate) - [ ] Agent-to-agent communication
- [ ] Persistent conversation management
🤝 Contributing
Contributions are welcome! See CONTRIBUTING.md for guidelines.
Before submitting:
- Run
pnpm typecheck(zero errors required) - Run
pnpm test(all tests must pass) - Ensure coverage ≥90% for new code
- Add JSDoc comments for public APIs
📄 License
MIT © The Noo Team
See LICENSE for details.
🔗 Links
- GitHub: https://github.com/ZacheryKuykendall/noo
- npm: https://www.npmjs.com/package/@thenoo/agentkit
- Issues: https://github.com/ZacheryKuykendall/noo/issues
- Discussions: https://github.com/ZacheryKuykendall/noo/discussions
Built with ❤️ by The Noo Team
