pi-better-background-tasks 0.13.1 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +67 -0
  2. package/package.json +3 -1
  3. package/src/adapter-contract.ts +16 -2
  4. package/src/batch.ts +108 -0
  5. package/src/delivery-observer.ts +42 -0
  6. package/src/goal-provider.ts +72 -5
  7. package/src/index.ts +39 -0
  8. package/src/navigator-provider.ts +175 -6
  9. package/src/observed-waits.ts +3677 -0
  10. package/src/runtime.ts +10 -0
  11. package/src/sandbox.ts +276 -2
  12. package/src/shared-execution-policy.ts +2 -0
  13. package/src/shared-operation-coordinator/index.ts +113 -0
  14. package/src/shared-operation-coordinator/src/errors.ts +75 -0
  15. package/src/shared-operation-coordinator/src/operations.ts +376 -0
  16. package/src/shared-operation-coordinator/src/outbox.ts +431 -0
  17. package/src/shared-operation-coordinator/src/rows.ts +439 -0
  18. package/src/shared-operation-coordinator/src/schema.ts +244 -0
  19. package/src/shared-operation-coordinator/src/sqlite.ts +239 -0
  20. package/src/shared-operation-coordinator/src/store.ts +397 -0
  21. package/src/shared-operation-coordinator/src/types.ts +648 -0
  22. package/src/shared-operation-coordinator/src/validate.ts +239 -0
  23. package/src/shared-operation-coordinator/src/waits.ts +1378 -0
  24. package/src/supervisor/README.md +111 -0
  25. package/src/supervisor/emit-runner.mjs +101 -0
  26. package/src/supervisor/generated/conditions.mjs +96 -0
  27. package/src/supervisor/generated/identity.mjs +95 -0
  28. package/src/supervisor/generated/process-identity.mjs +43 -0
  29. package/src/supervisor/generated/process.mjs +514 -0
  30. package/src/supervisor/generated/runner.mjs +872 -0
  31. package/src/supervisor/generated/store.mjs +605 -0
  32. package/src/supervisor/generated/types.mjs +50 -0
  33. package/src/supervisor/identity.ts +99 -0
  34. package/src/supervisor/index.ts +37 -0
  35. package/src/supervisor/invocation.ts +44 -0
  36. package/src/supervisor/runner.ts +982 -0
  37. package/src/supervisor/store.ts +649 -0
  38. package/src/supervisor/supervisor.ts +730 -0
  39. package/src/supervisor/types.ts +384 -0
  40. package/src/tools.ts +396 -9
  41. package/src/types.ts +8 -0
@@ -14,6 +14,7 @@ import { actionableFailures, failureLabel, readFailureState } from "./shared-fai
14
14
  import { failurePath, failureView } from "./failures.js";
15
15
  import { readLog } from "./logs.js";
16
16
  import { listMetasForOrigin, onMetaChanged, readMeta, writeMeta } from "./registry.js";
17
+ import { getObservedWaitHost, type DurableTaskProjection } from "./observed-waits.js";
17
18
  import { stopTask } from "./runtime.js";
18
19
  import { formatBackgroundTaskStall, observeBackgroundTaskStall } from "./stall.js";
19
20
  import type { BackgroundTaskCallbackOrigin, BackgroundTaskMeta, BackgroundTaskStatus } from "./types.js";
@@ -24,8 +25,15 @@ let activeNavigatorOrigin: BackgroundTaskCallbackOrigin | undefined;
24
25
  const TERMINAL_NAVIGATOR_RETENTION_MS = 30_000;
25
26
 
26
27
  export function ensureBackgroundTasksNavigatorProvider(pi: ExtensionAPI): void {
28
+ // A reloaded or replaced extension instance gets a fresh host. Re-register so
29
+ // the provider's durable-change subscription targets that host, not the one
30
+ // captured by the previous instance.
31
+ if (piRef === pi && unregister) return;
32
+ if (unregister) {
33
+ try { unregister(); } catch { /* ignore */ }
34
+ unregister = undefined;
35
+ }
27
36
  piRef = pi;
28
- if (unregister) return;
29
37
  unregister = registerBackgroundWorkProvider(provider);
30
38
  }
31
39
 
