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.
Files changed (94) hide show
  1. package/DESIGN.md +86 -0
  2. package/README.md +257 -11
  3. package/capability/BRICK.md +1 -1
  4. package/capability/index.mjs +154 -13
  5. package/cli.mjs +426 -41
  6. package/package.json +15 -3
  7. package/plugin.json +1457 -119
  8. package/skills/meta-harness/SKILL.md +63 -25
  9. package/src/adoption.mjs +102 -0
  10. package/src/agent-user.mjs +194 -0
  11. package/src/alerts.mjs +220 -14
  12. package/src/cascade.mjs +185 -0
  13. package/src/chat.mjs +80 -0
  14. package/src/codex-models.mjs +54 -0
  15. package/src/compat-harness.mjs +114 -0
  16. package/src/control.mjs +145 -0
  17. package/src/coordinator.mjs +267 -358
  18. package/src/dispatch-request.mjs +76 -0
  19. package/src/dispatch.mjs +119 -0
  20. package/src/documentation-authority.mjs +57 -0
  21. package/src/documentation.mjs +120 -32
  22. package/src/executor.mjs +101 -22
  23. package/src/gate-adapters/agy.mjs +155 -0
  24. package/src/gate-adapters/claude.mjs +303 -0
  25. package/src/gate-adapters/cline.mjs +111 -0
  26. package/src/gate-adapters/codex.mjs +164 -0
  27. package/src/gate-adapters/cursor.mjs +164 -0
  28. package/src/gate-adapters/devin.mjs +116 -0
  29. package/src/gate-adapters/dsh.mjs +284 -0
  30. package/src/gate-adapters/grok.mjs +112 -0
  31. package/src/gate-adapters/hermes.mjs +217 -0
  32. package/src/gate-adapters/hook-files.mjs +156 -0
  33. package/src/gate-adapters/index.mjs +131 -0
  34. package/src/gate-adapters/openclaw-plugin/gate-client.js +205 -0
  35. package/src/gate-adapters/openclaw-plugin/index.js +25 -0
  36. package/src/gate-adapters/openclaw-plugin/openclaw.plugin.json +9 -0
  37. package/src/gate-adapters/openclaw-plugin/package.json +15 -0
  38. package/src/gate-adapters/openclaw.mjs +288 -0
  39. package/src/gate-adapters/pi.mjs +146 -0
  40. package/src/gate.mjs +18 -0
  41. package/src/harness-updates.mjs +170 -0
  42. package/src/included-usage.mjs +344 -0
  43. package/src/jobs.mjs +135 -0
  44. package/src/json-reply.mjs +22 -0
  45. package/src/learner.mjs +97 -67
  46. package/src/maintenance.mjs +18 -0
  47. package/src/mcp-server.mjs +228 -0
  48. package/src/model-catalog.mjs +195 -0
  49. package/src/model-selection.mjs +67 -0
  50. package/src/paths.mjs +23 -0
  51. package/src/pool.mjs +69 -0
  52. package/src/process-manager.mjs +246 -0
  53. package/src/process-worker.mjs +18 -0
  54. package/src/reasoning.mjs +231 -0
  55. package/src/remote-operation.mjs +76 -0
  56. package/src/review.mjs +241 -0
  57. package/src/reviews.mjs +25 -0
  58. package/src/router-benchmark-corpus.mjs +16 -0
  59. package/src/router-benchmark.mjs +208 -0
  60. package/src/router.mjs +265 -346
  61. package/src/runtime.mjs +30 -8
  62. package/src/session/claude.mjs +358 -0
  63. package/src/session/codex.mjs +501 -0
  64. package/src/session/result.mjs +90 -0
  65. package/src/session/resume.mjs +393 -0
  66. package/src/session/run.mjs +258 -0
  67. package/src/session-jobs.mjs +77 -0
  68. package/src/setup.mjs +6 -3
  69. package/src/ssss-store.mjs +20 -0
  70. package/src/telemetry.mjs +267 -0
  71. package/src/termination.mjs +28 -0
  72. package/src/threads.mjs +150 -0
  73. package/src/usage-queue.mjs +137 -0
  74. package/src/verify-ssss.mjs +102 -0
  75. package/src/worker.mjs +955 -84
  76. package/src/worktree.mjs +244 -0
  77. package/ui/chunks/adapter-docs-freshness.md +16 -0
  78. package/ui/chunks/chat-handoff.md +26 -0
  79. package/ui/chunks/fleet-maintenance.md +21 -0
  80. package/ui/chunks/harness-inventory.md +21 -0
  81. package/ui/chunks/included-access.md +18 -0
  82. package/ui/chunks/included-usage-verification.md +15 -0
  83. package/ui/chunks/independent-review.md +17 -0
  84. package/ui/chunks/managed-execution.md +20 -0
  85. package/ui/chunks/official-documentation.md +18 -0
  86. package/ui/chunks/quota-recovery.md +21 -0
  87. package/ui/chunks/review-routing-decision.md +16 -0
  88. package/ui/chunks/route-work.md +18 -0
  89. package/ui/chunks/routing-evidence.md +18 -0
  90. package/ui/chunks/run-ledger.md +18 -0
  91. package/ui/chunks/session-controls.md +16 -0
  92. package/ui/home.js +198 -0
  93. package/ui/DESIGN.md +0 -32
  94. package/ui/card.js +0 -845
