@openagents-org/agent-launcher 0.2.202 → 0.2.204

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.
@@ -21,6 +21,12 @@ const BaseAdapter = require('./base');
21
21
  const { whereBinary } = require('../paths');
22
22
  const { formatAttachmentsForPrompt, SESSION_DEFAULT_RE, generateSessionTitle } = require('./utils');
23
23
  const { buildClaudeSystemPrompt } = require('./workspace-prompt');
24
+ const {
25
+ isFailedRun,
26
+ failureDetail,
27
+ classifyGeminiFailure,
28
+ retriesWithoutResume,
29
+ } = require('./gemini-stream');
24
30
 
25
31
  const IS_WINDOWS = process.platform === 'win32';
26
32
 
@@ -316,12 +322,20 @@ class GeminiAdapter extends BaseAdapter {
316
322
  });
317
323
  this._channelProcesses[msgChannel] = proc;
318
324
 
325
+ // Read before any event can replace it: whether this run passed -r.
326
+ const resumed = attempt === 0 && Boolean(this._channelSessions[msgChannel]);
319
327
  const lastResponseText = [];
320
328
  let hasToolUseSinceLastText = false;
321
329
  let postedThinking = false;
322
330
  let stderrBuf = '';
323
331
  let lineBuffer = '';
324
332
  let _pendingLines = Promise.resolve();
333
+ // Where the CLI says a run failed: the final result event, and any
334
+ // error-severity events along the way. See gemini-stream.js.
335
+ let resultStatus = null;
336
+ let resultError = null;
337
+ const errorMessages = [];
338
+ let idleKilled = false;
325
339
 
326
340
  if (proc.stderr) {
327
341
  proc.stderr.on('data', (chunk) => { stderrBuf += chunk.toString('utf-8'); });
@@ -348,6 +362,7 @@ class GeminiAdapter extends BaseAdapter {
348
362
  }
349
363
  if (consecutiveTimeouts >= 20) {
350
364
  this._log(`Process idle for ${consecutiveTimeouts * 15}s, killing...`);
365
+ idleKilled = true;
351
366
  await this._stopProcess(proc);
352
367
  }
353
368
  }
@@ -394,15 +409,24 @@ class GeminiAdapter extends BaseAdapter {
394
409
  else inputPreview = JSON.stringify(inp).slice(0, 150);
395
410
  }
396
411
  await this.sendStatus(msgChannel, `${toolName} › ${inputPreview}`);
412
+ } else if (eventType === 'error') {
413
+ // A warning (loop detected) does not fail the run; an error does.
414
+ if (event.severity === 'error' && event.message) {
415
+ errorMessages.push(String(event.message));
416
+ } else if (event.message) {
417
+ this._log(`CLI warning: ${this._redact(event.message)}`);
418
+ }
397
419
  } else if (eventType === 'result') {
398
- if (event.session_id) {
399
- this._channelSessions[msgChannel] = event.session_id;
400
- this._saveSessions();
401
- }
420
+ if (event.session_id) {
421
+ this._channelSessions[msgChannel] = event.session_id;
422
+ this._saveSessions();
423
+ }
424
+ resultStatus = event.status || null;
425
+ if (event.status === 'error') resultError = event.error || null;
402
426
  }
403
427
  };
404
428
 
