network-ai 4.0.12 → 4.0.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,12 +1,12 @@
1
- # Network-AI
1
+ # Network-AI
2
2
 
3
3
  **TypeScript/Node.js multi-agent orchestrator — shared state, guardrails, budgets, and cross-framework coordination**
4
4
 
5
5
  [![CI](https://github.com/jovanSAPFIONEER/Network-AI/actions/workflows/ci.yml/badge.svg)](https://github.com/jovanSAPFIONEER/Network-AI/actions/workflows/ci.yml)
6
6
  [![CodeQL](https://github.com/jovanSAPFIONEER/Network-AI/actions/workflows/codeql.yml/badge.svg)](https://github.com/jovanSAPFIONEER/Network-AI/actions/workflows/codeql.yml)
7
- [![Release](https://img.shields.io/badge/release-v4.0.12-blue.svg)](https://github.com/jovanSAPFIONEER/Network-AI/releases)
7
+ [![Release](https://img.shields.io/badge/release-v4.0.14-blue.svg)](https://github.com/jovanSAPFIONEER/Network-AI/releases)
8
8
  [![npm](https://img.shields.io/npm/dw/network-ai.svg?label=npm%20downloads)](https://www.npmjs.com/package/network-ai)
9
- [![Tests](https://img.shields.io/badge/tests-1216%20passing-brightgreen.svg)](#testing)
9
+ [![Tests](https://img.shields.io/badge/tests-1184%20passing-brightgreen.svg)](#testing)
10
10
  [![Adapters](https://img.shields.io/badge/frameworks-12%20supported-blueviolet.svg)](#adapter-system)
11
11
  [![License](https://img.shields.io/badge/license-MIT-brightgreen.svg)](LICENSE)
12
12
  [![Socket](https://socket.dev/api/badge/npm/package/network-ai)](https://socket.dev/npm/package/network-ai/overview)
@@ -15,13 +15,18 @@
15
15
  [![ClawHub](https://img.shields.io/badge/ClawHub-network--ai-orange.svg)](https://clawhub.ai/skills/network-ai)
16
16
  [![Integration Guide](https://img.shields.io/badge/docs-integration%20guide-informational.svg)](INTEGRATION_GUIDE.md)
17
17
 
18
- Network-AI is a TypeScript/Node.js multi-agent orchestrator for teams that need shared state, guardrails, budgets, and cross-framework coordination.
18
+ Network-AI is a TypeScript/Node.js multi-agent orchestrator that adds coordination, guardrails, and governance to any AI agent stack.
19
19
 
20
- - **Shared blackboard with locking** — atomic commits prevent race conditions and split-brain failures across parallel agents
20
+ - **Shared blackboard with locking** — atomic `propose validate → commit` prevents race conditions and split-brain failures across parallel agents
21
21
  - **Guardrails and budgets** — FSM governance, per-agent token ceilings, HMAC audit trails, and permission gating
22
22
  - **12 framework adapters** — LangChain, AutoGen, CrewAI, OpenAI Assistants, LlamaIndex, Semantic Kernel, and more in one orchestrator — no glue code, no lock-in
23
23
 
24
- If network-ai saves you time, a ⭐ helps others find it.  |  [**60-second quickstart →**](#hello-world----get-running-in-60-seconds)  |  [**Architecture →**](#architecture)  |  [**All adapters →**](#adapter-system)
24
+ **Use Network-AI as:**
25
+ - A **TypeScript/Node.js library** — `import { createSwarmOrchestrator } from 'network-ai'`
26
+ - An **MCP server** — `npx network-ai-server --port 3001`
27
+ - An **OpenClaw skill** — `clawhub install network-ai`
28
+
29
+ [**5-minute quickstart →**](QUICKSTART.md)  |  [**Architecture →**](ARCHITECTURE.md)  |  [**All adapters →**](#adapter-system)  |  [**Benchmarks →**](BENCHMARKS.md)
25
30
 
26
31
  ---
27
32
 
@@ -35,8 +40,6 @@ If network-ai saves you time, a ⭐ helps others find it.  |  [**60-se
35
40
  | Locked into one AI framework | 12 adapters — mix LangChain + AutoGen + CrewAI + custom in one swarm |
36
41
  | Agents escalating beyond their scope | `AuthGuardian` — scoped permission tokens required before sensitive operations |
37
42
 
38
- > Validated by **1,216 passing tests** across 9 test suites — [see testing section](#testing)
39
-
40
43
  ---
41
44
 
42
45
  ## Architecture
@@ -67,1091 +70,177 @@ If network-ai saves you time, a ⭐ helps others find it.  |  [**60-se
67
70
  HMAC-signed audit log
68
71
  ```
69
72
 
70
- ## Hello World -- Get Running in 60 Seconds
71
-
72
- ```typescript
73
- import { createSwarmOrchestrator, CustomAdapter } from 'network-ai';
74
-
75
- // 1. Create an adapter and register your agent
76
- const adapter = new CustomAdapter();
77
- adapter.registerHandler('greeter', async (payload) => {
78
- return { result: `Hello, ${payload.params.name}! Your task: ${payload.action}` };
79
- });
80
-
81
- // 2. Create the orchestrator
82
- const orchestrator = createSwarmOrchestrator({
83
- adapters: [{ adapter }],
84
- });
85
-
86
- // 3. Use the blackboard to coordinate
87
- orchestrator.blackboard.write('status', { ready: true }, 'greeter');
88
-
89
- // 4. Execute your agent through the adapter
90
- const result = await adapter.executeAgent('greeter', {
91
- action: 'welcome',
92
- params: { name: 'World' },
93
- }, { agentId: 'greeter' });
94
-
95
- console.log(result.data); // "Hello, World! Your task: welcome"
96
- ```
97
-
98
- That's it. No config files, no setup wizards. Add more agents, swap frameworks, layer on security -- all optional.
99
-
100
- ## Demos
101
-
102
- ### One command to run everything
103
-
104
- ```bash
105
- npm run demo
106
- ```
107
-
108
- Interactive menu or use flags directly:
109
-
110
- ```bash
111
- npm run demo -- --07 # Full AI showcase (OPENAI_API_KEY required)
112
- npm run demo -- --08 # Control-plane stress demo (no API key)
113
- npm run demo -- --both # Both sequentially
114
- npm run demo -- --both --silent-summary # Both, highlights only
115
- ```
73
+ [Full architecture, FSM journey, and handoff protocol](ARCHITECTURE.md)
116
74
 
117
75
  ---
118
76
 
119
- ### Demo 07 — Full AI Showcase *(requires `OPENAI_API_KEY`)*
120
-
121
- 8-agent pipeline that builds a Payment Processing Service from scratch with full governance:
122
-
123
- - **FSM state machine** — each agent phase is gated by `JourneyFSM` state transitions
124
- - **AuthGuardian tokens** — scoped HMAC-signed tokens required at every gate
125
- - **FederatedBudget** — per-agent token ceilings, hard cut-off on overspend
126
- - **QualityGateAgent** — AI-assisted security scan + content safety on generated code
127
- - **Fixer + debugger agents** — two-pass automated remediation loop
128
- - **Deterministic 10/10 scoring** — 8 objective gates, no LLM score parsing
129
- - **Cryptographic audit trail** — every write signed to `data/audit_log.jsonl`
130
-
131
- ```bash
132
- npm run demo -- --07
133
- ```
134
-
135
- ---
136
-
137
- ### Demo 08 — Control-Plane Stress Demo *(no API key)*
138
-
139
- No LLM calls. Runs in ~2 seconds. Shows the synchronization and governance primitives under load:
140
-
141
- - **`LockedBlackboard`** — atomic `propose → validate → commit` workflow with file-system mutex
142
- - **Priority preemption** — high-priority (3) write overwrites low-priority (0) write on same key
143
- - **FSM timeout** — state times out after 700 ms, FSM hard-stops
144
- - **Live compliance violations** — TOOL_ABUSE (6 rapid writes), TURN_TAKING (5 consecutive actions), RESPONSE_TIMEOUT (1.2 s sleep), JOURNEY_TIMEOUT — all captured by `ComplianceMonitor`
145
- - **`FederatedBudget`** — per-agent ceilings tracked without any AI backend
146
-
147
- ```bash
148
- npm run demo -- --08
149
- ```
150
-
151
- ---
152
-
153
- ### Demo 05 — Code Review Swarm *(requires `OPENAI_API_KEY`)*
154
-
155
- [![Code Review Swarm Demo](https://img.youtube.com/vi/UyMsNhaw9lU/0.jpg)](https://youtu.be/UyMsNhaw9lU)
156
-
157
- *5-agent code review swarm — parallel specialist agents coordinated through a shared blackboard*
158
-
159
- > The demo shows a code review swarm, but Network-AI is not a code review tool. The same orchestration pattern works for research pipelines, data processing, content moderation, customer support routing, document analysis, financial workflows — any task where multiple agents need to coordinate without stepping on each other.
160
-
161
- ```bash
162
- npm run demo -- --07 # or run directly:
163
- npx ts-node examples/05-code-review-swarm.ts
164
- ```
165
-
166
- Supports 4 modes: built-in code review, paste your own code, system design document, or custom role for any content type. Examples `01`–`03` run without any API key. `04-live-swarm.ts` runs a 10-agent live AI research swarm (3 parallel analyst waves + synthesizer).
167
-
168
- ## Why This Exists -- The Multi-Agent Race Condition Problem
169
-
170
- Most agent frameworks let you run multiple AI agents in parallel. None of them protect you when those agents write to the same resource at the same time.
171
-
172
- **The "Bank Run" scenario:**
173
-
174
- ```
175
- Agent A reads balance: $10,000
176
- Agent B reads balance: $10,000 (same moment)
177
- Agent A writes balance: $10,000 - $7,000 = $3,000
178
- Agent B writes balance: $10,000 - $6,000 = $4,000 <-- Agent A's write is gone
179
- ```
180
-
181
- Both agents thought they had $10,000. Both spent from it. You just lost $3,000 to a race condition. This isn't theoretical -- it happens any time two LLM agents hit a shared database, file, or API concurrently.
182
-
183
- **This is a split-brain problem.** Without concurrency control, your agents will:
184
- - **Corrupt shared state** -- Two agents overwrite each other's blackboard entries
185
- - **Double-spend budgets** -- Token costs exceed limits because agents don't see each other's spending
186
- - **Produce contradictory outputs** -- Agent A says "approved", Agent B says "denied", both write to the same key
187
-
188
- **How Network-AI prevents this:**
189
-
190
- ```typescript
191
- // Atomic commit -- no other agent can read or write "account:balance" during this operation
192
- const blackboard = new LockedBlackboard('.');
193
- const changeId = blackboard.proposeChange('account:balance', { amount: 7000, type: 'debit' }, 'agent-a');
194
- blackboard.validateChange(changeId); // Checks for conflicts
195
- blackboard.commitChange(changeId); // Atomic write with file-system mutex
196
-
197
- // Budget tracking -- hard ceiling on token spend
198
- // Even if 5 agents run in parallel, total spend cannot exceed the budget
199
- python scripts/swarm_guard.py budget-init --task-id "task_001" --budget 10000
200
- ```
201
-
202
- Network-AI wraps your agent swarm with **file-system mutexes**, **atomic commits**, and **token budget ceilings** so race conditions, double-spends, and split-brain writes are prevented — validated by [1,216 passing tests](#testing) across 9 test suites. This works with any framework — LangChain, CrewAI, AutoGen, or anything else connected through the adapter system.
203
-
204
- ### Why not just use LangGraph / CrewAI / AutoGen alone?
205
-
206
- | Problem | LangGraph | CrewAI | AutoGen | Network-AI |
207
- |---|---|---|---|---|
208
- | Two agents write the same key simultaneously | ❌ Last write wins silently | ❌ Last write wins silently | ❌ Last write wins silently | ✅ Atomic mutex + conflict resolution |
209
- | Budget overrun across parallel agents | ⚠️ Callbacks only | ❌ None | ❌ None | ✅ Hard ceiling per agent + task |
210
- | Cross-framework agents in one swarm | ❌ LangChain only | ❌ CrewAI only | ❌ AutoGen only | ✅ 12 frameworks via adapters |
211
- | Tamper-evident audit trail | ❌ None | ❌ None | ❌ None | ✅ HMAC-signed log |
212
- | Permission gating per API | ❌ None | ❌ None | ❌ None | ✅ AuthGuardian |
213
-
214
- > **Use Network-AI as the coordination layer on top of your existing framework** — keep your LangChain chains, CrewAI crews, and AutoGen agents, and add shared state + governance around them.
215
-
216
- ## Features
217
-
218
- ### Core Orchestration (Multi-Agent Coordination)
219
- - **Agent-to-Agent Handoffs** -- Delegate tasks between sessions using OpenClaw's `sessions_send`
220
- - **Permission Wall (AuthGuardian)** -- Gate access to sensitive APIs with justification-based approval
221
- - **Shared Blackboard** -- Markdown-based coordination state for agent communication
222
- - **Parallel Execution Patterns** -- Merge, vote, chain, and first-success synthesis strategies
223
- - **Task Decomposition** -- Automatic breaking of complex tasks into parallel subtasks
224
-
225
- ### Plug-and-Play Adapter System (v3.0) -- 12 AI Agent Frameworks
226
- - **AdapterRegistry** -- Route agents to the right framework automatically
227
- - **OpenClaw Adapter** -- Native OpenClaw skill execution via `callSkill`
228
- - **LangChain Adapter** -- Supports Runnables (`.invoke()`) and plain functions
229
- - **AutoGen Adapter** -- Supports `.run()` and `.generateReply()` agents
230
- - **CrewAI Adapter** -- Individual agents and full crew orchestration
231
- - **MCP Adapter** -- Model Context Protocol tool handlers
232
- - **LlamaIndex Adapter** -- Query engines, chat engines, and agent runners
233
- - **Semantic Kernel Adapter** -- Microsoft SK kernels, functions, and planners
234
- - **OpenAI Assistants Adapter** -- Assistants API with thread management
235
- - **Haystack Adapter** -- Pipelines, agents, and components
236
- - **DSPy Adapter** -- Modules, programs, and predictors
237
- - **Agno Adapter** -- Agents, teams, and functions (formerly Phidata)
238
- - **Custom Adapter** -- Register any function or HTTP endpoint as an agent
239
- - **BaseAdapter** -- Extend to write your own adapter in minutes
240
-
241
- ### Content Quality Gate (AI Safety)
242
- - **BlackboardValidator (Layer 1)** -- Rule-based validation (see benchmarks below)
243
- - **QualityGateAgent (Layer 2)** -- AI-assisted review with quarantine system
244
- - **Hallucination Detection** -- Catches vague, unsupported, or fabricated content
245
- - **Dangerous Code Detection** -- Blocks `eval()`, `exec()`, `rm -rf`, and other risky patterns
246
- - **Placeholder Rejection** -- Rejects TODO/FIXME/stub content from entering the blackboard
247
-
248
- **BlackboardValidator throughput** (measured on Node.js 20, Apple M2, single-thread):
249
-
250
- | Input size | Ops/sec | Latency |
251
- |---|---|---|
252
- | Small entry (~100 chars) | ~1,000,000 | < 1 µs |
253
- | Medium entry (~1 KB) | ~500,000 | ~2 µs |
254
- | Large entry (~10 KB) | ~159,000 | ~6 µs |
255
-
256
- Layer 2 (QualityGateAgent) adds LLM latency and is async — intended for high-value writes, not every write.
257
-
258
- ### Security Module (Defense-in-Depth)
259
- - **HMAC-Signed Tokens** -- Cryptographic token generation with expiration
260
- - **Input Sanitization** -- XSS, injection, path traversal, and prototype pollution prevention
261
- - **Blackboard Path Safety** -- Change ID sanitization prevents directory traversal in atomic commits
262
- - **Rate Limiting** -- Per-agent request throttling with lockout on failed auth
263
- - **AES-256-GCM Encryption** -- Encrypt sensitive blackboard entries at rest
264
- - **Privilege Escalation Prevention** -- Trust-ceiling enforcement
265
- - **Cryptographic Audit Logs** -- Tamper-evident signed audit trail with chain continuation
266
- - **Secure Gateway** -- Integrated security layer wrapping all operations
267
-
268
- ### Operational Safety & Governance
269
- - **Swarm Guard** -- Prevents "Handoff Tax" (wasted tokens) and detects silent agent failures
270
- - **Atomic Commits** -- File-system mutexes prevent split-brain in concurrent writes
271
- - **Priority-Based Preemption** -- Higher-priority agents preempt lower-priority writes on same-key conflicts (`priority-wins` strategy)
272
- - **Cost Awareness** -- Token budget tracking with automatic SafetyShutdown
273
- - **Budget-Aware Handoffs** -- `intercept-handoff` command wraps `sessions_send` with budget checks
274
- - **`--active-grants` Observability** -- Real-time view of which agents hold access to which APIs, with TTL countdown
275
- - **`--audit-summary` Observability** -- Per-agent and per-resource breakdown of permission requests, grants, and denials
276
- - **Justification Hardening** -- 16-pattern prompt-injection detector, keyword-stuffing defense, structural coherence scoring
277
-
278
- ## Project Structure
279
-
280
- ```
281
- Network-AI/
282
- |-- index.ts # Core orchestrator (SwarmOrchestrator, SharedBlackboard, AuthGuardian, TaskDecomposer)
283
- |-- security.ts # Security module (tokens, encryption, rate limiting, audit)
284
- |-- setup.ts # Developer setup & installation checker
285
- |-- package.json # NPM manifest & scripts
286
- |-- tsconfig.json # TypeScript configuration
287
- |-- skill.json # OpenClaw skill metadata
288
- |-- SKILL.md # OpenClaw skill definition (frontmatter + instructions)
289
- |-- QUICKSTART.md # 5-minute getting-started guide
290
- |-- requirements.txt # Python dependencies
291
- |-- swarm-blackboard.md # Runtime blackboard state (auto-generated)
292
- |-- adapters/ # Plug-and-play agent framework adapters (12 frameworks)
293
- | |-- index.ts # Barrel exports for all adapters
294
- | |-- base-adapter.ts # Abstract base class for adapters
295
- | |-- adapter-registry.ts # Multi-adapter routing & discovery
296
- | |-- openclaw-adapter.ts # OpenClaw skill adapter
297
- | |-- langchain-adapter.ts # LangChain adapter (Runnables & functions)
298
- | |-- autogen-adapter.ts # AutoGen adapter (.run() & .generateReply())
299
- | |-- crewai-adapter.ts # CrewAI adapter (agents & crews)
300
- | |-- mcp-adapter.ts # MCP tool handler adapter
301
- | |-- custom-adapter.ts # Custom function/HTTP agent adapter
302
- | |-- llamaindex-adapter.ts # LlamaIndex adapter (query/chat engines, agent runners)
303
- | |-- semantic-kernel-adapter.ts # Microsoft Semantic Kernel adapter
304
- | |-- openai-assistants-adapter.ts # OpenAI Assistants API adapter
305
- | |-- haystack-adapter.ts # deepset Haystack adapter (pipelines, agents)
306
- | |-- dspy-adapter.ts # Stanford DSPy adapter (modules, programs)
307
- | |-- agno-adapter.ts # Agno adapter (agents, teams -- formerly Phidata)
308
- |-- types/ # TypeScript type definitions
309
- | |-- agent-adapter.d.ts # Universal adapter interfaces (IAgentAdapter, AgentPayload, etc.)
310
- | |-- openclaw-core.d.ts # OpenClaw-specific type stubs
311
- |-- lib/ # TypeScript utilities
312
- | |-- swarm-utils.ts # Node.js helper functions
313
- | |-- locked-blackboard.ts # Atomic commits with file-system mutexes
314
- | |-- blackboard-validator.ts # Content quality gate (BlackboardValidator + QualityGateAgent)
315
- |-- scripts/ # Python helper scripts
316
- | |-- check_permission.py # AuthGuardian permission checker
317
- | |-- validate_token.py # Token validation
318
- | |-- revoke_token.py # Token revocation
319
- | |-- blackboard.py # Shared state management (with atomic commits)
320
- | |-- swarm_guard.py # Handoff tax, failure prevention, & budget tracking
321
- |-- references/ # Detailed documentation
322
- | |-- adapter-system.md # Adapter architecture & writing custom adapters
323
- | |-- auth-guardian.md # Permission system details
324
- | |-- blackboard-schema.md # Data structures
325
- | |-- trust-levels.md # Agent trust configuration
326
- | |-- mcp-roadmap.md # MCP networking implementation plan
327
- |-- test-standalone.ts # Core orchestrator tests (79 tests)
328
- |-- test-security.ts # Security module tests (33 tests)
329
- |-- test-adapters.ts # Adapter system tests (139 tests)
330
- |-- test-priority.ts # Priority & preemption tests (64 tests)
331
- |-- test-phase4.ts # Phase 4 FSM/compliance/adapter tests (147 tests)
332
- |-- test-phase5.ts # Phase 5 Named Multi-Blackboard tests (35 tests)
333
- |-- test-phase5b.ts # Phase 5 Part 2 Pluggable Backend tests (55 tests)
334
- |-- test-ai-quality.ts # AI quality gate demo
335
- |-- test.ts # Full integration test suite
336
- ```
337
-
338
- ## Quick Start
339
-
340
- See [QUICKSTART.md](QUICKSTART.md) for a 5-minute getting-started guide.
341
-
342
- ## Installation
343
-
344
- ### As a Dependency (recommended)
77
+ ## Install
345
78
 
346
79
  ```bash
347
80
  npm install network-ai
348
81
  ```
349
82
 
350
- That's it. No native dependencies, no build step.
83
+ No native dependencies, no build step. Adapters are dependency-free (BYOC — bring your own client).
351
84
 
352
- > **One package, two entry points:**
353
- > - `import { createSwarmOrchestrator } from 'network-ai'` — TypeScript/Node.js orchestration API
354
- > - `npx network-ai-server --port 3001` — MCP server binary (bundled in the same package)
355
-
356
- ### For Development (contributing / running tests)
357
-
358
- ```bash
359
- git clone https://github.com/jovanSAPFIONEER/Network-AI
360
- cd Network-AI
361
- npm install # TypeScript dev dependencies
362
- pip install -r requirements.txt # Optional: mypy, pytest, filelock for Python script development
363
- ```
364
-
365
- ### Verify Development Setup
366
-
367
- ```bash
368
- npm run setup:check # Check all files and dependencies
369
- npm run setup -- --list # List all 12 available adapters
370
- npm run setup:example # Generate a starter example.ts
371
- ```
372
-
373
- ### Running in PowerShell (Windows)
374
-
375
- All commands work in PowerShell. The only difference from bash is how you set environment variables.
376
-
377
- **Set your API key for the current session:**
378
-
379
- ```powershell
380
- $env:OPENAI_API_KEY = "sk-..."
381
- ```
382
-
383
- **Or load it from `.env` automatically** — copy the template first:
384
-
385
- ```powershell
386
- Copy-Item .env.example .env # then open .env and fill in your key
387
- ```
388
-
389
- **Run the examples (no API key needed):**
390
-
391
- ```powershell
392
- npx ts-node examples/01-hello-swarm.ts
393
- npx ts-node examples/02-fsm-pipeline.ts
394
- npx ts-node examples/03-parallel-agents.ts
395
- ```
396
-
397
- **Run the interactive launcher** (picks which example to run):
398
-
399
- ```powershell
400
- npx ts-node run.ts
401
- ```
402
-
403
- **Run the AI code review swarm demo** (requires `OPENAI_API_KEY`):
404
-
405
- ```powershell
406
- $env:OPENAI_API_KEY = "sk-..."
407
- npx ts-node examples/05-code-review-swarm.ts
408
- ```
409
-
410
- **Run the tests:**
411
-
412
- ```powershell
413
- npm test # Core orchestrator (79 tests)
414
- npm run test:security # Security module (33 tests)
415
- npm run test:adapters # Adapter system (139 tests)
416
- npm run test:priority # Priority & preemption (64 tests)
417
- npm run test:phase4 # Phase 4 FSM/compliance/adapter (147 tests)
418
- npm run test:phase5 # Phase 5 Named Multi-Blackboard (35 tests)
419
- npm run test:phase5b # Phase 5 Part 2 Pluggable Backend (55 tests)
420
- npm run test:all # All suites in sequence
421
- ```
422
-
423
- > **Tip:** To persist `OPENAI_API_KEY` across sessions, add it to your PowerShell profile or set it as a user environment variable via *System Properties → Environment Variables*.
424
-
425
- ### For OpenClaw Users
426
-
427
- Copy this skill into your OpenClaw workspace:
428
-
429
- ```bash
430
- cp -r Network-AI ~/.openclaw/workspace/skills/swarm-orchestrator
431
- ```
432
-
433
- Or install via ClawHub:
434
-
435
- ```bash
436
- clawhub install network-ai
437
- ```
438
-
439
- ## Usage
85
+ ---
440
86
 
441
- ### TypeScript / Node.js API
87
+ ## Two agents, one shared state — without race conditions
442
88
 
443
- #### Basic Setup
89
+ The real differentiator is coordination. Here is what no single-framework solution handles: two agents writing to the same resource concurrently, atomically, without corrupting each other.
444
90
 
445
91
  ```typescript
446
- import {
447
- SwarmOrchestrator,
448
- SharedBlackboard,
449
- AuthGuardian,
450
- createSwarmOrchestrator,
451
- } from 'network-ai';
452
-
453
- // Quick start with defaults
454
- const orchestrator = createSwarmOrchestrator();
455
- ```
456
-
457
- #### Using Adapters (Plug-and-Play)
92
+ import { LockedBlackboard, CustomAdapter, createSwarmOrchestrator } from 'network-ai';
458
93
 
459
- ```typescript
460
- import {
461
- createSwarmOrchestrator,
462
- AdapterRegistry,
463
- CustomAdapter,
464
- LangChainAdapter,
465
- } from 'network-ai';
94
+ const board = new LockedBlackboard('.');
95
+ const adapter = new CustomAdapter();
466
96
 
467
- // Create adapters
468
- const custom = new CustomAdapter();
469
- custom.registerHandler('my-agent', async (payload) => {
470
- return { result: 'done' };
97
+ // Agent 1: writes its analysis result atomically
98
+ adapter.registerHandler('analyst', async () => {
99
+ const id = board.propose('report:status', { phase: 'analysis', complete: true }, 'analyst');
100
+ board.validate(id, 'analyst');
101
+ board.commit(id); // file-system mutex — no race condition possible
102
+ return { result: 'analysis written' };
471
103
  });
472
104
 
473
- const langchain = new LangChainAdapter();
474
- langchain.registerRunnable('researcher', myLangChainRunnable);
475
-
476
- // Create orchestrator with adapters
477
- const orchestrator = createSwarmOrchestrator({
478
- adapters: [
479
- { adapter: custom },
480
- { adapter: langchain },
481
- ],
105
+ // Agent 2: runs concurrently, writes to its own key safely
106
+ adapter.registerHandler('reviewer', async () => {
107
+ const id = board.propose('report:review', { approved: true }, 'reviewer');
108
+ board.validate(id, 'reviewer');
109
+ board.commit(id);
110
+ const analysis = board.read('report:status');
111
+ return { result: `reviewed phase=${analysis?.phase}` };
482
112
  });
483
- ```
484
-
485
- #### Blackboard & Permissions
486
-
487
- ```typescript
488
- const blackboard = new SharedBlackboard('.');
489
- blackboard.write('task:analysis', { status: 'running' }, 'orchestrator');
490
- const data = blackboard.read('task:analysis');
491
-
492
- const auth = new AuthGuardian();
493
- const grant = auth.requestPermission('data_analyst', 'DATABASE', 'read',
494
- 'Need customer order history for sales report');
495
- ```
496
-
497
- ### Python Scripts
498
-
499
- #### 1. Initialize Budget (First!)
500
-
501
- ```bash
502
- python scripts/swarm_guard.py budget-init --task-id "task_001" --budget 10000
503
- ```
504
-
505
- #### 2. Budget-Aware Handoffs
506
-
507
- ```bash
508
- python scripts/swarm_guard.py intercept-handoff \
509
- --task-id "task_001" \
510
- --from orchestrator \
511
- --to data_analyst \
512
- --message "Analyze Q4 revenue data"
513
- ```
514
-
515
- Output (if allowed):
516
- ```
517
- HANDOFF ALLOWED: orchestrator -> data_analyst
518
- Tokens spent: 156
519
- Budget remaining: 9,844
520
- Handoff #1 (remaining: 2)
521
- -> Proceed with sessions_send
522
- ```
523
113
 
524
- #### 3. Check Permissions
114
+ createSwarmOrchestrator({ adapters: [{ adapter }] });
525
115
 
526
- ```bash
527
- python scripts/check_permission.py \
528
- --agent data_analyst \
529
- --resource DATABASE \
530
- --justification "Need customer order history for sales report"
531
- ```
116
+ // Both fire concurrently — mutex guarantees no write is ever lost
117
+ const [, ] = await Promise.all([
118
+ adapter.executeAgent('analyst', { action: 'run', params: {} }, { agentId: 'analyst' }),
119
+ adapter.executeAgent('reviewer', { action: 'run', params: {} }, { agentId: 'reviewer' }),
120
+ ]);
532
121
 
533
- Output:
122
+ console.log(board.read('report:status')); // { phase: 'analysis', complete: true }
123
+ console.log(board.read('report:review')); // { approved: true }
534
124
  ```
535
- GRANTED
536
- Token: grant_85364b44d987...
537
- Expires: 2026-02-04T15:30:00Z
538
- Restrictions: read_only, max_records:100
539
- ```
540
-
541
- #### 3a. View Active Grants
542
125
 
543
- See which agents currently hold access to which APIs:
126
+ Add budgets, permissions, and cross-framework agents with the same pattern. [QUICKSTART.md](QUICKSTART.md)
544
127
 
545
- ```bash
546
- # Human-readable
547
- python scripts/check_permission.py --active-grants
548
-
549
- # Filter by agent
550
- python scripts/check_permission.py --active-grants --agent data_analyst
551
-
552
- # Machine-readable JSON
553
- python scripts/check_permission.py --active-grants --json
554
- ```
555
-
556
- Output:
557
- ```
558
- Active Grants:
559
- ======================================================================
560
- Agent: data_analyst
561
- Resource: DATABASE
562
- Scope: read:orders
563
- Token: grant_c1ea828897...
564
- Remaining: 4.4 min
565
- Restrictions: read_only, max_records:100
566
- ------------------------------------------------------------------
567
-
568
- Total: 1 active, 0 expired
569
- ```
128
+ ---
570
129
 
571
- #### 3b. Audit Summary
130
+ ## Demo Control-Plane Stress Test *(no API key)*
572
131
 
573
- Summarize permission activity across all agents:
132
+ Runs in ~2 seconds. Proves the coordination primitives without any LLM calls.
574
133
 
575
134
  ```bash
576
- # Human-readable
577
- python scripts/check_permission.py --audit-summary
578
-
579
- # Last 50 entries, JSON output
580
- python scripts/check_permission.py --audit-summary --last 50 --json
581
- ```
582
-
583
- Output:
135
+ npm run demo -- --08
584
136
  ```
585
- Audit Summary
586
- ======================================================================
587
- Requests: 12
588
- Grants: 9
589
- Denials: 3
590
- Grant Rate: 75%
591
137
 
592
- By Agent:
593
- --------------------------------------------------
594
- Agent Requests Grants Denials
595
- data_analyst 4 3 1
596
- orchestrator 5 4 1
597
- strategy_advisor 3 2 1
598
- ```
138
+ What it shows: atomic blackboard locking, priority preemption (priority-3 wins over priority-0 on same key), FSM hard-stop at 700 ms, live compliance violation capture (TOOL_ABUSE, TURN_TAKING, RESPONSE_TIMEOUT, JOURNEY_TIMEOUT), and `FederatedBudget` tracking — all without a single API call.
599
139
 
600
- #### 4. Use the Blackboard
140
+ **8-agent AI pipeline** (requires `OPENAI_API_KEY` — builds a Payment Processing Service end-to-end):
601
141
 
602
142
  ```bash
603
- # Write
604
- python scripts/blackboard.py write "task:analysis" '{"status": "running"}'
605
-
606
- # Read
607
- python scripts/blackboard.py read "task:analysis"
608
-
609
- # Atomic commit workflow (for multi-agent safety)
610
- python scripts/blackboard.py propose "chg_001" "key" '{"value": 1}'
611
- python scripts/blackboard.py validate "chg_001"
612
- python scripts/blackboard.py commit "chg_001"
613
-
614
- # List all keys
615
- python scripts/blackboard.py list
616
- ```
617
-
618
- #### 5. Fan-Out / Fan-In with Shared Blackboard
619
-
620
- Coordinate multiple specialized agents working on independent subtasks, then merge results:
621
-
622
- ```typescript
623
- import { LockedBlackboard } from 'network-ai';
624
- import { Logger } from 'network-ai';
625
-
626
- const logger = Logger.create('fan-out');
627
- const board = new LockedBlackboard('.', logger, { conflictResolution: 'first-commit-wins' });
628
-
629
- // Fan-out: each agent writes to its own section
630
- const agents = ['reliability', 'security', 'cost', 'operations', 'performance'];
631
-
632
- for (const pillar of agents) {
633
- // Each agent evaluates independently, writes to its own key
634
- const id = board.propose(`eval:${pillar}`, { score: Math.random(), findings: [] }, pillar);
635
- board.validate(id, 'orchestrator');
636
- board.commit(id);
637
- }
638
-
639
- // Fan-in: orchestrator reads all results and merges
640
- const results = agents.map(pillar => ({
641
- pillar,
642
- ...board.read(`eval:${pillar}`)
643
- }));
644
-
645
- const summary = board.propose('eval:summary', {
646
- overall: results.reduce((sum, r) => sum + r.score, 0) / results.length,
647
- pillars: results
648
- }, 'orchestrator');
649
- board.validate(summary, 'orchestrator');
650
- board.commit(summary);
651
- ```
652
-
653
- This pattern works with any framework adapter -- LangChain agents, AutoGen agents, CrewAI crews, or any mix. The blackboard ensures no agent overwrites another's results.
654
-
655
- #### 6. Priority-Based Conflict Resolution (Phase 3)
656
-
657
- ```typescript
658
- import { LockedBlackboard } from 'network-ai';
659
-
660
- // Enable priority-wins strategy
661
- const board = new LockedBlackboard('.', { conflictResolution: 'priority-wins' });
662
-
663
- // Low-priority worker proposes a change
664
- const lowId = board.propose('shared:config', { mode: 'draft' }, 'worker', undefined, 1);
665
-
666
- // High-priority supervisor proposes to same key
667
- const highId = board.propose('shared:config', { mode: 'final' }, 'supervisor', undefined, 3);
668
-
669
- // Worker commits first
670
- board.validate(lowId, 'orchestrator');
671
- board.commit(lowId);
672
-
673
- // Supervisor validates -- higher priority wins despite stale hash
674
- board.validate(highId, 'orchestrator'); // true (preempts worker's value)
675
- board.commit(highId); // success
676
-
677
- board.read('shared:config'); // { mode: 'final' } -- supervisor wins
143
+ npm run demo -- --07
678
144
  ```
679
145
 
680
- #### 7. Check Budget Status
146
+ [![Code Review Swarm Demo](https://img.youtube.com/vi/UyMsNhaw9lU/0.jpg)](https://youtu.be/UyMsNhaw9lU)
681
147
 
682
- ```bash
683
- python scripts/swarm_guard.py budget-check --task-id "task_001"
684
- python scripts/swarm_guard.py budget-report --task-id "task_001"
685
- ```
148
+ ---
686
149
 
687
150
  ## Adapter System
688
151
 
689
- The adapter system lets you plug any agent framework into the orchestrator. Each adapter implements the `IAgentAdapter` interface.
690
-
691
- | Adapter | Framework | Agent Registration | Dependencies |
692
- |---------|-----------|-------------------|-------------|
693
- | `OpenClawAdapter` | OpenClaw | `registerSkill(name, skillRef)` | openclaw-core |
694
- | `LangChainAdapter` | LangChain | `registerRunnable(name, runnable)` or `registerFunction(name, fn)` | None (BYOC) |
695
- | `AutoGenAdapter` | AutoGen | `registerAgent(name, agent)` -- supports `.run()` and `.generateReply()` | None (BYOC) |
696
- | `CrewAIAdapter` | CrewAI | `registerAgent(name, agent)` or `registerCrew(name, crew)` | None (BYOC) |
697
- | `MCPAdapter` | MCP | `registerTool(name, handler)` | None (BYOC) |
698
- | `LlamaIndexAdapter` | LlamaIndex | `registerQueryEngine()`, `registerChatEngine()`, `registerAgentRunner()` | None (BYOC) |
699
- | `SemanticKernelAdapter` | Semantic Kernel | `registerKernel()`, `registerFunction()` | None (BYOC) |
700
- | `OpenAIAssistantsAdapter` | OpenAI Assistants | `registerAssistant(name, config)` | None (BYOC) |
701
- | `HaystackAdapter` | Haystack | `registerPipeline()`, `registerAgent()`, `registerComponent()` | None (BYOC) |
702
- | `DSPyAdapter` | DSPy | `registerModule()`, `registerProgram()`, `registerPredictor()` | None (BYOC) |
703
- | `AgnoAdapter` | Agno | `registerAgent()`, `registerTeam()`, `registerFunction()` | None (BYOC) |
704
- | `CustomAdapter` | Any | `registerHandler(name, fn)` or `registerHttpAgent(name, config)` | None |
705
-
706
- > **BYOC** = Bring Your Own Client. All adapters (except OpenClaw) are self-contained with zero npm dependencies. You provide your framework's SDK objects and the adapter wraps them.
707
-
708
- ### Writing a Custom Adapter
709
-
710
- Extend `BaseAdapter`:
711
-
712
- ```typescript
713
- import { BaseAdapter } from 'network-ai';
714
- import type { AgentPayload, AgentResult } from 'network-ai';
715
-
716
- class MyAdapter extends BaseAdapter {
717
- readonly name = 'my-framework';
718
-
719
- async executeAgent(agentId: string, payload: AgentPayload): Promise<AgentResult> {
720
- // Your framework-specific logic here
721
- return { success: true, output: 'result', metadata: { adapter: this.name } };
722
- }
723
-
724
- async listAgents() { return []; }
725
- async isAgentAvailable(id: string) { return true; }
726
- }
727
- ```
728
-
729
- See [references/adapter-system.md](references/adapter-system.md) for the full adapter architecture guide.
730
-
731
- ## API Architecture & Performance
732
-
733
- **Your swarm is only as fast as the backend it calls into.**
734
-
735
- Network-AI is backend-agnostic — every agent in a swarm can call a cloud API, a different cloud API, or a local GPU model. That choice has a direct and significant impact on speed, parallelism, and reliability.
736
-
737
- ### Why It Matters
738
-
739
- When you run a 5-agent swarm, Network-AI can dispatch all 5 calls simultaneously. Whether those calls actually execute in parallel depends entirely on what's behind each agent:
740
-
741
- | Backend | Parallelism | Typical 5-agent swarm | Notes |
742
- |---|---|---|---|
743
- | **Single cloud API key** (OpenAI, Anthropic, etc.) | Rate-limited | 40–70s sequential | RPM limits force sequential dispatch + retry waits |
744
- | **Multiple API keys / providers** | True parallel | 8–15s | Each agent hits a different key or provider |
745
- | **Local GPU** (Ollama, llama.cpp, vLLM) | True parallel | 5–20s depending on hardware | No RPM limit — all 5 agents fire simultaneously |
746
- | **Mixed** (some cloud, some local) | Partial | Varies | Local agents never block; cloud agents rate-paced |
747
-
748
- ### The Single-Key Rate Limit Problem
749
-
750
- Cloud APIs enforce **Requests Per Minute (RPM)** limits per API key. When you run 5 agents sharing one key and hit the ceiling, the API silently returns empty responses — not a 429 error, just blank content. Network-AI's swarm demos handle this automatically with **sequential dispatch** (one agent at a time) and **adaptive header-based pacing** that reads the `x-ratelimit-reset-requests` header to wait exactly as long as needed before the next call.
751
-
752
- ```
753
- Single key (gpt-5.2, 6 RPM limit):
754
- Agent 1 ──call──▶ response (7s)
755
- wait 1s
756
- Agent 2 ──call──▶ response (7s)
757
- wait 1s
758
- ... (sequential)
759
- Total: ~60s for 5 agents + coordinator
760
- ```
761
-
762
- ### Multiple Keys or Providers = True Parallel
763
-
764
- Register each reviewer agent against a different API key or provider and dispatch fires all 5 simultaneously:
765
-
766
- ```typescript
767
- import { CustomAdapter, AdapterRegistry } from 'network-ai';
768
-
769
- // Each agent points to a different OpenAI key
770
- const registry = new AdapterRegistry();
771
-
772
- for (const reviewer of REVIEWERS) {
773
- const adapter = new CustomAdapter();
774
- const client = new OpenAI({ apiKey: process.env[`OPENAI_KEY_${reviewer.id.toUpperCase()}`] });
775
-
776
- adapter.registerHandler(reviewer.id, async (payload) => {
777
- const resp = await client.chat.completions.create({ ... });
778
- return { findings: extractContent(resp) };
779
- });
780
-
781
- registry.register(reviewer.id, adapter);
782
- }
783
-
784
- // Now all 5 dispatch in parallel via Promise.all
785
- // Total: ~8-12s instead of ~60s
786
- ```
787
-
788
- ### Local GPU = Zero Rate Limits
789
-
790
- Run Ollama or any OpenAI-compatible local server and drop it in as a backend. No RPM ceiling means every agent fires the moment the previous one starts — true parallel for free:
791
-
792
- ```typescript
793
- // Point any agent at a local Ollama or vLLM server
794
- const localClient = new OpenAI({
795
- apiKey : 'not-needed',
796
- baseURL : 'http://localhost:11434/v1',
797
- });
798
-
799
- adapter.registerHandler('sec_review', async (payload) => {
800
- const resp = await localClient.chat.completions.create({
801
- model : 'llama3.2', // or mistral, deepseek-r1, codellama, etc.
802
- messages: [...],
803
- });
804
- return { findings: extractContent(resp) };
805
- });
806
- ```
807
-
808
- ### Mixing Cloud and Local
809
-
810
- The adapter system makes it trivial to give some agents a cloud backend and others a local one:
811
-
812
- ```typescript
813
- // Fast local model for lightweight reviewers
814
- registry.register('test_review', localAdapter);
815
- registry.register('arch_review', localAdapter);
816
-
817
- // Cloud model for high-stakes reviewers
818
- registry.register('sec_review', cloudAdapter); // GPT-4o / Claude
819
- ```
820
-
821
- Network-AI's orchestrator, blackboard, and trust model stay identical regardless of what's behind each adapter. The only thing that changes is speed.
822
-
823
- ### Summary
824
-
825
- | You have | What to expect |
826
- |---|---|
827
- | One cloud API key | Sequential dispatch, 40–70s per 5-agent swarm — fully handled automatically |
828
- | Multiple cloud keys | Near-parallel, 10–15s — use one key per adapter instance |
829
- | Local GPU (Ollama, vLLM) | True parallel, 5–20s depending on hardware |
830
- | Home GPU + cloud mix | Local agents never block — cloud agents rate-paced independently |
831
-
832
- The framework doesn't get in the way of any of these setups. Connect whatever backend you have and the orchestration layer handles the rest.
833
-
834
- ### Cloud Provider Performance
835
-
836
- Not all cloud APIs perform the same. Model size, inference infrastructure, and tier all affect how fast each agent gets a response — and that directly multiplies across every agent in your swarm.
837
-
838
- | Provider / Model | Avg response (5-agent swarm) | RPM limit (free/tier-1) | Notes |
839
- |---|---|---|---|
840
- | **OpenAI gpt-5.2** | 6–10s per call | 3–6 RPM | Flagship model, high latency, strict RPM |
841
- | **OpenAI gpt-4o-mini** | 2–4s per call | 500 RPM | Fast, cheap, good for reviewer agents |
842
- | **OpenAI gpt-4o** | 4–7s per call | 60–500 RPM | Balanced quality/speed |
843
- | **Anthropic Claude 3.5 Haiku** | 2–3s per call | 50 RPM | Fastest Claude, great for parallel agents |
844
- | **Anthropic Claude 3.7 Sonnet** | 4–8s per call | 50 RPM | Stronger reasoning, higher latency |
845
- | **Google Gemini 2.0 Flash** | 1–3s per call | 15 RPM (free) | Very fast inference, low RPM on free tier |
846
- | **Groq (Llama 3.3 70B)** | 0.5–2s per call | 30 RPM | Fastest cloud inference available |
847
- | **Together AI / Fireworks** | 1–3s per call | Varies by plan | Good for parallel workloads, competitive RPM |
848
-
849
- **Key insight:** A 5-agent swarm using `gpt-4o-mini` at 500 RPM can fire all 5 agents truly in parallel and finish in ~4s total. The same swarm on `gpt-5.2` at 6 RPM must go sequential and takes 60s. **The model tier matters more than the orchestration framework.**
850
-
851
- #### Choosing a Model for Swarm Agents
852
-
853
- - **Speed over depth** (many agents, real-time feedback) → `gpt-4o-mini`, `gpt-5-mini`, `claude-3.5-haiku`, `gemini-2.0-flash`, `groq/llama-3.3-70b`
854
- - **Depth over speed** (fewer agents, high-stakes output) → `gpt-4o`, `claude-3.7-sonnet`, `gpt-5.2`
855
- - **Free / no-cost testing** → Groq free tier, Gemini free tier, or Ollama locally
856
- - **Production swarms with budget** → Multiple keys across providers, route different agents to different models
152
+ 12 frameworks, zero adapter dependencies. You bring your own SDK objects.
857
153
 
858
- All of these plug into Network-AI through the `CustomAdapter` by swapping the client's `baseURL` and `model` string — no other code changes needed.
859
-
860
- ### `max_completion_tokens` The Silent Truncation Trap
861
-
862
- One of the most common failure modes in agentic output tasks is **silent truncation**. When a model hits the `max_completion_tokens` ceiling it stops mid-output and returns whatever it has — no error, no warning. The API call succeeds with a 200 and `finish_reason: "length"` instead of `"stop"`.
863
-
864
- **This is especially dangerous for code-rewrite agents** where the output is a full file. A fixed `max_completion_tokens: 3000` cap will silently drop everything after line ~150 of a 200-line fix.
865
-
866
- ```
867
- # What you set vs what you need
868
-
869
- max_completion_tokens: 3000 → enough for a short blog post
870
- → NOT enough for a 200-line code rewrite
871
-
872
- # Real numbers (gpt-5-mini, order-service.ts rewrite):
873
- Blockers section: ~120 tokens
874
- Fixed code: ~2,800 tokens (213 lines with // FIX: comments)
875
- Total needed: ~3,000 tokens ← hits the cap exactly, empty output
876
- Fix: set to 16,000 → full rewrite delivered in one shot
877
- ```
878
-
879
- **Lessons learned from building the code-review swarm:**
880
-
881
- | Issue | Root cause | Fix |
882
- |---|---|---|
883
- | Fixed code output was empty | `max_completion_tokens: 3000` too low for a full rewrite | Raise to `16000`+ for any code-output agent |
884
- | `finish_reason: "length"` silently discards output | Model hits cap, returns partial response with no error | Always check `choices[0].finish_reason` and alert on `"length"` |
885
- | `gpt-5.2` slow + expensive for reviewer agents | Flagship model = high latency + $14/1M output tokens | Use `gpt-5-mini` ($2/1M, 128k output, same RPM) for reviewer/fixer agents |
886
- | Coordinator + fixer as two separate calls | Second call hits rate limit window, adds 60s wait | Merge into one combined call with a structured two-section response format |
887
-
888
- **Rule of thumb for `max_completion_tokens` by task:**
889
-
890
- | Task | Recommended cap |
891
- |---|---|
892
- | Short classification / sentiment | 200–500 |
893
- | Code review findings (one reviewer) | 400–800 |
894
- | Blocker summary (coordinator) | 500–1,000 |
895
- | Full file rewrite (≤300 lines) | 12,000–16,000 |
896
- | Full file rewrite (≤1,000 lines) | 32,000–64,000 |
897
- | Document / design revision | 16,000–32,000 |
898
-
899
- All GPT-5 variants (`gpt-5`, `gpt-5-mini`, `gpt-5-nano`, `gpt-5.2`) support **128,000 max output tokens** — the ceiling is never the model, it's always the cap you set.
900
-
901
- #### Cloud GPU Instances (Self-Hosted on AWS / GCP / Azure)
902
-
903
- Running your own model on a cloud GPU VM (e.g. AWS `p3.2xlarge` / A100, GCP `a2-highgpu`, Azure `NC` series) sits between managed APIs and local hardware:
904
-
905
- | Setup | Parallelism | Speed vs managed API | RPM limit |
906
- |---|---|---|---|
907
- | A100 (80GB) + vLLM, Llama 3.3 70B | True parallel | **Faster** — 0.5–2s per call | None |
908
- | H100 + vLLM, Mixtral 8x7B | True parallel | **Faster** — 0.3–1s per call | None |
909
- | T4 / V100 + Ollama, Llama 3.2 8B | True parallel | Comparable | None |
910
-
911
- Since you own the endpoint, there are no rate limits — all 5 agents fire at the same moment. At inference speeds on an A100, a 5-agent swarm can complete in **3–8 seconds** for a 70B model, comparable to Groq and faster than any managed flagship model.
912
-
913
- The tradeoff is cost (GPU VMs are $1–$5/hr) and setup (vLLM install, model download). For high-volume production swarms or teams that want no external API dependency, it's the fastest architecture available. The connection is identical to local Ollama — just point `baseURL` at your VM's IP.
914
-
915
- ## Permission System
916
-
917
- The AuthGuardian evaluates requests using:
918
-
919
- | Factor | Weight | Description |
920
- |--------|--------|-------------|
921
- | Justification | 40% | Quality of business reason (hardened against prompt injection) |
922
- | Trust Level | 30% | Agent's established trust |
923
- | Risk Assessment | 30% | Resource sensitivity + scope |
924
-
925
- **Approval threshold: 0.5**
926
-
927
- ### Resource Types
928
-
929
- | Resource | Base Risk | Default Restrictions |
930
- |----------|-----------|---------------------|
931
- | `DATABASE` | 0.5 | `read_only`, `max_records:100` |
932
- | `PAYMENTS` | 0.7 | `read_only`, `no_pii_fields`, `audit_required` |
933
- | `EMAIL` | 0.4 | `rate_limit:10_per_minute` |
934
- | `FILE_EXPORT` | 0.6 | `anonymize_pii`, `local_only` |
935
-
936
- ## Security Module
937
-
938
- The security module ([security.ts](security.ts)) provides defense-in-depth protections:
939
-
940
- | Component | Class | Purpose |
941
- |-----------|-------|---------|
942
- | Token Manager | `SecureTokenManager` | HMAC-signed tokens with expiration |
943
- | Input Sanitizer | `InputSanitizer` | XSS, injection, traversal prevention |
944
- | Rate Limiter | `RateLimiter` | Per-agent request throttling + lockout |
945
- | Encryptor | `DataEncryptor` | AES-256-GCM encryption for sensitive data |
946
- | Permission Hardener | `PermissionHardener` | Trust-ceiling & privilege escalation prevention |
947
- | Audit Logger | `SecureAuditLogger` | Cryptographically signed audit entries |
948
- | Gateway | `SecureSwarmGateway` | Integrated security layer wrapping all ops |
154
+ | Adapter | Framework | Register method |
155
+ |---|---|---|
156
+ | `CustomAdapter` | Any function or HTTP endpoint | `registerHandler(name, fn)` |
157
+ | `LangChainAdapter` | LangChain | `registerRunnable(name, runnable)` |
158
+ | `AutoGenAdapter` | AutoGen / AG2 | `registerAgent(name, agent)` |
159
+ | `CrewAIAdapter` | CrewAI | `registerAgent` or `registerCrew` |
160
+ | `MCPAdapter` | Model Context Protocol | `registerTool(name, handler)` |
161
+ | `LlamaIndexAdapter` | LlamaIndex | `registerQueryEngine()`, `registerChatEngine()` |
162
+ | `SemanticKernelAdapter` | Microsoft Semantic Kernel | `registerKernel()`, `registerFunction()` |
163
+ | `OpenAIAssistantsAdapter` | OpenAI Assistants | `registerAssistant(name, config)` |
164
+ | `HaystackAdapter` | deepset Haystack | `registerPipeline()`, `registerAgent()` |
165
+ | `DSPyAdapter` | Stanford DSPy | `registerModule()`, `registerProgram()` |
166
+ | `AgnoAdapter` | Agno (formerly Phidata) | `registerAgent()`, `registerTeam()` |
167
+ | `OpenClawAdapter` | OpenClaw | `registerSkill(name, skillRef)` |
168
+
169
+ Extend `BaseAdapter` to add your own in minutes. See [references/adapter-system.md](references/adapter-system.md).
949
170
 
950
- ## Agent Trust Levels
171
+ ---
951
172
 
952
- | Agent | Trust | Role |
953
- |-------|-------|------|
954
- | `orchestrator` | 0.9 | Primary coordinator |
955
- | `risk_assessor` | 0.85 | Compliance specialist |
956
- | `data_analyst` | 0.8 | Data processing |
957
- | `strategy_advisor` | 0.7 | Business strategy |
958
- | Unknown | 0.5 | Default |
173
+ ## Works with LangGraph, CrewAI, and AutoGen
959
174
 
960
- ## Handoff Protocol
175
+ > Network-AI is the coordination layer you add **on top of** your existing stack. Keep your LangChain chains, CrewAI crews, and AutoGen agents — and add shared state, governance, and budgets around them.
961
176
 
962
- Format messages for delegation:
177
+ | Capability | Network-AI | LangGraph | CrewAI | AutoGen |
178
+ |---|---|---|---|---|
179
+ | Cross-framework agents in one swarm | ✅ 12 adapters | ❌ LangChain only | ❌ CrewAI only | ❌ AutoGen only |
180
+ | Atomic shared state (conflict-safe) | ✅ `propose → validate → commit` | ⚠️ Last-write-wins | ⚠️ Last-write-wins | ⚠️ Last-write-wins |
181
+ | Hard budget ceiling per agent | ✅ `FederatedBudget` | ⚠️ Callbacks only | ❌ | ❌ |
182
+ | Permission gating before sensitive ops | ✅ `AuthGuardian` | ❌ | ❌ | ❌ |
183
+ | Tamper-evident audit trail | ✅ HMAC-signed | ❌ | ❌ | ❌ |
184
+ | Encryption at rest | ✅ AES-256-GCM | ❌ | ❌ | ❌ |
185
+ | Language | TypeScript / Node.js | Python | Python | Python |
963
186
 
964
- ```
965
- [HANDOFF]
966
- Instruction: Analyze monthly sales by product category
967
- Context: Using database export from ./data/sales_export.csv
968
- Constraints: Focus on top 5 categories only
969
- Expected Output: JSON summary with category, revenue, growth_pct
970
- [/HANDOFF]
971
- ```
187
+ ---
972
188
 
973
189
  ## Testing
974
190
 
975
- Run all test suites:
976
-
977
- ```bash
978
- # All tests at once
979
- npm run test:all
980
-
981
- # Core orchestrator tests (79 tests)
982
- npm test
983
-
984
- # Security module tests (33 tests)
985
- npm run test:security
986
-
987
- # Adapter system tests (139 tests)
988
- npm run test:adapters
989
-
990
- # Full integration tests
991
- npx ts-node test.ts
992
- ```
993
-
994
- Test Python scripts:
995
-
996
191
  ```bash
997
- # Test permission system
998
- python scripts/check_permission.py --agent orchestrator --resource PAYMENTS \
999
- --justification "Generating monthly revenue report for management" --json
1000
-
1001
- # Test blackboard
1002
- python scripts/blackboard.py write "test:key" '{"value": 123}' --ttl 60
1003
- python scripts/blackboard.py read "test:key"
1004
-
1005
- # Test TTL cleanup
1006
- python scripts/revoke_token.py --list-expired
1007
- python scripts/revoke_token.py --cleanup
192
+ npm run test:all # All suites in sequence
193
+ npm test # Core orchestrator
194
+ npm run test:security # Security module
195
+ npm run test:adapters # All 12 adapters
196
+ npm run test:priority # Priority & preemption
1008
197
  ```
1009
198
 
1010
- **Test results (315 total):**
1011
- - `test-standalone.ts` -- 79 passed (blackboard, auth, integration, persistence, parallelization, coding domain, quality gate)
1012
- - `test-security.ts` -- 33 passed (tokens, sanitization, rate limiting, encryption, permissions, audit)
1013
- - `test-adapters.ts` -- 139 passed (12 adapters: Custom, LangChain, AutoGen, CrewAI, MCP, LlamaIndex, Semantic Kernel, OpenAI Assistants, Haystack, DSPy, Agno + registry routing, integration, edge cases)
1014
- - `test-priority.ts` -- 64 passed (priority-based preemption, conflict resolution, constructor overloads, backward compatibility)
199
+ **1,184 passing assertions across 15 test suites** (verified by counting `assert()` / `pass()` calls in each file):
1015
200
 
1016
- ## Audit Trail
1017
-
1018
- Logged events: `permission_granted`, `permission_denied`, `permission_revoked`, `ttl_cleanup`, `result_validated`
201
+ | Suite | Assertions | Covers |
202
+ |---|---|---|
203
+ | `test-standalone.ts` | 83 | Blackboard, auth, integration, persistence, parallelisation, quality gate |
204
+ | `test-adapters.ts` | 142 | All 12 adapters, registry routing, integration, edge cases |
205
+ | `test-phase4.ts` | 133 | FSM, compliance monitor, adapter integration |
206
+ | `test-phase5d.ts` | 119 | Pluggable backend |
207
+ | `test-phase5f.ts` | 113 | Phase 5f extended |
208
+ | `test-phase5g.ts` | 106 | Phase 5g extended |
209
+ | `test-phase6.ts` | 122 | Latest feature coverage |
210
+ | `test-phase5c.ts` | 74 | Named multi-blackboard |
211
+ | `test-phase5e.ts` | 88 | Phase 5e |
212
+ | `test-phase5b.ts` | 56 | Pluggable backend part 2 |
213
+ | `test-priority.ts` | 65 | Priority preemption, conflict resolution, backward compat |
214
+ | `test-security.ts` | 35 | Tokens, sanitization, rate limiting, encryption, audit |
215
+ | `test-phase5.ts` | 24 | Named multi-blackboard base |
216
+ | `test.ts` | 24 | Full integration |
217
+ | `test-phase4.ts` (stubs) | 4 | FSM stub coverage |
1019
218
 
1020
- The security module's `SecureAuditLogger` produces cryptographically signed entries that can be verified for tamper detection.
219
+ ---
1021
220
 
1022
221
  ## Documentation
1023
222
 
1024
- - [QUICKSTART.md](QUICKSTART.md) -- 5-minute getting-started guide
1025
- - [SKILL.md](SKILL.md) -- Main skill instructions (includes Orchestrator protocol)
1026
- - [references/adapter-system.md](references/adapter-system.md) -- Adapter architecture & writing custom adapters
1027
- - [references/auth-guardian.md](references/auth-guardian.md) -- Permission system details
1028
- - [references/blackboard-schema.md](references/blackboard-schema.md) -- Data structures
1029
- - [references/trust-levels.md](references/trust-levels.md) -- Trust configuration
1030
- - [references/mcp-roadmap.md](references/mcp-roadmap.md) -- MCP networking implementation plan
1031
-
1032
- ## Configuration
1033
-
1034
- ### Modify Trust Levels
1035
-
1036
- Edit `scripts/check_permission.py`:
1037
-
1038
- ```python
1039
- DEFAULT_TRUST_LEVELS = {
1040
- "orchestrator": 0.9,
1041
- "my_new_agent": 0.75, # Add your agent
1042
- }
1043
- ```
1044
-
1045
- ### Adjust Token TTL
1046
-
1047
- ```python
1048
- GRANT_TOKEN_TTL_MINUTES = 5 # Change as needed
1049
- ```
1050
-
1051
- ## Exports
1052
-
1053
- The module exports everything needed for programmatic use:
1054
-
1055
- ```typescript
1056
- // Core classes
1057
- import SwarmOrchestrator, { SharedBlackboard, AuthGuardian, TaskDecomposer } from 'network-ai';
1058
- import { BlackboardValidator, QualityGateAgent } from 'network-ai';
1059
-
1060
- // Factory
1061
- import { createSwarmOrchestrator } from 'network-ai';
1062
-
1063
- // Adapters (all 12)
1064
- import {
1065
- AdapterRegistry, BaseAdapter,
1066
- OpenClawAdapter, LangChainAdapter, AutoGenAdapter,
1067
- CrewAIAdapter, MCPAdapter, CustomAdapter,
1068
- LlamaIndexAdapter, SemanticKernelAdapter, OpenAIAssistantsAdapter,
1069
- HaystackAdapter, DSPyAdapter, AgnoAdapter,
1070
- } from 'network-ai';
1071
-
1072
- // Types
1073
- import type {
1074
- IAgentAdapter, AgentPayload, AgentContext, AgentResult, AgentInfo,
1075
- AdapterConfig, AdapterCapabilities,
1076
- TaskPayload, HandoffMessage, PermissionGrant, SwarmState,
1077
- AgentStatus, ParallelTask, ParallelExecutionResult, SynthesisStrategy,
1078
- } from 'network-ai';
1079
- ```
1080
-
1081
- ## License
223
+ | Doc | Contents |
224
+ |---|---|
225
+ | [QUICKSTART.md](QUICKSTART.md) | Installation, first run, PowerShell guide, Python scripts CLI |
226
+ | [ARCHITECTURE.md](ARCHITECTURE.md) | Race condition problem, FSM design, handoff protocol, project structure |
227
+ | [BENCHMARKS.md](BENCHMARKS.md) | Provider performance, rate limits, local GPU, `max_completion_tokens` guide |
228
+ | [SECURITY.md](SECURITY.md) | Security module, permission system, trust levels, audit trail |
229
+ | [INTEGRATION_GUIDE.md](INTEGRATION_GUIDE.md) | End-to-end integration walkthrough |
230
+ | [references/adapter-system.md](references/adapter-system.md) | Adapter architecture, writing custom adapters |
231
+ | [references/auth-guardian.md](references/auth-guardian.md) | Permission scoring, resource types |
232
+ | [references/trust-levels.md](references/trust-levels.md) | Trust level configuration |
1082
233
 
1083
- MIT License -- See [LICENSE](LICENSE)
234
+ ---
1084
235
 
1085
236
  ## Contributing
1086
237
 
1087
- If you find Network-AI useful, **give it a star** -- it helps others discover the project and motivates development:
238
+ 1. Fork feature branch `npm run test:all` pull request
239
+ 2. Bugs and feature requests via [Issues](https://github.com/jovanSAPFIONEER/Network-AI/issues)
240
+ 3. If Network-AI saves you time, a ⭐ helps others find it
1088
241
 
1089
242
  [![Star on GitHub](https://img.shields.io/github/stars/jovanSAPFIONEER/Network-AI?style=social)](https://github.com/jovanSAPFIONEER/Network-AI)
1090
243
 
1091
- **Want to contribute code?**
1092
-
1093
- 1. Fork the repository
1094
- 2. Create a feature branch
1095
- 3. Make your changes
1096
- 4. Run all tests (`npm run test:all`)
1097
- 5. Submit a pull request
1098
-
1099
- **Other ways to help:**
1100
- - Report bugs or suggest features via [Issues](https://github.com/jovanSAPFIONEER/Network-AI/issues)
1101
- - Share Network-AI with your team or on social media
1102
- - Write about your experience using it
1103
-
1104
244
  ---
1105
245
 
1106
- **Compatible with 12 agent frameworks: OpenClaw, LangChain, AutoGen, CrewAI, MCP, LlamaIndex, Semantic Kernel, OpenAI Assistants, Haystack, DSPy, Agno, and any custom adapter**
1107
-
1108
- ## Competitive Comparison
1109
-
1110
- > **TL;DR** — LangGraph, CrewAI, and AutoGen are excellent agent builders. Network-AI is the coordination layer you add on top when those agents need to share state, stay within budget, and leave an audit trail. They are complementary, not competing.
1111
-
1112
- How Network-AI compares to other multi-agent frameworks:
1113
-
1114
- | Capability | Network-AI | LangChain/LangGraph | AutoGen/AG2 | CrewAI | Claude SDK |
1115
- |---|---|---|---|---|---|
1116
- | **Multi-framework support** | 12 adapters | LangChain only | AutoGen only | CrewAI only | Claude only |
1117
- | **Shared state (blackboard)** | Atomic commits, TTL, priority | LangGraph state | Shared context | Shared memory | Project memory |
1118
- | **Conflict resolution** | Priority preemption, last-write-wins | None | None | None | None |
1119
- | **Fan-out / fan-in** | Native (parallel + merge) | LangGraph branches | Group chat | Parallel tasks | Subagents |
1120
- | **Permission gating** | AuthGuardian (weighted scoring) | None | None | None | None |
1121
- | **Budget tracking** | Token ceiling + per-task budgets | Callbacks only | None | None | None |
1122
- | **Audit trail** | HMAC-signed, tamper-evident | None | None | None | None |
1123
- | **Encryption at rest** | AES-256-GCM | None | None | None | None |
1124
- | **Observability** | `--active-grants`, `--audit-summary` | LangSmith (SaaS) | None | None | None |
1125
- | **Rate limiting** | Per-agent with lockout | None | None | None | None |
1126
- | **Justification hardening** | 16-pattern injection defense | None | None | None | None |
1127
- | **Language** | TypeScript/Node.js | Python | Python | Python | Python |
1128
- | **Dependencies** | Zero (per adapter) | Heavy | Heavy | Heavy | Moderate |
1129
- | **License** | MIT | MIT | CC-BY-4.0 | MIT | MIT |
1130
-
1131
- **Key differentiator:** Network-AI is the only framework that combines multi-framework orchestration with a governance layer (permissions, audit, encryption, budget enforcement). Other frameworks focus on one LLM provider; Network-AI wraps all of them.
1132
-
1133
- ## Related Concepts
1134
-
1135
- Network-AI fits into the broader AI agent ecosystem:
1136
-
1137
- - **Multi-Agent Systems** -- Coordinate multiple AI agents working together on complex tasks
1138
- - **Agentic AI** -- Build autonomous agents that reason, plan, and execute using LLMs
1139
- - **Behavioral Control Plane** -- Govern agent behavior with permission gating, compliance enforcement, and audit trails
1140
- - **Swarm Intelligence** -- Parallel fan-out/fan-in patterns with voting, merging, and chain strategies
1141
- - **Model Context Protocol (MCP)** -- Standard protocol support for LLM tool integration
1142
- - **Agent-to-Agent (A2A)** -- Inter-agent communication via shared blackboard and handoff protocol
1143
- - **Context Engineering** -- Manage and share context across agent boundaries
1144
- - **Agentic Workflows** -- Task decomposition, parallel processing, and synthesis pipelines
1145
- - **LLM Orchestration** -- Route tasks to the right agent framework automatically
1146
- - **Agent Governance** -- Permission gating, budget enforcement, audit logging, and compliance monitoring
1147
-
1148
- If you're using LangGraph, Dify, Flowise, PraisonAI, AutoGen/AG2, CrewAI, or any other agent framework, Network-AI can integrate with it through the adapter system.
1149
-
1150
- ---
1151
-
1152
- <details>
1153
- <summary>Keywords (for search)</summary>
1154
-
1155
- ai-agents, agentic-ai, multi-agent, multi-agent-systems, multi-agent-system, agent-framework, ai-agent-framework, agentic-framework, agentic-workflow, llm, llm-agents, llm-agent, large-language-models, generative-ai, genai, orchestration, ai-orchestration, swarm, swarm-intelligence, autonomous-agents, agents, ai, typescript, nodejs, mcp, model-context-protocol, a2a, agent-to-agent, function-calling, tool-integration, context-engineering, rag, ai-safety, multi-agents-collaboration, multi-agents, aiagents, aiagentframework, plug-and-play, adapter-registry, blackboard-pattern, agent-coordination, agent-handoffs, token-permissions, budget-tracking, cost-awareness, atomic-commits, hallucination-detection, content-quality-gate, behavioral-control-plane, governance-layer, compliance-enforcement, fan-out-fan-in, agent-observability, permission-gating, audit-trail, OpenClaw, Clawdbot, Moltbot, Clawdbot Swarm, Moltbot Security, Moltbot multi-agent, OpenClaw skills, AgentSkills, LangChain adapter, LangGraph, AutoGen adapter, AG2, CrewAI adapter, MCP adapter, LlamaIndex adapter, Semantic Kernel adapter, OpenAI Assistants adapter, Haystack adapter, DSPy adapter, Agno adapter, Phidata adapter, Dify, Flowise, PraisonAI, custom-adapter, AES-256 encryption, HMAC tokens, rate limiting, input sanitization, privilege escalation prevention, ClawHub, clawhub, agentic-rag, deep-research, workflow-orchestration, ai-assistant, ai-tools, developer-tools, open-source
1156
-
1157
- </details>
246
+ MIT License [LICENSE](LICENSE) &nbsp;·&nbsp; [CHANGELOG](CHANGELOG.md) &nbsp;·&nbsp; [CONTRIBUTING](CONTRIBUTING.md)