JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 286
  • Score
    100M100P100Q93661F
  • License PROPRIETARY

Core primitives for NebulaOS (Agent, Workflow, Providers)

Package Exports

  • @nebulaos/core
  • @nebulaos/core/dist/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@nebulaos/core) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

@starya/nebulaos-core

The core of NebulaOS for building AI Agents and complex Workflows. This package provides the essential primitives for orchestration, state management, and model abstraction.

Installation

pnpm add @starya/nebulaos-core

โœจ Features Overview

๐Ÿค– Agent System

  • โœ… Multi-Step Reasoning - Automatic tool calling loops with configurable max steps
  • โœ… Streaming Support - Real-time token streaming with executeStream()
  • โœ… Tool Calling - Function calling with Zod schema validation
  • โœ… Parallel Tool Execution - Execute multiple tools simultaneously
  • โœ… Structured Outputs - JSON mode with schema validation
  • โœ… Memory Management - Pluggable memory implementations (InMemory, Redis, etc.)
  • โœ… Dynamic Instructions - Support for async instruction resolution
  • โœ… Request/Response Interceptors - Middleware for RAG, sanitization, etc.
  • โœ… Multimodal Support - Text + Images (via ContentPart[])

๐Ÿ”„ Workflow Orchestration

  • โœ… Fluent API - Declarative workflow definition (.start().step().finish())
  • โœ… Branching & Parallel - Conditional paths and concurrent execution
  • โœ… State Persistence - Save/resume workflow state (requires state store)
  • โœ… Retry Policies - Exponential/Linear backoff with configurable attempts
  • โœ… Input/Output Validation - Zod schema validation at boundaries
  • โœ… Queue Integration - Async workflow execution (requires queue adapter)
  • โœ… Event-Driven - Lifecycle events for monitoring and logging

๐Ÿ“Š Observability & Tracing

  • โœ… Distributed Tracing - Automatic trace/span propagation via AsyncLocalStorage
  • โœ… Event System - Rich lifecycle events (execution:start, llm:call, tool:result, etc.)
  • โœ… Correlation IDs - Track requests across nested operations
  • โœ… Structured Logging - Beautiful console logs with ANSI colors and metadata trees
  • โœ… Log Levels - Configurable (debug, info, warn, error)
  • โœ… Custom Loggers - Implement ILogger for Datadog, CloudWatch, etc.
  • โœ… PII Masking - GDPR/LGPD compliance with pluggable masking

๐Ÿงช Testing & Quality

  • โœ… Provider Compliance Suite - Reusable test suite for model providers
  • โœ… Mock Implementations - MockProvider, MockStateStore for unit tests
  • โœ… Integration Tests - Live API tests with real providers
  • โœ… Type Safety - Full TypeScript support with strict typing
  • โœ… Test Coverage - Comprehensive unit and integration tests

๐Ÿ”Œ Provider System

  • โœ… Provider Abstraction - IModel interface for any LLM (OpenAI, Anthropic, etc.)
  • โœ… Token Usage Tracking - Automatic accumulation across multi-step flows
  • โœ… Streaming Protocol - Unified chunk types (content_delta, tool_call_start, etc.)
  • โœ… Error Handling - Graceful degradation and retry logic

๐Ÿ†• Recent Updates

v0.0.1 - Distributed Tracing & Stream Parity

  • Distributed Tracing: Automatic trace/span propagation across Agent โ†’ Workflow โ†’ Tool chains
  • executeStream() Parity: Full feature parity with execute() including token tracking, events, and max steps fallback
  • Enhanced Logging: Color-coded terminal output with hierarchical metadata display
  • Response Interceptors: Now run only on final responses (not intermediate tool calls)
  • Test Coverage: Expanded to 22 unit tests + 7 integration tests

Core Components

1. Agent (Agent)

The main class that manages the lifecycle of AI interaction.

Key Features

  • Memory-First: Every agent requires a memory implementation (e.g., InMemory) to maintain context.
  • Interceptors: Middleware to modify requests and responses.
    • Request Interceptors: Run before each LLM call. Useful for context injection (RAG).
    • Response Interceptors: Run only on the final response (or when there are no tool calls), ideal for output sanitization and formatting.
  • Streaming: Native support for text and tool call streaming.
  • Observability: Integrated event-based logging system with PII Masking support (GDPR/LGPD).

Complete Example

import { Agent, InMemory, Tool, z } from "@starya/nebulaos-core";
import { OpenAI } from "@starya/nebulaos-openai";

// 1. Tools
const calculator = new Tool({
  id: "calculator",
  description: "Adds two numbers",
  inputSchema: z.object({ a: z.number(), b: z.number() }),
  handler: async (ctx, input) => ({ result: input.a + input.b })
});

// 2. Agent
const agent = new Agent({
  name: "financial-assistant",
  model: new OpenAI({
    apiKey: process.env.OPENAI_API_KEY!,
    model: "gpt-4o"
  }),
  memory: new InMemory(),
  instructions: "You help with financial calculations.",
  tools: [calculator],
  logLevel: "info", // Detailed console logs
  interceptors: {
    response: [
        async (res) => {
            // Format final output to uppercase (example)
            if (res.content) res.content = res.content.toUpperCase();
            return res;
        }
    ]
  }
});

// 3. Execution
await agent.addMessage({ role: "user", content: "How much is 10 + 20?" });
const result = await agent.execute();
console.log(result.content);

๐Ÿ”„ Workflow (Workflow)

Orchestrator for long-running and complex processes, supporting persistence, retries, and validation.

Features

  • Fluent API: Declarative definition (.start().step().branch().finish()).
  • State Persistence: Saves the state of each step (requires stateStore).
  • Resilience: Configurable Retry Policies (Exponential, Linear).
  • Type-Safe: Input and output validation with Zod.

Workflow Example

import { Workflow, MockStateStore } from "@starya/nebulaos-core";
import { z } from "zod";

const workflow = new Workflow({
  id: "order-processing",
  stateStore: new MockStateStore(), // Or real implementation (Redis/Postgres)
  retryPolicy: {
      maxAttempts: 3,
      backoff: "exponential",
      initialDelay: 1000
  }
})
.start(async ({ input }) => {
    console.log("Validating order", input);
    return input;
})
.step("payment", async ({ input }) => {
    // Payment logic
    return { status: "paid", id: input.id };
})
.finish(async ({ input }) => {
    return { message: `Order ${input.id} processed successfully` };
});

// Execution
const result = await workflow.run({ id: 123, total: 500 });

๐Ÿ›ก๏ธ Logging & Observability

The Core emits rich events during execution (execution:start, llm:call, tool:result).

Configuration

The default logger (ConsoleLogger) can be configured via logLevel. For production, you can implement the ILogger interface to send logs to Datadog, CloudWatch, etc.

PII Masking (Privacy)

Protect sensitive data in logs by configuring a piiMasker.

const agent = new Agent({
  // ...
  piiMasker: {
      mask: (text) => text.replace(/\d{3}\.\d{3}\.\d{3}-\d{2}/g, "***") // Example mask
  }
});

๐Ÿงช Testing & Compliance

Package Tests

pnpm test

Provider Compliance Suite

If you are creating a new Provider (e.g., Anthropic), use the compliance suite to ensure full compatibility.

import { runProviderComplianceTests } from "@starya/nebulaos-core/test-utils";

runProviderComplianceTests(() => new MyNewProvider(...), { runLiveTests: true });