@herbertgao/pi-extensions 2026.10.10 → 2026.10.11

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 (108) hide show
  1. package/README.md +10 -8
  2. package/THIRD_PARTY_NOTICES.md +2 -2
  3. package/node_modules/@herbertgao/pi-cc-extensions/README.en.md +3 -0
  4. package/node_modules/@herbertgao/pi-cc-extensions/README.md +3 -0
  5. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/config.ts +1 -1
  6. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/panel.ts +3 -3
  7. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/compact-mode.ts +126 -42
  8. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/mouse/interaction.ts +24 -6
  9. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/mouse/scroll.ts +69 -16
  10. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/mouse/sticky-prompt.ts +1 -1
  11. package/node_modules/@herbertgao/pi-cc-extensions/package.json +4 -4
  12. package/node_modules/@herbertgao/sol-pi/README.md +7 -1
  13. package/node_modules/@herbertgao/sol-pi/docs/compatibility.md +28 -4
  14. package/node_modules/@herbertgao/sol-pi/docs/configuration.md +17 -4
  15. package/node_modules/@herbertgao/sol-pi/package.json +1 -1
  16. package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/action-fusion/index.ts +35 -25
  17. package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/action-fusion/then-run.ts +95 -26
  18. package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/evidence-preserving-reducer/candidate.ts +39 -2
  19. package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/evidence-preserving-reducer/index.ts +24 -0
  20. package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/observation-pack/index.ts +12 -7
  21. package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/online-context-compact/extension.ts +138 -130
  22. package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/online-context-compact/projection.ts +88 -14
  23. package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/online-context-compact/tools.ts +9 -0
  24. package/node_modules/@herbertgao/sol-pi/src/sol-pi/index.ts +14 -5
  25. package/node_modules/@herbertgao/sol-pi/src/sol-pi/shell-options.ts +22 -0
  26. package/node_modules/@herbertgao/sol-pi/src/sol-pi/tui.ts +11 -0
  27. package/node_modules/@juicesharp/rpiv-ask-user-question/answer-channel.ts +109 -0
  28. package/node_modules/@juicesharp/rpiv-ask-user-question/ask-user-question.ts +117 -71
  29. package/node_modules/@juicesharp/rpiv-ask-user-question/docs/hosts.md +2 -0
  30. package/node_modules/@juicesharp/rpiv-ask-user-question/docs/keyboard.md +3 -1
  31. package/node_modules/@juicesharp/rpiv-ask-user-question/docs/startup-performance.md +83 -0
  32. package/node_modules/@juicesharp/rpiv-ask-user-question/docs/tool-schema.md +74 -5
  33. package/node_modules/@juicesharp/rpiv-ask-user-question/events.ts +84 -0
  34. package/node_modules/@juicesharp/rpiv-ask-user-question/index.ts +10 -4
  35. package/node_modules/@juicesharp/rpiv-ask-user-question/package.json +4 -2
  36. package/node_modules/@juicesharp/rpiv-ask-user-question/presentation.ts +1 -1
  37. package/node_modules/@juicesharp/rpiv-ask-user-question/reconcile.ts +1 -1
  38. package/node_modules/@juicesharp/rpiv-ask-user-question/rpc-fallback.ts +5 -4
  39. package/node_modules/@juicesharp/rpiv-ask-user-question/state/build-questionnaire.ts +19 -19
  40. package/node_modules/@juicesharp/rpiv-ask-user-question/state/i18n-bridge.ts +1 -1
  41. package/node_modules/@juicesharp/rpiv-ask-user-question/state/key-router.ts +7 -4
  42. package/node_modules/@juicesharp/rpiv-ask-user-question/state/questionnaire-session.ts +10 -10
  43. package/node_modules/@juicesharp/rpiv-ask-user-question/state/row-intent.ts +2 -2
  44. package/node_modules/@juicesharp/rpiv-ask-user-question/state/selectors/contract.ts +6 -6
  45. package/node_modules/@juicesharp/rpiv-ask-user-question/state/selectors/derivations.ts +2 -2
  46. package/node_modules/@juicesharp/rpiv-ask-user-question/state/selectors/focus.ts +1 -1
  47. package/node_modules/@juicesharp/rpiv-ask-user-question/state/selectors/projections.ts +9 -9
  48. package/node_modules/@juicesharp/rpiv-ask-user-question/state/state-reducer.ts +5 -5
  49. package/node_modules/@juicesharp/rpiv-ask-user-question/state/state.ts +2 -2
  50. package/node_modules/@juicesharp/rpiv-ask-user-question/tool/external-answer.ts +125 -0
  51. package/node_modules/@juicesharp/rpiv-ask-user-question/tool/format-answer.ts +1 -1
  52. package/node_modules/@juicesharp/rpiv-ask-user-question/tool/normalize-params.ts +1 -1
  53. package/node_modules/@juicesharp/rpiv-ask-user-question/tool/response-envelope.ts +2 -2
  54. package/node_modules/@juicesharp/rpiv-ask-user-question/tool/types.ts +1 -1
  55. package/node_modules/@juicesharp/rpiv-ask-user-question/tool/validate-questionnaire.ts +1 -1
  56. package/node_modules/@juicesharp/rpiv-ask-user-question/view/component-binding.ts +4 -4
  57. package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/multi-select-view.ts +4 -4
  58. package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/option-list-view.ts +2 -2
  59. package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/preview/markdown-content-cache.ts +3 -3
  60. package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/preview/preview-block-renderer.ts +5 -5
  61. package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/preview/preview-layout-decider.ts +3 -3
  62. package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/preview/preview-pane.ts +10 -10
  63. package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/submit-picker.ts +2 -2
  64. package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/tab-bar.ts +1 -1
  65. package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/wrapping-select.ts +1 -1
  66. package/node_modules/@juicesharp/rpiv-ask-user-question/view/dialog-builder.ts +9 -9
  67. package/node_modules/@juicesharp/rpiv-ask-user-question/view/dialog-copy.ts +1 -1
  68. package/node_modules/@juicesharp/rpiv-ask-user-question/view/props-adapter.ts +8 -8
  69. package/node_modules/@juicesharp/rpiv-ask-user-question/view/tab-components.ts +4 -4
  70. package/node_modules/@juicesharp/rpiv-ask-user-question/view/tab-content-strategy.ts +10 -10
  71. package/node_modules/@narumitw/pi-btw/dist/index.ts +3 -0
  72. package/node_modules/@narumitw/pi-btw/dist/index.ts.map +2 -2
  73. package/node_modules/@narumitw/pi-btw/package.json +4 -4
  74. package/node_modules/@narumitw/pi-btw/src/fullscreen-ui.ts +6 -0
  75. package/node_modules/@narumitw/pi-btw/src/keybindings.ts +1 -1
  76. package/node_modules/@narumitw/pi-caffeinate/dist/index.ts +1 -0
  77. package/node_modules/@narumitw/pi-caffeinate/dist/index.ts.map +2 -2
  78. package/node_modules/@narumitw/pi-caffeinate/package.json +3 -3
  79. package/node_modules/@narumitw/pi-caffeinate/src/inhibitor-process.ts +1 -0
  80. package/node_modules/pi-antigravity/README.md +6 -2
  81. package/node_modules/pi-antigravity/package.json +2 -2
  82. package/node_modules/pi-antigravity/src/client/client.ts +44 -52
  83. package/node_modules/pi-antigravity/src/index.ts +13 -0
  84. package/node_modules/pi-antigravity/src/models/discovery.ts +25 -2
  85. package/node_modules/pi-antigravity/src/models/grouping.ts +107 -68
  86. package/node_modules/pi-antigravity/src/models/models.ts +10 -0
  87. package/node_modules/pi-antigravity/src/search/search.ts +581 -43
  88. package/node_modules/pi-antigravity/src/stream/stream.ts +53 -13
  89. package/node_modules/pi-antigravity/src/types/types.ts +13 -0
  90. package/node_modules/pi-antigravity/src/usage/usage.ts +11 -3
  91. package/node_modules/pi-web-access/CHANGELOG.md +21 -0
  92. package/node_modules/pi-web-access/README.md +22 -7
  93. package/node_modules/pi-web-access/credential-source.ts +54 -4
  94. package/node_modules/pi-web-access/curator-page.ts +3 -1
  95. package/node_modules/pi-web-access/curator-server.ts +1 -0
  96. package/node_modules/pi-web-access/deepseek.ts +204 -0
  97. package/node_modules/pi-web-access/dist/index.js +927 -642
  98. package/node_modules/pi-web-access/dist/mcp-cli.js +877 -615
  99. package/node_modules/pi-web-access/gemini-adc.ts +48 -1
  100. package/node_modules/pi-web-access/gemini-search.ts +8 -4
  101. package/node_modules/pi-web-access/index.ts +16 -1
  102. package/node_modules/pi-web-access/package.json +1 -1
  103. package/node_modules/pi-web-access/page-query.ts +12 -6
  104. package/node_modules/pi-web-access/query-rewrite.ts +16 -13
  105. package/node_modules/pi-web-access/summary-review.ts +16 -6
  106. package/node_modules/pi-web-access/utils.ts +3 -0
  107. package/node_modules/pi-web-access/web-tool-core.ts +2 -0
  108. package/package.json +9 -9
