The Infrastructure Layer for Autonomous AI Characters
npm install forbocai
Systém_Óverview // Prótocol_Init
ᚠ ᛫ ᛟ ᛫ ᚱ ᛫ ᛒ ᛫ ᛟ ᛫ ᚲ
Autonomous AI for game NPCs.



> W̶e̴ ̶b̶u̷i̸l̶d̶ ̵t̵h̶e̴ ̷v̴e̴s̶s̷e̵l̴s̴.̷ ̷T̷h̵e̷y̸ ̴b̵r̴e̴a̷t̸h̸e̷ ̸t̴h̸e̶i̶r̶ ̴o̵w̷n̴ ̸l̸i̷f̷e̸.̸
---
Públish_Séquence // NPM_Deploý
To publish a new version to NPM:
``bash1. Bump version
npm version
> Token Location: The NPM token is stored in
../api/NPM_TOKEN.md
> Current Version: Check package.json for the current version---
Overview
Córe_Módules // SDK_InitThe ForbocAI SDK is an Engine-Agnostic toolkit for creating autonomous AI-powered NPCs in any game or application. It runs anywhere (Node, Browser, Python, Rust).
- Local SLM Cortex — Run WebLLM (SmolLM2, Llama3) directly in-browser via WebGPU.
- Autonomous NPCs — Create agents with persona, memory, and validated actions.
- Persistent Memory — IndexedDB vector storage for 10k+ memories.
- Portable Souls — P2P IPFS pinning via integrated Helia node.
- Automated QA — Ghost Agents for headless testing at scale.
Requirements:
- Browser with WebGPU support (Chrome 113+, Edge 113+) for Cortex.
- Node.js 18+ for CLI/Build.
---
Architectural Philosophy (Strict)
Code_Dóctrine // Pure_FúnctionThe ForbocAI SDK strictly adheres to Functional Programming (FP) principles to ensure predictable, testable, and robust AI behavior.
$3
We reject Object-Oriented Programming (OOP) classes (class) in favor of Functional Composition.
- State is Immutable: Objects are never mutated in place. New versions are returned.
- Pure Functions: Logic is separated from data. Functions receive input and return output with no side effects.
- Factory Pattern: We use factory functions with closures to encapsulate private state (createAgent, createMemory) instead of classes (new Agent).$3
AI state (memories, personality, mood) is complex and sensitive. Classes encourage hidden mutations that lead to "Ghost in the Machine" bugs. Pure functions ensure that every thought process is traceable and reproducible.> Logic must be pure. Order must be absolute.
᛭ ᛫ ᛬ ᛫ ᛭
---
Installation
Instáll_Séquence // Pácкage`bash
JavaScript/TypeScript
npm install forbocai
`Windows: The SDK requires CMake and the Visual Studio C++ workload ("Desktop development with C++") to build the native Cortex (
node-llama-cpp). The install runs a preinstall check; if it fails, you'll see a message for either missing CMake or missing C++ toolset. Install CMake (add to PATH) and Visual Studio Build Tools with "Desktop development with C++" selected via the Visual Studio Installer (Modify → check "Desktop development with C++"). Then run npm install forbocai again.---
CLI Reference
CLI_Tóols // Cómmand_LíneThe SDK includes a comprehensive CLI for managing your AI infrastructure.
`bash
Agents
npx forbocai agent create "A wise wizard"
npx forbocai agent list
npx forbocai agent chat Memory & Bridge
npx forbocai memory recall "battle"
npx forbocai bridge validate action.jsonSystem
npx forbocai status
npx forbocai doctor
`---
Quick Start
Quíck_Stárt // Éxample`typescript
import { Cortex, Agent } from 'forbocai';// Córtex_Init // Loćal_Inférence
const cortex = await Cortex.init({ model: 'smollm2-135m' });
// Agént_Créate // NPC_Entíty
const npc = await Agent.create({
cortex,
persona: 'A suspicious merchant who was once cheated by adventurers.',
state: { inventory: ['rusty_key', 'healing_potion'], mood: 'suspicious' }
});
// Prócéss_Ínput // Dïalógue
const response = await npc.process({
input: 'I want to buy a healing potion.',
context: { playerGold: 50 }
});
console.log(response.dialogue);
// "Hmm, you have the coin... but how do I know you won't just take it and run?"
`
---
Core Modules
Módulátion_Máp // Sýstem_Óverview| Module | Description | Status |
|--------|-------------|--------|
| Cortex | Local SLM inference engine (Self-Contained) | ✅ Browser / 🚧 Node |
| Agent | Autonomous entities with persona, state, memory | ✅ Complete |
| Memory | Local Vector DB (IndexedDB / FS) | ✅ Complete |
| Bridge | Neuro-symbolic action validation | ✅ Complete |
| Soul | Portable agent state on IPFS/Solana | ✅ Complete |
| Ghost | Headless QA testing at scale | ✅ Complete |
---
The Neural Grid
Systém_Architécture // CónnectionThe ForbocAI Protocol strictly separates State (SDK) from Logic (API).
`
┌────────────────────────────────────────────────────────────────┐
│ THE NEURAL GRID │
├────────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────┐ ┌──────────────┐ │
│ │ SDK │ │ API │ │
│ │ (Container) │◄────────►│ (Pure Logic) │ │
│ └──────────────┘ └──────────────┘ │
│ │ │ │
│ The VESSEL The TRUTH │
│ [SLM + VectorDB] [Stateless Rules] │
│ [Memory + Soul] [No Database] │
│ │
└────────────────────────────────────────────────────────────────┘
`1. SDK is the Body: It contains the entire existence of the Agent.
* SLM Cortex: The brain (Local Inference).
* Vector Memory: The memory (Local Storage).
* Self-Contained: Runs locally (Browser/Node/Python/Rust) without external dependencies.
2. API is the Law: It is a stateless oracle that validates reality.
* No Database: The API never stores agent state.
* Pure Functions: Input (Action) → Output (Validation).
Mémory_Módule // Sémantic_RécallThe Memory module provides privacy-first local vector storage with semantic search.
`typescript
import { createMemory } from 'forbocai';// Initialize memory with temporal decay
const memory = createMemory({
decay: 'temporal', // Old memories fade over time
maxContextWindow: 10, // Max memories per recall
storageKey: 'npc_memory' // localStorage key
});
// Store observations with importance
await memory.store('Player saved my life in battle', 'experience', 0.95);
await memory.store('Found gold hidden in ruins', 'observation', 0.6);
// Semantic recall (ranked by relevance × importance)
const related = await memory.recall('Do I trust the player?', 5);
// Returns memories about player saving life (high relevance)
// Export for Soul portability
const allMemories = memory.export();
`Features:
- Local Storage: All data stays in
localStorage (browser) or memory (Node)
- Semantic Search: Word overlap similarity (upgradeable to embeddings)
- Temporal Decay: Older memories become less important over time
- API Sync: Optional cloud backup via ForbocAI API---
Module: Bridge (Action Validation)
Brídge_Módule // Néuro_SymbólicThe Bridge ensures AI-generated actions are always valid within game rules.
`typescript
import { createBridge, ValidationRule } from 'forbocai';const bridge = createBridge({
strictMode: true // Reject unknown action types
});
// Validate an AI action
const result = await bridge.validate(
{ type: 'ATTACK', target: 'orc_1' },
{
agentState: { hp: 85, mana: 50 },
worldState: { entities: ['orc_1', 'player_1'] }
}
);
if (result.valid) {
executeAction(result.correctedAction || action);
} else {
console.log('Invalid action:', result.reason);
// Falls back to IDLE
}
// Register custom rules
bridge.registerRule({
id: 'game.fly',
name: 'Flying Validation',
actionTypes: ['FLY'],
validate: (action, ctx) => {
const hasWings = ctx.agentState?.hasWings;
return hasWings
? { valid: true }
: { valid: false, reason: 'Agent cannot fly without wings' };
}
});
`Built-in Rules:
-
core.movement — Validates MOVE coordinates and world bounds
- core.attack — Validates ATTACK target exists
- core.interact — Validates INTERACT object specified
- core.speak — Validates SPEAK text not empty
- core.resources — Validates HP/mana sufficient for action---
Module: Soul (IPFS Portability)
Sóul_Módule // Pórtal_IdéntityThe Soul module enables cross-game agent portability via IPFS.
`typescript
import { createSoulInstance, importSoulFromIPFS } from 'forbocai';// Create a Soul from agent data
const soul = createSoulInstance(
'agent_123',
'Kira the Merchant',
'A suspicious merchant who distrusts adventurers',
{ mood: 'suspicious', inventory: ['rusty_key'] },
memories // From Memory module
);
// Export to IPFS
const { cid, ipfsUrl, signature } = await soul.export();
console.log(
Soul pinned: ${ipfsUrl});
// ipfs://QmXyz...// Import Soul in another game
const importedSoul = await importSoulFromIPFS(cid);
console.log(importedSoul.persona);
// "A suspicious merchant who distrusts adventurers"
// Create new agent from Soul
import { createAgentFromSoul } from 'forbocai';
const { agentId, persona } = await createAgentFromSoul(cid, cortexId);
`Features:
- IPFS Pinning: Decentralized storage via Pinata/Helia
- Signature: Cryptographic proof of ownership
- NFT-Ready: Soul CID can be referenced in Metaplex NFT metadata
---
Module: Ghost (Automated QA)
Ghóst_Módule // Autómated_QAThe Ghost module runs headless AI agents for automated game testing.
`typescript
import { createGhost } from 'forbocai';// Configure Ghost session
const ghost = createGhost({
testSuite: 'exploration', // or 'combat', 'dialogue', 'pathfinding', 'full'
duration: 300, // seconds
captureScreenshots: true
});
// Start session
const sessionId = await ghost.run();
console.log(
Ghost session started: ${sessionId});// Poll status
const status = await ghost.status();
console.log(
Progress: ${status.progress}%);// Wait for completion with progress callback
const results = await ghost.waitForCompletion(
5000, // Poll every 5 seconds
300000, // Timeout after 5 minutes
(status) => console.log(
${status.progress}% complete)
);// Analyze results
console.log(
Tests: ${results.passed}/${results.totalTests} passed);
console.log(Coverage: ${(results.coverage * 100).toFixed(1)}%);
console.log(Avg FPS: ${results.metrics.avgFrameRate});// View failed tests
results.tests
.filter(t => !t.passed)
.forEach(t => console.log(
FAIL: ${t.name} - ${t.error}));
`Test Suites:
-
exploration — Pathfinding, map coverage, navigation
- combat — Battle mechanics, AI decisions, balance
- dialogue — NPC conversations, branching logic
- pathfinding — Navigation mesh, obstacle avoidance
- full — All tests combinedMetrics Collected:
-
avgFrameRate — Average FPS during test
- memoryUsageMB — Peak memory usage
- aiDecisionsPerSec — Agent decision throughput
- explorationCoverage — Map area discoveredDigital Souls (Solana/Metaplex)
Assét_Cláss // The_SóulIn the ForbocAI ecosystem, an NFT is not just a receipt—it is an Encapsulated Soul.
* The Container: A standardized bundle containing the Agent's Personality, Memories, and State.
The Chain: The NFT is the Deed of Ownership* pointing to this digital life.
Portability: Take your trained NPC from Forboc* to a sequel or entirely different world. Uses IPFS for decentralized persistence.
Economy: Train a specialist NPC and sell it on the open market. The value is in the Experience*, not just the skin.
---
Documentation
Dócs_Máp // Référence- Introduction — SDK overview and quick start
- User Stories — BDD specifications for all features
- Concepts — Architecture and core abstractions
- API Reference — Complete endpoint documentation
---
Links
Éxternal_Líns // Cónnect- Website: forboc.ai
- Documentation: docs.forboc.ai
- Discord: discord.gg/6hr2jHqnsG
- Telegram: t.me/forbocai
---
ᚠ ᛫ ᛟ ᛫ ᚱ ᛫ ᛒ ᛫ ᛟ ᛫ ᚲ
## Developers
Dev_Ops // Releáse_Cycles
To redeploy the SDK to NPM:
1. Bump Version: Update version in package.json.
2. Build: npm run build (Generates dist/).
3. Auth: Ensure sdk/.npmrc contains the valid token from ../api/NPM_TOKEN.md.
`bash
# Command to configure local .npmrc
echo "//registry.npmjs.org/:_authToken=YOUR_TOKEN_HERE" > .npmrc
`
4. Publish: npm publish --access public.
> Note: The .npmrc file is gitignored (.gitignore) to prevent leaking secrets. Always verify the token in api/NPM_TOKEN.md matches the active Granular Access Token.🧪 Testing Flow
Tést_Séquence // VálidátionTo verify the full end-to-end loop (SDK <-> NPM <-> Render API):
1. Local Updates: Make changes to
sdk/ or api/ code.
2. Deploy:
* SDK: Push to NPM (see Developers section above).
* API: Commit and push changes to GitHub (triggers Render auto-deploy).
3. Consume:
`bash
# In your client app (e.g. Forboc/client)
npm install forbocai@latest
`
4. Verify:
Use the CLI to check connection to the production API:
`bash
npx forbocai api status
# > Checking API Status (https://api.forboc.ai)...
# > Status: ONLINE
`
License
Légal_Státus // Ríghts`All rights reserved. © 2026 ForbocAI