### Clone and Run Puzld.ai Development Setup Source: https://github.com/medchaouch/puzld.ai/blob/main/README.md This snippet details the steps to clone the Puzld.ai repository, install dependencies using Bun, build the project, link it globally, and finally run the Puzld.ai command-line interface. ```bash git clone https://github.com/MedChaouch/Puzld.ai.git cd Puzld.ai bun install bun run build npm link puzldai ``` -------------------------------- ### PuzldAI Quick Start Commands Source: https://github.com/medchaouch/puzld.ai/blob/main/README.md Demonstrates various command-line interface (CLI) commands for using PuzldAI. These examples cover launching the interactive TUI, running single tasks, comparing agent responses, setting up agent pipelines, and enabling multi-agent collaboration modes like correction, debate, and consensus. It also shows how to check available agents. ```bash # Interactive TUI puzldai # Single task puzldai run "explain recursion" # Compare agents puzldai compare claude,gemini "best error handling practices" # Pipeline: analyze → code → review puzldai run "build a logger" -P "gemini:analyze,claude:code,gemini:review" # Multi-agent collaboration puzldai correct "write a sort function" --producer claude --reviewer gemini puzldai debate "microservices vs monolith" -a claude,gemini puzldai consensus "best database choice" -a claude,gemini,ollama # Check what's available puzldai check ``` -------------------------------- ### Install and Update PuzldAI with npm Source: https://github.com/medchaouch/puzld.ai/blob/main/README.md This section provides instructions for installing the PuzldAI CLI globally using npm, updating it to the latest version, and running it without a global installation using npx. It's essential for setting up the PuzldAI environment. ```bash npm install -g puzldai npx puzldai npm update -g puzldai ``` -------------------------------- ### Puzld.ai Configuration File Example Source: https://context7.com/medchaouch/puzld.ai/llms.txt This snippet shows an example of the Puzld.ai configuration file located at `~/.puzldai/config.json`. It illustrates settings for default and fallback agents, router model, and enables/configures adapters for different AI models like Claude, Gemini, and Ollama. ```json { "defaultAgent": "auto", "fallbackAgent": "claude", "routerModel": "llama3.2", "adapters": { "claude": { "enabled": true, "path": "claude", "model": "sonnet" }, "gemini": { "enabled": true, "path": "gemini", "model": "gemini-2.5-pro" }, "ollama": { "enabled": true, "model": "llama3.2" } } } ``` -------------------------------- ### Start Puzld.ai API Server Source: https://context7.com/medchaouch/puzld.ai/llms.txt This snippet shows the command to start the Puzld.ai API server. It also includes an option to customize the port and host address for the server, allowing for flexible deployment configurations. ```bash # Start API server puzldai serve # Custom port and host puzldai serve --port 8080 --host 127.0.0.1 ``` -------------------------------- ### Initiate Debate with Multiple Agents (CLI) Source: https://context7.com/medchaouch/puzld.ai/llms.txt Command-line interface to start a debate between specified AI agents. This requires the 'puzldai' CLI tool to be installed. It takes the debate topic, a comma-separated list of agents, the number of rounds, and an optional moderator agent as arguments. ```bash # With moderator synthesis puzldai debate "Microservices vs Monolith" \ --agents claude,gemini,ollama \ --rounds 2 \ --moderator claude ``` -------------------------------- ### API Server Endpoints for PuzldAI (TypeScript) Source: https://context7.com/medchaouch/puzld.ai/llms.txt Demonstrates how to interact with the PuzldAI API server using TypeScript's fetch API. Includes examples for health checks, listing agents, submitting tasks, retrieving task status, and streaming task updates via Server-Sent Events (SSE). Assumes the API server is running on localhost:3000. ```typescript // API server endpoints // Health check fetch('http://localhost:3000/health') .then(r => r.json()) .then(data => console.log(data)); // { status: 'ok', timestamp: '2025-12-17T10:00:00.000Z' } // List agents fetch('http://localhost:3000/agents') .then(r => r.json()) .then(data => console.log(data)); // { agents: ['claude', 'gemini', 'codex', 'ollama'], available: ['claude', 'ollama'] } // Submit task fetch('http://localhost:3000/task', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt: 'Explain async/await', agent: 'claude' }) }) .then(r => r.json()) .then(data => console.log(data)); // { id: 'task_1234567890_abc123', status: 'pending' } // Get task status fetch('http://localhost:3000/task/task_1234567890_abc123') .then(r => r.json()) .then(data => console.log(data)); // { // status: 'completed', // result: 'Async/await is a syntax for handling promises...', // model: 'claude-sonnet-4.5', // startedAt: 1734430000000, // completedAt: 1734430005000 // } // Stream task updates (SSE) const eventSource = new EventSource('http://localhost:3000/task/task_1234567890_abc123/stream'); eventSource.onmessage = (event) => { const data = JSON.parse(event.data); console.log('Status:', data.status); if (data.status === 'completed') { console.log('Result:', data.result); eventSource.close(); } }; ``` -------------------------------- ### Serve PuzldAI with Web Terminal Source: https://context7.com/medchaouch/puzld.ai/llms.txt Starts the PuzldAI server with a web-based terminal interface, allowing interactive use. The --terminal-port flag specifies the port for the web terminal. ```bash puzldai serve --web --terminal-port 3001 ``` -------------------------------- ### Agentic Mode Execution with Tools (TypeScript) Source: https://context7.com/medchaouch/puzld.ai/llms.txt Execute agentic workflows in TypeScript, allowing AI agents to interact with a defined set of tools. This example demonstrates running an agent loop with specific tools, handling tool calls, permission requests, and tool results. It requires defining the agent adapter and the task. ```typescript // Agentic execution with tool access import { runAgentLoop } from 'puzldai/agentic'; import { claudeAdapter } from 'puzldai/adapters'; const result = await runAgentLoop( claudeAdapter, "Find all TODO comments in src/ and create a summary", { tools: ['view', 'glob', 'grep'], cwd: process.cwd(), onToolCall: (call) => { console.log(`Tool called: ${call.name}`); }, onPermissionRequest: async (request) => { // Implement permission logic if (request.tool === 'view' || request.tool === 'grep') { return { allow: true, remember: false }; } return { allow: false }; }, onToolResult: (result) => { console.log(`Result: ${result.content.slice(0, 100)}...`); } } ); console.log('Agent response:', result.content); console.log('Tool calls made:', result.toolCalls?.length); ``` -------------------------------- ### Get Task Status API Source: https://context7.com/medchaouch/puzld.ai/llms.txt Retrieves the status and result of a previously submitted task. ```APIDOC ## GET /task/{taskId} ### Description Retrieves the current status and, if completed, the result of a specific task identified by its `taskId`. ### Method GET ### Endpoint /task/{taskId} ### Parameters #### Path Parameters - **taskId** (string) - Required - The unique identifier of the task to retrieve. ### Request Example None (uses path parameter) ### Response #### Success Response (200) - **status** (string) - The current status of the task (e.g., 'pending', 'processing', 'completed', 'failed'). - **result** (string) - Optional - The result of the task if the status is 'completed'. - **model** (string) - Optional - The AI model used for the task. - **startedAt** (integer) - Optional - Timestamp when the task started execution. - **completedAt** (integer) - Optional - Timestamp when the task finished execution. #### Response Example ```json { "status": "completed", "result": "Async/await is a syntax for handling promises...", "model": "claude-sonnet-4.5", "startedAt": 1734430000000, "completedAt": 1734430005000 } ``` ``` -------------------------------- ### Index and Search Codebase with Puzld.ai CLI Source: https://context7.com/medchaouch/puzld.ai/llms.txt This snippet details how to use the Puzld.ai command-line interface for codebase indexing and searching. It covers indexing the current directory (with options for quick indexing and file limits), searching for specific code, retrieving context for tasks, and viewing project configuration and dependency graphs. ```bash # Index current directory puzldai index # Quick index (skip embeddings) puzldai index --quick # Search indexed code puzldai index --search "authentication" # Get context for a task puzldai index --context "fix login bug" # Show project configuration puzldai index --config # Show dependency graph puzldai index --graph # Index with limits puzldai index --max-files 500 ``` -------------------------------- ### CLI Entry Point Source: https://context7.com/medchaouch/puzld.ai/llms.txt Execute PuzldAI tasks via the command-line interface. Supports interactive TUI, single task execution with auto-routing, forcing specific agents, and overriding model versions. ```APIDOC ## CLI Entry Point ### Description Execute PuzldAI tasks via the command-line interface. Supports interactive TUI, single task execution with auto-routing, forcing specific agents, and overriding model versions. ### Usage Examples ```bash # Interactive TUI mode (default) puzldai # Single task execution with auto-routing puzldai run "explain async/await in JavaScript" # Force specific agent puzldai run "write a sorting algorithm" --agent claude # Override model version puzldai run "analyze this code" --agent claude --model opus # Check available agents puzldai check ``` ``` -------------------------------- ### PuzldAI CLI - Basic Commands Source: https://context7.com/medchaouch/puzld.ai/llms.txt Provides basic command-line interface functionalities for PuzldAI, including interactive mode, single task execution with auto-routing, forcing specific agents, overriding model versions, and checking available agents. ```bash # Interactive TUI mode (default) puzldai # Single task execution with auto-routing puzldai run "explain async/await in JavaScript" # Force specific agent puzldai run "write a sorting algorithm" --agent claude # Override model version puzldai run "analyze this code" --agent claude --model opus # Check available agents puzldai check ``` -------------------------------- ### Manage Templates with Puzld.ai CLI Source: https://context7.com/medchaouch/puzld.ai/llms.txt This snippet outlines the usage of the Puzld.ai command-line interface for template management. It covers listing, creating, showing, editing, and deleting templates, including defining pipelines and descriptions for custom workflows. ```bash # List templates puzldai template list # Create template puzldai template create code-review \ --pipeline "claude:analyze,gemini:review,claude:fix" \ --description "Full code review workflow" # Show template puzldai template show code-review # Edit template puzldai template edit code-review \ --pipeline "claude:analyze,codex:implement,gemini:test" # Delete template puzldai template delete code-review ``` -------------------------------- ### Manage Models and Configurations with Puzld.ai CLI Source: https://context7.com/medchaouch/puzld.ai/llms.txt This snippet covers managing model settings using the Puzld.ai command-line interface. It includes commands to show current settings, list available models (globally and for specific agents), set model overrides per agent or per task, and clear existing overrides. ```bash # Show current model settings puzldai model show # List available models puzldai model list puzldai model list claude # Set model for an agent puzldai model set claude opus puzldai model set gemini gemini-2.5-flash # Clear model override puzldai model clear claude # Per-task model override puzldai run "complex analysis" --agent claude --model opus ``` -------------------------------- ### Compare Agent Outputs (CLI) Source: https://github.com/medchaouch/puzld.ai/blob/main/README.md Compares the outputs of different AI agents for a given task. Users can specify which agents to use or rely on the default set. Supports sequential mode and picking the best response. ```bash puzldai compare "task" # Default: claude,gemini puzldai compare "task" -a claude,gemini,codex # Specify agents puzldai compare "task" -s # Sequential mode puzldai compare "task" -p # Pick best response ``` -------------------------------- ### Model Management CLI Commands Source: https://github.com/medchaouch/puzld.ai/blob/main/README.md Commands for interacting with model settings via the command-line interface. This includes viewing, listing, setting, and clearing models for agents, as well as overriding models for specific tasks or interactive sessions. ```bash # TUI /model # Open model selection panel # CLI puzldai model show # Show current models for all agents puzldai model list # List all available models puzldai model list claude # List models for specific agent puzldai model set claude opus # Set model for an agent puzldai model clear claude # Reset to CLI default # Per-task override puzldai run "task" -m opus # Override model for this run puzldai agent -a claude -m haiku # Interactive mode with specific model ``` -------------------------------- ### Compare Mode CLI Commands Source: https://github.com/medchaouch/puzld.ai/blob/main/README.md Command-line interface commands for the 'Compare' execution mode in Puzld.ai. These commands allow users to run the same prompt on multiple agents and switch between different view modes for comparing results. ```bash # TUI /compare claude,gemini "explain async/await" /sequential # Toggle: run one-at-a-time /pick # Toggle: select best response ``` -------------------------------- ### PuzldAI Adapter System for AI Models (TypeScript) Source: https://context7.com/medchaouch/puzld.ai/llms.txt Shows how to use PuzldAI's adapter system in TypeScript to interact with different AI models. It includes checking for available adapters using `getAvailableAdapters` and using a specific adapter, like the `claudeAdapter`, to send messages and receive responses. The `isAvailable` method checks if an adapter is ready for use. ```typescript // Check adapter availability import { getAvailableAdapters } from 'puzldai/adapters'; const available = await getAvailableAdapters(); console.log('Available agents:', available.map(a => a.name)); // Use specific adapter import { claudeAdapter } from 'puzldai/adapters'; if (await claudeAdapter.isAvailable()) { const response = await claudeAdapter.sendMessage( 'Explain closures in JavaScript', { model: 'sonnet' } ); console.log(response.content); } ``` -------------------------------- ### Autopilot Mode Execution (CLI) Source: https://github.com/medchaouch/puzld.ai/blob/main/README.md Describes a goal, and the AI automatically analyzes, plans, and executes the task using the most suitable agents for each step. Supports generating plan only or generating and executing. ```bash # TUI /autopilot "build a todo app with authentication" /planner claude # Set planner agent /execute # Toggle auto-execution on/off # CLI puzldai autopilot "task" # Generate plan only puzldai autopilot "task" -x # Generate and execute puzldai autopilot "task" -p claude # Use specific agent as planner ``` -------------------------------- ### Manage Sessions with Puzld.ai CLI Source: https://context7.com/medchaouch/puzld.ai/llms.txt This snippet demonstrates session management operations using the Puzld.ai command-line interface. It includes commands for listing all sessions, creating new sessions for specific agents, showing session details, deleting sessions, and clearing session history while retaining the session itself. ```bash # List all sessions puzldai session list # Create new session puzldai session new claude # Show session details puzldai session info # Delete session puzldai session delete # Clear session history (keep session) puzldai session clear ``` -------------------------------- ### Intelligent Context Management with PuzldAI (TypeScript) Source: https://context7.com/medchaouch/puzld.ai/llms.txt Demonstrates how to use PuzldAI's context management utilities in TypeScript. The `assembleContext` function intelligently manages the context window for AI agents by selecting, summarizing, and dropping context items based on specified criteria like `maxTokens` and `summarizeThreshold`. It takes agent configuration and a list of context items, each created with `createContextItem`. ```typescript // Intelligent context window management import { assembleContext, createContextItem } from 'puzldai/context'; const context = await assembleContext({ agent: 'claude', maxTokens: 100000, includeHistory: true, includePreviousResults: true, summarizeThreshold: 50000 }, [ createContextItem('system', 'You are a helpful coding assistant', { priority: 10, source: 'system' }), createContextItem('history', 'Previous conversation...', { priority: 5, source: 'chat' }), createContextItem('code', 'function example() {...}', { priority: 8, source: 'file' }) ]); console.log(`Assembled context: ${context.totalTokens} tokens`); console.log(`Items included: ${context.selected.length}`); console.log(`Items dropped: ${context.dropped.length}`); ``` -------------------------------- ### Puzld.ai CLI Commands Source: https://github.com/medchaouch/puzld.ai/blob/main/README.md The CLI mode offers a comprehensive set of commands for automating tasks, managing workflows, and interacting with Puzld.ai's features from the terminal. ```bash puzldai # Launch TUI puzldai run "task" # Single task puzldai run "task" -a claude # Force agent puzldai run "task" -m opus # Override model puzldai run "task" -P "..." # Pipeline puzldai run "task" -T template # Use template puzldai run "task" -i # Interactive: pause between steps puzldai compare "task" # Compare (default: claude,gemini) puzldai compare "task" -a a,b,c # Specify agents puzldai compare "task" -s # Sequential mode puzldai compare "task" -p # Pick best response puzldai autopilot "task" # Generate plan puzldai autopilot "task" -x # Plan + execute puzldai autopilot "task" -p claude # Use specific planner puzldai correct "task" --producer claude --reviewer gemini puzldai correct "task" --producer claude --reviewer gemini --fix puzldai debate "topic" -a claude,gemini -r 3 -m ollama puzldai consensus "task" -a claude,gemini -r 3 -s claude puzldai session list # List sessions puzldai session new # Create new session puzldai check # Agent status puzldai agent # Interactive agent mode puzldai agent -a claude # Force specific agent puzldai agent -m sonnet # With specific model puzldai model show # Show current models puzldai model list # List available models puzldai model set claude opus # Set model for agent puzldai model clear claude # Reset to CLI default puzldai serve # API server puzldai serve -p 8080 # Custom port puzldai serve -w # With web terminal puzldai template list # List templates puzldai template show # Show template details puzldai template create -P "..." -d "desc" puzldai template edit # Edit template puzldai template delete # Delete template puzldai index # Index codebase puzldai index --quick # Skip embeddings puzldai index --search "query" # Search indexed code puzldai index --context "task" # Get relevant context puzldai index --config # Show project config ``` -------------------------------- ### Correct Mode Collaboration (CLI) Source: https://github.com/medchaouch/puzld.ai/blob/main/README.md Enables one agent to produce content and another to review it, with an option to fix based on feedback. This mode facilitates a producer-reviewer workflow. ```bash # TUI /correct claude gemini "write a sorting algorithm" # CLI puzldai correct "task" --producer claude --reviewer gemini puzldai correct "task" --producer claude --reviewer gemini --fix ``` -------------------------------- ### Workflow Management (CLI) Source: https://github.com/medchaouch/puzld.ai/blob/main/README.md Manages reusable pipelines saved as workflows. Users can list, show details of, create, and delete templates. Supports interactive mode for execution. ```bash # TUI /workflow code-review "my code here" /workflows # Manage templates (interactive) /interactive # Toggle: pause between steps # CLI puzldai run "task" -T code-review puzldai run "task" -T code-review -i # Interactive mode puzldai template list # List all templates puzldai template show my-flow # Show template details puzldai template create my-flow -P "claude:plan,codex:code" puzldai template delete my-flow # Delete template ``` -------------------------------- ### Build Consensus with Multiple Agents (CLI) Source: https://context7.com/medchaouch/puzld.ai/llms.txt Command-line interface to build consensus among specified AI agents on a given topic. Similar to initiating a debate, this requires the 'puzldai' CLI tool and takes the topic, agents, rounds, and a synthesizer agent as arguments. ```bash # Build consensus among agents puzldai consensus "best database for this use case" \ --agents claude,gemini,ollama \ --rounds 2 \ --synthesizer claude ``` -------------------------------- ### PuzldAI CLI - Pipeline Execution Source: https://context7.com/medchaouch/puzld.ai/llms.txt Facilitates multi-step workflows by chaining agents in a pipeline. Supports specifying agents and their roles for each step, interactive mode with confirmations, and using saved templates for common workflows. ```bash # Chain agents with specific roles puzldai run "build a REST API" --pipeline "gemini:analyze,claude:code,gemini:review" # Interactive mode with confirmation between steps puzldai run "refactor authentication" --pipeline "claude:plan,codex:code" --interactive # Use saved templates puzldai run "implement user login" --template code-review ``` -------------------------------- ### Pipeline Mode Execution (CLI) Source: https://github.com/medchaouch/puzld.ai/blob/main/README.md Chains multiple agents together to execute complex tasks, where each agent handles a specific step in the sequence. Supports interactive mode to pause between steps. ```bash puzldai run "build a REST API" -P "gemini:analyze,claude:code,gemini:review" puzldai run "task" -P "claude:plan,codex:code" -i # Interactive: pause between steps ``` -------------------------------- ### Export Observation Data with Puzld.ai CLI Source: https://context7.com/medchaouch/puzld.ai/llms.txt This snippet shows how to export observation data using the Puzld.ai command-line interface. It covers viewing observation summaries, listing recent observations, and exporting observations and preference pairs in JSONL format for training purposes. ```bash # View observation summary puzldai observe summary --agent claude # List recent observations puzldai observe list --limit 20 # Export observations as JSONL puzldai observe export observations.jsonl --format jsonl --type observations # Export preference pairs for DPO training puzldai observe export preferences.jsonl --format jsonl --type preferences --agent claude ``` -------------------------------- ### Programmatic Observation Export with Puzld.ai Source: https://context7.com/medchaouch/puzld.ai/llms.txt This snippet demonstrates how to programmatically export observation data using the Puzld.ai library. It covers exporting all observations and DPO preference pairs, specifying output paths, formats, and inclusion of metadata. The structure of preference pairs is also detailed. ```typescript // Programmatic observation export import { exportObservations, exportPreferencePairs } from 'puzldai/observation'; // Export all observations await exportObservations({ outputPath: 'data/observations.jsonl', format: 'jsonl', agent: 'claude', limit: 10000 }); // Export DPO preference pairs await exportPreferencePairs({ outputPath: 'data/dpo-pairs.jsonl', format: 'jsonl', includeMetadata: true }); // Each preference pair includes: // - prompt: original user input // - chosen: accepted response/file // - rejected: rejected alternative // - metadata: context about the decision ``` -------------------------------- ### Puzld.ai TUI Commands Source: https://github.com/medchaouch/puzld.ai/blob/main/README.md The TUI mode provides an interactive command-line interface for interacting with Puzld.ai. It allows users to perform various actions through simple slash commands. ```text /compare claude,gemini "task" Compare agents side-by-side /autopilot "task" AI-planned workflow /workflow code-review "code" Run saved workflow /workflows Manage templates /correct claude gemini "task" Cross-agent correction /debate claude,gemini "topic" Multi-agent debate /consensus claude,gemini "task" Build consensus @claude "task" Agentic mode with Claude @gemini "task" Agentic mode with Gemini /plan @claude "task" Plan mode (analyze, no execution) /build @claude "task" Build mode (full tool access) /index Codebase indexing options /index search "query" Search indexed code /session Start new session /resume Resume previous session /settings Open settings panel /changelog Show version history /agent claude Switch agent /model Model selection panel /router ollama Set routing agent /planner claude Set autopilot planner /sequential Toggle: compare one-at-a-time /pick Toggle: select best from compare /execute Toggle: auto-run autopilot plans /interactive Toggle: pause between steps /help All commands ``` -------------------------------- ### PuzldAI CLI - Compare Mode Source: https://context7.com/medchaouch/puzld.ai/llms.txt Enables comparing responses from multiple AI agents for a given prompt. Supports parallel or sequential execution and allows an LLM to pick the best response. This mode is useful for evaluating different agent capabilities. ```bash # Compare responses from multiple agents puzldai compare "best practices for error handling" --agents claude,gemini,codex # Sequential execution instead of parallel puzldai compare "microservices vs monolith" --agents claude,gemini --sequential # Have LLM pick the best response puzldai compare "explain recursion" --agents claude,gemini,ollama --pick ``` -------------------------------- ### Consensus Mode Collaboration (CLI) Source: https://github.com/medchaouch/puzld.ai/blob/main/README.md Agents propose solutions to a task, vote on them, and synthesize a final answer. Supports configuring the number of rounds and a synthesizer agent. ```bash # TUI /consensus claude,gemini,ollama "best database for this use case" # CLI puzldai consensus "task" -a claude,gemini,ollama puzldai consensus "task" -a claude,gemini -r 3 -s claude # 3 rounds + synthesizer ``` -------------------------------- ### Agentic Mode Code Exploration (CLI) Source: https://github.com/medchaouch/puzld.ai/blob/main/README.md Enables LLMs to explore a codebase using tools and propose file edits, similar to Claude Code. PuzldAI acts as the execution layer, requiring user approval for proposed changes. ```bash # Agentic mode is described but no specific CLI commands are provided in the text. ``` -------------------------------- ### View Tool for Reading File Contents (TypeScript) Source: https://context7.com/medchaouch/puzld.ai/llms.txt Utilize the 'view' tool within Puzld.ai's agentic mode to read the content of a file. This tool can specify a path, an offset, and a limit for the content to be retrieved. The output includes line numbers. ```typescript // View tool: Read file contents with line numbers import { viewTool } from 'puzldai/agentic/tools'; const result = await viewTool.execute( { path: 'src/index.ts', offset: 0, limit: 50 }, process.cwd() ); console.log(result.content); // Output: // 1|import { Command } from 'commander'; // 2|import { runCommand } from './commands/run'; // 3|... ``` -------------------------------- ### List Agents API Source: https://context7.com/medchaouch/puzld.ai/llms.txt Retrieves a list of available and supported AI agents. ```APIDOC ## GET /agents ### Description Retrieves a list of all AI agents supported by PuzldAI and indicates which ones are currently available for use. ### Method GET ### Endpoint /agents ### Parameters None ### Request Example None ### Response #### Success Response (200) - **agents** (array of strings) - A list of all supported agent names. - **available** (array of strings) - A list of agent names that are currently available. #### Response Example ```json { "agents": ["claude", "gemini", "codex", "ollama"], "available": ["claude", "ollama"] } ``` ``` -------------------------------- ### Manage Memories and Retrieval with Puzld.ai Source: https://context7.com/medchaouch/puzld.ai/llms.txt This snippet demonstrates how to store and retrieve memories using the puzldai/memory module. It covers adding conversational and code-based memories, including metadata. It also shows how to perform retrieval based on a query and retrieve relevant memories. ```typescript // Store memories for future retrieval import { addMemory, retrieve } from 'puzldai/memory'; // Add conversation to memory await addMemory({ type: 'conversation', content: 'User asked about error handling. Recommended try-catch with custom error classes.', metadata: { topic: 'error-handling', agent: 'claude' } }); // Add code pattern await addMemory({ type: 'code', content: "\n class CustomError extends Error {\n constructor(message: string, public code: string) {\n super(message);\n this.name = 'CustomError';\n }\n }\n ", metadata: { language: 'typescript', pattern: 'custom-error-class' } }); // Retrieve relevant memories const results = await retrieve('error handling in TypeScript', { types: ['conversation', 'code'], limit: 5 }); for (const result of results.items) { console.log(`Score: ${result.score}`); console.log(`Content: ${result.content}`); } ``` -------------------------------- ### Glob Tool for Finding Files by Pattern (TypeScript) Source: https://context7.com/medchaouch/puzld.ai/llms.txt Leverage the 'glob' tool to find files matching a specific pattern. This tool supports glob patterns for file matching and can also exclude specific paths. It returns a list of file paths that match the criteria. ```typescript // Glob tool: Find files by pattern import { globTool } from 'puzldai/agentic/tools'; const result = await globTool.execute( { pattern: '**/*.ts', exclude: 'node_modules/**' }, process.cwd() ); console.log('TypeScript files:', result.content); ``` -------------------------------- ### Exporting Puzld.ai Observations to JSONL Source: https://github.com/medchaouch/puzld.ai/blob/main/README.md This TypeScript code demonstrates how to export observation data from Puzld.ai. It includes functions for exporting all observations as a JSONL file and for exporting preference pairs (chosen vs. rejected) for DPO training. Ensure the 'puzldai/observation' module is correctly imported. ```typescript import { exportObservations, exportPreferencePairs } from 'puzldai/observation'; // Export all observations as JSONL exportObservations({ outputPath: 'observations.jsonl', format: 'jsonl' }); // Export DPO training pairs (chosen vs rejected) exportPreferencePairs({ outputPath: 'preferences.jsonl', format: 'jsonl' }); ``` -------------------------------- ### Puzld.ai Configuration File Source: https://github.com/medchaouch/puzld.ai/blob/main/README.md The `config.json` file located at `~/.puzldai/config.json` allows users to customize Puzld.ai's default behavior, including agent settings, model preferences, and adapter configurations. ```json { "defaultAgent": "auto", "fallbackAgent": "claude", "routerModel": "llama3.2", "adapters": { "claude": { "enabled": true, "path": "claude", "model": "sonnet" }, "gemini": { "enabled": true, "path": "gemini", "model": "gemini-2.5-pro" }, "codex": { "enabled": false, "path": "codex", "model": "gpt-5.1-codex" }, "ollama": { "enabled": true, "model": "llama3.2" }, "mistral": { "enabled": true, "path": "vibe" } } } ``` -------------------------------- ### Pipeline Execution - Multi-Step Workflows Source: https://context7.com/medchaouch/puzld.ai/llms.txt Orchestrate multi-step workflows by chaining agents with specific roles or executing in an interactive mode with confirmation between steps. Supports saved templates for complex tasks. ```APIDOC ## Pipeline Execution - Multi-Step Workflows ### Description Orchestrate multi-step workflows by chaining agents with specific roles or executing in an interactive mode with confirmation between steps. Supports saved templates for complex tasks. ### CLI Usage Examples ```bash # Chain agents with specific roles puzldai run "build a REST API" --pipeline "gemini:analyze,claude:code,gemini:review" # Interactive mode with confirmation between steps puzldai run "refactor authentication" --pipeline "claude:plan,codex:code" --interactive # Use saved templates puzldai run "implement user login" --template code-review ``` ### Programmatic Usage Example ```typescript import { pipeline } from 'puzldai/chat'; const result = await pipeline( "Create a user authentication system", { agents: ['gemini', 'claude', 'gemini'], sequential: true, injectPreviousRuns: true } ); // Access results from each step const [analysis, implementation, review] = result.execution.results; console.log('Analysis:', analysis.content); console.log('Code:', implementation.content); console.log('Review:', review.content); // Check template statistics if (result.templateStats) { console.log(`Success rate: ${result.templateStats.successRate * 100}%`); console.log(`Average duration: ${result.templateStats.avgDuration}ms`); } ``` ``` -------------------------------- ### Grep Tool for Searching File Contents (TypeScript) Source: https://context7.com/medchaouch/puzld.ai/llms.txt Use the 'grep' tool to search for patterns within files. This tool allows specifying a regular expression pattern, a file path or directory, and an option for recursive searching. It returns the content matching the pattern. ```typescript // Grep tool: Search file contents import { grepTool } from 'puzldai/agentic/tools'; const result = await grepTool.execute( { pattern: 'TODO|FIXME', path: 'src/', recursive: true }, process.cwd() ); console.log('Found TODOs:', result.content); ``` -------------------------------- ### Submit Task API Source: https://context7.com/medchaouch/puzld.ai/llms.txt Submits a new task for an AI agent to process. ```APIDOC ## POST /task ### Description Submits a new task to be processed by a specified AI agent. Returns a task ID for status tracking. ### Method POST ### Endpoint /task ### Parameters #### Request Body - **prompt** (string) - Required - The instruction or question for the AI agent. - **agent** (string) - Required - The name of the AI agent to process the task. ### Request Example ```json { "prompt": "Explain async/await", "agent": "claude" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the submitted task. - **status** (string) - The initial status of the task (e.g., 'pending'). #### Response Example ```json { "id": "task_1234567890_abc123", "status": "pending" } ``` ``` -------------------------------- ### Debate Mode Collaboration (CLI) Source: https://github.com/medchaouch/puzld.ai/blob/main/README.md Facilitates a debate between multiple agents on a given topic, potentially across multiple rounds. An optional moderator can summarize the discussion. ```bash # TUI /debate claude,gemini "Is functional programming better than OOP?" # CLI puzldai debate "topic" -a claude,gemini puzldai debate "topic" -a claude,gemini -r 3 -m ollama # 3 rounds + moderator ``` -------------------------------- ### Compare Mode - Parallel Agent Evaluation Source: https://context7.com/medchaouch/puzld.ai/llms.txt Compare responses from multiple agents in parallel or sequentially. The framework can also be instructed to automatically pick the best response. ```APIDOC ## Compare Mode - Parallel Agent Evaluation ### Description Compare responses from multiple agents in parallel or sequentially. The framework can also be instructed to automatically pick the best response. ### CLI Usage Examples ```bash # Compare responses from multiple agents puzldai compare "best practices for error handling" --agents claude,gemini,codex # Sequential execution instead of parallel puzldai compare "microservices vs monolith" --agents claude,gemini --sequential # Have LLM pick the best response puzldai compare "explain recursion" --agents claude,gemini,ollama --pick ``` ### Programmatic Usage Example ```typescript import { compare } from 'puzldai/chat'; const result = await compare( "What's the best database for high-throughput writes?", { agents: ['claude', 'gemini', 'ollama'], sequential: false, includeHistory: true } ); // Access individual agent responses for (const stepResult of result.execution.results) { console.log(`${stepResult.agent}: ${stepResult.content}`); } // Check past preferences if (result.pastPreferences) { console.log('Historical preferences:', result.pastPreferences); } ``` ``` -------------------------------- ### Programmatic Consensus Building (TypeScript) Source: https://context7.com/medchaouch/puzld.ai/llms.txt Programmatically build consensus using Puzld.ai's executor module in TypeScript. This involves first building a consensus plan with specified parameters and then executing it. The results object contains the final consensus. ```typescript // Consensus building import { buildConsensusPlan, execute } from 'puzldai/executor'; const plan = buildConsensusPlan( "What's the optimal caching strategy?", { agents: ['claude', 'gemini', 'ollama'], rounds: 2, synthesizer: 'claude' } ); const execution = await execute(plan); const finalResult = execution.results[execution.results.length - 1]; console.log('Consensus:', finalResult.content); ``` -------------------------------- ### PuzldAI Programmatic - Compare Mode (TypeScript) Source: https://context7.com/medchaouch/puzld.ai/llms.txt Allows programmatic comparison of agent responses using the PuzldAI library in TypeScript. It facilitates parallel or sequential evaluation and can include chat history. The results provide access to individual agent responses and historical preferences. ```typescript // Programmatic usage import { compare } from 'puzldai/chat'; const result = await compare( "What's the best database for high-throughput writes?", { agents: ['claude', 'gemini', 'ollama'], sequential: false, includeHistory: true } ); // Access individual agent responses for (const stepResult of result.execution.results) { console.log(`${stepResult.agent}: ${stepResult.content}`); } // Check past preferences if (result.pastPreferences) { console.log('Historical preferences:', result.pastPreferences); } ``` -------------------------------- ### Multi-Agent Collaboration - Correct Mode Source: https://context7.com/medchaouch/puzld.ai/llms.txt Implement a producer-reviewer pattern for code generation and correction. Supports automatic fixes after the review process. ```APIDOC ## Multi-Agent Collaboration - Correct Mode ### Description Implement a producer-reviewer pattern for code generation and correction. Supports automatic fixes after the review process. ### CLI Usage Examples ```bash # Producer-reviewer pattern puzldai correct "write a merge sort function" \ --producer claude \ --reviewer gemini # With automatic fix after review puzldai correct "implement OAuth flow" \ --producer claude \ --reviewer gemini \ --fix ``` ### Programmatic Usage Example ```typescript import { orchestrate } from 'puzldai'; // Initial production const production = await orchestrate("Write a binary search tree", { agent: "claude" }); // Review by different agent const review = await orchestrate( `Review this code and suggest improvements:\n\n${production.content}`, { agent: "gemini" } ); // Apply fixes const fixed = await orchestrate( `Fix the issues:\n\nOriginal:\n${production.content}\n\nReview:\n${review.content}`, { agent: "claude" } ); console.log('Fixed code:', fixed.content); ``` ``` -------------------------------- ### PuzldAI Programmatic - Pipeline Execution (TypeScript) Source: https://context7.com/medchaouch/puzld.ai/llms.txt Enables programmatic execution of multi-step workflows using the PuzldAI library in TypeScript. This allows for controlled chaining of agents, sequential execution, and injection of previous run results. It also provides access to template statistics if templates are used. ```typescript // Pipeline with programmatic control import { pipeline } from 'puzldai/chat'; const result = await pipeline( "Create a user authentication system", { agents: ['gemini', 'claude', 'gemini'], sequential: true, injectPreviousRuns: true } ); // Access results from each step const [analysis, implementation, review] = result.execution.results; console.log('Analysis:', analysis.content); console.log('Code:', implementation.content); console.log('Review:', review.content); // Check template statistics if (result.templateStats) { console.log(`Success rate: ${result.templateStats.successRate * 100}%`); console.log(`Average duration: ${result.templateStats.avgDuration}ms`); } ``` -------------------------------- ### PuzldAI CLI - Correct Mode (Producer-Reviewer) Source: https://context7.com/medchaouch/puzld.ai/llms.txt Implements a producer-reviewer pattern for code correction using PuzldAI. It allows specifying a producer agent to generate code and a reviewer agent to suggest improvements. The `--fix` flag enables automatic application of suggested fixes. ```bash # Producer-reviewer pattern puzldai correct "write a merge sort function" \ --producer claude \ --reviewer gemini # With automatic fix after review puzldai correct "implement OAuth flow" \ --producer claude \ --reviewer gemini \ --fix ``` -------------------------------- ### Edit Tool for File Search and Replace (TypeScript) Source: https://context7.com/medchaouch/puzld.ai/llms.txt Employ the 'edit' tool to perform search and replace operations within files. This tool requires the file path, the string to search for, and the string to replace it with. It returns an error status if the operation fails. ```typescript // Edit tool: Search and replace in files import { editTool } from 'puzldai/agentic/tools'; const result = await editTool.execute( { path: 'src/config.ts', search: 'const PORT = 3000;', replace: 'const PORT = 8080;' }, process.cwd() ); if (!result.isError) { console.log('File edited successfully'); } ``` -------------------------------- ### PuzldAI CLI - Debate Mode Source: https://context7.com/medchaouch/puzld.ai/llms.txt Enables a debate mode where multiple agents discuss a topic over a specified number of rounds. This is useful for exploring different perspectives on a complex question and reaching a more informed conclusion. ```bash # Multi-round debate puzldai debate "Should we use TypeScript or JavaScript?" \ --agents claude,gemini \ --rounds 3 ``` -------------------------------- ### Programmatic Debate with Puzld.ai (TypeScript) Source: https://context7.com/medchaouch/puzld.ai/llms.txt Programmatically initiate a debate using the Puzld.ai library in TypeScript. This function allows specifying the debate topic, agents, number of rounds, moderator, and whether to include historical debate data. It returns a result object containing final positions and potentially past debates. ```typescript // Programmatic debate import { debate } from 'puzldai/chat'; const result = await debate( "What's the best state management solution for React?", { agents: ['claude', 'gemini', 'codex'], rounds: 3, moderator: 'claude', includeHistory: true } ); // Access final positions for (const position of result.finalPositions) { console.log(`${position.agent}: ${position.position}`); } // Check historical debates on similar topics if (result.pastDebates) { for (const past of result.pastDebates) { console.log(`Past debate: ${past.topic}`); console.log(`Winner: ${past.winner}`); console.log(`Pattern: ${past.winningPattern}`); } } ```