pi-better-background-tasks 0.17.0 → 0.19.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 (55) hide show
  1. package/README.md +4 -3
  2. package/package.json +4 -2
  3. package/runtime-client/artifacts/darwin-arm64.gz +0 -0
  4. package/runtime-client/artifacts/darwin-arm64.json +1 -1
  5. package/runtime-client/artifacts/darwin-x64.gz +0 -0
  6. package/runtime-client/artifacts/darwin-x64.json +1 -1
  7. package/runtime-client/artifacts/linux-arm64.gz +0 -0
  8. package/runtime-client/artifacts/linux-arm64.json +1 -1
  9. package/runtime-client/artifacts/linux-x64.gz +0 -0
  10. package/runtime-client/artifacts/linux-x64.json +1 -1
  11. package/runtime-client/src/runtime/client.mjs +30 -3
  12. package/runtime-client/src/runtime/work-client.mjs +150 -7
  13. package/src/adapter-contract.ts +1 -1
  14. package/src/failures.ts +4 -2
  15. package/src/goal-provider.ts +31 -16
  16. package/src/index.ts +9 -37
  17. package/src/managed-authority.ts +30 -0
  18. package/src/managed-client.ts +73 -0
  19. package/src/managed-frontend.ts +176 -0
  20. package/src/navigator-provider.ts +28 -10
  21. package/src/observed-wait-client.ts +10 -0
  22. package/src/observed-waits.ts +268 -62
  23. package/src/output.ts +12 -0
  24. package/src/process-identity.ts +18 -2
  25. package/src/process.ts +3 -3
  26. package/src/registry.ts +71 -6
  27. package/src/runtime.ts +26 -10
  28. package/src/sandbox.ts +21 -11
  29. package/src/shared-callback-batcher.ts +15 -3
  30. package/src/shared-failure-observations.ts +3 -0
  31. package/src/shared-navigator-panels.ts +26 -4
  32. package/src/shared-navigator.ts +220 -19
  33. package/src/shared-operation-coordinator/assignment-observation.mjs +71 -33
  34. package/src/shared-operation-coordinator/index.ts +2 -0
  35. package/src/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  36. package/src/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  37. package/src/shared-operation-coordinator/src/background-parent-callbacks.ts +68 -0
  38. package/src/shared-operation-coordinator/src/background-requests.ts +90 -0
  39. package/src/shared-operation-coordinator/src/discovery.ts +5 -3
  40. package/src/shared-operation-coordinator/src/operations.ts +50 -2
  41. package/src/shared-operation-coordinator/src/result-supervision.ts +12 -0
  42. package/src/shared-operation-coordinator/src/rows.ts +2 -0
  43. package/src/shared-operation-coordinator/src/schema.ts +71 -24
  44. package/src/shared-operation-coordinator/src/store.ts +50 -6
  45. package/src/shared-operation-coordinator/src/subagent-launch.ts +142 -0
  46. package/src/shared-operation-coordinator/src/types.ts +5 -1
  47. package/src/shared-operation-coordinator/src/upgrade.ts +22 -0
  48. package/src/shared-sandbox-core.ts +1 -1
  49. package/src/shared-work-client.mjs +150 -7
  50. package/src/supervisor/generated/process-identity.mjs +20 -2
  51. package/src/supervisor/generated/process.mjs +3 -3
  52. package/src/task-diagnostics.ts +1 -1
  53. package/src/tools.ts +60 -41
  54. package/src/types.ts +3 -1
  55. package/src/work-observation.ts +46 -19
package/src/tools.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  import { Type } from "typebox";
2
2
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
3
  import { advertiseBackgroundAdapter } from "./adapter-contract.js";
4
- import { formatBatchLaunch, spawnTaskBatch } from "./batch.js";
5
4
  import { refreshBackgroundTasksNavigator } from "./navigator-provider.js";
