pi-better-background-tasks 0.18.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 (49) hide show
  1. package/README.md +4 -3
  2. package/package.json +1 -1
  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/goal-provider.ts +31 -16
  15. package/src/index.ts +6 -9
  16. package/src/managed-authority.ts +5 -3
  17. package/src/managed-client.ts +20 -7
  18. package/src/managed-frontend.ts +62 -17
  19. package/src/navigator-provider.ts +15 -5
  20. package/src/observed-wait-client.ts +10 -0
  21. package/src/observed-waits.ts +154 -30
  22. package/src/process-identity.ts +18 -2
  23. package/src/process.ts +3 -3
  24. package/src/registry.ts +53 -5
  25. package/src/runtime.ts +19 -9
  26. package/src/sandbox.ts +14 -11
  27. package/src/shared-callback-batcher.ts +11 -2
  28. package/src/shared-navigator-panels.ts +26 -4
  29. package/src/shared-navigator.ts +197 -14
  30. package/src/shared-operation-coordinator/assignment-observation.mjs +43 -35
  31. package/src/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  32. package/src/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  33. package/src/shared-operation-coordinator/src/background-requests.ts +14 -3
  34. package/src/shared-operation-coordinator/src/discovery.ts +5 -3
  35. package/src/shared-operation-coordinator/src/operations.ts +50 -2
  36. package/src/shared-operation-coordinator/src/result-supervision.ts +12 -0
  37. package/src/shared-operation-coordinator/src/rows.ts +2 -0
  38. package/src/shared-operation-coordinator/src/schema.ts +40 -24
  39. package/src/shared-operation-coordinator/src/store.ts +34 -8
  40. package/src/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  41. package/src/shared-operation-coordinator/src/types.ts +5 -1
  42. package/src/shared-sandbox-core.ts +1 -1
  43. package/src/shared-work-client.mjs +150 -7
  44. package/src/supervisor/generated/process-identity.mjs +20 -2
  45. package/src/supervisor/generated/process.mjs +3 -3
  46. package/src/task-diagnostics.ts +1 -1
  47. package/src/tools.ts +41 -38
  48. package/src/types.ts +3 -1
  49. 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,
