@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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openagents-org/agent-launcher",
3
- "version": "0.2.206",
3
+ "version": "0.2.207",
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
@@ -1103,7 +1103,14 @@
1103
1103
  "args": []
1104
1104
  },
1105
1105
  "check_ready": {
1106
+ "env_vars": [
1107
+ "AMP_API_KEY"
1108
+ ],
1106
1109
  "login_command": "amp login",
1110
+ "status_args": [
1111
+ "usage"
1112
+ ],
1113
+ "logged_out_pattern": "invalid or missing api key|run ['\"]?amp login",
1107
1114
  "not_ready_message": "Amp is installed but not signed in — run: amp login or set AMP_API_KEY"
1108
1115
  },
1109
1116
  "env_config": [
@@ -1173,11 +1180,18 @@
1173
1180
  "CLINE_API_KEY",
1174
1181
  "ANTHROPIC_API_KEY",
1175
1182
  "OPENAI_API_KEY",
1176
- "OPENROUTER_API_KEY"
1183
+ "OPENROUTER_API_KEY",
1184
+ "AI_GATEWAY_API_KEY",
1185
+ "V0_API_KEY"
1177
1186
  ],
1178
1187
  "saved_env_key": "CLINE_API_KEY",
1188
+ "creds_file": "~/.cline/data/settings/providers.json",
1189
+ "creds_no_parse": true,
1190
+ "creds_key": "providers",
1191
+ "creds_classifier": "cline_providers",
1179
1192
  "login_command": "cline auth",
1180
- "not_ready_message": "Not configured — set an API key in Configure, or run: cline auth"
1193
+ "not_ready_message": "Not configured — set an API key in Configure, or run: cline auth",
1194
+ "unknown_message": "Cline's sign-in can't be confirmed from its settings (a Cline account keeps it elsewhere). The first run will tell; if it fails, run: cline auth"
1181
1195
  },
1182
1196
  "env_config": [
1183
1197
  {
@@ -1929,6 +1943,11 @@
1929
1943
  ],
1930
1944
  "saved_env_key": "COMMAND_CODE_API_KEY",
1931
1945
  "login_command": "command-code login",
1946
+ "status_args": [
1947
+ "status"
1948
+ ],
1949
+ "logged_in_pattern": "authentication verified|authenticated as",
1950
+ "logged_out_pattern": "not authenticated|not signed in|not logged in",
1932
1951
  "not_ready_message": "Not configured — sign in with `command-code login`, or set COMMAND_CODE_API_KEY in Configure",
1933
1952
  "unreadable_message": "Command Code credentials could not be read. Sign in again with `command-code login`, or re-enter COMMAND_CODE_API_KEY in the Configure screen."
1934
1953
  },
@@ -20,6 +20,7 @@
20
20
  const { WorkspaceClient, SessionRevokedError } = require('../workspace-client');
21
21
  const { generateSessionTitle, SESSION_DEFAULT_RE, redactSecrets, secretValues } = require('./utils');
22
22
  const { defaultAgentWorkdir } = require('../paths');
23
+ const { configuredModel } = require('../agent-model');
23
24
  const { buildThreadHistory } = require('./thread-history');
24
25
  const { publishResponseArtifacts } = require('./response-artifacts');
25
26
  const fs = require('fs');
@@ -134,18 +135,6 @@ const CONTROL_POLL_DEADLINE_MS = 20 * 1000;
134
135
  const CONTROL_ACTION_DEADLINE_MS = 60 * 1000;
135
136
  const CONTROL_DEADLINE_HIT = Symbol('control deadline hit');
136
137
 
