pi-better-background-tasks 0.10.0 → 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/README.md CHANGED
@@ -27,7 +27,16 @@ is installed, local tasks follow the independent **Background tasks** column in
27
27
  `/sandbox`. Its Sandbox switch starts Off for fresh settings. When enabled,
28
28
  commands run under macOS Seatbelt or Linux Bubblewrap with that column's project,
29
29
  outside-project, credential-file, command and network permissions. Protected
30
- paths remain denied.
30
+ paths remain denied. Run applications is the master execution switch. With it
31
+ On and Shell scripts Off, direct launches using `shell:false` and `argv` are
32
+ allowed; shell commands and explicit shell-interpreter launches, including
33
+ aliases, are refused. Applications may still invoke scripts or shells internally.
34
+
35
+ Command time limit caps each actual process or watch check, not the whole watch
36
+ duration. A smaller requested timeout wins; omitting or increasing it cannot
37
+ bypass the policy cap. Cleanup covers ordinary process-group descendants, not
38
+ deliberately daemonized processes. Shell scripts defaults On and the limit defaults
39
+ to No limit, including for legacy settings.
31
40
 
32
41
  The policy is captured once at launch. Later settings changes affect only new
33
42
  tasks. An existing process, including a watcher resumed in a later Pi session,
@@ -136,7 +145,9 @@ are excluded from task progress.
136
145
  that column at launch; subsequent changes do not alter an existing process or
137
146
  its future watch polls. Older saved settings copy Main into Background tasks
138
147
  once so the migration preserves behavior. Older sandbox publishers without the
139
- Background field retain their Main-policy behavior.
148
+ Background field retain their Main-policy behavior. A restrictive application
149
+ policy rejects an incompatible older background consumer instead of silently
150
+ dropping the restriction.
140
151
 
141
152
  Launch and status show `confined`, `unconfined`, or `unknown`, plus the backend
142
153
  when known and the policy source. `verbose:true` includes the persisted policy
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-background-tasks",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "Pi extension for durable background shell tasks, watchers, logs, and status inspection.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -10,7 +10,8 @@ type Request = {
10
10
  version: number;
11
11
  name: string;
12
12
  input: unknown;
13
- reply(value: { version: number; parameters: object; admission: Admission }): void;
13
+ executionControls?: boolean;
14
+ reply(value: { version: number; parameters: object; admission: Admission; executionControls: 1 }): void;
14
15
  };
15
16
 
16
17
  /** The schemas belong to one registerTools invocation, never to a module singleton. */
@@ -22,7 +23,7 @@ export function advertiseBackgroundAdapter(pi: ExtensionAPI, schemas: ReadonlyMa
22
23
  const parameters = schemas.get(request.name);
23
24
  if (!parameters) return;
24
25
  const admission = classify(request.name, request.input);
25
- if (admission) request.reply({ version: BACKGROUND_ADAPTER_VERSION, parameters, admission });
26
+ if (admission) request.reply({ version: BACKGROUND_ADAPTER_VERSION, parameters, admission, executionControls: 1 });
26
27
  });
27
28
  pi.on("session_shutdown", () => { if (typeof unsubscribe === "function") unsubscribe(); });
28
29
  }
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, sandboxProvenance } 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";
@@ -192,6 +192,32 @@ export interface TaskRuntimeDependencies {
192
192
  remoteRunner?: RemoteRunner;
193
193
  }
194
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
+
195
221
  type WatchPollRunner = (timeoutMs?: number) => Promise<CommandResult>;
196
222
 
197
223
  export function spawnTask(
@@ -205,9 +231,15 @@ export function spawnTask(
205
231
  // Resolved before any task directory, log, or metadata exists so a blocked
206
232
  // launch leaves nothing behind. Structured SSH must also honor launch restrictions.
207
233
  const intent = readTaskIntent(params);
234
+ const cwd = params.cwd ?? defaultCwd;
208
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);
209
242
  const id = nextTaskId();
210
- const cwd = params.cwd ?? defaultCwd;
211
243
  const logPath = logPathFor(id);
212
244
  ensureTaskDir(id);
213
245
  const remoteTask = params.ssh
@@ -246,7 +278,7 @@ export function spawnTask(
246
278
  });
247
279
  }
248
280
  const now = Date.now();
249
- const meta: BackgroundTaskMeta = {
281
+ const meta = withCommandPolicy({
250
282
  id,
251
283
  name: params.name,
252
284
  kind: "process",
@@ -273,7 +305,7 @@ export function spawnTask(
273
305
  ssh: remoteTask?.metadata.ssh,
274
306
  remote: remoteTask?.metadata.remote,
275
307
  ...intent,
276
- };
308
+ }, commandLimits.commandTimeoutSeconds);
277
309
  writeMeta(meta);
278
310
  scheduleLogRetention(pi, id, getActiveSession);
279
311
  if (tmuxBacked && remoteTask) {
@@ -303,7 +335,7 @@ export function spawnTask(
303
335
  void notifyTerminal(pi, latest, getActiveSession);
304
336
  });
305
337
  }
