pi-better-background-tasks 0.18.0 → 0.20.0

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.
Files changed (63) hide show
  1. package/README.md +25 -13
  2. package/package.json +1 -1
  3. package/runtime-client/artifacts/darwin-arm64.gz +0 -0
  4. package/runtime-client/artifacts/darwin-arm64.json +1 -1
  5. package/runtime-client/artifacts/darwin-x64.gz +0 -0
  6. package/runtime-client/artifacts/darwin-x64.json +1 -1
  7. package/runtime-client/artifacts/linux-arm64.gz +0 -0
  8. package/runtime-client/artifacts/linux-arm64.json +1 -1
  9. package/runtime-client/artifacts/linux-x64.gz +0 -0
  10. package/runtime-client/artifacts/linux-x64.json +1 -1
  11. package/runtime-client/src/runtime/client.mjs +30 -3
  12. package/runtime-client/src/runtime/root.mjs +5 -2
  13. package/runtime-client/src/runtime/work-client.mjs +150 -7
  14. package/src/adapter-contract.ts +1 -1
  15. package/src/goal-provider.ts +31 -16
  16. package/src/index.ts +25 -9
  17. package/src/managed-authority.ts +5 -3
  18. package/src/managed-client.ts +20 -7
  19. package/src/managed-frontend.ts +135 -19
  20. package/src/navigator-provider.ts +19 -5
  21. package/src/observed-wait-client.ts +10 -0
  22. package/src/observed-waits.ts +321 -53
  23. package/src/process-identity.ts +18 -2
  24. package/src/process.ts +48 -14
  25. package/src/registry.ts +53 -5
  26. package/src/review-settings.ts +18 -0
  27. package/src/runtime.ts +27 -82
  28. package/src/sandbox.ts +14 -11
  29. package/src/shared-callback-batcher.ts +11 -2
  30. package/src/shared-navigator-panels.ts +26 -4
  31. package/src/shared-navigator.ts +244 -40
  32. package/src/shared-operation-coordinator/assignment-observation.mjs +43 -35
  33. package/src/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  34. package/src/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  35. package/src/shared-operation-coordinator/src/background-requests.ts +14 -3
  36. package/src/shared-operation-coordinator/src/discovery.ts +5 -3
  37. package/src/shared-operation-coordinator/src/operations.ts +50 -2
  38. package/src/shared-operation-coordinator/src/outbox.ts +9 -0
  39. package/src/shared-operation-coordinator/src/result-supervision.ts +12 -0
  40. package/src/shared-operation-coordinator/src/rows.ts +2 -0
  41. package/src/shared-operation-coordinator/src/schema.ts +40 -24
  42. package/src/shared-operation-coordinator/src/store.ts +40 -8
  43. package/src/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  44. package/src/shared-operation-coordinator/src/types.ts +5 -1
  45. package/src/shared-sandbox-core.ts +1 -1
  46. package/src/shared-work-client.mjs +150 -7
  47. package/src/stall.ts +7 -4
  48. package/src/supervised-progress.ts +43 -0
  49. package/src/supervisor/README.md +1 -4
  50. package/src/supervisor/emit-runner.mjs +1 -0
  51. package/src/supervisor/generated/process-identity.mjs +20 -2
  52. package/src/supervisor/generated/process.mjs +52 -14
  53. package/src/supervisor/generated/runner.mjs +47 -4
  54. package/src/supervisor/generated/store.mjs +3 -3
  55. package/src/supervisor/generated/watch-fingerprint.mjs +69 -0
  56. package/src/supervisor/runner.ts +38 -3
  57. package/src/supervisor/store.ts +3 -3
  58. package/src/supervisor/supervisor.ts +6 -3
  59. package/src/task-diagnostics.ts +1 -1
  60. package/src/tools.ts +67 -54
  61. package/src/types.ts +7 -3
  62. package/src/watch-fingerprint.ts +70 -0
  63. package/src/work-observation.ts +46 -19
@@ -1,3 +1,4 @@
1
+ import { readFileSync } from "node:fs";
1
2
  import { execFileSync } from "node:child_process";
2
3
 
