@openagents-org/agent-launcher 0.2.206 → 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.
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
  /**
package/src/env.js CHANGED
@@ -144,6 +144,20 @@ function isCliLogin(agentEnv) {
144
144
  return !!agentEnv && agentEnv[AUTH_MODE_KEY] === CLI_LOGIN;
145
145
  }
146
146
 
147
+ /**
148
+ * Set on an agent's own env when its model is cleared from the workspace, so
149
+ * it runs on its CLI's default. A cleared model used to be dropped from the
150
+ * agent's env alone, and a model left in <type>.env (earlier versions saved
151
+ * workspace models there) filled the gap again at the agent's next start. A
152
+ * model in the agent's own env still wins; this only keeps the type's out.
153
+ */
154
+ const MODEL_MODE_KEY = 'OPENAGENTS_MODEL_MODE';
155
+ const MODEL_DEFAULT = 'default';
156
+
157
+ function usesDefaultModel(agentEnv) {
158
+ return !!agentEnv && agentEnv[MODEL_MODE_KEY] === MODEL_DEFAULT;
159
+ }
160
+
147
161
  /**
148
162
  * Keys and endpoints a CLI reads under a name of its own that no registry
149
163
  * field or readiness check declares (the launcher's auth-specs.ts offers the
@@ -225,14 +239,18 @@ function hasOwnKey(agentType, registry, agentEnv) {
225
239
  * maps the generic LLM_* names over the provider ones, so a relay left in
226
240
  * <type>.env used to override an agent configured for DeepSeek: its
227
241
  * LLM_BASE_URL and LLM_MODEL became PI_BASE_URL and PI_MODEL, and the agent's
228
- * key went to the relay. Its model is the one in its own env, else the CLI's
229
- * default.
242
+ * key went to the relay. An agent whose model was cleared (MODEL_MODE_KEY)
243
+ * takes no model from it either. Its model is the one in its own env, else the
244
+ * CLI's default.
230
245
  */
231
246
  function typeEnvFor(agentType, typeEnv, registry, agentEnv) {
232
247
  const signedIn = isCliLogin(agentEnv);
233
- if (!signedIn && !hasOwnKey(agentType, registry, agentEnv)) return typeEnv;
248
+ const ownKey = hasOwnKey(agentType, registry, agentEnv);
249
+ if (!signedIn && !ownKey && !usesDefaultModel(agentEnv)) return typeEnv;
234
250
  const out = { ...typeEnv };
235
- for (const key of credentialKeys(agentType, registry)) delete out[key];
251
+ if (signedIn || ownKey) {
252
+ for (const key of credentialKeys(agentType, registry)) delete out[key];
253
+ }
236
254
  for (const key of modelKeys(agentType, registry)) delete out[key];
237
255
  return out;
238
256
  }
@@ -263,5 +281,6 @@ function normalizeAnthropicBase(url) {
263
281
  }
264
282
 
265
283
  module.exports = {
266
- EnvManager, AUTH_MODE_KEY, CLI_LOGIN, isCliLogin, credentialKeys, modelKeys, stripForCliLogin, typeEnvFor,
284
+ EnvManager, AUTH_MODE_KEY, CLI_LOGIN, MODEL_MODE_KEY, MODEL_DEFAULT, isCliLogin, credentialKeys, modelKeys,
285
+ stripForCliLogin, typeEnvFor,
267
286
  };
package/src/index.js CHANGED
@@ -4,6 +4,7 @@
4
4
  // keeps every spawn from popping a stray console window. See win-console.js.
5
5
  require('./win-console').installWindowsHideDefault();
6
6
 
7
+ const fs = require('fs');
7
8
  const { Config } = require('./config');
8
9
  const { EnvManager, isCliLogin, typeEnvFor } = require('./env');
9
10
  const { Registry } = require('./registry');
@@ -119,7 +120,7 @@ class AgentConnector {
119
120
  // key while the run used a stale one ("401 Invalid token") or none at all
120
121
  // (Hermes falling back to OpenRouter: "401 Missing Authentication header").
121
122
  if (env && Object.keys(env).length) {
122
- this._configureAgentNativeAuth(agentType, env);
123
+ this._configureAgentNativeAuth(agentType, env, name);
123
124
  }
124
125
  return { success: true };
125
126
  }
@@ -131,9 +132,9 @@ class AgentConnector {
131
132
  * key saved there earlier into Hermes's config.yaml for an agent created on
132
133
  * the sign-in tab, which then ran on that key (401).
133
134
  */
134
- _configureAgentNativeAuth(agentType, agentEnv) {
135
+ _configureAgentNativeAuth(agentType, agentEnv, agentName) {
135
136
  const typeEnv = typeEnvFor(agentType, this.env.load(agentType), this.registry, agentEnv);
136
- this._configureNativeAuth(agentType, { ...typeEnv, ...agentEnv });
137
+ this._configureNativeAuth(agentType, { ...typeEnv, ...agentEnv }, agentName);
137
138
  // A Hermes agent moved to the `hermes setup` sign-in gets back the
138
139
  // provider the custom endpoint replaced.
139
140
  if (agentType === 'hermes' && isCliLogin(agentEnv)) {
@@ -142,10 +143,13 @@ class AgentConnector {
142
143
  }
143
144
 
144
145
  /** Push an agent's endpoint and key into the CLI's own config, for the types that need it. */
145
- _configureNativeAuth(agentType, env) {
146
+ _configureNativeAuth(agentType, env, agentName) {
146
147
  try {
147
148
  if (agentType === 'openclaw') {
148
- require('./adapters/openclaw').configureNativeAuth(env);
149
+ const OpenClawAdapter = require('./adapters/openclaw');
150
+ OpenClawAdapter.configureNativeAuth(agentName
151
+ ? OpenClawAdapter.instanceEnv(agentName, env, this._configDir)
152
+ : env);
149
153
  }
150
154
  // Hermes reads a custom endpoint only from its own config.yaml, so the
151
155
  // saved LLM_* values must be pushed through `hermes config set` — the
@@ -246,7 +250,16 @@ class AgentConnector {
246
250
  }
247
251
 
248
252
  removeAgent(name) {
253
+ const agent = this.config.getAgent(name);
249
254
  this.config.removeAgent(name);
255
+ // Its private OpenClaw store keeps the key in openclaw.json, and would
256
+ // hand old sessions to a new agent added later under the same name.
257
+ if (agent && agent.type === 'openclaw') {
258
+ try {
259
+ const dir = require('./adapters/openclaw').instanceStateDir(name, this._configDir);
260
+ fs.rmSync(dir, { recursive: true, force: true });
261
+ } catch {}
262
+ }
250
263
  return { success: true };
251
264
  }
252
265
 
@@ -287,7 +300,7 @@ class AgentConnector {
287
300
  // Preserve native auth side effects for agents that need them while
288
301
  // keeping the model choice scoped to this individual agent.
289
302
  const agentType = agent.type || 'openclaw';
290
- this._configureAgentNativeAuth(agentType, saved);
303
+ this._configureAgentNativeAuth(agentType, saved, agentName);
291
304
 
292
305
  return { success: true };
293
306
  }