306
- if (meta.deadlineAt) scheduleProcessTimeout(pi, id, meta.deadlineAt, getActiveSession);
338
+ scheduleProcessKill(pi, meta, getActiveSession);
307
339
  return meta;
308
340
  }
309
341
 
@@ -417,7 +449,7 @@ async function pollRemoteSession(
417
449
  const meta = readMeta(id);
418
450
  const remoteTask = activeRemoteTasks.get(id);
419
451
  if (!meta || meta.status !== "running" || meta.remote?.session !== "tmux" || !remoteTask) return;
420
- 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)));
421
453
  if (scheduledWorkSuspended) return;
422
454
  appendTaskOutput(meta.logPath, poll.output);
423
455
  if (poll.status === "timed_out") {
@@ -497,9 +529,11 @@ export function startWatchTask(
497
529
  }
498
530
  const blindChecks = readBlindChecks(params.blind_checks);
499
531
  const intent = readTaskIntent(params);
532
+ const cwd = params.cwd ?? defaultCwd;
500
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);
501
536
  const id = nextTaskId();
502
- const cwd = params.cwd ?? defaultCwd;
503
537
  const now = Date.now();
504
538
  const timeoutSeconds = resolveWatchTimeoutSeconds(params.timeout_seconds);
505
539
  const remoteTask = params.ssh