137
- /**
138
- * Model variables whose name does not follow `<TYPE>_MODEL`. Only the ones an
139
- * adapter really reads — see `modelLabel`, which tries `<TYPE>_MODEL` first
140
- * and `LLM_MODEL` last, so nothing else needs an entry here.
141
- */
142
- const MODEL_ENV_ALIASES = {
143
- claude: ['ANTHROPIC_MODEL', 'CLAUDE_MODEL'],
144
- gemini: ['GEMINI_MODEL', 'GOOGLE_GEMINI_MODEL'],
145
- antigravity: ['ANTIGRAVITY_MODEL', 'AGY_MODEL'],
146
- codex: ['CODEX_MODEL', 'OPENCLAW_MODEL'],
147
- };
148
-
149
138
  /**
150
139
  * Wrap an adapter's `_channelProcesses` so registering a child for a turn that
151
140
  * was already stopped kills it at once (see `_onProcessRegistered`).
@@ -422,17 +411,7 @@ class BaseAdapter {
422
411
  modelLabel() {
423
412
  const fromWorkspace = String(this.workspaceModel || '').trim();
424
413
  if (fromWorkspace) return fromWorkspace;
425
- const type = String(this.agentType || '').toUpperCase().replace(/[^A-Z0-9]+/g, '_');
426
- const candidates = [
427
- ...(type ? [`${type}_MODEL`] : []),
428
- ...(MODEL_ENV_ALIASES[this.agentType] || []),
429
- 'LLM_MODEL',
430
- ];
431
- for (const key of candidates) {
432
- const value = String((this.agentEnv && this.agentEnv[key]) || '').trim();
433
- if (value) return value;
434
- }
435
- return null;
414
+ return configuredModel(this.agentType, this.agentEnv);
436
415
  }
437
416
 
438
417
  async run() {
@@ -40,7 +40,10 @@ class ClaudeAdapter extends BaseAdapter {
40
40
  * gets a 403). Cloud-provider and model config is kept, and so is the
41
41
  * subscription token from `claude setup-token` — that one IS the
42
42
  * credential, and sweeping it up as a stray CLAUDE_* left anyone who
43
- * pasted one authenticating as nobody, silently.
43
+ * pasted one authenticating as nobody, silently. CLAUDE_CONFIG_DIR is
44
+ * kept too: it is where the user's global CLAUDE.md, settings, skills and
45
+ * project memory live, and dropping it started the agent from a blank
46
+ * ~/.claude with none of the memory it has outside the workspace.
44
47
  *
45
48
  * 2. Mirror the API key into ANTHROPIC_AUTH_TOKEN for third-party relays. The
46
49
  * CLI sends ANTHROPIC_API_KEY as `x-api-key`, which most Anthropic-
@@ -62,6 +65,7 @@ class ClaudeAdapter extends BaseAdapter {
62
65
  'CLAUDE_API_KEY',
63
66
  'CLAUDE_CODE_MAX_TURNS',
64
67
  'CLAUDE_CODE_OAUTH_TOKEN',
68
+ 'CLAUDE_CONFIG_DIR',
65
69
  ]);
66
70
  const env = { ...(baseEnv || {}) };
67
71
  for (const k of Object.keys(env)) {
@@ -270,16 +274,22 @@ class ClaudeAdapter extends BaseAdapter {
270
274
  *
271
275
  * Excludes the user's current message (the caller appends it normally)
272
276
  * and any status/thinking events, which are mostly tool-call noise.
277
+ * `current` is the triggering message: when given, the trigger itself and
278
+ * anything posted after it (queued follow-ups) are left out by event, since
279
+ * `currentMessage` text no longer matches once history is prepended.
273
280
  */
