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.
@@ -0,0 +1,71 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import type { BackgroundTaskMeta } from "./types.js";
3
+
4
+ export interface ProcessSample {
5
+ uid: number;
6
+ startTime: string;
7
+ state: string;
8
+ cpuTime: string;
9
+ waitChannel: string;
10
+ }
11
+
12
+ export interface TaskProcessDiagnostics {
13
+ availability: "available" | "blocked" | "unavailable";
14
+ identity?: "matches" | "absent" | "mismatch" | "unverified";
15
+ state?: string;
16
+ cpuTime?: string;
17
+ waitChannel?: string;
18
+ reason?: string;
19
+ limit: string;
20
+ }
21
+
22
+ const LIMIT = "One process snapshot cannot prove useful work or a hang; descendants and network requests are not inspected.";
23
+ const normalized = (value: string) => value.trim().replace(/\s+/g, " ");
24
+
25
+ /** Fixed, bounded probe of one registered task PID. Never reads argv, environment or paths. */
26
+ function sampleProcess(pid: number): ProcessSample | undefined {
27
+ if (process.platform !== "darwin" && process.platform !== "linux") throw new Error("unsupported platform");
28
+ const file = process.platform === "darwin" ? "/bin/ps" : "/usr/bin/ps";
29
+ let output: string;
30
+ try {
31
+ output = execFileSync(file, ["-p", String(pid), "-o", "uid=,lstart=,state=,time=,wchan="], {
32
+ encoding: "utf8", timeout: 2_000, maxBuffer: 4096,
33
+ stdio: ["ignore", "pipe", "pipe"], env: { LC_ALL: "C", PATH: "/usr/bin:/bin" },
34
+ }).trim();
35
+ } catch (error) {
36
+ const failure = error as { status?: number; stdout?: unknown; stderr?: unknown };
37
+ if (failure.status === 1 && !String(failure.stdout ?? "").trim() && !String(failure.stderr ?? "").trim()) return undefined;
38
+ throw new Error("process snapshot unavailable");
39
+ }
40
+ if (!output) return undefined;
41
+ const match = /^(\d+)\s+(\S+\s+\S+\s+\d+\s+[\d:]+\s+\d+)\s+([A-Za-z+<>NsLslWXZRTIDUP?-]+)\s+([\d:.\-]+)\s*(\S*)$/.exec(output);
42
+ if (!match || match[5]!.length > 128) throw new Error("unsupported process snapshot");
43
+ return { uid: Number(match[1]), startTime: normalized(match[2]!), state: match[3]!, cpuTime: match[4]!, waitChannel: match[5] || "unavailable" };
44
+ }
45
+
46
+ export function inspectTaskProcess(
47
+ meta: BackgroundTaskMeta,
48
+ access: "read" | "off" | "unknown" | "confined",
49
+ probe: (pid: number) => ProcessSample | undefined = sampleProcess,
50
+ ): TaskProcessDiagnostics {
51
+ const unavailable = (reason: string, identity?: TaskProcessDiagnostics["identity"]): TaskProcessDiagnostics =>
52
+ ({ availability: "unavailable", reason, ...(identity ? { identity } : {}), limit: LIMIT });
53
+ if (access === "confined") return unavailable("Process activity adapter is unavailable under Main confinement; no unconfined process probe was run. Process access Read does not bypass kernel rules.");
54
+ if (access !== "read") return { availability: "blocked", reason: access === "off"
55
+ ? "Process access is Off in Main or Background tasks. Enable Read in /sandbox; this does not describe task confinement."
56
+ : "Current process-access policy is unavailable; no process probe was run.", limit: LIMIT };
57
+ if (meta.ssh) return unavailable("Remote activity is unavailable; no remote diagnostic command was run.");
58
+ if (meta.kind !== "process") return unavailable("Watch poll PID is not retained; last completed check is progress evidence only.");
59
+ if (!Number.isSafeInteger(meta.pid) || meta.pid! <= 0) return unavailable("Task PID is unavailable.");
60
+ try {
61
+ const sample = probe(meta.pid!);
62
+ if (!sample) return { availability: "available", identity: "absent", reason: "Recorded PID is absent; the execution result may still be unavailable.", limit: LIMIT };
63
+ if (sample.uid !== process.getuid?.()) return unavailable("Recorded PID is not a current-user process.", "mismatch");
64
+ if (!meta.pidStartTime) return unavailable("Launch-time process identity is missing; sampled activity cannot be attributed to this task.", "unverified");
65
+ if (normalized(sample.startTime) !== normalized(meta.pidStartTime)) return unavailable("Recorded PID has been reused; sampled activity is not this task.", "mismatch");
66
+ return { availability: "available", identity: "matches", state: sample.state, cpuTime: sample.cpuTime,
67
+ waitChannel: sample.waitChannel, limit: LIMIT };
68
+ } catch {
69
+ return unavailable("OS process activity/wait evidence is unavailable or unsupported; no command output is disclosed.");
70
+ }
71
+ }
package/src/tools.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Type } from "typebox";
2
2
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import { advertiseBackgroundAdapter } from "./adapter-contract.js";
3
4
  import { refreshBackgroundTasksNavigator } from "./navigator-provider.js";
