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.
@@ -1,5 +1,6 @@
1
- import { writeRisk, riskReason } from "./writePolicy.mjs";
1
+ import { writeRisk, riskReason, automationReads } from "./writePolicy.mjs";
2
2
  import { appInputsText } from "./codexToolInputs.mjs";
3
+ import { otherLoginDenied, usesAnotherLogin } from "./otherLogins.mjs";
3
4
  // ASK IN THE IDEA (issue #478, rulings #470 #468 #417 #418).
4
5
  //
5
6
  // A coding agent on the person's computer works from a list of things it may
@@ -228,9 +229,95 @@ const scopeOf = (input, folder) =>
228
229
  const runsOutside = (toolName, input, folder) =>
229
230
  toolName === "Bash" && typeof input?.cwd === "string" && input.cwd !== "" && scopeOf(input, folder) !== undefined && !staysInFolder(".", input.cwd, folder);
230
231
 
232
+ // ---------------------------------------------------------------------------
233
+ // A FILE TOOL'S REMEMBERED RULE STAYS IN THE FOLDER (#6556)
234
+ //
235
+ // A rule for a file tool is the tool's bare name (`Edit`), so "Always allow in
236
+ // my-app" for one edit must not also wave through an edit of `/etc/hosts`.
237
+ // A remembered rule therefore applies only when every path the call names
238
+ // lands inside the linked folder, links followed (`realPathOf`), a relative
239
+ // path judged from the run's own folder (Claude's file tools resolve it
240
+ // there, not from the shell's `cd`s). A call with no path, a path that cannot
241
+ // be read as text, or one that lands outside or through a link that leads out,
242
+ // is covered by nothing: it asks, and offers no "Always" button, since no
243
+ // saved rule would apply to it. Bash has its own check above and is untouched.
244
+
245
+ const FILE_TOOLS = new Set(["Read", "Write", "Edit", "MultiEdit", "NotebookEdit"]);
246
+ const SEARCH_TOOLS = new Set(["Glob", "Grep"]);
247
+ /** Keys a tool puts a path in. */
248
+ const PATH_KEYS = ["file_path", "notebook_path", "path"];
249
+ const GLOB_CHARS = /[*?[\]{}()!]/;
250
+
251
+ /** The directory a glob starts from: its steps up to the first one that
252
+ * names more than one thing. Null for a pattern that reaches out of its
253
+ * root by itself: `..` steps, or a leading `~`. */
254
+ const globRoot = (pattern) => {
255
+ if (pattern.startsWith("~")) return null;
256
+ const steps = pattern.split(/[\\/]/);
257
+ if (steps.includes("..")) return null;
258
+ const fixed = [];
259
+ for (const step of steps) {
260
+ if (GLOB_CHARS.test(step)) break;
261
+ fixed.push(step);
262
+ }
263
+ return fixed.length === steps.length ? pattern : (fixed.join("/") || (pattern.startsWith("/") ? "/" : "."));
264
+ };
265
+
266
+ /** The paths a call names, as `{path, glob}` entries to judge, or null when
267
+ * the call must ask: a file tool with no path text, or one with a NUL byte. */
268
+ const targetsOf = (toolName, input) => {
269
+ const isText = (value) => typeof value === "string" && value !== "" && !value.includes("\0");
270
+ if (FILE_TOOLS.has(toolName)) {
271
+ const path = input?.file_path ?? input?.notebook_path;
272
+ return isText(path) ? [{ path }] : null;
273
+ }
274
+ if (SEARCH_TOOLS.has(toolName)) {
275
+ // No `path` means the run's own folder.
276
+ const out = [];
277
+ if (input?.path !== undefined && input.path !== null && input.path !== "") {
278
+ if (!isText(input.path)) return null;
279
+ out.push({ path: input.path });
280
+ } else out.push({ path: "." });
281
+ for (const key of toolName === "Glob" ? ["pattern"] : ["glob"]) {
282
+ const value = input?.[key];
283
+ if (value === undefined || value === null || value === "") continue;
284
+ if (!isText(value)) return null;
285
+ // A glob is judged from the search root (an absolute one is judged as written).
286
+ out.push({ path: value, glob: true, from: out[0].path });
287
+ }
288
+ return out;
289
+ }
290
+ // Any other tool that names a path (an engine's own file tool) is held to it too.
291
+ if (toolName === "Bash" || toolName === "Permissions" || String(toolName).startsWith("mcp__")) return [];
292
+ const out = [];
293
+ for (const key of PATH_KEYS) {
294
+ const value = input?.[key];
295
+ if (value === undefined || value === null) continue;
296
+ if (!isText(value)) return null;
297
+ out.push({ path: value });
298
+ }
299
+ return out;
300
+ };
301
+
302
+ /** Whether every path this call names lands inside `folder`, links followed.
303
+ * True for a tool that names no path (nothing to hold it to). */
304
+ export function targetsStayInFolder(toolName, input, folder, base) {
305
+ const targets = targetsOf(toolName, input);
306
+ if (targets === null) return false;
307
+ if (targets.length === 0) return true;
308
+ if (typeof folder !== "string" || folder === "") return false;
309
+ const from = typeof base === "string" && base !== "" ? base : folder;
310
+ return targets.every((target) => {
311
+ if (!target.glob) return staysInFolder(target.path, from, folder);
312
+ const root = globRoot(target.path);
313
+ return root !== null && staysInFolder(root, isAbsolute(root) ? from : resolve(from, target.from), folder);
314
+ });
315
+ }
316
+
231
317
  /** The "Always allow" button for a tool call. A shell command names its
232
318
  * family, or says it saves this command only. */