@@ -18,26 +17,19 @@ import {
18
17
  import { cursorKind, readOutputControls } from "./shared-log-utils.js";
19
18
  import { cancelCallbackBatch, getCallbackBatcher, setCallbackBatchContext } from "./shared-callback-batcher.js";
20
19
  import { registerDeliveryObserver } from "./delivery-observer.js";
21
- import {
22
- formatWaitView,
23
- getObservedWaitHost,
24
- observedWaitServiceUnavailableReason,
25
- type DurableTaskKind,
26
- type DurableLaunch,
27
- type WaitView,
28
- } from "./observed-waits.js";
29
- 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";
30
23
  import { inspectMeta, listMetasForOrigin, readMeta, writeMeta } from "./registry.js";
31
- import { awaitFirstWatchCheck, FIRST_WATCH_CHECK_WAIT_MS, resumeRunningTask, spawnTask, startWatchTask, stopTask, type WatchTaskParams, type BackgroundTaskRuntime } from "./runtime.js";
32
- import { runTaskMaintenance } from "./maintenance.js";
24
+ import type { WatchTaskParams, BackgroundTaskRuntime } from "./runtime.js";
33
25
  import { backgroundProcessDiagnosticsAccess, ForegroundSandboxBlockedError } from "./sandbox.js";
34
26
  import { inspectTaskProcess } from "./task-diagnostics.js";
35
27
  import type { BackgroundTaskCallbackOrigin, BackgroundTaskMeta } from "./types.js";
36
- import { isTerminalStatus } from "./types.js";
28
+ import { FIRST_WATCH_CHECK_WAIT_MS, isTerminalStatus } from "./types.js";
37
29
 
38
30
  export { formatLaunch } from "./output.js";
39
31
 
40
- const defaultRuntime = { awaitFirstWatchCheck, resumeRunningTask, spawnTask, startWatchTask, stopTask };
32
+ type ToolRuntime = Pick<BackgroundTaskRuntime, "awaitFirstWatchCheck" | "resumeRunningTask" | "spawnTask" | "startWatchTask" | "stopTask">;
41
33
 
42
34
  const JsonPathSchema = Type.String({
43
35
  pattern: "^\\$",
@@ -178,7 +170,7 @@ const IdParams = Type.Object({
178
170
  ...CursorFields,
179
171
  });
180
172
  const HistoryField = {
181
- 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." })),
182
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." })),
183
175
  };
184
176
  const StatusParams = Type.Object({
@@ -299,8 +291,7 @@ const BACKGROUND_ORCHESTRATION_GUIDELINES = [
299
291
  "Do not treat launch as completion of the parent milestone; relevant background work must be terminal, inspected, and integrated before verification or completion.",
300
292
  ];
301
293
 
302
- export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRuntime, keyof typeof defaultRuntime> = defaultRuntime, refreshNavigator = refreshBackgroundTasksNavigator, options: { resumeLocal?: boolean } = {}): void {
303
- const { resumeRunningTask, spawnTask } = runtime;
294
+ export function registerTools(pi: ExtensionAPI, runtime?: ToolRuntime, refreshNavigator = refreshBackgroundTasksNavigator, options: { resumeLocal?: boolean } = {}): void {
304
295
  let activeSession: BackgroundTaskCallbackOrigin | undefined;
305
296
  const getActiveSession = () => activeSession;
306
297
  const schemas = new Map<string, object>();
@@ -316,12 +307,14 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
316
307
  setCallbackBatchContext(pi, ctx);
317
308
  activeSession = getCallbackOrigin(ctx);
318
309
  if (options.resumeLocal !== false) {
319
- for (const meta of listMetasForOrigin(activeSession)) {
320
- if (meta.status === "running" || (meta.callback !== false && !meta.callbackSentAt && !meta.callbackSuppressedAt)) {
321
- resumeRunningTask(pi, meta, getActiveSession);
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
+ }
322
316
  }
323
- }
324
- runTaskMaintenance({ activeOrigin: activeSession });
317
+ runTaskMaintenance({ activeOrigin: activeSession });
325
318
  }
326
319
  });
327
320
  pi.on("agent_start", (_event, ctx) => {
@@ -360,6 +353,7 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
360
353
  refreshNavigator(ctx);
361
354
  return text(durable, launchReceipt(receipt));
362
355
  }
356
+ const { spawnTask } = runtime ?? await import("./runtime.js");
363
357
  const launched = reportLaunch(() => spawnTask(pi, params, ctx.cwd, origin, getActiveSession));
364
358
  refreshNavigator(ctx);
365
359
  return text(launched);
@@ -374,6 +368,7 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
374
368
  parameters: BatchParams,
375
369
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
376
370
  activeSession = getCallbackOrigin(ctx);
371
+ const { formatBatchLaunch, spawnTaskBatch } = await import("./batch.js");
377
372
  const launched = spawnTaskBatch(pi, params, ctx.cwd, activeSession, getActiveSession, {}, runtime);
378
373
  refreshNavigator(ctx);
379
374
  return text(formatBatchLaunch(launched), launched);
@@ -456,7 +451,7 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
456
451
  refreshNavigator(ctx);
457
452
  return text(durable);
458
453
  }
459
- 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"));
460
455
  refreshNavigator(ctx);
461
456
  return text(result);
462
457
  },
@@ -473,7 +468,7 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
473
468
  },
474
469
  async execute(toolCallId, params, signal, _onUpdate, ctx) {
475
470
  activeSession = getCallbackOrigin(ctx);
476
- 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);
477
472
  },
478
473
  });
479
474
 
@@ -487,7 +482,7 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
487
482
  },
488
483
  async execute(toolCallId, params, _signal, _onUpdate, ctx) {
489
484
  activeSession = getCallbackOrigin(ctx);
490
- 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);
491
486
  },
492
487
  });
493
488
 
@@ -503,14 +498,14 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
503
498
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
504
499
  const host = getObservedWaitHost(pi);
