FiveTech Support Forums

FiveWin / Harbour / xBase community
Board index Artificial Intelligence examples Claude Code app architecture
Posts: 44158
Joined: Thu Oct 06, 2005 05:47 PM
Claude Code app architecture
Posted: Fri Apr 17, 2026 07:32 PM
/*
   ================================================
   SIMULADOR DE CLAUDE CODE  (estilo Harbour)
   ================================================
   Este es un pseudo-código en sintaxis Harbour/Clipper
   que ilustra la arquitectura real de Claude Code:
   

   - Bucle principal del agente (Agent Loop)
   - Construcción de contexto
   - Llamada al modelo (mock)
   - Sistema de tools con chequeo de seguridad
   - Memoria persistente (CLAUDE.md)
   - Gestión de permisos
*/

PROCEDURE Main()

   LOCAL cInputUsuario   := ""
   LOCAL cContexto       := ""
   LOCAL cRespuestaClaude:= ""
   LOCAL lEjecutando     := .T.
   LOCAL nIteracion      := 0

   ? "========================================"
   ? "   CLAUDE CODE SIMULATOR (Harbour Edition)"
   ? "   Arquitectura real del agente de Anthropic"
   ? "========================================"
   ? "Escribe 'exit' para terminar"
   ?

   // Inicializar memoria persistente
   InitMemoria()

   DO WHILE lEjecutando

  nIteracion++

  // 1. Entrada del usuario
  ACCEPT "Usuario> " TO cInputUsuario
  IF LOWER(ALLTRIM(cInputUsuario)) == "exit"
     lEjecutando := .F.
     LOOP
  ENDIF

  // 2. Construir contexto completo (la parte más importante del "moat")
  cContexto := ConstruirContexto( cInputUsuario )

  // 3. Llamada al modelo (aquí iría la API de Claude)
  cRespuestaClaude := LlamarModeloClaude( cInputUsuario, cContexto )

  ? "Claude está pensando..."

  // 4. ¿La respuesta contiene tool calls?
  IF TieneToolCalls( cRespuestaClaude )

     // 5. Sistema de seguridad y permisos
     IF ChequearSeguridad( cRespuestaClaude )
        // Ejecutar herramientas
        EjecutarTools( cRespuestaClaude )
     ELSE
        ? "⚠️  Acción bloqueada por políticas de seguridad"
     ENDIF

  ELSE
     // Respuesta normal (sin tools)
     ? "Claude> " + cRespuestaClaude
  ENDIF

  // 6. Actualizar memoria persistente (CLAUDE.md)
  ActualizarMemoria( cInputUsuario, cRespuestaClaude )

  ? "Iteración #" + STR(nIteracion) + " completada"
  ? REPLICATE("-", 50)

   ENDDO

   ? "Claude Code ha terminado. ¡Hasta la próxima!"

RETURN

// ------------------------------------------------------------------
// FUNCIONES AUXILIARES (ilustran los componentes reales)

FUNCTION ConstruirContexto( cPrompt )
   LOCAL cMemoria := ""
   LOCAL cArchivos:= ""

   // Capa 1: Memoria persistente (siempre en contexto)
   cMemoria := LeerArchivo( "CLAUDE.md" )

   // Capa 2: Archivos relevantes del proyecto (búsqueda semántica)
   cArchivos := BuscarArchivosRelevantes( cPrompt )

   // Capa 3: Historial comprimido
   RETURN cMemoria + CRLF + ;
          "=== Archivos relevantes ===" + CRLF + ;
          cArchivos + CRLF + ;
          "Prompt actual: " + cPrompt
RETURN

FUNCTION LlamarModeloClaude( cPrompt, cContexto )
   // Aquí iría la llamada real a la API de Anthropic
   // En la versión real usa streaming + tool calling
   LOCAL cRespuesta := ""

   // Simulación de respuesta con posible tool call
   IF "crear archivo" $ LOWER(cPrompt)
      cRespuesta := '[TOOL_CALL] write_file {"path":"nuevo.txt", "content":"Hola desde Claude Code"}'
   ELSE
      cRespuesta := "Entendido. Voy a ayudarte con eso."
   ENDIF