package/src/router.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Meta Harness Smart Router
2
+ * Metaharness Smart Router
3
3
  * Manages honest quota/readiness tracking, benchmark matrices, RouteLLM complexity routing,
4
4
  * and cost-vs-frontier harness selection.
5
5
  *
@@ -7,409 +7,328 @@
7
7
  * - Zero hardcoded hostnames, IP addresses, or personal node topologies.
8
8
  * - Zero fabricated or simulated quota percentages: a figure is reported only when a real
9
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.
10
+ * - Candidates are the harnesses that can take work now; `resolvePool` reports why the others cannot.
11
11
  */
12
12
 
13
13
  import fs from 'node:fs';
14
14
  import path from 'node:path';
15
15
  import os from 'node:os';
16
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
- };
17
+ import { classifyTaskComplexity, selectOptimalHarness, computeEmpiricalScorecard } from '../capability/index.mjs';
18
+ import { inspectAgents } from './worker.mjs';
19
+ import { inspectNode } from './executor.mjs';
20
+ import { getModelCatalog, joinHarnessModels } from './model-catalog.mjs';
21
+ import { readReceipts, activeQuotaWalls, activeCredentialBlocks, includedBillingReceipts, recordRunReceipt } from './learner.mjs';
22
+ import { resolvePool, exclusionReason, isLocalExecutionNode } from './pool.mjs';
23
+ import { readCodexRateLimits, measuredWalls, codexWindowsByLength } from './telemetry.mjs';
24
+ import { claudeProofCurrent, claudeTokenCurrent, INCLUDED_AGENTS, readIncludedPolicy, readCodexAllowance } from './included-usage.mjs';
25
+ import { derivedDir } from './paths.mjs';
26
+ import { createModelValidator, filterPoolByModel } from './model-selection.mjs';
100
27
 
101
28
  /**
102
29
  * Helper to safely query host Total Recall CLI without assumptions
103
30
  */
