@openagents-org/agent-launcher 0.2.228 → 0.2.229

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.
@@ -26,6 +26,8 @@ const { formatAttachmentsForPrompt, redactSecrets, stripAnsi } = require('./util
26
26
  const { buildOpenCodeSkillMd, buildOpenCodeSystemPrompt, workspaceSkillName } = require('./workspace-prompt');
27
27
  const { whichBinary, whereBinary, getEnhancedEnv } = require('../paths');
28
28
  const { isPostinstallStub, isPostinstallStubOutput } = require('../postinstall-stub');
29
+ const EventEmitter = require('events');
30
+ const { OpenCodeServer } = require('./opencode-server');
29
31
 
30
32
  // The launcher's own CLI, whose `mcp-server` command serves the workspace tools.
31
33
  const WORKSPACE_MCP_BIN = path.resolve(__dirname, '..', '..', 'bin', 'agent-connector.js');
@@ -38,6 +40,9 @@ const IS_WINDOWS = process.platform === 'win32';
38
40
  // timeout killed those healthy runs midway through their answer.
39
41
  const TIMEOUT_MS = 300000; // 5 minutes
40
42
 
43
+ // _runViaServer's answer for "the server can't take this message": run it the ordinary way.
44
+ const NO_SERVER = Symbol('no-server');
45
+
41
46
  // Pinned OpenCode CLI version. Do NOT use @latest anywhere (registry.json /
42
47
  // opencode.yaml install commands, install hints below). This adapter parses
43
48
  // opencode's `--format json` stream, so an unbounded version floats the event
@@ -84,6 +89,22 @@ const CUSTOM_PROVIDER_ID = 'openagents-gateway';
84
89
  const ownDbPath = () => path.join(os.homedir(), '.openagents', 'opencode', 'opencode.db');
85
90
  const SHARED_DB_MIGRATED_RE = /database is not empty and has no session table/i;
86
91
 
92
+ // Lets OpenCode's subagents read and write outside the working directory, as
93
+ // the main session already may. `opencode run --dangerously-skip-permissions`
94
+ // answers only the main session's permission prompts (opencode-ai 1.17.11,
95
+ // packages/opencode/src/cli/cmd/run.ts: `permission.sessionID !== sessionID`
96
+ // is skipped). A subagent started by the task tool runs in a child session,
97
+ // and `external_directory` defaults to "ask", so its prompt went unanswered
98
+ // until the idle watchdog stopped the turn: "OpenCode timed out before
99
+ // producing a reply" (daily errors dashboard, 2026-11-17, ~10 runs from 4
100
+ // users). Fixed upstream in 1.19.0, which also answers child sessions; the
101
+ // pinned 1.17.11 is not. OPENCODE_PERMISSION is merged over the user's config
102
+ // last (packages/opencode/src/config/config.ts), so it is left out when the
103
+ // user set it, wrote an external_directory rule of their own, or set every
104
+ // permission at once.
105
+ const SUBAGENT_PERMISSION = JSON.stringify({ external_directory: 'allow' });
106
+ const CONFIG_FILES = ['opencode.json', 'opencode.jsonc', path.join('.opencode', 'opencode.json'), path.join('.opencode', 'opencode.jsonc')];
107
+
87
108
  // Short, de-identified, actionable user messages per failure category. These
88
109
  // must NEVER default to "run auth login": only credential_missing / auth_failed
89
110
  // mention authentication. Diagnostics (exit code, signal, redacted stdout/
@@ -146,6 +167,7 @@ class OpenCodeAdapter extends BaseAdapter {
146
167
  // Process tracking for stop control
147
168
  this._channelProcesses = {}; // channel → child process
148
169
  this._stoppingChannels = new Set();
170
+ this._server = null; // warm `opencode serve` (opencode-server.js), when enabled
149
171
 
150
172
  this._opencodeBinary = this._findOpencodeBinary();
151
173
  if (this._opencodeBinary) {
@@ -269,9 +291,40 @@ class OpenCodeAdapter extends BaseAdapter {
269
291
  touch();
270
292
  return { touch, cancel, timeoutMs };
271
293
  }
272
- _spawnEnv(channel) {
294
+
295
+ /**
296
+ * Whether the user's own OpenCode config has an external_directory rule,
297
+ * or sets every permission at once (`"permission": "deny"` or
298
+ * `{"*": "deny"}`): the global config and ~/.opencode, OPENCODE_CONFIG and
299
+ * OPENCODE_CONFIG_DIR, the inline config, and the project files from the
300
+ * run's folder up. A text match is enough, and errs toward leaving
301
+ * their rules alone.
302
+ */
303
+ static _userRulesExternalDirs(env, runCwd) {
304
+ const mentions = (text) => /external_directory|"permission"\s*:\s*("|\{\s*"\*")/.test(String(text || ''));
305
+ if (mentions(env.OPENCODE_CONFIG_CONTENT)) return true;
306
+ const home = env.HOME || env.USERPROFILE || os.homedir();
307
+ const globalDir = path.join(env.XDG_CONFIG_HOME || path.join(home, '.config'), 'opencode');
308
+ const files = ['config.json', 'opencode.json', 'opencode.jsonc'].map((f) => path.join(globalDir, f));
309
+ files.push(...['opencode.json', 'opencode.jsonc'].map((f) => path.join(home, '.opencode', f)));
310
+ if (env.OPENCODE_CONFIG) files.push(env.OPENCODE_CONFIG);
311
+ if (env.OPENCODE_CONFIG_DIR) files.push(...['opencode.json', 'opencode.jsonc'].map((f) => path.join(env.OPENCODE_CONFIG_DIR, f)));
312
+ for (let dir = runCwd ? path.resolve(runCwd) : ''; dir; ) {
313
+ files.push(...CONFIG_FILES.map((f) => path.join(dir, f)));
314
+ const up = path.dirname(dir);
315
+ dir = up === dir ? '' : up;
316
+ }
317
+ return files.some((file) => {
318
+ try { return mentions(fs.readFileSync(file, 'utf-8')); } catch { return false; }
319
+ });
320
+ }
321
+
322
+ _spawnEnv(channel, { contextFile = null } = {}) {
273
323
  const env = { ...(this.agentEnv || process.env) };
274
324
  if (!env.OPENCODE_DB && fs.existsSync(ownDbPath())) env.OPENCODE_DB = ownDbPath();
325
+ if (!env.OPENCODE_PERMISSION && !OpenCodeAdapter._userRulesExternalDirs(env, this._resolveCwd())) {
326
+ env.OPENCODE_PERMISSION = SUBAGENT_PERMISSION;
327
+ }
275
328
  if (!this._wiresWorkspaceMcp()) return env;
276
329
  // Give OpenCode the workspace tools (publish, todos, browser, ...) through
277
330
  // our MCP server, as the Claude adapter does. Merged into any inline config
@@ -282,11 +335,14 @@ class OpenCodeAdapter extends BaseAdapter {
282
335
  const args = [WORKSPACE_MCP_BIN, 'mcp-server',
283
336
  '--workspace-id', this.workspaceId, '--channel-name', channel || this.channelName || 'general',
284
337
  '--agent-name', this.agentName, '--endpoint', this.endpoint];
338
+ // On the warm server one tools server serves every channel: it reads the
339
+ // turn's channel and requester from this file (written per turn).
340
+ if (contextFile) args.push('--context-file', contextFile);
285
341
  const disabled = this.disabledModules || new Set();
286
342
  if (disabled.has('files')) args.push('--disable-files');
287
343
  if (disabled.has('browser')) args.push('--disable-browser');
288
344
  if (disabled.has('knowledge')) args.push('--disable-knowledge');
289
- const requester = channel && this.requesterEmailFor ? this.requesterEmailFor(channel) : null;
345
+ const requester = !contextFile && channel && this.requesterEmailFor ? this.requesterEmailFor(channel) : null;
290
346
  cfg.mcp = { ...(cfg.mcp || {}), openagents: { type: 'local', enabled: true,
291
347
  command: [process.execPath, ...args],
292
348
  environment: { OA_WORKSPACE_TOKEN: this.token, ...(requester ? { OPENAGENTS_REQUESTER_EMAIL: requester } : {}) } } };
@@ -826,10 +882,34 @@ class OpenCodeAdapter extends BaseAdapter {
826
882
  this._stopAllProcesses(
827
883
  'Task interrupted — daemon restarting. Send another message to continue.'
828
884
  ).catch(() => {});
885
+ if (this._server) this._server.stop();
829
886
  super.stop();
830
887
  }
831
888
 
889
+ /**
890
+ * Whether messages may go to a warm `opencode serve` instead of a new
891
+ * `opencode run`. Opt-in (OPENAGENTS_OPENCODE_SERVER=1), plain OpenCode
892
+ * only, and not on Windows or across the WSL boundary for now.
893
+ */
894
+ _serverEnabled() {
895
+ if ((this.agentEnv || process.env).OPENAGENTS_OPENCODE_SERVER !== '1') return false;
896
+ const bin = String(this._opencodeBinary || '');
897
+ return !IS_WINDOWS && !bin.startsWith('wsl:') && this._cliLabel() === 'OpenCode';
898
+ }
899
+
900
+ /** Where the warm server's tools read the current turn's channel and requester. */
901
+ _turnContextFile() {
902
+ return path.join(this.agentHome || os.tmpdir(), 'opencode-turn-context.json');
903
+ }
904
+
905
+ _getServer() {
906
+ if (!this._server) this._server = new OpenCodeServer({ binary: this._opencodeBinary, log: (m, l) => this._log(m, l) });
907
+ return this._server;
908
+ }
909
+
832
910
  async _stopProcess(proc) {
911
+ // A turn on the warm server keeps going until the server is told to stop it.
912
+ if (proc && proc.__abortAttached) { try { await proc.__abortAttached(); } catch {} }
833
913
  if (!proc || proc.exitCode !== null) return;
834
914
  try {
835
915
  if (IS_WINDOWS) {
@@ -985,7 +1065,7 @@ class OpenCodeAdapter extends BaseAdapter {
985
1065
  }
986
1066
  }
987
1067
 
988
- _runOpencode(content, msgChannel) {
1068
+ _runOpencode(content, msgChannel, { noServer = false } = {}) {
989
1069
  // Preflight BEFORE spawning: bail out with a structured, actionable error
990
1070
  // instead of launching a child that will hang for 5 minutes or exit 1 with
991
1071
  // an opaque message. Stubbing _runOpencode in tests bypasses this, exactly
@@ -1023,6 +1103,14 @@ class OpenCodeAdapter extends BaseAdapter {
1023
1103
  // Stopped while this turn was being prepared: start nothing (no tokens).
1024
1104
  if (this._stoppedBeforeStart(msgChannel)) return Promise.resolve('');
1025
1105
 
1106
+ if (!noServer && this._serverEnabled()) {
1107
+ // The server's setup must not depend on the channel, so it can serve them all.
1108
+ const contextFile = this._turnContextFile();
1109
+ const serverEnv = this._spawnEnv(this.channelName || 'general', { contextFile });
1110
+ return this._runViaServer({ msgChannel, runCwd, model, sessionId, fullPrompt, spawnEnv: serverEnv, contextFile })
1111
+ .then((r) => (r === NO_SERVER ? this._runOpencode(content, msgChannel, { noServer: true }) : r));
1112
+ }
1113
+
1026
1114
  return new Promise((resolve, reject) => {
1027
1115
  const proc = spawn(spawnBinary, spawnArgs, {
1028
1116
  stdio: ['pipe', 'pipe', 'pipe'],
@@ -1102,44 +1190,221 @@ class OpenCodeAdapter extends BaseAdapter {
1102
1190
  return finish(resolve, '');
1103
1191
  }
1104
1192
 
1105
- stdout = stdout.trim();
1106
- stderr = stderr.trim();
1107
-
1108
- // A structured error event may ride on stdout regardless of exit code
1109
- // (opencode emits {"type":"error", ...} as a JSONL event). Look there
1110
- // first so the real auth/provider/model failure is never discarded just
1111
- // because stderr happened to be empty.
1112
- const stdoutErr = OpenCodeAdapter._extractErrorFromStdout(stdout);
1113
-
1114
- if (timedOut) {
1115
- this._log(`opencode timed out after ${watchdog.timeoutMs / 1000}s idle (output: ${!!stdout})`);
1116
- const cls = this.constructor._classifyFailure({ code, signal, stdout, stderr, stdoutErr });
1117
- const category = (cls.category === 'unknown_error' || cls.category === 'process_crashed')
1118
- ? 'timeout' : cls.category;
1119
- return finish(reject, this._failure(category, cls.diagnostic || `idle=${watchdog.timeoutMs}ms`, cls.detail));
1120
- }
1193
+ const outcome = this._settleOutcome({ code, signal, stdout, stderr, timedOut, timeoutMs: watchdog.timeoutMs, responseState, msgChannel });
1194
+ return outcome.error ? finish(reject, outcome.error) : finish(resolve, outcome.text);
1195
+ });
1196
+ });
1197
+ }
1121
1198
 
1122
- if (signal) {
1123
- this._log(`opencode killed by signal ${signal} (output: ${!!stdout})`);
1124
- const cls = this.constructor._classifyFailure({ code, signal, stdout, stderr, stdoutErr });
1125
- return finish(reject, this._failure(cls.category, cls.diagnostic || `signal=${signal}`, cls.detail));
1126
- }
1199
+ /**
1200
+ * What a finished run means, from its exit and its JSON output: `{ text }`
1201
+ * for a reply or `{ error }` (a classified failure). Shared by `opencode run`
1202
+ * and runs on the warm server, so both fail the same way.
1203
+ */
1204
+ _settleOutcome({ code, signal, stdout, stderr, timedOut, timeoutMs, responseState, msgChannel }) {
1205
+ stdout = String(stdout || '').trim();
1206
+ stderr = String(stderr || '').trim();
1207
+
1208
+ // A structured error event may ride on stdout regardless of exit code
1209
+ // (opencode emits {"type":"error", ...} as a JSONL event). Look there
1210
+ // first so the real auth/provider/model failure is never discarded just
1211
+ // because stderr happened to be empty.
1212
+ const stdoutErr = OpenCodeAdapter._extractErrorFromStdout(stdout);
1213
+
1214
+ if (timedOut) {
1215
+ this._log(`opencode timed out after ${timeoutMs / 1000}s idle (output: ${!!stdout})`);
1216
+ const cls = this.constructor._classifyFailure({ code, signal, stdout, stderr, stdoutErr });
1217
+ const category = (cls.category === 'unknown_error' || cls.category === 'process_crashed')
1218
+ ? 'timeout' : cls.category;
1219
+ return { error: this._failure(category, cls.diagnostic || `idle=${timeoutMs}ms`, cls.detail) };
1220
+ }
1221
+
1222
+ if (signal) {
1223
+ this._log(`opencode killed by signal ${signal} (output: ${!!stdout})`);
1224
+ const cls = this.constructor._classifyFailure({ code, signal, stdout, stderr, stdoutErr });
1225
+ return { error: this._failure(cls.category, cls.diagnostic || `signal=${signal}`, cls.detail) };
1226
+ }
1227
+
1228
+ if (code !== 0) {
1229
+ const cls = this.constructor._classifyFailure({ code, signal, stdout, stderr, stdoutErr });
1230
+ this._log(`opencode exited code ${code} → [${cls.category}]: ${this._redact(cls.diagnostic).slice(0, 300)}`);
1231
+ return { error: this._failure(cls.category, cls.diagnostic, cls.detail) };
1232
+ }
1233
+
1234
+ // Exit 0.
1235
+ if (stdout) this._persistSessionId(msgChannel, stdout);
1236
+ const outcome = this.constructor._outcomeForCleanExit({ stdout, stderr, stdoutErr, responseState });
1237
+ if (outcome.text) return { text: outcome.text };
1238
+ const f = outcome.failure;
1239
+ this._log(`opencode exit 0 → [${f.category}]: ${this._redact(f.diagnostic).slice(0, 300)}`);
1240
+ return { error: this._failure(f.category, f.diagnostic, f.detail) };
1241
+ }
1127
1242
 
1128
- if (code !== 0) {
1129
- const cls = this.constructor._classifyFailure({ code, signal, stdout, stderr, stdoutErr });
1130
- this._log(`opencode exited code ${code} → [${cls.category}]: ${this._redact(cls.diagnostic).slice(0, 300)}`);
1131
- return finish(reject, this._failure(cls.category, cls.diagnostic, cls.detail));
1243
+ /**
1244
+ * One turn on the warm server (opencode-server.js): the message goes to the
1245
+ * session over HTTP and the server's live events become the same JSON
1246
+ * events `opencode run --format json` prints, so thinking, tool steps and
1247
+ * the reply show exactly as they do today. The finished message the request
1248
+ * returns is the source of truth: parts the live stream missed are replayed
1249
+ * from it. Permission requests are answered `once`, like
1250
+ * --dangerously-skip-permissions (rules that deny still deny). Returns
1251
+ * NO_SERVER when the message should run the ordinary way instead.
1252
+ */
1253
+ async _runViaServer({ msgChannel, runCwd, model, sessionId, fullPrompt, spawnEnv, contextFile = null }) {
1254
+ const slash = String(model || '').indexOf('/');
1255
+ if (slash <= 0) return NO_SERVER;
1256
+ const server = this._getServer();
1257
+ if (!(await server.acquire({ env: spawnEnv, cwd: runCwd }))) return NO_SERVER;
1258
+ if (contextFile) {
1259
+ // The server runs one turn at a time, so this is the only turn reading it.
1260
+ try {
1261
+ fs.mkdirSync(path.dirname(contextFile), { recursive: true });
1262
+ const requesterEmail = this.requesterEmailFor ? this.requesterEmailFor(msgChannel) : null;
1263
+ fs.writeFileSync(contextFile, JSON.stringify({ channel: msgChannel, requesterEmail }), { mode: 0o600 });
1264
+ } catch (e) {
1265
+ this._log(`Could not write the turn context (${e.message}); running this message without the server`, 'error');
1266
+ server.release();
1267
+ return NO_SERVER;
1268
+ }
1269
+ }
1270
+
1271
+ let sid = sessionId || null;
1272
+ // Stand-in for a child process, so stop and interrupt reach this turn.
1273
+ const proc = new EventEmitter();
1274
+ proc.pid = null;
1275
+ proc.exitCode = null;
1276
+ proc.kill = () => { if (proc.exitCode === null) { proc.exitCode = 0; proc.emit('exit', 0); } };
1277
+ proc.__abortAttached = () => server.abort(sid);
1278
+ this._channelProcesses[msgChannel] = proc;
1279
+
1280
+ const responseState = { finalText: '', allText: '', seenText: false };
1281
+ const lines = [];
1282
+ const emitted = new Set();
1283
+ const roles = {};
1284
+ const early = []; // parts seen before their message's role
1285
+ const children = new Set(); // subagent sessions started from this turn's session
1286
+ let pending = Promise.resolve();
1287
+ let timedOut = false;
1288
+ const watchdog = this._createIdleWatchdog(() => {
1289
+ timedOut = true;
1290
+ this._log(`opencode idle for ${this._runTimeoutMs() / 1000}s; stopping the turn on the server`);
1291
+ server.abort(sid).catch(() => {});
1292
+ });
1293
+ const emit = (part, final = false) => {
1294
+ const event = OpenCodeAdapter._eventForPart(part, final);
1295
+ if (!event) return;
1296
+ const key = `${part.id}:${event.type}`;
1297
+ if (emitted.has(key)) return;
1298
+ emitted.add(key);
1299
+ lines.push(JSON.stringify(event));
1300
+ pending = pending
1301
+ .then(() => this._handleStreamEvent(event, msgChannel, responseState))
1302
+ .catch((e) => this._log(`opencode stream event handling failed: ${e.message}`));
1303
+ };
1304
+ const unsubscribe = server.subscribe((ev) => {
1305
+ const props = (ev && ev.properties) || {};
1306
+ if (!sid) return;
1307
+ if (ev.type === 'message.updated' && props.info && props.info.sessionID === sid) {
1308
+ roles[props.info.id] = props.info.role;
1309
+ for (let k = early.length - 1; k >= 0; k--) {
1310
+ if (roles[early[k].messageID]) { const [part] = early.splice(k, 1); if (roles[part.messageID] === 'assistant') emit(part); }
1132
1311
  }
1312
+ } else if (ev.type === 'session.created' && props.info && props.info.parentID
1313
+ && (props.info.parentID === sid || children.has(props.info.parentID))) {
1314
+ children.add(props.info.id);
1315
+ } else if (ev.type === 'permission.asked' && (props.sessionID === sid || children.has(props.sessionID))) {
1316
+ // A subagent's prompt arrives from its own child session; left
1317
+ // unanswered it held the turn until the idle watchdog stopped it.
1318
+ watchdog.touch();
1319
+ server.replyPermission(props.sessionID, props.id, 'once').catch(() => {});
1320
+ } else if (ev.type === 'message.part.updated' && props.part && props.part.sessionID === sid) {
1321
+ watchdog.touch();
1322
+ const part = props.part;
1323
+ if (!roles[part.messageID]) early.push(part);
1324
+ else if (roles[part.messageID] === 'assistant') emit(part);
1325
+ } else if (ev.type === 'message.part.delta' && props.sessionID === sid) {
1326
+ watchdog.touch();
1327
+ }
1328
+ });
1329
+ const stopping = () => this._stoppingChannels.has(msgChannel);
1330
+ const done = () => {
1331
+ watchdog.cancel();
1332
+ unsubscribe();
1333
+ server.release();
1334
+ if (this._channelProcesses[msgChannel] === proc) delete this._channelProcesses[msgChannel];
1335
+ proc.kill();
1336
+ };
1133
1337
 
1134
- // Exit 0.
1135
- if (stdout) this._persistSessionId(msgChannel, stdout);
1136
- const outcome = this.constructor._outcomeForCleanExit({ stdout, stderr, stdoutErr, responseState });
1137
- if (outcome.text) return finish(resolve, outcome.text);
1138
- const f = outcome.failure;
1139
- this._log(`opencode exit 0 → [${f.category}]: ${this._redact(f.diagnostic).slice(0, 300)}`);
1140
- return finish(reject, this._failure(f.category, f.diagnostic, f.detail));
1338
+ try {
1339
+ try {
1340
+ if (!sid) {
1341
+ sid = (await server.request('POST', '/session', {})).id;
1342
+ this._channelSessions[msgChannel] = sid;
1343
+ this._saveSessions();
1344
+ }
1345
+ } catch (e) {
1346
+ this._log(`OpenCode server could not open a session (${e.message}); running this message without it`, 'error');
1347
+ done();
1348
+ return NO_SERVER;
1349
+ }
1350
+ this._log(`CLI (warm server): message to session ${sid}`);
1351
+ let res;
1352
+ try {
1353
+ res = await server.request('POST', `/session/${encodeURIComponent(sid)}/message`, {
1354
+ model: { providerID: model.slice(0, slash), modelID: model.slice(slash + 1) },
1355
+ parts: [{ type: 'text', text: fullPrompt }],
1356
+ });
1357
+ } catch (e) {
1358
+ if (!emitted.size && !stopping() && !timedOut) {
1359
+ // Nothing happened yet: an unknown session, or a server in trouble.
1360
+ this._log(`OpenCode server turn failed before any output (${e.message}); running this message without it`, 'error');
1361
+ if (e.status !== 404) server.stop();
1362
+ done();
1363
+ return NO_SERVER;
1364
+ }
1365
+ res = null;
1366
+ }
1367
+ for (const part of (res && res.parts) || []) emit(part, true);
1368
+ const info = (res && res.info) || {};
1369
+ if (info.error) lines.push(JSON.stringify({ type: 'error', sessionID: sid, error: info.error }));
1370
+ try { await pending; } catch {}
1371
+ if (stopping()) {
1372
+ this._stoppingChannels.delete(msgChannel);
1373
+ done();
1374
+ return '';
1375
+ }
1376
+ done();
1377
+ const outcome = this._settleOutcome({
1378
+ code: info.error || !res ? 1 : 0, signal: null, stdout: lines.join('\n'), stderr: '',
1379
+ timedOut, timeoutMs: watchdog.timeoutMs, responseState, msgChannel,
1141
1380
  });
1142
- });
1381
+ if (outcome.error) throw outcome.error;
1382
+ return outcome.text;
1383
+ } catch (e) {
1384
+ if (this._channelProcesses[msgChannel] === proc) done();
1385
+ throw e;
1386
+ }
1387
+ }
1388
+
1389
+ /**
1390
+ * The `opencode run --format json` event for a finished message part, or
1391
+ * null while it's still being written (live parts) / for other part types.
1392
+ */
1393
+ static _eventForPart(part, final = false) {
1394
+ if (!part || typeof part !== 'object') return null;
1395
+ const ended = final || Boolean(part.time && part.time.end);
1396
+ const base = { sessionID: part.sessionID, part };
1397
+ switch (part.type) {
1398
+ case 'step-start': return { type: 'step_start', ...base };
1399
+ case 'step-finish': return { type: 'step_finish', ...base };
1400
+ case 'reasoning': return ended ? { type: 'reasoning', ...base } : null;
1401
+ case 'text': return ended && !part.synthetic && !part.ignored ? { type: 'text', ...base } : null;
1402
+ case 'tool': {
1403
+ const status = part.state && part.state.status;
1404
+ return (status === 'completed' || status === 'error') ? { type: 'tool_use', ...base } : null;
1405
+ }
1406
+ default: return null;
1407
+ }
1143
1408
  }
1144
1409
 
1145
1410
  /**
@@ -123,7 +123,35 @@ function workspaceSkillName(agentName) {
123
123
  * - `'skills'` → points at the agent's workspace skill (Bash + curl),
124
124
  * since no MCP server is spawned and that tool would not exist.
125
125
  */
126
+ // Skill files are written once per agent and read by every one of its
127
+ // threads, including threads running at the same time. A channel baked into
128
+ // one would send another thread's to-dos, files and messages to the wrong
129
+ // place, so skill files carry this placeholder and say where the real channel
130
+ // is (the per-thread system prompt or header).
131
+ const SHARED_SKILL_CHANNEL = 'CURRENT_CHANNEL';
132
+
133
+ function buildSharedChannelNote() {
134
+ return (
135
+ `This skill file is shared by all of your threads, so its commands say \`${SHARED_SKILL_CHANNEL}\` ` +
136
+ 'instead of a channel. Replace it with the channel of the conversation you are answering — ' +
137
+ 'the `Channel:` in your instructions (or the channel in the `[OpenAgents workspace]` header). ' +
138
+ 'Never reuse a channel name from another conversation.\n\n'
139
+ );
140
+ }
141
+
126
142
  function buildWorkspaceIdentity(agentName, workspaceId, channelName, mode = 'execute', toolMode = 'mcp', model = null) {
143
+ // channelName null: a shared skill file, which must not name one channel.
144
+ if (channelName == null) {
145
+ return (
146
+ `You are agent '${agentName}' connected to an OpenAgents workspace.\n` +
147
+ 'Your text responses are automatically posted to the workspace chat ' +
148
+ '— just write your answer naturally.\n\n' +
149
+ '## Workspace Context\n' +
150
+ `- Workspace ID: ${workspaceId}\n` +
151
+ '- Channel: the one named in your instructions for this conversation\n\n' +
152
+ buildSharedChannelNote()
153
+ );
154
+ }
127
155
  const priorContext = toolMode === 'skills'
128
156
  ? (
129
157
  `When you need prior context, use the ${workspaceSkillName(agentName)} skill to ` +
@@ -265,7 +293,7 @@ function buildModePrompt(mode) {
265
293
  *
266
294
  * In plan mode, only read-only operations are documented.
267
295
  */
268
- function buildApiSkillsPrompt({ endpoint, workspaceId, token, agentName, channelName, disabledModules, mode = 'execute', isWindows = process.platform === 'win32', execTool = 'exec' }) {
296
+ function buildApiSkillsPrompt({ endpoint, workspaceId, token, agentName, channelName, disabledModules, mode = 'execute', isWindows = process.platform === 'win32', execTool = 'exec', publicShare = true }) {
269
297
  const disabled = disabledModules || new Set();
270
298
  const baseUrl = endpoint.replace(/\/+$/, '');
271
299
  const isPlan = mode === 'plan';
@@ -651,8 +679,19 @@ function buildApiSkillsPrompt({ endpoint, workspaceId, token, agentName, channel
651
679
  'or `pending`. When pending, STOP and end your turn — do not perform the action. The decision ' +
652
680
  'arrives as a new message in this thread @mentioning you (✅ Approved / ❌ Rejected). ' +
653
681
  'You can also poll:\n' +
654
- `\`${curl} -s -H "${h}" "${baseUrl}/v1/approvals/APPROVAL_ID?network=${workspaceId}"\`\n`
655
-
682
+ `\`${curl} -s -H "${h}" "${baseUrl}/v1/approvals/APPROVAL_ID?network=${workspaceId}"\`\n` +
683
+ (publicShare
684
+ ? '\n### Public share link (needs human approval)\n\n' +
685
+ 'Only when the user asks to share a file or knowledge entry publicly (with people outside ' +
686
+ 'the workspace). You cannot create the link yourself: this files a request, and a person who ' +
687
+ 'can manage the artifact approves it in the thread. The link shows a snapshot of the artifact ' +
688
+ 'as it is now. `expires_at` (ISO 8601) is optional; omit it for no expiry. `kind` is `file` or `knowledge`.\n\n' +
689
+ `\`${curl} -s -X POST -H "${h}" -H "Content-Type: application/json" ` +
690
+ `${baseUrl}/v1/public-shares/requests -d '{"network":"${workspaceId}","channel":"${channelName}",` +
691
+ `"kind":"file","id":"FILE_ID","reason":"The user asked to share this report","source":"openagents:${agentName}"}'\`\n\n` +
692
+ 'The response is a pending approval. STOP and tell the user it awaits approval; do not claim ' +
693
+ 'a link exists. When approved, the link arrives as a message in this thread @mentioning you.\n'
694
+ : '')
656
695
  );
657
696
  }
658
697
 
@@ -745,6 +784,7 @@ function buildClaudeMcpToolBlock() {
745
784
  'Use workspace_update_routine to change an existing routine — its schedule, task or paused state — instead of cancelling and recreating it.\n' +
746
785
  'Use workspace_send_notification to send a notification to the workspace inbox when you complete a task or have important results.\n' +
747
786
  'Use workspace_request_approval BEFORE deploying, spending money, emailing customers, deleting data, or any irreversible action; it blocks until a person decides. If it returns PENDING, stop and end your turn — the decision arrives as a message in the thread.\n' +
787
+ 'Use workspace_request_public_link only when the user asks to share a file or knowledge entry publicly; a person must approve it, and the link arrives in the thread.\n' +
748
788
  'Use workspace_write_knowledge to create or update shared knowledge base entries that persist across conversations.\n' +
749
789
  'Use workspace_read_knowledge to read knowledge entries by ID or slug (from @knowledge:slug mentions).\n'
750
790
  );
@@ -938,6 +978,10 @@ function buildOpenclawSystemPrompt({ agentName, workspaceId, channelName, endpoi
938
978
  parts.push(...buildPinnedSections({ toolMode: 'skills', mode, glossary }));
939
979
  parts.push(buildApiSkillsPrompt({
940
980
  endpoint, workspaceId, token, agentName, channelName, disabledModules, mode,
981
+ // Copilot passes this prompt on its command line, and on Windows it sits
982
+ // just under the length that fits (promptFitsArgv); the SKILL.md files,
983
+ // read from disk, carry the public-link section instead.
984
+ publicShare: false,
941
985
  }));
942
986
  parts.push(buildGuardrails());
943
987
  return parts.join('\n');
@@ -946,12 +990,12 @@ function buildOpenclawSystemPrompt({ agentName, workspaceId, channelName, endpoi
946
990
  /**
947
991
  * Build a SKILL.md file for OpenClaw's skill auto-discovery.
948
992
  */
949
- function buildOpenclawSkillMd({ endpoint, workspaceId, token, agentName, channelName, disabledModules, browserEnabled = false }) {
993
+ function buildOpenclawSkillMd({ endpoint, workspaceId, token, agentName, disabledModules, browserEnabled = false }) {
950
994
  const body = buildApiSkillsPrompt({
951
- endpoint, workspaceId, token, agentName, channelName, disabledModules, mode: 'execute',
995
+ endpoint, workspaceId, token, agentName, channelName: SHARED_SKILL_CHANNEL, disabledModules, mode: 'execute',
952
996
  });
953
997
 
954
- const identity = buildWorkspaceIdentity(agentName, workspaceId, channelName, 'execute', 'skills');
998
+ const identity = buildWorkspaceIdentity(agentName, workspaceId, null, 'execute', 'skills');
955
999
  const directive = buildBrowserDirective(browserEnabled);
956
1000
  const collab = buildCollaborationPrompt('skills', workspaceSkillName(agentName));
957
1001
 
@@ -1152,10 +1196,10 @@ function buildDeepSeekTaskFile({
1152
1196
  /**
1153
1197
  * Build workspace skill markdown for OpenCode (written to .opencode/skills/).
1154
1198
  */
1155
- function buildOpenCodeSkillMd({ endpoint, workspaceId, token, agentName, channelName, disabledModules }) {
1199
+ function buildOpenCodeSkillMd({ endpoint, workspaceId, token, agentName, disabledModules }) {
1156
1200
  const api = buildApiSkillsPrompt({
1157
1201
  endpoint, workspaceId, token, agentName,
1158
- channelName: channelName || 'general',
1202
+ channelName: SHARED_SKILL_CHANNEL,
1159
1203
  disabledModules,
1160
1204
  mode: 'execute',
1161
1205
  execTool: 'bash',
@@ -1169,7 +1213,8 @@ function buildOpenCodeSkillMd({ endpoint, workspaceId, token, agentName, channel
1169
1213
 
1170
1214
  const identity =
1171
1215
  `You are agent '${agentName}' connected to OpenAgents workspace ${workspaceId}.\n` +
1172
- 'Use these APIs via bash + curl to interact with the workspace.\n\n';
1216
+ 'Use these APIs via bash + curl to interact with the workspace.\n\n' +
1217
+ buildSharedChannelNote();
1173
1218
 
1174
1219
  return frontmatter + identity + api + '\n' + buildGuardrails();
1175
1220
  }
@@ -1185,10 +1230,10 @@ function buildOpenCodeSkillMd({ endpoint, workspaceId, token, agentName, channel
1185
1230
  * `exec` other adapters advertise — because an agent told to call a tool it
1186
1231
  * does not have simply does nothing.
1187
1232
  */
1188
- function buildCommandCodeSkillMd({ endpoint, workspaceId, token, agentName, channelName, disabledModules }) {
1233
+ function buildCommandCodeSkillMd({ endpoint, workspaceId, token, agentName, disabledModules }) {
1189
1234
  const api = buildApiSkillsPrompt({
1190
1235
  endpoint, workspaceId, token, agentName,
1191
- channelName: channelName || 'general',
1236
+ channelName: SHARED_SKILL_CHANNEL,
1192
1237
  disabledModules,
1193
1238
  mode: 'execute',
1194
1239
  execTool: 'shell_command',
@@ -1202,7 +1247,8 @@ function buildCommandCodeSkillMd({ endpoint, workspaceId, token, agentName, chan
1202
1247
 
1203
1248
  const identity =
1204
1249
  `You are agent '${agentName}' connected to OpenAgents workspace ${workspaceId}.\n` +
1205
- 'Use these APIs via `shell_command` + curl to interact with the workspace.\n\n';
1250
+ 'Use these APIs via `shell_command` + curl to interact with the workspace.\n\n' +
1251
+ buildSharedChannelNote();
1206
1252
 
1207
1253
  return frontmatter + identity + api + '\n' + buildGuardrails();
1208
1254
  }
@@ -1214,15 +1260,15 @@ function buildCommandCodeSkillMd({ endpoint, workspaceId, token, agentName, chan
1214
1260
  * of spawning an MCP server. Claude Code discovers the skill via its
1215
1261
  * .claude/skills/ directory and uses Bash + curl to call workspace APIs.
1216
1262
  */
1217
- function buildClaudeSkillMd({ endpoint, workspaceId, token, agentName, channelName, disabledModules, browserEnabled = false }) {
1263
+ function buildClaudeSkillMd({ endpoint, workspaceId, token, agentName, disabledModules, browserEnabled = false }) {
1218
1264
  const api = buildApiSkillsPrompt({
1219
1265
  endpoint, workspaceId, token, agentName,
1220
- channelName: channelName || 'general',
1266
+ channelName: SHARED_SKILL_CHANNEL,
1221
1267
  disabledModules,
1222
1268
  mode: 'execute',
1223
1269
  });
1224
1270
 
1225
- const identity = buildWorkspaceIdentity(agentName, workspaceId, channelName, 'execute', 'skills');
1271
+ const identity = buildWorkspaceIdentity(agentName, workspaceId, null, 'execute', 'skills');
1226
1272
  const directive = buildBrowserDirective(browserEnabled);
1227
1273
  const collab = buildCollaborationPrompt('skills', workspaceSkillName(agentName));
1228
1274
 
@@ -1245,15 +1291,15 @@ function buildClaudeSkillMd({ endpoint, workspaceId, token, agentName, channelNa
1245
1291
  * Written to .cursor/skills/<workspaceSkillName>.md before each CLI spawn.
1246
1292
  * Cursor discovers skills from the .cursor/skills/ directory automatically.
1247
1293
  */
1248
- function buildCursorSkillMd({ endpoint, workspaceId, token, agentName, channelName, disabledModules, browserEnabled = false }) {
1294
+ function buildCursorSkillMd({ endpoint, workspaceId, token, agentName, disabledModules, browserEnabled = false }) {
1249
1295
  const api = buildApiSkillsPrompt({
1250
1296
  endpoint, workspaceId, token, agentName,
1251
- channelName: channelName || 'general',
1297
+ channelName: SHARED_SKILL_CHANNEL,
1252
1298
  disabledModules,
1253
1299
  mode: 'execute',
1254
1300
  });
1255
1301
 
1256
- const identity = buildWorkspaceIdentity(agentName, workspaceId, channelName, 'execute', 'skills');
1302
+ const identity = buildWorkspaceIdentity(agentName, workspaceId, null, 'execute', 'skills');
1257
1303
  const directive = buildBrowserDirective(browserEnabled);
1258
1304
  const collab = buildCollaborationPrompt('skills', workspaceSkillName(agentName));
1259
1305
 
@@ -1300,6 +1346,7 @@ function buildHandoffPrompt(toolMode = 'mcp') {
1300
1346
  }
1301
1347
 
1302
1348
  module.exports = {
1349
+ SHARED_SKILL_CHANNEL,
1303
1350
  workspaceSkillName,
1304
1351
  buildHandoffPrompt,
1305
1352
  buildWorkspaceIdentity,
package/src/cli-models.js CHANGED
@@ -321,4 +321,40 @@ async function listCliModels(connector, type, opts = {}) {
321
321
  return fail(res.error || 'The CLI listed no models.');
322
322
  }
323
323
 
324
- module.exports = { listCliModels, supportsCliModels, cliModelsWithKey, parseCodexModels, parseClaudeModels, parseQoderModels, parsePiModels };
324
+ /**
325
+ * A ChatGPT sign-in refusing the model Codex ran on:
326
+ * "The 'gpt-6.1-sol' model is not supported when using Codex with a ChatGPT
327
+ * account." Returns that model, or null.
328
+ *
329
+ * With no model chosen, Codex runs its own default (or the user's
330
+ * ~/.codex/config.toml one), and that is often a model the account's plan
331
+ * does not include. The account's own list does not offer it.
332
+ */
333
+ function codexPlanRefusedModel(text) {
334
+ const m = String(text || '').match(/The '([^']{1,128})' model is not supported when using Codex with a ChatGPT account/i);
335
+ return m ? m[1] : null;
336
+ }
337
+
338
+ /**
339
+ * The models Codex lists for the account it is signed in to, in its picker's
340
+ * order (`codex debug models`, see parseCodexModels). [] when it will not say.
341
+ * `binary` is the Codex CLI the agent runs; `env` the env it runs it on.
342
+ */
343
+ async function codexAccountModels(binary, env, { timeoutMs, spawnImpl } = {}) {
344
+ if (!binary) return [];
345
+ const lister = LISTERS.codex;
346
+ const res = await runCli(binary, lister.args, { env, timeoutMs: timeoutMs || lister.timeoutMs, spawnImpl });
347
+ return lister.parse(res.stdout);
348
+ }
349
+
350
+ /**
351
+ * The model to run instead of one a ChatGPT plan refused: the first the
352
+ * account itself lists that is not the refused one. null when there is none.
353
+ */
354
+ async function codexPlanFallback(binary, env, refused, opts = {}) {
355
+ const models = await codexAccountModels(binary, env, opts);
356
+ const pick = models.find((m) => m.id !== refused);
357
+ return pick ? pick.id : null;
358
+ }
359
+
360
+ module.exports = { codexPlanRefusedModel, codexAccountModels, codexPlanFallback, listCliModels, supportsCliModels, cliModelsWithKey, parseCodexModels, parseClaudeModels, parseQoderModels, parsePiModels };