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/alerts.mjs
CHANGED
|
@@ -1,23 +1,229 @@
|
|
|
1
|
+
/** Operator alerts go through the alerts plugin. A failed send is reported as failed. */
|
|
2
|
+
import { execFileSync } from 'node:child_process';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { randomUUID } from 'node:crypto';
|
|
6
|
+
import { FileLeaseStore } from '@gregiteen/ssss-cli/leases';
|
|
7
|
+
import { readReceipts, activeQuotaWalls } from './learner.mjs';
|
|
8
|
+
import { readSessionUsageAnalytics } from './telemetry.mjs';
|
|
9
|
+
import { configDir } from './paths.mjs';
|
|
10
|
+
|
|
11
|
+
const SEVERITY = { info: 'info', warning: 'high', high: 'high', critical: 'critical' };
|
|
12
|
+
const RECOVERY_WINDOW_MS = 15 * 60_000;
|
|
13
|
+
|
|
14
|
+
function velocityAlertEventId(now = Date.now()) {
|
|
15
|
+
return `meta-harness-runaway-${Math.floor(now / (15 * 60_000))}`;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export async function priorityCacheProjects({ add, remove } = {}, store) {
|
|
19
|
+
if (!store) {
|
|
20
|
+
const { PluginStateStore } = await import('./ssss-store.mjs');
|
|
21
|
+
store = new PluginStateStore(path.join(configDir(), 'priority-cache.json'), 'meta-harness');
|
|
22
|
+
}
|
|
23
|
+
const state = store.read({ roots: [] });
|
|
24
|
+
if (!Array.isArray(state?.roots) || !state.roots.every(root => typeof root === 'string' && path.isAbsolute(root) && root !== path.parse(root).root)) {
|
|
25
|
+
throw new Error('Invalid Metaharness priority cache configuration.');
|
|
26
|
+
}
|
|
27
|
+
let roots = state.roots;
|
|
28
|
+
if (add !== undefined || remove !== undefined) {
|
|
29
|
+
if (process.env.TR_META_HARNESS_RUN) throw new Error('Only the operator may change cache priority.');
|
|
30
|
+
if (add !== undefined && remove !== undefined) throw new Error('Select either --add or --remove.');
|
|
31
|
+
const candidate = add ?? remove;
|
|
32
|
+
if (!path.isAbsolute(candidate)) throw new Error('Specify an absolute project checkout path.');
|
|
33
|
+
const root = add === undefined ? path.resolve(candidate) : fs.realpathSync(candidate);
|
|
34
|
+
if (add !== undefined && !fs.existsSync(path.join(root, '.git'))) throw new Error('Priority cache requires a Git checkout root.');
|
|
35
|
+
roots = add === undefined ? roots.filter(entry => entry !== root) : [...new Set([...roots, root])];
|
|
36
|
+
if (roots.length !== state.roots.length) store.write({ ...state, roots });
|
|
37
|
+
}
|
|
38
|
+
return { ok: true, roots };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const usageTotal = usage => (Number(usage?.inputTokens) || 0) + (Number(usage?.outputTokens) || 0);
|
|
42
|
+
|
|
1
43
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
44
|
+
* Metaharness job records are the authoritative list of background work on this machine. Each job
|
|
45
|
+
* reports its start times, harness session IDs, whether it is internal reasoning, and the largest usage
|
|
46
|
+
* snapshot it reported in the window (Codex snapshots are cumulative; internal jobs are single-turn).
|
|
4
47
|
*/
|
|
48
|
+
export function readMetaharnessJobs({ now = Date.now(), windowMs = 3600_000, dir = path.join(configDir(), 'jobs') } = {}) {
|
|
49
|
+
const since = now - windowMs;
|
|
50
|
+
let names;
|
|
51
|
+
try { names = fs.readdirSync(dir); } catch (error) { if (error.code === 'ENOENT') return []; throw error; }
|
|
52
|
+
const jobs = [];
|
|
53
|
+
for (const name of names) {
|
|
54
|
+
if (!name.endsWith('.events.jsonl')) continue;
|
|
55
|
+
const file = path.join(dir, name);
|
|
56
|
+
try { if (fs.statSync(file).mtimeMs < since) continue; } catch { continue; }
|
|
57
|
+
let raw;
|
|
58
|
+
try { raw = fs.readFileSync(file, 'utf8'); } catch { continue; }
|
|
59
|
+
const id = name.slice(0, -'.events.jsonl'.length);
|
|
60
|
+
const starts = [], sessionIds = new Set();
|
|
61
|
+
let tokens1h = 0;
|
|
62
|
+
for (const line of raw.split('\n')) {
|
|
63
|
+
if (!line) continue;
|
|
64
|
+
let event;
|
|
65
|
+
try { event = JSON.parse(line); } catch { continue; }
|
|
66
|
+
const at = Date.parse(event.t);
|
|
67
|
+
// Only agent launches count. The job record's own start and the copy of a launch mirrored into the
|
|
68
|
+
// owner job's log are not runs: counting them made one launch two and tripped normal work (2026-12-01).
|
|
69
|
+
if (event.kind === 'start' && Number.isFinite(at) && !event.record && !event.mirror) starts.push(at);
|
|
70
|
+
for (const key of ['sessionId', 'session', 'rootSessionId']) {
|
|
71
|
+
if (typeof event[key] === 'string' && event[key]) sessionIds.add(event[key]);
|
|
72
|
+
}
|
|
73
|
+
const usage = event.kind === 'usage' ? event : event.kind === 'finish' ? event.usage : null;
|
|
74
|
+
if (usage && at >= since && at <= now) tokens1h = Math.max(tokens1h, usageTotal(usage));
|
|
75
|
+
}
|
|
76
|
+
let request = null;
|
|
77
|
+
try { request = JSON.parse(fs.readFileSync(path.join(dir, `${id}.session.json`), 'utf8')).request; } catch { /* a job without a saved request */ }
|
|
78
|
+
jobs.push({ id, internal: request?.internalReasoning === true, starts, sessionIds: [...sessionIds], tokens1h });
|
|
79
|
+
}
|
|
80
|
+
return jobs;
|
|
81
|
+
}
|
|
5
82
|
|
|
6
|
-
|
|
83
|
+
export function readBreakerUsage({ now = Date.now(), jobsDir, claudeHome, codexHome } = {}) {
|
|
84
|
+
const jobs = readMetaharnessJobs({ now, ...(jobsDir ? { dir: jobsDir } : {}) });
|
|
85
|
+
const backgroundSessionIds = new Set(jobs.flatMap(job => job.sessionIds));
|
|
86
|
+
return { ...readSessionUsageAnalytics({ now, claudeHome, codexHome, windowMs: 3600_000, rollingHour: true, backgroundSessionIds }), jobs };
|
|
87
|
+
}
|
|
7
88
|
|
|
8
|
-
export
|
|
9
|
-
|
|
89
|
+
export const DEFAULT_BREAKER_LIMITS = Object.freeze({
|
|
90
|
+
maxInternalRunsPer15m: 15,
|
|
91
|
+
maxDispatchesPer15m: 40,
|
|
92
|
+
maxHourlyTokenBurn: 15_000_000,
|
|
93
|
+
});
|
|
10
94
|
|
|
11
|
-
|
|
95
|
+
export async function notifyAlert({ title = 'Metaharness', message = '', severity = 'info', eventId, dryRun = false } = {}) {
|
|
96
|
+
const args = ['alerts', 'send', '--title', title, '--message', message, '--severity', SEVERITY[severity] || 'info', '--source', 'meta-harness'];
|
|
97
|
+
if (eventId) args.push('--event-id', eventId);
|
|
98
|
+
if (dryRun) args.push('--dry-run');
|
|
12
99
|
try {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
100
|
+
execFileSync(process.env.TOTAL_RECALL_BIN || 'total-recall', args, { stdio: 'pipe', timeout: 15000 });
|
|
101
|
+
return { ok: true, title };
|
|
102
|
+
} catch (error) {
|
|
103
|
+
return { ok: false, title, error: String(error.stderr || error.message).slice(0, 300) };
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** One alert across the admission guard and monitor while an incident stays open. */
|
|
108
|
+
export async function observeVelocityIncident(tripped, alert, { store, leases, notify = notifyAlert, now = Date.now(), dryRun = false } = {}) {
|
|
109
|
+
if (dryRun) return tripped ? notify({ ...alert, eventId: velocityAlertEventId(now), dryRun: true }) : null;
|
|
110
|
+
if (!store) {
|
|
111
|
+
const { PluginStateStore } = await import('./ssss-store.mjs');
|
|
112
|
+
store = new PluginStateStore(path.join(configDir(), 'velocity-incident.json'), 'meta-harness');
|
|
113
|
+
}
|
|
114
|
+
if (!tripped && !store.read(null)) return null;
|
|
115
|
+
leases ||= new FileLeaseStore(path.join(configDir(), 'incident-leases'));
|
|
116
|
+
const lease = await leases.acquire({ workspace_id: 'local', target: 'velocity', principal_id: 'meta-harness', operation_id: 'alert' }, 60_000)
|
|
117
|
+
.catch(error => { if (error.message === 'Lease conflict.') return null; throw error; });
|
|
118
|
+
if (!lease) return null;
|
|
119
|
+
try {
|
|
120
|
+
let active = store.read(null);
|
|
121
|
+
if (!tripped) {
|
|
122
|
+
if (active && active.quietSince === undefined) store.write({ ...active, quietSince: now });
|
|
123
|
+
else if (active && now - active.quietSince >= RECOVERY_WINDOW_MS) store.write(null);
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
if (!active || active.quietSince !== undefined) {
|
|
127
|
+
active = active ? { eventId: active.eventId, notified: active.notified }
|
|
128
|
+
: { eventId: `meta-harness-runaway-${randomUUID()}`, notified: false };
|
|
129
|
+
store.write(active);
|
|
130
|
+
}
|
|
131
|
+
if (active.notified) return null;
|
|
132
|
+
const result = await notify({ ...alert, eventId: active.eventId });
|
|
133
|
+
if (result?.ok) store.write({ ...active, notified: true });
|
|
134
|
+
return result;
|
|
135
|
+
} finally {
|
|
136
|
+
await leases.release(lease);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* The breakers limit background work only: Metaharness jobs, marker-tagged internal sessions and their
|
|
142
|
+
* subagents. The operator's interactive sessions are reported in the metrics and never trip a limit.
|
|
143
|
+
* They read only the 15-minute and 1-hour windows, so older sessions are never parsed.
|
|
144
|
+
*/
|
|
145
|
+
export function evaluateRunawayBreakers({ analytics = readBreakerUsage(), limits = DEFAULT_BREAKER_LIMITS } = {}) {
|
|
146
|
+
const now = Date.parse(analytics?.observedAt) || Date.now();
|
|
147
|
+
const in15m = at => Number.isFinite(at) && at >= now - 15 * 60_000 && at <= now;
|
|
148
|
+
const jobs = analytics?.jobs || [];
|
|
149
|
+
const sessions = analytics?.rolling?.sessions || [];
|
|
150
|
+
const jobSessions = new Set(jobs.flatMap(job => job.sessionIds));
|
|
151
|
+
const loggedSessions = new Set(sessions.map(session => session.id).filter(Boolean));
|
|
152
|
+
// Marker-tagged sessions that no job record names were started outside Metaharness; they still count.
|
|
153
|
+
const unlinkedInternal15m = sessions.filter(session => session.internal && !session.subagent && !jobSessions.has(session.id) && in15m(session.startedAt)).length;
|
|
154
|
+
const starts15m = job => job.starts.filter(in15m).length;
|
|
155
|
+
const internal15m = jobs.filter(job => job.internal).reduce((sum, job) => sum + starts15m(job), 0) + unlinkedInternal15m;
|
|
156
|
+
const background15m = jobs.reduce((sum, job) => sum + starts15m(job), 0) + unlinkedInternal15m;
|
|
157
|
+
// Ephemeral jobs (internal reasoning) leave no harness log, so their own reported usage counts instead.
|
|
158
|
+
const unloggedJobTokens1h = jobs.filter(job => !job.sessionIds.some(id => loggedSessions.has(id))).reduce((sum, job) => sum + job.tokens1h, 0);
|
|
159
|
+
const tokens1h = (analytics?.rolling?.backgroundTokens || 0) + unloggedJobTokens1h;
|
|
160
|
+
const interactiveTokens1h = analytics?.rolling?.interactiveTokens || 0;
|
|
161
|
+
const reasons = [];
|
|
162
|
+
if (internal15m > limits.maxInternalRunsPer15m) {
|
|
163
|
+
reasons.push(`internal runs in 15m (${internal15m}) exceeded limit (${limits.maxInternalRunsPer15m})`);
|
|
164
|
+
}
|
|
165
|
+
if (background15m > limits.maxDispatchesPer15m) {
|
|
166
|
+
reasons.push(`background runs in 15m (${background15m}) exceeded limit (${limits.maxDispatchesPer15m})`);
|
|
167
|
+
}
|
|
168
|
+
if (tokens1h > limits.maxHourlyTokenBurn) {
|
|
169
|
+
reasons.push(`1h background token burn (${tokens1h.toLocaleString()}) exceeded limit (${limits.maxHourlyTokenBurn.toLocaleString()})`);
|
|
170
|
+
}
|
|
171
|
+
return {
|
|
172
|
+
tripped: reasons.length > 0,
|
|
173
|
+
reasons,
|
|
174
|
+
metrics: { internal15m, background15m, tokens1h, unloggedJobTokens1h, interactiveTokens1h, jobs1h: jobs.length },
|
|
175
|
+
limits,
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Enforce runaway velocity circuit breaker before starting a dispatch or background reasoning run.
|
|
181
|
+
* Sends an immediate critical operator alert for a new incident and throws when tripped.
|
|
182
|
+
*/
|
|
183
|
+
export async function enforceVelocityCircuitBreaker({ kind = 'dispatch', analytics, limits, notify = notifyAlert } = {}) {
|
|
184
|
+
if (process.env.TR_DISABLE_CIRCUIT_BREAKER === '1') return { ok: true, skipped: true };
|
|
185
|
+
const check = evaluateRunawayBreakers({ analytics: analytics ?? await readBreakerUsage(), limits });
|
|
186
|
+
if (!check.tripped) return { ok: true, ...check };
|
|
187
|
+
const alert = {
|
|
188
|
+
title: `Metaharness Circuit Breaker Tripped (${kind})`,
|
|
189
|
+
message: `Blocked ${kind}: ${check.reasons.join('; ')}.`,
|
|
190
|
+
severity: 'critical',
|
|
191
|
+
};
|
|
192
|
+
try { await observeVelocityIncident(true, alert, { notify }); }
|
|
193
|
+
catch (error) {
|
|
194
|
+
// State errors must never bypass enforcement or the first critical notification.
|
|
195
|
+
try { await notify({ ...alert, eventId: velocityAlertEventId() }); } catch { /* the guard still blocks */ }
|
|
196
|
+
check.notificationError = error.message;
|
|
197
|
+
}
|
|
198
|
+
throw Object.assign(new Error(`Metaharness circuit breaker tripped: ${check.reasons.join('; ')}`), {
|
|
199
|
+
code: 'CIRCUIT_BREAKER_TRIPPED',
|
|
200
|
+
failureKind: 'circuit-breaker',
|
|
201
|
+
breaker: check,
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** Alert on quota walls, measured usage over threshold, and runaway velocity/token burn. */
|
|
206
|
+
export async function checkAlerts({ quotas = {}, threshold = 85, dryRun = false, analytics } = {}) {
|
|
207
|
+
const walls = activeQuotaWalls(await readReceipts());
|
|
208
|
+
const candidates = Object.entries(walls).map(([harness, wall]) => ({
|
|
209
|
+
title: `Metaharness: ${harness} is out of quota`,
|
|
210
|
+
message: `${wall.message || 'Quota wall observed.'} Routing avoids ${harness} until ${wall.until}.`,
|
|
211
|
+
severity: 'warning', eventId: `meta-harness-wall-${harness}-${wall.until}`,
|
|
212
|
+
}));
|
|
213
|
+
for (const [id, quota] of Object.entries(quotas)) {
|
|
214
|
+
if (typeof quota?.usagePercent === 'number' && quota.usagePercent > threshold && quota.billingModel !== 'local') candidates.push({
|
|
215
|
+
title: `Metaharness: ${id} is at ${quota.usagePercent}%`, message: `Measured usage on ${id} is above ${threshold}%.`,
|
|
216
|
+
severity: 'warning', eventId: `meta-harness-usage-${id}-${new Date().toISOString().slice(0, 10)}`,
|
|
17
217
|
});
|
|
18
|
-
return { ok: true, dispatchedVia: 'total-recall-alerts' };
|
|
19
|
-
} catch {
|
|
20
|
-
// Fallback: console log without crashing
|
|
21
|
-
return { ok: true, dispatchedVia: 'fallback-logged', logged: { title, message, severity } };
|
|
22
218
|
}
|
|
219
|
+
const breaker = evaluateRunawayBreakers({ analytics: analytics ?? await readBreakerUsage() });
|
|
220
|
+
const sent = [];
|
|
221
|
+
for (const alert of candidates) sent.push(await notifyAlert({ ...alert, dryRun }));
|
|
222
|
+
const velocity = await observeVelocityIncident(breaker.tripped, {
|
|
223
|
+
title: 'Metaharness: Runaway usage spike detected',
|
|
224
|
+
message: breaker.reasons.join('; '),
|
|
225
|
+
severity: 'critical',
|
|
226
|
+
}, { dryRun });
|
|
227
|
+
if (velocity) sent.push(velocity);
|
|
228
|
+
return { ok: sent.every(row => row.ok), threshold, walls, breaker, alerts: sent };
|
|
23
229
|
}
|
package/src/cascade.mjs
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Verification-gated escalation: run the routed harness on its own branch, run the gate,
|
|
3
|
+
* and hand any failure to a stronger harness with the diagnostic.
|
|
4
|
+
*/
|
|
5
|
+
import { evaluateGateCascade } from '../capability/index.mjs';
|
|
6
|
+
import { dispatchWithReceipt } from './dispatch.mjs';
|
|
7
|
+
import { notifyAlert } from './alerts.mjs';
|
|
8
|
+
import { recordRunReceipt } from './learner.mjs';
|
|
9
|
+
import { resolvePool, localExecutionNode } from './pool.mjs';
|
|
10
|
+
import { routeTask } from './router.mjs';
|
|
11
|
+
import { runQualityGate } from './gate.mjs';
|
|
12
|
+
import { isGitRepo, isDirty, gitPointerProblem, pushBranch, createWorktree, removeWorktree, commitAll, linkDependencies, deleteBranch, provideDependencies } from './worktree.mjs';
|
|
13
|
+
import { forwardRemoteOperation } from './remote-operation.mjs';
|
|
14
|
+
import { queueIncludedJob } from './usage-queue.mjs';
|
|
15
|
+
import { configDir } from './paths.mjs';
|
|
16
|
+
import path from 'node:path';
|
|
17
|
+
import { cancellationResult, getActiveAdapters } from './worker.mjs';
|
|
18
|
+
import { executeCodeReview, reviewBlocksPush } from './review.mjs';
|
|
19
|
+
import { sessionOptions } from './session/run.mjs';
|
|
20
|
+
import fs from 'node:fs';
|
|
21
|
+
import { jobPaths } from './control.mjs';
|
|
22
|
+
|
|
23
|
+
// A routed attempt gets time in proportion to the work the route measured (A-101); --timeout-ms overrides.
|
|
24
|
+
export const ROUTED_TIMEOUT_MS = { local: 15 * 60_000, budget: 30 * 60_000, frontier: 90 * 60_000 };
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* What Metaharness itself recorded about this job, for the reviewer (A-122): questions the agent
|
|
28
|
+
* asked, the operator's replies, the goal check and the gate. The reviewer sees only the diff
|
|
29
|
+
* otherwise and cannot verify claims about how the job ran.
|
|
30
|
+
*/
|
|
31
|
+
export function reviewEvidence(jobId, attempt = {}) {
|
|
32
|
+
const evidence = { goalCheck: attempt.goalCheck ?? null, gate: attempt.gate ? { status: attempt.gate.status, passed: attempt.gate.passed } : null, questions: [], replies: [] };
|
|
33
|
+
if (!jobId) return evidence;
|
|
34
|
+
let paths;
|
|
35
|
+
try { paths = jobPaths(jobId); } catch { return evidence; }
|
|
36
|
+
const lines = file => { try { return fs.readFileSync(file, 'utf8').split('\n').filter(Boolean).map(l => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean); } catch { return []; } };
|
|
37
|
+
for (const e of lines(paths.events)) if (e.kind === 'question') evidence.questions.push({ requestId: e.requestId, questions: e.questions || e.text, source: e.source, t: e.t });
|
|
38
|
+
for (const c of lines(paths.inbox)) if (c.type === 'reply' || c.command === 'reply') evidence.replies.push({ requestId: c.requestId || null, text: c.text, t: c.t });
|
|
39
|
+
return evidence;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function executeRoutedTask(task, options = {}) {
|
|
43
|
+
if (cancellationResult()) return cancellationResult();
|
|
44
|
+
const remote = await forwardRemoteOperation('route', task, { ...options, execute: true });
|
|
45
|
+
if (remote) return remote;
|
|
46
|
+
if (options.node) localExecutionNode(options);
|
|
47
|
+
const cwd = options.cwd || process.cwd();
|
|
48
|
+
// The requested model travels with the controls, so every attempt and a queued replay run it.
|
|
49
|
+
const controls = { ...sessionOptions({ ...options, cwd }), ...(options.model !== undefined ? { model: options.model } : {}) };
|
|
50
|
+
if (!isGitRepo(cwd)) throw new Error('Routed execution writes on its own branch, so it must run inside a git repository');
|
|
51
|
+
// A chosen harness is the operator's decision. Nothing else is tried after it, so a run can never move to
|
|
52
|
+
// another harness's billing; dispatch still applies every admission check.
|
|
53
|
+
if (options.agent !== undefined && !getActiveAdapters().some(adapter => adapter.id === options.agent)) throw new Error(`Unknown harness ${options.agent}`);
|
|
54
|
+
const chosen = options.agent === undefined ? null : { ok: true, selected: options.agent, tier: 'frontier', reason: 'Chosen by the operator' };
|
|
55
|
+
const route = options.route || chosen || await routeTask(task, options);
|
|
56
|
+
const replay = { kind: 'route', gate: options.gate === true, gateOptions: options.gateOptions, controls };
|
|
57
|
+
if (!route.selected && route.deferred) {
|
|
58
|
+
const blocked = { ok: false, failureKind: 'quota', error: 'The included usage allowance is exhausted.', resetsAt: route.deferred.resetsAt };
|
|
59
|
+
const job = await queueIncludedJob({ agent: route.deferred.harness, cwd, prompt: task }, blocked,
|
|
60
|
+
{ role: 'Routed', replay, launchPrevented: true });
|
|
61
|
+
return { ...blocked, route, attempts: [], queued: true, queueId: job.id };
|
|
62
|
+
}
|
|
63
|
+
if (!route.selected) return { ok: false, route, attempts: [], error: 'No harness can take this task right now.' };
|
|
64
|
+
const node = localExecutionNode(options, route.placement);
|
|
65
|
+
const pool = chosen ? [options.agent] : options.pool || (await resolvePool(options)).ready.map(h => h.id);
|
|
66
|
+
const maxAttempts = chosen ? 1 : options.maxAttempts || 3;
|
|
67
|
+
const id = `route-${Date.now().toString(36)}`;
|
|
68
|
+
const attempts = [];
|
|
69
|
+
const alerts = [];
|
|
70
|
+
const tried = new Set();
|
|
71
|
+
let harness = route.selected, diagnostic = null, previous = null, carried = null;
|
|
72
|
+
const timeoutMs = options.timeoutMs || ROUTED_TIMEOUT_MS[route.tier] || ROUTED_TIMEOUT_MS.budget;
|
|
73
|
+
|
|
74
|
+
for (let index = 1; index <= maxAttempts && harness; index += 1) {
|
|
75
|
+
if (cancellationResult()) return { route, attempts, alerts, ...cancellationResult() };
|
|
76
|
+
tried.add(harness);
|
|
77
|
+
const branch = `meta-harness/${id}-${index}-${harness}`;
|
|
78
|
+
// An escalation continues from the previous attempt's unfinished work instead of starting over (A-102).
|
|
79
|
+
const directory = createWorktree(cwd, { branch, ...(carried ? { ref: carried } : {}) });
|
|
80
|
+
// A-107: each attempt streams its agent's events here live; the path is announced first.
|
|
81
|
+
const progressFile = options.progressDir === false ? undefined
|
|
82
|
+
: path.join(options.progressDir || path.join(configDir(), 'jobs'), `${id}-${index}-${harness}.events.jsonl`);
|
|
83
|
+
const attempt = { harness, branch: null, commit: null, gate: null, escalatedFrom: previous, ...(progressFile ? { progressFile } : {}) };
|
|
84
|
+
attempts.push(attempt);
|
|
85
|
+
if (progressFile) console.error(JSON.stringify({ progress: progressFile, attempt: index, harness }));
|
|
86
|
+
// A-109: the agent gets the repository's dependencies in its own checkout, so its tests run.
|
|
87
|
+
let stopped;
|
|
88
|
+
try {
|
|
89
|
+
attempt.dependencies = (options.provideDependencies || provideDependencies)(cwd, directory);
|
|
90
|
+
const prompt = `Work only in this checkout. Do not commit; the harness commits your changes.\nTask:\n${task}${diagnostic ? `\n\nA previous attempt by ${previous} failed. Diagnostic:\n${diagnostic}` : ''}`;
|
|
91
|
+
const result = await dispatchWithReceipt({ agent: harness, node, branch, cwd: directory, contextCwd: cwd, contextTask: task, prompt, permissions: { read: true, write: true }, timeoutMs,
|
|
92
|
+
...controls, goal: controls.goal || task.slice(0, 4000),
|
|
93
|
+
...(progressFile ? { progressFile } : {}), allowUnknownAuth: options.allowUnknownAuth === true }, { dispatchFn: options.dispatchFn, role: 'Routed', complexityScore: route.complexity?.score, escalatedFrom: previous, replay, retryId: options.retryId });
|
|
94
|
+
attempt.ok = result.ok === true;
|
|
95
|
+
if (result.cancelled) stopped = result;
|
|
96
|
+
attempt.durationMs = result.durationMs;
|
|
97
|
+
attempt.timeoutMs = timeoutMs;
|
|
98
|
+
attempt.output = result.response || result.partialOutput || null;
|
|
99
|
+
if (result.sessionId) { attempt.sessionId = result.sessionId; attempt.branch = branch; }
|
|
100
|
+
attempt.goalCheck = result.goalCheck;
|
|
101
|
+
attempt.structured = result.structured;
|
|
102
|
+
attempt.usage = result.usage;
|
|
103
|
+
if (!attempt.ok && result.stderr) attempt.stderr = result.stderr;
|
|
104
|
+
if (result.ok) {
|
|
105
|
+
attempt.commit = commitAll(directory, `meta-harness: ${task.slice(0, 60)}\n\nAgent: ${harness}`);
|
|
106
|
+
if (attempt.commit) attempt.branch = branch;
|
|
107
|
+
// Keep the session branch even when the goal required no repository edit.
|
|
108
|
+
else if (result.sessionId) attempt.branch = branch;
|
|
109
|
+
} else {
|
|
110
|
+
attempt.error = result.error;
|
|
111
|
+
attempt.failureKind = result.failureKind;
|
|
112
|
+
if (result.queued || result.queueError || (result.failureKind === 'quota' && options.retryId) || ['billing-policy', 'limit', 'interrupted'].includes(result.failureKind)) stopped = result;
|
|
113
|
+
}
|
|
114
|
+
if (attempt.ok && options.gate && !cancellationResult()) {
|
|
115
|
+
linkDependencies(cwd, directory);
|
|
116
|
+
attempt.gate = await (options.gateFn || runQualityGate)(directory, options.gateOptions);
|
|
117
|
+
// A gate that could not run says nothing about this agent's work, so it does not escalate.
|
|
118
|
+
if (['unavailable', 'unconfigured'].includes(attempt.gate.status)) {
|
|
119
|
+
attempt.ok = false;
|
|
120
|
+
attempt.error = `The quality gate is ${attempt.gate.status}: ${attempt.gate.summary}`;
|
|
121
|
+
return { ok: false, route, attempts, error: attempt.error };
|
|
122
|
+
}
|
|
123
|
+
await recordRunReceipt({ harness, role: 'Gate', task, success: attempt.gate.passed, failureKind: attempt.gate.passed ? null : 'gate', error: attempt.gate.passed ? null : attempt.gate.summary, gate: attempt.gate.status });
|
|
124
|
+
attempt.ok = attempt.gate.passed;
|
|
125
|
+
}
|
|
126
|
+
if (attempt.ok && attempt.commit && !cancellationResult()) {
|
|
127
|
+
attempt.review = await (options.reviewFn || executeCodeReview)({ cwd, author: harness, task,
|
|
128
|
+
evidence: reviewEvidence(options.jobId || process.env.TR_METAHARNESS_JOB, attempt),
|
|
129
|
+
target: `HEAD...${attempt.commit}`, dispatchFn: options.dispatchFn, reviewer: options.reviewer,
|
|
130
|
+
allowUnknownAuth: options.allowUnknownAuth === true, availableHarnesses: options.availableHarnesses });
|
|
131
|
+
if (reviewBlocksPush(attempt.review)) {
|
|
132
|
+
attempt.ok = false; attempt.failureKind = 'review';
|
|
133
|
+
attempt.error = attempt.review.error || JSON.stringify(attempt.review.review?.findings || []) || 'Review blocked the push.';
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
} catch (error) {
|
|
137
|
+
attempt.ok = false;
|
|
138
|
+
attempt.error = String(error.message);
|
|
139
|
+
} finally {
|
|
140
|
+
if (cancellationResult()) {
|
|
141
|
+
Object.assign(attempt, cancellationResult());
|
|
142
|
+
stopped = cancellationResult();
|
|
143
|
+
}
|
|
144
|
+
// A failed attempt's edits are kept as an unfinished commit on its branch for review and for the
|
|
145
|
+
// next attempt to continue from; only an attempt that changed nothing loses its branch (A-102).
|
|
146
|
+
if (!attempt.ok && !attempt.commit) {
|
|
147
|
+
let wip = null;
|
|
148
|
+
try { wip = commitAll(directory, `meta-harness: unfinished attempt by ${harness}\n\n${String(attempt.error || '').slice(0, 300)}`); }
|
|
149
|
+
catch (error) { attempt.wipError = String(error.message); }
|
|
150
|
+
if (wip) { attempt.wip = wip; attempt.branch = branch; carried = wip; }
|
|
151
|
+
} else if (!attempt.ok && attempt.commit) carried = attempt.commit;
|
|
152
|
+
// Edits that could not be committed are never deleted (A-114): the checkout and branch stay for recovery.
|
|
153
|
+
const unsafeGit = gitPointerProblem(directory);
|
|
154
|
+
if (unsafeGit) {
|
|
155
|
+
stopped = { ok: false, failureKind: 'security', error: `Refusing to run git as root: ${unsafeGit} during an agent-user run.` };
|
|
156
|
+
attempt.ok = false; attempt.error = stopped.error; attempt.failureKind = stopped.failureKind;
|
|
157
|
+
}
|
|
158
|
+
if (unsafeGit || (attempt.wipError && isDirty(directory))) { attempt.keptWorktree = directory; attempt.branch = branch; }
|
|
159
|
+
else {
|
|
160
|
+
removeWorktree(cwd, directory);
|
|
161
|
+
if (!attempt.ok && !attempt.wip && !attempt.commit && !attempt.sessionId) { deleteBranch(cwd, branch); attempt.branch = null; }
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
if (stopped?.cancelled) return { ...stopped, route, attempts, alerts, branch: attempt.branch, commit: attempt.commit, wip: attempt.wip, harness };
|
|
166
|
+
if (attempt.ok) {
|
|
167
|
+
const push = options.push === false ? { pushed: false, reason: 'push disabled for this run' } : pushBranch(cwd, attempt.branch);
|
|
168
|
+
return { ok: true, route, goalCheck: attempt.goalCheck, structured: attempt.structured, review: attempt.review,
|
|
169
|
+
gateApplied: Boolean(options.gate), branch: attempt.branch, commit: attempt.commit, push, harness, attempts, alerts };
|
|
170
|
+
}
|
|
171
|
+
if (stopped) return { ...stopped, route, attempts, alerts };
|
|
172
|
+
|
|
173
|
+
// Escalation stays with harnesses that can run the requested model.
|
|
174
|
+
const remaining = pool.filter(item => !tried.has(item) && (!route.modelSelection || route.modelSelection.compatible.includes(item)));
|
|
175
|
+
const next = remaining.length ? evaluateGateCascade(harness, { testsPassed: false }, remaining) : null;
|
|
176
|
+
diagnostic = attempt.gate?.summary || attempt.error || 'The previous attempt failed.';
|
|
177
|
+
previous = harness;
|
|
178
|
+
harness = next?.recommendedHarness && !tried.has(next.recommendedHarness) ? next.recommendedHarness : null;
|
|
179
|
+
if (harness) alerts.push(await notifyAlert({ title: 'Metaharness: escalating', message: `${previous} failed on "${task.slice(0, 60)}"; escalating to ${harness}.`, severity: 'warning' }));
|
|
180
|
+
}
|
|
181
|
+
const lastAttempt = attempts.at(-1);
|
|
182
|
+
const error = lastAttempt?.error || lastAttempt?.gate?.summary || 'No attempt passed.';
|
|
183
|
+
const failureKind = lastAttempt?.failureKind || (lastAttempt?.gate?.passed === false ? 'gate' : undefined);
|
|
184
|
+
return { ok: false, route, gateApplied: Boolean(options.gate), attempts, alerts, error, ...(failureKind ? { failureKind } : {}) };
|
|
185
|
+
}
|
package/src/chat.mjs
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { configDir } from './paths.mjs';
|
|
3
|
+
import { PluginStateStore } from './ssss-store.mjs';
|
|
4
|
+
import { getActiveAdapters } from './worker.mjs';
|
|
5
|
+
|
|
6
|
+
const CODEX_DRAFT = 'codex://threads/new';
|
|
7
|
+
const MAX_SELECTION_BYTES = 16_384;
|
|
8
|
+
const MAX_DRAFT_LINK_LENGTH = 8_192;
|
|
9
|
+
const UNSAFE_TEXT = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
|
|
10
|
+
const BRAIN_ID = /^(?:global|project:[^,]+|tenant:[a-zA-Z0-9._-]+)$/u;
|
|
11
|
+
const ADAPTER_ID = /^[a-z][a-z0-9-]{0,63}$/;
|
|
12
|
+
|
|
13
|
+
// Chat preferences follow the dashboard's brain. The auth store override is
|
|
14
|
+
// exclusively for credentials and may point outside an isolated dashboard.
|
|
15
|
+
const chatStore = () => new PluginStateStore(
|
|
16
|
+
path.join(configDir({ ...process.env, TR_SECRETS_BRAIN: undefined }), 'chat-default.json'),
|
|
17
|
+
'meta-harness',
|
|
18
|
+
);
|
|
19
|
+
const displayAdapter = ({ id, name }) => ({ id, name });
|
|
20
|
+
|
|
21
|
+
function brainContext(selection) {
|
|
22
|
+
if (typeof selection !== 'string' || Buffer.byteLength(selection) > MAX_SELECTION_BYTES || UNSAFE_TEXT.test(selection)) {
|
|
23
|
+
throw new Error('Chat requires a bounded comma-separated list of brain IDs');
|
|
24
|
+
}
|
|
25
|
+
const ids = [...new Set(selection.split(',').map(id => id.trim()))];
|
|
26
|
+
if (ids.some(id => !BRAIN_ID.test(id))) throw new Error('Chat brain IDs must use global, project:<name>, or tenant:<name>');
|
|
27
|
+
return `Use this Total Recall brain selection for Chat: ${JSON.stringify(ids)}. Resolve the selected IDs through Total Recall before retrieving or writing memory.`;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function launchUrl(adapterId, value) {
|
|
31
|
+
if (value === undefined) return undefined;
|
|
32
|
+
const message = 'Use an HTTPS launch URL without credentials, a query or a fragment, or a Codex Chat link for Codex';
|
|
33
|
+
if (typeof value !== 'string' || value.length > 2048 || UNSAFE_TEXT.test(value) || /\s|\\/u.test(value)) {
|
|
34
|
+
throw new Error(message);
|
|
35
|
+
}
|
|
36
|
+
if (adapterId === 'codex' && /^codex:\/\/threads\/[a-zA-Z0-9_-]{1,128}$/.test(value)) return value;
|
|
37
|
+
if (!value.startsWith('https://') || /[?#]/.test(value)) throw new Error(message);
|
|
38
|
+
const url = URL.parse(value);
|
|
39
|
+
if (!url?.hostname || url.username || url.password) throw new Error(message);
|
|
40
|
+
return url.href;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function resolveTarget(settings, adapters, context) {
|
|
44
|
+
const choices = adapters.map(displayAdapter);
|
|
45
|
+
if (!settings) return { ok: true, configured: false, choices, context };
|
|
46
|
+
const adapter = adapters.find(({ id }) => id === settings.adapterId);
|
|
47
|
+
if (!adapter) {
|
|
48
|
+
return {
|
|
49
|
+
ok: true, configured: false, choices, context,
|
|
50
|
+
warning: 'The saved Chat harness is unavailable. Choose a new default.',
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const target = launchUrl(adapter.id, settings.url) ?? (adapter.id === 'codex' ? CODEX_DRAFT : undefined);
|
|
55
|
+
let href = target;
|
|
56
|
+
if (target === CODEX_DRAFT) {
|
|
57
|
+
const draft = `${target}?prompt=${encodeURIComponent(context)}`;
|
|
58
|
+
if (draft.length <= MAX_DRAFT_LINK_LENGTH) href = draft;
|
|
59
|
+
}
|
|
60
|
+
return { ok: true, configured: true, choices, context, harness: displayAdapter(adapter), ...(href ? { href } : {}) };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Return a draft target. The caller decides when to open it and the operator submits in the harness. */
|
|
64
|
+
export function chatTarget(brains = 'global') {
|
|
65
|
+
const context = brainContext(brains);
|
|
66
|
+
const settings = chatStore().read(null);
|
|
67
|
+
if (settings !== null && (!settings || typeof settings.adapterId !== 'string' || !ADAPTER_ID.test(settings.adapterId))) {
|
|
68
|
+
throw new Error('The saved Chat default is invalid');
|
|
69
|
+
}
|
|
70
|
+
return resolveTarget(settings, getActiveAdapters(), context);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Only the adapter and optional launch URL are persistent. */
|
|
74
|
+
export function setChatDefault(adapterId, url) {
|
|
75
|
+
const adapters = getActiveAdapters();
|
|
76
|
+
if (!adapters.some(({ id }) => id === adapterId)) throw new Error('Choose a registered Metaharness adapter for Chat');
|
|
77
|
+
const settings = { adapterId, url: launchUrl(adapterId, url) };
|
|
78
|
+
chatStore().write(settings);
|
|
79
|
+
return resolveTarget(settings, adapters, brainContext('global'));
|
|
80
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/** The models the signed-in Codex account can run, as the installed Codex CLI last listed them. */
|
|
2
|
+
import { execFileSync } from 'node:child_process';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
|
|
7
|
+
const MAX_AGE_MS = 7 * 86400_000;
|
|
8
|
+
const codexHome = env => env.CODEX_HOME || path.join(env.HOME || os.homedir(), '.codex');
|
|
9
|
+
|
|
10
|
+
let installed;
|
|
11
|
+
/** The installed Codex CLI's version, read once per process; null when it does not answer. */
|
|
12
|
+
function installedCliVersion() {
|
|
13
|
+
if (installed === undefined) {
|
|
14
|
+
try { installed = execFileSync('codex', ['--version'], { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] }).match(/\d+\.\d+\.\d+/)?.[0] ?? null; }
|
|
15
|
+
catch { installed = null; }
|
|
16
|
+
}
|
|
17
|
+
return installed;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Model ids, or null when there is no verdict. Every Codex client (desktop app, IDE, CLI) overwrites
|
|
22
|
+
* this list with the models its own version can run, so only the CLI's own list counts.
|
|
23
|
+
*/
|
|
24
|
+
export function codexAccountModels({ env = process.env, now = Date.now(), cliVersion = installedCliVersion } = {}) {
|
|
25
|
+
try {
|
|
26
|
+
const cache = JSON.parse(fs.readFileSync(path.join(codexHome(env), 'models_cache.json'), 'utf8'));
|
|
27
|
+
const at = Date.parse(cache.fetched_at);
|
|
28
|
+
if (!Number.isFinite(at) || now - at > MAX_AGE_MS) return null;
|
|
29
|
+
if (!cache.client_version || cache.client_version !== cliVersion()) return null;
|
|
30
|
+
const ids = (cache.models || []).map(model => model?.slug).filter(slug => typeof slug === 'string');
|
|
31
|
+
return ids.length ? ids : null;
|
|
32
|
+
} catch { return null; }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The model Codex runs when a request names none. Profiles and other tables are not read. */
|
|
36
|
+
export function codexDefaultModel({ env = process.env } = {}) {
|
|
37
|
+
try {
|
|
38
|
+
for (const line of fs.readFileSync(path.join(codexHome(env), 'config.toml'), 'utf8').split('\n')) {
|
|
39
|
+
if (/^\s*\[/.test(line)) return null;
|
|
40
|
+
const found = line.match(/^\s*model\s*=\s*["']([^"']+)["']/);
|
|
41
|
+
if (found) return found[1];
|
|
42
|
+
}
|
|
43
|
+
} catch { /* no configuration */ }
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Why Codex cannot run this model, or null when it can or nothing is known. */
|
|
48
|
+
export function codexModelRefusal(model, options = {}) {
|
|
49
|
+
const listed = codexAccountModels(options);
|
|
50
|
+
const wanted = model ?? codexDefaultModel(options);
|
|
51
|
+
if (!listed || !wanted || listed.includes(wanted)) return null;
|
|
52
|
+
const version = (options.cliVersion || installedCliVersion)();
|
|
53
|
+
return `Codex's ${model ? 'requested' : 'default'} model ${wanted} is not available to the signed-in account in Codex CLI ${version}. Available: ${listed.join(', ')}. A newer CLI may list more.`;
|
|
54
|
+
}
|