6
5
  import {
7
6
  classifyOwnership,
@@ -11,32 +10,26 @@ import {
11
10
  formatMissingTask,
12
11
  formatMutationRefusal,
13
12
  formatStatus,
13
+ formatDurableStatusMetadata,
14
14
  formatStopResult,
15
15
  type OutputOptions,
16
16
  } from "./output.js";
17
17
  import { cursorKind, readOutputControls } from "./shared-log-utils.js";
18
18
  import { cancelCallbackBatch, getCallbackBatcher, setCallbackBatchContext } from "./shared-callback-batcher.js";
19
19
  import { registerDeliveryObserver } from "./delivery-observer.js";
20
- import {
21
- formatWaitView,
22
- getObservedWaitHost,
23
- observedWaitServiceUnavailableReason,
24
- type DurableTaskKind,
25
- type DurableLaunch,
26
- type WaitView,
27
- } from "./observed-waits.js";
28
- import { backgroundObservation } from "./work-observation.js";
20
+ import { getObservedWaitHost } from "./observed-wait-client.js";
21
+ import type { DurableTaskKind, DurableLaunch, WaitView } from "./observed-waits.js";
22
+ import { backgroundListNeedsHistory, backgroundObservation } from "./work-observation.js";
29
23
  import { inspectMeta, listMetasForOrigin, readMeta, writeMeta } from "./registry.js";
30
- import { awaitFirstWatchCheck, FIRST_WATCH_CHECK_WAIT_MS, resumeRunningTask, spawnTask, startWatchTask, stopTask, type WatchTaskParams, type BackgroundTaskRuntime } from "./runtime.js";
31
- import { runTaskMaintenance } from "./maintenance.js";
24
+ import type { WatchTaskParams, BackgroundTaskRuntime } from "./runtime.js";
32
25
  import { backgroundProcessDiagnosticsAccess, ForegroundSandboxBlockedError } from "./sandbox.js";
33
26
  import { inspectTaskProcess } from "./task-diagnostics.js";
34
27
  import type { BackgroundTaskCallbackOrigin, BackgroundTaskMeta } from "./types.js";
35
- import { isTerminalStatus } from "./types.js";
28
+ import { FIRST_WATCH_CHECK_WAIT_MS, isTerminalStatus } from "./types.js";
36
29
 
37
30
  export { formatLaunch } from "./output.js";
38
31
 
39
- const defaultRuntime = { awaitFirstWatchCheck, resumeRunningTask, spawnTask, startWatchTask, stopTask };
32
+ type ToolRuntime = Pick<BackgroundTaskRuntime, "awaitFirstWatchCheck" | "resumeRunningTask" | "spawnTask" | "startWatchTask" | "stopTask">;
40
33
 
41
34
  const JsonPathSchema = Type.String({
42
35
  pattern: "^\\$",
@@ -177,7 +170,7 @@ const IdParams = Type.Object({
177
170
  ...CursorFields,
178
171
  });
179
172
  const HistoryField = {
180
- 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." })),
173
+ diagnostics: Type.Optional(Type.Boolean({ description: "For status: sample registered task process identity, CPU time, state and wait evidence. Requires Process access Read in each enabled sandbox profile (Main and Background tasks); unavailable under Main confinement. No arguments, environment or remote probes; a snapshot cannot prove useful work or a hang." })),
181
174
  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." })),
182
175
  };
183
176
  const StatusParams = Type.Object({
@@ -298,8 +291,7 @@ const BACKGROUND_ORCHESTRATION_GUIDELINES = [
298
291
  "Do not treat launch as completion of the parent milestone; relevant background work must be terminal, inspected, and integrated before verification or completion.",
299
292
  ];
300
293
 
301
- export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRuntime, keyof typeof defaultRuntime> = defaultRuntime, refreshNavigator = refreshBackgroundTasksNavigator): void {
302
- const { resumeRunningTask, spawnTask } = runtime;
294
+ export function registerTools(pi: ExtensionAPI, runtime?: ToolRuntime, refreshNavigator = refreshBackgroundTasksNavigator, options: { resumeLocal?: boolean } = {}): void {
303
295
  let activeSession: BackgroundTaskCallbackOrigin | undefined;
304
296
  const getActiveSession = () => activeSession;
305
297
  const schemas = new Map<string, object>();
@@ -314,12 +306,16 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
314
306
  pi.on("session_start", async (_event, ctx) => {
315
307
  setCallbackBatchContext(pi, ctx);
316
308
  activeSession = getCallbackOrigin(ctx);
317
- for (const meta of listMetasForOrigin(activeSession)) {
318
- if (meta.status === "running" || (meta.callback !== false && !meta.callbackSentAt && !meta.callbackSuppressedAt)) {
319
- resumeRunningTask(pi, meta, getActiveSession);
309
+ if (options.resumeLocal !== false) {
310
+ const { resumeRunningTask } = runtime ?? await import("./runtime.js");
311
+ const { runTaskMaintenance } = await import("./maintenance.js");
312
+ for (const meta of listMetasForOrigin(activeSession)) {
313
+ if (meta.status === "running" || (meta.callback !== false && !meta.callbackSentAt && !meta.callbackSuppressedAt)) {
314
+ resumeRunningTask(pi, meta, getActiveSession);
315
+ }
320
316
  }
317
+ runTaskMaintenance({ activeOrigin: activeSession });
321
318
  }
322
- runTaskMaintenance({ activeOrigin: activeSession });
323
319
  });
324
320
  pi.on("agent_start", (_event, ctx) => {
325
321
  setCallbackBatchContext(pi, ctx);
@@ -357,6 +353,7 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
357
353
  refreshNavigator(ctx);
358
354
  return text(durable, launchReceipt(receipt));
359
355
  }
356
+ const { spawnTask } = runtime ?? await import("./runtime.js");
360
357
  const launched = reportLaunch(() => spawnTask(pi, params, ctx.cwd, origin, getActiveSession));
361
358
  refreshNavigator(ctx);
362
359
  return text(launched);
@@ -371,6 +368,7 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
371
368
  parameters: BatchParams,
372
369
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
373
370
  activeSession = getCallbackOrigin(ctx);
371
+ const { formatBatchLaunch, spawnTaskBatch } = await import("./batch.js");
374
372
  const launched = spawnTaskBatch(pi, params, ctx.cwd, activeSession, getActiveSession, {}, runtime);
375
373
  refreshNavigator(ctx);
376
374
  return text(formatBatchLaunch(launched), launched);
@@ -417,7 +415,7 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
417
415
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
418
416
  const origin = getCallbackOrigin(ctx);
419
417
  activeSession = origin;
420
- const durable = await durableStatusText(pi, params.id, ctx);
418
+ const durable = await durableStatusText(pi, params.id, ctx, params);
421
419
  if (durable !== undefined) return text(durable);
422
420
  return text(taskStatus(pi, params.id, params, statusOptions(params, origin)));
423
421
  },
@@ -453,7 +451,7 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
453
451
  refreshNavigator(ctx);
454
452
  return text(durable);
455
453
  }
456
- const result = await formatStop(pi, params.id, ctx, getActiveSession, statusOptions(params, origin), runtime);
454
+ const result = await formatStop(pi, params.id, ctx, getActiveSession, statusOptions(params, origin), runtime ?? await import("./runtime.js"));
457
455
  refreshNavigator(ctx);
458
456
  return text(result);
459
457
  },
@@ -470,7 +468,7 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
470
468
  },
471
469
  async execute(toolCallId, params, signal, _onUpdate, ctx) {
472
470
  activeSession = getCallbackOrigin(ctx);
473
- return actionText(pi, { ...params, request_id: params.request_id ?? toolCallId }, ctx, activeSession, getActiveSession, signal, runtime, refreshNavigator);
471
+ return actionText(pi, { ...params, request_id: params.request_id ?? toolCallId }, ctx, activeSession, getActiveSession, signal, runtime ?? await import("./runtime.js"), refreshNavigator);
474
472
  },
475
473
  });
476
474
 
@@ -484,7 +482,7 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
484
482
  },
485
483
  async execute(toolCallId, params, _signal, _onUpdate, ctx) {
486
484
  activeSession = getCallbackOrigin(ctx);
487
- return actionText(pi, { ...params, request_id: params.request_id ?? toolCallId }, ctx, activeSession, getActiveSession, undefined, runtime, refreshNavigator);
485
+ return actionText(pi, { ...params, request_id: params.request_id ?? toolCallId }, ctx, activeSession, getActiveSession, undefined, runtime ?? await import("./runtime.js"), refreshNavigator);
488
486
  },
489
487
  });
