@openagents-org/agent-launcher 0.2.205 → 0.2.207

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openagents-org/agent-launcher",
3
- "version": "0.2.205",
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 (
@@ -1096,7 +1106,12 @@ class ClaudeAdapter extends BaseAdapter {
1096
1106
  }
1097
1107
  } catch {}
1098
1108
  }
1099
- return pp.lastResponseText.join('\n').trim();
1109
+ const response = pp.lastResponseText.join('\n').trim();
1110
+ // Consume this turn before posting it. A persistent CLI can emit another
1111
+ // turn when a background task finishes, without a new user message (and
1112
+ // therefore without _sendToPersistentProc resetting the buffer).
1113
+ pp.lastResponseText = [];
1114
+ return response;
1100
1115
  }
1101
1116
 
1102
1117
  /** True when the CLI reported the resumed conversation no longer fits. */
@@ -1387,12 +1402,14 @@ class ClaudeAdapter extends BaseAdapter {
1387
1402
 
1388
1403
  // Spawn a persistent process and send the first message via stdin
1389
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();
1390
1407
 
1391
1408
  // When starting without a session (no --resume), prepend channel
1392
1409
  // history so the fresh CLI has conversation context.
1393
1410
  if (!this._channelSessions[msgChannel]) {
1394
1411
  try {
1395
- const recap = await this._buildChannelRecap(msgChannel, content);
1412
+ const recap = await this._buildChannelRecap(msgChannel, recapExclude, msg);
1396
1413
  if (recap) effectiveContent = `${recap}\n\n---\n\n${content}`;
1397
1414
  } catch {}
1398
1415
  }
@@ -1404,7 +1421,7 @@ class ClaudeAdapter extends BaseAdapter {
1404
1421
  await this._killPersistentProc(msgChannel);
1405
1422
  // Rebuild recap for retry without resume
1406
1423
  try {
1407
- const recap = await this._buildChannelRecap(msgChannel, content);
1424
+ const recap = await this._buildChannelRecap(msgChannel, recapExclude, msg);
1408
1425
  if (recap) effectiveContent = `${recap}\n\n---\n\n${content}`;
1409
1426
  } catch {}
1410
1427
  }
@@ -30,7 +30,7 @@ const { execSync, execFile } = require('child_process');
30
30
  // spawn() here is the WSL bridge from ../wsl: same signature as
31
31
  // child_process.spawn, and a straight pass-through unless the resolved CLI
32
32
  // lives on the other side of the Windows/WSL boundary.
33
- const { spawn, bridgeSpawn } = require('../wsl');
33
+ const { spawn, bridgeSpawn, isWslBinary } = require('../wsl');
34
34
 
35
35
  const BaseAdapter = require('./base');
36
36
  const { buildOpenclawSystemPrompt } = require('./workspace-prompt');
@@ -814,6 +814,9 @@ class HermesAdapter extends BaseAdapter {
814
814
  *
815
815
  * Only acts when LLM_BASE_URL is set: a user signed in via `hermes setup`
816
816
  * (the Nous login) must keep their own provider selection untouched.
817
+ *
818
+ * The `model:` lines this replaces are recorded (recordNativeAuth), so
819
+ * restoreNativeAuth can hand them back when an agent moves to the sign-in.
817
820
  */
818
821
  static configureNativeAuth(env) {
819
822
  const vals = env || {};
@@ -827,6 +830,9 @@ class HermesAdapter extends BaseAdapter {
827
830
  probe._log = () => {};
828
831
  const bin = probe._findHermesBinary();
829
832
  if (!bin) return { skipped: true, reason: 'hermes binary not found' };
833
+ // An in-distro hermes keeps its config inside WSL, out of reach of a file read.
834
+ const configFile = isWslBinary(bin) ? null : HermesAdapter.configFile();
835
+ const before = configFile ? readTextOrEmpty(configFile) : null;
830
836
 
831
837
  const { execFileSync } = require('child_process');
832
838
  const run = (args) => {
@@ -844,8 +850,160 @@ class HermesAdapter extends BaseAdapter {
844
850
  run(['config', 'set', 'model.base_url', baseUrl]);
845
851
  if (model) run(['config', 'set', 'model.default', model]);
846
852
  if (apiKey) run(['config', 'set', 'model.api_key', apiKey]);
853
+ if (configFile) {
854
+ try { HermesAdapter.recordNativeAuth(configFile, before, readTextOrEmpty(configFile)); } catch {}
855
+ }
847
856
  return { configured: true };
848
857
  }
858
+
859
+ /** The default profile's config.yaml, the one `hermes config set` writes. */
860
+ static configFile(env = process.env) {
861
+ const homeEnv = String(env.HERMES_HOME || '').trim();
862
+ const home = homeEnv || (IS_WINDOWS
863
+ ? path.join(env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'), 'hermes')
864
+ : path.join(os.homedir(), '.hermes'));
865
+ return path.join(home, 'config.yaml');
866
+ }
867
+
868
+ /** Where the `model:` lines from before configureNativeAuth are kept. */
869
+ static nativeAuthRecordFile() {
870
+ return path.join(os.homedir(), '.openagents', 'native-auth', 'hermes.json');
871
+ }
872
+
873
+ /**
874
+ * Remember what configureNativeAuth replaced. `original` is each managed
875
+ * `model:` line from before the FIRST custom endpoint, kept across later
876
+ * ones; `written` identifies each as configureNativeAuth left it, by hash
877
+ * only, so the key it wrote is not copied here.
878
+ */
879
+ static recordNativeAuth(configFile, beforeText, afterText) {
880
+ const recordFile = HermesAdapter.nativeAuthRecordFile();
881
+ const previous = readRecord(recordFile);
882
+ const original = previous && previous.configFile === configFile
883
+ ? previous.original
884
+ : HermesAdapter.modelLines(beforeText);
885
+ const written = {};
886
+ for (const [name, line] of Object.entries(HermesAdapter.modelLines(afterText))) written[name] = hashLine(line);
887
+ fs.mkdirSync(path.dirname(recordFile), { recursive: true });
888
+ // `original` may hold a key of the user's own provider.
889
+ fs.writeFileSync(recordFile, JSON.stringify({ configFile, original, written }, null, 2), { mode: 0o600 });
890
+ }
891
+
892
+ /**
893
+ * Hand Hermes back the `model:` lines configureNativeAuth replaced, for an
894
+ * agent that now runs on the `hermes setup` sign-in. Without this the custom
895
+ * endpoint and key stayed in config.yaml, and the signed-in agent kept
896
+ * calling them (401 once the key was gone or wrong).
897
+ *
898
+ * Only while every one of them is still exactly what configureNativeAuth
899
+ * wrote: lines the user has changed since (`hermes setup`, `hermes model`)
900
+ * are theirs and stay. Either way the record is dropped.
901
+ */
902
+ static restoreNativeAuth() {
903
+ const recordFile = HermesAdapter.nativeAuthRecordFile();
904
+ const record = readRecord(recordFile);
905
+ if (!record) return { skipped: true, reason: 'nothing recorded' };
906
+ const drop = () => { try { fs.unlinkSync(recordFile); } catch {} };
907
+ let text;
908
+ try { text = fs.readFileSync(record.configFile, 'utf8'); } catch {
909
+ drop();
910
+ return { skipped: true, reason: 'config.yaml not found' };
911
+ }
912
+ const current = HermesAdapter.modelLines(text);
913
+ if (Object.keys(current).some((name) => hashLine(current[name]) !== (record.written || {})[name])) {
914
+ drop();
915
+ return { skipped: true, reason: 'model section changed since' };
916
+ }
917
+ fs.writeFileSync(record.configFile, HermesAdapter.restoreModelLines(text, record.original || {}));
918
+ drop();
919
+ return { restored: true };
920
+ }
921
+
922
+ /**
923
+ * The lines of a config.yaml text that configureNativeAuth writes, verbatim
924
+ * or null where absent: the top-level `model:` line itself (`hermes config
925
+ * set` turns a plain `model: <id>` into a mapping) and its `default`,
926
+ * `provider`, `base_url` and `api_key` keys.
927
+ */
928
+ static modelLines(text) {
929
+ const { lines, at } = locateModelLines(text);
930
+ const out = {};
931
+ for (const name of MODEL_LINE_NAMES) out[name] = at[name] >= 0 ? lines[at[name]] : null;
932
+ return out;
933
+ }
934
+
935
+ /**
936
+ * `text` with each managed `model:` line put back as `original` has it: a
937
+ * line that was not there before is removed, one that was is restored in
938
+ * place (or under `model:`). Every other line, comments included, is left
939
+ * exactly as it is.
940
+ */
941
+ static restoreModelLines(text, original) {
942
+ const { lines, at } = locateModelLines(text);
943
+ const eol = /\r\n/.test(String(text || '')) ? '\r\n' : '\n';
944
+ const drop = new Set();
945
+ const insert = [];
946
+ for (const name of MODEL_LINE_NAMES) {
947
+ const was = original[name] == null ? null : String(original[name]);
948
+ if (at[name] >= 0) {
949
+ if (was == null) drop.add(at[name]);
950
+ else lines[at[name]] = was;
951
+ } else if (was != null && name !== 'header') {
952
+ insert.push(was);
953
+ }
954
+ }
955
+ const out = [];
956
+ lines.forEach((line, i) => {
957
+ if (!drop.has(i)) out.push(line);
958
+ if (i === at.header && !drop.has(i)) out.push(...insert);
959
+ });
960
+ return out.join(eol);
961
+ }
962
+ }
963
+
964
+ // What configureNativeAuth writes into config.yaml: the `model:` line and these keys under it.
965
+ const MODEL_KEYS = ['default', 'provider', 'base_url', 'api_key'];
966
+ const MODEL_LINE_NAMES = ['header', ...MODEL_KEYS];
967
+
968
+ /**
969
+ * Line indexes of the managed `model:` lines (-1 where absent). The section
970
+ * runs to the next top-level key: Hermes's own config.yaml has a long run of
971
+ * column-0 comments inside it, and `hermes config set model.api_key` appends
972
+ * the key after them. Only direct children count, by their indentation.
973
+ */
974
+ function locateModelLines(text) {
975
+ const lines = String(text || '').split(/\r?\n/);
976
+ const at = Object.fromEntries(MODEL_LINE_NAMES.map((name) => [name, -1]));
977
+ at.header = lines.findIndex((line) => /^model[ \t]*:/.test(line));
978
+ if (at.header < 0) return { lines, at };
979
+ let indent = null;
980
+ for (let i = at.header + 1; i < lines.length; i++) {
981
+ const line = lines[i];
982
+ if (line.trim() === '' || line.startsWith('#')) continue;
983
+ const m = /^([ \t]+)([A-Za-z_]+)[ \t]*:/.exec(line);
984
+ if (!/^[ \t]/.test(line)) break;
985
+ if (/^[ \t]*#/.test(line) || !m) continue;
986
+ if (indent == null) indent = m[1];
987
+ if (m[1] === indent && MODEL_KEYS.includes(m[2]) && at[m[2]] < 0) at[m[2]] = i;
988
+ }
989
+ return { lines, at };
990
+ }
991
+
992
+ function hashLine(line) {
993
+ return line == null ? null : crypto.createHash('sha256').update(line).digest('hex');
994
+ }
995
+
996
+ function readTextOrEmpty(file) {
997
+ try { return fs.readFileSync(file, 'utf8'); } catch { return ''; }
998
+ }
999
+
1000
+ function readRecord(file) {
1001
+ try {
1002
+ const record = JSON.parse(fs.readFileSync(file, 'utf8'));
1003
+ return record && typeof record.configFile === 'string' ? record : null;
1004
+ } catch {
1005
+ return null;
1006
+ }
849
1007
  }
850
1008
 
851
1009
  module.exports = HermesAdapter;
@@ -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,