pi-better-background-tasks 0.9.1 → 0.11.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.
package/src/runtime.ts CHANGED
@@ -7,7 +7,7 @@ import { currentProcessStartToken, readProcessStartToken } from "./process-ident
7
7
  import { DEFAULT_TMUX_BOOTSTRAP_TIMEOUT_MS, expandSshRemoteTaskPreset } from "./remote-task-preset.js";
8
8
  import type { RemoteRunner, ResolvedSshRemoteTask } from "./remote-task-preset.js";
9
9
  import { ensureTaskDir, logPathFor, nextTaskId, readMeta, sandboxProfilePathFor, writeMeta } from "./registry.js";
10
- import { confineCommandSpec, resolveForegroundSandboxPlan } from "./sandbox.js";
10
+ import { assertBackgroundExecutionAllowed, backgroundExecutionLimits, confineCommandSpec, isCommandTimeoutSeconds, resolveForegroundSandboxPlan, sandboxProvenance } from "./sandbox.js";
11
11
  import { takeRecoverySnapshot } from "./shared-sandbox-core.js";
12
12
  import { failurePath, readTaskIntent, recordExitFailure, recordFailure, recoverDeclaredOperation, recoverFailure, resumeFailureAttention, scheduleFailureAttention, stopFailureAttention, suspendFailureAttention, terminalFailureAttention } from "./failures.js";
13
13
  import { markFailureAttentionDelivered } from "./shared-failure-observations.js";
@@ -24,6 +24,7 @@ import type {
24
24
  SshConnectionParams,
25
25
  TerminalResult,
26
26
  } from "./types.js";
27
+ import { observeTaskStallAttention } from "./stall-attention.js";
27
28
  import { isTerminalStatus } from "./types.js";
28
29
 
29
30
  const watcherTimers = new Map<string, ReturnType<typeof setTimeout>>();
@@ -191,6 +192,32 @@ export interface TaskRuntimeDependencies {
191
192
  remoteRunner?: RemoteRunner;
192
193
  }
193
194
 
195
+ /**
196
+ * Persist the launch-time per-command cap with the task metadata. Reload and
197
+ * resume go through `readMeta`, so the value travels as ordinary JSON and the
198
+ * task keeps the cap it launched under.
199
+ */
200
+ function withCommandPolicy(meta: BackgroundTaskMeta, seconds: number | undefined): BackgroundTaskMeta {
201
+ return seconds === undefined ? meta : { ...meta, commandTimeoutSeconds: seconds };
202
+ }
203
+
204
+ function persistedCommandCapSeconds(meta: BackgroundTaskMeta): number | undefined {
205
+ const value = meta.commandTimeoutSeconds;
206
+ return isCommandTimeoutSeconds(value) ? value : undefined;
207
+ }
208
+
209
+ /**
210
+ * A cap that was persisted but is not a valid number of seconds.
211
+ *
212
+ * Metadata can be edited or written by an older build, so a present-but-invalid
213
+ * value must not quietly mean "unlimited": the task fails closed on resume
214
+ * instead of running without the cap the operator asked for.
215
+ */
216
+ function invalidPersistedCommandCap(meta: BackgroundTaskMeta): string | undefined {
217
+ if (meta.commandTimeoutSeconds === undefined || isCommandTimeoutSeconds(meta.commandTimeoutSeconds)) return undefined;
218
+ return `Persisted command time limit ${JSON.stringify(meta.commandTimeoutSeconds)} is invalid; the task was not resumed with an unlimited command.`;
219
+ }
220
+
194
221
  type WatchPollRunner = (timeoutMs?: number) => Promise<CommandResult>;
195
222
 
196
223
  export function spawnTask(
@@ -204,9 +231,15 @@ export function spawnTask(
204
231
  // Resolved before any task directory, log, or metadata exists so a blocked
205
232
  // launch leaves nothing behind. Structured SSH must also honor launch restrictions.
206
233
  const intent = readTaskIntent(params);
234
+ const cwd = params.cwd ?? defaultCwd;
207
235
  const sandboxPlan = resolveForegroundSandboxPlan(pi, !!params.ssh, params);
236
+ // The application/shell switches apply before any task state exists, so a
237
+ // refused launch leaves no id, directory, or metadata behind. Structured SSH
238
+ // is checked here too, because its command is a remote shell command. The
239
+ // launch cwd is passed so a relative alias resolves where the task will run.
240
+ assertBackgroundExecutionAllowed(params, sandboxPlan, { remote: Boolean(params.ssh), cwd });
241
+ const commandLimits = backgroundExecutionLimits(sandboxPlan);
208
242
  const id = nextTaskId();
209
- const cwd = params.cwd ?? defaultCwd;
210
243
  const logPath = logPathFor(id);
211
244
  ensureTaskDir(id);
212
245
  const remoteTask = params.ssh
@@ -245,7 +278,7 @@ export function spawnTask(
245
278
  });
246
279
  }