104
- function runHostCli(args = []) {
31
+ function runHostCli(args = [], { captureFailure = false } = {}) {
105
32
  try {
106
33
  const totalRecallBin = process.env.TOTAL_RECALL_BIN || 'total-recall';
107
34
  const output = execFileSync(totalRecallBin, args, {
108
35
  stdio: ['pipe', 'pipe', 'pipe'],
109
- timeout: 8000,
36
+ timeout: 20000,
110
37
  encoding: 'utf8'
111
38
  });
112
39
  return output.trim();
113
- } catch {
114
- return null;
40
+ } catch (error) {
41
+ // A failing owner often explains itself as JSON on stdout. Callers that need the reason read it here.
42
+ return captureFailure ? String(error.stdout || '').trim() || null : null;
115
43
  }
116
44
  }
117
45
 
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 [];
46
+ const gigabytes = bytes => (typeof bytes === 'number' ? +(bytes / 1024 ** 3).toFixed(2) : null);
47
+ function normalizeFleetRow(row) {
48
+ return { hostname: row.hostname, ip: row.ip, online: row.online !== false, self: Boolean(row.self), telemetry: row.state || null, cpuCores: row.cores ?? null, loadAvg1m: row.loadAvg?.[0] ?? null, freeMemGB: gigabytes(row.memory?.free), totalMemGB: gigabytes(row.memory?.total), memoryUtilizationPercent: row.memory?.usedPercent ?? null };
49
+ }
50
+ function fleetTelemetry(run = runHostCli) {
125
51
  try {
126
- const parsed = JSON.parse(fs.readFileSync(ledgerPath, 'utf8'));
127
- return Array.isArray(parsed) ? parsed : [];
128
- } catch {
129
- return [];
52
+ const parsed = JSON.parse(run(['system-monitor', 'fleet', '--json']) || 'null');
53
+ if (!parsed?.rows) return { ok: false, error: 'Fleet telemetry is unavailable', nodes: [] };
54
+ return { ok: true, machines: parsed.machines, answered: parsed.answered, nodes: parsed.rows.map(normalizeFleetRow) };
55
+ } catch (error) {
56
+ return { ok: false, error: String(error.message), nodes: [] };
130
57
  }
131
58
  }
132
59
 
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 = {};
60
+ const METERED_HARNESSES = new Set(['dsh', 'hermes', 'openclaw', 'pi', 'aider', 'goose', 'openhands', 'cline']);
61
+ const METERED_TTL_MS = 5 * 60 * 1000;
62
+ const meteredCacheFile = () => path.join(derivedDir(), 'metered-quota.json');
140
63
 
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;
64
+ const FLEET_TTL_MS = 60 * 1000;
65
+ const fleetCacheFile = () => path.join(derivedDir(), 'fleet-telemetry.json');
149
66
 
67
+ /** Asking every machine takes seconds, so placement reuses an answer under a minute old. A failed read is not kept. */
68
+ function cachedFleet() {
150
69
  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
- };
70
+ const cached = JSON.parse(fs.readFileSync(fleetCacheFile(), 'utf8'));
71
+ if (Date.now() - cached.at < FLEET_TTL_MS) return cached.fleet;
72
+ } catch { /* no usable cache: read it */ }
73
+ const fleet = fleetTelemetry();
74
+ if (fleet.ok) {
75
+ try {
76
+ fs.mkdirSync(path.dirname(fleetCacheFile()), { recursive: true, mode: 0o700 });
77
+ fs.writeFileSync(fleetCacheFile(), JSON.stringify({ at: Date.now(), fleet }), { mode: 0o600 });
78
+ } catch { /* a cache that cannot be written only costs the next read */ }
79
+ }
80
+ return fleet;
81
+ }
179
82
 
180
- // 2. Discover actually installed harnesses and their real authentication state
181
- let installedState = {};
83
+ /** The balance changes slowly and costs two secret reads and two requests. The file holds figures, never a key. */
84
+ async function cachedMeteredQuota(options) {
85
+ if (!options.meteredTtlMs) return readMeteredQuota(options);
182
86
  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
- }
87
+ const cached = JSON.parse(fs.readFileSync(meteredCacheFile(), 'utf8'));
88
+ if (Date.now() - cached.at < options.meteredTtlMs) return cached.quota;
89
+ } catch { /* no usable cache: read it */ }
90
+ const quota = await readMeteredQuota(options);
91
+ try {
92
+ fs.mkdirSync(path.dirname(meteredCacheFile()), { recursive: true, mode: 0o700 });
93
+ fs.writeFileSync(meteredCacheFile(), JSON.stringify({ at: Date.now(), quota }), { mode: 0o600 });
94
+ } catch { /* a cache that cannot be written only costs the next read */ }
95
+ return quota;
96
+ }
216
97
 