RETURN cRespuesta

FUNCTION TieneToolCalls( cRespuesta )
RETURN "[TOOL_CALL]" $ cRespuesta

FUNCTION ChequearSeguridad( cToolCall )
   // Clasificador de riesgo (como el que usa Claude Code)
   ? "   [Seguridad] Analizando riesgo de la herramienta..."
   // Aquí irían los clasificadores (Haiku, etc.)
RETURN .T.   // por simplicidad siempre aprueba en el simulador

FUNCTION EjecutarTools( cToolCall )
   LOCAL cTipo := ExtraerTipoTool( cToolCall )

   DO CASE
      CASE cTipo == "write_file"
         ? "   [Tool] Escribiendo archivo en disco..."
         // write_file real
      CASE cTipo == "exec_shell"
         ? "   [Tool] Ejecutando comando en terminal..."
         // exec_shell con sandbox
      CASE cTipo == "read_file"
         ? "   [Tool] Leyendo archivo..."
      OTHERWISE
         ? "   [Tool] Herramienta desconocida"
   ENDCASE
RETURN

FUNCTION InitMemoria()
   IF !FILE( "CLAUDE.md" )
      MemoWrit( "CLAUDE.md", "=== Memoria del proyecto ===\nSesión iniciada: " + DTOC(DATE()) )
   ENDIF
RETURN

FUNCTION ActualizarMemoria( cPrompt, cRespuesta )
   LOCAL cActual := MemoRead( "CLAUDE.md" )
   cActual += CRLF + "Usuario: " + cPrompt + CRLF + ;
              "Claude: " + cRespuesta + CRLF + ;
              "---"
   MemoWrit( "CLAUDE.md", cActual )
RETURN

// Funciones dummy para completar la sintaxis
FUNCTION LeerArchivo( cArchivo ) ; RETURN "Contenido de " + cArchivo
FUNCTION BuscarArchivosRelevantes( cPrompt ) ; RETURN "src/main.prg"
FUNCTION ExtraerTipoTool( cCall ) ; RETURN "write_file"
regards, saludos

Antonio Linares
www.fivetechsoft.com
Posts: 44158
Joined: Thu Oct 06, 2005 05:47 PM
Re: Claude Code app architecture
Posted: Fri Apr 17, 2026 07:39 PM
# Arquitectura de Claw-Code en Pseudocódigo Harbour

Basado en la documentación del repositorio `claw-code`, aquí está el pseudocódigo en Harbour que ilustra su arquitectura:

