@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
@@ -856,6 +856,8 @@ export function createChatEventStore(options) {
856
856
  /** B5-1: sessions whose latest `message_update` appends are still waiting
857
857
  * for the next persist (debounced; structural events / turn changes flush). */
858
858
  const pendingPersists = new Map();
859
+ /** P2-A: lightweight in-memory projection checkpoints. */
860
+ const checkpoints = new Map();
859
861
  function persistedPath(sessionId) {
860
862
  return persistenceDir
861
863
  ? path.join(persistenceDir, `${safeSessionId(sessionId)}.json`)
@@ -1390,14 +1392,41 @@ export function createChatEventStore(options) {
1390
1392
  epoch(sessionId) {
1391
1393
  return ringFor(sessionId).epoch;
1392
1394
  },
1395
+ minSeq(sessionId) {
1396
+ return ringFor(sessionId).minSeq;
1397
+ },
1393
1398
  latestSeq(sessionId) {
1394
1399
  return ringFor(sessionId).nextSeq - 1;
1395
1400
  },
1396
- snapshot(sessionId) {
1401
+ snapshot(sessionId, options) {
1397
1402
  const ring = rings.get(sessionId) ?? loadRing(sessionId);
1398
1403
  if (ring)
1399
1404
  rings.set(sessionId, ring);
1400
- return ring?.events.slice() ?? [];
1405
+ if (!ring)
1406
+ return [];
1407
+ if (options?.afterSeq !== undefined) {
1408
+ return ring.events.filter((event) => event.seq > options.afterSeq);
1409
+ }
1410
+ return ring.events.slice();
1411
+ },
1412
+ getCheckpoint(sessionId) {
1413
+ const cp = checkpoints.get(sessionId);
1414
+ if (!cp)
1415
+ return undefined;
1416
+ const ring = rings.get(sessionId) ?? loadRing(sessionId);
1417
+ if (!ring)
1418
+ return undefined;
1419
+ if (cp.eventEpoch !== ring.epoch || (ring.events.length > 0 && cp.asOfSeq < ring.minSeq)) {
1420
+ checkpoints.delete(sessionId);
1421
+ return undefined;
1422
+ }
1423
+ return cp;
1424
+ },
1425
+ setCheckpoint(sessionId, checkpoint) {
1426
+ checkpoints.set(sessionId, checkpoint);
1427
+ },
1428
+ invalidateCheckpoint(sessionId) {
1429
+ checkpoints.delete(sessionId);
1401
1430
  },
1402
1431
  goalHistory(sessionId) {
1403
1432
  const ring = ringFor(sessionId);
@@ -1436,6 +1465,7 @@ export function createChatEventStore(options) {
1436
1465
  rings.delete(sessionId);
1437
1466
  turnCounts.delete(sessionId);
1438
1467
  subscribers.delete(sessionId);
1468
+ checkpoints.delete(sessionId);
1439
1469
  // B5-1: drop any debounced (not yet written) updates with the ring itself —
1440
1470
  // the file is being deleted, so flushing first would only resurrect it.
1441
1471
  pendingPersists.delete(sessionId);
@@ -23,6 +23,7 @@ function validSource(value) {
23
23
  file: ["kind", "workspaceId", "path", "version", "versionScope", "view", "anchor", "startLine", "endLine", "sheet", "cellRange"],
24
24
  diff: ["kind", "workspaceId", "path", "side", "comparison", "version", "startLine", "endLine"],
25
25
  terminal: ["kind", "workspaceId", "terminalSessionId", "ownerSessionId", "shell", "anchor"],
26
+ api: ["kind", "workspaceId", "method", "url", "status", "elapsedMs", "anchor"],
26
27
  };
27
28
  const allowed = typeof s.kind === "string" ? keys[s.kind] : undefined;
28
29
  if (!allowed || Object.keys(s).some((key) => !allowed.includes(key)))
@@ -53,6 +54,9 @@ function validSource(value) {
53
54
  && validLine(s.startLine) && validLine(s.endLine) && s.endLine >= s.startLine;
54
55
  case "terminal":
55
56
  return boundedString(s.terminalSessionId) && boundedString(s.ownerSessionId) && boundedString(s.shell) && boundedString(s.anchor);
57
+ case "api":
58
+ return typeof s.method === "string" && /^[A-Za-z]{1,16}$/.test(s.method) && boundedString(s.url, 2_048) && typeof s.status === "number" && Number.isFinite(s.status)
59
+ && typeof s.elapsedMs === "number" && Number.isFinite(s.elapsedMs) && s.elapsedMs >= 0 && boundedString(s.anchor);
56
60
  default: return false;
57
61
  }
58
62
  }
@@ -53,12 +53,24 @@ export function classifyChatCompactionFailure(error) {
53
53
  };
54
54
  }
55
55
  if (/chat session not found/i.test(raw)) {
56
- return { status: 404, code: "NOT_FOUND", message: raw, raw };
56
+ return {
57
+ status: 404,
58
+ code: "NOT_FOUND",
59
+ message: "对话不存在或已被移除。",
60
+ raw,
61
+ };
57
62
  }
63
+ /*
64
+ * Never pass the raw provider text through as the user-facing message.
65
+ *
66
+ * `raw` is kept for local diagnosis, but it can contain API keys, bearer
67
+ * tokens and absolute paths from provider errors. The default branch used to
68
+ * return `raw` verbatim, which surfaced all of that in the UI.
69
+ */
58
70
  return {
59
71
  status: 409,
60
72
  code: "COMPACTION_FAILED",
61
- message: raw.trim() || "上下文压缩失败",
73
+ message: "上下文压缩失败",
62
74
  raw,
63
75
  };
64
76
  }
@@ -19,6 +19,7 @@
19
19
  */
20
20
  import { conservativeTokenEstimate } from "../../../shared/pi-context-pressure/compaction-policy.js";
21
21
  import { readPruneAccounting, reclaimedAmount, } from "./context-accounting.js";
22
+ import { formatCacheHitPercent } from "./session-stats.js";
22
23
  /** Fixed-density token estimate for preview text (chars → tokens). */
23
24
  export function estimateTokensFromText(text) {
24
25
  if (!text)
@@ -673,6 +674,43 @@ export function deriveContextInsights(events, options = {}) {
673
674
  contextEvents.push(contextEvent);
674
675
  if (pruned && typeof data.pruneId === "string")
675
676
  pruneEventsById.set(data.pruneId, contextEvent);
677
+ /*
678
+ * A compaction replaces the oldest prefix of the live surface.
679
+ *
680
+ * Pi reports the size of what it removed (`shadowedTokenCount`)
681
+ * but never the event seqs, and `firstKeptEntryId` is an opaque
682
+ * entry identity — so the exact node set cannot be claimed the
683
+ * way a pruner's `shadowedSeqs` allows. Without this, the ledger
684
+ * kept counting the consumed messages forever and the trend line
685
+ * showed no drop at the compaction, even though the event and its
686
+ * ✂ mark were present.
687
+ *
688
+ * `liveNodes` is appended in event order, so consuming from the
689
+ * front reproduces "the oldest prefix was summarized". The
690
+ * accounting only runs on `compaction_end`, once the size is
691
+ * known; `compaction_start` carries none.
692
+ */
693
+ if (!pruned && event.kind === "compaction_end") {
694
+ const freed = accounting.shadowedTokenCount;
695
+ if (typeof freed === "number" && freed > 0) {
696
+ const consumed = [];
697
+ let remaining = freed;
698
+ let prefix = 0;
699
+ while (remaining > 0 && prefix < liveNodes.length) {
700
+ remaining -= liveNodes[prefix].tokens;
701
+ prefix += 1;
702
+ }
703
+ for (let i = 0; i < prefix; i += 1)
704
+ consumed.push(liveNodes[i].seq);
705
+ if (consumed.length > 0) {
706
+ removedIds = claimNodes(new Set(consumed), event.seq);
707
+ if (removedIds.length > 0)
708
+ removalBasis = "seqs";
709
+ contextEvent.removedIds = removedIds;
710
+ contextEvent.removalBasis = "seqs";
711
+ }
712
+ }
713
+ }
676
714
  const lastStep = trend.at(-1);
677
715
  if (lastStep && event.kind !== "compaction_start") {
678
716
  lastStep.eventMark = pruned ? "prune" : "compact";
@@ -710,10 +748,9 @@ export function deriveContextInsights(events, options = {}) {
710
748
  composition.headroom = Math.max(0, contextWindow - composition.totalTokens);
711
749
  }
712
750
  const billed = usage.inputTokens + usage.cacheReadTokens + usage.cacheWriteTokens;
713
- usage.cacheHitPercent =
714
- billed > 0
715
- ? Math.round((usage.cacheReadTokens / billed) * 1000) / 10
716
- : null;
751
+ // Same formatter as the turn pills: a partial hit must not round up to 100%.
752
+ const cacheHitText = billed > 0 ? formatCacheHitPercent(usage.cacheReadTokens, billed) : null;
753
+ usage.cacheHitPercent = cacheHitText === null ? null : Number(cacheHitText);
717
754
  usage.turns = turnIds.length;
718
755
  if (usage.totalTokens === 0 && billed + usage.outputTokens > 0) {
719
756
  usage.totalTokens = billed + usage.outputTokens;
@@ -47,7 +47,10 @@ export function deriveChatContextUsage(events) {
47
47
  beforeAssistant.set(event.turnId, surface);
48
48
  const blocks = parseAssistantContent(data.content);
49
49
  const price = blocks?.length
50
- ? 4 + blocks.reduce((total, block) => total + 4 + tokensForText(block.type === "text" ? block.text : block.type === "thinking" ? block.thinking : block.toolName), 0)
50
+ ? 4 + blocks.reduce((total, block) => total + 4 + tokensForText(block.type === "text" ? block.text
51
+ : block.type === "thinking" ? block.thinking
52
+ : block.type === "toolCall" ? block.toolName
53
+ : ""), 0)
51
54
  : 8 + tokensForText(data.text);
52
55
  append(event.seq, price);
53
56
  }
@@ -7,6 +7,7 @@ import { parseAssertions } from "../../api-workbench-assertions.js";
7
7
  * api_send send one sandboxed HTTP request (env {{key}} substitution)
8
8
  * api_environments list environments; upsert baseUrl + key=value variables
9
9
  * api_history list / clear recent send history
10
+ * api_debug one-shot debugging brief (endpoints + env + history)
10
11
  *
11
12
  * Envelope: success { ok: true, ... } / failure { ok: false, error: { code, message } }
12
13
  * with stable APIWB_* error codes. Sends use the same validation,
@@ -15,8 +16,9 @@ import { parseAssertions } from "../../api-workbench-assertions.js";
15
16
  import { scanSpecsSnapshot, parseQueryParams, ApiWorkbenchCoreError, } from "../../api-workbench-core.js";
16
17
  const APIWB_TOOLS_DESCRIPTION = "API workbench: scan repo OpenAPI/Swagger specs and static code routes (api_scan), " +
17
18
  "send one sandboxed HTTP request with environment {{key}} substitution (api_send), " +
18
- "list/upsert environment prefixes + variables (api_environments), and review send history (api_history). " +
19
- "Use api_scan before guessing endpoints; environments carry non-secret key=value variables. Never submit credential values through tool arguments.";
19
+ "list/upsert environment prefixes + variables (api_environments), review send history (api_history), " +
20
+ "and pull a one-shot debugging brief (api_debug). " +
21
+ "Use api_scan or api_debug before guessing endpoints; environments carry non-secret key=value variables. Never submit credential values through tool arguments.";
20
22
  export async function buildApiWorkbenchTools(options) {
21
23
  const [{ Type }, { defineTool }] = await Promise.all([
22
24
  import("typebox"),
@@ -130,6 +132,66 @@ export async function buildApiWorkbenchTools(options) {
130
132
  }, { signal }));
131
133
  },
132
134
  }),
135
+ defineTool({
136
+ name: "api_debug",
137
+ label: "API debug brief",
138
+ description: "One-shot debugging brief: compact endpoint inventory, environments, credentials (metadata only), recent send history, and a debugging playbook. Read this BEFORE sending requests when unsure which endpoint/parameter to use; then use api_send to replay and iterate.",
139
+ parameters: Type.Object({
140
+ query: Type.Optional(Type.String({ maxLength: 120, description: "Case-insensitive substring filter for endpoint paths" })),
141
+ }, { additionalProperties: false }),
142
+ async execute(_id, params) {
143
+ return run("APIWB_DEBUG_FAILED", async () => {
144
+ const snapshot = await scanSpecsSnapshot(opts.repoRoot);
145
+ const needle = params.query?.trim().toLowerCase();
146
+ const endpoints = [];
147
+ for (const spec of snapshot.specs) {
148
+ for (const endpoint of spec.endpoints ?? []) {
149
+ const path = endpoint.path ?? "";
150
+ if (needle && !path.toLowerCase().includes(needle))
151
+ continue;
152
+ endpoints.push({
153
+ method: endpoint.method ?? "",
154
+ path,
155
+ ...(endpoint.summary ? { summary: endpoint.summary } : {}),
156
+ required: (endpoint.parameters ?? [])
157
+ .filter((p) => p && typeof p === "object" && p.required === true && p.in !== "body")
158
+ .map((p) => String(p.name ?? ""))
159
+ .filter(Boolean),
160
+ });
161
+ if (endpoints.length >= 80)
162
+ break;
163
+ }
164
+ if (endpoints.length >= 80)
165
+ break;
166
+ }
167
+ const env = await opts.apiWorkbench.readEnvironmentState();
168
+ const credentials = (await opts.apiWorkbench.auth.list()).credentials.map((c) => ({
169
+ id: c.id,
170
+ name: c.name,
171
+ origin: c.origin,
172
+ configured: c.configured,
173
+ }));
174
+ const history = opts.apiWorkbench.listWorkbenchHistory().slice(0, 10).map((h) => ({
175
+ method: h.method,
176
+ url: h.url,
177
+ status: h.status,
178
+ elapsedMs: h.elapsedMs,
179
+ at: h.at,
180
+ }));
181
+ return {
182
+ ok: true,
183
+ stats: snapshot.stats,
184
+ endpoints,
185
+ environments: env,
186
+ credentials,
187
+ history,
188
+ playbook: "1) api_scan/api_debug to inventory endpoints; 2) pick endpoint + environment ({{key}} substitution); " +
189
+ "3) api_send with responseFields to extract only needed fields; 4) on failure read authDiagnosis/error code, " +
190
+ "fix one variable at a time and resend; 5) confirm with assertions; 6) save recurring flows with api_collections.",
191
+ };
192
+ });
193
+ },
194
+ }),
133
195
  defineTool({
134
196
  name: "api_environments",
135
197
  label: "API environments",
@@ -183,7 +245,7 @@ export async function buildApiWorkbenchTools(options) {
183
245
  const capability = defineTool({
184
246
  name: "apiCapabilities",
185
247
  label: "API capabilities",
186
- description: "Directory for the API workbench. Does not send a request, change an environment, or run a collection. Returns the family, a summary, how to discover tools, the five tool names, and whether they have side effects.",
248
+ description: "Directory for the API workbench. Does not send a request, change an environment, or run a collection. Returns the family, a summary, how to discover tools, the six tool names, and whether they have side effects.",
187
249
  parameters: Type.Object({ target: Type.Optional(Type.String({ maxLength: 80 })) }, { additionalProperties: false }),
188
250
  async execute(_id, params) {
189
251
  const result = discover(params.target);
@@ -142,12 +142,12 @@ export async function buildBrowserTools(options) {
142
142
  }
143
143
  return p.observe ? automation.act(request, undefined, p.observe) : automation.act(request);
144
144
  }),
145
- tool("browser_tabs", "List/new/select/close tabs. Use an explicit tabId to select or close. A closed/busy tab can be closed explicitly; then select or create a new tab.", Type.Union([
145
+ tool("browser_tabs", "List/new/select/close tabs. Use an explicit tabId to select or close. A closed/busy tab can be closed explicitly; then select or create a new tab.", Object.assign(Type.Union([
146
146
  object({ action: Type.Literal("list"), ...target }),
147
147
  object({ action: Type.Literal("new"), ...target, url: Type.Optional(url), ...unscopedCompletion }),
148
148
  object({ action: Type.Literal("select"), tabId: Type.Integer({ minimum: 1 }), ...scopedCompletion }),
149
149
  object({ action: Type.Literal("close"), tabId: Type.Integer({ minimum: 1 }), ...unscopedCompletion }),
150
- ]), async (p) => {
150
+ ]), { type: "object" }), async (p) => {
151
151
  if (p.action === "list") {
152
152
  if (record(p).observe !== undefined)
153
153
  throw Object.assign(new Error("list does not perform an implicit observation"), { code: "INVALID_OBSERVATION" });
@@ -1,3 +1,32 @@
1
+ /**
2
+ * Headless stand-in for the terminal theme singleton.
3
+ *
4
+ * The Console has no TUI, so extensions cannot receive real ANSI styling. Returning the text
5
+ * unchanged keeps extension status/widget strings readable instead of failing: the SDK contract
6
+ * declares `ctx.ui.theme` as required, and any extension reading `ctx.ui.theme.fg(...)` would
7
+ * otherwise throw on every lifecycle event. The real singleton is deliberately not used — it is
8
+ * not exported from the package root, and the internal one throws "Theme not initialized."
9
+ * until `initTheme()` runs, which only happens in the top-level CLI entry (`main.js`).
10
+ */
11
+ function createHeadlessExtensionTheme() {
12
+ const passthrough = (text) => text;
13
+ return {
14
+ appearance: "dark",
15
+ colors: {},
16
+ style: (text, _options) => text,
17
+ fg: (_color, text) => text,
18
+ bg: (_color, text) => text,
19
+ bold: passthrough,
20
+ italic: passthrough,
21
+ underline: passthrough,
22
+ inverse: passthrough,
23
+ strikethrough: passthrough,
24
+ getFgAnsi: (_color) => "",
25
+ getBgAnsi: (_color) => "",
26
+ getColorMode: () => "truecolor",
27
+ getThinkingBorderColor: () => passthrough,
28
+ };
29
+ }
1
30
  const toolPolicies = new WeakMap();
2
31
  /** Selection controls declarations; this policy also gates deferred/nested calls. */
3
32
  export function setSessionToolPolicy(session, allowed) {
@@ -57,6 +86,8 @@ export function disposeSessionExtensions(session) {
57
86
  return close;
58
87
  }
59
88
  function createConsoleExtensionBindings(session) {
89
+ // The headless theme is stateless, so one per bindings object is enough.
90
+ const headlessTheme = createHeadlessExtensionTheme();
60
91
  return {
61
92
  mode: "rpc",
62
93
  onError: (error) => {
@@ -96,6 +127,14 @@ function createConsoleExtensionBindings(session) {
96
127
  addAutocompleteProvider: () => undefined,
97
128
  setEditorComponent: () => undefined,
98
129
  getEditorComponent: () => undefined,
130
+ // Required by the SDK contract; absent members make extensions crash on
131
+ // `ctx.ui.theme.fg(...)` instead of degrading to unstyled output.
132
+ theme: headlessTheme,
133
+ getAllThemes: () => [],
134
+ getTheme: () => undefined,
135
+ setTheme: () => ({ success: false, error: "Theme switching not supported in Console mode" }),
136
+ getToolsExpanded: () => false,
137
+ setToolsExpanded: () => undefined,
99
138
  },
100
139
  };
101
140
  }
@@ -127,6 +127,10 @@ function guardModelRuntimeCosts(value) {
127
127
  * absent at module load (discovered lazily by pi-readiness instead).
128
128
  */
129
129
  export function createDefaultPiSdkBindings() {
130
+ // Warm the ESM module graph while the user is still on the empty UI. The
131
+ // first create otherwise pays the cold SDK import before it can answer 201.
132
+ // A missing SDK still fails lazily on first use, not at bindings creation.
133
+ void loadSdk().catch(() => undefined);
130
134
  const consoleServices = new WeakSet();
131
135
  return {
132
136
  getAgentDir: async () => {