4
5
  import {
5
6
  classifyOwnership,
@@ -12,12 +13,13 @@ import {
12
13
  formatStopResult,
13
14
  type OutputOptions,
14
15
  } from "./output.js";
15
- import { readOutputControls } from "./shared-log-utils.js";
16
+ import { cursorKind, readOutputControls } from "./shared-log-utils.js";
16
17
  import { cancelCallbackBatch, getCallbackBatcher, setCallbackBatchContext } from "./shared-callback-batcher.js";
17
18
  import { inspectMeta, listMetasForOrigin, readMeta, writeMeta } from "./registry.js";
18
19
  import { awaitFirstWatchCheck, FIRST_WATCH_CHECK_WAIT_MS, resumeRunningTask, spawnTask, startWatchTask, stopTask, type WatchTaskParams } from "./runtime.js";
19
20
  import { runTaskMaintenance } from "./maintenance.js";
20
- import { ForegroundSandboxBlockedError } from "./sandbox.js";
21
+ import { backgroundProcessDiagnosticsAccess, ForegroundSandboxBlockedError } from "./sandbox.js";
22
+ import { inspectTaskProcess } from "./task-diagnostics.js";
21
23
  import type { BackgroundTaskCallbackOrigin, BackgroundTaskMeta } from "./types.js";
22
24
  import { isTerminalStatus } from "./types.js";
23
25
 
@@ -78,12 +80,12 @@ const CommandFields = {
78
80
  name: Type.Optional(Type.String({ description: "Human-readable task label." })),
79
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." })),
80
82
  argv: Type.Optional(Type.Array(Type.String(), { description: "Argument vector. Use with shell:false to avoid shell parsing." })),
81
- 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." })),
82
84
  cwd: Type.Optional(Type.String({ description: "Working directory. Defaults to the current pi cwd." })),
83
85
  env: Type.Optional(StringMap("Extra environment variables.")),
84
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." })),
85
87
  callback: Type.Optional(Type.Boolean({ description: "Queue a follow-up when the task reaches a terminal state. Default true." })),
86
- 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." })),
87
89
  ssh: Type.Optional(SshSchema),
88
90
  remote: Type.Optional(RemoteSchema),
89
91
  ...IntentFields,
@@ -123,6 +125,7 @@ const IdParams = Type.Object({
123
125
  ...CursorFields,
124
126
  });
125
127
  const HistoryField = {
128
+ diagnostics: Type.Optional(Type.Boolean({ description: "For status: sample registered task process identity, CPU time, state and wait evidence. Requires current Process access Read in both Main and Background tasks. No arguments, environment or remote probes; a snapshot cannot prove useful work or a hang." })),
126
129
  history: Type.Optional(Type.Boolean({ description: "If true, return an incident page that also lists failure history: expected failures and recovered or superseded incidents. Default output lists only failures that need action and counts the rest." })),
127
130
  };
128
131
  const StatusParams = Type.Object({
@@ -193,6 +196,14 @@ const BACKGROUND_ORCHESTRATION_GUIDELINES = [
193
196
  export function registerTools(pi: ExtensionAPI): void {
194
197
  let activeSession: BackgroundTaskCallbackOrigin | undefined;
195
198
  const getActiveSession = () => activeSession;
199
+ const schemas = new Map<string, object>();
200
+ const register: ExtensionAPI["registerTool"] = (definition) => {
201
+ // A reload must not share schema identity with the previous registration.
202
+ const parameters = { ...definition.parameters };
203
+ schemas.set(definition.name, parameters);
204
+ pi.registerTool({ ...definition, parameters });
205
+ };
206
+ advertiseBackgroundAdapter(pi, schemas);
196
207
 
197
208
  pi.on("session_start", async (_event, ctx) => {
198
209
  setCallbackBatchContext(pi, ctx);
@@ -225,7 +236,7 @@ export function registerTools(pi: ExtensionAPI): void {
225
236
  cancelCallbackBatch(pi);
226
237
  });
227
238
 
228
- pi.registerTool({
239
+ register({
229
240
  name: "bg_task_spawn",
230
241
  label: "BG Spawn",
231
242
  description: "Start a long-running background process and return immediately with its task id. For remote work, prefer structured ssh: pass ssh:{host,user} and put the remote command in command; spawn defaults to a remote tmux session with durable local logs and real remote stop. For short synchronous remote commands that should return output now, use remote_bash from pi-better-ssh. If tmux is missing, the preset attempts to install tmux non-interactively and fails closed with operator guidance when setup cannot proceed. Explicit remote.session=direct skips tmux, but direct mode has weaker stop semantics and may leave the remote process running. Never wait or poll in the foreground.",
@@ -239,7 +250,7 @@ export function registerTools(pi: ExtensionAPI): void {
239
250
  },
240
251
  });
241
252
 
242
- pi.registerTool({
253
+ register({
243
254
  name: "bg_task_watch",
244
255
  label: "BG Watch",
245
256
  description: `Poll a command in the background until success_when, failure_when, or timeout matches. For remote work, prefer structured ssh: pass ssh:{host,user} and provide the remote command in command; each interval opens a direct one-shot SSH poll without tmux installation. For short synchronous remote commands that should return output now, use remote_bash from pi-better-ssh. Returns its task id once the first check finishes. ${WATCH_CHECK_GUIDANCE} Default timeout 900 seconds; pass timeout_seconds:0 to disable.`,
@@ -253,7 +264,7 @@ export function registerTools(pi: ExtensionAPI): void {
253
264
  },
254
265
  });
255
266
 
256
- pi.registerTool({
267
+ register({
257
268
  name: "bg_task_list",
258
269
  label: "BG List",
259
270
  description: "List durable background tasks as compact rows under a 1 KiB UTF-8 budget (10 entries default), newest first. Current-session only unless all:true. Nonblocking. Pass the returned nextCursor as cursor to page further (every task is reachable), or statusCursor to get a small no-change response or failure-only updates; a higher limit/max_bytes gives a larger explicit page.",
@@ -264,18 +275,18 @@ export function registerTools(pi: ExtensionAPI): void {
264
275
  },
265
276
  });
266
277
 
267
- pi.registerTool({
278
+ register({
268
279
  name: "bg_task_status",
269
280
  label: "BG Status",
270
281
  description: "Inspect one background task. Default output is a compact model-facing summary (1 KiB UTF-8) with matched condition, exit/signal, stop error, and failure counts before progress. Current-session only unless all:true; unknown ownership is a gap, not missing or healthy. Pass verbose:true only when full raw metadata is explicitly needed. Environment values are omitted. A raw log nextCursor passed as cursor continues the raw log page; an incidentCursor pages incidents that need action; history:true lists failure history too. After a terminal callback, call this first and call bg_task_log only if the summary is insufficient.",
271
282
  parameters: StatusParams,
272
283
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
273
284
  activeSession = getCallbackOrigin(ctx);
274
- return text(formatStatus(inspectMeta(params.id), statusOptions(params, activeSession)));
285
+ return text(taskStatus(pi, params.id, params, statusOptions(params, activeSession)));
275
286
  },
276
287
  });
277
288
 
278
- pi.registerTool({
289
+ register({
279
290
  name: "bg_task_log",
280
291
  label: "BG Log",
281
292
  description: "Read a background task log. Default output is a compact 10-line terminal-aware tail for model ingestion (1 KiB UTF-8). Current-session only unless all:true. Pass lines for a bounded tail (tail_lines is a deprecated alias); lines:0 pages the retained raw log from the oldest retained offset (16 KiB pages, 64 KiB hard cap) with a caller-owned cursor. Capture and retention loss are disclosed; this is not a full-history archive. Nonblocking.",
@@ -289,7 +300,7 @@ export function registerTools(pi: ExtensionAPI): void {
289
300
  },
290
301
  });
291
302
 
292
- pi.registerTool({
303
+ register({
293
304
  name: "bg_task_stop",
294
305
  label: "BG Stop",
295
306
  description: "Cancel a watcher or terminate a background task. Only a task owned by the current session stops; a foreign-session or unverifiable task is refused unless all:true. For a tmux-backed SSH task, stop kills its remote tmux session before marking it cancelled. Direct SSH stop only tears down the local client and may leave the remote process running.",
@@ -302,7 +313,7 @@ export function registerTools(pi: ExtensionAPI): void {
302
313
  },
303
314
  });
304
315
 
305
- pi.registerTool({
316
+ register({
306
317
  name: "bg_task",
307
318
  label: "BG Task",
308
319
  description: "Action wrapper for background tasks: spawn, watch, list, status, log, stop, or clear. For remote work, prefer structured ssh: pass ssh:{host,user} and provide the remote command in command. For short synchronous remote commands that should return output now, use remote_bash from pi-better-ssh. SSH spawn defaults to durable tmux; SSH watches use direct one-shot polls without tmux installation; remote.session=direct is a weaker-stop spawn escape hatch. Spawn returns immediately; do not poll in foreground. For action:watch: " + WATCH_CHECK_GUIDANCE + " For action:status, default compact output and use verbose:true only for full metadata. For action:log, default compact tail and use lines:0 to page retained raw bytes. Standalone tools and these wrappers share the same output assembler. List/status/log default to the current session; pass all:true to override. Stop and clear change only current-session tasks: clear dismisses every owned terminal task, or one task with id (all:true allows another session's task by id).",
@@ -317,7 +328,7 @@ export function registerTools(pi: ExtensionAPI): void {
317
328
  },
318
329
  });
319
330
 
320
- pi.registerTool({
331
+ register({
321
332
  name: "bg_status",
322
333
  label: "BG Status",
323
334
  description: "Action wrapper for inspecting background tasks: list, status, log, stop, or clear. Nonblocking. Status is compact by default; log returns a compact tail by default. Use verbose:true or lines:0 only for explicit full-data recovery. Shares the same output assembler as the standalone tools. Current-session default; pass all:true to override. Stop and clear change only current-session tasks (clear with id and all:true for another session's task).",
@@ -353,6 +364,19 @@ function statusOptions(params: Record<string, unknown>, origin?: BackgroundTaskC
353
364
  };
354
365
  }
355
366
 
367
+ function taskStatus(pi: ExtensionAPI, id: string, params: Record<string, unknown>, options: OutputOptions): string {
368
+ const inspection = inspectMeta(id);
369
+ const enriched: OutputOptions = { ...options };
370
+ const kind = cursorKind(options.cursor);
371
+ if (params.diagnostics === true && !options.history && (!kind || kind === "s" || kind === "t") &&
372
+ inspection.meta && classifyOwnership(inspection.meta, options) === "allow") {
373
+ enriched.processDiagnostics = inspectTaskProcess(inspection.meta, backgroundProcessDiagnosticsAccess(pi));
374
+ // Fresh samples bypass status suppression, not raw or incident pagination.
375
+ if (kind === "s") enriched.cursor = undefined;
376
+ }
377
+ return formatStatus(inspection, enriched);
378
+ }
379
+
356
380
  function logOptions(params: Record<string, unknown>, origin?: BackgroundTaskCallbackOrigin): OutputOptions {
357
381
  // Canonical `lines`, else the deprecated `tail_lines` alias (#321).
358
382
  const lines = readOutputControls(params).lines;
@@ -409,7 +433,7 @@ async function runAction(
409
433
  return formatList(listOptions(params, callbackOrigin));
410
434
  case "status":
411
435
  if (!params.id) return "Invalid parameters: status requires id.";
412
- return formatStatus(inspectMeta(String(params.id)), statusOptions(params, callbackOrigin));
436
+ return taskStatus(pi, String(params.id), params, statusOptions(params, callbackOrigin));
413
437
  case "log":
414
438
  if (!params.id) return "Invalid parameters: log requires id.";
415
439
  return formatLog(String(params.id), logOptions(params, callbackOrigin));
package/src/types.ts CHANGED
@@ -82,6 +82,14 @@ export interface BackgroundTaskCallbackOrigin {
82
82
  sessionId?: string;
83
83
  }
84
84
 
85
+ export interface TaskSandboxProvenance {
86
+ confinement: "confined" | "unconfined" | "unknown";
87
+ backend?: string;
88
+ policySource: "background" | "main-legacy" | "no-publisher" | "remote";
89
+ policySummary: string;
90
+ changesAffectTask: false;
91
+ }
92
+
85
93
  export interface BackgroundTaskMeta {
86
94
  id: string;
87
95
  name?: string;
@@ -108,6 +116,13 @@ export interface BackgroundTaskMeta {
108
116
  command?: string;
109
117
  argv?: string[];
110
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;
111
126
  cwd: string;
112
127
  env?: Record<string, string>;
113
128
  /**
@@ -119,9 +134,13 @@ export interface BackgroundTaskMeta {
119
134
  * own request, so status, navigator, and goal surfaces read unchanged.
120
135
  */
121
136
  launchArgv?: string[];
137
+ /** Launch-time evidence, never inferred from current settings or missing profile files. */
138
+ sandbox?: TaskSandboxProvenance;
122
139
  maxLogBytes?: number;
123
140
  logDiscardedBytes?: number;
124
141
  logRetentionEvents?: number;
142
+ /** Own retention writes are not task output. Both fields must still match to ignore them. */
143
+ logMaintenance?: { mtimeMs: number; size: number };
125
144
  /** Incremented on every same-inode compaction so log-page cursors can detect it. */
126
145
  logGeneration?: number;
127
146
  /** Bytes never captured into watch/command buffers. Distinct from logDiscardedBytes. */