217
- if (agent?.authenticated === false) {
218
- status = 'needs_auth';
98
+ /** Metered balance, from the provider. */
99
+ async function readMeteredQuota(options) {
100
+ let meteredQuota = { billingModel: 'metered', creditRemainingUSD: null, usageUSD: null, usageDailyUSD: null, usageWeeklyUSD: null, usagePercent: null, quotaNote: 'No OpenRouter key in the auth store', status: 'unconfigured' };
101
+ try {
102
+ const key = options.openRouterKey !== undefined ? options.openRouterKey : runHostCli(['auth', 'secret', 'get', 'OPENROUTER_API_KEY']);
103
+ if (key) {
104
+ const response = await (options.fetchImpl || fetch)('https://openrouter.ai/api/v1/auth/key', { headers: { Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(6000) });
105
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
106
+ const data = (await response.json()).data || {};
107
+ const usage = typeof data.usage === 'number' ? +data.usage.toFixed(4) : null;
108
+ meteredQuota = {
109
+ billingModel: 'metered', creditRemainingUSD: typeof data.limit_remaining === 'number' ? +data.limit_remaining.toFixed(4) : null,
110
+ usageUSD: usage, usageDailyUSD: data.usage_daily ?? null, usageWeeklyUSD: data.usage_weekly ?? null,
111
+ usagePercent: data.limit && usage !== null ? Math.min(100, Math.round((usage / data.limit) * 100)) : null,
112
+ quotaNote: data.limit ? `Limit $${data.limit}` : 'No spending limit on this key', quotaSource: 'openrouter', status: 'ready',
113
+ };
219
114
  }
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
- };
115
+ } catch (error) {
116
+ meteredQuota.quotaNote = `OpenRouter could not be reached: ${error.message}`;
117
+ meteredQuota.status = 'unavailable';
232
118
  }
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
-
119
+ // Per-key usage says nothing about whether the account can pay. Only the account balance does.
247
120
  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
- }
121
+ const management = options.openRouterManagementKey !== undefined ? options.openRouterManagementKey : runHostCli(['auth', 'secret', 'get', 'OPENROUTER_MANAGEMENT_KEY']);
122
+ if (management) {
123
+ const response = await (options.fetchImpl || fetch)('https://openrouter.ai/api/v1/credits', { headers: { Authorization: `Bearer ${management}` }, signal: AbortSignal.timeout(6000) });
124
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
125
+ const { total_credits: credits, total_usage: used } = (await response.json()).data || {};
126
+ if (typeof credits === 'number' && typeof used === 'number') {
127
+ meteredQuota.creditRemainingUSD = +(credits - used).toFixed(2);
128
+ meteredQuota.quotaNote = `Account balance $${meteredQuota.creditRemainingUSD} of $${credits}`;
129
+ if (credits - used <= 0) meteredQuota.status = 'exhausted';
279
130
  }
280
131
  }
281
- } catch {
282
- meteredQuota.quotaNote = 'offline — unable to reach metered provider endpoint';
132
+ } catch (error) {
133
+ meteredQuota.balanceError = `The OpenRouter balance could not be read: ${error.message}`;
283
134
  }
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
- };
135
+ return meteredQuota;
312
136
  }
313
137
 
314
138
  /**
315
- * Query Benchmarks Matrix and Local Empirical Pass Rates
139
+ * Inspect Quota and Readiness status across harnesses and host compute.
140
+ * Dynamically queries whatever host hardware, installed binaries, and auth stores the user has.
141
+ * Never fabricates or hardcodes synthetic subscription percentages.
316
142
  */
