@openagents-org/agent-launcher 0.2.218 → 0.2.220

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/node_modules/ws/LICENSE +20 -0
  2. package/node_modules/ws/README.md +548 -0
  3. package/node_modules/ws/browser.js +8 -0
  4. package/node_modules/ws/index.js +22 -0
  5. package/node_modules/ws/lib/buffer-util.js +131 -0
  6. package/node_modules/ws/lib/constants.js +19 -0
  7. package/node_modules/ws/lib/event-target.js +292 -0
  8. package/node_modules/ws/lib/extension.js +203 -0
  9. package/node_modules/ws/lib/limiter.js +55 -0
  10. package/node_modules/ws/lib/permessage-deflate.js +528 -0
  11. package/node_modules/ws/lib/receiver.js +706 -0
  12. package/node_modules/ws/lib/sender.js +602 -0
  13. package/node_modules/ws/lib/stream.js +161 -0
  14. package/node_modules/ws/lib/subprotocol.js +62 -0
  15. package/node_modules/ws/lib/validation.js +152 -0
  16. package/node_modules/ws/lib/websocket-server.js +554 -0
  17. package/node_modules/ws/lib/websocket.js +1393 -0
  18. package/node_modules/ws/package.json +70 -0
  19. package/node_modules/ws/wrapper.mjs +21 -0
  20. package/package.json +5 -2
  21. package/registry.json +12 -2
  22. package/src/adapters/claude.js +13 -9
  23. package/src/adapters/codearts.js +1 -0
  24. package/src/adapters/codex.js +49 -9
  25. package/src/adapters/deepseek-runtime.js +6 -2
  26. package/src/adapters/kimi-stream.js +78 -5
  27. package/src/adapters/kimi.js +114 -24
  28. package/src/adapters/mimo-code.js +1 -0
  29. package/src/adapters/openclaw.js +24 -19
  30. package/src/adapters/opencode.js +55 -2
  31. package/src/adapters/utils.js +11 -0
  32. package/src/daemon.js +4 -2
  33. package/src/installer.js +206 -36
  34. package/src/native-build.js +132 -0
  35. package/src/probe.js +88 -7
  36. package/src/utils.js +123 -12