247
280
  const now = Date.now();
248
- const meta: BackgroundTaskMeta = {
281
+ const meta = withCommandPolicy({
249
282
  id,
250
283
  name: params.name,
251
284
  kind: "process",
@@ -262,6 +295,7 @@ export function spawnTask(
262
295
  cwd,
263
296
  env: params.env,
264
297
  launchArgv: launchArgvOf(commandSpec, launchSpec),
298
+ sandbox: sandboxProvenance(sandboxPlan, !!remoteTask),
265
299
  maxLogBytes: resolveMaxLogBytes(params.max_log_bytes),
266
300
  pid: spawned?.child.pid,
267
301
  pidStartTime: spawned?.child.pid ? readProcessStartToken(spawned.child.pid) : undefined,
@@ -271,9 +305,9 @@ export function spawnTask(
271
305
  ssh: remoteTask?.metadata.ssh,
272
306
  remote: remoteTask?.metadata.remote,
273
307
  ...intent,
274
- };
308
+ }, commandLimits.commandTimeoutSeconds);
275
309
  writeMeta(meta);
276
- scheduleLogRetention(id);
310
+ scheduleLogRetention(pi, id, getActiveSession);
277
311
  if (tmuxBacked && remoteTask) {
278
312
  activeRemoteTasks.set(id, remoteTask);
279
313
  appendLine(logPath, `--- remote tmux bootstrap ${new Date(now).toISOString()} target=${remoteTask.metadata.ssh.target} session=${remoteTask.metadata.remote.sessionName} ---`);
@@ -301,7 +335,7 @@ export function spawnTask(
301
335
  void notifyTerminal(pi, latest, getActiveSession);
302
336
  });
303
337
  }
304
- if (meta.deadlineAt) scheduleProcessTimeout(pi, id, meta.deadlineAt, getActiveSession);
338
+ scheduleProcessKill(pi, meta, getActiveSession);
305
339
  return meta;
306
340
  }
307
341
 
