openmonoagent-local-ai-coding-agent

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

OpenMonoAgent.ai — Local AI Coding Agent

OpenMonoAgent.ai — 本地AI编码Agent

Skill by ara.so — AI Agent Skills collection.
OpenMonoAgent is a terminal-native coding agent that runs entirely on your hardware using local LLMs via llama.cpp. Zero per-token costs, full Docker sandboxing, 20 built-in tools, LSP/Roslyn code intelligence, and MCP integration. Built on C#/.NET 10.
ara.so开发的Skill — AI Agent技能合集。
OpenMonoAgent是一款原生终端编码Agent,通过llama.cpp在本地硬件上运行本地大语言模型(LLM),实现零token成本、完整Docker沙箱隔离、内置20种工具、集成LSP/Roslyn代码智能分析与MCP,基于C#/.NET 10构建。

What It Does

核心功能

  • Local inference: Bundles llama.cpp for zero-config, zero-cost token generation
  • Agentic loop: 25 iterations per turn with doom-loop detection and automatic checkpointing
  • 20 tools: File operations, code analysis, Docker commands, git, search, Roslyn diagnostics
  • 5 specialist sub-agents: Explore, Plan, Coder, Verify, general-purpose with isolated tool sets
  • Docker sandbox: Project mounts as
    /workspace
    , blast radius limited to project directory
  • Code intelligence: Roslyn for C#, LSP for TypeScript/Python/Go/Rust, auto-detects graphify/MCP tools
  • Playbooks: YAML workflows with typed parameters, gates, and checkpoint/resume
  • Dual-box mode: Run agent on laptop, inference on separate GPU machine
  • 本地推理:内置llama.cpp,实现零配置、零token成本的令牌生成
  • 智能Agent循环:每轮支持25次迭代,包含死循环检测与自动 checkpoint 功能
  • 20种内置工具:文件操作、代码分析、Docker命令、git、搜索、Roslyn诊断等
  • 5个专业子Agent:探索、规划、编码、验证、通用型,各配备独立工具集
  • Docker沙箱:项目挂载至
    /workspace
    ,操作范围限制在项目目录内
  • 代码智能分析:C#项目支持Roslyn,TypeScript/Python/Go/Rust项目支持LSP,自动识别graphify/MCP工具
  • Playbook工作流:基于YAML的工作流,支持类型化参数、校验门限与断点续传
  • 双设备模式:Agent运行在笔记本,推理任务在独立GPU机器执行

Installation

安装步骤

Quick Install (Ubuntu 26.04 LTS or 25.10)

快速安装(Ubuntu 26.04 LTS 或 25.10)

