@openagents-org/agent-launcher 0.2.216 → 0.2.218

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openagents-org/agent-launcher",
3
- "version": "0.2.216",
3
+ "version": "0.2.218",
4
4
  "description": "OpenAgents Launcher — install, configure, and run AI coding agents from your terminal",
5
5
  "main": "src/index.js",
6
6
  "bin": {
package/registry.json CHANGED
@@ -1331,6 +1331,9 @@
1331
1331
  "-p",
1332
1332
  "hi"
1333
1333
  ],
1334
+ "env": {
1335
+ "GEMINI_CLI_TRUST_WORKSPACE": "true"
1336
+ },
1334
1337
  "timeout_s": 120
1335
1338
  },
1336
1339
  "env_config": [],
@@ -25,7 +25,7 @@ const https = require('https');
25
25
 
26
26
  const { whereBinary } = require('../paths');
27
27
  const BaseAdapter = require('./base');
28
- const { redactSecrets, formatAttachmentsForPrompt, decodeConsoleOutput, BENIGN_CLI_OUTPUT } = require('./utils');
28
+ const { redactSecrets, formatAttachmentsForPrompt, decodeConsoleOutput, BENIGN_CLI_OUTPUT, networkErrorText } = require('./utils');
29
29
  const { buildOpenclawSystemPrompt } = require('./workspace-prompt');
30
30
 
31
31
  const IS_WINDOWS = process.platform === 'win32';
@@ -39,7 +39,15 @@ const MAX_INLINE_ATTACHMENT_CHARS = 50000;
39
39
  // then went quiet left the run hanging forever with nothing in the log.
40
40
  // Overridable per instance (_directIdleTimeoutMs / _directTotalTimeoutMs).
41
41
  const DIRECT_IDLE_TIMEOUT_MS = 120000;
42
+ // The overall deadline is checked, not enforced, while the model is still
43
+ // producing: a reasoning model thinking for minutes (22k streamed events in one
44
+ // report) was cut off at 300s and everything it had sent was thrown away. Each
45
+ // time it comes due with new text or reasoning since the last check it moves
46
+ // on by the same step, up to the hard ceiling below; a stream that only sends
47
+ // keep-alives, or nothing new, still ends there. What reply text there is at
48
+ // that point is posted, marked as cut off.
42
49
  const DIRECT_TOTAL_TIMEOUT_MS = 300000;
50
+ const DIRECT_HARD_TIMEOUT_MS = 900000;
43
51
  const TEXT_FILE_RE = /\.(md|markdown|txt|text|csv|tsv|json|jsonl|ya?ml|toml|ini|xml|html?|log|sql|sh|py|js|mjs|cjs|ts|tsx|jsx|java|go|rs|rb|php|c|h|cc|cpp|hpp|cs|swift|kt)$/i;
44
52
 
45
53
  // How much of a failure's own words reach the channel.
@@ -983,13 +991,23 @@ class CodexAdapter extends BaseAdapter {
983
991
  const mod = parsed.protocol === 'https:' ? https : http;
984
992
  const idleMs = this._directIdleTimeoutMs || DIRECT_IDLE_TIMEOUT_MS;
985
993
  const totalMs = this._directTotalTimeoutMs || DIRECT_TOTAL_TIMEOUT_MS;
994
+ const hardMs = Math.max(totalMs, this._directHardTimeoutMs || DIRECT_HARD_TIMEOUT_MS);
986
995
  const started = Date.now();
987
996
  // What arrived before things stopped, so a stalled relay can be told
988
997
  // apart from one that answered in a shape we don't read.
989
998
  const progress = { status: 0, bytes: 0, events: 0 };
999
+ let reply = null; // what the stream has carried so far, once it is one
990
1000
  const seconds = () => Math.round((Date.now() - started) / 1000);
991
- const note = () => `HTTP ${progress.status || 'no response'}, ${progress.bytes} bytes, `
992
- + `${progress.events} events, ${seconds()}s`;
1001
+ const contentChars = () => (reply ? reply.text.length + reply.reasoning.length + reply.toolArgs.length : 0);
1002
+ // Text and reasoning counted apart: "still thinking" and "a relay
1003
+ // sending empty events" looked the same as bytes and events alone.
1004
+ const note = () => {
1005
+ const content = reply && contentChars()
1006
+ ? `, ${reply.text.length} reply chars, ${reply.reasoning.length} reasoning chars`
1007
+ : '';
1008
+ return `HTTP ${progress.status || 'no response'}, ${progress.bytes} bytes, `
1009
+ + `${progress.events} events${content}, ${seconds()}s`;
1010
+ };
993
1011
 
994
1012
  let settled = false;
995
1013
  let deadline = null;
@@ -1024,7 +1042,7 @@ class CodexAdapter extends BaseAdapter {
1024
1042
  return;
1025
1043
  }
1026
1044
 
1027
- const reply = { text: '', reasoning: '', toolArgs: '', error: '', finishReason: '' };
1045
+ reply = { text: '', reasoning: '', toolArgs: '', error: '', finishReason: '' };
1028
1046
  let streamed = false;
1029
1047
  let body = ''; // the raw response, kept until it turns out to be an SSE stream
1030
1048
  let buffer = '';
@@ -1068,14 +1086,30 @@ class CodexAdapter extends BaseAdapter {
1068
1086
  `The LLM API stopped responding, no data for ${Math.round(idleMs / 1000)}s (${note()})`));
