Documentation
Bridge SDK
API Reference

Bridge SDK — API Reference

Full API reference for all exports from @mariozechner/pi-coding-agent/extensions/nity/bridge.

Functions

createNitySession

function createNitySession(config?: NityBridgeConfig): Promise<NitySessionHandle>

Creates a new Nity bridge session backed by a pi-coding-agent instance. Resolves configuration with tier defaults, spins up the agent session, and emits a session_start event.


dispatchTask

function dispatchTask(
  taskType: NityTaskType,
  prompt: string,
  context?: NityContext,
  options?: { role?: NityRole; maxPromptTokens?: number }
): string

Constructs the full prompt for Nity tool invocation. Validates the prompt, selects the role prefix, formats context, and optimizes for token budget. Throws on invalid prompt or unknown task type.


getToolName

function getToolName(taskType: NityTaskType): string

Maps a bridge task type to the corresponding Nity tool name (nity_analyze, nity_execute, nity_quality_gate, nity_reflect, nity_skills).


isValidTaskType

function isValidTaskType(taskType: string): taskType is NityTaskType

Returns true if the string is a valid NityTaskType.


validatePrompt

function validatePrompt(prompt: string): { valid: boolean; errors: string[] }

Validates prompt content. Checks for non-empty string, minimum length (3 chars), and maximum length (100,000 chars).


optimizePrompt

function optimizePrompt(prompt: string, maxTokens?: number): string

Optimizes a prompt for token efficiency by collapsing excess whitespace and truncating to a character budget (rough estimate: 1 token ≈ 4 chars). Appends [...truncated] when cut. Pass maxTokens: 0 for unlimited.


selectRole

function selectRole(taskType: NityTaskType, explicitRole?: NityRole): NityRole

Resolves the role for a task. If an explicit role is provided (and not "auto"), uses it. Otherwise returns the default: pm for analyze/validate/reflect/skills, coder for execute.


resolveConfig

function resolveConfig(userConfig?: NityBridgeConfig): Required<NityBridgeConfig>

Merges user configuration with tier defaults. Uses the cost tier's orchestrator/executor models unless overridden. Returns a fully resolved config with all 14 fields populated.


getTierDefinition

function getTierDefinition(tier: CostTier): TierDefinition

Returns the TierDefinition for a cost tier, containing name, orchestrator model, executor model, and description.


getTierModels

function getTierModels(tier: CostTier): TierModelConfig

Returns the model configuration for a tier. Applies environment variable overrides (NITY_BRIDGE_ORCHESTRATOR_MODEL, NITY_BRIDGE_EXECUTOR_MODEL) over tier defaults.


getAllTiers

function getAllTiers(): Record<CostTier, TierModelConfig>

Returns model configurations for all three tiers, with environment variable overrides applied.


isValidCostTier

function isValidCostTier(tier: string): tier is CostTier

Returns true if the string is a valid CostTier (free, hybrid, or premium).


getCostIndicator

function getCostIndicator(tier: CostTier): 'free' | 'low' | 'medium' | 'high'

Returns the human-readable cost indicator for a tier: free for the free tier, low for hybrid, medium for premium.


getModelCapabilities

function getModelCapabilities(model: string): ModelCapabilities | null

Returns capabilities for a known model (ollama, anthropic/claude-sonnet-4-20250514, mimo). Returns null for unknown models.


modelHasCapability

function modelHasCapability(model: string, capability: keyof ModelCapabilities): boolean

Checks whether a model has a specific capability. Unknown models are assumed capable.


matchModel

function matchModel(requiredCapabilities: string[], preferredTier: CostTier): string

Finds the best model for required capabilities. Falls back to the orchestrator if the executor lacks a capability, or upgrades to premium if neither has it.


getFallbackChain

function getFallbackChain(tier: CostTier): string[]

Returns the fallback model chain for a tier. Free: ["ollama"], hybrid: ["claude-sonnet-4", "ollama"], premium: ["claude-sonnet-4", "claude-sonnet-4"].


getNextFallback

function getNextFallback(tier: CostTier, currentModel: string): string | null

Returns the next model in the fallback chain after currentModel, or null if at the end of the chain.


categorizeEvent

function categorizeEvent(event: PiAgentEvent): EventCategory

Categorizes a raw pi-coding-agent event into tool_call, tool_result, message, error, session, or unknown.


