@openagents-org/agent-launcher 0.2.206 → 0.2.208

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/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
  }
package/src/installer.js CHANGED
@@ -26,6 +26,7 @@ const { checkInstallPrereqs, missingPrereqError } = require('./install-preflight
26
26
  const { detectShadowedNodeShims, shadowedNodeWarning } = require('./node-shims');
27
27
  const { fixSpawnHelpers } = require('./node-pty-perms');
28
28
  const { isPostinstallStub } = require('./postinstall-stub');
29
+ const { classifyClineAuth } = require('./adapters/cline-stream');
29
30
 
30
31
  /**
31
32
  * OPENAGENTS_NO_SCRIPT_REPAIR=1: never run an install script npm skipped
@@ -45,6 +46,37 @@ const LOGIN_STATUS_TIMEOUT_MS = 8000;
45
46
  let credentialListCache = null;
46
47
  /** True while a background (non-blocking) `cmdkey /list` refresh is running. */
47
48
  let credentialListRefreshing = false;
49
+ /** Whether a macOS Keychain item exists, by service: { found, ts }. No secrets. */
50
+ const keychainItemCache = new Map();
51
+ /** Services with a background (non-blocking) Keychain lookup in flight. */
52
+ const keychainRefreshing = new Set();
53
+
54
+ /**
55
+ * Readers for a credential file whose content, not its existence, says whether
56
+ * the agent is signed in. Named by `check_ready.creds_classifier`. Each takes
57
+ * the parsed file (or `{ __parse_error: true }`) and returns 'ready',
58
+ * 'no_credentials' (the file shows no sign-in) or 'unknown' (it cannot tell).
59
+ * They test fields for presence only; no value is returned or logged.
60
+ *
61
+ * Reading the file for one non-empty field said "signed in" for a Cline file
62
+ * that only remembered which provider and model to use, with no key in it.
63
+ */
64
+ const CREDS_CLASSIFIERS = {
65
+ // The adapter's own reading of providers.json. A key-based provider picked
66
+ // with no key stored is no_credentials; a Cline account sign-in keeps its
67
+ // credential outside the file, so without a stored key it is unknown, never
68
+ // "signed out". Keys in the environment are judged by env_vars before this,
69
+ // which lists every key the adapter takes (CLINE_AUTH_ENV_VARS).
70
+ cline_providers(creds) {
71
+ return classifyClineAuth(creds, {}).state;
72
+ },
73
+ };
74
+
75
+ /** The named classifier's verdict, or null when the entry names none. */
76
+ function classifyCreds(checkReady, creds) {
77
+ const classify = checkReady && CREDS_CLASSIFIERS[checkReady.creds_classifier];
78
+ return classify ? classify(creds) : null;
79
+ }
48
80
 
49
81
  /**
50
82
  * Read a CLI's status output for its sign-in state: true (signed in), false
@@ -143,6 +175,7 @@ function compareVersions(a, b) {
143
175
  function clearVersionCache() {
144
176
  versionCache.clear();
145
177
  loginStatusCache.clear();
178
+ keychainItemCache.clear();
146
179
  }
147
180
 
148
181
  /**
@@ -989,6 +1022,19 @@ class Installer {
989
1022
  };
990
1023
  }
991
1024
 
1025
+ // The credential file is there but cannot say (a Cline account sign-in
1026
+ // keeps no key in it, or the file is in a shape this version does not
1027
+ // know). Not "signed out": the run decides, as for unreadable above.
1028
+ if (credsFile.unknown && signedIn !== false) {
1029
+ return {
1030
+ ready: false,
1031
+ auth_mode: null,
1032
+ auth_status: 'unknown',
1033
+ execution_mode: 'unavailable',
1034
+ message: checkReady.unknown_message || checkReady.not_ready_message || 'Sign-in could not be confirmed.',
1035
+ };
1036
+ }
1037
+
992
1038
  // No positive signal. For agents whose auth cannot be reliably probed
993
1039
  // without running them (generic `check_ready.unverifiable`), this is
994
1040
  // 'unknown' — they may already be signed in via a CLI login / keychain /
@@ -1034,14 +1080,18 @@ class Installer {
1034
1080
  const stat = fs.statSync(credsPath);
1035
1081
  if (stat.isDirectory()) return fs.readdirSync(credsPath).length > 0;
1036
1082
  const creds = JSON.parse(fs.readFileSync(credsPath, 'utf-8'));
1083
+ const verdict = classifyCreds(checkReady, creds);
1084
+ if (verdict) return verdict === 'ready';
1037
1085
  if (checkReady.creds_key) return !!creds[checkReady.creds_key];
1038
1086
  return true;
1039
1087
  }
1040
1088
  } catch {}
1041
1089
  }
1042
1090
 
1091
+ // The item's presence is the signal; creds_key cannot be checked here
1092
+ // without reading the secret out, which is what _checkMacKeychain avoids.
1043
1093
  if (checkReady.keychain_service && process.platform === 'darwin') {
1044
- if (this._checkMacKeychain(checkReady.keychain_service, checkReady.creds_key)) {
1094
+ if (this._checkMacKeychain(checkReady.keychain_service)) {
1045
1095
  return true;
1046
1096
  }
1047
1097
  }
@@ -1095,7 +1145,8 @@ class Installer {
1095
1145
 
1096
1146
  /**
1097
1147
  * Existence/readability of a credential file. Returns 'present' |
1098
- * 'unreadable' | 'absent'. A non-empty readable file (or a non-empty
1148
+ * 'unreadable' | 'absent', or 'unknown' when the entry's creds_classifier
1149
+ * cannot tell from the content. A non-empty readable file (or a non-empty
1099
1150
  * directory) is normally 'present'. Entries with creds_json_has_entries
1100
1151
  * additionally require at least one top-level JSON entry, allowing an empty
1101
1152
  * auto-created {} file to remain signed out. Credential values are never
@@ -1114,6 +1165,13 @@ class Installer {
1114
1165
  const st = fs.statSync(p);
1115
1166
  if (st.isDirectory()) return fs.readdirSync(p).length > 0 ? 'present' : 'absent';
1116
1167
  fs.accessSync(p, fs.constants.R_OK);
1168
+ if (checkReady.creds_classifier) {
1169
+ const raw = fs.readFileSync(p, 'utf-8');
1170
+ let parsed;
1171
+ try { parsed = JSON.parse(raw); } catch { parsed = { __parse_error: true }; }
1172
+ const verdict = classifyCreds(checkReady, parsed);
1173
+ if (verdict) return verdict === 'ready' ? 'present' : verdict === 'unknown' ? 'unknown' : 'absent';
1174
+ }
1117
1175
  if (checkReady.creds_json_has_entries) {
1118
1176
  const parsed = JSON.parse(fs.readFileSync(p, 'utf-8'));
1119
1177
  if (Array.isArray(parsed)) return parsed.length > 0 ? 'present' : 'absent';
@@ -1143,14 +1201,20 @@ class Installer {
1143
1201
  * Opt-in, content-free creds-file readiness. Active ONLY when
1144
1202
  * `check_ready.creds_no_parse` is set, so existing creds_file agents (which
1145
1203
  * parse + match `creds_key` via _checkCredsReady) keep their exact behavior.
1146
- * Returns { ready, unreadable }.
1204
+ * Returns { ready, unreadable }, plus `unknown: true` when the entry's
1205
+ * creds_classifier cannot tell from the file.
1147
1206
  */
1148
1207
  _evaluateCredsFile(checkReady, agentType) {
1149
1208
  if (!this._credsFile(checkReady) || !checkReady.creds_no_parse) {
1150
1209
  return { ready: false, unreadable: false };
1151
1210
  }
1152
1211
  const state = this._credsFileState(checkReady, agentType);
1153
- return { ready: state === 'present', unreadable: state === 'unreadable' };
1212
+ return {
1213
+ ready: state === 'present',
1214
+ unreadable: state === 'unreadable',
1215
+ // Only a creds_classifier can say this; left out otherwise.
1216
+ ...(state === 'unknown' ? { unknown: true } : {}),
1217
+ };
1154
1218
  }
1155
1219
 
1156
1220
  /**
@@ -1176,23 +1240,46 @@ class Installer {
1176
1240
  }
1177
1241
 
1178
1242
  /**
1179
- * Check a macOS Keychain generic-password entry. If creds_key is provided the
1180
- * stored value is parsed as JSON and required to contain that key; otherwise any
1181
- * non-empty value counts as ready. Returns false on non-macOS or on any error.
1243
+ * Whether a macOS Keychain generic-password item exists for `service`.
1244
+ *
1245
+ * Asks for the item's attributes only. `-w` would print the stored secret,
1246
+ * and a background process pulling a CLI's token out of the Keychain every
1247
+ * detection round is the credential-dumping pattern EDR tools flag
1248
+ * (CrowdStrike Falcon raised it every two minutes, once per round). Sign-in
1249
+ * detection only needs to know the item is there, so nothing is decrypted
1250
+ * and no ACL prompt can appear. Spawned without a shell, so the process
1251
+ * chain ends at `security` itself.
1252
+ *
1253
+ * Cached like _checkWindowsCredential, and never waited on in Electron main.
1182
1254
  */
1183
- _checkMacKeychain(service, credsKey) {
1184
- try {
1185
- const stdout = execSync(
1186
- `security find-generic-password -s ${JSON.stringify(service)} -w`,
1187
- { stdio: ['ignore', 'pipe', 'ignore'], timeout: 5000, encoding: 'utf-8' },
1188
- ).trim();
1189
- if (!stdout) return false;
1190
- if (!credsKey) return true;
1191
- const creds = JSON.parse(stdout);
1192
- return !!creds[credsKey];
1193
- } catch {
1194
- return false;
1255
+ _checkMacKeychain(service) {
1256
+ if (!service) return false;
1257
+ const cached = keychainItemCache.get(service);
1258
+ const fresh = cached && (Date.now() - cached.ts) < STATUS_CACHE_TTL_MS;
1259
+ const args = ['find-generic-password', '-s', service];
1260
+ if (!fresh && canBlock()) {
1261
+ let found = false;
1262
+ try {
1263
+ const run = (this._spawnSyncForTest || spawnSync)('security', args, {
1264
+ stdio: ['ignore', 'ignore', 'ignore'],
1265
+ timeout: 5000,
1266
+ });
1267
+ found = !run.error && run.status === 0;
1268
+ } catch {}
1269
+ keychainItemCache.set(service, { found, ts: Date.now() });
1270
+ } else if (!fresh && !keychainRefreshing.has(service)) {
1271
+ // Answer from the last lookup now; the refresh lands for the next call.
1272
+ keychainRefreshing.add(service);
1273
+ try {
1274
+ execFile('security', args, { timeout: 5000 }, (err) => {
1275
+ keychainRefreshing.delete(service);
1276
+ keychainItemCache.set(service, { found: !err, ts: Date.now() });
1277
+ });
1278
+ } catch {
1279
+ keychainRefreshing.delete(service);
1280
+ }
1195
1281
  }
1282
+ return !!(keychainItemCache.get(service) || {}).found;
1196
1283
  }
1197
1284
 
1198
1285
  /**
package/src/probe.js CHANGED
@@ -37,6 +37,7 @@ const { shouldUseShellForBinary, REASON } = require('./adapters/health-status');
37
37
  const { decodeConsoleOutput, BENIGN_CLI_OUTPUT, stripCliNoise } = require('./adapters/utils');
38
38
  const { formatAuthGuidance } = require('./auth-guidance');
39
39
  const { isCliLogin, stripForCliLogin, typeEnvFor } = require('./env');
40
+ const { configuredModel } = require('./agent-model');
40
41
 
41
42
  const PROBE_PROMPT = 'hi';
42
43
  const DEFAULT_TIMEOUT_MS = 90_000;
@@ -139,7 +140,10 @@ function classifyOutputText(text) {
139
140
  // authenticate: OAuth session expired and could not be refreshed".
140
141
  if (/session expired|could not be refreshed|(token|sign-?in|login) (has )?expired|run \/logout and \/login/.test(text)) return CODE.SESSION_EXPIRED;
141
142
  if (/not logged in|not authenticated|login required|authentication required|please (log ?in|sign ?in|authenticate)|(run|use) .{0,40}login|no credentials/.test(text)) return CODE.NOT_LOGGED_IN;
142
- if (/unrecognized_model|model_not_found|invalid model|issue with the selected model|unknown model|model.{0,40}(does not exist|not found|not exist|is not supported)/.test(text)) return CODE.BAD_MODEL;
143
+ // "Model 'x' is not available. This gateway only allows: …" is how the
144
+ // OpenAgents gateway refuses a model; read as a CLI error it sent people to
145
+ // a terminal to debug a model name.
146
+ if (/unrecognized_model|model_not_found|invalid model|no such model|issue with the selected model|unknown model|model.{0,40}(does not exist|not found|not exist|is not supported|is not available)/.test(text)) return CODE.BAD_MODEL;
143
147
  if (/\b50[234]\b|service (is )?(temporarily )?unavailable|temporarily unavailable|bad gateway|gateway time-?out/.test(text)) return CODE.SERVICE_UNAVAILABLE;
144
148
  return null;
145
149
  }
@@ -242,16 +246,8 @@ function buildGuidance(code, entry, agentEnv, extra = {}) {
242
246
  * more honestly than "everything is fine" would. Likewise an unclassifiable
243
247
  * error — swapping one shrug for another helps nobody.
244
248
  */
245
- async function directApiVerdict(agentEnv, entry) {
246
- // Required here rather than at the top so a test can stand in for it, and
247
- // so a probe that never reaches this path never loads the HTTP client.
248
- const { testLLMConnection } = require('./utils');
249
- let res;
250
- try {
251
- res = await testLLMConnection(agentEnv);
252
- } catch (e) {
253
- res = { success: false, error: e.message };
254
- }
249
+ async function directApiVerdict(agentEnv, entry, model, baseUrl, protocol) {
250
+ const res = await callLLM(agentEnv, model, baseUrl, protocol);
255
251
  if (!res || res.success) return null;
256
252
  const code = classifyFailure(res.error, {});
257
253
  if (code === CODE.CLI_ERROR) return null;
@@ -264,6 +260,61 @@ async function directApiVerdict(agentEnv, entry) {
264
260
  };
265
261
  }
266
262
 
263
+ /**
264
+ * Where a direct test must call for the key the agent holds. The client reads
265
+ * LLM_BASE_URL, OPENAI_BASE_URL and KIMI_BASE_URL, else calls OpenAI (or
266
+ * Anthropic, Moonshot): right for a key of theirs, wrong for a type that
267
+ * takes the generic key under a name of its own (DEEPSEEK_API_KEY,
268
+ * PI_API_KEY) and keeps its endpoint under one too. A DeepSeek key with no
269
+ * endpoint set went to OpenAI and came back "invalid key" from an agent that
270
+ * works. Returns that endpoint; undefined to leave it to the client; null
271
+ * when none is known, and there is nothing worth calling.
272
+ */
273
+ function directBaseUrl(entry, env) {
274
+ if (!env.LLM_API_KEY || env.LLM_BASE_URL) return undefined;
275
+ const rules = (entry && entry.resolve_env && entry.resolve_env.rules) || [];
276
+ const keyTo = rules.filter((r) => r && r.from === 'LLM_API_KEY' && r.to).map((r) => r.to);
277
+ if (!keyTo.length || keyTo.some((k) => /^(OPENAI|ANTHROPIC|KIMI|MOONSHOT)_/.test(k))) return undefined;
278
+ const own = [
279
+ ...rules.filter((r) => r && r.from === 'LLM_BASE_URL' && r.to).map((r) => r.to),
280
+ ...((entry && entry.env_config) || []).map((f) => f && f.name).filter((n) => n && /(BASE_URL|API_BASE)$/.test(n)),
281
+ ];
282
+ const found = own.find((k) => String(env[k] || '').trim());
283
+ return found ? String(env[found]).trim() : null;
284
+ }
285
+
286
+ /**
287
+ * The API a direct test must speak, where the agent's own config names it
288
+ * rather than its endpoint or key: 'anthropic' or 'openai'; undefined to
289
+ * leave it to the client; null for a format the test does not speak. A Pi
290
+ * agent on anthropic-messages behind a relay whose host says nothing was
291
+ * sent /chat/completions and reported broken.
292
+ */
293
+ function directProtocol(type, env) {
294
+ if (type !== 'pi') return undefined;
295
+ const { piApiFormat } = require('./adapters/pi-stream');
296
+ const format = piApiFormat(env);
297
+ if (!format) return undefined;
298
+ if (format === 'anthropic-messages') return 'anthropic';
299
+ if (format === 'openai-completions') return 'openai';
300
+ return null;
301
+ }
302
+
303
+ /**
304
+ * One direct call to the agent's endpoint, on the model the agent runs on.
305
+ * Never rejects.
306
+ */
307
+ async function callLLM(agentEnv, model, baseUrl, protocol) {
308
+ // Required here rather than at the top so a test can stand in for it, and
309
+ // so a probe that never reaches this path never loads the HTTP client.
310
+ const { testLLMConnection } = require('./utils');
311
+ try {
312
+ return await testLLMConnection(agentEnv, { model, ...(baseUrl ? { baseUrl } : {}), ...(protocol ? { protocol } : {}) });
313
+ } catch (e) {
314
+ return { success: false, error: e.message };
315
+ }
316
+ }
317
+
267
318
  /**
268
319
  * Stop a CLI that ran too long. On Windows a .cmd shim runs under cmd.exe, and
269
320
  * killing that leaves the node process it started alive (see cli-models.js).
@@ -396,6 +447,8 @@ async function probeAgentType(connector, type, opts = {}) {
396
447
  const resolved = connector.resolveAgentEnv(type, saved) || {};
397
448
  agentEnv = stripForCliLogin(type, { ...saved, ...resolved }, connector.registry, opts.agentEnv);
398
449
  } catch {}
450
+ // Where the adapter reads it (CODEX_MODEL for codex), not LLM_MODEL alone.
451
+ const model = configuredModel(type, agentEnv, connector.registry);
399
452
 
400
453
  if (!health.installed) {
401
454
  return done({
@@ -455,6 +508,11 @@ async function probeAgentType(connector, type, opts = {}) {
455
508
  || (entry.probe && entry.probe.timeout_s ? entry.probe.timeout_s * 1000 : DEFAULT_TIMEOUT_MS);
456
509
  const env = stripForCliLogin(type, { ...getEnhancedEnv(), ...agentEnv }, connector.registry, opts.agentEnv);
457
510
 
511
+ const baseUrl = directBaseUrl(entry, agentEnv);
512
+ const protocol = directProtocol(type, agentEnv);
513
+ const reachable = baseUrl !== null && protocol !== null;
514
+ const canCallDirect = hasApiKey && reachable;
515
+
458
516
  // ── Live tier 1: the agent's own CLI, when the registry declares how ──
459
517
  if (hasLiveCli) {
460
518
  const shell = probeArgs && health.binary ? shouldUseShellForBinary(health.binary) : true;
@@ -493,8 +551,8 @@ async function probeAgentType(connector, type, opts = {}) {
493
551
  // broken. Where the agent carries an endpoint and a key, ask the API the
494
552
  // same question directly: one round trip, and it says why.
495
553
  const unexplained = code === CODE.TIMEOUT || code === CODE.CLI_ERROR || code === CODE.EMPTY_RESPONSE;
496
- if (unexplained && hasApiKey) {
497
- const direct = await directApiVerdict(agentEnv, entry);
554
+ if (unexplained && canCallDirect) {
555
+ const direct = await directApiVerdict(agentEnv, entry, model, baseUrl, protocol);
498
556
  if (direct) return done(direct);
499
557
  }
500
558
  if (unexplained && staticVerdict) return done(staticVerdict);
@@ -507,10 +565,8 @@ async function probeAgentType(connector, type, opts = {}) {
507
565
  }
508
566
 
509
567
  // ── Live tier 2: direct LLM API call for API-key agents (e.g. OpenClaw) ──
510
- if (hasApiKey || (entry.install && entry.install.api_only)) {
511
- const { testLLMConnection } = require('./utils');
512
- let res;
513
- try { res = await testLLMConnection(agentEnv); } catch (e) { res = { success: false, error: e.message }; }
568
+ if (canCallDirect || (entry.install && entry.install.api_only && reachable)) {
569
+ const res = await callLLM(agentEnv, model, baseUrl, protocol);
514
570
  if (res && res.success) {
515
571
  return done({
516
572
  ok: true, method: 'llm_api', code: CODE.OK,
package/src/utils.js CHANGED
@@ -94,16 +94,24 @@ function completionResult(res, { isAnthropic, model }) {
94
94
  * Supports OpenAI-compatible and Anthropic APIs.
95
95
  *
96
96
  * @param {object} env - Env vars (LLM_API_KEY, LLM_BASE_URL, LLM_MODEL, etc.)
97
+ * @param {object} [opts]
98
+ * @param {string} [opts.model] - The model the agent runs on, when the caller
99
+ * knows it. Each type keeps it under its own variable (CODEX_MODEL,
100
+ * ANTHROPIC_MODEL), which `env` alone does not say; see agent-model.js.
101
+ * @param {string} [opts.baseUrl] - The endpoint, when the caller knows it from
102
+ * a variable of the agent's own (DEEPSEEK_BASE_URL); see probe.js.
103
+ * @param {'anthropic'|'openai'} [opts.protocol] - The API to speak, when the
104
+ * agent's config names it (Pi's PI_API_FORMAT) rather than its env shape.
97
105
  * @returns {Promise<{success: boolean, model?: string, response?: string, error?: string}>}
98
106
  */
99
- async function testLLMConnection(env) {
107
+ async function testLLMConnection(env, opts = {}) {
100
108
  const hasKimiConfig = !!(env.KIMI_API_KEY || env.MOONSHOT_API_KEY || env.KIMI_BASE_URL || env.KIMI_MODEL);
101
109
  const apiKey = env.KIMI_API_KEY || env.MOONSHOT_API_KEY || env.LLM_API_KEY || env.OPENAI_API_KEY
102
110
  || env.ANTHROPIC_AUTH_TOKEN || env.ANTHROPIC_API_KEY || '';
103
111
  if (!apiKey) return { success: false, error: 'No API key provided' };
104
112
 
105
- let baseUrl = (env.KIMI_BASE_URL || env.LLM_BASE_URL || env.OPENAI_BASE_URL || (hasKimiConfig ? 'https://api.moonshot.ai/v1' : 'https://api.openai.com/v1')).replace(/\/$/, '');
106
- const model = env.KIMI_MODEL || env.LLM_MODEL || env.OPENCLAW_MODEL || '';
113
+ let baseUrl = (opts.baseUrl || env.KIMI_BASE_URL || env.LLM_BASE_URL || env.OPENAI_BASE_URL || (hasKimiConfig ? 'https://api.moonshot.ai/v1' : 'https://api.openai.com/v1')).replace(/\/$/, '');
114
+ const model = String(opts.model || env.KIMI_MODEL || env.LLM_MODEL || env.OPENCLAW_MODEL || '').trim();
107
115
  // An agent configured the Anthropic way is Anthropic-shaped wherever it
108
116
  // points. Reading only the URL missed every relay whose host says nothing
109
117
  // about the protocol it speaks — the common case for Claude Code, which is
@@ -111,7 +119,9 @@ async function testLLMConnection(env) {
111
119
  // default endpoint with an Anthropic key.
112
120
  const hasAnthropicConfig = !hasKimiConfig && !env.LLM_API_KEY && !env.OPENAI_API_KEY
113
121
  && !!(env.ANTHROPIC_BASE_URL || env.ANTHROPIC_MODEL || env.ANTHROPIC_AUTH_TOKEN || env.ANTHROPIC_API_KEY);
114
- const isAnthropic = hasAnthropicConfig || baseUrl.includes('anthropic');
122
+ const isAnthropic = opts.protocol
123
+ ? opts.protocol === 'anthropic'
124
+ : hasAnthropicConfig || baseUrl.includes('anthropic');
115
125
 
116
126
  if (!isAnthropic && !baseUrl.endsWith('/v1')) {
117
127
  baseUrl += '/v1';
@@ -121,7 +131,9 @@ async function testLLMConnection(env) {
121
131
  // The configured endpoint, not the official one: a relay IS the API as
122
132
  // far as this agent is concerned, and testing api.anthropic.com would
123
133
  // report on a service the agent never talks to.
124
- const base = (env.ANTHROPIC_BASE_URL || 'https://api.anthropic.com').replace(/\/+$/, '');
134
+ // The caller's endpoint first, then the generic one: a relay named only
135
+ // in LLM_BASE_URL was skipped for the official host.
136
+ const base = (opts.baseUrl || env.ANTHROPIC_BASE_URL || env.LLM_BASE_URL || 'https://api.anthropic.com').replace(/\/+$/, '');
125
137
  const url = /\/v1$/.test(base) ? `${base}/messages` : `${base}/v1/messages`;
126
138
  const token = env.ANTHROPIC_AUTH_TOKEN || env.ANTHROPIC_API_KEY || apiKey;
127
139
  const headers = {
@@ -4,6 +4,8 @@ const https = require('https');
4
4
  const http = require('http');
5
5
 
6
6
  const DEFAULT_ENDPOINT = 'https://workspace-endpoint.openagents.org';
7
+ // Agent progress noise that never belongs in a conversation transcript.
8
+ const RECENT_MESSAGES_EXCLUDED_TYPES = 'status,thinking,todos,loading';
7
9
 
8
10
  /**
9
11
  * The error a request deadline produces. Every request carries a hard
@@ -369,10 +371,24 @@ class WorkspaceClient {
369
371
  }
370
372
 
371
373
  /**
372
- * Send a chat message to a workspace channel.
374
+ * Detect safe retry support before using a durable message outbox.
373
375
  */
376
+ async supportsMessageDelivery() {
377
+ if (this._messageDeliverySupported !== undefined && Date.now() < this._messageDeliveryCheckUntil) return this._messageDeliverySupported;
378
+ try {
379
+ const result = await this._get('/v1/events/delivery-capabilities');
380
+ this._messageDeliverySupported = (result.data || result).idempotent_messages === true;
381
+ } catch (e) {
382
+ if (e.status !== 404) throw e;
383
+ this._messageDeliverySupported = false;
384
+ }
385
+ this._messageDeliveryCheckUntil = Date.now() + 60000;
386
+ return this._messageDeliverySupported;
387
+ }
388
+
389
+ /** Send a chat message, optionally with a stable delivery key. */
374
390
  async sendMessage(workspaceId, channelName, token, content, {
375
- senderType = 'agent', senderName, messageType = 'chat', metadata, attachments, sessionId,
391
+ senderType = 'agent', senderName, messageType = 'chat', metadata, attachments, sessionId, idempotencyKey,
376
392
  } = {}) {
377
393
  const sourcePrefix = senderType === 'agent' ? 'openagents' : 'human';
378
394
  const source = senderName ? `${sourcePrefix}:${senderName}` : `${sourcePrefix}:unknown`;
@@ -393,6 +409,7 @@ class WorkspaceClient {
393
409
  }
394
410
  return this.sendEvent(workspaceId, {
395
411
  type: 'workspace.message.posted',
412
+ ...(idempotencyKey ? { idempotency_key: idempotencyKey } : {}),
396
413
  source,
397
414
  target: counterpart,
398
415
  payload,
@@ -403,6 +420,7 @@ class WorkspaceClient {
403
420
 
404
421
  return this.sendEvent(workspaceId, {
405
422
  type: 'workspace.message.posted',
423
+ ...(idempotencyKey ? { idempotency_key: idempotencyKey } : {}),
406
424
  source,
407
425
  target: `channel/${channelName}`,
408
426
  payload,
@@ -436,8 +454,16 @@ class WorkspaceClient {
436
454
  * to rebuild context for a fresh Claude Code session when --resume of the
437
455
  * previous session fails (the channel's chat history is the only thing
438
456
  * that survives a session-storage rotation).
457
+ *
458
+ * Agent status/thinking/todos/loading events are dropped server-side by
459
+ * default: one tool-heavy agent turn posts dozens of them into the same
460
+ * channel, and filtering only after the fetch left a "100 event" window
461
+ * holding a handful of real chat messages (OA-026). Pass
462
+ * `excludeMessageTypes: ''` to get every event.
439
463
  */
440
- async getRecentMessages(workspaceId, channelName, token, limit = 30, { sort = 'desc', before, timeout, throwOnError = false } = {}) {
464
+ async getRecentMessages(workspaceId, channelName, token, limit = 30, {
465
+ sort = 'desc', before, timeout, throwOnError = false, excludeMessageTypes = RECENT_MESSAGES_EXCLUDED_TYPES,
466
+ } = {}) {
441
467
  try {
442
468
  const params = new URLSearchParams({
443
469
  network: workspaceId,
@@ -447,6 +473,7 @@ class WorkspaceClient {
447
473
  limit: String(limit),
448
474
  });
449
475
  if (before) params.set('before', before);
476
+ if (excludeMessageTypes) params.set('exclude_message_types', excludeMessageTypes);
450
477
  const data = await this._get(`/v1/events?${params}`, this._wsHeaders(token), timeout);
451
478
  const result = data.data || data;
452
479
  const events = (result && result.events) || [];
@@ -1313,7 +1340,9 @@ class WorkspaceClient {
1313
1340
  resolve(parsed);
1314
1341
  }
1315
1342
  } catch {
1316
- reject(new Error(`Invalid response: ${data.slice(0, 200)}`));
1343
+ const err = new Error(`Invalid response (HTTP ${res.statusCode})`);
1344
+ err.status = res.statusCode;
1345
+ reject(err);
1317
1346
  }
1318
1347
  });
1319
1348
  });