tr-plugin-meta-harness 0.3.0 → 0.5.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/DESIGN.md +86 -0
- package/README.md +257 -11
- package/capability/BRICK.md +1 -1
- package/capability/index.mjs +154 -13
- package/cli.mjs +426 -41
- package/package.json +15 -3
- package/plugin.json +1457 -119
- package/skills/meta-harness/SKILL.md +63 -25
- package/src/adoption.mjs +102 -0
- package/src/agent-user.mjs +194 -0
- package/src/alerts.mjs +220 -14
- package/src/cascade.mjs +185 -0
- package/src/chat.mjs +80 -0
- package/src/codex-models.mjs +54 -0
- package/src/compat-harness.mjs +114 -0
- package/src/control.mjs +145 -0
- package/src/coordinator.mjs +267 -358
- package/src/dispatch-request.mjs +76 -0
- package/src/dispatch.mjs +119 -0
- package/src/documentation-authority.mjs +57 -0
- package/src/documentation.mjs +120 -32
- package/src/executor.mjs +101 -22
- package/src/gate-adapters/agy.mjs +155 -0
- package/src/gate-adapters/claude.mjs +303 -0
- package/src/gate-adapters/cline.mjs +111 -0
- package/src/gate-adapters/codex.mjs +164 -0
- package/src/gate-adapters/cursor.mjs +164 -0
- package/src/gate-adapters/devin.mjs +116 -0
- package/src/gate-adapters/dsh.mjs +284 -0
- package/src/gate-adapters/grok.mjs +112 -0
- package/src/gate-adapters/hermes.mjs +217 -0
- package/src/gate-adapters/hook-files.mjs +156 -0
- package/src/gate-adapters/index.mjs +131 -0
- package/src/gate-adapters/openclaw-plugin/gate-client.js +205 -0
- package/src/gate-adapters/openclaw-plugin/index.js +25 -0
- package/src/gate-adapters/openclaw-plugin/openclaw.plugin.json +9 -0
- package/src/gate-adapters/openclaw-plugin/package.json +15 -0
- package/src/gate-adapters/openclaw.mjs +288 -0
- package/src/gate-adapters/pi.mjs +146 -0
- package/src/gate.mjs +18 -0
- package/src/harness-updates.mjs +170 -0
- package/src/included-usage.mjs +344 -0
- package/src/jobs.mjs +135 -0
- package/src/json-reply.mjs +22 -0
- package/src/learner.mjs +97 -67
- package/src/maintenance.mjs +18 -0
- package/src/mcp-server.mjs +228 -0
- package/src/model-catalog.mjs +195 -0
- package/src/model-selection.mjs +67 -0
- package/src/paths.mjs +23 -0
- package/src/pool.mjs +69 -0
- package/src/process-manager.mjs +246 -0
- package/src/process-worker.mjs +18 -0
- package/src/reasoning.mjs +231 -0
- package/src/remote-operation.mjs +76 -0
- package/src/review.mjs +241 -0
- package/src/reviews.mjs +25 -0
- package/src/router-benchmark-corpus.mjs +16 -0
- package/src/router-benchmark.mjs +208 -0
- package/src/router.mjs +265 -346
- package/src/runtime.mjs +30 -8
- package/src/session/claude.mjs +358 -0
- package/src/session/codex.mjs +501 -0
- package/src/session/result.mjs +90 -0
- package/src/session/resume.mjs +393 -0
- package/src/session/run.mjs +258 -0
- package/src/session-jobs.mjs +77 -0
- package/src/setup.mjs +6 -3
- package/src/ssss-store.mjs +20 -0
- package/src/telemetry.mjs +267 -0
- package/src/termination.mjs +28 -0
- package/src/threads.mjs +150 -0
- package/src/usage-queue.mjs +137 -0
- package/src/verify-ssss.mjs +102 -0
- package/src/worker.mjs +955 -84
- package/src/worktree.mjs +244 -0
- package/ui/chunks/adapter-docs-freshness.md +16 -0
- package/ui/chunks/chat-handoff.md +26 -0
- package/ui/chunks/fleet-maintenance.md +21 -0
- package/ui/chunks/harness-inventory.md +21 -0
- package/ui/chunks/included-access.md +18 -0
- package/ui/chunks/included-usage-verification.md +15 -0
- package/ui/chunks/independent-review.md +17 -0
- package/ui/chunks/managed-execution.md +20 -0
- package/ui/chunks/official-documentation.md +18 -0
- package/ui/chunks/quota-recovery.md +21 -0
- package/ui/chunks/review-routing-decision.md +16 -0
- package/ui/chunks/route-work.md +18 -0
- package/ui/chunks/routing-evidence.md +18 -0
- package/ui/chunks/run-ledger.md +18 -0
- package/ui/chunks/session-controls.md +16 -0
- package/ui/home.js +198 -0
- package/ui/DESIGN.md +0 -32
- package/ui/card.js +0 -845
package/src/learner.mjs
CHANGED
|
@@ -1,90 +1,120 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
* and proposes friction-reducing rule/memory proposals.
|
|
2
|
+
* Execution receipts and the learning loop.
|
|
3
|
+
* Receipts are an append-only SSSS ledger. Scorecards, quota walls and proposals fold from it.
|
|
5
4
|
*/
|
|
6
|
-
|
|
7
|
-
import fs from 'node:fs';
|
|
8
|
-
import path from 'node:path';
|
|
9
|
-
import os from 'node:os';
|
|
10
5
|
import { computeEmpiricalScorecard } from '../capability/index.mjs';
|
|
6
|
+
import { receiptsFile } from './paths.mjs';
|
|
7
|
+
import { classifyFailure } from './worker.mjs';
|
|
11
8
|
|
|
12
|
-
function
|
|
13
|
-
const
|
|
14
|
-
|
|
15
|
-
fs.mkdirSync(baseDir, { recursive: true });
|
|
16
|
-
return path.join(baseDir, 'meta-harness-runs.json');
|
|
9
|
+
async function store() {
|
|
10
|
+
const { PluginStateStore } = await import('./ssss-store.mjs');
|
|
11
|
+
return new PluginStateStore(receiptsFile(), 'meta-harness');
|
|
17
12
|
}
|
|
13
|
+
/** Classify old failures with today's knowledge, so an early misreading cannot keep penalizing a harness. */
|
|
14
|
+
export const readReceipts = async () => liveReceipts((await store()).read([])).map(run => (run.failureKind === 'agent' && run.error ? { ...run, ...withoutAgent(classifyFailure(run.error, new Date(run.timestamp)), run) } : run));
|
|
15
|
+
const withoutAgent = (found, run) => (found.failureKind === 'agent' ? {} : { failureKind: found.failureKind, resetsAt: run.resetsAt || found.resetsAt || null });
|
|
18
16
|
|
|
19
|
-
/**
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
let entries = [];
|
|
25
|
-
if (fs.existsSync(ledgerPath)) {
|
|
26
|
-
try {
|
|
27
|
-
entries = JSON.parse(fs.readFileSync(ledgerPath, 'utf8'));
|
|
28
|
-
} catch {
|
|
29
|
-
entries = [];
|
|
30
|
-
}
|
|
31
|
-
}
|
|
17
|
+
/** The ledger is append-only, so a wrong row is voided by a later entry, never rewritten. Both stay on record. */
|
|
18
|
+
function liveReceipts(rows) {
|
|
19
|
+
const voided = new Set(rows.flatMap(row => row.voids || []));
|
|
20
|
+
return rows.filter(row => !row.voids && !voided.has(row.id));
|
|
21
|
+
}
|
|
32
22
|
|
|
23
|
+
export async function voidReceipts({ ids = [], reason = '' } = {}) {
|
|
24
|
+
if (!ids.length) throw new Error('--void needs at least one receipt id');
|
|
25
|
+
if (!String(reason).trim()) throw new Error('--void needs a --reason: a voided receipt stays on record with why');
|
|
26
|
+
const ledger = await store();
|
|
27
|
+
const live = new Set(liveReceipts(ledger.read([])).map(row => row.id));
|
|
28
|
+
const unknown = ids.filter(id => !live.has(id));
|
|
29
|
+
if (unknown.length) throw new Error(`No live receipt with id: ${unknown.join(', ')}`);
|
|
30
|
+
const entry = { id: `void-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`, timestamp: new Date().toISOString(), voids: ids, reason: String(reason) };
|
|
31
|
+
ledger.append(entry);
|
|
32
|
+
return { ok: true, voided: ids.length, id: entry.id, reason: entry.reason };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export async function recordRunReceipt(receipt = {}) {
|
|
36
|
+
if (!receipt.harness) throw new Error('A run receipt must name its harness');
|
|
33
37
|
const entry = {
|
|
34
|
-
id: receipt.id || `run-${Date.now()}`,
|
|
38
|
+
id: receipt.id || `run-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
|
|
35
39
|
timestamp: new Date().toISOString(),
|
|
36
|
-
harness: receipt.harness
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
+
harness: receipt.harness,
|
|
41
|
+
model: receipt.model ?? null,
|
|
42
|
+
exitCode: receipt.exitCode ?? null,
|
|
43
|
+
finishedReason: receipt.finishedReason ?? null,
|
|
44
|
+
role: receipt.role || null,
|
|
45
|
+
node: receipt.node || 'local',
|
|
46
|
+
task: String(receipt.task || '').slice(0, 300),
|
|
47
|
+
complexityScore: receipt.complexityScore ?? null,
|
|
48
|
+
success: receipt.success === true,
|
|
40
49
|
durationMs: receipt.durationMs || 0,
|
|
50
|
+
failureKind: receipt.failureKind || null,
|
|
51
|
+
...(receipt.billingMode ? { billingMode: receipt.billingMode } : {}),
|
|
52
|
+
...(Array.isArray(receipt.tools) && receipt.tools.length ? { tools: receipt.tools.map(({ tool, status, exitCode }) =>
|
|
53
|
+
({ tool, status, ...(Number.isInteger(exitCode) ? { exitCode } : {}) })) } : {}),
|
|
54
|
+
error: receipt.error ? String(receipt.error).slice(0, 500) : null,
|
|
55
|
+
resetsAt: receipt.resetsAt || null,
|
|
56
|
+
gate: receipt.gate || null,
|
|
41
57
|
escalatedFrom: receipt.escalatedFrom || null,
|
|
42
|
-
failures: receipt.failures || {}
|
|
43
58
|
};
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
// Keep last 1,000 runs
|
|
47
|
-
if (entries.length > 1000) {
|
|
48
|
-
entries = entries.slice(-1000);
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
fs.writeFileSync(ledgerPath, JSON.stringify(entries, null, 2), 'utf8');
|
|
52
|
-
return { ok: true, recorded: entry.id, totalRuns: entries.length };
|
|
59
|
+
(await store()).append(entry);
|
|
60
|
+
return entry;
|
|
53
61
|
}
|
|
54
62
|
|
|
55
63
|
/**
|
|
56
|
-
*
|
|
64
|
+
* Receipts that count under the included usage policy: included runs, plus quota refusals recorded before
|
|
65
|
+
* refusals carried a billingMode. Those legacy walls expire at their reset, so nothing stale lingers.
|
|
57
66
|
*/
|
|
58
|
-
export
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
+
export const includedBillingReceipts = (entries = []) =>
|
|
68
|
+
entries.filter(run => run.billingMode === 'included' || (!run.billingMode && run.failureKind === 'quota'));
|
|
69
|
+
|
|
70
|
+
/** A harness is walled from its last quota failure until the reported reset, or until a later success proves it clear. */
|
|
71
|
+
export function activeQuotaWalls(entries = [], now = Date.now(), unknownResetMs = 60 * 60 * 1000) {
|
|
72
|
+
const latest = new Map();
|
|
73
|
+
for (const run of entries) {
|
|
74
|
+
if (run.success || run.failureKind === 'quota') latest.set(run.harness, run);
|
|
75
|
+
}
|
|
76
|
+
const walls = {};
|
|
77
|
+
for (const [harness, run] of latest) {
|
|
78
|
+
if (run.success) continue;
|
|
79
|
+
const observed = Date.parse(run.timestamp);
|
|
80
|
+
const until = run.resetsAt ? Date.parse(run.resetsAt) : observed + unknownResetMs;
|
|
81
|
+
if (until > now) walls[harness] = { until: new Date(until).toISOString(), resetReported: Boolean(run.resetsAt), observedAt: run.timestamp, message: run.error };
|
|
67
82
|
}
|
|
83
|
+
return walls;
|
|
84
|
+
}
|
|
68
85
|
|
|
69
|
-
|
|
86
|
+
export function proposalsFrom(scorecard, entries = []) {
|
|
70
87
|
const proposals = [];
|
|
71
|
-
|
|
72
|
-
// Identify harnesses with elevated failure rates (>25%)
|
|
73
88
|
for (const [harness, stats] of Object.entries(scorecard)) {
|
|
74
|
-
if (stats.total >= 3 && stats.passRate < 75) {
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
recommendation: `Auto-escalate ${harness} to frontier model or apply strict preflight gate.`
|
|
80
|
-
});
|
|
81
|
-
}
|
|
89
|
+
if (stats.total >= 3 && stats.passRate < 75) proposals.push({
|
|
90
|
+
id: `meta-harness-low-pass-${harness}`, targetHarness: harness,
|
|
91
|
+
reason: `${harness} passed ${stats.passRate}% of ${stats.total} attributable runs.`,
|
|
92
|
+
recommendation: `Route complex work away from ${harness}, or require a gate before accepting its output.`,
|
|
93
|
+
});
|
|
82
94
|
}
|
|
95
|
+
const gateFailures = new Map();
|
|
96
|
+
for (const run of entries) if (run.failureKind === 'gate') gateFailures.set(run.harness, (gateFailures.get(run.harness) || 0) + 1);
|
|
97
|
+
for (const [harness, count] of gateFailures) if (count >= 3) proposals.push({
|
|
98
|
+
id: `meta-harness-gate-failures-${harness}`, targetHarness: harness,
|
|
99
|
+
reason: `${harness} output failed quality gates ${count} times.`,
|
|
100
|
+
recommendation: `Review recent ${harness} branches for a recurring defect and record the rule that prevents it.`,
|
|
101
|
+
});
|
|
102
|
+
return proposals;
|
|
103
|
+
}
|
|
83
104
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
};
|
|
105
|
+
/** A harness whose last run failed for a missing login or key stays out of the pool for an hour, then gets another chance. */
|
|
106
|
+
export function activeCredentialBlocks(entries = [], now = Date.now(), holdMs = 60 * 60 * 1000) {
|
|
107
|
+
const latest = new Map();
|
|
108
|
+
for (const run of entries) if (run.success || run.failureKind === 'auth') latest.set(run.harness, run);
|
|
109
|
+
const blocks = {};
|
|
110
|
+
for (const [harness, run] of latest) if (!run.success && Date.parse(run.timestamp) + holdMs > now) blocks[harness] = { observedAt: run.timestamp, message: run.error };
|
|
111
|
+
return blocks;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Read the same receipts the router uses. Proposals stay in this report. */
|
|
115
|
+
export async function learnFromHistory() {
|
|
116
|
+
const entries = await readReceipts();
|
|
117
|
+
const scorecard = computeEmpiricalScorecard(entries);
|
|
118
|
+
const proposals = proposalsFrom(scorecard, entries);
|
|
119
|
+
return { ok: true, totalHistoryRuns: entries.length, scorecard, walls: activeQuotaWalls(entries), credentialBlocks: activeCredentialBlocks(entries), proposals };
|
|
90
120
|
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** Run each maintenance owner even when another owner fails. The daemon records the result. */
|
|
2
|
+
import { setupIntegrations } from './setup.mjs';
|
|
3
|
+
import { runDocumentationCommand } from './documentation-authority.mjs';
|
|
4
|
+
|
|
5
|
+
export async function maintainIntegrations(options = {}, owners = {}) {
|
|
6
|
+
const steps = {
|
|
7
|
+
setup: owners.setup || (() => setupIntegrations()),
|
|
8
|
+
gates: owners.gates || (async () => (await import('./gate-adapters/index.mjs')).installAll()),
|
|
9
|
+
docs: owners.docs || (() => runDocumentationCommand('maintenance', options)),
|
|
10
|
+
jobs: owners.jobs || (async () => (await import('./jobs.mjs')).pruneJobs()),
|
|
11
|
+
};
|
|
12
|
+
const result = {};
|
|
13
|
+
for (const [name, execute] of Object.entries(steps)) {
|
|
14
|
+
try { result[name] = await execute(); }
|
|
15
|
+
catch (error) { result[name] = { ok: false, error: error.message }; }
|
|
16
|
+
}
|
|
17
|
+
return { ...result, ok: Object.values(result).every(step => step?.ok === true) };
|
|
18
|
+
}
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP stdio (JSONL), with the initialize lifecycle used by Claude and Codex.
|
|
3
|
+
* Protocol: https://modelcontextprotocol.io/specification/2025-11-25
|
|
4
|
+
* Approval result: https://code.claude.com/docs/en/agent-sdk/user-input
|
|
5
|
+
*/
|
|
6
|
+
import { createInterface } from 'node:readline';
|
|
7
|
+
import { execFile } from 'node:child_process';
|
|
8
|
+
import { promisify } from 'node:util';
|
|
9
|
+
import { randomUUID } from 'node:crypto';
|
|
10
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
11
|
+
import { brainDir } from './paths.mjs';
|
|
12
|
+
import { appendEvent, jobPaths, tailInbox } from './control.mjs';
|
|
13
|
+
|
|
14
|
+
const execute = promisify(execFile);
|
|
15
|
+
export const QUESTION_TIMEOUT_MS = 10 * 60_000;
|
|
16
|
+
export const NO_ANSWER = 'No answer; proceed on your best judgment';
|
|
17
|
+
const versions = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
|
|
18
|
+
const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
19
|
+
const textResult = text => ({ content: [{ type: 'text', text }] });
|
|
20
|
+
const fault = (code, message) => Object.assign(new Error(message), { code });
|
|
21
|
+
|
|
22
|
+
export const MCP_TOOLS = [
|
|
23
|
+
{ name: 'ask', description: 'Ask the operator questions and wait for a reply.', inputSchema: {
|
|
24
|
+
type: 'object', properties: { questions: { type: 'array', minItems: 1, items: { oneOf: [{ type: 'string', minLength: 1 }, { type: 'object' }] } } }, required: ['questions'], additionalProperties: false,
|
|
25
|
+
} },
|
|
26
|
+
{ name: 'approve', description: 'Answer a Claude Code permission prompt under the job approval policy.', inputSchema: {
|
|
27
|
+
type: 'object', properties: { tool_name: { type: 'string', minLength: 1 }, input: { type: 'object' }, tool_use_id: { type: 'string' } }, required: ['tool_name', 'input'],
|
|
28
|
+
} },
|
|
29
|
+
];
|
|
30
|
+
|
|
31
|
+
/** Return Claude's --mcp-config object and Codex's -c arguments. No shell parses these values. */
|
|
32
|
+
export function mcpConfigFor(job, options = {}) {
|
|
33
|
+
const id = jobPaths(job).id;
|
|
34
|
+
const command = process.execPath;
|
|
35
|
+
const args = [fileURLToPath(import.meta.url), '--approvals', options.approvalPolicy || 'auto',
|
|
36
|
+
'--question-timeout-ms', String(options.questionTimeoutMs ?? options.timeoutMs ?? QUESTION_TIMEOUT_MS)];
|
|
37
|
+
const env = { TR_METAHARNESS_JOB: id, TR_SECRETS_BRAIN: brainDir() };
|
|
38
|
+
if (process.env.TOTAL_RECALL_BIN) env.TOTAL_RECALL_BIN = process.env.TOTAL_RECALL_BIN;
|
|
39
|
+
const claude = { mcpServers: { metaharness: { command, args, env } } };
|
|
40
|
+
const tomlEnv = `{ ${Object.entries(env).map(([key, value]) => `${key} = ${JSON.stringify(value)}`).join(', ')} }`;
|
|
41
|
+
const codex = ['-c', `mcp_servers.metaharness.command=${JSON.stringify(command)}`,
|
|
42
|
+
'-c', `mcp_servers.metaharness.args=${JSON.stringify(args)}`, '-c', `mcp_servers.metaharness.env=${tomlEnv}`,
|
|
43
|
+
'-c', `mcp_servers.metaharness.tool_timeout_sec=${Math.ceil(Number(args.at(-1)) / 1000) + 60}`];
|
|
44
|
+
return { claude, codex, claudeArgs: ['--mcp-config', JSON.stringify(claude), '--permission-prompt-tool', 'mcp__metaharness__approve'], codexArgs: codex };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The decision owner returns a typed choice. Missing or failed decisions deny the call. */
|
|
48
|
+
async function decideApproval(request, { signal } = {}) {
|
|
49
|
+
const questions = { approval: { type: 'choice', instructions: 'Apply Total Recall rules to this tool request. Allow only if the request is authorized. Deny if authorization is unclear.',
|
|
50
|
+
criteria: { allow: 'Authorized by the operator and the applicable rules.', deny: 'Not authorized or prohibited by a rule.' } } };
|
|
51
|
+
const { stdout } = await execute(process.env.TOTAL_RECALL_BIN || 'total-recall',
|
|
52
|
+
['decision', 'run', '--state', JSON.stringify({ request }), '--questions', JSON.stringify(questions), '--json'],
|
|
53
|
+
{ encoding: 'utf8', timeout: 60_000, maxBuffer: 1024 * 1024, signal });
|
|
54
|
+
const record = JSON.parse(stdout);
|
|
55
|
+
if (record.ok === false) throw new Error(record.error || 'The decision owner failed.');
|
|
56
|
+
const answer = record.answers?.approval ?? record.decision?.answers?.approval ?? record.result?.approval;
|
|
57
|
+
const value = typeof answer === 'string' ? answer : answer?.choice;
|
|
58
|
+
if (!['allow', 'deny'].includes(value)) throw new Error('The decision owner returned no allow or deny answer.');
|
|
59
|
+
return { value, record };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Resolve all pending calls on close; no poll timer or child command outlives the server. */
|
|
63
|
+
export function createMcpTools({ job = process.env.TR_METAHARNESS_JOB, approvalPolicy = 'auto',
|
|
64
|
+
questionTimeoutMs = QUESTION_TIMEOUT_MS, timeoutMs, decisionFn = decideApproval, alertFn,
|
|
65
|
+
deferQuestions = process.env.TR_METAHARNESS_DEFER_QUESTIONS !== '0' } = {}) {
|
|
66
|
+
jobPaths(job);
|
|
67
|
+
if (!['auto', 'operator', 'rules'].includes(approvalPolicy)) throw new Error('Approval policy must be auto, operator, or rules.');
|
|
68
|
+
questionTimeoutMs = timeoutMs ?? questionTimeoutMs;
|
|
69
|
+
if (!Number.isSafeInteger(questionTimeoutMs) || questionTimeoutMs < 1) throw new Error('Question timeout must be a positive number of milliseconds.');
|
|
70
|
+
const pending = new Map();
|
|
71
|
+
const lifetime = new AbortController();
|
|
72
|
+
const children = new Set();
|
|
73
|
+
const notify = event => {
|
|
74
|
+
const task = alertFn ? Promise.resolve().then(() => alertFn(event)) : execute(process.env.TOTAL_RECALL_BIN || 'total-recall',
|
|
75
|
+
['alerts', 'send', '--title', `Metaharness: ${event.kind}`, '--message', `Job ${job}: ${event.text}`, '--severity', 'info', '--source', 'meta-harness'],
|
|
76
|
+
{ timeout: 15_000, maxBuffer: 65536, signal: lifetime.signal });
|
|
77
|
+
children.add(task);
|
|
78
|
+
task.catch(() => {}).finally(() => children.delete(task));
|
|
79
|
+
};
|
|
80
|
+
const watcher = tailInbox(job, command => {
|
|
81
|
+
const wait = pending.get(command.requestId);
|
|
82
|
+
if (!wait || command.type !== (wait.kind === 'question' ? 'reply' : 'approve')) return false;
|
|
83
|
+
wait.finish({ value: wait.kind === 'question' ? command.text : command.value, commandId: command.id });
|
|
84
|
+
return { via: 'metaharness' };
|
|
85
|
+
}, { recipient: 'mcp', onError: error => {
|
|
86
|
+
for (const wait of pending.values()) wait.fail(error);
|
|
87
|
+
} });
|
|
88
|
+
|
|
89
|
+
const waitFor = (event, signal) => new Promise((resolve, reject) => {
|
|
90
|
+
let timer;
|
|
91
|
+
const cleanup = () => { clearTimeout(timer); pending.delete(event.requestId); signal?.removeEventListener('abort', abort); };
|
|
92
|
+
const finish = value => { cleanup(); resolve(value); };
|
|
93
|
+
const fail = error => { cleanup(); reject(error); };
|
|
94
|
+
const abort = () => fail(new Error('The request was cancelled.'));
|
|
95
|
+
pending.set(event.requestId, { kind: event.kind, finish, fail });
|
|
96
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
97
|
+
if (signal?.aborted || lifetime.signal.aborted) { abort(); return; }
|
|
98
|
+
timer = setTimeout(() => finish({ value: event.kind === 'question' ? NO_ANSWER : 'deny', timeout: true }), questionTimeoutMs);
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
return {
|
|
102
|
+
async call(name, args, { signal, defer = deferQuestions } = {}) {
|
|
103
|
+
if (lifetime.signal.aborted) throw new Error('The MCP server has closed.');
|
|
104
|
+
if (name === 'ask') {
|
|
105
|
+
if (!object(args) || !Array.isArray(args.questions) || !args.questions.length ||
|
|
106
|
+
args.questions.some(q => typeof q === 'string' ? !q.trim() : !object(q))) throw fault(-32602, 'ask requires a non-empty questions array.');
|
|
107
|
+
} else if (name === 'approve') {
|
|
108
|
+
if (!object(args) || typeof args.tool_name !== 'string' || !args.tool_name.trim() || !object(args.input) ||
|
|
109
|
+
(args.tool_use_id !== undefined && typeof args.tool_use_id !== 'string')) throw fault(-32602, 'approve requires tool_name and input.');
|
|
110
|
+
} else throw fault(-32602, `Unknown tool: ${name}`);
|
|
111
|
+
const requestId = randomUUID();
|
|
112
|
+
if (name === 'ask' && defer) {
|
|
113
|
+
// A question costs nothing while it waits (A-125): record it, tell the agent to end its turn,
|
|
114
|
+
// and let the session runner start the next turn with the operator's answer. Holding the tool
|
|
115
|
+
// call open made Codex call the model every few seconds while it waited.
|
|
116
|
+
const event = { kind: 'question', source: 'deferred', requestId, text: JSON.stringify(args.questions), questions: args.questions };
|
|
117
|
+
appendEvent(job, event);
|
|
118
|
+
notify(event);
|
|
119
|
+
return textResult(`Your question went to the operator (request ${requestId}). End your turn now and do no other work. The operator's answer arrives as the next message in this session.`);
|
|
120
|
+
}
|
|
121
|
+
const event = { kind: name === 'ask' ? 'question' : 'approval', source: 'mcp', requestId,
|
|
122
|
+
text: name === 'ask' ? JSON.stringify(args.questions) : `${args.tool_name}: ${JSON.stringify(args.input)}`,
|
|
123
|
+
...(name === 'ask' ? { questions: args.questions } : { request: args, policy: approvalPolicy }) };
|
|
124
|
+
appendEvent(job, event);
|
|
125
|
+
let answer;
|
|
126
|
+
try {
|
|
127
|
+
if (name === 'ask' || approvalPolicy === 'operator') {
|
|
128
|
+
// Register the waiter before notifying the operator.
|
|
129
|
+
const waiting = waitFor(event, signal);
|
|
130
|
+
notify(event);
|
|
131
|
+
answer = await waiting;
|
|
132
|
+
} else if (approvalPolicy === 'auto') answer = { value: 'allow', policy: 'auto' };
|
|
133
|
+
else {
|
|
134
|
+
try { answer = { ...await decisionFn(args, { signal: signal ? AbortSignal.any([signal, lifetime.signal]) : lifetime.signal }), policy: 'rules' }; }
|
|
135
|
+
catch (error) { answer = { value: 'deny', policy: 'rules', error: error.message }; }
|
|
136
|
+
if (!['allow', 'deny'].includes(answer.value)) answer = { value: 'deny', policy: 'rules', error: 'Invalid decision answer.' };
|
|
137
|
+
}
|
|
138
|
+
} catch (error) {
|
|
139
|
+
appendEvent(job, { kind: 'ack', command: name, requestId, ok: true, cancelled: true, text: error.message });
|
|
140
|
+
throw error;
|
|
141
|
+
}
|
|
142
|
+
// tailInbox records delivery; this event records the actual answer and policy decision.
|
|
143
|
+
appendEvent(job, { kind: 'ack', command: name, requestId, ok: true, ...answer, text: String(answer.value) });
|
|
144
|
+
if (name === 'ask') return textResult(String(answer.value));
|
|
145
|
+
const result = answer.value === 'allow' ? { behavior: 'allow', updatedInput: args.input }
|
|
146
|
+
: { behavior: 'deny', message: answer.timeout ? 'Approval timed out.' : answer.error || 'The request was denied.' };
|
|
147
|
+
return textResult(JSON.stringify(result));
|
|
148
|
+
},
|
|
149
|
+
async close() {
|
|
150
|
+
lifetime.abort();
|
|
151
|
+
for (const wait of pending.values()) wait.fail(new Error('The MCP server has closed.'));
|
|
152
|
+
await watcher.close();
|
|
153
|
+
await Promise.allSettled(children);
|
|
154
|
+
},
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Never log on stdout here: every line must be a JSON-RPC message. */
|
|
159
|
+
export async function runMcpServer({ input = process.stdin, output = process.stdout, ...options } = {}) {
|
|
160
|
+
const tools = createMcpTools(options);
|
|
161
|
+
const lines = createInterface({ input, crlfDelay: Infinity });
|
|
162
|
+
const calls = new Map();
|
|
163
|
+
let initialized = false, ready = false, closed = false;
|
|
164
|
+
const write = message => { if (!closed) output.write(JSON.stringify(message) + '\n'); };
|
|
165
|
+
const respond = (id, result) => write({ jsonrpc: '2.0', id, result });
|
|
166
|
+
const error = (id, code, message) => write({ jsonrpc: '2.0', id, error: { code, message } });
|
|
167
|
+
const handle = async message => {
|
|
168
|
+
if (!object(message) || message.jsonrpc !== '2.0' || typeof message.method !== 'string' ||
|
|
169
|
+
(Object.hasOwn(message, 'id') && typeof message.id !== 'string' && typeof message.id !== 'number') ||
|
|
170
|
+
(message.params !== undefined && !object(message.params))) {
|
|
171
|
+
error(null, -32600, 'Invalid Request'); return;
|
|
172
|
+
}
|
|
173
|
+
const { id, method, params = {} } = message;
|
|
174
|
+
if (id === undefined) {
|
|
175
|
+
if (method === 'notifications/initialized' && initialized) ready = true;
|
|
176
|
+
if (method === 'notifications/cancelled') calls.get(params.requestId)?.controller.abort();
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
if (calls.has(id)) { error(id, -32600, 'Duplicate request ID'); return; }
|
|
180
|
+
if (method === 'initialize') {
|
|
181
|
+
if (initialized) { error(id, -32600, 'Already initialized'); return; }
|
|
182
|
+
if (typeof params.protocolVersion !== 'string' || !object(params.capabilities) || !object(params.clientInfo)) {
|
|
183
|
+
error(id, -32602, 'initialize requires protocolVersion, capabilities, and clientInfo'); return;
|
|
184
|
+
}
|
|
185
|
+
initialized = true;
|
|
186
|
+
respond(id, { protocolVersion: versions.includes(params.protocolVersion) ? params.protocolVersion : versions[0],
|
|
187
|
+
capabilities: { tools: {} }, serverInfo: { name: 'metaharness', version: '1.0.0' } });
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
if (method === 'ping') { respond(id, {}); return; }
|
|
191
|
+
if (!ready) { error(id, -32002, 'Initialize the MCP session first'); return; }
|
|
192
|
+
if (method === 'tools/list') { respond(id, { tools: MCP_TOOLS }); return; }
|
|
193
|
+
if (method !== 'tools/call') { error(id, -32601, 'Method not found'); return; }
|
|
194
|
+
if (typeof params.name !== 'string') { error(id, -32602, 'tools/call requires a tool name'); return; }
|
|
195
|
+
const controller = new AbortController();
|
|
196
|
+
const call = { controller };
|
|
197
|
+
calls.set(id, call);
|
|
198
|
+
call.done = (async () => {
|
|
199
|
+
try { respond(id, await tools.call(params.name, params.arguments, { signal: controller.signal })); }
|
|
200
|
+
catch (failure) {
|
|
201
|
+
if (typeof failure.code === 'number') error(id, failure.code, failure.message);
|
|
202
|
+
else respond(id, { ...textResult(failure.message), isError: true });
|
|
203
|
+
} finally { calls.delete(id); }
|
|
204
|
+
})();
|
|
205
|
+
};
|
|
206
|
+
lines.on('line', line => {
|
|
207
|
+
let message;
|
|
208
|
+
try { message = JSON.parse(line); } catch { error(null, -32700, 'Parse error'); return; }
|
|
209
|
+
void handle(message).catch(failure => error(message?.id ?? null, -32603, failure.message));
|
|
210
|
+
});
|
|
211
|
+
try { await new Promise((resolve, reject) => { lines.once('close', resolve); input.once('error', reject); output.once('error', reject); }); }
|
|
212
|
+
finally {
|
|
213
|
+
closed = true;
|
|
214
|
+
lines.close();
|
|
215
|
+
for (const call of calls.values()) call.controller.abort();
|
|
216
|
+
await tools.close();
|
|
217
|
+
await Promise.allSettled([...calls.values()].map(call => call.done));
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export const startMcpServer = runMcpServer;
|
|
222
|
+
|
|
223
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
224
|
+
const value = flag => { const i = process.argv.indexOf(flag); return i < 0 ? undefined : process.argv[i + 1]; };
|
|
225
|
+
await runMcpServer({ approvalPolicy: value('--approvals') || 'auto',
|
|
226
|
+
questionTimeoutMs: value('--question-timeout-ms') === undefined ? QUESTION_TIMEOUT_MS : Number(value('--question-timeout-ms')) })
|
|
227
|
+
.catch(error => { console.error(`Metaharness MCP: ${error.message}`); process.exitCode = 1; });
|
|
228
|
+
}
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Model and benchmark catalog: a projection of real sources, refreshed out of band.
|
|
3
|
+
* Reads never touch the network and never invent a figure. An unavailable source keeps its
|
|
4
|
+
* last good data and reports its error; a source never fetched is simply absent.
|
|
5
|
+
*/
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { execFileSync } from 'node:child_process';
|
|
9
|
+
import { derivedDir } from './paths.mjs';
|
|
10
|
+
import { findBinary } from './worker.mjs';
|
|
11
|
+
|
|
12
|
+
const OPENROUTER_URL = 'https://openrouter.ai/api/v1/models';
|
|
13
|
+
const AA_URL = 'https://artificialanalysis.ai/api/v2/language/models/free';
|
|
14
|
+
const SWE_PRO_URL = 'https://labs.scale.com/leaderboard/swe_bench_pro_public';
|
|
15
|
+
const TBENCH_URL = 'https://www.tbench.ai/';
|
|
16
|
+
const EMPTY = () => ({ updatedAt: null, source: 'not-synced', harnessModels: {}, sources: {}, pricing: {}, codingIndex: {}, leaderboards: {} });
|
|
17
|
+
|
|
18
|
+
const catalogFile = () => path.join(derivedDir(), 'model-catalog.json');
|
|
19
|
+
|
|
20
|
+
export function getModelCatalog() {
|
|
21
|
+
try {
|
|
22
|
+
const data = JSON.parse(fs.readFileSync(catalogFile(), 'utf8'));
|
|
23
|
+
if (data?.sources) return { ...EMPTY(), ...data };
|
|
24
|
+
} catch { /* not synced yet */ }
|
|
25
|
+
return EMPTY();
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Compare names across catalogs: no provider prefix, no effort suffix, no punctuation. */
|
|
29
|
+
export function normalizeModelName(name) {
|
|
30
|
+
return String(name).toLowerCase().split('/').pop().replace(/\([^)]*\)/g, ' ').replace(/[-_ ](low|medium|high|xhigh|max)\s*$/, '').replace(/[^a-z0-9]/g, '');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function parseOpenRouter(json) {
|
|
34
|
+
const pricing = {};
|
|
35
|
+
for (const model of json?.data || []) {
|
|
36
|
+
const prompt = Number(model.pricing?.prompt), completion = Number(model.pricing?.completion);
|
|
37
|
+
if (!Number.isFinite(prompt) || !Number.isFinite(completion)) continue;
|
|
38
|
+
pricing[normalizeModelName(model.id)] = { id: model.id, promptPer1M: +(prompt * 1e6).toFixed(4), completionPer1M: +(completion * 1e6).toFixed(4), contextWindow: model.context_length ?? null };
|
|
39
|
+
}
|
|
40
|
+
return pricing;
|
|
41
|
+
}
|
|
42
|
+
/** The free tier fills only some indices, so each stays null unless the provider returned it. */
|
|
43
|
+
export function parseArtificialAnalysis(json) {
|
|
44
|
+
const index = {};
|
|
45
|
+
for (const model of json?.data || []) {
|
|
46
|
+
const e = model.evaluations || {};
|
|
47
|
+
const row = { name: model.name, intelligenceIndex: e.artificial_analysis_intelligence_index ?? null, engineeringIndex: e.artificial_analysis_engineering_index ?? null, codingIndex: e.artificial_analysis_coding_index ?? null, agenticIndex: e.artificial_analysis_agentic_index ?? null };
|
|
48
|
+
if ([row.intelligenceIndex, row.engineeringIndex, row.codingIndex, row.agenticIndex].some(value => typeof value === 'number')) index[normalizeModelName(model.slug || model.name)] = row;
|
|
49
|
+
}
|
|
50
|
+
return index;
|
|
51
|
+
}
|
|
52
|
+
/** Server-rendered rows read: rank, model, score, ±, confidence interval. */
|
|
53
|
+
export function parseSweBenchPro(html) {
|
|
54
|
+
const text = String(html).replace(/<(script|style)[^>]*>[\s\S]*?<\/\1>/g, ' ').replace(/<[^>]+>/g, '|').replace(/\s*\|[\s|]*/g, '|');
|
|
55
|
+
return [...text.matchAll(/\|(\d{1,3})\|([^|]{2,80})(?:\|[A-Z]{2,8})?\|(\d{1,3}\.\d+)\|±\|(\d{1,3}\.\d+)(?=\|)/g)].map(m => ({ rank: +m[1], model: m[2].replace(/\*$/, '').trim(), score: +m[3], ci95: +m[4] }));
|
|
56
|
+
}
|
|
57
|
+
/** The page embeds its leaderboard as escaped JSON: a `leaderboard` with a version name, then a `rows` array. */
|
|
58
|
+
export function parseTerminalBench(html) {
|
|
59
|
+
const text = String(html).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
|
|
60
|
+
const start = text.indexOf('"rows":[');
|
|
61
|
+
if (start < 0) return { benchmark: null, rows: [] };
|
|
62
|
+
const open = start + '"rows":'.length;
|
|
63
|
+
let depth = 0, inString = false, end = -1;
|
|
64
|
+
for (let i = open; i < text.length; i += 1) {
|
|
65
|
+
const c = text[i];
|
|
66
|
+
if (inString) { if (c === '\\') i += 1; else if (c === '"') inString = false; continue; }
|
|
67
|
+
if (c === '"') inString = true;
|
|
68
|
+
else if (c === '[' || c === '{') depth += 1;
|
|
69
|
+
else if (c === ']' || c === '}') { depth -= 1; if (depth === 0) { end = i; break; } }
|
|
70
|
+
}
|
|
71
|
+
if (end < 0) return { benchmark: null, rows: [] };
|
|
72
|
+
const plain = value => (typeof value === 'string' ? value : value?.label ?? null);
|
|
73
|
+
const rows = JSON.parse(text.slice(open, end + 1)).map(row => ({
|
|
74
|
+
rank: row.rank ?? null, model: plain(row.metadata?.model_display), agent: plain(row.metadata?.agent_display), effort: row.metadata?.reasoning_effort ?? null,
|
|
75
|
+
score: row.metrics?.accuracy ?? null, ci95: row.metrics?.accuracy_ci95_half_width ?? null, costUSD: row.metrics?.total_cost_usd ?? null,
|
|
76
|
+
})).filter(row => row.model && typeof row.score === 'number');
|
|
77
|
+
const version = [...text.slice(0, start).matchAll(/"name":"(\d+)-(\d+)-(\d+)"/g)].at(-1);
|
|
78
|
+
return { benchmark: version ? `${version[1]}.${version[2]}` : null, rows };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function fromSource(previous, name, url, load, count) {
|
|
82
|
+
try {
|
|
83
|
+
const data = await load();
|
|
84
|
+
const size = count(data);
|
|
85
|
+
if (!size) throw new Error('Source returned no parseable rows');
|
|
86
|
+
return { data, status: { ok: true, url, fetchedAt: new Date().toISOString(), count: size } };
|
|
87
|
+
} catch (error) {
|
|
88
|
+
return { data: null, status: { ...(previous.sources?.[name] || {}), ok: false, url, attemptedAt: new Date().toISOString(), error: String(error.message).slice(0, 300) } };
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Ask each installed harness for its own model list. One failing does not hide the others. */
|
|
93
|
+
function harnessModelList(run) {
|
|
94
|
+
const readers = {
|
|
95
|
+
agy: ['agy', ['models'], text => text.split('\n').map(line => line.split('\t')).filter(parts => parts.length === 2).map(([id, name]) => ({ id: id.trim(), name: name.trim() }))],
|
|
96
|
+
ollama: ['ollama', ['list'], text => text.split('\n').slice(1).map(line => line.trim().split(/\s+/)[0]).filter(id => id && !/embed|bge-|minilm|rerank/i.test(id)).map(id => ({ id, name: id }))],
|
|
97
|
+
codex: ['codex', ['debug', 'models'], text => (JSON.parse(text).models || []).map(model => ({ id: model.slug, name: model.display_name || model.slug }))],
|
|
98
|
+
};
|
|
99
|
+
const models = {}, errors = {};
|
|
100
|
+
for (const [harness, [bin, args, parse]] of Object.entries(readers)) {
|
|
101
|
+
const binary = findBinary(bin);
|
|
102
|
+
if (!binary) continue;
|
|
103
|
+
try { models[harness] = parse(run(binary, args)); } catch (error) { errors[harness] = String(error.message).slice(0, 200); }
|
|
104
|
+
}
|
|
105
|
+
return { models, errors };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function secretFrom(names) {
|
|
109
|
+
for (const name of names) {
|
|
110
|
+
try {
|
|
111
|
+
const value = execFileSync(process.env.TOTAL_RECALL_BIN || 'total-recall', ['auth', 'secret', 'get', name], { encoding: 'utf8', timeout: 15000, stdio: ['ignore', 'pipe', 'ignore'] }).trim();
|
|
112
|
+
if (value) return value;
|
|
113
|
+
} catch { /* try the next name */ }
|
|
114
|
+
}
|
|
115
|
+
return null;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export async function syncModelCatalog({ fetchImpl = fetch, secret = secretFrom, run = (bin, args) => execFileSync(bin, args, { encoding: 'utf8', timeout: 15000, stdio: ['ignore', 'pipe', 'ignore'] }) } = {}) {
|
|
119
|
+
const previous = getModelCatalog();
|
|
120
|
+
const next = { ...previous, sources: { ...previous.sources } };
|
|
121
|
+
const getJson = async (url, headers = {}) => {
|
|
122
|
+
const response = await fetchImpl(url, { headers, signal: AbortSignal.timeout(30000) });
|
|
123
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
124
|
+
return response.json();
|
|
125
|
+
};
|
|
126
|
+
const getText = async url => {
|
|
127
|
+
const response = await fetchImpl(url, { signal: AbortSignal.timeout(30000) });
|
|
128
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
129
|
+
return response.text();
|
|
130
|
+
};
|
|
131
|
+
const apply = (name, key, outcome) => { next.sources[name] = outcome.status; if (outcome.data) next[key] = outcome.data; };
|
|
132
|
+
|
|
133
|
+
apply('openrouter', 'pricing', await fromSource(previous, 'openrouter', OPENROUTER_URL, async () => parseOpenRouter(await getJson(OPENROUTER_URL)), data => Object.keys(data).length));
|
|
134
|
+
apply('artificialAnalysis', 'codingIndex', await fromSource(previous, 'artificialAnalysis', AA_URL, async () => {
|
|
135
|
+
const key = secret(['DEVELOPER_ARTIFICIAL_ANALYSIS_API_KEY', 'ARTIFICIAL_ANALYSIS_API_KEY']);
|
|
136
|
+
if (!key) throw new Error('No Artificial Analysis key in the auth store');
|
|
137
|
+
const rows = {};
|
|
138
|
+
for (let page = 1, more = true; more && page <= 20; page += 1) {
|
|
139
|
+
const json = await getJson(`${AA_URL}?page=${page}`, { 'x-api-key': key });
|
|
140
|
+
Object.assign(rows, parseArtificialAnalysis(json));
|
|
141
|
+
more = json.pagination?.has_more === true;
|
|
142
|
+
}
|
|
143
|
+
return rows;
|
|
144
|
+
}, data => Object.keys(data).length));
|
|
145
|
+
next.sources.artificialAnalysis.attribution = 'Data from Artificial Analysis (artificialanalysis.ai)';
|
|
146
|
+
|
|
147
|
+
const swe = await fromSource(previous, 'sweBenchPro', SWE_PRO_URL, async () => parseSweBenchPro(await getText(SWE_PRO_URL)), rows => rows.length);
|
|
148
|
+
next.sources.sweBenchPro = swe.status;
|
|
149
|
+
const terminal = await fromSource(previous, 'terminalBench', TBENCH_URL, async () => parseTerminalBench(await getText(TBENCH_URL)), parsed => parsed.rows.length);
|
|
150
|
+
next.sources.terminalBench = { ...terminal.status, ...(terminal.data ? { benchmark: terminal.data.benchmark } : {}) };
|
|
151
|
+
next.leaderboards = { sweBenchPro: swe.data || previous.leaderboards?.sweBenchPro || [], terminalBench: terminal.data?.rows || previous.leaderboards?.terminalBench || [] };
|
|
152
|
+
|
|
153
|
+
const { models, errors } = harnessModelList(run);
|
|
154
|
+
next.harnessModels = { ...previous.harnessModels, ...models };
|
|
155
|
+
const failures = Object.entries(errors).map(([harness, error]) => `${harness}: ${error}`).join('; ');
|
|
156
|
+
next.sources.harnesses = { ok: !failures, fetchedAt: new Date().toISOString(), count: Object.values(next.harnessModels).flat().length, ...(failures ? { error: failures } : {}) };
|
|
157
|
+
next.updatedAt = new Date().toISOString();
|
|
158
|
+
next.source = 'sync';
|
|
159
|
+
saveCatalog(next);
|
|
160
|
+
const failed = Object.entries(next.sources).filter(([, status]) => !status.ok).map(([name, status]) => ({ source: name, error: status.error }));
|
|
161
|
+
return { ok: failed.length === 0, sources: next.sources, failed };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Attach only figures whose normalized names match. Nothing is estimated for a model without a match. */
|
|
165
|
+
export function joinHarnessModels(catalog = getModelCatalog()) {
|
|
166
|
+
const rows = [];
|
|
167
|
+
// Boards list a model once per effort or agent, best first, so the first row is its best result.
|
|
168
|
+
const board = list => {
|
|
169
|
+
const rows = new Map();
|
|
170
|
+
for (const row of list || []) { const key = normalizeModelName(row.model); if (!rows.has(key)) rows.set(key, row); }
|
|
171
|
+
return rows;
|
|
172
|
+
};
|
|
173
|
+
const swe = board(catalog.leaderboards?.sweBenchPro), terminal = board(catalog.leaderboards?.terminalBench);
|
|
174
|
+
// A board may drop the vendor ("Opus 5.5" for claude-opus-5-5). A suffix of at least five characters still names one model.
|
|
175
|
+
const lookup = (rows, key) => rows.get(key) || [...rows].find(([name]) => name.length >= 5 && key.endsWith(name))?.[1] || null;
|
|
176
|
+
for (const [harness, models] of Object.entries(catalog.harnessModels || {})) for (const model of models) {
|
|
177
|
+
const key = normalizeModelName(model.id);
|
|
178
|
+
const pricing = catalog.pricing?.[key] || null, index = catalog.codingIndex?.[key] || null;
|
|
179
|
+
rows.push({ harness, id: model.id, name: model.name, pricing, intelligenceIndex: index?.intelligenceIndex ?? null, engineeringIndex: index?.engineeringIndex ?? null, codingIndex: index?.codingIndex ?? null, agenticIndex: index?.agenticIndex ?? null, sweBenchPro: lookup(swe, key)?.score ?? null, terminalBench: lookup(terminal, key)?.score ?? null });
|
|
180
|
+
}
|
|
181
|
+
return rows;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export function saveCatalog(catalog) {
|
|
185
|
+
fs.mkdirSync(path.dirname(catalogFile()), { recursive: true });
|
|
186
|
+
const temporary = `${catalogFile()}.${process.pid}.tmp`;
|
|
187
|
+
fs.writeFileSync(temporary, JSON.stringify(catalog, null, 2));
|
|
188
|
+
fs.renameSync(temporary, catalogFile());
|
|
189
|
+
const cell = value => value ?? '-';
|
|
190
|
+
const lines = ['# Fleet Model Catalog', '', `Updated: ${catalog.updatedAt}`, '', '## Sources', ''];
|
|
191
|
+
for (const [name, status] of Object.entries(catalog.sources)) lines.push(`- **${name}**: ${status.ok ? `ok, ${status.count} rows, ${status.fetchedAt}` : `failed: ${status.error}`}${status.url ? ` (${status.url})` : ''}${status.attribution ? `. ${status.attribution}` : ''}`);
|
|
192
|
+
lines.push('', '## Harness models', '', '| Harness | Model | Input / Output per 1M | Intelligence index | Engineering index | SWE-bench Pro | Terminal-Bench |', '| :--- | :--- | :--- | :--- | :--- | :--- | :--- |');
|
|
193
|
+
for (const row of joinHarnessModels(catalog)) lines.push(`| ${row.harness} | \`${row.id}\` | ${row.pricing ? `$${row.pricing.promptPer1M} / $${row.pricing.completionPer1M}` : '-'} | ${cell(row.intelligenceIndex)} | ${cell(row.engineeringIndex)} | ${cell(row.sweBenchPro)} | ${cell(row.terminalBench)} |`);
|
|
194
|
+
fs.writeFileSync(path.join(path.dirname(catalogFile()), 'MODELS.md'), lines.join('\n') + '\n');
|
|
195
|
+
}
|