viewable-one 0.12.6 → 0.12.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/child.mjs CHANGED
@@ -19,6 +19,7 @@ import { createGzip, constants as zlibConstants } from "node:zlib";
19
19
  import { join } from "node:path";
20
20
 
21
21
  import { killTree } from "./kill.mjs";
22
+ import { reapGroup, signalGroup } from "./groupStop.mjs";
22
23
  import { makeAnswerTracker } from "./answerTag.mjs";
23
24
  import { RUNNER_BEAT_MS } from "./spawn.mjs";
24
25
  import { DELIVERED, SKIP, STOP, watchAnswers, watchReplyFiles } from "./followUps.mjs";
@@ -328,6 +329,9 @@ export function attachChild(child, {
328
329
  onChunk,
329
330
  stopCheck,
330
331
  killProcessGroup = false,
332
+ // Pids a group stop must spare: the preview server the session recorded
333
+ // (ruling A). Read at kill time, so a record written late still counts.
334
+ keepPids,
331
335
  flushFinalLine = false,
332
336
  // What the wall clock means for this child. The one-shot answer is "out of
333
337
  // time"; the streaming answer is "out of time ONLY if the turn is still
@@ -562,15 +566,16 @@ export function attachChild(child, {
562
566
 
563
567
  let killTimer;
564
568
  let killing = false;
569
+ let killedAt = 0;
565
570
  /** The one kill path: SIGTERM, then SIGKILL after the grace. A child that
566
571
  * ignores SIGTERM is still billing.
567
572
  *
568
- * IT IS THE CHILD'S PID AND NOT ITS PROCESS GROUP, and since 2026-09-06
569
- * that is load-bearing rather than incidental. `child.kill(sig)` signals
570
- * one pid; `process.kill(-pgid, sig)` would signal everything the child
571
- * started. Recovery-tracked agents now have a private group, but ordinary
572
- * callers can still share the runner's group. Normal agent shutdown
573
- * remains a single-PID signal; orphan recovery verifies members separately.
573
+ * WITHOUT A PRIVATE GROUP IT IS THE CHILD'S PID, NOT ITS PROCESS GROUP, and
574
+ * since 2026-09-06 that is load-bearing rather than incidental.
575
+ * `child.kill(sig)` signals one pid; `process.kill(-pgid, sig)` would signal
576
+ * everything in the group, which for a caller that shares the runner's
577
+ * group includes the runner. A child that leads its own group (see the
578
+ * #6557 paragraph below) is signalled as a group instead.
574
579
  *
575
580
  * Ruling A that day is what makes the distinction matter: a session
576
581
  * with the Browser switch on starts its dev server detached so the browser
@@ -587,15 +592,26 @@ export function attachChild(child, {
587
592
  * agent as a grandchild that survives and keeps billing. `killTree` sends
588
593
  * `taskkill /pid <pid> /t` and then `/t /f` there. The POSIX call it makes
589
594
  * is `child.kill(sig)`, this closure's own, so the paragraph above still
590
- * describes exactly what happens on his Mac. Package checks alone opt into
591
- * killProcessGroup: runChild gives them their OWN group, with no preview
592
- * intended to survive. Agent sessions never enable it. */
595
+ * describes exactly what happens on his Mac.
596
+ *
597
+ * A CHILD WITH ITS OWN GROUP IS STOPPED AS A GROUP (#6557). Package checks
598
+ * and every recovery-tracked agent (streaming, one-shot, ACP, Codex) start
599
+ * `detached`, so the child leads a private process group. Stop, the wall
600
+ * clock and the stall watchdog then signal that group, and `settle` waits
601
+ * until it is empty before it resolves: an ordinary background command the
602
+ * agent left running (`cmd > log &`) ends with the agent, and the runner
603
+ * deletes its recovery record only after that is true. The preview server
604
+ * the session recorded in `.viewable-server.json` is spared by pid (see
605
+ * groupStop.mjs): on macOS `nohup cmd & disown` keeps the agent's group, so
606
+ * the group alone cannot tell it from an ordinary background command. */
593
607
  const kill = () => {
594
608
  if (state.settled || killing) return;
595
609
  killing = true;
610
+ killedAt = Date.now();
596
611
  try { onKill(); } catch { /* cleanup must not prevent termination */ }
597
- const send = (force) =>
598
- killTree(child.pid, { force, signal: (_pid, sig) => killProcessGroup ? process.kill(-child.pid, sig) : child.kill(sig) }).catch(() => {
612
+ const send = (force) => (killProcessGroup
613
+ ? signalGroup(child.pid, force ? "SIGKILL" : "SIGTERM", { keep: keepPids })
614
+ : killTree(child.pid, { force, signal: (_pid, sig) => child.kill(sig) })).catch(() => {
599
615
  /* a child that is already gone is not an error here */
600
616
  });
601
617
  killTimer = setTimeout(() => send(true), killGraceMs);
@@ -632,17 +648,14 @@ export function attachChild(child, {
632
648
  state.settled = true;
633
649
  clearTimeout(wallTimer);
634
650
  clearTimeout(killTimer);
635
- if (killProcessGroup && (state.timedOut || state.stoppedByUser)) {
636
- // The npm parent may close before a script that ignored SIGTERM.
637
- try { process.kill(-child.pid, "SIGKILL"); } catch { /* group already gone */ }
638
- }
639
651
  for (const timer of timers) clearInterval(timer);
640
652
  // Flush and close the gzip trailer so the file on disk is complete and
641
653
  // valid gzip, whichever way this child ended - and only THEN resolve,
642
654
  // so whoever reads the transcript next finds the whole of it (see
643
655
  // openTranscriptSink's close()).
644
- const finish = () => resolve({
656
+ const finish = (survivors) => resolve({
645
657
  ...result,
658
+ ...(survivors?.length ? { descendantsRemain: survivors } : {}),
646
659
  log: ring.text(),
647
660
  stderr: errTail.trim(),
648
661
  truncated: ring.dropped > 0,
@@ -658,8 +671,16 @@ export function attachChild(child, {
658
671
  ...extraFields(state),
659
672
  });
660
673
  const closed = transcriptSink?.close();
661
- if (closed && typeof closed.then === "function") closed.then(finish, finish);
662
- else finish();
674
+ const flushed = closed && typeof closed.then === "function" ? closed.then(() => {}, () => {}) : null;
675
+ if (!(killing && killProcessGroup)) {
676
+ if (flushed) flushed.then(() => finish());
677
+ else finish();
678
+ return;
679
+ }
680
+ // Resolve only when the transcript is whole AND nothing the child started
681
+ // is left in its group (#6557).
682
+ Promise.all([flushed, reapGroup(child.pid, killedAt + killGraceMs, { keep: keepPids })])
683
+ .then(([, left]) => finish(left), () => finish([child.pid]));
663
684
  };
664
685
 
665
686
  child.on("error", (error) => settle({ ok: false, spawnError: error.message }));
@@ -689,7 +710,9 @@ export function attachChild(child, {
689
710
  * The wall clock is not a progress protocol and does not put a third state on
690
711
  * the board. It is the one bound between "a session hung" and "a session
691
712
  * billed all night". */
692
- 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, claudeResult = false }) {
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
+ // A private group is a group that is signalled: one flag, not two (#6557).
715
+ const ownGroup = (killProcessGroup || recoveryGroup) && platform !== "win32";
693
716
  return new Promise((resolve) => {
694
717
  let child;
695
718
  try {
@@ -702,7 +725,7 @@ export function runChild({ bin, args, cwd, env, input, recoveryGroup = false, on
702
725
  // `windowsHide: true` is harmless on POSIX (detect.mjs's execProbe has
703
726
  // carried it unconditionally since before this brief) and stops a
704
727
  // console window flashing per session on Windows.
705
- child = spawn(resolved.file, resolved.args, { cwd, env, stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"], shell: resolved.shell, windowsHide: true, detached: (killProcessGroup || recoveryGroup) && platform !== "win32" });
728
+ child = spawn(resolved.file, resolved.args, { cwd, env, stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"], shell: resolved.shell, windowsHide: true, detached: ownGroup });
706
729
  } catch (error) {
707
730
  resolve({ ok: false, spawnError: error instanceof Error ? error.message : String(error), log: "" });
708
731
  return;
@@ -725,7 +748,8 @@ export function runChild({ bin, args, cwd, env, input, recoveryGroup = false, on
725
748
  onChunk,
726
749
  stopCheck,
727
750
  stopPollMs,
728
- killProcessGroup: killProcessGroup && platform !== "win32",
751
+ killProcessGroup: ownGroup,
752
+ keepPids,
729
753
  transcriptDir,
730
754
  flushFinalLine: claudeResult,
731
755
  ...(claudeResult ? { onEvent: observeClaudeModel(args, { ...process.env, ...env }) } : {}),
@@ -809,7 +833,9 @@ export function runChild({ bin, args, cwd, env, input, recoveryGroup = false, on
809
833
  * whole new resume request - the watch loop's 5s poll, the app's receipt, the
810
834
  * worktree, and a cold `claude --resume`. That is tens of seconds and it is a
811
835
  * design decision, not a constant. */
812
- 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 }) {
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 }) {
837
+ // Its private group is signalled on Stop and timeout, not just created (#6557).
838
+ const ownGroup = recoveryGroup && platform !== "win32";
813
839
  return new Promise((resolve) => {
814
840
  try { imageAttachments(images); } catch (error) { resolve({ ok: false, log: "", spawnError: error.message }); return; }
815
841
  let child;
@@ -818,7 +844,7 @@ export function runStreamingChild({ bin, args, cwd, env, recoveryGroup = false,
818
844
  // AND opencode per ruling 5B) - streaming is the path a persistent
819
845
  // Claude Code session takes.
820
846
  const resolved = runnableCommand(bin, args, { platform, env });
821
- child = spawn(resolved.file, resolved.args, { cwd, env, stdio: ["pipe", "pipe", "pipe"], shell: resolved.shell, windowsHide: true, detached: recoveryGroup && platform !== "win32" });
847
+ child = spawn(resolved.file, resolved.args, { cwd, env, stdio: ["pipe", "pipe", "pipe"], shell: resolved.shell, windowsHide: true, detached: ownGroup });
822
848
  } catch (error) {
823
849
  resolve({ ok: false, spawnError: error instanceof Error ? error.message : String(error), log: "" });
824
850
  return;
@@ -842,6 +868,8 @@ export function runStreamingChild({ bin, args, cwd, env, recoveryGroup = false,
842
868
  stopCheck,
843
869
  stopPollMs,
844
870
  transcriptDir,
871
+ killProcessGroup: ownGroup,
872
+ keepPids,
845
873
  // THE WALL CLOCK MEANS SOMETHING ELSE HERE. Closing an IDLE child is
846
874
  // the reply window ending, not a timeout: the work finished when the
847
875
  // envelope landed. Only a child still mid-turn - no envelope since the
package/lib/codex.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import { writeRisk, riskReason } from "./writePolicy.mjs";
2
+ import { automationReadWords } 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";
@@ -252,7 +253,7 @@ function protocolQuestions(method, params) {
252
253
  // The tool's inputs come with it, short and with secrets hidden (#608).
253
254
  const details = toolInputsText(params);
254
255
  questions.push({ question: `${params.serverName}: ${params.message}`, options: ["Allow", "Not this"],
255
- why: `On your computer, ${params.serverName}\n${riskReason(writeRisk(params.serverName.toLowerCase(), params.message, params._meta?.tool_params) ?? "open-ended")}\n${details ? `${details}\n\n` : ""}This answer applies only to this request.` });
256
+ why: `On your computer, ${params.serverName}\n${riskReason(writeRisk(null, params.message, params._meta?.tool_params) ?? "open-ended")}\n${details ? `${details}\n\n` : ""}This answer applies only to this request.` });
256
257
  return { questions };
257
258
  }
258
259
 
@@ -335,6 +336,8 @@ function runCodexAttempt(opts, apps) {
335
336
  let finishTimer;
336
337
  let lastAssistantText = "";
337
338
  const opened = new Map();
339
+ let verifiedApps = null; // the apps as the running thread reports them; null until checked
340
+ const mcpCalls = new Map(); // item id -> Codex's own mcpToolCall item, for an approval that names only the item
338
341
  const closed = new Set();
339
342
  const messages = agentMessageAssembler();
340
343
  const emit = (event) => { if (!handle.settled()) translated.write(`${JSON.stringify({ ...event, session_id: threadId })}\n`); };
@@ -343,6 +346,8 @@ function runCodexAttempt(opts, apps) {
343
346
  kill: (signal) => child.kill(signal), on(event, fn) { child.on(event, fn); return facade; } };
344
347
  const handle = attachChild(facade, {
345
348
  ...opts,
349
+ // The app-server leads its own group when recovery-tracked (#6557).
350
+ killProcessGroup: opts.recoveryGroup === true && (opts.platform ?? process.platform) !== "win32",
346
351
  onSession: undefined, // The native thread/start path awaits this callback before prompting.
347
352
  resolve: (outcome) => { clearTimeout(finishTimer); abortQuestions(); rpc?.close(); resolve({ ...outcome, ...(appsRetry ? { appsRetry } : {}) }); },
348
353
  // Latch admission closed BEFORE SIGTERM. A still-running child may
@@ -390,7 +395,7 @@ function runCodexAttempt(opts, apps) {
390
395
  const toolStart = (item) => {
391
396
  if (closed.has(item.id)) return;
392
397
  let name; let input;
393
- if (item.type === "mcpToolCall") { name = `mcp__${item.server}__${item.tool}`; input = item.arguments; }
398
+ if (item.type === "mcpToolCall") { name = `mcp__${item.server}__${item.tool}`; input = item.arguments; mcpCalls.set(item.id, item); }
394
399
  else if (item.type === "commandExecution") { name = "Bash"; input = { command: item.command }; }
395
400
  else if (item.type === "fileChange") { name = "Edit"; input = { changes: item.changes }; }
396
401
  else return;
@@ -408,6 +413,29 @@ function runCodexAttempt(opts, apps) {
408
413
  opened.set(item.id, snapshot);
409
414
  assistant([{ type: "tool_use", id: item.id, name, input }]);
410
415
  };
416
+ // The app, tool and arguments an app approval is for, or null when they cannot
417
+ // be read reliably. Elicitation: the tool is `_meta.tool_name` (the field
418
+ // Codex's own reviewer reads), the arguments `_meta.tool_params`. Legacy input
419
+ // request: Codex's own started item (same item id) holds the server, tool and
420
+ // arguments. Never from the approval's words, which can quote an argument (#6955).
421
+ const calledApp = (method, params, question) => {
422
+ if (method === ELICITATION) {
423
+ const named = params._meta?.tool_name;
424
+ const tool = question.id === undefined && typeof named === "string" && named !== "" ? named : undefined;
425
+ const input = params._meta?.tool_params;
426
+ // Only a real tool approval (its marker, and its arguments as an object) can skip the ask.
427
+ // Codex marks a call it calls sensitive: that one asks.
428
+ if (!tool || params._meta?.codex_approval_kind !== "mcp_tool_call" || !object(input) || params._meta?.codex_sensitive_action === true) return null;
429
+ return { app: params.serverName, tool, input };
430
+ }
431
+ const item = mcpCalls.get(params.itemId);
432
+ return item && object(item.arguments ?? {}) ? { app: item.server, tool: item.tool, input: item.arguments ?? {} } : null;
433
+ };
434
+ const automationRead = ({ app, tool, input }) => {
435
+ // The labels of the thread that is running, read when it started (verifyCodexApps), never the earlier ones.
436
+ const source = verifiedApps?.find((entry) => entry.enabled && entry.name === app);
437
+ return source?.tools?.includes(tool) === true && opts.askPermission.appRead?.(app, tool, input, source.annotations?.[tool]) === true;
438
+ };
411
439
  rpc = codexRpc(child, {
412
440
  timeoutMs: opts.rpcTimeoutMs ?? 15_000,
413
441
  async onRequest(method, params, requestId) {
@@ -441,6 +469,17 @@ function runCodexAttempt(opts, apps) {
441
469
  if (controller.signal.aborted || approvalsClosed() || resolvedRequests.has(requestId) || !identityMatches()) return cancelled;
442
470
  const appApproval = question.id?.startsWith("mcp_tool_call_approval") ||
443
471
  (method === ELICITATION && question.id === undefined && question.options.includes("Allow"));
472
+ // An automation's read of an app is allowed by the automation itself (#5495, #6896):
473
+ // the same rule the server runs, with the app's own labels from the inventory.
474
+ // An approval that names no tool, or one with no arguments to read, keeps asking.
475
+ const called = appApproval ? calledApp(method, params, question) : null;
476
+ if (called && automationRead(called)) {
477
+ opts.log?.(`permission: ${called.tool} is a read in an automation, no question filed (#5495)`);
478
+ // The run's card says the automation was the yes, as a refusal says its no (#6955).
479
+ emit({ type: "system", subtype: "permission", decision: "allowed", automation: true, message: automationReadWords(called.app, called.tool) });
480
+ answers.push("Allow");
481
+ continue;
482
+ }
444
483
  const hostedQuestion = { ...question, options: [...question.options, CANCEL],
445
484
  recommendation: appApproval
446
485
  ? { answer: "Allow", why: "It lets this run carry on with what you asked." }
@@ -721,6 +760,7 @@ function runCodexAttempt(opts, apps) {
721
760
  finish("Checking apps again with the unverified apps turned off.");
722
761
  return;
723
762
  }
763
+ verifiedApps = checkedApps.sources;
724
764
  for (const message of apps.notices) emit({ type: "system", subtype: "info", message });
725
765
  emit({ type: "system", subtype: "init", model: thread.model ?? config.model, effort: thread.reasoningEffort ?? config.effort, engine: "codex" });
726
766
  emit({ type: "system", subtype: "info", message: planWindowInfoMessage(planWindow) });
package/lib/codexApps.mjs CHANGED
@@ -114,6 +114,19 @@ function pathPart(value) {
114
114
  return value;
115
115
  }
116
116
 
117
+ // The app's own labels per tool (readOnlyHint, destructiveHint), read from the
118
+ // inventory so an automation's read rule sees what the server says (#6896).
119
+ // Keyed by the tool's key, its name and its resource name; a tool with no
120
+ // labels has no entry.
121
+ function labelsOf(status) {
122
+ const labels = {};
123
+ for (const [key, tool] of Object.entries(status?.tools ?? {})) {
124
+ if (!object(tool?.annotations)) continue;
125
+ for (const name of [key, tool.name, tool._meta?.resource_name]) if (typeof name === "string" && name) labels[name] = tool.annotations;
126
+ }
127
+ return labels;
128
+ }
129
+
117
130
  // Built-in app provenance comes from the app-server's own tool metadata,
118
131
  // never a server-name exception. Store only IDs/names, not link credentials.
119
132
  function appTools(status) {
@@ -187,12 +200,12 @@ export async function prepareCodexApps(opts, { on, isDraft }) {
187
200
  const apps = new Map(Object.entries(config.apps ?? {}).filter(([id]) => id !== "_default").map(([id, app]) => [pathPart(id), new Set(Object.keys(app?.tools ?? {}))]));
188
201
  for (const [name, server] of Object.entries(servers)) {
189
202
  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 ?? {}) });
203
+ plan.sources.push({ name, kind: "configured", identity: "configured", enabled: server.enabled !== false, tools: Object.keys(status?.tools ?? {}), annotations: labelsOf(status) });
191
204
  }
192
205
  for (const status of inventory) {
193
206
  const names = Object.keys(status.tools);
194
207
  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 };
208
+ const source = { name: status.name, kind: status.pluginId ? "plugin" : "apps", identity: status.pluginId ?? "apps", enabled: true, tools: names, annotations: labelsOf(status) };
196
209
  plan.sources.push(source);
197
210
  if (status.pluginId) {
198
211
  const plugin = pathPart(status.pluginId);
@@ -292,6 +305,8 @@ export async function verifyCodexApps(rpc, { cwd, threadId, on, isDraft, sources
292
305
  if (source.tools.some((name) => !Object.hasOwn(status.tools, name))) {
293
306
  disableSource(plan, source, "Codex could not find all of its tools in this run");
294
307
  }
308
+ // The labels this thread reports, not the ones read before it started (#6896).
309
+ source.annotations = labelsOf(status);
295
310
  } catch { disableSource(plan, source, "Codex could not check approval for the app"); }
296
311
  }
297
312
  for (const source of plan.sources) {
@@ -22,6 +22,9 @@
22
22
  // breaks read as spaces, and any punctuation or symbol shows (a colon, an
23
23
  // ampersand, a bracket, an arrow, a percent sign), except = { } and a backslash, which
24
24
  // carry form, JSON and escaped data. A year (1900 to 2099) is not a code.
25
+ // A title or a name (NAME_FIELDS, also the title found inside a nested item)
26
+ // shows up to 6 digits in all ("Invoice 4521"; a phone number does not) unless it holds the word
27
+ // "code", a credential word, or nothing but a number (#5436).
25
28
  // Every other test is the same: a credential word, a labelled or token-shaped
26
29
  // value, an opaque run or a long run of digits still hides.
27
30
  // Booleans and null show as themselves; a number shows when it has at most
@@ -87,6 +90,13 @@ const DIGIT_RUN = /\d{4,}/;
87
90
  const YEAR = /(?<!\d)(?:19|20)\d{2}(?!\d)/g;
88
91
  // The fields that hold what a person wrote to be read (#4363).
89
92
  const PROSE_FIELDS = new Set(["title", "description", "subject", "body", "content", "markdown", "reason"]);
93
+ // A title or a name is a label a person types to read back ("Invoice 4521",
94
+ // "Room 1204", #5436): a number of up to 6 digits in all shows there when the text has
95
+ // words and no credential word. A longer run, a number alone, "code" or any
96
+ // credential word still hides. Other fields keep the 4-digit rule.
97
+ const NAME_FIELDS = new Set(["title", "name", "subject", "summary", "heading"]);
98
+ const digitCount = (text) => (text.match(/\d/g) ?? []).length;
99
+ const CODE_WORD = /(?<![A-Za-z])codes?(?![A-Za-z])/i;
90
100
 
91
101
  const MAX_INPUTS = 12;
92
102
  const MAX_VALUE = 80;
@@ -103,29 +113,39 @@ const count = (n, one, many) => `${n} ${n === 1 ? one : many}`;
103
113
  // code, and its markdown marks and line breaks read as plain words.
104
114
  const proseWords = (text) => text.replace(/[*`]+/g, "").replace(/\s+/g, " ").trim();
105
115
  // Length is checked first, so the patterns only ever scan 80 characters.
106
- const plainText = (text, prose = false) => text.length <= MAX_VALUE && (prose ? PROSE_CHARS : PLAIN_CHARS).test(text)
107
- && !DIGIT_RUN.test(prose ? text.replace(YEAR, "") : text) && !valueMentionsSecret(text)
116
+ // "code" as a word, camelCase split first ("loginCode 4521").
117
+ const codeWord = (text) => CODE_WORD.test(text.replace(/([a-z])([A-Z])/g, "$1 $2"));
118
+ const digitsHide = (text, prose, label) => {
119
+ const rest = prose ? text.replace(YEAR, "") : text;
120
+ if (!label) return DIGIT_RUN.test(rest);
121
+ // "each": every title of a list was checked alone (madeRows), so the digits of one never add to another's.
122
+ if (label === "each") return false;
123
+ // Every digit counts, a year too: "2026 123456" is ten digits.
124
+ return digitCount(text) > 6 || (DIGIT_RUN.test(rest) && (codeWord(rest) || !/\p{L}/u.test(rest)));
125
+ };
126
+ const plainText = (text, prose = false, label = false) => text.length <= MAX_VALUE && (prose ? PROSE_CHARS : PLAIN_CHARS).test(text)
127
+ && !digitsHide(text, prose, label) && !valueMentionsSecret(text)
108
128
  && !secretLike(text) && !opaque(text);
109
129
 
110
130
  // The text to show, or null when it must be hidden. A long text shows its
111
131
  // start, cut at a word, and only that start is tested, so the patterns scan
112
132
  // at most 81 characters whatever the size. No word break in the first 80
113
133
  // characters (one long run) stays hidden.
114
- function plainStart(text, prose = false) {
115
- if (text.length <= MAX_VALUE) return plainText(text, prose) ? text.trim() : null;
134
+ function plainStart(text, prose = false, label = false) {
135
+ if (text.length <= MAX_VALUE) return plainText(text, prose, label) ? text.trim() : null;
116
136
  const head = text.slice(0, MAX_VALUE + 1);
117
137
  const cut = head.lastIndexOf(" ");
118
138
  const start = cut > 0 ? head.slice(0, cut).trim() : "";
119
- return start && plainText(start, prose) ? `${start}…` : null;
139
+ return start && plainText(start, prose, label) ? `${start}…` : null;
120
140
  }
121
141
 
122
- function valueText(value, prose = false) {
142
+ function valueText(value, prose = false, label = false) {
123
143
  if (value === null || typeof value === "boolean") return String(value);
124
144
  // At most 3 digits before the point: 49.99 shows, a 4-digit PIN does not.
125
145
  if (typeof value === "number") return Number.isFinite(value) && Math.abs(value) < 1000 ? String(value) : HIDDEN;
126
146
  if (typeof value === "string") {
127
147
  if (value.trim() === "") return "(empty)";
128
- const start = prose ? plainStart(proseWords(value), true) : plainStart(value);
148
+ const start = prose ? plainStart(proseWords(value), true, label) : plainStart(value, false, label);
129
149
  return start ?? `${HIDDEN}, ${count(value.length, "character", "characters")}`;
130
150
  }
131
151
  // Nested values are summarised by size, never opened: a secret one level
@@ -189,9 +209,95 @@ function shownValue(name, value, names) {
189
209
  const named = Object.hasOwn(names ?? {}, name) && typeof names[name] === "string" ? plainStart(proseWords(names[name]), true) : null;
190
210
  if (named) return named;
191
211
  if (typeof value === "string" && UUID.test(value)) return value;
192
- return valueText(value, PROSE_FIELDS.has(name));
212
+ return valueText(value, PROSE_FIELDS.has(name), NAME_FIELDS.has(nameLetters(name)));
193
213
  }
194
214
 
215
+ // WHAT A NESTED ARGUMENT WILL MAKE (#5401). A page batch ("pages": [{
216
+ // properties: { title }, content }]) read "pages: 1 item": it named no page
217
+ // and never said what the page holds. The words a person reads are found by
218
+ // the fields' names, never by the app (#4419): the title and the start of the
219
+ // text of the items inside, at most three levels down, through the same
220
+ // filter as any text. A field named like a credential is never opened.
221
+ const TITLE_KEYS = new Set(["title", "name", "subject", "summary", "heading"]);
222
+ const TEXT_KEYS = new Set(["content", "markdown", "body", "text", "description"]);
223
+ // Deep enough for a title kept as rich text (Notion's API: properties.title
224
+ // [0].text.content); the walk opens at most WALK_NODES values in all.
225
+ const NESTED_DEPTH = 4;
226
+ const WALK_NODES = 200;
227
+ function firstText(value, keys, depth = 0, budget = { left: WALK_NODES }) {
228
+ if (depth > NESTED_DEPTH || value === null || typeof value !== "object" || --budget.left < 0) return undefined;
229
+ const entries = Array.isArray(value) ? value.slice(0, MAX_INPUTS).map((inner) => ["", inner]) : Object.entries(value).slice(0, MAX_INPUTS);
230
+ // The text of an item is never its title's own rich text.
231
+ const open = entries.filter(([key]) => !mentionsSecret(key) && !(keys === TEXT_KEYS && TITLE_KEYS.has(nameLetters(key))));
232
+ for (const [key, inner] of open) {
233
+ if (!keys.has(nameLetters(key))) continue;
234
+ if (typeof inner === "string" && inner.trim()) return inner;
235
+ const rich = richText(inner, depth + 1, budget);
236
+ if (rich !== undefined) return rich;
237
+ }
238
+ for (const [, inner] of open) {
239
+ const found = firstText(inner, keys, depth + 1, budget);
240
+ if (found !== undefined) return found;
241
+ }
242
+ return undefined;
243
+ }
244
+
245
+ /** Every text fragment of a rich text, joined before it is cut: a title kept
246
+ * as ["Launch ", "notes"] reads "Launch notes", never "Launch". Stops once
247
+ * there is more than the card shows. */
248
+ function richText(value, depth, budget, parts = []) {
249
+ if (depth > NESTED_DEPTH || value === null || typeof value !== "object" || --budget.left < 0) return undefined;
250
+ const entries = Array.isArray(value) ? value.slice(0, MAX_INPUTS).map((inner) => ["", inner]) : Object.entries(value).slice(0, MAX_INPUTS);
251
+ for (const [key, inner] of entries) {
252
+ if (parts.join("").length > MAX_VALUE) break;
253
+ if (mentionsSecret(key)) continue;
254
+ if (typeof inner === "string") { if (TEXT_KEYS.has(nameLetters(key))) parts.push(inner); }
255
+ else richText(inner, depth + 1, budget, parts);
256
+ }
257
+ const text = parts.join("");
258
+ return text.trim() ? text : undefined;
259
+ }
260
+
261
+ /** Title and Adds rows for an argument holding the items a write makes, or
262
+ * [] when nothing in it reads as one. Several items name their titles. */
263
+ function madeRows(value) {
264
+ const items = (Array.isArray(value) ? value : [value]).filter(record);
265
+ if (!items.length) return [];
266
+ const titles = items.map((item) => firstText(item, TITLE_KEYS)).filter((title) => title !== undefined);
267
+ const text = items.length === 1 ? firstText(items[0], TEXT_KEYS) : undefined;
268
+ const rows = [];
269
+ // Items with no title of their own still count: two pages, one titled, never read as one.
270
+ const rest = items.length - titles.length;
271
+ const more = titles.length && rest > 0 ? ` and ${rest} more` : "";
272
+ if (titles.length === 1) rows.push({ line: `Title: ${valueText(titles[0], true, true)}${more}` });
273
+ else if (titles.length > 1) {
274
+ // Each title is judged alone for its digits: "123456" next to "Meeting"
275
+ // stays hidden, "Part 123" next to "Part 456" stays readable. A hidden one
276
+ // is counted, never written as a word a real title could also be.
277
+ const visible = titles.map(proseWords).filter((title) => plainStart(title, true, true) !== null);
278
+ const hiddenCount = titles.length - visible.length;
279
+ const joined = visible.join(", ");
280
+ const shown = visible.length ? valueText(joined, true, "each") : HIDDEN;
281
+ // A list cut short or hidden says how many there are in all.
282
+ const cut = shown !== joined;
283
+ const hiddenNote = visible.length && hiddenCount ? `, ${hiddenCount} hidden` : "";
284
+ rows.push({ line: `Titles: ${shown}${hiddenNote}${cut ? ` (${items.length} in all)` : more}` });
285
+ }
286
+ if (text !== undefined) rows.push({ line: `Adds: ${valueText(text, true)}` });
287
+ return rows;
288
+ }
289
+
290
+ // "page_ids" reads "Pages", "parentPages" reads "Parent pages". The same
291
+ // words as plainLabel in src/integrations/writeResults.ts, which src cannot
292
+ // import from here: keep the two together.
293
+ const spoken = (name) => {
294
+ const text = name.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/[_.-]+/g, " ").trim().toLowerCase().replace(/ ids$/, "s");
295
+ return text.charAt(0).toUpperCase() + text.slice(1);
296
+ };
297
+ // A flag the model sets to say the person agreed ("user_confirmed"). A bare
298
+ // "confirm" is left alone: on Stripe it is the app's own "charge now".
299
+ const CONFIRM_FLAG = /^userconfirm(?:ed|ation)?$/;
300
+
195
301
  /** Approval-card rows, using the same secret filter as the computer asker.
196
302
  * `tool` is the app's tool name; a Stripe amount reads "Refund" only on a
197
303
  * refund tool (or when the tool is not known). `names` maps an argument to the
@@ -200,16 +306,31 @@ function shownValue(name, value, names) {
200
306
  * instead of "hidden, 36 characters". */
201
307
  export function appInputsText(provider, inputs = {}, tool = "refund", names = {}) {
202
308
  if (!record(inputs)) return toolInputsText({ _meta: { tool_params: inputs } });
203
- const labels = { team: "Team", title: "Title", description: "Description", priority: "Priority", page_id: "Page", page: "Page", parent: "Page", content: "Adds", markdown: "Adds", body: "Comment", owner: "Owner", repo: "Repository", issue_number: "Issue", pullNumber: "Pull request", customer: "Customer", payment_intent: "Payment", charge: "Payment", reason: "Reason", currency: "Currency", to: "To", subject: "Subject" };
309
+ const labels = { team: "Team", title: "Title", description: "Description", priority: "Priority", page_id: "Page", page: "Page", parent: "Page", content: "Adds", markdown: "Adds", body: "Comment", owner: "Owner", repo: "Repository", issue_number: "Issue", pullNumber: "Pull request", customer: "Customer", payment_intent: "Payment", charge: "Payment", reason: "Reason", currency: "Currency", to: "To", subject: "Subject", id: "Item" };
310
+ let named = Object.entries(inputs).some(([name, value]) => (labels[name] === "Title" || labels[name] === "Adds") && !placeholder(value));
204
311
  const money = (name, value) => provider === "stripe" && name === "amount" && Number.isSafeInteger(value) && value >= 0 && value <= 99999999;
205
312
  const rows = Object.entries(inputs).slice(0, MAX_INPUTS).flatMap(([name, value]) => {
206
313
  // An empty value tells the person nothing; a field with content always shows, as a count if nested (#4363).
207
314
  if (placeholder(value)) return [];
315
+ // "User confirmed: true" is a developer flag: Allow is the person's confirmation (#6453).
316
+ if (typeof value === "boolean" && CONFIRM_FLAG.test(nameLetters(name))) return [];
208
317
  if (money(name, value)) return [{ line: `${/refund/i.test(tool) ? "Refund" : "Amount"}: ${moneyText(value, inputs.currency)}` }];
209
318
  // The currency is already in the amount.
210
319
  if (provider === "stripe" && name === "currency" && money("amount", inputs.amount) && /^[a-z]{3}$/i.test(String(value))) return [];
320
+ // A list or object the caller found names for (the pages a delete acts on)
321
+ // reads as the item the call acts on: a capital label keeps it on the line
322
+ // under the question instead of under Details (#6453).
323
+ const label = Object.hasOwn(labels, name) ? labels[name]
324
+ : typeof value === "object" && Object.hasOwn(names ?? {}, name) && plainName(name) ? spoken(name) : undefined;
325
+ // Items under a name the card has no word for say what they make
326
+ // instead of how many there are (#5401): once per call, and never over a
327
+ // title or text the call already gives.
328
+ const made = !named && label === undefined && !mentionsSecret(name) && typeof value === "object" ? madeRows(value) : [];
329
+ if (made.length) { named = true; return made; }
211
330
  const display = mentionsSecret(name) || codeValue(name, value) ? HIDDEN : shownValue(name, value, names);
212
- return [{ line: `${(Object.hasOwn(labels, name) ? labels[name] : undefined) ?? (plainName(name) ? name : "hidden name")}: ${display}`, id: RAW_ID.test(display) }];
331
+ // A name with no label is sent as the app wrote it; the card keeps it
332
+ // under Details in plain words, off the line under the question (#5401).
333
+ return [{ line: `${label ?? (plainName(name) ? name : "hidden name")}: ${display}`, id: RAW_ID.test(display) }];
213
334
  });
214
335
  return "Details:\n" + [...rows.filter((row) => !row.id), ...rows.filter((row) => row.id)].map((row) => row.line).join("\n");
215
336
  }
@@ -38,8 +38,10 @@ export function conversationRules(spec, ask) {
38
38
  "says where the answer is.\n\n" +
39
39
  "When you change something a person can see, attach a screenshot of it to " +
40
40
  "an addComment (it takes `images`, up to 6 data URLs of PNG, JPEG, GIF or " +
41
- `WebP). When you are choosing between looks, ask with ${ask} and pass ` +
42
- "`images` so the person can see each one, and name them in the options.\n\n" +
41
+ `WebP). When you ask about something you saw (a screenshot, a page) or ` +
42
+ `are choosing between looks, ask with ${ask} and pass the pictures in ` +
43
+ "`images`, each as {image, caption} with one plain line saying what it " +
44
+ "shows, so the person can answer from Needs you without opening your work.\n\n" +
43
45
  "When you change a page of an app, write `.viewable-page.json` in the root " +
44
46
  "of the folder you work in, naming that page's address and what a person " +
45
47
  "calls it, like `{\"path\": \"/settings\", \"name\": \"settings page\"}`. " +
@@ -69,11 +71,38 @@ export function otherAppsRule() {
69
71
  );
70
72
  }
71
73
 
74
+ // A REFUSAL STOPS THE RUN AND ASKS (#6995). A read-only key that was refused
75
+ // sent a run to the Supabase CLI's full-rights login instead. Every engine is
76
+ // told this, in an idea's preamble and in a chat turn's prefix; the tools it
77
+ // names are also barred outright where the engine allows it (otherLogins.mjs).
78
+ // `ask` is the engine's own name for the board's ask_user.
79
+ export function refusalRule(ask) {
80
+ return (
81
+ "When a read or a write is refused (a key that only reads, a permission " +
82
+ "error, a 401 or 403, a tool or app that says no), stop that part of the " +
83
+ `task and ask the person with ${ask}: say what was refused and why, in ` +
84
+ "the words of the error, and what they could change. Never get round a " +
85
+ "refusal with another login, CLI session, token or key on this computer: " +
86
+ "no Supabase CLI, no gh token, no keychain or password manager, no key " +
87
+ "from a file or a setting, and no other account. If you cannot ask, say " +
88
+ "what was refused in your reply and stop there.\n\n"
89
+ );
90
+ }
91
+
72
92
  // USE MY COMPUTER'S APPS IS OFF (#481). A run without the switch has no way
73
93
  // to the person's own apps, so rather than hunt for one it says so in its
74
94
  // closing message, in these words: the app finds the sentence and offers
75
95
  // Open Manage agent under it.
76
96
  export const APPS_OFF_SENTENCE = "Turn on **Use my computer's apps** in Manage agent and I will try again.";
97
+ /** Closing words that ask for Use my computer's apps (#6552): the sentence
98
+ * above, bold, quoted or plain, as a model writes it back. The app's own
99
+ * reader is src/nodes/sessionWords.ts `offersComputerApps`. A run whose
100
+ * closing asks for the apps could not do its job; runnerCompletion.mjs says
101
+ * so on the row (`sidecar.unable`), and an automation counts it as failed. */
102
+ export function asksForComputerApps(text) {
103
+ return /Turn on [*'"\u2018\u201c]*Use my computer['\u2019]s apps[*'"\u2019\u201d]* in Manage agent/i.test(String(text ?? ""));
104
+ }
105
+
77
106
  export function computerAppsOffRule() {
78
107
  return (
79
108
  "You cannot reach the person's own apps from this run (their email, " +