# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview

**Foliko** is a minimalist plugin-based Agent framework in pure JavaScript (no TypeScript). It provides a lightweight core with extensible plugins for AI conversation, tool execution, workflow automation, and more.

## Commands

```bash
# Run basic example
npm start

# CLI chat mode
npm run chat

# Proactive agent examples
npm run proactive
npm run proactive:advanced

# No test suite yet
npm test
```

## Architecture

```
┌─────────────────────────────────────────────────┐
│                  Foliko Framework               │
├─────────────────────────────────────────────────┤
│  Framework (Container Layer)                    │
│  ├── pluginManager    - Plugin lifecycle       │
│  ├── toolRegistry    - Tool registration       │
│  ├── skillManager    - Skill management        │
│  ├── eventEmitter    - Event bus               │
│  └── Context System  - Session/Request/Agent  │
├─────────────────────────────────────────────────┤
│  Agent (Dialogue Layer)                         │
│  ├── chat()           - Send messages          │
│  ├── chatStream()     - Streaming responses    │
│  ├── tools           - From Framework         │
│  └── events          - Message/tool events    │
└─────────────────────────────────────────────────┘
```

### Context Architecture (分层上下文)

```
┌─────────────────────────────────────────────────┐
│              Request Context (Layer 1)            │
│  requestId, traceId, timeout, startTime        │
└─────────────────────────────────────────────────┘
                        │
                        ▼
┌─────────────────────────────────────────────────┐
│              Session Context (Layer 2)            │
│  sessionId, variables, messageStore            │
│  Per-Session 消息存储，变量管理，元数据          │
└─────────────────────────────────────────────────┘
                        │
                        ▼
┌─────────────────────────────────────────────────┐
│              Agent Context (Layer 3)            │
│  agentId, tools, skills, systemPrompt         │
└─────────────────────────────────────────────────┘
```

**Key Features**:

- Per-Session 消息隔离：每个 session 有独立的消息数组
- AsyncLocalStorage 三层隔离：Request / Session / Agent
- SessionContext 管理会话变量、元数据、压缩状态

### Core Classes

- **Framework** (`src/core/framework.js`) - Container managing plugins, tools, events, and agent creation
- **Agent** (`src/core/agent.js`) - Handles conversation, tool calls, subAgent delegation, and message queuing
- **Plugin** (`src/core/plugin-base.js`) - Base class with `install()`, `start()`, `reload()`, `uninstall()` lifecycle
- **PluginManager** (`src/core/plugin-manager.js`) - Manages plugin loading, priority ordering, and hot reload
- **ToolRegistry** (`src/core/tool-registry.js`) - Registers and executes tools with Zod schemas
- **AgentChatHandler** (`src/core/agent-chat.js`) - Handles AI provider communication and tool call loops
- **SessionContext** (`src/core/session-context.js`) - Per-Session 上下文，管理消息、变量、元数据
- **RequestContext** (`src/core/request-context.js`) - Per-Request 上下文，链路追踪、超时控制
- **ContextManager** (`src/core/context-manager.js`) - 上下文生命周期管理

### Directory Structure

```
src/
├── core/           # Framework, Agent, PluginManager, ToolRegistry
├── capabilities/   # SkillManager, WorkflowEngine
├── executors/      # MCPExecutor for MCP server integration
└── utils/          # EventEmitter

plugins/            # Built-in plugins (ai-plugin, tools-plugin, shell/python executors, session, scheduler, etc.)
cli/bin/           # CLI entry point
.agent/            # User configuration (plugins, skills, agents, mcp_config.json)
examples/          # Usage examples
```

### Plugin System

Plugins are registered via `framework.registerPlugin()` and loaded with `framework.loadPlugin()`. Each plugin:

- Has a `name`, `version`, `description`, and `priority`
- Implements `install(framework)` to register tools/events
- Implements `start(framework)` after initialization
- Can implement `reload(framework)` for hot reload
- Can implement `uninstall(framework)` for cleanup

### AI Integration

Uses Vercel AI SDK (`ai` package) with support for multiple providers:

- Anthropic, DeepSeek, MiniMax, OpenAI, OpenAI-Compatible

Provider selection via `config.provider` and AI settings in `.agent/ai.json`.

### Key Patterns

1. **Context Isolation**: Three-layer AsyncLocalStorage for Request/Session/Agent isolation
   - `framework.runInSession(sessionId, options, fn)` - 在 Session 上下文中执行
   - `framework.getCurrentSessionContext()` - 获取当前 Session Context
   - `framework.getRequestContext()` - 获取当前 Request Context
2. **Tool Execution**: Tools receive `(args, framework)` and return results; errors should be caught and returned as `{error: message}`
3. **Event System**: Framework emits events like `framework:ready`, `plugin:loaded`, `agent:message`, `tool-call`
4. **Hot Reload**: Manual only via `framework.reloadPlugin(name)` or `framework.reloadAllPlugins()` - no file watching
5. **Per-Session Message Storage**: `AgentChatHandler` uses `_sessionMessageStores` Map for Per-Session 消息隔离

### Built-in Plugins

- **ai-plugin** - AI conversation via Vercel AI SDK
- **tools-plugin** - Plugin management tools (list, reload, enable/disable)
- **shell-executor-plugin** - Shell command execution
- **python-executor-plugin** - Python code/script execution
- **session-plugin** - Multi-session management
- **scheduler-plugin** - Cron-based task scheduling
- **subagent-plugin** - Child agent isolation
- **email.js** - SMTP/IMAP email
- **telegram-plugin.js** - Telegram bot integration
- **audit-plugin.js** - Operation logging
- **rules-plugin.js** - Permission/content rules
- **storage-plugin.js** - Key-value persistence