package/src/installer.js CHANGED
@@ -27,6 +27,7 @@ const { checkInstallPrereqs, missingPrereqError } = require('./install-preflight
27
27
  const { detectShadowedNodeShims, shadowedNodeWarning } = require('./node-shims');
28
28
  const { fixSpawnHelpers } = require('./node-pty-perms');
29
29
  const { isPostinstallStub } = require('./postinstall-stub');
30
+ const { nativeBuildFor } = require('./native-build');
30
31
  const { classifyClineAuth } = require('./adapters/cline-stream');
31
32
 
32
33
  /**
@@ -71,8 +72,44 @@ const CREDS_CLASSIFIERS = {
71
72
  cline_providers(creds) {
72
73
  return classifyClineAuth(creds, {}).state;
73
74
  },
75
+ // ~/.copilot/config.json lists the GitHub accounts `copilot` /login signed
76
+ // in. An empty list (or no file) is not "signed out": a GH_TOKEN or a gh
77
+ // sign-in works without it, so that stays for the run to decide.
78
+ copilot_logged_in_users(creds) {
79
+ const users = creds && creds.loggedInUsers;
80
+ return Array.isArray(users) && users.length > 0 ? 'ready' : 'unknown';
81
+ },
74
82
  };
75
83
 
84
+ /**
85
+ * JSON that may carry `//` and `/* *\/` comments (JSONC). Copilot writes its
86
+ * config.json with a two-line `//` header, so a strict parse read a signed-in
87
+ * user's file as unparseable. Comments are removed outside strings only.
88
+ */
89
+ function parseJsonLoose(raw) {
90
+ const text = String(raw);
91
+ try { return JSON.parse(text); } catch { /* fall through to JSONC */ }
92
+ let out = '';
93
+ for (let i = 0; i < text.length; i++) {
94
+ const c = text[i];
95
+ if (c === '"') {
96
+ let j = i + 1;
97
+ while (j < text.length && text[j] !== '"') j += text[j] === '\\' ? 2 : 1;
98
+ out += text.slice(i, j + 1);
99
+ i = j;
100
+ } else if (c === '/' && text[i + 1] === '/') {
101
+ while (i < text.length && text[i] !== '\n') i++;
102
+ out += '\n';
103
+ } else if (c === '/' && text[i + 1] === '*') {
104
+ const end = text.indexOf('*/', i + 2);
105
+ i = end === -1 ? text.length : end + 1;
106
+ } else {
107
+ out += c;
108
+ }
109
+ }
110
+ return JSON.parse(out);
111
+ }
112
+
76
113
  /** The named classifier's verdict, or null when the entry names none. */
77
114
  function classifyCreds(checkReady, creds) {
78
115
  const classify = checkReady && CREDS_CLASSIFIERS[checkReady.creds_classifier];
@@ -1080,7 +1117,7 @@ class Installer {
1080
1117
  if (fs.existsSync(credsPath)) {
1081
1118
  const stat = fs.statSync(credsPath);
1082
1119
  if (stat.isDirectory()) return fs.readdirSync(credsPath).length > 0;
1083
- const creds = JSON.parse(fs.readFileSync(credsPath, 'utf-8'));
1120
+ const creds = parseJsonLoose(fs.readFileSync(credsPath, 'utf-8'));
1084
1121
  const verdict = classifyCreds(checkReady, creds);
1085
1122
  if (verdict) return verdict === 'ready';
1086
1123
  if (checkReady.creds_key) return !!creds[checkReady.creds_key];
@@ -1097,6 +1134,18 @@ class Installer {
1097
1134
  }
1098
1135
  }
1099
1136
 
1137
+ // An item named by service AND account. A separate field from
1138
+ // keychain_service so an older core, which would match on the service
1139
+ // alone, skips it rather than reading someone else's item as a sign-in.
1140
+ // agy keeps its Google sign-in as service `gemini`, account `antigravity`:
1141
+ // the same pair it stores on Windows as the target `gemini:antigravity`.
1142
+ const item = checkReady.keychain_item;
1143
+ if (item && item.service && item.account && process.platform === 'darwin') {
1144
+ if (this._checkMacKeychain(item.service, item.account)) {
1145
+ return true;
1146
+ }
1147
+ }
1148
+
1100
1149
  if (checkReady.credential_target && process.platform === 'win32') {
1101
1150
  if (this._checkWindowsCredential(checkReady.credential_target)) {
1102
1151
  return true;
@@ -1201,7 +1250,7 @@ class Installer {
1201
1250
  if (checkReady.creds_classifier) {
1202
1251
  const raw = fs.readFileSync(p, 'utf-8');
1203
1252
  let parsed;
1204
- try { parsed = JSON.parse(raw); } catch { parsed = { __parse_error: true }; }
1253
+ try { parsed = parseJsonLoose(raw); } catch { parsed = { __parse_error: true }; }
1205
1254
  const verdict = classifyCreds(checkReady, parsed);
1206
1255
  if (verdict) return verdict === 'ready' ? 'present' : verdict === 'unknown' ? 'unknown' : 'absent';
1207
1256
  }
@@ -1285,11 +1334,12 @@ class Installer {
1285
1334
  *
1286
1335
  * Cached like _checkWindowsCredential, and never waited on in Electron main.
1287
1336
  */
1288
- _checkMacKeychain(service) {
1337
+ _checkMacKeychain(service, account = null) {
1289
1338
  if (!service) return false;
1290
- const cached = keychainItemCache.get(service);
1339
+ const cacheKey = account ? `${service}\u0000${account}` : service;
1340
+ const cached = keychainItemCache.get(cacheKey);
1291
1341
  const fresh = cached && (Date.now() - cached.ts) < STATUS_CACHE_TTL_MS;
1292
- const args = ['find-generic-password', '-s', service];
1342
+ const args = ['find-generic-password', '-s', service, ...(account ? ['-a', account] : [])];
1293
1343
  if (!fresh && canBlock()) {
1294
1344
  let found = false;
1295
1345
  try {
@@ -1299,20 +1349,20 @@ class Installer {
1299
1349
  });
1300
1350
  found = !run.error && run.status === 0;
1301
1351
  } catch {}
1302
- keychainItemCache.set(service, { found, ts: Date.now() });
1303
- } else if (!fresh && !keychainRefreshing.has(service)) {
1352
+ keychainItemCache.set(cacheKey, { found, ts: Date.now() });
1353
+ } else if (!fresh && !keychainRefreshing.has(cacheKey)) {
1304
1354
  // Answer from the last lookup now; the refresh lands for the next call.
1305
- keychainRefreshing.add(service);
1355
+ keychainRefreshing.add(cacheKey);
1306
1356
  try {
1307
1357
  execFile('security', args, { timeout: 5000 }, (err) => {
1308
- keychainRefreshing.delete(service);
1309
- keychainItemCache.set(service, { found: !err, ts: Date.now() });
1358
+ keychainRefreshing.delete(cacheKey);
1359
+ keychainItemCache.set(cacheKey, { found: !err, ts: Date.now() });
1310
1360
  });
1311
1361
  } catch {
1312
- keychainRefreshing.delete(service);
1362
+ keychainRefreshing.delete(cacheKey);
1313
1363
  }
1314
1364
  }
1315
- return !!(keychainItemCache.get(service) || {}).found;
1365
+ return !!(keychainItemCache.get(cacheKey) || {}).found;
1316
1366
  }
1317
1367
 
1318
1368
  /**
@@ -1806,18 +1856,14 @@ class Installer {
1806
1856
  if (onData) onData(`\nDone! ${agentType} is now installed.\n`);
1807
1857
  resolve({ success: true, command: displayCmd });
1808
1858
  };
1809
- // An npm package whose postinstall was skipped exits 0 with a
1810
- // placeholder where its CLI should be. See _findPostinstallStub.
1811
- const stub = this._findPostinstallStub(agentType);
1812
- if (stub) {
1813
- this._repairPostinstallStub(agentType, stub, onData).then((problem) => {
1814
- if (!problem) return markDone();
1815
- if (onData) onData(`\n${problem}\n`);
1816
- reject(new Error(problem));
1817
- }, reject);
1818
- return;
1819
- }
1820
- markDone();
1859
+ // An npm install can exit 0 with no runnable CLI: the native build
1860
+ // left out, or the postinstall skipped. See finishNpmInstall (null
1861
+ // for an agent that is not an npm install).
1862
+ this.finishNpmInstall(agentType, onData).then((problem) => {
1863
+ if (!problem) return markDone();
1864
+ if (onData) onData(`\n${problem}\n`);
1865
+ reject(new Error(problem));
1866
+ }, reject);
1821
1867
  } else {
1822
1868
  // A partial install can leave a placeholder stub at
1823
1869
  // bin/<binary>.exe and npm-generated cmd-shims under
@@ -1913,7 +1959,29 @@ class Installer {
1913
1959
  * every other package and every other install.
1914
1960
  */
1915
1961
  _rebuildWithScripts(pkgName, prefix) {
1916
- const args = ['rebuild', pkgName, '--prefix', prefix, '--ignore-scripts=false', '--foreground-scripts'];
1962
+ return this._runNpmIn(prefix, ['rebuild', pkgName, '--prefix', prefix, '--ignore-scripts=false', '--foreground-scripts']);
1963
+ }
1964
+
1965
+ /**
1966
+ * Install the per-platform package that holds a wrapper's native build, on
1967
+ * its own (see native-build.js). `--include=optional` outranks an
1968
+ * `omit=optional` in an npmrc for this one command; `--no-save` keeps it out
1969
+ * of the runtime's package.json, so the next update resolves it afresh with
1970
+ * the wrapper's new version instead of pinning this one. From the registry
1971
+ * the install itself used (installRegistry): where the official one is out
1972
+ * of reach, the build's download is the one most likely to have failed.
1973
+ */
1974
+ _installNativeBuildPackage(build, prefix) {
1975
+ const registry = installRegistry();
1976
+ return this._runNpmIn(prefix, [
1977
+ 'install', `${build.name}@${build.spec}`, '--prefix', prefix,
1978
+ '--no-save', '--include=optional', '--foreground-scripts',
1979
+ ...(registry ? ['--registry', registry] : []),
1980
+ ]);
1981
+ }
1982
+
1983
+ /** Run npm with an argv (never a shell string) in `prefix`; resolves its output, rejects with it. */
1984
+ _runNpmIn(prefix, args) {
1917
1985
  const env = this._buildShellEnv();
1918
1986
  const run = this._execFileForTest || execFile;
1919
1987
  const runNpm = (file, argv, extra = {}) => new Promise((resolve, reject) => {
@@ -1936,9 +2004,10 @@ class Installer {
1936
2004
  const win = process.platform === 'win32';
1937
2005
  const npm = whichBinary('npm') || (win ? 'npm.cmd' : 'npm');
1938
2006
  // npm.cmd is a batch file and only runs through cmd.exe. With shell:true
1939
- // Node joins the argv with spaces, so quote the ones that contain any.
2007
+ // Node joins the argv with spaces, so quote the ones that contain any —
2008
+ // or a character cmd.exe would act on (a `^1.2.3` version range).
1940
2009
  if (win && /\.(cmd|bat)$/i.test(npm)) {
1941
- const q = (a) => (/\s/.test(a) ? `"${a}"` : a);
2010
+ const q = (a) => (/[\s^&|<>()]/.test(a) ? `"${a}"` : a);
1942
2011
  return runNpm(q(npm), args.map(q), { shell: true });
1943
2012
  }
1944
2013
  return runNpm(npm, args);
@@ -1961,8 +2030,97 @@ class Installer {
1961
2030
  * package already taken back out.
1962
2031
  */
1963
2032
  async finishNpmInstall(agentType, onData) {
2033
+ // The native build first: with it missing, claude-code's and opencode-ai's
2034
+ // postinstall ran and had nothing to copy, and re-running the script (the
2035
+ // placeholder repair below) cannot help until it is there.
2036
+ const missing = this._findMissingNativeBuild(agentType);
2037
+ let nativeRestored = false;
2038
+ if (missing) {
2039
+ const problem = await this._restoreNativeBuild(agentType, missing, onData);
2040
+ if (problem) return problem;
2041
+ nativeRestored = true;
2042
+ }
1964
2043
  const stub = this._findPostinstallStub(agentType);
1965
- return stub ? this._repairPostinstallStub(agentType, stub, onData) : null;
2044
+ return stub ? this._repairPostinstallStub(agentType, stub, onData, { nativeRestored }) : null;
2045
+ }
2046
+
2047
+ /**
2048
+ * The managed copy of an agent's npm package — `{ pkgName, pkgDir, prefix }`
2049
+ * — or null when it is not an npm install or is not there.
2050
+ */
2051
+ _managedNpmPackage(agentType) {
2052
+ const entry = this.registry.getEntry(agentType);
2053
+ const pkgName = this._npmPackageFor(entry && entry.install);
2054
+ if (!pkgName) return null;
2055
+ const prefixes = [getRuntimePrefix(agentType), path.join(os.homedir(), '.openagents', 'nodejs')];
2056
+ for (const prefix of prefixes) {
2057
+ const pkgDir = path.join(prefix, 'node_modules', ...pkgName.split('/'));
2058
+ if (fs.existsSync(path.join(pkgDir, 'package.json'))) return { pkgName, pkgDir, prefix };
2059
+ }
2060
+ return null;
2061
+ }
2062
+
2063
+ /**
2064
+ * The managed copy of an agent whose per-platform native build npm left out
2065
+ * (see native-build.js), or null — also when the package has none to check.
2066
+ *
2067
+ * @returns {{ pkgName: string, pkgDir: string, prefix: string, build: object } | null}
2068
+ */
2069
+ _findMissingNativeBuild(agentType) {
2070
+ const managed = this._managedNpmPackage(agentType);
2071
+ if (!managed) return null;
2072
+ const build = nativeBuildFor(managed.pkgDir);
2073
+ if (!build || build.installed) return null;
2074
+ // opencode-ai's postinstall fetches the build itself when npm left it out,
2075
+ // copies the binary over its placeholder and deletes the package again
2076
+ // (see COPIED_INTO_BIN). Installing it once more was redundant, and when
2077
+ // that failed the working install was removed. Read off disk, not run:
2078
+ // on Windows the placeholder is shell text named .exe.
2079
+ if (build.copiedIntoBin) {
2080
+ const entry = this.registry.getEntry(agentType);
2081
+ const binary = (entry && entry.install && entry.install.binary) || agentType;
2082
+ const bin = resolveManagedNpmPackageBin(agentType, managed.pkgName, binary);
2083
+ if (bin && !isPostinstallStub(bin)) return null;
2084
+ }
2085
+ return { ...managed, build };
2086
+ }
2087
+
2088
+ /**
2089
+ * Install the native build npm left out. Resolves null once it is in place,
2090
+ * otherwise the message to show — with the package taken back out, as for a
2091
+ * placeholder that cannot be repaired: left in place it reads as installed.
2092
+ */
2093
+ async _restoreNativeBuild(agentType, missing, onData) {
2094
+ const entry = this.registry.getEntry(agentType);
2095
+ const label = (entry && entry.label) || agentType;
2096
+ const { build, prefix, pkgDir } = missing;
2097
+ if (onData) {
2098
+ onData(`\nnpm did not install ${build.name}, the package that holds ${label}'s native build for `
2099
+ + `${build.target} (an optional dependency of ${build.pkgName}). Installing it on its own now.\n`);
2100
+ }
2101
+ let output = '';
2102
+ try {
2103
+ output = await this._installNativeBuildPackage(build, prefix);
2104
+ } catch (e) {
2105
+ output = (e && e.message) || '';
2106
+ }
2107
+ const now = nativeBuildFor(pkgDir);
2108
+ if (now && now.installed) {
2109
+ try { clearBinaryLookupCache(); } catch {}
2110
+ if (onData) onData(`${build.name} is in place: ${now.installed}\n`);
2111
+ return null;
2112
+ }
2113
+ try {
2114
+ this._cleanStaleShims(agentType);
2115
+ fs.rmSync(pkgDir, { recursive: true, force: true });
2116
+ } catch {}
2117
+ const tail = output.trim().slice(-2000);
2118
+ return `${label} was downloaded, but not its native build for this computer: npm did not install `
2119
+ + `${build.name} (an optional dependency of ${build.pkgName}), so ${label} cannot start. npm leaves `
2120
+ + 'an optional dependency out without failing the install when its download fails, or when optional '
2121
+ + 'dependencies are turned off (omit=optional in an npmrc). Installing it on its own failed too. '
2122
+ + `Check this computer's connection to the npm registry, then install ${label} again.`
2123
+ + (tail ? `\n\nnpm output:\n${tail}` : '');
1966
2124
  }
1967
2125
 
1968
2126
  /**
@@ -1986,22 +2144,25 @@ class Installer {
1986
2144
  * restores nothing, and with no placeholder left to notice the install gets
1987
2145
  * recorded as good.
1988
2146
  */
1989
- async _repairPostinstallStub(agentType, stub, onData) {
2147
+ async _repairPostinstallStub(agentType, stub, onData, { nativeRestored = false } = {}) {
1990
2148
  const entry = this.registry.getEntry(agentType);
1991
2149
  const label = (entry && entry.label) || agentType;
1992
2150
  // The user asked npm to skip install scripts; this lets them say the
1993
2151
  // repair must not run one either.
1994
2152
  const optedOut = scriptRepairDisabled();
2153
+ // With the native build only just restored, the script did run — it had
2154
+ // nothing to copy. Otherwise npm skipped it.
2155
+ const why = nativeRestored
2156
+ ? `${stub.pkgName}'s install script ran before its native build was there, so the ${label} CLI is `
2157
+ + 'still a placeholder.'
2158
+ : `npm skipped ${stub.pkgName}'s install script (ignore-scripts), so the ${label} CLI is only `
2159
+ + 'a placeholder.';
1995
2160
  let output = '';
1996
2161
  if (optedOut) {
1997
- if (onData) {
1998
- onData(`\nnpm skipped ${stub.pkgName}'s install script (ignore-scripts), so the ${label} CLI is only `
1999
- + 'a placeholder. OPENAGENTS_NO_SCRIPT_REPAIR=1 is set, so it is not being run.\n');
2000
- }
2162
+ if (onData) onData(`\n${why} OPENAGENTS_NO_SCRIPT_REPAIR=1 is set, so it is not being run.\n`);
2001
2163
  } else {
2002
2164
  if (onData) {
2003
- onData(`\nnpm skipped ${stub.pkgName}'s install script (ignore-scripts), so the ${label} CLI is only `
2004
- + 'a placeholder. Running it for this one package now — set OPENAGENTS_NO_SCRIPT_REPAIR=1 to refuse.\n');
2165
+ onData(`\n${why} Running it for this one package now — set OPENAGENTS_NO_SCRIPT_REPAIR=1 to refuse.\n`);
2005
2166
  }
2006
2167
  try {
2007
2168
  output = await this._rebuildWithScripts(stub.pkgName, stub.prefix);
@@ -2019,6 +2180,15 @@ class Installer {
2019
2180
  fs.rmSync(path.join(stub.prefix, 'node_modules', stub.pkgName), { recursive: true, force: true });
2020
2181
  } catch {}
2021
2182
  const tail = output.trim().slice(-2000);
2183
+ if (nativeRestored) {
2184
+ return `${label} was downloaded, but its setup could not be finished: ${stub.pkgName}'s `
2185
+ + 'install script did not put its native build in place, so its CLI is only a placeholder. '
2186
+ + (optedOut
2187
+ ? 'OPENAGENTS_NO_SCRIPT_REPAIR=1 stops OpenAgents from running the script again. '
2188
+ : 'Running the script again did not produce the binary either. ')
2189
+ + `Install ${label} again.`
2190
+ + (tail ? `\n\nnpm output:\n${tail}` : '');
2191
+ }
2022
2192
  return `${label} was downloaded, but its setup could not be finished: ${stub.pkgName}'s `
2023
2193
  + 'postinstall script did not run, so its CLI is only a placeholder. npm is set to skip '
2024
2194
  + 'install scripts (ignore-scripts=true in an npmrc), and '
@@ -3119,4 +3289,4 @@ function escapeRegExp(text) {
3119
3289
  return String(text).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
3120
3290
  }
3121
3291
 
3122
- module.exports = { Installer, compareVersions, clearVersionCache, loginVerdict, credentialListHasTarget };
3292
+ module.exports = { Installer, compareVersions, clearVersionCache, loginVerdict, credentialListHasTarget, parseJsonLoose };
@@ -0,0 +1,132 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * The per-platform npm package that holds an agent CLI's native build.
5
+ *
6
+ * @openai/codex, @anthropic-ai/claude-code and opencode-ai are thin npm
7
+ * wrappers: the executable itself is in one optional dependency per platform
8
+ * (`@openai/codex-win32-x64`, `@anthropic-ai/claude-code-darwin-arm64`, …).
9
+ * npm leaves an optional dependency out WITHOUT failing the install — when its
10
+ * download fails (it is the big one, tens of megabytes) or when optional
11
+ * dependencies are turned off (`omit=optional` in an npmrc). The wrapper is
12
+ * then all there is: codex throws "Missing optional dependency
13
+ * @openai/codex-win32-x64" on every run, and the claude-code / opencode-ai
14
+ * postinstall finds nothing to copy and leaves the package's placeholder,
15
+ * which read as "postinstall did not run".
16
+ *
17
+ * Only the packages listed here are checked. Many CLIs also list optional
18
+ * platform packages they can run without (node-pty, sharp, esbuild, bun), and
19
+ * a missing one of those must not fail an install.
20
+ */
21
+
22
+ const fs = require('fs');
23
+ const path = require('path');
24
+
25
+ /**
26
+ * Package names each wrapper accepts for this platform, in the order its own
27
+ * loader tries them; the first is the one to install when none is present.
28
+ * Mirrors bin/codex.js, claude-code's install.cjs and opencode-ai's
29
+ * postinstall.mjs.
30
+ */
31
+ const NATIVE_BUILDS = {
32
+ // codex.js maps every Linux target to a musl build published under the
33
+ // plain linux-<arch> name.
34
+ '@openai/codex': ({ os, cpu }) => [`@openai/codex-${os}-${cpu}`],
35
+ '@anthropic-ai/claude-code': ({ os, cpu, musl }) => [
36
+ `@anthropic-ai/claude-code-${os}-${cpu}${os === 'linux' && musl ? '-musl' : ''}`,
37
+ ],
38
+ // opencode-ai takes any of its variants (baseline = no AVX2) and calls
39
+ // win32 "windows".
40
+ 'opencode-ai': ({ os, cpu, musl }) => {
41
+ const base = `opencode-${os === 'win32' ? 'windows' : os}-${cpu}`;
42
+ if (os === 'linux') {
43
+ return musl
44
+ ? [`${base}-musl`, `${base}-baseline-musl`, base, `${base}-baseline`]
45
+ : [base, `${base}-baseline`, `${base}-musl`, `${base}-baseline-musl`];
46
+ }
47
+ return [base, `${base}-baseline`];
48
+ },
49
+ };
50
+
51
+ /**
52
+ * Wrappers whose postinstall copies the native build over their own bin
53
+ * placeholder. Once it has, the CLI runs without the per-platform package:
54
+ * opencode-ai's postinstall, finding that npm left it out, installs it into a
55
+ * temp directory, copies the binary from there and deletes the directory. A
56
+ * missing package next to a real binary is a working install. codex is not
57
+ * listed: bin/codex.js resolves the package on every run.
58
+ */
59
+ const COPIED_INTO_BIN = new Set(['@anthropic-ai/claude-code', 'opencode-ai']);
60
+
61
+ /** musl libc, detected the way claude-code's install.cjs does it. */
62
+ function isMusl() {
63
+ if (process.platform !== 'linux') return false;
64
+ try {
65
+ const report = process.report && typeof process.report.getReport === 'function'
66
+ ? process.report.getReport()
67
+ : null;
68
+ return report != null && report.header && report.header.glibcVersionRuntime === undefined;
69
+ } catch {
70
+ return false;
71
+ }
72
+ }
73
+
74
+ function readJson(file) {
75
+ try { return JSON.parse(fs.readFileSync(file, 'utf-8')); } catch { return null; }
76
+ }
77
+
78
+ /**
79
+ * Where `name` would be found by a require() made from inside `pkgDir`: its own
80
+ * node_modules first, then each parent's — nested or hoisted, as npm put it.
81
+ */
82
+ function findInstalled(pkgDir, name) {
83
+ let dir = path.resolve(pkgDir);
84
+ for (;;) {
85
+ if (path.basename(dir) !== 'node_modules') {
86
+ const candidate = path.join(dir, 'node_modules', ...name.split('/'));
87
+ if (fs.existsSync(path.join(candidate, 'package.json'))) return candidate;
88
+ }
89
+ const parent = path.dirname(dir);
90
+ if (parent === dir) return null;
91
+ dir = parent;
92
+ }
93
+ }
94
+
95
+ /**
96
+ * The native build an installed wrapper package needs on this machine.
97
+ *
98
+ * @param {string} pkgDir the wrapper's directory (…/node_modules/@openai/codex)
99
+ * @returns {{ pkgName: string, version: string, name: string, spec: string,
100
+ * accepted: string[], installed: string|null, target: string,
101
+ * copiedIntoBin: boolean } | null}
102
+ * null when the package is not one of NATIVE_BUILDS, or lists no build for
103
+ * this platform (nothing to check). `name`/`spec` are what to install —
104
+ * spec as the wrapper lists it, `npm:` aliases included. `copiedIntoBin`:
105
+ * see COPIED_INTO_BIN.
106
+ */
107
+ function nativeBuildFor(pkgDir, { platform = process.platform, arch = process.arch, musl = isMusl() } = {}) {
108
+ const pkg = readJson(path.join(pkgDir, 'package.json'));
109
+ if (!pkg || !NATIVE_BUILDS[pkg.name]) return null;
110
+ const optional = (pkg.optionalDependencies && typeof pkg.optionalDependencies === 'object')
111
+ ? pkg.optionalDependencies
112
+ : {};
113
+ const accepted = NATIVE_BUILDS[pkg.name]({ os: platform, cpu: arch, musl }).filter((n) => optional[n]);
114
+ if (!accepted.length) return null;
115
+ let installed = null;
116
+ for (const n of accepted) {
117
+ installed = findInstalled(pkgDir, n);
118
+ if (installed) break;
119
+ }
120
+ return {
121
+ pkgName: pkg.name,
122
+ version: pkg.version || '',
123
+ name: accepted[0],
124
+ spec: String(optional[accepted[0]]),
125
+ accepted,
126
+ installed,
127
+ target: `${platform}-${arch}${platform === 'linux' && musl ? '-musl' : ''}`,
128
+ copiedIntoBin: COPIED_INTO_BIN.has(pkg.name),
129
+ };
130
+ }
131
+
132
+ module.exports = { nativeBuildFor, findInstalled, isMusl, NATIVE_BUILDS, COPIED_INTO_BIN };
package/src/probe.js CHANGED
@@ -64,6 +64,8 @@ const CODE = {
64
64
  BAD_MODEL: 'bad_model',
65
65
  SERVICE_UNAVAILABLE: 'service_unavailable',
66
66
  CLI_ERROR: 'cli_error',
67
+ INSTALL_INCOMPLETE: 'install_incomplete',
68
+ ENDPOINT_INCOMPATIBLE: 'endpoint_incompatible',
67
69
  };
68
70
 
69
71
  const BENIGN_OUTPUT = BENIGN_CLI_OUTPUT;
@@ -133,6 +135,11 @@ function authFlavor(entry, agentEnv) {
133
135
  */
134
136
  /** Classify an error by its OUTPUT TEXT alone; null when nothing matches. */
135
137
  function classifyOutputText(text) {
138
+ // npm left out the per-platform package holding the native build (codex:
139
+ // "Missing optional dependency @openai/codex-win32-x64"), or the package's
140
+ // placeholder is what ran. Reinstalling fixes it; read as a CLI error it
141
+ // was a stack trace with no next step.
142
+ if (/missing optional dependency|native binary not installed|postinstall (script )?(was|did) not run/.test(text)) return CODE.INSTALL_INCOMPLETE;
136
143
  // Relays word this their own way and answer 403 rather than 402, so the
137
144
  // English-and-402 pattern alone read "out of credit" as "bad credentials"
138
145
  // — the one misreading that sends a user to re-authenticate a working key.
@@ -142,7 +149,12 @@ function classifyOutputText(text) {
142
149
  // was unreachable; a Codex that could not reach chatgpt.com ran out the
143
150
  // probe clock and was reported as waiting for interactive input. "Request
144
151
  // to <host> timed out" is the direct API test's own deadline (utils.js).
145
- if (/enotfound|econnrefused|econnreset|etimedout|eai_again|fetch failed|socket hang up|network error|error sending request|request to \S+ timed out|self[- ]signed certificate|unable to get local issuer/.test(text)) return CODE.NETWORK;
152
+ // Codex (Rust) also says "Connection failed", "stream disconnected before
153
+ // completion" or, refreshing its model list, "failed to refresh available
154
+ // models: request timed out" — on a device that cannot reach chatgpt.com
155
+ // that was all the probe saw before its clock ran out, and it was reported
156
+ // as a CLI waiting for a login prompt.
157
+ if (/enotfound|econnrefused|econnreset|etimedout|eai_again|fetch failed|socket hang up|network error|error sending request|request to \S+ timed out|self[- ]signed certificate|unable to get local issuer|connection failed|stream disconnected before completion|failed to lookup address|dns error|tls handshake|failed to refresh available models: request timed out/.test(text)) return CODE.NETWORK;
146
158
  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;
147
159
  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;
148
160
  // A sign-in that exists but has run out — Claude Code: "Failed to
@@ -229,6 +241,19 @@ function buildGuidance(code, entry, agentEnv, extra = {}) {
229
241
  case CODE.SERVICE_UNAVAILABLE:
230
242
  lines.push(`The model provider for ${label} is temporarily unavailable. Wait a few minutes and test again.`);
231
243
  break;
244
+ case CODE.ENDPOINT_INCOMPATIBLE:
245
+ lines.push(`${label}'s endpoint takes Responses API requests but refuses ${extra.param ? `the "${extra.param}" field` : 'a field'} that ${label} sends with every one of them, so every run fails there. ${label} has no setting to leave it out.`);
246
+ lines.push(type === 'codex'
247
+ ? 'Point the agent at an endpoint that supports the full Responses API, or edit the agent and set Agent capabilities to "Chat only · Chat Completions API" (it then answers without running tools on the device).'
248
+ : 'Point the agent at an endpoint that supports the full Responses API.');
249
+ break;
250
+ case CODE.INSTALL_INCOMPLETE:
251
+ lines.push(`${label} is installed, but not completely: the part that holds its native program for this computer is missing (npm can leave it out without failing the install). Reinstall ${label} from the launcher's Install page.`);
252
+ {
253
+ const cmd = installCommandFor(entry);
254
+ if (cmd) lines.push(`Or reinstall manually: ${cmd}`);
255
+ }
256
+ break;
232
257
  case CODE.VERSION_INCOMPATIBLE:
233
258
  lines.push(`The installed ${label} version is not the one OpenAgents supports. Reinstall it from the launcher's Install page.`);
234
259
  {
@@ -258,14 +283,14 @@ function buildGuidance(code, entry, agentEnv, extra = {}) {
258
283
  async function directApiVerdict(agentEnv, entry, model, baseUrl, protocol) {
259
284
  const res = await callLLM(agentEnv, model, baseUrl, protocol);
260
285
  if (!res || res.success) return null;
261
- const code = classifyFailure(res.error, {});
286
+ const code = directFailureCode(res.error, protocol);
262
287
  if (code === CODE.CLI_ERROR) return null;
263
288
  return {
264
289
  ok: false,
265
290
  method: 'llm_api',
266
291
  code,
267
292
  message: tail(res.error, OUTPUT_CAP),
268
- guidance: buildGuidance(code, entry, agentEnv),
293
+ guidance: buildGuidance(code, entry, agentEnv, { param: refusedParam(res.error) }),
269
294
  };
270
295
  }
271
296
 
@@ -300,6 +325,10 @@ function directBaseUrl(entry, env) {
300
325
  * sent /chat/completions and reported broken.
301
326
  */
302
327
  function directProtocol(type, env) {
328
+ // A Codex agent on a third-party endpoint in Responses mode runs the CLI
329
+ // against <base>/responses (adapters/codex.js); a chat/completions test
330
+ // passed for endpoints that then refused every run.
331
+ if (type === 'codex') return codexResponsesMode(env) ? 'responses' : undefined;
303
332
  if (type === 'deepseek') {
304
333
  // dsh calls a gateway in the format its URL says (see classifyDshEndpoint);
305
334
  // DeepSeek's own host is left to the client, which knows it.
@@ -316,6 +345,42 @@ function directProtocol(type, env) {
316
345
  return null;
317
346
  }
318
347
 
348
+ /** Whether a Codex agent runs the CLI on a custom Responses provider (as adapters/codex.js decides it). */
349
+ function codexResponsesMode(env) {
350
+ if (String(env.CODEX_WIRE_API || '').toLowerCase() !== 'responses') return false;
351
+ const base = String(env.OPENAI_BASE_URL || env.LLM_BASE_URL || '').trim();
352
+ return !!base && !base.includes('api.openai.com');
353
+ }
354
+
355
+ // The Responses test sends what the Codex CLI sends (utils.js). An endpoint
356
+ // that refuses one of those fields will refuse every Codex turn: that is not
357
+ // a bad key or a bad model. Only read so for that test — the chat test's own
358
+ // fields (max_completion_tokens) are not the agent's.
359
+ const RESPONSES_PARAM_REFUSED = /unsupported .{0,40}parameter|unsupported_parameter|unknown parameter|unrecognized request argument|unrecognized (key|field)|additional properties|extra (inputs|fields) are not permitted/i;
360
+
361
+ // The one field the Responses test adds that the CLI never sends (utils.js
362
+ // asks again without it when it is refused). A refusal of it is about the
363
+ // test, not about every Codex turn.
364
+ const RESPONSES_PROBE_ONLY = 'max_output_tokens';
365
+
366
+ /** The code for a failed direct test: the general reading, or the Responses-only one above. */
367
+ function directFailureCode(error, protocol) {
368
+ const text = String(error || '');
369
+ if (protocol === 'responses' && RESPONSES_PARAM_REFUSED.test(text) && !/with this model|reasoning[._]/i.test(text)) {
370
+ // The field the refusal names, or — when it names none — its text.
371
+ const param = refusedParam(text);
372
+ const probeOnly = param ? param === RESPONSES_PROBE_ONLY : text.includes(RESPONSES_PROBE_ONLY);
373
+ if (!probeOnly) return CODE.ENDPOINT_INCOMPATIBLE;
374
+ }
375
+ return classifyFailure(error, {});
376
+ }
377
+
378
+ /** The field a refusing endpoint named (`"param":"client_metadata"`), or ''. */
379
+ function refusedParam(error) {
380
+ const m = /"param"\s*:\s*"([^"]{1,64})"/.exec(String(error || ''));
381
+ return m ? m[1] : '';
382
+ }
383
+
319
384
  /**
320
385
  * One direct call to the agent's endpoint, on the model the agent runs on.
321
386
  * Never rejects.
@@ -390,8 +455,24 @@ function failureMessage(res, code, timeoutMs) {
390
455
  // Each line is scrubbed before that test: a provider that echoes the whole
391
456
  // key (`401 Incorrect API key provided: sk-proj-…`) had the one line that
392
457
  // explains the failure dropped as encoded.
393
- const lines = (s) => String(s || '').split(/\r?\n/).map((l) => scrub(l.trim()))
394
- .filter((l) => l && !BENIGN_OUTPUT.test(l) && !mostlyEncoded(l) && !/^at\s+\S/.test(l));
458
+ //
459
+ // A CLI's own log records (`2026-11-08T05:37:58Z ERROR module: …`) are kept,
460
+ // shorn of the timestamp, but rank after what it said in plain words. Codex's
461
+ // built-in ChatGPT connector (`rmcp::…`) is left out altogether: its lines
462
+ // are about that side service, and they were quoted as the reason a Codex
463
+ // probe failed in place of the model-list error underneath them. Only when
464
+ // nothing else was said do they stand, rather than no reason at all.
465
+ const LOG_RECORD = /^\d{4}-\d{2}-\d{2}T[\d:.]+Z?\s+(?=(TRACE|DEBUG|INFO|WARN|ERROR)\s)/;
466
+ const SIDE_SERVICE = /\brmcp::|\bcodex_mcp::/;
467
+ const lines = (s) => {
468
+ const said = String(s || '').split(/\r?\n/).map((l) => scrub(l.trim()))
469
+ .filter((l) => l && !BENIGN_OUTPUT.test(l) && !mostlyEncoded(l) && !/^at\s+\S/.test(l));
470
+ const own = said.filter((l) => !SIDE_SERVICE.test(l));
471
+ const kept = own.length ? own : said;
472
+ const plain = kept.filter((l) => !LOG_RECORD.test(l));
473
+ const logged = kept.filter((l) => LOG_RECORD.test(l)).map((l) => l.replace(LOG_RECORD, ''));
474
+ return [...plain, ...logged];
475
+ };
395
476
  const all = [...lines(res.stderr), ...lines(res.stdout)];
396
477
  const telling = all.find((l) => classifyOutputText(l.toLowerCase()) === code);
397
478
  const detail = tail(telling || lines(res.stderr).join('\n') || lines(res.stdout).join('\n'), OUTPUT_CAP);
@@ -684,11 +765,11 @@ async function probeAgentType(connector, type, opts = {}) {
684
765
  reply: tail(res.response || '', REPLY_CAP),
685
766
  });
686
767
  }
687
- const code = classifyFailure(res && res.error, {});
768
+ const code = directFailureCode(res && res.error, protocol);
688
769
  return done({
689
770
  ok: false, method: 'llm_api', code,
690
771
  message: tail(res && res.error, OUTPUT_CAP) || 'LLM API test failed',
691
- guidance: buildGuidance(code, entry, agentEnv),
772
+ guidance: buildGuidance(code, entry, agentEnv, { param: refusedParam(res && res.error) }),
692
773
  });
693
774
  }
694
775