@tea-agent/loop-agent 0.51.0 → 0.52.0-next.10

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 (234) hide show
  1. package/CHANGELOG.md +123 -5
  2. package/dist/build-stamp.json +3 -3
  3. package/dist/cli/command-definitions.js +1 -75
  4. package/dist/cli/help.js +1 -1
  5. package/dist/cli/program.js +1 -28
  6. package/dist/commands/init-accepted-merge.js +46 -0
  7. package/dist/commands/init-upgrade.js +115 -2
  8. package/dist/commands/init.js +79 -12
  9. package/dist/executors/pi-sdk-executor.js +3 -3
  10. package/dist/governance/path-guard.js +2 -0
  11. package/dist/records/harvest.js +1 -1
  12. package/dist/shared/git-progress.js +3 -0
  13. package/dist/shared/operator/capabilities.js +0 -122
  14. package/dist/shared/pi-context-pressure/checkpoint.js +94 -24
  15. package/dist/shared/pi-context-pressure/compaction-policy.js +152 -66
  16. package/dist/shared/pi-context-pressure/extension.js +25 -8
  17. package/dist/shared/pi-context-pressure/index.js +1 -1
  18. package/dist/shared/pi-context-pressure/telemetry.js +10 -0
  19. package/dist/shared/update/npm-client.js +14 -3
  20. package/dist/task/config-types.js +5 -10
  21. package/dist/task/delegate.js +1 -1
  22. package/dist/task/read-model.js +0 -4
  23. package/dist/task/runtime.js +0 -1
  24. package/dist/task/worktree.js +1 -1
  25. package/dist/worker/console/chat/api-workbench-core.js +17 -6
  26. package/dist/worker/console/chat/api-workbench.js +2 -0
  27. package/dist/worker/console/chat/assistant-content.js +21 -3
  28. package/dist/worker/console/chat/chat-event-projection.js +6 -0
  29. package/dist/worker/console/chat/chat-event-store.js +32 -2
  30. package/dist/worker/console/chat/chat-references.js +4 -0
  31. package/dist/worker/console/chat/compaction-errors.js +14 -2
  32. package/dist/worker/console/chat/context-insights.js +41 -4
  33. package/dist/worker/console/chat/context-usage.js +4 -1
  34. package/dist/worker/console/chat/pi-runtime/custom-tools/apiworkbench-tools.js +65 -3
  35. package/dist/worker/console/chat/pi-runtime/custom-tools/browser-tools.js +2 -2
  36. package/dist/worker/console/chat/pi-runtime/extension-bindings.js +39 -0
  37. package/dist/worker/console/chat/pi-runtime/sdk-bindings.js +4 -0
  38. package/dist/worker/console/chat/pi-runtime.js +389 -191
  39. package/dist/worker/console/chat/repo-browser.js +5 -2
  40. package/dist/worker/console/chat/repo-preview-kind.js +16 -6
  41. package/dist/worker/console/chat/routes.js +299 -25
  42. package/dist/worker/console/chat/scheduled-goal-request.js +1 -1
  43. package/dist/worker/console/chat/subagents/jobs.js +115 -4
  44. package/dist/worker/console/chat/terminal-sessions.js +52 -6
  45. package/dist/worker/console/chat/tool-exposure-catalog.js +1 -1
  46. package/dist/worker/console/chat/tool-presentation.js +17 -10
  47. package/dist/worker/console/chat/tool-preview.js +22 -0
  48. package/dist/worker/console/chat/turn-process.js +49 -0
  49. package/dist/worker/console/chat/vcp-prompt.js +14 -9
  50. package/dist/worker/console/chat/workspace-changes.js +17 -0
  51. package/dist/worker/console/console-update-runtime.js +5 -1
  52. package/dist/worker/console/operator-actions.js +7 -6
  53. package/dist/worker/console/operator-user-error.js +5 -1
  54. package/dist/worker/console/pi-compaction-settings.js +220 -0
  55. package/dist/worker/console/routes.js +1 -1
  56. package/dist/worker/console/server.js +148 -6
  57. package/dist/worker/console/static/assets/FilePreviewDocx-ybM3ZqSl.js +9 -0
  58. package/dist/worker/console/static/assets/abnfDiagram-N423BO3Z-CT26sIgH.js +1 -0
  59. package/dist/worker/console/static/assets/{arc-Bkf_oc0_.js → arc-CPwLqDB0.js} +1 -1
  60. package/dist/worker/console/static/assets/architectureDiagram-T3A2C74G-CzTSMPU_.js +36 -0
  61. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-D62uVvbI.js → blockDiagram-VBNYF7ZC-BfgbtJLH.js} +1 -1
  62. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-Iq0Y8Afx.js → c4Diagram-5PPSVZJV-B9pTjB8U.js} +1 -1
  63. package/dist/worker/console/static/assets/channel-DtYRMDck.js +1 -0
  64. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-D1TxRE3k.js → chunk-2GRJ4B5K-xORV8QsC.js} +1 -1
  65. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-BE-DHkAO.js → chunk-2Q5K7J3B-BzpYWAHK.js} +1 -1
  66. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-t0iYO8Cc.js → chunk-5RXB4S5H-D8zcRP6c.js} +1 -1
  67. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-Clo2nExi.js → chunk-5VM5RSS4-DVEXxzQJ.js} +1 -1
  68. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-C7bSpo-3.js → chunk-6Q2QTUOP-CKZOJU2z.js} +1 -1
  69. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-DorZaymh.js → chunk-GF5L2VYU-Cgx34Dj8.js} +1 -1
  70. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-Ch_4HvyJ.js → chunk-JWPE2WC7-ehcSKOcx.js} +1 -1
  71. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-yaSoFe-3.js → chunk-KBJHAD2P-CiY9emCG.js} +1 -1
  72. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-QpjaXecS.js → chunk-RYQCIY6F-Bk9X-ksQ.js} +1 -1
  73. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-B3t6cycg.js → chunk-XXDRQBXY-DC0xXfHy.js} +1 -1
  74. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-DyesHbs5.js +1 -0
  75. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-DyesHbs5.js +1 -0
  76. package/dist/worker/console/static/assets/cose-bilkent-JH36ORCC-C_EVg5l9.js +1 -0
  77. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-CP8LtrOl.js → cynefin-VYW2F7L2-BIFL8KrA.js} +1 -1
  78. package/dist/worker/console/static/assets/cynefinDiagram-MW4NZA55-DjtUYOlE.js +62 -0
  79. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-BK0ua9V8.js → dagre-VZM6K2ZE-D2aN2V9t.js} +1 -1
  80. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-t9-HP13j.js → diagram-7IWD3JNH-D_twhmFi.js} +1 -1
  81. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-L5Sg9jMD.js → diagram-B4RE2ZJO-ChzncqLV.js} +1 -1
  82. package/dist/worker/console/static/assets/diagram-LBJQPF4R-B6LO-bF2.js +24 -0
  83. package/dist/worker/console/static/assets/diagram-Q27KOJAE-GrzM7AFc.js +24 -0
  84. package/dist/worker/console/static/assets/diagram-UB23O5K3-Bv-lntaq.js +41 -0
  85. package/dist/worker/console/static/assets/docx-preview-CAbT0VNs.js +23 -0
  86. package/dist/worker/console/static/assets/docxPreview-D_T4B7qe.js +1 -0
  87. package/dist/worker/console/static/assets/ebnfDiagram-BXEA7PRR-BvD2jkO_.js +1 -0
  88. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-CNOuj3BO.js → erDiagram-JOGREHBK-BirPCcmA.js} +1 -1
  89. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-h_Cyayai.js → flowDiagram-UKHOOZJN-Chu1YnGQ.js} +1 -1
  90. package/dist/worker/console/static/assets/ganttDiagram-PKOTCBZU-Djn17xhB.js +292 -0
  91. package/dist/worker/console/static/assets/gitGraphDiagram-DS77QQ5N-Bx1qbGHx.js +106 -0
  92. package/dist/worker/console/static/assets/infoDiagram-6WML65LV-D-TLMqmb.js +2 -0
  93. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-DAdf5lHp.js → ishikawaDiagram-WSZJBQD7-DbJoh-6T.js} +1 -1
  94. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-BQbGtg66.js → journeyDiagram-NVQOT4AX-DsyokZ6e.js} +1 -1
  95. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-CetLubYc.js → kanban-definition-27J2QSJJ-DlzXTxic.js} +1 -1
  96. package/dist/worker/console/static/assets/{linear-DLZOjaVz.js → linear-ClnZn3vw.js} +1 -1
  97. package/dist/worker/console/static/assets/main-D-ZQ4gLb.css +1 -0
  98. package/dist/worker/console/static/assets/main-fc3P1HID.js +645 -0
  99. package/dist/worker/console/static/assets/{mermaid.core-B_xZl_gM.js → mermaid.core-DqSlcvbf.js} +5 -5
  100. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-Dzo3dzp0.js → mindmap-definition-FAOFIHXS-CSFbzpiX.js} +1 -1
  101. package/dist/worker/console/static/assets/pegDiagram-VL7TDLO6-DK80yQqe.js +1 -0
  102. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-Cp3YrVzQ.js → pieDiagram-7S7Q4E2Y-DWX7SFGb.js} +1 -1
  103. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-4tI5mUgW.js → quadrantDiagram-CIZ2JOQS-BEPPhtXs.js} +1 -1
  104. package/dist/worker/console/static/assets/railroadDiagram-AXF67PYL-Ck_s6fQn.js +1 -0
  105. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-DY-0JqdT.js → requirementDiagram-LRYGKXZP-CYig27Rj.js} +1 -1
  106. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-DuJIzRKC.js → sankeyDiagram-W5VNT64P-u-0aSx5s.js} +1 -1
  107. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-BTbVJ85l.js → sequenceDiagram-SI44F4Z6-NsEJI9sM.js} +1 -1
  108. package/dist/worker/console/static/assets/{sheet-workbook-BPPh1uLw.js → sheet-workbook-kZ_HK4Sg.js} +2 -2
  109. package/dist/worker/console/static/assets/sizeCapture-X5ZJPWSS-8vneVM5U.js +1 -0
  110. package/dist/worker/console/static/assets/stateDiagram-OKZ733FA-CMIobUBh.js +1 -0
  111. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Bd0pHHKP.js +1 -0
  112. package/dist/worker/console/static/assets/swimlanes-SLNWSIFB-D4Qzt6ug.js +2 -0
  113. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-BzmSZnl_.js +8 -0
  114. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-GR6lxokn.js → timeline-definition-Z64GVDOM-DMb1LpED.js} +1 -1
  115. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-DEkwyzsF.js → vennDiagram-T6HMQDX7-C_9eFOs3.js} +1 -1
  116. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-W5jnvEJ3.js → wardleyDiagram-T6FBY63Y-DJYMe3uT.js} +1 -1
  117. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-cqsloioo.js → xychartDiagram-ELKLHX3M-Cv_1Mi3u.js} +1 -1
  118. package/dist/worker/console/static/docx-preview.html +25 -0
  119. package/dist/worker/console/static/index.html +3 -2
  120. package/dist/worker/console/static/vcp/fonts/README.md +28 -0
  121. package/dist/worker/console/static/vcp/vendor/vcp-engine-v1.js +4 -4
  122. package/dist/worker/console/static-src/operator-chat/StateDot.js +17 -0
  123. package/dist/worker/console/static-src/operator-chat/changed-file-diff.js +15 -0
  124. package/dist/worker/console/static-src/operator-chat/chat-font-size.js +90 -0
  125. package/dist/worker/console/static-src/operator-chat/chat-session-order.js +96 -0
  126. package/dist/worker/console/static-src/operator-chat/chat-sse-events.js +8 -1
  127. package/dist/worker/console/static-src/operator-chat/compaction-message.js +4 -0
  128. package/dist/worker/console/static-src/operator-chat/details-rail-surfaces.js +2 -0
  129. package/dist/worker/console/static-src/operator-chat/file-touch.js +107 -0
  130. package/dist/worker/console/static-src/operator-chat/format-file-size.js +26 -0
  131. package/dist/worker/console/static-src/operator-chat/open-preview-in-browser.js +44 -0
  132. package/dist/worker/console/static-src/operator-chat/reference-display.js +7 -1
  133. package/dist/worker/console/static-src/operator-chat/tasks-auto-open.js +100 -0
  134. package/dist/worker/console/static-src/operator-chat/tasks-layout-tween.js +103 -0
  135. package/dist/worker/console/static-src/operator-chat/tasks-model.js +657 -0
  136. package/dist/worker/console/static-src/operator-chat/tasks-view-glide.js +96 -0
  137. package/dist/worker/console/static-src/operator-chat/turn-group-equality.js +1 -0
  138. package/dist/worker/console/static-src/operator-chat/use-auto-animate.js +61 -0
  139. package/dist/worker/console/static-src/operator-chat/useChatSessions.js +194 -47
  140. package/dist/worker/console/static-src/operator-chat/useChatStream.js +4 -0
  141. package/dist/worker/console/static-src/operator-chat/useChatThread.js +18 -0
  142. package/dist/worker/console/static-src/operator-chat/useRepoBrowser.js +111 -21
  143. package/dist/worker/console/static-src/operator-chat/useRuntimeControls.js +91 -47
  144. package/dist/worker/console/static-src/operator-chat/useVcpPreferences.js +1 -1
  145. package/dist/worker/console/static-src/operator-chat/user-turn-anchors-merge.js +50 -0
  146. package/dist/worker/console/static-src/operator-chat/vcp-fonts.js +180 -22
  147. package/dist/worker/console/static-src/operator-chat/vcp-frame.js +3 -3
  148. package/dist/worker/console/static-src/shell/console-update-progress.js +16 -0
  149. package/dist/worker/console/static-src/shell/console-update-reload.js +4 -1
  150. package/dist/worker/console/static-src/shell/workspace-route.js +0 -2
  151. package/dist/worker/console/vite.config.js +5 -1
  152. package/dist/worker/console/workspace-registry.js +62 -19
  153. package/dist/worker/observe/static/operator-chrome.js +0 -1
  154. package/dist/worker/scheduler/git-base.js +3 -0
  155. package/dist/worker/scheduler/night-git-finalizer.js +1 -1
  156. package/dist/worker/scheduler/night-harvest.js +1 -1
  157. package/dist/worker/scheduler/prepared-attempt-recovery.js +1 -1
  158. package/dist/worker/scheduler/scheduled-goal-evidence.js +1 -1
  159. package/dist/workflows/dag/backend-test-scenario-param.js +60 -4
  160. package/dist/workflows/dag/dynamic-runtime/reduction.js +7 -2
  161. package/dist/workflows/dag/frontend-test-framework-adapters.js +11 -2
  162. package/dist/workflows/script/windows/guest.js +13 -2
  163. package/dist/workflows/script/windows/native.js +21 -3
  164. package/docs/architecture/dag-execution.md +2 -13
  165. package/docs/architecture/facts-and-state.md +2 -3
  166. package/docs/architecture/runtime-boundaries.md +2 -2
  167. package/package.json +9 -7
  168. package/resource-catalog.v1.json +6 -6
  169. package/scripts/patch-pi-sdk-windows-hide.mjs +3 -3
  170. package/skills/loop-agent/references/command-reference.md +2 -41
  171. package/skills/loop-agent/references/harness-policy.md +3 -30
  172. package/skills/loop-agent/references/long-running-loop.md +6 -54
  173. package/dist/application/loop/run-action.js +0 -19
  174. package/dist/commands/dag-workflow-compile.js +0 -93
  175. package/dist/commands/dag-workflow-plan.js +0 -132
  176. package/dist/commands/dag-workflow-validate.js +0 -68
  177. package/dist/commands/loop-benchmark.js +0 -74
  178. package/dist/commands/loop.js +0 -251
  179. package/dist/commands/workflow.js +0 -259
  180. package/dist/infrastructure/harness/loop-store.js +0 -41
  181. package/dist/worker/console/static/assets/abnfDiagram-N423BO3Z-FQePHM07.js +0 -1
  182. package/dist/worker/console/static/assets/architectureDiagram-T3A2C74G-p_mwm8cd.js +0 -36
  183. package/dist/worker/console/static/assets/channel-CIBAg8WF.js +0 -1
  184. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-B4xQrSmv.js +0 -1
  185. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-B4xQrSmv.js +0 -1
  186. package/dist/worker/console/static/assets/cose-bilkent-JH36ORCC-BPXf8ZYr.js +0 -1
  187. package/dist/worker/console/static/assets/cynefinDiagram-MW4NZA55-CNsL9N2-.js +0 -62
  188. package/dist/worker/console/static/assets/diagram-LBJQPF4R-BipWFRgs.js +0 -24
  189. package/dist/worker/console/static/assets/diagram-Q27KOJAE-T2p4xa38.js +0 -24
  190. package/dist/worker/console/static/assets/diagram-UB23O5K3-CVwz6LVu.js +0 -41
  191. package/dist/worker/console/static/assets/ebnfDiagram-BXEA7PRR-CybQrGSA.js +0 -1
  192. package/dist/worker/console/static/assets/ganttDiagram-PKOTCBZU-D411_55h.js +0 -292
  193. package/dist/worker/console/static/assets/gitGraphDiagram-DS77QQ5N-DpVtzs9z.js +0 -106
  194. package/dist/worker/console/static/assets/index-B7cwOTL9.js +0 -649
  195. package/dist/worker/console/static/assets/index-CATbSkPc.css +0 -1
  196. package/dist/worker/console/static/assets/infoDiagram-6WML65LV-D74Uvx6K.js +0 -2
  197. package/dist/worker/console/static/assets/pegDiagram-VL7TDLO6-CSwoBOpM.js +0 -1
  198. package/dist/worker/console/static/assets/railroadDiagram-AXF67PYL-n0Mt3Yia.js +0 -1
  199. package/dist/worker/console/static/assets/sizeCapture-X5ZJPWSS-Dmf1pC7B.js +0 -1
  200. package/dist/worker/console/static/assets/stateDiagram-OKZ733FA-4-jdPUHD.js +0 -1
  201. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-DojWfYnC.js +0 -1
  202. package/dist/worker/console/static/assets/swimlanes-SLNWSIFB-DNhjjaAU.js +0 -2
  203. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-CJo4AKWH.js +0 -8
  204. package/dist/worker/console/static/vcp/fonts/Lanxi-/345/217/257/345/256/213.woff2 +0 -0
  205. package/dist/worker/console/static/vcp/fonts/Lanxi-/346/234/227/345/256/213.woff2 +0 -0
  206. package/dist/worker/console/static/vcp/fonts/Lanxi-/350/266/205/347/262/227/351/273/221.woff2 +0 -0
  207. package/dist/workflows/dynamic/compile.js +0 -371
  208. package/dist/workflows/dynamic/compileTypes.js +0 -1
  209. package/dist/workflows/dynamic/errors.js +0 -5
  210. package/dist/workflows/dynamic/profiles.js +0 -156
  211. package/dist/workflows/dynamic/spec.js +0 -115
  212. package/dist/workflows/dynamic/validate.js +0 -275
  213. package/dist/workflows/loop/actions/dag-action.js +0 -129
  214. package/dist/workflows/loop/actions/pi-review.js +0 -267
  215. package/dist/workflows/loop/actions/shared.js +0 -157
  216. package/dist/workflows/loop/actions/shell-verify.js +0 -82
  217. package/dist/workflows/loop/actions/types.js +0 -1
  218. package/dist/workflows/loop/actions/workflow-action.js +0 -255
  219. package/dist/workflows/loop/actions.js +0 -160
  220. package/dist/workflows/loop/benchmark.js +0 -513
  221. package/dist/workflows/loop/closeout.js +0 -135
  222. package/dist/workflows/loop/context.js +0 -47
  223. package/dist/workflows/loop/events.js +0 -26
  224. package/dist/workflows/loop/hash.js +0 -32
  225. package/dist/workflows/loop/index.js +0 -8
  226. package/dist/workflows/loop/paths.js +0 -17
  227. package/dist/workflows/loop/policy/auto-policy.js +0 -112
  228. package/dist/workflows/loop/policy/path-patterns.js +0 -13
  229. package/dist/workflows/loop/rounds.js +0 -81
  230. package/dist/workflows/loop/signals.js +0 -52
  231. package/dist/workflows/loop/state.js +0 -116
  232. package/dist/workflows/loop/templates.js +0 -54
  233. package/dist/workflows/loop/types.js +0 -28
  234. /package/dist/workflows/{dynamic/artifacts.js → dag/dynamic-runtime/reduction-artifacts.js} +0 -0
