-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhermesModelUtils.ts
More file actions
280 lines (250 loc) · 9.07 KB
/
Copy pathhermesModelUtils.ts
File metadata and controls
280 lines (250 loc) · 9.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
/**
* Hermes model helpers: normalize UI values and optionally probe ACP for available models.
*/
import * as acp from '@agentclientprotocol/sdk';
import { spawn } from 'child_process';
import { Readable, Writable } from 'stream';
import { CTRLNODE_ROOT, HERMES_HOME } from './config.js';
import { logger } from './logger.js';
import { checkBinaryExists, checkHermesAcpAvailable } from './providers/providerHealthUtils.js';
/** Normalize model id from CtrlNode UI (spaces → dashes). */
export function normalizeHermesModelId(model: string | undefined | null): string | undefined {
const trimmed = model?.trim();
if (!trimmed) return undefined;
return trimmed.replace(/\s+/g, '-');
}
/** Strip `provider:` or `vendor/model` prefix for routing heuristics. */
export function stripHermesModelPrefix(modelId: string): string {
const normalized = normalizeHermesModelId(modelId) ?? modelId;
if (normalized.includes(':')) {
return normalized.split(':').pop() ?? normalized;
}
if (normalized.includes('/')) {
return normalized.split('/').pop() ?? normalized;
}
return normalized;
}
/**
* Provider prefixes recognized by Hermes `parse_model_input` (`provider:model`).
* Not an exhaustive catalog — Hermes validates at runtime; this mirrors the syntax rules.
*/
const HERMES_EXPLICIT_PROVIDER_PREFIXES = new Set([
'openrouter',
'copilot-acp',
'copilot',
'anthropic',
'openai',
'openai-codex',
'google',
'gemini',
'xai',
'xai-oauth',
'nous',
'ollama',
'groq',
'mistral',
'deepseek',
'custom',
]);
export type ParsedHermesModelRef = {
/** Set when UI uses `provider:model` (e.g. `openrouter:anthropic/claude-sonnet-4`). */
explicitProvider?: string;
modelPart: string;
};
/** Parse Hermes model id the same way as `provider:model` vs bare model. */
export function parseHermesModelRef(modelId: string): ParsedHermesModelRef {
const normalized = normalizeHermesModelId(modelId) ?? modelId;
const colon = normalized.indexOf(':');
if (colon > 0) {
const providerPart = normalized.slice(0, colon).toLowerCase();
const modelPart = normalized.slice(colon + 1).trim();
if (providerPart && modelPart && HERMES_EXPLICIT_PROVIDER_PREFIXES.has(providerPart)) {
return { explicitProvider: providerPart, modelPart };
}
}
return { modelPart: normalized };
}
function canonicalHermesModelId(modelId: string): string {
return stripHermesModelPrefix(modelId).toLowerCase();
}
/**
* Whether to skip ACP `setSessionModel` for this agent model.
*
* Hermes supports many providers (openrouter, nous, copilot-acp, …). We only skip the
* **known-broken combo** from Hermes 0.14 logs: GPT-5 family while the session stays on
* Copilot ACP — `setSessionModel` remaps to `provider=openai` + `codex_stream` and
* CopilotACPClient lacks `.responses`.
*
* - `openrouter:…`, `nous:…`, etc. → always apply (provider switch).
* - `anthropic/claude-…`, `claude-…` → apply (works via copilot-acp in QA).
* - bare `gpt-5.4-mini` or `copilot-acp:gpt-5.4-mini` on a copilot session → skip.
*/
export function shouldSkipHermesAcpSessionModelSet(
modelId: string | undefined | null,
sessionInitialModel?: string,
): boolean {
if (!modelId?.trim()) return false;
const { explicitProvider, modelPart } = parseHermesModelRef(modelId);
const bare = modelPart.toLowerCase();
if (
sessionInitialModel?.trim() &&
canonicalHermesModelId(sessionInitialModel) === canonicalHermesModelId(modelId)
) {
return true;
}
if (explicitProvider && explicitProvider !== 'copilot-acp' && explicitProvider !== 'copilot') {
return false;
}
if (/^gpt-5/.test(bare) || /^gpt-4o/.test(bare)) {
return true;
}
return false;
}
/** Reason string for logs when {@link shouldSkipHermesAcpSessionModelSet} is true. */
export function hermesAcpModelSetSkipReason(
modelId: string,
sessionInitialModel?: string,
): string {
const { explicitProvider } = parseHermesModelRef(modelId);
if (
sessionInitialModel?.trim() &&
canonicalHermesModelId(sessionInitialModel) === canonicalHermesModelId(modelId)
) {
return 'matches_session_default';
}
if (explicitProvider && explicitProvider !== 'copilot-acp' && explicitProvider !== 'copilot') {
return 'explicit_provider';
}
return 'copilot_gpt5_set_model_hermes_bug';
}
/** Detect Hermes provider API failures echoed into task output or agent_log. */
export function detectHermesCopilotApiFailure(text: string): string | undefined {
const t = text.trim();
if (!t) return undefined;
if (/API call failed after \d+ retries/i.test(t)) return t.split('\n')[0]?.trim() ?? t;
if (/CopilotACPClient.*has no attribute 'responses'/i.test(t)) {
return "CopilotACPClient missing 'responses' (Hermes codex_stream path)";
}
return undefined;
}
/**
* Detect Hermes API errors that should block the task (recoverable config problems).
* Returns the error message if blockable, undefined otherwise.
*/
export function detectHermesBlockableError(text: string): string | undefined {
const t = text.trim();
if (!t) return undefined;
const m = t.match(/Non-retryable client error:.*?(\w[\w\s-]+ is not a valid model(?: ID)?)/i);
if (m) return m[1] ?? m[0];
if (/is not a valid model(?: id)?/i.test(t)) {
const line = t.split('\n').find(l => /is not a valid model/i.test(l));
return line?.trim() ?? t;
}
if (/invalid api key/i.test(t)) return 'Invalid API key — check your provider credentials';
if (/no api key/i.test(t)) return 'No API key configured — set OPENROUTER_API_KEY';
return undefined;
}
/**
* Returns true if the error message indicates a recoverable configuration problem
* (invalid model ID, bad API key, etc.) that should block rather than fail the task.
*/
export function isHermesBlockableError(msg: string): boolean {
if (/is not a valid model id/i.test(msg)) return true;
if (/invalid api key/i.test(msg)) return true;
if (/no api key/i.test(msg)) return true;
if (/authentication/i.test(msg)) return true;
return false;
}
const FALLBACK_MODELS = [
'gpt-5.4-mini',
'gpt-5.4',
'claude-sonnet-4',
'anthropic/claude-sonnet-4',
'claude-haiku-4-5',
];
let cachedModels: string[] | null = null;
let cacheExpiresAt = 0;
const CACHE_TTL_MS = 30 * 60_000;
/**
* Returns model ids advertised by Hermes ACP (cached). Falls back to a small static list.
*/
export async function listHermesModels(): Promise<string[]> {
if (cachedModels && Date.now() < cacheExpiresAt) return cachedModels;
const probed = await probeHermesModelsViaAcp();
const merged = [...new Set([...probed, ...FALLBACK_MODELS])].filter(Boolean);
cachedModels = merged;
cacheExpiresAt = Date.now() + CACHE_TTL_MS;
return merged;
}
async function probeHermesModelsViaAcp(): Promise<string[]> {
if (!(await checkBinaryExists('hermes')) || !(await checkHermesAcpAvailable())) {
return [];
}
const isWindows = process.platform === 'win32';
const cmd = isWindows ? 'cmd.exe' : 'hermes';
const args = isWindows ? ['/c', 'hermes', 'acp'] : ['acp'];
const env: NodeJS.ProcessEnv = { ...process.env };
if (HERMES_HOME) env['HERMES_HOME'] = HERMES_HOME;
return new Promise<string[]>((resolve) => {
const proc = spawn(cmd, args, {
cwd: CTRLNODE_ROOT,
env,
stdio: ['pipe', 'pipe', 'ignore'],
shell: false,
});
const finish = (models: string[]) => {
if (!proc.killed) proc.kill('SIGTERM');
resolve(models);
};
const timer = setTimeout(() => {
logger.debug('hermes_models.probe_timeout');
finish([]);
}, 14_000);
if (!proc.stdin || !proc.stdout) {
clearTimeout(timer);
finish([]);
return;
}
const output = Writable.toWeb(proc.stdin) as unknown as WritableStream<Uint8Array>;
const input = Readable.toWeb(proc.stdout) as unknown as ReadableStream<Uint8Array>;
const stream = acp.ndJsonStream(output, input);
const client: acp.Client = {
async requestPermission() {
return { outcome: { outcome: 'cancelled' } };
},
async sessionUpdate() {},
async writeTextFile() {
return {};
},
async readTextFile() {
return { content: '' };
},
};
void (async () => {
try {
const connection = new acp.ClientSideConnection((_agent) => client, stream);
await connection.initialize({
protocolVersion: acp.PROTOCOL_VERSION,
clientCapabilities: { fs: { readTextFile: true, writeTextFile: true } },
});
const session = await connection.newSession({
cwd: CTRLNODE_ROOT,
mcpServers: [],
});
const modelsState = (session as { models?: { availableModels?: Array<{ modelId: string }> } }).models;
const ids = modelsState?.availableModels?.map((m) => m.modelId).filter(Boolean) ?? [];
logger.debug('hermes_models.probe_ok', { count: ids.length });
clearTimeout(timer);
finish(ids);
} catch (err) {
logger.debug('hermes_models.probe_failed', {
error: err instanceof Error ? err.message : String(err),
});
clearTimeout(timer);
finish([]);
} finally {
proc.stdin?.end();
}
})();
});
}