main

Claude Code → Del Port Implementation Plan

Executive Summary

This document outlines a comprehensive plan to port Claude Code’s functionality to Del, replacing Anthropic’s Claude API with Ollama for local AI model execution. Del will maintain full compatibility with Claude Code’s interface while offering local processing capabilities.

Current Del Implementation State

COMPLETED FEATURES

  • File: cmd/del/main.go (1040 lines, 20 functions)
  • CLI Interface: Working command-line interface with --model flag
  • Basic Tools: 7 tools implemented:
    • read_file: Reads file contents with progress indicators
    • list_dir: Lists directory contents with file/folder counts
    • analyze_code: Auto-detects and analyzes code files (Go, Python, JS, etc.)
    • run_command: Executes shell commands
    • git_status: Checks Git repository status
    • write_file: Writes content to files
    • search_code: Searches for patterns in code
  • Markdown Rendering: ANSI-colored terminal output with headers, lists, code blocks
  • Tool Execution: Real-time progress streaming with Unicode indicators (● ⎿ ✅ ❌)
  • Model Integration: Works with Ollama API and DeepSeek Coder models
  • Auto-detection: Smart file detection for code analysis (prioritizes Go files)

RECENTLY COMPLETED

  1. Tool Calling: ✅ FIXED - Now uses Ollama’s native tool calling API instead of custom parsing
    • File Modified: cmd/del/main.go lines 2132-2249 (processMessage function)
    • Change: Replaced custom parseTextToolCalls() with proper Ollama tool calling
    • Status: Builds successfully, ready for testing

🔄 CURRENT ISSUES TO FIX

  1. No WebSocket: Currently CLI-only, needs WebSocket server for SDK
  2. Limited Tools: Only 7 tools vs Claude Code’s extensive tool set
  3. No SDK: Missing programmatic access module
  4. No MCP Integration: Need to connect to available MCP servers

🎯 IMMEDIATE NEXT TASKS

  1. Test Fixed Tool Calling: Verify Ollama native tool calling works correctly
  2. MCP Integration: Connect to available MCP servers in /usr/local/bin/mcp-*
    • Available: mcp-fetch, mcp-filesystem, mcp-git, mcp-maildir, mcp-memory, mcp-sequential-thinking, mcp-time
  3. WebSocket Server: Add real-time communication for SDK support

Analysis Phase Results

Claude Code Architecture Overview

Based on analysis of the deobfuscated source (cli.js - 345K lines) and package structure:

Core Components:

  • CLI Interface: Node.js-based terminal application (claude command)
  • SDK Module: sdk.mjs with TypeScript definitions for programmatic access
  • OAuth Authentication: Full OAuth2 flow with Anthropic Console integration
  • Streaming Communication: WebSocket-based real-time responses
  • Tool System: Extensive tool calling framework
  • Image Processing: Sharp integration for image handling

Key API Endpoints Discovered:

Base API: https://api.anthropic.com
OAuth Authorize: https://console.anthropic.com/oauth/authorize
Token: https://console.anthropic.com/v1/oauth/token
API Key Creation: https://api.anthropic.com/api/oauth/claude_cli/create_api_key
Roles: https://api.anthropic.com/api/oauth/claude_cli/roles

Authentication Flow:

  • OAuth2 with scopes: org:create_api_key, user:profile, user:inference
  • Client ID: 9d1c250a-e61b-44d9-88ed-5944d1962f5e
  • Local redirect server on port 54545

Implementation Roadmap

Phase 1: Foundation Architecture (Week 1-2)

1.1 Core Framework

  • Status: ⚡ PARTIALLY COMPLETE
  • Current State: Del has basic CLI, streaming, and tool execution
  • Remaining Work:
    • Implement WebSocket server for real-time communication
    • Add SDK module (del-sdk.mjs) for programmatic access
    • Create TypeScript definitions

1.2 Enhanced Tool System

  • Status: 🔄 IN PROGRESS
  • Current State: 7 basic tools implemented (read_file, list_dir, run_command, git_status, write_file, analyze_code, search_code)
  • Missing Tools to Add:
    • File operations: copy, move, delete, chmod
    • Advanced Git operations: commit, push, pull, branch, merge
    • Project analysis: dependency scan, test runner detection
    • Code refactoring: rename, extract function, format
    • Database operations: query, schema analysis
    • Web scraping: fetch URLs, parse HTML
    • Image processing: resize, convert, analyze
    • System monitoring: processes, disk usage, network