extractProgress

function extractProgress(event: PiAgentEvent): NityProgress | null

Extracts progress information from an event. Returns phase description, percentage (25/50/75), and a truncated delta. Returns null for unrecognized events.


extractQualityGates

function extractQualityGates(event: PiAgentEvent): { passed: boolean; details: string } | null

Extracts quality gate status from tool result events. Looks for "quality", "gate", "passed", or "failed" indicators in the output.


extractReflection

function extractReflection(event: PiAgentEvent): { lessons: string[]; followUps: string[] } | null

Extracts reflection data from tool result events. Parses bullet-pointed lines into lessons and follow-ups based on keyword matching ("follow-up", "next", "todo").


extractEpisodeRefs

function extractEpisodeRefs(event: PiAgentEvent): string[]

Extracts episode ID references from tool result events. Matches patterns like ep-123, episode: abc, [ep-xyz].


validateResult

function validateResult(result: NityResult): { valid: boolean; warnings: string[] }

Validates a NityResult for completeness. Checks for missing taskType, empty output on success, missing error on failure, negative duration, and quality gate contradictions.


buildResult

function buildResult(
  taskType: NityTaskType,
  events: PiAgentEvent[],
  duration: number,
  error?: string
): NityResult

Builds a structured NityResult from accumulated events. Aggregates messages and tool outputs, extracts quality gate status, reflection data, and episode references.


createEventTransformer

function createEventTransformer(
  taskType: NityTaskType
): (event: PiAgentEvent) => NityEvent | null

Creates a transformer function that converts raw pi-coding-agent events into typed NityEvent objects. Returns null for unknown event categories.


createProgressThrottler

function createProgressThrottler(
  emit: (progress: NityProgress) => void,
  minIntervalMs?: number
): { push: (progress: NityProgress) => void; cancel: () => void; flush: () => void }

Creates a throttled progress emitter. Batches rapid progress updates to a minimum interval (default 100ms). Returns push (queue a progress update), cancel (discard pending), and flush (emit pending immediately).


Classes

NitySessionRegistry

Multi-client session tracking with automatic cleanup on client disconnect.

class NitySessionRegistry {
  register(clientId: string, session: NitySessionHandle): void
  unregister(sessionId: string): Promise<void>
  cleanupClient(clientId: string): Promise<number>
  getClientSessions(clientId: string): NitySessionHandle[]
  getSession(sessionId: string): NitySessionHandle | undefined
  getStats(): NitySessionRegistryStats
  cleanupStale(): Promise<number>
}
MethodDescription
registerRegister a session under a client ID
unregisterClose and remove a specific session
cleanupClientClose all sessions for a client, returns count cleaned
getClientSessionsGet all active sessions for a client
getSessionGet a session by ID
getStatsGet registry statistics (total sessions, active clients, per-client counts)
cleanupStaleRemove timed-out and errored sessions, returns count cleaned

CostTracker

Session-level cost accounting with budget alerts and optimization suggestions.

class CostTracker {
  constructor(options?: { budgetLimit?: number; budgetAlertThreshold?: number })
 
  recordTask(tier: CostTier, inputTokens: number, outputTokens: number): number
  recordSession(): void
  estimateCost(tier: CostTier, estimatedInputTokens: number, estimatedOutputTokens: number): NityCostEstimate
  isBudgetExceeded(): boolean
  onBudgetAlert(callback: (spent: number, limit: number) => void): void
  getReport(): NityCostReport
  getOptimizationSuggestions(): string[]
  reset(): void
}
MethodDescription
recordTaskRecord a task execution, returns calculated cost in USD
recordSessionIncrement session counter
estimateCostEstimate cost before execution
isBudgetExceededCheck if total spend exceeds budgetLimit
onBudgetAlertRegister a callback fired when spend crosses budgetAlertThreshold
getReportGenerate a full NityCostReport with per-tier breakdown
getOptimizationSuggestionsGet cost-saving recommendations based on usage patterns
resetClear all tracking data

ProgressStore

Progress persistence for long-running tasks.

class ProgressStore {
  record(taskId: string, progress: NityProgress): void
  getHistory(taskId: string): NityProgress[]
  getLatest(taskId: string): NityProgress | null
  clear(taskId: string): void
  clearAll(): void
}
MethodDescription
recordStore a progress update for a task
getHistoryGet all progress updates for a task
getLatestGet the most recent progress for a task
clearRemove progress history for a task
clearAllRemove all progress history

