@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/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.208",
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,8 +20,10 @@
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');
26
+ const { ResponseOutbox } = require('./response-outbox');
25
27
  const fs = require('fs');
26
28
  const os = require('os');
27
29
  const path = require('path');
@@ -134,18 +136,6 @@ const CONTROL_POLL_DEADLINE_MS = 20 * 1000;
134
136
  const CONTROL_ACTION_DEADLINE_MS = 60 * 1000;
135
137
  const CONTROL_DEADLINE_HIT = Symbol('control deadline hit');
136
138
 
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
139
  /**
150
140
  * Wrap an adapter's `_channelProcesses` so registering a child for a turn that
151
141
  * was already stopped kills it at once (see `_onProcessRegistered`).
@@ -422,17 +412,7 @@ class BaseAdapter {
422
412
  modelLabel() {
423
413
  const fromWorkspace = String(this.workspaceModel || '').trim();
424
414
  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;
415
+ return configuredModel(this.agentType, this.agentEnv);
436
416
  }
437
417
 
438
418
  async run() {
@@ -468,6 +448,8 @@ class BaseAdapter {
468
448
  // /status responsive immediately after join.
469
449
  await this._skipExistingControlEvents();
470
450
  const heartbeatInterval = setInterval(() => this._heartbeat(), 30000);
451
+ const responseInterval = setInterval(() => this._flushResponses(), 10000);
452
+ void this._flushResponses();
471
453
  const controlPoller = this._controlPollerLoop();
472
454
 
473
455
  try {
@@ -483,6 +465,7 @@ class BaseAdapter {
483
465
  this._running = false;
484
466
  this._wakeControlPoller();
485
467
  clearInterval(heartbeatInterval);
468
+ clearInterval(responseInterval);
486
469
  if (this._presenceHeartbeatTimer) { clearTimeout(this._presenceHeartbeatTimer); this._presenceHeartbeatTimer = null; }
487
470
  try { await controlPoller; } catch {}
488
471
  try {
@@ -1853,35 +1836,56 @@ class BaseAdapter {
1853
1836
  async sendResponse(channel, content, { statusKind = 'completed' } = {}) {
1854
1837
  if (this._isMuted(channel)) return;
1855
1838
  try {
1856
- let attachments = [];
1857
- if (!(this.disabledModules || new Set()).has('files') && channel && !channel.startsWith('dm:') && this.client.uploadFile) {
1858
- const published = await publishResponseArtifacts({
1859
- content,
1860
- workingDir: this.workingDir,
1861
- upload: (filename, bytes, contentType) => this.client.uploadFile(this.workspaceId, this.token, filename, bytes, {
1862
- contentType, source: `openagents:${this.agentName}`, channelName: channel, visibility: 'inherit',
1863
- }),
1864
- onError: () => this._log('Could not attach a linked document; leaving its original link in the reply.'),
1865
- });
1866
- content = published.content;
1867
- attachments = published.attachments;
1868
- }
1869
- await this.client.sendMessage(this.workspaceId, channel, this.token, content, {
1870
- attachments,
1871
- senderType: 'agent',
1872
- senderName: this.agentName,
1839
+ await this._replyOutbox().enqueue({
1840
+ channel, content,
1873
1841
  metadata: { status_kind: statusKind, ...(this._channelTriggerId?.[channel] ? { in_reply_to: this._channelTriggerId[channel] } : {}) },
1874
- sessionId: this._sessionId,
1875
1842
  });
1876
1843
  } catch (e) {
1877
- if (e instanceof SessionRevokedError) {
1878
- this._onSessionRevoked();
1879
- return;
1880
- }
1844
+ this._log('Could not save or deliver the final reply; check the local response outbox and disk permissions.', 'error');
1881
1845
  throw e;
1882
1846
  }
1883
1847
  }
1884
1848
 
1849
+ _replyOutbox() {
1850
+ if (!this._responseOutbox) this._responseOutbox = new ResponseOutbox({
1851
+ endpoint: this.endpoint, workspaceId: this.workspaceId, agentName: this.agentName,
1852
+ directory: this._responseOutboxDirectory,
1853
+ log: (message, level) => this._log(message, level),
1854
+ onRevoked: () => this._onSessionRevoked(),
1855
+ prepare: async (entry) => {
1856
+ // Old/custom servers may not support idempotency. Never blindly retry
1857
+ // an ambiguous send against one of those servers.
1858
+ const safeRetry = this.client.supportsMessageDelivery
1859
+ ? await this.client.supportsMessageDelivery() : false;
1860
+ let published = { content: entry.content, attachments: [] };
1861
+ if (!(this.disabledModules || new Set()).has('files') && entry.channel && !entry.channel.startsWith('dm:') && this.client.uploadFile) {
1862
+ published = await publishResponseArtifacts({
1863
+ content: entry.content, workingDir: this.workingDir,
1864
+ upload: (filename, bytes, contentType) => this.client.uploadFile(this.workspaceId, this.token, filename, bytes, {
1865
+ contentType, source: `openagents:${this.agentName}`, channelName: entry.channel, visibility: 'inherit',
1866
+ }),
1867
+ onError: () => this._log('Could not attach a linked document; leaving its original link in the reply.'),
1868
+ });
1869
+ }
1870
+ return { ...published, safeRetry };
1871
+ },
1872
+ send: async (entry) => {
1873
+ if (this._isMuted(entry.channel)) throw new Error('Channel is muted');
1874
+ return this.client.sendMessage(this.workspaceId, entry.channel, this.token, entry.content, {
1875
+ attachments: entry.attachments, senderType: 'agent', senderName: this.agentName,
1876
+ metadata: entry.metadata, sessionId: this._sessionId,
1877
+ idempotencyKey: entry.safeRetry ? entry.id : undefined,
1878
+ });
1879
+ },
1880
+ });
1881
+ return this._responseOutbox;
1882
+ }
1883
+
1884
+ async _flushResponses() {
1885
+ try { await this._replyOutbox().flush(); }
1886
+ catch { this._log('Could not drain the response outbox; saved replies retained.', 'error'); }
1887
+ }
1888
+
1885
1889
  async cleanupTodos(channel) {
1886
1890
  try {
1887
1891
  const result = await this.client.getTodos(this.workspaceId, channel, this.token, {
@@ -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 (
@@ -516,14 +526,17 @@ class ClaudeAdapter extends BaseAdapter {
516
526
  // process.cwd() as the fallback — on a packaged Windows daemon that is
517
527
  // C:\WINDOWS\system32 and mkdir there throws EPERM.
518
528
  const workDir = this.workingDir || defaultAgentWorkdir(this.agentName);
519
- const skillDir = path.join(workDir, '.claude', 'skills');
520
- fs.mkdirSync(skillDir, { recursive: true });
521
- // Per-agent filename: agents sharing a working directory used to clobber
529
+ const skillsRoot = path.join(workDir, '.claude', 'skills');
530
+ const skillDir = path.join(skillsRoot, workspaceSkillName(this.agentName));
531
+ fs.mkdirSync(skillDir, { recursive: true, mode: 0o700 });
532
+ // Per-agent directory: Claude discovers <name>/SKILL.md, not flat .md files.
533
+ // Agents sharing a working directory used to clobber
522
534
  // one shared openagents-workspace.md, so uploads carried the identity of
523
535
  // whichever agent wrote the file last. Drop that legacy file so a stale
524
536
  // copy (with another agent's embedded identity) can never be read again.
525
- const skillFile = path.join(skillDir, `${workspaceSkillName(this.agentName)}.md`);
526
- try { fs.unlinkSync(path.join(skillDir, 'openagents-workspace.md')); } catch {}
537
+ const skillFile = path.join(skillDir, 'SKILL.md');
538
+ try { fs.unlinkSync(path.join(skillsRoot, 'openagents-workspace.md')); } catch {}
539
+ try { fs.unlinkSync(path.join(skillsRoot, `${workspaceSkillName(this.agentName)}.md`)); } catch {}
527
540
 
528
541
  const skillContent = buildClaudeSkillMd({
529
542
  endpoint: this.endpoint,
@@ -534,7 +547,8 @@ class ClaudeAdapter extends BaseAdapter {
534
547
  disabledModules: this.disabledModules,
535
548
  browserEnabled: this._browserEnabledCache === true,
536
549
  });
537
- fs.writeFileSync(skillFile, skillContent, 'utf-8');
550
+ fs.writeFileSync(skillFile, skillContent, { encoding: 'utf-8', mode: 0o600 });
551
+ fs.chmodSync(skillFile, 0o600);
538
552
  this._log(`Wrote workspace skill to ${skillFile}`);
539
553
 
540
554
  return { cmd, skillFile };
@@ -1392,12 +1406,14 @@ class ClaudeAdapter extends BaseAdapter {
1392
1406
 
1393
1407
  // Spawn a persistent process and send the first message via stdin
1394
1408
  let effectiveContent = content;
1409
+ // The trigger's own text, before thread history was prepended to it.
1410
+ const recapExclude = String(msg.originalContent ?? msg.content ?? '').trim();
1395
1411
 
1396
1412
  // When starting without a session (no --resume), prepend channel
1397
1413
  // history so the fresh CLI has conversation context.
1398
1414
  if (!this._channelSessions[msgChannel]) {
1399
1415
  try {
1400
- const recap = await this._buildChannelRecap(msgChannel, content);
1416
+ const recap = await this._buildChannelRecap(msgChannel, recapExclude, msg);
1401
1417
  if (recap) effectiveContent = `${recap}\n\n---\n\n${content}`;
1402
1418
  } catch {}
1403
1419
  }
@@ -1409,7 +1425,7 @@ class ClaudeAdapter extends BaseAdapter {
1409
1425
  await this._killPersistentProc(msgChannel);
1410
1426
  // Rebuild recap for retry without resume
1411
1427
  try {
1412
- const recap = await this._buildChannelRecap(msgChannel, content);
1428
+ const recap = await this._buildChannelRecap(msgChannel, recapExclude, msg);
1413
1429
  if (recap) effectiveContent = `${recap}\n\n---\n\n${content}`;
1414
1430
  } catch {}
1415
1431
  }
@@ -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,91 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const os = require('os');
6
+ const { createHash, randomUUID } = require('crypto');
7
+ const { isTransientNetworkError, isLogPoint } = require('./failure-streak');
8
+
9
+ /** Final answers are saved before delivery; neither tokens nor session IDs are saved. */
10
+ class ResponseOutbox {
11
+ constructor({ endpoint, workspaceId, agentName, directory, prepare, send, log, onRevoked }) {
12
+ const scope = createHash('sha256').update(JSON.stringify([endpoint, workspaceId, agentName])).digest('hex');
13
+ this.directory = directory || path.join(os.homedir(), '.openagents', 'response-outbox', scope);
14
+ this.prepare = prepare;
15
+ this.send = send;
16
+ this.log = log;
17
+ this.onRevoked = onRevoked;
18
+ this.flight = null;
19
+ }
20
+
21
+ save(entry) {
22
+ fs.mkdirSync(this.directory, { recursive: true, mode: 0o700 });
23
+ const file = path.join(this.directory, `${entry.id}.json`);
24
+ const temp = `${file}.${randomUUID()}.tmp`;
25
+ fs.writeFileSync(temp, JSON.stringify(entry), { mode: 0o600 });
26
+ fs.renameSync(temp, file);
27
+ }
28
+
29
+ async enqueue(reply) {
30
+ const createdAt = this.readEntries().reduce((latest, entry) => Math.max(latest, entry.createdAt + 1), Date.now());
31
+ this.save({ ...reply, id: randomUUID(), createdAt, attempts: 0 });
32
+ // A new reply arriving during a drain must not be left waiting for a heartbeat.
33
+ if (this.flight) await this.flight;
34
+ await this.flush();
35
+ }
36
+
37
+ flush() {
38
+ if (this.flight) return this.flight;
39
+ this.flight = this.drain().finally(() => { this.flight = null; });
40
+ return this.flight;
41
+ }
42
+
43
+ readEntries() {
44
+ let files;
45
+ try { files = fs.readdirSync(this.directory).filter(f => /^[\da-f-]+\.json$/.test(f)); }
46
+ catch (e) { if (e.code === 'ENOENT') return []; throw e; }
47
+ return files.map(file => {
48
+ try { return JSON.parse(fs.readFileSync(path.join(this.directory, file), 'utf8')); }
49
+ catch { this.log('Unreadable saved reply in response outbox; retained for recovery.', 'error'); return null; }
50
+ }).filter(Boolean).sort((a, b) => a.createdAt - b.createdAt);
51
+ }
52
+
53
+ async drain() {
54
+ const entries = this.readEntries();
55
+ const waitingChannels = new Set();
56
+ for (const entry of entries) {
57
+ if (waitingChannels.has(entry.channel)) continue;
58
+ if (entry.blocked || entry.nextAttemptAt > Date.now()) {
59
+ waitingChannels.add(entry.channel);
60
+ continue;
61
+ }
62
+ try {
63
+ if (!entry.prepared) {
64
+ Object.assign(entry, await this.prepare(entry), { prepared: true });
65
+ this.save(entry);
66
+ }
67
+ await this.send(entry);
68
+ fs.unlinkSync(path.join(this.directory, `${entry.id}.json`));
69
+ if (entry.attempts) this.log(`Delivered saved reply ${entry.id} after recovery.`);
70
+ } catch (e) {
71
+ waitingChannels.add(entry.channel);
72
+ entry.attempts++;
73
+ // A replaced session stops this adapter. Its successor can deliver the
74
+ // saved reply with a fresh session and the SAME idempotency key.
75
+ if (e.name === 'SessionRevokedError') {
76
+ this.onRevoked();
77
+ return;
78
+ }
79
+ const retry = isTransientNetworkError(e) && (!entry.prepared || entry.safeRetry);
80
+ entry.blocked = !retry;
81
+ entry.nextAttemptAt = Date.now() + Math.min(300000, 1000 * 2 ** Math.min(entry.attempts, 8));
82
+ this.save(entry);
83
+ if (isLogPoint(entry.attempts)) {
84
+ this.log(`Reply ${entry.id} saved locally: ${retry ? 'delivery will retry' : 'delivery needs attention; automatic retries paused'}${e.status ? ` (HTTP ${e.status})` : ''}.`, retry ? 'warn' : 'error');
85
+ }
86
+ }
87
+ }
88
+ }
89
+ }
90
+
91
+ module.exports = { ResponseOutbox };
@@ -746,6 +746,8 @@ function buildClaudeSkillsToolBlock(skillName = 'openagents-workspace') {
746
746
  'action. It is your ONLY interface to the workspace — every operation goes\n' +
747
747
  'through the exact Bash + curl commands documented there. Do not guess\n' +
748
748
  'endpoints or improvise; open and follow the skill instructions.\n' +
749
+ `If skill lookup fails, read .claude/skills/${skillName}/SKILL.md directly\n` +
750
+ 'from your working directory. Do not search the filesystem for it.\n' +
749
751
  `The ${skillName} skill (Bash + curl) covers all workspace operations:\n` +
750
752
  'reading message history, discovering agents (and who is in this channel),\n' +
751
753
  'sharing files, browsing the shared browser, managing to-do lists, setting\n' +