viewable-one 0.12.7 → 0.12.9

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.
@@ -1,7 +1,7 @@
1
1
  // Shared authenticated JSON transport for the MCP and runner endpoints.
2
2
  // The deadline covers token refresh and response-body consumption, not just
3
3
  // receiving headers. A stalled endpoint must not wedge runner settlement.
4
- import { REAUTH_REQUIRED_HINT, hostedToken, noteCredentialRejected, reauthRequired } from './auth.mjs';
4
+ import { hostedToken, noteCredentialRejected, reauthHint, reauthRequired } from './auth.mjs';
5
5
 
6
6
  export const NOT_SIGNED_IN_HINT =
7
7
  'Not signed in to the hosted board. Run `viewable login`, or for a script set ' +
@@ -52,7 +52,7 @@ export async function authenticatedJsonPost(url, body, options = {}) {
52
52
  // waiting; it must not cancel another caller's rotating-token exchange.
53
53
  const token = await hostedToken({ env, fetchImpl, forceRefresh });
54
54
  controller.signal.throwIfAborted();
55
- if (!token) return { authError: await reauthRequired(env) ? REAUTH_REQUIRED_HINT : NOT_SIGNED_IN_HINT };
55
+ if (!token) return { authError: await reauthRequired(env) ? await reauthHint(env) : NOT_SIGNED_IN_HINT };
56
56
  let result = await post(token);
57
57
  let lastBearer = token;
58
58
  if (result.response.status === 401 && !forceRefresh) {
package/lib/boardside.mjs CHANGED
@@ -237,5 +237,7 @@ export async function reportOutcomeOnBoard(session, outcome, frameId, options =
237
237
  const lines = [text, outcome.result?.fixAttempted && "Coding tried one fix.", outcome.picturesNote].filter(Boolean);
238
238
  const closing = lines.join("\n\n");
239
239
  const receipt = await commentOnAnchor(session, frameId, closing, { ...rest, fields });
240
- return { landed: receipt?.ok === true && Boolean(closingTextOf(outcome)) };
240
+ // A refused write rides inside a 200 (#7489): hand its words back so the
241
+ // runner can log why the answer did not land.
242
+ return { landed: receipt?.ok === true && Boolean(closingTextOf(outcome)), ...(receipt?.ok === false ? { refusal: receipt.detail } : {}) };
241
243
  }
package/lib/child.mjs CHANGED
@@ -24,6 +24,7 @@ import { makeAnswerTracker } from "./answerTag.mjs";
24
24
  import { RUNNER_BEAT_MS } from "./spawn.mjs";
25
25
  import { DELIVERED, SKIP, STOP, watchAnswers, watchReplyFiles } from "./followUps.mjs";
26
26
  import { runnableCommand } from "./windows-command.mjs";
27
+ import { otherBoardCall } from "./mcpjson.mjs";
27
28
 
28
29
  // Defaults, all overridable by env and all bounds rather than preferences.
29
30
  export const DEFAULTS = {
@@ -710,7 +711,7 @@ export function attachChild(child, {
710
711
  * The wall clock is not a progress protocol and does not put a third state on
711
712
  * the board. It is the one bound between "a session hung" and "a session
712
713
  * billed all night". */
713
- export function runChild({ bin, args, cwd, env, input, recoveryGroup = false, onProcess, onSession, maxMs, maxLogBytes = DEFAULTS.maxLogBytes, killGraceMs = DEFAULTS.killGraceMs, onChunk, onStdout, stopCheck, stopPollMs = 2000, onSpend, platform = process.platform, transcriptDir, killProcessGroup = false, keepPids, claudeResult = false }) {
714
+ export function runChild({ bin, args, cwd, env, input, recoveryGroup = false, onProcess, onSession, maxMs, maxLogBytes = DEFAULTS.maxLogBytes, killGraceMs = DEFAULTS.killGraceMs, onChunk, onStdout, stopCheck, stopPollMs = 2000, onSpend, platform = process.platform, transcriptDir, killProcessGroup = false, keepPids, claudeResult = false, notices = [] }) {
714
715
  // A private group is a group that is signalled: one flag, not two (#6557).
715
716
  const ownGroup = (killProcessGroup || recoveryGroup) && platform !== "win32";
716
717
  return new Promise((resolve) => {
@@ -757,6 +758,7 @@ export function runChild({ bin, args, cwd, env, input, recoveryGroup = false, on
757
758
  okOf: (state, code) => !state.timedOut && !state.stoppedByUser && !(claudeResult && state.resultWasError) && code === 0,
758
759
  extraFields: (state) => claudeResult ? { finishedWithError: state.resultWasError && !state.timedOut && !state.stoppedByUser } : {},
759
760
  });
761
+ emitNotices(child, notices);
760
762
  if (input !== undefined) {
761
763
  // A child that dies during startup can close the pipe before end lands.
762
764
  // Its process error/close event owns the outcome; stdin's EPIPE is not a
@@ -833,7 +835,7 @@ export function runChild({ bin, args, cwd, env, input, recoveryGroup = false, on
833
835
  * whole new resume request - the watch loop's 5s poll, the app's receipt, the
834
836
  * worktree, and a cold `claude --resume`. That is tens of seconds and it is a
835
837
  * design decision, not a constant. */
836
- export function runStreamingChild({ bin, args, cwd, env, recoveryGroup = false, onSpawn, onProcess, onSession, maxMs, maxLogBytes = DEFAULTS.maxLogBytes, killGraceMs = DEFAULTS.killGraceMs, stallMs = DEFAULTS.stallMs, onChunk, prompt, images, replyDir, replyPrefix, replyPollMs = 500, onUndeliveredReply, answerPoll, answerPollMs = 4000, askPermission, stopCheck, stopPollMs = 2000, onSpend, platform = process.platform, transcriptDir, keepPids }) {
838
+ export function runStreamingChild({ bin, args, cwd, env, recoveryGroup = false, onSpawn, onProcess, onSession, maxMs, maxLogBytes = DEFAULTS.maxLogBytes, killGraceMs = DEFAULTS.killGraceMs, stallMs = DEFAULTS.stallMs, onChunk, prompt, images, replyDir, replyPrefix, replyPollMs = 500, onUndeliveredReply, answerPoll, answerPollMs = 4000, askPermission, stopCheck, stopPollMs = 2000, onSpend, platform = process.platform, transcriptDir, keepPids, boardServerKey, notices = [], log }) {
837
839
  // Its private group is signalled on Stop and timeout, not just created (#6557).
838
840
  const ownGroup = recoveryGroup && platform !== "win32";
839
841
  return new Promise((resolve) => {
@@ -1000,6 +1002,19 @@ export function runStreamingChild({ bin, args, cwd, env, recoveryGroup = false,
1000
1002
  return;
1001
1003
  }
1002
1004
  const input = request.input && typeof request.input === "object" ? request.input : {};
1005
+ // ANOTHER BOARD SERVER IS REFUSED HERE, BEFORE ANY QUESTION (#7550).
1006
+ // The run loads only its own board server, so this is the second
1007
+ // line: a board server that got in anyway (a connector still
1008
+ // connecting, a renamed self-hosted one, a resource read naming one)
1009
+ // is never offered to the person as "Use report in glytch?", where
1010
+ // one Allow would write to another account's boards. Decided from the
1011
+ // call alone, never from the init list.
1012
+ const other = otherBoardCall(request.tool_name, input, { own: boardServerKey });
1013
+ if (other) {
1014
+ log?.(`permission: ${String(request.tool_name)} reaches another Viewable board server (${other.server}), refused (#7550)`);
1015
+ answerControl(requestId, { behavior: "deny", message: otherBoardDenied(other.server, boardServerKey) });
1016
+ return;
1017
+ }
1003
1018
  if (!askPermission) {
1004
1019
  answerControl(requestId, { behavior: "deny", message: "This run cannot ask the person for permission. Carry on without it." });
1005
1020
  return;
@@ -1027,6 +1042,7 @@ export function runStreamingChild({ bin, args, cwd, env, recoveryGroup = false,
1027
1042
  .finally(() => { pendingPermissions.delete(requestId); });
1028
1043
  }
1029
1044
 
1045
+ emitNotices(child, notices);
1030
1046
  sendToChild(userMessage(prompt, images));
1031
1047
 
1032
1048
  // Reply files and board answers: the steps are shared by all three engines
@@ -1291,3 +1307,18 @@ export function childEnv(baseEnv, { root, session, depth, fromId, platform = pro
1291
1307
  env.PM_SPAWN_DEPTH = String((depth ?? 0) + 1);
1292
1308
  return env;
1293
1309
  }
1310
+
1311
+ /** The refusal the model reads when it calls another board server (#7550);
1312
+ * `own` is the run's board server key, `glytch` on Codex. One sentence for
1313
+ * every engine (#7591). */
1314
+ export function otherBoardDenied(server, own) {
1315
+ return `${server} is not this run's board. Use your own board tools${own ? ` (mcp__${own}__ask_user, mcp__${own}__report and the rest)` : ""}; never another board server.`;
1316
+ }
1317
+
1318
+ /** Lines the runner says to the person before the agent starts, in the
1319
+ * agent's own stream so the run's card shows them (#7550: apps left off). */
1320
+ function emitNotices(child, notices) {
1321
+ for (const message of Array.isArray(notices) ? notices : []) {
1322
+ if (typeof message === "string" && message) child.stdout.emit("data", Buffer.from(`${JSON.stringify({ type: "system", subtype: "info", message })}\n`));
1323
+ }
1324
+ }
package/lib/codex.mjs CHANGED
@@ -1,16 +1,38 @@
1
1
  import { writeRisk, riskReason } from "./writePolicy.mjs";
2
+ import { automationReadWords, isTypedNo, typedWords as typedWordsOf } from "./permissionAsk.mjs";
2
3
  // Codex's native app-server protocol, translated to the board's session log.
3
4
  // No SDK or API key is needed: this uses the user's installed, signed-in CLI.
4
5
  import { PassThrough } from "node:stream";
5
6
  import { writeFile } from "node:fs/promises";
6
- import { attachChild, DEFAULTS } from "./child.mjs";
7
+ import { attachChild, DEFAULTS, otherBoardDenied } from "./child.mjs";
7
8
  import { imageAttachments } from "./imageAttachments.mjs";
8
9
  import { DELIVERED, SKIP, watchAnswers, watchReplyFiles } from "./followUps.mjs";
9
- import { CODEX_TOOL_TIMEOUT_SEC } from "./mcpjson.mjs";
10
+ import { CODEX_TOOL_TIMEOUT_SEC, otherBoardCall } from "./mcpjson.mjs";
10
11
  import { codexRpc, startCodex } from "./codex-rpc.mjs";
11
12
  import { planWindowInfoMessage, readPlanWindow } from "./codexPlanWindow.mjs";
12
13
  import { prepareCodexApps, verifyCodexApps } from "./codexApps.mjs";
13
14
  import { secretLike, toolInputsText } from "./codexToolInputs.mjs";
15
+ import { CODEX_LOGIN_HOOK_KEY, codexLoginHookCommand, codexOtherLoginArgs } from "./otherLogins.mjs";
16
+
17
+ // ANOTHER LOGIN IS REFUSED BEFORE IT RUNS, ON CODEX TOO (#7466). The board's
18
+ // ask in Codex's words, for the refusal the hook hands back; it matches the
19
+ // `mcp_servers.glytch` key codexBoardArgs registers.
20
+ const CODEX_ASK = "mcp__glytch__ask_user";
21
+ const LOGIN_HOOK_MISSING = "Codex on this computer did not load the block on other logins, so this run did not start. " +
22
+ "Update Codex (`codex update`) and run again.";
23
+
24
+ /** Whether the running app server lists the other-login hook (otherLogins.mjs
25
+ * `codexOtherLoginArgs`) as trusted and on for this folder. Codex runs an
26
+ * untrusted or switched-off hook never, so a run without it is not started:
27
+ * an older Codex (no hooks/list), a hash Codex no longer accepts, or custom
28
+ * arguments that replaced the hook all fail closed. */
29
+ async function requireLoginHook(rpc, cwd, command = codexLoginHookCommand({ ask: CODEX_ASK })) {
30
+ let listed;
31
+ try { listed = await rpc.request("hooks/list", cwd ? { cwds: [cwd] } : {}); } catch { throw new Error(LOGIN_HOOK_MISSING); }
32
+ const hooks = (Array.isArray(listed?.data) ? listed.data : []).flatMap((entry) => (Array.isArray(entry?.hooks) ? entry.hooks : []));
33
+ const ours = hooks.find((hook) => hook?.key === CODEX_LOGIN_HOOK_KEY && hook.command === command);
34
+ if (!ours || ours.enabled !== true || ours.eventName !== "preToolUse" || !["trusted", "managed"].includes(ours.trustStatus)) throw new Error(LOGIN_HOOK_MISSING);
35
+ }
14
36
 
15
37
  // MOVED ONTO THE HOSTED ENDPOINT, 2026-09-11 (brief 30, W2a): the local
16
38
  // stdio server this used to spawn as `mcp_servers.board`'s
@@ -256,12 +278,28 @@ function protocolQuestions(method, params) {
256
278
  return { questions };
257
279
  }
258
280
 
281
+ // The other board server an app approval reaches, or null (#7550, #7591).
282
+ // The run's own board is `mcp_servers.glytch`, set to approve every tool
283
+ // (codexBoardArgs), so it never asks: exempting it here costs nothing, and a
284
+ // plugin's or an app's `glytch` is switched off by the apps check before it
285
+ // can. When Codex names the call only in words (an older input request whose
286
+ // started item was never seen), the words are read for this refusal alone: a
287
+ // wrong read can only refuse, never allow (#6955 keeps allowing off the words).
288
+ const otherBoardAsk = (called, method, params, question) => {
289
+ const own = { own: "glytch" };
290
+ if (called) return otherBoardCall(`mcp__${called.app}__${called.tool}`, {}, own);
291
+ if (method === ELICITATION) return otherBoardCall("ReadMcpResourceTool", { server: params.serverName }, own);
292
+ const named = /^Allow (\S+) (\S+?)\?$/.exec(String(question.question ?? "").trim());
293
+ return named ? otherBoardCall(`mcp__${named[1]}__${named[2]}`, {}, own) : null;
294
+ };
295
+
259
296
  export async function runCodexChild(opts) {
260
297
  const isDraft = opts.codex?.planMode === "draft";
298
+ const prepare = () => prepareCodexApps(opts, { on: opts.codex?.computerApps === true, isDraft });
261
299
  let apps;
262
300
  try {
263
301
  imageAttachments(opts.images);
264
- apps = await prepareCodexApps(opts, { on: opts.codex?.computerApps === true, isDraft });
302
+ apps = await prepare();
265
303
  } catch (error) { return { ok: false, log: "", spawnError: error.message }; }
266
304
  const startedAt = Date.now();
267
305
  const maxMs = opts.maxMs ?? 60_000;
@@ -270,7 +308,15 @@ export async function runCodexChild(opts) {
270
308
  if (remainingMs <= 0) return { ok: false, log: "", spawnError: "Codex ran out of time checking apps." };
271
309
  const { appsRetry: retry, ...outcome } = await runCodexAttempt({ ...opts, maxMs: remainingMs }, apps);
272
310
  if (!retry || outcome.timedOut || outcome.stoppedByUser || outcome.stalled) return outcome;
273
- apps = { args: [...apps.args, ...retry.args], sources: retry.sources, notices: [...apps.notices, ...retry.notices] };
311
+ if (retry.unseen) {
312
+ // A new folder: Codex trusted it at thread/start and loaded its own
313
+ // servers after our read (#7529). Read the apps again, once, as Try
314
+ // again would; a server still unseen is then checked as usual. We
315
+ // never write the folder's trust ourselves.
316
+ try { apps = { ...(await prepare()), seen: undefined }; } catch (error) { return { ok: false, log: "", spawnError: error.message }; }
317
+ continue;
318
+ }
319
+ apps = { args: [...apps.args, ...retry.args], sources: retry.sources, notices: [...apps.notices, ...retry.notices], seen: apps.seen };
274
320
  }
275
321
  }
276
322
 
@@ -296,7 +342,10 @@ function runCodexAttempt(opts, apps) {
296
342
  // here, server by server, before the app server starts.
297
343
  const appSources = apps.sources;
298
344
  let appsRetry;
299
- const start = async () => [...(opts.args ?? ["app-server"]), ...(isDraft ? [] : codexBoardArgs(config).slice(1)), ...apps.args];
345
+ // The other-login hook goes last, on every run, a draft included: a
346
+ // read-only sandbox still reads a token file (#7466).
347
+ const start = async () => [...(opts.args ?? ["app-server"]), ...(isDraft ? [] : codexBoardArgs(config).slice(1)), ...apps.args,
348
+ ...codexOtherLoginArgs({ ask: CODEX_ASK })];
300
349
  start().then((args) => {
301
350
  try { child = startCodex({ ...opts, args }); } catch (error) { resolve({ ok: false, log: "", spawnError: error.message }); return; }
302
351
  drive();
@@ -335,6 +384,8 @@ function runCodexAttempt(opts, apps) {
335
384
  let finishTimer;
336
385
  let lastAssistantText = "";
337
386
  const opened = new Map();
387
+ let verifiedApps = null; // the apps as the running thread reports them; null until checked
388
+ const mcpCalls = new Map(); // item id -> Codex's own mcpToolCall item, for an approval that names only the item
338
389
  const closed = new Set();
339
390
  const messages = agentMessageAssembler();
340
391
  const emit = (event) => { if (!handle.settled()) translated.write(`${JSON.stringify({ ...event, session_id: threadId })}\n`); };
@@ -392,7 +443,7 @@ function runCodexAttempt(opts, apps) {
392
443
  const toolStart = (item) => {
393
444
  if (closed.has(item.id)) return;
394
445
  let name; let input;
395
- if (item.type === "mcpToolCall") { name = `mcp__${item.server}__${item.tool}`; input = item.arguments; }
446
+ if (item.type === "mcpToolCall") { name = `mcp__${item.server}__${item.tool}`; input = item.arguments; mcpCalls.set(item.id, item); }
396
447
  else if (item.type === "commandExecution") { name = "Bash"; input = { command: item.command }; }
397
448
  else if (item.type === "fileChange") { name = "Edit"; input = { changes: item.changes }; }
398
449
  else return;
@@ -410,6 +461,29 @@ function runCodexAttempt(opts, apps) {
410
461
  opened.set(item.id, snapshot);
411
462
  assistant([{ type: "tool_use", id: item.id, name, input }]);
412
463
  };
464
+ // The app, tool and arguments an app approval is for, or null when they cannot
465
+ // be read reliably. Elicitation: the tool is `_meta.tool_name` (the field
466
+ // Codex's own reviewer reads), the arguments `_meta.tool_params`. Legacy input
467
+ // request: Codex's own started item (same item id) holds the server, tool and
468
+ // arguments. Never from the approval's words, which can quote an argument (#6955).
469
+ const calledApp = (method, params, question) => {
470
+ if (method === ELICITATION) {
471
+ const named = params._meta?.tool_name;
472
+ const tool = question.id === undefined && typeof named === "string" && named !== "" ? named : undefined;
473
+ const input = params._meta?.tool_params;
474
+ // Only a real tool approval (its marker, and its arguments as an object) can skip the ask.
475
+ // Codex marks a call it calls sensitive: that one asks.
476
+ if (!tool || params._meta?.codex_approval_kind !== "mcp_tool_call" || !object(input) || params._meta?.codex_sensitive_action === true) return null;
477
+ return { app: params.serverName, tool, input };
478
+ }
479
+ const item = mcpCalls.get(params.itemId);
480
+ return item && object(item.arguments ?? {}) ? { app: item.server, tool: item.tool, input: item.arguments ?? {} } : null;
481
+ };
482
+ const automationRead = ({ app, tool, input }) => {
483
+ // The labels of the thread that is running, read when it started (verifyCodexApps), never the earlier ones.
484
+ const source = verifiedApps?.find((entry) => entry.enabled && entry.name === app);
485
+ return source?.tools?.includes(tool) === true && opts.askPermission.appRead?.(app, tool, input, source.annotations?.[tool]) === true;
486
+ };
413
487
  rpc = codexRpc(child, {
414
488
  timeoutMs: opts.rpcTimeoutMs ?? 15_000,
415
489
  async onRequest(method, params, requestId) {
@@ -443,6 +517,30 @@ function runCodexAttempt(opts, apps) {
443
517
  if (controller.signal.aborted || approvalsClosed() || resolvedRequests.has(requestId) || !identityMatches()) return cancelled;
444
518
  const appApproval = question.id?.startsWith("mcp_tool_call_approval") ||
445
519
  (method === ELICITATION && question.id === undefined && question.options.includes("Allow"));
520
+ // An automation's read of an app is allowed by the automation itself (#5495, #6896):
521
+ // the same rule the server runs, with the app's own labels from the inventory.
522
+ // An approval that names no tool, or one with no arguments to read, keeps asking.
523
+ const called = appApproval ? calledApp(method, params, question) : null;
524
+ // ANOTHER BOARD SERVER IS REFUSED BEFORE ANY QUESTION, ON CODEX TOO (#7550, #7591).
525
+ // The apps check switches off every board server it can name; this is the
526
+ // second line, as child.mjs is for Claude: a board server it missed (a
527
+ // renamed one, one that started late) is never offered to the person as
528
+ // "Allow?", where one Allow would write to another account's boards.
529
+ // Decided from the call alone: the server's name or a tool only the board
530
+ // has (otherBoardAsk).
531
+ const other = appApproval ? otherBoardAsk(called, method, params, question) : null;
532
+ if (other) {
533
+ opts.log?.(`permission: ${other.tool || "a request"} reaches another Viewable board server (${other.server}), refused (#7550)`);
534
+ emit({ type: "system", subtype: "permission", decision: "denied", message: otherBoardDenied(other.server, "glytch") });
535
+ return refused;
536
+ }
537
+ if (called && automationRead(called)) {
538
+ opts.log?.(`permission: ${called.tool} is a read in an automation, no question filed (#5495)`);
539
+ // The run's card says the automation was the yes, as a refusal says its no (#6955).
540
+ emit({ type: "system", subtype: "permission", decision: "allowed", automation: true, message: automationReadWords(called.app, called.tool) });
541
+ answers.push("Allow");
542
+ continue;
543
+ }
446
544
  const hostedQuestion = { ...question, options: [...question.options, CANCEL],
447
545
  recommendation: appApproval
448
546
  ? { answer: "Allow", why: "It lets this run carry on with what you asked." }
@@ -460,12 +558,16 @@ function runCodexAttempt(opts, apps) {
460
558
  if (verdict.behavior === "answer" && verdict.answer === CANCEL) return cancelled;
461
559
  if (verdict.behavior === "answer" && typeof verdict.answer === "string" && !verdict.answer.trim()) return refused;
462
560
  if (appApproval && verdict.behavior === "answer" && verdict.answer === "Not this") return refused;
463
- if ((method === ELICITATION || appApproval) && verdict.behavior === "answer" && typeof verdict.answer === "string" && !question.options.includes(verdict.answer)) {
561
+ // WORDS NEVER GRANT (#8224): typed words are own words even when they
562
+ // spell an option ("Allow"), and so is the app's "Not this: <words>".
563
+ const typedWords = verdict.behavior === "answer" && typeof verdict.answer === "string" &&
564
+ (verdict.typed === true || isTypedNo(verdict.answer) || !question.options.includes(verdict.answer));
565
+ if ((method === ELICITATION || appApproval) && typedWords) {
464
566
  // Declines have no protocol content. Use the incumbent live
465
567
  // reply path so own words reach the agent, never grant a call.
466
568
  ownWordsPending += 1;
467
569
  try {
468
- if (!(await deliver(`The person declined this app request: ${question.question}\nTheir answer: ${verdict.answer}`))) throw new Error("the turn is no longer active");
570
+ if (!(await deliver(`The person declined this app request: ${question.question}\nTheir answer: ${typedWordsOf(verdict.answer)}`))) throw new Error("the turn is no longer active");
469
571
  } catch (error) {
470
572
  // Completion may already have begun while steer was in
471
573
  // flight. Preserve its delivery failure before closing.
@@ -627,6 +729,8 @@ function runCodexAttempt(opts, apps) {
627
729
  }, Math.min(10_000, stallMs / 4));
628
730
  void (async () => {
629
731
  await rpc.initialize();
732
+ // Before anything that could run a command (#7466).
733
+ await requireLoginHook(rpc, opts.cwd);
630
734
  // ONE EXTRA CALL, ON THE SAME CONNECTION, BEFORE ANY BILLABLE TURN
631
735
  // (brief 46, Move 4). Codex reports no dollars; what it reports
632
736
  // instead is how full its 5-hour and weekly windows are
@@ -671,7 +775,9 @@ function runCodexAttempt(opts, apps) {
671
775
  // implementation thread's history or permissions.
672
776
  const thread = await rpc.request(!isDraft && config.resumeSessionId ? "thread/resume" : "thread/start", {
673
777
  ...(!isDraft && config.resumeSessionId ? { threadId: config.resumeSessionId } : {}),
674
- cwd: opts.cwd, approvalPolicy: asking ? "on-request" : "never", sandbox: isDraft ? "read-only" : "workspace-write",
778
+ // An ask that only reads apps (#8261) takes the same read-only sandbox,
779
+ // and keeps its board server and its thread.
780
+ cwd: opts.cwd, approvalPolicy: asking ? "on-request" : "never", sandbox: isDraft || config.readOnly === true ? "read-only" : "workspace-write",
675
781
  ...(isDraft ? { ephemeral: true } : {}),
676
782
  ...(config.model ? { model: config.model } : {}),
677
783
  // The extra writable root for `<boardRoot>/.glytch` retired with it
@@ -682,7 +788,7 @@ function runCodexAttempt(opts, apps) {
682
788
  // rather than by a filesystem-writing subprocess, so there is nothing
683
789
  // under `.glytch` for this sandbox to need write access to any more.
684
790
  config: {
685
- ...(isDraft ? {} : { "sandbox_workspace_write.writable_roots": [opts.cwd].filter(Boolean) }),
791
+ ...(isDraft || config.readOnly === true ? {} : { "sandbox_workspace_write.writable_roots": [opts.cwd].filter(Boolean) }),
686
792
  ...(config.effort ? { model_reasoning_effort: config.effort } : {}),
687
793
  // THE PLAN TOOL, SWITCHED ON (2026-09-26, the same live run): the
688
794
  // preamble tells a Codex session to plan with `update_plan`, and
@@ -716,13 +822,19 @@ function runCodexAttempt(opts, apps) {
716
822
  threadId = thread.thread?.id;
717
823
  if (!threadId) throw new Error("Codex did not return a thread id");
718
824
  await opts.onSession?.(threadId);
719
- const checkedApps = await verifyCodexApps(rpc, { cwd: opts.cwd, threadId, on: config.computerApps === true, isDraft, sources: appSources });
825
+ const checkedApps = await verifyCodexApps(rpc, { cwd: opts.cwd, threadId, on: config.computerApps === true, isDraft, sources: appSources, seen: apps.seen, env: opts.boardEnv });
826
+ if (checkedApps.unseen) {
827
+ appsRetry = checkedApps;
828
+ finish("Reading the apps again: Codex loaded this folder's apps after they were read.");
829
+ return;
830
+ }
720
831
  if (checkedApps.notices.length) {
721
832
  appsRetry = checkedApps;
722
833
  // Reap the child through the existing bounded shutdown before retrying.
723
834
  finish("Checking apps again with the unverified apps turned off.");
724
835
  return;
725
836
  }
837
+ verifiedApps = checkedApps.sources;
726
838
  for (const message of apps.notices) emit({ type: "system", subtype: "info", message });
727
839
  emit({ type: "system", subtype: "init", model: thread.model ?? config.model, effort: thread.reasoningEffort ?? config.effort, engine: "codex" });
728
840
  emit({ type: "system", subtype: "info", message: planWindowInfoMessage(planWindow) });
package/lib/codexApps.mjs CHANGED
@@ -3,6 +3,20 @@
3
3
  import { codexRpc, startCodex } from "./codex-rpc.mjs";
4
4
  import { killTree } from "./kill.mjs";
5
5
  import { secretLike } from "./codexToolInputs.mjs";
6
+ import { isBoardServer } from "./mcpjson.mjs";
7
+
8
+ // ANOTHER VIEWABLE BOARD IS NEVER ONE OF THE PERSON'S APPS (#7550). With the
9
+ // apps on, a `viewable` entry from `viewable init`, a plugin's board server or
10
+ // a ChatGPT app with the board's tools loaded beside the run's own `glytch`
11
+ // and offered the same tools. Each is switched off for the run and named in
12
+ // one line; a ChatGPT app can only be switched off with all of them.
13
+ const OTHER_BOARD = "a run uses only its own Viewable board";
14
+ const OTHER_BOARD_APP = "one of them is a Viewable board, and a run uses only its own";
15
+ /** Is this server another board server than the run's own: the configured
16
+ * `glytch` that codexBoardArgs points at the run's board? A plugin's or an
17
+ * app's `glytch` is someone else's. */
18
+ const otherBoard = (name, server, tools, { configured = true, env } = {}) =>
19
+ !(configured && name === "glytch") && isBoardServer(name, server, { ...(env ? { env } : {}), ...(tools ? { tools } : {}) });
6
20
 
7
21
  const unreadable = () => new Error("Couldn't read the apps set up in Codex, so this run did not start. Check your apps in Codex, then try again.");
8
22
  // Codex did not answer in time (slow under load, #5271). Not the person's apps.
@@ -114,6 +128,19 @@ function pathPart(value) {
114
128
  return value;
115
129
  }
116
130
 
131
+ // The app's own labels per tool (readOnlyHint, destructiveHint), read from the
132
+ // inventory so an automation's read rule sees what the server says (#6896).
133
+ // Keyed by the tool's key, its name and its resource name; a tool with no
134
+ // labels has no entry.
135
+ function labelsOf(status) {
136
+ const labels = {};
137
+ for (const [key, tool] of Object.entries(status?.tools ?? {})) {
138
+ if (!object(tool?.annotations)) continue;
139
+ for (const name of [key, tool.name, tool._meta?.resource_name]) if (typeof name === "string" && name) labels[name] = tool.annotations;
140
+ }
141
+ return labels;
142
+ }
143
+
117
144
  // Built-in app provenance comes from the app-server's own tool metadata,
118
145
  // never a server-name exception. Store only IDs/names, not link credentials.
119
146
  function appTools(status) {
@@ -137,7 +164,9 @@ function notice(source, reason) {
137
164
  // A source is never merely omitted from verification: apply its OFF policy
138
165
  // and check the resulting process before a turn. Unknown built-in provenance
139
166
  // can only be isolated at the built-in apps transport, as with the OFF switch.
140
- function disableSource(plan, source, reason) {
167
+ // A configured server's OFF keeps its endpoint (endpointArgs): an OFF with no
168
+ // url is the policy-only override Codex 0.165 rejects (#3269, #7529).
169
+ function disableSource(plan, source, reason, servers = {}) {
141
170
  const affected = source.kind === "apps" ? plan.sources.filter((entry) => entry.kind === "apps") : [source];
142
171
  for (const entry of affected) {
143
172
  if (!entry.enabled) continue;
@@ -145,7 +174,10 @@ function disableSource(plan, source, reason) {
145
174
  if (!plan.notices.includes(notice(entry, reason))) plan.notices.push(notice(entry, reason));
146
175
  }
147
176
  if (source.kind === "apps") plan.args.push("-c", "features.apps=false");
148
- else if (source.kind === "configured") plan.args.push("-c", `mcp_servers.${pathPart(source.name)}.enabled=false`);
177
+ else if (source.kind === "configured") {
178
+ const name = pathPart(source.name);
179
+ plan.args.push(...endpointArgs(name, servers[name]), "-c", `mcp_servers.${name}.enabled=false`);
180
+ }
149
181
  else plan.args.push("-c", `plugins.${pathPart(source.identity)}.mcp_servers.${pathPart(source.name)}.enabled=false`);
150
182
  }
151
183
 
@@ -179,21 +211,36 @@ export async function prepareCodexApps(opts, { on, isDraft }) {
179
211
  if (listed.some((entry) => entry.enabled !== false && !Object.hasOwn(servers, entry.name))) throw unsupported();
180
212
  const tools = Object.fromEntries(Object.entries(servers).map(([name, server]) => [name, Object.keys(server.tools ?? {})]));
181
213
  const plan = {
182
- args: [...sourceArgs, ...appsArgs(Object.entries(servers).map(([name, server]) => ({ ...server, name })), { on: allowed, isDraft, tools })],
214
+ args: [...sourceArgs, ...appsArgs(Object.entries(servers).map(([name, server]) => ({ ...server, name })), { on: allowed, isDraft, tools, env: opts.boardEnv })],
183
215
  sources: [], notices: [],
216
+ // The configured servers this read saw. A folder Codex trusts only at
217
+ // thread/start adds its own servers after it (#7529): verifyCodexApps
218
+ // names those, and the runner reads the apps again.
219
+ seen: Object.keys(servers),
184
220
  };
185
221
  if (!allowed) return plan;
186
222
  plan.args.push("-c", 'approvals_reviewer="user"');
187
223
  const apps = new Map(Object.entries(config.apps ?? {}).filter(([id]) => id !== "_default").map(([id, app]) => [pathPart(id), new Set(Object.keys(app?.tools ?? {}))]));
188
224
  for (const [name, server] of Object.entries(servers)) {
189
225
  const status = inventory.find((entry) => entry.name === name && !entry.pluginId);
190
- plan.sources.push({ name, kind: "configured", identity: "configured", enabled: server.enabled !== false, tools: Object.keys(status?.tools ?? {}) });
226
+ const source = { name, kind: "configured", identity: "configured", enabled: server.enabled !== false, tools: Object.keys(status?.tools ?? {}), annotations: labelsOf(status) };
227
+ plan.sources.push(source);
228
+ // appsArgs already switched it off; say so.
229
+ if (otherBoard(name, server, source.tools.length ? source.tools : undefined, { env: opts.boardEnv })) {
230
+ source.board = true;
231
+ if (source.enabled) { source.enabled = false; plan.notices.push(notice(source, OTHER_BOARD)); }
232
+ }
191
233
  }
192
234
  for (const status of inventory) {
193
235
  const names = Object.keys(status.tools);
194
236
  if (Object.hasOwn(servers, status.name) && !status.pluginId) continue;
195
- const source = { name: status.name, kind: status.pluginId ? "plugin" : "apps", identity: status.pluginId ?? "apps", enabled: true, tools: names };
237
+ const source = { name: status.name, kind: status.pluginId ? "plugin" : "apps", identity: status.pluginId ?? "apps", enabled: true, tools: names, annotations: labelsOf(status) };
196
238
  plan.sources.push(source);
239
+ if (otherBoard(status.name, null, names, { configured: false, env: opts.boardEnv })) {
240
+ source.board = true;
241
+ disableSource(plan, source, status.pluginId ? OTHER_BOARD : OTHER_BOARD_APP);
242
+ continue;
243
+ }
197
244
  if (status.pluginId) {
198
245
  const plugin = pathPart(status.pluginId);
199
246
  const server = pathPart(status.name);
@@ -237,10 +284,18 @@ export async function prepareCodexApps(opts, { on, isDraft }) {
237
284
  // Return a stricter plan when one source cannot be verified. The caller must
238
285
  // reap this process and apply that plan to a new process before any model turn.
239
286
  // Ignored OFF overrides still refuse: an unverified source must never stay on.
240
- export async function verifyCodexApps(rpc, { cwd, threadId, on, isDraft, sources = [] }) {
287
+ // With `seen` (the configured servers the read before the thread saw), a
288
+ // configured server outside it returns `unseen` and nothing else: the plan was
289
+ // built for another config, so the caller reads the apps again and starts a
290
+ // new process, apps on or off (#7529). Without `seen` it is checked as usual.
291
+ export async function verifyCodexApps(rpc, { cwd, threadId, on, isDraft, sources = [], seen, env }) {
241
292
  const allowed = on && !isDraft;
242
293
  try {
243
294
  const config = await readAppsConfig(rpc, cwd);
295
+ if (seen) {
296
+ const unseen = Object.keys(config.mcp_servers).filter((name) => !seen.includes(name) && !(name === "glytch" && !isDraft));
297
+ if (unseen.length) return { args: [], sources: structuredClone(sources), notices: [], unseen };
298
+ }
244
299
  if (!allowed && (config.features?.plugins !== false || config.features?.apps !== false)) throw unreadable();
245
300
  if (allowed && config.approvals_reviewer !== "user") throw unsupported();
246
301
  const prompt = (policy, names = []) => {
@@ -261,10 +316,16 @@ export async function verifyCodexApps(rpc, { cwd, threadId, on, isDraft, sources
261
316
  continue;
262
317
  }
263
318
  if (status.name === "glytch" && kind === "configured" && !isDraft) continue;
319
+ if (otherBoard(status.name, kind === "configured" ? servers[status.name] : null, Object.keys(status.tools), { configured: kind === "configured", env }) && (!source || source.enabled)) {
320
+ source ??= plan.sources[plan.sources.push({ name: status.name, kind, identity, enabled: true, tools: Object.keys(status.tools) }) - 1];
321
+ source.board = true;
322
+ disableSource(plan, source, kind === "apps" ? OTHER_BOARD_APP : OTHER_BOARD, servers);
323
+ continue;
324
+ }
264
325
  if (!source) {
265
326
  source = { name: status.name, kind, identity, enabled: true, tools: Object.keys(status.tools) };
266
327
  plan.sources.push(source);
267
- disableSource(plan, source, "Codex could not check the app in this run");
328
+ disableSource(plan, source, "Codex could not check the app in this run", servers);
268
329
  continue;
269
330
  }
270
331
  if (!source.enabled) {
@@ -290,16 +351,18 @@ export async function verifyCodexApps(rpc, { cwd, threadId, on, isDraft, sources
290
351
  }
291
352
  }
292
353
  if (source.tools.some((name) => !Object.hasOwn(status.tools, name))) {
293
- disableSource(plan, source, "Codex could not find all of its tools in this run");
354
+ disableSource(plan, source, "Codex could not find all of its tools in this run", servers);
294
355
  }
295
- } catch { disableSource(plan, source, "Codex could not check approval for the app"); }
356
+ // The labels this thread reports, not the ones read before it started (#6896).
357
+ source.annotations = labelsOf(status);
358
+ } catch { disableSource(plan, source, "Codex could not check approval for the app", servers); }
296
359
  }
297
360
  for (const source of plan.sources) {
298
361
  if (!source.enabled || (source.name === "glytch" && !isDraft)) continue;
299
362
  const status = inventory.find((entry) => entry.name === source.name);
300
363
  const kind = status?.pluginId ? "plugin" : status && Object.hasOwn(servers, status.name) ? "configured" : "apps";
301
364
  const identity = status?.pluginId ?? kind;
302
- if (!status || kind !== source.kind || identity !== source.identity) disableSource(plan, source, "Codex could not find the app in this run");
365
+ if (!status || kind !== source.kind || identity !== source.identity) disableSource(plan, source, "Codex could not find the app in this run", servers);
303
366
  }
304
367
  // Disabled entries may disappear entirely, but their config must prove OFF.
305
368
  for (const source of sources.filter((entry) => !entry.enabled)) {
@@ -310,16 +373,36 @@ export async function verifyCodexApps(rpc, { cwd, threadId, on, isDraft, sources
310
373
  if (!allowed) throw unreadable();
311
374
  if (sources.some((entry) => entry.name === name) || plan.sources.some((entry) => entry.name === name && entry.kind === "configured")) continue;
312
375
  // Added after discovery: check it like a late inventory entry.
376
+ if (otherBoard(name, server, undefined, { env })) {
377
+ const source = { name, kind: "configured", identity: "configured", enabled: true, tools: [], board: true };
378
+ plan.sources.push(source);
379
+ disableSource(plan, source, OTHER_BOARD, servers);
380
+ continue;
381
+ }
313
382
  try { prompt(server); } catch {
314
383
  const source = { name, kind: "configured", identity: "configured", enabled: true, tools: [] };
315
384
  plan.sources.push(source);
316
- disableSource(plan, source, "Codex could not check approval for the app");
385
+ disableSource(plan, source, "Codex could not check approval for the app", servers);
317
386
  }
318
387
  }
319
388
  return plan;
320
389
  } catch { throw allowed ? unsupported() : unreadable(); }
321
390
  }
322
391
 
392
+ // Codex 0.165 rejects policy-only CLI overrides for workspace-provided
393
+ // servers after account/read ("workspace requirements: invalid data").
394
+ // The same policy succeeds when its override table includes the endpoint.
395
+ // Reassert only the public endpoint; auth headers and tokens stay in their
396
+ // original source. Every override of a configured server starts with this:
397
+ // its prompt or OFF policy in appsArgs, and an OFF from disableSource (#7529).
398
+ function endpointArgs(name, server) {
399
+ if (!server?.environment_id || typeof server.url !== "string") return [];
400
+ let url;
401
+ try { url = new URL(server.url); } catch { throw unsupported(); }
402
+ if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.search || url.hash || secretLike(server.url)) throw unsupported();
403
+ return ["-c", `mcp_servers.${name}.url=${JSON.stringify(server.url)}`];
404
+ }
405
+
323
406
  // What the switch adds to the app server's command line (#481). Off, and in
324
407
  // every draft: each server the person enabled is switched off for this run.
325
408
  // On: each one stays, but every tool call asks first ("prompt" asks even for
@@ -328,29 +411,21 @@ export async function verifyCodexApps(rpc, { cwd, threadId, on, isDraft, sources
328
411
  // draft switches it off too. Codex reads `mcp_servers.<name>` as a dotted
329
412
  // path only when the name is plain (a quoted name makes a new, broken
330
413
  // server), so any other server or tool name refuses the run.
331
- export function appsArgs(servers, { on, isDraft, tools = {} }) {
414
+ export function appsArgs(servers, { on, isDraft, tools = {}, env }) {
332
415
  const args = [];
333
416
  for (const server of servers) {
334
417
  if (server.enabled === false) continue;
335
418
  if (server.name === "glytch" && !isDraft) continue;
336
- const saved = on && Object.hasOwn(tools, server.name) ? tools[server.name] : [];
419
+ // Another board server is switched off with the apps on too (#7550).
420
+ const board = otherBoard(server.name, server, tools[server.name]?.length ? tools[server.name] : undefined, { env });
421
+ const saved = on && !board && Object.hasOwn(tools, server.name) ? tools[server.name] : [];
337
422
  const names = [server.name, ...saved];
338
423
  const odd = names.find((name) => !/^[A-Za-z0-9_-]+$/.test(name));
339
424
  if (odd !== undefined) {
340
425
  throw new Error(`An app set up in Codex has a name this run can't switch off safely (${JSON.stringify(odd)}). Rename it in your Codex config, then try again.`);
341
426
  }
342
- // Codex 0.165 rejects policy-only CLI overrides for workspace-provided
343
- // servers after account/read ("workspace requirements: invalid data").
344
- // The same policy succeeds when its override table includes the endpoint.
345
- // Reassert only the public endpoint; auth headers and tokens stay in their
346
- // original source. Keep the same prompt/OFF policy below.
347
- if (server.environment_id && typeof server.url === "string") {
348
- let url;
349
- try { url = new URL(server.url); } catch { throw unsupported(); }
350
- if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.search || url.hash || secretLike(server.url)) throw unsupported();
351
- args.push("-c", `mcp_servers.${server.name}.url=${JSON.stringify(server.url)}`);
352
- }
353
- if (!on || isDraft) { args.push("-c", `mcp_servers.${server.name}.enabled=false`); continue; }
427
+ args.push(...endpointArgs(server.name, server));
428
+ if (!on || isDraft || board) { args.push("-c", `mcp_servers.${server.name}.enabled=false`); continue; }
354
429
  args.push("-c", `mcp_servers.${server.name}.default_tools_approval_mode="prompt"`);
355
430
  for (const tool of saved) args.push("-c", `mcp_servers.${server.name}.tools.${tool}.approval_mode="prompt"`);
356
431
  }