bash
bash <(curl -fsSL https://raw.githubusercontent.com/StartupHakk/OpenMonoAgent.ai/refs/heads/main/get-openmono.sh)
The installer:
  • Detects your hardware (GPU VRAM or CPU RAM)
  • Selects the appropriate model automatically
  • Installs Docker if missing
  • Pulls and configures the llama.cpp inference container
bash
bash <(curl -fsSL https://raw.githubusercontent.com/StartupHakk/OpenMonoAgent.ai/refs/heads/main/get-openmono.sh)
安装器功能:
  • 检测硬件配置(GPU显存或CPU内存)
  • 自动选择适配模型
  • 自动安装缺失的Docker
  • 拉取并配置llama.cpp推理容器

Hardware Requirements

硬件要求

VRAM/RAMModelSpeed
GPU 24GB+Qwen3.6-27B-Q4_K_M~45-70 tok/s
GPU 16GBQwen3.6-27B-UD-IQ3_XXS~20-42 tok/s
GPU 12GBQwen3.5-9B-Q4_K_M~38-40 tok/s
CPU 24GB RAMQwen3.6-35B-A3B-UD-Q4_K_XL~17-20 tok/s
显存/内存模型速度
GPU 24GB+Qwen3.6-27B-Q4_K_M~45-70 tok/s
GPU 16GBQwen3.6-27B-UD-IQ3_XXS~20-42 tok/s
GPU 12GBQwen3.5-9B-Q4_K_M~38-40 tok/s
CPU 24GB RAMQwen3.6-35B-A3B-UD-Q4_K_XL~17-20 tok/s

Basic Usage

基础使用

Starting the Agent

启动Agent

bash
undefined
bash
undefined

TUI mode (default, interactive)

TUI模式(默认,交互式)

cd your-project/ openmono agent
cd your-project/ openmono agent

Classic scrolling terminal

经典滚动终端模式

openmono agent --classic
openmono agent --classic

Non-interactive mode

非交互式模式

openmono agent --non-interactive
undefined
openmono agent --non-interactive
undefined

Key Commands

核心命令

bash
undefined
bash
undefined

Check status

检查状态

openmono status
openmono status

List available models

列出可用模型

openmono models list
openmono models list

Switch model

切换模型

openmono models set qwen3.6-27b-q4
openmono models set qwen3.6-27b-q4

Run a playbook

运行Playbook

openmono playbook run refactor-cleanup.yml
openmono playbook run refactor-cleanup.yml

Export conversation

导出对话记录

openmono export --format markdown session-2026-05-17.md
undefined
openmono export --format markdown session-2026-05-17.md
undefined

Slash Commands (in TUI/Classic mode)

斜杠命令(TUI/经典模式)

/think          Enter extended reasoning mode
/undo           Revert last tool execution
/resume         Continue from last checkpoint
/export         Export conversation history
/checkpoint     Save current state manually
/tools          List available tools
/config         Show current configuration
/help           Show all commands
/think          进入扩展推理模式
/undo           撤销上一次工具执行
/resume         从最近断点继续
/export         导出对话历史
/checkpoint     手动保存当前状态
/tools          列出可用工具
/config         查看当前配置
/help           查看所有命令

Keyboard Shortcuts (TUI mode)

键盘快捷键(TUI模式)

Ctrl+C          Cancel current operation
Ctrl+D          Exit agent
Ctrl+L          Clear screen
Ctrl+R          Reload configuration
Tab             Autocomplete command
Up/Down         Navigate history
Ctrl+C          取消当前操作
Ctrl+D          退出Agent
Ctrl+L          清屏
Ctrl+R          重新加载配置
Tab             命令自动补全
Up/Down         导航历史记录

Configuration

配置说明

User-Level Config

用户级配置

~/.openmono/settings.json
:
json
{
  "inference": {
    "provider": "llama-cpp",
    "model": "qwen3.6-27b-q4",
    "temperature": 0.7,
    "maxTokens": 8192,
    "reasoningMode": false
  },
  "agent": {
    "maxIterations": 25,
    "doomLoopThreshold": 3,
    "checkpointAt": 0.65,
    "compactAt": 0.80
  },
  "sandbox": {
    "enabled": true,
    "mountPath": "/workspace",
    "networkIsolation": true
  },
  "codeIntelligence": {
    "roslyn": {
      "enabled": true,
      "cacheDuration": 300
    },
    "lsp": {
      "autoStart": true,
      "servers": ["typescript", "python", "go", "rust"]
    },
    "mcp": {
      "enabled": true,
      "autoDetect": ["graphify", "code-review-graph"]
    }
  },
  "tools": {
    "parallelReads": true,
    "maxConcurrent": 5
  }
}
~/.openmono/settings.json
:
json
{
  "inference": {
    "provider": "llama-cpp",
    "model": "qwen3.6-27b-q4",
    "temperature": 0.7,
    "maxTokens": 8192,
    "reasoningMode": false
  },
  "agent": {
    "maxIterations": 25,
    "doomLoopThreshold": 3,
    "checkpointAt": 0.65,
    "compactAt": 0.80
  },
  "sandbox": {
    "enabled": true,
    "mountPath": "/workspace",
    "networkIsolation": true
  },
  "codeIntelligence": {
    "roslyn": {
      "enabled": true,
      "cacheDuration": 300
    },
    "lsp": {
      "autoStart": true,
      "servers": ["typescript", "python", "go", "rust"]
    },
    "mcp": {
      "enabled": true,
      "autoDetect": ["graphify", "code-review-graph"]
    }
  },
  "tools": {
    "parallelReads": true,
    "maxConcurrent": 5
  }
}

Project-Level Config

项目级配置

.openmono/settings.json
(overrides user-level):
json
{
  "inference": {
    "model": "qwen3.6-27b-q4",
    "temperature": 0.6
  },
  "permissions": {
    "allowedPaths": [
      "/workspace/src",
      "/workspace/tests"
    ],
    "deniedPaths": [
      "/workspace/.env",
      "/workspace/secrets"
    ],
    "allowedTools": [
      "read_file",
      "write_file",
      "list_directory",
      "run_command",
      "roslyn_analyze"
    ]
  },
  "mcp": {
    "servers": [
      {
        "name": "custom-graph",
        "command": "node",
        "args": ["/workspace/tools/graph-server.js"],
        "env": {
          "GRAPH_DB": "/workspace/.graph/db.sqlite"
        }
      }
    ]
  }
}
.openmono/settings.json
(覆盖用户级配置):
json
{
  "inference": {
    "model": "qwen3.6-27b-q4",
    "temperature": 0.6
  },
  "permissions": {
    "allowedPaths": [
      "/workspace/src",
      "/workspace/tests"
    ],
    "deniedPaths": [
      "/workspace/.env",
      "/workspace/secrets"
    ],
    "allowedTools": [
      "read_file",
      "write_file",
      "list_directory",
      "run_command",
      "roslyn_analyze"
    ]
  },
  "mcp": {
    "servers": [
      {
        "name": "custom-graph",
        "command": "node",
        "args": ["/workspace/tools/graph-server.js"],
        "env": {
          "GRAPH_DB": "/workspace/.graph/db.sqlite"
        }
      }
    ]
  }
}

Working with Playbooks

Playbook使用指南

Basic Playbook Structure

基础Playbook结构

refactor-api.yml
:
yaml
name: refactor-api-endpoints
description: Refactor REST API endpoints to use new validation middleware
version: 1.0.0

parameters:
  - name: targetController
    type: string
    required: true
    description: Controller class to refactor
  - name: addLogging
    type: boolean
    default: true
    description: Add structured logging to endpoints

gates:
  - condition: "file_exists('src/Middleware/ValidationMiddleware.cs')"
    message: "Validation middleware must exist before refactoring"

steps:
  - name: analyze-controller
    agent: explore
    prompt: "Analyze {{targetController}} and identify all endpoints that need validation"
    tools:
      - read_file
      - roslyn_analyze
      - list_directory

  - name: plan-refactor
    agent: plan
    prompt: "Create refactoring plan for validation middleware integration"
    checkpoint: true

  - name: apply-changes
    agent: coder
    prompt: |
      Apply refactoring:
      1. Add validation middleware to endpoints
      {% if addLogging %}
      2. Add structured logging with ILogger
      {% endif %}
      3. Update error handling
    tools:
      - read_file
      - write_file
      - roslyn_analyze

  - name: verify-build
    agent: verify
    prompt: "Verify refactored code compiles and passes static analysis"
    tools:
      - run_command
      - roslyn_diagnostics

outputs:
  - modifiedFiles
  - diagnosticsReport
refactor-api.yml
:
yaml
name: refactor-api-endpoints
description: Refactor REST API endpoints to use new validation middleware
version: 1.0.0

parameters:
  - name: targetController
    type: string
    required: true
    description: Controller class to refactor
  - name: addLogging
    type: boolean
    default: true
    description: Add structured logging to endpoints

gates:
  - condition: "file_exists('src/Middleware/ValidationMiddleware.cs')"
    message: "Validation middleware must exist before refactoring"

steps:
  - name: analyze-controller
    agent: explore
    prompt: "Analyze {{targetController}} and identify all endpoints that need validation"
    tools:
      - read_file
      - roslyn_analyze
      - list_directory

  - name: plan-refactor
    agent: plan
    prompt: "Create refactoring plan for validation middleware integration"
    checkpoint: true

  - name: apply-changes
    agent: coder
    prompt: |
      Apply refactoring:
      1. Add validation middleware to endpoints
      {% if addLogging %}
      2. Add structured logging with ILogger
      {% endif %}
      3. Update error handling
    tools:
      - read_file
      - write_file
      - roslyn_analyze

  - name: verify-build
    agent: verify
    prompt: "Verify refactored code compiles and passes static analysis"
    tools:
      - run_command
      - roslyn_diagnostics

outputs:
  - modifiedFiles
  - diagnosticsReport

Running Playbooks

运行Playbook

bash
undefined
bash
undefined

Run with parameters

带参数运行

openmono playbook run refactor-api.yml
--param targetController=UserController
--param addLogging=true
openmono playbook run refactor-api.yml
--param targetController=UserController
--param addLogging=true

Resume from checkpoint

从断点恢复

openmono playbook resume refactor-api.yml --checkpoint 2
openmono playbook resume refactor-api.yml --checkpoint 2

List available playbooks

列出可用Playbook

openmono playbook list
openmono playbook list

Validate playbook syntax

验证Playbook语法

openmono playbook validate refactor-api.yml
undefined
openmono playbook validate refactor-api.yml
undefined

Composable Playbooks

组合式Playbook

yaml
name: full-feature-implementation
description: Implement feature from requirements to tests

steps:
  - name: gather-requirements
    playbook: analyze-requirements.yml
    inputs:
      requirementsDoc: "{{requirementsPath}}"

  - name: implement-feature
    playbook: implement-backend.yml
    inputs:
      spec: "{{outputs.analyze-requirements.specification}}"

  - name: add-tests
    playbook: generate-tests.yml
    inputs:
      targetFiles: "{{outputs.implement-feature.modifiedFiles}}"
yaml
name: full-feature-implementation
description: Implement feature from requirements to tests

steps:
  - name: gather-requirements
    playbook: analyze-requirements.yml
    inputs:
      requirementsDoc: "{{requirementsPath}}"

  - name: implement-feature
    playbook: implement-backend.yml
    inputs:
      spec: "{{outputs.analyze-requirements.specification}}"

  - name: add-tests
    playbook: generate-tests.yml
    inputs:
      targetFiles: "{{outputs.implement-feature.modifiedFiles}}"

Code Intelligence Features

代码智能分析功能

Roslyn Analysis (C#)

Roslyn分析(C#)

Automatically available for C# projects:
csharp
// Agent can analyze type hierarchies
public interface IRepository<T> { }
public class UserRepository : IRepository<User> { }

// Agent understands call graphs
public class UserService
{
    private readonly IRepository<User> _repo;
    
    public async Task<User> GetUser(int id)
    {
        // Agent tracks callers and callees
        return await _repo.GetByIdAsync(id);
    }
}

// Agent detects diagnostics
public class ProblematicCode
{
    // CA1052: Static holder types should be Static or NotInheritable
    public class Constants
    {
        public const string ApiKey = "hardcoded"; // Security issue detected
    }
}
C#项目自动支持:
csharp
// Agent可分析类型层级
public interface IRepository<T> { }
public class UserRepository : IRepository<User> { }

// Agent理解调用图
public class UserService
{
    private readonly IRepository<User> _repo;
    
    public async Task<User> GetUser(int id)
    {
        // Agent跟踪调用方与被调用方
        return await _repo.GetByIdAsync(id);
    }
}

// Agent检测诊断问题
public class ProblematicCode
{
    // CA1052: Static holder types should be Static or NotInheritable
    public class Constants
    {
        public const string ApiKey = "hardcoded"; // 检测到硬编码密钥安全问题
    }
}

LSP Integration

LSP集成

Auto-starts language servers on first use:
typescript
// TypeScript - tsserver starts automatically
import { Express } from 'express';

export class ApiController {
    // Agent has symbol navigation, type info, references
    async getUser(req: Request, res: Response): Promise<void> {
        // Autocomplete, hover info, go-to-definition available
    }
}
python
undefined
首次使用时自动启动语言服务器:
typescript
// TypeScript - tsserver自动启动
import { Express } from 'express';

export class ApiController {
    // Agent支持符号导航、类型信息、引用查询
    async getUser(req: Request, res: Response): Promise<void> {
        // 支持自动补全、悬停信息、跳转定义
    }
}
python
undefined

Python - pyright/pylsp starts automatically

Python - pyright/pylsp自动启动

from typing import Optional, List from pydantic import BaseModel
class User(BaseModel): # Agent understands type hints, can suggest fixes id: int name: str email: Optional[str] = None
undefined
from typing import Optional, List from pydantic import BaseModel
class User(BaseModel): // Agent理解类型提示,可建议修复方案 id: int name: str email: Optional[str] = None
undefined

MCP Tool Integration

MCP工具集成

If
graphify
is installed, agent auto-detects:
bash
undefined
若安装了
graphify
,Agent会自动识别:
bash
undefined

Agent can use semantic graph queries

Agent可使用语义图查询

"Find all classes that implement the Repository pattern" "Show me the data flow from API endpoint to database" "List all usages of the User entity across the codebase"

If `code-review-graph` is installed:

```bash
"Find all classes that implement the Repository pattern" "Show me the data flow from API endpoint to database" "List all usages of the User entity across the codebase"

若安装了`code-review-graph`:

```bash

Agent can use structural analysis

Agent可使用结构分析

"Analyze the call graph for circular dependencies" "Find dead code that's never called" "Show the complexity metrics for this module"
undefined
"Analyze the call graph for circular dependencies" "Find dead code that's never called" "Show the complexity metrics for this module"
undefined

Tool Pipeline

工具执行流程

Every tool call goes through 12 steps:
  1. Parse — Extract tool name and arguments
  2. Schema Validate — Check against tool schema
  3. Path Sanity — Verify paths are within
    /workspace
  4. Plan-Mode Guard — Block writes if in plan/explore agent
  5. Capability Check — Verify agent has permission
  6. Cache — Return cached result if available (reads only)
  7. Pre-Hook — Custom validation logic
  8. Execute — Run the actual tool
  9. Post-Hook — Custom processing
  10. Artifact Store — Save outputs
  11. Log — Record execution details
  12. Return — Send result to agent
每个工具调用都会经过12个步骤:
  1. 解析 — 提取工具名称与参数
  2. Schema验证 — 检查是否符合工具Schema
  3. 路径合法性 — 验证路径是否在
    /workspace
    范围内
  4. 规划模式防护 — 若处于规划/探索Agent模式,阻止写入操作
  5. 权限检查 — 验证Agent是否具备操作权限
  6. 缓存 — 若为读取操作,返回缓存结果(如果存在)
  7. 前置钩子 — 自定义验证逻辑
  8. 执行 — 运行实际工具
  9. 后置钩子 — 自定义处理逻辑
  10. 工件存储 — 保存输出结果
  11. 日志 — 记录执行详情
  12. 返回 — 将结果发送给Agent

Tool Permission Example

工具权限示例

json
{
  "permissions": {
    "tools": {
      "read_file": {
        "enabled": true,
        "maxSize": "10MB",
        "allowedExtensions": [".cs", ".ts", ".py", ".go"]
      },
      "write_file": {
        "enabled": true,
        "maxSize": "1MB",
        "requiresConfirmation": true
      },
      "run_command": {
        "enabled": true,
        "allowedCommands": ["dotnet", "npm", "git"],
        "timeout": 60
      }
    }
  }
}
json
{
  "permissions": {
    "tools": {
      "read_file": {
        "enabled": true,
        "maxSize": "10MB",
        "allowedExtensions": [".cs", ".ts", ".py", ".go"]
      },
      "write_file": {
        "enabled": true,
        "maxSize": "1MB",
        "requiresConfirmation": true
      },
      "run_command": {
        "enabled": true,
        "allowedCommands": ["dotnet", "npm", "git"],
        "timeout": 60
      }
    }
  }
}

Dual-Box Setup (Agent on Laptop, Inference on GPU Server)

双设备配置(Agent在笔记本,推理在GPU服务器)

On GPU Server

GPU服务器端

bash
undefined
bash
undefined

Install and expose inference server

安装并暴露推理服务器

Expose on network (port 8080)

网络暴露(端口8080)

docker run -d
--name openmono-inference
--gpus all
-p 8080:8080
-v ~/.openmono/models:/models
openmono/inference:latest
undefined
docker run -d
--name openmono-inference
--gpus all
-p 8080:8080
-v ~/.openmono/models:/models
openmono/inference:latest
undefined

On Laptop (Agent)

笔记本端(Agent)

bash
undefined
bash
undefined

Install agent only (no inference)

仅安装Agent(不包含推理)

Configure remote inference

配置远程推理

openmono config set inference.endpoint http://gpu-server.local:8080

Or use the free relay:

```bash
openmono config set inference.endpoint http://gpu-server.local:8080

或使用免费中继服务:

```bash

On GPU server (register with relay)

GPU服务器端(注册中继)

openmono relay register
openmono relay register

On laptop (connect via relay)

笔记本端(通过中继连接)

openmono relay connect --token YOUR_RELAY_TOKEN
undefined
openmono relay connect --token YOUR_RELAY_TOKEN
undefined

Verify Connection

验证连接

bash
undefined
bash
undefined

Test inference connection

测试推理连接

openmono test inference
openmono test inference

Check latency

检查延迟

openmono status --verbose
undefined
openmono status --verbose
undefined

Programmatic Usage (C# API)

程序化使用(C# API)

If you want to embed OpenMono in your own .NET application:
csharp
using OpenMono.Agent;
using OpenMono.Inference;
using OpenMono.Tools;

// Configure inference provider
var inferenceConfig = new InferenceConfig
{
    Provider = InferenceProvider.LlamaCpp,
    Endpoint = "http://localhost:8080",
    Model = "qwen3.6-27b-q4",
    Temperature = 0.7,
    MaxTokens = 8192
};

// Create agent
var agent = new MonoAgent(inferenceConfig);

// Register custom tool
agent.ToolRegistry.Register(new CustomTool
{
    Name = "fetch_api_data",
    Description = "Fetch data from external API",
    Schema = new ToolSchema
    {
        Parameters = new[]
        {
            new Parameter { Name = "endpoint", Type = "string", Required = true },
            new Parameter { Name = "method", Type = "string", Default = "GET" }
        }
    },
    Execute = async (args) =>
    {
        var endpoint = args["endpoint"].ToString();
        var method = args["method"].ToString();
        
        using var client = new HttpClient();
        var response = await client.GetStringAsync(endpoint);
        
        return new ToolResult
        {
            Success = true,
            Output = response
        };
    }
});

// Run agent with prompt
var response = await agent.RunAsync(
    prompt: "Analyze the User model and suggest improvements",
    workspacePath: "/path/to/project",
    maxIterations: 25
);

// Access results
Console.WriteLine($"Completed in {response.Iterations} iterations");
foreach (var artifact in response.Artifacts)
{
    Console.WriteLine($"Generated: {artifact.Path}");
}
若要在自己的.NET应用中嵌入OpenMono:
csharp
using OpenMono.Agent;
using OpenMono.Inference;
using OpenMono.Tools;

// 配置推理提供者
var inferenceConfig = new InferenceConfig
{
    Provider = InferenceProvider.LlamaCpp,
    Endpoint = "http://localhost:8080",
    Model = "qwen3.6-27b-q4",
    Temperature = 0.7,
    MaxTokens = 8192
};

// 创建Agent
var agent = new MonoAgent(inferenceConfig);

// 注册自定义工具
agent.ToolRegistry.Register(new CustomTool
{
    Name = "fetch_api_data",
    Description = "Fetch data from external API",
    Schema = new ToolSchema
    {
        Parameters = new[]
        {
            new Parameter { Name = "endpoint", Type = "string", Required = true },
            new Parameter { Name = "method", Type = "string", Default = "GET" }
        }
    },
    Execute = async (args) =>
    {
        var endpoint = args["endpoint"].ToString();
        var method = args["method"].ToString();
        
        using var client = new HttpClient();
        var response = await client.GetStringAsync(endpoint);
        
        return new ToolResult
        {
            Success = true,
            Output = response
        };
    }
});

// 运行Agent并传入提示词
var response = await agent.RunAsync(
    prompt: "Analyze the User model and suggest improvements",
    workspacePath: "/path/to/project",
    maxIterations: 25
);

// 访问结果
Console.WriteLine($"Completed in {response.Iterations} iterations");
foreach (var artifact in response.Artifacts)
{
    Console.WriteLine($"Generated: {artifact.Path}");
}

Custom Sub-Agent

自定义子Agent

csharp
using OpenMono.Agent.SubAgents;

public class SecurityAuditorAgent : SubAgent
{
    public override string Name => "security-auditor";
    public override int MaxTurns => 20;
    
    public override string[] AllowedTools => new[]
    {
        "read_file",
        "list_directory",
        "roslyn_analyze",
        "run_command" // Limited to static analysis tools
    };
    
    public override string SystemPrompt => @"
        You are a security auditor. Your job is to:
        1. Identify security vulnerabilities
        2. Check for hardcoded secrets
        3. Verify dependency versions
        4. Suggest security improvements
        
        You cannot modify code - only report findings.
    ";
    
    protected override async Task<SubAgentResult> ExecuteAsync(
        string userPrompt,
        CancellationToken ct)
    {
        var findings = new List<SecurityFinding>();
        
        // Scan for hardcoded secrets
        var sourceFiles = await ToolExecutor.ExecuteAsync(
            "list_directory",
            new { path = "/workspace", recursive = true, pattern = "*.cs" }
        );
        
        foreach (var file in sourceFiles)
        {
            var content = await ToolExecutor.ExecuteAsync(
                "read_file",
                new { path = file }
            );
            
            if (ContainsHardcodedSecret(content))
            {
                findings.Add(new SecurityFinding
                {
                    Severity = "High",
                    File = file,
                    Issue = "Hardcoded secret detected"
                });
            }
        }
        
        return new SubAgentResult
        {
            Success = true,
            Findings = findings,
            Summary = $"Found {findings.Count} security issues"
        };
    }
}

// Register and use
agent.SubAgents.Register<SecurityAuditorAgent>();

var result = await agent.RunSubAgentAsync(
    "security-auditor",
    "Audit this project for security vulnerabilities"
);
csharp
using OpenMono.Agent.SubAgents;

public class SecurityAuditorAgent : SubAgent
{
    public override string Name => "security-auditor";
    public override int MaxTurns => 20;
    
    public override string[] AllowedTools => new[]
    {
        "read_file",
        "list_directory",
        "roslyn_analyze",
        "run_command" // 仅限制为静态分析工具
    };
    
    public override string SystemPrompt => @"
        You are a security auditor. Your job is to:
        1. Identify security vulnerabilities
        2. Check for hardcoded secrets
        3. Verify dependency versions
        4. Suggest security improvements
        
        You cannot modify code - only report findings.
    ";
    
    protected override async Task<SubAgentResult> ExecuteAsync(
        string userPrompt,
        CancellationToken ct)
    {
        var findings = new List<SecurityFinding>();
        
        // 扫描硬编码密钥
        var sourceFiles = await ToolExecutor.ExecuteAsync(
            "list_directory",
            new { path = "/workspace", recursive = true, pattern = "*.cs" }
        );
        
        foreach (var file in sourceFiles)
        {
            var content = await ToolExecutor.ExecuteAsync(
                "read_file",
                new { path = file }
            );
            
            if (ContainsHardcodedSecret(content))
            {
                findings.Add(new SecurityFinding
                {
                    Severity = "High",
                    File = file,
                    Issue = "Hardcoded secret detected"
                });
            }
        }
        
        return new SubAgentResult
        {
            Success = true,
            Findings = findings,
            Summary = $"Found {findings.Count} security issues"
        };
    }
}

// 注册并使用
agent.SubAgents.Register<SecurityAuditorAgent>();

var result = await agent.RunSubAgentAsync(
    "security-auditor",
    "Audit this project for security vulnerabilities"
);

Alternative Inference Providers

可选推理提供者

OpenAI (WIP)

OpenAI(开发中)

json
{
  "inference": {
    "provider": "openai",
    "model": "gpt-4",
    "apiKey": "${OPENAI_API_KEY}",
    "temperature": 0.7
  }
}
bash
export OPENAI_API_KEY=sk-...
openmono agent
json
{
  "inference": {
    "provider": "openai",
    "model": "gpt-4",
    "apiKey": "${OPENAI_API_KEY}",
    "temperature": 0.7
  }
}
bash
export OPENAI_API_KEY=sk-...
openmono agent

Anthropic (WIP)

Anthropic(开发中)

json
{
  "inference": {
    "provider": "anthropic",
    "model": "claude-3-5-sonnet-20241022",
    "apiKey": "${ANTHROPIC_API_KEY}"
  }
}
json
{
  "inference": {
    "provider": "anthropic",
    "model": "claude-3-5-sonnet-20241022",
    "apiKey": "${ANTHROPIC_API_KEY}"
  }
}

Ollama (WIP)

Ollama(开发中)

json
{
  "inference": {
    "provider": "ollama",
    "endpoint": "http://localhost:11434",
    "model": "qwen2.5-coder:32b"
  }
}
Note: OpenAI, Anthropic, and Ollama providers are work-in-progress. Local llama.cpp is the only fully supported provider.
json
{
  "inference": {
    "provider": "ollama",
    "endpoint": "http://localhost:11434",
    "model": "qwen2.5-coder:32b"
  }
}
注意:OpenAI、Anthropic与Ollama提供者仍在开发中,仅本地llama.cpp为完全支持的提供者。

Troubleshooting

故障排查

Agent Won't Start

Agent无法启动

bash
undefined
bash
undefined

Check Docker status

检查Docker状态

docker ps | grep openmono
docker ps | grep openmono

View logs

查看日志

docker logs openmono-inference
docker logs openmono-inference

Restart inference container

重启推理容器

docker restart openmono-inference
docker restart openmono-inference

Full reset

完全重置

openmono reset --hard
undefined
openmono reset --hard
undefined

Slow Inference

推理速度慢

bash
undefined
bash
undefined

Check current model and provider

检查当前模型与提供者

openmono status
openmono status

Verify GPU is being used (if available)

验证GPU是否被使用(若可用)

docker exec openmono-inference nvidia-smi
docker exec openmono-inference nvidia-smi

Switch to smaller model

切换至更小模型

openmono models set qwen3.5-9b-q4
openmono models set qwen3.5-9b-q4

Check for CPU throttling

检查CPU节流情况

openmono diagnose performance
undefined
openmono diagnose performance
undefined

Tools Not Working

工具无法工作

bash
undefined
bash
undefined

List available tools

列出可用工具

openmono tools list
openmono tools list

Check tool permissions

检查工具权限

openmono config get permissions.tools
openmono config get permissions.tools

Test specific tool

测试特定工具

openmono test tool read_file --path src/Program.cs
openmono test tool read_file --path src/Program.cs

View tool execution logs

查看工具执行日志

openmono logs --filter tools --tail 50
undefined
openmono logs --filter tools --tail 50
undefined

Roslyn/LSP Issues

Roslyn/LSP问题

bash
undefined
bash
undefined

Clear Roslyn cache

清除Roslyn缓存

rm -rf ~/.openmono/cache/roslyn/*
rm -rf ~/.openmono/cache/roslyn/*

Restart LSP servers

重启LSP服务器

openmono lsp restart
openmono lsp restart

Disable and re-enable

禁用并重新启用

openmono config set codeIntelligence.roslyn.enabled false openmono config set codeIntelligence.roslyn.enabled true
openmono config set codeIntelligence.roslyn.enabled false openmono config set codeIntelligence.roslyn.enabled true

Check compilation errors

检查编译错误

openmono roslyn compile --verbose
undefined
openmono roslyn compile --verbose
undefined

Context Overflow

上下文溢出

bash
undefined
bash
undefined

Force checkpoint

强制创建断点

/checkpoint
/checkpoint

Reduce max iterations

减少最大迭代次数

openmono config set agent.maxIterations 15
openmono config set agent.maxIterations 15

Enable aggressive compaction

启用激进压缩

openmono config set agent.compactAt 0.70
openmono config set agent.compactAt 0.70

Clear conversation and restart

清除对话并重启

openmono reset --conversation-only
undefined
openmono reset --conversation-only
undefined

Docker Permission Issues

Docker权限问题

bash
undefined
bash
undefined

Add user to docker group (requires logout/login)

将用户添加至docker组(需重新登录)

sudo usermod -aG docker $USER
sudo usermod -aG docker $USER

Or run with sudo (not recommended)

或使用sudo运行(不推荐)

sudo openmono agent
undefined
sudo openmono agent
undefined

Network Issues (Dual-Box)

双设备网络问题

bash
undefined
bash
undefined

Test connection

测试连接

Check firewall

检查防火墙

sudo ufw status sudo ufw allow 8080/tcp
sudo ufw status sudo ufw allow 8080/tcp

Verify relay connection

验证中继连接

openmono relay status
openmono relay status

Switch to direct connection

切换至直接连接

openmono config set inference.endpoint http://gpu-server.local:8080 openmono config set inference.useRelay false
undefined
openmono config set inference.endpoint http://gpu-server.local:8080 openmono config set inference.useRelay false
undefined

Common Patterns

常见使用模式

Automated Code Review

自动化代码评审

bash
openmono agent --classic << 'EOF'
Review all changes in the last commit:
1. Check for code smells
2. Verify error handling
3. Suggest performance improvements
4. Check for security issues

Use the verify sub-agent and Roslyn diagnostics.
/think
EOF
bash
openmono agent --classic << 'EOF'
Review all changes in the last commit:
1. Check for code smells
2. Verify error handling
3. Suggest performance improvements
4. Check for security issues

Use the verify sub-agent and Roslyn diagnostics.
/think
EOF

Generate Documentation

生成文档

yaml
undefined
yaml
undefined

generate-docs.yml

generate-docs.yml

name: generate-api-documentation steps:
  • name: analyze agent: explore prompt: "Map all public API endpoints and their parameters"
  • name: generate agent: coder prompt: | Generate OpenAPI/Swagger documentation:
    1. Create swagger.json
    2. Add XML doc comments to controllers
    3. Generate README.md with usage examples
undefined
name: generate-api-documentation steps:
  • name: analyze agent: explore prompt: "Map all public API endpoints and their parameters"
  • name: generate agent: coder prompt: | Generate OpenAPI/Swagger documentation:
    1. Create swagger.json
    2. Add XML doc comments to controllers
    3. Generate README.md with usage examples
undefined

Refactor with Verification

带验证的重构

yaml
undefined
yaml
undefined

safe-refactor.yml

safe-refactor.yml

name: refactor-with-rollback
parameters:
  • name: targetFile type: string required: true
steps:
  • name: backup agent: general-purpose prompt: "Create backup of {{targetFile}}"
  • name: refactor agent: coder prompt: "Refactor {{targetFile}} to improve maintainability" checkpoint: true
  • name: verify agent: verify prompt: | Verify refactoring:
    1. Code compiles
    2. Tests pass
    3. No new warnings
    onFailure: rollback: true restoreCheckpoint: backup
undefined
name: refactor-with-rollback
parameters:
  • name: targetFile type: string required: true
steps:
  • name: backup agent: general-purpose prompt: "Create backup of {{targetFile}}"
  • name: refactor agent: coder prompt: "Refactor {{targetFile}} to improve maintainability" checkpoint: true
  • name: verify agent: verify prompt: | Verify refactoring:
    1. Code compiles
    2. Tests pass
    3. No new warnings
    onFailure: rollback: true restoreCheckpoint: backup
undefined

Dependency Update Audit

依赖更新审计

bash
openmono agent
> Update all NuGet packages and verify compatibility:
> 1. Check current package versions
> 2. Update packages one at a time
> 3. Run tests after each update
> 4. Rollback if tests fail
> 5. Generate compatibility report
bash
openmono agent
> Update all NuGet packages and verify compatibility:
> 1. Check current package versions
> 2. Update packages one at a time
> 3. Run tests after each update
> 4. Rollback if tests fail
> 5. Generate compatibility report

Best Practices

最佳实践

  1. Use project-level config for sensitive permissions — don't allow all tools globally
  2. Enable sandboxing in production — never disable Docker isolation
  3. Set checkpoints before risky operations — use playbooks with
    checkpoint: true
  4. Limit tool concurrency for stability —
    maxConcurrent: 3-5
  5. Use sub-agents for specialized tasks — don't let general-purpose agent write to production
  6. Cache Roslyn analysis — 5 minute default is good for most projects
  7. Monitor context usage — enable auto-compaction at 70-80%
  8. Pin model versions in playbooks — don't rely on "latest"
  9. Use MCP for complex graphs — don't reinvent semantic analysis
  10. Log everything
    openmono logs --export
    before reporting issues
  1. 使用项目级配置管理敏感权限——不要全局允许所有工具
  2. 生产环境启用沙箱——永远不要禁用Docker隔离
  3. 风险操作前设置断点——使用带
    checkpoint: true
    的Playbook
  4. 限制工具并发数保证稳定性——
    maxConcurrent: 3-5
  5. 专业任务使用子Agent——不要让通用Agent操作生产环境代码
  6. 缓存Roslyn分析结果——默认5分钟缓存适合大多数项目
  7. 监控上下文使用——在70-80%时启用自动压缩
  8. Playbook中固定模型版本——不要依赖"latest"
  9. 复杂图分析使用MCP——不要重复实现语义分析
  10. 完整记录日志——上报问题前执行
    openmono logs --export

Resources

资源链接