@openagents-org/agent-launcher 0.2.199 → 0.2.201
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/package.json +1 -1
- package/registry.json +49 -19
- package/src/adapters/claude.js +4 -2
- package/src/adapters/codex.js +66 -5
- package/src/adapters/utils.js +33 -0
- package/src/cli.js +4 -0
- package/src/daemon.js +107 -33
- package/src/index.js +12 -1
- package/src/installer.js +43 -6
- package/src/probe.js +140 -28
- package/src/utils.js +147 -78
package/package.json
CHANGED
package/registry.json
CHANGED
|
@@ -48,14 +48,21 @@
|
|
|
48
48
|
"check_ready": {
|
|
49
49
|
"env_vars": [
|
|
50
50
|
"ANTHROPIC_API_KEY",
|
|
51
|
-
"ANTHROPIC_AUTH_TOKEN"
|
|
51
|
+
"ANTHROPIC_AUTH_TOKEN",
|
|
52
|
+
"CLAUDE_CODE_OAUTH_TOKEN"
|
|
52
53
|
],
|
|
53
|
-
"creds_file": "~/.claude
|
|
54
|
-
"creds_key":
|
|
54
|
+
"creds_file": "~/.claude/.credentials.json",
|
|
55
|
+
"creds_key": "claudeAiOauth",
|
|
55
56
|
"keychain_service": "Claude Code-credentials",
|
|
56
57
|
"not_ready_message": "Not logged in. Run: claude login",
|
|
57
58
|
"login_command": "claude login",
|
|
58
|
-
"alt_check": "claude --print hi"
|
|
59
|
+
"alt_check": "claude --print hi",
|
|
60
|
+
"status_args": [
|
|
61
|
+
"auth",
|
|
62
|
+
"status"
|
|
63
|
+
],
|
|
64
|
+
"logged_in_pattern": "\"loggedIn\"\\s*:\\s*true",
|
|
65
|
+
"logged_out_pattern": "\"loggedIn\"\\s*:\\s*false"
|
|
59
66
|
},
|
|
60
67
|
"probe": {
|
|
61
68
|
"args": [
|
|
@@ -146,7 +153,7 @@
|
|
|
146
153
|
"OPENAI_API_KEY"
|
|
147
154
|
],
|
|
148
155
|
"saved_env_key": "LLM_API_KEY",
|
|
149
|
-
"not_ready_message": "Not configured —
|
|
156
|
+
"not_ready_message": "Not configured — add a model API key in Configure"
|
|
150
157
|
},
|
|
151
158
|
"env_config": [
|
|
152
159
|
{
|
|
@@ -248,7 +255,14 @@
|
|
|
248
255
|
"OPENAI_API_KEY",
|
|
249
256
|
"OPENAI_BASE_URL"
|
|
250
257
|
],
|
|
251
|
-
"
|
|
258
|
+
"creds_file": "~/.codex/auth.json",
|
|
259
|
+
"creds_no_parse": true,
|
|
260
|
+
"status_args": [
|
|
261
|
+
"login",
|
|
262
|
+
"status"
|
|
263
|
+
],
|
|
264
|
+
"logged_in_pattern": "logged in using",
|
|
265
|
+
"logged_out_pattern": "not logged in",
|
|
252
266
|
"login_command": "codex login",
|
|
253
267
|
"unverifiable": true,
|
|
254
268
|
"not_ready_message": "Not configured. Set OPENAI_API_KEY + OPENAI_BASE_URL, or run: codex login"
|
|
@@ -402,7 +416,10 @@
|
|
|
402
416
|
},
|
|
403
417
|
"vendor": "Cursor",
|
|
404
418
|
"tagline": "The AI editor you love — now headless on your node.",
|
|
405
|
-
"provider_locked": true
|
|
419
|
+
"provider_locked": true,
|
|
420
|
+
"probe": {
|
|
421
|
+
"api_test": false
|
|
422
|
+
}
|
|
406
423
|
},
|
|
407
424
|
{
|
|
408
425
|
"name": "opencode",
|
|
@@ -448,7 +465,13 @@
|
|
|
448
465
|
],
|
|
449
466
|
"saved_env_key": "LLM_API_KEY",
|
|
450
467
|
"min_version": "1.17.0",
|
|
451
|
-
"not_ready_message": "Not configured —
|
|
468
|
+
"not_ready_message": "Not configured — sign in with `opencode auth login`, pick a free opencode/ model, or add an API key in Configure",
|
|
469
|
+
"creds_file": "~/.local/share/opencode/auth.json",
|
|
470
|
+
"creds_no_parse": true,
|
|
471
|
+
"creds_json_has_entries": true,
|
|
472
|
+
"keyless_model_prefixes": [
|
|
473
|
+
"opencode/"
|
|
474
|
+
]
|
|
452
475
|
},
|
|
453
476
|
"env_config": [
|
|
454
477
|
{
|
|
@@ -561,8 +584,12 @@
|
|
|
561
584
|
},
|
|
562
585
|
"check_ready": {
|
|
563
586
|
"creds_file": "~/.hermes/config.yaml",
|
|
587
|
+
"creds_file_windows": "%LOCALAPPDATA%/hermes/config.yaml",
|
|
564
588
|
"creds_no_parse": true,
|
|
565
|
-
"
|
|
589
|
+
"status_args": [
|
|
590
|
+
"status"
|
|
591
|
+
],
|
|
592
|
+
"logged_in_pattern": "✓\\s*logged in",
|
|
566
593
|
"login_command": "hermes setup",
|
|
567
594
|
"not_ready_message": "Hermes not configured — run: hermes setup",
|
|
568
595
|
"env_vars": [
|
|
@@ -670,7 +697,10 @@
|
|
|
670
697
|
],
|
|
671
698
|
"saved_env_key": "KIMI_API_KEY",
|
|
672
699
|
"login_command": "kimi login",
|
|
673
|
-
"not_ready_message": "Not configured — set an API key
|
|
700
|
+
"not_ready_message": "Not configured — set an API key in Configure, or run: kimi login",
|
|
701
|
+
"creds_file": "~/.kimi-code/credentials/kimi-code.json",
|
|
702
|
+
"creds_no_parse": true,
|
|
703
|
+
"creds_key": "refresh_token"
|
|
674
704
|
},
|
|
675
705
|
"env_config": [
|
|
676
706
|
{
|
|
@@ -968,7 +998,7 @@
|
|
|
968
998
|
"DEEPSEEK_API_KEY"
|
|
969
999
|
],
|
|
970
1000
|
"saved_env_key": "LLM_API_KEY",
|
|
971
|
-
"not_ready_message": "No model API key — set a model + LLM_API_KEY (or a provider key such as OPENAI_API_KEY)
|
|
1001
|
+
"not_ready_message": "No model API key — set a model + LLM_API_KEY (or a provider key such as OPENAI_API_KEY) in Configure"
|
|
972
1002
|
},
|
|
973
1003
|
"env_config": [
|
|
974
1004
|
{
|
|
@@ -1138,7 +1168,7 @@
|
|
|
1138
1168
|
],
|
|
1139
1169
|
"saved_env_key": "CLINE_API_KEY",
|
|
1140
1170
|
"login_command": "cline auth",
|
|
1141
|
-
"not_ready_message": "Not configured — set an API key
|
|
1171
|
+
"not_ready_message": "Not configured — set an API key in Configure, or run: cline auth"
|
|
1142
1172
|
},
|
|
1143
1173
|
"env_config": [
|
|
1144
1174
|
{
|
|
@@ -1391,7 +1421,7 @@
|
|
|
1391
1421
|
"NANOCLAW_AGENT_GROUP"
|
|
1392
1422
|
],
|
|
1393
1423
|
"saved_env_key": "NANOCLAW_AGENT_GROUP",
|
|
1394
|
-
"not_ready_message": "Set NANOCLAW_AGENT_GROUP (and NANOCLAW_HOME)
|
|
1424
|
+
"not_ready_message": "Set NANOCLAW_AGENT_GROUP (and NANOCLAW_HOME) in Configure"
|
|
1395
1425
|
},
|
|
1396
1426
|
"env_config": [
|
|
1397
1427
|
{
|
|
@@ -1599,7 +1629,7 @@
|
|
|
1599
1629
|
],
|
|
1600
1630
|
"saved_env_key": "PI_API_KEY",
|
|
1601
1631
|
"login_command": "pi",
|
|
1602
|
-
"not_ready_message": "Not configured — set a provider API key
|
|
1632
|
+
"not_ready_message": "Not configured — set a provider API key in Configure, or run `pi` and use /login once.",
|
|
1603
1633
|
"unreadable_message": "Pi credentials were found but could not be read. Check permissions on ~/.pi/agent, or run `pi` and sign in again."
|
|
1604
1634
|
},
|
|
1605
1635
|
"env_config": [
|
|
@@ -1778,7 +1808,7 @@
|
|
|
1778
1808
|
"DEEPSEEK_API_KEY"
|
|
1779
1809
|
],
|
|
1780
1810
|
"saved_env_key": "DEEPSEEK_API_KEY",
|
|
1781
|
-
"not_ready_message": "Not configured — set DEEPSEEK_API_KEY
|
|
1811
|
+
"not_ready_message": "Not configured — set DEEPSEEK_API_KEY in Configure. The harness has no CLI sign-in.",
|
|
1782
1812
|
"unreadable_message": "DeepSeek Harness credentials could not be read. Re-enter DEEPSEEK_API_KEY in the Configure screen."
|
|
1783
1813
|
},
|
|
1784
1814
|
"env_config": [
|
|
@@ -1890,7 +1920,7 @@
|
|
|
1890
1920
|
],
|
|
1891
1921
|
"saved_env_key": "COMMAND_CODE_API_KEY",
|
|
1892
1922
|
"login_command": "command-code login",
|
|
1893
|
-
"not_ready_message": "Not configured — sign in with `command-code login`, or set COMMAND_CODE_API_KEY
|
|
1923
|
+
"not_ready_message": "Not configured — sign in with `command-code login`, or set COMMAND_CODE_API_KEY in Configure",
|
|
1894
1924
|
"unreadable_message": "Command Code credentials could not be read. Sign in again with `command-code login`, or re-enter COMMAND_CODE_API_KEY in the Configure screen."
|
|
1895
1925
|
},
|
|
1896
1926
|
"env_config": [
|
|
@@ -1996,7 +2026,7 @@
|
|
|
1996
2026
|
"GEMINI_API_KEY"
|
|
1997
2027
|
],
|
|
1998
2028
|
"saved_env_key": "OPENWORKER_API_KEY",
|
|
1999
|
-
"not_ready_message": "No model API key — pick a provider and set OPENWORKER_API_KEY
|
|
2029
|
+
"not_ready_message": "No model API key — pick a provider and set OPENWORKER_API_KEY in Configure",
|
|
2000
2030
|
"unreadable_message": "The OpenWorker model key could not be read. Re-enter OPENWORKER_API_KEY in the Configure screen."
|
|
2001
2031
|
},
|
|
2002
2032
|
"env_config": [
|
|
@@ -2209,7 +2239,7 @@
|
|
|
2209
2239
|
"saved_env_key": "CODEBUDDY_API_KEY",
|
|
2210
2240
|
"login_command": "codebuddy",
|
|
2211
2241
|
"unverifiable": true,
|
|
2212
|
-
"not_ready_message": "Not signed in for this site. Sign in with the Login button — it opens the CLI on the site CODEBUDDY_REGION selects, where you run /login — or set CODEBUDDY_API_KEY / CODEBUDDY_AUTH_TOKEN
|
|
2242
|
+
"not_ready_message": "Not signed in for this site. Sign in with the Login button — it opens the CLI on the site CODEBUDDY_REGION selects, where you run /login — or set CODEBUDDY_API_KEY / CODEBUDDY_AUTH_TOKEN in Configure. A session for the other site does not carry over: the CLI keeps only one, and codebuddy.ai and codebuddy.cn are separate accounts.",
|
|
2213
2243
|
"auth_detected_labels": {
|
|
2214
2244
|
"cli_login": "CodeBuddy sign-in detected",
|
|
2215
2245
|
"api_key": "API key detected"
|
|
@@ -2302,7 +2332,7 @@
|
|
|
2302
2332
|
"CODEARTS_CLI_AK",
|
|
2303
2333
|
"CODEARTS_CLI_SK"
|
|
2304
2334
|
],
|
|
2305
|
-
"not_ready_message": "Needs a Huawei Cloud access key — set CODEARTS_CLI_AK and CODEARTS_CLI_SK
|
|
2335
|
+
"not_ready_message": "Needs a Huawei Cloud access key — set CODEARTS_CLI_AK and CODEARTS_CLI_SK in Configure. Create one at https://codearts.huaweicloud.com/portal/settings/cli-auth."
|
|
2306
2336
|
}
|
|
2307
2337
|
}
|
|
2308
2338
|
]
|
package/src/adapters/claude.js
CHANGED
|
@@ -21,7 +21,7 @@ const { execSync } = require('child_process');
|
|
|
21
21
|
const { spawn } = require('../wsl');
|
|
22
22
|
|
|
23
23
|
const BaseAdapter = require('./base');
|
|
24
|
-
const { formatAttachmentsForPrompt, SESSION_DEFAULT_RE, generateSessionTitle, redactSecrets } = require('./utils');
|
|
24
|
+
const { formatAttachmentsForPrompt, SESSION_DEFAULT_RE, generateSessionTitle, redactSecrets, stripCliNoise } = require('./utils');
|
|
25
25
|
const { buildClaudeSystemPrompt, buildClaudeSkillMd, buildPinnedSections, workspaceSkillName } = require('./workspace-prompt');
|
|
26
26
|
const { pinnedFingerprint, sampleRecap } = require('./decision-log');
|
|
27
27
|
const { defaultAgentWorkdir, whichBinary, whereBinary } = require('../paths');
|
|
@@ -1051,7 +1051,9 @@ class ClaudeAdapter extends BaseAdapter {
|
|
|
1051
1051
|
* and silent exit — where it is the ONLY thing there is to report.
|
|
1052
1052
|
*/
|
|
1053
1053
|
_stderrTail(pp) {
|
|
1054
|
-
|
|
1054
|
+
// Without Claude Code's harmless notices (an unknown relay model, the
|
|
1055
|
+
// disabled connectors): posted as "the" error, they hid the real one.
|
|
1056
|
+
const tail = stripCliNoise((pp && pp.stderrBuf) || '').trim();
|
|
1055
1057
|
return tail ? redactSecrets(tail).slice(-800) : '';
|
|
1056
1058
|
}
|
|
1057
1059
|
|
package/src/adapters/codex.js
CHANGED
|
@@ -25,7 +25,7 @@ const https = require('https');
|
|
|
25
25
|
|
|
26
26
|
const { whereBinary } = require('../paths');
|
|
27
27
|
const BaseAdapter = require('./base');
|
|
28
|
-
const { redactSecrets, formatAttachmentsForPrompt } = require('./utils');
|
|
28
|
+
const { redactSecrets, formatAttachmentsForPrompt, decodeConsoleOutput } = require('./utils');
|
|
29
29
|
const { buildOpenclawSystemPrompt } = require('./workspace-prompt');
|
|
30
30
|
|
|
31
31
|
const IS_WINDOWS = process.platform === 'win32';
|
|
@@ -203,6 +203,57 @@ class CodexAdapter extends BaseAdapter {
|
|
|
203
203
|
return resolveWslBinary('codex');
|
|
204
204
|
}
|
|
205
205
|
|
|
206
|
+
/**
|
|
207
|
+
* How to spawn `bin`: `{ file, args, shell }`, with `args` going before the
|
|
208
|
+
* codex arguments. On Windows an npm `.cmd` shim is resolved to
|
|
209
|
+
* `[node, <entry>.js]` (or the native `.exe` it forwards to) and spawned
|
|
210
|
+
* without a shell. Handing the shim to cmd.exe instead joined everything
|
|
211
|
+
* into one unquoted command line, so a profile folder with a space in it
|
|
212
|
+
* (`C:\Users\Windows 用户\…`) was cut at the space and the run died with
|
|
213
|
+
* "'C:\Users\Windows' 不是内部或外部命令".
|
|
214
|
+
*/
|
|
215
|
+
_resolveExec(bin, isWindows = IS_WINDOWS) {
|
|
216
|
+
const lower = String(bin).toLowerCase();
|
|
217
|
+
if (/\.[cm]?js$/.test(lower)) return { file: this._findNodeBin(), args: [bin], shell: false };
|
|
218
|
+
if (!isWindows || !/\.(cmd|bat)$/.test(lower)) return { file: bin, args: [], shell: false };
|
|
219
|
+
try {
|
|
220
|
+
const content = fs.readFileSync(bin, 'utf-8');
|
|
221
|
+
const js = content.match(/%dp0%\\([^\s"*?]+\.[cm]?js)/i);
|
|
222
|
+
if (js) {
|
|
223
|
+
return { file: this._findNodeBin(), args: [path.resolve(path.dirname(bin), js[1])], shell: false };
|
|
224
|
+
}
|
|
225
|
+
const exe = content.match(/%dp0%\\([^\s"*?]+\.exe)/i);
|
|
226
|
+
if (exe) return { file: path.resolve(path.dirname(bin), exe[1]), args: [], shell: false };
|
|
227
|
+
} catch {}
|
|
228
|
+
// A shim we can't read through still has to run under cmd.exe. Quote it,
|
|
229
|
+
// so at least the path survives the command line cmd.exe is given.
|
|
230
|
+
return { file: `"${bin}"`, args: [], shell: true };
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
_findNodeBin() {
|
|
234
|
+
const home = os.homedir();
|
|
235
|
+
const candidates = IS_WINDOWS
|
|
236
|
+
? [path.join(home, '.openagents', 'nodejs', 'node.exe')]
|
|
237
|
+
: [path.join(home, '.openagents', 'nodejs', 'bin', 'node'),
|
|
238
|
+
path.join(home, '.openagents', 'nodejs', 'node')];
|
|
239
|
+
for (const c of candidates) { try { if (fs.existsSync(c)) return c; } catch {} }
|
|
240
|
+
return process.execPath || 'node';
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
static _dirExists(p) {
|
|
244
|
+
try { return fs.statSync(p).isDirectory(); } catch { return false; }
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Decode CLI output. Codex writes UTF-8, but text that came from Windows
|
|
249
|
+
* itself (cmd.exe, a system error) is in the console code page, which on a
|
|
250
|
+
* Chinese system is GBK and showed up in chat as rows of "�". Fall back to
|
|
251
|
+
* GB18030 only when UTF-8 fails and GB18030 reads the bytes cleanly.
|
|
252
|
+
*/
|
|
253
|
+
static _decodeOutput(buf, isWindows = IS_WINDOWS) {
|
|
254
|
+
return decodeConsoleOutput(buf, isWindows);
|
|
255
|
+
}
|
|
256
|
+
|
|
206
257
|
_buildSystemContext(channelName) {
|
|
207
258
|
const base = buildOpenclawSystemPrompt({
|
|
208
259
|
agentName: this.agentName,
|
|
@@ -314,6 +365,14 @@ class CodexAdapter extends BaseAdapter {
|
|
|
314
365
|
}
|
|
315
366
|
|
|
316
367
|
async _handleViaSubprocess(content, msgChannel, attachments = []) {
|
|
368
|
+
// A missing cwd fails the spawn itself, and Node blames the shell for it
|
|
369
|
+
// ("spawn C:\Windows\system32\cmd.exe ENOENT"), which names nothing the
|
|
370
|
+
// user can fix. Say which folder is gone instead.
|
|
371
|
+
if (this.workingDir && !CodexAdapter._dirExists(this.workingDir)) {
|
|
372
|
+
await this.sendError(msgChannel, `Working directory does not exist: ${this.workingDir}`);
|
|
373
|
+
return;
|
|
374
|
+
}
|
|
375
|
+
|
|
317
376
|
const env = { ...(this.agentEnv || process.env) };
|
|
318
377
|
const effectiveModel = this._effectiveModel();
|
|
319
378
|
|
|
@@ -412,26 +471,27 @@ class CodexAdapter extends BaseAdapter {
|
|
|
412
471
|
// Stopped while this turn was being prepared: start nothing (no tokens).
|
|
413
472
|
if (this._stoppedBeforeStart(msgChannel)) return { stopped: true, responseText: '', exitCode: null };
|
|
414
473
|
return new Promise((resolve, reject) => {
|
|
415
|
-
const
|
|
474
|
+
const exec = this._resolveExec(cmd[0]);
|
|
475
|
+
const proc = spawn(exec.file, [...exec.args, ...cmd.slice(1)], {
|
|
416
476
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
417
477
|
env,
|
|
418
478
|
cwd: this.workingDir,
|
|
419
479
|
detached: !IS_WINDOWS,
|
|
420
480
|
windowsHide: true,
|
|
421
|
-
shell:
|
|
481
|
+
shell: exec.shell,
|
|
422
482
|
});
|
|
423
483
|
this._channelProcesses[msgChannel] = proc;
|
|
424
484
|
|
|
425
485
|
const responseTexts = [];
|
|
426
486
|
let hasToolUseSinceLastText = false;
|
|
427
487
|
let lineBuffer = '';
|
|
428
|
-
|
|
488
|
+
const stderrChunks = [];
|
|
429
489
|
let lastErrorMessage = '';
|
|
430
490
|
let turnFailed = false;
|
|
431
491
|
let _pendingLines = Promise.resolve();
|
|
432
492
|
|
|
433
493
|
if (proc.stderr) {
|
|
434
|
-
proc.stderr.on('data', (chunk) => {
|
|
494
|
+
proc.stderr.on('data', (chunk) => { stderrChunks.push(chunk); });
|
|
435
495
|
}
|
|
436
496
|
|
|
437
497
|
if (proc.stdin) {
|
|
@@ -518,6 +578,7 @@ class CodexAdapter extends BaseAdapter {
|
|
|
518
578
|
|
|
519
579
|
delete this._channelProcesses[msgChannel];
|
|
520
580
|
|
|
581
|
+
const stderrBuf = CodexAdapter._decodeOutput(Buffer.concat(stderrChunks));
|
|
521
582
|
if (code !== 0) {
|
|
522
583
|
this._log(`Codex CLI exited with code ${code}`);
|
|
523
584
|
if (stderrBuf.trim()) {
|
package/src/adapters/utils.js
CHANGED
|
@@ -149,8 +149,41 @@ function redactSecrets(s) {
|
|
|
149
149
|
return out;
|
|
150
150
|
}
|
|
151
151
|
|
|
152
|
+
/**
|
|
153
|
+
* Decode CLI output. The CLIs write UTF-8, but text that came from Windows
|
|
154
|
+
* itself (cmd.exe, a system error) is in the console code page, which on a
|
|
155
|
+
* Chinese system is GBK and showed up as rows of "�". Fall back to GB18030
|
|
156
|
+
* only when UTF-8 fails and GB18030 reads the bytes cleanly.
|
|
157
|
+
*/
|
|
158
|
+
function decodeConsoleOutput(buf, isWindows = process.platform === 'win32') {
|
|
159
|
+
const utf8 = buf.toString('utf-8');
|
|
160
|
+
if (!isWindows || !utf8.includes('�')) return utf8;
|
|
161
|
+
try {
|
|
162
|
+
return new TextDecoder('gb18030', { fatal: true }).decode(buf);
|
|
163
|
+
} catch {
|
|
164
|
+
return utf8;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Lines a CLI prints on a perfectly healthy run. Reported as "the" error,
|
|
170
|
+
* they hid the real one. Claude Code warns about its claude.ai connectors
|
|
171
|
+
* whenever a key is set, and about a model it does not know (any relay model:
|
|
172
|
+
* glm, kimi, …) — "…so it assumes a context window of 200000 tokens … Until
|
|
173
|
+
* then auto-compact keeps this session within 200k tokens".
|
|
174
|
+
*/
|
|
175
|
+
const BENIGN_CLI_OUTPUT = /claude\.ai connectors are disabled|doesn't recognize the model|assumes a context window|auto-compact keeps this session|CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT/i;
|
|
176
|
+
|
|
177
|
+
/** CLI output with the known-harmless lines taken out. */
|
|
178
|
+
function stripCliNoise(text) {
|
|
179
|
+
return String(text || '').split(/\r?\n/).filter((l) => !BENIGN_CLI_OUTPUT.test(l)).join('\n');
|
|
180
|
+
}
|
|
181
|
+
|
|
152
182
|
module.exports = {
|
|
153
183
|
SESSION_DEFAULT_RE,
|
|
184
|
+
BENIGN_CLI_OUTPUT,
|
|
185
|
+
stripCliNoise,
|
|
186
|
+
decodeConsoleOutput,
|
|
154
187
|
generateSessionTitle,
|
|
155
188
|
formatAttachmentsForPrompt,
|
|
156
189
|
redactSecrets,
|
package/src/cli.js
CHANGED
|
@@ -1035,6 +1035,10 @@ async function cmdProbe(connector, flags, positional) {
|
|
|
1035
1035
|
if (result.ok) {
|
|
1036
1036
|
print(`OK (${result.method}, ${result.durationMs}ms)${result.reply ? ` — ${result.reply}` : ''}`);
|
|
1037
1037
|
if (result.code === 'static_only') print(result.message);
|
|
1038
|
+
} else if (result.ok === null) {
|
|
1039
|
+
// Nothing could be run and the sign-in could not be checked either.
|
|
1040
|
+
print(`UNVERIFIED ${result.message || ''}`.trim());
|
|
1041
|
+
process.exitCode = 1;
|
|
1038
1042
|
} else {
|
|
1039
1043
|
print(`FAILED [${result.code}] ${result.message || ''}`.trim());
|
|
1040
1044
|
for (const line of result.guidance || []) print(` → ${line}`);
|
package/src/daemon.js
CHANGED
|
@@ -15,6 +15,8 @@ const { supportsCliModels } = require('./cli-models');
|
|
|
15
15
|
const { AUTH_MODE_KEY, isCliLogin, modelKeys, stripForCliLogin, typeEnvFor } = require('./env');
|
|
16
16
|
const { getEnhancedEnv, whichBinary, IS_WINDOWS, defaultAgentWorkdir } = require('./paths');
|
|
17
17
|
const { LogWriter } = require('./log-writer');
|
|
18
|
+
const { redactDiagnostic } = require('./adapters/health-status');
|
|
19
|
+
const { installCommandFor } = require('./probe');
|
|
18
20
|
|
|
19
21
|
// A signed-in agent's model list is asked for again after this long. What a
|
|
20
22
|
// CLI is offered changes when the CLI is upgraded (a vendor holds new models
|
|
@@ -98,6 +100,27 @@ function _sentKey(args) {
|
|
|
98
100
|
return present && !args.useDeviceCredentials;
|
|
99
101
|
}
|
|
100
102
|
|
|
103
|
+
/**
|
|
104
|
+
* The reason `agn create --install` gave for a failed runtime install, or null.
|
|
105
|
+
* The create itself still succeeds (exit 0) — the agent exists either way.
|
|
106
|
+
*/
|
|
107
|
+
function installFailureOf(stdout) {
|
|
108
|
+
const m = /Warning: install failed: ([\s\S]*)$/.exec(String(stdout || ''));
|
|
109
|
+
return m ? m[1].trim() || 'unknown error' : null;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* One line that says why a crashed `agn probe` child died. Node's stack dump
|
|
114
|
+
* starts with "node:internal/modules/cjs/loader:1433 / throw err; / ^", which
|
|
115
|
+
* is all a 400-char head of it ever showed; the line that names the problem
|
|
116
|
+
* ("Error: Cannot find module '…'") comes after.
|
|
117
|
+
*/
|
|
118
|
+
function probeCrashSummary(stderr) {
|
|
119
|
+
const lines = String(stderr || '').split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
|
|
120
|
+
const telling = lines.find((l) => /^\w*Error\b|Cannot find module/.test(l));
|
|
121
|
+
return telling || lines.join('\n') || 'probe failed';
|
|
122
|
+
}
|
|
123
|
+
|
|
101
124
|
/**
|
|
102
125
|
* Whether a node heartbeat failure is the workspace saying the node is gone:
|
|
103
126
|
* a 404 carrying the backend's own message (routers/nodes.py), not any 404.
|
|
@@ -184,12 +207,23 @@ class Daemon {
|
|
|
184
207
|
let parsed = null;
|
|
185
208
|
try { parsed = JSON.parse(r.stdout.trim()); } catch {}
|
|
186
209
|
if (!parsed || typeof parsed !== 'object') {
|
|
210
|
+
// The probe process itself died before it could answer — a fault on
|
|
211
|
+
// this device's OpenAgents install, not in the agent.
|
|
187
212
|
parsed = {
|
|
188
213
|
type, ok: false, method: 'none', code: 'probe_error',
|
|
189
|
-
message: (r.stderr
|
|
190
|
-
guidance: [
|
|
214
|
+
message: redactDiagnostic(probeCrashSummary(r.stderr), 400),
|
|
215
|
+
guidance: [
|
|
216
|
+
'The OpenAgents test could not start on this device. Restart OpenAgents and test again; if it keeps failing, reinstall OpenAgents.',
|
|
217
|
+
],
|
|
218
|
+
at: new Date().toISOString(),
|
|
191
219
|
};
|
|
192
220
|
}
|
|
221
|
+
// Still not installed after a failed install: keep the reason the
|
|
222
|
+
// install gave, which says far more than "Not installed".
|
|
223
|
+
const prev = this._probes[name];
|
|
224
|
+
if (parsed.code === 'not_installed' && prev && prev.code === 'install_failed') {
|
|
225
|
+
parsed = { ...prev, at: parsed.at || new Date().toISOString() };
|
|
226
|
+
}
|
|
193
227
|
parsed.agent = name;
|
|
194
228
|
this._probes[name] = parsed;
|
|
195
229
|
this._saveProbes();
|
|
@@ -199,6 +233,25 @@ class Daemon {
|
|
|
199
233
|
}
|
|
200
234
|
}
|
|
201
235
|
|
|
236
|
+
/** Report a runtime install that failed while creating `name`, as its probe result. */
|
|
237
|
+
_recordInstallFailure(name, type, error) {
|
|
238
|
+
let install = null;
|
|
239
|
+
try {
|
|
240
|
+
const entry = this.registry && this.registry.getEntry(type);
|
|
241
|
+
install = entry ? installCommandFor(entry) : null;
|
|
242
|
+
} catch {}
|
|
243
|
+
this._probes[name] = {
|
|
244
|
+
type, agent: name, ok: false, method: 'install', code: 'install_failed',
|
|
245
|
+
message: redactDiagnostic(error, 400),
|
|
246
|
+
guidance: [
|
|
247
|
+
'Installing the agent on this device failed. Install it from the launcher\'s Install page to see the full log.',
|
|
248
|
+
...(install ? [`Or install manually: ${install}`] : []),
|
|
249
|
+
],
|
|
250
|
+
at: new Date().toISOString(),
|
|
251
|
+
};
|
|
252
|
+
this._saveProbes();
|
|
253
|
+
}
|
|
254
|
+
|
|
202
255
|
/**
|
|
203
256
|
* Periodic sweep: probe each configured agent whose last result is missing
|
|
204
257
|
* or stale. Sequential on purpose — probes cost a (tiny) model call each;
|
|
@@ -745,6 +798,7 @@ async _runNodeCommand(n, cmd) {
|
|
|
745
798
|
try { fs.mkdirSync(workingDir, { recursive: true }); } catch {}
|
|
746
799
|
const r1 = await this._runAgn(['create', name, '--type', type, '--install', '--path', workingDir]);
|
|
747
800
|
if (r1.code !== 0) throw new Error(r1.stderr || r1.stdout || 'create failed');
|
|
801
|
+
const installError = installFailureOf(r1.stdout);
|
|
748
802
|
// Optional credentials for API-key agents (generic → provider mapping
|
|
749
803
|
// happens in env resolution). `useDeviceCredentials` means the device
|
|
750
804
|
// already holds them — nothing to write.
|
|
@@ -764,19 +818,32 @@ async _runNodeCommand(n, cmd) {
|
|
|
764
818
|
if (r2.code !== 0) throw new Error(r2.stderr || r2.stdout || 'connect failed');
|
|
765
819
|
ok = true;
|
|
766
820
|
message = `Agent '${name}' created`;
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
821
|
+
if (installError) {
|
|
822
|
+
// The agent exists and is connected, but its runtime did not install.
|
|
823
|
+
// Say why on the card: a probe now could only answer "Not installed".
|
|
824
|
+
message = `Agent '${name}' created, but installing ${type} failed: ${installError}`;
|
|
825
|
+
this._recordInstallFailure(name, type, installError);
|
|
826
|
+
this._nodeHeartbeat();
|
|
827
|
+
} else {
|
|
828
|
+
// First-connect smoke test, in the background (a probe can take its
|
|
829
|
+
// full timeout — never hold the create result hostage). The outcome
|
|
830
|
+
// reaches the workspace via the heartbeat's agents[].probe.
|
|
831
|
+
this._probeAgent(name).then(() => this._nodeHeartbeat()).catch(() => {});
|
|
832
|
+
}
|
|
771
833
|
this._askCliModels(name);
|
|
772
|
-
} else if (action === 'start_agent') {
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
834
|
+
} else if (action === 'start_agent' || action === 'stop_agent') {
|
|
835
|
+
// In-process, not via `agn start|stop`: that spawned a whole CLI just to
|
|
836
|
+
// drop a line into daemon.cmd for THIS process to poll back up, and the
|
|
837
|
+
// new state then waited for the next 10s heartbeat. A Stop clicked in
|
|
838
|
+
// the workspace could sit at "running" for half a minute. Report the
|
|
839
|
+
// new state as soon as it is set instead; stopAgent flips it to
|
|
840
|
+
// 'stopped' before it starts waiting on the agent to exit.
|
|
841
|
+
const settled = action === 'stop_agent' ? this.stopAgent(name) : this._startAgentIfIdle(name);
|
|
842
|
+
this._nodeHeartbeat();
|
|
843
|
+
await settled;
|
|
844
|
+
this._nodeHeartbeat();
|
|
845
|
+
ok = true;
|
|
846
|
+
message = `Agent '${name}' ${action === 'stop_agent' ? 'stopped' : 'started'}`;
|
|
780
847
|
} else if (action === 'remove_agent') {
|
|
781
848
|
const r = await this._runAgn(['remove', name]);
|
|
782
849
|
ok = r.code === 0;
|
|
@@ -1097,6 +1164,31 @@ async _runNodeCommand(n, cmd) {
|
|
|
1097
1164
|
this._writeStatus();
|
|
1098
1165
|
}
|
|
1099
1166
|
|
|
1167
|
+
/**
|
|
1168
|
+
* Start an agent unless it is already running.
|
|
1169
|
+
*
|
|
1170
|
+
* 'start' must be idempotent. The launcher sends start:<name> right after
|
|
1171
|
+
* (re)spawning the daemon, but the daemon's own start() already launched
|
|
1172
|
+
* every configured agent. A blind restart here tears down the just-joined
|
|
1173
|
+
* workspace session and re-joins as the same agent; the server revokes the
|
|
1174
|
+
* first session and the agent then stops the moment it next touches the
|
|
1175
|
+
* workspace (e.g. the first user message → "thinking..." status). Only
|
|
1176
|
+
* (re)launch when it isn't running.
|
|
1177
|
+
*/
|
|
1178
|
+
async _startAgentIfIdle(agentName) {
|
|
1179
|
+
const running =
|
|
1180
|
+
(this._adapters && this._adapters[agentName]) ||
|
|
1181
|
+
['running', 'starting'].includes(
|
|
1182
|
+
this._processes[agentName] && this._processes[agentName].state
|
|
1183
|
+
);
|
|
1184
|
+
if (running) {
|
|
1185
|
+
this._log(`Command: start ${agentName} — already running, skipping`);
|
|
1186
|
+
return;
|
|
1187
|
+
}
|
|
1188
|
+
this._log(`Command: start ${agentName}`);
|
|
1189
|
+
await this.restartAgent(agentName);
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1100
1192
|
/**
|
|
1101
1193
|
* Restart a single agent by name.
|
|
1102
1194
|
*/
|
|
@@ -1785,25 +1877,7 @@ async _runNodeCommand(n, cmd) {
|
|
|
1785
1877
|
this._log(`Command: stop ${agentName}`);
|
|
1786
1878
|
this.stopAgent(agentName);
|
|
1787
1879
|
} else if (cmd.startsWith('start:')) {
|
|
1788
|
-
|
|
1789
|
-
// 'start' must be idempotent. The launcher sends start:<name> right
|
|
1790
|
-
// after (re)spawning the daemon, but the daemon's own start() already
|
|
1791
|
-
// launched every configured agent. A blind restart here tears down
|
|
1792
|
-
// the just-joined workspace session and re-joins as the same agent;
|
|
1793
|
-
// the server revokes the first session and the agent then stops the
|
|
1794
|
-
// moment it next touches the workspace (e.g. the first user message →
|
|
1795
|
-
// "thinking..." status). Only (re)launch when it isn't running.
|
|
1796
|
-
const running =
|
|
1797
|
-
(this._adapters && this._adapters[agentName]) ||
|
|
1798
|
-
['running', 'starting'].includes(
|
|
1799
|
-
this._processes[agentName] && this._processes[agentName].state
|
|
1800
|
-
);
|
|
1801
|
-
if (running) {
|
|
1802
|
-
this._log(`Command: start ${agentName} — already running, skipping`);
|
|
1803
|
-
} else {
|
|
1804
|
-
this._log(`Command: start ${agentName}`);
|
|
1805
|
-
this.restartAgent(agentName);
|
|
1806
|
-
}
|
|
1880
|
+
this._startAgentIfIdle(cmd.slice(6).trim());
|
|
1807
1881
|
} else if (cmd.startsWith('restart:')) {
|
|
1808
1882
|
const agentName = cmd.slice(8).trim();
|
|
1809
1883
|
this._log(`Command: restart ${agentName}`);
|
package/src/index.js
CHANGED
|
@@ -57,8 +57,19 @@ class AgentConnector {
|
|
|
57
57
|
|
|
58
58
|
// -- Install / Uninstall --
|
|
59
59
|
|
|
60
|
+
/**
|
|
61
|
+
* Install an agent runtime the way the launcher's Install button does
|
|
62
|
+
* (installStreaming): it installs Node.js when an npm agent needs it, uses
|
|
63
|
+
* the configured npm mirror and runs npm path-safely. `agn install` and the
|
|
64
|
+
* workspace's remote create used the bare install(), which had none of
|
|
65
|
+
* that, and the failures it produced surfaced only as "Not installed".
|
|
66
|
+
*/
|
|
60
67
|
async install(agentType) {
|
|
61
|
-
|
|
68
|
+
let output = '';
|
|
69
|
+
const result = await this.installer.installStreaming(agentType, (chunk) => {
|
|
70
|
+
output = (output + String(chunk)).slice(-8000);
|
|
71
|
+
});
|
|
72
|
+
return { ...result, output: output.trim() };
|
|
62
73
|
}
|
|
63
74
|
|
|
64
75
|
async uninstall(agentType) {
|
package/src/installer.js
CHANGED
|
@@ -828,7 +828,10 @@ class Installer {
|
|
|
828
828
|
(entry.check_ready && entry.check_ready.min_version)
|
|
829
829
|
)) || null;
|
|
830
830
|
if (!minVersion) return { compatible: true, minVersion: null, message: null };
|
|
831
|
-
|
|
831
|
+
// "0.0.0" is a placeholder, not a release: Pi prints it when it cannot
|
|
832
|
+
// find its own package.json (a standalone build, a moved install). Blocking
|
|
833
|
+
// on it told a current Pi it was too old.
|
|
834
|
+
const cmp = /^v?0\.0\.0\b/.test(String(version || '').trim()) ? null : compareVersions(version, minVersion);
|
|
832
835
|
if (cmp === null) {
|
|
833
836
|
return { compatible: null, minVersion, message: `Version unknown (requires >= ${minVersion})` };
|
|
834
837
|
}
|
|
@@ -924,6 +927,22 @@ class Installer {
|
|
|
924
927
|
};
|
|
925
928
|
}
|
|
926
929
|
|
|
930
|
+
// A model that needs no credential at all — OpenCode Zen's free
|
|
931
|
+
// `opencode/…` models. The launcher's KEYLESS_AUTH_SETTINGS already counts
|
|
932
|
+
// them as ready; judged here on keys alone the same agent read "Not
|
|
933
|
+
// configured" in every smoke test.
|
|
934
|
+
const keylessPrefixes = Array.isArray(checkReady.keyless_model_prefixes) ? checkReady.keyless_model_prefixes : [];
|
|
935
|
+
const model = String((savedEnv && savedEnv.LLM_MODEL) || '').trim();
|
|
936
|
+
if (model && keylessPrefixes.some((p) => p && model.startsWith(p))) {
|
|
937
|
+
return {
|
|
938
|
+
ready: true,
|
|
939
|
+
auth_mode: null,
|
|
940
|
+
auth_status: 'ready',
|
|
941
|
+
execution_mode: 'subprocess',
|
|
942
|
+
message: 'Ready',
|
|
943
|
+
};
|
|
944
|
+
}
|
|
945
|
+
|
|
927
946
|
// Evaluated only after every key/env path above has had its say: it may
|
|
928
947
|
// shell out (macOS keychain, Windows `cmdkey`), which a key-configured
|
|
929
948
|
// agent never needs.
|
|
@@ -995,10 +1014,22 @@ class Installer {
|
|
|
995
1014
|
return keys.some((key) => !!(source && source[key]));
|
|
996
1015
|
}
|
|
997
1016
|
|
|
1017
|
+
/**
|
|
1018
|
+
* The credential file to look at on this platform. `creds_file_windows`
|
|
1019
|
+
* names it for a CLI that keeps its home elsewhere on Windows — Hermes uses
|
|
1020
|
+
* %LOCALAPPDATA%\hermes there, so ~/.hermes/config.yaml never existed and a
|
|
1021
|
+
* configured Hermes read "not configured".
|
|
1022
|
+
*/
|
|
1023
|
+
_credsFile(checkReady) {
|
|
1024
|
+
if (!checkReady) return null;
|
|
1025
|
+
if (process.platform === 'win32' && checkReady.creds_file_windows) return checkReady.creds_file_windows;
|
|
1026
|
+
return checkReady.creds_file || null;
|
|
1027
|
+
}
|
|
1028
|
+
|
|
998
1029
|
_checkCredsReady(checkReady, agentType) {
|
|
999
|
-
if (checkReady
|
|
1030
|
+
if (this._credsFile(checkReady)) {
|
|
1000
1031
|
try {
|
|
1001
|
-
const credsPath = this._expandHome(checkReady
|
|
1032
|
+
const credsPath = this._expandHome(this._credsFile(checkReady), agentType);
|
|
1002
1033
|
if (fs.existsSync(credsPath)) {
|
|
1003
1034
|
const stat = fs.statSync(credsPath);
|
|
1004
1035
|
if (stat.isDirectory()) return fs.readdirSync(credsPath).length > 0;
|
|
@@ -1034,6 +1065,12 @@ class Installer {
|
|
|
1034
1065
|
*/
|
|
1035
1066
|
_expandHome(p, agentType) {
|
|
1036
1067
|
if (typeof p !== 'string' || !p) return p;
|
|
1068
|
+
// A Windows location named by its variable (%LOCALAPPDATA%\hermes\…).
|
|
1069
|
+
if (/^%\w+%/.test(p)) {
|
|
1070
|
+
const m = /^%(\w+)%[\\/]?(.*)$/.exec(p);
|
|
1071
|
+
const base = m && process.env[m[1]];
|
|
1072
|
+
return base ? path.join(base, m[2]) : p;
|
|
1073
|
+
}
|
|
1037
1074
|
const home = this._homeForAgent(agentType);
|
|
1038
1075
|
if (p === '~') return home;
|
|
1039
1076
|
if (p.startsWith('~/') || p.startsWith('~\\')) return path.join(home, p.slice(2));
|
|
@@ -1068,8 +1105,8 @@ class Installer {
|
|
|
1068
1105
|
* renderer/browser user.
|
|
1069
1106
|
*/
|
|
1070
1107
|
_credsFileState(checkReady, agentType) {
|
|
1071
|
-
if (!checkReady
|
|
1072
|
-
const p = this._expandHome(checkReady
|
|
1108
|
+
if (!this._credsFile(checkReady)) return 'absent';
|
|
1109
|
+
const p = this._expandHome(this._credsFile(checkReady), agentType);
|
|
1073
1110
|
let exists = false;
|
|
1074
1111
|
try { exists = fs.existsSync(p); } catch { return 'unreadable'; }
|
|
1075
1112
|
if (!exists) return 'absent';
|
|
@@ -1109,7 +1146,7 @@ class Installer {
|
|
|
1109
1146
|
* Returns { ready, unreadable }.
|
|
1110
1147
|
*/
|
|
1111
1148
|
_evaluateCredsFile(checkReady, agentType) {
|
|
1112
|
-
if (!checkReady || !checkReady.
|
|
1149
|
+
if (!this._credsFile(checkReady) || !checkReady.creds_no_parse) {
|
|
1113
1150
|
return { ready: false, unreadable: false };
|
|
1114
1151
|
}
|
|
1115
1152
|
const state = this._credsFileState(checkReady, agentType);
|
package/src/probe.js
CHANGED
|
@@ -13,7 +13,9 @@
|
|
|
13
13
|
*
|
|
14
14
|
* Tiering (cheapest thing that proves liveness):
|
|
15
15
|
* 1. healthCheck gate — not installed / not configured fails fast with the
|
|
16
|
-
* existing auth guidance, no process spawned, no tokens spent.
|
|
16
|
+
* existing auth guidance, no process spawned, no tokens spent. An agent
|
|
17
|
+
* that declares a live CLI check still runs it: static sign-in checks
|
|
18
|
+
* miss keychains and CLI-side settings, and the run is the authority.
|
|
17
19
|
* 2. Live check, picked from the registry entry:
|
|
18
20
|
* - `probe.args` → run the agent CLI itself (e.g. --print hi)
|
|
19
21
|
* - `check_ready.alt_check` → run the entry's declared liveness command
|
|
@@ -31,7 +33,8 @@ const os = require('os');
|
|
|
31
33
|
// lives on the other side of the Windows/WSL boundary.
|
|
32
34
|
const { spawn } = require('./wsl');
|
|
33
35
|
const { getEnhancedEnv } = require('./paths');
|
|
34
|
-
const { shouldUseShellForBinary } = require('./adapters/health-status');
|
|
36
|
+
const { shouldUseShellForBinary, REASON } = require('./adapters/health-status');
|
|
37
|
+
const { decodeConsoleOutput, BENIGN_CLI_OUTPUT, stripCliNoise } = require('./adapters/utils');
|
|
35
38
|
const { formatAuthGuidance } = require('./auth-guidance');
|
|
36
39
|
const { isCliLogin, stripForCliLogin, typeEnvFor } = require('./env');
|
|
37
40
|
|
|
@@ -47,18 +50,24 @@ const CODE = {
|
|
|
47
50
|
UNKNOWN_TYPE: 'unknown_type',
|
|
48
51
|
NOT_INSTALLED: 'not_installed',
|
|
49
52
|
NOT_READY: 'not_ready',
|
|
53
|
+
VERSION_INCOMPATIBLE: 'version_incompatible',
|
|
50
54
|
INVALID_API_KEY: 'invalid_api_key',
|
|
51
55
|
MISSING_API_KEY: 'missing_api_key',
|
|
52
56
|
NOT_LOGGED_IN: 'not_logged_in',
|
|
57
|
+
SESSION_EXPIRED: 'session_expired',
|
|
53
58
|
OUT_OF_CREDIT: 'out_of_credit',
|
|
54
59
|
RATE_LIMITED: 'rate_limited',
|
|
55
60
|
NETWORK: 'network',
|
|
56
61
|
TIMEOUT: 'timeout',
|
|
57
62
|
EMPTY_RESPONSE: 'empty_response',
|
|
58
63
|
BAD_MODEL: 'bad_model',
|
|
64
|
+
SERVICE_UNAVAILABLE: 'service_unavailable',
|
|
59
65
|
CLI_ERROR: 'cli_error',
|
|
60
66
|
};
|
|
61
67
|
|
|
68
|
+
const BENIGN_OUTPUT = BENIGN_CLI_OUTPUT;
|
|
69
|
+
const withoutNoise = stripCliNoise;
|
|
70
|
+
|
|
62
71
|
/**
|
|
63
72
|
* The install command for THIS device's platform.
|
|
64
73
|
*
|
|
@@ -126,8 +135,12 @@ function classifyOutputText(text) {
|
|
|
126
135
|
if (/enotfound|econnrefused|econnreset|etimedout|eai_again|fetch failed|socket hang up|network error|self[- ]signed certificate|unable to get local issuer/.test(text)) return CODE.NETWORK;
|
|
127
136
|
if (/api key.{0,24}(not set|not found|missing)|no api key|missing api key|environment variable.{0,40}(is )?(not set|required)/.test(text)) return CODE.MISSING_API_KEY;
|
|
128
137
|
if (/invalid.{0,12}(api.?key|x-api-key|token)|incorrect api key|authentication[_ ]?error|invalid credentials|\b401\b|unauthorized|forbidden|\b403\b/.test(text)) return CODE.INVALID_API_KEY;
|
|
129
|
-
|
|
130
|
-
|
|
138
|
+
// A sign-in that exists but has run out — Claude Code: "Failed to
|
|
139
|
+
// authenticate: OAuth session expired and could not be refreshed".
|
|
140
|
+
if (/session expired|could not be refreshed|(token|sign-?in|login) (has )?expired|run \/logout and \/login/.test(text)) return CODE.SESSION_EXPIRED;
|
|
141
|
+
if (/not logged in|not authenticated|login required|authentication required|please (log ?in|sign ?in|authenticate)|(run|use) .{0,40}login|no credentials/.test(text)) return CODE.NOT_LOGGED_IN;
|
|
142
|
+
if (/unrecognized_model|model_not_found|invalid model|issue with the selected model|unknown model|model.{0,40}(does not exist|not found|not exist|is not supported)/.test(text)) return CODE.BAD_MODEL;
|
|
143
|
+
if (/\b50[234]\b|service (is )?(temporarily )?unavailable|temporarily unavailable|bad gateway|gateway time-?out/.test(text)) return CODE.SERVICE_UNAVAILABLE;
|
|
131
144
|
return null;
|
|
132
145
|
}
|
|
133
146
|
|
|
@@ -176,6 +189,11 @@ function buildGuidance(code, entry, agentEnv, extra = {}) {
|
|
|
176
189
|
? `${label} is not signed in on this device. In a terminal there, run: ${login}`
|
|
177
190
|
: `${label} is not signed in on this device. Sign in with its CLI, then re-run the test.`);
|
|
178
191
|
break;
|
|
192
|
+
case CODE.SESSION_EXPIRED:
|
|
193
|
+
lines.push(login
|
|
194
|
+
? `${label}'s sign-in on this device has expired. In a terminal there, run: ${login}`
|
|
195
|
+
: `${label}'s sign-in on this device has expired. Sign in again with its CLI, then re-run the test.`);
|
|
196
|
+
break;
|
|
179
197
|
case CODE.OUT_OF_CREDIT:
|
|
180
198
|
lines.push(`The provider account for ${label} is out of credit or quota. Add credit, or switch the agent to a different API key or model.`);
|
|
181
199
|
break;
|
|
@@ -195,6 +213,16 @@ function buildGuidance(code, entry, agentEnv, extra = {}) {
|
|
|
195
213
|
case CODE.BAD_MODEL:
|
|
196
214
|
lines.push(`The configured model isn't recognized or isn't served by ${label}'s endpoint. Pick a different model in the launcher (Agents → ${label} → Configure) or edit the agent in the workspace.`);
|
|
197
215
|
break;
|
|
216
|
+
case CODE.SERVICE_UNAVAILABLE:
|
|
217
|
+
lines.push(`The model provider for ${label} is temporarily unavailable. Wait a few minutes and test again.`);
|
|
218
|
+
break;
|
|
219
|
+
case CODE.VERSION_INCOMPATIBLE:
|
|
220
|
+
lines.push(`The installed ${label} version is not the one OpenAgents supports. Reinstall it from the launcher's Install page.`);
|
|
221
|
+
{
|
|
222
|
+
const cmd = installCommandFor(entry);
|
|
223
|
+
if (cmd) lines.push(`Or reinstall manually: ${cmd}`);
|
|
224
|
+
}
|
|
225
|
+
break;
|
|
198
226
|
case CODE.NOT_READY:
|
|
199
227
|
// Caller supplies the static-auth guidance lines instead.
|
|
200
228
|
break;
|
|
@@ -236,6 +264,51 @@ async function directApiVerdict(agentEnv, entry) {
|
|
|
236
264
|
};
|
|
237
265
|
}
|
|
238
266
|
|
|
267
|
+
/**
|
|
268
|
+
* Stop a CLI that ran too long. On Windows a .cmd shim runs under cmd.exe, and
|
|
269
|
+
* killing that leaves the node process it started alive (see cli-models.js).
|
|
270
|
+
*/
|
|
271
|
+
function killTree(child) {
|
|
272
|
+
if (process.platform === 'win32' && child.pid) {
|
|
273
|
+
try {
|
|
274
|
+
const killer = spawn('taskkill', ['/T', '/F', '/PID', String(child.pid)], { windowsHide: true, stdio: 'ignore' });
|
|
275
|
+
if (killer && typeof killer.on === 'function') killer.on('error', () => {});
|
|
276
|
+
} catch {}
|
|
277
|
+
}
|
|
278
|
+
try { child.kill('SIGKILL'); } catch {}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* A resolved binary as cmd.exe must see it. Node hands a shell: true spawn to
|
|
283
|
+
* cmd.exe as one unquoted line, so a CLI under "F:\Program Files\…" or a
|
|
284
|
+
* profile folder with a space in it was cut at the space and the probe read
|
|
285
|
+
* "'F:\Program' is not recognized" (in GBK, as mojibake).
|
|
286
|
+
*/
|
|
287
|
+
function shellQuoted(binary, shell) {
|
|
288
|
+
return shell && !/^".*"$/.test(binary) ? `"${binary}"` : binary;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* The one line worth reporting from a failed run.
|
|
293
|
+
*
|
|
294
|
+
* Stderr used to win outright, so a harmless warning there hid the real error
|
|
295
|
+
* on stdout, and a timeout with any output never said it timed out. Now: the
|
|
296
|
+
* line that the classifier recognised, else the output minus known noise,
|
|
297
|
+
* with the timeout named first.
|
|
298
|
+
*/
|
|
299
|
+
function failureMessage(res, code, timeoutMs) {
|
|
300
|
+
const lines = (s) => String(s || '').split(/\r?\n/).map((l) => l.trim())
|
|
301
|
+
.filter((l) => l && !BENIGN_OUTPUT.test(l));
|
|
302
|
+
const all = [...lines(res.stderr), ...lines(res.stdout)];
|
|
303
|
+
const telling = all.find((l) => classifyOutputText(l.toLowerCase()) === code);
|
|
304
|
+
const detail = tail(telling || lines(res.stderr).join('\n') || lines(res.stdout).join('\n'), OUTPUT_CAP);
|
|
305
|
+
if (res.timedOut) {
|
|
306
|
+
const prefix = `Timed out after ${Math.round(timeoutMs / 1000)}s`;
|
|
307
|
+
return detail ? `${prefix}: ${detail}` : prefix;
|
|
308
|
+
}
|
|
309
|
+
return detail || `Exited with code ${res.code}`;
|
|
310
|
+
}
|
|
311
|
+
|
|
239
312
|
/** Run a CLI to completion with a hard timeout. Never rejects. */
|
|
240
313
|
function runCommand(cmd, args, { env, timeoutMs, shell = false }) {
|
|
241
314
|
return new Promise((resolve) => {
|
|
@@ -252,22 +325,33 @@ function runCommand(cmd, args, { env, timeoutMs, shell = false }) {
|
|
|
252
325
|
resolve({ code: 1, stdout: '', stderr: '', spawnError: e.message, timedOut: false });
|
|
253
326
|
return;
|
|
254
327
|
}
|
|
255
|
-
|
|
256
|
-
|
|
328
|
+
// Bytes, decoded once at the end: a multi-byte character can straddle two
|
|
329
|
+
// chunks, and cmd.exe's own errors are in the console code page.
|
|
330
|
+
const stdout = [];
|
|
331
|
+
const stderr = [];
|
|
257
332
|
let timedOut = false;
|
|
258
333
|
let settled = false;
|
|
259
|
-
const timer = setTimeout(() => {
|
|
260
|
-
timedOut = true;
|
|
261
|
-
try { child.kill('SIGKILL'); } catch {}
|
|
262
|
-
}, timeoutMs);
|
|
263
334
|
const finish = (code, spawnError) => {
|
|
264
335
|
if (settled) return;
|
|
265
336
|
settled = true;
|
|
266
337
|
clearTimeout(timer);
|
|
267
|
-
resolve({
|
|
338
|
+
resolve({
|
|
339
|
+
code,
|
|
340
|
+
stdout: decodeConsoleOutput(Buffer.concat(stdout)),
|
|
341
|
+
stderr: decodeConsoleOutput(Buffer.concat(stderr)),
|
|
342
|
+
spawnError: spawnError || null,
|
|
343
|
+
timedOut,
|
|
344
|
+
});
|
|
268
345
|
};
|
|
269
|
-
|
|
270
|
-
|
|
346
|
+
// Settles here and not on 'close' alone: a grandchild that survives the
|
|
347
|
+
// kill can hold stdout open, and 'close' then never comes.
|
|
348
|
+
const timer = setTimeout(() => {
|
|
349
|
+
timedOut = true;
|
|
350
|
+
killTree(child);
|
|
351
|
+
finish(1);
|
|
352
|
+
}, timeoutMs);
|
|
353
|
+
child.stdout.on('data', (d) => { stdout.push(Buffer.from(d)); });
|
|
354
|
+
child.stderr.on('data', (d) => { stderr.push(Buffer.from(d)); });
|
|
271
355
|
child.on('error', (e) => finish(1, e.message));
|
|
272
356
|
child.on('close', (code) => finish(code == null ? 1 : code));
|
|
273
357
|
});
|
|
@@ -321,16 +405,37 @@ async function probeAgentType(connector, type, opts = {}) {
|
|
|
321
405
|
});
|
|
322
406
|
}
|
|
323
407
|
|
|
408
|
+
// Installed, but not a version this integration supports. Not a sign-in
|
|
409
|
+
// problem, so the sign-in guidance would only send the user the wrong way.
|
|
410
|
+
if (health.reason === REASON.VERSION_INCOMPATIBLE || health.compatible === false) {
|
|
411
|
+
return done({
|
|
412
|
+
ok: false, method: 'none', code: CODE.VERSION_INCOMPATIBLE,
|
|
413
|
+
message: health.message || 'Unsupported version',
|
|
414
|
+
guidance: buildGuidance(CODE.VERSION_INCOMPATIBLE, entry, agentEnv),
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
const probeArgs = entry.probe && Array.isArray(entry.probe.args) ? entry.probe.args : null;
|
|
419
|
+
const altCheck = entry.check_ready && entry.check_ready.alt_check;
|
|
420
|
+
const hasLiveCli = !!((probeArgs && health.binary) || altCheck);
|
|
421
|
+
|
|
324
422
|
// Definitively unconfigured (auth_status 'unknown' still gets a live try:
|
|
325
423
|
// the real run is the final authority for unverifiable logins).
|
|
424
|
+
let staticVerdict = null;
|
|
326
425
|
if (!health.ready && health.auth_status !== 'unknown') {
|
|
327
426
|
let lines = [];
|
|
328
427
|
try { lines = formatAuthGuidance(entry, health).lines; } catch {}
|
|
329
|
-
|
|
428
|
+
staticVerdict = {
|
|
330
429
|
ok: false, method: 'none', code: CODE.NOT_READY,
|
|
331
430
|
message: health.message || 'Not configured',
|
|
332
431
|
guidance: lines.length ? lines : buildGuidance(CODE.NOT_LOGGED_IN, entry, agentEnv),
|
|
333
|
-
}
|
|
432
|
+
};
|
|
433
|
+
// A sign-in kept where the static checks cannot see it (a keychain, a
|
|
434
|
+
// relay set up in the CLI's own settings) answered fine and was still
|
|
435
|
+
// reported "Not logged in". Where the agent declares a live check, that
|
|
436
|
+
// run decides; the static verdict only stands in when the run explains
|
|
437
|
+
// nothing.
|
|
438
|
+
if (!hasLiveCli) return done(staticVerdict);
|
|
334
439
|
}
|
|
335
440
|
|
|
336
441
|
const timeoutMs = opts.timeoutMs
|
|
@@ -338,27 +443,29 @@ async function probeAgentType(connector, type, opts = {}) {
|
|
|
338
443
|
const env = stripForCliLogin(type, { ...getEnhancedEnv(), ...agentEnv }, connector.registry, opts.agentEnv);
|
|
339
444
|
|
|
340
445
|
// Hoisted above the CLI tier: a failing CLI probe consults it too (below).
|
|
341
|
-
|
|
446
|
+
// `probe.api_test: false` opts out for an agent whose key is not a model
|
|
447
|
+
// API key (Cursor's is for Cursor's own service): an OpenAI-style call with
|
|
448
|
+
// it proves nothing either way.
|
|
449
|
+
const apiTestable = !(entry.probe && entry.probe.api_test === false);
|
|
450
|
+
const hasApiKey = apiTestable && !!(agentEnv.LLM_API_KEY || agentEnv.OPENAI_API_KEY || agentEnv.ANTHROPIC_API_KEY
|
|
342
451
|
|| agentEnv.ANTHROPIC_AUTH_TOKEN || agentEnv.KIMI_API_KEY || agentEnv.MOONSHOT_API_KEY);
|
|
343
452
|
|
|
344
453
|
// ── Live tier 1: the agent's own CLI, when the registry declares how ──
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
if ((probeArgs && health.binary) || altCheck) {
|
|
454
|
+
if (hasLiveCli) {
|
|
455
|
+
const shell = probeArgs && health.binary ? shouldUseShellForBinary(health.binary) : true;
|
|
348
456
|
const res = probeArgs && health.binary
|
|
349
457
|
// Node refuses to spawn .cmd/.bat without a shell (EINVAL since the
|
|
350
458
|
// CVE-2024-27980 hardening), which made every Windows CLI probe of an
|
|
351
459
|
// npm-shim binary fail as "Exited with code 1" with no output.
|
|
352
|
-
? await runCommand(health.binary, probeArgs, {
|
|
353
|
-
env, timeoutMs, shell: shouldUseShellForBinary(health.binary),
|
|
354
|
-
})
|
|
460
|
+
? await runCommand(shellQuoted(health.binary, shell), probeArgs, { env, timeoutMs, shell })
|
|
355
461
|
: await runCommand(altCheck, [], { env, timeoutMs, shell: true });
|
|
356
|
-
const output = `${res.stdout}\n${res.stderr}
|
|
357
|
-
|
|
462
|
+
const output = withoutNoise(`${res.stdout}\n${res.stderr}`);
|
|
463
|
+
const reply = withoutNoise(res.stdout).trim();
|
|
464
|
+
if (!res.timedOut && !res.spawnError && res.code === 0 && reply) {
|
|
358
465
|
return done({
|
|
359
466
|
ok: true, method: 'cli', code: CODE.OK,
|
|
360
467
|
message: 'Responded',
|
|
361
|
-
reply: tail(
|
|
468
|
+
reply: tail(reply, REPLY_CAP),
|
|
362
469
|
});
|
|
363
470
|
}
|
|
364
471
|
let code = res.code === 0 && !res.timedOut && !res.spawnError
|
|
@@ -385,10 +492,11 @@ async function probeAgentType(connector, type, opts = {}) {
|
|
|
385
492
|
const direct = await directApiVerdict(agentEnv, entry);
|
|
386
493
|
if (direct) return done(direct);
|
|
387
494
|
}
|
|
495
|
+
if (unexplained && staticVerdict) return done(staticVerdict);
|
|
388
496
|
|
|
389
497
|
return done({
|
|
390
498
|
ok: false, method: 'cli', code,
|
|
391
|
-
message:
|
|
499
|
+
message: failureMessage(res, code, timeoutMs),
|
|
392
500
|
guidance: buildGuidance(code, entry, agentEnv, { timeoutMs }),
|
|
393
501
|
});
|
|
394
502
|
}
|
|
@@ -414,9 +522,13 @@ async function probeAgentType(connector, type, opts = {}) {
|
|
|
414
522
|
}
|
|
415
523
|
|
|
416
524
|
// ── No safe live probe — report the static result honestly rather than
|
|
417
|
-
// inventing a CLI invocation that could misfire.
|
|
525
|
+
// inventing a CLI invocation that could misfire. Reaching here not ready
|
|
526
|
+
// means the sign-in could not be checked (auth_status 'unknown'): that is
|
|
527
|
+
// ok: null, not a failure — counted as one, every signed-in Codex or Cursor
|
|
528
|
+
// whose status command was slow read as "Not configured". ──
|
|
418
529
|
return done({
|
|
419
|
-
ok: health.ready === true, method: 'none', code: CODE.STATIC_ONLY,
|
|
530
|
+
ok: health.ready === true ? true : null, method: 'none', code: CODE.STATIC_ONLY,
|
|
531
|
+
auth_status: health.auth_status || null,
|
|
420
532
|
message: health.ready
|
|
421
533
|
? 'Static checks passed (no live probe is defined for this agent type)'
|
|
422
534
|
: (health.message || 'Not configured'),
|
package/src/utils.js
CHANGED
|
@@ -1,5 +1,93 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
/**
|
|
4
|
+
* How many advertised models to try before giving up on an endpoint's list.
|
|
5
|
+
* More than one because a gateway's list and what its backend actually serves
|
|
6
|
+
* are not the same set — same rule as the launcher's LLM test.
|
|
7
|
+
*/
|
|
8
|
+
const MODEL_CANDIDATES = 4;
|
|
9
|
+
|
|
10
|
+
/** Catalogue entries that cannot answer a chat completion. */
|
|
11
|
+
const NON_CHAT_MODEL =
|
|
12
|
+
/embed|whisper|tts|audio|dall-e|image|moderation|rerank|guard|transcribe|realtime|search|vision-preview/i;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Vendors whose own default model is known-good, and whose `/models` list is
|
|
16
|
+
* long, arbitrarily ordered and full of non-chat entries. Everything else (a
|
|
17
|
+
* relay, a self-hosted gateway, the OpenAgents gateway) is asked what it serves.
|
|
18
|
+
*/
|
|
19
|
+
const VENDOR_HOSTS = /(^|\.)(openai\.com|moonshot\.ai|deepseek\.com|anthropic\.com|x\.ai|mistral\.ai)$/i;
|
|
20
|
+
|
|
21
|
+
/** An endpoint saying "I don't serve that model", in any of its dialects. */
|
|
22
|
+
const MODEL_REJECTED =
|
|
23
|
+
/model.{0,60}?(is not available|does not exist|not found|unknown model|invalid model|no such model|not supported)|model_not_found/is;
|
|
24
|
+
|
|
25
|
+
/** One HTTP request. Resolves { status, data } or { error }; never rejects. */
|
|
26
|
+
function request(url, { method = 'POST', headers = {}, body = null, timeout = 15000 } = {}) {
|
|
27
|
+
const https = require('https');
|
|
28
|
+
const http = require('http');
|
|
29
|
+
return new Promise((resolve) => {
|
|
30
|
+
let parsedUrl;
|
|
31
|
+
try { parsedUrl = new URL(url); } catch (e) { resolve({ error: e.message }); return; }
|
|
32
|
+
const transport = parsedUrl.protocol === 'https:' ? https : http;
|
|
33
|
+
const allHeaders = body ? { ...headers, 'Content-Length': Buffer.byteLength(body) } : headers;
|
|
34
|
+
const req = transport.request(url, { method, headers: allHeaders, timeout }, (res) => {
|
|
35
|
+
let data = '';
|
|
36
|
+
res.on('data', (chunk) => { data += chunk; });
|
|
37
|
+
res.on('end', () => resolve({ status: res.statusCode, data }));
|
|
38
|
+
});
|
|
39
|
+
req.on('error', (e) => resolve({ error: e.message }));
|
|
40
|
+
req.on('timeout', () => { req.destroy(); resolve({ error: 'Request timed out' }); });
|
|
41
|
+
if (body) req.write(body);
|
|
42
|
+
req.end();
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The chat models an OpenAI-compatible endpoint says it serves, or [] when it
|
|
48
|
+
* publishes no readable list. A list we cannot read is not a test failure —
|
|
49
|
+
* the caller still has its default model to fall back on.
|
|
50
|
+
*/
|
|
51
|
+
async function servedModels(apiBase, headers) {
|
|
52
|
+
const res = await request(`${apiBase}/models`, { method: 'GET', headers, timeout: 10000 });
|
|
53
|
+
if (res.error || res.status >= 400) return [];
|
|
54
|
+
try {
|
|
55
|
+
const data = JSON.parse(res.data).data;
|
|
56
|
+
if (!Array.isArray(data)) return [];
|
|
57
|
+
const ids = [];
|
|
58
|
+
for (const m of data) {
|
|
59
|
+
const id = m && typeof m.id === 'string' ? m.id.trim() : '';
|
|
60
|
+
if (id && !NON_CHAT_MODEL.test(id) && !ids.includes(id)) ids.push(id);
|
|
61
|
+
if (ids.length >= MODEL_CANDIDATES) break;
|
|
62
|
+
}
|
|
63
|
+
return ids;
|
|
64
|
+
} catch {
|
|
65
|
+
return [];
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Read one completion response into the result shape. */
|
|
70
|
+
function completionResult(res, { isAnthropic, model }) {
|
|
71
|
+
if (res.error) return { success: false, error: res.error };
|
|
72
|
+
const { status, data } = res;
|
|
73
|
+
try {
|
|
74
|
+
const parsed = JSON.parse(data);
|
|
75
|
+
let text, usedModel;
|
|
76
|
+
if (isAnthropic) {
|
|
77
|
+
text = (parsed.content || [{}])[0].text || '';
|
|
78
|
+
usedModel = parsed.model || model || '?';
|
|
79
|
+
} else {
|
|
80
|
+
text = (parsed.choices || [{}])[0]?.message?.content || '';
|
|
81
|
+
usedModel = parsed.model || model || '?';
|
|
82
|
+
}
|
|
83
|
+
if (status >= 400) return { success: false, error: `HTTP ${status}: ${data.slice(0, 200)}` };
|
|
84
|
+
return { success: true, model: usedModel, response: text.slice(0, 80) };
|
|
85
|
+
} catch {
|
|
86
|
+
if (status >= 400) return { success: false, error: `HTTP ${status}: ${data.slice(0, 200)}` };
|
|
87
|
+
return { success: false, error: `Invalid response: ${data.slice(0, 200)}` };
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
3
91
|
/**
|
|
4
92
|
* Test an LLM connection by sending a minimal inference request.
|
|
5
93
|
*
|
|
@@ -8,14 +96,11 @@
|
|
|
8
96
|
* @param {object} env - Env vars (LLM_API_KEY, LLM_BASE_URL, LLM_MODEL, etc.)
|
|
9
97
|
* @returns {Promise<{success: boolean, model?: string, response?: string, error?: string}>}
|
|
10
98
|
*/
|
|
11
|
-
function testLLMConnection(env) {
|
|
12
|
-
const https = require('https');
|
|
13
|
-
const http = require('http');
|
|
14
|
-
|
|
99
|
+
async function testLLMConnection(env) {
|
|
15
100
|
const hasKimiConfig = !!(env.KIMI_API_KEY || env.MOONSHOT_API_KEY || env.KIMI_BASE_URL || env.KIMI_MODEL);
|
|
16
101
|
const apiKey = env.KIMI_API_KEY || env.MOONSHOT_API_KEY || env.LLM_API_KEY || env.OPENAI_API_KEY
|
|
17
102
|
|| env.ANTHROPIC_AUTH_TOKEN || env.ANTHROPIC_API_KEY || '';
|
|
18
|
-
if (!apiKey) return
|
|
103
|
+
if (!apiKey) return { success: false, error: 'No API key provided' };
|
|
19
104
|
|
|
20
105
|
let baseUrl = (env.KIMI_BASE_URL || env.LLM_BASE_URL || env.OPENAI_BASE_URL || (hasKimiConfig ? 'https://api.moonshot.ai/v1' : 'https://api.openai.com/v1')).replace(/\/$/, '');
|
|
21
106
|
const model = env.KIMI_MODEL || env.LLM_MODEL || env.OPENCLAW_MODEL || '';
|
|
@@ -32,84 +117,68 @@ function testLLMConnection(env) {
|
|
|
32
117
|
baseUrl += '/v1';
|
|
33
118
|
}
|
|
34
119
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
// sends the bearer when pointed at one. Only off the official host: the
|
|
52
|
-
// real API has no use for it.
|
|
120
|
+
if (isAnthropic) {
|
|
121
|
+
// The configured endpoint, not the official one: a relay IS the API as
|
|
122
|
+
// far as this agent is concerned, and testing api.anthropic.com would
|
|
123
|
+
// report on a service the agent never talks to.
|
|
124
|
+
const base = (env.ANTHROPIC_BASE_URL || 'https://api.anthropic.com').replace(/\/+$/, '');
|
|
125
|
+
const url = /\/v1$/.test(base) ? `${base}/messages` : `${base}/v1/messages`;
|
|
126
|
+
const token = env.ANTHROPIC_AUTH_TOKEN || env.ANTHROPIC_API_KEY || apiKey;
|
|
127
|
+
const headers = {
|
|
128
|
+
'x-api-key': token,
|
|
129
|
+
'anthropic-version': '2023-06-01',
|
|
130
|
+
'content-type': 'application/json',
|
|
131
|
+
};
|
|
132
|
+
// Relays are split on which header they read, and Claude Code itself
|
|
133
|
+
// sends the bearer when pointed at one. Only off the official host: the
|
|
134
|
+
// real API has no use for it.
|
|
135
|
+
try {
|
|
53
136
|
if (!/api\.anthropic\.com$/.test(new URL(url).hostname)) {
|
|
54
137
|
headers['authorization'] = `Bearer ${token}`;
|
|
55
138
|
}
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
}
|
|
61
|
-
} else {
|
|
62
|
-
url = baseUrl + '/chat/completions';
|
|
63
|
-
headers = {
|
|
64
|
-
'Authorization': `Bearer ${apiKey}`,
|
|
65
|
-
'Content-Type': 'application/json',
|
|
66
|
-
};
|
|
67
|
-
const requestBody = {
|
|
68
|
-
model: model || (hasKimiConfig ? 'kimi-k2.6' : 'gpt-4o-mini'),
|
|
69
|
-
messages: [{ role: 'user', content: 'Say hi in 5 words.' }],
|
|
70
|
-
};
|
|
71
|
-
if (hasKimiConfig) requestBody.max_tokens = 32;
|
|
72
|
-
else requestBody.max_completion_tokens = 32;
|
|
73
|
-
body = JSON.stringify(requestBody);
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
const parsedUrl = new URL(url);
|
|
77
|
-
const transport = parsedUrl.protocol === 'https:' ? https : http;
|
|
78
|
-
|
|
79
|
-
const req = transport.request(url, {
|
|
80
|
-
method: 'POST',
|
|
81
|
-
headers: { ...headers, 'Content-Length': Buffer.byteLength(body) },
|
|
82
|
-
timeout: 15000,
|
|
83
|
-
}, (res) => {
|
|
84
|
-
let data = '';
|
|
85
|
-
res.on('data', (chunk) => { data += chunk; });
|
|
86
|
-
res.on('end', () => {
|
|
87
|
-
try {
|
|
88
|
-
const parsed = JSON.parse(data);
|
|
89
|
-
let text, usedModel;
|
|
90
|
-
if (isAnthropic) {
|
|
91
|
-
text = (parsed.content || [{}])[0].text || '';
|
|
92
|
-
usedModel = parsed.model || model || '?';
|
|
93
|
-
} else {
|
|
94
|
-
text = (parsed.choices || [{}])[0]?.message?.content || '';
|
|
95
|
-
usedModel = parsed.model || model || '?';
|
|
96
|
-
}
|
|
97
|
-
if (res.statusCode >= 400) {
|
|
98
|
-
resolve({ success: false, error: `HTTP ${res.statusCode}: ${data.slice(0, 200)}` });
|
|
99
|
-
} else {
|
|
100
|
-
resolve({ success: true, model: usedModel, response: text.slice(0, 80) });
|
|
101
|
-
}
|
|
102
|
-
} catch {
|
|
103
|
-
resolve({ success: false, error: `Invalid response: ${data.slice(0, 200)}` });
|
|
104
|
-
}
|
|
105
|
-
});
|
|
139
|
+
} catch {}
|
|
140
|
+
const body = JSON.stringify({
|
|
141
|
+
model: env.ANTHROPIC_MODEL || model || 'claude-sonnet-4-20250514',
|
|
142
|
+
max_tokens: 32,
|
|
143
|
+
messages: [{ role: 'user', content: 'Say hi in 5 words.' }],
|
|
106
144
|
});
|
|
145
|
+
const res = await request(url, { headers, body });
|
|
146
|
+
return completionResult(res, { isAnthropic: true, model });
|
|
147
|
+
}
|
|
107
148
|
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
149
|
+
const headers = {
|
|
150
|
+
'Authorization': `Bearer ${apiKey}`,
|
|
151
|
+
'Content-Type': 'application/json',
|
|
152
|
+
};
|
|
153
|
+
// A blank model used to mean a hardcoded `gpt-4o-mini`, which exists only on
|
|
154
|
+
// OpenAI itself: on a relay or the OpenAgents gateway the smoke test then
|
|
155
|
+
// failed with "Model 'gpt-4o-mini' is not available" for an agent that
|
|
156
|
+
// works. Ask a non-vendor endpoint what it serves first.
|
|
157
|
+
const fallback = hasKimiConfig ? 'kimi-k2.6' : 'gpt-4o-mini';
|
|
158
|
+
let candidates = [model];
|
|
159
|
+
if (!model) {
|
|
160
|
+
let host = '';
|
|
161
|
+
try { host = new URL(baseUrl).hostname; } catch {}
|
|
162
|
+
const listed = VENDOR_HOSTS.test(host) ? [] : await servedModels(baseUrl, headers);
|
|
163
|
+
candidates = listed.includes(fallback) ? listed : listed.concat(fallback);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
let last = null;
|
|
167
|
+
for (const candidate of candidates) {
|
|
168
|
+
const requestBody = {
|
|
169
|
+
model: candidate,
|
|
170
|
+
messages: [{ role: 'user', content: 'Say hi in 5 words.' }],
|
|
171
|
+
};
|
|
172
|
+
if (hasKimiConfig) requestBody.max_tokens = 32;
|
|
173
|
+
else requestBody.max_completion_tokens = 32;
|
|
174
|
+
const res = await request(`${baseUrl}/chat/completions`, { headers, body: JSON.stringify(requestBody) });
|
|
175
|
+
last = completionResult(res, { isAnthropic: false, model: candidate });
|
|
176
|
+
if (last.success) return last;
|
|
177
|
+
// Only a model WE picked moves on to the next one. A configured model is
|
|
178
|
+
// sent as configured and its rejection reported as-is.
|
|
179
|
+
if (model || res.error || !MODEL_REJECTED.test(res.data || '')) return last;
|
|
180
|
+
}
|
|
181
|
+
return last;
|
|
113
182
|
}
|
|
114
183
|
|
|
115
184
|
module.exports = { testLLMConnection };
|