3
4
  /**
@@ -29,10 +30,11 @@ interface TokenMemoEntry {
29
30
 
30
31
  const tokenMemo = new Map<number, TokenMemoEntry>();
31
32
 
32
- function readTokenUncached(pid: number): string | undefined {
33
+ function readTokenUncached(pid: number, admission = false): string | undefined {
33
34
  if (!Number.isInteger(pid) || pid <= 0 || process.platform === "win32") return undefined;
34
35
  try {
35
- const output = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
36
+ const output = execFileSync(admission ? "/bin/ps" : "ps", ["-o", "lstart=", "-p", String(pid)], {
37
+ env: admission ? { LC_ALL: "C", TZ: "UTC0", PATH: "/usr/bin:/bin" } : process.env,
36
38
  encoding: "utf8",
37
39
  stdio: ["ignore", "pipe", "ignore"],
38
40
  timeout: 2_000,
@@ -43,6 +45,20 @@ function readTokenUncached(pid: number): string | undefined {
43
45
  }
44
46
  }
45
47
 
48
+ // Admission crosses process environments; stored task tokens retain their original format.
49
+ export function readAdmissionStartToken(pid: number): string | undefined {
50
+ if (process.platform !== "linux") return readTokenUncached(pid, true);
51
+ if (!Number.isInteger(pid) || pid <= 0) return undefined;
52
+ try {
53
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
54
+ // Fields after the parenthesized command start at field 3. Start time is field 22.
55
+ const start = stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
56
+ return start && /^\d+$/.test(start) ? start : undefined;
57
+ } catch {
58
+ return undefined;
59
+ }
60
+ }
61
+
46
62
  function remember(pid: number, token: string | undefined, now: number): void {
47
63
  if (tokenMemo.size >= TOKEN_MEMO_MAX_ENTRIES) {
48
64
  // Drop expired entries first; only evict live ones if that was not enough.
package/src/process.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
- import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, writeSync } from "node:fs";
3
- import { dirname, join } from "node:path";
2
+ import { accessSync, appendFileSync, closeSync, constants, existsSync, mkdirSync, openSync, readFileSync, writeSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join, win32 } from "node:path";
4
5
  import type { ChildProcess } from "node:child_process";
5
6
  import type { CommandResult, CommandSpec, StepGateFailure } from "./types.js";
6
7
 
@@ -17,7 +18,8 @@ const WINDOWS_BASH_CANDIDATES = [
17
18
  * POSIX keeps `/bin/bash`. Windows has no `/bin/bash`, and the `bash.exe` found
18
19
  * on PATH is usually the WSL launcher in System32 or the WindowsApps alias,
19
20
  * either of which would run the command inside WSL instead of Windows. Prefer
20
- * an explicit override, then Git for Windows, then a non-WSL `bash.exe` on PATH.
21
+ * an explicit override, then Pi's shellPath, Git for Windows, and a non-WSL
22
+ * `bash.exe` on PATH.
21
23
  *
22
24
  * Resolved lazily at spawn time, not module load: env-injection extensions
23
25
  * (e.g. pi-env) may apply settings.json `env` values after this module is
@@ -25,22 +27,53 @@ const WINDOWS_BASH_CANDIDATES = [
25
27
  *
26
28
  * Exposed for tests and reuse.
27
29
  */
