Chen Pilot is an intelligent AI agent that enables seamless interaction with blockchain networks and DeFi protocols through natural language commands. This agent provides a unified interface for managing Bitcoin wallets, Stellar operations, cross-chain swaps, and DeFi lending/borrowing activities.
- Node.js 18+
- PostgreSQL database
- Environment variables configured (see Configuration section)
git clone <repository-url>
cd chenpilot-experimentalpnpm installcp .env.example .env
# Edit .env with your configurationnpm run migration:runnpm run devChen Pilot includes an automated log rotation system with compression to efficiently manage log files.
- Daily Rotation: Logs automatically rotate at midnight
- Automatic Compression: Old logs are compressed to
.gzformat (80-90% size reduction) - Size-Based Rotation: Logs also rotate when reaching 20MB
- Automatic Cleanup: Old logs are deleted based on retention policies
- Sensitive Data Redaction: Passwords, tokens, and private keys are automatically redacted
logs/application-YYYY-MM-DD.log- All application logs (14 days retention)logs/error-YYYY-MM-DD.log- Error logs only (30 days retention)logs/exceptions-YYYY-MM-DD.log- Uncaught exceptions (30 days retention)logs/rejections-YYYY-MM-DD.log- Unhandled promise rejections (30 days retention)
Set the log level in your .env file:
LOG_LEVEL=info # Options: debug, info, warn, errorimport { logInfo, logError, logWarn, logDebug } from "./config/logger";
logInfo("User logged in", { userId: "123" });
logError("Database error", error, { context: "user-service" });For more details, see src/config/LOGGING.md
This project uses Husky, lint-staged, and commitlint to enforce code quality and commit message standards.
-
pre-commit
- Runs ESLint with auto-fix
- Runs Prettier formatting
- Blocks commits if checks fail
-
commit-msg
- Validates commit messages using Commitlint
- Enforces Conventional Commits format
- Blocks commits with invalid commit messages
This setup helps maintain consistent code style and a clean, readable git history.
Git hooks are enabled automatically after installing dependencies:
pnpm installIf hooks do not run for any reason, re-enable Husky manually:
pnpm exec husky installpnpm exec lint-stagedpnpm exec commitlint --edit $1{
"**/*.{ts,tsx}": ["eslint --fix", "prettier --write"]
}Commit messages must follow the Conventional Commits specification.
Examples of valid commit messages:
feat: add cross-chain swap workflow
fix: handle null wallet address
chore: update dependencies
docs: update README
Hooks can be skipped in exceptional cases:
git commit --no-verify
⚠️ Use sparingly. CI checks will still run and invalid commits may be rejected.
The agent uses an intelligent workflow system that:
- Parses Intent: Understands natural language commands
- Plans Workflow: Creates step-by-step execution plans
- Executes Tools: Runs appropriate tools in sequence
- Manages State: Tracks operation status and results
- Provides Feedback: Returns structured responses
For visual diagrams of how the agents, tool registry, and external services interact, see ARCHITECTURE_DIAGRAMS.md (Mermaid).
Use the SDK idempotency helpers to guarantee retries do not create duplicate intents.
import {
AgentClient,
createBtcToStellarSwapIdempotencyKey,
ChainId,
} from "@chen-pilot/sdk-core";
const client = new AgentClient({ baseUrl: "https://your-chenpilot-api" });
const swapRequest = {
fromChain: ChainId.BITCOIN,
toChain: ChainId.STELLAR,
fromToken: "BTC",
toToken: "XLM",
amount: "0.01",
destinationAddress: "G...",
};
// Generate once, persist in your app state, and reuse on retries
const idempotencyKey = createBtcToStellarSwapIdempotencyKey(
swapRequest,
"wallet-action-123"
);
await client.executeBtcToStellarSwap(swapRequest, {
userId: "user-uuid",
idempotencyKey,
maxRetries: 3,
});If a timeout/network failure happens, call executeBtcToStellarSwap again with the same idempotencyKey.
The SDK package includes TypeDoc configuration for automated HTML API reference generation.
cd packages/sdk
npm install
npm run docsGenerated output is written to:
packages/sdk/docsGitHub Actions workflow: .github/workflows/sdk-docs.yml
On each push to main, the workflow:
- Installs SDK dependencies
- Runs
npm run docsinpackages/sdk - Deploys the generated HTML docs to GitHub Pages
The system uses Redis-based distributed locks to prevent race conditions when executing multiple trades for the same user concurrently.
- Lock Key Pattern:
trade:{userId}- Ensures one trade per user at a time - Lock TTL: 60 seconds with configurable retry strategy
- Atomic Operations: Uses Redis SET with NX/EX and Lua scripts for safe lock/release
- Automatic Cleanup: Locks auto-expire to prevent deadlocks
- Acquire Lock:
acquireLock(resourceKey, identifier, options) - Release Lock:
releaseLock(resourceKey, identifier)- Only releases if owned by identifier - Extend Lock:
extendLock(resourceKey, identifier, ttl)- For long-running operations - Status Check:
isLocked(resourceKey)andgetLockInfo(resourceKey)
The SwapTool automatically acquires a user-specific lock before executing trades:
const lockKey = `trade:${userId}`;
const lockResult = await lockService.acquireLock(lockKey, userId, {
ttl: 60000,
retryDelay: 200,
maxRetries: 15,
});
if (!lockResult.acquired) {
return this.createErrorResult(
"swap",
"Another trade is currently in progress for your account. Please wait a moment and try again."
);
}
// Execute trade with lock held...
// Lock is automatically released in finally blockRedis connection is configured via environment variables:
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=optional
REDIS_DB=0- Lock Acquisition Failure: Returns user-friendly error message
- Redis Connection Issues: Graceful fallback with error logging
- Lock Extension: Supports long-running operations beyond initial TTL
- Automatic Release: Locks auto-expire to prevent permanent locks
- Fork the repository
- Create a feature branch
- Make your changes
- Ensure pre-commit and commit message checks pass
- Add tests if applicable
- Submit a pull request
This project is licensed under the ISC License.
For support and questions:
- Create an issue in the repository
- Check the API health endpoints
- Review the logs for error details
Chen Pilot — Your intelligent gateway to cross-chain DeFi operations