@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,11 +21,30 @@ const { execSync } = require('child_process');
21
21
  const { spawn } = require('../wsl');
22
22
 
23
23
  const BaseAdapter = require('./base');
24
+ const { classifyRunFailure, classifiedError, isClassifiedError } = require('./run-failure');
24
25
  const { formatAttachmentsForPrompt } = require('./utils');
25
26
  const { buildOpenclawSkillMd, buildOpenclawSystemPrompt, workspaceSkillName } = require('./workspace-prompt');
26
27
  const { getRuntimePrefix, whereBinary } = require('../paths');
27
28
 
28
29
  const IS_WINDOWS = process.platform === 'win32';
30
+ // What a failed `openclaw agent` run should tell the channel, per cause. The
31
+ // classifier appends the CLI's own words, redacted; see run-failure.js.
32
+ const OPENCLAW_GUIDANCE = {
33
+ auth:
34
+ 'OpenClaw could not authenticate with its model provider. Set LLM_API_KEY ' +
35
+ '(with LLM_BASE_URL and LLM_MODEL) for this agent, or sign in with ' +
36
+ '`openclaw auth` on the device.',
37
+ quota:
38
+ 'The provider is rate-limiting this agent, or its quota is exhausted. Wait ' +
39
+ 'and try again, or use a key with more quota.',
40
+ network:
41
+ "OpenClaw could not reach its provider from this device. Check the device's " +
42
+ 'network, or its proxy, and LLM_BASE_URL if a custom endpoint is set.',
43
+ model:
44
+ 'The provider rejected the requested model. Check LLM_MODEL for this agent.',
45
+ timeout: 'OpenClaw timed out before producing a response.',
46
+ };
47
+
29
48
  const OPENCLAW_STATE_DIR = path.join(
30
49
  IS_WINDOWS ? (process.env.USERPROFILE || '') : (process.env.HOME || ''),
31
50
  '.openclaw'
@@ -66,6 +85,23 @@ function retireOwnLegacyAuthProfiles(knownKeys) {
66
85
  }
67
86
  }
68
87
 