28
- export function resolveDefaultShell(): string {
30
+ export function resolveDefaultShell(shellPath?: string): string {
29
31
  const fromEnv = process.env.PI_BETTER_BACKGROUND_TASKS_SHELL;
30
32
  if (fromEnv) return fromEnv;
31
33
  if (process.platform !== "win32") return "/bin/bash";
32
- for (const candidate of WINDOWS_BASH_CANDIDATES) {
34
+ const configured = shellPath ?? readWindowsShellSetting();
35
+ const tried: string[] = [];
36
+ if (configured?.trim()) {
37
+ const candidate = /^~[\\/]/.test(configured) ? win32.join(homedir(), configured.slice(2)) : configured;
38
+ tried.push(candidate);
39
+ try {
40
+ accessSync(candidate, constants.F_OK);
41
+ return candidate;
42
+ } catch { /* An unavailable setting leaves standard Windows discovery enabled. */ }
43
+ }
44
+ const gitCandidates = [process.env.ProgramFiles, process.env["ProgramFiles(x86)"]]
45
+ .filter((directory): directory is string => Boolean(directory))
46
+ .map(directory => win32.join(directory, "Git", "bin", "bash.exe"));
47
+ for (const candidate of new Set([...gitCandidates, ...WINDOWS_BASH_CANDIDATES])) {
48
+ tried.push(candidate);
33
49
  if (existsSync(candidate)) return candidate;
34
50
  }
35
- for (const dir of (process.env.PATH ?? "").split(";")) {
51
+ for (const dir of (process.env.PATH ?? process.env.Path ?? "").split(";")) {
36
52
  const trimmed = dir.trim();
37
53
  if (!trimmed || /(^|[\\/])(system32|windowsapps)([\\/]|$)/i.test(trimmed)) continue;
38
- const candidate = join(trimmed, "bash.exe");
54
+ const candidate = win32.join(trimmed, "bash.exe");
55
+ tried.push(candidate);
39
56
  if (existsSync(candidate)) return candidate;
40
57
  }
41
- // Nothing usable found: keep the POSIX default so the failure surfaces as a
42
- // logged spawn error for the task instead of crashing the whole host process.
43
- return "/bin/bash";
58
+ throw new Error("No Bash executable found for Windows Background tasks. Set Pi's shellPath in settings.json or "
59
+ + "PI_BETTER_BACKGROUND_TASKS_SHELL to a working bash.exe. Searched:\n " + [...new Set(tried)].join("\n "));
60
+ }
61
+
62
+ function readWindowsShellSetting(): string | undefined {
63
+ const agentDir = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
64
+ try {
65
+ const settings = JSON.parse(readFileSync(join(agentDir, "settings.json"), "utf8"));
66
+ return typeof settings?.shellPath === "string" ? settings.shellPath : undefined;
67
+ } catch { return undefined; }
68
+ }
69
+
70
+ /** Capture effective session settings before dispatching a Windows launch. */
71
+ export function resolveWindowsLaunchShell(pi: object): string | undefined {
72
+ if (process.platform !== "win32") return undefined;
73
+ const override = process.env.PI_BETTER_BACKGROUND_TASKS_SHELL;
74
+ if (override) return override;
75
+ const settings = (pi as { getSettings?(): { shellPath?: unknown } }).getSettings?.();
76
+ return resolveDefaultShell(typeof settings?.shellPath === "string" ? settings.shellPath : undefined);
44
77
  }
45
78
 
46
79
  /** How long a timed-out process group has to exit on SIGTERM before SIGKILL. */
@@ -66,8 +99,8 @@ export function validateCommandSpec(spec: CommandSpec): void {
66
99
  /** Convert a Windows path to the `/c/...` form MSYS bash resolves in redirections. Exposed for tests and reuse. */
67
100
  export function toMsysPath(path: string): string {
68
101
  const forward = path.replace(/\\/g, "/");
69
- const drive = /^([A-Za-z]):(\/.+)$/.exec(forward);
70
- return drive ? `/${drive[1].toLowerCase()}${drive[2]}` : forward;
102
+ const [, drive, rest] = /^([A-Za-z]):(\/.+)$/.exec(forward) ?? [];
103
+ return drive && rest ? `/${drive.toLowerCase()}${rest}` : forward;
71
104
  }
72
105
 
73
106
  /** Single-quote a value for safe literal use in a bash script line. Exposed for tests and reuse. */
@@ -155,7 +188,7 @@ export function parseStepGateFailure(logText: string, id: string): StepGateFailu
155
188
  const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
156
189
  if (!line.startsWith(marker) || !line.endsWith(" ---")) continue;
157
190
  const match = /^--- step gate \[[^\]]+\]: first failing step exit=(-?\d+); shell exit=(-?\d+): (.*) ---$/.exec(line);
158
- if (!match) continue;
191
+ if (!match || match[3] === undefined) continue;
159
192
  const stepExitCode = Number(match[1]);
160
193
  const shellExitCode = Number(match[2]);
161
194
  if (!Number.isInteger(stepExitCode) || stepExitCode === 0) continue;
@@ -507,7 +540,8 @@ export function commandExecution(spec: CommandSpec): { execPath: string; execArg
507
540
  const [command, ...args] = spec.argv!;
508
541
  return { execPath: command!, execArgs: args };
509
542
  }
510
- return { execPath: resolveDefaultShell(), execArgs: [spec.loginShell === false ? "-c" : "-lc", spec.command!] };
543
+ const resolved = process.platform === "win32" ? spec.resolvedWindowsShell : undefined;
544
+ return { execPath: resolved ?? resolveDefaultShell(), execArgs: [spec.loginShell === false ? "-c" : "-lc", spec.command!] };
511
545
  }
512
546
 
513
547
  /** Stdio for a spawned task: stdin is always ignored; stdout/stderr are piped (collected) or ignored (redirected into the log by the child itself). */
package/src/registry.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import { mkdirSync, readFileSync, readdirSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import type { BackgroundTaskCallbackOrigin, BackgroundTaskMeta } from "./types.js";
@@ -11,7 +11,7 @@ const metaCache = new Map<string, BackgroundTaskMeta>();
11
11
  // cross-process index changes before any cached IDs are reused.
12
12
  const indexIdsCache = new Map<string, { ids: Set<string>; signature: string }>();
13
13
  const initializedIndexes = new Set<string>();
14
- const metaChangedListeners = new Set<() => void>();
14
+ const metaChangedListeners = new Set<(meta?: BackgroundTaskMeta) => void>();
15
15
  const registryIo = { fullDirectoryReads: 0, indexDirectoryReads: 0, metadataFileReads: 0, terminalMetadataFileReads: 0, indexRevisionChecks: 0 };
16
16
 
17
17
  export interface RegistryIoMetrics {
@@ -84,11 +84,11 @@ export function writeMeta(meta: BackgroundTaskMeta): void {
84
84
  metaCache.set(meta.id, meta);
85
85
  indexMeta(meta);
86
86
  for (const listener of metaChangedListeners) {
87
- try { listener(); } catch { /* best effort */ }
87
+ try { listener(meta); } catch { /* best effort */ }
88
88
  }
89
89
  }
90
90
 
91
- export function onMetaChanged(listener: () => void): () => void {
91
+ export function onMetaChanged(listener: (meta?: BackgroundTaskMeta) => void): () => void {
92
92
  metaChangedListeners.add(listener);
93
93
  return () => metaChangedListeners.delete(listener);
94
94
  }
@@ -190,8 +190,9 @@ export function removeMeta(meta: BackgroundTaskMeta): boolean {
190
190
  metaCache.delete(meta.id);
191
191
  removeIndexEntry(originIndexDir(originOf(meta)), meta.id);
192
192
  removeIndexEntry(originActiveIndexDir(originOf(meta)), meta.id);
193
+ removeIndexEntry(recentPath(originOf(meta)), meta.id);
193
194
  for (const listener of metaChangedListeners) {
194
- try { listener(); } catch { /* best effort */ }
195
+ try { listener(meta); } catch { /* best effort */ }
195
196
  }
196
197
  return true;
197
198
  } catch {
@@ -251,6 +252,7 @@ export function listActiveMetasForOrigin(origin: BackgroundTaskCallbackOrigin):
251
252
  export function observeMetasForOrigin(origin: BackgroundTaskCallbackOrigin, activeOnly = true): BackgroundTaskMeta[] {
252
253
  const directory = activeOnly ? originActiveIndexDir(origin) : originIndexDir(origin);
253
254
  let ids: string[];
255
+ registryIo.indexDirectoryReads++;
254
256
  try { ids = readdirSync(directory).filter(id => id !== ".initialized"); }
255
257
  catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; }
256
258
  return ids.map(id => {
@@ -261,6 +263,42 @@ export function observeMetasForOrigin(origin: BackgroundTaskCallbackOrigin, acti
261
263
  && (!activeOnly || meta.status === "running")).sort((a, b) => b.startedAt - a.startedAt);
262
264
  }
263
265
 
266
+ const RECENT_LIMIT = 256;
267
+ const RECENT_MS = 30000;
268
+ function recentPath(origin: BackgroundTaskCallbackOrigin): string {
269
+ return join(baseDir(), "by-origin-recent", originKey(origin));
270
+ }
271
+ function recentEntries(origin: BackgroundTaskCallbackOrigin): Array<{ id: string; observedAt: number }> {
272
+ const directory = recentPath(origin);
273
+ try {
274
+ registryIo.indexDirectoryReads++;
275
+ const entries = readdirSync(directory).filter(id => !id.startsWith(".")).flatMap(id => {
276
+ try { registryIo.indexRevisionChecks++; return [{ id, observedAt: statSync(join(directory, id)).mtimeMs }]; }
277
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; }
278
+ }).sort((a, b) => b.observedAt - a.observedAt || b.id.localeCompare(a.id));
279
+ return entries.filter(entry => Date.now() - entry.observedAt < RECENT_MS).slice(0, RECENT_LIMIT);
280
+ } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; }
281
+ }
282
+
283
+ export function recentMetaDeadline(origin: BackgroundTaskCallbackOrigin): number[] {
284
+ return recentEntries(origin).map(entry => entry.observedAt + RECENT_MS);
285
+ }
286
+
287
+ /** Exact cooperative source identity; no metadata or historical enumeration. */
288
+ export function observationRevisionForOrigin(origin: BackgroundTaskCallbackOrigin): string {
289
+ return [originActiveIndexDir(origin), recentPath(origin)].map(indexDirectorySignature).join(";");
290
+ }
291
+
292
+ /** Bounded cooperative writes, including results written before the first reader. */
293
+ export function observeRecentMetasForOrigin(origin: BackgroundTaskCallbackOrigin): BackgroundTaskMeta[] {
294
+ return recentEntries(origin).map(entry => {
295
+ const record = inspectMeta(entry.id);
296
+ if (record.found && !record.meta) throw new Error(`Unverified background task ${entry.id}: ${record.error}`);
297
+ return record.meta;
298
+ }).filter((meta): meta is BackgroundTaskMeta =>
299
+ !!meta && belongsToOrigin(meta, origin) && meta.dismissedAt === undefined);
300
+ }
301
+
264
302
  function readMetaForSweep(id: string): BackgroundTaskMeta | undefined {
265
303
  const cached = metaCache.get(id);
266
304
  if (cached && isTerminalStatus(cached.status)) return cached;
@@ -308,6 +346,16 @@ function indexMeta(meta: BackgroundTaskMeta): void {
308
346
  const activeDirectory = originActiveIndexDir(originOf(meta));
309
347
  if (meta.status === "running") writeIndexEntry(activeDirectory, meta.id);
310
348
  else removeIndexEntry(activeDirectory, meta.id);
349
+ const origin = originOf(meta), recentDirectory = recentPath(origin);
350
+ mkdirSync(recentDirectory, { recursive: true });
351
+ // Independent pointers preserve concurrent writers; prune only this bounded
352
+ // recent-write accelerator, never the authoritative metadata or history.
353
+ const candidates = readdirSync(recentDirectory).filter(id => !id.startsWith("."));
354
+ const retained = new Set(recentEntries(origin).filter(entry => entry.id !== meta.id).slice(0, RECENT_LIMIT - 1).map(entry => entry.id));
355
+ for (const id of candidates) if (id !== meta.id && !retained.has(id)) removeIndexEntry(recentDirectory, id);
356
+ const temporary = join(recentDirectory, `.${meta.id}.${process.pid}.next`);
357
+ writeFileSync(temporary, "");
358
+ renameSync(temporary, join(recentDirectory, meta.id));
311
359
  } catch {
312
360
  // Indexes are accelerators; meta.json remains authoritative.
313
361
  }
@@ -0,0 +1,18 @@
1
+ import { readHarnessSetting, updateHarnessSetting, type HarnessSettingsSeams } from "./shared-harness-settings.ts";
2
+
3
+ export const DEFAULT_BACKGROUND_REVIEW_INTERVAL_MINUTES = 10;
4
+ const key = "backgroundReviewIntervalMinutes";
5
+
6
+ function validMinutes(value: unknown): value is number {
7
+ return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 1440;
8
+ }
9
+
10
+ export function readBackgroundReviewInterval(seams?: HarnessSettingsSeams): number {
11
+ const value = readHarnessSetting(key, seams);
12
+ return validMinutes(value) ? value : DEFAULT_BACKGROUND_REVIEW_INTERVAL_MINUTES;
13
+ }
14
+
15
+ export function saveBackgroundReviewInterval(minutes: number, seams?: HarnessSettingsSeams): void {
16
+ if (!validMinutes(minutes)) throw new Error("Background review interval must be a whole number from 1 to 1440 minutes.");
17
+ updateHarnessSetting(key, () => minutes, seams);
18
+ }
package/src/runtime.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { createHash } from "node:crypto";
1
+ import { WATCH_FINGERPRINT_VERSION, watchOutcomeFingerprint } from "./watch-fingerprint.js";
2
2
  import { readFileSync, statSync } from "node:fs";
3
3
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
4
  import { appendLine, appendTaskOutput, appendWatchResult, retainLogTail, resolveMaxLogBytes } from "./logs.js";
5
5
  import { evaluateCondition, validateCondition } from "./conditions.js";
6
- import { parseStepGateFailure, processExists, runCommandOnce, spawnCommand, STEP_GATE_COMMAND_ENV, stepGateScript, stopProcessGroup } from "./process.js";
6
+ import { commandExecution, parseStepGateFailure, processExists, resolveWindowsLaunchShell, runCommandOnce, spawnCommand, STEP_GATE_COMMAND_ENV, stepGateScript, stopProcessGroup } from "./process.js";
7
7
  import { currentProcessStartToken, readProcessStartToken } from "./process-identity.js";
8
8
  import { DEFAULT_TMUX_BOOTSTRAP_TIMEOUT_MS, expandSshRemoteTaskPreset } from "./remote-task-preset.js";
9
9
  import type { RemoteRunner, ResolvedSshRemoteTask } from "./remote-task-preset.js";
@@ -27,7 +27,7 @@ import type {
27
27
  TerminalResult,
28
28
  } from "./types.js";
29
29
  import { observeTaskStallAttention } from "./stall-attention.js";
30
- import { isTerminalStatus } from "./types.js";
30
+ import { FIRST_WATCH_CHECK_WAIT_MS, isTerminalStatus } from "./types.js";
31
31
 
32
32
  export type ActiveSessionProvider = () => BackgroundTaskCallbackOrigin | undefined;
33
33
 
@@ -98,7 +98,7 @@ export const DEFAULT_WATCH_TIMEOUT_SECONDS = 15 * 60;
98
98
  /** Consecutive blind checks (exit 0, stderr, no condition matched) before a watch is flagged (#359). */
99
99
  export const DEFAULT_BLIND_CHECKS = 3;
100
100
  /** How long bg_task_watch waits for the first check before returning (#359). */
101
- export const FIRST_WATCH_CHECK_WAIT_MS = 15_000;
101
+ export { FIRST_WATCH_CHECK_WAIT_MS } from "./types.js";
102
102
  /** How to fix a false alarm: some tools write progress or warnings to stderr on success. */
103
103
  export const BLIND_CHECK_HINT = "If the stderr is expected (progress or warnings), redirect it (2>/dev/null) or set blind_checks:0.";
104
104
  /**
@@ -110,7 +110,8 @@ export type FirstCheckWaitEnd = "timeout" | "aborted" | "suspended";
110
110
  export type FirstCheckOutcome = FirstWatchCheck | { pending: FirstCheckWaitEnd; waitedMs: number } | undefined;
111
111
 
112
112
  /** Each cached extension factory owns its scheduling and suspension state. */
113
- export function createBackgroundTaskRuntime(attention = createFailureAttention(), deliverCompletion?: (origin: BackgroundTaskCallbackOrigin | undefined, event: Parameters<ReturnType<typeof getCallbackBatcher>["enqueue"]>[0]) => void, admission?: { assert(): void; prepared?(id: string): void }) {
113
+ export function createBackgroundTaskRuntime(attention = createFailureAttention(), deliverCompletion?: (origin: BackgroundTaskCallbackOrigin | undefined, event: Parameters<ReturnType<typeof getCallbackBatcher>["enqueue"]>[0]) => void, admission?: { assert(): void; prepared?(id: string): void },
114
+ sourceWork: (kind: string, id: string, work: () => unknown, dueAt?: number) => unknown = (_kind, _id, work) => work()) {
114
115
  const { resumeFailureAttention, scheduleFailureAttention, stopFailureAttention, suspendFailureAttention } = attention;
115
116
  const watcherTimers = new Map<string, ReturnType<typeof setTimeout>>();
116
117
  const remoteSessionTimers = new Map<string, ReturnType<typeof setTimeout>>();
@@ -314,6 +315,7 @@ function spawnTask(
314
315
  // launch cwd is passed so a relative alias resolves where the task will run.
315
316
  assertBackgroundExecutionAllowed(params, sandboxPlan, { remote: Boolean(params.ssh), cwd });
316
317
  const commandLimits = backgroundExecutionLimits(sandboxPlan);
318
+ const resolvedWindowsShell = params.ssh ? undefined : resolveWindowsLaunchShell(pi);
317
319
  const id = nextTaskId();
318
320
  admission?.prepared?.(id);
319
321
  const logPath = logPathFor(id);
@@ -329,7 +331,7 @@ function spawnTask(
329
331
  remote: params.remote,
330
332
  }, dependencies.remoteRunner)
331
333
  : undefined;
332
- const operatorSpec: CommandSpec = remoteTask?.commandSpec ?? { ...params, cwd, shell: params.shell ?? true };
334
+ const operatorSpec: CommandSpec = remoteTask?.commandSpec ?? { ...params, cwd, shell: params.shell ?? true, resolvedWindowsShell };
333
335
  const commandSpec = withStepGate(operatorSpec, id, stepGated);
334
336
  const sandboxNotices: string[] = [];
335
337
  const launchSpec = remoteTask
@@ -517,7 +519,8 @@ function scheduleRemoteSessionPoll(
517
519
  ): void {
518
520
  clearRemoteSessionTimer(id);
519
521
  if (scheduledWorkSuspended) return;
520
- const timer = setTimeout(() => void pollRemoteSession(pi, id, getActiveSession), delayMs);
522
+ const dueAt = Date.now() + delayMs;
523
+ const timer = setTimeout(() => void sourceWork("remote-poll", id, () => scheduledWorkSuspended ? undefined : pollRemoteSession(pi, id, getActiveSession), dueAt), delayMs);
521
524
  timer.unref();
522
525
  remoteSessionTimers.set(id, timer);
523
526
  }
@@ -627,6 +630,7 @@ function startWatchTask(
627
630
  const sandboxPlan = resolveForegroundSandboxPlan(pi, !!params.ssh, params, "bg_task_watch");
628
631
  assertBackgroundExecutionAllowed(params, sandboxPlan, { remote: Boolean(params.ssh), cwd });
629
632
  const commandLimits = backgroundExecutionLimits(sandboxPlan);
633
+ const resolvedWindowsShell = params.ssh || params.shell === false ? undefined : resolveWindowsLaunchShell(pi);
630
634
  const id = nextTaskId();
631
635
  admission?.prepared?.(id);
632
636
  const now = Date.now();
@@ -641,11 +645,12 @@ function startWatchTask(
641
645
  remote: params.remote,
642
646
  }, dependencies.remoteRunner)
643
647
  : undefined;
644
- const commandSpec: CommandSpec = remoteTask?.commandSpec ?? { ...params, cwd, shell: params.shell ?? true };
648
+ const commandSpec: CommandSpec = remoteTask?.commandSpec ?? { ...params, cwd, shell: params.shell ?? true, resolvedWindowsShell };
645
649
  const sandboxNotices: string[] = [];
646
650
  const launchSpec = remoteTask
647
651
  ? commandSpec
648
652
  : confineCommandSpec(commandSpec, sandboxPlan, sandboxProfilePathFor(id), {}, (line) => sandboxNotices.push(line), "bg_task_watch");
653
+ const invocation = resolvedWindowsShell ? commandExecution(launchSpec) : undefined;
649
654
  const meta = withCommandPolicy({
650
655
  id,
651
656
  name: params.name,
@@ -663,7 +668,7 @@ function startWatchTask(
663
668
  shell: commandSpec.shell,
664
669
  cwd,
665
670
  env: params.env,
666
- launchArgv: launchArgvOf(commandSpec, launchSpec),
671
+ launchArgv: invocation ? [invocation.execPath, ...invocation.execArgs] : launchArgvOf(commandSpec, launchSpec),
667
672
  sandbox: sandboxProvenance(sandboxPlan, !!remoteTask),
668
673
  maxLogBytes: resolveMaxLogBytes(params.max_log_bytes),
669
674
  spawnPid: process.pid,
@@ -735,6 +740,9 @@ function resumeRunningTask(
735
740
  scheduleLogRetention(pi, meta.id, getActiveSession);
736
741
  const remoteTask = resolvePersistedRemoteTask(meta, dependencies.remoteRunner);
737
742
  if (meta.kind === "command_watch") {
743
+ // Shared display refreshes can revisit an already supervised watch. They
744
+ // must not replace its captured interval with a new immediate poll.
745
+ if (watcherTimers.has(meta.id) || activePolls.has(meta.id)) return meta;
738
746
  scheduleWatch(pi, meta.id, 0, getActiveSession, remoteTask
739
747
  ? (timeoutMs) => remoteTask.runOnce(undefined, timeoutMs)
740
748
  : dependencies.watchPollRunner);
@@ -814,7 +822,8 @@ function scheduleHandoff(
814
822
  };
815
823
  const arm = () => {
816
824
  if (scheduledWorkSuspended) return;
817
- const timer = setTimeout(check, delayMs);
825
+ const dueAt = Date.now() + delayMs;
826
+ const timer = setTimeout(() => sourceWork("handoff", id, () => { if (!scheduledWorkSuspended) check(); }, dueAt), delayMs);
818
827
  timer.unref();
819
828
  handoffTimers.set(id, timer);
820
829
  };
@@ -957,7 +966,8 @@ function scheduleWatch(
957
966
  ): void {
958
967
  clearWatchTimer(id);
959
968
  if (scheduledWorkSuspended) return;
960
- const timer = setTimeout(() => void pollWatch(pi, id, getActiveSession, runOnce), delayMs);
969
+ const dueAt = Date.now() + delayMs;
970
+ const timer = setTimeout(() => void sourceWork("watch", id, () => scheduledWorkSuspended ? undefined : pollWatch(pi, id, getActiveSession, runOnce), dueAt), delayMs);
961
971
  timer.unref();
962
972
  watcherTimers.set(id, timer);
963
973
  }
@@ -1260,7 +1270,8 @@ function scheduleProcessTimeout(
1260
1270
  clearProcessTimeout(id);
1261
1271
  if (scheduledWorkSuspended) return;
1262
1272
  const delay = Math.max(0, deadlineAt - Date.now());
1263
- const timer = setTimeout(() => void timeoutProcess(pi, id, getActiveSession), delay);
1273
+ const dueAt = deadlineAt;
1274
+ const timer = setTimeout(() => void sourceWork("process-deadline", id, () => scheduledWorkSuspended ? undefined : timeoutProcess(pi, id, getActiveSession), dueAt), delay);
1264
1275
  timer.unref();
1265
1276
  processTimeoutTimers.set(id, timer);
1266
1277
  }
@@ -1459,7 +1470,9 @@ function launchArgvOf(commandSpec: CommandSpec, launchSpec: CommandSpec): string
1459
1470
  function scheduleLogRetention(pi: ExtensionAPI, id: string, getActiveSession?: ActiveSessionProvider): void {
1460
1471
  stopLogRetention(id);
1461
1472
  if (scheduledWorkSuspended) return;
1462
- const timer = setInterval(() => {
1473
+ let dueAt = Date.now() + LOG_RETENTION_CHECK_MS;
1474
+ const timer = setInterval(() => { const due = dueAt; dueAt = Date.now() + LOG_RETENTION_CHECK_MS; return sourceWork("log-retention", id, () => {
1475
+ if (scheduledWorkSuspended) return;
1463
1476
  const meta = readMeta(id);
1464
1477
  if (!meta || meta.status !== "running") {
1465
1478
  stopLogRetention(id);
@@ -1467,7 +1480,7 @@ function scheduleLogRetention(pi: ExtensionAPI, id: string, getActiveSession?: A
1467
1480
  }
1468
1481
  if (meta.kind === "process") enforceLogRetention(meta);
1469
1482
  if (observeTaskStallAttention(meta)) scheduleFailureAttention(pi, id, getActiveSession);
1470
- }, LOG_RETENTION_CHECK_MS);
1483
+ }, due); }, LOG_RETENTION_CHECK_MS);
1471
1484
  timer.unref();
1472
1485
  logRetentionTimers.set(id, timer);
1473
1486
  }
@@ -1530,74 +1543,6 @@ function extractLastState(result: { stdout: string }): unknown {
1530
1543
  }
1531
1544
  }
1532
1545
 
1533
- /** Version tag of the watch outcome fingerprint. A value from another version is adopted, never compared. */
1534
- const WATCH_FINGERPRINT_VERSION = "v1";
1535
- /** OSC and CSI control sequences are display markup, not content. */
1536
- const TERMINAL_ESCAPE = /\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)|\u001b\[[0-?]*[ -/]*[@-~]/g;
1537
-
1538
- /**
1539
- * Text as the terminal would settle it. Redraw frames and control sequences are
1540
- * display churn: repainting the same visible line is not a new observation.
1541
- */
1542
- function settledTerminalText(text: string): string {
1543
- return text
1544
- .replace(TERMINAL_ESCAPE, "")
1545
- .split("\n")
1546
- .map((line) => {
1547
- // A CR immediately before LF ends the line; any other CR overwrites it in place.
1548
- const body = line.endsWith("\r") ? line.slice(0, -1) : line;
1549
- return (body.split("\r").at(-1) ?? "").replace(/[ \t]+$/, "");
1550
- })
1551
- .join("\n")
1552
- .replace(/\n+$/, "");
1553
- }
1554
-
1555
- /** Objects compare by content regardless of key order, so reordered keys are not progress. */
1556
- function canonicalJsonText(value: unknown): string {
1557
- if (Array.isArray(value)) return `[${value.map(canonicalJsonText).join(",")}]`;
1558
- if (value && typeof value === "object") {
1559
- const record = value as Record<string, unknown>;
1560
- const entries = Object.keys(record).sort()
1561
- .map((key) => `${JSON.stringify(key)}:${canonicalJsonText(record[key])}`);
1562
- return `{${entries.join(",")}}`;
1563
- }
1564
- return JSON.stringify(value) ?? "null";
1565
- }
1566
-
1567
- /** stdout compares as JSON content when it parses, and as settled text otherwise. */
1568
- function canonicalWatchStdout(stdout: string): string {
1569
- const settled = settledTerminalText(stdout);
1570
- try {
1571
- return `json:${canonicalJsonText(JSON.parse(settled))}`;
1572
- } catch {
1573
- return `text:${settled}`;
1574
- }
1575
- }
1576
-
1577
- /**
1578
- * What a poll observed, independent of when it ran. Exit status, signal, error,
1579
- * stdout content, and stderr content are included; poll metadata (start time,
1580
- * end time, duration, check count) is deliberately not, so it can never hide a
1581
- * watch that reports the same outcome forever. Watch stdout may carry its own
1582
- * timestamps: projecting meaningful fields is the caller's job, not this
1583
- * fingerprint's guess.
1584
- */
1585
- function watchOutcomeFingerprint(result: CommandResult): string {
1586
- // A runner may report why the check itself could not run; that is part of the
1587
- // observed outcome, not poll metadata.
1588
- const reported = (result as CommandResult & { error?: unknown }).error;
1589
- const error = typeof reported === "string" ? settledTerminalText(reported) : null;
1590
- const payload = JSON.stringify([
1591
- result.exitCode,
1592
- result.signal ?? null,
1593
- result.timedOut === true,
1594
- error,
1595
- canonicalWatchStdout(result.stdout),
1596
- settledTerminalText(result.stderr),
1597
- ]);
1598
- return `${WATCH_FINGERPRINT_VERSION}:${createHash("sha256").update(payload).digest("hex")}`;
1599
- }
1600
-
1601
1546
  /**
1602
1547
  * A watch's state clock advances only when its observed outcome changes. The
1603
1548
  * poll itself is activity (`lastCheckedAt`), not progress, so a stationary
package/src/sandbox.ts CHANGED
@@ -214,7 +214,7 @@ export interface ForegroundSandboxPolicy {
214
214
  readonly denyWrite: readonly string[];
215
215
  /** Human-readable evidence for why `state` is what it is. */
216
216
  readonly reason: string;
217
- readonly permissions?: Readonly<SandboxPermissions & { enabled: boolean }>;
217
+ readonly permissions?: Readonly<SandboxPermissions & { enabled: boolean; processAccess?: "off" | "read" }>;
218
218
  readonly policySource?: "background" | "main-legacy";
219
219
  }
220
220
 
@@ -320,6 +320,7 @@ function readPermissions(value: unknown): ForegroundSandboxPolicy["permissions"]
320
320
  projectFiles: p.projectFiles as SandboxPermissions["projectFiles"],
321
321
  outsideProject: p.outsideProject as SandboxPermissions["outsideProject"],
322
322
  storedCredentials: p.storedCredentials as SandboxPermissions["storedCredentials"],
323
+ ...(p.processAccess === undefined ? {} : { processAccess: p.processAccess as "off" | "read" }),
323
324
  ...(p.shell === undefined ? {} : { shell: p.shell as boolean }),
324
325
  ...(p.commandTimeoutSeconds === undefined ? {} : { commandTimeoutSeconds: p.commandTimeoutSeconds as number | null }),
325
326
  });
@@ -343,16 +344,18 @@ export function observeForegroundSandboxPolicy(pi: unknown): void {
343
344
  try {
344
345
  const published = data && typeof data === "object" ? data as Record<string, unknown> : undefined;
345
346
  const hasBackground = published && Object.hasOwn(published, "background");
346
- const policy = readPolicy(hasBackground ? published.background : data, hasBackground ? "Background tasks" : "Main");
347
- if (hasBackground && !policy) throw new Error("Invalid Background tasks sandbox policy; update permissions in /sandbox.");
348
- const access = (value: unknown): unknown => {
349
- if (!value || typeof value !== "object") return undefined;
350
- return (value as { permissions?: { processAccess?: unknown } }).permissions?.processAccess;
351
- };
352
- mirror.mainConfined = published?.state !== "disabled" && published?.state !== "inactive";
353
- mirror.processAccess = access(data) === "read" && access(hasBackground ? published.background : data) === "read" ? "read" : "off";
354
- if (policy) Object.assign(policy, { policySource: hasBackground ? "background" : "main-legacy" });
355
- if (policy) { mirror.policy = policy; mirror.error = undefined; }
347
+ const main = readPolicy(data);
348
+ const policy = hasBackground ? readPolicy(published.background, "Background tasks") : main;
349
+ if (hasBackground && (!main || !policy)) throw new Error("Invalid Background tasks sandbox policy; update permissions in /sandbox.");
350
+ if (!policy || !main) return;
351
+ const isOff = (scope: ForegroundSandboxPolicy) => scope.state === "disabled" || scope.state === "inactive";
352
+ const allowsRead = (scope: ForegroundSandboxPolicy) => scope.permissions !== undefined &&
353
+ (isOff(scope) || scope.permissions.processAccess === "read");
354
+ mirror.mainConfined = !isOff(main);
355
+ mirror.processAccess = allowsRead(main) && allowsRead(policy) ? "read" : "off";
356
+ Object.assign(policy, { policySource: hasBackground ? "background" : "main-legacy" });
357
+ mirror.policy = policy;
358
+ mirror.error = undefined;
356
359
  } catch (error) {
357
360
  mirror.error = error as Error;
358
361
  mirror.processAccess = "off";
@@ -210,6 +210,8 @@ export interface CallbackBatcher {
210
210
  toolEnded(toolCallId: string): Promise<boolean>;
211
211
  deliverUrgent(event: UrgentCallbackEvent): boolean | Promise<boolean>;
212
212
  cancel(): void;
213
+ /** Await already-started handoffs after the owner has cancelled scheduling. */
214
+ settled(): Promise<void>;
213
215
  pendingCount(): number;
214
216
  }
215
217
 
@@ -568,6 +570,7 @@ export function createCallbackBatcher(
568
570
  const pending = new Map<string, PendingEvent>();
569
571
  const inFlight = new Set<string>();
570
572
  const urgentInFlight = new Set<string>();
573
+ const urgentSettlements = new Set<Promise<boolean>>();
571
574
  const handedOff = new Map<string, number>();
572
575
  const activeTools = new Set<string>();
573
576
  let sequence = 0;
@@ -750,10 +753,12 @@ export function createCallbackBatcher(
750
753
  { deliverAs: "followUp", triggerTurn: true },
751
754
  );
752
755
  if (isPromiseLike(handoff)) {
753
- return Promise.resolve(handoff).then(
756
+ const settlement = Promise.resolve(handoff).then(
754
757
  () => acknowledge(),
755
758
  () => false,
756
- ).finally(() => urgentInFlight.delete(key));
759
+ ).finally(() => { urgentInFlight.delete(key); urgentSettlements.delete(settlement); });
760
+ urgentSettlements.add(settlement);
761
+ return settlement;
757
762
  }
758
763
  const acknowledged = acknowledge();
759
764
  urgentInFlight.delete(key);
@@ -800,6 +805,10 @@ export function createCallbackBatcher(
800
805
  return pending.size > 0 ? api.flush() : true;
801
806
  },
802
807
  deliverUrgent,
808
+ async settled() {
809
+ await flushPromise;
810
+ await Promise.all([...urgentSettlements]);
811
+ },
803
812
  cancel() {
804
813
  cancelTimer();
805
814
  pending.clear();