@openagents-org/agent-launcher 0.2.205 → 0.2.207

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.
@@ -0,0 +1,60 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * The model an agent's env selects: the variable its adapter really reads.
5
+ *
6
+ * Each type names it its own way (CODEX_MODEL, ANTHROPIC_MODEL, KIMI_MODEL),
7
+ * and the workspace and the launcher do not save it the same way: the
8
+ * workspace writes LLM_MODEL, which env resolution maps onto the type's own
9
+ * variable, while the launcher writes the type's variable directly. Whatever
10
+ * reads the model has to look where the adapter looks. The smoke test read
11
+ * LLM_MODEL alone, so a codex agent set up in the launcher, answering fine on
12
+ * its CODEX_MODEL, was tested on a guessed "gpt-4o-mini" its relay refused.
13
+ */
14
+
15
+ const { modelKeys } = require('./env');
16
+
17
+ /**
18
+ * Model variables whose name does not follow `<TYPE>_MODEL`. Only the ones an
19
+ * adapter really reads: `<TYPE>_MODEL` is tried first and LLM_MODEL last, so
20
+ * nothing else needs an entry here.
21
+ */
22
+ const MODEL_ENV_ALIASES = {
23
+ claude: ['ANTHROPIC_MODEL', 'CLAUDE_MODEL'],
24
+ gemini: ['GEMINI_MODEL', 'GOOGLE_GEMINI_MODEL'],
25
+ antigravity: ['ANTIGRAVITY_MODEL', 'AGY_MODEL'],
26
+ codex: ['CODEX_MODEL', 'OPENCLAW_MODEL'],
27
+ };
28
+
29
+ /**
30
+ * Where to look, in order. `registry`, when given, adds the type's own model
31
+ * fields and the variable LLM_MODEL resolves to.
32
+ */
33
+ function modelVarsFor(agentType, registry) {
34
+ const type = String(agentType || '').toUpperCase().replace(/[^A-Z0-9]+/g, '_');
35
+ const vars = [...(type ? [`${type}_MODEL`] : []), ...(MODEL_ENV_ALIASES[agentType] || [])];
36
+ if (registry) {
37
+ try {
38
+ for (const key of modelKeys(agentType, registry)) if (key !== 'LLM_MODEL') vars.push(key);
39
+ } catch {}
40
+ }
41
+ vars.push('LLM_MODEL');
42
+ return [...new Set(vars)];
43
+ }
44
+
45
+ /**
46
+ * The model `env` selects for an agent of `agentType`, or null when it sets
47
+ * none and the agent runs on its CLI's default. Pass the env the agent is
48
+ * launched on (saved and resolved): resolution has already put LLM_MODEL
49
+ * where the adapter reads it.
50
+ */
51
+ function configuredModel(agentType, env, registry) {
52
+ if (!env) return null;
53
+ for (const key of modelVarsFor(agentType, registry)) {
54
+ const value = String(env[key] || '').trim();
55
+ if (value) return value;
56
+ }
57
+ return null;
58
+ }
59
+
60
+ module.exports = { MODEL_ENV_ALIASES, modelVarsFor, configuredModel };
package/src/cli.js CHANGED
@@ -6,6 +6,7 @@ require('./win-console').installWindowsHideDefault();
6
6
 
7
7
  const { AgentConnector, Daemon } = require('./index');
8
8
  const { hasCredentialMetadata, formatAuthGuidance } = require('./auth-guidance');
9
+ const { AUTH_MODE_KEY, CLI_LOGIN, isCliLogin } = require('./env');
9
10
 
10
11
  // ---------------------------------------------------------------------------
11
12
  // Arg parsing