```harbour// Definición de la estructura principal del sistema
CLASS ClawCodeHarness
    VAR oRuntime      // Runtime crate - cerebro del sistema
    VAR oApi          // API crate - clientes provider
    VAR oTools        // Tools crate - herramientas integradas
    VAR oPlugins      // Plugins crate - extensibilidad
    VAR oCommands     // Commands crate - comandos slash
    
    METHOD New()
        ::oRuntime    := Runtime():New()
        ::oApi        := Api():New()
        ::oTools      := Tools():New()
        ::oPlugins    := Plugins():New()
        ::oCommands   := Commands():New()
    RETURN Self
    
    // Flujo principal de ejecución
    METHOD Execute( cUserInput )
        LOCAL oSession := ::oRuntime:CreateSession()
        LOCAL oWorker  := ::oRuntime:SpawnWorker( oSession )
        
        DO CASE
        CASE ::IsPromptCommand( cUserInput )
            RETURN ::HandlePrompt( oWorker, cUserInput )
        CASE ::IsSlashCommand( cUserInput )
            RETURN ::oCommands:Execute( cUserInput, oSession )
        OTHERWISE
            RETURN ::HandleRepl( oWorker, cUserInput )
        ENDCASE
    ENDCLASS

// Máquina de estados del Worker
CLASS Worker
    VAR nStatus       // WorkerStatus enum
    VAR oSession
    VAR cTrustState
    
    METHOD New()
        ::nStatus := WORKER_SPAWNING
        ::cTrustState := "pending"
    RETURN Self
    
    METHOD TransitionTo( nNewStatus )
        ::nStatus := nNewStatus
        ::EmitLaneEvent( nNewStatus )
    ENDCLASS

// Definición de estados del worker
#define WORKER_SPAWNING        1
#define WORKER_TRUST_REQUIRED  2
#define WORKER_READY_FOR_PROMPT 3
#define WORKER_PROMPT_ACCEPTED 4
#define WORKER_RUNNING         5
#define WORKER_BLOCKED         6
#define WORKER_FINISHED        7
#define WORKER_FAILED          8

// Sistema de eventos estructurados
CLASS LaneEvent
    VAR cEventName     // lane.started, lane.ready, lane.blocked, etc.
    VAR cStatus        // success, failure, pending
    VAR oBlocker       // tipo de bloqueo si aplica
    VAR cDetails       // detalles adicionales
    
    METHOD New( cName, cStatus, oBlocker, cDetails )
        ::cEventName := cName
        ::cStatus    := cStatus
        ::oBlocker   := oBlocker
        ::cDetails   := cDetails
    ENDCLASS

// Runtime - cerebro del sistema
CLASS Runtime
    VAR oSessionStore
    VAR oPermissionEnforcer
    VAR oMcpManager
    VAR oWorkerRegistry
    
    METHOD CreateSession()
        LOCAL oSession := Session():New()
        ::oSessionStore:Add( oSession )
    RETURN oSession
    
    METHOD SpawnWorker( oSession )
        LOCAL oWorker := Worker():New()
        
        // Secuencia de boot del worker
        oWorker:TransitionTo( WORKER_SPAWNING )
        
        IF ::CheckTrustRequired( oSession )
            oWorker:TransitionTo( WORKER_TRUST_REQUIRED )
            IF ::AutoResolveTrust( oSession )
                oWorker:TransitionTo( WORKER_READY_FOR_PROMPT )
            ENDIF
        ELSE
            oWorker:TransitionTo( WORKER_READY_FOR_PROMPT )
        ENDIF
        
        ::oWorkerRegistry:Register( oWorker )
    RETURN oWorker
    ENDCLASS

// Sistema de herramientas
CLASS Tools
    VAR aToolSpecs     // array de especificaciones de herramientas
    
    METHOD New()
        ::LoadBuiltinTools()
        ::LoadPluginTools()
    ENDCLASS
    
    METHOD ExecuteTool( cToolName, hParams )
        LOCAL oTool := ::FindTool( cToolName )
        
        IF oTool != NIL
            RETURN oTool:Execute( hParams )
        ENDIF
        
    RETURN NIL
    ENDCLASS

// Ejemplo de herramienta integrada
CLASS BashTool
    METHOD Execute( hParams )
        LOCAL cCommand := hParams["command"]
        LOCAL nPermission := ::CheckPermission( cCommand )
        
        IF nPermission == PERMISSION_DENIED
            RETURN CreateErrorResult( "Permission denied" )
        ENDIF
        
        RETURN ::ExecuteBashCommand( cCommand )
    ENDCLASS
ENDCLASS

// Punto de entrada principal
FUNCTION Main()
    LOCAL oClaw := ClawCodeHarness():New()
    LOCAL cInput
    
    DO WHILE .T.
        cInput := GetUserInput()
        
        IF cInput == "quit"
            EXIT
        ENDIF
        
        oClaw:Execute( cInput )
    ENDDO
    
RETURN NIL```

## Notas

Este pseudocódigo Harbour ilustra los componentes clave de la arquitectura claw-code:

