@openagents-org/agent-launcher 0.2.227 → 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.
@@ -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 };
package/src/cli.js CHANGED
@@ -1405,7 +1405,7 @@ async function main() {
1405
1405
  // execute mode --dangerously-skip-permissions makes the allowlist a
1406
1406
  // suggestion, not a boundary.
1407
1407
  if (flags['disable-knowledge']) disabledModules.add('knowledge');
1408
- runMcpServer({ workspaceId, channelName, agentName, endpoint, token, disabledModules });
1408
+ runMcpServer({ workspaceId, channelName, agentName, endpoint, token, disabledModules, contextFile: flags['context-file'] || null });
1409
1409
  },
1410
1410
  };
1411
1411
 
package/src/installer.js CHANGED
@@ -153,6 +153,18 @@ const INSTALL_STALL_MS = (() => {
153
153
  return Number.isFinite(n) && n >= 0 ? n : 10 * 60 * 1000;
154
154
  })();
155
155
 
156
+ /**
157
+ * The last thing a stalled installer printed, for the stall message: its
158
+ * last non-empty line, terminal colours taken off, cut to a readable length.
159
+ * The command echo the launcher prints itself (`$ …`) does not count.
160
+ */
161
+ function stallLastLine(output) {
162
+ const lines = String(output || '').replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, '')
163
+ .split(/\r?\n|\r/).map((l) => l.trim()).filter((l) => l && !l.startsWith('$ '));
164
+ const last = lines[lines.length - 1] || '';
165
+ return last.length > 200 ? `${last.slice(0, 199)}…` : last;
166
+ }
167
+
156
168
  /**
157
169
  * How often the stall watchdog checks. Capped at half the stall budget so the
158
170
  * poll granularity never dominates the deadline (matters for a short budget in
@@ -1628,6 +1640,13 @@ class Installer {
1628
1640
 
1629
1641
  let env = this._buildShellEnv();
1630
1642
  const isWin = process.platform === 'win32';
1643
+ // Nobody can answer a prompt here (stdin is closed and, on Windows, the
1644
+ // console is hidden). A git fetch that asks for credentials — a GitHub
1645
+ // answer it reads as "sign in", or Git Credential Manager's sign-in
1646
+ // window — then waits until the stall watchdog kills it ten minutes
1647
+ // later. Make git fail at once instead, with its reason in the log.
1648
+ if (env.GIT_TERMINAL_PROMPT == null) env.GIT_TERMINAL_PROMPT = '0';
1649
+ if (env.GCM_INTERACTIVE == null) env.GCM_INTERACTIVE = 'never';
1631
1650
 
1632
1651
  // Resolve a compatible host and keep inherited PowerShell 7 modules out
1633
1652
  // of Windows PowerShell. Qoder otherwise cannot load Get-FileHash when
@@ -1768,9 +1787,14 @@ class Installer {
1768
1787
  stalled = true;
1769
1788
  clearStallTimer();
1770
1789
  const minutes = Math.round(INSTALL_STALL_MS / 60000);
1790
+ // What the installer said last is where it stopped: "Updating
1791
+ // https://github.com/…" is a download from GitHub that never
1792
+ // finished. Without it the stall said nothing about which step.
1793
+ const lastLine = stallLastLine(outputTail);
1771
1794
  const msg = `Install stalled: no output for ${minutes} minutes. `
1772
1795
  + 'The installer was stopped. It may be waiting on a prompt, or on a '
1773
- + 'download that never returns.';
1796
+ + 'download that never returns.'
1797
+ + (lastLine ? ` Last output: ${lastLine}` : '');
1774
1798
  if (onData) onData(`\n${msg}\n`);
1775
1799
  this._killProcessTree(proc);
1776
1800
  reject(new Error(msg));
@@ -3289,4 +3313,4 @@ function escapeRegExp(text) {
3289
3313
  return String(text).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
3290
3314
  }
3291
3315
 
3292
- module.exports = { Installer, compareVersions, clearVersionCache, loginVerdict, credentialListHasTarget, parseJsonLoose };
3316
+ module.exports = { Installer, compareVersions, clearVersionCache, loginVerdict, credentialListHasTarget, parseJsonLoose, stallLastLine };
package/src/mcp-server.js CHANGED
@@ -12,6 +12,7 @@
12
12
  * The workspace token is read from the OA_WORKSPACE_TOKEN env var.
13
13
  */
