@openagents-org/agent-launcher 0.2.200 → 0.2.202
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 +58 -19
- package/src/adapters/claude.js +4 -2
- package/src/adapters/codex.js +29 -15
- package/src/adapters/utils.js +33 -0
- package/src/cli.js +11 -1
- package/src/daemon.js +150 -20
- package/src/index.js +12 -1
- package/src/installer.js +43 -6
- package/src/probe.js +148 -31
- 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
|
{
|
|
@@ -239,6 +246,15 @@
|
|
|
239
246
|
null
|
|
240
247
|
]
|
|
241
248
|
},
|
|
249
|
+
"probe": {
|
|
250
|
+
"args": [
|
|
251
|
+
"exec",
|
|
252
|
+
"--skip-git-repo-check",
|
|
253
|
+
"hi"
|
|
254
|
+
],
|
|
255
|
+
"timeout_s": 120,
|
|
256
|
+
"skip_cli_with_key": true
|
|
257
|
+
},
|
|
242
258
|
"check_ready": {
|
|
243
259
|
"env_all": [
|
|
244
260
|
"OPENAI_API_KEY",
|
|
@@ -248,7 +264,14 @@
|
|
|
248
264
|
"OPENAI_API_KEY",
|
|
249
265
|
"OPENAI_BASE_URL"
|
|
250
266
|
],
|
|
251
|
-
"
|
|
267
|
+
"creds_file": "~/.codex/auth.json",
|
|
268
|
+
"creds_no_parse": true,
|
|
269
|
+
"status_args": [
|
|
270
|
+
"login",
|
|
271
|
+
"status"
|
|
272
|
+
],
|
|
273
|
+
"logged_in_pattern": "logged in using",
|
|
274
|
+
"logged_out_pattern": "not logged in",
|
|
252
275
|
"login_command": "codex login",
|
|
253
276
|
"unverifiable": true,
|
|
254
277
|
"not_ready_message": "Not configured. Set OPENAI_API_KEY + OPENAI_BASE_URL, or run: codex login"
|
|
@@ -402,7 +425,10 @@
|
|
|
402
425
|
},
|
|
403
426
|
"vendor": "Cursor",
|
|
404
427
|
"tagline": "The AI editor you love — now headless on your node.",
|
|
405
|
-
"provider_locked": true
|
|
428
|
+
"provider_locked": true,
|
|
429
|
+
"probe": {
|
|
430
|
+
"api_test": false
|
|
431
|
+
}
|
|
406
432
|
},
|
|
407
433
|
{
|
|
408
434
|
"name": "opencode",
|
|
@@ -448,7 +474,13 @@
|
|
|
448
474
|
],
|
|
449
475
|
"saved_env_key": "LLM_API_KEY",
|
|
450
476
|
"min_version": "1.17.0",
|
|
451
|
-
"not_ready_message": "Not configured —
|
|
477
|
+
"not_ready_message": "Not configured — sign in with `opencode auth login`, pick a free opencode/ model, or add an API key in Configure",
|
|
478
|
+
"creds_file": "~/.local/share/opencode/auth.json",
|
|
479
|
+
"creds_no_parse": true,
|
|
480
|
+
"creds_json_has_entries": true,
|
|
481
|
+
"keyless_model_prefixes": [
|
|
482
|
+
"opencode/"
|
|
483
|
+
]
|
|
452
484
|
},
|
|
453
485
|
"env_config": [
|
|
454
486
|
{
|
|
@@ -561,8 +593,12 @@
|
|
|
561
593
|
},
|
|
562
594
|
"check_ready": {
|
|
563
595
|
"creds_file": "~/.hermes/config.yaml",
|
|
596
|
+
"creds_file_windows": "%LOCALAPPDATA%/hermes/config.yaml",
|
|
564
597
|
"creds_no_parse": true,
|
|
565
|
-
"
|
|
598
|
+
"status_args": [
|
|
599
|
+
"status"
|
|
600
|
+
],
|
|
601
|
+
"logged_in_pattern": "✓\\s*logged in",
|
|
566
602
|
"login_command": "hermes setup",
|
|
567
603
|
"not_ready_message": "Hermes not configured — run: hermes setup",
|
|
568
604
|
"env_vars": [
|
|
@@ -670,7 +706,10 @@
|
|
|
670
706
|
],
|
|
671
707
|
"saved_env_key": "KIMI_API_KEY",
|
|
672
708
|
"login_command": "kimi login",
|
|
673
|
-
"not_ready_message": "Not configured — set an API key
|
|
709
|
+
"not_ready_message": "Not configured — set an API key in Configure, or run: kimi login",
|
|
710
|
+
"creds_file": "~/.kimi-code/credentials/kimi-code.json",
|
|
711
|
+
"creds_no_parse": true,
|
|
712
|
+
"creds_key": "refresh_token"
|
|
674
713
|
},
|
|
675
714
|
"env_config": [
|
|
676
715
|
{
|
|
@@ -968,7 +1007,7 @@
|
|
|
968
1007
|
"DEEPSEEK_API_KEY"
|
|
969
1008
|
],
|
|
970
1009
|
"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)
|
|
1010
|
+
"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
1011
|
},
|
|
973
1012
|
"env_config": [
|
|
974
1013
|
{
|
|
@@ -1138,7 +1177,7 @@
|
|
|
1138
1177
|
],
|
|
1139
1178
|
"saved_env_key": "CLINE_API_KEY",
|
|
1140
1179
|
"login_command": "cline auth",
|
|
1141
|
-
"not_ready_message": "Not configured — set an API key
|
|
1180
|
+
"not_ready_message": "Not configured — set an API key in Configure, or run: cline auth"
|
|
1142
1181
|
},
|
|
1143
1182
|
"env_config": [
|
|
1144
1183
|
{
|
|
@@ -1391,7 +1430,7 @@
|
|
|
1391
1430
|
"NANOCLAW_AGENT_GROUP"
|
|
1392
1431
|
],
|
|
1393
1432
|
"saved_env_key": "NANOCLAW_AGENT_GROUP",
|
|
1394
|
-
"not_ready_message": "Set NANOCLAW_AGENT_GROUP (and NANOCLAW_HOME)
|
|
1433
|
+
"not_ready_message": "Set NANOCLAW_AGENT_GROUP (and NANOCLAW_HOME) in Configure"
|
|
1395
1434
|
},
|
|
1396
1435
|
"env_config": [
|
|
1397
1436
|
{
|
|
@@ -1599,7 +1638,7 @@
|
|
|
1599
1638
|
],
|
|
1600
1639
|
"saved_env_key": "PI_API_KEY",
|
|
1601
1640
|
"login_command": "pi",
|
|
1602
|
-
"not_ready_message": "Not configured — set a provider API key
|
|
1641
|
+
"not_ready_message": "Not configured — set a provider API key in Configure, or run `pi` and use /login once.",
|
|
1603
1642
|
"unreadable_message": "Pi credentials were found but could not be read. Check permissions on ~/.pi/agent, or run `pi` and sign in again."
|
|
1604
1643
|
},
|
|
1605
1644
|
"env_config": [
|
|
@@ -1778,7 +1817,7 @@
|
|
|
1778
1817
|
"DEEPSEEK_API_KEY"
|
|
1779
1818
|
],
|
|
1780
1819
|
"saved_env_key": "DEEPSEEK_API_KEY",
|
|
1781
|
-
"not_ready_message": "Not configured — set DEEPSEEK_API_KEY
|
|
1820
|
+
"not_ready_message": "Not configured — set DEEPSEEK_API_KEY in Configure. The harness has no CLI sign-in.",
|
|
1782
1821
|
"unreadable_message": "DeepSeek Harness credentials could not be read. Re-enter DEEPSEEK_API_KEY in the Configure screen."
|
|
1783
1822
|
},
|
|
1784
1823
|
"env_config": [
|
|
@@ -1890,7 +1929,7 @@
|
|
|
1890
1929
|
],
|
|
1891
1930
|
"saved_env_key": "COMMAND_CODE_API_KEY",
|
|
1892
1931
|
"login_command": "command-code login",
|
|
1893
|
-
"not_ready_message": "Not configured — sign in with `command-code login`, or set COMMAND_CODE_API_KEY
|
|
1932
|
+
"not_ready_message": "Not configured — sign in with `command-code login`, or set COMMAND_CODE_API_KEY in Configure",
|
|
1894
1933
|
"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
1934
|
},
|
|
1896
1935
|
"env_config": [
|
|
@@ -1996,7 +2035,7 @@
|
|
|
1996
2035
|
"GEMINI_API_KEY"
|
|
1997
2036
|
],
|
|
1998
2037
|
"saved_env_key": "OPENWORKER_API_KEY",
|
|
1999
|
-
"not_ready_message": "No model API key — pick a provider and set OPENWORKER_API_KEY
|
|
2038
|
+
"not_ready_message": "No model API key — pick a provider and set OPENWORKER_API_KEY in Configure",
|
|
2000
2039
|
"unreadable_message": "The OpenWorker model key could not be read. Re-enter OPENWORKER_API_KEY in the Configure screen."
|
|
2001
2040
|
},
|
|
2002
2041
|
"env_config": [
|
|
@@ -2209,7 +2248,7 @@
|
|
|
2209
2248
|
"saved_env_key": "CODEBUDDY_API_KEY",
|
|
2210
2249
|
"login_command": "codebuddy",
|
|
2211
2250
|
"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
|
|
2251
|
+
"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
2252
|
"auth_detected_labels": {
|
|
2214
2253
|
"cli_login": "CodeBuddy sign-in detected",
|
|
2215
2254
|
"api_key": "API key detected"
|
|
@@ -2302,7 +2341,7 @@
|
|
|
2302
2341
|
"CODEARTS_CLI_AK",
|
|
2303
2342
|
"CODEARTS_CLI_SK"
|
|
2304
2343
|
],
|
|
2305
|
-
"not_ready_message": "Needs a Huawei Cloud access key — set CODEARTS_CLI_AK and CODEARTS_CLI_SK
|
|
2344
|
+
"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
2345
|
}
|
|
2307
2346
|
}
|
|
2308
2347
|
]
|
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';
|
|
@@ -218,16 +218,30 @@ class CodexAdapter extends BaseAdapter {
|
|
|
218
218
|
if (!isWindows || !/\.(cmd|bat)$/.test(lower)) return { file: bin, args: [], shell: false };
|
|
219
219
|
try {
|
|
220
220
|
const content = fs.readFileSync(bin, 'utf-8');
|
|
221
|
-
|
|
221
|
+
// Both npm shim styles: `"%dp0%\x.js"` and the older `"%~dp0\x.js"`.
|
|
222
|
+
const js = content.match(/%~?dp0%?\\([^\s"*?]+\.[cm]?js)/i);
|
|
222
223
|
if (js) {
|
|
223
224
|
return { file: this._findNodeBin(), args: [path.resolve(path.dirname(bin), js[1])], shell: false };
|
|
224
225
|
}
|
|
225
|
-
const exe = content.match(
|
|
226
|
+
const exe = content.match(/%~?dp0%?\\([^\s"*?]+\.exe)/i);
|
|
226
227
|
if (exe) return { file: path.resolve(path.dirname(bin), exe[1]), args: [], shell: false };
|
|
227
228
|
} catch {}
|
|
228
|
-
// A shim we can't read through still has to run under cmd.exe.
|
|
229
|
-
//
|
|
230
|
-
|
|
229
|
+
// A shim we can't read through still has to run under cmd.exe. Build that
|
|
230
|
+
// command line here (see _spawnArgv): `shell: true` would join the
|
|
231
|
+
// arguments unquoted, cutting a working dir or relay flag at a space.
|
|
232
|
+
return { file: process.env.ComSpec || 'cmd.exe', args: [], shell: false, cmdShim: bin };
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* argv + spawn options for `exec` running `rest`. A `cmdShim` goes through
|
|
237
|
+
* `cmd /d /s /c "<line>"` with every part quoted (`/s` strips only the
|
|
238
|
+
* outer pair), passed verbatim so Node adds no quoting of its own.
|
|
239
|
+
*/
|
|
240
|
+
_spawnArgv(exec, rest) {
|
|
241
|
+
if (!exec.cmdShim) return { argv: [...exec.args, ...rest], windowsVerbatimArguments: false };
|
|
242
|
+
const quote = (a) => `"${String(a).replace(/"/g, '""')}"`;
|
|
243
|
+
const line = [exec.cmdShim, ...rest].map(quote).join(' ');
|
|
244
|
+
return { argv: ['/d', '/s', '/c', `"${line}"`], windowsVerbatimArguments: true };
|
|
231
245
|
}
|
|
232
246
|
|
|
233
247
|
_findNodeBin() {
|
|
@@ -251,13 +265,7 @@ class CodexAdapter extends BaseAdapter {
|
|
|
251
265
|
* GB18030 only when UTF-8 fails and GB18030 reads the bytes cleanly.
|
|
252
266
|
*/
|
|
253
267
|
static _decodeOutput(buf, isWindows = IS_WINDOWS) {
|
|
254
|
-
|
|
255
|
-
if (!isWindows || !utf8.includes('\uFFFD')) return utf8;
|
|
256
|
-
try {
|
|
257
|
-
return new TextDecoder('gb18030', { fatal: true }).decode(buf);
|
|
258
|
-
} catch {
|
|
259
|
-
return utf8;
|
|
260
|
-
}
|
|
268
|
+
return decodeConsoleOutput(buf, isWindows);
|
|
261
269
|
}
|
|
262
270
|
|
|
263
271
|
_buildSystemContext(channelName) {
|
|
@@ -373,7 +381,11 @@ class CodexAdapter extends BaseAdapter {
|
|
|
373
381
|
async _handleViaSubprocess(content, msgChannel, attachments = []) {
|
|
374
382
|
// A missing cwd fails the spawn itself, and Node blames the shell for it
|
|
375
383
|
// ("spawn C:\Windows\system32\cmd.exe ENOENT"), which names nothing the
|
|
376
|
-
// user can fix.
|
|
384
|
+
// user can fix. A configured folder that was never made (or was cleaned
|
|
385
|
+
// up) is simply created; only one that cannot be is named instead.
|
|
386
|
+
if (this.workingDir && !CodexAdapter._dirExists(this.workingDir)) {
|
|
387
|
+
try { fs.mkdirSync(this.workingDir, { recursive: true }); } catch {}
|
|
388
|
+
}
|
|
377
389
|
if (this.workingDir && !CodexAdapter._dirExists(this.workingDir)) {
|
|
378
390
|
await this.sendError(msgChannel, `Working directory does not exist: ${this.workingDir}`);
|
|
379
391
|
return;
|
|
@@ -478,13 +490,15 @@ class CodexAdapter extends BaseAdapter {
|
|
|
478
490
|
if (this._stoppedBeforeStart(msgChannel)) return { stopped: true, responseText: '', exitCode: null };
|
|
479
491
|
return new Promise((resolve, reject) => {
|
|
480
492
|
const exec = this._resolveExec(cmd[0]);
|
|
481
|
-
const
|
|
493
|
+
const { argv, windowsVerbatimArguments } = this._spawnArgv(exec, cmd.slice(1));
|
|
494
|
+
const proc = spawn(exec.file, argv, {
|
|
482
495
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
483
496
|
env,
|
|
484
497
|
cwd: this.workingDir,
|
|
485
498
|
detached: !IS_WINDOWS,
|
|
486
499
|
windowsHide: true,
|
|
487
500
|
shell: exec.shell,
|
|
501
|
+
windowsVerbatimArguments,
|
|
488
502
|
});
|
|
489
503
|
this._channelProcesses[msgChannel] = proc;
|
|
490
504
|
|
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
|
@@ -360,7 +360,13 @@ async function cmdRuntimes(connector, flags) {
|
|
|
360
360
|
// Used by the daemon to report node runtimes to the workspace (Add-agent
|
|
361
361
|
// gallery). Emits ONLY JSON on stdout.
|
|
362
362
|
if (flags && flags.json) {
|
|
363
|
-
|
|
363
|
+
// --types a,b,c limits the run to those entries: the daemon splits
|
|
364
|
+
// detection over several of these so one slow CLI cannot hold up the rest.
|
|
365
|
+
const only = typeof flags.types === 'string'
|
|
366
|
+
? new Set(flags.types.split(',').map((s) => s.trim()).filter(Boolean))
|
|
367
|
+
: null;
|
|
368
|
+
const catalog = connector.registry.getCatalogSync().filter((e) => !only || only.has(e.name));
|
|
369
|
+
const runtimes = catalog.map((e) => {
|
|
364
370
|
let h;
|
|
365
371
|
try { h = connector.healthCheck(e.name); } catch { h = {}; }
|
|
366
372
|
// Credential contract, upward half: STATUS goes up, the secret stays on
|
|
@@ -1035,6 +1041,10 @@ async function cmdProbe(connector, flags, positional) {
|
|
|
1035
1041
|
if (result.ok) {
|
|
1036
1042
|
print(`OK (${result.method}, ${result.durationMs}ms)${result.reply ? ` — ${result.reply}` : ''}`);
|
|
1037
1043
|
if (result.code === 'static_only') print(result.message);
|
|
1044
|
+
} else if (result.ok === null) {
|
|
1045
|
+
// Nothing could be run and the sign-in could not be checked either.
|
|
1046
|
+
print(`UNVERIFIED ${result.message || ''}`.trim());
|
|
1047
|
+
process.exitCode = 1;
|
|
1038
1048
|
} else {
|
|
1039
1049
|
print(`FAILED [${result.code}] ${result.message || ''}`.trim());
|
|
1040
1050
|
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
|
|
@@ -24,6 +26,11 @@ const CLI_MODELS_MAX_AGE_MS = 3600 * 1000;
|
|
|
24
26
|
// may have failed for a passing reason (a slow start, an update mid-way). A
|
|
25
27
|
// little under the 10-minute sweep, so the next pass retries it.
|
|
26
28
|
const CLI_MODELS_RETRY_MS = 9 * 60 * 1000;
|
|
29
|
+
// Runtime detection runs as this many CLI children side by side, each checking
|
|
30
|
+
// its share of the catalog, and a child still running after the limit is
|
|
31
|
+
// stopped. A few rather than one per type: each child loads the whole core.
|
|
32
|
+
const RUNTIME_DETECT_GROUPS = 4;
|
|
33
|
+
const RUNTIME_DETECT_TIMEOUT_MS = 90 * 1000;
|
|
27
34
|
|
|
28
35
|
/**
|
|
29
36
|
* Mask an API key for display (same shape the workspace backend uses for
|
|
@@ -98,6 +105,27 @@ function _sentKey(args) {
|
|
|
98
105
|
return present && !args.useDeviceCredentials;
|
|
99
106
|
}
|
|
100
107
|
|
|
108
|
+
/**
|
|
109
|
+
* The reason `agn create --install` gave for a failed runtime install, or null.
|
|
110
|
+
* The create itself still succeeds (exit 0) — the agent exists either way.
|
|
111
|
+
*/
|
|
112
|
+
function installFailureOf(stdout) {
|
|
113
|
+
const m = /Warning: install failed: ([\s\S]*)$/.exec(String(stdout || ''));
|
|
114
|
+
return m ? m[1].trim() || 'unknown error' : null;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* One line that says why a crashed `agn probe` child died. Node's stack dump
|
|
119
|
+
* starts with "node:internal/modules/cjs/loader:1433 / throw err; / ^", which
|
|
120
|
+
* is all a 400-char head of it ever showed; the line that names the problem
|
|
121
|
+
* ("Error: Cannot find module '…'") comes after.
|
|
122
|
+
*/
|
|
123
|
+
function probeCrashSummary(stderr) {
|
|
124
|
+
const lines = String(stderr || '').split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
|
|
125
|
+
const telling = lines.find((l) => /^\w*Error\b|Cannot find module/.test(l));
|
|
126
|
+
return telling || lines.join('\n') || 'probe failed';
|
|
127
|
+
}
|
|
128
|
+
|
|
101
129
|
/**
|
|
102
130
|
* Whether a node heartbeat failure is the workspace saying the node is gone:
|
|
103
131
|
* a 404 carrying the backend's own message (routers/nodes.py), not any 404.
|
|
@@ -184,12 +212,23 @@ class Daemon {
|
|
|
184
212
|
let parsed = null;
|
|
185
213
|
try { parsed = JSON.parse(r.stdout.trim()); } catch {}
|
|
186
214
|
if (!parsed || typeof parsed !== 'object') {
|
|
215
|
+
// The probe process itself died before it could answer — a fault on
|
|
216
|
+
// this device's OpenAgents install, not in the agent.
|
|
187
217
|
parsed = {
|
|
188
218
|
type, ok: false, method: 'none', code: 'probe_error',
|
|
189
|
-
message: (r.stderr
|
|
190
|
-
guidance: [
|
|
219
|
+
message: redactDiagnostic(probeCrashSummary(r.stderr), 400),
|
|
220
|
+
guidance: [
|
|
221
|
+
'The OpenAgents test could not start on this device. Restart OpenAgents and test again; if it keeps failing, reinstall OpenAgents.',
|
|
222
|
+
],
|
|
223
|
+
at: new Date().toISOString(),
|
|
191
224
|
};
|
|
192
225
|
}
|
|
226
|
+
// Still not installed after a failed install: keep the reason the
|
|
227
|
+
// install gave, which says far more than "Not installed".
|
|
228
|
+
const prev = this._probes[name];
|
|
229
|
+
if (parsed.code === 'not_installed' && prev && prev.code === 'install_failed') {
|
|
230
|
+
parsed = { ...prev, at: parsed.at || new Date().toISOString() };
|
|
231
|
+
}
|
|
193
232
|
parsed.agent = name;
|
|
194
233
|
this._probes[name] = parsed;
|
|
195
234
|
this._saveProbes();
|
|
@@ -199,6 +238,25 @@ class Daemon {
|
|
|
199
238
|
}
|
|
200
239
|
}
|
|
201
240
|
|
|
241
|
+
/** Report a runtime install that failed while creating `name`, as its probe result. */
|
|
242
|
+
_recordInstallFailure(name, type, error) {
|
|
243
|
+
let install = null;
|
|
244
|
+
try {
|
|
245
|
+
const entry = this.registry && this.registry.getEntry(type);
|
|
246
|
+
install = entry ? installCommandFor(entry) : null;
|
|
247
|
+
} catch {}
|
|
248
|
+
this._probes[name] = {
|
|
249
|
+
type, agent: name, ok: false, method: 'install', code: 'install_failed',
|
|
250
|
+
message: redactDiagnostic(error, 400),
|
|
251
|
+
guidance: [
|
|
252
|
+
'Installing the agent on this device failed. Install it from the launcher\'s Install page to see the full log.',
|
|
253
|
+
...(install ? [`Or install manually: ${install}`] : []),
|
|
254
|
+
],
|
|
255
|
+
at: new Date().toISOString(),
|
|
256
|
+
};
|
|
257
|
+
this._saveProbes();
|
|
258
|
+
}
|
|
259
|
+
|
|
202
260
|
/**
|
|
203
261
|
* Periodic sweep: probe each configured agent whose last result is missing
|
|
204
262
|
* or stale. Sequential on purpose — probes cost a (tiny) model call each;
|
|
@@ -671,16 +729,50 @@ class Daemon {
|
|
|
671
729
|
}
|
|
672
730
|
}
|
|
673
731
|
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
732
|
+
/**
|
|
733
|
+
* Re-detect the installed/logged-in runtimes. A call made while one is
|
|
734
|
+
* already running joins it, so start-up, the periodic refresh and a
|
|
735
|
+
* workspace's Re-detect never run side by side.
|
|
736
|
+
*/
|
|
737
|
+
_refreshRuntimes() {
|
|
738
|
+
if (!this._runtimesInFlight) {
|
|
739
|
+
this._runtimesInFlight = this._detectRuntimes()
|
|
740
|
+
.catch(() => {})
|
|
741
|
+
.finally(() => { this._runtimesInFlight = null; });
|
|
742
|
+
}
|
|
743
|
+
return this._runtimesInFlight;
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
/**
|
|
747
|
+
* Detection checks each type with blocking CLI calls (--version, a login
|
|
748
|
+
* check), one after another. Run over the whole catalog in one child, a
|
|
749
|
+
* single CLI that hung held every result back, and the workspace sat on
|
|
750
|
+
* "Detecting…". The catalog is split over a few children run side by side,
|
|
751
|
+
* each with a time limit; a group that runs out keeps its last results.
|
|
752
|
+
*/
|
|
753
|
+
async _detectRuntimes() {
|
|
754
|
+
let types = [];
|
|
755
|
+
try { types = this.registry.getCatalogSync().map((e) => e.name); } catch {}
|
|
756
|
+
const groups = types.length
|
|
757
|
+
? Array.from({ length: Math.min(RUNTIME_DETECT_GROUPS, types.length) }, (_, i) =>
|
|
758
|
+
types.filter((_, j) => j % RUNTIME_DETECT_GROUPS === i))
|
|
759
|
+
: [null];
|
|
760
|
+
const found = new Map();
|
|
761
|
+
await Promise.all(groups.map(async (group) => {
|
|
762
|
+
const args = group ? ['runtimes', '--json', '--types', group.join(',')] : ['runtimes', '--json'];
|
|
763
|
+
try {
|
|
764
|
+
const r = await this._runAgn(args, { timeoutMs: RUNTIME_DETECT_TIMEOUT_MS });
|
|
765
|
+
if (r.code !== 0 || !r.stdout) return;
|
|
678
766
|
const parsed = JSON.parse(r.stdout.trim());
|
|
679
|
-
if (Array.isArray(parsed))
|
|
767
|
+
if (Array.isArray(parsed)) for (const rt of parsed) if (rt && rt.type) found.set(rt.type, rt);
|
|
768
|
+
} catch {
|
|
769
|
+
// this group keeps its previous snapshot
|
|
680
770
|
}
|
|
681
|
-
}
|
|
682
|
-
|
|
683
|
-
|
|
771
|
+
}));
|
|
772
|
+
if (!found.size) return;
|
|
773
|
+
const previous = new Map((this._runtimes || []).map((rt) => [rt.type, rt]));
|
|
774
|
+
const order = types.length ? types : [...found.keys()];
|
|
775
|
+
this._runtimes = order.map((type) => found.get(type) || previous.get(type)).filter(Boolean);
|
|
684
776
|
}
|
|
685
777
|
|
|
686
778
|
/**
|
|
@@ -745,6 +837,7 @@ async _runNodeCommand(n, cmd) {
|
|
|
745
837
|
try { fs.mkdirSync(workingDir, { recursive: true }); } catch {}
|
|
746
838
|
const r1 = await this._runAgn(['create', name, '--type', type, '--install', '--path', workingDir]);
|
|
747
839
|
if (r1.code !== 0) throw new Error(r1.stderr || r1.stdout || 'create failed');
|
|
840
|
+
const installError = installFailureOf(r1.stdout);
|
|
748
841
|
// Optional credentials for API-key agents (generic → provider mapping
|
|
749
842
|
// happens in env resolution). `useDeviceCredentials` means the device
|
|
750
843
|
// already holds them — nothing to write.
|
|
@@ -764,10 +857,18 @@ async _runNodeCommand(n, cmd) {
|
|
|
764
857
|
if (r2.code !== 0) throw new Error(r2.stderr || r2.stdout || 'connect failed');
|
|
765
858
|
ok = true;
|
|
766
859
|
message = `Agent '${name}' created`;
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
860
|
+
if (installError) {
|
|
861
|
+
// The agent exists and is connected, but its runtime did not install.
|
|
862
|
+
// Say why on the card: a probe now could only answer "Not installed".
|
|
863
|
+
message = `Agent '${name}' created, but installing ${type} failed: ${installError}`;
|
|
864
|
+
this._recordInstallFailure(name, type, installError);
|
|
865
|
+
this._nodeHeartbeat();
|
|
866
|
+
} else {
|
|
867
|
+
// First-connect smoke test, in the background (a probe can take its
|
|
868
|
+
// full timeout — never hold the create result hostage). The outcome
|
|
869
|
+
// reaches the workspace via the heartbeat's agents[].probe.
|
|
870
|
+
this._probeAgent(name).then(() => this._nodeHeartbeat()).catch(() => {});
|
|
871
|
+
}
|
|
771
872
|
this._askCliModels(name);
|
|
772
873
|
} else if (action === 'start_agent' || action === 'stop_agent') {
|
|
773
874
|
// In-process, not via `agn start|stop`: that spawned a whole CLI just to
|
|
@@ -876,8 +977,11 @@ async _runNodeCommand(n, cmd) {
|
|
|
876
977
|
}
|
|
877
978
|
}
|
|
878
979
|
|
|
879
|
-
/**
|
|
880
|
-
|
|
980
|
+
/**
|
|
981
|
+
* Run this launcher's own CLI as a child process, capturing output. With
|
|
982
|
+
* `timeoutMs`, a child still running then is killed and reported as failed.
|
|
983
|
+
*/
|
|
984
|
+
_runAgn(cliArgs, { timeoutMs } = {}) {
|
|
881
985
|
return new Promise((resolve) => {
|
|
882
986
|
let bin;
|
|
883
987
|
try {
|
|
@@ -890,6 +994,9 @@ async _runNodeCommand(n, cmd) {
|
|
|
890
994
|
// Run from home so a created agent's default working dir is sensible
|
|
891
995
|
// (not the ~/.openagents config dir).
|
|
892
996
|
cwd: os.homedir(),
|
|
997
|
+
// A timed detection owns its process group, so its CLI descendants
|
|
998
|
+
// can be stopped too without signalling the daemon itself.
|
|
999
|
+
detached: !!timeoutMs && !IS_WINDOWS,
|
|
893
1000
|
// The daemon has no console of its own (it is spawned DETACHED), so a
|
|
894
1001
|
// child without this gets a fresh console window — the blank black box
|
|
895
1002
|
// that used to appear every time _refreshRuntimes() ran.
|
|
@@ -897,10 +1004,32 @@ async _runNodeCommand(n, cmd) {
|
|
|
897
1004
|
});
|
|
898
1005
|
let stdout = '';
|
|
899
1006
|
let stderr = '';
|
|
1007
|
+
let settled = false;
|
|
1008
|
+
const finish = (result) => {
|
|
1009
|
+
if (settled) return;
|
|
1010
|
+
settled = true;
|
|
1011
|
+
clearTimeout(timer);
|
|
1012
|
+
resolve(result);
|
|
1013
|
+
};
|
|
1014
|
+
const timer = timeoutMs ? setTimeout(() => {
|
|
1015
|
+
if (IS_WINDOWS && child.pid) {
|
|
1016
|
+
// Killing only node.exe leaves the CLI (and its shell) running.
|
|
1017
|
+
const killer = spawn('taskkill', ['/T', '/F', '/PID', String(child.pid)], {
|
|
1018
|
+
windowsHide: true, stdio: 'ignore', timeout: 5000,
|
|
1019
|
+
});
|
|
1020
|
+
const fallback = () => { try { child.kill('SIGKILL'); } catch {} };
|
|
1021
|
+
killer.on('error', fallback);
|
|
1022
|
+
killer.on('close', (code) => { if (code !== 0) fallback(); });
|
|
1023
|
+
} else {
|
|
1024
|
+
try { process.kill(-child.pid, 'SIGKILL'); }
|
|
1025
|
+
catch { try { child.kill('SIGKILL'); } catch {} }
|
|
1026
|
+
}
|
|
1027
|
+
finish({ code: 1, stdout, stderr: `${stderr}timed out after ${timeoutMs}ms`, timedOut: true });
|
|
1028
|
+
}, timeoutMs) : null;
|
|
900
1029
|
child.stdout.on('data', (d) => { stdout += d.toString(); });
|
|
901
1030
|
child.stderr.on('data', (d) => { stderr += d.toString(); });
|
|
902
|
-
child.on('error', (e) =>
|
|
903
|
-
child.on('close', (code) =>
|
|
1031
|
+
child.on('error', (e) => finish({ code: 1, stdout, stderr: stderr || e.message }));
|
|
1032
|
+
child.on('close', (code) => finish({ code, stdout, stderr }));
|
|
904
1033
|
});
|
|
905
1034
|
}
|
|
906
1035
|
|
|
@@ -988,8 +1117,9 @@ async _runNodeCommand(n, cmd) {
|
|
|
988
1117
|
);
|
|
989
1118
|
|
|
990
1119
|
// Detect installed/logged-in agent runtimes for the Add-agent gallery. Runs
|
|
991
|
-
// in a child process (off the event loop), refreshed periodically.
|
|
992
|
-
|
|
1120
|
+
// in a child process (off the event loop), refreshed periodically. The
|
|
1121
|
+
// first result goes up at once rather than on the next 10s heartbeat.
|
|
1122
|
+
this._refreshRuntimes().then(() => this._nodeHeartbeat()).catch(() => {});
|
|
993
1123
|
this._runtimesInterval = setInterval(() => this._refreshRuntimes(), 120000);
|
|
994
1124
|
|
|
995
1125
|
// Smoke-test configured agent types periodically (each probe spends one
|
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,44 +405,72 @@ 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
|
+
// Hoisted above the CLI tier: a failing CLI probe consults it too (below),
|
|
419
|
+
// and `skip_cli_with_key` hands keyed agents straight to it.
|
|
420
|
+
// `probe.api_test: false` opts out for an agent whose key is not a model
|
|
421
|
+
// API key (Cursor's is for Cursor's own service): an OpenAI-style call with
|
|
422
|
+
// it proves nothing either way.
|
|
423
|
+
const apiTestable = !(entry.probe && entry.probe.api_test === false);
|
|
424
|
+
const hasApiKey = apiTestable && !!(agentEnv.LLM_API_KEY || agentEnv.OPENAI_API_KEY || agentEnv.ANTHROPIC_API_KEY
|
|
425
|
+
|| agentEnv.ANTHROPIC_AUTH_TOKEN || agentEnv.KIMI_API_KEY || agentEnv.MOONSHOT_API_KEY);
|
|
426
|
+
|
|
427
|
+
// `probe.skip_cli_with_key`: the adapter points the CLI at a key's endpoint
|
|
428
|
+
// with launch flags (Codex's `-c model_providers…`) that a bare probe run
|
|
429
|
+
// does not carry, so with a key the CLI would test the wrong endpoint.
|
|
430
|
+
const cliProbeApplies = !(entry.probe && entry.probe.skip_cli_with_key && hasApiKey);
|
|
431
|
+
const probeArgs = cliProbeApplies && entry.probe && Array.isArray(entry.probe.args) ? entry.probe.args : null;
|
|
432
|
+
const altCheck = entry.check_ready && entry.check_ready.alt_check;
|
|
433
|
+
const hasLiveCli = !!((probeArgs && health.binary) || altCheck);
|
|
434
|
+
|
|
324
435
|
// Definitively unconfigured (auth_status 'unknown' still gets a live try:
|
|
325
436
|
// the real run is the final authority for unverifiable logins).
|
|
437
|
+
let staticVerdict = null;
|
|
326
438
|
if (!health.ready && health.auth_status !== 'unknown') {
|
|
327
439
|
let lines = [];
|
|
328
440
|
try { lines = formatAuthGuidance(entry, health).lines; } catch {}
|
|
329
|
-
|
|
441
|
+
staticVerdict = {
|
|
330
442
|
ok: false, method: 'none', code: CODE.NOT_READY,
|
|
331
443
|
message: health.message || 'Not configured',
|
|
332
444
|
guidance: lines.length ? lines : buildGuidance(CODE.NOT_LOGGED_IN, entry, agentEnv),
|
|
333
|
-
}
|
|
445
|
+
};
|
|
446
|
+
// A sign-in kept where the static checks cannot see it (a keychain, a
|
|
447
|
+
// relay set up in the CLI's own settings) answered fine and was still
|
|
448
|
+
// reported "Not logged in". Where the agent declares a live check, that
|
|
449
|
+
// run decides; the static verdict only stands in when the run explains
|
|
450
|
+
// nothing.
|
|
451
|
+
if (!hasLiveCli) return done(staticVerdict);
|
|
334
452
|
}
|
|
335
453
|
|
|
336
454
|
const timeoutMs = opts.timeoutMs
|
|
337
455
|
|| (entry.probe && entry.probe.timeout_s ? entry.probe.timeout_s * 1000 : DEFAULT_TIMEOUT_MS);
|
|
338
456
|
const env = stripForCliLogin(type, { ...getEnhancedEnv(), ...agentEnv }, connector.registry, opts.agentEnv);
|
|
339
457
|
|
|
340
|
-
// Hoisted above the CLI tier: a failing CLI probe consults it too (below).
|
|
341
|
-
const hasApiKey = !!(agentEnv.LLM_API_KEY || agentEnv.OPENAI_API_KEY || agentEnv.ANTHROPIC_API_KEY
|
|
342
|
-
|| agentEnv.ANTHROPIC_AUTH_TOKEN || agentEnv.KIMI_API_KEY || agentEnv.MOONSHOT_API_KEY);
|
|
343
|
-
|
|
344
458
|
// ── Live tier 1: the agent's own CLI, when the registry declares how ──
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
if ((probeArgs && health.binary) || altCheck) {
|
|
459
|
+
if (hasLiveCli) {
|
|
460
|
+
const shell = probeArgs && health.binary ? shouldUseShellForBinary(health.binary) : true;
|
|
348
461
|
const res = probeArgs && health.binary
|
|
349
462
|
// Node refuses to spawn .cmd/.bat without a shell (EINVAL since the
|
|
350
463
|
// CVE-2024-27980 hardening), which made every Windows CLI probe of an
|
|
351
464
|
// 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
|
-
})
|
|
465
|
+
? await runCommand(shellQuoted(health.binary, shell), probeArgs, { env, timeoutMs, shell })
|
|
355
466
|
: await runCommand(altCheck, [], { env, timeoutMs, shell: true });
|
|
356
|
-
const output = `${res.stdout}\n${res.stderr}
|
|
357
|
-
|
|
467
|
+
const output = withoutNoise(`${res.stdout}\n${res.stderr}`);
|
|
468
|
+
const reply = withoutNoise(res.stdout).trim();
|
|
469
|
+
if (!res.timedOut && !res.spawnError && res.code === 0 && reply) {
|
|
358
470
|
return done({
|
|
359
471
|
ok: true, method: 'cli', code: CODE.OK,
|
|
360
472
|
message: 'Responded',
|
|
361
|
-
reply: tail(
|
|
473
|
+
reply: tail(reply, REPLY_CAP),
|
|
362
474
|
});
|
|
363
475
|
}
|
|
364
476
|
let code = res.code === 0 && !res.timedOut && !res.spawnError
|
|
@@ -385,10 +497,11 @@ async function probeAgentType(connector, type, opts = {}) {
|
|
|
385
497
|
const direct = await directApiVerdict(agentEnv, entry);
|
|
386
498
|
if (direct) return done(direct);
|
|
387
499
|
}
|
|
500
|
+
if (unexplained && staticVerdict) return done(staticVerdict);
|
|
388
501
|
|
|
389
502
|
return done({
|
|
390
503
|
ok: false, method: 'cli', code,
|
|
391
|
-
message:
|
|
504
|
+
message: failureMessage(res, code, timeoutMs),
|
|
392
505
|
guidance: buildGuidance(code, entry, agentEnv, { timeoutMs }),
|
|
393
506
|
});
|
|
394
507
|
}
|
|
@@ -414,9 +527,13 @@ async function probeAgentType(connector, type, opts = {}) {
|
|
|
414
527
|
}
|
|
415
528
|
|
|
416
529
|
// ── No safe live probe — report the static result honestly rather than
|
|
417
|
-
// inventing a CLI invocation that could misfire.
|
|
530
|
+
// inventing a CLI invocation that could misfire. Reaching here not ready
|
|
531
|
+
// means the sign-in could not be checked (auth_status 'unknown'): that is
|
|
532
|
+
// ok: null, not a failure — counted as one, every signed-in Codex or Cursor
|
|
533
|
+
// whose status command was slow read as "Not configured". ──
|
|
418
534
|
return done({
|
|
419
|
-
ok: health.ready === true, method: 'none', code: CODE.STATIC_ONLY,
|
|
535
|
+
ok: health.ready === true ? true : null, method: 'none', code: CODE.STATIC_ONLY,
|
|
536
|
+
auth_status: health.auth_status || null,
|
|
420
537
|
message: health.ready
|
|
421
538
|
? 'Static checks passed (no live probe is defined for this agent type)'
|
|
422
539
|
: (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 };
|