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
@@ -1,19 +1,41 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { truncateToWidth as piTruncateToWidth, visibleWidth as piVisibleWidth } from "@earendil-works/pi-tui";
3
+ import { readHarnessSetting, updateHarnessSetting } from "./shared-harness-settings.ts";
3
4
  import type { Component } from "@earendil-works/pi-tui";
4
5
  import { createRenderScheduler, type RenderScheduler } from "./shared-render-scheduler.ts";
5
- import { setNavigatorPanel } from "./shared-navigator-panels.ts";
6
+ import { setNavigatorPanel, type NavigatorPanelLayout } from "./shared-navigator-panels.ts";
6
7
 
7
8
  export default function navigatorExtension(): void {
8
9
  // Internal shared package. Pi may scan its symlink in the extension directory
9
10
  // for sibling relative imports; loading it directly should be harmless.
10
11
  }
11
12
 
13
+ export type NavigatorView = "tree" | "flatten";
14
+ export function getNavigatorView(): NavigatorView { return state().view ?? "flatten"; }
15
+ export function loadNavigatorView(): void {
16
+ const value = readHarnessSetting("navigatorView");
17
+ state().view = value === "tree" ? "tree" : "flatten";
18
+ }
19
+ export function setNavigatorView(value: string): void {
20
+ if (value !== "tree" && value !== "flatten") throw new Error("View must be tree or flatten.");
21
+ updateHarnessSetting("navigatorView", () => value);
22
+ state().view = value;
23
+ refreshBackgroundWorkNavigator();
24
+ }
25
+
12
26
  export type BackgroundWorkStatusTone = "running" | "success" | "failed" | "warning" | "muted";
13
27
 