@@ -17,7 +17,7 @@ import {
17
17
 
18
18
  const ZENTUI_PAGE_UP_INPUT = /^\x1b\[5;9(?::[12])?~$|^\x1b\[57421;9(?::[12])?u$|^\x1b\[1;6A$/;
19
19
  const ZENTUI_PAGE_DOWN_INPUT = /^\x1b\[6;9(?::[12])?~$|^\x1b\[57422;9(?::[12])?u$|^\x1b\[1;6B$/;
20
- const SCROLL_BOTTOM_SHORTCUT = "ctrl+end";
20
+ const SCROLL_BOTTOM_KEYBINDING = "tui.altScreen.bottom";
21
21
 
22
22
  patchRegistry.ensure(TOOL_MOUSE_TUI_SLOT, () => null);
23
23
  export function getToolMouseTui(): any {
@@ -68,6 +68,14 @@ export function setScrollButtonVisible(visible: boolean): void {
68
68
  export function noteNewTranscriptItem(): void {
69
69
  const state = scrollButtonState();
70
70
  const tui = getToolMouseTui();
71
+ if (nativeScrollTextEnabled(tui)) {
72
+ syncOfficialScrollToEnd(tui);
73
+ if (nativeScrollTextPatch && !isFullscreenAtBottom(tui)) {
74
+ state.newCount += 1;
75
+ tui.requestRender?.();
76
+ }
77
+ return;
78
+ }
71
79
  if (!dockScrollButtonActive() || !state.visible || !tui) return;
72
80
  // 提交新消息时官方可能直接跳回底部(不经过滚动输入):先按实时跟随状态校正,
73
81
  // 否则跟随期间的内容会被当成“离开底部时的新消息”计入。
@@ -137,34 +145,78 @@ export function restoreOfficialScrollToEnd(tui: any): void {
137
145
  tui[OFFICIAL_SCROLL_TO_END_KEY] = undefined;
138
146
  }
139
147
 
140
- /** dock 模式替换官方浮层;native 或 ccstyle off 时保留 Pi 原生 Jump to latest。 */
148
+ /** dock 模式替换官方浮层;native 保留 Pi 原生浮层并换上 dock 文案;ccstyle off 还原 Pi 原样。 */
141
149
  export function syncOfficialScrollToEnd(tui: any): void {
150
+ if (!nativeScrollTextEnabled(tui)) restoreNativeScrollIndicatorText();
142
151
  if (dockScrollButtonActive()) {
143
152
  disableOfficialScrollToEnd(tui);
144
153
  return;
145
154
  }
146
155
  restoreOfficialScrollToEnd(tui);
156
+ if (nativeScrollTextEnabled(tui)) {
157
+ // 离开 dock 时清零一次;native 的后续渲染保留共享计数。
158
+ if (getScrollButtonVisible()) setScrollButtonVisible(false);
159
+ setScrollButtonHovered(false);
160
+ syncNativeScrollIndicatorText(tui);
161
+ return;
162
+ }
147
163
  setScrollButtonVisible(false);
148
164
  setScrollButtonHovered(false);
149
165
  }
150
166
 
167
+ /** 只记录文案补丁;dock 的显隐、快捷键和原生浮层开关仍走原路径。 */
168
+ let nativeScrollTextPatch: { renderer: any; original: () => string } | undefined;
169
+
170
+ function nativeScrollTextEnabled(tui: any): boolean {
171
+ return (
172
+ toolMouseInteractionActive() && config.scrollButtonMode === "native" && fullscreenLazyTui(tui)
173
+ );
174
+ }
175
+
176
+ /** widget 销毁或离开 native 模式时还原 Pi 的原始回调。 */
177
+ export function restoreNativeScrollIndicatorText(): void {
178
+ if (!nativeScrollTextPatch) return;
179
+ const { renderer, original } = nativeScrollTextPatch;
180
+ renderer.scrollToEndIndicator = original;
181
+ nativeScrollTextPatch = undefined;
182
+ scrollButtonState().newCount = 0;
183
+ }
184
+
185
+ function syncNativeScrollIndicatorText(tui: any): void {
186
+ // Pi 的稳定 Proxy 会重绑捕获的方法;文案回调必须从真实 renderer 上取得。
187
+ const renderer = tui.valueOf();
188
+ if (nativeScrollTextPatch?.renderer !== renderer) restoreNativeScrollIndicatorText();
189
+ if (!nativeScrollTextPatch) {
190
+ const original = renderer.scrollToEndIndicator;
191
+ if (typeof original !== "function") return;
192
+ nativeScrollTextPatch = { renderer, original };
193
+ renderer.scrollToEndIndicator = () =>
194
+ original.call(renderer).replace("Jump to latest message", scrollButtonText());
195
+ }
196
+ if (isFullscreenAtBottom(renderer)) scrollButtonState().newCount = 0;
197
+ }
198
+
151
199
  /** 官方 fullscreen:是否已跟随 transcript 底部(按钮隐藏条件)。 */
152
200
  export function isFullscreenAtBottom(tui: any): boolean {
153
201
  const following = tui.isFollowingOutput ?? tui.getPrimaryScrollView?.()?.isFollowingEnd ?? true;
154
202
  return Boolean(following);
155
203
  }
156
204
 
157
- function formatShortcut(shortcut: string): string {
158
- return shortcut
159
- .split("+")
160
- .map((part) =>
161
- part.length <= 1 ? part.toUpperCase() : `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`,
205
+ /** 与 Pi 原生浮层同源(keyDisplayText):用户实际绑定,首字母大写,macOS 上 alt 显示为 option。 */
206
+ function scrollBottomShortcutText(): string {
207
+ return getKeybindings()
208
+ .getKeys(SCROLL_BOTTOM_KEYBINDING)
209
+ .map((key) =>
210
+ key
211
+ .split("+")
212
+ .map((part) => {
213
+ const display =
214
+ process.platform === "darwin" && part.toLowerCase() === "alt" ? "option" : part;
215
+ return display.charAt(0).toUpperCase() + display.slice(1);
216
+ })
217
+ .join("+"),
162
218
  )
163
- .join("+");
164
- }
165
-
166
- export function isScrollBottomInput(data: string): boolean {
167
- return matchesKey(data, SCROLL_BOTTOM_SHORTCUT);
219
+ .join("/");
168
220
  }
169
221
 
170
222
  function isScrollNavigationInput(data: string): boolean {
@@ -251,9 +303,8 @@ export function updateScrollButtonFromInput(tui: any, data: string): void {
251
303
  /** 无新内容时提示原文案;有新内容时换成累计条数。 */
252
304
  function scrollButtonText(): string {
253
305
  const count = getScrollButtonNewCount();
254
- const shortcut = formatShortcut(SCROLL_BOTTOM_SHORTCUT);
255
- if (count <= 0) return `Back to bottom · ${shortcut}`;
256
- return `${count} new message${count === 1 ? "" : "s"} · ${shortcut}`;
306
+ if (count <= 0) return "Back to bottom";
307
+ return `${count} new message${count === 1 ? "" : "s"}`;
257
308
  }
258
309
 
259
310
  export function renderScrollButton(width: number, theme: any): string[] {
@@ -263,9 +314,11 @@ export function renderScrollButton(width: number, theme: any): string[] {
263
314
  !fullscreenLazyTui(getToolMouseTui())
264
315
  )
265
316
  return [];
317
+ // 未绑定时与 Pi 原生一样省略快捷键段。
318
+ const shortcut = scrollBottomShortcutText();
266
319
  const label = theme.fg(
267
320
  getScrollButtonHovered() ? "text" : "accent",
268
- `[ ↓ ${scrollButtonText()} ]`,
321
+ `[ ↓ ${scrollButtonText()}${shortcut ? ` · ${shortcut}` : ""} ]`,
269
322
  );
270
323
  const leftPad = Math.max(0, Math.floor((width - visibleWidth(label)) / 2));
271
324
  return [`${" ".repeat(leftPad)}${truncateToWidth(label, width, "…")}`];
@@ -296,7 +296,7 @@ export function renderStickyPromptScreen(
296
296
  }
297
297
 
298
298
  /** 行与列都落在本帧画出的粘性条内。滚动条那一列在条外。 */
299
- function stickyBarHit(tui: any, packet: SgrMousePacket): boolean {
299
+ export function stickyBarHit(tui: any, packet: SgrMousePacket): boolean {
300
300
  const state = stickyState();
301
301
  if (!stickyPromptActive() || !state.visible || state.layout !== tui?.currentLayout) return false;
302
302
  if (packet.row - 1 !== state.row) return false;
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@herbertgao/pi-cc-extensions",
3
- "version": "1.0.7-local.1",
3
+ "version": "1.0.8-local.1",
4
4
  "license": "MIT",
5
5
  "description": "A Pi productivity suite with Claude Code-style UI, context inspection, and agent/session references",
6
6
  "type": "module",
@@ -71,10 +71,10 @@
71
71
  },
72
72
  "x-upstream": {
73
73
  "package": "pi-cc-extensions",
74
- "version": "1.0.7",
75
- "reviewedVersion": "1.0.7",
74
+ "version": "1.0.8",
75
+ "reviewedVersion": "1.0.8",
76
76
  "repository": "https://github.com/minuque/pi-cc-extensions",
77
- "commit": "5963eefd452822994e6a001830ded7676ebb1845",
77
+ "commit": "2cb2c1ec7240f183ff68cbab0ea6ae3239529f23",
78
78
  "trackVersion": true
79
79
  }
80
80
  }
@@ -13,7 +13,7 @@
13
13
  </p>
14
14
 
15
15
  > [!NOTE]
16
- > This package republishes the MIT-licensed SoL-Pi source from [NVlabs/SoL-Pi](https://github.com/NVlabs/SoL-Pi) at the reviewed commit recorded in `package.json`. It is maintained here as `@herbertgao/sol-pi`, not an official distribution of Pi or NVIDIA.
16
+ > This package republishes the MIT-licensed SoL-Pi source from [NVlabs/SoL-Pi](https://github.com/NVlabs/SoL-Pi). The complete import baseline remains `e1a586af0ad8956f42ae5b26bba20e48fbf30e00`, recorded in `package.json`; Pi 1.x and codemode compatibility fixes from `41fa7e0e230bedc5e639aed2e7b9cc5698726db1..219568034fa54ed121ede80961655e33dfb9d0e3` are selectively ported on top. This is not a complete re-import or an npm `sol-pi@0.1.1` release. It is maintained here as `@herbertgao/sol-pi`, not an official distribution of Pi or NVIDIA.
17
17
  >
18
18
  > The package is independently loadable and is bundled by `@herbertgao/pi-extensions`; its aggregate entry is covered by the collection smoke test.
19
19
 
@@ -49,6 +49,12 @@ The mechanisms share four rules:
49
49
  - **Preserve evidence.** Original observations remain available locally, and reducer failures leave the original result unchanged.
50
50
  - **Use Pi's runtime choices.** Authentication, provider URLs, the main model, and shell behavior remain under Pi's control.
51
51
 
52
+ ## Pi 1.x and codemode behavior
53
+
54
+ Action Fusion reports failed follow-up commands without losing the mutation's edit details, and inherits Pi's file-backed shell settings with project trust respected. Nested codemode calls do not count as independent model round-trips. Evidence-Preserving Reducer leaves nested tool results and their structured content unchanged. ObservationPack preserves message identity so Pi's mid-conversation system messages keep their positions and cached prefixes.
55
+
56
+ Online Context Compact declares `update_plan` to the model only, including in codemode-only mode. Codemode scripts cannot call it: plan boundaries must appear as direct tool results in the agent turn. Compaction uses Pi's effective token settings and context projection, does not count cache-warming replays as provider requests, and resumes a stopped task after a non-cancellation compaction failure before reporting that error. User cancellation does not schedule a continuation.
57
+
52
58
  ## Technical Details and Core Insights
53
59
 
54
60
  Read the [SoL-Pi blog](https://nvlabs.github.io/SoL-Pi/) for a deeper look at the technical details, design rationale, and core insights behind SoL-Pi, including how auto-research led to the four efficiency mechanisms and how they work.
@@ -12,6 +12,9 @@ SoL-Pi imports only public package exports:
12
12
  - native compaction events, `ExtensionContext.getContextUsage()`, and `ExtensionContext.compact()`
13
13
  - `ExtensionContext.model` and `ExtensionContext.modelRegistry`
14
14
  - the public session-manager methods exposed through `ExtensionContext`
15
+ - `SettingsManager` for trusted file-backed shell settings
16
+ - feature-detected `ExtensionAPI.getSettings()` and `buildSessionProjection()` on Pi 1.x
17
+ - tool `exposure` for model-only `update_plan` calls
15
18
 
16
19
  ## Action Fusion
17
20
 
@@ -31,7 +34,9 @@ Pi 1.x may return `Bash.isError` instead of throwing on a failed follow-up. Acti
31
34
 
32
35
  ## ObservationPack
33
36
 
34
- ObservationPack changes only the messages projected through the public `context` event. Stored session history remains intact. Original bytes and the JSONL ledger live under the session-derived SoL-Pi directory.
37
+ ObservationPack changes only the messages projected through the public `context` event. Pi passes `context` handlers a cloned copy of the conversation, so stored session history remains intact. ObservationPack replaces the content of those message objects in place and returns nothing. Since Pi 0.87, a handler that returns different message objects makes Pi merge every mid-conversation system message, such as prompt sections and tool-declaration deltas, into one leading system message, which breaks the provider's cached prefix on every later request. The in-place edit keeps those messages where they are on Pi 1.x and behaves the same on Pi 0.84.2.
38
+
39
+ Original bytes and the JSONL ledger live under the session-derived SoL-Pi directory.
35
40
 
36
41
  ## Evidence-Preserving Reducer
37
42
 
@@ -47,15 +52,15 @@ Online Context Compact uses ordinary public `context` and `before_provider_reque
47
52
 
48
53
  Before selecting or executing a boundary compaction, it also checks the optional `Symbol.for("pi-subagents:manager")` registry exposed by `pi-subagents`. A running top-level subagent, or an unreadable registry, suppresses that compaction rather than risking a context rewrite during delegated work. When the registry is absent, the check is a no-op.
49
54
 
50
- The native cut is selected from session entries, while removable-token savings are measured from the corresponding messages in the latest observed projection. ObservationPack placeholders are therefore priced at their projected size. Dropped messages, unseen additions, and ambiguous matches contribute no proven savings; the estimator never substitutes their raw byte counts or reruns context hooks to estimate them.
55
+ The native cut is estimated from Pi's canonical session projection when available (Pi 1.x), and from raw session entries on Pi 0.84.2. Removable-token savings are measured from corresponding messages in the latest observed extension projection. ObservationPack placeholders are therefore priced at their projected size, context edits are applied before choosing the cut, and retained system checkpoints are excluded from savings. Dropped messages, unseen additions, and ambiguous matches contribute no proven savings; the estimator never substitutes their raw byte counts or reruns context hooks. Pi's special recovery-omission suffix can allow a larger removable prefix than the public cut-point helper predicts; OCC conservatively underestimates savings in that case.
51
56
 
52
57
  Compaction preserves the current plan, request-horizon samples, and context-growth history. Every plan update uses the same step-ID/status comparison, including the first update after compaction. A boundary requires a previously registered unfinished step to become completed. Newly introduced completed IDs establish history without creating a boundary, so re-keyed completed snapshots do not retrigger compaction. An assistant must register a step before completing it to make that completion eligible for OCC. Economic compaction has a two-provider-request cooldown; context-window protection can override it. A new user task following a fully completed plan resets the request-horizon samples while preserving unpaid cache debt.
53
58
 
54
- Pi does not expose its active retained-tail compaction setting through the public extension context. The standalone extension therefore uses the Pi 0.85.1 default of 20,000 tokens for its economic estimate. Its programmatic factory accepts an explicit matching value for a non-default Pi setting.
59
+ On Pi builds whose `ExtensionAPI` has `getSettings()` (1.0.x), Online Context Compact reads Pi's effective `compaction.keepRecentTokens` and `compaction.reserveTokens`. A per-model `compaction.modelOverrides["<provider>/<id>"]` entry for the current `ctx.model` takes precedence, as in Pi. The reserve is used for window-pressure protection. On Pi 0.84.2 it uses the documented defaults of 20,000 retained-tail tokens and a 16,384-token reserve. An explicit `keepRecentTokens` passed to the programmatic factory overrides the retained tail on every version.
55
60
 
56
61
  Pi 0.85.1's `ExtensionContext.compact()` aborts the active agent before it summarizes, and `agent_settled` fires only once a whole run has drained every turn, retry, auto-compaction, and queued continuation. A plan boundary that selects compaction therefore saves its plan and progress state, calls `ExtensionContext.abort()` to stop the run, and runs compaction from the `agent_settled` that stop produces. The handler awaits the compaction's own `onComplete`/`onError` callbacks. On success, the extension sends a hidden reminder through public `ExtensionAPI.sendMessage()` with `triggerTurn: true`, so Pi starts a new turn against the compacted context and continues the current plan. The reminder asks it to preserve existing step IDs when updating progress; an immediate plan update is not required.
57
62
 
58
- A settlement barrier keeps the original `agent_settled` dispatch open until a synchronously triggered continuation settles. Print- and JSON-mode processes therefore complete the compact-and-continue sequence within the same Pi invocation; an outer driver does not need to resume the session or send `Continue working`. Successful compaction schedules a continuation. The exact native refusals `Nothing to compact (session too small)` and `Already compacted`, and Pi's explicit incomplete-summary token-cap error, also resume the interrupted task with the existing context. These skips are recorded as `sol-pi-online-context-compact-skipped` entries and shown as TUI warnings; they do not record a compaction or charge new cache debt. Plan-only turns cannot retry compaction until successful non-plan tool work or new user input occurs. Cancelling or exiting does not schedule a continuation. Other compaction errors still propagate.
63
+ A settlement barrier keeps the original `agent_settled` dispatch open until a synchronously triggered continuation settles. Print- and JSON-mode processes therefore complete the compact-and-continue sequence within the same Pi invocation; an outer driver does not need to resume the session or send `Continue working`. Successful compaction schedules a continuation. The exact native refusals `Nothing to compact (session too small)` and `Already compacted`, and Pi's explicit incomplete-summary token-cap error, also resume the interrupted task with the existing context. These skips are recorded as `sol-pi-online-context-compact-skipped` entries and shown as TUI warnings; they do not record a compaction or charge new cache debt. Plan-only turns cannot retry compaction until successful non-plan tool work or new user input occurs. Cancelling or exiting does not schedule a continuation. Other non-cancellation compaction errors schedule a hidden continuation before the failure propagates.
59
64
 
60
65
  Pi 0.85.1 does not return a promise from `ExtensionAPI.sendMessage()` and starts the requested turn synchronously, so it uses the extension's settlement barrier. Newer hosts can keep the context idle and defer the turn until settled handlers return; OCC returns control to such a host instead of waiting on the deferred turn or reporting a false start failure. A later-loaded third-party extension that performs long asynchronous work in its own `agent_settled` handler needs an integration test with that extension set.
61
66
 
@@ -67,6 +72,25 @@ Online Context Compact reads `ExtensionContext.getContextUsage()` for both the c
67
72
 
68
73
  The standalone entry passes `cacheWriteReadRatio` from `sol-pi.json` directly into Online Context Compact's economic check. It does not inspect model price metadata. Changing models during a session does not change the ratio; users who want a different decision policy update the configuration and start a new session.
69
74
 
75
+ ## Codemode
76
+
77
+ Pi 1.x codemode lets the model run a script that calls other tools through `ctx.executeTool()`. With `codemode.mode: "on"`, declared tools stay declared and are also callable from scripts. With `"only"`, they are hidden from the model and listed in the `codemode` tool description instead. Calls made from a script get the id `<codemode call id>/<n>`, and their results reach only the script, not the transcript. Every mechanism loads and runs in both modes:
78
+
79
+ | Mechanism | `codemode.mode: "on"` | `codemode.mode: "only"` |
80
+ |---|---|---|
81
+ | Action Fusion | Fused edit/write stay declared to the model and are also callable from scripts. | Fused edit/write are callable from scripts only. |
82
+ | ObservationPack | Large text results of direct tools and of `codemode` itself are packed. `obs_recall` is declared directly and callable from scripts. | `codemode` results are packed. `obs_recall` is listed in the `codemode` description and callable from scripts. |
83
+ | Evidence-Preserving Reducer | Reduces direct bash and fused edit/write results as before. Script calls are skipped. | No effect in normal operation: the model reaches bash, edit, and write through scripts, and script calls are skipped. It makes no model calls. |
84
+ | Online Context Compact | `update_plan` stays declared to the model and is not callable from scripts. | Same as `"on"`. |
85
+
86
+ **Action Fusion.** Scripts call `tools.edit` and `tools.write`; the `then_run` parameter appears in their script declarations. Edit and write declare no output schema, so following codemode's rule a successful call resolves to the combined text, including `[then_run:succeeded]` and the command output. A failed command (`[then_run:failed]`) or a failed mutation (`[then_run:skipped]`) rejects with an `Error` whose message holds that text. The file change is kept, so scripts that run `then_run` should use `try`/`catch` or `Promise.allSettled()`. Codemode lists script calls inside its own TUI row, so they show neither the Action Fusion banner nor the savings notice: a script already chains tools inside one model request.
87
+
88
+ **ObservationPack.** A `codemode` result is an ordinary tool result. Successful text-only results over 10 KiB are sent in full for two provider requests and then replaced by a placeholder naming `tool: codemode`. Tool calls made inside a script are not in the transcript and are never packed; only the script's output is. `tools.obs_recall({ id, offset })` resolves to the recall text, a header followed by the original bytes. The placeholder still says to call `obs_recall`; its wording is unchanged so placeholder bytes stay stable.
89
+
90
+ **Evidence-Preserving Reducer.** Because script calls are skipped, a script calling `tools.bash` gets Pi's own result: the call resolves to Pi's structured value `{ output, exit_code, truncated, full_output_path?, wall_time_seconds }`, and a non-zero exit resolves rather than rejects. A timeout, an abort, or a missing exit code rejects. The `codemode` result itself is never reduced.
91
+
92
+ **Online Context Compact.** `update_plan` is registered with exposure `"model-only"`: a script call would get a nested id that no turn reports as a tool result, so its plan boundary could never compact. The model calls `update_plan` directly in both modes, and plan boundaries compact and continue as described above.
93
+
70
94
  ## Interactive TUI
71
95
 
72
96
  The lightning savings treatment uses Pi 0.85.1's public `renderCall`,
@@ -46,7 +46,7 @@ This preflight does not make every valid SoL-Pi configuration all-enabled. Witho
46
46
  - `evidencePreservingReducer`: registers a `tool_result` handler and delegates long diagnostic-log reduction to the configured reducer provider/model.
47
47
  - `evidencePreservingReducerProvider`: provider namespace used to resolve the reducer model through Pi's model registry.
48
48
  - `evidencePreservingReducerModel`: model id used for Evidence-Preserving Reducer.
49
- - `onlineContextCompact`: registers `update_plan` and boundary-driven native compaction after the other SoL-Pi context transformers.
49
+ - `onlineContextCompact`: registers `update_plan` and boundary-driven native compaction after the other SoL-Pi context transformers. On Pi 1.x, `update_plan` is declared to the model only and cannot be called from codemode scripts.
50
50
  - `cacheWriteReadRatio`: supplies the single economic decision ratio used by Online Context Compact.
51
51
 
52
52
  ## Evidence-Preserving Reducer runtime inputs
@@ -57,18 +57,31 @@ The release entry supplies the run label and session-derived storage. It uses on
57
57
 
58
58
  ## Online Context Compact runtime inputs
59
59
 
60
- The release entry uses two runtime inputs:
60
+ The release entry uses these runtime inputs:
61
61
 
62
62
  - **Context window** — from `ExtensionContext.getContextUsage()`, used for window-pressure protection.
63
+ - **Compaction settings** — on Pi 1.x, the retained tail and the window-protection reserve follow Pi's effective `compaction.keepRecentTokens` and `compaction.reserveTokens`, including a `compaction.modelOverrides["<provider>/<id>"]` entry for the current model. Pi 0.84.2 does not expose its settings to extensions, so SoL-Pi uses Pi's defaults of 20,000 and 16,384 tokens there.
63
64
  - **Cache write/read ratio** — from `cacheWriteReadRatio` in the effective `sol-pi.json`. The value remains fixed for the session and is not recomputed when the model changes. It drives one runtime decision and is not a cost report.
64
65
 
65
- The configured ratio stays fixed for the loaded extension. The mechanism stores its current plan, progress summaries, request horizon, context growth, and compaction debt as versioned custom entries in Pi's session log. After a successful compaction it sends one hidden, generic message with `triggerTurn: true`, which starts a new turn and asks the assistant to continue the current plan, preserving existing step IDs when updating progress. A settlement barrier keeps print and JSON modes in the same Pi invocation until that continuation settles, so callers do not need to resume the session or inject `Continue working`. On Pi 1.x, OCC returns to the host to let its deferred continuation run after settled handlers finish. Recoverable native refusals (session too small, already compacted, or an incomplete summary at the token cap) resume with the unchanged context and no new cache debt; successful non-plan tool work or new user input is required before another plan-only attempt. Economic compaction has a two-provider-request cooldown, but window protection overrides it. Cancelling or exiting does not schedule an automatic continuation. The mechanism creates no separate Online Context Compact files. The programmatic factory exposes only a matching retained-tail value for installations whose Pi compaction setting differs from the default.
66
+ The configured ratio stays fixed for the loaded extension. The mechanism stores its current plan, progress summaries, request horizon, context growth, and compaction debt as versioned custom entries in Pi's session log. After a successful compaction it sends one hidden, generic message with `triggerTurn: true`, which starts a new turn and asks the assistant to continue the current plan, preserving existing step IDs when updating progress. Newly introduced completed steps are recorded as history and do not create completion boundaries. Economic compaction has a two-provider-request cooldown; context-window protection can override it. Known native refusals and incomplete-summary token-cap failures are recorded as skips, resume the task, and block plan-only compaction retries until successful non-plan tool work or new user input. If the compaction fails for any other non-cancellation reason, it sends a hidden message that tells the assistant to continue from the current plan, then reports the error. Print and JSON modes finish that continuation in the same Pi invocation, so callers do not need to resume the session or inject `Continue working`. Cancelling the compaction or exiting Pi does not schedule an automatic continuation. The mechanism creates no separate Online Context Compact files. The programmatic factory accepts an explicit retained-tail value, which overrides Pi's setting.
66
67
 
67
68
  ## Pi integration
68
69
 
69
70
  SoL-Pi reads no dedicated environment variables. Evidence-Preserving Reducer resolves its configured reducer provider/model through `ExtensionContext.modelRegistry` and uses Pi-managed authentication. If the configured reducer model is unavailable or the nested model call fails, the original tool result continues unchanged.
70
71
 
71
- SoL-Pi does not configure shell paths, command prefixes, storage paths, run IDs, provider URLs, reasoning levels, timeouts, or per-mechanism enable flags through environment variables. Apart from the EPR reducer provider/model route in `sol-pi.json`, model selection remains with Pi. Action Fusion uses Pi's default shell behavior. Persistent artifacts are derived from Pi's session directory and session ID.
72
+ SoL-Pi does not configure shell paths, command prefixes, storage paths, run IDs, provider URLs, reasoning levels, timeouts, or per-mechanism enable flags through environment variables. Apart from the EPR reducer provider/model route in `sol-pi.json`, model selection remains with Pi. Action Fusion uses Pi's built-in Bash execution, with `shellPath` and `shellCommandPrefix` inherited from Pi's file-backed settings at extension startup. Global settings apply everywhere; project settings override them only after project trust. Malformed settings stop initialization rather than silently selecting a different shell. Persistent artifacts are derived from Pi's session directory and session ID.
73
+
74
+ For native Windows with Git for Windows installed outside the default directories, configure its Bash executable in Pi's `settings.json` (not `sol-pi.json`), for example:
75
+
76
+ ```json
77
+ {
78
+ "shellPath": "D:/Tools/Git/bin/bash.exe"
79
+ }
80
+ ```
81
+
82
+ Replace that example path with your actual Git Bash installation. `then_run.command` remains a Bash command even if the model's ordinary command tool is PowerShell; Git Bash is a native Windows program and does not require WSL. Do not point `shellPath` at `powershell.exe`, because the built-in Bash tool invokes it with Bash arguments. Restart the extension after changing shell settings.
83
+
84
+ This bridge reads file-backed settings, not SDK/CLI-only in-memory overrides. Embedded runtimes can pass explicit `bashOptions` to `createActionFusionExtension`; programmatic execution overrides remain supported.
72
85
 
73
86
  ## Trust
74
87
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@herbertgao/sol-pi",
3
- "version": "0.4.1",
3
+ "version": "0.4.2",
4
4
  "description": "Token-efficient context and tool extensions for Pi, maintained from NVlabs/SoL-Pi.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -25,18 +25,14 @@ import {
25
25
  type EditToolDetails,
26
26
  type EditToolOptions,
27
27
  type ExtensionAPI,
28
+ type ExtensionContext,
28
29
  type ExtensionFactory,
29
30
  type WriteToolOptions,
30
31
  } from "@earendil-works/pi-coding-agent";
31
32
  import { Type } from "typebox";
32
33
  import { resolveToolPath } from "./file-queue.ts";
33
- import { renderSolPiTool, showSolPiSavings } from "../../tui.ts";
34
- import {
35
- createThenRunSchema,
36
- executeMutationThenRun,
37
- THEN_RUN_SUCCEEDED,
38
- type ThenRunInput,
39
- } from "./then-run.ts";
34
+ import { isNestedToolCallId, renderSolPiTool, showSolPiSavings } from "../../tui.ts";
35
+ import { createThenRunSchema, runFusedMutation, type ThenRunInput, type ThenRunStatus } from "./then-run.ts";
40
36
 
41
37
  const EDIT_THEN_RUN_DESCRIPTION =
42
38
  "Command to run next on this file after the edit succeeds — e.g. run, build, start/restart, install, or check it; optional timeout in seconds. Skipped if the edit fails; a non-zero exit is reported but keeps the edit.";
@@ -80,6 +76,26 @@ function hasExternalToolOwner(pi: ExtensionAPI, name: string): boolean {
80
76
  }
81
77
  }
82
78
 
79
+ /**
80
+ * Announce the avoided round-trip only when the command actually succeeded,
81
+ * as reported by the fusion itself, never by matching command output. Calls
82
+ * from a codemode script (`<parent id>/<n>`) save no model round-trip of their
83
+ * own: the script already chains tools inside one model call.
84
+ */
85
+ function announceSavings(status: ThenRunStatus, toolCallId: string, ctx: ExtensionContext): void {
86
+ if (status !== "succeeded" || isNestedToolCallId(toolCallId)) return;
87
+ showSolPiSavings(ctx, "Action Fusion", "1 model round-trip avoided");
88
+ }
89
+
90
+ /**
91
+ * Show the savings banner on a fused call unless it settled as an error: a
92
+ * failed or skipped command avoided no round-trip. Pi redraws the call row
93
+ * with the settled `isError` as well, so both renderers drop it together.
94
+ */
95
+ function showsSavingsBanner(thenRun: unknown, context: { readonly isError?: boolean }): boolean {
96
+ return Boolean(thenRun) && !context.isError;
97
+ }
98
+
83
99
  export function createActionFusionExtension(options: ActionFusionOptions = {}): ExtensionFactory {
84
100
  const baseEdit = memoizeByCwd((cwd: string) => createEditToolDefinition(cwd, options.editOptions));
85
101
  const baseWrite = memoizeByCwd((cwd: string) => createWriteToolDefinition(cwd, options.writeOptions));
@@ -103,7 +119,7 @@ export function createActionFusionExtension(options: ActionFusionOptions = {}):
103
119
  parameters: editParameters,
104
120
  async execute(toolCallId, input, signal, onUpdate, ctx) {
105
121
  const { then_run, ...editInput } = input as typeof input & { then_run?: ThenRunInput };
106
- const result = await executeMutationThenRun({
122
+ const { result, status } = await runFusedMutation({
107
123
  toolCallId,
108
124
  absolutePath: resolveToolPath(ctx.cwd, input.path),
109
125
  thenRun: then_run,
@@ -112,21 +128,18 @@ export function createActionFusionExtension(options: ActionFusionOptions = {}):
112
128
  ctx,
113
129
  mutate: () => baseEdit(ctx.cwd).execute(toolCallId, editInput, signal, onUpdate, ctx),
114
130
  });
115
- if (
116
- then_run &&
117
- result.content.some((block) => block.type === "text" && block.text.includes(THEN_RUN_SUCCEEDED))
118
- ) {
119
- showSolPiSavings(ctx, "Action Fusion", "1 model round-trip avoided");
120
- }
131
+ announceSavings(status, toolCallId, ctx);
121
132
  return result;
122
133
  },
123
134
  renderCall: (args, theme, context) => {
124
135
  const base = baseEdit(context.cwd).renderCall!(args, theme, context);
125
- return args.then_run ? renderSolPiTool(theme, "Action Fusion", "1 model round-trip avoided", base) : base;
136
+ return showsSavingsBanner(args.then_run, context)
137
+ ? renderSolPiTool(theme, "Action Fusion", "1 model round-trip avoided", base)
138
+ : base;
126
139
  },
127
140
  renderResult: (result, resultOptions, theme, context) => {
128
141
  const base = baseEdit(context.cwd).renderResult!(result, resultOptions, theme, context);
129
- return context.args.then_run
142
+ return showsSavingsBanner(context.args.then_run, context)
130
143
  ? renderSolPiTool(theme, "Action Fusion", "1 model round-trip avoided", base)
131
144
  : base;
132
145
  },
@@ -147,7 +160,7 @@ export function createActionFusionExtension(options: ActionFusionOptions = {}):
147
160
  }),
148
161
  async execute(toolCallId, input, signal, onUpdate, ctx) {
149
162
  const { then_run, ...writeInput } = input as typeof input & { then_run?: ThenRunInput };
150
- const result = await executeMutationThenRun({
163
+ const { result, status } = await runFusedMutation({
151
164
  toolCallId,
152
165
  absolutePath: resolveToolPath(ctx.cwd, input.path),
153
166
  thenRun: then_run,
@@ -173,21 +186,18 @@ export function createActionFusionExtension(options: ActionFusionOptions = {}):
173
186
  return write.execute(toolCallId, writeInput, signal, onUpdate, ctx);
174
187
  },
175
188
  });
176
- if (
177
- then_run &&
178
- result.content.some((block) => block.type === "text" && block.text.includes(THEN_RUN_SUCCEEDED))
179
- ) {
180
- showSolPiSavings(ctx, "Action Fusion", "1 model round-trip avoided");
181
- }
189
+ announceSavings(status, toolCallId, ctx);
182
190
  return result;
183
191
  },
184
192
  renderCall: (args, theme, context) => {
185
193
  const base = baseWrite(context.cwd).renderCall!(args, theme, context);
186
- return args.then_run ? renderSolPiTool(theme, "Action Fusion", "1 model round-trip avoided", base) : base;
194
+ return showsSavingsBanner(args.then_run, context)
195
+ ? renderSolPiTool(theme, "Action Fusion", "1 model round-trip avoided", base)
196
+ : base;
187
197
  },
188
198
  renderResult: (result, resultOptions, theme, context) => {
189
199
  const base = baseWrite(context.cwd).renderResult!(result, resultOptions, theme, context);
190
- return context.args.then_run
200
+ return showsSavingsBanner(context.args.then_run, context)
191
201
  ? renderSolPiTool(theme, "Action Fusion", "1 model round-trip avoided", base)
192
202
  : base;
193
203
  },
@@ -5,7 +5,7 @@
5
5
  import { createHash } from "node:crypto";
6
6
  import { readFile } from "node:fs/promises";
7
7
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
8
- import { type BashToolOptions, createBashToolDefinition, type ExtensionToolContext } from "@earendil-works/pi-coding-agent";
8
+ import { type BashToolOptions, createBashToolDefinition, type ToolDefinition } from "@earendil-works/pi-coding-agent";
9
9
  import { Type } from "typebox";
10
10
  import { withFusedFileQueue } from "./file-queue.ts";
11
11
 
@@ -13,6 +13,18 @@ export const THEN_RUN_SUCCEEDED = "[then_run:succeeded]";
13
13
  export const THEN_RUN_FAILED = "[then_run:failed]";
14
14
  export const THEN_RUN_SKIPPED = "[then_run:skipped]";
15
15
 
16
+ /**
17
+ * The context Pi passes to tool `execute()`: `ExtensionContext` before Pi 0.99,
18
+ * `ExtensionToolContext` since then. Derived so it compiles against both.
19
+ */
20
+ type ToolExecuteContext = Parameters<ToolDefinition["execute"]>[4];
21
+
22
+ /**
23
+ * What happened to the follow-up command of a returned fused result. Thrown
24
+ * results carry the status in their message instead.
25
+ */
26
+ export type ThenRunStatus = "none" | "succeeded" | "failed" | "skipped";
27
+
16
28
  export interface ThenRunInput {
17
29
  command: string;
18
30
  timeout?: number;
@@ -41,10 +53,10 @@ function resultText(result: AgentToolResult<unknown>): string {
41
53
  .join("\n");
42
54
  }
43
55
 
56
+ const THEN_RUN_SKIPPED_REASON = "The file mutation did not complete successfully; the command was not run.";
57
+
44
58
  function thenRunSkippedError(error: unknown): Error {
45
- return new Error(
46
- `${errorText(error)}\n\n${THEN_RUN_SKIPPED} The file mutation did not complete successfully; the command was not run.`,
47
- );
59
+ return new Error(`${errorText(error)}\n\n${THEN_RUN_SKIPPED} ${THEN_RUN_SKIPPED_REASON}`);
48
60
  }
49
61
 
50
62
  async function fileSha256(path: string): Promise<string> {
@@ -75,7 +87,35 @@ export async function assertUnchangedBeforeCommand(
75
87
  * fused mutation of the same file cannot interleave. Pi's built-in mutation
76
88
  * tool keeps its own queue; the two queues are not nested.
77
89
  */
78
- export async function executeMutationThenRun<TDetails>({
90
+ export async function executeMutationThenRun<TDetails>(
91
+ options: FusedMutationOptions<TDetails>,
92
+ ): Promise<AgentToolResult<TDetails>> {
93
+ return (await runFusedMutation(options)).result;
94
+ }
95
+
96
+ interface FusedMutationOptions<TDetails> {
97
+ toolCallId: string;
98
+ absolutePath: string;
99
+ thenRun: ThenRunInput | undefined;
100
+ mutate: () => Promise<AgentToolResult<TDetails>>;
101
+ bashOptions: BashToolOptions | undefined;
102
+ signal: AbortSignal | undefined;
103
+ ctx: ToolExecuteContext;
104
+ }
105
+
106
+ /**
107
+ * {@link executeMutationThenRun} plus the status of the follow-up command, so
108
+ * callers never have to infer success from text the command itself printed.
109
+ *
110
+ * A failing command is reported in one of two shapes, depending on Pi's bash:
111
+ * before Pi 0.99 it throws on a non-zero exit, and so do later versions on a
112
+ * timeout, an abort, or a missing exit code. Those failures throw an error
113
+ * that keeps the mutation output. Since Pi 0.99 a non-zero exit comes back as
114
+ * an `isError` result; it is returned as an `isError` result that keeps the
115
+ * mutation's details, so the edit diff still renders. Both carry
116
+ * `[then_run:failed]` followed by the command output.
117
+ */
118
+ export async function runFusedMutation<TDetails>({
79
119
  toolCallId,
80
120
  absolutePath,
81
121
  thenRun,
@@ -83,15 +123,7 @@ export async function executeMutationThenRun<TDetails>({
83
123
  bashOptions,
84
124
  signal,
85
125
  ctx,
86
- }: {
87
- toolCallId: string;
88
- absolutePath: string;
89
- thenRun: ThenRunInput | undefined;
90
- mutate: () => Promise<AgentToolResult<TDetails>>;
91
- bashOptions: BashToolOptions | undefined;
92
- signal: AbortSignal | undefined;
93
- ctx: ExtensionToolContext;
94
- }): Promise<AgentToolResult<TDetails>> {
126
+ }: FusedMutationOptions<TDetails>): Promise<{ result: AgentToolResult<TDetails>; status: ThenRunStatus }> {
95
127
  return withFusedFileQueue(absolutePath, async () => {
96
128
  let mutationResult: AgentToolResult<TDetails>;
97
129
  try {
@@ -104,26 +136,63 @@ export async function executeMutationThenRun<TDetails>({
104
136
  }
105
137
 
106
138
  if (thenRun === undefined) {
107
- return mutationResult;
139
+ return { result: mutationResult, status: "none" };
140
+ }
141
+ if (isErrorResult(mutationResult)) {
142
+ return {
143
+ result: appendThenRunText(mutationResult, `${THEN_RUN_SKIPPED} ${THEN_RUN_SKIPPED_REASON}`, true),
144
+ status: "skipped",
145
+ };
108
146
  }
109
147
 
110
148
  await assertUnchangedBeforeCommand(absolutePath);
111
149
  const bash = createBashToolDefinition(ctx.cwd, bashOptions);
150
+ let bashResult: AgentToolResult<unknown>;
112
151
  try {
113
- // pi-lens-ignore: sql-injection
114
- const bashResult = await bash.execute(`${toolCallId}:then_run`, thenRun, signal, undefined, ctx);
115
- const output = resultText(bashResult);
116
- if (bashResult.isError) throw new Error(output);
117
- return {
118
- ...mutationResult,
119
- content: [
120
- ...mutationResult.content,
121
- { type: "text", text: output ? `${THEN_RUN_SUCCEEDED}\n${output}` : THEN_RUN_SUCCEEDED },
122
- ],
123
- };
152
+ bashResult = await bash.execute(`${toolCallId}:then_run`, thenRun, signal, undefined, ctx);
124
153
  } catch (error) {
125
154
  const mutationOutput = resultText(mutationResult);
126
155
  throw new Error([mutationOutput, THEN_RUN_FAILED, errorText(error)].filter(Boolean).join("\n\n"), { cause: error });
127
156
  }
157
+ const output = resultText(bashResult);
158
+ if (isErrorResult(bashResult)) {
159
+ return {
160
+ result: appendThenRunText(mutationResult, output ? `${THEN_RUN_FAILED}\n${output}` : THEN_RUN_FAILED, true),
161
+ status: "failed",
162
+ };
163
+ }
164
+ return {
165
+ result: appendThenRunText(
166
+ mutationResult,
167
+ output ? `${THEN_RUN_SUCCEEDED}\n${output}` : THEN_RUN_SUCCEEDED,
168
+ false,
169
+ ),
170
+ status: "succeeded",
171
+ };
128
172
  });
129
173
  }
174
+
175
+ /** Pi 0.99+ results may report a failure with `isError` instead of throwing; 0.84 has no such field. */
176
+ type MaybeErrorResult<TDetails> = AgentToolResult<TDetails> & { isError?: boolean };
177
+
178
+ function isErrorResult(result: AgentToolResult<unknown>): boolean {
179
+ return (result as MaybeErrorResult<unknown>).isError === true;
180
+ }
181
+
182
+ /**
183
+ * Add the follow-up report to the mutation result. Only the mutation's own
184
+ * fields are kept: bash `details` and `structuredContent` describe a different
185
+ * tool and would confuse the edit and write renderers.
186
+ */
187
+ function appendThenRunText<TDetails>(
188
+ mutationResult: AgentToolResult<TDetails>,
189
+ text: string,
190
+ isError: boolean,
191
+ ): AgentToolResult<TDetails> {
192
+ const result: MaybeErrorResult<TDetails> = {
193
+ ...mutationResult,
194
+ content: [...mutationResult.content, { type: "text", text }],
195
+ };
196
+ if (isError) result.isError = true;
197
+ return result;
198
+ }