1.3 Markdown Rendering

  • Status: ✅ COMPLETE
  • Implementation: ANSI color-coded terminal rendering with headers, lists, code blocks

Phase 2: Advanced Communication Layer (Week 3-4)

2.1 WebSocket Server Implementation

New File: cmd/del-server/main.go

package main

import (
    "net/http"
    "github.com/gorilla/websocket"
    "github.com/ollama/ollama/api"
)

type DelServer struct {
    ollama      *api.Client
    wsUpgrader  websocket.Upgrader
    clients     map[*websocket.Conn]*Client
    tools       map[string]ToolFunc
    port        int
}

type Client struct {
    conn        *websocket.Conn
    sessionID   string
    chatHistory []api.Message
    mu          sync.RWMutex
}

func NewDelServer(port int) *DelServer {
    return &DelServer{
        port: port,
        wsUpgrader: websocket.Upgrader{
            CheckOrigin: func(r *http.Request) bool { return true },
        },
        clients: make(map[*websocket.Conn]*Client),
        tools:   make(map[string]ToolFunc),
    }
}

func (s *DelServer) Start() error {
    http.HandleFunc("/ws", s.handleWebSocket)
    http.HandleFunc("/api/v1/models", s.handleModels)
    http.HandleFunc("/api/v1/tools", s.handleTools)
    return http.ListenAndServe(fmt.Sprintf(":%d", s.port), nil)
}

Integration with existing Del:

  • Import tool functions from cmd/del/main.go
  • Extract tool registration into shared package pkg/tools/
  • Share message types in pkg/types/

2.2 Message Protocol

New File: pkg/types/messages.go

type WSMessage struct {
    Type      MessageType `json:"type"`
    SessionID string      `json:"session_id"`
    Content   string      `json:"content,omitempty"`
    ToolCall  *ToolCall   `json:"tool_call,omitempty"`
    Progress  *Progress   `json:"progress,omitempty"`
    Error     string      `json:"error,omitempty"`
    Timestamp int64       `json:"timestamp"`
}

type MessageType string

const (
    TypeUser         MessageType = "user"
    TypeAssistant    MessageType = "assistant"
    TypeToolStart    MessageType = "tool_start"
    TypeToolProgress MessageType = "tool_progress"
    TypeToolComplete MessageType = "tool_complete"
    TypeToolError    MessageType = "tool_error"
)

type ToolCall struct {
    Name string                 `json:"name"`
    Args map[string]interface{} `json:"args"`
    ID   string                 `json:"id"`
}

type Progress struct {
    Tool    string `json:"tool"`
    Status  string `json:"status"`
    Message string `json:"message"`
    Percent int    `json:"percent,omitempty"`
}

2.3 Streaming JSON Protocol

Exact format matching Claude Code SDK:

{"type": "user", "content": "analyze this code", "session_id": "sess_123"}
{"type": "tool_start", "tool_call": {"name": "analyze_code", "args": {}, "id": "tool_1"}}
{"type": "tool_progress", "progress": {"tool": "analyze_code", "status": "reading", "message": "Reading main.go..."}}
{"type": "tool_complete", "tool_call": {"name": "analyze_code", "id": "tool_1"}, "result": "Analysis: 20 functions"}
{"type": "assistant", "content": "## Analysis Results\n..."}

Phase 3: Enhanced Features (Week 5-6)

3.1 Multi-Model Support

type ModelProvider interface {
    Chat(ctx context.Context, req ChatRequest) (<-chan ChatResponse, error)
    ListModels() []Model
    SupportsTools() bool
}

type OllamaProvider struct {
    client *api.Client
    models []string
}

3.2 Configuration System

# ~/.del/config.yaml
models:
  default: "deepseek-coder-v2:16b"
  coding: "codellama:34b"
  analysis: "qwen2.5-coder:32b"

tools:
  enabled: true
  safe_mode: true
  custom_tools_dir: "~/.del/tools"

ui:
  markdown: true
  progress_indicators: true
  max_output_lines: 50

3.3 Plugin System

type Plugin interface {
    Name() string
    Commands() []Command
    Execute(cmd string, args []string) (string, error)
}

type Command struct {
    Name        string
    Description string
    Parameters  []Parameter
}

Phase 4: SDK and Integration (Week 7-8)

4.1 SDK Module (del-sdk.mjs)

New File: sdk/del-sdk.mjs (Copy from Claude Code pattern)

import { WebSocket } from 'ws';
import { createHash } from 'crypto';