14
28
  export type BackgroundWorkRow = {
15
29
  providerId: string;
16
30
  id: string;
31
+ /** Stable worker conversation identity, independent of execution attempts. */
32
+ agentId?: string;
33
+ parentAgentId?: string;
34
+ readOnly?: boolean;
35
+ treeDepth?: number;
36
+ lastChild?: boolean;
37
+
38
+ ownerGroupLabel?: string;
17
39
  name?: string;
18
40
  model?: string;
19
41
  effort?: string;
@@ -64,14 +86,71 @@ export type BackgroundWorkProvider = {
64
86
  showSection?(rows: BackgroundWorkRow[], now: number): boolean;
65
87
  parentRow?(now: number): BackgroundWorkRow | null;
66
88
  listRows(now: number): BackgroundWorkRow[];
89
+ prepareDetail?(id: string, options?: {logTailLines?: number}): void;
67
90
  detail(id: string, now: number, options?: { logTailLines?: number }): BackgroundWorkDetail | null;
68
91
  armCloseLabel(row: BackgroundWorkRow): string;
69
92
  close(id: string): BackgroundWorkCloseOutcome;
70
93
  /** Return true when this detail handled the key. The navigator refreshes the sheet. */
71
94
  handleDetailInput?(id: string, data: string): boolean;
95
+ /** An explicit navigator interaction may attach a deferred work subscription. */
96
+ onOpen?(): void;
72
97
  onVisibleChanged?(notify: () => void): () => void;
73
98
  };
74
99
 
100
+ /** UI time is independent of worker time; repeated refreshes never renew it. */
101
+ export function createTerminalRowRetention(retentionMs = 30_000) {
102
+ const held = new Map<string, { row: BackgroundWorkRow; until: number }>();
103
+ const dismissed = new Set<string>();
104
+ return {
105
+ clear() { held.clear(); dismissed.clear(); },
106
+ dismiss(id: string) { held.delete(id); dismissed.add(id); },
107
+ merge(rows: BackgroundWorkRow[], now: number): BackgroundWorkRow[] {
108
+ const result: BackgroundWorkRow[] = [];
109
+ const present = new Set(rows.map(row => row.id));
110
+ for (const id of dismissed) if (!present.has(id)) dismissed.delete(id);
111
+ for (const row of rows) {
112
+ if (dismissed.has(row.id)) continue;
113
+ const terminal = ["completed", "succeeded", "failed", "cancelled", "killed", "lost", "timed_out"].includes(row.status);
114
+ if (!terminal) { held.delete(row.id); result.push(row); continue; }
115
+ let entry = held.get(row.id);
116
+ if (!entry) { entry = {row, until: now + retentionMs}; held.set(row.id, entry); }
117
+ entry.row = {...row, expiresAt: entry.until};
118
+ if (now < entry.until) result.push(entry.row);
119
+ }
120
+ for (const [id, entry] of held) {
121
+ if (present.has(id)) continue;
122
+ if (now < entry.until) result.push(entry.row);
123
+ else held.delete(id);
124
+ }
125
+ return result;
126
+ },
127
+ };
128
+ }
129
+
130
+ /** A frontend-only diagnostic, never an execution record or authority to retry. */
131
+ export async function observeNavigatorLaunch<T>(ctx: ExtensionContext, providerId: string, key: string, name: string, launch: () => Promise<T>): Promise<T> {
132
+ const scope = JSON.stringify([ctx.cwd, ctx.sessionManager?.getSessionId?.()]);
133
+ const report = (error: unknown) => {
134
+ const s = state();
135
+ if (!isNavigatorUiAvailable(s.uiCtx) || s.observationScope !== scope) return;
136
+ const id = `launch-error-${key}`;
137
+ const primary = error instanceof Error ? error.message : String(error);
138
+ const failures = s.launchFailures ??= new Map();
139
+ const identity = rowKey(providerId, id);
140
+ failures.set(identity, {providerId, id, name, status: "failed", statusTone: "failed", kind: "launch-error", elapsed: "", primary,
141
+ secondary: "Launch failed or was not confirmed; inspect before retrying.", sortStartedAt: Date.now()});
142
+ // Diagnostics are session-local and bounded, including expired tombstones.
143
+ if (failures.size > 128) failures.delete(failures.keys().next().value!);
144
+ refreshBackgroundWorkNavigator();
145
+ };
146
+ try {
147
+ const result = await launch();
148
+ const response = result as {isError?: boolean; content?: {type: string; text?: string}[]};
149
+ if (response?.isError) report(response.content?.filter(item => item.type === "text").map(item => item.text).join("\n") || "Launch request failed");
150
+ return result;
151
+ } catch (error) { report(error); throw error; }
152
+ }
153
+
75
154
  type HostDeps = {
76
155
  createDefaultEditor: (tui: unknown, theme: unknown, keybindings: unknown) => unknown;
77
156
  isOpenTrigger: (data: string) => boolean;
@@ -82,6 +161,10 @@ type HostDeps = {
82
161
 
83
162
  type NavigatorState = {
84
163
  providers: Map<string, BackgroundWorkProvider>;
164
+ view?: NavigatorView;
165
+ terminalRows?: Map<string, ReturnType<typeof createTerminalRowRetention>>;
166
+ launchFailures?: Map<string, BackgroundWorkRow>;
167
+ observationScope?: string;
85
168
  registrationTokens?: Map<string, symbol>;
86
169
  unsubscribers: Map<string, () => void>;
87
170
  uiCtx?: ExtensionContext;
@@ -201,6 +284,10 @@ export function applyCloseConfirmFooter(ui: { setStatus(key: string, value: stri
201
284
  export function ensureBackgroundWorkNavigator(ctx: ExtensionContext, deps: HostDeps, owner?: symbol): void {
202
285
  if (!isNavigatorUiAvailable(ctx)) return;
203
286
  const s = state();
287
+ if (s.view === undefined) { try { loadNavigatorView(); } catch { s.view = "flatten"; } }
288
+ const scope = JSON.stringify([ctx.cwd, ctx.sessionManager?.getSessionId?.()]);
289
+ if (s.observationScope !== scope) { s.terminalRows?.clear(); s.launchFailures?.clear(); }
290
+ s.observationScope = scope;
204
291
  s.uiCtx = ctx;
205
292
  s.uiOwner = owner;
206
293
  s.deps = {
@@ -238,6 +325,9 @@ export function disposeBackgroundWorkNavigator(ctx?: ExtensionContext, owner?: s
238
325
  stopMainListWidget();
239
326
  const activeCtx = ctx ?? s.uiCtx;
240
327
  s.uiCtx = undefined;
328
+ s.terminalRows?.clear();
329
+ s.launchFailures?.clear();
330
+ s.observationScope = undefined;
241
331
  s.uiOwner = undefined;
242
332
  if (activeCtx && isNavigatorUiAvailable(activeCtx)) {
243
333
  try { setNavigatorPanel(activeCtx, MAIN_LIST_WIDGET_KEY, undefined); } catch { /* ignore */ }
@@ -327,7 +417,7 @@ function refreshMainListWidget(): void {
327
417
  }
328
418
  if (!s.mainListWidgetInstalled) {
329
419
  try {
330
- setNavigatorPanel(ctx, MAIN_LIST_WIDGET_KEY, (tui: { requestRender?(): void }, theme: unknown) => createMainListWidget(tui, theme, deps), { placement: "aboveEditor" });
420
+ setNavigatorPanel(ctx, MAIN_LIST_WIDGET_KEY, (tui: { requestRender?(): void }, theme: unknown, layout) => createMainListWidget(tui, theme, deps, layout), { placement: "aboveEditor" });
331
421
  s.mainListWidgetInstalled = true;
332
422
  } catch { /* ignore */ }
333
423
  }
@@ -405,7 +495,7 @@ function createPointerNavigation(targetAt: (event: WidgetMouseEvent) => string |
405
495
  };
406
496
  }
407
497
 
408
- function createMainListWidget(tui: { requestRender?(): void }, theme: unknown, deps: HostDeps): MainListWidget {
498
+ function createMainListWidget(tui: { requestRender?(): void }, theme: unknown, deps: HostDeps, panelLayout: NavigatorPanelLayout = { availableRows: () => Infinity }): MainListWidget {
409
499
  const requestRender = () => tui.requestRender?.();
410
500
  state().mainListRequestRender = requestRender;
411
501
  // navigatorId per rendered line, so a pointer row resolves by structure, never by row text.
@@ -438,8 +528,23 @@ function createMainListWidget(tui: { requestRender?(): void }, theme: unknown, d
438
528
  if (hint) { layout.lines.push(deps.truncate(` ${hint}`, renderWidth(width))); layout.owners.push(undefined); }
439
529
  lineWidth = renderWidth(width);
440
530
  // The leading gap line belongs to the widget too, so its slot stays ownerless.
531
+ let rawLines = ["", ...layout.lines];
441
532
  lineOwners = [undefined, ...layout.owners];
442
- const lines = ["", ...layout.lines].map((line, index) =>
533
+ const budget = Math.max(0, Math.floor(panelLayout.availableRows()));
534
+ if (rawLines.length > budget) {
535
+ const selected = state().mainListFocused ? lineOwners.indexOf(state().mainListSelectedId) : -1;
536
+ const count = Math.max(0, budget - 1);
537
+ const start = selected >= 0 ? Math.max(0, Math.min(selected - Math.floor(count / 2), rawLines.length - count)) : 2;
538
+ rawLines = rawLines.slice(start, start + count);
539
+ lineOwners = lineOwners.slice(start, start + count);
540
+ const visible = new Set(lineOwners.filter(Boolean));
541
+ if (budget > 0) {
542
+ const hidden = rows.length - visible.size;
543
+ rawLines.push(deps.truncate(hidden ? ` +${hidden} tasks` : ` ${rows.length} tasks`, renderWidth(width)));
544
+ lineOwners.push(undefined);
545
+ }
546
+ }
547
+ const lines = rawLines.map((line, index) =>
443
548
  pointer.hovered && lineOwners[index] === pointer.hovered ? highlightPointerTarget(theme, line, lineWidth) : line);
444
549
  state().lastMainListLines = lines;
445
550
  return lines;
@@ -482,10 +587,14 @@ function listRows(now = Date.now()): InternalRow[] {
482
587
  for (const provider of providers()) {
483
588
  let providerRows: BackgroundWorkRow[] = [];
484
589
  try { providerRows = provider.listRows(now) ?? []; } catch { providerRows = []; }
590
+ providerRows = [...providerRows, ...[...(state().launchFailures?.values() ?? [])].filter(row => row.providerId === provider.id)];
591
+ const retention = state().terminalRows ??= new Map();
592
+ if (!retention.has(provider.id)) retention.set(provider.id, createTerminalRowRetention());
593
+ if (isNavigatorUiAvailable(state().uiCtx)) providerRows = retention.get(provider.id)!.merge(providerRows, now);
485
594
  const orderedProviderRows = [...providerRows].sort((a, b) => b.sortStartedAt - a.sortStartedAt || rowDisplayName(a).localeCompare(rowDisplayName(b)));
486
595
  let showSection = orderedProviderRows.length > 0 || provider.parentRow !== undefined;
487
596
  try { showSection = provider.showSection?.(orderedProviderRows, now) ?? showSection; } catch { showSection = false; }
488
- if (!showSection) continue;
597
+ if (!showSection && !(getNavigatorView() === "tree" && provider.parentRow)) continue;
489
598
  let parentRow: BackgroundWorkRow | null = null;
490
599
  try { parentRow = provider.parentRow?.(now) ?? null; } catch { parentRow = null; }
491
600
  if (parentRow) {
@@ -500,7 +609,48 @@ function listRows(now = Date.now()): InternalRow[] {
500
609
  rows.push({ ...row, navigatorId: rowKey(provider.id, row.id), providerLabel: provider.label });
501
610
  }
502
611
  }
503
- return rows;
612
+ const conversations = mergeAgentAttempts(rows);
613
+ return getNavigatorView() === "tree" ? treeRows(conversations) : conversations;
614
+ }
615
+
616
+ /** A resumed execution is still the same agent in either layout. */
617
+ export function mergeAgentAttempts<T extends BackgroundWorkRow>(rows: T[]): T[] {
618
+ const latest = new Map<string, T>();
619
+ for (const row of rows) {
620
+ if (row.providerId !== "subagents" || !row.agentId) continue;
621
+ const previous = latest.get(row.agentId);
622
+ if (!previous || row.sortStartedAt > previous.sortStartedAt
623
+ || (row.sortStartedAt === previous.sortStartedAt && row.id > previous.id)) latest.set(row.agentId, row);
624
+ }
625
+ return rows.filter(row => row.providerId !== "subagents" || !row.agentId || latest.get(row.agentId) === row);
626
+ }
627
+
628
+ /** Two levels only: agents are peers, tasks attach by captured conversation. */
629
+ export function treeRows<T extends BackgroundWorkRow>(rows: T[]): T[] {
630
+ const agents = new Map<string, T>();
631
+ for (const row of rows.filter(row => row.providerId === "subagents")) {
632
+ const key = row.agentId ?? row.id;
633
+ const prior = agents.get(key);
634
+ if (!prior || row.sortStartedAt > prior.sortStartedAt) agents.set(key, row);
635
+ }
636
+ const tasks = rows.filter(row => row.providerId !== "subagents");
637
+ const ordered = [...agents.entries()].sort(([a], [b]) => a === "main" ? -1 : b === "main" ? 1 : 0);
638
+ const result: T[] = [], attached = new Set<T>();
639
+ for (const [key, agent] of ordered) {
640
+ const children = tasks.filter(row => (row.parentAgentId ?? "main") === key);
641
+ result.push({...agent, treeDepth: 0});
642
+ children.forEach((row, i) => { result.push({...row, treeDepth: 1, lastChild: i === children.length - 1}); attached.add(row); });
643
+ }
644
+ // Never hide live work when its owner's observation has not arrived yet.
645
+ const missing = new Map<string, T[]>();
646
+ for (const row of tasks) if (!attached.has(row)) {
647
+ const key = row.parentAgentId ?? "main";
648
+ missing.set(key, [...(missing.get(key) ?? []), row]);
649
+ }
650
+ for (const [key, children] of missing) children.forEach((row, i) => result.push({...row,
651
+ treeDepth: 1, lastChild: i === children.length - 1,
652
+ ownerGroupLabel: i === 0 ? (key === "main" ? "Main" : `Agent ${key} · not running`) : undefined}));
653
+ return result;
504
654
  }
505
655
 
506
656
  function rowDisplayName(row: Pick<BackgroundWorkRow, "name" | "id">): string {
@@ -581,6 +731,15 @@ function buildMainListLayout(
581
731
  lines.push(line);
582
732
  owners.push(owner);
583
733
  };
734
+ if (getNavigatorView() === "tree") {
735
+ push(providerGroupLabel("work", fg));
736
+ for (const row of rows) {
737
+ if (row.ownerGroupLabel) push(` ${dim(row.ownerGroupLabel, fg)}`);
738
+ push(formatMainListRow(row, options.focused === true && row.navigatorId === options.selectedId, fg, width), row.navigatorId);
739
+ }
740
+ push(""); push(shortcutsLine(options.focused === true, fg));
741
+ return {lines: lines.map(line => safeTruncate(line, width, truncate)), owners};
742
+ }
584
743
  const grouped = new Map<string, InternalRow[]>();
585
744
  for (const row of rows) {
586
745
  const existing = grouped.get(row.providerLabel) ?? [];
@@ -605,8 +764,9 @@ function buildMainListLayout(
605
764
  }
606
765
 
607
766
  function shortcutsLine(focused: boolean, fg: (color: string, value: string) => string): string {
767
+ const selected = state().mainListRows?.find(row => row.navigatorId === state().mainListSelectedId);
608
768
  const keys = focused
609
- ? "↑↓ switch · Enter detail · x stop · Esc unfocus"
769
+ ? `↑↓ switch · Enter detail${selected?.readOnly || selected?.parentRow ? "" : " · x stop"} · Esc unfocus`
610
770
  : "← work navigator";
611
771
  return dim(keys, fg);
612
772
  }
@@ -617,7 +777,7 @@ function providerGroupLabel(label: string, fg: (color: string, value: string) =>
617
777
  }
618
778
 
619
779
  function formatMainListRow(row: InternalRow, selected: boolean, fg: (color: string, value: string) => string, width: number): string {
620
- const prefix = selected ? fg("accent", "› ") : " ";
780
+ const prefix = (selected ? fg("accent", "› ") : " ") + (row.treeDepth === 1 ? dim(` ${row.lastChild ? "└─" : "├─"} `, fg) : "");
621
781
  const name = row.name || row.id;
622
782
  const indicator = statusIndicator(row);
623
783
  const status = fg(indicator.color, indicator.glyph);
@@ -647,17 +807,21 @@ function statusGlyph(row: InternalRow): string {
647
807
  function statusIndicator(row: InternalRow, now = Date.now()): { glyph: string; color: string } {
648
808
  void now;
649
809
  if (row.statusTone !== "running") return { glyph: statusGlyph(row), color: toneColor(row.statusTone, row.status) };
650
- return { glyph: RUNNING_DOT_GLYPH, color: "accent" };
810
+ const glyph = row.treeDepth === 1 && row.providerId === "background-tasks" ? ">_" : RUNNING_DOT_GLYPH;
811
+ return { glyph, color: "accent" };
651
812
  }
652
813
 
653
814
  function mainListSignature(rows: InternalRow[], options: { selectedId?: string; focused?: boolean; closeHint?: string | null } = {}): string {
654
815
  return JSON.stringify({
816
+ view: getNavigatorView(),
655
817
  focused: options.focused === true,
656
818
  closeHint: options.closeHint ?? null,
657
819
  selectedId: options.focused === true ? options.selectedId ?? null : null,
658
820
  rows: rows.map((row) => ({
659
821
  navigatorId: row.navigatorId,
660
822
  providerLabel: row.providerLabel,
823
+ parentAgentId: row.parentAgentId,
824
+ agentId: row.agentId,
661
825
  parentRow: row.parentRow === true,
662
826
  providerId: row.providerId,
663
827
  id: row.id,
@@ -683,6 +847,9 @@ function stableFacts(facts: string[] | undefined): string[] {
683
847
  }
684
848
 
685
849
  function rowSummary(row: InternalRow): string {
850
+ if (getNavigatorView() === "tree" && row.providerId === "background-tasks") {
851
+ return [singleLine(row.status).replaceAll("_", " "), ...(row.facts ?? []).map(singleLine)].join(" · ");
852
+ }
686
853
  if (row.providerId === "subagents") {
687
854
  const attention = row.facts?.map(singleLine).filter(Boolean);
688
855
  if (attention?.length) return `${singleLine(row.status)} · ${attention.join(" · ")}`;
@@ -728,22 +895,40 @@ function singleLine(value: unknown): string {
728
895
  return String(value ?? "").replace(/[\r\n\t]+/g, " ").replace(/ {2,}/g, " ").trim();
729
896
  }
730
897
 
898
+ function prepareDetail(navigatorId: string, options?: {logTailLines?: number}): void {
899
+ const {providerId,id}=splitRowKey(navigatorId);
900
+ try {state().providers.get(providerId)?.prepareDetail?.(id,options);}catch {/* observation failure retains cached detail */}
901
+ }
902
+
731
903
  function detailFor(navigatorId: string, now = Date.now(), options?: { logTailLines?: number }): BackgroundWorkDetail | null {
732
904
  const { providerId, id } = splitRowKey(navigatorId);
905
+ const failed = state().launchFailures?.get(navigatorId);
906
+ if (failed) return {providerId, id, title: failed.name ?? "Launch failed", status: "failed", statusTone: "failed", metadata: [], evidence: {label: "Launch error", text: failed.primary}};
733
907
  const provider = state().providers.get(providerId);
734
908
  if (!provider) return null;
735
909
  try { return provider.detail(id, now, options); } catch { return null; }
736
910
  }
737
911
 
738
912
  function closeFor(row: InternalRow): BackgroundWorkCloseOutcome {
739
- if (row.parentRow) return { action: "not-closable", providerId: row.providerId, id: row.id };
913
+ if (row.parentRow || row.readOnly) return { action: "not-closable", providerId: row.providerId, id: row.id };
740
914
  const provider = state().providers.get(row.providerId);
915
+ if (state().launchFailures?.delete(row.navigatorId)) {
916
+ state().terminalRows?.get(row.providerId)?.dismiss(row.id);
917
+ return {action: "dismissed", providerId: row.providerId, id: row.id};
918
+ }
741
919
  if (!provider) return { action: "missing", providerId: row.providerId, id: row.id };
742
- try { return provider.close(row.id); } catch { return { action: "missing", providerId: row.providerId, id: row.id }; }
920
+ try {
921
+ const outcome = provider.close(row.id);
922
+ if (["dismissed", "stopped-and-dismissed"].includes(outcome.action)
923
+ || outcome.action === "requested" && ["completed", "succeeded", "failed", "cancelled", "killed", "lost", "timed_out"].includes(row.status)) {
924
+ state().terminalRows?.get(row.providerId)?.dismiss(row.id);
925
+ }
926
+ return outcome;
927
+ } catch { return { action: "missing", providerId: row.providerId, id: row.id }; }
743
928
  }
744
929
 
745
930
  function closeHintFor(row: InternalRow | undefined): string | null {
746
- if (!row || row.parentRow) return null;
931
+ if (!row || row.parentRow || row.readOnly) return null;
747
932
  const provider = state().providers.get(row.providerId);
748
933
  if (!provider) return null;
749
934
  try { return `${provider.armCloseLabel(row)} ${row.name || row.id}`; } catch { return null; }
@@ -801,6 +986,9 @@ function wrapEditor(inner: any, deps: HostDeps): unknown {
801
986
 
802
987
  function handleMainListInput(data: string, deps: HostDeps): boolean {
803
988
  const s = state();
989
+ if (!s.mainListFocused && deps.isOpenTrigger(data)) {
990
+ for (const provider of s.providers.values()) provider.onOpen?.();
991
+ }
804
992
  const rows = listRows();
805
993
  if (rows.length === 0) {
806
994
  // Every row is gone, but an overlay that lost focus may still be mounted: Esc still closes it.
@@ -870,7 +1058,7 @@ function dismissOverlay(): void {
870
1058
 
871
1059
  function handleMainListCloseKey(): void {
872
1060
  const row = selectedMainListRow();
873
- if (!row || row.parentRow) return;
1061
+ if (!row || row.parentRow || row.readOnly) return;
874
1062
  const s = state();
875
1063
  const now = Date.now();
876
1064
  const arm = s.mainListCloseArm;
@@ -911,6 +1099,7 @@ function openNavigator(): void {
911
1099
  const ctx = s.uiCtx;
912
1100
  const deps = s.deps;
913
1101
  if (!ctx || !deps || !isNavigatorUiAvailable(ctx)) return;
1102
+ for (const provider of s.providers.values()) provider.onOpen?.();
914
1103
  const rows = listRows();
915
1104
  if (rows.length === 0) return;
916
1105
  const selectedId = selectedMainListRow()?.navigatorId ?? rows[0]!.navigatorId;
@@ -989,10 +1178,12 @@ function createOverlayComponent(
989
1178
  const overlayState: OverlayState = { rows: initialRows, selected: 0 };
990
1179
  let logTailRows: number = DEFAULT_LOG_TAIL_ROWS;
991
1180
  const expandedSections = new Set<string>();
1181
+ const initializedSections = new Set<string>();
992
1182
  let detailId: string = initialDetailId;
993
1183
  const initialRow = initialRows.find((row) => row.navigatorId === detailId);
1184
+ prepareDetail(detailId,{logTailLines:logTailRows});
994
1185
  let detail: BackgroundWorkDetail | null = detailFor(detailId, Date.now(), { logTailLines: logTailRows }) ?? (initialRow ? fallbackDetail(initialRow) : null);
995
- applyDefaultExpandedSections(detail, expandedSections);
1186
+ applyDefaultExpandedSections(detail, expandedSections, initializedSections);
996
1187
  {
997
1188
  const idx = overlayState.rows.findIndex((row) => row.navigatorId === detailId);
998
1189
  if (idx >= 0) overlayState.selected = idx;
@@ -1028,6 +1219,7 @@ function createOverlayComponent(
1028
1219
  const detailScheduler = createRenderScheduler(() => {
1029
1220
  if (closed) return;
1030
1221
  detail = detailFor(detailId, Date.now(), { logTailLines: logTailRows }) ?? detail;
1222
+ applyDefaultExpandedSections(detail, expandedSections, initializedSections);
1031
1223
  requestRender();
1032
1224
  startDetailTimer();
1033
1225
  });
@@ -1079,8 +1271,10 @@ function createOverlayComponent(
1079
1271
  clearCloseArm();
1080
1272
  detailId = row.navigatorId;
1081
1273
  expandedSections.clear();
1274
+ initializedSections.clear();
1275
+ prepareDetail(detailId,{logTailLines:logTailRows});
1082
1276
  detail = detailFor(row.navigatorId, Date.now(), { logTailLines: logTailRows }) ?? fallbackDetail(row);
1083
- applyDefaultExpandedSections(detail, expandedSections);
1277
+ applyDefaultExpandedSections(detail, expandedSections, initializedSections);
1084
1278
  startDetailTimer();
1085
1279
  requestRender();
1086
1280
  }
@@ -1102,7 +1296,7 @@ function createOverlayComponent(
1102
1296
 
1103
1297
  function handleCloseKey(): void {
1104
1298
  const row = selectedRow();
1105
- if (!row || row.parentRow) return;
1299
+ if (!row || row.parentRow || row.readOnly) return;
1106
1300
  const now = Date.now();
1107
1301
  if (closeArm?.id === row.navigatorId && now >= closeArm.armedAt && now < closeArm.armedAt + CLOSE_ARM_MS) {
1108
1302
  clearCloseArm();
@@ -1251,12 +1445,15 @@ function createOverlayComponent(
1251
1445
  const key = data === "m" || data === "M" ? "m" : "ctrl+s";
1252
1446
  if (!row || !provider?.handleDetailInput?.(row.id, key)) return;
1253
1447
  detail = detailFor(detailId, Date.now(), { logTailLines: logTailRows }) ?? detail;
1448
+ applyDefaultExpandedSections(detail, expandedSections, initializedSections);
1254
1449
  refreshMainListWidget();
1255
1450
  requestRender();
1256
1451
  }
1257
1452
  else if (data === "l" || data === "L") {
1258
1453
  logTailRows = cycleLogTailRows(logTailRows);
1454
+ prepareDetail(detailId,{logTailLines:logTailRows});
1259
1455
  if (detailId) detail = detailFor(detailId, Date.now(), { logTailLines: logTailRows }) ?? detail;
1456
+ applyDefaultExpandedSections(detail, expandedSections, initializedSections);
1260
1457
  requestRender();
1261
1458
  }
1262
1459
  else if (deps.matchKey(data, "escape")) {
@@ -1266,9 +1463,9 @@ function createOverlayComponent(
1266
1463
  /** Observation arrival updates this row without resetting selection or folded sections. */
1267
1464
  refreshDetail() {
1268
1465
  if (closed) return;
1269
- const wasLoading = detail?.status === "rebuilding";
1466
+ prepareDetail(detailId,{logTailLines:logTailRows});
1270
1467
  detail = detailFor(detailId, Date.now(), { logTailLines: logTailRows }) ?? detail;
1271
- if (wasLoading) applyDefaultExpandedSections(detail, expandedSections);
1468
+ applyDefaultExpandedSections(detail, expandedSections, initializedSections);
1272
1469
  startDetailTimer();
1273
1470
  requestRender();
1274
1471
  },
@@ -1502,8 +1699,12 @@ function firstToggleableSectionId(detail: BackgroundWorkDetail | null | undefine
1502
1699
  return detail && isFoldableEvidence(detail) ? EVIDENCE_SECTION_ID : undefined;
1503
1700
  }
1504
1701
 
1505
- function applyDefaultExpandedSections(detail: BackgroundWorkDetail | null, expandedSections: Set<string>): void {
1702
+ function applyDefaultExpandedSections(detail: BackgroundWorkDetail | null, expandedSections: Set<string>, initializedSections: Set<string>): void {
1506
1703
  for (const section of detail?.foldedSections ?? []) {
1704
+ if (initializedSections.has(section.id)) continue;
1705
+ // Details can arrive after a running row's fallback. Initialize each section
1706
+ // on first arrival, then preserve the user's choice across observations.
1707
+ initializedSections.add(section.id);
1507
1708
  if (section.expandedByDefault) expandedSections.add(section.id);
1508
1709
  }
1509
1710
  }
@@ -1,6 +1,16 @@
1
1
  // Generated from packages/operation-coordinator/assignment-observation.mjs. Do not edit directly.
2
2
  import { createRequire } from "node:module";
3
- import { createHash } from "node:crypto";
3
+ import { AssignmentInbox } from "./assignment-inbox.mjs";
4
+ import { pathToFileURL } from "node:url";
5
+
6
+ // Only first-party source SQL passes this facade; quoted values stay untouched.
7
+ const sourceTables = new Set(["schema_meta", "sqlite_master", "sqlite_schema", "assignment_change_source", "assignment_changes",
8
+ "waits", "wait_dependencies", "resume_claims", "operations", "coordinator_state", "assignment_outcomes",
9
+ "subagent_launch_intents", "background_input_versions", "background_parent_callbacks", "assignments", "assignment_bindings", "assignment_attempts"]);
10
+ function sourceSQL(sql) {
11
+ if (/^PRAGMA\s+data_version\s*$/i.test(sql)) return "PRAGMA coordinator_source.data_version";
12
+ return sql.replace(/'(?:''|[^'])*'|\b[A-Za-z_][A-Za-z_0-9]*\b/g, token => sourceTables.has(token) ? `coordinator_source.${token}` : token);
13
+ }
4
14
 
5
15
  /** Read-only, bounded projection input. Never creates/migrates a database. */
6
16
  export function readAssignmentWaits(path, owner, connection) {
@@ -44,42 +54,66 @@ export function readAssignmentWaits(path, owner, connection) {
44
54
  }
45
55
 
46
56
  /** A root read model owns this connection; ordinary observers remain one-shot. */
47
- export function createAssignmentReader(path) {
57
+ export function createAssignmentReader(path, inboxPath = ":memory:", derivedConnection, options = {}) {
58
+ const inbox = new AssignmentInbox(inboxPath, derivedConnection);
48
59
  let db;
49
60
  let identity;
50
61
  let snapshot = false;
62
+ const composed = options.composed === true;
63
+ const owner = derivedConnection;
64
+ const dropSource = () => {
65
+ if (composed) { if (db) owner.exec("DETACH DATABASE coordinator_source"); }
66
+ else db?.close();
67
+ db = undefined; statements.clear();
68
+ };
51
69
  const statements = new Map();
52
- return {
70
+ const reader = {
53
71
  revision() {
54
72
  const { statSync } = createRequire(import.meta.url)("node:fs");
55
73
  const stat = statSync(path, { bigint: true });
56
74
  const next = `${stat.dev}:${stat.ino}`;
57
75
  if (identity !== next) {
58
76
  if (snapshot) throw new Error("Coordinator identity changed during observation");
59
- db?.close();
60
- db = undefined;
61
- statements.clear();
77
+ dropSource();
62
78
  identity = next;
63
79
  }
64
80
  const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
65
- db ??= new DatabaseSync(path, { readOnly: true });
81
+ if (!db) {
82
+ if (composed) {
83
+ const uri = pathToFileURL(path); uri.searchParams.set("mode", "ro");
84
+ owner.prepare("ATTACH DATABASE ? AS coordinator_source").run(uri.href);
85
+ db = { prepare: sql => owner.prepare(sourceSQL(sql)), get observationActive() { return snapshot; }, beginSnapshot: () => reader.beginSnapshot() };
86
+ } else db = new DatabaseSync(path, { readOnly: true });
87
+ }
66
88
  return `${identity}:${db.prepare("PRAGMA data_version").get().data_version}`;
67
89
  },
90
+ connection(refresh = true) { if (refresh) this.revision(); return db; },
91
+ changes() { this.revision(); return inbox.receive(db, identity); },
92
+ acknowledgeChanges(batch, complete) { inbox.acknowledge(batch, complete); },
93
+ get changeMetrics() { return inbox.metrics; },
94
+ get snapshotActive() { return snapshot; },
95
+
68
96
  beginSnapshot() {
69
97
  this.revision();
70
98
  if (snapshot) throw new Error("Coordinator snapshot already open");
71
- db.exec("BEGIN");
99
+ const transaction = composed ? owner : db;
100
+ transaction.exec("BEGIN");
72
101
  snapshot = true;
73
102
  const release = () => {
74
103
  if (!snapshot) return;
75
- try { db.exec("ROLLBACK"); } finally { snapshot = false; }
104
+ try { transaction.exec("ROLLBACK"); } finally { snapshot = false; }
76
105
  };
77
106
  try {
78
107
  // Pin the WAL read view before recording its revision; other writers keep advancing.
79
108
  db.prepare("SELECT count(*) FROM sqlite_schema").get();
80
- return { revision: this.revision(), release };
109
+ return { revision: this.revision(), release, commit: () => {
110
+ if (!snapshot) return;
111
+ transaction.exec("COMMIT");
112
+ snapshot = false;
113
+ } };
81
114
  } catch (error) { release(); throw error; }
82
115
  },
116
+
83
117
  read(owner) {
84
118
  try {
85
119
  this.revision();
@@ -91,30 +125,34 @@ export function createAssignmentReader(path) {
91
125
  return { verified: false, waits: [], reason: "Coordinator state is unverified; compatible supervision is unavailable." };
92
126
  }
93
127
  },
94
- conversationRevisions() {
95
- try {
96
- this.revision();
97
- if (!["1", "2", "3", "4"].includes(db.prepare("SELECT value FROM schema_meta WHERE key = 'schema_version'").get()?.value)) return undefined;
98
- const hashes = new Map();
99
- const add = (sessionId, workspace, value) => {
100
- const key = JSON.stringify([sessionId, workspace]);
101
- if (!hashes.has(key)) hashes.set(key, createHash("sha256"));
102
- hashes.get(key).update(JSON.stringify(value));
103
- };
104
- // One source pass per changed database revision, instead of one
105
- // projection/query/log parse for every historical attempt.
106
- for (const row of db.prepare(`SELECT w.*, (SELECT json_group_array(attempt_id)
107
- FROM resume_claims c WHERE c.wait_id = w.wait_id AND c.generation = w.generation) AS claimed_attempts
108
- FROM waits w WHERE owner_kind = 'worker-conversation' ORDER BY wait_id, generation`).all()) {
109
- add(row.owner_session_id, row.owner_workspace, row);
110
- }
111
- for (const row of db.prepare("SELECT record_json FROM assignment_outcomes ORDER BY assignment_id").all()) {
112
- const record = JSON.parse(row.record_json);
113
- add(record.owner.sessionId, record.owner.workspace, record);
128
+ upgradeObligations() {
129
+ try { this.revision(); } catch (error) {
130
+ if (error.code === "ENOENT") return [];
131
+ throw error;
132
+ }
133
+ const version = db.prepare("SELECT value FROM schema_meta WHERE key='schema_version'").get()?.value;
134
+ if (!["1", "2", "3", "4"].includes(version)) throw new Error("Unsupported coordinator schema during upgrade");
135
+ const obligations = db.prepare("SELECT operation_id, task_id, observer_kind FROM operations WHERE phase='running' AND terminal_revision=0").all()
136
+ .map(row => ({ kind: "unsettled-operation", id: row.task_id, operationId: row.operation_id, observer: row.observer_kind }));
137
+ const reasons = db.prepare("SELECT claim_id AS id, state FROM resume_claims WHERE state IN ('claimed', 'published')").all()
138
+ .map(row => ({ kind: "resume-claim", id: row.id, state: row.state }));
139
+ for (const row of db.prepare("SELECT wait_id, generation, phase FROM waits WHERE owner_kind='worker-conversation' AND phase NOT IN ('consumed', 'cancelled') AND dispatch_disarmed=0").all()) {
140
+ reasons.push({ kind: "worker-wait", id: row.wait_id, generation: row.generation, phase: row.phase });
141
+ }
142
+ if (db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='subagent_launch_intents'").get()) {
143
+ for (const row of db.prepare("SELECT owner, request_key, attempts FROM subagent_launch_intents WHERE state='accepted'").all()) {
144
+ reasons.push({ kind: "launch-intent", id: row.request_key, owner: row.owner, attempts: JSON.parse(row.attempts).map(attempt => attempt.id) });
114
145
  }
115
- return new Map([...hashes].map(([key, hash]) => [key, hash.digest("hex")]));
116
- } catch { return undefined; }
146
+ }
147
+ for (const row of db.prepare("SELECT value FROM coordinator_state WHERE key LIKE 'background-request-v1:%'").all()) {
148
+ const request = JSON.parse(row.value);
149
+ if (request.state !== 'returned') reasons.push({kind:'background-request', id:request.key, owner:request.owner});
150
+ }
151
+ return [...obligations, ...reasons];
117
152
  },
118
- close() { if (snapshot) { db.exec("ROLLBACK"); snapshot = false; } db?.close(); db = undefined; statements.clear(); identity = undefined; },
153
+
154
+ close() { if (snapshot) { (composed ? owner : db).exec("ROLLBACK"); snapshot = false; } dropSource(); identity = undefined; inbox.close(); },
155
+
119
156
  };
157
+ return reader;
120
158
  }
@@ -118,3 +118,5 @@ export { StoreError, isStoreError } from "./src/errors.ts";
118
118
  export type { StoreErrorCode } from "./src/errors.ts";
119
119
  export { openStore, ownerDiff } from "./src/store.ts";
120
120
  export type { Store } from "./src/store.ts";
121
+
122
+ export type { ParentCallbackScope, ParentCallbackPage, RecentBackgroundTerminalPage } from './src/background-parent-callbacks.ts';