317
- export function getBenchmarks(options = {}) {
318
- const localLedger = options.ledger || readLocalRunLedger();
319
- const empirical = computeEmpiricalScorecard(localLedger);
320
- const customAdapters = getActiveAdapters().filter(a => a.custom);
143
+ export async function inspectQuotas(options = {}) {
144
+ const policy = options.policy || await readIncludedPolicy();
145
+ const quotas = {};
146
+ const remote = options.node && options.node !== 'local';
147
+ const fleet = (options.fleet || fleetTelemetry)();
148
+ const rowFor = node => fleet.nodes.find(row => [row.hostname, row.ip].includes(node) || String(row.hostname || '').split('.')[0] === node);
321
149
 
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
150
+ if (remote) {
151
+ const row = rowFor(options.node);
152
+ if (!row || row.freeMemGB === null) throw new Error(`No telemetry from mesh node ${options.node}${fleet.ok ? '' : `: ${fleet.error}`}`);
153
+ quotas.system = { ...row, node: options.node };
154
+ } else {
155
+ // os.freemem() on macOS excludes reclaimable memory, so the monitor's figure wins when it answered.
156
+ const totalMemBytes = os.totalmem(), freeMemBytes = os.freemem();
157
+ const self = fleet.nodes.find(row => row.self);
158
+ quotas.system = {
159
+ hostname: os.hostname(), platform: os.platform(), arch: os.arch(), cpuCores: os.cpus()?.length || 1,
160
+ loadAvg1m: parseFloat((os.loadavg()?.[0] || 0).toFixed(2)),
161
+ totalMemGB: parseFloat((totalMemBytes / 1024 ** 3).toFixed(2)), freeMemGB: parseFloat((freeMemBytes / 1024 ** 3).toFixed(2)),
162
+ memoryUtilizationPercent: Math.round(((totalMemBytes - freeMemBytes) / totalMemBytes) * 100), node: 'local',
163
+ ...(typeof self?.freeMemGB === 'number' ? { freeMemGB: self.freeMemGB, totalMemGB: self.totalMemGB, memoryUtilizationPercent: self.memoryUtilizationPercent } : {}),
330
164
  };
331
165
  }
332
166
 
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
- };
167
+ // Harness state comes from the selected machine. Quota walls are this machine's receipts.
168
+ const claudeToken = policy.enabled && claudeTokenCurrent(policy);
169
+ const claudePlan = policy.enabled && !claudeToken ? policy.claudePlan?.organization : undefined;
170
+ const inspected = remote ? await (options.inspectNodeFn || inspectNode)(options.node) :
171
+ await (options.inspect || inspectAgents)({ env: process.env, cwd: options.cwd, claudePlan });
172
+ const codexLimits = remote ? null : readCodexRateLimits();
173
+ const receipts = remote ? [] : (policy.enabled ? includedBillingReceipts : runs => runs)(await (options.receipts || readReceipts)());
174
+ const walls = remote ? {} : { ...activeQuotaWalls(receipts), ...(!policy.enabled ? measuredWalls(codexLimits) : {}) };
175
+ const metered = METERED_HARNESSES;
176
+
177
+ const blocks = activeCredentialBlocks(receipts);
178
+ for (const installed of inspected.agents || []) {
179
+ const agent = policy.enabled && !remote && installed.id === 'claude' && !claudePlan ?
180
+ { ...installed, authenticated: claudeToken || claudeProofCurrent(policy) } : installed;
181
+ const wall = walls[agent.id];
182
+ const block = blocks[agent.id];
183
+ const policyBlocked = policy.enabled && !INCLUDED_AGENTS.includes(agent.id);
184
+ const explicitOpenRouter = !remote && Boolean(policy.openRouter?.[agent.id]);
185
+ const reason = policyBlocked ? (explicitOpenRouter ? 'available through explicit OpenRouter dispatch' : 'outside the included usage route') : exclusionReason(agent, wall, block);
186
+ let status = 'ready';
187
+ if (!agent.installed) status = 'not_installed';
188
+ else if (policyBlocked) status = 'blocked';
189
+ else if (agent.authenticated === false || block) status = 'needs_auth';
190
+ else if (agent.blockedBy) status = 'blocked';
191
+ else if (wall) status = 'exhausted';
192
+ else if (agent.authenticated === 'unknown') status = 'unverified';
193
+ const quota = {
194
+ installed: Boolean(agent.installed), version: agent.version || null,
195
+ billingModel: policy.enabled && !remote && !claudePlan && !claudeToken && agent.id === 'claude' ? 'included-api-credits' :
196
+ agent.id === 'ollama' ? 'local' : metered.has(agent.id) ? 'metered' : 'subscription',
197
+ rolling5hUsedPercent: null, weeklyUsedPercent: null, usagePercent: null,
198
+ quotaSource: 'none', quotaNote: reason || 'No usage figure is available from this harness', status,
199
+ ...(explicitOpenRouter ? { explicitOpenRouter: true } : {}),
200
+ ...(wall ? { resetsAt: wall.until, wallMessage: wall.message } : {}),
201
+ };
202
+ if (agent.id === 'codex' && codexLimits) {
203
+ const { fiveHour, weekly } = codexWindowsByLength(codexLimits);
204
+ quota.rolling5hUsedPercent = fiveHour?.used_percent ?? null;
205
+ quota.weeklyUsedPercent = weekly?.used_percent ?? null;
206
+ if (codexLimits.primary || codexLimits.secondary) quota.usagePercent = Math.max(quota.rolling5hUsedPercent ?? 0, quota.weeklyUsedPercent ?? 0);
207
+ quota.quotaSource = 'codex-session-log';
208
+ quota.observedAt = codexLimits.observedAt;
209
+ if (!reason) quota.quotaNote = `Measured in the Codex session log at ${codexLimits.observedAt}`;
347
210
  }
211
+ quotas[agent.id] = quota;
348
212
  }
349
213
 
214
+ const meteredQuota = options.skipMetered || policy.enabled
215
+ ? { billingModel: 'metered', status: 'not-read', quotaNote: 'Not read: no metered harness is in this route pool' }
216
+ : await cachedMeteredQuota(options);
217
+ quotas.metered = meteredQuota;
218
+ if (meteredQuota.status === 'exhausted') for (const id of ['dsh', 'hermes', 'pi']) {
219
+ if (quotas[id]?.installed && !['needs_auth', 'blocked'].includes(quotas[id].status)) Object.assign(quotas[id], { status: 'exhausted', quotaNote: `Bills OpenRouter. ${meteredQuota.quotaNote}` });
220
+ }
221
+
222
+ return { ok: true, timestamp: new Date().toISOString(), node: options.node || 'local', fleet: { ok: fleet.ok, error: fleet.error, machines: fleet.machines, answered: fleet.answered, nodes: fleet.nodes }, quotas };
223
+ }
224
+
225
+ /** Models with sourced figures, the leaderboards they came from, and pass rates measured on this machine. */
226
+ export async function getBenchmarks(options = {}) {
227
+ const catalog = getModelCatalog();
228
+ const receipts = options.ledger || await readReceipts();
350
229
  return {
351
- ok: true,
352
- updatedAt: new Date().toISOString(),
353
- matrix: combined
230
+ ok: true, updatedAt: catalog.updatedAt, synced: Boolean(catalog.updatedAt),
231
+ note: catalog.updatedAt ? undefined : 'Run `total-recall meta-harness maintenance --models` to fetch real figures.',
232
+ sources: catalog.sources, models: joinHarnessModels(catalog), leaderboards: catalog.leaderboards,
233
+ local: computeEmpiricalScorecard(receipts),
354
234
  };
355
235
  }