export async function* query({
    prompt,
    options: {
        model = "deepseek-coder-v2:16b",
        maxTurns = 10,
        allowedTools = [],
        cwd = process.cwd(),
        delServerUrl = "ws://localhost:54546"
    } = {}
}) {
    const sessionId = createHash('sha256').update(Date.now().toString()).digest('hex').slice(0, 16);
    const ws = new WebSocket(`${delServerUrl}/ws`);
    
    try {
        await new Promise(resolve => ws.on('open', resolve));
        
        // Send initial message
        ws.send(JSON.stringify({
            type: 'user',
            content: prompt,
            session_id: sessionId,
            options: { model, maxTurns, allowedTools, cwd }
        }));
        
        // Stream responses
        for await (const message of websocketIterator(ws)) {
            const parsed = JSON.parse(message);
            yield parsed;
            
            if (parsed.type === 'assistant' && parsed.done) {
                break;
            }
        }
    } finally {
        ws.close();
    }
}

async function* websocketIterator(ws) {
    const messageQueue = [];
    let resolve;
    
    ws.on('message', (data) => {
        if (resolve) {
            resolve(data.toString());
            resolve = null;
        } else {
            messageQueue.push(data.toString());
        }
    });
    
    while (ws.readyState === WebSocket.OPEN) {
        if (messageQueue.length > 0) {
            yield messageQueue.shift();
        } else {
            yield new Promise(r => resolve = r);
        }
    }
}

TypeScript Definitions: sdk/del-sdk.d.ts

export interface QueryOptions {
    model?: string;
    maxTurns?: number;
    allowedTools?: string[];
    cwd?: string;
    delServerUrl?: string;
}

export interface DelMessage {
    type: 'user' | 'assistant' | 'tool_start' | 'tool_progress' | 'tool_complete' | 'tool_error';
    content?: string;
    session_id?: string;
    tool_call?: ToolCall;
    progress?: Progress;
    error?: string;
    timestamp?: number;
}

export interface ToolCall {
    name: string;
    args: Record<string, any>;
    id: string;
}

export declare function query(params: { prompt: string; options?: QueryOptions }): AsyncGenerator<DelMessage>;

Package.json: sdk/package.json

{
    "name": "@xlgmokha/del-sdk",
    "version": "1.0.0",
    "main": "del-sdk.mjs",
    "types": "del-sdk.d.ts",
    "type": "module",
    "dependencies": {
        "ws": "^8.0.0"
    },
    "bin": {
        "del": "../cmd/del/main"
    }
}

4.2 IDE Integration Preparation

  • VS Code extension boilerplate
  • IntelliJ plugin structure
  • Vim/Neovim plugin
  • Emacs package

4.3 Command Line Compatibility

# Claude Code commands -> Del equivalents
claude analyze ./src     # del analyze ./src
claude "fix this bug"    # del "fix this bug"
claude --model=sonnet    # del --model=codellama:34b

Phase 5: Advanced Tool Ecosystem (Week 9-10)

5.1 External Tool Integration

type ExternalTool struct {
    Name        string
    Command     string
    Args        []string
    Schema      ToolSchema
    Env         map[string]string
}

5.2 Specialized Tools

  • Code Analysis: AST parsing, complexity metrics, security scanning
  • Testing: Automatic test generation, test execution, coverage analysis
  • Documentation: README generation, API doc extraction
  • DevOps: Docker integration, CI/CD pipeline generation
  • Database: Schema visualization, query optimization

5.3 Custom Tool Creation

// ~/.del/tools/my_tool.go
package main

import "github.com/xlgmokha/deltron/sdk"

func main() {
    tool := &sdk.Tool{
        Name: "my_custom_tool",
        Description: "Does custom analysis",
        Execute: func(args map[string]interface{}) (string, error) {
            // Custom logic
        },
    }
    sdk.RegisterTool(tool)
}

Phase 6: Performance and Reliability (Week 11-12)

6.1 Performance Optimizations

  • Connection pooling for Ollama API
  • Response caching for repeated queries
  • Parallel tool execution
  • Streaming optimizations

6.2 Error Handling and Recovery

  • Graceful failure handling
  • Automatic retry mechanisms
  • Session persistence
  • Tool execution sandboxing

6.3 Testing and Quality Assurance

  • Unit tests for all tools
  • Integration tests with various models
  • Performance benchmarks
  • Security audits

API Specification

Core Del API

WebSocket Endpoint

ws://localhost:54546/ws

REST API Endpoints