@@ -51,11 +59,36 @@ const provider: BackgroundWorkProvider = {
51
59
  id: "background-tasks",
52
60
  label: "Background Tasks",
53
61
  priority: 20,
54
- visibleCount: () => visibleMetas(Date.now()).filter((meta) => meta.status === "running").length,
55
- listRows: (now) => visibleMetas(now).map((meta) => rowFromMeta(meta, now)),
56
- detail: (id, now, options) => detailFromMeta(readMeta(id), now, options),
57
- armCloseLabel: (row) => row.status === "running" ? "x again to stop" : "x again to dismiss",
62
+ visibleCount: () => {
63
+ const now = Date.now();
64
+ return visibleMetas(now).filter((meta) => meta.status === "running").length
65
+ + visibleDurableTasks(now).filter((task) => task.active).length;
66
+ },
67
+ listRows: (now) => [
68
+ ...visibleMetas(now).map((meta) => rowFromMeta(meta, now)),
69
+ ...visibleDurableTasks(now).map((task) => rowFromDurable(task, now)),
70
+ ],
71
+ detail: (id, now, options) => {
72
+ const durable = durableTask(id);
73
+ if (durable) return detailFromDurable(durable, options);
74
+ return detailFromMeta(readMeta(id), now, options);
75
+ },
76
+ armCloseLabel: (row) => row.status === "running" || row.status === "starting" ? "x again to stop" : "x again to dismiss",
58
77
  close: (id) => {
78
+ const durable = durableTask(id);
79
+ if (durable) {
80
+ const host = navigatorHost();
81
+ const origin = activeNavigatorOrigin;
82
+ if (!host || !origin) return { action: "missing", providerId: "background-tasks", id };
83
+ if (durable.active) {
84
+ void host.stopDurableTask(origin, id);
85
+ return { action: "stopped", providerId: "background-tasks", id, status: "stopping" };
86
+ }
87
+ if (host.dismissDurableTask(origin, id)) {
88
+ return { action: "dismissed", providerId: "background-tasks", id, status: durable.status };
89
+ }
90
+ return { action: "denied", providerId: "background-tasks", id };
91
+ }
59
92
  const meta = readMeta(id);
60
93
  if (!meta) return { action: "missing", providerId: "background-tasks", id };
61
94
  if (meta.status === "running") {
@@ -66,9 +99,145 @@ const provider: BackgroundWorkProvider = {
66
99
  writeMeta(meta);
67
100
  return { action: "dismissed", providerId: "background-tasks", id, status: meta.status };
68
101
  },
69
- onVisibleChanged: onMetaChanged,
102
+ onVisibleChanged: (notify) => {
103
+ const offMeta = onMetaChanged(notify);
104
+ const offDurable = getObservedWaitHost(piRef)?.onDurableTaskChange(notify);
105
+ return () => {
106
+ offMeta();
107
+ offDurable?.();
108
+ };
109
+ },
70
110
  };
71
111
 
112
+ function navigatorHost() {
113
+ return piRef ? getObservedWaitHost(piRef) : undefined;
114
+ }
115
+
116
+ function visibleDurableTasks(now = Date.now()): DurableTaskProjection[] {
117
+ const active = activeNavigatorOrigin;
118
+ const host = navigatorHost();
119
+ if (!active || !host) return [];
120
+ const listed = host.listDurableTasks(active, { retentionMs: TERMINAL_NAVIGATOR_RETENTION_MS });
121
+ return listed
122
+ .filter((task) => task.dismissedAt === undefined && !isExpiredDurableRow(task, now));
123
+ }
124
+
125
+ function durableTask(id: string): DurableTaskProjection | undefined {
126
+ const active = activeNavigatorOrigin;
127
+ const host = navigatorHost();
128
+ if (!active || !host) return undefined;
129
+ return host.readDurableTask(active, id);
130
+ }
131
+
132
+ function isExpiredDurableRow(task: DurableTaskProjection, now: number): boolean {
133
+ if (!task.terminal || task.endedAt === undefined) return false;
134
+ return now - task.endedAt >= TERMINAL_NAVIGATOR_RETENTION_MS;
135
+ }
136
+
137
+ function rowFromDurable(task: DurableTaskProjection, now: number): BackgroundWorkRow {
138
+ const command = durableCommandLabel(task);
139
+ const elapsed = formatDuration((task.endedAt ?? now) - task.startedAt);
140
+ const facts: string[] = [];
141
+ if (task.attention && task.reason) facts.push(task.reason);
142
+ else if (task.attention) facts.push(task.status);
143
+ if (task.kind === "watch" && task.intervalSeconds) facts.push(`every ${formatDuration(task.intervalSeconds * 1000)}`);
144
+ if (task.active && task.deadlineAt) facts.push(`${formatDuration(task.deadlineAt - now)} left`);
145
+ if (task.waits.length) facts.push(`${task.waits.length} wait${task.waits.length === 1 ? "" : "s"}`);
146
+ return {
147
+ providerId: "background-tasks",
148
+ id: task.id,
149
+ name: task.name,
150
+ status: task.status,
151
+ statusTone: toneForDurableStatus(task.status),
152
+ kind: task.kind,
153
+ elapsed,
154
+ primary: compactDurableLabel(task),
155
+ command,
156
+ tool: compactDurableLabel(task),
157
+ secondary: [task.cwd, task.exitCode !== null ? `exit ${task.exitCode}` : undefined].filter(Boolean).join(" · ") || undefined,
158
+ facts: facts.slice(0, 2),
159
+ sortStartedAt: task.startedAt,
160
+ expiresAt: task.terminal && task.endedAt !== undefined
161
+ ? task.endedAt + TERMINAL_NAVIGATOR_RETENTION_MS
162
+ : undefined,
163
+ };
164
+ }
165
+
166
+ function detailFromDurable(task: DurableTaskProjection, options?: { logTailLines?: number }): BackgroundWorkDetail {
167
+ const active = activeNavigatorOrigin;
168
+ const host = navigatorHost();
169
+ const lines = options?.logTailLines ?? NAVIGATOR_DETAIL_ROWS;
170
+ const log = active && host ? host.readDurableTaskLog(active, task.id, lines) : undefined;
171
+ const metadata = [
172
+ { label: "provider", value: "Background Tasks (durable)" },
173
+ { label: "kind", value: task.kind },
174
+ { label: "operation", value: task.operationId },
175
+ { label: "status", value: `${task.status}${task.terminalOutcome ? ` (${task.terminalOutcome})` : ""}` },
176
+ { label: "started", value: new Date(task.startedAt).toISOString() },
177
+ ...(task.endedAt !== undefined ? [{ label: "ended", value: new Date(task.endedAt).toISOString() }] : []),
178
+ { label: "cwd", value: task.cwd },
179
+ ...(task.exitCode !== null || task.signal ? [{ label: "exit", value: `${task.exitCode ?? "null"}${task.signal ? ` signal ${task.signal}` : ""}` }] : []),
180
+ ...(task.reason ? [{ label: "reason", value: task.reason }] : []),
181
+ ...(task.stepGateFailure ? [{ label: "step gate", value: `${task.stepGateFailure.command} exited ${task.stepGateFailure.stepExitCode}` }] : []),
182
+ { label: "stdout", value: task.logPaths.stdout },
183
+ { label: "stderr", value: task.logPaths.stderr },
184
+ { label: "events", value: task.logPaths.events },
185
+ ...(task.waits.length
186
+ ? [{ label: "waits", value: task.waits.map((wait) => `${wait.waitId} ${wait.phase}`).join(", ") }]
187
+ : []),
188
+ ];
189
+ const evidenceText = log
190
+ ? [log.stdout, log.stderr ? `stderr:\n${log.stderr}` : "", log.events ? `events:\n${log.events}` : ""]
191
+ .filter(Boolean).join("\n") || "(log is empty)"
192
+ : "(durable log is unavailable)";
193
+ return {
194
+ providerId: "background-tasks",
195
+ id: task.id,
196
+ title: task.name || task.id,
197
+ status: task.status,
198
+ statusTone: toneForDurableStatus(task.status),
199
+ subtitle: task.stepGateFailure?.command ?? task.reason ?? compactDurableLabel(task),
200
+ metadata,
201
+ foldedSections: [{
202
+ id: "command",
203
+ label: "command",
204
+ text: task.command ?? (task.argv ? task.argv.join(" ") : "(no command recorded)"),
205
+ collapsedText: compactDurableLabel(task),
206
+ expandedByDefault: true,
207
+ }],
208
+ evidence: {
209
+ label: log?.truncated ? "log tail" : "log",
210
+ text: evidenceText,
211
+ },
212
+ footerActions: [task.active ? "x stop" : "x dismiss"],
213
+ };
214
+ }
215
+
216
+ function durableCommandLabel(task: DurableTaskProjection): string {
217
+ if (task.command) return task.command;
218
+ if (task.argv?.length) return task.argv.join(" ");
219
+ return task.name ?? "(no command recorded)";
220
+ }
221
+
222
+ function compactDurableLabel(task: DurableTaskProjection): string {
223
+ const value = durableCommandLabel(task).trim();
224
+ const parts = value.split(/\s+/).filter(Boolean);
225
+ return parts.length <= 3 ? value : parts.slice(0, 3).join(" ");
226
+ }
227
+
228
+ function toneForDurableStatus(status: string): BackgroundWorkRow["statusTone"] {
229
+ switch (status) {
230
+ case "running":
231
+ case "starting": return "running";
232
+ case "succeeded": return "success";
233
+ case "failed":
234
+ case "timed_out":
235
+ case "lost": return "failed";
236
+ case "cancelled": return "warning";
237
+ default: return "muted";
238
+ }
239
+ }
240
+
72
241
  function visibleMetas(now = Date.now()): BackgroundTaskMeta[] {
73
242
  const active = activeNavigatorOrigin;
74
243
  if (!active) return [];