pi-better-server 0.6.0 → 0.7.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 (120) hide show
  1. package/package.json +4 -3
  2. package/scripts/measure-full-runtime/frontend.ts +10 -2
  3. package/scripts/measure-full-runtime.mjs +2 -0
  4. package/src/runtime/background-tools.ts +54 -8
  5. package/src/runtime/background.ts +16 -4
  6. package/src/runtime/domain/background/process.mjs +49 -11
  7. package/src/runtime/domain/background/supervisor/store.mjs +3 -3
  8. package/src/runtime/domain/background/supervisor/supervisor.mjs +9 -3
  9. package/src/runtime/domain/background-service/index.domain.mjs +19 -0
  10. package/src/runtime/domain/background-service/index.ts +19 -0
  11. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +87 -5
  12. package/src/runtime/domain/background-service/managed-frontend.ts +76 -5
  13. package/src/runtime/domain/background-service/navigator-provider.domain.mjs +5 -0
  14. package/src/runtime/domain/background-service/navigator-provider.ts +4 -0
  15. package/src/runtime/domain/background-service/observed-waits.domain.mjs +203 -31
  16. package/src/runtime/domain/background-service/observed-waits.ts +168 -24
  17. package/src/runtime/domain/background-service/process.domain.mjs +49 -11
  18. package/src/runtime/domain/background-service/process.ts +45 -11
  19. package/src/runtime/domain/background-service/review-settings.domain.mjs +16 -0
  20. package/src/runtime/domain/background-service/review-settings.ts +18 -0
  21. package/src/runtime/domain/background-service/runtime.domain.mjs +8 -70
  22. package/src/runtime/domain/background-service/runtime.ts +8 -73
  23. package/src/runtime/domain/background-service/shared-navigator.domain.mjs +55 -28
  24. package/src/runtime/domain/background-service/shared-navigator.ts +47 -26
  25. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  26. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.ts +9 -0
  27. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +5 -1
  28. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +6 -0
  29. package/src/runtime/domain/background-service/stall.domain.mjs +5 -3
  30. package/src/runtime/domain/background-service/stall.ts +7 -4
  31. package/src/runtime/domain/background-service/supervised-progress.domain.mjs +42 -0
  32. package/src/runtime/domain/background-service/supervised-progress.ts +43 -0
  33. package/src/runtime/domain/background-service/supervisor/README.md +1 -4
  34. package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +1 -0
  35. package/src/runtime/domain/background-service/supervisor/generated/process.mjs +49 -11
  36. package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +47 -4
  37. package/src/runtime/domain/background-service/supervisor/generated/store.mjs +3 -3
  38. package/src/runtime/domain/background-service/supervisor/generated/watch-fingerprint.mjs +69 -0
  39. package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +47 -4
  40. package/src/runtime/domain/background-service/supervisor/runner.ts +38 -3
  41. package/src/runtime/domain/background-service/supervisor/store.domain.mjs +3 -3
  42. package/src/runtime/domain/background-service/supervisor/store.ts +3 -3
  43. package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +9 -3
  44. package/src/runtime/domain/background-service/supervisor/supervisor.ts +6 -3
  45. package/src/runtime/domain/background-service/tools.domain.mjs +22 -16
  46. package/src/runtime/domain/background-service/tools.ts +26 -16
  47. package/src/runtime/domain/background-service/types.ts +4 -2
  48. package/src/runtime/domain/background-service/watch-fingerprint.domain.mjs +67 -0
  49. package/src/runtime/domain/background-service/watch-fingerprint.ts +70 -0
  50. package/src/runtime/domain/coordinator/src/outbox.mjs +7 -0
  51. package/src/runtime/domain/coordinator/src/store.mjs +5 -1
  52. package/src/runtime/domain/log-paths.mjs +8 -1
  53. package/src/runtime/domain/parse.mjs +9 -5
  54. package/src/runtime/domain/sandbox-policy/README.md +3 -3
  55. package/src/runtime/domain/sandbox-policy/package.json +1 -1
  56. package/src/runtime/domain/session-store.mjs +7 -0
  57. package/src/runtime/domain/subagents/README.md +12 -10
  58. package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +2 -5
  59. package/src/runtime/domain/subagents/assignment-outcomes.ts +2 -5
  60. package/src/runtime/domain/subagents/assignment-report.domain.mjs +22 -0
  61. package/src/runtime/domain/subagents/assignment-report.ts +20 -0
  62. package/src/runtime/domain/subagents/batch.mjs +13 -5
  63. package/src/runtime/domain/subagents/cleanup.domain.mjs +11 -2
  64. package/src/runtime/domain/subagents/cleanup.ts +10 -2
  65. package/src/runtime/domain/subagents/config.domain.mjs +5 -0
  66. package/src/runtime/domain/subagents/config.ts +7 -1
  67. package/src/runtime/domain/subagents/continuation.domain.mjs +4 -2
  68. package/src/runtime/domain/subagents/continuation.ts +4 -2
  69. package/src/runtime/domain/subagents/failures.domain.mjs +11 -2
  70. package/src/runtime/domain/subagents/failures.ts +10 -2
  71. package/src/runtime/domain/subagents/finalization.domain.mjs +5 -2
  72. package/src/runtime/domain/subagents/finalization.ts +7 -2
  73. package/src/runtime/domain/subagents/index.domain.mjs +163 -61
  74. package/src/runtime/domain/subagents/index.ts +163 -60
  75. package/src/runtime/domain/subagents/isolated-workspace.domain.mjs +515 -0
  76. package/src/runtime/domain/subagents/isolated-workspace.ts +557 -0
  77. package/src/runtime/domain/subagents/list.mjs +2 -2
  78. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +22 -5
  79. package/src/runtime/domain/subagents/managed-launch-client.ts +23 -6
  80. package/src/runtime/domain/subagents/output-payload.domain.mjs +24 -9
  81. package/src/runtime/domain/subagents/output-payload.ts +26 -12
  82. package/src/runtime/domain/subagents/package.json +4 -2
  83. package/src/runtime/domain/subagents/parse.domain.mjs +9 -5
  84. package/src/runtime/domain/subagents/parse.ts +10 -5
  85. package/src/runtime/domain/subagents/registry.domain.mjs +24 -18
  86. package/src/runtime/domain/subagents/registry.ts +23 -5
  87. package/src/runtime/domain/subagents/retained-result.domain.mjs +56 -0
  88. package/src/runtime/domain/subagents/retained-result.ts +65 -0
  89. package/src/runtime/domain/subagents/session-selection.domain.mjs +3 -1
  90. package/src/runtime/domain/subagents/session-selection.ts +2 -1
  91. package/src/runtime/domain/subagents/session-store.domain.mjs +7 -0
  92. package/src/runtime/domain/subagents/session-store.ts +9 -0
  93. package/src/runtime/domain/subagents/settings-page.domain.mjs +151 -107
  94. package/src/runtime/domain/subagents/settings-page.ts +147 -108
  95. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +23 -7
  96. package/src/runtime/domain/subagents/shared-catalog.ts +23 -7
  97. package/src/runtime/domain/subagents/shared-navigator.domain.mjs +55 -28
  98. package/src/runtime/domain/subagents/shared-navigator.ts +47 -26
  99. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  100. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.ts +9 -0
  101. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +5 -1
  102. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +6 -0
  103. package/src/runtime/domain/subagents/task-guard.domain.mjs +14 -1
  104. package/src/runtime/domain/subagents/task-guard.ts +13 -1
  105. package/src/runtime/domain/subagents/task-policy.domain.mjs +2 -1
  106. package/src/runtime/domain/subagents/task-policy.ts +5 -1
  107. package/src/runtime/domain/subagents/tools.domain.mjs +4 -8
  108. package/src/runtime/domain/subagents/tools.ts +4 -7
  109. package/src/runtime/domain/subagents/work-observation.domain.mjs +25 -1
  110. package/src/runtime/domain/subagents/work-observation.ts +20 -1
  111. package/src/runtime/domain/subagents/workspace-files.domain.mjs +103 -0
  112. package/src/runtime/domain/subagents/workspace-files.ts +114 -0
  113. package/src/runtime/domain/subagents/workspace-scope.domain.d.mts +38 -0
  114. package/src/runtime/domain/subagents/workspace-scope.domain.mjs +5 -0
  115. package/src/runtime/domain/subagents/workspace-scope.ts +6 -0
  116. package/src/runtime/domain/subagents/worktree-feedback.domain.mjs +55 -0
  117. package/src/runtime/domain/subagents/worktree-feedback.ts +77 -0
  118. package/src/runtime/read-model.ts +4 -2
  119. package/src/runtime/root.ts +5 -2
  120. package/src/version.ts +1 -1