1069
1087
  req.destroy();
1070
1088
  });
1071
- deadline = setTimeout(() => {
1072
- finish(new Error(
1073
- `The LLM API request went past ${Math.round(totalMs / 1000)}s with no usable reply (${note()})`));
1089
+ let charsAtCheck = 0;
1090
+ const onDeadline = () => {
1091
+ const elapsed = Date.now() - started;
1092
+ const chars = contentChars();
1093
+ if (chars > charsAtCheck && elapsed < hardMs) {
1094
+ charsAtCheck = chars;
1095
+ deadline = setTimeout(onDeadline, Math.min(totalMs, hardMs - elapsed));
1096
+ if (deadline.unref) deadline.unref();
1097
+ return;
1098
+ }
1099
+ const partial = reply ? CodexAdapter._completionText(reply) : '';
1100
+ if (partial) {
1101
+ this._log(`Direct API reply cut off at ${seconds()}s (${note()})`);
1102
+ finish(null, `${partial}\n\n_(Cut off: the model was still writing after ${seconds()}s.)_`);
1103
+ } else {
1104
+ const what = reply && reply.reasoning ? 'still thinking, no reply text yet' : 'no usable reply';
1105
+ finish(new Error(`The LLM API request went past ${seconds()}s with ${what} (${note()})`));
1106
+ }
1074
1107
  req.destroy();
1075
- }, totalMs);
1108
+ };
1109
+ deadline = setTimeout(onDeadline, totalMs);
1076
1110
  if (deadline.unref) deadline.unref();
1077
1111
 
1078
- req.on('error', (err) => finish(err));
1112
+ req.on('error', (err) => finish(err && err.message ? err : new Error(networkErrorText(err))));
1079
1113
  req.write(payload);
1080
1114
  req.end();
1081
1115
  });
