Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

第十二章:扩展开发

本章介绍如何扩展 OpenMatrix 的功能。

12.1 扩展点概览

OpenMatrix 提供以下扩展点:

扩展点说明位置
自定义 Agent添加新的执行 Agentagents/impl/
自定义质量门禁添加新的验证规则orchestrator/gates/
自定义 Skills添加新的 CLI 命令skills/
自定义存储后端替换存储实现storage/

12.2 自定义 Agent

Agent 基类

export abstract class BaseAgent {
    protected taskId: string;
    protected agentType: AgentType;

    abstract execute(): Promise<AgentResult>;

    protected readContext(): string;
    protected writeContext(content: string): void;
    protected logDecision(decision: Decision): void;
}

创建自定义 Agent

import { BaseAgent, AgentResult } from '../base-agent';

export class CustomAgent extends BaseAgent {
    constructor(taskId: string, context: AgentContext) {
        super(taskId, 'custom', context);
    }

    async execute(): Promise<AgentResult> {
        // 1. 读取上下文
        const context = this.readContext();

        // 2. 执行自定义逻辑
        const result = await this.performWork();

        // 3. 记录决策
        this.logDecision({
            description: 'Custom action performed',
            reason: 'Based on task requirements'
        });

        // 4. 返回结果
        return {
            taskId: this.taskId,
            agentType: 'custom',
            status: result.success ? 'success' : 'failed',
            output: {
                artifacts: result.files,
                contextUpdate: result.summary
            }
        };
    }
}

注册 Agent

const agentRegistry = {
    // ... 现有 Agent
    'custom': CustomAgent
};

12.3 自定义质量门禁

质量门禁接口

export interface QualityGate {
    name: string;
    check(context: GateContext): Promise<GateResult>;
    required: boolean;
    getSuggestions?(result: GateResult): string[];
}

创建自定义门禁

import { QualityGate, GateContext, GateResult } from './gate-interface';

export class CustomGate implements QualityGate {
    name = 'custom-check';
    required = true;

    async check(context: GateContext): Promise<GateResult> {
        const issues = await this.performCheck(context);

        return {
            status: issues.length === 0 ? 'pass' : 'fail',
            errors: issues
        };
    }

    getSuggestions(result: GateResult): string[] {
        return ['建议检查以下几点...'];
    }
}

12.4 自定义 Skill

Skill 文件格式

---
name: custom-skill
description: Custom skill description
---

# /om:custom-skill

Custom skill description.

## Usage

\`\`\`bash
/om:custom-skill [options]
\`\`\`

## Options

| Option | Type | Description |
|--------|------|-------------|
| --option1 | string | Option description |

## Examples

\`\`\`bash
/om:custom-skill --option1 value
\`\`\`

## Implementation

\`\`\`bash
openmatrix start --custom-option "$option"
\`\`\`

安装 Skill

cp custom-skill.md ~/.claude/commands/om/

12.5 插件系统

插件接口

export interface OpenMatrixPlugin {
    name: string;
    version: string;
    initialize(context: PluginContext): Promise<void>;
    agents?: AgentRegistration[];
    gates?: QualityGate[];
    hooks?: {
        beforeTaskStart?: (task: Task) => Promise<void>;
        afterTaskComplete?: (task: Task, result: AgentResult) => Promise<void>;
        onError?: (error: Error) => Promise<void>;
    };
}

创建插件

export class CustomPlugin implements OpenMatrixPlugin {
    name = 'custom-plugin';
    version = '1.0.0';

    async initialize(context: PluginContext): Promise<void> {
        // 初始化逻辑
    }

    agents = [
        { type: 'custom', factory: (id, ctx) => new CustomAgent(id, ctx) }
    ];

    gates = [new CustomGate()];

    hooks = {
        beforeTaskStart: async (task) => {
            console.log(`Starting: ${task.id}`);
        }
    };
}

12.6 开发环境

项目结构

openmatrix-extension/
├── src/
│   ├── agents/
│   │   └── custom-agent.ts
│   ├── gates/
│   │   └── custom-gate.ts
│   └── index.ts
├── tests/
│   └── agents/
├── package.json
└── tsconfig.json

测试扩展

import { describe, it, expect } from 'vitest';
import { CustomAgent } from '../../src/agents/custom-agent';

describe('CustomAgent', () => {
    it('should execute successfully', async () => {
        const agent = new CustomAgent('TASK-001', mockContext);
        const result = await agent.execute();
        expect(result.status).toBe('success');
    });
});

附录

下一章将提供 附录,包含类型定义、配置参考和常见问题解答。