14
14
 
15
+ const fs = require('fs');
15
16
  const readline = require('readline');
16
17
  const { execSync, spawn: spawnChild } = require('child_process');
17
18
  const net = require('net');
@@ -525,6 +526,20 @@ function buildToolDefs(disabledModules) {
525
526
  required: ['action', 'kind'],
526
527
  },
527
528
  },
529
+ {
530
+ name: 'workspace_request_public_link',
531
+ description: 'Ask a person to publish a public "anyone with the link" page for a workspace file (image, video, HTML page, web project, table, document…) or knowledge entry. Use ONLY when the user asked to share something publicly or with people outside the workspace. You cannot create the link yourself: this files a request in the thread, and a person who can manage the artifact approves or rejects it. The link shows a snapshot of the artifact as it is now — later edits are not visible until someone shares it again. Optionally set an expiry (default: never). Once approved, the link arrives as a message in this thread @mentioning you; until then, do not claim a link exists.',
532
+ inputSchema: {
533
+ type: 'object',
534
+ properties: {
535
+ kind: { type: 'string', enum: ['file', 'knowledge'], description: 'file = a workspace file or web project; knowledge = a knowledge base entry' },
536
+ id: { type: 'string', description: 'The file id or knowledge entry id' },
537
+ reason: { type: 'string', description: 'Why it should be public, shown to the approver (e.g. "The user asked to send this report to a client")' },
538
+ expires_at: { type: 'string', description: 'Optional ISO 8601 date/time after which the link stops working, e.g. "2026-12-31T00:00:00Z". Omit for no expiry.' },
539
+ },
540
+ required: ['kind', 'id'],
541
+ },
542
+ },
528
543
  {
529
544
  name: 'workspace_check_approval',
530
545
  description: 'Check the status of an approval request you made earlier (by id). Use after workspace_request_approval returned "pending".',
@@ -645,17 +660,34 @@ function isTextMime(mime) {
645
660
  // ── MCP Server ──────────────────────────────────────────────────────────────
646
661
 
647
662
  class McpServer {
648
- constructor({ wsClient, workspaceId, channelName, agentName, token, disabledModules, requesterEmail = process.env.OPENAGENTS_REQUESTER_EMAIL || null }) {
663
+ constructor({ wsClient, workspaceId, channelName, agentName, token, disabledModules, requesterEmail = process.env.OPENAGENTS_REQUESTER_EMAIL || null, contextFile = null }) {
649
664
  this.ws = wsClient;
650
665
  this.workspaceId = workspaceId;
651
- this.channelName = channelName;
666
+ this._channelName = channelName;
652
667
  this.agentName = agentName;
653
668
  this.token = token;
654
- this.requesterEmail = requesterEmail;
669
+ this._requesterEmail = requesterEmail;
670
+ // A long-lived agent (OpenCode's warm server) serves many channels with one
671
+ // tools server: the channel and requester of the current turn are read from
672
+ // this file, which the adapter writes before each turn.
673
+ this.contextFile = contextFile;
655
674
  this.disabledModules = disabledModules || new Set();
656
675
  this.tools = buildToolDefs(this.disabledModules);
657
676
  }
658
677
 
678
+ _turnContext() {
679
+ if (!this.contextFile) return {};
680
+ try { return JSON.parse(fs.readFileSync(this.contextFile, 'utf-8')) || {}; } catch { return {}; }
681
+ }
682
+
683
+ get channelName() { return this._turnContext().channel || this._channelName; }
684
+ set channelName(v) { this._channelName = v; }
685
+ get requesterEmail() {
686
+ const ctx = this._turnContext();
687
+ return Object.prototype.hasOwnProperty.call(ctx, 'requesterEmail') ? ctx.requesterEmail : this._requesterEmail;
688
+ }
689
+ set requesterEmail(v) { this._requesterEmail = v; }
690
+
659
691
  start() {
660
692
  const rl = readline.createInterface({ input: process.stdin, terminal: false });
661
693
  rl.on('line', (line) => {
@@ -1249,6 +1281,23 @@ class McpServer {
1249
1281
  return text(formatApproval(approval));
1250
1282
  }
1251
1283
 
1284
+ case 'workspace_request_public_link': {
1285
+ const approval = await this.ws.requestPublicShare(this.workspaceId, this.token, {
1286
+ channel: this.channelName,
1287
+ kind: args.kind || 'file',
1288
+ id: args.id,
1289
+ reason: args.reason,
1290
+ expires_at: args.expires_at,
1291
+ source: `openagents:${this.agentName}`,
1292
+ });
1293
+ return text(
1294
+ `Public link request filed (approval id: ${approval.id}, status: ${approval.status || 'pending'}). ` +
1295
+ 'No link exists yet: a person who can manage the artifact must approve it in this thread. ' +
1296
+ 'Stop here and tell the user it is waiting for their approval; when approved, the link arrives ' +
1297
+ 'as a message @mentioning you. Check later with workspace_check_approval.'
1298
+ );
1299
+ }
1300
+
1252
1301
  case 'workspace_check_approval': {
1253
1302
  const approval = await this.ws.getApproval(this.workspaceId, this.token, args.approval_id);
1254
1303
  return text(formatApproval(approval));
@@ -1341,6 +1390,7 @@ function runMcpServer(opts) {
1341
1390
  agentName: opts.agentName,
1342
1391
  token: opts.token,
1343
1392
  disabledModules: opts.disabledModules,
1393
+ contextFile: opts.contextFile || null,
1344
1394
  });
1345
1395
  server.start();
1346
1396
  }
package/src/probe.js CHANGED
@@ -27,7 +27,9 @@
27
27
  * of anything key-shaped before it leaves this module.
28
28
  */
29
29
 
30
+ const fs = require('fs');
30
31
  const os = require('os');
32
+ const path = require('path');
31
33
  // spawn() here is the WSL bridge from ./wsl: same signature as
32
34
  // child_process.spawn, and a straight pass-through unless the resolved CLI
33
35
  // lives on the other side of the Windows/WSL boundary.
@@ -38,6 +40,7 @@ const { decodeConsoleOutput, BENIGN_CLI_OUTPUT, stripCliNoise, redactSecrets } =
38
40
  const { formatAuthGuidance } = require('./auth-guidance');
39
41
  const { isCliLogin, stripForCliLogin, typeEnvFor } = require('./env');
40
42
  const { configuredModel } = require('./agent-model');
43
+ const { codexPlanRefusedModel, codexAccountModels, codexPlanFallback } = require('./cli-models');
41
44
 
42
45
  const PROBE_PROMPT = 'hi';
43
46
  const DEFAULT_TIMEOUT_MS = 90_000;
@@ -153,9 +156,14 @@ function classifyOutputText(text) {
153
156
  // completion" or, refreshing its model list, "failed to refresh available
154
157
  // models: request timed out" — on a device that cannot reach chatgpt.com
155
158
  // that was all the probe saw before its clock ran out, and it was reported
156
- // as a CLI waiting for a login prompt.
157
- if (/enotfound|econnrefused|econnreset|etimedout|eai_again|fetch failed|socket hang up|network error|error sending request|request to \S+ timed out|self[- ]signed certificate|unable to get local issuer|connection failed|stream disconnected before completion|failed to lookup address|dns error|tls handshake|failed to refresh available models: request timed out/.test(text)) return CODE.NETWORK;
159
+ // as a CLI waiting for a login prompt. With no route at all it prints
160
+ // "Reconnecting... waiting for network" until the clock runs out.
161
+ if (/enotfound|econnrefused|econnreset|etimedout|eai_again|fetch failed|socket hang up|network error|error sending request|request to \S+ timed out|self[- ]signed certificate|unable to get local issuer|connection failed|stream disconnected before completion|failed to lookup address|dns error|tls handshake|failed to refresh available models: request timed out|reconnecting\.{3} waiting for network/.test(text)) return CODE.NETWORK;
158
162
  if (/api key.{0,24}(not set|not found|missing)|no api key|missing api key|environment variable.{0,40}(is )?(not set|required)/.test(text)) return CODE.MISSING_API_KEY;
163
+ // Codex with no sign-in at all sends no credential: "401 Unauthorized:
164
+ // Missing bearer … authentication", or for a ChatGPT workspace "workspace
165
+ // routing discovery unauthorized (401)". Nothing to re-enter, a sign-in.
166
+ if (/missing bearer|workspace routing discovery unauthorized/.test(text)) return CODE.NOT_LOGGED_IN;
159
167
  if (/invalid.{0,12}(api.?key|x-api-key|token)|incorrect api key|authentication[_ ]?error|invalid credentials|\b401\b|unauthorized|forbidden|\b403\b/.test(text)) return CODE.INVALID_API_KEY;
160
168
  // A sign-in that exists but has run out — Claude Code: "Failed to
161
169
  // authenticate: OAuth session expired and could not be refreshed".
@@ -171,7 +179,10 @@ function classifyOutputText(text) {
171
179
 
172
180
  function classifyFailure(output, { timedOut = false, spawnError = null } = {}) {
173
181
  if (spawnError && /ENOENT/.test(String(spawnError))) return CODE.NOT_INSTALLED;
174
- const text = String(output || '').toLowerCase();
182
+ // Notices (see PROBE_NOISE) never decide the verdict: Claude Code's "this
183
+ // sign-in ends between …, run claude auth login before then" read as
184
+ // "not logged in" on a sign-in that still worked.
185
+ const text = withoutProbeNotices(output).toLowerCase();
175
186
  if (timedOut) {
176
187
  // A CLI that retries a hard API error (bad key, unknown model, quota)
177
188
  // until the probe clock runs out is NOT "waiting for interactive input" —
@@ -439,6 +450,64 @@ function mostlyEncoded(line) {
439
450
  return encoded * 2 >= body.length;
440
451
  }
441
452
 
453
+ /**
454
+ * Lines a CLI prints on a run that say nothing about why it failed, so a
455
+ * failed test never quotes them as the reason, and the classifier never reads
456
+ * them. Each was quoted as the reason on the daily errors dashboard:
457
+ * - the `codex exec` banner (version, workdir, model, sandbox, session id)
458
+ * and its echo of the prompt;
459
+ * - Codex's notices about the user's own config.toml (settings it ignores,
460
+ * under-development features, a skill file it could not load);
461
+ * - Gemini's "Ripgrep is not available" and duplicate-skill notices;
462
+ * - Claude Code's untrusted-folder permissions notice, and its "this sign-in
463
+ * ends between …" reminder, which read as "not logged in" though the
464
+ * sign-in still worked.
465
+ */
466
+ const PROBE_NOISE = new RegExp([
467
+ /^OpenAI Codex v\d/,
468
+ /^-{4,}$/,
469
+ /^(workdir|model|provider|approval|sandbox|reasoning effort|reasoning summaries|session id): \S+$/,
470
+ /^(user|hi)$/,
471
+ /^hook: /,
472
+ /^mcp startup:/,
473
+ /^warning: Codex is ignoring \d+ unrecognized configuration setting/i,
474
+ /^(user|project|session-flags)\b.*: `[^`]+` is ignored\.?$/,
475
+ /Under-development features (enabled|are incomplete)/,
476
+ /\bfailed to load skill\b/,
477
+ /^warning: Codex could not find bubblewrap/i,
478
+ /^WARNING: proceeding, even though we could not create PATH aliases/,
479
+ /^Ripgrep is not available/,
480
+ /is overriding the same skill from/,
481
+ /^Ignoring \d+ permissions\.\w+ entries/,
482
+ /^Warning: this sign-in ends between/,
483
+ ].map((r) => r.source).join('|'), 'i');
484
+
485
+ /**
486
+ * Codex prefixes a failed WebSocket attempt's reason with this notice ("…
487
+ * transport. unexpected status 401 Unauthorized: Missing bearer …"); the
488
+ * reason after it is what matters.
489
+ */
490
+ const CODEX_WS_FALLBACK = /^\s*warning: Falling back from WebSockets to HTTPS transport\.\s*/i;
491
+
492
+ /** One line of CLI output with the notices above taken off; '' when it was only notice. */
493
+ function probeLine(line) {
494
+ const l = String(line).replace(CODEX_WS_FALLBACK, '').trim();
495
+ return l && !PROBE_NOISE.test(l) ? l : '';
496
+ }
497
+
498
+ /** CLI output without the notices above. */
499
+ function withoutProbeNotices(text) {
500
+ return String(text || '').split(/\r?\n/).map(probeLine).filter(Boolean).join('\n');
501
+ }
502
+
503
+ /** CLI output without the known-harmless lines (shared and probe-only). */
504
+ function withoutProbeNoise(text) {
505
+ return withoutProbeNotices(withoutNoise(text));
506
+ }
507
+
508
+ /** A line that reads as the error itself, when the classifier knows none. */
509
+ const ERRORISH = /\b(error|fatal|failed|failure|denied|refused|unauthorized|forbidden|not supported|no longer supported|invalid|exception)\b/i;
510
+
442
511
  /**
443
512
  * The one line worth reporting from a failed run.
444
513
  *
@@ -464,23 +533,75 @@ function failureMessage(res, code, timeoutMs) {
464
533
  // nothing else was said do they stand, rather than no reason at all.
465
534
  const LOG_RECORD = /^\d{4}-\d{2}-\d{2}T[\d:.]+Z?\s+(?=(TRACE|DEBUG|INFO|WARN|ERROR)\s)/;
466
535
  const SIDE_SERVICE = /\brmcp::|\bcodex_mcp::/;
467
- const lines = (s) => {
468
- const said = String(s || '').split(/\r?\n/).map((l) => scrub(l.trim()))
536
+ // `codex exec` opens with a banner (version, workdir, model, sandbox,
537
+ // session id) and echoes the prompt. On a probe that timed out with nothing
538
+ // else said, that banner was quoted as the reason — "Timed out after 120s:
539
+ // OpenAI Codex v0.165.0 -------- workdir: …" — which explains nothing.
540
+ // Noise lines (see PROBE_NOISE) are dropped as well.
541
+ const grouped = (s) => {
542
+ const said = String(s || '').split(/\r?\n/).map((l) => scrub(probeLine(l)))
469
543
  .filter((l) => l && !BENIGN_OUTPUT.test(l) && !mostlyEncoded(l) && !/^at\s+\S/.test(l));
470
544
  const own = said.filter((l) => !SIDE_SERVICE.test(l));
471
545
  const kept = own.length ? own : said;
472
546
  const plain = kept.filter((l) => !LOG_RECORD.test(l));
473
547
  const logged = kept.filter((l) => LOG_RECORD.test(l)).map((l) => l.replace(LOG_RECORD, ''));
474
- return [...plain, ...logged];
548
+ return { plain, logged };
475
549
  };
550
+ const lines = (s) => { const g = grouped(s); return [...g.plain, ...g.logged]; };
476
551
  const all = [...lines(res.stderr), ...lines(res.stdout)];
477
552
  const telling = all.find((l) => classifyOutputText(l.toLowerCase()) === code);
478
- const detail = tail(telling || lines(res.stderr).join('\n') || lines(res.stdout).join('\n'), OUTPUT_CAP);
553
+ // Nothing the classifier knows: the last line that reads as an error, not
554
+ // the tail of everything. Gemini dumps its account record before
555
+ // "IneligibleTierError: This client is no longer supported…", and the tail
556
+ // began mid-dump.
557
+ // Plain words rank ahead of log records here too.
558
+ const lastErrorish = (ls) => [...ls].reverse().find((l) => ERRORISH.test(l));
559
+ const errorish = (s) => { const g = grouped(s); return lastErrorish(g.plain) || lastErrorish(g.logged); };
560
+ const fallback = errorish(res.stderr) || errorish(res.stdout)
561
+ || lines(res.stderr).join('\n') || lines(res.stdout).join('\n');
562
+ const detail = tail(telling || fallback, OUTPUT_CAP);
479
563
  if (res.timedOut) {
480
564
  const prefix = `Timed out after ${Math.round(timeoutMs / 1000)}s`;
481
565
  return detail ? `${prefix}: ${detail}` : prefix;
482
566
  }
483
- return detail || `Exited with code ${res.code}`;
567
+ if (detail) return detail;
568
+ // "Exited with code 0" said only that the CLI finished.
569
+ return res.code === 0 ? 'The CLI finished without replying' : `Exited with code ${res.code}`;
570
+ }
571
+
572
+ /** A model id safe to pass on a command line, through a Windows shell too. */
573
+ const CODEX_MODEL_ARG = /^[\w.:@/-]{1,128}$/;
574
+
575
+ /**
576
+ * Codex's probe run, cut down to the one question it asks.
577
+ *
578
+ * `codex exec hi` starts everything the user's ~/.codex/config.toml sets up
579
+ * before it sends "hi": every MCP server (a Figma connector whose host does
580
+ * not answer), every hook, and the built-in ChatGPT apps connector. On a slow
581
+ * or blocked network those alone ran the 120s probe clock out, and the test
582
+ * reported Codex broken when sign-in and model were fine. The real chat run
583
+ * still loads all of it; only the probe leaves it out.
584
+ *
585
+ * Only `-c` overrides, never newer flags: an older Codex rejects a flag it
586
+ * does not know, but ignores (with a warning) a feature it does not know.
587
+ * Server names are taken from the `[mcp_servers.<name>]` tables and only
588
+ * bare names are used, so nothing needs quoting through a Windows shell.
589
+ */
590
+ function codexProbeArgs(args, env = {}, model = null) {
591
+ if (!Array.isArray(args) || args[0] !== 'exec') return args;
592
+ const home = env.CODEX_HOME || path.join(os.homedir(), '.codex');
593
+ let text = '';
594
+ try { text = fs.readFileSync(path.join(home, 'config.toml'), 'utf8'); } catch {}
595
+ const names = new Set();
596
+ for (const m of text.matchAll(/^[ \t]*\[[ \t]*mcp_servers\.([A-Za-z0-9_-]+)[ \t]*[.\]]/gm)) names.add(m[1]);
597
+ const extra = ['-c', 'features.hooks=false', '-c', 'features.apps=false'];
598
+ for (const name of names) extra.push('-c', `mcp_servers.${name}.enabled=false`);
599
+ // The model the agent's chat runs on (the adapter passes `-m`). Without it
600
+ // the test ran Codex's own default: an agent set to gpt-5.6-luna failed
601
+ // its test on gpt-6.1-sol, which its ChatGPT plan does not include.
602
+ if (model && CODEX_MODEL_ARG.test(model)) extra.push('-m', model);
603
+ // After the subcommand: `codex exec -c … hi`.
604
+ return [args[0], ...extra, ...args.slice(1)];
484
605
  }
485
606
 
486
607
  /** Run a CLI to completion with a hard timeout. Never rejects. */
@@ -646,18 +767,44 @@ async function probeAgentType(connector, type, opts = {}) {
646
767
  // ── Live tier 1: the agent's own CLI, when the registry declares how ──
647
768
  if (hasLiveCli) {
648
769
  const shell = probeArgs && health.binary ? shouldUseShellForBinary(health.binary) : true;
649
- const res = probeArgs && health.binary
770
+ const runProbeCli = (m) => runCommand(shellQuoted(health.binary, shell),
771
+ type === 'codex' ? codexProbeArgs(probeArgs, env, m) : probeArgs, { env, timeoutMs, shell });
772
+ let res = probeArgs && health.binary
650
773
  // Node refuses to spawn .cmd/.bat without a shell (EINVAL since the
651
774
  // CVE-2024-27980 hardening), which made every Windows CLI probe of an
652
775
  // npm-shim binary fail as "Exited with code 1" with no output.
653
- ? await runCommand(shellQuoted(health.binary, shell), probeArgs, { env, timeoutMs, shell })
776
+ ? await runProbeCli(model)
654
777
  : await runCommand(altCheck, [], { env, timeoutMs, shell: true });
655
- const output = withoutNoise(`${res.stdout}\n${res.stderr}`);
656
- const reply = withoutNoise(res.stdout).trim();
778
+ // A ChatGPT sign-in refusing the model Codex ran on. With no model
779
+ // chosen that is Codex's default, and the chat adapter then runs the
780
+ // first model the account lists (adapters/codex.js); test that one. With
781
+ // a model chosen, say which models the account does list.
782
+ let planNote = '';
783
+ const refused = type === 'codex' && probeArgs && health.binary
784
+ ? codexPlanRefusedModel(`${res.stdout}\n${res.stderr}`) : null;
785
+ if (refused && !model) {
786
+ let fallback = null;
787
+ try { fallback = await codexPlanFallback(health.binary, env, refused); } catch {}
788
+ if (fallback && CODEX_MODEL_ARG.test(fallback)) {
789
+ res = await runProbeCli(fallback);
790
+ planNote = ` on ${fallback}: Codex's default model (${refused}) isn't included in this ChatGPT plan, so chats use ${fallback}`;
791
+ }
792
+ } else if (refused) {
793
+ let listed = [];
794
+ try { listed = (await codexAccountModels(health.binary, env)).map((m) => m.id); } catch {}
795
+ return done({
796
+ ok: false, method: 'cli', code: CODE.BAD_MODEL,
797
+ message: `${refused} isn't included in this ChatGPT plan.`
798
+ + (listed.length ? ` Models this account lists: ${listed.slice(0, 8).join(', ')}.` : ''),
799
+ guidance: buildGuidance(CODE.BAD_MODEL, entry, agentEnv),
800
+ });
801
+ }
802
+ const output = withoutProbeNoise(`${res.stdout}\n${res.stderr}`);
803
+ const reply = withoutProbeNoise(res.stdout).trim();
657
804
  if (!res.timedOut && !res.spawnError && res.code === 0 && reply) {
658
805
  return done({
659
806
  ok: true, method: 'cli', code: CODE.OK,
660
- message: 'Responded',
807
+ message: `Responded${planNote}`,
661
808
  reply: tail(reply, REPLY_CAP),
662
809
  });
663
810
  }
@@ -671,7 +818,7 @@ async function probeAgentType(connector, type, opts = {}) {
671
818
  if (res.timedOut && !res.spawnError && looksLikeAnswer) {
672
819
  return done({
673
820
  ok: true, method: 'cli', code: CODE.OK,
674
- message: `Responded (the CLI did not exit within ${Math.round(timeoutMs / 1000)}s)`,
821
+ message: `Responded${planNote} (the CLI did not exit within ${Math.round(timeoutMs / 1000)}s)`,
675
822
  reply: tail(reply, REPLY_CAP),
676
823
  });
677
824
  }
@@ -787,4 +934,4 @@ async function probeAgentType(connector, type, opts = {}) {
787
934
  });
788
935
  }
789
936
 
790
- module.exports = { probeAgentType, classifyFailure, buildGuidance, authFlavor, installCommandFor, scrub, failureMessage, CODE, DEFAULT_TIMEOUT_MS };
937
+ module.exports = { probeAgentType, codexProbeArgs, classifyFailure, buildGuidance, authFlavor, installCommandFor, scrub, failureMessage, CODE, DEFAULT_TIMEOUT_MS };