@@ -146,6 +146,8 @@ function isRecapEligible(msg, currentMessage) {
146
146
  if (!msg) return false;
147
147
  const mt = msg.messageType || 'chat';
148
148
  if (mt === 'status' || mt === 'thinking' || mt === 'loading') return false;
149
+ // Control signals (a queue cancel) are not conversation for the agent.
150
+ if (mt === 'queue_cancel') return false;
149
151
  const text = (msg.content || '').trim();
150
152
  if (!text) return false;
151
153
  if (text === currentMessage) return false;
@@ -290,6 +290,11 @@ class GeminiAdapter extends BaseAdapter {
290
290
 
291
291
  let cmd;
292
292
  const cleanEnv = { ...(this.agentEnv || process.env) };
293
+ // Without it a Gemini CLI with folder trust on (the default for a Google
294
+ // sign-in) stops with "Gemini CLI is not running in a trusted directory"
295
+ // in any working directory the user never trusted by hand. It is what the
296
+ // CLI's own --skip-trust sets; an explicit value of the user's stands.
297
+ if (cleanEnv.GEMINI_CLI_TRUST_WORKSPACE == null) cleanEnv.GEMINI_CLI_TRUST_WORKSPACE = 'true';
293
298
 
294
299
  let _shouldRetry = false;
295
300
  for (let attempt = 0; attempt < 2; attempt++) {
@@ -62,6 +62,14 @@ const TOOLSET_WARNING_RE = /^Warning: Unknown toolsets:/;
62
62
  // (t("cli.resume.session_not_found")), so this only matches the English text;
63
63
  // under another locale a lost session is not recognised as lost.
64
64
  const SESSION_NOT_FOUND_RE = /session not found/i;
65
+ // What Hermes says when a resumed session was opened on credentials that are
66
+ // no longer in config.yaml: "This chat can't use the API key it was started
67
+ // with any more (model.api_key: removed from config.yaml since this session
68
+ // started), so nothing can run in it." A session pins its credentials, so a
69
+ // session begun on the device-wide `model:` key an earlier version wrote
70
+ // (handed back once each agent got a provider of its own) could never run
71
+ // again; only a new session can. English only, like SESSION_NOT_FOUND_RE.
72
+ const SESSION_CREDENTIALS_GONE_RE = /(?:can't|cannot) use the (?:API key|credentials?) it was started with|removed from config\.yaml since this session started/i;
65
73
  const MAX_HISTORY_ENTRIES = 12;
66
74
  const OPENAGENTS_RULES = [
67
75
  '\n## OpenAgents-specific Rules',
@@ -826,6 +834,11 @@ class HermesAdapter extends BaseAdapter {
826
834
  async _converse(channelName, content) {
827
835
  const resumeId = this._channelSessions[channelName] || null;
828
836
  const run = await this._attemptTurn(channelName, content, resumeId);
837
+ if (resumeId && !run.stopped && SESSION_CREDENTIALS_GONE_RE.test(`${run.text || ''}\n${run.detail || ''}`)) {
838
+ this._log(`Hermes session ${resumeId} was started on credentials no longer in config.yaml, starting a new one`);
839
+ this._forgetSession(channelName);
840
+ return this._attemptTurn(channelName, content, null);
841
+ }
829
842
  const neverBegan = !run.stopped && run.exitCode !== 0 && !run.sessionId;
830
843
  if (!resumeId || !neverBegan) return run;
831
844
 
@@ -43,6 +43,11 @@ const OPENCODE_PINNED_VERSION = '1.17.11';
43
43
  // Supported floor — below this we block the run with `unsupported_version`.
44
44
  // The 1.17.x line is the stream-json shape this adapter targets.
45
45
  const OPENCODE_MIN_VERSION = '1.17.0';
46
+ // First major this adapter cannot drive. OpenCode 2 (`@opencode/cli`, its
47
+ // Homebrew formula and curl installer) is a new command line: `run` has no
48
+ // `--dir`, so every message died with "Unrecognized flag: --dir" while the
49
+ // preflight, seeing only "newer than tested", let it through.
50
+ const OPENCODE_UNSUPPORTED_MAJOR = 2;
46
51
  // Highest version whose JSON behavior is treated as verified. Newer is allowed
47
52
  // but flagged 'degraded' (the run still proceeds; any failure is classified).
48
53
  const OPENCODE_TESTED_MAX_VERSION = '1.17.11';
@@ -70,7 +75,7 @@ const FAILURE_MESSAGES = {
70
75
  cli_not_found: `OpenCode CLI not found. Install it (\`npm install -g opencode-ai@${OPENCODE_PINNED_VERSION}\`) and try again.`,
71
76
  cli_not_executable: 'OpenCode CLI was found but could not be started. Reinstall it, then retry.',
72
77
  install_incomplete: `OpenCode is installed, but its setup never finished: the opencode-ai package's postinstall script did not run (npm \`ignore-scripts\`, or a pnpm/bun install), so the \`opencode\` command is only a placeholder. Reinstall OpenCode from the launcher — or, for a copy you installed yourself, run \`npm install -g opencode-ai@${OPENCODE_PINNED_VERSION} --ignore-scripts=false\` — then retry.`,
73
- unsupported_version: `This OpenCode CLI version is not supported (requires >= ${OPENCODE_MIN_VERSION}). Reinstall \`opencode-ai@${OPENCODE_PINNED_VERSION}\` and retry.`,
78
+ unsupported_version: `This OpenCode CLI version is not supported: OpenAgents runs the opencode-ai 1.x CLI (${OPENCODE_MIN_VERSION} or newer), and OpenCode 2.x changed its command line. Reinstall OpenCode from the launcher, or run \`npm install -g opencode-ai@${OPENCODE_PINNED_VERSION}\`, and retry.`,
74
79
  model_missing: "No model is configured for OpenCode. Set a model (LLM_MODEL, e.g. `gpt-4o`) in this agent's configuration, then retry.",
75
80
  credential_missing: 'OpenCode has no API key or sign-in configured. Add an API key (LLM_API_KEY) or run `opencode auth login`, then retry.',
76
81
  auth_failed: "OpenCode's provider rejected the credentials (authentication failed). Check the API key or sign-in and retry.",
@@ -159,7 +164,10 @@ class OpenCodeAdapter extends BaseAdapter {
159
164
  // opencode hangs waiting for interactive provider/model selection.
160
165
  // Connected agents run unattended: let the CLI resolve permission prompts
161
166
  // automatically instead of rejecting tools outside the working directory.
162
- const args = ['run', '--format', 'json', '--dangerously-skip-permissions', '--dir', runCwd, '--model', model];
167
+ // --thinking adds the model's reasoning to the JSON stream as `reasoning`
168
+ // events, shown live as thinking (like Claude and Codex). Available since
169
+ // the minimum supported 1.17.0.
170
+ const args = ['run', '--format', 'json', '--thinking', '--dangerously-skip-permissions', '--dir', runCwd, '--model', model];
163
171
  if (sessionId) args.push('--session', sessionId);
164
172
  return args;
165
173
  }
@@ -504,6 +512,7 @@ class OpenCodeAdapter extends BaseAdapter {
504
512
  const eventType = String(event.type || '').toLowerCase();
505
513
  if (['step_start', 'step-start', 'step_finish', 'step-finish', 'tool_use', 'tool'].includes(eventType)) return null;
506
514
  if (OpenCodeAdapter._isToolEvent(event)) return null;
515
+ if (OpenCodeAdapter._isReasoningEvent(event)) return null;
507
516
  if (eventType.includes('error')) return null;
508
517
 
509
518
  const part = event.part;
@@ -574,6 +583,13 @@ class OpenCodeAdapter extends BaseAdapter {
574
583
  }
575
584
 
576
585
  async _handleStreamEvent(event, msgChannel, responseState = null) {
586
+ // Reasoning is a live thinking trace only: it never counts toward the reply.
587
+ const reasoning = OpenCodeAdapter._reasoningFromEvent(event);
588
+ if (reasoning !== null) {
589
+ if (reasoning.trim()) await this.sendThinking(msgChannel, reasoning.trim());
590
+ return;
591
+ }
592
+
577
593
  const status = OpenCodeAdapter._toolStatusFromEvent(event);
578
594
  if (status) {
579
595
  // A tool call resets `finalText` (the "text since the last tool"), so the
@@ -1075,8 +1091,21 @@ class OpenCodeAdapter extends BaseAdapter {
1075
1091
  * unusable cwd) and lets anything ambiguous through to a real run.
1076
1092
  */
1077
1093
  _preflight() {
1078
- const binary = this._opencodeBinary || this._findOpencodeBinary();
1079
- if (binary) this._opencodeBinary = binary;
1094
+ // The path found at start-up is kept, but not past the file it names: a
1095
+ // reinstall or an antivirus quarantine took it away, and every message
1096
+ // after that failed "CLI not found" until the agent restarted, even with
1097
+ // a working copy installed by then.
1098
+ let binary = this._opencodeBinary;
1099
+ if (binary && !fs.existsSync(binary)) {
1100
+ const found = this._findOpencodeBinary();
1101
+ if (found !== binary) {
1102
+ this._log(`${binary} is gone; ${found ? `using ${found}` : 'no other copy found'}`);
1103
+ this._versionProbe = null;
1104
+ }
1105
+ binary = found;
1106
+ }
1107
+ binary = binary || this._findOpencodeBinary();
1108
+ this._opencodeBinary = binary || null;
1080
1109
  if (!binary) return { ok: false, category: 'cli_not_found' };
1081
1110
 
1082
1111
  // Before every other check: the placeholder a skipped postinstall leaves
@@ -1100,7 +1129,7 @@ class OpenCodeAdapter extends BaseAdapter {
1100
1129
  ok: false,
1101
1130
  category: 'unsupported_version',
1102
1131
  detail: `detected ${probe.version || 'unknown'}`,
1103
- diagnostic: `detected ${probe.version}, requires >= ${OPENCODE_MIN_VERSION}`,
1132
+ diagnostic: `detected ${probe.version}, requires >= ${OPENCODE_MIN_VERSION} and < ${OPENCODE_UNSUPPORTED_MAJOR}.0.0`,
1104
1133
  };
1105
1134
  }
1106
1135
  // 'unknown' (unparseable) and 'degraded' (newer than tested) still run.
@@ -1262,6 +1291,24 @@ class OpenCodeAdapter extends BaseAdapter {
1262
1291
  // ------------------------------------------------------------------
1263
1292
 
1264
1293
  /** True when an event is a tool call, across opencode's version-varying shapes. */
1294
+ /** A `--thinking` reasoning event (`{type:"reasoning", part:{type:"reasoning", text}}`). */
1295
+ static _isReasoningEvent(event) {
1296
+ if (!event || typeof event !== 'object') return false;
1297
+ if (String(event.type || '').toLowerCase() === 'reasoning') return true;
1298
+ const part = event.part;
1299
+ return !!(part && typeof part === 'object' && String(part.type || '').toLowerCase() === 'reasoning');
1300
+ }
1301
+
1302
+ /** Reasoning text from a reasoning event ('' when empty), or null for any other event. */
1303
+ static _reasoningFromEvent(event) {
1304
+ if (!OpenCodeAdapter._isReasoningEvent(event)) return null;
1305
+ const part = (event.part && typeof event.part === 'object') ? event.part : event;
1306
+ const text = part.text || part.content || '';
1307
+ // Summaries of several reasoning steps arrive glued together
1308
+ // ("**Checking A****Testing B**"); give each heading its own paragraph.
1309
+ return typeof text === 'string' ? text.replace(/\*\*\*\*(?=\S)/g, '**\n\n**') : '';
1310
+ }
1311
+
1265
1312
  static _isToolEvent(event) {
1266
1313
  if (!event || typeof event !== 'object') return false;
1267
1314
  const t = String(event.type || '').toLowerCase();
@@ -1383,11 +1430,12 @@ class OpenCodeAdapter extends BaseAdapter {
1383
1430
  return 'empty_response';
1384
1431
  }
1385
1432
 
1386
- /** 'ok' | 'degraded' (newer than tested) | 'unsupported' (too old) | 'unknown'. */
1433
+ /** 'ok' | 'degraded' (newer than tested) | 'unsupported' (too old, or 2.x) | 'unknown'. */
1387
1434
  static _classifyVersion(version) {
1388
1435
  // Non-semver (or unreadable) → 'unknown': allow the run, never block on it.
1389
1436
  if (!version || !/^\d+\.\d+/.test(String(version))) return 'unknown';
1390
1437
  if (OpenCodeAdapter._cmpVer(version, OPENCODE_MIN_VERSION) < 0) return 'unsupported';
1438
+ if (Number(String(version).split('.')[0]) >= OPENCODE_UNSUPPORTED_MAJOR) return 'unsupported';
1391
1439
  if (OPENCODE_TESTED_MAX_VERSION && OpenCodeAdapter._cmpVer(version, OPENCODE_TESTED_MAX_VERSION) > 0) return 'degraded';
1392
1440
  return 'ok';
1393
1441
  }
@@ -247,8 +247,30 @@ function decodeConsoleOutput(buf, isWindows = process.platform === 'win32') {
247
247
  * from stdin...", which filled the smoke test's timeout message. Node's own
248
248
  * process warnings ("(node:1234) Warning: …", "(Use `node --trace-warnings
249
249
  * ...`") come ahead of the real error from npm-shipped CLIs like CodeBuddy.
250
+ * Newer Claude Code reports an unknown model as a one-line signal instead,
251
+ * "[claude-code:unrecognized_model] {"model":…}", on every run against a relay
252
+ * model; read as the failure, it turned a timed-out smoke test into "wrong
253
+ * model" and skipped the direct API check that would have said why.
250
254
  */
251
- const BENIGN_CLI_OUTPUT = /claude\.ai connectors are disabled|doesn't recognize the model|assumes a context window|auto-compact keeps this session|CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT|Model metadata for .* not found|Defaulting to fallback metadata|^\s*Reading (prompt|additional input) from stdin|^\s*\d{4}-\d{2}-\d{2}T[\d:.]+Z?\s+(TRACE|DEBUG|INFO|WARN)\s|^\s*\(node:\d+\) (\[\w+\] )?\w*Warning:|^\s*\(Use `node --trace-(warnings|deprecation) \.\.\.`/i;
255
+ const BENIGN_CLI_OUTPUT = /claude\.ai connectors are disabled|doesn't recognize the model|\[claude-code:unrecognized_model\]|assumes a context window|auto-compact keeps this session|CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT|Model metadata for .* not found|Defaulting to fallback metadata|^\s*Reading (prompt|additional input) from stdin|^\s*\d{4}-\d{2}-\d{2}T[\d:.]+Z?\s+(TRACE|DEBUG|INFO|WARN)\s|^\s*\(node:\d+\) (\[\w+\] )?\w*Warning:|^\s*\(Use `node --trace-(warnings|deprecation) \.\.\.`/i;
256
+
257
+ /**
258
+ * What a failed socket says went wrong. Node 20+ tries every address a host
259
+ * resolves to (happy eyeballs); when all of them fail it raises an
260
+ * AggregateError whose own message is EMPTY, with the reasons on `errors` and
261
+ * the code on `code`. Read as `e.message` alone that was "": the smoke test
262
+ * took it for success and crashed on the missing body ("Cannot read
263
+ * properties of undefined (reading 'slice')"), and a chat run failed with no
264
+ * reason at all.
265
+ */
266
+ function networkErrorText(err) {
267
+ if (!err) return 'unknown network error';
268
+ if (err.message) return err.message;
269
+ const inner = Array.isArray(err.errors)
270
+ ? [...new Set(err.errors.map((e) => e && e.message).filter(Boolean))].join('; ')
271
+ : '';
272
+ return inner || err.code || String(err) || 'unknown network error';
273
+ }
252
274
 
253
275
  /** CLI output with the known-harmless lines taken out. */
254
276
  function stripCliNoise(text) {
@@ -257,6 +279,7 @@ function stripCliNoise(text) {
257
279
 
258
280
  module.exports = {
259
281
  SESSION_DEFAULT_RE,
282
+ networkErrorText,
260
283
  BENIGN_CLI_OUTPUT,
261
284
  stripCliNoise,
262
285
  decodeConsoleOutput,
package/src/config.js CHANGED
@@ -3,6 +3,16 @@
3
3
  const fs = require('fs');
4
4
  const path = require('path');
5
5
 
6
+ // Windows refuses to replace or open a file another process holds open (the
7
+ // daemon and its `agn` children read daemon.yaml all the time). Such a refusal
8
+ // passes in milliseconds, so both sides wait a little and try again.
9
+ const BUSY_CODES = ['EPERM', 'EACCES', 'EBUSY'];
10
+ const BUSY_WAITS_MS = [10, 25, 50, 100, 200];
11
+
12
+ function pause(ms) {
13
+ try { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); } catch {}
14
+ }
15
+
6
16
  /**
7
17
  * Manages ~/.openagents/daemon.yaml — the agent/network configuration file.
8
18
  * Compatible with the Python SDK's daemon_config.py format.
@@ -19,14 +29,30 @@ class Config {
19
29
 
20
30
  // -- Read --
21
31
 
32
+ /**
33
+ * The config as it is on disk. A read that hits the file while it is held
34
+ * (Windows) or while a writer that could not replace it is rewriting it in
35
+ * place (empty for that moment) is tried again: read as "no agents", it made
36
+ * a probe started right after a save report "No agent named '<name>' on
37
+ * this device", and that result stood for an hour.
38
+ */
22
39
  load() {
23
- try {
24
- if (fs.existsSync(this.configFile)) {
40
+ for (let attempt = 0; ; attempt++) {
41
+ const last = attempt >= BUSY_WAITS_MS.length;
42
+ try {
43
+ if (!fs.existsSync(this.configFile)) break;
25
44
  const text = fs.readFileSync(this.configFile, 'utf-8');
26
- return parseYaml(text);
45
+ // An empty file is tried again only briefly: a writer's in-place
46
+ // rewrite is over within that, and a file that really is empty must
47
+ // not slow down every read.
48
+ if (text.trim() || last || attempt >= 2) return parseYaml(text);
49
+ } catch (err) {
50
+ if (last || !BUSY_CODES.includes(err.code)) {
51
+ console.error('Failed to load config:', err.message);
52
+ break;
53
+ }
27
54
  }
28
- } catch (err) {
29
- console.error('Failed to load config:', err.message);
55
+ pause(BUSY_WAITS_MS[attempt]);
30
56
  }
31
57
  return { version: 2, agents: [], networks: [] };
32
58
  }
@@ -51,19 +77,21 @@ class Config {
51
77
  * started right after a create read it empty and reported the new agent as
52
78
  * "Unknown agent type '<name>'", and a read-modify-write in that window
53
79
  * saves the empty list back. Windows can refuse the rename while a reader
54
- * holds the file open, so that case retries and then writes in place.
80
+ * holds the file open, so that case retries for a moment (the hold is a
81
+ * read, gone in milliseconds) and only then writes in place.
55
82
  */
56
83
  save(config) {
57
84
  fs.mkdirSync(this.configDir, { recursive: true });
58
85
  const text = serializeYaml(config);
59
86
  const tmp = `${this.configFile}.${process.pid}.tmp`;
60
87
  fs.writeFileSync(tmp, text, 'utf-8');
61
- for (let attempt = 0; attempt < 3; attempt++) {
88
+ for (let attempt = 0; attempt <= BUSY_WAITS_MS.length; attempt++) {
89
+ if (attempt > 0) pause(BUSY_WAITS_MS[attempt - 1]);
62
90
  try {
63
91
  fs.renameSync(tmp, this.configFile);
64
92
  return;
65
93
  } catch (err) {
66
- if (!['EPERM', 'EACCES', 'EBUSY'].includes(err.code)) {
94
+ if (!BUSY_CODES.includes(err.code)) {
67
95
  try { fs.unlinkSync(tmp); } catch {}
68
96
  throw err;
69
97
  }
package/src/daemon.js CHANGED
@@ -224,9 +224,19 @@ class Daemon {
224
224
  try {
225
225
  // By agent name, not type: the probe runs on this agent's own env, so a
226
226
  // signed-in agent is tested on its sign-in, not the type's saved key.
227
- const r = await this._runAgn(['probe', name, '--json']);
228
227
  let parsed = null;
229
- try { parsed = JSON.parse(r.stdout.trim()); } catch {}
228
+ let r;
229
+ for (let attempt = 0; attempt < 2; attempt++) {
230
+ r = await this._runAgn(['probe', name, '--json']);
231
+ parsed = null;
232
+ try { parsed = JSON.parse(r.stdout.trim()); } catch {}
233
+ // The child found no agent of that name while this daemon has one: it
234
+ // read daemon.yaml mid-save (Windows). Ask once more instead of
235
+ // keeping "No agent named '<name>' on this device" for an hour.
236
+ const unseen = parsed && parsed.code === 'unknown_type' && this.config.getAgent(name);
237
+ if (!unseen || attempt > 0) break;
238
+ await new Promise((resolve) => setTimeout(resolve, 500));
239
+ }
230
240
  if (!parsed || typeof parsed !== 'object') {
231
241
  // The probe process itself died before it could answer — a fault on
232
242
  // this device's OpenAgents install, not in the agent.
@@ -277,6 +287,24 @@ class Daemon {
277
287
  })();
278
288
  }
279
289
 
290
+ /**
291
+ * The connection test of an agent whose runtime was the wrong version ran
292
+ * before the repair (or at creation, while it was under way) and said
293
+ * "<version> is not supported"; nothing tested it again until the hourly
294
+ * sweep, so the device card kept that error for an agent that now worked.
295
+ */
296
+ _reprobeAfterRepair(agentType) {
297
+ const due = this.config.getAgents().filter((a) => (a.type || 'openclaw') === agentType
298
+ && this._probes[a.name] && this._probes[a.name].code === 'version_incompatible');
299
+ if (!due.length) return;
300
+ (async () => {
301
+ for (const a of due) {
302
+ try { await this._probeAgent(a.name); } catch {}
303
+ }
304
+ this._nodeHeartbeat();
305
+ })();
306
+ }
307
+
280
308
  /** Report a runtime install that failed while creating `name`, as its probe result. */
281
309
  _recordInstallFailure(name, type, error) {
282
310
  let install = null;
@@ -1984,7 +2012,10 @@ async _runNodeCommand(n, cmd) {
1984
2012
 
1985
2013
  if (typeof adapter.forgetRuntime === 'function') adapter.forgetRuntime();
1986
2014
  const next = adapter.preflight();
1987
- if (next && next.ok !== false) this._log(`${name}: supported ${agentType} runtime installed`);
2015
+ if (next && next.ok !== false) {
2016
+ this._log(`${name}: supported ${agentType} runtime installed`);
2017
+ this._reprobeAfterRepair(agentType);
2018
+ }
1988
2019
  return next;
1989
2020
  }
1990
2021
 
package/src/probe.js CHANGED
@@ -549,6 +549,13 @@ async function probeAgentType(connector, type, opts = {}) {
549
549
  const timeoutMs = opts.timeoutMs
550
550
  || (entry.probe && entry.probe.timeout_s ? entry.probe.timeout_s * 1000 : DEFAULT_TIMEOUT_MS);
551
551
  const env = stripForCliLogin(type, { ...getEnhancedEnv(), ...agentEnv }, connector.registry, opts.agentEnv);
552
+ // What the CLI needs set to answer headless at all, declared per agent
553
+ // (Gemini refuses to run in a folder it does not trust, and the probe runs
554
+ // in the home directory). The agent's own value, if any, stands.
555
+ const probeEnv = (entry.probe && entry.probe.env) || {};
556
+ for (const [name, value] of Object.entries(probeEnv)) {
557
+ if (env[name] == null) env[name] = String(value);
558
+ }
552
559
 
553
560
  const baseUrl = directBaseUrl(entry, agentEnv);
554
561
  const protocol = directProtocol(type, agentEnv);
@@ -608,7 +615,11 @@ async function probeAgentType(connector, type, opts = {}) {
608
615
  // same question directly: one round trip, and it says why.
609
616
  const unexplained = code === CODE.TIMEOUT || code === CODE.CLI_ERROR || code === CODE.EMPTY_RESPONSE;
610
617
  if (unexplained && canCallDirect) {
611
- const direct = await directApiVerdict(agentEnv, entry, model, baseUrl, protocol);
618
+ // `[1m]` is Claude Code's own 1M-context switch (`deepseek-v4-pro[1m]`),
619
+ // taken off before its requests go out; sent as part of the name, the
620
+ // relay would reject a model the agent actually runs on.
621
+ const wireModel = model ? String(model).replace(/\[1m\]$/i, '') : model;
622
+ const direct = await directApiVerdict(agentEnv, entry, wireModel, baseUrl, protocol);
612
623
  if (direct) return done(direct);
613
624
  }
614
625
  if (unexplained && staticVerdict) return done(staticVerdict);
package/src/utils.js CHANGED
@@ -22,6 +22,8 @@ const VENDOR_HOSTS = /(^|\.)(openai\.com|moonshot\.ai|deepseek\.com|anthropic\.c
22
22
  const MODEL_REJECTED =
23
23
  /model.{0,60}?(is not available|does not exist|not found|unknown model|invalid model|no such model|not supported)|model_not_found/is;
24
24
 
25
+ const { networkErrorText } = require('./adapters/utils');
26
+
25
27
  /** One HTTP request. Resolves { status, data } or { error }; never rejects. */
26
28
  function request(url, { method = 'POST', headers = {}, body = null, timeout = 15000 } = {}) {
27
29
  const https = require('https');
@@ -36,7 +38,7 @@ function request(url, { method = 'POST', headers = {}, body = null, timeout = 15
36
38
  res.on('data', (chunk) => { data += chunk; });
37
39
  res.on('end', () => resolve({ status: res.statusCode, data }));
38
40
  });
39
- req.on('error', (e) => resolve({ error: e.message }));
41
+ req.on('error', (e) => resolve({ error: networkErrorText(e) }));
40
42
  // Name the host and the deadline: a bare "Request timed out" on the
41
43
  // device card did not say whether the provider or the network was slow.
42
44
  req.on('timeout', () => { req.destroy(); resolve({ error: `Request to ${parsedUrl.host} timed out after ${Math.round(timeout / 1000)}s` }); });
@@ -94,7 +96,8 @@ const OUTPUT_LIMIT_REACHED = /max_tokens or model output limit was reached/i;
94
96
  /** Read one completion response into the result shape. */
95
97
  function completionResult(res, { isAnthropic, model }) {
96
98
  if (res.error) return { success: false, error: res.error };
97
- const { status, data } = res;
99
+ const status = res.status;
100
+ const data = String(res.data == null ? '' : res.data);
98
101
  if (status >= 400 && OUTPUT_LIMIT_REACHED.test(data || '')) {
99
102
  return { success: true, model: model || '?', response: '' };
100
103
  }