@openagents-org/agent-launcher 0.2.230 → 0.2.231

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.230",
3
+ "version": "0.2.231",
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
@@ -315,7 +315,7 @@
315
315
  ]
316
316
  },
317
317
  "vendor": "OpenAI",
318
- "tagline": "GPT-5.5 powered engineering from OpenAI."
318
+ "tagline": "GPT-6 powered engineering from OpenAI."
319
319
  },
320
320
  {
321
321
  "name": "cursor",
@@ -1857,12 +1857,12 @@ class BaseAdapter {
1857
1857
  * structured field: an earlier attempt matched the word "completed" in the
1858
1858
  * message text and fired on every bash for-loop that ended in `done`.
1859
1859
  */
1860
- async sendResponse(channel, content, { statusKind = 'completed' } = {}) {
1860
+ async sendResponse(channel, content, { statusKind = 'completed', model } = {}) {
1861
1861
  if (this._isMuted(channel)) return;
1862
1862
  try {
1863
1863
  await this._replyOutbox().enqueue({
1864
1864
  channel, content,
1865
- metadata: { status_kind: statusKind, ...(this._channelTriggerId?.[channel] ? { in_reply_to: this._channelTriggerId[channel] } : {}) },
1865
+ metadata: { status_kind: statusKind, ...((model || this.modelLabel()) ? { model: model || this.modelLabel() } : {}), ...(this._channelTriggerId?.[channel] ? { in_reply_to: this._channelTriggerId[channel] } : {}) },
1866
1866
  });
1867
1867
  } catch (e) {
1868
1868
  this._log('Could not save or deliver the final reply; check the local response outbox and disk permissions.', 'error');
@@ -960,6 +960,7 @@ class ClaudeAdapter extends BaseAdapter {
960
960
  }
961
961
 
962
962
  if (eventType === 'assistant') {
963
+ if (typeof event.message?.model === 'string' && event.message.model.trim()) pp.responseModel = event.message.model.trim();
963
964
  pp.awaitingToolResult = false;
964
965
  const blocks = (event.message || {}).content || [];
965
966
  for (const block of blocks) {
@@ -1032,7 +1033,7 @@ class ClaudeAdapter extends BaseAdapter {
1032
1033
  const trailing = pp.lastResponseText.join('\n').trim();
1033
1034
  if (trailing && !event.is_error) {
1034
1035
  this._resetIdleTimer(pp.msgChannel);
1035
- try { await this.sendResponse(pp.msgChannel, trailing); } catch {}
1036
+ try { await this.sendResponse(pp.msgChannel, trailing, { model: pp.responseModel }); } catch {}
1036
1037
  }
1037
1038
  pp.lastResponseText.length = 0;
1038
1039
  // The plan nudge was held back while background work ran (see
@@ -1108,6 +1109,7 @@ class ClaudeAdapter extends BaseAdapter {
1108
1109
  * if the process dies mid-message.
1109
1110
  */
1110
1111
  _sendToPersistentProc(pp, content) {
1112
+ pp.responseModel = null;
1111
1113
  pp.lastResponseText = [];
1112
1114
  pp.lastErrorText = '';
1113
1115
  pp.hasToolUseSinceLastText = false;
@@ -1238,7 +1240,7 @@ class ClaudeAdapter extends BaseAdapter {
1238
1240
  */
1239
1241
  async _postTurnOutcome(pp, msgChannel, finalResponse) {
1240
1242
  if (finalResponse) {
1241
- try { await this.sendResponse(msgChannel, finalResponse, { statusKind: pp.lastErrorText ? 'error' : 'completed' }); } catch {}
1243
+ try { await this.sendResponse(msgChannel, finalResponse, { statusKind: pp.lastErrorText ? 'error' : 'completed', model: pp.responseModel }); } catch {}
1242
1244
  } else if (pp.lastErrorText) {
1243
1245
  try { await this.sendError(msgChannel, this._formatClaudeError(pp.lastErrorText)); } catch {}
1244
1246
  } else if (!pp.everPostedAnything) {
@@ -0,0 +1,126 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('node:crypto');
4
+ const { spawn } = require('node:child_process');
5
+
6
+ const SUPPORTED = new Set(['claude', 'codex']);
7
+ const quote = value => `'${String(value).replace(/'/g, `'"'"'`)}'`;
8
+ const stripAnsi = text => text.replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, '').replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, '').replace(/\r/g, '');
9
+
10
+ function loginDetails(type, raw) {
11
+ const links = [...raw.matchAll(/\x1b\]8;[^;]*;(https:\/\/[^\x07\x1b]+)/g)].map(m => m[1]);
12
+ const text = stripAnsi(raw);
13
+ links.push(...(text.match(/https:\/\/[^\s<>]+/g) || []));
14
+ const url = links.find(link => {
15
+ try {
16
+ const parsed = new URL(link);
17
+ return !parsed.username && !parsed.password && !parsed.port && (type === 'codex'
18
+ ? parsed.hostname === 'auth.openai.com' && parsed.pathname === '/codex/device'
19
+ : ['claude.ai', 'claude.com'].includes(parsed.hostname) && parsed.pathname.endsWith('/oauth/authorize'));
20
+ } catch { return false; }
21
+ });
22
+ return { url, code: type === 'codex' ? (text.match(/\b[A-Z0-9]{4}-[A-Z0-9]{4,6}\b/) || [])[0] : undefined };
23
+ }
24
+
25
+ /** Native CLI owns OAuth and stores its credentials. Never relay its raw output. */
26
+ class BrowserLogin {
27
+ constructor({ spawnProcess = spawn, verify, onDone = () => {} } = {}) {
28
+ this.spawnProcess = spawnProcess;
29
+ this.verify = verify;
30
+ this.onDone = onDone;
31
+ this.sessions = new Map();
32
+ }
33
+
34
+ start(owner, type, binary, env, platform = process.platform) {
35
+ if (!SUPPORTED.has(type) || !['linux', 'darwin'].includes(platform)) throw new Error('Browser sign-in is not supported on this device.');
36
+ if (!binary || !binary.startsWith('/')) throw new Error('Install this agent on the device before signing in.');
37
+ for (const session of this.sessions.values()) {
38
+ if (session.type === type && ['starting', 'waiting'].includes(session.status)) {
39
+ if (session.owner !== owner) throw new Error('Another sign-in is already running on this device.');
40
+ this.cancel(owner, session.id);
41
+ }
42
+ }
43
+ const args = type === 'codex' ? ['login', '--device-auth'] : ['auth', 'login'];
44
+ // CLI links must not wrap at the pseudo-terminal's default 80 columns.
45
+ const command = `stty cols 500 rows 60; exec ${[binary, ...args].map(quote).join(' ')}`;
46
+ const scriptArgs = platform === 'darwin' ? ['-q', '/dev/null', '/bin/sh', '-c', command]
47
+ : ['-q', '-e', '-c', command, '/dev/null'];
48
+ const cleanEnv = { ...env, BROWSER: '/usr/bin/false', COLUMNS: '500', LINES: '60', TERM: 'xterm-256color' };
49
+ for (const key of Object.keys(cleanEnv)) if (/API_KEY|AUTH_TOKEN|OAUTH_TOKEN|BASE_URL/.test(key)) delete cleanEnv[key];
50
+ // Node implements stdin pipes as sockets on macOS. BSD script rejects
51
+ // tcgetattr's ENOTSUP on those; cat gives it an ordinary POSIX pipe.
52
+ const program = platform === 'darwin' ? '/bin/bash' : 'script';
53
+ const programArgs = platform === 'darwin'
54
+ ? ['-c', `exec ${['script', ...scriptArgs].map(quote).join(' ')} < <(cat)`] : scriptArgs;
55
+ const proc = this.spawnProcess(program, programArgs, { env: cleanEnv, stdio: ['pipe', 'pipe', 'pipe'], detached: true });
56
+ const session = { id: crypto.randomUUID(), owner, type, proc, status: 'starting', raw: '', expiresAt: Date.now() + 10 * 60_000 };
57
+ this.sessions.set(session.id, session);
58
+ const finish = (status) => {
59
+ session.status = status;
60
+ session.raw = '';
61
+ session.url = undefined;
62
+ session.code = undefined;
63
+ clearTimeout(session.timer);
64
+ };
65
+ const receive = chunk => {
66
+ if (!['starting', 'waiting'].includes(session.status)) return;
67
+ session.raw = (session.raw + chunk.toString()).slice(-64_000);
68
+ const details = loginDetails(type, session.raw);
69
+ if (details.url) Object.assign(session, details, { status: 'waiting' });
70
+ };
71
+ proc.stdout.on('data', receive);
72
+ proc.stderr.on('data', receive);
73
+ proc.on('error', () => finish('failed'));
74
+ proc.stdin.on('error', () => finish('failed'));
75
+ proc.on('exit', async code => {
76
+ proc.stdin.destroy?.();
77
+ if (!['starting', 'waiting'].includes(session.status)) return;
78
+ try {
79
+ const ready = code === 0 && await this.verify(type);
80
+ if (!['starting', 'waiting'].includes(session.status)) return;
81
+ finish(ready ? 'done' : 'failed');
82
+ if (ready) this.onDone(type);
83
+ } catch { finish('failed'); }
84
+ });
85
+ session.timer = setTimeout(() => this.cancel(owner, session.id), 10 * 60_000);
86
+ session.timer.unref?.();
87
+ const cleanup = setTimeout(() => { this.cancel(owner, session.id); this.sessions.delete(session.id); }, 15 * 60_000);
88
+ cleanup.unref?.();
89
+ return this.read(owner, session.id);
90
+ }
91
+
92
+ session(owner, id) {
93
+ const session = this.sessions.get(id);
94
+ if (!session || session.owner !== owner) throw new Error('Sign-in expired. Start again.');
95
+ return session;
96
+ }
97
+
98
+ read(owner, id) {
99
+ const { type, status, url, code, expiresAt } = this.session(owner, id);
100
+ return { sessionId: id, type, status, url, code, expiresAt };
101
+ }
102
+
103
+ input(owner, id, code) {
104
+ const session = this.session(owner, id);
105
+ if (session.type !== 'claude' || session.status !== 'waiting' || session.sent || typeof code !== 'string' || !/^[\x21-\x7e]{1,4096}$/.test(code)) throw new Error('Start a new sign-in and paste the complete authorization code.');
106
+ session.sent = true;
107
+ session.raw = '';
108
+ session.proc.stdin.write(`${code}\r`);
109
+ return this.read(owner, id);
110
+ }
111
+
112
+ cancel(owner, id) {
113
+ const session = this.session(owner, id);
114
+ if (['starting', 'waiting'].includes(session.status)) {
115
+ session.status = 'cancelled';
116
+ session.raw = ''; session.url = undefined; session.code = undefined;
117
+ clearTimeout(session.timer);
118
+ try { process.kill(-session.proc.pid, 'SIGTERM'); } catch { session.proc.kill(); }
119
+ }
120
+ return this.read(owner, id);
121
+ }
122
+
123
+ close() { for (const session of this.sessions.values()) this.cancel(session.owner, session.id); }
124
+ }
125
+
126
+ module.exports = { BrowserLogin, loginDetails };
@@ -0,0 +1,68 @@
1
+ 'use strict';
2
+
3
+ // The workspace relays ciphertext. The private key never leaves this device.
4
+ const crypto = require('node:crypto');
5
+ const fs = require('node:fs');
6
+ const path = require('node:path');
7
+ const ALGORITHM = 'RSA-OAEP-256+A256GCM';
8
+
9
+ function deviceCredentialKey(configDir) {
10
+ const filename = path.join(configDir, 'credential-key.pem');
11
+ fs.mkdirSync(configDir, { recursive: true, mode: 0o700 });
12
+ let pem;
13
+ try { pem = fs.readFileSync(filename, 'utf8'); }
14
+ catch (error) {
15
+ if (error.code !== 'ENOENT') throw error;
16
+ const pair = crypto.generateKeyPairSync('rsa', { modulusLength: 3072 });
17
+ const generated = pair.privateKey.export({ type: 'pkcs8', format: 'pem' });
18
+ // Another command can ask at the same time. Only the first key wins.
19
+ try { fs.writeFileSync(filename, generated, { mode: 0o600, flag: 'wx' }); }
20
+ catch (writeError) { if (writeError.code !== 'EEXIST') throw writeError; }
21
+ pem = fs.readFileSync(filename, 'utf8');
22
+ }
23
+ const privateKey = crypto.createPrivateKey(pem);
24
+ const publicDer = crypto.createPublicKey(privateKey).export({ type: 'spki', format: 'der' });
25
+ const keyId = crypto.createHash('sha256').update(publicDer).digest('hex');
26
+ return { privateKey, publicKey: publicDer.toString('base64'), keyId, algorithm: ALGORITHM };
27
+ }
28
+
29
+ function credentialContext(nodeId, action, args) {
30
+ const context = [nodeId, action, args.name || '', args.type || '', args.model || '', args.baseUrl || ''];
31
+ if (action === 'login_input') context.push(args.sessionId || '');
32
+ return JSON.stringify(context);
33
+ }
34
+
35
+ function decryptCredentials(configDir, nodeId, action, args) {
36
+ const envelope = args.encryptedCredentials;
37
+ if (!envelope) return args;
38
+ if (!['create_agent', 'configure_agent', 'login_input'].includes(action) || args.apiKey || args.config || args.modelAccessId) {
39
+ throw new Error('Invalid encrypted credential command');
40
+ }
41
+ const key = deviceCredentialKey(configDir);
42
+ if (envelope.algorithm !== ALGORITHM || envelope.keyId !== key.keyId ||
43
+ !Number.isFinite(envelope.expiresAt) || envelope.expiresAt < Date.now() ||
44
+ envelope.expiresAt > Date.now() + 10 * 60 * 1000) throw new Error('Credential envelope expired or key changed');
45
+ const context = credentialContext(nodeId, action, args);
46
+ const aesKey = crypto.privateDecrypt({ key: key.privateKey, oaepHash: 'sha256', padding: crypto.constants.RSA_PKCS1_OAEP_PADDING }, Buffer.from(envelope.wrappedKey, 'base64'));
47
+ let plaintext;
48
+ try {
49
+ const ciphertext = Buffer.from(envelope.ciphertext, 'base64');
50
+ const decipher = crypto.createDecipheriv('aes-256-gcm', aesKey, Buffer.from(envelope.iv, 'base64'));
51
+ decipher.setAAD(Buffer.from(`${context}\n${envelope.expiresAt}`));
52
+ decipher.setAuthTag(ciphertext.subarray(-16));
53
+ plaintext = Buffer.concat([decipher.update(ciphertext.subarray(0, -16)), decipher.final()]);
54
+ } finally { aesKey.fill(0); }
55
+ let credentials;
56
+ try { credentials = JSON.parse(plaintext.toString('utf8')); }
57
+ finally { plaintext.fill(0); }
58
+ if (!credentials || typeof credentials !== 'object' || Array.isArray(credentials) ||
59
+ Object.keys(credentials).some((k) => !['apiKey', 'config'].includes(k)) ||
60
+ (credentials.apiKey !== undefined && typeof credentials.apiKey !== 'string') ||
61
+ (credentials.config !== undefined && (!credentials.config || typeof credentials.config !== 'object' || Array.isArray(credentials.config) || Object.values(credentials.config).some((v) => typeof v !== 'string')))) {
62
+ throw new Error('Invalid credential fields');
63
+ }
64
+ const { encryptedCredentials, ...publicArgs } = args;
65
+ return { ...publicArgs, ...credentials };
66
+ }
67
+
68
+ module.exports = { deviceCredentialKey, decryptCredentials, credentialContext, ALGORITHM };
package/src/daemon.js CHANGED
@@ -22,6 +22,8 @@ const { hostFreeEnv } = require('./host-agent');
22
22
  const { LogWriter } = require('./log-writer');
23
23
  const { redactDiagnostic } = require('./adapters/health-status');
24
24
  const { installCommandFor } = require('./probe');
25
+ const { deviceCredentialKey, decryptCredentials } = require('./credential-envelope');
26
+ const { BrowserLogin } = require('./browser-login');
25
27
 
26
28
  /** Types whose endpoint is one device-wide config file of their own. None
27
29
  * left: OpenClaw gives each keyed agent a private store (adapters/openclaw.js)
@@ -180,7 +182,7 @@ class Daemon {
180
182
  this._cliModelsInFlight = new Set(); // sign-in keys whose CLI is being asked right now
181
183
  this._cliModelsStartupTimer = null;
182
184
  this._cliModelsInterval = null;
183
- this._reloadInFlight = null; // serialize concurrent _reload() calls
185
+ this._reloadInFlight = null; // serialize config reloads and explicit restarts
184
186
  this._runtimeRepairs = new Map(); // agent type → in-flight reinstall of its supported version
185
187
  }
186
188
 
@@ -518,12 +520,40 @@ class Daemon {
518
520
  * workspace knows this device has `agn login`; for an older device it shows
519
521
  * the CLI's own login command instead.
520
522
  */
523
+ /** Install a missing CLI before its native browser sign-in, without creating an agent. */
524
+ async _prepareBrowserLogin(type) {
525
+ if (!['claude', 'codex'].includes(type) || !['linux', 'darwin'].includes(process.platform)) {
526
+ throw new Error('Browser sign-in is not supported for this agent or device.');
527
+ }
528
+ const { Installer } = require('./installer');
529
+ const installer = new Installer(this.registry, this.config.configDir);
530
+ const existing = installer.which(type);
531
+ if (existing) return existing;
532
+ this._loginInstalls ??= new Map();
533
+ if (!this._loginInstalls.has(type)) {
534
+ const installing = (async () => {
535
+ const result = await this._runAgn(['install', type], { timeoutMs: 300_000 });
536
+ const binary = result.code === 0 && installer.which(type);
537
+ if (!binary) throw new Error('Could not install the agent for browser sign-in. Please retry.');
538
+ this._refreshRuntimes().then(() => this._nodeHeartbeat()).catch(() => {});
539
+ return binary;
540
+ })();
541
+ this._loginInstalls.set(type, installing);
542
+ }
543
+ try { return await this._loginInstalls.get(type); }
544
+ finally { this._loginInstalls.delete(type); }
545
+ }
546
+
521
547
  _heartbeatRuntimes() {
522
548
  return (this._runtimes || []).map((rt) => {
523
549
  if (!rt) return rt;
524
550
  // Whatever `agn login` can sign in, which is wider than _hasCliSignIn:
525
551
  // OpenCode signs in without the registry marking it a sign-in agent.
526
552
  const out = this._agnLoginFor(rt.type) ? { ...rt, loginCommand: agnLoginCommand(rt.type) } : rt;
553
+ if (['claude', 'codex'].includes(rt.type) && ['linux', 'darwin'].includes(process.platform)) {
554
+ this._browserLoginSupported ??= !!whichBinary('script');
555
+ if (this._browserLoginSupported) out.browserLogin = true;
556
+ }
527
557
  if (!out.installed || !supportsCliModels(rt.type)) return out;
528
558
  const listed = this._cliModels[this._cliModelsKey(this._signInAgent(rt.type))];
529
559
  return { ...out, cliModels: (listed && listed.models) || null };
@@ -1104,7 +1134,7 @@ class Daemon {
1104
1134
 
1105
1135
  async _runNodeCommand(n, cmd) {
1106
1136
  const action = cmd.action;
1107
- const args = cmd.args || {};
1137
+ let args = cmd.args || {};
1108
1138
  const name = (args.name || '').trim();
1109
1139
  let ok = false;
1110
1140
  let message = '';
@@ -1117,6 +1147,7 @@ async _runNodeCommand(n, cmd) {
1117
1147
  // belong to another one (they surface in no roster of ours either).
1118
1148
  const AGENT_SCOPED = new Set(['start_agent', 'stop_agent', 'remove_agent', 'configure_agent']);
1119
1149
  try {
1150
+ args = decryptCredentials(this.config.configDir, n.node_id, action, args);
1120
1151
  if (AGENT_SCOPED.has(action)) {
1121
1152
  const existing = this.config.getAgent(name);
1122
1153
  if (!existing || !this._agentOnNodeWorkspace(existing, n)) {
@@ -1252,6 +1283,31 @@ async _runNodeCommand(n, cmd) {
1252
1283
  data = { probe };
1253
1284
  // Push the fresh result right away (same pattern as detect_runtimes).
1254
1285
  this._nodeHeartbeat();
1286
+ } else if (['login_start', 'login_status', 'login_input', 'login_cancel'].includes(action)) {
1287
+ if (!this._browserLogins) this._browserLogins = new BrowserLogin({
1288
+ verify: async (type) => {
1289
+ const result = await this._runAgn(['runtimes', '--json', '--types', type], { timeoutMs: 30_000 });
1290
+ return result.code === 0 && JSON.parse(result.stdout).some(rt => rt.type === type && rt.signedIn === true);
1291
+ },
1292
+ onDone: () => { this._refreshRuntimes().then(() => this._nodeHeartbeat()).catch(() => {}); },
1293
+ });
1294
+ const owner = `${n.workspace_id}:${n.node_id}`;
1295
+ if (action === 'login_start') {
1296
+ const type = args.type;
1297
+ const binary = await this._prepareBrowserLogin(type);
1298
+ data = this._browserLogins.start(owner, type, binary, getEnhancedEnv());
1299
+ } else if (action === 'login_input') {
1300
+ if (!cmd.args?.encryptedCredentials) throw new Error('Authorization codes must be encrypted for this device.');
1301
+ data = this._browserLogins.input(owner, args.sessionId, args.config?.code);
1302
+ } else if (action === 'login_cancel') data = this._browserLogins.cancel(owner, args.sessionId);
1303
+ else data = this._browserLogins.read(owner, args.sessionId);
1304
+ ok = true;
1305
+ message = 'Sign-in status updated';
1306
+ } else if (action === 'credential_key') {
1307
+ const { privateKey, ...publicKey } = deviceCredentialKey(this.config.configDir);
1308
+ data = publicKey;
1309
+ ok = true;
1310
+ message = 'Device encryption ready';
1255
1311
  } else if (action === 'detect_runtimes') {
1256
1312
  await this._refreshRuntimes();
1257
1313
  // Push the fresh detection right away rather than waiting for the next
@@ -1282,7 +1338,7 @@ async _runNodeCommand(n, cmd) {
1282
1338
  }
1283
1339
  } catch (e) {
1284
1340
  ok = false;
1285
- message = e.message || String(e);
1341
+ message = cmd.args?.encryptedCredentials ? 'Encrypted setup failed. Check the agent on the device and try again.' : e.message || String(e);
1286
1342
  // Undo a create that failed after `agn create`: the entry stays in config
1287
1343
  // without this workspace's binding, so no roster here shows it, the
1288
1344
  // workspace's failed card cannot remove it, and every retry under the
@@ -1495,6 +1551,7 @@ async _runNodeCommand(n, cmd) {
1495
1551
  async stop() {
1496
1552
  if (this._shuttingDown) return;
1497
1553
  this._shuttingDown = true;
1554
+ this._browserLogins?.close();
1498
1555
  this._log('Shutting down...');
1499
1556
 
1500
1557
  if (this._statusInterval) clearInterval(this._statusInterval);
@@ -1582,7 +1639,11 @@ async _runNodeCommand(n, cmd) {
1582
1639
  /**
1583
1640
  * Restart a single agent by name.
1584
1641
  */
1585
- async restartAgent(agentName) {
1642
+ restartAgent(agentName) {
1643
+ return this._queueConfigOperation(() => this._restartAgentUnsafe(agentName));
1644
+ }
1645
+
1646
+ async _restartAgentUnsafe(agentName) {
1586
1647
  // Set state to 'starting' immediately so UI never sees 'stopped' during restart
1587
1648
  if (this._processes[agentName]) {
1588
1649
  this._processes[agentName].state = 'starting';
@@ -2129,7 +2190,8 @@ async _runNodeCommand(n, cmd) {
2129
2190
  this._log(`${name} adapter error: ${info.lastError}`, 'error');
2130
2191
  }
2131
2192
 
2132
- delete this._adapters[name];
2193
+ // A forced stop can outlive its slot. Never remove a replacement adapter.
2194
+ if (this._adapters[name] === adapter) delete this._adapters[name];
2133
2195
 
2134
2196
  // Final state: a clean stop (user stop / daemon shutdown) is NEVER an error.
2135
2197
  // A terminal failure recorded by the adapter (join/heartbeat/session-revoked)
@@ -2360,25 +2422,21 @@ async _runNodeCommand(n, cmd) {
2360
2422
  } catch {}
2361
2423
  }
2362
2424
 
2363
- async _reload() {
2364
- // Serialize reloads. fs.watch, the 'reload' command, and SIGHUP can
2365
- // all fire concurrently. Without a mutex, two _reload() calls in flight
2366
- // may both observe the same stale `this._adapters[name]` entry between
2367
- // stopAgent() and _launchAgent(), leaving a ghost adapter running
2368
- // alongside the new one → duplicate bot replies per message.
2369
- if (this._reloadInFlight) {
2370
- // Wait for the in-flight reload to finish, then run once more
2371
- // (the config may have changed again since it started).
2372
- this._reloadInFlight = this._reloadInFlight.then(
2373
- () => this._reloadUnsafe(),
2374
- () => this._reloadUnsafe(),
2375
- );
2376
- return this._reloadInFlight;
2377
- }
2378
- this._reloadInFlight = this._reloadUnsafe().finally(() => {
2379
- this._reloadInFlight = null;
2425
+ _queueConfigOperation(operation) {
2426
+ // `agn connect` sends restart while fs.watch is reconciling the preceding
2427
+ // create. Both must finish in order: a reload holding the pre-connect
2428
+ // config must not stop the newly connected adapter or relaunch it locally.
2429
+ const previous = this._reloadInFlight || Promise.resolve();
2430
+ const pending = previous.then(operation, operation);
2431
+ const settled = pending.finally(() => {
2432
+ if (this._reloadInFlight === settled) this._reloadInFlight = null;
2380
2433
  });
2381
- return this._reloadInFlight;
2434
+ this._reloadInFlight = settled;
2435
+ return settled;
2436
+ }
2437
+
2438
+ _reload() {
2439
+ return this._queueConfigOperation(() => this._reloadUnsafe());
2382
2440
  }
2383
2441
 
2384
2442
  async _reloadUnsafe() {