@@ -366,16 +367,33 @@ async function cmdRuntimes(connector, flags) {
366
367
  ? new Set(flags.types.split(',').map((s) => s.trim()).filter(Boolean))
367
368
  : null;
368
369
  const catalog = connector.registry.getCatalogSync().filter((e) => !only || only.has(e.name));
370
+ let agents = [];
371
+ try { agents = connector.config.getAgents() || []; } catch {}
369
372
  const runtimes = catalog.map((e) => {
370
373
  let h;
371
374
  try { h = connector.healthCheck(e.name); } catch { h = {}; }
375
+ // The workspace's Configure saves a key on the AGENT (daemon.yaml), never
376
+ // in <type>.env, so judged on the type alone a Kimi or Pi agent that
377
+ // answered fine read "Needs login" in the workspace while the launcher,
378
+ // which judges the type again with its agents' env, said Ready. Judge it
379
+ // the way the daemon launches it: a type is ready when one of its agents
380
+ // is.
381
+ let agentEnv = null;
382
+ if (h.installed && !h.ready) {
383
+ for (const a of agents) {
384
+ if ((a.type || 'openclaw') !== e.name) continue;
385
+ let ah;
386
+ try { ah = connector.healthCheck(e.name, { cliLogin: isCliLogin(a.env), agentEnv: a.env || {} }); } catch { continue; }
387
+ if (ah && ah.ready) { h = { ...h, ...ah, installed: true }; agentEnv = a.env || {}; break; }
388
+ }
389
+ }
372
390
  // Credential contract, upward half: STATUS goes up, the secret stays on
373
391
  // this device. `mode` says how the type authenticates today
374
392
  // (subscription = CLI/OAuth login, api_key = a stored key, none = not
375
393
  // configured); keyMasked shows only the key's tail.
376
394
  let keyMasked = null;
377
395
  try {
378
- const env = connector.env.load(e.name) || {};
396
+ const env = { ...(connector.env.load(e.name) || {}), ...(agentEnv || {}) };
379
397
  const key = env.LLM_API_KEY || null;
380
398
  if (key && key.length > 7) keyMasked = `…${key.slice(-4)}`;
381
399
  else if (key) keyMasked = '…';
@@ -1054,16 +1072,23 @@ async function cmdProbe(connector, flags, positional) {
1054
1072
 
1055
1073
  async function cmdModels(connector, flags, positional) {
1056
1074
  const target = positional[0];
1057
- if (!target) { print('Usage: agn models <type|agent> [--json]'); return; }
1075
+ if (!target) { print('Usage: agn models <type|agent> [--json] [--sign-in]'); return; }
1058
1076
 
1059
1077
  // Accept an agent name, as `agn probe` does: its CLI is asked on that
1060
1078
  // agent's own env, so a signed-in agent answers for its sign-in.
1079
+ // --sign-in: the target is a type, asked on the device's own sign-in with
1080
+ // no key at all, as an agent added with "sign in on the device" runs. Not
1081
+ // looked up as an agent: the first agent of a type is often named after it.
1061
1082
  let type = target;
1062
1083
  let agentEnv;
1063
- try {
1064
- const agent = connector.config.getAgent(target);
1065
- if (agent) { type = agent.type || 'openclaw'; agentEnv = agent.env || {}; }
1066
- } catch {}
1084
+ if (flags && flags['sign-in']) {
1085
+ agentEnv = { [AUTH_MODE_KEY]: CLI_LOGIN };
1086
+ } else {
1087
+ try {
1088
+ const agent = connector.config.getAgent(target);
1089
+ if (agent) { type = agent.type || 'openclaw'; agentEnv = agent.env || {}; }
1090
+ } catch {}
1091
+ }
1067
1092
 
1068
1093
  const result = await connector.listCliModels(type, { agentEnv });
1069
1094
 
@@ -1156,6 +1181,7 @@ Commands:
1156
1181
  test-llm <type> Test LLM connection
1157
1182
  probe <type|agent> [--json] Smoke-test an agent (tiny end-to-end prompt)
1158
1183
  models <type|agent> [--json] List the models the agent's CLI offers its signed-in account
1184
+ (--sign-in: a type, on the device's own sign-in)
1159
1185
  logs [agent] [--lines N] View daemon logs
1160
1186
  workspace create [name] Create a new workspace
1161
1187
  workspace join <token> Join workspace with token
package/src/daemon.js CHANGED
@@ -12,12 +12,19 @@ const os = require('os');
12
12
  const { WorkspaceClient } = require('./workspace-client');
13
13
  const { listEndpointModels } = require('./model-list');
14
14
  const { supportsCliModels } = require('./cli-models');
15
- const { AUTH_MODE_KEY, isCliLogin, modelKeys, stripForCliLogin, typeEnvFor } = require('./env');
15
+ const {
16
+ AUTH_MODE_KEY, CLI_LOGIN, MODEL_MODE_KEY, MODEL_DEFAULT, credentialKeys, isCliLogin, modelKeys, stripForCliLogin, typeEnvFor,
17
+ } = require('./env');
18
+ const { configuredModel } = require('./agent-model');
16
19
  const { getEnhancedEnv, whichBinary, IS_WINDOWS, defaultAgentWorkdir } = require('./paths');
17
20
  const { LogWriter } = require('./log-writer');
18
21
  const { redactDiagnostic } = require('./adapters/health-status');
19
22
  const { installCommandFor } = require('./probe');
20
23
 
24
+ /** Types whose endpoint is one device-wide config file of their own. OpenClaw
25
+ * left it: each keyed agent gets a private store (adapters/openclaw.js). */
26
+ const SHARED_NATIVE_CONFIG = new Set(['hermes']);
27
+
21
28
  // A signed-in agent's model list is asked for again after this long. What a
22
29
  // CLI is offered changes when the CLI is upgraded (a vendor holds new models
23
30
  // back from old versions), so the upgrade should show within the hour.
@@ -295,28 +302,72 @@ class Daemon {
295
302
  * their own env says otherwise (a token or a config dir of their own), so
296
303
  * those with the same env share an answer: a device with nine Claude agents
297
304
  * starts the CLI once, not nine times. The model each runs is left out, it
298
- * does not change what the account is offered. Hashed, since that env can
299
- * hold a token.
305
+ * does not change what the account is offered, and so is the sign-in
306
+ * marker: an agent is only asked while it runs on the sign-in, marked or
307
+ * not, and then its CLI gets the same env either way. Hashed, since that
308
+ * env can hold a token.
300
309
  */
301
310
  _cliModelsKey(a) {
302
311
  const skip = modelKeys(a.type, this.registry);
312
+ skip.add(AUTH_MODE_KEY);
303
313
  const own = Object.entries(a.env || {})
304
314
  .filter(([k]) => !skip.has(k))
305
315
  .sort(([x], [y]) => (x < y ? -1 : x > y ? 1 : 0));
306
316
  return crypto.createHash('sha256').update(JSON.stringify([a.type, own])).digest('hex');
307
317
  }
308
318
 
319
+ /**
320
+ * The agent the workspace's add form creates for `type` when "sign in on
321
+ * the device" is picked: none of its own env but the sign-in marker. It
322
+ * does not exist yet, so the form has no roster entry to read a list from;
323
+ * its list rides the runtime entry for the type instead (see
324
+ * _heartbeatRuntimes). Every agent on the device's sign-in shares its key.
325
+ */
326
+ _signInAgent(type) {
327
+ return { name: null, type, env: { [AUTH_MODE_KEY]: CLI_LOGIN } };
328
+ }
329
+
330
+ /** Whether this device is paired to any workspace, whose add form could ask. */
331
+ _isPaired() {
332
+ try {
333
+ return require('./node-config').listPairings().some((p) => p && p.node_id && p.token);
334
+ } catch {
335
+ return false;
336
+ }
337
+ }
338
+
339
+ /**
340
+ * Types whose CLI is installed here and can list what its sign-in is
341
+ * offered. Only on a paired device: nothing else reads these lists.
342
+ */
343
+ _signInTypes() {
344
+ const installed = (this._runtimes || [])
345
+ .filter((rt) => rt && rt.installed && supportsCliModels(rt.type))
346
+ .map((rt) => rt.type);
347
+ return installed.length && this._isPaired() ? installed : [];
348
+ }
349
+
350
+ /** Whether the list kept under `key` is missing or has aged out. */
351
+ _cliModelsStale(key) {
352
+ const last = this._cliModels[key];
353
+ if (!last) return true;
354
+ const maxAge = last.models ? CLI_MODELS_MAX_AGE_MS : CLI_MODELS_RETRY_MS;
355
+ return Date.now() - last.askedAt >= maxAge;
356
+ }
357
+
309
358
  /**
310
359
  * Ask an agent's CLI for its models via a child `agn models <name> --json`
311
- * (off the event loop, and on that agent's own env, like a probe).
312
- * Resolves true when the list it keeps for that sign-in changed.
360
+ * (off the event loop, and on that agent's own env, like a probe), or for
361
+ * a type's device sign-in (`_signInAgent`) via `agn models <type> --json
362
+ * --sign-in`. Resolves true when the list it keeps for that sign-in changed.
313
363
  */
314
364
  async _listCliModels(a) {
315
365
  const key = this._cliModelsKey(a);
316
366
  if (this._cliModelsInFlight.has(key)) return false;
317
367
  this._cliModelsInFlight.add(key);
318
368
  try {
319
- const r = await this._runAgn(['models', a.name, '--json']);
369
+ const args = a.name ? ['models', a.name, '--json'] : ['models', a.type, '--json', '--sign-in'];
370
+ const r = await this._runAgn(args);
320
371
  let parsed = null;
321
372
  try { parsed = JSON.parse(r.stdout.trim()); } catch {}
322
373
  const models = parsed && parsed.ok && Array.isArray(parsed.models) ? parsed.models : [];
@@ -344,26 +395,66 @@ class Daemon {
344
395
 
345
396
  /**
346
397
  * Periodic sweep: ask for every sign-in whose list is missing or has aged
347
- * out, and forget the ones no agent is on any more. Sequential, like the
348
- * probe sweep: there is no hurry.
398
+ * out, and forget the ones no agent is on any more. Besides the agents',
399
+ * that is each installed type's device sign-in, which the add form shows
400
+ * before an agent exists. Sequential, like the probe sweep: there is no
401
+ * hurry.
349
402
  */
350
403
  async _refreshCliModels() {
351
404
  const signIns = new Set();
352
- for (const a of this.config.getAgents()) {
353
- if (!a.network || !this._onCliSignIn(a)) continue;
405
+ const ask = async (a) => {
354
406
  const key = this._cliModelsKey(a);
355
- if (signIns.has(key)) continue;
407
+ if (signIns.has(key)) return;
356
408
  signIns.add(key);
357
- const last = this._cliModels[key];
358
- const maxAge = last && last.models ? CLI_MODELS_MAX_AGE_MS : CLI_MODELS_RETRY_MS;
359
- if (last && Date.now() - last.askedAt < maxAge) continue;
409
+ if (!this._cliModelsStale(key)) return;
360
410
  try { await this._listCliModels(a); } catch {}
411
+ };
412
+ for (const a of this.config.getAgents()) {
413
+ if (!a.network || !this._onCliSignIn(a)) continue;
414
+ await ask(a);
361
415
  }
416
+ for (const type of this._signInTypes()) await ask(this._signInAgent(type));
362
417
  for (const key of Object.keys(this._cliModels)) {
363
418
  if (!signIns.has(key)) delete this._cliModels[key];
364
419
  }
365
420
  }
366
421
 
422
+ /**
423
+ * Re-ask a type's device sign-in once its CLI was installed, upgraded,
424
+ * signed in or out: what it is offered changes with each (Claude Code
425
+ * lists four aliases signed out and eleven models on a Max account; an
426
+ * older Codex is not offered the newest ones), and the add form should not show
427
+ * the old answer for the next hour. The list on hand stays until the new
428
+ * one is in.
429
+ */
430
+ _cliModelsAfterDetection(previous) {
431
+ const sig = (rt) => (rt ? JSON.stringify([
432
+ !!rt.installed, rt.version || null, !!rt.ready, rt.authStatus || null, (rt.auth && rt.auth.mode) || null,
433
+ ]) : null);
434
+ let changed = false;
435
+ for (const rt of this._runtimes || []) {
436
+ if (!rt || !supportsCliModels(rt.type) || sig(rt) === sig(previous.get(rt.type))) continue;
437
+ const kept = this._cliModels[this._cliModelsKey(this._signInAgent(rt.type))];
438
+ if (kept) kept.askedAt = 0;
439
+ changed = true;
440
+ }
441
+ if (changed) this._refreshCliModels().catch(() => {});
442
+ }
443
+
444
+ /**
445
+ * The runtime list as the heartbeat sends it: each type whose CLI can list
446
+ * its sign-in's models carries that list, for the add form's model picker.
447
+ * Null until the CLI has answered, and from devices too old to ask, where
448
+ * the form keeps the catalog's list.
449
+ */
450
+ _heartbeatRuntimes() {
451
+ return (this._runtimes || []).map((rt) => {
452
+ if (!rt || !rt.installed || !supportsCliModels(rt.type)) return rt;
453
+ const listed = this._cliModels[this._cliModelsKey(this._signInAgent(rt.type))];
454
+ return { ...rt, cliModels: (listed && listed.models) || null };
455
+ });
456
+ }
457
+
367
458
  /**
368
459
  * Heartbeat this device (node) to EVERY workspace it is paired to,
369
460
  * independent of any agent, so each workspace's "connected devices" view
@@ -383,7 +474,7 @@ class Daemon {
383
474
  if (!pairings.length) return; // no node connected
384
475
  // deviceInfo, not gatherDeviceInfo: the heartbeat sends no device key, and
385
476
  // must never be the thing that writes node.json.
386
- const info = { ...nodeCfg.deviceInfo(), runtimes: this._runtimes || [], fs: this._buildFs() };
477
+ const info = { ...nodeCfg.deviceInfo(), runtimes: this._heartbeatRuntimes(), fs: this._buildFs() };
387
478
  await Promise.all(pairings.map((p) => this._nodeHeartbeatOne(nodeCfg, p, info)));
388
479
  }
389
480
 
@@ -544,15 +635,21 @@ class Daemon {
544
635
  for (const a of this.config.getAgents()) {
545
636
  if (!this._agentOnNodeWorkspace(a, node)) continue;
546
637
  const proc = this._processes[a.name];
547
- // Model/key: per-agent env override, else the type-level saved env.
548
- // Both power the workspace agent cards; the key goes out MASKED only,
549
- // so the edit form can show a key is configured without the secret
550
- // ever leaving the device. The endpoint goes out as a hostname, so
551
- // the workspace can tell a relay from the vendor its model list is for.
638
+ // Model/key: what the agent is launched on (its own env over the
639
+ // type's), read where its adapter reads them. LLM_MODEL/LLM_API_KEY
640
+ // alone missed every agent set up in the launcher, which saves
641
+ // CODEX_MODEL and OPENAI_API_KEY: its edit form showed no model and
642
+ // no key, and a save from it wiped the model it never showed. Both
643
+ // power the workspace agent cards; the key goes out MASKED only, so
644
+ // the edit form can show a key is configured without the secret ever
645
+ // leaving the device. The endpoint goes out as a hostname, so the
646
+ // workspace can tell a relay from the vendor its model list is for.
552
647
  let typeEnv = {};
553
648
  try { typeEnv = typeEnvFor(a.type, this.envManager.load(a.type) || {}, this.registry, a.env); } catch {}
554
- const model = (a.env && a.env.LLM_MODEL) || typeEnv.LLM_MODEL || null;
555
- const apiKey = (a.env && a.env.LLM_API_KEY) || typeEnv.LLM_API_KEY || null;
649
+ let env = {};
650
+ try { env = this._buildAgentEnv(a); } catch {}
651
+ const model = configuredModel(a.type, env, this.registry);
652
+ const apiKey = this._agentKey(a.type, env);
556
653
  // What the agent's own CLI says its signed-in account can run. Null
557
654
  // for an agent on a key or a relay, and until its CLI has answered.
558
655
  const listed = supportsCliModels(a.type) ? this._cliModels[this._cliModelsKey(a)] : null;
@@ -563,6 +660,7 @@ class Daemon {
563
660
  model: model || null,
564
661
  workingDir: a.path || null,
565
662
  apiKeyMasked: apiKey ? maskApiKey(apiKey) : null,
663
+ authMode: this._agentAuthMode(a, apiKey),
566
664
  baseUrlHost: endpointHost(this._configuredBaseUrl(a, typeEnv)),
567
665
  codexWireApi: a.type === 'codex' ? ((a.env && a.env.CODEX_WIRE_API) || typeEnv.CODEX_WIRE_API || 'chat') : null,
568
666
  cliModels: listed && listed.models && this._onCliSignIn(a) ? listed.models : null,
@@ -575,6 +673,61 @@ class Daemon {
575
673
  return roster;
576
674
  }
577
675
 
676
+ /**
677
+ * The key an agent runs on, from the env it is launched on: any of its
678
+ * type's key variables (OPENAI_API_KEY for codex, KIMI_API_KEY, …), not
679
+ * LLM_API_KEY alone. Empty for a signed-in agent, whose env has none.
680
+ */
681
+ _agentKey(type, env) {
682
+ let keys = [];
683
+ try { keys = [...credentialKeys(type, this.registry)].filter((k) => !/BASE_URL$/.test(k)); } catch {}
684
+ const found = keys.find((k) => String((env && env[k]) || '').trim());
685
+ return found ? String(env[found]).trim() : '';
686
+ }
687
+
688
+ /**
689
+ * How an agent authenticates, for the workspace to show: 'api_key' when it
690
+ * runs on a key, 'cli_login' when it runs on its CLI's own sign-in (marked
691
+ * so, or keyless on a type that has one), null for neither. A device holds
692
+ * one sign-in per CLI and any number of keys, and "which one is this agent
693
+ * on" could only be answered from daemon.log.
694
+ */
695
+ _agentAuthMode(a, apiKey) {
696
+ if (isCliLogin(a.env)) return CLI_LOGIN;
697
+ if (apiKey) return 'api_key';
698
+ return this._hasCliSignIn(a.type) ? CLI_LOGIN : null;
699
+ }
700
+
701
+ /**
702
+ * Whether a key, endpoint, model and the type's own credential fields the
703
+ * workspace sends for one agent stay on that agent alone, rather than also
704
+ * going to <type>.env, which every agent of the type without settings of
705
+ * its own runs on. Sharing turned signed-in agents into key agents (add a
706
+ * codex agent on a relay key, and every keyless codex agent ran on that key
707
+ * from its next restart, tool-less, in direct mode), and it moved agents
708
+ * set up in the launcher onto another one's key, endpoint and model: add a
709
+ * second DeepSeek or CodeArts agent from the workspace, and the first one
710
+ * ran on the new one's settings from its next restart.
711
+ * Hermes keeps sharing: its endpoint lives in one config file of its own
712
+ * for the whole device, which only a save to <type>.env updates (index.js
713
+ * _configureNativeAuth), so a key kept on the agent would never reach it.
714
+ * OpenClaw writes each keyed agent's private openclaw.json from the agent's
715
+ * own env when it starts, so it keeps its key on the agent like the rest.
716
+ */
717
+ _keepsKeysPerAgent(type) {
718
+ return !SHARED_NATIVE_CONFIG.has(type);
719
+ }
720
+
721
+ /** Whether this type's CLI has a sign-in of its own (`codex login`, …). */
722
+ _hasCliSignIn(type) {
723
+ try {
724
+ const entry = this.registry.getEntry(type);
725
+ return !!(entry && entry.check_ready && entry.check_ready.login_command);
726
+ } catch {
727
+ return false;
728
+ }
729
+ }
730
+
578
731
  /**
579
732
  * The base URL this agent's CLI is pointed at, found the way _buildAgentEnv
580
733
  * builds its env: LLM_BASE_URL or a provider variable (OPENAI_BASE_URL,
@@ -693,6 +846,30 @@ class Daemon {
693
846
  changes[AUTH_MODE_KEY] = '';
694
847
  }
695
848
  if (args.baseUrl !== undefined) changes.LLM_BASE_URL = args.baseUrl;
849
+ if (!_sentKey(args) && args.authMode === CLI_LOGIN && this._hasCliSignIn(type)) {
850
+ // "Sign in on the device" in the workspace form. Marked, the agent
851
+ // takes no key from <type>.env or the daemon's environment (env.js),
852
+ // so a key saved for its type no longer turns it into a key agent.
853
+ // Unmarked it did, from its next restart: the workspace offered the
854
+ // sign-in, and the agent quietly ran on whatever key the device held.
855
+ // An agent switching over from a key gives up what came with it: the
856
+ // key and endpoint, and a model it is not being sent now (a relay's
857
+ // model id, which the account behind the sign-in does not serve). One
858
+ // already signed in keeps its own model; this only pins the marker.
859
+ const existing = this.config.getAgent(name) || {};
860
+ const own = existing.env || {};
861
+ let hadKey = false;
862
+ try { hadKey = !isCliLogin(own) && !!this._agentKey(type, this._buildAgentEnv(existing)); } catch {}
863
+ changes[AUTH_MODE_KEY] = CLI_LOGIN;
864
+ for (const key of credentialKeys(type, this.registry)) {
865
+ if (key in own || key in changes) changes[key] = '';
866
+ }
867
+ if (hadKey && args.model === undefined) {
868
+ for (const key of Object.keys(own)) {
869
+ if (key === 'MODEL' || key.endsWith('_MODEL')) changes[key] = '';
870
+ }
871
+ }
872
+ }
696
873
  if (args.model !== undefined) {
697
874
  const existing = this.config.getAgent(name);
698
875
  if (!existing) throw new Error(`Agent '${name}' not found after create`);
@@ -704,8 +881,16 @@ class Daemon {
704
881
  changes.LLM_MODEL = String(args.model || '');
705
882
  const nativeVar = { claude: 'ANTHROPIC_MODEL', gemini: 'GEMINI_MODEL' }[type] || this._nativeModelVar(type);
706
883
  if (nativeVar) changes[nativeVar] = String(args.model || '');
884
+ // Cleared means the CLI's default, not whatever <type>.env still holds.
885
+ changes[MODEL_MODE_KEY] = String(args.model || '').trim() ? '' : MODEL_DEFAULT;
707
886
  }
708
887
  if (Object.keys(changes).length) this.config.updateAgentEnv(name, changes);
888
+ // Hermes reads its endpoint from config.yaml, not the agent env: without
889
+ // this a Hermes agent moved to the sign-in kept calling the relay
890
+ // (AgentConnector._configureAgentNativeAuth does the same for agn).
891
+ if (type === 'hermes' && changes[AUTH_MODE_KEY] === CLI_LOGIN) {
892
+ try { require('./adapters/hermes').restoreNativeAuth(); } catch {}
893
+ }
709
894
  }
710
895
 
711
896
  /**
@@ -773,6 +958,7 @@ class Daemon {
773
958
  const previous = new Map((this._runtimes || []).map((rt) => [rt.type, rt]));
774
959
  const order = types.length ? types : [...found.keys()];
775
960
  this._runtimes = order.map((type) => found.get(type) || previous.get(type)).filter(Boolean);
961
+ this._cliModelsAfterDetection(previous);
776
962
  }
777
963
 
778
964
  /**
@@ -787,8 +973,13 @@ class Daemon {
787
973
  * (Credential contract: config flows down transiently, secrets persist
788
974
  * only here, in the device's env store.)
789
975
  */
790
- async _applyConfigMap(type, config) {
791
- if (!config || typeof config !== 'object') return;
976
+ async _applyConfigMap(type, config, name) {
977
+ // Returns the keys saved to <type>.env. A type that keeps them on the
978
+ // agent (_keepsKeysPerAgent) gets them on `name` instead, and none back.
979
+ const applied = [];
980
+ const own = {};
981
+ const perAgent = !!name && this._keepsKeysPerAgent(type);
982
+ if (!config || typeof config !== 'object') return applied;
792
983
  let allowed = null;
793
984
  try {
794
985
  const entry = this.registry.getEntry(type);
@@ -796,7 +987,7 @@ class Daemon {
796
987
  ((entry && entry.env_config) || []).map((f) => f.name).filter(Boolean)
797
988
  );
798
989
  } catch {
799
- return; // no registry entry — refuse everything rather than guess
990
+ return applied; // no registry entry — refuse everything rather than guess
800
991
  }
801
992
  for (const [key, value] of Object.entries(config)) {
802
993
  if (!allowed.has(key)) {
@@ -804,8 +995,15 @@ class Daemon {
804
995
  continue;
805
996
  }
806
997
  if (value === null || value === undefined) continue;
807
- await this._runAgn(['env', type, '--set', `${key}=${String(value)}`]);
998
+ if (perAgent) { own[key] = String(value); continue; }
999
+ const r = await this._runAgn(['env', type, '--set', `${key}=${String(value)}`]);
1000
+ // Stop here rather than count it: the caller drops the agent's own copy
1001
+ // of what was applied, which would leave it with no credential at all.
1002
+ if (r.code !== 0) throw new Error(r.stderr || r.stdout || `Could not save ${key}`);
1003
+ applied.push(key);
808
1004
  }
1005
+ if (Object.keys(own).length) this.config.updateAgentEnv(name, own);
1006
+ return applied;
809
1007
  }
810
1008
 
811
1009
  async _runNodeCommand(n, cmd) {
@@ -815,6 +1013,8 @@ async _runNodeCommand(n, cmd) {
815
1013
  let ok = false;
816
1014
  let message = '';
817
1015
  let data = null;
1016
+ // An agent this create_agent wrote to config but did not finish setting up.
1017
+ let halfCreated = null;
818
1018
  // SECURITY: a workspace may only act on agents bound to it. Reject commands
819
1019
  // that target an existing agent connected to a different workspace, so a
820
1020
  // newly-paired workspace can't start/stop/remove/reconfigure agents that
@@ -838,14 +1038,17 @@ async _runNodeCommand(n, cmd) {
838
1038
  const r1 = await this._runAgn(['create', name, '--type', type, '--install', '--path', workingDir]);
839
1039
  if (r1.code !== 0) throw new Error(r1.stderr || r1.stdout || 'create failed');
840
1040
  const installError = installFailureOf(r1.stdout);
1041
+ halfCreated = name;
841
1042
  // Optional credentials for API-key agents (generic → provider mapping
842
1043
  // happens in env resolution). `useDeviceCredentials` means the device
843
1044
  // already holds them — nothing to write.
844
- if (_sentKey(args))
845
- await this._runAgn(['env', type, '--set', `LLM_API_KEY=${args.apiKey}`]);
846
- if (args.model) await this._setModelEnv(type, args.model);
847
- if (args.baseUrl) await this._runAgn(['env', type, '--set', `LLM_BASE_URL=${args.baseUrl}`]);
848
- await this._applyConfigMap(type, args.config);
1045
+ if (!this._keepsKeysPerAgent(type)) {
1046
+ if (_sentKey(args))
1047
+ await this._runAgn(['env', type, '--set', `LLM_API_KEY=${args.apiKey}`]);
1048
+ if (args.model) await this._setModelEnv(type, args.model);
1049
+ if (args.baseUrl) await this._runAgn(['env', type, '--set', `LLM_BASE_URL=${args.baseUrl}`]);
1050
+ }
1051
+ await this._applyConfigMap(type, args.config, name);
849
1052
  this._saveNodeAgentEnv(name, type, args);
850
1053
  // Attach to this node's workspace BY SLUG: the daemon already knows
851
1054
  // which workspace this command came from, so there is no token to
@@ -855,6 +1058,7 @@ async _runNodeCommand(n, cmd) {
855
1058
  'connect', name, '--workspace', n.workspace_slug || n.workspace_id, '--connection', n.node_id,
856
1059
  ]);
857
1060
  if (r2.code !== 0) throw new Error(r2.stderr || r2.stdout || 'connect failed');
1061
+ halfCreated = null;
858
1062
  ok = true;
859
1063
  message = `Agent '${name}' created`;
860
1064
  if (installError) {
@@ -892,17 +1096,30 @@ async _runNodeCommand(n, cmd) {
892
1096
  // restart it so the change takes effect. Working-dir changes require a
893
1097
  // recreate (agn has no in-place path change) at the new path.
894
1098
  const type = (args.type || '').trim();
895
- if (_sentKey(args))
896
- await this._runAgn(['env', type, '--set', `LLM_API_KEY=${args.apiKey}`]);
897
- if (args.model !== undefined) await this._setModelEnv(type, args.model);
898
- if (args.baseUrl !== undefined) await this._runAgn(['env', type, '--set', `LLM_BASE_URL=${args.baseUrl}`]);
899
- await this._applyConfigMap(type, args.config);
1099
+ if (!this._keepsKeysPerAgent(type)) {
1100
+ if (_sentKey(args))
1101
+ await this._runAgn(['env', type, '--set', `LLM_API_KEY=${args.apiKey}`]);
1102
+ if (args.model !== undefined) await this._setModelEnv(type, args.model);
1103
+ if (args.baseUrl !== undefined) await this._runAgn(['env', type, '--set', `LLM_BASE_URL=${args.baseUrl}`]);
1104
+ }
1105
+ const applied = await this._applyConfigMap(type, args.config, name);
1106
+ // Those just went to the type env (Hermes, OpenClaw), which a copy on
1107
+ // the agent itself (one the launcher saved) outranks at launch: drop
1108
+ // that copy, or the agent keeps running on the old key while the save
1109
+ // says ok.
1110
+ const unshadow = Object.fromEntries(applied.map((key) => [key, '']));
900
1111
  const newDir = (args.workingDir || '').trim();
901
1112
  if (newDir && newDir !== (args.currentWorkingDir || '')) {
902
1113
  try { fs.mkdirSync(newDir, { recursive: true }); } catch {}
1114
+ // The agent's own env goes with the entry remove/create replace, and
1115
+ // for a type that keeps its key on the agent that is the key, the
1116
+ // endpoint and the model. The form sends only what changed, so carry
1117
+ // the rest over before applying this command.
1118
+ const ownEnv = { ...((this.config.getAgent(name) || {}).env || {}) };
903
1119
  await this._runAgn(['remove', name]);
904
1120
  const rc = await this._runAgn(['create', name, '--type', type, '--install', '--path', newDir]);
905
1121
  if (rc.code !== 0) throw new Error(rc.stderr || rc.stdout || 'recreate failed');
1122
+ if (Object.keys(ownEnv).length) this.config.updateAgentEnv(name, { ...ownEnv, ...unshadow });
906
1123
  this._saveNodeAgentEnv(name, type, args);
907
1124
  const rc2 = await this._runAgn([
908
1125
  'connect', name, '--workspace', n.workspace_slug || n.workspace_id, '--connection', n.node_id,
@@ -912,6 +1129,7 @@ async _runNodeCommand(n, cmd) {
912
1129
  // Restart in-process. `agn stop` + `agn start` both round-trip
913
1130
  // through daemon.cmd, and the pair can interleave with the poll so
914
1131
  // the agent stops and never restarts.
1132
+ if (applied.length) this.config.updateAgentEnv(name, unshadow);
915
1133
  this._saveNodeAgentEnv(name, type, args);
916
1134
  await this.restartAgent(name);
917
1135
  }
@@ -966,6 +1184,12 @@ async _runNodeCommand(n, cmd) {
966
1184
  } catch (e) {
967
1185
  ok = false;
968
1186
  message = e.message || String(e);
1187
+ // Undo a create that failed after `agn create`: the entry stays in config
1188
+ // without this workspace's binding, so no roster here shows it, the
1189
+ // workspace's failed card cannot remove it, and every retry under the
1190
+ // same name hit "Agent '…' already exists". Only an entry this command
1191
+ // made is removed — a create refused for a taken name never sets it.
1192
+ if (halfCreated) await this._runAgn(['remove', halfCreated]);
969
1193
  }
970
1194
  try {
971
1195
  // Report back to the workspace that issued the command — with several
@@ -1679,6 +1903,7 @@ async _runNodeCommand(n, cmd) {
1679
1903
  agentName: name,
1680
1904
  endpoint,
1681
1905
  agentType,
1906
+ configDir: this.config.configDir,
1682
1907
  openclawAgentId: agentCfg.openclaw_agent_id || 'main',
1683
1908
  disabledModules: skillsToDisabledModules(agentCfg.skills),
1684
1909
  agentEnv: this._buildAgentEnv(agentCfg),
@@ -1866,7 +2091,10 @@ async _runNodeCommand(n, cmd) {
1866
2091
  const type = agentCfg.type || 'openclaw';
1867
2092
  const merged = this.envManager.getForAgent(type, this.registry, agentCfg.env);
1868
2093
  // A signed-in agent drops every key, the launcher's own environment's too.
1869
- return stripForCliLogin(type, { ...process.env, ...merged }, this.registry, agentCfg.env);
2094
+ const env = stripForCliLogin(type, { ...process.env, ...merged }, this.registry, agentCfg.env);
2095
+ return type === 'openclaw'
2096
+ ? require('./adapters/openclaw').instanceEnv(agentCfg.name, env, this.config.configDir)
2097
+ : env;
1870
2098
  }
1871
2099
 
1872
2100
  _agentConfigFingerprint(agentCfg) {
@@ -1952,6 +2180,11 @@ async _runNodeCommand(n, cmd) {
1952
2180
  } else if (cmd === 'reload') {
1953
2181
  this._log('Command: reload');
1954
2182
  this._reload();
2183
+ } else if (cmd === 'detect') {
2184
+ // The launcher just saw a sign-in finish (or a key saved): re-detect
2185
+ // and report, so the workspace doesn't keep "Needs login" until the
2186
+ // next 2-minute refresh. A run already in flight is joined.
2187
+ this._refreshRuntimes().then(() => this._nodeHeartbeat()).catch(() => {});
1955
2188
  } else if (cmd === 'heartbeat') {
1956
2189
  // A workspace page in the launcher just queued a command for this
1957
2190
  // device: heartbeat now so it is picked up, instead of on the next
@@ -2029,9 +2262,17 @@ async _runNodeCommand(n, cmd) {
2029
2262
  }
2030
2263
  }
2031
2264
 
2265
+ // A type's reported readiness is judged with its agents' env too (agn
2266
+ // runtimes), so adding an agent or saving a key on one changes what the
2267
+ // workspace should show. Report it now rather than on the 2-minute tick.
2268
+ const agentsChanged = newNames.size !== oldNames.size
2269
+ || [...newNames].some((n) => (oldConfigs[n] || '') !== newConfigs[n]);
2032
2270
  this._cachedAgentNames = newNames;
2033
2271
  this._cachedAgentConfigs = newConfigs;
2034
2272
  this._writeStatus();
2273
+ if (agentsChanged && this._runtimesInterval) {
2274
+ this._refreshRuntimes().then(() => this._nodeHeartbeat()).catch(() => {});
2275
+ }
2035
2276
  }
2036
2277
 
2037
2278
  /**