@openagents-org/agent-launcher 0.2.229 → 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.229",
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) {
@@ -82,6 +82,7 @@ const FAILURE_MESSAGES = {
82
82
  process_crashed: 'CodeArts Agent exited unexpectedly. Open diagnostics or retry.',
83
83
  cwd_unavailable: "CodeArts Agent's working directory is not accessible. Check the agent's configured path (or agent home) permissions.",
84
84
  config_invalid: 'CodeArts Agent would not start because one of its config files is invalid — the file and what is wrong with it are below. Correct or remove that entry, then retry.',
85
+ malformed_tool_call: "The model sent back a tool call CodeArts Agent could not read (it named no tool), so the run stopped. This comes from the model or the endpoint serving it, not from this agent's settings: retry, and if it keeps happening, switch this agent to another model or provider.",
85
86
  unknown_error: 'CodeArts Agent failed for an undetermined reason. Open diagnostics or retry.',
86
87
  };
87
88
 
@@ -522,6 +522,11 @@ class CodexAdapter extends BaseAdapter {
522
522
  // error left in daemon.log. Say it stopped, and why.
523
523
  if (CodexAdapter._endedEarly(result)) {
524
524
  await this._sendRunFailure(msgChannel, result, { partial: true });
525
+ // Failed after some text (an auto-compaction refused mid-turn):
526
+ // the reply is posted, so no rerun, but the next message must not
527
+ // resume the same thread and fail again.
528
+ const unusable = threadId ? CodexAdapter._unusableThread(result) : null;
529
+ if (unusable) await this._dropThread(msgChannel, unusable);
525
530
  }
526
531
  return;
527
532
  } else if (!planRetried && !this._effectiveModel() && !this._customProvider
@@ -549,17 +554,13 @@ class CodexAdapter extends BaseAdapter {
549
554
  } catch {}
550
555
  attempt--;
551
556
  continue;
552
- } else if (threadId && attempt === 0 && CodexAdapter._threadTooLarge(result)) {
553
- // The thread holds an item the API will no longer take, and codex
554
- // sends the whole thread with every turn, so every later message in
555
- // this channel failed the same way. Only a new thread runs again.
556
- this._log(`Thread ${threadId} for ${msgChannel} exceeds an API limit; starting a new one`);
557
- delete this._channelThreads[msgChannel];
558
- this._saveSessions();
559
- try {
560
- await this.sendStatus(msgChannel, 'This Codex conversation grew past what the model API accepts, '
561
- + 'so it continues in a new one. Earlier context in this thread is not carried over.');
562
- } catch {}
557
+ } else if (threadId && attempt === 0 && CodexAdapter._unusableThread(result)) {
558
+ // The thread holds something the service will no longer take (an
559
+ // item over an API limit, or reasoning sealed for another account),
560
+ // and codex resends the whole thread with every turn, so every later
561
+ // message in this channel failed the same way. Only a new thread
562
+ // runs again.
563
+ await this._dropThread(msgChannel, CodexAdapter._unusableThread(result));
563
564
  continue;
564
565
  } else if (result.exitCode !== 0 && threadId && attempt === 0 && !result.turnStarted && !CodexAdapter._serviceRefused(result)) {
565
566
  // Stale thread — clear and retry fresh. Only when the turn never
@@ -572,13 +573,16 @@ class CodexAdapter extends BaseAdapter {
572
573
  delete this._channelThreads[msgChannel];
573
574
  this._saveSessions();
574
575
  continue;
575
- } else if (fromAgent && CodexAdapter._finishedQuietly(result)) {
576
+ } else if (fromAgent && !result.ranTools && CodexAdapter._finishedQuietly(result)) {
576
577
  // Another agent wrote ("received", "noted") and codex ended its
577
578
  // turn with nothing to add, as the prompt tells it to. Posting
578
579
  // "Codex couldn't run" for that read as a failure: the daily errors
579
580
  // dashboard of 2026-11-17 had one agent post it 14 times in two
580
581
  // minutes while two agents acknowledged each other. A status says
581
- // so and wakes nobody. A person's message still gets the error.
582
+ // so and wakes nobody. A person's message still gets the error, and
583
+ // so does a turn that ran commands or edited files and then said
584
+ // nothing: that was a task, and whoever asked for it has to hear
585
+ // that no answer came.
582
586
  this._log(`Turn from another agent in ${msgChannel} ended with no reply; not posting one`);
583
587
  try { await this.sendStatus(msgChannel, 'Nothing to add, so no reply was posted.'); } catch {}
584
588
  return;
@@ -637,6 +641,7 @@ class CodexAdapter extends BaseAdapter {
637
641
  let lastErrorMessage = '';
638
642
  let turnFailed = false;
639
643
  let turnStarted = false;
644
+ let ranTools = false;
640
645
  let reconnectNoted = false;
641
646
  let _pendingLines = Promise.resolve();
642
647
 
@@ -678,6 +683,7 @@ class CodexAdapter extends BaseAdapter {
678
683
  try { await this.sendThinking(msgChannel, item.text); } catch {}
679
684
  } else if (item.type === 'command_execution') {
680
685
  hasToolUseSinceLastText = true;
686
+ ranTools = true;
681
687
  const cmdText = (item.command || '').slice(0, 200);
682
688
  const exitCode = item.exit_code;
683
689
  const output = (item.output || '').slice(0, 500);
@@ -689,6 +695,7 @@ class CodexAdapter extends BaseAdapter {
689
695
  this._log(`Command: ${cmdText} → exit ${exitCode}`);
690
696
  } else if (item.type === 'file_change') {
691
697
  hasToolUseSinceLastText = true;
698
+ ranTools = true;
692
699
  // codex reports the edited files in `changes`; `filename` is the
693
700
  // legacy shape and was always empty on current CLIs.
694
701
  const filename = Array.isArray(item.changes) && item.changes.length
@@ -754,6 +761,7 @@ class CodexAdapter extends BaseAdapter {
754
761
  errorMessage: lastErrorMessage,
755
762
  turnFailed,
756
763
  turnStarted,
764
+ ranTools,
757
765
  });
758
766
  });
759
767
 
@@ -894,6 +902,52 @@ class CodexAdapter extends BaseAdapter {
894
902
  return /array_above_max_length|context_length_exceeded/i.test(reason);
895
903
  }
896
904
 
905
+ /**
906
+ * Why the channel's thread can no longer be resumed, as `{ log, status }`
907
+ * (what the daemon log and the channel are told), or null when it can.
908
+ */
909
+ static _unusableThread(result) {
910
+ if (CodexAdapter._threadTooLarge(result)) {
911
+ return {
912
+ log: 'exceeds an API limit',
913
+ status: 'This Codex conversation grew past what the model API accepts, so it continues in a new one. '
914
+ + 'Earlier context in this thread is not carried over.',
915
+ };
916
+ }
917
+ if (CodexAdapter._threadUnverifiable(result)) {
918
+ return {
919
+ log: 'holds content this account cannot verify',
920
+ status: 'Codex could no longer read back this conversation\'s earlier turns (this happens after Codex is '
921
+ + 'signed in to a different account), so it continues in a new one. Earlier context in this thread is not '
922
+ + 'carried over.',
923
+ };
924
+ }
925
+ return null;
926
+ }
927
+
928
+ /** Forget the channel's thread, and say why in the log and the channel. */
929
+ async _dropThread(msgChannel, { log, status }) {
930
+ this._log(`Thread ${this._channelThreads[msgChannel]} for ${msgChannel} ${log}; starting a new one`);
931
+ delete this._channelThreads[msgChannel];
932
+ this._saveSessions();
933
+ try { await this.sendStatus(msgChannel, status); } catch {}
934
+ }
935
+
936
+ /**
937
+ * True when the service could not verify the thread's encrypted reasoning.
938
+ * Seen as `Error running remote compact task: {"error":{"message":"The
939
+ * encrypted content for item rs_… could not be verified. Reason: Encrypted
940
+ * content item_id did not match the target item id.", "code":
941
+ * "invalid_encrypted_content"}}` on every message of two agents, after their
942
+ * user signed Codex in to another ChatGPT account: the items were sealed for
943
+ * the old one, and codex resends them each turn. The run's error, else what
944
+ * its stderr gives as the reason (_stderrReason), as for _threadTooLarge.
945
+ */
946
+ static _threadUnverifiable({ errorMessage, stderr } = {}) {
947
+ const reason = String(errorMessage || '').trim() || CodexAdapter._stderrReason(stderr);
948
+ return /invalid_encrypted_content|encrypted content\b.{0,120}\bcould not be (?:verified|decrypted)/i.test(reason);
949
+ }
950
+
897
951
  /**
898
952
  * True when the model service turned the run away (rate limit, quota,
899
953
  * credentials, network) — nothing to do with the thread being resumed. Such
@@ -95,6 +95,7 @@ const FAILURE_MESSAGES = {
95
95
  cwd_unavailable: "MiMo Code's working directory is not accessible. Check the agent's configured path (or agent home) permissions.",
96
96
  session_missing: 'MiMo Code no longer has this conversation\'s session. Send the message again to start a new one.',
97
97
  config_invalid: 'MiMo Code would not start because one of its config files is invalid — the file and what is wrong with it are below. Correct or remove that entry, then retry.',
98
+ malformed_tool_call: "The model sent back a tool call MiMo Code could not read (it named no tool), so the run stopped. This comes from the model or the endpoint serving it, not from this agent's settings: retry, and if it keeps happening, switch this agent to another model or provider.",
98
99
  unknown_error: 'MiMo Code failed for an undetermined reason. Open diagnostics or retry.',
99
100
  };
100
101
 
@@ -132,6 +132,7 @@ const FAILURE_MESSAGES = {
132
132
  process_crashed: 'OpenCode exited unexpectedly. Open diagnostics or retry.',
133
133
  cwd_unavailable: "OpenCode's working directory is not accessible. Check the agent's configured path (or agent home) permissions.",
134
134
  shared_db_migrated: "OpenCode could not open its session database: a newer OpenCode (2.x, or the OpenCode desktop app) on this device has converted it to a format the OpenCode CLI that OpenAgents runs cannot read, and running it on a database of its own did not help either. Reinstall OpenCode from the launcher, or set OPENCODE_DB in this agent's configuration to the full path of a new file, then retry.",
135
+ malformed_tool_call: "The model sent back a tool call OpenCode could not read (it named no tool), so the run stopped. This comes from the model or the endpoint serving it, not from this agent's settings: retry, and if it keeps happening, switch this agent to another model or provider.",
135
136
  config_invalid: 'OpenCode would not start because one of its config files is invalid — the file and what is wrong with it are below. OpenCode reads it on every run, so every message fails until it is fixed: correct or remove that entry, then retry.',
136
137
  unknown_error: 'OpenCode failed for an undetermined reason. Open diagnostics or retry.',
137
138
  };
@@ -301,7 +302,8 @@ class OpenCodeAdapter extends BaseAdapter {
301
302
  * their rules alone.
302
303
  */
303
304
  static _userRulesExternalDirs(env, runCwd) {
304
- const mentions = (text) => /external_directory|"permission"\s*:\s*("|\{\s*"\*")/.test(String(text || ''));
305
+ const mentions = (text) => /external_directory/.test(String(text || ''))
306
+ || OpenCodeAdapter._setsEveryPermission(String(text || ''));
305
307
  if (mentions(env.OPENCODE_CONFIG_CONTENT)) return true;
306
308
  const home = env.HOME || env.USERPROFILE || os.homedir();
307
309
  const globalDir = path.join(env.XDG_CONFIG_HOME || path.join(home, '.config'), 'opencode');
@@ -319,6 +321,38 @@ class OpenCodeAdapter extends BaseAdapter {
319
321
  });
320
322
  }
321
323
 
324
+ /**
325
+ * Whether a config's text sets every permission at once: `"permission":
326
+ * "deny"`, or a `"*"` key anywhere in the permission object — not only as
327
+ * its first key: `{"bash": {"git *": "allow"}, "*": "deny"}` was read as
328
+ * no rule, and the external_directory allow then went over a lockdown.
329
+ * Only the object's own keys count, not a `"*"` inside a nested rule.
330
+ */
331
+ static _setsEveryPermission(text) {
332
+ const re = /"permission"\s*:\s*/g;
333
+ for (let m = re.exec(text); m; m = re.exec(text)) {
334
+ let i = m.index + m[0].length;
335
+ if (text[i] === '"') return true;
336
+ if (text[i] !== '{') continue;
337
+ let depth = 0;
338
+ let inString = false;
339
+ for (let start = i; i < text.length; i++) {
340
+ const c = text[i];
341
+ if (inString) {
342
+ if (c === '\\') i++;
343
+ else if (c === '"') {
344
+ inString = false;
345
+ // A key of the permission object itself.
346
+ if (depth === 1 && text.slice(start, i + 1) === '"*"' && /^\s*:/.test(text.slice(i + 1))) return true;
347
+ }
348
+ } else if (c === '"') { inString = true; start = i; }
349
+ else if (c === '{') depth++;
350
+ else if (c === '}' && --depth === 0) break;
351
+ }
352
+ }
353
+ return false;
354
+ }
355
+
322
356
  _spawnEnv(channel, { contextFile = null } = {}) {
323
357
  const env = { ...(this.agentEnv || process.env) };
324
358
  if (!env.OPENCODE_DB && fs.existsSync(ownDbPath())) env.OPENCODE_DB = ownDbPath();
@@ -1324,6 +1358,12 @@ class OpenCodeAdapter extends BaseAdapter {
1324
1358
  else if (roles[part.messageID] === 'assistant') emit(part);
1325
1359
  } else if (ev.type === 'message.part.delta' && props.sessionID === sid) {
1326
1360
  watchdog.touch();
1361
+ } else if ((ev.type === 'message.part.updated' && props.part && children.has(props.part.sessionID))
1362
+ || (ev.type === 'message.part.delta' && children.has(props.sessionID))) {
1363
+ // A subagent at work is the turn at work: its parts are not this
1364
+ // channel's reply, but a long task run in a child session left the
1365
+ // turn's own session quiet until the watchdog stopped it.
1366
+ watchdog.touch();
1327
1367
  }
1328
1368
  });
1329
1369
  const stopping = () => this._stoppingChannels.has(msgChannel);
@@ -1817,6 +1857,14 @@ class OpenCodeAdapter extends BaseAdapter {
1817
1857
  category = 'network_error';
1818
1858
  } else if (has(/\b5\d\d\b|server error|internal server|bad gateway|service unavailable|gateway timeout|server is busy|system is busy|系统繁忙|服务繁忙|đang bận/)) {
1819
1859
  category = 'provider_server_error';
1860
+ } else if (has(/expected '?function\.name'? to be a string/)) {
1861
+ // The provider streamed a tool call with no tool name, and the AI SDK
1862
+ // under OpenCode refused it: "Expected 'function.name' to be a string."
1863
+ // Six times in a row from one user's agents on GLM / DeepSeek models
1864
+ // (daily errors dashboard, 2026-11-18), each read as "OpenCode failed
1865
+ // for an undetermined reason". After the provider categories: a key,
1866
+ // credit or network failure in the same output is the cause to report.
1867
+ category = 'malformed_tool_call';
1820
1868
  } else if (has(/timeout|timed out/)) {
1821
1869
  category = 'timeout';
1822
1870
  } else if (err) {
@@ -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() {
package/src/probe.js CHANGED
@@ -69,6 +69,7 @@ const CODE = {
69
69
  CLI_ERROR: 'cli_error',
70
70
  INSTALL_INCOMPLETE: 'install_incomplete',
71
71
  ENDPOINT_INCOMPATIBLE: 'endpoint_incompatible',
72
+ CLIENT_ONLY: 'client_only',
72
73
  };
73
74
 
74
75
  const BENIGN_OUTPUT = BENIGN_CLI_OUTPUT;
@@ -172,7 +173,7 @@ function classifyOutputText(text) {
172
173
  // "Model 'x' is not available. This gateway only allows: …" is how the
173
174
  // OpenAgents gateway refuses a model; read as a CLI error it sent people to
174
175
  // a terminal to debug a model name.
175
- if (/unrecognized_model|model_not_found|invalid model|no such model|issue with the selected model|unknown model|model.{0,40}(does not exist|not found|not exist|is not supported|is not available)/.test(text)) return CODE.BAD_MODEL;
176
+ if (/unrecognized_model|model_not_found|invalid model|no such model|model must be a (?:valid )?model id|issue with the selected model|unknown model|model.{0,40}(does not exist|not found|not exist|is not supported|is not available)/.test(text)) return CODE.BAD_MODEL;
176
177
  if (/\b50[234]\b|service (is )?(temporarily )?unavailable|temporarily unavailable|bad gateway|gateway time-?out/.test(text)) return CODE.SERVICE_UNAVAILABLE;
177
178
  return null;
178
179
  }
@@ -294,6 +295,9 @@ function buildGuidance(code, entry, agentEnv, extra = {}) {
294
295
  async function directApiVerdict(agentEnv, entry, model, baseUrl, protocol) {
295
296
  const res = await callLLM(agentEnv, model, baseUrl, protocol);
296
297
  if (!res || res.success) return null;
298
+ // The endpoint turned the test away for not being the agent's CLI; that
299
+ // says nothing about the CLI's own run.
300
+ if (clientOnlyRefusal(res.error)) return null;
297
301
  const code = directFailureCode(res.error, protocol);
298
302
  if (code === CODE.CLI_ERROR) return null;
299
303
  return {
@@ -386,6 +390,28 @@ function directFailureCode(error, protocol) {
386
390
  return classifyFailure(error, {});
387
391
  }
388
392
 
393
+ /**
394
+ * A relay that serves only the coding CLIs it recognises, and refused the
395
+ * direct test for not being one: `HTTP 403: {"error":{"code":
396
+ * "client_not_allowed","message":"本站仅支持编程客户端使用:Codex、Claude Code、
397
+ * OpenCode、…"}}`. Read as any 403, it came back "invalid API key" — eight
398
+ * times in a minute for one OpenCode agent on the daily errors dashboard of
399
+ * 2026-11-18 — for a key the CLI itself may well be let through with. Only
400
+ * these words: an English "only allows authorized clients" is as likely a
401
+ * key refused for real.
402
+ */
403
+ const CLIENT_ONLY_REFUSAL = /client_not_allowed|仅支持[^。.\n]{0,24}客户端/i;
404
+
405
+ /** The start of a refusal, where its code and reason are, scrubbed and capped. */
406
+ function head(text, cap) {
407
+ const s = scrub(String(text || '').trim());
408
+ return s.length > cap ? `${s.slice(0, cap)}…` : s;
409
+ }
410
+
411
+ function clientOnlyRefusal(error) {
412
+ return CLIENT_ONLY_REFUSAL.test(String(error || ''));
413
+ }
414
+
389
415
  /** The field a refusing endpoint named (`"param":"client_metadata"`), or ''. */
390
416
  function refusedParam(error) {
391
417
  const m = /"param"\s*:\s*"([^"]{1,64})"/.exec(String(error || ''));
@@ -912,6 +938,16 @@ async function probeAgentType(connector, type, opts = {}) {
912
938
  reply: tail(res.response || '', REPLY_CAP),
913
939
  });
914
940
  }
941
+ // Could not be checked, not failed: the endpoint only answers the coding
942
+ // CLIs it recognises, and this test is not one of them.
943
+ if (res && clientOnlyRefusal(res.error)) {
944
+ return done({
945
+ ok: null, method: 'llm_api', code: CODE.CLIENT_ONLY,
946
+ message: 'This endpoint only takes requests from the coding tools it recognises, and it turned away the '
947
+ + `connection test, which calls it directly (${head(res.error, 240)}). The key and model could not be `
948
+ + 'checked ahead of time; send the agent a message, and a normal reply confirms it works.',
949
+ });
950
+ }
915
951
  const code = directFailureCode(res && res.error, protocol);
916
952
  return done({
917
953
  ok: false, method: 'llm_api', code,