@openagents-org/agent-launcher 0.2.212 → 0.2.214

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.212",
3
+ "version": "0.2.214",
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
@@ -616,8 +616,7 @@
616
616
  {
617
617
  "name": "LLM_BASE_URL",
618
618
  "description": "Custom OpenAI-compatible base URL (leave empty to use Hermes's own provider login)",
619
- "required": false,
620
- "placeholder": "https://api.openai.com/v1"
619
+ "required": false
621
620
  },
622
621
  {
623
622
  "name": "LLM_MODEL",
@@ -1844,8 +1843,7 @@
1844
1843
  {
1845
1844
  "name": "DEEPSEEK_BASE_URL",
1846
1845
  "description": "Optional gateway/proxy base URL. Leave blank for the public DeepSeek API. A URL ending in a version segment (e.g. https://relay.example.com/v1, or OpenAgents credits) is used as an OpenAI-compatible chat-completions endpoint; any other URL must speak the Anthropic Messages API (e.g. https://api.deepseek.com/anthropic).",
1847
- "required": false,
1848
- "placeholder": "https://api.deepseek.com/anthropic"
1846
+ "required": false
1849
1847
  },
1850
1848
  {
1851
1849
  "name": "DEEPSEEK_MODEL",
@@ -2254,8 +2252,7 @@
2254
2252
  {
2255
2253
  "name": "CODEBUDDY_BASE_URL",
2256
2254
  "description": "Advanced. Endpoint override, for an enterprise or self-hosted deployment. Blank means the endpoint the region above selects.",
2257
- "required": false,
2258
- "placeholder": "https://www.codebuddy.cn"
2255
+ "required": false
2259
2256
  }
2260
2257
  ],
2261
2258
  "check_ready": {
@@ -604,7 +604,7 @@ class CodexAdapter extends BaseAdapter {
604
604
  }
605
605
  });
606
606
 
