pi-better-background-tasks 0.16.0 → 0.18.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 (40) hide show
  1. package/README.md +9 -0
  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/daemon-owner.mjs +2 -1
  12. package/runtime-client/src/runtime/work-client.mjs +16 -2
  13. package/src/failures.ts +4 -2
  14. package/src/index.ts +6 -30
  15. package/src/managed-authority.ts +28 -0
  16. package/src/managed-client.ts +60 -0
  17. package/src/managed-frontend.ts +131 -0
  18. package/src/navigator-provider.ts +14 -6
  19. package/src/observed-waits.ts +286 -48
  20. package/src/output.ts +12 -0
  21. package/src/registry.ts +18 -1
  22. package/src/runtime.ts +8 -2
  23. package/src/sandbox.ts +7 -0
  24. package/src/shared-callback-batcher.ts +4 -1
  25. package/src/shared-failure-observations.ts +3 -0
  26. package/src/shared-navigator.ts +23 -5
  27. package/src/shared-operation-coordinator/assignment-observation.mjs +48 -1
  28. package/src/shared-operation-coordinator/index.ts +2 -0
  29. package/src/shared-operation-coordinator/src/background-parent-callbacks.ts +68 -0
  30. package/src/shared-operation-coordinator/src/background-requests.ts +79 -0
  31. package/src/shared-operation-coordinator/src/discovery.ts +9 -0
  32. package/src/shared-operation-coordinator/src/operations.ts +6 -4
  33. package/src/shared-operation-coordinator/src/result-supervision.ts +128 -0
  34. package/src/shared-operation-coordinator/src/schema.ts +50 -1
  35. package/src/shared-operation-coordinator/src/store.ts +38 -0
  36. package/src/shared-operation-coordinator/src/subagent-launch.ts +119 -0
  37. package/src/shared-operation-coordinator/src/types.ts +6 -0
  38. package/src/shared-operation-coordinator/src/upgrade.ts +22 -0
  39. package/src/shared-work-client.mjs +16 -2
  40. package/src/tools.ts +76 -37
package/src/tools.ts CHANGED
@@ -11,6 +11,7 @@ import {
11
11
  formatMissingTask,
12
12
  formatMutationRefusal,
13
13
  formatStatus,
14
+ formatDurableStatusMetadata,
14
15
  formatStopResult,
15
16
  type OutputOptions,
16
17
  } from "./output.js";
@@ -22,6 +23,7 @@ import {
22
23
  getObservedWaitHost,
23
24
  observedWaitServiceUnavailableReason,
24
25
  type DurableTaskKind,
26
+ type DurableLaunch,
25
27
  type WaitView,
26
28
  } from "./observed-waits.js";
27
29
  import { backgroundObservation } from "./work-observation.js";
@@ -297,7 +299,7 @@ const BACKGROUND_ORCHESTRATION_GUIDELINES = [
297
299
  "Do not treat launch as completion of the parent milestone; relevant background work must be terminal, inspected, and integrated before verification or completion.",
298
300
  ];
299
301
 