@@ -45,17 +45,17 @@ import { createWorkflowRecorder } from "./workflow/record.js";
45
45
  import { buildWorkflowJobTools } from "./workflow/job-tools.js";
46
46
  import { assertConsoleResourcePolicy, withConsoleResourcePolicy } from "./subagents/resource-policy.js";
47
47
  import { bindSessionExtensions, createConsoleToolPolicyExtension, disposeSessionExtensions, setSessionToolPolicy } from "./pi-runtime/extension-bindings.js";
48
+ import { createPiCompactionSettings, resolveCompactionSettings, } from "../pi-compaction-settings.js";
48
49
  import { createOperatorChatResourceLoader, } from "./resource-loader.js";
49
50
  import { applySkillAutoInvocationPreferences, loadResourcePreferences, } from "./resource-preferences-store.js";
50
51
  import { buildPiModeLoopIsolationOptions } from "./pi-mode-loop-isolation.js";
51
52
  import { applyWorkflowIntakeSkillAuthority, resolveWorkflowIntakeCapability, verifyWorkflowIntakeSkillInventory, workflowIntakeMaterializationFailure, } from "./workflow-intake-skills.js";
52
53
  import { applyProcessRetryOverride, } from "../../../shared/pi-retry-settings.js";
53
- import { applyProcessCompactionOverride, createCompactionController, createContextPressureExtension, createSiftBridgeState, housekeepSiftStash, isConsoleSiftEnabled, parseCompactionPolicy, parsePiToolResultPruneConfig, parseSiftBridgeConfig, projectPromptPressure, deriveEffectiveWindow, projectSafeTelemetry, isContextOverflow, emptyContextPressureCounters, } from "../../../shared/pi-context-pressure/index.js";
54
+ import { applyProcessCompactionOverride, createCompactionController, createContextPressureExtension, createSiftBridgeState, housekeepSiftStash, isConsoleSiftEnabled, parseCompactionPolicy, parsePiToolResultPruneConfig, parseSiftBridgeConfig, projectSafeTelemetry, isContextOverflow, emptyContextPressureCounters, } from "../../../shared/pi-context-pressure/index.js";
54
55
  import { incrementCounter as incrementPressureCounter } from "../../../shared/pi-context-pressure/telemetry.js";