356
236
 
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());
237
+ /** Ask the decision plugin to classify. Its failure is reported; the caller sees which classifier answered. */
238
+ export function classifyWithDecision(task, run = args => runHostCli(args, { captureFailure: true })) {
239
+ const questions = { complexity: { type: 'choice', instructions: 'How demanding is this software engineering task for a coding agent?', criteria: { local: 'A small mechanical change a local model can make.', budget: 'Routine engineering with a clear path.', frontier: 'Architecture, security, or work across many files.' } } };
240
+ const output = run(['decision', 'run', '--state', JSON.stringify({ task: task.slice(0, 2000) }), '--questions', JSON.stringify(questions), '--json']);
241
+ if (!output) throw new Error('The decision plugin did not answer');
242
+ const parsed = JSON.parse(output);
243
+ if (parsed.ok === false) throw new Error(parsed.error || 'The decision plugin reported a failure');
244
+ const answer = parsed.answers?.complexity ?? parsed.decision?.answers?.complexity ?? parsed.result?.complexity;
245
+ const tier = typeof answer === 'string' ? answer : answer?.choice;
246
+ if (!['local', 'budget', 'frontier'].includes(tier)) throw new Error('The decision plugin returned no usable tier');
247
+ return { tier, confidence: answer?.confidence ?? null };
248
+ }
365
249
 
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) {
250
+ /** Local-tier work goes to the online machine with the most free memory that reported telemetry. */
251
+ export function placeLocalWork(fleet = {}) {
252
+ const nodes = (fleet.nodes || []).filter(node => node.online !== false && typeof node.freeMemGB === 'number');
253
+ if (!nodes.length) return null;
254
+ const best = nodes.reduce((a, b) => (b.freeMemGB > a.freeMemGB ? b : a));
255
+ return { node: best.hostname, freeMemGB: best.freeMemGB };
256
+ }
257
+
258
+ export async function routeTask(taskDescription, options = {}) {
259
+ const policy = await readIncludedPolicy();
260
+ let complexity = classifyTaskComplexity(taskDescription, options);
261
+ let classifier = { source: 'heuristic' };
262
+ if (options.jev && !policy.enabled) {
370
263
  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;
264
+ const decided = classifyWithDecision(taskDescription, options.decisionRun);
265
+ complexity = { ...complexity, tier: decided.tier, isFrontierRecommended: decided.tier === 'frontier', isLocalRecommended: decided.tier === 'local' };
266
+ classifier = { source: 'decision', confidence: decided.confidence };
267
+ } catch (error) {
268
+ classifier = { source: 'heuristic', decisionError: String(error.message).slice(0, 300) };
382
269
  }
383
270
  }
384
-
385
- const routing = selectOptimalHarness(taskDescription, available, quotas, {
386
- ...options,
387
- empiricalScorecard
271
+ // Plan-only routing on a selected node chooses from that node's harnesses, not this machine's.
272
+ const remote = options.node && !isLocalExecutionNode(options.node);
273
+ const inspected = remote ? (options.inspectNodeFn || inspectNode)(options.node) : null;
274
+ const scoped = remote ? { ...options, inspectNodeFn: () => inspected, inspect: () => inspected } : options;
275
+ // One inspection serves the pool and the quota report. Read only what this decision uses:
276
+ // fleet telemetry places local work, and the balance matters only to a metered harness.
277
+ const shared = scoped.inspect ? null : inspectAgents({ env: process.env });
278
+ const lean = shared ? { ...scoped, inspect: () => shared } : scoped;
279
+ const [resolved, receipts] = await Promise.all([resolvePool({ ...lean, policy }), readReceipts()]);
280
+ // A requested model narrows the pool to the harnesses that can run it, and says why the others cannot.
281
+ const { pool, selection: modelSelection } = options.model === undefined ? { pool: resolved, selection: null }
282
+ : filterPoolByModel(resolved, options.model, options.modelValidator || createModelValidator({ local: !remote }));
283
+ const quotaReport = await inspectQuotas({
284
+ ...lean,
285
+ policy,
286
+ meteredTtlMs: METERED_TTL_MS,
287
+ skipMetered: policy.enabled || (lean.openRouterKey === undefined && !pool.ready.some(h => METERED_HARNESSES.has(h.id))),
288
+ ...(remote || lean.fleet ? {} : { fleet: complexity.tier === 'local' ? cachedFleet : () => ({ ok: false, error: 'Not read: this route places no local work', nodes: [] }) }),
388
289
  });
389
-
290
+ const quotas = quotaReport.quotas;
291
+ // No ready harness means none can take the task. The ranking reads an empty list as the whole
292
+ // catalog, so a node whose only ready harness was walled for quota chose an OpenRouter harness
293
+ // outside the included policy, with no credit behind it.
294
+ const rank = ready => (ready.length
295
+ ? selectOptimalHarness(taskDescription, ready.map(h => h.id), quotas, { ...options, tierOverride: complexity.tier, empiricalScorecard: computeEmpiricalScorecard(receipts) })
296
+ : { selected: null, candidates: [] });
297
+ let excluded = pool.excluded;
298
+ let routing = rank(pool.ready);
299
+ // Quota walls come from launches this machine saw refused. With none recorded here, a route kept
300
+ // choosing a Codex that was out of quota, and the selected-harness write gate then blocked every
301
+ // other harness. Before choosing Codex, ask it for its allowance (no turn), and record a quota
302
+ // answer as the wall a refused launch records (A-124), so later routes skip it without asking.
303
+ if (policy.enabled && !remote && routing.selected === 'codex') {
304
+ const allowance = await (options.codexAllowance || readCodexAllowance)(options.cwd || process.cwd());
305
+ if (allowance?.ok === false && allowance.failureKind === 'quota') {
306
+ const resetsAt = allowance.resetsAt || null;
307
+ try {
308
+ await (options.recordReceipt || recordRunReceipt)({ harness: 'codex', role: 'Route', task: String(taskDescription).slice(0, 200),
309
+ success: false, failureKind: 'quota', billingMode: 'included', error: allowance.error, resetsAt });
310
+ } catch { /* the route still skips Codex; only the next route asks again */ }
311
+ excluded = [...excluded, { harness: 'codex', reason: resetsAt ? `out of quota until ${resetsAt}` : 'out of quota', failureKind: 'quota', resetsAt }];
312
+ quotas.codex = { ...quotas.codex, status: 'exhausted', wallMessage: allowance.error, ...(resetsAt ? { resetsAt } : {}) };
313
+ routing = rank(pool.ready.filter(h => h.id !== 'codex'));
314
+ }
315
+ }
390
316
  const selectedQuota = quotas[routing.selected] || {};
391
- const usage = selectedQuota.usagePercent ?? null;
392
317
  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
-
318
+ if (policy.enabled && options.jev) warnings.push('Included usage policy uses the local task classifier.');
319
+ if (typeof selectedQuota.usagePercent === 'number' && selectedQuota.usagePercent > 85) warnings.push(`${routing.selected} is at ${selectedQuota.usagePercent}% measured usage.`);
320
+ if (selectedQuota.status === 'unverified') warnings.push(`${routing.selected} has no login probe; only a completed run proves it works.`);
321
+ if (selectedQuota.billingModel === 'metered') warnings.push(`${routing.selected} bills per token.`);
322
+ if (!routing.selected) warnings.push(modelSelection ? `No harness that can run ${options.model} can take this task right now.` : 'No harness can take this task right now.');
323
+ const selectedModel = modelSelection?.checks.find(check => check.harness === routing.selected);
324
+ if (selectedModel?.source === 'unverified') warnings.push(selectedModel.note);
400
325
  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
326
+ ok: Boolean(routing.selected), task: taskDescription, classifier, complexity,
327
+ selected: routing.selected, tier: complexity.tier, model: options.model ?? null, ...(modelSelection ? { modelSelection } : {}), candidates: routing.candidates, excluded,
328
+ ...(policy.enabled && !routing.selected ? { deferred: excluded.find(row => row.failureKind === 'quota') || null } : {}),
329
+ placement: complexity.tier === 'local' ? placeLocalWork(quotaReport.fleet) : null,
330
+ scoring: 'Adapter quality and cost scores are configured priors, adjusted by pass rates measured on this machine.',
331
+ quotaSnapshot: { selectedHarnessStatus: selectedQuota.status || null, selectedHarnessUsage: selectedQuota.usagePercent ?? null, freeMemGB: quotas.system.freeMemGB ?? null },
332
+ warnings,
414
333
  };
415
334
  }