405
- proc.on('exit', async (code) => {
429
+ proc.on('exit', async (code, signal) => {
406
430
  if (timeoutTimer) clearInterval(timeoutTimer);
407
431
 
408
432
  try { await _pendingLines; } catch {}
@@ -415,30 +439,73 @@ class GeminiAdapter extends BaseAdapter {
415
439
  delete this._channelProcesses[msgChannel];
416
440
 
417
441
  if (code !== 0) {
418
- this._log(`CLI exited with code ${code}`);
419
- if (stderrBuf.trim()) {
420
- this._log(`stderr: ${stderrBuf.trim().slice(0, 500)}`);
442
+ this._log(`CLI exited with ${signal ? `signal ${signal}` : `code ${code}`}`);
443
+ // Redact the whole buffer before cutting it; keep the end, where the failure is.
444
+ const stderrText = this._redact(stderrBuf).trim();
445
+ if (stderrText) this._log(`stderr: ${stderrText.slice(-500)}`);
446
+ }
447
+
448
+ // stream-json deltas are fragments of one message: join with no separator.
449
+ const fullResponse = lastResponseText.join('').trim();
450
+
451
+ // Stopped by the user: their exit is neither a failure to report
452
+ // nor a reason to retry from a fresh session, and `_handleUserStop`
453
+ // has already told the channel. The base clears the flag when the
454
+ // channel's next turn starts.
455
+ if (this._stoppingChannels.has(msgChannel)) {
456
+ resolve(false);
457
+ return;
458
+ }
459
+
460
+ if (idleKilled) {
461
+ if (fullResponse) {
462
+ try { await this.sendResponse(msgChannel, fullResponse); } catch {}
421
463
  }
464
+ const detail = failureDetail({
465
+ stderr: stderrBuf, error: resultError, errorMessages, secrets: this._knownSecrets(),
466
+ });
467
+ try {
468
+ await this.sendError(
469
+ msgChannel,
470
+ 'Gemini CLI produced no output for 5 minutes and was stopped.' +
471
+ (detail ? `\n\nDetails: ${detail}` : ''),
472
+ );
473
+ } catch {}
474
+ resolve(false);
475
+ return;
422
476
  }
423
477
 
424
- if (lastResponseText.length > 0) {
425
- const fullResponse = lastResponseText.join('').trim(); // Gemini deltas are partial strings, no newline needed between them usually, but wait, delta:true means it appends. If it's multiple blocks, we should join with empty string? Let's check `delta: true`.
426
- // Actually if delta: true, they are chunks. We pushed them to array. `lastResponseText.join('')` is correct.
478
+ if (!isFailedRun({ code, resultStatus, errorMessages })) {
427
479
  if (fullResponse) {
428
480
  try { await this.sendResponse(msgChannel, fullResponse); } catch {}
481
+ } else if (!postedThinking) {
482
+ try { await this.sendResponse(msgChannel, 'No response generated. Please try again.'); } catch {}
429
483
  }
430
484
  resolve(false);
431
- } else if (code !== 0 && this._channelSessions[msgChannel]) {
432
- this._log(`Stale session detected for ${msgChannel}, clearing and retrying without resume`);
485
+ return;
486
+ }
487
+
488
+ const failure = classifyGeminiFailure({
489
+ code, stderr: stderrBuf, error: resultError, errorMessages, secrets: this._knownSecrets(),
490
+ });
491
+ this._log(`Run failed (${failure.kind})`, 'error');
492
+
493
+ // Only a resume that failed, or a failure nothing explains, is worth
494
+ // a fresh session. Retrying anything else repeats the same wait for
495
+ // the same error and throws the channel's history away.
496
+ if (!fullResponse && resumed && retriesWithoutResume(failure.kind)) {
497
+ this._log(`Could not resume the session for ${msgChannel}, clearing and retrying without resume`);
433
498
  delete this._channelSessions[msgChannel];
434
499
  this._saveSessions();
435
500
  resolve(true);
436
- } else {
437
- if (!postedThinking) {
438
- try { await this.sendResponse(msgChannel, 'No response generated. Please try again.'); } catch {}
439
- }
440
- resolve(false);
501
+ return;
502
+ }
503
+
504
+ if (fullResponse) {
505
+ try { await this.sendResponse(msgChannel, fullResponse); } catch {}
441
506
  }
507
+ try { await this.sendError(msgChannel, failure.message); } catch {}
508
+ resolve(false);
442
509
  });
443
510
 
444
511
  proc.on('error', (err) => {
@@ -458,7 +525,7 @@ class GeminiAdapter extends BaseAdapter {
458
525
  });
459
526
  } catch (e) {
460
527
  this._log(`Error handling message: ${e.message}`);
461
- await this.sendError(msgChannel, `Error processing message: ${e.message}`);
528
+ await this.sendError(msgChannel, `Error processing message: ${this._redact(e.message)}`);
462
529
  break;
463
530
  }
464
531
  if (!_shouldRetry) break;
@@ -37,6 +37,8 @@ const { buildOpenclawSystemPrompt } = require('./workspace-prompt');
37
37
  const { isRecapEligible } = require('./decision-log');
38
38
  const { REASON } = require('./health-status');
39
39
  const { whichBinary, whereBinary } = require('../paths');
40
+ const { classifyRunFailure, classifiedError, isClassifiedError } = require('./run-failure');
41
+ const { maskSecretValues } = require('./utils');
40
42
 
41
43
  const IS_WINDOWS = process.platform === 'win32';
42
44
  const HERMES_INSTALL_HINT = IS_WINDOWS
@@ -81,6 +83,31 @@ const PREFILL_CLOSING = [
81
83
  'The text above is standing context from the OpenAgents workspace, not a message to answer. The conversation follows.',
82
84
  ];
83
85
 
86
+ // What a failed `hermes chat` run should tell the channel, per cause. The
87
+ // classifier appends the CLI's own words, redacted; see run-failure.js.
88
+ const HERMES_GUIDANCE = {
89
+ auth:
90
+ 'Hermes could not authenticate. Set LLM_API_KEY (with LLM_BASE_URL and ' +
91
+ 'LLM_MODEL) for this agent, or run `hermes setup` on the device to sign in ' +
92
+ 'to a provider.',
93
+ quota:
94
+ "The provider is rate-limiting this agent or its quota is exhausted. Wait " +
95
+ 'and try again, or use a key with more quota.',
96
+ network:
97
+ 'Hermes could not reach its provider from this device. Check the device\'s ' +
98
+ 'network, or its proxy, and LLM_BASE_URL if a custom endpoint is set.',
99
+ model:
100
+ 'The provider rejected the requested model. Pick another model for this ' +
101
+ 'agent, or clear LLM_MODEL to use the profile default.',
102
+ provider:
103
+ 'Hermes has no inference provider configured. Set LLM_API_KEY (with ' +
104
+ 'LLM_BASE_URL and LLM_MODEL) for this agent, or run `hermes setup` on the ' +
105
+ 'device to choose one.',
106
+ config:
107
+ "Hermes's own configuration is invalid — check the profile's config under " +
108
+ 'HERMES_HOME, or run `hermes setup` again.',
109
+ };
110
+
84
111
  class HermesAdapter extends BaseAdapter {
85
112
  /**
86
113
  * @param {object} opts - BaseAdapter opts plus:
@@ -706,14 +733,39 @@ class HermesAdapter extends BaseAdapter {
706
733
  // The turn did not finish, and stdout is Hermes's own account of why,
707
734
  // after whatever answer it had reached. Worth more to the user than
708
735
  // an exit code.
709
- this._log(`Hermes turn did not finish (code=${run.exitCode})`);
710
- await this.sendError(msgChannel, run.text);
736
+ // It is prose, so the shape rules of redaction stay off it; what is
737
+ // masked is this agent's own secrets, which a provider error quoted
738
+ // there would echo.
739
+ // Masked before it is cut, so a secret straddling the cut cannot
740
+ // survive as a fragment; the reason is at the end, so keep the tail.
741
+ this._log(`Hermes turn did not finish (code=${run.exitCode})`, 'error');
742
+ const said = maskSecretValues(run.text, this._knownSecrets());
743
+ await this.sendError(msgChannel, said.length > 2000 ? `…${said.slice(-2000)}` : said);
711
744
  } else {
712
- throw new Error(`hermes exited with code ${run.exitCode}: ${run.detail.slice(0, 600)}`);
745
+ // Nothing on stdout, so the reason is whatever Hermes wrote to stderr:
746
+ // in -Q mode that is where it reports a backend error that produced
747
+ // no reply, and a credential check that failed before the turn began.
748
+ // stdout is never classified — it is the model's reply, and a reply
749
+ // that mentions a sign-in page is not an auth failure.
750
+ const failure = classifyRunFailure({
751
+ code: run.exitCode,
752
+ stderr: run.detail,
753
+ cli: 'Hermes',
754
+ guidance: HERMES_GUIDANCE,
755
+ skip: ['session'],
756
+ secrets: this._knownSecrets(),
757
+ });
758
+ this._log(`Hermes run failed (${failure.kind}, code=${run.exitCode})`, 'error');
759
+ throw classifiedError(failure.message);
713
760
  }
714
761
  } catch (e) {
715
762
  this._log(`Hermes adapter error: ${e.message}`);
716
- await this.sendError(msgChannel, `Error processing message: ${e.message}`);
763
+ // A classified failure is already the sentence the user should read;
764
+ // anything else is an adapter-side error and says so.
765
+ await this.sendError(
766
+ msgChannel,
767
+ isClassifiedError(e) ? e.message : `Error processing message: ${this._redact(e.message)}`,
768
+ );
717
769
  }
718
770
  }
719
771
 
@@ -100,6 +100,8 @@ class KimiAdapter extends LlmDirectAdapter {
100
100
  ...opts,
101
101
  adapterLabel: 'Kimi',
102
102
  modelEnvVar: 'KIMI_MODEL',
103
+ apiKeyEnvVar: 'KIMI_API_KEY',
104
+ baseUrlEnvVar: 'KIMI_BASE_URL',
103
105
  suppressConfigLog: true,
104
106
  });
105
107
 
@@ -13,11 +13,41 @@ const https = require('https');
13
13
  const http = require('http');
14
14
 
15
15
  const BaseAdapter = require('./base');
16
+ const { classifyRunFailure, classifiedError, isClassifiedError } = require('./run-failure');
16
17
  const { formatAttachmentsForPrompt } = require('./utils');
17
18
  const { buildOpenclawSystemPrompt } = require('./workspace-prompt');
18
19
 
19
20
  const MAX_HISTORY = 50;
20
21
 
22
+ /**
23
+ * What a failed API call should tell the channel, per cause. `label` is the
24
+ * adapter's own name (NanoClaw, Cursor, …) so the message names the agent the
25
+ * user configured, not the base class. `keyVar` / `urlVar` are the settings
26
+ * that adapter actually reads — a Kimi agent is configured through KIMI_API_KEY,
27
+ * and telling its user to check OPENAI_API_KEY sends them looking for a
28
+ * setting they never made. The classifier appends what the API said,
29
+ * redacted; see run-failure.js.
30
+ */
31
+ function directGuidance(label, keyVar = 'OPENAI_API_KEY', urlVar = 'OPENAI_BASE_URL') {
32
+ return {
33
+ auth:
34
+ `${label} could not authenticate with the model endpoint. Check ` +
35
+ `${keyVar} for this agent, and that the key belongs to the endpoint ` +
36
+ `in ${urlVar}.`,
37
+ quota:
38
+ 'The endpoint is rate-limiting this agent, or its quota is exhausted. ' +
39
+ 'Wait and try again, or use a key with more quota.',
40
+ network:
41
+ `${label} could not reach the model endpoint from this device. Check ` +
42
+ `the device's network, or its proxy, and ${urlVar}.`,
43
+ model:
44
+ 'The endpoint rejected the requested model. Check the model configured ' +
45
+ 'for this agent — a relay often serves different model names than the ' +
46
+ 'provider it fronts.',
47
+ timeout: `${label} gave up waiting for the model endpoint to answer.`,
48
+ };
49
+ }
50
+
21
51
  class LlmDirectAdapter extends BaseAdapter {
22
52
  /**
23
53
  * @param {object} opts - BaseAdapter opts plus:
@@ -32,6 +62,9 @@ class LlmDirectAdapter extends BaseAdapter {
32
62
  this._usesPinnedContext = true;
33
63
  this._adapterLabel = opts.adapterLabel || 'LLM';
34
64
  this._modelEnvVar = opts.modelEnvVar || '';
65
+ // The settings a failure message should point at; see directGuidance.
66
+ this._apiKeyEnvVar = opts.apiKeyEnvVar || 'OPENAI_API_KEY';
67
+ this._baseUrlEnvVar = opts.baseUrlEnvVar || 'OPENAI_BASE_URL';
35
68
 
36
69
  const env = this.agentEnv || process.env;
37
70
  this._apiKey = env.OPENAI_API_KEY || '';
@@ -138,7 +171,10 @@ class LlmDirectAdapter extends BaseAdapter {
138
171
  }
139
172
  } catch (e) {
140
173
  this._log(`Error handling message: ${e.message}`);
141
- await this.sendError(msgChannel, `Error processing message: ${e.message}`);
174
+ await this.sendError(
175
+ msgChannel,
176
+ isClassifiedError(e) ? e.message : `Error processing message: ${this._redact(e.message)}`,
177
+ );
142
178
  }
143
179
  }
144
180
 
@@ -179,7 +215,20 @@ class LlmDirectAdapter extends BaseAdapter {
179
215
  res.on('data', (c) => { body += c; });
180
216
  res.on('end', () => {
181
217
  cleanup();
182
- reject(new Error(`LLM API returned ${res.statusCode}: ${body.slice(0, 300)}`));
218
+ // The body is the provider's own error, and providers put the key
219
+ // fragment they rejected in it — classify on the raw text, quote
220
+ // only the redacted one.
221
+ const failure = classifyRunFailure({
222
+ code: res.statusCode,
223
+ codeLabel: `HTTP ${res.statusCode}`,
224
+ error: `HTTP status ${res.statusCode} ${body}`,
225
+ cli: this._adapterLabel,
226
+ guidance: directGuidance(this._adapterLabel, this._apiKeyEnvVar, this._baseUrlEnvVar),
227
+ skip: ['session'],
228
+ secrets: this._knownSecrets(),
229
+ });
230
+ this._log(`API call failed (${failure.kind}, HTTP ${res.statusCode})`, 'error');
231
+ reject(classifiedError(failure.message));
183
232
  });
184
233
  return;
185
234
  }
@@ -220,7 +269,23 @@ class LlmDirectAdapter extends BaseAdapter {
220
269
  this._activeRequests.add(req);
221
270
  req.on('error', (err) => {
222
271
  this._activeRequests.delete(req);
223
- reject(err);
272
+ // A stop destroys the request on purpose — that is not a failure to
273
+ // explain, and `_handleUserStop` has already told the channel.
274
+ if (this._stoppingChannels.has(channel)) {
275
+ reject(err);
276
+ return;
277
+ }
278
+ const failure = classifyRunFailure({
279
+ code: null,
280
+ codeLabel: 'connection failed',
281
+ error: err && err.message,
282
+ cli: this._adapterLabel,
283
+ guidance: directGuidance(this._adapterLabel, this._apiKeyEnvVar, this._baseUrlEnvVar),
284
+ skip: ['session'],
285
+ secrets: this._knownSecrets(),
286
+ });
287
+ this._log(`API call failed (${failure.kind}, no response)`, 'error');
288
+ reject(classifiedError(failure.message));
224
289
  });
225
290
  req.on('timeout', () => {
226
291
  req.destroy(new Error('LLM API request timed out'));