@openagents-org/agent-launcher 0.2.219 → 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.
@@ -711,10 +711,19 @@ class OpenClawAdapter extends BaseAdapter {
711
711
  const text = String(stderr || '');
712
712
  const start = text.search(/\{\s*"payloads"/);
713
713
  if (start < 0) return text;
714
- // Braces inside JSON strings (the reply text) are not structure: skip
715
- // string contents, honoring backslash escapes.
714
+ const end = OpenClawAdapter._jsonObjectEnd(text, start);
715
+ return text.slice(0, start) + (end < 0 ? '' : text.slice(end));
716
+ }
717
+
718
+ /**
719
+ * Index just past the `}` that closes the JSON object opening at `start`,
720
+ * or -1 if it never closes. Braces inside JSON strings are not structure: a
721
+ * reply that quotes the end of a code block, or a lone "}", once cut the
722
+ * envelope short, and the whole reply was dropped as "No response
723
+ * generated". String contents are skipped, honoring backslash escapes.
724
+ */
725
+ static _jsonObjectEnd(text, start) {
716
726
  let depth = 0;
717
- let end = text.length;
718
727
  let inString = false;
719
728
  for (let i = start; i < text.length; i++) {
720
729
  const ch = text[i];
@@ -723,9 +732,9 @@ class OpenClawAdapter extends BaseAdapter {
723
732
  else if (ch === '"') inString = false;
724
733
  } else if (ch === '"') inString = true;
725
734
  else if (ch === '{') depth++;
726
- else if (ch === '}' && --depth === 0) { end = i + 1; break; }
735
+ else if (ch === '}' && --depth === 0) return i + 1;
727
736
  }
728
- return text.slice(0, start) + text.slice(end);
737
+ return -1;
729
738
  }
730
739
 
731
740
  /**
@@ -754,20 +763,16 @@ class OpenClawAdapter extends BaseAdapter {
754
763
  // Find the JSON by looking for '{"payloads"' or the last complete JSON object.
755
764
  let jsonStr = null;
756
765
 
757
- // Strategy 1: find {"payloads" or { "payloads" (with whitespace)
758
- let payloadsIdx = text.indexOf('{"payloads"');
759
- if (payloadsIdx < 0) {
760
- // Try with whitespace after {
761
- const match = text.match(/\{\s*"payloads"/);
762
- if (match) payloadsIdx = match.index;
763
- }
764
- if (payloadsIdx >= 0) {
765
- // Find the matching closing brace by counting braces
766
- let depth = 0;
767
- for (let i = payloadsIdx; i < text.length; i++) {
768
- if (text[i] === '{') depth++;
769
- else if (text[i] === '}') { depth--; if (depth === 0) { jsonStr = text.slice(payloadsIdx, i + 1); break; } }
770
- }
766
+ // Strategy 1: each {"payloads" or { "payloads" (with whitespace), up to
767
+ // the brace that closes it. The first one that parses is the envelope; one
768
+ // that does not (a trace line quoting a cut-off envelope) is skipped.
769
+ for (const match of text.matchAll(/\{\s*"payloads"/g)) {
770
+ const end = OpenClawAdapter._jsonObjectEnd(text, match.index);
771
+ if (end < 0) continue;
772
+ const candidate = text.slice(match.index, end);
773
+ try { JSON.parse(candidate); } catch { continue; }
774
+ jsonStr = candidate;
775
+ break;
771
776
  }
772
777
 
773
778
  // Strategy 2: find last '{' that starts a valid JSON with "payloads"
@@ -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, redactSecrets } = require('./utils');
24
+ const { formatAttachmentsForPrompt, redactSecrets, stripAnsi } = require('./utils');
25
25
  const { buildOpenCodeSkillMd, buildOpenCodeSystemPrompt, workspaceSkillName } = require('./workspace-prompt');
26
26
  const { whichBinary, whereBinary, getEnhancedEnv } = require('../paths');
27
27
  const { isPostinstallStub, isPostinstallStubOutput } = require('../postinstall-stub');
@@ -91,6 +91,7 @@ const FAILURE_MESSAGES = {
91
91
  permission_denied: 'OpenCode could not get permission for a tool call. Check the agent’s explicit deny rules or file access settings; sending continue alone will not change them.',
92
92
  process_crashed: 'OpenCode exited unexpectedly. Open diagnostics or retry.',
93
93
  cwd_unavailable: "OpenCode's working directory is not accessible. Check the agent's configured path (or agent home) permissions.",
94
+ config_invalid: 'OpenCode would not start because one of its config files is invalid — the file and what is wrong with it are below. OpenCode reads it on every run, so every message fails until it is fixed: correct or remove that entry, then retry.',
94
95
  unknown_error: 'OpenCode failed for an undetermined reason. Open diagnostics or retry.',
95
96
  };
96
97
 
@@ -1373,6 +1374,9 @@ class OpenCodeAdapter extends BaseAdapter {
1373
1374
  * { category, diagnostic, detail }.
1374
1375
  */
1375
1376
  static _classifyFailure({ code, signal, stdout, stderr, stdoutErr } = {}) {
1377
+ // OpenCode colours its errors even into a pipe; quoted as they came, the
1378
+ // channel showed "\x1b[91m\x1b[1mError: \x1b[0m…".
1379
+ stderr = stripAnsi(stderr);
1376
1380
  const err = stdoutErr || OpenCodeAdapter._extractErrorFromStdout(stdout || '');
1377
1381
  const status = err && err.status ? String(err.status) : '';
1378
1382
  const msg = (err && err.message) || '';
@@ -1383,9 +1387,15 @@ class OpenCodeAdapter extends BaseAdapter {
1383
1387
  const hay = `${name} ${status} ${msg} ${stderr || ''}`.toLowerCase();
1384
1388
  const has = (re) => re.test(hay);
1385
1389
 
1390
+ const configError = OpenCodeAdapter._configError(stderr);
1386
1391
  let category;
1387
1392
  if (isPostinstallStubOutput(hay)) {
1388
1393
  category = 'install_incomplete';
1394
+ } else if (configError) {
1395
+ // Checked before the provider patterns: what is wrong with the file is
1396
+ // free text ("Unrecognized key: model", "got {…401…}") that would read
1397
+ // as a bad model or a rejected key.
1398
+ category = 'config_invalid';
1389
1399
  } else if (has(/(?:unrecognized|unknown) (?:flag|option|argument)s?:?\s*['"`]?--?[a-z]/)) {
1390
1400
  // The CLI refused a flag this adapter always passes, so it is not a
1391
1401
  // build we support (one whose version string we could not read gets
@@ -1419,10 +1429,53 @@ class OpenCodeAdapter extends BaseAdapter {
1419
1429
  category = 'unknown_error';
1420
1430
  }
1421
1431
 
1422
- const detail = OpenCodeAdapter._redact(msg || stderr || '').slice(0, 200);
1432
+ const detail = configError
1433
+ ? OpenCodeAdapter._redact(configError).slice(0, 500)
1434
+ : OpenCodeAdapter._redact(msg || stderr || '').slice(0, 200);
1423
1435
  return { category, diagnostic, detail };
1424
1436
  }
1425
1437
 
1438
+ /**
1439
+ * OpenCode's refusal of a config file, as one line: which file, and what is
1440
+ * wrong with it — or null. Its two shapes (opencode-ai 1.17.11):
1441
+ *
1442
+ * Error: Configuration is invalid at <file>
1443
+ * ↳ Expected { readonly "type": "local", ... } | …, got {"url":"…"} mcp.upsy
1444
+ * ↳ Missing key mcp.upsy.enabled
1445
+ *
1446
+ * Error: Config file at <file> is not valid JSON(C):
1447
+ * --- JSONC Input --- … --- Errors ---
1448
+ * ValueExpected at line 1, column 15
1449
+ * Line 1: {"provider": {,}
1450
+ * ^
1451
+ *
1452
+ * The first 200 characters of stderr usually ended inside the file's path,
1453
+ * before the reason.
1454
+ */
1455
+ static _configError(text) {
1456
+ const lines = stripAnsi(text).split(/\r?\n/);
1457
+ // OpenCode's own error line, not the phrase quoted somewhere else.
1458
+ const at = lines.findIndex((l) => /^\s*(?:error:\s*)?(?:configuration is invalid at |config file at .+ is not valid json)/i.test(l));
1459
+ if (at < 0) return null;
1460
+ const head = lines[at].trim().replace(/^error:\s*/i, '').replace(/:\s*$/, '');
1461
+ const reasons = [];
1462
+ for (const l of lines.slice(at + 1)) {
1463
+ const m = l.trim().match(/^↳\s*(.+)$/);
1464
+ if (m) reasons.push(m[1]);
1465
+ }
1466
+ if (!reasons.length) {
1467
+ const start = lines.findIndex((l) => l.trim() === '--- Errors ---');
1468
+ for (const l of start < 0 ? [] : lines.slice(start + 1)) {
1469
+ const t = l.trim();
1470
+ if (/^---/.test(t)) break;
1471
+ // The echoed source line and its caret, not reasons.
1472
+ if (!t || /^line \d+:/i.test(t) || /^\^+$/.test(t)) continue;
1473
+ reasons.push(t);
1474
+ }
1475
+ }
1476
+ return reasons.length ? `${head}: ${reasons.join('; ')}` : head;
1477
+ }
1478
+
1426
1479
  /** Category for an exit-0 run that produced no final assistant text. */
1427
1480
  static _emptyExitCategory(stdout) {
1428
1481
  const raw = String(stdout || '').trim();
@@ -272,6 +272,16 @@ function networkErrorText(err) {
272
272
  return inner || err.code || String(err) || 'unknown network error';
273
273
  }
274
274
 
275
+ // Terminal escape sequences (colour, cursor). A CLI that colours its errors
276
+ // writes them to a pipe too, and quoted into a channel they show as
277
+ // "\x1b[91m\x1b[1mError: \x1b[0m…".
278
+ const ANSI_RE = /\x1b\[[0-9;?]*[ -/]*[@-~]/g;
279
+
280
+ /** `text` with terminal escape sequences removed. */
281
+ function stripAnsi(text) {
282
+ return String(text || '').replace(ANSI_RE, '');
283
+ }
284
+
275
285
  /** CLI output with the known-harmless lines taken out. */
276
286
  function stripCliNoise(text) {
277
287
  return String(text || '').split(/\r?\n/).filter((l) => !BENIGN_CLI_OUTPUT.test(l)).join('\n');
@@ -282,6 +292,7 @@ module.exports = {
282
292
  networkErrorText,
283
293
  BENIGN_CLI_OUTPUT,
284
294
  stripCliNoise,
295
+ stripAnsi,
285
296
  decodeConsoleOutput,
286
297
  generateSessionTitle,
287
298
  formatAttachmentsForPrompt,
package/src/daemon.js CHANGED
@@ -44,8 +44,10 @@ const RUNTIME_DETECT_TIMEOUT_MS = 90 * 1000;
44
44
  // not installed). Time alone does not change them, and re-running them every
45
45
  // hour re-reported the same failure all day; they are swept daily, and again
46
46
  // as soon as detection sees the type installed or signed in.
47
- const SETUP_INCOMPLETE = new Set(['not_ready', 'not_logged_in', 'missing_api_key', 'not_installed', 'install_failed']);
47
+ const SETUP_INCOMPLETE = new Set(['not_ready', 'not_logged_in', 'missing_api_key', 'not_installed', 'install_failed', 'install_incomplete']);
48
48
  const SETUP_INCOMPLETE_MAX_AGE_MS = 24 * 3600 * 1000;
49
+ // Probe results a runtime reinstall fixes: tested again as soon as one succeeds.
50
+ const REPROBE_AFTER_REPAIR = new Set(['version_incompatible', 'install_incomplete']);
49
51
 
50
52
  /**
51
53
  * Mask an API key for display (same shape the workspace backend uses for
@@ -295,7 +297,7 @@ class Daemon {
295
297
  */
296
298
  _reprobeAfterRepair(agentType) {
297
299
  const due = this.config.getAgents().filter((a) => (a.type || 'openclaw') === agentType
298
- && this._probes[a.name] && this._probes[a.name].code === 'version_incompatible');
300
+ && this._probes[a.name] && REPROBE_AFTER_REPAIR.has(this._probes[a.name].code));
299
301
  if (!due.length) return;
300
302
  (async () => {
301
303
  for (const a of due) {
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
  /**
@@ -1855,18 +1856,14 @@ class Installer {
1855
1856
  if (onData) onData(`\nDone! ${agentType} is now installed.\n`);
1856
1857
  resolve({ success: true, command: displayCmd });
1857
1858
  };
1858
- // An npm package whose postinstall was skipped exits 0 with a
1859
- // placeholder where its CLI should be. See _findPostinstallStub.
1860
- const stub = this._findPostinstallStub(agentType);
1861
- if (stub) {
1862
- this._repairPostinstallStub(agentType, stub, onData).then((problem) => {
1863
- if (!problem) return markDone();
1864
- if (onData) onData(`\n${problem}\n`);
1865
- reject(new Error(problem));
1866
- }, reject);
1867
- return;
1868
- }
1869
- 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);
1870
1867
  } else {
1871
1868
  // A partial install can leave a placeholder stub at
1872
1869
  // bin/<binary>.exe and npm-generated cmd-shims under
@@ -1962,7 +1959,29 @@ class Installer {
1962
1959
  * every other package and every other install.
1963
1960
  */
1964
1961
  _rebuildWithScripts(pkgName, prefix) {
1965
- 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) {
1966
1985
  const env = this._buildShellEnv();
1967
1986
  const run = this._execFileForTest || execFile;
1968
1987
  const runNpm = (file, argv, extra = {}) => new Promise((resolve, reject) => {
@@ -1985,9 +2004,10 @@ class Installer {
1985
2004
  const win = process.platform === 'win32';
1986
2005
  const npm = whichBinary('npm') || (win ? 'npm.cmd' : 'npm');
1987
2006
  // npm.cmd is a batch file and only runs through cmd.exe. With shell:true
1988
- // 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).
1989
2009
  if (win && /\.(cmd|bat)$/i.test(npm)) {
1990
- const q = (a) => (/\s/.test(a) ? `"${a}"` : a);
2010
+ const q = (a) => (/[\s^&|<>()]/.test(a) ? `"${a}"` : a);
1991
2011
  return runNpm(q(npm), args.map(q), { shell: true });
1992
2012
  }
1993
2013
  return runNpm(npm, args);
@@ -2010,8 +2030,97 @@ class Installer {
2010
2030
  * package already taken back out.
2011
2031
  */
2012
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
+ }
2013
2043
  const stub = this._findPostinstallStub(agentType);
2014
- 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}` : '');
2015
2124
  }
2016
2125
 
2017
2126
  /**
@@ -2035,22 +2144,25 @@ class Installer {
2035
2144
  * restores nothing, and with no placeholder left to notice the install gets
2036
2145
  * recorded as good.
2037
2146
  */
2038
- async _repairPostinstallStub(agentType, stub, onData) {
2147
+ async _repairPostinstallStub(agentType, stub, onData, { nativeRestored = false } = {}) {
2039
2148
  const entry = this.registry.getEntry(agentType);
2040
2149
  const label = (entry && entry.label) || agentType;
2041
2150
  // The user asked npm to skip install scripts; this lets them say the
2042
2151
  // repair must not run one either.
2043
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.';
2044
2160
  let output = '';
2045
2161
  if (optedOut) {
2046
- if (onData) {
2047
- onData(`\nnpm skipped ${stub.pkgName}'s install script (ignore-scripts), so the ${label} CLI is only `
2048
- + 'a placeholder. OPENAGENTS_NO_SCRIPT_REPAIR=1 is set, so it is not being run.\n');
2049
- }
2162
+ if (onData) onData(`\n${why} OPENAGENTS_NO_SCRIPT_REPAIR=1 is set, so it is not being run.\n`);
2050
2163
  } else {
2051
2164
  if (onData) {
2052
- onData(`\nnpm skipped ${stub.pkgName}'s install script (ignore-scripts), so the ${label} CLI is only `
2053
- + '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`);
2054
2166
  }
2055
2167
  try {
2056
2168
  output = await this._rebuildWithScripts(stub.pkgName, stub.prefix);
@@ -2068,6 +2180,15 @@ class Installer {
2068
2180
  fs.rmSync(path.join(stub.prefix, 'node_modules', stub.pkgName), { recursive: true, force: true });
2069
2181
  } catch {}
2070
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
+ }
2071
2192
  return `${label} was downloaded, but its setup could not be finished: ${stub.pkgName}'s `
2072
2193
  + 'postinstall script did not run, so its CLI is only a placeholder. npm is set to skip '
2073
2194
  + 'install scripts (ignore-scripts=true in an npmrc), and '
@@ -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 };