Bridge SDK — Quick Start
The Bridge SDK lets external clients (Kilo Code, Cursor, VS Code, or any Node.js process) orchestrate Nity as a bidirectional sub-agent through the pi-coding-agent runtime.
How It Works
The bridge is bidirectional:
Kilo Code (PM & Coder orchestrator)
│
├─ sendTask("analyze", ...) → Nity runs full PM pipeline
├─ sendTask("execute", ...) → Nity runs full Coder pipeline
├─ sendTask("validate", ...) → Nity runs quality gates
├─ sendTask("reflect", ...) → Nity runs self-reflection
└─ sendTask("skills", ...) → Nity runs skill matching
│
▼
Nity (PM & Coder for execution)
│
├─→ Standalone (LoopEngine) — simple tasks
└─→ QuantumReef (12 engines) — complex tasksKilo commands all 5 Nity tools through sendTask(). When you call sendTask("execute", prompt), Nity doesn't just run code — it runs the full pipeline: TaskAnalyzer → StrategyPlanner → ExecutionRouter → QualityGates → SelfReflection. The result includes quality gate status, reflection data, and episode references.
Kilo is the outer PM (orchestrating which tool to invoke, validating results). Nity is the inner PM & Coder (analyzing complexity, routing execution, checking quality, reflecting on outcomes). Two PMs in harmony.
Installation
The Bridge SDK is bundled with @mariozechner/pi-coding-agent. No separate install is needed.
npm install @mariozechner/pi-coding-agentImport from the extensions/nity/bridge subpath:
import { createNitySession } from '@mariozechner/pi-coding-agent/extensions/nity/bridge';Basic Usage
Create a session, dispatch a task, and read the result:
import { createNitySession } from '@mariozechner/pi-coding-agent/extensions/nity/bridge';
const session = await createNitySession({
costTier: 'free', // Uses Ollama ($0)
});
const result = await session.sendTask('analyze', 'Review the auth module for security issues');
console.log(result.output);
console.log(result.duration);
await session.close();What's happening
createNitySessionspins up a pi-coding-agent session and returns aNitySessionHandle.sendTaskdispatches a prompt to Nity using theanalyzetask type, which routes to thenity_analyzetool.- The result includes structured output, execution duration, and optional quality gate / reflection data.
closecleans up the underlying session.
Cost Tiers
The Bridge SDK supports three cost tiers that control which models are used for orchestration and execution:
| Tier | Orchestrator | Executor | Cost | Use Case |
|---|---|---|---|---|
free | Ollama | Ollama (local) | $0 | Development, testing |
hybrid | Ollama | Claude Sonnet 4 | Low | Balanced production |
premium | Claude Sonnet 4 | Claude Sonnet 4 | Medium | Maximum capability |
// Free tier — $0, local models only
const free = await createNitySession({ costTier: 'free' });
// Hybrid — Ollama orchestrates, Claude executes
const hybrid = await createNitySession({ costTier: 'hybrid' });
// Premium — Claude for both layers
const premium = await createNitySession({ costTier: 'premium' });The free tier requires a running Ollama instance. See the Cost Tiers page for environment variable overrides and model configuration.
Dispatching Different Task Types
Five task types are available, each routing to a different Nity tool. Kilo chooses which tool to invoke — this is the PM orchestration layer:
// Analyze — Kilo delegates analysis to Nity's PM pipeline
await session.sendTask('analyze', 'Break down the payment flow architecture');
// Execute — Kilo delegates implementation to Nity's Coder pipeline
await session.sendTask('execute', 'Add rate limiting to the /api/users endpoint');
// Validate — Kilo delegates quality verification to Nity
await session.sendTask('validate', 'Check the new caching layer for correctness');
// Reflect — Kilo delegates learning capture to Nity
await session.sendTask('reflect', 'What went well with the migration?');
// Skills — Kilo delegates pattern matching to Nity
await session.sendTask('skills', 'Find relevant patterns for WebSocket auth');Role Selection
Each task automatically uses PM or Coder mode. Override with the options.role parameter:
// Default: analyze uses PM mode
await session.sendTask('analyze', 'Review auth security');
// → Nity receives: [PM Mode — Focus on analysis, quality, and strategic decisions.]
// Override: force Coder mode for code-focused analysis
await session.sendTask('analyze', 'Review auth security', undefined, { role: 'coder' });
// → Nity receives: [Coder Mode — Focus on implementation, correctness, and code quality.]| Task Type | Default Role | Focus |
|---|---|---|
analyze | PM | Analysis, complexity, risk, strategy |
execute | Coder | Implementation, code quality, correctness |
validate | PM | Quality gates, blocking issues |
reflect | PM | Lessons, follow-ups, episode persistence |
skills | PM | Pattern matching, success rates |
Structured Results
Every sendTask() returns a NityResult with quality gates, reflection, and episode references — Nity's full PM output:
const result = await session.sendTask('validate', 'Check the auth module');
console.log(result.success); // true
console.log(result.qualityGatePassed); // true — Nity's quality gates passed
console.log(result.reflection); // { lessons: [...], followUps: [...] }
console.log(result.episodeId); // 'ep-auth-2026-03-21' — persisted to memory
console.log(result.duration); // 4523 — msInjecting Context
Pass previous episodes, memory, or skill hints to give Nity background on the task:
const result = await session.sendTask('execute', 'Refactor the error handling', {
episodes: [
{ id: 'ep-001', summary: 'Initial error audit', outcome: 'Found 3 unhandled cases' },
],
memory: {
goal: 'Standardize error responses across the API',
discoveries: ['Validation errors use inconsistent formats'],
},
});See Context Injection for the full NityContext reference.
Subscribing to Events
Monitor task progress in real time:
const unsubscribe = session.subscribe((event) => {
if (event.type === 'task_progress') {
console.log(`Progress: ${event.payload.progress}`);
}
});
const result = await session.sendTask('execute', 'Build the dashboard');
// Clean up when done
unsubscribe();See Event Streaming for all event types and extraction utilities.
Cleanup
Always close sessions when you're done. Sessions have a default 5-minute timeout, but explicit cleanup is recommended:
// Close a single session
await session.close();
// For multi-client setups, use the registry
import { NitySessionRegistry } from '@mariozechner/pi-coding-agent/extensions/nity/bridge';
const registry = new NitySessionRegistry();
registry.register('client-abc', session);
// On client disconnect
await registry.cleanupClient('client-abc');Forgetting to close sessions leaks resources. In production, use NitySessionRegistry.cleanupStale() on a timer to garbage-collect timed-out sessions.
The Full Picture
Kilo orchestrates Nity via the Bridge SDK. Nity orchestrates execution via QuantumReef. The user sees everything through their preferred client.
User → Kilo Code (PM orchestrator)
│
├─ sendTask("analyze", ...)
├─ sendTask("execute", ...)
└─ sendTask("validate", ...)
│
▼
Nity (PM & Coder)
│
┌──────┴──────┐
▼ ▼
Standalone QuantumReef Bridge
(LoopEngine) (WebSocket → 12 engines)
│
├─→ Claude Code
├─→ OpenCode
├─→ Aider
└─→ ...9 moreSee Nity as PM — QuantumReef Integration for the full architecture, WebSocket protocol, category mapping, and routing logic.
Next Steps
- pi-coding-agent SDK docs (opens in a new tab) — base SDK reference