300
- export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRuntime, keyof typeof defaultRuntime> = defaultRuntime, refreshNavigator = refreshBackgroundTasksNavigator): void {
302
+ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRuntime, keyof typeof defaultRuntime> = defaultRuntime, refreshNavigator = refreshBackgroundTasksNavigator, options: { resumeLocal?: boolean } = {}): void {
301
303
  const { resumeRunningTask, spawnTask } = runtime;
302
304
  let activeSession: BackgroundTaskCallbackOrigin | undefined;
303
305
  const getActiveSession = () => activeSession;
@@ -313,12 +315,14 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
313
315
  pi.on("session_start", async (_event, ctx) => {
314
316
  setCallbackBatchContext(pi, ctx);
315
317
  activeSession = getCallbackOrigin(ctx);
318
+ if (options.resumeLocal !== false) {
316
319
  for (const meta of listMetasForOrigin(activeSession)) {
317
320
  if (meta.status === "running" || (meta.callback !== false && !meta.callbackSentAt && !meta.callbackSuppressedAt)) {
318
321
  resumeRunningTask(pi, meta, getActiveSession);
319
322
  }
320
323
  }
321
324
  runTaskMaintenance({ activeOrigin: activeSession });
325
+ }
322
326
  });
323
327
  pi.on("agent_start", (_event, ctx) => {
324
328
  setCallbackBatchContext(pi, ctx);
@@ -348,13 +352,15 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
348
352
  promptGuidelines: BACKGROUND_ORCHESTRATION_GUIDELINES,
349
353
  parameters: SpawnParams,
350
354
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
351
- activeSession = getCallbackOrigin(ctx);
352
- const durable = await durableLaunchText(pi, "process", params, ctx);
355
+ const origin = getCallbackOrigin(ctx);
356
+ activeSession = origin;
357
+ let receipt: DurableLaunch | undefined;
358
+ const durable = await durableLaunchText(pi, "process", params, ctx, launch => { receipt = launch; });
353
359
  if (durable !== undefined) {
354
360
  refreshNavigator(ctx);
355
- return text(durable);
361
+ return text(durable, launchReceipt(receipt));
356
362
  }
357
- const launched = reportLaunch(() => spawnTask(pi, params, ctx.cwd, activeSession, getActiveSession));
363
+ const launched = reportLaunch(() => spawnTask(pi, params, ctx.cwd, origin, getActiveSession));
358
364
  refreshNavigator(ctx);
359
365
  return text(launched);
360
366
  },
@@ -381,13 +387,15 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
381
387
  promptGuidelines: BACKGROUND_ORCHESTRATION_GUIDELINES,
382
388
  parameters: WatchParams,
383
389
  async execute(_toolCallId, params, signal, _onUpdate, ctx) {
384
- activeSession = getCallbackOrigin(ctx);
385
- const durable = await durableLaunchText(pi, "watch", params, ctx);
390
+ const origin = getCallbackOrigin(ctx);
391
+ activeSession = origin;
392
+ let receipt: DurableLaunch | undefined;
393
+ const durable = await durableLaunchText(pi, "watch", params, ctx, launch => { receipt = launch; });
386
394
  if (durable !== undefined) {
387
395
  refreshNavigator(ctx);
388
- return text(durable);
396
+ return text(durable, launchReceipt(receipt));
389
397
  }
390
- const launched = await launchWatch(pi, params, ctx.cwd, activeSession, getActiveSession, FIRST_WATCH_CHECK_WAIT_MS, signal, runtime);
398
+ const launched = await launchWatch(pi, params, ctx.cwd, origin, getActiveSession, FIRST_WATCH_CHECK_WAIT_MS, signal, runtime);
391
399
  refreshNavigator(ctx);
392
400
  return text(launched);
393
401
  },
@@ -410,10 +418,11 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
410
418
  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.",
411
419
  parameters: StatusParams,
412
420
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
413
- activeSession = getCallbackOrigin(ctx);
414
- const durable = durableStatusText(pi, params.id, ctx);
421
+ const origin = getCallbackOrigin(ctx);
422
+ activeSession = origin;
423
+ const durable = await durableStatusText(pi, params.id, ctx, params);
415
424
  if (durable !== undefined) return text(durable);
416
- return text(taskStatus(pi, params.id, params, statusOptions(params, activeSession)));
425
+ return text(taskStatus(pi, params.id, params, statusOptions(params, origin)));
417
426
  },
418
427
  });
419
428
 
@@ -426,10 +435,11 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
426
435
  return renderBackgroundTaskLogDisplay(result, options, theme);
427
436
  },
428
437
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
429
- activeSession = ctx ? getCallbackOrigin(ctx) : activeSession;
430
- const durable = durableLogText(pi, params.id, params, ctx);
438
+ const origin = getCallbackOrigin(ctx);
439
+ activeSession = origin;
440
+ const durable = await durableLogText(pi, params.id, params, ctx);
431
441
  if (durable !== undefined) return text(durable);
432
- return logText(params.id, logOptions(params, activeSession));
442
+ return logText(params.id, logOptions(params, origin));
433
443
  },
434
444
  });
435
445
 
@@ -439,13 +449,14 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
439
449
  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.",
440
450
  parameters: Type.Object({ ...IdParams.properties, request_id: Type.Optional(Type.String({ description: "Stable cancellation request identity. Reuse this value after a disconnect." })) }),