490
488
 
@@ -500,14 +498,14 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
500
498
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
501
499
  const host = getObservedWaitHost(pi);
502
500
  if (!host?.available) {
503
- return text(observedWaitServiceUnavailableReason(pi)
501
+ return text((await import("./observed-waits.js")).observedWaitServiceUnavailableReason(pi)
504
502
  ?? "Observed waits are unavailable in this session; inspect tasks directly and continue without a durable wait.");
505
503
  }
506
504
  try {
507
505
  const wait = host.usesServerResults
508
506
  ? await host.superviseParentWait(ctx, params.task_ids, params.continuation_note)
509
507
  : host.waitForParent(ctx, params.task_ids, params.continuation_note);
510
- return text(formatWaitView(wait), wait);
508
+ return text((await import("./observed-waits.js")).formatWaitView(wait), wait);
511
509
  } catch (error) {
512
510
  return text(`Wait was not registered: ${readableError(error)}`);
513
511
  }
@@ -522,7 +520,7 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
522
520
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
523
521
  const host = getObservedWaitHost(pi);
524
522
  if (!host?.available) {
525
- return text(observedWaitServiceUnavailableReason(pi)
523
+ return text((await import("./observed-waits.js")).observedWaitServiceUnavailableReason(pi)
526
524
  ?? "Observed waits are unavailable in this session; no wait was consumed.");
527
525
  }
528
526
  try {
@@ -568,6 +566,7 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
568
566
  try {
569
567
  const waits = host.listWaitsForParent(ctx, { pendingOnly: params.pending_only === true });
570
568
  if (waits.length === 0) return text("No durable waits for this session.");
569
+ const { formatWaitView } = await import("./observed-waits.js");
571
570
  return text(waits.map((wait: WaitView) => formatWaitView(wait)).join("\n\n"), waits);
572
571
  } catch (error) {
573
572
  return text(`Waits could not be listed: ${readableError(error)}`);
@@ -668,7 +667,7 @@ async function actionText(
668
667
  callbackOrigin: BackgroundTaskCallbackOrigin,
669
668
  getActiveSession: () => BackgroundTaskCallbackOrigin | undefined,
670
669
  signal: AbortSignal | undefined,
671
- runtime: Pick<BackgroundTaskRuntime, keyof typeof defaultRuntime>,
670
+ runtime: ToolRuntime,
672
671
  refreshNavigator: typeof refreshBackgroundTasksNavigator,
673
672
  ) {
674
673
  if (params.action === "log" && params.id) {
@@ -688,7 +687,7 @@ async function runAction(
688
687
  callbackOrigin: BackgroundTaskCallbackOrigin,
689
688
  getActiveSession: () => BackgroundTaskCallbackOrigin | undefined,
690
689
  signal: AbortSignal | undefined,
691
- runtime: Pick<BackgroundTaskRuntime, keyof typeof defaultRuntime>,
690
+ runtime: ToolRuntime,
692
691
  refreshNavigator: typeof refreshBackgroundTasksNavigator,
693
692
  onLaunch?: (launch: DurableLaunch) => void,
694
693
  ): Promise<string> {
@@ -710,7 +709,7 @@ async function runAction(
710
709
  return durableAwareList(pi, params, callbackOrigin, ctx);
711
710
  case "status": {
712
711
  if (!params.id) return "Invalid parameters: status requires id.";
713
- const durable = await durableStatusText(pi, String(params.id), ctx);
712
+ const durable = await durableStatusText(pi, String(params.id), ctx, params);
714
713
  if (durable !== undefined) return durable;
715
714
  return taskStatus(pi, String(params.id), params, statusOptions(params, callbackOrigin));
716
715
  }
@@ -743,7 +742,7 @@ async function runAction(
743
742
  }
744
743
  }
745
744
 
746
- /** Shared history applies ownership, filters and paging before metadata crosses the socket. */
745
+ /** Ordinary lists reuse retained activity; explicit filtered/paged lists open history. */
747
746
  async function durableAwareList(
748
747
  pi: ExtensionAPI,
749
748
  params: Record<string, unknown>,
@@ -751,10 +750,16 @@ async function durableAwareList(
751
750
  ctx: ExtensionContext,
752
751
  ): Promise<string> {
753
752
  const options = listOptions(params, origin);
754
- const snapshot = origin && !unavailableSessionOrigins.has(origin) ? await backgroundObservation(pi, ctx, true, params.all === true,
753
+ const history = backgroundListNeedsHistory(params);
754
+ const snapshot = origin && !unavailableSessionOrigins.has(origin) ? await backgroundObservation(pi, ctx, history, params.all === true,
755
755
  { limit: options.limit, statuses: options.statuses, cursor: options.cursor }) : undefined;
756
756
  if (snapshot && snapshot.status !== "ready") throw new Error(snapshot.reason ?? "Background activity is unverified");
757
- const legacy = formatList(options, snapshot?.backgroundIndex);
757
+ const index = snapshot?.backgroundIndex ?? (snapshot ? { records: snapshot.rows
758
+ .map((row: any) => ({ found: true, meta: row.meta.durable ? { ...row.meta,
759
+ callbackOrigin: { cwd: row.meta.owner.workspace, sessionId: row.meta.owner.sessionId },
760
+ logPath: row.meta.logPaths?.stdout ?? "" } : row.meta }))
761
+ .sort((a: any, b: any) => b.meta.startedAt - a.meta.startedAt || b.meta.id.localeCompare(a.meta.id)) } : undefined);
762
+ const legacy = formatList(options, index);
758
763
  if (snapshot) return legacy;
759
764
  const host = getObservedWaitHost(pi);
760
765
  if ((!snapshot && !host?.available) || !origin || typeof params.cursor === "string") return legacy;
@@ -840,11 +845,24 @@ async function durableLaunchText(
840
845
  }
841
846
  }
842
847
 
843
- async function durableStatusText(pi: ExtensionAPI, id: string, ctx: ExtensionContext): Promise<string | undefined> {
848
+ async function durableStatusText(pi: ExtensionAPI, id: string, ctx: ExtensionContext, params: Record<string, unknown>): Promise<string | undefined> {
844
849
  const host = getObservedWaitHost(pi);
845
850
  if (!host || !host.isDurableTask(id)) return undefined;
846
851
  try {
847
- return host.formatStatus(await host.settledStatusForParent(ctx, id));
852
+ const view = await host.settledStatusForParent(ctx, id);
853
+ if (params.verbose === true || cursorKind(typeof params.cursor === "string" ? params.cursor : undefined) === "t") {
854
+ const origin = { cwd: ctx.cwd, sessionId: ctx.sessionManager.getSessionId() };
855
+ const task = host.readDurableTask(origin, id);
856
+ if (!task) return `Background task ${id} is outside the current session scope.`;
857
+ const meta = {
858
+ ...task, kind: task.kind === "watch" ? "command_watch" : "process", status: view.status,
859
+ argv: task.argv ? [...task.argv] : undefined,
860
+ logPath: task.logPaths.stdout, callbackOrigin: origin,
861
+ lastExitCode: view.exitCode, result: task.terminal ? { exitCode: view.exitCode, signal: view.signal } : undefined,
862
+ };
863
+ return formatDurableStatusMetadata(meta, statusOptions(params, origin));
864
+ }
865
+ return host.formatStatus(view);
848
866
  } catch (error) {
849
867
  return readableError(error);
850
868
  }
@@ -909,9 +927,9 @@ export async function launchWatch(
909
927
  getActiveSession: () => BackgroundTaskCallbackOrigin | undefined,
910
928
  waitMs = FIRST_WATCH_CHECK_WAIT_MS,
911
929
  signal?: AbortSignal,
912
- runtime: Pick<BackgroundTaskRuntime, keyof typeof defaultRuntime> = defaultRuntime,
930
+ runtime?: ToolRuntime,
913
931
  ): Promise<string> {
914
- const { startWatchTask, awaitFirstWatchCheck } = runtime;
932
+ const { startWatchTask, awaitFirstWatchCheck } = runtime ?? await import("./runtime.js");
915
933
  let meta: BackgroundTaskMeta;
916
934
  try {
917
935
  meta = startWatchTask(pi, params, cwd, callbackOrigin, getActiveSession);
@@ -938,7 +956,8 @@ function getCallbackOrigin(ctx: ExtensionContext | undefined): BackgroundTaskCal
938
956
  sessionId = undefined;
939
957
  unavailable = true;
940
958
  }
941
- const origin = { cwd: ctx?.cwd ?? "", sessionId };
959
+ const origin: BackgroundTaskCallbackOrigin = { cwd: ctx?.cwd ?? "", sessionId,
960
+ branchId: ctx?.sessionManager?.getLeafId?.() ?? null };
942
961
  if (unavailable) unavailableSessionOrigins.add(origin);
943
962
  return origin;
944
963
  }
@@ -1057,9 +1076,9 @@ async function formatStop(
1057
1076
  _ctx: ExtensionContext,
1058
1077
  getActiveSession?: () => BackgroundTaskCallbackOrigin | undefined,
1059
1078
  options: OutputOptions = {},
1060
- runtime: Pick<BackgroundTaskRuntime, "stopTask"> = defaultRuntime,
1079
+ runtime?: Pick<BackgroundTaskRuntime, "stopTask">,
1061
1080
  ): Promise<string> {
1062
- const { stopTask } = runtime;
1081
+ const { stopTask } = runtime ?? await import("./runtime.js");
1063
1082
  const existing = inspectMeta(id);
1064
1083
  if (!existing.meta && !existing.found) return formatStopResult(existing, options);
1065
1084
  if (!existing.meta) return formatMissingTask(existing, options);
package/src/types.ts CHANGED
@@ -93,6 +93,7 @@ export interface ResolvedRemoteTaskMetadata {
93
93
  export interface BackgroundTaskCallbackOrigin {
94
94
  cwd: string;
95
95
  sessionId?: string;
96
+ branchId?: string | null;
96
97
  }
97
98
 
98
99
  export interface TaskSandboxProvenance {
@@ -231,4 +232,5 @@ export interface TerminalResult {
231
232
 
232
233
  export function isTerminalStatus(status: BackgroundTaskStatus): boolean {
233
234
  return status !== "running";
234
- }
235
+ }
236
+ export const FIRST_WATCH_CHECK_WAIT_MS = 15_000;
@@ -4,18 +4,44 @@ import { join } from "node:path";
4
4
  import { homedir } from "node:os";
5
5
  import { setTimeout as delay } from "node:timers/promises";
6
6
 
7
+ import { cursorKind } from "./shared-log-utils.js";
8
+
7
9
  const hostedClients = new WeakSet<object>();
10
+ const connectionAborts = new WeakMap<object, AbortController>();
8
11
  const clients = new WeakMap<object, Promise<any>>();
9
12
  const generations = new WeakMap<object, number>();
10
13
  const listeners = new WeakMap<object, Set<() => void>>();
14
+ const subscribedClients = new WeakMap<object, any>();
15
+ const activityScopes = new WeakMap<object, string>();
16
+
17
+ /** Goal reads the subscribed observation, never a periodic full-state RPC. */
18
+ export async function backgroundGoalObservation(pi: ExtensionAPI, ctx: ExtensionContext, cachedOnly = false): Promise<any> {
19
+ const scope = { background: true, cwd: ctx.cwd, sessionId: ctx.sessionManager?.getSessionId(), processId: process.pid };
20
+ const key = JSON.stringify(scope);
21
+ if (cachedOnly) {
22
+ const client = subscribedClients.get(pi);
23
+ return client && !client.closed && activityScopes.get(client) === key ? client.snapshot : undefined;
24
+ }
25
+ const client = await observationClient(pi, scope);
26
+ if (activityScopes.get(client) !== key) {
27
+ await client.subscribe(scope);
28
+ activityScopes.set(client, key);
29
+ }
30
+ return client.snapshot;
31
+ }
11
32
  export function onBackgroundObservation(pi: ExtensionAPI, notify: () => void): () => void {
12
33
  let set = listeners.get(pi);
13
34
  if (!set) { set = new Set(); listeners.set(pi, set); }
14
35
  set.add(notify); return () => { set.delete(notify); };
15
36
  }
16
37
 
38
+ export function backgroundListNeedsHistory(params: Record<string, unknown>): boolean {
39
+ return params.all === true || params.limit !== undefined || params.status !== undefined
40
+ || typeof params.cursor === "string" && cursorKind(params.cursor) !== "s";
41
+ }
42
+
17
43
  /** A query connection grants no supervisor, transcript writer or retention authority. */
18
- export function backgroundObservation(pi: ExtensionAPI, ctx: ExtensionContext, history = false, all = false, page?: { limit?: number; statuses?: string[]; cursor?: string }): Promise<any> {
44
+ export function backgroundObservation(pi: ExtensionAPI, ctx: ExtensionContext, history = false, all = false, page?: { limit?: number; statuses?: string[]; cursor?: string }, wait?: { timeoutMs: number; signal?: AbortSignal }): Promise<any> {
19
45
  const scope = { background: true, cwd: ctx.cwd, sessionId: ctx.sessionManager?.getSessionId(), processId: process.pid };
20
46
  const generation = generations.get(pi) ?? 0;
21
47
  const read = async (retry: boolean): Promise<any> => {
@@ -24,12 +50,13 @@ export function backgroundObservation(pi: ExtensionAPI, ctx: ExtensionContext, h
24
50
  const client = await connection;
25
51
  if ((generations.get(pi) ?? 0) !== generation) throw new Error("runtime-unavailable: client closed");
26
52
  try {
27
- const deadline = Date.now() + 20000;
53
+ const deadline = Date.now() + (wait?.timeoutMs ?? 20000);
28
54
  for (;;) {
55
+ wait?.signal?.throwIfAborted();
29
56
  checkGeneration();
30
57
  const snapshot = await client.get({ ...scope, backgroundHistory: history, backgroundAll: all, ...page });
31
58
  if (!history || snapshot.status !== "rebuilding" || Date.now() >= deadline) return snapshot;
32
- await delay(20);
59
+ await delay(wait ? 100 : 20, undefined, { signal: wait?.signal });
33
60
  }
34
61
  }
35
62
  catch (error) {
@@ -49,6 +76,8 @@ function observationClient(pi: ExtensionAPI, scope: { background: boolean; cwd:
49
76
  };
50
77
  let pending = clients.get(pi);
51
78
  if (!pending) {
79
+ const controller = new AbortController();
80
+ connectionAborts.set(pi, controller);
52
81
  pending = (async () => {
53
82
  let hosted: any;
54
83
  let rejected: unknown;
@@ -59,50 +88,46 @@ function observationClient(pi: ExtensionAPI, scope: { background: boolean; cwd:
59
88
  if (hosted) {
60
89
  hostedClients.add(hosted);
61
90
  hosted.onChange(() => { for (const notify of listeners.get(pi) ?? []) notify(); });
62
- try { await hosted.subscribe(scope); checkOpen(); return hosted; }
91
+ try { await hosted.subscribe(scope); activityScopes.set(hosted, JSON.stringify({ ...scope, processId: process.pid })); checkOpen(); subscribedClients.set(pi, hosted); return hosted; }
63
92
  catch (error) { hosted.close(); throw error; }
64
93
  }
65
94
  const requestedRoot = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
66
95
  mkdirSync(requestedRoot, { recursive: true, mode: 0o700 });
67
96
  const root = realpathSync(requestedRoot);
68
- const ensure = async () => {
69
- checkOpen();
97
+ const ensure = async (timeoutMs?: number, signal?: AbortSignal) => {
70
98
  const installer = new URL("../runtime-client/src/runtime/client.mjs", import.meta.url).href;
71
99
  const { ensureRuntime } = await import(installer);
72
- checkOpen();
73
- await ensureRuntime({ agentDir: root, serverDir: process.env.PI_SERVER_DIR });
100
+ await ensureRuntime({ agentDir: root, serverDir: process.env.PI_SERVER_DIR, timeoutMs, signal });
74
101
  };
75
102
  let registration;
76
103
  try { registration = JSON.parse(readFileSync(join(root, "server-registration-v1.json"), "utf8")); }
77
104
  catch (error) {
78
105
  if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
79
- await ensure();
106
+ await ensure(undefined, controller.signal);
80
107
  registration = JSON.parse(readFileSync(join(root, "server-registration-v1.json"), "utf8"));
81
108
  }
82
109
  if (registration.version !== 1 || registration.agentDir !== root) throw new Error("Invalid canonical runtime registration");
83
110
  const module = new URL("./shared-work-client.mjs", import.meta.url).href;
84
- const { WorkClient } = await import(module);
111
+ const { connectWorkClient } = await import(module);
85
112
  const connect = async () => {
86
113
  checkOpen();
87
- const client = new WorkClient(join(registration.serverDir, "pi-server.sock"), root, ["runtime-background-state-v1"]);
114
+ const client = await connectWorkClient(join(registration.serverDir, "pi-server.sock"), root, ["runtime-background-state-v1"], {
115
+ signal: controller.signal, recover: ({ timeoutMs, signal }: { timeoutMs: number; signal: AbortSignal }) => ensure(timeoutMs, signal),
116
+ });
88
117
  let subscribed = false;
89
118
  client.onChange(() => {
90
119
  if (!subscribed || clients.get(pi) !== pending) return;
91
120
  if (client.closed) clients.delete(pi);
92
121
  for (const notify of listeners.get(pi) ?? []) notify();
93
122
  });
94
- try { await client.subscribe(scope); }
123
+ try { checkOpen(); await client.subscribe(scope); checkOpen(); }
95
124
  catch (error) { client.close(); throw error; }
125
+ subscribedClients.set(pi, client);
96
126
  subscribed = true;
127
+ activityScopes.set(client, JSON.stringify({ ...scope, processId: process.pid }));
97
128
  return client;
98
129
  };
99
- try { return await connect(); }
100
- catch (error) {
101
- if (!["ENOENT", "ECONNREFUSED"].includes((error as NodeJS.ErrnoException).code ?? "")) throw error;
102
- // Registration chooses transport; only the owner-safe installer may recover it.
103
- await ensure();
104
- return connect();
105
- }
130
+ return connect();
106
131
  })();
107
132
  clients.set(pi, pending);
108
133
  pending.catch(() => { if (clients.get(pi) === pending) clients.delete(pi); });
@@ -111,7 +136,9 @@ function observationClient(pi: ExtensionAPI, scope: { background: boolean; cwd:
111
136
  }
112
137
 
113
138
  export function closeBackgroundObservation(pi: ExtensionAPI): void {
139
+ subscribedClients.delete(pi);
114
140
  generations.set(pi, (generations.get(pi) ?? 0) + 1);
141
+ connectionAborts.get(pi)?.abort(); connectionAborts.delete(pi);
115
142
  const pending = clients.get(pi); clients.delete(pi);
116
143
  void pending?.then(client => client.close(), () => {});
117
144
  }