233
- export function alwaysOptionFor(toolName, input, folderName, folder) {
319
+ export function alwaysOptionFor(toolName, input, folderName, folder, base) {
320
+ if (!targetsStayInFolder(toolName, input, folder, base)) return "";
234
321
  if (toolName !== "Bash") return alwaysLabel(folderName);
235
322
  if (runsOutside(toolName, input, folder)) return "";
236
323
  const family = safeFamilyOf(input?.command, scopeOf(input, folder));
@@ -418,7 +505,8 @@ export function questionFor({ toolName, input, folder, base }) {
418
505
  const mcp = /^mcp__(.+?)__(.+)$/.exec(String(toolName));
419
506
  if (mcp) {
420
507
  const [, provider, name] = mcp;
421
- const risk = writeRisk(provider.toLowerCase(), name, input) ?? "open-ended";
508
+ // A computer app has no catalog row: its risk is read from the call alone (#5442).
509
+ const risk = writeRisk(null, name, input) ?? "open-ended";
422
510
  return { question: `Use ${name.replaceAll("_", " ")} in ${provider}?`,
423
511
  // A tool that only flags itself destructive has no reason line (#4571).
424
512
  why: `On your computer, ${provider}\n${riskReason(risk) ? `${riskReason(risk)}\n` : ""}${appInputsText(provider, input, name)}`,
@@ -457,7 +545,7 @@ export function questionFor({ toolName, input, folder, base }) {
457
545
  return {
458
546
  question: bash ? bash.question : `Can I ${action}?`,
459
547
  why,
460
- options: [ALLOW, toolName === "Bash" ? ALLOW_RUN : "", NOT_THIS, alwaysOptionFor(toolName, input, folderName, folder)].filter(Boolean),
548
+ options: [ALLOW, toolName === "Bash" ? ALLOW_RUN : "", NOT_THIS, alwaysOptionFor(toolName, input, folderName, folder, base)].filter(Boolean),
461
549
  recommendation: { answer: ALLOW, why: "It lets this run carry on with what you asked." },
462
550
  };
463
551
  }
@@ -497,8 +585,10 @@ export async function rememberRule(env, folder, key) {
497
585
  * saved before #3726 still matches its family when it names one (`Bash(ls:*)`,
498
586
  * cat, pwd, head, tail, wc), and only then; any other (`Bash(npm:*)`,
499
587
  * `Bash(rm:*)`) matches no key any more. */
500
- export function ruleCovers(rules, toolName, input, folder) {
588
+ export function ruleCovers(rules, toolName, input, folder, base) {
501
589
  if (!rememberable(toolName, input)) return false;
590
+ // A file tool's rule is its bare name, so the paths it names are checked here (#6556).
591
+ if (!targetsStayInFolder(toolName, input, folder, base)) return false;
502
592
  // A command run from outside the linked folder is never covered, not even by
503
593
  // a rule saved for those exact bytes (#3759): the bytes mean something else there.
504
594
  if (runsOutside(toolName, input, folder)) return false;
@@ -573,6 +663,20 @@ export const CLICK_AND_SCREEN_DENIED = "I can't press buttons inside other apps.
573
663
  const CLICK_AND_SCREEN_WORD = new RegExp(`(?:^|[\\s;&|()\`'"=])(?:[^\\s;&|()\`'"]*/)?(?:${CLICK_AND_SCREEN_COMMANDS.join("|")})(?=$|[\\s;&|()\`'"])`);
574
664
  export const drivesAnotherApp = (command) => CLICK_AND_SCREEN_WORD.test(String(command ?? ""));
575
665
 
666
+ /** The run card's line for an app read an automation's run made with no
667
+ * question (#6955): it says the automation was the yes and, as the server's
668
+ * receipt does for the same read (integrations `read: true`, #6628), never
669
+ * calls it a change. The tool reads as the question names it. The app is the
670
+ * engine's server key ("argos", "google_calendar"), so it reads as a name,
671
+ * each word capitalised ("Argos", "Google Calendar"); a key that already has
672
+ * a capital ("GitHub") stays as it is. */
673
+ const appWords = (app) => {
674
+ const key = String(app);
675
+ return /[A-Z]/.test(key) ? key : key.split(/[-_\s]+/).filter(Boolean).map((word) => word[0].toUpperCase() + word.slice(1)).join(" ");
676
+ };
677
+ export const automationReadWords = (app, tool) =>
678
+ `Read ${String(tool).replaceAll("_", " ")} in ${appWords(app)} without asking: setting the automation was your yes. Nothing was changed.`;
679
+
576
680
  /** Build the asker for one run.
577
681
  *
578
682
  * `ask({ toolName, input, signal })` resolves to `{behavior: "allow"}` or
@@ -591,9 +695,12 @@ export const drivesAnotherApp = (command) => CLICK_AND_SCREEN_WORD.test(String(c
591
695
  * fromId the idea the run belongs to
592
696
  * poll the run's answer poll, so the permission question's answer is
593
697
  * not also typed into the conversation (`claim`)
698
+ * askTool the engine's own name for the board's ask_user, for the words
699
+ * a refused other login hands back (#6995)
594
700
  */
595
701
  export function createPermissionAsker({
596
- folder, cwd, session, boardId, fromId, env, callTool = hostedCallTool, poll, log = () => {}, pollMs = 2000,
702
+ folder, cwd, session, boardId, fromId, env, callTool = hostedCallTool, poll, log = () => {}, pollMs = 2000, automation = false,
703
+ askTool = "ask_user",
597
704
  }) {
598
705
  const folderName = basename(folder) || folder;
599
706
  const scopedCallTool = (name, args, options) => callTool(name, args, { ...options, sessionBoardId: boardId });
@@ -604,12 +711,28 @@ export function createPermissionAsker({
604
711
  // second command's ask that was waiting beside the one answered.
605
712
  const runAllowed = new AbortController();
606
713
  const coveredByRun = (toolName, question) => !question && toolName === "Bash" && runAllowed.signal.aborted;
714
+ /** Whether a call of `tool` is a read made inside an automation's run, so it
715
+ * needs no question (ruling #5495): the same rule the server runs
716
+ * (writePolicy.automationReads), and only when `hints`, the app's own labels
717
+ * for the tool as the engine reports them (Codex's inventory), say
718
+ * read-only (#6955). With no labels the computer cannot tell a read from a
719
+ * write, so Claude's and ACP's requests, which carry none, always ask. The
720
+ * server's own rule keeps its label-less reads: it holds the tool's labels
721
+ * and the person's Allow list, which the computer has neither of. */
722
+ const readInAutomation = (tool, input, hints) => automation && hints?.readOnlyHint === true
723
+ && automationReads(tool, input && typeof input === "object" ? input : {}, hints);
607
724
  const ask = async ({ toolName, input: asked = {}, signal, question }) => {
608
725
  if (signal?.aborted) return null;
609
726
  if (!question && toolName === "Bash" && drivesAnotherApp(asked.command)) {
610
727
  log("permission: a command that drives another app is refused (#4204)");
611
728
  return { behavior: "deny", message: CLICK_AND_SCREEN_DENIED };
612
729
  }
730
+ // Another login, token or saved key (#6995): refused before any question,
731
+ // remembered rule or "Allow for this run", so a refusal is never got round.
732
+ if (!question && toolName === "Bash" && usesAnotherLogin(asked.command)) {
733
+ log("permission: a command that uses another login is refused (#6995)");
734
+ return { behavior: "deny", message: otherLoginDenied(askTool) };
735
+ }
613
736
  // A Claude command carries no working folder: it runs in the shell the run
614
737
  // started in (a worktree, not the linked folder itself) and wherever its
615
738
  // allowed `cd`s moved it, so its paths and links are judged there (#3759,
@@ -629,7 +752,7 @@ export function createPermissionAsker({
629
752
  // write the folder's remembered permission rules.
630
753
  const remembered = question ? [] : await readRules(env, folder);
631
754
  if (signal?.aborted) return null;
632
- if (!question && ruleCovers(remembered, toolName, input, folder)) {
755
+ if (!question && ruleCovers(remembered, toolName, input, folder, cwd)) {
633
756
  log(`permission: ${ruleKeyFor(toolName, input, folder)} is allowed in ${folderName} (remembered), no question filed`);
634
757
  return allow();
635
758
  }
@@ -683,6 +806,7 @@ export function createPermissionAsker({
683
806
  const verdict = verdictFor(answer, folderName, q.options.find((o) => o.startsWith("Always allow")) ?? null, { runOffered: q.options.includes(ALLOW_RUN) });
684
807
  if (verdict.forRun) runAllowed.abort();
685
808
  if (verdict.remember && !rememberable(toolName, input)) log("permission: this grant names no scope, so it is allowed once and not remembered");
809
+ 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
810
  else if (verdict.remember) {
687
811
  try { await rememberRule(env, folder, ruleKeyFor(toolName, input, folder)); }
688
812
  catch (error) { log(`permission: could not save the rule (${error?.message ?? error}); allowing this once`); }
@@ -697,5 +821,8 @@ export function createPermissionAsker({
697
821
  if (delay > 0) await sleepFor(delay, waitSignal);
698
822
  }
699
823
  };
824
+ // Codex hands over the app, the tool and the tool's labels apart, so the
825
+ // boundary between app and tool is never guessed. The only door that skips.
826
+ ask.appRead = (app, name, input, hints) => readInAutomation(name, input, hints);
700
827
  return ask;
701
828
  }
@@ -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
 
@@ -15,8 +15,7 @@ import * as runnerApiModule from "./runnerApi.mjs";
15
15
  import { callTool as hostedCallToolDefault } from "./hosted.mjs";
16
16
  import { runnerMcpUrlFrom } from "./mcpjson.mjs";
17
17
  import { hostedConfig, hostedToken } from "./auth.mjs";
18
- import { computerAppsOffRule, otherAppsRule } from "./conversationRules.mjs";
19
- import { acceptsMessages, agentFor, commandFor, isPersistentRequest, preambleFor } from "./agents.mjs";
18
+ import { acceptsMessages, agentFor, chatRulesFor, commandFor, isPersistentRequest, preambleFor } from "./agents.mjs";
20
19
  import { getRepoMap, formatRepoPrimer } from "./repomap.mjs";
21
20
  import { buildAttemptsSectionFromRows } from "./compose.mjs";
22
21
  import { imageInspectionInstruction } from "./imageAttachments.mjs";
@@ -84,7 +83,9 @@ export async function executeRequest(project, run, settings, log, timing, receip
84
83
  // and its `runnerApi` calls, not a signal file).
85
84
  const isChat = isChatTurn(request);
86
85
 
87
- const ctx = { eventSeq: run.event_seq, project, root, id, request, isChat, runnerApi, hostedEnv, rowsOpts, session, claimedAt, boardId, settings, log };
86
+ // A run an automation filed carries its `schedule_id` (the claimed row is the whole `runs` row).
87
+ const fromAutomation = typeof run.schedule_id === "string" && run.schedule_id !== "";
88
+ const ctx = { eventSeq: run.event_seq, project, root, id, request, isChat, fromAutomation, runnerApi, hostedEnv, rowsOpts, session, claimedAt, boardId, settings, log };
88
89
  const admitted = await admitRequest(ctx, preparation);
89
90
  if ("patch" in admitted) return finish(admitted.patch);
90
91
  const prepared = await prepareRun(ctx, admitted, receipt, preparation);
@@ -171,13 +172,15 @@ function makePlanRun({ project, root, id, request, isChat, runnerApi, hostedEnv,
171
172
  const repoPrimer = formatRepoPrimer(repoMap, attemptsSection ? attemptsSection.length : 0);
172
173
  // chat turn, difference 1: NO IDEA PREAMBLE. The app composes the persona,
173
174
  // room context and message; instructions such as "call report before you
174
- // finish" do not belong in chat. Only the other-apps rule and, when
175
- // needed, the apps-off rule are added for Claude Code and Codex, so the reply can offer Manage agent.
175
+ // finish" do not belong in chat. Only the rules every run keeps are added
176
+ // (agents.mjs chatRulesFor): a refusal stops and asks, for every engine
177
+ // (#6995), and for Claude Code and Codex the other-apps rule and, when
178
+ // needed, the apps-off rule, so the reply can offer Manage agent.
176
179
  let text = request.planMode === "draft"
177
180
  ? `Investigate the request using read-only research, then return an actionable implementation plan in your final response. Structure the response as a report: keep resolved or contextual findings in their own sections; put actionable work under a \`## Implementation plan\` heading with one \`### Step N: ...\` or \`### Issue X: ...\` heading per top-level item; put numbered substeps under a \`**Steps:**\` label; and label checks and open decisions clearly. Do not implement anything, use tools to modify files, or ask for permission to implement. The human will edit and approve or reject your final plan on the board.\n\n${String(request.prompt)}`
178
181
  : `${isChat ? "" : preambleFor(agent, { ...(made.isolated ? {} : { workplace: IN_PLACE_WORKPLACE }), computerApps: request.computerApps === true })}${String(request.prompt)}`;
179
- if (isChat && request.planMode !== "draft" && ["claude", "codex"].includes(agent)) {
180
- text = `${otherAppsRule()}${request.computerApps === true ? "" : computerAppsOffRule()}${text}`;
182
+ if (isChat && request.planMode !== "draft") {
183
+ text = `${chatRulesFor(agent, { computerApps: request.computerApps === true })}${text}`;
181
184
  }
182
185
  if (request.planMode === "execute") text += `\n\nHUMAN-APPROVED IMPLEMENTATION PLAN\nFollow this exact plan, including the human's edits. Ask the human about any material scope change before implementing it.\n\n${request.approvedPlan}`;
183
186
  if (note) text = `${text}\n\n${note}`;
@@ -9,6 +9,7 @@ import { createRowsAnswerPoll } from "./rowsAnswers.mjs";
9
9
  import { createPermissionAsker } from "./permissionAsk.mjs";
10
10
  import { makeRowEventStreamer } from "./rowsEvents.mjs";
11
11
  import { AGENTS, agentFor, prepareWorkspace, runnerFor } from "./agents.mjs";
12
+ import { readWorktreeRecord } from "./devserver.mjs";
12
13
  import { classifyExit } from "./exitClass.mjs";
13
14
  import { DEFAULTS, childEnv } from "./child.mjs";
14
15
  import { BOARD_DIR } from "./paths.mjs";
@@ -37,7 +38,7 @@ export function resumeNotes(request) {
37
38
 
38
39
  /** Spawn the run's process and see it through to its receipt. */
39
40
  export async function startRun(ctx, state, { timing, receipt, preparation, finish }) {
40
- const { root, id, request, isChat, runnerApi, rowsOpts, hostedEnv, session, boardId, settings, log } = ctx;
41
+ const { root, id, request, isChat, fromAutomation, runnerApi, rowsOpts, hostedEnv, session, boardId, settings, log } = ctx;
41
42
  const { referenceImages, from, agent, made, useStreaming, boardToken, childMcpUrl, hostedCallTool, isPersistent, maxMs, resumeTreeGone, resumeSessionId, planRun } = state;
42
43
  const { TREE_GONE_NOTE, NOT_FOUND_NOTE } = resumeNotes(request);
43
44
  const plan = await planRun({ resumeId: resumeSessionId, note: resumeTreeGone ? TREE_GONE_NOTE : null });
@@ -95,9 +96,9 @@ export async function startRun(ctx, state, { timing, receipt, preparation, finis
95
96
  // (it stays read-only).
96
97
  const askPermission = boardToken && request.planMode !== "draft" && (useStreaming || agentFor(agent) === "codex" || chosen.spec?.protocol === "acp")
97
98
  ? createPermissionAsker({
98
- folder: root, cwd: made.cwd, agentLabel: AGENTS[agentFor(agent)]?.label ?? "The agent", session, boardId, fromId: from, env: hostedEnv,
99
+ folder: root, cwd: made.cwd, agentLabel: AGENTS[agentFor(agent)]?.label ?? "The agent", session, boardId, fromId: from, env: hostedEnv, automation: fromAutomation === true,
99
100
  callTool: hostedCallTool, poll: rowsPoll, log: (message) => log(`[${id}] ${message}`),
100
- pollMs: settings.permissionPollMs ?? 2000,
101
+ pollMs: settings.permissionPollMs ?? 2000, askTool: AGENTS[agentFor(agent)]?.boardTool("ask_user"),
101
102
  })
102
103
  : undefined;
103
104
 
@@ -129,7 +130,14 @@ export async function startRun(ctx, state, { timing, receipt, preparation, finis
129
130
 
130
131
  const makeRunOpts = runOptionsFor(ctx, state, { imageSuffix, onChunk, childEnvObj, stopCheck, answerPoll, askPermission, receipt });
131
132
  const runOpts = makeRunOpts(plan);
132
- const runFn = runnerFor(agent, useStreaming);
133
+ // A child that left something running in its group after Stop keeps the
134
+ // recovery record, so the next pass can still find and end it (#6557).
135
+ const runner = runnerFor(agent, useStreaming);
136
+ const runFn = async (options) => {
137
+ const outcome = await runner(options);
138
+ if (outcome?.descendantsRemain) await settings.recoveryTracker?.retain(outcome.descendantsRemain);
139
+ return outcome;
140
+ };
133
141
 
134
142
  if (settings.stopped?.has(id)) return await finish({ status: "stopped", result: settings.leaseLost?.has(id) ? "STOPPED\n\nRunner connection expired before the process was started.\n" : "STOPPED\n\nStopped by user request before the process was started.\n", finished_at: new Date().toISOString() });
135
143
  preparation.complete();
@@ -208,6 +216,8 @@ function runOptionsFor({ id, request, runnerApi, rowsOpts, settings, log }, { ag
208
216
  onChunk,
209
217
  requireResume: request.recovery === true && Boolean(request.resumeSessionId),
210
218
  recoveryGroup: Boolean(settings.recoveryTracker),
219
+ // The server the session recorded survives Stop (ruling A, 2026-09-06).
220
+ keepPids: async () => { const record = await readWorktreeRecord(made.cwd); return record ? [Number(record.pid)] : []; },
211
221
  onProcess: settings.recoveryTracker ? (pid) => settings.recoveryTracker.onProcess(pid, { group: platform !== "win32" }) : undefined,
212
222
  onSession: async (threadId) => {
213
223
  receipt.sidecar = { ...receipt.sidecar, [agentFor(agent) === "codex" ? "codexThreadId" : "claudeSessionId"]: threadId, resumeSessionId: threadId, restartable: true };
@@ -60,6 +60,28 @@ async function retainGroups(record, snapshot, identity, gone, onChange = () => {
60
60
  if (retained.length !== (record.groups ?? []).length) { record.groups = retained; onChange(); }
61
61
  }
62
62
 
63
+ /** A retained record is only a reminder that something may still be running.
64
+ * Once every survivor has exited (or its pid belongs to another process now),
65
+ * delete it, so the run stops holding a slot. Only the record this call kept
66
+ * is removed: a newer run with the same id has a different token. */
67
+ function watchSurvivors(path, token, survivors, { readIdentity, isAlive }) {
68
+ const timer = setInterval(async () => {
69
+ try {
70
+ for (const member of survivors) {
71
+ if (!isAlive(member.pid)) continue;
72
+ const current = await readIdentity(member.pid);
73
+ if (current?.command?.includes("<defunct>")) continue;
74
+ if (sameProcessIdentity(member, current) !== false) return; // still running, or cannot tell
75
+ }
76
+ clearInterval(timer);
77
+ try {
78
+ if (JSON.parse(readFileSync(path, "utf8")).retainedToken === token) unlinkSync(path);
79
+ } catch { /* already replaced or removed */ }
80
+ } catch { /* look again next tick */ }
81
+ }, 2000);
82
+ timer.unref?.();
83
+ }
84
+
63
85
  export async function trackRun(project, run, settings, receipt, { readIdentity = readProcessIdentity, readTable = processTable, readGroups = processGroups, isAlive = alive, now = () => performance.now(), after = setTimeout, cancel = clearTimeout } = {}) {
64
86
  if (!run.lease_generation) return null; // Installed server without fencing.
65
87
  const path = recoveryPath(project, run.id, settings);
@@ -74,6 +96,10 @@ export async function trackRun(project, run, settings, receipt, { readIdentity =
74
96
  host: hostname(), pid: process.pid, ownerStartedAt: owner?.startedAt, ownerCommand: owner?.command, budgetMs: wallClockFor(run.request), workingMs: 0, sidecar: receipt.sidecar,
75
97
  ...(preparedResume ? { launching: true, preparedResume: true } : {}) };
76
98
  let closed = false;
99
+ // Set when a stopped child left a running process behind (#6557): the record
100
+ // is then the only thing that can still end it, so close() must not delete it.
101
+ let retained = false;
102
+ let survivors = [];
77
103
  const write = () => {
78
104
  record.workingMs = Math.ceil(performance.now() - started);
79
105
  record.savedAt = Date.now(); // Recovery charges a surviving agent from here.
@@ -180,12 +206,31 @@ export async function trackRun(project, run, settings, receipt, { readIdentity =
180
206
  registering.add(registration);
181
207
  try { persist(); void output(); } catch { (settings.stopped ??= new Set()).add(run.id); }
182
208
  },
183
- async close({ keep = false } = {}) {
209
+ /** A stopped child left these pids running. Save their identities now, so
210
+ * a restart can anchor and end them (stopOrphan), and let close() keep the
211
+ * record until they are gone. */
212
+ async retain(pids = []) {
213
+ retained = true;
214
+ const found = [];
215
+ for (const pid of pids) {
216
+ const identity = await readIdentity(pid);
217
+ if (identity) found.push({ pid, ...identity });
218
+ }
219
+ survivors = found;
220
+ if (found.length) {
221
+ const seen = new Set(found.map(member => member.pid));
222
+ record.processes = [...found, ...(record.processes ?? []).filter(member => !seen.has(member.pid))];
223
+ }
224
+ record.retainedToken = randomUUID();
225
+ try { write(); } catch { /* the previous save still stands */ }
226
+ },
227
+ async close({ keep = retained } = {}) {
184
228
  closed = true; clearInterval(timer);
185
229
  if (outputTimer) { cancel(outputTimer); outputTimer = null; }
186
230
  resolveOutput?.(); resolveOutput = null; pendingOutput = null;
187
231
  try {
188
232
  if (!keep) { try { unlinkSync(path); } catch (error) { if (error.code !== "ENOENT") throw error; } }
233
+ else if (retained && survivors.length) watchSurvivors(path, record.retainedToken, survivors, { readIdentity, isAlive });
189
234
  } finally { await lock.release(); }
190
235
  },
191
236
  };
@@ -95,6 +95,14 @@ export async function prepareRequestWorkspace(context, services = defaultService
95
95
  const isOwnTree = wantedRecordedTree && typeof ownTreePath === "string" && ownTreePath !== "";
96
96
  if (wantedRecordedTree && !isOwnTree) log(`[${id}] the named worktree ${request.worktreePath} is not this idea's own; not reused`);
97
97
  const reusedTree = isOwnTree ? await reuseWorktree(root, ownTreePath, log, lifecycle) : null;
98
+ // THE REPO LOCK COULD NOT BE HELD (#6558): spawn nothing. The tree is not
99
+ // gone and a fallback would put the session in the checkout the holder is
100
+ // changing, so neither "the copy is gone" nor an unisolated run is true.
101
+ const lockRefusal = (detail) => {
102
+ log(`[${id}] refused: ${detail}`);
103
+ return { ok: false, patch: { status: "error", result: `ERROR\n\nNOTHING WAS SPAWNED AND NOTHING WAS BILLED.\n\n${detail}\n\nRun again once the other repository change has finished.\n`, finished_at: new Date().toISOString() } };
104
+ };
105
+ if (reusedTree?.lockRefused) return lockRefusal(reusedTree.detail);
98
106
  if ((request.recovery === true || (request.continues && isResume)) && wantedRecordedTree && !reusedTree) {
99
107
  return { ok: false, patch: { status: "error", result: "ERROR\n\nThis session cannot continue because its separate copy is gone. Run again to start a new session.\n", finished_at: new Date().toISOString(), sidecar: { ...(request.recovery === true ? { recoveryFailed: true } : {}) } } };
100
108
  }
@@ -118,6 +126,7 @@ export async function prepareRequestWorkspace(context, services = defaultService
118
126
  ? { cwd: root, isolated: false, detail: `Ran in the linked folder per idea setting (worktree off).` }
119
127
  : await makeWorktree(root, id, log, title(request), lifecycle);
120
128
  preparation?.check();
129
+ if (made.lockRefused) return lockRefusal(made.detail);
121
130
 
122
131
  const wantedIsolation = !isChat && !request.cwd && request.useWorktree !== false;
123
132
  if (wantedIsolation && !made.isolated) {
@@ -112,10 +112,11 @@ export async function credentialRemoved({ env = process.env, fetchImpl = fetch,
112
112
  * outside this process (a systemd unit, WMI) starts it with the user's
113
113
  * default environment instead, so the script carries these itself. Keys and
114
114
  * tokens stay out: the uninstall reads the stored sign-in from the home. */
115
- export function carriedEnv(env = process.env) {
115
+ export function carriedEnv(env = process.env, platform = process.platform) {
116
+ // Windows environment names are case-insensitive; retain the supplied Path spelling.
116
117
  const keep = /^(HOME|PATH|USERPROFILE|APPDATA|LOCALAPPDATA|TMPDIR|TEMP|TMP|XDG_[A-Z_]+|(VIEWABLE|GLYTCH)_[A-Z0-9_]+)$/;
117
118
  const secret = /TOKEN|SECRET|KEY|PASSWORD/i;
118
- return Object.fromEntries(Object.entries(env).filter(([name, value]) => typeof value === "string" && keep.test(name) && !secret.test(name)));
119
+ return Object.fromEntries(Object.entries(env).filter(([name, value]) => typeof value === "string" && (keep.test(name) || (platform === "win32" && /^PATH$/i.test(name))) && !secret.test(name)));
119
120
  }
120
121
 
121
122
  /** The detached command: `viewable uninstall --yes`, then, only when it
@@ -125,9 +126,19 @@ export function selfUninstallCommand({ execPath = process.execPath, cliPath = CL
125
126
  const npm = globalPackageDir(cliPath, target) ? npmCommand(["uninstall", "-g", "viewable-one"], target) : null;
126
127
  const script = [
127
128
  'const { spawnSync } = require("node:child_process");',
128
- `const env = { ...process.env, ...${JSON.stringify(carriedEnv(env))} };`,
129
+ // The launcher may spell Path differently from the daemon. Collapse aliases
130
+ // before either spawn so Node cannot discard the carried search path.
131
+ 'const mergeEnv = (base, carried) => {',
132
+ ' const merged = { ...base, ...carried };',
133
+ ' if (process.platform === "win32") {',
134
+ ' const key = Object.keys(carried).find((name) => /^path$/i.test(name)) ?? Object.keys(base).find((name) => /^path$/i.test(name));',
135
+ ' for (const name of Object.keys(merged)) if (/^path$/i.test(name) && name !== key) delete merged[name];',
136
+ ' }',
137
+ ' return merged;',
138
+ '};',
139
+ `const env = mergeEnv(process.env, ${JSON.stringify(carriedEnv(env, options.platform))});`,
129
140
  `const done = spawnSync(process.execPath, [${JSON.stringify(cliPath)}, "uninstall", "--yes"], { stdio: "ignore", env });`,
130
- npm ? `if (done.status === 0) spawnSync(${JSON.stringify(npm.file)}, ${JSON.stringify(npm.args)}, { stdio: "ignore", env: { ...env, ...${JSON.stringify(carriedEnv(npm.env))} }, shell: false });` : "",
141
+ npm ? `if (done.status === 0) spawnSync(${JSON.stringify(npm.file)}, ${JSON.stringify(npm.args)}, { stdio: "ignore", env: mergeEnv(env, ${JSON.stringify(carriedEnv(npm.env, options.platform))}), shell: false });` : "",
131
142
  ].join("\n");
132
143
  return { command: execPath, args: ["-e", script], script };
133
144
  }