@openagents-org/agent-launcher 0.2.219 → 0.2.221

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 (38) 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/src/adapters/claude.js +13 -9
  22. package/src/adapters/codearts.js +1 -0
  23. package/src/adapters/codex.js +49 -9
  24. package/src/adapters/kimi-stream.js +78 -5
  25. package/src/adapters/kimi.js +114 -24
  26. package/src/adapters/mimo-code.js +1 -0
  27. package/src/adapters/openclaw.js +24 -19
  28. package/src/adapters/opencode.js +55 -2
  29. package/src/adapters/pi-launcher-provider.mjs +10 -24
  30. package/src/adapters/pi-provider-config.js +36 -0
  31. package/src/adapters/pi.js +6 -1
  32. package/src/adapters/utils.js +11 -0
  33. package/src/cli-models.js +39 -2
  34. package/src/daemon.js +4 -2
  35. package/src/installer.js +144 -23
  36. package/src/native-build.js +132 -0
  37. package/src/probe.js +64 -4
  38. package/src/utils.js +123 -12
@@ -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();
@@ -8,30 +8,10 @@
8
8
  * ~/.pi/agent/models.json and auth.json untouched.
9
9
  */
10
10
 
11
- const value = (name) => String(process.env[name] || '').trim()
11
+ import launcherConfig from './pi-provider-config.js'
12
12
 
13
- const PROVIDER_DEFAULTS = {
14
- anthropic: {
15
- baseUrl: 'https://api.anthropic.com',
16
- api: 'anthropic-messages',
17
- },
18
- openai: {
19
- baseUrl: 'https://api.openai.com/v1',
20
- api: 'openai-responses',
21
- },
22
- deepseek: {
23
- baseUrl: 'https://api.deepseek.com/v1',
24
- api: 'openai-completions',
25
- },
26
- google: {
27
- baseUrl: 'https://generativelanguage.googleapis.com/v1beta',
28
- api: 'google-generative-ai',
29
- },
30
- openrouter: {
31
- baseUrl: 'https://openrouter.ai/api/v1',
32
- api: 'openai-completions',
33
- },
34
- }
13
+ const { PROVIDER_DEFAULTS, launcherProviderId } = launcherConfig
14
+ const value = (name) => String(process.env[name] || '').trim()
35
15
 