441
451
  async execute(toolCallId, params, _signal, _onUpdate, ctx) {
442
- activeSession = getCallbackOrigin(ctx);
452
+ const origin = getCallbackOrigin(ctx);
453
+ activeSession = origin;
443
454
  const durable = await durableStopText(pi, params.id, ctx, params.request_id ?? toolCallId);
444
455
  if (durable !== undefined) {
445
456
  refreshNavigator(ctx);
446
457
  return text(durable);
447
458
  }
448
- const result = await formatStop(pi, params.id, ctx, getActiveSession, statusOptions(params, activeSession), runtime);
459
+ const result = await formatStop(pi, params.id, ctx, getActiveSession, statusOptions(params, origin), runtime);
449
460
  refreshNavigator(ctx);
450
461
  return text(result);
451
462
  },
@@ -496,7 +507,9 @@ export function registerTools(pi: ExtensionAPI, runtime: Pick<BackgroundTaskRunt
496
507
  ?? "Observed waits are unavailable in this session; inspect tasks directly and continue without a durable wait.");
497
508
  }
498
509
  try {
499
- const wait = host.waitForParent(ctx, params.task_ids, params.continuation_note);
510
+ const wait = host.usesServerResults
511
+ ? await host.superviseParentWait(ctx, params.task_ids, params.continuation_note)
512
+ : host.waitForParent(ctx, params.task_ids, params.continuation_note);
500
513
  return text(formatWaitView(wait), wait);
501
514
  } catch (error) {
502
515
  return text(`Wait was not registered: ${readableError(error)}`);
@@ -592,6 +605,11 @@ export function text(textValue: string, details?: unknown) {
592
605
  return { content: [{ type: "text" as const, text: textValue }], details };
593
606
  }
594
607
 
608
+ function launchReceipt(launch?: DurableLaunch) {
609
+ return launch ? { id: launch.id, operationId: launch.operationId, kind: launch.kind,
610
+ owner: launch.owner, started: launch.started, claimed: launch.claimed } : undefined;
611
+ }
612
+
595
613
  /** Requested byte budget: canonical `max_bytes`, else the deprecated `maxBytes` alias (#321). */
596
614
  function requestedMaxBytes(params: Record<string, unknown>): number | undefined {
597
615
  const value = readOutputControls(params).maxBytes;
@@ -657,11 +675,13 @@ async function actionText(
657
675
  refreshNavigator: typeof refreshBackgroundTasksNavigator,
658
676
  ) {
659
677
  if (params.action === "log" && params.id) {
660
- const durable = durableLogText(pi, String(params.id), params, ctx);
678
+ const durable = await durableLogText(pi, String(params.id), params, ctx);
661
679
  if (durable !== undefined) return text(durable);
662
680
  return logText(String(params.id), logOptions(params, callbackOrigin));
663
681
  }
664
- return text(await runAction(pi, params, ctx, callbackOrigin, getActiveSession, signal, runtime, refreshNavigator));
682
+ let receipt: DurableLaunch | undefined;
683
+ return text(await runAction(pi, params, ctx, callbackOrigin, getActiveSession, signal, runtime, refreshNavigator,
684
+ launch => { receipt = launch; }), launchReceipt(receipt));
665
685
  }
666
686
 
667
687
  async function runAction(
@@ -673,18 +693,19 @@ async function runAction(
673
693
  signal: AbortSignal | undefined,
674
694
  runtime: Pick<BackgroundTaskRuntime, keyof typeof defaultRuntime>,
675
695
  refreshNavigator: typeof refreshBackgroundTasksNavigator,
696
+ onLaunch?: (launch: DurableLaunch) => void,
676
697
  ): Promise<string> {
677
698
  const { spawnTask } = runtime;
678
699
  const withNavigatorRefresh = (ctx: ExtensionContext, result: string) => { refreshNavigator(ctx); return result; };
679
700
  switch (params.action) {
680
701
  case "spawn": {
681
- const durable = await durableLaunchText(pi, "process", params, ctx);
702
+ const durable = await durableLaunchText(pi, "process", params, ctx, onLaunch);
682
703
  if (durable !== undefined) return withNavigatorRefresh(ctx, durable);
683
704
  return withNavigatorRefresh(ctx, reportLaunch(() => spawnTask(pi, params, ctx.cwd, callbackOrigin, getActiveSession)));
684
705
  }
685
706
  case "watch": {
686
707
  if (!params.success_when) return "Invalid parameters: watch requires success_when.";
687
- const durable = await durableLaunchText(pi, "watch", params, ctx);
708
+ const durable = await durableLaunchText(pi, "watch", params, ctx, onLaunch);
688
709
  if (durable !== undefined) return withNavigatorRefresh(ctx, durable);
689
710
  return withNavigatorRefresh(ctx, await launchWatch(pi, params as unknown as WatchTaskParams, ctx.cwd, callbackOrigin, getActiveSession, FIRST_WATCH_CHECK_WAIT_MS, signal, runtime));
690
711
  }
@@ -692,13 +713,13 @@ async function runAction(
692
713
  return durableAwareList(pi, params, callbackOrigin, ctx);
693
714
  case "status": {
694
715
  if (!params.id) return "Invalid parameters: status requires id.";
695
- const durable = durableStatusText(pi, String(params.id), ctx);
716
+ const durable = await durableStatusText(pi, String(params.id), ctx, params);
696
717
  if (durable !== undefined) return durable;
697
718
  return taskStatus(pi, String(params.id), params, statusOptions(params, callbackOrigin));
698
719
  }
699
720
  case "log": {
700
721
  if (!params.id) return "Invalid parameters: log requires id.";
701
- const durable = durableLogText(pi, String(params.id), params, ctx);
722
+ const durable = await durableLogText(pi, String(params.id), params, ctx);
702
723
  if (durable !== undefined) return durable;
703
724
  return formatLog(String(params.id), logOptions(params, callbackOrigin));
704
725
  }
@@ -710,6 +731,7 @@ async function runAction(
710
731
  }
711
732
  case "clear": {
712
733
  const host = getObservedWaitHost(pi);
734
+ await host?.refreshManagedResults();
713
735
  const durableId = typeof params.id === "string" && params.id && host?.isDurableTask(params.id) === true;
714
736
  if (durableId) {
715
737
  return withNavigatorRefresh(ctx, dismissDurableForClear(pi, params, callbackOrigin)
@@ -776,13 +798,13 @@ function dismissDurableForClear(
776
798
  if (!host.isDurableTask(id)) return undefined;
777
799
  const task = host.readDurableTask(origin, id);
778
800
  if (!task) return `Durable operation ${id} belongs to another session; it was not dismissed.`;
779
- if (!task.terminal) return `Durable operation ${id} is ${task.status}; stop it before dismissing it.`;
780
801
  const dismissed = host.dismissDurableTask(origin, id);
802
+ if (!dismissed && !task.terminal) return `Durable operation ${id} is ${task.status}; stop it before dismissing it.`;
781
803
  return dismissed
782
804
  ? `Dismissed durable operation ${id}. Its terminal evidence remains available through bg_task_status and bg_task_log.`
783
805
  : `Durable operation ${id} was not dismissed.`;
784
806
  }
785
- const terminal = host.listDurableTasks(origin).filter((task) => task.terminal);
807
+ const terminal = host.listDurableTasks(origin, { fresh: true }).filter((task) => task.terminal);
786
808
  let dismissed = 0;
787
809
  for (const task of terminal) if (host.dismissDurableTask(origin, task.id)) dismissed += 1;
788
810
  return dismissed > 0
@@ -796,9 +818,10 @@ function readableError(error: unknown): string {
796
818
 
797
819
  /**
798
820
  * Route a local launch through the durable supervisor when the observed-waits
799
- * host is open. `undefined` means "use the legacy task route": remote/SSH work,
800
- * an extension installed without the durable host, or a session that has not
801
- * activated yet. Admission and sandboxing happen inside the host, through the
821
+ * host is installed. `undefined` means "use the legacy task route": remote/SSH
822
+ * work, an extension without the durable host, or a session not yet activated.
823
+ * A failed activation is never permission to start a second legacy command.
824
+ * Admission and sandboxing happen inside the host, through the
802
825
  * same `resolve*SandboxPlan` helpers the legacy route uses.
803
826
  */
804
827
  async function durableLaunchText(
@@ -806,11 +829,13 @@ async function durableLaunchText(
806
829
  kind: DurableTaskKind,
807
830
  params: Record<string, unknown>,
808
831
  ctx: ExtensionContext,
832
+ onLaunch?: (launch: DurableLaunch) => void,
809
833
  ): Promise<string | undefined> {
810
834
  const host = getObservedWaitHost(pi);
811
- if (!host?.available || params.ssh) return undefined;
835
+ if (!host || params.ssh || !host.available && !host.hasActivated) return undefined;
812
836
  try {
813
837
  const launched = await host.launchParent({ kind, params, ctx });
838
+ onLaunch?.(launched);
814
839
  return host.formatLaunch(launched);
815
840
  } catch (error) {
816
841
  if (error instanceof ForegroundSandboxBlockedError) return error.message;
@@ -818,25 +843,39 @@ async function durableLaunchText(
818
843
  }
819
844
  }
820
845
 
821
- function durableStatusText(pi: ExtensionAPI, id: string, ctx: ExtensionContext): string | undefined {
846
+ async function durableStatusText(pi: ExtensionAPI, id: string, ctx: ExtensionContext, params: Record<string, unknown>): Promise<string | undefined> {
822
847
  const host = getObservedWaitHost(pi);
823
- if (!host?.available || !host.isDurableTask(id)) return undefined;
848
+ if (!host || !host.isDurableTask(id)) return undefined;
824
849
  try {
825
- return host.formatStatus(host.statusForParent(ctx, id));
850
+ const view = await host.settledStatusForParent(ctx, id);
851
+ if (params.verbose === true || cursorKind(typeof params.cursor === "string" ? params.cursor : undefined) === "t") {
852
+ const origin = { cwd: ctx.cwd, sessionId: ctx.sessionManager.getSessionId() };
853
+ const task = host.readDurableTask(origin, id);
854
+ if (!task) return `Background task ${id} is outside the current session scope.`;
855
+ const meta = {
856
+ ...task, kind: task.kind === "watch" ? "command_watch" : "process", status: view.status,
857
+ argv: task.argv ? [...task.argv] : undefined,
858
+ logPath: task.logPaths.stdout, callbackOrigin: origin,
859
+ lastExitCode: view.exitCode, result: task.terminal ? { exitCode: view.exitCode, signal: view.signal } : undefined,
860
+ };
861
+ return formatDurableStatusMetadata(meta, statusOptions(params, origin));
862
+ }
863
+ return host.formatStatus(view);
826
864
  } catch (error) {
827
865
  return readableError(error);
828
866
  }
829
867
  }
830
868
 
831
- function durableLogText(
869
+ async function durableLogText(
832
870
  pi: ExtensionAPI,
833
871
  id: string,
834
872
  params: Record<string, unknown>,
835
873
  ctx: ExtensionContext,
836
- ): string | undefined {
874
+ ): Promise<string | undefined> {
837
875
  const host = getObservedWaitHost(pi);
838
- if (!host?.available || !host.isDurableTask(id)) return undefined;
876
+ if (!host || !host.isDurableTask(id)) return undefined;
839
877
  try {
878
+ await host.settledStatusForParent(ctx, id);
840
879
  const requested = typeof params.lines === "number" ? params.lines
841
880
  : typeof params.tail_lines === "number" ? params.tail_lines : 40;
842
881
  // `lines: 0` means the retained raw log on the legacy route; the durable
@@ -850,7 +889,7 @@ function durableLogText(
850
889
 
851
890
  async function durableStopText(pi: ExtensionAPI, id: string, ctx: ExtensionContext, requestId?: string): Promise<string | undefined> {
852
891
  const host = getObservedWaitHost(pi);
853
- if (!host?.available || !host.isDurableTask(id)) return undefined;
892
+ if (!host || !host.isDurableTask(id)) return undefined;
854
893
  try {
855
894
  const status = host.formatStatus(await host.stopForParent(ctx, id, requestId));
856
895
  return requestId ? `Cancellation request: ${requestId}\n${status}` : status;