Commit 78b3e22

mo khan <mo@mokhan.ca>
2025-06-23 00:30:02
docs: update PLAN.md
1 parent 11443cd
Changed files (1)
PLAN.md
@@ -4,6 +4,34 @@
 
 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)
+
+### 🔄 **CURRENT ISSUES TO FIX**
+1. **Tool Calling**: Uses custom parsing instead of Ollama's native tool support
+2. **No WebSocket**: Currently CLI-only, needs WebSocket server for SDK
+3. **Limited Tools**: Only 7 tools vs Claude Code's extensive tool set
+4. **No SDK**: Missing programmatic access module
+
+### 🎯 **IMMEDIATE NEXT TASK**
+**File to modify**: `cmd/del/main.go` around lines 836-980 (tool calling section)
+**Goal**: Implement native Ollama tool calling to replace custom parsing
+
 ## Analysis Phase Results
 
 ### Claude Code Architecture Overview
@@ -64,22 +92,59 @@ Roles: https://api.anthropic.com/api/oauth/claude_cli/roles
 ### Phase 2: Advanced Communication Layer (Week 3-4)
 
 #### 2.1 WebSocket Server Implementation
+
+**New File**: `cmd/del-server/main.go`
 ```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 []Message
+    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`
 ```go
 type WSMessage struct {
     Type      MessageType `json:"type"`
@@ -88,15 +153,41 @@ type WSMessage struct {
     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**:
 ```json
-{"type": "user", "content": "analyze this code"}
-{"type": "tool_start", "tool": "analyze_code", "args": {}}
-{"type": "tool_progress", "tool": "analyze_code", "status": "reading"}
-{"type": "tool_complete", "tool": "analyze_code", "result": "..."}
+{"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..."}
 ```
 
@@ -153,18 +244,116 @@ type Command struct {
 ### 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)
 ```javascript
+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()
+        cwd = process.cwd(),
+        delServerUrl = "ws://localhost:54546"
     } = {}
 }) {
-    const ws = new WebSocket('ws://localhost:54546');
-    // Implementation similar to Claude Code's SDK
+    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`
+```typescript
+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`
+```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"
+    }
 }
 ```
 
@@ -389,11 +578,67 @@ const (
 
 **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
+```bash
+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. **IMMEDIATE**: Fix Ollama native tool calling (lines 836-980 in main.go)
+2. **Week 1**: Add WebSocket server (`cmd/del-server/main.go`)
+3. **Week 2**: Extract tools to `pkg/tools/` for sharing
+4. **Week 3**: Create SDK module (`sdk/del-sdk.mjs`)
+
 ## Next Steps
 
-1. **Week 1**: Complete WebSocket server implementation
-2. **Week 2**: Add missing tool implementations  
-3. **Week 3**: Begin SDK module development
-4. **Week 4**: Start documentation and examples
+1. **IMMEDIATE**: Replace custom tool parsing with Ollama's native tool support in `cmd/del/main.go`
+2. **Week 1**: Complete WebSocket server implementation in new `cmd/del-server/main.go`
+3. **Week 2**: Extract tools into shared `pkg/tools/` package
+4. **Week 3**: Begin SDK module development in `sdk/del-sdk.mjs`
+5. **Week 4**: Start documentation and examples
+
+### Recovery Commands
+```bash
+# Clone repository
+git clone https://github.com/xlgmokha/deltron
+cd deltron
+
+# Build current version
+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
+```
 
-This plan provides a roadmap for creating a full-featured, local alternative to Claude Code while maintaining compatibility and adding significant enhancements through the Ollama ecosystem.
\ No newline at end of file
+This plan provides complete implementation details for creating a full-featured, local alternative to Claude Code while maintaining compatibility and adding significant enhancements through the Ollama ecosystem. All file structures, code examples, and exact next steps are documented for seamless continuation after context loss.
\ No newline at end of file