505
500
  if (!host?.available) {
506
- return text(observedWaitServiceUnavailableReason(pi)
501
+ return text((await import("./observed-waits.js")).observedWaitServiceUnavailableReason(pi)
507
502
  ?? "Observed waits are unavailable in this session; inspect tasks directly and continue without a durable wait.");
508
503
  }
509
504
  try {
510
505
  const wait = host.usesServerResults
511
506
  ? await host.superviseParentWait(ctx, params.task_ids, params.continuation_note)
512
507
  : host.waitForParent(ctx, params.task_ids, params.continuation_note);
513
- return text(formatWaitView(wait), wait);
508
+ return text((await import("./observed-waits.js")).formatWaitView(wait), wait);
514
509
  } catch (error) {
515
510
  return text(`Wait was not registered: ${readableError(error)}`);
516
511
  }
@@ -525,7 +520,7 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
525
520
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
526
521
  const host = getObservedWaitHost(pi);
527
522
  if (!host?.available) {
528
- return text(observedWaitServiceUnavailableReason(pi)
523
+ return text((await import("./observed-waits.js")).observedWaitServiceUnavailableReason(pi)
529
524
  ?? "Observed waits are unavailable in this session; no wait was consumed.");
530
525
  }
531
526
  try {
@@ -571,6 +566,7 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
571
566
  try {
572
567
  const waits = host.listWaitsForParent(ctx, { pendingOnly: params.pending_only === true });
573
568
  if (waits.length === 0) return text("No durable waits for this session.");
569
+ const { formatWaitView } = await import("./observed-waits.js");
574
570
  return text(waits.map((wait: WaitView) => formatWaitView(wait)).join("\n\n"), waits);
575
571
  } catch (error) {
576
572
  return text(`Waits could not be listed: ${readableError(error)}`);
@@ -671,7 +667,7 @@ async function actionText(
671
667
  callbackOrigin: BackgroundTaskCallbackOrigin,
672
668
  getActiveSession: () => BackgroundTaskCallbackOrigin | undefined,
673
669
  signal: AbortSignal | undefined,
674
- runtime: Pick<BackgroundTaskRuntime, keyof typeof defaultRuntime>,
670
+ runtime: ToolRuntime,
675
671
  refreshNavigator: typeof refreshBackgroundTasksNavigator,
676
672
  ) {
677
673
  if (params.action === "log" && params.id) {
@@ -691,7 +687,7 @@ async function runAction(
691
687
  callbackOrigin: BackgroundTaskCallbackOrigin,
692
688
  getActiveSession: () => BackgroundTaskCallbackOrigin | undefined,
693
689
  signal: AbortSignal | undefined,
694
- runtime: Pick<BackgroundTaskRuntime, keyof typeof defaultRuntime>,
690
+ runtime: ToolRuntime,
695
691
  refreshNavigator: typeof refreshBackgroundTasksNavigator,
696
692
  onLaunch?: (launch: DurableLaunch) => void,
697
693
  ): Promise<string> {
@@ -746,7 +742,7 @@ async function runAction(
746
742
  }
747
743
  }
748
744
 
749
- /** Shared history applies ownership, filters and paging before metadata crosses the socket. */
745
+ /** Ordinary lists reuse retained activity; explicit filtered/paged lists open history. */
750
746
  async function durableAwareList(
751
747
  pi: ExtensionAPI,
752
748
  params: Record<string, unknown>,
@@ -754,10 +750,16 @@ async function durableAwareList(
754
750
  ctx: ExtensionContext,
755
751
  ): Promise<string> {
756
752
  const options = listOptions(params, origin);
757
- 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,
758
755
  { limit: options.limit, statuses: options.statuses, cursor: options.cursor }) : undefined;
759
756
  if (snapshot && snapshot.status !== "ready") throw new Error(snapshot.reason ?? "Background activity is unverified");
760
- 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);
761
763
  if (snapshot) return legacy;
762
764
  const host = getObservedWaitHost(pi);
763
765
  if ((!snapshot && !host?.available) || !origin || typeof params.cursor === "string") return legacy;
@@ -925,9 +927,9 @@ export async function launchWatch(
925
927
  getActiveSession: () => BackgroundTaskCallbackOrigin | undefined,
926
928
  waitMs = FIRST_WATCH_CHECK_WAIT_MS,
927
929
  signal?: AbortSignal,
928
- runtime: Pick<BackgroundTaskRuntime, keyof typeof defaultRuntime> = defaultRuntime,
930
+ runtime?: ToolRuntime,
929
931
  ): Promise<string> {
930
- const { startWatchTask, awaitFirstWatchCheck } = runtime;
932
+ const { startWatchTask, awaitFirstWatchCheck } = runtime ?? await import("./runtime.js");
931
933
  let meta: BackgroundTaskMeta;
932
934
  try {
933
935
  meta = startWatchTask(pi, params, cwd, callbackOrigin, getActiveSession);
@@ -954,7 +956,8 @@ function getCallbackOrigin(ctx: ExtensionContext | undefined): BackgroundTaskCal
954
956
  sessionId = undefined;
955
957
  unavailable = true;
956
958
  }
957
- const origin = { cwd: ctx?.cwd ?? "", sessionId };
959
+ const origin: BackgroundTaskCallbackOrigin = { cwd: ctx?.cwd ?? "", sessionId,
960
+ branchId: ctx?.sessionManager?.getLeafId?.() ?? null };
958
961
  if (unavailable) unavailableSessionOrigins.add(origin);
959
962
  return origin;
960
963
  }
@@ -1073,9 +1076,9 @@ async function formatStop(
1073
1076
  _ctx: ExtensionContext,
1074
1077
  getActiveSession?: () => BackgroundTaskCallbackOrigin | undefined,
1075
1078
  options: OutputOptions = {},
1076
- runtime: Pick<BackgroundTaskRuntime, "stopTask"> = defaultRuntime,
1079
+ runtime?: Pick<BackgroundTaskRuntime, "stopTask">,
1077
1080
  ): Promise<string> {
1078
- const { stopTask } = runtime;
1081
+ const { stopTask } = runtime ?? await import("./runtime.js");
1079
1082
  const existing = inspectMeta(id);
1080
1083
  if (!existing.meta && !existing.found) return formatStopResult(existing, options);
1081
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
  }