@@ -369,7 +369,7 @@ const BACK_TO_MAIN = "← main (Esc)";
369
369
  const BACK_TARGET = "back-to-main";
370
370
  function highlightPointerTarget(theme, line, width) {
371
371
  const colors = theme;
372
- return colors?.bg?.("selectedBg", line + " ".repeat(Math.max(0, width - visibleWidth(line))))
372
+ return colors?.bg?.("selectedBg", line + " ".repeat(Math.max(0, width - piVisibleWidth(line))))
373
373
  ?? themeFgFromTheme(theme)("accent", line);
374
374
  }
375
375
  function createPointerNavigation(targetAt, activate) {
@@ -698,16 +698,16 @@ function formatMainListRow(row, selected, fg, width) {
698
698
  const status = fg(indicator.color, indicator.glyph);
699
699
  const elapsed = singleLine(row.elapsed || "-");
700
700
  const available = Math.max(24, width || MAIN_LIST_FALLBACK_WIDTH);
701
- const elapsedWidth = Math.min(Math.max(visibleWidth(elapsed), 4), 12);
701
+ const elapsedWidth = Math.min(Math.max(piVisibleWidth(elapsed), 4), 12);
702
702
  const statusWidth = 2;
703
- const leftPrefixWidth = visibleWidth(prefix) + statusWidth + 1;
703
+ const leftPrefixWidth = piVisibleWidth(prefix) + statusWidth + 1;
704
704
  const maxNameWidth = Math.max(8, Math.floor(available * 0.36));
705
705
  const nameWidth = Math.max(8, Math.min(44, maxNameWidth, available - leftPrefixWidth - elapsedWidth - 10));
706
706
  const rightWidth = Math.max(8, available - leftPrefixWidth - nameWidth - 1);
707
707
  const summaryWidth = Math.max(1, rightWidth - elapsedWidth - 1);
708
708
  const left = `${prefix}${fit(status, statusWidth)} ${fit(name, nameWidth)}`;
709
709
  const right = `${dim(fitRight(rowSummary(row), summaryWidth), fg)} ${fitRight(elapsed, elapsedWidth)}`;
710
- const gap = Math.max(1, available - visibleWidth(left) - visibleWidth(right));
710
+ const gap = Math.max(1, available - piVisibleWidth(left) - piVisibleWidth(right));
711
711
  return `${left}${" ".repeat(gap)}${right}`;
712
712
  }
713
713
  function statusGlyph(row) {
@@ -809,16 +809,16 @@ function rowSummary(row) {
809
809
  }
810
810
  function fit(value, width) {
811
811
  const str = singleLine(value);
812
- const visible = visibleWidth(str);
813
- if (visible >= width)
814
- return truncateVisible(str, width);
812
+ const visible = piVisibleWidth(str);
813
+ if (visible > width)
814
+ return piTruncateToWidth(str, width);
815
815
  return str + " ".repeat(width - visible);
816
816
  }
817
817
  function fitRight(value, width) {
818
818
  const str = singleLine(value);
819
- const visible = visibleWidth(str);
820
- if (visible >= width)
821
- return truncateVisible(str, width);
819
+ const visible = piVisibleWidth(str);
820
+ if (visible > width)
821
+ return piTruncateToWidth(str, width);
822
822
  return " ".repeat(width - visible) + str;
823
823
  }
824
824
  function singleLine(value) {
@@ -901,29 +901,49 @@ function installNavigatorEditor(ui, deps) {
901
901
  function wrapEditor(inner, deps) {
902
902
  if (inner && typeof inner.render === "function")
903
903
  state().editorComponent = inner;
904
+ const methods = new Map();
905
+ const replacements = new Map();
904
906
  const proxy = new Proxy(inner, {
905
907
  get(target, prop) {
908
+ const value = Reflect.get(target, prop);
909
+ if (typeof value !== "function" || replacements.get(prop) === value)
910
+ return value;
911
+ const cached = methods.get(prop);
912
+ if (cached && cached.original === value)
913
+ return cached.exposed;
914
+ // Capture the method before another editor decorator replaces it.
915
+ // A decorator can retain this wrapper and call it as its delegate.
916
+ let exposed = value.bind(target);
906
917
  if (prop === "handleInput") {
907
- return (data) => {
918
+ exposed = (data) => {
908
919
  if (target.getText?.() === "" && handleMainListInput(data, deps)) {
909
920
  return;
910
921
  }
911
- target.handleInput(data);
922
+ value.call(target, data);
912
923
  };
913
924
  }
914
- if (prop === "render" && typeof target.render === "function") {
915
- return (...args) => {
925
+ if (prop === "render") {
926
+ exposed = (...args) => {
916
927
  const s = state();
917
928
  if (s.editorFocusTarget === proxy)
918
929
  s.editorRenders = (s.editorRenders ?? 0) + 1;
919
- return target.render(...args);
930
+ return value.apply(target, args);
920
931
  };
921
932
  }
922
- const value = Reflect.get(target, prop);
923
- return typeof value === "function" ? value.bind(target) : value;
933
+ methods.set(prop, { original: value, exposed });
934
+ return exposed;
924
935
  },
925
936
  set(target, prop, value) {
926
- return Reflect.set(target, prop, value);
937
+ const cached = methods.get(prop);
938
+ const restoring = cached !== undefined && value === cached.exposed;
939
+ if (!Reflect.set(target, prop, restoring ? cached.original : value))
940
+ return false;
941
+ // Preserve replacement identity so the installing decorator can undo it.
942
+ if (!restoring && typeof value === "function")
943
+ replacements.set(prop, value);
944
+ else
945
+ replacements.delete(prop);
946
+ return true;
927
947
  },
928
948
  });
929
949
  // Pi mounts and focuses whatever the factory returns; an extension that
@@ -1137,6 +1157,8 @@ function openNavigator() {
1137
1157
  catch { /* keep foreground usable */ }
1138
1158
  }
1139
1159
  function createOverlayComponent(initialRows, deps, tui, theme, done, onClosed, initialDetailId) {
1160
+ let editorRendersSeen = state().editorRenders ?? 0;
1161
+ let sawLiveEditor = liveEditorMounted(tui) === true;
1140
1162
  // The overlay only ever shows one row's detail; the rail below it is the list.
1141
1163
  const overlayState = { rows: initialRows, selected: 0 };
1142
1164
  let logTailRows = DEFAULT_LOG_TAIL_ROWS;
@@ -1296,19 +1318,24 @@ function createOverlayComponent(initialRows, deps, tui, theme, done, onClosed, i
1296
1318
  closeArmTimer.unref?.();
1297
1319
  requestRender();
1298
1320
  }
1299
- let editorRendersSeen;
1300
1321
  /**
1301
- * Our editor wrapper was uninstalled: close, since no key of ours can reach this overlay again and
1302
- * it would cover the editor that replaced ours (#332). An extension that composes the editor inside
1303
- * its own non-container component still renders ours, so the wrapper also counts as live while it
1304
- * rendered since the previous overlay frame (Pi renders the editor before it composites overlays).
1322
+ * Close when a replacement editor takes over while the sheet is open (#332).
1323
+ * A wrapper inside another extension's editor still counts as live if it rendered since
1324
+ * the last overlay frame. Pi renders the editor before it composites overlays.
1305
1325
  */
1306
1326
  function closeIfEditorReplaced() {
1307
- const rendersBefore = editorRendersSeen;
1308
1327
  const renders = state().editorRenders ?? 0;
1328
+ const rendered = renders !== editorRendersSeen;
1309
1329
  editorRendersSeen = renders;
1310
- state().editorRenderedLastFrame = rendersBefore === undefined ? undefined : renders !== rendersBefore;
1311
- if (closed || liveEditorMounted(tui) !== false || rendersBefore === undefined || renders !== rendersBefore)
1330
+ state().editorRenderedLastFrame = rendered;
1331
+ if (closed)
1332
+ return;
1333
+ const mounted = liveEditorMounted(tui);
1334
+ if (rendered || mounted === true) {
1335
+ sawLiveEditor = true;
1336
+ return;
1337
+ }
1338
+ if (mounted !== false || !sawLiveEditor)
1312
1339
  return;
1313
1340
  // Not from inside pi-tui's render pass: hiding an overlay there would change the stack it is drawing.
1314
1341
  queueMicrotask(() => {
@@ -1839,10 +1866,10 @@ function fill(glyph, label, width) {
1839
1866
  return prefix + glyph.repeat(w - visibleWidth(prefix));
1840
1867
  }
1841
1868
  function safeTruncate(line, width, truncate) {
1842
- if (visibleWidth(line) <= width)
1869
+ if (piVisibleWidth(line) <= width)
1843
1870
  return line;
1844
1871
  const cut = truncate(line, width);
1845
- return visibleWidth(cut) > width ? truncateVisible(cut, width) : cut;
1872
+ return piVisibleWidth(cut) > width ? piTruncateToWidth(cut, width) : cut;
1846
1873
  }
1847
1874
  const ANSI_RE = new RegExp("[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\\u0007)|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))", "g");
1848
1875
  const FORMATTING_PREFIX_RE = new RegExp(`^(?:${ANSI_RE.source}|<\\/?[a-zA-Z][\\w-]*>|</>)`);
@@ -460,7 +460,7 @@ const BACK_TARGET = "back-to-main";
460
460
 
461
461
  function highlightPointerTarget(theme: unknown, line: string, width: number): string {
462
462
  const colors = theme as { bg?(color: string, value: string): string } | undefined;
463
- return colors?.bg?.("selectedBg", line + " ".repeat(Math.max(0, width - visibleWidth(line))))
463
+ return colors?.bg?.("selectedBg", line + " ".repeat(Math.max(0, width - piVisibleWidth(line))))
464
464
  ?? themeFgFromTheme(theme)("accent", line);
465
465
  }
466
466
 
@@ -783,16 +783,16 @@ function formatMainListRow(row: InternalRow, selected: boolean, fg: (color: stri
783
783
  const status = fg(indicator.color, indicator.glyph);
784
784
  const elapsed = singleLine(row.elapsed || "-");
785
785
  const available = Math.max(24, width || MAIN_LIST_FALLBACK_WIDTH);
786
- const elapsedWidth = Math.min(Math.max(visibleWidth(elapsed), 4), 12);
786
+ const elapsedWidth = Math.min(Math.max(piVisibleWidth(elapsed), 4), 12);
787
787
  const statusWidth = 2;
788
- const leftPrefixWidth = visibleWidth(prefix) + statusWidth + 1;
788
+ const leftPrefixWidth = piVisibleWidth(prefix) + statusWidth + 1;
789
789
  const maxNameWidth = Math.max(8, Math.floor(available * 0.36));
790
790
  const nameWidth = Math.max(8, Math.min(44, maxNameWidth, available - leftPrefixWidth - elapsedWidth - 10));
791
791
  const rightWidth = Math.max(8, available - leftPrefixWidth - nameWidth - 1);
792
792
  const summaryWidth = Math.max(1, rightWidth - elapsedWidth - 1);
793
793
  const left = `${prefix}${fit(status, statusWidth)} ${fit(name, nameWidth)}`;
794
794
  const right = `${dim(fitRight(rowSummary(row), summaryWidth), fg)} ${fitRight(elapsed, elapsedWidth)}`;
795
- const gap = Math.max(1, available - visibleWidth(left) - visibleWidth(right));
795
+ const gap = Math.max(1, available - piVisibleWidth(left) - piVisibleWidth(right));
796
796
  return `${left}${" ".repeat(gap)}${right}`;
797
797
  }
798
798
 
@@ -879,15 +879,15 @@ function rowSummary(row: InternalRow): string {
879
879
 
880
880
  function fit(value: string, width: number): string {
881
881
  const str = singleLine(value);
882
- const visible = visibleWidth(str);
883
- if (visible >= width) return truncateVisible(str, width);
882
+ const visible = piVisibleWidth(str);
883
+ if (visible > width) return piTruncateToWidth(str, width);
884
884
  return str + " ".repeat(width - visible);
885
885
  }
886
886
 
887
887
  function fitRight(value: string, width: number): string {
888
888
  const str = singleLine(value);
889
- const visible = visibleWidth(str);
890
- if (visible >= width) return truncateVisible(str, width);
889
+ const visible = piVisibleWidth(str);
890
+ if (visible > width) return piTruncateToWidth(str, width);
891
891
  return " ".repeat(width - visible) + str;
892
892
  }
893
893
 
@@ -954,28 +954,43 @@ function installNavigatorEditor(ui: any, deps: HostDeps): unknown {
954
954
 
955
955
  function wrapEditor(inner: any, deps: HostDeps): unknown {
956
956
  if (inner && typeof inner.render === "function") state().editorComponent = inner as Component;
957
+ const methods = new Map<PropertyKey, { original: Function; exposed: Function }>();
958
+ const replacements = new Map<PropertyKey, Function>();
957
959
  const proxy: any = new Proxy(inner, {
958
960
  get(target, prop) {
961
+ const value = Reflect.get(target, prop);
962
+ if (typeof value !== "function" || replacements.get(prop) === value) return value;
963
+ const cached = methods.get(prop);
964
+ if (cached && cached.original === value) return cached.exposed;
965
+ // Capture the method before another editor decorator replaces it.
966
+ // A decorator can retain this wrapper and call it as its delegate.
967
+ let exposed = value.bind(target);
959
968
  if (prop === "handleInput") {
960
- return (data: string) => {
969
+ exposed = (data: string) => {
961
970
  if (target.getText?.() === "" && handleMainListInput(data, deps)) {
962
971
  return;
963
972
  }
964
- target.handleInput(data);
973
+ value.call(target, data);
965
974
  };
966
975
  }
967
- if (prop === "render" && typeof target.render === "function") {
968
- return (...args: unknown[]) => {
976
+ if (prop === "render") {
977
+ exposed = (...args: unknown[]) => {
969
978
  const s = state();
970
979
  if (s.editorFocusTarget === proxy) s.editorRenders = (s.editorRenders ?? 0) + 1;
971
- return target.render(...args);
980
+ return value.apply(target, args);
972
981
  };
973
982
  }
974
- const value = Reflect.get(target, prop);
975
- return typeof value === "function" ? value.bind(target) : value;
983
+ methods.set(prop, { original: value, exposed });
984
+ return exposed;
976
985
  },
977
986
  set(target, prop, value) {
978
- return Reflect.set(target, prop, value);
987
+ const cached = methods.get(prop);
988
+ const restoring = cached !== undefined && value === cached.exposed;
989
+ if (!Reflect.set(target, prop, restoring ? cached.original : value)) return false;
990
+ // Preserve replacement identity so the installing decorator can undo it.
991
+ if (!restoring && typeof value === "function") replacements.set(prop, value);
992
+ else replacements.delete(prop);
993
+ return true;
979
994
  },
980
995
  });
981
996
  // Pi mounts and focuses whatever the factory returns; an extension that
@@ -1174,6 +1189,8 @@ function createOverlayComponent(
1174
1189
  onClosed: () => void,
1175
1190
  initialDetailId: string,
1176
1191
  ) {
1192
+ let editorRendersSeen = state().editorRenders ?? 0;
1193
+ let sawLiveEditor = liveEditorMounted(tui) === true;
1177
1194
  // The overlay only ever shows one row's detail; the rail below it is the list.
1178
1195
  const overlayState: OverlayState = { rows: initialRows, selected: 0 };
1179
1196
  let logTailRows: number = DEFAULT_LOG_TAIL_ROWS;
@@ -1331,19 +1348,23 @@ function createOverlayComponent(
1331
1348
  requestRender();
1332
1349
  }
1333
1350
 
1334
- let editorRendersSeen: number | undefined;
1335
1351
  /**
1336
- * Our editor wrapper was uninstalled: close, since no key of ours can reach this overlay again and
1337
- * it would cover the editor that replaced ours (#332). An extension that composes the editor inside
1338
- * its own non-container component still renders ours, so the wrapper also counts as live while it
1339
- * rendered since the previous overlay frame (Pi renders the editor before it composites overlays).
1352
+ * Close when a replacement editor takes over while the sheet is open (#332).
1353
+ * A wrapper inside another extension's editor still counts as live if it rendered since
1354
+ * the last overlay frame. Pi renders the editor before it composites overlays.
1340
1355
  */
1341
1356
  function closeIfEditorReplaced(): void {
1342
- const rendersBefore = editorRendersSeen;
1343
1357
  const renders = state().editorRenders ?? 0;
1358
+ const rendered = renders !== editorRendersSeen;
1344
1359
  editorRendersSeen = renders;
1345
- state().editorRenderedLastFrame = rendersBefore === undefined ? undefined : renders !== rendersBefore;
1346
- if (closed || liveEditorMounted(tui) !== false || rendersBefore === undefined || renders !== rendersBefore) return;
1360
+ state().editorRenderedLastFrame = rendered;
1361
+ if (closed) return;
1362
+ const mounted = liveEditorMounted(tui);
1363
+ if (rendered || mounted === true) {
1364
+ sawLiveEditor = true;
1365
+ return;
1366
+ }
1367
+ if (mounted !== false || !sawLiveEditor) return;
1347
1368
  // Not from inside pi-tui's render pass: hiding an overlay there would change the stack it is drawing.
1348
1369
  queueMicrotask(() => {
1349
1370
  if (closed) return;
@@ -1870,9 +1891,9 @@ function fill(glyph: string, label: string, width: number): string {
1870
1891
  }
1871
1892
 
1872
1893
  function safeTruncate(line: string, width: number, truncate: (s: string, width: number) => string): string {
1873
- if (visibleWidth(line) <= width) return line;
1894
+ if (piVisibleWidth(line) <= width) return line;
1874
1895
  const cut = truncate(line, width);
1875
- return visibleWidth(cut) > width ? truncateVisible(cut, width) : cut;
1896
+ return piVisibleWidth(cut) > width ? piTruncateToWidth(cut, width) : cut;
1876
1897
  }
1877
1898
 
1878
1899
  const ANSI_RE = new RegExp("[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\\u0007)|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))", "g");
@@ -156,6 +156,13 @@ export function listOutbox(ctx, filter = {}) {
156
156
  const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
157
157
  return getRows(ctx, `SELECT * FROM outbox_events ${where} ORDER BY created_at, event_id`, ...params).map((row) => mapOutbox(ctx, row));
158
158
  }
159
+ /** Check a wait handoff without loading the retained evidence for its generations. */
160
+ export function hasDeliveredWaitDependency(ctx, operationId, terminalRevision, recipient) {
161
+ const owner = ownerClause("recipient", recipient);
162
+ return getRows(ctx, `SELECT 1 FROM outbox_events
163
+ WHERE operation_id = ? AND terminal_revision = ? AND event_type = 'dependency-ready'
164
+ AND delivered_at IS NOT NULL AND ${owner.sql} LIMIT 1`, requireId("operationId", operationId), requireCounter("terminalRevision", terminalRevision), ...owner.params).length > 0;
165
+ }
159
166
  /** Find recipients with deliverable dependencies without loading each event's evidence. */
160
167
  export function listDispatchableOutboxRecipients(ctx) {
161
168
  return getRows(ctx, `SELECT recipient_kind, recipient_session_id, recipient_workspace, recipient_branch_id, recipient_goal_id,
@@ -281,6 +281,15 @@ export function listOutbox(ctx: StoreContext, filter: OutboxFilter = {}): Outbox
281
281
  ).map((row) => mapOutbox(ctx, row));
282
282
  }
283
283
 
284
+ /** Check a wait handoff without loading the retained evidence for its generations. */
285
+ export function hasDeliveredWaitDependency(ctx: StoreContext, operationId: string, terminalRevision: number, recipient: OwnerIdentity): boolean {
286
+ const owner = ownerClause("recipient", recipient);
287
+ return getRows(ctx, `SELECT 1 FROM outbox_events
288
+ WHERE operation_id = ? AND terminal_revision = ? AND event_type = 'dependency-ready'
289
+ AND delivered_at IS NOT NULL AND ${owner.sql} LIMIT 1`,
290
+ requireId("operationId", operationId), requireCounter("terminalRevision", terminalRevision), ...owner.params).length > 0;
291
+ }
292
+
284
293
  /** Find recipients with deliverable dependencies without loading each event's evidence. */
285
294
  export function listDispatchableOutboxRecipients(ctx: StoreContext): Array<{ recipient: OwnerIdentity; count: number }> {
286
295
  return getRows(
@@ -24,7 +24,7 @@ import { createContext, openDatabase, run } from "./sqlite.domain.mjs";
24
24
  import { getOperation as readOperationRecord, listAssignmentCleanupOperations as readAssignmentCleanupOperations, listOperations as readOperationRecords, listRunningSupervisedBy as readRunningSupervisedBy, releaseSupervision as writeSupervisionRelease, recordSupervision as writeSupervision, recordTerminalOutcome as writeTerminalOutcome, registerOperation as writeOperation, } from "./operations.domain.mjs";
25
25
  import { getChangeRevision as readChangeRevision, readDiscoveryClaim as readClaim, readDiscoveryState, releaseDiscoveryClaim as deleteDiscoveryClaim, tryClaimDiscovery as writeDiscoveryClaim, } from "./discovery.domain.mjs";
26
26
  import { acknowledgeResult as writeAcknowledgement, cancelWait as writeCancellation, claimResume as writeClaim, findPendingWaitForOwner, getWait as readWait, listDependencies as readDependencies, listEvidencePins as readPins, listEvidenceReads as readReads, listResumeClaims as readClaims, listUnreconciledClaims, listWaits as readWaits, publishResumeAttempt as writeAttemptPublication, recordEvidencePin as writePin, recordEvidenceRead as writeRead, registerWait as writeWait, releaseEvidencePins as writePinRelease, holdFailedResume as writeHoldFailedResume, releaseResumeClaim as writeClaimRelease, transitionWaitPhase as writePhase, } from "./waits.domain.mjs";
27
- import { claimOutbox as writeOutboxClaim, listDispatchableOutboxRecipients as readDispatchableOutboxRecipients, listOutbox as readOutbox, markOutboxDelivered as writeOutboxDelivery, releaseOutbox as writeOutboxRelease, } from "./outbox.domain.mjs";
27
+ import { claimOutbox as writeOutboxClaim, hasDeliveredWaitDependency as readDeliveredWaitDependency, listDispatchableOutboxRecipients as readDispatchableOutboxRecipients, listOutbox as readOutbox, markOutboxDelivered as writeOutboxDelivery, releaseOutbox as writeOutboxRelease, } from "./outbox.domain.mjs";
28
28
  import { readOperationEvidence } from "./rows.domain.mjs";
29
29
  import { SCHEMA_VERSION, } from "./types.domain.mjs";
30
30
  export function openStore(options) {
@@ -250,6 +250,10 @@ export function openStore(options) {
250
250
  alive();
251
251
  return readOutbox(ctx, filter);
252
252
  },
253
+ hasDeliveredWaitDependency(operationId, terminalRevision, recipient) {
254
+ alive();
255
+ return readDeliveredWaitDependency(ctx, operationId, terminalRevision, recipient);
256
+ },
253
257
  listDispatchableOutboxRecipients() {
254
258
  alive();
255
259
  return readDispatchableOutboxRecipients(ctx);
@@ -68,6 +68,7 @@ import {
68
68
  } from "./waits.ts";
69
69
  import {
70
70
  claimOutbox as writeOutboxClaim,
71
+ hasDeliveredWaitDependency as readDeliveredWaitDependency,
71
72
  listDispatchableOutboxRecipients as readDispatchableOutboxRecipients,
72
73
  listOutbox as readOutbox,
73
74
  markOutboxDelivered as writeOutboxDelivery,
@@ -318,6 +319,7 @@ export interface Store {
318
319
  // ---- outbox ----
319
320
 
320
321
  listOutbox(filter?: OutboxFilter): OutboxEventRecord[];
322
+ hasDeliveredWaitDependency(operationId: string, terminalRevision: number, recipient: OwnerIdentity): boolean;
321
323
  /** Lightweight dispatch candidates; evidence is read only after a claim succeeds. */
322
324
  listDispatchableOutboxRecipients(): Array<{ recipient: OwnerIdentity; count: number }>;
323
325
  /** Claim pending deliveries for a `ready`/`resuming` generation. */
@@ -559,6 +561,10 @@ export function openStore(options: StoreOptions): Store {
559
561
  alive();
560
562
  return readOutbox(ctx, filter);
561
563
  },
564
+ hasDeliveredWaitDependency(operationId, terminalRevision, recipient) {
565
+ alive();
566
+ return readDeliveredWaitDependency(ctx, operationId, terminalRevision, recipient);
567
+ },
562
568
  listDispatchableOutboxRecipients() {
563
569
  alive();
564
570
  return readDispatchableOutboxRecipients(ctx);
@@ -1,7 +1,8 @@
1
1
  // Generated fixed launch domain from packages/pi-better-subagents/task-guard.ts. Do not edit directly.
2
2
  /** Installed as the final inline extension by the trusted native launcher. */
3
3
  import { SettingsManager } from "@earendil-works/pi-coding-agent";
4
- import { canonicalizePath, describeSandboxSupport } from "./shared-sandbox-core.domain.mjs";
4
+ import { deniedGitOperation, worktreeDenialText } from "./worktree-feedback.domain.mjs";
5
+ import { canonicalizePath, compileWritePolicy, describeSandboxSupport } from "./shared-sandbox-core.domain.mjs";
5
6
  import { GUARDED_TASK_TOOLS, installTaskTools, TASK_BUILTINS } from "./shared-task-sandbox.domain.mjs";
6
7
  import { parseTaskPolicy, RUN_APPLICATION, selectTaskTools } from "./task-policy.domain.mjs";
7
8
  import { SANDBOX_POLICY_CHANNEL, SANDBOX_POLICY_REQUEST_CHANNEL } from "./permission-policy.domain.mjs";
@@ -62,6 +63,18 @@ export default function taskGuard(pi, input, fatal, ownedTools = false) {
62
63
  policy: Object.freeze({ writableRoot: policy.root, home: policy.home, permissions: policy.permissions, denyWrite: policy.denyWrite,
63
64
  runtimeCompatibility: true, runtimeWrite: Object.freeze([policy.scratch]) }),
64
65
  });
66
+ if (policy.worktreeGitDir) {
67
+ const gitDir = policy.worktreeGitDir;
68
+ const compiled = compileWritePolicy(plan.policy);
69
+ pi.on("tool_result", event => {
70
+ const operation = deniedGitOperation(event, gitDir, compiled);
71
+ if (operation)
72
+ return {
73
+ content: [...event.content, { type: "text", text: worktreeDenialText(operation, policy.root) }],
74
+ details: { ...(event.details && typeof event.details === "object" ? event.details : {}), deniedWorktreeGitOperation: operation },
75
+ };
76
+ });
77
+ }
65
78
  const controller = Object.freeze({ requireLaunchPlan: () => plan });
66
79
  let shellPath;
67
80
  let currentCwd = process.cwd();
@@ -1,6 +1,7 @@
1
1
  /** Installed as the final inline extension by the trusted native launcher. */
2
2
  import { SettingsManager, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
- import { canonicalizePath, describeSandboxSupport } from "./shared-sandbox-core.ts";
3
+ import { deniedGitOperation, worktreeDenialText } from "./worktree-feedback.ts";
4
+ import { canonicalizePath, compileWritePolicy, describeSandboxSupport } from "./shared-sandbox-core.ts";
4
5
  import { GUARDED_TASK_TOOLS, installTaskTools, TASK_BUILTINS } from "./shared-task-sandbox.ts";
5
6
  import { parseTaskPolicy, RUN_APPLICATION, selectTaskTools, type TaskPolicy } from "./task-policy.ts";
6
7
  import { SANDBOX_POLICY_CHANNEL, SANDBOX_POLICY_REQUEST_CHANNEL } from "./permission-policy.ts";
@@ -51,6 +52,17 @@ export default function taskGuard(pi: ExtensionAPI, input: unknown, fatal: (erro
51
52
  policy: Object.freeze({ writableRoot: policy.root, home: policy.home, permissions: policy.permissions, denyWrite: policy.denyWrite,
52
53
  runtimeCompatibility: true, runtimeWrite: Object.freeze([policy.scratch]) }),
53
54
  });
55
+ if (policy.worktreeGitDir) {
56
+ const gitDir = policy.worktreeGitDir;
57
+ const compiled = compileWritePolicy(plan.policy);
58
+ pi.on("tool_result", event => {
59
+ const operation = deniedGitOperation(event, gitDir, compiled);
60
+ if (operation) return {
61
+ content: [...event.content, {type: "text", text: worktreeDenialText(operation, policy.root)}],
62
+ details: { ...(event.details && typeof event.details === "object" ? event.details : {}), deniedWorktreeGitOperation: operation },
63
+ };
64
+ });
65
+ }
54
66
  const controller = Object.freeze({ requireLaunchPlan: () => plan });
55
67
  let shellPath: string | undefined;
56
68
  let currentCwd = process.cwd();
@@ -125,6 +125,7 @@ export function parseTaskPolicy(value) {
125
125
  throw new Error("Invalid task sandbox extension tools.");
126
126
  return Object.freeze({
127
127
  version: 1, root: absolute("root"), home: absolute("home"), agentDir: absolute("agentDir"), profilePath: absolute("profilePath"), scratch: absolute("scratch"),
128
+ ...(v.worktreeGitDir !== undefined ? { worktreeGitDir: absolute("worktreeGitDir") } : {}),
128
129
  permissions: Object.freeze({
129
130
  projectFiles: p.projectFiles, outsideProject: p.outsideProject, storedCredentials: p.storedCredentials,
130
131
  commands: p.commands, network: p.network,
@@ -172,7 +173,7 @@ export function prepareTaskRuntime(options) {
172
173
  const scratch = createTaskScratch();
173
174
  const policy = parseTaskPolicy({
174
175
  version: 1, root, home, agentDir, profilePath: join(controlDir, "task.sb"), scratch: scratch.path,
175
- permissions,
176
+ permissions, worktreeGitDir: options.worktreeGitDir,
176
177
  denyWrite: [...new Set([
177
178
  ...(options.capturedDenyWrite ?? []),
178
179
  controlDir, scratch.anchor, agentDir, ...runtimeDirectories, ...(options.runtimeRoots ?? []), join(root, ".pi"),
@@ -69,6 +69,8 @@ export type TaskPermissions = Readonly<SandboxPermissions> & CommandSettings;
69
69
  export type TaskPolicy = Readonly<{
70
70
  version: 1;
71
71
  root: string;
72
+ /** Actual linked checkout metadata recorded by the launcher. */
73
+ worktreeGitDir?: string;
72
74
  home: string;
73
75
  agentDir: string;
74
76
  profilePath: string;
@@ -154,6 +156,7 @@ export function parseTaskPolicy(value: unknown): TaskPolicy { if (!value || t
154
156
  })) throw new Error("Invalid task sandbox extension tools.");
155
157
  return Object.freeze({
156
158
  version: 1, root: absolute("root"), home: absolute("home"), agentDir: absolute("agentDir"), profilePath: absolute("profilePath"), scratch: absolute("scratch"),
159
+ ...(v.worktreeGitDir !== undefined ? { worktreeGitDir: absolute("worktreeGitDir") } : {}),
157
160
  permissions: Object.freeze({
158
161
  projectFiles: p.projectFiles, outsideProject: p.outsideProject, storedCredentials: p.storedCredentials,
159
162
  commands: p.commands, network: p.network,
@@ -175,6 +178,7 @@ export function prepareTaskRuntime(options: {
175
178
  root: string; controlDir: string; tools: readonly string[]; piBin?: string;
176
179
  permissions?: SandboxPermissions & Partial<CommandSettings>; extensionPaths?: readonly string[]; runtimeRoots?: readonly string[];
177
180
  capturedDenyWrite?: readonly string[];
181
+ worktreeGitDir?: string;
178
182
  /** Trusted launcher-selected bridge from the pinned worker release. */
179
183
  operationBridgePath?: string;
180
184
  applyPatch?: boolean; extensionTools?: readonly TaskExtensionTool[];
@@ -206,7 +210,7 @@ export function prepareTaskRuntime(options: {
206
210
  const scratch = createTaskScratch();
207
211
  const policy = parseTaskPolicy({
208
212
  version: 1, root, home, agentDir, profilePath: join(controlDir, "task.sb"), scratch: scratch.path,
209
- permissions,
213
+ permissions, worktreeGitDir: options.worktreeGitDir,
210
214
  denyWrite: [...new Set([
211
215
  ...(options.capturedDenyWrite ?? []),
212
216
  controlDir, scratch.anchor, agentDir, ...runtimeDirectories, ...(options.runtimeRoots ?? []), join(root, ".pi"),
@@ -17,10 +17,9 @@
17
17
  import { createHash } from "node:crypto";
18
18
  import { assignmentFor, projectAssignment, createAssignmentProjector, withAssignmentObservations } from "./assignment-projection.mjs";
19
19
  import { readMeta, listRunRecords, effectiveStatus, isFinalResultStatus } from "./registry.domain.mjs";
20
- import { buildSubagentResultPayload } from "./finalization.domain.mjs";
21
20
  import { stopRun } from "./stop.domain.mjs";
22
21
  import { SUBAGENT_LIST_DEFAULT_LIMIT, SUBAGENT_LIST_MAX_LIMIT, SUBAGENT_LIST_STATUSES, collectSubagentList, formatSubagentListRow, listFolderScopeKey, normalizeSubagentListOptions, } from "./list.domain.mjs";
23
- import { assembleOrphanedResult, assembleRunningResult, assembleSubagentListPayload, assembleSubagentOutput, assembleUnreadableMetadata, listIncidentCount, formatIncidentLabel, listRevisions, requestScopeKey, resolveActiveOrigin, resolveRunAccess, unknownRunError, } from "./output-payload.domain.mjs";
22
+ import { assembleOrphanedResult, assembleRunningResult, assembleSubagentListPayload, assembleSubagentOutput, assembleUnreadableMetadata, listIncidentCount, formatIncidentLabel, listRevisions, requestScopeKey, resolveActiveOrigin, resolveRunAccess, assembleSubagentResult, unknownRunError, } from "./output-payload.domain.mjs";
24
23
  import { budgetFor, readOutputControls } from "./shared-log-utils.domain.mjs";
25
24
  import { readRunFailures } from "./failures.domain.mjs";
26
25
  import { actionablePermissionBlockers } from "./shared-failure-observations.domain.mjs";
@@ -465,7 +464,8 @@ export function subagentResultTool(Type, baseSession = {}) {
465
464
  if (access.kind === "denied")
466
465
  return subagentResultText(access.payload);
467
466
  const meta = access.meta;
468
- const observed = await session.observeAssignment?.(meta.id);
467
+ // A saved result remains readable after its row leaves the live observation.
468
+ const observed = access.retained ? undefined : await session.observeAssignment?.(meta.id);
469
469
  const outcome = meta.assignment ? baseSession.inspectOutcome?.(meta, params, ctx) : undefined;
470
470
  // Exact inspection has already checked recipient and read authority.
471
471
  // Its immutable terminal record supersedes an older shared projection
@@ -497,11 +497,7 @@ export function subagentResultTool(Type, baseSession = {}) {
497
497
  }
498
498
  return resultText(assembleRunningResult(p.id, meta, p, scopeKey, healthLine));
499
499
  }
500
- const body = buildSubagentResultPayload(p.id, p, healthLine, scopeKey);
501
- if (body === null) {
502
- return resultText(assembleRunningResult(p.id, meta, p, scopeKey, healthLine));
503
- }
504
- return resultText(body);
500
+ return resultText(assembleSubagentResult(p.id, meta, p, healthLine, scopeKey));
505
501
  });
506
502
  },
507
503
  };
@@ -18,7 +18,6 @@ import { createHash } from "node:crypto";
18
18
  import { assignmentFor, projectAssignment, createAssignmentProjector, withAssignmentObservations } from "./assignment-projection.mjs";
19
19
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
20
20
  import { readMeta, listRunRecords, effectiveStatus, isFinalResultStatus, type RunCallbackOrigin, type RunMeta, type RunStatus } from "./registry.ts";
21
- import { buildSubagentResultPayload } from "./finalization.ts";
22
21
  import { stopRun } from "./stop.ts";
23
22
  import {
24
23
  SUBAGENT_LIST_DEFAULT_LIMIT,
@@ -41,6 +40,7 @@ import {
41
40
  requestScopeKey,
42
41
  resolveActiveOrigin,
43
42
  resolveRunAccess,
43
+ assembleSubagentResult,
44
44
  unknownRunError,
45
45
  type SubagentToolSession,
46
46
  } from "./output-payload.ts";
@@ -531,7 +531,8 @@ export function subagentResultTool(Type: TypeModule, baseSession: SubagentToolSe
531
531
  }
532
532
  if (access.kind === "denied") return subagentResultText(access.payload);
533
533
  const meta = access.meta;
534
- const observed = await session.observeAssignment?.(meta.id);
534
+ // A saved result remains readable after its row leaves the live observation.
535
+ const observed = access.retained ? undefined : await session.observeAssignment?.(meta.id);
535
536
  const outcome = meta.assignment ? baseSession.inspectOutcome?.(meta, params as Record<string, unknown>, ctx) : undefined;
536
537
  // Exact inspection has already checked recipient and read authority.
537
538
  // Its immutable terminal record supersedes an older shared projection
@@ -563,11 +564,7 @@ export function subagentResultTool(Type: TypeModule, baseSession: SubagentToolSe
563
564
  }
564
565
  return resultText(assembleRunningResult(p.id, meta, p, scopeKey, healthLine));
565
566
  }
566
- const body = buildSubagentResultPayload(p.id, p, healthLine, scopeKey);
567
- if (body === null) {
568
- return resultText(assembleRunningResult(p.id, meta, p, scopeKey, healthLine));
569
- }
570
- return resultText(body);
567
+ return resultText(assembleSubagentResult(p.id, meta, p, healthLine, scopeKey));
571
568
  });
572
569
  },
573
570
  } as ToolDefinition;