viewable-one 0.12.6 → 0.12.7

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.
@@ -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\"}`. " +
@@ -74,6 +76,15 @@ export function otherAppsRule() {
74
76
  // closing message, in these words: the app finds the sentence and offers
75
77
  // Open Manage agent under it.
76
78
  export const APPS_OFF_SENTENCE = "Turn on **Use my computer's apps** in Manage agent and I will try again.";
79
+ /** Closing words that ask for Use my computer's apps (#6552): the sentence
80
+ * above, bold, quoted or plain, as a model writes it back. The app's own
81
+ * reader is src/nodes/sessionWords.ts `offersComputerApps`. A run whose
82
+ * closing asks for the apps could not do its job; runnerCompletion.mjs says
83
+ * so on the row (`sidecar.unable`), and an automation counts it as failed. */
84
+ export function asksForComputerApps(text) {
85
+ return /Turn on [*'"\u2018\u201c]*Use my computer['\u2019]s apps[*'"\u2019\u201d]* in Manage agent/i.test(String(text ?? ""));
86
+ }
87
+
77
88
  export function computerAppsOffRule() {
78
89
  return (
79
90
  "You cannot reach the person's own apps from this run (their email, " +
package/lib/detect.mjs CHANGED
@@ -176,7 +176,8 @@ function ownPathDirs({ env = process.env } = {}) {
176
176
  * with `existsSync`, so a caller gets back a concrete path instead of a
177
177
  * boolean), the well-known install directories (`knownBinDirs`, also no
178
178
  * process spawned), and last a login shell's `command -v` (`loginShellWhich`
179
- * - slowest, memoized, asked only when the first two came up empty).
179
+ * - slowest, asked only when the first two came up empty; `detectAgents`
180
+ * remembers its answer, see `resolveMemo`).
180
181
  *
181
182
  * On POSIX a `bin` that already names a place (it contains a separator) is
182
183
  * `PM_<AGENT>_BIN` set to an explicit path, handed back unchanged and
@@ -476,6 +477,12 @@ export async function probeClaudeEffort(bin, { exec = execProbe, env = process.e
476
477
  return models;
477
478
  }
478
479
 
480
+ /** What `detectAgents` learned from `resolveAgentBinary`, per tool name, PATH and
481
+ * shell: a found path stays until it stops answering, a miss for this long. A
482
+ * tool installed after a miss shows up within one window. */
483
+ export const RESOLVE_MISS_MS = 30 * 60 * 1000;
484
+ const resolveMemo = new Map();
485
+
479
486
  /** Probe every engine. Returns the `agents` block stage 2 writes into the
480
487
  * mark file:
481
488
  *
@@ -493,11 +500,44 @@ export async function detectAgents({
493
500
  fileExists,
494
501
  timeoutMs = PROBE_TIMEOUT_MS,
495
502
  codexDiscover = exec === execProbe ? discoverCodex : null,
503
+ // The way a real run finds a tool (`resolveAgentBinary`: PATH, the usual
504
+ // install folders, then a login shell). Only the real probe uses it; a test's
505
+ // fake exec answers for the names it is given and nothing else.
506
+ resolve = exec === execProbe ? resolveAgentBinary : null,
507
+ memo,
508
+ now = Date.now,
496
509
  } = {}) {
510
+ const cache = memo ?? (resolve === resolveAgentBinary ? resolveMemo : new Map());
497
511
  const agents = {};
512
+ const probedBin = {};
498
513
  for (const spec of bins) {
499
514
  const bin = env[`PM_${spec.key.toUpperCase()}_BIN`]?.trim() || spec.bin;
500
- const result = await exec(bin, ["--version"], { timeoutMs, env });
515
+ let result = await exec(bin, ["--version"], { timeoutMs, env });
516
+ probedBin[spec.key] = bin;
517
+ // A watcher started by hand or by a service has a short PATH. "Not on this
518
+ // PATH" is not "not installed": a run would find the tool through
519
+ // `resolveAgentBinary`, so the mark must too, or the board reads Claude Code
520
+ // as missing and sends the run to another tool (#6646).
521
+ if (result?.ok !== true && resolve) {
522
+ // The lookup can spawn login shells, and this probe runs every five
523
+ // minutes before the first beat: remember a path, and a miss for a while.
524
+ const key = `${bin}\0${env.PATH ?? ""}\0${env.SHELL ?? ""}\0${env.HOME ?? ""}`;
525
+ const seen = cache.get(key);
526
+ try {
527
+ let path;
528
+ if (seen && (seen.path !== null || now() - seen.at < RESOLVE_MISS_MS)) path = seen.path;
529
+ else {
530
+ const resolved = await resolve(bin, { env, platform });
531
+ path = resolved?.found && resolved.path !== bin ? resolved.path : null;
532
+ cache.set(key, { path, at: now() });
533
+ }
534
+ if (path !== null) {
535
+ const retry = await exec(path, ["--version"], { timeoutMs, env });
536
+ if (retry?.ok === true) { result = retry; probedBin[spec.key] = path; }
537
+ else cache.delete(key);
538
+ }
539
+ } catch { /* an unresolvable tool stays not found */ }
540
+ }
501
541
  const found = result?.ok === true;
502
542
  const version = found ? versionFrom(result.stdout || result.stderr) : undefined;
503
543
  agents[spec.key] = { found, ...(version ? { version } : {}) };
@@ -506,14 +546,14 @@ export async function detectAgents({
506
546
  // elsewhere; Codex is queried through app-server below.
507
547
  if (agents.claude) {
508
548
  if (agents.claude.found) {
509
- const effortModels = await probeClaudeEffort(env.PM_CLAUDE_BIN?.trim() || bins.find((b) => b.key === "claude")?.bin || "claude", { exec, env, timeoutMs });
549
+ const effortModels = await probeClaudeEffort(probedBin.claude, { exec, env, timeoutMs });
510
550
  if (Object.keys(effortModels).length) agents.claude.effortModels = effortModels;
511
551
  }
512
552
  agents.claude.loggedIn = await claudeLoggedIn({ exec, env, platform, credentialsPath, fileExists });
513
553
  }
514
554
  if (agents.codex?.found && codexDiscover) {
515
555
  try {
516
- Object.assign(agents.codex, await codexDiscover({ bin: env.PM_CODEX_BIN?.trim() || "codex", env, timeoutMs }));
556
+ Object.assign(agents.codex, await codexDiscover({ bin: probedBin.codex, env, timeoutMs }));
517
557
  } catch { /* version detection remains valid when model discovery fails */ }
518
558
  }
519
559
  return agents;
package/lib/doctor.mjs CHANGED
@@ -447,7 +447,9 @@ export async function doctorRows(
447
447
  ? row("version", "version", true, "unknown", `${version} installed; npm did not answer (offline?)`)
448
448
  : compareVersions(newestPublished, version) > 0
449
449
  ? row("version", "version", true, "update available", `${version} installed, ${newestPublished} on npm: npm i -g viewable-one@latest --force`)
450
- : row("version", "version", true, "current", `${version} is the latest`),
450
+ : row("version", "version", true, "current", compareVersions(version, newestPublished) > 0
451
+ ? `${version} is newer than the published ${newestPublished}`
452
+ : `${version} is the latest`),
451
453
  );
452
454
 
453
455
  return rows;
@@ -0,0 +1,81 @@
1
+ // Ending what an agent left running in its own process group (#6557).
2
+ //
3
+ // A recovery-tracked agent leads a private group, so everything it started
4
+ // without `setsid` shares that group. Stop, the wall clock and the stall
5
+ // watchdog end the group, EXCEPT the preview server the session recorded in
6
+ // `.viewable-server.json` (ruling A, 2026-09-06). That server is not always in
7
+ // a group of its own: on macOS the instruction is `nohup <cmd> & disown`,
8
+ // which keeps the agent's group. So the server is spared by pid (and what it
9
+ // started), not by group. With no recorded server the whole group is signalled
10
+ // at once, which leaves no window for a fork to slip through.
11
+ import { processSnapshot, descendantPids } from "./procs.mjs";
12
+
13
+ const nap = (ms) => new Promise((done) => setTimeout(done, ms));
14
+
15
+ /** Is anything still alive in the group `pgid` leads? A member we may not
16
+ * signal (EPERM) is still a member. A group cannot be recycled while it has
17
+ * members, so a true answer here is about OUR group. */
18
+ function groupAlive(pgid) {
19
+ try { process.kill(-pgid, 0); return true; } catch (error) { return error.code === "EPERM"; }
20
+ }
21
+
22
+ async function spared(keep) {
23
+ try {
24
+ const pids = await keep?.();
25
+ return new Set([...(pids ?? [])].map(Number).filter((pid) => Number.isInteger(pid) && pid > 1));
26
+ } catch { return new Set(); }
27
+ }
28
+
29
+ /** The members of `pgid` that may be ended: all of them minus the spared
30
+ * servers and their descendants. null means the process list was unreadable. */
31
+ async function members(pgid, spare, snapshot) {
32
+ const table = await snapshot();
33
+ if (!table) return null;
34
+ const keep = new Set();
35
+ for (const pid of spare) {
36
+ if (!table.has(pid)) continue;
37
+ keep.add(pid);
38
+ for (const child of descendantPids(pid, table)) keep.add(child);
39
+ }
40
+ const found = [];
41
+ for (const [pid, row] of table) {
42
+ if (pid > 1 && row.pgid === pgid && !keep.has(pid) && !row.command?.includes("<defunct>")) found.push(pid);
43
+ }
44
+ return found;
45
+ }
46
+
47
+ /** Send `sig` to everything in the group that is not a spared server.
48
+ * `verified` signals only pids the process table shows in this group right
49
+ * now, never a bare group number (the late SIGKILL pass: a group that emptied
50
+ * during the grace must not be signalled blind). */
51
+ export async function signalGroup(pgid, sig, { keep, verified = false, snapshot = () => processSnapshot(), kill = (pid, s) => process.kill(pid, s) } = {}) {
52
+ const spare = await spared(keep);
53
+ if (!spare.size && !verified) {
54
+ try { kill(-pgid, sig); } catch { /* the group is already empty */ }
55
+ return;
56
+ }
57
+ // Signal members one by one. If the list is unreadable, end only the agent
58
+ // itself, as before #6557 (and nothing at all on a verified pass).
59
+ const found = (await members(pgid, spare, snapshot)) ?? (verified ? [] : [pgid]);
60
+ for (const pid of found) {
61
+ try { kill(pid, sig); } catch { /* gone already */ }
62
+ }
63
+ }
64
+
65
+ /** AFTER A KILL, WAIT UNTIL THE GROUP HAS NOTHING LEFT TO END. What the agent
66
+ * started gets until `deadline` (the kill grace) to follow SIGTERM, then
67
+ * SIGKILL, then a bounded wait for the kernel to reap them. Returns the pids
68
+ * that survived (empty: done), so the caller can keep recovery evidence for
69
+ * exactly those. POSIX only, like the group itself. */
70
+ export async function reapGroup(pgid, deadline, { keep, snapshot = () => processSnapshot(), alive = groupAlive, kill, wait = nap, now = Date.now, finalWaitMs = 2_000 } = {}) {
71
+ if (!Number.isInteger(pgid) || pgid <= 1) return [];
72
+ const spare = await spared(keep);
73
+ const step = spare.size ? 100 : 25;
74
+ const left = async () => spare.size ? ((await members(pgid, spare, snapshot))?.length ?? 1) > 0 : alive(pgid);
75
+ while (await left() && now() < deadline) await wait(step);
76
+ if (!await left()) return [];
77
+ await signalGroup(pgid, "SIGKILL", { keep, verified: true, snapshot, ...(kill ? { kill } : {}) });
78
+ for (let waited = 0; waited < finalWaitMs && await left(); waited += step) await wait(step);
79
+ if (!await left()) return [];
80
+ return (await members(pgid, spare, snapshot)) ?? [pgid];
81
+ }
@@ -228,9 +228,95 @@ const scopeOf = (input, folder) =>
228
228
  const runsOutside = (toolName, input, folder) =>
229
229
  toolName === "Bash" && typeof input?.cwd === "string" && input.cwd !== "" && scopeOf(input, folder) !== undefined && !staysInFolder(".", input.cwd, folder);
230
230
 
231
+ // ---------------------------------------------------------------------------
232
+ // A FILE TOOL'S REMEMBERED RULE STAYS IN THE FOLDER (#6556)
233
+ //
234
+ // A rule for a file tool is the tool's bare name (`Edit`), so "Always allow in
235
+ // my-app" for one edit must not also wave through an edit of `/etc/hosts`.
236
+ // A remembered rule therefore applies only when every path the call names
237
+ // lands inside the linked folder, links followed (`realPathOf`), a relative
238
+ // path judged from the run's own folder (Claude's file tools resolve it
239
+ // there, not from the shell's `cd`s). A call with no path, a path that cannot
240
+ // be read as text, or one that lands outside or through a link that leads out,
241
+ // is covered by nothing: it asks, and offers no "Always" button, since no
242
+ // saved rule would apply to it. Bash has its own check above and is untouched.
243
+
244
+ const FILE_TOOLS = new Set(["Read", "Write", "Edit", "MultiEdit", "NotebookEdit"]);
245
+ const SEARCH_TOOLS = new Set(["Glob", "Grep"]);
246
+ /** Keys a tool puts a path in. */
247
+ const PATH_KEYS = ["file_path", "notebook_path", "path"];
248
+ const GLOB_CHARS = /[*?[\]{}()!]/;
249
+
250
+ /** The directory a glob starts from: its steps up to the first one that
251
+ * names more than one thing. Null for a pattern that reaches out of its
252
+ * root by itself: `..` steps, or a leading `~`. */
253
+ const globRoot = (pattern) => {
254
+ if (pattern.startsWith("~")) return null;
255
+ const steps = pattern.split(/[\\/]/);
256
+ if (steps.includes("..")) return null;
257
+ const fixed = [];
258
+ for (const step of steps) {
259
+ if (GLOB_CHARS.test(step)) break;
260
+ fixed.push(step);
261
+ }
262
+ return fixed.length === steps.length ? pattern : (fixed.join("/") || (pattern.startsWith("/") ? "/" : "."));
263
+ };
264
+
265
+ /** The paths a call names, as `{path, glob}` entries to judge, or null when
266
+ * the call must ask: a file tool with no path text, or one with a NUL byte. */
267
+ const targetsOf = (toolName, input) => {
268
+ const isText = (value) => typeof value === "string" && value !== "" && !value.includes("\0");
269
+ if (FILE_TOOLS.has(toolName)) {
270
+ const path = input?.file_path ?? input?.notebook_path;
271
+ return isText(path) ? [{ path }] : null;
272
+ }
273
+ if (SEARCH_TOOLS.has(toolName)) {
274
+ // No `path` means the run's own folder.
275
+ const out = [];
276
+ if (input?.path !== undefined && input.path !== null && input.path !== "") {
277
+ if (!isText(input.path)) return null;
278
+ out.push({ path: input.path });
279
+ } else out.push({ path: "." });
280
+ for (const key of toolName === "Glob" ? ["pattern"] : ["glob"]) {
281
+ const value = input?.[key];
282
+ if (value === undefined || value === null || value === "") continue;
283
+ if (!isText(value)) return null;
284
+ // A glob is judged from the search root (an absolute one is judged as written).
285
+ out.push({ path: value, glob: true, from: out[0].path });
286
+ }
287
+ return out;
288
+ }
289
+ // Any other tool that names a path (an engine's own file tool) is held to it too.
290
+ if (toolName === "Bash" || toolName === "Permissions" || String(toolName).startsWith("mcp__")) return [];
291
+ const out = [];
292
+ for (const key of PATH_KEYS) {
293
+ const value = input?.[key];
294
+ if (value === undefined || value === null) continue;
295
+ if (!isText(value)) return null;
296
+ out.push({ path: value });
297
+ }
298
+ return out;
299
+ };
300
+
301
+ /** Whether every path this call names lands inside `folder`, links followed.
302
+ * True for a tool that names no path (nothing to hold it to). */
303
+ export function targetsStayInFolder(toolName, input, folder, base) {
304
+ const targets = targetsOf(toolName, input);
305
+ if (targets === null) return false;
306
+ if (targets.length === 0) return true;
307
+ if (typeof folder !== "string" || folder === "") return false;
308
+ const from = typeof base === "string" && base !== "" ? base : folder;
309
+ return targets.every((target) => {
310
+ if (!target.glob) return staysInFolder(target.path, from, folder);
311
+ const root = globRoot(target.path);
312
+ return root !== null && staysInFolder(root, isAbsolute(root) ? from : resolve(from, target.from), folder);
313
+ });
314
+ }
315
+
231
316
  /** The "Always allow" button for a tool call. A shell command names its
232
317
  * family, or says it saves this command only. */
233
- export function alwaysOptionFor(toolName, input, folderName, folder) {
318
+ export function alwaysOptionFor(toolName, input, folderName, folder, base) {
319
+ if (!targetsStayInFolder(toolName, input, folder, base)) return "";
234
320
  if (toolName !== "Bash") return alwaysLabel(folderName);
235
321
  if (runsOutside(toolName, input, folder)) return "";
236
322
  const family = safeFamilyOf(input?.command, scopeOf(input, folder));
@@ -418,7 +504,8 @@ export function questionFor({ toolName, input, folder, base }) {
418
504
  const mcp = /^mcp__(.+?)__(.+)$/.exec(String(toolName));
419
505
  if (mcp) {
420
506
  const [, provider, name] = mcp;
421
- const risk = writeRisk(provider.toLowerCase(), name, input) ?? "open-ended";
507
+ // A computer app has no catalog row: its risk is read from the call alone (#5442).
508
+ const risk = writeRisk(null, name, input) ?? "open-ended";
422
509
  return { question: `Use ${name.replaceAll("_", " ")} in ${provider}?`,
423
510
  // A tool that only flags itself destructive has no reason line (#4571).
424
511
  why: `On your computer, ${provider}\n${riskReason(risk) ? `${riskReason(risk)}\n` : ""}${appInputsText(provider, input, name)}`,
@@ -457,7 +544,7 @@ export function questionFor({ toolName, input, folder, base }) {
457
544
  return {
458
545
  question: bash ? bash.question : `Can I ${action}?`,
459
546
  why,
460
- options: [ALLOW, toolName === "Bash" ? ALLOW_RUN : "", NOT_THIS, alwaysOptionFor(toolName, input, folderName, folder)].filter(Boolean),
547
+ options: [ALLOW, toolName === "Bash" ? ALLOW_RUN : "", NOT_THIS, alwaysOptionFor(toolName, input, folderName, folder, base)].filter(Boolean),
461
548
  recommendation: { answer: ALLOW, why: "It lets this run carry on with what you asked." },
462
549
  };
463
550
  }
@@ -497,8 +584,10 @@ export async function rememberRule(env, folder, key) {
497
584
  * saved before #3726 still matches its family when it names one (`Bash(ls:*)`,
498
585
  * cat, pwd, head, tail, wc), and only then; any other (`Bash(npm:*)`,
499
586
  * `Bash(rm:*)`) matches no key any more. */
500
- export function ruleCovers(rules, toolName, input, folder) {
587
+ export function ruleCovers(rules, toolName, input, folder, base) {
501
588
  if (!rememberable(toolName, input)) return false;
589
+ // A file tool's rule is its bare name, so the paths it names are checked here (#6556).
590
+ if (!targetsStayInFolder(toolName, input, folder, base)) return false;
502
591
  // A command run from outside the linked folder is never covered, not even by
503
592
  // a rule saved for those exact bytes (#3759): the bytes mean something else there.
504
593
  if (runsOutside(toolName, input, folder)) return false;
@@ -629,7 +718,7 @@ export function createPermissionAsker({
629
718
  // write the folder's remembered permission rules.
630
719
  const remembered = question ? [] : await readRules(env, folder);
631
720
  if (signal?.aborted) return null;
632
- if (!question && ruleCovers(remembered, toolName, input, folder)) {
721
+ if (!question && ruleCovers(remembered, toolName, input, folder, cwd)) {
633
722
  log(`permission: ${ruleKeyFor(toolName, input, folder)} is allowed in ${folderName} (remembered), no question filed`);
634
723
  return allow();
635
724
  }
@@ -683,6 +772,7 @@ export function createPermissionAsker({
683
772
  const verdict = verdictFor(answer, folderName, q.options.find((o) => o.startsWith("Always allow")) ?? null, { runOffered: q.options.includes(ALLOW_RUN) });
684
773
  if (verdict.forRun) runAllowed.abort();
685
774
  if (verdict.remember && !rememberable(toolName, input)) log("permission: this grant names no scope, so it is allowed once and not remembered");
775
+ else if (verdict.remember && !targetsStayInFolder(toolName, input, folder, cwd)) log("permission: this call names a path outside the folder, so it is allowed once and not remembered (#6556)");
686
776
  else if (verdict.remember) {
687
777
  try { await rememberRule(env, folder, ruleKeyFor(toolName, input, folder)); }
688
778
  catch (error) { log(`permission: could not save the rule (${error?.message ?? error}); allowing this once`); }
@@ -46,7 +46,11 @@ async function claimAdmitted(root, project, settings, runnerApi, { activeRunIds,
46
46
  if (!(await flushCompletions(project, settings))) return { claimed: false, transient: true, detail: "Saved completions are waiting to sync." };
47
47
  const room = await runningRoom(project, settings, runnerApi, { activeRunIds, log });
48
48
  if (!room.ok) return { claimed: false, ...room };
49
- const claimed = await runnerApi.claim({ projectIds: [project.id], runnerInstanceId: settings.runnerInstanceId ??= randomUUID(), fencing: true }, rowsOpts);
49
+ const claimed = await runnerApi.claim({
50
+ projectIds: [project.id], runnerInstanceId: settings.runnerInstanceId ??= randomUUID(), fencing: true,
51
+ // The database holds the same cap across this computer's folders (#5732).
52
+ ...(Number.isFinite(settings.maxConcurrent) ? { maxConcurrent: settings.maxConcurrent } : {}),
53
+ }, rowsOpts);
50
54
  if (!claimed.ok) return { claimed: false, transient: claimed.transient === true, ...retryHint(claimed), detail: claimed.error };
51
55
  if (!claimed.run) return { claimed: false, idle: true, detail: "nothing pending" };
52
56
  return { claimed: true, run: claimed.run };
package/lib/runnerApi.mjs CHANGED
@@ -193,8 +193,13 @@ export function heartbeat({ projectIds, presence, runnerInstanceId, activeRunIds
193
193
  * `listRequests`/`claimRequest`'s exclusive-create-on-disk race. `run.request`
194
194
  * is the SpawnRequest a file used to carry; `run.project_id` names which
195
195
  * registered project (and therefore which root) it belongs to. */
196
- export function claim({ projectIds, runnerInstanceId, fencing }, options = {}) {
197
- return call("claim", { projectIds, ...(runnerInstanceId !== undefined ? { runnerInstanceId } : {}), ...(fencing === true ? { fencing } : {}) }, options);
196
+ /** `maxConcurrent` is PM_SPAWN_MAX_CONCURRENT when set: the database holds it
197
+ * per computer across folders (#5732). Absent (the default) is no cap. */
198
+ export function claim({ projectIds, runnerInstanceId, fencing, maxConcurrent }, options = {}) {
199
+ return call("claim", {
200
+ projectIds, ...(runnerInstanceId !== undefined ? { runnerInstanceId } : {}), ...(fencing === true ? { fencing } : {}),
201
+ ...(Number.isSafeInteger(maxConcurrent) && maxConcurrent >= 1 ? { maxConcurrent } : {}),
202
+ }, options);
198
203
  }
199
204
 
200
205
  /** `update {runId, patch}` -> ok, or `{ok:false, error:"result already
@@ -12,7 +12,8 @@
12
12
  // not in four separate writes racing whatever else might be reading the row.
13
13
  import { cleanWorktree, isGitCheckout, worktreeSummary } from "./worktree.mjs";
14
14
  import { readWorktreeRecord } from "./devserver.mjs";
15
- import { reportOutcomeOnBoard, formatVerdict } from "./boardside.mjs";
15
+ import { reportOutcomeOnBoard, formatVerdict, closingTextOf, finishedCleanly } from "./boardside.mjs";
16
+ import { asksForComputerApps } from "./conversationRules.mjs";
16
17
  import { promoteLateRows } from "./rowsAnswers.mjs";
17
18
  import { housekeeping } from "./runnerMaintenance.mjs";
18
19
  import { classifyExit } from "./exitClass.mjs";
@@ -238,6 +239,13 @@ export async function completeRequest(context, services = defaultServices) {
238
239
  // its exit happened to read as ok - "you stopped it" is worth keeping
239
240
  // separate from "it finished" even when the two exits look alike.
240
241
  const status = wasStopped ? "stopped" : outcome.ok === true ? "done" : "error";
242
+ // A RUN THAT FINISHED BUT COULD NOT DO ITS JOB (#6552): it had no way to
243
+ // the person's apps and its closing words ask for them. The row stays
244
+ // `done` (the session did end well); `unable` names why, so a scheduled
245
+ // run's automation counts a failure (runs_habit_completion) instead of
246
+ // "Ran". A run that had the apps never sets it.
247
+ const unable = status === "done" && request?.computerApps !== true
248
+ && finishedCleanly(outcome) && asksForComputerApps(closingTextOf(outcome)) ? "computer-apps" : undefined;
241
249
  const patch = {
242
250
  status,
243
251
  result: `${outcome.ok === true ? "OK" : "ERROR"}\n\n${detail}\n`,
@@ -247,7 +255,7 @@ export async function completeRequest(context, services = defaultServices) {
247
255
  // final sidecar and may retain their early workspace receipt instead.
248
256
  // The pictures ride on the closing reply only: two of them on every run
249
257
  // row would weigh down each list of runs (#2194).
250
- sidecar: { ...(sidecar ?? {}), resultLanded, ...(outcome.result ? { result: withoutPictures(outcome.result) } : {}), ...(status === "error" ? agentErrorOf(outcome) : {}) },
258
+ sidecar: { ...(sidecar ?? {}), resultLanded, ...(unable ? { unable } : {}), ...(outcome.result ? { result: withoutPictures(outcome.result) } : {}), ...(status === "error" ? agentErrorOf(outcome) : {}) },
251
259
  ...(server ? { server } : {}),
252
260
  };
253
261