@@ -517,7 +551,7 @@ export function startWatchTask(
517
551
  const launchSpec = remoteTask
518
552
  ? commandSpec
519
553
  : confineCommandSpec(commandSpec, sandboxPlan, sandboxProfilePathFor(id), {}, (line) => sandboxNotices.push(line), "bg_task_watch");
520
- const meta: BackgroundTaskMeta = {
554
+ const meta = withCommandPolicy({
521
555
  id,
522
556
  name: params.name,
523
557
  kind: "command_watch",
@@ -546,7 +580,7 @@ export function startWatchTask(
546
580
  ssh: remoteTask?.metadata.ssh,
547
581
  remote: remoteTask?.metadata.remote,
548
582
  ...intent,
549
- };
583
+ }, commandLimits.commandTimeoutSeconds);
550
584
  ensureTaskDir(id);
551
585
  appendLine(meta.logPath, `--- watch ${new Date(now).toISOString()} interval_ms=${meta.intervalMs} ---`);
552
586
  for (const line of sandboxNotices) appendLine(meta.logPath, `--- ${line} ---`);
@@ -585,6 +619,13 @@ export function resumeRunningTask(
585
619
  void notifyTerminal(pi, meta, getActiveSession);
586
620
  return meta;
587
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
+ }
588
629
  scheduleFailureAttention(pi, meta.id, getActiveSession);
589
630
 
590
631
  // Same Pi process: an earlier (reloaded or switched-away) extension instance may
@@ -608,7 +649,7 @@ export function resumeRunningTask(
608
649
  if (meta.remote?.session === "tmux" && meta.remote.sessionStarted !== false && remoteTask) {
609
650
  activeRemoteTasks.set(meta.id, remoteTask);
610
651
  scheduleRemoteSessionPoll(pi, meta.id, 0, getActiveSession);
611
- if (meta.deadlineAt) scheduleProcessTimeout(pi, meta.id, meta.deadlineAt, getActiveSession);
652
+ scheduleProcessKill(pi, meta, getActiveSession);
612
653
  // An earlier instance's in-flight timeout kill may still finalize it.
613
654
  if (ownedByThisProcess) scheduleHandoff(pi, meta.id, getActiveSession);
614
655
  return meta;
@@ -621,7 +662,7 @@ export function resumeRunningTask(
621
662
  markProcessLost(pi, meta, getActiveSession);
622
663
  return meta;
623
664
  }
624
- if (meta.deadlineAt) scheduleProcessTimeout(pi, meta.id, meta.deadlineAt, getActiveSession);
665
+ scheduleProcessKill(pi, meta, getActiveSession);
625
666
  return meta;
626
667
  }
627
668
 
@@ -781,8 +822,9 @@ export async function stopTask(
781
822
  stopProcessGroup(meta.pid, meta.pgid);
782
823
  } catch (error) {
783
824
  recordStopError(meta, error instanceof Error ? error.message : String(error));
784
- if (meta.deadlineAt && meta.deadlineAt > Date.now()) {
785
- scheduleProcessTimeout(pi, id, meta.deadlineAt, getActiveSession);
825
+ const killAt = processKillDeadlineMs(meta);
826
+ if (killAt !== undefined && killAt > Date.now()) {
827
+ scheduleProcessTimeout(pi, id, killAt, getActiveSession);
786
828
  }
787
829
  return meta;
788
830
  }
@@ -849,9 +891,15 @@ async function pollWatch(
849
891
  return;
850
892
  }
851
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);
852
900
  const result = runOnce
853
- ? await runOnce(timeoutMs)
854
- : await runCommandOnce(commandSpecFromMeta(meta), undefined, timeoutMs);
901
+ ? await runOnce(pollTimeoutMs)
902
+ : await runCommandOnce(commandSpecFromMeta(meta), undefined, pollTimeoutMs);
855
903
  checked = {
856
904
  exitCode: result.exitCode, signal: result.signal, durationMs: Math.max(0, result.endedAt - result.startedAt),
857
905
  ...(result.timedOut ? { timedOut: true } : {}), stdout: result.stdout, stderr: result.stderr,
@@ -871,7 +919,7 @@ async function pollWatch(
871
919
 
872
920
  const pollKey = result.startedAt;
873
921
  if (result.timedOut) {
874
- 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);
875
923
  return;
876
924
  }
877
925
 
@@ -1062,6 +1110,52 @@ function remainingDeadlineMs(deadlineAt: number | undefined): number | undefined
1062
1110
  return Math.max(1, deadlineAt - Date.now());
1063
1111
  }
1064
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
+
1065
1159
  function scheduleProcessTimeout(
1066
1160
  pi: ExtensionAPI,
1067
1161
  id: string,
@@ -1104,7 +1198,7 @@ async function finalizeProcessTimeout(
1104
1198
  const meta = readMeta(id);
1105
1199
  if (!meta || meta.status !== "running" || meta.kind !== "process") return;
1106
1200
 
1107
- let reason = "timeout";
1201
+ let reason = capEndsFirst(meta) ? commandCapReason(meta) : "timeout";
1108
1202
  if (meta.remote?.session === "tmux" && meta.remote.sessionStarted !== true) {
1109
1203
  reason = `timeout before remote tmux session ${meta.remote.sessionName} started on ${meta.ssh?.target}`;
1110
1204
  } else if (meta.remote?.session === "tmux") {
package/src/sandbox.ts CHANGED
@@ -25,21 +25,34 @@
25
25
  * tests that pin them.
26
26
  */
27
27
 
28
- import { mkdirSync } from "node:fs";
28
+ import { accessSync, constants, mkdirSync, realpathSync, statSync } from "node:fs";
29
29
  import { homedir } from "node:os";
30
- import { dirname } from "node:path";
30
+ import { delimiter, dirname, resolve } from "node:path";
31
31
 
32
32
  import { commandExecution } from "./process.js";
33
33
  import { baseDir } from "./registry.js";
34
- import { compileWritePolicy, describeSandboxSupport, maybeBuildSandboxCommand, type SandboxSeams } from "./shared-sandbox-core.js";
34
+ import { compileWritePolicy, describeSandboxSupport, directApplicationTarget, maybeBuildSandboxCommand, type SandboxSeams } from "./shared-sandbox-core.js";
35
35
 
36
36
  type SandboxPermissions = {
37
37
  /** `write` = read, create and overwrite in place; `read-write` = Write & delete. */
38
38
  projectFiles: "off" | "read" | "write" | "read-write";
39
39
  outsideProject: "off" | "read" | "write" | "read-write";
40
40
  storedCredentials: "off" | "read" | "read-write";
41
+ /** Master switch for command execution. */
41
42
  commands: boolean;
42
43
  network: boolean;
44
+ /**
45
+ * Optional refinement of `commands`: may a launch command be interpreted by a
46
+ * shell? Absent means yes (the historical behavior). Off confines a launch to
47
+ * a direct executable through `shell: false` argv.
48
+ */
49
+ shell?: boolean;
50
+ /**
51
+ * Optional outer cap for one launch command, in seconds. Absent or null means
52
+ * no cap. A value is validated here and copied into the immutable launch
53
+ * snapshot; it caps each actual command, never a watch's whole lifetime.
54
+ */
55
+ commandTimeoutSeconds?: number | null;
43
56
  };
44
57
  import type { CommandSpec, TaskSandboxProvenance } from "./types.js";
45
58
  import { SandboxDiagnostics, diagnosticPackageVersion, type DiagnosticResource } from "./shared-sandbox-diagnostics.js";
@@ -73,6 +86,114 @@ export const FOREGROUND_SANDBOX_POLICY_CHANNEL = "pi-better-sandbox:policy";
73
86
  /** Channel a consumer emits on to ask for the current policy. */
74
87
  export const FOREGROUND_SANDBOX_POLICY_REQUEST_CHANNEL = "pi-better-sandbox:policy-request";
75
88
 
89
+ /** Largest single-command cap a timer can hold: 2_147_483 seconds is 2_147_483_000 ms. */
90
+ export const MAX_COMMAND_TIMEOUT_SECONDS = 2_147_483;
91
+
92
+ /** A positive finite number of seconds no larger than {@link MAX_COMMAND_TIMEOUT_SECONDS}. */
93
+ export function isCommandTimeoutSeconds(value: unknown): value is number {
94
+ return typeof value === "number" && Number.isFinite(value) && value > 0 && value <= MAX_COMMAND_TIMEOUT_SECONDS;
95
+ }
96
+
97
+ /** Executables whose whole purpose is to interpret a shell command string. */
98
+ const SHELL_EXECUTABLES = Object.freeze([
99
+ "sh", "bash", "zsh", "dash", "ksh", "ksh93", "mksh", "pdksh", "ash", "csh", "tcsh", "fish",
100
+ "yash", "posh", "rbash", "busybox", "pwsh", "powershell", "cmd",
101
+ ] as const);
102
+ const SHELL_NAMES = new Set<string>(SHELL_EXECUTABLES);
103
+
104
+ function shellExecutableName(path: string): boolean {
105
+ const normalized = String(path ?? "").replace(/\\/g, "/");
106
+ const name = normalized.slice(normalized.lastIndexOf("/") + 1).toLowerCase();
107
+ const stem = name.endsWith(".exe") ? name.slice(0, -4) : name;
108
+ return name.length > 0 && (SHELL_NAMES.has(name) || SHELL_NAMES.has(stem));
109
+ }
110
+
111
+ /**
112
+ * Resolve an executable the way spawn will: a relative or bare name against the
113
+ * launch cwd, and a bare name through the launch's PATH. A relative PATH entry
114
+ * is itself resolved against the launch cwd, because the child changes directory
115
+ * before it searches PATH.
116
+ *
117
+ * The candidate must be a regular file this process may execute, so a
118
+ * non-executable shadow earlier on PATH does not stand in for the real target.
119
+ */
120
+ function resolvedExecutablePath(executable: string, env: NodeJS.ProcessEnv, cwd: string): string | undefined {
121
+ const value = String(executable ?? "");
122
+ if (value.includes("/") || (process.platform === "win32" && value.includes("\\"))) {
123
+ return resolve(cwd, value);
124
+ }
125
+ const path = env.PATH ?? env.Path;
126
+ if (!path) return undefined;
127
+ for (const directory of path.split(delimiter)) {
128
+ const candidate = resolve(cwd, directory || ".", value);
129
+ try {
130
+ if (!statSync(candidate).isFile()) continue;
131
+ accessSync(candidate, constants.X_OK);
132
+ return candidate;
133
+ } catch { /* A PATH entry may vanish, or not be executable. */ }
134
+ }
135
+ return undefined;
136
+ }
137
+
138
+ let shellIdentities: { path: string | undefined; cwd: string; ids: Set<string> } | undefined;
139
+
140
+ /**
141
+ * Device/inode identities of the known shell binaries on this launch's PATH.
142
+ *
143
+ * A hardlink to a shell can carry any name, so a name check and a symlink's
144
+ * canonical target cannot see it. This mirrors the confined executor's identity
145
+ * check (`task-sandbox/exec.ts`), resolved against the launch cwd and PATH.
146
+ */
147
+ function knownShellIdentities(env: NodeJS.ProcessEnv, cwd: string): Set<string> {
148
+ const path = env.PATH ?? env.Path;
149
+ const cached = shellIdentities;
150
+ if (cached && cached.path === path && cached.cwd === cwd) return cached.ids;
151
+ const ids = new Set<string>();
152
+ for (const directory of (path ?? "").split(delimiter)) {
153
+ for (const name of SHELL_EXECUTABLES) {
154
+ try {
155
+ const info = statSync(resolve(cwd, directory || ".", name), { bigint: true });
156
+ if (info.isFile()) ids.add(`${info.dev}:${info.ino}`);
157
+ } catch { /* Not present in this directory. */ }
158
+ }
159
+ }
160
+ shellIdentities = { path, cwd, ids };
161
+ return ids;
162
+ }
163
+
164
+ /**
165
+ * True when `argv[0]` names a shell interpreter directly.
166
+ *
167
+ * With Shell scripts Off, a `shell: false` argv is still a way to ask a shell to
168
+ * run a command (`["/bin/bash", "-c", ...]`). The requested name is checked
169
+ * first, then the executable spawn would resolve against `cwd` and the launch's
170
+ * PATH, then its canonical target, so a symlink or an alternate name pointing at
171
+ * a shell is still refused. A hardlink to a shell is refused by inode identity.
172
+ * Only a direct interpreter is refused: an application that happens to launch a
173
+ * shell itself is a different capability from asking Pi to interpret a command.
174
+ */
175
+ export function isShellExecutable(
176
+ executable: string,
177
+ env: NodeJS.ProcessEnv = process.env,
178
+ cwd: string = process.cwd(),
179
+ ): boolean {
180
+ if (shellExecutableName(executable)) return true;
181
+ const resolved = resolvedExecutablePath(String(executable ?? ""), env, cwd);
182
+ if (!resolved) return false;
183
+ let canonical: string;
184
+ try {
185
+ canonical = realpathSync.native(resolved);
186
+ } catch {
187
+ return false;
188
+ }
189
+ if (shellExecutableName(canonical)) return true;
190
+ try {
191
+ const info = statSync(canonical, { bigint: true });
192
+ if (knownShellIdentities(env, cwd).has(`${info.dev}:${info.ino}`)) return true;
193
+ } catch { /* A missing file fails when the launch runs it. */ }
194
+ return false;
195
+ }
196
+
76
197
  /**
77
198
  * What the foreground sandbox is doing right now.
78
199
  *
@@ -188,12 +309,19 @@ function readPermissions(value: unknown): ForegroundSandboxPolicy["permissions"]
188
309
  if (typeof p.enabled !== "boolean" || typeof p.commands !== "boolean" ||
189
310
  typeof p.network !== "boolean" || !access(p.projectFiles) ||
190
311
  !access(p.outsideProject) || !credential(p.storedCredentials) ||
191
- (p.processAccess !== undefined && p.processAccess !== "off" && p.processAccess !== "read")) return undefined;
312
+ (p.processAccess !== undefined && p.processAccess !== "off" && p.processAccess !== "read") ||
313
+ (p.shell !== undefined && typeof p.shell !== "boolean") ||
314
+ (p.commandTimeoutSeconds !== undefined && p.commandTimeoutSeconds !== null &&
315
+ !isCommandTimeoutSeconds(p.commandTimeoutSeconds))) return undefined;
316
+ // Copy only what the publisher sent: absent optional settings keep their
317
+ // documented default meaning instead of being invented here.
192
318
  return Object.freeze({
193
319
  enabled: p.enabled, commands: p.commands, network: p.network,
194
320
  projectFiles: p.projectFiles as SandboxPermissions["projectFiles"],
195
321
  outsideProject: p.outsideProject as SandboxPermissions["outsideProject"],
196
322
  storedCredentials: p.storedCredentials as SandboxPermissions["storedCredentials"],
323
+ ...(p.shell === undefined ? {} : { shell: p.shell as boolean }),
324
+ ...(p.commandTimeoutSeconds === undefined ? {} : { commandTimeoutSeconds: p.commandTimeoutSeconds as number | null }),
197
325
  });
198
326
  }
199
327
 
@@ -320,11 +448,85 @@ export function planFor(policy: ForegroundSandboxPolicy | undefined): Foreground
320
448
  storedCredentials: policy.permissions.storedCredentials,
321
449
  commands: policy.permissions.commands,
322
450
  network: policy.permissions.network,
451
+ ...(policy.permissions.shell === undefined ? {} : { shell: policy.permissions.shell }),
452
+ ...(policy.permissions.commandTimeoutSeconds === undefined ? {} : { commandTimeoutSeconds: policy.permissions.commandTimeoutSeconds }),
323
453
  } : undefined;
324
454
  return { confined: true, writableRoot: policy.writableRoot, denyWrite: policy.denyWrite,
325
455
  ...(permissions ? { permissions } : {}) };
326
456
  }
327
457
 
458
+ /**
459
+ * The application, shell, and time switches captured with one launch plan.
460
+ *
461
+ * The Background tasks profile is the gate: when it is off, launches keep their
462
+ * historical unconfined behavior. When it is on, `commands` remains the master
463
+ * switch (enforced by {@link planFor}); this narrows it with the optional
464
+ * `shell` and `commandTimeoutSeconds` fields. An absent `shell` means On, and an
465
+ * absent or null cap means no cap, so a publisher that predates those fields is
466
+ * unchanged.
467
+ */
468
+ export interface BackgroundExecutionLimits {
469
+ /** May a launch command be interpreted by a shell? */
470
+ readonly shell: boolean;
471
+ /** Immutable outer cap for one command, in seconds; undefined means unlimited. */
472
+ readonly commandTimeoutSeconds?: number;
473
+ }
474
+
475
+ const UNLIMITED_EXECUTION: BackgroundExecutionLimits = Object.freeze({ shell: true });
476
+
477
+ /** Read the immutable application switches captured for `plan`. */
478
+ export function backgroundExecutionLimits(plan: ForegroundSandboxPlan): BackgroundExecutionLimits {
479
+ const permissions = launchPolicies.get(plan)?.permissions;
480
+ if (!permissions?.enabled) return UNLIMITED_EXECUTION;
481
+ const cap = isCommandTimeoutSeconds(permissions.commandTimeoutSeconds)
482
+ ? permissions.commandTimeoutSeconds
483
+ : undefined;
484
+ return Object.freeze({
485
+ shell: permissions.shell !== false,
486
+ ...(cap === undefined ? {} : { commandTimeoutSeconds: cap }),
487
+ });
488
+ }
489
+
490
+ /**
491
+ * Refuse a launch the captured Background tasks application switches forbid.
492
+ *
493
+ * Called before any task id, directory, log, or metadata exists, so a refused
494
+ * launch leaves nothing behind. `commands: false` is still the master refusal
495
+ * and is raised by {@link planFor}; this is the narrower shell rule. With Shell
496
+ * scripts Off, only a direct executable through `shell: false` argv is allowed.
497
+ * A shell command string and a direct shell interpreter in argv[0] would both
498
+ * reintroduce shell interpretation, and structured SSH carries a remote shell
499
+ * command, so all three are refused.
500
+ *
501
+ * `cwd` is the launch directory the task will actually run in. A relative
502
+ * executable, a relative PATH entry, and an alias found only in that directory
503
+ * are resolved exactly as the launch resolves them, never against Pi's own
504
+ * process cwd.
505
+ */
506
+ export function assertBackgroundExecutionAllowed(
507
+ spec: CommandSpec,
508
+ plan: ForegroundSandboxPlan,
509
+ options: { remote?: boolean; cwd?: string } = {},
510
+ ): void {
511
+ const limits = backgroundExecutionLimits(plan);
512
+ if (limits.shell) return;
513
+ const launchCwd = options.cwd ?? spec.cwd ?? process.cwd();
514
+ const detail = options.remote
515
+ ? "Structured SSH carries a remote shell command, so it cannot run while Shell scripts is Off. Use a local shell:false argv launch, or turn Shell scripts on in /sandbox."
516
+ : spec.shell !== false
517
+ ? "Background tasks profile disables shell commands. Pass shell:false with an argv for a direct executable, or turn Shell scripts on in /sandbox."
518
+ : isShellExecutable(spec.argv?.[0] ?? "", { ...process.env, ...spec.env }, launchCwd)
519
+ ? "Background tasks profile disables shell commands. A direct shell executable is refused; launch the program itself with shell:false, or turn Shell scripts on in /sandbox."
520
+ : undefined;
521
+ if (detail === undefined) return;
522
+ const policy = launchPolicies.get(plan) ?? {
523
+ state: "failed" as const,
524
+ denyWrite: [],
525
+ reason: "The Background tasks profile disables shell commands.",
526
+ };
527
+ throw new ForegroundSandboxBlockedError(policy, detail);
528
+ }
529
+
328
530
  /**
329
531
  * Wrap a local command in the platform's write sandbox.
330
532
  *
@@ -351,6 +553,10 @@ export function confineCommandSpec(
351
553
  if (!plan.confined) return spec;
352
554
 
353
555
  const { execPath, execArgs } = commandExecution(spec);
556
+ const directOnly = spec.shell === false && plan.permissions?.shell === false;
557
+ const target = directOnly
558
+ ? directApplicationTarget(execPath, execArgs, { ...process.env, ...spec.env }, false)
559
+ : { execPath, execArgs };
354
560
  // The generated profile is written here, so its directory must exist before
355
561
  // the backend builds the command.
356
562
  mkdirSync(dirname(profilePath), { recursive: true });
@@ -385,8 +591,8 @@ export function confineCommandSpec(
385
591
  {
386
592
  profilePath,
387
593
  policy,
388
- execPath,
389
- execArgs,
594
+ ...target,
595
+ ...(directOnly ? { internalHelperExecutable: true } : {}),
390
596
  },
391
597
  // `explicitSandbox` because the foreground state already said a sandbox
392
598
  // applies: an absent or unusable backend must throw here rather than hand
@@ -405,7 +611,8 @@ export function confineCommandSpec(
405
611
  }
406
612
  for (const line of command.notices ?? []) onNotice(line);
407
613
 
408
- return { ...spec, argv: [command.file, ...command.fileArgs], shell: false };
614
+ return { ...spec, ...(directOnly ? { env: { PATH: "/usr/bin:/bin", HOME: homedir() } } : {}),
615
+ argv: [command.file, ...command.fileArgs], shell: false };
409
616
  }
410
617
 
411
618
  function blocked(plan: ForegroundSandboxPlan & { confined: true }, detail: string): Error {
@@ -58,7 +58,16 @@ export type SandboxPermissions = {
58
58
  projectFiles: SandboxFileAccess;
59
59
  outsideProject: SandboxFileAccess;
60
60
  storedCredentials: "off" | "read" | "read-write";
61
+ /** Run applications: the master switch for command execution (bash and run_application). */
61
62
  commands: boolean;
63
+ /** Shell scripts inside commands; omitted (legacy) profiles keep shell execution On. */
64
+ shell?: boolean;
65
+ /**
66
+ * Cap for every command path, in seconds. The effective timeout is
67
+ * `min(requested, cap)`, and the cap applies when the caller omits a timeout.
68
+ * Omitted or null means no limit. Must be positive, finite and <= 2147483.
69
+ */
70
+ commandTimeoutSeconds?: number | null;
62
71
  network: boolean;
63
72
  /** Fixed process_list adapter only; omitted legacy profiles keep it Off. */
64
73
  processAccess?: "off" | "read";
@@ -103,6 +112,89 @@ export type SandboxTarget = {
103
112
  execArgs: readonly string[];
104
113
  };
105
114
 
115
+ export const SHELL_EXECUTABLE_NAMES = Object.freeze([
116
+ "sh", "bash", "zsh", "dash", "ksh", "ksh93", "mksh", "pdksh", "ash", "csh", "tcsh", "fish",
117
+ "yash", "posh", "rbash", "busybox", "pwsh", "powershell", "cmd",
118
+ ] as const);
119
+
120
+ // Fixed runtime code starts after confinement. The launch data is JSON, never
121
+ // env/shell syntax. Native execve never falls back to a command interpreter.
122
+ const APPLICATION_RUNNER = `
123
+ const fs = require("node:fs");
124
+ const path = require("node:path");
125
+ const spec = JSON.parse(process.argv[1]);
126
+ function resolveExecutable(executable) {
127
+ if (executable.includes(path.sep)) return path.resolve(executable);
128
+ const directories = (spec.env.PATH || spec.env.Path || "").split(path.delimiter);
129
+ const resolved = directories.map(directory => path.resolve(directory || ".", executable)).find(candidate => {
130
+ try { fs.accessSync(candidate, fs.constants.X_OK); return fs.statSync(candidate).isFile(); }
131
+ catch { return false; }
132
+ });
133
+ if (!resolved) throw new Error("Executable not found: " + executable);
134
+ return resolved;
135
+ }
136
+ function isShellInterpreter(interpreter) {
137
+ const canonical = fs.realpathSync(interpreter);
138
+ if (spec.shellNames.includes(path.basename(interpreter)) || spec.shellNames.includes(path.basename(canonical))) return true;
139
+ const target = fs.statSync(canonical, { bigint: true });
140
+ const directories = new Set(["/bin", "/usr/bin", ...(spec.env.PATH || spec.env.Path || "").split(path.delimiter)]);
141
+ for (const directory of directories) for (const name of spec.shellNames) {
142
+ try {
143
+ const known = fs.statSync(path.resolve(directory || ".", name), { bigint: true });
144
+ if (target.dev === known.dev && target.ino === known.ino) return true;
145
+ } catch { /* A shell need not exist in every executable directory. */ }
146
+ }
147
+ return false;
148
+ }
149
+ function verifyExecutable(executable, depth = 0) {
150
+ if (depth > 4) throw new Error("Too many shebang interpreters.");
151
+ fs.accessSync(executable, fs.constants.X_OK);
152
+ const fd = fs.openSync(executable, "r");
153
+ const header = Buffer.alloc(4096);
154
+ let size;
155
+ try { size = fs.readSync(fd, header, 0, header.length, 0); }
156
+ finally { fs.closeSync(fd); }
157
+ const magic = size >= 4 ? header.readUInt32BE(0) : 0;
158
+ const binary = [0x7f454c46, 0xfeedface, 0xcefaedfe, 0xfeedfacf, 0xcffaedfe,
159
+ 0xcafebabe, 0xbebafeca, 0xcafebabf, 0xbfbafeca].includes(magic);
160
+ const script = size >= 2 && header[0] === 35 && header[1] === 33;
161
+ if (!binary && !script) throw new Error("Executable has no supported binary format or shebang; shell fallback is disabled.");
162
+ if (!spec.shell && script) {
163
+ const words = header.subarray(2, size).toString("utf8").split(/\\r?\\n/, 1)[0].trim().split(/\\s+/);
164
+ let interpreter = resolveExecutable(words[0]);
165
+ if (path.basename(fs.realpathSync(interpreter)) === "env") {
166
+ if (words.length !== 2 || words[1].startsWith("-") || words[1].includes("=")) {
167
+ throw new Error("Sandbox: Shell scripts are Off; an env shebang must name one direct interpreter without options.");
168
+ }
169
+ interpreter = resolveExecutable(words[1]);
170
+ }
171
+ if (isShellInterpreter(interpreter)) {
172
+ throw new Error("Sandbox: Shell scripts are Off; the executable uses a shell shebang.");
173
+ }
174
+ verifyExecutable(interpreter, depth + 1);
175
+ }
176
+ }
177
+ try {
178
+ if (typeof process.execve !== "function") {
179
+ throw new Error("Direct application execution requires Node.js with process.execve (22.15+ or 24+). Update Node.js; no shell fallback was run.");
180
+ }
181
+ const executable = resolveExecutable(spec.executable);
182
+ verifyExecutable(executable);
183
+ process.execve(executable, [executable, ...spec.args], spec.env);
184
+ } catch (error) {
185
+ console.error(error.code === "ENOEXEC" ? "Executable format is unsupported; shell fallback is disabled." : error.message);
186
+ process.exitCode = 126;
187
+ }
188
+ `;
189
+
190
+ /** Fixed post-boundary launcher for literal argv, without env assignment or shell fallback. */
191
+ export function directApplicationTarget(
192
+ executable: string, args: readonly string[], env: NodeJS.ProcessEnv, shell: boolean,
193
+ ): SandboxTarget {
194
+ return { execPath: canonicalizePath(process.execPath), execArgs: ["--eval", APPLICATION_RUNNER,
195
+ JSON.stringify({ executable, args, env, shell, shellNames: SHELL_EXECUTABLE_NAMES })] };
196
+ }
197
+
106
198
  export type SandboxCommandArgs = SandboxTarget & {
107
199
  /** Where the macOS backend writes its generated SBPL profile. */
108
200
  profilePath: string;
package/src/tools.ts CHANGED
@@ -80,12 +80,12 @@ const CommandFields = {
80
80
  name: Type.Optional(Type.String({ description: "Human-readable task label." })),
81
81
  command: Type.Optional(Type.String({ description: "Shell command to run, or the remote command when ssh is set. Required unless shell:false with argv is used." })),
82
82
  argv: Type.Optional(Type.Array(Type.String(), { description: "Argument vector. Use with shell:false to avoid shell parsing." })),
83
- shell: Type.Optional(Type.Boolean({ description: "Run command through the package's bash-compatible shell. Default true." })),
83
+ shell: Type.Optional(Type.Boolean({ description: "Run command through the package's bash-compatible shell. Default true. When the Background tasks sandbox profile turns Shell scripts off, a shell command and a direct shell executable are refused; pass argv with shell:false for a direct executable." })),
84
84
  cwd: Type.Optional(Type.String({ description: "Working directory. Defaults to the current pi cwd." })),
85
85
  env: Type.Optional(StringMap("Extra environment variables.")),
86
86
  max_log_bytes: Type.Optional(Type.Number({ description: "Maximum retained raw-log bytes. Default 4194304 (4 MiB). Older output is compacted while the task runs." })),
87
87
  callback: Type.Optional(Type.Boolean({ description: "Queue a follow-up when the task reaches a terminal state. Default true." })),
88
- timeout_seconds: Type.Optional(Type.Number({ description: "Optional timeout in seconds. Command watchers default to 900 seconds when omitted; pass 0 to disable. Spawned processes have no default timeout." })),
88
+ timeout_seconds: Type.Optional(Type.Number({ description: "Optional whole-task timeout in seconds. Command watchers default to 900 seconds when omitted; pass 0 to disable. Spawned processes have no default timeout. When the Background tasks sandbox profile sets a command time limit, that cap applies to each actual command (and each watch check) independently: a smaller timeout_seconds still wins, and 0 does not disable the policy cap." })),
89
89
  ssh: Type.Optional(SshSchema),
90
90
  remote: Type.Optional(RemoteSchema),
91
91
  ...IntentFields,
package/src/types.ts CHANGED
@@ -116,6 +116,13 @@ export interface BackgroundTaskMeta {
116
116
  command?: string;
117
117
  argv?: string[];
118
118
  shell?: boolean;
119
+ /**
120
+ * Per-command cap captured from the Background tasks profile at launch, in
121
+ * seconds. Absent means the launch had no cap. Persisted so a resumed task
122
+ * keeps the cap it started under; it bounds one command (each check for a
123
+ * watch), never a watch's whole lifetime.
124
+ */
125
+ commandTimeoutSeconds?: number;
119
126
  cwd: string;
120
127
  env?: Record<string, string>;
121
128
  /**