55
56
  import { resolveDefaultChatModel, resolveLowChatModel, } from "./model-resolver.js";
56
57
  import { filterActiveInterviewTools } from "../interview/tools.js";
57
58
  import { redactRuntimeText } from "./runtime-context.js";
58
- import { classifyChatCompactionFailure } from "./compaction-errors.js";
59
59
  import { BrowserAutomationService } from "./browser-automation.js";
60
60
  import { buildTodoContinuationContext, } from "./todos.js";
61
61
  import { buildPersistentTerminalTools } from "./terminal-tools.js";
@@ -187,6 +187,13 @@ export function OPERATOR_CHAT_ACTIVE_TOOL_NAMES() {
187
187
  export function computeOperatorChatActiveToolNames(session, sessionMode = DEFAULT_CONSOLE_CHAT_SESSION_MODE) {
188
188
  return computeChatActiveToolNames(session, sessionMode);
189
189
  }
190
+ /**
191
+ * Last-resort window when neither the provider nor `models.json` declares one.
192
+ * Matches the default the Console model editor writes for a new model, so a
193
+ * gateway that reports nothing still gets proactive compaction instead of
194
+ * running until it rejects the request.
195
+ */
196
+ const DEFAULT_CONTEXT_WINDOW = 128_000;
190
197
  const OPERATOR_CHAT_SESSION_EXCLUDE_TOOLS = Object.freeze([
191
198
  "apply_patch",
192
199
  "apply-patch",
@@ -325,6 +332,15 @@ export function createWizardLocalHeadersExtension(options) {
325
332
  }
326
333
  export { THINKING_LEVELS, RuntimeSnapshotUnavailableError, projectRuntimeSnapshot, };
327
334
  export { createDefaultPiSdkBindings } from "./pi-runtime/sdk-bindings.js";
335
+ /**
336
+ * Give queued macrotasks (an in-flight HTTP 201, an SSE write, a pending
337
+ * `/sessions` read) a turn on the loop before the next synchronous stretch of
338
+ * session preparation starts. Microtasks alone are not enough: they drain
339
+ * inside the same tick that the materialization chain continues in.
340
+ */
341
+ function yieldEventLoop() {
342
+ return new Promise((resolve) => setImmediate(resolve));
343
+ }
328
344
  /** Catalog listing must not load skills/extensions/context — those belong to reopen. */
329
345
  const CATALOG_RESOURCE_LOADER_OPTIONS = Object.freeze({
330
346
  noContextFiles: true,
@@ -462,6 +478,30 @@ export class PiSessionInitFailedError extends Error {
462
478
  this.name = "PiSessionInitFailedError";
463
479
  }
464
480
  }
481
+ /**
482
+ * Merge saved user preferences into a parsed policy.
483
+ *
484
+ * Only the three policy-shaped knobs are overridable here; everything else
485
+ * stays with the environment parser so there is a single source for each
486
+ * decision. The environment still wins inside `resolveCompactionSettings`.
487
+ */
488
+ function withUserCompactionSettings(policy, settings) {
489
+ if (!settings)
490
+ return policy;
491
+ const resolved = resolveCompactionSettings({ saved: settings });
492
+ return {
493
+ ...policy,
494
+ ...(resolved.thresholdRatio === undefined
495
+ ? {}
496
+ : { thresholdRatio: resolved.thresholdRatio }),
497
+ ...(resolved.headroomTokens === undefined
498
+ ? {}
499
+ : { headroomTokens: resolved.headroomTokens }),
500
+ ...(resolved.retainRatio === undefined
501
+ ? {}
502
+ : { retainRatio: resolved.retainRatio }),
503
+ };
504
+ }
465
505
  async function readModelConfigFileVersion(filePath) {
466
506
  try {
467
507
  const value = await stat(filePath, { bigint: true });
@@ -796,6 +836,7 @@ export class ConsolePiRuntime {
796
836
  async refreshSkillPrefsCache() {
797
837
  const prefs = await this.loadSkillAutoInvocationPreferences();
798
838
  this.cachedSkillPrefs = prefs;
839
+ this.invalidateWorkspaceInspection();
799
840
  return prefs;
800
841
  }
801
842
  getCompactionController(sessionId) {
@@ -850,112 +891,83 @@ export class ConsolePiRuntime {
850
891
  ...(pruneSettings.enabled && policy.mode !== "off" ? { prune: pruneSettings.config } : {}),
851
892
  });
852
893
  }
853
- applySessionRecoveryOverrides(sessionId, services, session) {
894
+ /**
895
+ * The conversation window Pi itself reports, and the window Pi will compute
896
+ * its threshold against.
897
+ *
898
+ * Pi derives its own compaction threshold from the model definition, so the
899
+ * reserve handed to it must be expressed against that same number. A gateway
900
+ * limit only narrows the Console's trigger basis; feeding it to Pi as the
901
+ * window would make Pi subtract the limit twice and never fire.
902
+ */
903
+ piDeclaredWindow(session, reportedWindow) {
904
+ const configured = session?.model?.contextWindow;
905
+ if (typeof configured === "number" && Number.isFinite(configured) && configured > 0) {
906
+ return configured;
907
+ }
908
+ if (typeof reportedWindow === "number" && reportedWindow > 0) {
909
+ return reportedWindow;
910
+ }
911
+ return undefined;
912
+ }
913
+ applySessionRecoveryOverrides(sessionId, services, session, userSettings) {
854
914
  applyProcessRetryOverride(services?.settingsManager);
855
915
  const manager = services?.settingsManager;
856
- const window = session?.getSessionStats?.()?.contextUsage?.contextWindow;
916
+ const reportedWindow = session?.getSessionStats?.()?.contextUsage?.contextWindow;
917
+ const declaredWindow = this.piDeclaredWindow(session, reportedWindow);
857
918
  applyProcessCompactionOverride(manager, {
858
- policy: parseCompactionPolicy(),
859
- ...(typeof window === "number" ? { contextWindow: window } : {}),
860
- // Console should allow an explicit compact as soon as there is a
861
- // previous turn. Pi's 20k default is a useful retention policy for
862
- // the TUI, but becomes a hard "session too small" gate here.
863
- keepRecentTokens: 0,
919
+ // User-scoped ratio / headroom / retain, when the operator saved them
920
+ // in 设置 → 模型. Environment variables still win inside
921
+ // resolveCompactionSettings.
922
+ policy: withUserCompactionSettings(parseCompactionPolicy(), userSettings),
923
+ ...(typeof declaredWindow === "number"
924
+ ? { contextWindow: declaredWindow }
925
+ : {}),
864
926
  });
865
927
  void sessionId;
866
928
  }
867
- async runPrePromptCompaction(sessionId, session, promptText, imageCount, onEvent, signal) {
868
- const policy = parseCompactionPolicy();
869
- if (signal?.aborted)
870
- return;
871
- if (policy.mode === "off")
872
- return;
873
- const controller = this.getCompactionController(sessionId);
874
- const stats = session.getSessionStats?.();
875
- const window = stats?.contextUsage?.contextWindow;
876
- const tokens = stats?.contextUsage?.tokens;
877
- if (typeof window === "number" && window > 0) {
878
- this.applySessionRecoveryOverrides(sessionId, this.serviceScopes.get(sessionId) ?? {}, session);
879
- }
880
- const projection = projectPromptPressure({
881
- currentContextTokens: tokens,
882
- promptText,
883
- imageCount,
884
- });
885
- if (projection.usageUnavailable) {
886
- incrementPressureCounter(controller.counters, "usage-unavailable");
887
- return;
888
- }
889
- const effective = typeof window === "number" && window > 0
890
- ? deriveEffectiveWindow(window, policy)
891
- : undefined;
892
- if (!effective || projection.projected < effective.triggerTokens) {
893
- controller.pruneArmed = false;
894
- return;
895
- }
896
- controller.pruneArmed = true;
897
- if (typeof session.compact !== "function")
898
- return;
899
- const compactionId = newCompactionId(sessionId);
900
- onEvent({
901
- type: "compaction_start",
902
- sessionId,
903
- compactionId,
904
- reason: "threshold",
905
- });
906
- controller.proactiveCompaction = true;
929
+ /**
930
+ * Read the saved compaction preferences once per session start.
931
+ *
932
+ * A missing or unreadable file must not break session creation; the policy
933
+ * falls back to environment variables and then to the declared window.
934
+ */
935
+ async loadUserCompactionSettings() {
936
+ const appDataRoot = this.options.appDataRoot;
937
+ if (!appDataRoot)
938
+ return undefined;
907
939
  try {
908
- signal?.throwIfAborted();
909
- incrementPressureCounter(controller.counters, "pre-prompt-threshold");
910
- const result = await this.compactWithOverflowFallback(sessionId, session, undefined, signal);
911
- const snapshot = projectCompactSnapshot(result ?? {});
912
- onEvent({
913
- type: "compaction_end",
914
- sessionId,
915
- compactionId,
916
- reason: "threshold",
917
- status: signal?.aborted ? "aborted" : "completed",
918
- willRetry: false,
919
- summary: snapshot.summary,
920
- ...(snapshot.firstKeptEntryId
921
- ? { firstKeptEntryId: snapshot.firstKeptEntryId }
922
- : {}),
923
- ...(snapshot.tokensBefore === undefined
924
- ? {}
925
- : { tokensBefore: snapshot.tokensBefore }),
926
- ...(snapshot.accounting ? {
927
- shadowedTokenCount: snapshot.accounting.shadowedTokenCount,
928
- replacementTokenCount: snapshot.accounting.replacementTokenCount,
929
- netTokensFreed: snapshot.accounting.netTokensFreed,
930
- accounting: snapshot.accounting.accounting,
931
- shrinkProof: snapshot.accounting.shrinkProof,
932
- } : {}),
933
- });
940
+ const store = await createPiCompactionSettings(appDataRoot);
941
+ return await store.current();
934
942
  }
935
- catch (error) {
936
- if (!signal?.aborted)
937
- incrementPressureCounter(controller.counters, "l0-compact-failed");
938
- const classified = classifyChatCompactionFailure(error);
939
- onEvent({
940
- type: "compaction_end",
941
- sessionId,
942
- compactionId,
943
- reason: "threshold",
944
- status: signal?.aborted ? "aborted" : "failed",
945
- willRetry: false,
946
- ...(signal?.aborted
947
- ? {}
948
- : {
949
- code: classified.code,
950
- errorMessage: classified.code === "COMPACTION_FAILED"
951
- ? "上下文压缩失败"
952
- : redactRuntimeText(classified.message, 600),
953
- }),
954
- });
943
+ catch {
944
+ return undefined;
955
945
  }
956
- finally {
957
- controller.proactiveCompaction = false;
946
+ }
947
+ /**
948
+ * Pick the context window to gate proactive compaction on.
949
+ *
950
+ * `getSessionStats().contextUsage.contextWindow` is what the provider
951
+ * reported for the live request, and a private/self-hosted gateway
952
+ * routinely reports `0`, `-1` or nothing at all — it has no obligation to
953
+ * tell us its limit. Gating only on that value silently disabled
954
+ * proactive compaction on such gateways: every session ran until the
955
+ * provider rejected the request, then fell back to the local checkpoint.
956
+ *
957
+ * The model definition in `models.json` (`session.model.contextWindow`)
958
+ * is the configured window and is authoritative when present. The
959
+ * reported value wins only when it is a usable positive number, because
960
+ * a gateway may enforce a tighter limit than the declared window.
961
+ */
962
+ resolveContextWindow(session, reportedWindow) {
963
+ if (typeof reportedWindow === "number" && reportedWindow > 0) {
964
+ return reportedWindow;
965
+ }
966
+ const configured = session.model?.contextWindow;
967
+ if (typeof configured === "number" && configured > 0) {
968
+ return configured;
958
969
  }
970
+ return DEFAULT_CONTEXT_WINDOW;
959
971
  }
960
972
  /**
961
973
  * Resolve a skill in the current session inventory by server-issued resourceId.
@@ -1136,6 +1148,10 @@ export class ConsolePiRuntime {
1136
1148
  if (existing?.status === "failed")
1137
1149
  return Promise.reject(existing.error);
1138
1150
  const promise = Promise.resolve(init.initializationBarrier)
1151
+ // The durable 201 response is still being written when this detached
1152
+ // chain starts. Yield one macrotask so it flushes before the first
1153
+ // synchronous preparation stretch takes the loop.
1154
+ .then(() => yieldEventLoop())
1139
1155
  .then(() => this.materializeSession(sessionId, init))
1140
1156
  .then(() => {
1141
1157
  if (this.disposedSessions.has(sessionId)) {
@@ -1184,19 +1200,21 @@ export class ConsolePiRuntime {
1184
1200
  abandon();
1185
1201
  return undefined;
1186
1202
  }
1187
- // Capture before services parse models.json. A concurrent edit can therefore
1188
- // cause at most one harmless extra refresh, never a missed next-turn refresh.
1189
- const modelConfigFile = await captureModelConfigFile(agentDir);
1190
- if (aborted()) {
1191
- abandon();
1192
- return undefined;
1193
- }
1194
1203
  const appendSystemPrompt = composeChatSystemPromptParts({
1195
1204
  sessionMode: init.sessionMode,
1196
1205
  workflowPrompt: OPERATOR_CHAT_SYSTEM_PROMPT_BASE,
1197
1206
  systemPromptSuffix: init.systemPromptSuffix,
1198
1207
  });
1199
- await this.refreshSkillPrefsCache().catch(() => undefined);
1208
+ // One parallel pass: models.json change capture and the skill
1209
+ // auto-invocation preferences are independent, so a new session never
1210
+ // pays their disk reads one after another.
1211
+ const [modelConfigFile] = await Promise.all([
1212
+ // Capture before services parse models.json. A concurrent edit can
1213
+ // therefore cause at most one harmless extra refresh, never a missed
1214
+ // next-turn refresh.
1215
+ captureModelConfigFile(agentDir),
1216
+ this.refreshSkillPrefsCache().catch(() => undefined),
1217
+ ]);
1200
1218
  if (aborted()) {
1201
1219
  abandon();
1202
1220
  return undefined;
@@ -1212,6 +1230,10 @@ export class ConsolePiRuntime {
1212
1230
  agentDir,
1213
1231
  resourceLoaderOptions,
1214
1232
  });
1233
+ // ResourceLoader construction is the heaviest synchronous stretch of
1234
+ // preparation (skills/AGENTS.md/packages scan). Let queued HTTP/SSE work
1235
+ // run before tool assembly starts.
1236
+ await yieldEventLoop();
1215
1237
  if (init.sessionMode !== "pi") {
1216
1238
  const expected = this.workflowIntakeCapabilities.get(init.sessionId);
1217
1239
  const loader = services.resourceLoader;
@@ -1248,6 +1270,10 @@ export class ConsolePiRuntime {
1248
1270
  }) ?? undefined)
1249
1271
  : undefined;
1250
1272
  assertNoWriteToolInList(OPERATOR_CHAT_ALLOWED_TOOLS);
1273
+ // Tool assembly builds every custom tool factory synchronously; yield
1274
+ // first so an already-queued create response or list read is not delayed
1275
+ // by the whole assembly.
1276
+ await yieldEventLoop();
1251
1277
  const customTools = await this.loadCustomTools(init.sessionId);
1252
1278
  if (aborted()) {
1253
1279
  abandon();
@@ -1275,8 +1301,16 @@ export class ConsolePiRuntime {
1275
1301
  await disposeSessionExtensions(session).catch(() => undefined);
1276
1302
  return undefined;
1277
1303
  }
1304
+ // Session creation registers the full tool catalog synchronously; the
1305
+ // extension handshake below is the next long await, so give the loop one
1306
+ // turn in between.
1307
+ await yieldEventLoop();
1278
1308
  try {
1279
1309
  await bindSessionExtensions(session);
1310
+ // Seven console extensions emit `session_start` here. Yield after the
1311
+ // handshake so their synchronous registrations do not stack onto the
1312
+ // readiness write that follows.
1313
+ await yieldEventLoop();
1280
1314
  assertConsoleResourcePolicy(session, services.resourceLoader);
1281
1315
  if (aborted()) {
1282
1316
  abandon();
@@ -1284,7 +1318,7 @@ export class ConsolePiRuntime {
1284
1318
  return undefined;
1285
1319
  }
1286
1320
  this.pinSessionTools(init.sessionId, session);
1287
- this.applySessionRecoveryOverrides(init.sessionId, services, session);
1321
+ this.applySessionRecoveryOverrides(init.sessionId, services, session, await this.loadUserCompactionSettings());
1288
1322
  }
1289
1323
  catch (error) {
1290
1324
  abandon();
@@ -1893,7 +1927,28 @@ export class ConsolePiRuntime {
1893
1927
  * conversation JSONL so the picker is not blocked on cold reopen.
1894
1928
  */
1895
1929
  workspaceModelRuntime;
1896
- workspaceInspection;
1930
+ static WORKSPACE_INSPECTION_TTL_MS = 45_000;
1931
+ workspaceInspectionServices;
1932
+ workspaceInspectionCachedAt = 0;
1933
+ workspaceInspectionInFlight = null;
1934
+ workspaceInspectionGeneration = 0;
1935
+ workspaceInspectionModelsVersion;
1936
+ workspaceInspectionPrefsMtime;
1937
+ workspaceSnapshotTemplates = new Map();
1938
+ workspaceSnapshotInFlight = new Map();
1939
+ /**
1940
+ * Actively invalidate cached workspace inspection services and snapshot
1941
+ * templates (P1-A generation invalidation). Next inspection rebuilds cleanly.
1942
+ */
1943
+ invalidateWorkspaceInspection() {
1944
+ this.workspaceInspectionServices = undefined;
1945
+ this.workspaceInspectionCachedAt = 0;
1946
+ this.workspaceInspectionInFlight = null;
1947
+ this.workspaceInspectionGeneration += 1;
1948
+ this.workspaceSnapshotTemplates.clear();
1949
+ this.workspaceSnapshotInFlight.clear();
1950
+ this.workspaceModelRuntime = undefined;
1951
+ }
1897
1952
  async getWorkspaceModelRuntime() {
1898
1953
  if (!this.workspaceModelRuntime) {
1899
1954
  this.workspaceModelRuntime = (async () => {
@@ -1914,34 +1969,84 @@ export class ConsolePiRuntime {
1914
1969
  /**
1915
1970
  * Full OPEN-surface services for inspect UIs. No SessionManager / JSONL.
1916
1971
  * Cached without sessionId so todo/goal extensions stay off the shared scope.
1972
+ * P1-A: short TTL + generation invalidation + single-flight concurrency.
1917
1973
  */
1918
1974
  async getWorkspaceInspectionServices() {
1919
- if (!this.workspaceInspection) {
1920
- this.workspaceInspection = (async () => {
1975
+ const now = Date.now();
1976
+ if (this.workspaceInspectionServices &&
1977
+ now - this.workspaceInspectionCachedAt < ConsolePiRuntime.WORKSPACE_INSPECTION_TTL_MS) {
1978
+ try {
1921
1979
  const agentDir = await safeGetAgentDir(this.bindings);
1922
- const appendSystemPrompt = composeChatSystemPromptParts({
1923
- sessionMode: DEFAULT_CONSOLE_CHAT_SESSION_MODE,
1924
- workflowPrompt: OPERATOR_CHAT_SYSTEM_PROMPT_BASE,
1925
- });
1926
- const { services } = await this.bindings.createServices({
1927
- cwd: this.options.cwd,
1928
- agentDir,
1929
- resourceLoaderOptions: await this.buildResourceLoaderOptions({
1930
- appendSystemPrompt,
1931
- }),
1932
- });
1933
- return {
1934
- modelRuntime: services.modelRuntime,
1935
- resourceLoader: services
1936
- .resourceLoader,
1937
- settingsManager: services.settingsManager,
1938
- };
1939
- })().catch((error) => {
1940
- this.workspaceInspection = undefined;
1941
- throw error;
1942
- });
1980
+ const modelsPath = path.join(agentDir, "models.json");
1981
+ const currentModelsVersion = await readModelConfigFileVersion(modelsPath);
1982
+ let prefsMtime;
1983
+ if (this.options.resourcePreferencesPath) {
1984
+ try {
1985
+ prefsMtime = (await stat(this.options.resourcePreferencesPath)).mtimeMs;
1986
+ }
1987
+ catch {
1988
+ prefsMtime = undefined;
1989
+ }
1990
+ }
1991
+ if (this.workspaceInspectionModelsVersion &&
1992
+ sameModelConfigFileVersion(this.workspaceInspectionModelsVersion, currentModelsVersion) &&
1993
+ this.workspaceInspectionPrefsMtime === prefsMtime) {
1994
+ return this.workspaceInspectionServices;
1995
+ }
1996
+ }
1997
+ catch {
1998
+ // Failed probe: invalidate and recreate.
1999
+ }
2000
+ this.invalidateWorkspaceInspection();
2001
+ }
2002
+ if (this.workspaceInspectionInFlight) {
2003
+ return this.workspaceInspectionInFlight;
1943
2004
  }
1944
- return this.workspaceInspection;
2005
+ const promise = (async () => {
2006
+ const agentDir = await safeGetAgentDir(this.bindings);
2007
+ const modelsPath = path.join(agentDir, "models.json");
2008
+ const currentModelsVersion = await readModelConfigFileVersion(modelsPath);
2009
+ let prefsMtime;
2010
+ if (this.options.resourcePreferencesPath) {
2011
+ try {
2012
+ prefsMtime = (await stat(this.options.resourcePreferencesPath)).mtimeMs;
2013
+ }
2014
+ catch {
2015
+ prefsMtime = undefined;
2016
+ }
2017
+ }
2018
+ const appendSystemPrompt = composeChatSystemPromptParts({
2019
+ sessionMode: DEFAULT_CONSOLE_CHAT_SESSION_MODE,
2020
+ workflowPrompt: OPERATOR_CHAT_SYSTEM_PROMPT_BASE,
2021
+ });
2022
+ const { services } = await this.bindings.createServices({
2023
+ cwd: this.options.cwd,
2024
+ agentDir,
2025
+ resourceLoaderOptions: await this.buildResourceLoaderOptions({
2026
+ appendSystemPrompt,
2027
+ }),
2028
+ });
2029
+ const inspectionServices = {
2030
+ modelRuntime: services.modelRuntime,
2031
+ resourceLoader: services
2032
+ .resourceLoader,
2033
+ settingsManager: services.settingsManager,
2034
+ };
2035
+ this.workspaceInspectionServices = inspectionServices;
2036
+ this.workspaceInspectionCachedAt = Date.now();
2037
+ this.workspaceInspectionModelsVersion = currentModelsVersion;
2038
+ this.workspaceInspectionPrefsMtime = prefsMtime;
2039
+ return inspectionServices;
2040
+ })()
2041
+ .catch((error) => {
2042
+ this.invalidateWorkspaceInspection();
2043
+ throw error;
2044
+ })
2045
+ .finally(() => {
2046
+ this.workspaceInspectionInFlight = null;
2047
+ });
2048
+ this.workspaceInspectionInFlight = promise;
2049
+ return promise;
1945
2050
  }
1946
2051
  async listModels(sessionId) {
1947
2052
  const live = this.modelRuntimes.get(sessionId);
@@ -2214,8 +2319,9 @@ export class ConsolePiRuntime {
2214
2319
  if (this.disposedSessions.has(sessionId))
2215
2320
  return disposedResult();
2216
2321
  const services = this.serviceScopes.get(sessionId);
2217
- if (services)
2218
- this.applySessionRecoveryOverrides(sessionId, services, session);
2322
+ if (services) {
2323
+ this.applySessionRecoveryOverrides(sessionId, services, session, await this.loadUserCompactionSettings());
2324
+ }
2219
2325
  await this.refreshModelConfiguration(sessionId, "force");
2220
2326
  if (this.disposedSessions.has(sessionId))
2221
2327
  return disposedResult();
@@ -2274,6 +2380,15 @@ export class ConsolePiRuntime {
2274
2380
  }
2275
2381
  async getRuntimeSnapshot(sessionId, options) {
2276
2382
  const initializing = this.sessionInit.get(sessionId)?.status === "initializing";
2383
+ // Inspect GETs that supplied a durable `workspaceProjection` must not wait
2384
+ // for extension `session_start`: the model selector and context overview
2385
+ // render from the cached workspace ResourceLoader/ModelRuntime instead.
2386
+ // Direct `getRuntimeSnapshot(sessionId)` (no projection) keeps the
2387
+ // blocking `ensureSessionReady` contract, including
2388
+ // PiSessionInitFailedError, for callers that need the live Agent.
2389
+ if (initializing && options?.workspaceProjection) {
2390
+ return this.projectWorkspaceRuntimeSnapshot(sessionId, options);
2391
+ }
2277
2392
  if (this.sessions.has(sessionId) || initializing) {
2278
2393
  try {
2279
2394
  await this.ensureSessionReady(sessionId);
@@ -2434,52 +2549,89 @@ export class ConsolePiRuntime {
2434
2549
  const thinkingSelection = this.resolveWorkspaceThinkingSelection(sessionId, hint.thinkingLevel);
2435
2550
  const effectiveThinkingLevel = settingsManager?.getDefaultThinkingLevel?.() ??
2436
2551
  (thinkingSelection === "auto" ? undefined : thinkingSelection);
2437
- const rawSystemPrompt = resourceLoader?.getSystemPrompt?.() ||
2438
- composeChatSystemPrompt({
2439
- sessionMode,
2440
- workflowPrompt: OPERATOR_CHAT_SYSTEM_PROMPT_BASE,
2441
- });
2442
- if (!rawSystemPrompt) {
2443
- throw new RuntimeSnapshotUnavailableError("system prompt projection failed: workspace prompt was empty");
2444
- }
2445
- let models = [];
2446
- try {
2447
- models = this.bindings
2448
- .listAvailableModels({ modelRuntime: inspection.modelRuntime })
2449
- .map((entry) => ({
2450
- provider: entry.provider,
2451
- id: entry.id,
2452
- ...(entry.name ? { name: entry.name } : {}),
2453
- hasCredentials: entry.hasCredentials,
2454
- }));
2455
- }
2456
- catch (error) {
2457
- throw new RuntimeSnapshotUnavailableError(`model enumeration failed: ${error instanceof Error ? error.message : String(error)}`);
2458
- }
2459
- const thinkingLevels = [
2460
- { value: "auto" },
2461
- ...THINKING_LEVELS.map((value) => ({ value })),
2462
- ];
2463
- let skillPrefs = { schemaVersion: 1, skills: {} };
2464
- let skillPrefsError;
2465
- if (resourceLoader) {
2466
- try {
2467
- skillPrefs = await this.loadSkillAutoInvocationPreferences();
2552
+ const now = Date.now();
2553
+ let template = this.workspaceSnapshotTemplates.get(sessionMode);
2554
+ if (!template ||
2555
+ template.generation !== this.workspaceInspectionGeneration ||
2556
+ now - template.cachedAt >= ConsolePiRuntime.WORKSPACE_INSPECTION_TTL_MS) {
2557
+ const existingInFlight = this.workspaceSnapshotInFlight.get(sessionMode);
2558
+ if (existingInFlight) {
2559
+ template = await existingInFlight;
2468
2560
  }
2469
- catch (error) {
2470
- skillPrefsError = error;
2561
+ else {
2562
+ const promise = (async () => {
2563
+ const rawSystemPrompt = resourceLoader?.getSystemPrompt?.() ||
2564
+ composeChatSystemPrompt({
2565
+ sessionMode,
2566
+ workflowPrompt: OPERATOR_CHAT_SYSTEM_PROMPT_BASE,
2567
+ });
2568
+ if (!rawSystemPrompt) {
2569
+ throw new RuntimeSnapshotUnavailableError("system prompt projection failed: workspace prompt was empty");
2570
+ }
2571
+ let models = [];
2572
+ try {
2573
+ models = this.bindings
2574
+ .listAvailableModels({ modelRuntime: inspection.modelRuntime })
2575
+ .map((entry) => ({
2576
+ provider: entry.provider,
2577
+ id: entry.id,
2578
+ ...(entry.name ? { name: entry.name } : {}),
2579
+ hasCredentials: entry.hasCredentials,
2580
+ }));
2581
+ }
2582
+ catch (error) {
2583
+ throw new RuntimeSnapshotUnavailableError(`model enumeration failed: ${error instanceof Error ? error.message : String(error)}`);
2584
+ }
2585
+ const thinkingLevels = [
2586
+ { value: "auto" },
2587
+ ...THINKING_LEVELS.map((value) => ({ value })),
2588
+ ];
2589
+ let skillPrefs = { schemaVersion: 1, skills: {} };
2590
+ let skillPrefsError;
2591
+ if (resourceLoader) {
2592
+ try {
2593
+ skillPrefs = await this.loadSkillAutoInvocationPreferences();
2594
+ }
2595
+ catch (error) {
2596
+ skillPrefsError = error;
2597
+ }
2598
+ }
2599
+ const activeTools = chatActiveToolBaseline(sessionMode);
2600
+ const inventories = await collectRuntimeInventories({
2601
+ resourceLoader,
2602
+ skillPrefs,
2603
+ skillPrefsError,
2604
+ agentDir: await safeGetAgentDir(this.bindings),
2605
+ cwd: this.options.cwd,
2606
+ tools: [],
2607
+ activeToolNames: activeTools,
2608
+ });
2609
+ const createdTemplate = {
2610
+ models,
2611
+ thinkingLevels,
2612
+ rawSystemPrompt,
2613
+ activeTools,
2614
+ contextFiles: inventories.contextFiles,
2615
+ skills: inventories.skills,
2616
+ extensions: inventories.extensions,
2617
+ packages: inventories.packages,
2618
+ mcp: inventories.mcp,
2619
+ diagnostics: inventories.diagnostics,
2620
+ cachedAt: Date.now(),
2621
+ generation: this.workspaceInspectionGeneration,
2622
+ };
2623
+ this.workspaceSnapshotTemplates.set(sessionMode, createdTemplate);
2624
+ return createdTemplate;
2625
+ })().finally(() => {
2626
+ this.workspaceSnapshotInFlight.delete(sessionMode);
2627
+ });
2628
+ this.workspaceSnapshotInFlight.set(sessionMode, promise);
2629
+ template = await promise;
2471
2630
  }
2472
2631
  }
2473
- const activeTools = chatActiveToolBaseline(sessionMode);
2474
- const inventories = await collectRuntimeInventories({
2475
- resourceLoader,
2476
- skillPrefs,
2477
- skillPrefsError,
2478
- agentDir: await safeGetAgentDir(this.bindings),
2479
- cwd: this.options.cwd,
2480
- tools: [],
2481
- activeToolNames: activeTools,
2482
- });
2632
+ if (!template) {
2633
+ throw new RuntimeSnapshotUnavailableError("workspace snapshot template missing");
2634
+ }
2483
2635
  const storedModel = this.sessionModels.get(sessionId);
2484
2636
  const provider = storedModel?.provider ?? hint.modelProvider;
2485
2637
  const modelId = storedModel?.modelId ?? hint.modelId;
@@ -2496,21 +2648,21 @@ export class ConsolePiRuntime {
2496
2648
  ? { effectiveThinkingLevel: effectiveThinkingLevel }
2497
2649
  : {}),
2498
2650
  },
2499
- models,
2500
- thinkingLevels,
2651
+ models: template.models,
2652
+ thinkingLevels: template.thinkingLevels,
2501
2653
  systemPrompt: {
2502
- ...(options.includeRaw ? { raw: rawSystemPrompt } : {}),
2503
- text: rawSystemPrompt,
2504
- sha256: createHash("sha256").update(rawSystemPrompt).digest("hex"),
2505
- characters: rawSystemPrompt.length,
2654
+ ...(options.includeRaw ? { raw: template.rawSystemPrompt } : {}),
2655
+ text: template.rawSystemPrompt,
2656
+ sha256: createHash("sha256").update(template.rawSystemPrompt).digest("hex"),
2657
+ characters: template.rawSystemPrompt.length,
2506
2658
  },
2507
- activeTools,
2508
- contextFiles: inventories.contextFiles,
2509
- skills: inventories.skills,
2510
- extensions: inventories.extensions,
2511
- packages: inventories.packages,
2512
- mcp: inventories.mcp,
2513
- diagnostics: inventories.diagnostics,
2659
+ activeTools: template.activeTools,
2660
+ contextFiles: template.contextFiles,
2661
+ skills: template.skills,
2662
+ extensions: template.extensions,
2663
+ packages: template.packages,
2664
+ mcp: template.mcp,
2665
+ diagnostics: template.diagnostics,
2514
2666
  hasBash: true,
2515
2667
  });
2516
2668
  }
@@ -2908,6 +3060,16 @@ export class ConsolePiRuntime {
2908
3060
  if (options?.signal?.aborted) {
2909
3061
  return;
2910
3062
  }
3063
+ /*
3064
+ * Re-read the compaction preferences before every turn.
3065
+ *
3066
+ * The saved file is the source of truth and reading it is cheap, so a
3067
+ * change made in 设置 → 模型 applies to the NEXT turn instead of only to
3068
+ * sessions created afterwards. Without this, saving a corrected headroom
3069
+ * did nothing until the user happened to open a new session — the
3070
+ * setting looked ignored.
3071
+ */
3072
+ this.applySessionRecoveryOverrides(sessionId, this.serviceScopes.get(sessionId) ?? {}, session, await this.loadUserCompactionSettings());
2911
3073
  let promptImages = options?.images;
2912
3074
  if ((options?.referenceImageCount ?? 0) > 0 && !session.model?.input?.includes("image")) {
2913
3075
  promptImages = promptImages?.slice(0, Math.max(0, promptImages.length - options.referenceImageCount));
@@ -2945,7 +3107,17 @@ export class ConsolePiRuntime {
2945
3107
  return;
2946
3108
  }
2947
3109
  emitContextUsage();
2948
- await this.runPrePromptCompaction(sessionId, session, text, promptImages?.length ?? 0, onEvent, options?.signal);
3110
+ /*
3111
+ * No pre-prompt compaction here.
3112
+ *
3113
+ * Pi checks the threshold before EVERY provider request
3114
+ * (`_compactBeforeNextAssistantResponse`, driven by
3115
+ * `prepareNextTurnWithContext`), and its `reserveTokens` is set from
3116
+ * the resolved spec in `applySessionRecoveryOverrides`. A second gate
3117
+ * here would have to agree with Pi's forever, and it only ever ran on
3118
+ * user input — so it could never cover an agentic loop. One threshold,
3119
+ * owned by Pi, is the whole point of the DSH-aligned policy.
3120
+ */
2949
3121
  if (options?.signal?.aborted)
2950
3122
  return;
2951
3123
  let step = 0;
@@ -3055,6 +3227,23 @@ export class ConsolePiRuntime {
3055
3227
  ? activeCompaction?.compactionId ?? newCompactionId(sessionId)
3056
3228
  : undefined;
3057
3229
  const mapped = mapSdkEvent(sessionId, event.type === "tool_execution_start" ? { ...event, args: projectSkillReadArgs(event.toolName, event.args, currentSkills(), this.serviceScopes.get(sessionId)?.cwd ?? this.options.cwd) } : event, compactionId, Math.max(1, step));
3230
+ /*
3231
+ * Say WHY a compaction produced a local summary.
3232
+ *
3233
+ * The extension only takes over after the provider summary request
3234
+ * failed, so a completed compaction with the fallback armed means the
3235
+ * gateway refused twice: once for the original request and again for
3236
+ * the summary. Without this the message stream shows a compaction that
3237
+ * looks identical to a normal one, while the content is visibly worse.
3238
+ */
3239
+ if (mapped?.type === "compaction_end") {
3240
+ const controller = this.compactionControllers.get(sessionId);
3241
+ if (controller?.summaryRetryPending) {
3242
+ mapped.localFallback = true;
3243
+ mapped.localFallbackReason = "网关拒绝了摘要请求,已改用本地摘要";
3244
+ controller.summaryRetryPending = undefined;
3245
+ }
3246
+ }
3058
3247
  if (event.type === "compaction_end")
3059
3248
  activeCompaction = undefined;
3060
3249
  if (mapped?.type === "error") {
@@ -3435,6 +3624,15 @@ export class ConsolePiRuntime {
3435
3624
  if (typeof session.compact !== "function")
3436
3625
  throw new Error("COMPACTION_UNSUPPORTED");
3437
3626
  incrementPressureCounter(this.getCompactionController(sessionId).counters, "manual");
3627
+ /*
3628
+ * Manual compaction runs exactly once.
3629
+ *
3630
+ * DSH's `compactionRetries` exists to keep an automatic turn under the
3631
+ * pressure threshold. Pi runs its own automatic compaction inside the SDK
3632
+ * and exposes no post-pass hook, so that retry is NOT implemented here —
3633
+ * see the design doc's "未实现" section. A user who asked for one
3634
+ * compaction gets one.
3635
+ */
3438
3636
  const result = await this.compactWithOverflowFallback(sessionId, session, customInstructions);
3439
3637
  return projectCompactSnapshot(result ?? {});
3440
3638
  }