607
- proc.on('exit', async (code) => {
607
+ proc.on('exit', async (code, signal) => {
608
608
  // Wait for all in-flight processLine calls
609
609
  try { await _pendingLines; } catch {}
610
610
 
@@ -617,7 +617,7 @@ class CodexAdapter extends BaseAdapter {
617
617
 
618
618
  const stderrBuf = CodexAdapter._decodeOutput(Buffer.concat(stderrChunks));
619
619
  if (code !== 0) {
620
- this._log(`Codex CLI exited with code ${code}`);
620
+ this._log(`Codex CLI exited with code ${code}${signal ? ` (${signal})` : ''}`);
621
621
  if (stderrBuf.trim()) {
622
622
  this._log(`stderr: ${stderrBuf.trim().slice(0, 500)}`);
623
623
  }
@@ -626,6 +626,7 @@ class CodexAdapter extends BaseAdapter {
626
626
  resolve({
627
627
  responseText: responseTexts.join('\n').trim(),
628
628
  exitCode: code,
629
+ signal,
629
630
  stderr: stderrBuf,
630
631
  errorMessage: lastErrorMessage,
631
632
  turnFailed,
@@ -744,11 +745,13 @@ class CodexAdapter extends BaseAdapter {
744
745
 
745
746
  /**
746
747
  * Pick the most informative failure detail from a run result:
747
- * turn.failed / error event message → stderr tail → exit code. Redacted.
748
+ * turn.failed / error event message → stderr tail → signal → exit code.
749
+ * Redacted.
748
750
  */
749
- static _failureDetail({ errorMessage, stderr, exitCode } = {}) {
751
+ static _failureDetail({ errorMessage, stderr, exitCode, signal } = {}) {
750
752
  const raw = String(errorMessage || '').trim()
751
753
  || CodexAdapter._stderrReason(stderr)
754
+ || (signal ? `codex was terminated by ${signal}` : '')
752
755
  || (exitCode ? `codex exited with code ${exitCode}` : '');
753
756
  const detail = CodexAdapter._explain(CodexAdapter._unwrap(raw));
754
757
  return CodexAdapter._redact(detail).slice(0, 500).trim();
@@ -767,7 +770,10 @@ class CodexAdapter extends BaseAdapter {
767
770
  * when neither exists does the raw tail stand.
768
771
  */
769
772
  static _stderrReason(stderr) {
770
- const lines = String(stderr || '').split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
773
+ // The stdin banner is never a reason: a run whose stderr holds nothing
774
+ // else falls through to the exit code instead of quoting the banner.
775
+ const lines = String(stderr || '').split(/\r?\n/).map((l) => l.trim())
776
+ .filter((l) => l && !/^Reading (prompt|additional input) from stdin/i.test(l));
771
777
  if (!lines.length) return '';
772
778
  const TRACE = /^\d{4}-\d{2}-\d{2}T[\d:.]+Z?\s+(TRACE|DEBUG|INFO|WARN|ERROR)\s+(?:[\w:]+:\s+)?(.*)$/;
773
779
  const plain = [];
@@ -775,7 +781,7 @@ class CodexAdapter extends BaseAdapter {
775
781
  for (const line of lines) {
776
782
  const m = line.match(TRACE);
777
783
  if (!m) {
778
- if (!/^Reading (prompt|additional input) from stdin/i.test(line)) plain.push(line);
784
+ plain.push(line);
779
785
  } else if (m[1] === 'ERROR' && m[2] && !errors.includes(m[2])) {
780
786
  errors.push(m[2]);
781
787
  }
@@ -384,6 +384,67 @@ function classifyKimiError(info) {
384
384
  return { kind: 'error', userMessage: `Kimi Code CLI ${why}.` };
385
385
  }
386
386
 
387
+ // ---------------------------------------------------------------------------
388
+ // Workspace tools (MCP) through a private Kimi home
389
+ // ---------------------------------------------------------------------------
390
+
391
+ /**
392
+ * Kimi Code has no flag for an MCP config and ignores a project-level
393
+ * `.kimi-code/mcp.json`; it reads MCP servers from `$KIMI_CODE_HOME/mcp.json`
394
+ * (2.4.1). Each agent therefore runs with its own Kimi home under
395
+ * ~/.openagents, so the workspace server can be added without editing the
396
+ * user's ~/.kimi-code. Kimi passes its whole environment to stdio MCP
397
+ * servers, so the file names only the command: the token, workspace and
398
+ * channel of each run travel in the environment (see buildKimiWorkspaceEnv).
399
+ */
400
+ const KIMI_MCP_SERVER_NAME = 'openagents-workspace';
401
+
402
+ /**
403
+ * Entries of the user's Kimi home a private home links back to: the
404
+ * `kimi login` credentials (a directory, so token refreshes land in the
405
+ * user's home) and config.toml (providers and default model for the
406
+ * no-API-key route).
407
+ */
408
+ const KIMI_HOME_LINKS = [
409
+ { name: 'credentials', dir: true },
410
+ { name: 'config.toml', dir: false },
411
+ ];
412
+
413
+ /** Directory name of an agent's private Kimi home: readable, unique per workspace+agent. */
414
+ function kimiHomeName(workspaceId, agentName) {
415
+ const raw = `${workspaceId == null ? '' : workspaceId}\u0000${agentName == null ? '' : agentName}`;
416
+ const hash = crypto.createHash('sha256').update(raw).digest('hex').slice(0, 8);
417
+ const slug = (v) => String(v == null ? '' : v).toLowerCase()
418
+ .replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 32) || 'agent';
419
+ return `${slug(workspaceId)}_${slug(agentName)}-${hash}`;
420
+ }
421
+
422
+ /**
423
+ * The private home's mcp.json: the user's own MCP servers (so a private home
424
+ * loses nothing the user configured) plus the workspace server, which always
425
+ * wins its name. An unreadable user file contributes nothing.
426
+ */
427
+ function buildKimiMcpConfig(userConfig, server) {
428
+ const base = userConfig && typeof userConfig === 'object' && !Array.isArray(userConfig) ? userConfig : {};
429
+ const servers = base.mcpServers && typeof base.mcpServers === 'object' && !Array.isArray(base.mcpServers)
430
+ ? { ...base.mcpServers }
431
+ : {};
432
+ servers[KIMI_MCP_SERVER_NAME] = server;
433
+ return { ...base, mcpServers: servers };
434
+ }
435
+
436
+ /** What the workspace MCP server reads from its environment (cli.js `mcp-server`). */
437
+ function buildKimiWorkspaceEnv({ token, workspaceId, channel, agentName, endpoint }) {
438
+ const env = {
439
+ OPENAGENTS_WORKSPACE_ID: String(workspaceId || ''),
440
+ OPENAGENTS_CHANNEL_NAME: String(channel || 'general'),
441
+ OPENAGENTS_AGENT_NAME: String(agentName || 'agent'),
442
+ };
443
+ if (endpoint) env.OPENAGENTS_ENDPOINT = String(endpoint);
444
+ if (token) env.OA_WORKSPACE_TOKEN = String(token);
445
+ return env;
446
+ }
447
+
387
448
  module.exports = {
388
449
  parseKimiVersion,
389
450
  classifyKimiVersion,
@@ -402,4 +463,9 @@ module.exports = {
402
463
  DEFAULT_MAX_COMPLETION_TOKENS,
403
464
  EXIT_PERMANENT,
404
465
  EXIT_TRANSIENT,
466
+ KIMI_MCP_SERVER_NAME,
467
+ KIMI_HOME_LINKS,
468
+ kimiHomeName,
469
+ buildKimiMcpConfig,
470
+ buildKimiWorkspaceEnv,
405
471
  };
@@ -19,7 +19,17 @@
19
19
  * OpenAI-compatible chat completions against KIMI_BASE_URL (inherited from
20
20
  * LlmDirectAdapter).
21
21
  *
22
- * Verified against Kimi Code CLI v0.39.1. NOTE: the legacy Python `kimi-cli`
22
+ * - workspace tools: the CLI reads MCP servers only from
23
+ * `$KIMI_CODE_HOME/mcp.json`, so each agent runs with a private Kimi home
24
+ * (~/.openagents/kimi-homes/<agent>/) that adds the workspace MCP server to
25
+ * the user's own servers and links their `kimi login` credentials and
26
+ * config.toml back in. The token, workspace and channel reach the MCP
27
+ * server through the environment, never through a file.
28
+ * - no sandbox: print mode approves every tool call and the CLI has no
29
+ * filesystem boundary, so the agent can write outside its working
30
+ * directory. That is the CLI's own model, not something this adapter adds.
31
+ *
32
+ * Verified against Kimi Code CLI v0.39.1 and 2.4.1. NOTE: the legacy Python `kimi-cli`
23
33
  * (PyPI) also installs a `kimi` binary but reports 1.x versions and has a
24
34
  * different interface — it is detected and NOT driven.
25
35
  */
@@ -49,6 +59,11 @@ const {
49
59
  classifyKimiVersion,
50
60
  classifyKimiError,
51
61
  encodeKimiWorkDirKey,
62
+ KIMI_MCP_SERVER_NAME,
63
+ KIMI_HOME_LINKS,
64
+ kimiHomeName,
65
+ buildKimiMcpConfig,
66
+ buildKimiWorkspaceEnv,
52
67
  } = require('./kimi-stream');
53
68
 
54
69
  const IS_WINDOWS = process.platform === 'win32';
@@ -255,10 +270,14 @@ class KimiAdapter extends LlmDirectAdapter {
255
270
  if (!proc || proc.exitCode !== null) return;
256
271
  try {
257
272
  if (IS_WINDOWS) {
258
- try { proc.kill('SIGINT'); } catch {}
259
- const exited = await this._waitExit(proc, 1500);
260
- if (!exited) {
261
- try { execSync(`taskkill /F /T /PID ${proc.pid}`, { timeout: 5000, windowsHide: true }); } catch {}
273
+ // Tree first. On Windows proc.kill() is TerminateProcess whatever the
274
+ // signal, so "SIGINT, then taskkill /T if it is still alive" never
275
+ // reached taskkill — and once kimi is dead its shell commands can no
276
+ // longer be found through it: a Stop left them running.
277
+ try { execSync(`taskkill /F /T /PID ${proc.pid}`, { timeout: 5000, windowsHide: true }); } catch {}
278
+ if (!(await this._waitExit(proc, 1500))) {
279
+ try { proc.kill(); } catch {}
280
+ await this._waitExit(proc, 1000);
262
281
  }
263
282
  } else {
264
283
  try { process.kill(-proc.pid, 'SIGINT'); } catch { try { proc.kill('SIGINT'); } catch {} }
@@ -456,6 +475,13 @@ class KimiAdapter extends LlmDirectAdapter {
456
475
  if (this._mode === 'plan') {
457
476
  lines.push('You are in PLAN mode: investigate and propose a plan; do not modify files.');
458
477
  }
478
+ if (this._workspaceToolsReady) {
479
+ lines.push(
480
+ `For anything in the OpenAgents workspace — chat history, files, uploads, knowledge, todos — use the ` +
481
+ `\`workspace_*\` tools (MCP server "${KIMI_MCP_SERVER_NAME}"). They are already signed in: never look for, ` +
482
+ 'print or use a workspace token, and do not call the workspace HTTP API yourself.',
483
+ );
484
+ }
459
485
  lines.push('Work in the current working directory. Reply concisely. The user request follows:');
460
486
  return lines.join('\n');
461
487
  }
@@ -584,6 +610,9 @@ class KimiAdapter extends LlmDirectAdapter {
584
610
 
585
611
  // Resuming → Kimi already has history, send the bare turn. Fresh →
586
612
  // prepend a context header (+ recap when available).
613
+ // Decided before the prompt is built: the header only promises the
614
+ // workspace tools when this run will actually have them.
615
+ this._workspaceToolsReady = !!this._prepareKimiHome();
587
616
  let prompt;
588
617
  if (resumeId) {
589
618
  prompt = content;
@@ -633,6 +662,92 @@ class KimiAdapter extends LlmDirectAdapter {
633
662
  }
634
663
  }
635
664
 
665
+ // ------------------------------------------------------------------
666
+ // Private Kimi home (workspace MCP tools)
667
+ // ------------------------------------------------------------------
668
+
669
+ /** This agent's own Kimi home. See KIMI_MCP_SERVER_NAME in kimi-stream.js. */
670
+ _kimiHome() {
671
+ return path.join(os.homedir(), '.openagents', 'kimi-homes', kimiHomeName(this.workspaceId, this.agentName));
672
+ }
673
+
674
+ /** The user's own Kimi home, which the private one links back to. */
675
+ _userKimiHome() {
676
+ const env = this.agentEnv || {};
677
+ return env.KIMI_CODE_HOME || process.env.KIMI_CODE_HOME || path.join(os.homedir(), '.kimi-code');
678
+ }
679
+
680
+ /**
681
+ * (Re)build the private home for one run and return its path, or null when
682
+ * it cannot be prepared — the run then goes ahead without workspace tools,
683
+ * exactly as before.
684
+ *
685
+ * Every run re-checks the links, so a `kimi login` done after the agent
686
+ * started is picked up, and rewrites mcp.json, so a change to the user's own
687
+ * MCP servers or to the agent's disabled modules applies at once.
688
+ */
689
+ _prepareKimiHome() {
690
+ const home = this._kimiHome();
691
+ try {
692
+ fs.mkdirSync(home, { recursive: true, mode: 0o700 });
693
+ const userHome = this._userKimiHome();
694
+ for (const { name, dir } of KIMI_HOME_LINKS) this._linkIntoKimiHome(path.join(userHome, name), path.join(home, name), dir);
695
+
696
+ const command = this._mcpServerCommand();
697
+ if (!command) {
698
+ this._log('Could not locate the OpenAgents CLI — workspace tools are unavailable this run');
699
+ return null;
700
+ }
701
+ let userConfig = null;
702
+ try { userConfig = JSON.parse(fs.readFileSync(path.join(userHome, 'mcp.json'), 'utf-8')); } catch {}
703
+ const config = buildKimiMcpConfig(userConfig, command);
704
+ const file = path.join(home, 'mcp.json');
705
+ const tmp = `${file}.${process.pid}.tmp`;
706
+ fs.writeFileSync(tmp, JSON.stringify(config, null, 2), { mode: 0o600 });
707
+ fs.renameSync(tmp, file);
708
+ return home;
709
+ } catch (e) {
710
+ this._log(`Could not prepare the private Kimi home (${redactSecrets(e && e.message)}) — workspace tools are unavailable this run`);
711
+ return null;
712
+ }
713
+ }
714
+
715
+ /**
716
+ * Point `dest` at `target` in the user's home. A directory is linked
717
+ * (a junction on Windows, which needs no privilege), so writes such as a
718
+ * credentials refresh land in the user's home. A file is symlinked on POSIX
719
+ * and copied on Windows, where file symlinks need Developer Mode. Anything
720
+ * already at `dest` that is not ours to replace is left alone.
721
+ */
722
+ _linkIntoKimiHome(target, dest, isDir) {
723
+ if (!fs.existsSync(target)) return;
724
+ let st = null;
725
+ try { st = fs.lstatSync(dest); } catch {}
726
+ if (st && st.isSymbolicLink()) {
727
+ let current = null;
728
+ try { current = fs.readlinkSync(dest); } catch {}
729
+ if (current && path.resolve(path.dirname(dest), current) === path.resolve(target)) return;
730
+ fs.rmSync(dest, { force: true });
731
+ } else if (st && !(IS_WINDOWS && !isDir && st.isFile())) {
732
+ return;
733
+ }
734
+ if (isDir) fs.symlinkSync(target, dest, IS_WINDOWS ? 'junction' : 'dir');
735
+ else if (IS_WINDOWS) fs.copyFileSync(target, dest);
736
+ else fs.symlinkSync(target, dest, 'file');
737
+ }
738
+
739
+ /** The stdio command that runs this package's workspace MCP server. */
740
+ _mcpServerCommand() {
741
+ const bin = path.resolve(__dirname, '..', '..', 'bin', 'agent-connector.js');
742
+ if (!fs.existsSync(bin)) return null;
743
+ const args = [bin, 'mcp-server'];
744
+ const disabled = this.disabledModules || new Set();
745
+ if (disabled.has('files')) args.push('--disable-files');
746
+ if (disabled.has('browser')) args.push('--disable-browser');
747
+ if (disabled.has('knowledge')) args.push('--disable-knowledge');
748
+ return { command: process.execPath, args };
749
+ }
750
+
636
751
  _dirExists(p) {
637
752
  try { return fs.statSync(p).isDirectory(); } catch { return false; }
638
753
  }
@@ -683,6 +798,17 @@ class KimiAdapter extends LlmDirectAdapter {
683
798
  // Stopped while this turn was being prepared: start nothing (no tokens).
684
799
  if (this._stoppedBeforeStart(channel)) return Promise.resolve({ userStopped: true });
685
800
  const { env: cleanEnv } = buildKimiEnv(this.agentEnv || process.env);
801
+ const kimiHome = this._prepareKimiHome();
802
+ if (kimiHome) {
803
+ cleanEnv.KIMI_CODE_HOME = kimiHome;
804
+ Object.assign(cleanEnv, buildKimiWorkspaceEnv({
805
+ token: this.token,
806
+ workspaceId: this.workspaceId,
807
+ channel,
808
+ agentName: this.agentName,
809
+ endpoint: this.endpoint,
810
+ }));
811
+ }
686
812
  const [cmd, ...spawnArgs] = this._spawnableCmd(kimiBin, args);
687
813
  // Before the spawn, so the session this run creates shows up as new.
688
814
  const sessionWatch = this._watchKimiSessions(cleanEnv, workingDir, args);
@@ -702,6 +828,7 @@ class KimiAdapter extends LlmDirectAdapter {
702
828
  const state = {
703
829
  ok: false,
704
830
  finalText: '',
831
+ pendingThought: '',
705
832
  sessionId: null,
706
833
  anyOutput: false,
707
834
  userStopped: false,
@@ -743,12 +870,21 @@ class KimiAdapter extends LlmDirectAdapter {
743
870
  for (const e of interpretKimiMessage(m)) {
744
871
  switch (e.kind) {
745
872
  case 'text':
873
+ // Held back until the turn moves on: the LAST text is the reply,
874
+ // posted once as the response rather than also as a thought.
746
875
  state.anyOutput = true;
876
+ if (state.pendingThought) {
877
+ try { await this.sendThinking(channel, state.pendingThought); } catch {}
878
+ }
879
+ state.pendingThought = e.text;
747
880
  state.finalText = e.text;
748
- try { await this.sendThinking(channel, e.text); } catch {}
749
881
  break;
750
882
  case 'tool_start':
751
883
  state.anyOutput = true;
884
+ if (state.pendingThought) {
885
+ try { await this.sendThinking(channel, state.pendingThought); } catch {}
886
+ state.pendingThought = '';
887
+ }
752
888
  try {
753
889
  await this.sendStatus(channel, e.preview ? `${e.name}: ${e.preview}` : e.name);
754
890
  } catch {}
@@ -100,6 +100,9 @@ function needsDoctorMigration(message) {
100
100
  return /requires[^\n]*\bmigration\b/i.test(text) && /openclaw doctor --fix/i.test(text);
101
101
  }
102
102
 
103
+ /** OpenClaw's refusal to run embedded while a Gateway owns the state. */
104
+ const GATEWAY_RUNNING = /A Gateway is running for this state directory/i;
105
+
103
106
  /** Budget for one `openclaw doctor --fix` run. */
104
107
  const DOCTOR_REPAIR_TIMEOUT_MS = 120000;
105
108
 
@@ -383,7 +386,7 @@ class OpenClawAdapter extends BaseAdapter {
383
386
  */
384
387
  async _runCliAgentWithMigration(userMessage, channel) {
385
388
  try {
386
- return await this._runCliAgent(userMessage, channel);
389
+ return await this._runCliTurn(userMessage, channel);
387
390
  } catch (e) {
388
391
  // At most one repair per turn; a repair that failed is not retried on
389
392
  // every later message.
@@ -396,7 +399,23 @@ class OpenClawAdapter extends BaseAdapter {
396
399
  this._doctorRepairFailed = true;
397
400
  throw e;
398
401
  }
399
- return this._runCliAgent(userMessage, channel);
402
+ return this._runCliTurn(userMessage, channel);
403
+ }
404
+ }
405
+
406
+ /**
407
+ * One turn, embedded (`--local`) by default. OpenClaw refuses an embedded
408
+ * run while the user's own Gateway serves the same state directory — "A
409
+ * Gateway is running for this state directory … Run without --local to use
410
+ * it" — and every message failed that way. Hand the turn to that Gateway.
411
+ */
412
+ async _runCliTurn(userMessage, channel) {
413
+ try {
414
+ return await this._runCliAgent(userMessage, channel);
415
+ } catch (e) {
416
+ if (!GATEWAY_RUNNING.test((e && e.message) || '')) throw e;
417
+ this._log('A Gateway is running for this OpenClaw state — retrying the turn through it');
418
+ return this._runCliAgent(userMessage, channel, { local: false });
400
419
  }
401
420
  }
402
421
 
@@ -471,7 +490,7 @@ class OpenClawAdapter extends BaseAdapter {
471
490
  return { spawnBin: binary, spawnArgs: args };
472
491
  }
473
492
 
474
- _runCliAgent(userMessage, channel) {
493
+ _runCliAgent(userMessage, channel, { local = true } = {}) {
475
494
  return new Promise((resolve, reject) => {
476
495
  // Stopped while this turn was being prepared: start nothing (no tokens).
477
496
  if (this._stoppedBeforeStart(channel)) {
@@ -496,7 +515,7 @@ class OpenClawAdapter extends BaseAdapter {
496
515
 
497
516
  const args = [
498
517
  '--log-level', 'trace',
499
- 'agent', '--local',
518
+ 'agent', ...(local ? ['--local'] : []),
500
519
  '--agent', this.openclawAgentId,
501
520
  '--session-id', sessionKey,
502
521
  '--message', userMessage,
package/src/cli.js CHANGED
@@ -1059,6 +1059,11 @@ async function cmdProbe(connector, flags, positional) {
1059
1059
  } catch {}
1060
1060
 
1061
1061
  const result = await connector.probeAgentType(type, { agentEnv });
1062
+ // The daemon probes by agent name: a name that is neither an agent here nor
1063
+ // a type is an agent that is gone, not a type the catalog lacks.
1064
+ if (!agentEnv && result.code === 'unknown_type') {
1065
+ result.message = `No agent named '${target}' on this device`;
1066
+ }
1062
1067
 
1063
1068
  if (flags && flags.json) {
1064
1069
  // Machine consumers (the daemon's probe_agent node command) read ONLY
package/src/config.js CHANGED
@@ -45,9 +45,32 @@ class Config {
45
45
 
46
46
  // -- Write --
47
47
 
48
+ /**
49
+ * Replace the file in one step. A plain writeFileSync truncates first, and
50
+ * the daemon and its `agn` children read this file all the time: a probe
51
+ * started right after a create read it empty and reported the new agent as
52
+ * "Unknown agent type '<name>'", and a read-modify-write in that window
53
+ * 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.
55
+ */
48
56
  save(config) {
49
57
  fs.mkdirSync(this.configDir, { recursive: true });
50
- fs.writeFileSync(this.configFile, serializeYaml(config), 'utf-8');
58
+ const text = serializeYaml(config);
59
+ const tmp = `${this.configFile}.${process.pid}.tmp`;
60
+ fs.writeFileSync(tmp, text, 'utf-8');
61
+ for (let attempt = 0; attempt < 3; attempt++) {
62
+ try {
63
+ fs.renameSync(tmp, this.configFile);
64
+ return;
65
+ } catch (err) {
66
+ if (!['EPERM', 'EACCES', 'EBUSY'].includes(err.code)) {
67
+ try { fs.unlinkSync(tmp); } catch {}
68
+ throw err;
69
+ }
70
+ }
71
+ }
72
+ try { fs.unlinkSync(tmp); } catch {}
73
+ fs.writeFileSync(this.configFile, text, 'utf-8');
51
74
  }
52
75
 
53
76
  addAgent({ name, type, role, path: agentPath, env }) {
package/src/probe.js CHANGED
@@ -34,7 +34,7 @@ const os = require('os');
34
34
  const { spawn } = require('./wsl');
35
35
  const { getEnhancedEnv } = require('./paths');
36
36
  const { shouldUseShellForBinary, REASON } = require('./adapters/health-status');
37
- const { decodeConsoleOutput, BENIGN_CLI_OUTPUT, stripCliNoise } = require('./adapters/utils');
37
+ const { decodeConsoleOutput, BENIGN_CLI_OUTPUT, stripCliNoise, redactSecrets } = require('./adapters/utils');
38
38
  const { formatAuthGuidance } = require('./auth-guidance');
39
39
  const { isCliLogin, stripForCliLogin, typeEnvFor } = require('./env');
40
40
  const { configuredModel } = require('./agent-model');
@@ -90,10 +90,14 @@ function installCommandFor(entry) {
90
90
  /** Redact anything that looks like a secret before output leaves the device. */
91
91
  function scrub(text) {
92
92
  if (!text) return '';
93
- return String(text)
93
+ const masked = String(text)
94
94
  .replace(/sk-[A-Za-z0-9_-]{8,}/g, 'sk-****')
95
95
  .replace(/(api[-_ ]?key["':\s=]+)[A-Za-z0-9_-]{8,}/gi, '$1****')
96
96
  .replace(/Bearer\s+[A-Za-z0-9._-]{8,}/gi, 'Bearer ****');
97
+ // Then everything the adapters strip from quoted CLI text: a Codex probe
98
+ // that failed after printing a token-shaped blob showed that blob as its
99
+ // reason, on the device card in the workspace.
100
+ return redactSecrets(masked);
97
101
  }
98
102
 
99
103
  function tail(text, cap) {
@@ -355,8 +359,11 @@ function shellQuoted(binary, shell) {
355
359
  * with the timeout named first.
356
360
  */
357
361
  function failureMessage(res, code, timeoutMs) {
362
+ // A line that is one long run of base64/base64url characters is an encoded
363
+ // blob (a token, encrypted reasoning), never a sentence that says why the
364
+ // CLI failed. JSON and URLs have characters outside that set and stay.
358
365
  const lines = (s) => String(s || '').split(/\r?\n/).map((l) => l.trim())
359
- .filter((l) => l && !BENIGN_OUTPUT.test(l));
366
+ .filter((l) => l && !BENIGN_OUTPUT.test(l) && !/^[A-Za-z0-9+/=._-]{24,}$/.test(l));
360
367
  const all = [...lines(res.stderr), ...lines(res.stdout)];
361
368
  const telling = all.find((l) => classifyOutputText(l.toLowerCase()) === code);
362
369
  const detail = tail(telling || lines(res.stderr).join('\n') || lines(res.stdout).join('\n'), OUTPUT_CAP);
@@ -660,4 +667,4 @@ async function probeAgentType(connector, type, opts = {}) {
660
667
  });
661
668
  }
662
669
 
663
- module.exports = { probeAgentType, classifyFailure, buildGuidance, authFlavor, installCommandFor, scrub, CODE, DEFAULT_TIMEOUT_MS };
670
+ module.exports = { probeAgentType, classifyFailure, buildGuidance, authFlavor, installCommandFor, scrub, failureMessage, CODE, DEFAULT_TIMEOUT_MS };