Skip to content
scarecr0w12 edited this page Jun 24, 2026 · 3 revisions

CortexPrism — Agent Orientation

CortexPrism is an open-source AI agent operating system built on Deno 2.x + TypeScript strict mode. It hosts, orchestrates, and empowers AI agents with memory, tools, sandboxed code execution, a web UI, reflection, model routing, and layered security.


Build / Verify Commands

# Type-check — must exit 0 before any PR
deno task check

# Lint
deno task lint

# Format (auto-fixes)
deno task fmt

# Run all tests
deno task test

# Run a single test file
deno test --allow-all tests/<file>_test.ts

# Run check + lint + fmt in one shot
deno task check && deno task lint && deno task fmt

Runtime Commands

deno task dev          # Interactive chat (dev mode)
deno task serve        # HTTP + WebSocket server on :3000
deno task daemon       # Run background supervisor (foreground)
deno task migrate      # Apply all pending DB migrations

Project Layout

packages/
├── core/           — @cortex/core
│   ├── contracts/  —   config, db, i18n, paths, plugins (pure interfaces)
│   └── src/        —   config, db, i18n, utils, plugins
├── gate/           — @cortex/gate
│   ├── contracts/  —   policy, vault, sandbox, validator
│   └── src/        —   security, sandbox, vfs
├── ai/             — @cortex/ai
│   ├── contracts/  —   agent, tools, llm, memory, pipeline, skills
│   └── src/        —   agent, tools, memory, llm, pipeline, skills
├── server/         — @cortex/server
│   ├── contracts/  —   router, websocket, channels, mcp, middleware
│   └── src/        —   server, hub, channels, a2a, mcp, voice, workspace, codegraph
├── infra/          — @cortex/infra
│   ├── contracts/  —   scheduler, ipc, services, triggers
│   └── src/        —   processes, services, scheduler, ipc, triggers, workflow, observability, swarm
└── cli/            — @cortex/cli
    ├── contracts/  —   commands, registry, tui
    └── src/        —   cli, tui

src/
├── main.ts         — CLI entry point (composition root)
├── agent/          — agent loop orchestrator (81 lines)
│   stages/         —   7 pipeline stages
│   post/           —   post-turn modules
│   helpers/        —   shared helpers
├── server/
│   ├── server.ts   — HTTP server entry
│   ├── new-router.ts — route dispatcher
│   ├── routes/     —   69 route modules
│   └── ui/         —   78 modular UI files (29 JS, 46 pages, 3 shared)
└── tests/          —   27 test files

Multi-User & Federation

  • Source: src/server/auth.ts, src/server/identity.ts
  • PBKDF2 password hashing, team management with join policies, API token authentication (SHA-256 hashed)
  • Resource sharing between users, instance-to-instance federation
  • RequestIdentity carries user/team/admin context through all API routes

Swarm (packages/infra/src/swarm/)

  • Source: packages/infra/src/swarm/coordinator.ts
  • Distributed agent coordination across multiple Cortex instances via A2A protocol
  • 5 directive kinds: spawn_agent, execute_task, query_resources, forward_message, sync_state
  • Nodes register, discover peers, dispatch directives, and aggregate resource usage across the fleet

Key Conventions

TypeScript

  • Strict mode — no implicit any, no ! non-null assertions without a comment justifying why
  • Async-first — prefer async/await over raw Promise chains
  • Fire-and-forget — background tasks (memory write, reflection) use .catch(() => {}) and never block a response
  • Error handling — catch at call-site boundaries; surface actionable error messages to the user

Paths

  • Never hardcode paths — always import PATHS from packages/core/src/config/paths.ts
  • Data dir: ~/.cortex/data/ (override via CORTEX_DATA_DIR)
  • Config dir: ~/.cortex/ (override via CORTEX_CONFIG_DIR)

Database

  • SQL client: Db wrapper from packages/core/src/db/client.ts (libsql)
  • Migrations in packages/core/src/db/migrations/NNN_description.sqlidempotent, never edit once applied
  • Register new migrations in the targets array in packages/core/src/db/migrate.ts

Secrets / Security

  • No hardcoded credentials, API keys, or tokens anywhere in source
  • Use CORTEX_VAULT_KEY env var; store secrets via the vault module (packages/gate/src/security/vault.ts)
  • Every tool call is gated through the policy validator (packages/gate/src/security/validator.ts)

Adding a New CLI Command

  1. Create packages/cli/src/cli/your-cmd.ts exporting a Command from @cliffy/command
  2. Import and register it in packages/cli/src/cli/registry.ts or src/main.ts
  3. Document it in README.md and add a CHANGELOG.md entry

Adding a New Built-in Tool

  1. Create packages/ai/src/tools/builtin/your_tool.ts implementing the Tool interface from packages/ai/src/tools/types.ts
  2. Register it in packages/ai/src/tools/registry.ts
  3. Add it to the WebSocket handler in src/server/ws.ts if needed
  4. Add a policy rule if it executes shell commands or makes network requests

Adding a Database Migration

  1. Create packages/core/src/db/migrations/NNN_description.sql (next sequential number)
  2. Add an entry to the targets array in packages/core/src/db/migrate.ts
  3. Never edit a migration that has already been applied — create a new one instead

Subprocess Spawning

  • Use Deno.Command, never Deno.run (deprecated)

Before Committing

Always run all three verification steps before staging and committing:

deno task check && deno task lint && deno task fmt
  • deno fmt auto-fixes formatting (including markdown in CHANGELOG.md).
  • If deno fmt modified files, re-stage them before committing.
  • Never skip deno fmt — CI will reject unformatted files.

Commit Style

Conventional commits:

feat: add discord channel adapter
fix: handle empty response from Ollama
docs: update CLI reference for vault command
chore: bump deno.json dependencies
refactor: extract policy evaluation into pure function
test: add workspace path traversal cases

LLM Providers Supported

Anthropic, OpenAI, Google Gemini, Mistral, Groq, DeepSeek, OpenRouter, xAI, Together AI, AWS Bedrock, Cohere, Ollama, Kilo, Cerebras, Fireworks, Perplexity, NVIDIA, Moonshot, Novita, LM Studio, LiteLLM, HuggingFace, Alibaba, Venice, DeepInfra, Hyperbolic, MiniMax, Zhipu/GLM, Replicate, Cloudflare Workers AI (30 total). Provider adapters live in packages/ai/src/llm/.

Databases Used

File Purpose
cortex.db Core: sessions, jobs, policies, nodes, services
memory.db 5-tier memory (episodic, semantic, reflection, graph)
lens.db Cortex Lens audit log
vault.db Encrypted credential vault
plugins.db Plugin registry

Deno Import Map

Dependencies are declared in deno.json under "imports". Key packages:

  • @cliffy/command, @cliffy/prompt — CLI framework
  • @std/assert, @std/path, @std/fs, @std/fmt, @std/datetime — Deno standard library
  • npm:@anthropic-ai/sdk, npm:openai, npm:@google/generative-ai, npm:@aws-sdk/client-bedrock-runtime — LLM SDKs
  • npm:@libsql/client — SQLite/libSQL client

Clone this wiki locally