refactor: remove Mixture of Agents and Kimi usage
MOA_* was never configured, so enrichArbiterPromptWithMoa always returned the prompt unchanged and the Kimi usage fetch only produced an empty dashboard row. Remove src/moa.ts, src/kimi-usage.ts, the arbiter prompt enrichment, MoA config/schema, the Kimi row and MoA line in the Discord status dashboard, and the MOA_* / unused FALLBACK_* provider examples from the docs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
24
.env.example
24
.env.example
@@ -62,15 +62,6 @@ STATUS_CHANNEL_ID= # Discord channel ID for live status updat
|
||||
# CODEX_WARMUP_MAX_CONSECUTIVE_FAILURES=2
|
||||
# CODEX_WARMUP_FAILURE_COOLDOWN_MS=21600000 # Back off 6h after repeated failure
|
||||
|
||||
# --- Fallback provider (when Claude/Codex both unavailable) ---
|
||||
# FALLBACK_ENABLED=true # Enable fallback provider
|
||||
# FALLBACK_PROVIDER_NAME=kimi # Provider name for logging
|
||||
# FALLBACK_BASE_URL= # OpenAI-compatible API base URL
|
||||
# FALLBACK_AUTH_TOKEN= # API token for fallback provider
|
||||
# FALLBACK_MODEL=kimi-k2.5 # Fallback model
|
||||
# FALLBACK_SMALL_MODEL=kimi-k2.5 # Fallback small model
|
||||
# FALLBACK_COOLDOWN_MS=600000 # Cooldown between fallback attempts (10min)
|
||||
|
||||
# --- Per-role model overrides (paired rooms) ---
|
||||
# Override global CLAUDE_MODEL/CODEX_MODEL per role.
|
||||
# Model is injected based on each role's agent type (claude-code → CLAUDE_MODEL, codex → CODEX_MODEL).
|
||||
@@ -86,21 +77,6 @@ STATUS_CHANNEL_ID= # Discord channel ID for live status updat
|
||||
# ARBITER_EFFORT=xhigh # Arbiter effort override
|
||||
# ARBITER_FALLBACK_ENABLED=true # Fall back to codex on Claude failure (default: true)
|
||||
|
||||
# --- Mixture of Agents (MoA) ---
|
||||
# Queries external API models in parallel before arbiter runs.
|
||||
# Their opinions are injected into the arbiter's prompt for better judgment.
|
||||
# The SDK arbiter (subscription-based, no extra cost) aggregates all perspectives.
|
||||
# MOA_ENABLED=true
|
||||
# MOA_REF_MODELS=kimi,glm # Comma-separated reference model names
|
||||
# MOA_KIMI_MODEL=kimi-k2.6 # Kimi model
|
||||
# MOA_KIMI_BASE_URL=https://api.kimi.com/coding # Kimi API endpoint
|
||||
# MOA_KIMI_API_FORMAT=anthropic # Kimi Code API format
|
||||
# MOA_KIMI_API_KEY=sk-kimi-xxx # Kimi API key
|
||||
# MOA_GLM_MODEL=glm-5.1 # GLM model
|
||||
# MOA_GLM_BASE_URL=https://open.bigmodel.cn/api/anthropic # GLM API endpoint
|
||||
# MOA_GLM_API_FORMAT=anthropic # GLM Anthropic-compatible API
|
||||
# MOA_GLM_API_KEY=xxx # GLM API key
|
||||
|
||||
# --- Advanced ---
|
||||
# MAX_CONCURRENT_AGENTS=5 # Max parallel agent processes
|
||||
# SESSION_COMMAND_ALLOWED_SENDERS= # Comma-separated Discord user IDs for session commands
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
### Removed
|
||||
|
||||
- 웹 대시보드(`src/web-dashboard-*`, `apps/dashboard`), Android 앱(`apps/android`), Glasses UI와 이를 위해서만 있던 설정 저장소(`settings-store`, `settings-store-moa`, `room-skill-settings`, `runtime-inventory`, `codex-live-status`, `settings-effort`), `WEB_DASHBOARD_*` 설정, `dashboard:*`/`android:*` 스크립트, react·vite·playwright 의존성. 잘못된 계정(`~/.codex`)을 갱신하던 Codex 계정 새로고침 루프도 함께 제거. 호스트 증거 도구의 `dashboard_dist`/`android_debug_apk` 항목 제거. Discord 상태 대시보드는 그대로 유지
|
||||
- Mixture of Agents(MoA) arbiter 프롬프트 보강, Kimi 사용량 조회/대시보드 행, `MOA_*` 설정, 코드에서 읽지 않던 `FALLBACK_*` provider 설정 예시
|
||||
|
||||
### Fixed
|
||||
|
||||
|
||||
10
README.md
10
README.md
@@ -24,7 +24,6 @@ EJClaw는 Discord 위에서 동작하는 Tribunal 멀티에이전트 개발 보
|
||||
## 핵심 기능
|
||||
|
||||
- Tribunal 3-에이전트 루프: owner / reviewer / arbiter
|
||||
- Mixture of Agents(MoA): 외부 모델 의견을 arbiter 판단에 주입
|
||||
- 역할별 agent type / model / effort 설정
|
||||
- role-fixed Discord 봇 3개 체계
|
||||
- reviewer host runtime + read-only guard
|
||||
@@ -68,10 +67,6 @@ GitHub `main` 베이스 위에 운영 중 검증된 변경을 현재 코드 구
|
||||
→ 왕복이 누적되면 arbiter 자동 요청 가능
|
||||
```
|
||||
|
||||
### MoA
|
||||
|
||||
MoA가 켜져 있으면 arbiter가 판정하기 전에 Kimi, GLM 같은 외부 모델 의견을 병렬 수집하고, 그 결과를 arbiter 프롬프트에 주입합니다. 최종 판정은 여전히 EJClaw arbiter가 내립니다.
|
||||
|
||||
## 방 설정 모델
|
||||
|
||||
현재 room 설정의 기준은 다음과 같습니다.
|
||||
@@ -107,11 +102,6 @@ Discord ──► SQLite (WAL) ──► GroupQueue ──┬──► Owner (ho
|
||||
│ └─ BLOCKED → arbiter / user
|
||||
│
|
||||
├──► Arbiter (on-demand, fresh session)
|
||||
│ │
|
||||
│ ┌───┴─── MoA ───┐
|
||||
│ │ Kimi / GLM │
|
||||
│ │ 의견 수집 │
|
||||
│ └───────────────┘
|
||||
│
|
||||
IPC follow-up / host tools
|
||||
│
|
||||
|
||||
@@ -45,11 +45,6 @@ Discord ──► SQLite (WAL) ──► GroupQueue ──┬──► Owner (ho
|
||||
│ └─ BLOCKED → arbiter / user
|
||||
│
|
||||
├──► Arbiter (on-demand)
|
||||
│ │
|
||||
│ ┌───┴─── MoA ───┐
|
||||
│ │ Kimi / GLM │
|
||||
│ │ 의견 수집 │
|
||||
│ └───────────────┘
|
||||
│
|
||||
IPC polling / host tools
|
||||
│
|
||||
|
||||
@@ -90,28 +90,6 @@ GROQ_API_KEY=
|
||||
- 기본은 Groq Whisper(`whisper-large-v3-turbo`)
|
||||
- `GROQ_API_KEY`가 없고 `OPENAI_API_KEY`가 있으면 OpenAI Whisper(`whisper-1`)로 자동 대체됩니다(`src/channels/discord.ts`)
|
||||
|
||||
## MoA
|
||||
|
||||
```bash
|
||||
MOA_ENABLED=true
|
||||
MOA_REF_MODELS=kimi,glm
|
||||
|
||||
MOA_KIMI_MODEL=kimi-k2.6
|
||||
MOA_KIMI_BASE_URL=https://api.kimi.com/coding
|
||||
MOA_KIMI_API_KEY=sk-kimi-xxx
|
||||
MOA_KIMI_API_FORMAT=anthropic
|
||||
|
||||
MOA_GLM_MODEL=glm-5.1
|
||||
MOA_GLM_BASE_URL=https://open.bigmodel.cn/api/anthropic
|
||||
MOA_GLM_API_KEY=xxx
|
||||
MOA_GLM_API_FORMAT=anthropic
|
||||
```
|
||||
|
||||
MoA는 arbiter 판정 전에 외부 모델 의견을 수집해 prompt에 주입합니다.
|
||||
대시보드 설정 화면에서 `MOA_ENABLED`, `MOA_REF_MODELS`, 모델명, base URL,
|
||||
API format, API key 교체와 연결 테스트를 관리할 수 있습니다. 저장 후에는
|
||||
스택 재시작이 필요합니다.
|
||||
|
||||
## 운영 / 배포 관련 설정
|
||||
|
||||
```bash
|
||||
|
||||
@@ -27,15 +27,6 @@ You have been summoned because the owner and reviewer reached a deadlock after m
|
||||
- List the concrete options as a short numbered list (1., 2., …) with a one-line consequence for each, so the user can reply with just a number or a short phrase.
|
||||
- Include only the minimum context needed to decide — do not assume the user remembers the prior discussion.
|
||||
|
||||
## MoA (Mixture of Agents) Reference Opinions
|
||||
|
||||
You may receive reference opinions from external models appended to your prompt. When present:
|
||||
|
||||
- **Cite them explicitly** in your verdict — e.g., "Reference model A agrees that...", "Reference model B raises a concern about..."
|
||||
- **Cross-reference** their opinions against the owner/reviewer conversation and code evidence
|
||||
- **Resolve conflicts** — if reference opinions disagree with each other or with owner/reviewer, state which view you adopt and why
|
||||
- Do NOT blindly follow reference opinions — they are inputs to your judgment, not authorities
|
||||
|
||||
## Rules
|
||||
|
||||
- Base your verdict on evidence (code, test output, logs), not on who said what first
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { loadConfig } from './config/load-config.js';
|
||||
import type { MoaConfig } from './moa.js';
|
||||
import type { RoleModelConfig } from './config/schema.js';
|
||||
|
||||
export type { AppConfig, RoleModelConfig } from './config/schema.js';
|
||||
@@ -128,12 +127,6 @@ export function getRoleModelConfig(
|
||||
}
|
||||
}
|
||||
|
||||
// ── Mixture of Agents (MoA) ──────────────────────────────────────
|
||||
|
||||
export function getMoaConfig(): MoaConfig {
|
||||
return CONFIG.moa;
|
||||
}
|
||||
|
||||
export const PAIRED_MAX_ROUND_TRIPS = CONFIG.paired.maxRoundTrips;
|
||||
|
||||
export const RECOVERY_STAGGER_MS = CONFIG.runtime.recoveryStaggerMs;
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
|
||||
import type { MoaConfig, MoaModelConfig } from '../moa.js';
|
||||
import type { AgentType } from '../types.js';
|
||||
import { getEnv, listConfiguredEnvKeys } from '../env.js';
|
||||
|
||||
@@ -75,35 +74,6 @@ function buildRoleModelConfig(envPrefix: string): RoleModelConfig {
|
||||
};
|
||||
}
|
||||
|
||||
function parseMoaReferenceModels(): MoaModelConfig[] {
|
||||
const names = (readText('MOA_REF_MODELS') ?? '')
|
||||
.split(',')
|
||||
.map((value) => value.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
return names
|
||||
.map((name) => {
|
||||
const prefix = `MOA_${name.toUpperCase()}`;
|
||||
const model = readNonEmptyText(`${prefix}_MODEL`) ?? '';
|
||||
const baseUrl = readNonEmptyText(`${prefix}_BASE_URL`) ?? '';
|
||||
const apiKey = readNonEmptyText(`${prefix}_API_KEY`) ?? '';
|
||||
if (!model || !baseUrl || !apiKey) return null;
|
||||
const rawFormat = readText(`${prefix}_API_FORMAT`) ?? '';
|
||||
const apiFormat: 'openai' | 'anthropic' =
|
||||
rawFormat === 'anthropic' ? 'anthropic' : 'openai';
|
||||
return { name, model, baseUrl, apiKey, apiFormat };
|
||||
})
|
||||
.filter((value): value is MoaModelConfig => value !== null);
|
||||
}
|
||||
|
||||
function buildMoaConfig(): MoaConfig {
|
||||
const referenceModels = parseMoaReferenceModels();
|
||||
return {
|
||||
enabled: readText('MOA_ENABLED') === 'true' && referenceModels.length > 0,
|
||||
referenceModels,
|
||||
};
|
||||
}
|
||||
|
||||
function escapeRegex(value: string): string {
|
||||
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
}
|
||||
@@ -256,7 +226,6 @@ export function loadConfig(): AppConfig {
|
||||
claudeDefaultModel: readText('CLAUDE_MODEL') ?? 'claude',
|
||||
codexDefaultModel: readText('CODEX_MODEL') ?? 'codex',
|
||||
},
|
||||
moa: buildMoaConfig(),
|
||||
status: {
|
||||
channelId: readText('STATUS_CHANNEL_ID') ?? '',
|
||||
// Base periodic refresh. Event-driven updates (new message, agent
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { MoaConfig } from '../moa.js';
|
||||
import type { AgentType } from '../types.js';
|
||||
|
||||
export interface RoleModelConfig {
|
||||
@@ -69,7 +68,6 @@ export interface AppConfig {
|
||||
claudeDefaultModel: string;
|
||||
codexDefaultModel: string;
|
||||
};
|
||||
moa: MoaConfig;
|
||||
status: {
|
||||
channelId: string;
|
||||
updateInterval: number;
|
||||
|
||||
@@ -1,208 +0,0 @@
|
||||
/**
|
||||
* Kimi Usage API
|
||||
*
|
||||
* Fetches subscription quota usage from the Kimi Code API.
|
||||
* Endpoint: GET https://api.kimi.com/coding/v1/usages
|
||||
* Auth: Bearer token (same as FALLBACK_AUTH_TOKEN or MOA_KIMI_API_KEY)
|
||||
*
|
||||
* Response maps to the same 5h / weekly window structure as Claude/Codex.
|
||||
*/
|
||||
|
||||
import { getEnv } from './env.js';
|
||||
import { logger } from './logger.js';
|
||||
import { formatResetRemaining, type UsageRow } from './dashboard-usage-rows.js';
|
||||
|
||||
// ── Types ────────────────────────────────────────────────────────
|
||||
|
||||
export interface KimiUsageResponse {
|
||||
user?: {
|
||||
userId?: string;
|
||||
region?: string;
|
||||
membership?: { level?: string };
|
||||
};
|
||||
/** Weekly (rolling) quota */
|
||||
usage?: {
|
||||
limit?: string;
|
||||
used?: string;
|
||||
remaining?: string;
|
||||
resetTime?: string;
|
||||
};
|
||||
/** Per-window limits (e.g. 5-hour sliding window) */
|
||||
limits?: Array<{
|
||||
window?: { duration?: number; timeUnit?: string };
|
||||
detail?: {
|
||||
limit?: string;
|
||||
used?: string;
|
||||
remaining?: string;
|
||||
resetTime?: string;
|
||||
};
|
||||
}>;
|
||||
parallel?: { limit?: string };
|
||||
}
|
||||
|
||||
export interface KimiUsageData {
|
||||
/** 5-hour sliding window */
|
||||
fiveHour?: { pct: number; resetTime: string };
|
||||
/** Weekly rolling quota */
|
||||
weekly?: { pct: number; resetTime: string };
|
||||
/** Membership level (e.g. "LEVEL_INTERMEDIATE") */
|
||||
membershipLevel?: string;
|
||||
}
|
||||
|
||||
// ── Config ───────────────────────────────────────────────────────
|
||||
|
||||
const FETCH_TIMEOUT_MS = 10_000;
|
||||
const MIN_FETCH_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes
|
||||
|
||||
let lastFetchAt = 0;
|
||||
let cachedData: KimiUsageData | null = null;
|
||||
|
||||
function getKimiConfig(): { baseUrl: string; authToken: string } | null {
|
||||
// Try MoA config first, then fallback config
|
||||
const authToken =
|
||||
getEnv('MOA_KIMI_API_KEY') || getEnv('FALLBACK_AUTH_TOKEN') || '';
|
||||
const baseUrl =
|
||||
getEnv('MOA_KIMI_BASE_URL') || getEnv('FALLBACK_BASE_URL') || '';
|
||||
if (!baseUrl || !authToken) return null;
|
||||
return { baseUrl, authToken };
|
||||
}
|
||||
|
||||
// ── Parsing ──────────────────────────────────────────────────────
|
||||
|
||||
function parseWindowPct(detail?: {
|
||||
limit?: string;
|
||||
used?: string;
|
||||
remaining?: string;
|
||||
}): number {
|
||||
if (!detail) return -1;
|
||||
const limit = parseInt(detail.limit || '0', 10);
|
||||
if (limit <= 0) return -1;
|
||||
|
||||
if (detail.used != null) {
|
||||
const used = parseInt(detail.used, 10);
|
||||
return Math.round((used / limit) * 100);
|
||||
}
|
||||
if (detail.remaining != null) {
|
||||
const remaining = parseInt(detail.remaining, 10);
|
||||
return Math.round(((limit - remaining) / limit) * 100);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function parseResponse(resp: KimiUsageResponse): KimiUsageData {
|
||||
const data: KimiUsageData = {};
|
||||
|
||||
// Weekly quota (top-level "usage" field)
|
||||
if (resp.usage) {
|
||||
const pct = parseWindowPct(resp.usage);
|
||||
data.weekly = { pct, resetTime: resp.usage.resetTime || '' };
|
||||
}
|
||||
|
||||
// 5-hour sliding window (first entry in "limits" array)
|
||||
if (resp.limits && resp.limits.length > 0) {
|
||||
const first = resp.limits[0];
|
||||
if (first.detail) {
|
||||
const pct = parseWindowPct(first.detail);
|
||||
data.fiveHour = { pct, resetTime: first.detail.resetTime || '' };
|
||||
}
|
||||
}
|
||||
|
||||
// Membership
|
||||
data.membershipLevel = resp.user?.membership?.level;
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
// ── Fetch ────────────────────────────────────────────────────────
|
||||
|
||||
export async function fetchKimiUsage(): Promise<KimiUsageData | null> {
|
||||
const config = getKimiConfig();
|
||||
if (!config) return null;
|
||||
|
||||
const now = Date.now();
|
||||
if (now - lastFetchAt < MIN_FETCH_INTERVAL_MS && cachedData) {
|
||||
return cachedData;
|
||||
}
|
||||
|
||||
const url = `${config.baseUrl.replace(/\/+$/, '')}/v1/usages`;
|
||||
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'GET',
|
||||
headers: { Authorization: `Bearer ${config.authToken}` },
|
||||
signal: controller.signal,
|
||||
});
|
||||
clearTimeout(timer);
|
||||
|
||||
if (!response.ok) {
|
||||
logger.warn(
|
||||
{ status: response.status, url },
|
||||
'Kimi usage API returned non-OK status',
|
||||
);
|
||||
return cachedData; // Return stale cache on failure
|
||||
}
|
||||
|
||||
const json = (await response.json()) as KimiUsageResponse;
|
||||
cachedData = parseResponse(json);
|
||||
lastFetchAt = Date.now();
|
||||
|
||||
logger.debug(
|
||||
{
|
||||
weeklyPct: cachedData.weekly?.pct,
|
||||
fiveHourPct: cachedData.fiveHour?.pct,
|
||||
membership: cachedData.membershipLevel,
|
||||
},
|
||||
'Kimi usage fetched',
|
||||
);
|
||||
|
||||
return cachedData;
|
||||
} catch (err) {
|
||||
logger.warn({ err, url }, 'Failed to fetch Kimi usage');
|
||||
return cachedData; // Return stale cache on failure
|
||||
}
|
||||
}
|
||||
|
||||
// ── UsageRow builder ─────────────────────────────────────────────
|
||||
|
||||
function formatMembershipLabel(level?: string): string {
|
||||
if (!level) return '';
|
||||
// "LEVEL_INTERMEDIATE" → "mid", "LEVEL_PREMIUM" → "premium", etc.
|
||||
const cleaned = level.replace(/^LEVEL_/i, '').toLowerCase();
|
||||
const labelMap: Record<string, string> = {
|
||||
basic: 'basic',
|
||||
intermediate: 'mid',
|
||||
premium: 'premium',
|
||||
enterprise: 'ent',
|
||||
};
|
||||
return labelMap[cleaned] || cleaned;
|
||||
}
|
||||
|
||||
export function buildKimiUsageRows(data: KimiUsageData | null): UsageRow[] {
|
||||
if (!data) return [];
|
||||
|
||||
const memberLabel = formatMembershipLabel(data.membershipLevel);
|
||||
const name = memberLabel ? `Kimi ${memberLabel}` : 'Kimi';
|
||||
|
||||
return [
|
||||
{
|
||||
name,
|
||||
h5pct: data.fiveHour?.pct ?? -1,
|
||||
h5reset: data.fiveHour?.resetTime
|
||||
? formatResetRemaining(data.fiveHour.resetTime)
|
||||
: '',
|
||||
d7pct: data.weekly?.pct ?? -1,
|
||||
d7reset: data.weekly?.resetTime
|
||||
? formatResetRemaining(data.weekly.resetTime)
|
||||
: '',
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/** Force clear cached data (for testing). */
|
||||
export function resetKimiUsageCache(): void {
|
||||
cachedData = null;
|
||||
lastFetchAt = 0;
|
||||
}
|
||||
@@ -32,11 +32,6 @@ vi.mock('./config.js', () => ({
|
||||
effort: undefined,
|
||||
fallbackEnabled: true,
|
||||
})),
|
||||
getMoaConfig: vi.fn(() => ({
|
||||
enabled: false,
|
||||
referenceModels: [],
|
||||
aggregator: {},
|
||||
})),
|
||||
TIMEZONE: 'Asia/Seoul',
|
||||
}));
|
||||
|
||||
@@ -44,10 +39,6 @@ vi.mock('./arbiter-context.js', () => ({
|
||||
buildArbiterContextPrompt: vi.fn(() => ''),
|
||||
}));
|
||||
|
||||
vi.mock('./moa.js', () => ({
|
||||
runMoaArbiter: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('./platform-prompts.js', () => ({
|
||||
readArbiterPrompt: vi.fn(() => ''),
|
||||
}));
|
||||
|
||||
@@ -1,16 +1,12 @@
|
||||
import { AgentOutput } from './agent-runner.js';
|
||||
import { GroupQueue } from './group-queue.js';
|
||||
import type { Logger } from 'pino';
|
||||
import type { AgentTriggerReason } from './agent-error-detection.js';
|
||||
import { getMoaConfig } from './config.js';
|
||||
import { createPairedExecutionLifecycle } from './message-agent-executor-paired.js';
|
||||
import type { PairedTurnIdentity } from './paired-turn-identity.js';
|
||||
import { executeMessageAgentAttemptLifecycle } from './message-agent-executor-lifecycle.js';
|
||||
import { runMessageAgentAttempt } from './message-agent-executor-attempt-runner.js';
|
||||
import { handoffMessageAgentExecutionToCodex } from './message-agent-executor-handoff.js';
|
||||
import { prepareMessageAgentExecutionTarget } from './message-agent-executor-target.js';
|
||||
import { collectMoaReferences, formatMoaReferencesForPrompt } from './moa.js';
|
||||
import { readArbiterPrompt } from './platform-prompts.js';
|
||||
import { shouldRetryFreshSessionOnAgentFailure } from './session-recovery.js';
|
||||
import type { AgentType, PairedRoomRole, RegisteredGroup } from './types.js';
|
||||
import {
|
||||
@@ -51,44 +47,6 @@ function clearAppliedCompactRefreshAfterSuccess(args: {
|
||||
});
|
||||
}
|
||||
|
||||
async function enrichArbiterPromptWithMoa(args: {
|
||||
prompt: string;
|
||||
enabled: boolean;
|
||||
log: Pick<Logger, 'info' | 'warn'>;
|
||||
}): Promise<string> {
|
||||
const moaConfig = getMoaConfig();
|
||||
if (!args.enabled || !moaConfig.enabled) return args.prompt;
|
||||
args.log.info(
|
||||
{ models: moaConfig.referenceModels.map((m) => m.name) },
|
||||
'MoA: collecting reference opinions before arbiter',
|
||||
);
|
||||
const systemPrompt =
|
||||
readArbiterPrompt(process.cwd()) || 'You are an arbiter.';
|
||||
try {
|
||||
const references = await collectMoaReferences({
|
||||
config: moaConfig,
|
||||
systemPrompt,
|
||||
contextPrompt: args.prompt,
|
||||
});
|
||||
const moaSection = formatMoaReferencesForPrompt(references);
|
||||
if (!moaSection) return args.prompt;
|
||||
args.log.info(
|
||||
{
|
||||
successCount: references.filter((r) => !r.error).length,
|
||||
totalCount: references.length,
|
||||
},
|
||||
'MoA: injected reference opinions into arbiter prompt',
|
||||
);
|
||||
return args.prompt + '\n' + moaSection;
|
||||
} catch (err) {
|
||||
args.log.warn(
|
||||
{ err, models: moaConfig.referenceModels.map((m) => m.name) },
|
||||
'MoA: failed to collect reference opinions; continuing without enrichment',
|
||||
);
|
||||
return args.prompt;
|
||||
}
|
||||
}
|
||||
|
||||
export interface MessageAgentExecutorDeps {
|
||||
assistantName: string;
|
||||
queue: Pick<GroupQueue, 'registerProcess' | 'enqueueMessageCheck'> &
|
||||
@@ -140,7 +98,6 @@ export async function runAgentForGroup(
|
||||
effectiveServiceId,
|
||||
effectiveAgentType,
|
||||
sessionFolder,
|
||||
arbiterMode,
|
||||
effectiveGroup,
|
||||
isClaudeCodeAgent,
|
||||
forceFreshClaudeReviewerSession,
|
||||
@@ -160,14 +117,8 @@ export async function runAgentForGroup(
|
||||
clearRoleSdkSessions();
|
||||
}
|
||||
|
||||
const moaEnrichedPrompt = await enrichArbiterPromptWithMoa({
|
||||
prompt,
|
||||
enabled: arbiterMode && Boolean(pairedExecutionContext),
|
||||
log,
|
||||
});
|
||||
|
||||
const { effectivePrompt, compactRefresh } = buildPromptWithCompactRefresh({
|
||||
prompt: moaEnrichedPrompt,
|
||||
prompt,
|
||||
sessionFolder,
|
||||
sessionId: currentSessionId,
|
||||
role: activeRole,
|
||||
|
||||
@@ -40,11 +40,6 @@ vi.mock('./config.js', () => ({
|
||||
isClaudeService: vi.fn(() => true),
|
||||
isReviewService: vi.fn(() => false),
|
||||
isSessionCommandSenderAllowed: vi.fn(() => false),
|
||||
getMoaConfig: vi.fn(() => ({
|
||||
enabled: false,
|
||||
referenceModels: [],
|
||||
aggregator: {},
|
||||
})),
|
||||
TIMEZONE: 'Asia/Seoul',
|
||||
}));
|
||||
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { assertSafeMoaBaseUrl } from './moa.js';
|
||||
|
||||
describe('assertSafeMoaBaseUrl', () => {
|
||||
it('accepts public https endpoints', () => {
|
||||
expect(() =>
|
||||
assertSafeMoaBaseUrl('https://api.moonshot.cn/v1'),
|
||||
).not.toThrow();
|
||||
expect(() =>
|
||||
assertSafeMoaBaseUrl('https://open.bigmodel.cn/api/paas/v4'),
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it('rejects non-http(s) schemes', () => {
|
||||
expect(() => assertSafeMoaBaseUrl('file:///etc/passwd')).toThrow(
|
||||
/http\(s\)/,
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects loopback and localhost', () => {
|
||||
expect(() => assertSafeMoaBaseUrl('http://127.0.0.1:8080')).toThrow(
|
||||
/not allowed/,
|
||||
);
|
||||
expect(() => assertSafeMoaBaseUrl('http://localhost/v1')).toThrow(
|
||||
/not allowed/,
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects cloud metadata and private ranges', () => {
|
||||
expect(() => assertSafeMoaBaseUrl('http://169.254.169.254/latest')).toThrow(
|
||||
/not allowed/,
|
||||
);
|
||||
expect(() => assertSafeMoaBaseUrl('http://10.0.0.5/v1')).toThrow(
|
||||
/not allowed/,
|
||||
);
|
||||
expect(() => assertSafeMoaBaseUrl('http://192.168.1.1/v1')).toThrow(
|
||||
/not allowed/,
|
||||
);
|
||||
expect(() => assertSafeMoaBaseUrl('http://100.101.210.95/v1')).toThrow(
|
||||
/not allowed/,
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects malformed URLs', () => {
|
||||
expect(() => assertSafeMoaBaseUrl('not-a-url')).toThrow(/Invalid/);
|
||||
});
|
||||
});
|
||||
297
src/moa.ts
297
src/moa.ts
@@ -1,297 +0,0 @@
|
||||
/**
|
||||
* Mixture of Agents (MoA) — lightweight reference opinions.
|
||||
*
|
||||
* Queries external API models (Kimi, GLM, etc.) in parallel for their
|
||||
* opinions on the deadlock. These opinions are then injected into the
|
||||
* SDK-based arbiter's prompt so it can aggregate all perspectives.
|
||||
*
|
||||
* No extra SDK processes. The existing arbiter (Claude/Codex subscription)
|
||||
* naturally becomes the aggregator.
|
||||
*/
|
||||
import { logger } from './logger.js';
|
||||
|
||||
export interface MoaModelConfig {
|
||||
name: string;
|
||||
model: string;
|
||||
baseUrl: string;
|
||||
apiKey: string;
|
||||
/** API format: 'openai' (default) or 'anthropic' (Messages API). */
|
||||
apiFormat: 'openai' | 'anthropic';
|
||||
}
|
||||
|
||||
export interface MoaConfig {
|
||||
enabled: boolean;
|
||||
referenceModels: MoaModelConfig[];
|
||||
}
|
||||
|
||||
export interface MoaReferenceResult {
|
||||
model: string;
|
||||
response: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface MoaReferenceStatus {
|
||||
model: string;
|
||||
checkedAt: string;
|
||||
ok: boolean;
|
||||
error: string | null;
|
||||
responseLength?: number;
|
||||
}
|
||||
|
||||
const referenceStatuses = new Map<string, MoaReferenceStatus>();
|
||||
|
||||
function normalizeError(err: unknown): string {
|
||||
return err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reject MoA base URLs that point at loopback / private / link-local hosts.
|
||||
*
|
||||
* MoA reference models are external SaaS endpoints (Kimi, GLM, ...). Allowing
|
||||
* an internal host lets a compromised or misconfigured settings write turn the
|
||||
* server-side MoA fetch into an SSRF probe (e.g. cloud metadata at
|
||||
* 169.254.169.254). Only http(s) to a non-private host is permitted.
|
||||
*/
|
||||
export function assertSafeMoaBaseUrl(baseUrl: string): URL {
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(baseUrl);
|
||||
} catch {
|
||||
throw new Error(`Invalid MoA base URL: ${baseUrl}`);
|
||||
}
|
||||
if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
|
||||
throw new Error(`MoA base URL must use http(s): ${baseUrl}`);
|
||||
}
|
||||
if (isPrivateOrLocalHost(parsed.hostname)) {
|
||||
throw new Error(
|
||||
`MoA base URL host is not allowed (loopback/private/link-local): ${parsed.hostname}`,
|
||||
);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function isPrivateOrLocalHost(hostname: string): boolean {
|
||||
const host = hostname.replace(/^\[|\]$/g, '').toLowerCase();
|
||||
if (
|
||||
host === 'localhost' ||
|
||||
host.endsWith('.localhost') ||
|
||||
host.endsWith('.internal') ||
|
||||
host.endsWith('.local')
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
// IPv6 loopback / link-local / unique-local
|
||||
if (host === '::1' || host === '::') return true;
|
||||
if (
|
||||
host.startsWith('fe80:') ||
|
||||
host.startsWith('fc') ||
|
||||
host.startsWith('fd')
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
const ipv4 = host.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
|
||||
if (ipv4) {
|
||||
const [a, b] = [Number(ipv4[1]), Number(ipv4[2])];
|
||||
if (a === 127 || a === 0 || a === 10) return true; // loopback / this-host / private
|
||||
if (a === 169 && b === 254) return true; // link-local incl. cloud metadata
|
||||
if (a === 172 && b >= 16 && b <= 31) return true; // private
|
||||
if (a === 192 && b === 168) return true; // private
|
||||
if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT / tailnet
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function recordReferenceStatus(
|
||||
status: Omit<MoaReferenceStatus, 'checkedAt'>,
|
||||
): MoaReferenceStatus {
|
||||
const next: MoaReferenceStatus = {
|
||||
...status,
|
||||
checkedAt: new Date().toISOString(),
|
||||
};
|
||||
referenceStatuses.set(status.model, next);
|
||||
return next;
|
||||
}
|
||||
|
||||
export function getMoaReferenceStatuses(): MoaReferenceStatus[] {
|
||||
return [...referenceStatuses.values()];
|
||||
}
|
||||
|
||||
async function queryModel(
|
||||
model: MoaModelConfig,
|
||||
systemPrompt: string,
|
||||
userPrompt: string,
|
||||
timeoutMs = 60_000,
|
||||
): Promise<string> {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
||||
|
||||
try {
|
||||
assertSafeMoaBaseUrl(model.baseUrl);
|
||||
const base = model.baseUrl.replace(/\/+$/, '');
|
||||
const isAnthropic = model.apiFormat === 'anthropic';
|
||||
|
||||
const url = isAnthropic
|
||||
? `${base}/v1/messages`
|
||||
: `${base}/chat/completions`;
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
if (isAnthropic) {
|
||||
headers['x-api-key'] = model.apiKey;
|
||||
headers['anthropic-version'] = '2023-06-01';
|
||||
} else {
|
||||
headers['Authorization'] = `Bearer ${model.apiKey}`;
|
||||
}
|
||||
|
||||
const body = isAnthropic
|
||||
? {
|
||||
model: model.model,
|
||||
system: systemPrompt,
|
||||
max_tokens: 2048,
|
||||
messages: [{ role: 'user', content: userPrompt }],
|
||||
}
|
||||
: {
|
||||
model: model.model,
|
||||
max_tokens: 2048,
|
||||
messages: [
|
||||
{ role: 'system', content: systemPrompt },
|
||||
{ role: 'user', content: userPrompt },
|
||||
],
|
||||
};
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify(body),
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const respBody = await response.text().catch(() => '');
|
||||
throw new Error(
|
||||
`${response.status} ${response.statusText}: ${respBody.slice(0, 200)}`,
|
||||
);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
// Parse response based on format
|
||||
let content: string | undefined;
|
||||
if (isAnthropic) {
|
||||
const blocks = (data as { content?: { type: string; text: string }[] })
|
||||
.content;
|
||||
content = blocks
|
||||
?.filter((b: { type: string }) => b.type === 'text')
|
||||
.map((b: { text: string }) => b.text)
|
||||
.join('');
|
||||
} else {
|
||||
content = (data as { choices?: { message?: { content?: string } }[] })
|
||||
.choices?.[0]?.message?.content;
|
||||
}
|
||||
|
||||
if (!content) throw new Error('Empty response from model');
|
||||
return content;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Query all reference models in parallel and return their opinions.
|
||||
* These are injected into the SDK arbiter's prompt — the arbiter
|
||||
* aggregates them into a final verdict.
|
||||
*/
|
||||
export async function collectMoaReferences(args: {
|
||||
config: MoaConfig;
|
||||
systemPrompt: string;
|
||||
contextPrompt: string;
|
||||
}): Promise<MoaReferenceResult[]> {
|
||||
const { config, systemPrompt, contextPrompt } = args;
|
||||
|
||||
logger.info(
|
||||
{
|
||||
models: config.referenceModels.map((m) => m.name),
|
||||
},
|
||||
'MoA: querying reference models for opinions',
|
||||
);
|
||||
|
||||
const results = await Promise.allSettled(
|
||||
config.referenceModels.map((model) =>
|
||||
queryModel(model, systemPrompt, contextPrompt),
|
||||
),
|
||||
);
|
||||
|
||||
return results.map((result, i) => {
|
||||
const model = config.referenceModels[i].name;
|
||||
if (result.status === 'fulfilled') {
|
||||
recordReferenceStatus({
|
||||
model,
|
||||
ok: true,
|
||||
error: null,
|
||||
responseLength: result.value.length,
|
||||
});
|
||||
logger.info(
|
||||
{ model, responseLen: result.value.length },
|
||||
'MoA: reference model responded',
|
||||
);
|
||||
return { model, response: result.value };
|
||||
}
|
||||
const error = normalizeError(result.reason);
|
||||
recordReferenceStatus({ model, ok: false, error });
|
||||
logger.warn({ model, error }, 'MoA: reference model failed');
|
||||
return { model, response: '', error };
|
||||
});
|
||||
}
|
||||
|
||||
export async function probeMoaReferenceModel(
|
||||
model: MoaModelConfig,
|
||||
): Promise<MoaReferenceStatus> {
|
||||
try {
|
||||
const response = await queryModel(
|
||||
model,
|
||||
'You are a configuration health check. Reply with a short plain-text OK.',
|
||||
'Reply exactly: OK',
|
||||
20_000,
|
||||
);
|
||||
return recordReferenceStatus({
|
||||
model: model.name,
|
||||
ok: true,
|
||||
error: null,
|
||||
responseLength: response.length,
|
||||
});
|
||||
} catch (err) {
|
||||
return recordReferenceStatus({
|
||||
model: model.name,
|
||||
ok: false,
|
||||
error: normalizeError(err),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Format reference opinions into a section that gets appended
|
||||
* to the arbiter's prompt.
|
||||
*/
|
||||
export function formatMoaReferencesForPrompt(
|
||||
references: MoaReferenceResult[],
|
||||
): string | null {
|
||||
const successful = references.filter((r) => !r.error && r.response);
|
||||
if (successful.length === 0) return null;
|
||||
|
||||
const opinions = successful
|
||||
.map((r) => `### ${r.model}:\n${r.response}`)
|
||||
.join('\n\n---\n\n');
|
||||
|
||||
return [
|
||||
'',
|
||||
`<moa-references count="${successful.length}">`,
|
||||
`The following ${successful.length} independent AI models have also reviewed this deadlock:`,
|
||||
'',
|
||||
opinions,
|
||||
'',
|
||||
'Consider these perspectives alongside the conversation. Where they agree, that strengthens the case.',
|
||||
'Where they disagree, weigh the evidence. Your verdict is final.',
|
||||
'</moa-references>',
|
||||
].join('\n');
|
||||
}
|
||||
@@ -169,7 +169,7 @@ describe('renderUsageTable', () => {
|
||||
});
|
||||
|
||||
describe('buildWebUsageRowsForSnapshot', () => {
|
||||
it('keeps real Claude and Kimi rows ahead of Codex rows for web snapshots', () => {
|
||||
it('keeps real Claude rows ahead of Codex rows for snapshots', () => {
|
||||
const rows = buildWebUsageRowsForSnapshot({
|
||||
serviceAgentType: 'claude-code',
|
||||
claudeAccounts: [
|
||||
@@ -206,10 +206,6 @@ describe('buildWebUsageRowsForSnapshot', () => {
|
||||
},
|
||||
},
|
||||
],
|
||||
kimiUsage: {
|
||||
fiveHour: { pct: 18, resetTime: '2026-04-26T12:00:00.000Z' },
|
||||
weekly: { pct: 29, resetTime: '2026-04-27T12:00:00.000Z' },
|
||||
},
|
||||
codexRows: [
|
||||
{
|
||||
name: 'Codex1',
|
||||
@@ -224,11 +220,10 @@ describe('buildWebUsageRowsForSnapshot', () => {
|
||||
const names = rows.map((row) => row.name);
|
||||
expect(names[0]).toMatch(/^Claude1/);
|
||||
expect(names[1]).toMatch(/^Claude2/);
|
||||
expect(names[2]).toMatch(/^Kimi/);
|
||||
expect(names[3]).toBe('Codex1');
|
||||
expect(names[2]).toBe('Codex1');
|
||||
});
|
||||
|
||||
it('does not invent Claude or Kimi rows for codex-only services', () => {
|
||||
it('does not invent Claude rows for codex-only services', () => {
|
||||
const rows = buildWebUsageRowsForSnapshot({
|
||||
serviceAgentType: 'codex',
|
||||
claudeAccounts: [
|
||||
@@ -240,10 +235,6 @@ describe('buildWebUsageRowsForSnapshot', () => {
|
||||
usage: null,
|
||||
},
|
||||
],
|
||||
kimiUsage: {
|
||||
fiveHour: { pct: 18, resetTime: '2026-04-26T12:00:00.000Z' },
|
||||
weekly: { pct: 29, resetTime: '2026-04-27T12:00:00.000Z' },
|
||||
},
|
||||
codexRows: [
|
||||
{
|
||||
name: 'Codex1',
|
||||
|
||||
@@ -15,13 +15,7 @@ import {
|
||||
STATUS_SHOW_ROOMS,
|
||||
USAGE_DASHBOARD_ENABLED,
|
||||
CODEX_WARMUP_CONFIG,
|
||||
getMoaConfig,
|
||||
} from './config.js';
|
||||
import {
|
||||
fetchKimiUsage,
|
||||
buildKimiUsageRows,
|
||||
type KimiUsageData,
|
||||
} from './kimi-usage.js';
|
||||
import { getGlobalFailoverInfo } from './service-routing.js';
|
||||
import {
|
||||
fetchAllClaudeUsage,
|
||||
@@ -109,7 +103,6 @@ const DASHBOARD_DUPLICATE_CLEANUP_POLL_MS = 300_000;
|
||||
let statusMessageId: string | null = null;
|
||||
let cachedUsageContent = '';
|
||||
let cachedClaudeAccounts: ClaudeAccountUsage[] = [];
|
||||
let cachedKimiUsage: KimiUsageData | null = null;
|
||||
let usageUpdateInProgress = false;
|
||||
let channelMetaCache = new Map<string, ChannelMeta>();
|
||||
let channelMetaLastRefresh = 0;
|
||||
@@ -142,7 +135,7 @@ export function requestImmediateStatusUpdate(): void {
|
||||
let cachedCodexUsageRows: UsageRow[] = [];
|
||||
/** Codex service only: ISO timestamp of last successful usage fetch. */
|
||||
let codexUsageFetchedAt: string | null = null;
|
||||
/** Renderer service only: ISO timestamp of last successful Claude/Kimi usage render. */
|
||||
/** Renderer service only: ISO timestamp of last successful Claude usage render. */
|
||||
let rendererUsageFetchedAt: string | null = null;
|
||||
|
||||
export interface WatcherTaskSummary {
|
||||
@@ -279,14 +272,12 @@ export function formatRoomName(
|
||||
export function buildWebUsageRowsForSnapshot(args: {
|
||||
serviceAgentType: AgentType;
|
||||
claudeAccounts: ClaudeAccountUsage[];
|
||||
kimiUsage: KimiUsageData | null;
|
||||
codexRows: UsageRow[];
|
||||
}): UsageRow[] {
|
||||
const rows: UsageRow[] = [];
|
||||
|
||||
if (args.serviceAgentType === 'claude-code') {
|
||||
rows.push(...buildClaudeUsageRows(args.claudeAccounts));
|
||||
rows.push(...buildKimiUsageRows(args.kimiUsage));
|
||||
}
|
||||
|
||||
rows.push(...args.codexRows);
|
||||
@@ -300,7 +291,6 @@ function buildUsageSnapshotRows(opts: UnifiedDashboardOptions): {
|
||||
const rows = buildWebUsageRowsForSnapshot({
|
||||
serviceAgentType: opts.serviceAgentType,
|
||||
claudeAccounts: cachedClaudeAccounts,
|
||||
kimiUsage: cachedKimiUsage,
|
||||
codexRows: cachedCodexUsageRows,
|
||||
});
|
||||
|
||||
@@ -625,13 +615,6 @@ async function buildUsageContent(): Promise<string> {
|
||||
}
|
||||
}
|
||||
|
||||
// Kimi usage
|
||||
try {
|
||||
cachedKimiUsage = await fetchKimiUsage();
|
||||
} catch (err) {
|
||||
logger.warn({ err }, 'Failed to fetch Kimi usage for dashboard');
|
||||
}
|
||||
|
||||
const lines: string[] = ['📊 *사용량*'];
|
||||
const bar = (pct: number) => {
|
||||
const filled = Math.max(0, Math.min(5, Math.round(pct / 20)));
|
||||
@@ -663,10 +646,6 @@ async function buildUsageContent(): Promise<string> {
|
||||
);
|
||||
}
|
||||
|
||||
// Group 3: Kimi coding plan
|
||||
const kimiRows = buildKimiUsageRows(cachedKimiUsage);
|
||||
claudeBotRows.push(...kimiRows);
|
||||
|
||||
lines.push(...renderUsageTable(claudeBotRows, codexBotRows));
|
||||
|
||||
lines.push('');
|
||||
@@ -806,15 +785,6 @@ function buildModelConfigSection(): string {
|
||||
}
|
||||
}
|
||||
|
||||
// MoA status
|
||||
const moaConfig = getMoaConfig();
|
||||
if (moaConfig.enabled) {
|
||||
const refs = moaConfig.referenceModels
|
||||
.map((m) => `${m.name} \`${m.model}\``)
|
||||
.join(', ');
|
||||
lines.push(` **MoA** — ${refs}`);
|
||||
}
|
||||
|
||||
if (failover.active) {
|
||||
lines.push(` ⚠️ **Failover 활성** — ${failover.reason || '알 수 없음'}`);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user