GET    /api/v1/models          - List available models
POST   /api/v1/chat            - Start chat session
GET    /api/v1/tools           - List available tools
POST   /api/v1/tools/{name}    - Execute specific tool
GET    /api/v1/status          - Server health check

Message Types

const (
    TypeUser         = "user"
    TypeAssistant    = "assistant"
    TypeSystem       = "system"
    TypeTool         = "tool"
    TypeToolStart    = "tool_start"
    TypeToolProgress = "tool_progress"
    TypeToolComplete = "tool_complete"
    TypeToolError    = "tool_error"
    TypeError        = "error"
    TypePing         = "ping"
    TypePong         = "pong"
)

Tool Execution Protocol

Tool Definition

{
    "name": "analyze_code",
    "description": "Analyze code structure and metrics",
    "parameters": {
        "type": "object",
        "properties": {
            "path": {"type": "string", "description": "File path"},
            "language": {"type": "string", "description": "Programming language"}
        }
    }
}

Tool Execution Flow

// 1. Tool Start
{"type": "tool_start", "tool": "analyze_code", "args": {"path": "main.go"}}

// 2. Progress Updates
{"type": "tool_progress", "tool": "analyze_code", "status": "reading", "message": "Reading main.go..."}
{"type": "tool_progress", "tool": "analyze_code", "status": "analyzing", "message": "Analyzing structure..."}

// 3. Completion
{"type": "tool_complete", "tool": "analyze_code", "result": "Analysis: 20 functions, 1000 lines"}

Migration Path from Claude Code

For Users

  1. Installation: npm uninstall -g @anthropic-ai/claude-code && npm install -g @xlgmokha/del
  2. Configuration: del setup (auto-migrate Claude Code settings)
  3. Model Setup: del models install deepseek-coder-v2:16b
  4. Usage: Same commands, local processing

For Developers

  1. SDK Migration:
    // Old
    import { query } from '@anthropic-ai/claude-code';
    
    // New  
    import { query } from '@xlgmokha/del-sdk';
    
  2. WebSocket Migration: Update endpoint URLs
  3. Tool Definitions: Compatible JSON schema

Key Advantages of Del over Claude Code

Technical Benefits

  • Local Processing: No internet required after model download
  • Privacy: Code never leaves your machine
  • Speed: No API rate limits or network latency
  • Cost: No per-token charges
  • Customization: Plugin system for custom tools

Feature Enhancements

  • Multi-Model Support: Switch between different coding models
  • Tool Ecosystem: Extensive tool library
  • Better Integration: Deep OS and IDE integration
  • Markdown Rendering: Rich terminal output
  • Session Management: Persistent conversations

Success Metrics

Functional Parity

  • 100% tool compatibility with Claude Code
  • Streaming response time < 200ms
  • WebSocket reconnection success rate > 99%
  • SDK API compatibility > 95%

Performance Targets

  • Response time < 2s for simple queries
  • Tool execution time < 5s average
  • Memory usage < 500MB base
  • Startup time < 3s

User Experience

  • Installation success rate > 95%
  • Migration from Claude Code < 5 minutes
  • Zero-config startup for common use cases
  • Helpful error messages and debugging info

Risk Mitigation

Technical Risks

  • Ollama Compatibility: Test with multiple Ollama versions
  • Model Quality: Benchmark against Claude Code responses
  • Performance: Profile and optimize critical paths
  • Memory Usage: Implement efficient memory management

User Adoption Risks

  • Migration Complexity: Provide automated migration tools
  • Feature Gap: Prioritize most-used Claude Code features
  • Documentation: Comprehensive guides and examples
  • Community: Active support and issue resolution

Timeline Summary

Phase Duration Key Deliverables
1 Weeks 1-2 Core architecture, enhanced tools
2 Weeks 3-4 WebSocket server, streaming protocol
3 Weeks 5-6 Multi-model support, configuration
4 Weeks 7-8 SDK module, IDE integration prep
5 Weeks 9-10 Tool ecosystem, custom tools
6 Weeks 11-12 Performance, testing, release

Total Timeline: 12 weeks to full Claude Code parity with enhanced features

Context Recovery Information

Critical File Locations

  • Main Implementation: /home/mokhax/src/github.com/xlgmokha/deltron/cmd/del/main.go
  • Go Module: /home/mokhax/src/github.com/xlgmokha/deltron/go.mod
  • This Plan: /home/mokhax/src/github.com/xlgmokha/deltron/PLAN.md
  • Dependencies: Uses github.com/ollama/ollama/api for Ollama integration