88
+ /**
89
+ * Whether OpenClaw refused to start because local state from an older release
90
+ * still needs its own migration ("Legacy workspace setup state requires
91
+ * migration …; run openclaw doctor --fix", "requires legacy credential
92
+ * migration; run openclaw doctor --fix").
93
+ *
94
+ * Every upgrade across a storage change hits this, and the user's only way out
95
+ * was a terminal. The adapter runs that same Doctor repair itself and retries.
96
+ */
97
+ function needsDoctorMigration(message) {
98
+ const text = String(message || '');
99
+ return /requires[^\n]*\bmigration\b/i.test(text) && /openclaw doctor --fix/i.test(text);
100
+ }
101
+
102
+ /** Budget for one `openclaw doctor --fix` run. */
103
+ const DOCTOR_REPAIR_TIMEOUT_MS = 120000;
104
+
69
105
  class OpenClawAdapter extends BaseAdapter {
70
106
  /**
71
107
  * @param {object} opts - BaseAdapter opts plus:
@@ -281,7 +317,7 @@ class OpenClawAdapter extends BaseAdapter {
281
317
  await this.sendStatus(msgChannel, 'thinking...');
282
318
 
283
319
  try {
284
- const responseText = await this._runCliAgent(content, msgChannel);
320
+ const responseText = await this._runCliAgentWithMigration(content, msgChannel);
285
321
  if (this._stoppingChannels.has(msgChannel)) return;
286
322
 
287
323
  if (responseText) {
@@ -291,7 +327,10 @@ class OpenClawAdapter extends BaseAdapter {
291
327
  }
292
328
  } catch (e) {
293
329
  this._log(`Error handling message: ${e.message}`);
294
- await this.sendError(msgChannel, `Error processing message: ${e.message}`);
330
+ await this.sendError(
331
+ msgChannel,
332
+ isClassifiedError(e) ? e.message : `Error processing message: ${this._redact(e.message)}`,
333
+ );
295
334
  }
296
335
  }
297
336
 
@@ -299,6 +338,101 @@ class OpenClawAdapter extends BaseAdapter {
299
338
  // CLI mode (openclaw agent --local)
300
339
  // ------------------------------------------------------------------
301
340
 
341
+ /**
342
+ * Run the turn; when OpenClaw refuses to start over an unmigrated state
343
+ * store, run its Doctor repair once and retry. Doctor archives what it
344
+ * migrates rather than deleting it.
345
+ */
346
+ async _runCliAgentWithMigration(userMessage, channel) {
347
+ try {
348
+ return await this._runCliAgent(userMessage, channel);
349
+ } catch (e) {
350
+ // At most one repair per turn; a repair that failed is not retried on
351
+ // every later message.
352
+ if (!needsDoctorMigration(e && e.message) || this._doctorRepairFailed) throw e;
353
+ this._log('OpenClaw needs a state migration — running openclaw doctor --fix --non-interactive');
354
+ await this.sendStatus(channel, 'Migrating OpenClaw local data...').catch(() => {});
355
+ const repair = await this._runDoctorRepair();
356
+ this._log(`Doctor repair ${repair.ok ? 'finished' : `failed: ${repair.detail}`}`);
357
+ if (!repair.ok) {
358
+ this._doctorRepairFailed = true;
359
+ throw e;
360
+ }
361
+ return this._runCliAgent(userMessage, channel);
362
+ }
363
+ }
364
+
365
+ /** `openclaw doctor --fix --non-interactive`, resolved to {ok, detail}. */
366
+ _runDoctorRepair() {
367
+ return new Promise((resolve) => {
368
+ const binary = this._openclawBinary || this._findOpenclawBinary();
369
+ if (!binary) { resolve({ ok: false, detail: 'OpenClaw binary not found' }); return; }
370
+ const { spawnBin, spawnArgs } = this._spawnTarget(binary, ['doctor', '--fix', '--non-interactive']);
371
+ let tail = '';
372
+ const keepTail = (d) => { tail = (tail + d).slice(-300); };
373
+ let proc;
374
+ try {
375
+ proc = spawn(spawnBin, spawnArgs, {
376
+ stdio: ['ignore', 'pipe', 'pipe'],
377
+ env: this._spawnEnv(),
378
+ cwd: this.workingDir || process.env.HOME || '/',
379
+ timeout: DOCTOR_REPAIR_TIMEOUT_MS,
380
+ windowsHide: true,
381
+ });
382
+ } catch (err) {
383
+ resolve({ ok: false, detail: err.message });
384
+ return;
385
+ }
386
+ proc.stdout.on('data', keepTail);
387
+ proc.stderr.on('data', keepTail);
388
+ proc.on('error', (err) => resolve({ ok: false, detail: err.message }));
389
+ proc.on('exit', (code) => resolve({ ok: code === 0, detail: `exit ${code}: ${tail.trim()}` }));
390
+ });
391
+ }
392
+
393
+ /** The child environment for an `openclaw` run. */
394
+ _spawnEnv() {
395
+ const spawnEnv = { ...(this.agentEnv || process.env) };
396
+ if (IS_WINDOWS) {
397
+ const nodeBinDir = path.dirname(process.execPath);
398
+ const npmBin = path.join(process.env.APPDATA || '', 'npm');
399
+ const portableDir = path.join(os.homedir(), '.openagents', 'nodejs');
400
+ const runtimeBin = path.join(getRuntimePrefix('openclaw'), 'node_modules', '.bin');
401
+ for (const p of [runtimeBin, nodeBinDir, npmBin, portableDir]) {
402
+ if (p && !(spawnEnv.PATH || '').includes(p)) {
403
+ spawnEnv.PATH = p + path.delimiter + (spawnEnv.PATH || '');
404
+ }
405
+ }
406
+ }
407
+ return spawnEnv;
408
+ }
409
+
410
+ /**
411
+ * How to start `openclaw <args>`: always node + openclaw.mjs directly (no
412
+ * shims, no cmd.exe, cross-platform). This avoids Windows .cmd shim issues
413
+ * and Unicode path encoding problems.
414
+ */
415
+ _spawnTarget(binary, args) {
416
+ const portableDir = path.join(os.homedir(), '.openagents', 'nodejs');
417
+ // Unified path first (symlink on Unix), then legacy bin/ fallback, then system node
418
+ const nodeUnified = path.join(portableDir, IS_WINDOWS ? 'node.exe' : 'node');
419
+ let nodeBin = fs.existsSync(nodeUnified) ? nodeUnified : path.join(portableDir, 'bin', 'node');
420
+ if (!fs.existsSync(nodeBin)) nodeBin = whereBinary('node') || 'node';
421
+
422
+ // binary from _findOpenclawBinary() is already resolved to .mjs when possible
423
+ if (binary && binary.endsWith('.mjs')) {
424
+ // Direct node + .mjs invocation (works for managed, legacy, AND global installs)
425
+ return { spawnBin: nodeBin, spawnArgs: [binary, ...args] };
426
+ }
427
+ // Check managed locations explicitly
428
+ const runtimeMjs = path.join(getRuntimePrefix('openclaw'), 'node_modules', 'openclaw', 'openclaw.mjs');
429
+ const legacyMjs = path.join(portableDir, 'node_modules', 'openclaw', 'openclaw.mjs');
430
+ const openclawMjs = fs.existsSync(runtimeMjs) ? runtimeMjs : (fs.existsSync(legacyMjs) ? legacyMjs : null);
431
+ if (openclawMjs) return { spawnBin: nodeBin, spawnArgs: [openclawMjs, ...args] };
432
+ // Last resort: spawn binary directly with shell (handles .cmd on Windows)
433
+ return { spawnBin: binary, spawnArgs: args };
434
+ }
435
+
302
436
  _runCliAgent(userMessage, channel) {
303
437
  return new Promise((resolve, reject) => {
304
438
  // Stopped while this turn was being prepared: start nothing (no tokens).
@@ -333,18 +467,7 @@ class OpenClawAdapter extends BaseAdapter {
333
467
 
334
468
  this._log(`CLI: ${binary} ${args.slice(0, 5).join(' ')} ...`);
335
469
 
336
- const spawnEnv = { ...(this.agentEnv || process.env) };
337
- if (IS_WINDOWS) {
338
- const nodeBinDir = path.dirname(process.execPath);
339
- const npmBin = path.join(process.env.APPDATA || '', 'npm');
340
- const portableDir2 = path.join(os.homedir(), '.openagents', 'nodejs');
341
- const runtimeBin = path.join(getRuntimePrefix('openclaw'), 'node_modules', '.bin');
342
- for (const p of [runtimeBin, nodeBinDir, npmBin, portableDir2]) {
343
- if (p && !(spawnEnv.PATH || '').includes(p)) {
344
- spawnEnv.PATH = p + path.delimiter + (spawnEnv.PATH || '');
345
- }
346
- }
347
- }
470
+ const spawnEnv = this._spawnEnv();
348
471
 
349
472
  // Tool name → human-readable status
350
473
  const toolLabels = {
@@ -382,34 +505,7 @@ class OpenClawAdapter extends BaseAdapter {
382
505
  const stderrFd = fs.openSync(stderrFile, 'w');
383
506
  this._log('Spawn: stderr → ' + stderrFile);
384
507
 
385
- // Always spawn node + openclaw.mjs directly (no shims, no cmd.exe, cross-platform)
386
- // This avoids Windows .cmd shim issues and Unicode path encoding problems.
387
- const portableDir = path.join(os.homedir(), '.openagents', 'nodejs');
388
- // Unified path first (symlink on Unix), then legacy bin/ fallback, then system node
389
- const nodeUnified = path.join(portableDir, IS_WINDOWS ? 'node.exe' : 'node');
390
- let nodeBin = fs.existsSync(nodeUnified) ? nodeUnified : path.join(portableDir, 'bin', 'node');
391
- if (!fs.existsSync(nodeBin)) nodeBin = whereBinary('node') || 'node';
392
-
393
- // binary from _findOpenclawBinary() is already resolved to .mjs when possible
394
- let spawnBin, spawnArgs;
395
- if (binary && binary.endsWith('.mjs')) {
396
- // Direct node + .mjs invocation (works for managed, legacy, AND global installs)
397
- spawnBin = nodeBin;
398
- spawnArgs = [binary, ...args];
399
- } else {
400
- // Check managed locations explicitly
401
- const runtimeMjs = path.join(getRuntimePrefix('openclaw'), 'node_modules', 'openclaw', 'openclaw.mjs');
402
- const legacyMjs = path.join(portableDir, 'node_modules', 'openclaw', 'openclaw.mjs');
403
- const openclawMjs = fs.existsSync(runtimeMjs) ? runtimeMjs : (fs.existsSync(legacyMjs) ? legacyMjs : null);
404
- if (openclawMjs) {
405
- spawnBin = nodeBin;
406
- spawnArgs = [openclawMjs, ...args];
407
- } else {
408
- // Last resort: spawn binary directly with shell (handles .cmd on Windows)
409
- spawnBin = binary;
410
- spawnArgs = args;
411
- }
412
- }
508
+ const { spawnBin, spawnArgs } = this._spawnTarget(binary, args);
413
509
  const proc = spawn(spawnBin, spawnArgs, {
414
510
  stdio: ['ignore', 'pipe', stderrFd],
415
511
  env: spawnEnv,
@@ -457,7 +553,10 @@ class OpenClawAdapter extends BaseAdapter {
457
553
  closeFd();
458
554
  try { fs.unlinkSync(stderrFile); } catch {}
459
555
  try { proc.kill(); } catch {}
460
- reject(new Error('CLI timed out after 600 seconds'));
556
+ reject(classifiedError(
557
+ 'OpenClaw ran for 10 minutes without finishing and was stopped. Send the '
558
+ + 'request again, or break a long task into smaller steps.',
559
+ ));
461
560
  }, 600000);
462
561
 
463
562
  proc.on('error', (err) => {
@@ -503,7 +602,24 @@ class OpenClawAdapter extends BaseAdapter {
503
602
  return;
504
603
  }
505
604
  if (code !== 0) {
506
- reject(new Error(`CLI exited ${code}: ${allOutput.slice(-300)}`));
605
+ // --log-level trace fills stderr with diagnostics, so quote the lines
606
+ // that say something about the failure rather than the last 300
607
+ // characters of the trace — and strip secrets from what is quoted.
608
+ // Only OpenClaw's own words are read for the cause: its trace, and
609
+ // the error object a failed --json run prints. The reply is the
610
+ // model's, and a reply that mentions a sign-in page or a
611
+ // settings.json is not an auth or a config failure.
612
+ const failure = classifyRunFailure({
613
+ code,
614
+ stderr: OpenClawAdapter._traceOnly(stderrContent),
615
+ error: OpenClawAdapter._cliError(output),
616
+ cli: 'OpenClaw',
617
+ guidance: OPENCLAW_GUIDANCE,
618
+ skip: ['session'],
619
+ secrets: this._knownSecrets(),
620
+ });
621
+ this._log(`Run failed (${failure.kind}, exit ${code})`, 'error');
622
+ reject(classifiedError(failure.message));
507
623
  return;
508
624
  }
509
625
  this._parseCliOutput(allOutput, resolve);
@@ -530,6 +646,48 @@ class OpenClawAdapter extends BaseAdapter {
530
646
  } catch {}
531
647
  }
532
648
 
649
+ /**
650
+ * stderr without the `{"payloads": …}` reply --json writes into it: what is
651
+ * left is OpenClaw's trace.
652
+ */
653
+ static _traceOnly(stderr) {
654
+ const text = String(stderr || '');
655
+ const start = text.search(/\{\s*"payloads"/);
656
+ if (start < 0) return text;
657
+ // Braces inside JSON strings (the reply text) are not structure: skip
658
+ // string contents, honoring backslash escapes.
659
+ let depth = 0;
660
+ let end = text.length;
661
+ let inString = false;
662
+ for (let i = start; i < text.length; i++) {
663
+ const ch = text[i];
664
+ if (inString) {
665
+ if (ch === '\\') i++;
666
+ else if (ch === '"') inString = false;
667
+ } else if (ch === '"') inString = true;
668
+ else if (ch === '{') depth++;
669
+ else if (ch === '}' && --depth === 0) { end = i + 1; break; }
670
+ }
671
+ return text.slice(0, start) + text.slice(end);
672
+ }
673
+
674
+ /**
675
+ * The error a failed `--json` run reports on stdout, as
676
+ * `{"ok":false,"error":{"type","message"}}` (openclaw 2026.9.8), or null.
677
+ * Older releases print nothing there and leave the reason in the trace.
678
+ */
679
+ static _cliError(stdout) {
680
+ const text = String(stdout || '').trim();
681
+ for (const candidate of [text, ...text.split('\n').map((l) => l.trim())]) {
682
+ if (!candidate.startsWith('{')) continue;
683
+ try {
684
+ const parsed = JSON.parse(candidate);
685
+ if (parsed && parsed.ok === false && parsed.error) return parsed.error;
686
+ } catch {}
687
+ }
688
+ return null;
689
+ }
690
+
533
691
  _parseCliOutput(output, resolve) {
534
692
  const text = output.trim();
535
693
  if (!text) { resolve(''); return; }
@@ -703,3 +861,4 @@ class OpenClawAdapter extends BaseAdapter {
703
861
 
704
862
  module.exports = OpenClawAdapter;
705
863
  module.exports.retireOwnLegacyAuthProfiles = retireOwnLegacyAuthProfiles;
864
+ module.exports.needsDoctorMigration = needsDoctorMigration;
@@ -0,0 +1,224 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * One place for "this CLI run failed — why, and what does the channel get
5
+ * told". Pure: no process, network or adapter state, so every branch is
6
+ * unit-testable (see test/run-failure.test.js).
7
+ *
8
+ * Every CLI adapter hit the same dead end — a failed run reached the user as
9
+ * "No response generated. Please try again.", with the real reason (bad key,
10
+ * blocked network, exhausted quota) only in the daemon log. Each adapter that
11
+ * fixed it grew its own copy of the same regexes and the same
12
+ * "guidance + Details:" shape. This module is that copy, once.
13
+ *
14
+ * Two things stay per-adapter, and are passed in:
15
+ * - `cli`, the name to use in the fallback wording;
16
+ * - `guidance`, the sentence to lead with per kind, because what a user
17
+ * should DO about a bad key differs per CLI (env var, `x login`, the
18
+ * launcher). Kinds without a sentence fall back to generic wording.
19
+ *
20
+ * What the CLI actually said is always appended, redacted, as "Details: …" —
21
+ * that is the part that makes a report actionable when the guidance guessed
22
+ * wrong.
23
+ */
24
+
25
+ const { redactSecrets } = require('./utils');
26
+
27
+ /** How much of the CLI's own words to quote back. */
28
+ const DETAIL_CAP = 300;
29
+
30
+ // A config file named next to a word that says it could not be read as one.
31
+ // The file name alone is not a failure: CLIs print the path of the settings
32
+ // they loaded on every run, and "settings.json not found" is a missing file,
33
+ // not a broken one.
34
+ const CONFIG_FILE = '(?:settings|providers|config)\\.(?:json|ya?ml|toml)';
35
+ const UNREADABLE = '(?:invalid|malformed|corrupt|syntax error|unexpected token|(?:could not|cannot|failed to|unable to) parse)';
36
+
37
+ /**
38
+ * Failure kinds, in the order they are tested. Earlier wins, so the more
39
+ * specific causes come first: "authentication failed or timed out" is an auth
40
+ * failure, not a timeout.
41
+ *
42
+ * Each pattern wants the failure itself, not a word that is merely near one —
43
+ * this text is whatever a CLI printed, and "sign-in page rendered" or
44
+ * "path is forbidden by the sandbox" is a tool talking about its work. So
45
+ * "sign in" counts only as a request or a requirement, and "forbidden" only
46
+ * as the HTTP status or the error itself.
47
+ */
48
+ const PATTERNS = [
49
+ ['session', /Error resuming session|Invalid session identifier|No previous sessions found/i],
50
+ ['auth', /authentication (?:required|failed)|not authenticated|no valid credentials|please (?:sign|log) in|(?:sign|log)[ -]?in (?:is )?required|not (?:signed|logged) in|Please set an Auth method|API key not valid|API[_ ]?KEY[_ ]?INVALID|UNAUTHENTICATED|PERMISSION_DENIED|invalid_grant|re-?authenticate|IneligibleTier|account is not eligible|\bunauthorized\b|\b403\b[^\n]{0,24}\bforbidden\b|\bforbidden\b[^\n]{0,24}\b403\b|\berror["']?[:=]\s*["']?forbidden\b|(?:invalid|incorrect)[^\n]{0,20}(?:api.?key|token|credential)|api[_ -]?key (?:is )?(?:missing|required|not set|unset)|\b(?:status|HTTP):? 40[13]\b|GEMINI_API_KEY/i],
51
+ ['quota', /RESOURCE_EXHAUSTED|\bquota\b|exhausted your capacity|rate.?limit|too many requests|\b429\b|overloaded/i],
52
+ ['network', /fetch failed|ENOTFOUND|ETIMEDOUT|ECONNREFUSED|ECONNRESET|EAI_AGAIN|UND_ERR_CONNECT_TIMEOUT|socket hang up|getaddrinfo|network error|self[- ]signed certificate|unable to verify the first certificate/i],
53
+ ['model', /ModelNotFound|models?\b[^\n]{0,60}\bnot (?:found|supported)|unknown model|invalid model|unsupported model|no such model|model[^\n]{0,30}(?:unavailable|does not exist)|\bstatus:? 404\b/i],
54
+ ['provider', /modelProvider|model provider|unknown provider|no (?:inference )?provider configured|provider[^\n]{0,30}(?:not|un)(?:available|configured|supported|known)/i],
55
+ ['config', new RegExp(
56
+ `${CONFIG_FILE}[^\\n]{0,60}${UNREADABLE}|${UNREADABLE}[^\\n]{0,60}${CONFIG_FILE}`
57
+ + '|config(?:uration)? (?:error|is invalid|invalid|malformed)|invalid json|malformed (?:json|ya?ml|toml|config)',
58
+ 'i',
59
+ )],
60
+ ['timeout', /print-timeout|timed? ?out|deadline exceeded/i],
61
+ ];
62
+
63
+ /**
64
+ * Generic wording for a kind the adapter gave no sentence for. Deliberately
65
+ * vague about the fix — an adapter that knows better passes `guidance`.
66
+ */
67
+ function defaultGuidance(kind, cli) {
68
+ switch (kind) {
69
+ case 'session':
70
+ return `${cli} could not resume this channel's previous session.`;
71
+ case 'auth':
72
+ return `${cli} could not authenticate. Check this agent's API key or sign-in.`;
73
+ case 'quota':
74
+ return 'The provider is rate-limiting this agent, or its quota is exhausted. Wait and try again.';
75
+ case 'network':
76
+ return `${cli} could not reach its provider from this device. Check the device's network, or its proxy.`;
77
+ case 'model':
78
+ return `The provider rejected the requested model. Check the model configured for this agent.`;
79
+ case 'provider':
80
+ return `${cli} has no usable provider configured.`;
81
+ case 'config':
82
+ return `${cli}'s configuration looks invalid.`;
83
+ case 'timeout':
84
+ return `${cli} timed out before producing a response.`;
85
+ default:
86
+ return '';
87
+ }
88
+ }
89
+
90
+ /** The message text of a `{type, message}` error, a bare string, or nothing. */
91
+ function errorMessage(error) {
92
+ if (!error) return '';
93
+ if (typeof error === 'string') return error;
94
+ if (typeof error === 'object') return String(error.message || error.type || '');
95
+ return String(error);
96
+ }
97
+
98
+ const oneLine = (s) => s.replace(/\s+/g, ' ').trim();
99
+ const cap = (s, max = DETAIL_CAP) => (s.length > max ? `${s.slice(0, max - 1)}…` : s);
100
+
101
+ // stderr lines that say something about the failure, as opposed to the
102
+ // "Loaded cached credentials." / "YOLO mode is enabled." chatter around it.
103
+ const TELLING_RE = /error|fail|invalid|denied|not |please|unable|cannot|refused/i;
104
+
105
+ /**
106
+ * Did the run fail? The CLI's own verdict comes first: a success result
107
+ * settles it whatever the exit code and whatever error events came before it
108
+ * (an error the run recovered from is not a failed run — reporting it would
109
+ * post a notice under a reply that was delivered). Without one, an error
110
+ * result, an error-severity event, or a non-zero exit (a signal leaves code
111
+ * null) is a failure.
112
+ */
113
+ function isFailedRun({ code, resultStatus, errorMessages = [] } = {}) {
114
+ const status = String(resultStatus || '').toLowerCase();
115
+ if (status === 'success') return false;
116
+ if (status === 'error' || errorMessages.length > 0) return true;
117
+ return code !== 0;
118
+ }
119
+
120
+ /**
121
+ * The most useful part of what the CLI said, secrets stripped. A structured
122
+ * error wins over stderr, which is mostly startup chatter. Redaction runs over
123
+ * the whole text BEFORE it is cut, so a key split across the cut cannot
124
+ * survive as a fragment.
125
+ *
126
+ * `secrets` are the values the caller knows to be secret — the agent's own
127
+ * keys and its workspace token (BaseAdapter._knownSecrets). They are masked by
128
+ * value, which is the only protection for a key whose format no pattern knows.
129
+ */
130
+ function failureDetail({ stderr, error, errorMessages = [], secrets = [], max = DETAIL_CAP } = {}) {
131
+ const structured = [errorMessage(error), ...errorMessages].filter(Boolean).join(' | ');
132
+ if (structured) return cap(oneLine(redactSecrets(structured, secrets)), max);
133
+ const lines = redactSecrets(stderr || '', secrets).split('\n').map((l) => l.trim()).filter(Boolean);
134
+ if (!lines.length) return '';
135
+ const telling = lines.filter((l) => TELLING_RE.test(l));
136
+ return cap(oneLine((telling.length ? telling : lines).slice(-2).join(' ')), max);
137
+ }
138
+
139
+ /**
140
+ * Which kind of failure the text describes, or null. Matched against the RAW
141
+ * text, never the redacted one: redaction rewrites the very words ("api_key",
142
+ * "token") some patterns key on.
143
+ */
144
+ function classifyFailureText(text, { skip = [] } = {}) {
145
+ const s = String(text || '');
146
+ if (!s.trim()) return null;
147
+ for (const [kind, re] of PATTERNS) {
148
+ if (skip.includes(kind)) continue;
149
+ if (re.test(s)) return kind;
150
+ }
151
+ return null;
152
+ }
153
+
154
+ /**
155
+ * Turn a failed run into `{ kind, message, detail }`, where `message` is what
156
+ * the channel should read: guidance for a recognised cause, then the CLI's own
157
+ * words. An unrecognised failure quotes those words with the exit code, which
158
+ * still beats "No response generated".
159
+ *
160
+ * @param {object} info
161
+ * @param {number|null} info.code process exit code (null when signalled)
162
+ * @param {string} info.stderr everything the process wrote to stderr
163
+ * @param {object|string} info.error a structured error from the CLI's stream
164
+ * @param {string[]} info.errorMessages error-severity events from the stream
165
+ * @param {string} info.cli the CLI's name, for the fallback wording
166
+ * @param {object} info.guidance kind → the sentence to lead with
167
+ * @param {string[]} info.skip kinds this CLI can never produce
168
+ * @param {string[]} info.secrets values to mask wherever they appear
169
+ * @param {string} info.codeLabel how to name `code` when it is not an exit
170
+ * code — "HTTP 429" for an adapter that talks to an API rather than a CLI.
171
+ */
172
+ function classifyRunFailure({
173
+ code, stderr, error, errorMessages = [], cli = 'The CLI', guidance = {}, skip = [],
174
+ secrets = [], codeLabel = '',
175
+ } = {}) {
176
+ const errType = error && typeof error === 'object' ? String(error.type || '') : '';
177
+ const structured = [errType, errorMessage(error), ...errorMessages].filter(Boolean).join('\n');
178
+ const detail = failureDetail({ stderr, error, errorMessages, secrets });
179
+ const kind = classifyFailureText([structured, stderr].filter(Boolean).join('\n'), { skip });
180
+
181
+ if (kind) {
182
+ const lead = guidance[kind] || defaultGuidance(kind, cli);
183
+ return { kind, detail, message: detail ? `${lead}\n\nDetails: ${detail}` : lead };
184
+ }
185
+ return {
186
+ kind: 'unknown',
187
+ detail,
188
+ message: detail
189
+ ? `${cli} failed (${codeLabel || `exit ${code ?? '?'}`}): ${detail}`
190
+ : (codeLabel
191
+ ? `${cli} failed (${codeLabel}) without a response.`
192
+ : `${cli} exited with code ${code ?? '?'} without a response.`),
193
+ };
194
+ }
195
+
196
+ /**
197
+ * An Error whose message is already the sentence the channel should read.
198
+ * Adapters that report a failure by throwing (rather than posting inline) mark
199
+ * it this way so their catch can post it as-is instead of wrapping it in
200
+ * "Error processing message: …", which reads like an adapter bug.
201
+ */
202
+ function classifiedError(message) {
203
+ const err = new Error(message);
204
+ err.classified = true;
205
+ return err;
206
+ }
207
+
208
+ /** True for an error carrying a message meant for the channel verbatim. */
209
+ function isClassifiedError(e) {
210
+ return !!(e && e.classified);
211
+ }
212
+
213
+ module.exports = {
214
+ DETAIL_CAP,
215
+ classifiedError,
216
+ isClassifiedError,
217
+ PATTERNS,
218
+ isFailedRun,
219
+ errorMessage,
220
+ failureDetail,
221
+ classifyFailureText,
222
+ classifyRunFailure,
223
+ defaultGuidance,
224
+ };
@@ -123,29 +123,99 @@ function formatAttachmentsForPrompt(
123
123
  return lines.join('\n');
124
124
  }
125
125
 
126
+ /**
127
+ * Environment variable names whose value is a credential. Deliberately broad:
128
+ * masking a value that turns out to be harmless costs one word of an error
129
+ * notice, while missing a key posts it to every member of the workspace.
130
+ */
131
+ const SECRET_NAME_RE = /KEY|TOKEN|SECRET|PASSWORD|PASSWD|AUTH/i;
132
+ /** Shorter than this and a value is as likely a flag ("1", "true") as a secret. */
133
+ const MIN_SECRET_LENGTH = 8;
134
+
135
+ /**
136
+ * The exact values an agent must never quote back: everything in its
137
+ * environment whose name says it is a credential, plus whatever the caller
138
+ * already knows to be one (the workspace token). Longest first, so a secret
139
+ * that contains another is masked whole rather than leaving its tail behind.
140
+ *
141
+ * @param {object} env the environment the agent's CLI runs with
142
+ * @param {string[]} extra further values to mask
143
+ * @returns {string[]}
144
+ */
145
+ function secretValues(env, extra = []) {
146
+ const out = new Set();
147
+ const add = (value) => {
148
+ const v = typeof value === 'string' ? value.trim() : '';
149
+ if (v.length >= MIN_SECRET_LENGTH) out.add(v);
150
+ };
151
+ for (const [name, value] of Object.entries(env || {})) {
152
+ if (SECRET_NAME_RE.test(name)) add(value);
153
+ }
154
+ for (const value of extra || []) add(value);
155
+ return [...out].sort((x, y) => y.length - x.length);
156
+ }
157
+
158
+ /**
159
+ * Mask known secret values in `text` and touch nothing else. For text that is
160
+ * mostly prose or code — a model's partial answer — where the shape rules of
161
+ * redactSecrets would rewrite ordinary words ("token limit", `password: string`).
162
+ */
163
+ function maskSecretValues(text, secrets) {
164
+ let out = String(text == null ? '' : text);
165
+ for (const secret of secrets || []) {
166
+ if (typeof secret === 'string' && secret.length >= MIN_SECRET_LENGTH) {
167
+ out = out.split(secret).join('[REDACTED]');
168
+ }
169
+ }
170
+ return out;
171
+ }
172
+
126
173
  /**
127
174
  * Strip secrets out of anything on its way to a log line or a channel message.
128
175
  *
129
176
  * Adapter diagnostics quote raw CLI output, and a CLI that fails on auth tends
130
- * to echo the credential it was handed. The shapes here are the ones that
131
- * actually turn up in that output; the closing catch-all takes any long opaque
132
- * token the named patterns missed.
177
+ * to echo the credential it was handed. Two passes:
178
+ *
179
+ * 1. `secrets` — the values we already know are secret (see secretValues),
180
+ * masked wherever they appear. No pattern can know every provider's key
181
+ * format; this needs no format at all. It runs first because a pattern
182
+ * that recognises half of a key would otherwise leave the other half.
183
+ * 2. The shapes that actually turn up in CLI output, for a credential that
184
+ * is not ours to know (another tool's token, a key in a config file). The
185
+ * closing catch-all takes any long opaque token the named patterns missed.
133
186
  *
134
187
  * Lived as a private static on two adapters before claude needed it as well —
135
188
  * a third identical copy is one copy too many for a security-relevant rule.
189
+ *
190
+ * @param {string} s
191
+ * @param {string[]} [secrets] exact values to mask, e.g. from secretValues()
136
192
  */
137
- function redactSecrets(s) {
138
- let out = String(s == null ? '' : s);
193
+ function redactSecrets(s, secrets) {
194
+ let out = maskSecretValues(s, secrets);
139
195
  out = out
196
+ // scheme://user:password@host, and scheme://token@host.
197
+ .replace(/(\b[a-z][a-z0-9+.-]*:\/\/)[^/\s@?#]+@/gi, '$1[REDACTED]@')
140
198
  .replace(/\bsk-[A-Za-z0-9_-]{6,}/g, 'sk-[REDACTED]')
141
199
  .replace(/\b(?:github_pat|gh[pousr])_[A-Za-z0-9_]{10,}/g, '[REDACTED_TOKEN]')
142
200
  .replace(/\bxox[baprs]-[A-Za-z0-9-]{8,}/g, '[REDACTED_TOKEN]')
143
201
  .replace(/\bAKIA[0-9A-Z]{12,}/g, '[REDACTED_KEY]')
144
202
  .replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/g, '[REDACTED_JWT]')
145
- .replace(/(authorization|api[_-]?key|x-api-key|token|bearer|secret|password|passwd)(["'\s:=]+)([^\s"',}]+)/gi,
203
+ // Google API keys are 39 chars, one short of the catch-all below.
204
+ .replace(/\bAIza[0-9A-Za-z_-]{30,}/g, '[REDACTED_KEY]')
205
+ .replace(/\bya29\.[0-9A-Za-z_-]{20,}/g, '[REDACTED_TOKEN]')
206
+ // key: value. An Authorization value is "<scheme> <credential>", so the
207
+ // scheme word is skipped — taking it for the value masked "Bearer" and
208
+ // left the token standing right behind it.
209
+ .replace(/(authorization|api[_-]?key|x-api-key|token|bearer|secret|password|passwd)(["'\s:=]+)(?:(?:bearer|basic|token)[ \t]+)?([^\s"',}]+)/gi,
146
210
  (m, k, sep) => `${k}${sep}[REDACTED]`)
211
+ // A Basic credential quoted without its header name. Base64 has no shape
212
+ // of its own, so this wants padding or some length before it believes it.
213
+ .replace(/\b(basic)[ \t]+(?:[A-Za-z0-9+/]{16,}={0,2}|[A-Za-z0-9+/]{4,}={1,2})/gi, '$1 [REDACTED]')
147
214
  .replace(/([?&](?:api[_-]?key|key|token|access_token)=)[^&\s"']+/gi, '$1[REDACTED]')
148
- .replace(/\b[A-Za-z0-9_-]{40,}\b/g, '[REDACTED]');
215
+ .replace(/\b[A-Za-z0-9_-]{40,}\b/g, '[REDACTED]')
216
+ // Keys too short for the catch-all with no prefix to know them by: bare
217
+ // hex (32+), and the "<32 hex>.<secret>" form Zhipu issues.
218
+ .replace(/\b[0-9a-f]{32,}(?:\.[A-Za-z0-9]{8,})?\b/gi, '[REDACTED]');
149
219
  return out;
150
220
  }
151
221
 
@@ -187,4 +257,6 @@ module.exports = {
187
257
  generateSessionTitle,
188
258
  formatAttachmentsForPrompt,
189
259
  redactSecrets,
260
+ maskSecretValues,
261
+ secretValues,
190
262
  };