274
- async _buildChannelRecap(channelName, currentMessage) {
275
- // The head window is raw events — status/thinking noise is filtered out
276
- // AFTER the fetch, and an opening turn is often mostly noise, so fetch
277
- // well more than the 5 chat messages the sampler will keep.
281
+ async _buildChannelRecap(channelName, currentMessage, current = null) {
282
+ const before = current?.messageId;
278
283
  const [headMsgs, tailMsgs] = await Promise.all([
279
284
  this.client.getRecentMessages(this.workspaceId, channelName, this.token, 30, { sort: 'asc' }),
280
- this.client.getRecentMessages(this.workspaceId, channelName, this.token, 60),
285
+ this.client.getRecentMessages(this.workspaceId, channelName, this.token, 60, before ? { before } : {}),
281
286
  ]);
282
- const lines = sampleRecap(headMsgs, tailMsgs, currentMessage);
287
+ const cutoff = Date.parse(current?.createdAt || '');
288
+ const priorOnly = (msgs) => (msgs || []).filter((m) => {
289
+ if (before && m.messageId === before) return false;
290
+ return !(Number.isFinite(cutoff) && Date.parse(m.createdAt || '') > cutoff);
291
+ });
292
+ const lines = sampleRecap(priorOnly(headMsgs), priorOnly(tailMsgs), currentMessage);
283
293
  if (lines.length === 0) return null;
284
294
 
285
295
  return (
@@ -1392,12 +1402,14 @@ class ClaudeAdapter extends BaseAdapter {
1392
1402
 
1393
1403
  // Spawn a persistent process and send the first message via stdin
1394
1404
  let effectiveContent = content;
1405
+ // The trigger's own text, before thread history was prepended to it.
1406
+ const recapExclude = String(msg.originalContent ?? msg.content ?? '').trim();
1395
1407
 
1396
1408
  // When starting without a session (no --resume), prepend channel
1397
1409
  // history so the fresh CLI has conversation context.
1398
1410
  if (!this._channelSessions[msgChannel]) {
1399
1411
  try {
1400
- const recap = await this._buildChannelRecap(msgChannel, content);
1412
+ const recap = await this._buildChannelRecap(msgChannel, recapExclude, msg);
1401
1413
  if (recap) effectiveContent = `${recap}\n\n---\n\n${content}`;
1402
1414
  } catch {}
1403
1415
  }
@@ -1409,7 +1421,7 @@ class ClaudeAdapter extends BaseAdapter {
1409
1421
  await this._killPersistentProc(msgChannel);
1410
1422
  // Rebuild recap for retry without resume
1411
1423
  try {
1412
- const recap = await this._buildChannelRecap(msgChannel, content);
1424
+ const recap = await this._buildChannelRecap(msgChannel, recapExclude, msg);
1413
1425
  if (recap) effectiveContent = `${recap}\n\n---\n\n${content}`;
1414
1426
  } catch {}
1415
1427
  }
@@ -14,6 +14,7 @@
14
14
  const fs = require('fs');
15
15
  const path = require('path');
16
16
  const os = require('os');
17
+ const { createHash } = require('crypto');
17
18
  const { execSync } = require('child_process');
18
19
  // spawn() here is the WSL bridge from ../wsl: same signature as
19
20
  // child_process.spawn, and a straight pass-through unless the resolved CLI
@@ -68,8 +69,8 @@ const OPENCLAW_STATE_DIR = path.join(
68
69
  *
69
70
  * @param {Array<string|undefined>} knownKeys API keys this agent is configured with
70
71
  */
71
- function retireOwnLegacyAuthProfiles(knownKeys) {
72
- const file = path.join(OPENCLAW_STATE_DIR, 'agents', 'main', 'agent', 'auth-profiles.json');
72
+ function retireOwnLegacyAuthProfiles(knownKeys, stateDir = OPENCLAW_STATE_DIR) {
73
+ const file = path.join(stateDir, 'agents', 'main', 'agent', 'auth-profiles.json');
73
74
  let data;
74
75
  try { data = JSON.parse(fs.readFileSync(file, 'utf-8')); } catch { return false; }
75
76
  const keys = new Set((knownKeys || []).filter(Boolean));
@@ -111,6 +112,11 @@ class OpenClawAdapter extends BaseAdapter {
111
112
  constructor(opts) {
112
113
  super(opts);
113
114
  this.openclawAgentId = opts.openclawAgentId || 'main';
115
+ this.agentEnv = OpenClawAdapter.instanceEnv(this.agentName, this.agentEnv, opts.configDir);
116
+ this._openclawStateDir = this.agentEnv.OPENCLAW_STATE_DIR || OPENCLAW_STATE_DIR;
117
+ // Rebuild from this instance's saved env on startup as well as on save:
118
+ // older launchers persisted separate keys but overwrote one native config.
119
+ OpenClawAdapter.configureNativeAuth(this.agentEnv, { agentId: this.openclawAgentId });
114
120
  this.disabledModules = opts.disabledModules || new Set();
115
121
  // channel → the `openclaw agent` run in flight, so a stop can end it
116
122
  // instead of letting it spend tokens until it finishes on its own.
@@ -129,7 +135,7 @@ class OpenClawAdapter extends BaseAdapter {
129
135
  // still have that file; clear it before the first run rather than on the
130
136
  // next save.
131
137
  const env = this.agentEnv || {};
132
- if (retireOwnLegacyAuthProfiles([env.LLM_API_KEY, env.OPENAI_API_KEY, env.ANTHROPIC_API_KEY])) {
138
+ if (retireOwnLegacyAuthProfiles([env.LLM_API_KEY, env.OPENAI_API_KEY, env.ANTHROPIC_API_KEY], this._openclawStateDir)) {
133
139
  this._log('Archived the legacy auth-profiles.json this launcher wrote (OpenClaw now stores credentials in SQLite)');
134
140
  }
135
141
 
@@ -137,6 +143,26 @@ class OpenClawAdapter extends BaseAdapter {
137
143
  this._installWorkspaceSkill();
138
144
  }
139
145
 
146
+ /** An agent's private OpenClaw store, whether or not it exists yet. */
147
+ static instanceStateDir(agentName, configDir = path.join(os.homedir(), '.openagents')) {
148
+ // Hash the identity so case-insensitive filesystems and path-like names
149
+ // cannot alias another agent or escape the managed root.
150
+ const id = createHash('sha256').update(String(agentName)).digest('hex').slice(0, 24);
151
+ return path.resolve(configDir, 'openclaw', id);
152
+ }
153
+
154
+ /** The save path and every CLI launch must agree on an instance's store. */
155
+ static instanceEnv(agentName, env, configDir = path.join(os.homedir(), '.openagents')) {
156
+ // Native OpenClaw users with no launcher-managed key retain their own setup.
157
+ if (!env.LLM_API_KEY) return env;
158
+ const stateDir = OpenClawAdapter.instanceStateDir(agentName, configDir);
159
+ const scoped = { ...env, OPENCLAW_STATE_DIR: stateDir, OPENCLAW_CONFIG_PATH: path.join(stateDir, 'openclaw.json') };
160
+ // This supported native override relocates auth outside the state root;
161
+ // an inherited profile there can outrank the instance's provider env key.
162
+ delete scoped.OPENCLAW_AGENT_DIR;
163
+ return scoped;
164
+ }
165
+
140
166
  // ------------------------------------------------------------------
141
167
  // Binary resolution
142
168
  // ------------------------------------------------------------------
@@ -203,14 +229,26 @@ class OpenClawAdapter extends BaseAdapter {
203
229
 
204
230
  _resolveOpenclawWorkspace() {
205
231
  const agentId = this.openclawAgentId;
232
+ // A private store says in its own config where each id's workspace is
233
+ // (configureNativeAuth pins them), so the skill goes where the run looks.
234
+ if (this.agentEnv && this.agentEnv.OPENCLAW_STATE_DIR) {
235
+ let agents = {};
236
+ try {
237
+ const configFile = this.agentEnv.OPENCLAW_CONFIG_PATH || path.join(this._openclawStateDir, 'openclaw.json');
238
+ agents = JSON.parse(fs.readFileSync(configFile, 'utf-8')).agents || {};
239
+ } catch {}
240
+ const entry = (agents.entries || {})[agentId] || {};
241
+ const pinned = entry.workspace || (agents.defaults || {}).workspace;
242
+ if (pinned && fs.existsSync(pinned)) return pinned;
243
+ }
206
244
  const wsDir = agentId && agentId !== 'main'
207
- ? path.join(OPENCLAW_STATE_DIR, `workspace-${agentId}`)
208
- : path.join(OPENCLAW_STATE_DIR, 'workspace');
245
+ ? path.join(this._openclawStateDir, `workspace-${agentId}`)
246
+ : path.join(this._openclawStateDir, 'workspace');
209
247
 
210
248
  if (fs.existsSync(wsDir)) return wsDir;
211
249
 
212
250
  // Fall back to default workspace
213
- const fallback = path.join(OPENCLAW_STATE_DIR, 'workspace');
251
+ const fallback = path.join(this._openclawStateDir, 'workspace');
214
252
  if (fs.existsSync(fallback)) return fallback;
215
253
 
216
254
  return null;
@@ -785,14 +823,14 @@ class OpenClawAdapter extends BaseAdapter {
785
823
  /**
786
824
  * Configure OpenClaw's native auth and model from user-provided
787
825
  * LLM_API_KEY / LLM_BASE_URL / LLM_MODEL values.
788
- * Called by the Launcher's saveAgentEnv when type === 'openclaw'.
826
+ * Called when adding/saving an instance and when its adapter starts.
789
827
  *
790
828
  * For standard providers (OpenAI, Anthropic), the key travels in the env
791
829
  * and only the model is set here. For custom endpoints, uses
792
830
  * models.providers in openclaw.json which gives full tool support via the
793
831
  * CLI gateway mode.
794
832
  */
795
- static configureNativeAuth(env) {
833
+ static configureNativeAuth(env, { agentId } = {}) {
796
834
  const apiKey = env.LLM_API_KEY;
797
835
  // Strip /chat/completions suffix — OpenClaw appends it internally
798
836
  const rawUrl = env.LLM_BASE_URL || 'https://api.openai.com/v1';
@@ -802,7 +840,8 @@ class OpenClawAdapter extends BaseAdapter {
802
840
 
803
841
  const isOpenAI = baseUrl.includes('api.openai.com');
804
842
  const isAnthropic = baseUrl.includes('api.anthropic.com');
805
- const configFile = path.join(OPENCLAW_STATE_DIR, 'openclaw.json');
843
+ const stateDir = env.OPENCLAW_STATE_DIR || OPENCLAW_STATE_DIR;
844
+ const configFile = env.OPENCLAW_CONFIG_PATH || path.join(stateDir, 'openclaw.json');
806
845
 
807
846
  // The key itself never goes into auth-profiles.json any more: current
808
847
  // OpenClaw keeps credentials in SQLite and refuses to start while a legacy
@@ -810,29 +849,17 @@ class OpenClawAdapter extends BaseAdapter {
810
849
  // migration; run openclaw doctor --fix"). A standard provider reads the
811
850
  // key from the OPENAI_API_KEY / ANTHROPIC_API_KEY the resolve rules put
812
851
  // in its env; a custom one from models.providers below.
813
- retireOwnLegacyAuthProfiles([apiKey]);
814
-
815
- if (isOpenAI || isAnthropic) {
816
- const provider = isAnthropic ? 'anthropic' : 'openai';
817
- // Set model
818
- try {
819
- fs.mkdirSync(OPENCLAW_STATE_DIR, { recursive: true });
820
- let config = {};
821
- try { config = JSON.parse(fs.readFileSync(configFile, 'utf-8')); } catch {}
822
- config.agents = config.agents || {};
823
- config.agents.defaults = config.agents.defaults || {};
824
- config.agents.defaults.model = { primary: `${provider}/${model}` };
825
- fs.writeFileSync(configFile, JSON.stringify(config, null, 2), 'utf-8');
826
- } catch {}
827
- } else {
828
- // Custom endpoint — use models.providers for full gateway/tool support
829
- // This is the proper way to add custom LLM endpoints to OpenClaw.
830
- // See: https://docs.openclaw.ai/concepts/model-providers
831
- try {
832
- fs.mkdirSync(OPENCLAW_STATE_DIR, { recursive: true });
833
- let config = {};
834
- try { config = JSON.parse(fs.readFileSync(configFile, 'utf-8')); } catch {}
852
+ retireOwnLegacyAuthProfiles([apiKey], stateDir);
835
853
 
854
+ try {
855
+ // A private store holds the agent's key and sessions: owner only.
856
+ fs.mkdirSync(path.dirname(configFile), { recursive: true, mode: env.OPENCLAW_STATE_DIR ? 0o700 : 0o777 });
857
+ let config = {};
858
+ try { config = JSON.parse(fs.readFileSync(configFile, 'utf-8')); } catch {}
859
+ const provider = isAnthropic ? 'anthropic' : (isOpenAI ? 'openai' : 'custom');
860
+ if (provider === 'custom') {
861
+ // Custom endpoint — use models.providers for full gateway/tool support.
862
+ // See: https://docs.openclaw.ai/concepts/model-providers
836
863
  config.models = config.models || {};
837
864
  config.models.providers = config.models.providers || {};
838
865
  config.models.providers.custom = {
@@ -848,14 +875,36 @@ class OpenClawAdapter extends BaseAdapter {
848
875
  api: 'openai-completions',
849
876
  models: [{ id: model, name: model }],
850
877
  };
851
-
852
- config.agents = config.agents || {};
853
- config.agents.defaults = config.agents.defaults || {};
854
- config.agents.defaults.model = { primary: `custom/${model}` };
855
-
856
- fs.writeFileSync(configFile, JSON.stringify(config, null, 2), 'utf-8');
857
- } catch {}
858
- }
878
+ }
879
+ config.agents = config.agents || {};
880
+ config.agents.defaults = config.agents.defaults || {};
881
+ config.agents.defaults.model = { primary: `${provider}/${model}` };
882
+ if (env.OPENCLAW_STATE_DIR) {
883
+ // OpenClaw's workspace default can still point at ~/.openclaw/workspace;
884
+ // set it explicitly so skills and memory follow the private state too.
885
+ const workspace = config.agents.defaults.workspace || path.join(stateDir, 'workspace');
886
+ config.agents.defaults.workspace = workspace;
887
+ fs.mkdirSync(workspace, { recursive: true });
888
+ // A private store serves one agent, which runs one OpenClaw agent id.
889
+ // `main` needs no entry on any OpenClaw release, and releases up to
890
+ // 2026.7 refuse to start on an `agents.entries` key at all ("Config
891
+ // invalid ... Unrecognized key"). Another id has to be listed there,
892
+ // and alone: 2026.10 refuses a roster of more than one agent that
893
+ // declares no owner ("multi-agent rosters require agents.ownership"),
894
+ // and gives each id of such a roster a workspace of its own
895
+ // (workspace/<id>), where the workspace skill is not installed. So the
896
+ // roster holds the id this agent runs on now, pinned to the private
897
+ // workspace, and is dropped for main. A save with no id (from the
898
+ // launcher) leaves it as the adapter last wrote it.
899
+ if (agentId === 'main') {
900
+ delete config.agents.entries;
901
+ } else if (agentId) {
902
+ const current = (config.agents.entries || {})[agentId] || {};
903
+ config.agents.entries = { [agentId]: { ...current, workspace: current.workspace || workspace } };
904
+ }
905
+ }
906
+ fs.writeFileSync(configFile, JSON.stringify(config, null, 2), { encoding: 'utf-8', mode: 0o600 });
907
+ } catch {}
859
908
  }
860
909
  }
861
910
 
@@ -857,6 +857,35 @@ function inferLauncherProvider(env = {}) {
857
857
  return { provider: 'openai', apiFormat: 'openai-completions' };
858
858
  }
859
859
 
860
+ /** Each provider's default API format, as in pi-launcher-provider.mjs. */
861
+ const PI_PROVIDER_API_FORMATS = {
862
+ anthropic: 'anthropic-messages',
863
+ openai: 'openai-responses',
864
+ deepseek: 'openai-completions',
865
+ google: 'google-generative-ai',
866
+ openrouter: 'openai-completions',
867
+ };
868
+
869
+ /**
870
+ * The API format a Pi agent's launcher provider speaks, resolved the way it
871
+ * is at run time (the adapter's _buildEnv, then pi-launcher-provider.mjs): an
872
+ * explicit PI_API_FORMAT, else the one inferred for a relay-only config, else
873
+ * the provider's default. Null when there is no launcher provider to speak
874
+ * for (no PI_PROVIDER, no PI_BASE_URL): Pi then runs on its own provider
875
+ * config (its sign-in, an ANTHROPIC_API_KEY), whose format these fields do
876
+ * not say.
877
+ */
878
+ function piApiFormat(env = {}) {
879
+ const val = (k) => String(env[k] == null ? '' : env[k]).trim().toLowerCase();
880
+ const inferred = inferLauncherProvider(env);
881
+ const provider = val('PI_PROVIDER') || (inferred && inferred.provider);
882
+ if (!provider) return null;
883
+ const configured = val('PI_API_FORMAT');
884
+ if (configured && configured !== 'auto') return configured;
885
+ if (inferred) return inferred.apiFormat;
886
+ return PI_PROVIDER_API_FORMATS[provider] || 'openai-completions';
887
+ }
888
+
860
889
  function buildPiArgs({
861
890
  sessionDir,
862
891
  sessionId,
@@ -943,6 +972,7 @@ module.exports = {
943
972
  isValidSessionId,
944
973
  buildPiArgs,
945
974
  inferLauncherProvider,
975
+ piApiFormat,
946
976
  normalizeThinking,
947
977
  parseTrustProject,
948
978
  redactArgs,
@@ -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