1. **Estructura modular en crates** - `runtime`, `api`, `tools`, `plugins`, `commands` [1](#0-0) 
2. **Máquina de estados del worker** - transición desde `Spawning` hasta `Finished/Failed` [2](#0-1) 
3. **Sistema de eventos estructurados** - `LaneEvent` para orquestación [3](#0-2) 
4. **Runtime como cerebro** - gestiona sesiones, permisos, y ciclo de vida [4](#0-3) 
5. **Sistema de herramientas** - 40 herramientas expuestas incluyendo bash, file ops, etc. [5](#0-4) 

El pseudocódigo mantiene la filosofía "clawable" de ejecución determinista, legible por máquina y recuperable sin intervención humana.

Wiki pages you might want to explore:
- [Overview (instructkr/claw-code)](/wiki/instructkr/claw-code#1)
- [Lane Orchestration & Roadmap (instructkr/claw-code)](/wiki/instructkr/claw-code#8)

### Citations

**File:** rust/README.md (L179-206)
```markdown```text
rust/
├── Cargo.toml              # Workspace root
├── Cargo.lock
└── crates/
    ├── api/                # Provider clients + streaming + request preflight
    ├── commands/           # Shared slash-command registry + help rendering
    ├── compat-harness/     # TS manifest extraction harness
    ├── mock-anthropic-service/ # Deterministic local Anthropic-compatible mock
    ├── plugins/            # Plugin metadata, manager, install/enable/disable surfaces
    ├── runtime/            # Session, config, permissions, MCP, prompts, auth/runtime loop
    ├── rusty-claude-cli/   # Main CLI binary (`claw`)
    ├── telemetry/          # Session tracing and usage telemetry types
    └── tools/              # Built-in tools, skill resolution, tool search, agent runtime surfaces```

### Crate Responsibilities

- **api** — provider clients, SSE streaming, request/response types, auth (API key + OAuth bearer), request-size/context-window preflight
- **commands** — slash command definitions, parsing, help text generation, JSON/text command rendering
- **compat-harness** — extracts tool/prompt manifests from upstream TS source
- **mock-anthropic-service** — deterministic `/v1/messages` mock for CLI parity tests and local harness runs
- **plugins** — plugin metadata, install/enable/disable/update flows, plugin tool definitions, hook integration surfaces
- **runtime** — `ConversationRuntime`, config loading, session persistence, permission policy, MCP client lifecycle, system prompt assembly, usage tracking
- **rusty-claude-cli** — REPL, one-shot prompt, direct CLI subcommands, streaming display, tool call rendering, CLI argument parsing
- **telemetry** — session trace events and supporting telemetry payloads
- **tools** — tool specs + execution: Bash, ReadFile, WriteFile, EditFile, GlobSearch, GrepSearch, WebSearch, WebFetch, Agent, TodoWrite, NotebookEdit, Skill, ToolSearch, and runtime-facing tool discovery

```
**File:** ROADMAP.md (L75-87)
```markdown
## Phase 1 — Reliable Worker Boot

### 1. Ready-handshake lifecycle for coding workers
Add explicit states:
- `spawning`
- `trust_required`
- `ready_for_prompt`
- `prompt_accepted`
- `running`
- `blocked`
- `finished`
- `failed````

**File:** rust/crates/runtime/src/lib.rs (L1-6)
```rust//! Core runtime primitives for the `claw` CLI and supporting crates.
//!
//! This crate owns session persistence, permission evaluation, prompt assembly,
//! MCP plumbing, tool-facing file operations, and the core conversation loop
//! that drives interactive and one-shot turns.```

**File:** PARITY.md (L145-151)
```markdown## Tool Surface: 40 exposed tool specs on `main`

- `mvp_tool_specs()` in `rust/crates/tools/src/lib.rs` exposes **40** tool specs.
- Core execution is present for `bash`, `read_file`, `write_file`, `edit_file`, `glob_search`, and `grep_search`.
- Existing product tools in `mvp_tool_specs()` include `WebFetch`, `WebSearch`, `TodoWrite`, `Skill`, `Agent`, `ToolSearch`, `NotebookEdit`, `Sleep`, `SendUserMessage`, `Config`, `EnterPlanMode`, `ExitPlanMode`, `StructuredOutput`, `REPL`, and `PowerShell`.
- The 9-lane push replaced pure fixed-payload stubs for `Task*`, `Team*`, `Cron*`, `LSP`, and MCP tools with registry-backed handlers on `main`.
- `Brief` is handled as an execution alias in `execute_tool()`, but it is not a separately exposed tool spec in `mvp_tool_specs()`.```
regards, saludos

Antonio Linares
www.fivetechsoft.com
Posts: 44158
Joined: Thu Oct 06, 2005 05:47 PM
Re: Claude Code app architecture
Posted: Sat Apr 18, 2026 07:55 PM
regards, saludos

Antonio Linares
www.fivetechsoft.com

Continue the discussion