36
16
  function providerKey(provider) {
37
17
  return value('PI_API_KEY') || {
@@ -78,7 +58,13 @@ export default function configureLauncherProvider(pi) {
78
58
  compat.supportsDeveloperRole = false
79
59
  }
80
60
 
81
- pi.registerProvider(provider, {
61
+ // Pi prefers auth.json credentials over an extension's configured key.
62
+ // Match the adapter's process-local provider id when Launcher supplied a
63
+ // key, while keyless relays can still reuse their existing Pi login.
64
+ const providerId = launcherProviderId({
65
+ provider, model, baseUrl: configuredBaseUrl, apiKey: value('PI_API_KEY'),
66
+ })
67
+ pi.registerProvider(providerId, {
82
68
  baseUrl,
83
69
  api,
84
70
  // Pass the resolved secret directly to the process-local provider. This is
@@ -0,0 +1,36 @@
1
+ 'use strict';
2
+
3
+ const PROVIDER_DEFAULTS = {
4
+ anthropic: {
5
+ baseUrl: 'https://api.anthropic.com',
6
+ api: 'anthropic-messages',
7
+ },
8
+ openai: {
9
+ baseUrl: 'https://api.openai.com/v1',
10
+ api: 'openai-responses',
11
+ },
12
+ deepseek: {
13
+ baseUrl: 'https://api.deepseek.com/v1',
14
+ api: 'openai-completions',
15
+ },
16
+ google: {
17
+ baseUrl: 'https://generativelanguage.googleapis.com/v1beta',
18
+ api: 'google-generative-ai',
19
+ },
20
+ openrouter: {
21
+ baseUrl: 'https://openrouter.ai/api/v1',
22
+ api: 'openai-completions',
23
+ },
24
+ };
25
+
26
+ /** Keep Launcher keys separate from native Pi credentials when we can register the provider. */
27
+ function launcherProviderId({ provider, model, baseUrl, apiKey }) {
28
+ const name = String(provider || '').trim().toLowerCase();
29
+ if (name && String(model || '').trim() && String(apiKey || '').trim() &&
30
+ (String(baseUrl || '').trim().replace(/\/+$/, '') || PROVIDER_DEFAULTS[name]?.baseUrl)) {
31
+ return `openagents-${name}`;
32
+ }
33
+ return provider;
34
+ }
35
+
36
+ module.exports = { PROVIDER_DEFAULTS, launcherProviderId };
@@ -64,6 +64,8 @@ const {
64
64
  MIN_PI_VERSION,
65
65
  } = require('./pi-stream');
66
66
 
67
+ const { launcherProviderId } = require('./pi-provider-config');
68
+
67
69
  const IS_WINDOWS = process.platform === 'win32';
68
70
  const LAUNCHER_PROVIDER_EXTENSION = path.join(__dirname, 'pi-launcher-provider.mjs');
69
71
 
@@ -1384,7 +1386,10 @@ class PiAdapter extends BaseAdapter {
1384
1386
  sessionDir: this._sessionDir,
1385
1387
  sessionId,
1386
1388
  appendSystemPrompt,
1387
- provider: cfg.provider,
1389
+ // A stored Pi login wins over an extension's apiKey for the same
1390
+ // provider. Keep Launcher-key requests in a separate provider namespace
1391
+ // so a native login cannot authenticate a different endpoint.
1392
+ provider: launcherProviderId({ ...cfg, apiKey: launcherKey }),
1388
1393
  model: cfg.model,
1389
1394
  thinking: cfg.thinking,
1390
1395
  sessionName: `${this.agentName}/${channel}`,
@@ -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/cli-models.js CHANGED
@@ -16,6 +16,7 @@
16
16
  */
17
17
 
18
18
  const os = require('os');
19
+ const { stripVTControlCharacters } = require('node:util');
19
20
  // spawn() here is the WSL bridge from ./wsl: same signature as
20
21
  // child_process.spawn, and a straight pass-through unless the resolved CLI
21
22
  // lives on the other side of the Windows/WSL boundary.
@@ -124,12 +125,48 @@ function parseQoderModels(text) {
124
125
  return [...seen.values()].slice(0, MAX_MODELS);
125
126
  }
126
127
 
128
+ /**
129
+ * Pi --list-models prints the configured providers' catalog as a table, not a
130
+ * per-model subscription entitlement check. Qualify ids so identical model
131
+ * names on different signed-in providers remain selectable without ambiguity.
132
+ */
133
+ function parsePiModels(text, env = {}) {
134
+ const selectedProvider = String(env.PI_PROVIDER || '').trim().toLowerCase();
135
+ const seen = new Map();
136
+ let inTable = false;
137
+ for (const raw of stripVTControlCharacters(String(text || '')).split(/\r?\n/)) {
138
+ const fields = raw.trim().split(/\s+/);
139
+ if (fields.join(' ') === 'provider model context max-out thinking images') {
140
+ inTable = true;
141
+ continue;
142
+ }
143
+ if (!inTable || fields.length !== 6 ||
144
+ !/^\d+(?:\.\d+)?[KM]?$/i.test(fields[2]) ||
145
+ !/^\d+(?:\.\d+)?[KM]?$/i.test(fields[3]) ||
146
+ !/^(yes|no)$/.test(fields[4]) || !/^(yes|no)$/.test(fields[5])) continue;
147
+ const [provider, model] = fields;
148
+ if (!/^[\w.-]+$/.test(provider) || !cleanId(model)) continue;
149
+ if (selectedProvider && provider.toLowerCase() !== selectedProvider) continue;
150
+ const id = cleanId(`${provider}/${model}`);
151
+ if (!id || seen.has(id)) continue;
152
+ seen.set(id, { id, label: cleanLabel(`${model} (${provider})`, id) });
153
+ if (seen.size >= MAX_MODELS) break;
154
+ }
155
+ return [...seen.values()];
156
+ }
157
+
127
158
  /**
128
159
  * How each CLI is asked. Claude Code has no command for it; its SDK control
129
160
  * protocol does, and a run that is sent the request and then end-of-input
130
161
  * answers and exits without a prompt ever reaching a model.
131
162
  */
132
163
  const LISTERS = {
164
+ pi: {
165
+ args: ['--no-approve', '--no-extensions', '--no-skills', '--list-models'],
166
+ parse: parsePiModels,
167
+ timeoutMs: 30_000,
168
+ env: { PI_SKIP_VERSION_CHECK: '1', NO_COLOR: '1' },
169
+ },
133
170
  codex: {
134
171
  args: ['debug', 'models'],
135
172
  parse: parseCodexModels,
@@ -279,9 +316,9 @@ async function listCliModels(connector, type, opts = {}) {
279
316
  });
280
317
  // A run killed for taking too long may still have answered: Claude Code
281
318
  // replies before it finishes starting up.
282
- const models = lister.parse(res.stdout);
319
+ const models = lister.parse(res.stdout, agentEnv);
283
320
  if (models.length) return { type, ok: true, models };
284
321
  return fail(res.error || 'The CLI listed no models.');
285
322
  }
286
323
 
287
- module.exports = { listCliModels, supportsCliModels, cliModelsWithKey, parseCodexModels, parseClaudeModels, parseQoderModels };
324
+ module.exports = { listCliModels, supportsCliModels, cliModelsWithKey, parseCodexModels, parseClaudeModels, parseQoderModels, parsePiModels };
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 '