pi-better-background-tasks 0.6.4 → 0.6.6

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-background-tasks",
3
- "version": "0.6.4",
3
+ "version": "0.6.6",
4
4
  "description": "Pi extension for durable background shell tasks, watchers, logs, and status inspection.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -2,6 +2,7 @@
2
2
  import { appendFileSync, closeSync, existsSync, openSync, readFileSync, mkdirSync, statSync } from "node:fs";
3
3
  import { dirname } from "node:path";
4
4
  import { createHash } from "node:crypto";
5
+ import { isPermissionBlocker, permissionBlockerKey, type PermissionBlocker } from "./shared-permission-blocker.ts";
5
6
 
6
7
  /**
7
8
  * Explicit, append-only incident dispositions (#315).
@@ -30,6 +31,7 @@ export interface FailureEvent {
30
31
  disposition?: IncidentDisposition;
31
32
  /** Disposition events only: why the incidents are classified this way. */
32
33
  reason?: string;
34
+ permissionBlockers?: PermissionBlocker[];
33
35
  }
34
36
  export interface DispositionRecord {
35
37
  eventId: string;
@@ -38,6 +40,7 @@ export interface DispositionRecord {
38
40
  reason: string;
39
41
  evidence?: string;
40
42
  at: number;
43
+ permissionBlockers?: PermissionBlocker[];
41
44
  }
42
45
  export interface FailureObservation {
43
46
  id: string;
@@ -56,6 +59,8 @@ export interface FailureObservation {
56
59
  resolvedAt?: number;
57
60
  /** Latest explicit disposition applied to this incident. */
58
61
  disposition?: DispositionRecord;
62
+ /** Retained even after recovery; active surfaces filter by current actionability. */
63
+ permissionBlockers?: PermissionBlocker[];
59
64
  }
60
65
  export interface FailureState {
61
66
  version: 1;
@@ -247,12 +252,26 @@ export function validateDisposition(state: FailureState, event: FailureEvent): s
247
252
  if (current.status !== "unresolved") return `Incident ${id} is already disposed (${failureLabel(current).toLowerCase()})`;
248
253
  if (event.disposition === "open" && current.disposition?.disposition === "open") return `Incident ${id} is already open`;
249
254
  }
255
+ if (event.permissionBlockers !== undefined) {
256
+ if (event.disposition !== "open" || !Array.isArray(event.permissionBlockers) || !event.permissionBlockers.length ||
257
+ event.permissionBlockers.length > 20 || !event.permissionBlockers.every(isPermissionBlocker)) return "Invalid permission blocker metadata";
258
+ const bound = new Set<string>();
259
+ for (const blocker of event.permissionBlockers) {
260
+ const current = blocker.incidentId ? findIncident(state, blocker.incidentId) : undefined;
261
+ if (!current || !ids.includes(current.id) || current.category !== "tool" || current.operation !== blocker.operation ||
262
+ blocker.context !== "worker" || blocker.basis !== "agent-reported" || blocker.remoteOutcome !== "unknown" ||
263
+ blocker.policySnapshotId !== undefined || bound.has(current.id)) return "Permission blocker must name an unresolved failed worker attempt";
264
+ bound.add(current.id);
265
+ }
266
+ if (bound.size !== ids.length) return "Permission blocker metadata must cover every target";
267
+ }
250
268
  return undefined;
251
269
  }
252
270
 
253
271
  /** Pure transition. Lifecycle is deliberately not an input or an output. */
254
272
  export function reduceFailure(state: FailureState, event: FailureEvent, observedAt: number): FailureState {
255
273
  if (state.seen.includes(event.id)) return state;
274
+ if (event.permissionBlockers !== undefined && event.kind !== "disposition") return state;
256
275
  // Invalid dispositions fail closed: nothing changes and the id is not consumed.
257
276
  if (event.kind === "disposition" && validateDisposition(state, event)) return state;
258
277
  const next: FailureState = { ...state, seen: [...state.seen, event.id],
@@ -265,11 +284,13 @@ export function reduceFailure(state: FailureState, event: FailureEvent, observed
265
284
  const at = event.at ?? observedAt;
266
285
  const record: DispositionRecord = { eventId: event.id, disposition: event.disposition!, incidents: [...event.incidents!],
267
286
  reason: text(event.reason, ""), ...(event.evidence ? { evidence: text(event.evidence, "") } : {}), at };
287
+ if (event.permissionBlockers) record.permissionBlockers = event.permissionBlockers.map(x => ({ ...x }));
268
288
  for (const id of record.incidents) {
269
289
  const [key, current] = Object.entries(next.observations).find(([, item]) => item.id === id)!;
270
290
  const status = record.disposition === "recovered" ? "resolved" : record.disposition === "superseded" ? "superseded"
271
291
  : record.disposition === "expected" ? "expected" : current.status;
272
292
  next.observations[key] = { ...current, status, disposition: record,
293
+ ...(record.permissionBlockers ? { permissionBlockers: record.permissionBlockers.filter(x => x.incidentId === id) } : {}),
273
294
  ...(status === "resolved" || status === "superseded" ? { resolvedAt: at } : {}) };
274
295
  if (status === "resolved" || status === "superseded") next.resolved = { ...next.resolved, [id]: at };
275
296
  }
@@ -298,6 +319,7 @@ export function reduceFailure(state: FailureState, event: FailureEvent, observed
298
319
  lastObservedAt: observedAt, lastSequence: next.seen.length, at: event.at,
299
320
  count: active ? previous.count + 1 : 1,
300
321
  ...(active && previous.disposition ? { disposition: previous.disposition } : {}),
322
+ ...(active && previous.permissionBlockers ? { permissionBlockers: previous.permissionBlockers } : {}),
301
323
  };
302
324
  return next;
303
325
  }
@@ -315,6 +337,16 @@ export function activeFailures(state: FailureState): FailureObservation[] {
315
337
  export function actionableFailures(state: FailureState): FailureObservation[] {
316
338
  return activeFailures(state).filter(needsAction);
317
339
  }
340
+ /** Only currently actionable reports, not closed history or arbitrary tool-result claims. */
341
+ export function actionablePermissionBlockers(state: FailureState): PermissionBlocker[] {
342
+ const unique = new Map<string, PermissionBlocker>();
343
+ for (const incident of actionableFailures(state)) {
344
+ for (const blocker of incident.permissionBlockers ?? []) {
345
+ if (isPermissionBlocker(blocker)) unique.set(permissionBlockerKey(blocker), { ...blocker });
346
+ }
347
+ }
348
+ return [...unique.values()];
349
+ }
318
350
  function closedOrder(a: FailureObservation, b: FailureObservation): number {
319
351
  return (b.lastSequence ?? 0) - (a.lastSequence ?? 0) || b.lastObservedAt - a.lastObservedAt;
320
352
  }
@@ -449,12 +481,20 @@ export function shortEvidence(evidence: string): string {
449
481
  function failureRow(x: FailureObservation, detail: IncidentDetail = "compact"): string {
450
482
  const time = x.at === undefined ? `observed ${new Date(x.firstObservedAt).toISOString()}` : new Date(x.at).toISOString();
451
483
  const compact = detail !== "full";
484
+ const permission = Boolean(x.permissionBlockers?.length);
485
+ let annotation = "";
486
+ if (x.permissionBlockers?.length) {
487
+ const resources = x.permissionBlockers.map(b => b.resource).join(", ");
488
+ annotation = ` · Worker permission blocker: ${resources} (agent-reported; remote outcome unknown; not a foreground denial). No remote authorization or successful validation inferred.`;
489
+ if (needsAction(x)) annotation += " Changed worker settings require a fresh launch.";
490
+ }
452
491
  // Full rows (raw evidence) show the journal summary verbatim; compact rows unwrap and cap it.
453
- const summary = compact ? capUtf8(dropLoneSurrogates(unwrapToolResultText(x.summary)).replace(/\s+/g, " ").trim(), COMPACT_EXCERPT_BYTES) : x.summary;
492
+ const summary = compact && permission ? "Permission access failure" : compact ? capUtf8(dropLoneSurrogates(unwrapToolResultText(x.summary)).replace(/\s+/g, " ").trim(), COMPACT_EXCERPT_BYTES) : x.summary;
454
493
  const reason = x.disposition ? text(x.disposition.reason, "") : "";
455
- const disposition = x.disposition ? ` · ${x.disposition.disposition}: ${compact ? capUtf8(reason, COMPACT_EXCERPT_BYTES) : reason}` : "";
456
- const evidence = x.evidence ? text(x.evidence, "") : "";
457
- return `${failureLabel(x)} · ${time} · ${summary}${x.count > 1 ? ` (${x.count} occurrences)` : ""}${disposition}${evidence ? ` · evidence: ${compact ? shortEvidence(evidence) : evidence}` : ""}`;
494
+ const disposition = x.disposition ? ` · ${x.disposition.disposition}${compact && permission ? "" : `: ${compact ? capUtf8(reason, COMPACT_EXCERPT_BYTES) : reason}`}` : "";
495
+ const evidence = x.evidence && !(compact && permission) ? text(x.evidence, "") : "";
496
+ const proof = !compact && permission && x.disposition?.evidence ? ` · disposition evidence: ${text(x.disposition.evidence, "")}` : "";
497
+ return `${failureLabel(x)} · ${time} · ${summary}${x.count > 1 ? ` (${x.count} occurrences)` : ""}${disposition}${evidence ? ` · evidence: ${compact ? shortEvidence(evidence) : evidence}` : ""}${proof}${annotation}`;
458
498
  }
459
499
 
460
500
  /**
@@ -573,13 +613,15 @@ export interface FailureIncidentPage {
573
613
  */
574
614
  export function failureRevision(state: FailureState): string {
575
615
  return failureIdentity(Object.values(state.observations)
576
- .map((item) => [item.id, item.status, item.category, item.count, item.lastSequence ?? 0, item.summary, item.evidence ?? ""])
616
+ .map((item) => [item.id, item.status, item.category, item.count, item.lastSequence ?? 0, item.summary, item.evidence ?? "",
617
+ ...(item.permissionBlockers ? [item.permissionBlockers.map(permissionBlockerKey).sort()] : [])])
577
618
  .sort((a, b) => String(a[0]).localeCompare(String(b[0]))));
578
619
  }
579
620
 
580
621
  /** Digest of the rows a cursor pages. Scope and detail are part of it: the same incidents render different bytes. */
581
622
  function incidentRevision(state: FailureState, scope: IncidentScope = "actionable", detail: IncidentDetail = "compact"): string {
582
- return failureIdentity(scope, detail, scopedFailures(state, scope).map((item) => [item.id, item.status, item.count, item.summary, item.evidence ?? ""])).slice(0, 16);
623
+ return failureIdentity(scope, detail, scopedFailures(state, scope).map((item) => [item.id, item.status, item.count, item.summary, item.evidence ?? "",
624
+ ...(item.permissionBlockers ? [item.permissionBlockers.map(permissionBlockerKey).sort()] : [])])).slice(0, 16);
583
625
  }
584
626
 
585
627
  /** Cursors carry a digest of their resource/scope, not the scope text. */
@@ -999,6 +1041,8 @@ function readStoredState(path: string): FailureState {
999
1041
  !Number.isFinite(row.observedAt) || Math.abs(row.observedAt) > 8.64e15 ||
1000
1042
  (e.at !== undefined && (!Number.isFinite(e.at) || Math.abs(e.at) > 8.64e15)) ||
1001
1043
  (e.incidents !== undefined && (!Array.isArray(e.incidents) || !e.incidents.every((id: unknown) => typeof id === "string"))) ||
1044
+ (e.permissionBlockers !== undefined && (e.kind !== "disposition" ||
1045
+ (!state.seen.includes(e.id) && validateDisposition(state, e) !== undefined))) ||
1002
1046
  [e.summary, e.category, e.evidence, e.reason].some((v) => v !== undefined && typeof v !== "string")) throw new Error("invalid record");
1003
1047
  state = reduceFailure(state, e, row.observedAt);
1004
1048
  } catch { state = storageProblem(state, "Failure journal contains unreadable records; observations may be incomplete"); }
@@ -1021,6 +1065,7 @@ export function observeFailures(path: string, events: readonly FailureEvent[], n
1021
1065
  }
1022
1066
  // Rejected dispositions are never journaled or marked seen.
1023
1067
  if (raw.kind === "disposition" && validateDisposition(state, raw)) continue;
1068
+ if (raw.permissionBlockers !== undefined && raw.kind !== "disposition") continue;
1024
1069
  const event = { ...raw, ...(raw.summary ? { summary: text(raw.summary, "") } : {}),
1025
1070
  ...(raw.evidence ? { evidence: text(raw.evidence, "") } : {}), ...(raw.reason ? { reason: text(raw.reason, "") } : {}) };
1026
1071
  try {
@@ -0,0 +1,48 @@
1
+ // Generated from packages/failure-observations/permission-blocker.ts. Do not edit directly.
2
+ /** Privacy-safe wire contract. Context and identity must be assigned by a trusted adapter. */
3
+ export const PERMISSION_RESOURCES = Object.freeze([
4
+ "credential-files", "process-inspection", "project-files", "outside-project-files",
5
+ "runtime-control-files", "command-execution", "network-access", "unknown",
6
+ ] as const);
7
+ export type PermissionResource = typeof PERMISSION_RESOURCES[number];
8
+ export interface PermissionBlocker {
9
+ version: 1;
10
+ kind: "permission-blocker";
11
+ context: "worker" | "foreground";
12
+ resource: PermissionResource;
13
+ basis: "policy-refusal" | "os-permission-error" | "agent-reported";
14
+ /** A stable hash or bounded logical identifier, never a command or path. */
15
+ operation: string;
16
+ remoteOutcome: "unknown" | "not-started";
17
+ incidentId?: string;
18
+ runId?: string;
19
+ policySnapshotId?: string;
20
+ }
21
+ const FIELDS = new Set(["version", "kind", "context", "resource", "basis", "operation", "remoteOutcome", "incidentId", "runId", "policySnapshotId"]);
22
+ const LOGICAL_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/;
23
+ // Responses SDK references join call_id and item_id with "|"; these are opaque evidence ids,
24
+ // not caller-chosen logical operations. Keep the same bound and exclude paths and prose.
25
+ const INCIDENT_REFERENCE = /^[A-Za-z0-9][A-Za-z0-9._:|\-]{0,199}$/;
26
+ export function isPermissionResource(value: unknown): value is PermissionResource {
27
+ return typeof value === "string" && (PERMISSION_RESOURCES as readonly string[]).includes(value);
28
+ }
29
+ /** Pure and strict: no coercion, unknown fields, paths, argv, or free-form prose. */
30
+ export function isPermissionBlocker(value: unknown): value is PermissionBlocker {
31
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
32
+ const prototype = Object.getPrototypeOf(value);
33
+ if (prototype !== Object.prototype && prototype !== null) return false;
34
+ if (Reflect.ownKeys(value).some(key => typeof key !== "string" || !FIELDS.has(key))) return false;
35
+ const v = value as Record<string, unknown>;
36
+ if (v.version !== 1 || v.kind !== "permission-blocker" || !["worker", "foreground"].includes(v.context as string) ||
37
+ !isPermissionResource(v.resource) || !["policy-refusal", "os-permission-error", "agent-reported"].includes(v.basis as string) ||
38
+ !["unknown", "not-started"].includes(v.remoteOutcome as string) ||
39
+ typeof v.operation !== "string" || v.operation.length > 64 || !LOGICAL_ID.test(v.operation)) return false;
40
+ if (Object.hasOwn(v, "incidentId") && (typeof v.incidentId !== "string" || !INCIDENT_REFERENCE.test(v.incidentId))) return false;
41
+ return ["runId", "policySnapshotId"].every(key => !Object.hasOwn(v, key) ||
42
+ (typeof v[key] === "string" && LOGICAL_ID.test(v[key] as string)));
43
+ }
44
+ /** Order-independent identity without I/O or a platform-specific crypto dependency. */
45
+ export function permissionBlockerKey(blocker: PermissionBlocker): string {
46
+ return JSON.stringify([blocker.version, blocker.kind, blocker.context, blocker.resource, blocker.basis,
47
+ blocker.operation, blocker.remoteOutcome, blocker.incidentId ?? null, blocker.runId ?? null, blocker.policySnapshotId ?? null]);
48
+ }
@@ -60,6 +60,8 @@ export type SandboxPermissions = {
60
60
  storedCredentials: "off" | "read" | "read-write";
61
61
  commands: boolean;
62
62
  network: boolean;
63
+ /** Fixed process_list adapter only; omitted legacy profiles keep it Off. */
64
+ processAccess?: "off" | "read";
63
65
  };
64
66
 
65
67
  /** Whether a file access level allows creating and overwriting files. */