Exact Current State

  • Del Binary: Built with go build cmd/del/main.go → creates main executable
  • Working Test: echo "analyze the code" | timeout 15s ./main --model deepseek-coder-v2:16b
  • Last Working Feature: Markdown rendering and tool execution with progress indicators

Build Instructions

cd /home/mokhax/src/github.com/xlgmokha/deltron
go build -o del cmd/del/main.go
./del --model deepseek-coder-v2:16b

Key Dependencies in go.mod

module github.com/xlgmokha/deltron
go 1.21
require github.com/ollama/ollama v0.1.18

Critical Lines to Modify Next

  • File: cmd/del/main.go
  • Lines 836-980: Replace custom tool parsing with Ollama native tools
  • Lines 67-96: Update system prompt for better tool calling
  • Lines 692-730: Add WebSocket server alongside CLI

Next Implementation Priority

  1. COMPLETED: Fix Ollama native tool calling (lines 2132-2249 in main.go)
  2. IMMEDIATE: Test the fixed tool calling system
  3. Week 1: MCP server integration (/usr/local/bin/mcp-*)
  4. Week 2: Add WebSocket server (cmd/del-server/main.go)
  5. Week 3: Extract tools to pkg/tools/ for sharing
  6. Week 4: Create SDK module (sdk/del-sdk.mjs)

Next Steps

  1. COMPLETED: Replace custom tool parsing with Ollama’s native tool support in cmd/del/main.go
  2. IMMEDIATE: Test and validate the fixed tool calling works with real models
  3. NEXT: Integrate MCP servers for enhanced functionality
    • mcp-memory for persistent memory system
    • mcp-filesystem for advanced file operations
    • mcp-git for enhanced git operations
    • mcp-fetch for web capabilities
  4. Week 1: Complete MCP integration and test all servers
  5. Week 2: Add WebSocket server for SDK support

Recovery Commands

# Navigate to project
cd /home/mokhax/src/github.com/xlgmokha/deltron

# Build current version (after tool calling fix)
go build -o del cmd/del/main.go

# Test current functionality
echo "analyze the code" | ./del --model deepseek-coder-v2:16b

# View this plan
cat PLAN.md

# Check available MCP servers
ls -la /usr/local/bin/mcp-*

Current Session Context Recovery

COMPLETED THIS SESSION

  1. Fixed Major Bug: Ollama native tool calling now works
    • File: /home/mokhax/src/github.com/xlgmokha/deltron/cmd/del/main.go
    • Lines Modified: 2132-2249 (processMessage function)
    • Change: Replaced custom parseTextToolCalls() with proper Ollama Chat API tool calling
    • Status: ✅ Builds successfully

🎯 IMMEDIATE NEXT PRIORITIES

  1. Test Tool Calling: Verify the fix works with real Ollama models
  2. MCP Memory Integration: Connect to mcp-memory for persistent conversation memory
  3. MCP File Operations: Connect to mcp-filesystem for enhanced file tools
  4. MCP Git Integration: Connect to mcp-git for advanced git operations

🧠 MEMORY SYSTEM PLAN

  • Goal: Give Del persistent memory across conversations to become “the best programmer in the world”
  • Implementation: Use mcp-memory server at /usr/local/bin/mcp-memory
  • Benefits: Remember every conversation, learn patterns, improve over time

📁 PROJECT STRUCTURE

/home/mokhax/src/github.com/xlgmokha/deltron/
├── cmd/del/main.go                 # Main Del implementation (MODIFIED)
├── PLAN.md                         # This file (UPDATED)
├── README.md                       # Project documentation
├── go.mod                          # Go dependencies
└── del                            # Built binary

🔗 MCP SERVERS AVAILABLE

/usr/local/bin/mcp-fetch            # Web fetching
/usr/local/bin/mcp-filesystem       # File operations
/usr/local/bin/mcp-git              # Git operations  
/usr/local/bin/mcp-maildir          # Email
/usr/local/bin/mcp-memory           # Memory/storage ⭐
/usr/local/bin/mcp-sequential-thinking  # Reasoning
/usr/local/bin/mcp-time             # Time operations

🚀 NEXT SESSION GOALS

  1. Test the fixed tool calling system
  2. Integrate mcp-memory for persistent conversation memory
  3. Integrate mcp-filesystem for advanced file operations
  4. Make Del remember everything and continuously improve

This plan provides complete context recovery information for seamless continuation of Del development. The major tool calling bug has been fixed and Del is ready for MCP integration to become a truly powerful, memory-enabled coding assistant.