@@ -415,7 +449,7 @@ async function pollRemoteSession(
415
449
  const meta = readMeta(id);
416
450
  const remoteTask = activeRemoteTasks.get(id);
417
451
  if (!meta || meta.status !== "running" || meta.remote?.session !== "tmux" || !remoteTask) return;
418
- const poll = await remoteTask.pollTmuxSession(meta.remote.logOffset ?? 0, remainingDeadlineMs(meta.deadlineAt));
452
+ const poll = await remoteTask.pollTmuxSession(meta.remote.logOffset ?? 0, remainingDeadlineMs(processKillDeadlineMs(meta)));
419
453
  if (scheduledWorkSuspended) return;
420
454
  appendTaskOutput(meta.logPath, poll.output);
421
455
  if (poll.status === "timed_out") {
@@ -495,9 +529,11 @@ export function startWatchTask(
495
529
  }
496
530
  const blindChecks = readBlindChecks(params.blind_checks);
497
531
  const intent = readTaskIntent(params);
532
+ const cwd = params.cwd ?? defaultCwd;
498
533
  const sandboxPlan = resolveForegroundSandboxPlan(pi, !!params.ssh, params, "bg_task_watch");
534
+ assertBackgroundExecutionAllowed(params, sandboxPlan, { remote: Boolean(params.ssh), cwd });
535
+ const commandLimits = backgroundExecutionLimits(sandboxPlan);
499
536
  const id = nextTaskId();
500
- const cwd = params.cwd ?? defaultCwd;
501
537
  const now = Date.now();
502
538
  const timeoutSeconds = resolveWatchTimeoutSeconds(params.timeout_seconds);
503
539
  const remoteTask = params.ssh
@@ -515,7 +551,7 @@ export function startWatchTask(
515
551
  const launchSpec = remoteTask
516
552
  ? commandSpec
517
553
  : confineCommandSpec(commandSpec, sandboxPlan, sandboxProfilePathFor(id), {}, (line) => sandboxNotices.push(line), "bg_task_watch");
518
- const meta: BackgroundTaskMeta = {
554
+ const meta = withCommandPolicy({
519
555
  id,
520
556
  name: params.name,
521
557
  kind: "command_watch",
@@ -533,6 +569,7 @@ export function startWatchTask(
533
569
  cwd,
534
570
  env: params.env,
535
571
  launchArgv: launchArgvOf(commandSpec, launchSpec),
572
+ sandbox: sandboxProvenance(sandboxPlan, !!remoteTask),
536
573
  maxLogBytes: resolveMaxLogBytes(params.max_log_bytes),
537
574
  spawnPid: process.pid,
538
575
  spawnPidStartTime: currentProcessStartToken(),
@@ -543,11 +580,12 @@ export function startWatchTask(
543
580
  ssh: remoteTask?.metadata.ssh,
544
581
  remote: remoteTask?.metadata.remote,
545
582
  ...intent,
546
- };
583
+ }, commandLimits.commandTimeoutSeconds);
547
584
  ensureTaskDir(id);
548
585
  appendLine(meta.logPath, `--- watch ${new Date(now).toISOString()} interval_ms=${meta.intervalMs} ---`);
549
586
  for (const line of sandboxNotices) appendLine(meta.logPath, `--- ${line} ---`);
550
587
  writeMeta(meta);
588
+ scheduleLogRetention(pi, meta.id, getActiveSession);
551
589
  let resolveFirst!: (check: FirstWatchCheck | "suspended" | undefined) => void;
552
590
  const firstCheck = new Promise<FirstWatchCheck | "suspended" | undefined>((resolve) => { resolveFirst = resolve; });
553
591
  firstCheckWaiters.set(id, { promise: firstCheck, resolve: resolveFirst });
@@ -581,6 +619,13 @@ export function resumeRunningTask(
581
619
  void notifyTerminal(pi, meta, getActiveSession);
582
620
  return meta;
583
621
  }
622
+ // A corrupt persisted cap must never resume as an unlimited command. Fail
623
+ // the task before any timer, poll, or launch is scheduled.
624
+ const invalidCap = invalidPersistedCommandCap(meta);
625
+ if (invalidCap) {
626
+ finalize(meta, { status: "failed", reason: invalidCap }, pi, getActiveSession);
627
+ return meta;
628
+ }
584
629
  scheduleFailureAttention(pi, meta.id, getActiveSession);
585
630
 
586
631
  // Same Pi process: an earlier (reloaded or switched-away) extension instance may
@@ -592,6 +637,7 @@ export function resumeRunningTask(
592
637
  writeMeta(meta);
593
638
  }
594
639
 
640
+ scheduleLogRetention(pi, meta.id, getActiveSession);
595
641
  const remoteTask = resolvePersistedRemoteTask(meta, dependencies.remoteRunner);
596
642
  if (meta.kind === "command_watch") {
597
643
  scheduleWatch(pi, meta.id, 0, getActiveSession, remoteTask
@@ -600,11 +646,10 @@ export function resumeRunningTask(
600
646
  return meta;
601
647
  }
602
648
 
603
- scheduleLogRetention(meta.id);
604
649
  if (meta.remote?.session === "tmux" && meta.remote.sessionStarted !== false && remoteTask) {
605
650
  activeRemoteTasks.set(meta.id, remoteTask);
606
651
  scheduleRemoteSessionPoll(pi, meta.id, 0, getActiveSession);
607
- if (meta.deadlineAt) scheduleProcessTimeout(pi, meta.id, meta.deadlineAt, getActiveSession);
652
+ scheduleProcessKill(pi, meta, getActiveSession);
608
653
  // An earlier instance's in-flight timeout kill may still finalize it.
609
654
  if (ownedByThisProcess) scheduleHandoff(pi, meta.id, getActiveSession);
610
655
  return meta;
@@ -617,7 +662,7 @@ export function resumeRunningTask(
617
662
  markProcessLost(pi, meta, getActiveSession);
618
663
  return meta;
619
664
  }
620
- if (meta.deadlineAt) scheduleProcessTimeout(pi, meta.id, meta.deadlineAt, getActiveSession);
665
+ scheduleProcessKill(pi, meta, getActiveSession);
621
666
  return meta;
622
667
  }
623
668
 
@@ -777,8 +822,9 @@ export async function stopTask(
777
822
  stopProcessGroup(meta.pid, meta.pgid);
778
823
  } catch (error) {
779
824
  recordStopError(meta, error instanceof Error ? error.message : String(error));
780
- if (meta.deadlineAt && meta.deadlineAt > Date.now()) {
781
- scheduleProcessTimeout(pi, id, meta.deadlineAt, getActiveSession);
825
+ const killAt = processKillDeadlineMs(meta);
826
+ if (killAt !== undefined && killAt > Date.now()) {
827
+ scheduleProcessTimeout(pi, id, killAt, getActiveSession);
782
828
  }
783
829
  return meta;
784
830
  }
@@ -845,9 +891,15 @@ async function pollWatch(
845
891
  return;
846
892
  }
847
893
  const timeoutMs = remainingDeadlineMs(meta.deadlineAt);
894
+ // The policy cap bounds one check, never the watch's whole lifetime. The
895
+ // smaller of it and the caller's remaining timeout_seconds wins, and a
896
+ // caller's timeout_seconds:0 cannot disable the policy cap.
897
+ const capMs = commandCapMs(meta);
898
+ const pollTimeoutMs = capMs === undefined ? timeoutMs : timeoutMs === undefined ? capMs : Math.min(timeoutMs, capMs);
899
+ const capBound = capMs !== undefined && (timeoutMs === undefined || capMs < timeoutMs);
848
900
  const result = runOnce
849
- ? await runOnce(timeoutMs)
850
- : await runCommandOnce(commandSpecFromMeta(meta), undefined, timeoutMs);
901
+ ? await runOnce(pollTimeoutMs)
902
+ : await runCommandOnce(commandSpecFromMeta(meta), undefined, pollTimeoutMs);
851
903
  checked = {
852
904
  exitCode: result.exitCode, signal: result.signal, durationMs: Math.max(0, result.endedAt - result.startedAt),
853
905
  ...(result.timedOut ? { timedOut: true } : {}), stdout: result.stdout, stderr: result.stderr,
@@ -867,7 +919,7 @@ async function pollWatch(
867
919
 
868
920
  const pollKey = result.startedAt;
869
921
  if (result.timedOut) {
870
- finalize(latest, { status: "timed_out", reason: watchTimeoutReason(latest), commandResult: result }, pi, getActiveSession);
922
+ finalize(latest, { status: "timed_out", reason: capBound ? commandCapReason(latest) : watchTimeoutReason(latest), commandResult: result }, pi, getActiveSession);
871
923
  return;
872
924
  }
873
925
 
@@ -1058,6 +1110,52 @@ function remainingDeadlineMs(deadlineAt: number | undefined): number | undefined
1058
1110
  return Math.max(1, deadlineAt - Date.now());
1059
1111
  }
1060
1112
 
1113
+ /** A validated persisted per-command cap, in milliseconds. */
1114
+ function commandCapMs(meta: BackgroundTaskMeta): number | undefined {
1115
+ const seconds = persistedCommandCapSeconds(meta);
1116
+ if (seconds === undefined) return undefined;
1117
+ return Math.max(1, Math.round(seconds * 1000));
1118
+ }
1119
+
1120
+ /**
1121
+ * When a spawned task's command hits the policy cap.
1122
+ *
1123
+ * A spawn task is one command, so the cap runs from the launch (`startedAt`). A
1124
+ * resumed task keeps that same snapshot, which is why the cap is measured from
1125
+ * the persisted start rather than from the moment of resume.
1126
+ */
1127
+ function commandCapDeadlineMs(meta: BackgroundTaskMeta): number | undefined {
1128
+ const capMs = commandCapMs(meta);
1129
+ return capMs === undefined ? undefined : meta.startedAt + capMs;
1130
+ }
1131
+
1132
+ /** The smaller of the caller's whole-task deadline and the policy cap. */
1133
+ function processKillDeadlineMs(meta: BackgroundTaskMeta): number | undefined {
1134
+ const capDeadlineAt = commandCapDeadlineMs(meta);
1135
+ if (capDeadlineAt === undefined) return meta.deadlineAt;
1136
+ if (meta.deadlineAt === undefined) return capDeadlineAt;
1137
+ return Math.min(capDeadlineAt, meta.deadlineAt);
1138
+ }
1139
+
1140
+ /** True when the cap, not the caller's timeout_seconds, ends this command first. */
1141
+ function capEndsFirst(meta: BackgroundTaskMeta): boolean {
1142
+ const capDeadlineAt = commandCapDeadlineMs(meta);
1143
+ return capDeadlineAt !== undefined && (meta.deadlineAt === undefined || capDeadlineAt < meta.deadlineAt);
1144
+ }
1145
+
1146
+ function commandCapReason(meta: BackgroundTaskMeta): string {
1147
+ return `timeout: Background tasks command time limit of ${persistedCommandCapSeconds(meta)}s was reached`;
1148
+ }
1149
+
1150
+ function scheduleProcessKill(
1151
+ pi: ExtensionAPI,
1152
+ meta: BackgroundTaskMeta,
1153
+ getActiveSession?: ActiveSessionProvider,
1154
+ ): void {
1155
+ const killAt = processKillDeadlineMs(meta);
1156
+ if (killAt !== undefined) scheduleProcessTimeout(pi, meta.id, killAt, getActiveSession);
1157
+ }
1158
+
1061
1159
  function scheduleProcessTimeout(
1062
1160
  pi: ExtensionAPI,
1063
1161
  id: string,
@@ -1100,7 +1198,7 @@ async function finalizeProcessTimeout(
1100
1198
  const meta = readMeta(id);
1101
1199
  if (!meta || meta.status !== "running" || meta.kind !== "process") return;
1102
1200
 
1103
- let reason = "timeout";
1201
+ let reason = capEndsFirst(meta) ? commandCapReason(meta) : "timeout";
1104
1202
  if (meta.remote?.session === "tmux" && meta.remote.sessionStarted !== true) {
1105
1203
  reason = `timeout before remote tmux session ${meta.remote.sessionName} started on ${meta.ssh?.target}`;
1106
1204
  } else if (meta.remote?.session === "tmux") {
@@ -1155,6 +1253,7 @@ async function notifyTerminal(
1155
1253
  meta: BackgroundTaskMeta,
1156
1254
  getActiveSession?: ActiveSessionProvider,
1157
1255
  ): Promise<void> {
1256
+ observeTaskStallAttention(readMeta(meta.id) ?? meta);
1158
1257
  // A suspended instance has no active session: delivering or suppressing here would
1159
1258
  // be wrong either way. The instance that resumes the task delivers it (#324).
1160
1259
  if (scheduledWorkSuspended) return;
@@ -1260,16 +1359,17 @@ function launchArgvOf(commandSpec: CommandSpec, launchSpec: CommandSpec): string
1260
1359
  return launchSpec === commandSpec ? undefined : launchSpec.argv;
1261
1360
  }
1262
1361
 
1263
- function scheduleLogRetention(id: string): void {
1362
+ function scheduleLogRetention(pi: ExtensionAPI, id: string, getActiveSession?: ActiveSessionProvider): void {
1264
1363
  stopLogRetention(id);
1265
1364
  if (scheduledWorkSuspended) return;
1266
1365
  const timer = setInterval(() => {
1267
1366
  const meta = readMeta(id);
1268
- if (!meta || meta.status !== "running" || meta.kind !== "process") {
1367
+ if (!meta || meta.status !== "running") {
1269
1368
  stopLogRetention(id);
1270
1369
  return;
1271
1370
  }
1272
- enforceLogRetention(meta);
1371
+ if (meta.kind === "process") enforceLogRetention(meta);
1372
+ if (observeTaskStallAttention(meta)) scheduleFailureAttention(pi, id, getActiveSession);
1273
1373
  }, LOG_RETENTION_CHECK_MS);
1274
1374
  timer.unref();
1275
1375
  logRetentionTimers.set(id, timer);
@@ -1283,8 +1383,10 @@ function stopLogRetention(id: string): void {
1283
1383
 
1284
1384
  function enforceLogRetention(meta: BackgroundTaskMeta): void {
1285
1385
  try {
1286
- const mtimeMs = Math.trunc(statSync(meta.logPath).mtimeMs);
1287
- if (mtimeMs > (meta.lastProgressAt ?? meta.startedAt)) {
1386
+ const log = statSync(meta.logPath);
1387
+ const mtimeMs = Math.trunc(log.mtimeMs);
1388
+ const maintenance = meta.logMaintenance?.mtimeMs === mtimeMs && meta.logMaintenance.size === log.size;
1389
+ if (!maintenance && mtimeMs > (meta.lastProgressAt ?? meta.startedAt)) {
1288
1390
  meta.lastProgressAt = mtimeMs;
1289
1391
  writeMeta(meta);
1290
1392
  }
@@ -1296,6 +1398,10 @@ function enforceLogRetention(meta: BackgroundTaskMeta): void {
1296
1398
  meta.logDiscardedBytes = (meta.logDiscardedBytes ?? 0) + compacted.discardedBytes;
1297
1399
  meta.logRetentionEvents = (meta.logRetentionEvents ?? 0) + 1;
1298
1400
  meta.logGeneration = (meta.logGeneration ?? 0) + 1;
1401
+ try {
1402
+ const log = statSync(meta.logPath);
1403
+ meta.logMaintenance = { mtimeMs: Math.trunc(log.mtimeMs), size: log.size };
1404
+ } catch { /* Missing log remains an evidence gap. */ }
1299
1405
  writeMeta(meta);
1300
1406
  }
1301
1407