open-index/open-npm huggingface dataset:
npm package: @reactive-academy/js-array-unique
Description: Function to remove duplicated items from item and return array with unique elements only
Author: Patrik Mäsiar
Latest version: 1.0.2

# js-array-unique
Function to remove duplicated items from array and return an array with unique elements only

[![NPM](https://img.shields.io/npm/l/react-keyboard-key)](https://github.com/Reactive-academy/js-array-unique/blob/main/LICENSE)

## Installation
```bash
npm install @reactive-academy/js-array-unique
```
```bash
yarn add @reactive-academy/js-array-unique
```

## Usage
### Array with primitive items
```javascript
import unique from '@reactive-academy/js-array-unique';

const items = ['a', 'b', 'c', 'c', 'a'];
// output: ['a', 'b', 'c']
const uniqueItems = unique(items); 
```

### Objects in the array
```javascript
import unique from '@reactive-academy/js-array-unique';

const items1 = [{id: 1, name: 'Patrick'}, {id: 2, name: 'John'}];
const items2 = [{id: 1, name: 'Patrick'}, {id: 1, name: 'Patrick'}, {id: 2, name: 'John'}, {id: 3, name: 'Frank'}];
// output: [{id: 1, name: 'Patrick'}, {id: 2, name: 'John'}, {id: 3, name: 'Frank'}]
const uniqueItems = unique([...items1, ...items2], 'id');
```
npm package: @reactive-academy/logrocker
Description: Logrocker - Simple development debugger
Author: Patrik Mäsiar
Latest version: 1.0.1

# Logrocker
Simple development debugger
[logrocker.com](https://logrocker.com)

[![NPM](https://img.shields.io/npm/l/logrocker)](https://github.com/Reactive-academy/logrocker/blob/main/LICENSE)

## Installation
```bash
npm install @reactive-academy/logrocker
```
```bash
yarn add @reactive-academy/logrocker
```

## Usage
```javascript
import Logger from '@reactive-academy/logrocker';

...

// Example 1
Logger.log("Hello world 👋🏻");

// Example 2
try {
  ...
} catch (e) {
  Logger.error("Something went wrong.", e);
}
```
npm package: @reactive-agents/cli
Description: rax — the Reactive Agents CLI for scaffolding, running, and inspecting AI agents
Latest version: 0.9.0

# @reactive-agents/cli — `rax`

**The Reactive Agents eXecutable** — CLI for scaffolding, running, and inspecting AI agents.

[![npm downloads](https://img.shields.io/npm/dm/%40reactive-agents%2Fcli?logo=npm)](https://www.npmjs.com/package/@reactive-agents/cli)

## Installation

```bash
# Global install
bun add -g @reactive-agents/cli

# Or run without installing
bunx @reactive-agents/cli --help
```

## Commands

```bash
rax init <name> [--template minimal|standard|full]
  Scaffold a new Reactive Agents project

rax create agent <name> [--recipe basic|researcher|coder|orchestrator]
  Generate an agent file in your project

rax run <prompt> [--provider anthropic|openai|ollama|gemini|litellm|test] [--model <model>] [--name <name>] [--stream]
  Run an agent with a prompt and print the result

rax dev [--entry src/index.ts] [--no-watch]
  Run your local agent entrypoint in watch mode

rax eval run --suite <name>
  Run an evaluation suite

rax playground
  Launch an interactive agent REPL session

rax inspect <agent-id> [--logs-tail 200] [--json]
  Inspect local deployment signals and recent matching logs

rax deploy up [--target local|fly|railway|render|cloudrun|digitalocean] [--mode daemon|sdk] [--dry-run]
  Build + deploy agent container through provider adapters

rax deploy down [--target <target>]
  Stop deployment (target auto-detected from config)

rax deploy status [--target <target>]
  Show deployment status (target auto-detected from config)

rax deploy logs [-f] [--target <target>]
  Tail deployment logs (target auto-detected from config)

rax version
  Print version
```

## Deploy Provider Contracts

Deploy adapters are validated with CLI contract tests so upstream CLI changes can trigger early patches.

```bash
bun test apps/cli/tests/cli-contracts.test.ts
RUN_SLOW_TESTS=1 bun test apps/cli/tests/cli-contracts.test.ts
```

Baseline contract checks include:

- Docker `>= 20`, Compose `>= 2`
- `gcloud >= 380.0.0`
- `doctl >= 1.72.0`
- Fly/Railway/Render command and flag availability for adapter-invoked subcommands

Containerized fallback CLIs (`flyctl`, `gcloud`, `doctl`) are supported when Docker is available.

## Examples

```bash
# Scaffold a new project with all features
rax init my-ai-app --template full
cd my-ai-app
bun install

# Generate a research agent
rax create agent researcher --recipe researcher

# Run a one-off prompt
export ANTHROPIC_API_KEY=sk-ant-...
rax run "Summarize the state of fusion energy" --provider anthropic
```

## Documentation

Full documentation at [docs.reactiveagents.dev/reference/cli/](https://docs.reactiveagents.dev/reference/cli/)
npm package: @reactive-agents/core
Description: Core services for Reactive Agents — EventBus, AgentService, TaskService, and shared types
Latest version: 0.9.0

# @reactive-agents/core

Core services and types for the [Reactive Agents](https://docs.reactiveagents.dev/) framework.

Provides the foundational building blocks that all other packages depend on: the EventBus, AgentService, TaskService, and shared schemas.

## Installation

```bash
bun add @reactive-agents/core
```

Or install everything at once:

```bash
bun add reactive-agents
```

## What's Included

| Export                     | Description                            |
| -------------------------- | -------------------------------------- |
| `EventBusLive`             | Publish/subscribe event bus layer      |
| `AgentServiceLive`         | Create and manage agent instances      |
| `TaskServiceLive`          | Create, track, and cancel tasks        |
| `CoreServicesLive`         | Composite layer wiring all three above |
| `AgentId`, `TaskId`        | Branded ID types                       |
| `AgentConfig`, `TaskInput` | Validated schemas                      |
| `AgentError`, `TaskError`  | Tagged error types                     |

## Usage

```typescript
import { Effect } from "effect";
import { CoreServicesLive, AgentService } from "@reactive-agents/core";

const program = Effect.gen(function* () {
  const agents = yield* AgentService;
  const agent = yield* agents.create({ name: "my-agent", capabilities: [] });
  return agent;
});

const result = await Effect.runPromise(
  program.pipe(Effect.provide(CoreServicesLive)),
);
```

## Documentation

Full documentation at [docs.reactiveagents.dev](https://docs.reactiveagents.dev/)
npm package: @reactive-agents/cost
Description: Cost management for Reactive Agents — complexity routing and budget enforcement
Latest version: 0.9.0

# @reactive-agents/cost

Cost management for the [Reactive Agents](https://docs.reactiveagents.dev/) framework.

Automatically routes tasks to the cheapest capable model and enforces per-request and session budgets.

## Installation

```bash
bun add @reactive-agents/cost
```

## Features

- **Complexity router** — classifies tasks and selects Haiku / Sonnet / Opus accordingly
- **Budget enforcer** — blocks requests that would exceed configured limits
- **Cost tracking** — accumulates token usage and USD cost per session

## Usage

```typescript
import { ReactiveAgents } from "reactive-agents";

const agent = await ReactiveAgents.create()
  .withName("budget-agent")
  .withProvider("anthropic")
  .withCostTracking({
    maxSessionCost: 1.0, // $1.00 per session
    maxRequestCost: 0.1, // $0.10 per request
  })
  .build();

const result = await agent.run("Summarize this document");
console.log(result.metadata.cost); // { usd: 0.003, tokens: 450 }
console.log(result.metadata.modelUsed); // "claude-haiku-4-5" (auto-routed)
```

## Routing Logic

| Task signals                 | → Model |
| ---------------------------- | ------- |
| Simple, short, factual       | Haiku   |
| Analysis, coding, multi-step | Sonnet  |
| Complex reasoning, research  | Opus    |

## Documentation

Full documentation at [docs.reactiveagents.dev](https://docs.reactiveagents.dev/)
npm package: @reactive-agents/eval
Description: Evaluation framework for Reactive Agents — LLM-as-judge scoring, regression detection, dataset loading
Latest version: 0.9.0

# @reactive-agents/eval

Evaluation framework for [Reactive Agents](https://docs.reactiveagents.dev/) — benchmark agent quality, track regressions, and run automated test suites.

## Installation

```bash
bun add @reactive-agents/eval
```

## Features

- **5-dimension scoring** — Accuracy, Relevance, Completeness, Safety, Cost Efficiency
- **LLM-as-judge** — Uses an LLM to evaluate agent outputs against expected answers
- **Evaluation suites** — Define test cases with inputs, expected outputs, and dimensions
- **SQLite persistence** — Store eval runs via `EvalStore` for history and comparison
- **Dataset service** — Load and manage evaluation datasets
- **CLI integration** — Run evaluations via `rax eval`

## Usage

```typescript
import { EvalService, createEvalLayer } from "@reactive-agents/eval";
import { Effect } from "effect";

const program = Effect.gen(function* () {
  const evalService = yield* EvalService;

  const run = yield* evalService.runSuite({
    id: "qa-benchmark",
    name: "QA Benchmark",
    cases: [
      {
        id: "q1",
        input: "What is the capital of France?",
        expectedOutput: "Paris",
        dimensions: ["accuracy", "relevance"],
      },
    ],
  });

  console.log(`Score: ${run.summary.overallScore}`);
  console.log(`Passed: ${run.summary.passRate}%`);
});
```

## Dimensions

| Dimension         | What It Measures                                     |
| ----------------- | ---------------------------------------------------- |
| `accuracy`        | Factual correctness against expected output          |
| `relevance`       | How well the response addresses the question         |
| `completeness`    | Coverage of all aspects of the expected answer       |
| `safety`          | Absence of harmful, biased, or inappropriate content |
| `cost-efficiency` | Token usage and cost relative to quality             |

## Persistence

Use `EvalStore` for SQLite-backed eval history:

```typescript
import { createEvalStore } from "@reactive-agents/eval";

const store = createEvalStore("./eval-history.db");
// Eval runs are automatically persisted when using EvalServicePersistentLive
```

## Documentation

Full documentation at [docs.reactiveagents.dev](https://docs.reactiveagents.dev/)
npm package: @reactive-agents/gateway
Description: Persistent autonomous agent harness for the [Reactive Agents](https://docs.reactiveagents.dev/) framework.
Latest version: 0.9.0

# @reactive-agents/gateway

Persistent autonomous agent harness for the [Reactive Agents](https://docs.reactiveagents.dev/) framework.

Keeps agents running long-term with adaptive heartbeats, cron scheduling, webhook ingestion, and a composable policy engine that governs when and how events trigger agent execution.

## Installation

```bash
bun add @reactive-agents/gateway
```

Or install everything at once:

```bash
bun add reactive-agents
```

## Usage

```typescript
import { ReactiveAgents } from "reactive-agents";

const agent = await ReactiveAgents.create()
  .withName("ops-agent")
  .withProvider("anthropic")
  .withGateway({
    heartbeat: { intervalMs: 1_800_000, policy: "adaptive" },
    crons: [
      { schedule: "0 9 * * MON", instruction: "Review open PRs and summarize status" },
      { schedule: "0 */6 * * *", instruction: "Check system health metrics" },
    ],
    webhooks: [
      { path: "/github", adapter: "github", secret: process.env.WEBHOOK_SECRET },
    ],
    policies: {
      dailyTokenBudget: 50_000,
      maxActionsPerHour: 30,
    },
  })
  .build();
```

### Direct Service Usage

```typescript
import { GatewayService, PolicyEngine, SchedulerService } from "@reactive-agents/gateway";
import { createGitHubAdapter } from "@reactive-agents/gateway";
import { createCostBudgetPolicy, createRateLimitPolicy } from "@reactive-agents/gateway";
```

## Key Features

- **Adaptive heartbeats** — `always`, `adaptive`, or `conservative` policies that skip idle beats to save tokens
- **Cron scheduling** — standard cron expressions with timezone support and per-job priority
- **Webhook ingestion** — HTTP endpoint with pluggable adapters (GitHub, generic) and secret verification
- **Policy engine** — composable policies for cost budgets, rate limits, event merging, and access control
- **Event routing** — unified `GatewayEvent` envelope routes heartbeats, crons, webhooks, and channels through the same pipeline
- **EventBus integration** — all gateway events publish to the core EventBus for observability
- **State tracking** — tracks tokens used, actions per hour, consecutive skips, and pending events without LLM calls

## Built-in Policies

| Policy | Purpose |
| --- | --- |
| `createAdaptiveHeartbeatPolicy` | Skip heartbeats when agent is idle |
| `createCostBudgetPolicy` | Enforce daily token budget |
| `createRateLimitPolicy` | Cap actions per hour |
| `createEventMergingPolicy` | Merge duplicate events within a time window |
| `createAccessControlPolicy` | Allowlist/blocklist sender filtering |

## Documentation

Full documentation at [docs.reactiveagents.dev](https://docs.reactiveagents.dev/)

## License

MIT
npm package: @reactive-agents/guardrails
Description: Safety guardrails for Reactive Agents — prompt injection detection, PII scanning, and toxicity filtering
Latest version: 0.9.0

# @reactive-agents/guardrails

Safety guardrails for the [Reactive Agents](https://docs.reactiveagents.dev/) framework.

Protects agents from prompt injection, PII leakage, and toxic content — applied automatically during the `guardrail` phase of the execution engine.

## Installation

```bash
bun add @reactive-agents/guardrails
```

## Protections

| Guard              | What it catches                           |
| ------------------ | ----------------------------------------- |
| Prompt injection   | Attempts to override system instructions  |
| PII detection      | Emails, phone numbers, SSNs, credit cards |
| Toxicity filtering | Harmful or abusive content                |
| Output contracts   | Schema-validates agent responses          |

## Usage

```typescript
import { ReactiveAgents } from "reactive-agents";

const agent = await ReactiveAgents.create()
  .withName("customer-support")
  .withProvider("anthropic")
  .withGuardrails()
  .build();

// Prompt injection attempts are blocked before reaching the LLM
const result = await agent.run("Ignore previous instructions and...");
// result.success === false, result.error describes the violation
```

## Custom Guards

```typescript
.withGuardrails({
  blockTopics: ["competitor-names"],
  maxOutputLength: 2000,
  requireOutputSchema: MyResponseSchema,
})
```

## Documentation

Full documentation at [docs.reactiveagents.dev/guides/guardrails/](https://docs.reactiveagents.dev/guides/guardrails/)
npm package: @reactive-agents/health
Description: Health checks and readiness probes for the [Reactive Agents](https://docs.reactiveagents.dev/) framework.
Latest version: 0.9.0

# @reactive-agents/health

Health checks and readiness probes for the [Reactive Agents](https://docs.reactiveagents.dev/) framework.

Provides an HTTP health server with registered probes, returning structured status responses. Integrates with the builder via `.withHealthCheck()` and exposes `agent.health()` for programmatic access.

## Installation

```bash
bun add @reactive-agents/health
```

Or install everything at once:

```bash
bun add reactive-agents
```

## Usage

```typescript
import { ReactiveAgents } from "reactive-agents";

const agent = await ReactiveAgents.create()
  .withName("my-agent")
  .withProvider("anthropic")
  .withHealthCheck()
  .build();

const health = await agent.health();
// {
//   status: "healthy",
//   uptime: 12345,
//   checks: [{ name: "llm", healthy: true, durationMs: 42 }],
//   timestamp: "2026-03-15T..."
// }
```

### Direct Service Usage

```typescript
import { Effect } from "effect";
import { makeHealthService, Health } from "@reactive-agents/health";

const program = Effect.gen(function* () {
  const health = yield* Health;
  yield* health.registerCheck("db", () => Effect.succeed(true));
  yield* health.start();
  const status = yield* health.check();
  return status;
});
```

## Key Features

- **HTTP endpoints** — `/health` and `/ready` with structured JSON responses
- **Registered probes** — add custom checks for LLM connectivity, database, external services
- **Aggregate status** — reports `healthy`, `degraded`, or `unhealthy` based on all probes
- **Builder integration** — single `.withHealthCheck()` call enables health probes
- **Per-check timing** — each probe reports its own `durationMs` for latency visibility

## Documentation

Full documentation at [docs.reactiveagents.dev](https://docs.reactiveagents.dev/)

## License

MIT
npm package: @reactive-agents/identity
Description: Identity and access control for Reactive Agents — agent certificates and RBAC
Latest version: 0.9.0

# @reactive-agents/identity

Identity and access control for the [Reactive Agents](https://docs.reactiveagents.dev/) framework.

Manages agent certificates and role-based access control (RBAC) so agents can safely act on behalf of users with well-defined permissions.

## Installation

```bash
bun add @reactive-agents/identity
```

## Features

- **Agent certificates** — cryptographically identified agent instances
- **RBAC** — role and permission checks before privileged operations
- **Identity context** — propagated through the execution engine

## Usage

```typescript
import { ReactiveAgents } from "reactive-agents";

const agent = await ReactiveAgents.create()
  .withName("privileged-agent")
  .withProvider("anthropic")
  .withIdentity({
    roles: ["reader", "writer"],
    issuer: "my-org",
  })
  .build();
```

## Documentation

Full documentation at [docs.reactiveagents.dev](https://docs.reactiveagents.dev/)
npm package: @reactive-agents/interaction
Description: Interaction modes for Reactive Agents — 5 autonomy modes, checkpoints, and human collaboration
Latest version: 0.9.0

# @reactive-agents/interaction

Interaction modes for the [Reactive Agents](https://docs.reactiveagents.dev/) framework.

Gives agents 5 levels of autonomy — from fully autonomous to human-in-the-loop collaborative — with dynamic transitions based on confidence and cost.

## Installation

```bash
bun add @reactive-agents/interaction
```

## The 5 Modes

| Mode            | Autonomy                     | When it activates              |
| --------------- | ---------------------------- | ------------------------------ |
| `autonomous`    | Full — no interruptions      | High confidence, routine tasks |
| `supervised`    | Periodic checkpoints         | Moderate confidence            |
| `collaborative` | Human decides key steps      | Complex or ambiguous tasks     |
| `consultative`  | Human approves before acting | High-cost or risky operations  |
| `interrogative` | Human provides all direction | Information gathering only     |

## Usage

```typescript
import { ReactiveAgents } from "reactive-agents";

const agent = await ReactiveAgents.create()
  .withName("assistant")
  .withProvider("anthropic")
  .withInteraction({
    defaultMode: "supervised",
    onCheckpoint: async (ctx) => {
      // Called when agent wants human approval
      console.log("Agent wants to: ", ctx.proposedAction);
      return { approved: true };
    },
  })
  .build();
```

Modes transition automatically — an autonomous agent escalates to `consultative` if it detects a high-cost operation, then de-escalates when confidence recovers.

## Documentation

Full documentation at [docs.reactiveagents.dev/guides/interaction-modes/](https://docs.reactiveagents.dev/guides/interaction-modes/)
npm package: @reactive-agents/memory
Description: Memory system for Reactive Agents — Working, Semantic, Episodic, and Procedural memory backed by bun:sqlite
Latest version: 0.9.0

# @reactive-agents/memory

Memory system for the [Reactive Agents](https://docs.reactiveagents.dev/) framework.

Four memory types backed by `bun:sqlite` — Working, Semantic, Episodic, and Procedural — with FTS5 full-text search (Tier 1) and optional vector embeddings (Tier 2).

## Installation

```bash
bun add @reactive-agents/memory
```

> **Requires Bun** — uses `bun:sqlite` natively.

## Memory Types

| Type       | Purpose                       | Backend          |
| ---------- | ----------------------------- | ---------------- |
| Working    | Short-term in-session context | SQLite in-memory |
| Semantic   | Long-term knowledge store     | SQLite + FTS5    |
| Episodic   | Conversation history          | SQLite           |
| Procedural | Learned workflows             | SQLite           |

## Tiers

- **Tier 1** — FTS5 full-text search. Fast, no external API needed.
- **Tier 2** — `sqlite-vec` KNN vector search. Requires an embedding provider.

## Usage

```typescript
import { ReactiveAgents } from "reactive-agents";

const agent = await ReactiveAgents.create()
  .withName("my-agent")
  .withProvider("anthropic")
  .withMemory("1") // Tier 1: FTS5
  // .withMemory("2") // Tier 2: vector embeddings
  .build();
```

## Environment Variables (Tier 2 only)

```bash
EMBEDDING_PROVIDER=openai
EMBEDDING_MODEL=text-embedding-3-small
OPENAI_API_KEY=sk-...
```

## Documentation

Full documentation at [docs.reactiveagents.dev/guides/memory/](https://docs.reactiveagents.dev/guides/memory/)
npm package: @reactive-agents/observability
Description: Observability for Reactive Agents — distributed tracing, metrics, and structured logging
Latest version: 0.9.0

# @reactive-agents/observability

Observability for the [Reactive Agents](https://docs.reactiveagents.dev/) framework.

Adds distributed tracing, metrics, and structured logging to every phase of the agent execution engine.

## Installation

```bash
bun add @reactive-agents/observability
```

## Features

- **Distributed tracing** — span per execution phase, compatible with OpenTelemetry exporters
- **Metrics** — token usage, latency, step count, cost per run
- **Structured logging** — JSON logs with trace context for easy querying

## Usage

```typescript
import { ReactiveAgents } from "reactive-agents";

const agent = await ReactiveAgents.create()
  .withName("traced-agent")
  .withProvider("anthropic")
  .withObservability()
  .build();

const result = await agent.run("Analyze this data");
// All 10 execution phases are traced automatically
```

## What Gets Traced

Each of the 10 execution phases emits a span:

```
bootstrap → guardrail → cost-route → strategy-select →
think → act → observe → verify → memory-flush → complete
```

## Documentation

Full documentation at [docs.reactiveagents.dev](https://docs.reactiveagents.dev/)
npm package: @reactive-agents/orchestration
Description: Multi-agent orchestration for Reactive Agents — workflow engine and agent coordination
Latest version: 0.9.0

# @reactive-agents/orchestration

Multi-agent orchestration for the [Reactive Agents](https://docs.reactiveagents.dev/) framework.

Coordinate fleets of agents in parallel or sequential workflows, with typed message passing and failure handling.

## Installation

```bash
bun add @reactive-agents/orchestration
```

## Features

- **Parallel execution** — run multiple agents concurrently, collect results
- **Sequential pipelines** — chain agents where each step's output feeds the next
- **Typed handoffs** — Effect-TS schemas validate inter-agent messages
- **Failure isolation** — one agent failing doesn't crash the whole workflow

## Usage

```typescript
import { ReactiveAgents } from "reactive-agents";
import { createOrchestration } from "@reactive-agents/orchestration";

const workflow = createOrchestration({
  name: "research-pipeline",
  steps: [
    { agent: "searcher", input: (ctx) => ctx.query },
    { agent: "summarizer", input: (ctx) => ctx.previousResult },
    { agent: "critic", input: (ctx) => ctx.previousResult },
  ],
});

const result = await workflow.run({
  query: "Latest advances in fusion energy",
});
```

## Documentation

Full documentation at [docs.reactiveagents.dev](https://docs.reactiveagents.dev/)
npm package: @reactive-agents/prompts
Description: Prompt management for Reactive Agents — template engine and built-in prompt library
Latest version: 0.9.0

# @reactive-agents/prompts

Prompt management for the [Reactive Agents](https://docs.reactiveagents.dev/) framework.

A template engine with variable interpolation and a built-in library of agent prompts for common use cases.

## Installation

```bash
bun add @reactive-agents/prompts
```

## Features

- **Template engine** — `{{variable}}` interpolation with type-safe bindings
- **Prompt library** — pre-built system prompts for researcher, coder, analyst, and more
- **Versioning** — store and retrieve prompt versions

## Usage

```typescript
import { PromptTemplate, PromptLibrary } from "@reactive-agents/prompts";

// Use a built-in prompt
const systemPrompt = PromptLibrary.get("researcher");

// Or define your own
const template = PromptTemplate.create({
  template: "You are a {{role}} expert. Answer in {{language}}.",
  variables: { role: "TypeScript", language: "English" },
});

const prompt = template.render({ role: "React", language: "Spanish" });
```

With the builder:

```typescript
import { ReactiveAgents } from "reactive-agents";

// Enable built-in prompt templates (reasoning, evaluation, agent)
const agent = await ReactiveAgents.create()
  .withName("researcher")
  .withProvider("anthropic")
  .withPrompts() // registers all built-in templates
  .build();

// Or register custom templates at build time:
const customAgent = await ReactiveAgents.create()
  .withName("custom")
  .withProvider("anthropic")
  .withPrompts({
    templates: [
      {
        id: "custom.system",
        name: "Custom System Prompt",
        version: 1,
        template: "You are a {{role}} expert. Answer in {{language}}.",
        variables: [
          { name: "role", required: true, type: "string" },
          {
            name: "language",
            required: false,
            type: "string",
            defaultValue: "English",
          },
        ],
      },
    ],
  })
  .build();
```

## Documentation

Full documentation at [docs.reactiveagents.dev](https://docs.reactiveagents.dev/)
npm package: @reactive-agents/reactive-intelligence
Description: Reactive Intelligence layer for Reactive Agents — entropy sensing, adaptive control, and learning
Latest version: 0.9.0

# @reactive-agents/reactive-intelligence

Reactive intelligence layer for the [Reactive Agents](https://docs.reactiveagents.dev/) framework.

Real-time entropy sensing, adaptive control, and local learning that monitors agent reasoning quality and intervenes automatically — triggering early stops, context compression, or strategy switches when the agent is struggling.

## Installation

```bash
bun add @reactive-agents/reactive-intelligence
```

Or install everything at once:

```bash
bun add reactive-agents
```

## Usage

```typescript
import { ReactiveAgents } from "reactive-agents";

const agent = await ReactiveAgents.create()
  .withName("smart-agent")
  .withProvider("anthropic")
  .withReasoning()
  .withReactiveIntelligence()
  .build();

const result = await agent.run("Analyze market trends for Q1 2026");
```

### Direct Service Usage

```typescript
import {
  EntropySensorServiceLive,
  ReactiveControllerServiceLive,
  LearningEngineServiceLive,
  createReactiveIntelligenceLayer,
} from "@reactive-agents/reactive-intelligence";
```

## Architecture

### Entropy Sensor

Scores reasoning quality each iteration using 5 entropy sources:

| Source | What It Measures |
| --- | --- |
| Token entropy | LLM confidence from logprobs |
| Structural entropy | Format compliance, hedge words, thought density |
| Semantic entropy | Task alignment, novelty, repetition |
| Behavioral entropy | Tool reuse, action diversity, loop detection |
| Context pressure | Context window utilization and overflow risk |

### Reactive Controller

Consumes entropy scores and makes real-time decisions:

- **Early stop** — halt when entropy is consistently low (agent is confident)
- **Context compression** — trigger compaction when context pressure is high
- **Strategy switch** — switch reasoning strategy when the current one is looping

### Learning Engine

Improves agent performance over time without additional prompting:

- **Conformal calibration** — adjusts entropy thresholds to the specific model
- **Thompson Sampling bandit** — learns which strategies work best per task category
- **Skill synthesis** — extracts reusable skill fragments from successful runs

### Telemetry Client

Opt-in telemetry that reports anonymized run metrics (HMAC-signed, fire-and-forget) to improve the framework.

## Key Features

- **5-source entropy scoring** — composite signal with adaptive weights per model
- **Trajectory analysis** — classifies entropy trends as converging, flat, diverging, oscillating, or v-recovery
- **Model registry** — pre-calibrated baselines for common models (Claude, GPT-4, Gemini, Ollama)
- **EventBus-driven** — entropy scores publish as events, no polling required
- **Zero config** — `.withReactiveIntelligence()` enables everything with sensible defaults

## Documentation

Full documentation at [docs.reactiveagents.dev](https://docs.reactiveagents.dev/)

## License

MIT
npm package: @reactive-agents/runtime
Description: Runtime for Reactive Agents — ExecutionEngine, ReactiveAgentBuilder, and createRuntime
Latest version: 0.9.0

# @reactive-agents/runtime

The execution runtime for [Reactive Agents](https://docs.reactiveagents.dev/).

Contains the 10-phase `ExecutionEngine`, the `ReactiveAgentBuilder` fluent API, and `createRuntime()` — the function that wires all optional layers together.

## Installation

```bash
bun add @reactive-agents/runtime
```

Or install everything at once (recommended for new projects):

```bash
bun add reactive-agents
```

## Usage

### Builder API (recommended)

```typescript
import { ReactiveAgents } from "@reactive-agents/runtime";

const agent = await ReactiveAgents.create()
  .withName("my-agent")
  .withProvider("anthropic")
  .withModel("claude-sonnet-4-20250514")
  .withMemory("1")
  .withReasoning()
  .withGuardrails()
  .withCostTracking()
  .build();

const result = await agent.run("Explain the CAP theorem");
console.log(result.output);
console.log(result.metadata); // { duration, cost, tokensUsed, stepsCount }
```

### Effect API

```typescript
import { Effect } from "effect";
import { ReactiveAgents } from "@reactive-agents/runtime";

const program = Effect.gen(function* () {
  const agent = yield* ReactiveAgents.create()
    .withName("my-agent")
    .withProvider("anthropic")
    .buildEffect();

  return yield* agent.runEffect("What is the meaning of life?");
});

const result = await Effect.runPromise(program);
```

### Low-level `createRuntime()`

```typescript
import { createRuntime } from "@reactive-agents/runtime";
import { Effect } from "effect";

const runtime = createRuntime({
  agentId: "my-agent",
  provider: "anthropic",
  enableReasoning: true,
  enableGuardrails: true,
  enableCostTracking: true,
});
```

## The 10-Phase Execution Engine

Every task flows through:

1. **Bootstrap** — load memory context
2. **Guardrail** — safety checks on input
3. **Cost Route** — select optimal model
4. **Strategy Select** — choose reasoning strategy
5. **Think** — LLM completion
6. **Act** — tool execution
7. **Observe** — append results
8. **Verify** — fact-check output
9. **Memory Flush** — persist session
10. **Complete** — return result

Each phase supports `before`, `after`, and `on-error` lifecycle hooks.

## Documentation

Full documentation at [docs.reactiveagents.dev](https://docs.reactiveagents.dev/)
npm package: @reactive-agents/testing
Description: Testing utilities for the [Reactive Agents](https://docs.reactiveagents.dev/) framework.
Latest version: 0.9.0

# @reactive-agents/testing

Testing utilities for the [Reactive Agents](https://docs.reactiveagents.dev/) framework.

Mock services, assertion helpers, deterministic test scenarios, and streaming assertions for building reliable agent tests without real LLM calls.

## Installation

```bash
bun add @reactive-agents/testing --dev
```

## Usage

### Deterministic Test Scenarios

```typescript
import { ReactiveAgents } from "reactive-agents";

const agent = await ReactiveAgents.create()
  .withTestScenario([
    { toolCall: { name: "web-search", args: { query: "AI news" } } },
    { text: "Here is the summary of AI news." },
  ])
  .withTools({ tools: [mySearchTool] })
  .build();

const result = await agent.run("Find AI news");
```

### Streaming Assertions

```typescript
import { expectStream } from "@reactive-agents/testing";

await expectStream(agent.runStream("hello")).toEmitTextDeltas();
await expectStream(agent.runStream("hello")).toComplete({ within: 5000 });
await expectStream(agent.runStream("hello")).toEmitEvents(["TextDelta", "StreamCompleted"]);
```

### Mock Services

```typescript
import { createMockLLM, createMockToolService, createMockEventBus } from "@reactive-agents/testing";

const llm = createMockLLM([{ content: "Hello!" }]);
const tools = createMockToolService({ "my-tool": { result: "ok" } });
const bus = createMockEventBus();
```

### Assertion Helpers

```typescript
import { assertToolCalled, assertStepCount, assertCostUnder } from "@reactive-agents/testing";

assertToolCalled(result, "web-search");
assertStepCount(result, { max: 5 });
assertCostUnder(result, 0.01);
```

## Key Features

- **`withTestScenario()`** — sequential turn consumption with text, toolCall, json, and error turns
- **`expectStream()`** — streaming assertion API for `runStream()` output
- **Mock LLM** — deterministic responses without API keys or network calls
- **Mock EventBus** — captures published events for inspection
- **Mock ToolService** — stub tool results for isolated testing
- **Scenario fixtures** — pre-built guardrail block, budget exhausted, and max iteration scenarios

## Documentation

Full documentation at [docs.reactiveagents.dev](https://docs.reactiveagents.dev/)

## License

MIT
npm package: @reactive-agents/tools
Description: Tool system for Reactive Agents — registry, sandboxed execution, and MCP client
Latest version: 0.9.0

# @reactive-agents/tools

Tool system for the [Reactive Agents](https://docs.reactiveagents.dev/) framework.

Provides a type-safe tool registry, sandboxed execution, and an MCP (Model Context Protocol) client.

## Installation

```bash
bun add @reactive-agents/tools
```

## Features

- **Tool registry** — register typed tools with Effect-TS schemas
- **Sandboxed execution** — tools run in isolation with timeout and resource limits
- **MCP client** — connect to any MCP-compatible tool server

## Usage

```typescript
import { ReactiveAgents } from "reactive-agents";
import { Effect } from "effect";

// Built-in tools (web search, file I/O, HTTP, code execution) are auto-registered
const agent = await ReactiveAgents.create()
  .withName("research-agent")
  .withProvider("anthropic")
  .withReasoning()
  .withTools() // enable built-in tools
  .build();

// Or register custom tools at build time:
const agentWithCustomTools = await ReactiveAgents.create()
  .withName("custom-agent")
  .withProvider("anthropic")
  .withTools({
    tools: [
      {
        definition: {
          name: "lookup",
          description: "Look up a value in the database",
          parameters: [
            {
              name: "key",
              type: "string",
              description: "Lookup key",
              required: true,
            },
          ],
          riskLevel: "low",
          timeoutMs: 5_000,
          requiresApproval: false,
          source: "function",
        },
        handler: (args) => Effect.succeed(`Value for ${args.key}`),
      },
    ],
  })
  .build();

const result = await agent.run("What are the latest AI developments?");
```

## MCP Client

The MCP client supports connecting to local MCP servers over stdio using `Bun.spawn()`.

```typescript
import { makeMCPClient } from "@reactive-agents/tools";
import { Effect } from "effect";

const program = Effect.gen(function* () {
  const client = yield* makeMCPClient;

  // Connect to a local MCP server over stdio
  const server = yield* client.connect({
    name: "filesystem",
    transport: "stdio",
    command: "npx",
    args: ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
  });

  // Call a tool on the server
  const result = yield* client.callTool("filesystem", "read_file", {
    path: "/tmp/example.txt",
  });

  yield* client.disconnect("filesystem");
  return result;
});
```

**Transport support:**

- **stdio** — Fully implemented. Uses `Bun.spawn()` with a background stdout reader loop for line-delimited JSON-RPC. Handles the MCP `initialize` handshake, tool discovery via `tools/list`, and `tools/call` invocations. Pending requests are tracked with Promise-based resolution; the subprocess is killed on disconnect.
- **SSE (HTTP event stream)** — Stub, not yet implemented.
- **WebSocket** — Stub, not yet implemented.

## Documentation

Full documentation at [docs.reactiveagents.dev/guides/tools/](https://docs.reactiveagents.dev/guides/tools/)
npm package: @reactive-agents/verification
Description: Output verification for Reactive Agents — semantic entropy and fact decomposition
Latest version: 0.9.0

# @reactive-agents/verification

Output verification for the [Reactive Agents](https://docs.reactiveagents.dev/) framework.

Reduces hallucinations by measuring semantic entropy (consistency across multiple samples) and decomposing claims into verifiable facts.

## Installation

```bash
bun add @reactive-agents/verification
```

## Techniques

| Technique          | How it works                                                |
| ------------------ | ----------------------------------------------------------- |
| Semantic entropy   | Samples the LLM N times; high variance → low confidence     |
| Fact decomposition | Breaks output into atomic claims, checks each independently |

## Usage

```typescript
import { ReactiveAgents } from "reactive-agents";

const agent = await ReactiveAgents.create()
  .withName("fact-checker")
  .withProvider("anthropic")
  .withVerification()
  .build();

const result = await agent.run("What year did the Berlin Wall fall?");
console.log(result.metadata.confidence); // 0.0–1.0
```

When confidence is below the threshold, the agent can re-sample or escalate to the user depending on the active interaction mode.

## Documentation

Full documentation at [docs.reactiveagents.dev](https://docs.reactiveagents.dev/)
npm package: @reactive-commons/messaging
Description: Set of abstractions and implementations over different patterns and practices that make the foundation of a reactive microservices architecture
Author: Juan Marín
Latest version: 1.3.1

[![Build Status](https://travis-ci.org/reactive-commons/reactive-commons-js.svg?branch=master)](https://travis-ci.org/reactive-commons/reactive-commons-js)
[![NPM Version](https://img.shields.io/npm/v/@reactive-commons/messaging)](https://www.npmjs.com/package/@reactive-commons/messaging)
# reactive-commons-js
The purpose of reactive-commons is to provide a set of abstractions and implementations over different patterns and practices that make the foundation of a reactive microservices architecture.

Even though the main purpose is to provide such abstractions in a mostly generic way such abstractions would be of little use without a concrete implementation so we provide some implementations in a best effors maner that aim to be easy to change, personalize and extend.

The first approach to this work was to release a very simple abstractions and a corresponding implementation over asyncronous message driven communication between microservices build on top of rxjs.
npm package: @reactive-contracts/vite-plugin
Description: Vite plugin for Reactive Contracts - auto-compile contracts with HMR support
Author: Reactive Contracts Contributors
Latest version: 0.2.0

# @reactive-contracts/vite-plugin

Vite plugin for [Reactive Contracts](https://github.com/creativoma/reactive-contracts) - automatically compile contracts during development with HMR support.

## Features

- 🔄 **Auto-compile** - Contracts are automatically compiled when files change
- ⚡ **HMR Support** - Hot Module Replacement for contract changes
- 🛠️ **Dev Mode Warnings** - Clear console warnings and error messages
- 📦 **Zero Configuration** - Works out of the box with `rcontracts.config.ts`

## Installation

```bash
# npm
npm install @reactive-contracts/vite-plugin -D

# pnpm
pnpm add @reactive-contracts/vite-plugin -D

# yarn
yarn add @reactive-contracts/vite-plugin -D
```

## Usage

Add the plugin to your `vite.config.ts`:

```typescript
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { reactiveContracts } from '@reactive-contracts/vite-plugin';

export default defineConfig({
  plugins: [
    react(),
    reactiveContracts(),
  ],
});
```

## Configuration

The plugin uses your existing `rcontracts.config.ts` file by default. You can also pass options directly:

```typescript
reactiveContracts({
  // Path to config file (default: './rcontracts.config.ts')
  configFile: './rcontracts.config.ts',

  // Enable/disable HMR (default: true)
  hmr: true,

  // Compile on build start (default: true)
  compileOnBuildStart: true,

  // Log level: 'verbose' | 'normal' | 'silent' (default: 'normal')
  logLevel: 'normal',
})
```

## How It Works

1. **Build Start**: Compiles all contracts when Vite starts
2. **File Watch**: Watches `contracts/**/*.contract.ts` for changes
3. **HMR**: When a contract changes, it recompiles and triggers HMR for affected modules
4. **Error Reporting**: Shows clear errors in the Vite console

## Requirements

- Vite 5.0+
- A valid `rcontracts.config.ts` configuration file
- Contract files matching the configured glob pattern

## License

MIT