Interfaces

NitySessionHandle

The primary interface returned by createNitySession.

interface NitySessionHandle {
  id: string;
  state: NitySessionState;
  sendTask(
    type: NityTaskType,
    prompt: string,
    context?: NityContext,
    options?: NityTaskOptions
  ): Promise<NityResult>;
  cancelTask(): void;
  isRunning(): boolean;
  subscribe(callback: (event: NityEvent) => void): () => void;
  close(): Promise<void>;
  getHealth(): {
    state: NitySessionState;
    errorCount: number;
    lastActivity: number;
    isTimedOut: boolean;
    uptime: number;
  };
}

NityBridgeConfig

Configuration for createNitySession. All fields are optional.

interface NityBridgeConfig {
  costTier?: CostTier;                    // Model tier (default: 'free')
  orchestratorModel?: string;             // Override orchestrator model
  executorModel?: string;                 // Override executor model
  timeout?: number;                       // Session timeout in ms (default: 300000)
  maxRetries?: number;                    // Max retries on transient errors (default: 2)
  enableQualityGates?: boolean;           // Quality gate checks (default: true)
  enableReflection?: boolean;             // Post-task reflection (default: true)
  workingDirectory?: string;              // Working directory for execution
  enableFallback?: boolean;               // Fallback to standalone on Nity failure (default: true)
  contextProvider?: () => Promise<NityContext | undefined>;  // Auto-inject context
  budgetLimit?: number;                   // USD budget per session (0 = unlimited)
  budgetAlertThreshold?: number;          // Alert threshold in USD (0 = disabled)
  requiredCapabilities?: string[];        // Required model capabilities
  maxPromptTokens?: number;               // Token budget for prompt optimization (0 = unlimited)
}

NityResult

Structured result from a task execution.

interface NityResult {
  taskType: NityTaskType;
  success: boolean;
  output: string;
  duration: number;
  qualityReport?: QualityGateReport;
  reflection?: ReflectionRecord;
  episodeId?: string;
  error?: string;
  qualityGatePassed?: boolean;
}

NityContext

Context injection for enriching prompts with memory, episodes, and skill hints.

interface NityContext {
  episodes?: Array<{ id: string; summary: string; outcome: string }>;
  memory?: {
    goal?: string;
    discoveries?: string[];
    workingSet?: string[];
  };
  skillHints?: Array<{ name: string; successRate: number }>;
  metadata?: Record<string, string>;
}

NityTaskOptions

Options for sendTask.

interface NityTaskOptions {
  signal?: AbortSignal;         // Cancellation signal
  priority?: NityTaskPriority;  // 'low' | 'normal' | 'high' | 'critical'
  role?: NityRole;              // Force a specific role
  cacheKey?: string;            // Enable result caching
  cacheMaxAge?: number;         // Cache TTL in ms (default: 300000)
}

Types

NityTaskType

type NityTaskType = 'analyze' | 'execute' | 'validate' | 'reflect' | 'skills';

NityRole

type NityRole = 'pm' | 'coder' | 'auto';

NityTaskPriority

type NityTaskPriority = 'low' | 'normal' | 'high' | 'critical';

NitySessionState

type NitySessionState = 'idle' | 'active' | 'completed' | 'error';

CostTier

type CostTier = 'free' | 'hybrid' | 'premium';

NityEventType

type NityEventType = 'session_start' | 'task_start' | 'task_progress' | 'task_complete' | 'task_error' | 'session_close';

NityEvent

interface NityEvent {
  type: NityEventType;
  timestamp: number;
  payload: Record<string, unknown>;
}

NityProgress

interface NityProgress {
  phase: string;
  percentage: number;
  delta?: string;
}

NityCostEstimate

interface NityCostEstimate {
  estimatedCost: number;
  orchestratorModel: string;
  executorModel: string;
  tier: CostTier;
}

NityCostReport

interface NityCostReport {
  totalSessions: number;
  totalTasks: number;
  totalCost: number;
  byTier: Record<CostTier, { tasks: number; cost: number }>;
  avgCostPerTask: number;
}

All imports use the subpath @mariozechner/pi-coding-agent/extensions/nity/bridge. See the pi-coding-agent SDK docs (opens in a new tab) for the base createAgentSession API.