{"id":50146726,"url":"https://github.com/mmmarcinho/cortex-agent","last_synced_at":"2026-05-24T05:08:37.222Z","repository":{"id":357652996,"uuid":"1237253708","full_name":"MMMarcinho/cortex-agent","owner":"MMMarcinho","description":"A cyber bionic Agent with human-like memory, thinking and logical reasoning capabilities.","archived":false,"fork":false,"pushed_at":"2026-05-19T06:17:41.000Z","size":175,"stargazers_count":0,"open_issues_count":0,"forks_count":1,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-05-19T08:52:06.314Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/MMMarcinho.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-05-13T02:40:01.000Z","updated_at":"2026-05-19T06:14:04.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/MMMarcinho/cortex-agent","commit_stats":null,"previous_names":["mmmarcinho/connor-agent","mmmarcinho/cortex-agent"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/MMMarcinho/cortex-agent","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MMMarcinho%2Fcortex-agent","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MMMarcinho%2Fcortex-agent/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MMMarcinho%2Fcortex-agent/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MMMarcinho%2Fcortex-agent/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/MMMarcinho","download_url":"https://codeload.github.com/MMMarcinho/cortex-agent/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MMMarcinho%2Fcortex-agent/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33422097,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-23T22:14:44.296Z","status":"online","status_checked_at":"2026-05-24T02:00:06.296Z","response_time":57,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-05-24T05:08:22.121Z","updated_at":"2026-05-24T05:08:37.217Z","avatar_url":"https://github.com/MMMarcinho.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# cortex-agent\n\nA cyber bionic AI agent with human-like cognition — long-term memory, a live emotion model, and adaptive behavioral modes that shift as the session evolves.\n\n## What makes it different\n\nMost agents are stateless: every session starts blank, every response is calculated the same way. Cortex is designed around the observation that effective human intelligence is not stateless — it carries memory across time, adapts its behavior based on internal state, and knows when it's confident vs. uncertain, energized vs. depleted.\n\nCortex implements this through three interlocking systems:\n\n**Emotion model** — five continuous dimensions (energy, focus, frustration, novelty, confidence) that change in response to tool outcomes, user feedback, memory hits, and idle time. Not cosmetic: the values directly influence what the agent does and how it talks to you.\n\n**Long-term memory** — powered by [aizo](https://github.com/mmmarcinho/aizo), a Rust-based semantic memory store. Preferences, patterns, tool outcomes, and session insights are written back automatically. Recalled at the start of every turn and injected into the system prompt.\n\n**Behavioral modes** — four discrete modes (PROTECT, CONSERVE, EXPLORE, DELIVER) selected each turn from the emotional state and memory signals. Each mode changes the system prompt directive and tool availability.\n\n---\n\n## Architecture\n\n```\nsrc/\n├── index.ts                  # CLI entry point, session lifecycle\n├── config.ts                 # Config loading (file + env vars)\n├── types.ts                  # All shared types\n│\n├── runtime/\n│   ├── index.ts              # Main Runtime class — orchestrates everything\n│   ├── emotion.ts            # EmotionState, EmotionTrajectory, recall bias, prompt modifiers\n│   ├── behavioral_mode.ts    # Mode selection (PROTECT / CONSERVE / EXPLORE / DELIVER)\n│   └── working_memory.ts     # TaskStack, EpisodicBuffer, WorkingMemory\n│\n├── llm/\n│   ├── types.ts              # ChatClient interface + message types\n│   ├── index.ts              # Provider loader (reads llm.config.json)\n│   ├── anthropic.ts          # Anthropic SDK client\n│   └── openai.ts             # OpenAI-compatible client (Ollama, Groq, Together, etc.)\n│\n├── aizo_bridge/\n│   └── index.ts              # aizo binary wrapper: recall, add, touch, top, analyze\n│\n├── reflection/\n│   └── index.ts              # Mid-session reflection trigger and runner\n│\n├── session/\n│   └── index.ts              # Session logger (transcript.md, events.jsonl, summary.json)\n│\n└── tools/\n    ├── index.ts              # ToolRegistry\n    └── builtins/\n        ├── shell.ts          # shell — run arbitrary shell commands\n        ├── read_file.ts      # read_file — read a file from disk\n        ├── write_file.ts     # write_file — write a file to disk\n        └── grep.ts           # grep — search file contents\n```\n\n---\n\n## Emotion model\n\nEach turn the agent maintains five dimensions, all clamped to `[0, 1]`:\n\n| Dimension | Starts at | Meaning |\n|-----------|-----------|---------|\n| `energy` | 1.0 | Capacity for complex work. Drains with each LLM call and tool use |\n| `focus` | 0.7 | Alignment with the current task. Drops on task switches |\n| `frustration` | 0.05 | Accumulated friction. Rises on tool failures, negative feedback |\n| `novelty` | 0.5 | Degree of unexplored territory. Rises when memory recalls nothing |\n| `confidence` | 0.5 | Trust in own judgement. Rises on successes, drops on failures |\n\n**Natural decay** — frustration and novelty drift back toward baseline at 5% per minute of idle time.\n\n**Cross-session carry-over** — the emotion snapshot from the end of a session is averaged with the defaults at the start of the next one, so a session that ended frustrated does not restart at peak confidence.\n\n**Trajectory** — a rolling 5-snapshot window fits a linear trend over each dimension. These trends adjust the thresholds used by behavioral modes and prompt modifiers.\n\n**Flow state** — when both novelty trend and confidence trend are positive, the agent is in flow: all caution modifiers are suppressed and it runs without second-guessing itself.\n\n---\n\n## Behavioral modes\n\nSelected every turn from emotion and memory signals:\n\n| Mode | Trigger | Effect |\n|------|---------|--------|\n| `PROTECT` | Risk pattern in input, or taboo memory matched | Warns user, refuses to execute, asks for explicit confirmation |\n| `CONSERVE` | Energy \u003c 0.3 or frustration \u003e 0.7 | Minimal response, complex tools suppressed, defers to user |\n| `EXPLORE` | Novelty \u003e 0.6 and confidence \u003e 0.5 | Considers alternatives before acting, notes interesting options |\n| `DELIVER` | Default | Executes directly, no extra commentary |\n\nRisk patterns that trigger PROTECT include: `rm -rf`, `drop table`, `force push`, `chmod 777`, `kill -9`, and similar destructive commands.\n\n---\n\n## Long-term memory (aizo)\n\nCortex uses [aizo](https://github.com/mmmarcinho/aizo) — a Rust binary — as its memory backend. Aizo stores items with a score (0–10), keywords, and a reason string. Items decay over time and are re-weighted by access frequency.\n\n**What gets written automatically:**\n- Tool success/failure patterns (with tool name and exit code snippet)\n- Emotional threshold crossings (e.g. frustration spike during a specific tool)\n- Confidence builders (high-confidence moments tied to task types)\n- Session-end emotion state (for cross-session carry-over)\n\n**End-of-session extraction** — at shutdown, the full session transcript is piped through `aizo extract` (which generates a structured extraction prompt), then through the reflection LLM, then through `aizo import`. This extracts user preferences, habits, and patterns from natural conversation without any manual annotation.\n\n**Mid-session reflection** — triggered after 15 tool calls or 10 minutes of idle time. Uses the reflection LLM to review the episodic buffer and confirm which memory items are still relevant (via `aizo touch`), plus optional corrections to novelty and confidence.\n\n**Memory-biased recall** — the recall query is modified by emotional state before hitting aizo:\n- High frustration: appends `safe reliable` to the query and includes taboo items\n- Low confidence: filters to only high-score items (≥ 7.0)\n- Low energy: caps results at 5\n\n---\n\n## Multi-provider LLM\n\nCortex decouples the LLM from the agent. Any provider that speaks the OpenAI API format works.\n\nTwo independent clients are configured: **main** (used for every agent turn) and **reflection** (used for mid-session reflection and end-of-session memory extraction). You can use a large model for main and a cheap/fast model for reflection.\n\n### Configuration file\n\nCreate `llm.config.json` in the project root, or `~/.cortex/llm.config.json` for global defaults. Project-local file takes priority.\n\n```json\n{\n  \"main\": {\n    \"provider\": \"anthropic\",\n    \"model\": \"claude-sonnet-4-6\"\n  },\n  \"reflection\": {\n    \"provider\": \"anthropic\",\n    \"model\": \"claude-haiku-4-5-20251001\"\n  }\n}\n```\n\n**Using Ollama (local):**\n```json\n{\n  \"main\": {\n    \"provider\": \"openai\",\n    \"model\": \"llama3.1:8b\",\n    \"base_url\": \"http://localhost:11434/v1\"\n  },\n  \"reflection\": {\n    \"provider\": \"openai\",\n    \"model\": \"qwen2.5:3b\",\n    \"base_url\": \"http://localhost:11434/v1\"\n  }\n}\n```\n\n**Using Groq:**\n```json\n{\n  \"main\": {\n    \"provider\": \"openai\",\n    \"model\": \"llama-3.3-70b-versatile\",\n    \"base_url\": \"https://api.groq.com/openai/v1\",\n    \"api_key\": \"gsk_...\"\n  },\n  \"reflection\": {\n    \"provider\": \"openai\",\n    \"model\": \"llama-3.1-8b-instant\",\n    \"base_url\": \"https://api.groq.com/openai/v1\",\n    \"api_key\": \"gsk_...\"\n  }\n}\n```\n\n---\n\n## Installation\n\n**Requirements:** Node.js ≥ 18, TypeScript 6\n\n```bash\ngit clone https://github.com/mmmarcinho/cortex-agent\ncd cortex-agent\nnpm install\nnpm run build\n```\n\n**aizo** (the memory backend) is bundled via `aizo-node` and downloaded automatically on `npm install`. If the binary is unavailable, the agent runs in degraded memory mode — everything still works, memory is just not persisted.\n\nYou can also install aizo manually via Cargo:\n```bash\ncargo install aizo\n```\n\n---\n\n## Running\n\n```bash\nnpm start\n```\n\n```\ncortex initializing...\nSession: 2026-05-19-143022\nReady. Type your message, /status, /task \u003cdesc\u003e, /done, /reset, or /quit\n\nyou\u003e\n```\n\n### CLI commands\n\n| Command | Description |\n|---------|-------------|\n| `/status` | Show current emotion state with bar chart and active mode |\n| `/task \u003cdescription\u003e` | Push a new task onto the task stack |\n| `/done` | Mark the active task complete (triggers confidence and energy boost) |\n| `/reset` | Clear conversation history (keeps memory and emotion state) |\n| `/quit` or `/exit` | End session and run memory extraction from transcript |\n\n### Bootstrap memory\n\nSeed the agent's memory from `MEMORY.md`:\n\n```bash\nnpm run bootstrap\n```\n\nEdit `MEMORY.md` to define initial preferences, habits, and taboos before the first run. Each `memory-seed` block is an item with a score and keywords.\n\n### Replay an emotion timeline\n\nReconstruct how the emotion model evolved across a saved session:\n\n```bash\nnpm run replay -- ~/.cortex/sessions/2026-05-19-143022/events.jsonl\n```\n\nPrints a step-by-step table of all five emotion dimensions across every logged event.\n\n---\n\n## Configuration\n\nConfig is loaded in priority order: defaults → `~/.cortex/config.json` → `./.cortex/config.json` → environment variables.\n\n```json\n{\n  \"model\": \"claude-sonnet-4-6\",\n  \"reflection_model\": \"claude-haiku-4-5-20251001\",\n  \"max_tokens\": 4096,\n\n  \"aizo_binary\": \"aizo\",\n  \"aizo_db\": \"~/.cortex/memory.db\",\n\n  \"sessions_dir\": \"~/.cortex/sessions\",\n\n  \"reflection_tool_call_threshold\": 15,\n  \"reflection_idle_minutes_threshold\": 10,\n\n  \"emotion\": {\n    \"llm_call_energy_cost\": 0.02,\n    \"tool_success_confidence_gain\": 0.05,\n    \"tool_failure_frustration_gain\": 0.1,\n    \"task_completed_energy_gain\": 0.12\n  }\n}\n```\n\n### Environment variables\n\n| Variable | Description |\n|----------|-------------|\n| `CORTEX_MODEL` | Override the main model |\n| `CORTEX_MAX_TOKENS` | Override max tokens per call |\n| `CORTEX_SESSIONS_DIR` | Override sessions directory |\n| `AIZO_BINARY` | Path to aizo binary |\n| `AIZO_DB` | Path to aizo database file |\n| `ANTHROPIC_API_KEY` | Anthropic API key |\n| `OPENAI_API_KEY` | OpenAI-compatible API key |\n\n---\n\n## Session output\n\nEach session writes three files to `~/.cortex/sessions/\u003csession-id\u003e/`:\n\n| File | Contents |\n|------|----------|\n| `transcript.md` | Human-readable log of every turn with emotion bar |\n| `events.jsonl` | Machine-readable event stream (turns, tool calls, task events) |\n| `summary.json` | Session totals: turns, tool calls, duration, final emotion snapshot |\n\n---\n\n## Adding tools\n\nAdd a `.ts` file to `src/tools/builtins/`. Export an object matching the `Tool` interface:\n\n```typescript\nimport type { Tool } from '../../types';\n\nconst myTool: Tool = {\n  name: 'my_tool',\n  description: 'What this tool does',\n  params: [\n    { name: 'input', type: 'string', desc: 'The input string', required: true },\n  ],\n  handler: async (params) =\u003e {\n    const result = doSomething(params['input'] as string);\n    return { exitCode: 0, stdout: result, stderr: '' };\n  },\n};\n\nmodule.exports = myTool;\n```\n\nThe tool is auto-discovered and registered at startup. To mark it as complex (suppressed in CONSERVE mode), add its name to `COMPLEX_TOOLS` in `src/tools/index.ts`.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmmmarcinho%2Fcortex-agent","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmmmarcinho%2Fcortex-agent","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmmmarcinho%2Fcortex-agent/lists"}