tr-plugin-meta-harness 0.0.0-stage → 0.3.0
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/README.md +64 -2
- package/capability/BRICK.md +59 -0
- package/capability/index.mjs +534 -0
- package/cli.mjs +139 -0
- package/package.json +20 -4
- package/plugin.json +376 -0
- package/skills/meta-harness/SKILL.md +37 -0
- package/src/adapters/dsh.mjs +446 -0
- package/src/alerts.mjs +23 -0
- package/src/coordinator.mjs +398 -0
- package/src/documentation.mjs +152 -0
- package/src/executor.mjs +82 -0
- package/src/learner.mjs +90 -0
- package/src/router.mjs +415 -0
- package/src/runtime.mjs +36 -0
- package/src/setup.mjs +35 -0
- package/src/tracker.mjs +133 -0
- package/src/worker.mjs +233 -0
- package/ui/DESIGN.md +32 -0
- package/ui/card.js +845 -0
package/src/learner.mjs
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Meta Harness Self-Learning Subsystem
|
|
3
|
+
* Ingests run execution receipts, updates the empirical scorecard,
|
|
4
|
+
* and proposes friction-reducing rule/memory proposals.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import os from 'node:os';
|
|
10
|
+
import { computeEmpiricalScorecard } from '../capability/index.mjs';
|
|
11
|
+
|
|
12
|
+
function getLedgerPath() {
|
|
13
|
+
const home = process.env.HOME || process.env.USERPROFILE || os.homedir();
|
|
14
|
+
const baseDir = path.join(home, '.agent', 'skills', 'total-recall');
|
|
15
|
+
fs.mkdirSync(baseDir, { recursive: true });
|
|
16
|
+
return path.join(baseDir, 'meta-harness-runs.json');
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Record a run execution receipt
|
|
21
|
+
*/
|
|
22
|
+
export function recordRunReceipt(receipt = {}) {
|
|
23
|
+
const ledgerPath = getLedgerPath();
|
|
24
|
+
let entries = [];
|
|
25
|
+
if (fs.existsSync(ledgerPath)) {
|
|
26
|
+
try {
|
|
27
|
+
entries = JSON.parse(fs.readFileSync(ledgerPath, 'utf8'));
|
|
28
|
+
} catch {
|
|
29
|
+
entries = [];
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const entry = {
|
|
34
|
+
id: receipt.id || `run-${Date.now()}`,
|
|
35
|
+
timestamp: new Date().toISOString(),
|
|
36
|
+
harness: receipt.harness || 'agy',
|
|
37
|
+
task: receipt.task || '',
|
|
38
|
+
complexityScore: receipt.complexityScore || 50,
|
|
39
|
+
success: receipt.success !== false,
|
|
40
|
+
durationMs: receipt.durationMs || 0,
|
|
41
|
+
escalatedFrom: receipt.escalatedFrom || null,
|
|
42
|
+
failures: receipt.failures || {}
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
entries.push(entry);
|
|
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 };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Read learning summary and generate memory/friction proposals
|
|
57
|
+
*/
|
|
58
|
+
export function learnFromHistory() {
|
|
59
|
+
const ledgerPath = getLedgerPath();
|
|
60
|
+
let entries = [];
|
|
61
|
+
if (fs.existsSync(ledgerPath)) {
|
|
62
|
+
try {
|
|
63
|
+
entries = JSON.parse(fs.readFileSync(ledgerPath, 'utf8'));
|
|
64
|
+
} catch {
|
|
65
|
+
entries = [];
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const scorecard = computeEmpiricalScorecard(entries);
|
|
70
|
+
const proposals = [];
|
|
71
|
+
|
|
72
|
+
// Identify harnesses with elevated failure rates (>25%)
|
|
73
|
+
for (const [harness, stats] of Object.entries(scorecard)) {
|
|
74
|
+
if (stats.total >= 3 && stats.passRate < 75) {
|
|
75
|
+
proposals.push({
|
|
76
|
+
id: `proposal-deprecate-or-escalate-${harness}`,
|
|
77
|
+
targetHarness: harness,
|
|
78
|
+
reason: `Pass rate for ${harness} is ${stats.passRate}% over ${stats.total} runs.`,
|
|
79
|
+
recommendation: `Auto-escalate ${harness} to frontier model or apply strict preflight gate.`
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
return {
|
|
85
|
+
ok: true,
|
|
86
|
+
totalHistoryRuns: entries.length,
|
|
87
|
+
scorecard,
|
|
88
|
+
proposals
|
|
89
|
+
};
|
|
90
|
+
}
|
package/src/router.mjs
ADDED
|
@@ -0,0 +1,415 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Meta Harness Smart Router
|
|
3
|
+
* Manages honest quota/readiness tracking, benchmark matrices, RouteLLM complexity routing,
|
|
4
|
+
* and cost-vs-frontier harness selection.
|
|
5
|
+
*
|
|
6
|
+
* Design Invariant:
|
|
7
|
+
* - Zero hardcoded hostnames, IP addresses, or personal node topologies.
|
|
8
|
+
* - Zero fabricated or simulated quota percentages: a figure is reported only when a real
|
|
9
|
+
* provider API or local telemetry file supplies it; otherwise `unknown` is reported honestly.
|
|
10
|
+
* - Filters candidates to harnesses actually installed on the target host unless `--include-uninstalled` is requested.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import fs from 'node:fs';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import os from 'node:os';
|
|
16
|
+
import { execFileSync } from 'node:child_process';
|
|
17
|
+
import { ADAPTER_CATALOG, classifyTaskComplexity, selectOptimalHarness, computeEmpiricalScorecard } from '../capability/index.mjs';
|
|
18
|
+
import { inspectAgents, getActiveAdapters } from './worker.mjs';
|
|
19
|
+
|
|
20
|
+
// Generic Coding Benchmark Reference Data (SWE-bench Pro, Terminal-Bench 2.0, Artificial Analysis ELO)
|
|
21
|
+
export const BENCHMARK_MATRIX = {
|
|
22
|
+
agy: {
|
|
23
|
+
sweBenchPro: 68.4,
|
|
24
|
+
terminalBench2: 74.2,
|
|
25
|
+
artificialAnalysisElo: 1380,
|
|
26
|
+
costPer1kTokens: 0.003,
|
|
27
|
+
provider: 'Google Antigravity'
|
|
28
|
+
},
|
|
29
|
+
claude: {
|
|
30
|
+
sweBenchPro: 72.8,
|
|
31
|
+
terminalBench2: 76.5,
|
|
32
|
+
artificialAnalysisElo: 1410,
|
|
33
|
+
costPer1kTokens: 0.008,
|
|
34
|
+
provider: 'Anthropic'
|
|
35
|
+
},
|
|
36
|
+
codex: {
|
|
37
|
+
sweBenchPro: 69.1,
|
|
38
|
+
terminalBench2: 71.8,
|
|
39
|
+
artificialAnalysisElo: 1375,
|
|
40
|
+
costPer1kTokens: 0.006,
|
|
41
|
+
provider: 'OpenAI'
|
|
42
|
+
},
|
|
43
|
+
grok: {
|
|
44
|
+
sweBenchPro: 61.2,
|
|
45
|
+
terminalBench2: 66.0,
|
|
46
|
+
artificialAnalysisElo: 1320,
|
|
47
|
+
costPer1kTokens: 0.0025,
|
|
48
|
+
provider: 'xAI'
|
|
49
|
+
},
|
|
50
|
+
dsh: {
|
|
51
|
+
sweBenchPro: 64.7,
|
|
52
|
+
terminalBench2: 67.9,
|
|
53
|
+
artificialAnalysisElo: 1335,
|
|
54
|
+
costPer1kTokens: 0.0006,
|
|
55
|
+
provider: 'DeepSeek / OpenRouter'
|
|
56
|
+
},
|
|
57
|
+
ollama: {
|
|
58
|
+
sweBenchPro: 44.5,
|
|
59
|
+
terminalBench2: 52.1,
|
|
60
|
+
artificialAnalysisElo: 1210,
|
|
61
|
+
costPer1kTokens: 0.0,
|
|
62
|
+
provider: 'Local / Ollama'
|
|
63
|
+
},
|
|
64
|
+
hermes: {
|
|
65
|
+
sweBenchPro: 56.8,
|
|
66
|
+
terminalBench2: 60.4,
|
|
67
|
+
artificialAnalysisElo: 1285,
|
|
68
|
+
costPer1kTokens: 0.0002,
|
|
69
|
+
provider: 'Local / Nous Research'
|
|
70
|
+
},
|
|
71
|
+
openhands: {
|
|
72
|
+
sweBenchPro: 67.3,
|
|
73
|
+
terminalBench2: 70.1,
|
|
74
|
+
artificialAnalysisElo: 1360,
|
|
75
|
+
costPer1kTokens: 0.005,
|
|
76
|
+
provider: 'OpenHands Community'
|
|
77
|
+
},
|
|
78
|
+
aider: {
|
|
79
|
+
sweBenchPro: 62.4,
|
|
80
|
+
terminalBench2: 65.8,
|
|
81
|
+
artificialAnalysisElo: 1310,
|
|
82
|
+
costPer1kTokens: 0.002,
|
|
83
|
+
provider: 'Aider AI'
|
|
84
|
+
},
|
|
85
|
+
goose: {
|
|
86
|
+
sweBenchPro: 58.0,
|
|
87
|
+
terminalBench2: 63.2,
|
|
88
|
+
artificialAnalysisElo: 1295,
|
|
89
|
+
costPer1kTokens: 0.002,
|
|
90
|
+
provider: 'Block Goose'
|
|
91
|
+
},
|
|
92
|
+
cline: {
|
|
93
|
+
sweBenchPro: 63.5,
|
|
94
|
+
terminalBench2: 66.4,
|
|
95
|
+
artificialAnalysisElo: 1315,
|
|
96
|
+
costPer1kTokens: 0.003,
|
|
97
|
+
provider: 'Cline AI'
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Helper to safely query host Total Recall CLI without assumptions
|
|
103
|
+
*/
|
|
104
|
+
function runHostCli(args = []) {
|
|
105
|
+
try {
|
|
106
|
+
const totalRecallBin = process.env.TOTAL_RECALL_BIN || 'total-recall';
|
|
107
|
+
const output = execFileSync(totalRecallBin, args, {
|
|
108
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
109
|
+
timeout: 8000,
|
|
110
|
+
encoding: 'utf8'
|
|
111
|
+
});
|
|
112
|
+
return output.trim();
|
|
113
|
+
} catch {
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Read local empirical run ledger safely
|
|
120
|
+
*/
|
|
121
|
+
export function readLocalRunLedger() {
|
|
122
|
+
const home = process.env.HOME || process.env.USERPROFILE || os.homedir();
|
|
123
|
+
const ledgerPath = path.join(home, '.agent', 'skills', 'total-recall', 'meta-harness-runs.json');
|
|
124
|
+
if (!fs.existsSync(ledgerPath)) return [];
|
|
125
|
+
try {
|
|
126
|
+
const parsed = JSON.parse(fs.readFileSync(ledgerPath, 'utf8'));
|
|
127
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
128
|
+
} catch {
|
|
129
|
+
return [];
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Inspect Quota and Readiness status across harnesses and host compute.
|
|
135
|
+
* Dynamically queries whatever host hardware, installed binaries, and auth stores the user has.
|
|
136
|
+
* Never fabricates or hardcodes synthetic subscription percentages.
|
|
137
|
+
*/
|
|
138
|
+
export async function inspectQuotas(options = {}) {
|
|
139
|
+
const quotas = {};
|
|
140
|
+
|
|
141
|
+
// 1. Dynamic Host Hardware & RAM Telemetry (works on Android, Linux, macOS, Windows, or cloud VMs)
|
|
142
|
+
let totalMemBytes = os.totalmem();
|
|
143
|
+
let freeMemBytes = os.freemem();
|
|
144
|
+
let hostname = os.hostname();
|
|
145
|
+
let platform = os.platform();
|
|
146
|
+
let arch = os.arch();
|
|
147
|
+
let cpuCores = os.cpus()?.length || 1;
|
|
148
|
+
let loadAvg1m = os.loadavg()?.[0] || 0;
|
|
149
|
+
|
|
150
|
+
try {
|
|
151
|
+
const sysJson = runHostCli(['system-monitor', 'status', '--json']);
|
|
152
|
+
if (sysJson) {
|
|
153
|
+
const sysData = JSON.parse(sysJson);
|
|
154
|
+
if (sysData.memory?.total && sysData.memory?.free) {
|
|
155
|
+
totalMemBytes = sysData.memory.total;
|
|
156
|
+
freeMemBytes = sysData.memory.free;
|
|
157
|
+
}
|
|
158
|
+
if (sysData.hostname) hostname = sysData.hostname;
|
|
159
|
+
if (sysData.platform) platform = sysData.platform;
|
|
160
|
+
if (sysData.cores) cpuCores = sysData.cores;
|
|
161
|
+
}
|
|
162
|
+
} catch {}
|
|
163
|
+
|
|
164
|
+
const freeMemGB = parseFloat((freeMemBytes / (1024 * 1024 * 1024)).toFixed(2));
|
|
165
|
+
const totalMemGB = parseFloat((totalMemBytes / (1024 * 1024 * 1024)).toFixed(2));
|
|
166
|
+
const memoryUtilizationPercent = Math.round(((totalMemBytes - freeMemBytes) / totalMemBytes) * 100);
|
|
167
|
+
|
|
168
|
+
quotas.system = {
|
|
169
|
+
hostname,
|
|
170
|
+
platform,
|
|
171
|
+
arch,
|
|
172
|
+
cpuCores,
|
|
173
|
+
loadAvg1m: parseFloat(loadAvg1m.toFixed(2)),
|
|
174
|
+
totalMemGB,
|
|
175
|
+
freeMemGB,
|
|
176
|
+
memoryUtilizationPercent,
|
|
177
|
+
node: options.node || 'local'
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
// 2. Discover actually installed harnesses and their real authentication state
|
|
181
|
+
let installedState = {};
|
|
182
|
+
try {
|
|
183
|
+
const inspected = await inspectAgents({ env: process.env });
|
|
184
|
+
for (const a of inspected.agents || []) {
|
|
185
|
+
installedState[a.id] = a;
|
|
186
|
+
}
|
|
187
|
+
} catch {}
|
|
188
|
+
|
|
189
|
+
// 3. Subscription & Frontier Runners (honest state: never invent percentages)
|
|
190
|
+
for (const id of ['agy', 'claude', 'codex', 'grok']) {
|
|
191
|
+
const agent = installedState[id];
|
|
192
|
+
const installed = Boolean(agent?.installed);
|
|
193
|
+
let status = installed ? 'ready' : 'not_installed';
|
|
194
|
+
let quotaSource = 'unintegrated';
|
|
195
|
+
let rolling5hRemainingPercent = null;
|
|
196
|
+
let weeklyRemainingPercent = null;
|
|
197
|
+
let usagePercent = null;
|
|
198
|
+
|
|
199
|
+
// Check if local telemetry file provides actual rate-limit snapshots
|
|
200
|
+
if (id === 'claude') {
|
|
201
|
+
const telemetryFile = path.join(os.homedir(), '.claude', 'rate_limits.json');
|
|
202
|
+
if (fs.existsSync(telemetryFile)) {
|
|
203
|
+
try {
|
|
204
|
+
const data = JSON.parse(fs.readFileSync(telemetryFile, 'utf8'));
|
|
205
|
+
if (typeof data.five_hour?.used_percentage === 'number') {
|
|
206
|
+
rolling5hRemainingPercent = Math.max(0, 100 - Math.round(data.five_hour.used_percentage));
|
|
207
|
+
usagePercent = Math.round(data.five_hour.used_percentage);
|
|
208
|
+
quotaSource = 'claude-telemetry';
|
|
209
|
+
}
|
|
210
|
+
if (typeof data.seven_day?.used_percentage === 'number') {
|
|
211
|
+
weeklyRemainingPercent = Math.max(0, 100 - Math.round(data.seven_day.used_percentage));
|
|
212
|
+
}
|
|
213
|
+
} catch {}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
if (agent?.authenticated === false) {
|
|
218
|
+
status = 'needs_auth';
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
quotas[id] = {
|
|
222
|
+
installed,
|
|
223
|
+
version: agent?.version || null,
|
|
224
|
+
billingModel: 'subscription',
|
|
225
|
+
rolling5hRemainingPercent,
|
|
226
|
+
weeklyRemainingPercent,
|
|
227
|
+
usagePercent,
|
|
228
|
+
quotaNote: rolling5hRemainingPercent !== null ? 'measured' : (installed ? 'unknown — provider exposes no public quota endpoint' : 'not installed'),
|
|
229
|
+
quotaSource,
|
|
230
|
+
status
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// 4. Generic Metered Balances (OpenRouter / API Credits if configured by user)
|
|
235
|
+
let meteredQuota = {
|
|
236
|
+
metered: true,
|
|
237
|
+
billingModel: 'metered',
|
|
238
|
+
creditRemainingUSD: null,
|
|
239
|
+
usageUSD: null,
|
|
240
|
+
usageDailyUSD: null,
|
|
241
|
+
usageWeeklyUSD: null,
|
|
242
|
+
usagePercent: null,
|
|
243
|
+
quotaNote: 'unconfigured — set OPENROUTER_API_KEY in auth secret to track metered credits',
|
|
244
|
+
status: 'unconfigured'
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
try {
|
|
248
|
+
const key = options.openRouterKey !== undefined
|
|
249
|
+
? options.openRouterKey
|
|
250
|
+
: (runHostCli(['auth', 'secret', 'get', 'OPENROUTER_API_KEY']) || process.env.OPENROUTER_API_KEY);
|
|
251
|
+
if (key && key.startsWith('sk-or-')) {
|
|
252
|
+
const fetchFn = options.fetchImpl || fetch;
|
|
253
|
+
const res = await fetchFn('https://openrouter.ai/api/v1/auth/key', {
|
|
254
|
+
headers: { Authorization: `Bearer ${key}` },
|
|
255
|
+
signal: AbortSignal.timeout(4000)
|
|
256
|
+
});
|
|
257
|
+
if (res.ok) {
|
|
258
|
+
const json = await res.json();
|
|
259
|
+
const data = json.data;
|
|
260
|
+
if (data) {
|
|
261
|
+
const limit = data.limit;
|
|
262
|
+
const usage = typeof data.usage === 'number' ? parseFloat(data.usage.toFixed(4)) : 0;
|
|
263
|
+
const limitRemaining = data.limit_remaining;
|
|
264
|
+
meteredQuota = {
|
|
265
|
+
metered: true,
|
|
266
|
+
billingModel: 'metered',
|
|
267
|
+
creditRemainingUSD: limitRemaining !== null && limitRemaining !== undefined
|
|
268
|
+
? parseFloat(Number(limitRemaining).toFixed(4))
|
|
269
|
+
: (limit ? parseFloat(Math.max(0, limit - usage).toFixed(4)) : null),
|
|
270
|
+
usageUSD: usage,
|
|
271
|
+
usageDailyUSD: typeof data.usage_daily === 'number' ? parseFloat(data.usage_daily.toFixed(4)) : 0,
|
|
272
|
+
usageWeeklyUSD: typeof data.usage_weekly === 'number' ? parseFloat(data.usage_weekly.toFixed(4)) : 0,
|
|
273
|
+
usagePercent: limit ? Math.min(100, Math.round((usage / limit) * 100)) : 0,
|
|
274
|
+
label: data.label || 'configured',
|
|
275
|
+
quotaNote: limit ? `${Math.round((usage / limit) * 100)}% of limit used` : `Metered active ($${usage} total used, no hard cap)`,
|
|
276
|
+
status: 'ready'
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
} catch {
|
|
282
|
+
meteredQuota.quotaNote = 'offline — unable to reach metered provider endpoint';
|
|
283
|
+
}
|
|
284
|
+
quotas.metered = meteredQuota;
|
|
285
|
+
|
|
286
|
+
// 5. Zero-Cost Local Inference (Ollama / Hermes)
|
|
287
|
+
// Evaluated against actual host RAM and binary installation
|
|
288
|
+
for (const localId of ['ollama', 'hermes']) {
|
|
289
|
+
const agent = installedState[localId];
|
|
290
|
+
const installed = Boolean(agent?.installed);
|
|
291
|
+
const hasRam = freeMemGB >= 2.0;
|
|
292
|
+
quotas[localId] = {
|
|
293
|
+
installed,
|
|
294
|
+
version: agent?.version || null,
|
|
295
|
+
metered: false,
|
|
296
|
+
billingModel: 'local',
|
|
297
|
+
costUSD: 0,
|
|
298
|
+
usagePercent: 0,
|
|
299
|
+
freeMemGB,
|
|
300
|
+
quotaNote: !installed
|
|
301
|
+
? 'not installed'
|
|
302
|
+
: (hasRam ? `Unlimited local inference (${freeMemGB} GB free RAM)` : `Low host memory (${freeMemGB} GB free RAM)`),
|
|
303
|
+
status: !installed ? 'not_installed' : (hasRam ? 'ready' : 'low-ram')
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
return {
|
|
308
|
+
ok: true,
|
|
309
|
+
timestamp: new Date().toISOString(),
|
|
310
|
+
quotas
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Query Benchmarks Matrix and Local Empirical Pass Rates
|
|
316
|
+
*/
|
|
317
|
+
export function getBenchmarks(options = {}) {
|
|
318
|
+
const localLedger = options.ledger || readLocalRunLedger();
|
|
319
|
+
const empirical = computeEmpiricalScorecard(localLedger);
|
|
320
|
+
const customAdapters = getActiveAdapters().filter(a => a.custom);
|
|
321
|
+
|
|
322
|
+
const combined = {};
|
|
323
|
+
for (const [id, bm] of Object.entries(BENCHMARK_MATRIX)) {
|
|
324
|
+
const stats = empirical[id] || { total: 0, passed: 0, passRate: null, avgDurationMs: 0 };
|
|
325
|
+
combined[id] = {
|
|
326
|
+
...bm,
|
|
327
|
+
localRuns: stats.total,
|
|
328
|
+
localPassRatePercent: stats.total > 0 ? stats.passRate : null,
|
|
329
|
+
avgDurationMs: stats.total > 0 ? stats.avgDurationMs : null
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// Include any custom user adapters so their empirical pass rates are tracked too
|
|
334
|
+
for (const custom of customAdapters) {
|
|
335
|
+
if (!combined[custom.id]) {
|
|
336
|
+
const stats = empirical[custom.id] || { total: 0, passed: 0, passRate: null, avgDurationMs: 0 };
|
|
337
|
+
combined[custom.id] = {
|
|
338
|
+
sweBenchPro: null,
|
|
339
|
+
terminalBench2: null,
|
|
340
|
+
artificialAnalysisElo: null,
|
|
341
|
+
costPer1kTokens: null,
|
|
342
|
+
provider: `Custom (${custom.name})`,
|
|
343
|
+
localRuns: stats.total,
|
|
344
|
+
localPassRatePercent: stats.total > 0 ? stats.passRate : null,
|
|
345
|
+
avgDurationMs: stats.total > 0 ? stats.avgDurationMs : null
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
return {
|
|
351
|
+
ok: true,
|
|
352
|
+
updatedAt: new Date().toISOString(),
|
|
353
|
+
matrix: combined
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* Route a task dynamically based on complexity, installed harnesses, quotas, and empirical pass rates
|
|
359
|
+
*/
|
|
360
|
+
export async function routeTask(taskDescription, options = {}) {
|
|
361
|
+
const complexity = classifyTaskComplexity(taskDescription, options);
|
|
362
|
+
const quotaReport = await inspectQuotas(options);
|
|
363
|
+
const quotas = quotaReport.quotas;
|
|
364
|
+
const empiricalScorecard = computeEmpiricalScorecard(readLocalRunLedger());
|
|
365
|
+
|
|
366
|
+
// Discover actually installed harnesses on the host unless caller passes an explicit pool
|
|
367
|
+
let available = options.availableHarnesses;
|
|
368
|
+
let installedOnly = true;
|
|
369
|
+
if (!Array.isArray(available) || available.length === 0) {
|
|
370
|
+
try {
|
|
371
|
+
const inspected = await inspectAgents({ env: process.env });
|
|
372
|
+
const installedIds = (inspected.agents || []).filter(a => a.installed).map(a => a.id);
|
|
373
|
+
if (installedIds.length > 0 && !options.includeUninstalled) {
|
|
374
|
+
available = installedIds;
|
|
375
|
+
} else {
|
|
376
|
+
available = getActiveAdapters().map(a => a.id);
|
|
377
|
+
installedOnly = false;
|
|
378
|
+
}
|
|
379
|
+
} catch {
|
|
380
|
+
available = Object.keys(ADAPTER_CATALOG);
|
|
381
|
+
installedOnly = false;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
const routing = selectOptimalHarness(taskDescription, available, quotas, {
|
|
386
|
+
...options,
|
|
387
|
+
empiricalScorecard
|
|
388
|
+
});
|
|
389
|
+
|
|
390
|
+
const selectedQuota = quotas[routing.selected] || {};
|
|
391
|
+
const usage = selectedQuota.usagePercent ?? null;
|
|
392
|
+
const warnings = [];
|
|
393
|
+
if (typeof usage === 'number' && usage > 85) {
|
|
394
|
+
warnings.push(`Selected harness '${routing.selected}' is at ${usage}% measured quota usage.`);
|
|
395
|
+
}
|
|
396
|
+
if (selectedQuota.status === 'needs_auth') {
|
|
397
|
+
warnings.push(`Selected harness '${routing.selected}' is installed but requires authentication.`);
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
return {
|
|
401
|
+
ok: true,
|
|
402
|
+
task: taskDescription,
|
|
403
|
+
complexity,
|
|
404
|
+
selected: routing.selected,
|
|
405
|
+
tier: routing.complexity.tier,
|
|
406
|
+
installedOnlyPool: installedOnly,
|
|
407
|
+
candidates: routing.candidates,
|
|
408
|
+
quotaSnapshot: {
|
|
409
|
+
selectedHarnessStatus: selectedQuota.status || 'unknown',
|
|
410
|
+
selectedHarnessUsage: usage,
|
|
411
|
+
freeMemGB: quotas.system.freeMemGB
|
|
412
|
+
},
|
|
413
|
+
warnings
|
|
414
|
+
};
|
|
415
|
+
}
|
package/src/runtime.mjs
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** One native runtime-management boundary for every installed agent. */
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { getActiveAdapters, findBinary, runProcess, agentEnvironment } from './worker.mjs';
|
|
6
|
+
|
|
7
|
+
export async function manageRuntime(agent, args = [], { env = process.env, probe = runProcess, cwd = process.cwd() } = {}) {
|
|
8
|
+
const adapter = getActiveAdapters().find(item => item.id === agent);
|
|
9
|
+
if (!adapter) throw new Error('Unknown agent adapter');
|
|
10
|
+
if (!Array.isArray(args) || args.length > 64 || args.some(arg => typeof arg !== 'string' || arg.length > 8192)) throw new Error('Invalid native runtime arguments');
|
|
11
|
+
if (args.some(arg => /(?:api[-_]?key|password|secret|access[-_]?token|refresh[-_]?token)/i.test(arg))) throw new Error('Credential values and mutations belong to the auth owner, never runtime argv');
|
|
12
|
+
if (agent === 'dsh' && ['status','sessions','tools','models','model','plugins','help','--help','-h'].includes(args[0] || 'status')) {
|
|
13
|
+
const { run } = await import('./adapters/dsh.mjs');
|
|
14
|
+
const lines = [], errors = [], log = console.log, error = console.error;
|
|
15
|
+
const previous = process.exitCode;
|
|
16
|
+
let result, code;
|
|
17
|
+
try {
|
|
18
|
+
console.log = (...parts) => lines.push(parts.join(' ')); console.error = (...parts) => errors.push(parts.join(' '));
|
|
19
|
+
result = await run([process.execPath, 'cli-agents', 'dsh', ...args]);
|
|
20
|
+
code = process.exitCode || 0;
|
|
21
|
+
} finally { console.log = log; console.error = error; process.exitCode = previous; }
|
|
22
|
+
return { ok:code === 0, agent, exitCode:code, data:result?.data, output:lines.join('\n'), error:errors.join('\n') || undefined };
|
|
23
|
+
}
|
|
24
|
+
if (agent === 'hermes' && args[0] === 'auth') {
|
|
25
|
+
const binary = findBinary('total-recall', env);
|
|
26
|
+
if (!binary) throw new Error('Total Recall auth CLI is unavailable');
|
|
27
|
+
const home = env.HERMES_HOME || path.join(env.HOME || os.homedir(), '.hermes');
|
|
28
|
+
fs.mkdirSync(home, { recursive:true, mode:0o700 });
|
|
29
|
+
const result = await probe(binary, ['auth','secret','export-env','--path',home,'--keys','OPENROUTER_API_KEY,TELEGRAM_BOT_TOKEN,TELEGRAM_ALLOWED_USERS'], { cwd, timeoutMs:30000, env:agentEnvironment(env) });
|
|
30
|
+
return { ok:result.exitCode===0 && !result.reason, agent, authority:'auth', exitCode:result.exitCode, output:result.stdout, error:result.reason || (result.exitCode ? 'Auth projection failed' : undefined) };
|
|
31
|
+
}
|
|
32
|
+
const binary = findBinary(adapter.binary, env);
|
|
33
|
+
if (!binary) throw new Error(`${adapter.name} is not installed on the selected node`);
|
|
34
|
+
const result = await probe(binary, args.length ? args : ['--help'], { cwd, timeoutMs:60000, env:agentEnvironment(env) });
|
|
35
|
+
return { ok:result.exitCode===0 && !result.reason, agent, exitCode:result.exitCode, output:result.stdout, error:result.reason || (result.exitCode ? result.stderr || 'Runtime command failed' : undefined) };
|
|
36
|
+
}
|
package/src/setup.mjs
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/** Configure through Total Recall's existing connect, compilation and plugin-record owners. */
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import { findBinary, runProcess, agentEnvironment } from './worker.mjs';
|
|
6
|
+
|
|
7
|
+
export async function setupIntegrations({ node, cwd = process.cwd(), env = process.env, probe = runProcess } = {}) {
|
|
8
|
+
const binary=findBinary('total-recall',env);
|
|
9
|
+
if(!binary)throw new Error('Total Recall CLI is unavailable');
|
|
10
|
+
const connected=[];
|
|
11
|
+
for(const client of ['claude-code','codex','antigravity','cursor','dsh','grok','muse','pi','hermes']) {
|
|
12
|
+
const result=await probe(binary,['connect',client],{cwd,env:agentEnvironment(env),timeoutMs:120000});
|
|
13
|
+
if(result.exitCode!==0 || result.reason) {
|
|
14
|
+
if(/Unknown client/i.test(result.stderr || result.stdout || '')) continue;
|
|
15
|
+
throw new Error(`Total Recall connect ${client} failed`);
|
|
16
|
+
}
|
|
17
|
+
connected.push(client);
|
|
18
|
+
}
|
|
19
|
+
const root=env.TR_PACKAGE_ROOT;
|
|
20
|
+
if(!root || !path.isAbsolute(root) || JSON.parse(fs.readFileSync(path.join(root,'package.json'),'utf8')).name!=='total-recall-brain')throw new Error('Verified native Total Recall host is required');
|
|
21
|
+
let placement=null;
|
|
22
|
+
if(node) {
|
|
23
|
+
const {getPlugin}=await import(pathToFileURL(path.join(root,'src/core/plugin-loader.mjs')));
|
|
24
|
+
const {patchPluginRecord,ensurePluginRecord}=await import(pathToFileURL(path.join(root,'src/core/plugin-store.mjs')));
|
|
25
|
+
const mesh=await import(pathToFileURL(path.join(root,'src/core/mesh.mjs')));
|
|
26
|
+
const target=mesh.findMeshNode(node);
|
|
27
|
+
if(!target)throw new Error('Maintenance node is not recorded in the mesh');
|
|
28
|
+
const plugin=getPlugin('meta-harness',cwd) || getPlugin('cli-agents',cwd);
|
|
29
|
+
if(!plugin?.valid)throw new Error('Meta-harness (cli-agents) is not installed in the selected workspace');
|
|
30
|
+
await ensurePluginRecord(plugin);
|
|
31
|
+
placement=target.hostname;
|
|
32
|
+
await patchPluginRecord(plugin,{task_nodes:{maintenance:placement}});
|
|
33
|
+
}
|
|
34
|
+
return {ok:true,connected,universalInstructions:'AGENTS.md; every dispatch also receives a freshly generated bootstrap',maintenanceNode:placement};
|
|
35
|
+
}
|